repo_name
stringlengths
5
100
path
stringlengths
4
375
copies
stringclasses
991 values
size
stringlengths
4
7
content
stringlengths
666
1M
license
stringclasses
15 values
matburt/ansible
test/units/parsing/vault/test_vault_editor.py
142
6762
# (c) 2014, James Tanner <tanner.jc@gmail.com> # (c) 2014, James Cammarata, <jcammarata@ansible.com> # # 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 #!/usr/bin/env python import sys import getpass import os import shutil import time import tempfile from binascii import unhexlify from binascii import hexlify from nose.plugins.skip import SkipTest from ansible.compat.tests import unittest from ansible.compat.tests.mock import patch from ansible.utils.unicode import to_bytes, to_unicode from ansible import errors from ansible.parsing.vault import VaultLib from ansible.parsing.vault import VaultEditor # Counter import fails for 2.0.1, requires >= 2.6.1 from pip try: from Crypto.Util import Counter HAS_COUNTER = True except ImportError: HAS_COUNTER = False # KDF import fails for 2.0.1, requires >= 2.6.1 from pip try: from Crypto.Protocol.KDF import PBKDF2 HAS_PBKDF2 = True except ImportError: HAS_PBKDF2 = False # AES IMPORTS try: from Crypto.Cipher import AES as AES HAS_AES = True except ImportError: HAS_AES = False v10_data = """$ANSIBLE_VAULT;1.0;AES 53616c7465645f5fd0026926a2d415a28a2622116273fbc90e377225c12a347e1daf4456d36a77f9 9ad98d59f61d06a4b66718d855f16fb7bdfe54d1ec8aeaa4d06c2dc1fa630ae1846a029877f0eeb1 83c62ffb04c2512995e815de4b4d29ed""" v11_data = """$ANSIBLE_VAULT;1.1;AES256 62303130653266653331306264616235333735323636616539316433666463323964623162386137 3961616263373033353631316333623566303532663065310a393036623466376263393961326530 64336561613965383835646464623865663966323464653236343638373165343863623638316664 3631633031323837340a396530313963373030343933616133393566366137363761373930663833 3739""" class TestVaultEditor(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_methods_exist(self): v = VaultEditor(None) slots = ['create_file', 'decrypt_file', 'edit_file', 'encrypt_file', 'rekey_file', 'read_data', 'write_data', 'shuffle_files'] for slot in slots: assert hasattr(v, slot), "VaultLib is missing the %s method" % slot @patch.object(VaultEditor, '_editor_shell_command') def test_create_file(self, mock_editor_shell_command): def sc_side_effect(filename): return ['touch', filename] mock_editor_shell_command.side_effect = sc_side_effect tmp_file = tempfile.NamedTemporaryFile() os.unlink(tmp_file.name) ve = VaultEditor("ansible") ve.create_file(tmp_file.name) self.assertTrue(os.path.exists(tmp_file.name)) def test_decrypt_1_0(self): """ Skip testing decrypting 1.0 files if we don't have access to AES, KDF or Counter, or we are running on python3 since VaultAES hasn't been backported. """ if not HAS_AES or not HAS_COUNTER or not HAS_PBKDF2 or sys.version > '3': raise SkipTest v10_file = tempfile.NamedTemporaryFile(delete=False) with v10_file as f: f.write(to_bytes(v10_data)) ve = VaultEditor("ansible") # make sure the password functions for the cipher error_hit = False try: ve.decrypt_file(v10_file.name) except errors.AnsibleError as e: error_hit = True # verify decrypted content f = open(v10_file.name, "rb") fdata = to_unicode(f.read()) f.close() os.unlink(v10_file.name) assert error_hit == False, "error decrypting 1.0 file" assert fdata.strip() == "foo", "incorrect decryption of 1.0 file: %s" % fdata.strip() def test_decrypt_1_1(self): if not HAS_AES or not HAS_COUNTER or not HAS_PBKDF2: raise SkipTest v11_file = tempfile.NamedTemporaryFile(delete=False) with v11_file as f: f.write(to_bytes(v11_data)) ve = VaultEditor("ansible") # make sure the password functions for the cipher error_hit = False try: ve.decrypt_file(v11_file.name) except errors.AnsibleError as e: error_hit = True # verify decrypted content f = open(v11_file.name, "rb") fdata = to_unicode(f.read()) f.close() os.unlink(v11_file.name) assert error_hit == False, "error decrypting 1.0 file" assert fdata.strip() == "foo", "incorrect decryption of 1.0 file: %s" % fdata.strip() def test_rekey_migration(self): """ Skip testing rekeying files if we don't have access to AES, KDF or Counter, or we are running on python3 since VaultAES hasn't been backported. """ if not HAS_AES or not HAS_COUNTER or not HAS_PBKDF2 or sys.version > '3': raise SkipTest v10_file = tempfile.NamedTemporaryFile(delete=False) with v10_file as f: f.write(to_bytes(v10_data)) ve = VaultEditor("ansible") # make sure the password functions for the cipher error_hit = False try: ve.rekey_file(v10_file.name, 'ansible2') except errors.AnsibleError as e: error_hit = True # verify decrypted content f = open(v10_file.name, "rb") fdata = f.read() f.close() assert error_hit == False, "error rekeying 1.0 file to 1.1" # ensure filedata can be decrypted, is 1.1 and is AES256 vl = VaultLib("ansible2") dec_data = None error_hit = False try: dec_data = vl.decrypt(fdata) except errors.AnsibleError as e: error_hit = True os.unlink(v10_file.name) assert vl.cipher_name == "AES256", "wrong cipher name set after rekey: %s" % vl.cipher_name assert error_hit == False, "error decrypting migrated 1.0 file" assert dec_data.strip() == "foo", "incorrect decryption of rekeyed/migrated file: %s" % dec_data
gpl-3.0
gibiansky/tensorflow
tensorflow/python/kernel_tests/candidate_sampler_ops_test.py
110
5343
# 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. # ============================================================================== """Tests for CandidateSamplerOp.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.ops import array_ops from tensorflow.python.ops import candidate_sampling_ops from tensorflow.python.ops import math_ops from tensorflow.python.platform import test class RangeSamplerOpsTest(test.TestCase): BATCH_SIZE = 3 NUM_TRUE = 2 RANGE = 5 NUM_SAMPLED = RANGE TRUE_LABELS = [[1, 2], [0, 4], [3, 3]] def testTrueCandidates(self): with self.test_session() as sess: indices = constant_op.constant([0, 0, 1, 1, 2, 2]) true_candidates_vec = constant_op.constant([1, 2, 0, 4, 3, 3]) true_candidates_matrix = array_ops.reshape( true_candidates_vec, [self.BATCH_SIZE, self.NUM_TRUE]) indices_val, true_candidates_val = sess.run( [indices, true_candidates_matrix]) self.assertAllEqual(indices_val, [0, 0, 1, 1, 2, 2]) self.assertAllEqual(true_candidates_val, self.TRUE_LABELS) def testSampledCandidates(self): with self.test_session(): true_classes = constant_op.constant( [[1, 2], [0, 4], [3, 3]], dtype=dtypes.int64) sampled_candidates, _, _ = candidate_sampling_ops.all_candidate_sampler( true_classes, self.NUM_TRUE, self.NUM_SAMPLED, True) result = sampled_candidates.eval() expected_ids = [0, 1, 2, 3, 4] self.assertAllEqual(result, expected_ids) self.assertEqual(sampled_candidates.get_shape(), [self.NUM_SAMPLED]) def testTrueLogExpectedCount(self): with self.test_session(): true_classes = constant_op.constant( [[1, 2], [0, 4], [3, 3]], dtype=dtypes.int64) _, true_expected_count, _ = candidate_sampling_ops.all_candidate_sampler( true_classes, self.NUM_TRUE, self.NUM_SAMPLED, True) true_log_expected_count = math_ops.log(true_expected_count) result = true_log_expected_count.eval() self.assertAllEqual(result, [[0.0] * self.NUM_TRUE] * self.BATCH_SIZE) self.assertEqual(true_expected_count.get_shape(), [self.BATCH_SIZE, self.NUM_TRUE]) self.assertEqual(true_log_expected_count.get_shape(), [self.BATCH_SIZE, self.NUM_TRUE]) def testSampledLogExpectedCount(self): with self.test_session(): true_classes = constant_op.constant( [[1, 2], [0, 4], [3, 3]], dtype=dtypes.int64) _, _, sampled_expected_count = candidate_sampling_ops.all_candidate_sampler( true_classes, self.NUM_TRUE, self.NUM_SAMPLED, True) sampled_log_expected_count = math_ops.log(sampled_expected_count) result = sampled_log_expected_count.eval() self.assertAllEqual(result, [0.0] * self.NUM_SAMPLED) self.assertEqual(sampled_expected_count.get_shape(), [self.NUM_SAMPLED]) self.assertEqual(sampled_log_expected_count.get_shape(), [self.NUM_SAMPLED]) def testAccidentalHits(self): with self.test_session() as sess: true_classes = constant_op.constant( [[1, 2], [0, 4], [3, 3]], dtype=dtypes.int64) sampled_candidates, _, _ = candidate_sampling_ops.all_candidate_sampler( true_classes, self.NUM_TRUE, self.NUM_SAMPLED, True) accidental_hits = candidate_sampling_ops.compute_accidental_hits( true_classes, sampled_candidates, self.NUM_TRUE) indices, ids, weights = sess.run(accidental_hits) self.assertEqual(1, accidental_hits[0].get_shape().ndims) self.assertEqual(1, accidental_hits[1].get_shape().ndims) self.assertEqual(1, accidental_hits[2].get_shape().ndims) for index, id_, weight in zip(indices, ids, weights): self.assertTrue(id_ in self.TRUE_LABELS[index]) self.assertLess(weight, -1.0e37) def testSeed(self): def draw(seed): with self.test_session(): true_classes = constant_op.constant( [[1, 2], [0, 4], [3, 3]], dtype=dtypes.int64) sampled, _, _ = candidate_sampling_ops.log_uniform_candidate_sampler( true_classes, self.NUM_TRUE, self.NUM_SAMPLED, True, 5, seed=seed) return sampled.eval() # Non-zero seed. Repeatable. for seed in [1, 12, 123, 1234]: self.assertAllEqual(draw(seed), draw(seed)) # Seed=0 means random seeds. num_same = 0 for _ in range(10): if np.allclose(draw(None), draw(None)): num_same += 1 # Accounts for the fact that the same random seed may be picked # twice very rarely. self.assertLessEqual(num_same, 2) if __name__ == "__main__": test.main()
apache-2.0
barryrobison/arsenalsuite
cpp/apps/burner/plugins/realflow.py
11
5336
from blur.Stone import * from blur.Classes import * from blur.Burner import * from PyQt4.QtCore import * from PyQt4.QtSql import * import re, traceback class RealFlowBurner(JobBurner): def __init__(self,job,slave): JobBurner.__init__(self,job,slave) self.Job = job self.Slave = slave self.RenderStarted = False self.JobDone = False self.RealFlowService = None self.RealFlowSoftware = None self.RealFlowDir = None def __del__(self): # Nothing is required # self.cleanup() is explicitly called by the slave pass # Names of processes to kill after burn is finished def processNames(self): return QStringList() << "realflow.exe" def getRealFlowService(self): if self.RealFlowService is None: realflowServices = self.Job.jobServices().services().filter('service',QRegExp('^RealFlow')) if len(realflowServices) == 0: raise "Unable to find RealFlow service for job to determine render executable" if len(realflowServices) > 1: raise "Multiple RealFlow services listed, unable to determine which RealFlow installation to use" self.RealFlowService = realflowServices[0] return self.RealFlowService def getRealFlowSoftware(self): if self.RealFlowSoftware is None: service = self.getRealFlowService() self.RealFlowSoftware = service.software() if not self.RealFlowSoftware.isRecord(): self.jobErrored( "service " + xsiService().service() + " has no software entry" ); return self.RealFlowSoftware def getRealFlowDir(self): sw = self.getRealFlowSoftware() return sw.installedPath() def workingDirectory(self): return self.getRealFlowDir() def executable(self): try: return self.getRealFlowDir() + "RealFlow.exe" except: traceback.print_exc() self.jobErrored( "Unknown exception getting fusion path: " + traceback.format_exc() ) def buildCmdArgs(self): # C:\Program Files (x86)\Next Limit\x64\RealFlow\RealFlow.exe -nogui -range 1 100 -mesh -useCache "emitter.flw" args = QStringList() args << "-nogui" args << "-range" tasks = self.assignedTasks().split("-") self.StartFrame = int(tasks[0]) if len(tasks) == 2: args << str(int(tasks[0])-1) << tasks[1] self.EndFrame = int(tasks[1]) elif len(tasks) == 1: args << str(int(tasks[0])-1) << tasks[0] self.EndFrame = int(tasks[0]) if self.Job.simType() == 'Mesh': args << "-mesh" args << "-useCache" args << self.burnFile() return args def startProcess(self): Log( "RealFlowBurner::startBurn() called" ) JobBurner.startProcess(self) self.BurnProcess = self.process() self.Started = QDateTime.currentDateTime() self.checkupTimer().start(2 * 60 * 1000) # Every two minutes Log( "RealFlowBurner::startBurn() done" ) def cleanup(self): Log( "RealFlowBurner::cleanup() called" ) JobBurner.cleanup(self) Log( "RealFlowBurner::cleaup() done" ) #C:\Program Files (x86)\Next Limit\x64\RealFlow4>RealFlow -nogui -range 1 2 "G:\F #errari\01_Shots\Sc005\S0001.00\FX\LavaSplash\LavaSplashPreset\LavaSplashPreset-V #3.flw" #'import site' failed; use -v for traceback #----------------------------------------------------------------- #1998-2007 (c) Next Limit - RealFlow(32bits) v4.3.8.0124 #----------------------------------------------------------------- #Initializing Parameter Blocks ... #Checking license (use -license to enter a valid license)... #Initializing expressions engine ... #Initializing Real Impact world ... #Initializing Simulation Events dispatcher ... #Loading plugins ... #Loading workspace G:\Ferrari\01_Shots\Sc005\S0001.00\FX\LavaSplash\LavaSplashPre #set\LavaSplashPreset-V3.flw ... #>12:27:33: RealFlow error: Couldn't install license server. The UDP port 2222is #used by another application. Probably another RealFlow instance. #>>> Reading SD file #>>> 50% #>>> 100% #>12:27:33: Workspace version: 2046 #>>> Setting up scene #>>> 14% #>>> 28% #>>> 42% #>>> 57% #>>> 71% #>>> 85% #>>> 100% #Using 2 threads for this simulation ... #.................................................. #>12:27:51: Frame 2 finished. #>12:27:51: Elapsed time: (0h0m18s) #>12:27:51: ========================================= def slotProcessOutputLine(self,line,channel): Log( "RealFlowBurner::slotReadOutput() called, ready to read output" ) error = False # Job started if re.search( '100%', line ): self.RenderStarted = True self.taskStart(self.StartFrame) # Frames Rendered mo = re.search( r'Frame (\d+) finished.', line ) if mo: frame = int(mo.group(1)) self.taskDone(frame) if frame == self.EndFrame: self.JobDone = True QTimer.singleShot( 30000, self, SLOT('jobFinished()') ) else: self.taskStart(frame + 1) return JobBurner.slotProcessOutputLine(self,line,channel) def slotProcessExited(self): if not self.JobDone: self.checkup() if self.JobDone: self.jobFinished() return JobBurner.slotProcessExited(self) class RealFlowBurnerPlugin(JobBurnerPlugin): def __init__(self): JobBurnerPlugin.__init__(self) def jobTypes(self): return QStringList('RealFlow') def createBurner(self,job,slave): Log( "RealFlowBurnerPlugin::createBurner() called, Creating RealFlowBurner" ) if job.jobType().name() == 'RealFlow': return RealFlowBurner(job,slave) return None JobBurnerFactory.registerPlugin( RealFlowBurnerPlugin() )
gpl-2.0
jmcarp/django
tests/template_tests/filter_tests/test_truncatewords_html.py
386
1607
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.template.defaultfilters import truncatewords_html from django.test import SimpleTestCase class FunctionTests(SimpleTestCase): def test_truncate_zero(self): self.assertEqual(truncatewords_html('<p>one <a href="#">two - three <br>four</a> five</p>', 0), '') def test_truncate(self): self.assertEqual( truncatewords_html('<p>one <a href="#">two - three <br>four</a> five</p>', 2), '<p>one <a href="#">two ...</a></p>', ) def test_truncate2(self): self.assertEqual( truncatewords_html('<p>one <a href="#">two - three <br>four</a> five</p>', 4), '<p>one <a href="#">two - three <br>four ...</a></p>', ) def test_truncate3(self): self.assertEqual( truncatewords_html('<p>one <a href="#">two - three <br>four</a> five</p>', 5), '<p>one <a href="#">two - three <br>four</a> five</p>', ) def test_truncate4(self): self.assertEqual( truncatewords_html('<p>one <a href="#">two - three <br>four</a> five</p>', 100), '<p>one <a href="#">two - three <br>four</a> five</p>', ) def test_truncate_unicode(self): self.assertEqual(truncatewords_html('\xc5ngstr\xf6m was here', 1), '\xc5ngstr\xf6m ...') def test_truncate_complex(self): self.assertEqual( truncatewords_html('<i>Buenos d&iacute;as! &#x00bf;C&oacute;mo est&aacute;?</i>', 3), '<i>Buenos d&iacute;as! &#x00bf;C&oacute;mo ...</i>', )
bsd-3-clause
kenwang815/KodiPlugins
script.module.youtube.dl/lib/youtube_dl/extractor/cbc.py
7
6190
# coding: utf-8 from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( js_to_json, smuggle_url, ) class CBCIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?cbc\.ca/(?!player/)(?:[^/]+/)+(?P<id>[^/?#]+)' _TESTS = [{ # with mediaId 'url': 'http://www.cbc.ca/22minutes/videos/clips-season-23/don-cherry-play-offs', 'md5': '97e24d09672fc4cf56256d6faa6c25bc', 'info_dict': { 'id': '2682904050', 'ext': 'mp4', 'title': 'Don Cherry – All-Stars', 'description': 'Don Cherry has a bee in his bonnet about AHL player John Scott because that guy’s got heart.', 'timestamp': 1454463000, 'upload_date': '20160203', 'uploader': 'CBCC-NEW', }, }, { # with clipId 'url': 'http://www.cbc.ca/archives/entry/1978-robin-williams-freestyles-on-90-minutes-live', 'md5': '0274a90b51a9b4971fe005c63f592f12', 'info_dict': { 'id': '2487345465', 'ext': 'mp4', 'title': 'Robin Williams freestyles on 90 Minutes Live', 'description': 'Wacky American comedian Robin Williams shows off his infamous "freestyle" comedic talents while being interviewed on CBC\'s 90 Minutes Live.', 'upload_date': '19780210', 'uploader': 'CBCC-NEW', 'timestamp': 255977160, }, }, { # multiple iframes 'url': 'http://www.cbc.ca/natureofthings/blog/birds-eye-view-from-vancouvers-burrard-street-bridge-how-we-got-the-shot', 'playlist': [{ 'md5': '377572d0b49c4ce0c9ad77470e0b96b4', 'info_dict': { 'id': '2680832926', 'ext': 'mp4', 'title': 'An Eagle\'s-Eye View Off Burrard Bridge', 'description': 'Hercules the eagle flies from Vancouver\'s Burrard Bridge down to a nearby park with a mini-camera strapped to his back.', 'upload_date': '20160201', 'timestamp': 1454342820, 'uploader': 'CBCC-NEW', }, }, { 'md5': '415a0e3f586113894174dfb31aa5bb1a', 'info_dict': { 'id': '2658915080', 'ext': 'mp4', 'title': 'Fly like an eagle!', 'description': 'Eagle equipped with a mini camera flies from the world\'s tallest tower', 'upload_date': '20150315', 'timestamp': 1426443984, 'uploader': 'CBCC-NEW', }, }], }] @classmethod def suitable(cls, url): return False if CBCPlayerIE.suitable(url) else super(CBCIE, cls).suitable(url) def _real_extract(self, url): display_id = self._match_id(url) webpage = self._download_webpage(url, display_id) player_init = self._search_regex( r'CBC\.APP\.Caffeine\.initInstance\(({.+?})\);', webpage, 'player init', default=None) if player_init: player_info = self._parse_json(player_init, display_id, js_to_json) media_id = player_info.get('mediaId') if not media_id: clip_id = player_info['clipId'] media_id = self._download_json( 'http://feed.theplatform.com/f/h9dtGB/punlNGjMlc1F?fields=id&byContent=byReleases%3DbyId%253D' + clip_id, clip_id)['entries'][0]['id'].split('/')[-1] return self.url_result('cbcplayer:%s' % media_id, 'CBCPlayer', media_id) else: entries = [self.url_result('cbcplayer:%s' % media_id, 'CBCPlayer', media_id) for media_id in re.findall(r'<iframe[^>]+src="[^"]+?mediaId=(\d+)"', webpage)] return self.playlist_result(entries) class CBCPlayerIE(InfoExtractor): _VALID_URL = r'(?:cbcplayer:|https?://(?:www\.)?cbc\.ca/(?:player/play/|i/caffeine/syndicate/\?mediaId=))(?P<id>\d+)' _TESTS = [{ 'url': 'http://www.cbc.ca/player/play/2683190193', 'md5': '64d25f841ddf4ddb28a235338af32e2c', 'info_dict': { 'id': '2683190193', 'ext': 'mp4', 'title': 'Gerry Runs a Sweat Shop', 'description': 'md5:b457e1c01e8ff408d9d801c1c2cd29b0', 'timestamp': 1455071400, 'upload_date': '20160210', 'uploader': 'CBCC-NEW', }, }, { # Redirected from http://www.cbc.ca/player/AudioMobile/All%20in%20a%20Weekend%20Montreal/ID/2657632011/ 'url': 'http://www.cbc.ca/player/play/2657631896', 'md5': 'e5e708c34ae6fca156aafe17c43e8b75', 'info_dict': { 'id': '2657631896', 'ext': 'mp3', 'title': 'CBC Montreal is organizing its first ever community hackathon!', 'description': 'The modern technology we tend to depend on so heavily, is never without it\'s share of hiccups and headaches. Next weekend - CBC Montreal will be getting members of the public for its first Hackathon.', 'timestamp': 1425704400, 'upload_date': '20150307', 'uploader': 'CBCC-NEW', }, }, { # available only when we add `formats=MPEG4,FLV,MP3` to theplatform url 'url': 'http://www.cbc.ca/player/play/2164402062', 'md5': '17a61eb813539abea40618d6323a7f82', 'info_dict': { 'id': '2164402062', 'ext': 'flv', 'title': 'Cancer survivor four times over', 'description': 'Tim Mayer has beaten three different forms of cancer four times in five years.', 'timestamp': 1320410746, 'upload_date': '20111104', 'uploader': 'CBCC-NEW', }, }] def _real_extract(self, url): video_id = self._match_id(url) return { '_type': 'url_transparent', 'ie_key': 'ThePlatform', 'url': smuggle_url( 'http://link.theplatform.com/s/ExhSPC/media/guid/2655402169/%s?mbr=true&formats=MPEG4,FLV,MP3' % video_id, { 'force_smil_url': True }), 'id': video_id, }
gpl-2.0
browseinfo/odoo_saas3_nicolas
addons/anonymization/anonymization.py
39
28666
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved # $Id$ # # 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 lxml import etree import os import base64 try: import cPickle as pickle except ImportError: import pickle import random import datetime from openerp.osv import fields, osv from openerp.tools.translate import _ from itertools import groupby from operator import itemgetter FIELD_STATES = [('clear', 'Clear'), ('anonymized', 'Anonymized'), ('not_existing', 'Not Existing'), ('new', 'New')] ANONYMIZATION_STATES = FIELD_STATES + [('unstable', 'Unstable')] WIZARD_ANONYMIZATION_STATES = [('clear', 'Clear'), ('anonymized', 'Anonymized'), ('unstable', 'Unstable')] ANONYMIZATION_HISTORY_STATE = [('started', 'Started'), ('done', 'Done'), ('in_exception', 'Exception occured')] ANONYMIZATION_DIRECTION = [('clear -> anonymized', 'clear -> anonymized'), ('anonymized -> clear', 'anonymized -> clear')] def group(lst, cols): if isinstance(cols, basestring): cols = [cols] return dict((k, [v for v in itr]) for k, itr in groupby(sorted(lst, key=itemgetter(*cols)), itemgetter(*cols))) class ir_model_fields_anonymization(osv.osv): _name = 'ir.model.fields.anonymization' _rec_name = 'field_id' _columns = { 'model_name': fields.char('Object Name', size=128, required=True), 'model_id': fields.many2one('ir.model', 'Object', ondelete='set null'), 'field_name': fields.char('Field Name', size=128, required=True), 'field_id': fields.many2one('ir.model.fields', 'Field', ondelete='set null'), 'state': fields.selection(selection=FIELD_STATES, String='Status', required=True, readonly=True), } _sql_constraints = [ ('model_id_field_id_uniq', 'unique (model_name, field_name)', _("You cannot have two fields with the same name on the same object!")), ] def _get_global_state(self, cr, uid, context=None): ids = self.search(cr, uid, [('state', '<>', 'not_existing')], context=context) fields = self.browse(cr, uid, ids, context=context) if not len(fields) or len(fields) == len([f for f in fields if f.state == 'clear']): state = 'clear' # all fields are clear elif len(fields) == len([f for f in fields if f.state == 'anonymized']): state = 'anonymized' # all fields are anonymized else: state = 'unstable' # fields are mixed: this should be fixed return state def _check_write(self, cr, uid, context=None): """check that the field is created from the menu and not from an database update otherwise the database update can crash:""" if context is None: context = {} if context.get('manual'): global_state = self._get_global_state(cr, uid, context=context) if global_state == 'anonymized': raise osv.except_osv('Error!', "The database is currently anonymized, you cannot create, modify or delete fields.") elif global_state == 'unstable': msg = _("The database anonymization is currently in an unstable state. Some fields are anonymized," + \ " while some fields are not anonymized. You should try to solve this problem before trying to create, write or delete fields.") raise osv.except_osv('Error!', msg) return True def _get_model_and_field_ids(self, cr, uid, vals, context=None): model_and_field_ids = (False, False) if 'field_name' in vals and vals['field_name'] and 'model_name' in vals and vals['model_name']: ir_model_fields_obj = self.pool.get('ir.model.fields') ir_model_obj = self.pool.get('ir.model') model_ids = ir_model_obj.search(cr, uid, [('model', '=', vals['model_name'])], context=context) if model_ids: field_ids = ir_model_fields_obj.search(cr, uid, [('name', '=', vals['field_name']), ('model_id', '=', model_ids[0])], context=context) if field_ids: field_id = field_ids[0] model_and_field_ids = (model_ids[0], field_id) return model_and_field_ids def create(self, cr, uid, vals, context=None): # check field state: all should be clear before we can add a new field to anonymize: self._check_write(cr, uid, context=context) global_state = self._get_global_state(cr, uid, context=context) if 'field_name' in vals and vals['field_name'] and 'model_name' in vals and vals['model_name']: vals['model_id'], vals['field_id'] = self._get_model_and_field_ids(cr, uid, vals, context=context) # check not existing fields: if not vals.get('field_id'): vals['state'] = 'not_existing' else: vals['state'] = global_state res = super(ir_model_fields_anonymization, self).create(cr, uid, vals, context=context) return res def write(self, cr, uid, ids, vals, context=None): # check field state: all should be clear before we can modify a field: if not (len(vals.keys()) == 1 and vals.get('state') == 'clear'): self._check_write(cr, uid, context=context) if 'field_name' in vals and vals['field_name'] and 'model_name' in vals and vals['model_name']: vals['model_id'], vals['field_id'] = self._get_model_and_field_ids(cr, uid, vals, context=context) # check not existing fields: if 'field_id' in vals: if not vals.get('field_id'): vals['state'] = 'not_existing' else: global_state = self._get_global_state(cr, uid, context) if global_state != 'unstable': vals['state'] = global_state res = super(ir_model_fields_anonymization, self).write(cr, uid, ids, vals, context=context) return res def unlink(self, cr, uid, ids, context=None): # check field state: all should be clear before we can unlink a field: self._check_write(cr, uid, context=context) res = super(ir_model_fields_anonymization, self).unlink(cr, uid, ids, context=context) return res def onchange_model_id(self, cr, uid, ids, model_id, context=None): res = {'value': { 'field_name': False, 'field_id': False, 'model_name': False, }} if model_id: ir_model_obj = self.pool.get('ir.model') model_ids = ir_model_obj.search(cr, uid, [('id', '=', model_id)]) model_id = model_ids and model_ids[0] or None model_name = model_id and ir_model_obj.browse(cr, uid, model_id).model or False res['value']['model_name'] = model_name return res def onchange_model_name(self, cr, uid, ids, model_name, context=None): res = {'value': { 'field_name': False, 'field_id': False, 'model_id': False, }} if model_name: ir_model_obj = self.pool.get('ir.model') model_ids = ir_model_obj.search(cr, uid, [('model', '=', model_name)]) model_id = model_ids and model_ids[0] or False res['value']['model_id'] = model_id return res def onchange_field_name(self, cr, uid, ids, field_name, model_name): res = {'value': { 'field_id': False, }} if field_name and model_name: ir_model_fields_obj = self.pool.get('ir.model.fields') field_ids = ir_model_fields_obj.search(cr, uid, [('name', '=', field_name), ('model', '=', model_name)]) field_id = field_ids and field_ids[0] or False res['value']['field_id'] = field_id return res def onchange_field_id(self, cr, uid, ids, field_id, model_name): res = {'value': { 'field_name': False, }} if field_id: ir_model_fields_obj = self.pool.get('ir.model.fields') field = ir_model_fields_obj.browse(cr, uid, field_id) res['value']['field_name'] = field.name return res _defaults = { 'state': lambda *a: 'clear', } class ir_model_fields_anonymization_history(osv.osv): _name = 'ir.model.fields.anonymization.history' _order = "date desc" _columns = { 'date': fields.datetime('Date', required=True, readonly=True), 'field_ids': fields.many2many('ir.model.fields.anonymization', 'anonymized_field_to_history_rel', 'field_id', 'history_id', 'Fields', readonly=True), 'state': fields.selection(selection=ANONYMIZATION_HISTORY_STATE, string='Status', required=True, readonly=True), 'direction': fields.selection(selection=ANONYMIZATION_DIRECTION, string='Direction', required=True, readonly=True), 'msg': fields.text('Message', readonly=True), 'filepath': fields.char(string='File path', size=256, readonly=True), } class ir_model_fields_anonymize_wizard(osv.osv_memory): _name = 'ir.model.fields.anonymize.wizard' def _get_state(self, cr, uid, ids, name, arg, context=None): res = {} state = self._get_state_value(cr, uid, context=None) for id in ids: res[id] = state return res def _get_summary(self, cr, uid, ids, name, arg, context=None): res = {} summary = self._get_summary_value(cr, uid, context) for id in ids: res[id] = summary return res _columns = { 'name': fields.char(size=64, string='File Name'), 'summary': fields.function(_get_summary, type='text', string='Summary'), 'file_export': fields.binary(string='Export'), 'file_import': fields.binary(string='Import', help="This is the file created by the anonymization process. It should have the '.pickle' extention."), 'state': fields.function(_get_state, string='Status', type='selection', selection=WIZARD_ANONYMIZATION_STATES, readonly=False), 'msg': fields.text(string='Message'), } def _get_state_value(self, cr, uid, context=None): state = self.pool.get('ir.model.fields.anonymization')._get_global_state(cr, uid, context=context) return state def _get_summary_value(self, cr, uid, context=None): summary = u'' anon_field_obj = self.pool.get('ir.model.fields.anonymization') ir_model_fields_obj = self.pool.get('ir.model.fields') anon_field_ids = anon_field_obj.search(cr, uid, [('state', '<>', 'not_existing')], context=context) anon_fields = anon_field_obj.browse(cr, uid, anon_field_ids, context=context) field_ids = [anon_field.field_id.id for anon_field in anon_fields if anon_field.field_id] fields = ir_model_fields_obj.browse(cr, uid, field_ids, context=context) fields_by_id = dict([(f.id, f) for f in fields]) for anon_field in anon_fields: field = fields_by_id.get(anon_field.field_id.id) values = { 'model_name': field.model_id.name, 'model_code': field.model_id.model, 'field_code': field.name, 'field_name': field.field_description, 'state': anon_field.state, } summary += u" * %(model_name)s (%(model_code)s) -> %(field_name)s (%(field_code)s): state: (%(state)s)\n" % values return summary def default_get(self, cr, uid, fields_list, context=None): res = {} res['name'] = '.pickle' res['summary'] = self._get_summary_value(cr, uid, context) res['state'] = self._get_state_value(cr, uid, context) res['msg'] = _("""Before executing the anonymization process, you should make a backup of your database.""") return res def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, *args, **kwargs): state = self.pool.get('ir.model.fields.anonymization')._get_global_state(cr, uid, context=context) if context is None: context = {} step = context.get('step', 'new_window') res = super(ir_model_fields_anonymize_wizard, self).fields_view_get(cr, uid, view_id, view_type, context, *args, **kwargs) eview = etree.fromstring(res['arch']) placeholder = eview.xpath("group[@name='placeholder1']") if len(placeholder): placeholder = placeholder[0] if step == 'new_window' and state == 'clear': # clicked in the menu and the fields are not anonymized: warn the admin that backuping the db is very important placeholder.addnext(etree.Element('field', {'name': 'msg', 'colspan': '4', 'nolabel': '1'})) placeholder.addnext(etree.Element('newline')) placeholder.addnext(etree.Element('label', {'string': 'Warning'})) eview.remove(placeholder) elif step == 'new_window' and state == 'anonymized': # clicked in the menu and the fields are already anonymized placeholder.addnext(etree.Element('newline')) placeholder.addnext(etree.Element('field', {'name': 'file_import', 'required': "1"})) placeholder.addnext(etree.Element('label', {'string': 'Anonymization file'})) eview.remove(placeholder) elif step == 'just_anonymized': # we just ran the anonymization process, we need the file export field placeholder.addnext(etree.Element('newline')) placeholder.addnext(etree.Element('field', {'name': 'file_export'})) # we need to remove the button: buttons = eview.xpath("button") for button in buttons: eview.remove(button) # and add a message: placeholder.addnext(etree.Element('field', {'name': 'msg', 'colspan': '4', 'nolabel': '1'})) placeholder.addnext(etree.Element('newline')) placeholder.addnext(etree.Element('label', {'string': 'Result'})) # remove the placeholer: eview.remove(placeholder) elif step == 'just_desanonymized': # we just reversed the anonymization process, we don't need any field # we need to remove the button buttons = eview.xpath("button") for button in buttons: eview.remove(button) # and add a message # and add a message: placeholder.addnext(etree.Element('field', {'name': 'msg', 'colspan': '4', 'nolabel': '1'})) placeholder.addnext(etree.Element('newline')) placeholder.addnext(etree.Element('label', {'string': 'Result'})) # remove the placeholer: eview.remove(placeholder) else: msg = _("The database anonymization is currently in an unstable state. Some fields are anonymized," + \ " while some fields are not anonymized. You should try to solve this problem before trying to do anything else.") raise osv.except_osv('Error!', msg) res['arch'] = etree.tostring(eview) return res def _raise_after_history_update(self, cr, uid, history_id, error_type, error_msg): self.pool.get('ir.model.fields.anonymization.history').write(cr, uid, history_id, { 'state': 'in_exception', 'msg': error_msg, }) raise osv.except_osv(error_type, error_msg) def anonymize_database(self, cr, uid, ids, context=None): """Sets the 'anonymized' state to defined fields""" # create a new history record: anonymization_history_model = self.pool.get('ir.model.fields.anonymization.history') vals = { 'date': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), 'state': 'started', 'direction': 'clear -> anonymized', } history_id = anonymization_history_model.create(cr, uid, vals) # check that all the defined fields are in the 'clear' state state = self.pool.get('ir.model.fields.anonymization')._get_global_state(cr, uid, context=context) if state == 'anonymized': self._raise_after_history_update(cr, uid, history_id, _('Error !'), _("The database is currently anonymized, you cannot anonymize it again.")) elif state == 'unstable': msg = _("The database anonymization is currently in an unstable state. Some fields are anonymized," + \ " while some fields are not anonymized. You should try to solve this problem before trying to do anything.") self._raise_after_history_update(cr, uid, history_id, 'Error !', msg) # do the anonymization: dirpath = os.environ.get('HOME') or os.getcwd() rel_filepath = 'field_anonymization_%s_%s.pickle' % (cr.dbname, history_id) abs_filepath = os.path.abspath(os.path.join(dirpath, rel_filepath)) ir_model_fields_anonymization_model = self.pool.get('ir.model.fields.anonymization') field_ids = ir_model_fields_anonymization_model.search(cr, uid, [('state', '<>', 'not_existing')], context=context) fields = ir_model_fields_anonymization_model.browse(cr, uid, field_ids, context=context) if not fields: msg = "No fields are going to be anonymized." self._raise_after_history_update(cr, uid, history_id, 'Error !', msg) data = [] for field in fields: model_name = field.model_id.model field_name = field.field_id.name field_type = field.field_id.ttype table_name = self.pool[model_name]._table # get the current value sql = "select id, %s from %s" % (field_name, table_name) cr.execute(sql) records = cr.dictfetchall() for record in records: data.append({"model_id": model_name, "field_id": field_name, "id": record['id'], "value": record[field_name]}) # anonymize the value: anonymized_value = None sid = str(record['id']) if field_type == 'char': anonymized_value = 'xxx'+sid elif field_type == 'selection': anonymized_value = 'xxx'+sid elif field_type == 'text': anonymized_value = 'xxx'+sid elif field_type == 'boolean': anonymized_value = random.choice([True, False]) elif field_type == 'date': anonymized_value = '2011-11-11' elif field_type == 'datetime': anonymized_value = '2011-11-11 11:11:11' elif field_type == 'float': anonymized_value = 0.0 elif field_type == 'integer': anonymized_value = 0 elif field_type in ['binary', 'many2many', 'many2one', 'one2many', 'reference']: # cannot anonymize these kind of fields msg = _("Cannot anonymize fields of these types: binary, many2many, many2one, one2many, reference.") self._raise_after_history_update(cr, uid, history_id, 'Error !', msg) if anonymized_value is None: self._raise_after_history_update(cr, uid, history_id, _('Error !'), _("Anonymized value is None. This cannot happens.")) sql = "update %(table)s set %(field)s = %%(anonymized_value)s where id = %%(id)s" % { 'table': table_name, 'field': field_name, } cr.execute(sql, { 'anonymized_value': anonymized_value, 'id': record['id'] }) # save pickle: fn = open(abs_filepath, 'w') pickle.dump(data, fn, pickle.HIGHEST_PROTOCOL) # update the anonymization fields: values = { 'state': 'anonymized', } ir_model_fields_anonymization_model.write(cr, uid, field_ids, values, context=context) # add a result message in the wizard: msgs = ["Anonymization successful.", "", "Donot forget to save the resulting file to a safe place because you will not be able to revert the anonymization without this file.", "", "This file is also stored in the %s directory. The absolute file path is: %s.", ] msg = '\n'.join(msgs) % (dirpath, abs_filepath) fn = open(abs_filepath, 'r') self.write(cr, uid, ids, { 'msg': msg, 'file_export': base64.encodestring(fn.read()), }) fn.close() # update the history record: anonymization_history_model.write(cr, uid, history_id, { 'field_ids': [[6, 0, field_ids]], 'msg': msg, 'filepath': abs_filepath, 'state': 'done', }) # handle the view: view_id = self._id_get(cr, uid, 'ir.ui.view', 'view_ir_model_fields_anonymize_wizard_form', 'anonymization') return { 'res_id': ids[0], 'view_id': [view_id], 'view_type': 'form', "view_mode": 'form', 'res_model': 'ir.model.fields.anonymize.wizard', 'type': 'ir.actions.act_window', 'context': {'step': 'just_anonymized'}, 'target':'new', } def reverse_anonymize_database(self, cr, uid, ids, context=None): """Set the 'clear' state to defined fields""" ir_model_fields_anonymization_model = self.pool.get('ir.model.fields.anonymization') anonymization_history_model = self.pool.get('ir.model.fields.anonymization.history') # create a new history record: vals = { 'date': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), 'state': 'started', 'direction': 'anonymized -> clear', } history_id = anonymization_history_model.create(cr, uid, vals) # check that all the defined fields are in the 'anonymized' state state = ir_model_fields_anonymization_model._get_global_state(cr, uid, context=context) if state == 'clear': raise osv.except_osv_('Error!', "The database is not currently anonymized, you cannot reverse the anonymization.") elif state == 'unstable': msg = _("The database anonymization is currently in an unstable state. Some fields are anonymized," + \ " while some fields are not anonymized. You should try to solve this problem before trying to do anything.") raise osv.except_osv('Error!', msg) wizards = self.browse(cr, uid, ids, context=context) for wizard in wizards: if not wizard.file_import: msg = _("It is not possible to reverse the anonymization process without supplying the anonymization export file.") self._raise_after_history_update(cr, uid, history_id, 'Error !', msg) # reverse the anonymization: # load the pickle file content into a data structure: data = pickle.loads(base64.decodestring(wizard.file_import)) migration_fix_obj = self.pool.get('ir.model.fields.anonymization.migration.fix') fix_ids = migration_fix_obj.search(cr, uid, [('target_version', '=', '7.0')]) fixes = migration_fix_obj.read(cr, uid, fix_ids, ['model_name', 'field_name', 'query', 'query_type', 'sequence']) fixes = group(fixes, ('model_name', 'field_name')) for line in data: queries = [] table_name = self.pool[line['model_id']]._table if line['model_id'] in self.pool else None # check if custom sql exists: key = (line['model_id'], line['field_id']) custom_updates = fixes.get(key) if custom_updates: custom_updates.sort(key=itemgetter('sequence')) queries = [(record['query'], record['query_type']) for record in custom_updates if record['query_type']] elif table_name: queries = [("update %(table)s set %(field)s = %%(value)s where id = %%(id)s" % { 'table': table_name, 'field': line['field_id'], }, 'sql')] for query in queries: if query[1] == 'sql': sql = query[0] cr.execute(sql, { 'value': line['value'], 'id': line['id'] }) elif query[1] == 'python': raw_code = query[0] code = raw_code % line eval(code) else: raise Exception("Unknown query type '%s'. Valid types are: sql, python." % (query['query_type'], )) # update the anonymization fields: ir_model_fields_anonymization_model = self.pool.get('ir.model.fields.anonymization') field_ids = ir_model_fields_anonymization_model.search(cr, uid, [('state', '<>', 'not_existing')], context=context) values = { 'state': 'clear', } ir_model_fields_anonymization_model.write(cr, uid, field_ids, values, context=context) # add a result message in the wizard: msg = '\n'.join(["Successfully reversed the anonymization.", "", ]) self.write(cr, uid, ids, {'msg': msg}) # update the history record: anonymization_history_model.write(cr, uid, history_id, { 'field_ids': [[6, 0, field_ids]], 'msg': msg, 'filepath': False, 'state': 'done', }) # handle the view: view_id = self._id_get(cr, uid, 'ir.ui.view', 'view_ir_model_fields_anonymize_wizard_form', 'anonymization') return { 'res_id': ids[0], 'view_id': [view_id], 'view_type': 'form', "view_mode": 'form', 'res_model': 'ir.model.fields.anonymize.wizard', 'type': 'ir.actions.act_window', 'context': {'step': 'just_desanonymized'}, 'target':'new', } def _id_get(self, cr, uid, model, id_str, mod): if '.' in id_str: mod, id_str = id_str.split('.') try: idn = self.pool.get('ir.model.data')._get_id(cr, uid, mod, id_str) res = int(self.pool.get('ir.model.data').read(cr, uid, [idn], ['res_id'])[0]['res_id']) except: res = None return res class ir_model_fields_anonymization_migration_fix(osv.osv): _name = 'ir.model.fields.anonymization.migration.fix' _order = "sequence" _columns = { 'target_version': fields.char('Target Version'), 'model_name': fields.char('Model'), 'field_name': fields.char('Field'), 'query': fields.text('Query'), 'query_type': fields.selection(string='Query', selection=[('sql', 'sql'), ('python', 'python')]), 'sequence': fields.integer('Sequence'), } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
lexus42/4022322442test
static/Brython3.1.1-20150328-091302/Lib/unittest/case.py
743
48873
"""Test case implementation""" import sys import functools import difflib import pprint import re import warnings import collections from . import result from .util import (strclass, safe_repr, _count_diff_all_purpose, _count_diff_hashable) __unittest = True DIFF_OMITTED = ('\nDiff is %s characters long. ' 'Set self.maxDiff to None to see it.') class SkipTest(Exception): """ Raise this exception in a test to skip it. Usually you can use TestCase.skipTest() or one of the skipping decorators instead of raising this directly. """ class _ExpectedFailure(Exception): """ Raise this when a test is expected to fail. This is an implementation detail. """ def __init__(self, exc_info): super(_ExpectedFailure, self).__init__() self.exc_info = exc_info class _UnexpectedSuccess(Exception): """ The test was supposed to fail, but it didn't! """ class _Outcome(object): def __init__(self): self.success = True self.skipped = None self.unexpectedSuccess = None self.expectedFailure = None self.errors = [] self.failures = [] def _id(obj): return obj def skip(reason): """ Unconditionally skip a test. """ def decorator(test_item): if not isinstance(test_item, type): @functools.wraps(test_item) def skip_wrapper(*args, **kwargs): raise SkipTest(reason) test_item = skip_wrapper test_item.__unittest_skip__ = True test_item.__unittest_skip_why__ = reason return test_item return decorator def skipIf(condition, reason): """ Skip a test if the condition is true. """ if condition: return skip(reason) return _id def skipUnless(condition, reason): """ Skip a test unless the condition is true. """ if not condition: return skip(reason) return _id def expectedFailure(func): @functools.wraps(func) def wrapper(*args, **kwargs): try: func(*args, **kwargs) except Exception: raise _ExpectedFailure(sys.exc_info()) raise _UnexpectedSuccess return wrapper class _AssertRaisesBaseContext(object): def __init__(self, expected, test_case, callable_obj=None, expected_regex=None): self.expected = expected self.test_case = test_case if callable_obj is not None: try: self.obj_name = callable_obj.__name__ except AttributeError: self.obj_name = str(callable_obj) else: self.obj_name = None if isinstance(expected_regex, (bytes, str)): expected_regex = re.compile(expected_regex) self.expected_regex = expected_regex self.msg = None def _raiseFailure(self, standardMsg): msg = self.test_case._formatMessage(self.msg, standardMsg) raise self.test_case.failureException(msg) def handle(self, name, callable_obj, args, kwargs): """ If callable_obj is None, assertRaises/Warns is being used as a context manager, so check for a 'msg' kwarg and return self. If callable_obj is not None, call it passing args and kwargs. """ if callable_obj is None: self.msg = kwargs.pop('msg', None) return self with self: callable_obj(*args, **kwargs) class _AssertRaisesContext(_AssertRaisesBaseContext): """A context manager used to implement TestCase.assertRaises* methods.""" def __enter__(self): return self def __exit__(self, exc_type, exc_value, tb): if exc_type is None: try: exc_name = self.expected.__name__ except AttributeError: exc_name = str(self.expected) if self.obj_name: self._raiseFailure("{} not raised by {}".format(exc_name, self.obj_name)) else: self._raiseFailure("{} not raised".format(exc_name)) if not issubclass(exc_type, self.expected): # let unexpected exceptions pass through return False # store exception, without traceback, for later retrieval self.exception = exc_value.with_traceback(None) if self.expected_regex is None: return True expected_regex = self.expected_regex if not expected_regex.search(str(exc_value)): self._raiseFailure('"{}" does not match "{}"'.format( expected_regex.pattern, str(exc_value))) return True class _AssertWarnsContext(_AssertRaisesBaseContext): """A context manager used to implement TestCase.assertWarns* methods.""" def __enter__(self): # The __warningregistry__'s need to be in a pristine state for tests # to work properly. for v in sys.modules.values(): if getattr(v, '__warningregistry__', None): v.__warningregistry__ = {} self.warnings_manager = warnings.catch_warnings(record=True) self.warnings = self.warnings_manager.__enter__() warnings.simplefilter("always", self.expected) return self def __exit__(self, exc_type, exc_value, tb): self.warnings_manager.__exit__(exc_type, exc_value, tb) if exc_type is not None: # let unexpected exceptions pass through return try: exc_name = self.expected.__name__ except AttributeError: exc_name = str(self.expected) first_matching = None for m in self.warnings: w = m.message if not isinstance(w, self.expected): continue if first_matching is None: first_matching = w if (self.expected_regex is not None and not self.expected_regex.search(str(w))): continue # store warning for later retrieval self.warning = w self.filename = m.filename self.lineno = m.lineno return # Now we simply try to choose a helpful failure message if first_matching is not None: self._raiseFailure('"{}" does not match "{}"'.format( self.expected_regex.pattern, str(first_matching))) if self.obj_name: self._raiseFailure("{} not triggered by {}".format(exc_name, self.obj_name)) else: self._raiseFailure("{} not triggered".format(exc_name)) class TestCase(object): """A class whose instances are single test cases. By default, the test code itself should be placed in a method named 'runTest'. If the fixture may be used for many test cases, create as many test methods as are needed. When instantiating such a TestCase subclass, specify in the constructor arguments the name of the test method that the instance is to execute. Test authors should subclass TestCase for their own tests. Construction and deconstruction of the test's environment ('fixture') can be implemented by overriding the 'setUp' and 'tearDown' methods respectively. If it is necessary to override the __init__ method, the base class __init__ method must always be called. It is important that subclasses should not change the signature of their __init__ method, since instances of the classes are instantiated automatically by parts of the framework in order to be run. When subclassing TestCase, you can set these attributes: * failureException: determines which exception will be raised when the instance's assertion methods fail; test methods raising this exception will be deemed to have 'failed' rather than 'errored'. * longMessage: determines whether long messages (including repr of objects used in assert methods) will be printed on failure in *addition* to any explicit message passed. * maxDiff: sets the maximum length of a diff in failure messages by assert methods using difflib. It is looked up as an instance attribute so can be configured by individual tests if required. """ failureException = AssertionError longMessage = True maxDiff = 80*8 # If a string is longer than _diffThreshold, use normal comparison instead # of difflib. See #11763. _diffThreshold = 2**16 # Attribute used by TestSuite for classSetUp _classSetupFailed = False def __init__(self, methodName='runTest'): """Create an instance of the class that will use the named test method when executed. Raises a ValueError if the instance does not have a method with the specified name. """ self._testMethodName = methodName self._outcomeForDoCleanups = None self._testMethodDoc = 'No test' try: testMethod = getattr(self, methodName) except AttributeError: if methodName != 'runTest': # we allow instantiation with no explicit method name # but not an *incorrect* or missing method name raise ValueError("no such test method in %s: %s" % (self.__class__, methodName)) else: self._testMethodDoc = testMethod.__doc__ self._cleanups = [] # Map types to custom assertEqual functions that will compare # instances of said type in more detail to generate a more useful # error message. self._type_equality_funcs = {} self.addTypeEqualityFunc(dict, 'assertDictEqual') self.addTypeEqualityFunc(list, 'assertListEqual') self.addTypeEqualityFunc(tuple, 'assertTupleEqual') self.addTypeEqualityFunc(set, 'assertSetEqual') self.addTypeEqualityFunc(frozenset, 'assertSetEqual') self.addTypeEqualityFunc(str, 'assertMultiLineEqual') def addTypeEqualityFunc(self, typeobj, function): """Add a type specific assertEqual style function to compare a type. This method is for use by TestCase subclasses that need to register their own type equality functions to provide nicer error messages. Args: typeobj: The data type to call this function on when both values are of the same type in assertEqual(). function: The callable taking two arguments and an optional msg= argument that raises self.failureException with a useful error message when the two arguments are not equal. """ self._type_equality_funcs[typeobj] = function def addCleanup(self, function, *args, **kwargs): """Add a function, with arguments, to be called when the test is completed. Functions added are called on a LIFO basis and are called after tearDown on test failure or success. Cleanup items are called even if setUp fails (unlike tearDown).""" self._cleanups.append((function, args, kwargs)) def setUp(self): "Hook method for setting up the test fixture before exercising it." pass def tearDown(self): "Hook method for deconstructing the test fixture after testing it." pass @classmethod def setUpClass(cls): "Hook method for setting up class fixture before running tests in the class." @classmethod def tearDownClass(cls): "Hook method for deconstructing the class fixture after running all tests in the class." def countTestCases(self): return 1 def defaultTestResult(self): return result.TestResult() def shortDescription(self): """Returns a one-line description of the test, or None if no description has been provided. The default implementation of this method returns the first line of the specified test method's docstring. """ doc = self._testMethodDoc return doc and doc.split("\n")[0].strip() or None def id(self): return "%s.%s" % (strclass(self.__class__), self._testMethodName) def __eq__(self, other): if type(self) is not type(other): return NotImplemented return self._testMethodName == other._testMethodName def __hash__(self): return hash((type(self), self._testMethodName)) def __str__(self): return "%s (%s)" % (self._testMethodName, strclass(self.__class__)) def __repr__(self): return "<%s testMethod=%s>" % \ (strclass(self.__class__), self._testMethodName) def _addSkip(self, result, reason): addSkip = getattr(result, 'addSkip', None) if addSkip is not None: addSkip(self, reason) else: warnings.warn("TestResult has no addSkip method, skips not reported", RuntimeWarning, 2) result.addSuccess(self) def _executeTestPart(self, function, outcome, isTest=False): try: function() except KeyboardInterrupt: raise except SkipTest as e: outcome.success = False outcome.skipped = str(e) except _UnexpectedSuccess: exc_info = sys.exc_info() outcome.success = False if isTest: outcome.unexpectedSuccess = exc_info else: outcome.errors.append(exc_info) except _ExpectedFailure: outcome.success = False exc_info = sys.exc_info() if isTest: outcome.expectedFailure = exc_info else: outcome.errors.append(exc_info) except self.failureException: outcome.success = False outcome.failures.append(sys.exc_info()) exc_info = sys.exc_info() except: outcome.success = False outcome.errors.append(sys.exc_info()) def run(self, result=None): orig_result = result if result is None: result = self.defaultTestResult() startTestRun = getattr(result, 'startTestRun', None) if startTestRun is not None: startTestRun() result.startTest(self) testMethod = getattr(self, self._testMethodName) if (getattr(self.__class__, "__unittest_skip__", False) or getattr(testMethod, "__unittest_skip__", False)): # If the class or method was skipped. try: skip_why = (getattr(self.__class__, '__unittest_skip_why__', '') or getattr(testMethod, '__unittest_skip_why__', '')) self._addSkip(result, skip_why) finally: result.stopTest(self) return try: outcome = _Outcome() self._outcomeForDoCleanups = outcome self._executeTestPart(self.setUp, outcome) if outcome.success: self._executeTestPart(testMethod, outcome, isTest=True) self._executeTestPart(self.tearDown, outcome) self.doCleanups() if outcome.success: result.addSuccess(self) else: if outcome.skipped is not None: self._addSkip(result, outcome.skipped) for exc_info in outcome.errors: result.addError(self, exc_info) for exc_info in outcome.failures: result.addFailure(self, exc_info) if outcome.unexpectedSuccess is not None: addUnexpectedSuccess = getattr(result, 'addUnexpectedSuccess', None) if addUnexpectedSuccess is not None: addUnexpectedSuccess(self) else: warnings.warn("TestResult has no addUnexpectedSuccess method, reporting as failures", RuntimeWarning) result.addFailure(self, outcome.unexpectedSuccess) if outcome.expectedFailure is not None: addExpectedFailure = getattr(result, 'addExpectedFailure', None) if addExpectedFailure is not None: addExpectedFailure(self, outcome.expectedFailure) else: warnings.warn("TestResult has no addExpectedFailure method, reporting as passes", RuntimeWarning) result.addSuccess(self) return result finally: result.stopTest(self) if orig_result is None: stopTestRun = getattr(result, 'stopTestRun', None) if stopTestRun is not None: stopTestRun() def doCleanups(self): """Execute all cleanup functions. Normally called for you after tearDown.""" outcome = self._outcomeForDoCleanups or _Outcome() while self._cleanups: function, args, kwargs = self._cleanups.pop() part = lambda: function(*args, **kwargs) self._executeTestPart(part, outcome) # return this for backwards compatibility # even though we no longer us it internally return outcome.success def __call__(self, *args, **kwds): return self.run(*args, **kwds) def debug(self): """Run the test without collecting errors in a TestResult""" self.setUp() getattr(self, self._testMethodName)() self.tearDown() while self._cleanups: function, args, kwargs = self._cleanups.pop(-1) function(*args, **kwargs) def skipTest(self, reason): """Skip this test.""" raise SkipTest(reason) def fail(self, msg=None): """Fail immediately, with the given message.""" raise self.failureException(msg) def assertFalse(self, expr, msg=None): """Check that the expression is false.""" if expr: msg = self._formatMessage(msg, "%s is not false" % safe_repr(expr)) raise self.failureException(msg) def assertTrue(self, expr, msg=None): """Check that the expression is true.""" if not expr: msg = self._formatMessage(msg, "%s is not true" % safe_repr(expr)) raise self.failureException(msg) def _formatMessage(self, msg, standardMsg): """Honour the longMessage attribute when generating failure messages. If longMessage is False this means: * Use only an explicit message if it is provided * Otherwise use the standard message for the assert If longMessage is True: * Use the standard message * If an explicit message is provided, plus ' : ' and the explicit message """ if not self.longMessage: return msg or standardMsg if msg is None: return standardMsg try: # don't switch to '{}' formatting in Python 2.X # it changes the way unicode input is handled return '%s : %s' % (standardMsg, msg) except UnicodeDecodeError: return '%s : %s' % (safe_repr(standardMsg), safe_repr(msg)) def assertRaises(self, excClass, callableObj=None, *args, **kwargs): """Fail unless an exception of class excClass is raised by callableObj when invoked with arguments args and keyword arguments kwargs. If a different type of exception is raised, it will not be caught, and the test case will be deemed to have suffered an error, exactly as for an unexpected exception. If called with callableObj omitted or None, will return a context object used like this:: with self.assertRaises(SomeException): do_something() An optional keyword argument 'msg' can be provided when assertRaises is used as a context object. The context manager keeps a reference to the exception as the 'exception' attribute. This allows you to inspect the exception after the assertion:: with self.assertRaises(SomeException) as cm: do_something() the_exception = cm.exception self.assertEqual(the_exception.error_code, 3) """ context = _AssertRaisesContext(excClass, self, callableObj) return context.handle('assertRaises', callableObj, args, kwargs) def assertWarns(self, expected_warning, callable_obj=None, *args, **kwargs): """Fail unless a warning of class warnClass is triggered by callable_obj when invoked with arguments args and keyword arguments kwargs. If a different type of warning is triggered, it will not be handled: depending on the other warning filtering rules in effect, it might be silenced, printed out, or raised as an exception. If called with callable_obj omitted or None, will return a context object used like this:: with self.assertWarns(SomeWarning): do_something() An optional keyword argument 'msg' can be provided when assertWarns is used as a context object. The context manager keeps a reference to the first matching warning as the 'warning' attribute; similarly, the 'filename' and 'lineno' attributes give you information about the line of Python code from which the warning was triggered. This allows you to inspect the warning after the assertion:: with self.assertWarns(SomeWarning) as cm: do_something() the_warning = cm.warning self.assertEqual(the_warning.some_attribute, 147) """ context = _AssertWarnsContext(expected_warning, self, callable_obj) return context.handle('assertWarns', callable_obj, args, kwargs) def _getAssertEqualityFunc(self, first, second): """Get a detailed comparison function for the types of the two args. Returns: A callable accepting (first, second, msg=None) that will raise a failure exception if first != second with a useful human readable error message for those types. """ # # NOTE(gregory.p.smith): I considered isinstance(first, type(second)) # and vice versa. I opted for the conservative approach in case # subclasses are not intended to be compared in detail to their super # class instances using a type equality func. This means testing # subtypes won't automagically use the detailed comparison. Callers # should use their type specific assertSpamEqual method to compare # subclasses if the detailed comparison is desired and appropriate. # See the discussion in http://bugs.python.org/issue2578. # if type(first) is type(second): asserter = self._type_equality_funcs.get(type(first)) if asserter is not None: if isinstance(asserter, str): asserter = getattr(self, asserter) return asserter return self._baseAssertEqual def _baseAssertEqual(self, first, second, msg=None): """The default assertEqual implementation, not type specific.""" if not first == second: standardMsg = '%s != %s' % (safe_repr(first), safe_repr(second)) msg = self._formatMessage(msg, standardMsg) raise self.failureException(msg) def assertEqual(self, first, second, msg=None): """Fail if the two objects are unequal as determined by the '==' operator. """ assertion_func = self._getAssertEqualityFunc(first, second) assertion_func(first, second, msg=msg) def assertNotEqual(self, first, second, msg=None): """Fail if the two objects are equal as determined by the '!=' operator. """ if not first != second: msg = self._formatMessage(msg, '%s == %s' % (safe_repr(first), safe_repr(second))) raise self.failureException(msg) def assertAlmostEqual(self, first, second, places=None, msg=None, delta=None): """Fail if the two objects are unequal as determined by their difference rounded to the given number of decimal places (default 7) and comparing to zero, or by comparing that the between the two objects is more than the given delta. Note that decimal places (from zero) are usually not the same as significant digits (measured from the most signficant digit). If the two objects compare equal then they will automatically compare almost equal. """ if first == second: # shortcut return if delta is not None and places is not None: raise TypeError("specify delta or places not both") if delta is not None: if abs(first - second) <= delta: return standardMsg = '%s != %s within %s delta' % (safe_repr(first), safe_repr(second), safe_repr(delta)) else: if places is None: places = 7 if round(abs(second-first), places) == 0: return standardMsg = '%s != %s within %r places' % (safe_repr(first), safe_repr(second), places) msg = self._formatMessage(msg, standardMsg) raise self.failureException(msg) def assertNotAlmostEqual(self, first, second, places=None, msg=None, delta=None): """Fail if the two objects are equal as determined by their difference rounded to the given number of decimal places (default 7) and comparing to zero, or by comparing that the between the two objects is less than the given delta. Note that decimal places (from zero) are usually not the same as significant digits (measured from the most signficant digit). Objects that are equal automatically fail. """ if delta is not None and places is not None: raise TypeError("specify delta or places not both") if delta is not None: if not (first == second) and abs(first - second) > delta: return standardMsg = '%s == %s within %s delta' % (safe_repr(first), safe_repr(second), safe_repr(delta)) else: if places is None: places = 7 if not (first == second) and round(abs(second-first), places) != 0: return standardMsg = '%s == %s within %r places' % (safe_repr(first), safe_repr(second), places) msg = self._formatMessage(msg, standardMsg) raise self.failureException(msg) def assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None): """An equality assertion for ordered sequences (like lists and tuples). For the purposes of this function, a valid ordered sequence type is one which can be indexed, has a length, and has an equality operator. Args: seq1: The first sequence to compare. seq2: The second sequence to compare. seq_type: The expected datatype of the sequences, or None if no datatype should be enforced. msg: Optional message to use on failure instead of a list of differences. """ if seq_type is not None: seq_type_name = seq_type.__name__ if not isinstance(seq1, seq_type): raise self.failureException('First sequence is not a %s: %s' % (seq_type_name, safe_repr(seq1))) if not isinstance(seq2, seq_type): raise self.failureException('Second sequence is not a %s: %s' % (seq_type_name, safe_repr(seq2))) else: seq_type_name = "sequence" differing = None try: len1 = len(seq1) except (TypeError, NotImplementedError): differing = 'First %s has no length. Non-sequence?' % ( seq_type_name) if differing is None: try: len2 = len(seq2) except (TypeError, NotImplementedError): differing = 'Second %s has no length. Non-sequence?' % ( seq_type_name) if differing is None: if seq1 == seq2: return seq1_repr = safe_repr(seq1) seq2_repr = safe_repr(seq2) if len(seq1_repr) > 30: seq1_repr = seq1_repr[:30] + '...' if len(seq2_repr) > 30: seq2_repr = seq2_repr[:30] + '...' elements = (seq_type_name.capitalize(), seq1_repr, seq2_repr) differing = '%ss differ: %s != %s\n' % elements for i in range(min(len1, len2)): try: item1 = seq1[i] except (TypeError, IndexError, NotImplementedError): differing += ('\nUnable to index element %d of first %s\n' % (i, seq_type_name)) break try: item2 = seq2[i] except (TypeError, IndexError, NotImplementedError): differing += ('\nUnable to index element %d of second %s\n' % (i, seq_type_name)) break if item1 != item2: differing += ('\nFirst differing element %d:\n%s\n%s\n' % (i, item1, item2)) break else: if (len1 == len2 and seq_type is None and type(seq1) != type(seq2)): # The sequences are the same, but have differing types. return if len1 > len2: differing += ('\nFirst %s contains %d additional ' 'elements.\n' % (seq_type_name, len1 - len2)) try: differing += ('First extra element %d:\n%s\n' % (len2, seq1[len2])) except (TypeError, IndexError, NotImplementedError): differing += ('Unable to index element %d ' 'of first %s\n' % (len2, seq_type_name)) elif len1 < len2: differing += ('\nSecond %s contains %d additional ' 'elements.\n' % (seq_type_name, len2 - len1)) try: differing += ('First extra element %d:\n%s\n' % (len1, seq2[len1])) except (TypeError, IndexError, NotImplementedError): differing += ('Unable to index element %d ' 'of second %s\n' % (len1, seq_type_name)) standardMsg = differing diffMsg = '\n' + '\n'.join( difflib.ndiff(pprint.pformat(seq1).splitlines(), pprint.pformat(seq2).splitlines())) standardMsg = self._truncateMessage(standardMsg, diffMsg) msg = self._formatMessage(msg, standardMsg) self.fail(msg) def _truncateMessage(self, message, diff): max_diff = self.maxDiff if max_diff is None or len(diff) <= max_diff: return message + diff return message + (DIFF_OMITTED % len(diff)) def assertListEqual(self, list1, list2, msg=None): """A list-specific equality assertion. Args: list1: The first list to compare. list2: The second list to compare. msg: Optional message to use on failure instead of a list of differences. """ self.assertSequenceEqual(list1, list2, msg, seq_type=list) def assertTupleEqual(self, tuple1, tuple2, msg=None): """A tuple-specific equality assertion. Args: tuple1: The first tuple to compare. tuple2: The second tuple to compare. msg: Optional message to use on failure instead of a list of differences. """ self.assertSequenceEqual(tuple1, tuple2, msg, seq_type=tuple) def assertSetEqual(self, set1, set2, msg=None): """A set-specific equality assertion. Args: set1: The first set to compare. set2: The second set to compare. msg: Optional message to use on failure instead of a list of differences. assertSetEqual uses ducktyping to support different types of sets, and is optimized for sets specifically (parameters must support a difference method). """ try: difference1 = set1.difference(set2) except TypeError as e: self.fail('invalid type when attempting set difference: %s' % e) except AttributeError as e: self.fail('first argument does not support set difference: %s' % e) try: difference2 = set2.difference(set1) except TypeError as e: self.fail('invalid type when attempting set difference: %s' % e) except AttributeError as e: self.fail('second argument does not support set difference: %s' % e) if not (difference1 or difference2): return lines = [] if difference1: lines.append('Items in the first set but not the second:') for item in difference1: lines.append(repr(item)) if difference2: lines.append('Items in the second set but not the first:') for item in difference2: lines.append(repr(item)) standardMsg = '\n'.join(lines) self.fail(self._formatMessage(msg, standardMsg)) def assertIn(self, member, container, msg=None): """Just like self.assertTrue(a in b), but with a nicer default message.""" if member not in container: standardMsg = '%s not found in %s' % (safe_repr(member), safe_repr(container)) self.fail(self._formatMessage(msg, standardMsg)) def assertNotIn(self, member, container, msg=None): """Just like self.assertTrue(a not in b), but with a nicer default message.""" if member in container: standardMsg = '%s unexpectedly found in %s' % (safe_repr(member), safe_repr(container)) self.fail(self._formatMessage(msg, standardMsg)) def assertIs(self, expr1, expr2, msg=None): """Just like self.assertTrue(a is b), but with a nicer default message.""" if expr1 is not expr2: standardMsg = '%s is not %s' % (safe_repr(expr1), safe_repr(expr2)) self.fail(self._formatMessage(msg, standardMsg)) def assertIsNot(self, expr1, expr2, msg=None): """Just like self.assertTrue(a is not b), but with a nicer default message.""" if expr1 is expr2: standardMsg = 'unexpectedly identical: %s' % (safe_repr(expr1),) self.fail(self._formatMessage(msg, standardMsg)) def assertDictEqual(self, d1, d2, msg=None): self.assertIsInstance(d1, dict, 'First argument is not a dictionary') self.assertIsInstance(d2, dict, 'Second argument is not a dictionary') if d1 != d2: standardMsg = '%s != %s' % (safe_repr(d1, True), safe_repr(d2, True)) diff = ('\n' + '\n'.join(difflib.ndiff( pprint.pformat(d1).splitlines(), pprint.pformat(d2).splitlines()))) standardMsg = self._truncateMessage(standardMsg, diff) self.fail(self._formatMessage(msg, standardMsg)) def assertDictContainsSubset(self, subset, dictionary, msg=None): """Checks whether dictionary is a superset of subset.""" warnings.warn('assertDictContainsSubset is deprecated', DeprecationWarning) missing = [] mismatched = [] for key, value in subset.items(): if key not in dictionary: missing.append(key) elif value != dictionary[key]: mismatched.append('%s, expected: %s, actual: %s' % (safe_repr(key), safe_repr(value), safe_repr(dictionary[key]))) if not (missing or mismatched): return standardMsg = '' if missing: standardMsg = 'Missing: %s' % ','.join(safe_repr(m) for m in missing) if mismatched: if standardMsg: standardMsg += '; ' standardMsg += 'Mismatched values: %s' % ','.join(mismatched) self.fail(self._formatMessage(msg, standardMsg)) def assertCountEqual(self, first, second, msg=None): """An unordered sequence comparison asserting that the same elements, regardless of order. If the same element occurs more than once, it verifies that the elements occur the same number of times. self.assertEqual(Counter(list(first)), Counter(list(second))) Example: - [0, 1, 1] and [1, 0, 1] compare equal. - [0, 0, 1] and [0, 1] compare unequal. """ first_seq, second_seq = list(first), list(second) try: first = collections.Counter(first_seq) second = collections.Counter(second_seq) except TypeError: # Handle case with unhashable elements differences = _count_diff_all_purpose(first_seq, second_seq) else: if first == second: return differences = _count_diff_hashable(first_seq, second_seq) if differences: standardMsg = 'Element counts were not equal:\n' lines = ['First has %d, Second has %d: %r' % diff for diff in differences] diffMsg = '\n'.join(lines) standardMsg = self._truncateMessage(standardMsg, diffMsg) msg = self._formatMessage(msg, standardMsg) self.fail(msg) def assertMultiLineEqual(self, first, second, msg=None): """Assert that two multi-line strings are equal.""" self.assertIsInstance(first, str, 'First argument is not a string') self.assertIsInstance(second, str, 'Second argument is not a string') if first != second: # don't use difflib if the strings are too long if (len(first) > self._diffThreshold or len(second) > self._diffThreshold): self._baseAssertEqual(first, second, msg) firstlines = first.splitlines(keepends=True) secondlines = second.splitlines(keepends=True) if len(firstlines) == 1 and first.strip('\r\n') == first: firstlines = [first + '\n'] secondlines = [second + '\n'] standardMsg = '%s != %s' % (safe_repr(first, True), safe_repr(second, True)) diff = '\n' + ''.join(difflib.ndiff(firstlines, secondlines)) standardMsg = self._truncateMessage(standardMsg, diff) self.fail(self._formatMessage(msg, standardMsg)) def assertLess(self, a, b, msg=None): """Just like self.assertTrue(a < b), but with a nicer default message.""" if not a < b: standardMsg = '%s not less than %s' % (safe_repr(a), safe_repr(b)) self.fail(self._formatMessage(msg, standardMsg)) def assertLessEqual(self, a, b, msg=None): """Just like self.assertTrue(a <= b), but with a nicer default message.""" if not a <= b: standardMsg = '%s not less than or equal to %s' % (safe_repr(a), safe_repr(b)) self.fail(self._formatMessage(msg, standardMsg)) def assertGreater(self, a, b, msg=None): """Just like self.assertTrue(a > b), but with a nicer default message.""" if not a > b: standardMsg = '%s not greater than %s' % (safe_repr(a), safe_repr(b)) self.fail(self._formatMessage(msg, standardMsg)) def assertGreaterEqual(self, a, b, msg=None): """Just like self.assertTrue(a >= b), but with a nicer default message.""" if not a >= b: standardMsg = '%s not greater than or equal to %s' % (safe_repr(a), safe_repr(b)) self.fail(self._formatMessage(msg, standardMsg)) def assertIsNone(self, obj, msg=None): """Same as self.assertTrue(obj is None), with a nicer default message.""" if obj is not None: standardMsg = '%s is not None' % (safe_repr(obj),) self.fail(self._formatMessage(msg, standardMsg)) def assertIsNotNone(self, obj, msg=None): """Included for symmetry with assertIsNone.""" if obj is None: standardMsg = 'unexpectedly None' self.fail(self._formatMessage(msg, standardMsg)) def assertIsInstance(self, obj, cls, msg=None): """Same as self.assertTrue(isinstance(obj, cls)), with a nicer default message.""" if not isinstance(obj, cls): standardMsg = '%s is not an instance of %r' % (safe_repr(obj), cls) self.fail(self._formatMessage(msg, standardMsg)) def assertNotIsInstance(self, obj, cls, msg=None): """Included for symmetry with assertIsInstance.""" if isinstance(obj, cls): standardMsg = '%s is an instance of %r' % (safe_repr(obj), cls) self.fail(self._formatMessage(msg, standardMsg)) def assertRaisesRegex(self, expected_exception, expected_regex, callable_obj=None, *args, **kwargs): """Asserts that the message in a raised exception matches a regex. Args: expected_exception: Exception class expected to be raised. expected_regex: Regex (re pattern object or string) expected to be found in error message. callable_obj: Function to be called. msg: Optional message used in case of failure. Can only be used when assertRaisesRegex is used as a context manager. args: Extra args. kwargs: Extra kwargs. """ context = _AssertRaisesContext(expected_exception, self, callable_obj, expected_regex) return context.handle('assertRaisesRegex', callable_obj, args, kwargs) def assertWarnsRegex(self, expected_warning, expected_regex, callable_obj=None, *args, **kwargs): """Asserts that the message in a triggered warning matches a regexp. Basic functioning is similar to assertWarns() with the addition that only warnings whose messages also match the regular expression are considered successful matches. Args: expected_warning: Warning class expected to be triggered. expected_regex: Regex (re pattern object or string) expected to be found in error message. callable_obj: Function to be called. msg: Optional message used in case of failure. Can only be used when assertWarnsRegex is used as a context manager. args: Extra args. kwargs: Extra kwargs. """ context = _AssertWarnsContext(expected_warning, self, callable_obj, expected_regex) return context.handle('assertWarnsRegex', callable_obj, args, kwargs) def assertRegex(self, text, expected_regex, msg=None): """Fail the test unless the text matches the regular expression.""" if isinstance(expected_regex, (str, bytes)): assert expected_regex, "expected_regex must not be empty." expected_regex = re.compile(expected_regex) if not expected_regex.search(text): msg = msg or "Regex didn't match" msg = '%s: %r not found in %r' % (msg, expected_regex.pattern, text) raise self.failureException(msg) def assertNotRegex(self, text, unexpected_regex, msg=None): """Fail the test if the text matches the regular expression.""" if isinstance(unexpected_regex, (str, bytes)): unexpected_regex = re.compile(unexpected_regex) match = unexpected_regex.search(text) if match: msg = msg or "Regex matched" msg = '%s: %r matches %r in %r' % (msg, text[match.start():match.end()], unexpected_regex.pattern, text) raise self.failureException(msg) def _deprecate(original_func): def deprecated_func(*args, **kwargs): warnings.warn( 'Please use {0} instead.'.format(original_func.__name__), DeprecationWarning, 2) return original_func(*args, **kwargs) return deprecated_func # see #9424 failUnlessEqual = assertEquals = _deprecate(assertEqual) failIfEqual = assertNotEquals = _deprecate(assertNotEqual) failUnlessAlmostEqual = assertAlmostEquals = _deprecate(assertAlmostEqual) failIfAlmostEqual = assertNotAlmostEquals = _deprecate(assertNotAlmostEqual) failUnless = assert_ = _deprecate(assertTrue) failUnlessRaises = _deprecate(assertRaises) failIf = _deprecate(assertFalse) assertRaisesRegexp = _deprecate(assertRaisesRegex) assertRegexpMatches = _deprecate(assertRegex) class FunctionTestCase(TestCase): """A test case that wraps a test function. This is useful for slipping pre-existing test functions into the unittest framework. Optionally, set-up and tidy-up functions can be supplied. As with TestCase, the tidy-up ('tearDown') function will always be called if the set-up ('setUp') function ran successfully. """ def __init__(self, testFunc, setUp=None, tearDown=None, description=None): super(FunctionTestCase, self).__init__() self._setUpFunc = setUp self._tearDownFunc = tearDown self._testFunc = testFunc self._description = description def setUp(self): if self._setUpFunc is not None: self._setUpFunc() def tearDown(self): if self._tearDownFunc is not None: self._tearDownFunc() def runTest(self): self._testFunc() def id(self): return self._testFunc.__name__ def __eq__(self, other): if not isinstance(other, self.__class__): return NotImplemented return self._setUpFunc == other._setUpFunc and \ self._tearDownFunc == other._tearDownFunc and \ self._testFunc == other._testFunc and \ self._description == other._description def __ne__(self, other): return not self == other def __hash__(self): return hash((type(self), self._setUpFunc, self._tearDownFunc, self._testFunc, self._description)) def __str__(self): return "%s (%s)" % (strclass(self.__class__), self._testFunc.__name__) def __repr__(self): return "<%s tec=%s>" % (strclass(self.__class__), self._testFunc) def shortDescription(self): if self._description is not None: return self._description doc = self._testFunc.__doc__ return doc and doc.split("\n")[0].strip() or None
gpl-3.0
OscarES/serpentinetracker
visualize.py
1
14931
# Copyright 2009, Stephen Molloy # # This file is part of Serpentine. # # Serpentine 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. # # Serpentine 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 Serpentine. If not, see <http://www.gnu.org/licenses/>. # from matplotlib.path import Path from matplotlib.patches import PathPatch '''Module to control of the visualisation of beamline, beamrep and ...''' from matplotlib.patches import Rectangle import matplotlib.pyplot as plt import numpy as np from scipy import interpolate class Visualize(object) : def __init__(self) : '''Class to visualize numerical data as function of beamline distance "S" ''' self.xlim = None self.plotNames = [] self.axes = [] self.acb = None # from serpentine def PlotBPMReadings(self,so, formatstr='', classname='BPM'): """Plot the BPM readings from the most recent tracking operation""" readings = so.GetBPMReadings(classname) plt.plot(readings[0, :], readings[1, :], '-rx') plt.plot(readings[0, :], readings[2, :], '-xb') plt.ylabel('x/y / m') self.PostPlot("PlotBPMReadings") # From beamline def PlotRparam(self, so, param1=1, param2=1): """Plots the value of the R matrix element R[param1,param2] vs S Note that param1 and param2 use 'Matlab-style' indexing, rather than 'Python-style'. i.e. they can be any integer between 1 and 6 inclusive.""" spos = np.zeros(len(so.beamline)) rparam = np.ones(len(so.beamline)) for ele in so.beamline: spos[so.beamline.index(ele)] = ele.S rparam[so.beamline.index(ele)] = ele.R[param1-1, param2-1] plt.plot(spos, rparam, '-x') plt.ylabel('R_'+str(param1)+str(param2)) self.PostPlot("PlotRParam") # From beamline def PlotMomProfile(self, so, formatstr='-x'): """Plots the momentum profile of the reference particle""" spos, mom = so.beamline.GetMomProfile() plt.plot(spos, mom, formatstr) plt.ylabel('P / GeV/c') self.PostPlot("PlotMomProfile") # From beamline (get data from serpentine and beam line... ) def PlotEkProfile(self, so, formatstr='-x'): """Plots the kinetic energy profile of the reference particle""" spos, kenergy = so.beamline.GetEkProfile(so.beam_in.restmass) plt.plot(spos, kenergy, formatstr) self.PostPlot("PlotEkProfile") def PlotRFPhases(self, so): """Plots the RF phases of the AccCav objects in beamline.""" so.plot(so.beamline.GetRFPhases(), 'x') self.PostPlot("PlotRFPhases") # From beamline def PlotTwiss(self,so, betax=True, betay=True, spline=False) : """PlotTwiss(self, betax=True, betay=True, spline=False) Plot the twiss parameters. if betax: plot Beta_x versus S if betay: plot Beta_y versus S""" twiss_dict = so.beamline.GetTwiss() if betax : xarr = np.array(twiss_dict['S']) yarr = np.array(twiss_dict['betax']) if spline == False: plt.plot(xarr, yarr, '-bx') else : pass f= interpolate.InterpolatedUnivariateSpline(xarr,yarr,k=3) xarrp = np.linspace(xarr.min(),xarr.max(),1000) # plt.plot(xarrp,f(xarrp),'-kx') xstr = 'Beta_x / m ' plt.plot(xarr,yarr,'-bx',label='Beta_x') if betay : xarr = np.array(twiss_dict['S']) yarr = np.array(twiss_dict['betay']) if spline == False : plt.plot(xarr, yarr, '-rx') else : pass f= interpolate.InterpolatedUnivariateSpline(xarr,yarr,k=3) xarrp = np.linspace(xarr.min(),xarr.max(),1000) # plt.plot(xarrp,f(xarrp),'-kx') xstr = xstr + '& Beta_y / m' plt.plot(xarr,yarr,'-rx',label='Beta_y') plt.ylabel('beta_{x,y}') plt.legend(loc=0) self.PostPlot("PlotTwiss") def Matplotlib2D(self,so, projection='sx', options = '', labelmag = False, labeldiag = False) : '''Draw matplotlib representation of beamline. so : serpentine object (could be beamline) projection : 'sx','sy (no implemented yet' options : undefined as yet label : mark each element with its name return : none''' ##################################### # Draw beam line ##################################### bl_verticies = [] bl_codes = [] eheight = 0.025 # first point bl_codes.append(Path.MOVETO) bl_verticies.append((so.beamline[0].S,0)) for e in so.beamline[1:] : bl_codes.append(Path.LINETO) bl_verticies.append((e.S,0)) # last point bl_codes.append(Path.CLOSEPOLY) bl_verticies.append((so.beamline[-1].S,0)) # make path patch bl_verticies = np.array(bl_verticies,float) bl_path = Path(bl_verticies,bl_codes) bl_pathpatch = PathPatch(bl_path, facecolor='None', edgecolor = 'green') # plot and update axe = plt.gca() axe.add_patch(bl_pathpatch) axe.dataLim.update_from_data_xy(bl_verticies) axe.autoscale_view() # set ranges xmin = bl_verticies[:,0].min() xmax = bl_verticies[:,0].max() ymin = bl_verticies[:,1].min() ymax = bl_verticies[:,1].max() xdiff = xmax-xmin axe.set_xlim(xmin-0.05*xdiff,xmax+0.05*xdiff) axe.set_ylim(ymin-eheight*4.5,ymax+eheight*4.5) ##################################### # Draw beam elements ##################################### for e in so.beamline : # swtich on each element type textsloc = e.S+e.L/2.0 if e.__class__.__name__ == "Quad" : if e.B > 0 : rect = Rectangle((e.S,0),e.L,eheight) if labelmag : plt.text(textsloc,1.75*eheight,e.name,size=12, rotation=-90, ha="center",va="center", clip_on=True) else : rect = Rectangle((e.S,0),e.L,-eheight) if labelmag : plt.text(textsloc,-1.75*eheight,e.name,size=12, rotation=-90, ha="center",va="center", clip_on=True) axe.add_patch(rect) elif e.__class__.__name__ == "Sext" : if e.B > 0 : rect = Rectangle((e.S,0),e.L,eheight,facecolor='green') if labelmag : plt.text(textsloc,3.5*eheight,e.name,size=12, rotation=-90, ha="center",va="center", clip_on=True) else : rect = Rectangle((e.S,0),e.L,-eheight,facecolor='green') if labelmag : plt.text(textsloc,-3.5*eheight,e.name,size=12, rotation=-90, ha="center",va="center", clip_on=True) axe.add_patch(rect) elif e.__class__.__name__ == "Sbend" : rect = Rectangle((e.S,-eheight/2.0),e.L,eheight,facecolor='red') axe.add_patch(rect) if labelmag : plt.text(textsloc,3.5*eheight,e.name,size=12, rotation=-90, ha="center",va="center", clip_on=True) elif e.__class__.__name__ == "BasicDiag" : rect = Rectangle((e.S,-eheight/2.0),e.L,eheight,fill=False,ls='dashed') axe.add_patch(rect) if labeldiag : plt.text(textsloc,-3.5*eheight,e.name,size=12, rotation=-90, ha="center",va="center", clip_on=True) elif e.__class__.__name__ == "BPM" : rect = Rectangle((e.S,-eheight/2.0),e.L,eheight,fill=False,ls='dashed') axe.add_patch(rect) if labeldiag : plt.text(textsloc,-3.5*eheight,e.name,size=12, rotation=-90, ha="center",va="center", clip_on=True) elif e.__class__.__name__ == "Screen" : rect = Rectangle((e.S,-eheight/2.0),e.L,eheight,fill=False,ls='dashed') axe.add_patch(rect) if labeldiag : plt.text(textsloc,-3.5*eheight,e.name,size=12, rotation=-90, ha="center",va="center", clip_on=True) elif e.__class__.__name__ == "EmitScreen" : rect = Rectangle((e.S,-eheight/2.0),e.L,eheight,fill=False,ls='dashed') axe.add_patch(rect) if labeldiag : plt.text(textsloc,-3.5*eheight,e.name,size=12, rotation=-90, ha="center",va="center", clip_on=True) elif e.__class__.__name__ == "OTR" : rect = Rectangle((e.S,-eheight/2.0),e.L,eheight,fill=False,ls='dashed') axe.add_patch(rect) if labeldiag : plt.text(textsloc,-3.5*eheight,e.name,size=12, rotation=-90, ha="center",va="center", clip_on=True) elif e.__class__.__name__ == "ICT" : rect = Rectangle((e.S,-eheight/2.0),e.L,eheight,fill=False,ls='dashed') axe.add_patch(rect) if labeldiag : plt.text(textsloc,-3.5*eheight,e.name,size=12, rotation=-90, ha="center",va="center") elif e.__class__.__name__ == "Xcor" : pass elif e.__class__.__name__ == "Ycor" : pass # set axis labels etc axe.yaxis.set_ticklabels("") self.PostPlot("Matplotlib2D") def XAxesLabel(self) : plt.xlabel('S / m') def Update(self, cb=False) : """Update all axes limits from stored values""" for a in self.axes : if a != self.acb : a.set_xlim(self.xlim) plt.show() # loop over all figures # fnums = plt.get_fignums() # for f in fnums : # f = plt.figure(f) # loop over all subplots # for a in f.get_axes() : # if a != self.acb : # a.set_xlim(self.xlim) # elif cb == False : # remove callback make the change and then reinstall callback. # pass def PostPlot(self, plotName = '') : # keep list of plots self.plotNames.append(plotName) # if no limits set some if self.xlim == None : self.UpdateLimits() # apply consistent limits self.SetLimits() # keep axes for redrawing later self.AddAxes() # update all plots self.Update() def UpdateLimits(self) : """Get current plot limits and store locally""" a = plt.gca() self.xlim = a.get_xlim() print self.xlim def SetLimits(self) : """Set the visualisation limits from the current axis""" a = plt.gca() a.set_xlim(self.xlim) def AddAxes(self) : self.axes.append(plt.gca()) def ObserveAxes(self) : """Function to install axes change callback""" self.acb = plt.gca() self.acb.callbacks.connect('xlim_changed',self.CallbackUpdate) def CallbackUpdate(self,ra) : self.xlim = self.acb.get_xlim() self.Update(True) def VisualizeTestRecursion() : import visualize import elements import serpentine import beamline print 'visualize.VisualizeTestRecursion' # set twiss parameters mytwiss = elements.Twiss() mytwiss.betax = 6.85338806855804 mytwiss.alphax = 1.11230788371885 mytwiss.etax = 3.89188697330735e-012 mytwiss.etaxp = 63.1945125619190e-015 mytwiss.betay = 2.94129410712918 mytwiss.alphay = -1.91105724003646 mytwiss.etay = 0 mytwiss.etayp = 0 mytwiss.nemitx = 5.08807339588144e-006 mytwiss.nemity = 50.8807339588144e-009 mytwiss.sigz = 8.00000000000000e-003 mytwiss.sigP = 1.03999991965541e-003 mytwiss.pz_cor = 0 qf = elements.Quad("QF",L=0.25,P=1.25,B=5) dr1 = elements.Drift("D1",L=0.50,P=1.25) qd = elements.Quad("QD",L=0.25,P=1.25,B=-5) dr2 = elements.Drift("D2",L=0.5,P=1.25) m1 = elements.BasicDiag("M1",L=0.0) fodo = beamline.Line([qf,dr1,qd,dr2,m1]) fodo_sim = serpentine.Serpentine(line=fodo,twiss=mytwiss) vis = visualize.Visualize() plt.figure(1) plt.subplot(3,1,1) vis.Matplotlib2D(fodo_sim,labelmag=False, labeldiag=False) vis.ObserveAxes() plt.subplot(3,1,2) vis.PlotTwiss(fodo_sim) return fodo def VisualizeTestATF2() : import visualize import elements import serpentine import beamline print 'visualize.VisualizeTestATF2()' # set twiss parameters mytwiss = elements.Twiss() mytwiss.betax = 6.85338806855804 mytwiss.alphax = 1.11230788371885 mytwiss.etax = 3.89188697330735e-012 mytwiss.etaxp = 63.1945125619190e-015 mytwiss.betay = 2.94129410712918 mytwiss.alphay = -1.91105724003646 mytwiss.etay = 0 mytwiss.etayp = 0 mytwiss.nemitx = 5.08807339588144e-006 mytwiss.nemity = 50.8807339588144e-009 mytwiss.sigz = 8.00000000000000e-003 mytwiss.sigP = 1.03999991965541e-003 mytwiss.pz_cor = 0 # load beam line atfFull = serpentine.Serpentine(line='./examples/atf/newATF2lat.aml',twiss=mytwiss) atfExt = serpentine.Serpentine(line=beamline.Line(atfFull.beamline[947:]),twiss=mytwiss) # zero zero cors atfExt.beamline.ZeroCors() # Track atfExt.Track() readings = atfExt.GetBPMReadings() vis = visualize.Visualize() plt.figure(1) plt.subplot(3,1,1) vis.Matplotlib2D(atfExt,labelmag=False, labeldiag=False) vis.ObserveAxes() plt.subplot(3,1,2) vis.PlotTwiss(atfExt) plt.subplot(3,1,3) vis.PlotBPMReadings(atfExt,'b') vis.XAxesLabel() plt.figure(2) plt.subplot(3,1,1) vis.PlotRparam(atfExt,1,1) plt.subplot(3,1,2) vis.PlotRparam(atfExt,2,2) plt.subplot(3,1,3) vis.PlotMomProfile(atfExt) vis.XAxesLabel() return vis
gpl-3.0
fu3kingt3pe/spiderfoot
ext/dns/rdtypes/IN/AAAA.py
100
2186
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import dns.exception import dns.inet import dns.rdata import dns.tokenizer class AAAA(dns.rdata.Rdata): """AAAA record. @ivar address: an IPv6 address @type address: string (in the standard IPv6 format)""" __slots__ = ['address'] def __init__(self, rdclass, rdtype, address): super(AAAA, self).__init__(rdclass, rdtype) # check that it's OK junk = dns.inet.inet_pton(dns.inet.AF_INET6, address) self.address = address def to_text(self, origin=None, relativize=True, **kw): return self.address def from_text(cls, rdclass, rdtype, tok, origin = None, relativize = True): address = tok.get_identifier() tok.get_eol() return cls(rdclass, rdtype, address) from_text = classmethod(from_text) def to_wire(self, file, compress = None, origin = None): file.write(dns.inet.inet_pton(dns.inet.AF_INET6, self.address)) def from_wire(cls, rdclass, rdtype, wire, current, rdlen, origin = None): address = dns.inet.inet_ntop(dns.inet.AF_INET6, wire[current : current + rdlen]) return cls(rdclass, rdtype, address) from_wire = classmethod(from_wire) def _cmp(self, other): sa = dns.inet.inet_pton(dns.inet.AF_INET6, self.address) oa = dns.inet.inet_pton(dns.inet.AF_INET6, other.address) return cmp(sa, oa)
gpl-2.0
droodle/kansha
tests/test_security.py
2
7754
# -*- coding:utf-8 -*- #-- # Copyright (c) 2012-2014 Net-ng. # All rights reserved. # # This software is licensed under the BSD License, as described in # the file LICENSE.txt, which you should have received as part of # this distribution. #-- import unittest from nagare import database, i18n, security, component from nagare.namespaces import xhtml5 from sqlalchemy import MetaData from kansha.board import comp as board_module from kansha.board import boardsmanager from . import helpers from kansha.security import Unauthorized from elixir import metadata as __metadata__ database.set_metadata(__metadata__, 'sqlite:///:memory:', False, {}) class BoardTest(unittest.TestCase): def setUp(self): helpers.setup_db(__metadata__) self.boards_manager = boardsmanager.BoardsManager() def tearDown(self): helpers.teardown_db(__metadata__) def test_view_board_1(self): """Test security view board 1 Board Private User not logged """ helpers.set_dummy_context() # to be able to create board board = helpers.create_board() helpers.set_context() # real security manager for tests self.assertFalse(security.has_permissions('view', board)) def test_view_board_2(self): """Test security view board 2 Board Public User not logged """ helpers.set_dummy_context() # to be able to create board board = helpers.create_board() board.set_visibility(board_module.BOARD_PUBLIC) user = helpers.create_user('bis') helpers.set_context(user) self.assertTrue(security.has_permissions('view', board)) def test_view_board_3(self): """Test security view board 3 Board Private User logged but not member of the board """ helpers.set_dummy_context() # to be able to create board board = helpers.create_board() board.set_visibility(board_module.BOARD_PRIVATE) user = helpers.create_user('bis') helpers.set_context(user) self.assertFalse(security.has_permissions('view', board)) def test_view_board_4(self): """Test security view board 4 Board Private User member of the board """ helpers.set_dummy_context() # to be able to create board board = helpers.create_board() board.set_visibility(board_module.BOARD_PRIVATE) user = helpers.create_user('bis') helpers.set_context(user) data = board.data # don't collect data.members.append(user.data) self.assertTrue(security.has_permissions('view', board)) def test_view_board_5(self): """Test security view board 5 Board Public User member of the board """ helpers.set_dummy_context() # to be able to create board board = helpers.create_board() board.set_visibility(board_module.BOARD_PUBLIC) user = helpers.create_user('bis') helpers.set_context(user) data = board.data # don't collect data.members.append(user.data) self.assertTrue(security.has_permissions('view', board)) def test_rendering_security_view_board_1(self): """Test rendering security view board 1 Test rendering (Board private / user not logged) """ helpers.set_dummy_context() # to be able to create board board = helpers.create_board() board.set_visibility(board_module.BOARD_PRIVATE) helpers.set_context() with self.assertRaises(Unauthorized): component.Component(board).render(xhtml5.Renderer()) def test_rendering_security_view_board_2(self): """Test rendering security view board 2 Test rendering (Board private / user member) """ helpers.set_dummy_context() # to be able to create board board = helpers.create_board() board.set_visibility(board_module.BOARD_PRIVATE) user = helpers.create_user('bis') helpers.set_context(user) data = board.data # don't collect data.members.append(user.data) with i18n.Locale('en', 'US'): component.Component(board).render(xhtml5.Renderer()) def test_rendering_security_view_board_3(self): """Test rendering security view board 3 Test rendering (Board public / user not logged) """ helpers.set_dummy_context() # for board creation board = helpers.create_board() helpers.set_context() # for realistic security check board.set_visibility(board_module.BOARD_PUBLIC) with i18n.Locale('en', 'US'): component.Component(board).render(xhtml5.Renderer()) def test_vote_card_1(self): """Test security vote card 1 Board PUBLIC/Vote PUBLIC User not logged """ helpers.set_dummy_context() board = helpers.create_board() board.set_visibility(board_module.BOARD_PUBLIC) board.allow_votes(board_module.VOTES_PUBLIC) helpers.set_context() with self.assertRaises(Unauthorized): board.columns[0]().cards[0]().votes().vote() def test_vote_card_2(self): """Test security vote card 2 Board PUBLIC/Vote PUBLIC User logged """ helpers.set_dummy_context() board = helpers.create_board() board.set_visibility(board_module.BOARD_PUBLIC) board.allow_votes(board_module.VOTES_PUBLIC) user = helpers.create_user('bis') helpers.set_context(user) board.columns[0]().cards[0]().votes().vote() def test_vote_card_3(self): """Test security vote card 3 Board PRIVATE/Vote MEMBERS User logged """ helpers.set_dummy_context() board = helpers.create_board() board.set_visibility(board_module.BOARD_PRIVATE) board.allow_votes(board_module.VOTES_MEMBERS) user = helpers.create_user('bis') helpers.set_context(user) with self.assertRaises(Unauthorized): board.columns[0]().cards[0]().votes().vote() def test_vote_card_4(self): """Test security vote card 4 Board PRIVATE/Vote MEMBERS User member """ helpers.set_dummy_context() board = helpers.create_board() board.set_visibility(board_module.BOARD_PRIVATE) board.allow_votes(board_module.VOTES_MEMBERS) user = helpers.create_user('bis') helpers.set_context(user) data = board.data # don't collect data.members.append(user.data) board.columns[0]().cards[0]().votes().vote() def test_vote_card_5(self): """Test security vote card 5 Board PUBLIC/Vote OFF User member """ helpers.set_dummy_context() board = helpers.create_board() board.set_visibility(board_module.BOARD_PUBLIC) board.allow_votes(board_module.VOTES_OFF) user = helpers.create_user('bis') helpers.set_context(user) data = board.data # don't collect data.members.append(user.data) with self.assertRaises(Unauthorized): board.columns[0]().cards[0]().votes().vote() def test_vote_card_6(self): """Test security vote card 6 Board PUBLIC/Vote OFF User logged """ helpers.set_dummy_context() board = helpers.create_board() board.set_visibility(board_module.BOARD_PUBLIC) board.allow_votes(board_module.VOTES_OFF) user = helpers.create_user('bis') helpers.set_context(user) with self.assertRaises(Unauthorized): board.columns[0]().cards[0]().votes().vote()
bsd-3-clause
pepevalbe/ardupilot
mk/PX4/Tools/genmsg/test/test_genmsg_command_line.py
216
1937
# Software License Agreement (BSD License) # # Copyright (c) 2011, Willow Garage, 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 Willow Garage, 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. def test_includepath_to_dict(): from genmsg.command_line import includepath_to_dict assert {} == includepath_to_dict([]) assert {'std_msgs': [ 'foo' ]} == includepath_to_dict(['std_msgs:foo']) assert {'std_msgs': [ 'foo' ], 'bar_msgs': [ 'baz:colon' ]} == includepath_to_dict(['std_msgs:foo', 'bar_msgs:baz:colon'])
gpl-3.0
c0710204/edx-platform
common/lib/xmodule/xmodule/tests/test_video.py
8
24664
# -*- coding: utf-8 -*- # pylint: disable=W0212 """Test for Video Xmodule functional logic. These test data read from xml, not from mongo. We have a ModuleStoreTestCase class defined in common/lib/xmodule/xmodule/modulestore/tests/django_utils.py. You can search for usages of this in the cms and lms tests for examples. You use this so that it will do things like point the modulestore setting to mongo, flush the contentstore before and after, load the templates, etc. You can then use the CourseFactory and XModuleItemFactory as defined in common/lib/xmodule/xmodule/modulestore/tests/factories.py to create the course, section, subsection, unit, etc. """ import unittest import datetime from mock import Mock, patch from . import LogicTest from lxml import etree from opaque_keys.edx.locations import SlashSeparatedCourseKey from xmodule.video_module import VideoDescriptor, create_youtube_string, get_video_from_cdn from .test_import import DummySystem from xblock.field_data import DictFieldData from xblock.fields import ScopeIds from xmodule.tests import get_test_descriptor_system def instantiate_descriptor(**field_data): """ Instantiate descriptor with most properties. """ system = get_test_descriptor_system() course_key = SlashSeparatedCourseKey('org', 'course', 'run') usage_key = course_key.make_usage_key('video', 'SampleProblem') return system.construct_xblock_from_class( VideoDescriptor, scope_ids=ScopeIds(None, None, usage_key, usage_key), field_data=DictFieldData(field_data), ) class VideoModuleTest(LogicTest): """Logic tests for Video Xmodule.""" descriptor_class = VideoDescriptor raw_field_data = { 'data': '<video />' } def test_parse_youtube(self): """Test parsing old-style Youtube ID strings into a dict.""" youtube_str = '0.75:jNCf2gIqpeE,1.00:ZwkTiUPN0mg,1.25:rsq9auxASqI,1.50:kMyNdzVHHgg' output = VideoDescriptor._parse_youtube(youtube_str) self.assertEqual(output, {'0.75': 'jNCf2gIqpeE', '1.00': 'ZwkTiUPN0mg', '1.25': 'rsq9auxASqI', '1.50': 'kMyNdzVHHgg'}) def test_parse_youtube_one_video(self): """ Ensure that all keys are present and missing speeds map to the empty string. """ youtube_str = '0.75:jNCf2gIqpeE' output = VideoDescriptor._parse_youtube(youtube_str) self.assertEqual(output, {'0.75': 'jNCf2gIqpeE', '1.00': '', '1.25': '', '1.50': ''}) def test_parse_youtube_invalid(self): """Ensure that ids that are invalid return an empty dict""" # invalid id youtube_str = 'thisisaninvalidid' output = VideoDescriptor._parse_youtube(youtube_str) self.assertEqual(output, {'0.75': '', '1.00': '', '1.25': '', '1.50': ''}) # another invalid id youtube_str = ',::,:,,' output = VideoDescriptor._parse_youtube(youtube_str) self.assertEqual(output, {'0.75': '', '1.00': '', '1.25': '', '1.50': ''}) # and another one, partially invalid youtube_str = '0.75_BAD!!!,1.0:AXdE34_U,1.25:KLHF9K_Y,1.5:VO3SxfeD,' output = VideoDescriptor._parse_youtube(youtube_str) self.assertEqual(output, {'0.75': '', '1.00': 'AXdE34_U', '1.25': 'KLHF9K_Y', '1.50': 'VO3SxfeD'}) def test_parse_youtube_key_format(self): """ Make sure that inconsistent speed keys are parsed correctly. """ youtube_str = '1.00:p2Q6BrNhdh8' youtube_str_hack = '1.0:p2Q6BrNhdh8' self.assertEqual( VideoDescriptor._parse_youtube(youtube_str), VideoDescriptor._parse_youtube(youtube_str_hack) ) def test_parse_youtube_empty(self): """ Some courses have empty youtube attributes, so we should handle that well. """ self.assertEqual( VideoDescriptor._parse_youtube(''), {'0.75': '', '1.00': '', '1.25': '', '1.50': ''} ) class VideoDescriptorTestBase(unittest.TestCase): """ Base class for tests for VideoDescriptor """ def setUp(self): self.descriptor = instantiate_descriptor() class TestCreateYoutubeString(VideoDescriptorTestBase): """ Checks that create_youtube_string correcty extracts information from Video descriptor. """ def test_create_youtube_string(self): """ Test that Youtube ID strings are correctly created when writing back out to XML. """ self.descriptor.youtube_id_0_75 = 'izygArpw-Qo' self.descriptor.youtube_id_1_0 = 'p2Q6BrNhdh8' self.descriptor.youtube_id_1_25 = '1EeWXzPdhSA' self.descriptor.youtube_id_1_5 = 'rABDYkeK0x8' expected = "0.75:izygArpw-Qo,1.00:p2Q6BrNhdh8,1.25:1EeWXzPdhSA,1.50:rABDYkeK0x8" self.assertEqual(create_youtube_string(self.descriptor), expected) def test_create_youtube_string_missing(self): """ Test that Youtube IDs which aren't explicitly set aren't included in the output string. """ self.descriptor.youtube_id_0_75 = 'izygArpw-Qo' self.descriptor.youtube_id_1_0 = 'p2Q6BrNhdh8' self.descriptor.youtube_id_1_25 = '1EeWXzPdhSA' expected = "0.75:izygArpw-Qo,1.00:p2Q6BrNhdh8,1.25:1EeWXzPdhSA" self.assertEqual(create_youtube_string(self.descriptor), expected) class VideoDescriptorImportTestCase(unittest.TestCase): """ Make sure that VideoDescriptor can import an old XML-based video correctly. """ def assert_attributes_equal(self, video, attrs): """ Assert that `video` has the correct attributes. `attrs` is a map of {metadata_field: value}. """ for key, value in attrs.items(): self.assertEquals(getattr(video, key), value) def test_constructor(self): sample_xml = ''' <video display_name="Test Video" youtube="1.0:p2Q6BrNhdh8,0.75:izygArpw-Qo,1.25:1EeWXzPdhSA,1.5:rABDYkeK0x8" show_captions="false" download_track="true" download_video="true" start_time="00:00:01" end_time="00:01:00"> <source src="http://www.example.com/source.mp4"/> <source src="http://www.example.com/source.ogg"/> <track src="http://www.example.com/track"/> <handout src="http://www.example.com/handout"/> <transcript language="ua" src="ukrainian_translation.srt" /> <transcript language="ge" src="german_translation.srt" /> </video> ''' descriptor = instantiate_descriptor(data=sample_xml) self.assert_attributes_equal(descriptor, { 'youtube_id_0_75': 'izygArpw-Qo', 'youtube_id_1_0': 'p2Q6BrNhdh8', 'youtube_id_1_25': '1EeWXzPdhSA', 'youtube_id_1_5': 'rABDYkeK0x8', 'download_video': True, 'show_captions': False, 'start_time': datetime.timedelta(seconds=1), 'end_time': datetime.timedelta(seconds=60), 'track': 'http://www.example.com/track', 'handout': 'http://www.example.com/handout', 'download_track': True, 'html5_sources': ['http://www.example.com/source.mp4', 'http://www.example.com/source.ogg'], 'data': '', 'transcripts': {'ua': 'ukrainian_translation.srt', 'ge': 'german_translation.srt'} }) def test_from_xml(self): module_system = DummySystem(load_error_modules=True) xml_data = ''' <video display_name="Test Video" youtube="1.0:p2Q6BrNhdh8,0.75:izygArpw-Qo,1.25:1EeWXzPdhSA,1.5:rABDYkeK0x8" show_captions="false" download_track="false" start_time="00:00:01" download_video="false" end_time="00:01:00"> <source src="http://www.example.com/source.mp4"/> <track src="http://www.example.com/track"/> <handout src="http://www.example.com/handout"/> <transcript language="uk" src="ukrainian_translation.srt" /> <transcript language="de" src="german_translation.srt" /> </video> ''' output = VideoDescriptor.from_xml(xml_data, module_system, Mock()) self.assert_attributes_equal(output, { 'youtube_id_0_75': 'izygArpw-Qo', 'youtube_id_1_0': 'p2Q6BrNhdh8', 'youtube_id_1_25': '1EeWXzPdhSA', 'youtube_id_1_5': 'rABDYkeK0x8', 'show_captions': False, 'start_time': datetime.timedelta(seconds=1), 'end_time': datetime.timedelta(seconds=60), 'track': 'http://www.example.com/track', 'handout': 'http://www.example.com/handout', 'download_track': False, 'download_video': False, 'html5_sources': ['http://www.example.com/source.mp4'], 'data': '', 'transcripts': {'uk': 'ukrainian_translation.srt', 'de': 'german_translation.srt'}, }) def test_from_xml_missing_attributes(self): """ Ensure that attributes have the right values if they aren't explicitly set in XML. """ module_system = DummySystem(load_error_modules=True) xml_data = ''' <video display_name="Test Video" youtube="1.0:p2Q6BrNhdh8,1.25:1EeWXzPdhSA" show_captions="true"> <source src="http://www.example.com/source.mp4"/> </video> ''' output = VideoDescriptor.from_xml(xml_data, module_system, Mock()) self.assert_attributes_equal(output, { 'youtube_id_0_75': '', 'youtube_id_1_0': 'p2Q6BrNhdh8', 'youtube_id_1_25': '1EeWXzPdhSA', 'youtube_id_1_5': '', 'show_captions': True, 'start_time': datetime.timedelta(seconds=0.0), 'end_time': datetime.timedelta(seconds=0.0), 'track': '', 'handout': None, 'download_track': False, 'download_video': True, 'html5_sources': ['http://www.example.com/source.mp4'], 'data': '' }) def test_from_xml_missing_download_track(self): """ Ensure that attributes have the right values if they aren't explicitly set in XML. """ module_system = DummySystem(load_error_modules=True) xml_data = ''' <video display_name="Test Video" youtube="1.0:p2Q6BrNhdh8,1.25:1EeWXzPdhSA" show_captions="true"> <source src="http://www.example.com/source.mp4"/> <track src="http://www.example.com/track"/> </video> ''' output = VideoDescriptor.from_xml(xml_data, module_system, Mock()) self.assert_attributes_equal(output, { 'youtube_id_0_75': '', 'youtube_id_1_0': 'p2Q6BrNhdh8', 'youtube_id_1_25': '1EeWXzPdhSA', 'youtube_id_1_5': '', 'show_captions': True, 'start_time': datetime.timedelta(seconds=0.0), 'end_time': datetime.timedelta(seconds=0.0), 'track': 'http://www.example.com/track', 'download_track': True, 'download_video': True, 'html5_sources': ['http://www.example.com/source.mp4'], 'data': '', 'transcripts': {}, }) def test_from_xml_no_attributes(self): """ Make sure settings are correct if none are explicitly set in XML. """ module_system = DummySystem(load_error_modules=True) xml_data = '<video></video>' output = VideoDescriptor.from_xml(xml_data, module_system, Mock()) self.assert_attributes_equal(output, { 'youtube_id_0_75': '', 'youtube_id_1_0': 'OEoXaMPEzfM', 'youtube_id_1_25': '', 'youtube_id_1_5': '', 'show_captions': True, 'start_time': datetime.timedelta(seconds=0.0), 'end_time': datetime.timedelta(seconds=0.0), 'track': '', 'handout': None, 'download_track': False, 'download_video': False, 'html5_sources': [], 'data': '', 'transcripts': {}, }) def test_from_xml_double_quotes(self): """ Make sure we can handle the double-quoted string format (which was used for exporting for a few weeks). """ module_system = DummySystem(load_error_modules=True) xml_data = ''' <video display_name="&quot;display_name&quot;" html5_sources="[&quot;source_1&quot;, &quot;source_2&quot;]" show_captions="false" download_video="true" sub="&quot;html5_subtitles&quot;" track="&quot;http://www.example.com/track&quot;" handout="&quot;http://www.example.com/handout&quot;" download_track="true" youtube_id_0_75="&quot;OEoXaMPEzf65&quot;" youtube_id_1_25="&quot;OEoXaMPEzf125&quot;" youtube_id_1_5="&quot;OEoXaMPEzf15&quot;" youtube_id_1_0="&quot;OEoXaMPEzf10&quot;" /> ''' output = VideoDescriptor.from_xml(xml_data, module_system, Mock()) self.assert_attributes_equal(output, { 'youtube_id_0_75': 'OEoXaMPEzf65', 'youtube_id_1_0': 'OEoXaMPEzf10', 'youtube_id_1_25': 'OEoXaMPEzf125', 'youtube_id_1_5': 'OEoXaMPEzf15', 'show_captions': False, 'start_time': datetime.timedelta(seconds=0.0), 'end_time': datetime.timedelta(seconds=0.0), 'track': 'http://www.example.com/track', 'handout': 'http://www.example.com/handout', 'download_track': True, 'download_video': True, 'html5_sources': ["source_1", "source_2"], 'data': '' }) def test_from_xml_double_quote_concatenated_youtube(self): module_system = DummySystem(load_error_modules=True) xml_data = ''' <video display_name="Test Video" youtube="1.0:&quot;p2Q6BrNhdh8&quot;,1.25:&quot;1EeWXzPdhSA&quot;"> </video> ''' output = VideoDescriptor.from_xml(xml_data, module_system, Mock()) self.assert_attributes_equal(output, { 'youtube_id_0_75': '', 'youtube_id_1_0': 'p2Q6BrNhdh8', 'youtube_id_1_25': '1EeWXzPdhSA', 'youtube_id_1_5': '', 'show_captions': True, 'start_time': datetime.timedelta(seconds=0.0), 'end_time': datetime.timedelta(seconds=0.0), 'track': '', 'handout': None, 'download_track': False, 'download_video': False, 'html5_sources': [], 'data': '' }) def test_old_video_format(self): """ Test backwards compatibility with VideoModule's XML format. """ module_system = DummySystem(load_error_modules=True) xml_data = """ <video display_name="Test Video" youtube="1.0:p2Q6BrNhdh8,0.75:izygArpw-Qo,1.25:1EeWXzPdhSA,1.5:rABDYkeK0x8" show_captions="false" source="http://www.example.com/source.mp4" from="00:00:01" to="00:01:00"> <source src="http://www.example.com/source.mp4"/> <track src="http://www.example.com/track"/> </video> """ output = VideoDescriptor.from_xml(xml_data, module_system, Mock()) self.assert_attributes_equal(output, { 'youtube_id_0_75': 'izygArpw-Qo', 'youtube_id_1_0': 'p2Q6BrNhdh8', 'youtube_id_1_25': '1EeWXzPdhSA', 'youtube_id_1_5': 'rABDYkeK0x8', 'show_captions': False, 'start_time': datetime.timedelta(seconds=1), 'end_time': datetime.timedelta(seconds=60), 'track': 'http://www.example.com/track', # 'download_track': True, 'html5_sources': ['http://www.example.com/source.mp4'], 'data': '', }) def test_old_video_data(self): """ Ensure that Video is able to read VideoModule's model data. """ module_system = DummySystem(load_error_modules=True) xml_data = """ <video display_name="Test Video" youtube="1.0:p2Q6BrNhdh8,0.75:izygArpw-Qo,1.25:1EeWXzPdhSA,1.5:rABDYkeK0x8" show_captions="false" from="00:00:01" to="00:01:00"> <source src="http://www.example.com/source.mp4"/> <track src="http://www.example.com/track"/> </video> """ video = VideoDescriptor.from_xml(xml_data, module_system, Mock()) self.assert_attributes_equal(video, { 'youtube_id_0_75': 'izygArpw-Qo', 'youtube_id_1_0': 'p2Q6BrNhdh8', 'youtube_id_1_25': '1EeWXzPdhSA', 'youtube_id_1_5': 'rABDYkeK0x8', 'show_captions': False, 'start_time': datetime.timedelta(seconds=1), 'end_time': datetime.timedelta(seconds=60), 'track': 'http://www.example.com/track', # 'download_track': True, 'html5_sources': ['http://www.example.com/source.mp4'], 'data': '' }) def test_import_with_float_times(self): """ Ensure that Video is able to read VideoModule's model data. """ module_system = DummySystem(load_error_modules=True) xml_data = """ <video display_name="Test Video" youtube="1.0:p2Q6BrNhdh8,0.75:izygArpw-Qo,1.25:1EeWXzPdhSA,1.5:rABDYkeK0x8" show_captions="false" from="1.0" to="60.0"> <source src="http://www.example.com/source.mp4"/> <track src="http://www.example.com/track"/> </video> """ video = VideoDescriptor.from_xml(xml_data, module_system, Mock()) self.assert_attributes_equal(video, { 'youtube_id_0_75': 'izygArpw-Qo', 'youtube_id_1_0': 'p2Q6BrNhdh8', 'youtube_id_1_25': '1EeWXzPdhSA', 'youtube_id_1_5': 'rABDYkeK0x8', 'show_captions': False, 'start_time': datetime.timedelta(seconds=1), 'end_time': datetime.timedelta(seconds=60), 'track': 'http://www.example.com/track', # 'download_track': True, 'html5_sources': ['http://www.example.com/source.mp4'], 'data': '' }) class VideoExportTestCase(VideoDescriptorTestBase): """ Make sure that VideoDescriptor can export itself to XML correctly. """ def assertXmlEqual(self, expected, xml): for attr in ['tag', 'attrib', 'text', 'tail']: self.assertEqual(getattr(expected, attr), getattr(xml, attr)) for left, right in zip(expected, xml): self.assertXmlEqual(left, right) def test_export_to_xml(self): """ Test that we write the correct XML on export. """ self.descriptor.youtube_id_0_75 = 'izygArpw-Qo' self.descriptor.youtube_id_1_0 = 'p2Q6BrNhdh8' self.descriptor.youtube_id_1_25 = '1EeWXzPdhSA' self.descriptor.youtube_id_1_5 = 'rABDYkeK0x8' self.descriptor.show_captions = False self.descriptor.start_time = datetime.timedelta(seconds=1.0) self.descriptor.end_time = datetime.timedelta(seconds=60) self.descriptor.track = 'http://www.example.com/track' self.descriptor.handout = 'http://www.example.com/handout' self.descriptor.download_track = True self.descriptor.html5_sources = ['http://www.example.com/source.mp4', 'http://www.example.com/source.ogg'] self.descriptor.download_video = True self.descriptor.transcripts = {'ua': 'ukrainian_translation.srt', 'ge': 'german_translation.srt'} xml = self.descriptor.definition_to_xml(None) # We don't use the `resource_fs` parameter expected = etree.fromstring('''\ <video url_name="SampleProblem" start_time="0:00:01" youtube="0.75:izygArpw-Qo,1.00:p2Q6BrNhdh8,1.25:1EeWXzPdhSA,1.50:rABDYkeK0x8" show_captions="false" end_time="0:01:00" download_video="true" download_track="true"> <source src="http://www.example.com/source.mp4"/> <source src="http://www.example.com/source.ogg"/> <track src="http://www.example.com/track"/> <handout src="http://www.example.com/handout"/> <transcript language="ge" src="german_translation.srt" /> <transcript language="ua" src="ukrainian_translation.srt" /> </video> ''') self.assertXmlEqual(expected, xml) def test_export_to_xml_empty_end_time(self): """ Test that we write the correct XML on export. """ self.descriptor.youtube_id_0_75 = 'izygArpw-Qo' self.descriptor.youtube_id_1_0 = 'p2Q6BrNhdh8' self.descriptor.youtube_id_1_25 = '1EeWXzPdhSA' self.descriptor.youtube_id_1_5 = 'rABDYkeK0x8' self.descriptor.show_captions = False self.descriptor.start_time = datetime.timedelta(seconds=5.0) self.descriptor.end_time = datetime.timedelta(seconds=0.0) self.descriptor.track = 'http://www.example.com/track' self.descriptor.download_track = True self.descriptor.html5_sources = ['http://www.example.com/source.mp4', 'http://www.example.com/source.ogg'] self.descriptor.download_video = True xml = self.descriptor.definition_to_xml(None) # We don't use the `resource_fs` parameter expected = etree.fromstring('''\ <video url_name="SampleProblem" start_time="0:00:05" youtube="0.75:izygArpw-Qo,1.00:p2Q6BrNhdh8,1.25:1EeWXzPdhSA,1.50:rABDYkeK0x8" show_captions="false" download_video="true" download_track="true"> <source src="http://www.example.com/source.mp4"/> <source src="http://www.example.com/source.ogg"/> <track src="http://www.example.com/track"/> </video> ''') self.assertXmlEqual(expected, xml) def test_export_to_xml_empty_parameters(self): """ Test XML export with defaults. """ xml = self.descriptor.definition_to_xml(None) # Check that download_video field is also set to default (False) in xml for backward compatibility expected = '<video url_name="SampleProblem" download_video="false"/>\n' self.assertEquals(expected, etree.tostring(xml, pretty_print=True)) class VideoCdnTest(unittest.TestCase): """ Tests for Video CDN. """ @patch('requests.get') def test_get_video_success(self, cdn_response): """ Test successful CDN request. """ original_video_url = "http://www.original_video.com/original_video.mp4" cdn_response_video_url = "http://www.cdn_video.com/cdn_video.mp4" cdn_response_content = '{{"sources":["{cdn_url}"]}}'.format(cdn_url=cdn_response_video_url) cdn_response.return_value=Mock(status_code=200, content=cdn_response_content) fake_cdn_url = 'http://fake_cdn.com/' self.assertEqual( get_video_from_cdn(fake_cdn_url, original_video_url), cdn_response_video_url ) @patch('requests.get') def test_get_no_video_exists(self, cdn_response): """ Test if no alternative video in CDN exists. """ original_video_url = "http://www.original_video.com/original_video.mp4" cdn_response.return_value=Mock(status_code=404) fake_cdn_url = 'http://fake_cdn.com/' self.assertIsNone(get_video_from_cdn(fake_cdn_url, original_video_url))
agpl-3.0
Donkyhotay/MoonPy
zope/schema/tests/test_listfield.py
1
4559
############################################################################## # # Copyright (c) 2001, 2002 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """List field tests $Id: test_listfield.py 69144 2006-07-16 15:10:16Z jim $ """ from unittest import main, makeSuite from zope.interface import implements from zope.schema import Field, List, Int from zope.schema.interfaces import IField from zope.schema.interfaces import ICollection, ISequence, IList from zope.schema.interfaces import NotAContainer, RequiredMissing from zope.schema.interfaces import WrongContainedType, WrongType, NotUnique from zope.schema.interfaces import TooShort, TooLong from zope.schema.tests.test_field import CollectionFieldTestBase class ListTest(CollectionFieldTestBase): """Test the List Field.""" _Field_Factory = List def testValidate(self): field = List(title=u'List field', description=u'', readonly=False, required=False) field.validate(None) field.validate([]) field.validate([1, 2]) field.validate([3,]) def testValidateRequired(self): field = List(title=u'List field', description=u'', readonly=False, required=True) field.validate([]) field.validate([1, 2]) field.validate([3,]) self.assertRaises(RequiredMissing, field.validate, None) def testValidateMinValues(self): field = List(title=u'List field', description=u'', readonly=False, required=False, min_length=2) field.validate(None) field.validate([1, 2]) field.validate([1, 2, 3]) self.assertRaises(TooShort, field.validate, []) self.assertRaises(TooShort, field.validate, [1,]) def testValidateMaxValues(self): field = List(title=u'List field', description=u'', readonly=False, required=False, max_length=2) field.validate(None) field.validate([]) field.validate([1, 2]) self.assertRaises(TooLong, field.validate, [1, 2, 3, 4]) self.assertRaises(TooLong, field.validate, [1, 2, 3]) def testValidateMinValuesAndMaxValues(self): field = List(title=u'List field', description=u'', readonly=False, required=False, min_length=1, max_length=2) field.validate(None) field.validate([1, ]) field.validate([1, 2]) self.assertRaises(TooShort, field.validate, []) self.assertRaises(TooLong, field.validate, [1, 2, 3]) def testValidateValueTypes(self): field = List(title=u'List field', description=u'', readonly=False, required=False, value_type=Int()) field.validate(None) field.validate([5,]) field.validate([2, 3]) self.assertRaises(WrongContainedType, field.validate, ['',] ) self.assertRaises(WrongContainedType, field.validate, [3.14159,] ) def testCorrectValueType(self): # TODO: We should not allow for a None valeu type. List(value_type=None) # do not allow arbitrary value types self.assertRaises(ValueError, List, value_type=object()) self.assertRaises(ValueError, List, value_type=Field) # however, allow anything that implements IField List(value_type=Field()) class FakeField(object): implements(IField) List(value_type=FakeField()) def testUnique(self): field = self._Field_Factory(title=u'test field', description=u'', readonly=False, required=True, unique=True) field.validate([1, 2]) self.assertRaises(NotUnique, field.validate, [1, 2, 1]) def testImplements(self): field = List() self.failUnless(IList.providedBy(field)) self.failUnless(ISequence.providedBy(field)) self.failUnless(ICollection.providedBy(field)) def test_suite(): return makeSuite(ListTest) if __name__ == '__main__': main(defaultTest='test_suite')
gpl-3.0
linkedin/simoorg
src/simoorg/plugins/handler/BaseHandler.py
8
1340
# # Copyright 2015 LinkedIn Corp. 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. # """ The base class for all the handler plugins """ class BaseHandler(object): """ Base handler class""" def __init__(self, config_dir, target, logger_instance=None, verbose=True): """ BaseHandler Constructor """ pass def authenticate(self): """ If the handler requires any authentication, those steps Should be included in this function """ pass def execute_command(self): """ This method should read the custom log output and return it to the caller, Also Expected to return a tuple of three values, namely. Execution Status, Output and Error message """ pass def load_config(self): """ Method to load any required configs """ pass
apache-2.0
rmfitzpatrick/ansible
lib/ansible/modules/storage/infinidat/infini_export.py
29
5157
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2016, Gregory Shulov (gregory.shulov@gmail.com) # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: infini_export version_added: 2.3 short_description: Create, Delete or Modify NFS Exports on Infinibox description: - This module creates, deletes or modifies NFS exports on Infinibox. author: Gregory Shulov (@GR360RY) options: name: description: - Export name. Should always start with C(/). (ex. name=/data) aliases: ['export', 'path'] required: true state: description: - Creates/Modifies export when present and removes when absent. required: false default: "present" choices: [ "present", "absent" ] inner_path: description: - Internal path of the export. default: "/" client_list: description: - List of dictionaries with client entries. See examples. Check infini_export_client module to modify individual NFS client entries for export. default: "All Hosts(*), RW, no_root_squash: True" required: false filesystem: description: - Name of exported file system. required: true extends_documentation_fragment: - infinibox requirements: - munch ''' EXAMPLES = ''' - name: Export bar filesystem under foo pool as /data infini_export: name: /data01 filesystem: foo user: admin password: secret system: ibox001 - name: Export and specify client list explicitly infini_export: name: /data02 filesystem: foo client_list: - client: 192.168.0.2 access: RW no_root_squash: True - client: 192.168.0.100 access: RO no_root_squash: False - client: 192.168.0.10-192.168.0.20 access: RO no_root_squash: False system: ibox001 user: admin password: secret ''' RETURN = ''' ''' try: from munch import unmunchify HAS_MUNCH = True except ImportError: HAS_MUNCH = False from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.infinibox import HAS_INFINISDK, api_wrapper, get_system, infinibox_argument_spec def transform(d): return frozenset(d.items()) @api_wrapper def get_filesystem(module, system): """Return Filesystem or None""" try: return system.filesystems.get(name=module.params['filesystem']) except: return None @api_wrapper def get_export(module, filesystem, system): """Retrun export if found. When not found return None""" export = None exports_to_list = system.exports.to_list() for e in exports_to_list: if e.get_export_path() == module.params['name']: export = e break return export @api_wrapper def update_export(module, export, filesystem, system): """ Create new filesystem or update existing one""" changed = False name = module.params['name'] client_list = module.params['client_list'] if export is None: if not module.check_mode: export = system.exports.create(export_path=name, filesystem=filesystem) if client_list: export.update_permissions(client_list) changed = True else: if client_list: if set(map(transform, unmunchify(export.get_permissions()))) != set(map(transform, client_list)): if not module.check_mode: export.update_permissions(client_list) changed = True module.exit_json(changed=changed) @api_wrapper def delete_export(module, export): """ Delete file system""" if not module.check_mode: export.delete() module.exit_json(changed=True) def main(): argument_spec = infinibox_argument_spec() argument_spec.update( dict( name = dict(required=True), state = dict(default='present', choices=['present', 'absent']), filesystem = dict(required=True), client_list = dict(type='list') ) ) module = AnsibleModule(argument_spec, supports_check_mode=True) if not HAS_INFINISDK: module.fail_json(msg='infinisdk is required for this module') if not HAS_MUNCH: module.fail_json(msg='the python munch library is required for this module') state = module.params['state'] system = get_system(module) filesystem = get_filesystem(module, system) export = get_export(module, filesystem, system) if filesystem is None: module.fail_json(msg='Filesystem {} not found'.format(module.params['filesystem'])) if state == 'present': update_export(module, export, filesystem, system) elif export and state == 'absent': delete_export(module, export) elif export is None and state == 'absent': module.exit_json(changed=False) if __name__ == '__main__': main()
gpl-3.0
sbugrov/biutils_PY
binary_heap.py
2
1581
class BinHeap: def __init__(self): self.heapList = [0] self.currentSize = 0 def percUp(self,i): while i // 2 > 0: if self.heapList[i] < self.heapList[i // 2]: tmp = self.heapList[i // 2] self.heapList[i // 2] = self.heapList[i] self.heapList[i] = tmp i = i // 2 def insert(self,k): self.heapList.append(k) self.currentSize = self.currentSize + 1 self.percUp(self.currentSize) def percDown(self,i): while (i * 2) <= self.currentSize: mc = self.minChild(i) if self.heapList[i] > self.heapList[mc]: tmp = self.heapList[i] self.heapList[i] = self.heapList[mc] self.heapList[mc] = tmp i = mc def minChild(self,i): if i * 2 + 1 > self.currentSize: return i * 2 else: if self.heapList[i*2] < self.heapList[i*2+1]: return i * 2 else: return i * 2 + 1 def delMin(self): retval = self.heapList[1] self.heapList[1] = self.heapList[self.currentSize] self.currentSize = self.currentSize - 1 self.heapList.pop() self.percDown(1) return retval def buildHeap(self,alist): i = len(alist) // 2 self.currentSize = len(alist) self.heapList = [0] + alist[:] while (i > 0): self.percDown(i) i = i - 1 bh = BinHeap() bh.buildHeap([9,5,6,2,3]) print(bh.delMin()) print(bh.delMin()) print(bh.delMin()) print(bh.delMin()) print(bh.delMin())
mit
lucafavatella/intellij-community
python/lib/Lib/linecache.py
99
4070
"""Cache lines from files. This is intended to read lines from modules imported -- hence if a filename is not found, it will look down the module search path for a file by that name. """ import sys import os __all__ = ["getline", "clearcache", "checkcache"] def getline(filename, lineno, module_globals=None): lines = getlines(filename, module_globals) if 1 <= lineno <= len(lines): return lines[lineno-1] else: return '' # The cache cache = {} # The cache def clearcache(): """Clear the cache entirely.""" global cache cache = {} def getlines(filename, module_globals=None): """Get the lines for a file from the cache. Update the cache if it doesn't contain an entry for this file already.""" if filename in cache: return cache[filename][2] else: return updatecache(filename, module_globals) def checkcache(filename=None): """Discard cache entries that are out of date. (This is not checked upon each call!)""" if filename is None: filenames = cache.keys() else: if filename in cache: filenames = [filename] else: return for filename in filenames: size, mtime, lines, fullname = cache[filename] if mtime is None: continue # no-op for files loaded via a __loader__ try: stat = os.stat(fullname) except os.error: del cache[filename] continue if size != stat.st_size or mtime != stat.st_mtime: del cache[filename] def updatecache(filename, module_globals=None): """Update a cache entry and return its list of lines. If something's wrong, print a message, discard the cache entry, and return an empty list.""" if filename in cache: del cache[filename] if not filename or filename[0] + filename[-1] == '<>': return [] fullname = filename try: stat = os.stat(fullname) except os.error, msg: basename = os.path.split(filename)[1] # Try for a __loader__, if available if module_globals and '__loader__' in module_globals: name = module_globals.get('__name__') loader = module_globals['__loader__'] get_source = getattr(loader, 'get_source', None) if name and get_source: if basename.startswith(name.split('.')[-1]+'.'): try: data = get_source(name) except (ImportError, IOError): pass else: if data is None: # No luck, the PEP302 loader cannot find the source # for this module. return [] cache[filename] = ( len(data), None, [line+'\n' for line in data.splitlines()], fullname ) return cache[filename][2] # Try looking through the module search path. for dirname in sys.path: # When using imputil, sys.path may contain things other than # strings; ignore them when it happens. try: fullname = os.path.join(dirname, basename) except (TypeError, AttributeError): # Not sufficiently string-like to do anything useful with. pass else: try: stat = os.stat(fullname) break except os.error: pass else: # No luck ## print '*** Cannot stat', filename, ':', msg return [] try: fp = open(fullname, 'rU') lines = fp.readlines() fp.close() except IOError, msg: ## print '*** Cannot open', fullname, ':', msg return [] size, mtime = stat.st_size, stat.st_mtime cache[filename] = size, mtime, lines, fullname return lines
apache-2.0
kaarolch/ansible
lib/ansible/modules/cloud/ovirt/ovirt_users_facts.py
3
3045
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (c) 2016 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/>. # import traceback from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.ovirt import ( check_sdk, create_connection, get_dict_of_struct, ovirt_full_argument_spec, ) ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'version': '1.0'} DOCUMENTATION = ''' --- module: ovirt_users_facts short_description: Retrieve facts about one or more oVirt users author: "Ondra Machacek (@machacekondra)" version_added: "2.3" description: - "Retrieve facts about one or more oVirt users." notes: - "This module creates a new top-level C(ovirt_users) fact, which contains a list of users." options: pattern: description: - "Search term which is accepted by oVirt search backend." - "For example to search user X use following pattern: name=X" extends_documentation_fragment: ovirt ''' EXAMPLES = ''' # Examples don't contain auth parameter for simplicity, # look at ovirt_auth module to see how to reuse authentication: # Gather facts about all users which first names start with C(john): - ovirt_users_facts: pattern: name=john* - debug: var: ovirt_users ''' RETURN = ''' ovirt_users: description: "List of dictionaries describing the users. User attribues are mapped to dictionary keys, all users attributes can be found at following url: https://ovirt.example.com/ovirt-engine/api/model#types/user." returned: On success. type: list ''' def main(): argument_spec = ovirt_full_argument_spec( pattern=dict(default='', required=False), ) module = AnsibleModule(argument_spec) check_sdk(module) try: connection = create_connection(module.params.pop('auth')) users_service = connection.system_service().users_service() users = users_service.list(search=module.params['pattern']) module.exit_json( changed=False, ansible_facts=dict( ovirt_users=[ get_dict_of_struct(c) for c in users ], ), ) except Exception as e: module.fail_json(msg=str(e), exception=traceback.format_exc()) finally: connection.close(logout=False) if __name__ == '__main__': main()
gpl-3.0
kost/volatility
volatility/plugins/overlays/windows/win8_sp0_x86_vtypes.py
14
547803
ntkrpamp_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']], } ], '_KUSER_SHARED_DATA' : [ 0x5f0, { 'TickCountLowDeprecated' : [ 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, ['wchar']]], 'MaxStackTraceDepth' : [ 0x238, ['unsigned long']], 'CryptoExponent' : [ 0x23c, ['unsigned long']], 'TimeZoneId' : [ 0x240, ['unsigned long']], 'LargePageMinimum' : [ 0x244, ['unsigned long']], 'AitSamplingValue' : [ 0x248, ['unsigned long']], 'AppCompatFlag' : [ 0x24c, ['unsigned long']], 'RNGSeedVersion' : [ 0x250, ['unsigned long long']], 'GlobalValidationRunlevel' : [ 0x258, ['unsigned long']], 'TimeZoneBiasStamp' : [ 0x25c, ['long']], 'Reserved2' : [ 0x260, ['unsigned long']], 'NtProductType' : [ 0x264, ['Enumeration', dict(target = 'long', choices = {1: 'NtProductWinNt', 2: 'NtProductLanManNt', 3: 'NtProductServer'})]], 'ProductTypeIsValid' : [ 0x268, ['unsigned char']], 'Reserved0' : [ 0x269, ['array', 1, ['unsigned char']]], 'NativeProcessorArchitecture' : [ 0x26a, ['unsigned short']], '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'})]], 'AltArchitecturePad' : [ 0x2c4, ['array', 1, ['unsigned long']]], 'SystemExpirationDate' : [ 0x2c8, ['_LARGE_INTEGER']], 'SuiteMask' : [ 0x2d0, ['unsigned long']], 'KdDebuggerEnabled' : [ 0x2d4, ['unsigned char']], 'MitigationPolicies' : [ 0x2d5, ['unsigned char']], 'NXSupportPolicy' : [ 0x2d5, ['BitField', dict(start_bit = 0, end_bit = 2, native_type='unsigned char')]], 'SEHValidationPolicy' : [ 0x2d5, ['BitField', dict(start_bit = 2, end_bit = 4, native_type='unsigned char')]], 'CurDirDevicesSkippedForDlls' : [ 0x2d5, ['BitField', dict(start_bit = 4, end_bit = 6, native_type='unsigned char')]], 'Reserved' : [ 0x2d5, ['BitField', dict(start_bit = 6, end_bit = 8, native_type='unsigned char')]], 'Reserved6' : [ 0x2d6, ['array', 2, ['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']], 'Reserved12' : [ 0x2ed, ['array', 3, ['unsigned char']]], 'SharedDataFlags' : [ 0x2f0, ['unsigned long']], 'DbgErrorPortPresent' : [ 0x2f0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]], 'DbgElevationEnabled' : [ 0x2f0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]], 'DbgVirtEnabled' : [ 0x2f0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]], 'DbgInstallerDetectEnabled' : [ 0x2f0, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned long')]], 'DbgLkgEnabled' : [ 0x2f0, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned long')]], 'DbgDynProcessorEnabled' : [ 0x2f0, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned long')]], 'DbgConsoleBrokerEnabled' : [ 0x2f0, ['BitField', dict(start_bit = 6, end_bit = 7, native_type='unsigned long')]], 'DbgSecureBootEnabled' : [ 0x2f0, ['BitField', dict(start_bit = 7, end_bit = 8, native_type='unsigned long')]], 'SpareBits' : [ 0x2f0, ['BitField', dict(start_bit = 8, end_bit = 32, native_type='unsigned long')]], 'DataFlagsPad' : [ 0x2f4, ['array', 1, ['unsigned long']]], 'TestRetInstruction' : [ 0x2f8, ['unsigned long long']], 'QpcFrequency' : [ 0x300, ['long long']], 'SystemCallPad' : [ 0x308, ['array', 3, ['unsigned long long']]], 'TickCount' : [ 0x320, ['_KSYSTEM_TIME']], 'TickCountQuad' : [ 0x320, ['unsigned long long']], 'ReservedTickCountOverlay' : [ 0x320, ['array', 3, ['unsigned long']]], 'TickCountPad' : [ 0x32c, ['array', 1, ['unsigned long']]], 'Cookie' : [ 0x330, ['unsigned long']], 'CookiePad' : [ 0x334, ['array', 1, ['unsigned long']]], 'ConsoleSessionForegroundProcessId' : [ 0x338, ['long long']], 'TimeUpdateSequence' : [ 0x340, ['unsigned long long']], 'BaselineSystemTimeQpc' : [ 0x348, ['unsigned long long']], 'BaselineInterruptTimeQpc' : [ 0x350, ['unsigned long long']], 'QpcSystemTimeIncrement' : [ 0x358, ['unsigned long long']], 'QpcInterruptTimeIncrement' : [ 0x360, ['unsigned long long']], 'QpcSystemTimeIncrement32' : [ 0x368, ['unsigned long']], 'QpcInterruptTimeIncrement32' : [ 0x36c, ['unsigned long']], 'QpcSystemTimeIncrementShift' : [ 0x370, ['unsigned char']], 'QpcInterruptTimeIncrementShift' : [ 0x371, ['unsigned char']], 'Reserved8' : [ 0x372, ['array', 14, ['unsigned char']]], 'UserModeGlobalLogger' : [ 0x380, ['array', 16, ['unsigned short']]], 'ImageFileExecutionOptions' : [ 0x3a0, ['unsigned long']], 'LangGenerationCount' : [ 0x3a4, ['unsigned long']], 'Reserved4' : [ 0x3a8, ['unsigned long long']], 'InterruptTimeBias' : [ 0x3b0, ['unsigned long long']], 'TscQpcBias' : [ 0x3b8, ['unsigned long long']], 'ActiveProcessorCount' : [ 0x3c0, ['unsigned long']], 'ActiveGroupCount' : [ 0x3c4, ['unsigned char']], 'Reserved9' : [ 0x3c5, ['unsigned char']], 'TscQpcData' : [ 0x3c6, ['unsigned short']], 'TscQpcEnabled' : [ 0x3c6, ['unsigned char']], 'TscQpcShift' : [ 0x3c7, ['unsigned char']], 'TimeZoneBiasEffectiveStart' : [ 0x3c8, ['_LARGE_INTEGER']], 'TimeZoneBiasEffectiveEnd' : [ 0x3d0, ['_LARGE_INTEGER']], 'XState' : [ 0x3d8, ['_XSTATE_CONFIGURATION']], } ], '__unnamed_107c' : [ 0x8, { 'LowPart' : [ 0x0, ['unsigned long']], 'HighPart' : [ 0x4, ['unsigned long']], } ], '_ULARGE_INTEGER' : [ 0x8, { 'LowPart' : [ 0x0, ['unsigned long']], 'HighPart' : [ 0x4, ['unsigned long']], 'u' : [ 0x0, ['__unnamed_107c']], 'QuadPart' : [ 0x0, ['unsigned long long']], } ], '__unnamed_1080' : [ 0x8, { 'LowPart' : [ 0x0, ['unsigned long']], 'HighPart' : [ 0x4, ['long']], } ], '_LARGE_INTEGER' : [ 0x8, { 'LowPart' : [ 0x0, ['unsigned long']], 'HighPart' : [ 0x4, ['long']], 'u' : [ 0x0, ['__unnamed_1080']], 'QuadPart' : [ 0x0, ['long long']], } ], '__unnamed_109b' : [ 0x4, { 'LongFunction' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]], 'Persistent' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]], 'Private' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 32, native_type='unsigned long')]], } ], '__unnamed_109d' : [ 0x4, { 'Flags' : [ 0x0, ['unsigned long']], 's' : [ 0x0, ['__unnamed_109b']], } ], '_TP_CALLBACK_ENVIRON_V3' : [ 0x28, { 'Version' : [ 0x0, ['unsigned long']], 'Pool' : [ 0x4, ['pointer', ['_TP_POOL']]], 'CleanupGroup' : [ 0x8, ['pointer', ['_TP_CLEANUP_GROUP']]], 'CleanupGroupCancelCallback' : [ 0xc, ['pointer', ['void']]], 'RaceDll' : [ 0x10, ['pointer', ['void']]], 'ActivationContext' : [ 0x14, ['pointer', ['_ACTIVATION_CONTEXT']]], 'FinalizationCallback' : [ 0x18, ['pointer', ['void']]], 'u' : [ 0x1c, ['__unnamed_109d']], 'CallbackPriority' : [ 0x20, ['Enumeration', dict(target = 'long', choices = {0: 'TP_CALLBACK_PRIORITY_HIGH', 1: 'TP_CALLBACK_PRIORITY_NORMAL', 2: 'TP_CALLBACK_PRIORITY_LOW', 3: 'TP_CALLBACK_PRIORITY_COUNT'})]], 'Size' : [ 0x24, ['unsigned long']], } ], '_TEB' : [ 0xfe8, { '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']], 'ActivationContextStackPointer' : [ 0x1a8, ['pointer', ['_ACTIVATION_CONTEXT_STACK']]], 'SpareBytes' : [ 0x1ac, ['array', 36, ['unsigned char']]], 'TxFsContext' : [ 0x1d0, ['unsigned long']], '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, ['wchar']]], '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']]]], 'HardErrorMode' : [ 0xf28, ['unsigned long']], 'Instrumentation' : [ 0xf2c, ['array', 9, ['pointer', ['void']]]], 'ActivityId' : [ 0xf50, ['_GUID']], 'SubProcessTag' : [ 0xf60, ['pointer', ['void']]], 'PerflibData' : [ 0xf64, ['pointer', ['void']]], 'EtwTraceData' : [ 0xf68, ['pointer', ['void']]], 'WinSockData' : [ 0xf6c, ['pointer', ['void']]], 'GdiBatchCount' : [ 0xf70, ['unsigned long']], 'CurrentIdealProcessor' : [ 0xf74, ['_PROCESSOR_NUMBER']], 'IdealProcessorValue' : [ 0xf74, ['unsigned long']], 'ReservedPad0' : [ 0xf74, ['unsigned char']], 'ReservedPad1' : [ 0xf75, ['unsigned char']], 'ReservedPad2' : [ 0xf76, ['unsigned char']], 'IdealProcessor' : [ 0xf77, ['unsigned char']], 'GuaranteedStackBytes' : [ 0xf78, ['unsigned long']], 'ReservedForPerf' : [ 0xf7c, ['pointer', ['void']]], 'ReservedForOle' : [ 0xf80, ['pointer', ['void']]], 'WaitingOnLoaderLock' : [ 0xf84, ['unsigned long']], 'SavedPriorityState' : [ 0xf88, ['pointer', ['void']]], 'ReservedForCodeCoverage' : [ 0xf8c, ['unsigned long']], 'ThreadPoolData' : [ 0xf90, ['pointer', ['void']]], 'TlsExpansionSlots' : [ 0xf94, ['pointer', ['pointer', ['void']]]], 'MuiGeneration' : [ 0xf98, ['unsigned long']], 'IsImpersonating' : [ 0xf9c, ['unsigned long']], 'NlsCache' : [ 0xfa0, ['pointer', ['void']]], 'pShimData' : [ 0xfa4, ['pointer', ['void']]], 'HeapVirtualAffinity' : [ 0xfa8, ['unsigned short']], 'LowFragHeapDataSlot' : [ 0xfaa, ['unsigned short']], 'CurrentTransactionHandle' : [ 0xfac, ['pointer', ['void']]], 'ActiveFrame' : [ 0xfb0, ['pointer', ['_TEB_ACTIVE_FRAME']]], 'FlsData' : [ 0xfb4, ['pointer', ['void']]], 'PreferredLanguages' : [ 0xfb8, ['pointer', ['void']]], 'UserPrefLanguages' : [ 0xfbc, ['pointer', ['void']]], 'MergedPrefLanguages' : [ 0xfc0, ['pointer', ['void']]], 'MuiImpersonation' : [ 0xfc4, ['unsigned long']], 'CrossTebFlags' : [ 0xfc8, ['unsigned short']], 'SpareCrossTebBits' : [ 0xfc8, ['BitField', dict(start_bit = 0, end_bit = 16, native_type='unsigned short')]], 'SameTebFlags' : [ 0xfca, ['unsigned short']], 'SafeThunkCall' : [ 0xfca, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned short')]], 'InDebugPrint' : [ 0xfca, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned short')]], 'HasFiberData' : [ 0xfca, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned short')]], 'SkipThreadAttach' : [ 0xfca, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned short')]], 'WerInShipAssertCode' : [ 0xfca, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned short')]], 'RanProcessInit' : [ 0xfca, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned short')]], 'ClonedThread' : [ 0xfca, ['BitField', dict(start_bit = 6, end_bit = 7, native_type='unsigned short')]], 'SuppressDebugMsg' : [ 0xfca, ['BitField', dict(start_bit = 7, end_bit = 8, native_type='unsigned short')]], 'DisableUserStackWalk' : [ 0xfca, ['BitField', dict(start_bit = 8, end_bit = 9, native_type='unsigned short')]], 'RtlExceptionAttached' : [ 0xfca, ['BitField', dict(start_bit = 9, end_bit = 10, native_type='unsigned short')]], 'InitialThread' : [ 0xfca, ['BitField', dict(start_bit = 10, end_bit = 11, native_type='unsigned short')]], 'SessionAware' : [ 0xfca, ['BitField', dict(start_bit = 11, end_bit = 12, native_type='unsigned short')]], 'SpareSameTebBits' : [ 0xfca, ['BitField', dict(start_bit = 12, end_bit = 16, native_type='unsigned short')]], 'TxnScopeEnterCallback' : [ 0xfcc, ['pointer', ['void']]], 'TxnScopeExitCallback' : [ 0xfd0, ['pointer', ['void']]], 'TxnScopeContext' : [ 0xfd4, ['pointer', ['void']]], 'LockCount' : [ 0xfd8, ['unsigned long']], 'SpareUlong0' : [ 0xfdc, ['unsigned long']], 'ResourceRetValue' : [ 0xfe0, ['pointer', ['void']]], 'ReservedForWdf' : [ 0xfe4, ['pointer', ['void']]], } ], '_LIST_ENTRY' : [ 0x8, { 'Flink' : [ 0x0, ['pointer', ['_LIST_ENTRY']]], 'Blink' : [ 0x4, ['pointer', ['_LIST_ENTRY']]], } ], '_SINGLE_LIST_ENTRY' : [ 0x4, { 'Next' : [ 0x0, ['pointer', ['_SINGLE_LIST_ENTRY']]], } ], '_RTL_SPLAY_LINKS' : [ 0xc, { 'Parent' : [ 0x0, ['pointer', ['_RTL_SPLAY_LINKS']]], 'LeftChild' : [ 0x4, ['pointer', ['_RTL_SPLAY_LINKS']]], 'RightChild' : [ 0x8, ['pointer', ['_RTL_SPLAY_LINKS']]], } ], '_RTL_DYNAMIC_HASH_TABLE_CONTEXT' : [ 0xc, { 'ChainHead' : [ 0x0, ['pointer', ['_LIST_ENTRY']]], 'PrevLinkage' : [ 0x4, ['pointer', ['_LIST_ENTRY']]], 'Signature' : [ 0x8, ['unsigned long']], } ], '_RTL_DYNAMIC_HASH_TABLE_ENUMERATOR' : [ 0x14, { 'HashEntry' : [ 0x0, ['_RTL_DYNAMIC_HASH_TABLE_ENTRY']], 'ChainHead' : [ 0xc, ['pointer', ['_LIST_ENTRY']]], 'BucketIndex' : [ 0x10, ['unsigned long']], } ], '_RTL_DYNAMIC_HASH_TABLE' : [ 0x24, { 'Flags' : [ 0x0, ['unsigned long']], 'Shift' : [ 0x4, ['unsigned long']], 'TableSize' : [ 0x8, ['unsigned long']], 'Pivot' : [ 0xc, ['unsigned long']], 'DivisorMask' : [ 0x10, ['unsigned long']], 'NumEntries' : [ 0x14, ['unsigned long']], 'NonEmptyBuckets' : [ 0x18, ['unsigned long']], 'NumEnumerators' : [ 0x1c, ['unsigned long']], 'Directory' : [ 0x20, ['pointer', ['void']]], } ], '_UNICODE_STRING' : [ 0x8, { 'Length' : [ 0x0, ['unsigned short']], 'MaximumLength' : [ 0x2, ['unsigned short']], 'Buffer' : [ 0x4, ['pointer', ['unsigned short']]], } ], '_STRING' : [ 0x8, { 'Length' : [ 0x0, ['unsigned short']], 'MaximumLength' : [ 0x2, ['unsigned short']], 'Buffer' : [ 0x4, ['pointer', ['unsigned char']]], } ], '_LUID' : [ 0x8, { 'LowPart' : [ 0x0, ['unsigned long']], 'HighPart' : [ 0x4, ['long']], } ], '_IMAGE_NT_HEADERS' : [ 0xf8, { 'Signature' : [ 0x0, ['unsigned long']], 'FileHeader' : [ 0x4, ['_IMAGE_FILE_HEADER']], 'OptionalHeader' : [ 0x18, ['_IMAGE_OPTIONAL_HEADER']], } ], '_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']], } ], '_RTL_BALANCED_NODE' : [ 0xc, { 'Children' : [ 0x0, ['array', 2, ['pointer', ['_RTL_BALANCED_NODE']]]], 'Left' : [ 0x0, ['pointer', ['_RTL_BALANCED_NODE']]], 'Right' : [ 0x4, ['pointer', ['_RTL_BALANCED_NODE']]], 'Red' : [ 0x8, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned char')]], 'Balance' : [ 0x8, ['BitField', dict(start_bit = 0, end_bit = 2, native_type='unsigned char')]], 'ParentValue' : [ 0x8, ['unsigned long']], } ], '_RTL_RB_TREE' : [ 0x8, { 'Root' : [ 0x0, ['pointer', ['_RTL_BALANCED_NODE']]], 'Min' : [ 0x4, ['pointer', ['_RTL_BALANCED_NODE']]], } ], '_RTL_AVL_TREE' : [ 0x4, { 'Root' : [ 0x0, ['pointer', ['_RTL_BALANCED_NODE']]], } ], '_KPCR' : [ 0x4280, { 'NtTib' : [ 0x0, ['_NT_TIB']], 'Used_ExceptionList' : [ 0x0, ['pointer', ['_EXCEPTION_REGISTRATION_RECORD']]], 'Used_StackBase' : [ 0x4, ['pointer', ['void']]], 'Spare2' : [ 0x8, ['pointer', ['void']]], 'TssCopy' : [ 0xc, ['pointer', ['void']]], 'ContextSwitches' : [ 0x10, ['unsigned long']], 'SetMemberCopy' : [ 0x14, ['unsigned long']], 'Used_Self' : [ 0x18, ['pointer', ['void']]], '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']], 'SpareUnused' : [ 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']], } ], '_KPRCB' : [ 0x4160, { 'MinorVersion' : [ 0x0, ['unsigned short']], 'MajorVersion' : [ 0x2, ['unsigned short']], 'CurrentThread' : [ 0x4, ['pointer', ['_KTHREAD']]], 'NextThread' : [ 0x8, ['pointer', ['_KTHREAD']]], 'IdleThread' : [ 0xc, ['pointer', ['_KTHREAD']]], 'LegacyNumber' : [ 0x10, ['unsigned char']], 'NestingLevel' : [ 0x11, ['unsigned char']], 'BuildType' : [ 0x12, ['unsigned short']], 'CpuType' : [ 0x14, ['unsigned char']], 'CpuID' : [ 0x15, ['unsigned char']], 'CpuStep' : [ 0x16, ['unsigned short']], 'CpuStepping' : [ 0x16, ['unsigned char']], 'CpuModel' : [ 0x17, ['unsigned char']], 'ProcessorState' : [ 0x18, ['_KPROCESSOR_STATE']], 'KernelReserved' : [ 0x338, ['array', 16, ['unsigned long']]], 'HalReserved' : [ 0x378, ['array', 16, ['unsigned long']]], 'CFlushSize' : [ 0x3b8, ['unsigned long']], 'CoresPerPhysicalProcessor' : [ 0x3bc, ['unsigned char']], 'LogicalProcessorsPerCore' : [ 0x3bd, ['unsigned char']], 'PrcbPad0' : [ 0x3be, ['array', 2, ['unsigned char']]], 'MHz' : [ 0x3c0, ['unsigned long']], 'CpuVendor' : [ 0x3c4, ['unsigned char']], 'GroupIndex' : [ 0x3c5, ['unsigned char']], 'Group' : [ 0x3c6, ['unsigned short']], 'GroupSetMember' : [ 0x3c8, ['unsigned long']], 'Number' : [ 0x3cc, ['unsigned long']], 'ClockOwner' : [ 0x3d0, ['unsigned char']], 'PendingTick' : [ 0x3d1, ['unsigned char']], 'PrcbPad1' : [ 0x3d2, ['array', 70, ['unsigned char']]], 'LockQueue' : [ 0x418, ['array', 17, ['_KSPIN_LOCK_QUEUE']]], 'NpxThread' : [ 0x4a0, ['pointer', ['_KTHREAD']]], 'InterruptCount' : [ 0x4a4, ['unsigned long']], 'KernelTime' : [ 0x4a8, ['unsigned long']], 'UserTime' : [ 0x4ac, ['unsigned long']], 'DpcTime' : [ 0x4b0, ['unsigned long']], 'DpcTimeCount' : [ 0x4b4, ['unsigned long']], 'InterruptTime' : [ 0x4b8, ['unsigned long']], 'AdjustDpcThreshold' : [ 0x4bc, ['unsigned long']], 'PageColor' : [ 0x4c0, ['unsigned long']], 'DebuggerSavedIRQL' : [ 0x4c4, ['unsigned char']], 'NodeColor' : [ 0x4c5, ['unsigned char']], 'PrcbPad20' : [ 0x4c6, ['array', 2, ['unsigned char']]], 'NodeShiftedColor' : [ 0x4c8, ['unsigned long']], 'ParentNode' : [ 0x4cc, ['pointer', ['_KNODE']]], 'SecondaryColorMask' : [ 0x4d0, ['unsigned long']], 'DpcTimeLimit' : [ 0x4d4, ['unsigned long']], 'PrcbPad21' : [ 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']], 'MmSpinLockOrdering' : [ 0x4f8, ['long']], 'IoReadOperationCount' : [ 0x4fc, ['long']], 'IoWriteOperationCount' : [ 0x500, ['long']], 'IoOtherOperationCount' : [ 0x504, ['long']], 'IoReadTransferCount' : [ 0x508, ['_LARGE_INTEGER']], 'IoWriteTransferCount' : [ 0x510, ['_LARGE_INTEGER']], 'IoOtherTransferCount' : [ 0x518, ['_LARGE_INTEGER']], 'CcFastMdlReadNoWait' : [ 0x520, ['unsigned long']], 'CcFastMdlReadWait' : [ 0x524, ['unsigned long']], 'CcFastMdlReadNotPossible' : [ 0x528, ['unsigned long']], 'CcMapDataNoWait' : [ 0x52c, ['unsigned long']], 'CcMapDataWait' : [ 0x530, ['unsigned long']], 'CcPinMappedDataCount' : [ 0x534, ['unsigned long']], 'CcPinReadNoWait' : [ 0x538, ['unsigned long']], 'CcPinReadWait' : [ 0x53c, ['unsigned long']], 'CcMdlReadNoWait' : [ 0x540, ['unsigned long']], 'CcMdlReadWait' : [ 0x544, ['unsigned long']], 'CcLazyWriteHotSpots' : [ 0x548, ['unsigned long']], 'CcLazyWriteIos' : [ 0x54c, ['unsigned long']], 'CcLazyWritePages' : [ 0x550, ['unsigned long']], 'CcDataFlushes' : [ 0x554, ['unsigned long']], 'CcDataPages' : [ 0x558, ['unsigned long']], 'CcLostDelayedWrites' : [ 0x55c, ['unsigned long']], 'CcFastReadResourceMiss' : [ 0x560, ['unsigned long']], 'CcCopyReadWaitMiss' : [ 0x564, ['unsigned long']], 'CcFastMdlReadResourceMiss' : [ 0x568, ['unsigned long']], 'CcMapDataNoWaitMiss' : [ 0x56c, ['unsigned long']], 'CcMapDataWaitMiss' : [ 0x570, ['unsigned long']], 'CcPinReadNoWaitMiss' : [ 0x574, ['unsigned long']], 'CcPinReadWaitMiss' : [ 0x578, ['unsigned long']], 'CcMdlReadNoWaitMiss' : [ 0x57c, ['unsigned long']], 'CcMdlReadWaitMiss' : [ 0x580, ['unsigned long']], 'CcReadAheadIos' : [ 0x584, ['unsigned long']], 'KeAlignmentFixupCount' : [ 0x588, ['unsigned long']], 'KeExceptionDispatchCount' : [ 0x58c, ['unsigned long']], 'KeSystemCalls' : [ 0x590, ['unsigned long']], 'AvailableTime' : [ 0x594, ['unsigned long']], 'PrcbPad22' : [ 0x598, ['array', 2, ['unsigned long']]], 'PPLookasideList' : [ 0x5a0, ['array', 16, ['_PP_LOOKASIDE_LIST']]], 'PPNxPagedLookasideList' : [ 0x620, ['array', 32, ['_GENERAL_LOOKASIDE_POOL']]], 'PPNPagedLookasideList' : [ 0xf20, ['array', 32, ['_GENERAL_LOOKASIDE_POOL']]], 'PPPagedLookasideList' : [ 0x1820, ['array', 32, ['_GENERAL_LOOKASIDE_POOL']]], 'PacketBarrier' : [ 0x2120, ['unsigned long']], 'ReverseStall' : [ 0x2124, ['long']], 'IpiFrame' : [ 0x2128, ['pointer', ['void']]], 'PrcbPad3' : [ 0x212c, ['array', 52, ['unsigned char']]], 'CurrentPacket' : [ 0x2160, ['array', 3, ['pointer', ['void']]]], 'TargetSet' : [ 0x216c, ['unsigned long']], 'WorkerRoutine' : [ 0x2170, ['pointer', ['void']]], 'IpiFrozen' : [ 0x2174, ['unsigned long']], 'PrcbPad4' : [ 0x2178, ['array', 40, ['unsigned char']]], 'RequestSummary' : [ 0x21a0, ['unsigned long']], 'SignalDone' : [ 0x21a4, ['pointer', ['_KPRCB']]], 'PrcbPad50' : [ 0x21a8, ['array', 48, ['unsigned char']]], 'InterruptLastCount' : [ 0x21d8, ['unsigned long']], 'InterruptRate' : [ 0x21dc, ['unsigned long']], 'DpcData' : [ 0x21e0, ['array', 2, ['_KDPC_DATA']]], 'DpcStack' : [ 0x2208, ['pointer', ['void']]], 'MaximumDpcQueueDepth' : [ 0x220c, ['long']], 'DpcRequestRate' : [ 0x2210, ['unsigned long']], 'MinimumDpcRate' : [ 0x2214, ['unsigned long']], 'DpcLastCount' : [ 0x2218, ['unsigned long']], 'PrcbLock' : [ 0x221c, ['unsigned long']], 'DpcGate' : [ 0x2220, ['_KGATE']], 'ThreadDpcEnable' : [ 0x2230, ['unsigned char']], 'QuantumEnd' : [ 0x2231, ['unsigned char']], 'DpcRoutineActive' : [ 0x2232, ['unsigned char']], 'IdleSchedule' : [ 0x2233, ['unsigned char']], 'DpcRequestSummary' : [ 0x2234, ['long']], 'DpcRequestSlot' : [ 0x2234, ['array', 2, ['short']]], 'NormalDpcState' : [ 0x2234, ['short']], 'ThreadDpcState' : [ 0x2236, ['short']], 'DpcNormalProcessingActive' : [ 0x2234, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]], 'DpcNormalProcessingRequested' : [ 0x2234, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]], 'DpcNormalThreadSignal' : [ 0x2234, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]], 'DpcNormalTimerExpiration' : [ 0x2234, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned long')]], 'DpcNormalDpcPresent' : [ 0x2234, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned long')]], 'DpcNormalLocalInterrupt' : [ 0x2234, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned long')]], 'DpcNormalSpare' : [ 0x2234, ['BitField', dict(start_bit = 6, end_bit = 16, native_type='unsigned long')]], 'DpcThreadActive' : [ 0x2234, ['BitField', dict(start_bit = 16, end_bit = 17, native_type='unsigned long')]], 'DpcThreadRequested' : [ 0x2234, ['BitField', dict(start_bit = 17, end_bit = 18, native_type='unsigned long')]], 'DpcThreadSpare' : [ 0x2234, ['BitField', dict(start_bit = 18, end_bit = 32, native_type='unsigned long')]], 'LastTimerHand' : [ 0x2238, ['unsigned long']], 'LastTick' : [ 0x223c, ['unsigned long']], 'PeriodicCount' : [ 0x2240, ['unsigned long']], 'PeriodicBias' : [ 0x2244, ['unsigned long']], 'ClockInterrupts' : [ 0x2248, ['unsigned long']], 'ReadyScanTick' : [ 0x224c, ['unsigned long']], 'BalanceState' : [ 0x2250, ['unsigned char']], 'GroupSchedulingOverQuota' : [ 0x2251, ['unsigned char']], 'PrcbPad41' : [ 0x2252, ['array', 10, ['unsigned char']]], 'TimerTable' : [ 0x2260, ['_KTIMER_TABLE']], 'CallDpc' : [ 0x3aa0, ['_KDPC']], 'ClockKeepAlive' : [ 0x3ac0, ['long']], 'PrcbPad6' : [ 0x3ac4, ['array', 4, ['unsigned char']]], 'DpcWatchdogPeriod' : [ 0x3ac8, ['long']], 'DpcWatchdogCount' : [ 0x3acc, ['long']], 'KeSpinLockOrdering' : [ 0x3ad0, ['long']], 'PrcbPad70' : [ 0x3ad4, ['array', 1, ['unsigned long']]], 'QueueIndex' : [ 0x3ad8, ['unsigned long']], 'DeferredReadyListHead' : [ 0x3adc, ['_SINGLE_LIST_ENTRY']], 'WaitListHead' : [ 0x3ae0, ['_LIST_ENTRY']], 'WaitLock' : [ 0x3ae8, ['unsigned long']], 'ReadySummary' : [ 0x3aec, ['unsigned long']], 'ReadyQueueWeight' : [ 0x3af0, ['unsigned long']], 'BuddyPrcb' : [ 0x3af4, ['pointer', ['_KPRCB']]], 'StartCycles' : [ 0x3af8, ['unsigned long long']], 'GenerationTarget' : [ 0x3b00, ['unsigned long long']], 'CycleTime' : [ 0x3b08, ['unsigned long long']], 'HighCycleTime' : [ 0x3b10, ['unsigned long']], 'ScbOffset' : [ 0x3b14, ['unsigned long']], 'AffinitizedCycles' : [ 0x3b18, ['unsigned long long']], 'DispatcherReadyListHead' : [ 0x3b20, ['array', 32, ['_LIST_ENTRY']]], 'ChainedInterruptList' : [ 0x3c20, ['pointer', ['void']]], 'LookasideIrpFloat' : [ 0x3c24, ['long']], 'ScbQueue' : [ 0x3c28, ['_RTL_RB_TREE']], 'ScbList' : [ 0x3c30, ['_LIST_ENTRY']], 'MmPageFaultCount' : [ 0x3c38, ['long']], 'MmCopyOnWriteCount' : [ 0x3c3c, ['long']], 'MmTransitionCount' : [ 0x3c40, ['long']], 'MmCacheTransitionCount' : [ 0x3c44, ['long']], 'MmDemandZeroCount' : [ 0x3c48, ['long']], 'MmPageReadCount' : [ 0x3c4c, ['long']], 'MmPageReadIoCount' : [ 0x3c50, ['long']], 'MmCacheReadCount' : [ 0x3c54, ['long']], 'MmCacheIoCount' : [ 0x3c58, ['long']], 'MmDirtyPagesWriteCount' : [ 0x3c5c, ['long']], 'MmDirtyWriteIoCount' : [ 0x3c60, ['long']], 'MmMappedPagesWriteCount' : [ 0x3c64, ['long']], 'MmMappedWriteIoCount' : [ 0x3c68, ['long']], 'CachedCommit' : [ 0x3c6c, ['unsigned long']], 'CachedResidentAvailable' : [ 0x3c70, ['unsigned long']], 'HyperPte' : [ 0x3c74, ['pointer', ['void']]], 'PrcbPad8' : [ 0x3c78, ['array', 4, ['unsigned char']]], 'VendorString' : [ 0x3c7c, ['array', 13, ['unsigned char']]], 'InitialApicId' : [ 0x3c89, ['unsigned char']], 'LogicalProcessorsPerPhysicalProcessor' : [ 0x3c8a, ['unsigned char']], 'PrcbPad9' : [ 0x3c8b, ['array', 5, ['unsigned char']]], 'FeatureBits' : [ 0x3c90, ['unsigned long']], 'UpdateSignature' : [ 0x3c98, ['_LARGE_INTEGER']], 'IsrTime' : [ 0x3ca0, ['unsigned long long']], 'Stride' : [ 0x3ca8, ['unsigned long']], 'PrcbPad90' : [ 0x3cac, ['unsigned long']], 'PowerState' : [ 0x3cb0, ['_PROCESSOR_POWER_STATE']], 'PrcbPad91' : [ 0x3e30, ['array', 1, ['unsigned long']]], 'DpcWatchdogDpc' : [ 0x3e34, ['_KDPC']], 'DpcWatchdogTimer' : [ 0x3e58, ['_KTIMER']], 'HypercallPageList' : [ 0x3e80, ['_SLIST_HEADER']], 'HypercallPageVirtual' : [ 0x3e88, ['pointer', ['void']]], 'VirtualApicAssist' : [ 0x3e8c, ['pointer', ['void']]], 'StatisticsPage' : [ 0x3e90, ['pointer', ['unsigned long long']]], 'Cache' : [ 0x3e94, ['array', 5, ['_CACHE_DESCRIPTOR']]], 'CacheCount' : [ 0x3ed0, ['unsigned long']], 'PackageProcessorSet' : [ 0x3ed4, ['_KAFFINITY_EX']], 'CacheProcessorMask' : [ 0x3ee0, ['array', 5, ['unsigned long']]], 'ScanSiblingMask' : [ 0x3ef4, ['unsigned long']], 'CoreProcessorSet' : [ 0x3ef8, ['unsigned long']], 'ScanSiblingIndex' : [ 0x3efc, ['unsigned long']], 'LLCLevel' : [ 0x3f00, ['unsigned long']], 'WheaInfo' : [ 0x3f04, ['pointer', ['void']]], 'EtwSupport' : [ 0x3f08, ['pointer', ['void']]], 'InterruptObjectPool' : [ 0x3f10, ['_SLIST_HEADER']], 'PrcbPad92' : [ 0x3f18, ['array', 8, ['unsigned long']]], 'ProcessorProfileControlArea' : [ 0x3f38, ['pointer', ['_PROCESSOR_PROFILE_CONTROL_AREA']]], 'ProfileEventIndexAddress' : [ 0x3f3c, ['pointer', ['void']]], 'TimerExpirationDpc' : [ 0x3f40, ['_KDPC']], 'SynchCounters' : [ 0x3f60, ['_SYNCH_COUNTERS']], 'FsCounters' : [ 0x4018, ['_FILESYSTEM_DISK_COUNTERS']], 'Context' : [ 0x4028, ['pointer', ['_CONTEXT']]], 'ContextFlagsInit' : [ 0x402c, ['unsigned long']], 'ExtendedState' : [ 0x4030, ['pointer', ['_XSAVE_AREA']]], 'EntropyTimingState' : [ 0x4034, ['_KENTROPY_TIMING_STATE']], } ], '_KAPC' : [ 0x30, { 'Type' : [ 0x0, ['unsigned char']], 'SpareByte0' : [ 0x1, ['unsigned char']], 'Size' : [ 0x2, ['unsigned char']], 'SpareByte1' : [ 0x3, ['unsigned char']], 'SpareLong0' : [ 0x4, ['unsigned long']], 'Thread' : [ 0x8, ['pointer', ['_KTHREAD']]], 'ApcListEntry' : [ 0xc, ['_LIST_ENTRY']], 'KernelRoutine' : [ 0x14, ['pointer', ['void']]], 'RundownRoutine' : [ 0x18, ['pointer', ['void']]], 'NormalRoutine' : [ 0x1c, ['pointer', ['void']]], 'Reserved' : [ 0x14, ['array', 3, ['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']], } ], '_KTHREAD' : [ 0x1e8, { 'Header' : [ 0x0, ['_DISPATCHER_HEADER']], 'SListFaultAddress' : [ 0x10, ['pointer', ['void']]], 'QuantumTarget' : [ 0x18, ['unsigned long long']], 'InitialStack' : [ 0x20, ['pointer', ['void']]], 'StackLimit' : [ 0x24, ['pointer', ['void']]], 'StackBase' : [ 0x28, ['pointer', ['void']]], 'ThreadLock' : [ 0x2c, ['unsigned long']], 'CycleTime' : [ 0x30, ['unsigned long long']], 'HighCycleTime' : [ 0x38, ['unsigned long']], 'ServiceTable' : [ 0x3c, ['pointer', ['void']]], 'CurrentRunTime' : [ 0x40, ['unsigned long']], 'ExpectedRunTime' : [ 0x44, ['unsigned long']], 'KernelStack' : [ 0x48, ['pointer', ['void']]], 'StateSaveArea' : [ 0x4c, ['pointer', ['_XSAVE_FORMAT']]], 'SchedulingGroup' : [ 0x50, ['pointer', ['_KSCHEDULING_GROUP']]], 'WaitRegister' : [ 0x54, ['_KWAIT_STATUS_REGISTER']], 'Running' : [ 0x55, ['unsigned char']], 'Alerted' : [ 0x56, ['array', 2, ['unsigned char']]], 'KernelStackResident' : [ 0x58, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]], 'ReadyTransition' : [ 0x58, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]], 'ProcessReadyQueue' : [ 0x58, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]], 'WaitNext' : [ 0x58, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned long')]], 'SystemAffinityActive' : [ 0x58, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned long')]], 'Alertable' : [ 0x58, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned long')]], 'CodePatchInProgress' : [ 0x58, ['BitField', dict(start_bit = 6, end_bit = 7, native_type='unsigned long')]], 'UserStackWalkActive' : [ 0x58, ['BitField', dict(start_bit = 7, end_bit = 8, native_type='unsigned long')]], 'ApcInterruptRequest' : [ 0x58, ['BitField', dict(start_bit = 8, end_bit = 9, native_type='unsigned long')]], 'QuantumEndMigrate' : [ 0x58, ['BitField', dict(start_bit = 9, end_bit = 10, native_type='unsigned long')]], 'UmsDirectedSwitchEnable' : [ 0x58, ['BitField', dict(start_bit = 10, end_bit = 11, native_type='unsigned long')]], 'TimerActive' : [ 0x58, ['BitField', dict(start_bit = 11, end_bit = 12, native_type='unsigned long')]], 'SystemThread' : [ 0x58, ['BitField', dict(start_bit = 12, end_bit = 13, native_type='unsigned long')]], 'ProcessDetachActive' : [ 0x58, ['BitField', dict(start_bit = 13, end_bit = 14, native_type='unsigned long')]], 'CalloutActive' : [ 0x58, ['BitField', dict(start_bit = 14, end_bit = 15, native_type='unsigned long')]], 'ScbReadyQueue' : [ 0x58, ['BitField', dict(start_bit = 15, end_bit = 16, native_type='unsigned long')]], 'ApcQueueable' : [ 0x58, ['BitField', dict(start_bit = 16, end_bit = 17, native_type='unsigned long')]], 'ReservedStackInUse' : [ 0x58, ['BitField', dict(start_bit = 17, end_bit = 18, native_type='unsigned long')]], 'UmsPerformingSyscall' : [ 0x58, ['BitField', dict(start_bit = 18, end_bit = 19, native_type='unsigned long')]], 'Reserved' : [ 0x58, ['BitField', dict(start_bit = 19, end_bit = 32, native_type='unsigned long')]], 'MiscFlags' : [ 0x58, ['long']], 'AutoAlignment' : [ 0x5c, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]], 'DisableBoost' : [ 0x5c, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]], 'UserAffinitySet' : [ 0x5c, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]], 'AlertedByThreadId' : [ 0x5c, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned long')]], 'QuantumDonation' : [ 0x5c, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned long')]], 'EnableStackSwap' : [ 0x5c, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned long')]], 'GuiThread' : [ 0x5c, ['BitField', dict(start_bit = 6, end_bit = 7, native_type='unsigned long')]], 'DisableQuantum' : [ 0x5c, ['BitField', dict(start_bit = 7, end_bit = 8, native_type='unsigned long')]], 'ChargeOnlyGroup' : [ 0x5c, ['BitField', dict(start_bit = 8, end_bit = 9, native_type='unsigned long')]], 'DeferPreemption' : [ 0x5c, ['BitField', dict(start_bit = 9, end_bit = 10, native_type='unsigned long')]], 'QueueDeferPreemption' : [ 0x5c, ['BitField', dict(start_bit = 10, end_bit = 11, native_type='unsigned long')]], 'ForceDeferSchedule' : [ 0x5c, ['BitField', dict(start_bit = 11, end_bit = 12, native_type='unsigned long')]], 'ExplicitIdealProcessor' : [ 0x5c, ['BitField', dict(start_bit = 12, end_bit = 13, native_type='unsigned long')]], 'FreezeCount' : [ 0x5c, ['BitField', dict(start_bit = 13, end_bit = 14, native_type='unsigned long')]], 'EtwStackTraceApcInserted' : [ 0x5c, ['BitField', dict(start_bit = 14, end_bit = 22, native_type='unsigned long')]], 'ReservedFlags' : [ 0x5c, ['BitField', dict(start_bit = 22, end_bit = 32, native_type='unsigned long')]], 'ThreadFlags' : [ 0x5c, ['long']], 'Spare0' : [ 0x60, ['unsigned long']], 'SystemCallNumber' : [ 0x64, ['unsigned long']], 'FirstArgument' : [ 0x68, ['pointer', ['void']]], 'TrapFrame' : [ 0x6c, ['pointer', ['_KTRAP_FRAME']]], 'ApcState' : [ 0x70, ['_KAPC_STATE']], 'ApcStateFill' : [ 0x70, ['array', 23, ['unsigned char']]], 'Priority' : [ 0x87, ['unsigned char']], 'UserIdealProcessor' : [ 0x88, ['unsigned long']], 'ContextSwitches' : [ 0x8c, ['unsigned long']], 'State' : [ 0x90, ['unsigned char']], 'NpxState' : [ 0x91, ['unsigned char']], 'WaitIrql' : [ 0x92, ['unsigned char']], 'WaitMode' : [ 0x93, ['unsigned char']], 'WaitStatus' : [ 0x94, ['long']], 'WaitBlockList' : [ 0x98, ['pointer', ['_KWAIT_BLOCK']]], 'WaitListEntry' : [ 0x9c, ['_LIST_ENTRY']], 'SwapListEntry' : [ 0x9c, ['_SINGLE_LIST_ENTRY']], 'Queue' : [ 0xa4, ['pointer', ['_KQUEUE']]], 'Teb' : [ 0xa8, ['pointer', ['void']]], 'RelativeTimerBias' : [ 0xb0, ['unsigned long long']], 'Timer' : [ 0xb8, ['_KTIMER']], 'WaitBlock' : [ 0xe0, ['array', 4, ['_KWAIT_BLOCK']]], 'WaitBlockFill8' : [ 0xe0, ['array', 20, ['unsigned char']]], 'ThreadCounters' : [ 0xf4, ['pointer', ['_KTHREAD_COUNTERS']]], 'WaitBlockFill9' : [ 0xe0, ['array', 44, ['unsigned char']]], 'XStateSave' : [ 0x10c, ['pointer', ['_XSTATE_SAVE']]], 'WaitBlockFill10' : [ 0xe0, ['array', 68, ['unsigned char']]], 'Win32Thread' : [ 0x124, ['pointer', ['void']]], 'WaitBlockFill11' : [ 0xe0, ['array', 88, ['unsigned char']]], 'WaitTime' : [ 0x138, ['unsigned long']], 'KernelApcDisable' : [ 0x13c, ['short']], 'SpecialApcDisable' : [ 0x13e, ['short']], 'CombinedApcDisable' : [ 0x13c, ['unsigned long']], 'QueueListEntry' : [ 0x140, ['_LIST_ENTRY']], 'NextProcessor' : [ 0x148, ['unsigned long']], 'DeferredProcessor' : [ 0x14c, ['unsigned long']], 'Process' : [ 0x150, ['pointer', ['_KPROCESS']]], 'UserAffinity' : [ 0x154, ['_GROUP_AFFINITY']], 'UserAffinityFill' : [ 0x154, ['array', 6, ['unsigned char']]], 'PreviousMode' : [ 0x15a, ['unsigned char']], 'BasePriority' : [ 0x15b, ['unsigned char']], 'PriorityDecrement' : [ 0x15c, ['unsigned char']], 'ForegroundBoost' : [ 0x15c, ['BitField', dict(start_bit = 0, end_bit = 4, native_type='unsigned char')]], 'UnusualBoost' : [ 0x15c, ['BitField', dict(start_bit = 4, end_bit = 8, native_type='unsigned char')]], 'Preempted' : [ 0x15d, ['unsigned char']], 'AdjustReason' : [ 0x15e, ['unsigned char']], 'AdjustIncrement' : [ 0x15f, ['unsigned char']], 'Affinity' : [ 0x160, ['_GROUP_AFFINITY']], 'AffinityFill' : [ 0x160, ['array', 6, ['unsigned char']]], 'ApcStateIndex' : [ 0x166, ['unsigned char']], 'WaitBlockCount' : [ 0x167, ['unsigned char']], 'IdealProcessor' : [ 0x168, ['unsigned long']], 'ApcStatePointer' : [ 0x16c, ['array', 2, ['pointer', ['_KAPC_STATE']]]], 'SavedApcState' : [ 0x174, ['_KAPC_STATE']], 'SavedApcStateFill' : [ 0x174, ['array', 23, ['unsigned char']]], 'WaitReason' : [ 0x18b, ['unsigned char']], 'SuspendCount' : [ 0x18c, ['unsigned char']], 'Saturation' : [ 0x18d, ['unsigned char']], 'SListFaultCount' : [ 0x18e, ['unsigned short']], 'SchedulerApc' : [ 0x190, ['_KAPC']], 'SchedulerApcFill0' : [ 0x190, ['array', 1, ['unsigned char']]], 'ResourceIndex' : [ 0x191, ['unsigned char']], 'SchedulerApcFill1' : [ 0x190, ['array', 3, ['unsigned char']]], 'QuantumReset' : [ 0x193, ['unsigned char']], 'SchedulerApcFill2' : [ 0x190, ['array', 4, ['unsigned char']]], 'KernelTime' : [ 0x194, ['unsigned long']], 'SchedulerApcFill3' : [ 0x190, ['array', 36, ['unsigned char']]], 'WaitPrcb' : [ 0x1b4, ['pointer', ['_KPRCB']]], 'SchedulerApcFill4' : [ 0x190, ['array', 40, ['unsigned char']]], 'LegoData' : [ 0x1b8, ['pointer', ['void']]], 'SchedulerApcFill5' : [ 0x190, ['array', 47, ['unsigned char']]], 'CallbackNestingLevel' : [ 0x1bf, ['unsigned char']], 'UserTime' : [ 0x1c0, ['unsigned long']], 'SuspendEvent' : [ 0x1c4, ['_KEVENT']], 'ThreadListEntry' : [ 0x1d4, ['_LIST_ENTRY']], 'MutantListHead' : [ 0x1dc, ['_LIST_ENTRY']], } ], '_KSTACK_CONTROL' : [ 0x20, { 'StackBase' : [ 0x0, ['unsigned long']], 'ActualLimit' : [ 0x4, ['unsigned long']], 'StackExpansion' : [ 0x4, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]], 'PreviousTrapFrame' : [ 0x8, ['pointer', ['_KTRAP_FRAME']]], 'PreviousExceptionList' : [ 0xc, ['pointer', ['void']]], 'Previous' : [ 0x10, ['_KERNEL_STACK_SEGMENT']], } ], '_KSPIN_LOCK_QUEUE' : [ 0x8, { 'Next' : [ 0x0, ['pointer', ['_KSPIN_LOCK_QUEUE']]], 'Lock' : [ 0x4, ['pointer', ['unsigned long']]], } ], '_FAST_MUTEX' : [ 0x20, { 'Count' : [ 0x0, ['long']], 'Owner' : [ 0x4, ['pointer', ['void']]], 'Contention' : [ 0x8, ['unsigned long']], 'Event' : [ 0xc, ['_KEVENT']], 'OldIrql' : [ 0x1c, ['unsigned long']], } ], '_KEVENT' : [ 0x10, { 'Header' : [ 0x0, ['_DISPATCHER_HEADER']], } ], '_SLIST_HEADER' : [ 0x8, { 'Alignment' : [ 0x0, ['unsigned long long']], 'Next' : [ 0x0, ['_SINGLE_LIST_ENTRY']], 'Depth' : [ 0x4, ['unsigned short']], 'Sequence' : [ 0x6, ['unsigned short']], } ], '_LOOKASIDE_LIST_EX' : [ 0x48, { 'L' : [ 0x0, ['_GENERAL_LOOKASIDE_POOL']], } ], '_NPAGED_LOOKASIDE_LIST' : [ 0xc0, { 'L' : [ 0x0, ['_GENERAL_LOOKASIDE']], 'Lock__ObsoleteButDoNotDelete' : [ 0x80, ['unsigned long']], } ], '_PAGED_LOOKASIDE_LIST' : [ 0xc0, { 'L' : [ 0x0, ['_GENERAL_LOOKASIDE']], 'Lock__ObsoleteButDoNotDelete' : [ 0x80, ['_FAST_MUTEX']], } ], '_IO_STATUS_BLOCK' : [ 0x8, { 'Status' : [ 0x0, ['long']], 'Pointer' : [ 0x0, ['pointer', ['void']]], 'Information' : [ 0x4, ['unsigned long']], } ], '_QUAD' : [ 0x8, { 'UseThisFieldToCopy' : [ 0x0, ['long long']], 'DoNotUseThisField' : [ 0x0, ['double']], } ], '_WORK_QUEUE_ITEM' : [ 0x10, { 'List' : [ 0x0, ['_LIST_ENTRY']], 'WorkerRoutine' : [ 0x8, ['pointer', ['void']]], 'Parameter' : [ 0xc, ['pointer', ['void']]], } ], '_EX_PUSH_LOCK' : [ 0x4, { 'Locked' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]], 'Waiting' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]], 'Waking' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]], 'MultipleShared' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned long')]], 'Shared' : [ 0x0, ['BitField', dict(start_bit = 4, end_bit = 32, native_type='unsigned long')]], 'Value' : [ 0x0, ['unsigned long']], 'Ptr' : [ 0x0, ['pointer', ['void']]], } ], '_PROCESSOR_NUMBER' : [ 0x4, { 'Group' : [ 0x0, ['unsigned short']], 'Number' : [ 0x2, ['unsigned char']], 'Reserved' : [ 0x3, ['unsigned char']], } ], '_EX_PUSH_LOCK_CACHE_AWARE' : [ 0x80, { 'Locks' : [ 0x0, ['array', 32, ['pointer', ['_EX_PUSH_LOCK']]]], } ], '_PP_LOOKASIDE_LIST' : [ 0x8, { 'P' : [ 0x0, ['pointer', ['_GENERAL_LOOKASIDE']]], 'L' : [ 0x4, ['pointer', ['_GENERAL_LOOKASIDE']]], } ], '_GENERAL_LOOKASIDE' : [ 0x80, { 'ListHead' : [ 0x0, ['_SLIST_HEADER']], 'SingleListHead' : [ 0x0, ['_SINGLE_LIST_ENTRY']], '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: 'NonPagedPoolBase', 1: 'PagedPool', 2: 'NonPagedPoolBaseMustSucceed', 3: 'DontUseThisType', 4: 'NonPagedPoolBaseCacheAligned', 5: 'PagedPoolCacheAligned', 6: 'NonPagedPoolBaseCacheAlignedMustS', 7: 'MaxPoolType', 34: 'NonPagedPoolMustSucceedSession', 516: 'NonPagedPoolNxCacheAligned', 35: 'DontUseThisTypeSession', 32: 'NonPagedPoolSession', 512: 'NonPagedPoolNx', 544: 'NonPagedPoolSessionNx', 36: 'NonPagedPoolCacheAlignedSession', 33: 'PagedPoolSession', 38: 'NonPagedPoolCacheAlignedMustSSession', 37: 'PagedPoolCacheAlignedSession'})]], 'Tag' : [ 0x20, ['unsigned long']], 'Size' : [ 0x24, ['unsigned long']], 'AllocateEx' : [ 0x28, ['pointer', ['void']]], 'Allocate' : [ 0x28, ['pointer', ['void']]], 'FreeEx' : [ 0x2c, ['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']]], } ], '_KNODE' : [ 0xc0, { 'DeepIdleSet' : [ 0x0, ['unsigned long']], 'ProximityId' : [ 0x40, ['unsigned long']], 'NodeNumber' : [ 0x44, ['unsigned short']], 'PrimaryNodeNumber' : [ 0x46, ['unsigned short']], 'MaximumProcessors' : [ 0x48, ['unsigned char']], 'Flags' : [ 0x49, ['_flags']], 'Stride' : [ 0x4a, ['unsigned char']], 'NodePad0' : [ 0x4b, ['unsigned char']], 'Affinity' : [ 0x4c, ['_GROUP_AFFINITY']], 'IdleCpuSet' : [ 0x58, ['unsigned long']], 'IdleSmtSet' : [ 0x5c, ['unsigned long']], 'Seed' : [ 0x80, ['unsigned long']], 'Lowest' : [ 0x84, ['unsigned long']], 'Highest' : [ 0x88, ['unsigned long']], 'ParkLock' : [ 0x8c, ['long']], 'NonParkedSet' : [ 0x90, ['unsigned long']], } ], '_ENODE' : [ 0x280, { 'Ncb' : [ 0x0, ['_KNODE']], 'ExWorkerQueues' : [ 0xc0, ['array', 7, ['_EX_WORK_QUEUE']]], 'ExpThreadSetManagerEvent' : [ 0x248, ['_KEVENT']], 'ExpWorkerThreadBalanceManagerPtr' : [ 0x258, ['pointer', ['_ETHREAD']]], 'ExpWorkerSeed' : [ 0x25c, ['unsigned long']], 'ExWorkerFullInit' : [ 0x260, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]], 'ExWorkerStructInit' : [ 0x260, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]], 'ExWorkerFlags' : [ 0x260, ['unsigned long']], } ], '_HANDLE_TABLE' : [ 0x5c, { 'NextHandleNeedingPool' : [ 0x0, ['unsigned long']], 'ExtraInfoPages' : [ 0x4, ['long']], 'TableCode' : [ 0x8, ['unsigned long']], 'QuotaProcess' : [ 0xc, ['pointer', ['_EPROCESS']]], 'HandleTableList' : [ 0x10, ['_LIST_ENTRY']], 'UniqueProcessId' : [ 0x18, ['unsigned long']], 'Flags' : [ 0x1c, ['unsigned long']], 'StrictFIFO' : [ 0x1c, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned char')]], 'EnableHandleExceptions' : [ 0x1c, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned char')]], 'Rundown' : [ 0x1c, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned char')]], 'Duplicated' : [ 0x1c, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned char')]], 'HandleContentionEvent' : [ 0x20, ['_EX_PUSH_LOCK']], 'HandleTableLock' : [ 0x24, ['_EX_PUSH_LOCK']], 'FreeLists' : [ 0x28, ['array', 1, ['_HANDLE_TABLE_FREE_LIST']]], 'ActualEntry' : [ 0x28, ['array', 20, ['unsigned char']]], 'DebugInfo' : [ 0x3c, ['pointer', ['_HANDLE_TRACE_DEBUG_INFO']]], } ], '_HANDLE_TABLE_ENTRY_INFO' : [ 0x4, { 'AuditMask' : [ 0x0, ['unsigned long']], } ], '_HANDLE_TABLE_ENTRY' : [ 0x8, { 'VolatileLowValue' : [ 0x0, ['long']], 'LowValue' : [ 0x0, ['long']], 'InfoTable' : [ 0x0, ['pointer', ['_HANDLE_TABLE_ENTRY_INFO']]], 'Unlocked' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]], 'Attributes' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 3, native_type='unsigned long')]], 'ObjectPointerBits' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 32, native_type='unsigned long')]], 'HighValue' : [ 0x4, ['long']], 'NextFreeHandleEntry' : [ 0x4, ['pointer', ['_HANDLE_TABLE_ENTRY']]], 'LeafHandleValue' : [ 0x4, ['_EXHANDLE']], 'GrantedAccessBits' : [ 0x4, ['BitField', dict(start_bit = 0, end_bit = 25, native_type='unsigned long')]], 'ProtectFromClose' : [ 0x4, ['BitField', dict(start_bit = 25, end_bit = 26, native_type='unsigned long')]], 'RefCnt' : [ 0x4, ['BitField', dict(start_bit = 26, end_bit = 32, native_type='unsigned long')]], } ], '_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']], } ], '__unnamed_12ef' : [ 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_12ef']], 'AuditPrivileges' : [ 0x60, ['unsigned char']], 'ObjectName' : [ 0x64, ['_UNICODE_STRING']], 'ObjectTypeName' : [ 0x6c, ['_UNICODE_STRING']], } ], '_AUX_ACCESS_DATA' : [ 0xc4, { 'PrivilegesUsed' : [ 0x0, ['pointer', ['_PRIVILEGE_SET']]], 'GenericMapping' : [ 0x4, ['_GENERIC_MAPPING']], 'AccessesToAudit' : [ 0x14, ['unsigned long']], 'MaximumAuditMask' : [ 0x18, ['unsigned long']], 'TransactionId' : [ 0x1c, ['_GUID']], 'NewSecurityDescriptor' : [ 0x2c, ['pointer', ['void']]], 'ExistingSecurityDescriptor' : [ 0x30, ['pointer', ['void']]], 'ParentSecurityDescriptor' : [ 0x34, ['pointer', ['void']]], 'DeRefSecurityDescriptor' : [ 0x38, ['pointer', ['void']]], 'SDLock' : [ 0x3c, ['pointer', ['void']]], 'AccessReasons' : [ 0x40, ['_ACCESS_REASONS']], 'GenerateStagingEvents' : [ 0xc0, ['unsigned char']], } ], '_ETHREAD' : [ 0x2c8, { 'Tcb' : [ 0x0, ['_KTHREAD']], 'CreateTime' : [ 0x1e8, ['_LARGE_INTEGER']], 'ExitTime' : [ 0x1f0, ['_LARGE_INTEGER']], 'KeyedWaitChain' : [ 0x1f0, ['_LIST_ENTRY']], 'ChargeOnlySession' : [ 0x1f8, ['pointer', ['void']]], 'PostBlockList' : [ 0x1fc, ['_LIST_ENTRY']], 'ForwardLinkShadow' : [ 0x1fc, ['pointer', ['void']]], 'StartAddress' : [ 0x200, ['pointer', ['void']]], 'TerminationPort' : [ 0x204, ['pointer', ['_TERMINATION_PORT']]], 'ReaperLink' : [ 0x204, ['pointer', ['_ETHREAD']]], 'KeyedWaitValue' : [ 0x204, ['pointer', ['void']]], 'ActiveTimerListLock' : [ 0x208, ['unsigned long']], 'ActiveTimerListHead' : [ 0x20c, ['_LIST_ENTRY']], 'Cid' : [ 0x214, ['_CLIENT_ID']], 'KeyedWaitSemaphore' : [ 0x21c, ['_KSEMAPHORE']], 'AlpcWaitSemaphore' : [ 0x21c, ['_KSEMAPHORE']], 'ClientSecurity' : [ 0x230, ['_PS_CLIENT_SECURITY_CONTEXT']], 'IrpList' : [ 0x234, ['_LIST_ENTRY']], 'TopLevelIrp' : [ 0x23c, ['unsigned long']], 'DeviceToVerify' : [ 0x240, ['pointer', ['_DEVICE_OBJECT']]], 'Win32StartAddress' : [ 0x244, ['pointer', ['void']]], 'LegacyPowerObject' : [ 0x248, ['pointer', ['void']]], 'ThreadListEntry' : [ 0x24c, ['_LIST_ENTRY']], 'RundownProtect' : [ 0x254, ['_EX_RUNDOWN_REF']], 'ThreadLock' : [ 0x258, ['_EX_PUSH_LOCK']], 'ReadClusterSize' : [ 0x25c, ['unsigned long']], 'MmLockOrdering' : [ 0x260, ['long']], 'CmLockOrdering' : [ 0x264, ['long']], 'CrossThreadFlags' : [ 0x268, ['unsigned long']], 'Terminated' : [ 0x268, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]], 'ThreadInserted' : [ 0x268, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]], 'HideFromDebugger' : [ 0x268, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]], 'ActiveImpersonationInfo' : [ 0x268, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned long')]], 'HardErrorsAreDisabled' : [ 0x268, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned long')]], 'BreakOnTermination' : [ 0x268, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned long')]], 'SkipCreationMsg' : [ 0x268, ['BitField', dict(start_bit = 6, end_bit = 7, native_type='unsigned long')]], 'SkipTerminationMsg' : [ 0x268, ['BitField', dict(start_bit = 7, end_bit = 8, native_type='unsigned long')]], 'CopyTokenOnOpen' : [ 0x268, ['BitField', dict(start_bit = 8, end_bit = 9, native_type='unsigned long')]], 'ThreadIoPriority' : [ 0x268, ['BitField', dict(start_bit = 9, end_bit = 12, native_type='unsigned long')]], 'ThreadPagePriority' : [ 0x268, ['BitField', dict(start_bit = 12, end_bit = 15, native_type='unsigned long')]], 'RundownFail' : [ 0x268, ['BitField', dict(start_bit = 15, end_bit = 16, native_type='unsigned long')]], 'UmsForceQueueTermination' : [ 0x268, ['BitField', dict(start_bit = 16, end_bit = 17, native_type='unsigned long')]], 'ReservedCrossThreadFlags' : [ 0x268, ['BitField', dict(start_bit = 17, end_bit = 32, native_type='unsigned long')]], 'SameThreadPassiveFlags' : [ 0x26c, ['unsigned long']], 'ActiveExWorker' : [ 0x26c, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]], 'MemoryMaker' : [ 0x26c, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]], 'ClonedThread' : [ 0x26c, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]], 'KeyedEventInUse' : [ 0x26c, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned long')]], 'SelfTerminate' : [ 0x26c, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned long')]], 'SameThreadApcFlags' : [ 0x270, ['unsigned long']], 'Spare' : [ 0x270, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned char')]], 'StartAddressInvalid' : [ 0x270, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned char')]], 'EtwCalloutActive' : [ 0x270, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned char')]], 'OwnsProcessWorkingSetExclusive' : [ 0x270, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned char')]], 'OwnsProcessWorkingSetShared' : [ 0x270, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned char')]], 'OwnsSystemCacheWorkingSetExclusive' : [ 0x270, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned char')]], 'OwnsSystemCacheWorkingSetShared' : [ 0x270, ['BitField', dict(start_bit = 6, end_bit = 7, native_type='unsigned char')]], 'OwnsSessionWorkingSetExclusive' : [ 0x270, ['BitField', dict(start_bit = 7, end_bit = 8, native_type='unsigned char')]], 'OwnsSessionWorkingSetShared' : [ 0x271, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned char')]], 'OwnsProcessAddressSpaceExclusive' : [ 0x271, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned char')]], 'OwnsProcessAddressSpaceShared' : [ 0x271, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned char')]], 'SuppressSymbolLoad' : [ 0x271, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned char')]], 'Prefetching' : [ 0x271, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned char')]], 'OwnsVadExclusive' : [ 0x271, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned char')]], 'OwnsChangeControlAreaExclusive' : [ 0x271, ['BitField', dict(start_bit = 6, end_bit = 7, native_type='unsigned char')]], 'OwnsChangeControlAreaShared' : [ 0x271, ['BitField', dict(start_bit = 7, end_bit = 8, native_type='unsigned char')]], 'OwnsPagedPoolWorkingSetExclusive' : [ 0x272, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned char')]], 'OwnsPagedPoolWorkingSetShared' : [ 0x272, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned char')]], 'OwnsSystemPtesWorkingSetExclusive' : [ 0x272, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned char')]], 'OwnsSystemPtesWorkingSetShared' : [ 0x272, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned char')]], 'TrimTrigger' : [ 0x272, ['BitField', dict(start_bit = 4, end_bit = 6, native_type='unsigned char')]], 'Spare2' : [ 0x272, ['BitField', dict(start_bit = 6, end_bit = 8, native_type='unsigned char')]], 'PriorityRegionActive' : [ 0x273, ['unsigned char']], 'CacheManagerActive' : [ 0x274, ['unsigned char']], 'DisablePageFaultClustering' : [ 0x275, ['unsigned char']], 'ActiveFaultCount' : [ 0x276, ['unsigned char']], 'LockOrderState' : [ 0x277, ['unsigned char']], 'AlpcMessageId' : [ 0x278, ['unsigned long']], 'AlpcMessage' : [ 0x27c, ['pointer', ['void']]], 'AlpcReceiveAttributeSet' : [ 0x27c, ['unsigned long']], 'ExitStatus' : [ 0x280, ['long']], 'AlpcWaitListEntry' : [ 0x284, ['_LIST_ENTRY']], 'CacheManagerCount' : [ 0x28c, ['unsigned long']], 'IoBoostCount' : [ 0x290, ['unsigned long']], 'BoostList' : [ 0x294, ['_LIST_ENTRY']], 'DeboostList' : [ 0x29c, ['_LIST_ENTRY']], 'BoostListLock' : [ 0x2a4, ['unsigned long']], 'IrpListLock' : [ 0x2a8, ['unsigned long']], 'ReservedForSynchTracking' : [ 0x2ac, ['pointer', ['void']]], 'CmCallbackListHead' : [ 0x2b0, ['_SINGLE_LIST_ENTRY']], 'ActivityId' : [ 0x2b4, ['pointer', ['_GUID']]], 'WnfContext' : [ 0x2b8, ['pointer', ['void']]], 'SeLearningModeListHead' : [ 0x2bc, ['_SINGLE_LIST_ENTRY']], 'KernelStackReference' : [ 0x2c0, ['unsigned long']], } ], '_EPROCESS' : [ 0x2e8, { 'Pcb' : [ 0x0, ['_KPROCESS']], 'ProcessLock' : [ 0xa0, ['_EX_PUSH_LOCK']], 'CreateTime' : [ 0xa8, ['_LARGE_INTEGER']], 'RundownProtect' : [ 0xb0, ['_EX_RUNDOWN_REF']], 'UniqueProcessId' : [ 0xb4, ['pointer', ['void']]], 'ActiveProcessLinks' : [ 0xb8, ['_LIST_ENTRY']], 'Flags2' : [ 0xc0, ['unsigned long']], 'JobNotReallyActive' : [ 0xc0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]], 'AccountingFolded' : [ 0xc0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]], 'NewProcessReported' : [ 0xc0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]], 'ExitProcessReported' : [ 0xc0, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned long')]], 'ReportCommitChanges' : [ 0xc0, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned long')]], 'LastReportMemory' : [ 0xc0, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned long')]], 'NoWakeCharge' : [ 0xc0, ['BitField', dict(start_bit = 6, end_bit = 7, native_type='unsigned long')]], 'HandleTableRundown' : [ 0xc0, ['BitField', dict(start_bit = 7, end_bit = 8, native_type='unsigned long')]], 'NeedsHandleRundown' : [ 0xc0, ['BitField', dict(start_bit = 8, end_bit = 9, native_type='unsigned long')]], 'RefTraceEnabled' : [ 0xc0, ['BitField', dict(start_bit = 9, end_bit = 10, native_type='unsigned long')]], 'NumaAware' : [ 0xc0, ['BitField', dict(start_bit = 10, end_bit = 11, native_type='unsigned long')]], 'EmptyJobEvaluated' : [ 0xc0, ['BitField', dict(start_bit = 11, end_bit = 12, native_type='unsigned long')]], 'DefaultPagePriority' : [ 0xc0, ['BitField', dict(start_bit = 12, end_bit = 15, native_type='unsigned long')]], 'PrimaryTokenFrozen' : [ 0xc0, ['BitField', dict(start_bit = 15, end_bit = 16, native_type='unsigned long')]], 'ProcessVerifierTarget' : [ 0xc0, ['BitField', dict(start_bit = 16, end_bit = 17, native_type='unsigned long')]], 'StackRandomizationDisabled' : [ 0xc0, ['BitField', dict(start_bit = 17, end_bit = 18, native_type='unsigned long')]], 'AffinityPermanent' : [ 0xc0, ['BitField', dict(start_bit = 18, end_bit = 19, native_type='unsigned long')]], 'AffinityUpdateEnable' : [ 0xc0, ['BitField', dict(start_bit = 19, end_bit = 20, native_type='unsigned long')]], 'PropagateNode' : [ 0xc0, ['BitField', dict(start_bit = 20, end_bit = 21, native_type='unsigned long')]], 'ExplicitAffinity' : [ 0xc0, ['BitField', dict(start_bit = 21, end_bit = 22, native_type='unsigned long')]], 'ProcessExecutionState' : [ 0xc0, ['BitField', dict(start_bit = 22, end_bit = 24, native_type='unsigned long')]], 'DisallowStrippedImages' : [ 0xc0, ['BitField', dict(start_bit = 24, end_bit = 25, native_type='unsigned long')]], 'HighEntropyASLREnabled' : [ 0xc0, ['BitField', dict(start_bit = 25, end_bit = 26, native_type='unsigned long')]], 'ExtensionPointDisable' : [ 0xc0, ['BitField', dict(start_bit = 26, end_bit = 27, native_type='unsigned long')]], 'ForceRelocateImages' : [ 0xc0, ['BitField', dict(start_bit = 27, end_bit = 28, native_type='unsigned long')]], 'ProcessStateChangeRequest' : [ 0xc0, ['BitField', dict(start_bit = 28, end_bit = 30, native_type='unsigned long')]], 'ProcessStateChangeInProgress' : [ 0xc0, ['BitField', dict(start_bit = 30, end_bit = 31, native_type='unsigned long')]], 'DisallowWin32kSystemCalls' : [ 0xc0, ['BitField', dict(start_bit = 31, end_bit = 32, native_type='unsigned long')]], 'Flags' : [ 0xc4, ['unsigned long']], 'CreateReported' : [ 0xc4, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]], 'NoDebugInherit' : [ 0xc4, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]], 'ProcessExiting' : [ 0xc4, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]], 'ProcessDelete' : [ 0xc4, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned long')]], 'Wow64SplitPages' : [ 0xc4, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned long')]], 'VmDeleted' : [ 0xc4, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned long')]], 'OutswapEnabled' : [ 0xc4, ['BitField', dict(start_bit = 6, end_bit = 7, native_type='unsigned long')]], 'Outswapped' : [ 0xc4, ['BitField', dict(start_bit = 7, end_bit = 8, native_type='unsigned long')]], 'ForkFailed' : [ 0xc4, ['BitField', dict(start_bit = 8, end_bit = 9, native_type='unsigned long')]], 'Wow64VaSpace4Gb' : [ 0xc4, ['BitField', dict(start_bit = 9, end_bit = 10, native_type='unsigned long')]], 'AddressSpaceInitialized' : [ 0xc4, ['BitField', dict(start_bit = 10, end_bit = 12, native_type='unsigned long')]], 'SetTimerResolution' : [ 0xc4, ['BitField', dict(start_bit = 12, end_bit = 13, native_type='unsigned long')]], 'BreakOnTermination' : [ 0xc4, ['BitField', dict(start_bit = 13, end_bit = 14, native_type='unsigned long')]], 'DeprioritizeViews' : [ 0xc4, ['BitField', dict(start_bit = 14, end_bit = 15, native_type='unsigned long')]], 'WriteWatch' : [ 0xc4, ['BitField', dict(start_bit = 15, end_bit = 16, native_type='unsigned long')]], 'ProcessInSession' : [ 0xc4, ['BitField', dict(start_bit = 16, end_bit = 17, native_type='unsigned long')]], 'OverrideAddressSpace' : [ 0xc4, ['BitField', dict(start_bit = 17, end_bit = 18, native_type='unsigned long')]], 'HasAddressSpace' : [ 0xc4, ['BitField', dict(start_bit = 18, end_bit = 19, native_type='unsigned long')]], 'LaunchPrefetched' : [ 0xc4, ['BitField', dict(start_bit = 19, end_bit = 20, native_type='unsigned long')]], 'Background' : [ 0xc4, ['BitField', dict(start_bit = 20, end_bit = 21, native_type='unsigned long')]], 'VmTopDown' : [ 0xc4, ['BitField', dict(start_bit = 21, end_bit = 22, native_type='unsigned long')]], 'ImageNotifyDone' : [ 0xc4, ['BitField', dict(start_bit = 22, end_bit = 23, native_type='unsigned long')]], 'PdeUpdateNeeded' : [ 0xc4, ['BitField', dict(start_bit = 23, end_bit = 24, native_type='unsigned long')]], 'VdmAllowed' : [ 0xc4, ['BitField', dict(start_bit = 24, end_bit = 25, native_type='unsigned long')]], 'CrossSessionCreate' : [ 0xc4, ['BitField', dict(start_bit = 25, end_bit = 26, native_type='unsigned long')]], 'ProcessInserted' : [ 0xc4, ['BitField', dict(start_bit = 26, end_bit = 27, native_type='unsigned long')]], 'DefaultIoPriority' : [ 0xc4, ['BitField', dict(start_bit = 27, end_bit = 30, native_type='unsigned long')]], 'ProcessSelfDelete' : [ 0xc4, ['BitField', dict(start_bit = 30, end_bit = 31, native_type='unsigned long')]], 'SetTimerResolutionLink' : [ 0xc4, ['BitField', dict(start_bit = 31, end_bit = 32, native_type='unsigned long')]], 'ProcessQuotaUsage' : [ 0xc8, ['array', 2, ['unsigned long']]], 'ProcessQuotaPeak' : [ 0xd0, ['array', 2, ['unsigned long']]], 'PeakVirtualSize' : [ 0xd8, ['unsigned long']], 'VirtualSize' : [ 0xdc, ['unsigned long']], 'SessionProcessLinks' : [ 0xe0, ['_LIST_ENTRY']], 'ExceptionPortData' : [ 0xe8, ['pointer', ['void']]], 'ExceptionPortValue' : [ 0xe8, ['unsigned long']], 'ExceptionPortState' : [ 0xe8, ['BitField', dict(start_bit = 0, end_bit = 3, native_type='unsigned long')]], 'Token' : [ 0xec, ['_EX_FAST_REF']], 'WorkingSetPage' : [ 0xf0, ['unsigned long']], 'AddressCreationLock' : [ 0xf4, ['_EX_PUSH_LOCK']], 'RotateInProgress' : [ 0xf8, ['pointer', ['_ETHREAD']]], 'ForkInProgress' : [ 0xfc, ['pointer', ['_ETHREAD']]], 'HardwareTrigger' : [ 0x100, ['unsigned long']], 'CommitChargeJob' : [ 0x104, ['pointer', ['_EJOB']]], 'CloneRoot' : [ 0x108, ['pointer', ['_MM_AVL_TABLE']]], 'NumberOfPrivatePages' : [ 0x10c, ['unsigned long']], 'NumberOfLockedPages' : [ 0x110, ['unsigned long']], 'Win32Process' : [ 0x114, ['pointer', ['void']]], 'Job' : [ 0x118, ['pointer', ['_EJOB']]], 'SectionObject' : [ 0x11c, ['pointer', ['void']]], 'SectionBaseAddress' : [ 0x120, ['pointer', ['void']]], 'Cookie' : [ 0x124, ['unsigned long']], 'VdmObjects' : [ 0x128, ['pointer', ['void']]], 'WorkingSetWatch' : [ 0x12c, ['pointer', ['_PAGEFAULT_HISTORY']]], 'Win32WindowStation' : [ 0x130, ['pointer', ['void']]], 'InheritedFromUniqueProcessId' : [ 0x134, ['pointer', ['void']]], 'LdtInformation' : [ 0x138, ['pointer', ['void']]], 'CreatorProcess' : [ 0x13c, ['pointer', ['_EPROCESS']]], 'ConsoleHostProcess' : [ 0x13c, ['unsigned long']], 'Peb' : [ 0x140, ['pointer', ['_PEB']]], 'Session' : [ 0x144, ['pointer', ['void']]], 'AweInfo' : [ 0x148, ['pointer', ['void']]], 'QuotaBlock' : [ 0x14c, ['pointer', ['_EPROCESS_QUOTA_BLOCK']]], 'ObjectTable' : [ 0x150, ['pointer', ['_HANDLE_TABLE']]], 'DebugPort' : [ 0x154, ['pointer', ['void']]], 'PaeTop' : [ 0x158, ['pointer', ['void']]], 'DeviceMap' : [ 0x15c, ['pointer', ['void']]], 'EtwDataSource' : [ 0x160, ['pointer', ['void']]], 'PageDirectoryPte' : [ 0x168, ['unsigned long long']], 'ImageFileName' : [ 0x170, ['array', 15, ['unsigned char']]], 'PriorityClass' : [ 0x17f, ['unsigned char']], 'SecurityPort' : [ 0x180, ['pointer', ['void']]], 'SeAuditProcessCreationInfo' : [ 0x184, ['_SE_AUDIT_PROCESS_CREATION_INFO']], 'JobLinks' : [ 0x188, ['_LIST_ENTRY']], 'HighestUserAddress' : [ 0x190, ['pointer', ['void']]], 'ThreadListHead' : [ 0x194, ['_LIST_ENTRY']], 'ActiveThreads' : [ 0x19c, ['unsigned long']], 'ImagePathHash' : [ 0x1a0, ['unsigned long']], 'DefaultHardErrorProcessing' : [ 0x1a4, ['unsigned long']], 'LastThreadExitStatus' : [ 0x1a8, ['long']], 'PrefetchTrace' : [ 0x1ac, ['_EX_FAST_REF']], 'LockedPagesList' : [ 0x1b0, ['pointer', ['_MM_AVL_TABLE']]], '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']], 'CommitCharge' : [ 0x1ec, ['unsigned long']], 'CommitChargePeak' : [ 0x1f0, ['unsigned long']], 'Vm' : [ 0x1f4, ['_MMSUPPORT']], 'MmProcessLinks' : [ 0x264, ['_LIST_ENTRY']], 'ModifiedPageCount' : [ 0x26c, ['unsigned long']], 'ExitStatus' : [ 0x270, ['long']], 'VadRoot' : [ 0x274, ['_MM_AVL_TABLE']], 'VadPhysicalPages' : [ 0x28c, ['unsigned long']], 'VadPhysicalPagesLimit' : [ 0x290, ['unsigned long']], 'AlpcContext' : [ 0x294, ['_ALPC_PROCESS_CONTEXT']], 'TimerResolutionLink' : [ 0x2a4, ['_LIST_ENTRY']], 'TimerResolutionStackRecord' : [ 0x2ac, ['pointer', ['_PO_DIAG_STACK_RECORD']]], 'RequestedTimerResolution' : [ 0x2b0, ['unsigned long']], 'SmallestTimerResolution' : [ 0x2b4, ['unsigned long']], 'ExitTime' : [ 0x2b8, ['_LARGE_INTEGER']], 'ActiveThreadsHighWatermark' : [ 0x2c0, ['unsigned long']], 'LargePrivateVadCount' : [ 0x2c4, ['unsigned long']], 'ThreadListLock' : [ 0x2c8, ['_EX_PUSH_LOCK']], 'WnfContext' : [ 0x2cc, ['pointer', ['void']]], 'SectionMappingSize' : [ 0x2d0, ['unsigned long']], 'SignatureLevel' : [ 0x2d4, ['unsigned char']], 'SectionSignatureLevel' : [ 0x2d5, ['unsigned char']], 'SpareByte20' : [ 0x2d6, ['array', 2, ['unsigned char']]], 'KeepAliveCounter' : [ 0x2d8, ['unsigned long']], 'DiskCounters' : [ 0x2dc, ['pointer', ['_PROCESS_DISK_COUNTERS']]], 'LastFreezeInterruptTime' : [ 0x2e0, ['unsigned long long']], } ], '_KPROCESS' : [ 0xa0, { 'Header' : [ 0x0, ['_DISPATCHER_HEADER']], 'ProfileListHead' : [ 0x10, ['_LIST_ENTRY']], 'DirectoryTableBase' : [ 0x18, ['unsigned long']], 'LdtDescriptor' : [ 0x1c, ['_KGDTENTRY']], 'Int21Descriptor' : [ 0x24, ['_KIDTENTRY']], 'ThreadListHead' : [ 0x2c, ['_LIST_ENTRY']], 'ProcessLock' : [ 0x34, ['unsigned long']], 'Affinity' : [ 0x38, ['_KAFFINITY_EX']], 'ReadyListHead' : [ 0x44, ['_LIST_ENTRY']], 'SwapListEntry' : [ 0x4c, ['_SINGLE_LIST_ENTRY']], 'ActiveProcessors' : [ 0x50, ['_KAFFINITY_EX']], 'AutoAlignment' : [ 0x5c, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='long')]], 'DisableBoost' : [ 0x5c, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='long')]], 'DisableQuantum' : [ 0x5c, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='long')]], 'AffinitySet' : [ 0x5c, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='long')]], 'DeepFreeze' : [ 0x5c, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned long')]], 'TimerVirtualization' : [ 0x5c, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned long')]], 'ActiveGroupsMask' : [ 0x5c, ['BitField', dict(start_bit = 6, end_bit = 7, native_type='unsigned long')]], 'ReservedFlags' : [ 0x5c, ['BitField', dict(start_bit = 7, end_bit = 32, native_type='long')]], 'ProcessFlags' : [ 0x5c, ['long']], 'BasePriority' : [ 0x60, ['unsigned char']], 'QuantumReset' : [ 0x61, ['unsigned char']], 'Visited' : [ 0x62, ['unsigned char']], 'Flags' : [ 0x63, ['_KEXECUTE_OPTIONS']], 'ThreadSeed' : [ 0x64, ['array', 1, ['unsigned long']]], 'IdealNode' : [ 0x68, ['array', 1, ['unsigned short']]], 'IdealGlobalNode' : [ 0x6a, ['unsigned short']], 'Spare1' : [ 0x6c, ['unsigned short']], 'IopmOffset' : [ 0x6e, ['unsigned short']], 'SchedulingGroup' : [ 0x70, ['pointer', ['_KSCHEDULING_GROUP']]], 'StackCount' : [ 0x74, ['_KSTACK_COUNT']], 'ProcessListEntry' : [ 0x78, ['_LIST_ENTRY']], 'CycleTime' : [ 0x80, ['unsigned long long']], 'ContextSwitches' : [ 0x88, ['unsigned long long']], 'FreezeCount' : [ 0x90, ['unsigned long']], 'KernelTime' : [ 0x94, ['unsigned long']], 'UserTime' : [ 0x98, ['unsigned long']], 'VdmTrapcHandler' : [ 0x9c, ['pointer', ['void']]], } ], '__unnamed_133f' : [ 0x4, { 'MasterIrp' : [ 0x0, ['pointer', ['_IRP']]], 'IrpCount' : [ 0x0, ['long']], 'SystemBuffer' : [ 0x0, ['pointer', ['void']]], } ], '__unnamed_1345' : [ 0x8, { 'UserApcRoutine' : [ 0x0, ['pointer', ['void']]], 'IssuingProcess' : [ 0x0, ['pointer', ['void']]], 'UserApcContext' : [ 0x4, ['pointer', ['void']]], } ], '__unnamed_1347' : [ 0x8, { 'AsynchronousParameters' : [ 0x0, ['__unnamed_1345']], 'AllocationSize' : [ 0x0, ['_LARGE_INTEGER']], } ], '__unnamed_1352' : [ 0x2c, { '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']]], 'IrpExtension' : [ 0x28, ['pointer', ['void']]], } ], '__unnamed_1354' : [ 0x30, { 'Overlay' : [ 0x0, ['__unnamed_1352']], '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_133f']], '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_1347']], 'CancelRoutine' : [ 0x38, ['pointer', ['void']]], 'UserBuffer' : [ 0x3c, ['pointer', ['void']]], 'Tail' : [ 0x40, ['__unnamed_1354']], } ], '__unnamed_135b' : [ 0x10, { 'SecurityContext' : [ 0x0, ['pointer', ['_IO_SECURITY_CONTEXT']]], 'Options' : [ 0x4, ['unsigned long']], 'FileAttributes' : [ 0x8, ['unsigned short']], 'ShareAccess' : [ 0xa, ['unsigned short']], 'EaLength' : [ 0xc, ['unsigned long']], } ], '__unnamed_135f' : [ 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_1363' : [ 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_1365' : [ 0x10, { 'Length' : [ 0x0, ['unsigned long']], 'Key' : [ 0x4, ['unsigned long']], 'ByteOffset' : [ 0x8, ['_LARGE_INTEGER']], } ], '__unnamed_1369' : [ 0x10, { 'Length' : [ 0x0, ['unsigned long']], 'FileName' : [ 0x4, ['pointer', ['_UNICODE_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: 'FileIoCompletionNotificationInformation', 42: 'FileIoStatusBlockRangeInformation', 43: 'FileIoPriorityHintInformation', 44: 'FileSfioReserveInformation', 45: 'FileSfioVolumeInformation', 46: 'FileHardLinkInformation', 47: 'FileProcessIdsUsingFileInformation', 48: 'FileNormalizedNameInformation', 49: 'FileNetworkPhysicalNameInformation', 50: 'FileIdGlobalTxDirectoryInformation', 51: 'FileIsRemoteDeviceInformation', 52: 'FileAttributeCacheInformation', 53: 'FileNumaNodeInformation', 54: 'FileStandardLinkInformation', 55: 'FileRemoteProtocolInformation', 56: 'FileRenameInformationBypassAccessCheck', 57: 'FileLinkInformationBypassAccessCheck', 58: 'FileVolumeNameInformation', 59: 'FileIdInformation', 60: 'FileIdExtdDirectoryInformation', 61: 'FileMaximumInformation'})]], 'FileIndex' : [ 0xc, ['unsigned long']], } ], '__unnamed_136b' : [ 0x8, { 'Length' : [ 0x0, ['unsigned long']], 'CompletionFilter' : [ 0x4, ['unsigned long']], } ], '__unnamed_136d' : [ 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: 'FileIoCompletionNotificationInformation', 42: 'FileIoStatusBlockRangeInformation', 43: 'FileIoPriorityHintInformation', 44: 'FileSfioReserveInformation', 45: 'FileSfioVolumeInformation', 46: 'FileHardLinkInformation', 47: 'FileProcessIdsUsingFileInformation', 48: 'FileNormalizedNameInformation', 49: 'FileNetworkPhysicalNameInformation', 50: 'FileIdGlobalTxDirectoryInformation', 51: 'FileIsRemoteDeviceInformation', 52: 'FileAttributeCacheInformation', 53: 'FileNumaNodeInformation', 54: 'FileStandardLinkInformation', 55: 'FileRemoteProtocolInformation', 56: 'FileRenameInformationBypassAccessCheck', 57: 'FileLinkInformationBypassAccessCheck', 58: 'FileVolumeNameInformation', 59: 'FileIdInformation', 60: 'FileIdExtdDirectoryInformation', 61: 'FileMaximumInformation'})]], } ], '__unnamed_136f' : [ 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: 'FileIoCompletionNotificationInformation', 42: 'FileIoStatusBlockRangeInformation', 43: 'FileIoPriorityHintInformation', 44: 'FileSfioReserveInformation', 45: 'FileSfioVolumeInformation', 46: 'FileHardLinkInformation', 47: 'FileProcessIdsUsingFileInformation', 48: 'FileNormalizedNameInformation', 49: 'FileNetworkPhysicalNameInformation', 50: 'FileIdGlobalTxDirectoryInformation', 51: 'FileIsRemoteDeviceInformation', 52: 'FileAttributeCacheInformation', 53: 'FileNumaNodeInformation', 54: 'FileStandardLinkInformation', 55: 'FileRemoteProtocolInformation', 56: 'FileRenameInformationBypassAccessCheck', 57: 'FileLinkInformationBypassAccessCheck', 58: 'FileVolumeNameInformation', 59: 'FileIdInformation', 60: 'FileIdExtdDirectoryInformation', 61: 'FileMaximumInformation'})]], 'FileObject' : [ 0x8, ['pointer', ['_FILE_OBJECT']]], 'ReplaceIfExists' : [ 0xc, ['unsigned char']], 'AdvanceOnly' : [ 0xd, ['unsigned char']], 'ClusterCount' : [ 0xc, ['unsigned long']], 'DeleteHandle' : [ 0xc, ['pointer', ['void']]], } ], '__unnamed_1371' : [ 0x10, { 'Length' : [ 0x0, ['unsigned long']], 'EaList' : [ 0x4, ['pointer', ['void']]], 'EaListLength' : [ 0x8, ['unsigned long']], 'EaIndex' : [ 0xc, ['unsigned long']], } ], '__unnamed_1373' : [ 0x4, { 'Length' : [ 0x0, ['unsigned long']], } ], '__unnamed_1377' : [ 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: 'FileFsVolumeFlagsInformation', 11: 'FileFsSectorSizeInformation', 12: 'FileFsDataCopyInformation', 13: 'FileFsMaximumInformation'})]], } ], '__unnamed_1379' : [ 0x10, { 'OutputBufferLength' : [ 0x0, ['unsigned long']], 'InputBufferLength' : [ 0x4, ['unsigned long']], 'FsControlCode' : [ 0x8, ['unsigned long']], 'Type3InputBuffer' : [ 0xc, ['pointer', ['void']]], } ], '__unnamed_137c' : [ 0x10, { 'Length' : [ 0x0, ['pointer', ['_LARGE_INTEGER']]], 'Key' : [ 0x4, ['unsigned long']], 'ByteOffset' : [ 0x8, ['_LARGE_INTEGER']], } ], '__unnamed_137e' : [ 0x10, { 'OutputBufferLength' : [ 0x0, ['unsigned long']], 'InputBufferLength' : [ 0x4, ['unsigned long']], 'IoControlCode' : [ 0x8, ['unsigned long']], 'Type3InputBuffer' : [ 0xc, ['pointer', ['void']]], } ], '__unnamed_1380' : [ 0x8, { 'SecurityInformation' : [ 0x0, ['unsigned long']], 'Length' : [ 0x4, ['unsigned long']], } ], '__unnamed_1382' : [ 0x8, { 'SecurityInformation' : [ 0x0, ['unsigned long']], 'SecurityDescriptor' : [ 0x4, ['pointer', ['void']]], } ], '__unnamed_1386' : [ 0x8, { 'Vpb' : [ 0x0, ['pointer', ['_VPB']]], 'DeviceObject' : [ 0x4, ['pointer', ['_DEVICE_OBJECT']]], } ], '__unnamed_138a' : [ 0x4, { 'Srb' : [ 0x0, ['pointer', ['_SCSI_REQUEST_BLOCK']]], } ], '__unnamed_138e' : [ 0x10, { 'Length' : [ 0x0, ['unsigned long']], 'StartSid' : [ 0x4, ['pointer', ['void']]], 'SidList' : [ 0x8, ['pointer', ['_FILE_GET_QUOTA_INFORMATION']]], 'SidListLength' : [ 0xc, ['unsigned long']], } ], '__unnamed_1392' : [ 0x4, { 'Type' : [ 0x0, ['Enumeration', dict(target = 'long', choices = {0: 'BusRelations', 1: 'EjectionRelations', 2: 'PowerRelations', 3: 'RemovalRelations', 4: 'TargetDeviceRelation', 5: 'SingleBusRelations', 6: 'TransportRelations'})]], } ], '__unnamed_1396' : [ 0x10, { 'InterfaceType' : [ 0x0, ['pointer', ['_GUID']]], 'Size' : [ 0x4, ['unsigned short']], 'Version' : [ 0x6, ['unsigned short']], 'Interface' : [ 0x8, ['pointer', ['_INTERFACE']]], 'InterfaceSpecificData' : [ 0xc, ['pointer', ['void']]], } ], '__unnamed_139a' : [ 0x4, { 'Capabilities' : [ 0x0, ['pointer', ['_DEVICE_CAPABILITIES']]], } ], '__unnamed_139e' : [ 0x4, { 'IoResourceRequirementList' : [ 0x0, ['pointer', ['_IO_RESOURCE_REQUIREMENTS_LIST']]], } ], '__unnamed_13a0' : [ 0x10, { 'WhichSpace' : [ 0x0, ['unsigned long']], 'Buffer' : [ 0x4, ['pointer', ['void']]], 'Offset' : [ 0x8, ['unsigned long']], 'Length' : [ 0xc, ['unsigned long']], } ], '__unnamed_13a2' : [ 0x1, { 'Lock' : [ 0x0, ['unsigned char']], } ], '__unnamed_13a6' : [ 0x4, { 'IdType' : [ 0x0, ['Enumeration', dict(target = 'long', choices = {0: 'BusQueryDeviceID', 1: 'BusQueryHardwareIDs', 2: 'BusQueryCompatibleIDs', 3: 'BusQueryInstanceID', 4: 'BusQueryDeviceSerialNumber', 5: 'BusQueryContainerID'})]], } ], '__unnamed_13aa' : [ 0x8, { 'DeviceTextType' : [ 0x0, ['Enumeration', dict(target = 'long', choices = {0: 'DeviceTextDescription', 1: 'DeviceTextLocationInformation'})]], 'LocaleId' : [ 0x4, ['unsigned long']], } ], '__unnamed_13ae' : [ 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', 4: 'DeviceUsageTypeBoot', 5: 'DeviceUsageTypePostDisplay'})]], } ], '__unnamed_13b2' : [ 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_13b6' : [ 0x4, { 'PowerSequence' : [ 0x0, ['pointer', ['_POWER_SEQUENCE']]], } ], '__unnamed_13be' : [ 0x10, { 'SystemContext' : [ 0x0, ['unsigned long']], 'SystemPowerStateContext' : [ 0x0, ['_SYSTEM_POWER_STATE_CONTEXT']], '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_13c2' : [ 0x8, { 'AllocatedResources' : [ 0x0, ['pointer', ['_CM_RESOURCE_LIST']]], 'AllocatedResourcesTranslated' : [ 0x4, ['pointer', ['_CM_RESOURCE_LIST']]], } ], '__unnamed_13c4' : [ 0x10, { 'ProviderId' : [ 0x0, ['unsigned long']], 'DataPath' : [ 0x4, ['pointer', ['void']]], 'BufferSize' : [ 0x8, ['unsigned long']], 'Buffer' : [ 0xc, ['pointer', ['void']]], } ], '__unnamed_13c6' : [ 0x10, { 'Argument1' : [ 0x0, ['pointer', ['void']]], 'Argument2' : [ 0x4, ['pointer', ['void']]], 'Argument3' : [ 0x8, ['pointer', ['void']]], 'Argument4' : [ 0xc, ['pointer', ['void']]], } ], '__unnamed_13c8' : [ 0x10, { 'Create' : [ 0x0, ['__unnamed_135b']], 'CreatePipe' : [ 0x0, ['__unnamed_135f']], 'CreateMailslot' : [ 0x0, ['__unnamed_1363']], 'Read' : [ 0x0, ['__unnamed_1365']], 'Write' : [ 0x0, ['__unnamed_1365']], 'QueryDirectory' : [ 0x0, ['__unnamed_1369']], 'NotifyDirectory' : [ 0x0, ['__unnamed_136b']], 'QueryFile' : [ 0x0, ['__unnamed_136d']], 'SetFile' : [ 0x0, ['__unnamed_136f']], 'QueryEa' : [ 0x0, ['__unnamed_1371']], 'SetEa' : [ 0x0, ['__unnamed_1373']], 'QueryVolume' : [ 0x0, ['__unnamed_1377']], 'SetVolume' : [ 0x0, ['__unnamed_1377']], 'FileSystemControl' : [ 0x0, ['__unnamed_1379']], 'LockControl' : [ 0x0, ['__unnamed_137c']], 'DeviceIoControl' : [ 0x0, ['__unnamed_137e']], 'QuerySecurity' : [ 0x0, ['__unnamed_1380']], 'SetSecurity' : [ 0x0, ['__unnamed_1382']], 'MountVolume' : [ 0x0, ['__unnamed_1386']], 'VerifyVolume' : [ 0x0, ['__unnamed_1386']], 'Scsi' : [ 0x0, ['__unnamed_138a']], 'QueryQuota' : [ 0x0, ['__unnamed_138e']], 'SetQuota' : [ 0x0, ['__unnamed_1373']], 'QueryDeviceRelations' : [ 0x0, ['__unnamed_1392']], 'QueryInterface' : [ 0x0, ['__unnamed_1396']], 'DeviceCapabilities' : [ 0x0, ['__unnamed_139a']], 'FilterResourceRequirements' : [ 0x0, ['__unnamed_139e']], 'ReadWriteConfig' : [ 0x0, ['__unnamed_13a0']], 'SetLock' : [ 0x0, ['__unnamed_13a2']], 'QueryId' : [ 0x0, ['__unnamed_13a6']], 'QueryDeviceText' : [ 0x0, ['__unnamed_13aa']], 'UsageNotification' : [ 0x0, ['__unnamed_13ae']], 'WaitWake' : [ 0x0, ['__unnamed_13b2']], 'PowerSequence' : [ 0x0, ['__unnamed_13b6']], 'Power' : [ 0x0, ['__unnamed_13be']], 'StartDevice' : [ 0x0, ['__unnamed_13c2']], 'WMI' : [ 0x0, ['__unnamed_13c4']], 'Others' : [ 0x0, ['__unnamed_13c6']], } ], '_IO_STACK_LOCATION' : [ 0x24, { 'MajorFunction' : [ 0x0, ['unsigned char']], 'MinorFunction' : [ 0x1, ['unsigned char']], 'Flags' : [ 0x2, ['unsigned char']], 'Control' : [ 0x3, ['unsigned char']], 'Parameters' : [ 0x4, ['__unnamed_13c8']], 'DeviceObject' : [ 0x14, ['pointer', ['_DEVICE_OBJECT']]], 'FileObject' : [ 0x18, ['pointer', ['_FILE_OBJECT']]], 'CompletionRoutine' : [ 0x1c, ['pointer', ['void']]], 'Context' : [ 0x20, ['pointer', ['void']]], } ], '__unnamed_13de' : [ 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_13de']], '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']]], } ], '_KDPC' : [ 0x20, { 'Type' : [ 0x0, ['unsigned char']], 'Importance' : [ 0x1, ['unsigned char']], 'Number' : [ 0x2, ['unsigned short']], 'DpcListEntry' : [ 0x4, ['_LIST_ENTRY']], 'DeferredRoutine' : [ 0xc, ['pointer', ['void']]], 'DeferredContext' : [ 0x10, ['pointer', ['void']]], 'SystemArgument1' : [ 0x14, ['pointer', ['void']]], 'SystemArgument2' : [ 0x18, ['pointer', ['void']]], 'DpcData' : [ 0x1c, ['pointer', ['void']]], } ], '_IO_DRIVER_CREATE_CONTEXT' : [ 0x10, { 'Size' : [ 0x0, ['short']], 'ExtraCreateParameter' : [ 0x4, ['pointer', ['_ECP_LIST']]], 'DeviceObjectHint' : [ 0x8, ['pointer', ['void']]], 'TxnParameters' : [ 0xc, ['pointer', ['_TXN_PARAMETER_BLOCK']]], } ], '_IO_PRIORITY_INFO' : [ 0x10, { 'Size' : [ 0x0, ['unsigned long']], 'ThreadPriority' : [ 0x4, ['unsigned long']], 'PagePriority' : [ 0x8, ['unsigned long']], 'IoPriority' : [ 0xc, ['Enumeration', dict(target = 'long', choices = {0: 'IoPriorityVeryLow', 1: 'IoPriorityLow', 2: 'IoPriorityNormal', 3: 'IoPriorityHigh', 4: 'IoPriorityCritical', 5: 'MaxIoPriorityTypes'})]], } ], '_OBJECT_HANDLE_INFORMATION' : [ 0x8, { 'HandleAttributes' : [ 0x0, ['unsigned long']], 'GrantedAccess' : [ 0x4, ['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']], } ], '_EVENT_DATA_DESCRIPTOR' : [ 0x10, { 'Ptr' : [ 0x0, ['unsigned long long']], 'Size' : [ 0x8, ['unsigned long']], 'Reserved' : [ 0xc, ['unsigned long']], } ], '_EVENT_DESCRIPTOR' : [ 0x10, { 'Id' : [ 0x0, ['unsigned short']], 'Version' : [ 0x2, ['unsigned char']], 'Channel' : [ 0x3, ['unsigned char']], 'Level' : [ 0x4, ['unsigned char']], 'Opcode' : [ 0x5, ['unsigned char']], 'Task' : [ 0x6, ['unsigned short']], 'Keyword' : [ 0x8, ['unsigned long long']], } ], '_EVENT_RECORD' : [ 0x68, { 'EventHeader' : [ 0x0, ['_EVENT_HEADER']], 'BufferContext' : [ 0x50, ['_ETW_BUFFER_CONTEXT']], 'ExtendedDataCount' : [ 0x54, ['unsigned short']], 'UserDataLength' : [ 0x56, ['unsigned short']], 'ExtendedData' : [ 0x58, ['pointer', ['_EVENT_HEADER_EXTENDED_DATA_ITEM']]], 'UserData' : [ 0x5c, ['pointer', ['void']]], 'UserContext' : [ 0x60, ['pointer', ['void']]], } ], '_PERFINFO_GROUPMASK' : [ 0x20, { 'Masks' : [ 0x0, ['array', 8, ['unsigned long']]], } ], '_FILE_OBJECT' : [ 0x80, { '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']]], 'IrpListLock' : [ 0x70, ['unsigned long']], 'IrpList' : [ 0x74, ['_LIST_ENTRY']], 'FileObjectExtension' : [ 0x7c, ['pointer', ['void']]], } ], '_EX_RUNDOWN_REF' : [ 0x4, { 'Count' : [ 0x0, ['unsigned long']], 'Ptr' : [ 0x0, ['pointer', ['void']]], } ], '_MM_PAGE_ACCESS_INFO_HEADER' : [ 0x38, { 'Link' : [ 0x0, ['_SINGLE_LIST_ENTRY']], 'Type' : [ 0x4, ['Enumeration', dict(target = 'long', choices = {0: 'MmPteAccessType', 1: 'MmCcReadAheadType', 2: 'MmPfnRepurposeType', 3: 'MmMaximumPageAccessType'})]], 'EmptySequenceNumber' : [ 0x8, ['unsigned long']], 'CurrentFileIndex' : [ 0x8, ['unsigned long']], 'CreateTime' : [ 0x10, ['unsigned long long']], 'EmptyTime' : [ 0x18, ['unsigned long long']], 'TempEntry' : [ 0x18, ['pointer', ['_MM_PAGE_ACCESS_INFO']]], 'PageEntry' : [ 0x20, ['pointer', ['_MM_PAGE_ACCESS_INFO']]], 'FileEntry' : [ 0x24, ['pointer', ['unsigned long']]], 'FirstFileEntry' : [ 0x28, ['pointer', ['unsigned long']]], 'Process' : [ 0x2c, ['pointer', ['_EPROCESS']]], 'SessionId' : [ 0x30, ['unsigned long']], 'PageFrameEntry' : [ 0x20, ['pointer', ['unsigned long']]], 'LastPageFrameEntry' : [ 0x24, ['pointer', ['unsigned long']]], } ], '_WHEA_ERROR_PACKET_V2' : [ 0x50, { 'Signature' : [ 0x0, ['unsigned long']], 'Version' : [ 0x4, ['unsigned long']], 'Length' : [ 0x8, ['unsigned long']], 'Flags' : [ 0xc, ['_WHEA_ERROR_PACKET_FLAGS']], 'ErrorType' : [ 0x10, ['Enumeration', dict(target = 'long', choices = {0: 'WheaErrTypeProcessor', 1: 'WheaErrTypeMemory', 2: 'WheaErrTypePCIExpress', 3: 'WheaErrTypeNMI', 4: 'WheaErrTypePCIXBus', 5: 'WheaErrTypePCIXDevice', 6: 'WheaErrTypeGeneric'})]], 'ErrorSeverity' : [ 0x14, ['Enumeration', dict(target = 'long', choices = {0: 'WheaErrSevRecoverable', 1: 'WheaErrSevFatal', 2: 'WheaErrSevCorrected', 3: 'WheaErrSevInformational'})]], 'ErrorSourceId' : [ 0x18, ['unsigned long']], 'ErrorSourceType' : [ 0x1c, ['Enumeration', dict(target = 'long', choices = {0: 'WheaErrSrcTypeMCE', 1: 'WheaErrSrcTypeCMC', 2: 'WheaErrSrcTypeCPE', 3: 'WheaErrSrcTypeNMI', 4: 'WheaErrSrcTypePCIe', 5: 'WheaErrSrcTypeGeneric', 6: 'WheaErrSrcTypeINIT', 7: 'WheaErrSrcTypeBOOT', 8: 'WheaErrSrcTypeSCIGeneric', 9: 'WheaErrSrcTypeIPFMCA', 10: 'WheaErrSrcTypeIPFCMC', 11: 'WheaErrSrcTypeIPFCPE', 12: 'WheaErrSrcTypeMax'})]], 'NotifyType' : [ 0x20, ['_GUID']], 'Context' : [ 0x30, ['unsigned long long']], 'DataFormat' : [ 0x38, ['Enumeration', dict(target = 'long', choices = {0: 'WheaDataFormatIPFSalRecord', 1: 'WheaDataFormatXPFMCA', 2: 'WheaDataFormatMemory', 3: 'WheaDataFormatPCIExpress', 4: 'WheaDataFormatNMIPort', 5: 'WheaDataFormatPCIXBus', 6: 'WheaDataFormatPCIXDevice', 7: 'WheaDataFormatGeneric', 8: 'WheaDataFormatMax'})]], 'Reserved1' : [ 0x3c, ['unsigned long']], 'DataOffset' : [ 0x40, ['unsigned long']], 'DataLength' : [ 0x44, ['unsigned long']], 'PshedDataOffset' : [ 0x48, ['unsigned long']], 'PshedDataLength' : [ 0x4c, ['unsigned long']], } ], '_WHEA_ERROR_RECORD' : [ 0xc8, { 'Header' : [ 0x0, ['_WHEA_ERROR_RECORD_HEADER']], 'SectionDescriptor' : [ 0x80, ['array', 1, ['_WHEA_ERROR_RECORD_SECTION_DESCRIPTOR']]], } ], '_WHEA_ERROR_RECORD_SECTION_DESCRIPTOR' : [ 0x48, { 'SectionOffset' : [ 0x0, ['unsigned long']], 'SectionLength' : [ 0x4, ['unsigned long']], 'Revision' : [ 0x8, ['_WHEA_REVISION']], 'ValidBits' : [ 0xa, ['_WHEA_ERROR_RECORD_SECTION_DESCRIPTOR_VALIDBITS']], 'Reserved' : [ 0xb, ['unsigned char']], 'Flags' : [ 0xc, ['_WHEA_ERROR_RECORD_SECTION_DESCRIPTOR_FLAGS']], 'SectionType' : [ 0x10, ['_GUID']], 'FRUId' : [ 0x20, ['_GUID']], 'SectionSeverity' : [ 0x30, ['Enumeration', dict(target = 'long', choices = {0: 'WheaErrSevRecoverable', 1: 'WheaErrSevFatal', 2: 'WheaErrSevCorrected', 3: 'WheaErrSevInformational'})]], 'FRUText' : [ 0x34, ['array', 20, ['unsigned char']]], } ], '_GUID' : [ 0x10, { 'Data1' : [ 0x0, ['unsigned long']], 'Data2' : [ 0x4, ['unsigned short']], 'Data3' : [ 0x6, ['unsigned short']], 'Data4' : [ 0x8, ['array', 8, ['unsigned char']]], } ], '_FSRTL_ADVANCED_FCB_HEADER' : [ 0x40, { 'NodeTypeCode' : [ 0x0, ['short']], 'NodeByteSize' : [ 0x2, ['short']], 'Flags' : [ 0x4, ['unsigned char']], 'IsFastIoPossible' : [ 0x5, ['unsigned char']], 'Flags2' : [ 0x6, ['unsigned char']], 'Reserved' : [ 0x7, ['BitField', dict(start_bit = 0, end_bit = 4, native_type='unsigned char')]], 'Version' : [ 0x7, ['BitField', dict(start_bit = 4, end_bit = 8, native_type='unsigned char')]], 'Resource' : [ 0x8, ['pointer', ['_ERESOURCE']]], 'PagingIoResource' : [ 0xc, ['pointer', ['_ERESOURCE']]], 'AllocationSize' : [ 0x10, ['_LARGE_INTEGER']], 'FileSize' : [ 0x18, ['_LARGE_INTEGER']], 'ValidDataLength' : [ 0x20, ['_LARGE_INTEGER']], 'FastMutex' : [ 0x28, ['pointer', ['_FAST_MUTEX']]], 'FilterContexts' : [ 0x2c, ['_LIST_ENTRY']], 'PushLock' : [ 0x34, ['_EX_PUSH_LOCK']], 'FileContextSupportPointer' : [ 0x38, ['pointer', ['pointer', ['void']]]], 'Oplock' : [ 0x3c, ['pointer', ['void']]], 'ReservedForRemote' : [ 0x3c, ['pointer', ['void']]], } ], '_iobuf' : [ 0x20, { '_ptr' : [ 0x0, ['pointer', ['unsigned char']]], '_cnt' : [ 0x4, ['long']], '_base' : [ 0x8, ['pointer', ['unsigned char']]], '_flag' : [ 0xc, ['long']], '_file' : [ 0x10, ['long']], '_charbuf' : [ 0x14, ['long']], '_bufsiz' : [ 0x18, ['long']], '_tmpfname' : [ 0x1c, ['pointer', ['unsigned char']]], } ], '__unnamed_156c' : [ 0x8, { 'Long' : [ 0x0, ['unsigned long long']], 'VolatileLong' : [ 0x0, ['unsigned long long']], 'HighLow' : [ 0x0, ['_MMPTE_HIGHLOW']], 'Flush' : [ 0x0, ['_HARDWARE_PTE']], 'Hard' : [ 0x0, ['_MMPTE_HARDWARE']], 'Proto' : [ 0x0, ['_MMPTE_PROTOTYPE']], 'Soft' : [ 0x0, ['_MMPTE_SOFTWARE']], 'TimeStamp' : [ 0x0, ['_MMPTE_TIMESTAMP']], 'Trans' : [ 0x0, ['_MMPTE_TRANSITION']], 'Subsect' : [ 0x0, ['_MMPTE_SUBSECTION']], 'List' : [ 0x0, ['_MMPTE_LIST']], } ], '_MMPTE' : [ 0x8, { 'u' : [ 0x0, ['__unnamed_156c']], } ], '_ERESOURCE' : [ 0x38, { 'SystemResourcesList' : [ 0x0, ['_LIST_ENTRY']], 'OwnerTable' : [ 0x8, ['pointer', ['_OWNER_ENTRY']]], 'ActiveCount' : [ 0xc, ['short']], 'Flag' : [ 0xe, ['unsigned short']], 'ReservedLowFlags' : [ 0xe, ['unsigned char']], 'WaiterPriority' : [ 0xf, ['unsigned char']], 'SharedWaiters' : [ 0x10, ['pointer', ['_KSEMAPHORE']]], 'ExclusiveWaiters' : [ 0x14, ['pointer', ['_KEVENT']]], 'OwnerEntry' : [ 0x18, ['_OWNER_ENTRY']], 'ActiveEntries' : [ 0x20, ['unsigned long']], 'ContentionCount' : [ 0x24, ['unsigned long']], 'NumberOfSharedWaiters' : [ 0x28, ['unsigned long']], 'NumberOfExclusiveWaiters' : [ 0x2c, ['unsigned long']], 'Address' : [ 0x30, ['pointer', ['void']]], 'CreatorBackTraceIndex' : [ 0x30, ['unsigned long']], 'SpinLock' : [ 0x34, ['unsigned long']], } ], '_MI_CACHED_PTE' : [ 0x8, { 'GlobalTimeStamp' : [ 0x0, ['unsigned long']], 'PteIndex' : [ 0x4, ['unsigned long']], 'Long' : [ 0x0, ['long long']], } ], '_KLOCK_QUEUE_HANDLE' : [ 0xc, { 'LockQueue' : [ 0x0, ['_KSPIN_LOCK_QUEUE']], 'OldIrql' : [ 0x8, ['unsigned char']], } ], '_MMPFNLIST' : [ 0x14, { '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']], 'Lock' : [ 0x10, ['unsigned long']], } ], '__unnamed_15a8' : [ 0x4, { 'Flink' : [ 0x0, ['unsigned long']], 'WsIndex' : [ 0x0, ['unsigned long']], 'Event' : [ 0x0, ['pointer', ['_KEVENT']]], 'Next' : [ 0x0, ['pointer', ['void']]], 'VolatileNext' : [ 0x0, ['pointer', ['void']]], 'KernelStackOwner' : [ 0x0, ['pointer', ['_KTHREAD']]], 'NextStackPfn' : [ 0x0, ['_SINGLE_LIST_ENTRY']], } ], '__unnamed_15ac' : [ 0x4, { 'Blink' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 25, native_type='unsigned long')]], 'TbFlushStamp' : [ 0x0, ['BitField', dict(start_bit = 25, end_bit = 29, native_type='unsigned long')]], 'SpareBlink' : [ 0x0, ['BitField', dict(start_bit = 29, end_bit = 32, native_type='unsigned long')]], 'ImageProtoPte' : [ 0x0, ['pointer', ['_MMPTE']]], 'ShareCount' : [ 0x0, ['unsigned long']], } ], '__unnamed_15af' : [ 0x4, { 'ReferenceCount' : [ 0x0, ['unsigned short']], 'VolatileReferenceCount' : [ 0x0, ['short']], 'ShortFlags' : [ 0x2, ['unsigned short']], 'VolatileShortFlags' : [ 0x2, ['unsigned short']], } ], '__unnamed_15b1' : [ 0x4, { 'ReferenceCount' : [ 0x0, ['unsigned short']], 'e1' : [ 0x2, ['_MMPFNENTRY']], 'e2' : [ 0x0, ['__unnamed_15af']], } ], '__unnamed_15b5' : [ 0x4, { 'PteFrame' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 25, native_type='unsigned long')]], 'PageIdentity' : [ 0x0, ['BitField', dict(start_bit = 25, end_bit = 27, native_type='unsigned long')]], 'PrototypePte' : [ 0x0, ['BitField', dict(start_bit = 27, end_bit = 28, native_type='unsigned long')]], 'PageColor' : [ 0x0, ['BitField', dict(start_bit = 28, end_bit = 32, native_type='unsigned long')]], 'EntireField' : [ 0x0, ['unsigned long']], } ], '_MMPFN' : [ 0x1c, { 'u1' : [ 0x0, ['__unnamed_15a8']], 'u2' : [ 0x4, ['__unnamed_15ac']], 'PteAddress' : [ 0x8, ['pointer', ['_MMPTE']]], 'VolatilePteAddress' : [ 0x8, ['pointer', ['void']]], 'Lock' : [ 0x8, ['long']], 'PteLong' : [ 0x8, ['unsigned long']], 'u3' : [ 0xc, ['__unnamed_15b1']], 'OriginalPte' : [ 0x10, ['_MMPTE']], 'u4' : [ 0x18, ['__unnamed_15b5']], } ], '_MI_SYSTEM_PTE_TYPE' : [ 0x34, { 'Bitmap' : [ 0x0, ['_RTL_BITMAP']], 'Flags' : [ 0x8, ['unsigned long']], 'Hint' : [ 0xc, ['unsigned long']], 'BasePte' : [ 0x10, ['pointer', ['_MMPTE']]], 'FailureCount' : [ 0x14, ['pointer', ['unsigned long']]], 'Vm' : [ 0x18, ['pointer', ['_MMSUPPORT']]], 'TotalSystemPtes' : [ 0x1c, ['long']], 'TotalFreeSystemPtes' : [ 0x20, ['long']], 'CachedPteCount' : [ 0x24, ['long']], 'PteFailures' : [ 0x28, ['unsigned long']], 'SpinLock' : [ 0x2c, ['unsigned long']], 'GlobalMutex' : [ 0x2c, ['pointer', ['_FAST_MUTEX']]], 'CachedPtes' : [ 0x30, ['pointer', ['_MI_CACHED_PTE']]], } ], '__unnamed_15d3' : [ 0x4, { 'VirtualAddress' : [ 0x0, ['pointer', ['void']]], 'Long' : [ 0x0, ['unsigned long']], 'e1' : [ 0x0, ['_MMWSLENTRY']], 'e2' : [ 0x0, ['_MMWSLE_FREE_ENTRY']], } ], '_MMWSLE' : [ 0x4, { 'u1' : [ 0x0, ['__unnamed_15d3']], } ], '_MMWSL' : [ 0xd9c, { 'FirstFree' : [ 0x0, ['unsigned long']], 'FirstDynamic' : [ 0x4, ['unsigned long']], 'LastEntry' : [ 0x8, ['unsigned long']], 'NextSlot' : [ 0xc, ['unsigned long']], 'LastInitializedWsle' : [ 0x10, ['unsigned long']], 'NextAgingSlot' : [ 0x14, ['unsigned long']], 'NextAccessClearingSlot' : [ 0x18, ['unsigned long']], 'LastAccessClearingRemainder' : [ 0x1c, ['unsigned long']], 'LastAgingRemainder' : [ 0x20, ['unsigned long']], 'WsleSize' : [ 0x24, ['unsigned long']], 'NonDirectCount' : [ 0x28, ['unsigned long']], 'LowestPagableAddress' : [ 0x2c, ['pointer', ['void']]], 'NonDirectHash' : [ 0x30, ['pointer', ['_MMWSLE_NONDIRECT_HASH']]], 'HashTableStart' : [ 0x34, ['pointer', ['_MMWSLE_HASH']]], 'HighestPermittedHashAddress' : [ 0x38, ['pointer', ['_MMWSLE_HASH']]], 'ActiveWsleCounts' : [ 0x3c, ['array', 8, ['unsigned long']]], 'ActiveWsles' : [ 0x5c, ['array', 8, ['_MI_ACTIVE_WSLE']]], 'Wsle' : [ 0x9c, ['pointer', ['_MMWSLE']]], 'UserVaInfo' : [ 0xa0, ['_MI_USER_VA_INFO']], } ], '_MMSUPPORT' : [ 0x70, { 'WorkingSetMutex' : [ 0x0, ['_EX_PUSH_LOCK']], 'ExitGate' : [ 0x4, ['pointer', ['_KGATE']]], 'AccessLog' : [ 0x8, ['pointer', ['void']]], 'WorkingSetExpansionLinks' : [ 0xc, ['_LIST_ENTRY']], 'AgeDistribution' : [ 0x14, ['array', 7, ['unsigned long']]], 'MinimumWorkingSetSize' : [ 0x30, ['unsigned long']], 'WorkingSetSize' : [ 0x34, ['unsigned long']], 'WorkingSetPrivateSize' : [ 0x38, ['unsigned long']], 'MaximumWorkingSetSize' : [ 0x3c, ['unsigned long']], 'ChargedWslePages' : [ 0x40, ['unsigned long']], 'ActualWslePages' : [ 0x44, ['unsigned long']], 'WorkingSetSizeOverhead' : [ 0x48, ['unsigned long']], 'PeakWorkingSetSize' : [ 0x4c, ['unsigned long']], 'HardFaultCount' : [ 0x50, ['unsigned long']], 'VmWorkingSetList' : [ 0x54, ['pointer', ['_MMWSL']]], 'NextPageColor' : [ 0x58, ['unsigned short']], 'LastTrimStamp' : [ 0x5a, ['unsigned short']], 'PageFaultCount' : [ 0x5c, ['unsigned long']], 'TrimmedPageCount' : [ 0x60, ['unsigned long']], 'ForceTrimPages' : [ 0x64, ['unsigned long']], 'Flags' : [ 0x68, ['_MMSUPPORT_FLAGS']], 'WsSwapSupport' : [ 0x6c, ['pointer', ['void']]], } ], '__unnamed_15f0' : [ 0x4, { 'LongFlags' : [ 0x0, ['unsigned long']], 'Flags' : [ 0x0, ['_MMSECTION_FLAGS']], } ], '__unnamed_15f9' : [ 0xc, { 'NumberOfSystemCacheViews' : [ 0x0, ['unsigned long']], 'ImageRelocationStartBit' : [ 0x0, ['unsigned long']], 'WritableUserReferences' : [ 0x4, ['long']], 'ImageRelocationSizeIn64k' : [ 0x4, ['BitField', dict(start_bit = 0, end_bit = 16, native_type='unsigned long')]], 'Unused' : [ 0x4, ['BitField', dict(start_bit = 16, end_bit = 29, native_type='unsigned long')]], 'BitMap' : [ 0x4, ['BitField', dict(start_bit = 29, end_bit = 31, native_type='unsigned long')]], 'ImageActive' : [ 0x4, ['BitField', dict(start_bit = 31, end_bit = 32, native_type='unsigned long')]], 'SubsectionRoot' : [ 0x8, ['pointer', ['_MM_AVL_TABLE']]], 'SeImageStub' : [ 0x8, ['pointer', ['_MI_IMAGE_SECURITY_REFERENCE']]], } ], '__unnamed_15fb' : [ 0xc, { 'e2' : [ 0x0, ['__unnamed_15f9']], } ], '_CONTROL_AREA' : [ 0x48, { 'Segment' : [ 0x0, ['pointer', ['_SEGMENT']]], 'ListHead' : [ 0x4, ['_LIST_ENTRY']], 'NumberOfSectionReferences' : [ 0xc, ['unsigned long']], 'NumberOfPfnReferences' : [ 0x10, ['unsigned long']], 'NumberOfMappedViews' : [ 0x14, ['unsigned long']], 'NumberOfUserReferences' : [ 0x18, ['unsigned long']], 'u' : [ 0x1c, ['__unnamed_15f0']], 'FlushInProgressCount' : [ 0x20, ['unsigned long']], 'FilePointer' : [ 0x24, ['_EX_FAST_REF']], 'ControlAreaLock' : [ 0x28, ['long']], 'ModifiedWriteCount' : [ 0x2c, ['unsigned long']], 'WaitList' : [ 0x30, ['pointer', ['_MI_CONTROL_AREA_WAIT_BLOCK']]], 'u2' : [ 0x34, ['__unnamed_15fb']], 'LockedPages' : [ 0x40, ['unsigned long long']], } ], '_MM_STORE_KEY' : [ 0x4, { 'KeyLow' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 28, native_type='unsigned long')]], 'KeyHigh' : [ 0x0, ['BitField', dict(start_bit = 28, end_bit = 32, native_type='unsigned long')]], 'EntireKey' : [ 0x0, ['unsigned long']], } ], '_MMPAGING_FILE' : [ 0x64, { 'Size' : [ 0x0, ['unsigned long']], 'MaximumSize' : [ 0x4, ['unsigned long']], 'MinimumSize' : [ 0x8, ['unsigned long']], 'FreeSpace' : [ 0xc, ['unsigned long']], 'PeakUsage' : [ 0x10, ['unsigned long']], 'HighestPage' : [ 0x14, ['unsigned long']], 'FreeReservationSpace' : [ 0x18, ['unsigned long']], 'LargestReserveCluster' : [ 0x1c, ['unsigned long']], 'File' : [ 0x20, ['pointer', ['_FILE_OBJECT']]], 'Entry' : [ 0x24, ['array', 2, ['pointer', ['_MMMOD_WRITER_MDL_ENTRY']]]], 'PageFileName' : [ 0x2c, ['_UNICODE_STRING']], 'Bitmaps' : [ 0x34, ['pointer', ['_MI_PAGING_FILE_SPACE_BITMAPS']]], 'AllocationBitmapHint' : [ 0x38, ['unsigned long']], 'ReservationBitmapHint' : [ 0x3c, ['unsigned long']], 'LargestNonReservedClusterSize' : [ 0x40, ['unsigned long']], 'RefreshClusterSize' : [ 0x44, ['unsigned long']], 'LastRefreshClusterSize' : [ 0x48, ['unsigned long']], 'ReservedClusterSizeAggregate' : [ 0x4c, ['unsigned long']], 'ToBeEvictedCount' : [ 0x50, ['unsigned long']], 'PageFileNumber' : [ 0x54, ['BitField', dict(start_bit = 0, end_bit = 4, native_type='unsigned short')]], 'BootPartition' : [ 0x54, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned short')]], 'WsSwapPagefile' : [ 0x54, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned short')]], 'NoReservations' : [ 0x54, ['BitField', dict(start_bit = 6, end_bit = 7, native_type='unsigned short')]], 'Spare0' : [ 0x54, ['BitField', dict(start_bit = 7, end_bit = 16, native_type='unsigned short')]], 'AdriftMdls' : [ 0x56, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned char')]], 'Spare1' : [ 0x56, ['BitField', dict(start_bit = 1, end_bit = 8, native_type='unsigned char')]], 'Spare2' : [ 0x57, ['BitField', dict(start_bit = 0, end_bit = 8, native_type='unsigned char')]], 'FileHandle' : [ 0x58, ['pointer', ['void']]], 'Lock' : [ 0x5c, ['unsigned long']], 'LockOwner' : [ 0x60, ['pointer', ['_ETHREAD']]], } ], '_MI_PAGING_FILE_SPACE_BITMAPS' : [ 0x18, { 'RefCount' : [ 0x0, ['unsigned long']], 'Anchor' : [ 0x0, ['pointer', ['_MI_PAGING_FILE_SPACE_BITMAPS']]], 'AllocationBitmap' : [ 0x4, ['_RTL_BITMAP']], 'ReservationBitmap' : [ 0xc, ['_RTL_BITMAP']], 'EvictStoreBitmap' : [ 0x14, ['pointer', ['_RTL_BITMAP']]], } ], '_RTL_BITMAP' : [ 0x8, { 'SizeOfBitMap' : [ 0x0, ['unsigned long']], 'Buffer' : [ 0x4, ['pointer', ['unsigned long']]], } ], 'tagSWITCH_CONTEXT' : [ 0x58, { 'Attribute' : [ 0x0, ['tagSWITCH_CONTEXT_ATTRIBUTE']], 'Data' : [ 0x18, ['tagSWITCH_CONTEXT_DATA']], } ], '__unnamed_1645' : [ 0xc, { 'Failure' : [ 0x0, ['Enumeration', dict(target = 'long', choices = {0: '_None', 1: '_CmInitializeHive', 2: '_HvInitializeHive', 3: '_HvpBuildMap', 4: '_HvpBuildMapAndCopy', 5: '_HvpInitMap', 6: '_HvLoadHive', 7: '_HvpReadFileImageAndBuildMap', 8: '_HvpRecoverData', 9: '_CmpValidateHiveSecurityDescriptors', 10: '_HvpEnlistBinInMap', 11: '_CmCheckRegistry', 12: '_CmRegistryIO', 13: '_CmCheckRegistry2', 14: '_CmpCheckKey', 15: '_CmpCheckValueList', 16: '_HvCheckHive', 17: '_HvCheckBin'})]], 'Status' : [ 0x4, ['long']], 'Point' : [ 0x8, ['unsigned long']], } ], '__unnamed_1648' : [ 0xc, { 'Action' : [ 0x0, ['unsigned long']], 'Handle' : [ 0x4, ['pointer', ['void']]], 'Status' : [ 0x8, ['long']], } ], '__unnamed_164a' : [ 0x4, { 'CheckStack' : [ 0x0, ['pointer', ['void']]], } ], '__unnamed_164e' : [ 0x10, { 'Cell' : [ 0x0, ['unsigned long']], 'CellPoint' : [ 0x4, ['pointer', ['_CELL_DATA']]], 'RootPoint' : [ 0x8, ['pointer', ['void']]], 'Index' : [ 0xc, ['unsigned long']], } ], '__unnamed_1650' : [ 0x10, { 'List' : [ 0x0, ['pointer', ['_CELL_DATA']]], 'Index' : [ 0x4, ['unsigned long']], 'Cell' : [ 0x8, ['unsigned long']], 'CellPoint' : [ 0xc, ['pointer', ['_CELL_DATA']]], } ], '__unnamed_1654' : [ 0xc, { 'Space' : [ 0x0, ['unsigned long']], 'MapPoint' : [ 0x4, ['unsigned long']], 'BinPoint' : [ 0x8, ['pointer', ['_HBIN']]], } ], '__unnamed_1658' : [ 0x8, { 'Bin' : [ 0x0, ['pointer', ['_HBIN']]], 'CellPoint' : [ 0x4, ['pointer', ['_HCELL']]], } ], '__unnamed_165a' : [ 0x4, { 'FileOffset' : [ 0x0, ['unsigned long']], } ], '_HIVE_LOAD_FAILURE' : [ 0x120, { 'Hive' : [ 0x0, ['pointer', ['_HHIVE']]], 'Index' : [ 0x4, ['unsigned long']], 'RecoverableIndex' : [ 0x8, ['unsigned long']], 'Locations' : [ 0xc, ['array', 8, ['__unnamed_1645']]], 'RecoverableLocations' : [ 0x6c, ['array', 8, ['__unnamed_1645']]], 'RegistryIO' : [ 0xcc, ['__unnamed_1648']], 'CheckRegistry2' : [ 0xd8, ['__unnamed_164a']], 'CheckKey' : [ 0xdc, ['__unnamed_164e']], 'CheckValueList' : [ 0xec, ['__unnamed_1650']], 'CheckHive' : [ 0xfc, ['__unnamed_1654']], 'CheckHive1' : [ 0x108, ['__unnamed_1654']], 'CheckBin' : [ 0x114, ['__unnamed_1658']], 'RecoverData' : [ 0x11c, ['__unnamed_165a']], } ], '_PCW_COUNTER_DESCRIPTOR' : [ 0x8, { 'Id' : [ 0x0, ['unsigned short']], 'StructIndex' : [ 0x2, ['unsigned short']], 'Offset' : [ 0x4, ['unsigned short']], 'Size' : [ 0x6, ['unsigned short']], } ], '_PCW_REGISTRATION_INFORMATION' : [ 0x18, { 'Version' : [ 0x0, ['unsigned long']], 'Name' : [ 0x4, ['pointer', ['_UNICODE_STRING']]], 'CounterCount' : [ 0x8, ['unsigned long']], 'Counters' : [ 0xc, ['pointer', ['_PCW_COUNTER_DESCRIPTOR']]], 'Callback' : [ 0x10, ['pointer', ['void']]], 'CallbackContext' : [ 0x14, ['pointer', ['void']]], } ], '_PCW_PROCESSOR_INFO' : [ 0xb8, { 'IdleTime' : [ 0x0, ['unsigned long long']], 'AvailableTime' : [ 0x8, ['unsigned long long']], 'UserTime' : [ 0x10, ['unsigned long long']], 'KernelTime' : [ 0x18, ['unsigned long long']], 'Interrupts' : [ 0x20, ['unsigned long']], 'DpcTime' : [ 0x28, ['unsigned long long']], 'InterruptTime' : [ 0x30, ['unsigned long long']], 'ClockInterrupts' : [ 0x38, ['unsigned long']], 'DpcCount' : [ 0x3c, ['unsigned long']], 'DpcRate' : [ 0x40, ['unsigned long']], 'C1Time' : [ 0x48, ['unsigned long long']], 'C2Time' : [ 0x50, ['unsigned long long']], 'C3Time' : [ 0x58, ['unsigned long long']], 'C1Transitions' : [ 0x60, ['unsigned long long']], 'C2Transitions' : [ 0x68, ['unsigned long long']], 'C3Transitions' : [ 0x70, ['unsigned long long']], 'ParkingStatus' : [ 0x78, ['unsigned long']], 'CurrentFrequency' : [ 0x7c, ['unsigned long']], 'PercentMaxFrequency' : [ 0x80, ['unsigned long']], 'StateFlags' : [ 0x84, ['unsigned long']], 'NominalThroughput' : [ 0x88, ['unsigned long']], 'ActiveThroughput' : [ 0x8c, ['unsigned long']], 'ScaledThroughput' : [ 0x90, ['unsigned long long']], 'ScaledKernelThroughput' : [ 0x98, ['unsigned long long']], 'AverageIdleTime' : [ 0xa0, ['unsigned long long']], 'IdleBreakEvents' : [ 0xa8, ['unsigned long long']], 'PerformanceLimit' : [ 0xb0, ['unsigned long']], 'PerformanceLimitFlags' : [ 0xb4, ['unsigned long']], } ], '_PCW_DATA' : [ 0x8, { 'Data' : [ 0x0, ['pointer', ['void']]], 'Size' : [ 0x4, ['unsigned long']], } ], '_SYNCH_COUNTERS' : [ 0xb8, { 'SpinLockAcquireCount' : [ 0x0, ['unsigned long']], 'SpinLockContentionCount' : [ 0x4, ['unsigned long']], 'SpinLockSpinCount' : [ 0x8, ['unsigned long']], 'IpiSendRequestBroadcastCount' : [ 0xc, ['unsigned long']], 'IpiSendRequestRoutineCount' : [ 0x10, ['unsigned long']], 'IpiSendSoftwareInterruptCount' : [ 0x14, ['unsigned long']], 'ExInitializeResourceCount' : [ 0x18, ['unsigned long']], 'ExReInitializeResourceCount' : [ 0x1c, ['unsigned long']], 'ExDeleteResourceCount' : [ 0x20, ['unsigned long']], 'ExecutiveResourceAcquiresCount' : [ 0x24, ['unsigned long']], 'ExecutiveResourceContentionsCount' : [ 0x28, ['unsigned long']], 'ExecutiveResourceReleaseExclusiveCount' : [ 0x2c, ['unsigned long']], 'ExecutiveResourceReleaseSharedCount' : [ 0x30, ['unsigned long']], 'ExecutiveResourceConvertsCount' : [ 0x34, ['unsigned long']], 'ExAcqResExclusiveAttempts' : [ 0x38, ['unsigned long']], 'ExAcqResExclusiveAcquiresExclusive' : [ 0x3c, ['unsigned long']], 'ExAcqResExclusiveAcquiresExclusiveRecursive' : [ 0x40, ['unsigned long']], 'ExAcqResExclusiveWaits' : [ 0x44, ['unsigned long']], 'ExAcqResExclusiveNotAcquires' : [ 0x48, ['unsigned long']], 'ExAcqResSharedAttempts' : [ 0x4c, ['unsigned long']], 'ExAcqResSharedAcquiresExclusive' : [ 0x50, ['unsigned long']], 'ExAcqResSharedAcquiresShared' : [ 0x54, ['unsigned long']], 'ExAcqResSharedAcquiresSharedRecursive' : [ 0x58, ['unsigned long']], 'ExAcqResSharedWaits' : [ 0x5c, ['unsigned long']], 'ExAcqResSharedNotAcquires' : [ 0x60, ['unsigned long']], 'ExAcqResSharedStarveExclusiveAttempts' : [ 0x64, ['unsigned long']], 'ExAcqResSharedStarveExclusiveAcquiresExclusive' : [ 0x68, ['unsigned long']], 'ExAcqResSharedStarveExclusiveAcquiresShared' : [ 0x6c, ['unsigned long']], 'ExAcqResSharedStarveExclusiveAcquiresSharedRecursive' : [ 0x70, ['unsigned long']], 'ExAcqResSharedStarveExclusiveWaits' : [ 0x74, ['unsigned long']], 'ExAcqResSharedStarveExclusiveNotAcquires' : [ 0x78, ['unsigned long']], 'ExAcqResSharedWaitForExclusiveAttempts' : [ 0x7c, ['unsigned long']], 'ExAcqResSharedWaitForExclusiveAcquiresExclusive' : [ 0x80, ['unsigned long']], 'ExAcqResSharedWaitForExclusiveAcquiresShared' : [ 0x84, ['unsigned long']], 'ExAcqResSharedWaitForExclusiveAcquiresSharedRecursive' : [ 0x88, ['unsigned long']], 'ExAcqResSharedWaitForExclusiveWaits' : [ 0x8c, ['unsigned long']], 'ExAcqResSharedWaitForExclusiveNotAcquires' : [ 0x90, ['unsigned long']], 'ExSetResOwnerPointerExclusive' : [ 0x94, ['unsigned long']], 'ExSetResOwnerPointerSharedNew' : [ 0x98, ['unsigned long']], 'ExSetResOwnerPointerSharedOld' : [ 0x9c, ['unsigned long']], 'ExTryToAcqExclusiveAttempts' : [ 0xa0, ['unsigned long']], 'ExTryToAcqExclusiveAcquires' : [ 0xa4, ['unsigned long']], 'ExBoostExclusiveOwner' : [ 0xa8, ['unsigned long']], 'ExBoostSharedOwners' : [ 0xac, ['unsigned long']], 'ExEtwSynchTrackingNotificationsCount' : [ 0xb0, ['unsigned long']], 'ExEtwSynchTrackingNotificationsAccountedCount' : [ 0xb4, ['unsigned long']], } ], '_ETW_PERF_COUNTERS' : [ 0x18, { 'TotalActiveSessions' : [ 0x0, ['long']], 'TotalBufferMemoryNonPagedPool' : [ 0x4, ['long']], 'TotalBufferMemoryPagedPool' : [ 0x8, ['long']], 'TotalGuidsEnabled' : [ 0xc, ['long']], 'TotalGuidsNotEnabled' : [ 0x10, ['long']], 'TotalGuidsPreEnabled' : [ 0x14, ['long']], } ], '_ETW_SESSION_PERF_COUNTERS' : [ 0x18, { 'BufferMemoryPagedPool' : [ 0x0, ['long']], 'BufferMemoryNonPagedPool' : [ 0x4, ['long']], 'EventsLoggedCount' : [ 0x8, ['unsigned long long']], 'EventsLost' : [ 0x10, ['long']], 'NumConsumers' : [ 0x14, ['long']], } ], '_FILESYSTEM_DISK_COUNTERS' : [ 0x10, { 'FsBytesRead' : [ 0x0, ['unsigned long long']], 'FsBytesWritten' : [ 0x8, ['unsigned long long']], } ], '_TEB32' : [ 0xfe8, { 'NtTib' : [ 0x0, ['_NT_TIB32']], 'EnvironmentPointer' : [ 0x1c, ['unsigned long']], 'ClientId' : [ 0x20, ['_CLIENT_ID32']], 'ActiveRpcHandle' : [ 0x28, ['unsigned long']], 'ThreadLocalStoragePointer' : [ 0x2c, ['unsigned long']], 'ProcessEnvironmentBlock' : [ 0x30, ['unsigned long']], 'LastErrorValue' : [ 0x34, ['unsigned long']], 'CountOfOwnedCriticalSections' : [ 0x38, ['unsigned long']], 'CsrClientThread' : [ 0x3c, ['unsigned long']], 'Win32ThreadInfo' : [ 0x40, ['unsigned long']], 'User32Reserved' : [ 0x44, ['array', 26, ['unsigned long']]], 'UserReserved' : [ 0xac, ['array', 5, ['unsigned long']]], 'WOW32Reserved' : [ 0xc0, ['unsigned long']], 'CurrentLocale' : [ 0xc4, ['unsigned long']], 'FpSoftwareStatusRegister' : [ 0xc8, ['unsigned long']], 'SystemReserved1' : [ 0xcc, ['array', 54, ['unsigned long']]], 'ExceptionCode' : [ 0x1a4, ['long']], 'ActivationContextStackPointer' : [ 0x1a8, ['unsigned long']], 'SpareBytes' : [ 0x1ac, ['array', 36, ['unsigned char']]], 'TxFsContext' : [ 0x1d0, ['unsigned long']], 'GdiTebBatch' : [ 0x1d4, ['_GDI_TEB_BATCH32']], 'RealClientId' : [ 0x6b4, ['_CLIENT_ID32']], 'GdiCachedProcessHandle' : [ 0x6bc, ['unsigned long']], 'GdiClientPID' : [ 0x6c0, ['unsigned long']], 'GdiClientTID' : [ 0x6c4, ['unsigned long']], 'GdiThreadLocalInfo' : [ 0x6c8, ['unsigned long']], 'Win32ClientInfo' : [ 0x6cc, ['array', 62, ['unsigned long']]], 'glDispatchTable' : [ 0x7c4, ['array', 233, ['unsigned long']]], 'glReserved1' : [ 0xb68, ['array', 29, ['unsigned long']]], 'glReserved2' : [ 0xbdc, ['unsigned long']], 'glSectionInfo' : [ 0xbe0, ['unsigned long']], 'glSection' : [ 0xbe4, ['unsigned long']], 'glTable' : [ 0xbe8, ['unsigned long']], 'glCurrentRC' : [ 0xbec, ['unsigned long']], 'glContext' : [ 0xbf0, ['unsigned long']], 'LastStatusValue' : [ 0xbf4, ['unsigned long']], 'StaticUnicodeString' : [ 0xbf8, ['_STRING32']], 'StaticUnicodeBuffer' : [ 0xc00, ['array', 261, ['wchar']]], 'DeallocationStack' : [ 0xe0c, ['unsigned long']], 'TlsSlots' : [ 0xe10, ['array', 64, ['unsigned long']]], 'TlsLinks' : [ 0xf10, ['LIST_ENTRY32']], 'Vdm' : [ 0xf18, ['unsigned long']], 'ReservedForNtRpc' : [ 0xf1c, ['unsigned long']], 'DbgSsReserved' : [ 0xf20, ['array', 2, ['unsigned long']]], 'HardErrorMode' : [ 0xf28, ['unsigned long']], 'Instrumentation' : [ 0xf2c, ['array', 9, ['unsigned long']]], 'ActivityId' : [ 0xf50, ['_GUID']], 'SubProcessTag' : [ 0xf60, ['unsigned long']], 'PerflibData' : [ 0xf64, ['unsigned long']], 'EtwTraceData' : [ 0xf68, ['unsigned long']], 'WinSockData' : [ 0xf6c, ['unsigned long']], 'GdiBatchCount' : [ 0xf70, ['unsigned long']], 'CurrentIdealProcessor' : [ 0xf74, ['_PROCESSOR_NUMBER']], 'IdealProcessorValue' : [ 0xf74, ['unsigned long']], 'ReservedPad0' : [ 0xf74, ['unsigned char']], 'ReservedPad1' : [ 0xf75, ['unsigned char']], 'ReservedPad2' : [ 0xf76, ['unsigned char']], 'IdealProcessor' : [ 0xf77, ['unsigned char']], 'GuaranteedStackBytes' : [ 0xf78, ['unsigned long']], 'ReservedForPerf' : [ 0xf7c, ['unsigned long']], 'ReservedForOle' : [ 0xf80, ['unsigned long']], 'WaitingOnLoaderLock' : [ 0xf84, ['unsigned long']], 'SavedPriorityState' : [ 0xf88, ['unsigned long']], 'ReservedForCodeCoverage' : [ 0xf8c, ['unsigned long']], 'ThreadPoolData' : [ 0xf90, ['unsigned long']], 'TlsExpansionSlots' : [ 0xf94, ['unsigned long']], 'MuiGeneration' : [ 0xf98, ['unsigned long']], 'IsImpersonating' : [ 0xf9c, ['unsigned long']], 'NlsCache' : [ 0xfa0, ['unsigned long']], 'pShimData' : [ 0xfa4, ['unsigned long']], 'HeapVirtualAffinity' : [ 0xfa8, ['unsigned short']], 'LowFragHeapDataSlot' : [ 0xfaa, ['unsigned short']], 'CurrentTransactionHandle' : [ 0xfac, ['unsigned long']], 'ActiveFrame' : [ 0xfb0, ['unsigned long']], 'FlsData' : [ 0xfb4, ['unsigned long']], 'PreferredLanguages' : [ 0xfb8, ['unsigned long']], 'UserPrefLanguages' : [ 0xfbc, ['unsigned long']], 'MergedPrefLanguages' : [ 0xfc0, ['unsigned long']], 'MuiImpersonation' : [ 0xfc4, ['unsigned long']], 'CrossTebFlags' : [ 0xfc8, ['unsigned short']], 'SpareCrossTebBits' : [ 0xfc8, ['BitField', dict(start_bit = 0, end_bit = 16, native_type='unsigned short')]], 'SameTebFlags' : [ 0xfca, ['unsigned short']], 'SafeThunkCall' : [ 0xfca, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned short')]], 'InDebugPrint' : [ 0xfca, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned short')]], 'HasFiberData' : [ 0xfca, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned short')]], 'SkipThreadAttach' : [ 0xfca, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned short')]], 'WerInShipAssertCode' : [ 0xfca, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned short')]], 'RanProcessInit' : [ 0xfca, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned short')]], 'ClonedThread' : [ 0xfca, ['BitField', dict(start_bit = 6, end_bit = 7, native_type='unsigned short')]], 'SuppressDebugMsg' : [ 0xfca, ['BitField', dict(start_bit = 7, end_bit = 8, native_type='unsigned short')]], 'DisableUserStackWalk' : [ 0xfca, ['BitField', dict(start_bit = 8, end_bit = 9, native_type='unsigned short')]], 'RtlExceptionAttached' : [ 0xfca, ['BitField', dict(start_bit = 9, end_bit = 10, native_type='unsigned short')]], 'InitialThread' : [ 0xfca, ['BitField', dict(start_bit = 10, end_bit = 11, native_type='unsigned short')]], 'SessionAware' : [ 0xfca, ['BitField', dict(start_bit = 11, end_bit = 12, native_type='unsigned short')]], 'SpareSameTebBits' : [ 0xfca, ['BitField', dict(start_bit = 12, end_bit = 16, native_type='unsigned short')]], 'TxnScopeEnterCallback' : [ 0xfcc, ['unsigned long']], 'TxnScopeExitCallback' : [ 0xfd0, ['unsigned long']], 'TxnScopeContext' : [ 0xfd4, ['unsigned long']], 'LockCount' : [ 0xfd8, ['unsigned long']], 'SpareUlong0' : [ 0xfdc, ['unsigned long']], 'ResourceRetValue' : [ 0xfe0, ['unsigned long']], 'ReservedForWdf' : [ 0xfe4, ['unsigned long']], } ], '_TEB64' : [ 0x1820, { 'NtTib' : [ 0x0, ['_NT_TIB64']], 'EnvironmentPointer' : [ 0x38, ['unsigned long long']], 'ClientId' : [ 0x40, ['_CLIENT_ID64']], 'ActiveRpcHandle' : [ 0x50, ['unsigned long long']], 'ThreadLocalStoragePointer' : [ 0x58, ['unsigned long long']], 'ProcessEnvironmentBlock' : [ 0x60, ['unsigned long long']], 'LastErrorValue' : [ 0x68, ['unsigned long']], 'CountOfOwnedCriticalSections' : [ 0x6c, ['unsigned long']], 'CsrClientThread' : [ 0x70, ['unsigned long long']], 'Win32ThreadInfo' : [ 0x78, ['unsigned long long']], 'User32Reserved' : [ 0x80, ['array', 26, ['unsigned long']]], 'UserReserved' : [ 0xe8, ['array', 5, ['unsigned long']]], 'WOW32Reserved' : [ 0x100, ['unsigned long long']], 'CurrentLocale' : [ 0x108, ['unsigned long']], 'FpSoftwareStatusRegister' : [ 0x10c, ['unsigned long']], 'SystemReserved1' : [ 0x110, ['array', 54, ['unsigned long long']]], 'ExceptionCode' : [ 0x2c0, ['long']], 'ActivationContextStackPointer' : [ 0x2c8, ['unsigned long long']], 'SpareBytes' : [ 0x2d0, ['array', 24, ['unsigned char']]], 'TxFsContext' : [ 0x2e8, ['unsigned long']], 'GdiTebBatch' : [ 0x2f0, ['_GDI_TEB_BATCH64']], 'RealClientId' : [ 0x7d8, ['_CLIENT_ID64']], 'GdiCachedProcessHandle' : [ 0x7e8, ['unsigned long long']], 'GdiClientPID' : [ 0x7f0, ['unsigned long']], 'GdiClientTID' : [ 0x7f4, ['unsigned long']], 'GdiThreadLocalInfo' : [ 0x7f8, ['unsigned long long']], 'Win32ClientInfo' : [ 0x800, ['array', 62, ['unsigned long long']]], 'glDispatchTable' : [ 0x9f0, ['array', 233, ['unsigned long long']]], 'glReserved1' : [ 0x1138, ['array', 29, ['unsigned long long']]], 'glReserved2' : [ 0x1220, ['unsigned long long']], 'glSectionInfo' : [ 0x1228, ['unsigned long long']], 'glSection' : [ 0x1230, ['unsigned long long']], 'glTable' : [ 0x1238, ['unsigned long long']], 'glCurrentRC' : [ 0x1240, ['unsigned long long']], 'glContext' : [ 0x1248, ['unsigned long long']], 'LastStatusValue' : [ 0x1250, ['unsigned long']], 'StaticUnicodeString' : [ 0x1258, ['_STRING64']], 'StaticUnicodeBuffer' : [ 0x1268, ['array', 261, ['wchar']]], 'DeallocationStack' : [ 0x1478, ['unsigned long long']], 'TlsSlots' : [ 0x1480, ['array', 64, ['unsigned long long']]], 'TlsLinks' : [ 0x1680, ['LIST_ENTRY64']], 'Vdm' : [ 0x1690, ['unsigned long long']], 'ReservedForNtRpc' : [ 0x1698, ['unsigned long long']], 'DbgSsReserved' : [ 0x16a0, ['array', 2, ['unsigned long long']]], 'HardErrorMode' : [ 0x16b0, ['unsigned long']], 'Instrumentation' : [ 0x16b8, ['array', 11, ['unsigned long long']]], 'ActivityId' : [ 0x1710, ['_GUID']], 'SubProcessTag' : [ 0x1720, ['unsigned long long']], 'PerflibData' : [ 0x1728, ['unsigned long long']], 'EtwTraceData' : [ 0x1730, ['unsigned long long']], 'WinSockData' : [ 0x1738, ['unsigned long long']], 'GdiBatchCount' : [ 0x1740, ['unsigned long']], 'CurrentIdealProcessor' : [ 0x1744, ['_PROCESSOR_NUMBER']], 'IdealProcessorValue' : [ 0x1744, ['unsigned long']], 'ReservedPad0' : [ 0x1744, ['unsigned char']], 'ReservedPad1' : [ 0x1745, ['unsigned char']], 'ReservedPad2' : [ 0x1746, ['unsigned char']], 'IdealProcessor' : [ 0x1747, ['unsigned char']], 'GuaranteedStackBytes' : [ 0x1748, ['unsigned long']], 'ReservedForPerf' : [ 0x1750, ['unsigned long long']], 'ReservedForOle' : [ 0x1758, ['unsigned long long']], 'WaitingOnLoaderLock' : [ 0x1760, ['unsigned long']], 'SavedPriorityState' : [ 0x1768, ['unsigned long long']], 'ReservedForCodeCoverage' : [ 0x1770, ['unsigned long long']], 'ThreadPoolData' : [ 0x1778, ['unsigned long long']], 'TlsExpansionSlots' : [ 0x1780, ['unsigned long long']], 'DeallocationBStore' : [ 0x1788, ['unsigned long long']], 'BStoreLimit' : [ 0x1790, ['unsigned long long']], 'MuiGeneration' : [ 0x1798, ['unsigned long']], 'IsImpersonating' : [ 0x179c, ['unsigned long']], 'NlsCache' : [ 0x17a0, ['unsigned long long']], 'pShimData' : [ 0x17a8, ['unsigned long long']], 'HeapVirtualAffinity' : [ 0x17b0, ['unsigned short']], 'LowFragHeapDataSlot' : [ 0x17b2, ['unsigned short']], 'CurrentTransactionHandle' : [ 0x17b8, ['unsigned long long']], 'ActiveFrame' : [ 0x17c0, ['unsigned long long']], 'FlsData' : [ 0x17c8, ['unsigned long long']], 'PreferredLanguages' : [ 0x17d0, ['unsigned long long']], 'UserPrefLanguages' : [ 0x17d8, ['unsigned long long']], 'MergedPrefLanguages' : [ 0x17e0, ['unsigned long long']], 'MuiImpersonation' : [ 0x17e8, ['unsigned long']], 'CrossTebFlags' : [ 0x17ec, ['unsigned short']], 'SpareCrossTebBits' : [ 0x17ec, ['BitField', dict(start_bit = 0, end_bit = 16, native_type='unsigned short')]], 'SameTebFlags' : [ 0x17ee, ['unsigned short']], 'SafeThunkCall' : [ 0x17ee, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned short')]], 'InDebugPrint' : [ 0x17ee, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned short')]], 'HasFiberData' : [ 0x17ee, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned short')]], 'SkipThreadAttach' : [ 0x17ee, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned short')]], 'WerInShipAssertCode' : [ 0x17ee, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned short')]], 'RanProcessInit' : [ 0x17ee, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned short')]], 'ClonedThread' : [ 0x17ee, ['BitField', dict(start_bit = 6, end_bit = 7, native_type='unsigned short')]], 'SuppressDebugMsg' : [ 0x17ee, ['BitField', dict(start_bit = 7, end_bit = 8, native_type='unsigned short')]], 'DisableUserStackWalk' : [ 0x17ee, ['BitField', dict(start_bit = 8, end_bit = 9, native_type='unsigned short')]], 'RtlExceptionAttached' : [ 0x17ee, ['BitField', dict(start_bit = 9, end_bit = 10, native_type='unsigned short')]], 'InitialThread' : [ 0x17ee, ['BitField', dict(start_bit = 10, end_bit = 11, native_type='unsigned short')]], 'SessionAware' : [ 0x17ee, ['BitField', dict(start_bit = 11, end_bit = 12, native_type='unsigned short')]], 'SpareSameTebBits' : [ 0x17ee, ['BitField', dict(start_bit = 12, end_bit = 16, native_type='unsigned short')]], 'TxnScopeEnterCallback' : [ 0x17f0, ['unsigned long long']], 'TxnScopeExitCallback' : [ 0x17f8, ['unsigned long long']], 'TxnScopeContext' : [ 0x1800, ['unsigned long long']], 'LockCount' : [ 0x1808, ['unsigned long']], 'SpareUlong0' : [ 0x180c, ['unsigned long']], 'ResourceRetValue' : [ 0x1810, ['unsigned long long']], 'ReservedForWdf' : [ 0x1818, ['unsigned long long']], } ], '_KTIMER_TABLE' : [ 0x1840, { 'TimerExpiry' : [ 0x0, ['array', 16, ['pointer', ['_KTIMER']]]], 'TimerEntries' : [ 0x40, ['array', 256, ['_KTIMER_TABLE_ENTRY']]], } ], '_KTIMER_TABLE_ENTRY' : [ 0x18, { 'Lock' : [ 0x0, ['unsigned long']], 'Entry' : [ 0x4, ['_LIST_ENTRY']], 'Time' : [ 0x10, ['_ULARGE_INTEGER']], } ], '_KAFFINITY_EX' : [ 0xc, { 'Count' : [ 0x0, ['unsigned short']], 'Size' : [ 0x2, ['unsigned short']], 'Reserved' : [ 0x4, ['unsigned long']], 'Bitmap' : [ 0x8, ['array', 1, ['unsigned long']]], } ], '_GROUP_AFFINITY' : [ 0xc, { 'Mask' : [ 0x0, ['unsigned long']], 'Group' : [ 0x4, ['unsigned short']], 'Reserved' : [ 0x6, ['array', 3, ['unsigned short']]], } ], '_XSTATE_SAVE' : [ 0x20, { 'Reserved1' : [ 0x0, ['long long']], 'Reserved2' : [ 0x8, ['unsigned long']], 'Prev' : [ 0xc, ['pointer', ['_XSTATE_SAVE']]], 'Reserved3' : [ 0x10, ['pointer', ['_XSAVE_AREA']]], 'Thread' : [ 0x14, ['pointer', ['_KTHREAD']]], 'Reserved4' : [ 0x18, ['pointer', ['void']]], 'Level' : [ 0x1c, ['unsigned char']], 'XStateContext' : [ 0x0, ['_XSTATE_CONTEXT']], } ], '_XSAVE_AREA' : [ 0x240, { 'LegacyState' : [ 0x0, ['_XSAVE_FORMAT']], 'Header' : [ 0x200, ['_XSAVE_AREA_HEADER']], } ], '_MCGEN_TRACE_CONTEXT' : [ 0x38, { 'RegistrationHandle' : [ 0x0, ['unsigned long long']], 'Logger' : [ 0x8, ['unsigned long long']], 'MatchAnyKeyword' : [ 0x10, ['unsigned long long']], 'MatchAllKeyword' : [ 0x18, ['unsigned long long']], 'Flags' : [ 0x20, ['unsigned long']], 'IsEnabled' : [ 0x24, ['unsigned long']], 'Level' : [ 0x28, ['unsigned char']], 'Reserve' : [ 0x29, ['unsigned char']], 'EnableBitsCount' : [ 0x2a, ['unsigned short']], 'EnableBitMask' : [ 0x2c, ['pointer', ['unsigned long']]], 'EnableKeyWords' : [ 0x30, ['pointer', ['unsigned long long']]], 'EnableLevel' : [ 0x34, ['pointer', ['unsigned char']]], } ], '_EVENT_FILTER_DESCRIPTOR' : [ 0x10, { 'Ptr' : [ 0x0, ['unsigned long long']], 'Size' : [ 0x8, ['unsigned long']], 'Type' : [ 0xc, ['unsigned long']], } ], '_SID' : [ 0xc, { 'Revision' : [ 0x0, ['unsigned char']], 'SubAuthorityCount' : [ 0x1, ['unsigned char']], 'IdentifierAuthority' : [ 0x2, ['_SID_IDENTIFIER_AUTHORITY']], 'SubAuthority' : [ 0x8, ['array', 1, ['unsigned long']]], } ], '_PNP_DEVICE_COMPLETION_QUEUE' : [ 0x2c, { 'DispatchedList' : [ 0x0, ['_LIST_ENTRY']], 'DispatchedCount' : [ 0x8, ['unsigned long']], 'CompletedList' : [ 0xc, ['_LIST_ENTRY']], 'CompletedSemaphore' : [ 0x14, ['_KSEMAPHORE']], 'SpinLock' : [ 0x28, ['unsigned long']], } ], '_KSEMAPHORE' : [ 0x14, { 'Header' : [ 0x0, ['_DISPATCHER_HEADER']], 'Limit' : [ 0x10, ['long']], } ], '_DEVOBJ_EXTENSION' : [ 0x3c, { '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']]], 'DependentList' : [ 0x2c, ['_LIST_ENTRY']], 'ProviderList' : [ 0x34, ['_LIST_ENTRY']], } ], '__unnamed_176e' : [ 0x4, { 'LegacyDeviceNode' : [ 0x0, ['pointer', ['_DEVICE_NODE']]], 'PendingDeviceRelations' : [ 0x0, ['pointer', ['_DEVICE_RELATIONS']]], 'Information' : [ 0x0, ['pointer', ['void']]], } ], '__unnamed_1770' : [ 0x4, { 'NextResourceDeviceNode' : [ 0x0, ['pointer', ['_DEVICE_NODE']]], } ], '__unnamed_1774' : [ 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' : [ 0x1cc, { 'Sibling' : [ 0x0, ['pointer', ['_DEVICE_NODE']]], 'Child' : [ 0x4, ['pointer', ['_DEVICE_NODE']]], 'Parent' : [ 0x8, ['pointer', ['_DEVICE_NODE']]], 'LastChild' : [ 0xc, ['pointer', ['_DEVICE_NODE']]], 'PhysicalDeviceObject' : [ 0x10, ['pointer', ['_DEVICE_OBJECT']]], 'InstancePath' : [ 0x14, ['_UNICODE_STRING']], 'ServiceName' : [ 0x1c, ['_UNICODE_STRING']], 'PendingIrp' : [ 0x24, ['pointer', ['_IRP']]], 'Level' : [ 0x28, ['unsigned long']], 'CurrentPowerState' : [ 0x2c, ['_POWER_STATE']], 'Notify' : [ 0x30, ['_PO_DEVICE_NOTIFY']], 'PoIrpManager' : [ 0x6c, ['_PO_IRP_MANAGER']], 'FxDevice' : [ 0x7c, ['pointer', ['_POP_FX_DEVICE']]], 'FxDeviceLock' : [ 0x80, ['long']], 'FxRemoveEvent' : [ 0x84, ['_KEVENT']], 'FxActivationCount' : [ 0x94, ['long']], 'FxSleepCount' : [ 0x98, ['long']], 'Plugin' : [ 0x9c, ['pointer', ['_POP_FX_PLUGIN']]], 'UniqueId' : [ 0xa0, ['_UNICODE_STRING']], 'PowerFlags' : [ 0xa8, ['unsigned long']], 'State' : [ 0xac, ['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', 789: 'MaxDeviceNodeState'})]], 'PreviousState' : [ 0xb0, ['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', 789: 'MaxDeviceNodeState'})]], 'StateHistory' : [ 0xb4, ['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', 789: 'MaxDeviceNodeState'})]]], 'StateHistoryEntry' : [ 0x104, ['unsigned long']], 'CompletionStatus' : [ 0x108, ['long']], 'Flags' : [ 0x10c, ['unsigned long']], 'UserFlags' : [ 0x110, ['unsigned long']], 'Problem' : [ 0x114, ['unsigned long']], 'ProblemStatus' : [ 0x118, ['long']], 'ResourceList' : [ 0x11c, ['pointer', ['_CM_RESOURCE_LIST']]], 'ResourceListTranslated' : [ 0x120, ['pointer', ['_CM_RESOURCE_LIST']]], 'DuplicatePDO' : [ 0x124, ['pointer', ['_DEVICE_OBJECT']]], 'ResourceRequirements' : [ 0x128, ['pointer', ['_IO_RESOURCE_REQUIREMENTS_LIST']]], 'InterfaceType' : [ 0x12c, ['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: 'Vmcs', 17: 'ACPIBus', 18: 'MaximumInterfaceType', -1: 'InterfaceTypeUndefined'})]], 'BusNumber' : [ 0x130, ['unsigned long']], 'ChildInterfaceType' : [ 0x134, ['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: 'Vmcs', 17: 'ACPIBus', 18: 'MaximumInterfaceType', -1: 'InterfaceTypeUndefined'})]], 'ChildBusNumber' : [ 0x138, ['unsigned long']], 'ChildBusTypeIndex' : [ 0x13c, ['unsigned short']], 'RemovalPolicy' : [ 0x13e, ['unsigned char']], 'HardwareRemovalPolicy' : [ 0x13f, ['unsigned char']], 'TargetDeviceNotify' : [ 0x140, ['_LIST_ENTRY']], 'DeviceArbiterList' : [ 0x148, ['_LIST_ENTRY']], 'DeviceTranslatorList' : [ 0x150, ['_LIST_ENTRY']], 'NoTranslatorMask' : [ 0x158, ['unsigned short']], 'QueryTranslatorMask' : [ 0x15a, ['unsigned short']], 'NoArbiterMask' : [ 0x15c, ['unsigned short']], 'QueryArbiterMask' : [ 0x15e, ['unsigned short']], 'OverUsed1' : [ 0x160, ['__unnamed_176e']], 'OverUsed2' : [ 0x164, ['__unnamed_1770']], 'BootResources' : [ 0x168, ['pointer', ['_CM_RESOURCE_LIST']]], 'BootResourcesTranslated' : [ 0x16c, ['pointer', ['_CM_RESOURCE_LIST']]], 'CapabilityFlags' : [ 0x170, ['unsigned long']], 'DockInfo' : [ 0x174, ['__unnamed_1774']], 'DisableableDepends' : [ 0x184, ['unsigned long']], 'PendedSetInterfaceState' : [ 0x188, ['_LIST_ENTRY']], 'LegacyBusListEntry' : [ 0x190, ['_LIST_ENTRY']], 'DriverUnloadRetryCount' : [ 0x198, ['unsigned long']], 'PreviousParent' : [ 0x19c, ['pointer', ['_DEVICE_NODE']]], 'DeletedChildren' : [ 0x1a0, ['unsigned long']], 'NumaNodeIndex' : [ 0x1a4, ['unsigned long']], 'ContainerID' : [ 0x1a8, ['_GUID']], 'OverrideFlags' : [ 0x1b8, ['unsigned char']], 'DeviceIdsHash' : [ 0x1bc, ['unsigned long']], 'RequiresUnloadedDriver' : [ 0x1c0, ['unsigned char']], 'PendingEjectRelations' : [ 0x1c4, ['pointer', ['_PENDING_RELATIONS_LIST_ENTRY']]], 'StateFlags' : [ 0x1c8, ['unsigned long']], } ], '_PNP_ASSIGN_RESOURCES_CONTEXT' : [ 0xc, { 'IncludeFailedDevices' : [ 0x0, ['unsigned long']], 'DeviceCount' : [ 0x4, ['unsigned long']], 'DeviceList' : [ 0x8, ['array', 1, ['pointer', ['_DEVICE_OBJECT']]]], } ], '_PNP_RESOURCE_REQUEST' : [ 0x28, { 'PhysicalDevice' : [ 0x0, ['pointer', ['_DEVICE_OBJECT']]], 'Flags' : [ 0x4, ['unsigned long']], 'AllocationType' : [ 0x8, ['Enumeration', dict(target = 'long', choices = {0: 'ArbiterRequestLegacyReported', 1: 'ArbiterRequestHalReported', 2: 'ArbiterRequestLegacyAssigned', 3: 'ArbiterRequestPnpDetected', 4: 'ArbiterRequestPnpEnumerated', -1: 'ArbiterRequestUndefined'})]], 'Priority' : [ 0xc, ['unsigned long']], 'Position' : [ 0x10, ['unsigned long']], 'ResourceRequirements' : [ 0x14, ['pointer', ['_IO_RESOURCE_REQUIREMENTS_LIST']]], 'ReqList' : [ 0x18, ['pointer', ['void']]], 'ResourceAssignment' : [ 0x1c, ['pointer', ['_CM_RESOURCE_LIST']]], 'TranslatedResourceAssignment' : [ 0x20, ['pointer', ['_CM_RESOURCE_LIST']]], 'Status' : [ 0x24, ['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: 'Vmcs', 17: 'ACPIBus', 18: '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']]], } ], '_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_181b' : [ 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']], 'SwitchPartition' : [ 0x0, ['_DBGKD_SWITCH_PARTITION']], 'GetContextEx' : [ 0x0, ['_DBGKD_CONTEXT_EX']], 'SetContextEx' : [ 0x0, ['_DBGKD_CONTEXT_EX']], } ], '_DBGKD_MANIPULATE_STATE64' : [ 0x38, { 'ApiNumber' : [ 0x0, ['unsigned long']], 'ProcessorLevel' : [ 0x4, ['unsigned short']], 'Processor' : [ 0x6, ['unsigned short']], 'ReturnStatus' : [ 0x8, ['long']], 'u' : [ 0x10, ['__unnamed_181b']], } ], '__unnamed_1822' : [ 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']], 'GetContextEx' : [ 0x0, ['_DBGKD_CONTEXT_EX']], 'SetContextEx' : [ 0x0, ['_DBGKD_CONTEXT_EX']], } ], '_DBGKD_MANIPULATE_STATE32' : [ 0x34, { 'ApiNumber' : [ 0x0, ['unsigned long']], 'ProcessorLevel' : [ 0x4, ['unsigned short']], 'Processor' : [ 0x6, ['unsigned short']], 'ReturnStatus' : [ 0x8, ['long']], 'u' : [ 0xc, ['__unnamed_1822']], } ], '_DBGKD_READ_WRITE_MSR' : [ 0xc, { 'Msr' : [ 0x0, ['unsigned long']], 'DataValueLow' : [ 0x4, ['unsigned long']], 'DataValueHigh' : [ 0x8, ['unsigned long']], } ], '_DBGKD_BREAKPOINTEX' : [ 0x8, { 'BreakPointCount' : [ 0x0, ['unsigned long']], 'ContinueStatus' : [ 0x4, ['long']], } ], '_DBGKD_SEARCH_MEMORY' : [ 0x18, { 'SearchAddress' : [ 0x0, ['unsigned long long']], 'FoundAddress' : [ 0x0, ['unsigned long long']], 'SearchLength' : [ 0x8, ['unsigned long long']], 'PatternLength' : [ 0x10, ['unsigned long']], } ], '_DBGKD_RESTORE_BREAKPOINT' : [ 0x4, { 'BreakPointHandle' : [ 0x0, ['unsigned long']], } ], '_DBGKD_CONTINUE' : [ 0x4, { 'ContinueStatus' : [ 0x0, ['long']], } ], '_DBGKD_CONTINUE2' : [ 0x20, { 'ContinueStatus' : [ 0x0, ['long']], 'ControlSet' : [ 0x4, ['_X86_DBGKD_CONTROL_SET']], 'AnyControlSet' : [ 0x4, ['_DBGKD_ANY_CONTROL_SET']], } ], '_POP_CPU_INFO' : [ 0x10, { 'Eax' : [ 0x0, ['unsigned long']], 'Ebx' : [ 0x4, ['unsigned long']], 'Ecx' : [ 0x8, ['unsigned long']], 'Edx' : [ 0xc, ['unsigned long']], } ], '_POP_FX_COMPONENT_FLAGS' : [ 0x8, { 'Value' : [ 0x0, ['long']], 'Value2' : [ 0x4, ['long']], 'RefCount' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 30, native_type='unsigned long')]], 'Idling' : [ 0x0, ['BitField', dict(start_bit = 30, end_bit = 31, native_type='unsigned long')]], 'Active' : [ 0x0, ['BitField', dict(start_bit = 31, end_bit = 32, native_type='unsigned long')]], 'CriticalIdleOverride' : [ 0x4, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]], 'ResidentOverride' : [ 0x4, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]], 'Reserved' : [ 0x4, ['BitField', dict(start_bit = 2, end_bit = 32, native_type='unsigned long')]], } ], '_POP_FX_DEVICE_STATUS' : [ 0x4, { 'Value' : [ 0x0, ['long']], 'SystemTransition' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]], 'PepD0Notify' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]], 'IdleTimerOn' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]], 'IgnoreIdleTimeout' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned long')]], 'IrpInUse' : [ 0x0, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned long')]], 'IrpPending' : [ 0x0, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned long')]], 'DPNRDeviceNotified' : [ 0x0, ['BitField', dict(start_bit = 6, end_bit = 7, native_type='unsigned long')]], 'DPNRReceivedFromPep' : [ 0x0, ['BitField', dict(start_bit = 7, end_bit = 8, native_type='unsigned long')]], 'Reserved' : [ 0x0, ['BitField', dict(start_bit = 8, end_bit = 32, native_type='unsigned long')]], } ], '_POP_RW_LOCK' : [ 0x8, { 'Lock' : [ 0x0, ['_EX_PUSH_LOCK']], 'Thread' : [ 0x4, ['pointer', ['_KTHREAD']]], } ], '_VOLUME_CACHE_MAP' : [ 0x78, { 'NodeTypeCode' : [ 0x0, ['short']], 'NodeByteCode' : [ 0x2, ['short']], 'UseCount' : [ 0x4, ['unsigned long']], 'DeviceObject' : [ 0x8, ['pointer', ['_DEVICE_OBJECT']]], 'VolumeCacheMapLinks' : [ 0xc, ['_LIST_ENTRY']], 'DirtyPages' : [ 0x14, ['unsigned long']], 'LogHandleContext' : [ 0x18, ['_LOG_HANDLE_CONTEXT']], 'Flags' : [ 0x68, ['unsigned long']], 'PagesQueuedToDisk' : [ 0x6c, ['unsigned long']], 'LoggedPagesQueuedToDisk' : [ 0x70, ['unsigned long']], } ], '_SHARED_CACHE_MAP' : [ 0x170, { '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']]]], 'FileObjectFastRef' : [ 0x44, ['_EX_FAST_REF']], 'VacbLock' : [ 0x48, ['_EX_PUSH_LOCK']], 'DirtyPages' : [ 0x4c, ['unsigned long']], 'LoggedStreamLinks' : [ 0x50, ['_LIST_ENTRY']], 'SharedCacheMapLinks' : [ 0x58, ['_LIST_ENTRY']], 'Flags' : [ 0x60, ['unsigned long']], 'Status' : [ 0x64, ['long']], 'Mbcb' : [ 0x68, ['pointer', ['_MBCB']]], 'Section' : [ 0x6c, ['pointer', ['void']]], 'CreateEvent' : [ 0x70, ['pointer', ['_KEVENT']]], 'WaitOnActiveCount' : [ 0x74, ['pointer', ['_KEVENT']]], 'PagesToWrite' : [ 0x78, ['unsigned long']], 'BeyondLastFlush' : [ 0x80, ['long long']], 'Callbacks' : [ 0x88, ['pointer', ['_CACHE_MANAGER_CALLBACKS']]], 'LazyWriteContext' : [ 0x8c, ['pointer', ['void']]], 'PrivateList' : [ 0x90, ['_LIST_ENTRY']], 'V1' : [ 0x98, ['_LOGGED_STREAM_CALLBACK_V1']], 'V2' : [ 0x98, ['_LOGGED_STREAM_CALLBACK_V2']], 'LargestLSN' : [ 0xa0, ['_LARGE_INTEGER']], 'DirtyPageThreshold' : [ 0xa8, ['unsigned long']], 'LazyWritePassCount' : [ 0xac, ['unsigned long']], 'UninitializeEvent' : [ 0xb0, ['pointer', ['_CACHE_UNINITIALIZE_EVENT']]], 'BcbLock' : [ 0xb4, ['_FAST_MUTEX']], 'LastUnmapBehindOffset' : [ 0xd8, ['_LARGE_INTEGER']], 'Event' : [ 0xe0, ['_KEVENT']], 'HighWaterMappingOffset' : [ 0xf0, ['_LARGE_INTEGER']], 'PrivateCacheMap' : [ 0xf8, ['_PRIVATE_CACHE_MAP']], 'WriteBehindWorkQueueEntry' : [ 0x160, ['pointer', ['void']]], 'VolumeCacheMap' : [ 0x164, ['pointer', ['_VOLUME_CACHE_MAP']]], 'ProcImagePathHash' : [ 0x168, ['unsigned long']], 'WritesInProgress' : [ 0x16c, ['unsigned long']], } ], '__unnamed_18a5' : [ 0x8, { 'FileOffset' : [ 0x0, ['_LARGE_INTEGER']], 'ActiveCount' : [ 0x0, ['unsigned short']], 'Links' : [ 0x0, ['_LIST_ENTRY']], } ], '_VACB' : [ 0x18, { 'BaseAddress' : [ 0x0, ['pointer', ['void']]], 'SharedCacheMap' : [ 0x4, ['pointer', ['_SHARED_CACHE_MAP']]], 'Overlay' : [ 0x8, ['__unnamed_18a5']], 'ArrayHead' : [ 0x10, ['pointer', ['_VACB_ARRAY_HEADER']]], } ], '__unnamed_18c6' : [ 0x4, { 'FileObject' : [ 0x0, ['pointer', ['_FILE_OBJECT']]], } ], '__unnamed_18c8' : [ 0x4, { 'SharedCacheMap' : [ 0x0, ['pointer', ['_SHARED_CACHE_MAP']]], } ], '__unnamed_18ca' : [ 0x4, { 'Event' : [ 0x0, ['pointer', ['_KEVENT']]], } ], '__unnamed_18cc' : [ 0x4, { 'Reason' : [ 0x0, ['unsigned long']], } ], '__unnamed_18ce' : [ 0x4, { 'Read' : [ 0x0, ['__unnamed_18c6']], 'Write' : [ 0x0, ['__unnamed_18c8']], 'Event' : [ 0x0, ['__unnamed_18ca']], 'Notification' : [ 0x0, ['__unnamed_18cc']], } ], '_WORK_QUEUE_ENTRY' : [ 0x10, { 'WorkQueueLinks' : [ 0x0, ['_LIST_ENTRY']], 'Parameters' : [ 0x8, ['__unnamed_18ce']], 'Function' : [ 0xc, ['unsigned char']], } ], '_CC_EXTERNAL_CACHE_INFO' : [ 0x18, { 'Callback' : [ 0x0, ['pointer', ['void']]], 'DirtyPageStatistics' : [ 0x4, ['_DIRTY_PAGE_STATISTICS']], 'Links' : [ 0x10, ['_LIST_ENTRY']], } ], '_LOG_HANDLE_CONTEXT' : [ 0x50, { 'LogHandle' : [ 0x0, ['pointer', ['void']]], 'FlushToLsnRoutine' : [ 0x4, ['pointer', ['void']]], 'QueryLogHandleInfoRoutine' : [ 0x8, ['pointer', ['void']]], 'DirtyPageStatistics' : [ 0xc, ['_DIRTY_PAGE_STATISTICS']], 'DirtyPageThresholds' : [ 0x18, ['_DIRTY_PAGE_THRESHOLDS']], 'AdditionalPagesToWrite' : [ 0x28, ['unsigned long']], 'CcLWScanDPThreshold' : [ 0x2c, ['unsigned long']], 'LargestLsnForCurrentLWScan' : [ 0x30, ['_LARGE_INTEGER']], 'RelatedFileObject' : [ 0x38, ['pointer', ['_FILE_OBJECT']]], 'LargestLsnFileObjectKey' : [ 0x3c, ['unsigned long']], 'LastLWTimeStamp' : [ 0x40, ['_LARGE_INTEGER']], 'Flags' : [ 0x48, ['unsigned long']], } ], '_MBCB' : [ 0x88, { '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']], 'MostRecentlyDirtiedPage' : [ 0x20, ['long long']], 'BitmapRange1' : [ 0x28, ['_BITMAP_RANGE']], 'BitmapRange2' : [ 0x48, ['_BITMAP_RANGE']], 'BitmapRange3' : [ 0x68, ['_BITMAP_RANGE']], } ], '_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']]], } ], 'VACB_LEVEL_ALLOCATION_LIST' : [ 0x10, { 'VacbLevelList' : [ 0x0, ['_LIST_ENTRY']], 'VacbLevelWithBcbListHeads' : [ 0x8, ['pointer', ['void']]], 'VacbLevelsAllocated' : [ 0xc, ['unsigned long']], } ], '_VACB_LEVEL_REFERENCE' : [ 0x8, { 'Reference' : [ 0x0, ['long']], 'SpecialReference' : [ 0x4, ['long']], } ], '_CACHE_UNINITIALIZE_EVENT' : [ 0x14, { 'Next' : [ 0x0, ['pointer', ['_CACHE_UNINITIALIZE_EVENT']]], 'Event' : [ 0x4, ['_KEVENT']], } ], '_HEAP_LIST_LOOKUP' : [ 0x24, { 'ExtendedLookup' : [ 0x0, ['pointer', ['_HEAP_LIST_LOOKUP']]], 'ArraySize' : [ 0x4, ['unsigned long']], 'ExtraItem' : [ 0x8, ['unsigned long']], 'ItemCount' : [ 0xc, ['unsigned long']], 'OutOfRangeItems' : [ 0x10, ['unsigned long']], 'BaseIndex' : [ 0x14, ['unsigned long']], 'ListHead' : [ 0x18, ['pointer', ['_LIST_ENTRY']]], 'ListsInUseUlong' : [ 0x1c, ['pointer', ['unsigned long']]], 'ListHints' : [ 0x20, ['pointer', ['pointer', ['_LIST_ENTRY']]]], } ], '_HEAP' : [ 0x248, { 'Entry' : [ 0x0, ['_HEAP_ENTRY']], 'SegmentSignature' : [ 0x8, ['unsigned long']], 'SegmentFlags' : [ 0xc, ['unsigned long']], 'SegmentListEntry' : [ 0x10, ['_LIST_ENTRY']], 'Heap' : [ 0x18, ['pointer', ['_HEAP']]], 'BaseAddress' : [ 0x1c, ['pointer', ['void']]], 'NumberOfPages' : [ 0x20, ['unsigned long']], 'FirstEntry' : [ 0x24, ['pointer', ['_HEAP_ENTRY']]], 'LastValidEntry' : [ 0x28, ['pointer', ['_HEAP_ENTRY']]], 'NumberOfUnCommittedPages' : [ 0x2c, ['unsigned long']], 'NumberOfUnCommittedRanges' : [ 0x30, ['unsigned long']], 'SegmentAllocatorBackTraceIndex' : [ 0x34, ['unsigned short']], 'Reserved' : [ 0x36, ['unsigned short']], 'UCRSegmentList' : [ 0x38, ['_LIST_ENTRY']], 'Flags' : [ 0x40, ['unsigned long']], 'ForceFlags' : [ 0x44, ['unsigned long']], 'CompatibilityFlags' : [ 0x48, ['unsigned long']], 'EncodeFlagMask' : [ 0x4c, ['unsigned long']], 'Encoding' : [ 0x50, ['_HEAP_ENTRY']], 'Interceptor' : [ 0x58, ['unsigned long']], 'VirtualMemoryThreshold' : [ 0x5c, ['unsigned long']], 'Signature' : [ 0x60, ['unsigned long']], 'SegmentReserve' : [ 0x64, ['unsigned long']], 'SegmentCommit' : [ 0x68, ['unsigned long']], 'DeCommitFreeBlockThreshold' : [ 0x6c, ['unsigned long']], 'DeCommitTotalFreeThreshold' : [ 0x70, ['unsigned long']], 'TotalFreeSize' : [ 0x74, ['unsigned long']], 'MaximumAllocationSize' : [ 0x78, ['unsigned long']], 'ProcessHeapsListIndex' : [ 0x7c, ['unsigned short']], 'HeaderValidateLength' : [ 0x7e, ['unsigned short']], 'HeaderValidateCopy' : [ 0x80, ['pointer', ['void']]], 'NextAvailableTagIndex' : [ 0x84, ['unsigned short']], 'MaximumTagIndex' : [ 0x86, ['unsigned short']], 'TagEntries' : [ 0x88, ['pointer', ['_HEAP_TAG_ENTRY']]], 'UCRList' : [ 0x8c, ['_LIST_ENTRY']], 'AlignRound' : [ 0x94, ['unsigned long']], 'AlignMask' : [ 0x98, ['unsigned long']], 'VirtualAllocdBlocks' : [ 0x9c, ['_LIST_ENTRY']], 'SegmentList' : [ 0xa4, ['_LIST_ENTRY']], 'AllocatorBackTraceIndex' : [ 0xac, ['unsigned short']], 'NonDedicatedListLength' : [ 0xb0, ['unsigned long']], 'BlocksIndex' : [ 0xb4, ['pointer', ['void']]], 'UCRIndex' : [ 0xb8, ['pointer', ['void']]], 'PseudoTagEntries' : [ 0xbc, ['pointer', ['_HEAP_PSEUDO_TAG_ENTRY']]], 'FreeLists' : [ 0xc0, ['_LIST_ENTRY']], 'LockVariable' : [ 0xc8, ['pointer', ['_HEAP_LOCK']]], 'CommitRoutine' : [ 0xcc, ['pointer', ['void']]], 'FrontEndHeap' : [ 0xd0, ['pointer', ['void']]], 'FrontHeapLockCount' : [ 0xd4, ['unsigned short']], 'FrontEndHeapType' : [ 0xd6, ['unsigned char']], 'RequestedFrontEndHeapType' : [ 0xd7, ['unsigned char']], 'FrontEndHeapUsageData' : [ 0xd8, ['pointer', ['unsigned short']]], 'FrontEndHeapMaximumIndex' : [ 0xdc, ['unsigned short']], 'FrontEndHeapStatusBitmap' : [ 0xde, ['array', 257, ['unsigned char']]], 'Counters' : [ 0x1e0, ['_HEAP_COUNTERS']], 'TuningParameters' : [ 0x23c, ['_HEAP_TUNING_PARAMETERS']], } ], '__unnamed_193c' : [ 0x38, { 'CriticalSection' : [ 0x0, ['_RTL_CRITICAL_SECTION']], 'Resource' : [ 0x0, ['_ERESOURCE']], } ], '_HEAP_LOCK' : [ 0x38, { 'Lock' : [ 0x0, ['__unnamed_193c']], } ], '_HEAP_ENTRY' : [ 0x8, { 'Size' : [ 0x0, ['unsigned short']], 'Flags' : [ 0x2, ['unsigned char']], 'SmallTagIndex' : [ 0x3, ['unsigned char']], 'SubSegmentCode' : [ 0x0, ['pointer', ['void']]], 'PreviousSize' : [ 0x4, ['unsigned short']], 'SegmentOffset' : [ 0x6, ['unsigned char']], 'LFHFlags' : [ 0x6, ['unsigned char']], 'UnusedBytes' : [ 0x7, ['unsigned char']], 'FunctionIndex' : [ 0x0, ['unsigned short']], 'ContextValue' : [ 0x2, ['unsigned short']], 'InterceptorValue' : [ 0x0, ['unsigned long']], 'UnusedBytesLength' : [ 0x4, ['unsigned short']], 'EntryOffset' : [ 0x6, ['unsigned char']], 'ExtendedBlockSignature' : [ 0x7, ['unsigned char']], 'Code1' : [ 0x0, ['unsigned long']], 'Code2' : [ 0x4, ['unsigned short']], 'Code3' : [ 0x6, ['unsigned char']], 'Code4' : [ 0x7, ['unsigned char']], 'Code234' : [ 0x4, ['unsigned long']], 'AgregateCode' : [ 0x0, ['unsigned long long']], } ], '_HEAP_SEGMENT' : [ 0x40, { 'Entry' : [ 0x0, ['_HEAP_ENTRY']], 'SegmentSignature' : [ 0x8, ['unsigned long']], 'SegmentFlags' : [ 0xc, ['unsigned long']], 'SegmentListEntry' : [ 0x10, ['_LIST_ENTRY']], 'Heap' : [ 0x18, ['pointer', ['_HEAP']]], 'BaseAddress' : [ 0x1c, ['pointer', ['void']]], 'NumberOfPages' : [ 0x20, ['unsigned long']], 'FirstEntry' : [ 0x24, ['pointer', ['_HEAP_ENTRY']]], 'LastValidEntry' : [ 0x28, ['pointer', ['_HEAP_ENTRY']]], 'NumberOfUnCommittedPages' : [ 0x2c, ['unsigned long']], 'NumberOfUnCommittedRanges' : [ 0x30, ['unsigned long']], 'SegmentAllocatorBackTraceIndex' : [ 0x34, ['unsigned short']], 'Reserved' : [ 0x36, ['unsigned short']], 'UCRSegmentList' : [ 0x38, ['_LIST_ENTRY']], } ], '_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']], } ], '_HEAP_FREE_ENTRY' : [ 0x10, { 'Size' : [ 0x0, ['unsigned short']], 'Flags' : [ 0x2, ['unsigned char']], 'SmallTagIndex' : [ 0x3, ['unsigned char']], 'SubSegmentCode' : [ 0x0, ['pointer', ['void']]], 'PreviousSize' : [ 0x4, ['unsigned short']], 'SegmentOffset' : [ 0x6, ['unsigned char']], 'LFHFlags' : [ 0x6, ['unsigned char']], 'UnusedBytes' : [ 0x7, ['unsigned char']], 'FunctionIndex' : [ 0x0, ['unsigned short']], 'ContextValue' : [ 0x2, ['unsigned short']], 'InterceptorValue' : [ 0x0, ['unsigned long']], 'UnusedBytesLength' : [ 0x4, ['unsigned short']], 'EntryOffset' : [ 0x6, ['unsigned char']], 'ExtendedBlockSignature' : [ 0x7, ['unsigned char']], 'Code1' : [ 0x0, ['unsigned long']], 'Code2' : [ 0x4, ['unsigned short']], 'Code3' : [ 0x6, ['unsigned char']], 'Code4' : [ 0x7, ['unsigned char']], 'Code234' : [ 0x4, ['unsigned long']], 'AgregateCode' : [ 0x0, ['unsigned long long']], 'FreeList' : [ 0x8, ['_LIST_ENTRY']], } ], '__unnamed_1991' : [ 0x4, { 'DataLength' : [ 0x0, ['short']], 'TotalLength' : [ 0x2, ['short']], } ], '__unnamed_1993' : [ 0x4, { 's1' : [ 0x0, ['__unnamed_1991']], 'Length' : [ 0x0, ['unsigned long']], } ], '__unnamed_1995' : [ 0x4, { 'Type' : [ 0x0, ['short']], 'DataInfoOffset' : [ 0x2, ['short']], } ], '__unnamed_1997' : [ 0x4, { 's2' : [ 0x0, ['__unnamed_1995']], 'ZeroInit' : [ 0x0, ['unsigned long']], } ], '_PORT_MESSAGE' : [ 0x18, { 'u1' : [ 0x0, ['__unnamed_1993']], 'u2' : [ 0x4, ['__unnamed_1997']], 'ClientId' : [ 0x8, ['_CLIENT_ID']], 'DoNotUseThisField' : [ 0x8, ['double']], 'MessageId' : [ 0x10, ['unsigned long']], 'ClientViewSize' : [ 0x14, ['unsigned long']], 'CallbackId' : [ 0x14, ['unsigned long']], } ], '_ALPC_MESSAGE_ATTRIBUTES' : [ 0x8, { 'AllocatedAttributes' : [ 0x0, ['unsigned long']], 'ValidAttributes' : [ 0x4, ['unsigned long']], } ], '_ALPC_HANDLE_ENTRY' : [ 0x4, { 'Object' : [ 0x0, ['pointer', ['void']]], } ], '_BLOB_TYPE' : [ 0x20, { 'ResourceId' : [ 0x0, ['Enumeration', dict(target = 'long', choices = {0: 'BLOB_TYPE_UNKNOWN', 1: 'BLOB_TYPE_CONNECTION_INFO', 2: 'BLOB_TYPE_MESSAGE', 3: 'BLOB_TYPE_SECURITY_CONTEXT', 4: 'BLOB_TYPE_SECTION', 5: 'BLOB_TYPE_REGION', 6: 'BLOB_TYPE_VIEW', 7: 'BLOB_TYPE_RESERVE', 8: 'BLOB_TYPE_DIRECT_TRANSFER', 9: 'BLOB_TYPE_HANDLE_DATA', 10: 'BLOB_TYPE_MAX_ID'})]], 'PoolTag' : [ 0x4, ['unsigned long']], 'LookasideIndex' : [ 0x8, ['unsigned long']], 'Flags' : [ 0xc, ['unsigned long']], 'Counters' : [ 0x10, ['pointer', ['_BLOB_COUNTERS']]], 'DeleteProcedure' : [ 0x14, ['pointer', ['void']]], 'DestroyProcedure' : [ 0x18, ['pointer', ['void']]], 'UsualSize' : [ 0x1c, ['unsigned long']], } ], '__unnamed_19b4' : [ 0x1, { 'ReferenceCache' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned char')]], 'Lookaside' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned char')]], 'Initializing' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned char')]], 'Deleted' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned char')]], } ], '__unnamed_19b6' : [ 0x1, { 's1' : [ 0x0, ['__unnamed_19b4']], 'Flags' : [ 0x0, ['unsigned char']], } ], '_BLOB' : [ 0x18, { 'ResourceList' : [ 0x0, ['_LIST_ENTRY']], 'FreeListEntry' : [ 0x0, ['_SINGLE_LIST_ENTRY']], 'u1' : [ 0x8, ['__unnamed_19b6']], 'ResourceId' : [ 0x9, ['unsigned char']], 'CachedReferences' : [ 0xa, ['short']], 'ReferenceCount' : [ 0xc, ['long']], 'Pad' : [ 0x10, ['unsigned long']], 'Lock' : [ 0x14, ['_EX_PUSH_LOCK']], } ], '__unnamed_19c5' : [ 0x4, { 'Internal' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]], 'Secure' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]], } ], '__unnamed_19c7' : [ 0x4, { 's1' : [ 0x0, ['__unnamed_19c5']], } ], '_KALPC_SECTION' : [ 0x28, { 'SectionObject' : [ 0x0, ['pointer', ['void']]], 'Size' : [ 0x4, ['unsigned long']], 'HandleTable' : [ 0x8, ['pointer', ['_ALPC_HANDLE_TABLE']]], 'SectionHandle' : [ 0xc, ['pointer', ['void']]], 'OwnerProcess' : [ 0x10, ['pointer', ['_EPROCESS']]], 'OwnerPort' : [ 0x14, ['pointer', ['_ALPC_PORT']]], 'u1' : [ 0x18, ['__unnamed_19c7']], 'NumberOfRegions' : [ 0x1c, ['unsigned long']], 'RegionListHead' : [ 0x20, ['_LIST_ENTRY']], } ], '__unnamed_19d0' : [ 0x4, { 'Secure' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]], } ], '__unnamed_19d2' : [ 0x4, { 's1' : [ 0x0, ['__unnamed_19d0']], } ], '_KALPC_REGION' : [ 0x30, { 'RegionListEntry' : [ 0x0, ['_LIST_ENTRY']], 'Section' : [ 0x8, ['pointer', ['_KALPC_SECTION']]], 'Offset' : [ 0xc, ['unsigned long']], 'Size' : [ 0x10, ['unsigned long']], 'ViewSize' : [ 0x14, ['unsigned long']], 'u1' : [ 0x18, ['__unnamed_19d2']], 'NumberOfViews' : [ 0x1c, ['unsigned long']], 'ViewListHead' : [ 0x20, ['_LIST_ENTRY']], 'ReadOnlyView' : [ 0x28, ['pointer', ['_KALPC_VIEW']]], 'ReadWriteView' : [ 0x2c, ['pointer', ['_KALPC_VIEW']]], } ], '__unnamed_19d8' : [ 0x4, { 'WriteAccess' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]], 'AutoRelease' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]], 'ForceUnlink' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]], } ], '__unnamed_19da' : [ 0x4, { 's1' : [ 0x0, ['__unnamed_19d8']], } ], '_KALPC_VIEW' : [ 0x34, { 'ViewListEntry' : [ 0x0, ['_LIST_ENTRY']], 'Region' : [ 0x8, ['pointer', ['_KALPC_REGION']]], 'OwnerPort' : [ 0xc, ['pointer', ['_ALPC_PORT']]], 'OwnerProcess' : [ 0x10, ['pointer', ['_EPROCESS']]], 'Address' : [ 0x14, ['pointer', ['void']]], 'Size' : [ 0x18, ['unsigned long']], 'SecureViewHandle' : [ 0x1c, ['pointer', ['void']]], 'WriteAccessHandle' : [ 0x20, ['pointer', ['void']]], 'u1' : [ 0x24, ['__unnamed_19da']], 'NumberOfOwnerMessages' : [ 0x28, ['unsigned long']], 'ProcessViewListEntry' : [ 0x2c, ['_LIST_ENTRY']], } ], '_ALPC_COMMUNICATION_INFO' : [ 0x24, { 'ConnectionPort' : [ 0x0, ['pointer', ['_ALPC_PORT']]], 'ServerCommunicationPort' : [ 0x4, ['pointer', ['_ALPC_PORT']]], 'ClientCommunicationPort' : [ 0x8, ['pointer', ['_ALPC_PORT']]], 'CommunicationList' : [ 0xc, ['_LIST_ENTRY']], 'HandleTable' : [ 0x14, ['_ALPC_HANDLE_TABLE']], } ], '__unnamed_19f5' : [ 0x4, { 'Initialized' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]], 'Type' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 3, native_type='unsigned long')]], 'ConnectionPending' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned long')]], 'ConnectionRefused' : [ 0x0, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned long')]], 'Disconnected' : [ 0x0, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned long')]], 'Closed' : [ 0x0, ['BitField', dict(start_bit = 6, end_bit = 7, native_type='unsigned long')]], 'NoFlushOnClose' : [ 0x0, ['BitField', dict(start_bit = 7, end_bit = 8, native_type='unsigned long')]], 'ReturnExtendedInfo' : [ 0x0, ['BitField', dict(start_bit = 8, end_bit = 9, native_type='unsigned long')]], 'Waitable' : [ 0x0, ['BitField', dict(start_bit = 9, end_bit = 10, native_type='unsigned long')]], 'DynamicSecurity' : [ 0x0, ['BitField', dict(start_bit = 10, end_bit = 11, native_type='unsigned long')]], 'Wow64CompletionList' : [ 0x0, ['BitField', dict(start_bit = 11, end_bit = 12, native_type='unsigned long')]], 'Lpc' : [ 0x0, ['BitField', dict(start_bit = 12, end_bit = 13, native_type='unsigned long')]], 'LpcToLpc' : [ 0x0, ['BitField', dict(start_bit = 13, end_bit = 14, native_type='unsigned long')]], 'HasCompletionList' : [ 0x0, ['BitField', dict(start_bit = 14, end_bit = 15, native_type='unsigned long')]], 'HadCompletionList' : [ 0x0, ['BitField', dict(start_bit = 15, end_bit = 16, native_type='unsigned long')]], 'EnableCompletionList' : [ 0x0, ['BitField', dict(start_bit = 16, end_bit = 17, native_type='unsigned long')]], } ], '__unnamed_19f7' : [ 0x4, { 's1' : [ 0x0, ['__unnamed_19f5']], 'State' : [ 0x0, ['unsigned long']], } ], '_ALPC_PORT' : [ 0x108, { 'PortListEntry' : [ 0x0, ['_LIST_ENTRY']], 'CommunicationInfo' : [ 0x8, ['pointer', ['_ALPC_COMMUNICATION_INFO']]], 'OwnerProcess' : [ 0xc, ['pointer', ['_EPROCESS']]], 'CompletionPort' : [ 0x10, ['pointer', ['void']]], 'CompletionKey' : [ 0x14, ['pointer', ['void']]], 'CompletionPacketLookaside' : [ 0x18, ['pointer', ['_ALPC_COMPLETION_PACKET_LOOKASIDE']]], 'PortContext' : [ 0x1c, ['pointer', ['void']]], 'StaticSecurity' : [ 0x20, ['_SECURITY_CLIENT_CONTEXT']], 'IncomingQueueLock' : [ 0x5c, ['_EX_PUSH_LOCK']], 'MainQueue' : [ 0x60, ['_LIST_ENTRY']], 'LargeMessageQueue' : [ 0x68, ['_LIST_ENTRY']], 'PendingQueueLock' : [ 0x70, ['_EX_PUSH_LOCK']], 'PendingQueue' : [ 0x74, ['_LIST_ENTRY']], 'WaitQueueLock' : [ 0x7c, ['_EX_PUSH_LOCK']], 'WaitQueue' : [ 0x80, ['_LIST_ENTRY']], 'Semaphore' : [ 0x88, ['pointer', ['_KSEMAPHORE']]], 'DummyEvent' : [ 0x88, ['pointer', ['_KEVENT']]], 'PortAttributes' : [ 0x8c, ['_ALPC_PORT_ATTRIBUTES']], 'ResourceListLock' : [ 0xb8, ['_EX_PUSH_LOCK']], 'ResourceListHead' : [ 0xbc, ['_LIST_ENTRY']], 'PortObjectLock' : [ 0xc4, ['_EX_PUSH_LOCK']], 'CompletionList' : [ 0xc8, ['pointer', ['_ALPC_COMPLETION_LIST']]], 'MessageZone' : [ 0xcc, ['pointer', ['_ALPC_MESSAGE_ZONE']]], 'CallbackObject' : [ 0xd0, ['pointer', ['_CALLBACK_OBJECT']]], 'CallbackContext' : [ 0xd4, ['pointer', ['void']]], 'CanceledQueue' : [ 0xd8, ['_LIST_ENTRY']], 'SequenceNo' : [ 0xe0, ['long']], 'u1' : [ 0xe4, ['__unnamed_19f7']], 'TargetQueuePort' : [ 0xe8, ['pointer', ['_ALPC_PORT']]], 'TargetSequencePort' : [ 0xec, ['pointer', ['_ALPC_PORT']]], 'CachedMessage' : [ 0xf0, ['pointer', ['_KALPC_MESSAGE']]], 'MainQueueLength' : [ 0xf4, ['unsigned long']], 'LargeMessageQueueLength' : [ 0xf8, ['unsigned long']], 'PendingQueueLength' : [ 0xfc, ['unsigned long']], 'CanceledQueueLength' : [ 0x100, ['unsigned long']], 'WaitQueueLength' : [ 0x104, ['unsigned long']], } ], '_ALPC_COMPLETION_LIST' : [ 0x58, { 'Entry' : [ 0x0, ['_LIST_ENTRY']], 'OwnerProcess' : [ 0x8, ['pointer', ['_EPROCESS']]], 'CompletionListLock' : [ 0xc, ['_EX_PUSH_LOCK']], 'Mdl' : [ 0x10, ['pointer', ['_MDL']]], 'UserVa' : [ 0x14, ['pointer', ['void']]], 'UserLimit' : [ 0x18, ['pointer', ['void']]], 'DataUserVa' : [ 0x1c, ['pointer', ['void']]], 'SystemVa' : [ 0x20, ['pointer', ['void']]], 'TotalSize' : [ 0x24, ['unsigned long']], 'Header' : [ 0x28, ['pointer', ['_ALPC_COMPLETION_LIST_HEADER']]], 'List' : [ 0x2c, ['pointer', ['void']]], 'ListSize' : [ 0x30, ['unsigned long']], 'Bitmap' : [ 0x34, ['pointer', ['void']]], 'BitmapSize' : [ 0x38, ['unsigned long']], 'Data' : [ 0x3c, ['pointer', ['void']]], 'DataSize' : [ 0x40, ['unsigned long']], 'BitmapLimit' : [ 0x44, ['unsigned long']], 'BitmapNextHint' : [ 0x48, ['unsigned long']], 'ConcurrencyCount' : [ 0x4c, ['unsigned long']], 'AttributeFlags' : [ 0x50, ['unsigned long']], 'AttributeSize' : [ 0x54, ['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' : [ 0x90, { 'TypeList' : [ 0x0, ['_LIST_ENTRY']], 'Name' : [ 0x8, ['_UNICODE_STRING']], 'DefaultObject' : [ 0x10, ['pointer', ['void']]], 'Index' : [ 0x14, ['unsigned char']], 'TotalNumberOfObjects' : [ 0x18, ['unsigned long']], 'TotalNumberOfHandles' : [ 0x1c, ['unsigned long']], 'HighWaterNumberOfObjects' : [ 0x20, ['unsigned long']], 'HighWaterNumberOfHandles' : [ 0x24, ['unsigned long']], 'TypeInfo' : [ 0x28, ['_OBJECT_TYPE_INITIALIZER']], 'TypeLock' : [ 0x80, ['_EX_PUSH_LOCK']], 'Key' : [ 0x84, ['unsigned long']], 'CallbackList' : [ 0x88, ['_LIST_ENTRY']], } ], '__unnamed_1a14' : [ 0x4, { 'QueueType' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 2, native_type='unsigned long')]], 'QueuePortType' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 6, native_type='unsigned long')]], 'Canceled' : [ 0x0, ['BitField', dict(start_bit = 6, end_bit = 7, native_type='unsigned long')]], 'Ready' : [ 0x0, ['BitField', dict(start_bit = 7, end_bit = 8, native_type='unsigned long')]], 'ReleaseMessage' : [ 0x0, ['BitField', dict(start_bit = 8, end_bit = 9, native_type='unsigned long')]], 'SharedQuota' : [ 0x0, ['BitField', dict(start_bit = 9, end_bit = 10, native_type='unsigned long')]], 'ReplyWaitReply' : [ 0x0, ['BitField', dict(start_bit = 10, end_bit = 11, native_type='unsigned long')]], 'OwnerPortReference' : [ 0x0, ['BitField', dict(start_bit = 11, end_bit = 12, native_type='unsigned long')]], 'ReserveReference' : [ 0x0, ['BitField', dict(start_bit = 12, end_bit = 13, native_type='unsigned long')]], 'ReceiverReference' : [ 0x0, ['BitField', dict(start_bit = 13, end_bit = 14, native_type='unsigned long')]], 'ViewAttributeRetrieved' : [ 0x0, ['BitField', dict(start_bit = 14, end_bit = 15, native_type='unsigned long')]], 'InDispatch' : [ 0x0, ['BitField', dict(start_bit = 15, end_bit = 16, native_type='unsigned long')]], } ], '__unnamed_1a16' : [ 0x4, { 's1' : [ 0x0, ['__unnamed_1a14']], 'State' : [ 0x0, ['unsigned long']], } ], '_KALPC_MESSAGE' : [ 0x90, { 'Entry' : [ 0x0, ['_LIST_ENTRY']], 'PortQueue' : [ 0x8, ['pointer', ['_ALPC_PORT']]], 'OwnerPort' : [ 0xc, ['pointer', ['_ALPC_PORT']]], 'WaitingThread' : [ 0x10, ['pointer', ['_ETHREAD']]], 'u1' : [ 0x14, ['__unnamed_1a16']], 'SequenceNo' : [ 0x18, ['long']], 'QuotaProcess' : [ 0x1c, ['pointer', ['_EPROCESS']]], 'QuotaBlock' : [ 0x1c, ['pointer', ['void']]], 'CancelSequencePort' : [ 0x20, ['pointer', ['_ALPC_PORT']]], 'CancelQueuePort' : [ 0x24, ['pointer', ['_ALPC_PORT']]], 'CancelSequenceNo' : [ 0x28, ['long']], 'CancelListEntry' : [ 0x2c, ['_LIST_ENTRY']], 'Reserve' : [ 0x34, ['pointer', ['_KALPC_RESERVE']]], 'MessageAttributes' : [ 0x38, ['_KALPC_MESSAGE_ATTRIBUTES']], 'DataUserVa' : [ 0x54, ['pointer', ['void']]], 'DataSystemVa' : [ 0x58, ['pointer', ['void']]], 'CommunicationInfo' : [ 0x5c, ['pointer', ['_ALPC_COMMUNICATION_INFO']]], 'ConnectionPort' : [ 0x60, ['pointer', ['_ALPC_PORT']]], 'ServerThread' : [ 0x64, ['pointer', ['_ETHREAD']]], 'WakeReference' : [ 0x68, ['pointer', ['void']]], 'ExtensionBuffer' : [ 0x6c, ['pointer', ['void']]], 'ExtensionBufferSize' : [ 0x70, ['unsigned long']], 'PortMessage' : [ 0x78, ['_PORT_MESSAGE']], } ], '_REMOTE_PORT_VIEW' : [ 0xc, { 'Length' : [ 0x0, ['unsigned long']], 'ViewSize' : [ 0x4, ['unsigned long']], 'ViewBase' : [ 0x8, ['pointer', ['void']]], } ], '_KALPC_RESERVE' : [ 0x14, { 'OwnerPort' : [ 0x0, ['pointer', ['_ALPC_PORT']]], 'HandleTable' : [ 0x4, ['pointer', ['_ALPC_HANDLE_TABLE']]], 'Handle' : [ 0x8, ['pointer', ['void']]], 'Message' : [ 0xc, ['pointer', ['_KALPC_MESSAGE']]], 'Active' : [ 0x10, ['long']], } ], '_KALPC_HANDLE_DATA' : [ 0xc, { 'Flags' : [ 0x0, ['unsigned long']], 'ObjectType' : [ 0x4, ['unsigned long']], 'DuplicateContext' : [ 0x8, ['pointer', ['_OB_DUPLICATE_OBJECT_STATE']]], } ], '_KALPC_MESSAGE_ATTRIBUTES' : [ 0x1c, { 'ClientContext' : [ 0x0, ['pointer', ['void']]], 'ServerContext' : [ 0x4, ['pointer', ['void']]], 'PortContext' : [ 0x8, ['pointer', ['void']]], 'CancelPortContext' : [ 0xc, ['pointer', ['void']]], 'SecurityData' : [ 0x10, ['pointer', ['_KALPC_SECURITY_DATA']]], 'View' : [ 0x14, ['pointer', ['_KALPC_VIEW']]], 'HandleData' : [ 0x18, ['pointer', ['_KALPC_HANDLE_DATA']]], } ], '__unnamed_1a4d' : [ 0x4, { 'Revoked' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]], 'Impersonated' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]], } ], '__unnamed_1a4f' : [ 0x4, { 's1' : [ 0x0, ['__unnamed_1a4d']], } ], '_KALPC_SECURITY_DATA' : [ 0x50, { 'HandleTable' : [ 0x0, ['pointer', ['_ALPC_HANDLE_TABLE']]], 'ContextHandle' : [ 0x4, ['pointer', ['void']]], 'OwningProcess' : [ 0x8, ['pointer', ['_EPROCESS']]], 'OwnerPort' : [ 0xc, ['pointer', ['_ALPC_PORT']]], 'DynamicSecurity' : [ 0x10, ['_SECURITY_CLIENT_CONTEXT']], 'u1' : [ 0x4c, ['__unnamed_1a4f']], } ], '_IO_MINI_COMPLETION_PACKET_USER' : [ 0x28, { 'ListEntry' : [ 0x0, ['_LIST_ENTRY']], 'PacketType' : [ 0x8, ['unsigned long']], 'KeyContext' : [ 0xc, ['pointer', ['void']]], 'ApcContext' : [ 0x10, ['pointer', ['void']]], 'IoStatus' : [ 0x14, ['long']], 'IoStatusInformation' : [ 0x18, ['unsigned long']], 'MiniPacketCallback' : [ 0x1c, ['pointer', ['void']]], 'Context' : [ 0x20, ['pointer', ['void']]], 'Allocated' : [ 0x24, ['unsigned char']], } ], '_ALPC_DISPATCH_CONTEXT' : [ 0x20, { 'PortObject' : [ 0x0, ['pointer', ['_ALPC_PORT']]], 'Message' : [ 0x4, ['pointer', ['_KALPC_MESSAGE']]], 'CommunicationInfo' : [ 0x8, ['pointer', ['_ALPC_COMMUNICATION_INFO']]], 'TargetThread' : [ 0xc, ['pointer', ['_ETHREAD']]], 'TargetPort' : [ 0x10, ['pointer', ['_ALPC_PORT']]], 'Flags' : [ 0x14, ['unsigned long']], 'TotalLength' : [ 0x18, ['unsigned short']], 'Type' : [ 0x1a, ['unsigned short']], 'DataInfoOffset' : [ 0x1c, ['unsigned short']], 'SignalCompletion' : [ 0x1e, ['unsigned char']], 'PostedToCompletionList' : [ 0x1f, ['unsigned char']], } ], '_IOP_IRP_EXTENSION' : [ 0x20, { 'ExtensionFlags' : [ 0x0, ['unsigned short']], 'Allocated' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned short')]], 'PropagateId' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned short')]], 'TimeStamped' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned short')]], 'SpareBits' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 8, native_type='unsigned short')]], 'TypesAllocated' : [ 0x2, ['unsigned short']], 'ActivityId' : [ 0x4, ['_GUID']], 'Timestamp' : [ 0x18, ['_LARGE_INTEGER']], } ], '_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']]]], } ], '_FILE_SEGMENT_ELEMENT' : [ 0x8, { 'Buffer' : [ 0x0, ['pointer64', ['void']]], 'Alignment' : [ 0x0, ['unsigned long long']], } ], '_RELATIVE_SYMLINK_INFO' : [ 0x14, { 'ExposedNamespaceLength' : [ 0x0, ['unsigned short']], 'Flags' : [ 0x2, ['unsigned short']], 'DeviceNameLength' : [ 0x4, ['unsigned short']], 'Reserved' : [ 0x6, ['unsigned short']], 'InteriorMountPoint' : [ 0x8, ['pointer', ['_RELATIVE_SYMLINK_INFO']]], 'OpenedName' : [ 0xc, ['_UNICODE_STRING']], } ], '_ECP_LIST' : [ 0x10, { 'Signature' : [ 0x0, ['unsigned long']], 'Flags' : [ 0x4, ['unsigned long']], 'EcpList' : [ 0x8, ['_LIST_ENTRY']], } ], '_IOP_FILE_OBJECT_EXTENSION' : [ 0x24, { 'FoExtFlags' : [ 0x0, ['unsigned long']], 'FoExtPerTypeExtension' : [ 0x4, ['array', 7, ['pointer', ['void']]]], 'FoIoPriorityHint' : [ 0x20, ['Enumeration', dict(target = 'long', choices = {0: 'IopIoPriorityNotSet', 1: 'IopIoPriorityVeryLow', 2: 'IopIoPriorityLow', 3: 'IopIoPriorityNormal', 4: 'IopIoPriorityHigh', 5: 'IopIoPriorityCritical', 6: 'MaxIopIoPriorityTypes'})]], } ], '_OPEN_PACKET' : [ 0x70, { 'Type' : [ 0x0, ['short']], 'Size' : [ 0x2, ['short']], 'FileObject' : [ 0x4, ['pointer', ['_FILE_OBJECT']]], 'FinalStatus' : [ 0x8, ['long']], 'Information' : [ 0xc, ['unsigned long']], 'ParseCheck' : [ 0x10, ['unsigned long']], 'RelatedFileObject' : [ 0x14, ['pointer', ['_FILE_OBJECT']]], 'ReferencedDeviceObject' : [ 0x14, ['pointer', ['_DEVICE_OBJECT']]], 'OriginalAttributes' : [ 0x18, ['pointer', ['_OBJECT_ATTRIBUTES']]], 'AllocationSize' : [ 0x20, ['_LARGE_INTEGER']], 'CreateOptions' : [ 0x28, ['unsigned long']], 'FileAttributes' : [ 0x2c, ['unsigned short']], 'ShareAccess' : [ 0x2e, ['unsigned short']], 'EaBuffer' : [ 0x30, ['pointer', ['void']]], 'EaLength' : [ 0x34, ['unsigned long']], 'Options' : [ 0x38, ['unsigned long']], 'Disposition' : [ 0x3c, ['unsigned long']], 'BasicInformation' : [ 0x40, ['pointer', ['_FILE_BASIC_INFORMATION']]], 'NetworkInformation' : [ 0x44, ['pointer', ['_FILE_NETWORK_OPEN_INFORMATION']]], 'CreateFileType' : [ 0x48, ['Enumeration', dict(target = 'long', choices = {0: 'CreateFileTypeNone', 1: 'CreateFileTypeNamedPipe', 2: 'CreateFileTypeMailslot'})]], 'MailslotOrPipeParameters' : [ 0x4c, ['pointer', ['void']]], 'Override' : [ 0x50, ['unsigned char']], 'QueryOnly' : [ 0x51, ['unsigned char']], 'DeleteOnly' : [ 0x52, ['unsigned char']], 'FullAttributes' : [ 0x53, ['unsigned char']], 'LocalFileObject' : [ 0x54, ['pointer', ['_DUMMY_FILE_OBJECT']]], 'InternalFlags' : [ 0x58, ['unsigned long']], 'AccessMode' : [ 0x5c, ['unsigned char']], 'DriverCreateContext' : [ 0x60, ['_IO_DRIVER_CREATE_CONTEXT']], } ], '_ETW_SYSTEMTIME' : [ 0x10, { 'Year' : [ 0x0, ['unsigned short']], 'Month' : [ 0x2, ['unsigned short']], 'DayOfWeek' : [ 0x4, ['unsigned short']], 'Day' : [ 0x6, ['unsigned short']], 'Hour' : [ 0x8, ['unsigned short']], 'Minute' : [ 0xa, ['unsigned short']], 'Second' : [ 0xc, ['unsigned short']], 'Milliseconds' : [ 0xe, ['unsigned short']], } ], '_TIME_FIELDS' : [ 0x10, { 'Year' : [ 0x0, ['short']], 'Month' : [ 0x2, ['short']], 'Day' : [ 0x4, ['short']], 'Hour' : [ 0x6, ['short']], 'Minute' : [ 0x8, ['short']], 'Second' : [ 0xa, ['short']], 'Milliseconds' : [ 0xc, ['short']], 'Weekday' : [ 0xe, ['short']], } ], '__unnamed_1b16' : [ 0x4, { 'MajorVersion' : [ 0x0, ['unsigned char']], 'MinorVersion' : [ 0x1, ['unsigned char']], 'SubVersion' : [ 0x2, ['unsigned char']], 'SubMinorVersion' : [ 0x3, ['unsigned char']], } ], '_TRACE_LOGFILE_HEADER' : [ 0x110, { 'BufferSize' : [ 0x0, ['unsigned long']], 'Version' : [ 0x4, ['unsigned long']], 'VersionDetail' : [ 0x4, ['__unnamed_1b16']], 'ProviderVersion' : [ 0x8, ['unsigned long']], 'NumberOfProcessors' : [ 0xc, ['unsigned long']], 'EndTime' : [ 0x10, ['_LARGE_INTEGER']], 'TimerResolution' : [ 0x18, ['unsigned long']], 'MaximumFileSize' : [ 0x1c, ['unsigned long']], 'LogFileMode' : [ 0x20, ['unsigned long']], 'BuffersWritten' : [ 0x24, ['unsigned long']], 'LogInstanceGuid' : [ 0x28, ['_GUID']], 'StartBuffers' : [ 0x28, ['unsigned long']], 'PointerSize' : [ 0x2c, ['unsigned long']], 'EventsLost' : [ 0x30, ['unsigned long']], 'CpuSpeedInMHz' : [ 0x34, ['unsigned long']], 'LoggerName' : [ 0x38, ['pointer', ['unsigned short']]], 'LogFileName' : [ 0x3c, ['pointer', ['unsigned short']]], 'TimeZone' : [ 0x40, ['_RTL_TIME_ZONE_INFORMATION']], 'BootTime' : [ 0xf0, ['_LARGE_INTEGER']], 'PerfFreq' : [ 0xf8, ['_LARGE_INTEGER']], 'StartTime' : [ 0x100, ['_LARGE_INTEGER']], 'ReservedFlags' : [ 0x108, ['unsigned long']], 'BuffersLost' : [ 0x10c, ['unsigned long']], } ], '_WMI_LOGGER_CONTEXT' : [ 0x270, { 'LoggerId' : [ 0x0, ['unsigned long']], 'BufferSize' : [ 0x4, ['unsigned long']], 'MaximumEventSize' : [ 0x8, ['unsigned long']], 'LoggerMode' : [ 0xc, ['unsigned long']], 'AcceptNewEvents' : [ 0x10, ['long']], 'EventMarker' : [ 0x14, ['array', 1, ['unsigned long']]], 'ErrorMarker' : [ 0x18, ['unsigned long']], 'SizeMask' : [ 0x1c, ['unsigned long']], 'GetCpuClock' : [ 0x20, ['pointer', ['void']]], 'LoggerThread' : [ 0x24, ['pointer', ['_ETHREAD']]], 'LoggerStatus' : [ 0x28, ['long']], 'FailureReason' : [ 0x2c, ['unsigned long']], 'BufferQueue' : [ 0x30, ['_ETW_BUFFER_QUEUE']], 'OverflowQueue' : [ 0x3c, ['_ETW_BUFFER_QUEUE']], 'GlobalList' : [ 0x48, ['_LIST_ENTRY']], 'ProviderBinaryList' : [ 0x50, ['_LIST_ENTRY']], 'BatchedBufferList' : [ 0x58, ['pointer', ['_WMI_BUFFER_HEADER']]], 'CurrentBuffer' : [ 0x58, ['_EX_FAST_REF']], 'LoggerName' : [ 0x5c, ['_UNICODE_STRING']], 'LogFileName' : [ 0x64, ['_UNICODE_STRING']], 'LogFilePattern' : [ 0x6c, ['_UNICODE_STRING']], 'NewLogFileName' : [ 0x74, ['_UNICODE_STRING']], 'ClockType' : [ 0x7c, ['unsigned long']], 'LastFlushedBuffer' : [ 0x80, ['unsigned long']], 'FlushTimer' : [ 0x84, ['unsigned long']], 'FlushThreshold' : [ 0x88, ['unsigned long']], 'ByteOffset' : [ 0x90, ['_LARGE_INTEGER']], 'MinimumBuffers' : [ 0x98, ['unsigned long']], 'BuffersAvailable' : [ 0x9c, ['long']], 'NumberOfBuffers' : [ 0xa0, ['long']], 'MaximumBuffers' : [ 0xa4, ['unsigned long']], 'EventsLost' : [ 0xa8, ['unsigned long']], 'BuffersWritten' : [ 0xac, ['unsigned long']], 'LogBuffersLost' : [ 0xb0, ['unsigned long']], 'RealTimeBuffersDelivered' : [ 0xb4, ['unsigned long']], 'RealTimeBuffersLost' : [ 0xb8, ['unsigned long']], 'SequencePtr' : [ 0xbc, ['pointer', ['long']]], 'LocalSequence' : [ 0xc0, ['unsigned long']], 'InstanceGuid' : [ 0xc4, ['_GUID']], 'MaximumFileSize' : [ 0xd4, ['unsigned long']], 'FileCounter' : [ 0xd8, ['long']], 'PoolType' : [ 0xdc, ['Enumeration', dict(target = 'long', choices = {0: 'NonPagedPoolBase', 1: 'PagedPool', 2: 'NonPagedPoolBaseMustSucceed', 3: 'DontUseThisType', 4: 'NonPagedPoolBaseCacheAligned', 5: 'PagedPoolCacheAligned', 6: 'NonPagedPoolBaseCacheAlignedMustS', 7: 'MaxPoolType', 34: 'NonPagedPoolMustSucceedSession', 516: 'NonPagedPoolNxCacheAligned', 35: 'DontUseThisTypeSession', 32: 'NonPagedPoolSession', 512: 'NonPagedPoolNx', 544: 'NonPagedPoolSessionNx', 36: 'NonPagedPoolCacheAlignedSession', 33: 'PagedPoolSession', 38: 'NonPagedPoolCacheAlignedMustSSession', 37: 'PagedPoolCacheAlignedSession'})]], 'ReferenceTime' : [ 0xe0, ['_ETW_REF_CLOCK']], 'CollectionOn' : [ 0xf0, ['long']], 'ProviderInfoSize' : [ 0xf4, ['unsigned long']], 'Consumers' : [ 0xf8, ['_LIST_ENTRY']], 'NumConsumers' : [ 0x100, ['unsigned long']], 'TransitionConsumer' : [ 0x104, ['pointer', ['_ETW_REALTIME_CONSUMER']]], 'RealtimeLogfileHandle' : [ 0x108, ['pointer', ['void']]], 'RealtimeLogfileName' : [ 0x10c, ['_UNICODE_STRING']], 'RealtimeWriteOffset' : [ 0x118, ['_LARGE_INTEGER']], 'RealtimeReadOffset' : [ 0x120, ['_LARGE_INTEGER']], 'RealtimeLogfileSize' : [ 0x128, ['_LARGE_INTEGER']], 'RealtimeLogfileUsage' : [ 0x130, ['unsigned long long']], 'RealtimeMaximumFileSize' : [ 0x138, ['unsigned long long']], 'RealtimeBuffersSaved' : [ 0x140, ['unsigned long']], 'RealtimeReferenceTime' : [ 0x148, ['_ETW_REF_CLOCK']], 'NewRTEventsLost' : [ 0x158, ['Enumeration', dict(target = 'long', choices = {0: 'EtwRtEventNoLoss', 1: 'EtwRtEventLost', 2: 'EtwRtBufferLost', 3: 'EtwRtBackupLost', 4: 'EtwRtEventLossMax'})]], 'LoggerEvent' : [ 0x15c, ['_KEVENT']], 'FlushEvent' : [ 0x16c, ['_KEVENT']], 'FlushTimeOutTimer' : [ 0x180, ['_KTIMER']], 'LoggerDpc' : [ 0x1a8, ['_KDPC']], 'LoggerMutex' : [ 0x1c8, ['_KMUTANT']], 'LoggerLock' : [ 0x1e8, ['_EX_PUSH_LOCK']], 'BufferListSpinLock' : [ 0x1ec, ['unsigned long']], 'BufferListPushLock' : [ 0x1ec, ['_EX_PUSH_LOCK']], 'ClientSecurityContext' : [ 0x1f0, ['_SECURITY_CLIENT_CONTEXT']], 'SecurityDescriptor' : [ 0x22c, ['_EX_FAST_REF']], 'StartTime' : [ 0x230, ['_LARGE_INTEGER']], 'LogFileHandle' : [ 0x238, ['pointer', ['void']]], 'BufferSequenceNumber' : [ 0x240, ['long long']], 'Flags' : [ 0x248, ['unsigned long']], 'Persistent' : [ 0x248, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]], 'AutoLogger' : [ 0x248, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]], 'FsReady' : [ 0x248, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]], 'RealTime' : [ 0x248, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned long')]], 'Wow' : [ 0x248, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned long')]], 'KernelTrace' : [ 0x248, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned long')]], 'NoMoreEnable' : [ 0x248, ['BitField', dict(start_bit = 6, end_bit = 7, native_type='unsigned long')]], 'StackTracing' : [ 0x248, ['BitField', dict(start_bit = 7, end_bit = 8, native_type='unsigned long')]], 'ErrorLogged' : [ 0x248, ['BitField', dict(start_bit = 8, end_bit = 9, native_type='unsigned long')]], 'RealtimeLoggerContextFreed' : [ 0x248, ['BitField', dict(start_bit = 9, end_bit = 10, native_type='unsigned long')]], 'PebsTracing' : [ 0x248, ['BitField', dict(start_bit = 10, end_bit = 11, native_type='unsigned long')]], 'PmcCounters' : [ 0x248, ['BitField', dict(start_bit = 11, end_bit = 12, native_type='unsigned long')]], 'PageAlignBuffers' : [ 0x248, ['BitField', dict(start_bit = 12, end_bit = 13, native_type='unsigned long')]], 'SpareFlags1' : [ 0x248, ['BitField', dict(start_bit = 13, end_bit = 16, native_type='unsigned long')]], 'SystemLoggerIndex' : [ 0x248, ['BitField', dict(start_bit = 16, end_bit = 24, native_type='unsigned long')]], 'StackCaching' : [ 0x248, ['BitField', dict(start_bit = 24, end_bit = 25, native_type='unsigned long')]], 'SpareFlags2' : [ 0x248, ['BitField', dict(start_bit = 25, end_bit = 32, native_type='unsigned long')]], 'RequestFlag' : [ 0x24c, ['unsigned long']], 'DbgRequestNewFie' : [ 0x24c, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]], 'DbgRequestUpdateFile' : [ 0x24c, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]], 'DbgRequestFlush' : [ 0x24c, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]], 'DbgRequestDisableRealtime' : [ 0x24c, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned long')]], 'DbgRequestDisconnectConsumer' : [ 0x24c, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned long')]], 'DbgRequestConnectConsumer' : [ 0x24c, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned long')]], 'DbgRequestNotifyConsumer' : [ 0x24c, ['BitField', dict(start_bit = 6, end_bit = 7, native_type='unsigned long')]], 'DbgRequestUpdateHeader' : [ 0x24c, ['BitField', dict(start_bit = 7, end_bit = 8, native_type='unsigned long')]], 'DbgRequestDefferdFlush' : [ 0x24c, ['BitField', dict(start_bit = 8, end_bit = 9, native_type='unsigned long')]], 'DbgRequestDefferdFlushTimer' : [ 0x24c, ['BitField', dict(start_bit = 9, end_bit = 10, native_type='unsigned long')]], 'DbgRequestFlushTimer' : [ 0x24c, ['BitField', dict(start_bit = 10, end_bit = 11, native_type='unsigned long')]], 'DbgRequestUpdateDebugger' : [ 0x24c, ['BitField', dict(start_bit = 11, end_bit = 12, native_type='unsigned long')]], 'DbgSpareRequestFlags' : [ 0x24c, ['BitField', dict(start_bit = 12, end_bit = 32, native_type='unsigned long')]], 'HookIdMap' : [ 0x250, ['_RTL_BITMAP']], 'StackCache' : [ 0x258, ['pointer', ['_ETW_STACK_CACHE']]], 'PmcData' : [ 0x25c, ['pointer', ['_ETW_PMC_SUPPORT']]], 'WinRtProviderBinaryList' : [ 0x260, ['_LIST_ENTRY']], 'ScratchArray' : [ 0x268, ['pointer', ['pointer', ['_WMI_BUFFER_HEADER']]]], } ], '_ETW_PMC_SUPPORT' : [ 0x24, { 'Source' : [ 0x0, ['array', -16, ['Enumeration', dict(target = 'long', choices = {0: 'ProfileTime', 1: 'ProfileAlignmentFixup', 2: 'ProfileTotalIssues', 3: 'ProfilePipelineDry', 4: 'ProfileLoadInstructions', 5: 'ProfilePipelineFrozen', 6: 'ProfileBranchInstructions', 7: 'ProfileTotalNonissues', 8: 'ProfileDcacheMisses', 9: 'ProfileIcacheMisses', 10: 'ProfileCacheMisses', 11: 'ProfileBranchMispredictions', 12: 'ProfileStoreInstructions', 13: 'ProfileFpInstructions', 14: 'ProfileIntegerInstructions', 15: 'Profile2Issue', 16: 'Profile3Issue', 17: 'Profile4Issue', 18: 'ProfileSpecialInstructions', 19: 'ProfileTotalCycles', 20: 'ProfileIcacheIssues', 21: 'ProfileDcacheAccesses', 22: 'ProfileMemoryBarrierCycles', 23: 'ProfileLoadLinkedIssues', 24: 'ProfileMaximum'})]]], 'HookIdCount' : [ 0x10, ['unsigned long']], 'HookId' : [ 0x14, ['array', 4, ['unsigned short']]], 'CountersCount' : [ 0x1c, ['unsigned long']], 'ProcessorCtrs' : [ 0x20, ['array', 1, ['pointer', ['_HAL_PMC_COUNTERS']]]], } ], '_ETW_LOGGER_HANDLE' : [ 0x1, { 'DereferenceAndLeave' : [ 0x0, ['unsigned char']], } ], '_LUID_AND_ATTRIBUTES' : [ 0xc, { 'Luid' : [ 0x0, ['_LUID']], 'Attributes' : [ 0x8, ['unsigned long']], } ], '_TOKEN' : [ 0x288, { 'TokenSource' : [ 0x0, ['_TOKEN_SOURCE']], 'TokenId' : [ 0x10, ['_LUID']], 'AuthenticationId' : [ 0x18, ['_LUID']], 'ParentTokenId' : [ 0x20, ['_LUID']], 'ExpirationTime' : [ 0x28, ['_LARGE_INTEGER']], 'TokenLock' : [ 0x30, ['pointer', ['_ERESOURCE']]], 'ModifiedId' : [ 0x34, ['_LUID']], 'Privileges' : [ 0x40, ['_SEP_TOKEN_PRIVILEGES']], 'AuditPolicy' : [ 0x58, ['_SEP_AUDIT_POLICY']], 'SessionId' : [ 0x78, ['unsigned long']], 'UserAndGroupCount' : [ 0x7c, ['unsigned long']], 'RestrictedSidCount' : [ 0x80, ['unsigned long']], 'VariableLength' : [ 0x84, ['unsigned long']], 'DynamicCharged' : [ 0x88, ['unsigned long']], 'DynamicAvailable' : [ 0x8c, ['unsigned long']], 'DefaultOwnerIndex' : [ 0x90, ['unsigned long']], 'UserAndGroups' : [ 0x94, ['pointer', ['_SID_AND_ATTRIBUTES']]], 'RestrictedSids' : [ 0x98, ['pointer', ['_SID_AND_ATTRIBUTES']]], 'PrimaryGroup' : [ 0x9c, ['pointer', ['void']]], 'DynamicPart' : [ 0xa0, ['pointer', ['unsigned long']]], 'DefaultDacl' : [ 0xa4, ['pointer', ['_ACL']]], 'TokenType' : [ 0xa8, ['Enumeration', dict(target = 'long', choices = {1: 'TokenPrimary', 2: 'TokenImpersonation'})]], 'ImpersonationLevel' : [ 0xac, ['Enumeration', dict(target = 'long', choices = {0: 'SecurityAnonymous', 1: 'SecurityIdentification', 2: 'SecurityImpersonation', 3: 'SecurityDelegation'})]], 'TokenFlags' : [ 0xb0, ['unsigned long']], 'TokenInUse' : [ 0xb4, ['unsigned char']], 'IntegrityLevelIndex' : [ 0xb8, ['unsigned long']], 'MandatoryPolicy' : [ 0xbc, ['unsigned long']], 'LogonSession' : [ 0xc0, ['pointer', ['_SEP_LOGON_SESSION_REFERENCES']]], 'OriginatingLogonSession' : [ 0xc4, ['_LUID']], 'SidHash' : [ 0xcc, ['_SID_AND_ATTRIBUTES_HASH']], 'RestrictedSidHash' : [ 0x154, ['_SID_AND_ATTRIBUTES_HASH']], 'pSecurityAttributes' : [ 0x1dc, ['pointer', ['_AUTHZBASEP_SECURITY_ATTRIBUTES_INFORMATION']]], 'Package' : [ 0x1e0, ['pointer', ['void']]], 'Capabilities' : [ 0x1e4, ['pointer', ['_SID_AND_ATTRIBUTES']]], 'CapabilityCount' : [ 0x1e8, ['unsigned long']], 'CapabilitiesHash' : [ 0x1ec, ['_SID_AND_ATTRIBUTES_HASH']], 'LowboxNumberEntry' : [ 0x274, ['pointer', ['_SEP_LOWBOX_NUMBER_ENTRY']]], 'LowboxHandlesEntry' : [ 0x278, ['pointer', ['_SEP_LOWBOX_HANDLES_ENTRY']]], 'pClaimAttributes' : [ 0x27c, ['pointer', ['_AUTHZBASEP_CLAIM_ATTRIBUTES_COLLECTION']]], 'VariablePart' : [ 0x280, ['unsigned long']], } ], '_SEP_LOGON_SESSION_REFERENCES' : [ 0x3c, { 'Next' : [ 0x0, ['pointer', ['_SEP_LOGON_SESSION_REFERENCES']]], 'LogonId' : [ 0x4, ['_LUID']], 'BuddyLogonId' : [ 0xc, ['_LUID']], 'ReferenceCount' : [ 0x14, ['unsigned long']], 'Flags' : [ 0x18, ['unsigned long']], 'pDeviceMap' : [ 0x1c, ['pointer', ['_DEVICE_MAP']]], 'Token' : [ 0x20, ['pointer', ['void']]], 'AccountName' : [ 0x24, ['_UNICODE_STRING']], 'AuthorityName' : [ 0x2c, ['_UNICODE_STRING']], 'LowBoxHandlesTable' : [ 0x34, ['_SEP_LOWBOX_HANDLES_TABLE']], } ], '_OBJECT_HEADER' : [ 0x20, { 'PointerCount' : [ 0x0, ['long']], 'HandleCount' : [ 0x4, ['long']], 'NextToFree' : [ 0x4, ['pointer', ['void']]], 'Lock' : [ 0x8, ['_EX_PUSH_LOCK']], 'TypeIndex' : [ 0xc, ['unsigned char']], 'TraceFlags' : [ 0xd, ['unsigned char']], 'DbgRefTrace' : [ 0xd, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned char')]], 'DbgTracePermanent' : [ 0xd, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned char')]], 'InfoMask' : [ 0xe, ['unsigned char']], 'Flags' : [ 0xf, ['unsigned char']], 'ObjectCreateInfo' : [ 0x10, ['pointer', ['_OBJECT_CREATE_INFORMATION']]], 'QuotaBlockCharged' : [ 0x10, ['pointer', ['void']]], 'SecurityDescriptor' : [ 0x14, ['pointer', ['void']]], 'Body' : [ 0x18, ['_QUAD']], } ], '_OBJECT_HEADER_QUOTA_INFO' : [ 0x10, { 'PagedPoolCharge' : [ 0x0, ['unsigned long']], 'NonPagedPoolCharge' : [ 0x4, ['unsigned long']], 'SecurityDescriptorCharge' : [ 0x8, ['unsigned long']], 'SecurityDescriptorQuotaBlock' : [ 0xc, ['pointer', ['void']]], } ], '_OBJECT_HEADER_PROCESS_INFO' : [ 0x8, { 'ExclusiveProcess' : [ 0x0, ['pointer', ['_EPROCESS']]], 'Reserved' : [ 0x4, ['unsigned long']], } ], '_OBJECT_HEADER_HANDLE_INFO' : [ 0x8, { 'HandleCountDataBase' : [ 0x0, ['pointer', ['_OBJECT_HANDLE_COUNT_DATABASE']]], 'SingleEntry' : [ 0x0, ['_OBJECT_HANDLE_COUNT_ENTRY']], } ], '_OBJECT_HEADER_NAME_INFO' : [ 0x10, { 'Directory' : [ 0x0, ['pointer', ['_OBJECT_DIRECTORY']]], 'Name' : [ 0x4, ['_UNICODE_STRING']], 'ReferenceCount' : [ 0xc, ['long']], } ], '_OBJECT_HEADER_CREATOR_INFO' : [ 0x10, { 'TypeList' : [ 0x0, ['_LIST_ENTRY']], 'CreatorUniqueProcess' : [ 0x8, ['pointer', ['void']]], 'CreatorBackTraceIndex' : [ 0xc, ['unsigned short']], 'Reserved' : [ 0xe, ['unsigned short']], } ], '_OBJECT_HEADER_AUDIT_INFO' : [ 0x8, { 'SecurityDescriptor' : [ 0x0, ['pointer', ['void']]], 'Reserved' : [ 0x4, ['unsigned long']], } ], '_OBP_LOOKUP_CONTEXT' : [ 0x18, { 'Directory' : [ 0x0, ['pointer', ['_OBJECT_DIRECTORY']]], 'Object' : [ 0x4, ['pointer', ['void']]], 'EntryLink' : [ 0x8, ['pointer', ['pointer', ['_OBJECT_DIRECTORY_ENTRY']]]], 'HashValue' : [ 0xc, ['unsigned long']], 'HashIndex' : [ 0x10, ['unsigned short']], 'DirectoryLocked' : [ 0x12, ['unsigned char']], 'LockedExclusive' : [ 0x13, ['unsigned char']], 'LockStateSignature' : [ 0x14, ['unsigned long']], } ], '_OBJECT_DIRECTORY' : [ 0xa8, { 'HashBuckets' : [ 0x0, ['array', 37, ['pointer', ['_OBJECT_DIRECTORY_ENTRY']]]], 'Lock' : [ 0x94, ['_EX_PUSH_LOCK']], 'DeviceMap' : [ 0x98, ['pointer', ['_DEVICE_MAP']]], 'ShadowDirectory' : [ 0x98, ['pointer', ['_OBJECT_DIRECTORY']]], 'SessionId' : [ 0x9c, ['unsigned long']], 'NamespaceEntry' : [ 0xa0, ['pointer', ['void']]], 'Flags' : [ 0xa4, ['unsigned long']], } ], '_WHEAP_INFO_BLOCK' : [ 0xc, { 'ErrorSourceCount' : [ 0x0, ['unsigned long']], 'ErrorSourceTable' : [ 0x4, ['pointer', ['_WHEAP_ERROR_SOURCE_TABLE']]], 'WorkQueue' : [ 0x8, ['pointer', ['_WHEAP_WORK_QUEUE']]], } ], '_WHEAP_ERROR_SOURCE' : [ 0x418, { 'ListEntry' : [ 0x0, ['_LIST_ENTRY']], 'FailedAllocations' : [ 0x8, ['unsigned long']], 'PlatformErrorSourceId' : [ 0xc, ['unsigned long']], 'ErrorCount' : [ 0x10, ['long']], 'RecordCount' : [ 0x14, ['unsigned long']], 'RecordLength' : [ 0x18, ['unsigned long']], 'PoolTag' : [ 0x1c, ['unsigned long']], 'Type' : [ 0x20, ['Enumeration', dict(target = 'long', choices = {0: 'WheaErrSrcTypeMCE', 1: 'WheaErrSrcTypeCMC', 2: 'WheaErrSrcTypeCPE', 3: 'WheaErrSrcTypeNMI', 4: 'WheaErrSrcTypePCIe', 5: 'WheaErrSrcTypeGeneric', 6: 'WheaErrSrcTypeINIT', 7: 'WheaErrSrcTypeBOOT', 8: 'WheaErrSrcTypeSCIGeneric', 9: 'WheaErrSrcTypeIPFMCA', 10: 'WheaErrSrcTypeIPFCMC', 11: 'WheaErrSrcTypeIPFCPE', 12: 'WheaErrSrcTypeMax'})]], 'Records' : [ 0x24, ['pointer', ['_WHEAP_ERROR_RECORD_WRAPPER']]], 'Context' : [ 0x28, ['pointer', ['void']]], 'SectionCount' : [ 0x2c, ['unsigned long']], 'SectionLength' : [ 0x30, ['unsigned long']], 'TickCountAtLastError' : [ 0x38, ['_LARGE_INTEGER']], 'AccumulatedErrors' : [ 0x40, ['unsigned long']], 'TotalErrors' : [ 0x44, ['unsigned long']], 'Deferred' : [ 0x48, ['unsigned char']], 'Descriptor' : [ 0x49, ['_WHEA_ERROR_SOURCE_DESCRIPTOR']], } ], '_WHEAP_ERROR_RECORD_WRAPPER' : [ 0xe4, { 'WorkEntry' : [ 0x0, ['_LIST_ENTRY']], 'Length' : [ 0x8, ['unsigned long']], 'ProcessorNumber' : [ 0xc, ['unsigned long']], 'Flags' : [ 0x10, ['_WHEAP_ERROR_RECORD_WRAPPER_FLAGS']], 'InUse' : [ 0x14, ['long']], 'ErrorSource' : [ 0x18, ['pointer', ['_WHEAP_ERROR_SOURCE']]], 'ErrorRecord' : [ 0x1c, ['_WHEA_ERROR_RECORD']], } ], '_KSECONDARY_IDT_ENTRY' : [ 0x1c, { 'SpinLock' : [ 0x0, ['unsigned long']], 'ConnectLock' : [ 0x4, ['_KEVENT']], 'LineMasked' : [ 0x14, ['unsigned char']], 'InterruptList' : [ 0x18, ['pointer', ['_KINTERRUPT']]], } ], '_WNF_STATE_NAME' : [ 0x8, { 'Data' : [ 0x0, ['array', 2, ['unsigned long']]], } ], '_PS_CLIENT_SECURITY_CONTEXT' : [ 0x4, { 'ImpersonationData' : [ 0x0, ['unsigned long']], 'ImpersonationToken' : [ 0x0, ['pointer', ['void']]], 'ImpersonationLevel' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 2, native_type='unsigned long')]], 'EffectiveOnly' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='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']], 'ArmControlSet' : [ 0x0, ['_ARM_DBGKD_CONTROL_SET']], 'ArmCeControlSet' : [ 0x0, ['_ARMCE_DBGKD_CONTROL_SET']], 'PpcControlSet' : [ 0x0, ['_PPC_DBGKD_CONTROL_SET']], } ], '_MI_VERIFIER_POOL_HEADER' : [ 0x4, { 'VerifierPoolEntry' : [ 0x0, ['pointer', ['_VI_POOL_ENTRY']]], } ], '_POP_FX_PLUGIN' : [ 0x60, { 'Link' : [ 0x0, ['_LIST_ENTRY']], 'Version' : [ 0x8, ['unsigned long']], 'Flags' : [ 0x10, ['unsigned long long']], 'WorkOrder' : [ 0x18, ['_POP_FX_WORK_ORDER']], 'WorkQueue' : [ 0x2c, ['_KQUEUE']], 'AcceptDeviceNotification' : [ 0x54, ['pointer', ['void']]], 'AcceptProcessorNotification' : [ 0x58, ['pointer', ['void']]], } ], '_ARM_DBGKD_CONTROL_SET' : [ 0xc, { 'Continue' : [ 0x0, ['unsigned long']], 'CurrentSymbolStart' : [ 0x4, ['unsigned long']], 'CurrentSymbolEnd' : [ 0x8, ['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']], } ], '_HARDWARE_PTE' : [ 0x8, { 'Valid' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long long')]], 'Write' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long long')]], 'Owner' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long long')]], 'WriteThrough' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned long long')]], 'CacheDisable' : [ 0x0, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned long long')]], 'Accessed' : [ 0x0, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned long long')]], 'Dirty' : [ 0x0, ['BitField', dict(start_bit = 6, end_bit = 7, native_type='unsigned long long')]], 'LargePage' : [ 0x0, ['BitField', dict(start_bit = 7, end_bit = 8, native_type='unsigned long long')]], 'Global' : [ 0x0, ['BitField', dict(start_bit = 8, end_bit = 9, native_type='unsigned long long')]], 'CopyOnWrite' : [ 0x0, ['BitField', dict(start_bit = 9, end_bit = 10, native_type='unsigned long long')]], 'Prototype' : [ 0x0, ['BitField', dict(start_bit = 10, end_bit = 11, native_type='unsigned long long')]], 'reserved0' : [ 0x0, ['BitField', dict(start_bit = 11, end_bit = 12, native_type='unsigned long long')]], 'PageFrameNumber' : [ 0x0, ['BitField', dict(start_bit = 12, end_bit = 38, native_type='unsigned long long')]], 'reserved1' : [ 0x0, ['BitField', dict(start_bit = 38, end_bit = 64, native_type='unsigned long long')]], 'LowPart' : [ 0x0, ['unsigned long']], 'HighPart' : [ 0x4, ['unsigned long']], } ], '_ALPC_PORT_ATTRIBUTES' : [ 0x2c, { 'Flags' : [ 0x0, ['unsigned long']], 'SecurityQos' : [ 0x4, ['_SECURITY_QUALITY_OF_SERVICE']], 'MaxMessageLength' : [ 0x10, ['unsigned long']], 'MemoryBandwidth' : [ 0x14, ['unsigned long']], 'MaxPoolUsage' : [ 0x18, ['unsigned long']], 'MaxSectionSize' : [ 0x1c, ['unsigned long']], 'MaxViewSize' : [ 0x20, ['unsigned long']], 'MaxTotalSectionSize' : [ 0x24, ['unsigned long']], 'DupObjectTypes' : [ 0x28, ['unsigned long']], } ], '_KQUEUE' : [ 0x28, { 'Header' : [ 0x0, ['_DISPATCHER_HEADER']], 'EntryListHead' : [ 0x10, ['_LIST_ENTRY']], 'CurrentCount' : [ 0x18, ['unsigned long']], 'MaximumCount' : [ 0x1c, ['unsigned long']], 'ThreadListHead' : [ 0x20, ['_LIST_ENTRY']], } ], '_KSTACK_COUNT' : [ 0x4, { 'Value' : [ 0x0, ['long']], 'State' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 3, native_type='unsigned long')]], 'StackCount' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 32, native_type='unsigned long')]], } ], '_KENTROPY_TIMING_STATE' : [ 0x128, { 'EntropyCount' : [ 0x0, ['unsigned long']], 'Buffer' : [ 0x4, ['array', 64, ['unsigned long']]], 'Dpc' : [ 0x104, ['_KDPC']], 'LastDeliveredBuffer' : [ 0x124, ['unsigned long']], } ], '_DISPATCHER_HEADER' : [ 0x10, { 'Type' : [ 0x0, ['unsigned char']], 'TimerControlFlags' : [ 0x1, ['unsigned char']], 'Absolute' : [ 0x1, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned char')]], 'Wake' : [ 0x1, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned char')]], 'EncodedTolerableDelay' : [ 0x1, ['BitField', dict(start_bit = 2, end_bit = 8, native_type='unsigned char')]], 'Abandoned' : [ 0x1, ['unsigned char']], 'Signalling' : [ 0x1, ['unsigned char']], 'ThreadControlFlags' : [ 0x2, ['unsigned char']], 'CycleProfiling' : [ 0x2, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned char')]], 'CounterProfiling' : [ 0x2, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned char')]], 'GroupScheduling' : [ 0x2, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned char')]], 'AffinitySet' : [ 0x2, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned char')]], 'Reserved' : [ 0x2, ['BitField', dict(start_bit = 4, end_bit = 8, native_type='unsigned char')]], 'Hand' : [ 0x2, ['unsigned char']], 'Size' : [ 0x2, ['unsigned char']], 'TimerMiscFlags' : [ 0x3, ['unsigned char']], 'Index' : [ 0x3, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned char')]], 'Processor' : [ 0x3, ['BitField', dict(start_bit = 1, end_bit = 6, native_type='unsigned char')]], 'Inserted' : [ 0x3, ['BitField', dict(start_bit = 6, end_bit = 7, native_type='unsigned char')]], 'Expired' : [ 0x3, ['BitField', dict(start_bit = 7, end_bit = 8, native_type='unsigned char')]], 'DebugActive' : [ 0x3, ['unsigned char']], 'DpcActive' : [ 0x3, ['unsigned char']], 'Lock' : [ 0x0, ['long']], 'LockNV' : [ 0x0, ['long']], 'SignalState' : [ 0x4, ['long']], 'WaitListHead' : [ 0x8, ['_LIST_ENTRY']], } ], '_VI_POOL_ENTRY' : [ 0x10, { 'PageHeader' : [ 0x0, ['_VI_POOL_PAGE_HEADER']], 'InUse' : [ 0x0, ['_VI_POOL_ENTRY_INUSE']], 'NextFree' : [ 0x0, ['pointer', ['_SINGLE_LIST_ENTRY']]], } ], '_MM_PAGE_ACCESS_INFO' : [ 0x8, { 'Flags' : [ 0x0, ['_MM_PAGE_ACCESS_INFO_FLAGS']], 'FileOffset' : [ 0x0, ['unsigned long long']], 'VirtualAddress' : [ 0x0, ['pointer', ['void']]], 'DontUse0' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 3, native_type='unsigned long')]], 'Spare0' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 32, native_type='unsigned long')]], 'PointerProtoPte' : [ 0x4, ['pointer', ['void']]], } ], '_MI_CONTROL_AREA_WAIT_BLOCK' : [ 0x1c, { 'Next' : [ 0x0, ['pointer', ['_MI_CONTROL_AREA_WAIT_BLOCK']]], 'WaitReason' : [ 0x4, ['unsigned long']], 'WaitResponse' : [ 0x8, ['unsigned long']], 'Gate' : [ 0xc, ['_KGATE']], } ], '_HEAP_COUNTERS' : [ 0x5c, { 'TotalMemoryReserved' : [ 0x0, ['unsigned long']], 'TotalMemoryCommitted' : [ 0x4, ['unsigned long']], 'TotalMemoryLargeUCR' : [ 0x8, ['unsigned long']], 'TotalSizeInVirtualBlocks' : [ 0xc, ['unsigned long']], 'TotalSegments' : [ 0x10, ['unsigned long']], 'TotalUCRs' : [ 0x14, ['unsigned long']], 'CommittOps' : [ 0x18, ['unsigned long']], 'DeCommitOps' : [ 0x1c, ['unsigned long']], 'LockAcquires' : [ 0x20, ['unsigned long']], 'LockCollisions' : [ 0x24, ['unsigned long']], 'CommitRate' : [ 0x28, ['unsigned long']], 'DecommittRate' : [ 0x2c, ['unsigned long']], 'CommitFailures' : [ 0x30, ['unsigned long']], 'InBlockCommitFailures' : [ 0x34, ['unsigned long']], 'PollIntervalCounter' : [ 0x38, ['unsigned long']], 'DecommitsSinceLastCheck' : [ 0x3c, ['unsigned long']], 'HeapPollInterval' : [ 0x40, ['unsigned long']], 'AllocAndFreeOps' : [ 0x44, ['unsigned long']], 'AllocationIndicesActive' : [ 0x48, ['unsigned long']], 'InBlockDeccommits' : [ 0x4c, ['unsigned long']], 'InBlockDeccomitSize' : [ 0x50, ['unsigned long']], 'HighWatermarkSize' : [ 0x54, ['unsigned long']], 'LastPolledSize' : [ 0x58, ['unsigned long']], } ], '_SYSPTES_HEADER' : [ 0x14, { 'ListHead' : [ 0x0, ['_LIST_ENTRY']], 'Count' : [ 0x8, ['unsigned long']], 'NumberOfEntries' : [ 0xc, ['unsigned long']], 'NumberOfEntriesPeak' : [ 0x10, ['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']]], } ], '_PENDING_RELATIONS_LIST_ENTRY' : [ 0x3c, { 'Link' : [ 0x0, ['_LIST_ENTRY']], 'WorkItem' : [ 0x8, ['_WORK_QUEUE_ITEM']], 'DeviceEvent' : [ 0x18, ['pointer', ['_PNP_DEVICE_EVENT_ENTRY']]], 'DeviceObject' : [ 0x1c, ['pointer', ['_DEVICE_OBJECT']]], 'RelationsList' : [ 0x20, ['pointer', ['_RELATION_LIST']]], 'EjectIrp' : [ 0x24, ['pointer', ['_IRP']]], 'Lock' : [ 0x28, ['Enumeration', dict(target = 'long', choices = {0: 'IRPLOCK_CANCELABLE', 1: 'IRPLOCK_CANCEL_STARTED', 2: 'IRPLOCK_CANCEL_COMPLETE', 3: 'IRPLOCK_COMPLETED'})]], 'Problem' : [ 0x2c, ['unsigned long']], 'ProfileChangingEject' : [ 0x30, ['unsigned char']], 'DisplaySafeRemovalDialog' : [ 0x31, ['unsigned char']], 'LightestSleepState' : [ 0x34, ['Enumeration', dict(target = 'long', choices = {0: 'PowerSystemUnspecified', 1: 'PowerSystemWorking', 2: 'PowerSystemSleeping1', 3: 'PowerSystemSleeping2', 4: 'PowerSystemSleeping3', 5: 'PowerSystemHibernate', 6: 'PowerSystemShutdown', 7: 'PowerSystemMaximum'})]], 'DockInterface' : [ 0x38, ['pointer', ['DOCK_INTERFACE']]], } ], '_CELL_DATA' : [ 0x50, { 'u' : [ 0x0, ['_u']], } ], '_INITIAL_PRIVILEGE_SET' : [ 0x2c, { 'PrivilegeCount' : [ 0x0, ['unsigned long']], 'Control' : [ 0x4, ['unsigned long']], 'Privilege' : [ 0x8, ['array', 3, ['_LUID_AND_ATTRIBUTES']]], } ], '_HEAP_TUNING_PARAMETERS' : [ 0x8, { 'CommittThresholdShift' : [ 0x0, ['unsigned long']], 'MaxPreCommittThreshold' : [ 0x4, ['unsigned long']], } ], '_MMWSLE_NONDIRECT_HASH' : [ 0x8, { 'Key' : [ 0x0, ['pointer', ['void']]], 'Index' : [ 0x4, ['unsigned long']], } ], '_POP_FX_WORK_ORDER' : [ 0x14, { 'WorkItem' : [ 0x0, ['_WORK_QUEUE_ITEM']], 'WorkCount' : [ 0x10, ['long']], } ], '_POOL_TRACKER_BIG_PAGES' : [ 0x10, { 'Va' : [ 0x0, ['unsigned long']], 'Key' : [ 0x4, ['unsigned long']], 'PoolType' : [ 0x8, ['unsigned long']], 'NumberOfBytes' : [ 0xc, ['unsigned long']], } ], 'tagSWITCH_CONTEXT_DATA' : [ 0x40, { 'guPlatform' : [ 0x0, ['_GUID']], 'guMinPlatform' : [ 0x10, ['_GUID']], 'ulElementCount' : [ 0x20, ['unsigned long']], 'ulContextMinimum' : [ 0x24, ['unsigned short']], 'ullOsMaxVersionTested' : [ 0x28, ['unsigned long long']], 'guElements' : [ 0x30, ['array', 1, ['_GUID']]], } ], '_WHEAP_ERROR_SOURCE_TABLE' : [ 0x20, { 'Signature' : [ 0x0, ['unsigned long']], 'Count' : [ 0x4, ['long']], 'Items' : [ 0x8, ['_LIST_ENTRY']], 'InsertLock' : [ 0x10, ['_KEVENT']], } ], '_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']], } ], '_ACCESS_REASONS' : [ 0x80, { 'Data' : [ 0x0, ['array', 32, ['unsigned long']]], } ], '_CM_KEY_BODY' : [ 0x2c, { 'Type' : [ 0x0, ['unsigned long']], 'KeyControlBlock' : [ 0x4, ['pointer', ['_CM_KEY_CONTROL_BLOCK']]], 'NotifyBlock' : [ 0x8, ['pointer', ['_CM_NOTIFY_BLOCK']]], 'ProcessID' : [ 0xc, ['pointer', ['void']]], 'KeyBodyList' : [ 0x10, ['_LIST_ENTRY']], 'Flags' : [ 0x18, ['BitField', dict(start_bit = 0, end_bit = 16, native_type='unsigned long')]], 'HandleTags' : [ 0x18, ['BitField', dict(start_bit = 16, end_bit = 32, native_type='unsigned long')]], 'KtmTrans' : [ 0x1c, ['pointer', ['void']]], 'KtmUow' : [ 0x20, ['pointer', ['_GUID']]], 'ContextListHead' : [ 0x24, ['_LIST_ENTRY']], } ], '_KWAIT_BLOCK' : [ 0x18, { 'WaitListEntry' : [ 0x0, ['_LIST_ENTRY']], 'WaitType' : [ 0x8, ['unsigned char']], 'BlockState' : [ 0x9, ['unsigned char']], 'WaitKey' : [ 0xa, ['unsigned short']], 'Thread' : [ 0xc, ['pointer', ['_KTHREAD']]], 'NotificationQueue' : [ 0xc, ['pointer', ['_KQUEUE']]], 'Object' : [ 0x10, ['pointer', ['void']]], 'SparePtr' : [ 0x14, ['pointer', ['void']]], } ], '_MMPTE_PROTOTYPE' : [ 0x8, { 'Valid' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long long')]], 'DemandFillProto' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long long')]], 'HiberVerifyConverted' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long long')]], 'Unused1' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 8, native_type='unsigned long long')]], 'ReadOnly' : [ 0x0, ['BitField', dict(start_bit = 8, end_bit = 9, native_type='unsigned long long')]], 'Combined' : [ 0x0, ['BitField', dict(start_bit = 9, end_bit = 10, native_type='unsigned long long')]], 'Prototype' : [ 0x0, ['BitField', dict(start_bit = 10, end_bit = 11, native_type='unsigned long long')]], 'Protection' : [ 0x0, ['BitField', dict(start_bit = 11, end_bit = 16, native_type='unsigned long long')]], 'Unused' : [ 0x0, ['BitField', dict(start_bit = 16, end_bit = 32, native_type='unsigned long long')]], 'ProtoAddress' : [ 0x0, ['BitField', dict(start_bit = 32, end_bit = 64, native_type='unsigned long long')]], } ], '_WHEA_ERROR_PACKET_FLAGS' : [ 0x4, { 'PreviousError' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]], 'Reserved1' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]], 'HypervisorError' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]], 'Simulated' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned long')]], 'PlatformPfaControl' : [ 0x0, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned long')]], 'PlatformDirectedOffline' : [ 0x0, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned long')]], 'Reserved2' : [ 0x0, ['BitField', dict(start_bit = 6, end_bit = 32, native_type='unsigned long')]], 'AsULONG' : [ 0x0, ['unsigned long']], } ], '_THERMAL_INFORMATION_EX' : [ 0x4c, { 'ThermalStamp' : [ 0x0, ['unsigned long']], 'ThermalConstant1' : [ 0x4, ['unsigned long']], 'ThermalConstant2' : [ 0x8, ['unsigned long']], 'SamplingPeriod' : [ 0xc, ['unsigned long']], 'CurrentTemperature' : [ 0x10, ['unsigned long']], 'PassiveTripPoint' : [ 0x14, ['unsigned long']], 'CriticalTripPoint' : [ 0x18, ['unsigned long']], 'ActiveTripPointCount' : [ 0x1c, ['unsigned char']], 'ActiveTripPoint' : [ 0x20, ['array', 10, ['unsigned long']]], 'S4TransitionTripPoint' : [ 0x48, ['unsigned long']], } ], '__unnamed_1c87' : [ 0x4, { 'FilePointerIndex' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 9, native_type='unsigned long')]], 'HardFault' : [ 0x0, ['BitField', dict(start_bit = 9, end_bit = 10, native_type='unsigned long')]], 'Image' : [ 0x0, ['BitField', dict(start_bit = 10, end_bit = 11, native_type='unsigned long')]], 'Spare0' : [ 0x0, ['BitField', dict(start_bit = 11, end_bit = 12, native_type='unsigned long')]], } ], '__unnamed_1c89' : [ 0x4, { 'FilePointerIndex' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 9, native_type='unsigned long')]], 'HardFault' : [ 0x0, ['BitField', dict(start_bit = 9, end_bit = 10, native_type='unsigned long')]], 'Spare1' : [ 0x0, ['BitField', dict(start_bit = 10, end_bit = 12, native_type='unsigned long')]], } ], '_MM_PAGE_ACCESS_INFO_FLAGS' : [ 0x4, { 'File' : [ 0x0, ['__unnamed_1c87']], 'Private' : [ 0x0, ['__unnamed_1c89']], } ], '_VI_VERIFIER_ISSUE' : [ 0x10, { 'IssueType' : [ 0x0, ['unsigned long']], 'Address' : [ 0x4, ['pointer', ['void']]], 'Parameters' : [ 0x8, ['array', 2, ['unsigned long']]], } ], '_MMSUBSECTION_FLAGS' : [ 0x4, { 'SubsectionAccessed' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned short')]], 'Protection' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 6, native_type='unsigned short')]], 'StartingSector4132' : [ 0x0, ['BitField', dict(start_bit = 6, end_bit = 16, native_type='unsigned short')]], 'SubsectionStatic' : [ 0x2, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned short')]], 'GlobalMemory' : [ 0x2, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned short')]], 'DirtyPages' : [ 0x2, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned short')]], 'Spare' : [ 0x2, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned short')]], 'SectorEndOffset' : [ 0x2, ['BitField', dict(start_bit = 4, end_bit = 16, native_type='unsigned short')]], } ], '_EXCEPTION_POINTERS' : [ 0x8, { 'ExceptionRecord' : [ 0x0, ['pointer', ['_EXCEPTION_RECORD']]], 'ContextRecord' : [ 0x4, ['pointer', ['_CONTEXT']]], } ], '_KMUTANT' : [ 0x20, { 'Header' : [ 0x0, ['_DISPATCHER_HEADER']], 'MutantListEntry' : [ 0x10, ['_LIST_ENTRY']], 'OwnerThread' : [ 0x18, ['pointer', ['_KTHREAD']]], 'Abandoned' : [ 0x1c, ['unsigned char']], 'ApcDisable' : [ 0x1d, ['unsigned char']], } ], '_OBJECT_REF_INFO' : [ 0x1c, { 'ObjectHeader' : [ 0x0, ['pointer', ['_OBJECT_HEADER']]], 'NextRef' : [ 0x4, ['pointer', ['void']]], 'ImageFileName' : [ 0x8, ['array', 16, ['unsigned char']]], 'NextPos' : [ 0x18, ['unsigned short']], 'MaxStacks' : [ 0x1a, ['unsigned short']], 'StackInfo' : [ 0x1c, ['array', 0, ['_OBJECT_REF_STACK_INFO']]], } ], '_HBIN' : [ 0x20, { 'Signature' : [ 0x0, ['unsigned long']], 'FileOffset' : [ 0x4, ['unsigned long']], 'Size' : [ 0x8, ['unsigned long']], 'Reserved1' : [ 0xc, ['array', 2, ['unsigned long']]], 'TimeStamp' : [ 0x14, ['_LARGE_INTEGER']], 'Spare' : [ 0x1c, ['unsigned long']], } ], '_MI_IMAGE_SECURITY_REFERENCE' : [ 0x8, { 'SecurityContext' : [ 0x0, ['_IMAGE_SECURITY_CONTEXT']], 'DynamicRelocations' : [ 0x4, ['pointer', ['void']]], } ], '_AUTHZBASEP_CLAIM_ATTRIBUTES_COLLECTION' : [ 0x130, { 'DeviceGroupsCount' : [ 0x0, ['unsigned long']], 'pDeviceGroups' : [ 0x4, ['pointer', ['_SID_AND_ATTRIBUTES']]], 'RestrictedDeviceGroupsCount' : [ 0x8, ['unsigned long']], 'pRestrictedDeviceGroups' : [ 0xc, ['pointer', ['_SID_AND_ATTRIBUTES']]], 'DeviceGroupsHash' : [ 0x10, ['_SID_AND_ATTRIBUTES_HASH']], 'RestrictedDeviceGroupsHash' : [ 0x98, ['_SID_AND_ATTRIBUTES_HASH']], 'pUserSecurityAttributes' : [ 0x120, ['pointer', ['_AUTHZBASEP_SECURITY_ATTRIBUTES_INFORMATION']]], 'pDeviceSecurityAttributes' : [ 0x124, ['pointer', ['_AUTHZBASEP_SECURITY_ATTRIBUTES_INFORMATION']]], 'pRestrictedUserSecurityAttributes' : [ 0x128, ['pointer', ['_AUTHZBASEP_SECURITY_ATTRIBUTES_INFORMATION']]], 'pRestrictedDeviceSecurityAttributes' : [ 0x12c, ['pointer', ['_AUTHZBASEP_SECURITY_ATTRIBUTES_INFORMATION']]], } ], '_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, ['wchar']]], } ], '_MMPTE_HIGHLOW' : [ 0x8, { 'LowPart' : [ 0x0, ['unsigned long']], 'HighPart' : [ 0x4, ['unsigned long']], } ], '_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']], } ], '_MMWSLE_FREE_ENTRY' : [ 0x4, { 'MustBeZero' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]], 'PreviousFree' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 12, native_type='unsigned long')]], 'NextFree' : [ 0x0, ['BitField', dict(start_bit = 12, 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']]], } ], '_LEARNING_MODE_DATA' : [ 0x8, { 'Settings' : [ 0x0, ['unsigned long']], 'Enabled' : [ 0x4, ['unsigned char']], 'PermissiveModeEnabled' : [ 0x5, ['unsigned char']], } ], '_WHEA_REVISION' : [ 0x2, { 'MinorRevision' : [ 0x0, ['unsigned char']], 'MajorRevision' : [ 0x1, ['unsigned char']], 'AsUSHORT' : [ 0x0, ['unsigned short']], } ], '_EJOB' : [ 0x2b8, { 'Event' : [ 0x0, ['_KEVENT']], 'JobLinks' : [ 0x10, ['_LIST_ENTRY']], 'ProcessListHead' : [ 0x18, ['_LIST_ENTRY']], 'JobLock' : [ 0x20, ['_ERESOURCE']], 'TotalUserTime' : [ 0x58, ['_LARGE_INTEGER']], 'TotalKernelTime' : [ 0x60, ['_LARGE_INTEGER']], 'TotalCycleTime' : [ 0x68, ['_LARGE_INTEGER']], 'ThisPeriodTotalUserTime' : [ 0x70, ['_LARGE_INTEGER']], 'ThisPeriodTotalKernelTime' : [ 0x78, ['_LARGE_INTEGER']], 'TotalContextSwitches' : [ 0x80, ['unsigned long long']], 'TotalPageFaultCount' : [ 0x88, ['unsigned long']], 'TotalProcesses' : [ 0x8c, ['unsigned long']], 'ActiveProcesses' : [ 0x90, ['unsigned long']], 'TotalTerminatedProcesses' : [ 0x94, ['unsigned long']], 'PerProcessUserTimeLimit' : [ 0x98, ['_LARGE_INTEGER']], 'PerJobUserTimeLimit' : [ 0xa0, ['_LARGE_INTEGER']], 'MinimumWorkingSetSize' : [ 0xa8, ['unsigned long']], 'MaximumWorkingSetSize' : [ 0xac, ['unsigned long']], 'LimitFlags' : [ 0xb0, ['unsigned long']], 'ActiveProcessLimit' : [ 0xb4, ['unsigned long']], 'Affinity' : [ 0xb8, ['_KAFFINITY_EX']], 'AccessState' : [ 0xc4, ['pointer', ['_JOB_ACCESS_STATE']]], 'AccessStateQuotaReference' : [ 0xc8, ['pointer', ['void']]], 'UIRestrictionsClass' : [ 0xcc, ['unsigned long']], 'EndOfJobTimeAction' : [ 0xd0, ['unsigned long']], 'CompletionPort' : [ 0xd4, ['pointer', ['void']]], 'CompletionKey' : [ 0xd8, ['pointer', ['void']]], 'CompletionCount' : [ 0xe0, ['unsigned long long']], 'SessionId' : [ 0xe8, ['unsigned long']], 'SchedulingClass' : [ 0xec, ['unsigned long']], 'ReadOperationCount' : [ 0xf0, ['unsigned long long']], 'WriteOperationCount' : [ 0xf8, ['unsigned long long']], 'OtherOperationCount' : [ 0x100, ['unsigned long long']], 'ReadTransferCount' : [ 0x108, ['unsigned long long']], 'WriteTransferCount' : [ 0x110, ['unsigned long long']], 'OtherTransferCount' : [ 0x118, ['unsigned long long']], 'DiskIoInfo' : [ 0x120, ['_PROCESS_DISK_COUNTERS']], 'ProcessMemoryLimit' : [ 0x148, ['unsigned long']], 'JobMemoryLimit' : [ 0x14c, ['unsigned long']], 'PeakProcessMemoryUsed' : [ 0x150, ['unsigned long']], 'PeakJobMemoryUsed' : [ 0x154, ['unsigned long']], 'EffectiveAffinity' : [ 0x158, ['_KAFFINITY_EX']], 'EffectivePerProcessUserTimeLimit' : [ 0x168, ['_LARGE_INTEGER']], 'EffectiveMinimumWorkingSetSize' : [ 0x170, ['unsigned long']], 'EffectiveMaximumWorkingSetSize' : [ 0x174, ['unsigned long']], 'EffectiveProcessMemoryLimit' : [ 0x178, ['unsigned long']], 'EffectiveProcessMemoryLimitJob' : [ 0x17c, ['pointer', ['_EJOB']]], 'EffectivePerProcessUserTimeLimitJob' : [ 0x180, ['pointer', ['_EJOB']]], 'EffectiveLimitFlags' : [ 0x184, ['unsigned long']], 'EffectiveSchedulingClass' : [ 0x188, ['unsigned long']], 'EffectiveFreezeCount' : [ 0x18c, ['unsigned long']], 'EffectiveBackgroundCount' : [ 0x190, ['unsigned long']], 'EffectiveSwapCount' : [ 0x194, ['unsigned long']], 'EffectiveNotificationLimitCount' : [ 0x198, ['unsigned long']], 'EffectivePriorityClass' : [ 0x19c, ['unsigned char']], 'PriorityClass' : [ 0x19d, ['unsigned char']], 'Reserved1' : [ 0x19e, ['array', 2, ['unsigned char']]], 'CompletionFilter' : [ 0x1a0, ['unsigned long']], 'WakeChannel' : [ 0x1a8, ['_WNF_STATE_NAME']], 'WakeInfo' : [ 0x1a8, ['_PS_WAKE_INFORMATION']], 'WakeFilter' : [ 0x1f0, ['_JOBOBJECT_WAKE_FILTER']], 'LowEdgeLatchFilter' : [ 0x1f8, ['unsigned long']], 'OwnedHighEdgeFilters' : [ 0x1fc, ['unsigned long']], 'NotificationLink' : [ 0x200, ['pointer', ['_EJOB']]], 'CurrentJobMemoryUsed' : [ 0x208, ['unsigned long long']], 'NotificationInfo' : [ 0x210, ['pointer', ['_JOB_NOTIFICATION_INFORMATION']]], 'NotificationInfoQuotaReference' : [ 0x214, ['pointer', ['void']]], 'NotificationPacket' : [ 0x218, ['pointer', ['_IO_MINI_COMPLETION_PACKET_USER']]], 'CpuRateControl' : [ 0x21c, ['pointer', ['_JOB_CPU_RATE_CONTROL']]], 'EffectiveSchedulingGroup' : [ 0x220, ['pointer', ['void']]], 'MemoryLimitsLock' : [ 0x224, ['_EX_PUSH_LOCK']], 'SiblingJobLinks' : [ 0x228, ['_LIST_ENTRY']], 'ChildJobListHead' : [ 0x230, ['_LIST_ENTRY']], 'ParentJob' : [ 0x238, ['pointer', ['_EJOB']]], 'RootJob' : [ 0x23c, ['pointer', ['_EJOB']]], 'IteratorListHead' : [ 0x240, ['_LIST_ENTRY']], 'Accounting' : [ 0x248, ['_EPROCESS_VALUES']], 'ShadowActiveProcessCount' : [ 0x298, ['unsigned long']], 'SequenceNumber' : [ 0x29c, ['unsigned long']], 'TimerListLock' : [ 0x2a0, ['unsigned long']], 'TimerListHead' : [ 0x2a4, ['_LIST_ENTRY']], 'JobFlags' : [ 0x2ac, ['unsigned long']], 'CloseDone' : [ 0x2ac, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]], 'MultiGroup' : [ 0x2ac, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]], 'OutstandingNotification' : [ 0x2ac, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]], 'NotificationInProgress' : [ 0x2ac, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned long')]], 'UILimits' : [ 0x2ac, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned long')]], 'CpuRateControlActive' : [ 0x2ac, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned long')]], 'OwnCpuRateControl' : [ 0x2ac, ['BitField', dict(start_bit = 6, end_bit = 7, native_type='unsigned long')]], 'Terminating' : [ 0x2ac, ['BitField', dict(start_bit = 7, end_bit = 8, native_type='unsigned long')]], 'WorkingSetLock' : [ 0x2ac, ['BitField', dict(start_bit = 8, end_bit = 9, native_type='unsigned long')]], 'JobFrozen' : [ 0x2ac, ['BitField', dict(start_bit = 9, end_bit = 10, native_type='unsigned long')]], 'Background' : [ 0x2ac, ['BitField', dict(start_bit = 10, end_bit = 11, native_type='unsigned long')]], 'WakeNotificationAllocated' : [ 0x2ac, ['BitField', dict(start_bit = 11, end_bit = 12, native_type='unsigned long')]], 'WakeNotificationEnabled' : [ 0x2ac, ['BitField', dict(start_bit = 12, end_bit = 13, native_type='unsigned long')]], 'WakeNotificationPending' : [ 0x2ac, ['BitField', dict(start_bit = 13, end_bit = 14, native_type='unsigned long')]], 'LimitNotificationRequired' : [ 0x2ac, ['BitField', dict(start_bit = 14, end_bit = 15, native_type='unsigned long')]], 'ZeroCountNotificationRequired' : [ 0x2ac, ['BitField', dict(start_bit = 15, end_bit = 16, native_type='unsigned long')]], 'CycleTimeNotificationRequired' : [ 0x2ac, ['BitField', dict(start_bit = 16, end_bit = 17, native_type='unsigned long')]], 'CycleTimeNotificationPending' : [ 0x2ac, ['BitField', dict(start_bit = 17, end_bit = 18, native_type='unsigned long')]], 'TimersVirtualized' : [ 0x2ac, ['BitField', dict(start_bit = 18, end_bit = 19, native_type='unsigned long')]], 'JobSwapped' : [ 0x2ac, ['BitField', dict(start_bit = 19, end_bit = 20, native_type='unsigned long')]], 'ViolationDetected' : [ 0x2ac, ['BitField', dict(start_bit = 20, end_bit = 21, native_type='unsigned long')]], 'EmptyJobNotified' : [ 0x2ac, ['BitField', dict(start_bit = 21, end_bit = 22, native_type='unsigned long')]], 'NoSystemCharge' : [ 0x2ac, ['BitField', dict(start_bit = 22, end_bit = 23, native_type='unsigned long')]], 'SpareJobFlags' : [ 0x2ac, ['BitField', dict(start_bit = 23, end_bit = 32, native_type='unsigned long')]], 'EffectiveHighEdgeFilters' : [ 0x2b0, ['unsigned long']], } ], '_PPM_IDLE_STATES' : [ 0xe0, { 'ForceIdle' : [ 0x0, ['unsigned char']], 'EstimateIdleDuration' : [ 0x1, ['unsigned char']], 'ExitLatencyTraceEnabled' : [ 0x2, ['unsigned char']], 'ExitLatencyCountdown' : [ 0x4, ['unsigned long']], 'TargetState' : [ 0x8, ['unsigned long']], 'ActualState' : [ 0xc, ['unsigned long']], 'ActualPlatformState' : [ 0x10, ['unsigned long']], 'OldState' : [ 0x14, ['unsigned long']], 'OverrideIndex' : [ 0x18, ['unsigned long']], 'PlatformIdleCount' : [ 0x1c, ['unsigned long']], 'ProcessorIdleCount' : [ 0x20, ['unsigned long']], 'Type' : [ 0x24, ['unsigned long']], 'ReasonFlags' : [ 0x28, ['unsigned long']], 'InitiateWakeStamp' : [ 0x30, ['long long']], 'PreviousStatus' : [ 0x38, ['long']], 'PrimaryProcessorMask' : [ 0x3c, ['_KAFFINITY_EX']], 'SecondaryProcessorMask' : [ 0x48, ['_KAFFINITY_EX']], 'IdlePrepare' : [ 0x54, ['pointer', ['void']]], 'IdleExecute' : [ 0x58, ['pointer', ['void']]], 'IdleComplete' : [ 0x5c, ['pointer', ['void']]], 'IdleCancel' : [ 0x60, ['pointer', ['void']]], 'IdleIsHalted' : [ 0x64, ['pointer', ['void']]], 'IdleInitiateWake' : [ 0x68, ['pointer', ['void']]], 'PrepareInfo' : [ 0x70, ['_PROCESSOR_IDLE_PREPARE_INFO']], 'State' : [ 0xc0, ['array', 1, ['_PPM_IDLE_STATE']]], } ], '_PEB' : [ 0x250, { 'InheritedAddressSpace' : [ 0x0, ['unsigned char']], 'ReadImageFileExecOptions' : [ 0x1, ['unsigned char']], 'BeingDebugged' : [ 0x2, ['unsigned char']], 'BitField' : [ 0x3, ['unsigned char']], 'ImageUsesLargePages' : [ 0x3, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned char')]], 'IsProtectedProcess' : [ 0x3, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned char')]], 'IsLegacyProcess' : [ 0x3, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned char')]], 'IsImageDynamicallyRelocated' : [ 0x3, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned char')]], 'SkipPatchingUser32Forwarders' : [ 0x3, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned char')]], 'IsPackagedProcess' : [ 0x3, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned char')]], 'IsAppContainer' : [ 0x3, ['BitField', dict(start_bit = 6, end_bit = 7, native_type='unsigned char')]], 'SpareBits' : [ 0x3, ['BitField', dict(start_bit = 7, end_bit = 8, native_type='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']]], 'AtlThunkSListPtr' : [ 0x20, ['pointer', ['void']]], 'IFEOKey' : [ 0x24, ['pointer', ['void']]], 'CrossProcessFlags' : [ 0x28, ['unsigned long']], 'ProcessInJob' : [ 0x28, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]], 'ProcessInitializing' : [ 0x28, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]], 'ProcessUsingVEH' : [ 0x28, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]], 'ProcessUsingVCH' : [ 0x28, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned long')]], 'ProcessUsingFTH' : [ 0x28, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned long')]], 'ReservedBits0' : [ 0x28, ['BitField', dict(start_bit = 5, end_bit = 32, native_type='unsigned long')]], 'KernelCallbackTable' : [ 0x2c, ['pointer', ['void']]], 'UserSharedInfoPtr' : [ 0x2c, ['pointer', ['void']]], 'SystemReserved' : [ 0x30, ['array', 1, ['unsigned long']]], 'AtlThunkSListPtr32' : [ 0x34, ['unsigned long']], 'ApiSetMap' : [ 0x38, ['pointer', ['void']]], 'TlsExpansionCounter' : [ 0x3c, ['unsigned long']], 'TlsBitmap' : [ 0x40, ['pointer', ['void']]], 'TlsBitmapBits' : [ 0x44, ['array', 2, ['unsigned long']]], 'ReadOnlySharedMemoryBase' : [ 0x4c, ['pointer', ['void']]], 'HotpatchInformation' : [ 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', ['_RTL_CRITICAL_SECTION']]], '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']], 'ActiveProcessAffinityMask' : [ 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', ['_ACTIVATION_CONTEXT_DATA']]], 'ProcessAssemblyStorageMap' : [ 0x1fc, ['pointer', ['_ASSEMBLY_STORAGE_MAP']]], 'SystemDefaultActivationContextData' : [ 0x200, ['pointer', ['_ACTIVATION_CONTEXT_DATA']]], 'SystemAssemblyStorageMap' : [ 0x204, ['pointer', ['_ASSEMBLY_STORAGE_MAP']]], 'MinimumStackCommit' : [ 0x208, ['unsigned long']], 'FlsCallback' : [ 0x20c, ['pointer', ['_FLS_CALLBACK_INFO']]], 'FlsListHead' : [ 0x210, ['_LIST_ENTRY']], 'FlsBitmap' : [ 0x218, ['pointer', ['void']]], 'FlsBitmapBits' : [ 0x21c, ['array', 4, ['unsigned long']]], 'FlsHighIndex' : [ 0x22c, ['unsigned long']], 'WerRegistrationData' : [ 0x230, ['pointer', ['void']]], 'WerShipAssertPtr' : [ 0x234, ['pointer', ['void']]], 'pUnused' : [ 0x238, ['pointer', ['void']]], 'pImageHeaderHash' : [ 0x23c, ['pointer', ['void']]], 'TracingFlags' : [ 0x240, ['unsigned long']], 'HeapTracingEnabled' : [ 0x240, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]], 'CritSecTracingEnabled' : [ 0x240, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]], 'LibLoaderTracingEnabled' : [ 0x240, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]], 'SpareTracingBits' : [ 0x240, ['BitField', dict(start_bit = 3, end_bit = 32, native_type='unsigned long')]], 'CsrServerReadOnlySharedMemoryBase' : [ 0x248, ['unsigned long long']], } ], '_HEAP_UCR_DESCRIPTOR' : [ 0x18, { 'ListEntry' : [ 0x0, ['_LIST_ENTRY']], 'SegmentEntry' : [ 0x8, ['_LIST_ENTRY']], 'Address' : [ 0x10, ['pointer', ['void']]], 'Size' : [ 0x14, ['unsigned long']], } ], '_ETW_REALTIME_CONSUMER' : [ 0x4c, { 'Links' : [ 0x0, ['_LIST_ENTRY']], 'ProcessHandle' : [ 0x8, ['pointer', ['void']]], 'ProcessObject' : [ 0xc, ['pointer', ['_EPROCESS']]], 'NextNotDelivered' : [ 0x10, ['pointer', ['void']]], 'RealtimeConnectContext' : [ 0x14, ['pointer', ['void']]], 'DisconnectEvent' : [ 0x18, ['pointer', ['_KEVENT']]], 'DataAvailableEvent' : [ 0x1c, ['pointer', ['_KEVENT']]], 'UserBufferCount' : [ 0x20, ['pointer', ['unsigned long']]], 'UserBufferListHead' : [ 0x24, ['pointer', ['_SINGLE_LIST_ENTRY']]], 'BuffersLost' : [ 0x28, ['unsigned long']], 'EmptyBuffersCount' : [ 0x2c, ['unsigned long']], 'LoggerId' : [ 0x30, ['unsigned short']], 'Flags' : [ 0x32, ['unsigned char']], 'ShutDownRequested' : [ 0x32, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned char')]], 'NewBuffersLost' : [ 0x32, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned char')]], 'Disconnected' : [ 0x32, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned char')]], 'Notified' : [ 0x32, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned char')]], 'ReservedBufferSpaceBitMap' : [ 0x34, ['_RTL_BITMAP']], 'ReservedBufferSpace' : [ 0x3c, ['pointer', ['unsigned char']]], 'ReservedBufferSpaceSize' : [ 0x40, ['unsigned long']], 'UserPagesAllocated' : [ 0x44, ['unsigned long']], 'UserPagesReused' : [ 0x48, ['unsigned long']], } ], '__unnamed_1ce8' : [ 0x4, { 'BaseMid' : [ 0x0, ['unsigned char']], 'Flags1' : [ 0x1, ['unsigned char']], 'Flags2' : [ 0x2, ['unsigned char']], 'BaseHi' : [ 0x3, ['unsigned char']], } ], '__unnamed_1cef' : [ 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_1cf1' : [ 0x4, { 'Bytes' : [ 0x0, ['__unnamed_1ce8']], 'Bits' : [ 0x0, ['__unnamed_1cef']], } ], '_KGDTENTRY' : [ 0x8, { 'LimitLow' : [ 0x0, ['unsigned short']], 'BaseLow' : [ 0x2, ['unsigned short']], 'HighWord' : [ 0x4, ['__unnamed_1cf1']], } ], '_POOL_DESCRIPTOR' : [ 0x1140, { 'PoolType' : [ 0x0, ['Enumeration', dict(target = 'long', choices = {0: 'NonPagedPoolBase', 1: 'PagedPool', 2: 'NonPagedPoolBaseMustSucceed', 3: 'DontUseThisType', 4: 'NonPagedPoolBaseCacheAligned', 5: 'PagedPoolCacheAligned', 6: 'NonPagedPoolBaseCacheAlignedMustS', 7: 'MaxPoolType', 34: 'NonPagedPoolMustSucceedSession', 516: 'NonPagedPoolNxCacheAligned', 35: 'DontUseThisTypeSession', 32: 'NonPagedPoolSession', 512: 'NonPagedPoolNx', 544: 'NonPagedPoolSessionNx', 36: 'NonPagedPoolCacheAlignedSession', 33: 'PagedPoolSession', 38: 'NonPagedPoolCacheAlignedMustSSession', 37: 'PagedPoolCacheAlignedSession'})]], 'PagedLock' : [ 0x4, ['_FAST_MUTEX']], 'NonPagedLock' : [ 0x4, ['unsigned long']], 'RunningAllocs' : [ 0x40, ['long']], 'RunningDeAllocs' : [ 0x44, ['long']], 'TotalBigPages' : [ 0x48, ['long']], 'ThreadsProcessingDeferrals' : [ 0x4c, ['long']], 'TotalBytes' : [ 0x50, ['unsigned long']], 'PoolIndex' : [ 0x80, ['unsigned long']], 'TotalPages' : [ 0xc0, ['long']], 'PendingFrees' : [ 0x100, ['_SINGLE_LIST_ENTRY']], 'PendingFreeDepth' : [ 0x104, ['long']], 'ListHeads' : [ 0x140, ['array', 512, ['_LIST_ENTRY']]], } ], '_BLOB_COUNTERS' : [ 0x8, { 'CreatedObjects' : [ 0x0, ['unsigned long']], 'DeletedObjects' : [ 0x4, ['unsigned long']], } ], '_KGATE' : [ 0x10, { 'Header' : [ 0x0, ['_DISPATCHER_HEADER']], } ], '_WHEA_ERROR_RECORD_HEADER' : [ 0x80, { 'Signature' : [ 0x0, ['unsigned long']], 'Revision' : [ 0x4, ['_WHEA_REVISION']], 'SignatureEnd' : [ 0x6, ['unsigned long']], 'SectionCount' : [ 0xa, ['unsigned short']], 'Severity' : [ 0xc, ['Enumeration', dict(target = 'long', choices = {0: 'WheaErrSevRecoverable', 1: 'WheaErrSevFatal', 2: 'WheaErrSevCorrected', 3: 'WheaErrSevInformational'})]], 'ValidBits' : [ 0x10, ['_WHEA_ERROR_RECORD_HEADER_VALIDBITS']], 'Length' : [ 0x14, ['unsigned long']], 'Timestamp' : [ 0x18, ['_WHEA_TIMESTAMP']], 'PlatformId' : [ 0x20, ['_GUID']], 'PartitionId' : [ 0x30, ['_GUID']], 'CreatorId' : [ 0x40, ['_GUID']], 'NotifyType' : [ 0x50, ['_GUID']], 'RecordId' : [ 0x60, ['unsigned long long']], 'Flags' : [ 0x68, ['_WHEA_ERROR_RECORD_HEADER_FLAGS']], 'PersistenceInfo' : [ 0x6c, ['_WHEA_PERSISTENCE_INFO']], 'Reserved' : [ 0x74, ['array', 12, ['unsigned char']]], } ], '_ALPC_PROCESS_CONTEXT' : [ 0x10, { 'Lock' : [ 0x0, ['_EX_PUSH_LOCK']], 'ViewListHead' : [ 0x4, ['_LIST_ENTRY']], 'PagedPoolQuotaCache' : [ 0xc, ['unsigned long']], } ], '_DRIVER_EXTENSION' : [ 0x24, { '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']]], 'KseCallbacks' : [ 0x1c, ['pointer', ['void']]], 'DvCallbacks' : [ 0x20, ['pointer', ['void']]], } ], '_PRIVILEGE_SET' : [ 0x14, { 'PrivilegeCount' : [ 0x0, ['unsigned long']], 'Control' : [ 0x4, ['unsigned long']], 'Privilege' : [ 0x8, ['array', 1, ['_LUID_AND_ATTRIBUTES']]], } ], '_WHEAP_WORK_QUEUE' : [ 0x44, { 'ListHead' : [ 0x0, ['_LIST_ENTRY']], 'ListLock' : [ 0x8, ['unsigned long']], 'ItemCount' : [ 0xc, ['long']], 'Dpc' : [ 0x10, ['_KDPC']], 'WorkItem' : [ 0x30, ['_WORK_QUEUE_ITEM']], 'WorkRoutine' : [ 0x40, ['pointer', ['void']]], } ], '_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']], } ], '_KINTERRUPT' : [ 0x2a0, { 'Type' : [ 0x0, ['short']], 'Size' : [ 0x2, ['short']], 'InterruptListEntry' : [ 0x4, ['_LIST_ENTRY']], 'ServiceRoutine' : [ 0xc, ['pointer', ['void']]], 'MessageServiceRoutine' : [ 0x10, ['pointer', ['void']]], 'MessageIndex' : [ 0x14, ['unsigned long']], 'ServiceContext' : [ 0x18, ['pointer', ['void']]], 'SpinLock' : [ 0x1c, ['unsigned long']], 'TickCount' : [ 0x20, ['unsigned long']], 'ActualLock' : [ 0x24, ['pointer', ['unsigned long']]], 'DispatchAddress' : [ 0x28, ['pointer', ['void']]], 'Vector' : [ 0x2c, ['unsigned long']], 'Irql' : [ 0x30, ['unsigned char']], 'SynchronizeIrql' : [ 0x31, ['unsigned char']], 'FloatingSave' : [ 0x32, ['unsigned char']], 'Connected' : [ 0x33, ['unsigned char']], 'Number' : [ 0x34, ['unsigned long']], 'ShareVector' : [ 0x38, ['unsigned char']], 'ActiveCount' : [ 0x3a, ['unsigned short']], 'InternalState' : [ 0x3c, ['long']], 'Mode' : [ 0x40, ['Enumeration', dict(target = 'long', choices = {0: 'LevelSensitive', 1: 'Latched'})]], 'Polarity' : [ 0x44, ['Enumeration', dict(target = 'long', choices = {0: 'InterruptPolarityUnknown', 1: 'InterruptRisingEdge', 2: 'InterruptFallingEdge', 3: 'InterruptActiveBoth'})]], 'ServiceCount' : [ 0x48, ['unsigned long']], 'DispatchCount' : [ 0x4c, ['unsigned long']], 'PassiveEvent' : [ 0x50, ['pointer', ['_KEVENT']]], 'DispatchCode' : [ 0x54, ['array', 145, ['unsigned long']]], 'DisconnectData' : [ 0x298, ['pointer', ['void']]], 'ServiceThread' : [ 0x29c, ['pointer', ['_KTHREAD']]], } ], '_AUTHZBASEP_SECURITY_ATTRIBUTES_INFORMATION' : [ 0x18, { 'SecurityAttributeCount' : [ 0x0, ['unsigned long']], 'SecurityAttributesList' : [ 0x4, ['_LIST_ENTRY']], 'WorkingSecurityAttributeCount' : [ 0xc, ['unsigned long']], 'WorkingSecurityAttributesList' : [ 0x10, ['_LIST_ENTRY']], } ], '_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']], } ], '_STRING64' : [ 0x10, { 'Length' : [ 0x0, ['unsigned short']], 'MaximumLength' : [ 0x2, ['unsigned short']], 'Buffer' : [ 0x8, ['unsigned long long']], } ], '_HIVE_LIST_ENTRY' : [ 0x58, { 'FileName' : [ 0x0, ['pointer', ['unsigned short']]], 'BaseName' : [ 0x4, ['pointer', ['unsigned short']]], 'RegRootName' : [ 0x8, ['pointer', ['unsigned short']]], 'CmHive' : [ 0xc, ['pointer', ['_CMHIVE']]], 'HHiveFlags' : [ 0x10, ['unsigned long']], 'CmHiveFlags' : [ 0x14, ['unsigned long']], 'CmKcbCacheSize' : [ 0x18, ['unsigned long']], 'CmHive2' : [ 0x1c, ['pointer', ['_CMHIVE']]], 'HiveMounted' : [ 0x20, ['unsigned char']], 'ThreadFinished' : [ 0x21, ['unsigned char']], 'ThreadStarted' : [ 0x22, ['unsigned char']], 'Allocate' : [ 0x23, ['unsigned char']], 'WinPERequired' : [ 0x24, ['unsigned char']], 'StartEvent' : [ 0x28, ['_KEVENT']], 'FinishedEvent' : [ 0x38, ['_KEVENT']], 'MountLock' : [ 0x48, ['_KEVENT']], } ], '_HMAP_DIRECTORY' : [ 0x1000, { 'Directory' : [ 0x0, ['array', 1024, ['pointer', ['_HMAP_TABLE']]]], } ], '_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']]], } ], '_ALPC_HANDLE_TABLE' : [ 0x10, { 'Handles' : [ 0x0, ['pointer', ['_ALPC_HANDLE_ENTRY']]], 'TotalHandles' : [ 0x4, ['unsigned long']], 'Flags' : [ 0x8, ['unsigned long']], 'Lock' : [ 0xc, ['_EX_PUSH_LOCK']], } ], '__unnamed_1d4c' : [ 0x3a4, { 'XpfMceDescriptor' : [ 0x0, ['_WHEA_XPF_MCE_DESCRIPTOR']], 'XpfCmcDescriptor' : [ 0x0, ['_WHEA_XPF_CMC_DESCRIPTOR']], 'XpfNmiDescriptor' : [ 0x0, ['_WHEA_XPF_NMI_DESCRIPTOR']], 'IpfMcaDescriptor' : [ 0x0, ['_WHEA_IPF_MCA_DESCRIPTOR']], 'IpfCmcDescriptor' : [ 0x0, ['_WHEA_IPF_CMC_DESCRIPTOR']], 'IpfCpeDescriptor' : [ 0x0, ['_WHEA_IPF_CPE_DESCRIPTOR']], 'AerRootportDescriptor' : [ 0x0, ['_WHEA_AER_ROOTPORT_DESCRIPTOR']], 'AerEndpointDescriptor' : [ 0x0, ['_WHEA_AER_ENDPOINT_DESCRIPTOR']], 'AerBridgeDescriptor' : [ 0x0, ['_WHEA_AER_BRIDGE_DESCRIPTOR']], 'GenErrDescriptor' : [ 0x0, ['_WHEA_GENERIC_ERROR_DESCRIPTOR']], } ], '_WHEA_ERROR_SOURCE_DESCRIPTOR' : [ 0x3cc, { 'Length' : [ 0x0, ['unsigned long']], 'Version' : [ 0x4, ['unsigned long']], 'Type' : [ 0x8, ['Enumeration', dict(target = 'long', choices = {0: 'WheaErrSrcTypeMCE', 1: 'WheaErrSrcTypeCMC', 2: 'WheaErrSrcTypeCPE', 3: 'WheaErrSrcTypeNMI', 4: 'WheaErrSrcTypePCIe', 5: 'WheaErrSrcTypeGeneric', 6: 'WheaErrSrcTypeINIT', 7: 'WheaErrSrcTypeBOOT', 8: 'WheaErrSrcTypeSCIGeneric', 9: 'WheaErrSrcTypeIPFMCA', 10: 'WheaErrSrcTypeIPFCMC', 11: 'WheaErrSrcTypeIPFCPE', 12: 'WheaErrSrcTypeMax'})]], 'State' : [ 0xc, ['Enumeration', dict(target = 'long', choices = {1: 'WheaErrSrcStateStopped', 2: 'WheaErrSrcStateStarted'})]], 'MaxRawDataLength' : [ 0x10, ['unsigned long']], 'NumRecordsToPreallocate' : [ 0x14, ['unsigned long']], 'MaxSectionsPerRecord' : [ 0x18, ['unsigned long']], 'ErrorSourceId' : [ 0x1c, ['unsigned long']], 'PlatformErrorSourceId' : [ 0x20, ['unsigned long']], 'Flags' : [ 0x24, ['unsigned long']], 'Info' : [ 0x28, ['__unnamed_1d4c']], } ], '_MMPTE_HARDWARE' : [ 0x8, { 'Valid' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long long')]], 'Dirty1' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long long')]], 'Owner' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long long')]], 'WriteThrough' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned long long')]], 'CacheDisable' : [ 0x0, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned long long')]], 'Accessed' : [ 0x0, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned long long')]], 'Dirty' : [ 0x0, ['BitField', dict(start_bit = 6, end_bit = 7, native_type='unsigned long long')]], 'LargePage' : [ 0x0, ['BitField', dict(start_bit = 7, end_bit = 8, native_type='unsigned long long')]], 'Global' : [ 0x0, ['BitField', dict(start_bit = 8, end_bit = 9, native_type='unsigned long long')]], 'CopyOnWrite' : [ 0x0, ['BitField', dict(start_bit = 9, end_bit = 10, native_type='unsigned long long')]], 'Unused' : [ 0x0, ['BitField', dict(start_bit = 10, end_bit = 11, native_type='unsigned long long')]], 'Write' : [ 0x0, ['BitField', dict(start_bit = 11, end_bit = 12, native_type='unsigned long long')]], 'PageFrameNumber' : [ 0x0, ['BitField', dict(start_bit = 12, end_bit = 38, native_type='unsigned long long')]], 'reserved1' : [ 0x0, ['BitField', dict(start_bit = 38, end_bit = 64, native_type='unsigned long long')]], } ], '_IO_COMPLETION_CONTEXT' : [ 0x8, { 'Port' : [ 0x0, ['pointer', ['void']]], 'Key' : [ 0x4, ['pointer', ['void']]], } ], '_EX_WORK_QUEUE' : [ 0x38, { 'WorkerQueue' : [ 0x0, ['_KQUEUE']], 'WorkItemsProcessed' : [ 0x28, ['unsigned long']], 'WorkItemsProcessedLastPass' : [ 0x2c, ['unsigned long']], 'ThreadCount' : [ 0x30, ['long']], 'TryFailed' : [ 0x34, ['unsigned char']], } ], '_IOV_FORCED_PENDING_TRACE' : [ 0x100, { 'Irp' : [ 0x0, ['pointer', ['_IRP']]], 'Thread' : [ 0x4, ['pointer', ['_ETHREAD']]], 'StackTrace' : [ 0x8, ['array', 62, ['pointer', ['void']]]], } ], '_IOP_IRP_EXTENSION_STATUS' : [ 0xc, { 'Flags' : [ 0x0, ['unsigned long']], 'ActivityId' : [ 0x4, ['unsigned long']], 'IoTracking' : [ 0x8, ['unsigned long']], } ], '_DBGKD_SET_CONTEXT' : [ 0x4, { 'ContextFlags' : [ 0x0, ['unsigned long']], } ], '_VI_POOL_ENTRY_INUSE' : [ 0x10, { 'VirtualAddress' : [ 0x0, ['pointer', ['void']]], 'CallingAddress' : [ 0x4, ['pointer', ['void']]], 'NumberOfBytes' : [ 0x8, ['unsigned long']], 'Tag' : [ 0xc, ['unsigned long']], } ], '_INTERFACE' : [ 0x10, { 'Size' : [ 0x0, ['unsigned short']], 'Version' : [ 0x2, ['unsigned short']], 'Context' : [ 0x4, ['pointer', ['void']]], 'InterfaceReference' : [ 0x8, ['pointer', ['void']]], 'InterfaceDereference' : [ 0xc, ['pointer', ['void']]], } ], '_ACL' : [ 0x8, { 'AclRevision' : [ 0x0, ['unsigned char']], 'Sbz1' : [ 0x1, ['unsigned char']], 'AclSize' : [ 0x2, ['unsigned short']], 'AceCount' : [ 0x4, ['unsigned short']], 'Sbz2' : [ 0x6, ['unsigned short']], } ], '_LAZY_WRITER' : [ 0x50, { 'ScanDpc' : [ 0x0, ['_KDPC']], 'ScanTimer' : [ 0x20, ['_KTIMER']], 'ScanActive' : [ 0x48, ['unsigned char']], 'OtherWork' : [ 0x49, ['unsigned char']], 'PendingTeardownScan' : [ 0x4a, ['unsigned char']], 'PendingPeriodicScan' : [ 0x4b, ['unsigned char']], 'PendingLowMemoryScan' : [ 0x4c, ['unsigned char']], 'PendingPowerScan' : [ 0x4d, ['unsigned char']], 'PendingCoalescingFlushScan' : [ 0x4e, ['unsigned char']], } ], '_PI_BUS_EXTENSION' : [ 0x44, { 'Flags' : [ 0x0, ['unsigned long']], 'NumberCSNs' : [ 0x4, ['unsigned char']], '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'})]], } ], '_DEVICE_DESCRIPTION' : [ 0x40, { 'Version' : [ 0x0, ['unsigned long']], 'Master' : [ 0x4, ['unsigned char']], 'ScatterGather' : [ 0x5, ['unsigned char']], 'DemandMode' : [ 0x6, ['unsigned char']], 'AutoInitialize' : [ 0x7, ['unsigned char']], 'Dma32BitAddresses' : [ 0x8, ['unsigned char']], 'IgnoreCount' : [ 0x9, ['unsigned char']], 'Reserved1' : [ 0xa, ['unsigned char']], 'Dma64BitAddresses' : [ 0xb, ['unsigned char']], 'BusNumber' : [ 0xc, ['unsigned long']], 'DmaChannel' : [ 0x10, ['unsigned long']], 'InterfaceType' : [ 0x14, ['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: 'Vmcs', 17: 'ACPIBus', 18: 'MaximumInterfaceType', -1: 'InterfaceTypeUndefined'})]], 'DmaWidth' : [ 0x18, ['Enumeration', dict(target = 'long', choices = {0: 'Width8Bits', 1: 'Width16Bits', 2: 'Width32Bits', 3: 'Width64Bits', 4: 'WidthNoWrap', 5: 'MaximumDmaWidth'})]], 'DmaSpeed' : [ 0x1c, ['Enumeration', dict(target = 'long', choices = {0: 'Compatible', 1: 'TypeA', 2: 'TypeB', 3: 'TypeC', 4: 'TypeF', 5: 'MaximumDmaSpeed'})]], 'MaximumLength' : [ 0x20, ['unsigned long']], 'DmaPort' : [ 0x24, ['unsigned long']], 'DmaAddressWidth' : [ 0x28, ['unsigned long']], 'DmaControllerInstance' : [ 0x2c, ['unsigned long']], 'DmaRequestLine' : [ 0x30, ['unsigned long']], 'DeviceAddress' : [ 0x38, ['_LARGE_INTEGER']], } ], '_SID_AND_ATTRIBUTES' : [ 0x8, { 'Sid' : [ 0x0, ['pointer', ['void']]], 'Attributes' : [ 0x4, ['unsigned long']], } ], '_SID_IDENTIFIER_AUTHORITY' : [ 0x6, { 'Value' : [ 0x0, ['array', 6, ['unsigned char']]], } ], '_PROCESS_DISK_COUNTERS' : [ 0x28, { 'BytesRead' : [ 0x0, ['unsigned long long']], 'BytesWritten' : [ 0x8, ['unsigned long long']], 'ReadOperationCount' : [ 0x10, ['unsigned long long']], 'WriteOperationCount' : [ 0x18, ['unsigned long long']], 'FlushOperationCount' : [ 0x20, ['unsigned long long']], } ], '_IO_WORKITEM' : [ 0x30, { 'WorkItem' : [ 0x0, ['_WORK_QUEUE_ITEM']], 'Routine' : [ 0x10, ['pointer', ['void']]], 'IoObject' : [ 0x14, ['pointer', ['void']]], 'Context' : [ 0x18, ['pointer', ['void']]], 'Type' : [ 0x1c, ['unsigned long']], 'ActivityId' : [ 0x20, ['_GUID']], } ], '_MMWSLE_HASH' : [ 0x4, { 'Index' : [ 0x0, ['unsigned long']], } ], '_JOBOBJECT_WAKE_FILTER' : [ 0x8, { 'HighEdgeFilter' : [ 0x0, ['unsigned long']], 'LowEdgeFilter' : [ 0x4, ['unsigned long']], } ], '_STRING32' : [ 0x8, { 'Length' : [ 0x0, ['unsigned short']], 'MaximumLength' : [ 0x2, ['unsigned short']], 'Buffer' : [ 0x4, ['unsigned long']], } ], '_DBGKD_FILL_MEMORY' : [ 0x10, { 'Address' : [ 0x0, ['unsigned long long']], 'Length' : [ 0x8, ['unsigned long']], 'Flags' : [ 0xc, ['unsigned short']], 'PatternLength' : [ 0xe, ['unsigned short']], } ], '_MI_ACTIVE_WSLE' : [ 0x8, { 'Flink' : [ 0x0, ['unsigned long']], 'Blink' : [ 0x4, ['unsigned long']], } ], '_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']], } ], '_HEAP_PSEUDO_TAG_ENTRY' : [ 0xc, { 'Allocs' : [ 0x0, ['unsigned long']], 'Frees' : [ 0x4, ['unsigned long']], 'Size' : [ 0x8, ['unsigned long']], } ], '_CALL_HASH_ENTRY' : [ 0x14, { 'ListEntry' : [ 0x0, ['_LIST_ENTRY']], 'CallersAddress' : [ 0x8, ['pointer', ['void']]], 'CallersCaller' : [ 0xc, ['pointer', ['void']]], 'CallCount' : [ 0x10, ['unsigned long']], } ], '_VF_TRACKER_STAMP' : [ 0x8, { 'Thread' : [ 0x0, ['pointer', ['void']]], 'Flags' : [ 0x4, ['BitField', dict(start_bit = 0, end_bit = 8, native_type='unsigned char')]], 'OldIrql' : [ 0x5, ['BitField', dict(start_bit = 0, end_bit = 8, native_type='unsigned char')]], 'NewIrql' : [ 0x6, ['BitField', dict(start_bit = 0, end_bit = 8, native_type='unsigned char')]], 'Processor' : [ 0x7, ['BitField', dict(start_bit = 0, end_bit = 8, native_type='unsigned char')]], } ], '_VI_TRACK_IRQL' : [ 0x20, { 'Thread' : [ 0x0, ['pointer', ['void']]], 'OldIrql' : [ 0x4, ['unsigned char']], 'NewIrql' : [ 0x5, ['unsigned char']], 'Processor' : [ 0x6, ['unsigned short']], 'TickCount' : [ 0x8, ['unsigned long']], 'StackTrace' : [ 0xc, ['array', 5, ['pointer', ['void']]]], } ], '_SESSION_LOWBOX_MAP' : [ 0x20, { 'ListEntry' : [ 0x0, ['_LIST_ENTRY']], 'SessionId' : [ 0x8, ['unsigned long']], 'LowboxMap' : [ 0xc, ['_SEP_LOWBOX_NUMBER_MAPPING']], } ], '_PROCESSOR_PROFILE_CONTROL_AREA' : [ 0x60, { 'PebsDsSaveArea' : [ 0x0, ['_PEBS_DS_SAVE_AREA']], } ], '_PEB_LDR_DATA' : [ 0x30, { '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']]], 'ShutdownInProgress' : [ 0x28, ['unsigned char']], 'ShutdownThreadId' : [ 0x2c, ['pointer', ['void']]], } ], '_PNP_DEVICE_EVENT_ENTRY' : [ 0x74, { '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']]], 'RefCount' : [ 0x20, ['unsigned long']], 'Lock' : [ 0x24, ['unsigned long']], 'Cancel' : [ 0x28, ['unsigned char']], 'Parent' : [ 0x2c, ['pointer', ['_PNP_DEVICE_EVENT_ENTRY']]], 'Data' : [ 0x30, ['_PLUGPLAY_EVENT_BLOCK']], } ], '_HEAP_STOP_ON_TAG' : [ 0x4, { 'HeapAndTagIndex' : [ 0x0, ['unsigned long']], 'TagIndex' : [ 0x0, ['unsigned short']], 'HeapIndex' : [ 0x2, ['unsigned short']], } ], '_PS_WAKE_INFORMATION' : [ 0x48, { 'NotificationChannel' : [ 0x0, ['unsigned long long']], 'WakeCounters' : [ 0x8, ['array', 8, ['unsigned long long']]], } ], '_DBGKD_GET_CONTEXT' : [ 0x4, { 'Unused' : [ 0x0, ['unsigned long']], } ], '_TEB_ACTIVE_FRAME_CONTEXT' : [ 0x8, { 'Flags' : [ 0x0, ['unsigned long']], 'FrameName' : [ 0x4, ['pointer', ['unsigned char']]], } ], '_XSTATE_CONFIGURATION' : [ 0x218, { 'EnabledFeatures' : [ 0x0, ['unsigned long long']], 'EnabledVolatileFeatures' : [ 0x8, ['unsigned long long']], 'Size' : [ 0x10, ['unsigned long']], 'OptimizedSave' : [ 0x14, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]], 'Features' : [ 0x18, ['array', 64, ['_XSTATE_FEATURE']]], } ], '_CM_KEY_CONTROL_BLOCK' : [ 0xa0, { 'RefCount' : [ 0x0, ['unsigned long']], 'ExtFlags' : [ 0x4, ['BitField', dict(start_bit = 0, end_bit = 16, native_type='unsigned long')]], 'PrivateAlloc' : [ 0x4, ['BitField', dict(start_bit = 16, end_bit = 17, native_type='unsigned long')]], 'Delete' : [ 0x4, ['BitField', dict(start_bit = 17, end_bit = 18, native_type='unsigned long')]], 'HiveUnloaded' : [ 0x4, ['BitField', dict(start_bit = 18, end_bit = 19, native_type='unsigned long')]], 'Decommissioned' : [ 0x4, ['BitField', dict(start_bit = 19, end_bit = 20, native_type='unsigned long')]], 'LockTablePresent' : [ 0x4, ['BitField', dict(start_bit = 20, end_bit = 21, native_type='unsigned long')]], 'TotalLevels' : [ 0x4, ['BitField', dict(start_bit = 21, end_bit = 31, native_type='unsigned long')]], 'DelayedDeref' : [ 0x8, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]], 'DelayedClose' : [ 0x8, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]], 'Parking' : [ 0x8, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]], 'KeyHash' : [ 0xc, ['_CM_KEY_HASH']], 'ConvKey' : [ 0xc, ['unsigned long']], 'NextHash' : [ 0x10, ['pointer', ['_CM_KEY_HASH']]], 'KeyHive' : [ 0x14, ['pointer', ['_HHIVE']]], 'KeyCell' : [ 0x18, ['unsigned long']], 'KcbPushlock' : [ 0x1c, ['_EX_PUSH_LOCK']], 'Owner' : [ 0x20, ['pointer', ['_KTHREAD']]], 'SharedCount' : [ 0x20, ['long']], 'SlotHint' : [ 0x24, ['unsigned long']], 'ParentKcb' : [ 0x28, ['pointer', ['_CM_KEY_CONTROL_BLOCK']]], 'NameBlock' : [ 0x2c, ['pointer', ['_CM_NAME_CONTROL_BLOCK']]], 'CachedSecurity' : [ 0x30, ['pointer', ['_CM_KEY_SECURITY_CACHE']]], 'ValueCache' : [ 0x34, ['_CACHED_CHILD_LIST']], 'IndexHint' : [ 0x3c, ['pointer', ['_CM_INDEX_HINT_BLOCK']]], 'HashKey' : [ 0x3c, ['unsigned long']], 'SubKeyCount' : [ 0x3c, ['unsigned long']], 'KeyBodyListHead' : [ 0x40, ['_LIST_ENTRY']], 'FreeListEntry' : [ 0x40, ['_LIST_ENTRY']], 'KeyBodyArray' : [ 0x48, ['array', 4, ['pointer', ['_CM_KEY_BODY']]]], 'KcbLastWriteTime' : [ 0x58, ['_LARGE_INTEGER']], 'KcbMaxNameLen' : [ 0x60, ['unsigned short']], 'KcbMaxValueNameLen' : [ 0x62, ['unsigned short']], 'KcbMaxValueDataLen' : [ 0x64, ['unsigned long']], 'KcbUserFlags' : [ 0x68, ['BitField', dict(start_bit = 0, end_bit = 4, native_type='unsigned long')]], 'KcbVirtControlFlags' : [ 0x68, ['BitField', dict(start_bit = 4, end_bit = 8, native_type='unsigned long')]], 'KcbDebug' : [ 0x68, ['BitField', dict(start_bit = 8, end_bit = 16, native_type='unsigned long')]], 'Flags' : [ 0x68, ['BitField', dict(start_bit = 16, end_bit = 32, native_type='unsigned long')]], 'KCBUoWListHead' : [ 0x6c, ['_LIST_ENTRY']], 'DelayQueueEntry' : [ 0x74, ['_LIST_ENTRY']], 'Stolen' : [ 0x74, ['pointer', ['unsigned char']]], 'TransKCBOwner' : [ 0x7c, ['pointer', ['_CM_TRANS']]], 'KCBLock' : [ 0x80, ['_CM_INTENT_LOCK']], 'KeyLock' : [ 0x88, ['_CM_INTENT_LOCK']], 'TransValueCache' : [ 0x90, ['_CHILD_LIST']], 'TransValueListOwner' : [ 0x98, ['pointer', ['_CM_TRANS']]], 'FullKCBName' : [ 0x9c, ['pointer', ['_UNICODE_STRING']]], } ], '_MMPTE_SOFTWARE' : [ 0x8, { 'Valid' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long long')]], 'PageFileLow' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 5, native_type='unsigned long long')]], 'Protection' : [ 0x0, ['BitField', dict(start_bit = 5, end_bit = 10, native_type='unsigned long long')]], 'Prototype' : [ 0x0, ['BitField', dict(start_bit = 10, end_bit = 11, native_type='unsigned long long')]], 'Transition' : [ 0x0, ['BitField', dict(start_bit = 11, end_bit = 12, native_type='unsigned long long')]], 'InStore' : [ 0x0, ['BitField', dict(start_bit = 12, end_bit = 13, native_type='unsigned long long')]], 'PageFileReserved' : [ 0x0, ['BitField', dict(start_bit = 13, end_bit = 14, native_type='unsigned long long')]], 'PageFileAllocated' : [ 0x0, ['BitField', dict(start_bit = 14, end_bit = 15, native_type='unsigned long long')]], 'DbgCrc' : [ 0x0, ['BitField', dict(start_bit = 15, end_bit = 32, native_type='unsigned long long')]], 'PageFileHigh' : [ 0x0, ['BitField', dict(start_bit = 32, end_bit = 64, native_type='unsigned long long')]], } ], '__unnamed_1ddd' : [ 0x8, { 'IoStatus' : [ 0x0, ['_IO_STATUS_BLOCK']], } ], '_MMMOD_WRITER_MDL_ENTRY' : [ 0x68, { 'Links' : [ 0x0, ['_LIST_ENTRY']], 'u' : [ 0x8, ['__unnamed_1ddd']], 'Irp' : [ 0x10, ['pointer', ['_IRP']]], 'u1' : [ 0x14, ['_MODWRITER_FLAGS']], 'ByteCount' : [ 0x18, ['unsigned long']], 'PagingFile' : [ 0x1c, ['pointer', ['_MMPAGING_FILE']]], 'File' : [ 0x20, ['pointer', ['_FILE_OBJECT']]], 'ControlArea' : [ 0x24, ['pointer', ['_CONTROL_AREA']]], 'FileResource' : [ 0x28, ['pointer', ['_ERESOURCE']]], 'WriteOffset' : [ 0x30, ['_LARGE_INTEGER']], 'IssueTime' : [ 0x38, ['_LARGE_INTEGER']], 'PointerMdl' : [ 0x40, ['pointer', ['_MDL']]], 'Mdl' : [ 0x44, ['_MDL']], 'Page' : [ 0x60, ['array', 1, ['unsigned long']]], } ], '_NT_TIB32' : [ 0x1c, { 'ExceptionList' : [ 0x0, ['unsigned long']], 'StackBase' : [ 0x4, ['unsigned long']], 'StackLimit' : [ 0x8, ['unsigned long']], 'SubSystemTib' : [ 0xc, ['unsigned long']], 'FiberData' : [ 0x10, ['unsigned long']], 'Version' : [ 0x10, ['unsigned long']], 'ArbitraryUserPointer' : [ 0x14, ['unsigned long']], 'Self' : [ 0x18, ['unsigned long']], } ], '_CM_RESOURCE_LIST' : [ 0x24, { 'Count' : [ 0x0, ['unsigned long']], 'List' : [ 0x4, ['array', 1, ['_CM_FULL_RESOURCE_DESCRIPTOR']]], } ], '_POOL_TRACKER_TABLE' : [ 0x1c, { 'Key' : [ 0x0, ['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']], } ], '_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: 'Vmcs', 17: 'ACPIBus', 18: 'MaximumInterfaceType', -1: 'InterfaceTypeUndefined'})]], 'BusNumber' : [ 0x4, ['unsigned long']], 'PartialResourceList' : [ 0x8, ['_CM_PARTIAL_RESOURCE_LIST']], } ], '_WHEA_ERROR_RECORD_SECTION_DESCRIPTOR_FLAGS' : [ 0x4, { 'Primary' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]], 'ContainmentWarning' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]], 'Reset' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]], 'ThresholdExceeded' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned long')]], 'ResourceNotAvailable' : [ 0x0, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned long')]], 'LatentError' : [ 0x0, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned long')]], 'Reserved' : [ 0x0, ['BitField', dict(start_bit = 6, end_bit = 32, native_type='unsigned long')]], 'AsULONG' : [ 0x0, ['unsigned long']], } ], '_WMI_BUFFER_HEADER' : [ 0x48, { 'BufferSize' : [ 0x0, ['unsigned long']], 'SavedOffset' : [ 0x4, ['unsigned long']], 'CurrentOffset' : [ 0x8, ['unsigned long']], 'ReferenceCount' : [ 0xc, ['long']], 'TimeStamp' : [ 0x10, ['_LARGE_INTEGER']], 'SequenceNumber' : [ 0x18, ['long long']], 'ClockType' : [ 0x20, ['BitField', dict(start_bit = 0, end_bit = 3, native_type='unsigned long long')]], 'Frequency' : [ 0x20, ['BitField', dict(start_bit = 3, end_bit = 64, native_type='unsigned long long')]], 'SlistEntry' : [ 0x20, ['_SINGLE_LIST_ENTRY']], 'NextBuffer' : [ 0x20, ['pointer', ['_WMI_BUFFER_HEADER']]], 'ClientContext' : [ 0x28, ['_ETW_BUFFER_CONTEXT']], 'State' : [ 0x2c, ['Enumeration', dict(target = 'long', choices = {0: 'EtwBufferStateFree', 1: 'EtwBufferStateGeneralLogging', 2: 'EtwBufferStateCSwitch', 3: 'EtwBufferStateFlush', 4: 'EtwBufferStateMaximum'})]], 'Offset' : [ 0x30, ['unsigned long']], 'BufferFlag' : [ 0x34, ['unsigned short']], 'BufferType' : [ 0x36, ['unsigned short']], 'Padding1' : [ 0x38, ['array', 4, ['unsigned long']]], 'ReferenceTime' : [ 0x38, ['_ETW_REF_CLOCK']], 'GlobalEntry' : [ 0x38, ['_LIST_ENTRY']], 'Pointer0' : [ 0x38, ['pointer', ['void']]], 'Pointer1' : [ 0x3c, ['pointer', ['void']]], } ], '_NT_TIB64' : [ 0x38, { 'ExceptionList' : [ 0x0, ['unsigned long long']], 'StackBase' : [ 0x8, ['unsigned long long']], 'StackLimit' : [ 0x10, ['unsigned long long']], 'SubSystemTib' : [ 0x18, ['unsigned long long']], 'FiberData' : [ 0x20, ['unsigned long long']], 'Version' : [ 0x20, ['unsigned long']], 'ArbitraryUserPointer' : [ 0x28, ['unsigned long long']], 'Self' : [ 0x30, ['unsigned long long']], } ], '_POWER_SEQUENCE' : [ 0xc, { 'SequenceD1' : [ 0x0, ['unsigned long']], 'SequenceD2' : [ 0x4, ['unsigned long']], 'SequenceD3' : [ 0x8, ['unsigned long']], } ], '_EPROCESS_VALUES' : [ 0x50, { 'KernelTime' : [ 0x0, ['unsigned long long']], 'UserTime' : [ 0x8, ['unsigned long long']], 'CycleTime' : [ 0x10, ['unsigned long long']], 'ContextSwitches' : [ 0x18, ['unsigned long long']], 'ReadOperationCount' : [ 0x20, ['long long']], 'WriteOperationCount' : [ 0x28, ['long long']], 'OtherOperationCount' : [ 0x30, ['long long']], 'ReadTransferCount' : [ 0x38, ['long long']], 'WriteTransferCount' : [ 0x40, ['long long']], 'OtherTransferCount' : [ 0x48, ['long long']], } ], '_PROCESSOR_POWER_STATE' : [ 0x180, { 'IdleStates' : [ 0x0, ['pointer', ['_PPM_IDLE_STATES']]], 'IdleAccounting' : [ 0x4, ['pointer', ['_PROC_IDLE_ACCOUNTING']]], 'PlatformIdleAccounting' : [ 0x8, ['pointer', ['_PLATFORM_IDLE_ACCOUNTING']]], 'IdleTimeLast' : [ 0x10, ['unsigned long long']], 'IdleTimeTotal' : [ 0x18, ['unsigned long long']], 'IdleTimeEntry' : [ 0x20, ['unsigned long long']], 'Reserved' : [ 0x28, ['unsigned long long']], 'IdlePolicy' : [ 0x30, ['_PROC_IDLE_POLICY']], 'Synchronization' : [ 0x38, ['_PPM_IDLE_SYNCHRONIZATION_STATE']], 'PerfFeedback' : [ 0x40, ['_PROC_FEEDBACK']], 'Hypervisor' : [ 0xa8, ['Enumeration', dict(target = 'long', choices = {0: 'ProcHypervisorNone', 1: 'ProcHypervisorPresent', 2: 'ProcHypervisorPower'})]], 'LastSysTime' : [ 0xac, ['unsigned long']], 'WmiDispatchPtr' : [ 0xb0, ['unsigned long']], 'WmiInterfaceEnabled' : [ 0xb4, ['long']], 'FFHThrottleStateInfo' : [ 0xb8, ['_PPM_FFH_THROTTLE_STATE_INFO']], 'PerfActionDpc' : [ 0xd8, ['_KDPC']], 'PerfActionMask' : [ 0xf8, ['long']], 'HvIdleCheck' : [ 0x100, ['_PROC_IDLE_SNAP']], 'PerfCheck' : [ 0x110, ['_PROC_PERF_SNAP']], 'Domain' : [ 0x150, ['pointer', ['_PROC_PERF_DOMAIN']]], 'PerfConstraint' : [ 0x154, ['pointer', ['_PROC_PERF_CONSTRAINT']]], 'Concurrency' : [ 0x158, ['pointer', ['_PPM_CONCURRENCY_ACCOUNTING']]], 'Load' : [ 0x15c, ['pointer', ['_PROC_PERF_LOAD']]], 'PerfHistory' : [ 0x160, ['pointer', ['_PROC_PERF_HISTORY']]], 'GuaranteedPerformancePercent' : [ 0x164, ['unsigned char']], 'HvTargetState' : [ 0x165, ['unsigned char']], 'Parked' : [ 0x166, ['unsigned char']], 'OverUtilized' : [ 0x167, ['unsigned char']], 'LatestPerformancePercent' : [ 0x168, ['unsigned long']], 'AveragePerformancePercent' : [ 0x16c, ['unsigned long']], 'LatestAffinitizedPercent' : [ 0x170, ['unsigned long']], 'Utility' : [ 0x174, ['unsigned long']], 'AffinitizedUtility' : [ 0x178, ['unsigned long']], } ], '_OBJECT_REF_STACK_INFO' : [ 0xc, { 'Sequence' : [ 0x0, ['unsigned long']], 'Index' : [ 0x4, ['unsigned short']], 'NumTraces' : [ 0x6, ['unsigned short']], 'Tag' : [ 0x8, ['unsigned long']], } ], '_PPC_DBGKD_CONTROL_SET' : [ 0xc, { 'Continue' : [ 0x0, ['unsigned long']], 'CurrentSymbolStart' : [ 0x4, ['unsigned long']], 'CurrentSymbolEnd' : [ 0x8, ['unsigned long']], } ], '_MMPFNENTRY' : [ 0x2, { 'PageLocation' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 3, native_type='unsigned char')]], 'WriteInProgress' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned char')]], 'Modified' : [ 0x0, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned char')]], 'ReadInProgress' : [ 0x0, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned char')]], 'CacheAttribute' : [ 0x0, ['BitField', dict(start_bit = 6, end_bit = 8, native_type='unsigned char')]], 'Priority' : [ 0x1, ['BitField', dict(start_bit = 0, end_bit = 3, native_type='unsigned char')]], 'OnProtectedStandby' : [ 0x1, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned char')]], 'InPageError' : [ 0x1, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned char')]], 'Spare' : [ 0x1, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned char')]], 'RemovalRequested' : [ 0x1, ['BitField', dict(start_bit = 6, end_bit = 7, native_type='unsigned char')]], 'ParityError' : [ 0x1, ['BitField', dict(start_bit = 7, end_bit = 8, native_type='unsigned char')]], } ], '_SEGMENT_OBJECT' : [ 0x28, { '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']]], 'MmSectionFlags' : [ 0x20, ['pointer', ['_MMSECTION_FLAGS']]], 'MmSubSectionFlags' : [ 0x24, ['pointer', ['_MMSUBSECTION_FLAGS']]], } ], '_PCW_CALLBACK_INFORMATION' : [ 0x20, { 'AddCounter' : [ 0x0, ['_PCW_COUNTER_INFORMATION']], 'RemoveCounter' : [ 0x0, ['_PCW_COUNTER_INFORMATION']], 'EnumerateInstances' : [ 0x0, ['_PCW_MASK_INFORMATION']], 'CollectData' : [ 0x0, ['_PCW_MASK_INFORMATION']], } ], '_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']]], } ], '_TOKEN_SOURCE' : [ 0x10, { 'SourceName' : [ 0x0, ['array', 8, ['unsigned char']]], 'SourceIdentifier' : [ 0x8, ['_LUID']], } ], '_CMHIVE' : [ 0x908, { 'Hive' : [ 0x0, ['_HHIVE']], 'FileHandles' : [ 0x3a0, ['array', 6, ['pointer', ['void']]]], 'NotifyList' : [ 0x3b8, ['_LIST_ENTRY']], 'HiveList' : [ 0x3c0, ['_LIST_ENTRY']], 'PreloadedHiveList' : [ 0x3c8, ['_LIST_ENTRY']], 'HiveRundown' : [ 0x3d0, ['_EX_RUNDOWN_REF']], 'ParseCacheEntries' : [ 0x3d4, ['_LIST_ENTRY']], 'KcbCacheTable' : [ 0x3dc, ['pointer', ['_CM_KEY_HASH_TABLE_ENTRY']]], 'KcbCacheTableSize' : [ 0x3e0, ['unsigned long']], 'DeletedKcbTable' : [ 0x3e4, ['pointer', ['_CM_KEY_HASH_TABLE_ENTRY']]], 'DeletedKcbTableSize' : [ 0x3e8, ['unsigned long']], 'Identity' : [ 0x3ec, ['unsigned long']], 'HiveLock' : [ 0x3f0, ['pointer', ['_FAST_MUTEX']]], 'WriterLock' : [ 0x3f4, ['pointer', ['_FAST_MUTEX']]], 'FlusherLock' : [ 0x3f8, ['pointer', ['_ERESOURCE']]], 'FlushDirtyVector' : [ 0x3fc, ['_RTL_BITMAP']], 'FlushOffsetArray' : [ 0x404, ['pointer', ['CMP_OFFSET_ARRAY']]], 'FlushOffsetArrayCount' : [ 0x408, ['unsigned long']], 'FlushBaseBlock' : [ 0x40c, ['pointer', ['_HBASE_BLOCK']]], 'FlushHiveTruncated' : [ 0x410, ['unsigned long']], 'SecurityLock' : [ 0x414, ['_EX_PUSH_LOCK']], 'UseCount' : [ 0x418, ['unsigned long']], 'LastShrinkHiveSize' : [ 0x41c, ['unsigned long']], 'ActualFileSize' : [ 0x420, ['_LARGE_INTEGER']], 'LogFileSizes' : [ 0x428, ['array', 2, ['_LARGE_INTEGER']]], 'FileFullPath' : [ 0x438, ['_UNICODE_STRING']], 'FileUserName' : [ 0x440, ['_UNICODE_STRING']], 'HiveRootPath' : [ 0x448, ['_UNICODE_STRING']], 'SecurityCount' : [ 0x450, ['unsigned long']], 'SecurityCacheSize' : [ 0x454, ['unsigned long']], 'SecurityHitHint' : [ 0x458, ['long']], 'SecurityCache' : [ 0x45c, ['pointer', ['_CM_KEY_SECURITY_CACHE_ENTRY']]], 'SecurityHash' : [ 0x460, ['array', 64, ['_LIST_ENTRY']]], 'UnloadEventCount' : [ 0x660, ['unsigned long']], 'UnloadEventArray' : [ 0x664, ['pointer', ['pointer', ['_KEVENT']]]], 'RootKcb' : [ 0x668, ['pointer', ['_CM_KEY_CONTROL_BLOCK']]], 'Frozen' : [ 0x66c, ['unsigned char']], 'UnloadWorkItem' : [ 0x670, ['pointer', ['_CM_WORKITEM']]], 'UnloadWorkItemHolder' : [ 0x674, ['_CM_WORKITEM']], 'GrowOnlyMode' : [ 0x688, ['unsigned char']], 'GrowOffset' : [ 0x68c, ['unsigned long']], 'KcbConvertListHead' : [ 0x690, ['_LIST_ENTRY']], 'KnodeConvertListHead' : [ 0x698, ['_LIST_ENTRY']], 'CellRemapArray' : [ 0x6a0, ['pointer', ['_CM_CELL_REMAP_BLOCK']]], 'Flags' : [ 0x6a4, ['unsigned long']], 'TrustClassEntry' : [ 0x6a8, ['_LIST_ENTRY']], 'DirtyTime' : [ 0x6b0, ['unsigned long long']], 'CmRm' : [ 0x6b8, ['pointer', ['_CM_RM']]], 'CmRmInitFailPoint' : [ 0x6bc, ['unsigned long']], 'CmRmInitFailStatus' : [ 0x6c0, ['long']], 'CreatorOwner' : [ 0x6c4, ['pointer', ['_KTHREAD']]], 'RundownThread' : [ 0x6c8, ['pointer', ['_KTHREAD']]], 'ActiveFlushThread' : [ 0x6cc, ['pointer', ['_ETHREAD']]], 'FlushBoostLock' : [ 0x6d0, ['_EX_PUSH_LOCK']], 'LastWriteTime' : [ 0x6d8, ['_LARGE_INTEGER']], 'ReferenceCount' : [ 0x6e0, ['long']], 'FlushFlags' : [ 0x6e4, ['unsigned long']], 'FlushActive' : [ 0x6e4, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]], 'DiskFileBad' : [ 0x6e4, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]], 'FlushBoosted' : [ 0x6e4, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]], 'PrimaryWritePending' : [ 0x6e4, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned long')]], 'PriorPurgeComplete' : [ 0x6e4, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned long')]], 'FlushWaitList' : [ 0x6e8, ['pointer', ['_HIVE_WAIT_PACKET']]], 'UnloadHistoryIndex' : [ 0x6ec, ['long']], 'UnloadHistory' : [ 0x6f0, ['array', 128, ['unsigned long']]], 'BootStart' : [ 0x8f0, ['unsigned long']], 'UnaccessedStart' : [ 0x8f4, ['unsigned long']], 'UnaccessedEnd' : [ 0x8f8, ['unsigned long']], 'LoadedKeyCount' : [ 0x8fc, ['unsigned long']], 'HandleClosePending' : [ 0x900, ['unsigned long']], 'HandleClosePendingEvent' : [ 0x904, ['_EX_PUSH_LOCK']], } ], '_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']], } ], '_DIRTY_PAGE_THRESHOLDS' : [ 0x10, { 'DirtyPageThreshold' : [ 0x0, ['unsigned long']], 'DirtyPageThresholdTop' : [ 0x4, ['unsigned long']], 'DirtyPageThresholdBottom' : [ 0x8, ['unsigned long']], 'DirtyPageTarget' : [ 0xc, ['unsigned long']], } ], 'DOCK_INTERFACE' : [ 0x18, { 'Size' : [ 0x0, ['unsigned short']], 'Version' : [ 0x2, ['unsigned short']], 'Context' : [ 0x4, ['pointer', ['void']]], 'InterfaceReference' : [ 0x8, ['pointer', ['void']]], 'InterfaceDereference' : [ 0xc, ['pointer', ['void']]], 'ProfileDepartureSetMode' : [ 0x10, ['pointer', ['void']]], 'ProfileDepartureUpdate' : [ 0x14, ['pointer', ['void']]], } ], 'CMP_OFFSET_ARRAY' : [ 0xc, { 'FileOffset' : [ 0x0, ['unsigned long']], 'DataBuffer' : [ 0x4, ['pointer', ['void']]], 'DataLength' : [ 0x8, ['unsigned long']], } ], '_MMSUPPORT_FLAGS' : [ 0x4, { 'WorkingSetType' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 3, native_type='unsigned char')]], 'ForceCredits' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 6, native_type='unsigned char')]], 'MaximumWorkingSetHard' : [ 0x0, ['BitField', dict(start_bit = 6, end_bit = 7, native_type='unsigned char')]], 'MinimumWorkingSetHard' : [ 0x0, ['BitField', dict(start_bit = 7, end_bit = 8, native_type='unsigned char')]], 'SessionMaster' : [ 0x1, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned char')]], 'TrimmerState' : [ 0x1, ['BitField', dict(start_bit = 1, end_bit = 3, native_type='unsigned char')]], 'Reserved' : [ 0x1, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned char')]], 'PageStealers' : [ 0x1, ['BitField', dict(start_bit = 4, end_bit = 8, native_type='unsigned char')]], 'MemoryPriority' : [ 0x2, ['BitField', dict(start_bit = 0, end_bit = 8, native_type='unsigned char')]], 'WsleDeleted' : [ 0x3, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned char')]], 'VmExiting' : [ 0x3, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned char')]], 'ExpansionFailed' : [ 0x3, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned char')]], 'Available' : [ 0x3, ['BitField', dict(start_bit = 3, end_bit = 8, native_type='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']]], } ], '_ALPC_COMPLETION_PACKET_LOOKASIDE' : [ 0x30, { 'Lock' : [ 0x0, ['unsigned long']], 'Size' : [ 0x4, ['unsigned long']], 'ActiveCount' : [ 0x8, ['unsigned long']], 'PendingNullCount' : [ 0xc, ['unsigned long']], 'PendingCheckCompletionListCount' : [ 0x10, ['unsigned long']], 'PendingDelete' : [ 0x14, ['unsigned long']], 'FreeListHead' : [ 0x18, ['_SINGLE_LIST_ENTRY']], 'CompletionPort' : [ 0x1c, ['pointer', ['void']]], 'CompletionKey' : [ 0x20, ['pointer', ['void']]], 'Entry' : [ 0x24, ['array', 1, ['_ALPC_COMPLETION_PACKET_LOOKASIDE_ENTRY']]], } ], '_KSYSTEM_TIME' : [ 0xc, { 'LowPart' : [ 0x0, ['unsigned long']], 'High1Time' : [ 0x4, ['long']], 'High2Time' : [ 0x8, ['long']], } ], '_TERMINATION_PORT' : [ 0x8, { 'Next' : [ 0x0, ['pointer', ['_TERMINATION_PORT']]], 'Port' : [ 0x4, ['pointer', ['void']]], } ], '_MEMORY_ALLOCATION_DESCRIPTOR' : [ 0x14, { 'ListEntry' : [ 0x0, ['_LIST_ENTRY']], 'MemoryType' : [ 0x8, ['Enumeration', dict(target = 'long', choices = {0: 'LoaderExceptionBlock', 1: 'LoaderSystemBlock', 2: 'LoaderFree', 3: 'LoaderBad', 4: 'LoaderLoadedProgram', 5: 'LoaderFirmwareTemporary', 6: 'LoaderFirmwarePermanent', 7: 'LoaderOsloaderHeap', 8: 'LoaderOsloaderStack', 9: 'LoaderSystemCode', 10: 'LoaderHalCode', 11: 'LoaderBootDriver', 12: 'LoaderConsoleInDriver', 13: 'LoaderConsoleOutDriver', 14: 'LoaderStartupDpcStack', 15: 'LoaderStartupKernelStack', 16: 'LoaderStartupPanicStack', 17: 'LoaderStartupPcrPage', 18: 'LoaderStartupPdrPage', 19: 'LoaderRegistryData', 20: 'LoaderMemoryData', 21: 'LoaderNlsData', 22: 'LoaderSpecialMemory', 23: 'LoaderBBTMemory', 24: 'LoaderReserve', 25: 'LoaderXIPRom', 26: 'LoaderHALCachedMemory', 27: 'LoaderLargePageFiller', 28: 'LoaderErrorLogMemory', 29: 'LoaderMaximum'})]], 'BasePage' : [ 0xc, ['unsigned long']], 'PageCount' : [ 0x10, ['unsigned long']], } ], '_CM_INTENT_LOCK' : [ 0x8, { 'OwnerCount' : [ 0x0, ['unsigned long']], 'OwnerTable' : [ 0x4, ['pointer', ['pointer', ['_CM_KCB_UOW']]]], } ], '_PROC_IDLE_ACCOUNTING' : [ 0x390, { 'StateCount' : [ 0x0, ['unsigned long']], 'TotalTransitions' : [ 0x4, ['unsigned long']], 'ResetCount' : [ 0x8, ['unsigned long']], 'AbortCount' : [ 0xc, ['unsigned long']], 'StartTime' : [ 0x10, ['unsigned long long']], 'PriorIdleTime' : [ 0x18, ['unsigned long long']], 'TimeUnit' : [ 0x20, ['Enumeration', dict(target = 'long', choices = {0: 'PpmIdleBucketTimeInQpc', 1: 'PpmIdleBucketTimeIn100ns', 2: 'PpmIdleBucketTimeMaximum'})]], 'State' : [ 0x28, ['array', 1, ['_PROC_IDLE_STATE_ACCOUNTING']]], } ], '_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']]], } ], '_SEP_LOWBOX_NUMBER_MAPPING' : [ 0x14, { 'Lock' : [ 0x0, ['_EX_PUSH_LOCK']], 'Bitmap' : [ 0x4, ['_RTL_BITMAP']], 'HashTable' : [ 0xc, ['pointer', ['_RTL_DYNAMIC_HASH_TABLE']]], 'Active' : [ 0x10, ['unsigned char']], } ], '_MAPPED_FILE_SEGMENT' : [ 0x20, { 'ControlArea' : [ 0x0, ['pointer', ['_CONTROL_AREA']]], 'TotalNumberOfPtes' : [ 0x4, ['unsigned long']], 'SegmentFlags' : [ 0x8, ['_SEGMENT_FLAGS']], 'NumberOfCommittedPages' : [ 0xc, ['unsigned long']], 'SizeOfSegment' : [ 0x10, ['unsigned long long']], 'ExtendInfo' : [ 0x18, ['pointer', ['_MMEXTEND_INFO']]], 'BasedAddress' : [ 0x18, ['pointer', ['void']]], 'SegmentLock' : [ 0x1c, ['_EX_PUSH_LOCK']], } ], '_GDI_TEB_BATCH' : [ 0x4e0, { 'Offset' : [ 0x0, ['unsigned long']], 'HDC' : [ 0x4, ['unsigned long']], 'Buffer' : [ 0x8, ['array', 310, ['unsigned long']]], } ], '_MM_DRIVER_VERIFIER_DATA' : [ 0x84, { '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']], 'OptionChanges' : [ 0x68, ['unsigned long']], 'VerifyMode' : [ 0x6c, ['unsigned long']], 'PreviousBucketName' : [ 0x70, ['_UNICODE_STRING']], 'ActivityCounter' : [ 0x78, ['unsigned long']], 'PreviousActivityCounter' : [ 0x7c, ['unsigned long']], 'WorkerTrimRequests' : [ 0x80, ['unsigned long']], } ], '_VI_FAULT_TRACE' : [ 0x24, { 'Thread' : [ 0x0, ['pointer', ['_ETHREAD']]], 'StackTrace' : [ 0x4, ['array', 8, ['pointer', ['void']]]], } ], '_GENERIC_MAPPING' : [ 0x10, { 'GenericRead' : [ 0x0, ['unsigned long']], 'GenericWrite' : [ 0x4, ['unsigned long']], 'GenericExecute' : [ 0x8, ['unsigned long']], 'GenericAll' : [ 0xc, ['unsigned long']], } ], '_OBJECT_HANDLE_COUNT_DATABASE' : [ 0xc, { 'CountEntries' : [ 0x0, ['unsigned long']], 'HandleCountEntries' : [ 0x4, ['array', 1, ['_OBJECT_HANDLE_COUNT_ENTRY']]], } ], '_OWNER_ENTRY' : [ 0x8, { 'OwnerThread' : [ 0x0, ['unsigned long']], 'IoPriorityBoosted' : [ 0x4, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]], 'OwnerReferenced' : [ 0x4, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]], 'OwnerCount' : [ 0x4, ['BitField', dict(start_bit = 2, end_bit = 32, native_type='unsigned long')]], 'TableSize' : [ 0x4, ['unsigned long']], } ], '_ETIMER' : [ 0xb8, { 'KeTimer' : [ 0x0, ['_KTIMER']], 'Lock' : [ 0x28, ['unsigned long']], 'TimerApc' : [ 0x2c, ['_KAPC']], 'TimerDpc' : [ 0x5c, ['_KDPC']], 'ActiveTimerListEntry' : [ 0x7c, ['_LIST_ENTRY']], 'Period' : [ 0x84, ['unsigned long']], 'TimerFlags' : [ 0x88, ['unsigned char']], 'ApcAssociated' : [ 0x88, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned char')]], 'FlushDpcs' : [ 0x88, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned char')]], 'Paused' : [ 0x88, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned char')]], 'Spare1' : [ 0x88, ['BitField', dict(start_bit = 3, end_bit = 8, native_type='unsigned char')]], 'DueTimeType' : [ 0x89, ['unsigned char']], 'Spare2' : [ 0x8a, ['unsigned short']], 'WakeReason' : [ 0x8c, ['pointer', ['_DIAGNOSTIC_CONTEXT']]], 'WakeTimerListEntry' : [ 0x90, ['_LIST_ENTRY']], 'VirtualizedTimerCookie' : [ 0x98, ['pointer', ['void']]], 'VirtualizedTimerLinks' : [ 0x9c, ['_LIST_ENTRY']], 'DueTime' : [ 0xa8, ['unsigned long long']], 'CoalescingWindow' : [ 0xb0, ['unsigned long']], } ], '_PROC_PERF_SNAP' : [ 0x40, { 'Time' : [ 0x0, ['unsigned long long']], 'LastTime' : [ 0x8, ['unsigned long long']], 'Active' : [ 0x10, ['unsigned long long']], 'LastActive' : [ 0x18, ['unsigned long long']], 'FrequencyScaledActive' : [ 0x20, ['unsigned long long']], 'PerformanceScaledActive' : [ 0x28, ['unsigned long long']], 'CyclesActive' : [ 0x30, ['unsigned long long']], 'CyclesAffinitized' : [ 0x38, ['unsigned long long']], } ], '_OBJECT_DIRECTORY_ENTRY' : [ 0xc, { 'ChainLink' : [ 0x0, ['pointer', ['_OBJECT_DIRECTORY_ENTRY']]], 'Object' : [ 0x4, ['pointer', ['void']]], 'HashValue' : [ 0x8, ['unsigned long']], } ], '_POOL_BLOCK_HEAD' : [ 0x10, { 'Header' : [ 0x0, ['_POOL_HEADER']], 'List' : [ 0x8, ['_LIST_ENTRY']], } ], '_EXHANDLE' : [ 0x4, { 'TagBits' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 2, native_type='unsigned long')]], 'Index' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 32, native_type='unsigned long')]], 'GenericHandleOverlay' : [ 0x0, ['pointer', ['void']]], 'Value' : [ 0x0, ['unsigned long']], } ], '_XSTATE_FEATURE' : [ 0x8, { 'Offset' : [ 0x0, ['unsigned long']], 'Size' : [ 0x4, ['unsigned long']], } ], '_DBGKD_CONTEXT_EX' : [ 0xc, { 'Offset' : [ 0x0, ['unsigned long']], 'ByteCount' : [ 0x4, ['unsigned long']], 'BytesCopied' : [ 0x8, ['unsigned long']], } ], '_ARBITER_INSTANCE' : [ 0x5ec, { 'Signature' : [ 0x0, ['unsigned long']], 'MutexEvent' : [ 0x4, ['pointer', ['_KEVENT']]], 'Name' : [ 0x8, ['pointer', ['unsigned short']]], 'OrderingName' : [ 0xc, ['pointer', ['unsigned short']]], 'ResourceType' : [ 0x10, ['long']], 'Allocation' : [ 0x14, ['pointer', ['_RTL_RANGE_LIST']]], 'PossibleAllocation' : [ 0x18, ['pointer', ['_RTL_RANGE_LIST']]], 'OrderingList' : [ 0x1c, ['_ARBITER_ORDERING_LIST']], 'ReservedList' : [ 0x24, ['_ARBITER_ORDERING_LIST']], 'ReferenceCount' : [ 0x2c, ['long']], 'Interface' : [ 0x30, ['pointer', ['_ARBITER_INTERFACE']]], 'AllocationStackMaxSize' : [ 0x34, ['unsigned long']], 'AllocationStack' : [ 0x38, ['pointer', ['_ARBITER_ALLOCATION_STATE']]], 'UnpackRequirement' : [ 0x3c, ['pointer', ['void']]], 'PackResource' : [ 0x40, ['pointer', ['void']]], 'UnpackResource' : [ 0x44, ['pointer', ['void']]], 'ScoreRequirement' : [ 0x48, ['pointer', ['void']]], 'TestAllocation' : [ 0x4c, ['pointer', ['void']]], 'RetestAllocation' : [ 0x50, ['pointer', ['void']]], 'CommitAllocation' : [ 0x54, ['pointer', ['void']]], 'RollbackAllocation' : [ 0x58, ['pointer', ['void']]], 'BootAllocation' : [ 0x5c, ['pointer', ['void']]], 'QueryArbitrate' : [ 0x60, ['pointer', ['void']]], 'QueryConflict' : [ 0x64, ['pointer', ['void']]], 'AddReserved' : [ 0x68, ['pointer', ['void']]], 'StartArbiter' : [ 0x6c, ['pointer', ['void']]], 'PreprocessEntry' : [ 0x70, ['pointer', ['void']]], 'AllocateEntry' : [ 0x74, ['pointer', ['void']]], 'GetNextAllocationRange' : [ 0x78, ['pointer', ['void']]], 'FindSuitableRange' : [ 0x7c, ['pointer', ['void']]], 'AddAllocation' : [ 0x80, ['pointer', ['void']]], 'BacktrackAllocation' : [ 0x84, ['pointer', ['void']]], 'OverrideConflict' : [ 0x88, ['pointer', ['void']]], 'InitializeRangeList' : [ 0x8c, ['pointer', ['void']]], 'TransactionInProgress' : [ 0x90, ['unsigned char']], 'TransactionEvent' : [ 0x94, ['pointer', ['_KEVENT']]], 'Extension' : [ 0x98, ['pointer', ['void']]], 'BusDeviceObject' : [ 0x9c, ['pointer', ['_DEVICE_OBJECT']]], 'ConflictCallbackContext' : [ 0xa0, ['pointer', ['void']]], 'ConflictCallback' : [ 0xa4, ['pointer', ['void']]], 'PdoDescriptionString' : [ 0xa8, ['array', 336, ['wchar']]], 'PdoSymbolicNameString' : [ 0x348, ['array', 672, ['unsigned char']]], 'PdoAddressString' : [ 0x5e8, ['array', 1, ['wchar']]], } ], '_KDEVICE_QUEUE_ENTRY' : [ 0x10, { 'DeviceListEntry' : [ 0x0, ['_LIST_ENTRY']], 'SortKey' : [ 0x8, ['unsigned long']], 'Inserted' : [ 0xc, ['unsigned char']], } ], '__unnamed_1eff' : [ 0x4, { 'UserData' : [ 0x0, ['unsigned long']], 'Next' : [ 0x0, ['unsigned long']], } ], '__unnamed_1f01' : [ 0x4, { 'u' : [ 0x0, ['__unnamed_1eff']], } ], '__unnamed_1f03' : [ 0x4, { 'NewCell' : [ 0x0, ['__unnamed_1f01']], } ], '_HCELL' : [ 0x8, { 'Size' : [ 0x0, ['long']], 'u' : [ 0x4, ['__unnamed_1f03']], } ], '_WHEA_GENERIC_ERROR_DESCRIPTOR' : [ 0x34, { 'Type' : [ 0x0, ['unsigned short']], 'Reserved' : [ 0x2, ['unsigned char']], 'Enabled' : [ 0x3, ['unsigned char']], 'ErrStatusBlockLength' : [ 0x4, ['unsigned long']], 'RelatedErrorSourceId' : [ 0x8, ['unsigned long']], 'ErrStatusAddressSpaceID' : [ 0xc, ['unsigned char']], 'ErrStatusAddressBitWidth' : [ 0xd, ['unsigned char']], 'ErrStatusAddressBitOffset' : [ 0xe, ['unsigned char']], 'ErrStatusAddressAccessSize' : [ 0xf, ['unsigned char']], 'ErrStatusAddress' : [ 0x10, ['_LARGE_INTEGER']], 'Notify' : [ 0x18, ['_WHEA_NOTIFICATION_DESCRIPTOR']], } ], '_HMAP_TABLE' : [ 0x1800, { 'Table' : [ 0x0, ['array', 512, ['_HMAP_ENTRY']]], } ], '_SEP_LOWBOX_HANDLES_ENTRY' : [ 0x1c, { 'HashEntry' : [ 0x0, ['_RTL_DYNAMIC_HASH_TABLE_ENTRY']], 'ReferenceCount' : [ 0xc, ['unsigned long']], 'PackageSid' : [ 0x10, ['pointer', ['void']]], 'HandleCount' : [ 0x14, ['unsigned long']], 'Handles' : [ 0x18, ['pointer', ['pointer', ['void']]]], } ], '_PROC_PERF_CONSTRAINT' : [ 0x50, { 'Prcb' : [ 0x0, ['pointer', ['_KPRCB']]], 'PerfContext' : [ 0x4, ['unsigned long']], 'PlatformCap' : [ 0x8, ['unsigned long']], 'ThermalCap' : [ 0xc, ['unsigned long']], 'LimitReasons' : [ 0x10, ['unsigned long']], 'PlatformCapStartTime' : [ 0x18, ['unsigned long long']], 'TargetPercent' : [ 0x20, ['unsigned long']], 'DesiredPercent' : [ 0x24, ['unsigned long']], 'SelectedPercent' : [ 0x28, ['unsigned long']], 'SelectedFrequency' : [ 0x2c, ['unsigned long']], 'PreviousFrequency' : [ 0x30, ['unsigned long']], 'PreviousPercent' : [ 0x34, ['unsigned long']], 'LatestFrequencyPercent' : [ 0x38, ['unsigned long']], 'SelectedState' : [ 0x40, ['unsigned long long']], 'Force' : [ 0x48, ['unsigned char']], } ], '__unnamed_1f16' : [ 0x10, { 'CallerCompletion' : [ 0x0, ['pointer', ['void']]], 'CallerContext' : [ 0x4, ['pointer', ['void']]], 'CallerDevice' : [ 0x8, ['pointer', ['_DEVICE_OBJECT']]], 'SystemWake' : [ 0xc, ['unsigned char']], } ], '__unnamed_1f19' : [ 0x8, { 'NotifyDevice' : [ 0x0, ['pointer', ['_PO_DEVICE_NOTIFY']]], 'FxDeviceActivated' : [ 0x4, ['unsigned char']], } ], '_POP_IRP_DATA' : [ 0x90, { 'Link' : [ 0x0, ['_LIST_ENTRY']], 'Irp' : [ 0x8, ['pointer', ['_IRP']]], 'Pdo' : [ 0xc, ['pointer', ['_DEVICE_OBJECT']]], 'TargetDevice' : [ 0x10, ['pointer', ['_DEVICE_OBJECT']]], 'CurrentDevice' : [ 0x14, ['pointer', ['_DEVICE_OBJECT']]], 'WatchdogStart' : [ 0x18, ['unsigned long long']], 'WatchdogTimer' : [ 0x20, ['_KTIMER']], 'WatchdogDpc' : [ 0x48, ['_KDPC']], 'MinorFunction' : [ 0x68, ['unsigned char']], 'PowerStateType' : [ 0x6c, ['Enumeration', dict(target = 'long', choices = {0: 'SystemPowerState', 1: 'DevicePowerState'})]], 'PowerState' : [ 0x70, ['_POWER_STATE']], 'WatchdogEnabled' : [ 0x74, ['unsigned char']], 'FxDevice' : [ 0x78, ['pointer', ['_POP_FX_DEVICE']]], 'SystemTransition' : [ 0x7c, ['unsigned char']], 'NotifyPEP' : [ 0x7d, ['unsigned char']], 'Device' : [ 0x80, ['__unnamed_1f16']], 'System' : [ 0x80, ['__unnamed_1f19']], } ], '_IMAGE_DATA_DIRECTORY' : [ 0x8, { 'VirtualAddress' : [ 0x0, ['unsigned long']], 'Size' : [ 0x4, ['unsigned long']], } ], '_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')]], 'Reserved1' : [ 0x4, ['BitField', dict(start_bit = 18, end_bit = 19, native_type='unsigned long')]], 'Reserved' : [ 0x4, ['BitField', dict(start_bit = 19, 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']], } ], '_MI_USER_VA_INFO' : [ 0xcfc, { 'NumberOfCommittedPageTables' : [ 0x0, ['unsigned long']], 'PhysicalMappingCount' : [ 0x4, ['unsigned long']], 'VadBitMapHint' : [ 0x8, ['unsigned long']], 'LastAllocationSizeHint' : [ 0xc, ['unsigned long']], 'LastAllocationSize' : [ 0x10, ['unsigned long']], 'LowestBottomUpVadBit' : [ 0x14, ['unsigned long']], 'VadBitMapSize' : [ 0x18, ['unsigned long']], 'MaximumLastVadBit' : [ 0x1c, ['unsigned long']], 'VadsBeingDeleted' : [ 0x20, ['long']], 'LastVadDeletionEvent' : [ 0x24, ['pointer', ['_KEVENT']]], 'VadBitBuffer' : [ 0x28, ['pointer', ['unsigned long']]], 'LowestBottomUpAllocationAddress' : [ 0x2c, ['pointer', ['void']]], 'HighestTopDownAllocationAddress' : [ 0x30, ['pointer', ['void']]], 'FreeTebHint' : [ 0x34, ['pointer', ['void']]], 'PrivateFixupVadCount' : [ 0x38, ['unsigned long']], 'UsedPageTableEntries' : [ 0x3c, ['array', 1536, ['unsigned short']]], 'CommittedPageTables' : [ 0xc3c, ['array', 48, ['unsigned long']]], } ], '_PROC_FEEDBACK' : [ 0x68, { 'Lock' : [ 0x0, ['unsigned long']], 'CyclesLast' : [ 0x8, ['unsigned long long']], 'CyclesActive' : [ 0x10, ['unsigned long long']], 'Counters' : [ 0x18, ['array', 2, ['pointer', ['_PROC_FEEDBACK_COUNTER']]]], 'LastUpdateTime' : [ 0x20, ['unsigned long long']], 'UnscaledTime' : [ 0x28, ['unsigned long long']], 'UnaccountedTime' : [ 0x30, ['long long']], 'ScaledTime' : [ 0x38, ['array', 2, ['unsigned long long']]], 'UnaccountedKernelTime' : [ 0x48, ['unsigned long long']], 'PerformanceScaledKernelTime' : [ 0x50, ['unsigned long long']], 'UserTimeLast' : [ 0x58, ['unsigned long']], 'KernelTimeLast' : [ 0x5c, ['unsigned long']], 'KernelTimesIndex' : [ 0x60, ['unsigned char']], } ], '__unnamed_1f2c' : [ 0x18, { 'Length' : [ 0x0, ['unsigned long']], 'Alignment' : [ 0x4, ['unsigned long']], 'MinimumAddress' : [ 0x8, ['_LARGE_INTEGER']], 'MaximumAddress' : [ 0x10, ['_LARGE_INTEGER']], } ], '__unnamed_1f30' : [ 0x14, { 'MinimumVector' : [ 0x0, ['unsigned long']], 'MaximumVector' : [ 0x4, ['unsigned long']], 'AffinityPolicy' : [ 0x8, ['unsigned short']], 'Group' : [ 0xa, ['unsigned short']], 'PriorityPolicy' : [ 0xc, ['Enumeration', dict(target = 'long', choices = {0: 'IrqPriorityUndefined', 1: 'IrqPriorityLow', 2: 'IrqPriorityNormal', 3: 'IrqPriorityHigh'})]], 'TargetedProcessors' : [ 0x10, ['unsigned long']], } ], '__unnamed_1f32' : [ 0x8, { 'MinimumChannel' : [ 0x0, ['unsigned long']], 'MaximumChannel' : [ 0x4, ['unsigned long']], } ], '__unnamed_1f34' : [ 0x10, { 'RequestLine' : [ 0x0, ['unsigned long']], 'Reserved' : [ 0x4, ['unsigned long']], 'Channel' : [ 0x8, ['unsigned long']], 'TransferWidth' : [ 0xc, ['unsigned long']], } ], '__unnamed_1f36' : [ 0xc, { 'Data' : [ 0x0, ['array', 3, ['unsigned long']]], } ], '__unnamed_1f38' : [ 0x10, { 'Length' : [ 0x0, ['unsigned long']], 'MinBusNumber' : [ 0x4, ['unsigned long']], 'MaxBusNumber' : [ 0x8, ['unsigned long']], 'Reserved' : [ 0xc, ['unsigned long']], } ], '__unnamed_1f3a' : [ 0xc, { 'Priority' : [ 0x0, ['unsigned long']], 'Reserved1' : [ 0x4, ['unsigned long']], 'Reserved2' : [ 0x8, ['unsigned long']], } ], '__unnamed_1f3c' : [ 0x18, { 'Length40' : [ 0x0, ['unsigned long']], 'Alignment40' : [ 0x4, ['unsigned long']], 'MinimumAddress' : [ 0x8, ['_LARGE_INTEGER']], 'MaximumAddress' : [ 0x10, ['_LARGE_INTEGER']], } ], '__unnamed_1f3e' : [ 0x18, { 'Length48' : [ 0x0, ['unsigned long']], 'Alignment48' : [ 0x4, ['unsigned long']], 'MinimumAddress' : [ 0x8, ['_LARGE_INTEGER']], 'MaximumAddress' : [ 0x10, ['_LARGE_INTEGER']], } ], '__unnamed_1f40' : [ 0x18, { 'Length64' : [ 0x0, ['unsigned long']], 'Alignment64' : [ 0x4, ['unsigned long']], 'MinimumAddress' : [ 0x8, ['_LARGE_INTEGER']], 'MaximumAddress' : [ 0x10, ['_LARGE_INTEGER']], } ], '__unnamed_1f42' : [ 0xc, { 'Class' : [ 0x0, ['unsigned char']], 'Type' : [ 0x1, ['unsigned char']], 'Reserved1' : [ 0x2, ['unsigned char']], 'Reserved2' : [ 0x3, ['unsigned char']], 'IdLowPart' : [ 0x4, ['unsigned long']], 'IdHighPart' : [ 0x8, ['unsigned long']], } ], '__unnamed_1f44' : [ 0x18, { 'Port' : [ 0x0, ['__unnamed_1f2c']], 'Memory' : [ 0x0, ['__unnamed_1f2c']], 'Interrupt' : [ 0x0, ['__unnamed_1f30']], 'Dma' : [ 0x0, ['__unnamed_1f32']], 'DmaV3' : [ 0x0, ['__unnamed_1f34']], 'Generic' : [ 0x0, ['__unnamed_1f2c']], 'DevicePrivate' : [ 0x0, ['__unnamed_1f36']], 'BusNumber' : [ 0x0, ['__unnamed_1f38']], 'ConfigData' : [ 0x0, ['__unnamed_1f3a']], 'Memory40' : [ 0x0, ['__unnamed_1f3c']], 'Memory48' : [ 0x0, ['__unnamed_1f3e']], 'Memory64' : [ 0x0, ['__unnamed_1f40']], 'Connection' : [ 0x0, ['__unnamed_1f42']], } ], '_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_1f44']], } ], '_POP_THERMAL_ZONE' : [ 0x150, { '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']], 'HighPrecisionThrottle' : [ 0x10, ['long']], 'Throttle' : [ 0x14, ['long']], 'PendingThrottle' : [ 0x18, ['long']], 'ThrottleStartTime' : [ 0x20, ['unsigned long long']], 'LastTime' : [ 0x28, ['unsigned long long']], 'SampleRate' : [ 0x30, ['unsigned long']], 'LastTemp' : [ 0x34, ['unsigned long']], 'PassiveTimer' : [ 0x38, ['_KTIMER']], 'PassiveDpc' : [ 0x60, ['_KDPC']], 'OverThrottled' : [ 0x80, ['_POP_ACTION_TRIGGER']], 'Irp' : [ 0x90, ['pointer', ['_IRP']]], 'Info' : [ 0x94, ['_THERMAL_INFORMATION_EX']], 'InfoLastUpdateTime' : [ 0xe0, ['_LARGE_INTEGER']], 'Metrics' : [ 0xe8, ['_POP_THERMAL_ZONE_METRICS']], } ], '_MMPTE_LIST' : [ 0x8, { 'Valid' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long long')]], 'OneEntry' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long long')]], 'filler0' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 10, native_type='unsigned long long')]], 'Prototype' : [ 0x0, ['BitField', dict(start_bit = 10, end_bit = 11, native_type='unsigned long long')]], 'filler1' : [ 0x0, ['BitField', dict(start_bit = 11, end_bit = 32, native_type='unsigned long long')]], 'NextEntry' : [ 0x0, ['BitField', dict(start_bit = 32, end_bit = 64, native_type='unsigned long long')]], } ], '_VI_POOL_PAGE_HEADER' : [ 0xc, { 'NextPage' : [ 0x0, ['pointer', ['_SINGLE_LIST_ENTRY']]], 'VerifierEntry' : [ 0x4, ['pointer', ['void']]], 'Signature' : [ 0x8, ['unsigned long']], } ], '_HANDLE_TRACE_DEBUG_INFO' : [ 0x80, { 'RefCount' : [ 0x0, ['long']], 'TableSize' : [ 0x4, ['unsigned long']], 'BitMaskFlags' : [ 0x8, ['unsigned long']], 'CloseCompactionLock' : [ 0xc, ['_FAST_MUTEX']], 'CurrentStackIndex' : [ 0x2c, ['unsigned long']], 'TraceDb' : [ 0x30, ['array', 1, ['_HANDLE_TRACE_DB_ENTRY']]], } ], '_HHIVE' : [ 0x3a0, { 'Signature' : [ 0x0, ['unsigned long']], 'GetCellRoutine' : [ 0x4, ['pointer', ['void']]], 'Allocate' : [ 0x8, ['pointer', ['void']]], 'Free' : [ 0xc, ['pointer', ['void']]], 'FileWrite' : [ 0x10, ['pointer', ['void']]], 'FileRead' : [ 0x14, ['pointer', ['void']]], 'HiveLoadFailure' : [ 0x18, ['pointer', ['void']]], 'BaseBlock' : [ 0x1c, ['pointer', ['_HBASE_BLOCK']]], 'DirtyVector' : [ 0x20, ['_RTL_BITMAP']], 'DirtyCount' : [ 0x28, ['unsigned long']], 'DirtyAlloc' : [ 0x2c, ['unsigned long']], 'BaseBlockAlloc' : [ 0x30, ['unsigned long']], 'Cluster' : [ 0x34, ['unsigned long']], 'Flat' : [ 0x38, ['unsigned char']], 'ReadOnly' : [ 0x39, ['unsigned char']], 'DirtyFlag' : [ 0x3a, ['unsigned char']], 'HvBinHeadersUse' : [ 0x3c, ['unsigned long']], 'HvFreeCellsUse' : [ 0x40, ['unsigned long']], 'HvUsedCellsUse' : [ 0x44, ['unsigned long']], 'CmUsedCellsUse' : [ 0x48, ['unsigned long']], 'HiveFlags' : [ 0x4c, ['unsigned long']], 'CurrentLog' : [ 0x50, ['unsigned long']], 'LogSize' : [ 0x54, ['array', 2, ['unsigned long']]], 'RefreshCount' : [ 0x5c, ['unsigned long']], 'StorageTypeCount' : [ 0x60, ['unsigned long']], 'Version' : [ 0x64, ['unsigned long']], 'Storage' : [ 0x68, ['array', 2, ['_DUAL']]], } ], '_WHEA_XPF_NMI_DESCRIPTOR' : [ 0x3, { 'Type' : [ 0x0, ['unsigned short']], 'Enabled' : [ 0x2, ['unsigned char']], } ], '_CM_WORKITEM' : [ 0x14, { 'ListEntry' : [ 0x0, ['_LIST_ENTRY']], 'Private' : [ 0x8, ['unsigned long']], 'WorkerRoutine' : [ 0xc, ['pointer', ['void']]], 'Parameter' : [ 0x10, ['pointer', ['void']]], } ], '_POP_THERMAL_ZONE_METRICS' : [ 0x68, { 'MetricsResource' : [ 0x0, ['_ERESOURCE']], 'ActiveCount' : [ 0x38, ['unsigned long']], 'PassiveCount' : [ 0x3c, ['unsigned long']], 'LastActiveStartTick' : [ 0x40, ['_LARGE_INTEGER']], 'AverageActiveTime' : [ 0x48, ['_LARGE_INTEGER']], 'LastPassiveStartTick' : [ 0x50, ['_LARGE_INTEGER']], 'AveragePassiveTime' : [ 0x58, ['_LARGE_INTEGER']], 'StartTickSinceLastReset' : [ 0x60, ['_LARGE_INTEGER']], } ], '_CM_TRANS' : [ 0x68, { 'TransactionListEntry' : [ 0x0, ['_LIST_ENTRY']], 'KCBUoWListHead' : [ 0x8, ['_LIST_ENTRY']], 'LazyCommitListEntry' : [ 0x10, ['_LIST_ENTRY']], 'KtmTrans' : [ 0x18, ['pointer', ['void']]], 'CmRm' : [ 0x1c, ['pointer', ['_CM_RM']]], 'KtmEnlistmentObject' : [ 0x20, ['pointer', ['_KENLISTMENT']]], 'KtmEnlistmentHandle' : [ 0x24, ['pointer', ['void']]], 'KtmUow' : [ 0x28, ['_GUID']], 'StartLsn' : [ 0x38, ['unsigned long long']], 'TransState' : [ 0x40, ['unsigned long']], 'HiveCount' : [ 0x44, ['unsigned long']], 'HiveArray' : [ 0x48, ['array', 7, ['pointer', ['_CMHIVE']]]], } ], '_WHEA_ERROR_RECORD_HEADER_VALIDBITS' : [ 0x4, { 'PlatformId' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]], 'Timestamp' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]], 'PartitionId' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]], 'Reserved' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 32, native_type='unsigned long')]], 'AsULONG' : [ 0x0, ['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']]], } ], '_RTL_RANGE_LIST' : [ 0x14, { 'ListHead' : [ 0x0, ['_LIST_ENTRY']], 'Flags' : [ 0x8, ['unsigned long']], 'Count' : [ 0xc, ['unsigned long']], 'Stamp' : [ 0x10, ['unsigned long']], } ], '_RTL_TIME_ZONE_INFORMATION' : [ 0xac, { 'Bias' : [ 0x0, ['long']], 'StandardName' : [ 0x4, ['array', 32, ['wchar']]], 'StandardStart' : [ 0x44, ['_TIME_FIELDS']], 'StandardBias' : [ 0x54, ['long']], 'DaylightName' : [ 0x58, ['array', 32, ['wchar']]], 'DaylightStart' : [ 0x98, ['_TIME_FIELDS']], 'DaylightBias' : [ 0xa8, ['long']], } ], '_OBJECT_CREATE_INFORMATION' : [ 0x2c, { 'Attributes' : [ 0x0, ['unsigned long']], 'RootDirectory' : [ 0x4, ['pointer', ['void']]], 'ProbeMode' : [ 0x8, ['unsigned char']], 'PagedPoolCharge' : [ 0xc, ['unsigned long']], 'NonPagedPoolCharge' : [ 0x10, ['unsigned long']], 'SecurityDescriptorCharge' : [ 0x14, ['unsigned long']], 'SecurityDescriptor' : [ 0x18, ['pointer', ['void']]], 'SecurityQos' : [ 0x1c, ['pointer', ['_SECURITY_QUALITY_OF_SERVICE']]], 'SecurityQualityOfService' : [ 0x20, ['_SECURITY_QUALITY_OF_SERVICE']], } ], '_POOL_HACKER' : [ 0x28, { 'Header' : [ 0x0, ['_POOL_HEADER']], 'Contents' : [ 0x8, ['array', 8, ['unsigned long']]], } ], '_PO_DIAG_STACK_RECORD' : [ 0x8, { 'StackDepth' : [ 0x0, ['unsigned long']], 'Stack' : [ 0x4, ['array', 1, ['pointer', ['void']]]], } ], '_SECTION_OBJECT_POINTERS' : [ 0xc, { 'DataSectionObject' : [ 0x0, ['pointer', ['void']]], 'SharedCacheMap' : [ 0x4, ['pointer', ['void']]], 'ImageSectionObject' : [ 0x8, ['pointer', ['void']]], } ], '_VF_BTS_DATA_MANAGEMENT_AREA' : [ 0x34, { 'BTSBufferBase' : [ 0x0, ['pointer', ['void']]], 'BTSIndex' : [ 0x4, ['pointer', ['void']]], 'BTSMax' : [ 0x8, ['pointer', ['void']]], 'BTSInterruptThreshold' : [ 0xc, ['pointer', ['void']]], 'PEBSBufferBase' : [ 0x10, ['pointer', ['void']]], 'PEBSIndex' : [ 0x14, ['pointer', ['void']]], 'PEBSMax' : [ 0x18, ['pointer', ['void']]], 'PEBSInterruptThreshold' : [ 0x1c, ['pointer', ['void']]], 'PEBSCounterReset' : [ 0x20, ['array', 2, ['pointer', ['void']]]], 'Reserved' : [ 0x28, ['array', 12, ['unsigned char']]], } ], '_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']], } ], '_SEP_AUDIT_POLICY' : [ 0x1e, { 'AdtTokenPolicy' : [ 0x0, ['_TOKEN_AUDIT_POLICY']], 'PolicySetStatus' : [ 0x1d, ['unsigned char']], } ], '__unnamed_1f98' : [ 0x4, { 'SnapSharedExportsFailed' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]], 'Spare' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 32, native_type='unsigned long')]], } ], '__unnamed_1f9a' : [ 0x10, { 'AllSharedExportThunks' : [ 0x0, ['_VF_TARGET_ALL_SHARED_EXPORT_THUNKS']], 'Flags' : [ 0x0, ['__unnamed_1f98']], } ], '_VF_TARGET_DRIVER' : [ 0x1c, { 'TreeNode' : [ 0x0, ['_VF_AVL_TREE_NODE']], 'u1' : [ 0x8, ['__unnamed_1f9a']], 'VerifiedData' : [ 0x18, ['pointer', ['_VF_TARGET_VERIFIED_DRIVER_DATA']]], } ], '_MM_AVL_TABLE' : [ 0x18, { 'BalancedRoot' : [ 0x0, ['_MM_AVL_NODE']], 'DepthOfTree' : [ 0xc, ['BitField', dict(start_bit = 0, end_bit = 5, native_type='unsigned long')]], 'TableType' : [ 0xc, ['BitField', dict(start_bit = 5, end_bit = 8, native_type='unsigned long')]], 'NumberGenericTableElements' : [ 0xc, ['BitField', dict(start_bit = 8, end_bit = 32, native_type='unsigned long')]], 'NodeHint' : [ 0x10, ['pointer', ['void']]], 'NodeFreeHint' : [ 0x14, ['pointer', ['void']]], } ], '__unnamed_1fa7' : [ 0x14, { 'ClassGuid' : [ 0x0, ['_GUID']], 'SymbolicLinkName' : [ 0x10, ['array', 1, ['wchar']]], } ], '__unnamed_1fa9' : [ 0x2, { 'DeviceId' : [ 0x0, ['array', 1, ['wchar']]], } ], '__unnamed_1fab' : [ 0x8, { 'NotificationStructure' : [ 0x0, ['pointer', ['void']]], 'DeviceId' : [ 0x4, ['array', 1, ['wchar']]], } ], '__unnamed_1fad' : [ 0x4, { 'Notification' : [ 0x0, ['pointer', ['void']]], } ], '__unnamed_1faf' : [ 0x8, { 'NotificationCode' : [ 0x0, ['unsigned long']], 'NotificationData' : [ 0x4, ['unsigned long']], } ], '__unnamed_1fb1' : [ 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, ['wchar']]], } ], '__unnamed_1fb3' : [ 0x10, { 'BlockedDriverGuid' : [ 0x0, ['_GUID']], } ], '__unnamed_1fb5' : [ 0x2, { 'ParentId' : [ 0x0, ['array', 1, ['wchar']]], } ], '__unnamed_1fb7' : [ 0x20, { 'PowerSettingGuid' : [ 0x0, ['_GUID']], 'Flags' : [ 0x10, ['unsigned long']], 'SessionId' : [ 0x14, ['unsigned long']], 'DataLength' : [ 0x18, ['unsigned long']], 'Data' : [ 0x1c, ['array', 1, ['unsigned char']]], } ], '__unnamed_1fb9' : [ 0x20, { 'DeviceClass' : [ 0x0, ['__unnamed_1fa7']], 'TargetDevice' : [ 0x0, ['__unnamed_1fa9']], 'InstallDevice' : [ 0x0, ['__unnamed_1fa9']], 'CustomNotification' : [ 0x0, ['__unnamed_1fab']], 'ProfileNotification' : [ 0x0, ['__unnamed_1fad']], 'PowerNotification' : [ 0x0, ['__unnamed_1faf']], 'VetoNotification' : [ 0x0, ['__unnamed_1fb1']], 'BlockedDriverNotification' : [ 0x0, ['__unnamed_1fb3']], 'InvalidIDNotification' : [ 0x0, ['__unnamed_1fb5']], 'PowerSettingNotification' : [ 0x0, ['__unnamed_1fb7']], 'PropertyChangeNotification' : [ 0x0, ['__unnamed_1fa9']], 'DeviceInstanceNotification' : [ 0x0, ['__unnamed_1fa9']], } ], '_PLUGPLAY_EVENT_BLOCK' : [ 0x44, { 'EventGuid' : [ 0x0, ['_GUID']], 'EventCategory' : [ 0x10, ['Enumeration', dict(target = 'long', choices = {0: 'HardwareProfileChangeEvent', 1: 'TargetDeviceChangeEvent', 2: 'DeviceClassChangeEvent', 3: 'CustomDeviceEvent', 4: 'DeviceInstallEvent', 5: 'DeviceArrivalEvent', 6: 'VetoEvent', 7: 'BlockedDriverEvent', 8: 'InvalidIDEvent', 9: 'DevicePropertyChangeEvent', 10: 'DeviceInstanceRemovalEvent', 11: 'DeviceInstanceStartedEvent', 12: 'MaxPlugEventCategory'})]], 'Result' : [ 0x14, ['pointer', ['unsigned long']]], 'Flags' : [ 0x18, ['unsigned long']], 'TotalSize' : [ 0x1c, ['unsigned long']], 'DeviceObject' : [ 0x20, ['pointer', ['void']]], 'u' : [ 0x24, ['__unnamed_1fb9']], } ], '_VF_SUSPECT_DRIVER_ENTRY' : [ 0x18, { 'Links' : [ 0x0, ['_LIST_ENTRY']], 'Loads' : [ 0x8, ['unsigned long']], 'Unloads' : [ 0xc, ['unsigned long']], 'BaseName' : [ 0x10, ['_UNICODE_STRING']], } ], '_MMPTE_TIMESTAMP' : [ 0x8, { 'MustBeZero' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long long')]], 'PageFileLow' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 5, native_type='unsigned long long')]], 'Protection' : [ 0x0, ['BitField', dict(start_bit = 5, end_bit = 10, native_type='unsigned long long')]], 'Prototype' : [ 0x0, ['BitField', dict(start_bit = 10, end_bit = 11, native_type='unsigned long long')]], 'Transition' : [ 0x0, ['BitField', dict(start_bit = 11, end_bit = 12, native_type='unsigned long long')]], 'Unused' : [ 0x0, ['BitField', dict(start_bit = 12, end_bit = 32, native_type='unsigned long long')]], 'GlobalTimeStamp' : [ 0x0, ['BitField', dict(start_bit = 32, end_bit = 64, native_type='unsigned long long')]], } ], '_SID_AND_ATTRIBUTES_HASH' : [ 0x88, { 'SidCount' : [ 0x0, ['unsigned long']], 'SidAttr' : [ 0x4, ['pointer', ['_SID_AND_ATTRIBUTES']]], 'Hash' : [ 0x8, ['array', 32, ['unsigned long']]], } ], '_XSTATE_CONTEXT' : [ 0x20, { 'Mask' : [ 0x0, ['unsigned long long']], 'Length' : [ 0x8, ['unsigned long']], 'Reserved1' : [ 0xc, ['unsigned long']], 'Area' : [ 0x10, ['pointer', ['_XSAVE_AREA']]], 'Reserved2' : [ 0x14, ['unsigned long']], 'Buffer' : [ 0x18, ['pointer', ['void']]], 'Reserved3' : [ 0x1c, ['unsigned long']], } ], '_PROCESSOR_IDLE_PREPARE_INFO' : [ 0x50, { 'Context' : [ 0x0, ['pointer', ['void']]], 'Constraints' : [ 0x8, ['_PROCESSOR_IDLE_CONSTRAINTS']], 'DependencyCount' : [ 0x38, ['unsigned long']], 'DependencyUsed' : [ 0x3c, ['unsigned long']], 'DependencyArray' : [ 0x40, ['pointer', ['_PROCESSOR_IDLE_DEPENDENCY']]], 'PlatformIdleStateIndex' : [ 0x44, ['unsigned long']], 'ProcessorIdleStateIndex' : [ 0x48, ['unsigned long']], 'IdleSelectFailureMask' : [ 0x4c, ['unsigned long']], } ], '_XSAVE_FORMAT' : [ 0x200, { 'ControlWord' : [ 0x0, ['unsigned short']], 'StatusWord' : [ 0x2, ['unsigned short']], 'TagWord' : [ 0x4, ['unsigned char']], 'Reserved1' : [ 0x5, ['unsigned char']], 'ErrorOpcode' : [ 0x6, ['unsigned short']], 'ErrorOffset' : [ 0x8, ['unsigned long']], 'ErrorSelector' : [ 0xc, ['unsigned short']], 'Reserved2' : [ 0xe, ['unsigned short']], 'DataOffset' : [ 0x10, ['unsigned long']], 'DataSelector' : [ 0x14, ['unsigned short']], 'Reserved3' : [ 0x16, ['unsigned short']], 'MxCsr' : [ 0x18, ['unsigned long']], 'MxCsr_Mask' : [ 0x1c, ['unsigned long']], 'FloatRegisters' : [ 0x20, ['array', 8, ['_M128A']]], 'XmmRegisters' : [ 0xa0, ['array', 8, ['_M128A']]], 'Reserved4' : [ 0x120, ['array', 220, ['unsigned char']]], 'Cr0NpxState' : [ 0x1fc, ['unsigned long']], } ], '__unnamed_1fd6' : [ 0x1, { 'AsUCHAR' : [ 0x0, ['unsigned char']], 'NoDomainAccounting' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned char')]], 'IncreasePolicy' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 3, native_type='unsigned char')]], 'DecreasePolicy' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 5, native_type='unsigned char')]], 'Reserved' : [ 0x0, ['BitField', dict(start_bit = 5, end_bit = 8, native_type='unsigned char')]], } ], 'PROCESSOR_PERFSTATE_POLICY' : [ 0x1c, { 'Revision' : [ 0x0, ['unsigned long']], 'MaxThrottle' : [ 0x4, ['unsigned char']], 'MinThrottle' : [ 0x5, ['unsigned char']], 'BusyAdjThreshold' : [ 0x6, ['unsigned char']], 'Spare' : [ 0x7, ['unsigned char']], 'Flags' : [ 0x7, ['__unnamed_1fd6']], 'TimeCheck' : [ 0x8, ['unsigned long']], 'IncreaseTime' : [ 0xc, ['unsigned long']], 'DecreaseTime' : [ 0x10, ['unsigned long']], 'IncreasePercent' : [ 0x14, ['unsigned long']], 'DecreasePercent' : [ 0x18, ['unsigned long']], } ], '_BUS_EXTENSION_LIST' : [ 0x8, { 'Next' : [ 0x0, ['pointer', ['void']]], 'BusExtension' : [ 0x4, ['pointer', ['_PI_BUS_EXTENSION']]], } ], '_CACHED_CHILD_LIST' : [ 0x8, { 'Count' : [ 0x0, ['unsigned long']], 'ValueList' : [ 0x4, ['unsigned long']], 'RealKcb' : [ 0x4, ['pointer', ['_CM_KEY_CONTROL_BLOCK']]], } ], '_KDEVICE_QUEUE' : [ 0x14, { 'Type' : [ 0x0, ['short']], 'Size' : [ 0x2, ['short']], 'DeviceListHead' : [ 0x4, ['_LIST_ENTRY']], 'Lock' : [ 0xc, ['unsigned long']], 'Busy' : [ 0x10, ['unsigned char']], } ], '_SYSTEM_POWER_STATE_CONTEXT' : [ 0x4, { 'Reserved1' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 8, native_type='unsigned long')]], 'TargetSystemState' : [ 0x0, ['BitField', dict(start_bit = 8, end_bit = 12, native_type='unsigned long')]], 'EffectiveSystemState' : [ 0x0, ['BitField', dict(start_bit = 12, end_bit = 16, native_type='unsigned long')]], 'CurrentSystemState' : [ 0x0, ['BitField', dict(start_bit = 16, end_bit = 20, native_type='unsigned long')]], 'IgnoreHibernationPath' : [ 0x0, ['BitField', dict(start_bit = 20, end_bit = 21, native_type='unsigned long')]], 'PseudoTransition' : [ 0x0, ['BitField', dict(start_bit = 21, end_bit = 22, native_type='unsigned long')]], 'Reserved2' : [ 0x0, ['BitField', dict(start_bit = 22, end_bit = 32, native_type='unsigned long')]], 'ContextAsUlong' : [ 0x0, ['unsigned long']], } ], '_PEBS_DS_SAVE_AREA' : [ 0x60, { 'BtsBufferBase' : [ 0x0, ['unsigned long long']], 'BtsIndex' : [ 0x8, ['unsigned long long']], 'BtsAbsoluteMaximum' : [ 0x10, ['unsigned long long']], 'BtsInterruptThreshold' : [ 0x18, ['unsigned long long']], 'PebsBufferBase' : [ 0x20, ['unsigned long long']], 'PebsIndex' : [ 0x28, ['unsigned long long']], 'PebsAbsoluteMaximum' : [ 0x30, ['unsigned long long']], 'PebsInterruptThreshold' : [ 0x38, ['unsigned long long']], 'PebsCounterReset0' : [ 0x40, ['unsigned long long']], 'PebsCounterReset1' : [ 0x48, ['unsigned long long']], 'PebsCounterReset2' : [ 0x50, ['unsigned long long']], 'PebsCounterReset3' : [ 0x58, ['unsigned long long']], } ], '_OBJECT_TYPE_INITIALIZER' : [ 0x58, { 'Length' : [ 0x0, ['unsigned short']], 'ObjectTypeFlags' : [ 0x2, ['unsigned char']], 'CaseInsensitive' : [ 0x2, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned char')]], 'UnnamedObjectsOnly' : [ 0x2, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned char')]], 'UseDefaultObject' : [ 0x2, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned char')]], 'SecurityRequired' : [ 0x2, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned char')]], 'MaintainHandleCount' : [ 0x2, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned char')]], 'MaintainTypeList' : [ 0x2, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned char')]], 'SupportsObjectCallbacks' : [ 0x2, ['BitField', dict(start_bit = 6, end_bit = 7, native_type='unsigned char')]], 'CacheAligned' : [ 0x2, ['BitField', dict(start_bit = 7, end_bit = 8, native_type='unsigned char')]], 'ObjectTypeCode' : [ 0x4, ['unsigned long']], 'InvalidAttributes' : [ 0x8, ['unsigned long']], 'GenericMapping' : [ 0xc, ['_GENERIC_MAPPING']], 'ValidAccessMask' : [ 0x1c, ['unsigned long']], 'RetainAccess' : [ 0x20, ['unsigned long']], 'PoolType' : [ 0x24, ['Enumeration', dict(target = 'long', choices = {0: 'NonPagedPoolBase', 1: 'PagedPool', 2: 'NonPagedPoolBaseMustSucceed', 3: 'DontUseThisType', 4: 'NonPagedPoolBaseCacheAligned', 5: 'PagedPoolCacheAligned', 6: 'NonPagedPoolBaseCacheAlignedMustS', 7: 'MaxPoolType', 34: 'NonPagedPoolMustSucceedSession', 516: 'NonPagedPoolNxCacheAligned', 35: 'DontUseThisTypeSession', 32: 'NonPagedPoolSession', 512: 'NonPagedPoolNx', 544: 'NonPagedPoolSessionNx', 36: 'NonPagedPoolCacheAlignedSession', 33: 'PagedPoolSession', 38: 'NonPagedPoolCacheAlignedMustSSession', 37: 'PagedPoolCacheAlignedSession'})]], 'DefaultPagedPoolCharge' : [ 0x28, ['unsigned long']], 'DefaultNonPagedPoolCharge' : [ 0x2c, ['unsigned long']], 'DumpProcedure' : [ 0x30, ['pointer', ['void']]], 'OpenProcedure' : [ 0x34, ['pointer', ['void']]], 'CloseProcedure' : [ 0x38, ['pointer', ['void']]], 'DeleteProcedure' : [ 0x3c, ['pointer', ['void']]], 'ParseProcedure' : [ 0x40, ['pointer', ['void']]], 'SecurityProcedure' : [ 0x44, ['pointer', ['void']]], 'QueryNameProcedure' : [ 0x48, ['pointer', ['void']]], 'OkayToCloseProcedure' : [ 0x4c, ['pointer', ['void']]], 'WaitObjectFlagMask' : [ 0x50, ['unsigned long']], 'WaitObjectFlagOffset' : [ 0x54, ['unsigned short']], 'WaitObjectPointerOffset' : [ 0x56, ['unsigned short']], } ], '__unnamed_2008' : [ 0x4, { 'LongFlags' : [ 0x0, ['unsigned long']], 'SubsectionFlags' : [ 0x0, ['_MMSUBSECTION_FLAGS']], } ], '_SUBSECTION' : [ 0x20, { 'ControlArea' : [ 0x0, ['pointer', ['_CONTROL_AREA']]], 'SubsectionBase' : [ 0x4, ['pointer', ['_MMPTE']]], 'NextSubsection' : [ 0x8, ['pointer', ['_SUBSECTION']]], 'PtesInSubsection' : [ 0xc, ['unsigned long']], 'UnusedPtes' : [ 0x10, ['unsigned long']], 'GlobalPerSessionHead' : [ 0x10, ['pointer', ['_MM_AVL_TABLE']]], 'u' : [ 0x14, ['__unnamed_2008']], 'StartingSector' : [ 0x18, ['unsigned long']], 'NumberOfFullSectors' : [ 0x1c, ['unsigned long']], } ], 'tagSWITCH_CONTEXT_ATTRIBUTE' : [ 0x18, { 'ulContextUpdateCounter' : [ 0x0, ['unsigned long long']], 'fAllowContextUpdate' : [ 0x8, ['long']], 'fEnableTrace' : [ 0xc, ['long']], 'EtwHandle' : [ 0x10, ['unsigned long long']], } ], '_IO_CLIENT_EXTENSION' : [ 0x8, { 'NextExtension' : [ 0x0, ['pointer', ['_IO_CLIENT_EXTENSION']]], 'ClientIdentificationAddress' : [ 0x4, ['pointer', ['void']]], } ], '_ETW_BUFFER_CONTEXT' : [ 0x4, { 'ProcessorNumber' : [ 0x0, ['unsigned char']], 'Alignment' : [ 0x1, ['unsigned char']], 'ProcessorIndex' : [ 0x0, ['unsigned short']], 'LoggerId' : [ 0x2, ['unsigned short']], } ], '_DIRTY_PAGE_STATISTICS' : [ 0xc, { 'DirtyPages' : [ 0x0, ['unsigned long']], 'DirtyPagesLastScan' : [ 0x4, ['unsigned long']], 'DirtyPagesScheduledLastScan' : [ 0x8, ['unsigned long']], } ], '_PROC_IDLE_SNAP' : [ 0x10, { 'Time' : [ 0x0, ['unsigned long long']], 'Idle' : [ 0x8, ['unsigned long long']], } ], '_KERNEL_STACK_SEGMENT' : [ 0x10, { 'StackBase' : [ 0x0, ['unsigned long']], 'StackLimit' : [ 0x4, ['unsigned long']], 'KernelStack' : [ 0x8, ['unsigned long']], 'InitialStack' : [ 0xc, ['unsigned long']], } ], '_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')]], 'DisableExceptionChainValidation' : [ 0x0, ['BitField', dict(start_bit = 6, end_bit = 7, native_type='unsigned char')]], 'Spare' : [ 0x0, ['BitField', dict(start_bit = 7, end_bit = 8, native_type='unsigned char')]], 'ExecuteOptions' : [ 0x0, ['unsigned char']], 'ExecuteOptionsNV' : [ 0x0, ['unsigned char']], } ], '_SEP_TOKEN_PRIVILEGES' : [ 0x18, { 'Present' : [ 0x0, ['unsigned long long']], 'Enabled' : [ 0x8, ['unsigned long long']], 'EnabledByDefault' : [ 0x10, ['unsigned long long']], } ], '_WHEA_XPF_MCE_DESCRIPTOR' : [ 0x398, { 'Type' : [ 0x0, ['unsigned short']], 'Enabled' : [ 0x2, ['unsigned char']], 'NumberOfBanks' : [ 0x3, ['unsigned char']], 'Flags' : [ 0x4, ['_XPF_MCE_FLAGS']], 'MCG_Capability' : [ 0x8, ['unsigned long long']], 'MCG_GlobalControl' : [ 0x10, ['unsigned long long']], 'Banks' : [ 0x18, ['array', 32, ['_WHEA_XPF_MC_BANK_DESCRIPTOR']]], } ], '_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']], } ], '_VACB_ARRAY_HEADER' : [ 0x10, { 'VacbArrayIndex' : [ 0x0, ['unsigned long']], 'MappingCount' : [ 0x4, ['unsigned long']], 'HighestMappedIndex' : [ 0x8, ['unsigned long']], 'Reserved' : [ 0xc, ['unsigned long']], } ], '_MMWSLENTRY' : [ 0x4, { 'Valid' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]], 'Spare' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]], 'Hashed' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]], 'Direct' : [ 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')]], 'Age' : [ 0x0, ['BitField', dict(start_bit = 9, end_bit = 12, native_type='unsigned long')]], 'VirtualPageNumber' : [ 0x0, ['BitField', dict(start_bit = 12, end_bit = 32, native_type='unsigned long')]], } ], '_DBGKD_SWITCH_PARTITION' : [ 0x4, { 'Partition' : [ 0x0, ['unsigned long']], } ], '_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']], } ], '_WHEA_XPF_CMC_DESCRIPTOR' : [ 0x3a4, { 'Type' : [ 0x0, ['unsigned short']], 'Enabled' : [ 0x2, ['unsigned char']], 'NumberOfBanks' : [ 0x3, ['unsigned char']], 'Reserved' : [ 0x4, ['unsigned long']], 'Notify' : [ 0x8, ['_WHEA_NOTIFICATION_DESCRIPTOR']], 'Banks' : [ 0x24, ['array', 32, ['_WHEA_XPF_MC_BANK_DESCRIPTOR']]], } ], '_WHEA_TIMESTAMP' : [ 0x8, { 'Seconds' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 8, native_type='unsigned long long')]], 'Minutes' : [ 0x0, ['BitField', dict(start_bit = 8, end_bit = 16, native_type='unsigned long long')]], 'Hours' : [ 0x0, ['BitField', dict(start_bit = 16, end_bit = 24, native_type='unsigned long long')]], 'Precise' : [ 0x0, ['BitField', dict(start_bit = 24, end_bit = 25, native_type='unsigned long long')]], 'Reserved' : [ 0x0, ['BitField', dict(start_bit = 25, end_bit = 32, native_type='unsigned long long')]], 'Day' : [ 0x0, ['BitField', dict(start_bit = 32, end_bit = 40, native_type='unsigned long long')]], 'Month' : [ 0x0, ['BitField', dict(start_bit = 40, end_bit = 48, native_type='unsigned long long')]], 'Year' : [ 0x0, ['BitField', dict(start_bit = 48, end_bit = 56, native_type='unsigned long long')]], 'Century' : [ 0x0, ['BitField', dict(start_bit = 56, end_bit = 64, native_type='unsigned long long')]], 'AsLARGE_INTEGER' : [ 0x0, ['_LARGE_INTEGER']], } ], '_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, ['wchar']]], } ], '_CACHE_DESCRIPTOR' : [ 0xc, { 'Level' : [ 0x0, ['unsigned char']], 'Associativity' : [ 0x1, ['unsigned char']], 'LineSize' : [ 0x2, ['unsigned short']], 'Size' : [ 0x4, ['unsigned long']], 'Type' : [ 0x8, ['Enumeration', dict(target = 'long', choices = {0: 'CacheUnified', 1: 'CacheInstruction', 2: 'CacheData', 3: 'CacheTrace'})]], } ], '__unnamed_204c' : [ 0x4, { 'ProviderPdo' : [ 0x0, ['pointer', ['_DEVICE_OBJECT']]], 'ProviderReservation' : [ 0x0, ['pointer', ['_PNP_RESERVED_PROVIDER_INFO']]], } ], '_PNP_PROVIDER_INFO' : [ 0x10, { 'ListEntry' : [ 0x0, ['_LIST_ENTRY']], 'ProviderType' : [ 0x8, ['unsigned char']], 'Satisfied' : [ 0x9, ['unsigned char']], 'Flags' : [ 0xa, ['unsigned short']], 'u' : [ 0xc, ['__unnamed_204c']], } ], '_FILE_BASIC_INFORMATION' : [ 0x28, { 'CreationTime' : [ 0x0, ['_LARGE_INTEGER']], 'LastAccessTime' : [ 0x8, ['_LARGE_INTEGER']], 'LastWriteTime' : [ 0x10, ['_LARGE_INTEGER']], 'ChangeTime' : [ 0x18, ['_LARGE_INTEGER']], 'FileAttributes' : [ 0x20, ['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']]], } ], '_EVENT_HEADER' : [ 0x50, { 'Size' : [ 0x0, ['unsigned short']], 'HeaderType' : [ 0x2, ['unsigned short']], 'Flags' : [ 0x4, ['unsigned short']], 'EventProperty' : [ 0x6, ['unsigned short']], 'ThreadId' : [ 0x8, ['unsigned long']], 'ProcessId' : [ 0xc, ['unsigned long']], 'TimeStamp' : [ 0x10, ['_LARGE_INTEGER']], 'ProviderId' : [ 0x18, ['_GUID']], 'EventDescriptor' : [ 0x28, ['_EVENT_DESCRIPTOR']], 'KernelTime' : [ 0x38, ['unsigned long']], 'UserTime' : [ 0x3c, ['unsigned long']], 'ProcessorTime' : [ 0x38, ['unsigned long long']], 'ActivityId' : [ 0x40, ['_GUID']], } ], '_KiIoAccessMap' : [ 0x2024, { 'DirectionMap' : [ 0x0, ['array', 32, ['unsigned char']]], 'IoMap' : [ 0x20, ['array', 8196, ['unsigned char']]], } ], '_PF_KERNEL_GLOBALS' : [ 0x40, { 'AccessBufferAgeThreshold' : [ 0x0, ['unsigned long long']], 'AccessBufferRef' : [ 0x8, ['_EX_RUNDOWN_REF']], 'AccessBufferExistsEvent' : [ 0xc, ['_KEVENT']], 'AccessBufferMax' : [ 0x1c, ['unsigned long']], 'AccessBufferList' : [ 0x20, ['_SLIST_HEADER']], 'StreamSequenceNumber' : [ 0x28, ['long']], 'Flags' : [ 0x2c, ['unsigned long']], 'ScenarioPrefetchCount' : [ 0x30, ['long']], } ], '_CM_KEY_HASH_TABLE_ENTRY' : [ 0xc, { 'Lock' : [ 0x0, ['_EX_PUSH_LOCK']], 'Owner' : [ 0x4, ['pointer', ['_KTHREAD']]], 'Entry' : [ 0x8, ['pointer', ['_CM_KEY_HASH']]], } ], '_ARBITER_QUERY_ARBITRATE_PARAMETERS' : [ 0x4, { 'ArbitrationList' : [ 0x0, ['pointer', ['_LIST_ENTRY']]], } ], '_ARBITER_BOOT_ALLOCATION_PARAMETERS' : [ 0x4, { 'ArbitrationList' : [ 0x0, ['pointer', ['_LIST_ENTRY']]], } ], '_EXCEPTION_REGISTRATION_RECORD' : [ 0x8, { 'Next' : [ 0x0, ['pointer', ['_EXCEPTION_REGISTRATION_RECORD']]], 'Handler' : [ 0x4, ['pointer', ['void']]], } ], '_POP_SYSTEM_IDLE' : [ 0x40, { 'AverageIdleness' : [ 0x0, ['long']], 'LowestIdleness' : [ 0x4, ['long']], 'Time' : [ 0x8, ['unsigned long']], 'Timeout' : [ 0xc, ['unsigned long']], 'LastUserInput' : [ 0x10, ['unsigned long']], 'Action' : [ 0x14, ['POWER_ACTION_POLICY']], 'MinState' : [ 0x20, ['Enumeration', dict(target = 'long', choices = {0: 'PowerSystemUnspecified', 1: 'PowerSystemWorking', 2: 'PowerSystemSleeping1', 3: 'PowerSystemSleeping2', 4: 'PowerSystemSleeping3', 5: 'PowerSystemHibernate', 6: 'PowerSystemShutdown', 7: 'PowerSystemMaximum'})]], 'SystemRequired' : [ 0x24, ['unsigned long']], 'IdleWorker' : [ 0x28, ['unsigned char']], 'Sampling' : [ 0x29, ['unsigned char']], 'LastTick' : [ 0x30, ['unsigned long long']], 'LastSystemRequiredTime' : [ 0x38, ['unsigned long']], } ], '_VF_TARGET_ALL_SHARED_EXPORT_THUNKS' : [ 0x10, { 'SharedExportThunks' : [ 0x0, ['pointer', ['_VERIFIER_SHARED_EXPORT_THUNK']]], 'PoolSharedExportThunks' : [ 0x4, ['pointer', ['_VERIFIER_SHARED_EXPORT_THUNK']]], 'OrderDependentSharedExportThunks' : [ 0x8, ['pointer', ['_VERIFIER_SHARED_EXPORT_THUNK']]], 'XdvSharedExportThunks' : [ 0xc, ['pointer', ['_VERIFIER_SHARED_EXPORT_THUNK']]], } ], '_KSCHEDULING_GROUP' : [ 0x140, { 'Value' : [ 0x0, ['unsigned short']], 'Type' : [ 0x2, ['unsigned char']], 'HardCap' : [ 0x3, ['unsigned char']], 'RelativeWeight' : [ 0x4, ['unsigned long']], 'QueryHistoryTimeStamp' : [ 0x8, ['unsigned long long']], 'NotificationCycles' : [ 0x10, ['long long']], 'SchedulingGroupList' : [ 0x18, ['_LIST_ENTRY']], 'NotificationDpc' : [ 0x20, ['pointer', ['_KDPC']]], 'PerProcessor' : [ 0x40, ['array', 1, ['_KSCB']]], } ], '_ETW_REF_CLOCK' : [ 0x10, { 'StartTime' : [ 0x0, ['_LARGE_INTEGER']], 'StartPerfClock' : [ 0x8, ['_LARGE_INTEGER']], } ], '_OB_DUPLICATE_OBJECT_STATE' : [ 0x18, { 'SourceProcess' : [ 0x0, ['pointer', ['_EPROCESS']]], 'SourceHandle' : [ 0x4, ['pointer', ['void']]], 'Object' : [ 0x8, ['pointer', ['void']]], 'TargetAccess' : [ 0xc, ['unsigned long']], 'ObjectInfo' : [ 0x10, ['_HANDLE_TABLE_ENTRY_INFO']], 'HandleAttributes' : [ 0x14, ['unsigned long']], } ], '_MMPTE_SUBSECTION' : [ 0x8, { 'Valid' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long long')]], 'Unused0' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 5, native_type='unsigned long long')]], 'Protection' : [ 0x0, ['BitField', dict(start_bit = 5, end_bit = 10, native_type='unsigned long long')]], 'Prototype' : [ 0x0, ['BitField', dict(start_bit = 10, end_bit = 11, native_type='unsigned long long')]], 'Unused1' : [ 0x0, ['BitField', dict(start_bit = 11, end_bit = 32, native_type='unsigned long long')]], 'SubsectionAddress' : [ 0x0, ['BitField', dict(start_bit = 32, end_bit = 64, native_type='unsigned long long')]], } ], '_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'})]], } ], '_POP_IRP_WORKER_ENTRY' : [ 0x18, { 'Link' : [ 0x0, ['_LIST_ENTRY']], 'Thread' : [ 0x8, ['pointer', ['_ETHREAD']]], 'Irp' : [ 0xc, ['pointer', ['_IRP']]], 'Device' : [ 0x10, ['pointer', ['_DEVICE_OBJECT']]], 'Static' : [ 0x14, ['unsigned char']], } ], '__unnamed_2081' : [ 0xc, { 'Start' : [ 0x0, ['_LARGE_INTEGER']], 'Length' : [ 0x8, ['unsigned long']], } ], '__unnamed_2083' : [ 0xc, { 'Level' : [ 0x0, ['unsigned short']], 'Group' : [ 0x2, ['unsigned short']], 'Vector' : [ 0x4, ['unsigned long']], 'Affinity' : [ 0x8, ['unsigned long']], } ], '__unnamed_2085' : [ 0xc, { 'Group' : [ 0x0, ['unsigned short']], 'MessageCount' : [ 0x2, ['unsigned short']], 'Vector' : [ 0x4, ['unsigned long']], 'Affinity' : [ 0x8, ['unsigned long']], } ], '__unnamed_2087' : [ 0xc, { 'Raw' : [ 0x0, ['__unnamed_2085']], 'Translated' : [ 0x0, ['__unnamed_2083']], } ], '__unnamed_2089' : [ 0xc, { 'Channel' : [ 0x0, ['unsigned long']], 'Port' : [ 0x4, ['unsigned long']], 'Reserved1' : [ 0x8, ['unsigned long']], } ], '__unnamed_208b' : [ 0xc, { 'Channel' : [ 0x0, ['unsigned long']], 'RequestLine' : [ 0x4, ['unsigned long']], 'TransferWidth' : [ 0x8, ['unsigned char']], 'Reserved1' : [ 0x9, ['unsigned char']], 'Reserved2' : [ 0xa, ['unsigned char']], 'Reserved3' : [ 0xb, ['unsigned char']], } ], '__unnamed_208d' : [ 0xc, { 'Start' : [ 0x0, ['unsigned long']], 'Length' : [ 0x4, ['unsigned long']], 'Reserved' : [ 0x8, ['unsigned long']], } ], '__unnamed_208f' : [ 0xc, { 'DataSize' : [ 0x0, ['unsigned long']], 'Reserved1' : [ 0x4, ['unsigned long']], 'Reserved2' : [ 0x8, ['unsigned long']], } ], '__unnamed_2091' : [ 0xc, { 'Start' : [ 0x0, ['_LARGE_INTEGER']], 'Length40' : [ 0x8, ['unsigned long']], } ], '__unnamed_2093' : [ 0xc, { 'Start' : [ 0x0, ['_LARGE_INTEGER']], 'Length48' : [ 0x8, ['unsigned long']], } ], '__unnamed_2095' : [ 0xc, { 'Start' : [ 0x0, ['_LARGE_INTEGER']], 'Length64' : [ 0x8, ['unsigned long']], } ], '__unnamed_2097' : [ 0xc, { 'Generic' : [ 0x0, ['__unnamed_2081']], 'Port' : [ 0x0, ['__unnamed_2081']], 'Interrupt' : [ 0x0, ['__unnamed_2083']], 'MessageInterrupt' : [ 0x0, ['__unnamed_2087']], 'Memory' : [ 0x0, ['__unnamed_2081']], 'Dma' : [ 0x0, ['__unnamed_2089']], 'DmaV3' : [ 0x0, ['__unnamed_208b']], 'DevicePrivate' : [ 0x0, ['__unnamed_1f36']], 'BusNumber' : [ 0x0, ['__unnamed_208d']], 'DeviceSpecificData' : [ 0x0, ['__unnamed_208f']], 'Memory40' : [ 0x0, ['__unnamed_2091']], 'Memory48' : [ 0x0, ['__unnamed_2093']], 'Memory64' : [ 0x0, ['__unnamed_2095']], 'Connection' : [ 0x0, ['__unnamed_1f42']], } ], '_CM_PARTIAL_RESOURCE_DESCRIPTOR' : [ 0x10, { 'Type' : [ 0x0, ['unsigned char']], 'ShareDisposition' : [ 0x1, ['unsigned char']], 'Flags' : [ 0x2, ['unsigned short']], 'u' : [ 0x4, ['__unnamed_2097']], } ], '_OBJECT_HEADER_PADDING_INFO' : [ 0x4, { 'PaddingAmount' : [ 0x0, ['unsigned long']], } ], '__unnamed_209f' : [ 0x4, { 'PhysicalAddress' : [ 0x0, ['unsigned long']], 'VirtualSize' : [ 0x0, ['unsigned long']], } ], '_IMAGE_SECTION_HEADER' : [ 0x28, { 'Name' : [ 0x0, ['array', 8, ['unsigned char']]], 'Misc' : [ 0x8, ['__unnamed_209f']], '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']], } ], '_ARBITER_ADD_RESERVED_PARAMETERS' : [ 0x4, { 'ReserveDevice' : [ 0x0, ['pointer', ['_DEVICE_OBJECT']]], } ], '__unnamed_20a9' : [ 0x50, { 'CellData' : [ 0x0, ['_CELL_DATA']], 'List' : [ 0x0, ['array', 1, ['unsigned long']]], } ], '_CM_CACHED_VALUE_INDEX' : [ 0x54, { 'CellIndex' : [ 0x0, ['unsigned long']], 'Data' : [ 0x4, ['__unnamed_20a9']], } ], '_DBGKD_QUERY_SPECIAL_CALLS' : [ 0x4, { 'NumberOfSpecialCalls' : [ 0x0, ['unsigned long']], } ], '_VF_AVL_TREE_NODE' : [ 0x8, { 'p' : [ 0x0, ['pointer', ['void']]], 'RangeSize' : [ 0x4, ['unsigned long']], } ], '_POP_FX_DEVICE' : [ 0x108, { 'Link' : [ 0x0, ['_LIST_ENTRY']], 'Plugin' : [ 0x8, ['pointer', ['_POP_FX_PLUGIN']]], 'PluginHandle' : [ 0xc, ['pointer', ['PEPHANDLE__']]], 'MiniPlugin' : [ 0x10, ['pointer', ['_POP_FX_PLUGIN']]], 'MiniPluginHandle' : [ 0x14, ['pointer', ['PEPHANDLE__']]], 'DevNode' : [ 0x18, ['pointer', ['_DEVICE_NODE']]], 'DeviceObject' : [ 0x1c, ['pointer', ['_DEVICE_OBJECT']]], 'TargetDevice' : [ 0x20, ['pointer', ['_DEVICE_OBJECT']]], 'Callbacks' : [ 0x24, ['_POP_FX_DRIVER_CALLBACKS']], 'DriverContext' : [ 0x40, ['pointer', ['void']]], 'RemoveLock' : [ 0x44, ['_IO_REMOVE_LOCK']], 'WorkOrder' : [ 0x5c, ['_POP_FX_WORK_ORDER']], 'Status' : [ 0x70, ['_POP_FX_DEVICE_STATUS']], 'PowerReqCall' : [ 0x74, ['long']], 'PowerNotReqCall' : [ 0x78, ['long']], 'IdleLock' : [ 0x7c, ['unsigned long']], 'IdleTimer' : [ 0x80, ['_KTIMER']], 'IdleDpc' : [ 0xa8, ['_KDPC']], 'IdleTimeout' : [ 0xc8, ['unsigned long long']], 'IdleStamp' : [ 0xd0, ['unsigned long long']], 'Irp' : [ 0xd8, ['pointer', ['_IRP']]], 'IrpData' : [ 0xdc, ['pointer', ['_POP_IRP_DATA']]], 'NextIrpDeviceObject' : [ 0xe0, ['pointer', ['_DEVICE_OBJECT']]], 'NextIrpPowerState' : [ 0xe4, ['_POWER_STATE']], 'NextIrpCallerCompletion' : [ 0xe8, ['pointer', ['void']]], 'NextIrpCallerContext' : [ 0xec, ['pointer', ['void']]], 'IrpCompleteEvent' : [ 0xf0, ['_KEVENT']], 'ComponentCount' : [ 0x100, ['unsigned long']], 'Components' : [ 0x104, ['array', 1, ['pointer', ['_POP_FX_COMPONENT']]]], } ], '__unnamed_20bc' : [ 0x8, { 'IdleTime' : [ 0x0, ['unsigned long']], 'NonIdleTime' : [ 0x4, ['unsigned long']], } ], '__unnamed_20be' : [ 0x8, { 'Disk' : [ 0x0, ['__unnamed_20bc']], } ], '_DEVICE_OBJECT_POWER_EXTENSION' : [ 0x40, { 'IdleCount' : [ 0x0, ['unsigned long']], 'BusyCount' : [ 0x4, ['unsigned long']], 'BusyReference' : [ 0x8, ['unsigned long']], 'TotalBusyCount' : [ 0xc, ['unsigned long']], 'ConservationIdleTime' : [ 0x10, ['unsigned long']], 'PerformanceIdleTime' : [ 0x14, ['unsigned long']], 'DeviceObject' : [ 0x18, ['pointer', ['_DEVICE_OBJECT']]], 'IdleList' : [ 0x1c, ['_LIST_ENTRY']], 'IdleType' : [ 0x24, ['Enumeration', dict(target = 'long', choices = {0: 'DeviceIdleNormal', 1: 'DeviceIdleDisk'})]], 'IdleState' : [ 0x28, ['Enumeration', dict(target = 'long', choices = {0: 'PowerDeviceUnspecified', 1: 'PowerDeviceD0', 2: 'PowerDeviceD1', 3: 'PowerDeviceD2', 4: 'PowerDeviceD3', 5: 'PowerDeviceMaximum'})]], 'CurrentState' : [ 0x2c, ['Enumeration', dict(target = 'long', choices = {0: 'PowerDeviceUnspecified', 1: 'PowerDeviceD0', 2: 'PowerDeviceD1', 3: 'PowerDeviceD2', 4: 'PowerDeviceD3', 5: 'PowerDeviceMaximum'})]], 'Volume' : [ 0x30, ['_LIST_ENTRY']], 'Specific' : [ 0x38, ['__unnamed_20be']], } ], '_ARBITER_RETEST_ALLOCATION_PARAMETERS' : [ 0xc, { 'ArbitrationList' : [ 0x0, ['pointer', ['_LIST_ENTRY']]], 'AllocateFromCount' : [ 0x4, ['unsigned long']], 'AllocateFrom' : [ 0x8, ['pointer', ['_CM_PARTIAL_RESOURCE_DESCRIPTOR']]], } ], '_MI_TRIAGE_DUMP_DATA' : [ 0x1c, { 'BadPageCount' : [ 0x0, ['unsigned long']], 'BadPagesDetected' : [ 0x4, ['long']], 'ZeroedPageSingleBitErrorsDetected' : [ 0x8, ['long']], 'ScrubPasses' : [ 0xc, ['long']], 'ScrubBadPagesFound' : [ 0x10, ['long']], 'FeatureBits' : [ 0x14, ['unsigned long']], 'TimeZoneId' : [ 0x18, ['unsigned long']], } ], '_WHEA_ERROR_RECORD_SECTION_DESCRIPTOR_VALIDBITS' : [ 0x1, { 'FRUId' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned char')]], 'FRUText' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned char')]], 'Reserved' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 8, native_type='unsigned char')]], 'AsUCHAR' : [ 0x0, ['unsigned char']], } ], '_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']]], } ], '_KENLISTMENT' : [ 0x168, { 'cookie' : [ 0x0, ['unsigned long']], 'NamespaceLink' : [ 0x4, ['_KTMOBJECT_NAMESPACE_LINK']], 'EnlistmentId' : [ 0x18, ['_GUID']], 'Mutex' : [ 0x28, ['_KMUTANT']], 'NextSameTx' : [ 0x48, ['_LIST_ENTRY']], 'NextSameRm' : [ 0x50, ['_LIST_ENTRY']], 'ResourceManager' : [ 0x58, ['pointer', ['_KRESOURCEMANAGER']]], 'Transaction' : [ 0x5c, ['pointer', ['_KTRANSACTION']]], 'State' : [ 0x60, ['Enumeration', dict(target = 'long', choices = {0: 'KEnlistmentUninitialized', 256: 'KEnlistmentActive', 258: 'KEnlistmentPrepared', 259: 'KEnlistmentInDoubt', 260: 'KEnlistmentCommitted', 261: 'KEnlistmentCommittedNotify', 262: 'KEnlistmentCommitRequested', 257: 'KEnlistmentPreparing', 264: 'KEnlistmentDelegated', 265: 'KEnlistmentDelegatedDisconnected', 266: 'KEnlistmentPrePreparing', 263: 'KEnlistmentAborted', 268: 'KEnlistmentRecovering', 269: 'KEnlistmentAborting', 270: 'KEnlistmentReadOnly', 271: 'KEnlistmentOutcomeUnavailable', 272: 'KEnlistmentOffline', 273: 'KEnlistmentPrePrepared', 274: 'KEnlistmentInitialized', 267: 'KEnlistmentForgotten'})]], 'Flags' : [ 0x64, ['unsigned long']], 'NotificationMask' : [ 0x68, ['unsigned long']], 'Key' : [ 0x6c, ['pointer', ['void']]], 'KeyRefCount' : [ 0x70, ['unsigned long']], 'RecoveryInformation' : [ 0x74, ['pointer', ['void']]], 'RecoveryInformationLength' : [ 0x78, ['unsigned long']], 'DynamicNameInformation' : [ 0x7c, ['pointer', ['void']]], 'DynamicNameInformationLength' : [ 0x80, ['unsigned long']], 'FinalNotification' : [ 0x84, ['pointer', ['_KTMNOTIFICATION_PACKET']]], 'SupSubEnlistment' : [ 0x88, ['pointer', ['_KENLISTMENT']]], 'SupSubEnlHandle' : [ 0x8c, ['pointer', ['void']]], 'SubordinateTxHandle' : [ 0x90, ['pointer', ['void']]], 'CrmEnlistmentEnId' : [ 0x94, ['_GUID']], 'CrmEnlistmentTmId' : [ 0xa4, ['_GUID']], 'CrmEnlistmentRmId' : [ 0xb4, ['_GUID']], 'NextHistory' : [ 0xc4, ['unsigned long']], 'History' : [ 0xc8, ['array', 20, ['_KENLISTMENT_HISTORY']]], } ], '_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']], } ], '_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']], } ], '_IA64_DBGKD_CONTROL_SET' : [ 0x14, { 'Continue' : [ 0x0, ['unsigned long']], 'CurrentSymbolStart' : [ 0x4, ['unsigned long long']], 'CurrentSymbolEnd' : [ 0xc, ['unsigned long long']], } ], '_DEVICE_RELATIONS' : [ 0x8, { 'Count' : [ 0x0, ['unsigned long']], 'Objects' : [ 0x4, ['array', 1, ['pointer', ['_DEVICE_OBJECT']]]], } ], '_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']], } ], '_ALPC_COMPLETION_LIST_HEADER' : [ 0x180, { 'StartMagic' : [ 0x0, ['unsigned long long']], 'TotalSize' : [ 0x8, ['unsigned long']], 'ListOffset' : [ 0xc, ['unsigned long']], 'ListSize' : [ 0x10, ['unsigned long']], 'BitmapOffset' : [ 0x14, ['unsigned long']], 'BitmapSize' : [ 0x18, ['unsigned long']], 'DataOffset' : [ 0x1c, ['unsigned long']], 'DataSize' : [ 0x20, ['unsigned long']], 'AttributeFlags' : [ 0x24, ['unsigned long']], 'AttributeSize' : [ 0x28, ['unsigned long']], 'State' : [ 0x40, ['_ALPC_COMPLETION_LIST_STATE']], 'LastMessageId' : [ 0x48, ['unsigned long']], 'LastCallbackId' : [ 0x4c, ['unsigned long']], 'PostCount' : [ 0x80, ['unsigned long']], 'ReturnCount' : [ 0xc0, ['unsigned long']], 'LogSequenceNumber' : [ 0x100, ['unsigned long']], 'UserLock' : [ 0x140, ['_RTL_SRWLOCK']], 'EndMagic' : [ 0x148, ['unsigned long 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']], } ], '_WHEA_AER_ENDPOINT_DESCRIPTOR' : [ 0x20, { 'Type' : [ 0x0, ['unsigned short']], 'Enabled' : [ 0x2, ['unsigned char']], 'Reserved' : [ 0x3, ['unsigned char']], 'BusNumber' : [ 0x4, ['unsigned long']], 'Slot' : [ 0x8, ['_WHEA_PCI_SLOT_NUMBER']], 'DeviceControl' : [ 0xc, ['unsigned short']], 'Flags' : [ 0xe, ['_AER_ENDPOINT_DESCRIPTOR_FLAGS']], 'UncorrectableErrorMask' : [ 0x10, ['unsigned long']], 'UncorrectableErrorSeverity' : [ 0x14, ['unsigned long']], 'CorrectableErrorMask' : [ 0x18, ['unsigned long']], 'AdvancedCapsAndControl' : [ 0x1c, ['unsigned long']], } ], '_ETW_WMITRACE_WORK' : [ 0xf0, { 'LoggerId' : [ 0x0, ['unsigned long']], 'SpareUlong' : [ 0x4, ['unsigned long']], 'LoggerName' : [ 0x8, ['array', 65, ['unsigned char']]], 'FileName' : [ 0x49, ['array', 129, ['unsigned char']]], 'MaximumFileSize' : [ 0xcc, ['unsigned long']], 'MinBuffers' : [ 0xd0, ['unsigned long']], 'MaxBuffers' : [ 0xd4, ['unsigned long']], 'BufferSize' : [ 0xd8, ['unsigned long']], 'Mode' : [ 0xdc, ['unsigned long']], 'FlushTimer' : [ 0xe0, ['unsigned long']], 'MatchAny' : [ 0x8, ['unsigned long long']], 'MatchAll' : [ 0x10, ['unsigned long long']], 'EnableProperty' : [ 0x18, ['unsigned long']], 'Guid' : [ 0x1c, ['_GUID']], 'Level' : [ 0x2c, ['unsigned char']], 'Status' : [ 0xe8, ['long']], } ], '_DEVICE_MAP' : [ 0x34, { 'DosDevicesDirectory' : [ 0x0, ['pointer', ['_OBJECT_DIRECTORY']]], 'GlobalDosDevicesDirectory' : [ 0x4, ['pointer', ['_OBJECT_DIRECTORY']]], 'DosDevicesDirectoryHandle' : [ 0x8, ['pointer', ['void']]], 'ReferenceCount' : [ 0xc, ['unsigned long']], 'DriveMap' : [ 0x10, ['unsigned long']], 'DriveType' : [ 0x14, ['array', 32, ['unsigned char']]], } ], '_CHILD_LIST' : [ 0x8, { 'Count' : [ 0x0, ['unsigned long']], 'List' : [ 0x4, ['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']]], } ], '_ARMCE_DBGKD_CONTROL_SET' : [ 0xc, { 'Continue' : [ 0x0, ['unsigned long']], 'CurrentSymbolStart' : [ 0x4, ['unsigned long']], 'CurrentSymbolEnd' : [ 0x8, ['unsigned long']], } ], '_WHEA_ERROR_RECORD_HEADER_FLAGS' : [ 0x4, { 'Recovered' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]], 'PreviousError' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]], 'Simulated' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]], 'Reserved' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 32, native_type='unsigned long')]], 'AsULONG' : [ 0x0, ['unsigned long']], } ], '_XSAVE_AREA_HEADER' : [ 0x40, { 'Mask' : [ 0x0, ['unsigned long long']], 'Reserved' : [ 0x8, ['array', 7, ['unsigned long long']]], } ], '_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']], } ], '_PNP_DEVICE_COMPLETION_REQUEST' : [ 0x24, { 'ListEntry' : [ 0x0, ['_LIST_ENTRY']], 'DeviceNode' : [ 0x8, ['pointer', ['_DEVICE_NODE']]], 'Context' : [ 0xc, ['pointer', ['void']]], 'CompletionState' : [ 0x10, ['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', 789: 'MaxDeviceNodeState'})]], 'IrpPended' : [ 0x14, ['unsigned long']], 'Status' : [ 0x18, ['long']], 'Information' : [ 0x1c, ['pointer', ['void']]], 'ReferenceCount' : [ 0x20, ['long']], } ], '_KTRAP_FRAME' : [ 0x8c, { 'DbgEbp' : [ 0x0, ['unsigned long']], 'DbgEip' : [ 0x4, ['unsigned long']], 'DbgArgMark' : [ 0x8, ['unsigned long']], 'DbgArgPointer' : [ 0xc, ['unsigned long']], 'TempSegCs' : [ 0x10, ['unsigned short']], 'Logging' : [ 0x12, ['unsigned char']], 'FrameType' : [ 0x13, ['unsigned char']], '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 char']], 'EntropyQueueDpc' : [ 0x49, ['unsigned char']], 'Reserved' : [ 0x4a, ['array', 2, ['unsigned char']]], '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_2122' : [ 0x4, { 'LongFlags' : [ 0x0, ['unsigned long']], 'VadFlags' : [ 0x0, ['_MMVAD_FLAGS']], } ], '__unnamed_2125' : [ 0x4, { 'LongFlags1' : [ 0x0, ['unsigned long']], 'VadFlags1' : [ 0x0, ['_MMVAD_FLAGS1']], } ], '_MMVAD_SHORT' : [ 0x28, { 'VadNode' : [ 0x0, ['_MM_AVL_NODE']], 'StartingVpn' : [ 0xc, ['unsigned long']], 'EndingVpn' : [ 0x10, ['unsigned long']], 'PushLock' : [ 0x14, ['_EX_PUSH_LOCK']], 'u' : [ 0x18, ['__unnamed_2122']], 'u1' : [ 0x1c, ['__unnamed_2125']], 'EventList' : [ 0x20, ['pointer', ['_MI_VAD_EVENT_BLOCK']]], 'ReferenceCount' : [ 0x24, ['long']], } ], '_WAIT_CONTEXT_BLOCK' : [ 0x28, { 'WaitQueueEntry' : [ 0x0, ['_KDEVICE_QUEUE_ENTRY']], 'DmaWaitEntry' : [ 0x0, ['_LIST_ENTRY']], 'NumberOfChannels' : [ 0x8, ['unsigned long']], 'SyncCallback' : [ 0xc, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]], 'DmaContext' : [ 0xc, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]], 'Reserved' : [ 0xc, ['BitField', dict(start_bit = 2, end_bit = 32, native_type='unsigned long')]], 'DeviceRoutine' : [ 0x10, ['pointer', ['void']]], 'DeviceContext' : [ 0x14, ['pointer', ['void']]], 'NumberOfMapRegisters' : [ 0x18, ['unsigned long']], 'DeviceObject' : [ 0x1c, ['pointer', ['void']]], 'CurrentIrp' : [ 0x20, ['pointer', ['void']]], 'BufferChainingDpc' : [ 0x24, ['pointer', ['_KDPC']]], } ], '_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']]], } ], '_CM_NAME_CONTROL_BLOCK' : [ 0x10, { 'Compressed' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]], 'RefCount' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 32, native_type='unsigned long')]], 'NameHash' : [ 0x4, ['_CM_NAME_HASH']], 'ConvKey' : [ 0x4, ['unsigned long']], 'NextHash' : [ 0x8, ['pointer', ['_CM_KEY_HASH']]], 'NameLength' : [ 0xc, ['unsigned short']], 'Name' : [ 0xe, ['array', 1, ['wchar']]], } ], '_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, ['wchar']]], } ], '_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']]], 'RmId' : [ 0x70, ['_GUID']], 'LogId' : [ 0x80, ['_GUID']], 'Flags' : [ 0x90, ['unsigned long']], 'TmId' : [ 0x94, ['_GUID']], 'GuidSignature' : [ 0xa4, ['unsigned long']], 'LastReorganizeTime' : [ 0xa8, ['unsigned long long']], 'Reserved1' : [ 0xb0, ['array', 83, ['unsigned long']]], 'CheckSum' : [ 0x1fc, ['unsigned long']], 'Reserved2' : [ 0x200, ['array', 882, ['unsigned long']]], 'ThawTmId' : [ 0xfc8, ['_GUID']], 'ThawRmId' : [ 0xfd8, ['_GUID']], 'ThawLogId' : [ 0xfe8, ['_GUID']], 'BootType' : [ 0xff8, ['unsigned long']], 'BootRecover' : [ 0xffc, ['unsigned long']], } ], '_GENERAL_LOOKASIDE_POOL' : [ 0x48, { 'ListHead' : [ 0x0, ['_SLIST_HEADER']], 'SingleListHead' : [ 0x0, ['_SINGLE_LIST_ENTRY']], '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: 'NonPagedPoolBase', 1: 'PagedPool', 2: 'NonPagedPoolBaseMustSucceed', 3: 'DontUseThisType', 4: 'NonPagedPoolBaseCacheAligned', 5: 'PagedPoolCacheAligned', 6: 'NonPagedPoolBaseCacheAlignedMustS', 7: 'MaxPoolType', 34: 'NonPagedPoolMustSucceedSession', 516: 'NonPagedPoolNxCacheAligned', 35: 'DontUseThisTypeSession', 32: 'NonPagedPoolSession', 512: 'NonPagedPoolNx', 544: 'NonPagedPoolSessionNx', 36: 'NonPagedPoolCacheAlignedSession', 33: 'PagedPoolSession', 38: 'NonPagedPoolCacheAlignedMustSSession', 37: 'PagedPoolCacheAlignedSession'})]], 'Tag' : [ 0x20, ['unsigned long']], 'Size' : [ 0x24, ['unsigned long']], 'AllocateEx' : [ 0x28, ['pointer', ['void']]], 'Allocate' : [ 0x28, ['pointer', ['void']]], 'FreeEx' : [ 0x2c, ['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']]], } ], '_RTL_DYNAMIC_HASH_TABLE_ENTRY' : [ 0xc, { 'Linkage' : [ 0x0, ['_LIST_ENTRY']], 'Signature' : [ 0x8, ['unsigned long']], } ], '_M128A' : [ 0x10, { 'Low' : [ 0x0, ['unsigned long long']], 'High' : [ 0x8, ['long long']], } ], '_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']]], } ], '_KTIMER' : [ 0x28, { 'Header' : [ 0x0, ['_DISPATCHER_HEADER']], 'DueTime' : [ 0x10, ['_ULARGE_INTEGER']], 'TimerListEntry' : [ 0x18, ['_LIST_ENTRY']], 'Dpc' : [ 0x20, ['pointer', ['_KDPC']]], 'Period' : [ 0x24, ['unsigned long']], } ], '_RTL_ATOM_TABLE' : [ 0x1c, { 'Signature' : [ 0x0, ['unsigned long']], 'ReferenceCount' : [ 0x4, ['long']], 'PushLock' : [ 0x8, ['_EX_PUSH_LOCK']], 'ExHandleTable' : [ 0xc, ['pointer', ['_HANDLE_TABLE']]], 'Flags' : [ 0x10, ['unsigned long']], 'NumberOfBuckets' : [ 0x14, ['unsigned long']], 'Buckets' : [ 0x18, ['array', 1, ['pointer', ['_RTL_ATOM_TABLE_ENTRY']]]], } ], '__unnamed_2162' : [ 0x10, { 'ProgrammedTime' : [ 0x0, ['unsigned long long']], 'TimerInfo' : [ 0x8, ['pointer', ['_DIAGNOSTIC_BUFFER']]], } ], '_POP_POWER_ACTION' : [ 0xd8, { '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']], 'DeviceType' : [ 0x14, ['Enumeration', dict(target = 'long', choices = {0: 'PolicyDeviceSystemButton', 1: 'PolicyDeviceThermalZone', 2: 'PolicyDeviceBattery', 3: 'PolicyDeviceMemory', 4: 'PolicyInitiatePowerActionAPI', 5: 'PolicySetPowerStateAPI', 6: 'PolicyImmediateDozeS4', 7: 'PolicySystemIdle', 8: 'PolicyDeviceWakeAlarm', 9: 'PolicyDeviceMax'})]], 'DeviceTypeFlags' : [ 0x18, ['unsigned long']], 'IrpMinor' : [ 0x1c, ['unsigned char']], 'Waking' : [ 0x1d, ['unsigned char']], 'SystemState' : [ 0x20, ['Enumeration', dict(target = 'long', choices = {0: 'PowerSystemUnspecified', 1: 'PowerSystemWorking', 2: 'PowerSystemSleeping1', 3: 'PowerSystemSleeping2', 4: 'PowerSystemSleeping3', 5: 'PowerSystemHibernate', 6: 'PowerSystemShutdown', 7: 'PowerSystemMaximum'})]], 'NextSystemState' : [ 0x24, ['Enumeration', dict(target = 'long', choices = {0: 'PowerSystemUnspecified', 1: 'PowerSystemWorking', 2: 'PowerSystemSleeping1', 3: 'PowerSystemSleeping2', 4: 'PowerSystemSleeping3', 5: 'PowerSystemHibernate', 6: 'PowerSystemShutdown', 7: 'PowerSystemMaximum'})]], 'EffectiveSystemState' : [ 0x28, ['Enumeration', dict(target = 'long', choices = {0: 'PowerSystemUnspecified', 1: 'PowerSystemWorking', 2: 'PowerSystemSleeping1', 3: 'PowerSystemSleeping2', 4: 'PowerSystemSleeping3', 5: 'PowerSystemHibernate', 6: 'PowerSystemShutdown', 7: 'PowerSystemMaximum'})]], 'CurrentSystemState' : [ 0x2c, ['Enumeration', dict(target = 'long', choices = {0: 'PowerSystemUnspecified', 1: 'PowerSystemWorking', 2: 'PowerSystemSleeping1', 3: 'PowerSystemSleeping2', 4: 'PowerSystemSleeping3', 5: 'PowerSystemHibernate', 6: 'PowerSystemShutdown', 7: 'PowerSystemMaximum'})]], 'ShutdownBugCode' : [ 0x30, ['pointer', ['_POP_SHUTDOWN_BUG_CHECK']]], 'DevState' : [ 0x34, ['pointer', ['_POP_DEVICE_SYS_STATE']]], 'HiberContext' : [ 0x38, ['pointer', ['_POP_HIBER_CONTEXT']]], 'WakeTime' : [ 0x40, ['unsigned long long']], 'SleepTime' : [ 0x48, ['unsigned long long']], 'WakeAlarmSignaled' : [ 0x50, ['Enumeration', dict(target = 'long', choices = {0: 'PoAc', 1: 'PoDc', 2: 'PoHot', 3: 'PoConditionMaximum'})]], 'WakeAlarm' : [ 0x58, ['array', 3, ['__unnamed_2162']]], 'FilteredCapabilities' : [ 0x88, ['SYSTEM_POWER_CAPABILITIES']], } ], '_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, ['wchar']]], } ], '_CM_KEY_HASH' : [ 0x10, { 'ConvKey' : [ 0x0, ['unsigned long']], 'NextHash' : [ 0x4, ['pointer', ['_CM_KEY_HASH']]], 'KeyHive' : [ 0x8, ['pointer', ['_HHIVE']]], 'KeyCell' : [ 0xc, ['unsigned long']], } ], '_WHEA_IPF_CMC_DESCRIPTOR' : [ 0x4, { 'Type' : [ 0x0, ['unsigned short']], 'Enabled' : [ 0x2, ['unsigned char']], 'Reserved' : [ 0x3, ['unsigned char']], } ], '_PROCESSOR_IDLE_DEPENDENCY' : [ 0x6, { 'Processor' : [ 0x0, ['_PROCESSOR_NUMBER']], 'ExpectedState' : [ 0x4, ['unsigned char']], } ], '_AMD64_DBGKD_CONTROL_SET' : [ 0x1c, { 'TraceFlag' : [ 0x0, ['unsigned long']], 'Dr7' : [ 0x4, ['unsigned long long']], 'CurrentSymbolStart' : [ 0xc, ['unsigned long long']], 'CurrentSymbolEnd' : [ 0x14, ['unsigned long long']], } ], '_PO_DEVICE_NOTIFY' : [ 0x3c, { 'Link' : [ 0x0, ['_LIST_ENTRY']], 'PowerChildren' : [ 0x8, ['_LIST_ENTRY']], 'PowerParents' : [ 0x10, ['_LIST_ENTRY']], 'TargetDevice' : [ 0x18, ['pointer', ['_DEVICE_OBJECT']]], 'OrderLevel' : [ 0x1c, ['unsigned char']], 'DeviceObject' : [ 0x20, ['pointer', ['_DEVICE_OBJECT']]], 'DeviceName' : [ 0x24, ['pointer', ['unsigned short']]], 'DriverName' : [ 0x28, ['pointer', ['unsigned short']]], 'ChildCount' : [ 0x2c, ['unsigned long']], 'ActiveChild' : [ 0x30, ['unsigned long']], 'ParentCount' : [ 0x34, ['unsigned long']], 'ActiveParent' : [ 0x38, ['unsigned long']], } ], '_CM_KEY_SECURITY_CACHE_ENTRY' : [ 0x8, { 'Cell' : [ 0x0, ['unsigned long']], 'CachedSecurity' : [ 0x4, ['pointer', ['_CM_KEY_SECURITY_CACHE']]], } ], '_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']], } ], '_GDI_TEB_BATCH32' : [ 0x4e0, { 'Offset' : [ 0x0, ['unsigned long']], 'HDC' : [ 0x4, ['unsigned long']], 'Buffer' : [ 0x8, ['array', 310, ['unsigned long']]], } ], '_WHEA_AER_ROOTPORT_DESCRIPTOR' : [ 0x24, { 'Type' : [ 0x0, ['unsigned short']], 'Enabled' : [ 0x2, ['unsigned char']], 'Reserved' : [ 0x3, ['unsigned char']], 'BusNumber' : [ 0x4, ['unsigned long']], 'Slot' : [ 0x8, ['_WHEA_PCI_SLOT_NUMBER']], 'DeviceControl' : [ 0xc, ['unsigned short']], 'Flags' : [ 0xe, ['_AER_ROOTPORT_DESCRIPTOR_FLAGS']], 'UncorrectableErrorMask' : [ 0x10, ['unsigned long']], 'UncorrectableErrorSeverity' : [ 0x14, ['unsigned long']], 'CorrectableErrorMask' : [ 0x18, ['unsigned long']], 'AdvancedCapsAndControl' : [ 0x1c, ['unsigned long']], 'RootErrorCommand' : [ 0x20, ['unsigned long']], } ], '_PROC_IDLE_STATE_ACCOUNTING' : [ 0x368, { 'TotalTime' : [ 0x0, ['unsigned long long']], 'CancelCount' : [ 0x8, ['unsigned long']], 'FailureCount' : [ 0xc, ['unsigned long']], 'SuccessCount' : [ 0x10, ['unsigned long']], 'InvalidBucketIndex' : [ 0x14, ['unsigned long']], 'MinTime' : [ 0x18, ['unsigned long long']], 'MaxTime' : [ 0x20, ['unsigned long long']], 'IdleTimeBuckets' : [ 0x28, ['array', 26, ['_PROC_IDLE_STATE_BUCKET']]], } ], '_IMAGE_SECURITY_CONTEXT' : [ 0x4, { 'PageHashes' : [ 0x0, ['pointer', ['void']]], 'Value' : [ 0x0, ['unsigned long']], 'SecurityBeingCreated' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 2, native_type='unsigned long')]], 'SecurityMandatory' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]], 'PageHashPointer' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 32, native_type='unsigned long')]], } ], '__unnamed_2189' : [ 0x4, { 'Level' : [ 0x0, ['unsigned long']], } ], '__unnamed_218b' : [ 0x4, { 'Type' : [ 0x0, ['unsigned long']], } ], '_POP_ACTION_TRIGGER' : [ 0x10, { 'Type' : [ 0x0, ['Enumeration', dict(target = 'long', choices = {0: 'PolicyDeviceSystemButton', 1: 'PolicyDeviceThermalZone', 2: 'PolicyDeviceBattery', 3: 'PolicyDeviceMemory', 4: 'PolicyInitiatePowerActionAPI', 5: 'PolicySetPowerStateAPI', 6: 'PolicyImmediateDozeS4', 7: 'PolicySystemIdle', 8: 'PolicyDeviceWakeAlarm', 9: 'PolicyDeviceMax'})]], 'Flags' : [ 0x4, ['unsigned long']], 'Wait' : [ 0x8, ['pointer', ['_POP_TRIGGER_WAIT']]], 'Battery' : [ 0xc, ['__unnamed_2189']], 'Button' : [ 0xc, ['__unnamed_218b']], } ], '_KENLISTMENT_HISTORY' : [ 0x8, { 'Notification' : [ 0x0, ['unsigned long']], 'NewState' : [ 0x4, ['Enumeration', dict(target = 'long', choices = {0: 'KEnlistmentUninitialized', 256: 'KEnlistmentActive', 258: 'KEnlistmentPrepared', 259: 'KEnlistmentInDoubt', 260: 'KEnlistmentCommitted', 261: 'KEnlistmentCommittedNotify', 262: 'KEnlistmentCommitRequested', 257: 'KEnlistmentPreparing', 264: 'KEnlistmentDelegated', 265: 'KEnlistmentDelegatedDisconnected', 266: 'KEnlistmentPrePreparing', 263: 'KEnlistmentAborted', 268: 'KEnlistmentRecovering', 269: 'KEnlistmentAborting', 270: 'KEnlistmentReadOnly', 271: 'KEnlistmentOutcomeUnavailable', 272: 'KEnlistmentOffline', 273: 'KEnlistmentPrePrepared', 274: 'KEnlistmentInitialized', 267: 'KEnlistmentForgotten'})]], } ], '_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']]], } ], '_CM_CELL_REMAP_BLOCK' : [ 0x8, { 'OldCell' : [ 0x0, ['unsigned long']], 'NewCell' : [ 0x4, ['unsigned long']], } ], '_PI_RESOURCE_ARBITER_ENTRY' : [ 0x38, { 'DeviceArbiterList' : [ 0x0, ['_LIST_ENTRY']], 'ResourceType' : [ 0x8, ['unsigned char']], 'ArbiterInterface' : [ 0xc, ['pointer', ['_ARBITER_INTERFACE']]], 'DeviceNode' : [ 0x10, ['pointer', ['_DEVICE_NODE']]], 'ResourceList' : [ 0x14, ['_LIST_ENTRY']], 'BestResourceList' : [ 0x1c, ['_LIST_ENTRY']], 'BestConfig' : [ 0x24, ['_LIST_ENTRY']], 'ActiveArbiterList' : [ 0x2c, ['_LIST_ENTRY']], 'State' : [ 0x34, ['unsigned char']], 'ResourcesChanged' : [ 0x35, ['unsigned char']], } ], '_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']]], } ], '_MODWRITER_FLAGS' : [ 0x4, { 'KeepForever' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]], 'Networked' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]], 'IoPriority' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 5, native_type='unsigned long')]], } ], '_RTL_USER_PROCESS_PARAMETERS' : [ 0x2a0, { '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']]], 'EnvironmentSize' : [ 0x290, ['unsigned long']], 'EnvironmentVersion' : [ 0x294, ['unsigned long']], 'PackageDependencyData' : [ 0x298, ['pointer', ['void']]], 'ProcessGroupId' : [ 0x29c, ['unsigned long']], } ], '_PHYSICAL_MEMORY_RUN' : [ 0x8, { 'BasePage' : [ 0x0, ['unsigned long']], 'PageCount' : [ 0x4, ['unsigned long']], } ], '_RTL_SRWLOCK' : [ 0x4, { 'Locked' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]], 'Waiting' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]], 'Waking' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]], 'MultipleShared' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned long')]], 'Shared' : [ 0x0, ['BitField', dict(start_bit = 4, end_bit = 32, native_type='unsigned long')]], 'Value' : [ 0x0, ['unsigned long']], 'Ptr' : [ 0x0, ['pointer', ['void']]], } ], '_ALPC_MESSAGE_ZONE' : [ 0x18, { 'Mdl' : [ 0x0, ['pointer', ['_MDL']]], 'UserVa' : [ 0x4, ['pointer', ['void']]], 'UserLimit' : [ 0x8, ['pointer', ['void']]], 'SystemVa' : [ 0xc, ['pointer', ['void']]], 'SystemLimit' : [ 0x10, ['pointer', ['void']]], 'Size' : [ 0x14, ['unsigned long']], } ], '_KTMOBJECT_NAMESPACE_LINK' : [ 0x14, { 'Links' : [ 0x0, ['_RTL_BALANCED_LINKS']], 'Expired' : [ 0x10, ['unsigned char']], } ], '_CACHE_MANAGER_CALLBACKS' : [ 0x10, { 'AcquireForLazyWrite' : [ 0x0, ['pointer', ['void']]], 'ReleaseFromLazyWrite' : [ 0x4, ['pointer', ['void']]], 'AcquireForReadAhead' : [ 0x8, ['pointer', ['void']]], 'ReleaseFromReadAhead' : [ 0xc, ['pointer', ['void']]], } ], '_PROC_PERF_LOAD' : [ 0x2, { 'BusyPercentage' : [ 0x0, ['unsigned char']], 'FrequencyPercentage' : [ 0x1, ['unsigned char']], } ], '_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']], } ], '_WHEA_IPF_MCA_DESCRIPTOR' : [ 0x4, { 'Type' : [ 0x0, ['unsigned short']], 'Enabled' : [ 0x2, ['unsigned char']], 'Reserved' : [ 0x3, ['unsigned char']], } ], '_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']], } ], '_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']], 'PoolTag' : [ 0x4, ['unsigned long']], 'AllocatorBackTraceIndex' : [ 0x4, ['unsigned short']], 'PoolTagHash' : [ 0x6, ['unsigned short']], } ], '_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']], } ], '_VF_POOL_TRACE' : [ 0x40, { 'Address' : [ 0x0, ['pointer', ['void']]], 'Size' : [ 0x4, ['unsigned long']], 'Thread' : [ 0x8, ['pointer', ['_ETHREAD']]], 'StackTrace' : [ 0xc, ['array', 13, ['pointer', ['void']]]], } ], '__unnamed_220e' : [ 0x4, { 'LongFlags' : [ 0x0, ['unsigned long']], 'Flags' : [ 0x0, ['_MM_SESSION_SPACE_FLAGS']], } ], '_MM_SESSION_SPACE' : [ 0x1fc0, { 'ReferenceCount' : [ 0x0, ['long']], 'u' : [ 0x4, ['__unnamed_220e']], 'SessionId' : [ 0x8, ['unsigned long']], 'ProcessReferenceToSession' : [ 0xc, ['long']], 'ProcessList' : [ 0x10, ['_LIST_ENTRY']], 'SessionPageDirectoryIndex' : [ 0x18, ['unsigned long']], 'NonPagablePages' : [ 0x1c, ['unsigned long']], 'CommittedPages' : [ 0x20, ['unsigned long']], 'PagedPoolStart' : [ 0x24, ['pointer', ['void']]], 'PagedPoolEnd' : [ 0x28, ['pointer', ['void']]], 'SessionObject' : [ 0x2c, ['pointer', ['void']]], 'SessionObjectHandle' : [ 0x30, ['pointer', ['void']]], 'SessionPoolAllocationFailures' : [ 0x34, ['array', 4, ['unsigned long']]], 'ImageList' : [ 0x44, ['_LIST_ENTRY']], 'LocaleId' : [ 0x4c, ['unsigned long']], 'AttachCount' : [ 0x50, ['unsigned long']], 'AttachGate' : [ 0x54, ['_KGATE']], 'WsListEntry' : [ 0x64, ['_LIST_ENTRY']], 'Lookaside' : [ 0x80, ['array', 24, ['_GENERAL_LOOKASIDE']]], 'Session' : [ 0xc80, ['_MMSESSION']], 'PagedPoolInfo' : [ 0xcb8, ['_MM_PAGED_POOL_INFO']], 'Vm' : [ 0xcec, ['_MMSUPPORT']], 'Wsle' : [ 0xd5c, ['pointer', ['_MMWSLE']]], 'DriverUnload' : [ 0xd60, ['_MI_SESSION_DRIVER_UNLOAD']], 'PagedPool' : [ 0xd80, ['_POOL_DESCRIPTOR']], 'PageTables' : [ 0x1ec0, ['pointer', ['_MMPTE']]], 'SpecialPool' : [ 0x1ec8, ['_MI_SPECIAL_POOL']], 'SessionPteLock' : [ 0x1f10, ['_FAST_MUTEX']], 'PoolBigEntriesInUse' : [ 0x1f30, ['long']], 'PagedPoolPdeCount' : [ 0x1f34, ['unsigned long']], 'SpecialPoolPdeCount' : [ 0x1f38, ['unsigned long']], 'DynamicSessionPdeCount' : [ 0x1f3c, ['unsigned long']], 'SystemPteInfo' : [ 0x1f40, ['_MI_SYSTEM_PTE_TYPE']], 'PoolTrackTableExpansion' : [ 0x1f74, ['pointer', ['void']]], 'PoolTrackTableExpansionSize' : [ 0x1f78, ['unsigned long']], 'PoolTrackBigPages' : [ 0x1f7c, ['pointer', ['void']]], 'PoolTrackBigPagesSize' : [ 0x1f80, ['unsigned long']], 'IoState' : [ 0x1f84, ['Enumeration', dict(target = 'long', choices = {1: 'IoSessionStateCreated', 2: 'IoSessionStateInitialized', 3: 'IoSessionStateConnected', 4: 'IoSessionStateDisconnected', 5: 'IoSessionStateDisconnectedLoggedOn', 6: 'IoSessionStateLoggedOn', 7: 'IoSessionStateLoggedOff', 8: 'IoSessionStateTerminated', 9: 'IoSessionStateMax'})]], 'IoStateSequence' : [ 0x1f88, ['unsigned long']], 'IoNotificationEvent' : [ 0x1f8c, ['_KEVENT']], 'SessionPoolPdes' : [ 0x1f9c, ['_RTL_BITMAP']], } ], '_WHEA_XPF_MC_BANK_DESCRIPTOR' : [ 0x1c, { 'BankNumber' : [ 0x0, ['unsigned char']], 'ClearOnInitialization' : [ 0x1, ['unsigned char']], 'StatusDataFormat' : [ 0x2, ['unsigned char']], 'Flags' : [ 0x3, ['_XPF_MC_BANK_FLAGS']], 'ControlMsr' : [ 0x4, ['unsigned long']], 'StatusMsr' : [ 0x8, ['unsigned long']], 'AddressMsr' : [ 0xc, ['unsigned long']], 'MiscMsr' : [ 0x10, ['unsigned long']], 'ControlData' : [ 0x14, ['unsigned long long']], } ], '__unnamed_221e' : [ 0x4, { 'LongFlags2' : [ 0x0, ['unsigned long']], 'VadFlags2' : [ 0x0, ['_MMVAD_FLAGS2']], } ], '__unnamed_2223' : [ 0x4, { 'SequentialVa' : [ 0x0, ['_MI_VAD_SEQUENTIAL_INFO']], 'ExtendedInfo' : [ 0x0, ['pointer', ['_MMEXTEND_INFO']]], } ], '_MMVAD' : [ 0x48, { 'Core' : [ 0x0, ['_MMVAD_SHORT']], 'u2' : [ 0x28, ['__unnamed_221e']], 'Subsection' : [ 0x2c, ['pointer', ['_SUBSECTION']]], 'MappedSubsection' : [ 0x2c, ['pointer', ['_MSUBSECTION']]], 'FirstPrototypePte' : [ 0x30, ['pointer', ['_MMPTE']]], 'LastContiguousPte' : [ 0x34, ['pointer', ['_MMPTE']]], 'ViewLinks' : [ 0x38, ['_LIST_ENTRY']], 'VadsProcess' : [ 0x40, ['pointer', ['_EPROCESS']]], 'u4' : [ 0x44, ['__unnamed_2223']], } ], '_CM_RM' : [ 0x58, { 'RmListEntry' : [ 0x0, ['_LIST_ENTRY']], 'TransactionListHead' : [ 0x8, ['_LIST_ENTRY']], 'TmHandle' : [ 0x10, ['pointer', ['void']]], 'Tm' : [ 0x14, ['pointer', ['void']]], 'RmHandle' : [ 0x18, ['pointer', ['void']]], 'KtmRm' : [ 0x1c, ['pointer', ['void']]], 'RefCount' : [ 0x20, ['unsigned long']], 'ContainerNum' : [ 0x24, ['unsigned long']], 'ContainerSize' : [ 0x28, ['unsigned long long']], 'CmHive' : [ 0x30, ['pointer', ['_CMHIVE']]], 'LogFileObject' : [ 0x34, ['pointer', ['void']]], 'MarshallingContext' : [ 0x38, ['pointer', ['void']]], 'RmFlags' : [ 0x3c, ['unsigned long']], 'LogStartStatus1' : [ 0x40, ['long']], 'LogStartStatus2' : [ 0x44, ['long']], 'BaseLsn' : [ 0x48, ['unsigned long long']], 'RmLock' : [ 0x50, ['pointer', ['_ERESOURCE']]], } ], '_NONOPAQUE_OPLOCK' : [ 0x50, { 'IrpExclusiveOplock' : [ 0x0, ['pointer', ['_IRP']]], 'FileObject' : [ 0x4, ['pointer', ['_FILE_OBJECT']]], 'ExclusiveOplockOwner' : [ 0x8, ['pointer', ['_EPROCESS']]], 'ExclusiveOplockOwnerThread' : [ 0xc, ['pointer', ['_ETHREAD']]], 'WaiterPriority' : [ 0x10, ['unsigned char']], 'IrpOplocksR' : [ 0x14, ['_LIST_ENTRY']], 'IrpOplocksRH' : [ 0x1c, ['_LIST_ENTRY']], 'RHBreakQueue' : [ 0x24, ['_LIST_ENTRY']], 'WaitingIrps' : [ 0x2c, ['_LIST_ENTRY']], 'DelayAckFileObjectQueue' : [ 0x34, ['_LIST_ENTRY']], 'AtomicQueue' : [ 0x3c, ['_LIST_ENTRY']], 'DeleterParentKey' : [ 0x44, ['pointer', ['_GUID']]], 'OplockState' : [ 0x48, ['unsigned long']], 'FastMutex' : [ 0x4c, ['pointer', ['_FAST_MUTEX']]], } ], '_OBJECT_HANDLE_COUNT_ENTRY' : [ 0x8, { 'Process' : [ 0x0, ['pointer', ['_EPROCESS']]], 'HandleCount' : [ 0x4, ['BitField', dict(start_bit = 0, end_bit = 24, native_type='unsigned long')]], 'LockCount' : [ 0x4, ['BitField', dict(start_bit = 24, end_bit = 32, native_type='unsigned long')]], } ], '_CLIENT_ID' : [ 0x8, { 'UniqueProcess' : [ 0x0, ['pointer', ['void']]], 'UniqueThread' : [ 0x4, ['pointer', ['void']]], } ], '_WHEA_MEMORY_ERROR_SECTION' : [ 0x49, { 'ValidBits' : [ 0x0, ['_WHEA_MEMORY_ERROR_SECTION_VALIDBITS']], 'ErrorStatus' : [ 0x8, ['_WHEA_ERROR_STATUS']], 'PhysicalAddress' : [ 0x10, ['unsigned long long']], 'PhysicalAddressMask' : [ 0x18, ['unsigned long long']], 'Node' : [ 0x20, ['unsigned short']], 'Card' : [ 0x22, ['unsigned short']], 'Module' : [ 0x24, ['unsigned short']], 'Bank' : [ 0x26, ['unsigned short']], 'Device' : [ 0x28, ['unsigned short']], 'Row' : [ 0x2a, ['unsigned short']], 'Column' : [ 0x2c, ['unsigned short']], 'BitPosition' : [ 0x2e, ['unsigned short']], 'RequesterId' : [ 0x30, ['unsigned long long']], 'ResponderId' : [ 0x38, ['unsigned long long']], 'TargetId' : [ 0x40, ['unsigned long long']], 'ErrorType' : [ 0x48, ['unsigned char']], } ], '_KWAIT_STATUS_REGISTER' : [ 0x1, { 'Flags' : [ 0x0, ['unsigned char']], 'State' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 2, native_type='unsigned char')]], 'Affinity' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned char')]], 'Priority' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned char')]], 'Apc' : [ 0x0, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned char')]], 'UserApc' : [ 0x0, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned char')]], 'Alert' : [ 0x0, ['BitField', dict(start_bit = 6, end_bit = 7, native_type='unsigned char')]], 'Unused' : [ 0x0, ['BitField', dict(start_bit = 7, end_bit = 8, native_type='unsigned char')]], } ], '_VI_DEADLOCK_RESOURCE' : [ 0x80, { 'Type' : [ 0x0, ['Enumeration', dict(target = 'long', choices = {0: 'VfDeadlockUnknown', 1: 'VfDeadlockMutex', 2: 'VfDeadlockMutexAbandoned', 3: 'VfDeadlockFastMutex', 4: 'VfDeadlockFastMutexUnsafe', 5: 'VfDeadlockSpinLock', 6: 'VfDeadlockInStackQueuedSpinLock', 7: 'VfDeadlockUnusedSpinLock', 8: 'VfDeadlockEresource', 9: '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']]]], } ], '_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']], } ], '_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')]], 'AttemptingDelete' : [ 0x0, ['BitField', dict(start_bit = 8, end_bit = 9, native_type='unsigned long')]], 'PrefetchCreated' : [ 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')]], 'NoChange' : [ 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')]], 'PreferredNode' : [ 0x0, ['BitField', dict(start_bit = 20, end_bit = 26, native_type='unsigned long')]], 'GlobalOnlyPerSession' : [ 0x0, ['BitField', dict(start_bit = 26, end_bit = 27, native_type='unsigned long')]], 'UserWritable' : [ 0x0, ['BitField', dict(start_bit = 27, end_bit = 28, native_type='unsigned long')]], 'Spare' : [ 0x0, ['BitField', dict(start_bit = 28, end_bit = 32, native_type='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']], } ], '_MM_PAGED_POOL_INFO' : [ 0x34, { 'Mutex' : [ 0x0, ['_FAST_MUTEX']], 'PagedPoolAllocationMap' : [ 0x20, ['_RTL_BITMAP']], 'FirstPteForPagedPool' : [ 0x28, ['pointer', ['_MMPTE']]], 'PagedPoolHint' : [ 0x2c, ['unsigned long']], 'AllocatedPagedPool' : [ 0x30, ['unsigned long']], } ], '_MI_REVERSE_VIEW_MAP' : [ 0x18, { 'ViewLinks' : [ 0x0, ['_LIST_ENTRY']], 'SystemCacheVa' : [ 0x8, ['pointer', ['void']]], 'SessionViewVa' : [ 0x8, ['pointer', ['void']]], 'VadsProcess' : [ 0x8, ['pointer', ['_EPROCESS']]], 'Type' : [ 0x8, ['BitField', dict(start_bit = 0, end_bit = 2, native_type='unsigned long')]], 'Subsection' : [ 0xc, ['pointer', ['_SUBSECTION']]], 'SectionOffset' : [ 0x10, ['unsigned long long']], } ], '_IO_SECURITY_CONTEXT' : [ 0x10, { 'SecurityQos' : [ 0x0, ['pointer', ['_SECURITY_QUALITY_OF_SERVICE']]], 'AccessState' : [ 0x4, ['pointer', ['_ACCESS_STATE']]], 'DesiredAccess' : [ 0x8, ['unsigned long']], 'FullCreateOptions' : [ 0xc, ['unsigned long']], } ], '_PROC_PERF_DOMAIN' : [ 0x90, { 'Link' : [ 0x0, ['_LIST_ENTRY']], 'Master' : [ 0x8, ['pointer', ['_KPRCB']]], 'Members' : [ 0xc, ['_KAFFINITY_EX']], 'ProcessorCount' : [ 0x18, ['unsigned long']], 'Processors' : [ 0x1c, ['pointer', ['_PROC_PERF_CONSTRAINT']]], 'GetFFHThrottleState' : [ 0x20, ['pointer', ['void']]], 'BoostPolicyHandler' : [ 0x24, ['pointer', ['void']]], 'BoostModeHandler' : [ 0x28, ['pointer', ['void']]], 'PerfSelectionHandler' : [ 0x2c, ['pointer', ['void']]], 'PerfControlHandler' : [ 0x30, ['pointer', ['void']]], 'MaxFrequency' : [ 0x34, ['unsigned long']], 'NominalFrequency' : [ 0x38, ['unsigned long']], 'MaxPercent' : [ 0x3c, ['unsigned long']], 'MinPerfPercent' : [ 0x40, ['unsigned long']], 'MinThrottlePercent' : [ 0x44, ['unsigned long']], 'Coordination' : [ 0x48, ['unsigned char']], 'HardPlatformCap' : [ 0x49, ['unsigned char']], 'AffinitizeControl' : [ 0x4a, ['unsigned char']], 'SelectedPercent' : [ 0x4c, ['unsigned long']], 'SelectedFrequency' : [ 0x50, ['unsigned long']], 'DesiredPercent' : [ 0x54, ['unsigned long']], 'MaxPolicyPercent' : [ 0x58, ['unsigned long']], 'MinPolicyPercent' : [ 0x5c, ['unsigned long']], 'ConstrainedMaxPercent' : [ 0x60, ['unsigned long']], 'ConstrainedMinPercent' : [ 0x64, ['unsigned long']], 'GuaranteedPercent' : [ 0x68, ['unsigned long']], 'TolerancePercent' : [ 0x6c, ['unsigned long']], 'SelectedState' : [ 0x70, ['unsigned long long']], 'Force' : [ 0x78, ['unsigned char']], 'PerfChangeTime' : [ 0x80, ['unsigned long long']], 'PerfChangeIntervalCount' : [ 0x88, ['unsigned long']], } ], '_X86_DBGKD_CONTROL_SET' : [ 0x10, { 'TraceFlag' : [ 0x0, ['unsigned long']], 'Dr7' : [ 0x4, ['unsigned long']], 'CurrentSymbolStart' : [ 0x8, ['unsigned long']], 'CurrentSymbolEnd' : [ 0xc, ['unsigned long']], } ], '_HANDLE_TRACE_DB_ENTRY' : [ 0x50, { 'ClientId' : [ 0x0, ['_CLIENT_ID']], 'Handle' : [ 0x8, ['pointer', ['void']]], 'Type' : [ 0xc, ['unsigned long']], 'StackTrace' : [ 0x10, ['array', 16, ['pointer', ['void']]]], } ], '_WHEA_IPF_CPE_DESCRIPTOR' : [ 0x4, { 'Type' : [ 0x0, ['unsigned short']], 'Enabled' : [ 0x2, ['unsigned char']], 'Reserved' : [ 0x3, ['unsigned char']], } ], '_DUMMY_FILE_OBJECT' : [ 0xa0, { 'ObjectHeader' : [ 0x0, ['_OBJECT_HEADER']], 'FileObjectBody' : [ 0x20, ['array', 128, ['unsigned char']]], } ], '_POP_TRIGGER_WAIT' : [ 0x20, { 'Event' : [ 0x0, ['_KEVENT']], 'Status' : [ 0x10, ['long']], 'Link' : [ 0x14, ['_LIST_ENTRY']], 'Trigger' : [ 0x1c, ['pointer', ['_POP_ACTION_TRIGGER']]], } ], '_RELATION_LIST' : [ 0x14, { 'Count' : [ 0x0, ['unsigned long']], 'TagCount' : [ 0x4, ['unsigned long']], 'FirstLevel' : [ 0x8, ['unsigned long']], 'MaxLevel' : [ 0xc, ['unsigned long']], 'Entries' : [ 0x10, ['array', 1, ['pointer', ['_RELATION_LIST_ENTRY']]]], } ], '_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']]], } ], '__unnamed_228e' : [ 0x4, { 'Balance' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 2, native_type='long')]], 'Parent' : [ 0x0, ['pointer', ['_MM_AVL_NODE']]], } ], '_MM_AVL_NODE' : [ 0xc, { 'u1' : [ 0x0, ['__unnamed_228e']], 'LeftChild' : [ 0x4, ['pointer', ['_MM_AVL_NODE']]], 'RightChild' : [ 0x8, ['pointer', ['_MM_AVL_NODE']]], } ], '_ETW_BUFFER_QUEUE' : [ 0xc, { 'QueueHead' : [ 0x0, ['pointer', ['_SINGLE_LIST_ENTRY']]], 'QueueTail' : [ 0x4, ['pointer', ['_SINGLE_LIST_ENTRY']]], 'QueueEntry' : [ 0x8, ['_SINGLE_LIST_ENTRY']], } ], '_ARBITER_TEST_ALLOCATION_PARAMETERS' : [ 0xc, { 'ArbitrationList' : [ 0x0, ['pointer', ['_LIST_ENTRY']]], 'AllocateFromCount' : [ 0x4, ['unsigned long']], 'AllocateFrom' : [ 0x8, ['pointer', ['_CM_PARTIAL_RESOURCE_DESCRIPTOR']]], } ], '_MI_SPECIAL_POOL' : [ 0x48, { 'Lock' : [ 0x0, ['unsigned long']], 'Paged' : [ 0x8, ['_MI_PTE_CHAIN_HEAD']], 'NonPaged' : [ 0x20, ['_MI_PTE_CHAIN_HEAD']], 'PagesInUse' : [ 0x38, ['unsigned long']], 'SpecialPoolPdes' : [ 0x3c, ['_RTL_BITMAP']], } ], '_LOGGED_STREAM_CALLBACK_V2' : [ 0x4, { 'LogHandleContext' : [ 0x0, ['pointer', ['_LOG_HANDLE_CONTEXT']]], } ], '_ARBITER_QUERY_CONFLICT_PARAMETERS' : [ 0x10, { 'PhysicalDeviceObject' : [ 0x0, ['pointer', ['_DEVICE_OBJECT']]], 'ConflictingResource' : [ 0x4, ['pointer', ['_IO_RESOURCE_DESCRIPTOR']]], 'ConflictCount' : [ 0x8, ['pointer', ['unsigned long']]], 'Conflicts' : [ 0xc, ['pointer', ['pointer', ['_ARBITER_CONFLICT_INFO']]]], } ], '_POP_CURRENT_BROADCAST' : [ 0x10, { 'InProgress' : [ 0x0, ['unsigned char']], 'SystemContext' : [ 0x4, ['_SYSTEM_POWER_STATE_CONTEXT']], 'PowerAction' : [ 0x8, ['Enumeration', dict(target = 'long', choices = {0: 'PowerActionNone', 1: 'PowerActionReserved', 2: 'PowerActionSleep', 3: 'PowerActionHibernate', 4: 'PowerActionShutdown', 5: 'PowerActionShutdownReset', 6: 'PowerActionShutdownOff', 7: 'PowerActionWarmEject'})]], 'DeviceState' : [ 0xc, ['pointer', ['_POP_DEVICE_SYS_STATE']]], } ], '_PHYSICAL_MEMORY_DESCRIPTOR' : [ 0x10, { 'NumberOfRuns' : [ 0x0, ['unsigned long']], 'NumberOfPages' : [ 0x4, ['unsigned long']], 'Run' : [ 0x8, ['array', 1, ['_PHYSICAL_MEMORY_RUN']]], } ], 'PEPHANDLE__' : [ 0x4, { 'unused' : [ 0x0, ['long']], } ], '_PNP_DEVICE_EVENT_LIST' : [ 0x4c, { 'Status' : [ 0x0, ['long']], 'EventQueueMutex' : [ 0x4, ['_KMUTANT']], 'Lock' : [ 0x24, ['_FAST_MUTEX']], 'List' : [ 0x44, ['_LIST_ENTRY']], } ], '_IOV_IRP_TRACE' : [ 0x40, { 'Irp' : [ 0x0, ['pointer', ['_IRP']]], 'Thread' : [ 0x4, ['pointer', ['_KTHREAD']]], 'KernelApcDisable' : [ 0x8, ['short']], 'SpecialApcDisable' : [ 0xa, ['short']], 'CombinedApcDisable' : [ 0x8, ['unsigned long']], 'Irql' : [ 0xc, ['unsigned char']], 'StackTrace' : [ 0x10, ['array', 12, ['pointer', ['void']]]], } ], '_MAILSLOT_CREATE_PARAMETERS' : [ 0x18, { 'MailslotQuota' : [ 0x0, ['unsigned long']], 'MaximumMessageSize' : [ 0x4, ['unsigned long']], 'ReadTimeout' : [ 0x8, ['_LARGE_INTEGER']], 'TimeoutSpecified' : [ 0x10, ['unsigned char']], } ], '_PO_IRP_MANAGER' : [ 0x10, { 'DeviceIrpQueue' : [ 0x0, ['_PO_IRP_QUEUE']], 'SystemIrpQueue' : [ 0x8, ['_PO_IRP_QUEUE']], } ], '_SEP_LOWBOX_HANDLES_TABLE' : [ 0x8, { 'Lock' : [ 0x0, ['_EX_PUSH_LOCK']], 'HashTable' : [ 0x4, ['pointer', ['_RTL_DYNAMIC_HASH_TABLE']]], } ], '_PPM_FFH_THROTTLE_STATE_INFO' : [ 0x20, { 'EnableLogging' : [ 0x0, ['unsigned char']], 'MismatchCount' : [ 0x4, ['unsigned long']], 'Initialized' : [ 0x8, ['unsigned char']], 'LastValue' : [ 0x10, ['unsigned long long']], 'LastLogTickCount' : [ 0x18, ['_LARGE_INTEGER']], } ], '_PROC_IDLE_POLICY' : [ 0x5, { 'PromotePercent' : [ 0x0, ['unsigned char']], 'DemotePercent' : [ 0x1, ['unsigned char']], 'PromotePercentBase' : [ 0x2, ['unsigned char']], 'DemotePercentBase' : [ 0x3, ['unsigned char']], 'AllowScaling' : [ 0x4, ['unsigned char']], } ], '_CLIENT_ID64' : [ 0x10, { 'UniqueProcess' : [ 0x0, ['unsigned long long']], 'UniqueThread' : [ 0x8, ['unsigned long long']], } ], '_KDPC_DATA' : [ 0x14, { 'DpcListHead' : [ 0x0, ['_LIST_ENTRY']], 'DpcLock' : [ 0x8, ['unsigned long']], 'DpcQueueDepth' : [ 0xc, ['long']], 'DpcCount' : [ 0x10, ['unsigned long']], } ], '_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']], } ], '_KSCB' : [ 0xd0, { 'GenerationCycles' : [ 0x0, ['unsigned long long']], 'UnderQuotaCycleTarget' : [ 0x8, ['unsigned long long']], 'RankCycleTarget' : [ 0x10, ['unsigned long long']], 'LongTermCycles' : [ 0x18, ['unsigned long long']], 'LastReportedCycles' : [ 0x20, ['unsigned long long']], 'OverQuotaHistory' : [ 0x28, ['unsigned long long']], 'PerProcessorList' : [ 0x30, ['_LIST_ENTRY']], 'QueueNode' : [ 0x38, ['_RTL_BALANCED_NODE']], 'Inserted' : [ 0x44, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned char')]], 'OverQuota' : [ 0x44, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned char')]], 'HardCap' : [ 0x44, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned char')]], 'RankBias' : [ 0x44, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned char')]], 'Spare1' : [ 0x44, ['BitField', dict(start_bit = 4, end_bit = 8, native_type='unsigned char')]], 'Spare2' : [ 0x45, ['unsigned char']], 'ReadySummary' : [ 0x46, ['unsigned short']], 'Rank' : [ 0x48, ['unsigned long']], 'ReadyListHead' : [ 0x4c, ['array', 16, ['_LIST_ENTRY']]], } ], '__unnamed_22c6' : [ 0x8, { 'UserData' : [ 0x0, ['pointer', ['void']]], 'Owner' : [ 0x4, ['pointer', ['void']]], } ], '__unnamed_22c8' : [ 0x8, { 'ListHead' : [ 0x0, ['_LIST_ENTRY']], } ], '_RTLP_RANGE_LIST_ENTRY' : [ 0x28, { 'Start' : [ 0x0, ['unsigned long long']], 'End' : [ 0x8, ['unsigned long long']], 'Allocated' : [ 0x10, ['__unnamed_22c6']], 'Merged' : [ 0x10, ['__unnamed_22c8']], 'Attributes' : [ 0x18, ['unsigned char']], 'PublicFlags' : [ 0x19, ['unsigned char']], 'PrivateFlags' : [ 0x1a, ['unsigned short']], 'ListEntry' : [ 0x1c, ['_LIST_ENTRY']], } ], '_ALPC_COMPLETION_PACKET_LOOKASIDE_ENTRY' : [ 0xc, { 'ListEntry' : [ 0x0, ['_SINGLE_LIST_ENTRY']], 'Packet' : [ 0x4, ['pointer', ['_IO_MINI_COMPLETION_PACKET_USER']]], 'Lookaside' : [ 0x8, ['pointer', ['_ALPC_COMPLETION_PACKET_LOOKASIDE']]], } ], '_PROC_PERF_HISTORY' : [ 0x1c, { 'Count' : [ 0x0, ['unsigned long']], 'Slot' : [ 0x4, ['unsigned long']], 'UtilityTotal' : [ 0x8, ['unsigned long']], 'AffinitizedUtilityTotal' : [ 0xc, ['unsigned long']], 'FrequencyTotal' : [ 0x10, ['unsigned long']], 'HistoryList' : [ 0x14, ['array', 1, ['_PROC_PERF_HISTORY_ENTRY']]], } ], '__unnamed_22d4' : [ 0x2, { 'AsUSHORT' : [ 0x0, ['unsigned short']], 'AllowScaling' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned short')]], 'Disabled' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned short')]], 'Reserved' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 16, native_type='unsigned short')]], } ], 'PROCESSOR_IDLESTATE_POLICY' : [ 0x20, { 'Revision' : [ 0x0, ['unsigned short']], 'Flags' : [ 0x2, ['__unnamed_22d4']], 'PolicyCount' : [ 0x4, ['unsigned long']], 'Policy' : [ 0x8, ['array', 3, ['PROCESSOR_IDLESTATE_INFO']]], } ], '_ACTIVATION_CONTEXT_STACK' : [ 0x18, { 'ActiveFrame' : [ 0x0, ['pointer', ['_RTL_ACTIVATION_CONTEXT_STACK_FRAME']]], 'FrameListCache' : [ 0x4, ['_LIST_ENTRY']], 'Flags' : [ 0xc, ['unsigned long']], 'NextCookieSequenceNumber' : [ 0x10, ['unsigned long']], 'StackId' : [ 0x14, ['unsigned long']], } ], '_MSUBSECTION' : [ 0x3c, { 'ControlArea' : [ 0x0, ['pointer', ['_CONTROL_AREA']]], 'SubsectionBase' : [ 0x4, ['pointer', ['_MMPTE']]], 'NextSubsection' : [ 0x8, ['pointer', ['_SUBSECTION']]], 'NextMappedSubsection' : [ 0x8, ['pointer', ['_MSUBSECTION']]], 'PtesInSubsection' : [ 0xc, ['unsigned long']], 'UnusedPtes' : [ 0x10, ['unsigned long']], 'GlobalPerSessionHead' : [ 0x10, ['pointer', ['_MM_AVL_TABLE']]], 'u' : [ 0x14, ['__unnamed_2008']], 'StartingSector' : [ 0x18, ['unsigned long']], 'NumberOfFullSectors' : [ 0x1c, ['unsigned long']], 'SubsectionNode' : [ 0x20, ['_MM_AVL_NODE']], 'DereferenceList' : [ 0x2c, ['_LIST_ENTRY']], 'NumberOfMappedViews' : [ 0x34, ['unsigned long']], 'NumberOfPfnReferences' : [ 0x38, ['unsigned long']], } ], '_RTL_DRIVE_LETTER_CURDIR' : [ 0x10, { 'Flags' : [ 0x0, ['unsigned short']], 'Length' : [ 0x2, ['unsigned short']], 'TimeStamp' : [ 0x4, ['unsigned long']], 'DosPath' : [ 0x8, ['_STRING']], } ], '_MI_PTE_CHAIN_HEAD' : [ 0x18, { 'Flink' : [ 0x0, ['_MMPTE']], 'Blink' : [ 0x8, ['_MMPTE']], 'PteBase' : [ 0x10, ['pointer', ['_MMPTE']]], } ], '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']], 'FastSystemS4' : [ 0x11, ['unsigned char']], 'Hiberboot' : [ 0x12, ['unsigned char']], 'WakeAlarmPresent' : [ 0x13, ['unsigned char']], 'AoAc' : [ 0x14, ['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'})]], } ], '_PPM_IDLE_SYNCHRONIZATION_STATE' : [ 0x4, { 'AsLong' : [ 0x0, ['long']], 'RefCount' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 24, native_type='long')]], 'State' : [ 0x0, ['BitField', dict(start_bit = 24, end_bit = 32, native_type='unsigned long')]], } ], '_PPM_CONCURRENCY_ACCOUNTING' : [ 0x28, { 'Lock' : [ 0x0, ['unsigned long']], 'Processors' : [ 0x4, ['unsigned long']], 'ActiveProcessors' : [ 0x8, ['unsigned long']], 'LastUpdateTime' : [ 0x10, ['unsigned long long']], 'TotalTime' : [ 0x18, ['unsigned long long']], 'AccumulatedTime' : [ 0x20, ['array', 1, ['unsigned long long']]], } ], '__unnamed_22f0' : [ 0x4, { 'ImageCommitment' : [ 0x0, ['unsigned long']], 'CreatingProcess' : [ 0x0, ['pointer', ['_EPROCESS']]], } ], '__unnamed_22f4' : [ 0x4, { 'ImageInformation' : [ 0x0, ['pointer', ['_MI_SECTION_IMAGE_INFORMATION']]], 'FirstMappedVa' : [ 0x0, ['pointer', ['void']]], } ], '_SEGMENT' : [ 0x30, { 'ControlArea' : [ 0x0, ['pointer', ['_CONTROL_AREA']]], 'TotalNumberOfPtes' : [ 0x4, ['unsigned long']], 'SegmentFlags' : [ 0x8, ['_SEGMENT_FLAGS']], 'NumberOfCommittedPages' : [ 0xc, ['unsigned long']], 'SizeOfSegment' : [ 0x10, ['unsigned long long']], 'ExtendInfo' : [ 0x18, ['pointer', ['_MMEXTEND_INFO']]], 'BasedAddress' : [ 0x18, ['pointer', ['void']]], 'SegmentLock' : [ 0x1c, ['_EX_PUSH_LOCK']], 'u1' : [ 0x20, ['__unnamed_22f0']], 'u2' : [ 0x24, ['__unnamed_22f4']], 'PrototypePte' : [ 0x28, ['pointer', ['_MMPTE']]], } ], '_DIAGNOSTIC_CONTEXT' : [ 0x10, { 'CallerType' : [ 0x0, ['Enumeration', dict(target = 'long', choices = {0: 'KernelRequester', 1: 'UserProcessRequester', 2: 'UserSharedServiceRequester'})]], 'Process' : [ 0x4, ['pointer', ['_EPROCESS']]], 'ServiceTag' : [ 0x8, ['unsigned long']], 'DeviceObject' : [ 0x4, ['pointer', ['_DEVICE_OBJECT']]], 'ReasonSize' : [ 0xc, ['unsigned long']], } ], '__unnamed_22fd' : [ 0x4, { 'MissedEtwRegistration' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]], 'Spare' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 32, native_type='unsigned long')]], } ], '__unnamed_22ff' : [ 0x4, { 'Flags' : [ 0x0, ['__unnamed_22fd']], 'Whole' : [ 0x0, ['unsigned long']], } ], '_VF_TARGET_VERIFIED_DRIVER_DATA' : [ 0x90, { 'SuspectDriverEntry' : [ 0x0, ['pointer', ['_VF_SUSPECT_DRIVER_ENTRY']]], 'WMICallback' : [ 0x4, ['pointer', ['void']]], 'EtwHandlesListHead' : [ 0x8, ['_LIST_ENTRY']], 'u1' : [ 0x10, ['__unnamed_22ff']], 'Signature' : [ 0x14, ['unsigned long']], 'PoolPageHeaders' : [ 0x18, ['_SLIST_HEADER']], 'PoolTrackers' : [ 0x20, ['_SLIST_HEADER']], 'CurrentPagedPoolAllocations' : [ 0x28, ['unsigned long']], 'CurrentNonPagedPoolAllocations' : [ 0x2c, ['unsigned long']], 'PeakPagedPoolAllocations' : [ 0x30, ['unsigned long']], 'PeakNonPagedPoolAllocations' : [ 0x34, ['unsigned long']], 'PagedBytes' : [ 0x38, ['unsigned long']], 'NonPagedBytes' : [ 0x3c, ['unsigned long']], 'PeakPagedBytes' : [ 0x40, ['unsigned long']], 'PeakNonPagedBytes' : [ 0x44, ['unsigned long']], 'RaiseIrqls' : [ 0x48, ['unsigned long']], 'AcquireSpinLocks' : [ 0x4c, ['unsigned long']], 'SynchronizeExecutions' : [ 0x50, ['unsigned long']], 'AllocationsWithNoTag' : [ 0x54, ['unsigned long']], 'AllocationsFailed' : [ 0x58, ['unsigned long']], 'AllocationsFailedDeliberately' : [ 0x5c, ['unsigned long']], 'LockedBytes' : [ 0x60, ['unsigned long']], 'PeakLockedBytes' : [ 0x64, ['unsigned long']], 'MappedLockedBytes' : [ 0x68, ['unsigned long']], 'PeakMappedLockedBytes' : [ 0x6c, ['unsigned long']], 'MappedIoSpaceBytes' : [ 0x70, ['unsigned long']], 'PeakMappedIoSpaceBytes' : [ 0x74, ['unsigned long']], 'PagesForMdlBytes' : [ 0x78, ['unsigned long']], 'PeakPagesForMdlBytes' : [ 0x7c, ['unsigned long']], 'ContiguousMemoryBytes' : [ 0x80, ['unsigned long']], 'PeakContiguousMemoryBytes' : [ 0x84, ['unsigned long']], 'ContiguousMemoryListHead' : [ 0x88, ['_LIST_ENTRY']], } ], '_MMVAD_FLAGS1' : [ 0x4, { 'CommitCharge' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 31, native_type='unsigned long')]], 'MemCommit' : [ 0x0, ['BitField', dict(start_bit = 31, end_bit = 32, native_type='unsigned long')]], } ], '_PRIVATE_CACHE_MAP' : [ 0x68, { 'NodeTypeCode' : [ 0x0, ['short']], 'Flags' : [ 0x0, ['_PRIVATE_CACHE_MAP_FLAGS']], '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']], 'SequentialReadCount' : [ 0x30, ['unsigned long']], 'ReadAheadLength' : [ 0x34, ['unsigned long']], 'ReadAheadOffset' : [ 0x38, ['_LARGE_INTEGER']], 'ReadAheadBeyondLastByte' : [ 0x40, ['_LARGE_INTEGER']], 'PrevReadAheadBeyondLastByte' : [ 0x48, ['unsigned long long']], 'ReadAheadSpinLock' : [ 0x50, ['unsigned long']], 'PipelinedReadAheadRequestSize' : [ 0x54, ['unsigned long']], 'ReadAheadGrowth' : [ 0x58, ['unsigned long']], 'PrivateLinks' : [ 0x5c, ['_LIST_ENTRY']], 'ReadAheadWorkItem' : [ 0x64, ['pointer', ['void']]], } ], '_CM_KEY_NODE' : [ 0x50, { 'Signature' : [ 0x0, ['unsigned short']], 'Flags' : [ 0x2, ['unsigned short']], 'LastWriteTime' : [ 0x4, ['_LARGE_INTEGER']], 'AccessBits' : [ 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, ['wchar']]], } ], '_AER_ROOTPORT_DESCRIPTOR_FLAGS' : [ 0x2, { 'UncorrectableErrorMaskRW' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned short')]], 'UncorrectableErrorSeverityRW' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned short')]], 'CorrectableErrorMaskRW' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned short')]], 'AdvancedCapsAndControlRW' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned short')]], 'RootErrorCommandRW' : [ 0x0, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned short')]], 'Reserved' : [ 0x0, ['BitField', dict(start_bit = 5, end_bit = 16, native_type='unsigned short')]], 'AsUSHORT' : [ 0x0, ['unsigned short']], } ], '_PTE_TRACKER' : [ 0x44, { 'ListEntry' : [ 0x0, ['_LIST_ENTRY']], 'Mdl' : [ 0x8, ['pointer', ['_MDL']]], 'Count' : [ 0xc, ['unsigned long']], 'SystemVa' : [ 0x10, ['pointer', ['void']]], 'StartVa' : [ 0x14, ['pointer', ['void']]], 'Offset' : [ 0x18, ['unsigned long']], 'Length' : [ 0x1c, ['unsigned long']], 'Page' : [ 0x20, ['unsigned long']], 'IoMapping' : [ 0x24, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]], 'Matched' : [ 0x24, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]], 'CacheAttribute' : [ 0x24, ['BitField', dict(start_bit = 2, end_bit = 4, native_type='unsigned long')]], 'Spare' : [ 0x24, ['BitField', dict(start_bit = 4, end_bit = 32, native_type='unsigned long')]], 'StackTrace' : [ 0x28, ['array', 7, ['pointer', ['void']]]], } ], '_KTHREAD_COUNTERS' : [ 0x1a8, { 'WaitReasonBitMap' : [ 0x0, ['unsigned long long']], 'UserData' : [ 0x8, ['pointer', ['_THREAD_PERFORMANCE_DATA']]], 'Flags' : [ 0xc, ['unsigned long']], 'ContextSwitches' : [ 0x10, ['unsigned long']], 'CycleTimeBias' : [ 0x18, ['unsigned long long']], 'HardwareCounters' : [ 0x20, ['unsigned long long']], 'HwCounter' : [ 0x28, ['array', 16, ['_COUNTER_READING']]], } ], '_SHARED_CACHE_MAP_LIST_CURSOR' : [ 0xc, { 'SharedCacheMapLinks' : [ 0x0, ['_LIST_ENTRY']], 'Flags' : [ 0x8, ['unsigned long']], } ], '_DBGKD_GET_VERSION64' : [ 0x28, { 'MajorVersion' : [ 0x0, ['unsigned short']], 'MinorVersion' : [ 0x2, ['unsigned short']], 'ProtocolVersion' : [ 0x4, ['unsigned char']], 'KdSecondaryVersion' : [ 0x5, ['unsigned char']], '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']], } ], '_PROC_FEEDBACK_COUNTER' : [ 0x28, { 'InstantaneousRead' : [ 0x0, ['pointer', ['void']]], 'DifferentialRead' : [ 0x0, ['pointer', ['void']]], 'LastActualCount' : [ 0x8, ['unsigned long long']], 'LastReferenceCount' : [ 0x10, ['unsigned long long']], 'CachedValue' : [ 0x18, ['unsigned long']], 'Affinitized' : [ 0x20, ['unsigned char']], 'Differential' : [ 0x21, ['unsigned char']], 'DisableInterrupts' : [ 0x22, ['unsigned char']], 'Context' : [ 0x24, ['unsigned long']], } ], '_HMAP_ENTRY' : [ 0xc, { 'BlockAddress' : [ 0x0, ['unsigned long']], 'BinAddress' : [ 0x4, ['unsigned long']], 'MemAlloc' : [ 0x8, ['unsigned long']], } ], '_RTL_ATOM_TABLE_ENTRY' : [ 0x1c, { 'HashLink' : [ 0x0, ['pointer', ['_RTL_ATOM_TABLE_ENTRY']]], 'HandleIndex' : [ 0x4, ['unsigned short']], 'Atom' : [ 0x6, ['unsigned short']], 'Reference' : [ 0x8, ['_RTL_ATOM_TABLE_REFERENCE']], 'NameLength' : [ 0x18, ['unsigned char']], 'Name' : [ 0x1a, ['array', 1, ['wchar']]], } ], '_PLATFORM_IDLE_ACCOUNTING' : [ 0x388, { 'ResetCount' : [ 0x0, ['unsigned long']], 'StateCount' : [ 0x4, ['unsigned long']], 'TimeUnit' : [ 0x8, ['Enumeration', dict(target = 'long', choices = {0: 'PpmIdleBucketTimeInQpc', 1: 'PpmIdleBucketTimeIn100ns', 2: 'PpmIdleBucketTimeMaximum'})]], 'StartTime' : [ 0x10, ['unsigned long long']], 'State' : [ 0x18, ['array', 1, ['_PLATFORM_IDLE_STATE_ACCOUNTING']]], } ], '_TXN_PARAMETER_BLOCK' : [ 0x8, { 'Length' : [ 0x0, ['unsigned short']], 'TxFsContext' : [ 0x2, ['unsigned short']], 'TransactionObject' : [ 0x4, ['pointer', ['void']]], } ], '_DUAL' : [ 0x19c, { 'Length' : [ 0x0, ['unsigned long']], 'Map' : [ 0x4, ['pointer', ['_HMAP_DIRECTORY']]], 'SmallDir' : [ 0x8, ['pointer', ['_HMAP_TABLE']]], 'Guard' : [ 0xc, ['unsigned long']], 'FreeDisplay' : [ 0x10, ['array', 24, ['_FREE_DISPLAY']]], 'FreeBins' : [ 0x190, ['_LIST_ENTRY']], 'FreeSummary' : [ 0x198, ['unsigned long']], } ], '_MI_VAD_SEQUENTIAL_INFO' : [ 0x4, { 'Length' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 11, native_type='unsigned long')]], 'Vpn' : [ 0x0, ['BitField', dict(start_bit = 11, end_bit = 32, native_type='unsigned long')]], } ], '_PNP_DEVICE_ACTION_ENTRY' : [ 0x20, { 'ListEntry' : [ 0x0, ['_LIST_ENTRY']], 'DeviceObject' : [ 0x8, ['pointer', ['_DEVICE_OBJECT']]], 'RequestType' : [ 0xc, ['Enumeration', dict(target = 'long', choices = {0: 'AssignResources', 1: 'ClearDeviceProblem', 2: 'ClearProblem', 3: 'ClearEjectProblem', 4: 'HaltDevice', 5: 'QueryPowerRelations', 6: 'Rebalance', 7: 'ReenumerateBootDevices', 8: 'ReenumerateDeviceOnly', 9: 'ReenumerateDeviceTree', 10: 'ReenumerateRootDevices', 11: 'RequeryDeviceState', 12: 'ResetDevice', 13: 'ResourceRequirementsChanged', 14: 'RestartEnumeration', 15: 'SetDeviceProblem', 16: 'StartDevice', 17: 'StartSystemDevicesPass0', 18: 'StartSystemDevicesPass1', 19: 'NotifyTransportRelationsChange', 20: 'NotifyEjectionRelationsChange', 21: 'ConfigureDevice', 22: 'ConfigureDeviceClass'})]], 'ReorderingBarrier' : [ 0x10, ['unsigned char']], 'RequestArgument' : [ 0x14, ['unsigned long']], 'CompletionEvent' : [ 0x18, ['pointer', ['_KEVENT']]], 'CompletionStatus' : [ 0x1c, ['pointer', ['long']]], } ], '_SEP_LOWBOX_NUMBER_ENTRY' : [ 0x1c, { 'HashEntry' : [ 0x0, ['_RTL_DYNAMIC_HASH_TABLE_ENTRY']], 'ReferenceCount' : [ 0xc, ['unsigned long']], 'PackageSid' : [ 0x10, ['pointer', ['void']]], 'LowboxNumber' : [ 0x14, ['unsigned long']], 'AtomTable' : [ 0x18, ['pointer', ['void']]], } ], '_COUNTER_READING' : [ 0x18, { 'Type' : [ 0x0, ['Enumeration', dict(target = 'long', choices = {0: 'PMCCounter', 1: 'MaxHardwareCounterType'})]], 'Index' : [ 0x4, ['unsigned long']], 'Start' : [ 0x8, ['unsigned long long']], 'Total' : [ 0x10, ['unsigned long long']], } ], '_MMSESSION' : [ 0x38, { 'SystemSpaceViewLock' : [ 0x0, ['_FAST_MUTEX']], 'SystemSpaceViewLockPointer' : [ 0x20, ['pointer', ['_FAST_MUTEX']]], 'SystemSpaceViewTable' : [ 0x24, ['pointer', ['_MMVIEW']]], 'SystemSpaceHashSize' : [ 0x28, ['unsigned long']], 'SystemSpaceHashEntries' : [ 0x2c, ['unsigned long']], 'SystemSpaceHashKey' : [ 0x30, ['unsigned long']], 'BitmapFailures' : [ 0x34, ['unsigned long']], } ], '_ETW_REG_ENTRY' : [ 0x28, { 'RegList' : [ 0x0, ['_LIST_ENTRY']], 'GuidEntry' : [ 0x8, ['pointer', ['_ETW_GUID_ENTRY']]], 'ReplyQueue' : [ 0xc, ['pointer', ['_ETW_REPLY_QUEUE']]], 'ReplySlot' : [ 0xc, ['array', 4, ['pointer', ['_ETW_QUEUE_ENTRY']]]], 'Caller' : [ 0xc, ['pointer', ['void']]], 'SessionId' : [ 0x10, ['unsigned long']], 'Process' : [ 0x1c, ['pointer', ['_EPROCESS']]], 'CallbackContext' : [ 0x1c, ['pointer', ['void']]], 'Callback' : [ 0x20, ['pointer', ['void']]], 'Index' : [ 0x24, ['unsigned short']], 'Flags' : [ 0x26, ['unsigned char']], 'DbgKernelRegistration' : [ 0x26, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned char')]], 'DbgUserRegistration' : [ 0x26, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned char')]], 'DbgReplyRegistration' : [ 0x26, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned char')]], 'DbgClassicRegistration' : [ 0x26, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned char')]], 'DbgSessionSpaceRegistration' : [ 0x26, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned char')]], 'DbgModernRegistration' : [ 0x26, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned char')]], 'DbgClosed' : [ 0x26, ['BitField', dict(start_bit = 6, end_bit = 7, native_type='unsigned char')]], 'DbgInserted' : [ 0x26, ['BitField', dict(start_bit = 7, end_bit = 8, native_type='unsigned char')]], 'EnableMask' : [ 0x27, ['unsigned char']], } ], '_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']], } ], '_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: 'Vmcs', 17: 'ACPIBus', 18: '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'})]], } ], '_LDR_DATA_TABLE_ENTRY' : [ 0x98, { 'InLoadOrderLinks' : [ 0x0, ['_LIST_ENTRY']], 'InMemoryOrderLinks' : [ 0x8, ['_LIST_ENTRY']], 'InInitializationOrderLinks' : [ 0x10, ['_LIST_ENTRY']], 'InProgressLinks' : [ 0x10, ['_LIST_ENTRY']], 'DllBase' : [ 0x18, ['pointer', ['void']]], 'EntryPoint' : [ 0x1c, ['pointer', ['void']]], 'SizeOfImage' : [ 0x20, ['unsigned long']], 'FullDllName' : [ 0x24, ['_UNICODE_STRING']], 'BaseDllName' : [ 0x2c, ['_UNICODE_STRING']], 'FlagGroup' : [ 0x34, ['array', 4, ['unsigned char']]], 'Flags' : [ 0x34, ['unsigned long']], 'PackagedBinary' : [ 0x34, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]], 'MarkedForRemoval' : [ 0x34, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]], 'ImageDll' : [ 0x34, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]], 'LoadNotificationsSent' : [ 0x34, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned long')]], 'TelemetryEntryProcessed' : [ 0x34, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned long')]], 'ProcessStaticImport' : [ 0x34, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned long')]], 'InLegacyLists' : [ 0x34, ['BitField', dict(start_bit = 6, end_bit = 7, native_type='unsigned long')]], 'InIndexes' : [ 0x34, ['BitField', dict(start_bit = 7, end_bit = 8, native_type='unsigned long')]], 'ShimDll' : [ 0x34, ['BitField', dict(start_bit = 8, end_bit = 9, native_type='unsigned long')]], 'InExceptionTable' : [ 0x34, ['BitField', dict(start_bit = 9, end_bit = 10, native_type='unsigned long')]], 'ReservedFlags1' : [ 0x34, ['BitField', dict(start_bit = 10, end_bit = 12, native_type='unsigned long')]], 'LoadInProgress' : [ 0x34, ['BitField', dict(start_bit = 12, end_bit = 13, native_type='unsigned long')]], 'ReservedFlags2' : [ 0x34, ['BitField', dict(start_bit = 13, end_bit = 14, native_type='unsigned long')]], 'EntryProcessed' : [ 0x34, ['BitField', dict(start_bit = 14, end_bit = 15, native_type='unsigned long')]], 'ReservedFlags3' : [ 0x34, ['BitField', dict(start_bit = 15, end_bit = 18, native_type='unsigned long')]], 'DontCallForThreads' : [ 0x34, ['BitField', dict(start_bit = 18, end_bit = 19, native_type='unsigned long')]], 'ProcessAttachCalled' : [ 0x34, ['BitField', dict(start_bit = 19, end_bit = 20, native_type='unsigned long')]], 'ProcessAttachFailed' : [ 0x34, ['BitField', dict(start_bit = 20, end_bit = 21, native_type='unsigned long')]], 'CorDeferredValidate' : [ 0x34, ['BitField', dict(start_bit = 21, end_bit = 22, native_type='unsigned long')]], 'CorImage' : [ 0x34, ['BitField', dict(start_bit = 22, end_bit = 23, native_type='unsigned long')]], 'DontRelocate' : [ 0x34, ['BitField', dict(start_bit = 23, end_bit = 24, native_type='unsigned long')]], 'CorILOnly' : [ 0x34, ['BitField', dict(start_bit = 24, end_bit = 25, native_type='unsigned long')]], 'ReservedFlags5' : [ 0x34, ['BitField', dict(start_bit = 25, end_bit = 28, native_type='unsigned long')]], 'Redirected' : [ 0x34, ['BitField', dict(start_bit = 28, end_bit = 29, native_type='unsigned long')]], 'ReservedFlags6' : [ 0x34, ['BitField', dict(start_bit = 29, end_bit = 31, native_type='unsigned long')]], 'CompatDatabaseProcessed' : [ 0x34, ['BitField', dict(start_bit = 31, end_bit = 32, native_type='unsigned long')]], 'ObsoleteLoadCount' : [ 0x38, ['unsigned short']], 'TlsIndex' : [ 0x3a, ['unsigned short']], 'HashLinks' : [ 0x3c, ['_LIST_ENTRY']], 'TimeDateStamp' : [ 0x44, ['unsigned long']], 'EntryPointActivationContext' : [ 0x48, ['pointer', ['_ACTIVATION_CONTEXT']]], 'PatchInformation' : [ 0x4c, ['pointer', ['void']]], 'DdagNode' : [ 0x50, ['pointer', ['_LDR_DDAG_NODE']]], 'NodeModuleLink' : [ 0x54, ['_LIST_ENTRY']], 'SnapContext' : [ 0x5c, ['pointer', ['_LDRP_DLL_SNAP_CONTEXT']]], 'ParentDllBase' : [ 0x60, ['pointer', ['void']]], 'SwitchBackContext' : [ 0x64, ['pointer', ['void']]], 'BaseAddressIndexNode' : [ 0x68, ['_RTL_BALANCED_NODE']], 'MappingInfoIndexNode' : [ 0x74, ['_RTL_BALANCED_NODE']], 'OriginalBase' : [ 0x80, ['unsigned long']], 'LoadTime' : [ 0x88, ['_LARGE_INTEGER']], 'BaseNameHashValue' : [ 0x90, ['unsigned long']], 'LoadReason' : [ 0x94, ['Enumeration', dict(target = 'long', choices = {0: 'LoadReasonStaticDependency', 1: 'LoadReasonStaticForwarderDependency', 2: 'LoadReasonDynamicForwarderDependency', 3: 'LoadReasonDelayloadDependency', 4: 'LoadReasonDynamicLoad', 5: 'LoadReasonAsImageLoad', 6: 'LoadReasonAsDataLoad', -1: 'LoadReasonUnknown'})]], } ], '_LDR_DDAG_NODE' : [ 0x30, { 'Modules' : [ 0x0, ['_LIST_ENTRY']], 'ServiceTagList' : [ 0x8, ['pointer', ['_LDR_SERVICE_TAG_RECORD']]], 'LoadCount' : [ 0xc, ['unsigned long']], 'ReferenceCount' : [ 0x10, ['unsigned long']], 'DependencyCount' : [ 0x14, ['unsigned long']], 'Dependencies' : [ 0x18, ['_LDRP_CSLIST']], 'RemovalLink' : [ 0x18, ['_SINGLE_LIST_ENTRY']], 'IncomingDependencies' : [ 0x1c, ['_LDRP_CSLIST']], 'State' : [ 0x20, ['Enumeration', dict(target = 'long', choices = {0: 'LdrModulesPlaceHolder', 1: 'LdrModulesMapping', 2: 'LdrModulesMapped', 3: 'LdrModulesWaitingForDependencies', 4: 'LdrModulesSnapping', 5: 'LdrModulesSnapped', 6: 'LdrModulesCondensed', 7: 'LdrModulesReadyToInit', 8: 'LdrModulesInitializing', 9: 'LdrModulesReadyToRun', '\xfb': 'LdrModulesMerged', '\xfd': 'LdrModulesSnapError', '\xfc': 'LdrModulesInitError', -1: 'LdrModulesUnloading', '\xfe': 'LdrModulesUnloaded'})]], 'CondenseLink' : [ 0x24, ['_SINGLE_LIST_ENTRY']], 'PreorderNumber' : [ 0x28, ['unsigned long']], 'LowestLink' : [ 0x2c, ['unsigned long']], } ], '_POP_DEVICE_SYS_STATE' : [ 0x104, { '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'})]], 'SpinLock' : [ 0x8, ['unsigned long']], 'Thread' : [ 0xc, ['pointer', ['_KTHREAD']]], 'AbortEvent' : [ 0x10, ['pointer', ['_KEVENT']]], 'ReadySemaphore' : [ 0x14, ['pointer', ['_KSEMAPHORE']]], 'FinishedSemaphore' : [ 0x18, ['pointer', ['_KSEMAPHORE']]], 'Order' : [ 0x1c, ['_PO_DEVICE_NOTIFY_ORDER']], 'Pending' : [ 0xec, ['_LIST_ENTRY']], 'Status' : [ 0xf4, ['long']], 'FailedDevice' : [ 0xf8, ['pointer', ['_DEVICE_OBJECT']]], 'Waking' : [ 0xfc, ['unsigned char']], 'Cancelled' : [ 0xfd, ['unsigned char']], 'IgnoreErrors' : [ 0xfe, ['unsigned char']], 'IgnoreNotImplemented' : [ 0xff, ['unsigned char']], 'TimeRefreshLockAcquired' : [ 0x100, ['unsigned char']], } ], '_SEGMENT_FLAGS' : [ 0x4, { 'TotalNumberOfPtes4132' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 10, native_type='unsigned short')]], 'Spare0' : [ 0x0, ['BitField', dict(start_bit = 10, end_bit = 11, native_type='unsigned short')]], 'LargePages' : [ 0x0, ['BitField', dict(start_bit = 11, end_bit = 12, native_type='unsigned short')]], 'Spare1' : [ 0x0, ['BitField', dict(start_bit = 12, end_bit = 13, native_type='unsigned short')]], 'DebugSymbolsLoaded' : [ 0x0, ['BitField', dict(start_bit = 13, end_bit = 14, native_type='unsigned short')]], 'WriteCombined' : [ 0x0, ['BitField', dict(start_bit = 14, end_bit = 15, native_type='unsigned short')]], 'NoCache' : [ 0x0, ['BitField', dict(start_bit = 15, end_bit = 16, native_type='unsigned short')]], 'FloppyMedia' : [ 0x2, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned char')]], 'DefaultProtectionMask' : [ 0x2, ['BitField', dict(start_bit = 1, end_bit = 6, native_type='unsigned char')]], 'Binary32' : [ 0x2, ['BitField', dict(start_bit = 6, end_bit = 7, native_type='unsigned char')]], 'ContainsDebug' : [ 0x2, ['BitField', dict(start_bit = 7, end_bit = 8, native_type='unsigned char')]], 'ILOnly' : [ 0x3, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned char')]], 'Spare' : [ 0x3, ['BitField', dict(start_bit = 1, end_bit = 4, native_type='unsigned char')]], 'ImageSigningLevel' : [ 0x3, ['BitField', dict(start_bit = 4, end_bit = 8, native_type='unsigned char')]], } ], '_VF_KE_CRITICAL_REGION_TRACE' : [ 0x20, { 'Thread' : [ 0x0, ['pointer', ['_ETHREAD']]], 'StackTrace' : [ 0x4, ['array', 7, ['pointer', ['void']]]], } ], '_LOGGED_STREAM_CALLBACK_V1' : [ 0x8, { 'LogHandle' : [ 0x0, ['pointer', ['void']]], 'FlushToLsnRoutine' : [ 0x4, ['pointer', ['void']]], } ], '_DIAGNOSTIC_BUFFER' : [ 0x18, { 'Size' : [ 0x0, ['unsigned long']], 'CallerType' : [ 0x4, ['Enumeration', dict(target = 'long', choices = {0: 'KernelRequester', 1: 'UserProcessRequester', 2: 'UserSharedServiceRequester'})]], 'ProcessImageNameOffset' : [ 0x8, ['unsigned long']], 'ProcessId' : [ 0xc, ['unsigned long']], 'ServiceTag' : [ 0x10, ['unsigned long']], 'DeviceDescriptionOffset' : [ 0x8, ['unsigned long']], 'DevicePathOffset' : [ 0xc, ['unsigned long']], 'ReasonOffset' : [ 0x14, ['unsigned long']], } ], '_CLIENT_ID32' : [ 0x8, { 'UniqueProcess' : [ 0x0, ['unsigned long']], 'UniqueThread' : [ 0x4, ['unsigned long']], } ], '_CM_KEY_INDEX' : [ 0x8, { 'Signature' : [ 0x0, ['unsigned short']], 'Count' : [ 0x2, ['unsigned short']], 'List' : [ 0x4, ['array', 1, ['unsigned long']]], } ], '_VI_DEADLOCK_THREAD' : [ 0x20, { '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']], 'ThreadUsesEresources' : [ 0x1c, ['unsigned char']], } ], '_PPM_IDLE_STATE' : [ 0x20, { 'DomainMembers' : [ 0x0, ['_KAFFINITY_EX']], 'Latency' : [ 0xc, ['unsigned long']], 'Power' : [ 0x10, ['unsigned long']], 'StateFlags' : [ 0x14, ['unsigned long']], 'StateType' : [ 0x18, ['unsigned char']], 'InterruptsEnabled' : [ 0x19, ['unsigned char']], 'Interruptible' : [ 0x1a, ['unsigned char']], 'ContextRetained' : [ 0x1b, ['unsigned char']], 'CacheCoherent' : [ 0x1c, ['unsigned char']], } ], '_KRESOURCEMANAGER' : [ 0x154, { 'NotificationAvailable' : [ 0x0, ['_KEVENT']], 'cookie' : [ 0x10, ['unsigned long']], 'State' : [ 0x14, ['Enumeration', dict(target = 'long', choices = {0: 'KResourceManagerUninitialized', 1: 'KResourceManagerOffline', 2: 'KResourceManagerOnline'})]], 'Flags' : [ 0x18, ['unsigned long']], 'Mutex' : [ 0x1c, ['_KMUTANT']], 'NamespaceLink' : [ 0x3c, ['_KTMOBJECT_NAMESPACE_LINK']], 'RmId' : [ 0x50, ['_GUID']], 'NotificationQueue' : [ 0x60, ['_KQUEUE']], 'NotificationMutex' : [ 0x88, ['_KMUTANT']], 'EnlistmentHead' : [ 0xa8, ['_LIST_ENTRY']], 'EnlistmentCount' : [ 0xb0, ['unsigned long']], 'NotificationRoutine' : [ 0xb4, ['pointer', ['void']]], 'Key' : [ 0xb8, ['pointer', ['void']]], 'ProtocolListHead' : [ 0xbc, ['_LIST_ENTRY']], 'PendingPropReqListHead' : [ 0xc4, ['_LIST_ENTRY']], 'CRMListEntry' : [ 0xcc, ['_LIST_ENTRY']], 'Tm' : [ 0xd4, ['pointer', ['_KTM']]], 'Description' : [ 0xd8, ['_UNICODE_STRING']], 'Enlistments' : [ 0xe0, ['_KTMOBJECT_NAMESPACE']], 'CompletionBinding' : [ 0x140, ['_KRESOURCEMANAGER_COMPLETION_BINDING']], } ], '_MMEXTEND_INFO' : [ 0x10, { 'CommittedSize' : [ 0x0, ['unsigned long long']], 'ReferenceCount' : [ 0x8, ['unsigned long']], } ], '_HANDLE_TABLE_FREE_LIST' : [ 0x34, { 'FreeListLock' : [ 0x0, ['_EX_PUSH_LOCK']], 'FirstFreeHandleEntry' : [ 0x4, ['pointer', ['_HANDLE_TABLE_ENTRY']]], 'LastFreeHandleEntry' : [ 0x8, ['pointer', ['_HANDLE_TABLE_ENTRY']]], 'HandleCount' : [ 0xc, ['long']], 'HighWaterMark' : [ 0x10, ['unsigned long']], 'Reserved' : [ 0x14, ['array', 8, ['unsigned long']]], } ], '_WHEAP_ERROR_RECORD_WRAPPER_FLAGS' : [ 0x4, { 'Preallocated' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]], 'FromPersistentStore' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]], 'PlatformPfaControl' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]], 'PlatformDirectedOffline' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned long')]], 'Reserved' : [ 0x0, ['BitField', dict(start_bit = 4, end_bit = 32, native_type='unsigned long')]], 'AsULONG' : [ 0x0, ['unsigned long']], } ], '_GDI_TEB_BATCH64' : [ 0x4e8, { 'Offset' : [ 0x0, ['unsigned long']], 'HDC' : [ 0x8, ['unsigned long long']], 'Buffer' : [ 0x10, ['array', 310, ['unsigned long']]], } ], '__unnamed_23ac' : [ 0x4, { 'NodeSize' : [ 0x0, ['unsigned long']], 'UseLookaside' : [ 0x0, ['unsigned long']], } ], '_VF_AVL_TREE' : [ 0x14, { 'NodeRangeSize' : [ 0x0, ['unsigned long']], 'NodeCount' : [ 0x4, ['unsigned long']], 'Tables' : [ 0x8, ['pointer', ['_VF_AVL_TABLE']]], 'TablesNo' : [ 0xc, ['unsigned long']], 'u1' : [ 0x10, ['__unnamed_23ac']], } ], '_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']], } ], '_WHEA_MEMORY_ERROR_SECTION_VALIDBITS' : [ 0x8, { 'ErrorStatus' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long long')]], 'PhysicalAddress' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long long')]], 'PhysicalAddressMask' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long long')]], 'Node' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned long long')]], 'Card' : [ 0x0, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned long long')]], 'Module' : [ 0x0, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned long long')]], 'Bank' : [ 0x0, ['BitField', dict(start_bit = 6, end_bit = 7, native_type='unsigned long long')]], 'Device' : [ 0x0, ['BitField', dict(start_bit = 7, end_bit = 8, native_type='unsigned long long')]], 'Row' : [ 0x0, ['BitField', dict(start_bit = 8, end_bit = 9, native_type='unsigned long long')]], 'Column' : [ 0x0, ['BitField', dict(start_bit = 9, end_bit = 10, native_type='unsigned long long')]], 'BitPosition' : [ 0x0, ['BitField', dict(start_bit = 10, end_bit = 11, native_type='unsigned long long')]], 'RequesterId' : [ 0x0, ['BitField', dict(start_bit = 11, end_bit = 12, native_type='unsigned long long')]], 'ResponderId' : [ 0x0, ['BitField', dict(start_bit = 12, end_bit = 13, native_type='unsigned long long')]], 'TargetId' : [ 0x0, ['BitField', dict(start_bit = 13, end_bit = 14, native_type='unsigned long long')]], 'ErrorType' : [ 0x0, ['BitField', dict(start_bit = 14, end_bit = 15, native_type='unsigned long long')]], 'Reserved' : [ 0x0, ['BitField', dict(start_bit = 15, end_bit = 64, native_type='unsigned long long')]], 'ValidBits' : [ 0x0, ['unsigned long long']], } ], '_AER_ENDPOINT_DESCRIPTOR_FLAGS' : [ 0x2, { 'UncorrectableErrorMaskRW' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned short')]], 'UncorrectableErrorSeverityRW' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned short')]], 'CorrectableErrorMaskRW' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned short')]], 'AdvancedCapsAndControlRW' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned short')]], 'Reserved' : [ 0x0, ['BitField', dict(start_bit = 4, end_bit = 16, native_type='unsigned short')]], 'AsUSHORT' : [ 0x0, ['unsigned short']], } ], '_RELATION_LIST_ENTRY' : [ 0xc, { 'Count' : [ 0x0, ['unsigned long']], 'MaxCount' : [ 0x4, ['unsigned long']], 'Devices' : [ 0x8, ['array', 1, ['pointer', ['_DEVICE_OBJECT']]]], } ], '_HEAP_FREE_ENTRY_EXTRA' : [ 0x4, { 'TagIndex' : [ 0x0, ['unsigned short']], 'FreeBackTraceIndex' : [ 0x2, ['unsigned short']], } ], '_PROC_PERF_HISTORY_ENTRY' : [ 0x6, { 'Utility' : [ 0x0, ['unsigned short']], 'AffinitizedUtility' : [ 0x2, ['unsigned short']], 'Frequency' : [ 0x4, ['unsigned char']], 'Reserved' : [ 0x5, ['unsigned char']], } ], '_POP_FX_COMPONENT' : [ 0x88, { 'Id' : [ 0x0, ['_GUID']], 'Index' : [ 0x10, ['unsigned long']], 'WorkOrder' : [ 0x14, ['_POP_FX_WORK_ORDER']], 'Device' : [ 0x28, ['pointer', ['_POP_FX_DEVICE']]], 'Flags' : [ 0x2c, ['_POP_FX_COMPONENT_FLAGS']], 'Resident' : [ 0x34, ['long']], 'ActiveEvent' : [ 0x38, ['_KEVENT']], 'IdleLock' : [ 0x48, ['unsigned long']], 'IdleConditionComplete' : [ 0x4c, ['long']], 'IdleStateComplete' : [ 0x50, ['long']], 'IdleStamp' : [ 0x58, ['unsigned long long']], 'CurrentIdleState' : [ 0x60, ['unsigned long']], 'IdleStateCount' : [ 0x64, ['unsigned long']], 'IdleStates' : [ 0x68, ['pointer', ['_POP_FX_IDLE_STATE']]], 'DeepestWakeableIdleState' : [ 0x6c, ['unsigned long']], 'ProviderCount' : [ 0x70, ['unsigned long']], 'Providers' : [ 0x74, ['pointer', ['_POP_FX_PROVIDER']]], 'IdleProviderCount' : [ 0x78, ['unsigned long']], 'DependentCount' : [ 0x7c, ['unsigned long']], 'Dependents' : [ 0x80, ['pointer', ['_POP_FX_DEPENDENT']]], } ], '_POP_FX_DRIVER_CALLBACKS' : [ 0x1c, { 'ComponentActive' : [ 0x0, ['pointer', ['void']]], 'ComponentIdle' : [ 0x4, ['pointer', ['void']]], 'ComponentIdleState' : [ 0x8, ['pointer', ['void']]], 'DevicePowerRequired' : [ 0xc, ['pointer', ['void']]], 'DevicePowerNotRequired' : [ 0x10, ['pointer', ['void']]], 'PowerControl' : [ 0x14, ['pointer', ['void']]], 'ComponentCriticalTransition' : [ 0x18, ['pointer', ['void']]], } ], '_PROVIDER_BINARY_ENTRY' : [ 0x2c, { 'ListEntry' : [ 0x0, ['_LIST_ENTRY']], 'ConsumersNotified' : [ 0x8, ['unsigned char']], 'Spare' : [ 0x9, ['array', 3, ['unsigned char']]], 'DebugIdSize' : [ 0xc, ['unsigned long']], 'DebugId' : [ 0x10, ['_CVDD']], } ], '_VI_DEADLOCK_GLOBALS' : [ 0x40e0, { 'TimeAcquire' : [ 0x0, ['long long']], 'TimeRelease' : [ 0x8, ['long long']], 'ResourceDatabase' : [ 0x10, ['pointer', ['_LIST_ENTRY']]], 'ResourceDatabaseCount' : [ 0x14, ['unsigned long']], 'ResourceAddressRange' : [ 0x18, ['array', 1023, ['_VF_ADDRESS_RANGE']]], 'ThreadDatabase' : [ 0x2010, ['pointer', ['_LIST_ENTRY']]], 'ThreadDatabaseCount' : [ 0x2014, ['unsigned long']], 'ThreadAddressRange' : [ 0x2018, ['array', 1023, ['_VF_ADDRESS_RANGE']]], 'AllocationFailures' : [ 0x4010, ['unsigned long']], 'NodesTrimmedBasedOnAge' : [ 0x4014, ['unsigned long']], 'NodesTrimmedBasedOnCount' : [ 0x4018, ['unsigned long']], 'NodesSearched' : [ 0x401c, ['unsigned long']], 'MaxNodesSearched' : [ 0x4020, ['unsigned long']], 'SequenceNumber' : [ 0x4024, ['unsigned long']], 'RecursionDepthLimit' : [ 0x4028, ['unsigned long']], 'SearchedNodesLimit' : [ 0x402c, ['unsigned long']], 'DepthLimitHits' : [ 0x4030, ['unsigned long']], 'SearchLimitHits' : [ 0x4034, ['unsigned long']], 'ABC_ACB_Skipped' : [ 0x4038, ['unsigned long']], 'OutOfOrderReleases' : [ 0x403c, ['unsigned long']], 'NodesReleasedOutOfOrder' : [ 0x4040, ['unsigned long']], 'TotalReleases' : [ 0x4044, ['unsigned long']], 'RootNodesDeleted' : [ 0x4048, ['unsigned long']], 'ForgetHistoryCounter' : [ 0x404c, ['unsigned long']], 'Instigator' : [ 0x4050, ['pointer', ['void']]], 'NumberOfParticipants' : [ 0x4054, ['unsigned long']], 'Participant' : [ 0x4058, ['array', 32, ['pointer', ['_VI_DEADLOCK_NODE']]]], 'ChildrenCountWatermark' : [ 0x40d8, ['long']], } ], '_KTM' : [ 0x238, { 'cookie' : [ 0x0, ['unsigned long']], 'Mutex' : [ 0x4, ['_KMUTANT']], 'State' : [ 0x24, ['Enumeration', dict(target = 'long', choices = {0: 'KKtmUninitialized', 1: 'KKtmInitialized', 2: 'KKtmRecovering', 3: 'KKtmOnline', 4: 'KKtmRecoveryFailed', 5: 'KKtmOffline'})]], 'NamespaceLink' : [ 0x28, ['_KTMOBJECT_NAMESPACE_LINK']], 'TmIdentity' : [ 0x3c, ['_GUID']], 'Flags' : [ 0x4c, ['unsigned long']], 'VolatileFlags' : [ 0x50, ['unsigned long']], 'LogFileName' : [ 0x54, ['_UNICODE_STRING']], 'LogFileObject' : [ 0x5c, ['pointer', ['_FILE_OBJECT']]], 'MarshallingContext' : [ 0x60, ['pointer', ['void']]], 'LogManagementContext' : [ 0x64, ['pointer', ['void']]], 'Transactions' : [ 0x68, ['_KTMOBJECT_NAMESPACE']], 'ResourceManagers' : [ 0xc8, ['_KTMOBJECT_NAMESPACE']], 'LsnOrderedMutex' : [ 0x128, ['_KMUTANT']], 'LsnOrderedList' : [ 0x148, ['_LIST_ENTRY']], 'CommitVirtualClock' : [ 0x150, ['_LARGE_INTEGER']], 'CommitVirtualClockMutex' : [ 0x158, ['_FAST_MUTEX']], 'BaseLsn' : [ 0x178, ['_CLS_LSN']], 'CurrentReadLsn' : [ 0x180, ['_CLS_LSN']], 'LastRecoveredLsn' : [ 0x188, ['_CLS_LSN']], 'TmRmHandle' : [ 0x190, ['pointer', ['void']]], 'TmRm' : [ 0x194, ['pointer', ['_KRESOURCEMANAGER']]], 'LogFullNotifyEvent' : [ 0x198, ['_KEVENT']], 'CheckpointWorkItem' : [ 0x1a8, ['_WORK_QUEUE_ITEM']], 'CheckpointTargetLsn' : [ 0x1b8, ['_CLS_LSN']], 'LogFullCompletedWorkItem' : [ 0x1c0, ['_WORK_QUEUE_ITEM']], 'LogWriteResource' : [ 0x1d0, ['_ERESOURCE']], 'LogFlags' : [ 0x208, ['unsigned long']], 'LogFullStatus' : [ 0x20c, ['long']], 'RecoveryStatus' : [ 0x210, ['long']], 'LastCheckBaseLsn' : [ 0x218, ['_CLS_LSN']], 'RestartOrderedList' : [ 0x220, ['_LIST_ENTRY']], 'OfflineWorkItem' : [ 0x228, ['_WORK_QUEUE_ITEM']], } ], '_VF_BTS_RECORD' : [ 0xc, { 'JumpedFrom' : [ 0x0, ['pointer', ['void']]], 'JumpedTo' : [ 0x4, ['pointer', ['void']]], 'Unused1' : [ 0x8, ['BitField', dict(start_bit = 0, end_bit = 3, native_type='unsigned long')]], 'Predicted' : [ 0x8, ['BitField', dict(start_bit = 3, end_bit = 7, native_type='unsigned long')]], 'Unused2' : [ 0x8, ['BitField', dict(start_bit = 7, end_bit = 32, native_type='unsigned long')]], } ], '_PLATFORM_IDLE_STATE_ACCOUNTING' : [ 0x370, { 'CancelCount' : [ 0x0, ['unsigned long']], 'FailureCount' : [ 0x4, ['unsigned long']], 'SuccessCount' : [ 0x8, ['unsigned long']], 'MaxTime' : [ 0x10, ['unsigned long long']], 'MinTime' : [ 0x18, ['unsigned long long']], 'TotalTime' : [ 0x20, ['unsigned long long']], 'InvalidBucketIndex' : [ 0x28, ['unsigned long']], 'IdleTimeBuckets' : [ 0x30, ['array', 26, ['_PROC_IDLE_STATE_BUCKET']]], } ], '_KTRANSACTION' : [ 0x1e0, { 'OutcomeEvent' : [ 0x0, ['_KEVENT']], 'cookie' : [ 0x10, ['unsigned long']], 'Mutex' : [ 0x14, ['_KMUTANT']], 'TreeTx' : [ 0x34, ['pointer', ['_KTRANSACTION']]], 'GlobalNamespaceLink' : [ 0x38, ['_KTMOBJECT_NAMESPACE_LINK']], 'TmNamespaceLink' : [ 0x4c, ['_KTMOBJECT_NAMESPACE_LINK']], 'UOW' : [ 0x60, ['_GUID']], 'State' : [ 0x70, ['Enumeration', dict(target = 'long', choices = {0: 'KTransactionUninitialized', 1: 'KTransactionActive', 2: 'KTransactionPreparing', 3: 'KTransactionPrepared', 4: 'KTransactionInDoubt', 5: 'KTransactionCommitted', 6: 'KTransactionAborted', 7: 'KTransactionDelegated', 8: 'KTransactionPrePreparing', 9: 'KTransactionForgotten', 10: 'KTransactionRecovering', 11: 'KTransactionPrePrepared'})]], 'Flags' : [ 0x74, ['unsigned long']], 'EnlistmentHead' : [ 0x78, ['_LIST_ENTRY']], 'EnlistmentCount' : [ 0x80, ['unsigned long']], 'RecoverableEnlistmentCount' : [ 0x84, ['unsigned long']], 'PrePrepareRequiredEnlistmentCount' : [ 0x88, ['unsigned long']], 'PrepareRequiredEnlistmentCount' : [ 0x8c, ['unsigned long']], 'OutcomeRequiredEnlistmentCount' : [ 0x90, ['unsigned long']], 'PendingResponses' : [ 0x94, ['unsigned long']], 'SuperiorEnlistment' : [ 0x98, ['pointer', ['_KENLISTMENT']]], 'LastLsn' : [ 0xa0, ['_CLS_LSN']], 'PromotedEntry' : [ 0xa8, ['_LIST_ENTRY']], 'PromoterTransaction' : [ 0xb0, ['pointer', ['_KTRANSACTION']]], 'PromotePropagation' : [ 0xb4, ['pointer', ['void']]], 'IsolationLevel' : [ 0xb8, ['unsigned long']], 'IsolationFlags' : [ 0xbc, ['unsigned long']], 'Timeout' : [ 0xc0, ['_LARGE_INTEGER']], 'Description' : [ 0xc8, ['_UNICODE_STRING']], 'RollbackThread' : [ 0xd0, ['pointer', ['_KTHREAD']]], 'RollbackWorkItem' : [ 0xd4, ['_WORK_QUEUE_ITEM']], 'RollbackDpc' : [ 0xe4, ['_KDPC']], 'RollbackTimer' : [ 0x108, ['_KTIMER']], 'LsnOrderedEntry' : [ 0x130, ['_LIST_ENTRY']], 'Outcome' : [ 0x138, ['Enumeration', dict(target = 'long', choices = {0: 'KTxOutcomeUninitialized', 1: 'KTxOutcomeUndetermined', 2: 'KTxOutcomeCommitted', 3: 'KTxOutcomeAborted', 4: 'KTxOutcomeUnavailable'})]], 'Tm' : [ 0x13c, ['pointer', ['_KTM']]], 'CommitReservation' : [ 0x140, ['long long']], 'TransactionHistory' : [ 0x148, ['array', 10, ['_KTRANSACTION_HISTORY']]], 'TransactionHistoryCount' : [ 0x198, ['unsigned long']], 'DTCPrivateInformation' : [ 0x19c, ['pointer', ['void']]], 'DTCPrivateInformationLength' : [ 0x1a0, ['unsigned long']], 'DTCPrivateInformationMutex' : [ 0x1a4, ['_KMUTANT']], 'PromotedTxSelfHandle' : [ 0x1c4, ['pointer', ['void']]], 'PendingPromotionCount' : [ 0x1c8, ['unsigned long']], 'PromotionCompletedEvent' : [ 0x1cc, ['_KEVENT']], } ], '_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')]], 'PagePriority' : [ 0x0, ['BitField', dict(start_bit = 18, end_bit = 21, native_type='unsigned long')]], 'PipelineReadAheads' : [ 0x0, ['BitField', dict(start_bit = 21, end_bit = 22, native_type='unsigned long')]], 'Available' : [ 0x0, ['BitField', dict(start_bit = 22, end_bit = 32, native_type='unsigned long')]], } ], '_CM_KCB_UOW' : [ 0x38, { 'TransactionListEntry' : [ 0x0, ['_LIST_ENTRY']], 'KCBLock' : [ 0x8, ['pointer', ['_CM_INTENT_LOCK']]], 'KeyLock' : [ 0xc, ['pointer', ['_CM_INTENT_LOCK']]], 'KCBListEntry' : [ 0x10, ['_LIST_ENTRY']], 'KeyControlBlock' : [ 0x18, ['pointer', ['_CM_KEY_CONTROL_BLOCK']]], 'Transaction' : [ 0x1c, ['pointer', ['_CM_TRANS']]], 'UoWState' : [ 0x20, ['unsigned long']], 'ActionType' : [ 0x24, ['Enumeration', dict(target = 'long', choices = {0: 'UoWAddThisKey', 1: 'UoWAddChildKey', 2: 'UoWDeleteThisKey', 3: 'UoWDeleteChildKey', 4: 'UoWSetValueNew', 5: 'UoWSetValueExisting', 6: 'UoWDeleteValue', 7: 'UoWSetKeyUserFlags', 8: 'UoWSetLastWriteTime', 9: 'UoWSetSecurityDescriptor', 10: 'UoWRenameSubKey', 11: 'UoWRenameOldSubKey', 12: 'UoWRenameNewSubKey', 13: 'UoWIsolation', 14: 'UoWInvalid'})]], 'StorageType' : [ 0x28, ['Enumeration', dict(target = 'long', choices = {0: 'Stable', 1: 'Volatile', 2: 'InvalidStorage'})]], 'ChildKCB' : [ 0x30, ['pointer', ['_CM_KEY_CONTROL_BLOCK']]], 'VolatileKeyCell' : [ 0x30, ['unsigned long']], 'OldValueCell' : [ 0x30, ['unsigned long']], 'NewValueCell' : [ 0x34, ['unsigned long']], 'UserFlags' : [ 0x30, ['unsigned long']], 'LastWriteTime' : [ 0x30, ['_LARGE_INTEGER']], 'TxSecurityCell' : [ 0x30, ['unsigned long']], 'OldChildKCB' : [ 0x30, ['pointer', ['_CM_KEY_CONTROL_BLOCK']]], 'NewChildKCB' : [ 0x34, ['pointer', ['_CM_KEY_CONTROL_BLOCK']]], 'OtherChildKCB' : [ 0x30, ['pointer', ['_CM_KEY_CONTROL_BLOCK']]], 'ThisVolatileKeyCell' : [ 0x34, ['unsigned long']], } ], '_KPROCESSOR_STATE' : [ 0x320, { 'ContextFrame' : [ 0x0, ['_CONTEXT']], 'SpecialRegisters' : [ 0x2cc, ['_KSPECIAL_REGISTERS']], } ], '_MMPTE_TRANSITION' : [ 0x8, { 'Valid' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long long')]], 'Write' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long long')]], 'Spare' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long long')]], 'WriteThrough' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned long long')]], 'CacheDisable' : [ 0x0, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned long long')]], 'Protection' : [ 0x0, ['BitField', dict(start_bit = 5, end_bit = 10, native_type='unsigned long long')]], 'Prototype' : [ 0x0, ['BitField', dict(start_bit = 10, end_bit = 11, native_type='unsigned long long')]], 'Transition' : [ 0x0, ['BitField', dict(start_bit = 11, end_bit = 12, native_type='unsigned long long')]], 'PageFrameNumber' : [ 0x0, ['BitField', dict(start_bit = 12, end_bit = 38, native_type='unsigned long long')]], 'Unused' : [ 0x0, ['BitField', dict(start_bit = 38, end_bit = 64, native_type='unsigned long long')]], } ], '_PROCESSOR_IDLE_CONSTRAINTS' : [ 0x30, { 'TotalTime' : [ 0x0, ['unsigned long long']], 'IdleTime' : [ 0x8, ['unsigned long long']], 'ExpectedIdleDuration' : [ 0x10, ['unsigned long long']], 'MaxIdleDuration' : [ 0x18, ['unsigned long']], 'OverrideState' : [ 0x1c, ['unsigned long']], 'TimeCheck' : [ 0x20, ['unsigned long']], 'PromotePercent' : [ 0x24, ['unsigned char']], 'DemotePercent' : [ 0x25, ['unsigned char']], 'Parked' : [ 0x26, ['unsigned char']], 'Interruptible' : [ 0x27, ['unsigned char']], 'PlatformIdle' : [ 0x28, ['unsigned char']], } ], '_VF_WATCHDOG_IRP' : [ 0x14, { 'ListEntry' : [ 0x0, ['_LIST_ENTRY']], 'Irp' : [ 0x8, ['pointer', ['_IRP']]], 'DueTickCount' : [ 0xc, ['unsigned long']], 'Inserted' : [ 0x10, ['unsigned char']], 'TrackedStackLocation' : [ 0x11, ['unsigned char']], 'CancelTimeoutTicks' : [ 0x12, ['unsigned short']], } ], '_MMVAD_FLAGS2' : [ 0x4, { 'FileOffset' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 24, native_type='unsigned long')]], 'Large' : [ 0x0, ['BitField', dict(start_bit = 24, end_bit = 25, native_type='unsigned long')]], 'TrimBehind' : [ 0x0, ['BitField', dict(start_bit = 25, end_bit = 26, native_type='unsigned long')]], 'Inherit' : [ 0x0, ['BitField', dict(start_bit = 26, end_bit = 27, native_type='unsigned long')]], 'CopyOnWrite' : [ 0x0, ['BitField', dict(start_bit = 27, end_bit = 28, native_type='unsigned long')]], 'NoValidationNeeded' : [ 0x0, ['BitField', dict(start_bit = 28, end_bit = 29, native_type='unsigned long')]], 'Spare' : [ 0x0, ['BitField', dict(start_bit = 29, end_bit = 32, native_type='unsigned long')]], } ], '_flags' : [ 0x1, { 'Removable' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned char')]], 'GroupAssigned' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned char')]], 'GroupCommitted' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned char')]], 'GroupAssignmentFixed' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned char')]], 'Fill' : [ 0x0, ['BitField', dict(start_bit = 4, end_bit = 8, native_type='unsigned char')]], } ], '__unnamed_240e' : [ 0x8, { 'Head' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 24, native_type='unsigned long long')]], 'Tail' : [ 0x0, ['BitField', dict(start_bit = 24, end_bit = 48, native_type='unsigned long long')]], 'ActiveThreadCount' : [ 0x0, ['BitField', dict(start_bit = 48, end_bit = 64, native_type='unsigned long long')]], } ], '__unnamed_2410' : [ 0x8, { 's1' : [ 0x0, ['__unnamed_240e']], 'Value' : [ 0x0, ['long long']], } ], '_ALPC_COMPLETION_LIST_STATE' : [ 0x8, { 'u1' : [ 0x0, ['__unnamed_2410']], } ], '_CM_KEY_SECURITY_CACHE' : [ 0x2c, { 'Cell' : [ 0x0, ['unsigned long']], 'ConvKey' : [ 0x4, ['unsigned long']], 'List' : [ 0x8, ['_LIST_ENTRY']], 'DescriptorLength' : [ 0x10, ['unsigned long']], 'RealRefCount' : [ 0x14, ['unsigned long']], 'Descriptor' : [ 0x18, ['_SECURITY_DESCRIPTOR_RELATIVE']], } ], '_CM_NAME_HASH' : [ 0xc, { 'ConvKey' : [ 0x0, ['unsigned long']], 'NextHash' : [ 0x4, ['pointer', ['_CM_NAME_HASH']]], 'NameLength' : [ 0x8, ['unsigned short']], 'Name' : [ 0xa, ['array', 1, ['wchar']]], } ], '_PROC_IDLE_STATE_BUCKET' : [ 0x20, { 'TotalTime' : [ 0x0, ['unsigned long long']], 'MinTime' : [ 0x8, ['unsigned long long']], 'MaxTime' : [ 0x10, ['unsigned long long']], 'Count' : [ 0x18, ['unsigned long']], } ], '_PO_IRP_QUEUE' : [ 0x8, { 'CurrentIrp' : [ 0x0, ['pointer', ['_IRP']]], 'PendingIrpList' : [ 0x4, ['pointer', ['_IRP']]], } ], '__unnamed_2422' : [ 0x4, { 'Active' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]], 'OnlyTryAcquireUsed' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]], 'ReleasedOutOfOrder' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]], 'SequenceNumber' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 32, native_type='unsigned long')]], 'Whole' : [ 0x0, ['unsigned long']], } ], '_VI_DEADLOCK_NODE' : [ 0x6c, { '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']]], 'u1' : [ 0x24, ['__unnamed_2422']], 'ChildrenCount' : [ 0x28, ['long']], 'StackTrace' : [ 0x2c, ['array', 8, ['pointer', ['void']]]], 'ParentStackTrace' : [ 0x4c, ['array', 8, ['pointer', ['void']]]], } ], 'PROCESSOR_IDLESTATE_INFO' : [ 0x8, { 'TimeCheck' : [ 0x0, ['unsigned long']], 'DemotePercent' : [ 0x4, ['unsigned char']], 'PromotePercent' : [ 0x5, ['unsigned char']], 'Spare' : [ 0x6, ['array', 2, ['unsigned char']]], } ], '_KTMOBJECT_NAMESPACE' : [ 0x60, { 'Table' : [ 0x0, ['_RTL_AVL_TABLE']], 'Mutex' : [ 0x38, ['_KMUTANT']], 'LinksOffset' : [ 0x58, ['unsigned short']], 'GuidOffset' : [ 0x5a, ['unsigned short']], 'Expired' : [ 0x5c, ['unsigned char']], } ], '_LPCP_PORT_QUEUE' : [ 0x10, { 'NonPagedPortQueue' : [ 0x0, ['pointer', ['_LPCP_NONPAGED_PORT_QUEUE']]], 'Semaphore' : [ 0x4, ['pointer', ['_KSEMAPHORE']]], 'ReceiveHead' : [ 0x8, ['_LIST_ENTRY']], } ], '_CM_KEY_REFERENCE' : [ 0x8, { 'KeyCell' : [ 0x0, ['unsigned long']], 'KeyHive' : [ 0x4, ['pointer', ['_HHIVE']]], } ], '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'})]], } ], '_OBJECT_DUMP_CONTROL' : [ 0x8, { 'Stream' : [ 0x0, ['pointer', ['void']]], 'Detail' : [ 0x4, ['unsigned long']], } ], '_EVENT_HEADER_EXTENDED_DATA_ITEM' : [ 0x10, { 'Reserved1' : [ 0x0, ['unsigned short']], 'ExtType' : [ 0x2, ['unsigned short']], 'Linkage' : [ 0x4, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned short')]], 'Reserved2' : [ 0x4, ['BitField', dict(start_bit = 1, end_bit = 16, native_type='unsigned short')]], 'DataSize' : [ 0x6, ['unsigned short']], 'DataPtr' : [ 0x8, ['unsigned long long']], } ], '_VF_ADDRESS_RANGE' : [ 0x8, { 'Start' : [ 0x0, ['pointer', ['unsigned char']]], 'End' : [ 0x4, ['pointer', ['unsigned char']]], } ], '_OBJECT_SYMBOLIC_LINK' : [ 0x18, { 'CreationTime' : [ 0x0, ['_LARGE_INTEGER']], 'LinkTarget' : [ 0x8, ['_UNICODE_STRING']], 'DosDeviceDriveIndex' : [ 0x10, ['unsigned long']], } ], '_LPCP_NONPAGED_PORT_QUEUE' : [ 0x18, { 'Semaphore' : [ 0x0, ['_KSEMAPHORE']], 'BackPointer' : [ 0x14, ['pointer', ['_LPCP_PORT_OBJECT']]], } ], '_KRESOURCEMANAGER_COMPLETION_BINDING' : [ 0x14, { 'NotificationListHead' : [ 0x0, ['_LIST_ENTRY']], 'Port' : [ 0x8, ['pointer', ['void']]], 'Key' : [ 0xc, ['unsigned long']], 'BindingProcess' : [ 0x10, ['pointer', ['_EPROCESS']]], } ], '_VF_TRACKER' : [ 0x10, { 'TrackerFlags' : [ 0x0, ['unsigned long']], 'TrackerSize' : [ 0x4, ['unsigned long']], 'TrackerIndex' : [ 0x8, ['unsigned long']], 'TraceDepth' : [ 0xc, ['unsigned long']], } ], '_CALL_PERFORMANCE_DATA' : [ 0x204, { 'SpinLock' : [ 0x0, ['unsigned long']], 'HashTable' : [ 0x4, ['array', 64, ['_LIST_ENTRY']]], } ], '_ARBITER_ALTERNATIVE' : [ 0x38, { 'Minimum' : [ 0x0, ['unsigned long long']], 'Maximum' : [ 0x8, ['unsigned long long']], 'Length' : [ 0x10, ['unsigned long long']], 'Alignment' : [ 0x18, ['unsigned long long']], 'Priority' : [ 0x20, ['long']], 'Flags' : [ 0x24, ['unsigned long']], 'Descriptor' : [ 0x28, ['pointer', ['_IO_RESOURCE_DESCRIPTOR']]], 'Reserved' : [ 0x2c, ['array', 3, ['unsigned long']]], } ], '_WHEA_ERROR_STATUS' : [ 0x8, { 'ErrorStatus' : [ 0x0, ['unsigned long long']], 'Reserved1' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 8, native_type='unsigned long long')]], 'ErrorType' : [ 0x0, ['BitField', dict(start_bit = 8, end_bit = 16, native_type='unsigned long long')]], 'Address' : [ 0x0, ['BitField', dict(start_bit = 16, end_bit = 17, native_type='unsigned long long')]], 'Control' : [ 0x0, ['BitField', dict(start_bit = 17, end_bit = 18, native_type='unsigned long long')]], 'Data' : [ 0x0, ['BitField', dict(start_bit = 18, end_bit = 19, native_type='unsigned long long')]], 'Responder' : [ 0x0, ['BitField', dict(start_bit = 19, end_bit = 20, native_type='unsigned long long')]], 'Requester' : [ 0x0, ['BitField', dict(start_bit = 20, end_bit = 21, native_type='unsigned long long')]], 'FirstError' : [ 0x0, ['BitField', dict(start_bit = 21, end_bit = 22, native_type='unsigned long long')]], 'Overflow' : [ 0x0, ['BitField', dict(start_bit = 22, end_bit = 23, native_type='unsigned long long')]], 'Reserved2' : [ 0x0, ['BitField', dict(start_bit = 23, end_bit = 64, native_type='unsigned long long')]], } ], '_WHEA_PERSISTENCE_INFO' : [ 0x8, { 'Signature' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 16, native_type='unsigned long long')]], 'Length' : [ 0x0, ['BitField', dict(start_bit = 16, end_bit = 40, native_type='unsigned long long')]], 'Identifier' : [ 0x0, ['BitField', dict(start_bit = 40, end_bit = 56, native_type='unsigned long long')]], 'Attributes' : [ 0x0, ['BitField', dict(start_bit = 56, end_bit = 58, native_type='unsigned long long')]], 'DoNotLog' : [ 0x0, ['BitField', dict(start_bit = 58, end_bit = 59, native_type='unsigned long long')]], 'Reserved' : [ 0x0, ['BitField', dict(start_bit = 59, end_bit = 64, native_type='unsigned long long')]], 'AsULONGLONG' : [ 0x0, ['unsigned long long']], } ], '_MI_SECTION_IMAGE_INFORMATION' : [ 0x38, { 'ExportedImageInformation' : [ 0x0, ['_SECTION_IMAGE_INFORMATION']], 'InternalImageInformation' : [ 0x30, ['_MI_EXTRA_IMAGE_INFORMATION']], } ], '_STACK_TABLE' : [ 0x8040, { 'NumStackTraces' : [ 0x0, ['unsigned short']], 'TraceCapacity' : [ 0x2, ['unsigned short']], 'StackTrace' : [ 0x4, ['array', 16, ['pointer', ['_OBJECT_REF_TRACE']]]], 'StackTableHash' : [ 0x44, ['array', 16381, ['unsigned short']]], } ], '_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']], } ], '_ETW_GUID_ENTRY' : [ 0x160, { 'GuidList' : [ 0x0, ['_LIST_ENTRY']], 'RefCount' : [ 0x8, ['long']], 'Guid' : [ 0xc, ['_GUID']], 'RegListHead' : [ 0x1c, ['_LIST_ENTRY']], 'SecurityDescriptor' : [ 0x24, ['pointer', ['void']]], 'LastEnable' : [ 0x28, ['_ETW_LAST_ENABLE_INFO']], 'MatchId' : [ 0x28, ['unsigned long long']], 'ProviderEnableInfo' : [ 0x38, ['_TRACE_ENABLE_INFO']], 'EnableInfo' : [ 0x58, ['array', 8, ['_TRACE_ENABLE_INFO']]], 'FilterData' : [ 0x158, ['pointer', ['pointer', ['_EVENT_FILTER_HEADER']]]], } ], '_DEFERRED_WRITE' : [ 0x24, { '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']]], } ], '__unnamed_247a' : [ 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_247c' : [ 0x4, { 'bits' : [ 0x0, ['__unnamed_247a']], 'AsULONG' : [ 0x0, ['unsigned long']], } ], '_WHEA_PCI_SLOT_NUMBER' : [ 0x4, { 'u' : [ 0x0, ['__unnamed_247c']], } ], '_PNP_RESERVED_PROVIDER_INFO' : [ 0x1c, { 'ListEntry' : [ 0x0, ['_LIST_ENTRY']], 'DependentList' : [ 0x8, ['_LIST_ENTRY']], 'ReservationId' : [ 0x10, ['_UNICODE_STRING']], 'ReferenceCount' : [ 0x18, ['long']], } ], '_ARBITER_ORDERING_LIST' : [ 0x8, { 'Count' : [ 0x0, ['unsigned short']], 'Maximum' : [ 0x2, ['unsigned short']], 'Orderings' : [ 0x4, ['pointer', ['_ARBITER_ORDERING']]], } ], '_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']], 'ImageFlags' : [ 0x23, ['unsigned char']], 'ComPlusNativeReady' : [ 0x23, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned char')]], 'ComPlusILOnly' : [ 0x23, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned char')]], 'ImageDynamicallyRelocated' : [ 0x23, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned char')]], 'ImageMappedFlat' : [ 0x23, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned char')]], 'BaseBelow4gb' : [ 0x23, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned char')]], 'Reserved' : [ 0x23, ['BitField', dict(start_bit = 5, end_bit = 8, native_type='unsigned char')]], 'LoaderFlags' : [ 0x24, ['unsigned long']], 'ImageFileSize' : [ 0x28, ['unsigned long']], 'CheckSum' : [ 0x2c, ['unsigned long']], } ], '_VF_AVL_TABLE' : [ 0x80, { 'RtlTable' : [ 0x0, ['_RTL_AVL_TABLE']], 'ReservedNode' : [ 0x38, ['pointer', ['_VF_AVL_TREE_NODE']]], 'NodeToFree' : [ 0x3c, ['pointer', ['void']]], 'Lock' : [ 0x40, ['long']], } ], '_XPF_MC_BANK_FLAGS' : [ 0x1, { 'ClearOnInitializationRW' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned char')]], 'ControlDataRW' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned char')]], 'Reserved' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 8, native_type='unsigned char')]], 'AsUCHAR' : [ 0x0, ['unsigned char']], } ], '_TOKEN_AUDIT_POLICY' : [ 0x1d, { 'PerUserPolicy' : [ 0x0, ['array', 29, ['unsigned char']]], } ], '_ETW_LAST_ENABLE_INFO' : [ 0x10, { 'EnableFlags' : [ 0x0, ['_LARGE_INTEGER']], 'LoggerId' : [ 0x8, ['unsigned short']], 'Level' : [ 0xa, ['unsigned char']], 'Enabled' : [ 0xb, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned char')]], 'InternalFlag' : [ 0xb, ['BitField', dict(start_bit = 1, end_bit = 8, native_type='unsigned char')]], } ], '__unnamed_2492' : [ 0x8, { 'EndingOffset' : [ 0x0, ['pointer', ['_LARGE_INTEGER']]], 'ResourceToRelease' : [ 0x4, ['pointer', ['pointer', ['_ERESOURCE']]]], } ], '__unnamed_2494' : [ 0x4, { 'ResourceToRelease' : [ 0x0, ['pointer', ['_ERESOURCE']]], } ], '__unnamed_2498' : [ 0x8, { 'SyncType' : [ 0x0, ['Enumeration', dict(target = 'long', choices = {0: 'SyncTypeOther', 1: 'SyncTypeCreateSection'})]], 'PageProtection' : [ 0x4, ['unsigned long']], } ], '__unnamed_249c' : [ 0x8, { 'NotificationType' : [ 0x0, ['Enumeration', dict(target = 'long', choices = {0: 'NotifyTypeCreate', 1: 'NotifyTypeRetired'})]], 'SafeToRecurse' : [ 0x4, ['unsigned char']], } ], '__unnamed_249e' : [ 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_2492']], 'ReleaseForModifiedPageWriter' : [ 0x0, ['__unnamed_2494']], 'AcquireForSectionSynchronization' : [ 0x0, ['__unnamed_2498']], 'NotifyStreamFileObject' : [ 0x0, ['__unnamed_249c']], 'Others' : [ 0x0, ['__unnamed_249e']], } ], '_MI_SESSION_DRIVER_UNLOAD' : [ 0x4, { 'Function' : [ 0x0, ['pointer', ['void']]], 'FunctionValue' : [ 0x0, ['unsigned long']], } ], '_LDR_SERVICE_TAG_RECORD' : [ 0x8, { 'Next' : [ 0x0, ['pointer', ['_LDR_SERVICE_TAG_RECORD']]], 'ServiceTag' : [ 0x4, ['unsigned long']], } ], '_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']]], } ], '_HIVE_WAIT_PACKET' : [ 0x1c, { 'WakeEvent' : [ 0x0, ['_KEVENT']], 'Status' : [ 0x10, ['long']], 'Next' : [ 0x14, ['pointer', ['_HIVE_WAIT_PACKET']]], 'PrimaryFileWritten' : [ 0x18, ['unsigned char']], } ], '__unnamed_24ab' : [ 0x4, { 'PollInterval' : [ 0x0, ['unsigned long']], } ], '__unnamed_24ad' : [ 0x18, { 'PollInterval' : [ 0x0, ['unsigned long']], 'Vector' : [ 0x4, ['unsigned long']], 'SwitchToPollingThreshold' : [ 0x8, ['unsigned long']], 'SwitchToPollingWindow' : [ 0xc, ['unsigned long']], 'ErrorThreshold' : [ 0x10, ['unsigned long']], 'ErrorThresholdWindow' : [ 0x14, ['unsigned long']], } ], '__unnamed_24af' : [ 0x18, { 'Polled' : [ 0x0, ['__unnamed_24ab']], 'Interrupt' : [ 0x0, ['__unnamed_24ad']], 'LocalInterrupt' : [ 0x0, ['__unnamed_24ad']], 'Sci' : [ 0x0, ['__unnamed_24ad']], 'Nmi' : [ 0x0, ['__unnamed_24ad']], } ], '_WHEA_NOTIFICATION_DESCRIPTOR' : [ 0x1c, { 'Type' : [ 0x0, ['unsigned char']], 'Length' : [ 0x1, ['unsigned char']], 'Flags' : [ 0x2, ['_WHEA_NOTIFICATION_FLAGS']], 'u' : [ 0x4, ['__unnamed_24af']], } ], '_POP_HIBER_CONTEXT' : [ 0x120, { 'Reset' : [ 0x0, ['unsigned char']], 'HiberFlags' : [ 0x1, ['unsigned char']], 'WroteHiberFile' : [ 0x2, ['unsigned char']], 'VerifyKernelPhaseOnResume' : [ 0x3, ['unsigned char']], 'KernelPhaseVerificationActive' : [ 0x4, ['unsigned char']], 'InitializationFinished' : [ 0x5, ['unsigned char']], 'NextTableLockHeld' : [ 0x8, ['long']], 'BootPhaseFinishedBarrier' : [ 0xc, ['long']], 'KernelResumeFinishedBarrier' : [ 0x10, ['long']], 'MapFrozen' : [ 0x14, ['unsigned char']], 'DiscardMap' : [ 0x18, ['_RTL_BITMAP']], 'KernelPhaseMap' : [ 0x18, ['_RTL_BITMAP']], 'BootPhaseMap' : [ 0x20, ['_RTL_BITMAP']], 'ClonedRanges' : [ 0x28, ['_LIST_ENTRY']], 'ClonedRangeCount' : [ 0x30, ['unsigned long']], 'ClonedPageCount' : [ 0x38, ['unsigned long long']], 'CurrentMap' : [ 0x40, ['pointer', ['_RTL_BITMAP']]], 'NextCloneRange' : [ 0x44, ['pointer', ['_LIST_ENTRY']]], 'NextPreserve' : [ 0x48, ['unsigned long']], 'LoaderMdl' : [ 0x4c, ['pointer', ['_MDL']]], 'AllocatedMdl' : [ 0x50, ['pointer', ['_MDL']]], 'PagesOut' : [ 0x58, ['unsigned long long']], 'IoPages' : [ 0x60, ['pointer', ['void']]], 'IoPagesCount' : [ 0x64, ['unsigned long']], 'CurrentMcb' : [ 0x68, ['pointer', ['void']]], 'DumpStack' : [ 0x6c, ['pointer', ['_DUMP_STACK_CONTEXT']]], 'WakeState' : [ 0x70, ['pointer', ['_KPROCESSOR_STATE']]], 'IoProgress' : [ 0x74, ['unsigned long']], 'Status' : [ 0x78, ['long']], 'GraphicsProc' : [ 0x7c, ['unsigned long']], 'MemoryImage' : [ 0x80, ['pointer', ['PO_MEMORY_IMAGE']]], 'PerformanceStats' : [ 0x84, ['pointer', ['unsigned long']]], 'BootLoaderLogMdl' : [ 0x88, ['pointer', ['_MDL']]], 'SiLogOffset' : [ 0x8c, ['unsigned long']], 'FirmwareRuntimeInformationMdl' : [ 0x90, ['pointer', ['_MDL']]], 'FirmwareRuntimeInformationVa' : [ 0x94, ['pointer', ['void']]], 'ResumeContext' : [ 0x98, ['pointer', ['void']]], 'ResumeContextPages' : [ 0x9c, ['unsigned long']], 'ProcessorCount' : [ 0xa0, ['unsigned long']], 'ProcessorContext' : [ 0xa4, ['pointer', ['_POP_PER_PROCESSOR_CONTEXT']]], 'ProdConsBuffer' : [ 0xa8, ['pointer', ['unsigned char']]], 'ProdConsSize' : [ 0xac, ['unsigned long']], 'MaxDataPages' : [ 0xb0, ['unsigned long']], 'ExtraBuffer' : [ 0xb4, ['pointer', ['void']]], 'ExtraBufferSize' : [ 0xb8, ['unsigned long']], 'ExtraMapVa' : [ 0xbc, ['pointer', ['void']]], 'BitlockerKeyPFN' : [ 0xc0, ['unsigned long']], 'IoInfo' : [ 0xc8, ['_POP_IO_INFO']], 'HardwareConfigurationSignature' : [ 0x118, ['unsigned long']], } ], '_OBJECT_REF_TRACE' : [ 0x40, { 'StackTrace' : [ 0x0, ['array', 16, ['pointer', ['void']]]], } ], '_CVDD' : [ 0x1c, { 'Signature' : [ 0x0, ['unsigned long']], 'NB10' : [ 0x0, ['_NB10']], 'RsDs' : [ 0x0, ['_RSDS']], } ], '_OBJECT_NAME_INFORMATION' : [ 0x8, { 'Name' : [ 0x0, ['_UNICODE_STRING']], } ], '_WHEA_AER_BRIDGE_DESCRIPTOR' : [ 0x2c, { 'Type' : [ 0x0, ['unsigned short']], 'Enabled' : [ 0x2, ['unsigned char']], 'Reserved' : [ 0x3, ['unsigned char']], 'BusNumber' : [ 0x4, ['unsigned long']], 'Slot' : [ 0x8, ['_WHEA_PCI_SLOT_NUMBER']], 'DeviceControl' : [ 0xc, ['unsigned short']], 'Flags' : [ 0xe, ['_AER_BRIDGE_DESCRIPTOR_FLAGS']], 'UncorrectableErrorMask' : [ 0x10, ['unsigned long']], 'UncorrectableErrorSeverity' : [ 0x14, ['unsigned long']], 'CorrectableErrorMask' : [ 0x18, ['unsigned long']], 'AdvancedCapsAndControl' : [ 0x1c, ['unsigned long']], 'SecondaryUncorrectableErrorMask' : [ 0x20, ['unsigned long']], 'SecondaryUncorrectableErrorSev' : [ 0x24, ['unsigned long']], 'SecondaryCapsAndControl' : [ 0x28, ['unsigned long']], } ], '_PCW_COUNTER_INFORMATION' : [ 0x10, { 'CounterMask' : [ 0x0, ['unsigned long long']], 'InstanceMask' : [ 0x8, ['pointer', ['_UNICODE_STRING']]], } ], '_DUMP_STACK_CONTEXT' : [ 0x100, { 'Init' : [ 0x0, ['_DUMP_INITIALIZATION_CONTEXT']], 'PartitionOffset' : [ 0xc0, ['_LARGE_INTEGER']], 'DumpPointers' : [ 0xc8, ['pointer', ['void']]], 'PointersLength' : [ 0xcc, ['unsigned long']], 'ModulePrefix' : [ 0xd0, ['pointer', ['unsigned short']]], 'DriverList' : [ 0xd4, ['_LIST_ENTRY']], 'InitMsg' : [ 0xdc, ['_STRING']], 'ProgMsg' : [ 0xe4, ['_STRING']], 'DoneMsg' : [ 0xec, ['_STRING']], 'FileObject' : [ 0xf4, ['pointer', ['void']]], 'UsageType' : [ 0xf8, ['Enumeration', dict(target = 'long', choices = {0: 'DeviceUsageTypeUndefined', 1: 'DeviceUsageTypePaging', 2: 'DeviceUsageTypeHibernation', 3: 'DeviceUsageTypeDumpFile', 4: 'DeviceUsageTypeBoot', 5: 'DeviceUsageTypePostDisplay'})]], } ], '_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' : [ 0x24, { 'InitiatingThread' : [ 0x0, ['pointer', ['_ETHREAD']]], 'InitiatingProcess' : [ 0x4, ['pointer', ['_EPROCESS']]], 'ThreadId' : [ 0x8, ['pointer', ['void']]], 'ProcessId' : [ 0xc, ['pointer', ['void']]], 'Code' : [ 0x10, ['unsigned long']], 'Parameter1' : [ 0x14, ['unsigned long']], 'Parameter2' : [ 0x18, ['unsigned long']], 'Parameter3' : [ 0x1c, ['unsigned long']], 'Parameter4' : [ 0x20, ['unsigned long']], } ], '_NB10' : [ 0x14, { 'Signature' : [ 0x0, ['unsigned long']], 'Offset' : [ 0x4, ['unsigned long']], 'TimeStamp' : [ 0x8, ['unsigned long']], 'Age' : [ 0xc, ['unsigned long']], 'PdbName' : [ 0x10, ['array', 1, ['unsigned char']]], } ], '_MI_EXTRA_IMAGE_INFORMATION' : [ 0x8, { 'SizeOfHeaders' : [ 0x0, ['unsigned long']], 'SizeOfImage' : [ 0x4, ['unsigned long']], } ], '_PCW_MASK_INFORMATION' : [ 0x20, { 'CounterMask' : [ 0x0, ['unsigned long long']], 'InstanceMask' : [ 0x8, ['pointer', ['_UNICODE_STRING']]], 'InstanceId' : [ 0xc, ['unsigned long']], 'CollectMultiple' : [ 0x10, ['unsigned char']], 'Buffer' : [ 0x14, ['pointer', ['_PCW_BUFFER']]], 'CancelEvent' : [ 0x18, ['pointer', ['_KEVENT']]], } ], '_MMVAD_FLAGS' : [ 0x4, { 'VadType' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 3, native_type='unsigned long')]], 'Protection' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 8, native_type='unsigned long')]], 'PreferredNode' : [ 0x0, ['BitField', dict(start_bit = 8, end_bit = 14, native_type='unsigned long')]], 'NoChange' : [ 0x0, ['BitField', dict(start_bit = 14, end_bit = 15, native_type='unsigned long')]], 'PrivateMemory' : [ 0x0, ['BitField', dict(start_bit = 15, end_bit = 16, native_type='unsigned long')]], 'Teb' : [ 0x0, ['BitField', dict(start_bit = 16, end_bit = 17, native_type='unsigned long')]], 'PrivateFixup' : [ 0x0, ['BitField', dict(start_bit = 17, end_bit = 18, native_type='unsigned long')]], 'Spare' : [ 0x0, ['BitField', dict(start_bit = 18, end_bit = 31, native_type='unsigned long')]], 'DeleteInProgress' : [ 0x0, ['BitField', dict(start_bit = 31, end_bit = 32, native_type='unsigned long')]], } ], '_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']], } ], '_MI_VAD_EVENT_BLOCK' : [ 0x18, { 'Next' : [ 0x0, ['pointer', ['_MI_VAD_EVENT_BLOCK']]], 'WaitReason' : [ 0x4, ['unsigned long']], 'Gate' : [ 0x8, ['_KGATE']], 'SecureInfo' : [ 0x8, ['_MMADDRESS_LIST']], 'BitMap' : [ 0x8, ['_RTL_BITMAP']], 'InPageSupport' : [ 0x8, ['pointer', ['_MMINPAGE_SUPPORT']]], 'PhysicalMemory' : [ 0x8, ['_MI_PHYSMEM_BLOCK']], 'LargePage' : [ 0x8, ['pointer', ['_MI_LARGEPAGE_MEMORY_INFO']]], } ], '__unnamed_24e8' : [ 0x10, { 'TestAllocation' : [ 0x0, ['_ARBITER_TEST_ALLOCATION_PARAMETERS']], 'RetestAllocation' : [ 0x0, ['_ARBITER_RETEST_ALLOCATION_PARAMETERS']], 'BootAllocation' : [ 0x0, ['_ARBITER_BOOT_ALLOCATION_PARAMETERS']], 'QueryAllocatedResources' : [ 0x0, ['_ARBITER_QUERY_ALLOCATED_RESOURCES_PARAMETERS']], 'QueryConflict' : [ 0x0, ['_ARBITER_QUERY_CONFLICT_PARAMETERS']], 'QueryArbitrate' : [ 0x0, ['_ARBITER_QUERY_ARBITRATE_PARAMETERS']], 'AddReserved' : [ 0x0, ['_ARBITER_ADD_RESERVED_PARAMETERS']], } ], '_ARBITER_PARAMETERS' : [ 0x10, { 'Parameters' : [ 0x0, ['__unnamed_24e8']], } ], '__unnamed_24ec' : [ 0x8, { 'idxRecord' : [ 0x0, ['unsigned long']], 'cidContainer' : [ 0x4, ['unsigned long']], } ], '_CLS_LSN' : [ 0x8, { 'offset' : [ 0x0, ['__unnamed_24ec']], 'ullOffset' : [ 0x0, ['unsigned long long']], } ], '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']], } ], '_RSDS' : [ 0x1c, { 'Signature' : [ 0x0, ['unsigned long']], 'Guid' : [ 0x4, ['_GUID']], 'Age' : [ 0x14, ['unsigned long']], 'PdbName' : [ 0x18, ['array', 1, ['unsigned char']]], } ], 'PO_MEMORY_IMAGE' : [ 0x2c8, { 'Signature' : [ 0x0, ['unsigned long']], 'ImageType' : [ 0x4, ['unsigned long']], 'CheckSum' : [ 0x8, ['unsigned long']], 'LengthSelf' : [ 0xc, ['unsigned long']], 'PageSelf' : [ 0x10, ['unsigned long']], 'PageSize' : [ 0x14, ['unsigned long']], 'SystemTime' : [ 0x18, ['_LARGE_INTEGER']], 'InterruptTime' : [ 0x20, ['unsigned long long']], 'FeatureFlags' : [ 0x28, ['unsigned long']], 'HiberFlags' : [ 0x2c, ['unsigned char']], 'spare' : [ 0x2d, ['array', 3, ['unsigned char']]], 'NoHiberPtes' : [ 0x30, ['unsigned long']], 'HiberVa' : [ 0x34, ['unsigned long']], 'NoFreePages' : [ 0x38, ['unsigned long']], 'FreeMapCheck' : [ 0x3c, ['unsigned long']], 'WakeCheck' : [ 0x40, ['unsigned long']], 'NumPagesForLoader' : [ 0x48, ['unsigned long long']], 'FirstBootRestorePage' : [ 0x50, ['unsigned long']], 'FirstKernelRestorePage' : [ 0x54, ['unsigned long']], 'PerfInfo' : [ 0x58, ['_PO_HIBER_PERF']], 'FirmwareRuntimeInformationPages' : [ 0x200, ['unsigned long']], 'FirmwareRuntimeInformation' : [ 0x204, ['array', 1, ['unsigned long']]], 'SiLogOffset' : [ 0x208, ['unsigned long']], 'NoBootLoaderLogPages' : [ 0x20c, ['unsigned long']], 'BootLoaderLogPages' : [ 0x210, ['array', 24, ['unsigned long']]], 'NotUsed' : [ 0x270, ['unsigned long']], 'ResumeContextCheck' : [ 0x274, ['unsigned long']], 'ResumeContextPages' : [ 0x278, ['unsigned long']], 'Hiberboot' : [ 0x27c, ['unsigned char']], 'HvCr3' : [ 0x280, ['unsigned long long']], 'HvEntryPoint' : [ 0x288, ['unsigned long long']], 'HvReservedTransitionAddress' : [ 0x290, ['unsigned long long']], 'HvReservedTransitionAddressSize' : [ 0x298, ['unsigned long long']], 'BootFlags' : [ 0x2a0, ['unsigned long long']], 'HalEntryPointPhysical' : [ 0x2a8, ['unsigned long long']], 'HighestPhysicalPage' : [ 0x2b0, ['unsigned long']], 'BitlockerKeyPfns' : [ 0x2b4, ['array', 4, ['unsigned long']]], 'HardwareSignature' : [ 0x2c4, ['unsigned long']], } ], 'BATTERY_REPORTING_SCALE' : [ 0x8, { 'Granularity' : [ 0x0, ['unsigned long']], 'Capacity' : [ 0x4, ['unsigned long']], } ], '_RTL_ATOM_TABLE_REFERENCE' : [ 0x10, { 'LowBoxList' : [ 0x0, ['_LIST_ENTRY']], 'LowBoxID' : [ 0x8, ['unsigned long']], 'ReferenceCount' : [ 0xc, ['unsigned short']], 'Flags' : [ 0xe, ['unsigned short']], } ], '_CURDIR' : [ 0xc, { 'DosPath' : [ 0x0, ['_UNICODE_STRING']], 'Handle' : [ 0x8, ['pointer', ['void']]], } ], '_PO_HIBER_PERF' : [ 0x1a8, { 'HiberIoTicks' : [ 0x0, ['unsigned long long']], 'HiberIoCpuTicks' : [ 0x8, ['unsigned long long']], 'HiberInitTicks' : [ 0x10, ['unsigned long long']], 'HiberHiberFileTicks' : [ 0x18, ['unsigned long long']], 'HiberCompressTicks' : [ 0x20, ['unsigned long long']], 'HiberSharedBufferTicks' : [ 0x28, ['unsigned long long']], 'TotalHibernateTime' : [ 0x30, ['_LARGE_INTEGER']], 'POSTTime' : [ 0x38, ['unsigned long']], 'ResumeBootMgrTime' : [ 0x3c, ['unsigned long']], 'BootmgrUserInputTime' : [ 0x40, ['unsigned long']], 'ResumeAppTicks' : [ 0x48, ['unsigned long long']], 'ResumeAppStartTimestamp' : [ 0x50, ['unsigned long long']], 'ResumeLibraryInitTicks' : [ 0x58, ['unsigned long long']], 'ResumeInitTicks' : [ 0x60, ['unsigned long long']], 'ResumeRestoreImageStartTimestamp' : [ 0x68, ['unsigned long long']], 'ResumeHiberFileTicks' : [ 0x70, ['unsigned long long']], 'ResumeIoTicks' : [ 0x78, ['unsigned long long']], 'ResumeDecompressTicks' : [ 0x80, ['unsigned long long']], 'ResumeAllocateTicks' : [ 0x88, ['unsigned long long']], 'ResumeUserInOutTicks' : [ 0x90, ['unsigned long long']], 'ResumeMapTicks' : [ 0x98, ['unsigned long long']], 'ResumeUnmapTicks' : [ 0xa0, ['unsigned long long']], 'ResumeKernelSwitchTimestamp' : [ 0xa8, ['unsigned long long']], 'WriteLogDataTimestamp' : [ 0xb0, ['unsigned long long']], 'KernelReturnFromHandler' : [ 0xb8, ['unsigned long long']], 'TimeStampCounterAtSwitchTime' : [ 0xc0, ['unsigned long long']], 'HalTscOffset' : [ 0xc8, ['unsigned long long']], 'HvlTscOffset' : [ 0xd0, ['unsigned long long']], 'SleeperThreadEnd' : [ 0xd8, ['unsigned long long']], 'KernelReturnSystemPowerStateTimestamp' : [ 0xe0, ['unsigned long long']], 'IoBoundedness' : [ 0xe8, ['unsigned long long']], 'KernelDecompressTicks' : [ 0xf0, ['unsigned long long']], 'KernelIoTicks' : [ 0xf8, ['unsigned long long']], 'KernelCopyTicks' : [ 0x100, ['unsigned long long']], 'ReadCheckCount' : [ 0x108, ['unsigned long long']], 'KernelInitTicks' : [ 0x110, ['unsigned long long']], 'KernelResumeHiberFileTicks' : [ 0x118, ['unsigned long long']], 'KernelIoCpuTicks' : [ 0x120, ['unsigned long long']], 'KernelSharedBufferTicks' : [ 0x128, ['unsigned long long']], 'KernelAnimationTicks' : [ 0x130, ['unsigned long long']], 'AnimationStart' : [ 0x138, ['_LARGE_INTEGER']], 'AnimationStop' : [ 0x140, ['_LARGE_INTEGER']], 'DeviceResumeTime' : [ 0x148, ['unsigned long']], 'BootPagesProcessed' : [ 0x150, ['unsigned long long']], 'KernelPagesProcessed' : [ 0x158, ['unsigned long long']], 'BootBytesWritten' : [ 0x160, ['unsigned long long']], 'KernelBytesWritten' : [ 0x168, ['unsigned long long']], 'BootPagesWritten' : [ 0x170, ['unsigned long long']], 'KernelPagesWritten' : [ 0x178, ['unsigned long long']], 'BytesWritten' : [ 0x180, ['unsigned long long']], 'PagesWritten' : [ 0x188, ['unsigned long']], 'FileRuns' : [ 0x18c, ['unsigned long']], 'NoMultiStageResumeReason' : [ 0x190, ['unsigned long']], 'MaxHuffRatio' : [ 0x194, ['unsigned long']], 'AdjustedTotalResumeTime' : [ 0x198, ['unsigned long long']], 'ResumeCompleteTimestamp' : [ 0x1a0, ['unsigned long long']], } ], '_POP_FX_PROVIDER' : [ 0x8, { 'Index' : [ 0x0, ['unsigned long']], 'Activating' : [ 0x4, ['unsigned char']], } ], '_RTL_BALANCED_LINKS' : [ 0x10, { 'Parent' : [ 0x0, ['pointer', ['_RTL_BALANCED_LINKS']]], 'LeftChild' : [ 0x4, ['pointer', ['_RTL_BALANCED_LINKS']]], 'RightChild' : [ 0x8, ['pointer', ['_RTL_BALANCED_LINKS']]], 'Balance' : [ 0xc, ['unsigned char']], 'Reserved' : [ 0xd, ['array', 3, ['unsigned char']]], } ], '_FREE_DISPLAY' : [ 0x10, { 'RealVectorSize' : [ 0x0, ['unsigned long']], 'Hint' : [ 0x4, ['unsigned long']], 'Display' : [ 0x8, ['_RTL_BITMAP']], } ], '__unnamed_2508' : [ 0x4, { 'Flags' : [ 0x0, ['_MMSECURE_FLAGS']], 'StartVa' : [ 0x0, ['pointer', ['void']]], } ], '_MMADDRESS_LIST' : [ 0x8, { 'u1' : [ 0x0, ['__unnamed_2508']], 'EndVa' : [ 0x4, ['pointer', ['void']]], } ], '_MI_PHYSMEM_BLOCK' : [ 0x4, { 'IoTracker' : [ 0x0, ['pointer', ['_MMIO_TRACKER']]], } ], '_POP_PER_PROCESSOR_CONTEXT' : [ 0x70, { 'UncompressedData' : [ 0x0, ['pointer', ['unsigned char']]], 'MappingVa' : [ 0x4, ['pointer', ['void']]], 'XpressEncodeWorkspace' : [ 0x8, ['pointer', ['void']]], 'CompressedDataBuffer' : [ 0xc, ['pointer', ['unsigned char']]], 'CopyTicks' : [ 0x10, ['unsigned long long']], 'CompressTicks' : [ 0x18, ['unsigned long long']], 'BytesCopied' : [ 0x20, ['unsigned long long']], 'PagesProcessed' : [ 0x28, ['unsigned long long']], 'DecompressTicks' : [ 0x30, ['unsigned long long']], 'ResumeCopyTicks' : [ 0x38, ['unsigned long long']], 'SharedBufferTicks' : [ 0x40, ['unsigned long long']], 'DecompressTicksByMethod' : [ 0x48, ['array', 2, ['unsigned long long']]], 'DecompressSizeByMethod' : [ 0x58, ['array', 2, ['unsigned long long']]], 'CompressCount' : [ 0x68, ['unsigned long']], 'HuffCompressCount' : [ 0x6c, ['unsigned long']], } ], '_IO_REMOVE_LOCK' : [ 0x18, { 'Common' : [ 0x0, ['_IO_REMOVE_LOCK_COMMON_BLOCK']], } ], '_POP_IO_INFO' : [ 0x50, { 'DumpMdl' : [ 0x0, ['pointer', ['_MDL']]], 'IoStatus' : [ 0x4, ['Enumeration', dict(target = 'long', choices = {0: 'IoReady', 1: 'IoPending', 2: 'IoDone'})]], 'IoStartCount' : [ 0x8, ['unsigned long long']], 'IoBytesCompleted' : [ 0x10, ['unsigned long long']], 'IoBytesInProgress' : [ 0x18, ['unsigned long long']], 'RequestSize' : [ 0x20, ['unsigned long long']], 'IoLocation' : [ 0x28, ['_LARGE_INTEGER']], 'FileOffset' : [ 0x30, ['unsigned long long']], 'Buffer' : [ 0x38, ['pointer', ['void']]], 'AsyncCapable' : [ 0x3c, ['unsigned char']], 'BytesToRead' : [ 0x40, ['unsigned long long']], 'Pages' : [ 0x48, ['unsigned long']], } ], '_LDRP_CSLIST' : [ 0x4, { 'Tail' : [ 0x0, ['pointer', ['_SINGLE_LIST_ENTRY']]], } ], '_MMVIEW' : [ 0x28, { 'PteOffset' : [ 0x0, ['unsigned long long']], 'Entry' : [ 0x8, ['unsigned long']], 'u1' : [ 0xc, ['_MMVIEW_CONTROL_AREA']], 'ViewLinks' : [ 0x10, ['_LIST_ENTRY']], 'SessionViewVa' : [ 0x18, ['pointer', ['void']]], 'SessionId' : [ 0x1c, ['unsigned long']], 'SessionIdForGlobalSubsections' : [ 0x20, ['unsigned long']], } ], '_AER_BRIDGE_DESCRIPTOR_FLAGS' : [ 0x2, { 'UncorrectableErrorMaskRW' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned short')]], 'UncorrectableErrorSeverityRW' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned short')]], 'CorrectableErrorMaskRW' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned short')]], 'AdvancedCapsAndControlRW' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned short')]], 'SecondaryUncorrectableErrorMaskRW' : [ 0x0, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned short')]], 'SecondaryUncorrectableErrorSevRW' : [ 0x0, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned short')]], 'SecondaryCapsAndControlRW' : [ 0x0, ['BitField', dict(start_bit = 6, end_bit = 7, native_type='unsigned short')]], 'Reserved' : [ 0x0, ['BitField', dict(start_bit = 7, end_bit = 16, native_type='unsigned short')]], 'AsUSHORT' : [ 0x0, ['unsigned short']], } ], '_MMVIEW_CONTROL_AREA' : [ 0x4, { 'ControlArea' : [ 0x0, ['pointer', ['_CONTROL_AREA']]], 'Writable' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]], 'ExceptionForInPageErrors' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]], 'Unused' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]], 'UsedForControlArea' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 32, native_type='unsigned long')]], } ], '_MM_SESSION_SPACE_FLAGS' : [ 0x4, { 'Initialized' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]], 'DeletePending' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]], 'PoolInitialized' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]], 'DynamicVaInitialized' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned long')]], 'WsInitialized' : [ 0x0, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned long')]], 'PoolDestroyed' : [ 0x0, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned long')]], 'ObjectInitialized' : [ 0x0, ['BitField', dict(start_bit = 6, end_bit = 7, native_type='unsigned long')]], 'Filler' : [ 0x0, ['BitField', dict(start_bit = 7, end_bit = 32, native_type='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']], 'Flags' : [ 0x18, ['unsigned long']], 'CreatorBackTraceIndexHigh' : [ 0x1c, ['unsigned short']], 'SpareUSHORT' : [ 0x1e, ['unsigned short']], } ], '_TRACE_ENABLE_INFO' : [ 0x20, { 'IsEnabled' : [ 0x0, ['unsigned long']], 'Level' : [ 0x4, ['unsigned char']], 'Reserved1' : [ 0x5, ['unsigned char']], 'LoggerId' : [ 0x6, ['unsigned short']], 'EnableProperty' : [ 0x8, ['unsigned long']], 'Reserved2' : [ 0xc, ['unsigned long']], 'MatchAnyKeyword' : [ 0x10, ['unsigned long long']], 'MatchAllKeyword' : [ 0x18, ['unsigned long long']], } ], '_POP_FX_DEPENDENT' : [ 0x8, { 'Index' : [ 0x0, ['unsigned long']], 'ProviderIndex' : [ 0x4, ['unsigned long']], } ], '_XPF_MCE_FLAGS' : [ 0x4, { 'MCG_CapabilityRW' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]], 'MCG_GlobalControlRW' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]], 'Reserved' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 32, native_type='unsigned long')]], 'AsULONG' : [ 0x0, ['unsigned long']], } ], '__unnamed_2537' : [ 0x8, { 'Signature' : [ 0x0, ['unsigned long']], 'CheckSum' : [ 0x4, ['unsigned long']], } ], '__unnamed_2539' : [ 0x10, { 'DiskId' : [ 0x0, ['_GUID']], } ], '__unnamed_253b' : [ 0x10, { 'Mbr' : [ 0x0, ['__unnamed_2537']], 'Gpt' : [ 0x0, ['__unnamed_2539']], } ], '_DUMP_INITIALIZATION_CONTEXT' : [ 0xc0, { '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']], 'MarkMemoryOnly' : [ 0x45, ['unsigned char']], 'HiberResume' : [ 0x46, ['unsigned char']], 'Reserved1' : [ 0x47, ['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_253b']], 'ReadRoutine' : [ 0x6c, ['pointer', ['void']]], 'GetDriveTelemetryRoutine' : [ 0x70, ['pointer', ['void']]], 'LogSectionTruncateSize' : [ 0x74, ['unsigned long']], 'Parameters' : [ 0x78, ['array', 16, ['unsigned long']]], 'GetTransferSizesRoutine' : [ 0xb8, ['pointer', ['void']]], 'DumpNotifyRoutine' : [ 0xbc, ['pointer', ['void']]], } ], '_ETW_QUEUE_ENTRY' : [ 0x20, { 'ListEntry' : [ 0x0, ['_LIST_ENTRY']], 'DataBlock' : [ 0x8, ['pointer', ['_ETWP_NOTIFICATION_HEADER']]], 'RegEntry' : [ 0xc, ['pointer', ['_ETW_REG_ENTRY']]], 'ReplyObject' : [ 0x10, ['pointer', ['_ETW_REG_ENTRY']]], 'WakeReference' : [ 0x14, ['pointer', ['void']]], 'RegIndex' : [ 0x18, ['unsigned short']], 'ReplyIndex' : [ 0x1a, ['unsigned short']], 'Flags' : [ 0x1c, ['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']], } ], '_PO_DEVICE_NOTIFY_ORDER' : [ 0xd0, { 'Locked' : [ 0x0, ['unsigned char']], 'WarmEjectPdoPointer' : [ 0x4, ['pointer', ['pointer', ['_DEVICE_OBJECT']]]], 'OrderLevel' : [ 0x8, ['array', 5, ['_PO_NOTIFY_ORDER_LEVEL']]], } ], '_EVENT_FILTER_HEADER' : [ 0x18, { 'Id' : [ 0x0, ['unsigned short']], 'Version' : [ 0x2, ['unsigned char']], 'Reserved' : [ 0x3, ['array', 5, ['unsigned char']]], 'InstanceId' : [ 0x8, ['unsigned long long']], 'Size' : [ 0x10, ['unsigned long']], 'NextOffset' : [ 0x14, ['unsigned long']], } ], '_IO_REMOVE_LOCK_COMMON_BLOCK' : [ 0x18, { 'Removed' : [ 0x0, ['unsigned char']], 'Reserved' : [ 0x1, ['array', 3, ['unsigned char']]], 'IoCount' : [ 0x4, ['long']], 'RemoveEvent' : [ 0x8, ['_KEVENT']], } ], '_POP_FX_IDLE_STATE' : [ 0x18, { 'TransitionLatency' : [ 0x0, ['unsigned long long']], 'ResidencyRequirement' : [ 0x8, ['unsigned long long']], 'NominalPower' : [ 0x10, ['unsigned long']], } ], '_WHEA_NOTIFICATION_FLAGS' : [ 0x2, { 'PollIntervalRW' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned short')]], 'SwitchToPollingThresholdRW' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned short')]], 'SwitchToPollingWindowRW' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned short')]], 'ErrorThresholdRW' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned short')]], 'ErrorThresholdWindowRW' : [ 0x0, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned short')]], 'Reserved' : [ 0x0, ['BitField', dict(start_bit = 5, end_bit = 16, native_type='unsigned short')]], 'AsUSHORT' : [ 0x0, ['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' : [ 0x28, { 'DeviceCount' : [ 0x0, ['unsigned long']], 'ActiveCount' : [ 0x4, ['unsigned long']], 'WaitSleep' : [ 0x8, ['_LIST_ENTRY']], 'ReadySleep' : [ 0x10, ['_LIST_ENTRY']], 'ReadyS0' : [ 0x18, ['_LIST_ENTRY']], 'WaitS0' : [ 0x20, ['_LIST_ENTRY']], } ], '_ETWP_NOTIFICATION_HEADER' : [ 0x48, { 'NotificationType' : [ 0x0, ['Enumeration', dict(target = 'long', choices = {1: 'EtwNotificationTypeNoReply', 2: 'EtwNotificationTypeLegacyEnable', 3: 'EtwNotificationTypeEnable', 4: 'EtwNotificationTypePrivateLogger', 5: 'EtwNotificationTypePerflib', 6: 'EtwNotificationTypeAudio', 7: 'EtwNotificationTypeSession', 8: 'EtwNotificationTypeReserved', 9: 'EtwNotificationTypeCredentialUI', 10: 'EtwNotificationTypeMax'})]], 'NotificationSize' : [ 0x4, ['unsigned long']], 'RefCount' : [ 0x8, ['long']], 'ReplyRequested' : [ 0xc, ['unsigned char']], 'ReplyIndex' : [ 0x10, ['unsigned long']], 'Timeout' : [ 0x10, ['unsigned long']], 'ReplyCount' : [ 0x14, ['unsigned long']], 'NotifyeeCount' : [ 0x14, ['unsigned long']], 'ReplyHandle' : [ 0x18, ['unsigned long long']], 'ReplyObject' : [ 0x18, ['pointer', ['void']]], 'RegIndex' : [ 0x18, ['unsigned long']], 'TargetPID' : [ 0x20, ['unsigned long']], 'SourcePID' : [ 0x24, ['unsigned long']], 'DestinationGuid' : [ 0x28, ['_GUID']], 'SourceGuid' : [ 0x38, ['_GUID']], } ], '_THREAD_PERFORMANCE_DATA' : [ 0x1c0, { 'Size' : [ 0x0, ['unsigned short']], 'Version' : [ 0x2, ['unsigned short']], 'ProcessorNumber' : [ 0x4, ['_PROCESSOR_NUMBER']], 'ContextSwitches' : [ 0x8, ['unsigned long']], 'HwCountersCount' : [ 0xc, ['unsigned long']], 'UpdateCount' : [ 0x10, ['unsigned long long']], 'WaitReasonBitMap' : [ 0x18, ['unsigned long long']], 'HardwareCounters' : [ 0x20, ['unsigned long long']], 'CycleTime' : [ 0x28, ['_COUNTER_READING']], 'HwCounters' : [ 0x40, ['array', 16, ['_COUNTER_READING']]], } ], '_ETW_REPLY_QUEUE' : [ 0x2c, { 'Queue' : [ 0x0, ['_KQUEUE']], 'EventsLost' : [ 0x28, ['long']], } ], '_ARBITER_QUERY_ALLOCATED_RESOURCES_PARAMETERS' : [ 0x4, { 'AllocatedResources' : [ 0x0, ['pointer', ['pointer', ['_CM_PARTIAL_RESOURCE_LIST']]]], } ], '_MI_LARGEPAGE_MEMORY_INFO' : [ 0x10, { 'ListHead' : [ 0x0, ['_LIST_ENTRY']], 'ColoredPageInfoBase' : [ 0x8, ['pointer', ['_COLORED_PAGE_INFO']]], 'PagesNeedZeroing' : [ 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']], 'Xcr0' : [ 0x3c, ['unsigned long long']], 'Reserved' : [ 0x44, ['array', 4, ['unsigned long']]], } ], '_RTL_ACTIVATION_CONTEXT_STACK_FRAME' : [ 0xc, { 'Previous' : [ 0x0, ['pointer', ['_RTL_ACTIVATION_CONTEXT_STACK_FRAME']]], 'ActivationContext' : [ 0x4, ['pointer', ['_ACTIVATION_CONTEXT']]], 'Flags' : [ 0x8, ['unsigned long']], } ], '_MMIO_TRACKER' : [ 0x38, { 'ListEntry' : [ 0x0, ['_LIST_ENTRY']], 'PageFrameIndex' : [ 0x8, ['unsigned long']], 'NumberOfPages' : [ 0xc, ['unsigned long']], 'BaseVa' : [ 0x10, ['pointer', ['void']]], 'CacheFlushTimeStamp' : [ 0x10, ['unsigned long']], 'Mdl' : [ 0x14, ['pointer', ['_MDL']]], 'MdlPages' : [ 0x18, ['unsigned long']], 'StackTrace' : [ 0x1c, ['array', 6, ['pointer', ['void']]]], 'CacheInfo' : [ 0x34, ['array', 1, ['_IO_CACHE_INFO']]], } ], '_ARBITER_ORDERING' : [ 0x10, { 'Start' : [ 0x0, ['unsigned long long']], 'End' : [ 0x8, ['unsigned long long']], } ], '__unnamed_257c' : [ 0x4, { 'ImagePteOffset' : [ 0x0, ['unsigned long']], 'TossPage' : [ 0x0, ['unsigned long']], } ], '__unnamed_257f' : [ 0x4, { 'e1' : [ 0x0, ['_MMINPAGE_FLAGS']], 'LongFlags' : [ 0x0, ['unsigned long']], } ], '_MMINPAGE_SUPPORT' : [ 0xe0, { 'ListEntry' : [ 0x0, ['_LIST_ENTRY']], 'Thread' : [ 0x8, ['pointer', ['_ETHREAD']]], 'ListHead' : [ 0xc, ['_LIST_ENTRY']], 'Event' : [ 0x18, ['_KEVENT']], 'CollidedEvent' : [ 0x28, ['_KEVENT']], 'IoStatus' : [ 0x38, ['_IO_STATUS_BLOCK']], 'ReadOffset' : [ 0x40, ['_LARGE_INTEGER']], 'PteContents' : [ 0x48, ['_MMPTE']], 'LockedProtoPfn' : [ 0x50, ['pointer', ['_MMPFN']]], 'WaitCount' : [ 0x54, ['long']], 'ByteCount' : [ 0x58, ['unsigned long']], 'u3' : [ 0x5c, ['__unnamed_257c']], 'u1' : [ 0x60, ['__unnamed_257f']], 'FilePointer' : [ 0x64, ['pointer', ['_FILE_OBJECT']]], 'ControlArea' : [ 0x68, ['pointer', ['_CONTROL_AREA']]], 'FaultingAddress' : [ 0x6c, ['pointer', ['void']]], 'PointerPte' : [ 0x70, ['pointer', ['_MMPTE']]], 'BasePte' : [ 0x74, ['pointer', ['_MMPTE']]], 'Pfn' : [ 0x78, ['pointer', ['_MMPFN']]], 'PrefetchMdl' : [ 0x7c, ['pointer', ['_MDL']]], 'Mdl' : [ 0x80, ['_MDL']], 'Page' : [ 0x9c, ['array', 16, ['unsigned long']]], } ], '_RTL_AVL_TABLE' : [ 0x38, { 'BalancedRoot' : [ 0x0, ['_RTL_BALANCED_LINKS']], 'OrderedPointer' : [ 0x10, ['pointer', ['void']]], 'WhichOrderedElement' : [ 0x14, ['unsigned long']], 'NumberGenericTableElements' : [ 0x18, ['unsigned long']], 'DepthOfTree' : [ 0x1c, ['unsigned long']], 'RestartKey' : [ 0x20, ['pointer', ['_RTL_BALANCED_LINKS']]], 'DeleteCount' : [ 0x24, ['unsigned long']], 'CompareRoutine' : [ 0x28, ['pointer', ['void']]], 'AllocateRoutine' : [ 0x2c, ['pointer', ['void']]], 'FreeRoutine' : [ 0x30, ['pointer', ['void']]], 'TableContext' : [ 0x34, ['pointer', ['void']]], } ], '_MMINPAGE_FLAGS' : [ 0x4, { 'InjectRetry' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned char')]], 'CrossThreadPadding' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 8, native_type='unsigned char')]], 'PrefetchSystemVmType' : [ 0x1, ['BitField', dict(start_bit = 0, end_bit = 2, native_type='unsigned char')]], 'VaPrefetchReadBlock' : [ 0x1, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned char')]], 'CollidedFlowThrough' : [ 0x1, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned char')]], 'ForceCollisions' : [ 0x1, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned char')]], 'InPageExpanded' : [ 0x1, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned char')]], 'IssuedAtLowPriority' : [ 0x1, ['BitField', dict(start_bit = 6, end_bit = 7, native_type='unsigned char')]], 'FaultFromStore' : [ 0x1, ['BitField', dict(start_bit = 7, end_bit = 8, native_type='unsigned char')]], 'PagePriority' : [ 0x2, ['BitField', dict(start_bit = 0, end_bit = 3, native_type='unsigned char')]], 'PerformRelocations' : [ 0x2, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned char')]], 'ClusteredPagePriority' : [ 0x2, ['BitField', dict(start_bit = 4, end_bit = 7, native_type='unsigned char')]], 'MakeClusterValid' : [ 0x2, ['BitField', dict(start_bit = 7, end_bit = 8, native_type='unsigned char')]], 'ZeroLastPage' : [ 0x3, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned char')]], 'UserFault' : [ 0x3, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned char')]], 'BoostedPriority' : [ 0x3, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned char')]], 'StandbyProtectionNeeded' : [ 0x3, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned char')]], 'PteChanged' : [ 0x3, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned char')]], 'PageFileFault' : [ 0x3, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned char')]], 'Spare1' : [ 0x3, ['BitField', dict(start_bit = 6, end_bit = 8, native_type='unsigned char')]], } ], '_KTRANSACTION_HISTORY' : [ 0x8, { 'RecordType' : [ 0x0, ['Enumeration', dict(target = 'long', choices = {1: 'KTMOH_CommitTransaction_Result', 2: 'KTMOH_RollbackTransaction_Result'})]], 'Payload' : [ 0x4, ['unsigned long']], } ], '_MMSECURE_FLAGS' : [ 0x4, { 'ReadOnly' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]], 'NoWrite' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]], 'SecNoChange' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]], 'Spare' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 12, native_type='unsigned long')]], } ], '_COLORED_PAGE_INFO' : [ 0x10, { 'BeingZeroed' : [ 0x0, ['long']], 'Processor' : [ 0x4, ['unsigned long']], 'PagesQueued' : [ 0x8, ['unsigned long']], 'PfnAllocation' : [ 0xc, ['pointer', ['_MMPFN']]], } ], '_DESCRIPTOR' : [ 0x8, { 'Pad' : [ 0x0, ['unsigned short']], 'Limit' : [ 0x2, ['unsigned short']], 'Base' : [ 0x4, ['unsigned long']], } ], '_IO_CACHE_INFO' : [ 0x1, { 'CacheAttribute' : [ 0x0, ['unsigned char']], } ], }
gpl-2.0
ionelanton/restbodal
lib/web2py/dal.py
2
420985
#!/bin/env python # -*- coding: utf-8 -*- """ This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu> License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) Thanks to * Niall Sweeny <niall.sweeny@fonjax.com> for MS SQL support * Marcel Leuthi <mluethi@mlsystems.ch> for Oracle support * Denes * Chris Clark * clach05 * Denes Lengyel * and many others who have contributed to current and previous versions This file contains the DAL support for many relational databases, including: - SQLite & SpatiaLite - MySQL - Postgres - Firebird - Oracle - MS SQL - DB2 - Interbase - Ingres - Informix (9+ and SE) - SapDB (experimental) - Cubrid (experimental) - CouchDB (experimental) - MongoDB (in progress) - Google:nosql - Google:sql - Teradata - IMAP (experimental) Example of usage: >>> # from dal import DAL, Field ### create DAL connection (and create DB if it doesn't exist) >>> db = DAL(('sqlite://storage.sqlite','mysql://a:b@localhost/x'), ... folder=None) ### define a table 'person' (create/alter as necessary) >>> person = db.define_table('person',Field('name','string')) ### insert a record >>> id = person.insert(name='James') ### retrieve it by id >>> james = person(id) ### retrieve it by name >>> james = person(name='James') ### retrieve it by arbitrary query >>> query = (person.name=='James') & (person.name.startswith('J')) >>> james = db(query).select(person.ALL)[0] ### update one record >>> james.update_record(name='Jim') <Row {'id': 1, 'name': 'Jim'}> ### update multiple records by query >>> db(person.name.like('J%')).update(name='James') 1 ### delete records by query >>> db(person.name.lower() == 'jim').delete() 0 ### retrieve multiple records (rows) >>> people = db(person).select(orderby=person.name, ... groupby=person.name, limitby=(0,100)) ### further filter them >>> james = people.find(lambda row: row.name == 'James').first() >>> print james.id, james.name 1 James ### check aggregates >>> counter = person.id.count() >>> print db(person).select(counter).first()(counter) 1 ### delete one record >>> james.delete_record() 1 ### delete (drop) entire database table >>> person.drop() Supported field types: id string text boolean integer double decimal password upload blob time date datetime Supported DAL URI strings: 'sqlite://test.db' 'spatialite://test.db' 'sqlite:memory' 'spatialite:memory' 'jdbc:sqlite://test.db' 'mysql://root:none@localhost/test' 'postgres://mdipierro:password@localhost/test' 'postgres:psycopg2://mdipierro:password@localhost/test' 'postgres:pg8000://mdipierro:password@localhost/test' 'jdbc:postgres://mdipierro:none@localhost/test' 'mssql://web2py:none@A64X2/web2py_test' 'mssql2://web2py:none@A64X2/web2py_test' # alternate mappings 'oracle://username:password@database' 'firebird://user:password@server:3050/database' 'db2://DSN=dsn;UID=user;PWD=pass' 'firebird://username:password@hostname/database' 'firebird_embedded://username:password@c://path' 'informix://user:password@server:3050/database' 'informixu://user:password@server:3050/database' # unicode informix 'ingres://database' # or use an ODBC connection string, e.g. 'ingres://dsn=dsn_name' 'google:datastore' # for google app engine datastore 'google:sql' # for google app engine with sql (mysql compatible) 'teradata://DSN=dsn;UID=user;PWD=pass; DATABASE=database' # experimental 'imap://user:password@server:port' # experimental 'mongodb://user:password@server:port/database' # experimental For more info: help(DAL) help(Field) """ ################################################################################### # this file only exposes DAL and Field ################################################################################### __all__ = ['DAL', 'Field'] DEFAULTLENGTH = {'string':512, 'password':512, 'upload':512, 'text':2**15, 'blob':2**31} TIMINGSSIZE = 100 SPATIALLIBS = { 'Windows':'libspatialite', 'Linux':'libspatialite.so', 'Darwin':'libspatialite.dylib' } DEFAULT_URI = 'sqlite://dummy.db' import re import sys import locale import os import types import datetime import threading import time import csv import cgi import copy import socket import logging import base64 import shutil import marshal import decimal import struct import urllib import hashlib import uuid import glob import traceback import platform PYTHON_VERSION = sys.version_info[0] if PYTHON_VERSION == 2: import cPickle as pickle import cStringIO as StringIO import copy_reg as copyreg hashlib_md5 = hashlib.md5 bytes, unicode = str, unicode else: import pickle from io import StringIO as StringIO import copyreg long = int hashlib_md5 = lambda s: hashlib.md5(bytes(s,'utf8')) bytes, unicode = bytes, str CALLABLETYPES = (types.LambdaType, types.FunctionType, types.BuiltinFunctionType, types.MethodType, types.BuiltinMethodType) TABLE_ARGS = set( ('migrate','primarykey','fake_migrate','format','redefine', 'singular','plural','trigger_name','sequence_name', 'common_filter','polymodel','table_class','on_define','actual_name')) SELECT_ARGS = set( ('orderby', 'groupby', 'limitby','required', 'cache', 'left', 'distinct', 'having', 'join','for_update', 'processor','cacheable', 'orderby_on_limitby')) ogetattr = object.__getattribute__ osetattr = object.__setattr__ exists = os.path.exists pjoin = os.path.join ################################################################################### # following checks allow the use of dal without web2py, as a standalone module ################################################################################### try: from lib.web2py.utils import web2py_uuid except (ImportError, SystemError): import uuid def web2py_uuid(): return str(uuid.uuid4()) try: import portalocker have_portalocker = True except ImportError: have_portalocker = False try: import serializers have_serializers = True except ImportError: have_serializers = False try: import json as simplejson except ImportError: try: import gluon.contrib.simplejson as simplejson except ImportError: simplejson = None try: import validators have_validators = True except (ImportError, SyntaxError): have_validators = False LOGGER = logging.getLogger("web2py.dal") DEFAULT = lambda:0 GLOBAL_LOCKER = threading.RLock() THREAD_LOCAL = threading.local() # internal representation of tables with field # <table>.<field>, tables and fields may only be [a-zA-Z0-9_] REGEX_TYPE = re.compile('^([\w\_\:]+)') REGEX_DBNAME = re.compile('^(\w+)(\:\w+)*') REGEX_W = re.compile('^\w+$') REGEX_TABLE_DOT_FIELD = re.compile('^(\w+)\.(\w+)$') REGEX_UPLOAD_PATTERN = re.compile('(?P<table>[\w\-]+)\.(?P<field>[\w\-]+)\.(?P<uuidkey>[\w\-]+)\.(?P<name>\w+)\.\w+$') REGEX_CLEANUP_FN = re.compile('[\'"\s;]+') REGEX_UNPACK = re.compile('(?<!\|)\|(?!\|)') REGEX_PYTHON_KEYWORDS = re.compile('^(and|del|from|not|while|as|elif|global|or|with|assert|else|if|pass|yield|break|except|import|print|class|exec|in|raise|continue|finally|is|return|def|for|lambda|try)$') REGEX_SELECT_AS_PARSER = re.compile("\s+AS\s+(\S+)") REGEX_CONST_STRING = re.compile('(\"[^\"]*?\")|(\'[^\']*?\')') REGEX_SEARCH_PATTERN = re.compile('^{[^\.]+\.[^\.]+(\.(lt|gt|le|ge|eq|ne|contains|startswith|year|month|day|hour|minute|second))?(\.not)?}$') REGEX_SQUARE_BRACKETS = re.compile('^.+\[.+\]$') REGEX_STORE_PATTERN = re.compile('\.(?P<e>\w{1,5})$') REGEX_QUOTES = re.compile("'[^']*'") REGEX_ALPHANUMERIC = re.compile('^[0-9a-zA-Z]\w*$') REGEX_PASSWORD = re.compile('\://([^:@]*)\:') REGEX_NOPASSWD = re.compile('\/\/[\w\.\-]+[\:\/](.+)(?=@)') # was '(?<=[\:\/])([^:@/]+)(?=@.+)' # list of drivers will be built on the fly # and lists only what is available DRIVERS = [] try: from new import classobj from google.appengine.ext import db as gae from google.appengine.api import namespace_manager, rdbms from google.appengine.api.datastore_types import Key ### for belongs on ID from google.appengine.ext.db.polymodel import PolyModel DRIVERS.append('google') except ImportError: pass if not 'google' in DRIVERS: try: from pysqlite2 import dbapi2 as sqlite2 DRIVERS.append('SQLite(sqlite2)') except ImportError: LOGGER.debug('no SQLite drivers pysqlite2.dbapi2') try: from sqlite3 import dbapi2 as sqlite3 DRIVERS.append('SQLite(sqlite3)') except ImportError: LOGGER.debug('no SQLite drivers sqlite3') try: # first try contrib driver, then from site-packages (if installed) try: import contrib.pymysql as pymysql # monkeypatch pymysql because they havent fixed the bug: # https://github.com/petehunt/PyMySQL/issues/86 pymysql.ESCAPE_REGEX = re.compile("'") pymysql.ESCAPE_MAP = {"'": "''"} # end monkeypatch except ImportError: import pymysql DRIVERS.append('MySQL(pymysql)') except ImportError: LOGGER.debug('no MySQL driver pymysql') try: import MySQLdb DRIVERS.append('MySQL(MySQLdb)') except ImportError: LOGGER.debug('no MySQL driver MySQLDB') try: import psycopg2 from psycopg2.extensions import adapt as psycopg2_adapt DRIVERS.append('PostgreSQL(psycopg2)') except ImportError: LOGGER.debug('no PostgreSQL driver psycopg2') try: # first try contrib driver, then from site-packages (if installed) try: import contrib.pg8000.dbapi as pg8000 except ImportError: import pg8000.dbapi as pg8000 DRIVERS.append('PostgreSQL(pg8000)') except ImportError: LOGGER.debug('no PostgreSQL driver pg8000') try: import cx_Oracle DRIVERS.append('Oracle(cx_Oracle)') except ImportError: LOGGER.debug('no Oracle driver cx_Oracle') try: try: import pyodbc except ImportError: try: import contrib.pypyodbc as pyodbc except Exception, e: raise ImportError(str(e)) DRIVERS.append('MSSQL(pyodbc)') DRIVERS.append('DB2(pyodbc)') DRIVERS.append('Teradata(pyodbc)') DRIVERS.append('Ingres(pyodbc)') except ImportError: LOGGER.debug('no MSSQL/DB2/Teradata/Ingres driver pyodbc') try: import Sybase DRIVERS.append('Sybase(Sybase)') except ImportError: LOGGER.debug('no Sybase driver') try: import kinterbasdb DRIVERS.append('Interbase(kinterbasdb)') DRIVERS.append('Firebird(kinterbasdb)') except ImportError: LOGGER.debug('no Firebird/Interbase driver kinterbasdb') try: import fdb DRIVERS.append('Firebird(fdb)') except ImportError: LOGGER.debug('no Firebird driver fdb') ##### try: import firebirdsql DRIVERS.append('Firebird(firebirdsql)') except ImportError: LOGGER.debug('no Firebird driver firebirdsql') try: import informixdb DRIVERS.append('Informix(informixdb)') LOGGER.warning('Informix support is experimental') except ImportError: LOGGER.debug('no Informix driver informixdb') try: import sapdb DRIVERS.append('SQL(sapdb)') LOGGER.warning('SAPDB support is experimental') except ImportError: LOGGER.debug('no SAP driver sapdb') try: import cubriddb DRIVERS.append('Cubrid(cubriddb)') LOGGER.warning('Cubrid support is experimental') except ImportError: LOGGER.debug('no Cubrid driver cubriddb') try: from com.ziclix.python.sql import zxJDBC import java.sql # Try sqlite jdbc driver from http://www.zentus.com/sqlitejdbc/ from org.sqlite import JDBC # required by java.sql; ensure we have it zxJDBC_sqlite = java.sql.DriverManager DRIVERS.append('PostgreSQL(zxJDBC)') DRIVERS.append('SQLite(zxJDBC)') LOGGER.warning('zxJDBC support is experimental') is_jdbc = True except ImportError: LOGGER.debug('no SQLite/PostgreSQL driver zxJDBC') is_jdbc = False try: import couchdb DRIVERS.append('CouchDB(couchdb)') except ImportError: LOGGER.debug('no Couchdb driver couchdb') try: import pymongo DRIVERS.append('MongoDB(pymongo)') except: LOGGER.debug('no MongoDB driver pymongo') try: import imaplib DRIVERS.append('IMAP(imaplib)') except: LOGGER.debug('no IMAP driver imaplib') PLURALIZE_RULES = [ (re.compile('child$'), re.compile('child$'), 'children'), (re.compile('oot$'), re.compile('oot$'), 'eet'), (re.compile('ooth$'), re.compile('ooth$'), 'eeth'), (re.compile('l[eo]af$'), re.compile('l([eo])af$'), 'l\\1aves'), (re.compile('sis$'), re.compile('sis$'), 'ses'), (re.compile('man$'), re.compile('man$'), 'men'), (re.compile('ife$'), re.compile('ife$'), 'ives'), (re.compile('eau$'), re.compile('eau$'), 'eaux'), (re.compile('lf$'), re.compile('lf$'), 'lves'), (re.compile('[sxz]$'), re.compile('$'), 'es'), (re.compile('[^aeioudgkprt]h$'), re.compile('$'), 'es'), (re.compile('(qu|[^aeiou])y$'), re.compile('y$'), 'ies'), (re.compile('$'), re.compile('$'), 's'), ] def pluralize(singular, rules=PLURALIZE_RULES): for line in rules: re_search, re_sub, replace = line plural = re_search.search(singular) and re_sub.sub(replace, singular) if plural: return plural def hide_password(uri): if isinstance(uri,(list,tuple)): return [hide_password(item) for item in uri] return REGEX_NOPASSWD.sub('******',uri) def OR(a,b): return a|b def AND(a,b): return a&b def IDENTITY(x): return x def varquote_aux(name,quotestr='%s'): return name if REGEX_W.match(name) else quotestr % name def quote_keyword(a,keyword='timestamp'): regex = re.compile('\.keyword(?=\w)') a = regex.sub('."%s"' % keyword,a) return a if 'google' in DRIVERS: is_jdbc = False class GAEDecimalProperty(gae.Property): """ GAE decimal implementation """ data_type = decimal.Decimal def __init__(self, precision, scale, **kwargs): super(GAEDecimalProperty, self).__init__(self, **kwargs) d = '1.' for x in range(scale): d += '0' self.round = decimal.Decimal(d) def get_value_for_datastore(self, model_instance): value = super(GAEDecimalProperty, self)\ .get_value_for_datastore(model_instance) if value is None or value == '': return None else: return str(value) def make_value_from_datastore(self, value): if value is None or value == '': return None else: return decimal.Decimal(value).quantize(self.round) def validate(self, value): value = super(GAEDecimalProperty, self).validate(value) if value is None or isinstance(value, decimal.Decimal): return value elif isinstance(value, basestring): return decimal.Decimal(value) raise gae.BadValueError("Property %s must be a Decimal or string."\ % self.name) ################################################################################### # class that handles connection pooling (all adapters are derived from this one) ################################################################################### class ConnectionPool(object): POOLS = {} check_active_connection = True @staticmethod def set_folder(folder): THREAD_LOCAL.folder = folder # ## this allows gluon to commit/rollback all dbs in this thread def close(self,action='commit',really=True): if action: if callable(action): action(self) else: getattr(self, action)() # ## if you want pools, recycle this connection if self.pool_size: GLOBAL_LOCKER.acquire() pool = ConnectionPool.POOLS[self.uri] if len(pool) < self.pool_size: pool.append(self.connection) really = False GLOBAL_LOCKER.release() if really: self.close_connection() self.connection = None @staticmethod def close_all_instances(action): """ to close cleanly databases in a multithreaded environment """ dbs = getattr(THREAD_LOCAL,'db_instances',{}).items() for db_uid, db_group in dbs: for db in db_group: if hasattr(db,'_adapter'): db._adapter.close(action) getattr(THREAD_LOCAL,'db_instances',{}).clear() getattr(THREAD_LOCAL,'db_instances_zombie',{}).clear() if callable(action): action(None) return def find_or_make_work_folder(self): """ this actually does not make the folder. it has to be there """ self.folder = getattr(THREAD_LOCAL,'folder','') # Creating the folder if it does not exist if False and self.folder and not exists(self.folder): os.mkdir(self.folder) def after_connection_hook(self): """hook for the after_connection parameter""" if callable(self._after_connection): self._after_connection(self) self.after_connection() def after_connection(self): """ this it is supposed to be overloaded by adapters""" pass def reconnect(self, f=None, cursor=True): """ this function defines: self.connection and self.cursor (iff cursor is True) if self.pool_size>0 it will try pull the connection from the pool if the connection is not active (closed by db server) it will loop if not self.pool_size or no active connections in pool makes a new one """ if getattr(self,'connection', None) != None: return if f is None: f = self.connector # if not hasattr(self, "driver") or self.driver is None: # LOGGER.debug("Skipping connection since there's no driver") # return if not self.pool_size: self.connection = f() self.cursor = cursor and self.connection.cursor() else: uri = self.uri POOLS = ConnectionPool.POOLS while True: GLOBAL_LOCKER.acquire() if not uri in POOLS: POOLS[uri] = [] if POOLS[uri]: self.connection = POOLS[uri].pop() GLOBAL_LOCKER.release() self.cursor = cursor and self.connection.cursor() try: if self.cursor and self.check_active_connection: self.execute('SELECT 1;') break except: pass else: GLOBAL_LOCKER.release() self.connection = f() self.cursor = cursor and self.connection.cursor() break self.after_connection_hook() ################################################################################### # this is a generic adapter that does nothing; all others are derived from this one ################################################################################### class BaseAdapter(ConnectionPool): native_json = False driver = None driver_name = None drivers = () # list of drivers from which to pick connection = None commit_on_alter_table = False support_distributed_transaction = False uploads_in_blob = False can_select_for_update = True TRUE = 'T' FALSE = 'F' T_SEP = ' ' QUOTE_TEMPLATE = '"%s"' types = { 'boolean': 'CHAR(1)', 'string': 'CHAR(%(length)s)', 'text': 'TEXT', 'json': 'TEXT', 'password': 'CHAR(%(length)s)', 'blob': 'BLOB', 'upload': 'CHAR(%(length)s)', 'integer': 'INTEGER', 'bigint': 'INTEGER', 'float':'DOUBLE', 'double': 'DOUBLE', 'decimal': 'DOUBLE', 'date': 'DATE', 'time': 'TIME', 'datetime': 'TIMESTAMP', 'id': 'INTEGER PRIMARY KEY AUTOINCREMENT', 'reference': 'INTEGER REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', 'list:integer': 'TEXT', 'list:string': 'TEXT', 'list:reference': 'TEXT', # the two below are only used when DAL(...bigint_id=True) and replace 'id','reference' 'big-id': 'BIGINT PRIMARY KEY AUTOINCREMENT', 'big-reference': 'BIGINT REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', } def id_query(self, table): return table._id != None def adapt(self, obj): return "'%s'" % obj.replace("'", "''") def smart_adapt(self, obj): if isinstance(obj,(int,float)): return str(obj) return self.adapt(str(obj)) def file_exists(self, filename): """ to be used ONLY for files that on GAE may not be on filesystem """ return exists(filename) def file_open(self, filename, mode='rb', lock=True): """ to be used ONLY for files that on GAE may not be on filesystem """ if have_portalocker and lock: fileobj = portalocker.LockedFile(filename,mode) else: fileobj = open(filename,mode) return fileobj def file_close(self, fileobj): """ to be used ONLY for files that on GAE may not be on filesystem """ if fileobj: fileobj.close() def file_delete(self, filename): os.unlink(filename) def find_driver(self,adapter_args,uri=None): if getattr(self,'driver',None) != None: return drivers_available = [driver for driver in self.drivers if driver in globals()] if uri: items = uri.split('://',1)[0].split(':') request_driver = items[1] if len(items)>1 else None else: request_driver = None request_driver = request_driver or adapter_args.get('driver') if request_driver: if request_driver in drivers_available: self.driver_name = request_driver self.driver = globals().get(request_driver) else: raise RuntimeError("driver %s not available" % request_driver) elif drivers_available: self.driver_name = drivers_available[0] self.driver = globals().get(self.driver_name) else: raise RuntimeError("no driver available %s" % str(self.drivers)) def __init__(self, db,uri,pool_size=0, folder=None, db_codec='UTF-8', credential_decoder=IDENTITY, driver_args={}, adapter_args={},do_connect=True, after_connection=None): self.db = db self.dbengine = "None" self.uri = uri self.pool_size = pool_size self.folder = folder self.db_codec = db_codec self._after_connection = after_connection class Dummy(object): lastrowid = 1 def __getattr__(self, value): return lambda *a, **b: [] self.connection = Dummy() self.cursor = Dummy() def sequence_name(self,tablename): return '%s_sequence' % tablename def trigger_name(self,tablename): return '%s_sequence' % tablename def varquote(self,name): return name def create_table(self, table, migrate=True, fake_migrate=False, polymodel=None): db = table._db fields = [] # PostGIS geo fields are added after the table has been created postcreation_fields = [] sql_fields = {} sql_fields_aux = {} TFK = {} tablename = table._tablename sortable = 0 types = self.types for field in table: sortable += 1 field_name = field.name field_type = field.type if isinstance(field_type,SQLCustomType): ftype = field_type.native or field_type.type elif field_type.startswith('reference'): referenced = field_type[10:].strip() if referenced == '.': referenced = tablename constraint_name = self.constraint_name(tablename, field_name) if not '.' in referenced \ and referenced != tablename \ and hasattr(table,'_primarykey'): ftype = types['integer'] else: if hasattr(table,'_primarykey'): rtablename,rfieldname = referenced.split('.') rtable = db[rtablename] rfield = rtable[rfieldname] # must be PK reference or unique if rfieldname in rtable._primarykey or \ rfield.unique: ftype = types[rfield.type[:9]] % \ dict(length=rfield.length) # multicolumn primary key reference? if not rfield.unique and len(rtable._primarykey)>1: # then it has to be a table level FK if rtablename not in TFK: TFK[rtablename] = {} TFK[rtablename][rfieldname] = field_name else: ftype = ftype + \ types['reference FK'] % dict( constraint_name = constraint_name, # should be quoted foreign_key = '%s (%s)' % (rtablename, rfieldname), table_name = tablename, field_name = field_name, on_delete_action=field.ondelete) else: # make a guess here for circular references if referenced in db: id_fieldname = db[referenced]._id.name elif referenced == tablename: id_fieldname = table._id.name else: #make a guess id_fieldname = 'id' ftype = types[field_type[:9]] % dict( index_name = field_name+'__idx', field_name = field_name, constraint_name = constraint_name, foreign_key = '%s (%s)' % (referenced, id_fieldname), on_delete_action=field.ondelete) elif field_type.startswith('list:reference'): ftype = types[field_type[:14]] elif field_type.startswith('decimal'): precision, scale = map(int,field_type[8:-1].split(',')) ftype = types[field_type[:7]] % \ dict(precision=precision,scale=scale) elif field_type.startswith('geo'): if not hasattr(self,'srid'): raise RuntimeError('Adapter does not support geometry') srid = self.srid geotype, parms = field_type[:-1].split('(') if not geotype in types: raise SyntaxError( 'Field: unknown field type: %s for %s' \ % (field_type, field_name)) ftype = types[geotype] if self.dbengine == 'postgres' and geotype == 'geometry': # parameters: schema, srid, dimension dimension = 2 # GIS.dimension ??? parms = parms.split(',') if len(parms) == 3: schema, srid, dimension = parms elif len(parms) == 2: schema, srid = parms else: schema = parms[0] ftype = "SELECT AddGeometryColumn ('%%(schema)s', '%%(tablename)s', '%%(fieldname)s', %%(srid)s, '%s', %%(dimension)s);" % types[geotype] ftype = ftype % dict(schema=schema, tablename=tablename, fieldname=field_name, srid=srid, dimension=dimension) postcreation_fields.append(ftype) elif not field_type in types: raise SyntaxError('Field: unknown field type: %s for %s' % \ (field_type, field_name)) else: ftype = types[field_type]\ % dict(length=field.length) if not field_type.startswith('id') and \ not field_type.startswith('reference'): if field.notnull: ftype += ' NOT NULL' else: ftype += self.ALLOW_NULL() if field.unique: ftype += ' UNIQUE' if field.custom_qualifier: ftype += ' %s' % field.custom_qualifier # add to list of fields sql_fields[field_name] = dict( length=field.length, unique=field.unique, notnull=field.notnull, sortable=sortable, type=str(field_type), sql=ftype) if field.notnull and not field.default is None: # Caveat: sql_fields and sql_fields_aux # differ for default values. # sql_fields is used to trigger migrations and sql_fields_aux # is used for create tables. # The reason is that we do not want to trigger # a migration simply because a default value changes. not_null = self.NOT_NULL(field.default, field_type) ftype = ftype.replace('NOT NULL', not_null) sql_fields_aux[field_name] = dict(sql=ftype) # Postgres - PostGIS: # geometry fields are added after the table has been created, not now if not (self.dbengine == 'postgres' and \ field_type.startswith('geom')): fields.append('%s %s' % (field_name, ftype)) other = ';' # backend-specific extensions to fields if self.dbengine == 'mysql': if not hasattr(table, "_primarykey"): fields.append('PRIMARY KEY(%s)' % table._id.name) other = ' ENGINE=InnoDB CHARACTER SET utf8;' fields = ',\n '.join(fields) for rtablename in TFK: rfields = TFK[rtablename] pkeys = db[rtablename]._primarykey fkeys = [ rfields[k] for k in pkeys ] fields = fields + ',\n ' + \ types['reference TFK'] % dict( table_name = tablename, field_name=', '.join(fkeys), foreign_table = rtablename, foreign_key = ', '.join(pkeys), on_delete_action = field.ondelete) if getattr(table,'_primarykey',None): query = "CREATE TABLE %s(\n %s,\n %s) %s" % \ (tablename, fields, self.PRIMARY_KEY(', '.join(table._primarykey)),other) else: query = "CREATE TABLE %s(\n %s\n)%s" % \ (tablename, fields, other) if self.uri.startswith('sqlite:///') \ or self.uri.startswith('spatialite:///'): path_encoding = sys.getfilesystemencoding() \ or locale.getdefaultlocale()[1] or 'utf8' dbpath = self.uri[9:self.uri.rfind('/')]\ .decode('utf8').encode(path_encoding) elif self.uri.startswith('sqlite://'): path_encoding = sys.getfilesystemencoding() \ or locale.getdefaultlocale()[1] or 'utf8' dbpath = self.uri[9:self.uri.rfind('/')]\ .decode('utf8').encode(path_encoding) else: dbpath = self.folder if not migrate: return query elif self.uri.startswith('sqlite:memory')\ or self.uri.startswith('spatialite:memory'): table._dbt = None elif isinstance(migrate, str): table._dbt = pjoin(dbpath, migrate) else: table._dbt = pjoin( dbpath, '%s_%s.table' % (table._db._uri_hash, tablename)) if table._dbt: table._loggername = pjoin(dbpath, 'sql.log') logfile = self.file_open(table._loggername, 'a') else: logfile = None if not table._dbt or not self.file_exists(table._dbt): if table._dbt: logfile.write('timestamp: %s\n' % datetime.datetime.today().isoformat()) logfile.write(query + '\n') if not fake_migrate: self.create_sequence_and_triggers(query,table) table._db.commit() # Postgres geom fields are added now, # after the table has been created for query in postcreation_fields: self.execute(query) table._db.commit() if table._dbt: tfile = self.file_open(table._dbt, 'w') pickle.dump(sql_fields, tfile) self.file_close(tfile) if fake_migrate: logfile.write('faked!\n') else: logfile.write('success!\n') else: tfile = self.file_open(table._dbt, 'r') try: sql_fields_old = pickle.load(tfile) except EOFError: self.file_close(tfile) self.file_close(logfile) raise RuntimeError('File %s appears corrupted' % table._dbt) self.file_close(tfile) if sql_fields != sql_fields_old: self.migrate_table(table, sql_fields, sql_fields_old, sql_fields_aux, logfile, fake_migrate=fake_migrate) self.file_close(logfile) return query def migrate_table( self, table, sql_fields, sql_fields_old, sql_fields_aux, logfile, fake_migrate=False, ): db = table._db db._migrated.append(table._tablename) tablename = table._tablename def fix(item): k,v=item if not isinstance(v,dict): v=dict(type='unknown',sql=v) return k.lower(),v # make sure all field names are lower case to avoid # migrations because of case cahnge sql_fields = dict(map(fix,sql_fields.iteritems())) sql_fields_old = dict(map(fix,sql_fields_old.iteritems())) sql_fields_aux = dict(map(fix,sql_fields_aux.iteritems())) if db._debug: logging.debug('migrating %s to %s' % (sql_fields_old,sql_fields)) keys = sql_fields.keys() for key in sql_fields_old: if not key in keys: keys.append(key) new_add = self.concat_add(tablename) metadata_change = False sql_fields_current = copy.copy(sql_fields_old) for key in keys: query = None if not key in sql_fields_old: sql_fields_current[key] = sql_fields[key] if self.dbengine in ('postgres',) and \ sql_fields[key]['type'].startswith('geometry'): # 'sql' == ftype in sql query = [ sql_fields[key]['sql'] ] else: query = ['ALTER TABLE %s ADD %s %s;' % \ (tablename, key, sql_fields_aux[key]['sql'].replace(', ', new_add))] metadata_change = True elif self.dbengine in ('sqlite', 'spatialite'): if key in sql_fields: sql_fields_current[key] = sql_fields[key] metadata_change = True elif not key in sql_fields: del sql_fields_current[key] ftype = sql_fields_old[key]['type'] if self.dbengine in ('postgres',) and ftype.startswith('geometry'): geotype, parms = ftype[:-1].split('(') schema = parms.split(',')[0] query = [ "SELECT DropGeometryColumn ('%(schema)s', '%(table)s', '%(field)s');" % dict(schema=schema, table=tablename, field=key,) ] elif self.dbengine in ('firebird',): query = ['ALTER TABLE %s DROP %s;' % (tablename, key)] else: query = ['ALTER TABLE %s DROP COLUMN %s;' % (tablename, key)] metadata_change = True elif sql_fields[key]['sql'] != sql_fields_old[key]['sql'] \ and not (key in table.fields and isinstance(table[key].type, SQLCustomType)) \ and not sql_fields[key]['type'].startswith('reference')\ and not sql_fields[key]['type'].startswith('double')\ and not sql_fields[key]['type'].startswith('id'): sql_fields_current[key] = sql_fields[key] t = tablename tt = sql_fields_aux[key]['sql'].replace(', ', new_add) if self.dbengine in ('firebird',): drop_expr = 'ALTER TABLE %s DROP %s;' else: drop_expr = 'ALTER TABLE %s DROP COLUMN %s;' key_tmp = key + '__tmp' query = ['ALTER TABLE %s ADD %s %s;' % (t, key_tmp, tt), 'UPDATE %s SET %s=%s;' % (t, key_tmp, key), drop_expr % (t, key), 'ALTER TABLE %s ADD %s %s;' % (t, key, tt), 'UPDATE %s SET %s=%s;' % (t, key, key_tmp), drop_expr % (t, key_tmp)] metadata_change = True elif sql_fields[key]['type'] != sql_fields_old[key]['type']: sql_fields_current[key] = sql_fields[key] metadata_change = True if query: logfile.write('timestamp: %s\n' % datetime.datetime.today().isoformat()) db['_lastsql'] = '\n'.join(query) for sub_query in query: logfile.write(sub_query + '\n') if fake_migrate: if db._adapter.commit_on_alter_table: self.save_dbt(table,sql_fields_current) logfile.write('faked!\n') else: self.execute(sub_query) # Caveat: mysql, oracle and firebird do not allow multiple alter table # in one transaction so we must commit partial transactions and # update table._dbt after alter table. if db._adapter.commit_on_alter_table: db.commit() self.save_dbt(table,sql_fields_current) logfile.write('success!\n') elif metadata_change: self.save_dbt(table,sql_fields_current) if metadata_change and not (query and db._adapter.commit_on_alter_table): db.commit() self.save_dbt(table,sql_fields_current) logfile.write('success!\n') def save_dbt(self,table, sql_fields_current): tfile = self.file_open(table._dbt, 'w') pickle.dump(sql_fields_current, tfile) self.file_close(tfile) def LOWER(self, first): return 'LOWER(%s)' % self.expand(first) def UPPER(self, first): return 'UPPER(%s)' % self.expand(first) def COUNT(self, first, distinct=None): return ('COUNT(%s)' if not distinct else 'COUNT(DISTINCT %s)') \ % self.expand(first) def EXTRACT(self, first, what): return "EXTRACT(%s FROM %s)" % (what, self.expand(first)) def EPOCH(self, first): return self.EXTRACT(first, 'epoch') def LENGTH(self, first): return "LENGTH(%s)" % self.expand(first) def AGGREGATE(self, first, what): return "%s(%s)" % (what, self.expand(first)) def JOIN(self): return 'JOIN' def LEFT_JOIN(self): return 'LEFT JOIN' def RANDOM(self): return 'Random()' def NOT_NULL(self, default, field_type): return 'NOT NULL DEFAULT %s' % self.represent(default,field_type) def COALESCE(self, first, second): expressions = [self.expand(first)]+[self.expand(e) for e in second] return 'COALESCE(%s)' % ','.join(expressions) def COALESCE_ZERO(self, first): return 'COALESCE(%s,0)' % self.expand(first) def RAW(self, first): return first def ALLOW_NULL(self): return '' def SUBSTRING(self, field, parameters): return 'SUBSTR(%s,%s,%s)' % (self.expand(field), parameters[0], parameters[1]) def PRIMARY_KEY(self, key): return 'PRIMARY KEY(%s)' % key def _drop(self, table, mode): return ['DROP TABLE %s;' % table] def drop(self, table, mode=''): db = table._db if table._dbt: logfile = self.file_open(table._loggername, 'a') queries = self._drop(table, mode) for query in queries: if table._dbt: logfile.write(query + '\n') self.execute(query) db.commit() del db[table._tablename] del db.tables[db.tables.index(table._tablename)] db._remove_references_to(table) if table._dbt: self.file_delete(table._dbt) logfile.write('success!\n') def _insert(self, table, fields): if fields: keys = ','.join(f.name for f, v in fields) values = ','.join(self.expand(v, f.type) for f, v in fields) return 'INSERT INTO %s(%s) VALUES (%s);' % (table, keys, values) else: return self._insert_empty(table) def _insert_empty(self, table): return 'INSERT INTO %s DEFAULT VALUES;' % table def insert(self, table, fields): query = self._insert(table,fields) try: self.execute(query) except Exception: e = sys.exc_info()[1] if hasattr(table,'_on_insert_error'): return table._on_insert_error(table,fields,e) raise e if hasattr(table,'_primarykey'): return dict([(k[0].name, k[1]) for k in fields \ if k[0].name in table._primarykey]) id = self.lastrowid(table) if not isinstance(id,int): return id rid = Reference(id) (rid._table, rid._record) = (table, None) return rid def bulk_insert(self, table, items): return [self.insert(table,item) for item in items] def NOT(self, first): return '(NOT %s)' % self.expand(first) def AND(self, first, second): return '(%s AND %s)' % (self.expand(first), self.expand(second)) def OR(self, first, second): return '(%s OR %s)' % (self.expand(first), self.expand(second)) def BELONGS(self, first, second): if isinstance(second, str): return '(%s IN (%s))' % (self.expand(first), second[:-1]) elif not second: return '(1=0)' items = ','.join(self.expand(item, first.type) for item in second) return '(%s IN (%s))' % (self.expand(first), items) def REGEXP(self, first, second): "regular expression operator" raise NotImplementedError def LIKE(self, first, second): "case sensitive like operator" raise NotImplementedError def ILIKE(self, first, second): "case in-sensitive like operator" return '(%s LIKE %s)' % (self.expand(first), self.expand(second, 'string')) def STARTSWITH(self, first, second): return '(%s LIKE %s)' % (self.expand(first), self.expand(second+'%', 'string')) def ENDSWITH(self, first, second): return '(%s LIKE %s)' % (self.expand(first), self.expand('%'+second, 'string')) def CONTAINS(self,first,second,case_sensitive=False): if first.type in ('string','text', 'json'): if isinstance(second,Expression): second = Expression(None,self.CONCAT('%',Expression( None,self.REPLACE(second,('%','%%'))),'%')) else: second = '%'+str(second).replace('%','%%')+'%' elif first.type.startswith('list:'): if isinstance(second,Expression): second = Expression(None,self.CONCAT( '%|',Expression(None,self.REPLACE( Expression(None,self.REPLACE( second,('%','%%'))),('|','||'))),'|%')) else: second = '%|'+str(second).replace('%','%%')\ .replace('|','||')+'|%' op = case_sensitive and self.LIKE or self.ILIKE return op(first,second) def EQ(self, first, second=None): if second is None: return '(%s IS NULL)' % self.expand(first) return '(%s = %s)' % (self.expand(first), self.expand(second, first.type)) def NE(self, first, second=None): if second is None: return '(%s IS NOT NULL)' % self.expand(first) return '(%s <> %s)' % (self.expand(first), self.expand(second, first.type)) def LT(self,first,second=None): if second is None: raise RuntimeError("Cannot compare %s < None" % first) return '(%s < %s)' % (self.expand(first), self.expand(second,first.type)) def LE(self,first,second=None): if second is None: raise RuntimeError("Cannot compare %s <= None" % first) return '(%s <= %s)' % (self.expand(first), self.expand(second,first.type)) def GT(self,first,second=None): if second is None: raise RuntimeError("Cannot compare %s > None" % first) return '(%s > %s)' % (self.expand(first), self.expand(second,first.type)) def GE(self,first,second=None): if second is None: raise RuntimeError("Cannot compare %s >= None" % first) return '(%s >= %s)' % (self.expand(first), self.expand(second,first.type)) def is_numerical_type(self, ftype): return ftype in ('integer','boolean','double','bigint') or \ ftype.startswith('decimal') def REPLACE(self, first, (second, third)): return 'REPLACE(%s,%s,%s)' % (self.expand(first,'string'), self.expand(second,'string'), self.expand(third,'string')) def CONCAT(self, *items): return '(%s)' % ' || '.join(self.expand(x,'string') for x in items) def ADD(self, first, second): if self.is_numerical_type(first.type): return '(%s + %s)' % (self.expand(first), self.expand(second, first.type)) else: return self.CONCAT(first, second) def SUB(self, first, second): return '(%s - %s)' % (self.expand(first), self.expand(second, first.type)) def MUL(self, first, second): return '(%s * %s)' % (self.expand(first), self.expand(second, first.type)) def DIV(self, first, second): return '(%s / %s)' % (self.expand(first), self.expand(second, first.type)) def MOD(self, first, second): return '(%s %% %s)' % (self.expand(first), self.expand(second, first.type)) def AS(self, first, second): return '%s AS %s' % (self.expand(first), second) def ON(self, first, second): if use_common_filters(second): second = self.common_filter(second,[first._tablename]) return '%s ON %s' % (self.expand(first), self.expand(second)) def INVERT(self, first): return '%s DESC' % self.expand(first) def COMMA(self, first, second): return '%s, %s' % (self.expand(first), self.expand(second)) def expand(self, expression, field_type=None): if isinstance(expression, Field): out = '%s.%s' % (expression.table._tablename, expression.name) if field_type == 'string' and not expression.type in ( 'string','text','json','password'): out = 'CAST(%s AS %s)' % (out, self.types['text']) return out elif isinstance(expression, (Expression, Query)): first = expression.first second = expression.second op = expression.op optional_args = expression.optional_args or {} if not second is None: out = op(first, second, **optional_args) elif not first is None: out = op(first,**optional_args) elif isinstance(op, str): if op.endswith(';'): op=op[:-1] out = '(%s)' % op else: out = op() return out elif field_type: return str(self.represent(expression,field_type)) elif isinstance(expression,(list,tuple)): return ','.join(self.represent(item,field_type) \ for item in expression) elif isinstance(expression, bool): return '1' if expression else '0' else: return str(expression) def table_alias(self,name): return str(name if isinstance(name,Table) else self.db[name]) def alias(self, table, alias): """ Given a table object, makes a new table object with alias name. """ other = copy.copy(table) other['_ot'] = other._ot or other._tablename other['ALL'] = SQLALL(other) other['_tablename'] = alias for fieldname in other.fields: other[fieldname] = copy.copy(other[fieldname]) other[fieldname]._tablename = alias other[fieldname].tablename = alias other[fieldname].table = other table._db[alias] = other return other def _truncate(self, table, mode=''): tablename = table._tablename return ['TRUNCATE TABLE %s %s;' % (tablename, mode or '')] def truncate(self, table, mode= ' '): # Prepare functions "write_to_logfile" and "close_logfile" if table._dbt: logfile = self.file_open(table._loggername, 'a') else: class Logfile(object): def write(self, value): pass def close(self): pass logfile = Logfile() try: queries = table._db._adapter._truncate(table, mode) for query in queries: logfile.write(query + '\n') self.execute(query) table._db.commit() logfile.write('success!\n') finally: logfile.close() def _update(self, tablename, query, fields): if query: if use_common_filters(query): query = self.common_filter(query, [tablename]) sql_w = ' WHERE ' + self.expand(query) else: sql_w = '' sql_v = ','.join(['%s=%s' % (field.name, self.expand(value, field.type)) \ for (field, value) in fields]) tablename = "%s" % self.db[tablename] return 'UPDATE %s SET %s%s;' % (tablename, sql_v, sql_w) def update(self, tablename, query, fields): sql = self._update(tablename, query, fields) try: self.execute(sql) except Exception: e = sys.exc_info()[1] table = self.db[tablename] if hasattr(table,'_on_update_error'): return table._on_update_error(table,query,fields,e) raise e try: return self.cursor.rowcount except: return None def _delete(self, tablename, query): if query: if use_common_filters(query): query = self.common_filter(query, [tablename]) sql_w = ' WHERE ' + self.expand(query) else: sql_w = '' return 'DELETE FROM %s%s;' % (tablename, sql_w) def delete(self, tablename, query): sql = self._delete(tablename, query) ### special code to handle CASCADE in SQLite & SpatiaLite db = self.db table = db[tablename] if self.dbengine in ('sqlite', 'spatialite') and table._referenced_by: deleted = [x[table._id.name] for x in db(query).select(table._id)] ### end special code to handle CASCADE in SQLite & SpatiaLite self.execute(sql) try: counter = self.cursor.rowcount except: counter = None ### special code to handle CASCADE in SQLite & SpatiaLite if self.dbengine in ('sqlite', 'spatialite') and counter: for field in table._referenced_by: if field.type=='reference '+table._tablename \ and field.ondelete=='CASCADE': db(field.belongs(deleted)).delete() ### end special code to handle CASCADE in SQLite & SpatiaLite return counter def get_table(self, query): tablenames = self.tables(query) if len(tablenames)==1: return tablenames[0] elif len(tablenames)<1: raise RuntimeError("No table selected") else: raise RuntimeError("Too many tables selected") def expand_all(self, fields, tablenames): db = self.db new_fields = [] append = new_fields.append for item in fields: if isinstance(item,SQLALL): new_fields += item._table elif isinstance(item,str): if REGEX_TABLE_DOT_FIELD.match(item): tablename,fieldname = item.split('.') append(db[tablename][fieldname]) else: append(Expression(db,lambda item=item:item)) else: append(item) # ## if no fields specified take them all from the requested tables if not new_fields: for table in tablenames: for field in db[table]: append(field) return new_fields def _select(self, query, fields, attributes): tables = self.tables for key in set(attributes.keys())-SELECT_ARGS: raise SyntaxError('invalid select attribute: %s' % key) args_get = attributes.get tablenames = tables(query) tablenames_for_common_filters = tablenames for field in fields: if isinstance(field, basestring) \ and REGEX_TABLE_DOT_FIELD.match(field): tn,fn = field.split('.') field = self.db[tn][fn] for tablename in tables(field): if not tablename in tablenames: tablenames.append(tablename) if len(tablenames) < 1: raise SyntaxError('Set: no tables selected') self._colnames = map(self.expand, fields) def geoexpand(field): if isinstance(field.type,str) and field.type.startswith('geometry'): field = field.st_astext() return self.expand(field) sql_f = ', '.join(map(geoexpand, fields)) sql_o = '' sql_s = '' left = args_get('left', False) inner_join = args_get('join', False) distinct = args_get('distinct', False) groupby = args_get('groupby', False) orderby = args_get('orderby', False) having = args_get('having', False) limitby = args_get('limitby', False) orderby_on_limitby = args_get('orderby_on_limitby', True) for_update = args_get('for_update', False) if self.can_select_for_update is False and for_update is True: raise SyntaxError('invalid select attribute: for_update') if distinct is True: sql_s += 'DISTINCT' elif distinct: sql_s += 'DISTINCT ON (%s)' % distinct if inner_join: icommand = self.JOIN() if not isinstance(inner_join, (tuple, list)): inner_join = [inner_join] ijoint = [t._tablename for t in inner_join if not isinstance(t,Expression)] ijoinon = [t for t in inner_join if isinstance(t, Expression)] itables_to_merge={} #issue 490 [itables_to_merge.update( dict.fromkeys(tables(t))) for t in ijoinon] ijoinont = [t.first._tablename for t in ijoinon] [itables_to_merge.pop(t) for t in ijoinont if t in itables_to_merge] #issue 490 iimportant_tablenames = ijoint + ijoinont + itables_to_merge.keys() iexcluded = [t for t in tablenames if not t in iimportant_tablenames] if left: join = attributes['left'] command = self.LEFT_JOIN() if not isinstance(join, (tuple, list)): join = [join] joint = [t._tablename for t in join if not isinstance(t, Expression)] joinon = [t for t in join if isinstance(t, Expression)] #patch join+left patch (solves problem with ordering in left joins) tables_to_merge={} [tables_to_merge.update( dict.fromkeys(tables(t))) for t in joinon] joinont = [t.first._tablename for t in joinon] [tables_to_merge.pop(t) for t in joinont if t in tables_to_merge] tablenames_for_common_filters = [t for t in tablenames if not t in joinont ] important_tablenames = joint + joinont + tables_to_merge.keys() excluded = [t for t in tablenames if not t in important_tablenames ] else: excluded = tablenames if use_common_filters(query): query = self.common_filter(query,tablenames_for_common_filters) sql_w = ' WHERE ' + self.expand(query) if query else '' if inner_join and not left: sql_t = ', '.join([self.table_alias(t) for t in iexcluded + \ itables_to_merge.keys()]) for t in ijoinon: sql_t += ' %s %s' % (icommand, t) elif not inner_join and left: sql_t = ', '.join([self.table_alias(t) for t in excluded + \ tables_to_merge.keys()]) if joint: sql_t += ' %s %s' % (command, ','.join([self.table_alias(t) for t in joint])) for t in joinon: sql_t += ' %s %s' % (command, t) elif inner_join and left: all_tables_in_query = set(important_tablenames + \ iimportant_tablenames + \ tablenames) tables_in_joinon = set(joinont + ijoinont) tables_not_in_joinon = \ all_tables_in_query.difference(tables_in_joinon) sql_t = ','.join([self.table_alias(t) for t in tables_not_in_joinon]) for t in ijoinon: sql_t += ' %s %s' % (icommand, t) if joint: sql_t += ' %s %s' % (command, ','.join([self.table_alias(t) for t in joint])) for t in joinon: sql_t += ' %s %s' % (command, t) else: sql_t = ', '.join(self.table_alias(t) for t in tablenames) if groupby: if isinstance(groupby, (list, tuple)): groupby = xorify(groupby) sql_o += ' GROUP BY %s' % self.expand(groupby) if having: sql_o += ' HAVING %s' % attributes['having'] if orderby: if isinstance(orderby, (list, tuple)): orderby = xorify(orderby) if str(orderby) == '<random>': sql_o += ' ORDER BY %s' % self.RANDOM() else: sql_o += ' ORDER BY %s' % self.expand(orderby) if limitby: if orderby_on_limitby and not orderby and tablenames: sql_o += ' ORDER BY %s' % ', '.join(['%s.%s'%(t,x) for t in tablenames for x in (hasattr(self.db[t],'_primarykey') and self.db[t]._primarykey or [self.db[t]._id.name])]) # oracle does not support limitby sql = self.select_limitby(sql_s, sql_f, sql_t, sql_w, sql_o, limitby) if for_update and self.can_select_for_update is True: sql = sql.rstrip(';') + ' FOR UPDATE;' return sql def select_limitby(self, sql_s, sql_f, sql_t, sql_w, sql_o, limitby): if limitby: (lmin, lmax) = limitby sql_o += ' LIMIT %i OFFSET %i' % (lmax - lmin, lmin) return 'SELECT %s %s FROM %s%s%s;' % \ (sql_s, sql_f, sql_t, sql_w, sql_o) def _fetchall(self): return self.cursor.fetchall() def _select_aux(self,sql,fields,attributes): args_get = attributes.get cache = args_get('cache',None) if not cache: self.execute(sql) rows = self._fetchall() else: (cache_model, time_expire) = cache key = self.uri + '/' + sql + '/rows' if len(key)>200: key = hashlib_md5(key).hexdigest() def _select_aux2(): self.execute(sql) return self._fetchall() rows = cache_model(key,_select_aux2,time_expire) if isinstance(rows,tuple): rows = list(rows) limitby = args_get('limitby', None) or (0,) rows = self.rowslice(rows,limitby[0],None) processor = args_get('processor',self.parse) cacheable = args_get('cacheable',False) return processor(rows,fields,self._colnames,cacheable=cacheable) def select(self, query, fields, attributes): """ Always returns a Rows object, possibly empty. """ sql = self._select(query, fields, attributes) cache = attributes.get('cache', None) if cache and attributes.get('cacheable',False): del attributes['cache'] (cache_model, time_expire) = cache key = self.uri + '/' + sql if len(key)>200: key = hashlib_md5(key).hexdigest() args = (sql,fields,attributes) return cache_model( key, lambda self=self,args=args:self._select_aux(*args), time_expire) else: return self._select_aux(sql,fields,attributes) def _count(self, query, distinct=None): tablenames = self.tables(query) if query: if use_common_filters(query): query = self.common_filter(query, tablenames) sql_w = ' WHERE ' + self.expand(query) else: sql_w = '' sql_t = ','.join(self.table_alias(t) for t in tablenames) if distinct: if isinstance(distinct,(list, tuple)): distinct = xorify(distinct) sql_d = self.expand(distinct) return 'SELECT count(DISTINCT %s) FROM %s%s;' % \ (sql_d, sql_t, sql_w) return 'SELECT count(*) FROM %s%s;' % (sql_t, sql_w) def count(self, query, distinct=None): self.execute(self._count(query, distinct)) return self.cursor.fetchone()[0] def tables(self, *queries): tables = set() for query in queries: if isinstance(query, Field): tables.add(query.tablename) elif isinstance(query, (Expression, Query)): if not query.first is None: tables = tables.union(self.tables(query.first)) if not query.second is None: tables = tables.union(self.tables(query.second)) return list(tables) def commit(self): if self.connection: return self.connection.commit() def rollback(self): if self.connection: return self.connection.rollback() def close_connection(self): if self.connection: return self.connection.close() def distributed_transaction_begin(self, key): return def prepare(self, key): if self.connection: self.connection.prepare() def commit_prepared(self, key): if self.connection: self.connection.commit() def rollback_prepared(self, key): if self.connection: self.connection.rollback() def concat_add(self, tablename): return ', ADD ' def constraint_name(self, table, fieldname): return '%s_%s__constraint' % (table,fieldname) def create_sequence_and_triggers(self, query, table, **args): self.execute(query) def log_execute(self, *a, **b): if not self.connection: return None command = a[0] if hasattr(self,'filter_sql_command'): command = self.filter_sql_command(command) if self.db._debug: LOGGER.debug('SQL: %s' % command) self.db._lastsql = command t0 = time.time() ret = self.cursor.execute(command, *a[1:], **b) self.db._timings.append((command,time.time()-t0)) del self.db._timings[:-TIMINGSSIZE] return ret def execute(self, *a, **b): return self.log_execute(*a, **b) def represent(self, obj, fieldtype): field_is_type = fieldtype.startswith if isinstance(obj, CALLABLETYPES): obj = obj() if isinstance(fieldtype, SQLCustomType): value = fieldtype.encoder(obj) if fieldtype.type in ('string','text', 'json'): return self.adapt(value) return value if isinstance(obj, (Expression, Field)): return str(obj) if field_is_type('list:'): if not obj: obj = [] elif not isinstance(obj, (list, tuple)): obj = [obj] if field_is_type('list:string'): obj = map(str,obj) else: obj = map(int,[o for o in obj if o != '']) # we don't want to bar_encode json objects if isinstance(obj, (list, tuple)) and (not fieldtype == "json"): obj = bar_encode(obj) if obj is None: return 'NULL' if obj == '' and not fieldtype[:2] in ['st', 'te', 'lib', 'pa', 'up']: return 'NULL' r = self.represent_exceptions(obj, fieldtype) if not r is None: return r if fieldtype == 'boolean': if obj and not str(obj)[:1].upper() in '0F': return self.smart_adapt(self.TRUE) else: return self.smart_adapt(self.FALSE) if fieldtype == 'id' or fieldtype == 'integer': return str(long(obj)) if field_is_type('decimal'): return str(obj) elif field_is_type('reference'): # reference if fieldtype.find('.')>0: return repr(obj) elif isinstance(obj, (Row, Reference)): return str(obj['id']) return str(long(obj)) elif fieldtype == 'double': return repr(float(obj)) if isinstance(obj, unicode): obj = obj.encode(self.db_codec) if fieldtype == 'blob': obj = base64.b64encode(str(obj)) elif fieldtype == 'date': if isinstance(obj, (datetime.date, datetime.datetime)): obj = obj.isoformat()[:10] else: obj = str(obj) elif fieldtype == 'datetime': if isinstance(obj, datetime.datetime): obj = obj.isoformat(self.T_SEP)[:19] elif isinstance(obj, datetime.date): obj = obj.isoformat()[:10]+' 00:00:00' else: obj = str(obj) elif fieldtype == 'time': if isinstance(obj, datetime.time): obj = obj.isoformat()[:10] else: obj = str(obj) elif fieldtype == 'json': if not self.native_json: if have_serializers: obj = serializers.json(obj) elif simplejson: obj = simplejson.dumps(obj) else: raise RuntimeError("missing simplejson") if not isinstance(obj,bytes): obj = bytes(obj) try: obj.decode(self.db_codec) except: obj = obj.decode('latin1').encode(self.db_codec) return self.adapt(obj) def represent_exceptions(self, obj, fieldtype): return None def lastrowid(self, table): return None def rowslice(self, rows, minimum=0, maximum=None): """ By default this function does nothing; overload when db does not do slicing. """ return rows def parse_value(self, value, field_type, blob_decode=True): if field_type != 'blob' and isinstance(value, str): try: value = value.decode(self.db._db_codec) except Exception: pass if isinstance(value, unicode): value = value.encode('utf-8') if isinstance(field_type, SQLCustomType): value = field_type.decoder(value) if not isinstance(field_type, str) or value is None: return value elif field_type in ('string', 'text', 'password', 'upload', 'dict'): return value elif field_type.startswith('geo'): return value elif field_type == 'blob' and not blob_decode: return value else: key = REGEX_TYPE.match(field_type).group(0) return self.parsemap[key](value,field_type) def parse_reference(self, value, field_type): referee = field_type[10:].strip() if not '.' in referee: value = Reference(value) value._table, value._record = self.db[referee], None return value def parse_boolean(self, value, field_type): return value == self.TRUE or str(value)[:1].lower() == 't' def parse_date(self, value, field_type): if isinstance(value, datetime.datetime): return value.date() if not isinstance(value, (datetime.date,datetime.datetime)): (y, m, d) = map(int, str(value)[:10].strip().split('-')) value = datetime.date(y, m, d) return value def parse_time(self, value, field_type): if not isinstance(value, datetime.time): time_items = map(int,str(value)[:8].strip().split(':')[:3]) if len(time_items) == 3: (h, mi, s) = time_items else: (h, mi, s) = time_items + [0] value = datetime.time(h, mi, s) return value def parse_datetime(self, value, field_type): if not isinstance(value, datetime.datetime): value = str(value) date_part,time_part,timezone = value[:10],value[11:19],value[19:] if '+' in timezone: ms,tz = timezone.split('+') h,m = tz.split(':') dt = datetime.timedelta(seconds=3600*int(h)+60*int(m)) elif '-' in timezone: ms,tz = timezone.split('-') h,m = tz.split(':') dt = -datetime.timedelta(seconds=3600*int(h)+60*int(m)) else: dt = None (y, m, d) = map(int,date_part.split('-')) time_parts = time_part and time_part.split(':')[:3] or (0,0,0) while len(time_parts)<3: time_parts.append(0) time_items = map(int,time_parts) (h, mi, s) = time_items value = datetime.datetime(y, m, d, h, mi, s) if dt: value = value + dt return value def parse_blob(self, value, field_type): return base64.b64decode(str(value)) def parse_decimal(self, value, field_type): decimals = int(field_type[8:-1].split(',')[-1]) if self.dbengine in ('sqlite', 'spatialite'): value = ('%.' + str(decimals) + 'f') % value if not isinstance(value, decimal.Decimal): value = decimal.Decimal(str(value)) return value def parse_list_integers(self, value, field_type): if not isinstance(self, NoSQLAdapter): value = bar_decode_integer(value) return value def parse_list_references(self, value, field_type): if not isinstance(self, NoSQLAdapter): value = bar_decode_integer(value) return [self.parse_reference(r, field_type[5:]) for r in value] def parse_list_strings(self, value, field_type): if not isinstance(self, NoSQLAdapter): value = bar_decode_string(value) return value def parse_id(self, value, field_type): return long(value) def parse_integer(self, value, field_type): return long(value) def parse_double(self, value, field_type): return float(value) def parse_json(self, value, field_type): if not self.native_json: if not isinstance(value, basestring): raise RuntimeError('json data not a string') if isinstance(value, unicode): value = value.encode('utf-8') if have_serializers: value = serializers.loads_json(value) elif simplejson: value = simplejson.loads(value) else: raise RuntimeError("missing simplejson") return value def build_parsemap(self): self.parsemap = { 'id':self.parse_id, 'integer':self.parse_integer, 'bigint':self.parse_integer, 'float':self.parse_double, 'double':self.parse_double, 'reference':self.parse_reference, 'boolean':self.parse_boolean, 'date':self.parse_date, 'time':self.parse_time, 'datetime':self.parse_datetime, 'blob':self.parse_blob, 'decimal':self.parse_decimal, 'json':self.parse_json, 'list:integer':self.parse_list_integers, 'list:reference':self.parse_list_references, 'list:string':self.parse_list_strings, } def parse(self, rows, fields, colnames, blob_decode=True, cacheable = False): self.build_parsemap() db = self.db virtualtables = [] new_rows = [] tmps = [] for colname in colnames: if not REGEX_TABLE_DOT_FIELD.match(colname): tmps.append(None) else: (tablename, fieldname) = colname.split('.') table = db[tablename] field = table[fieldname] ft = field.type tmps.append((tablename,fieldname,table,field,ft)) for (i,row) in enumerate(rows): new_row = Row() for (j,colname) in enumerate(colnames): value = row[j] tmp = tmps[j] if tmp: (tablename,fieldname,table,field,ft) = tmp if tablename in new_row: colset = new_row[tablename] else: colset = new_row[tablename] = Row() if tablename not in virtualtables: virtualtables.append(tablename) value = self.parse_value(value,ft,blob_decode) if field.filter_out: value = field.filter_out(value) colset[fieldname] = value # for backward compatibility if ft=='id' and fieldname!='id' and \ not 'id' in table.fields: colset['id'] = value if ft == 'id' and not cacheable: # temporary hack to deal with # GoogleDatastoreAdapter # references if isinstance(self, GoogleDatastoreAdapter): id = value.key().id_or_name() colset[fieldname] = id colset.gae_item = value else: id = value colset.update_record = RecordUpdater(colset,table,id) colset.delete_record = RecordDeleter(table,id) for rfield in table._referenced_by: referee_link = db._referee_name and \ db._referee_name % dict( table=rfield.tablename,field=rfield.name) if referee_link and not referee_link in colset: colset[referee_link] = LazySet(rfield,id) else: if not '_extra' in new_row: new_row['_extra'] = Row() new_row['_extra'][colname] = \ self.parse_value(value, fields[j].type,blob_decode) new_column_name = \ REGEX_SELECT_AS_PARSER.search(colname) if not new_column_name is None: column_name = new_column_name.groups(0) setattr(new_row,column_name[0],value) new_rows.append(new_row) rowsobj = Rows(db, new_rows, colnames, rawrows=rows) for tablename in virtualtables: ### new style virtual fields table = db[tablename] fields_virtual = [(f,v) for (f,v) in table.iteritems() if isinstance(v,FieldVirtual)] fields_lazy = [(f,v) for (f,v) in table.iteritems() if isinstance(v,FieldMethod)] if fields_virtual or fields_lazy: for row in rowsobj.records: box = row[tablename] for f,v in fields_virtual: box[f] = v.f(row) for f,v in fields_lazy: box[f] = (v.handler or VirtualCommand)(v.f,row) ### old style virtual fields for item in table.virtualfields: try: rowsobj = rowsobj.setvirtualfields(**{tablename:item}) except (KeyError, AttributeError): # to avoid breaking virtualfields when partial select pass return rowsobj def common_filter(self, query, tablenames): tenant_fieldname = self.db._request_tenant for tablename in tablenames: table = self.db[tablename] # deal with user provided filters if table._common_filter != None: query = query & table._common_filter(query) # deal with multi_tenant filters if tenant_fieldname in table: default = table[tenant_fieldname].default if not default is None: newquery = table[tenant_fieldname] == default if query is None: query = newquery else: query = query & newquery return query def CASE(self,query,t,f): def represent(x): types = {type(True):'boolean',type(0):'integer',type(1.0):'double'} if x is None: return 'NULL' elif isinstance(x,Expression): return str(x) else: return self.represent(x,types.get(type(x),'string')) return Expression(self.db,'CASE WHEN %s THEN %s ELSE %s END' % \ (self.expand(query),represent(t),represent(f))) ################################################################################### # List of all the available adapters; they all extend BaseAdapter. ################################################################################### class SQLiteAdapter(BaseAdapter): drivers = ('sqlite2','sqlite3') can_select_for_update = None # support ourselves with BEGIN TRANSACTION def EXTRACT(self,field,what): return "web2py_extract('%s',%s)" % (what, self.expand(field)) @staticmethod def web2py_extract(lookup, s): table = { 'year': (0, 4), 'month': (5, 7), 'day': (8, 10), 'hour': (11, 13), 'minute': (14, 16), 'second': (17, 19), } try: if lookup != 'epoch': (i, j) = table[lookup] return int(s[i:j]) else: return time.mktime(datetime.datetime.strptime(s, '%Y-%m-%d %H:%M:%S').timetuple()) except: return None @staticmethod def web2py_regexp(expression, item): return re.compile(expression).search(item) is not None def __init__(self, db, uri, pool_size=0, folder=None, db_codec ='UTF-8', credential_decoder=IDENTITY, driver_args={}, adapter_args={}, do_connect=True, after_connection=None): self.db = db self.dbengine = "sqlite" self.uri = uri if do_connect: self.find_driver(adapter_args) self.pool_size = 0 self.folder = folder self.db_codec = db_codec self._after_connection = after_connection self.find_or_make_work_folder() path_encoding = sys.getfilesystemencoding() \ or locale.getdefaultlocale()[1] or 'utf8' if uri.startswith('sqlite:memory'): dbpath = ':memory:' else: dbpath = uri.split('://',1)[1] if dbpath[0] != '/': if PYTHON_VERSION == 2: dbpath = pjoin( self.folder.decode(path_encoding).encode('utf8'), dbpath) else: dbpath = pjoin(self.folder, dbpath) if not 'check_same_thread' in driver_args: driver_args['check_same_thread'] = False if not 'detect_types' in driver_args and do_connect: driver_args['detect_types'] = self.driver.PARSE_DECLTYPES def connector(dbpath=dbpath, driver_args=driver_args): return self.driver.Connection(dbpath, **driver_args) self.connector = connector if do_connect: self.reconnect() def after_connection(self): self.connection.create_function('web2py_extract', 2, SQLiteAdapter.web2py_extract) self.connection.create_function("REGEXP", 2, SQLiteAdapter.web2py_regexp) def _truncate(self, table, mode=''): tablename = table._tablename return ['DELETE FROM %s;' % tablename, "DELETE FROM sqlite_sequence WHERE name='%s';" % tablename] def lastrowid(self, table): return self.cursor.lastrowid def REGEXP(self,first,second): return '(%s REGEXP %s)' % (self.expand(first), self.expand(second,'string')) def select(self, query, fields, attributes): """ Simulate SELECT ... FOR UPDATE with BEGIN IMMEDIATE TRANSACTION. Note that the entire database, rather than one record, is locked (it will be locked eventually anyway by the following UPDATE). """ if attributes.get('for_update', False) and not 'cache' in attributes: self.execute('BEGIN IMMEDIATE TRANSACTION;') return super(SQLiteAdapter, self).select(query, fields, attributes) class SpatiaLiteAdapter(SQLiteAdapter): drivers = ('sqlite3','sqlite2') types = copy.copy(BaseAdapter.types) types.update(geometry='GEOMETRY') def __init__(self, db, uri, pool_size=0, folder=None, db_codec ='UTF-8', credential_decoder=IDENTITY, driver_args={}, adapter_args={}, do_connect=True, srid=4326, after_connection=None): self.db = db self.dbengine = "spatialite" self.uri = uri if do_connect: self.find_driver(adapter_args) self.pool_size = 0 self.folder = folder self.db_codec = db_codec self._after_connection = after_connection self.find_or_make_work_folder() self.srid = srid path_encoding = sys.getfilesystemencoding() \ or locale.getdefaultlocale()[1] or 'utf8' if uri.startswith('spatialite:memory'): dbpath = ':memory:' else: dbpath = uri.split('://',1)[1] if dbpath[0] != '/': dbpath = pjoin( self.folder.decode(path_encoding).encode('utf8'), dbpath) if not 'check_same_thread' in driver_args: driver_args['check_same_thread'] = False if not 'detect_types' in driver_args and do_connect: driver_args['detect_types'] = self.driver.PARSE_DECLTYPES def connector(dbpath=dbpath, driver_args=driver_args): return self.driver.Connection(dbpath, **driver_args) self.connector = connector if do_connect: self.reconnect() def after_connection(self): self.connection.enable_load_extension(True) # for Windows, rename libspatialite-2.dll to libspatialite.dll # Linux uses libspatialite.so # Mac OS X uses libspatialite.dylib libspatialite = SPATIALLIBS[platform.system()] self.execute(r'SELECT load_extension("%s");' % libspatialite) self.connection.create_function('web2py_extract', 2, SQLiteAdapter.web2py_extract) self.connection.create_function("REGEXP", 2, SQLiteAdapter.web2py_regexp) # GIS functions def ST_ASGEOJSON(self, first, second): return 'AsGeoJSON(%s,%s,%s)' %(self.expand(first), second['precision'], second['options']) def ST_ASTEXT(self, first): return 'AsText(%s)' %(self.expand(first)) def ST_CONTAINS(self, first, second): return 'Contains(%s,%s)' %(self.expand(first), self.expand(second, first.type)) def ST_DISTANCE(self, first, second): return 'Distance(%s,%s)' %(self.expand(first), self.expand(second, first.type)) def ST_EQUALS(self, first, second): return 'Equals(%s,%s)' %(self.expand(first), self.expand(second, first.type)) def ST_INTERSECTS(self, first, second): return 'Intersects(%s,%s)' %(self.expand(first), self.expand(second, first.type)) def ST_OVERLAPS(self, first, second): return 'Overlaps(%s,%s)' %(self.expand(first), self.expand(second, first.type)) def ST_SIMPLIFY(self, first, second): return 'Simplify(%s,%s)' %(self.expand(first), self.expand(second, 'double')) def ST_TOUCHES(self, first, second): return 'Touches(%s,%s)' %(self.expand(first), self.expand(second, first.type)) def ST_WITHIN(self, first, second): return 'Within(%s,%s)' %(self.expand(first), self.expand(second, first.type)) def represent(self, obj, fieldtype): field_is_type = fieldtype.startswith if field_is_type('geo'): srid = 4326 # Spatialite default srid for geometry geotype, parms = fieldtype[:-1].split('(') parms = parms.split(',') if len(parms) >= 2: schema, srid = parms[:2] # if field_is_type('geometry'): value = "ST_GeomFromText('%s',%s)" %(obj, srid) # elif field_is_type('geography'): # value = "ST_GeogFromText('SRID=%s;%s')" %(srid, obj) # else: # raise SyntaxError, 'Invalid field type %s' %fieldtype return value return BaseAdapter.represent(self, obj, fieldtype) class JDBCSQLiteAdapter(SQLiteAdapter): drivers = ('zxJDBC_sqlite',) def __init__(self, db, uri, pool_size=0, folder=None, db_codec='UTF-8', credential_decoder=IDENTITY, driver_args={}, adapter_args={}, do_connect=True, after_connection=None): self.db = db self.dbengine = "sqlite" self.uri = uri if do_connect: self.find_driver(adapter_args) self.pool_size = pool_size self.folder = folder self.db_codec = db_codec self._after_connection = after_connection self.find_or_make_work_folder() path_encoding = sys.getfilesystemencoding() \ or locale.getdefaultlocale()[1] or 'utf8' if uri.startswith('sqlite:memory'): dbpath = ':memory:' else: dbpath = uri.split('://',1)[1] if dbpath[0] != '/': dbpath = pjoin( self.folder.decode(path_encoding).encode('utf8'), dbpath) def connector(dbpath=dbpath,driver_args=driver_args): return self.driver.connect( self.driver.getConnection('jdbc:sqlite:'+dbpath), **driver_args) self.connector = connector if do_connect: self.reconnect() def after_connection(self): # FIXME http://www.zentus.com/sqlitejdbc/custom_functions.html for UDFs self.connection.create_function('web2py_extract', 2, SQLiteAdapter.web2py_extract) def execute(self, a): return self.log_execute(a) class MySQLAdapter(BaseAdapter): drivers = ('MySQLdb','pymysql') commit_on_alter_table = True support_distributed_transaction = True types = { 'boolean': 'CHAR(1)', 'string': 'VARCHAR(%(length)s)', 'text': 'LONGTEXT', 'json': 'LONGTEXT', 'password': 'VARCHAR(%(length)s)', 'blob': 'LONGBLOB', 'upload': 'VARCHAR(%(length)s)', 'integer': 'INT', 'bigint': 'BIGINT', 'float': 'FLOAT', 'double': 'DOUBLE', 'decimal': 'NUMERIC(%(precision)s,%(scale)s)', 'date': 'DATE', 'time': 'TIME', 'datetime': 'DATETIME', 'id': 'INT AUTO_INCREMENT NOT NULL', 'reference': 'INT, INDEX %(index_name)s (%(field_name)s), FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', 'list:integer': 'LONGTEXT', 'list:string': 'LONGTEXT', 'list:reference': 'LONGTEXT', 'big-id': 'BIGINT AUTO_INCREMENT NOT NULL', 'big-reference': 'BIGINT, INDEX %(index_name)s (%(field_name)s), FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', } QUOTE_TEMPLATE = "`%s`" def varquote(self,name): return varquote_aux(name,'`%s`') def RANDOM(self): return 'RAND()' def SUBSTRING(self,field,parameters): return 'SUBSTRING(%s,%s,%s)' % (self.expand(field), parameters[0], parameters[1]) def EPOCH(self, first): return "UNIX_TIMESTAMP(%s)" % self.expand(first) def CONCAT(self, *items): return 'CONCAT(%s)' % ','.join(self.expand(x,'string') for x in items) def REGEXP(self,first,second): return '(%s REGEXP %s)' % (self.expand(first), self.expand(second,'string')) def _drop(self,table,mode): # breaks db integrity but without this mysql does not drop table return ['SET FOREIGN_KEY_CHECKS=0;','DROP TABLE %s;' % table, 'SET FOREIGN_KEY_CHECKS=1;'] def _insert_empty(self, table): return 'INSERT INTO %s VALUES (DEFAULT);' % table def distributed_transaction_begin(self,key): self.execute('XA START;') def prepare(self,key): self.execute("XA END;") self.execute("XA PREPARE;") def commit_prepared(self,ley): self.execute("XA COMMIT;") def rollback_prepared(self,key): self.execute("XA ROLLBACK;") REGEX_URI = re.compile('^(?P<user>[^:@]+)(\:(?P<password>[^@]*))?@(?P<host>[^\:/]+)(\:(?P<port>[0-9]+))?/(?P<db>[^?]+)(\?set_encoding=(?P<charset>\w+))?$') def __init__(self,db,uri,pool_size=0,folder=None,db_codec ='UTF-8', credential_decoder=IDENTITY, driver_args={}, adapter_args={}, do_connect=True, after_connection=None): self.db = db self.dbengine = "mysql" self.uri = uri if do_connect: self.find_driver(adapter_args,uri) self.pool_size = pool_size self.folder = folder self.db_codec = db_codec self._after_connection = after_connection self.find_or_make_work_folder() ruri = uri.split('://',1)[1] m = self.REGEX_URI.match(ruri) if not m: raise SyntaxError( "Invalid URI string in DAL: %s" % self.uri) user = credential_decoder(m.group('user')) if not user: raise SyntaxError('User required') password = credential_decoder(m.group('password')) if not password: password = '' host = m.group('host') if not host: raise SyntaxError('Host name required') db = m.group('db') if not db: raise SyntaxError('Database name required') port = int(m.group('port') or '3306') charset = m.group('charset') or 'utf8' driver_args.update(db=db, user=credential_decoder(user), passwd=credential_decoder(password), host=host, port=port, charset=charset) def connector(driver_args=driver_args): return self.driver.connect(**driver_args) self.connector = connector if do_connect: self.reconnect() def after_connection(self): self.execute('SET FOREIGN_KEY_CHECKS=1;') self.execute("SET sql_mode='NO_BACKSLASH_ESCAPES';") def lastrowid(self,table): self.execute('select last_insert_id();') return int(self.cursor.fetchone()[0]) class PostgreSQLAdapter(BaseAdapter): drivers = ('psycopg2','pg8000') support_distributed_transaction = True types = { 'boolean': 'CHAR(1)', 'string': 'VARCHAR(%(length)s)', 'text': 'TEXT', 'json': 'TEXT', 'password': 'VARCHAR(%(length)s)', 'blob': 'BYTEA', 'upload': 'VARCHAR(%(length)s)', 'integer': 'INTEGER', 'bigint': 'BIGINT', 'float': 'FLOAT', 'double': 'FLOAT8', 'decimal': 'NUMERIC(%(precision)s,%(scale)s)', 'date': 'DATE', 'time': 'TIME', 'datetime': 'TIMESTAMP', 'id': 'SERIAL PRIMARY KEY', 'reference': 'INTEGER REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', 'list:integer': 'TEXT', 'list:string': 'TEXT', 'list:reference': 'TEXT', 'geometry': 'GEOMETRY', 'geography': 'GEOGRAPHY', 'big-id': 'BIGSERIAL PRIMARY KEY', 'big-reference': 'BIGINT REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', 'reference FK': ', CONSTRAINT FK_%(constraint_name)s FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', 'reference TFK': ' CONSTRAINT FK_%(foreign_table)s_PK FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_table)s (%(foreign_key)s) ON DELETE %(on_delete_action)s', } def varquote(self,name): return varquote_aux(name,'"%s"') def adapt(self,obj): if self.driver_name == 'psycopg2': return psycopg2_adapt(obj).getquoted() elif self.driver_name == 'pg8000': return "'%s'" % str(obj).replace("%","%%").replace("'","''") else: return "'%s'" % str(obj).replace("'","''") def sequence_name(self,table): return '%s_id_Seq' % table def RANDOM(self): return 'RANDOM()' def ADD(self, first, second): t = first.type if t in ('text','string','password', 'json', 'upload','blob'): return '(%s || %s)' % (self.expand(first), self.expand(second, t)) else: return '(%s + %s)' % (self.expand(first), self.expand(second, t)) def distributed_transaction_begin(self,key): return def prepare(self,key): self.execute("PREPARE TRANSACTION '%s';" % key) def commit_prepared(self,key): self.execute("COMMIT PREPARED '%s';" % key) def rollback_prepared(self,key): self.execute("ROLLBACK PREPARED '%s';" % key) def create_sequence_and_triggers(self, query, table, **args): # following lines should only be executed if table._sequence_name does not exist # self.execute('CREATE SEQUENCE %s;' % table._sequence_name) # self.execute("ALTER TABLE %s ALTER COLUMN %s SET DEFAULT NEXTVAL('%s');" \ # % (table._tablename, table._fieldname, table._sequence_name)) self.execute(query) REGEX_URI = re.compile('^(?P<user>[^:@]+)(\:(?P<password>[^@]*))?@(?P<host>[^\:@]+)(\:(?P<port>[0-9]+))?/(?P<db>[^\?]+)(\?sslmode=(?P<sslmode>.+))?$') def __init__(self,db,uri,pool_size=0,folder=None,db_codec ='UTF-8', credential_decoder=IDENTITY, driver_args={}, adapter_args={}, do_connect=True, srid=4326, after_connection=None): self.db = db self.dbengine = "postgres" self.uri = uri if do_connect: self.find_driver(adapter_args,uri) self.pool_size = pool_size self.folder = folder self.db_codec = db_codec self._after_connection = after_connection self.srid = srid self.find_or_make_work_folder() ruri = uri.split('://',1)[1] m = self.REGEX_URI.match(ruri) if not m: raise SyntaxError("Invalid URI string in DAL") user = credential_decoder(m.group('user')) if not user: raise SyntaxError('User required') password = credential_decoder(m.group('password')) if not password: password = '' host = m.group('host') if not host: raise SyntaxError('Host name required') db = m.group('db') if not db: raise SyntaxError('Database name required') port = m.group('port') or '5432' sslmode = m.group('sslmode') if sslmode: msg = ("dbname='%s' user='%s' host='%s' " "port=%s password='%s' sslmode='%s'") \ % (db, user, host, port, password, sslmode) else: msg = ("dbname='%s' user='%s' host='%s' " "port=%s password='%s'") \ % (db, user, host, port, password) # choose diver according uri if self.driver: self.__version__ = "%s %s" % (self.driver.__name__, self.driver.__version__) else: self.__version__ = None def connector(msg=msg,driver_args=driver_args): return self.driver.connect(msg,**driver_args) self.connector = connector if do_connect: self.reconnect() def after_connection(self): self.connection.set_client_encoding('UTF8') self.execute("SET standard_conforming_strings=on;") self.try_json() def lastrowid(self,table): self.execute("select currval('%s')" % table._sequence_name) return int(self.cursor.fetchone()[0]) def try_json(self): # check JSON data type support # (to be added to after_connection) if self.driver_name == "pg8000": supports_json = self.connection.server_version >= "9.2.0" elif (self.driver_name == "psycopg2") and \ (self.driver.__version__ >= "2.0.12"): supports_json = self.connection.server_version >= 90200 elif self.driver_name == "zxJDBC": supports_json = self.connection.dbversion >= "9.2.0" else: supports_json = None if supports_json: self.types["json"] = "JSON" self.native_json = True else: LOGGER.debug("Your database version does not support the JSON data type (using TEXT instead)") def LIKE(self,first,second): args = (self.expand(first), self.expand(second,'string')) if not first.type in ('string', 'text', 'json'): return '(CAST(%s AS CHAR(%s)) LIKE %s)' % (args[0], first.length, args[1]) else: return '(%s LIKE %s)' % args def ILIKE(self,first,second): args = (self.expand(first), self.expand(second,'string')) if not first.type in ('string', 'text', 'json'): return '(CAST(%s AS CHAR(%s)) LIKE %s)' % (args[0], first.length, args[1]) else: return '(%s ILIKE %s)' % args def REGEXP(self,first,second): return '(%s ~ %s)' % (self.expand(first), self.expand(second,'string')) def STARTSWITH(self,first,second): return '(%s ILIKE %s)' % (self.expand(first), self.expand(second+'%','string')) def ENDSWITH(self,first,second): return '(%s ILIKE %s)' % (self.expand(first), self.expand('%'+second,'string')) # GIS functions def ST_ASGEOJSON(self, first, second): """ http://postgis.org/docs/ST_AsGeoJSON.html """ return 'ST_AsGeoJSON(%s,%s,%s,%s)' %(second['version'], self.expand(first), second['precision'], second['options']) def ST_ASTEXT(self, first): """ http://postgis.org/docs/ST_AsText.html """ return 'ST_AsText(%s)' %(self.expand(first)) def ST_X(self, first): """ http://postgis.org/docs/ST_X.html """ return 'ST_X(%s)' %(self.expand(first)) def ST_Y(self, first): """ http://postgis.org/docs/ST_Y.html """ return 'ST_Y(%s)' %(self.expand(first)) def ST_CONTAINS(self, first, second): """ http://postgis.org/docs/ST_Contains.html """ return 'ST_Contains(%s,%s)' %(self.expand(first), self.expand(second, first.type)) def ST_DISTANCE(self, first, second): """ http://postgis.org/docs/ST_Distance.html """ return 'ST_Distance(%s,%s)' %(self.expand(first), self.expand(second, first.type)) def ST_EQUALS(self, first, second): """ http://postgis.org/docs/ST_Equals.html """ return 'ST_Equals(%s,%s)' %(self.expand(first), self.expand(second, first.type)) def ST_INTERSECTS(self, first, second): """ http://postgis.org/docs/ST_Intersects.html """ return 'ST_Intersects(%s,%s)' %(self.expand(first), self.expand(second, first.type)) def ST_OVERLAPS(self, first, second): """ http://postgis.org/docs/ST_Overlaps.html """ return 'ST_Overlaps(%s,%s)' %(self.expand(first), self.expand(second, first.type)) def ST_SIMPLIFY(self, first, second): """ http://postgis.org/docs/ST_Simplify.html """ return 'ST_Simplify(%s,%s)' %(self.expand(first), self.expand(second, 'double')) def ST_TOUCHES(self, first, second): """ http://postgis.org/docs/ST_Touches.html """ return 'ST_Touches(%s,%s)' %(self.expand(first), self.expand(second, first.type)) def ST_WITHIN(self, first, second): """ http://postgis.org/docs/ST_Within.html """ return 'ST_Within(%s,%s)' %(self.expand(first), self.expand(second, first.type)) def represent(self, obj, fieldtype): field_is_type = fieldtype.startswith if field_is_type('geo'): srid = 4326 # postGIS default srid for geometry geotype, parms = fieldtype[:-1].split('(') parms = parms.split(',') if len(parms) >= 2: schema, srid = parms[:2] if field_is_type('geometry'): value = "ST_GeomFromText('%s',%s)" %(obj, srid) elif field_is_type('geography'): value = "ST_GeogFromText('SRID=%s;%s')" %(srid, obj) # else: # raise SyntaxError('Invalid field type %s' %fieldtype) return value return BaseAdapter.represent(self, obj, fieldtype) class NewPostgreSQLAdapter(PostgreSQLAdapter): drivers = ('psycopg2','pg8000') types = { 'boolean': 'CHAR(1)', 'string': 'VARCHAR(%(length)s)', 'text': 'TEXT', 'json': 'TEXT', 'password': 'VARCHAR(%(length)s)', 'blob': 'BYTEA', 'upload': 'VARCHAR(%(length)s)', 'integer': 'INTEGER', 'bigint': 'BIGINT', 'float': 'FLOAT', 'double': 'FLOAT8', 'decimal': 'NUMERIC(%(precision)s,%(scale)s)', 'date': 'DATE', 'time': 'TIME', 'datetime': 'TIMESTAMP', 'id': 'SERIAL PRIMARY KEY', 'reference': 'INTEGER REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', 'list:integer': 'BIGINT[]', 'list:string': 'TEXT[]', 'list:reference': 'BIGINT[]', 'geometry': 'GEOMETRY', 'geography': 'GEOGRAPHY', 'big-id': 'BIGSERIAL PRIMARY KEY', 'big-reference': 'BIGINT REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', } def parse_list_integers(self, value, field_type): return value def parse_list_references(self, value, field_type): return [self.parse_reference(r, field_type[5:]) for r in value] def parse_list_strings(self, value, field_type): return value def represent(self, obj, fieldtype): field_is_type = fieldtype.startswith if field_is_type('list:'): if not obj: obj = [] elif not isinstance(obj, (list, tuple)): obj = [obj] if field_is_type('list:string'): obj = map(str,obj) else: obj = map(int,obj) return 'ARRAY[%s]' % ','.join(repr(item) for item in obj) return BaseAdapter.represent(self, obj, fieldtype) class JDBCPostgreSQLAdapter(PostgreSQLAdapter): drivers = ('zxJDBC',) REGEX_URI = re.compile('^(?P<user>[^:@]+)(\:(?P<password>[^@]*))?@(?P<host>[^\:/]+)(\:(?P<port>[0-9]+))?/(?P<db>.+)$') def __init__(self,db,uri,pool_size=0,folder=None,db_codec ='UTF-8', credential_decoder=IDENTITY, driver_args={}, adapter_args={}, do_connect=True, after_connection=None ): self.db = db self.dbengine = "postgres" self.uri = uri if do_connect: self.find_driver(adapter_args,uri) self.pool_size = pool_size self.folder = folder self.db_codec = db_codec self._after_connection = after_connection self.find_or_make_work_folder() ruri = uri.split('://',1)[1] m = self.REGEX_URI.match(ruri) if not m: raise SyntaxError("Invalid URI string in DAL") user = credential_decoder(m.group('user')) if not user: raise SyntaxError('User required') password = credential_decoder(m.group('password')) if not password: password = '' host = m.group('host') if not host: raise SyntaxError('Host name required') db = m.group('db') if not db: raise SyntaxError('Database name required') port = m.group('port') or '5432' msg = ('jdbc:postgresql://%s:%s/%s' % (host, port, db), user, password) def connector(msg=msg,driver_args=driver_args): return self.driver.connect(*msg,**driver_args) self.connector = connector if do_connect: self.reconnect() def after_connection(self): self.connection.set_client_encoding('UTF8') self.execute('BEGIN;') self.execute("SET CLIENT_ENCODING TO 'UNICODE';") self.try_json() class OracleAdapter(BaseAdapter): drivers = ('cx_Oracle',) commit_on_alter_table = False types = { 'boolean': 'CHAR(1)', 'string': 'VARCHAR2(%(length)s)', 'text': 'CLOB', 'json': 'CLOB', 'password': 'VARCHAR2(%(length)s)', 'blob': 'CLOB', 'upload': 'VARCHAR2(%(length)s)', 'integer': 'INT', 'bigint': 'NUMBER', 'float': 'FLOAT', 'double': 'BINARY_DOUBLE', 'decimal': 'NUMERIC(%(precision)s,%(scale)s)', 'date': 'DATE', 'time': 'CHAR(8)', 'datetime': 'DATE', 'id': 'NUMBER PRIMARY KEY', 'reference': 'NUMBER, CONSTRAINT %(constraint_name)s FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', 'list:integer': 'CLOB', 'list:string': 'CLOB', 'list:reference': 'CLOB', 'big-id': 'NUMBER PRIMARY KEY', 'big-reference': 'NUMBER, CONSTRAINT %(constraint_name)s FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', 'reference FK': ', CONSTRAINT FK_%(constraint_name)s FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', 'reference TFK': ' CONSTRAINT FK_%(foreign_table)s_PK FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_table)s (%(foreign_key)s) ON DELETE %(on_delete_action)s', } def sequence_name(self,tablename): return '%s_sequence' % tablename def trigger_name(self,tablename): return '%s_trigger' % tablename def LEFT_JOIN(self): return 'LEFT OUTER JOIN' def RANDOM(self): return 'dbms_random.value' def NOT_NULL(self,default,field_type): return 'DEFAULT %s NOT NULL' % self.represent(default,field_type) def _drop(self,table,mode): sequence_name = table._sequence_name return ['DROP TABLE %s %s;' % (table, mode), 'DROP SEQUENCE %s;' % sequence_name] def select_limitby(self, sql_s, sql_f, sql_t, sql_w, sql_o, limitby): if limitby: (lmin, lmax) = limitby if len(sql_w) > 1: sql_w_row = sql_w + ' AND w_row > %i' % lmin else: sql_w_row = 'WHERE w_row > %i' % lmin return 'SELECT %s %s FROM (SELECT w_tmp.*, ROWNUM w_row FROM (SELECT %s FROM %s%s%s) w_tmp WHERE ROWNUM<=%i) %s %s %s;' % (sql_s, sql_f, sql_f, sql_t, sql_w, sql_o, lmax, sql_t, sql_w_row, sql_o) return 'SELECT %s %s FROM %s%s%s;' % (sql_s, sql_f, sql_t, sql_w, sql_o) def constraint_name(self, tablename, fieldname): constraint_name = BaseAdapter.constraint_name(self, tablename, fieldname) if len(constraint_name)>30: constraint_name = '%s_%s__constraint' % (tablename[:10], fieldname[:7]) return constraint_name def represent_exceptions(self, obj, fieldtype): if fieldtype == 'blob': obj = base64.b64encode(str(obj)) return ":CLOB('%s')" % obj elif fieldtype == 'date': if isinstance(obj, (datetime.date, datetime.datetime)): obj = obj.isoformat()[:10] else: obj = str(obj) return "to_date('%s','yyyy-mm-dd')" % obj elif fieldtype == 'datetime': if isinstance(obj, datetime.datetime): obj = obj.isoformat()[:19].replace('T',' ') elif isinstance(obj, datetime.date): obj = obj.isoformat()[:10]+' 00:00:00' else: obj = str(obj) return "to_date('%s','yyyy-mm-dd hh24:mi:ss')" % obj return None def __init__(self,db,uri,pool_size=0,folder=None,db_codec ='UTF-8', credential_decoder=IDENTITY, driver_args={}, adapter_args={}, do_connect=True, after_connection=None): self.db = db self.dbengine = "oracle" self.uri = uri if do_connect: self.find_driver(adapter_args,uri) self.pool_size = pool_size self.folder = folder self.db_codec = db_codec self._after_connection = after_connection self.find_or_make_work_folder() ruri = uri.split('://',1)[1] if not 'threaded' in driver_args: driver_args['threaded']=True def connector(uri=ruri,driver_args=driver_args): return self.driver.connect(uri,**driver_args) self.connector = connector if do_connect: self.reconnect() def after_connection(self): self.execute("ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD HH24:MI:SS';") self.execute("ALTER SESSION SET NLS_TIMESTAMP_FORMAT = 'YYYY-MM-DD HH24:MI:SS';") oracle_fix = re.compile("[^']*('[^']*'[^']*)*\:(?P<clob>CLOB\('([^']+|'')*'\))") def execute(self, command, args=None): args = args or [] i = 1 while True: m = self.oracle_fix.match(command) if not m: break command = command[:m.start('clob')] + str(i) + command[m.end('clob'):] args.append(m.group('clob')[6:-2].replace("''", "'")) i += 1 if command[-1:]==';': command = command[:-1] return self.log_execute(command, args) def create_sequence_and_triggers(self, query, table, **args): tablename = table._tablename id_name = table._id.name sequence_name = table._sequence_name trigger_name = table._trigger_name self.execute(query) self.execute('CREATE SEQUENCE %s START WITH 1 INCREMENT BY 1 NOMAXVALUE MINVALUE -1;' % sequence_name) self.execute(""" CREATE OR REPLACE TRIGGER %(trigger_name)s BEFORE INSERT ON %(tablename)s FOR EACH ROW DECLARE curr_val NUMBER; diff_val NUMBER; PRAGMA autonomous_transaction; BEGIN IF :NEW.%(id)s IS NOT NULL THEN EXECUTE IMMEDIATE 'SELECT %(sequence_name)s.nextval FROM dual' INTO curr_val; diff_val := :NEW.%(id)s - curr_val - 1; IF diff_val != 0 THEN EXECUTE IMMEDIATE 'alter sequence %(sequence_name)s increment by '|| diff_val; EXECUTE IMMEDIATE 'SELECT %(sequence_name)s.nextval FROM dual' INTO curr_val; EXECUTE IMMEDIATE 'alter sequence %(sequence_name)s increment by 1'; END IF; END IF; SELECT %(sequence_name)s.nextval INTO :NEW.%(id)s FROM DUAL; END; """ % dict(trigger_name=trigger_name, tablename=tablename, sequence_name=sequence_name,id=id_name)) def lastrowid(self,table): sequence_name = table._sequence_name self.execute('SELECT %s.currval FROM dual;' % sequence_name) return long(self.cursor.fetchone()[0]) #def parse_value(self, value, field_type, blob_decode=True): # if blob_decode and isinstance(value, cx_Oracle.LOB): # try: # value = value.read() # except self.driver.ProgrammingError: # # After a subsequent fetch the LOB value is not valid anymore # pass # return BaseAdapter.parse_value(self, value, field_type, blob_decode) def _fetchall(self): if any(x[1]==cx_Oracle.CLOB for x in self.cursor.description): return [tuple([(c.read() if type(c) == cx_Oracle.LOB else c) \ for c in r]) for r in self.cursor] else: return self.cursor.fetchall() class MSSQLAdapter(BaseAdapter): drivers = ('pyodbc',) T_SEP = 'T' QUOTE_TEMPLATE = "[%s]" types = { 'boolean': 'BIT', 'string': 'VARCHAR(%(length)s)', 'text': 'TEXT', 'json': 'TEXT', 'password': 'VARCHAR(%(length)s)', 'blob': 'IMAGE', 'upload': 'VARCHAR(%(length)s)', 'integer': 'INT', 'bigint': 'BIGINT', 'float': 'FLOAT', 'double': 'FLOAT', 'decimal': 'NUMERIC(%(precision)s,%(scale)s)', 'date': 'DATETIME', 'time': 'CHAR(8)', 'datetime': 'DATETIME', 'id': 'INT IDENTITY PRIMARY KEY', 'reference': 'INT NULL, CONSTRAINT %(constraint_name)s FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', 'list:integer': 'TEXT', 'list:string': 'TEXT', 'list:reference': 'TEXT', 'geometry': 'geometry', 'geography': 'geography', 'big-id': 'BIGINT IDENTITY PRIMARY KEY', 'big-reference': 'BIGINT NULL, CONSTRAINT %(constraint_name)s FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', 'reference FK': ', CONSTRAINT FK_%(constraint_name)s FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', 'reference TFK': ' CONSTRAINT FK_%(foreign_table)s_PK FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_table)s (%(foreign_key)s) ON DELETE %(on_delete_action)s', } def concat_add(self,tablename): return '; ALTER TABLE %s ADD ' % tablename def varquote(self,name): return varquote_aux(name,'[%s]') def EXTRACT(self,field,what): return "DATEPART(%s,%s)" % (what, self.expand(field)) def LEFT_JOIN(self): return 'LEFT OUTER JOIN' def RANDOM(self): return 'NEWID()' def ALLOW_NULL(self): return ' NULL' def SUBSTRING(self,field,parameters): return 'SUBSTRING(%s,%s,%s)' % (self.expand(field), parameters[0], parameters[1]) def PRIMARY_KEY(self,key): return 'PRIMARY KEY CLUSTERED (%s)' % key def AGGREGATE(self, first, what): if what == 'LENGTH': what = 'LEN' return "%s(%s)" % (what, self.expand(first)) def select_limitby(self, sql_s, sql_f, sql_t, sql_w, sql_o, limitby): if limitby: (lmin, lmax) = limitby sql_s += ' TOP %i' % lmax if 'GROUP BY' in sql_o: orderfound = sql_o.find('ORDER BY ') if orderfound >= 0: sql_o = sql_o[:orderfound] return 'SELECT %s %s FROM %s%s%s;' % (sql_s, sql_f, sql_t, sql_w, sql_o) TRUE = 1 FALSE = 0 REGEX_DSN = re.compile('^(?P<dsn>.+)$') REGEX_URI = re.compile('^(?P<user>[^:@]+)(\:(?P<password>[^@]*))?@(?P<host>[^\:/]+)(\:(?P<port>[0-9]+))?/(?P<db>[^\?]+)(\?(?P<urlargs>.*))?$') REGEX_ARGPATTERN = re.compile('(?P<argkey>[^=]+)=(?P<argvalue>[^&]*)') def __init__(self,db,uri,pool_size=0,folder=None,db_codec ='UTF-8', credential_decoder=IDENTITY, driver_args={}, adapter_args={}, do_connect=True, srid=4326, after_connection=None): self.db = db self.dbengine = "mssql" self.uri = uri if do_connect: self.find_driver(adapter_args,uri) self.pool_size = pool_size self.folder = folder self.db_codec = db_codec self._after_connection = after_connection self.srid = srid self.find_or_make_work_folder() # ## read: http://bytes.com/groups/python/460325-cx_oracle-utf8 ruri = uri.split('://',1)[1] if '@' not in ruri: try: m = self.REGEX_DSN.match(ruri) if not m: raise SyntaxError( 'Parsing uri string(%s) has no result' % self.uri) dsn = m.group('dsn') if not dsn: raise SyntaxError('DSN required') except SyntaxError: e = sys.exc_info()[1] LOGGER.error('NdGpatch error') raise e # was cnxn = 'DSN=%s' % dsn cnxn = dsn else: m = self.REGEX_URI.match(ruri) if not m: raise SyntaxError( "Invalid URI string in DAL: %s" % self.uri) user = credential_decoder(m.group('user')) if not user: raise SyntaxError('User required') password = credential_decoder(m.group('password')) if not password: password = '' host = m.group('host') if not host: raise SyntaxError('Host name required') db = m.group('db') if not db: raise SyntaxError('Database name required') port = m.group('port') or '1433' # Parse the optional url name-value arg pairs after the '?' # (in the form of arg1=value1&arg2=value2&...) # Default values (drivers like FreeTDS insist on uppercase parameter keys) argsdict = { 'DRIVER':'{SQL Server}' } urlargs = m.group('urlargs') or '' for argmatch in self.REGEX_ARGPATTERN.finditer(urlargs): argsdict[str(argmatch.group('argkey')).upper()] = argmatch.group('argvalue') urlargs = ';'.join(['%s=%s' % (ak, av) for (ak, av) in argsdict.iteritems()]) cnxn = 'SERVER=%s;PORT=%s;DATABASE=%s;UID=%s;PWD=%s;%s' \ % (host, port, db, user, password, urlargs) def connector(cnxn=cnxn,driver_args=driver_args): return self.driver.connect(cnxn,**driver_args) self.connector = connector if do_connect: self.reconnect() def lastrowid(self,table): #self.execute('SELECT @@IDENTITY;') self.execute('SELECT SCOPE_IDENTITY();') return long(self.cursor.fetchone()[0]) def rowslice(self,rows,minimum=0,maximum=None): if maximum is None: return rows[minimum:] return rows[minimum:maximum] def EPOCH(self, first): return "DATEDIFF(second, '1970-01-01 00:00:00', %s)" % self.expand(first) def CONCAT(self, *items): return '(%s)' % ' + '.join(self.expand(x,'string') for x in items) # GIS Spatial Extensions # No STAsGeoJSON in MSSQL def ST_ASTEXT(self, first): return '%s.STAsText()' %(self.expand(first)) def ST_CONTAINS(self, first, second): return '%s.STContains(%s)=1' %(self.expand(first), self.expand(second, first.type)) def ST_DISTANCE(self, first, second): return '%s.STDistance(%s)' %(self.expand(first), self.expand(second, first.type)) def ST_EQUALS(self, first, second): return '%s.STEquals(%s)=1' %(self.expand(first), self.expand(second, first.type)) def ST_INTERSECTS(self, first, second): return '%s.STIntersects(%s)=1' %(self.expand(first), self.expand(second, first.type)) def ST_OVERLAPS(self, first, second): return '%s.STOverlaps(%s)=1' %(self.expand(first), self.expand(second, first.type)) # no STSimplify in MSSQL def ST_TOUCHES(self, first, second): return '%s.STTouches(%s)=1' %(self.expand(first), self.expand(second, first.type)) def ST_WITHIN(self, first, second): return '%s.STWithin(%s)=1' %(self.expand(first), self.expand(second, first.type)) def represent(self, obj, fieldtype): field_is_type = fieldtype.startswith if field_is_type('geometry'): srid = 0 # MS SQL default srid for geometry geotype, parms = fieldtype[:-1].split('(') if parms: srid = parms return "geometry::STGeomFromText('%s',%s)" %(obj, srid) elif fieldtype == 'geography': srid = 4326 # MS SQL default srid for geography geotype, parms = fieldtype[:-1].split('(') if parms: srid = parms return "geography::STGeomFromText('%s',%s)" %(obj, srid) # else: # raise SyntaxError('Invalid field type %s' %fieldtype) return "geometry::STGeomFromText('%s',%s)" %(obj, srid) return BaseAdapter.represent(self, obj, fieldtype) class MSSQL3Adapter(MSSQLAdapter): """ experimental support for pagination in MSSQL""" def select_limitby(self, sql_s, sql_f, sql_t, sql_w, sql_o, limitby): if limitby: (lmin, lmax) = limitby if lmin == 0: sql_s += ' TOP %i' % lmax return 'SELECT %s %s FROM %s%s%s;' % (sql_s, sql_f, sql_t, sql_w, sql_o) lmin += 1 sql_o_inner = sql_o[sql_o.find('ORDER BY ')+9:] sql_g_inner = sql_o[:sql_o.find('ORDER BY ')] sql_f_outer = ['f_%s' % f for f in range(len(sql_f.split(',')))] sql_f_inner = [f for f in sql_f.split(',')] sql_f_iproxy = ['%s AS %s' % (o, n) for (o, n) in zip(sql_f_inner, sql_f_outer)] sql_f_iproxy = ', '.join(sql_f_iproxy) sql_f_oproxy = ', '.join(sql_f_outer) return 'SELECT %s %s FROM (SELECT %s ROW_NUMBER() OVER (ORDER BY %s) AS w_row, %s FROM %s%s%s) TMP WHERE w_row BETWEEN %i AND %s;' % (sql_s,sql_f_oproxy,sql_s,sql_f,sql_f_iproxy,sql_t,sql_w,sql_g_inner,lmin,lmax) return 'SELECT %s %s FROM %s%s%s;' % (sql_s,sql_f,sql_t,sql_w,sql_o) def rowslice(self,rows,minimum=0,maximum=None): return rows class MSSQL2Adapter(MSSQLAdapter): drivers = ('pyodbc',) types = { 'boolean': 'CHAR(1)', 'string': 'NVARCHAR(%(length)s)', 'text': 'NTEXT', 'json': 'NTEXT', 'password': 'NVARCHAR(%(length)s)', 'blob': 'IMAGE', 'upload': 'NVARCHAR(%(length)s)', 'integer': 'INT', 'bigint': 'BIGINT', 'float': 'FLOAT', 'double': 'FLOAT', 'decimal': 'NUMERIC(%(precision)s,%(scale)s)', 'date': 'DATETIME', 'time': 'CHAR(8)', 'datetime': 'DATETIME', 'id': 'INT IDENTITY PRIMARY KEY', 'reference': 'INT, CONSTRAINT %(constraint_name)s FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', 'list:integer': 'NTEXT', 'list:string': 'NTEXT', 'list:reference': 'NTEXT', 'big-id': 'BIGINT IDENTITY PRIMARY KEY', 'big-reference': 'BIGINT, CONSTRAINT %(constraint_name)s FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', 'reference FK': ', CONSTRAINT FK_%(constraint_name)s FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', 'reference TFK': ' CONSTRAINT FK_%(foreign_table)s_PK FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_table)s (%(foreign_key)s) ON DELETE %(on_delete_action)s', } def represent(self, obj, fieldtype): value = BaseAdapter.represent(self, obj, fieldtype) if fieldtype in ('string','text', 'json') and value[:1]=="'": value = 'N'+value return value def execute(self,a): return self.log_execute(a.decode('utf8')) class VerticaAdapter(MSSQLAdapter): drivers = ('pyodbc',) T_SEP = ' ' types = { 'boolean': 'BOOLEAN', 'string': 'VARCHAR(%(length)s)', 'text': 'BYTEA', 'json': 'VARCHAR(%(length)s)', 'password': 'VARCHAR(%(length)s)', 'blob': 'BYTEA', 'upload': 'VARCHAR(%(length)s)', 'integer': 'INT', 'bigint': 'BIGINT', 'float': 'FLOAT', 'double': 'DOUBLE PRECISION', 'decimal': 'DECIMAL(%(precision)s,%(scale)s)', 'date': 'DATE', 'time': 'TIME', 'datetime': 'DATETIME', 'id': 'IDENTITY', 'reference': 'INT REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', 'list:integer': 'BYTEA', 'list:string': 'BYTEA', 'list:reference': 'BYTEA', 'big-reference': 'BIGINT REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', } def EXTRACT(self, first, what): return "DATE_PART('%s', TIMESTAMP %s)" % (what, self.expand(first)) def _truncate(self, table, mode=''): tablename = table._tablename return ['TRUNCATE %s %s;' % (tablename, mode or '')] def select_limitby(self, sql_s, sql_f, sql_t, sql_w, sql_o, limitby): if limitby: (lmin, lmax) = limitby sql_o += ' LIMIT %i OFFSET %i' % (lmax - lmin, lmin) return 'SELECT %s %s FROM %s%s%s;' % \ (sql_s, sql_f, sql_t, sql_w, sql_o) def lastrowid(self,table): self.execute('SELECT LAST_INSERT_ID();') return long(self.cursor.fetchone()[0]) def execute(self, a): return self.log_execute(a) class SybaseAdapter(MSSQLAdapter): drivers = ('Sybase',) types = { 'boolean': 'BIT', 'string': 'CHAR VARYING(%(length)s)', 'text': 'TEXT', 'json': 'TEXT', 'password': 'CHAR VARYING(%(length)s)', 'blob': 'IMAGE', 'upload': 'CHAR VARYING(%(length)s)', 'integer': 'INT', 'bigint': 'BIGINT', 'float': 'FLOAT', 'double': 'FLOAT', 'decimal': 'NUMERIC(%(precision)s,%(scale)s)', 'date': 'DATETIME', 'time': 'CHAR(8)', 'datetime': 'DATETIME', 'id': 'INT IDENTITY PRIMARY KEY', 'reference': 'INT NULL, CONSTRAINT %(constraint_name)s FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', 'list:integer': 'TEXT', 'list:string': 'TEXT', 'list:reference': 'TEXT', 'geometry': 'geometry', 'geography': 'geography', 'big-id': 'BIGINT IDENTITY PRIMARY KEY', 'big-reference': 'BIGINT NULL, CONSTRAINT %(constraint_name)s FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', 'reference FK': ', CONSTRAINT FK_%(constraint_name)s FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', 'reference TFK': ' CONSTRAINT FK_%(foreign_table)s_PK FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_table)s (%(foreign_key)s) ON DELETE %(on_delete_action)s', } def __init__(self,db,uri,pool_size=0,folder=None,db_codec ='UTF-8', credential_decoder=IDENTITY, driver_args={}, adapter_args={}, do_connect=True, srid=4326, after_connection=None): self.db = db self.dbengine = "sybase" self.uri = uri if do_connect: self.find_driver(adapter_args,uri) self.pool_size = pool_size self.folder = folder self.db_codec = db_codec self._after_connection = after_connection self.srid = srid self.find_or_make_work_folder() # ## read: http://bytes.com/groups/python/460325-cx_oracle-utf8 ruri = uri.split('://',1)[1] if '@' not in ruri: try: m = self.REGEX_DSN.match(ruri) if not m: raise SyntaxError( 'Parsing uri string(%s) has no result' % self.uri) dsn = m.group('dsn') if not dsn: raise SyntaxError('DSN required') except SyntaxError: e = sys.exc_info()[1] LOGGER.error('NdGpatch error') raise e else: m = self.REGEX_URI.match(uri) if not m: raise SyntaxError( "Invalid URI string in DAL: %s" % self.uri) user = credential_decoder(m.group('user')) if not user: raise SyntaxError('User required') password = credential_decoder(m.group('password')) if not password: password = '' host = m.group('host') if not host: raise SyntaxError('Host name required') db = m.group('db') if not db: raise SyntaxError('Database name required') port = m.group('port') or '1433' dsn = 'sybase:host=%s:%s;dbname=%s' % (host,port,db) driver_args.update(user = credential_decoder(user), password = credential_decoder(password)) def connector(dsn=dsn,driver_args=driver_args): return self.driver.connect(dsn,**driver_args) self.connector = connector if do_connect: self.reconnect() class FireBirdAdapter(BaseAdapter): drivers = ('kinterbasdb','firebirdsql','fdb','pyodbc') commit_on_alter_table = False support_distributed_transaction = True types = { 'boolean': 'CHAR(1)', 'string': 'VARCHAR(%(length)s)', 'text': 'BLOB SUB_TYPE 1', 'json': 'BLOB SUB_TYPE 1', 'password': 'VARCHAR(%(length)s)', 'blob': 'BLOB SUB_TYPE 0', 'upload': 'VARCHAR(%(length)s)', 'integer': 'INTEGER', 'bigint': 'BIGINT', 'float': 'FLOAT', 'double': 'DOUBLE PRECISION', 'decimal': 'DECIMAL(%(precision)s,%(scale)s)', 'date': 'DATE', 'time': 'TIME', 'datetime': 'TIMESTAMP', 'id': 'INTEGER PRIMARY KEY', 'reference': 'INTEGER REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', 'list:integer': 'BLOB SUB_TYPE 1', 'list:string': 'BLOB SUB_TYPE 1', 'list:reference': 'BLOB SUB_TYPE 1', 'big-id': 'BIGINT PRIMARY KEY', 'big-reference': 'BIGINT REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', } def sequence_name(self,tablename): return 'genid_%s' % tablename def trigger_name(self,tablename): return 'trg_id_%s' % tablename def RANDOM(self): return 'RAND()' def EPOCH(self, first): return "DATEDIFF(second, '1970-01-01 00:00:00', %s)" % self.expand(first) def NOT_NULL(self,default,field_type): return 'DEFAULT %s NOT NULL' % self.represent(default,field_type) def SUBSTRING(self,field,parameters): return 'SUBSTRING(%s from %s for %s)' % (self.expand(field), parameters[0], parameters[1]) def LENGTH(self, first): return "CHAR_LENGTH(%s)" % self.expand(first) def CONTAINS(self,first,second,case_sensitive=False): if first.type.startswith('list:'): second = Expression(None,self.CONCAT('|',Expression( None,self.REPLACE(second,('|','||'))),'|')) return '(%s CONTAINING %s)' % (self.expand(first), self.expand(second, 'string')) def _drop(self,table,mode): sequence_name = table._sequence_name return ['DROP TABLE %s %s;' % (table, mode), 'DROP GENERATOR %s;' % sequence_name] def select_limitby(self, sql_s, sql_f, sql_t, sql_w, sql_o, limitby): if limitby: (lmin, lmax) = limitby sql_s = ' FIRST %i SKIP %i %s' % (lmax - lmin, lmin, sql_s) return 'SELECT %s %s FROM %s%s%s;' % (sql_s, sql_f, sql_t, sql_w, sql_o) def _truncate(self,table,mode = ''): return ['DELETE FROM %s;' % table._tablename, 'SET GENERATOR %s TO 0;' % table._sequence_name] REGEX_URI = re.compile('^(?P<user>[^:@]+)(\:(?P<password>[^@]*))?@(?P<host>[^\:/]+)(\:(?P<port>[0-9]+))?/(?P<db>.+?)(\?set_encoding=(?P<charset>\w+))?$') def __init__(self,db,uri,pool_size=0,folder=None,db_codec ='UTF-8', credential_decoder=IDENTITY, driver_args={}, adapter_args={}, do_connect=True, after_connection=None): self.db = db self.dbengine = "firebird" self.uri = uri if do_connect: self.find_driver(adapter_args,uri) self.pool_size = pool_size self.folder = folder self.db_codec = db_codec self._after_connection = after_connection self.find_or_make_work_folder() ruri = uri.split('://',1)[1] m = self.REGEX_URI.match(ruri) if not m: raise SyntaxError("Invalid URI string in DAL: %s" % self.uri) user = credential_decoder(m.group('user')) if not user: raise SyntaxError('User required') password = credential_decoder(m.group('password')) if not password: password = '' host = m.group('host') if not host: raise SyntaxError('Host name required') port = int(m.group('port') or 3050) db = m.group('db') if not db: raise SyntaxError('Database name required') charset = m.group('charset') or 'UTF8' driver_args.update(dsn='%s/%s:%s' % (host,port,db), user = credential_decoder(user), password = credential_decoder(password), charset = charset) def connector(driver_args=driver_args): return self.driver.connect(**driver_args) self.connector = connector if do_connect: self.reconnect() def create_sequence_and_triggers(self, query, table, **args): tablename = table._tablename sequence_name = table._sequence_name trigger_name = table._trigger_name self.execute(query) self.execute('create generator %s;' % sequence_name) self.execute('set generator %s to 0;' % sequence_name) self.execute('create trigger %s for %s active before insert position 0 as\nbegin\nif(new.id is null) then\nbegin\nnew.id = gen_id(%s, 1);\nend\nend;' % (trigger_name, tablename, sequence_name)) def lastrowid(self,table): sequence_name = table._sequence_name self.execute('SELECT gen_id(%s, 0) FROM rdb$database' % sequence_name) return long(self.cursor.fetchone()[0]) class FireBirdEmbeddedAdapter(FireBirdAdapter): drivers = ('kinterbasdb','firebirdsql','fdb','pyodbc') REGEX_URI = re.compile('^(?P<user>[^:@]+)(\:(?P<password>[^@]*))?@(?P<path>[^\?]+)(\?set_encoding=(?P<charset>\w+))?$') def __init__(self,db,uri,pool_size=0,folder=None,db_codec ='UTF-8', credential_decoder=IDENTITY, driver_args={}, adapter_args={}, do_connect=True, after_connection=None): self.db = db self.dbengine = "firebird" self.uri = uri if do_connect: self.find_driver(adapter_args,uri) self.pool_size = pool_size self.folder = folder self.db_codec = db_codec self._after_connection = after_connection self.find_or_make_work_folder() ruri = uri.split('://',1)[1] m = self.REGEX_URI.match(ruri) if not m: raise SyntaxError( "Invalid URI string in DAL: %s" % self.uri) user = credential_decoder(m.group('user')) if not user: raise SyntaxError('User required') password = credential_decoder(m.group('password')) if not password: password = '' pathdb = m.group('path') if not pathdb: raise SyntaxError('Path required') charset = m.group('charset') if not charset: charset = 'UTF8' host = '' driver_args.update(host=host, database=pathdb, user=credential_decoder(user), password=credential_decoder(password), charset=charset) def connector(driver_args=driver_args): return self.driver.connect(**driver_args) self.connector = connector if do_connect: self.reconnect() class InformixAdapter(BaseAdapter): drivers = ('informixdb',) types = { 'boolean': 'CHAR(1)', 'string': 'VARCHAR(%(length)s)', 'text': 'BLOB SUB_TYPE 1', 'json': 'BLOB SUB_TYPE 1', 'password': 'VARCHAR(%(length)s)', 'blob': 'BLOB SUB_TYPE 0', 'upload': 'VARCHAR(%(length)s)', 'integer': 'INTEGER', 'bigint': 'BIGINT', 'float': 'FLOAT', 'double': 'DOUBLE PRECISION', 'decimal': 'NUMERIC(%(precision)s,%(scale)s)', 'date': 'DATE', 'time': 'CHAR(8)', 'datetime': 'DATETIME', 'id': 'SERIAL', 'reference': 'INTEGER REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', 'list:integer': 'BLOB SUB_TYPE 1', 'list:string': 'BLOB SUB_TYPE 1', 'list:reference': 'BLOB SUB_TYPE 1', 'big-id': 'BIGSERIAL', 'big-reference': 'BIGINT REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', 'reference FK': 'REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s CONSTRAINT FK_%(table_name)s_%(field_name)s', 'reference TFK': 'FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_table)s (%(foreign_key)s) ON DELETE %(on_delete_action)s CONSTRAINT TFK_%(table_name)s_%(field_name)s', } def RANDOM(self): return 'Random()' def NOT_NULL(self,default,field_type): return 'DEFAULT %s NOT NULL' % self.represent(default,field_type) def select_limitby(self, sql_s, sql_f, sql_t, sql_w, sql_o, limitby): if limitby: (lmin, lmax) = limitby fetch_amt = lmax - lmin dbms_version = int(self.connection.dbms_version.split('.')[0]) if lmin and (dbms_version >= 10): # Requires Informix 10.0+ sql_s += ' SKIP %d' % (lmin, ) if fetch_amt and (dbms_version >= 9): # Requires Informix 9.0+ sql_s += ' FIRST %d' % (fetch_amt, ) return 'SELECT %s %s FROM %s%s%s;' % (sql_s, sql_f, sql_t, sql_w, sql_o) def represent_exceptions(self, obj, fieldtype): if fieldtype == 'date': if isinstance(obj, (datetime.date, datetime.datetime)): obj = obj.isoformat()[:10] else: obj = str(obj) return "to_date('%s','%%Y-%%m-%%d')" % obj elif fieldtype == 'datetime': if isinstance(obj, datetime.datetime): obj = obj.isoformat()[:19].replace('T',' ') elif isinstance(obj, datetime.date): obj = obj.isoformat()[:10]+' 00:00:00' else: obj = str(obj) return "to_date('%s','%%Y-%%m-%%d %%H:%%M:%%S')" % obj return None REGEX_URI = re.compile('^(?P<user>[^:@]+)(\:(?P<password>[^@]*))?@(?P<host>[^\:/]+)(\:(?P<port>[0-9]+))?/(?P<db>.+)$') def __init__(self,db,uri,pool_size=0,folder=None,db_codec ='UTF-8', credential_decoder=IDENTITY, driver_args={}, adapter_args={}, do_connect=True, after_connection=None): self.db = db self.dbengine = "informix" self.uri = uri if do_connect: self.find_driver(adapter_args,uri) self.pool_size = pool_size self.folder = folder self.db_codec = db_codec self._after_connection = after_connection self.find_or_make_work_folder() ruri = uri.split('://',1)[1] m = self.REGEX_URI.match(ruri) if not m: raise SyntaxError( "Invalid URI string in DAL: %s" % self.uri) user = credential_decoder(m.group('user')) if not user: raise SyntaxError('User required') password = credential_decoder(m.group('password')) if not password: password = '' host = m.group('host') if not host: raise SyntaxError('Host name required') db = m.group('db') if not db: raise SyntaxError('Database name required') user = credential_decoder(user) password = credential_decoder(password) dsn = '%s@%s' % (db,host) driver_args.update(user=user,password=password,autocommit=True) def connector(dsn=dsn,driver_args=driver_args): return self.driver.connect(dsn,**driver_args) self.connector = connector if do_connect: self.reconnect() def execute(self,command): if command[-1:]==';': command = command[:-1] return self.log_execute(command) def lastrowid(self,table): return self.cursor.sqlerrd[1] class InformixSEAdapter(InformixAdapter): """ work in progress """ def select_limitby(self, sql_s, sql_f, sql_t, sql_w, sql_o, limitby): return 'SELECT %s %s FROM %s%s%s;' % \ (sql_s, sql_f, sql_t, sql_w, sql_o) def rowslice(self,rows,minimum=0,maximum=None): if maximum is None: return rows[minimum:] return rows[minimum:maximum] class DB2Adapter(BaseAdapter): drivers = ('pyodbc',) types = { 'boolean': 'CHAR(1)', 'string': 'VARCHAR(%(length)s)', 'text': 'CLOB', 'json': 'CLOB', 'password': 'VARCHAR(%(length)s)', 'blob': 'BLOB', 'upload': 'VARCHAR(%(length)s)', 'integer': 'INT', 'bigint': 'BIGINT', 'float': 'REAL', 'double': 'DOUBLE', 'decimal': 'NUMERIC(%(precision)s,%(scale)s)', 'date': 'DATE', 'time': 'TIME', 'datetime': 'TIMESTAMP', 'id': 'INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY NOT NULL', 'reference': 'INT, FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', 'list:integer': 'CLOB', 'list:string': 'CLOB', 'list:reference': 'CLOB', 'big-id': 'BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY NOT NULL', 'big-reference': 'BIGINT, FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', 'reference FK': ', CONSTRAINT FK_%(constraint_name)s FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', 'reference TFK': ' CONSTRAINT FK_%(foreign_table)s_PK FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_table)s (%(foreign_key)s) ON DELETE %(on_delete_action)s', } def LEFT_JOIN(self): return 'LEFT OUTER JOIN' def RANDOM(self): return 'RAND()' def select_limitby(self, sql_s, sql_f, sql_t, sql_w, sql_o, limitby): if limitby: (lmin, lmax) = limitby sql_o += ' FETCH FIRST %i ROWS ONLY' % lmax return 'SELECT %s %s FROM %s%s%s;' % (sql_s, sql_f, sql_t, sql_w, sql_o) def represent_exceptions(self, obj, fieldtype): if fieldtype == 'blob': obj = base64.b64encode(str(obj)) return "BLOB('%s')" % obj elif fieldtype == 'datetime': if isinstance(obj, datetime.datetime): obj = obj.isoformat()[:19].replace('T','-').replace(':','.') elif isinstance(obj, datetime.date): obj = obj.isoformat()[:10]+'-00.00.00' return "'%s'" % obj return None def __init__(self,db,uri,pool_size=0,folder=None,db_codec ='UTF-8', credential_decoder=IDENTITY, driver_args={}, adapter_args={}, do_connect=True, after_connection=None): self.db = db self.dbengine = "db2" self.uri = uri if do_connect: self.find_driver(adapter_args,uri) self.pool_size = pool_size self.folder = folder self.db_codec = db_codec self._after_connection = after_connection self.find_or_make_work_folder() ruri = uri.split('://', 1)[1] def connector(cnxn=ruri,driver_args=driver_args): return self.driver.connect(cnxn,**driver_args) self.connector = connector if do_connect: self.reconnect() def execute(self,command): if command[-1:]==';': command = command[:-1] return self.log_execute(command) def lastrowid(self,table): self.execute('SELECT DISTINCT IDENTITY_VAL_LOCAL() FROM %s;' % table) return long(self.cursor.fetchone()[0]) def rowslice(self,rows,minimum=0,maximum=None): if maximum is None: return rows[minimum:] return rows[minimum:maximum] class TeradataAdapter(BaseAdapter): drivers = ('pyodbc',) types = { 'boolean': 'CHAR(1)', 'string': 'VARCHAR(%(length)s)', 'text': 'CLOB', 'json': 'CLOB', 'password': 'VARCHAR(%(length)s)', 'blob': 'BLOB', 'upload': 'VARCHAR(%(length)s)', 'integer': 'INT', 'bigint': 'BIGINT', 'float': 'REAL', 'double': 'DOUBLE', 'decimal': 'NUMERIC(%(precision)s,%(scale)s)', 'date': 'DATE', 'time': 'TIME', 'datetime': 'TIMESTAMP', # Modified Constraint syntax for Teradata. # Teradata does not support ON DELETE. 'id': 'INT GENERATED ALWAYS AS IDENTITY', # Teradata Specific 'reference': 'INT', 'list:integer': 'CLOB', 'list:string': 'CLOB', 'list:reference': 'CLOB', 'big-id': 'BIGINT GENERATED ALWAYS AS IDENTITY', # Teradata Specific 'big-reference': 'BIGINT', 'reference FK': ' REFERENCES %(foreign_key)s', 'reference TFK': ' FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_table)s (%(foreign_key)s)', } def __init__(self,db,uri,pool_size=0,folder=None,db_codec ='UTF-8', credential_decoder=IDENTITY, driver_args={}, adapter_args={}, do_connect=True, after_connection=None): self.db = db self.dbengine = "teradata" self.uri = uri if do_connect: self.find_driver(adapter_args,uri) self.pool_size = pool_size self.folder = folder self.db_codec = db_codec self._after_connection = after_connection self.find_or_make_work_folder() ruri = uri.split('://', 1)[1] def connector(cnxn=ruri,driver_args=driver_args): return self.driver.connect(cnxn,**driver_args) self.connector = connector if do_connect: self.reconnect() def LEFT_JOIN(self): return 'LEFT OUTER JOIN' # Similar to MSSQL, Teradata can't specify a range (for Pageby) def select_limitby(self, sql_s, sql_f, sql_t, sql_w, sql_o, limitby): if limitby: (lmin, lmax) = limitby sql_s += ' TOP %i' % lmax return 'SELECT %s %s FROM %s%s%s;' % (sql_s, sql_f, sql_t, sql_w, sql_o) def _truncate(self, table, mode=''): tablename = table._tablename return ['DELETE FROM %s ALL;' % (tablename)] INGRES_SEQNAME='ii***lineitemsequence' # NOTE invalid database object name # (ANSI-SQL wants this form of name # to be a delimited identifier) class IngresAdapter(BaseAdapter): drivers = ('pyodbc',) types = { 'boolean': 'CHAR(1)', 'string': 'VARCHAR(%(length)s)', 'text': 'CLOB', 'json': 'CLOB', 'password': 'VARCHAR(%(length)s)', ## Not sure what this contains utf8 or nvarchar. Or even bytes? 'blob': 'BLOB', 'upload': 'VARCHAR(%(length)s)', ## FIXME utf8 or nvarchar... or blob? what is this type? 'integer': 'INTEGER4', # or int8... 'bigint': 'BIGINT', 'float': 'FLOAT', 'double': 'FLOAT8', 'decimal': 'NUMERIC(%(precision)s,%(scale)s)', 'date': 'ANSIDATE', 'time': 'TIME WITHOUT TIME ZONE', 'datetime': 'TIMESTAMP WITHOUT TIME ZONE', 'id': 'int not null unique with default next value for %s' % INGRES_SEQNAME, 'reference': 'INT, FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', 'list:integer': 'CLOB', 'list:string': 'CLOB', 'list:reference': 'CLOB', 'big-id': 'bigint not null unique with default next value for %s' % INGRES_SEQNAME, 'big-reference': 'BIGINT, FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', 'reference FK': ', CONSTRAINT FK_%(constraint_name)s FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', 'reference TFK': ' CONSTRAINT FK_%(foreign_table)s_PK FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_table)s (%(foreign_key)s) ON DELETE %(on_delete_action)s', ## FIXME TODO } def LEFT_JOIN(self): return 'LEFT OUTER JOIN' def RANDOM(self): return 'RANDOM()' def select_limitby(self, sql_s, sql_f, sql_t, sql_w, sql_o, limitby): if limitby: (lmin, lmax) = limitby fetch_amt = lmax - lmin if fetch_amt: sql_s += ' FIRST %d ' % (fetch_amt, ) if lmin: # Requires Ingres 9.2+ sql_o += ' OFFSET %d' % (lmin, ) return 'SELECT %s %s FROM %s%s%s;' % (sql_s, sql_f, sql_t, sql_w, sql_o) def __init__(self,db,uri,pool_size=0,folder=None,db_codec ='UTF-8', credential_decoder=IDENTITY, driver_args={}, adapter_args={}, do_connect=True, after_connection=None): self.db = db self.dbengine = "ingres" self._driver = pyodbc self.uri = uri if do_connect: self.find_driver(adapter_args,uri) self.pool_size = pool_size self.folder = folder self.db_codec = db_codec self._after_connection = after_connection self.find_or_make_work_folder() connstr = uri.split(':', 1)[1] # Simple URI processing connstr = connstr.lstrip() while connstr.startswith('/'): connstr = connstr[1:] if '=' in connstr: # Assume we have a regular ODBC connection string and just use it ruri = connstr else: # Assume only (local) dbname is passed in with OS auth database_name = connstr default_driver_name = 'Ingres' vnode = '(local)' servertype = 'ingres' ruri = 'Driver={%s};Server=%s;Database=%s' % (default_driver_name, vnode, database_name) def connector(cnxn=ruri,driver_args=driver_args): return self.driver.connect(cnxn,**driver_args) self.connector = connector # TODO if version is >= 10, set types['id'] to Identity column, see http://community.actian.com/wiki/Using_Ingres_Identity_Columns if do_connect: self.reconnect() def create_sequence_and_triggers(self, query, table, **args): # post create table auto inc code (if needed) # modify table to btree for performance.... # Older Ingres releases could use rule/trigger like Oracle above. if hasattr(table,'_primarykey'): modify_tbl_sql = 'modify %s to btree unique on %s' % \ (table._tablename, ', '.join(["'%s'" % x for x in table.primarykey])) self.execute(modify_tbl_sql) else: tmp_seqname='%s_iisq' % table._tablename query=query.replace(INGRES_SEQNAME, tmp_seqname) self.execute('create sequence %s' % tmp_seqname) self.execute(query) self.execute('modify %s to btree unique on %s' % (table._tablename, 'id')) def lastrowid(self,table): tmp_seqname='%s_iisq' % table self.execute('select current value for %s' % tmp_seqname) return long(self.cursor.fetchone()[0]) # don't really need int type cast here... class IngresUnicodeAdapter(IngresAdapter): drivers = ('pyodbc',) types = { 'boolean': 'CHAR(1)', 'string': 'NVARCHAR(%(length)s)', 'text': 'NCLOB', 'json': 'NCLOB', 'password': 'NVARCHAR(%(length)s)', ## Not sure what this contains utf8 or nvarchar. Or even bytes? 'blob': 'BLOB', 'upload': 'VARCHAR(%(length)s)', ## FIXME utf8 or nvarchar... or blob? what is this type? 'integer': 'INTEGER4', # or int8... 'bigint': 'BIGINT', 'float': 'FLOAT', 'double': 'FLOAT8', 'decimal': 'NUMERIC(%(precision)s,%(scale)s)', 'date': 'ANSIDATE', 'time': 'TIME WITHOUT TIME ZONE', 'datetime': 'TIMESTAMP WITHOUT TIME ZONE', 'id': 'INTEGER4 not null unique with default next value for %s'% INGRES_SEQNAME, 'reference': 'INTEGER4, FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', 'list:integer': 'NCLOB', 'list:string': 'NCLOB', 'list:reference': 'NCLOB', 'big-id': 'BIGINT not null unique with default next value for %s'% INGRES_SEQNAME, 'big-reference': 'BIGINT, FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', 'reference FK': ', CONSTRAINT FK_%(constraint_name)s FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', 'reference TFK': ' CONSTRAINT FK_%(foreign_table)s_PK FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_table)s (%(foreign_key)s) ON DELETE %(on_delete_action)s', ## FIXME TODO } class SAPDBAdapter(BaseAdapter): drivers = ('sapdb',) support_distributed_transaction = False types = { 'boolean': 'CHAR(1)', 'string': 'VARCHAR(%(length)s)', 'text': 'LONG', 'json': 'LONG', 'password': 'VARCHAR(%(length)s)', 'blob': 'LONG', 'upload': 'VARCHAR(%(length)s)', 'integer': 'INT', 'bigint': 'BIGINT', 'float': 'FLOAT', 'double': 'DOUBLE PRECISION', 'decimal': 'FIXED(%(precision)s,%(scale)s)', 'date': 'DATE', 'time': 'TIME', 'datetime': 'TIMESTAMP', 'id': 'INT PRIMARY KEY', 'reference': 'INT, FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', 'list:integer': 'LONG', 'list:string': 'LONG', 'list:reference': 'LONG', 'big-id': 'BIGINT PRIMARY KEY', 'big-reference': 'BIGINT, FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', } def sequence_name(self,table): return '%s_id_Seq' % table def select_limitby(self, sql_s, sql_f, sql_t, sql_w, sql_o, limitby): if limitby: (lmin, lmax) = limitby if len(sql_w) > 1: sql_w_row = sql_w + ' AND w_row > %i' % lmin else: sql_w_row = 'WHERE w_row > %i' % lmin return '%s %s FROM (SELECT w_tmp.*, ROWNO w_row FROM (SELECT %s FROM %s%s%s) w_tmp WHERE ROWNO=%i) %s %s %s;' % (sql_s, sql_f, sql_f, sql_t, sql_w, sql_o, lmax, sql_t, sql_w_row, sql_o) return 'SELECT %s %s FROM %s%s%s;' % (sql_s, sql_f, sql_t, sql_w, sql_o) def create_sequence_and_triggers(self, query, table, **args): # following lines should only be executed if table._sequence_name does not exist self.execute('CREATE SEQUENCE %s;' % table._sequence_name) self.execute("ALTER TABLE %s ALTER COLUMN %s SET DEFAULT NEXTVAL('%s');" \ % (table._tablename, table._id.name, table._sequence_name)) self.execute(query) REGEX_URI = re.compile('^(?P<user>[^:@]+)(\:(?P<password>[^@]*))?@(?P<host>[^\:@]+)(\:(?P<port>[0-9]+))?/(?P<db>[^\?]+)(\?sslmode=(?P<sslmode>.+))?$') def __init__(self,db,uri,pool_size=0,folder=None,db_codec ='UTF-8', credential_decoder=IDENTITY, driver_args={}, adapter_args={}, do_connect=True, after_connection=None): self.db = db self.dbengine = "sapdb" self.uri = uri if do_connect: self.find_driver(adapter_args,uri) self.pool_size = pool_size self.folder = folder self.db_codec = db_codec self._after_connection = after_connection self.find_or_make_work_folder() ruri = uri.split('://',1)[1] m = self.REGEX_URI.match(ruri) if not m: raise SyntaxError("Invalid URI string in DAL") user = credential_decoder(m.group('user')) if not user: raise SyntaxError('User required') password = credential_decoder(m.group('password')) if not password: password = '' host = m.group('host') if not host: raise SyntaxError('Host name required') db = m.group('db') if not db: raise SyntaxError('Database name required') def connector(user=user, password=password, database=db, host=host, driver_args=driver_args): return self.driver.Connection(user, password, database, host, **driver_args) self.connector = connector if do_connect: self.reconnect() def lastrowid(self,table): self.execute("select %s.NEXTVAL from dual" % table._sequence_name) return long(self.cursor.fetchone()[0]) class CubridAdapter(MySQLAdapter): drivers = ('cubriddb',) REGEX_URI = re.compile('^(?P<user>[^:@]+)(\:(?P<password>[^@]*))?@(?P<host>[^\:/]+)(\:(?P<port>[0-9]+))?/(?P<db>[^?]+)(\?set_encoding=(?P<charset>\w+))?$') def __init__(self, db, uri, pool_size=0, folder=None, db_codec='UTF-8', credential_decoder=IDENTITY, driver_args={}, adapter_args={}, do_connect=True, after_connection=None): self.db = db self.dbengine = "cubrid" self.uri = uri if do_connect: self.find_driver(adapter_args,uri) self.pool_size = pool_size self.folder = folder self.db_codec = db_codec self._after_connection = after_connection self.find_or_make_work_folder() ruri = uri.split('://',1)[1] m = self.REGEX_URI.match(ruri) if not m: raise SyntaxError( "Invalid URI string in DAL: %s" % self.uri) user = credential_decoder(m.group('user')) if not user: raise SyntaxError('User required') password = credential_decoder(m.group('password')) if not password: password = '' host = m.group('host') if not host: raise SyntaxError('Host name required') db = m.group('db') if not db: raise SyntaxError('Database name required') port = int(m.group('port') or '30000') charset = m.group('charset') or 'utf8' user = credential_decoder(user) passwd = credential_decoder(password) def connector(host=host,port=port,db=db, user=user,passwd=password,driver_args=driver_args): return self.driver.connect(host,port,db,user,passwd,**driver_args) self.connector = connector if do_connect: self.reconnect() def after_connection(self): self.execute('SET FOREIGN_KEY_CHECKS=1;') self.execute("SET sql_mode='NO_BACKSLASH_ESCAPES';") ######## GAE MySQL ########## class DatabaseStoredFile: web2py_filesystem = False def escape(self,obj): return self.db._adapter.escape(obj) def __init__(self,db,filename,mode): if not db._adapter.dbengine in ('mysql', 'postgres'): raise RuntimeError("only MySQL/Postgres can store metadata .table files in database for now") self.db = db self.filename = filename self.mode = mode if not self.web2py_filesystem: if db._adapter.dbengine == 'mysql': sql = "CREATE TABLE IF NOT EXISTS web2py_filesystem (path VARCHAR(255), content LONGTEXT, PRIMARY KEY(path) ) ENGINE=InnoDB;" elif db._adapter.dbengine == 'postgres': sql = "CREATE TABLE IF NOT EXISTS web2py_filesystem (path VARCHAR(255), content TEXT, PRIMARY KEY(path));" self.db.executesql(sql) DatabaseStoredFile.web2py_filesystem = True self.p=0 self.data = '' if mode in ('r','rw','a'): query = "SELECT content FROM web2py_filesystem WHERE path='%s'" \ % filename rows = self.db.executesql(query) if rows: self.data = rows[0][0] elif exists(filename): datafile = open(filename, 'r') try: self.data = datafile.read() finally: datafile.close() elif mode in ('r','rw'): raise RuntimeError("File %s does not exist" % filename) def read(self, bytes): data = self.data[self.p:self.p+bytes] self.p += len(data) return data def readline(self): i = self.data.find('\n',self.p)+1 if i>0: data, self.p = self.data[self.p:i], i else: data, self.p = self.data[self.p:], len(self.data) return data def write(self,data): self.data += data def close_connection(self): if self.db is not None: self.db.executesql( "DELETE FROM web2py_filesystem WHERE path='%s'" % self.filename) query = "INSERT INTO web2py_filesystem(path,content) VALUES ('%s','%s')"\ % (self.filename, self.data.replace("'","''")) self.db.executesql(query) self.db.commit() self.db = None def close(self): self.close_connection() @staticmethod def exists(db, filename): if exists(filename): return True query = "SELECT path FROM web2py_filesystem WHERE path='%s'" % filename if db.executesql(query): return True return False class UseDatabaseStoredFile: def file_exists(self, filename): return DatabaseStoredFile.exists(self.db,filename) def file_open(self, filename, mode='rb', lock=True): return DatabaseStoredFile(self.db,filename,mode) def file_close(self, fileobj): fileobj.close_connection() def file_delete(self,filename): query = "DELETE FROM web2py_filesystem WHERE path='%s'" % filename self.db.executesql(query) self.db.commit() class GoogleSQLAdapter(UseDatabaseStoredFile,MySQLAdapter): uploads_in_blob = True REGEX_URI = re.compile('^(?P<instance>.*)/(?P<db>.*)$') def __init__(self, db, uri='google:sql://realm:domain/database', pool_size=0, folder=None, db_codec='UTF-8', credential_decoder=IDENTITY, driver_args={}, adapter_args={}, do_connect=True, after_connection=None): self.db = db self.dbengine = "mysql" self.uri = uri self.pool_size = pool_size self.db_codec = db_codec self._after_connection = after_connection self.folder = folder or pjoin('$HOME',THREAD_LOCAL.folder.split( os.sep+'applications'+os.sep,1)[1]) ruri = uri.split("://")[1] m = self.REGEX_URI.match(ruri) if not m: raise SyntaxError("Invalid URI string in SQLDB: %s" % self.uri) instance = credential_decoder(m.group('instance')) self.dbstring = db = credential_decoder(m.group('db')) driver_args['instance'] = instance if not 'charset' in driver_args: driver_args['charset'] = 'utf8' self.createdb = createdb = adapter_args.get('createdb',True) if not createdb: driver_args['database'] = db def connector(driver_args=driver_args): return rdbms.connect(**driver_args) self.connector = connector if do_connect: self.reconnect() def after_connection(self): if self.createdb: # self.execute('DROP DATABASE %s' % self.dbstring) self.execute('CREATE DATABASE IF NOT EXISTS %s' % self.dbstring) self.execute('USE %s' % self.dbstring) self.execute("SET FOREIGN_KEY_CHECKS=1;") self.execute("SET sql_mode='NO_BACKSLASH_ESCAPES';") def execute(self, command, *a, **b): return self.log_execute(command.decode('utf8'), *a, **b) class NoSQLAdapter(BaseAdapter): can_select_for_update = False @staticmethod def to_unicode(obj): if isinstance(obj, str): return obj.decode('utf8') elif not isinstance(obj, unicode): return unicode(obj) return obj def id_query(self, table): return table._id > 0 def represent(self, obj, fieldtype): field_is_type = fieldtype.startswith if isinstance(obj, CALLABLETYPES): obj = obj() if isinstance(fieldtype, SQLCustomType): return fieldtype.encoder(obj) if isinstance(obj, (Expression, Field)): raise SyntaxError("non supported on GAE") if self.dbengine == 'google:datastore': if isinstance(fieldtype, gae.Property): return obj is_string = isinstance(fieldtype,str) is_list = is_string and field_is_type('list:') if is_list: if not obj: obj = [] if not isinstance(obj, (list, tuple)): obj = [obj] if obj == '' and not \ (is_string and fieldtype[:2] in ['st','te', 'pa','up']): return None if not obj is None: if isinstance(obj, list) and not is_list: obj = [self.represent(o, fieldtype) for o in obj] elif fieldtype in ('integer','bigint','id'): obj = long(obj) elif fieldtype == 'double': obj = float(obj) elif is_string and field_is_type('reference'): if isinstance(obj, (Row, Reference)): obj = obj['id'] obj = long(obj) elif fieldtype == 'boolean': if obj and not str(obj)[0].upper() in '0F': obj = True else: obj = False elif fieldtype == 'date': if not isinstance(obj, datetime.date): (y, m, d) = map(int,str(obj).strip().split('-')) obj = datetime.date(y, m, d) elif isinstance(obj,datetime.datetime): (y, m, d) = (obj.year, obj.month, obj.day) obj = datetime.date(y, m, d) elif fieldtype == 'time': if not isinstance(obj, datetime.time): time_items = map(int,str(obj).strip().split(':')[:3]) if len(time_items) == 3: (h, mi, s) = time_items else: (h, mi, s) = time_items + [0] obj = datetime.time(h, mi, s) elif fieldtype == 'datetime': if not isinstance(obj, datetime.datetime): (y, m, d) = map(int,str(obj)[:10].strip().split('-')) time_items = map(int,str(obj)[11:].strip().split(':')[:3]) while len(time_items)<3: time_items.append(0) (h, mi, s) = time_items obj = datetime.datetime(y, m, d, h, mi, s) elif fieldtype == 'blob': pass elif fieldtype == 'json': if isinstance(obj, basestring): obj = self.to_unicode(obj) if have_serializers: obj = serializers.loads_json(obj) elif simplejson: obj = simplejson.loads(obj) else: raise RuntimeError("missing simplejson") elif is_string and field_is_type('list:string'): return map(self.to_unicode,obj) elif is_list: return map(int,obj) else: obj = self.to_unicode(obj) return obj def _insert(self,table,fields): return 'insert %s in %s' % (fields, table) def _count(self,query,distinct=None): return 'count %s' % repr(query) def _select(self,query,fields,attributes): return 'select %s where %s' % (repr(fields), repr(query)) def _delete(self,tablename, query): return 'delete %s where %s' % (repr(tablename),repr(query)) def _update(self,tablename,query,fields): return 'update %s (%s) where %s' % (repr(tablename), repr(fields),repr(query)) def commit(self): """ remember: no transactions on many NoSQL """ pass def rollback(self): """ remember: no transactions on many NoSQL """ pass def close_connection(self): """ remember: no transactions on many NoSQL """ pass # these functions should never be called! def OR(self,first,second): raise SyntaxError("Not supported") def AND(self,first,second): raise SyntaxError("Not supported") def AS(self,first,second): raise SyntaxError("Not supported") def ON(self,first,second): raise SyntaxError("Not supported") def STARTSWITH(self,first,second=None): raise SyntaxError("Not supported") def ENDSWITH(self,first,second=None): raise SyntaxError("Not supported") def ADD(self,first,second): raise SyntaxError("Not supported") def SUB(self,first,second): raise SyntaxError("Not supported") def MUL(self,first,second): raise SyntaxError("Not supported") def DIV(self,first,second): raise SyntaxError("Not supported") def LOWER(self,first): raise SyntaxError("Not supported") def UPPER(self,first): raise SyntaxError("Not supported") def EXTRACT(self,first,what): raise SyntaxError("Not supported") def LENGTH(self, first): raise SyntaxError("Not supported") def AGGREGATE(self,first,what): raise SyntaxError("Not supported") def LEFT_JOIN(self): raise SyntaxError("Not supported") def RANDOM(self): raise SyntaxError("Not supported") def SUBSTRING(self,field,parameters): raise SyntaxError("Not supported") def PRIMARY_KEY(self,key): raise SyntaxError("Not supported") def ILIKE(self,first,second): raise SyntaxError("Not supported") def drop(self,table,mode): raise SyntaxError("Not supported") def alias(self,table,alias): raise SyntaxError("Not supported") def migrate_table(self,*a,**b): raise SyntaxError("Not supported") def distributed_transaction_begin(self,key): raise SyntaxError("Not supported") def prepare(self,key): raise SyntaxError("Not supported") def commit_prepared(self,key): raise SyntaxError("Not supported") def rollback_prepared(self,key): raise SyntaxError("Not supported") def concat_add(self,table): raise SyntaxError("Not supported") def constraint_name(self, table, fieldname): raise SyntaxError("Not supported") def create_sequence_and_triggers(self, query, table, **args): pass def log_execute(self,*a,**b): raise SyntaxError("Not supported") def execute(self,*a,**b): raise SyntaxError("Not supported") def represent_exceptions(self, obj, fieldtype): raise SyntaxError("Not supported") def lastrowid(self,table): raise SyntaxError("Not supported") def rowslice(self,rows,minimum=0,maximum=None): raise SyntaxError("Not supported") class GAEF(object): def __init__(self,name,op,value,apply): self.name=name=='id' and '__key__' or name self.op=op self.value=value self.apply=apply def __repr__(self): return '(%s %s %s:%s)' % (self.name, self.op, repr(self.value), type(self.value)) class GoogleDatastoreAdapter(NoSQLAdapter): uploads_in_blob = True types = {} def file_exists(self, filename): pass def file_open(self, filename, mode='rb', lock=True): pass def file_close(self, fileobj): pass REGEX_NAMESPACE = re.compile('.*://(?P<namespace>.+)') def __init__(self,db,uri,pool_size=0,folder=None,db_codec ='UTF-8', credential_decoder=IDENTITY, driver_args={}, adapter_args={}, do_connect=True, after_connection=None): self.types.update({ 'boolean': gae.BooleanProperty, 'string': (lambda **kwargs: gae.StringProperty(multiline=True, **kwargs)), 'text': gae.TextProperty, 'json': gae.TextProperty, 'password': gae.StringProperty, 'blob': gae.BlobProperty, 'upload': gae.StringProperty, 'integer': gae.IntegerProperty, 'bigint': gae.IntegerProperty, 'float': gae.FloatProperty, 'double': gae.FloatProperty, 'decimal': GAEDecimalProperty, 'date': gae.DateProperty, 'time': gae.TimeProperty, 'datetime': gae.DateTimeProperty, 'id': None, 'reference': gae.IntegerProperty, 'list:string': (lambda **kwargs: gae.StringListProperty(default=None, **kwargs)), 'list:integer': (lambda **kwargs: gae.ListProperty(int,default=None, **kwargs)), 'list:reference': (lambda **kwargs: gae.ListProperty(int,default=None, **kwargs)), }) self.db = db self.uri = uri self.dbengine = 'google:datastore' self.folder = folder db['_lastsql'] = '' self.db_codec = 'UTF-8' self._after_connection = after_connection self.pool_size = 0 match = self.REGEX_NAMESPACE.match(uri) if match: namespace_manager.set_namespace(match.group('namespace')) def parse_id(self, value, field_type): return value def create_table(self,table,migrate=True,fake_migrate=False, polymodel=None): myfields = {} for field in table: if isinstance(polymodel,Table) and field.name in polymodel.fields(): continue attr = {} if isinstance(field.custom_qualifier, dict): #this is custom properties to add to the GAE field declartion attr = field.custom_qualifier field_type = field.type if isinstance(field_type, SQLCustomType): ftype = self.types[field_type.native or field_type.type](**attr) elif isinstance(field_type, gae.Property): ftype = field_type elif field_type.startswith('id'): continue elif field_type.startswith('decimal'): precision, scale = field_type[7:].strip('()').split(',') precision = int(precision) scale = int(scale) ftype = GAEDecimalProperty(precision, scale, **attr) elif field_type.startswith('reference'): if field.notnull: attr = dict(required=True) referenced = field_type[10:].strip() ftype = self.types[field_type[:9]](referenced, **attr) elif field_type.startswith('list:reference'): if field.notnull: attr['required'] = True referenced = field_type[15:].strip() ftype = self.types[field_type[:14]](**attr) elif field_type.startswith('list:'): ftype = self.types[field_type](**attr) elif not field_type in self.types\ or not self.types[field_type]: raise SyntaxError('Field: unknown field type: %s' % field_type) else: ftype = self.types[field_type](**attr) myfields[field.name] = ftype if not polymodel: table._tableobj = classobj(table._tablename, (gae.Model, ), myfields) elif polymodel==True: table._tableobj = classobj(table._tablename, (PolyModel, ), myfields) elif isinstance(polymodel,Table): table._tableobj = classobj(table._tablename, (polymodel._tableobj, ), myfields) else: raise SyntaxError("polymodel must be None, True, a table or a tablename") return None def expand(self,expression,field_type=None): if isinstance(expression,Field): if expression.type in ('text', 'blob', 'json'): raise SyntaxError('AppEngine does not index by: %s' % expression.type) return expression.name elif isinstance(expression, (Expression, Query)): if not expression.second is None: return expression.op(expression.first, expression.second) elif not expression.first is None: return expression.op(expression.first) else: return expression.op() elif field_type: return self.represent(expression,field_type) elif isinstance(expression,(list,tuple)): return ','.join([self.represent(item,field_type) for item in expression]) else: return str(expression) ### TODO from gql.py Expression def AND(self,first,second): a = self.expand(first) b = self.expand(second) if b[0].name=='__key__' and a[0].name!='__key__': return b+a return a+b def EQ(self,first,second=None): if isinstance(second, Key): return [GAEF(first.name,'=',second,lambda a,b:a==b)] return [GAEF(first.name,'=',self.represent(second,first.type),lambda a,b:a==b)] def NE(self,first,second=None): if first.type != 'id': return [GAEF(first.name,'!=',self.represent(second,first.type),lambda a,b:a!=b)] else: if not second is None: second = Key.from_path(first._tablename, long(second)) return [GAEF(first.name,'!=',second,lambda a,b:a!=b)] def LT(self,first,second=None): if first.type != 'id': return [GAEF(first.name,'<',self.represent(second,first.type),lambda a,b:a<b)] else: second = Key.from_path(first._tablename, long(second)) return [GAEF(first.name,'<',second,lambda a,b:a<b)] def LE(self,first,second=None): if first.type != 'id': return [GAEF(first.name,'<=',self.represent(second,first.type),lambda a,b:a<=b)] else: second = Key.from_path(first._tablename, long(second)) return [GAEF(first.name,'<=',second,lambda a,b:a<=b)] def GT(self,first,second=None): if first.type != 'id' or second==0 or second == '0': return [GAEF(first.name,'>',self.represent(second,first.type),lambda a,b:a>b)] else: second = Key.from_path(first._tablename, long(second)) return [GAEF(first.name,'>',second,lambda a,b:a>b)] def GE(self,first,second=None): if first.type != 'id': return [GAEF(first.name,'>=',self.represent(second,first.type),lambda a,b:a>=b)] else: second = Key.from_path(first._tablename, long(second)) return [GAEF(first.name,'>=',second,lambda a,b:a>=b)] def INVERT(self,first): return '-%s' % first.name def COMMA(self,first,second): return '%s, %s' % (self.expand(first),self.expand(second)) def BELONGS(self,first,second=None): if not isinstance(second,(list, tuple)): raise SyntaxError("Not supported") if first.type != 'id': return [GAEF(first.name,'in',self.represent(second,first.type),lambda a,b:a in b)] else: second = [Key.from_path(first._tablename, int(i)) for i in second] return [GAEF(first.name,'in',second,lambda a,b:a in b)] def CONTAINS(self,first,second,case_sensitive=False): # silently ignoring: GAE can only do case sensitive matches! if not first.type.startswith('list:'): raise SyntaxError("Not supported") return [GAEF(first.name,'=',self.expand(second,first.type[5:]),lambda a,b:b in a)] def NOT(self,first): nops = { self.EQ: self.NE, self.NE: self.EQ, self.LT: self.GE, self.GT: self.LE, self.LE: self.GT, self.GE: self.LT} if not isinstance(first,Query): raise SyntaxError("Not suported") nop = nops.get(first.op,None) if not nop: raise SyntaxError("Not suported %s" % first.op.__name__) first.op = nop return self.expand(first) def truncate(self,table,mode): self.db(self.db._adapter.id_query(table)).delete() def select_raw(self,query,fields=None,attributes=None): db = self.db fields = fields or [] attributes = attributes or {} args_get = attributes.get new_fields = [] for item in fields: if isinstance(item,SQLALL): new_fields += item._table else: new_fields.append(item) fields = new_fields if query: tablename = self.get_table(query) elif fields: tablename = fields[0].tablename query = db._adapter.id_query(fields[0].table) else: raise SyntaxError("Unable to determine a tablename") if query: if use_common_filters(query): query = self.common_filter(query,[tablename]) #tableobj is a GAE Model class (or subclass) tableobj = db[tablename]._tableobj filters = self.expand(query) projection = None if len(db[tablename].fields) == len(fields): #getting all fields, not a projection query projection = None elif args_get('projection') == True: projection = [] for f in fields: if f.type in ['text', 'blob', 'json']: raise SyntaxError( "text and blob field types not allowed in projection queries") else: projection.append(f.name) elif args_get('filterfields') == True: projection = [] for f in fields: projection.append(f.name) # real projection's can't include 'id'. # it will be added to the result later query_projection = [ p for p in projection if \ p != db[tablename]._id.name] if projection and \ args_get('projection') == True\ else None cursor = None if isinstance(args_get('reusecursor'), str): cursor = args_get('reusecursor') items = gae.Query(tableobj, projection=query_projection, cursor=cursor) for filter in filters: if args_get('projection') == True and \ filter.name in query_projection and \ filter.op in ['=', '<=', '>=']: raise SyntaxError( "projection fields cannot have equality filters") if filter.name=='__key__' and filter.op=='>' and filter.value==0: continue elif filter.name=='__key__' and filter.op=='=': if filter.value==0: items = [] elif isinstance(filter.value, Key): # key qeuries return a class instance, # can't use projection # extra values will be ignored in post-processing later item = tableobj.get(filter.value) items = (item and [item]) or [] else: # key qeuries return a class instance, # can't use projection # extra values will be ignored in post-processing later item = tableobj.get_by_id(filter.value) items = (item and [item]) or [] elif isinstance(items,list): # i.e. there is a single record! items = [i for i in items if filter.apply( getattr(item,filter.name),filter.value)] else: if filter.name=='__key__' and filter.op != 'in': items.order('__key__') items = items.filter('%s %s' % (filter.name,filter.op), filter.value) if not isinstance(items,list): if args_get('left', None): raise SyntaxError('Set: no left join in appengine') if args_get('groupby', None): raise SyntaxError('Set: no groupby in appengine') orderby = args_get('orderby', False) if orderby: ### THIS REALLY NEEDS IMPROVEMENT !!! if isinstance(orderby, (list, tuple)): orderby = xorify(orderby) if isinstance(orderby,Expression): orderby = self.expand(orderby) orders = orderby.split(', ') for order in orders: order={'-id':'-__key__','id':'__key__'}.get(order,order) items = items.order(order) if args_get('limitby', None): (lmin, lmax) = attributes['limitby'] (limit, offset) = (lmax - lmin, lmin) rows = items.fetch(limit,offset=offset) #cursor is only useful if there was a limit and we didn't return # all results if args_get('reusecursor'): db['_lastcursor'] = items.cursor() items = rows return (items, tablename, projection or db[tablename].fields) def select(self,query,fields,attributes): """ This is the GAE version of select. some notes to consider: - db['_lastsql'] is not set because there is not SQL statement string for a GAE query - 'nativeRef' is a magical fieldname used for self references on GAE - optional attribute 'projection' when set to True will trigger use of the GAE projection queries. note that there are rules for what is accepted imposed by GAE: each field must be indexed, projection queries cannot contain blob or text fields, and you cannot use == and also select that same field. see https://developers.google.com/appengine/docs/python/datastore/queries#Query_Projection - optional attribute 'filterfields' when set to True web2py will only parse the explicitly listed fields into the Rows object, even though all fields are returned in the query. This can be used to reduce memory usage in cases where true projection queries are not usable. - optional attribute 'reusecursor' allows use of cursor with queries that have the limitby attribute. Set the attribute to True for the first query, set it to the value of db['_lastcursor'] to continue a previous query. The user must save the cursor value between requests, and the filters must be identical. It is up to the user to follow google's limitations: https://developers.google.com/appengine/docs/python/datastore/queries#Query_Cursors """ (items, tablename, fields) = self.select_raw(query,fields,attributes) # self.db['_lastsql'] = self._select(query,fields,attributes) rows = [[(t==self.db[tablename]._id.name and item) or \ (t=='nativeRef' and item) or getattr(item, t) \ for t in fields] for item in items] colnames = ['%s.%s' % (tablename, t) for t in fields] processor = attributes.get('processor',self.parse) return processor(rows,fields,colnames,False) def count(self,query,distinct=None,limit=None): if distinct: raise RuntimeError("COUNT DISTINCT not supported") (items, tablename, fields) = self.select_raw(query) # self.db['_lastsql'] = self._count(query) try: return len(items) except TypeError: return items.count(limit=limit) def delete(self,tablename, query): """ This function was changed on 2010-05-04 because according to http://code.google.com/p/googleappengine/issues/detail?id=3119 GAE no longer supports deleting more than 1000 records. """ # self.db['_lastsql'] = self._delete(tablename,query) (items, tablename, fields) = self.select_raw(query) # items can be one item or a query if not isinstance(items,list): #use a keys_only query to ensure that this runs as a datastore # small operations leftitems = items.fetch(1000, keys_only=True) counter = 0 while len(leftitems): counter += len(leftitems) gae.delete(leftitems) leftitems = items.fetch(1000, keys_only=True) else: counter = len(items) gae.delete(items) return counter def update(self,tablename,query,update_fields): # self.db['_lastsql'] = self._update(tablename,query,update_fields) (items, tablename, fields) = self.select_raw(query) counter = 0 for item in items: for field, value in update_fields: setattr(item, field.name, self.represent(value,field.type)) item.put() counter += 1 LOGGER.info(str(counter)) return counter def insert(self,table,fields): dfields=dict((f.name,self.represent(v,f.type)) for f,v in fields) # table._db['_lastsql'] = self._insert(table,fields) tmp = table._tableobj(**dfields) tmp.put() rid = Reference(tmp.key().id()) (rid._table, rid._record, rid._gaekey) = (table, None, tmp.key()) return rid def bulk_insert(self,table,items): parsed_items = [] for item in items: dfields=dict((f.name,self.represent(v,f.type)) for f,v in item) parsed_items.append(table._tableobj(**dfields)) gae.put(parsed_items) return True def uuid2int(uuidv): return uuid.UUID(uuidv).int def int2uuid(n): return str(uuid.UUID(int=n)) class CouchDBAdapter(NoSQLAdapter): drivers = ('couchdb',) uploads_in_blob = True types = { 'boolean': bool, 'string': str, 'text': str, 'json': str, 'password': str, 'blob': str, 'upload': str, 'integer': long, 'bigint': long, 'float': float, 'double': float, 'date': datetime.date, 'time': datetime.time, 'datetime': datetime.datetime, 'id': long, 'reference': long, 'list:string': list, 'list:integer': list, 'list:reference': list, } def file_exists(self, filename): pass def file_open(self, filename, mode='rb', lock=True): pass def file_close(self, fileobj): pass def expand(self,expression,field_type=None): if isinstance(expression,Field): if expression.type=='id': return "%s._id" % expression.tablename return BaseAdapter.expand(self,expression,field_type) def AND(self,first,second): return '(%s && %s)' % (self.expand(first),self.expand(second)) def OR(self,first,second): return '(%s || %s)' % (self.expand(first),self.expand(second)) def EQ(self,first,second): if second is None: return '(%s == null)' % self.expand(first) return '(%s == %s)' % (self.expand(first),self.expand(second,first.type)) def NE(self,first,second): if second is None: return '(%s != null)' % self.expand(first) return '(%s != %s)' % (self.expand(first),self.expand(second,first.type)) def COMMA(self,first,second): return '%s + %s' % (self.expand(first),self.expand(second)) def represent(self, obj, fieldtype): value = NoSQLAdapter.represent(self, obj, fieldtype) if fieldtype=='id': return repr(str(long(value))) elif fieldtype in ('date','time','datetime','boolean'): return serializers.json(value) return repr(not isinstance(value,unicode) and value \ or value and value.encode('utf8')) def __init__(self,db,uri='couchdb://127.0.0.1:5984', pool_size=0,folder=None,db_codec ='UTF-8', credential_decoder=IDENTITY, driver_args={}, adapter_args={}, do_connect=True, after_connection=None): self.db = db self.uri = uri if do_connect: self.find_driver(adapter_args) self.dbengine = 'couchdb' self.folder = folder db['_lastsql'] = '' self.db_codec = 'UTF-8' self._after_connection = after_connection self.pool_size = pool_size url='http://'+uri[10:] def connector(url=url,driver_args=driver_args): return self.driver.Server(url,**driver_args) self.reconnect(connector,cursor=False) def create_table(self, table, migrate=True, fake_migrate=False, polymodel=None): if migrate: try: self.connection.create(table._tablename) except: pass def insert(self,table,fields): id = uuid2int(web2py_uuid()) ctable = self.connection[table._tablename] values = dict((k.name,self.represent(v,k.type)) for k,v in fields) values['_id'] = str(id) ctable.save(values) return id def _select(self,query,fields,attributes): if not isinstance(query,Query): raise SyntaxError("Not Supported") for key in set(attributes.keys())-SELECT_ARGS: raise SyntaxError('invalid select attribute: %s' % key) new_fields=[] for item in fields: if isinstance(item,SQLALL): new_fields += item._table else: new_fields.append(item) def uid(fd): return fd=='id' and '_id' or fd def get(row,fd): return fd=='id' and long(row['_id']) or row.get(fd,None) fields = new_fields tablename = self.get_table(query) fieldnames = [f.name for f in (fields or self.db[tablename])] colnames = ['%s.%s' % (tablename,k) for k in fieldnames] fields = ','.join(['%s.%s' % (tablename,uid(f)) for f in fieldnames]) fn="(function(%(t)s){if(%(query)s)emit(%(order)s,[%(fields)s]);})" %\ dict(t=tablename, query=self.expand(query), order='%s._id' % tablename, fields=fields) return fn, colnames def select(self,query,fields,attributes): if not isinstance(query,Query): raise SyntaxError("Not Supported") fn, colnames = self._select(query,fields,attributes) tablename = colnames[0].split('.')[0] ctable = self.connection[tablename] rows = [cols['value'] for cols in ctable.query(fn)] processor = attributes.get('processor',self.parse) return processor(rows,fields,colnames,False) def delete(self,tablename,query): if not isinstance(query,Query): raise SyntaxError("Not Supported") if query.first.type=='id' and query.op==self.EQ: id = query.second tablename = query.first.tablename assert(tablename == query.first.tablename) ctable = self.connection[tablename] try: del ctable[str(id)] return 1 except couchdb.http.ResourceNotFound: return 0 else: tablename = self.get_table(query) rows = self.select(query,[self.db[tablename]._id],{}) ctable = self.connection[tablename] for row in rows: del ctable[str(row.id)] return len(rows) def update(self,tablename,query,fields): if not isinstance(query,Query): raise SyntaxError("Not Supported") if query.first.type=='id' and query.op==self.EQ: id = query.second tablename = query.first.tablename ctable = self.connection[tablename] try: doc = ctable[str(id)] for key,value in fields: doc[key.name] = self.represent(value,self.db[tablename][key.name].type) ctable.save(doc) return 1 except couchdb.http.ResourceNotFound: return 0 else: tablename = self.get_table(query) rows = self.select(query,[self.db[tablename]._id],{}) ctable = self.connection[tablename] table = self.db[tablename] for row in rows: doc = ctable[str(row.id)] for key,value in fields: doc[key.name] = self.represent(value,table[key.name].type) ctable.save(doc) return len(rows) def count(self,query,distinct=None): if distinct: raise RuntimeError("COUNT DISTINCT not supported") if not isinstance(query,Query): raise SyntaxError("Not Supported") tablename = self.get_table(query) rows = self.select(query,[self.db[tablename]._id],{}) return len(rows) def cleanup(text): """ validates that the given text is clean: only contains [0-9a-zA-Z_] """ if not REGEX_ALPHANUMERIC.match(text): raise SyntaxError('invalid table or field name: %s' % text) return text class MongoDBAdapter(NoSQLAdapter): native_json = True drivers = ('pymongo',) uploads_in_blob = True types = { 'boolean': bool, 'string': str, 'text': str, 'json': str, 'password': str, 'blob': str, 'upload': str, 'integer': long, 'bigint': long, 'float': float, 'double': float, 'date': datetime.date, 'time': datetime.time, 'datetime': datetime.datetime, 'id': long, 'reference': long, 'list:string': list, 'list:integer': list, 'list:reference': list, } error_messages = {"javascript_needed": "This must yet be replaced" + " with javascript in order to work."} def __init__(self,db,uri='mongodb://127.0.0.1:5984/db', pool_size=0, folder=None, db_codec ='UTF-8', credential_decoder=IDENTITY, driver_args={}, adapter_args={}, do_connect=True, after_connection=None): self.db = db self.uri = uri if do_connect: self.find_driver(adapter_args) import random from bson.objectid import ObjectId from bson.son import SON import pymongo.uri_parser m = pymongo.uri_parser.parse_uri(uri) self.SON = SON self.ObjectId = ObjectId self.random = random self.dbengine = 'mongodb' self.folder = folder db['_lastsql'] = '' self.db_codec = 'UTF-8' self._after_connection = after_connection self.pool_size = pool_size #this is the minimum amount of replicates that it should wait # for on insert/update self.minimumreplication = adapter_args.get('minimumreplication',0) # by default all inserts and selects are performand asynchronous, # but now the default is # synchronous, except when overruled by either this default or # function parameter self.safe = adapter_args.get('safe',True) if isinstance(m,tuple): m = {"database" : m[1]} if m.get('database')==None: raise SyntaxError("Database is required!") def connector(uri=self.uri,m=m): # Connection() is deprecated if hasattr(self.driver, "MongoClient"): Connection = self.driver.MongoClient else: Connection = self.driver.Connection return Connection(uri)[m.get('database')] self.reconnect(connector,cursor=False) def object_id(self, arg=None): """ Convert input to a valid Mongodb ObjectId instance self.object_id("<random>") -> ObjectId (not unique) instance """ if not arg: arg = 0 if isinstance(arg, basestring): # we assume an integer as default input rawhex = len(arg.replace("0x", "").replace("L", "")) == 24 if arg.isdigit() and (not rawhex): arg = int(arg) elif arg == "<random>": arg = int("0x%sL" % \ "".join([self.random.choice("0123456789abcdef") \ for x in range(24)]), 0) elif arg.isalnum(): if not arg.startswith("0x"): arg = "0x%s" % arg try: arg = int(arg, 0) except ValueError, e: raise ValueError( "invalid objectid argument string: %s" % e) else: raise ValueError("Invalid objectid argument string. " + "Requires an integer or base 16 value") elif isinstance(arg, self.ObjectId): return arg if not isinstance(arg, (int, long)): raise TypeError("object_id argument must be of type " + "ObjectId or an objectid representable integer") if arg == 0: hexvalue = "".zfill(24) else: hexvalue = hex(arg)[2:].replace("L", "") return self.ObjectId(hexvalue) def parse_reference(self, value, field_type): # here we have to check for ObjectID before base parse if isinstance(value, self.ObjectId): value = long(str(value), 16) return super(MongoDBAdapter, self).parse_reference(value, field_type) def parse_id(self, value, field_type): if isinstance(value, self.ObjectId): value = long(str(value), 16) return super(MongoDBAdapter, self).parse_id(value, field_type) def represent(self, obj, fieldtype): # the base adatpter does not support MongoDB ObjectId if isinstance(obj, self.ObjectId): value = obj else: value = NoSQLAdapter.represent(self, obj, fieldtype) # reference types must be convert to ObjectID if fieldtype =='date': if value == None: return value # this piece of data can be stripped off based on the fieldtype t = datetime.time(0, 0, 0) # mongodb doesn't has a date object and so it must datetime, # string or integer return datetime.datetime.combine(value, t) elif fieldtype == 'time': if value == None: return value # this piece of data can be stripped of based on the fieldtype d = datetime.date(2000, 1, 1) # mongodb doesn't has a time object and so it must datetime, # string or integer return datetime.datetime.combine(d, value) elif (isinstance(fieldtype, basestring) and fieldtype.startswith('list:')): if fieldtype.startswith('list:reference'): newval = [] for v in value: newval.append(self.object_id(v)) return newval return value elif ((isinstance(fieldtype, basestring) and fieldtype.startswith("reference")) or (isinstance(fieldtype, Table)) or fieldtype=="id"): value = self.object_id(value) return value def create_table(self, table, migrate=True, fake_migrate=False, polymodel=None, isCapped=False): if isCapped: raise RuntimeError("Not implemented") def count(self, query, distinct=None, snapshot=True): if distinct: raise RuntimeError("COUNT DISTINCT not supported") if not isinstance(query,Query): raise SyntaxError("Not Supported") tablename = self.get_table(query) return long(self.select(query,[self.db[tablename]._id], {}, count=True,snapshot=snapshot)['count']) # Maybe it would be faster if we just implemented the pymongo # .count() function which is probably quicker? # therefor call __select() connection[table].find(query).count() # Since this will probably reduce the return set? def expand(self, expression, field_type=None): if isinstance(expression, Query): # any query using 'id':= # set name as _id (as per pymongo/mongodb primary key) # convert second arg to an objectid field # (if its not already) # if second arg is 0 convert to objectid if isinstance(expression.first,Field) and \ ((expression.first.type == 'id') or \ ("reference" in expression.first.type)): if expression.first.type == 'id': expression.first.name = '_id' # cast to Mongo ObjectId if isinstance(expression.second, (tuple, list, set)): expression.second = [self.object_id(item) for item in expression.second] else: expression.second = self.object_id(expression.second) result = expression.op(expression.first, expression.second) if isinstance(expression, Field): if expression.type=='id': result = "_id" else: result = expression.name elif isinstance(expression, (Expression, Query)): if not expression.second is None: result = expression.op(expression.first, expression.second) elif not expression.first is None: result = expression.op(expression.first) elif not isinstance(expression.op, str): result = expression.op() else: result = expression.op elif field_type: result = self.represent(expression,field_type) elif isinstance(expression,(list,tuple)): result = ','.join(self.represent(item,field_type) for item in expression) else: result = expression return result def drop(self, table, mode=''): ctable = self.connection[table._tablename] ctable.drop() def truncate(self, table, mode, safe=None): if safe == None: safe=self.safe ctable = self.connection[table._tablename] ctable.remove(None, safe=True) def _select(self, query, fields, attributes): if 'for_update' in attributes: logging.warn('mongodb does not support for_update') for key in set(attributes.keys())-set(('limitby', 'orderby','for_update')): if attributes[key]!=None: logging.warn('select attribute not implemented: %s' % key) new_fields=[] mongosort_list = [] # try an orderby attribute orderby = attributes.get('orderby', False) limitby = attributes.get('limitby', False) # distinct = attributes.get('distinct', False) if orderby: if isinstance(orderby, (list, tuple)): orderby = xorify(orderby) # !!!! need to add 'random' for f in self.expand(orderby).split(','): if f.startswith('-'): mongosort_list.append((f[1:], -1)) else: mongosort_list.append((f, 1)) if limitby: limitby_skip, limitby_limit = limitby else: limitby_skip = limitby_limit = 0 mongofields_dict = self.SON() mongoqry_dict = {} for item in fields: if isinstance(item, SQLALL): new_fields += item._table else: new_fields.append(item) fields = new_fields if isinstance(query,Query): tablename = self.get_table(query) elif len(fields) != 0: tablename = fields[0].tablename else: raise SyntaxError("The table name could not be found in " + "the query nor from the select statement.") mongoqry_dict = self.expand(query) fields = fields or self.db[tablename] for field in fields: mongofields_dict[field.name] = 1 return tablename, mongoqry_dict, mongofields_dict, mongosort_list, \ limitby_limit, limitby_skip def select(self, query, fields, attributes, count=False, snapshot=False): # TODO: support joins tablename, mongoqry_dict, mongofields_dict, mongosort_list, \ limitby_limit, limitby_skip = self._select(query, fields, attributes) ctable = self.connection[tablename] if count: return {'count' : ctable.find( mongoqry_dict, mongofields_dict, skip=limitby_skip, limit=limitby_limit, sort=mongosort_list, snapshot=snapshot).count()} else: # pymongo cursor object mongo_list_dicts = ctable.find(mongoqry_dict, mongofields_dict, skip=limitby_skip, limit=limitby_limit, sort=mongosort_list, snapshot=snapshot) rows = [] # populate row in proper order # Here we replace ._id with .id to follow the standard naming colnames = [] newnames = [] for field in fields: colname = str(field) colnames.append(colname) tablename, fieldname = colname.split(".") if fieldname == "_id": # Mongodb reserved uuid key field.name = "id" newnames.append(".".join((tablename, field.name))) for record in mongo_list_dicts: row=[] for colname in colnames: tablename, fieldname = colname.split(".") # switch to Mongo _id uuids for retrieving # record id's if fieldname == "id": fieldname = "_id" if fieldname in record: value = record[fieldname] else: value = None row.append(value) rows.append(row) processor = attributes.get('processor', self.parse) result = processor(rows, fields, newnames, False) return result def _insert(self, table, fields): values = dict() for k, v in fields: if not k.name in ["id", "safe"]: fieldname = k.name fieldtype = table[k.name].type values[fieldname] = self.represent(v, fieldtype) return values # Safe determines whether a asynchronious request is done or a # synchronious action is done # For safety, we use by default synchronous requests def insert(self, table, fields, safe=None): if safe==None: safe = self.safe ctable = self.connection[table._tablename] values = self._insert(table, fields) ctable.insert(values, safe=safe) return long(str(values['_id']), 16) #this function returns a dict with the where clause and update fields def _update(self, tablename, query, fields): if not isinstance(query, Query): raise SyntaxError("Not Supported") filter = None if query: filter = self.expand(query) modify = {'$set': dict((k.name, self.represent(v, k.type)) for k, v in fields)} return modify, filter def update(self, tablename, query, fields, safe=None): if safe == None: safe = self.safe # return amount of adjusted rows or zero, but no exceptions # @ related not finding the result if not isinstance(query, Query): raise RuntimeError("Not implemented") amount = self.count(query, False) modify, filter = self._update(tablename, query, fields) try: result = self.connection[tablename].update(filter, modify, multi=True, safe=safe) if safe: try: # if result count is available fetch it return result["n"] except (KeyError, AttributeError, TypeError): return amount else: return amount except Exception, e: # TODO Reverse update query to verifiy that the query succeded raise RuntimeError("uncaught exception when updating rows: %s" % e) def _delete(self, tablename, query): if not isinstance(query, Query): raise RuntimeError("query type %s is not supported" % \ type(query)) return self.expand(query) def delete(self, tablename, query, safe=None): if safe is None: safe = self.safe amount = 0 amount = self.count(query, False) filter = self._delete(tablename, query) self.connection[tablename].remove(filter, safe=safe) return amount def bulk_insert(self, table, items): return [self.insert(table,item) for item in items] ## OPERATORS def INVERT(self, first): #print "in invert first=%s" % first return '-%s' % self.expand(first) # TODO This will probably not work:( def NOT(self, first): result = {} result["$not"] = self.expand(first) return result def AND(self,first,second): f = self.expand(first) s = self.expand(second) f.update(s) return f def OR(self,first,second): # pymongo expects: .find({'$or': [{'name':'1'}, {'name':'2'}]}) result = {} f = self.expand(first) s = self.expand(second) result['$or'] = [f,s] return result def BELONGS(self, first, second): if isinstance(second, str): return {self.expand(first) : {"$in" : [ second[:-1]]} } elif second==[] or second==() or second==set(): return {1:0} items = [self.expand(item, first.type) for item in second] return {self.expand(first) : {"$in" : items} } def EQ(self,first,second): result = {} result[self.expand(first)] = self.expand(second) return result def NE(self, first, second=None): result = {} result[self.expand(first)] = {'$ne': self.expand(second)} return result def LT(self,first,second=None): if second is None: raise RuntimeError("Cannot compare %s < None" % first) result = {} result[self.expand(first)] = {'$lt': self.expand(second)} return result def LE(self,first,second=None): if second is None: raise RuntimeError("Cannot compare %s <= None" % first) result = {} result[self.expand(first)] = {'$lte': self.expand(second)} return result def GT(self,first,second): result = {} result[self.expand(first)] = {'$gt': self.expand(second)} return result def GE(self,first,second=None): if second is None: raise RuntimeError("Cannot compare %s >= None" % first) result = {} result[self.expand(first)] = {'$gte': self.expand(second)} return result def ADD(self, first, second): raise NotImplementedError(self.error_messages["javascript_needed"]) return '%s + %s' % (self.expand(first), self.expand(second, first.type)) def SUB(self, first, second): raise NotImplementedError(self.error_messages["javascript_needed"]) return '(%s - %s)' % (self.expand(first), self.expand(second, first.type)) def MUL(self, first, second): raise NotImplementedError(self.error_messages["javascript_needed"]) return '(%s * %s)' % (self.expand(first), self.expand(second, first.type)) def DIV(self, first, second): raise NotImplementedError(self.error_messages["javascript_needed"]) return '(%s / %s)' % (self.expand(first), self.expand(second, first.type)) def MOD(self, first, second): raise NotImplementedError(self.error_messages["javascript_needed"]) return '(%s %% %s)' % (self.expand(first), self.expand(second, first.type)) def AS(self, first, second): raise NotImplementedError(self.error_messages["javascript_needed"]) return '%s AS %s' % (self.expand(first), second) # We could implement an option that simulates a full featured SQL # database. But I think the option should be set explicit or # implemented as another library. def ON(self, first, second): raise NotImplementedError("This is not possible in NoSQL" + " but can be simulated with a wrapper.") return '%s ON %s' % (self.expand(first), self.expand(second)) # BLOW ARE TWO IMPLEMENTATIONS OF THE SAME FUNCITONS # WHICH ONE IS BEST? def COMMA(self, first, second): return '%s, %s' % (self.expand(first), self.expand(second)) def LIKE(self, first, second): #escaping regex operators? return {self.expand(first): ('%s' % \ self.expand(second, 'string').replace('%','/'))} def STARTSWITH(self, first, second): #escaping regex operators? return {self.expand(first): ('/^%s/' % \ self.expand(second, 'string'))} def ENDSWITH(self, first, second): #escaping regex operators? return {self.expand(first): ('/%s^/' % \ self.expand(second, 'string'))} def CONTAINS(self, first, second, case_sensitive=False): # silently ignore, only case sensitive # There is a technical difference, but mongodb doesn't support # that, but the result will be the same val = second if isinstance(second,self.ObjectId) else \ {'$regex':".*" + re.escape(self.expand(second, 'string')) + ".*"} return {self.expand(first) : val} def LIKE(self, first, second): import re return {self.expand(first): {'$regex': \ re.escape(self.expand(second, 'string')).replace('%','.*')}} #TODO verify full compatibilty with official SQL Like operator def STARTSWITH(self, first, second): #TODO Solve almost the same problem as with endswith import re return {self.expand(first): {'$regex' : '^' + re.escape(self.expand(second, 'string'))}} #TODO verify full compatibilty with official SQL Like operator def ENDSWITH(self, first, second): #escaping regex operators? #TODO if searched for a name like zsa_corbitt and the function # is endswith('a') then this is also returned. # Aldo it end with a t import re return {self.expand(first): {'$regex': \ re.escape(self.expand(second, 'string')) + '$'}} #TODO verify full compatibilty with official oracle contains operator def CONTAINS(self, first, second, case_sensitive=False): # silently ignore, only case sensitive #There is a technical difference, but mongodb doesn't support # that, but the result will be the same #TODO contains operators need to be transformed to Regex return {self.expand(first) : {'$regex': \ ".*" + re.escape(self.expand(second, 'string')) + ".*"}} class IMAPAdapter(NoSQLAdapter): drivers = ('imaplib',) """ IMAP server adapter This class is intended as an interface with email IMAP servers to perform simple queries in the web2py DAL query syntax, so email read, search and other related IMAP mail services (as those implemented by brands like Google(r), and Yahoo!(r) can be managed from web2py applications. The code uses examples by Yuji Tomita on this post: http://yuji.wordpress.com/2011/06/22/python-imaplib-imap-example-with-gmail/#comment-1137 and is based in docs for Python imaplib, python email and email IETF's (i.e. RFC2060 and RFC3501) This adapter was tested with a small set of operations with Gmail(r). Other services requests could raise command syntax and response data issues. It creates its table and field names "statically", meaning that the developer should leave the table and field definitions to the DAL instance by calling the adapter's .define_tables() method. The tables are defined with the IMAP server mailbox list information. .define_tables() returns a dictionary mapping dal tablenames to the server mailbox names with the following structure: {<tablename>: str <server mailbox name>} Here is a list of supported fields: Field Type Description ################################################################ uid string answered boolean Flag created date content list:string A list of text or html parts to string cc string bcc string size integer the amount of octets of the message* deleted boolean Flag draft boolean Flag flagged boolean Flag sender string recent boolean Flag seen boolean Flag subject string mime string The mime header declaration email string The complete RFC822 message** attachments <type list> Each non text part as dict encoding string The main detected encoding *At the application side it is measured as the length of the RFC822 message string WARNING: As row id's are mapped to email sequence numbers, make sure your imap client web2py app does not delete messages during select or update actions, to prevent updating or deleting different messages. Sequence numbers change whenever the mailbox is updated. To avoid this sequence numbers issues, it is recommended the use of uid fields in query references (although the update and delete in separate actions rule still applies). # This is the code recommended to start imap support # at the app's model: imapdb = DAL("imap://user:password@server:port", pool_size=1) # port 993 for ssl imapdb.define_tables() Here is an (incomplete) list of possible imap commands: # Count today's unseen messages # smaller than 6000 octets from the # inbox mailbox q = imapdb.INBOX.seen == False q &= imapdb.INBOX.created == datetime.date.today() q &= imapdb.INBOX.size < 6000 unread = imapdb(q).count() # Fetch last query messages rows = imapdb(q).select() # it is also possible to filter query select results with limitby and # sequences of mailbox fields set.select(<fields sequence>, limitby=(<int>, <int>)) # Mark last query messages as seen messages = [row.uid for row in rows] seen = imapdb(imapdb.INBOX.uid.belongs(messages)).update(seen=True) # Delete messages in the imap database that have mails from mr. Gumby deleted = 0 for mailbox in imapdb.tables deleted += imapdb(imapdb[mailbox].sender.contains("gumby")).delete() # It is possible also to mark messages for deletion instead of ereasing them # directly with set.update(deleted=True) # This object give access # to the adapter auto mailbox # mapped names (which native # mailbox has what table name) imapdb.mailboxes <dict> # tablename, server native name pairs # To retrieve a table native mailbox name use: imapdb.<table>.mailbox ### New features v2.4.1: # Declare mailboxes statically with tablename, name pairs # This avoids the extra server names retrieval imapdb.define_tables({"inbox": "INBOX"}) # Selects without content/attachments/email columns will only # fetch header and flags imapdb(q).select(imapdb.INBOX.sender, imapdb.INBOX.subject) """ types = { 'string': str, 'text': str, 'date': datetime.date, 'datetime': datetime.datetime, 'id': long, 'boolean': bool, 'integer': int, 'bigint': long, 'blob': str, 'list:string': str, } dbengine = 'imap' REGEX_URI = re.compile('^(?P<user>[^:]+)(\:(?P<password>[^@]*))?@(?P<host>[^\:@]+)(\:(?P<port>[0-9]+))?$') def __init__(self, db, uri, pool_size=0, folder=None, db_codec ='UTF-8', credential_decoder=IDENTITY, driver_args={}, adapter_args={}, do_connect=True, after_connection=None): # db uri: user@example.com:password@imap.server.com:123 # TODO: max size adapter argument for preventing large mail transfers self.db = db self.uri = uri if do_connect: self.find_driver(adapter_args) self.pool_size=pool_size self.folder = folder self.db_codec = db_codec self._after_connection = after_connection self.credential_decoder = credential_decoder self.driver_args = driver_args self.adapter_args = adapter_args self.mailbox_size = None self.static_names = None self.charset = sys.getfilesystemencoding() # imap class self.imap4 = None uri = uri.split("://")[1] """ MESSAGE is an identifier for sequence number""" self.flags = ['\\Deleted', '\\Draft', '\\Flagged', '\\Recent', '\\Seen', '\\Answered'] self.search_fields = { 'id': 'MESSAGE', 'created': 'DATE', 'uid': 'UID', 'sender': 'FROM', 'to': 'TO', 'cc': 'CC', 'bcc': 'BCC', 'content': 'TEXT', 'size': 'SIZE', 'deleted': '\\Deleted', 'draft': '\\Draft', 'flagged': '\\Flagged', 'recent': '\\Recent', 'seen': '\\Seen', 'subject': 'SUBJECT', 'answered': '\\Answered', 'mime': None, 'email': None, 'attachments': None } db['_lastsql'] = '' m = self.REGEX_URI.match(uri) user = m.group('user') password = m.group('password') host = m.group('host') port = int(m.group('port')) over_ssl = False if port==993: over_ssl = True driver_args.update(host=host,port=port, password=password, user=user) def connector(driver_args=driver_args): # it is assumed sucessful authentication alLways # TODO: support direct connection and login tests if over_ssl: self.imap4 = self.driver.IMAP4_SSL else: self.imap4 = self.driver.IMAP4 connection = self.imap4(driver_args["host"], driver_args["port"]) data = connection.login(driver_args["user"], driver_args["password"]) # static mailbox list connection.mailbox_names = None # dummy cursor function connection.cursor = lambda : True return connection self.db.define_tables = self.define_tables self.connector = connector if do_connect: self.reconnect() def reconnect(self, f=None, cursor=True): """ IMAP4 Pool connection method imap connection lacks of self cursor command. A custom command should be provided as a replacement for connection pooling to prevent uncaught remote session closing """ if getattr(self,'connection',None) != None: return if f is None: f = self.connector if not self.pool_size: self.connection = f() self.cursor = cursor and self.connection.cursor() else: POOLS = ConnectionPool.POOLS uri = self.uri while True: GLOBAL_LOCKER.acquire() if not uri in POOLS: POOLS[uri] = [] if POOLS[uri]: self.connection = POOLS[uri].pop() GLOBAL_LOCKER.release() self.cursor = cursor and self.connection.cursor() if self.cursor and self.check_active_connection: try: # check if connection is alive or close it result, data = self.connection.list() except: # Possible connection reset error # TODO: read exception class self.connection = f() break else: GLOBAL_LOCKER.release() self.connection = f() self.cursor = cursor and self.connection.cursor() break self.after_connection_hook() def get_last_message(self, tablename): last_message = None # request mailbox list to the server # if needed if not isinstance(self.connection.mailbox_names, dict): self.get_mailboxes() try: result = self.connection.select(self.connection.mailbox_names[tablename]) last_message = int(result[1][0]) except (IndexError, ValueError, TypeError, KeyError): e = sys.exc_info()[1] LOGGER.debug("Error retrieving the last mailbox sequence number. %s" % str(e)) return last_message def get_uid_bounds(self, tablename): if not isinstance(self.connection.mailbox_names, dict): self.get_mailboxes() # fetch first and last messages # return (first, last) messages uid's last_message = self.get_last_message(tablename) result, data = self.connection.uid("search", None, "(ALL)") uid_list = data[0].strip().split() if len(uid_list) <= 0: return None else: return (uid_list[0], uid_list[-1]) def convert_date(self, date, add=None): if add is None: add = datetime.timedelta() """ Convert a date object to a string with d-Mon-Y style for IMAP or the inverse case add <timedelta> adds to the date object """ months = [None, "JAN","FEB","MAR","APR","MAY","JUN", "JUL", "AUG","SEP","OCT","NOV","DEC"] if isinstance(date, basestring): # Prevent unexpected date response format try: dayname, datestring = date.split(",") date_list = datestring.strip().split() year = int(date_list[2]) month = months.index(date_list[1].upper()) day = int(date_list[0]) hms = map(int, date_list[3].split(":")) return datetime.datetime(year, month, day, hms[0], hms[1], hms[2]) + add except (ValueError, AttributeError, IndexError), e: LOGGER.error("Could not parse date text: %s. %s" % (date, e)) return None elif isinstance(date, (datetime.datetime, datetime.date)): return (date + add).strftime("%d-%b-%Y") else: return None @staticmethod def header_represent(f, r): from email.header import decode_header text, encoding = decode_header(f)[0] if encoding: text = text.decode(encoding).encode('utf-8') return text def encode_text(self, text, charset, errors="replace"): """ convert text for mail to unicode""" if text is None: text = "" else: if isinstance(text, str): if charset is None: text = unicode(text, "utf-8", errors) else: text = unicode(text, charset, errors) else: raise Exception("Unsupported mail text type %s" % type(text)) return text.encode("utf-8") def get_charset(self, message): charset = message.get_content_charset() return charset def get_mailboxes(self): """ Query the mail database for mailbox names """ if self.static_names: # statically defined mailbox names self.connection.mailbox_names = self.static_names return self.static_names.keys() mailboxes_list = self.connection.list() self.connection.mailbox_names = dict() mailboxes = list() x = 0 for item in mailboxes_list[1]: x = x + 1 item = item.strip() if not "NOSELECT" in item.upper(): sub_items = item.split("\"") sub_items = [sub_item for sub_item in sub_items \ if len(sub_item.strip()) > 0] # mailbox = sub_items[len(sub_items) -1] mailbox = sub_items[-1] # remove unwanted characters and store original names # Don't allow leading non alphabetic characters mailbox_name = re.sub('^[_0-9]*', '', re.sub('[^_\w]','',re.sub('[/ ]','_',mailbox))) mailboxes.append(mailbox_name) self.connection.mailbox_names[mailbox_name] = mailbox return mailboxes def get_query_mailbox(self, query): nofield = True tablename = None attr = query while nofield: if hasattr(attr, "first"): attr = attr.first if isinstance(attr, Field): return attr.tablename elif isinstance(attr, Query): pass else: return None else: return None return tablename def is_flag(self, flag): if self.search_fields.get(flag, None) in self.flags: return True else: return False def define_tables(self, mailbox_names=None): """ Auto create common IMAP fileds This function creates fields definitions "statically" meaning that custom fields as in other adapters should not be supported and definitions handled on a service/mode basis (local syntax for Gmail(r), Ymail(r) Returns a dictionary with tablename, server native mailbox name pairs. """ if mailbox_names: # optional statically declared mailboxes self.static_names = mailbox_names else: self.static_names = None if not isinstance(self.connection.mailbox_names, dict): self.get_mailboxes() names = self.connection.mailbox_names.keys() for name in names: self.db.define_table("%s" % name, Field("uid", "string", writable=False), Field("answered", "boolean"), Field("created", "datetime", writable=False), Field("content", "list:string", writable=False), Field("to", "string", writable=False), Field("cc", "string", writable=False), Field("bcc", "string", writable=False), Field("size", "integer", writable=False), Field("deleted", "boolean"), Field("draft", "boolean"), Field("flagged", "boolean"), Field("sender", "string", writable=False), Field("recent", "boolean", writable=False), Field("seen", "boolean"), Field("subject", "string", writable=False), Field("mime", "string", writable=False), Field("email", "string", writable=False, readable=False), Field("attachments", list, writable=False, readable=False), Field("encoding", writable=False) ) # Set a special _mailbox attribute for storing # native mailbox names self.db[name].mailbox = \ self.connection.mailbox_names[name] # decode quoted printable self.db[name].to.represent = self.db[name].cc.represent = \ self.db[name].bcc.represent = self.db[name].sender.represent = \ self.db[name].subject.represent = self.header_represent # Set the db instance mailbox collections self.db.mailboxes = self.connection.mailbox_names return self.db.mailboxes def create_table(self, *args, **kwargs): # not implemented # but required by DAL pass def _select(self, query, fields, attributes): if use_common_filters(query): query = self.common_filter(query, [self.get_query_mailbox(query),]) return str(query) def select(self, query, fields, attributes): """ Search and Fetch records and return web2py rows """ # move this statement elsewhere (upper-level) if use_common_filters(query): query = self.common_filter(query, [self.get_query_mailbox(query),]) import email # get records from imap server with search + fetch # convert results to a dictionary tablename = None fetch_results = list() if isinstance(query, Query): tablename = self.get_table(query) mailbox = self.connection.mailbox_names.get(tablename, None) if mailbox is None: raise ValueError("Mailbox name not found: %s" % mailbox) else: # select with readonly result, selected = self.connection.select(mailbox, True) if result != "OK": raise Exception("IMAP error: %s" % selected) self.mailbox_size = int(selected[0]) search_query = "(%s)" % str(query).strip() search_result = self.connection.uid("search", None, search_query) # Normal IMAP response OK is assumed (change this) if search_result[0] == "OK": # For "light" remote server responses just get the first # ten records (change for non-experimental implementation) # However, light responses are not guaranteed with this # approach, just fewer messages. limitby = attributes.get('limitby', None) messages_set = search_result[1][0].split() # descending order messages_set.reverse() if limitby is not None: # TODO: orderby, asc/desc, limitby from complete message set messages_set = messages_set[int(limitby[0]):int(limitby[1])] # keep the requests small for header/flags if any([(field.name in ["content", "size", "attachments", "email"]) for field in fields]): imap_fields = "(RFC822 FLAGS)" else: imap_fields = "(RFC822.HEADER FLAGS)" if len(messages_set) > 0: # create fetch results object list # fetch each remote message and store it in memmory # (change to multi-fetch command syntax for faster # transactions) for uid in messages_set: # fetch the RFC822 message body typ, data = self.connection.uid("fetch", uid, imap_fields) if typ == "OK": fr = {"message": int(data[0][0].split()[0]), "uid": long(uid), "email": email.message_from_string(data[0][1]), "raw_message": data[0][1]} fr["multipart"] = fr["email"].is_multipart() # fetch flags for the message fr["flags"] = self.driver.ParseFlags(data[1]) fetch_results.append(fr) else: # error retrieving the message body raise Exception("IMAP error retrieving the body: %s" % data) else: raise Exception("IMAP search error: %s" % search_result[1]) elif isinstance(query, (Expression, basestring)): raise NotImplementedError() else: raise TypeError("Unexpected query type") imapqry_dict = {} imapfields_dict = {} if len(fields) == 1 and isinstance(fields[0], SQLALL): allfields = True elif len(fields) == 0: allfields = True else: allfields = False if allfields: colnames = ["%s.%s" % (tablename, field) for field in self.search_fields.keys()] else: colnames = ["%s.%s" % (tablename, field.name) for field in fields] for k in colnames: imapfields_dict[k] = k imapqry_list = list() imapqry_array = list() for fr in fetch_results: attachments = [] content = [] size = 0 n = int(fr["message"]) item_dict = dict() message = fr["email"] uid = fr["uid"] charset = self.get_charset(message) flags = fr["flags"] raw_message = fr["raw_message"] # Return messages data mapping static fields # and fetched results. Mapping should be made # outside the select function (with auxiliary # instance methods) # pending: search flags states trough the email message # instances for correct output # preserve subject encoding (ASCII/quoted printable) if "%s.id" % tablename in colnames: item_dict["%s.id" % tablename] = n if "%s.created" % tablename in colnames: item_dict["%s.created" % tablename] = self.convert_date(message["Date"]) if "%s.uid" % tablename in colnames: item_dict["%s.uid" % tablename] = uid if "%s.sender" % tablename in colnames: # If there is no encoding found in the message header # force utf-8 replacing characters (change this to # module's defaults). Applies to .sender, .to, .cc and .bcc fields item_dict["%s.sender" % tablename] = message["From"] if "%s.to" % tablename in colnames: item_dict["%s.to" % tablename] = message["To"] if "%s.cc" % tablename in colnames: if "Cc" in message.keys(): item_dict["%s.cc" % tablename] = message["Cc"] else: item_dict["%s.cc" % tablename] = "" if "%s.bcc" % tablename in colnames: if "Bcc" in message.keys(): item_dict["%s.bcc" % tablename] = message["Bcc"] else: item_dict["%s.bcc" % tablename] = "" if "%s.deleted" % tablename in colnames: item_dict["%s.deleted" % tablename] = "\\Deleted" in flags if "%s.draft" % tablename in colnames: item_dict["%s.draft" % tablename] = "\\Draft" in flags if "%s.flagged" % tablename in colnames: item_dict["%s.flagged" % tablename] = "\\Flagged" in flags if "%s.recent" % tablename in colnames: item_dict["%s.recent" % tablename] = "\\Recent" in flags if "%s.seen" % tablename in colnames: item_dict["%s.seen" % tablename] = "\\Seen" in flags if "%s.subject" % tablename in colnames: item_dict["%s.subject" % tablename] = message["Subject"] if "%s.answered" % tablename in colnames: item_dict["%s.answered" % tablename] = "\\Answered" in flags if "%s.mime" % tablename in colnames: item_dict["%s.mime" % tablename] = message.get_content_type() if "%s.encoding" % tablename in colnames: item_dict["%s.encoding" % tablename] = charset # Here goes the whole RFC822 body as an email instance # for controller side custom processing # The message is stored as a raw string # >> email.message_from_string(raw string) # returns a Message object for enhanced object processing if "%s.email" % tablename in colnames: # WARNING: no encoding performed (raw message) item_dict["%s.email" % tablename] = raw_message # Size measure as suggested in a Velocity Reviews post # by Tim Williams: "how to get size of email attachment" # Note: len() and server RFC822.SIZE reports doesn't match # To retrieve the server size for representation would add a new # fetch transaction to the process for part in message.walk(): maintype = part.get_content_maintype() if ("%s.attachments" % tablename in colnames) or \ ("%s.content" % tablename in colnames): if "%s.attachments" % tablename in colnames: if not ("text" in maintype): payload = part.get_payload(decode=True) if payload: attachment = { "payload": payload, "filename": part.get_filename(), "encoding": part.get_content_charset(), "mime": part.get_content_type(), "disposition": part["Content-Disposition"]} attachments.append(attachment) if "%s.content" % tablename in colnames: payload = part.get_payload(decode=True) part_charset = self.get_charset(part) if "text" in maintype: if payload: content.append(self.encode_text(payload, part_charset)) if "%s.size" % tablename in colnames: if part is not None: size += len(str(part)) item_dict["%s.content" % tablename] = content item_dict["%s.attachments" % tablename] = attachments item_dict["%s.size" % tablename] = size imapqry_list.append(item_dict) # extra object mapping for the sake of rows object # creation (sends an array or lists) for item_dict in imapqry_list: imapqry_array_item = list() for fieldname in colnames: imapqry_array_item.append(item_dict[fieldname]) imapqry_array.append(imapqry_array_item) # parse result and return a rows object colnames = colnames processor = attributes.get('processor',self.parse) return processor(imapqry_array, fields, colnames) def _update(self, tablename, query, fields, commit=False): # TODO: the adapter should implement an .expand method commands = list() if use_common_filters(query): query = self.common_filter(query, [tablename,]) mark = [] unmark = [] if query: for item in fields: field = item[0] name = field.name value = item[1] if self.is_flag(name): flag = self.search_fields[name] if (value is not None) and (flag != "\\Recent"): if value: mark.append(flag) else: unmark.append(flag) result, data = self.connection.select( self.connection.mailbox_names[tablename]) string_query = "(%s)" % query result, data = self.connection.search(None, string_query) store_list = [item.strip() for item in data[0].split() if item.strip().isdigit()] # build commands for marked flags for number in store_list: result = None if len(mark) > 0: commands.append((number, "+FLAGS", "(%s)" % " ".join(mark))) if len(unmark) > 0: commands.append((number, "-FLAGS", "(%s)" % " ".join(unmark))) return commands def update(self, tablename, query, fields): rowcount = 0 commands = self._update(tablename, query, fields) for command in commands: result, data = self.connection.store(*command) if result == "OK": rowcount += 1 else: raise Exception("IMAP storing error: %s" % data) return rowcount def _count(self, query, distinct=None): raise NotImplementedError() def count(self,query,distinct=None): counter = 0 tablename = self.get_query_mailbox(query) if query and tablename is not None: if use_common_filters(query): query = self.common_filter(query, [tablename,]) result, data = self.connection.select(self.connection.mailbox_names[tablename]) string_query = "(%s)" % query result, data = self.connection.search(None, string_query) store_list = [item.strip() for item in data[0].split() if item.strip().isdigit()] counter = len(store_list) return counter def delete(self, tablename, query): counter = 0 if query: if use_common_filters(query): query = self.common_filter(query, [tablename,]) result, data = self.connection.select(self.connection.mailbox_names[tablename]) string_query = "(%s)" % query result, data = self.connection.search(None, string_query) store_list = [item.strip() for item in data[0].split() if item.strip().isdigit()] for number in store_list: result, data = self.connection.store(number, "+FLAGS", "(\\Deleted)") if result == "OK": counter += 1 else: raise Exception("IMAP store error: %s" % data) if counter > 0: result, data = self.connection.expunge() return counter def BELONGS(self, first, second): result = None name = self.search_fields[first.name] if name == "MESSAGE": values = [str(val) for val in second if str(val).isdigit()] result = "%s" % ",".join(values).strip() elif name == "UID": values = [str(val) for val in second if str(val).isdigit()] result = "UID %s" % ",".join(values).strip() else: raise Exception("Operation not supported") # result = "(%s %s)" % (self.expand(first), self.expand(second)) return result def CONTAINS(self, first, second, case_sensitive=False): # silently ignore, only case sensitive result = None name = self.search_fields[first.name] if name in ("FROM", "TO", "SUBJECT", "TEXT"): result = "%s \"%s\"" % (name, self.expand(second)) else: if first.name in ("cc", "bcc"): result = "%s \"%s\"" % (first.name.upper(), self.expand(second)) elif first.name == "mime": result = "HEADER Content-Type \"%s\"" % self.expand(second) else: raise Exception("Operation not supported") return result def GT(self, first, second): result = None name = self.search_fields[first.name] if name == "MESSAGE": last_message = self.get_last_message(first.tablename) result = "%d:%d" % (int(self.expand(second)) + 1, last_message) elif name == "UID": # GT and LT may not return # expected sets depending on # the uid format implemented try: pedestal, threshold = self.get_uid_bounds(first.tablename) except TypeError: e = sys.exc_info()[1] LOGGER.debug("Error requesting uid bounds: %s", str(e)) return "" try: lower_limit = int(self.expand(second)) + 1 except (ValueError, TypeError): e = sys.exc_info()[1] raise Exception("Operation not supported (non integer UID)") result = "UID %s:%s" % (lower_limit, threshold) elif name == "DATE": result = "SINCE %s" % self.convert_date(second, add=datetime.timedelta(1)) elif name == "SIZE": result = "LARGER %s" % self.expand(second) else: raise Exception("Operation not supported") return result def GE(self, first, second): result = None name = self.search_fields[first.name] if name == "MESSAGE": last_message = self.get_last_message(first.tablename) result = "%s:%s" % (self.expand(second), last_message) elif name == "UID": # GT and LT may not return # expected sets depending on # the uid format implemented try: pedestal, threshold = self.get_uid_bounds(first.tablename) except TypeError: e = sys.exc_info()[1] LOGGER.debug("Error requesting uid bounds: %s", str(e)) return "" lower_limit = self.expand(second) result = "UID %s:%s" % (lower_limit, threshold) elif name == "DATE": result = "SINCE %s" % self.convert_date(second) else: raise Exception("Operation not supported") return result def LT(self, first, second): result = None name = self.search_fields[first.name] if name == "MESSAGE": result = "%s:%s" % (1, int(self.expand(second)) - 1) elif name == "UID": try: pedestal, threshold = self.get_uid_bounds(first.tablename) except TypeError: e = sys.exc_info()[1] LOGGER.debug("Error requesting uid bounds: %s", str(e)) return "" try: upper_limit = int(self.expand(second)) - 1 except (ValueError, TypeError): e = sys.exc_info()[1] raise Exception("Operation not supported (non integer UID)") result = "UID %s:%s" % (pedestal, upper_limit) elif name == "DATE": result = "BEFORE %s" % self.convert_date(second) elif name == "SIZE": result = "SMALLER %s" % self.expand(second) else: raise Exception("Operation not supported") return result def LE(self, first, second): result = None name = self.search_fields[first.name] if name == "MESSAGE": result = "%s:%s" % (1, self.expand(second)) elif name == "UID": try: pedestal, threshold = self.get_uid_bounds(first.tablename) except TypeError: e = sys.exc_info()[1] LOGGER.debug("Error requesting uid bounds: %s", str(e)) return "" upper_limit = int(self.expand(second)) result = "UID %s:%s" % (pedestal, upper_limit) elif name == "DATE": result = "BEFORE %s" % self.convert_date(second, add=datetime.timedelta(1)) else: raise Exception("Operation not supported") return result def NE(self, first, second=None): if (second is None) and isinstance(first, Field): # All records special table query if first.type == "id": return self.GE(first, 1) result = self.NOT(self.EQ(first, second)) result = result.replace("NOT NOT", "").strip() return result def EQ(self,first,second): name = self.search_fields[first.name] result = None if name is not None: if name == "MESSAGE": # query by message sequence number result = "%s" % self.expand(second) elif name == "UID": result = "UID %s" % self.expand(second) elif name == "DATE": result = "ON %s" % self.convert_date(second) elif name in self.flags: if second: result = "%s" % (name.upper()[1:]) else: result = "NOT %s" % (name.upper()[1:]) else: raise Exception("Operation not supported") else: raise Exception("Operation not supported") return result def AND(self, first, second): result = "%s %s" % (self.expand(first), self.expand(second)) return result def OR(self, first, second): result = "OR %s %s" % (self.expand(first), self.expand(second)) return "%s" % result.replace("OR OR", "OR") def NOT(self, first): result = "NOT %s" % self.expand(first) return result ######################################################################## # end of adapters ######################################################################## ADAPTERS = { 'sqlite': SQLiteAdapter, 'spatialite': SpatiaLiteAdapter, 'sqlite:memory': SQLiteAdapter, 'spatialite:memory': SpatiaLiteAdapter, 'mysql': MySQLAdapter, 'postgres': PostgreSQLAdapter, 'postgres:psycopg2': PostgreSQLAdapter, 'postgres:pg8000': PostgreSQLAdapter, 'postgres2:psycopg2': NewPostgreSQLAdapter, 'postgres2:pg8000': NewPostgreSQLAdapter, 'oracle': OracleAdapter, 'mssql': MSSQLAdapter, 'mssql2': MSSQL2Adapter, 'mssql3': MSSQL3Adapter, 'vertica': VerticaAdapter, 'sybase': SybaseAdapter, 'db2': DB2Adapter, 'teradata': TeradataAdapter, 'informix': InformixAdapter, 'informix-se': InformixSEAdapter, 'firebird': FireBirdAdapter, 'firebird_embedded': FireBirdAdapter, 'ingres': IngresAdapter, 'ingresu': IngresUnicodeAdapter, 'sapdb': SAPDBAdapter, 'cubrid': CubridAdapter, 'jdbc:sqlite': JDBCSQLiteAdapter, 'jdbc:sqlite:memory': JDBCSQLiteAdapter, 'jdbc:postgres': JDBCPostgreSQLAdapter, 'gae': GoogleDatastoreAdapter, # discouraged, for backward compatibility 'google:datastore': GoogleDatastoreAdapter, 'google:sql': GoogleSQLAdapter, 'couchdb': CouchDBAdapter, 'mongodb': MongoDBAdapter, 'imap': IMAPAdapter } def sqlhtml_validators(field): """ Field type validation, using web2py's validators mechanism. makes sure the content of a field is in line with the declared fieldtype """ db = field.db if not have_validators: return [] field_type, field_length = field.type, field.length if isinstance(field_type, SQLCustomType): if hasattr(field_type, 'validator'): return field_type.validator else: field_type = field_type.type elif not isinstance(field_type,str): return [] requires=[] def ff(r,id): row=r(id) if not row: return id elif hasattr(r, '_format') and isinstance(r._format,str): return r._format % row elif hasattr(r, '_format') and callable(r._format): return r._format(row) else: return id if field_type in (('string', 'text', 'password')): requires.append(validators.IS_LENGTH(field_length)) elif field_type == 'json': requires.append(validators.IS_EMPTY_OR(validators.IS_JSON())) elif field_type == 'double' or field_type == 'float': requires.append(validators.IS_FLOAT_IN_RANGE(-1e100, 1e100)) elif field_type in ('integer','bigint'): requires.append(validators.IS_INT_IN_RANGE(-1e100, 1e100)) elif field_type.startswith('decimal'): requires.append(validators.IS_DECIMAL_IN_RANGE(-10**10, 10**10)) elif field_type == 'date': requires.append(validators.IS_DATE()) elif field_type == 'time': requires.append(validators.IS_TIME()) elif field_type == 'datetime': requires.append(validators.IS_DATETIME()) elif db and field_type.startswith('reference') and \ field_type.find('.') < 0 and \ field_type[10:] in db.tables: referenced = db[field_type[10:]] def repr_ref(id, row=None, r=referenced, f=ff): return f(r, id) field.represent = field.represent or repr_ref if hasattr(referenced, '_format') and referenced._format: requires = validators.IS_IN_DB(db,referenced._id, referenced._format) if field.unique: requires._and = validators.IS_NOT_IN_DB(db,field) if field.tablename == field_type[10:]: return validators.IS_EMPTY_OR(requires) return requires elif db and field_type.startswith('list:reference') and \ field_type.find('.') < 0 and \ field_type[15:] in db.tables: referenced = db[field_type[15:]] def list_ref_repr(ids, row=None, r=referenced, f=ff): if not ids: return None refs = None db, id = r._db, r._id if isinstance(db._adapter, GoogleDatastoreAdapter): def count(values): return db(id.belongs(values)).select(id) rx = range(0, len(ids), 30) refs = reduce(lambda a,b:a&b, [count(ids[i:i+30]) for i in rx]) else: refs = db(id.belongs(ids)).select(id) return (refs and ', '.join(str(f(r,x.id)) for x in refs) or '') field.represent = field.represent or list_ref_repr if hasattr(referenced, '_format') and referenced._format: requires = validators.IS_IN_DB(db,referenced._id, referenced._format,multiple=True) else: requires = validators.IS_IN_DB(db,referenced._id, multiple=True) if field.unique: requires._and = validators.IS_NOT_IN_DB(db,field) return requires elif field_type.startswith('list:'): def repr_list(values,row=None): return', '.join(str(v) for v in (values or [])) field.represent = field.represent or repr_list if field.unique: requires.insert(0,validators.IS_NOT_IN_DB(db,field)) sff = ['in', 'do', 'da', 'ti', 'de', 'bo'] if field.notnull and not field_type[:2] in sff: requires.insert(0, validators.IS_NOT_EMPTY()) elif not field.notnull and field_type[:2] in sff and requires: requires[-1] = validators.IS_EMPTY_OR(requires[-1]) return requires def bar_escape(item): return str(item).replace('|', '||') def bar_encode(items): return '|%s|' % '|'.join(bar_escape(item) for item in items if str(item).strip()) def bar_decode_integer(value): if not hasattr(value,'split') and hasattr(value,'read'): value = value.read() return [long(x) for x in value.split('|') if x.strip()] def bar_decode_string(value): return [x.replace('||', '|') for x in REGEX_UNPACK.split(value[1:-1]) if x.strip()] class Row(object): """ a dictionary that lets you do d['a'] as well as d.a this is only used to store a Row """ __init__ = lambda self,*args,**kwargs: self.__dict__.update(*args,**kwargs) def __getitem__(self, k): key=str(k) _extra = self.__dict__.get('_extra', None) if _extra is not None: v = _extra.get(key, None) if v: return v m = REGEX_TABLE_DOT_FIELD.match(key) if m: try: return ogetattr(self, m.group(1))[m.group(2)] except (KeyError,AttributeError,TypeError): key = m.group(2) return ogetattr(self, key) __setitem__ = lambda self, key, value: setattr(self, str(key), value) __delitem__ = object.__delattr__ __copy__ = lambda self: Row(self) __call__ = __getitem__ get = lambda self, key, default=None: self.__dict__.get(key,default) has_key = __contains__ = lambda self, key: key in self.__dict__ __nonzero__ = lambda self: len(self.__dict__)>0 update = lambda self, *args, **kwargs: self.__dict__.update(*args, **kwargs) keys = lambda self: self.__dict__.keys() items = lambda self: self.__dict__.items() values = lambda self: self.__dict__.values() __iter__ = lambda self: self.__dict__.__iter__() iteritems = lambda self: self.__dict__.iteritems() __str__ = __repr__ = lambda self: '<Row %s>' % self.as_dict() __int__ = lambda self: object.__getattribute__(self,'id') __long__ = lambda self: long(object.__getattribute__(self,'id')) def __eq__(self,other): try: return self.as_dict() == other.as_dict() except AttributeError: return False def __ne__(self,other): return not (self == other) def __copy__(self): return Row(dict(self)) def as_dict(self, datetime_to_str=False, custom_types=None): SERIALIZABLE_TYPES = [str, unicode, int, long, float, bool, list, dict] if isinstance(custom_types,(list,tuple,set)): SERIALIZABLE_TYPES += custom_types elif custom_types: SERIALIZABLE_TYPES.append(custom_types) d = dict(self) for k in copy.copy(d.keys()): v=d[k] if d[k] is None: continue elif isinstance(v,Row): d[k]=v.as_dict() elif isinstance(v,Reference): d[k]=long(v) elif isinstance(v,decimal.Decimal): d[k]=float(v) elif isinstance(v, (datetime.date, datetime.datetime, datetime.time)): if datetime_to_str: d[k] = v.isoformat().replace('T',' ')[:19] elif not isinstance(v,tuple(SERIALIZABLE_TYPES)): del d[k] return d def as_xml(self, row_name="row", colnames=None, indent=' '): def f(row,field,indent=' '): if isinstance(row,Row): spc = indent+' \n' items = [f(row[x],x,indent+' ') for x in row] return '%s<%s>\n%s\n%s</%s>' % ( indent, field, spc.join(item for item in items if item), indent, field) elif not callable(row): if REGEX_ALPHANUMERIC.match(field): return '%s<%s>%s</%s>' % (indent,field,row,field) else: return '%s<extra name="%s">%s</extra>' % \ (indent,field,row) else: return None return f(self, row_name, indent=indent) def as_json(self, mode="object", default=None, colnames=None, serialize=True, **kwargs): """ serializes the row to a JSON object kwargs are passed to .as_dict method only "object" mode supported serialize = False used by Rows.as_json TODO: return array mode with query column order mode and colnames are not implemented """ item = self.as_dict(**kwargs) if serialize: if have_serializers: return serializers.json(item, default=default or serializers.custom_json) elif simplejson: return simplejson.dumps(item) else: raise RuntimeError("missing simplejson") else: return item ################################################################################ # Everything below should be independent of the specifics of the database # and should work for RDBMs and some NoSQL databases ################################################################################ class SQLCallableList(list): def __call__(self): return copy.copy(self) def smart_query(fields,text): if not isinstance(fields,(list,tuple)): fields = [fields] new_fields = [] for field in fields: if isinstance(field,Field): new_fields.append(field) elif isinstance(field,Table): for ofield in field: new_fields.append(ofield) else: raise RuntimeError("fields must be a list of fields") fields = new_fields field_map = {} for field in fields: n = field.name.lower() if not n in field_map: field_map[n] = field n = str(field).lower() if not n in field_map: field_map[n] = field constants = {} i = 0 while True: m = REGEX_CONST_STRING.search(text) if not m: break text = text[:m.start()]+('#%i' % i)+text[m.end():] constants[str(i)] = m.group()[1:-1] i+=1 text = re.sub('\s+',' ',text).lower() for a,b in [('&','and'), ('|','or'), ('~','not'), ('==','='), ('<','<'), ('>','>'), ('<=','<='), ('>=','>='), ('<>','!='), ('=<','<='), ('=>','>='), ('=','='), (' less or equal than ','<='), (' greater or equal than ','>='), (' equal or less than ','<='), (' equal or greater than ','>='), (' less or equal ','<='), (' greater or equal ','>='), (' equal or less ','<='), (' equal or greater ','>='), (' not equal to ','!='), (' not equal ','!='), (' equal to ','='), (' equal ','='), (' equals ','='), (' less than ','<'), (' greater than ','>'), (' starts with ','startswith'), (' ends with ','endswith'), (' not in ' , 'notbelongs'), (' in ' , 'belongs'), (' is ','=')]: if a[0]==' ': text = text.replace(' is'+a,' %s ' % b) text = text.replace(a,' %s ' % b) text = re.sub('\s+',' ',text).lower() text = re.sub('(?P<a>[\<\>\!\=])\s+(?P<b>[\<\>\!\=])','\g<a>\g<b>',text) query = field = neg = op = logic = None for item in text.split(): if field is None: if item == 'not': neg = True elif not neg and not logic and item in ('and','or'): logic = item elif item in field_map: field = field_map[item] else: raise RuntimeError("Invalid syntax") elif not field is None and op is None: op = item elif not op is None: if item.startswith('#'): if not item[1:] in constants: raise RuntimeError("Invalid syntax") value = constants[item[1:]] else: value = item if field.type in ('text', 'string', 'json'): if op == '=': op = 'like' if op == '=': new_query = field==value elif op == '<': new_query = field<value elif op == '>': new_query = field>value elif op == '<=': new_query = field<=value elif op == '>=': new_query = field>=value elif op == '!=': new_query = field!=value elif op == 'belongs': new_query = field.belongs(value.split(',')) elif op == 'notbelongs': new_query = ~field.belongs(value.split(',')) elif field.type in ('text', 'string', 'json'): if op == 'contains': new_query = field.contains(value) elif op == 'like': new_query = field.like(value) elif op == 'startswith': new_query = field.startswith(value) elif op == 'endswith': new_query = field.endswith(value) else: raise RuntimeError("Invalid operation") elif field._db._adapter.dbengine=='google:datastore' and \ field.type in ('list:integer', 'list:string', 'list:reference'): if op == 'contains': new_query = field.contains(value) else: raise RuntimeError("Invalid operation") else: raise RuntimeError("Invalid operation") if neg: new_query = ~new_query if query is None: query = new_query elif logic == 'and': query &= new_query elif logic == 'or': query |= new_query field = op = neg = logic = None return query class DAL(object): """ an instance of this class represents a database connection Example:: db = DAL('sqlite://test.db') or db = DAL({"uri": ..., "items": ...}) # experimental db.define_table('tablename', Field('fieldname1'), Field('fieldname2')) """ def __new__(cls, uri='sqlite://dummy.db', *args, **kwargs): if not hasattr(THREAD_LOCAL,'db_instances'): THREAD_LOCAL.db_instances = {} if not hasattr(THREAD_LOCAL,'db_instances_zombie'): THREAD_LOCAL.db_instances_zombie = {} if uri == '<zombie>': db_uid = kwargs['db_uid'] # a zombie must have a db_uid! if db_uid in THREAD_LOCAL.db_instances: db_group = THREAD_LOCAL.db_instances[db_uid] db = db_group[-1] elif db_uid in THREAD_LOCAL.db_instances_zombie: db = THREAD_LOCAL.db_instances_zombie[db_uid] else: db = super(DAL, cls).__new__(cls) THREAD_LOCAL.db_instances_zombie[db_uid] = db else: db_uid = kwargs.get('db_uid',hashlib_md5(repr(uri)).hexdigest()) if db_uid in THREAD_LOCAL.db_instances_zombie: db = THREAD_LOCAL.db_instances_zombie[db_uid] del THREAD_LOCAL.db_instances_zombie[db_uid] else: db = super(DAL, cls).__new__(cls) db_group = THREAD_LOCAL.db_instances.get(db_uid,[]) db_group.append(db) THREAD_LOCAL.db_instances[db_uid] = db_group db._db_uid = db_uid return db @staticmethod def set_folder(folder): """ # ## this allows gluon to set a folder for this thread # ## <<<<<<<<< Should go away as new DAL replaces old sql.py """ BaseAdapter.set_folder(folder) @staticmethod def get_instances(): """ Returns a dictionary with uri as key with timings and defined tables {'sqlite://storage.sqlite': { 'dbstats': [(select auth_user.email from auth_user, 0.02009)], 'dbtables': { 'defined': ['auth_cas', 'auth_event', 'auth_group', 'auth_membership', 'auth_permission', 'auth_user'], 'lazy': '[]' } } } """ dbs = getattr(THREAD_LOCAL,'db_instances',{}).items() infos = {} for db_uid, db_group in dbs: for db in db_group: if not db._uri: continue k = hide_password(db._uri) infos[k] = dict(dbstats = [(row[0], row[1]) for row in db._timings], dbtables = {'defined': sorted(list(set(db.tables) - set(db._LAZY_TABLES.keys()))), 'lazy': sorted(db._LAZY_TABLES.keys())} ) return infos @staticmethod def distributed_transaction_begin(*instances): if not instances: return thread_key = '%s.%s' % (socket.gethostname(), threading.currentThread()) keys = ['%s.%i' % (thread_key, i) for (i,db) in instances] instances = enumerate(instances) for (i, db) in instances: if not db._adapter.support_distributed_transaction(): raise SyntaxError( 'distributed transaction not suported by %s' % db._dbname) for (i, db) in instances: db._adapter.distributed_transaction_begin(keys[i]) @staticmethod def distributed_transaction_commit(*instances): if not instances: return instances = enumerate(instances) thread_key = '%s.%s' % (socket.gethostname(), threading.currentThread()) keys = ['%s.%i' % (thread_key, i) for (i,db) in instances] for (i, db) in instances: if not db._adapter.support_distributed_transaction(): raise SyntaxError( 'distributed transaction not suported by %s' % db._dbanme) try: for (i, db) in instances: db._adapter.prepare(keys[i]) except: for (i, db) in instances: db._adapter.rollback_prepared(keys[i]) raise RuntimeError('failure to commit distributed transaction') else: for (i, db) in instances: db._adapter.commit_prepared(keys[i]) return def __init__(self, uri=DEFAULT_URI, pool_size=0, folder=None, db_codec='UTF-8', check_reserved=None, migrate=True, fake_migrate=False, migrate_enabled=True, fake_migrate_all=False, decode_credentials=False, driver_args=None, adapter_args=None, attempts=5, auto_import=False, bigint_id=False,debug=False,lazy_tables=False, db_uid=None, do_connect=True, after_connection=None): """ Creates a new Database Abstraction Layer instance. Keyword arguments: :uri: string that contains information for connecting to a database. (default: 'sqlite://dummy.db') experimental: you can specify a dictionary as uri parameter i.e. with db = DAL({"uri": "sqlite://storage.sqlite", "items": {...}, ...}) for an example of dict input you can check the output of the scaffolding db model with db.as_dict() Note that for compatibility with Python older than version 2.6.5 you should cast your dict input keys to str due to a syntax limitation on kwarg names. for proper DAL dictionary input you can use one of: obj = serializers.cast_keys(dict, [encoding="utf-8"]) or else (for parsing json input) obj = serializers.loads_json(data, unicode_keys=False) :pool_size: How many open connections to make to the database object. :folder: where .table files will be created. automatically set within web2py use an explicit path when using DAL outside web2py :db_codec: string encoding of the database (default: 'UTF-8') :check_reserved: list of adapters to check tablenames and column names against sql/nosql reserved keywords. (Default None) * 'common' List of sql keywords that are common to all database types such as "SELECT, INSERT". (recommended) * 'all' Checks against all known SQL keywords. (not recommended) <adaptername> Checks against the specific adapters list of keywords (recommended) * '<adaptername>_nonreserved' Checks against the specific adapters list of nonreserved keywords. (if available) :migrate (defaults to True) sets default migrate behavior for all tables :fake_migrate (defaults to False) sets default fake_migrate behavior for all tables :migrate_enabled (defaults to True). If set to False disables ALL migrations :fake_migrate_all (defaults to False). If sets to True fake migrates ALL tables :attempts (defaults to 5). Number of times to attempt connecting :auto_import (defaults to False). If set, import automatically table definitions from the databases folder :bigint_id (defaults to False): If set, turn on bigint instead of int for id fields :lazy_tables (defaults to False): delay table definition until table access :after_connection (defaults to None): a callable that will be execute after the connection """ items = None if isinstance(uri, dict): if "items" in uri: items = uri.pop("items") try: newuri = uri.pop("uri") except KeyError: newuri = DEFAULT_URI locals().update(uri) uri = newuri if uri == '<zombie>' and db_uid is not None: return if not decode_credentials: credential_decoder = lambda cred: cred else: credential_decoder = lambda cred: urllib.unquote(cred) self._folder = folder if folder: self.set_folder(folder) self._uri = uri self._pool_size = pool_size self._db_codec = db_codec self._lastsql = '' self._timings = [] self._pending_references = {} self._request_tenant = 'request_tenant' self._common_fields = [] self._referee_name = '%(table)s' self._bigint_id = bigint_id self._debug = debug self._migrated = [] self._LAZY_TABLES = {} self._lazy_tables = lazy_tables self._tables = SQLCallableList() self._driver_args = driver_args self._adapter_args = adapter_args self._check_reserved = check_reserved self._decode_credentials = decode_credentials self._attempts = attempts self._do_connect = do_connect if not str(attempts).isdigit() or attempts < 0: attempts = 5 if uri: uris = isinstance(uri,(list,tuple)) and uri or [uri] error = '' connected = False for k in range(attempts): for uri in uris: try: if is_jdbc and not uri.startswith('jdbc:'): uri = 'jdbc:'+uri self._dbname = REGEX_DBNAME.match(uri).group() if not self._dbname in ADAPTERS: raise SyntaxError("Error in URI '%s' or database not supported" % self._dbname) # notice that driver args or {} else driver_args # defaults to {} global, not correct kwargs = dict(db=self,uri=uri, pool_size=pool_size, folder=folder, db_codec=db_codec, credential_decoder=credential_decoder, driver_args=driver_args or {}, adapter_args=adapter_args or {}, do_connect=do_connect, after_connection=after_connection) self._adapter = ADAPTERS[self._dbname](**kwargs) types = ADAPTERS[self._dbname].types # copy so multiple DAL() possible self._adapter.types = copy.copy(types) if bigint_id: if 'big-id' in types and 'reference' in types: self._adapter.types['id'] = types['big-id'] self._adapter.types['reference'] = types['big-reference'] connected = True break except SyntaxError: raise except Exception: tb = traceback.format_exc() sys.stderr.write('DEBUG: connect attempt %i, connection error:\n%s' % (k, tb)) if connected: break else: time.sleep(1) if not connected: raise RuntimeError("Failure to connect, tried %d times:\n%s" % (attempts, tb)) else: self._adapter = BaseAdapter(db=self,pool_size=0, uri='None',folder=folder, db_codec=db_codec, after_connection=after_connection) migrate = fake_migrate = False adapter = self._adapter self._uri_hash = hashlib_md5(adapter.uri).hexdigest() self.check_reserved = check_reserved if self.check_reserved: from reserved_sql_keywords import ADAPTERS as RSK self.RSK = RSK self._migrate = migrate self._fake_migrate = fake_migrate self._migrate_enabled = migrate_enabled self._fake_migrate_all = fake_migrate_all if auto_import or items: self.import_table_definitions(adapter.folder, items=items) @property def tables(self): return self._tables def import_table_definitions(self, path, migrate=False, fake_migrate=False, items=None): pattern = pjoin(path,self._uri_hash+'_*.table') if items: for tablename, table in items.iteritems(): # TODO: read all field/table options fields = [] # remove unsupported/illegal Table arguments [table.pop(name) for name in ("name", "fields") if name in table] if "items" in table: for fieldname, field in table.pop("items").iteritems(): # remove unsupported/illegal Field arguments [field.pop(key) for key in ("requires", "name", "compute", "colname") if key in field] fields.append(Field(str(fieldname), **field)) self.define_table(str(tablename), *fields, **table) else: for filename in glob.glob(pattern): tfile = self._adapter.file_open(filename, 'r') try: sql_fields = pickle.load(tfile) name = filename[len(pattern)-7:-6] mf = [(value['sortable'], Field(key, type=value['type'], length=value.get('length',None), notnull=value.get('notnull',False), unique=value.get('unique',False))) \ for key, value in sql_fields.iteritems()] mf.sort(lambda a,b: cmp(a[0],b[0])) self.define_table(name,*[item[1] for item in mf], **dict(migrate=migrate, fake_migrate=fake_migrate)) finally: self._adapter.file_close(tfile) def check_reserved_keyword(self, name): """ Validates ``name`` against SQL keywords Uses self.check_reserve which is a list of operators to use. self.check_reserved ['common', 'postgres', 'mysql'] self.check_reserved ['all'] """ for backend in self.check_reserved: if name.upper() in self.RSK[backend]: raise SyntaxError( 'invalid table/column name "%s" is a "%s" reserved SQL/NOSQL keyword' % (name, backend.upper())) def parse_as_rest(self,patterns,args,vars,queries=None,nested_select=True): """ EXAMPLE: db.define_table('person',Field('name'),Field('info')) db.define_table('pet',Field('ownedby',db.person),Field('name'),Field('info')) @request.restful() def index(): def GET(*args,**vars): patterns = [ "/friends[person]", "/{person.name}/:field", "/{person.name}/pets[pet.ownedby]", "/{person.name}/pets[pet.ownedby]/{pet.name}", "/{person.name}/pets[pet.ownedby]/{pet.name}/:field", ("/dogs[pet]", db.pet.info=='dog'), ("/dogs[pet]/{pet.name.startswith}", db.pet.info=='dog'), ] parser = db.parse_as_rest(patterns,args,vars) if parser.status == 200: return dict(content=parser.response) else: raise HTTP(parser.status,parser.error) def POST(table_name,**vars): if table_name == 'person': return db.person.validate_and_insert(**vars) elif table_name == 'pet': return db.pet.validate_and_insert(**vars) else: raise HTTP(400) return locals() """ db = self re1 = REGEX_SEARCH_PATTERN re2 = REGEX_SQUARE_BRACKETS def auto_table(table,base='',depth=0): patterns = [] for field in db[table].fields: if base: tag = '%s/%s' % (base,field.replace('_','-')) else: tag = '/%s/%s' % (table.replace('_','-'),field.replace('_','-')) f = db[table][field] if not f.readable: continue if f.type=='id' or 'slug' in field or f.type.startswith('reference'): tag += '/{%s.%s}' % (table,field) patterns.append(tag) patterns.append(tag+'/:field') elif f.type.startswith('boolean'): tag += '/{%s.%s}' % (table,field) patterns.append(tag) patterns.append(tag+'/:field') elif f.type in ('float','double','integer','bigint'): tag += '/{%s.%s.ge}/{%s.%s.lt}' % (table,field,table,field) patterns.append(tag) patterns.append(tag+'/:field') elif f.type.startswith('list:'): tag += '/{%s.%s.contains}' % (table,field) patterns.append(tag) patterns.append(tag+'/:field') elif f.type in ('date','datetime'): tag+= '/{%s.%s.year}' % (table,field) patterns.append(tag) patterns.append(tag+'/:field') tag+='/{%s.%s.month}' % (table,field) patterns.append(tag) patterns.append(tag+'/:field') tag+='/{%s.%s.day}' % (table,field) patterns.append(tag) patterns.append(tag+'/:field') if f.type in ('datetime','time'): tag+= '/{%s.%s.hour}' % (table,field) patterns.append(tag) patterns.append(tag+'/:field') tag+='/{%s.%s.minute}' % (table,field) patterns.append(tag) patterns.append(tag+'/:field') tag+='/{%s.%s.second}' % (table,field) patterns.append(tag) patterns.append(tag+'/:field') if depth>0: for f in db[table]._referenced_by: tag+='/%s[%s.%s]' % (table,f.tablename,f.name) patterns.append(tag) patterns += auto_table(table,base=tag,depth=depth-1) return patterns if patterns == 'auto': patterns=[] for table in db.tables: if not table.startswith('auth_'): patterns.append('/%s[%s]' % (table,table)) patterns += auto_table(table,base='',depth=1) else: i = 0 while i<len(patterns): pattern = patterns[i] if not isinstance(pattern,str): pattern = pattern[0] tokens = pattern.split('/') if tokens[-1].startswith(':auto') and re2.match(tokens[-1]): new_patterns = auto_table(tokens[-1][tokens[-1].find('[')+1:-1], '/'.join(tokens[:-1])) patterns = patterns[:i]+new_patterns+patterns[i+1:] i += len(new_patterns) else: i += 1 if '/'.join(args) == 'patterns': return Row({'status':200,'pattern':'list', 'error':None,'response':patterns}) for pattern in patterns: basequery, exposedfields = None, [] if isinstance(pattern,tuple): if len(pattern)==2: pattern, basequery = pattern elif len(pattern)>2: pattern, basequery, exposedfields = pattern[0:3] otable=table=None if not isinstance(queries,dict): dbset=db(queries) if basequery is not None: dbset = dbset(basequery) i=0 tags = pattern[1:].split('/') if len(tags)!=len(args): continue for tag in tags: if re1.match(tag): # print 're1:'+tag tokens = tag[1:-1].split('.') table, field = tokens[0], tokens[1] if not otable or table == otable: if len(tokens)==2 or tokens[2]=='eq': query = db[table][field]==args[i] elif tokens[2]=='ne': query = db[table][field]!=args[i] elif tokens[2]=='lt': query = db[table][field]<args[i] elif tokens[2]=='gt': query = db[table][field]>args[i] elif tokens[2]=='ge': query = db[table][field]>=args[i] elif tokens[2]=='le': query = db[table][field]<=args[i] elif tokens[2]=='year': query = db[table][field].year()==args[i] elif tokens[2]=='month': query = db[table][field].month()==args[i] elif tokens[2]=='day': query = db[table][field].day()==args[i] elif tokens[2]=='hour': query = db[table][field].hour()==args[i] elif tokens[2]=='minute': query = db[table][field].minutes()==args[i] elif tokens[2]=='second': query = db[table][field].seconds()==args[i] elif tokens[2]=='startswith': query = db[table][field].startswith(args[i]) elif tokens[2]=='contains': query = db[table][field].contains(args[i]) else: raise RuntimeError("invalid pattern: %s" % pattern) if len(tokens)==4 and tokens[3]=='not': query = ~query elif len(tokens)>=4: raise RuntimeError("invalid pattern: %s" % pattern) if not otable and isinstance(queries,dict): dbset = db(queries[table]) if basequery is not None: dbset = dbset(basequery) dbset=dbset(query) else: raise RuntimeError("missing relation in pattern: %s" % pattern) elif re2.match(tag) and args[i]==tag[:tag.find('[')]: ref = tag[tag.find('[')+1:-1] if '.' in ref and otable: table,field = ref.split('.') selfld = '_id' if db[table][field].type.startswith('reference '): refs = [ x.name for x in db[otable] if x.type == db[table][field].type ] else: refs = [ x.name for x in db[table]._referenced_by if x.tablename==otable ] if refs: selfld = refs[0] if nested_select: try: dbset=db(db[table][field].belongs(dbset._select(db[otable][selfld]))) except ValueError: return Row({'status':400,'pattern':pattern, 'error':'invalid path','response':None}) else: items = [item.id for item in dbset.select(db[otable][selfld])] dbset=db(db[table][field].belongs(items)) else: table = ref if not otable and isinstance(queries,dict): dbset = db(queries[table]) dbset=dbset(db[table]) elif tag==':field' and table: # print 're3:'+tag field = args[i] if not field in db[table]: break # hand-built patterns should respect .readable=False as well if not db[table][field].readable: return Row({'status':418,'pattern':pattern, 'error':'I\'m a teapot','response':None}) try: distinct = vars.get('distinct', False) == 'True' offset = long(vars.get('offset',None) or 0) limits = (offset,long(vars.get('limit',None) or 1000)+offset) except ValueError: return Row({'status':400,'error':'invalid limits','response':None}) items = dbset.select(db[table][field], distinct=distinct, limitby=limits) if items: return Row({'status':200,'response':items, 'pattern':pattern}) else: return Row({'status':404,'pattern':pattern, 'error':'no record found','response':None}) elif tag != args[i]: break otable = table i += 1 if i==len(tags) and table: ofields = vars.get('order',db[table]._id.name).split('|') try: orderby = [db[table][f] if not f.startswith('~') else ~db[table][f[1:]] for f in ofields] except (KeyError, AttributeError): return Row({'status':400,'error':'invalid orderby','response':None}) if exposedfields: fields = [field for field in db[table] if str(field).split('.')[-1] in exposedfields and field.readable] else: fields = [field for field in db[table] if field.readable] count = dbset.count() try: offset = long(vars.get('offset',None) or 0) limits = (offset,long(vars.get('limit',None) or 1000)+offset) except ValueError: return Row({'status':400,'error':'invalid limits','response':None}) if count > limits[1]-limits[0]: return Row({'status':400,'error':'too many records','response':None}) try: response = dbset.select(limitby=limits,orderby=orderby,*fields) except ValueError: return Row({'status':400,'pattern':pattern, 'error':'invalid path','response':None}) return Row({'status':200,'response':response, 'pattern':pattern,'count':count}) return Row({'status':400,'error':'no matching pattern','response':None}) def define_table( self, tablename, *fields, **args ): if not isinstance(tablename,str): raise SyntaxError("missing table name") elif hasattr(self,tablename) or tablename in self.tables: if not args.get('redefine',False): raise SyntaxError('table already defined: %s' % tablename) elif tablename.startswith('_') or hasattr(self,tablename) or \ REGEX_PYTHON_KEYWORDS.match(tablename): raise SyntaxError('invalid table name: %s' % tablename) elif self.check_reserved: self.check_reserved_keyword(tablename) else: invalid_args = set(args)-TABLE_ARGS if invalid_args: raise SyntaxError('invalid table "%s" attributes: %s' \ % (tablename,invalid_args)) if self._lazy_tables and not tablename in self._LAZY_TABLES: self._LAZY_TABLES[tablename] = (tablename,fields,args) table = None else: table = self.lazy_define_table(tablename,*fields,**args) if not tablename in self.tables: self.tables.append(tablename) return table def lazy_define_table( self, tablename, *fields, **args ): args_get = args.get common_fields = self._common_fields if common_fields: fields = list(fields) + list(common_fields) table_class = args_get('table_class',Table) table = table_class(self, tablename, *fields, **args) table._actual = True self[tablename] = table # must follow above line to handle self references table._create_references() for field in table: if field.requires == DEFAULT: field.requires = sqlhtml_validators(field) migrate = self._migrate_enabled and args_get('migrate',self._migrate) if migrate and not self._uri in (None,'None') \ or self._adapter.dbengine=='google:datastore': fake_migrate = self._fake_migrate_all or \ args_get('fake_migrate',self._fake_migrate) polymodel = args_get('polymodel',None) try: GLOBAL_LOCKER.acquire() self._lastsql = self._adapter.create_table( table,migrate=migrate, fake_migrate=fake_migrate, polymodel=polymodel) finally: GLOBAL_LOCKER.release() else: table._dbt = None on_define = args_get('on_define',None) if on_define: on_define(table) return table def as_dict(self, flat=False, sanitize=True, field_options=True): dbname = db_uid = uri = None if not sanitize: uri, dbname, db_uid = (self._uri, self._dbname, self._db_uid) db_as_dict = dict(items={}, tables=[], uri=uri, dbname=dbname, db_uid=db_uid, **dict([(k, getattr(self, "_" + k)) for k in 'pool_size','folder','db_codec', 'check_reserved','migrate','fake_migrate', 'migrate_enabled','fake_migrate_all', 'decode_credentials','driver_args', 'adapter_args', 'attempts', 'bigint_id','debug','lazy_tables', 'do_connect'])) for table in self: tablename = str(table) db_as_dict["tables"].append(tablename) db_as_dict["items"][tablename] = table.as_dict(flat=flat, sanitize=sanitize, field_options=field_options) return db_as_dict def as_xml(self, sanitize=True, field_options=True): if not have_serializers: raise ImportError("No xml serializers available") d = self.as_dict(flat=True, sanitize=sanitize, field_options=field_options) return serializers.xml(d) def as_json(self, sanitize=True, field_options=True): if not have_serializers: raise ImportError("No json serializers available") d = self.as_dict(flat=True, sanitize=sanitize, field_options=field_options) return serializers.json(d) def as_yaml(self, sanitize=True, field_options=True): if not have_serializers: raise ImportError("No YAML serializers available") d = self.as_dict(flat=True, sanitize=sanitize, field_options=field_options) return serializers.yaml(d) def __contains__(self, tablename): try: return tablename in self.tables except AttributeError: # The instance has no .tables attribute yet return False has_key = __contains__ def get(self,key,default=None): return self.__dict__.get(key,default) def __iter__(self): for tablename in self.tables: yield self[tablename] def __getitem__(self, key): return self.__getattr__(str(key)) def __getattr__(self, key): if ogetattr(self,'_lazy_tables') and \ key in ogetattr(self,'_LAZY_TABLES'): tablename, fields, args = self._LAZY_TABLES.pop(key) return self.lazy_define_table(tablename,*fields,**args) return ogetattr(self, key) def __setitem__(self, key, value): osetattr(self, str(key), value) def __setattr__(self, key, value): if key[:1]!='_' and key in self: raise SyntaxError( 'Object %s exists and cannot be redefined' % key) osetattr(self,key,value) __delitem__ = object.__delattr__ def __repr__(self): if hasattr(self,'_uri'): return '<DAL uri="%s">' % hide_password(str(self._uri)) else: return '<DAL db_uid="%s">' % self._db_uid def smart_query(self,fields,text): return Set(self, smart_query(fields,text)) def __call__(self, query=None, ignore_common_filters=None): if isinstance(query,Table): query = self._adapter.id_query(query) elif isinstance(query,Field): query = query!=None elif isinstance(query, dict): icf = query.get("ignore_common_filters") if icf: ignore_common_filters = icf return Set(self, query, ignore_common_filters=ignore_common_filters) def commit(self): self._adapter.commit() def rollback(self): self._adapter.rollback() def close(self): self._adapter.close() if self._db_uid in THREAD_LOCAL.db_instances: db_group = THREAD_LOCAL.db_instances[self._db_uid] db_group.remove(self) if not db_group: del THREAD_LOCAL.db_instances[self._db_uid] def executesql(self, query, placeholders=None, as_dict=False, fields=None, colnames=None): """ placeholders is optional and will always be None. If using raw SQL with placeholders, placeholders may be a sequence of values to be substituted in or, (if supported by the DB driver), a dictionary with keys matching named placeholders in your SQL. Added 2009-12-05 "as_dict" optional argument. Will always be None when using DAL. If using raw SQL can be set to True and the results cursor returned by the DB driver will be converted to a sequence of dictionaries keyed with the db field names. Tested with SQLite but should work with any database since the cursor.description used to get field names is part of the Python dbi 2.0 specs. Results returned with as_dict=True are the same as those returned when applying .to_list() to a DAL query. [{field1: value1, field2: value2}, {field1: value1b, field2: value2b}] Added 2012-08-24 "fields" and "colnames" optional arguments. If either is provided, the results cursor returned by the DB driver will be converted to a DAL Rows object using the db._adapter.parse() method. The "fields" argument is a list of DAL Field objects that match the fields returned from the DB. The Field objects should be part of one or more Table objects defined on the DAL object. The "fields" list can include one or more DAL Table objects in addition to or instead of including Field objects, or it can be just a single table (not in a list). In that case, the Field objects will be extracted from the table(s). Instead of specifying the "fields" argument, the "colnames" argument can be specified as a list of field names in tablename.fieldname format. Again, these should represent tables and fields defined on the DAL object. It is also possible to specify both "fields" and the associated "colnames". In that case, "fields" can also include DAL Expression objects in addition to Field objects. For Field objects in "fields", the associated "colnames" must still be in tablename.fieldname format. For Expression objects in "fields", the associated "colnames" can be any arbitrary labels. Note, the DAL Table objects referred to by "fields" or "colnames" can be dummy tables and do not have to represent any real tables in the database. Also, note that the "fields" and "colnames" must be in the same order as the fields in the results cursor returned from the DB. """ adapter = self._adapter if placeholders: adapter.execute(query, placeholders) else: adapter.execute(query) if as_dict: if not hasattr(adapter.cursor,'description'): raise RuntimeError("database does not support executesql(...,as_dict=True)") # Non-DAL legacy db query, converts cursor results to dict. # sequence of 7-item sequences. each sequence tells about a column. # first item is always the field name according to Python Database API specs columns = adapter.cursor.description # reduce the column info down to just the field names fields = [f[0] for f in columns] # will hold our finished resultset in a list data = adapter._fetchall() # convert the list for each row into a dictionary so it's # easier to work with. row['field_name'] rather than row[0] return [dict(zip(fields,row)) for row in data] try: data = adapter._fetchall() except: return None if fields or colnames: fields = [] if fields is None else fields if not isinstance(fields, list): fields = [fields] extracted_fields = [] for field in fields: if isinstance(field, Table): extracted_fields.extend([f for f in field]) else: extracted_fields.append(field) if not colnames: colnames = ['%s.%s' % (f.tablename, f.name) for f in extracted_fields] data = adapter.parse( data, fields=extracted_fields, colnames=colnames) return data def _remove_references_to(self, thistable): for table in self: table._referenced_by = [field for field in table._referenced_by if not field.table==thistable] def export_to_csv_file(self, ofile, *args, **kwargs): step = long(kwargs.get('max_fetch_rows,',500)) write_colnames = kwargs['write_colnames'] = \ kwargs.get("write_colnames", True) for table in self.tables: ofile.write('TABLE %s\r\n' % table) query = self._adapter.id_query(self[table]) nrows = self(query).count() kwargs['write_colnames'] = write_colnames for k in range(0,nrows,step): self(query).select(limitby=(k,k+step)).export_to_csv_file( ofile, *args, **kwargs) kwargs['write_colnames'] = False ofile.write('\r\n\r\n') ofile.write('END') def import_from_csv_file(self, ifile, id_map=None, null='<NULL>', unique='uuid', map_tablenames=None, ignore_missing_tables=False, *args, **kwargs): #if id_map is None: id_map={} id_offset = {} # only used if id_map is None map_tablenames = map_tablenames or {} for line in ifile: line = line.strip() if not line: continue elif line == 'END': return elif not line.startswith('TABLE ') or \ not line[6:] in self.tables: raise SyntaxError('invalid file format') else: tablename = line[6:] tablename = map_tablenames.get(tablename,tablename) if tablename is not None and tablename in self.tables: self[tablename].import_from_csv_file( ifile, id_map, null, unique, id_offset, *args, **kwargs) elif tablename is None or ignore_missing_tables: # skip all non-empty lines for line in ifile: if not line.strip(): breal else: raise RuntimeError("Unable to import table that does not exist.\nTry db.import_from_csv_file(..., map_tablenames={'table':'othertable'},ignore_missing_tables=True)") def DAL_unpickler(db_uid): return DAL('<zombie>',db_uid=db_uid) def DAL_pickler(db): return DAL_unpickler, (db._db_uid,) copyreg.pickle(DAL, DAL_pickler, DAL_unpickler) class SQLALL(object): """ Helper class providing a comma-separated string having all the field names (prefixed by table name and '.') normally only called from within gluon.sql """ def __init__(self, table): self._table = table def __str__(self): return ', '.join([str(field) for field in self._table]) # class Reference(int): class Reference(long): def __allocate(self): if not self._record: self._record = self._table[long(self)] if not self._record: raise RuntimeError( "Using a recursive select but encountered a broken reference: %s %d"%(self._table, long(self))) def __getattr__(self, key): if key == 'id': return long(self) self.__allocate() return self._record.get(key, None) def get(self, key, default=None): return self.__getattr__(key, default) def __setattr__(self, key, value): if key.startswith('_'): long.__setattr__(self, key, value) return self.__allocate() self._record[key] = value def __getitem__(self, key): if key == 'id': return long(self) self.__allocate() return self._record.get(key, None) def __setitem__(self,key,value): self.__allocate() self._record[key] = value def Reference_unpickler(data): return marshal.loads(data) def Reference_pickler(data): try: marshal_dump = marshal.dumps(long(data)) except AttributeError: marshal_dump = 'i%s' % struct.pack('<i', long(data)) return (Reference_unpickler, (marshal_dump,)) copyreg.pickle(Reference, Reference_pickler, Reference_unpickler) class MethodAdder(object): def __init__(self,table): self.table = table def __call__(self): return self.register() def __getattr__(self,method_name): return self.register(method_name) def register(self,method_name=None): def _decorated(f): instance = self.table import types method = types.MethodType(f, instance, instance.__class__) name = method_name or f.func_name setattr(instance, name, method) return f return _decorated class Table(object): """ an instance of this class represents a database table Example:: db = DAL(...) db.define_table('users', Field('name')) db.users.insert(name='me') # print db.users._insert(...) to see SQL db.users.drop() """ def __init__( self, db, tablename, *fields, **args ): """ Initializes the table and performs checking on the provided fields. Each table will have automatically an 'id'. If a field is of type Table, the fields (excluding 'id') from that table will be used instead. :raises SyntaxError: when a supplied field is of incorrect type. """ self._actual = False # set to True by define_table() self._tablename = tablename self._ot = args.get('actual_name') self._sequence_name = args.get('sequence_name') or \ db and db._adapter.sequence_name(tablename) self._trigger_name = args.get('trigger_name') or \ db and db._adapter.trigger_name(tablename) self._common_filter = args.get('common_filter') self._format = args.get('format') self._singular = args.get( 'singular',tablename.replace('_',' ').capitalize()) self._plural = args.get( 'plural',pluralize(self._singular.lower()).capitalize()) # horrible but for backard compatibility of appamdin: if 'primarykey' in args and args['primarykey'] is not None: self._primarykey = args.get('primarykey') self._before_insert = [] self._before_update = [Set.delete_uploaded_files] self._before_delete = [Set.delete_uploaded_files] self._after_insert = [] self._after_update = [] self._after_delete = [] self.add_method = MethodAdder(self) fieldnames,newfields=set(),[] if hasattr(self,'_primarykey'): if not isinstance(self._primarykey,list): raise SyntaxError( "primarykey must be a list of fields from table '%s'" \ % tablename) if len(self._primarykey)==1: self._id = [f for f in fields if isinstance(f,Field) \ and f.name==self._primarykey[0]][0] elif not [f for f in fields if isinstance(f,Field) and f.type=='id']: field = Field('id', 'id') newfields.append(field) fieldnames.add('id') self._id = field virtual_fields = [] for field in fields: if isinstance(field, (FieldMethod, FieldVirtual)): virtual_fields.append(field) elif isinstance(field, Field) and not field.name in fieldnames: if field.db is not None: field = copy.copy(field) newfields.append(field) fieldnames.add(field.name) if field.type=='id': self._id = field elif isinstance(field, Table): table = field for field in table: if not field.name in fieldnames and not field.type=='id': t2 = not table._actual and self._tablename field = field.clone(point_self_references_to=t2) newfields.append(field) fieldnames.add(field.name) elif not isinstance(field, (Field, Table)): raise SyntaxError( 'define_table argument is not a Field or Table: %s' % field) fields = newfields self._db = db tablename = tablename self._fields = SQLCallableList() self.virtualfields = [] fields = list(fields) if db and db._adapter.uploads_in_blob==True: uploadfields = [f.name for f in fields if f.type=='blob'] for field in fields: fn = field.uploadfield if isinstance(field, Field) and field.type == 'upload'\ and fn is True: fn = field.uploadfield = '%s_blob' % field.name if isinstance(fn,str) and not fn in uploadfields: fields.append(Field(fn,'blob',default='', writable=False,readable=False)) lower_fieldnames = set() reserved = dir(Table) + ['fields'] for field in fields: field_name = field.name if db and db.check_reserved: db.check_reserved_keyword(field_name) elif field_name in reserved: raise SyntaxError("field name %s not allowed" % field_name) if field_name.lower() in lower_fieldnames: raise SyntaxError("duplicate field %s in table %s" \ % (field_name, tablename)) else: lower_fieldnames.add(field_name.lower()) self.fields.append(field_name) self[field_name] = field if field.type == 'id': self['id'] = field field.tablename = field._tablename = tablename field.table = field._table = self field.db = field._db = db self.ALL = SQLALL(self) if hasattr(self,'_primarykey'): for k in self._primarykey: if k not in self.fields: raise SyntaxError( "primarykey must be a list of fields from table '%s " % tablename) else: self[k].notnull = True for field in virtual_fields: self[field.name] = field @property def fields(self): return self._fields def update(self,*args,**kwargs): raise RuntimeError("Syntax Not Supported") def _enable_record_versioning(self, archive_db=None, archive_name = '%(tablename)s_archive', current_record = 'current_record', is_active = 'is_active'): archive_db = archive_db or self._db archive_name = archive_name % dict(tablename=self._tablename) if archive_name in archive_db.tables(): return # do not try define the archive if already exists fieldnames = self.fields() same_db = archive_db is self._db field_type = self if same_db else 'bigint' clones = [] for field in self: clones.append(field.clone( unique=False, type=field.type if same_db else 'bigint')) archive_db.define_table( archive_name, Field(current_record,field_type), *clones) self._before_update.append( lambda qset,fs,db=archive_db,an=archive_name,cn=current_record: archive_record(qset,fs,db[an],cn)) if is_active and is_active in fieldnames: self._before_delete.append( lambda qset: qset.update(is_active=False)) newquery = lambda query, t=self: t.is_active == True query = self._common_filter if query: newquery = query & newquery self._common_filter = newquery def _validate(self,**vars): errors = Row() for key,value in vars.iteritems(): value,error = self[key].validate(value) if error: errors[key] = error return errors def _create_references(self): db = self._db pr = db._pending_references self._referenced_by = [] for field in self: fieldname = field.name field_type = field.type if isinstance(field_type,str) and field_type[:10] == 'reference ': ref = field_type[10:].strip() if not ref.split(): raise SyntaxError('Table: reference to nothing: %s' %ref) refs = ref.split('.') rtablename = refs[0] if not rtablename in db: pr[rtablename] = pr.get(rtablename,[]) + [field] continue rtable = db[rtablename] if len(refs)==2: rfieldname = refs[1] if not hasattr(rtable,'_primarykey'): raise SyntaxError( 'keyed tables can only reference other keyed tables (for now)') if rfieldname not in rtable.fields: raise SyntaxError( "invalid field '%s' for referenced table '%s' in table '%s'" \ % (rfieldname, rtablename, self._tablename)) rtable._referenced_by.append(field) for referee in pr.get(self._tablename,[]): self._referenced_by.append(referee) def _filter_fields(self, record, id=False): return dict([(k, v) for (k, v) in record.iteritems() if k in self.fields and (self[k].type!='id' or id)]) def _build_query(self,key): """ for keyed table only """ query = None for k,v in key.iteritems(): if k in self._primarykey: if query: query = query & (self[k] == v) else: query = (self[k] == v) else: raise SyntaxError( 'Field %s is not part of the primary key of %s' % \ (k,self._tablename)) return query def __getitem__(self, key): if not key: return None elif isinstance(key, dict): """ for keyed table """ query = self._build_query(key) rows = self._db(query).select() if rows: return rows[0] return None elif str(key).isdigit() or 'google' in DRIVERS and isinstance(key, Key): return self._db(self._id == key).select(limitby=(0,1), orderby_on_limitby=False).first() elif key: return ogetattr(self, str(key)) def __call__(self, key=DEFAULT, **kwargs): for_update = kwargs.get('_for_update',False) if '_for_update' in kwargs: del kwargs['_for_update'] orderby = kwargs.get('_orderby',None) if '_orderby' in kwargs: del kwargs['_orderby'] if not key is DEFAULT: if isinstance(key, Query): record = self._db(key).select( limitby=(0,1),for_update=for_update, orderby=orderby, orderby_on_limitby=False).first() elif not str(key).isdigit(): record = None else: record = self._db(self._id == key).select( limitby=(0,1),for_update=for_update, orderby=orderby, orderby_on_limitby=False).first() if record: for k,v in kwargs.iteritems(): if record[k]!=v: return None return record elif kwargs: query = reduce(lambda a,b:a&b,[self[k]==v for k,v in kwargs.iteritems()]) return self._db(query).select(limitby=(0,1),for_update=for_update, orderby=orderby, orderby_on_limitby=False).first() else: return None def __setitem__(self, key, value): if isinstance(key, dict) and isinstance(value, dict): """ option for keyed table """ if set(key.keys()) == set(self._primarykey): value = self._filter_fields(value) kv = {} kv.update(value) kv.update(key) if not self.insert(**kv): query = self._build_query(key) self._db(query).update(**self._filter_fields(value)) else: raise SyntaxError( 'key must have all fields from primary key: %s'%\ (self._primarykey)) elif str(key).isdigit(): if key == 0: self.insert(**self._filter_fields(value)) elif self._db(self._id == key)\ .update(**self._filter_fields(value)) is None: raise SyntaxError('No such record: %s' % key) else: if isinstance(key, dict): raise SyntaxError( 'value must be a dictionary: %s' % value) osetattr(self, str(key), value) __getattr__ = __getitem__ def __setattr__(self, key, value): if key[:1]!='_' and key in self: raise SyntaxError('Object exists and cannot be redefined: %s' % key) osetattr(self,key,value) def __delitem__(self, key): if isinstance(key, dict): query = self._build_query(key) if not self._db(query).delete(): raise SyntaxError('No such record: %s' % key) elif not str(key).isdigit() or \ not self._db(self._id == key).delete(): raise SyntaxError('No such record: %s' % key) def __contains__(self,key): return hasattr(self,key) has_key = __contains__ def items(self): return self.__dict__.items() def __iter__(self): for fieldname in self.fields: yield self[fieldname] def iteritems(self): return self.__dict__.iteritems() def __repr__(self): return '<Table %s (%s)>' % (self._tablename,','.join(self.fields())) def __str__(self): if self._ot is not None: ot = self._db._adapter.QUOTE_TEMPLATE % self._ot if 'Oracle' in str(type(self._db._adapter)): return '%s %s' % (ot, self._tablename) return '%s AS %s' % (ot, self._tablename) return self._tablename def _drop(self, mode = ''): return self._db._adapter._drop(self, mode) def drop(self, mode = ''): return self._db._adapter.drop(self,mode) def _listify(self,fields,update=False): new_fields = {} # format: new_fields[name] = (field,value) # store all fields passed as input in new_fields for name in fields: if not name in self.fields: if name != 'id': raise SyntaxError( 'Field %s does not belong to the table' % name) else: field = self[name] value = fields[name] if field.filter_in: value = field.filter_in(value) new_fields[name] = (field,value) # check all fields that should be in the table but are not passed to_compute = [] for ofield in self: name = ofield.name if not name in new_fields: # if field is supposed to be computed, compute it! if ofield.compute: # save those to compute for later to_compute.append((name,ofield)) # if field is required, check its default value elif not update and not ofield.default is None: value = ofield.default fields[name] = value new_fields[name] = (ofield,value) # if this is an update, user the update field instead elif update and not ofield.update is None: value = ofield.update fields[name] = value new_fields[name] = (ofield,value) # if the field is still not there but it should, error elif not update and ofield.required: raise RuntimeError( 'Table: missing required field: %s' % name) # now deal with fields that are supposed to be computed if to_compute: row = Row(fields) for name,ofield in to_compute: # try compute it try: row[name] = new_value = ofield.compute(row) new_fields[name] = (ofield, new_value) except (KeyError, AttributeError): # error silently unless field is required! if ofield.required: raise SyntaxError('unable to compute field: %s' % name) return new_fields.values() def _attempt_upload(self, fields): for field in self: if field.type=='upload' and field.name in fields: value = fields[field.name] if value and not isinstance(value,str): if hasattr(value,'file') and hasattr(value,'filename'): new_name = field.store(value.file,filename=value.filename) elif hasattr(value,'read') and hasattr(value,'name'): new_name = field.store(value,filename=value.name) else: raise RuntimeError("Unable to handle upload") fields[field.name] = new_name def _defaults(self, fields): "If there are no fields/values specified, return table defaults" if not fields: fields = {} for field in self: if field.type != "id": fields[field.name] = field.default return fields def _insert(self, **fields): fields = self._defaults(fields) return self._db._adapter._insert(self, self._listify(fields)) def insert(self, **fields): fields = self._defaults(fields) self._attempt_upload(fields) if any(f(fields) for f in self._before_insert): return 0 ret = self._db._adapter.insert(self, self._listify(fields)) if ret and self._after_insert: fields = Row(fields) [f(fields,ret) for f in self._after_insert] return ret def validate_and_insert(self,**fields): response = Row() response.errors = Row() new_fields = copy.copy(fields) for key,value in fields.iteritems(): value,error = self[key].validate(value) if error: response.errors[key] = "%s" % error else: new_fields[key] = value if not response.errors: response.id = self.insert(**new_fields) else: response.id = None return response def update_or_insert(self, _key=DEFAULT, **values): if _key is DEFAULT: record = self(**values) elif isinstance(_key,dict): record = self(**_key) else: record = self(_key) if record: record.update_record(**values) newid = None else: newid = self.insert(**values) return newid def bulk_insert(self, items): """ here items is a list of dictionaries """ items = [self._listify(item) for item in items] if any(f(item) for item in items for f in self._before_insert):return 0 ret = self._db._adapter.bulk_insert(self,items) ret and [[f(item,ret[k]) for k,item in enumerate(items)] for f in self._after_insert] return ret def _truncate(self, mode = None): return self._db._adapter._truncate(self, mode) def truncate(self, mode = None): return self._db._adapter.truncate(self, mode) def import_from_csv_file( self, csvfile, id_map=None, null='<NULL>', unique='uuid', id_offset=None, # id_offset used only when id_map is None *args, **kwargs ): """ Import records from csv file. Column headers must have same names as table fields. Field 'id' is ignored. If column names read 'table.file' the 'table.' prefix is ignored. 'unique' argument is a field which must be unique (typically a uuid field) 'restore' argument is default False; if set True will remove old values in table first. 'id_map' ff set to None will not map ids. The import will keep the id numbers in the restored table. This assumes that there is an field of type id that is integer and in incrementing order. Will keep the id numbers in restored table. """ delimiter = kwargs.get('delimiter', ',') quotechar = kwargs.get('quotechar', '"') quoting = kwargs.get('quoting', csv.QUOTE_MINIMAL) restore = kwargs.get('restore', False) if restore: self._db[self].truncate() reader = csv.reader(csvfile, delimiter=delimiter, quotechar=quotechar, quoting=quoting) colnames = None if isinstance(id_map, dict): if not self._tablename in id_map: id_map[self._tablename] = {} id_map_self = id_map[self._tablename] def fix(field, value, id_map, id_offset): list_reference_s='list:reference' if value == null: value = None elif field.type=='blob': value = base64.b64decode(value) elif field.type=='double' or field.type=='float': if not value.strip(): value = None else: value = float(value) elif field.type in ('integer','bigint'): if not value.strip(): value = None else: value = long(value) elif field.type.startswith('list:string'): value = bar_decode_string(value) elif field.type.startswith(list_reference_s): ref_table = field.type[len(list_reference_s):].strip() if id_map is not None: value = [id_map[ref_table][long(v)] \ for v in bar_decode_string(value)] else: value = [v for v in bar_decode_string(value)] elif field.type.startswith('list:'): value = bar_decode_integer(value) elif id_map and field.type.startswith('reference'): try: value = id_map[field.type[9:].strip()][long(value)] except KeyError: pass elif id_offset and field.type.startswith('reference'): try: value = id_offset[field.type[9:].strip()]+long(value) except KeyError: pass return (field.name, value) def is_id(colname): if colname in self: return self[colname].type == 'id' else: return False first = True unique_idx = None for line in reader: if not line: break if not colnames: colnames = [x.split('.',1)[-1] for x in line][:len(line)] cols, cid = [], None for i,colname in enumerate(colnames): if is_id(colname): cid = i else: cols.append(i) if colname == unique: unique_idx = i else: items = [fix(self[colnames[i]], line[i], id_map, id_offset) \ for i in cols if colnames[i] in self.fields] if not id_map and cid is not None and id_offset is not None and not unique_idx: csv_id = long(line[cid]) curr_id = self.insert(**dict(items)) if first: first = False # First curr_id is bigger than csv_id, # then we are not restoring but # extending db table with csv db table if curr_id>csv_id: id_offset[self._tablename] = curr_id-csv_id else: id_offset[self._tablename] = 0 # create new id until we get the same as old_id+offset while curr_id<csv_id+id_offset[self._tablename]: self._db(self._db[self][colnames[cid]] == curr_id).delete() curr_id = self.insert(**dict(items)) # Validation. Check for duplicate of 'unique' &, # if present, update instead of insert. elif not unique_idx: new_id = self.insert(**dict(items)) else: unique_value = line[unique_idx] query = self._db[self][unique] == unique_value record = self._db(query).select().first() if record: record.update_record(**dict(items)) new_id = record[self._id.name] else: new_id = self.insert(**dict(items)) if id_map and cid is not None: id_map_self[long(line[cid])] = new_id def as_dict(self, flat=False, sanitize=True, field_options=True): tablename = str(self) table_as_dict = dict(name=tablename, items={}, fields=[], sequence_name=self._sequence_name, trigger_name=self._trigger_name, common_filter=self._common_filter, format=self._format, singular=self._singular, plural=self._plural) for field in self: if (field.readable or field.writable) or (not sanitize): table_as_dict["fields"].append(field.name) table_as_dict["items"][field.name] = \ field.as_dict(flat=flat, sanitize=sanitize, options=field_options) return table_as_dict def as_xml(self, sanitize=True, field_options=True): if not have_serializers: raise ImportError("No xml serializers available") d = self.as_dict(flat=True, sanitize=sanitize, field_options=field_options) return serializers.xml(d) def as_json(self, sanitize=True, field_options=True): if not have_serializers: raise ImportError("No json serializers available") d = self.as_dict(flat=True, sanitize=sanitize, field_options=field_options) return serializers.json(d) def as_yaml(self, sanitize=True, field_options=True): if not have_serializers: raise ImportError("No YAML serializers available") d = self.as_dict(flat=True, sanitize=sanitize, field_options=field_options) return serializers.yaml(d) def with_alias(self, alias): return self._db._adapter.alias(self,alias) def on(self, query): return Expression(self._db,self._db._adapter.ON,self,query) def archive_record(qset,fs,archive_table,current_record): tablenames = qset.db._adapter.tables(qset.query) if len(tablenames)!=1: raise RuntimeError("cannot update join") table = qset.db[tablenames[0]] for row in qset.select(): fields = archive_table._filter_fields(row) fields[current_record] = row.id archive_table.insert(**fields) return False class Expression(object): def __init__( self, db, op, first=None, second=None, type=None, **optional_args ): self.db = db self.op = op self.first = first self.second = second self._table = getattr(first,'_table',None) ### self._tablename = first._tablename ## CHECK if not type and first and hasattr(first,'type'): self.type = first.type else: self.type = type self.optional_args = optional_args def sum(self): db = self.db return Expression(db, db._adapter.AGGREGATE, self, 'SUM', self.type) def max(self): db = self.db return Expression(db, db._adapter.AGGREGATE, self, 'MAX', self.type) def min(self): db = self.db return Expression(db, db._adapter.AGGREGATE, self, 'MIN', self.type) def len(self): db = self.db return Expression(db, db._adapter.LENGTH, self, None, 'integer') def avg(self): db = self.db return Expression(db, db._adapter.AGGREGATE, self, 'AVG', self.type) def abs(self): db = self.db return Expression(db, db._adapter.AGGREGATE, self, 'ABS', self.type) def lower(self): db = self.db return Expression(db, db._adapter.LOWER, self, None, self.type) def upper(self): db = self.db return Expression(db, db._adapter.UPPER, self, None, self.type) def replace(self,a,b): db = self.db return Expression(db, db._adapter.REPLACE, self, (a,b), self.type) def year(self): db = self.db return Expression(db, db._adapter.EXTRACT, self, 'year', 'integer') def month(self): db = self.db return Expression(db, db._adapter.EXTRACT, self, 'month', 'integer') def day(self): db = self.db return Expression(db, db._adapter.EXTRACT, self, 'day', 'integer') def hour(self): db = self.db return Expression(db, db._adapter.EXTRACT, self, 'hour', 'integer') def minutes(self): db = self.db return Expression(db, db._adapter.EXTRACT, self, 'minute', 'integer') def coalesce(self,*others): db = self.db return Expression(db, db._adapter.COALESCE, self, others, self.type) def coalesce_zero(self): db = self.db return Expression(db, db._adapter.COALESCE_ZERO, self, None, self.type) def seconds(self): db = self.db return Expression(db, db._adapter.EXTRACT, self, 'second', 'integer') def epoch(self): db = self.db return Expression(db, db._adapter.EPOCH, self, None, 'integer') def __getslice__(self, start, stop): db = self.db if start < 0: pos0 = '(%s - %d)' % (self.len(), abs(start) - 1) else: pos0 = start + 1 if stop < 0: length = '(%s - %d - %s)' % (self.len(), abs(stop) - 1, pos0) elif stop == sys.maxint: length = self.len() else: length = '(%s - %s)' % (stop + 1, pos0) return Expression(db,db._adapter.SUBSTRING, self, (pos0, length), self.type) def __getitem__(self, i): return self[i:i + 1] def __str__(self): return self.db._adapter.expand(self,self.type) def __or__(self, other): # for use in sortby db = self.db return Expression(db,db._adapter.COMMA,self,other,self.type) def __invert__(self): db = self.db if hasattr(self,'_op') and self.op == db._adapter.INVERT: return self.first return Expression(db,db._adapter.INVERT,self,type=self.type) def __add__(self, other): db = self.db return Expression(db,db._adapter.ADD,self,other,self.type) def __sub__(self, other): db = self.db if self.type in ('integer','bigint'): result_type = 'integer' elif self.type in ['date','time','datetime','double','float']: result_type = 'double' elif self.type.startswith('decimal('): result_type = self.type else: raise SyntaxError("subtraction operation not supported for type") return Expression(db,db._adapter.SUB,self,other,result_type) def __mul__(self, other): db = self.db return Expression(db,db._adapter.MUL,self,other,self.type) def __div__(self, other): db = self.db return Expression(db,db._adapter.DIV,self,other,self.type) def __mod__(self, other): db = self.db return Expression(db,db._adapter.MOD,self,other,self.type) def __eq__(self, value): db = self.db return Query(db, db._adapter.EQ, self, value) def __ne__(self, value): db = self.db return Query(db, db._adapter.NE, self, value) def __lt__(self, value): db = self.db return Query(db, db._adapter.LT, self, value) def __le__(self, value): db = self.db return Query(db, db._adapter.LE, self, value) def __gt__(self, value): db = self.db return Query(db, db._adapter.GT, self, value) def __ge__(self, value): db = self.db return Query(db, db._adapter.GE, self, value) def like(self, value, case_sensitive=False): db = self.db op = case_sensitive and db._adapter.LIKE or db._adapter.ILIKE return Query(db, op, self, value) def regexp(self, value): db = self.db return Query(db, db._adapter.REGEXP, self, value) def belongs(self, *value): """ Accepts the following inputs: field.belongs(1,2) field.belongs((1,2)) field.belongs(query) Does NOT accept: field.belongs(1) """ db = self.db if len(value) == 1: value = value[0] if isinstance(value,Query): value = db(value)._select(value.first._table._id) return Query(db, db._adapter.BELONGS, self, value) def startswith(self, value): db = self.db if not self.type in ('string', 'text', 'json'): raise SyntaxError("startswith used with incompatible field type") return Query(db, db._adapter.STARTSWITH, self, value) def endswith(self, value): db = self.db if not self.type in ('string', 'text', 'json'): raise SyntaxError("endswith used with incompatible field type") return Query(db, db._adapter.ENDSWITH, self, value) def contains(self, value, all=False, case_sensitive=False): """ The case_sensitive parameters is only useful for PostgreSQL For other RDMBs it is ignored and contains is always case in-sensitive For MongoDB and GAE contains is always case sensitive """ db = self.db if isinstance(value,(list, tuple)): subqueries = [self.contains(str(v).strip(),case_sensitive=case_sensitive) for v in value if str(v).strip()] if not subqueries: return self.contains('') else: return reduce(all and AND or OR,subqueries) if not self.type in ('string', 'text', 'json') and not self.type.startswith('list:'): raise SyntaxError("contains used with incompatible field type") return Query(db, db._adapter.CONTAINS, self, value, case_sensitive=case_sensitive) def with_alias(self, alias): db = self.db return Expression(db, db._adapter.AS, self, alias, self.type) # GIS expressions def st_asgeojson(self, precision=15, options=0, version=1): return Expression(self.db, self.db._adapter.ST_ASGEOJSON, self, dict(precision=precision, options=options, version=version), 'string') def st_astext(self): db = self.db return Expression(db, db._adapter.ST_ASTEXT, self, type='string') def st_x(self): db = self.db return Expression(db, db._adapter.ST_X, self, type='string') def st_y(self): db = self.db return Expression(db, db._adapter.ST_Y, self, type='string') def st_distance(self, other): db = self.db return Expression(db,db._adapter.ST_DISTANCE,self,other, 'double') def st_simplify(self, value): db = self.db return Expression(db, db._adapter.ST_SIMPLIFY, self, value, self.type) # GIS queries def st_contains(self, value): db = self.db return Query(db, db._adapter.ST_CONTAINS, self, value) def st_equals(self, value): db = self.db return Query(db, db._adapter.ST_EQUALS, self, value) def st_intersects(self, value): db = self.db return Query(db, db._adapter.ST_INTERSECTS, self, value) def st_overlaps(self, value): db = self.db return Query(db, db._adapter.ST_OVERLAPS, self, value) def st_touches(self, value): db = self.db return Query(db, db._adapter.ST_TOUCHES, self, value) def st_within(self, value): db = self.db return Query(db, db._adapter.ST_WITHIN, self, value) # for use in both Query and sortby class SQLCustomType(object): """ allows defining of custom SQL types Example:: decimal = SQLCustomType( type ='double', native ='integer', encoder =(lambda x: int(float(x) * 100)), decoder = (lambda x: Decimal("0.00") + Decimal(str(float(x)/100)) ) ) db.define_table( 'example', Field('value', type=decimal) ) :param type: the web2py type (default = 'string') :param native: the backend type :param encoder: how to encode the value to store it in the backend :param decoder: how to decode the value retrieved from the backend :param validator: what validators to use ( default = None, will use the default validator for type) """ def __init__( self, type='string', native=None, encoder=None, decoder=None, validator=None, _class=None, ): self.type = type self.native = native self.encoder = encoder or (lambda x: x) self.decoder = decoder or (lambda x: x) self.validator = validator self._class = _class or type def startswith(self, text=None): try: return self.type.startswith(self, text) except TypeError: return False def __getslice__(self, a=0, b=100): return None def __getitem__(self, i): return None def __str__(self): return self._class class FieldVirtual(object): def __init__(self, name, f=None, ftype='string',label=None,table_name=None): # for backward compatibility (self.name, self.f) = (name, f) if f else ('unknown', name) self.type = ftype self.label = label or self.name.capitalize().replace('_',' ') self.represent = lambda v,r:v self.formatter = IDENTITY self.comment = None self.readable = True self.writable = False self.requires = None self.widget = None self.tablename = table_name self.filter_out = None def __str__(self): return '%s.%s' % (self.tablename, self.name) class FieldMethod(object): def __init__(self, name, f=None, handler=None): # for backward compatibility (self.name, self.f) = (name, f) if f else ('unknown', name) self.handler = handler def list_represent(x,r=None): return ', '.join(str(y) for y in x or []) class Field(Expression): Virtual = FieldVirtual Method = FieldMethod Lazy = FieldMethod # for backward compatibility """ an instance of this class represents a database field example:: a = Field(name, 'string', length=32, default=None, required=False, requires=IS_NOT_EMPTY(), ondelete='CASCADE', notnull=False, unique=False, uploadfield=True, widget=None, label=None, comment=None, uploadfield=True, # True means store on disk, # 'a_field_name' means store in this field in db # False means file content will be discarded. writable=True, readable=True, update=None, authorize=None, autodelete=False, represent=None, uploadfolder=None, uploadseparate=False # upload to separate directories by uuid_keys # first 2 character and tablename.fieldname # False - old behavior # True - put uploaded file in # <uploaddir>/<tablename>.<fieldname>/uuid_key[:2] # directory) uploadfs=None # a pyfilesystem where to store upload to be used as argument of DAL.define_table allowed field types: string, boolean, integer, double, text, blob, date, time, datetime, upload, password """ def __init__( self, fieldname, type='string', length=None, default=DEFAULT, required=False, requires=DEFAULT, ondelete='CASCADE', notnull=False, unique=False, uploadfield=True, widget=None, label=None, comment=None, writable=True, readable=True, update=None, authorize=None, autodelete=False, represent=None, uploadfolder=None, uploadseparate=False, uploadfs=None, compute=None, custom_store=None, custom_retrieve=None, custom_retrieve_file_properties=None, custom_delete=None, filter_in = None, filter_out = None, custom_qualifier = None, map_none = None, ): self._db = self.db = None # both for backward compatibility self.op = None self.first = None self.second = None self.name = fieldname = cleanup(fieldname) if not isinstance(fieldname,str) or hasattr(Table,fieldname) or \ fieldname[0] == '_' or REGEX_PYTHON_KEYWORDS.match(fieldname): raise SyntaxError('Field: invalid field name: %s' % fieldname) self.type = type if not isinstance(type, (Table,Field)) else 'reference %s' % type self.length = length if not length is None else DEFAULTLENGTH.get(self.type,512) self.default = default if default!=DEFAULT else (update or None) self.required = required # is this field required self.ondelete = ondelete.upper() # this is for reference fields only self.notnull = notnull self.unique = unique self.uploadfield = uploadfield self.uploadfolder = uploadfolder self.uploadseparate = uploadseparate self.uploadfs = uploadfs self.widget = widget self.comment = comment self.writable = writable self.readable = readable self.update = update self.authorize = authorize self.autodelete = autodelete self.represent = list_represent if \ represent==None and type in ('list:integer','list:string') else represent self.compute = compute self.isattachment = True self.custom_store = custom_store self.custom_retrieve = custom_retrieve self.custom_retrieve_file_properties = custom_retrieve_file_properties self.custom_delete = custom_delete self.filter_in = filter_in self.filter_out = filter_out self.custom_qualifier = custom_qualifier self.label = label if label!=None else fieldname.replace('_',' ').title() self.requires = requires if requires!=None else [] self.map_none = map_none def set_attributes(self,*args,**attributes): self.__dict__.update(*args,**attributes) def clone(self,point_self_references_to=False,**args): field = copy.copy(self) if point_self_references_to and \ field.type == 'reference %s'+field._tablename: field.type = 'reference %s' % point_self_references_to field.__dict__.update(args) return field def store(self, file, filename=None, path=None): if self.custom_store: return self.custom_store(file,filename,path) if isinstance(file, cgi.FieldStorage): filename = filename or file.filename file = file.file elif not filename: filename = file.name filename = os.path.basename(filename.replace('/', os.sep)\ .replace('\\', os.sep)) m = REGEX_STORE_PATTERN.search(filename) extension = m and m.group('e') or 'txt' uuid_key = web2py_uuid().replace('-', '')[-16:] encoded_filename = base64.b16encode(filename).lower() newfilename = '%s.%s.%s.%s' % \ (self._tablename, self.name, uuid_key, encoded_filename) newfilename = newfilename[:(self.length - 1 - len(extension))] + '.' + extension self_uploadfield = self.uploadfield if isinstance(self_uploadfield,Field): blob_uploadfield_name = self_uploadfield.uploadfield keys={self_uploadfield.name: newfilename, blob_uploadfield_name: file.read()} self_uploadfield.table.insert(**keys) elif self_uploadfield == True: if path: pass elif self.uploadfolder: path = self.uploadfolder elif self.db._adapter.folder: path = pjoin(self.db._adapter.folder, '..', 'uploads') else: raise RuntimeError( "you must specify a Field(...,uploadfolder=...)") if self.uploadseparate: if self.uploadfs: raise RuntimeError("not supported") path = pjoin(path,"%s.%s" %(self._tablename, self.name), uuid_key[:2]) if not exists(path): os.makedirs(path) pathfilename = pjoin(path, newfilename) if self.uploadfs: dest_file = self.uploadfs.open(newfilename, 'wb') else: dest_file = open(pathfilename, 'wb') try: shutil.copyfileobj(file, dest_file) except IOError: raise IOError( 'Unable to store file "%s" because invalid permissions, readonly file system, or filename too long' % pathfilename) dest_file.close() return newfilename def retrieve(self, name, path=None, nameonly=False): """ if nameonly==True return (filename, fullfilename) instead of (filename, stream) """ self_uploadfield = self.uploadfield if self.custom_retrieve: return self.custom_retrieve(name, path) import http if self.authorize or isinstance(self_uploadfield, str): row = self.db(self == name).select().first() if not row: raise http.HTTP(404) if self.authorize and not self.authorize(row): raise http.HTTP(403) m = REGEX_UPLOAD_PATTERN.match(name) if not m or not self.isattachment: raise TypeError('Can\'t retrieve %s' % name) file_properties = self.retrieve_file_properties(name,path) filename = file_properties['filename'] if isinstance(self_uploadfield, str): # ## if file is in DB stream = StringIO.StringIO(row[self_uploadfield] or '') elif isinstance(self_uploadfield,Field): blob_uploadfield_name = self_uploadfield.uploadfield query = self_uploadfield == name data = self_uploadfield.table(query)[blob_uploadfield_name] stream = StringIO.StringIO(data) elif self.uploadfs: # ## if file is on pyfilesystem stream = self.uploadfs.open(name, 'rb') else: # ## if file is on regular filesystem # this is intentially a sting with filename and not a stream # this propagates and allows stream_file_or_304_or_206 to be called fullname = pjoin(file_properties['path'],name) if nameonly: return (filename, fullname) stream = open(fullname,'rb') return (filename, stream) def retrieve_file_properties(self, name, path=None): self_uploadfield = self.uploadfield if self.custom_retrieve_file_properties: return self.custom_retrieve_file_properties(name, path) try: m = REGEX_UPLOAD_PATTERN.match(name) if not m or not self.isattachment: raise TypeError('Can\'t retrieve %s file properties' % name) filename = base64.b16decode(m.group('name'), True) filename = REGEX_CLEANUP_FN.sub('_', filename) except (TypeError, AttributeError): filename = name if isinstance(self_uploadfield, str): # ## if file is in DB return dict(path=None,filename=filename) elif isinstance(self_uploadfield,Field): return dict(path=None,filename=filename) else: # ## if file is on filesystem if path: pass elif self.uploadfolder: path = self.uploadfolder else: path = pjoin(self.db._adapter.folder, '..', 'uploads') if self.uploadseparate: t = m.group('table') f = m.group('field') u = m.group('uuidkey') path = pjoin(path,"%s.%s" % (t,f),u[:2]) return dict(path=path,filename=filename) def formatter(self, value): requires = self.requires if value is None or not requires: return value or self.map_none if not isinstance(requires, (list, tuple)): requires = [requires] elif isinstance(requires, tuple): requires = list(requires) else: requires = copy.copy(requires) requires.reverse() for item in requires: if hasattr(item, 'formatter'): value = item.formatter(value) return value def validate(self, value): if not self.requires or self.requires == DEFAULT: return ((value if value!=self.map_none else None), None) requires = self.requires if not isinstance(requires, (list, tuple)): requires = [requires] for validator in requires: (value, error) = validator(value) if error: return (value, error) return ((value if value!=self.map_none else None), None) def count(self, distinct=None): return Expression(self.db, self.db._adapter.COUNT, self, distinct, 'integer') def as_dict(self, flat=False, sanitize=True, options=True): attrs = ('type', 'length', 'default', 'required', 'ondelete', 'notnull', 'unique', 'uploadfield', 'widget', 'label', 'comment', 'writable', 'readable', 'update', 'authorize', 'autodelete', 'represent', 'uploadfolder', 'uploadseparate', 'uploadfs', 'compute', 'custom_store', 'custom_retrieve', 'custom_retrieve_file_properties', 'custom_delete', 'filter_in', 'filter_out', 'custom_qualifier', 'map_none', 'name') SERIALIZABLE_TYPES = (int, long, basestring, dict, list, float, tuple, bool, type(None)) def flatten(obj): if flat: if isinstance(obj, flatten.__class__): return str(type(obj)) elif isinstance(obj, type): try: return str(obj).split("'")[1] except IndexError: return str(obj) elif not isinstance(obj, SERIALIZABLE_TYPES): return str(obj) elif isinstance(obj, dict): newobj = dict() for k, v in obj.items(): newobj[k] = flatten(v) return newobj elif isinstance(obj, (list, tuple, set)): return [flatten(v) for v in obj] else: return obj elif isinstance(obj, (dict, set)): return obj.copy() else: return obj def filter_requires(t, r, options=True): if sanitize and any([keyword in str(t).upper() for keyword in ("CRYPT", "IS_STRONG")]): return None if not isinstance(r, dict): if options and hasattr(r, "options"): if callable(r.options): r.options() newr = r.__dict__.copy() else: newr = r.copy() # remove options if not required if not options and newr.has_key("labels"): [newr.update({key:None}) for key in ("labels", "theset") if (key in newr)] for k, v in newr.items(): if k == "other": if isinstance(v, dict): otype, other = v.popitem() else: otype = flatten(type(v)) other = v newr[k] = {otype: filter_requires(otype, other, options=options)} else: newr[k] = flatten(v) return newr if isinstance(self.requires, (tuple, list, set)): requires = dict([(flatten(type(r)), filter_requires(type(r), r, options=options)) for r in self.requires]) else: requires = {flatten(type(self.requires)): filter_requires(type(self.requires), self.requires, options=options)} d = dict(colname="%s.%s" % (self.tablename, self.name), requires=requires) d.update([(attr, flatten(getattr(self, attr))) for attr in attrs]) return d def as_xml(self, sanitize=True, options=True): if have_serializers: xml = serializers.xml else: raise ImportError("No xml serializers available") d = self.as_dict(flat=True, sanitize=sanitize, options=options) return xml(d) def as_json(self, sanitize=True, options=True): if have_serializers: json = serializers.json else: raise ImportError("No json serializers available") d = self.as_dict(flat=True, sanitize=sanitize, options=options) return json(d) def as_yaml(self, sanitize=True, options=True): if have_serializers: d = self.as_dict(flat=True, sanitize=sanitize, options=options) return serializers.yaml(d) else: raise ImportError("No YAML serializers available") def __nonzero__(self): return True def __str__(self): try: return '%s.%s' % (self.tablename, self.name) except: return '<no table>.%s' % self.name class Query(object): """ a query object necessary to define a set. it can be stored or can be passed to DAL.__call__() to obtain a Set Example:: query = db.users.name=='Max' set = db(query) records = set.select() """ def __init__( self, db, op, first=None, second=None, ignore_common_filters = False, **optional_args ): self.db = self._db = db self.op = op self.first = first self.second = second self.ignore_common_filters = ignore_common_filters self.optional_args = optional_args def __repr__(self): return '<Query %s>' % BaseAdapter.expand(self.db._adapter,self) def __str__(self): return self.db._adapter.expand(self) def __and__(self, other): return Query(self.db,self.db._adapter.AND,self,other) __rand__ = __and__ def __or__(self, other): return Query(self.db,self.db._adapter.OR,self,other) __ror__ = __or__ def __invert__(self): if self.op==self.db._adapter.NOT: return self.first return Query(self.db,self.db._adapter.NOT,self) def __eq__(self, other): return repr(self) == repr(other) def __ne__(self, other): return not (self == other) def case(self,t=1,f=0): return self.db._adapter.CASE(self,t,f) def as_dict(self, flat=False, sanitize=True): """Experimental stuff This allows to return a plain dictionary with the basic query representation. Can be used with json/xml services for client-side db I/O Example: >>> q = db.auth_user.id != 0 >>> q.as_dict(flat=True) {"op": "NE", "first":{"tablename": "auth_user", "fieldname": "id"}, "second":0} """ SERIALIZABLE_TYPES = (tuple, dict, list, int, long, float, basestring, type(None), bool) def loop(d): newd = dict() for k, v in d.items(): if k in ("first", "second"): if isinstance(v, self.__class__): newd[k] = loop(v.__dict__) elif isinstance(v, Field): newd[k] = {"tablename": v._tablename, "fieldname": v.name} elif isinstance(v, Expression): newd[k] = loop(v.__dict__) elif isinstance(v, SERIALIZABLE_TYPES): newd[k] = v elif isinstance(v, (datetime.date, datetime.time, datetime.datetime)): newd[k] = unicode(v) elif k == "op": if callable(v): newd[k] = v.__name__ elif isinstance(v, basestring): newd[k] = v else: pass # not callable or string elif isinstance(v, SERIALIZABLE_TYPES): if isinstance(v, dict): newd[k] = loop(v) else: newd[k] = v return newd if flat: return loop(self.__dict__) else: return self.__dict__ def as_xml(self, sanitize=True): if have_serializers: xml = serializers.xml else: raise ImportError("No xml serializers available") d = self.as_dict(flat=True, sanitize=sanitize) return xml(d) def as_json(self, sanitize=True): if have_serializers: json = serializers.json else: raise ImportError("No json serializers available") d = self.as_dict(flat=True, sanitize=sanitize) return json(d) def xorify(orderby): if not orderby: return None orderby2 = orderby[0] for item in orderby[1:]: orderby2 = orderby2 | item return orderby2 def use_common_filters(query): return (query and hasattr(query,'ignore_common_filters') and \ not query.ignore_common_filters) class Set(object): """ a Set represents a set of records in the database, the records are identified by the query=Query(...) object. normally the Set is generated by DAL.__call__(Query(...)) given a set, for example set = db(db.users.name=='Max') you can: set.update(db.users.name='Massimo') set.delete() # all elements in the set set.select(orderby=db.users.id, groupby=db.users.name, limitby=(0,10)) and take subsets: subset = set(db.users.id<5) """ def __init__(self, db, query, ignore_common_filters = None): self.db = db self._db = db # for backward compatibility self.dquery = None # if query is a dict, parse it if isinstance(query, dict): query = self.parse(query) if not ignore_common_filters is None and \ use_common_filters(query) == ignore_common_filters: query = copy.copy(query) query.ignore_common_filters = ignore_common_filters self.query = query def __repr__(self): return '<Set %s>' % BaseAdapter.expand(self.db._adapter,self.query) def __call__(self, query, ignore_common_filters=False): if query is None: return self elif isinstance(query,Table): query = self.db._adapter.id_query(query) elif isinstance(query,str): query = Expression(self.db,query) elif isinstance(query,Field): query = query!=None if self.query: return Set(self.db, self.query & query, ignore_common_filters=ignore_common_filters) else: return Set(self.db, query, ignore_common_filters=ignore_common_filters) def _count(self,distinct=None): return self.db._adapter._count(self.query,distinct) def _select(self, *fields, **attributes): adapter = self.db._adapter tablenames = adapter.tables(self.query, attributes.get('join',None), attributes.get('left',None), attributes.get('orderby',None), attributes.get('groupby',None)) fields = adapter.expand_all(fields, tablenames) return adapter._select(self.query,fields,attributes) def _delete(self): db = self.db tablename = db._adapter.get_table(self.query) return db._adapter._delete(tablename,self.query) def _update(self, **update_fields): db = self.db tablename = db._adapter.get_table(self.query) fields = db[tablename]._listify(update_fields,update=True) return db._adapter._update(tablename,self.query,fields) def as_dict(self, flat=False, sanitize=True): if flat: uid = dbname = uri = None codec = self.db._db_codec if not sanitize: uri, dbname, uid = (self.db._dbname, str(self.db), self.db._db_uid) d = {"query": self.query.as_dict(flat=flat)} d["db"] = {"uid": uid, "codec": codec, "name": dbname, "uri": uri} return d else: return self.__dict__ def as_xml(self, sanitize=True): if have_serializers: xml = serializers.xml else: raise ImportError("No xml serializers available") d = self.as_dict(flat=True, sanitize=sanitize) return xml(d) def as_json(self, sanitize=True): if have_serializers: json = serializers.json else: raise ImportError("No json serializers available") d = self.as_dict(flat=True, sanitize=sanitize) return json(d) def parse(self, dquery): "Experimental: Turn a dictionary into a Query object" self.dquery = dquery return self.build(self.dquery) def build(self, d): "Experimental: see .parse()" op, first, second = (d["op"], d["first"], d.get("second", None)) left = right = built = None if op in ("AND", "OR"): if not (type(first), type(second)) == (dict, dict): raise SyntaxError("Invalid AND/OR query") if op == "AND": built = self.build(first) & self.build(second) else: built = self.build(first) | self.build(second) elif op == "NOT": if first is None: raise SyntaxError("Invalid NOT query") built = ~self.build(first) else: # normal operation (GT, EQ, LT, ...) for k, v in {"left": first, "right": second}.items(): if isinstance(v, dict) and v.get("op"): v = self.build(v) if isinstance(v, dict) and ("tablename" in v): v = self.db[v["tablename"]][v["fieldname"]] if k == "left": left = v else: right = v if hasattr(self.db._adapter, op): opm = getattr(self.db._adapter, op) if op == "EQ": built = left == right elif op == "NE": built = left != right elif op == "GT": built = left > right elif op == "GE": built = left >= right elif op == "LT": built = left < right elif op == "LE": built = left <= right elif op in ("JOIN", "LEFT_JOIN", "RANDOM", "ALLOW_NULL"): built = Expression(self.db, opm) elif op in ("LOWER", "UPPER", "EPOCH", "PRIMARY_KEY", "COALESCE_ZERO", "RAW", "INVERT"): built = Expression(self.db, opm, left) elif op in ("COUNT", "EXTRACT", "AGGREGATE", "SUBSTRING", "REGEXP", "LIKE", "ILIKE", "STARTSWITH", "ENDSWITH", "ADD", "SUB", "MUL", "DIV", "MOD", "AS", "ON", "COMMA", "NOT_NULL", "COALESCE", "CONTAINS", "BELONGS"): built = Expression(self.db, opm, left, right) # expression as string elif not (left or right): built = Expression(self.db, op) else: raise SyntaxError("Operator not supported: %s" % op) return built def isempty(self): return not self.select(limitby=(0,1), orderby_on_limitby=False) def count(self,distinct=None, cache=None): db = self.db if cache: cache_model, time_expire = cache sql = self._count(distinct=distinct) key = db._uri + '/' + sql if len(key)>200: key = hashlib_md5(key).hexdigest() return cache_model( key, (lambda self=self,distinct=distinct: \ db._adapter.count(self.query,distinct)), time_expire) return db._adapter.count(self.query,distinct) def select(self, *fields, **attributes): adapter = self.db._adapter tablenames = adapter.tables(self.query, attributes.get('join',None), attributes.get('left',None), attributes.get('orderby',None), attributes.get('groupby',None)) fields = adapter.expand_all(fields, tablenames) return adapter.select(self.query,fields,attributes) def nested_select(self,*fields,**attributes): return Expression(self.db,self._select(*fields,**attributes)) def delete(self): db = self.db tablename = db._adapter.get_table(self.query) table = db[tablename] if any(f(self) for f in table._before_delete): return 0 ret = db._adapter.delete(tablename,self.query) ret and [f(self) for f in table._after_delete] return ret def update(self, **update_fields): db = self.db tablename = db._adapter.get_table(self.query) table = db[tablename] table._attempt_upload(update_fields) if any(f(self,update_fields) for f in table._before_update): return 0 fields = table._listify(update_fields,update=True) if not fields: raise SyntaxError("No fields to update") ret = db._adapter.update("%s" % table,self.query,fields) ret and [f(self,update_fields) for f in table._after_update] return ret def update_naive(self, **update_fields): """ same as update but does not call table._before_update and _after_update """ tablename = self.db._adapter.get_table(self.query) table = self.db[tablename] fields = table._listify(update_fields,update=True) if not fields: raise SyntaxError("No fields to update") ret = self.db._adapter.update("%s" % table,self.query,fields) return ret def validate_and_update(self, **update_fields): tablename = self.db._adapter.get_table(self.query) response = Row() response.errors = Row() new_fields = copy.copy(update_fields) for key,value in update_fields.iteritems(): value,error = self.db[tablename][key].validate(value) if error: response.errors[key] = error else: new_fields[key] = value table = self.db[tablename] if response.errors: response.updated = None else: if not any(f(self,new_fields) for f in table._before_update): fields = table._listify(new_fields,update=True) if not fields: raise SyntaxError("No fields to update") ret = self.db._adapter.update(tablename,self.query,fields) ret and [f(self,new_fields) for f in table._after_update] else: ret = 0 response.updated = ret return response def delete_uploaded_files(self, upload_fields=None): table = self.db[self.db._adapter.tables(self.query)[0]] # ## mind uploadfield==True means file is not in DB if upload_fields: fields = upload_fields.keys() else: fields = table.fields fields = [f for f in fields if table[f].type == 'upload' and table[f].uploadfield == True and table[f].autodelete] if not fields: return False for record in self.select(*[table[f] for f in fields]): for fieldname in fields: field = table[fieldname] oldname = record.get(fieldname, None) if not oldname: continue if upload_fields and oldname == upload_fields[fieldname]: continue if field.custom_delete: field.custom_delete(oldname) else: uploadfolder = field.uploadfolder if not uploadfolder: uploadfolder = pjoin( self.db._adapter.folder, '..', 'uploads') if field.uploadseparate: items = oldname.split('.') uploadfolder = pjoin( uploadfolder, "%s.%s" % (items[0], items[1]), items[2][:2]) oldpath = pjoin(uploadfolder, oldname) if exists(oldpath): os.unlink(oldpath) return False class RecordUpdater(object): def __init__(self, colset, table, id): self.colset, self.db, self.tablename, self.id = \ colset, table._db, table._tablename, id def __call__(self, **fields): colset, db, tablename, id = self.colset, self.db, self.tablename, self.id table = db[tablename] newfields = fields or dict(colset) for fieldname in newfields.keys(): if not fieldname in table.fields or table[fieldname].type=='id': del newfields[fieldname] table._db(table._id==id,ignore_common_filters=True).update(**newfields) colset.update(newfields) return colset class RecordDeleter(object): def __init__(self, table, id): self.db, self.tablename, self.id = table._db, table._tablename, id def __call__(self): return self.db(self.db[self.tablename]._id==self.id).delete() class LazySet(object): def __init__(self, field, id): self.db, self.tablename, self.fieldname, self.id = \ field.db, field._tablename, field.name, id def _getset(self): query = self.db[self.tablename][self.fieldname]==self.id return Set(self.db,query) def __repr__(self): return repr(self._getset()) def __call__(self, query, ignore_common_filters=False): return self._getset()(query, ignore_common_filters) def _count(self,distinct=None): return self._getset()._count(distinct) def _select(self, *fields, **attributes): return self._getset()._select(*fields,**attributes) def _delete(self): return self._getset()._delete() def _update(self, **update_fields): return self._getset()._update(**update_fields) def isempty(self): return self._getset().isempty() def count(self,distinct=None, cache=None): return self._getset().count(distinct,cache) def select(self, *fields, **attributes): return self._getset().select(*fields,**attributes) def nested_select(self,*fields,**attributes): return self._getset().nested_select(*fields,**attributes) def delete(self): return self._getset().delete() def update(self, **update_fields): return self._getset().update(**update_fields) def update_naive(self, **update_fields): return self._getset().update_naive(**update_fields) def validate_and_update(self, **update_fields): return self._getset().validate_and_update(**update_fields) def delete_uploaded_files(self, upload_fields=None): return self._getset().delete_uploaded_files(upload_fields) class VirtualCommand(object): def __init__(self,method,row): self.method=method self.row=row def __call__(self,*args,**kwargs): return self.method(self.row,*args,**kwargs) def lazy_virtualfield(f): f.__lazy__ = True return f class Rows(object): """ A wrapper for the return value of a select. It basically represents a table. It has an iterator and each row is represented as a dictionary. """ # ## TODO: this class still needs some work to care for ID/OID def __init__( self, db=None, records=[], colnames=[], compact=True, rawrows=None ): self.db = db self.records = records self.colnames = colnames self.compact = compact self.response = rawrows def __repr__(self): return '<Rows (%s)>' % len(self.records) def setvirtualfields(self,**keyed_virtualfields): """ db.define_table('x',Field('number','integer')) if db(db.x).isempty(): [db.x.insert(number=i) for i in range(10)] from gluon.dal import lazy_virtualfield class MyVirtualFields(object): # normal virtual field (backward compatible, discouraged) def normal_shift(self): return self.x.number+1 # lazy virtual field (because of @staticmethod) @lazy_virtualfield def lazy_shift(instance,row,delta=4): return row.x.number+delta db.x.virtualfields.append(MyVirtualFields()) for row in db(db.x).select(): print row.number, row.normal_shift, row.lazy_shift(delta=7) """ if not keyed_virtualfields: return self for row in self.records: for (tablename,virtualfields) in keyed_virtualfields.iteritems(): attributes = dir(virtualfields) if not tablename in row: box = row[tablename] = Row() else: box = row[tablename] updated = False for attribute in attributes: if attribute[0] != '_': method = getattr(virtualfields,attribute) if hasattr(method,'__lazy__'): box[attribute]=VirtualCommand(method,row) elif type(method)==types.MethodType: if not updated: virtualfields.__dict__.update(row) updated = True box[attribute]=method() return self def __and__(self,other): if self.colnames!=other.colnames: raise Exception('Cannot & incompatible Rows objects') records = self.records+other.records return Rows(self.db,records,self.colnames) def __or__(self,other): if self.colnames!=other.colnames: raise Exception('Cannot | incompatible Rows objects') records = self.records records += [record for record in other.records \ if not record in records] return Rows(self.db,records,self.colnames) def __nonzero__(self): if len(self.records): return 1 return 0 def __len__(self): return len(self.records) def __getslice__(self, a, b): return Rows(self.db,self.records[a:b],self.colnames,compact=self.compact) def __getitem__(self, i): row = self.records[i] keys = row.keys() if self.compact and len(keys) == 1 and keys[0] != '_extra': return row[row.keys()[0]] return row def __iter__(self): """ iterator over records """ for i in xrange(len(self)): yield self[i] def __str__(self): """ serializes the table into a csv file """ s = StringIO.StringIO() self.export_to_csv_file(s) return s.getvalue() def first(self): if not self.records: return None return self[0] def last(self): if not self.records: return None return self[-1] def find(self,f,limitby=None): """ returns a new Rows object, a subset of the original object, filtered by the function f """ if not self: return Rows(self.db, [], self.colnames) records = [] if limitby: a,b = limitby else: a,b = 0,len(self) k = 0 for row in self: if f(row): if a<=k: records.append(row) k += 1 if k==b: break return Rows(self.db, records, self.colnames) def exclude(self, f): """ removes elements from the calling Rows object, filtered by the function f, and returns a new Rows object containing the removed elements """ if not self.records: return Rows(self.db, [], self.colnames) removed = [] i=0 while i<len(self): row = self[i] if f(row): removed.append(self.records[i]) del self.records[i] else: i += 1 return Rows(self.db, removed, self.colnames) def sort(self, f, reverse=False): """ returns a list of sorted elements (not sorted in place) """ rows = Rows(self.db,[],self.colnames,compact=False) rows.records = sorted(self,key=f,reverse=reverse) return rows def group_by_value(self, field): """ regroups the rows, by one of the fields """ if not self.records: return {} key = str(field) grouped_row_group = dict() for row in self: value = row[key] if not value in grouped_row_group: grouped_row_group[value] = [row] else: grouped_row_group[value].append(row) return grouped_row_group def render(self, i=None, fields=None): """ Takes an index and returns a copy of the indexed row with values transformed via the "represent" attributes of the associated fields. If no index is specified, a generator is returned for iteration over all the rows. fields -- a list of fields to transform (if None, all fields with "represent" attributes will be transformed). """ if i is None: return (self.repr(i, fields=fields) for i in range(len(self))) import sqlhtml row = copy.copy(self.records[i]) keys = row.keys() tables = [f.tablename for f in fields] if fields \ else [k for k in keys if k != '_extra'] for table in tables: repr_fields = [f.name for f in fields if f.tablename == table] \ if fields else [k for k in row[table].keys() if (hasattr(self.db[table], k) and isinstance(self.db[table][k], Field) and self.db[table][k].represent)] for field in repr_fields: row[table][field] = sqlhtml.represent( self.db[table][field], row[table][field], row[table]) if self.compact and len(keys) == 1 and keys[0] != '_extra': return row[keys[0]] return row def as_list(self, compact=True, storage_to_dict=True, datetime_to_str=True, custom_types=None): """ returns the data as a list or dictionary. :param storage_to_dict: when True returns a dict, otherwise a list(default True) :param datetime_to_str: convert datetime fields as strings (default True) """ (oc, self.compact) = (self.compact, compact) if storage_to_dict: items = [item.as_dict(datetime_to_str, custom_types) for item in self] else: items = [item for item in self] self.compact = compact return items def as_dict(self, key='id', compact=True, storage_to_dict=True, datetime_to_str=True, custom_types=None): """ returns the data as a dictionary of dictionaries (storage_to_dict=True) or records (False) :param key: the name of the field to be used as dict key, normally the id :param compact: ? (default True) :param storage_to_dict: when True returns a dict, otherwise a list(default True) :param datetime_to_str: convert datetime fields as strings (default True) """ # test for multiple rows multi = False f = self.first() if f and isinstance(key, basestring): multi = any([isinstance(v, f.__class__) for v in f.values()]) if (not "." in key) and multi: # No key provided, default to int indices def new_key(): i = 0 while True: yield i i += 1 key_generator = new_key() key = lambda r: key_generator.next() rows = self.as_list(compact, storage_to_dict, datetime_to_str, custom_types) if isinstance(key,str) and key.count('.')==1: (table, field) = key.split('.') return dict([(r[table][field],r) for r in rows]) elif isinstance(key,str): return dict([(r[key],r) for r in rows]) else: return dict([(key(r),r) for r in rows]) def export_to_csv_file(self, ofile, null='<NULL>', *args, **kwargs): """ export data to csv, the first line contains the column names :param ofile: where the csv must be exported to :param null: how null values must be represented (default '<NULL>') :param delimiter: delimiter to separate values (default ',') :param quotechar: character to use to quote string values (default '"') :param quoting: quote system, use csv.QUOTE_*** (default csv.QUOTE_MINIMAL) :param represent: use the fields .represent value (default False) :param colnames: list of column names to use (default self.colnames) This will only work when exporting rows objects!!!! DO NOT use this with db.export_to_csv() """ delimiter = kwargs.get('delimiter', ',') quotechar = kwargs.get('quotechar', '"') quoting = kwargs.get('quoting', csv.QUOTE_MINIMAL) represent = kwargs.get('represent', False) writer = csv.writer(ofile, delimiter=delimiter, quotechar=quotechar, quoting=quoting) colnames = kwargs.get('colnames', self.colnames) write_colnames = kwargs.get('write_colnames',True) # a proper csv starting with the column names if write_colnames: writer.writerow(colnames) def none_exception(value): """ returns a cleaned up value that can be used for csv export: - unicode text is encoded as such - None values are replaced with the given representation (default <NULL>) """ if value is None: return null elif isinstance(value, unicode): return value.encode('utf8') elif isinstance(value,Reference): return long(value) elif hasattr(value, 'isoformat'): return value.isoformat()[:19].replace('T', ' ') elif isinstance(value, (list,tuple)): # for type='list:..' return bar_encode(value) return value for record in self: row = [] for col in colnames: if not REGEX_TABLE_DOT_FIELD.match(col): row.append(record._extra[col]) else: (t, f) = col.split('.') field = self.db[t][f] if isinstance(record.get(t, None), (Row,dict)): value = record[t][f] else: value = record[f] if field.type=='blob' and not value is None: value = base64.b64encode(value) elif represent and field.represent: value = field.represent(value) row.append(none_exception(value)) writer.writerow(row) def xml(self,strict=False,row_name='row',rows_name='rows'): """ serializes the table using sqlhtml.SQLTABLE (if present) """ if strict: ncols = len(self.colnames) return '<%s>\n%s\n</%s>' % (rows_name, '\n'.join(row.as_xml(row_name=row_name, colnames=self.colnames) for row in self), rows_name) import sqlhtml return sqlhtml.SQLTABLE(self).xml() def as_xml(self,row_name='row',rows_name='rows'): return self.xml(strict=True, row_name=row_name, rows_name=rows_name) def as_json(self, mode='object', default=None): """ serializes the rows to a JSON list or object with objects mode='object' is not implemented (should return a nested object structure) """ items = [record.as_json(mode=mode, default=default, serialize=False, colnames=self.colnames) for record in self] if have_serializers: return serializers.json(items, default=default or serializers.custom_json) elif simplejson: return simplejson.dumps(items) else: raise RuntimeError("missing simplejson") # for consistent naming yet backwards compatible as_csv = __str__ json = as_json ################################################################################ # dummy function used to define some doctests ################################################################################ def test_all(): """ >>> if len(sys.argv)<2: db = DAL(\"sqlite://test.db\") >>> if len(sys.argv)>1: db = DAL(sys.argv[1]) >>> tmp = db.define_table('users',\ Field('stringf', 'string', length=32, required=True),\ Field('booleanf', 'boolean', default=False),\ Field('passwordf', 'password', notnull=True),\ Field('uploadf', 'upload'),\ Field('blobf', 'blob'),\ Field('integerf', 'integer', unique=True),\ Field('doublef', 'double', unique=True,notnull=True),\ Field('jsonf', 'json'),\ Field('datef', 'date', default=datetime.date.today()),\ Field('timef', 'time'),\ Field('datetimef', 'datetime'),\ migrate='test_user.table') Insert a field >>> db.users.insert(stringf='a', booleanf=True, passwordf='p', blobf='0A',\ uploadf=None, integerf=5, doublef=3.14,\ jsonf={"j": True},\ datef=datetime.date(2001, 1, 1),\ timef=datetime.time(12, 30, 15),\ datetimef=datetime.datetime(2002, 2, 2, 12, 30, 15)) 1 Drop the table >>> db.users.drop() Examples of insert, select, update, delete >>> tmp = db.define_table('person',\ Field('name'),\ Field('birth','date'),\ migrate='test_person.table') >>> person_id = db.person.insert(name=\"Marco\",birth='2005-06-22') >>> person_id = db.person.insert(name=\"Massimo\",birth='1971-12-21') commented len(db().select(db.person.ALL)) commented 2 >>> me = db(db.person.id==person_id).select()[0] # test select >>> me.name 'Massimo' >>> db.person[2].name 'Massimo' >>> db.person(2).name 'Massimo' >>> db.person(name='Massimo').name 'Massimo' >>> db.person(db.person.name=='Massimo').name 'Massimo' >>> row = db.person[2] >>> row.name == row['name'] == row['person.name'] == row('person.name') True >>> db(db.person.name=='Massimo').update(name='massimo') # test update 1 >>> db(db.person.name=='Marco').select().first().delete_record() # test delete 1 Update a single record >>> me.update_record(name=\"Max\") <Row {'name': 'Max', 'birth': datetime.date(1971, 12, 21), 'id': 2}> >>> me.name 'Max' Examples of complex search conditions >>> len(db((db.person.name=='Max')&(db.person.birth<'2003-01-01')).select()) 1 >>> len(db((db.person.name=='Max')&(db.person.birth<datetime.date(2003,01,01))).select()) 1 >>> len(db((db.person.name=='Max')|(db.person.birth<'2003-01-01')).select()) 1 >>> me = db(db.person.id==person_id).select(db.person.name)[0] >>> me.name 'Max' Examples of search conditions using extract from date/datetime/time >>> len(db(db.person.birth.month()==12).select()) 1 >>> len(db(db.person.birth.year()>1900).select()) 1 Example of usage of NULL >>> len(db(db.person.birth==None).select()) ### test NULL 0 >>> len(db(db.person.birth!=None).select()) ### test NULL 1 Examples of search conditions using lower, upper, and like >>> len(db(db.person.name.upper()=='MAX').select()) 1 >>> len(db(db.person.name.like('%ax')).select()) 1 >>> len(db(db.person.name.upper().like('%AX')).select()) 1 >>> len(db(~db.person.name.upper().like('%AX')).select()) 0 orderby, groupby and limitby >>> people = db().select(db.person.name, orderby=db.person.name) >>> order = db.person.name|~db.person.birth >>> people = db().select(db.person.name, orderby=order) >>> people = db().select(db.person.name, orderby=db.person.name, groupby=db.person.name) >>> people = db().select(db.person.name, orderby=order, limitby=(0,100)) Example of one 2 many relation >>> tmp = db.define_table('dog',\ Field('name'),\ Field('birth','date'),\ Field('owner',db.person),\ migrate='test_dog.table') >>> db.dog.insert(name='Snoopy', birth=None, owner=person_id) 1 A simple JOIN >>> len(db(db.dog.owner==db.person.id).select()) 1 >>> len(db().select(db.person.ALL, db.dog.name,left=db.dog.on(db.dog.owner==db.person.id))) 1 Drop tables >>> db.dog.drop() >>> db.person.drop() Example of many 2 many relation and Set >>> tmp = db.define_table('author', Field('name'),\ migrate='test_author.table') >>> tmp = db.define_table('paper', Field('title'),\ migrate='test_paper.table') >>> tmp = db.define_table('authorship',\ Field('author_id', db.author),\ Field('paper_id', db.paper),\ migrate='test_authorship.table') >>> aid = db.author.insert(name='Massimo') >>> pid = db.paper.insert(title='QCD') >>> tmp = db.authorship.insert(author_id=aid, paper_id=pid) Define a Set >>> authored_papers = db((db.author.id==db.authorship.author_id)&(db.paper.id==db.authorship.paper_id)) >>> rows = authored_papers.select(db.author.name, db.paper.title) >>> for row in rows: print row.author.name, row.paper.title Massimo QCD Example of search condition using belongs >>> set = (1, 2, 3) >>> rows = db(db.paper.id.belongs(set)).select(db.paper.ALL) >>> print rows[0].title QCD Example of search condition using nested select >>> nested_select = db()._select(db.authorship.paper_id) >>> rows = db(db.paper.id.belongs(nested_select)).select(db.paper.ALL) >>> print rows[0].title QCD Example of expressions >>> mynumber = db.define_table('mynumber', Field('x', 'integer')) >>> db(mynumber).delete() 0 >>> for i in range(10): tmp = mynumber.insert(x=i) >>> db(mynumber).select(mynumber.x.sum())[0](mynumber.x.sum()) 45 >>> db(mynumber.x+2==5).select(mynumber.x + 2)[0](mynumber.x + 2) 5 Output in csv >>> print str(authored_papers.select(db.author.name, db.paper.title)).strip() author.name,paper.title\r Massimo,QCD Delete all leftover tables >>> DAL.distributed_transaction_commit(db) >>> db.mynumber.drop() >>> db.authorship.drop() >>> db.author.drop() >>> db.paper.drop() """ ################################################################################ # deprecated since the new DAL; here only for backward compatibility ################################################################################ SQLField = Field SQLTable = Table SQLXorable = Expression SQLQuery = Query SQLSet = Set SQLRows = Rows SQLStorage = Row SQLDB = DAL GQLDB = DAL DAL.Field = Field # was necessary in gluon/globals.py session.connect DAL.Table = Table # was necessary in gluon/globals.py session.connect ################################################################################ # Geodal utils ################################################################################ def geoPoint(x,y): return "POINT (%f %f)" % (x,y) def geoLine(*line): return "LINESTRING (%s)" % ','.join("%f %f" % item for item in line) def geoPolygon(*line): return "POLYGON ((%s))" % ','.join("%f %f" % item for item in line) ################################################################################ # run tests ################################################################################ if __name__ == '__main__': import doctest doctest.testmod()
mit
eomerdws/aeneas
aeneas/diagnostics.py
3
11025
#!/usr/bin/env python # coding=utf-8 # aeneas is a Python/C library and a set of tools # to automagically synchronize audio and text (aka forced alignment) # # Copyright (C) 2012-2013, Alberto Pettarin (www.albertopettarin.it) # Copyright (C) 2013-2015, ReadBeyond Srl (www.readbeyond.it) # Copyright (C) 2015-2017, Alberto Pettarin (www.albertopettarin.it) # # 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/>. """ This module contains the following classes: * :class:`~aeneas.diagnostics.Diagnostics`, checking whether the setup of ``aeneas`` was successful. This module can be executed from command line with:: python -m aeneas.diagnostics .. versionadded:: 1.4.1 """ from __future__ import absolute_import from __future__ import print_function import sys import aeneas.globalfunctions as gf class Diagnostics(object): """ Check whether the setup of ``aeneas`` was successful. """ @classmethod def check_shell_encoding(cls): """ Check whether ``sys.stdin`` and ``sys.stdout`` are UTF-8 encoded. Return ``True`` on failure and ``False`` on success. :rtype: bool """ is_in_utf8 = True is_out_utf8 = True if sys.stdin.encoding not in ["UTF-8", "UTF8"]: is_in_utf8 = False if sys.stdout.encoding not in ["UTF-8", "UTF8"]: is_out_utf8 = False if (is_in_utf8) and (is_out_utf8): gf.print_success(u"shell encoding OK") else: gf.print_warning(u"shell encoding WARNING") if not is_in_utf8: gf.print_warning(u" The default input encoding of your shell is not UTF-8") if not is_out_utf8: gf.print_warning(u" The default output encoding of your shell is not UTF-8") gf.print_info(u" If you plan to use aeneas on the command line,") if gf.is_posix(): gf.print_info(u" you might want to 'export PYTHONIOENCODING=UTF-8' in your shell") else: gf.print_info(u" you might want to 'set PYTHONIOENCODING=UTF-8' in your shell") return True return False @classmethod def check_ffprobe(cls): """ Check whether ``ffprobe`` can be called. Return ``True`` on failure and ``False`` on success. :rtype: bool """ try: from aeneas.ffprobewrapper import FFPROBEWrapper file_path = gf.absolute_path(u"tools/res/audio.mp3", __file__) prober = FFPROBEWrapper() properties = prober.read_properties(file_path) gf.print_success(u"ffprobe OK") return False except: pass gf.print_error(u"ffprobe ERROR") gf.print_info(u" Please make sure you have ffprobe installed correctly") gf.print_info(u" (usually it is provided by the ffmpeg installer)") gf.print_info(u" and that its path is in your PATH environment variable") return True @classmethod def check_ffmpeg(cls): """ Check whether ``ffmpeg`` can be called. Return ``True`` on failure and ``False`` on success. :rtype: bool """ try: from aeneas.ffmpegwrapper import FFMPEGWrapper input_file_path = gf.absolute_path(u"tools/res/audio.mp3", __file__) handler, output_file_path = gf.tmp_file(suffix=u".wav") converter = FFMPEGWrapper() result = converter.convert(input_file_path, output_file_path) gf.delete_file(handler, output_file_path) if result: gf.print_success(u"ffmpeg OK") return False except: pass gf.print_error(u"ffmpeg ERROR") gf.print_info(u" Please make sure you have ffmpeg installed correctly") gf.print_info(u" and that its path is in your PATH environment variable") return True @classmethod def check_espeak(cls): """ Check whether ``espeak`` can be called. Return ``True`` on failure and ``False`` on success. :rtype: bool """ try: from aeneas.textfile import TextFile from aeneas.textfile import TextFragment from aeneas.ttswrappers.espeakttswrapper import ESPEAKTTSWrapper text = u"From fairest creatures we desire increase," text_file = TextFile() text_file.add_fragment(TextFragment(language=u"eng", lines=[text], filtered_lines=[text])) handler, output_file_path = gf.tmp_file(suffix=u".wav") ESPEAKTTSWrapper().synthesize_multiple(text_file, output_file_path) gf.delete_file(handler, output_file_path) gf.print_success(u"espeak OK") return False except: pass gf.print_error(u"espeak ERROR") gf.print_info(u" Please make sure you have espeak installed correctly") gf.print_info(u" and that its path is in your PATH environment variable") gf.print_info(u" You might also want to check that the espeak-data directory") gf.print_info(u" is set up correctly, for example, it has the correct permissions") return True @classmethod def check_tools(cls): """ Check whether ``aeneas.tools.*`` can be imported. Return ``True`` on failure and ``False`` on success. :rtype: bool """ try: from aeneas.tools.convert_syncmap import ConvertSyncMapCLI # disabling this check, as it requires the optional dependency youtube-dl # COMMENTED from aeneas.tools.download import DownloadCLI from aeneas.tools.execute_job import ExecuteJobCLI from aeneas.tools.execute_task import ExecuteTaskCLI from aeneas.tools.extract_mfcc import ExtractMFCCCLI from aeneas.tools.ffmpeg_wrapper import FFMPEGWrapperCLI from aeneas.tools.ffprobe_wrapper import FFPROBEWrapperCLI # disabling this check, as it requires the optional dependency Pillow # COMMENTED from aeneas.tools.plot_waveform import PlotWaveformCLI from aeneas.tools.read_audio import ReadAudioCLI from aeneas.tools.read_text import ReadTextCLI from aeneas.tools.run_sd import RunSDCLI from aeneas.tools.run_vad import RunVADCLI from aeneas.tools.synthesize_text import SynthesizeTextCLI from aeneas.tools.validate import ValidateCLI gf.print_success(u"aeneas.tools OK") return False except: pass gf.print_error(u"aeneas.tools ERROR") gf.print_info(u" Unable to import one or more aeneas.tools") gf.print_info(u" Please check that you installed aeneas properly") return True @classmethod def check_cdtw(cls): """ Check whether Python C extension ``cdtw`` can be imported. Return ``True`` on failure and ``False`` on success. :rtype: bool """ if gf.can_run_c_extension("cdtw"): gf.print_success(u"aeneas.cdtw AVAILABLE") return False gf.print_warning(u"aeneas.cdtw NOT AVAILABLE") gf.print_info(u" You can still run aeneas but it will be significantly slower") gf.print_info(u" Please refer to the installation documentation for details") return True @classmethod def check_cmfcc(cls): """ Check whether Python C extension ``cmfcc`` can be imported. Return ``True`` on failure and ``False`` on success. :rtype: bool """ if gf.can_run_c_extension("cmfcc"): gf.print_success(u"aeneas.cmfcc AVAILABLE") return False gf.print_warning(u"aeneas.cmfcc NOT AVAILABLE") gf.print_info(u" You can still run aeneas but it will be significantly slower") gf.print_info(u" Please refer to the installation documentation for details") return True @classmethod def check_cew(cls): """ Check whether Python C extension ``cew`` can be imported. Return ``True`` on failure and ``False`` on success. :rtype: bool """ if gf.can_run_c_extension("cew"): gf.print_success(u"aeneas.cew AVAILABLE") return False gf.print_warning(u"aeneas.cew NOT AVAILABLE") gf.print_info(u" You can still run aeneas but it will be a bit slower") gf.print_info(u" Please refer to the installation documentation for details") return True @classmethod def check_all(cls, tools=True, encoding=True, c_ext=True): """ Perform all checks. Return a tuple of booleans ``(errors, warnings, c_ext_warnings)``. :param bool tools: if ``True``, check aeneas tools :param bool encoding: if ``True``, check shell encoding :param bool c_ext: if ``True``, check Python C extensions :rtype: (bool, bool, bool) """ # errors are fatal if cls.check_ffprobe(): return (True, False, False) if cls.check_ffmpeg(): return (True, False, False) if cls.check_espeak(): return (True, False, False) if (tools) and (cls.check_tools()): return (True, False, False) # warnings are non-fatal warnings = False c_ext_warnings = False if encoding: warnings = cls.check_shell_encoding() if c_ext: # we do not want lazy evaluation c_ext_warnings = cls.check_cdtw() or c_ext_warnings c_ext_warnings = cls.check_cmfcc() or c_ext_warnings c_ext_warnings = cls.check_cew() or c_ext_warnings # return results return (False, warnings, c_ext_warnings) def main(): errors, warnings, c_ext_warnings = Diagnostics.check_all() if errors: sys.exit(1) if c_ext_warnings: gf.print_warning(u"All required dependencies are met but at least one Python C extension is not available") sys.exit(2) else: gf.print_success(u"All required dependencies are met and all available Python C extensions are working") sys.exit(0) if __name__ == '__main__': main()
agpl-3.0
zmike/servo
tests/wpt/web-platform-tests/tools/html5lib/utils/entities.py
438
2734
import json import html5lib def parse(path="html5ents.xml"): return html5lib.parse(open(path), treebuilder="lxml") def entity_table(tree): return dict((entity_name("".join(tr[0].xpath(".//text()"))), entity_characters(tr[1].text)) for tr in tree.xpath("//h:tbody/h:tr", namespaces={"h":"http://www.w3.org/1999/xhtml"})) def entity_name(inp): return inp.strip() def entity_characters(inp): return "".join(codepoint_to_character(item) for item in inp.split() if item) def codepoint_to_character(inp): return ("\U000"+inp[2:]).decode("unicode-escape") def make_tests_json(entities): test_list = make_test_list(entities) tests_json = {"tests": [make_test(*item) for item in test_list] } return tests_json def make_test(name, characters, good): return { "description":test_description(name, good), "input":"&%s"%name, "output":test_expected(name, characters, good) } def test_description(name, good): with_semicolon = name.endswith(";") semicolon_text = {True:"with a semi-colon", False:"without a semi-colon"}[with_semicolon] if good: text = "Named entity: %s %s"%(name, semicolon_text) else: text = "Bad named entity: %s %s"%(name, semicolon_text) return text def test_expected(name, characters, good): rv = [] if not good or not name.endswith(";"): rv.append("ParseError") rv.append(["Character", characters]) return rv def make_test_list(entities): tests = [] for entity_name, characters in entities.items(): if entity_name.endswith(";") and not subentity_exists(entity_name, entities): tests.append((entity_name[:-1], "&" + entity_name[:-1], False)) tests.append((entity_name, characters, True)) return sorted(tests) def subentity_exists(entity_name, entities): for i in range(1, len(entity_name)): if entity_name[:-i] in entities: return True return False def make_entities_code(entities): entities_text = "\n".join(" \"%s\": u\"%s\","%( name, entities[name].encode( "unicode-escape").replace("\"", "\\\"")) for name in sorted(entities.keys())) return """entities = { %s }"""%entities_text def main(): entities = entity_table(parse()) tests_json = make_tests_json(entities) json.dump(tests_json, open("namedEntities.test", "w"), indent=4) code = make_entities_code(entities) open("entities_constants.py", "w").write(code) if __name__ == "__main__": main()
mpl-2.0
Vagab0nd/SiCKRAGE
lib3/kodipydent/rpctohive.py
2
2496
import json class Hive(dict): def __init__(self, rpc): dict.__init__(self) self['root'] = 'http://{hostname}:{port}' self['objects'] = {} self['endpoints'] = {'SingleEndpoint': {'path':'/jsonrpc','methods':['POST']}} self['variable_settings'] = { 'default_type': 'json_rpc', 'custom_types': { 'json_rpc': { 'description': 'Takes all vars and puts them in a body JSON object' } } } self['variables'] = { 'hostname': { 'type': 'url_replacement' }, 'port': { 'type': 'url_replacement' }, 'jsonrpc': { 'type': 'json_rpc', 'value': '2.0' }, 'request_id': { 'type': 'json_rpc' }, 'username': { 'type': 'http_basic_auth', 'optional': True, }, 'password': { 'type': 'http_basic_auth', 'optional': True } } for name, method in rpc['methods'].items(): self.add_method(name, method) def add_method(self, name, method): obj, action = name.split('.', 1) if obj not in self['objects']: self['objects'][obj] = {'actions':{}} self['objects'][obj]['actions'][action] = Method(name, method) def dump(self, file): with open(file, 'w') as out: json.dump(self, out, indent=4) class Method(dict): def __init__(self, name, method): dict.__init__(self) self['description'] = method['description'] self['endpoint'] = 'SingleEndpoint' self['method'] = 'POST' self['variables'] = Variables(method['params']) self['variables']['method'] = { 'type': 'json_rpc', 'value': name } class Variables(dict): def __init__(self, variables): dict.__init__(self) for each in variables: self.add_var(each) def add_var(self, variable): out = {} if not variable.get('required', False): out['optional'] = True out['type'] = 'json_rpc' if 'default' in variable: out['value'] = variable['default'] if 'description' in variable: out['description'] = variable['description'] self[variable['name']] = out
gpl-3.0
sursum/buckanjaren
buckanjaren/lib/python3.5/site-packages/django/conf/locale/en_AU/formats.py
504
2117
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # from __future__ import unicode_literals # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j M Y' # '25 Oct 2006' TIME_FORMAT = 'P' # '2:30 p.m.' DATETIME_FORMAT = 'j M Y, P' # '25 Oct 2006, 2:30 p.m.' YEAR_MONTH_FORMAT = 'F Y' # 'October 2006' MONTH_DAY_FORMAT = 'j F' # '25 October' SHORT_DATE_FORMAT = 'd/m/Y' # '25/10/2006' SHORT_DATETIME_FORMAT = 'd/m/Y P' # '25/10/2006 2:30 p.m.' FIRST_DAY_OF_WEEK = 0 # Sunday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = [ '%d/%m/%Y', '%d/%m/%y', # '25/10/2006', '25/10/06' # '%b %d %Y', '%b %d, %Y', # 'Oct 25 2006', 'Oct 25, 2006' # '%d %b %Y', '%d %b, %Y', # '25 Oct 2006', '25 Oct, 2006' # '%B %d %Y', '%B %d, %Y', # 'October 25 2006', 'October 25, 2006' # '%d %B %Y', '%d %B, %Y', # '25 October 2006', '25 October, 2006' ] DATETIME_INPUT_FORMATS = [ '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M:%S.%f', # '2006-10-25 14:30:59.000200' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' '%d/%m/%Y %H:%M:%S', # '25/10/2006 14:30:59' '%d/%m/%Y %H:%M:%S.%f', # '25/10/2006 14:30:59.000200' '%d/%m/%Y %H:%M', # '25/10/2006 14:30' '%d/%m/%Y', # '25/10/2006' '%d/%m/%y %H:%M:%S', # '25/10/06 14:30:59' '%d/%m/%y %H:%M:%S.%f', # '25/10/06 14:30:59.000200' '%d/%m/%y %H:%M', # '25/10/06 14:30' '%d/%m/%y', # '25/10/06' ] DECIMAL_SEPARATOR = '.' THOUSAND_SEPARATOR = ',' NUMBER_GROUPING = 3
mit
zeptonaut/catapult
third_party/html5lib-python/html5lib/ihatexml.py
1727
16581
from __future__ import absolute_import, division, unicode_literals import re import warnings from .constants import DataLossWarning baseChar = """ [#x0041-#x005A] | [#x0061-#x007A] | [#x00C0-#x00D6] | [#x00D8-#x00F6] | [#x00F8-#x00FF] | [#x0100-#x0131] | [#x0134-#x013E] | [#x0141-#x0148] | [#x014A-#x017E] | [#x0180-#x01C3] | [#x01CD-#x01F0] | [#x01F4-#x01F5] | [#x01FA-#x0217] | [#x0250-#x02A8] | [#x02BB-#x02C1] | #x0386 | [#x0388-#x038A] | #x038C | [#x038E-#x03A1] | [#x03A3-#x03CE] | [#x03D0-#x03D6] | #x03DA | #x03DC | #x03DE | #x03E0 | [#x03E2-#x03F3] | [#x0401-#x040C] | [#x040E-#x044F] | [#x0451-#x045C] | [#x045E-#x0481] | [#x0490-#x04C4] | [#x04C7-#x04C8] | [#x04CB-#x04CC] | [#x04D0-#x04EB] | [#x04EE-#x04F5] | [#x04F8-#x04F9] | [#x0531-#x0556] | #x0559 | [#x0561-#x0586] | [#x05D0-#x05EA] | [#x05F0-#x05F2] | [#x0621-#x063A] | [#x0641-#x064A] | [#x0671-#x06B7] | [#x06BA-#x06BE] | [#x06C0-#x06CE] | [#x06D0-#x06D3] | #x06D5 | [#x06E5-#x06E6] | [#x0905-#x0939] | #x093D | [#x0958-#x0961] | [#x0985-#x098C] | [#x098F-#x0990] | [#x0993-#x09A8] | [#x09AA-#x09B0] | #x09B2 | [#x09B6-#x09B9] | [#x09DC-#x09DD] | [#x09DF-#x09E1] | [#x09F0-#x09F1] | [#x0A05-#x0A0A] | [#x0A0F-#x0A10] | [#x0A13-#x0A28] | [#x0A2A-#x0A30] | [#x0A32-#x0A33] | [#x0A35-#x0A36] | [#x0A38-#x0A39] | [#x0A59-#x0A5C] | #x0A5E | [#x0A72-#x0A74] | [#x0A85-#x0A8B] | #x0A8D | [#x0A8F-#x0A91] | [#x0A93-#x0AA8] | [#x0AAA-#x0AB0] | [#x0AB2-#x0AB3] | [#x0AB5-#x0AB9] | #x0ABD | #x0AE0 | [#x0B05-#x0B0C] | [#x0B0F-#x0B10] | [#x0B13-#x0B28] | [#x0B2A-#x0B30] | [#x0B32-#x0B33] | [#x0B36-#x0B39] | #x0B3D | [#x0B5C-#x0B5D] | [#x0B5F-#x0B61] | [#x0B85-#x0B8A] | [#x0B8E-#x0B90] | [#x0B92-#x0B95] | [#x0B99-#x0B9A] | #x0B9C | [#x0B9E-#x0B9F] | [#x0BA3-#x0BA4] | [#x0BA8-#x0BAA] | [#x0BAE-#x0BB5] | [#x0BB7-#x0BB9] | [#x0C05-#x0C0C] | [#x0C0E-#x0C10] | [#x0C12-#x0C28] | [#x0C2A-#x0C33] | [#x0C35-#x0C39] | [#x0C60-#x0C61] | [#x0C85-#x0C8C] | [#x0C8E-#x0C90] | [#x0C92-#x0CA8] | [#x0CAA-#x0CB3] | [#x0CB5-#x0CB9] | #x0CDE | [#x0CE0-#x0CE1] | [#x0D05-#x0D0C] | [#x0D0E-#x0D10] | [#x0D12-#x0D28] | [#x0D2A-#x0D39] | [#x0D60-#x0D61] | [#x0E01-#x0E2E] | #x0E30 | [#x0E32-#x0E33] | [#x0E40-#x0E45] | [#x0E81-#x0E82] | #x0E84 | [#x0E87-#x0E88] | #x0E8A | #x0E8D | [#x0E94-#x0E97] | [#x0E99-#x0E9F] | [#x0EA1-#x0EA3] | #x0EA5 | #x0EA7 | [#x0EAA-#x0EAB] | [#x0EAD-#x0EAE] | #x0EB0 | [#x0EB2-#x0EB3] | #x0EBD | [#x0EC0-#x0EC4] | [#x0F40-#x0F47] | [#x0F49-#x0F69] | [#x10A0-#x10C5] | [#x10D0-#x10F6] | #x1100 | [#x1102-#x1103] | [#x1105-#x1107] | #x1109 | [#x110B-#x110C] | [#x110E-#x1112] | #x113C | #x113E | #x1140 | #x114C | #x114E | #x1150 | [#x1154-#x1155] | #x1159 | [#x115F-#x1161] | #x1163 | #x1165 | #x1167 | #x1169 | [#x116D-#x116E] | [#x1172-#x1173] | #x1175 | #x119E | #x11A8 | #x11AB | [#x11AE-#x11AF] | [#x11B7-#x11B8] | #x11BA | [#x11BC-#x11C2] | #x11EB | #x11F0 | #x11F9 | [#x1E00-#x1E9B] | [#x1EA0-#x1EF9] | [#x1F00-#x1F15] | [#x1F18-#x1F1D] | [#x1F20-#x1F45] | [#x1F48-#x1F4D] | [#x1F50-#x1F57] | #x1F59 | #x1F5B | #x1F5D | [#x1F5F-#x1F7D] | [#x1F80-#x1FB4] | [#x1FB6-#x1FBC] | #x1FBE | [#x1FC2-#x1FC4] | [#x1FC6-#x1FCC] | [#x1FD0-#x1FD3] | [#x1FD6-#x1FDB] | [#x1FE0-#x1FEC] | [#x1FF2-#x1FF4] | [#x1FF6-#x1FFC] | #x2126 | [#x212A-#x212B] | #x212E | [#x2180-#x2182] | [#x3041-#x3094] | [#x30A1-#x30FA] | [#x3105-#x312C] | [#xAC00-#xD7A3]""" ideographic = """[#x4E00-#x9FA5] | #x3007 | [#x3021-#x3029]""" combiningCharacter = """ [#x0300-#x0345] | [#x0360-#x0361] | [#x0483-#x0486] | [#x0591-#x05A1] | [#x05A3-#x05B9] | [#x05BB-#x05BD] | #x05BF | [#x05C1-#x05C2] | #x05C4 | [#x064B-#x0652] | #x0670 | [#x06D6-#x06DC] | [#x06DD-#x06DF] | [#x06E0-#x06E4] | [#x06E7-#x06E8] | [#x06EA-#x06ED] | [#x0901-#x0903] | #x093C | [#x093E-#x094C] | #x094D | [#x0951-#x0954] | [#x0962-#x0963] | [#x0981-#x0983] | #x09BC | #x09BE | #x09BF | [#x09C0-#x09C4] | [#x09C7-#x09C8] | [#x09CB-#x09CD] | #x09D7 | [#x09E2-#x09E3] | #x0A02 | #x0A3C | #x0A3E | #x0A3F | [#x0A40-#x0A42] | [#x0A47-#x0A48] | [#x0A4B-#x0A4D] | [#x0A70-#x0A71] | [#x0A81-#x0A83] | #x0ABC | [#x0ABE-#x0AC5] | [#x0AC7-#x0AC9] | [#x0ACB-#x0ACD] | [#x0B01-#x0B03] | #x0B3C | [#x0B3E-#x0B43] | [#x0B47-#x0B48] | [#x0B4B-#x0B4D] | [#x0B56-#x0B57] | [#x0B82-#x0B83] | [#x0BBE-#x0BC2] | [#x0BC6-#x0BC8] | [#x0BCA-#x0BCD] | #x0BD7 | [#x0C01-#x0C03] | [#x0C3E-#x0C44] | [#x0C46-#x0C48] | [#x0C4A-#x0C4D] | [#x0C55-#x0C56] | [#x0C82-#x0C83] | [#x0CBE-#x0CC4] | [#x0CC6-#x0CC8] | [#x0CCA-#x0CCD] | [#x0CD5-#x0CD6] | [#x0D02-#x0D03] | [#x0D3E-#x0D43] | [#x0D46-#x0D48] | [#x0D4A-#x0D4D] | #x0D57 | #x0E31 | [#x0E34-#x0E3A] | [#x0E47-#x0E4E] | #x0EB1 | [#x0EB4-#x0EB9] | [#x0EBB-#x0EBC] | [#x0EC8-#x0ECD] | [#x0F18-#x0F19] | #x0F35 | #x0F37 | #x0F39 | #x0F3E | #x0F3F | [#x0F71-#x0F84] | [#x0F86-#x0F8B] | [#x0F90-#x0F95] | #x0F97 | [#x0F99-#x0FAD] | [#x0FB1-#x0FB7] | #x0FB9 | [#x20D0-#x20DC] | #x20E1 | [#x302A-#x302F] | #x3099 | #x309A""" digit = """ [#x0030-#x0039] | [#x0660-#x0669] | [#x06F0-#x06F9] | [#x0966-#x096F] | [#x09E6-#x09EF] | [#x0A66-#x0A6F] | [#x0AE6-#x0AEF] | [#x0B66-#x0B6F] | [#x0BE7-#x0BEF] | [#x0C66-#x0C6F] | [#x0CE6-#x0CEF] | [#x0D66-#x0D6F] | [#x0E50-#x0E59] | [#x0ED0-#x0ED9] | [#x0F20-#x0F29]""" extender = """ #x00B7 | #x02D0 | #x02D1 | #x0387 | #x0640 | #x0E46 | #x0EC6 | #x3005 | #[#x3031-#x3035] | [#x309D-#x309E] | [#x30FC-#x30FE]""" letter = " | ".join([baseChar, ideographic]) # Without the name = " | ".join([letter, digit, ".", "-", "_", combiningCharacter, extender]) nameFirst = " | ".join([letter, "_"]) reChar = re.compile(r"#x([\d|A-F]{4,4})") reCharRange = re.compile(r"\[#x([\d|A-F]{4,4})-#x([\d|A-F]{4,4})\]") def charStringToList(chars): charRanges = [item.strip() for item in chars.split(" | ")] rv = [] for item in charRanges: foundMatch = False for regexp in (reChar, reCharRange): match = regexp.match(item) if match is not None: rv.append([hexToInt(item) for item in match.groups()]) if len(rv[-1]) == 1: rv[-1] = rv[-1] * 2 foundMatch = True break if not foundMatch: assert len(item) == 1 rv.append([ord(item)] * 2) rv = normaliseCharList(rv) return rv def normaliseCharList(charList): charList = sorted(charList) for item in charList: assert item[1] >= item[0] rv = [] i = 0 while i < len(charList): j = 1 rv.append(charList[i]) while i + j < len(charList) and charList[i + j][0] <= rv[-1][1] + 1: rv[-1][1] = charList[i + j][1] j += 1 i += j return rv # We don't really support characters above the BMP :( max_unicode = int("FFFF", 16) def missingRanges(charList): rv = [] if charList[0] != 0: rv.append([0, charList[0][0] - 1]) for i, item in enumerate(charList[:-1]): rv.append([item[1] + 1, charList[i + 1][0] - 1]) if charList[-1][1] != max_unicode: rv.append([charList[-1][1] + 1, max_unicode]) return rv def listToRegexpStr(charList): rv = [] for item in charList: if item[0] == item[1]: rv.append(escapeRegexp(chr(item[0]))) else: rv.append(escapeRegexp(chr(item[0])) + "-" + escapeRegexp(chr(item[1]))) return "[%s]" % "".join(rv) def hexToInt(hex_str): return int(hex_str, 16) def escapeRegexp(string): specialCharacters = (".", "^", "$", "*", "+", "?", "{", "}", "[", "]", "|", "(", ")", "-") for char in specialCharacters: string = string.replace(char, "\\" + char) return string # output from the above nonXmlNameBMPRegexp = re.compile('[\x00-,/:-@\\[-\\^`\\{-\xb6\xb8-\xbf\xd7\xf7\u0132-\u0133\u013f-\u0140\u0149\u017f\u01c4-\u01cc\u01f1-\u01f3\u01f6-\u01f9\u0218-\u024f\u02a9-\u02ba\u02c2-\u02cf\u02d2-\u02ff\u0346-\u035f\u0362-\u0385\u038b\u038d\u03a2\u03cf\u03d7-\u03d9\u03db\u03dd\u03df\u03e1\u03f4-\u0400\u040d\u0450\u045d\u0482\u0487-\u048f\u04c5-\u04c6\u04c9-\u04ca\u04cd-\u04cf\u04ec-\u04ed\u04f6-\u04f7\u04fa-\u0530\u0557-\u0558\u055a-\u0560\u0587-\u0590\u05a2\u05ba\u05be\u05c0\u05c3\u05c5-\u05cf\u05eb-\u05ef\u05f3-\u0620\u063b-\u063f\u0653-\u065f\u066a-\u066f\u06b8-\u06b9\u06bf\u06cf\u06d4\u06e9\u06ee-\u06ef\u06fa-\u0900\u0904\u093a-\u093b\u094e-\u0950\u0955-\u0957\u0964-\u0965\u0970-\u0980\u0984\u098d-\u098e\u0991-\u0992\u09a9\u09b1\u09b3-\u09b5\u09ba-\u09bb\u09bd\u09c5-\u09c6\u09c9-\u09ca\u09ce-\u09d6\u09d8-\u09db\u09de\u09e4-\u09e5\u09f2-\u0a01\u0a03-\u0a04\u0a0b-\u0a0e\u0a11-\u0a12\u0a29\u0a31\u0a34\u0a37\u0a3a-\u0a3b\u0a3d\u0a43-\u0a46\u0a49-\u0a4a\u0a4e-\u0a58\u0a5d\u0a5f-\u0a65\u0a75-\u0a80\u0a84\u0a8c\u0a8e\u0a92\u0aa9\u0ab1\u0ab4\u0aba-\u0abb\u0ac6\u0aca\u0ace-\u0adf\u0ae1-\u0ae5\u0af0-\u0b00\u0b04\u0b0d-\u0b0e\u0b11-\u0b12\u0b29\u0b31\u0b34-\u0b35\u0b3a-\u0b3b\u0b44-\u0b46\u0b49-\u0b4a\u0b4e-\u0b55\u0b58-\u0b5b\u0b5e\u0b62-\u0b65\u0b70-\u0b81\u0b84\u0b8b-\u0b8d\u0b91\u0b96-\u0b98\u0b9b\u0b9d\u0ba0-\u0ba2\u0ba5-\u0ba7\u0bab-\u0bad\u0bb6\u0bba-\u0bbd\u0bc3-\u0bc5\u0bc9\u0bce-\u0bd6\u0bd8-\u0be6\u0bf0-\u0c00\u0c04\u0c0d\u0c11\u0c29\u0c34\u0c3a-\u0c3d\u0c45\u0c49\u0c4e-\u0c54\u0c57-\u0c5f\u0c62-\u0c65\u0c70-\u0c81\u0c84\u0c8d\u0c91\u0ca9\u0cb4\u0cba-\u0cbd\u0cc5\u0cc9\u0cce-\u0cd4\u0cd7-\u0cdd\u0cdf\u0ce2-\u0ce5\u0cf0-\u0d01\u0d04\u0d0d\u0d11\u0d29\u0d3a-\u0d3d\u0d44-\u0d45\u0d49\u0d4e-\u0d56\u0d58-\u0d5f\u0d62-\u0d65\u0d70-\u0e00\u0e2f\u0e3b-\u0e3f\u0e4f\u0e5a-\u0e80\u0e83\u0e85-\u0e86\u0e89\u0e8b-\u0e8c\u0e8e-\u0e93\u0e98\u0ea0\u0ea4\u0ea6\u0ea8-\u0ea9\u0eac\u0eaf\u0eba\u0ebe-\u0ebf\u0ec5\u0ec7\u0ece-\u0ecf\u0eda-\u0f17\u0f1a-\u0f1f\u0f2a-\u0f34\u0f36\u0f38\u0f3a-\u0f3d\u0f48\u0f6a-\u0f70\u0f85\u0f8c-\u0f8f\u0f96\u0f98\u0fae-\u0fb0\u0fb8\u0fba-\u109f\u10c6-\u10cf\u10f7-\u10ff\u1101\u1104\u1108\u110a\u110d\u1113-\u113b\u113d\u113f\u1141-\u114b\u114d\u114f\u1151-\u1153\u1156-\u1158\u115a-\u115e\u1162\u1164\u1166\u1168\u116a-\u116c\u116f-\u1171\u1174\u1176-\u119d\u119f-\u11a7\u11a9-\u11aa\u11ac-\u11ad\u11b0-\u11b6\u11b9\u11bb\u11c3-\u11ea\u11ec-\u11ef\u11f1-\u11f8\u11fa-\u1dff\u1e9c-\u1e9f\u1efa-\u1eff\u1f16-\u1f17\u1f1e-\u1f1f\u1f46-\u1f47\u1f4e-\u1f4f\u1f58\u1f5a\u1f5c\u1f5e\u1f7e-\u1f7f\u1fb5\u1fbd\u1fbf-\u1fc1\u1fc5\u1fcd-\u1fcf\u1fd4-\u1fd5\u1fdc-\u1fdf\u1fed-\u1ff1\u1ff5\u1ffd-\u20cf\u20dd-\u20e0\u20e2-\u2125\u2127-\u2129\u212c-\u212d\u212f-\u217f\u2183-\u3004\u3006\u3008-\u3020\u3030\u3036-\u3040\u3095-\u3098\u309b-\u309c\u309f-\u30a0\u30fb\u30ff-\u3104\u312d-\u4dff\u9fa6-\uabff\ud7a4-\uffff]') nonXmlNameFirstBMPRegexp = re.compile('[\x00-@\\[-\\^`\\{-\xbf\xd7\xf7\u0132-\u0133\u013f-\u0140\u0149\u017f\u01c4-\u01cc\u01f1-\u01f3\u01f6-\u01f9\u0218-\u024f\u02a9-\u02ba\u02c2-\u0385\u0387\u038b\u038d\u03a2\u03cf\u03d7-\u03d9\u03db\u03dd\u03df\u03e1\u03f4-\u0400\u040d\u0450\u045d\u0482-\u048f\u04c5-\u04c6\u04c9-\u04ca\u04cd-\u04cf\u04ec-\u04ed\u04f6-\u04f7\u04fa-\u0530\u0557-\u0558\u055a-\u0560\u0587-\u05cf\u05eb-\u05ef\u05f3-\u0620\u063b-\u0640\u064b-\u0670\u06b8-\u06b9\u06bf\u06cf\u06d4\u06d6-\u06e4\u06e7-\u0904\u093a-\u093c\u093e-\u0957\u0962-\u0984\u098d-\u098e\u0991-\u0992\u09a9\u09b1\u09b3-\u09b5\u09ba-\u09db\u09de\u09e2-\u09ef\u09f2-\u0a04\u0a0b-\u0a0e\u0a11-\u0a12\u0a29\u0a31\u0a34\u0a37\u0a3a-\u0a58\u0a5d\u0a5f-\u0a71\u0a75-\u0a84\u0a8c\u0a8e\u0a92\u0aa9\u0ab1\u0ab4\u0aba-\u0abc\u0abe-\u0adf\u0ae1-\u0b04\u0b0d-\u0b0e\u0b11-\u0b12\u0b29\u0b31\u0b34-\u0b35\u0b3a-\u0b3c\u0b3e-\u0b5b\u0b5e\u0b62-\u0b84\u0b8b-\u0b8d\u0b91\u0b96-\u0b98\u0b9b\u0b9d\u0ba0-\u0ba2\u0ba5-\u0ba7\u0bab-\u0bad\u0bb6\u0bba-\u0c04\u0c0d\u0c11\u0c29\u0c34\u0c3a-\u0c5f\u0c62-\u0c84\u0c8d\u0c91\u0ca9\u0cb4\u0cba-\u0cdd\u0cdf\u0ce2-\u0d04\u0d0d\u0d11\u0d29\u0d3a-\u0d5f\u0d62-\u0e00\u0e2f\u0e31\u0e34-\u0e3f\u0e46-\u0e80\u0e83\u0e85-\u0e86\u0e89\u0e8b-\u0e8c\u0e8e-\u0e93\u0e98\u0ea0\u0ea4\u0ea6\u0ea8-\u0ea9\u0eac\u0eaf\u0eb1\u0eb4-\u0ebc\u0ebe-\u0ebf\u0ec5-\u0f3f\u0f48\u0f6a-\u109f\u10c6-\u10cf\u10f7-\u10ff\u1101\u1104\u1108\u110a\u110d\u1113-\u113b\u113d\u113f\u1141-\u114b\u114d\u114f\u1151-\u1153\u1156-\u1158\u115a-\u115e\u1162\u1164\u1166\u1168\u116a-\u116c\u116f-\u1171\u1174\u1176-\u119d\u119f-\u11a7\u11a9-\u11aa\u11ac-\u11ad\u11b0-\u11b6\u11b9\u11bb\u11c3-\u11ea\u11ec-\u11ef\u11f1-\u11f8\u11fa-\u1dff\u1e9c-\u1e9f\u1efa-\u1eff\u1f16-\u1f17\u1f1e-\u1f1f\u1f46-\u1f47\u1f4e-\u1f4f\u1f58\u1f5a\u1f5c\u1f5e\u1f7e-\u1f7f\u1fb5\u1fbd\u1fbf-\u1fc1\u1fc5\u1fcd-\u1fcf\u1fd4-\u1fd5\u1fdc-\u1fdf\u1fed-\u1ff1\u1ff5\u1ffd-\u2125\u2127-\u2129\u212c-\u212d\u212f-\u217f\u2183-\u3006\u3008-\u3020\u302a-\u3040\u3095-\u30a0\u30fb-\u3104\u312d-\u4dff\u9fa6-\uabff\ud7a4-\uffff]') # Simpler things nonPubidCharRegexp = re.compile("[^\x20\x0D\x0Aa-zA-Z0-9\-\'()+,./:=?;!*#@$_%]") class InfosetFilter(object): replacementRegexp = re.compile(r"U[\dA-F]{5,5}") def __init__(self, replaceChars=None, dropXmlnsLocalName=False, dropXmlnsAttrNs=False, preventDoubleDashComments=False, preventDashAtCommentEnd=False, replaceFormFeedCharacters=True, preventSingleQuotePubid=False): self.dropXmlnsLocalName = dropXmlnsLocalName self.dropXmlnsAttrNs = dropXmlnsAttrNs self.preventDoubleDashComments = preventDoubleDashComments self.preventDashAtCommentEnd = preventDashAtCommentEnd self.replaceFormFeedCharacters = replaceFormFeedCharacters self.preventSingleQuotePubid = preventSingleQuotePubid self.replaceCache = {} def coerceAttribute(self, name, namespace=None): if self.dropXmlnsLocalName and name.startswith("xmlns:"): warnings.warn("Attributes cannot begin with xmlns", DataLossWarning) return None elif (self.dropXmlnsAttrNs and namespace == "http://www.w3.org/2000/xmlns/"): warnings.warn("Attributes cannot be in the xml namespace", DataLossWarning) return None else: return self.toXmlName(name) def coerceElement(self, name, namespace=None): return self.toXmlName(name) def coerceComment(self, data): if self.preventDoubleDashComments: while "--" in data: warnings.warn("Comments cannot contain adjacent dashes", DataLossWarning) data = data.replace("--", "- -") return data def coerceCharacters(self, data): if self.replaceFormFeedCharacters: for i in range(data.count("\x0C")): warnings.warn("Text cannot contain U+000C", DataLossWarning) data = data.replace("\x0C", " ") # Other non-xml characters return data def coercePubid(self, data): dataOutput = data for char in nonPubidCharRegexp.findall(data): warnings.warn("Coercing non-XML pubid", DataLossWarning) replacement = self.getReplacementCharacter(char) dataOutput = dataOutput.replace(char, replacement) if self.preventSingleQuotePubid and dataOutput.find("'") >= 0: warnings.warn("Pubid cannot contain single quote", DataLossWarning) dataOutput = dataOutput.replace("'", self.getReplacementCharacter("'")) return dataOutput def toXmlName(self, name): nameFirst = name[0] nameRest = name[1:] m = nonXmlNameFirstBMPRegexp.match(nameFirst) if m: warnings.warn("Coercing non-XML name", DataLossWarning) nameFirstOutput = self.getReplacementCharacter(nameFirst) else: nameFirstOutput = nameFirst nameRestOutput = nameRest replaceChars = set(nonXmlNameBMPRegexp.findall(nameRest)) for char in replaceChars: warnings.warn("Coercing non-XML name", DataLossWarning) replacement = self.getReplacementCharacter(char) nameRestOutput = nameRestOutput.replace(char, replacement) return nameFirstOutput + nameRestOutput def getReplacementCharacter(self, char): if char in self.replaceCache: replacement = self.replaceCache[char] else: replacement = self.escapeChar(char) return replacement def fromXmlName(self, name): for item in set(self.replacementRegexp.findall(name)): name = name.replace(item, self.unescapeChar(item)) return name def escapeChar(self, char): replacement = "U%05X" % ord(char) self.replaceCache[char] = replacement return replacement def unescapeChar(self, charcode): return chr(int(charcode[1:], 16))
bsd-3-clause
oihane/odoo
openerp/tools/appdirs.py
376
19980
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2005-2010 ActiveState Software Inc. # Copyright (c) 2013 Eddy Petrișor """Utilities for determining application-specific dirs. See <http://github.com/ActiveState/appdirs> for details and usage. """ # Dev Notes: # - MSDN on where to store app data files: # http://support.microsoft.com/default.aspx?scid=kb;en-us;310294#XSLTH3194121123120121120120 # - Mac OS X: http://developer.apple.com/documentation/MacOSX/Conceptual/BPFileSystem/index.html # - XDG spec for Un*x: http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html __version_info__ = (1, 3, 0) __version__ = '.'.join(map(str, __version_info__)) import sys import os PY3 = sys.version_info[0] == 3 if PY3: unicode = str def user_data_dir(appname=None, appauthor=None, version=None, roaming=False): r"""Return full path to the user-specific data dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only required and used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be "<major>.<minor>". Only applied when appname is present. "roaming" (boolean, default False) can be set True to use the Windows roaming appdata directory. That means that for users on a Windows network setup for roaming profiles, this user data will be sync'd on login. See <http://technet.microsoft.com/en-us/library/cc766489(WS.10).aspx> for a discussion of issues. Typical user data directories are: Mac OS X: ~/Library/Application Support/<AppName> Unix: ~/.local/share/<AppName> # or in $XDG_DATA_HOME, if defined Win XP (not roaming): C:\Documents and Settings\<username>\Application Data\<AppAuthor>\<AppName> Win XP (roaming): C:\Documents and Settings\<username>\Local Settings\Application Data\<AppAuthor>\<AppName> Win 7 (not roaming): C:\Users\<username>\AppData\Local\<AppAuthor>\<AppName> Win 7 (roaming): C:\Users\<username>\AppData\Roaming\<AppAuthor>\<AppName> For Unix, we follow the XDG spec and support $XDG_DATA_HOME. That means, by deafult "~/.local/share/<AppName>". """ if sys.platform == "win32": if appauthor is None: appauthor = appname const = roaming and "CSIDL_APPDATA" or "CSIDL_LOCAL_APPDATA" path = os.path.normpath(_get_win_folder(const)) if appname: path = os.path.join(path, appauthor, appname) elif sys.platform == 'darwin': path = os.path.expanduser('~/Library/Application Support/') if appname: path = os.path.join(path, appname) else: path = os.getenv('XDG_DATA_HOME', os.path.expanduser("~/.local/share")) if appname: path = os.path.join(path, appname) if appname and version: path = os.path.join(path, version) return path def site_data_dir(appname=None, appauthor=None, version=None, multipath=False): """Return full path to the user-shared data dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only required and used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be "<major>.<minor>". Only applied when appname is present. "multipath" is an optional parameter only applicable to *nix which indicates that the entire list of data dirs should be returned. By default, the first item from XDG_DATA_DIRS is returned, or '/usr/local/share/<AppName>', if XDG_DATA_DIRS is not set Typical user data directories are: Mac OS X: /Library/Application Support/<AppName> Unix: /usr/local/share/<AppName> or /usr/share/<AppName> Win XP: C:\Documents and Settings\All Users\Application Data\<AppAuthor>\<AppName> Vista: (Fail! "C:\ProgramData" is a hidden *system* directory on Vista.) Win 7: C:\ProgramData\<AppAuthor>\<AppName> # Hidden, but writeable on Win 7. For Unix, this is using the $XDG_DATA_DIRS[0] default. WARNING: Do not use this on Windows. See the Vista-Fail note above for why. """ if sys.platform == "win32": if appauthor is None: appauthor = appname path = os.path.normpath(_get_win_folder("CSIDL_COMMON_APPDATA")) if appname: path = os.path.join(path, appauthor, appname) elif sys.platform == 'darwin': path = os.path.expanduser('/Library/Application Support') if appname: path = os.path.join(path, appname) else: # XDG default for $XDG_DATA_DIRS # only first, if multipath is False path = os.getenv('XDG_DATA_DIRS', os.pathsep.join(['/usr/local/share', '/usr/share'])) pathlist = [ os.path.expanduser(x.rstrip(os.sep)) for x in path.split(os.pathsep) ] if appname: if version: appname = os.path.join(appname, version) pathlist = [ os.sep.join([x, appname]) for x in pathlist ] if multipath: path = os.pathsep.join(pathlist) else: path = pathlist[0] return path if appname and version: path = os.path.join(path, version) return path def user_config_dir(appname=None, appauthor=None, version=None, roaming=False): r"""Return full path to the user-specific config dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only required and used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be "<major>.<minor>". Only applied when appname is present. "roaming" (boolean, default False) can be set True to use the Windows roaming appdata directory. That means that for users on a Windows network setup for roaming profiles, this user data will be sync'd on login. See <http://technet.microsoft.com/en-us/library/cc766489(WS.10).aspx> for a discussion of issues. Typical user data directories are: Mac OS X: same as user_data_dir Unix: ~/.config/<AppName> # or in $XDG_CONFIG_HOME, if defined Win *: same as user_data_dir For Unix, we follow the XDG spec and support $XDG_DATA_HOME. That means, by deafult "~/.local/share/<AppName>". """ if sys.platform in [ "win32", "darwin" ]: path = user_data_dir(appname, appauthor, None, roaming) else: path = os.getenv('XDG_CONFIG_HOME', os.path.expanduser("~/.config")) if appname: path = os.path.join(path, appname) if appname and version: path = os.path.join(path, version) return path def site_config_dir(appname=None, appauthor=None, version=None, multipath=False): """Return full path to the user-shared data dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only required and used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be "<major>.<minor>". Only applied when appname is present. "multipath" is an optional parameter only applicable to *nix which indicates that the entire list of config dirs should be returned. By default, the first item from XDG_CONFIG_DIRS is returned, or '/etc/xdg/<AppName>', if XDG_CONFIG_DIRS is not set Typical user data directories are: Mac OS X: same as site_data_dir Unix: /etc/xdg/<AppName> or $XDG_CONFIG_DIRS[i]/<AppName> for each value in $XDG_CONFIG_DIRS Win *: same as site_data_dir Vista: (Fail! "C:\ProgramData" is a hidden *system* directory on Vista.) For Unix, this is using the $XDG_CONFIG_DIRS[0] default, if multipath=False WARNING: Do not use this on Windows. See the Vista-Fail note above for why. """ if sys.platform in [ "win32", "darwin" ]: path = site_data_dir(appname, appauthor) if appname and version: path = os.path.join(path, version) else: # XDG default for $XDG_CONFIG_DIRS # only first, if multipath is False path = os.getenv('XDG_CONFIG_DIRS', '/etc/xdg') pathlist = [ os.path.expanduser(x.rstrip(os.sep)) for x in path.split(os.pathsep) ] if appname: if version: appname = os.path.join(appname, version) pathlist = [ os.sep.join([x, appname]) for x in pathlist ] if multipath: path = os.pathsep.join(pathlist) else: path = pathlist[0] return path def user_cache_dir(appname=None, appauthor=None, version=None, opinion=True): r"""Return full path to the user-specific cache dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only required and used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be "<major>.<minor>". Only applied when appname is present. "opinion" (boolean) can be False to disable the appending of "Cache" to the base app data dir for Windows. See discussion below. Typical user cache directories are: Mac OS X: ~/Library/Caches/<AppName> Unix: ~/.cache/<AppName> (XDG default) Win XP: C:\Documents and Settings\<username>\Local Settings\Application Data\<AppAuthor>\<AppName>\Cache Vista: C:\Users\<username>\AppData\Local\<AppAuthor>\<AppName>\Cache On Windows the only suggestion in the MSDN docs is that local settings go in the `CSIDL_LOCAL_APPDATA` directory. This is identical to the non-roaming app data dir (the default returned by `user_data_dir` above). Apps typically put cache data somewhere *under* the given dir here. Some examples: ...\Mozilla\Firefox\Profiles\<ProfileName>\Cache ...\Acme\SuperApp\Cache\1.0 OPINION: This function appends "Cache" to the `CSIDL_LOCAL_APPDATA` value. This can be disabled with the `opinion=False` option. """ if sys.platform == "win32": if appauthor is None: appauthor = appname path = os.path.normpath(_get_win_folder("CSIDL_LOCAL_APPDATA")) if appname: path = os.path.join(path, appauthor, appname) if opinion: path = os.path.join(path, "Cache") elif sys.platform == 'darwin': path = os.path.expanduser('~/Library/Caches') if appname: path = os.path.join(path, appname) else: path = os.getenv('XDG_CACHE_HOME', os.path.expanduser('~/.cache')) if appname: path = os.path.join(path, appname) if appname and version: path = os.path.join(path, version) return path def user_log_dir(appname=None, appauthor=None, version=None, opinion=True): r"""Return full path to the user-specific log dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only required and used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be "<major>.<minor>". Only applied when appname is present. "opinion" (boolean) can be False to disable the appending of "Logs" to the base app data dir for Windows, and "log" to the base cache dir for Unix. See discussion below. Typical user cache directories are: Mac OS X: ~/Library/Logs/<AppName> Unix: ~/.cache/<AppName>/log # or under $XDG_CACHE_HOME if defined Win XP: C:\Documents and Settings\<username>\Local Settings\Application Data\<AppAuthor>\<AppName>\Logs Vista: C:\Users\<username>\AppData\Local\<AppAuthor>\<AppName>\Logs On Windows the only suggestion in the MSDN docs is that local settings go in the `CSIDL_LOCAL_APPDATA` directory. (Note: I'm interested in examples of what some windows apps use for a logs dir.) OPINION: This function appends "Logs" to the `CSIDL_LOCAL_APPDATA` value for Windows and appends "log" to the user cache dir for Unix. This can be disabled with the `opinion=False` option. """ if sys.platform == "darwin": path = os.path.join( os.path.expanduser('~/Library/Logs'), appname) elif sys.platform == "win32": path = user_data_dir(appname, appauthor, version); version=False if opinion: path = os.path.join(path, "Logs") else: path = user_cache_dir(appname, appauthor, version); version=False if opinion: path = os.path.join(path, "log") if appname and version: path = os.path.join(path, version) return path class AppDirs(object): """Convenience wrapper for getting application dirs.""" def __init__(self, appname, appauthor=None, version=None, roaming=False, multipath=False): self.appname = appname self.appauthor = appauthor self.version = version self.roaming = roaming self.multipath = multipath @property def user_data_dir(self): return user_data_dir(self.appname, self.appauthor, version=self.version, roaming=self.roaming) @property def site_data_dir(self): return site_data_dir(self.appname, self.appauthor, version=self.version, multipath=self.multipath) @property def user_config_dir(self): return user_config_dir(self.appname, self.appauthor, version=self.version, roaming=self.roaming) @property def site_config_dir(self): return site_data_dir(self.appname, self.appauthor, version=self.version, multipath=self.multipath) @property def user_cache_dir(self): return user_cache_dir(self.appname, self.appauthor, version=self.version) @property def user_log_dir(self): return user_log_dir(self.appname, self.appauthor, version=self.version) #---- internal support stuff def _get_win_folder_from_registry(csidl_name): """This is a fallback technique at best. I'm not sure if using the registry for this guarantees us the correct answer for all CSIDL_* names. """ import _winreg shell_folder_name = { "CSIDL_APPDATA": "AppData", "CSIDL_COMMON_APPDATA": "Common AppData", "CSIDL_LOCAL_APPDATA": "Local AppData", }[csidl_name] key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders") dir, type = _winreg.QueryValueEx(key, shell_folder_name) return dir def _get_win_folder_with_pywin32(csidl_name): from win32com.shell import shellcon, shell dir = shell.SHGetFolderPath(0, getattr(shellcon, csidl_name), 0, 0) # Try to make this a unicode path because SHGetFolderPath does # not return unicode strings when there is unicode data in the # path. try: dir = unicode(dir) # Downgrade to short path name if have highbit chars. See # <http://bugs.activestate.com/show_bug.cgi?id=85099>. has_high_char = False for c in dir: if ord(c) > 255: has_high_char = True break if has_high_char: try: import win32api dir = win32api.GetShortPathName(dir) except ImportError: pass except UnicodeError: pass return dir def _get_win_folder_with_ctypes(csidl_name): import ctypes csidl_const = { "CSIDL_APPDATA": 26, "CSIDL_COMMON_APPDATA": 35, "CSIDL_LOCAL_APPDATA": 28, }[csidl_name] buf = ctypes.create_unicode_buffer(1024) ctypes.windll.shell32.SHGetFolderPathW(None, csidl_const, None, 0, buf) # Downgrade to short path name if have highbit chars. See # <http://bugs.activestate.com/show_bug.cgi?id=85099>. has_high_char = False for c in buf: if ord(c) > 255: has_high_char = True break if has_high_char: buf2 = ctypes.create_unicode_buffer(1024) if ctypes.windll.kernel32.GetShortPathNameW(buf.value, buf2, 1024): buf = buf2 return buf.value if sys.platform == "win32": try: import win32com.shell _get_win_folder = _get_win_folder_with_pywin32 except ImportError: try: import ctypes _get_win_folder = _get_win_folder_with_ctypes except ImportError: _get_win_folder = _get_win_folder_from_registry #---- self test code if __name__ == "__main__": appname = "MyApp" appauthor = "MyCompany" props = ("user_data_dir", "site_data_dir", "user_config_dir", "site_config_dir", "user_cache_dir", "user_log_dir") print("-- app dirs (with optional 'version')") dirs = AppDirs(appname, appauthor, version="1.0") for prop in props: print("%s: %s" % (prop, getattr(dirs, prop))) print("\n-- app dirs (without optional 'version')") dirs = AppDirs(appname, appauthor) for prop in props: print("%s: %s" % (prop, getattr(dirs, prop))) print("\n-- app dirs (without optional 'appauthor')") dirs = AppDirs(appname) for prop in props: print("%s: %s" % (prop, getattr(dirs, prop)))
agpl-3.0
Bulochkin/tensorflow_pack
tensorflow/contrib/bayesflow/python/kernel_tests/stochastic_gradient_estimators_test.py
87
7522
# 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. # ============================================================================== """Tests for stochastic graphs.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.contrib import distributions from tensorflow.contrib.bayesflow.python.ops import stochastic_gradient_estimators from tensorflow.contrib.bayesflow.python.ops import stochastic_tensor from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.ops import gradient_checker from tensorflow.python.ops import gradients_impl from tensorflow.python.ops import math_ops from tensorflow.python.ops import variables from tensorflow.python.platform import test st = stochastic_tensor sge = stochastic_gradient_estimators dists = distributions def _vimco(loss): """Python implementation of VIMCO.""" n = loss.shape[0] log_loss = np.log(loss) geometric_mean = [] for j in range(n): geometric_mean.append( np.exp(np.mean([log_loss[i, :] for i in range(n) if i != j], 0))) geometric_mean = np.array(geometric_mean) learning_signal = [] for j in range(n): learning_signal.append(np.sum([loss[i, :] for i in range(n) if i != j], 0)) learning_signal = np.array(learning_signal) local_learning_signal = np.log(1 / n * (learning_signal + geometric_mean)) # log_mean - local_learning_signal log_mean = np.log(np.mean(loss, 0)) advantage = log_mean - local_learning_signal return advantage class StochasticGradientEstimatorsTest(test.TestCase): def setUp(self): self._p = constant_op.constant(0.999999) self._final_loss = constant_op.constant(3.2) def _testScoreFunction(self, loss_fn, expected): x = st.StochasticTensor(dists.Bernoulli(probs=self._p), loss_fn=loss_fn) sf = x.loss(self._final_loss) with self.test_session() as sess: sess.run(variables.global_variables_initializer()) self.assertAllClose(*sess.run([expected, sf])) def testScoreFunction(self): expected = math_ops.log(self._p) * self._final_loss self._testScoreFunction(sge.score_function, expected) def testScoreFunctionWithConstantBaseline(self): b = constant_op.constant(9.8) expected = math_ops.log(self._p) * (self._final_loss - b) self._testScoreFunction( sge.get_score_function_with_constant_baseline(b), expected) def testScoreFunctionWithBaselineFn(self): b = constant_op.constant(9.8) def baseline_fn(stoch_tensor, loss): self.assertTrue(isinstance(stoch_tensor, st.StochasticTensor)) self.assertTrue(isinstance(loss, ops.Tensor)) return b expected = math_ops.log(self._p) * (self._final_loss - b) self._testScoreFunction( sge.get_score_function_with_baseline(baseline_fn), expected) def testScoreFunctionWithMeanBaseline(self): ema_decay = 0.8 num_steps = 6 x = st.StochasticTensor( dists.Bernoulli(probs=self._p), loss_fn=sge.get_score_function_with_baseline( sge.get_mean_baseline(ema_decay))) sf = x.loss(self._final_loss) # Expected EMA value ema = 0. for _ in range(num_steps): ema -= (1. - ema_decay) * (ema - self._final_loss) # Baseline is EMA with bias correction bias_correction = 1. - ema_decay**num_steps baseline = ema / bias_correction expected = math_ops.log(self._p) * (self._final_loss - baseline) with self.test_session() as sess: sess.run(variables.global_variables_initializer()) for _ in range(num_steps - 1): sess.run(sf) # run to update EMA self.assertAllClose(*sess.run([expected, sf])) def testScoreFunctionWithAdvantageFn(self): b = constant_op.constant(9.8) def advantage_fn(stoch_tensor, loss): self.assertTrue(isinstance(stoch_tensor, st.StochasticTensor)) self.assertTrue(isinstance(loss, ops.Tensor)) return loss - b expected = math_ops.log(self._p) * (self._final_loss - b) self._testScoreFunction( sge.get_score_function_with_advantage(advantage_fn), expected) def testVIMCOAdvantageFn(self): # simple_loss: (3, 2) with 3 samples, batch size 2 simple_loss = np.array( [[1.0, 1.5], [1e-6, 1e4], [2.0, 3.0]]) # random_loss: (100, 50, 64) with 100 samples, batch shape (50, 64) random_loss = 100 * np.random.rand(100, 50, 64) advantage_fn = sge.get_vimco_advantage_fn(have_log_loss=False) with self.test_session() as sess: for loss in [simple_loss, random_loss]: expected = _vimco(loss) loss_t = constant_op.constant(loss, dtype=dtypes.float32) advantage_t = advantage_fn(None, loss_t) # ST is not used advantage = sess.run(advantage_t) self.assertEqual(expected.shape, advantage_t.get_shape()) self.assertAllClose(expected, advantage, atol=5e-5) def testVIMCOAdvantageGradients(self): loss = np.log( [[1.0, 1.5], [1e-6, 1e4], [2.0, 3.0]]) advantage_fn = sge.get_vimco_advantage_fn(have_log_loss=True) with self.test_session(): loss_t = constant_op.constant(loss, dtype=dtypes.float64) advantage_t = advantage_fn(None, loss_t) # ST is not used gradient_error = gradient_checker.compute_gradient_error( loss_t, loss_t.get_shape().as_list(), advantage_t, advantage_t.get_shape().as_list(), x_init_value=loss) self.assertLess(gradient_error, 1e-3) def testVIMCOAdvantageWithSmallProbabilities(self): theta_value = np.random.rand(10, 100000) # Test with float16 dtype to ensure stability even in this extreme case. theta = constant_op.constant(theta_value, dtype=dtypes.float16) advantage_fn = sge.get_vimco_advantage_fn(have_log_loss=True) with self.test_session() as sess: log_loss = -math_ops.reduce_sum(theta, [1]) advantage_t = advantage_fn(None, log_loss) grad_t = gradients_impl.gradients(advantage_t, theta)[0] advantage, grad = sess.run((advantage_t, grad_t)) self.assertTrue(np.all(np.isfinite(advantage))) self.assertTrue(np.all(np.isfinite(grad))) def testScoreFunctionWithMeanBaselineHasUniqueVarScope(self): ema_decay = 0.8 x = st.StochasticTensor( dists.Bernoulli(probs=self._p), loss_fn=sge.get_score_function_with_baseline( sge.get_mean_baseline(ema_decay))) y = st.StochasticTensor( dists.Bernoulli(probs=self._p), loss_fn=sge.get_score_function_with_baseline( sge.get_mean_baseline(ema_decay))) sf_x = x.loss(self._final_loss) sf_y = y.loss(self._final_loss) with self.test_session() as sess: # Smoke test sess.run(variables.global_variables_initializer()) sess.run([sf_x, sf_y]) if __name__ == "__main__": test.main()
apache-2.0
treejames/viewfinder
marketing/tornado/test/ioloop_test.py
25
12135
#!/usr/bin/env python from __future__ import absolute_import, division, print_function, with_statement import contextlib import datetime import functools import socket import sys import threading import time from tornado import gen from tornado.ioloop import IOLoop, TimeoutError from tornado.stack_context import ExceptionStackContext, StackContext, wrap, NullContext from tornado.testing import AsyncTestCase, bind_unused_port from tornado.test.util import unittest, skipIfNonUnix, skipOnTravis try: from concurrent import futures except ImportError: futures = None class TestIOLoop(AsyncTestCase): @skipOnTravis def test_add_callback_wakeup(self): # Make sure that add_callback from inside a running IOLoop # wakes up the IOLoop immediately instead of waiting for a timeout. def callback(): self.called = True self.stop() def schedule_callback(): self.called = False self.io_loop.add_callback(callback) # Store away the time so we can check if we woke up immediately self.start_time = time.time() self.io_loop.add_timeout(self.io_loop.time(), schedule_callback) self.wait() self.assertAlmostEqual(time.time(), self.start_time, places=2) self.assertTrue(self.called) @skipOnTravis def test_add_callback_wakeup_other_thread(self): def target(): # sleep a bit to let the ioloop go into its poll loop time.sleep(0.01) self.stop_time = time.time() self.io_loop.add_callback(self.stop) thread = threading.Thread(target=target) self.io_loop.add_callback(thread.start) self.wait() self.assertAlmostEqual(time.time(), self.stop_time, places=2) thread.join() def test_add_timeout_timedelta(self): self.io_loop.add_timeout(datetime.timedelta(microseconds=1), self.stop) self.wait() def test_multiple_add(self): sock, port = bind_unused_port() try: self.io_loop.add_handler(sock.fileno(), lambda fd, events: None, IOLoop.READ) # Attempting to add the same handler twice fails # (with a platform-dependent exception) self.assertRaises(Exception, self.io_loop.add_handler, sock.fileno(), lambda fd, events: None, IOLoop.READ) finally: self.io_loop.remove_handler(sock.fileno()) sock.close() def test_remove_without_add(self): # remove_handler should not throw an exception if called on an fd # was never added. sock, port = bind_unused_port() try: self.io_loop.remove_handler(sock.fileno()) finally: sock.close() def test_add_callback_from_signal(self): # cheat a little bit and just run this normally, since we can't # easily simulate the races that happen with real signal handlers self.io_loop.add_callback_from_signal(self.stop) self.wait() def test_add_callback_from_signal_other_thread(self): # Very crude test, just to make sure that we cover this case. # This also happens to be the first test where we run an IOLoop in # a non-main thread. other_ioloop = IOLoop() thread = threading.Thread(target=other_ioloop.start) thread.start() other_ioloop.add_callback_from_signal(other_ioloop.stop) thread.join() other_ioloop.close() def test_add_callback_while_closing(self): # Issue #635: add_callback() should raise a clean exception # if called while another thread is closing the IOLoop. closing = threading.Event() def target(): other_ioloop.add_callback(other_ioloop.stop) other_ioloop.start() closing.set() other_ioloop.close(all_fds=True) other_ioloop = IOLoop() thread = threading.Thread(target=target) thread.start() closing.wait() for i in range(1000): try: other_ioloop.add_callback(lambda: None) except RuntimeError as e: self.assertEqual("IOLoop is closing", str(e)) break def test_handle_callback_exception(self): # IOLoop.handle_callback_exception can be overridden to catch # exceptions in callbacks. def handle_callback_exception(callback): self.assertIs(sys.exc_info()[0], ZeroDivisionError) self.stop() self.io_loop.handle_callback_exception = handle_callback_exception with NullContext(): # remove the test StackContext that would see this uncaught # exception as a test failure. self.io_loop.add_callback(lambda: 1 / 0) self.wait() @skipIfNonUnix # just because socketpair is so convenient def test_read_while_writeable(self): # Ensure that write events don't come in while we're waiting for # a read and haven't asked for writeability. (the reverse is # difficult to test for) client, server = socket.socketpair() try: def handler(fd, events): self.assertEqual(events, IOLoop.READ) self.stop() self.io_loop.add_handler(client.fileno(), handler, IOLoop.READ) self.io_loop.add_timeout(self.io_loop.time() + 0.01, functools.partial(server.send, b'asdf')) self.wait() self.io_loop.remove_handler(client.fileno()) finally: client.close() server.close() def test_remove_timeout_after_fire(self): # It is not an error to call remove_timeout after it has run. handle = self.io_loop.add_timeout(self.io_loop.time(), self.stop()) self.wait() self.io_loop.remove_timeout(handle) def test_remove_timeout_cleanup(self): # Add and remove enough callbacks to trigger cleanup. # Not a very thorough test, but it ensures that the cleanup code # gets executed and doesn't blow up. This test is only really useful # on PollIOLoop subclasses, but it should run silently on any # implementation. for i in range(2000): timeout = self.io_loop.add_timeout(self.io_loop.time() + 3600, lambda: None) self.io_loop.remove_timeout(timeout) # HACK: wait two IOLoop iterations for the GC to happen. self.io_loop.add_callback(lambda: self.io_loop.add_callback(self.stop)) self.wait() # Deliberately not a subclass of AsyncTestCase so the IOLoop isn't # automatically set as current. class TestIOLoopCurrent(unittest.TestCase): def setUp(self): self.io_loop = IOLoop() def tearDown(self): self.io_loop.close() def test_current(self): def f(): self.current_io_loop = IOLoop.current() self.io_loop.stop() self.io_loop.add_callback(f) self.io_loop.start() self.assertIs(self.current_io_loop, self.io_loop) class TestIOLoopAddCallback(AsyncTestCase): def setUp(self): super(TestIOLoopAddCallback, self).setUp() self.active_contexts = [] def add_callback(self, callback, *args, **kwargs): self.io_loop.add_callback(callback, *args, **kwargs) @contextlib.contextmanager def context(self, name): self.active_contexts.append(name) yield self.assertEqual(self.active_contexts.pop(), name) def test_pre_wrap(self): # A pre-wrapped callback is run in the context in which it was # wrapped, not when it was added to the IOLoop. def f1(): self.assertIn('c1', self.active_contexts) self.assertNotIn('c2', self.active_contexts) self.stop() with StackContext(functools.partial(self.context, 'c1')): wrapped = wrap(f1) with StackContext(functools.partial(self.context, 'c2')): self.add_callback(wrapped) self.wait() def test_pre_wrap_with_args(self): # Same as test_pre_wrap, but the function takes arguments. # Implementation note: The function must not be wrapped in a # functools.partial until after it has been passed through # stack_context.wrap def f1(foo, bar): self.assertIn('c1', self.active_contexts) self.assertNotIn('c2', self.active_contexts) self.stop((foo, bar)) with StackContext(functools.partial(self.context, 'c1')): wrapped = wrap(f1) with StackContext(functools.partial(self.context, 'c2')): self.add_callback(wrapped, 1, bar=2) result = self.wait() self.assertEqual(result, (1, 2)) class TestIOLoopAddCallbackFromSignal(TestIOLoopAddCallback): # Repeat the add_callback tests using add_callback_from_signal def add_callback(self, callback, *args, **kwargs): self.io_loop.add_callback_from_signal(callback, *args, **kwargs) @unittest.skipIf(futures is None, "futures module not present") class TestIOLoopFutures(AsyncTestCase): def test_add_future_threads(self): with futures.ThreadPoolExecutor(1) as pool: self.io_loop.add_future(pool.submit(lambda: None), lambda future: self.stop(future)) future = self.wait() self.assertTrue(future.done()) self.assertTrue(future.result() is None) def test_add_future_stack_context(self): ready = threading.Event() def task(): # we must wait for the ioloop callback to be scheduled before # the task completes to ensure that add_future adds the callback # asynchronously (which is the scenario in which capturing # the stack_context matters) ready.wait(1) assert ready.isSet(), "timed out" raise Exception("worker") def callback(future): self.future = future raise Exception("callback") def handle_exception(typ, value, traceback): self.exception = value self.stop() return True # stack_context propagates to the ioloop callback, but the worker # task just has its exceptions caught and saved in the Future. with futures.ThreadPoolExecutor(1) as pool: with ExceptionStackContext(handle_exception): self.io_loop.add_future(pool.submit(task), callback) ready.set() self.wait() self.assertEqual(self.exception.args[0], "callback") self.assertEqual(self.future.exception().args[0], "worker") class TestIOLoopRunSync(unittest.TestCase): def setUp(self): self.io_loop = IOLoop() def tearDown(self): self.io_loop.close() def test_sync_result(self): self.assertEqual(self.io_loop.run_sync(lambda: 42), 42) def test_sync_exception(self): with self.assertRaises(ZeroDivisionError): self.io_loop.run_sync(lambda: 1 / 0) def test_async_result(self): @gen.coroutine def f(): yield gen.Task(self.io_loop.add_callback) raise gen.Return(42) self.assertEqual(self.io_loop.run_sync(f), 42) def test_async_exception(self): @gen.coroutine def f(): yield gen.Task(self.io_loop.add_callback) 1 / 0 with self.assertRaises(ZeroDivisionError): self.io_loop.run_sync(f) def test_current(self): def f(): self.assertIs(IOLoop.current(), self.io_loop) self.io_loop.run_sync(f) def test_timeout(self): @gen.coroutine def f(): yield gen.Task(self.io_loop.add_timeout, self.io_loop.time() + 1) self.assertRaises(TimeoutError, self.io_loop.run_sync, f, timeout=0.01) if __name__ == "__main__": unittest.main()
apache-2.0
daliguro/tf101-kernel-test
tools/perf/scripts/python/netdev-times.py
11271
15048
# Display a process of packets and processed time. # It helps us to investigate networking or network device. # # options # tx: show only tx chart # rx: show only rx chart # dev=: show only thing related to specified device # debug: work with debug mode. It shows buffer status. import os import sys sys.path.append(os.environ['PERF_EXEC_PATH'] + \ '/scripts/python/Perf-Trace-Util/lib/Perf/Trace') from perf_trace_context import * from Core import * from Util import * all_event_list = []; # insert all tracepoint event related with this script irq_dic = {}; # key is cpu and value is a list which stacks irqs # which raise NET_RX softirq net_rx_dic = {}; # key is cpu and value include time of NET_RX softirq-entry # and a list which stacks receive receive_hunk_list = []; # a list which include a sequence of receive events rx_skb_list = []; # received packet list for matching # skb_copy_datagram_iovec buffer_budget = 65536; # the budget of rx_skb_list, tx_queue_list and # tx_xmit_list of_count_rx_skb_list = 0; # overflow count tx_queue_list = []; # list of packets which pass through dev_queue_xmit of_count_tx_queue_list = 0; # overflow count tx_xmit_list = []; # list of packets which pass through dev_hard_start_xmit of_count_tx_xmit_list = 0; # overflow count tx_free_list = []; # list of packets which is freed # options show_tx = 0; show_rx = 0; dev = 0; # store a name of device specified by option "dev=" debug = 0; # indices of event_info tuple EINFO_IDX_NAME= 0 EINFO_IDX_CONTEXT=1 EINFO_IDX_CPU= 2 EINFO_IDX_TIME= 3 EINFO_IDX_PID= 4 EINFO_IDX_COMM= 5 # Calculate a time interval(msec) from src(nsec) to dst(nsec) def diff_msec(src, dst): return (dst - src) / 1000000.0 # Display a process of transmitting a packet def print_transmit(hunk): if dev != 0 and hunk['dev'].find(dev) < 0: return print "%7s %5d %6d.%06dsec %12.3fmsec %12.3fmsec" % \ (hunk['dev'], hunk['len'], nsecs_secs(hunk['queue_t']), nsecs_nsecs(hunk['queue_t'])/1000, diff_msec(hunk['queue_t'], hunk['xmit_t']), diff_msec(hunk['xmit_t'], hunk['free_t'])) # Format for displaying rx packet processing PF_IRQ_ENTRY= " irq_entry(+%.3fmsec irq=%d:%s)" PF_SOFT_ENTRY=" softirq_entry(+%.3fmsec)" PF_NAPI_POLL= " napi_poll_exit(+%.3fmsec %s)" PF_JOINT= " |" PF_WJOINT= " | |" PF_NET_RECV= " |---netif_receive_skb(+%.3fmsec skb=%x len=%d)" PF_NET_RX= " |---netif_rx(+%.3fmsec skb=%x)" PF_CPY_DGRAM= " | skb_copy_datagram_iovec(+%.3fmsec %d:%s)" PF_KFREE_SKB= " | kfree_skb(+%.3fmsec location=%x)" PF_CONS_SKB= " | consume_skb(+%.3fmsec)" # Display a process of received packets and interrputs associated with # a NET_RX softirq def print_receive(hunk): show_hunk = 0 irq_list = hunk['irq_list'] cpu = irq_list[0]['cpu'] base_t = irq_list[0]['irq_ent_t'] # check if this hunk should be showed if dev != 0: for i in range(len(irq_list)): if irq_list[i]['name'].find(dev) >= 0: show_hunk = 1 break else: show_hunk = 1 if show_hunk == 0: return print "%d.%06dsec cpu=%d" % \ (nsecs_secs(base_t), nsecs_nsecs(base_t)/1000, cpu) for i in range(len(irq_list)): print PF_IRQ_ENTRY % \ (diff_msec(base_t, irq_list[i]['irq_ent_t']), irq_list[i]['irq'], irq_list[i]['name']) print PF_JOINT irq_event_list = irq_list[i]['event_list'] for j in range(len(irq_event_list)): irq_event = irq_event_list[j] if irq_event['event'] == 'netif_rx': print PF_NET_RX % \ (diff_msec(base_t, irq_event['time']), irq_event['skbaddr']) print PF_JOINT print PF_SOFT_ENTRY % \ diff_msec(base_t, hunk['sirq_ent_t']) print PF_JOINT event_list = hunk['event_list'] for i in range(len(event_list)): event = event_list[i] if event['event_name'] == 'napi_poll': print PF_NAPI_POLL % \ (diff_msec(base_t, event['event_t']), event['dev']) if i == len(event_list) - 1: print "" else: print PF_JOINT else: print PF_NET_RECV % \ (diff_msec(base_t, event['event_t']), event['skbaddr'], event['len']) if 'comm' in event.keys(): print PF_WJOINT print PF_CPY_DGRAM % \ (diff_msec(base_t, event['comm_t']), event['pid'], event['comm']) elif 'handle' in event.keys(): print PF_WJOINT if event['handle'] == "kfree_skb": print PF_KFREE_SKB % \ (diff_msec(base_t, event['comm_t']), event['location']) elif event['handle'] == "consume_skb": print PF_CONS_SKB % \ diff_msec(base_t, event['comm_t']) print PF_JOINT def trace_begin(): global show_tx global show_rx global dev global debug for i in range(len(sys.argv)): if i == 0: continue arg = sys.argv[i] if arg == 'tx': show_tx = 1 elif arg =='rx': show_rx = 1 elif arg.find('dev=',0, 4) >= 0: dev = arg[4:] elif arg == 'debug': debug = 1 if show_tx == 0 and show_rx == 0: show_tx = 1 show_rx = 1 def trace_end(): # order all events in time all_event_list.sort(lambda a,b :cmp(a[EINFO_IDX_TIME], b[EINFO_IDX_TIME])) # process all events for i in range(len(all_event_list)): event_info = all_event_list[i] name = event_info[EINFO_IDX_NAME] if name == 'irq__softirq_exit': handle_irq_softirq_exit(event_info) elif name == 'irq__softirq_entry': handle_irq_softirq_entry(event_info) elif name == 'irq__softirq_raise': handle_irq_softirq_raise(event_info) elif name == 'irq__irq_handler_entry': handle_irq_handler_entry(event_info) elif name == 'irq__irq_handler_exit': handle_irq_handler_exit(event_info) elif name == 'napi__napi_poll': handle_napi_poll(event_info) elif name == 'net__netif_receive_skb': handle_netif_receive_skb(event_info) elif name == 'net__netif_rx': handle_netif_rx(event_info) elif name == 'skb__skb_copy_datagram_iovec': handle_skb_copy_datagram_iovec(event_info) elif name == 'net__net_dev_queue': handle_net_dev_queue(event_info) elif name == 'net__net_dev_xmit': handle_net_dev_xmit(event_info) elif name == 'skb__kfree_skb': handle_kfree_skb(event_info) elif name == 'skb__consume_skb': handle_consume_skb(event_info) # display receive hunks if show_rx: for i in range(len(receive_hunk_list)): print_receive(receive_hunk_list[i]) # display transmit hunks if show_tx: print " dev len Qdisc " \ " netdevice free" for i in range(len(tx_free_list)): print_transmit(tx_free_list[i]) if debug: print "debug buffer status" print "----------------------------" print "xmit Qdisc:remain:%d overflow:%d" % \ (len(tx_queue_list), of_count_tx_queue_list) print "xmit netdevice:remain:%d overflow:%d" % \ (len(tx_xmit_list), of_count_tx_xmit_list) print "receive:remain:%d overflow:%d" % \ (len(rx_skb_list), of_count_rx_skb_list) # called from perf, when it finds a correspoinding event def irq__softirq_entry(name, context, cpu, sec, nsec, pid, comm, vec): if symbol_str("irq__softirq_entry", "vec", vec) != "NET_RX": return event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, vec) all_event_list.append(event_info) def irq__softirq_exit(name, context, cpu, sec, nsec, pid, comm, vec): if symbol_str("irq__softirq_entry", "vec", vec) != "NET_RX": return event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, vec) all_event_list.append(event_info) def irq__softirq_raise(name, context, cpu, sec, nsec, pid, comm, vec): if symbol_str("irq__softirq_entry", "vec", vec) != "NET_RX": return event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, vec) all_event_list.append(event_info) def irq__irq_handler_entry(name, context, cpu, sec, nsec, pid, comm, irq, irq_name): event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, irq, irq_name) all_event_list.append(event_info) def irq__irq_handler_exit(name, context, cpu, sec, nsec, pid, comm, irq, ret): event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, irq, ret) all_event_list.append(event_info) def napi__napi_poll(name, context, cpu, sec, nsec, pid, comm, napi, dev_name): event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, napi, dev_name) all_event_list.append(event_info) def net__netif_receive_skb(name, context, cpu, sec, nsec, pid, comm, skbaddr, skblen, dev_name): event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, skbaddr, skblen, dev_name) all_event_list.append(event_info) def net__netif_rx(name, context, cpu, sec, nsec, pid, comm, skbaddr, skblen, dev_name): event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, skbaddr, skblen, dev_name) all_event_list.append(event_info) def net__net_dev_queue(name, context, cpu, sec, nsec, pid, comm, skbaddr, skblen, dev_name): event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, skbaddr, skblen, dev_name) all_event_list.append(event_info) def net__net_dev_xmit(name, context, cpu, sec, nsec, pid, comm, skbaddr, skblen, rc, dev_name): event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, skbaddr, skblen, rc ,dev_name) all_event_list.append(event_info) def skb__kfree_skb(name, context, cpu, sec, nsec, pid, comm, skbaddr, protocol, location): event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, skbaddr, protocol, location) all_event_list.append(event_info) def skb__consume_skb(name, context, cpu, sec, nsec, pid, comm, skbaddr): event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, skbaddr) all_event_list.append(event_info) def skb__skb_copy_datagram_iovec(name, context, cpu, sec, nsec, pid, comm, skbaddr, skblen): event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, skbaddr, skblen) all_event_list.append(event_info) def handle_irq_handler_entry(event_info): (name, context, cpu, time, pid, comm, irq, irq_name) = event_info if cpu not in irq_dic.keys(): irq_dic[cpu] = [] irq_record = {'irq':irq, 'name':irq_name, 'cpu':cpu, 'irq_ent_t':time} irq_dic[cpu].append(irq_record) def handle_irq_handler_exit(event_info): (name, context, cpu, time, pid, comm, irq, ret) = event_info if cpu not in irq_dic.keys(): return irq_record = irq_dic[cpu].pop() if irq != irq_record['irq']: return irq_record.update({'irq_ext_t':time}) # if an irq doesn't include NET_RX softirq, drop. if 'event_list' in irq_record.keys(): irq_dic[cpu].append(irq_record) def handle_irq_softirq_raise(event_info): (name, context, cpu, time, pid, comm, vec) = event_info if cpu not in irq_dic.keys() \ or len(irq_dic[cpu]) == 0: return irq_record = irq_dic[cpu].pop() if 'event_list' in irq_record.keys(): irq_event_list = irq_record['event_list'] else: irq_event_list = [] irq_event_list.append({'time':time, 'event':'sirq_raise'}) irq_record.update({'event_list':irq_event_list}) irq_dic[cpu].append(irq_record) def handle_irq_softirq_entry(event_info): (name, context, cpu, time, pid, comm, vec) = event_info net_rx_dic[cpu] = {'sirq_ent_t':time, 'event_list':[]} def handle_irq_softirq_exit(event_info): (name, context, cpu, time, pid, comm, vec) = event_info irq_list = [] event_list = 0 if cpu in irq_dic.keys(): irq_list = irq_dic[cpu] del irq_dic[cpu] if cpu in net_rx_dic.keys(): sirq_ent_t = net_rx_dic[cpu]['sirq_ent_t'] event_list = net_rx_dic[cpu]['event_list'] del net_rx_dic[cpu] if irq_list == [] or event_list == 0: return rec_data = {'sirq_ent_t':sirq_ent_t, 'sirq_ext_t':time, 'irq_list':irq_list, 'event_list':event_list} # merge information realted to a NET_RX softirq receive_hunk_list.append(rec_data) def handle_napi_poll(event_info): (name, context, cpu, time, pid, comm, napi, dev_name) = event_info if cpu in net_rx_dic.keys(): event_list = net_rx_dic[cpu]['event_list'] rec_data = {'event_name':'napi_poll', 'dev':dev_name, 'event_t':time} event_list.append(rec_data) def handle_netif_rx(event_info): (name, context, cpu, time, pid, comm, skbaddr, skblen, dev_name) = event_info if cpu not in irq_dic.keys() \ or len(irq_dic[cpu]) == 0: return irq_record = irq_dic[cpu].pop() if 'event_list' in irq_record.keys(): irq_event_list = irq_record['event_list'] else: irq_event_list = [] irq_event_list.append({'time':time, 'event':'netif_rx', 'skbaddr':skbaddr, 'skblen':skblen, 'dev_name':dev_name}) irq_record.update({'event_list':irq_event_list}) irq_dic[cpu].append(irq_record) def handle_netif_receive_skb(event_info): global of_count_rx_skb_list (name, context, cpu, time, pid, comm, skbaddr, skblen, dev_name) = event_info if cpu in net_rx_dic.keys(): rec_data = {'event_name':'netif_receive_skb', 'event_t':time, 'skbaddr':skbaddr, 'len':skblen} event_list = net_rx_dic[cpu]['event_list'] event_list.append(rec_data) rx_skb_list.insert(0, rec_data) if len(rx_skb_list) > buffer_budget: rx_skb_list.pop() of_count_rx_skb_list += 1 def handle_net_dev_queue(event_info): global of_count_tx_queue_list (name, context, cpu, time, pid, comm, skbaddr, skblen, dev_name) = event_info skb = {'dev':dev_name, 'skbaddr':skbaddr, 'len':skblen, 'queue_t':time} tx_queue_list.insert(0, skb) if len(tx_queue_list) > buffer_budget: tx_queue_list.pop() of_count_tx_queue_list += 1 def handle_net_dev_xmit(event_info): global of_count_tx_xmit_list (name, context, cpu, time, pid, comm, skbaddr, skblen, rc, dev_name) = event_info if rc == 0: # NETDEV_TX_OK for i in range(len(tx_queue_list)): skb = tx_queue_list[i] if skb['skbaddr'] == skbaddr: skb['xmit_t'] = time tx_xmit_list.insert(0, skb) del tx_queue_list[i] if len(tx_xmit_list) > buffer_budget: tx_xmit_list.pop() of_count_tx_xmit_list += 1 return def handle_kfree_skb(event_info): (name, context, cpu, time, pid, comm, skbaddr, protocol, location) = event_info for i in range(len(tx_queue_list)): skb = tx_queue_list[i] if skb['skbaddr'] == skbaddr: del tx_queue_list[i] return for i in range(len(tx_xmit_list)): skb = tx_xmit_list[i] if skb['skbaddr'] == skbaddr: skb['free_t'] = time tx_free_list.append(skb) del tx_xmit_list[i] return for i in range(len(rx_skb_list)): rec_data = rx_skb_list[i] if rec_data['skbaddr'] == skbaddr: rec_data.update({'handle':"kfree_skb", 'comm':comm, 'pid':pid, 'comm_t':time}) del rx_skb_list[i] return def handle_consume_skb(event_info): (name, context, cpu, time, pid, comm, skbaddr) = event_info for i in range(len(tx_xmit_list)): skb = tx_xmit_list[i] if skb['skbaddr'] == skbaddr: skb['free_t'] = time tx_free_list.append(skb) del tx_xmit_list[i] return def handle_skb_copy_datagram_iovec(event_info): (name, context, cpu, time, pid, comm, skbaddr, skblen) = event_info for i in range(len(rx_skb_list)): rec_data = rx_skb_list[i] if skbaddr == rec_data['skbaddr']: rec_data.update({'handle':"skb_copy_datagram_iovec", 'comm':comm, 'pid':pid, 'comm_t':time}) del rx_skb_list[i] return
gpl-2.0
tensorflow/graphics
tensorflow_graphics/rendering/tests/cpu_rasterization_backend_test.py
1
1133
# Copyright 2020 The TensorFlow Authors # # 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 # # https://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 """Tests for the rasterization_backend.""" from tensorflow_graphics.rendering import rasterization_backend from tensorflow_graphics.rendering.tests import rasterization_backend_test_base from tensorflow_graphics.util import test_case class CPURasterizationBackendTest( rasterization_backend_test_base.RasterizationBackendTestBase): def setUp(self): super(CPURasterizationBackendTest, self).setUp() self._backend = rasterization_backend.RasterizationBackends.CPU if __name__ == '__main__': test_case.main()
apache-2.0
schoonc/AutobahnPython
examples/asyncio/wamp/pubsub/decorators/backend.py
8
2308
############################################################################### # # The MIT License (MIT) # # Copyright (c) Tavendo GmbH # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # ############################################################################### from os import environ try: import asyncio except ImportError: # Trollius >= 0.3 was renamed import trollius as asyncio from autobahn.asyncio.wamp import ApplicationSession, ApplicationRunner class Component(ApplicationSession): """ An application component that publishes an event every second. """ @asyncio.coroutine def onJoin(self, details): counter = 0 while True: print("publish: com.myapp.topic1", counter) self.publish(u'com.myapp.topic1', counter) print("publish: com.myapp.topic2 'Hello world.'") self.publish(u'com.myapp.topic2', "Hello world.") counter += 1 yield from asyncio.sleep(1) if __name__ == '__main__': runner = ApplicationRunner( environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws"), u"crossbardemo", debug_wamp=False, # optional; log many WAMP details debug=False, # optional; log even more details ) runner.run(Component)
mit
nzavagli/UnrealPy
UnrealPyEmbed/Source/Python/Lib/python27/test/test_bufio.py
125
2755
import unittest from test import test_support as support import io # C implementation. import _pyio as pyio # Python implementation. # Simple test to ensure that optimizations in the IO library deliver the # expected results. For best testing, run this under a debug-build Python too # (to exercise asserts in the C code). lengths = list(range(1, 257)) + [512, 1000, 1024, 2048, 4096, 8192, 10000, 16384, 32768, 65536, 1000000] class BufferSizeTest(unittest.TestCase): def try_one(self, s): # Write s + "\n" + s to file, then open it and ensure that successive # .readline()s deliver what we wrote. # Ensure we can open TESTFN for writing. support.unlink(support.TESTFN) # Since C doesn't guarantee we can write/read arbitrary bytes in text # files, use binary mode. f = self.open(support.TESTFN, "wb") try: # write once with \n and once without f.write(s) f.write(b"\n") f.write(s) f.close() f = open(support.TESTFN, "rb") line = f.readline() self.assertEqual(line, s + b"\n") line = f.readline() self.assertEqual(line, s) line = f.readline() self.assertTrue(not line) # Must be at EOF f.close() finally: support.unlink(support.TESTFN) def drive_one(self, pattern): for length in lengths: # Repeat string 'pattern' as often as needed to reach total length # 'length'. Then call try_one with that string, a string one larger # than that, and a string one smaller than that. Try this with all # small sizes and various powers of 2, so we exercise all likely # stdio buffer sizes, and "off by one" errors on both sides. q, r = divmod(length, len(pattern)) teststring = pattern * q + pattern[:r] self.assertEqual(len(teststring), length) self.try_one(teststring) self.try_one(teststring + b"x") self.try_one(teststring[:-1]) def test_primepat(self): # A pattern with prime length, to avoid simple relationships with # stdio buffer sizes. self.drive_one(b"1234567890\00\01\02\03\04\05\06") def test_nullpat(self): self.drive_one(bytes(1000)) class CBufferSizeTest(BufferSizeTest): open = io.open class PyBufferSizeTest(BufferSizeTest): open = staticmethod(pyio.open) class BuiltinBufferSizeTest(BufferSizeTest): open = open def test_main(): support.run_unittest(CBufferSizeTest, PyBufferSizeTest, BuiltinBufferSizeTest) if __name__ == "__main__": test_main()
mit
dhenrygithub/QGIS
python/ext-libs/pygments/plugin.py
365
1862
# -*- coding: utf-8 -*- """ pygments.plugin ~~~~~~~~~~~~~~~ Pygments setuptools plugin interface. The methods defined here also work if setuptools isn't installed but they just return nothing. lexer plugins:: [pygments.lexers] yourlexer = yourmodule:YourLexer formatter plugins:: [pygments.formatters] yourformatter = yourformatter:YourFormatter /.ext = yourformatter:YourFormatter As you can see, you can define extensions for the formatter with a leading slash. syntax plugins:: [pygments.styles] yourstyle = yourstyle:YourStyle filter plugin:: [pygments.filter] yourfilter = yourfilter:YourFilter :copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ try: import pkg_resources except ImportError: pkg_resources = None LEXER_ENTRY_POINT = 'pygments.lexers' FORMATTER_ENTRY_POINT = 'pygments.formatters' STYLE_ENTRY_POINT = 'pygments.styles' FILTER_ENTRY_POINT = 'pygments.filters' def find_plugin_lexers(): if pkg_resources is None: return for entrypoint in pkg_resources.iter_entry_points(LEXER_ENTRY_POINT): yield entrypoint.load() def find_plugin_formatters(): if pkg_resources is None: return for entrypoint in pkg_resources.iter_entry_points(FORMATTER_ENTRY_POINT): yield entrypoint.name, entrypoint.load() def find_plugin_styles(): if pkg_resources is None: return for entrypoint in pkg_resources.iter_entry_points(STYLE_ENTRY_POINT): yield entrypoint.name, entrypoint.load() def find_plugin_filters(): if pkg_resources is None: return for entrypoint in pkg_resources.iter_entry_points(FILTER_ENTRY_POINT): yield entrypoint.name, entrypoint.load()
gpl-2.0
pwong-mapr/private-hue
desktop/core/ext-py/Django-1.4.5/django/contrib/localflavor/de/forms.py
87
3251
""" DE-specific Form helpers """ from __future__ import absolute_import import re from django.contrib.localflavor.de.de_states import STATE_CHOICES from django.core.validators import EMPTY_VALUES from django.forms import ValidationError from django.forms.fields import Field, RegexField, Select from django.utils.translation import ugettext_lazy as _ id_re = re.compile(r"^(?P<residence>\d{10})(?P<origin>\w{1,3})[-\ ]?(?P<birthday>\d{7})[-\ ]?(?P<validity>\d{7})[-\ ]?(?P<checksum>\d{1})$") class DEZipCodeField(RegexField): default_error_messages = { 'invalid': _('Enter a zip code in the format XXXXX.'), } def __init__(self, max_length=None, min_length=None, *args, **kwargs): super(DEZipCodeField, self).__init__(r'^\d{5}$', max_length, min_length, *args, **kwargs) class DEStateSelect(Select): """ A Select widget that uses a list of DE states as its choices. """ def __init__(self, attrs=None): super(DEStateSelect, self).__init__(attrs, choices=STATE_CHOICES) class DEIdentityCardNumberField(Field): """ A German identity card number. Checks the following rules to determine whether the number is valid: * Conforms to the XXXXXXXXXXX-XXXXXXX-XXXXXXX-X format. * No group consists entirely of zeroes. * Included checksums match calculated checksums Algorithm is documented at http://de.wikipedia.org/wiki/Personalausweis """ default_error_messages = { 'invalid': _('Enter a valid German identity card number in XXXXXXXXXXX-XXXXXXX-XXXXXXX-X format.'), } def has_valid_checksum(self, number): given_number, given_checksum = number[:-1], number[-1] calculated_checksum = 0 fragment = "" parameter = 7 for i in range(len(given_number)): fragment = str(int(given_number[i]) * parameter) if fragment.isalnum(): calculated_checksum += int(fragment[-1]) if parameter == 1: parameter = 7 elif parameter == 3: parameter = 1 elif parameter ==7: parameter = 3 return str(calculated_checksum)[-1] == given_checksum def clean(self, value): super(DEIdentityCardNumberField, self).clean(value) if value in EMPTY_VALUES: return u'' match = re.match(id_re, value) if not match: raise ValidationError(self.error_messages['invalid']) gd = match.groupdict() residence, origin = gd['residence'], gd['origin'] birthday, validity, checksum = gd['birthday'], gd['validity'], gd['checksum'] if residence == '0000000000' or birthday == '0000000' or validity == '0000000': raise ValidationError(self.error_messages['invalid']) all_digits = u"%s%s%s%s" % (residence, birthday, validity, checksum) if not self.has_valid_checksum(residence) or not self.has_valid_checksum(birthday) or \ not self.has_valid_checksum(validity) or not self.has_valid_checksum(all_digits): raise ValidationError(self.error_messages['invalid']) return u'%s%s-%s-%s-%s' % (residence, origin, birthday, validity, checksum)
apache-2.0
indonoso/small-Inventory
migrations/versions/b5d826fbeb95_.py
1
1106
"""empty message Revision ID: b5d826fbeb95 Revises: 25743fc519b2 Create Date: 2017-01-29 22:50:26.051735 """ # revision identifiers, used by Alembic. revision = 'b5d826fbeb95' down_revision = '25743fc519b2' from alembic import op import sqlalchemy as sa def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('association', sa.Column('brand', sa.Integer(), nullable=True), sa.Column('supplier', sa.Integer(), nullable=True), sa.ForeignKeyConstraint(['brand'], ['brand.id_'], ), sa.ForeignKeyConstraint(['supplier'], ['supplier.id_'], ) ) op.drop_constraint('brand_supplier_fkey', 'brand', type_='foreignkey') op.drop_column('brand', 'supplier') # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('brand', sa.Column('supplier', sa.INTEGER(), autoincrement=False, nullable=True)) op.create_foreign_key('brand_supplier_fkey', 'brand', 'supplier', ['supplier'], ['id_']) op.drop_table('association') # ### end Alembic commands ###
mit
mmolero/pyqode.python
test/test_modes/test_goto_assignments.py
2
2306
""" Test the autocomplete mode """ from pyqode.core.api import TextHelper from pyqode.qt import QtCore, QtWidgets from pyqode.qt.QtTest import QTest from pyqode.python import modes as pymodes from test.helpers import editor_open def get_mode(editor): return editor.modes.get(pymodes.GoToAssignmentsMode) @editor_open(__file__) def test_enabled(editor): mode = get_mode(editor) assert mode.enabled mode.enabled = False mode.enabled = True @editor_open(__file__) def test_goto_variable(editor): editor.clear() code = "a = 15\nprint(a)" editor.setPlainText(code) mode = get_mode(editor) TextHelper(editor).goto_line(2, len('print(a)') - 2) mode.request_goto() QTest.qWait(5000) # todo: restore assertion once jedi#571 is resolved # assert TextHelper(editor).current_line_nbr() == 0 out = False def _on_out_of_doc(*args): global out out = True @editor_open(__file__) def test_goto_out_of_doc(editor): global out out = False editor.clear() code = "import logging\nlogging.basicConfig()" editor.setPlainText(code) mode = get_mode(editor) TextHelper(editor).goto_line(1, len('logging.basicConfig()') - 4) mode.out_of_doc.connect(_on_out_of_doc) assert out is False mode.request_goto() QTest.qWait(5000) assert out is True flg_multi = False def accept_dlg(): global flg_multi flg_multi = True widgets = QtWidgets.QApplication.instance().topLevelWidgets() for w in widgets: if isinstance(w, QtWidgets.QDialog): QTest.keyPress(w, QtCore.Qt.Key_Tab) QTest.keyPress(w, QtCore.Qt.Key_Tab) QTest.keyPress(w, QtCore.Qt.Key_Return) @editor_open(__file__) def test_multiple_results(editor): global flg_multi editor.clear() code = "import os\nos.path.abspath('..')" editor.setPlainText(code) mode = get_mode(editor) TextHelper(editor).goto_line(1, 4) QTest.qWait(5000) mode.request_goto() assert flg_multi is False QtCore.QTimer.singleShot(1000, accept_dlg) QTest.qWait(5000) assert flg_multi is True @editor_open(__file__) def test_make_unique(editor): seq = ['a', 'b', 'c', 'a'] mode = get_mode(editor) new_seq = mode._unique(seq) assert len(new_seq) == len(seq) - 1
mit
bretlowery/snakr
lib/django/conf/locale/mk/formats.py
504
1742
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # from __future__ import unicode_literals # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'd F Y' TIME_FORMAT = 'H:i' DATETIME_FORMAT = 'j. F Y H:i' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j. F' SHORT_DATE_FORMAT = 'j.m.Y' SHORT_DATETIME_FORMAT = 'j.m.Y H:i' FIRST_DAY_OF_WEEK = 1 # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = [ '%d.%m.%Y', '%d.%m.%y', # '25.10.2006', '25.10.06' '%d. %m. %Y', '%d. %m. %y', # '25. 10. 2006', '25. 10. 06' ] DATETIME_INPUT_FORMATS = [ '%d.%m.%Y %H:%M:%S', # '25.10.2006 14:30:59' '%d.%m.%Y %H:%M:%S.%f', # '25.10.2006 14:30:59.000200' '%d.%m.%Y %H:%M', # '25.10.2006 14:30' '%d.%m.%Y', # '25.10.2006' '%d.%m.%y %H:%M:%S', # '25.10.06 14:30:59' '%d.%m.%y %H:%M:%S.%f', # '25.10.06 14:30:59.000200' '%d.%m.%y %H:%M', # '25.10.06 14:30' '%d.%m.%y', # '25.10.06' '%d. %m. %Y %H:%M:%S', # '25. 10. 2006 14:30:59' '%d. %m. %Y %H:%M:%S.%f', # '25. 10. 2006 14:30:59.000200' '%d. %m. %Y %H:%M', # '25. 10. 2006 14:30' '%d. %m. %Y', # '25. 10. 2006' '%d. %m. %y %H:%M:%S', # '25. 10. 06 14:30:59' '%d. %m. %y %H:%M:%S.%f', # '25. 10. 06 14:30:59.000200' '%d. %m. %y %H:%M', # '25. 10. 06 14:30' '%d. %m. %y', # '25. 10. 06' ] DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' NUMBER_GROUPING = 3
bsd-3-clause
giliam/sharbrary
sharing/forms.py
1
2215
# coding: utf-8 from django import forms from django.utils.translation import ugettext_lazy as _ from django.db.models import Q from django.contrib.auth.models import User from django.contrib.admin import widgets from django.shortcuts import get_object_or_404 from sharing.models import Lending, Profile from library.models import Book from utils.models.availability import is_lending_possible, is_returning_possible class LendingEndForm(forms.ModelForm): class Meta: model = Lending fields = ('end_date',) def clean_end_date(self): end_date = self.cleaned_data['end_date'] if self.instance.beginning_date > end_date: raise forms.ValidationError(_("The end date must be after the beginning date.")) is_returning_possible(end_date,self.instance) return end_date class LendingForm(forms.ModelForm): class Meta: model = Lending fields = ('book_copy', 'borrower', 'beginning_date',) def clean(self): beginning_date = self.cleaned_data['beginning_date'] book_copy = self.cleaned_data['book_copy'] is_lending_possible(beginning_date,book_copy) return self.cleaned_data class LogInForm(forms.Form): username = forms.CharField(label=_("Username"), max_length=30) password = forms.CharField(label=_("Password"), widget=forms.PasswordInput) class UserForm(forms.ModelForm): confirm_password = forms.CharField(label=_("Confirm password"),widget=forms.PasswordInput()) class Meta: model = User fields = ('username', 'email', 'password',) widgets = { 'password': forms.PasswordInput(), } class UserEditForm(forms.ModelForm): password = forms.CharField(label=_("Password"),widget=forms.PasswordInput(),required=False) confirm_password = forms.CharField(label=_("Confirm password"),widget=forms.PasswordInput(),required=False) class Meta: model = User fields = ('email', 'password',) widgets = { 'password': forms.PasswordInput(), } class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ('informations', 'phone_number', 'picture','locale',)
gpl-2.0
mjudsp/Tsallis
sklearn/decomposition/tests/test_truncated_svd.py
73
6086
"""Test truncated SVD transformer.""" import numpy as np import scipy.sparse as sp from sklearn.decomposition import TruncatedSVD from sklearn.utils import check_random_state from sklearn.utils.testing import (assert_array_almost_equal, assert_equal, assert_raises, assert_greater, assert_array_less) # Make an X that looks somewhat like a small tf-idf matrix. # XXX newer versions of SciPy have scipy.sparse.rand for this. shape = 60, 55 n_samples, n_features = shape rng = check_random_state(42) X = rng.randint(-100, 20, np.product(shape)).reshape(shape) X = sp.csr_matrix(np.maximum(X, 0), dtype=np.float64) X.data[:] = 1 + np.log(X.data) Xdense = X.A def test_algorithms(): svd_a = TruncatedSVD(30, algorithm="arpack") svd_r = TruncatedSVD(30, algorithm="randomized", random_state=42) Xa = svd_a.fit_transform(X)[:, :6] Xr = svd_r.fit_transform(X)[:, :6] assert_array_almost_equal(Xa, Xr, decimal=5) comp_a = np.abs(svd_a.components_) comp_r = np.abs(svd_r.components_) # All elements are equal, but some elements are more equal than others. assert_array_almost_equal(comp_a[:9], comp_r[:9]) assert_array_almost_equal(comp_a[9:], comp_r[9:], decimal=2) def test_attributes(): for n_components in (10, 25, 41): tsvd = TruncatedSVD(n_components).fit(X) assert_equal(tsvd.n_components, n_components) assert_equal(tsvd.components_.shape, (n_components, n_features)) def test_too_many_components(): for algorithm in ["arpack", "randomized"]: for n_components in (n_features, n_features + 1): tsvd = TruncatedSVD(n_components=n_components, algorithm=algorithm) assert_raises(ValueError, tsvd.fit, X) def test_sparse_formats(): for fmt in ("array", "csr", "csc", "coo", "lil"): Xfmt = Xdense if fmt == "dense" else getattr(X, "to" + fmt)() tsvd = TruncatedSVD(n_components=11) Xtrans = tsvd.fit_transform(Xfmt) assert_equal(Xtrans.shape, (n_samples, 11)) Xtrans = tsvd.transform(Xfmt) assert_equal(Xtrans.shape, (n_samples, 11)) def test_inverse_transform(): for algo in ("arpack", "randomized"): # We need a lot of components for the reconstruction to be "almost # equal" in all positions. XXX Test means or sums instead? tsvd = TruncatedSVD(n_components=52, random_state=42) Xt = tsvd.fit_transform(X) Xinv = tsvd.inverse_transform(Xt) assert_array_almost_equal(Xinv, Xdense, decimal=1) def test_integers(): Xint = X.astype(np.int64) tsvd = TruncatedSVD(n_components=6) Xtrans = tsvd.fit_transform(Xint) assert_equal(Xtrans.shape, (n_samples, tsvd.n_components)) def test_explained_variance(): # Test sparse data svd_a_10_sp = TruncatedSVD(10, algorithm="arpack") svd_r_10_sp = TruncatedSVD(10, algorithm="randomized", random_state=42) svd_a_20_sp = TruncatedSVD(20, algorithm="arpack") svd_r_20_sp = TruncatedSVD(20, algorithm="randomized", random_state=42) X_trans_a_10_sp = svd_a_10_sp.fit_transform(X) X_trans_r_10_sp = svd_r_10_sp.fit_transform(X) X_trans_a_20_sp = svd_a_20_sp.fit_transform(X) X_trans_r_20_sp = svd_r_20_sp.fit_transform(X) # Test dense data svd_a_10_de = TruncatedSVD(10, algorithm="arpack") svd_r_10_de = TruncatedSVD(10, algorithm="randomized", random_state=42) svd_a_20_de = TruncatedSVD(20, algorithm="arpack") svd_r_20_de = TruncatedSVD(20, algorithm="randomized", random_state=42) X_trans_a_10_de = svd_a_10_de.fit_transform(X.toarray()) X_trans_r_10_de = svd_r_10_de.fit_transform(X.toarray()) X_trans_a_20_de = svd_a_20_de.fit_transform(X.toarray()) X_trans_r_20_de = svd_r_20_de.fit_transform(X.toarray()) # helper arrays for tests below svds = (svd_a_10_sp, svd_r_10_sp, svd_a_20_sp, svd_r_20_sp, svd_a_10_de, svd_r_10_de, svd_a_20_de, svd_r_20_de) svds_trans = ( (svd_a_10_sp, X_trans_a_10_sp), (svd_r_10_sp, X_trans_r_10_sp), (svd_a_20_sp, X_trans_a_20_sp), (svd_r_20_sp, X_trans_r_20_sp), (svd_a_10_de, X_trans_a_10_de), (svd_r_10_de, X_trans_r_10_de), (svd_a_20_de, X_trans_a_20_de), (svd_r_20_de, X_trans_r_20_de), ) svds_10_v_20 = ( (svd_a_10_sp, svd_a_20_sp), (svd_r_10_sp, svd_r_20_sp), (svd_a_10_de, svd_a_20_de), (svd_r_10_de, svd_r_20_de), ) svds_sparse_v_dense = ( (svd_a_10_sp, svd_a_10_de), (svd_a_20_sp, svd_a_20_de), (svd_r_10_sp, svd_r_10_de), (svd_r_20_sp, svd_r_20_de), ) # Assert the 1st component is equal for svd_10, svd_20 in svds_10_v_20: assert_array_almost_equal( svd_10.explained_variance_ratio_, svd_20.explained_variance_ratio_[:10], decimal=5, ) # Assert that 20 components has higher explained variance than 10 for svd_10, svd_20 in svds_10_v_20: assert_greater( svd_20.explained_variance_ratio_.sum(), svd_10.explained_variance_ratio_.sum(), ) # Assert that all the values are greater than 0 for svd in svds: assert_array_less(0.0, svd.explained_variance_ratio_) # Assert that total explained variance is less than 1 for svd in svds: assert_array_less(svd.explained_variance_ratio_.sum(), 1.0) # Compare sparse vs. dense for svd_sparse, svd_dense in svds_sparse_v_dense: assert_array_almost_equal(svd_sparse.explained_variance_ratio_, svd_dense.explained_variance_ratio_) # Test that explained_variance is correct for svd, transformed in svds_trans: total_variance = np.var(X.toarray(), axis=0).sum() variances = np.var(transformed, axis=0) true_explained_variance_ratio = variances / total_variance assert_array_almost_equal( svd.explained_variance_ratio_, true_explained_variance_ratio, )
bsd-3-clause
thauser/pnc-cli
pnc_cli/swagger_client/models/build_configuration_rest.py
1
12779
# coding: utf-8 """ Copyright 2015 SmartBear Software 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. Ref: https://github.com/swagger-api/swagger-codegen """ from datetime import datetime from pprint import pformat from six import iteritems class BuildConfigurationRest(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ def __init__(self): """ BuildConfigurationRest - a model defined in Swagger :param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict attributeMap: The key is attribute name and the value is json key in definition. """ self.swagger_types = { 'id': 'int', 'name': 'str', 'description': 'str', 'build_script': 'str', 'repository_configuration': 'RepositoryConfigurationRest', 'scm_revision': 'str', 'creation_time': 'datetime', 'last_modification_time': 'datetime', 'archived': 'bool', 'project': 'ProjectRest', 'environment': 'BuildEnvironmentRest', 'dependency_ids': 'list[int]', 'product_version_id': 'int', 'build_configuration_set_ids': 'list[int]', 'generic_parameters': 'dict(str, str)' } self.attribute_map = { 'id': 'id', 'name': 'name', 'description': 'description', 'build_script': 'buildScript', 'repository_configuration': 'repositoryConfiguration', 'scm_revision': 'scmRevision', 'creation_time': 'creationTime', 'last_modification_time': 'lastModificationTime', 'archived': 'archived', 'project': 'project', 'environment': 'environment', 'dependency_ids': 'dependencyIds', 'product_version_id': 'productVersionId', 'build_configuration_set_ids': 'buildConfigurationSetIds', 'generic_parameters': 'genericParameters' } self._id = None self._name = None self._description = None self._build_script = None self._repository_configuration = None self._scm_revision = None self._creation_time = None self._last_modification_time = None self._archived = None self._project = None self._environment = None self._dependency_ids = None self._product_version_id = None self._build_configuration_set_ids = None self._generic_parameters = None @property def id(self): """ Gets the id of this BuildConfigurationRest. :return: The id of this BuildConfigurationRest. :rtype: int """ return self._id @id.setter def id(self, id): """ Sets the id of this BuildConfigurationRest. :param id: The id of this BuildConfigurationRest. :type: int """ self._id = id @property def name(self): """ Gets the name of this BuildConfigurationRest. :return: The name of this BuildConfigurationRest. :rtype: str """ return self._name @name.setter def name(self, name): """ Sets the name of this BuildConfigurationRest. :param name: The name of this BuildConfigurationRest. :type: str """ self._name = name @property def description(self): """ Gets the description of this BuildConfigurationRest. :return: The description of this BuildConfigurationRest. :rtype: str """ return self._description @description.setter def description(self, description): """ Sets the description of this BuildConfigurationRest. :param description: The description of this BuildConfigurationRest. :type: str """ self._description = description @property def build_script(self): """ Gets the build_script of this BuildConfigurationRest. :return: The build_script of this BuildConfigurationRest. :rtype: str """ return self._build_script @build_script.setter def build_script(self, build_script): """ Sets the build_script of this BuildConfigurationRest. :param build_script: The build_script of this BuildConfigurationRest. :type: str """ self._build_script = build_script @property def repository_configuration(self): """ Gets the repository_configuration of this BuildConfigurationRest. :return: The repository_configuration of this BuildConfigurationRest. :rtype: RepositoryConfigurationRest """ return self._repository_configuration @repository_configuration.setter def repository_configuration(self, repository_configuration): """ Sets the repository_configuration of this BuildConfigurationRest. :param repository_configuration: The repository_configuration of this BuildConfigurationRest. :type: RepositoryConfigurationRest """ self._repository_configuration = repository_configuration @property def scm_revision(self): """ Gets the scm_revision of this BuildConfigurationRest. :return: The scm_revision of this BuildConfigurationRest. :rtype: str """ return self._scm_revision @scm_revision.setter def scm_revision(self, scm_revision): """ Sets the scm_revision of this BuildConfigurationRest. :param scm_revision: The scm_revision of this BuildConfigurationRest. :type: str """ self._scm_revision = scm_revision @property def creation_time(self): """ Gets the creation_time of this BuildConfigurationRest. :return: The creation_time of this BuildConfigurationRest. :rtype: datetime """ return self._creation_time @creation_time.setter def creation_time(self, creation_time): """ Sets the creation_time of this BuildConfigurationRest. :param creation_time: The creation_time of this BuildConfigurationRest. :type: datetime """ self._creation_time = creation_time @property def last_modification_time(self): """ Gets the last_modification_time of this BuildConfigurationRest. :return: The last_modification_time of this BuildConfigurationRest. :rtype: datetime """ return self._last_modification_time @last_modification_time.setter def last_modification_time(self, last_modification_time): """ Sets the last_modification_time of this BuildConfigurationRest. :param last_modification_time: The last_modification_time of this BuildConfigurationRest. :type: datetime """ self._last_modification_time = last_modification_time @property def archived(self): """ Gets the archived of this BuildConfigurationRest. :return: The archived of this BuildConfigurationRest. :rtype: bool """ return self._archived @archived.setter def archived(self, archived): """ Sets the archived of this BuildConfigurationRest. :param archived: The archived of this BuildConfigurationRest. :type: bool """ self._archived = archived @property def project(self): """ Gets the project of this BuildConfigurationRest. :return: The project of this BuildConfigurationRest. :rtype: ProjectRest """ return self._project @project.setter def project(self, project): """ Sets the project of this BuildConfigurationRest. :param project: The project of this BuildConfigurationRest. :type: ProjectRest """ self._project = project @property def environment(self): """ Gets the environment of this BuildConfigurationRest. :return: The environment of this BuildConfigurationRest. :rtype: BuildEnvironmentRest """ return self._environment @environment.setter def environment(self, environment): """ Sets the environment of this BuildConfigurationRest. :param environment: The environment of this BuildConfigurationRest. :type: BuildEnvironmentRest """ self._environment = environment @property def dependency_ids(self): """ Gets the dependency_ids of this BuildConfigurationRest. :return: The dependency_ids of this BuildConfigurationRest. :rtype: list[int] """ return self._dependency_ids @dependency_ids.setter def dependency_ids(self, dependency_ids): """ Sets the dependency_ids of this BuildConfigurationRest. :param dependency_ids: The dependency_ids of this BuildConfigurationRest. :type: list[int] """ self._dependency_ids = dependency_ids @property def product_version_id(self): """ Gets the product_version_id of this BuildConfigurationRest. :return: The product_version_id of this BuildConfigurationRest. :rtype: int """ return self._product_version_id @product_version_id.setter def product_version_id(self, product_version_id): """ Sets the product_version_id of this BuildConfigurationRest. :param product_version_id: The product_version_id of this BuildConfigurationRest. :type: int """ self._product_version_id = product_version_id @property def build_configuration_set_ids(self): """ Gets the build_configuration_set_ids of this BuildConfigurationRest. :return: The build_configuration_set_ids of this BuildConfigurationRest. :rtype: list[int] """ return self._build_configuration_set_ids @build_configuration_set_ids.setter def build_configuration_set_ids(self, build_configuration_set_ids): """ Sets the build_configuration_set_ids of this BuildConfigurationRest. :param build_configuration_set_ids: The build_configuration_set_ids of this BuildConfigurationRest. :type: list[int] """ self._build_configuration_set_ids = build_configuration_set_ids @property def generic_parameters(self): """ Gets the generic_parameters of this BuildConfigurationRest. :return: The generic_parameters of this BuildConfigurationRest. :rtype: dict(str, str) """ return self._generic_parameters @generic_parameters.setter def generic_parameters(self, generic_parameters): """ Sets the generic_parameters of this BuildConfigurationRest. :param generic_parameters: The generic_parameters of this BuildConfigurationRest. :type: dict(str, str) """ self._generic_parameters = generic_parameters def to_dict(self): """ Returns the model properties as a dict """ result = {} for attr, _ in iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, datetime): result[attr] = str(value.date()) else: result[attr] = value return result def to_str(self): """ Returns the string representation of the model """ return pformat(self.to_dict()) def __repr__(self): """ For `print` and `pprint` """ return self.to_str()
apache-2.0
eternnoir/PyrserPTT
GraberServer.py
1
2451
# -*- coding: utf-8 -*- __author__ = 'frank' from PyrserPTT import PyserPtt from mongoengine import * import multiprocessing import time import hashlib import sys connect('admin',host='mongodb://') boardList = [] def getNewAtricalByBorad(board,pages=2): graber = PyserPtt.PyserPtt(board,pages) articalList = graber.getArticalList() checkAndSaveArtical(articalList) def checkAndSaveArtical(articalList): print 'GET ' + str(len(articalList))+'POSTs' for a in articalList: exits = PyserPtt.Artical.Artical.objects(url = a.url) if len(exits) is 0: print 'Save '+a.title a.save() else: if isDiffArtical(exits,a): a.save() print 'Diff '+ a.title else: print 'NOCHG '+a.title def isDiffArtical(articalList,newArtical): newArtMd5 = getMd5(newArtical.htmlcontent) for art in articalList: if newArtMd5 == getMd5(art.htmlcontent): return False return True def getMd5(ori): ori = ori.encode('utf8') md5str = hashlib.md5(ori).hexdigest() return md5str def doGrabing(): while True: print 'Grabing.....' pool = multiprocessing.Pool(processes=len(boardList)) for b in boardList: pool.apply_async(getNewAtricalByBorad,(b,4,)) pool.close() pool.join() print 'Sleep.....' time.sleep(180) def doUpdateAll(): urlList = PyserPtt.Artical.Artical.objects().distinct('url') print 'Check '+str(len(urlList))+' Urls' for url in urlList: print 'Update ' + url; try: checkAndSaveArtical([ _getArticalByUrl(url)]) except Exception: print 'Can not update '+ url time.sleep(3) return def _getArticalByUrl(url): contentGraber = PyserPtt.PttHtmlGraber.WebPttBot('') oldarti = PyserPtt.Artical.Artical.objects(url = url)[0] html = contentGraber.getHtmlContent(PyserPtt.pttSiteUrl+url) a = PyserPtt.Artical.Artical( title=oldarti.title, nrec=oldarti.nrec, url=oldarti.url, mark=oldarti.mark, date=oldarti.date, author=oldarti.author, board=oldarti.board, htmlcontent = html) return a if __name__ == "__main__": par = None if len(sys.argv)>1: par = sys.argv[1] print par if par == 'u': doUpdateAll() else: doGrabing()
gpl-2.0
floresconlimon/qutebrowser
tests/unit/misc/test_crashdialog.py
5
2656
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2015 Florian Bruhin (The Compiler) <mail@qutebrowser.org> # # This file is part of qutebrowser. # # qutebrowser 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. # # qutebrowser 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 qutebrowser. If not, see <http://www.gnu.org/licenses/>. """Tests for qutebrowser.misc.crashdialog.""" from qutebrowser.misc import crashdialog VALID_CRASH_TEXT = """ Fatal Python error: Segmentation fault _ Current thread 0x00007f09b538d700 (most recent call first): File "", line 1 in testfunc File "filename", line 88 in func """ VALID_CRASH_TEXT_EMPTY = """ Fatal Python error: Aborted _ Current thread 0x00007f09b538d700 (most recent call first): File "", line 1 in_ File "filename", line 88 in func """ VALID_CRASH_TEXT_THREAD = """ Fatal Python error: Segmentation fault _ Thread 0x00007fa135ac7700 (most recent call first): File "", line 1 in testfunc """ INVALID_CRASH_TEXT = """ Hello world! """ class TestParseFatalStacktrace: """Tests for parse_fatal_stacktrace.""" def test_valid_text(self): """Test parse_fatal_stacktrace with a valid text.""" text = VALID_CRASH_TEXT.strip().replace('_', ' ') typ, func = crashdialog.parse_fatal_stacktrace(text) assert (typ, func) == ("Segmentation fault", 'testfunc') def test_valid_text_thread(self): """Test parse_fatal_stacktrace with a valid text #2.""" text = VALID_CRASH_TEXT_THREAD.strip().replace('_', ' ') typ, func = crashdialog.parse_fatal_stacktrace(text) assert (typ, func) == ("Segmentation fault", 'testfunc') def test_valid_text_empty(self): """Test parse_fatal_stacktrace with a valid text but empty function.""" text = VALID_CRASH_TEXT_EMPTY.strip().replace('_', ' ') typ, func = crashdialog.parse_fatal_stacktrace(text) assert (typ, func) == ('Aborted', '') def test_invalid_text(self): """Test parse_fatal_stacktrace with an invalid text.""" text = INVALID_CRASH_TEXT.strip().replace('_', ' ') typ, func = crashdialog.parse_fatal_stacktrace(text) assert (typ, func) == ('', '')
gpl-3.0
macs03/demo-cms
cms/lib/python2.7/site-packages/cms/utils/check.py
3
16338
# -*- coding: utf-8 -*- from __future__ import with_statement from contextlib import contextmanager import inspect from itertools import chain import os from django.conf import settings from django.template import Lexer, TOKEN_BLOCK from django.utils import six from django.utils.decorators import method_decorator from django.utils.termcolors import colorize from sekizai.helpers import validate_template from cms import constants from cms.models import AliasPluginModel from cms.utils import get_cms_setting from cms.utils.compat.dj import get_app_paths, is_installed SUCCESS = 1 WARNING = 2 ERROR = 3 SKIPPED = 4 CHECKERS = [] class FileOutputWrapper(object): """ Wraps two file-like objects (that support at the very least the 'write' method) into an API to be used by the check function further down in this module. The following properties are public (and required) by alternative implementations: errors: integer count of errors encountered successes: integer count of successes encountered warnings: integer count of warnings encountered skips: integer count of skips encountered successful: Whether the checks were successful (no errors) They must also provide these methods: write_line(message=''): writes a message to stdout write_stderr_line(message=''): writes a message to stderr success(message): reports and registers a successful check error(message): reports and registers an error warn(message); reports and registers a warning skip(message): reports and registers a skipped check section(title): A context manager that starts a new section. For the Section API see FileSectionWrapper """ def __init__(self, stdout, stderr): self.stdout = stdout self.stderr = stderr self.section_wrapper = FileSectionWrapper self.errors = 0 self.successes = 0 self.warnings = 0 self.skips = 0 def colorize(self, msg, opts=(), **kwargs): return colorize(msg, opts=opts, **kwargs) def write_line(self, message=''): self.write(u'%s\n' % message) def write(self, message): self.stdout.write(message) def write_stderr_line(self, message=''): self.write_stderr(u'%s\n' % message) def write_stderr(self, message): self.stderr.write(message) def success(self, message): self.successes += 1 self.write_line(u'%s %s' % (message, self.colorize('[OK]', fg='green', opts=['bold']))) def error(self, message): self.errors += 1 self.write_stderr_line(u'%s %s' % (message, self.colorize('[ERROR]', fg='red', opts=['bold']))) def warn(self, message): self.warnings += 1 self.write_stderr_line(u'%s %s' % (message, self.colorize('[WARNING]', fg='yellow', opts=['bold']))) def skip(self, message): self.skips += 1 self.write_line(u'%s %s' % (message, self.colorize('[SKIP]', fg='blue', opts=['bold']))) @method_decorator(contextmanager) def section(self, title): self.write_line(self.colorize(title, opts=['bold'])) self.write_line(self.colorize('=' * len(title), opts=['bold'])) self.write_line() wrapper = self.section_wrapper(self) try: yield wrapper except: self.error('Checker failed, see traceback') raise self.errors += wrapper.errors self.successes += wrapper.successes self.warnings += wrapper.warnings self.skips += wrapper.skips self.write_line('') @property def successful(self): return not self.errors class FileSectionWrapper(FileOutputWrapper): """ Used from FileOutputWrapper to report checks in a section. If you want to provide your own output class, you may want to subclass this class for the section reporting too. If you want to use your own, you must defined at least the same API as FileOutputWrapper, as well as these four additional methods: finish_success(message): End the section (successfully) finish_error(message): End the section with errors finish_warning(message): End this section with a warning finish_skip(message): End this (skipped) section """ def __init__(self, wrapper): super(FileSectionWrapper, self).__init__(wrapper.stdout, wrapper.stderr) self.wrapper = wrapper def write_line(self, message=''): self.write(u' - %s\n' % message) def write_stderr_line(self, message=''): self.write_stderr(u' - %s\n' % message) def finish_success(self, message): self.wrapper.write_line() self.wrapper.success(message) def finish_error(self, message): self.wrapper.write_line() self.wrapper.error(message) def finish_warning(self, message): self.wrapper.write_line() self.wrapper.warning(message) def finish_skip(self, message): self.wrapper.write_lin() self.wrapper.skip(message) def define_check(func): """ Helper decorator to register a check function. """ CHECKERS.append(func) return func @define_check def check_sekizai(output): with output.section("Sekizai") as section: if is_installed('sekizai'): section.success("Sekizai is installed") else: section.error("Sekizai is not installed, could not find 'sekizai' in INSTALLED_APPS") if 'sekizai.context_processors.sekizai' in settings.TEMPLATE_CONTEXT_PROCESSORS: section.success("Sekizai template context processor is installed") else: section.error("Sekizai template context processor is not installed, could not find 'sekizai.context_processors.sekizai' in TEMPLATE_CONTEXT_PROCESSORS") for template, _ in get_cms_setting('TEMPLATES'): if template == constants.TEMPLATE_INHERITANCE_MAGIC: continue if validate_template(template, ['js', 'css']): section.success("Sekizai namespaces 'js' and 'css' found in %r" % template) else: section.error("Sekizai namespaces 'js' and 'css' not found in %r" % template) if section.successful: section.finish_success("Sekizai configuration okay") else: section.finish_error("Sekizai configuration has errors") @define_check def check_i18n(output): with output.section("Internationalization") as section: if isinstance(getattr(settings, 'CMS_LANGUAGES', {}), dict): section.success("New style CMS_LANGUAGES") else: section.warn("Old style (tuple based) CMS_LANGUAGES, please switch to the new (dictionary based) style") if getattr(settings, 'LANGUAGE_CODE', '').find('_') > -1: section.warn("LANGUAGE_CODE must contain a valid language code, not a locale (e.g.: 'en-us' instead of 'en_US'): '%s' provided" % getattr(settings, 'LANGUAGE_CODE', '')) for lang in getattr(settings, 'LANGUAGES', ()): if lang[0].find('_') > -1: section.warn("LANGUAGES must contain valid language codes, not locales (e.g.: 'en-us' instead of 'en_US'): '%s' provided" % lang[0]) if isinstance(settings.SITE_ID, six.integer_types): for site, items in get_cms_setting('LANGUAGES').items(): if type(site) == int: for lang in items: if lang['code'].find('_') > -1: section.warn("CMS_LANGUAGES entries must contain valid language codes, not locales (e.g.: 'en-us' instead of 'en_US'): '%s' provided" % lang['code']) else: section.error("SITE_ID must be an integer, not %r" % settings.SITE_ID) for deprecated in ['CMS_HIDE_UNTRANSLATED', 'CMS_LANGUAGE_FALLBACK', 'CMS_LANGUAGE_CONF', 'CMS_SITE_LANGUAGES', 'CMS_FRONTEND_LANGUAGES']: if hasattr(settings, deprecated): section.warn("Deprecated setting %s found. This setting is now handled in the new style CMS_LANGUAGES and can be removed" % deprecated) @define_check def check_deprecated_settings(output): with output.section("Deprecated settings") as section: found = False for deprecated in ['CMS_FLAT_URLS', 'CMS_MODERATOR']: if hasattr(settings, deprecated): section.warn("Deprecated setting %s found. This setting is no longer in use and can be removed" % deprecated) found = True if not found: section.skip("No deprecated settings found") @define_check def check_plugin_instances(output): from cms.management.commands.subcommands.list import plugin_report with output.section("Plugin instances") as section: # get the report report = plugin_report() section.success("Plugin instances of %s types found in the database" % len(report)) # loop over plugin types in the report for plugin_type in report: # warn about those that are not installed if not plugin_type["model"]: section.error("%s has instances but is no longer installed" % plugin_type["type"] ) # warn about those that have unsaved instances if plugin_type["unsaved_instances"]: section.error("%s has %s unsaved instances" % (plugin_type["type"], len(plugin_type["unsaved_instances"]))) if section.successful: section.finish_success("The plugins in your database are in good order") else: section.finish_error("There are potentially serious problems with the plugins in your database. \nEven if your site works, you should run the 'manage.py cms list plugins' \ncommand and then the 'manage.py cms delete_orphaned_plugins' command. \nThis will alter your database; read the documentation before using it.") @define_check def check_copy_relations(output): from cms.plugin_pool import plugin_pool from cms.extensions import extension_pool from cms.extensions.models import BaseExtension from cms.models.pluginmodel import CMSPlugin c_to_s = lambda klass: '%s.%s' % (klass.__module__, klass.__name__) def get_class(method_name, model): for cls in inspect.getmro(model): if method_name in cls.__dict__: return cls return None with output.section('Presence of "copy_relations"') as section: plugin_pool.discover_plugins() for plugin in plugin_pool.plugins.values(): plugin_class = plugin.model if get_class('copy_relations', plugin_class) is not CMSPlugin or plugin_class is CMSPlugin: # this class defines a ``copy_relations`` method, nothing more # to do continue for rel in plugin_class._meta.many_to_many: section.warn('%s has a many-to-many relation to %s,\n but no "copy_relations" method defined.' % ( c_to_s(plugin_class), c_to_s(rel.model), )) for rel in plugin_class._meta.get_all_related_objects(): if rel.model != CMSPlugin and not issubclass(rel.model, plugin.model) and rel.model != AliasPluginModel: section.warn('%s has a foreign key from %s,\n but no "copy_relations" method defined.' % ( c_to_s(plugin_class), c_to_s(rel.model), )) for extension in chain(extension_pool.page_extensions, extension_pool.title_extensions): if get_class('copy_relations', extension) is not BaseExtension: # OK, looks like there is a 'copy_relations' defined in the # extension... move along... continue for rel in extension._meta.many_to_many: section.warn('%s has a many-to-many relation to %s,\n but no "copy_relations" method defined.' % ( c_to_s(extension), c_to_s(rel.related.parent_model), )) for rel in extension._meta.get_all_related_objects(): if rel.model != extension: section.warn('%s has a foreign key from %s,\n but no "copy_relations" method defined.' % ( c_to_s(extension), c_to_s(rel.model), )) if not section.warnings: section.finish_success('All plugins and page/title extensions have "copy_relations" method if needed.') else: section.finish_success('Some plugins or page/title extensions do not define a "copy_relations" method.\nThis might lead to data loss when publishing or copying plugins/extensions.\nSee https://django-cms.readthedocs.org/en/latest/extending_cms/custom_plugins.html#handling-relations or https://django-cms.readthedocs.org/en/latest/extending_cms/extending_page_title.html#handling-relations.') def _load_all_templates(directory): """ Loads all templates in a directory (recursively) and yields tuples of template tokens and template paths. """ if os.path.exists(directory): for name in os.listdir(directory): path = os.path.join(directory, name) if os.path.isdir(path): for template in _load_all_templates(path): yield template elif path.endswith('.html'): with open(path, 'rb') as fobj: source = fobj.read().decode(settings.FILE_CHARSET) lexer = Lexer(source, path) yield lexer.tokenize(), path @define_check def deprecations(output): # deprecated placeholder_tags scan (1 in 3.1) templates_dirs = list(getattr(settings, 'TEMPLATE_DIRS', [])) templates_dirs.extend( [os.path.join(path, 'templates') for path in get_app_paths()] ) with output.section('Usage of deprecated placeholder_tags') as section: for template_dir in templates_dirs: for tokens, path in _load_all_templates(template_dir): for token in tokens: if token.token_type == TOKEN_BLOCK: bits = token.split_contents() if bits[0] == 'load' and 'placeholder_tags' in bits: section.warn( 'Usage of deprecated template tag library ' 'placeholder tags in template %s' % path ) def check(output): """ Checks the configuration/environment of this django CMS installation. 'output' should be an object that provides the same API as FileOutputWrapper. Returns whether the configuration/environment are okay (has no errors) """ title = "Checking django CMS installation" border = '*' * len(title) output.write_line(output.colorize(border, opts=['bold'])) output.write_line(output.colorize(title, opts=['bold'])) output.write_line(output.colorize(border, opts=['bold'])) output.write_line() for checker in CHECKERS: checker(output) output.write_line() with output.section("OVERALL RESULTS"): if output.errors: output.write_stderr_line(output.colorize("%s errors!" % output.errors, opts=['bold'], fg='red')) if output.warnings: output.write_stderr_line(output.colorize("%s warnings!" % output.warnings, opts=['bold'], fg='yellow')) if output.skips: output.write_line(output.colorize("%s checks skipped!" % output.skips, opts=['bold'], fg='blue')) output.write_line(output.colorize("%s checks successful!" % output.successes, opts=['bold'], fg='green')) output.write_line() if output.errors: output.write_stderr_line(output.colorize('Please check the errors above', opts=['bold'], fg='red')) elif output.warnings: output.write_stderr_line(output.colorize('Installation okay, but please check warnings above', opts=['bold'], fg='yellow')) else: output.write_line(output.colorize('Installation okay', opts=['bold'], fg='green')) return output.successful
mit
thorgate/django-project-template
{{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/accounts/forms.py
1
3829
from typing import List from django import forms from django.contrib.auth import forms as auth_forms from django.contrib.auth import get_user_model from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth.tokens import default_token_generator from django.utils.encoding import force_bytes from django.utils.http import urlsafe_base64_encode from django.utils.translation import gettext_lazy as _ from crispy_forms.helper import FormHelper from crispy_forms.layout import Field, Layout, Submit from accounts.emails import send_password_reset from accounts.models import User class LoginForm(AuthenticationForm): def __init__(self, *args, **kwargs): super(LoginForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_class = "login-form" self.helper.form_show_labels = False self.helper.layout = Layout( Field("username", placeholder=_("Username")), Field("password", placeholder=_("Password")), ) self.helper.add_input(Submit("submit", _("Log in"))) class PasswordResetForm(auth_forms.PasswordResetForm): helper = FormHelper() helper.form_class = "login-form" helper.layout = Layout("email", Submit("submit", _("Reset my password"))) # pylint: disable=arguments-differ def save(self, *args, **kwargs): """ Generates a one-use only link for resetting password and sends to the Copy of Django's implementation, changed to use our own email-sending. """ user_model = get_user_model() email = self.cleaned_data["email"] active_users = user_model.objects.filter(email__iexact=email, is_active=True) for user in active_users: # Make sure that no email is sent to a user that actually has # a password marked as unusable if not user.has_usable_password(): continue uid = urlsafe_base64_encode(force_bytes(user.pk)) token = default_token_generator.make_token(user) send_password_reset(user, uid, token) class SetPasswordForm(auth_forms.SetPasswordForm): helper = FormHelper() helper.form_class = "login-form" helper.layout = Layout("new_password1", Submit("submit", _("Change my password"))) def __init__(self, user, *args, **kwargs): super(SetPasswordForm, self).__init__(user, *args, **kwargs) del self.fields["new_password2"] class ChangePasswordForm(forms.ModelForm): class Meta: model = User fields: List[str] = [] password_old = forms.CharField( widget=forms.PasswordInput(), label=_("Enter your old password for confirmation"), required=True, ) password_new = forms.CharField( widget=forms.PasswordInput(), label=_("New password"), required=True ) helper = FormHelper() helper.layout = Layout( "password_old", "password_new", Submit("submit", _("Save changes"), css_class="btn btn-primary"), ) def clean(self): cleaned_data = super(ChangePasswordForm, self).clean() password_old = cleaned_data.get("password_old", "") self.password_new = cleaned_data.get("password_new", "") # If either old or new password is None, then we get an inline error and don't want to raise ValidationError if ( password_old and self.password_new and not self.instance.check_password(password_old) ): raise forms.ValidationError( _("The old password you've entered is not correct!") ) return cleaned_data def save(self, commit=True): self.instance.set_password(self.password_new) return super(ChangePasswordForm, self).save(commit)
isc
NathanMH/scripts
noncerto_twitter.py
1
1617
import smtplib from email.message import EmailMessage import tweepy import authentication CONSUMER_KEY = authentication.CONSUMER_KEY CONSUMER_SECRET = authentication.CONSUMER_SECRET ACCESS_TOKEN = authentication.ACCESS_KEY ACCESS_TOKEN_SECRET = authentication.ACCESS_SECRET SEND_EMAIL_ADDRESS = authentication.SEND_EMAIL_ADDRESS EMAIL_PASS = authentication.EMAIL_PASS RECEIVE_EMAIL_ADDRESS = authentication.RECEIVE_EMAIL_ADDRESS SUBJECT = "Noncerto just tweeted." # Email def send_email(): server = smtplib.SMTP_SSL('smtp.gmail.com', 465) server.login(SEND_EMAIL_ADDRESS, EMAIL_PASS) BODY = '\r\n'.join(['To: %s' % RECEIVE_EMAIL_ADDRESS, 'From: %s' % SEND_EMAIL_ADDRESS, 'Subject: %s' % SUBJECT, ]) # server.sendmail(SEND_EMAIL_ADDRESS, RECEIVE_EMAIL_ADDRESS, BODY) server.sendmail(SEND_EMAIL_ADDRESS, authentication.TEST_RECEIVE_EMAIL_ADDRESS, BODY) # Twitter def authen(): """ Authentication for Twitter. """ auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET) api = tweepy.API(auth) return api class MyStreamListener(tweepy.StreamListener): def on_status(self, status): send_email() if __name__ == "__main__": API = authen() # Username: "noncerto" USERID = "2657045784" TEST_USERID = "575930104" myStreamListener = MyStreamListener() myStream = tweepy.Stream(auth=API.auth, listener=myStreamListener) # myStream.filter(follow=[USERID]) # Test myStream.filter(follow=[TEST_USERID])
mit
timduru/platform-external-chromium_org
third_party/simplejson/scanner.py
674
2560
"""JSON token scanner """ import re def _import_c_make_scanner(): try: from simplejson._speedups import make_scanner return make_scanner except ImportError: return None c_make_scanner = _import_c_make_scanner() __all__ = ['make_scanner'] NUMBER_RE = re.compile( r'(-?(?:0|[1-9]\d*))(\.\d+)?([eE][-+]?\d+)?', (re.VERBOSE | re.MULTILINE | re.DOTALL)) def py_make_scanner(context): parse_object = context.parse_object parse_array = context.parse_array parse_string = context.parse_string match_number = NUMBER_RE.match encoding = context.encoding strict = context.strict parse_float = context.parse_float parse_int = context.parse_int parse_constant = context.parse_constant object_hook = context.object_hook object_pairs_hook = context.object_pairs_hook memo = context.memo def _scan_once(string, idx): try: nextchar = string[idx] except IndexError: raise StopIteration if nextchar == '"': return parse_string(string, idx + 1, encoding, strict) elif nextchar == '{': return parse_object((string, idx + 1), encoding, strict, _scan_once, object_hook, object_pairs_hook, memo) elif nextchar == '[': return parse_array((string, idx + 1), _scan_once) elif nextchar == 'n' and string[idx:idx + 4] == 'null': return None, idx + 4 elif nextchar == 't' and string[idx:idx + 4] == 'true': return True, idx + 4 elif nextchar == 'f' and string[idx:idx + 5] == 'false': return False, idx + 5 m = match_number(string, idx) if m is not None: integer, frac, exp = m.groups() if frac or exp: res = parse_float(integer + (frac or '') + (exp or '')) else: res = parse_int(integer) return res, m.end() elif nextchar == 'N' and string[idx:idx + 3] == 'NaN': return parse_constant('NaN'), idx + 3 elif nextchar == 'I' and string[idx:idx + 8] == 'Infinity': return parse_constant('Infinity'), idx + 8 elif nextchar == '-' and string[idx:idx + 9] == '-Infinity': return parse_constant('-Infinity'), idx + 9 else: raise StopIteration def scan_once(string, idx): try: return _scan_once(string, idx) finally: memo.clear() return scan_once make_scanner = c_make_scanner or py_make_scanner
bsd-3-clause
facebook/mysql-5.6
xtrabackup/test/kewpie/percona_tests/xtrabackup_disabled/xb_stats_test.py
19
5345
#! /usr/bin/env python # -*- mode: python; indent-tabs-mode: nil; -*- # vim:expandtab:shiftwidth=2:tabstop=2:smarttab: # # Copyright (C) 2011 Patrick Crews # # # 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 shutil from lib.util.mysqlBaseTestCase import mysqlBaseTestCase server_requirements = [[]] servers = [] server_manager = None test_executor = None # we explicitly use the --no-timestamp option # here. We will be using a generic / vanilla backup dir backup_path = None class basicTest(mysqlBaseTestCase): def setUp(self): master_server = servers[0] # assumption that this is 'master' backup_path = os.path.join(master_server.vardir, '_xtrabackup') # remove backup path if os.path.exists(backup_path): shutil.rmtree(backup_path) def test_xb_stats(self): self.servers = servers logging = test_executor.logging if servers[0].type not in ['mysql','percona']: return else: innobackupex = test_executor.system_manager.innobackupex_path xtrabackup = test_executor.system_manager.xtrabackup_path master_server = servers[0] # assumption that this is 'master' backup_path = os.path.join(master_server.vardir, '_xtrabackup') output_path = os.path.join(master_server.vardir, 'innobackupex.out') exec_path = os.path.dirname(innobackupex) table_name = "`test`" # populate our server with a test bed test_cmd = "./gentest.pl --gendata=conf/percona/percona.zz" retcode, output = self.execute_randgen(test_cmd, test_executor, master_server) # take a backup cmd = [ xtrabackup , "--defaults-file=%s" %master_server.cnf_file , "--backup" , "--datadir=%s" %(master_server.datadir) , "--target-dir=%s" %backup_path ] cmd = " ".join(cmd) retcode, output = self.execute_cmd(cmd, output_path, exec_path, True) self.assertEqual(retcode,0,output) # first prepare cmd = [ xtrabackup , "--defaults-file=%s" %master_server.cnf_file , "--prepare" , "--datadir=%s" %(master_server.datadir) , "--target-dir=%s" %backup_path ] cmd = " ".join(cmd) retcode, output = self.execute_cmd(cmd, output_path, exec_path, True ) self.assertEqual(retcode,0,output) # Attempt to use --stats, which should fail # as we haven't finished our prepare statement yet cmd = [ xtrabackup , "--defaults-file=%s" %master_server.cnf_file , "--stats" , "--datadir=%s" %(backup_path) ] cmd = " ".join(cmd) retcode, output = self.execute_cmd(cmd, output_path, exec_path, True) self.assertEqual(retcode,1,output) expected_output1 = "xtrabackup: Error: Cannot find log file ib_logfile0." expected_output2 = "xtrabackup: Error: to use the statistics feature, you need a clean copy of the database including correctly sized log files, so you need to execute with --prepare twice to use this functionality on a backup." output_split = output.strip().split('\n')[-2:] # last 2 lines line1 = output_split[0].strip() line2 = output_split[1].strip() self.assertEqual(line1, expected_output1, msg= "Expected: %s || actual: %s || full: %s" %(expected_output1, line1, output)) self.assertEqual(line2, expected_output2, msg= "Expected: %s || actual: %s || full: %s" %(expected_output2, line2, output)) # second prepare cmd = [ xtrabackup , "--defaults-file=%s" %master_server.cnf_file , "--prepare" , "--datadir=%s" %(master_server.datadir) , "--target-dir=%s" %backup_path ] cmd = " ".join(cmd) retcode, output = self.execute_cmd(cmd, output_path, exec_path, True) self.assertEqual(retcode,0,output) # Attempt to use --stats, which should work this time cmd = [ xtrabackup , "--defaults-file=%s" %master_server.cnf_file , "--stats" , "--datadir=%s" %(backup_path) ] cmd = " ".join(cmd) retcode, output = self.execute_cmd(cmd, output_path, exec_path, True) self.assertEqual(retcode,0,output)
gpl-2.0
ZHAW-INES/rioxo-uClinux-dist
user/python/python-2.4.4/Lib/plat-irix6/cdplayer.py
8
2975
# This file implements a class which forms an interface to the .cdplayerrc # file that is maintained by SGI's cdplayer program. # # Usage is as follows: # # import readcd # r = readcd.Readcd() # c = Cdplayer(r.gettrackinfo()) # # Now you can use c.artist, c.title and c.track[trackno] (where trackno # starts at 1). When the CD is not recognized, all values will be the empty # string. # It is also possible to set the above mentioned variables to new values. # You can then use c.write() to write out the changed values to the # .cdplayerrc file. cdplayerrc = '.cdplayerrc' class Cdplayer: def __init__(self, tracklist): import string self.artist = '' self.title = '' if type(tracklist) == type(''): t = [] for i in range(2, len(tracklist), 4): t.append((None, \ (int(tracklist[i:i+2]), \ int(tracklist[i+2:i+4])))) tracklist = t self.track = [None] + [''] * len(tracklist) self.id = 'd' + string.zfill(len(tracklist), 2) for track in tracklist: start, length = track self.id = self.id + string.zfill(length[0], 2) + \ string.zfill(length[1], 2) try: import posix f = open(posix.environ['HOME'] + '/' + cdplayerrc, 'r') except IOError: return import re reg = re.compile(r'^([^:]*):\t(.*)') s = self.id + '.' l = len(s) while 1: line = f.readline() if line == '': break if line[:l] == s: line = line[l:] match = reg.match(line) if not match: print 'syntax error in ~/' + cdplayerrc continue name, value = match.group(1, 2) if name == 'title': self.title = value elif name == 'artist': self.artist = value elif name[:5] == 'track': trackno = int(name[6:]) self.track[trackno] = value f.close() def write(self): import posix filename = posix.environ['HOME'] + '/' + cdplayerrc try: old = open(filename, 'r') except IOError: old = open('/dev/null', 'r') new = open(filename + '.new', 'w') s = self.id + '.' l = len(s) while 1: line = old.readline() if line == '': break if line[:l] != s: new.write(line) new.write(self.id + '.title:\t' + self.title + '\n') new.write(self.id + '.artist:\t' + self.artist + '\n') for i in range(1, len(self.track)): new.write('%s.track.%r:\t%s\n' % (i, track)) old.close() new.close() posix.rename(filename + '.new', filename)
gpl-2.0
minggo/electron
tools/win/generate_breakpad_symbols.py
188
3481
#!/usr/bin/env python # Copyright (c) 2013 GitHub, Inc. # Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Convert pdb to sym for given directories""" import errno import glob import optparse import os import Queue import re import subprocess import sys import threading CONCURRENT_TASKS=4 SOURCE_ROOT=os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) DUMP_SYMS=os.path.join(SOURCE_ROOT, 'vendor', 'breakpad', 'dump_syms.exe') def GetCommandOutput(command): """Runs the command list, returning its output. Prints the given command (which should be a list of one or more strings), then runs it and returns its output (stdout) as a string. From chromium_utils. """ devnull = open(os.devnull, 'w') proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=devnull, bufsize=1) output = proc.communicate()[0] return output def mkdir_p(path): """Simulates mkdir -p.""" try: os.makedirs(path) except OSError as e: if e.errno == errno.EEXIST and os.path.isdir(path): pass else: raise def GenerateSymbols(options, binaries): """Dumps the symbols of binary and places them in the given directory.""" queue = Queue.Queue() print_lock = threading.Lock() def _Worker(): while True: binary = queue.get() if options.verbose: with print_lock: print "Generating symbols for %s" % binary syms = GetCommandOutput([DUMP_SYMS, binary]) module_line = re.match("MODULE [^ ]+ [^ ]+ ([0-9A-Fa-f]+) (.*)\r\n", syms) if module_line == None: with print_lock: print "Failed to get symbols for %s" % binary queue.task_done() continue output_path = os.path.join(options.symbols_dir, module_line.group(2), module_line.group(1)) mkdir_p(output_path) symbol_file = "%s.sym" % module_line.group(2)[:-4] # strip .pdb f = open(os.path.join(output_path, symbol_file), 'w') f.write(syms) f.close() queue.task_done() for binary in binaries: queue.put(binary) for _ in range(options.jobs): t = threading.Thread(target=_Worker) t.daemon = True t.start() queue.join() def main(): parser = optparse.OptionParser() parser.add_option('', '--symbols-dir', default='', help='The directory where to write the symbols file.') parser.add_option('', '--clear', default=False, action='store_true', help='Clear the symbols directory before writing new ' 'symbols.') parser.add_option('-j', '--jobs', default=CONCURRENT_TASKS, action='store', type='int', help='Number of parallel tasks to run.') parser.add_option('-v', '--verbose', action='store_true', help='Print verbose status output.') (options, directories) = parser.parse_args() if not options.symbols_dir: print "Required option --symbols-dir missing." return 1 if options.clear: try: shutil.rmtree(options.symbols_dir) except: pass pdbs = [] for directory in directories: pdbs += glob.glob(os.path.join(directory, '*.exe.pdb')) pdbs += glob.glob(os.path.join(directory, '*.dll.pdb')) GenerateSymbols(options, pdbs) return 0 if '__main__' == __name__: sys.exit(main())
mit
swangui/ggrid
mako/cache.py
19
7735
# mako/cache.py # Copyright (C) 2006-2012 the Mako authors and contributors <see AUTHORS file> # # This module is part of Mako and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php from mako import exceptions, util _cache_plugins = util.PluginLoader("mako.cache") register_plugin = _cache_plugins.register register_plugin("beaker", "mako.ext.beaker_cache", "BeakerCacheImpl") class Cache(object): """Represents a data content cache made available to the module space of a specific :class:`.Template` object. .. versionadded:: 0.6 :class:`.Cache` by itself is mostly a container for a :class:`.CacheImpl` object, which implements a fixed API to provide caching services; specific subclasses exist to implement different caching strategies. Mako includes a backend that works with the Beaker caching system. Beaker itself then supports a number of backends (i.e. file, memory, memcached, etc.) The construction of a :class:`.Cache` is part of the mechanics of a :class:`.Template`, and programmatic access to this cache is typically via the :attr:`.Template.cache` attribute. """ impl = None """Provide the :class:`.CacheImpl` in use by this :class:`.Cache`. This accessor allows a :class:`.CacheImpl` with additional methods beyond that of :class:`.Cache` to be used programmatically. """ id = None """Return the 'id' that identifies this cache. This is a value that should be globally unique to the :class:`.Template` associated with this cache, and can be used by a caching system to name a local container for data specific to this template. """ starttime = None """Epochal time value for when the owning :class:`.Template` was first compiled. A cache implementation may wish to invalidate data earlier than this timestamp; this has the effect of the cache for a specific :class:`.Template` starting clean any time the :class:`.Template` is recompiled, such as when the original template file changed on the filesystem. """ def __init__(self, template, *args): # check for a stale template calling the # constructor if isinstance(template, basestring) and args: return self.template = template self.id = template.module.__name__ self.starttime = template.module._modified_time self._def_regions = {} self.impl = self._load_impl(self.template.cache_impl) def _load_impl(self, name): return _cache_plugins.load(name)(self) def get_or_create(self, key, creation_function, **kw): """Retrieve a value from the cache, using the given creation function to generate a new value.""" return self._ctx_get_or_create(key, creation_function, None, **kw) def _ctx_get_or_create(self, key, creation_function, context, **kw): """Retrieve a value from the cache, using the given creation function to generate a new value.""" if not self.template.cache_enabled: return creation_function() return self.impl.get_or_create(key, creation_function, **self._get_cache_kw(kw, context)) def set(self, key, value, **kw): """Place a value in the cache. :param key: the value's key. :param value: the value. :param \**kw: cache configuration arguments. """ self.impl.set(key, value, **self._get_cache_kw(kw, None)) put = set """A synonym for :meth:`.Cache.set`. This is here for backwards compatibility. """ def get(self, key, **kw): """Retrieve a value from the cache. :param key: the value's key. :param \**kw: cache configuration arguments. The backend is configured using these arguments upon first request. Subsequent requests that use the same series of configuration values will use that same backend. """ return self.impl.get(key, **self._get_cache_kw(kw, None)) def invalidate(self, key, **kw): """Invalidate a value in the cache. :param key: the value's key. :param \**kw: cache configuration arguments. The backend is configured using these arguments upon first request. Subsequent requests that use the same series of configuration values will use that same backend. """ self.impl.invalidate(key, **self._get_cache_kw(kw, None)) def invalidate_body(self): """Invalidate the cached content of the "body" method for this template. """ self.invalidate('render_body', __M_defname='render_body') def invalidate_def(self, name): """Invalidate the cached content of a particular ``<%def>`` within this template. """ self.invalidate('render_%s' % name, __M_defname='render_%s' % name) def invalidate_closure(self, name): """Invalidate a nested ``<%def>`` within this template. Caching of nested defs is a blunt tool as there is no management of scope -- nested defs that use cache tags need to have names unique of all other nested defs in the template, else their content will be overwritten by each other. """ self.invalidate(name, __M_defname=name) def _get_cache_kw(self, kw, context): defname = kw.pop('__M_defname', None) if not defname: tmpl_kw = self.template.cache_args.copy() tmpl_kw.update(kw) elif defname in self._def_regions: tmpl_kw = self._def_regions[defname] else: tmpl_kw = self.template.cache_args.copy() tmpl_kw.update(kw) self._def_regions[defname] = tmpl_kw if context and self.impl.pass_context: tmpl_kw = tmpl_kw.copy() tmpl_kw.setdefault('context', context) return tmpl_kw class CacheImpl(object): """Provide a cache implementation for use by :class:`.Cache`.""" def __init__(self, cache): self.cache = cache pass_context = False """If ``True``, the :class:`.Context` will be passed to :meth:`get_or_create <.CacheImpl.get_or_create>` as the name ``'context'``. """ def get_or_create(self, key, creation_function, **kw): """Retrieve a value from the cache, using the given creation function to generate a new value. This function *must* return a value, either from the cache, or via the given creation function. If the creation function is called, the newly created value should be populated into the cache under the given key before being returned. :param key: the value's key. :param creation_function: function that when called generates a new value. :param \**kw: cache configuration arguments. """ raise NotImplementedError() def set(self, key, value, **kw): """Place a value in the cache. :param key: the value's key. :param value: the value. :param \**kw: cache configuration arguments. """ raise NotImplementedError() def get(self, key, **kw): """Retrieve a value from the cache. :param key: the value's key. :param \**kw: cache configuration arguments. """ raise NotImplementedError() def invalidate(self, key, **kw): """Invalidate a value in the cache. :param key: the value's key. :param \**kw: cache configuration arguments. """ raise NotImplementedError()
mit
LinuxChristian/home-assistant
homeassistant/components/sensor/rfxtrx.py
12
4744
""" Support for RFXtrx sensors. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.rfxtrx/ """ import logging import voluptuous as vol import homeassistant.components.rfxtrx as rfxtrx import homeassistant.helpers.config_validation as cv from homeassistant.const import CONF_PLATFORM from homeassistant.helpers.entity import Entity from homeassistant.util import slugify from homeassistant.components.rfxtrx import ( ATTR_AUTOMATIC_ADD, ATTR_NAME, ATTR_FIREEVENT, CONF_DEVICES, DATA_TYPES, ATTR_DATA_TYPE, ATTR_ENTITY_ID) DEPENDENCIES = ['rfxtrx'] _LOGGER = logging.getLogger(__name__) PLATFORM_SCHEMA = vol.Schema({ vol.Required(CONF_PLATFORM): rfxtrx.DOMAIN, vol.Optional(CONF_DEVICES, default={}): vol.All(dict, rfxtrx.valid_sensor), vol.Optional(ATTR_AUTOMATIC_ADD, default=False): cv.boolean, }, extra=vol.ALLOW_EXTRA) def setup_platform(hass, config, add_devices_callback, discovery_info=None): """Set up the RFXtrx platform.""" from RFXtrx import SensorEvent sensors = [] for packet_id, entity_info in config[CONF_DEVICES].items(): event = rfxtrx.get_rfx_object(packet_id) device_id = "sensor_" + slugify(event.device.id_string.lower()) if device_id in rfxtrx.RFX_DEVICES: continue _LOGGER.info("Add %s rfxtrx.sensor", entity_info[ATTR_NAME]) sub_sensors = {} data_types = entity_info[ATTR_DATA_TYPE] if not data_types: data_types = [''] for data_type in DATA_TYPES: if data_type in event.values: data_types = [data_type] break for _data_type in data_types: new_sensor = RfxtrxSensor(None, entity_info[ATTR_NAME], _data_type, entity_info[ATTR_FIREEVENT]) sensors.append(new_sensor) sub_sensors[_data_type] = new_sensor rfxtrx.RFX_DEVICES[device_id] = sub_sensors add_devices_callback(sensors) def sensor_update(event): """Handle sensor updates from the RFXtrx gateway.""" if not isinstance(event, SensorEvent): return device_id = "sensor_" + slugify(event.device.id_string.lower()) if device_id in rfxtrx.RFX_DEVICES: sensors = rfxtrx.RFX_DEVICES[device_id] for key in sensors: sensor = sensors[key] sensor.event = event # Fire event if sensors[key].should_fire_event: sensor.hass.bus.fire( "signal_received", { ATTR_ENTITY_ID: sensors[key].entity_id, } ) return # Add entity if not exist and the automatic_add is True if not config[ATTR_AUTOMATIC_ADD]: return pkt_id = "".join("{0:02x}".format(x) for x in event.data) _LOGGER.info("Automatic add rfxtrx.sensor: %s", pkt_id) data_type = '' for _data_type in DATA_TYPES: if _data_type in event.values: data_type = _data_type break new_sensor = RfxtrxSensor(event, pkt_id, data_type) sub_sensors = {} sub_sensors[new_sensor.data_type] = new_sensor rfxtrx.RFX_DEVICES[device_id] = sub_sensors add_devices_callback([new_sensor]) if sensor_update not in rfxtrx.RECEIVED_EVT_SUBSCRIBERS: rfxtrx.RECEIVED_EVT_SUBSCRIBERS.append(sensor_update) class RfxtrxSensor(Entity): """Representation of a RFXtrx sensor.""" def __init__(self, event, name, data_type, should_fire_event=False): """Initialize the sensor.""" self.event = event self._name = name self.should_fire_event = should_fire_event self.data_type = data_type self._unit_of_measurement = DATA_TYPES.get(data_type, '') def __str__(self): """Return the name of the sensor.""" return self._name @property def state(self): """Return the state of the sensor.""" if not self.event: return None return self.event.values.get(self.data_type) @property def name(self): """Get the name of the sensor.""" return "{} {}".format(self._name, self.data_type) @property def device_state_attributes(self): """Return the state attributes.""" if not self.event: return None return self.event.values @property def unit_of_measurement(self): """Return the unit this state is expressed in.""" return self._unit_of_measurement
apache-2.0
brownharryb/erpnext
erpnext/accounts/report/trial_balance_for_party/trial_balance_for_party.py
8
5969
# Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe import _ from frappe.utils import flt, cint from erpnext.accounts.report.trial_balance.trial_balance import validate_filters def execute(filters=None): validate_filters(filters) show_party_name = is_party_name_visible(filters) columns = get_columns(filters, show_party_name) data = get_data(filters, show_party_name) return columns, data def get_data(filters, show_party_name): party_name_field = "{0}_name".format(frappe.scrub(filters.get('party_type'))) if filters.get('party_type') == 'Student': party_name_field = 'first_name' elif filters.get('party_type') == 'Shareholder': party_name_field = 'title' party_filters = {"name": filters.get("party")} if filters.get("party") else {} parties = frappe.get_all(filters.get("party_type"), fields = ["name", party_name_field], filters = party_filters, order_by="name") company_currency = frappe.get_cached_value('Company', filters.company, "default_currency") opening_balances = get_opening_balances(filters) balances_within_period = get_balances_within_period(filters) data = [] # total_debit, total_credit = 0, 0 total_row = frappe._dict({ "opening_debit": 0, "opening_credit": 0, "debit": 0, "credit": 0, "closing_debit": 0, "closing_credit": 0 }) for party in parties: row = { "party": party.name } if show_party_name: row["party_name"] = party.get(party_name_field) # opening opening_debit, opening_credit = opening_balances.get(party.name, [0, 0]) row.update({ "opening_debit": opening_debit, "opening_credit": opening_credit }) # within period debit, credit = balances_within_period.get(party.name, [0, 0]) row.update({ "debit": debit, "credit": credit }) # closing closing_debit, closing_credit = toggle_debit_credit(opening_debit + debit, opening_credit + credit) row.update({ "closing_debit": closing_debit, "closing_credit": closing_credit }) # totals for col in total_row: total_row[col] += row.get(col) row.update({ "currency": company_currency }) has_value = False if (opening_debit or opening_credit or debit or credit or closing_debit or closing_credit): has_value =True if cint(filters.show_zero_values) or has_value: data.append(row) # Add total row total_row.update({ "party": "'" + _("Totals") + "'", "currency": company_currency }) data.append(total_row) return data def get_opening_balances(filters): gle = frappe.db.sql(""" select party, sum(debit) as opening_debit, sum(credit) as opening_credit from `tabGL Entry` where company=%(company)s and ifnull(party_type, '') = %(party_type)s and ifnull(party, '') != '' and (posting_date < %(from_date)s or ifnull(is_opening, 'No') = 'Yes') group by party""", { "company": filters.company, "from_date": filters.from_date, "party_type": filters.party_type }, as_dict=True) opening = frappe._dict() for d in gle: opening_debit, opening_credit = toggle_debit_credit(d.opening_debit, d.opening_credit) opening.setdefault(d.party, [opening_debit, opening_credit]) return opening def get_balances_within_period(filters): gle = frappe.db.sql(""" select party, sum(debit) as debit, sum(credit) as credit from `tabGL Entry` where company=%(company)s and ifnull(party_type, '') = %(party_type)s and ifnull(party, '') != '' and posting_date >= %(from_date)s and posting_date <= %(to_date)s and ifnull(is_opening, 'No') = 'No' group by party""", { "company": filters.company, "from_date": filters.from_date, "to_date": filters.to_date, "party_type": filters.party_type }, as_dict=True) balances_within_period = frappe._dict() for d in gle: balances_within_period.setdefault(d.party, [d.debit, d.credit]) return balances_within_period def toggle_debit_credit(debit, credit): if flt(debit) > flt(credit): debit = flt(debit) - flt(credit) credit = 0.0 else: credit = flt(credit) - flt(debit) debit = 0.0 return debit, credit def get_columns(filters, show_party_name): columns = [ { "fieldname": "party", "label": _(filters.party_type), "fieldtype": "Link", "options": filters.party_type, "width": 200 }, { "fieldname": "opening_debit", "label": _("Opening (Dr)"), "fieldtype": "Currency", "options": "currency", "width": 120 }, { "fieldname": "opening_credit", "label": _("Opening (Cr)"), "fieldtype": "Currency", "options": "currency", "width": 120 }, { "fieldname": "debit", "label": _("Debit"), "fieldtype": "Currency", "options": "currency", "width": 120 }, { "fieldname": "credit", "label": _("Credit"), "fieldtype": "Currency", "options": "currency", "width": 120 }, { "fieldname": "closing_debit", "label": _("Closing (Dr)"), "fieldtype": "Currency", "options": "currency", "width": 120 }, { "fieldname": "closing_credit", "label": _("Closing (Cr)"), "fieldtype": "Currency", "options": "currency", "width": 120 }, { "fieldname": "currency", "label": _("Currency"), "fieldtype": "Link", "options": "Currency", "hidden": 1 } ] if show_party_name: columns.insert(1, { "fieldname": "party_name", "label": _(filters.party_type) + " Name", "fieldtype": "Data", "width": 200 }) return columns def is_party_name_visible(filters): show_party_name = False if filters.get('party_type') in ['Customer', 'Supplier']: if filters.get("party_type") == "Customer": party_naming_by = frappe.db.get_single_value("Selling Settings", "cust_master_name") else: party_naming_by = frappe.db.get_single_value("Buying Settings", "supp_master_name") if party_naming_by == "Naming Series": show_party_name = True else: show_party_name = True return show_party_name
gpl-3.0
filias/django
tests/invalid_models_tests/test_models.py
10
24552
# -*- encoding: utf-8 -*- from __future__ import unicode_literals import unittest import warnings from django.conf import settings from django.core.checks import Error from django.db import connections, models from django.test import SimpleTestCase from django.test.utils import isolate_apps, override_settings def get_max_column_name_length(): allowed_len = None db_alias = None for db in settings.DATABASES.keys(): connection = connections[db] max_name_length = connection.ops.max_name_length() if max_name_length is None or connection.features.truncates_names: continue else: if allowed_len is None: allowed_len = max_name_length db_alias = db elif max_name_length < allowed_len: allowed_len = max_name_length db_alias = db return (allowed_len, db_alias) @isolate_apps('invalid_models_tests') class IndexTogetherTests(SimpleTestCase): def test_non_iterable(self): class Model(models.Model): class Meta: index_together = 42 errors = Model.check() expected = [ Error( "'index_together' must be a list or tuple.", obj=Model, id='models.E008', ), ] self.assertEqual(errors, expected) def test_non_list(self): class Model(models.Model): class Meta: index_together = 'not-a-list' errors = Model.check() expected = [ Error( "'index_together' must be a list or tuple.", obj=Model, id='models.E008', ), ] self.assertEqual(errors, expected) def test_list_containing_non_iterable(self): class Model(models.Model): class Meta: index_together = [('a', 'b'), 42] errors = Model.check() expected = [ Error( "All 'index_together' elements must be lists or tuples.", obj=Model, id='models.E009', ), ] self.assertEqual(errors, expected) def test_pointing_to_missing_field(self): class Model(models.Model): class Meta: index_together = [ ["missing_field"], ] errors = Model.check() expected = [ Error( "'index_together' refers to the non-existent field 'missing_field'.", obj=Model, id='models.E012', ), ] self.assertEqual(errors, expected) def test_pointing_to_non_local_field(self): class Foo(models.Model): field1 = models.IntegerField() class Bar(Foo): field2 = models.IntegerField() class Meta: index_together = [ ["field2", "field1"], ] errors = Bar.check() expected = [ Error( "'index_together' refers to field 'field1' which is not " "local to model 'Bar'.", hint=("This issue may be caused by multi-table inheritance."), obj=Bar, id='models.E016', ), ] self.assertEqual(errors, expected) def test_pointing_to_m2m_field(self): class Model(models.Model): m2m = models.ManyToManyField('self') class Meta: index_together = [ ["m2m"], ] errors = Model.check() expected = [ Error( "'index_together' refers to a ManyToManyField 'm2m', but " "ManyToManyFields are not permitted in 'index_together'.", obj=Model, id='models.E013', ), ] self.assertEqual(errors, expected) # unique_together tests are very similar to index_together tests. @isolate_apps('invalid_models_tests') class UniqueTogetherTests(SimpleTestCase): def test_non_iterable(self): class Model(models.Model): class Meta: unique_together = 42 errors = Model.check() expected = [ Error( "'unique_together' must be a list or tuple.", obj=Model, id='models.E010', ), ] self.assertEqual(errors, expected) def test_list_containing_non_iterable(self): class Model(models.Model): one = models.IntegerField() two = models.IntegerField() class Meta: unique_together = [('a', 'b'), 42] errors = Model.check() expected = [ Error( "All 'unique_together' elements must be lists or tuples.", obj=Model, id='models.E011', ), ] self.assertEqual(errors, expected) def test_non_list(self): class Model(models.Model): class Meta: unique_together = 'not-a-list' errors = Model.check() expected = [ Error( "'unique_together' must be a list or tuple.", obj=Model, id='models.E010', ), ] self.assertEqual(errors, expected) def test_valid_model(self): class Model(models.Model): one = models.IntegerField() two = models.IntegerField() class Meta: # unique_together can be a simple tuple unique_together = ('one', 'two') errors = Model.check() self.assertEqual(errors, []) def test_pointing_to_missing_field(self): class Model(models.Model): class Meta: unique_together = [ ["missing_field"], ] errors = Model.check() expected = [ Error( "'unique_together' refers to the non-existent field 'missing_field'.", obj=Model, id='models.E012', ), ] self.assertEqual(errors, expected) def test_pointing_to_m2m(self): class Model(models.Model): m2m = models.ManyToManyField('self') class Meta: unique_together = [ ["m2m"], ] errors = Model.check() expected = [ Error( "'unique_together' refers to a ManyToManyField 'm2m', but " "ManyToManyFields are not permitted in 'unique_together'.", obj=Model, id='models.E013', ), ] self.assertEqual(errors, expected) @isolate_apps('invalid_models_tests') class FieldNamesTests(SimpleTestCase): def test_ending_with_underscore(self): class Model(models.Model): field_ = models.CharField(max_length=10) m2m_ = models.ManyToManyField('self') errors = Model.check() expected = [ Error( 'Field names must not end with an underscore.', obj=Model._meta.get_field('field_'), id='fields.E001', ), Error( 'Field names must not end with an underscore.', obj=Model._meta.get_field('m2m_'), id='fields.E001', ), ] self.assertEqual(errors, expected) max_column_name_length, column_limit_db_alias = get_max_column_name_length() @unittest.skipIf(max_column_name_length is None, "The database doesn't have a column name length limit.") def test_M2M_long_column_name(self): """ #13711 -- Model check for long M2M column names when database has column name length limits. """ allowed_len, db_alias = get_max_column_name_length() # A model with very long name which will be used to set relations to. class VeryLongModelNamezzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz(models.Model): title = models.CharField(max_length=11) # Main model for which checks will be performed. class ModelWithLongField(models.Model): m2m_field = models.ManyToManyField( VeryLongModelNamezzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz, related_name="rn1" ) m2m_field2 = models.ManyToManyField( VeryLongModelNamezzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz, related_name="rn2", through='m2msimple' ) m2m_field3 = models.ManyToManyField( VeryLongModelNamezzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz, related_name="rn3", through='m2mcomplex' ) fk = models.ForeignKey( VeryLongModelNamezzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz, models.CASCADE, related_name="rn4", ) # Models used for setting `through` in M2M field. class m2msimple(models.Model): id2 = models.ForeignKey(ModelWithLongField, models.CASCADE) class m2mcomplex(models.Model): id2 = models.ForeignKey(ModelWithLongField, models.CASCADE) long_field_name = 'a' * (self.max_column_name_length + 1) models.ForeignKey( VeryLongModelNamezzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz, models.CASCADE, ).contribute_to_class(m2msimple, long_field_name) models.ForeignKey( VeryLongModelNamezzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz, models.CASCADE, db_column=long_field_name ).contribute_to_class(m2mcomplex, long_field_name) errors = ModelWithLongField.check() # First error because of M2M field set on the model with long name. m2m_long_name = "verylongmodelnamezzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz_id" if self.max_column_name_length > len(m2m_long_name): # Some databases support names longer than the test name. expected = [] else: expected = [ Error( 'Autogenerated column name too long for M2M field "%s". ' 'Maximum length is "%s" for database "%s".' % (m2m_long_name, self.max_column_name_length, self.column_limit_db_alias), hint="Use 'through' to create a separate model for " "M2M and then set column_name using 'db_column'.", obj=ModelWithLongField, id='models.E019', ) ] # Second error because the FK specified in the `through` model # `m2msimple` has auto-generated name longer than allowed. # There will be no check errors in the other M2M because it # specifies db_column for the FK in `through` model even if the actual # name is longer than the limits of the database. expected.append( Error( 'Autogenerated column name too long for M2M field "%s_id". ' 'Maximum length is "%s" for database "%s".' % (long_field_name, self.max_column_name_length, self.column_limit_db_alias), hint="Use 'through' to create a separate model for " "M2M and then set column_name using 'db_column'.", obj=ModelWithLongField, id='models.E019', ) ) self.assertEqual(errors, expected) @unittest.skipIf(max_column_name_length is None, "The database doesn't have a column name length limit.") def test_local_field_long_column_name(self): """ #13711 -- Model check for long column names when database does not support long names. """ allowed_len, db_alias = get_max_column_name_length() class ModelWithLongField(models.Model): title = models.CharField(max_length=11) long_field_name = 'a' * (self.max_column_name_length + 1) long_field_name2 = 'b' * (self.max_column_name_length + 1) models.CharField(max_length=11).contribute_to_class(ModelWithLongField, long_field_name) models.CharField(max_length=11, db_column='vlmn').contribute_to_class(ModelWithLongField, long_field_name2) errors = ModelWithLongField.check() # Error because of the field with long name added to the model # without specifying db_column expected = [ Error( 'Autogenerated column name too long for field "%s". ' 'Maximum length is "%s" for database "%s".' % (long_field_name, self.max_column_name_length, self.column_limit_db_alias), hint="Set the column name manually using 'db_column'.", obj=ModelWithLongField, id='models.E018', ) ] self.assertEqual(errors, expected) def test_including_separator(self): class Model(models.Model): some__field = models.IntegerField() errors = Model.check() expected = [ Error( 'Field names must not contain "__".', obj=Model._meta.get_field('some__field'), id='fields.E002', ) ] self.assertEqual(errors, expected) def test_pk(self): class Model(models.Model): pk = models.IntegerField() errors = Model.check() expected = [ Error( "'pk' is a reserved word that cannot be used as a field name.", obj=Model._meta.get_field('pk'), id='fields.E003', ) ] self.assertEqual(errors, expected) @isolate_apps('invalid_models_tests') class ShadowingFieldsTests(SimpleTestCase): def test_field_name_clash_with_child_accessor(self): class Parent(models.Model): pass class Child(Parent): child = models.CharField(max_length=100) errors = Child.check() expected = [ Error( "The field 'child' clashes with the field " "'child' from model 'invalid_models_tests.parent'.", obj=Child._meta.get_field('child'), id='models.E006', ) ] self.assertEqual(errors, expected) def test_multiinheritance_clash(self): class Mother(models.Model): clash = models.IntegerField() class Father(models.Model): clash = models.IntegerField() class Child(Mother, Father): # Here we have two clashed: id (automatic field) and clash, because # both parents define these fields. pass errors = Child.check() expected = [ Error( "The field 'id' from parent model " "'invalid_models_tests.mother' clashes with the field 'id' " "from parent model 'invalid_models_tests.father'.", obj=Child, id='models.E005', ), Error( "The field 'clash' from parent model " "'invalid_models_tests.mother' clashes with the field 'clash' " "from parent model 'invalid_models_tests.father'.", obj=Child, id='models.E005', ) ] self.assertEqual(errors, expected) def test_inheritance_clash(self): class Parent(models.Model): f_id = models.IntegerField() class Target(models.Model): # This field doesn't result in a clash. f_id = models.IntegerField() class Child(Parent): # This field clashes with parent "f_id" field. f = models.ForeignKey(Target, models.CASCADE) errors = Child.check() expected = [ Error( "The field 'f' clashes with the field 'f_id' " "from model 'invalid_models_tests.parent'.", obj=Child._meta.get_field('f'), id='models.E006', ) ] self.assertEqual(errors, expected) def test_multigeneration_inheritance(self): class GrandParent(models.Model): clash = models.IntegerField() class Parent(GrandParent): pass class Child(Parent): pass class GrandChild(Child): clash = models.IntegerField() errors = GrandChild.check() expected = [ Error( "The field 'clash' clashes with the field 'clash' " "from model 'invalid_models_tests.grandparent'.", obj=GrandChild._meta.get_field('clash'), id='models.E006', ) ] self.assertEqual(errors, expected) def test_id_clash(self): class Target(models.Model): pass class Model(models.Model): fk = models.ForeignKey(Target, models.CASCADE) fk_id = models.IntegerField() errors = Model.check() expected = [ Error( "The field 'fk_id' clashes with the field 'fk' from model " "'invalid_models_tests.model'.", obj=Model._meta.get_field('fk_id'), id='models.E006', ) ] self.assertEqual(errors, expected) @isolate_apps('invalid_models_tests') class OtherModelTests(SimpleTestCase): def test_unique_primary_key(self): invalid_id = models.IntegerField(primary_key=False) class Model(models.Model): id = invalid_id errors = Model.check() expected = [ Error( "'id' can only be used as a field name if the field also sets " "'primary_key=True'.", obj=Model, id='models.E004', ), ] self.assertEqual(errors, expected) def test_ordering_non_iterable(self): class Model(models.Model): class Meta: ordering = "missing_field" errors = Model.check() expected = [ Error( "'ordering' must be a tuple or list " "(even if you want to order by only one field).", obj=Model, id='models.E014', ), ] self.assertEqual(errors, expected) def test_just_ordering_no_errors(self): class Model(models.Model): order = models.PositiveIntegerField() class Meta: ordering = ['order'] self.assertEqual(Model.check(), []) def test_just_order_with_respect_to_no_errors(self): class Question(models.Model): pass class Answer(models.Model): question = models.ForeignKey(Question, models.CASCADE) class Meta: order_with_respect_to = 'question' self.assertEqual(Answer.check(), []) def test_ordering_with_order_with_respect_to(self): class Question(models.Model): pass class Answer(models.Model): question = models.ForeignKey(Question, models.CASCADE) order = models.IntegerField() class Meta: order_with_respect_to = 'question' ordering = ['order'] errors = Answer.check() expected = [ Error( "'ordering' and 'order_with_respect_to' cannot be used together.", obj=Answer, id='models.E021', ), ] self.assertEqual(errors, expected) def test_non_valid(self): class RelationModel(models.Model): pass class Model(models.Model): relation = models.ManyToManyField(RelationModel) class Meta: ordering = ['relation'] errors = Model.check() expected = [ Error( "'ordering' refers to the non-existent field 'relation'.", obj=Model, id='models.E015', ), ] self.assertEqual(errors, expected) def test_ordering_pointing_to_missing_field(self): class Model(models.Model): class Meta: ordering = ("missing_field",) errors = Model.check() expected = [ Error( "'ordering' refers to the non-existent field 'missing_field'.", obj=Model, id='models.E015', ) ] self.assertEqual(errors, expected) def test_ordering_pointing_to_missing_foreignkey_field(self): # refs #22711 class Model(models.Model): missing_fk_field = models.IntegerField() class Meta: ordering = ("missing_fk_field_id",) errors = Model.check() expected = [ Error( "'ordering' refers to the non-existent field 'missing_fk_field_id'.", obj=Model, id='models.E015', ) ] self.assertEqual(errors, expected) def test_ordering_pointing_to_existing_foreignkey_field(self): # refs #22711 class Parent(models.Model): pass class Child(models.Model): parent = models.ForeignKey(Parent, models.CASCADE) class Meta: ordering = ("parent_id",) self.assertFalse(Child.check()) @override_settings(TEST_SWAPPED_MODEL_BAD_VALUE='not-a-model') def test_swappable_missing_app_name(self): class Model(models.Model): class Meta: swappable = 'TEST_SWAPPED_MODEL_BAD_VALUE' errors = Model.check() expected = [ Error( "'TEST_SWAPPED_MODEL_BAD_VALUE' is not of the form 'app_label.app_name'.", id='models.E001', ), ] self.assertEqual(errors, expected) @override_settings(TEST_SWAPPED_MODEL_BAD_MODEL='not_an_app.Target') def test_swappable_missing_app(self): class Model(models.Model): class Meta: swappable = 'TEST_SWAPPED_MODEL_BAD_MODEL' errors = Model.check() expected = [ Error( "'TEST_SWAPPED_MODEL_BAD_MODEL' references 'not_an_app.Target', " 'which has not been installed, or is abstract.', id='models.E002', ), ] self.assertEqual(errors, expected) def test_two_m2m_through_same_relationship(self): class Person(models.Model): pass class Group(models.Model): primary = models.ManyToManyField(Person, through="Membership", related_name="primary") secondary = models.ManyToManyField(Person, through="Membership", related_name="secondary") class Membership(models.Model): person = models.ForeignKey(Person, models.CASCADE) group = models.ForeignKey(Group, models.CASCADE) errors = Group.check() expected = [ Error( "The model has two many-to-many relations through " "the intermediate model 'invalid_models_tests.Membership'.", obj=Group, id='models.E003', ) ] self.assertEqual(errors, expected) def test_missing_parent_link(self): with warnings.catch_warnings(record=True) as warns: warnings.simplefilter('always') class Place(models.Model): pass class ParkingLot(Place): # In lieu of any other connector, an existing OneToOneField will be # promoted to the primary key. parent = models.OneToOneField(Place, models.CASCADE) self.assertEqual(len(warns), 1) msg = str(warns[0].message) self.assertEqual( msg, 'Add parent_link=True to invalid_models_tests.ParkingLot.parent ' 'as an implicit link is deprecated.' ) self.assertEqual(ParkingLot._meta.pk.name, 'parent')
bsd-3-clause
SpaceKatt/CSPLN
apps/scaffolding/mac/web2py/web2py.app/Contents/Resources/applications/admin/languages/af.py
17
3528
# -*- coding: utf-8 -*- { '!langcode!': 'af', '!langname!': 'Afrikaanse', '%Y-%m-%d': '%Y-%m-%d', '%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S', '%s %%{row} deleted': '%s rows deleted', '%s %%{row} updated': '%s rows updated', '(requires internet access)': '(vereis internet toegang)', '(something like "it-it")': '(iets soos "it-it")', '@markmin\x01Searching: **%s** %%{file}': 'Soek: **%s** lêre', 'About': 'oor', 'About application': 'Oor program', 'Additional code for your application': 'Additionele kode vir u application', 'Admin language': 'Admin taal', 'Application name:': 'Program naam:', 'Change admin password': 'verander admin wagwoord', 'Check for upgrades': 'soek vir upgrades', 'Clean': 'maak skoon', 'Compile': 'kompileer', 'Controllers': 'Beheerders', 'Create': 'skep', 'Deploy': 'deploy', 'Deploy on Google App Engine': 'Stuur na Google App Engine toe', 'Edit': 'wysig', 'Edit application': 'Wysig program', 'Errors': 'foute', 'Help': 'hulp', 'Install': 'installeer', 'Installed applications': 'Geinstalleerde apps', 'Languages': 'Tale', 'License for': 'Lisensie vir', 'Logout': 'logout', 'Models': 'Modelle', 'Modules': 'Modules', 'New application wizard': 'Nuwe app wizard', 'New simple application': 'Nuwe eenvoudige app', 'Overwrite installed app': 'skryf oor geinstalleerde program', 'Pack all': 'pack alles', 'Plugins': 'Plugins', 'Powered by': 'Aangedryf deur', 'Site': 'site', 'Start wizard': 'start wizard', 'Static files': 'Static files', 'Sure you want to delete this object?': 'Is jy seker jy will hierde object verwyder?', 'The application logic, each URL path is mapped in one exposed function in the controller': 'The application logic, each URL path is mapped in one exposed function in the controller', 'The data representation, define database tables and sets': 'The data representation, define database tables and sets', 'The presentations layer, views are also known as templates': 'The presentations layer, views are also known as templates', 'There are no plugins': 'Daar is geen plugins', 'These files are served without processing, your images go here': 'Hierdie lêre is sonder veranderinge geserved, jou images gaan hier', 'To create a plugin, name a file/folder plugin_[name]': 'Om n plugin te skep, noem n lêer/gids plugin_[name]', 'Translation strings for the application': 'Vertaling woorde vir die program', 'Uninstall': 'verwyder', 'Upload & install packed application': 'Oplaai & install gepakte program', 'Upload a package:': 'Oplaai n package:', 'Use an url:': 'Gebruik n url:', 'Views': 'Views', 'administrative interface': 'administrative interface', 'and rename it:': 'en verander die naam:', 'collapse/expand all': 'collapse/expand all', 'controllers': 'beheerders', 'create file with filename:': 'skep lêer met naam:', 'created by': 'geskep deur', 'crontab': 'crontab', 'currently running': 'loop tans', 'database administration': 'database administration', 'direction: ltr': 'direction: ltr', 'download layouts': 'aflaai layouts', 'download plugins': 'aflaai plugins', 'exposes': 'exposes', 'extends': 'extends', 'filter': 'filter', 'includes': 'includes', 'languages': 'tale', 'loading...': 'laai...', 'models': 'modelle', 'modules': 'modules', 'plugins': 'plugins', 'shell': 'shell', 'static': 'static', 'test': 'toets', 'update all languages': 'update all languages', 'upload': 'oplaai', 'upload file:': 'oplaai lêer:', 'upload plugin file:': 'upload plugin lêer:', 'versioning': 'versioning', 'views': 'views', 'web2py Recent Tweets': 'web2py Onlangse Tweets', }
gpl-3.0
ericzolf/ansible
lib/ansible/module_utils/common/process.py
51
1679
# Copyright (c) 2018, Ansible Project # Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause) from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os from ansible.module_utils.common.file import is_executable def get_bin_path(arg, opt_dirs=None, required=None): ''' Find system executable in PATH. Raises ValueError if executable is not found. Optional arguments: - required: [Deprecated] Prior to 2.10, if executable is not found and required is true it raises an Exception. In 2.10 and later, an Exception is always raised. This parameter will be removed in 2.14. - opt_dirs: optional list of directories to search in addition to PATH If found return full path, otherwise raise ValueError. ''' opt_dirs = [] if opt_dirs is None else opt_dirs sbin_paths = ['/sbin', '/usr/sbin', '/usr/local/sbin'] paths = [] for d in opt_dirs: if d is not None and os.path.exists(d): paths.append(d) paths += os.environ.get('PATH', '').split(os.pathsep) bin_path = None # mangle PATH to include /sbin dirs for p in sbin_paths: if p not in paths and os.path.exists(p): paths.append(p) for d in paths: if not d: continue path = os.path.join(d, arg) if os.path.exists(path) and not os.path.isdir(path) and is_executable(path): bin_path = path break if bin_path is None: raise ValueError('Failed to find required executable %s in paths: %s' % (arg, os.pathsep.join(paths))) return bin_path
gpl-3.0
mmauroy/SickRage
tests/common_tests.py
12
8560
import unittest import sys import os.path sys.path.insert(1, os.path.abspath(os.path.join(os.path.dirname(__file__), '../lib'))) sys.path.insert(1, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) from sickbeard import common class QualityTests(unittest.TestCase): # TODO: repack / proper ? air-by-date ? season rip? multi-ep? def test_SDTV(self): self.assertEqual(common.Quality.SDTV, common.Quality.nameQuality("Test.Show.S01E02.PDTV.XViD-GROUP")) self.assertEqual(common.Quality.SDTV, common.Quality.nameQuality("Test.Show.S01E02.PDTV.x264-GROUP")) self.assertEqual(common.Quality.SDTV, common.Quality.nameQuality("Test.Show.S01E02.HDTV.XViD-GROUP")) self.assertEqual(common.Quality.SDTV, common.Quality.nameQuality("Test.Show.S01E02.HDTV.x264-GROUP")) self.assertEqual(common.Quality.SDTV, common.Quality.nameQuality("Test.Show.S01E02.DSR.XViD-GROUP")) self.assertEqual(common.Quality.SDTV, common.Quality.nameQuality("Test.Show.S01E02.DSR.x264-GROUP")) self.assertEqual(common.Quality.SDTV, common.Quality.nameQuality("Test.Show.S01E02.TVRip.XViD-GROUP")) self.assertEqual(common.Quality.SDTV, common.Quality.nameQuality("Test.Show.S01E02.TVRip.x264-GROUP")) self.assertEqual(common.Quality.SDTV, common.Quality.nameQuality("Test.Show.S01E02.WEBRip.XViD-GROUP")) self.assertEqual(common.Quality.SDTV, common.Quality.nameQuality("Test.Show.S01E02.WEBRip.x264-GROUP")) self.assertEqual(common.Quality.SDTV, common.Quality.nameQuality("Test.Show.S01E02.WEB-DL.x264-GROUP")) self.assertEqual(common.Quality.SDTV, common.Quality.nameQuality("Test.Show.S01E02.WEB-DL.AAC2.0.H.264-GROUP")) self.assertEqual(common.Quality.SDTV, common.Quality.nameQuality("Test.Show.S01E02 WEB-DL H 264-GROUP")) self.assertEqual(common.Quality.SDTV, common.Quality.nameQuality("Test.Show.S01E02_WEB-DL_H_264-GROUP")) self.assertEqual(common.Quality.SDTV, common.Quality.nameQuality("Test.Show.S01E02.WEB-DL.AAC2.0.H264-GROUP")) def test_SDDVD(self): self.assertEqual(common.Quality.SDDVD, common.Quality.nameQuality("Test.Show.S01E02.DVDRiP.XViD-GROUP")) self.assertEqual(common.Quality.SDDVD, common.Quality.nameQuality("Test.Show.S01E02.DVDRiP.DiVX-GROUP")) self.assertEqual(common.Quality.SDDVD, common.Quality.nameQuality("Test.Show.S01E02.DVDRiP.x264-GROUP")) self.assertEqual(common.Quality.SDDVD, common.Quality.nameQuality("Test.Show.S01E02.DVDRip.WS.XViD-GROUP")) self.assertEqual(common.Quality.SDDVD, common.Quality.nameQuality("Test.Show.S01E02.DVDRip.WS.DiVX-GROUP")) self.assertEqual(common.Quality.SDDVD, common.Quality.nameQuality("Test.Show.S01E02.DVDRip.WS.x264-GROUP")) self.assertEqual(common.Quality.SDDVD, common.Quality.nameQuality("Test.Show.S01E02.BDRIP.XViD-GROUP")) self.assertEqual(common.Quality.SDDVD, common.Quality.nameQuality("Test.Show.S01E02.BDRIP.DiVX-GROUP")) self.assertEqual(common.Quality.SDDVD, common.Quality.nameQuality("Test.Show.S01E02.BDRIP.x264-GROUP")) self.assertEqual(common.Quality.SDDVD, common.Quality.nameQuality("Test.Show.S01E02.BDRIP.WS.XViD-GROUP")) self.assertEqual(common.Quality.SDDVD, common.Quality.nameQuality("Test.Show.S01E02.BDRIP.WS.DiVX-GROUP")) self.assertEqual(common.Quality.SDDVD, common.Quality.nameQuality("Test.Show.S01E02.BDRIP.WS.x264-GROUP")) def test_HDTV(self): self.assertEqual(common.Quality.HDTV, common.Quality.nameQuality("Test.Show.S01E02.720p.HDTV.x264-GROUP")) self.assertEqual(common.Quality.HDTV, common.Quality.nameQuality("Test.Show.S01E02.HR.WS.PDTV.x264-GROUP")) def test_RAWHDTV(self): self.assertEqual(common.Quality.RAWHDTV, common.Quality.nameQuality("Test.Show.S01E02.720p.HDTV.DD5.1.MPEG2-GROUP")) self.assertEqual(common.Quality.RAWHDTV, common.Quality.nameQuality("Test.Show.S01E02.1080i.HDTV.DD2.0.MPEG2-GROUP")) self.assertEqual(common.Quality.RAWHDTV, common.Quality.nameQuality("Test.Show.S01E02.1080i.HDTV.H.264.DD2.0-GROUP")) self.assertEqual(common.Quality.RAWHDTV, common.Quality.nameQuality("Test Show - S01E02 - 1080i HDTV MPA1.0 H.264 - GROUP")) self.assertEqual(common.Quality.RAWHDTV, common.Quality.nameQuality("Test.Show.S01E02.1080i.HDTV.DD.5.1.h264-GROUP")) def test_FULLHDTV(self): self.assertEqual(common.Quality.FULLHDTV, common.Quality.nameQuality("Test.Show.S01E02.1080p.HDTV.x264-GROUP")) def test_HDWEBDL(self): self.assertEqual(common.Quality.HDWEBDL, common.Quality.nameQuality("Test.Show.S01E02.720p.WEB-DL-GROUP")) self.assertEqual(common.Quality.HDWEBDL, common.Quality.nameQuality("Test.Show.S01E02.720p.WEBRip-GROUP")) self.assertEqual(common.Quality.HDWEBDL, common.Quality.nameQuality("Test.Show.S01E02.WEBRip.720p.H.264.AAC.2.0-GROUP")) self.assertEqual(common.Quality.HDWEBDL, common.Quality.nameQuality("Test.Show.S01E02.720p.WEB-DL.AAC2.0.H.264-GROUP")) self.assertEqual(common.Quality.HDWEBDL, common.Quality.nameQuality("Test Show S01E02 720p WEB-DL AAC2 0 H 264-GROUP")) self.assertEqual(common.Quality.HDWEBDL, common.Quality.nameQuality("Test_Show.S01E02_720p_WEB-DL_AAC2.0_H264-GROUP")) self.assertEqual(common.Quality.HDWEBDL, common.Quality.nameQuality("Test.Show.S01E02.720p.WEB-DL.AAC2.0.H264-GROUP")) self.assertEqual(common.Quality.HDWEBDL, common.Quality.nameQuality("Test.Show.S01E02.720p.iTunes.Rip.H264.AAC-GROUP")) def test_FULLHDWEBDL(self): self.assertEqual(common.Quality.FULLHDWEBDL, common.Quality.nameQuality("Test.Show.S01E02.1080p.WEB-DL-GROUP")) self.assertEqual(common.Quality.FULLHDWEBDL, common.Quality.nameQuality("Test.Show.S01E02.1080p.WEBRip-GROUP")) self.assertEqual(common.Quality.FULLHDWEBDL, common.Quality.nameQuality("Test.Show.S01E02.WEBRip.1080p.H.264.AAC.2.0-GROUP")) self.assertEqual(common.Quality.FULLHDWEBDL, common.Quality.nameQuality("Test.Show.S01E02.WEBRip.1080p.H264.AAC.2.0-GROUP")) self.assertEqual(common.Quality.FULLHDWEBDL, common.Quality.nameQuality("Test.Show.S01E02.1080p.iTunes.H.264.AAC-GROUP")) self.assertEqual(common.Quality.FULLHDWEBDL, common.Quality.nameQuality("Test Show S01E02 1080p iTunes H 264 AAC-GROUP")) self.assertEqual(common.Quality.FULLHDWEBDL, common.Quality.nameQuality("Test_Show_S01E02_1080p_iTunes_H_264_AAC-GROUP")) def test_HDBLURAY(self): self.assertEqual(common.Quality.HDBLURAY, common.Quality.nameQuality("Test.Show.S01E02.720p.BluRay.x264-GROUP")) self.assertEqual(common.Quality.HDBLURAY, common.Quality.nameQuality("Test.Show.S01E02.720p.HDDVD.x264-GROUP")) def test_FULLHDBLURAY(self): self.assertEqual(common.Quality.FULLHDBLURAY, common.Quality.nameQuality("Test.Show.S01E02.1080p.BluRay.x264-GROUP")) self.assertEqual(common.Quality.FULLHDBLURAY, common.Quality.nameQuality("Test.Show.S01E02.1080p.HDDVD.x264-GROUP")) def test_UNKNOWN(self): self.assertEqual(common.Quality.UNKNOWN, common.Quality.nameQuality("Test.Show.S01E02-SiCKBEARD")) # def test_reverse_parsing(self): # self.assertEqual(common.Quality.SDTV, common.Quality.nameQuality("Test Show - S01E02 - SDTV - GROUP")) # self.assertEqual(common.Quality.SDDVD, common.Quality.nameQuality("Test Show - S01E02 - SD DVD - GROUP")) # self.assertEqual(common.Quality.HDTV, common.Quality.nameQuality("Test Show - S01E02 - HDTV - GROUP")) # self.assertEqual(common.Quality.RAWHDTV, common.Quality.nameQuality("Test Show - S01E02 - RawHD - GROUP")) # self.assertEqual(common.Quality.FULLHDTV, common.Quality.nameQuality("Test Show - S01E02 - 1080p HDTV - GROUP")) # self.assertEqual(common.Quality.HDWEBDL, common.Quality.nameQuality("Test Show - S01E02 - 720p WEB-DL - GROUP")) # self.assertEqual(common.Quality.FULLHDWEBDL, common.Quality.nameQuality("Test Show - S01E02 - 1080p WEB-DL - GROUP")) # self.assertEqual(common.Quality.HDBLURAY, common.Quality.nameQuality("Test Show - S01E02 - 720p BluRay - GROUP")) # self.assertEqual(common.Quality.FULLHDBLURAY, common.Quality.nameQuality("Test Show - S01E02 - 1080p BluRay - GROUP")) # self.assertEqual(common.Quality.UNKNOWN, common.Quality.nameQuality("Test Show - S01E02 - Unknown - SiCKBEARD")) if __name__ == '__main__': suite = unittest.TestLoader().loadTestsFromTestCase(QualityTests) unittest.TextTestRunner(verbosity=2).run(suite)
gpl-3.0
ignacioelola/nlp_experiments
exp.py
1
1625
import gensim import logging import sys # logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) def book_to_sentences(filename): with open(filename, 'rb') as infile: sentences = [] sentence = [] for line in infile.readlines(): clean_line = line.lower().replace('-', '').replace(',', '').replace(';', '').replace(':', '').replace('?', '.').replace('!', '.').replace('_', '').replace('\n', '').replace('\r', '').replace('\xef', '').replace('\xbb', '').replace('\xbf', '') if '.' in clean_line: for i in range(0, clean_line.count('.')): sentence.extend(clean_line[:clean_line.find('.')].split()) sentences.append(sentence) clean_line = clean_line[clean_line.find('.')+1:] sentence = clean_line[:clean_line.find('.')].split() else: sentence.extend(clean_line.split()) return sentences def train_and_most_similar(filenames, word): for filename in filenames: sentences = book_to_sentences(filename) model = gensim.models.Word2Vec(sentences) if word in model: print('{0} most similar words to {1} are {2}'.format(filename.replace('.txt', ''), word, str(model.most_similar(word)))) else: print('{0} model does not contain the word {1}'.format(filename.replace('.txt', ''), word)) if __name__ == '__main__': train_and_most_similar(['ulysses.txt', 'metamorphosis.txt', 'leaves_of_grass.txt', 'alices_adventures_in_wonderland.txt'], 'man')
apache-2.0
pgagne/robottelo
tests/foreman/longrun/test_inc_updates.py
3
11167
"""Tests for the Incremental Update feature :Requirement: Inc Updates :CaseAutomation: Automated :CaseLevel: Acceptance :CaseComponent: Hosts-Content :TestType: Functional :CaseImportance: High :Upstream: No """ from datetime import date, timedelta, datetime from fauxfactory import gen_alpha from nailgun import entities from nailgun import entity_mixins from robottelo import manifests from robottelo.api.utils import ( call_entity_method_with_timeout, enable_rhrepo_and_fetchid, promote, upload_manifest, wait_for_tasks, ) from robottelo.cleanup import vm_cleanup from robottelo.cli.contentview import ContentView as ContentViewCLI from robottelo.constants import ( DEFAULT_ARCHITECTURE, DEFAULT_RELEASE_VERSION, DEFAULT_SUBSCRIPTION_NAME, DISTRO_RHEL6, PRDS, REAL_0_RH_PACKAGE, REPOS, REPOSET, ) from robottelo.decorators import ( run_in_one_thread, skip_if_not_set, tier4, upgrade ) from robottelo.test import TestCase from robottelo.vm import VirtualMachine @run_in_one_thread class IncrementalUpdateTestCase(TestCase): """Tests for the Incremental Update feature""" @classmethod @skip_if_not_set('clients') def setUpClass(cls): """Creates the pre-requisites for the Incremental updates that used in all test""" super(IncrementalUpdateTestCase, cls).setUpClass() # Create a new Organization cls.org = entities.Organization(name=gen_alpha()).create() # Create two lifecycle environments - DEV, QE cls.dev_lce = entities.LifecycleEnvironment( name='DEV', organization=cls.org ).create() cls.qe_lce = entities.LifecycleEnvironment( name='QE', prior=cls.dev_lce, organization=cls.org ).create() # Upload manifest with manifests.clone() as manifest: upload_manifest(cls.org.id, manifest.content) # Enable repositories - RHE Virtualization Agents and rhel6 sat6tools rhva_6_repo_id = enable_rhrepo_and_fetchid( basearch=DEFAULT_ARCHITECTURE, org_id=cls.org.id, product=PRDS['rhel'], repo=REPOS['rhva6']['name'], reposet=REPOSET['rhva6'], releasever=DEFAULT_RELEASE_VERSION, ) rhel6_sat6tools_repo_id = enable_rhrepo_and_fetchid( basearch=DEFAULT_ARCHITECTURE, org_id=cls.org.id, product=PRDS['rhel'], repo=REPOS['rhst6']['name'], reposet=REPOSET['rhst6'], releasever=None, ) # Read the repositories cls.rhva_6_repo = entities.Repository(id=rhva_6_repo_id).read() cls.rhel6_sat6tools_repo = entities.Repository( id=rhel6_sat6tools_repo_id ).read() # Sync the enabled repositories try: cls.old_task_timeout = entity_mixins.TASK_TIMEOUT # Update timeout to 15 minutes to finish sync entity_mixins.TASK_TIMEOUT = 900 for repo in [cls.rhva_6_repo, cls.rhel6_sat6tools_repo]: assert repo.sync()['result'] == u'success' finally: entity_mixins.TASK_TIMEOUT = cls.old_task_timeout def setUp(self): """Creates the pre-requisites for the Incremental updates that used per each test""" super(IncrementalUpdateTestCase, self).setUp() # Create content view that will be used filtered erratas self.rhel_6_partial_cv = entities.ContentView( organization=self.org, name=gen_alpha(), repository=[self.rhva_6_repo, self.rhel6_sat6tools_repo] ).create() # Create a content view filter to filter out errata rhel_6_partial_cvf = entities.ErratumContentViewFilter( content_view=self.rhel_6_partial_cv, type='erratum', name='rhel_6_partial_cv_filter', repository=[self.rhva_6_repo] ).create() # Create a content view filter rule - filtering out errata in the last # 365 days start_date = (date.today() - timedelta(days=365)).strftime('%Y-%m-%d') entities.ContentViewFilterRule( content_view_filter=rhel_6_partial_cvf, types=['security', 'enhancement', 'bugfix'], start_date=start_date, end_date=date.today().strftime('%Y-%m-%d') ).create() # Publish content view and re-read it self.rhel_6_partial_cv.publish() self.rhel_6_partial_cv = self.rhel_6_partial_cv.read() # Promote content view to 'DEV' and 'QE' assert len(self.rhel_6_partial_cv.version) == 1 for env in (self.dev_lce, self.qe_lce): promote(self.rhel_6_partial_cv.version[0], env.id) # Create host collection self.rhel_6_partial_hc = entities.HostCollection( organization=self.org, name=gen_alpha(), max_hosts=5).create() # Create activation key for content view kwargs = {'organization': self.org, 'environment': self.qe_lce.id} rhel_6_partial_ak = entities.ActivationKey( name=gen_alpha(), content_view=self.rhel_6_partial_cv, host_collection=[self.rhel_6_partial_hc], **kwargs ).create() # Assign subscription to activation key. Fetch available subscriptions subs = entities.Subscription(organization=self.org).search() assert len(subs) > 0 # Add subscription to activation key sub_found = False for sub in subs: if sub.read_json()['product_name'] == DEFAULT_SUBSCRIPTION_NAME: rhel_6_partial_ak.add_subscriptions(data={ u'subscription_id': sub.id }) sub_found = True assert sub_found # Enable product content in activation key rhel_6_partial_ak.content_override(data={'content_override': { u'content_label': REPOS['rhst6']['id'], u'value': u'1' }}) # Create client machine and register it to satellite with # rhel_6_partial_ak self.vm = VirtualMachine(distro=DISTRO_RHEL6, tag='incupdate') self.addCleanup(vm_cleanup, self.vm) self.setup_vm(self.vm, rhel_6_partial_ak.name, self.org.label) self.vm.enable_repo(REPOS['rhva6']['id']) timestamp = datetime.utcnow() self.vm.run('yum install -y {0}'.format(REAL_0_RH_PACKAGE)) # Find the content host and ensure that tasks started by package # installation has finished host = entities.Host().search( query={'search': 'name={}'.format(self.vm.hostname)}) wait_for_tasks( search_query='label = Actions::Katello::Host::UploadPackageProfile' ' and resource_id = {}' ' and started_at >= "{}"'.format( host[0].id, timestamp) ) # Force host to generate or refresh errata applicability call_entity_method_with_timeout(host[0].errata_applicability, timeout=600) @staticmethod def setup_vm(client, act_key, org_name): """Creates the vm and registers it to the satellite""" client.create() client.install_katello_ca() # Register content host, install katello-agent client.register_contenthost( org_name, act_key, releasever=DEFAULT_RELEASE_VERSION ) assert client.subscribed client.install_katello_agent() client.run('katello-package-upload') @staticmethod def get_applicable_errata(repo): """Retrieves applicable errata for the given repo""" return entities.Errata(repository=repo).search( query={'errata_restrict_applicable': True} ) @tier4 @upgrade def test_positive_noapply_api(self): """Check if api incremental update can be done without actually applying it :id: 481c5ff2-801f-4eff-b1e0-95ea5bb37f95 :Setup: The prerequisites are already covered in the setUpClass() but for easy debug, get the content view id, Repository id and Lifecycle environment id using hammer and plug these statements on the top of the test. For example:: self.rhel_6_partial_cv = ContentView(id=38).read() self.rhva_6_repo = Repository(id=164).read() self.qe_lce = LifecycleEnvironment(id=46).read() :expectedresults: Incremental update completed with no errors and Content view has a newer version :CaseLevel: System """ # Get the content view versions and use the recent one. API always # returns the versions in ascending order so it is safe to assume the # last one in the list is the recent cv_versions = self.rhel_6_partial_cv.version # Get the applicable errata errata_list = self.get_applicable_errata(self.rhva_6_repo) self.assertGreater(len(errata_list), 0) # Apply incremental update using the first applicable errata entities.ContentViewVersion().incremental_update(data={ 'content_view_version_environments': [{ 'content_view_version_id': cv_versions[-1].id, 'environment_ids': [self.qe_lce.id] }], 'add_content': { 'errata_ids': [errata_list[0].id] } }) # Re-read the content view to get the latest versions self.rhel_6_partial_cv = self.rhel_6_partial_cv.read() self.assertGreater( len(self.rhel_6_partial_cv.version), len(cv_versions) ) @tier4 @upgrade def test_positive_noapply_cli(self): """Check if cli incremental update can be done without actually applying it :id: f25b0919-74cb-4e2c-829e-482558990b3c :expectedresults: Incremental update completed with no errors and Content view has a newer version :CaseLevel: System """ # Get the content view versions and use the recent one. API always # returns the versions in ascending order so it is safe to assume the # last one in the list is the recent cv_versions = self.rhel_6_partial_cv.version # Get the applicable errata errata_list = self.get_applicable_errata(self.rhva_6_repo) self.assertGreater(len(errata_list), 0) # Apply incremental update using the first applicable errata ContentViewCLI.version_incremental_update({ u'content-view-version-id': cv_versions[-1].id, u'lifecycle-environment-ids': self.qe_lce.id, u'errata-ids': errata_list[0].id, }) # Re-read the content view to get the latest versions self.rhel_6_partial_cv = self.rhel_6_partial_cv.read() self.assertGreater( len(self.rhel_6_partial_cv.version), len(cv_versions) )
gpl-3.0
ArtsiomCh/tensorflow
tensorflow/contrib/image/python/kernel_tests/distort_image_ops_test.py
16
12282
# Copyright 2017 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. # ============================================================================== """Tests for python distort_image_ops.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import time import numpy as np from six.moves import xrange # pylint: disable=redefined-builtin from tensorflow.contrib.image.python.ops import distort_image_ops from tensorflow.core.protobuf import config_pb2 from tensorflow.python.client import session from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import test_util from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import random_ops from tensorflow.python.ops import variables from tensorflow.python.platform import googletest from tensorflow.python.platform import test # TODO(huangyp): also measure the differences between AdjustHsvInYiq and # AdjustHsv in core. class AdjustHueInYiqTest(test_util.TensorFlowTestCase): def _adjust_hue_in_yiq_np(self, x_np, delta_h): """Rotate hue in YIQ space. Mathematically we first convert rgb color to yiq space, rotate the hue degrees, and then convert back to rgb. Args: x_np: input x with last dimension = 3. delta_h: degree of hue rotation, in radians. Returns: Adjusted y with the same shape as x_np. """ self.assertEqual(x_np.shape[-1], 3) x_v = x_np.reshape([-1, 3]) y_v = np.ndarray(x_v.shape, dtype=x_v.dtype) u = np.cos(delta_h) w = np.sin(delta_h) # Projection matrix from RGB to YIQ. Numbers from wikipedia # https://en.wikipedia.org/wiki/YIQ tyiq = np.array([[0.299, 0.587, 0.114], [0.596, -0.274, -0.322], [0.211, -0.523, 0.312]]) y_v = np.dot(x_v, tyiq.T) # Hue rotation matrix in YIQ space. hue_rotation = np.array([[1.0, 0.0, 0.0], [0.0, u, -w], [0.0, w, u]]) y_v = np.dot(y_v, hue_rotation.T) # Projecting back to RGB space. y_v = np.dot(y_v, np.linalg.inv(tyiq).T) return y_v.reshape(x_np.shape) def _adjust_hue_in_yiq_tf(self, x_np, delta_h): with self.test_session(use_gpu=True): x = constant_op.constant(x_np) y = distort_image_ops.adjust_hsv_in_yiq(x, delta_h, 1, 1) y_tf = y.eval() return y_tf def test_adjust_random_hue_in_yiq(self): x_shapes = [ [2, 2, 3], [4, 2, 3], [2, 4, 3], [2, 5, 3], [1000, 1, 3], ] test_styles = [ 'all_random', 'rg_same', 'rb_same', 'gb_same', 'rgb_same', ] for x_shape in x_shapes: for test_style in test_styles: x_np = np.random.rand(*x_shape) * 255. delta_h = (np.random.rand() * 2.0 - 1.0) * np.pi if test_style == 'all_random': pass elif test_style == 'rg_same': x_np[..., 1] = x_np[..., 0] elif test_style == 'rb_same': x_np[..., 2] = x_np[..., 0] elif test_style == 'gb_same': x_np[..., 2] = x_np[..., 1] elif test_style == 'rgb_same': x_np[..., 1] = x_np[..., 0] x_np[..., 2] = x_np[..., 0] else: raise AssertionError('Invalid test style: %s' % (test_style)) y_np = self._adjust_hue_in_yiq_np(x_np, delta_h) y_tf = self._adjust_hue_in_yiq_tf(x_np, delta_h) self.assertAllClose(y_tf, y_np, rtol=2e-4, atol=1e-4) def test_invalid_shapes(self): x_np = np.random.rand(2, 3) * 255. delta_h = np.random.rand() * 2.0 - 1.0 with self.assertRaisesRegexp(ValueError, 'Shape must be at least rank 3'): self._adjust_hue_in_yiq_tf(x_np, delta_h) x_np = np.random.rand(4, 2, 4) * 255. delta_h = np.random.rand() * 2.0 - 1.0 with self.assertRaisesOpError('input must have 3 channels but instead has ' '4 channels'): self._adjust_hue_in_yiq_tf(x_np, delta_h) class AdjustValueInYiqTest(test_util.TensorFlowTestCase): def _adjust_value_in_yiq_np(self, x_np, scale): return x_np * scale def _adjust_value_in_yiq_tf(self, x_np, scale): with self.test_session(use_gpu=True): x = constant_op.constant(x_np) y = distort_image_ops.adjust_hsv_in_yiq(x, 0, 1, scale) y_tf = y.eval() return y_tf def test_adjust_random_value_in_yiq(self): x_shapes = [ [2, 2, 3], [4, 2, 3], [2, 4, 3], [2, 5, 3], [1000, 1, 3], ] test_styles = [ 'all_random', 'rg_same', 'rb_same', 'gb_same', 'rgb_same', ] for x_shape in x_shapes: for test_style in test_styles: x_np = np.random.rand(*x_shape) * 255. scale = np.random.rand() * 2.0 - 1.0 if test_style == 'all_random': pass elif test_style == 'rg_same': x_np[..., 1] = x_np[..., 0] elif test_style == 'rb_same': x_np[..., 2] = x_np[..., 0] elif test_style == 'gb_same': x_np[..., 2] = x_np[..., 1] elif test_style == 'rgb_same': x_np[..., 1] = x_np[..., 0] x_np[..., 2] = x_np[..., 0] else: raise AssertionError('Invalid test style: %s' % (test_style)) y_np = self._adjust_value_in_yiq_np(x_np, scale) y_tf = self._adjust_value_in_yiq_tf(x_np, scale) self.assertAllClose(y_tf, y_np, rtol=2e-5, atol=1e-5) def test_invalid_shapes(self): x_np = np.random.rand(2, 3) * 255. scale = np.random.rand() * 2.0 - 1.0 with self.assertRaisesRegexp(ValueError, 'Shape must be at least rank 3'): self._adjust_value_in_yiq_tf(x_np, scale) x_np = np.random.rand(4, 2, 4) * 255. scale = np.random.rand() * 2.0 - 1.0 with self.assertRaisesOpError('input must have 3 channels but instead has ' '4 channels'): self._adjust_value_in_yiq_tf(x_np, scale) class AdjustSaturationInYiqTest(test_util.TensorFlowTestCase): def _adjust_saturation_in_yiq_tf(self, x_np, scale): with self.test_session(use_gpu=True): x = constant_op.constant(x_np) y = distort_image_ops.adjust_hsv_in_yiq(x, 0, scale, 1) y_tf = y.eval() return y_tf def _adjust_saturation_in_yiq_np(self, x_np, scale): """Adjust saturation using linear interpolation.""" rgb_weights = np.array([0.299, 0.587, 0.114]) gray = np.sum(x_np * rgb_weights, axis=-1, keepdims=True) y_v = x_np * scale + gray * (1 - scale) return y_v def test_adjust_random_saturation_in_yiq(self): x_shapes = [ [2, 2, 3], [4, 2, 3], [2, 4, 3], [2, 5, 3], [1000, 1, 3], ] test_styles = [ 'all_random', 'rg_same', 'rb_same', 'gb_same', 'rgb_same', ] with self.test_session(): for x_shape in x_shapes: for test_style in test_styles: x_np = np.random.rand(*x_shape) * 255. scale = np.random.rand() * 2.0 - 1.0 if test_style == 'all_random': pass elif test_style == 'rg_same': x_np[..., 1] = x_np[..., 0] elif test_style == 'rb_same': x_np[..., 2] = x_np[..., 0] elif test_style == 'gb_same': x_np[..., 2] = x_np[..., 1] elif test_style == 'rgb_same': x_np[..., 1] = x_np[..., 0] x_np[..., 2] = x_np[..., 0] else: raise AssertionError('Invalid test style: %s' % (test_style)) y_baseline = self._adjust_saturation_in_yiq_np(x_np, scale) y_tf = self._adjust_saturation_in_yiq_tf(x_np, scale) self.assertAllClose(y_tf, y_baseline, rtol=2e-5, atol=1e-5) def test_invalid_shapes(self): x_np = np.random.rand(2, 3) * 255. scale = np.random.rand() * 2.0 - 1.0 with self.assertRaisesRegexp(ValueError, 'Shape must be at least rank 3'): self._adjust_saturation_in_yiq_tf(x_np, scale) x_np = np.random.rand(4, 2, 4) * 255. scale = np.random.rand() * 2.0 - 1.0 with self.assertRaisesOpError('input must have 3 channels but instead has ' '4 channels'): self._adjust_saturation_in_yiq_tf(x_np, scale) class AdjustHueInYiqBenchmark(test.Benchmark): def _benchmark_adjust_hue_in_yiq(self, device, cpu_count): image_shape = [299, 299, 3] warmup_rounds = 100 benchmark_rounds = 1000 config = config_pb2.ConfigProto() if cpu_count is not None: config.inter_op_parallelism_threads = 1 config.intra_op_parallelism_threads = cpu_count with session.Session('', graph=ops.Graph(), config=config) as sess: with ops.device(device): inputs = variables.Variable( random_ops.random_uniform(image_shape, dtype=dtypes.float32) * 255, trainable=False, dtype=dtypes.float32) delta = constant_op.constant(0.1, dtype=dtypes.float32) outputs = distort_image_ops.adjust_hsv_in_yiq(inputs, delta, 1, 1) run_op = control_flow_ops.group(outputs) sess.run(variables.global_variables_initializer()) for i in xrange(warmup_rounds + benchmark_rounds): if i == warmup_rounds: start = time.time() sess.run(run_op) end = time.time() step_time = (end - start) / benchmark_rounds tag = device + '_%s' % (cpu_count if cpu_count is not None else 'all') print('benchmarkadjust_hue_in_yiq_299_299_3_%s step_time: %.2f us' % (tag, step_time * 1e6)) self.report_benchmark( name='benchmarkadjust_hue_in_yiq_299_299_3_%s' % (tag), iters=benchmark_rounds, wall_time=step_time) def benchmark_adjust_hue_in_yiqCpu1(self): self._benchmark_adjust_hue_in_yiq('/cpu:0', 1) def benchmark_adjust_hue_in_yiqCpuAll(self): self._benchmark_adjust_hue_in_yiq('/cpu:0', None) class AdjustSaturationInYiqBenchmark(test.Benchmark): def _benchmark_adjust_saturation_in_yiq(self, device, cpu_count): image_shape = [299, 299, 3] warmup_rounds = 100 benchmark_rounds = 1000 config = config_pb2.ConfigProto() if cpu_count is not None: config.inter_op_parallelism_threads = 1 config.intra_op_parallelism_threads = cpu_count with session.Session('', graph=ops.Graph(), config=config) as sess: with ops.device(device): inputs = variables.Variable( random_ops.random_uniform(image_shape, dtype=dtypes.float32) * 255, trainable=False, dtype=dtypes.float32) scale = constant_op.constant(0.1, dtype=dtypes.float32) outputs = distort_image_ops.adjust_hsv_in_yiq(inputs, 0, scale, 1) run_op = control_flow_ops.group(outputs) sess.run(variables.global_variables_initializer()) for _ in xrange(warmup_rounds): sess.run(run_op) start = time.time() for _ in xrange(benchmark_rounds): sess.run(run_op) end = time.time() step_time = (end - start) / benchmark_rounds tag = '%s' % (cpu_count) if cpu_count is not None else '_all' print('benchmarkAdjustSaturationInYiq_299_299_3_cpu%s step_time: %.2f us' % (tag, step_time * 1e6)) self.report_benchmark( name='benchmarkAdjustSaturationInYiq_299_299_3_cpu%s' % (tag), iters=benchmark_rounds, wall_time=step_time) def benchmark_adjust_saturation_in_yiq_cpu1(self): self._benchmark_adjust_saturation_in_yiq('/cpu:0', 1) def benchmark_adjust_saturation_in_yiq_cpu_all(self): self._benchmark_adjust_saturation_in_yiq('/cpu:0', None) if __name__ == '__main__': googletest.main()
apache-2.0
sjperkins/tensorflow
tensorflow/python/grappler/tf_optimizer_test.py
39
2031
# Copyright 2017 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. # ============================================================================== """Tests for the swig wrapper tf_optimizer.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.core.protobuf import rewriter_config_pb2 from tensorflow.python.framework import constant_op from tensorflow.python.framework import meta_graph from tensorflow.python.framework import ops from tensorflow.python.grappler import tf_optimizer from tensorflow.python.ops import math_ops from tensorflow.python.platform import test class PyWrapOptimizeGraphTest(test.TestCase): def testBasic(self): """Make sure arguments can be passed correctly.""" a = constant_op.constant(10, name='a') b = constant_op.constant(20, name='b') c = math_ops.add_n([a, b], name='c') d = math_ops.add_n([b, c], name='d') train_op = ops.get_collection_ref(ops.GraphKeys.TRAIN_OP) train_op.append(d) mg = meta_graph.create_meta_graph_def(graph=ops.get_default_graph()) rewriter_config = rewriter_config_pb2.RewriterConfig() rewriter_config.optimizers.append('constfold') graph = tf_optimizer.OptimizeGraph(rewriter_config, mg) self.assertEqual(len(graph.node), 5) self.assertItemsEqual([node.name for node in graph.node], ['a', 'b', 'c', 'd', 'ConstantFolding/c']) if __name__ == '__main__': test.main()
apache-2.0
tito/pymt
tools/depend/depend.py
2
2070
from subprocess import * import os system_lib = ['re', 'optparse', 'os', 'sys', 'shutil', 'warnings', 'Queue', 'osc', 'numpy', 'math', 'xml.dom', 'logging', 'random', 'ctypeasc', 'ConfigParser', 'getopt', 'ctypes', 'gzip', 'urllib', 'gtk', 'operator', 'time'] system_lib_find = ['cssutils', 'pyglet', 'encutils', 'squirtle', 'factory'] def f9(seq): # Not order preserving return {}.fromkeys(seq).keys() cmd = "find pymt -iname '*.py' -exec grep -H 'import' {} \;" output = Popen(cmd, shell=True, stdout=PIPE).communicate()[0] cmps = [] for line in output.split("\n"): if line == '': continue if line.find('`') > 0: continue if line.find('=') > 0: continue filename, line = map(lambda x: x.strip(), line.split(':', 1)) line = line.rsplit('#', 1)[0] filename = filename[:-3] if line.startswith('import'): line = line[7:].replace(' ', '').split(',') for k in line: cmps.append((filename, k)) elif line.startswith('from'): line = line[4:].rsplit('import', 1)[0].strip() cmps.append((filename, line)) # remove init cmps2 = [] for a, b in cmps: p = 0 for s in system_lib: if s in b: p = 1 if s in a: p = 1 for s in system_lib_find: if b.find(s) >= 0: p = 1 if a.find(s) >= 0: p = 1 if p: continue if os.path.basename(a) == '__init__': a = a[:-9] cmps2.append((a, b)) cmps = cmps2 # resolve path in b cmps2 = [] kcmp = f9(map(lambda x: x[0], cmps)) for a, b in cmps: nb = b.lstrip('.') nbp = len(b) - len(nb) bc = b = b.replace('.', '/') if nbp > 0: bc = ('../' * nbp) + b # test in current directory c = os.path.normpath(os.path.join(a, bc)) if os.path.exists(c + '.py'): b = c elif os.path.exists(c): b = c elif os.path.exists(os.path.normpath(os.path.join(a, '../', bc))): b = os.path.normpath(os.path.join(a, '../', bc)) elif os.path.exists(os.path.normpath(os.path.join(a, '../', bc)) + '.py'): b = os.path.normpath(os.path.join(a, '../', bc)) else: pass # append cmps2.append((a, b)) cmps = cmps2 print 'digraph {' for a, b in cmps: print '"%s" -> "%s"' % (b, a) print '}'
lgpl-3.0
Bismarrck/tensorflow
tensorflow/python/keras/layers/local_test.py
8
16388
# 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. # ============================================================================== """Tests for locally-connected layers.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.python import keras from tensorflow.python.framework import test_util as tf_test_util from tensorflow.python.keras import testing_utils from tensorflow.python.platform import test from tensorflow.python.training.rmsprop import RMSPropOptimizer class LocallyConnected1DLayersTest(test.TestCase): # TODO(fchollet): investigate why LocallyConnected1D # fails inside a graph function in an eager context (fails with error # "Incompatible shapes between op input and calculated input gradient"). @tf_test_util.run_deprecated_v1 def test_locallyconnected_1d(self): with self.cached_session(): num_samples = 2 num_steps = 8 input_dim = 5 filter_length = 3 filters = 4 for padding in ['valid', 'same']: for strides in [1]: if padding == 'same' and strides != 1: continue for data_format in ['channels_first', 'channels_last']: for implementation in [1, 2]: kwargs = { 'filters': filters, 'kernel_size': filter_length, 'padding': padding, 'strides': strides, 'data_format': data_format, 'implementation': implementation } if padding == 'same' and implementation == 1: self.assertRaises(ValueError, keras.layers.LocallyConnected1D, **kwargs) else: testing_utils.layer_test( keras.layers.LocallyConnected1D, kwargs=kwargs, input_shape=(num_samples, num_steps, input_dim)) def test_locallyconnected_1d_regularization(self): num_samples = 2 num_steps = 8 input_dim = 5 filter_length = 3 filters = 4 for data_format in ['channels_first', 'channels_last']: for padding in ['valid', 'same']: for implementation in [1, 2]: kwargs = { 'filters': filters, 'kernel_size': filter_length, 'kernel_regularizer': 'l2', 'bias_regularizer': 'l2', 'activity_regularizer': 'l2', 'data_format': data_format, 'implementation': implementation, 'padding': padding } if padding == 'same' and implementation == 1: self.assertRaises(ValueError, keras.layers.LocallyConnected1D, **kwargs) else: with self.cached_session(): layer = keras.layers.LocallyConnected1D(**kwargs) layer.build((num_samples, num_steps, input_dim)) self.assertEqual(len(layer.losses), 2) layer( keras.backend.variable(np.ones((num_samples, num_steps, input_dim)))) self.assertEqual(len(layer.losses), 3) k_constraint = keras.constraints.max_norm(0.01) b_constraint = keras.constraints.max_norm(0.01) kwargs = { 'filters': filters, 'kernel_size': filter_length, 'kernel_constraint': k_constraint, 'bias_constraint': b_constraint, } with self.cached_session(): layer = keras.layers.LocallyConnected1D(**kwargs) layer.build((num_samples, num_steps, input_dim)) self.assertEqual(layer.kernel.constraint, k_constraint) self.assertEqual(layer.bias.constraint, b_constraint) class LocallyConnected2DLayersTest(test.TestCase): # TODO(fchollet): investigate why LocallyConnected2D # fails inside a graph function in an eager context (fails with error # "Incompatible shapes between op input and calculated input gradient"). @tf_test_util.run_deprecated_v1 def test_locallyconnected_2d(self): with self.cached_session(): num_samples = 8 filters = 3 stack_size = 4 num_row = 6 num_col = 10 for padding in ['valid', 'same']: for strides in [(1, 1), (2, 2)]: for implementation in [1, 2]: if padding == 'same' and strides != (1, 1): continue kwargs = { 'filters': filters, 'kernel_size': 3, 'padding': padding, 'kernel_regularizer': 'l2', 'bias_regularizer': 'l2', 'strides': strides, 'data_format': 'channels_last', 'implementation': implementation } if padding == 'same' and implementation == 1: self.assertRaises(ValueError, keras.layers.LocallyConnected2D, **kwargs) else: testing_utils.layer_test( keras.layers.LocallyConnected2D, kwargs=kwargs, input_shape=(num_samples, num_row, num_col, stack_size)) @tf_test_util.run_deprecated_v1 def test_locallyconnected_2d_channels_first(self): with self.cached_session(): num_samples = 8 filters = 3 stack_size = 4 num_row = 6 num_col = 10 for implementation in [1, 2]: for padding in ['valid', 'same']: kwargs = { 'filters': filters, 'kernel_size': 3, 'data_format': 'channels_first', 'implementation': implementation, 'padding': padding } if padding == 'same' and implementation == 1: self.assertRaises(ValueError, keras.layers.LocallyConnected2D, **kwargs) else: testing_utils.layer_test( keras.layers.LocallyConnected2D, kwargs=kwargs, input_shape=(num_samples, num_row, num_col, stack_size)) def test_locallyconnected_2d_regularization(self): num_samples = 2 filters = 3 stack_size = 4 num_row = 6 num_col = 7 for implementation in [1, 2]: for padding in ['valid', 'same']: kwargs = { 'filters': filters, 'kernel_size': 3, 'kernel_regularizer': 'l2', 'bias_regularizer': 'l2', 'activity_regularizer': 'l2', 'implementation': implementation, 'padding': padding } if padding == 'same' and implementation == 1: self.assertRaises(ValueError, keras.layers.LocallyConnected2D, **kwargs) else: with self.cached_session(): layer = keras.layers.LocallyConnected2D(**kwargs) layer.build((num_samples, num_row, num_col, stack_size)) self.assertEqual(len(layer.losses), 2) layer( keras.backend.variable( np.ones((num_samples, num_row, num_col, stack_size)))) self.assertEqual(len(layer.losses), 3) k_constraint = keras.constraints.max_norm(0.01) b_constraint = keras.constraints.max_norm(0.01) kwargs = { 'filters': filters, 'kernel_size': 3, 'kernel_constraint': k_constraint, 'bias_constraint': b_constraint, } with self.cached_session(): layer = keras.layers.LocallyConnected2D(**kwargs) layer.build((num_samples, num_row, num_col, stack_size)) self.assertEqual(layer.kernel.constraint, k_constraint) self.assertEqual(layer.bias.constraint, b_constraint) class LocallyConnectedImplementationModeTest(test.TestCase): @tf_test_util.run_deprecated_v1 def test_locallyconnected_implementation(self): with self.cached_session(): num_samples = 4 num_classes = 3 num_epochs = 2 np.random.seed(1) targets = np.random.randint(0, num_classes, (num_samples,)) for width in [1, 6]: for height in [7]: for filters in [2]: for data_format in ['channels_first', 'channels_last']: inputs = get_inputs( data_format, filters, height, num_samples, width) for kernel_x in [(3,)]: for kernel_y in [()] if width == 1 else [(2,)]: for stride_x in [(1,)]: for stride_y in [()] if width == 1 else [(3,)]: for layers in [2]: kwargs = { 'layers': layers, 'filters': filters, 'kernel_size': kernel_x + kernel_y, 'strides': stride_x + stride_y, 'data_format': data_format, 'num_classes': num_classes } model_1 = get_model(implementation=1, **kwargs) model_2 = get_model(implementation=2, **kwargs) # Build models. model_1.train_on_batch(inputs, targets) model_2.train_on_batch(inputs, targets) # Copy weights. copy_model_weights(model_2, model_1) # Compare outputs at initialization. out_1 = model_1.call(inputs) out_2 = model_2.call(inputs) self.assertAllCloseAccordingToType(out_1, out_2, rtol=1e-5, atol=1e-5) # Train. model_1.fit(x=inputs, y=targets, epochs=num_epochs, batch_size=num_samples) model_2.fit(x=inputs, y=targets, epochs=num_epochs, batch_size=num_samples) # Compare outputs after a few training steps. out_1 = model_1.call(inputs) out_2 = model_2.call(inputs) self.assertAllCloseAccordingToType( out_1, out_2, atol=2e-4) @tf_test_util.run_in_graph_and_eager_modes def test_make_2d(self): input_shapes = [ (0,), (0, 0), (1,), (2,), (3,), (1, 0), (0, 3), (1, 1), (1, 2), (3, 1), (2, 2), (3, 3), (1, 0, 1), (5, 2, 3), (3, 5, 6, 7, 0), (3, 2, 2, 4, 4), (1, 2, 3, 4, 7, 2), ] np.random.seed(1) for input_shape in input_shapes: inputs = np.random.normal(0, 1, input_shape) inputs_tf = keras.backend.variable(inputs) split_dim = np.random.randint(0, inputs.ndim + 1) shape_2d = (int(np.prod(inputs.shape[:split_dim])), int(np.prod(inputs.shape[split_dim:]))) inputs_2d = np.reshape(inputs, shape_2d) inputs_2d_tf = keras.layers.local.make_2d(inputs_tf, split_dim) inputs_2d_tf = keras.backend.get_value(inputs_2d_tf) self.assertAllCloseAccordingToType(inputs_2d, inputs_2d_tf) def get_inputs(data_format, filters, height, num_samples, width): if data_format == 'channels_first': if width == 1: input_shape = (filters, height) else: input_shape = (filters, height, width) elif data_format == 'channels_last': if width == 1: input_shape = (height, filters) else: input_shape = (height, width, filters) else: raise NotImplementedError(data_format) inputs = np.random.normal(0, 1, (num_samples,) + input_shape).astype(np.float32) return inputs def xent(y_true, y_pred): y_true = keras.backend.cast( keras.backend.reshape(y_true, (-1,)), keras.backend.dtypes_module.int32) return keras.backend.nn.sparse_softmax_cross_entropy_with_logits( labels=y_true, logits=y_pred) def get_model(implementation, filters, kernel_size, strides, layers, num_classes, data_format): model = keras.Sequential() if len(kernel_size) == 1: lc_layer = keras.layers.LocallyConnected1D elif len(kernel_size) == 2: lc_layer = keras.layers.LocallyConnected2D else: raise NotImplementedError(kernel_size) for _ in range(layers): model.add(lc_layer( padding='valid', kernel_initializer=keras.initializers.random_normal(), bias_initializer=keras.initializers.random_normal(), filters=filters, strides=strides, kernel_size=kernel_size, activation=keras.activations.relu, data_format=data_format, implementation=implementation)) model.add(keras.layers.Flatten()) model.add(keras.layers.Dense(num_classes)) model.compile( optimizer=RMSPropOptimizer(0.01), metrics=[keras.metrics.categorical_accuracy], loss=xent ) return model def copy_lc_weights(lc_layer_2_from, lc_layer_1_to): lc_2_kernel, lc_2_bias = lc_layer_2_from.weights lc_2_kernel_masked = lc_2_kernel * lc_layer_2_from.kernel_mask data_format = lc_layer_2_from.data_format if data_format == 'channels_first': if isinstance(lc_layer_2_from, keras.layers.LocallyConnected1D): permutation = (3, 0, 1, 2) elif isinstance(lc_layer_2_from, keras.layers.LocallyConnected2D): permutation = (4, 5, 0, 1, 2, 3) else: raise NotImplementedError(lc_layer_2_from) elif data_format == 'channels_last': if isinstance(lc_layer_2_from, keras.layers.LocallyConnected1D): permutation = (2, 0, 1, 3) elif isinstance(lc_layer_2_from, keras.layers.LocallyConnected2D): permutation = (3, 4, 0, 1, 2, 5) else: raise NotImplementedError(lc_layer_2_from) else: raise NotImplementedError(data_format) lc_2_kernel_masked = keras.backend.permute_dimensions( lc_2_kernel_masked, permutation) lc_2_kernel_mask = keras.backend.math_ops.not_equal( lc_2_kernel_masked, 0) lc_2_kernel_flat = keras.backend.array_ops.boolean_mask( lc_2_kernel_masked, lc_2_kernel_mask) lc_2_kernel_reshaped = keras.backend.reshape(lc_2_kernel_flat, lc_layer_1_to.kernel.shape) lc_2_kernel_reshaped = keras.backend.get_value(lc_2_kernel_reshaped) lc_2_bias = keras.backend.get_value(lc_2_bias) lc_layer_1_to.set_weights([lc_2_kernel_reshaped, lc_2_bias]) def copy_model_weights(model_2_from, model_1_to): for l in range(len(model_2_from.layers)): layer_2_from = model_2_from.layers[l] layer_1_to = model_1_to.layers[l] if isinstance(layer_2_from, (keras.layers.LocallyConnected2D, keras.layers.LocallyConnected1D)): copy_lc_weights(layer_2_from, layer_1_to) elif isinstance(layer_2_from, keras.layers.Dense): weights_2, bias_2 = layer_2_from.weights weights_2 = keras.backend.get_value(weights_2) bias_2 = keras.backend.get_value(bias_2) layer_1_to.set_weights([weights_2, bias_2]) else: continue if __name__ == '__main__': test.main()
apache-2.0
klynch/emacs.d-old
python-libs/rope/base/ast.py
32
1981
import _ast from _ast import * from rope.base import fscommands def parse(source, filename='<string>'): # NOTE: the raw string should be given to `compile` function if isinstance(source, unicode): source = fscommands.unicode_to_file_data(source) if '\r' in source: source = source.replace('\r\n', '\n').replace('\r', '\n') if not source.endswith('\n'): source += '\n' try: return compile(source, filename, 'exec', _ast.PyCF_ONLY_AST) except (TypeError, ValueError), e: error = SyntaxError() error.lineno = 1 error.filename = filename error.msg = str(e) raise error def walk(node, walker): """Walk the syntax tree""" method_name = '_' + node.__class__.__name__ method = getattr(walker, method_name, None) if method is not None: return method(node) for child in get_child_nodes(node): walk(child, walker) def get_child_nodes(node): if isinstance(node, _ast.Module): return node.body result = [] if node._fields is not None: for name in node._fields: child = getattr(node, name) if isinstance(child, list): for entry in child: if isinstance(entry, _ast.AST): result.append(entry) if isinstance(child, _ast.AST): result.append(child) return result def call_for_nodes(node, callback, recursive=False): """If callback returns `True` the child nodes are skipped""" result = callback(node) if recursive and not result: for child in get_child_nodes(node): call_for_nodes(child, callback, recursive) def get_children(node): result = [] if node._fields is not None: for name in node._fields: if name in ['lineno', 'col_offset']: continue child = getattr(node, name) result.append(child) return result
gpl-3.0
chaffra/sympy
sympy/series/tests/test_fourier.py
21
3982
from sympy import (symbols, pi, Piecewise, sin, cos, sinc, Rational, oo, fourier_series, Add) from sympy.series.fourier import FourierSeries from sympy.utilities.pytest import raises x, y, z = symbols('x y z') fo = fourier_series(x, (x, -pi, pi)) fe = fourier_series(x**2, (-pi, pi)) fp = fourier_series(Piecewise((0, x < 0), (pi, True)), (x, -pi, pi)) def test_FourierSeries(): assert fourier_series(1, (-pi, pi)) == 1 assert (Piecewise((0, x < 0), (pi, True)). fourier_series((x, -pi, pi)).truncate()) == fp.truncate() assert isinstance(fo, FourierSeries) assert fo.function == x assert fo.x == x assert fo.period == (-pi, pi) assert fo.term(3) == 2*sin(3*x) / 3 assert fe.term(3) == -4*cos(3*x) / 9 assert fp.term(3) == 2*sin(3*x) / 3 assert fo.as_leading_term(x) == 2*sin(x) assert fe.as_leading_term(x) == pi**2 / 3 assert fp.as_leading_term(x) == pi / 2 assert fo.truncate() == 2*sin(x) - sin(2*x) + (2*sin(3*x) / 3) assert fe.truncate() == -4*cos(x) + cos(2*x) + pi**2 / 3 assert fp.truncate() == 2*sin(x) + (2*sin(3*x) / 3) + pi / 2 fot = fo.truncate(n=None) s = [0, 2*sin(x), -sin(2*x)] for i, t in enumerate(fot): if i == 3: break assert s[i] == t def _check_iter(f, i): for ind, t in enumerate(f): assert t == f[ind] if ind == i: break _check_iter(fo, 3) _check_iter(fe, 3) _check_iter(fp, 3) assert fo.subs(x, x**2) == fo raises(ValueError, lambda: fourier_series(x, (0, 1, 2))) raises(ValueError, lambda: fourier_series(x, (x, 0, oo))) raises(ValueError, lambda: fourier_series(x*y, (0, oo))) def test_FourierSeries_2(): p = Piecewise((0, x < 0), (x, True)) f = fourier_series(p, (x, -2, 2)) assert f.term(3) == (2*sin(3*pi*x / 2) / (3*pi) - 4*cos(3*pi*x / 2) / (9*pi**2)) assert f.truncate() == (2*sin(pi*x / 2) / pi - sin(pi*x) / pi - 4*cos(pi*x / 2) / pi**2 + Rational(1, 2)) def test_fourier_series_square_wave(): """Test if fourier_series approximates discontinuous function correctly.""" square_wave = Piecewise((1, x < pi), (-1, True)) s = fourier_series(square_wave, (x, 0, 2*pi)) assert s.truncate(3) == 4 / pi * sin(x) + 4 / (3 * pi) * sin(3 * x) + \ 4 / (5 * pi) * sin(5 * x) assert s.sigma_approximation(4) == 4 / pi * sin(x) * sinc(pi / 4) + \ 4 / (3 * pi) * sin(3 * x) * sinc(3 * pi / 4) def test_FourierSeries__operations(): fes = fe.scale(-1).shift(pi**2) assert fes.truncate() == 4*cos(x) - cos(2*x) + 2*pi**2 / 3 assert fp.shift(-pi/2).truncate() == (2*sin(x) + (2*sin(3*x) / 3) + (2*sin(5*x) / 5)) fos = fo.scale(3) assert fos.truncate() == 6*sin(x) - 3*sin(2*x) + 2*sin(3*x) fx = fe.scalex(2).shiftx(1) assert fx.truncate() == -4*cos(2*x + 2) + cos(4*x + 4) + pi**2 / 3 fl = fe.scalex(3).shift(-pi).scalex(2).shiftx(1).scale(4) assert fl.truncate() == (-16*cos(6*x + 6) + 4*cos(12*x + 12) - 4*pi + 4*pi**2 / 3) raises(ValueError, lambda: fo.shift(x)) raises(ValueError, lambda: fo.shiftx(sin(x))) raises(ValueError, lambda: fo.scale(x*y)) raises(ValueError, lambda: fo.scalex(x**2)) def test_FourierSeries__neg(): assert (-fo).truncate() == -2*sin(x) + sin(2*x) - (2*sin(3*x) / 3) assert (-fe).truncate() == +4*cos(x) - cos(2*x) - pi**2 / 3 def test_FourierSeries__add__sub(): assert fo + fo == fo.scale(2) assert fo - fo == 0 assert -fe - fe == fe.scale(-2) assert (fo + fe).truncate() == 2*sin(x) - sin(2*x) - 4*cos(x) + cos(2*x) \ + pi**2 / 3 assert (fo - fe).truncate() == 2*sin(x) - sin(2*x) + 4*cos(x) - cos(2*x) \ - pi**2 / 3 assert isinstance(fo + 1, Add) raises(ValueError, lambda: fo + fourier_series(x, (x, 0, 2)))
bsd-3-clause
google-research/google-research
non_semantic_speech_benchmark/eval_embedding/finetune/train_keras.py
1
6282
# coding=utf-8 # Copyright 2021 The Google Research Authors. # # 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 """Trains on embeddings using Keras.""" from absl import app from absl import flags import tensorflow.compat.v2 as tf from non_semantic_speech_benchmark.eval_embedding.finetune import get_data from non_semantic_speech_benchmark.eval_embedding.finetune import models FLAGS = flags.FLAGS flags.DEFINE_string('file_pattern', None, 'Dataset location.') flags.DEFINE_string('samples_key', None, 'Samples name.') flags.DEFINE_integer('ml', 16000, 'Minimum length.') flags.DEFINE_alias('min_length', 'ml') flags.DEFINE_string('label_key', None, 'Name of label to use.') flags.DEFINE_list('label_list', None, 'List of possible label values.') flags.DEFINE_integer('tbs', 1, 'Hyperparameter: batch size.') flags.DEFINE_alias('train_batch_size', 'tbs') flags.DEFINE_integer('shuffle_buffer_size', None, 'shuffle_buffer_size') flags.DEFINE_integer('nc', None, 'num_clusters') flags.DEFINE_alias('num_clusters', 'nc') flags.DEFINE_float('alpha_init', None, 'Initial autopool alpha.') flags.DEFINE_alias('ai', 'alpha_init') flags.DEFINE_boolean('ubn', None, 'Whether to use batch normalization.') flags.DEFINE_alias('use_batch_normalization', 'ubn') flags.DEFINE_float('lr', 0.001, 'Hyperparameter: learning rate.') flags.DEFINE_string('logdir', None, 'Path to directory where to store summaries.') flags.DEFINE_integer('training_steps', 1000, 'The number of steps to run training for.') flags.DEFINE_integer('measurement_store_interval', 10, 'The number of steps between storing objective value in ' 'measurements.') def train_and_report(debug=False): """Trains the classifier.""" tf.logging.info('samples_key: %s', FLAGS.samples_key) tf.logging.info('Logdir: %s', FLAGS.logdir) tf.logging.info('Batch size: %s', FLAGS.train_batch_size) tf.logging.info('label_list: %s', FLAGS.label_list) reader = tf.data.TFRecordDataset ds = get_data.get_data( file_pattern=FLAGS.file_pattern, reader=reader, samples_key=FLAGS.samples_key, min_length=FLAGS.min_length, label_key=FLAGS.label_key, label_list=FLAGS.label_list, batch_size=FLAGS.train_batch_size, loop_forever=True, shuffle=True, shuffle_buffer_size=FLAGS.shuffle_buffer_size) # Create model, loss, and other objects. y_onehot_spec = ds.element_spec[1] assert len(y_onehot_spec.shape) == 2, y_onehot_spec.shape num_classes = y_onehot_spec.shape[1] model = models.get_keras_model( num_classes, input_length=FLAGS.min_length, use_batchnorm=FLAGS.use_batch_normalization, num_clusters=FLAGS.num_clusters, alpha_init=FLAGS.alpha_init) # Define loss and optimizer hyparameters. loss_obj = tf.keras.losses.CategoricalCrossentropy(from_logits=True) opt = tf.keras.optimizers.Adam( learning_rate=FLAGS.lr, beta_1=0.9, beta_2=0.999, epsilon=1e-8) # Add additional metrics to track. train_loss = tf.keras.metrics.Mean(name='train_loss') train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy( name='train_accuracy') summary_writer = tf.summary.create_file_writer(FLAGS.logdir) train_step = get_train_step( model, loss_obj, opt, train_loss, train_accuracy, summary_writer) global_step = opt.iterations checkpoint = tf.train.Checkpoint(model=model, global_step=global_step) manager = tf.train.CheckpointManager( checkpoint, FLAGS.logdir, max_to_keep=None) tf.logging.info('Checkpoint prefix: %s', FLAGS.logdir) checkpoint.restore(manager.latest_checkpoint) if debug: return for wav_samples, y_onehot in ds: wav_samples.shape.assert_has_rank(2) wav_samples.shape.assert_is_compatible_with( [FLAGS.train_batch_size, FLAGS.min_length]) y_onehot.shape.assert_is_compatible_with( [FLAGS.train_batch_size, len(FLAGS.label_list)]) train_step(wav_samples, y_onehot, global_step) # Optional print output and save model. if global_step % 10 == 0: tf.logging.info('step: %i, train loss: %f, train accuracy: %f', global_step, train_loss.result(), train_accuracy.result()) if global_step % FLAGS.measurement_store_interval == 0: manager.save(checkpoint_number=global_step) manager.save(checkpoint_number=global_step) tf.logging.info('Finished training.') def get_train_step(model, loss_obj, opt, train_loss, train_accuracy, summary_writer): """Returns a function for train step.""" @tf.function def train_step(wav_samples, y_onehot, step): with tf.GradientTape() as tape: logits = model(wav_samples, training=True) assert model.trainable_variables logits.shape.assert_is_compatible_with(y_onehot.shape) loss_value = loss_obj(y_true=y_onehot, y_pred=logits) # Grads and optimizer. grads = tape.gradient(loss_value, model.trainable_variables) opt.apply_gradients(zip(grads, model.trainable_variables)) # Record loss. train_loss.update_state(loss_value) train_accuracy.update_state(tf.math.argmax(y_onehot, axis=1), logits) # Summaries. with summary_writer.as_default(): tf.summary.scalar('xent_loss', loss_value, step=step) tf.summary.scalar('xent_loss_smoothed', train_loss.result(), step=step) tf.summary.scalar('accuracy', train_accuracy.result(), step=step) return train_step def main(unused_argv): assert FLAGS.file_pattern assert FLAGS.shuffle_buffer_size assert FLAGS.samples_key assert FLAGS.label_key assert FLAGS.label_list assert FLAGS.logdir tf.enable_v2_behavior() assert tf.executing_eagerly() train_and_report() if __name__ == '__main__': app.run(main)
apache-2.0
mohankr/echoes_tools_repo
git_refs.py
20
3729
# # Copyright (C) 2009 The Android Open Source Project # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import sys from trace import Trace HEAD = 'HEAD' R_HEADS = 'refs/heads/' R_TAGS = 'refs/tags/' R_PUB = 'refs/published/' class GitRefs(object): def __init__(self, gitdir): self._gitdir = gitdir self._phyref = None self._symref = None self._mtime = {} @property def all(self): self._EnsureLoaded() return self._phyref def get(self, name): try: return self.all[name] except KeyError: return '' def deleted(self, name): if self._phyref is not None: if name in self._phyref: del self._phyref[name] if name in self._symref: del self._symref[name] if name in self._mtime: del self._mtime[name] def symref(self, name): try: self._EnsureLoaded() return self._symref[name] except KeyError: return '' def _EnsureLoaded(self): if self._phyref is None or self._NeedUpdate(): self._LoadAll() def _NeedUpdate(self): Trace(': scan refs %s', self._gitdir) for name, mtime in self._mtime.iteritems(): try: if mtime != os.path.getmtime(os.path.join(self._gitdir, name)): return True except OSError: return True return False def _LoadAll(self): Trace(': load refs %s', self._gitdir) self._phyref = {} self._symref = {} self._mtime = {} self._ReadPackedRefs() self._ReadLoose('refs/') self._ReadLoose1(os.path.join(self._gitdir, HEAD), HEAD) scan = self._symref attempts = 0 while scan and attempts < 5: scan_next = {} for name, dest in scan.iteritems(): if dest in self._phyref: self._phyref[name] = self._phyref[dest] else: scan_next[name] = dest scan = scan_next attempts += 1 def _ReadPackedRefs(self): path = os.path.join(self._gitdir, 'packed-refs') try: fd = open(path, 'rb') mtime = os.path.getmtime(path) except IOError: return except OSError: return try: for line in fd: if line[0] == '#': continue if line[0] == '^': continue line = line[:-1] p = line.split(' ') id = p[0] name = p[1] self._phyref[name] = id finally: fd.close() self._mtime['packed-refs'] = mtime def _ReadLoose(self, prefix): base = os.path.join(self._gitdir, prefix) for name in os.listdir(base): p = os.path.join(base, name) if os.path.isdir(p): self._mtime[prefix] = os.path.getmtime(base) self._ReadLoose(prefix + name + '/') elif name.endswith('.lock'): pass else: self._ReadLoose1(p, prefix + name) def _ReadLoose1(self, path, name): try: fd = open(path, 'rb') mtime = os.path.getmtime(path) except OSError: return except IOError: return try: id = fd.readline() finally: fd.close() if not id: return id = id[:-1] if id.startswith('ref: '): self._symref[name] = id[5:] else: self._phyref[name] = id self._mtime[name] = mtime
apache-2.0
sudheesh001/oh-mainline
vendor/packages/python-social-auth/social/tests/backends/test_broken.py
80
1072
import unittest2 as unittest from social.backends.base import BaseAuth class BrokenBackendAuth(BaseAuth): name = 'broken' class BrokenBackendTest(unittest.TestCase): def setUp(self): self.backend = BrokenBackendAuth() def tearDown(self): self.backend = None def test_auth_url(self): with self.assertRaisesRegexp(NotImplementedError, 'Implement in subclass'): self.backend.auth_url() def test_auth_html(self): with self.assertRaisesRegexp(NotImplementedError, 'Implement in subclass'): self.backend.auth_html() def test_auth_complete(self): with self.assertRaisesRegexp(NotImplementedError, 'Implement in subclass'): self.backend.auth_complete() def test_get_user_details(self): with self.assertRaisesRegexp(NotImplementedError, 'Implement in subclass'): self.backend.get_user_details(None)
agpl-3.0
willworth/thermos
thermos/Lib/site-packages/werkzeug/contrib/wrappers.py
105
10398
# -*- coding: utf-8 -*- """ werkzeug.contrib.wrappers ~~~~~~~~~~~~~~~~~~~~~~~~~ Extra wrappers or mixins contributed by the community. These wrappers can be mixed in into request objects to add extra functionality. Example:: from werkzeug.wrappers import Request as RequestBase from werkzeug.contrib.wrappers import JSONRequestMixin class Request(RequestBase, JSONRequestMixin): pass Afterwards this request object provides the extra functionality of the :class:`JSONRequestMixin`. :copyright: (c) 2014 by the Werkzeug Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ import codecs try: from simplejson import loads except ImportError: from json import loads from werkzeug.exceptions import BadRequest from werkzeug.utils import cached_property from werkzeug.http import dump_options_header, parse_options_header from werkzeug._compat import wsgi_decoding_dance def is_known_charset(charset): """Checks if the given charset is known to Python.""" try: codecs.lookup(charset) except LookupError: return False return True class JSONRequestMixin(object): """Add json method to a request object. This will parse the input data through simplejson if possible. :exc:`~werkzeug.exceptions.BadRequest` will be raised if the content-type is not json or if the data itself cannot be parsed as json. """ @cached_property def json(self): """Get the result of simplejson.loads if possible.""" if 'json' not in self.environ.get('CONTENT_TYPE', ''): raise BadRequest('Not a JSON request') try: return loads(self.data.decode(self.charset, self.encoding_errors)) except Exception: raise BadRequest('Unable to read JSON request') class ProtobufRequestMixin(object): """Add protobuf parsing method to a request object. This will parse the input data through `protobuf`_ if possible. :exc:`~werkzeug.exceptions.BadRequest` will be raised if the content-type is not protobuf or if the data itself cannot be parsed property. .. _protobuf: http://code.google.com/p/protobuf/ """ #: by default the :class:`ProtobufRequestMixin` will raise a #: :exc:`~werkzeug.exceptions.BadRequest` if the object is not #: initialized. You can bypass that check by setting this #: attribute to `False`. protobuf_check_initialization = True def parse_protobuf(self, proto_type): """Parse the data into an instance of proto_type.""" if 'protobuf' not in self.environ.get('CONTENT_TYPE', ''): raise BadRequest('Not a Protobuf request') obj = proto_type() try: obj.ParseFromString(self.data) except Exception: raise BadRequest("Unable to parse Protobuf request") # Fail if not all required fields are set if self.protobuf_check_initialization and not obj.IsInitialized(): raise BadRequest("Partial Protobuf request") return obj class RoutingArgsRequestMixin(object): """This request mixin adds support for the wsgiorg routing args `specification`_. .. _specification: https://wsgi.readthedocs.io/en/latest/specifications/routing_args.html """ def _get_routing_args(self): return self.environ.get('wsgiorg.routing_args', (()))[0] def _set_routing_args(self, value): if self.shallow: raise RuntimeError('A shallow request tried to modify the WSGI ' 'environment. If you really want to do that, ' 'set `shallow` to False.') self.environ['wsgiorg.routing_args'] = (value, self.routing_vars) routing_args = property(_get_routing_args, _set_routing_args, doc=''' The positional URL arguments as `tuple`.''') del _get_routing_args, _set_routing_args def _get_routing_vars(self): rv = self.environ.get('wsgiorg.routing_args') if rv is not None: return rv[1] rv = {} if not self.shallow: self.routing_vars = rv return rv def _set_routing_vars(self, value): if self.shallow: raise RuntimeError('A shallow request tried to modify the WSGI ' 'environment. If you really want to do that, ' 'set `shallow` to False.') self.environ['wsgiorg.routing_args'] = (self.routing_args, value) routing_vars = property(_get_routing_vars, _set_routing_vars, doc=''' The keyword URL arguments as `dict`.''') del _get_routing_vars, _set_routing_vars class ReverseSlashBehaviorRequestMixin(object): """This mixin reverses the trailing slash behavior of :attr:`script_root` and :attr:`path`. This makes it possible to use :func:`~urlparse.urljoin` directly on the paths. Because it changes the behavior or :class:`Request` this class has to be mixed in *before* the actual request class:: class MyRequest(ReverseSlashBehaviorRequestMixin, Request): pass This example shows the differences (for an application mounted on `/application` and the request going to `/application/foo/bar`): +---------------+-------------------+---------------------+ | | normal behavior | reverse behavior | +===============+===================+=====================+ | `script_root` | ``/application`` | ``/application/`` | +---------------+-------------------+---------------------+ | `path` | ``/foo/bar`` | ``foo/bar`` | +---------------+-------------------+---------------------+ """ @cached_property def path(self): """Requested path as unicode. This works a bit like the regular path info in the WSGI environment but will not include a leading slash. """ path = wsgi_decoding_dance(self.environ.get('PATH_INFO') or '', self.charset, self.encoding_errors) return path.lstrip('/') @cached_property def script_root(self): """The root path of the script includling a trailing slash.""" path = wsgi_decoding_dance(self.environ.get('SCRIPT_NAME') or '', self.charset, self.encoding_errors) return path.rstrip('/') + '/' class DynamicCharsetRequestMixin(object): """"If this mixin is mixed into a request class it will provide a dynamic `charset` attribute. This means that if the charset is transmitted in the content type headers it's used from there. Because it changes the behavior or :class:`Request` this class has to be mixed in *before* the actual request class:: class MyRequest(DynamicCharsetRequestMixin, Request): pass By default the request object assumes that the URL charset is the same as the data charset. If the charset varies on each request based on the transmitted data it's not a good idea to let the URLs change based on that. Most browsers assume either utf-8 or latin1 for the URLs if they have troubles figuring out. It's strongly recommended to set the URL charset to utf-8:: class MyRequest(DynamicCharsetRequestMixin, Request): url_charset = 'utf-8' .. versionadded:: 0.6 """ #: the default charset that is assumed if the content type header #: is missing or does not contain a charset parameter. The default #: is latin1 which is what HTTP specifies as default charset. #: You may however want to set this to utf-8 to better support #: browsers that do not transmit a charset for incoming data. default_charset = 'latin1' def unknown_charset(self, charset): """Called if a charset was provided but is not supported by the Python codecs module. By default latin1 is assumed then to not lose any information, you may override this method to change the behavior. :param charset: the charset that was not found. :return: the replacement charset. """ return 'latin1' @cached_property def charset(self): """The charset from the content type.""" header = self.environ.get('CONTENT_TYPE') if header: ct, options = parse_options_header(header) charset = options.get('charset') if charset: if is_known_charset(charset): return charset return self.unknown_charset(charset) return self.default_charset class DynamicCharsetResponseMixin(object): """If this mixin is mixed into a response class it will provide a dynamic `charset` attribute. This means that if the charset is looked up and stored in the `Content-Type` header and updates itself automatically. This also means a small performance hit but can be useful if you're working with different charsets on responses. Because the charset attribute is no a property at class-level, the default value is stored in `default_charset`. Because it changes the behavior or :class:`Response` this class has to be mixed in *before* the actual response class:: class MyResponse(DynamicCharsetResponseMixin, Response): pass .. versionadded:: 0.6 """ #: the default charset. default_charset = 'utf-8' def _get_charset(self): header = self.headers.get('content-type') if header: charset = parse_options_header(header)[1].get('charset') if charset: return charset return self.default_charset def _set_charset(self, charset): header = self.headers.get('content-type') ct, options = parse_options_header(header) if not ct: raise TypeError('Cannot set charset if Content-Type ' 'header is missing.') options['charset'] = charset self.headers['Content-Type'] = dump_options_header(ct, options) charset = property(_get_charset, _set_charset, doc=""" The charset for the response. It's stored inside the Content-Type header as a parameter.""") del _get_charset, _set_charset
mit
anakinsolo/backend
Lib/site-packages/pip/_vendor/html5lib/treebuilders/etree_lxml.py
1724
14031
"""Module for supporting the lxml.etree library. The idea here is to use as much of the native library as possible, without using fragile hacks like custom element names that break between releases. The downside of this is that we cannot represent all possible trees; specifically the following are known to cause problems: Text or comments as siblings of the root element Docypes with no name When any of these things occur, we emit a DataLossWarning """ from __future__ import absolute_import, division, unicode_literals import warnings import re import sys from . import _base from ..constants import DataLossWarning from .. import constants from . import etree as etree_builders from .. import ihatexml import lxml.etree as etree fullTree = True tag_regexp = re.compile("{([^}]*)}(.*)") comment_type = etree.Comment("asd").tag class DocumentType(object): def __init__(self, name, publicId, systemId): self.name = name self.publicId = publicId self.systemId = systemId class Document(object): def __init__(self): self._elementTree = None self._childNodes = [] def appendChild(self, element): self._elementTree.getroot().addnext(element._element) def _getChildNodes(self): return self._childNodes childNodes = property(_getChildNodes) def testSerializer(element): rv = [] finalText = None infosetFilter = ihatexml.InfosetFilter() def serializeElement(element, indent=0): if not hasattr(element, "tag"): if hasattr(element, "getroot"): # Full tree case rv.append("#document") if element.docinfo.internalDTD: if not (element.docinfo.public_id or element.docinfo.system_url): dtd_str = "<!DOCTYPE %s>" % element.docinfo.root_name else: dtd_str = """<!DOCTYPE %s "%s" "%s">""" % ( element.docinfo.root_name, element.docinfo.public_id, element.docinfo.system_url) rv.append("|%s%s" % (' ' * (indent + 2), dtd_str)) next_element = element.getroot() while next_element.getprevious() is not None: next_element = next_element.getprevious() while next_element is not None: serializeElement(next_element, indent + 2) next_element = next_element.getnext() elif isinstance(element, str) or isinstance(element, bytes): # Text in a fragment assert isinstance(element, str) or sys.version_info.major == 2 rv.append("|%s\"%s\"" % (' ' * indent, element)) else: # Fragment case rv.append("#document-fragment") for next_element in element: serializeElement(next_element, indent + 2) elif element.tag == comment_type: rv.append("|%s<!-- %s -->" % (' ' * indent, element.text)) if hasattr(element, "tail") and element.tail: rv.append("|%s\"%s\"" % (' ' * indent, element.tail)) else: assert isinstance(element, etree._Element) nsmatch = etree_builders.tag_regexp.match(element.tag) if nsmatch is not None: ns = nsmatch.group(1) tag = nsmatch.group(2) prefix = constants.prefixes[ns] rv.append("|%s<%s %s>" % (' ' * indent, prefix, infosetFilter.fromXmlName(tag))) else: rv.append("|%s<%s>" % (' ' * indent, infosetFilter.fromXmlName(element.tag))) if hasattr(element, "attrib"): attributes = [] for name, value in element.attrib.items(): nsmatch = tag_regexp.match(name) if nsmatch is not None: ns, name = nsmatch.groups() name = infosetFilter.fromXmlName(name) prefix = constants.prefixes[ns] attr_string = "%s %s" % (prefix, name) else: attr_string = infosetFilter.fromXmlName(name) attributes.append((attr_string, value)) for name, value in sorted(attributes): rv.append('|%s%s="%s"' % (' ' * (indent + 2), name, value)) if element.text: rv.append("|%s\"%s\"" % (' ' * (indent + 2), element.text)) indent += 2 for child in element: serializeElement(child, indent) if hasattr(element, "tail") and element.tail: rv.append("|%s\"%s\"" % (' ' * (indent - 2), element.tail)) serializeElement(element, 0) if finalText is not None: rv.append("|%s\"%s\"" % (' ' * 2, finalText)) return "\n".join(rv) def tostring(element): """Serialize an element and its child nodes to a string""" rv = [] finalText = None def serializeElement(element): if not hasattr(element, "tag"): if element.docinfo.internalDTD: if element.docinfo.doctype: dtd_str = element.docinfo.doctype else: dtd_str = "<!DOCTYPE %s>" % element.docinfo.root_name rv.append(dtd_str) serializeElement(element.getroot()) elif element.tag == comment_type: rv.append("<!--%s-->" % (element.text,)) else: # This is assumed to be an ordinary element if not element.attrib: rv.append("<%s>" % (element.tag,)) else: attr = " ".join(["%s=\"%s\"" % (name, value) for name, value in element.attrib.items()]) rv.append("<%s %s>" % (element.tag, attr)) if element.text: rv.append(element.text) for child in element: serializeElement(child) rv.append("</%s>" % (element.tag,)) if hasattr(element, "tail") and element.tail: rv.append(element.tail) serializeElement(element) if finalText is not None: rv.append("%s\"" % (' ' * 2, finalText)) return "".join(rv) class TreeBuilder(_base.TreeBuilder): documentClass = Document doctypeClass = DocumentType elementClass = None commentClass = None fragmentClass = Document implementation = etree def __init__(self, namespaceHTMLElements, fullTree=False): builder = etree_builders.getETreeModule(etree, fullTree=fullTree) infosetFilter = self.infosetFilter = ihatexml.InfosetFilter() self.namespaceHTMLElements = namespaceHTMLElements class Attributes(dict): def __init__(self, element, value={}): self._element = element dict.__init__(self, value) for key, value in self.items(): if isinstance(key, tuple): name = "{%s}%s" % (key[2], infosetFilter.coerceAttribute(key[1])) else: name = infosetFilter.coerceAttribute(key) self._element._element.attrib[name] = value def __setitem__(self, key, value): dict.__setitem__(self, key, value) if isinstance(key, tuple): name = "{%s}%s" % (key[2], infosetFilter.coerceAttribute(key[1])) else: name = infosetFilter.coerceAttribute(key) self._element._element.attrib[name] = value class Element(builder.Element): def __init__(self, name, namespace): name = infosetFilter.coerceElement(name) builder.Element.__init__(self, name, namespace=namespace) self._attributes = Attributes(self) def _setName(self, name): self._name = infosetFilter.coerceElement(name) self._element.tag = self._getETreeTag( self._name, self._namespace) def _getName(self): return infosetFilter.fromXmlName(self._name) name = property(_getName, _setName) def _getAttributes(self): return self._attributes def _setAttributes(self, attributes): self._attributes = Attributes(self, attributes) attributes = property(_getAttributes, _setAttributes) def insertText(self, data, insertBefore=None): data = infosetFilter.coerceCharacters(data) builder.Element.insertText(self, data, insertBefore) def appendChild(self, child): builder.Element.appendChild(self, child) class Comment(builder.Comment): def __init__(self, data): data = infosetFilter.coerceComment(data) builder.Comment.__init__(self, data) def _setData(self, data): data = infosetFilter.coerceComment(data) self._element.text = data def _getData(self): return self._element.text data = property(_getData, _setData) self.elementClass = Element self.commentClass = builder.Comment # self.fragmentClass = builder.DocumentFragment _base.TreeBuilder.__init__(self, namespaceHTMLElements) def reset(self): _base.TreeBuilder.reset(self) self.insertComment = self.insertCommentInitial self.initial_comments = [] self.doctype = None def testSerializer(self, element): return testSerializer(element) def getDocument(self): if fullTree: return self.document._elementTree else: return self.document._elementTree.getroot() def getFragment(self): fragment = [] element = self.openElements[0]._element if element.text: fragment.append(element.text) fragment.extend(list(element)) if element.tail: fragment.append(element.tail) return fragment def insertDoctype(self, token): name = token["name"] publicId = token["publicId"] systemId = token["systemId"] if not name: warnings.warn("lxml cannot represent empty doctype", DataLossWarning) self.doctype = None else: coercedName = self.infosetFilter.coerceElement(name) if coercedName != name: warnings.warn("lxml cannot represent non-xml doctype", DataLossWarning) doctype = self.doctypeClass(coercedName, publicId, systemId) self.doctype = doctype def insertCommentInitial(self, data, parent=None): self.initial_comments.append(data) def insertCommentMain(self, data, parent=None): if (parent == self.document and self.document._elementTree.getroot()[-1].tag == comment_type): warnings.warn("lxml cannot represent adjacent comments beyond the root elements", DataLossWarning) super(TreeBuilder, self).insertComment(data, parent) def insertRoot(self, token): """Create the document root""" # Because of the way libxml2 works, it doesn't seem to be possible to # alter information like the doctype after the tree has been parsed. # Therefore we need to use the built-in parser to create our iniial # tree, after which we can add elements like normal docStr = "" if self.doctype: assert self.doctype.name docStr += "<!DOCTYPE %s" % self.doctype.name if (self.doctype.publicId is not None or self.doctype.systemId is not None): docStr += (' PUBLIC "%s" ' % (self.infosetFilter.coercePubid(self.doctype.publicId or ""))) if self.doctype.systemId: sysid = self.doctype.systemId if sysid.find("'") >= 0 and sysid.find('"') >= 0: warnings.warn("DOCTYPE system cannot contain single and double quotes", DataLossWarning) sysid = sysid.replace("'", 'U00027') if sysid.find("'") >= 0: docStr += '"%s"' % sysid else: docStr += "'%s'" % sysid else: docStr += "''" docStr += ">" if self.doctype.name != token["name"]: warnings.warn("lxml cannot represent doctype with a different name to the root element", DataLossWarning) docStr += "<THIS_SHOULD_NEVER_APPEAR_PUBLICLY/>" root = etree.fromstring(docStr) # Append the initial comments: for comment_token in self.initial_comments: root.addprevious(etree.Comment(comment_token["data"])) # Create the root document and add the ElementTree to it self.document = self.documentClass() self.document._elementTree = root.getroottree() # Give the root element the right name name = token["name"] namespace = token.get("namespace", self.defaultNamespace) if namespace is None: etree_tag = name else: etree_tag = "{%s}%s" % (namespace, name) root.tag = etree_tag # Add the root element to the internal child/open data structures root_element = self.elementClass(name, namespace) root_element._element = root self.document._childNodes.append(root_element) self.openElements.append(root_element) # Reset to the default insert comment function self.insertComment = self.insertCommentMain
mit
ncb000gt/node-gyp
gyp/pylib/gyp/xml_fix.py
2767
2174
# Copyright (c) 2011 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. """Applies a fix to CR LF TAB handling in xml.dom. Fixes this: http://code.google.com/p/chromium/issues/detail?id=76293 Working around this: http://bugs.python.org/issue5752 TODO(bradnelson): Consider dropping this when we drop XP support. """ import xml.dom.minidom def _Replacement_write_data(writer, data, is_attrib=False): """Writes datachars to writer.""" data = data.replace("&", "&amp;").replace("<", "&lt;") data = data.replace("\"", "&quot;").replace(">", "&gt;") if is_attrib: data = data.replace( "\r", "&#xD;").replace( "\n", "&#xA;").replace( "\t", "&#x9;") writer.write(data) def _Replacement_writexml(self, writer, indent="", addindent="", newl=""): # indent = current indentation # addindent = indentation to add to higher levels # newl = newline string writer.write(indent+"<" + self.tagName) attrs = self._get_attributes() a_names = attrs.keys() a_names.sort() for a_name in a_names: writer.write(" %s=\"" % a_name) _Replacement_write_data(writer, attrs[a_name].value, is_attrib=True) writer.write("\"") if self.childNodes: writer.write(">%s" % newl) for node in self.childNodes: node.writexml(writer, indent + addindent, addindent, newl) writer.write("%s</%s>%s" % (indent, self.tagName, newl)) else: writer.write("/>%s" % newl) class XmlFix(object): """Object to manage temporary patching of xml.dom.minidom.""" def __init__(self): # Preserve current xml.dom.minidom functions. self.write_data = xml.dom.minidom._write_data self.writexml = xml.dom.minidom.Element.writexml # Inject replacement versions of a function and a method. xml.dom.minidom._write_data = _Replacement_write_data xml.dom.minidom.Element.writexml = _Replacement_writexml def Cleanup(self): if self.write_data: xml.dom.minidom._write_data = self.write_data xml.dom.minidom.Element.writexml = self.writexml self.write_data = None def __del__(self): self.Cleanup()
mit
kzvyahin/cfme_tests
scripts/enable_external_db.py
6
1937
#!/usr/bin/env python2 """Set up an external DB on an appliance over SSH. Appliance address and database address are required. Database name and region are optional and default to 'vmdb_production' and 0 respectively. Credentials are optional but default values must be set in credentials.yaml under 'database' key. Example usage: Connect appliance 10.0.0.1 to database 'cfme_db' on 20.0.0.1, use region 1 and default credentials (from yaml): enable_external_db.py 10.0.0.1 20.0.0.1 --database cfme_db --region 1 """ import argparse import sys from utils.appliance import IPAppliance from utils.conf import credentials def main(): parser = argparse.ArgumentParser(epilog=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('address', nargs='?', default=None, help='hostname or ip address of target appliance') parser.add_argument('db_address', help='hostname or ip address of external database') parser.add_argument('--database', default='vmdb_production', help='name of the external database') parser.add_argument('--region', default=0, type=int, help='region to assign to the new DB') parser.add_argument('--username', default=credentials['database']['username'], help='username for external database') parser.add_argument('--password', default=credentials['database']['password'], help='password for external database') args = parser.parse_args() print('Initializing Appliance External DB') ip_a = IPAppliance(args.address) status, out = ip_a.enable_external_db(args.db_address, args.region, args.database, args.username, args.password) if status != 0: print('Enabling DB failed with error:') print(out) sys.exit(1) else: print('DB Enabled, evm watchdog should start the UI shortly.') if __name__ == '__main__': sys.exit(main())
gpl-2.0
citrix-openstack-build/heat
heat/tests/test_components.py
5
6976
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # 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 heat.engine.components import Component from heat.engine.components import Components from heat.tests.common import HeatTestCase class ComponentTest(HeatTestCase): def test_init(self): comp = Component() self.assertEqual(comp.type, 'OS::Heat::SoftwareConfig') self.assertEqual(comp.properties, {}) self.assertEqual(comp.scripts, {}) self.assertEqual(comp.relations, []) self.assertEqual(comp.hosted_on(), None) self.assertEqual(comp.depends(), []) def test_hosted_on(self): schema = { 'relationships': [ {'hosted_on': 'wordpress'} ] } comp = Component(schema) self.assertEqual(comp.hosted_on(), 'wordpress') def test_depends(self): schema = { 'relationships': [ {'depends_on': 'config_mysql'} ] } comp = Component(schema) self.assertEqual(comp.depends(), ['config_mysql']) comp['relationships'].append({'depends_on': 'config_wordpress'}) self.assertEqual(comp.depends(), ['config_mysql', 'config_wordpress']) class ComponentsTest(HeatTestCase): def test_init(self): schema = {} comps = Components(schema) self.assertEqual(0, len(comps)) schema['config_mysql'] = {} comps = Components(schema) self.assertEqual(1, len(comps)) comp = comps['config_mysql'] self.assertIsInstance(comp, Component) def test_depends(self): schema = { 'install_mysql': { }, 'config_mysql': { 'relationships': [ {'depends_on': 'install_mysql'} ] }, 'start_mysql': { 'relationships': [ {'depends_on': 'config_mysql'} ] } } comps = Components(schema) self.assertEqual(3, len(comps)) deps = comps.depends() self.assertEqual(2, len(deps)) self.assertIn('install_mysql', deps) self.assertIn('config_mysql', deps) def test_multi_depends(self): schema = { 'install_mysql': { }, 'config_mysql': { 'relationships': [ {'depends_on': 'install_mysql'} ] }, 'start_mysql': { 'relationships': [ {'depends_on': 'config_mysql'} ] }, 'install_wordpress': {}, 'config_wordpress': { 'relationships': [ {'depends_on': 'install_wordpress'} ] }, 'start_wordpress': { 'relationships': [ {'depends_on': 'config_wordpress'}, {'depends_on': 'start_mysql'} ] } } comps = Components(schema) deps = comps.depends() self.assertEqual(5, len(deps)) self.assertNotIn('start_wordpress', deps) self.assertIn('install_wordpress', deps) self.assertIn('config_wordpress', deps) self.assertIn('start_mysql', deps) self.assertIn('config_mysql', deps) self.assertIn('install_mysql', deps) def test_filter(self): schema = { 'install_mysql': { 'relationships': [ {'hosted_on': 'mysql'} ] }, 'config_mysql': { 'relationships': [ {'hosted_on': 'mysql'}, {'depends_on': 'install_mysql'} ] }, 'start_mysql': { 'relationships': [ {'hosted_on': 'mysql'}, {'depends_on': 'config_mysql'} ] }, 'install_wordpress': { 'relationships': [ {'hosted_on': 'wordpress'} ] }, 'config_wordpress': { 'relationships': [ {'hosted_on': 'wordpress'}, {'depends_on': 'install_wordpress'} ] }, 'start_wordpress': { 'relationships': [ {'hosted_on': 'wordpress'}, {'depends_on': 'config_wordpress'}, {'depends_on': 'start_mysql'} ] } } comps = Components(schema) names = comps.filter('mysql') self.assertEqual(3, len(names)) self.assertIn('config_mysql', names) self.assertIn('install_mysql', names) self.assertIn('start_mysql', names) names = comps.filter('wordpress') self.assertEqual(3, len(names)) self.assertIn('config_wordpress', names) self.assertIn('install_wordpress', names) self.assertIn('start_wordpress', names) def test_validate(self): schema = {'install_mysql': {}} comps = Components(schema) self.assertTrue(comps.validate()) schema = { 'config_mysql': { 'relationships': [ {'depends_on': 'config_mysql'} ] } } comps = Components(schema) err = self.assertRaises(ValueError, comps.validate) self.assertIn('component config_mysql depends on itself.', str(err)) schema = { 'config_mysql': { 'relationships': [ {'depends_on': 'install_mysql'} ] } } comps = Components(schema) err = self.assertRaises(ValueError, comps.validate) self.assertIn('component install_mysql is not defined.', str(err)) schema = { 'install_mysql': { }, 'config_mysql': { 'relationships': [ {'depends_on': 'install_mysql'}, {'depends_on': 'install_mysql'} ] } } comps = Components(schema) err = self.assertRaises(ValueError, comps.validate) self.assertIn('duplicated install_mysql in config_mysql depends on.', str(err))
apache-2.0
zlorb/mitmproxy
mitmproxy/utils/human.py
3
2501
import datetime import ipaddress import time import functools import typing SIZE_TABLE = [ ("b", 1024 ** 0), ("k", 1024 ** 1), ("m", 1024 ** 2), ("g", 1024 ** 3), ("t", 1024 ** 4), ] SIZE_UNITS = dict(SIZE_TABLE) def pretty_size(size): for bottom, top in zip(SIZE_TABLE, SIZE_TABLE[1:]): if bottom[1] <= size < top[1]: suf = bottom[0] lim = bottom[1] x = round(size / lim, 2) if x == int(x): x = int(x) return str(x) + suf return "%s%s" % (size, SIZE_TABLE[0][0]) @functools.lru_cache() def parse_size(s: typing.Optional[str]) -> typing.Optional[int]: """ Parse a size with an optional k/m/... suffix. Invalid values raise a ValueError. For added convenience, passing `None` returns `None`. """ if s is None: return None try: return int(s) except ValueError: pass for i in SIZE_UNITS.keys(): if s.endswith(i): try: return int(s[:-1]) * SIZE_UNITS[i] except ValueError: break raise ValueError("Invalid size specification.") def pretty_duration(secs): formatters = [ (100, "{:.0f}s"), (10, "{:2.1f}s"), (1, "{:1.2f}s"), ] for limit, formatter in formatters: if secs >= limit: return formatter.format(secs) # less than 1 sec return "{:.0f}ms".format(secs * 1000) def format_timestamp(s): s = time.localtime(s) d = datetime.datetime.fromtimestamp(time.mktime(s)) return d.strftime("%Y-%m-%d %H:%M:%S") def format_timestamp_with_milli(s): d = datetime.datetime.fromtimestamp(s) return d.strftime("%Y-%m-%d %H:%M:%S.%f")[:-3] def format_address(address: typing.Optional[tuple]) -> str: """ This function accepts IPv4/IPv6 tuples and returns the formatted address string with port number """ if address is None: return "<no address>" try: host = ipaddress.ip_address(address[0]) if host.is_unspecified: return "*:{}".format(address[1]) if isinstance(host, ipaddress.IPv4Address): return "{}:{}".format(str(host), address[1]) # If IPv6 is mapped to IPv4 elif host.ipv4_mapped: return "{}:{}".format(str(host.ipv4_mapped), address[1]) return "[{}]:{}".format(str(host), address[1]) except ValueError: return "{}:{}".format(address[0], address[1])
mit
AkshaySathe2/WearableSunshine
flatten.py
4
5942
#! /usr/local/bin/python import argparse import os import shutil import sys import tempfile import git IGNORE_PATTERNS = ('.git', ".DS_Store") SAFE_CHARS = ["-", "_", "."] MAX_LENGTH = 100 STUDENT = "student" DEVELOP = "develop-" DEVELOP_DEFAULT = "all develop branches" DIFF_FORMAT = """ You can download a zip of this exercise [here](https://github.com/udacity/ud843-QuakeReport/archive/{number}-Exercise-{name}.zip), \ and a zip of the solution [here](https://github.com/udacity/ud843-QuakeReport/archive/{number}-Solution-{name}.zip). \ Also, you can find a visual summary of the solution [here](https://github.com/udacity/ud843-QuakeReport/compare/\ {number}-Exercise-{name}...{number}-Solution-{name}). """ def flatten(repo_dir, target_dir, student, develop_branches, remove_branches, links): repo = git.Repo(repo_dir) if develop_branches == DEVELOP_DEFAULT: develop_branches = [branch for branch in repo.branches if DEVELOP in branch.name] if remove_branches: remove_local_branches(repo, student, develop_branches) flat = len(develop_branches) == 1 # print develop_branches try: temp_dir = tempfile.mkdtemp() # try: # current_branch = repo.active_branch # print "Stashing" # repo.git.stash() for develop in develop_branches: to_temp_dir(repo, repo_dir, develop, temp_dir, flat, links) if links: insert_diff_links(temp_dir) copy_snapshots(repo, student, temp_dir, target_dir) # finally: # if current_branch: # repo.git.checkout(current_branch) # print "Popping" # if repo.git.stash("list"): # repo.git.stash("pop") finally: if os.path.exists(temp_dir): shutil.rmtree(temp_dir) print "Done! Review and commit the", student, "branch at your leisure." print "Then run $ git push --all --prune" def remove_local_branches(repo, student, develop_branches): for branch in repo.branches: if branch.name != student and str(branch) not in develop_branches: print "Removing local branch:", branch.name repo.git.branch(branch.name, "-D") def to_temp_dir(repo, repo_dir, develop, temp_dir, flat, links): for rev in repo.git.rev_list(develop).split("\n"): commit = repo.commit(rev) branch_name = clean_commit_message(commit.message) if "Exercise" in branch_name or "Solution" in branch_name: if branch_name in repo.branches: repo.git.branch(branch_name, "-D") new_branch = repo.create_head(branch_name) new_branch.set_commit(rev) repo.git.checkout(commit) print "Saving snapshot of:", branch_name repo.git.clean("-fdx") if flat: target_dir = os.path.join(temp_dir, branch_name) else: folder_name = develop.name.split("-",1)[1] target_dir = os.path.join(temp_dir, folder_name, branch_name) shutil.copytree(repo_dir, target_dir, ignore=shutil.ignore_patterns(*IGNORE_PATTERNS)) if links: with open(os.path.join(target_dir, "README.md"), "a") as readme: print branch_name number, _, name = branch_name.split("-") readme.write(DIFF_FORMAT.format(number=number, name=name)) def clean_commit_message(message): first_line = message.split("\n")[0] safe_message = "".join( c for c in first_line if c.isalnum() or c in SAFE_CHARS).strip() return safe_message[:MAX_LENGTH] if len(safe_message) > MAX_LENGTH else safe_message def insert_diff_links(temp_dir): for item in os.listdir(temp_dir): number, _, name = item.split("-") with open(os.path.join(temp_dir, item, "README.md"), "a") as readme: readme.write(DIFF_FORMAT.format(number=number, name=name)) def copy_snapshots(repo, student, temp_dir, target_dir): if target_dir == os.getcwd(): repo.git.checkout(student) for item in os.listdir(temp_dir): source_dir = os.path.join(temp_dir, item) dest_dir = os.path.join(target_dir, item) if os.path.exists(dest_dir): shutil.rmtree(dest_dir) print "Copying: ", item shutil.copytree(source_dir, dest_dir) DESCRIPTION = "This script " EPILOG = " To make changes to " def main(): parser = argparse.ArgumentParser( description=DESCRIPTION, epilog=EPILOG, formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-b', '--remove', action='store_true', help='delete all local branches except the student and develop branches') parser.add_argument('-d', '--directory', default=os.getcwd(), help="the directory of the source repository") parser.add_argument('-t', '--target', default=os.getcwd(), help="target directory") parser.add_argument('-s', '--student', default=STUDENT, help="branch where snapshots will be copied") parser.add_argument('-l', '--links', action='store_true', help="Add links to branches and diff to README files") parser.add_argument('develop_branches', nargs="*", default=DEVELOP_DEFAULT, help="the branches where snapshots will be copied from") parsed = parser.parse_args() flatten( parsed.directory, parsed.target, parsed.student, parsed.develop_branches, parsed.remove, parsed.links ) if __name__ == "__main__": sys.exit(main())
apache-2.0
theicfire/djangofun
dbindexer/compiler.py
13
1320
from .resolver import resolver from django.utils.importlib import import_module def __repr__(self): return '<%s, %s, %s, %s>' % (self.alias, self.col, self.field.name, self.field.model.__name__) from django.db.models.sql.where import Constraint Constraint.__repr__ = __repr__ # TODO: manipulate a copy of the query instead of the query itself. This has to # be done because the query can be reused afterwards by the user so that a # manipulated query can result in strange behavior for these cases! #TODO: Add watching layer which gives suggestions for indexes via query inspection # at runtime class BaseCompiler(object): def convert_filters(self): resolver.convert_filters(self.query) class SQLCompiler(BaseCompiler): def execute_sql(self, *args, **kwargs): self.convert_filters() return super(SQLCompiler, self).execute_sql(*args, **kwargs) def results_iter(self): self.convert_filters() return super(SQLCompiler, self).results_iter() class SQLInsertCompiler(BaseCompiler): def execute_sql(self, return_id=False): resolver.convert_insert_query(self.query) return super(SQLInsertCompiler, self).execute_sql(return_id=return_id) class SQLUpdateCompiler(BaseCompiler): pass class SQLDeleteCompiler(BaseCompiler): pass
bsd-3-clause
OmarIthawi/edx-platform
lms/djangoapps/bulk_email/admin.py
71
3138
""" Django admin page for bulk email models """ from django.contrib import admin from bulk_email.models import CourseEmail, Optout, CourseEmailTemplate, CourseAuthorization from bulk_email.forms import CourseEmailTemplateForm, CourseAuthorizationAdminForm class CourseEmailAdmin(admin.ModelAdmin): """Admin for course email.""" readonly_fields = ('sender',) class OptoutAdmin(admin.ModelAdmin): """Admin for optouts.""" list_display = ('user', 'course_id') class CourseEmailTemplateAdmin(admin.ModelAdmin): """Admin for course email templates.""" form = CourseEmailTemplateForm fieldsets = ( (None, { # make the HTML template display above the plain template: 'fields': ('html_template', 'plain_template', 'name'), 'description': ''' Enter template to be used by course staff when sending emails to enrolled students. The HTML template is for HTML email, and may contain HTML markup. The plain template is for plaintext email. Both templates should contain the string '{{message_body}}' (with two curly braces on each side), to indicate where the email text is to be inserted. Other tags that may be used (surrounded by one curly brace on each side): {platform_name} : the name of the platform {course_title} : the name of the course {course_url} : the course's full URL {email} : the user's email address {account_settings_url} : URL at which users can change email preferences {course_image_url} : URL for the course's course image. Will return a broken link if course doesn't have a course image set. Note that there is currently NO validation on tags, so be careful. Typos or use of unsupported tags will cause email sending to fail. ''' }), ) # Turn off the action bar (we have no bulk actions) actions = None def has_add_permission(self, request): """Enable the ability to add new templates, as we want to be able to define multiple templates.""" return True def has_delete_permission(self, request, obj=None): """Disables the ability to remove existing templates, as we'd like to make sure we don't have dangling references.""" return False class CourseAuthorizationAdmin(admin.ModelAdmin): """Admin for enabling email on a course-by-course basis.""" form = CourseAuthorizationAdminForm fieldsets = ( (None, { 'fields': ('course_id', 'email_enabled'), 'description': ''' Enter a course id in the following form: Org/Course/CourseRun, eg MITx/6.002x/2012_Fall Do not enter leading or trailing slashes. There is no need to surround the course ID with quotes. Validation will be performed on the course name, and if it is invalid, an error message will display. To enable email for the course, check the "Email enabled" box, then click "Save". ''' }), ) admin.site.register(CourseEmail, CourseEmailAdmin) admin.site.register(Optout, OptoutAdmin) admin.site.register(CourseEmailTemplate, CourseEmailTemplateAdmin) admin.site.register(CourseAuthorization, CourseAuthorizationAdmin)
agpl-3.0
rhtu/linux
tools/perf/scripts/python/compaction-times.py
958
7950
# report time spent in compaction # Licensed under the terms of the GNU GPL License version 2 # testing: # 'echo 1 > /proc/sys/vm/compact_memory' to force compaction of all zones import os import sys import re import signal signal.signal(signal.SIGPIPE, signal.SIG_DFL) usage = "usage: perf script report compaction-times.py -- [-h] [-u] [-p|-pv] [-t | [-m] [-fs] [-ms]] [pid|pid-range|comm-regex]\n" class popt: DISP_DFL = 0 DISP_PROC = 1 DISP_PROC_VERBOSE=2 class topt: DISP_TIME = 0 DISP_MIG = 1 DISP_ISOLFREE = 2 DISP_ISOLMIG = 4 DISP_ALL = 7 class comm_filter: def __init__(self, re): self.re = re def filter(self, pid, comm): m = self.re.search(comm) return m == None or m.group() == "" class pid_filter: def __init__(self, low, high): self.low = (0 if low == "" else int(low)) self.high = (0 if high == "" else int(high)) def filter(self, pid, comm): return not (pid >= self.low and (self.high == 0 or pid <= self.high)) def set_type(t): global opt_disp opt_disp = (t if opt_disp == topt.DISP_ALL else opt_disp|t) def ns(sec, nsec): return (sec * 1000000000) + nsec def time(ns): return "%dns" % ns if opt_ns else "%dus" % (round(ns, -3) / 1000) class pair: def __init__(self, aval, bval, alabel = None, blabel = None): self.alabel = alabel self.blabel = blabel self.aval = aval self.bval = bval def __add__(self, rhs): self.aval += rhs.aval self.bval += rhs.bval return self def __str__(self): return "%s=%d %s=%d" % (self.alabel, self.aval, self.blabel, self.bval) class cnode: def __init__(self, ns): self.ns = ns self.migrated = pair(0, 0, "moved", "failed") self.fscan = pair(0,0, "scanned", "isolated") self.mscan = pair(0,0, "scanned", "isolated") def __add__(self, rhs): self.ns += rhs.ns self.migrated += rhs.migrated self.fscan += rhs.fscan self.mscan += rhs.mscan return self def __str__(self): prev = 0 s = "%s " % time(self.ns) if (opt_disp & topt.DISP_MIG): s += "migration: %s" % self.migrated prev = 1 if (opt_disp & topt.DISP_ISOLFREE): s += "%sfree_scanner: %s" % (" " if prev else "", self.fscan) prev = 1 if (opt_disp & topt.DISP_ISOLMIG): s += "%smigration_scanner: %s" % (" " if prev else "", self.mscan) return s def complete(self, secs, nsecs): self.ns = ns(secs, nsecs) - self.ns def increment(self, migrated, fscan, mscan): if (migrated != None): self.migrated += migrated if (fscan != None): self.fscan += fscan if (mscan != None): self.mscan += mscan class chead: heads = {} val = cnode(0); fobj = None @classmethod def add_filter(cls, filter): cls.fobj = filter @classmethod def create_pending(cls, pid, comm, start_secs, start_nsecs): filtered = 0 try: head = cls.heads[pid] filtered = head.is_filtered() except KeyError: if cls.fobj != None: filtered = cls.fobj.filter(pid, comm) head = cls.heads[pid] = chead(comm, pid, filtered) if not filtered: head.mark_pending(start_secs, start_nsecs) @classmethod def increment_pending(cls, pid, migrated, fscan, mscan): head = cls.heads[pid] if not head.is_filtered(): if head.is_pending(): head.do_increment(migrated, fscan, mscan) else: sys.stderr.write("missing start compaction event for pid %d\n" % pid) @classmethod def complete_pending(cls, pid, secs, nsecs): head = cls.heads[pid] if not head.is_filtered(): if head.is_pending(): head.make_complete(secs, nsecs) else: sys.stderr.write("missing start compaction event for pid %d\n" % pid) @classmethod def gen(cls): if opt_proc != popt.DISP_DFL: for i in cls.heads: yield cls.heads[i] @classmethod def str(cls): return cls.val def __init__(self, comm, pid, filtered): self.comm = comm self.pid = pid self.val = cnode(0) self.pending = None self.filtered = filtered self.list = [] def __add__(self, rhs): self.ns += rhs.ns self.val += rhs.val return self def mark_pending(self, secs, nsecs): self.pending = cnode(ns(secs, nsecs)) def do_increment(self, migrated, fscan, mscan): self.pending.increment(migrated, fscan, mscan) def make_complete(self, secs, nsecs): self.pending.complete(secs, nsecs) chead.val += self.pending if opt_proc != popt.DISP_DFL: self.val += self.pending if opt_proc == popt.DISP_PROC_VERBOSE: self.list.append(self.pending) self.pending = None def enumerate(self): if opt_proc == popt.DISP_PROC_VERBOSE and not self.is_filtered(): for i, pelem in enumerate(self.list): sys.stdout.write("%d[%s].%d: %s\n" % (self.pid, self.comm, i+1, pelem)) def is_pending(self): return self.pending != None def is_filtered(self): return self.filtered def display(self): if not self.is_filtered(): sys.stdout.write("%d[%s]: %s\n" % (self.pid, self.comm, self.val)) def trace_end(): sys.stdout.write("total: %s\n" % chead.str()) for i in chead.gen(): i.display(), i.enumerate() def compaction__mm_compaction_migratepages(event_name, context, common_cpu, common_secs, common_nsecs, common_pid, common_comm, common_callchain, nr_migrated, nr_failed): chead.increment_pending(common_pid, pair(nr_migrated, nr_failed), None, None) def compaction__mm_compaction_isolate_freepages(event_name, context, common_cpu, common_secs, common_nsecs, common_pid, common_comm, common_callchain, start_pfn, end_pfn, nr_scanned, nr_taken): chead.increment_pending(common_pid, None, pair(nr_scanned, nr_taken), None) def compaction__mm_compaction_isolate_migratepages(event_name, context, common_cpu, common_secs, common_nsecs, common_pid, common_comm, common_callchain, start_pfn, end_pfn, nr_scanned, nr_taken): chead.increment_pending(common_pid, None, None, pair(nr_scanned, nr_taken)) def compaction__mm_compaction_end(event_name, context, common_cpu, common_secs, common_nsecs, common_pid, common_comm, common_callchain, zone_start, migrate_start, free_start, zone_end, sync, status): chead.complete_pending(common_pid, common_secs, common_nsecs) def compaction__mm_compaction_begin(event_name, context, common_cpu, common_secs, common_nsecs, common_pid, common_comm, common_callchain, zone_start, migrate_start, free_start, zone_end, sync): chead.create_pending(common_pid, common_comm, common_secs, common_nsecs) def pr_help(): global usage sys.stdout.write(usage) sys.stdout.write("\n") sys.stdout.write("-h display this help\n") sys.stdout.write("-p display by process\n") sys.stdout.write("-pv display by process (verbose)\n") sys.stdout.write("-t display stall times only\n") sys.stdout.write("-m display stats for migration\n") sys.stdout.write("-fs display stats for free scanner\n") sys.stdout.write("-ms display stats for migration scanner\n") sys.stdout.write("-u display results in microseconds (default nanoseconds)\n") comm_re = None pid_re = None pid_regex = "^(\d*)-(\d*)$|^(\d*)$" opt_proc = popt.DISP_DFL opt_disp = topt.DISP_ALL opt_ns = True argc = len(sys.argv) - 1 if argc >= 1: pid_re = re.compile(pid_regex) for i, opt in enumerate(sys.argv[1:]): if opt[0] == "-": if opt == "-h": pr_help() exit(0); elif opt == "-p": opt_proc = popt.DISP_PROC elif opt == "-pv": opt_proc = popt.DISP_PROC_VERBOSE elif opt == '-u': opt_ns = False elif opt == "-t": set_type(topt.DISP_TIME) elif opt == "-m": set_type(topt.DISP_MIG) elif opt == "-fs": set_type(topt.DISP_ISOLFREE) elif opt == "-ms": set_type(topt.DISP_ISOLMIG) else: sys.exit(usage) elif i == argc - 1: m = pid_re.search(opt) if m != None and m.group() != "": if m.group(3) != None: f = pid_filter(m.group(3), m.group(3)) else: f = pid_filter(m.group(1), m.group(2)) else: try: comm_re=re.compile(opt) except: sys.stderr.write("invalid regex '%s'" % opt) sys.exit(usage) f = comm_filter(comm_re) chead.add_filter(f)
gpl-2.0
jhg/django
tests/template_backends/test_utils.py
351
1521
from django.core.exceptions import ImproperlyConfigured from django.template import engines from django.test import SimpleTestCase, override_settings class TemplateStringsTests(SimpleTestCase): @override_settings(TEMPLATES=[{ 'BACKEND': 'raise.import.error', }]) def test_backend_import_error(self): """ Failing to import a backend keeps raising the original import error. Regression test for #24265. """ with self.assertRaises(ImportError): engines.all() with self.assertRaises(ImportError): engines.all() @override_settings(TEMPLATES=[{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', # Incorrect: APP_DIRS and loaders are mutually incompatible. 'APP_DIRS': True, 'OPTIONS': {'loaders': []}, }]) def test_backend_improperly_configured(self): """ Failing to initialize a backend keeps raising the original exception. Regression test for #24265. """ with self.assertRaises(ImproperlyConfigured): engines.all() with self.assertRaises(ImproperlyConfigured): engines.all() @override_settings(TEMPLATES=[{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', }, { 'BACKEND': 'django.template.backends.django.DjangoTemplates', }]) def test_backend_names_must_be_unique(self): with self.assertRaises(ImproperlyConfigured): engines.all()
bsd-3-clause
meizon/python-oauth2
oauth2/clients/smtp.py
884
1680
""" The MIT License Copyright (c) 2007-2010 Leah Culver, Joe Stump, Mark Paschal, Vic Fryzel Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import oauth2 import smtplib import base64 class SMTP(smtplib.SMTP): """SMTP wrapper for smtplib.SMTP that implements XOAUTH.""" def authenticate(self, url, consumer, token): if consumer is not None and not isinstance(consumer, oauth2.Consumer): raise ValueError("Invalid consumer.") if token is not None and not isinstance(token, oauth2.Token): raise ValueError("Invalid token.") self.docmd('AUTH', 'XOAUTH %s' % \ base64.b64encode(oauth2.build_xoauth_string(url, consumer, token)))
mit
waynecoulson/TV-Show-Downloader
lib/hachoir_parser/audio/real_audio.py
90
3782
""" RealAudio (.ra) parser Author: Mike Melanson References: http://wiki.multimedia.cx/index.php?title=RealMedia Samples: http://samples.mplayerhq.hu/real/RA/ """ from lib.hachoir_parser import Parser from lib.hachoir_core.field import (FieldSet, UInt8, UInt16, UInt32, Bytes, RawBytes, String, PascalString8) from lib.hachoir_core.tools import humanFrequency from lib.hachoir_core.text_handler import displayHandler from lib.hachoir_core.endian import BIG_ENDIAN class Metadata(FieldSet): def createFields(self): yield PascalString8(self, "title", charset="ISO-8859-1") yield PascalString8(self, "author", charset="ISO-8859-1") yield PascalString8(self, "copyright", charset="ISO-8859-1") yield PascalString8(self, "comment", charset="ISO-8859-1") class RealAudioFile(Parser): MAGIC = ".ra\xFD" PARSER_TAGS = { "id": "real_audio", "category": "audio", "file_ext": ["ra"], "mime": (u"audio/x-realaudio", u"audio/x-pn-realaudio"), "min_size": 6*8, "magic": ((MAGIC, 0),), "description": u"Real audio (.ra)", } endian = BIG_ENDIAN def validate(self): if self["signature"].value != self.MAGIC: return "Invalid signature" if self["version"].value not in (3, 4): return "Unknown version" return True def createFields(self): yield Bytes(self, "signature", 4, r"RealAudio identifier ('.ra\xFD')") yield UInt16(self, "version", "Version") if self["version"].value == 3: yield UInt16(self, "header_size", "Header size") yield RawBytes(self, "Unknown1", 10) yield UInt32(self, "data_size", "Data size") yield Metadata(self, "metadata") yield UInt8(self, "Unknown2") yield PascalString8(self, "FourCC") audio_size = self["data_size"].value else: # version = 4 yield UInt16(self, "reserved1", "Reserved, should be 0") yield String(self, "ra4sig", 4, "'.ra4' signature") yield UInt32(self, "filesize", "File size (minus 40 bytes)") yield UInt16(self, "version2", "Version 2 (always equal to version)") yield UInt32(self, "headersize", "Header size (minus 16)") yield UInt16(self, "codec_flavor", "Codec flavor") yield UInt32(self, "coded_frame_size", "Coded frame size") yield RawBytes(self, "unknown1", 12) yield UInt16(self, "subpacketh", "Subpacket h (?)") yield UInt16(self, "frame_size", "Frame size") yield UInt16(self, "sub_packet_size", "Subpacket size") yield UInt16(self, "unknown2", "Unknown") yield displayHandler(UInt16(self, "sample_rate", "Sample rate"), humanFrequency) yield UInt16(self, "unknown3", "Unknown") yield UInt16(self, "sample_size", "Sample size") yield UInt16(self, "channels", "Channels") yield PascalString8(self, "Interleaving ID String") yield PascalString8(self, "FourCC") yield RawBytes(self, "unknown4", 3) yield Metadata(self, "metadata") audio_size = (self["filesize"].value + 40) - (self["headersize"].value + 16) if 0 < audio_size: yield RawBytes(self, "audio_data", audio_size) def createDescription(self): if (self["version"].value == 3): return "RealAudio v3 file, '%s' codec" % self["FourCC"].value elif (self["version"].value == 4): return "RealAudio v4 file, '%s' codec, %s, %u channels" % ( self["FourCC"].value, self["sample_rate"].display, self["channels"].value) else: return "Real audio"
gpl-3.0
cybercomgroup/Big_Data
Cloudera/Code/SVM/titanic_data_prediction.py
1
1881
import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn import svm train_set = pd.read_csv('../Titanic_Dataset/train.csv') test_set = pd.read_csv('../Titanic_Dataset/test.csv') ###Data preparation train_set["Embarked"].replace("S", "0", True) train_set["Embarked"].replace("C", "1", True) train_set["Embarked"].replace("Q", "2", True) train_set["Sex"].replace("male", "0", True) train_set["Sex"].replace("female", "1", True) del train_set["Name"] del train_set["Cabin"] del train_set["Ticket"] del train_set["PassengerId"] train_set.fillna(0, None, None, True) titanic_results = train_set["Survived"] del train_set["Survived"] ###End data preparation ##Selftest machine=svm.SVC() machine.fit(train_set.values, titanic_results.values) predicted_survival=machine.predict(train_set.values) predictionSuccess=(1-np.mean(predicted_survival != titanic_results.values))*100 print("Test against training set(self test): "+str(predictionSuccess)+"% correctness") ###End selftest ###Predict survival of test.csv test_set["Embarked"].replace("S", "0", True) test_set["Embarked"].replace("C", "1", True) test_set["Embarked"].replace("Q", "2", True) test_set["Sex"].replace("male", "0", True) test_set["Sex"].replace("female", "1", True) del test_set["Name"] del test_set["Cabin"] del test_set["Ticket"] del test_set["PassengerId"] test_set.fillna(0, None, None, True) #print(test_set.values) test_prediction=machine.predict(test_set) #print("Test aganst test set: "+str(test_prediction)) untouchedTest = pd.read_csv('../Titanic_Dataset/test.csv') untouchedTest=untouchedTest["PassengerId"] untouchedTest.columns=["PassengerId"] predictionDF=pd.DataFrame(test_prediction, np.arange(len(test_prediction)),columns=["Survived"]) joinedDF=pd.concat([untouchedTest,predictionDF], axis=1) joinedDF.to_csv("predicted.csv",index=False) ###End Predict
gpl-3.0
systers/mailman
src/mailman/rules/any.py
7
1224
# Copyright (C) 2007-2015 by the Free Software Foundation, Inc. # # This file is part of GNU Mailman. # # GNU Mailman 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. # # GNU Mailman 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 Mailman. If not, see <http://www.gnu.org/licenses/>. """Check if any previous rules have matched.""" __all__ = [ 'Any', ] from mailman.core.i18n import _ from mailman.interfaces.rules import IRule from zope.interface import implementer @implementer(IRule) class Any: """Look for any previous rule match.""" name = 'any' description = _('Look for any previous rule hit.') record = False def check(self, mlist, msg, msgdata): """See `IRule`.""" return len(msgdata.get('rule_hits', [])) > 0
gpl-3.0
skbkontur/Diamond
src/collectors/puppetagent/puppetagent.py
57
1534
# coding=utf-8 """ Collect stats from puppet agent's last_run_summary.yaml #### Dependencies * yaml """ try: import yaml except ImportError: yaml = None import diamond.collector class PuppetAgentCollector(diamond.collector.Collector): def get_default_config_help(self): config_help = super(PuppetAgentCollector, self).get_default_config_help() config_help.update({ 'yaml_path': "Path to last_run_summary.yaml", }) return config_help def get_default_config(self): """ Returns the default collector settings """ config = super(PuppetAgentCollector, self).get_default_config() config.update({ 'yaml_path': '/var/lib/puppet/state/last_run_summary.yaml', 'path': 'puppetagent', }) return config def _get_summary(self): summary_fp = open(self.config['yaml_path'], 'r') try: summary = yaml.load(summary_fp) finally: summary_fp.close() return summary def collect(self): if yaml is None: self.log.error('Unable to import yaml') return summary = self._get_summary() for sect, data in summary.iteritems(): for stat, value in data.iteritems(): if value is None or isinstance(value, basestring): continue metric = '.'.join([sect, stat]) self.publish(metric, value)
mit
heke123/chromium-crosswalk
third_party/WebKit/LayoutTests/http/tests/websocket/cookie-flood_wsh.py
37
1924
# Copyright (C) 2013 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. from mod_pywebsocket import msgutil def web_socket_do_extra_handshake(request): # Exact number of headers that will fit in 256KB. Above 256KB an # ERR_RESPONSE_HEADERS_TOO_BIG error is triggered instead. for i in xrange(5978): request.extra_headers.append( ('Set-Cookie', 'WK-websocket-test-flood-%d=1' % i)) def web_socket_transfer_data(request): pass
bsd-3-clause
synth3tk/the-blue-alliance
controllers/suggestions/suggest_team_media_controller.py
1
2019
import os from google.appengine.ext import ndb from controllers.base_controller import LoggedInHandler from helpers.media_helper import MediaHelper, MediaParser from helpers.suggestions.suggestion_creator import SuggestionCreator from models.media import Media from models.team import Team from template_engine import jinja2_engine class SuggestTeamMediaController(LoggedInHandler): """ Allow users to suggest media for TBA to add to teams. """ def get(self): team_key = self.request.get("team_key") year_str = self.request.get("year") self._require_login("/suggest/team/media?team_key=%s&year=%s" % (team_key, year_str)) if not team_key or not year_str: self.redirect("/", abort=True) year = int(year_str) team_future = Team.get_by_id_async(self.request.get("team_key")) team = team_future.get_result() media_key_futures = Media.query(Media.references == team.key, Media.year == year).fetch_async(500, keys_only=True) media_futures = ndb.get_multi_async(media_key_futures.get_result()) medias_by_slugname = MediaHelper.group_by_slugname([media_future.get_result() for media_future in media_futures]) self.template_values.update({ "status": self.request.get("status"), "team": team, "year": year, "medias_by_slugname": medias_by_slugname }) self.response.out.write(jinja2_engine.render('suggest_team_media.html', self.template_values)) def post(self): self._require_login() team_key = self.request.get("team_key") year_str = self.request.get("year") status = SuggestionCreator.createTeamMediaSuggestion( author_account_key=self.user_bundle.account.key, media_url=self.request.get("media_url"), team_key=team_key, year_str=year_str) self.redirect('/suggest/team/media?team_key=%s&year=%s&status=%s' % (team_key, year_str, status))
mit
zomux/deepy
deepy/tensor/theano_imports.py
2
32100
# This file is automatically created, never edit it directly. from wrapper import deepy_tensor, deepy_nnet def all(*args, **kwargs): return deepy_tensor.all(*args, **kwargs) def gt(*args, **kwargs): return deepy_tensor.gt(*args, **kwargs) def partial(*args, **kwargs): return deepy_tensor.partial(*args, **kwargs) def dcols(*args, **kwargs): return deepy_tensor.dcols(*args, **kwargs) def as_tensor(*args, **kwargs): return deepy_tensor.as_tensor(*args, **kwargs) def ge(*args, **kwargs): return deepy_tensor.ge(*args, **kwargs) def set_subtensor(*args, **kwargs): return deepy_tensor.set_subtensor(*args, **kwargs) def ptp(*args, **kwargs): return deepy_tensor.ptp(*args, **kwargs) def mod_check(*args, **kwargs): return deepy_tensor.mod_check(*args, **kwargs) def pprint(*args, **kwargs): return deepy_tensor.pprint(*args, **kwargs) def makeKeepDims(*args, **kwargs): return deepy_tensor.makeKeepDims(*args, **kwargs) def tensor3s(*args, **kwargs): return deepy_tensor.tensor3s(*args, **kwargs) def discrete_dtypes(*args, **kwargs): return deepy_tensor.discrete_dtypes(*args, **kwargs) def division(*args, **kwargs): return deepy_tensor.division(*args, **kwargs) def matrices(*args, **kwargs): return deepy_tensor.matrices(*args, **kwargs) def tri(*args, **kwargs): return deepy_tensor.tri(*args, **kwargs) def scalar(*args, **kwargs): return deepy_tensor.scalar(*args, **kwargs) def vector(*args, **kwargs): return deepy_tensor.vector(*args, **kwargs) def ccol(*args, **kwargs): return deepy_tensor.ccol(*args, **kwargs) def round(*args, **kwargs): return deepy_tensor.round(*args, **kwargs) def crow(*args, **kwargs): return deepy_tensor.crow(*args, **kwargs) def lscalar(*args, **kwargs): return deepy_tensor.lscalar(*args, **kwargs) def second(*args, **kwargs): return deepy_tensor.second(*args, **kwargs) def xor(*args, **kwargs): return deepy_tensor.xor(*args, **kwargs) def sub(*args, **kwargs): return deepy_tensor.sub(*args, **kwargs) def diag(*args, **kwargs): return deepy_tensor.diag(*args, **kwargs) def sum(*args, **kwargs): return deepy_tensor.sum(*args, **kwargs) def dcol(*args, **kwargs): return deepy_tensor.dcol(*args, **kwargs) def row(*args, **kwargs): return deepy_tensor.row(*args, **kwargs) def neq(*args, **kwargs): return deepy_tensor.neq(*args, **kwargs) def btensor5(*args, **kwargs): return deepy_tensor.btensor5(*args, **kwargs) def btensor4(*args, **kwargs): return deepy_tensor.btensor4(*args, **kwargs) def btensor3(*args, **kwargs): return deepy_tensor.btensor3(*args, **kwargs) def fmatrices(*args, **kwargs): return deepy_tensor.fmatrices(*args, **kwargs) def values_eq_approx_always_true(*args, **kwargs): return deepy_tensor.values_eq_approx_always_true(*args, **kwargs) def sinh(*args, **kwargs): return deepy_tensor.sinh(*args, **kwargs) def trunc(*args, **kwargs): return deepy_tensor.trunc(*args, **kwargs) def constant_cache(*args, **kwargs): return deepy_tensor.constant_cache(*args, **kwargs) def vectors(*args, **kwargs): return deepy_tensor.vectors(*args, **kwargs) def and_(*args, **kwargs): return deepy_tensor.and_(*args, **kwargs) def bitwise_and(*args, **kwargs): return deepy_tensor.bitwise_and(*args, **kwargs) def divmod(*args, **kwargs): return deepy_tensor.divmod(*args, **kwargs) def sgn(*args, **kwargs): return deepy_tensor.sgn(*args, **kwargs) def iround(*args, **kwargs): return deepy_tensor.iround(*args, **kwargs) def deg2rad(*args, **kwargs): return deepy_tensor.deg2rad(*args, **kwargs) def eye(*args, **kwargs): return deepy_tensor.eye(*args, **kwargs) def dtensor5s(*args, **kwargs): return deepy_tensor.dtensor5s(*args, **kwargs) def as_index_variable(*args, **kwargs): return deepy_tensor.as_index_variable(*args, **kwargs) def frow(*args, **kwargs): return deepy_tensor.frow(*args, **kwargs) def tensor_from_scalar(*args, **kwargs): return deepy_tensor.tensor_from_scalar(*args, **kwargs) def sort(*args, **kwargs): return deepy_tensor.sort(*args, **kwargs) def zeros_like(*args, **kwargs): return deepy_tensor.zeros_like(*args, **kwargs) def float64_atol(*args, **kwargs): return deepy_tensor.float64_atol(*args, **kwargs) def drows(*args, **kwargs): return deepy_tensor.drows(*args, **kwargs) def dvectors(*args, **kwargs): return deepy_tensor.dvectors(*args, **kwargs) def ftensor5(*args, **kwargs): return deepy_tensor.ftensor5(*args, **kwargs) def ftensor4(*args, **kwargs): return deepy_tensor.ftensor4(*args, **kwargs) def logging(*args, **kwargs): return deepy_tensor.logging(*args, **kwargs) def ctensor5(*args, **kwargs): return deepy_tensor.ctensor5(*args, **kwargs) def join(*args, **kwargs): return deepy_tensor.join(*args, **kwargs) def erfinv(*args, **kwargs): return deepy_tensor.erfinv(*args, **kwargs) def erf(*args, **kwargs): return deepy_tensor.erf(*args, **kwargs) def printing(*args, **kwargs): return deepy_tensor.printing(*args, **kwargs) def advanced_inc_subtensor(*args, **kwargs): return deepy_tensor.advanced_inc_subtensor(*args, **kwargs) def ltensor4s(*args, **kwargs): return deepy_tensor.ltensor4s(*args, **kwargs) def complex_from_polar(*args, **kwargs): return deepy_tensor.complex_from_polar(*args, **kwargs) def scal(*args, **kwargs): return deepy_tensor.scal(*args, **kwargs) def minimum(*args, **kwargs): return deepy_tensor.minimum(*args, **kwargs) def numbers(*args, **kwargs): return deepy_tensor.numbers(*args, **kwargs) def tan(*args, **kwargs): return deepy_tensor.tan(*args, **kwargs) def ftensor4s(*args, **kwargs): return deepy_tensor.ftensor4s(*args, **kwargs) def iscalar(*args, **kwargs): return deepy_tensor.iscalar(*args, **kwargs) def imatrix(*args, **kwargs): return deepy_tensor.imatrix(*args, **kwargs) def tile(*args, **kwargs): return deepy_tensor.tile(*args, **kwargs) def erfc(*args, **kwargs): return deepy_tensor.erfc(*args, **kwargs) def config(*args, **kwargs): return deepy_tensor.config(*args, **kwargs) def sin(*args, **kwargs): return deepy_tensor.sin(*args, **kwargs) def max(*args, **kwargs): return deepy_tensor.max(*args, **kwargs) def itensor4(*args, **kwargs): return deepy_tensor.itensor4(*args, **kwargs) def fscalars(*args, **kwargs): return deepy_tensor.fscalars(*args, **kwargs) def itensor5(*args, **kwargs): return deepy_tensor.itensor5(*args, **kwargs) def flatnonzero(*args, **kwargs): return deepy_tensor.flatnonzero(*args, **kwargs) def ltensor5(*args, **kwargs): return deepy_tensor.ltensor5(*args, **kwargs) def ltensor4(*args, **kwargs): return deepy_tensor.ltensor4(*args, **kwargs) def alloc(*args, **kwargs): return deepy_tensor.alloc(*args, **kwargs) def ltensor3(*args, **kwargs): return deepy_tensor.ltensor3(*args, **kwargs) def hashtype(*args, **kwargs): return deepy_tensor.hashtype(*args, **kwargs) def switch(*args, **kwargs): return deepy_tensor.switch(*args, **kwargs) def dvector(*args, **kwargs): return deepy_tensor.dvector(*args, **kwargs) def stacklists(*args, **kwargs): return deepy_tensor.stacklists(*args, **kwargs) def continuous_dtypes(*args, **kwargs): return deepy_tensor.continuous_dtypes(*args, **kwargs) def permute_row_elements(*args, **kwargs): return deepy_tensor.permute_row_elements(*args, **kwargs) def float_matrix_types(*args, **kwargs): return deepy_tensor.float_matrix_types(*args, **kwargs) def is_flat(*args, **kwargs): return deepy_tensor.is_flat(*args, **kwargs) def cols(*args, **kwargs): return deepy_tensor.cols(*args, **kwargs) def float_vector_types(*args, **kwargs): return deepy_tensor.float_vector_types(*args, **kwargs) def fvectors(*args, **kwargs): return deepy_tensor.fvectors(*args, **kwargs) def le(*args, **kwargs): return deepy_tensor.le(*args, **kwargs) def builtins(*args, **kwargs): return deepy_tensor.builtins(*args, **kwargs) def itensor4s(*args, **kwargs): return deepy_tensor.itensor4s(*args, **kwargs) def lt(*args, **kwargs): return deepy_tensor.lt(*args, **kwargs) def choose(*args, **kwargs): return deepy_tensor.choose(*args, **kwargs) def iscalars(*args, **kwargs): return deepy_tensor.iscalars(*args, **kwargs) def as_tensor_variable(*args, **kwargs): return deepy_tensor.as_tensor_variable(*args, **kwargs) def int_dtypes(*args, **kwargs): return deepy_tensor.int_dtypes(*args, **kwargs) def drow(*args, **kwargs): return deepy_tensor.drow(*args, **kwargs) def ftensor3s(*args, **kwargs): return deepy_tensor.ftensor3s(*args, **kwargs) def make_slice(*args, **kwargs): return deepy_tensor.make_slice(*args, **kwargs) def mean(*args, **kwargs): return deepy_tensor.mean(*args, **kwargs) def square(*args, **kwargs): return deepy_tensor.square(*args, **kwargs) def ogrid(*args, **kwargs): return deepy_tensor.ogrid(*args, **kwargs) def allclose(*args, **kwargs): return deepy_tensor.allclose(*args, **kwargs) def eq(*args, **kwargs): return deepy_tensor.eq(*args, **kwargs) def matrix(*args, **kwargs): return deepy_tensor.matrix(*args, **kwargs) def gof(*args, **kwargs): return deepy_tensor.gof(*args, **kwargs) def tensor_copy(*args, **kwargs): return deepy_tensor.tensor_copy(*args, **kwargs) def fscalar(*args, **kwargs): return deepy_tensor.fscalar(*args, **kwargs) def float_types(*args, **kwargs): return deepy_tensor.float_types(*args, **kwargs) def get_vector_length(*args, **kwargs): return deepy_tensor.get_vector_length(*args, **kwargs) def log2(*args, **kwargs): return deepy_tensor.log2(*args, **kwargs) def diagonal(*args, **kwargs): return deepy_tensor.diagonal(*args, **kwargs) def float32_atol(*args, **kwargs): return deepy_tensor.float32_atol(*args, **kwargs) def scalar_from_tensor(*args, **kwargs): return deepy_tensor.scalar_from_tensor(*args, **kwargs) def or_(*args, **kwargs): return deepy_tensor.or_(*args, **kwargs) def expm1(*args, **kwargs): return deepy_tensor.expm1(*args, **kwargs) def ctensor3(*args, **kwargs): return deepy_tensor.ctensor3(*args, **kwargs) def ctensor4(*args, **kwargs): return deepy_tensor.ctensor4(*args, **kwargs) def setdefault(*args, **kwargs): return deepy_tensor.setdefault(*args, **kwargs) def int_div(*args, **kwargs): return deepy_tensor.int_div(*args, **kwargs) def grad(*args, **kwargs): return deepy_tensor.grad(*args, **kwargs) def shape_padaxis(*args, **kwargs): return deepy_tensor.shape_padaxis(*args, **kwargs) def complex_vector_types(*args, **kwargs): return deepy_tensor.complex_vector_types(*args, **kwargs) def arccos(*args, **kwargs): return deepy_tensor.arccos(*args, **kwargs) def fcol(*args, **kwargs): return deepy_tensor.fcol(*args, **kwargs) def zmatrix(*args, **kwargs): return deepy_tensor.zmatrix(*args, **kwargs) def arctan2(*args, **kwargs): return deepy_tensor.arctan2(*args, **kwargs) def advanced_set_subtensor1(*args, **kwargs): return deepy_tensor.advanced_set_subtensor1(*args, **kwargs) def bscalar(*args, **kwargs): return deepy_tensor.bscalar(*args, **kwargs) def true_div(*args, **kwargs): return deepy_tensor.true_div(*args, **kwargs) def check_equal_numpy(*args, **kwargs): return deepy_tensor.check_equal_numpy(*args, **kwargs) def exp2(*args, **kwargs): return deepy_tensor.exp2(*args, **kwargs) def zeros(*args, **kwargs): return deepy_tensor.zeros(*args, **kwargs) def shape_padright(*args, **kwargs): return deepy_tensor.shape_padright(*args, **kwargs) def max_and_argmax(*args, **kwargs): return deepy_tensor.max_and_argmax(*args, **kwargs) def j1(*args, **kwargs): return deepy_tensor.j1(*args, **kwargs) def arctanh(*args, **kwargs): return deepy_tensor.arctanh(*args, **kwargs) def imatrices(*args, **kwargs): return deepy_tensor.imatrices(*args, **kwargs) def cosh(*args, **kwargs): return deepy_tensor.cosh(*args, **kwargs) def std(*args, **kwargs): return deepy_tensor.std(*args, **kwargs) def wvector(*args, **kwargs): return deepy_tensor.wvector(*args, **kwargs) def irow(*args, **kwargs): return deepy_tensor.irow(*args, **kwargs) def floor_div(*args, **kwargs): return deepy_tensor.floor_div(*args, **kwargs) def irows(*args, **kwargs): return deepy_tensor.irows(*args, **kwargs) def clip(*args, **kwargs): return deepy_tensor.clip(*args, **kwargs) def addbroadcast(*args, **kwargs): return deepy_tensor.addbroadcast(*args, **kwargs) def numpy_scalar(*args, **kwargs): return deepy_tensor.numpy_scalar(*args, **kwargs) def dmatrix(*args, **kwargs): return deepy_tensor.dmatrix(*args, **kwargs) def ceil_intdiv(*args, **kwargs): return deepy_tensor.ceil_intdiv(*args, **kwargs) def any(*args, **kwargs): return deepy_tensor.any(*args, **kwargs) def all_dtypes(*args, **kwargs): return deepy_tensor.all_dtypes(*args, **kwargs) def tensor5(*args, **kwargs): return deepy_tensor.tensor5(*args, **kwargs) def angle(*args, **kwargs): return deepy_tensor.angle(*args, **kwargs) def min(*args, **kwargs): return deepy_tensor.min(*args, **kwargs) def register_transfer(*args, **kwargs): return deepy_tensor.register_transfer(*args, **kwargs) def take(*args, **kwargs): return deepy_tensor.take(*args, **kwargs) def icols(*args, **kwargs): return deepy_tensor.icols(*args, **kwargs) def warnings(*args, **kwargs): return deepy_tensor.warnings(*args, **kwargs) def icol(*args, **kwargs): return deepy_tensor.icol(*args, **kwargs) def lscalars(*args, **kwargs): return deepy_tensor.lscalars(*args, **kwargs) def fvector(*args, **kwargs): return deepy_tensor.fvector(*args, **kwargs) def dtensor4s(*args, **kwargs): return deepy_tensor.dtensor4s(*args, **kwargs) def vertical_stack(*args, **kwargs): return deepy_tensor.vertical_stack(*args, **kwargs) def exp(*args, **kwargs): return deepy_tensor.exp(*args, **kwargs) def neg(*args, **kwargs): return deepy_tensor.neg(*args, **kwargs) def theano(*args, **kwargs): return deepy_tensor.theano(*args, **kwargs) def dot(*args, **kwargs): return deepy_tensor.dot(*args, **kwargs) def wcol(*args, **kwargs): return deepy_tensor.wcol(*args, **kwargs) def copy(*args, **kwargs): return deepy_tensor.copy(*args, **kwargs) def swapaxes(*args, **kwargs): return deepy_tensor.swapaxes(*args, **kwargs) def float16_rtol(*args, **kwargs): return deepy_tensor.float16_rtol(*args, **kwargs) def fmatrix(*args, **kwargs): return deepy_tensor.fmatrix(*args, **kwargs) def itensor3(*args, **kwargs): return deepy_tensor.itensor3(*args, **kwargs) def alloc_validate_shape(*args, **kwargs): return deepy_tensor.alloc_validate_shape(*args, **kwargs) def ceil(*args, **kwargs): return deepy_tensor.ceil(*args, **kwargs) def ones(*args, **kwargs): return deepy_tensor.ones(*args, **kwargs) def mul(*args, **kwargs): return deepy_tensor.mul(*args, **kwargs) def python_all(*args, **kwargs): return deepy_tensor.python_all(*args, **kwargs) def chi2sf(*args, **kwargs): return deepy_tensor.chi2sf(*args, **kwargs) def advanced_set_subtensor(*args, **kwargs): return deepy_tensor.advanced_set_subtensor(*args, **kwargs) def get_idx_list(*args, **kwargs): return deepy_tensor.get_idx_list(*args, **kwargs) def dtensor5(*args, **kwargs): return deepy_tensor.dtensor5(*args, **kwargs) def dtensor4(*args, **kwargs): return deepy_tensor.dtensor4(*args, **kwargs) def where(*args, **kwargs): return deepy_tensor.where(*args, **kwargs) def dtensor3(*args, **kwargs): return deepy_tensor.dtensor3(*args, **kwargs) def complex_dtypes(*args, **kwargs): return deepy_tensor.complex_dtypes(*args, **kwargs) def argmax(*args, **kwargs): return deepy_tensor.argmax(*args, **kwargs) def j0(*args, **kwargs): return deepy_tensor.j0(*args, **kwargs) def wrow(*args, **kwargs): return deepy_tensor.wrow(*args, **kwargs) def tensor4(*args, **kwargs): return deepy_tensor.tensor4(*args, **kwargs) def constant_or_value(*args, **kwargs): return deepy_tensor.constant_or_value(*args, **kwargs) def tensor3(*args, **kwargs): return deepy_tensor.tensor3(*args, **kwargs) def extract_constant(*args, **kwargs): return deepy_tensor.extract_constant(*args, **kwargs) def rad2deg(*args, **kwargs): return deepy_tensor.rad2deg(*args, **kwargs) def isnan(*args, **kwargs): return deepy_tensor.isnan(*args, **kwargs) def tensor(*args, **kwargs): return deepy_tensor.tensor(*args, **kwargs) def erfcx(*args, **kwargs): return deepy_tensor.erfcx(*args, **kwargs) def tensor5s(*args, **kwargs): return deepy_tensor.tensor5s(*args, **kwargs) def nonzero_values(*args, **kwargs): return deepy_tensor.nonzero_values(*args, **kwargs) def smallest(*args, **kwargs): return deepy_tensor.smallest(*args, **kwargs) def python_complex(*args, **kwargs): return deepy_tensor.python_complex(*args, **kwargs) def cmatrix(*args, **kwargs): return deepy_tensor.cmatrix(*args, **kwargs) def lvectors(*args, **kwargs): return deepy_tensor.lvectors(*args, **kwargs) def transpose(*args, **kwargs): return deepy_tensor.transpose(*args, **kwargs) def advanced_subtensor1(*args, **kwargs): return deepy_tensor.advanced_subtensor1(*args, **kwargs) def complex_scalar_types(*args, **kwargs): return deepy_tensor.complex_scalar_types(*args, **kwargs) def lvector(*args, **kwargs): return deepy_tensor.lvector(*args, **kwargs) def outer(*args, **kwargs): return deepy_tensor.outer(*args, **kwargs) def cos(*args, **kwargs): return deepy_tensor.cos(*args, **kwargs) def sparse_module_ref(*args, **kwargs): return deepy_tensor.sparse_module_ref(*args, **kwargs) def arccosh(*args, **kwargs): return deepy_tensor.arccosh(*args, **kwargs) def div_proxy(*args, **kwargs): return deepy_tensor.div_proxy(*args, **kwargs) def itensor5s(*args, **kwargs): return deepy_tensor.itensor5s(*args, **kwargs) def inplace_increment(*args, **kwargs): return deepy_tensor.inplace_increment(*args, **kwargs) def uint_dtypes(*args, **kwargs): return deepy_tensor.uint_dtypes(*args, **kwargs) def col(*args, **kwargs): return deepy_tensor.col(*args, **kwargs) def bmatrix(*args, **kwargs): return deepy_tensor.bmatrix(*args, **kwargs) def adv_index_broadcastable_pattern(*args, **kwargs): return deepy_tensor.adv_index_broadcastable_pattern(*args, **kwargs) def pow(*args, **kwargs): return deepy_tensor.pow(*args, **kwargs) def round_half_to_even(*args, **kwargs): return deepy_tensor.round_half_to_even(*args, **kwargs) def ztensor5(*args, **kwargs): return deepy_tensor.ztensor5(*args, **kwargs) def ztensor4(*args, **kwargs): return deepy_tensor.ztensor4(*args, **kwargs) def ztensor3(*args, **kwargs): return deepy_tensor.ztensor3(*args, **kwargs) def tensordot(*args, **kwargs): return deepy_tensor.tensordot(*args, **kwargs) def invert(*args, **kwargs): return deepy_tensor.invert(*args, **kwargs) def ltensor3s(*args, **kwargs): return deepy_tensor.ltensor3s(*args, **kwargs) def advanced_subtensor(*args, **kwargs): return deepy_tensor.advanced_subtensor(*args, **kwargs) def numpy(*args, **kwargs): return deepy_tensor.numpy(*args, **kwargs) def get_scalar_constant_value(*args, **kwargs): return deepy_tensor.get_scalar_constant_value(*args, **kwargs) def erfcinv(*args, **kwargs): return deepy_tensor.erfcinv(*args, **kwargs) def arcsin(*args, **kwargs): return deepy_tensor.arcsin(*args, **kwargs) def imag(*args, **kwargs): return deepy_tensor.imag(*args, **kwargs) def round_half_away_from_zero(*args, **kwargs): return deepy_tensor.round_half_away_from_zero(*args, **kwargs) def tanh(*args, **kwargs): return deepy_tensor.tanh(*args, **kwargs) def compile(*args, **kwargs): return deepy_tensor.compile(*args, **kwargs) def cast(*args, **kwargs): return deepy_tensor.cast(*args, **kwargs) def mgrid(*args, **kwargs): return deepy_tensor.mgrid(*args, **kwargs) def gamma(*args, **kwargs): return deepy_tensor.gamma(*args, **kwargs) def xrange(*args, **kwargs): return deepy_tensor.xrange(*args, **kwargs) def brow(*args, **kwargs): return deepy_tensor.brow(*args, **kwargs) def get_scalar_constant_value_elemwises(*args, **kwargs): return deepy_tensor.get_scalar_constant_value_elemwises(*args, **kwargs) def bvector(*args, **kwargs): return deepy_tensor.bvector(*args, **kwargs) def int_vector_types(*args, **kwargs): return deepy_tensor.int_vector_types(*args, **kwargs) def conj(*args, **kwargs): return deepy_tensor.conj(*args, **kwargs) def inc_subtensor(*args, **kwargs): return deepy_tensor.inc_subtensor(*args, **kwargs) def bitwise_xor(*args, **kwargs): return deepy_tensor.bitwise_xor(*args, **kwargs) def reshape(*args, **kwargs): return deepy_tensor.reshape(*args, **kwargs) def sqrt(*args, **kwargs): return deepy_tensor.sqrt(*args, **kwargs) def complex(*args, **kwargs): return deepy_tensor.complex(*args, **kwargs) def split(*args, **kwargs): return deepy_tensor.split(*args, **kwargs) def largest(*args, **kwargs): return deepy_tensor.largest(*args, **kwargs) def complex_types(*args, **kwargs): return deepy_tensor.complex_types(*args, **kwargs) def dedent(*args, **kwargs): return deepy_tensor.dedent(*args, **kwargs) def min_informative_str(*args, **kwargs): return deepy_tensor.min_informative_str(*args, **kwargs) def sys(*args, **kwargs): return deepy_tensor.sys(*args, **kwargs) def stack(*args, **kwargs): return deepy_tensor.stack(*args, **kwargs) def ivectors(*args, **kwargs): return deepy_tensor.ivectors(*args, **kwargs) def lcol(*args, **kwargs): return deepy_tensor.lcol(*args, **kwargs) def zcol(*args, **kwargs): return deepy_tensor.zcol(*args, **kwargs) def lrow(*args, **kwargs): return deepy_tensor.lrow(*args, **kwargs) def numpy_diagonal_return_view(*args, **kwargs): return deepy_tensor.numpy_diagonal_return_view(*args, **kwargs) def izip(*args, **kwargs): return deepy_tensor.izip(*args, **kwargs) def float64_rtol(*args, **kwargs): return deepy_tensor.float64_rtol(*args, **kwargs) def absolute_import(*args, **kwargs): return deepy_tensor.absolute_import(*args, **kwargs) def shape(*args, **kwargs): return deepy_tensor.shape(*args, **kwargs) def advanced_inc_subtensor1(*args, **kwargs): return deepy_tensor.advanced_inc_subtensor1(*args, **kwargs) def grad_undefined(*args, **kwargs): return deepy_tensor.grad_undefined(*args, **kwargs) def add(*args, **kwargs): return deepy_tensor.add(*args, **kwargs) def inverse_permutation(*args, **kwargs): return deepy_tensor.inverse_permutation(*args, **kwargs) def dscalar(*args, **kwargs): return deepy_tensor.dscalar(*args, **kwargs) def real(*args, **kwargs): return deepy_tensor.real(*args, **kwargs) def psi(*args, **kwargs): return deepy_tensor.psi(*args, **kwargs) def abs_(*args, **kwargs): return deepy_tensor.abs_(*args, **kwargs) def shape_padleft(*args, **kwargs): return deepy_tensor.shape_padleft(*args, **kwargs) def lcols(*args, **kwargs): return deepy_tensor.lcols(*args, **kwargs) def complex_matrix_types(*args, **kwargs): return deepy_tensor.complex_matrix_types(*args, **kwargs) def int_scalar_types(*args, **kwargs): return deepy_tensor.int_scalar_types(*args, **kwargs) def frows(*args, **kwargs): return deepy_tensor.frows(*args, **kwargs) def mod(*args, **kwargs): return deepy_tensor.mod(*args, **kwargs) def bitwise_not(*args, **kwargs): return deepy_tensor.bitwise_not(*args, **kwargs) def bitwise_or(*args, **kwargs): return deepy_tensor.bitwise_or(*args, **kwargs) def arange(*args, **kwargs): return deepy_tensor.arange(*args, **kwargs) def zrow(*args, **kwargs): return deepy_tensor.zrow(*args, **kwargs) def batched_tensordot(*args, **kwargs): return deepy_tensor.batched_tensordot(*args, **kwargs) def lrows(*args, **kwargs): return deepy_tensor.lrows(*args, **kwargs) def ivector(*args, **kwargs): return deepy_tensor.ivector(*args, **kwargs) def flatten(*args, **kwargs): return deepy_tensor.flatten(*args, **kwargs) def dtensor3s(*args, **kwargs): return deepy_tensor.dtensor3s(*args, **kwargs) def fcols(*args, **kwargs): return deepy_tensor.fcols(*args, **kwargs) def nonzero(*args, **kwargs): return deepy_tensor.nonzero(*args, **kwargs) def zscalar(*args, **kwargs): return deepy_tensor.zscalar(*args, **kwargs) def wscalar(*args, **kwargs): return deepy_tensor.wscalar(*args, **kwargs) def prod(*args, **kwargs): return deepy_tensor.prod(*args, **kwargs) def gammaln(*args, **kwargs): return deepy_tensor.gammaln(*args, **kwargs) def grad_not_implemented(*args, **kwargs): return deepy_tensor.grad_not_implemented(*args, **kwargs) def int_matrix_types(*args, **kwargs): return deepy_tensor.int_matrix_types(*args, **kwargs) def power(*args, **kwargs): return deepy_tensor.power(*args, **kwargs) def unbroadcast(*args, **kwargs): return deepy_tensor.unbroadcast(*args, **kwargs) def wmatrix(*args, **kwargs): return deepy_tensor.wmatrix(*args, **kwargs) def integer_dtypes(*args, **kwargs): return deepy_tensor.integer_dtypes(*args, **kwargs) def print_function(*args, **kwargs): return deepy_tensor.print_function(*args, **kwargs) def dscalars(*args, **kwargs): return deepy_tensor.dscalars(*args, **kwargs) def argsort(*args, **kwargs): return deepy_tensor.argsort(*args, **kwargs) def constructor(*args, **kwargs): return deepy_tensor.constructor(*args, **kwargs) def ones_like(*args, **kwargs): return deepy_tensor.ones_like(*args, **kwargs) def cscalar(*args, **kwargs): return deepy_tensor.cscalar(*args, **kwargs) def arcsinh(*args, **kwargs): return deepy_tensor.arcsinh(*args, **kwargs) def lmatrix(*args, **kwargs): return deepy_tensor.lmatrix(*args, **kwargs) def python_any(*args, **kwargs): return deepy_tensor.python_any(*args, **kwargs) def elemwise(*args, **kwargs): return deepy_tensor.elemwise(*args, **kwargs) def batched_dot(*args, **kwargs): return deepy_tensor.batched_dot(*args, **kwargs) def rows(*args, **kwargs): return deepy_tensor.rows(*args, **kwargs) def log(*args, **kwargs): return deepy_tensor.log(*args, **kwargs) def transfer(*args, **kwargs): return deepy_tensor.transfer(*args, **kwargs) def lmatrices(*args, **kwargs): return deepy_tensor.lmatrices(*args, **kwargs) def log10(*args, **kwargs): return deepy_tensor.log10(*args, **kwargs) def zvector(*args, **kwargs): return deepy_tensor.zvector(*args, **kwargs) def identity_like(*args, **kwargs): return deepy_tensor.identity_like(*args, **kwargs) def get_canonical_form_slice(*args, **kwargs): return deepy_tensor.get_canonical_form_slice(*args, **kwargs) def argmin(*args, **kwargs): return deepy_tensor.argmin(*args, **kwargs) def default(*args, **kwargs): return deepy_tensor.default(*args, **kwargs) def tensor4s(*args, **kwargs): return deepy_tensor.tensor4s(*args, **kwargs) def maximum(*args, **kwargs): return deepy_tensor.maximum(*args, **kwargs) def itensor3s(*args, **kwargs): return deepy_tensor.itensor3s(*args, **kwargs) def log1p(*args, **kwargs): return deepy_tensor.log1p(*args, **kwargs) def horizontal_stack(*args, **kwargs): return deepy_tensor.horizontal_stack(*args, **kwargs) def patternbroadcast(*args, **kwargs): return deepy_tensor.patternbroadcast(*args, **kwargs) def tril(*args, **kwargs): return deepy_tensor.tril(*args, **kwargs) def constant(*args, **kwargs): return deepy_tensor.constant(*args, **kwargs) def inv(*args, **kwargs): return deepy_tensor.inv(*args, **kwargs) def triu(*args, **kwargs): return deepy_tensor.triu(*args, **kwargs) def float16_atol(*args, **kwargs): return deepy_tensor.float16_atol(*args, **kwargs) def fill(*args, **kwargs): return deepy_tensor.fill(*args, **kwargs) def floor(*args, **kwargs): return deepy_tensor.floor(*args, **kwargs) def arctan(*args, **kwargs): return deepy_tensor.arctan(*args, **kwargs) def scalars(*args, **kwargs): return deepy_tensor.scalars(*args, **kwargs) def isclose(*args, **kwargs): return deepy_tensor.isclose(*args, **kwargs) def roll(*args, **kwargs): return deepy_tensor.roll(*args, **kwargs) def int_types(*args, **kwargs): return deepy_tensor.int_types(*args, **kwargs) def ltensor5s(*args, **kwargs): return deepy_tensor.ltensor5s(*args, **kwargs) def make_constant(*args, **kwargs): return deepy_tensor.make_constant(*args, **kwargs) def cvector(*args, **kwargs): return deepy_tensor.cvector(*args, **kwargs) def float_dtypes(*args, **kwargs): return deepy_tensor.float_dtypes(*args, **kwargs) def bcol(*args, **kwargs): return deepy_tensor.bcol(*args, **kwargs) def sqr(*args, **kwargs): return deepy_tensor.sqr(*args, **kwargs) def isinf(*args, **kwargs): return deepy_tensor.isinf(*args, **kwargs) def dmatrices(*args, **kwargs): return deepy_tensor.dmatrices(*args, **kwargs) def float_scalar_types(*args, **kwargs): return deepy_tensor.float_scalar_types(*args, **kwargs) def float32_rtol(*args, **kwargs): return deepy_tensor.float32_rtol(*args, **kwargs) def ftensor5s(*args, **kwargs): return deepy_tensor.ftensor5s(*args, **kwargs) def ftensor3(*args, **kwargs): return deepy_tensor.ftensor3(*args, **kwargs) def integer_types(*args, **kwargs): return deepy_tensor.integer_types(*args, **kwargs) def wtensor4(*args, **kwargs): return deepy_tensor.wtensor4(*args, **kwargs) def wtensor5(*args, **kwargs): return deepy_tensor.wtensor5(*args, **kwargs) def wtensor3(*args, **kwargs): return deepy_tensor.wtensor3(*args, **kwargs)
mit
michaeljohn32/odoomrp-wip
mrp_production_capacity/models/mrp.py
17
5937
# -*- coding: utf-8 -*- ############################################################################## # For copyright and license notices, see __openerp__.py file in root directory ############################################################################## from openerp import models, fields, api, exceptions, _ class MrpWorkcenter(models.Model): _inherit = 'mrp.workcenter' capacity_per_cycle = fields.Float( string='Capacity per Cycle Max.', help='Capacity per cycle maximum.') capacity_per_cycle_min = fields.Float( string='Capacity per Cycle Min.', help='Capacity per cycle minimum.') @api.constrains('capacity_per_cycle', 'capacity_per_cycle_min') def _check_max_min(self): if (self.capacity_per_cycle <= 0.0 or self.capacity_per_cycle_min <= 0.0): raise exceptions.Warning( _('Capacity per cycle must be positive.')) if self.capacity_per_cycle < self.capacity_per_cycle_min: raise exceptions.Warning( _('Maximum value must be greater than minimum.')) class MrpRoutingWorkcenter(models.Model): _inherit = 'mrp.routing.workcenter' limited_production_capacity = fields.Boolean() @api.constrains('limited_production_capacity') def _check_one_limited_workcenter_per_route(self): if len(self.routing_id.workcenter_lines.filtered( 'limited_production_capacity')) > 1: raise exceptions.Warning( _('Only one line must be defined as limited per routing.')) class MrpProduction(models.Model): _inherit = 'mrp.production' @api.one @api.depends('product_qty', 'routing_id') def _calc_capacity(self): limited_lines = self.routing_id.workcenter_lines.filtered( 'limited_production_capacity') self.capacity_min = limited_lines and min(limited_lines.mapped( 'workcenter_id.capacity_per_cycle_min')) self.capacity_max = limited_lines and max(limited_lines.mapped( 'workcenter_id.capacity_per_cycle')) self.show_split_button = (limited_lines and self.product_qty > self.capacity_max) show_split_button = fields.Boolean( 'Show split button', compute='_calc_capacity') capacity_min = fields.Float( 'Capacity min.', compute='_calc_capacity') capacity_max = fields.Float( 'Capacity max.', compute='_calc_capacity') @api.multi @api.onchange('product_qty', 'routing_id') def _onchange_product_qty_check_capacity(self): self.ensure_one() result = {} if not self.product_qty or not self.routing_id: return result gt_max = self.capacity_max and self.product_qty > self.capacity_max lt_min = self.capacity_min and self.product_qty < self.capacity_min if gt_max and lt_min: warning = { 'title': _('Warning!'), 'message': _('Product QTY < Capacity per cycle' ' minimum, and > Capacity per cycle' ' maximum. You must click the' ' "Split Quantity" button') } result['warning'] = warning elif lt_min: warning = { 'title': _('Warning!'), 'message': _('Product QTY < Capacity per cycle minimum.') } result['warning'] = warning elif gt_max: warning = { 'title': _('Warning!'), 'message': _('Product QTY > Capacity per cycle maximum.' ' You must click the "Split Quantity" button') } result['warning'] = warning return result @api.one @api.onchange('routing_id') def _onchange_routing_id(self): limited = self.routing_id.workcenter_lines.filtered( 'limited_production_capacity') if limited and limited.workcenter_id.capacity_per_cycle: self.product_qty = limited.workcenter_id.capacity_per_cycle @api.multi def button_split_quantity(self): self.ensure_one() context = self.env.context.copy() context['active_id'] = self.id context['active_ids'] = [self.id] context['active_model'] = 'mrp.production' return { 'name': _('Split production'), 'type': 'ir.actions.act_window', 'res_model': 'wiz.split.production', 'view_type': 'form', 'view_mode': 'form', 'target': 'new', 'context': context } @api.multi def action_confirm(self): if any(p.show_split_button for p in self): raise exceptions.Warning( _('Product QTY > Capacity per cycle maximum. You must' ' click the "Split Quantity" button')) return super(MrpProduction, self).action_confirm() class MrpProductionWorkcenterLine(models.Model): _inherit = 'mrp.production.workcenter.line' @api.multi @api.onchange('workcenter_id') def _onchange_workcenter_id_check_capacity(self): result = {} if self.production_id.product_qty and self.workcenter_id: capacity_max = self.workcenter_id.capacity_per_cycle capacity_min = self.workcenter_id.capacity_per_cycle_min gt_max = (capacity_max and self.production_id.product_qty > capacity_max) lt_min = (capacity_min and self.production_id.product_qty < capacity_min) if lt_min or gt_max: warning = { 'title': _('Warning!'), 'message': _('Product QTY < Capacity per cycle minimum, or' ' > Capacity per cycle maximum') } result['warning'] = warning return result
agpl-3.0
devendermishrajio/nova_test_latest
nova/image/s3.py
38
17754
# 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. """Proxy AMI-related calls from cloud controller to objectstore service.""" import base64 import binascii import os import shutil import tarfile import tempfile import boto.s3.connection import eventlet from lxml import etree from oslo_concurrency import processutils from oslo_config import cfg from oslo_log import log as logging from nova.api.ec2 import ec2utils import nova.cert.rpcapi from nova.compute import arch from nova import exception from nova.i18n import _, _LE, _LI from nova.image import glance from nova import utils LOG = logging.getLogger(__name__) s3_opts = [ cfg.StrOpt('image_decryption_dir', default='/tmp', help='Parent directory for tempdir used for image decryption'), cfg.StrOpt('s3_host', default='$my_ip', help='Hostname or IP for OpenStack to use when accessing ' 'the S3 api'), cfg.IntOpt('s3_port', default=3333, help='Port used when accessing the S3 api'), cfg.StrOpt('s3_access_key', default='notchecked', help='Access key to use for S3 server for images'), cfg.StrOpt('s3_secret_key', default='notchecked', help='Secret key to use for S3 server for images'), cfg.BoolOpt('s3_use_ssl', default=False, help='Whether to use SSL when talking to S3'), cfg.BoolOpt('s3_affix_tenant', default=False, help='Whether to affix the tenant id to the access key ' 'when downloading from S3'), ] CONF = cfg.CONF CONF.register_opts(s3_opts) CONF.import_opt('my_ip', 'nova.netconf') class S3ImageService(object): """Wraps an existing image service to support s3 based register.""" # translate our internal state to states valid by the EC2 API documentation image_state_map = {'downloading': 'pending', 'failed_download': 'failed', 'decrypting': 'pending', 'failed_decrypt': 'failed', 'untarring': 'pending', 'failed_untar': 'failed', 'uploading': 'pending', 'failed_upload': 'failed', 'available': 'available'} def __init__(self, service=None, *args, **kwargs): self.cert_rpcapi = nova.cert.rpcapi.CertAPI() self.service = service or glance.get_default_image_service() self.service.__init__(*args, **kwargs) def _translate_uuids_to_ids(self, context, images): return [self._translate_uuid_to_id(context, img) for img in images] def _translate_uuid_to_id(self, context, image): image_copy = image.copy() try: image_uuid = image_copy['id'] except KeyError: pass else: image_copy['id'] = ec2utils.glance_id_to_id(context, image_uuid) for prop in ['kernel_id', 'ramdisk_id']: try: image_uuid = image_copy['properties'][prop] except (KeyError, ValueError): pass else: image_id = ec2utils.glance_id_to_id(context, image_uuid) image_copy['properties'][prop] = image_id try: image_copy['properties']['image_state'] = self.image_state_map[ image['properties']['image_state']] except (KeyError, ValueError): pass return image_copy def _translate_id_to_uuid(self, context, image): image_copy = image.copy() try: image_id = image_copy['id'] except KeyError: pass else: image_copy['id'] = ec2utils.id_to_glance_id(context, image_id) for prop in ['kernel_id', 'ramdisk_id']: try: image_id = image_copy['properties'][prop] except (KeyError, ValueError): pass else: image_uuid = ec2utils.id_to_glance_id(context, image_id) image_copy['properties'][prop] = image_uuid return image_copy def create(self, context, metadata, data=None): """Create an image. metadata['properties'] should contain image_location. """ image = self._s3_create(context, metadata) return image def delete(self, context, image_id): image_uuid = ec2utils.id_to_glance_id(context, image_id) self.service.delete(context, image_uuid) def update(self, context, image_id, metadata, data=None): image_uuid = ec2utils.id_to_glance_id(context, image_id) metadata = self._translate_id_to_uuid(context, metadata) image = self.service.update(context, image_uuid, metadata, data) return self._translate_uuid_to_id(context, image) def detail(self, context, **kwargs): # NOTE(bcwaldon): sort asc to make sure we assign lower ids # to older images kwargs.setdefault('sort_dir', 'asc') images = self.service.detail(context, **kwargs) return self._translate_uuids_to_ids(context, images) def show(self, context, image_id): image_uuid = ec2utils.id_to_glance_id(context, image_id) image = self.service.show(context, image_uuid) return self._translate_uuid_to_id(context, image) @staticmethod def _conn(context): # NOTE(vish): access and secret keys for s3 server are not # checked in nova-objectstore access = CONF.s3_access_key if CONF.s3_affix_tenant: access = '%s:%s' % (access, context.project_id) secret = CONF.s3_secret_key calling = boto.s3.connection.OrdinaryCallingFormat() return boto.s3.connection.S3Connection(aws_access_key_id=access, aws_secret_access_key=secret, is_secure=CONF.s3_use_ssl, calling_format=calling, port=CONF.s3_port, host=CONF.s3_host) @staticmethod def _download_file(bucket, filename, local_dir): key = bucket.get_key(filename) local_filename = os.path.join(local_dir, os.path.basename(filename)) key.get_contents_to_filename(local_filename) return local_filename def _s3_parse_manifest(self, context, metadata, manifest): manifest = etree.fromstring(manifest) image_format = 'ami' try: kernel_id = manifest.find('machine_configuration/kernel_id').text if kernel_id == 'true': image_format = 'aki' kernel_id = None except Exception: kernel_id = None try: ramdisk_id = manifest.find('machine_configuration/ramdisk_id').text if ramdisk_id == 'true': image_format = 'ari' ramdisk_id = None except Exception: ramdisk_id = None try: guestarch = manifest.find( 'machine_configuration/architecture').text except Exception: guestarch = arch.X86_64 if not arch.is_valid(guestarch): raise exception.InvalidArchitectureName(arch=guestarch) # NOTE(yamahata): # EC2 ec2-budlne-image --block-device-mapping accepts # <virtual name>=<device name> where # virtual name = {ami, root, swap, ephemeral<N>} # where N is no negative integer # device name = the device name seen by guest kernel. # They are converted into # block_device_mapping/mapping/{virtual, device} # # Do NOT confuse this with ec2-register's block device mapping # argument. mappings = [] try: block_device_mapping = manifest.findall('machine_configuration/' 'block_device_mapping/' 'mapping') for bdm in block_device_mapping: mappings.append({'virtual': bdm.find('virtual').text, 'device': bdm.find('device').text}) except Exception: mappings = [] properties = metadata['properties'] properties['architecture'] = guestarch def _translate_dependent_image_id(image_key, image_id): image_uuid = ec2utils.ec2_id_to_glance_id(context, image_id) properties[image_key] = image_uuid if kernel_id: _translate_dependent_image_id('kernel_id', kernel_id) if ramdisk_id: _translate_dependent_image_id('ramdisk_id', ramdisk_id) if mappings: properties['mappings'] = mappings metadata.update({'disk_format': image_format, 'container_format': image_format, 'status': 'queued', 'is_public': False, 'properties': properties}) metadata['properties']['image_state'] = 'pending' # TODO(bcwaldon): right now, this removes user-defined ids. # We need to re-enable this. metadata.pop('id', None) image = self.service.create(context, metadata) # extract the new uuid and generate an int id to present back to user image_uuid = image['id'] image['id'] = ec2utils.glance_id_to_id(context, image_uuid) # return image_uuid so the caller can still make use of image_service return manifest, image, image_uuid def _s3_create(self, context, metadata): """Gets a manifest from s3 and makes an image.""" image_path = tempfile.mkdtemp(dir=CONF.image_decryption_dir) image_location = metadata['properties']['image_location'].lstrip('/') bucket_name = image_location.split('/')[0] manifest_path = image_location[len(bucket_name) + 1:] bucket = self._conn(context).get_bucket(bucket_name) key = bucket.get_key(manifest_path) manifest = key.get_contents_as_string() manifest, image, image_uuid = self._s3_parse_manifest(context, metadata, manifest) def delayed_create(): """This handles the fetching and decrypting of the part files.""" log_vars = {'image_location': image_location, 'image_path': image_path} def _update_image_state(context, image_uuid, image_state): metadata = {'properties': {'image_state': image_state}} self.service.update(context, image_uuid, metadata, purge_props=False) def _update_image_data(context, image_uuid, image_data): metadata = {} self.service.update(context, image_uuid, metadata, image_data, purge_props=False) try: _update_image_state(context, image_uuid, 'downloading') try: parts = [] elements = manifest.find('image').getiterator('filename') for fn_element in elements: part = self._download_file(bucket, fn_element.text, image_path) parts.append(part) # NOTE(vish): this may be suboptimal, should we use cat? enc_filename = os.path.join(image_path, 'image.encrypted') with open(enc_filename, 'w') as combined: for filename in parts: with open(filename) as part: shutil.copyfileobj(part, combined) except Exception: LOG.exception(_LE("Failed to download %(image_location)s " "to %(image_path)s"), log_vars) _update_image_state(context, image_uuid, 'failed_download') return _update_image_state(context, image_uuid, 'decrypting') try: hex_key = manifest.find('image/ec2_encrypted_key').text encrypted_key = binascii.a2b_hex(hex_key) hex_iv = manifest.find('image/ec2_encrypted_iv').text encrypted_iv = binascii.a2b_hex(hex_iv) dec_filename = os.path.join(image_path, 'image.tar.gz') self._decrypt_image(context, enc_filename, encrypted_key, encrypted_iv, dec_filename) except Exception: LOG.exception(_LE("Failed to decrypt %(image_location)s " "to %(image_path)s"), log_vars) _update_image_state(context, image_uuid, 'failed_decrypt') return _update_image_state(context, image_uuid, 'untarring') try: unz_filename = self._untarzip_image(image_path, dec_filename) except Exception: LOG.exception(_LE("Failed to untar %(image_location)s " "to %(image_path)s"), log_vars) _update_image_state(context, image_uuid, 'failed_untar') return _update_image_state(context, image_uuid, 'uploading') try: with open(unz_filename) as image_file: _update_image_data(context, image_uuid, image_file) except Exception: LOG.exception(_LE("Failed to upload %(image_location)s " "to %(image_path)s"), log_vars) _update_image_state(context, image_uuid, 'failed_upload') return metadata = {'status': 'active', 'properties': {'image_state': 'available'}} self.service.update(context, image_uuid, metadata, purge_props=False) shutil.rmtree(image_path) except exception.ImageNotFound: LOG.info(_LI("Image %s was deleted underneath us"), image_uuid) return eventlet.spawn_n(delayed_create) return image def _decrypt_image(self, context, encrypted_filename, encrypted_key, encrypted_iv, decrypted_filename): elevated = context.elevated() try: key = self.cert_rpcapi.decrypt_text(elevated, project_id=context.project_id, text=base64.b64encode(encrypted_key)) except Exception as exc: msg = _('Failed to decrypt private key: %s') % exc raise exception.NovaException(msg) try: iv = self.cert_rpcapi.decrypt_text(elevated, project_id=context.project_id, text=base64.b64encode(encrypted_iv)) except Exception as exc: raise exception.NovaException(_('Failed to decrypt initialization ' 'vector: %s') % exc) try: utils.execute('openssl', 'enc', '-d', '-aes-128-cbc', '-in', '%s' % (encrypted_filename,), '-K', '%s' % (key,), '-iv', '%s' % (iv,), '-out', '%s' % (decrypted_filename,)) except processutils.ProcessExecutionError as exc: raise exception.NovaException(_('Failed to decrypt image file ' '%(image_file)s: %(err)s') % {'image_file': encrypted_filename, 'err': exc.stdout}) @staticmethod def _test_for_malicious_tarball(path, filename): """Raises exception if extracting tarball would escape extract path.""" tar_file = tarfile.open(filename, 'r|gz') for n in tar_file.getnames(): if not os.path.abspath(os.path.join(path, n)).startswith(path): tar_file.close() raise exception.NovaException(_('Unsafe filenames in image')) tar_file.close() @staticmethod def _untarzip_image(path, filename): S3ImageService._test_for_malicious_tarball(path, filename) tar_file = tarfile.open(filename, 'r|gz') tar_file.extractall(path) image_file = tar_file.getnames()[0] tar_file.close() return os.path.join(path, image_file)
apache-2.0
1yvT0s/scrapy
scrapy/dupefilters.py
116
2209
from __future__ import print_function import os import logging from scrapy.utils.job import job_dir from scrapy.utils.request import request_fingerprint class BaseDupeFilter(object): @classmethod def from_settings(cls, settings): return cls() def request_seen(self, request): return False def open(self): # can return deferred pass def close(self, reason): # can return a deferred pass def log(self, request, spider): # log that a request has been filtered pass class RFPDupeFilter(BaseDupeFilter): """Request Fingerprint duplicates filter""" def __init__(self, path=None, debug=False): self.file = None self.fingerprints = set() self.logdupes = True self.debug = debug self.logger = logging.getLogger(__name__) if path: self.file = open(os.path.join(path, 'requests.seen'), 'a+') self.file.seek(0) self.fingerprints.update(x.rstrip() for x in self.file) @classmethod def from_settings(cls, settings): debug = settings.getbool('DUPEFILTER_DEBUG') return cls(job_dir(settings), debug) def request_seen(self, request): fp = self.request_fingerprint(request) if fp in self.fingerprints: return True self.fingerprints.add(fp) if self.file: self.file.write(fp + os.linesep) def request_fingerprint(self, request): return request_fingerprint(request) def close(self, reason): if self.file: self.file.close() def log(self, request, spider): if self.debug: msg = "Filtered duplicate request: %(request)s" self.logger.debug(msg, {'request': request}, extra={'spider': spider}) elif self.logdupes: msg = ("Filtered duplicate request: %(request)s" " - no more duplicates will be shown" " (see DUPEFILTER_DEBUG to show all duplicates)") self.logger.debug(msg, {'request': request}, extra={'spider': spider}) self.logdupes = False spider.crawler.stats.inc_value('dupefilter/filtered', spider=spider)
bsd-3-clause
google-research/deeplab2
model/layers/blocks.py
1
7815
# coding=utf-8 # Copyright 2021 The Deeplab2 Authors. # # 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. """Implements building blocks for neural networks.""" from typing import Optional from absl import logging import tensorflow as tf from deeplab2.model import utils from deeplab2.model.layers import convolutions from deeplab2.model.layers import squeeze_and_excite backend = tf.keras.backend layers = tf.keras.layers class InvertedBottleneckBlock(tf.keras.layers.Layer): """An inverted bottleneck block. Reference: Sandler, M., Howard, A., et al. Mobilenetv2: Inverted residuals and linear bottlenecks. In CVPR, 2018 Howard, A., Sandler, M., et al. Searching for mobilenetv3. In ICCV, 2019 """ def __init__(self, in_filters: int, out_filters: int, expand_ratio: int, strides: int, kernel_size: int = 3, se_ratio: Optional[float] = None, activation: str = 'relu', se_inner_activation: str = 'relu', se_gating_activation: str = 'sigmoid', depthwise_activation: Optional[str] = None, expand_se_in_filters: bool = False, atrous_rate: int = 1, divisible_by: int = 1, bn_layer: layers.Layer = tf.keras.layers.BatchNormalization, conv_kernel_weight_decay: float = 0.0, regularize_depthwise: bool = False, use_depthwise: bool = True, use_residual: bool = True, name: Optional[str] = None): """Initializes an inverted bottleneck block with BN after convolutions. Args: in_filters: The number of filters of the input tensor. out_filters: The number of filters of the output tensor. expand_ratio: The expand_ratio for an inverted bottleneck block. If expand_ratio is <= 1, this argument will be ignored. strides: The number of stride. If greater than 1, this block will ultimately downsample the input. kernel_size: The kernel size of the depthwise conv layer. se_ratio: If not None, se ratio for the squeeze and excitation layer. activation: The name of the activation function. se_inner_activation: The name of squeeze-excitation inner activation. se_gating_activation: The name of squeeze-excitation gating activation. depthwise_activation: The name of the activation function for depthwise only. expand_se_in_filters: Whether or not to expand in_filter in squeeze and excitation layer. atrous_rate: The atrous dilation rate to use for. divisible_by: A number that all inner dimensions are divisible by. bn_layer: An optional tf.keras.layers.Layer that computes the normalization (default: tf.keras.layers.BatchNormalization). conv_kernel_weight_decay: The weight decay for convolution kernels. regularize_depthwise: Whether or not apply regularization on depthwise. use_depthwise: Whether to uses standard convolutions instead of depthwise. use_residual: Whether to include residual connection between input and output. name: Name for the block. """ super(InvertedBottleneckBlock, self).__init__(name=name) self._in_filters = in_filters self._out_filters = out_filters self._expand_ratio = expand_ratio self._strides = strides self._kernel_size = kernel_size self._se_ratio = se_ratio self._divisible_by = divisible_by self._atrous_rate = atrous_rate self._regularize_depthwise = regularize_depthwise self._use_depthwise = use_depthwise self._use_residual = use_residual self._activation = activation self._se_inner_activation = se_inner_activation self._se_gating_activation = se_gating_activation self._depthwise_activation = depthwise_activation self._expand_se_in_filters = expand_se_in_filters if tf.keras.backend.image_data_format() == 'channels_last': self._bn_axis = -1 else: self._bn_axis = 1 if depthwise_activation is None: self._depthwise_activation = activation if regularize_depthwise: depthwise_kernel_weight_decay = conv_kernel_weight_decay else: depthwise_kernel_weight_decay = 0.0 if self._expand_ratio <= 1 and not self._use_depthwise: raise ValueError( 'Undefined behavior if expand_ratio <= 1 and not use_depthwise') expand_filters = self._in_filters if self._expand_ratio > 1: # First 1x1 conv for channel expansion. expand_filters = utils.make_divisible( self._in_filters * self._expand_ratio, self._divisible_by) expand_kernel = 1 if self._use_depthwise else self._kernel_size expand_stride = 1 if self._use_depthwise else self._strides self._conv1_bn_act = convolutions.Conv2DSame( output_channels=expand_filters, kernel_size=expand_kernel, strides=expand_stride, atrous_rate=1, use_bias=False, use_bn=True, bn_layer=bn_layer, activation=self._activation, conv_kernel_weight_decay=conv_kernel_weight_decay, name='expand_conv') if self._use_depthwise: # Depthwise conv. self._conv2_bn_act = convolutions.DepthwiseConv2DSame( kernel_size=self._kernel_size, strides=self._strides, atrous_rate=self._atrous_rate, use_bias=False, use_bn=True, bn_layer=bn_layer, activation=self._depthwise_activation, name='depthwise_conv') # Squeeze and excitation. if self._se_ratio is not None and self._se_ratio > 0: if self._expand_se_in_filters: in_filters = expand_filters else: in_filters = self._in_filters self._squeeze_excitation = squeeze_and_excite.SqueezeAndExcite( in_filters=in_filters, out_filters=expand_filters, se_ratio=self._se_ratio, divisible_by=self._divisible_by, kernel_initializer='he_normal', kernel_regularizer=tf.keras.regularizers.l2(conv_kernel_weight_decay), activation=self._se_inner_activation, gating_activation=self._se_gating_activation, name=name + '_se') else: logging.info( 'Squeeze and Excitation is skipped due to undefined se_ratio') self._squeeze_excitation = None # Last 1x1 conv. self._conv3_bn = convolutions.Conv2DSame( output_channels=self._out_filters, kernel_size=1, strides=1, atrous_rate=1, use_bias=False, use_bn=True, bn_layer=bn_layer, activation=None, conv_kernel_weight_decay=conv_kernel_weight_decay, name='project_conv') def call(self, inputs, training=None): shortcut = inputs if self._expand_ratio > 1: x = self._conv1_bn_act(inputs, training=training) else: x = inputs if self._use_depthwise: x = self._conv2_bn_act(x, training=training) if self._squeeze_excitation is not None: x = self._squeeze_excitation(x) x = self._conv3_bn(x, training=training) if (self._use_residual and self._in_filters == self._out_filters): x = tf.add(x, shortcut) return x
apache-2.0
ThiagoGarciaAlves/erpnext
erpnext/accounts/report/item_wise_purchase_register/item_wise_purchase_register.py
44
4811
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe import _ from frappe.utils import flt def execute(filters=None): if not filters: filters = {} columns = get_columns() last_col = len(columns) item_list = get_items(filters) aii_account_map = get_aii_accounts() if item_list: item_tax, tax_accounts = get_tax_accounts(item_list, columns) data = [] for d in item_list: purchase_receipt = None if d.purchase_receipt: purchase_receipt = d.purchase_receipt elif d.po_detail: purchase_receipt = ", ".join(frappe.db.sql_list("""select distinct parent from `tabPurchase Receipt Item` where docstatus=1 and prevdoc_detail_docname=%s""", d.po_detail)) expense_account = d.expense_account or aii_account_map.get(d.company) row = [d.item_code, d.item_name, d.item_group, d.parent, d.posting_date, d.supplier, d.supplier_name, d.credit_to, d.project_name, d.company, d.purchase_order, purchase_receipt, expense_account, d.qty, d.base_net_rate, d.base_net_amount] for tax in tax_accounts: row.append(item_tax.get(d.parent, {}).get(d.item_code, {}).get(tax, 0)) total_tax = sum(row[last_col:]) row += [total_tax, d.base_net_amount + total_tax] data.append(row) return columns, data def get_columns(): return [_("Item Code") + ":Link/Item:120", _("Item Name") + "::120", _("Item Group") + ":Link/Item Group:100", _("Invoice") + ":Link/Purchase Invoice:120", _("Posting Date") + ":Date:80", _("Supplier") + ":Link/Supplier:120", "Supplier Name::120", "Payable Account:Link/Account:120", _("Project") + ":Link/Project:80", _("Company") + ":Link/Company:100", _("Purchase Order") + ":Link/Purchase Order:100", _("Purchase Receipt") + ":Link/Purchase Receipt:100", _("Expense Account") + ":Link/Account:140", _("Qty") + ":Float:120", _("Rate") + ":Currency:120", _("Amount") + ":Currency:120"] def get_conditions(filters): conditions = "" for opts in (("company", " and company=%(company)s"), ("supplier", " and pi.supplier = %(supplier)s"), ("item_code", " and pi_item.item_code = %(item_code)s"), ("from_date", " and pi.posting_date>=%(from_date)s"), ("to_date", " and pi.posting_date<=%(to_date)s")): if filters.get(opts[0]): conditions += opts[1] return conditions def get_items(filters): conditions = get_conditions(filters) match_conditions = frappe.build_match_conditions("Purchase Invoice") return frappe.db.sql("""select pi_item.parent, pi.posting_date, pi.credit_to, pi.company, pi.supplier, pi.remarks, pi.base_net_total, pi_item.item_code, pi_item.item_name, pi_item.item_group, pi_item.project_name, pi_item.purchase_order, pi_item.purchase_receipt, pi_item.po_detail, pi_item.expense_account, pi_item.qty, pi_item.base_net_rate, pi_item.base_net_amount, pi.supplier_name from `tabPurchase Invoice` pi, `tabPurchase Invoice Item` pi_item where pi.name = pi_item.parent and pi.docstatus = 1 %s %s order by pi.posting_date desc, pi_item.item_code desc""" % (conditions, match_conditions), filters, as_dict=1) def get_aii_accounts(): return dict(frappe.db.sql("select name, stock_received_but_not_billed from tabCompany")) def get_tax_accounts(item_list, columns): import json item_tax = {} tax_accounts = [] invoice_wise_items = {} for d in item_list: invoice_wise_items.setdefault(d.parent, []).append(d) tax_details = frappe.db.sql("""select parent, account_head, item_wise_tax_detail, charge_type, base_tax_amount_after_discount_amount from `tabPurchase Taxes and Charges` where parenttype = 'Purchase Invoice' and docstatus = 1 and ifnull(account_head, '') != '' and category in ('Total', 'Valuation and Total') and parent in (%s)""" % ', '.join(['%s']*len(invoice_wise_items)), tuple(invoice_wise_items.keys())) for parent, account_head, item_wise_tax_detail, charge_type, tax_amount in tax_details: if account_head not in tax_accounts: tax_accounts.append(account_head) if item_wise_tax_detail: try: item_wise_tax_detail = json.loads(item_wise_tax_detail) for item, tax_amount in item_wise_tax_detail.items(): item_tax.setdefault(parent, {}).setdefault(item, {})[account_head] = \ flt(tax_amount[1]) if isinstance(tax_amount, list) else flt(tax_amount) except ValueError: continue elif charge_type == "Actual" and tax_amount: for d in invoice_wise_items.get(parent, []): item_tax.setdefault(parent, {}).setdefault(d.item_code, {})[account_head] = \ (tax_amount * d.base_net_amount) / d.base_net_total tax_accounts.sort() columns += [account_head + ":Currency:80" for account_head in tax_accounts] columns += ["Total Tax:Currency:80", "Total:Currency:80"] return item_tax, tax_accounts
agpl-3.0
ohmini/thaifoodapi
lib/django/template/loader.py
66
6521
import warnings from django.utils import six from django.utils.deprecation import ( DeprecationInstanceCheck, RemovedInDjango20Warning, RemovedInDjango110Warning, ) from . import engines from .backends.django import DjangoTemplates from .base import Origin from .engine import ( _context_instance_undefined, _dictionary_undefined, _dirs_undefined, ) from .exceptions import TemplateDoesNotExist from .loaders import base def get_template(template_name, dirs=_dirs_undefined, using=None): """ Loads and returns a template for the given name. Raises TemplateDoesNotExist if no such template exists. """ chain = [] engines = _engine_list(using) for engine in engines: try: # This is required for deprecating the dirs argument. Simply # return engine.get_template(template_name) in Django 1.10. if isinstance(engine, DjangoTemplates): return engine.get_template(template_name, dirs) elif dirs is not _dirs_undefined: warnings.warn( "Skipping template backend %s because its get_template " "method doesn't support the dirs argument." % engine.name, stacklevel=2) else: return engine.get_template(template_name) except TemplateDoesNotExist as e: chain.append(e) raise TemplateDoesNotExist(template_name, chain=chain) def select_template(template_name_list, dirs=_dirs_undefined, using=None): """ Loads and returns a template for one of the given names. Tries names in order and returns the first template found. Raises TemplateDoesNotExist if no such template exists. """ chain = [] engines = _engine_list(using) for template_name in template_name_list: for engine in engines: try: # This is required for deprecating the dirs argument. Simply # use engine.get_template(template_name) in Django 1.10. if isinstance(engine, DjangoTemplates): return engine.get_template(template_name, dirs) elif dirs is not _dirs_undefined: warnings.warn( "Skipping template backend %s because its get_template " "method doesn't support the dirs argument." % engine.name, stacklevel=2) else: return engine.get_template(template_name) except TemplateDoesNotExist as e: chain.append(e) if template_name_list: raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain) else: raise TemplateDoesNotExist("No template names provided") def render_to_string(template_name, context=None, context_instance=_context_instance_undefined, dirs=_dirs_undefined, dictionary=_dictionary_undefined, request=None, using=None): """ Loads a template and renders it with a context. Returns a string. template_name may be a string or a list of strings. """ if (context_instance is _context_instance_undefined and dirs is _dirs_undefined and dictionary is _dictionary_undefined): # No deprecated arguments were passed - use the new code path if isinstance(template_name, (list, tuple)): template = select_template(template_name, using=using) else: template = get_template(template_name, using=using) return template.render(context, request) else: chain = [] # Some deprecated arguments were passed - use the legacy code path for engine in _engine_list(using): try: # This is required for deprecating properly arguments specific # to Django templates. Remove Engine.render_to_string() at the # same time as this code path in Django 1.10. if isinstance(engine, DjangoTemplates): if request is not None: raise ValueError( "render_to_string doesn't support the request argument " "when some deprecated arguments are passed.") # Hack -- use the internal Engine instance of DjangoTemplates. return engine.engine.render_to_string( template_name, context, context_instance, dirs, dictionary) elif context_instance is not _context_instance_undefined: warnings.warn( "Skipping template backend %s because its render_to_string " "method doesn't support the context_instance argument." % engine.name, stacklevel=2) elif dirs is not _dirs_undefined: warnings.warn( "Skipping template backend %s because its render_to_string " "method doesn't support the dirs argument." % engine.name, stacklevel=2) elif dictionary is not _dictionary_undefined: warnings.warn( "Skipping template backend %s because its render_to_string " "method doesn't support the dictionary argument." % engine.name, stacklevel=2) except TemplateDoesNotExist as e: chain.append(e) continue if template_name: if isinstance(template_name, (list, tuple)): template_name = ', '.join(template_name) raise TemplateDoesNotExist(template_name, chain=chain) else: raise TemplateDoesNotExist("No template names provided") def _engine_list(using=None): return engines.all() if using is None else [engines[using]] class BaseLoader(base.Loader): _accepts_engine_in_init = False def __init__(self, *args, **kwargs): warnings.warn( "django.template.loader.BaseLoader was superseded by " "django.template.loaders.base.Loader.", RemovedInDjango110Warning, stacklevel=2) super(BaseLoader, self).__init__(*args, **kwargs) class LoaderOrigin(six.with_metaclass(DeprecationInstanceCheck, Origin)): alternative = 'django.template.Origin' deprecation_warning = RemovedInDjango20Warning
bsd-3-clause
hexlism/xx_net
python27/1.0/lib/encodings/euc_kr.py
816
1027
# # euc_kr.py: Python Unicode Codec for EUC_KR # # Written by Hye-Shik Chang <perky@FreeBSD.org> # import _codecs_kr, codecs import _multibytecodec as mbc codec = _codecs_kr.getcodec('euc_kr') class Codec(codecs.Codec): encode = codec.encode decode = codec.decode class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): codec = codec class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): codec = codec class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): codec = codec class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): codec = codec def getregentry(): return codecs.CodecInfo( name='euc_kr', encode=Codec().encode, decode=Codec().decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamreader=StreamReader, streamwriter=StreamWriter, )
bsd-2-clause
luiseduardohdbackup/odoo
addons/google_account/__openerp__.py
312
1457
# -*- 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': 'Google Users', 'version': '1.0', 'category': 'Tools', 'description': """ The module adds google user in res user. ======================================== """, 'author': 'OpenERP SA', 'website': 'https://www.odoo.com', 'depends': ['base_setup'], 'data': [ 'google_account_data.xml', ], 'demo': [], 'installable': True, 'auto_install': False, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
addiks/gmattermost
src/Gtk/GtkStyleProviderToTextViewAdapter.py
1
6526
from copy import copy from gi.repository import Gtk # This component allows applying style-properties from (css-)style-providers to text-tag's. class GtkStyleProviderToTextViewAdapter: __styleProvider = None # Gtk.StyleProvider __attachedTextViews = [] # list(Gtk.TextView) __ignoreEvents = False # boolean def __init__(self, styleProvider): # Gtk.StyleProvider self.__styleProvider = styleProvider def attachTextView(self, textView): # Gtk.TextView if textView not in self.__attachedTextViews: self.__attachedTextViews.append(textView) # Gtk.TextBuffer textBuffer = textView.get_buffer() # Gtk.TagTable tagTable = textBuffer.get_tag_table() tagTable.connect('tag-added', self.__onTagAddedToTagTable) tagTable.connect('tag-changed', self.__onTagChangedInTagTable) tagTable.connect('tag-removed', self.__onTagRemovedFromTagTable) tagTable.foreach(self.__updateTextTag, textView) def __updateTextTag(self, textTag, textView): # Gtk.TextTag, Gtk.TextView # Gtk.StyleProvider styleProvider = self.__styleProvider # Gtk.WidgetPath widgetPath = self.__buildWidgetPathForTextTag(textTag, textView) styleContext = Gtk.StyleContext() styleContext.set_path(widgetPath) styleContext.add_provider(styleProvider, 800) #styleContext.invalidate() # Deprecated (?) self.__ignoreEvents = True textTag.set_property("left-margin-set", True) textTag.set_property("indent-set", True) self.__ignoreEvents = False for prop in textTag.list_properties(): # GParamString cssPropertyName = self.__mapTextTagPropertyNameToCSSName(prop.name) if cssPropertyName != None: cssPropertyValue = styleContext.get_property(cssPropertyName, styleContext.get_state()) if cssPropertyValue != None: self.__ignoreEvents = True textTag.set_property(prop.name, cssPropertyValue) self.__ignoreEvents = False def __onTagAddedToTagTable(self, tagTable, textTag, data=None): if not self.__ignoreEvents: for textView in self.__attachedTextViews: # Gtk.TextView # Gtk.TextBuffer textBuffer = textView.get_buffer() if textBuffer.get_tag_table() == tagTable: self.__updateTextTag(textTag, textView) def __onTagChangedInTagTable(self, tagTable, textTag, sizeChanged, data=None): if not self.__ignoreEvents: for textView in self.__attachedTextViews: # Gtk.TextView # Gtk.TextBuffer textBuffer = textView.get_buffer() if textBuffer.get_tag_table() == tagTable: self.__updateTextTag(textTag, textView) def __onTagRemovedFromTagTable(self, tagTable, textTag, data=None): if not self.__ignoreEvents: pass def __buildWidgetPathForTextTag(self, textTag, textView): # Gtk.TextTag, Gtk.TextView # Gtk.WidgetPath widgetPath = textView.get_path().copy() textTagPos = widgetPath.append_type(Gtk.TextTag) tagName = textTag.get_property('name') tagClasses = tagName.split("_") widgetPath.iter_set_name(textTagPos, tagName) for className in tagClasses: widgetPath.iter_add_class(textTagPos, className) return widgetPath def __mapTextTagPropertyNameToCSSName(self, name): result = None nameMap = { # 'accumulative-margin': None, # 'background': None, # 'background-full-height': None, # 'background-full-height-set': None, # 'background-gdk': None, # 'background-rgba': None, # 'background-set': None, # 'direction': None, # 'editable': None, # 'editable-set': None, # 'fallback': None, # 'fallback-set': None, # 'family': None, # 'family-set': None, # 'font': None, # 'font-desc': None, # 'font-features': None, # 'font-features-set': None, # 'foreground': None, # 'foreground-gdk': None, # 'foreground-rgba': None, # 'foreground-set': None, # 'indent': 'margin-left', # 'indent-set': None, # 'invisible': None, # 'invisible-set': None, # 'justification': None, # 'justification-set': None, # 'language': None, # 'language-set': None, 'left-margin': 'margin-left', # 'left-margin-set': None, # 'letter-spacing': None, # 'letter-spacing-set': None, # 'name': None, # 'paragraph-background': None, # 'paragraph-background-gdk': None, # 'paragraph-background-rgba': None, # 'paragraph-background-set': None, 'pixels-above-lines': 'margin-top', # 'pixels-above-lines-set': None, 'pixels-below-lines': 'margin-bottom', # 'pixels-below-lines-set': None, # 'pixels-inside-wrap': None, # 'pixels-inside-wrap-set': None, 'right-margin': 'margin-right', # 'right-margin-set': None, # 'rise': None, # 'rise-set': None, # 'scale': None, # 'scale-set': None, # 'size': 'font-size', 'size-points': 'font-size', # 'size-set': None, # 'stretch': None, # 'stretch-set': None, # 'strikethrough': None, # 'strikethrough-rgba': None, # 'strikethrough-rgba-set': None, # 'strikethrough-set': None, # 'style': None, # 'style-set': None, # 'tabs': None, # 'tabs-set': None, # 'underline': None, # 'underline-rgba': None, # 'underline-rgba-set': None, # 'underline-set': None, # 'variant': None, # 'variant-set': None, 'weight': 'font-weight', # 'weight-set': None, # 'wrap-mode': None, # 'wrap-mode-set': None } if name in nameMap: result = nameMap[name] return result
gpl-3.0
glovebx/odoo
openerp/modules/registry.py
220
19731
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## """ Models registries. """ from collections import Mapping, defaultdict import logging import os import threading import openerp from .. import SUPERUSER_ID from openerp.tools import assertion_report, lazy_property, classproperty, config from openerp.tools.lru import LRU _logger = logging.getLogger(__name__) class Registry(Mapping): """ Model registry for a particular database. The registry is essentially a mapping between model names and model instances. There is one registry instance per database. """ def __init__(self, db_name): super(Registry, self).__init__() self.models = {} # model name/model instance mapping self._sql_error = {} self._store_function = {} self._pure_function_fields = {} # {model: [field, ...], ...} self._init = True self._init_parent = {} self._assertion_report = assertion_report.assertion_report() self._fields_by_model = None # modules fully loaded (maintained during init phase by `loading` module) self._init_modules = set() self.db_name = db_name self._db = openerp.sql_db.db_connect(db_name) # special cursor for test mode; None means "normal" mode self.test_cr = None # Indicates that the registry is self.ready = False # Inter-process signaling (used only when openerp.multi_process is True): # The `base_registry_signaling` sequence indicates the whole registry # must be reloaded. # The `base_cache_signaling sequence` indicates all caches must be # invalidated (i.e. cleared). self.base_registry_signaling_sequence = None self.base_cache_signaling_sequence = None self.cache = LRU(8192) # Flag indicating if at least one model cache has been cleared. # Useful only in a multi-process context. self._any_cache_cleared = False cr = self.cursor() has_unaccent = openerp.modules.db.has_unaccent(cr) if openerp.tools.config['unaccent'] and not has_unaccent: _logger.warning("The option --unaccent was given but no unaccent() function was found in database.") self.has_unaccent = openerp.tools.config['unaccent'] and has_unaccent cr.close() # # Mapping abstract methods implementation # => mixin provides methods keys, items, values, get, __eq__, and __ne__ # def __len__(self): """ Return the size of the registry. """ return len(self.models) def __iter__(self): """ Return an iterator over all model names. """ return iter(self.models) def __getitem__(self, model_name): """ Return the model with the given name or raise KeyError if it doesn't exist.""" return self.models[model_name] def __call__(self, model_name): """ Same as ``self[model_name]``. """ return self.models[model_name] @lazy_property def pure_function_fields(self): """ Return the list of pure function fields (field objects) """ fields = [] for mname, fnames in self._pure_function_fields.iteritems(): model_fields = self[mname]._fields for fname in fnames: fields.append(model_fields[fname]) return fields def clear_manual_fields(self): """ Invalidate the cache for manual fields. """ self._fields_by_model = None def get_manual_fields(self, cr, model_name): """ Return the manual fields (as a dict) for the given model. """ if self._fields_by_model is None: # Query manual fields for all models at once self._fields_by_model = dic = defaultdict(dict) cr.execute('SELECT * FROM ir_model_fields WHERE state=%s', ('manual',)) for field in cr.dictfetchall(): dic[field['model']][field['name']] = field return self._fields_by_model[model_name] def do_parent_store(self, cr): for o in self._init_parent: self.get(o)._parent_store_compute(cr) self._init = False def obj_list(self): """ Return the list of model names in this registry.""" return self.keys() def add(self, model_name, model): """ Add or replace a model in the registry.""" self.models[model_name] = model def load(self, cr, module): """ Load a given module in the registry. At the Python level, the modules are already loaded, but not yet on a per-registry level. This method populates a registry with the given modules, i.e. it instanciates all the classes of a the given module and registers them in the registry. """ from .. import models models_to_load = [] # need to preserve loading order lazy_property.reset_all(self) # Instantiate registered classes (via the MetaModel automatic discovery # or via explicit constructor call), and add them to the pool. for cls in models.MetaModel.module_to_models.get(module.name, []): # models register themselves in self.models model = cls._build_model(self, cr) if model._name not in models_to_load: # avoid double-loading models whose declaration is split models_to_load.append(model._name) return [self.models[m] for m in models_to_load] def setup_models(self, cr, partial=False): """ Complete the setup of models. This must be called after loading modules and before using the ORM. :param partial: ``True`` if all models have not been loaded yet. """ lazy_property.reset_all(self) # load custom models ir_model = self['ir.model'] cr.execute('select model from ir_model where state=%s', ('manual',)) for (model_name,) in cr.fetchall(): ir_model.instanciate(cr, SUPERUSER_ID, model_name, {}) # prepare the setup on all models for model in self.models.itervalues(): model._prepare_setup(cr, SUPERUSER_ID) # do the actual setup from a clean state self._m2m = {} for model in self.models.itervalues(): model._setup_base(cr, SUPERUSER_ID, partial) for model in self.models.itervalues(): model._setup_fields(cr, SUPERUSER_ID) for model in self.models.itervalues(): model._setup_complete(cr, SUPERUSER_ID) def clear_caches(self): """ Clear the caches This clears the caches associated to methods decorated with ``tools.ormcache`` or ``tools.ormcache_multi`` for all the models. """ for model in self.models.itervalues(): model.clear_caches() # Special case for ir_ui_menu which does not use openerp.tools.ormcache. ir_ui_menu = self.models.get('ir.ui.menu') if ir_ui_menu is not None: ir_ui_menu.clear_cache() # Useful only in a multi-process context. def reset_any_cache_cleared(self): self._any_cache_cleared = False # Useful only in a multi-process context. def any_cache_cleared(self): return self._any_cache_cleared @classmethod def setup_multi_process_signaling(cls, cr): if not openerp.multi_process: return None, None # Inter-process signaling: # The `base_registry_signaling` sequence indicates the whole registry # must be reloaded. # The `base_cache_signaling sequence` indicates all caches must be # invalidated (i.e. cleared). cr.execute("""SELECT sequence_name FROM information_schema.sequences WHERE sequence_name='base_registry_signaling'""") if not cr.fetchall(): cr.execute("""CREATE SEQUENCE base_registry_signaling INCREMENT BY 1 START WITH 1""") cr.execute("""SELECT nextval('base_registry_signaling')""") cr.execute("""CREATE SEQUENCE base_cache_signaling INCREMENT BY 1 START WITH 1""") cr.execute("""SELECT nextval('base_cache_signaling')""") cr.execute(""" SELECT base_registry_signaling.last_value, base_cache_signaling.last_value FROM base_registry_signaling, base_cache_signaling""") r, c = cr.fetchone() _logger.debug("Multiprocess load registry signaling: [Registry: # %s] "\ "[Cache: # %s]", r, c) return r, c def enter_test_mode(self): """ Enter the 'test' mode, where one cursor serves several requests. """ assert self.test_cr is None self.test_cr = self._db.test_cursor() RegistryManager.enter_test_mode() def leave_test_mode(self): """ Leave the test mode. """ assert self.test_cr is not None self.test_cr.force_close() self.test_cr = None RegistryManager.leave_test_mode() def cursor(self): """ Return a new cursor for the database. The cursor itself may be used as a context manager to commit/rollback and close automatically. """ cr = self.test_cr if cr is not None: # While in test mode, we use one special cursor across requests. The # test cursor uses a reentrant lock to serialize accesses. The lock # is granted here by cursor(), and automatically released by the # cursor itself in its method close(). cr.acquire() return cr return self._db.cursor() class DummyRLock(object): """ Dummy reentrant lock, to be used while running rpc and js tests """ def acquire(self): pass def release(self): pass def __enter__(self): self.acquire() def __exit__(self, type, value, traceback): self.release() class RegistryManager(object): """ Model registries manager. The manager is responsible for creation and deletion of model registries (essentially database connection/model registry pairs). """ _registries = None _lock = threading.RLock() _saved_lock = None @classproperty def registries(cls): if cls._registries is None: size = config.get('registry_lru_size', None) if not size: # Size the LRU depending of the memory limits if os.name != 'posix': # cannot specify the memory limit soft on windows... size = 42 else: # A registry takes 10MB of memory on average, so we reserve # 10Mb (registry) + 5Mb (working memory) per registry avgsz = 15 * 1024 * 1024 size = int(config['limit_memory_soft'] / avgsz) cls._registries = LRU(size) return cls._registries @classmethod def lock(cls): """ Return the current registry lock. """ return cls._lock @classmethod def enter_test_mode(cls): """ Enter the 'test' mode, where the registry is no longer locked. """ assert cls._saved_lock is None cls._lock, cls._saved_lock = DummyRLock(), cls._lock @classmethod def leave_test_mode(cls): """ Leave the 'test' mode. """ assert cls._saved_lock is not None cls._lock, cls._saved_lock = cls._saved_lock, None @classmethod def get(cls, db_name, force_demo=False, status=None, update_module=False): """ Return a registry for a given database name.""" with cls.lock(): try: return cls.registries[db_name] except KeyError: return cls.new(db_name, force_demo, status, update_module) finally: # set db tracker - cleaned up at the WSGI # dispatching phase in openerp.service.wsgi_server.application threading.current_thread().dbname = db_name @classmethod def new(cls, db_name, force_demo=False, status=None, update_module=False): """ Create and return a new registry for a given database name. The (possibly) previous registry for that database name is discarded. """ import openerp.modules with cls.lock(): with openerp.api.Environment.manage(): registry = Registry(db_name) # Initializing a registry will call general code which will in # turn call registries.get (this object) to obtain the registry # being initialized. Make it available in the registries # dictionary then remove it if an exception is raised. cls.delete(db_name) cls.registries[db_name] = registry try: with registry.cursor() as cr: seq_registry, seq_cache = Registry.setup_multi_process_signaling(cr) registry.base_registry_signaling_sequence = seq_registry registry.base_cache_signaling_sequence = seq_cache # This should be a method on Registry openerp.modules.load_modules(registry._db, force_demo, status, update_module) except Exception: del cls.registries[db_name] raise # load_modules() above can replace the registry by calling # indirectly new() again (when modules have to be uninstalled). # Yeah, crazy. registry = cls.registries[db_name] cr = registry.cursor() try: registry.do_parent_store(cr) cr.commit() finally: cr.close() registry.ready = True if update_module: # only in case of update, otherwise we'll have an infinite reload loop! cls.signal_registry_change(db_name) return registry @classmethod def delete(cls, db_name): """Delete the registry linked to a given database. """ with cls.lock(): if db_name in cls.registries: cls.registries[db_name].clear_caches() del cls.registries[db_name] @classmethod def delete_all(cls): """Delete all the registries. """ with cls.lock(): for db_name in cls.registries.keys(): cls.delete(db_name) @classmethod def clear_caches(cls, db_name): """Clear caches This clears the caches associated to methods decorated with ``tools.ormcache`` or ``tools.ormcache_multi`` for all the models of the given database name. This method is given to spare you a ``RegistryManager.get(db_name)`` that would loads the given database if it was not already loaded. """ with cls.lock(): if db_name in cls.registries: cls.registries[db_name].clear_caches() @classmethod def check_registry_signaling(cls, db_name): """ Check if the modules have changed and performs all necessary operations to update the registry of the corresponding database. :returns: True if changes has been detected in the database and False otherwise. """ changed = False if openerp.multi_process and db_name in cls.registries: registry = cls.get(db_name) cr = registry.cursor() try: cr.execute(""" SELECT base_registry_signaling.last_value, base_cache_signaling.last_value FROM base_registry_signaling, base_cache_signaling""") r, c = cr.fetchone() _logger.debug("Multiprocess signaling check: [Registry - old# %s new# %s] "\ "[Cache - old# %s new# %s]", registry.base_registry_signaling_sequence, r, registry.base_cache_signaling_sequence, c) # Check if the model registry must be reloaded (e.g. after the # database has been updated by another process). if registry.base_registry_signaling_sequence is not None and registry.base_registry_signaling_sequence != r: changed = True _logger.info("Reloading the model registry after database signaling.") registry = cls.new(db_name) # Check if the model caches must be invalidated (e.g. after a write # occured on another process). Don't clear right after a registry # has been reload. elif registry.base_cache_signaling_sequence is not None and registry.base_cache_signaling_sequence != c: changed = True _logger.info("Invalidating all model caches after database signaling.") registry.clear_caches() registry.reset_any_cache_cleared() registry.base_registry_signaling_sequence = r registry.base_cache_signaling_sequence = c finally: cr.close() return changed @classmethod def signal_caches_change(cls, db_name): if openerp.multi_process and db_name in cls.registries: # Check the registries if any cache has been cleared and signal it # through the database to other processes. registry = cls.get(db_name) if registry.any_cache_cleared(): _logger.info("At least one model cache has been cleared, signaling through the database.") cr = registry.cursor() r = 1 try: cr.execute("select nextval('base_cache_signaling')") r = cr.fetchone()[0] finally: cr.close() registry.base_cache_signaling_sequence = r registry.reset_any_cache_cleared() @classmethod def signal_registry_change(cls, db_name): if openerp.multi_process and db_name in cls.registries: _logger.info("Registry changed, signaling through the database") registry = cls.get(db_name) cr = registry.cursor() r = 1 try: cr.execute("select nextval('base_registry_signaling')") r = cr.fetchone()[0] finally: cr.close() registry.base_registry_signaling_sequence = r # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
nthall/pip
pip/_vendor/requests/packages/chardet/euckrfreq.py
3121
45978
######################## BEGIN LICENSE BLOCK ######################## # The Original Code is Mozilla Communicator client code. # # The Initial Developer of the Original Code is # Netscape Communications Corporation. # Portions created by the Initial Developer are Copyright (C) 1998 # the Initial Developer. All Rights Reserved. # # Contributor(s): # Mark Pilgrim - port to Python # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 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 # 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., 51 Franklin St, Fifth Floor, Boston, MA # 02110-1301 USA ######################### END LICENSE BLOCK ######################### # Sampling from about 20M text materials include literature and computer technology # 128 --> 0.79 # 256 --> 0.92 # 512 --> 0.986 # 1024 --> 0.99944 # 2048 --> 0.99999 # # Idea Distribution Ratio = 0.98653 / (1-0.98653) = 73.24 # Random Distribution Ration = 512 / (2350-512) = 0.279. # # Typical Distribution Ratio EUCKR_TYPICAL_DISTRIBUTION_RATIO = 6.0 EUCKR_TABLE_SIZE = 2352 # Char to FreqOrder table , EUCKRCharToFreqOrder = ( \ 13, 130, 120,1396, 481,1719,1720, 328, 609, 212,1721, 707, 400, 299,1722, 87, 1397,1723, 104, 536,1117,1203,1724,1267, 685,1268, 508,1725,1726,1727,1728,1398, 1399,1729,1730,1731, 141, 621, 326,1057, 368,1732, 267, 488, 20,1733,1269,1734, 945,1400,1735, 47, 904,1270,1736,1737, 773, 248,1738, 409, 313, 786, 429,1739, 116, 987, 813,1401, 683, 75,1204, 145,1740,1741,1742,1743, 16, 847, 667, 622, 708,1744,1745,1746, 966, 787, 304, 129,1747, 60, 820, 123, 676,1748,1749,1750, 1751, 617,1752, 626,1753,1754,1755,1756, 653,1757,1758,1759,1760,1761,1762, 856, 344,1763,1764,1765,1766, 89, 401, 418, 806, 905, 848,1767,1768,1769, 946,1205, 709,1770,1118,1771, 241,1772,1773,1774,1271,1775, 569,1776, 999,1777,1778,1779, 1780, 337, 751,1058, 28, 628, 254,1781, 177, 906, 270, 349, 891,1079,1782, 19, 1783, 379,1784, 315,1785, 629, 754,1402, 559,1786, 636, 203,1206,1787, 710, 567, 1788, 935, 814,1789,1790,1207, 766, 528,1791,1792,1208,1793,1794,1795,1796,1797, 1403,1798,1799, 533,1059,1404,1405,1156,1406, 936, 884,1080,1800, 351,1801,1802, 1803,1804,1805, 801,1806,1807,1808,1119,1809,1157, 714, 474,1407,1810, 298, 899, 885,1811,1120, 802,1158,1812, 892,1813,1814,1408, 659,1815,1816,1121,1817,1818, 1819,1820,1821,1822, 319,1823, 594, 545,1824, 815, 937,1209,1825,1826, 573,1409, 1022,1827,1210,1828,1829,1830,1831,1832,1833, 556, 722, 807,1122,1060,1834, 697, 1835, 900, 557, 715,1836,1410, 540,1411, 752,1159, 294, 597,1211, 976, 803, 770, 1412,1837,1838, 39, 794,1413, 358,1839, 371, 925,1840, 453, 661, 788, 531, 723, 544,1023,1081, 869, 91,1841, 392, 430, 790, 602,1414, 677,1082, 457,1415,1416, 1842,1843, 475, 327,1024,1417, 795, 121,1844, 733, 403,1418,1845,1846,1847, 300, 119, 711,1212, 627,1848,1272, 207,1849,1850, 796,1213, 382,1851, 519,1852,1083, 893,1853,1854,1855, 367, 809, 487, 671,1856, 663,1857,1858, 956, 471, 306, 857, 1859,1860,1160,1084,1861,1862,1863,1864,1865,1061,1866,1867,1868,1869,1870,1871, 282, 96, 574,1872, 502,1085,1873,1214,1874, 907,1875,1876, 827, 977,1419,1420, 1421, 268,1877,1422,1878,1879,1880, 308,1881, 2, 537,1882,1883,1215,1884,1885, 127, 791,1886,1273,1423,1887, 34, 336, 404, 643,1888, 571, 654, 894, 840,1889, 0, 886,1274, 122, 575, 260, 908, 938,1890,1275, 410, 316,1891,1892, 100,1893, 1894,1123, 48,1161,1124,1025,1895, 633, 901,1276,1896,1897, 115, 816,1898, 317, 1899, 694,1900, 909, 734,1424, 572, 866,1425, 691, 85, 524,1010, 543, 394, 841, 1901,1902,1903,1026,1904,1905,1906,1907,1908,1909, 30, 451, 651, 988, 310,1910, 1911,1426, 810,1216, 93,1912,1913,1277,1217,1914, 858, 759, 45, 58, 181, 610, 269,1915,1916, 131,1062, 551, 443,1000, 821,1427, 957, 895,1086,1917,1918, 375, 1919, 359,1920, 687,1921, 822,1922, 293,1923,1924, 40, 662, 118, 692, 29, 939, 887, 640, 482, 174,1925, 69,1162, 728,1428, 910,1926,1278,1218,1279, 386, 870, 217, 854,1163, 823,1927,1928,1929,1930, 834,1931, 78,1932, 859,1933,1063,1934, 1935,1936,1937, 438,1164, 208, 595,1938,1939,1940,1941,1219,1125,1942, 280, 888, 1429,1430,1220,1431,1943,1944,1945,1946,1947,1280, 150, 510,1432,1948,1949,1950, 1951,1952,1953,1954,1011,1087,1955,1433,1043,1956, 881,1957, 614, 958,1064,1065, 1221,1958, 638,1001, 860, 967, 896,1434, 989, 492, 553,1281,1165,1959,1282,1002, 1283,1222,1960,1961,1962,1963, 36, 383, 228, 753, 247, 454,1964, 876, 678,1965, 1966,1284, 126, 464, 490, 835, 136, 672, 529, 940,1088,1435, 473,1967,1968, 467, 50, 390, 227, 587, 279, 378, 598, 792, 968, 240, 151, 160, 849, 882,1126,1285, 639,1044, 133, 140, 288, 360, 811, 563,1027, 561, 142, 523,1969,1970,1971, 7, 103, 296, 439, 407, 506, 634, 990,1972,1973,1974,1975, 645,1976,1977,1978,1979, 1980,1981, 236,1982,1436,1983,1984,1089, 192, 828, 618, 518,1166, 333,1127,1985, 818,1223,1986,1987,1988,1989,1990,1991,1992,1993, 342,1128,1286, 746, 842,1994, 1995, 560, 223,1287, 98, 8, 189, 650, 978,1288,1996,1437,1997, 17, 345, 250, 423, 277, 234, 512, 226, 97, 289, 42, 167,1998, 201,1999,2000, 843, 836, 824, 532, 338, 783,1090, 182, 576, 436,1438,1439, 527, 500,2001, 947, 889,2002,2003, 2004,2005, 262, 600, 314, 447,2006, 547,2007, 693, 738,1129,2008, 71,1440, 745, 619, 688,2009, 829,2010,2011, 147,2012, 33, 948,2013,2014, 74, 224,2015, 61, 191, 918, 399, 637,2016,1028,1130, 257, 902,2017,2018,2019,2020,2021,2022,2023, 2024,2025,2026, 837,2027,2028,2029,2030, 179, 874, 591, 52, 724, 246,2031,2032, 2033,2034,1167, 969,2035,1289, 630, 605, 911,1091,1168,2036,2037,2038,1441, 912, 2039, 623,2040,2041, 253,1169,1290,2042,1442, 146, 620, 611, 577, 433,2043,1224, 719,1170, 959, 440, 437, 534, 84, 388, 480,1131, 159, 220, 198, 679,2044,1012, 819,1066,1443, 113,1225, 194, 318,1003,1029,2045,2046,2047,2048,1067,2049,2050, 2051,2052,2053, 59, 913, 112,2054, 632,2055, 455, 144, 739,1291,2056, 273, 681, 499,2057, 448,2058,2059, 760,2060,2061, 970, 384, 169, 245,1132,2062,2063, 414, 1444,2064,2065, 41, 235,2066, 157, 252, 877, 568, 919, 789, 580,2067, 725,2068, 2069,1292,2070,2071,1445,2072,1446,2073,2074, 55, 588, 66,1447, 271,1092,2075, 1226,2076, 960,1013, 372,2077,2078,2079,2080,2081,1293,2082,2083,2084,2085, 850, 2086,2087,2088,2089,2090, 186,2091,1068, 180,2092,2093,2094, 109,1227, 522, 606, 2095, 867,1448,1093, 991,1171, 926, 353,1133,2096, 581,2097,2098,2099,1294,1449, 1450,2100, 596,1172,1014,1228,2101,1451,1295,1173,1229,2102,2103,1296,1134,1452, 949,1135,2104,2105,1094,1453,1454,1455,2106,1095,2107,2108,2109,2110,2111,2112, 2113,2114,2115,2116,2117, 804,2118,2119,1230,1231, 805,1456, 405,1136,2120,2121, 2122,2123,2124, 720, 701,1297, 992,1457, 927,1004,2125,2126,2127,2128,2129,2130, 22, 417,2131, 303,2132, 385,2133, 971, 520, 513,2134,1174, 73,1096, 231, 274, 962,1458, 673,2135,1459,2136, 152,1137,2137,2138,2139,2140,1005,1138,1460,1139, 2141,2142,2143,2144, 11, 374, 844,2145, 154,1232, 46,1461,2146, 838, 830, 721, 1233, 106,2147, 90, 428, 462, 578, 566,1175, 352,2148,2149, 538,1234, 124,1298, 2150,1462, 761, 565,2151, 686,2152, 649,2153, 72, 173,2154, 460, 415,2155,1463, 2156,1235, 305,2157,2158,2159,2160,2161,2162, 579,2163,2164,2165,2166,2167, 747, 2168,2169,2170,2171,1464, 669,2172,2173,2174,2175,2176,1465,2177, 23, 530, 285, 2178, 335, 729,2179, 397,2180,2181,2182,1030,2183,2184, 698,2185,2186, 325,2187, 2188, 369,2189, 799,1097,1015, 348,2190,1069, 680,2191, 851,1466,2192,2193, 10, 2194, 613, 424,2195, 979, 108, 449, 589, 27, 172, 81,1031, 80, 774, 281, 350, 1032, 525, 301, 582,1176,2196, 674,1045,2197,2198,1467, 730, 762,2199,2200,2201, 2202,1468,2203, 993,2204,2205, 266,1070, 963,1140,2206,2207,2208, 664,1098, 972, 2209,2210,2211,1177,1469,1470, 871,2212,2213,2214,2215,2216,1471,2217,2218,2219, 2220,2221,2222,2223,2224,2225,2226,2227,1472,1236,2228,2229,2230,2231,2232,2233, 2234,2235,1299,2236,2237, 200,2238, 477, 373,2239,2240, 731, 825, 777,2241,2242, 2243, 521, 486, 548,2244,2245,2246,1473,1300, 53, 549, 137, 875, 76, 158,2247, 1301,1474, 469, 396,1016, 278, 712,2248, 321, 442, 503, 767, 744, 941,1237,1178, 1475,2249, 82, 178,1141,1179, 973,2250,1302,2251, 297,2252,2253, 570,2254,2255, 2256, 18, 450, 206,2257, 290, 292,1142,2258, 511, 162, 99, 346, 164, 735,2259, 1476,1477, 4, 554, 343, 798,1099,2260,1100,2261, 43, 171,1303, 139, 215,2262, 2263, 717, 775,2264,1033, 322, 216,2265, 831,2266, 149,2267,1304,2268,2269, 702, 1238, 135, 845, 347, 309,2270, 484,2271, 878, 655, 238,1006,1478,2272, 67,2273, 295,2274,2275, 461,2276, 478, 942, 412,2277,1034,2278,2279,2280, 265,2281, 541, 2282,2283,2284,2285,2286, 70, 852,1071,2287,2288,2289,2290, 21, 56, 509, 117, 432,2291,2292, 331, 980, 552,1101, 148, 284, 105, 393,1180,1239, 755,2293, 187, 2294,1046,1479,2295, 340,2296, 63,1047, 230,2297,2298,1305, 763,1306, 101, 800, 808, 494,2299,2300,2301, 903,2302, 37,1072, 14, 5,2303, 79, 675,2304, 312, 2305,2306,2307,2308,2309,1480, 6,1307,2310,2311,2312, 1, 470, 35, 24, 229, 2313, 695, 210, 86, 778, 15, 784, 592, 779, 32, 77, 855, 964,2314, 259,2315, 501, 380,2316,2317, 83, 981, 153, 689,1308,1481,1482,1483,2318,2319, 716,1484, 2320,2321,2322,2323,2324,2325,1485,2326,2327, 128, 57, 68, 261,1048, 211, 170, 1240, 31,2328, 51, 435, 742,2329,2330,2331, 635,2332, 264, 456,2333,2334,2335, 425,2336,1486, 143, 507, 263, 943,2337, 363, 920,1487, 256,1488,1102, 243, 601, 1489,2338,2339,2340,2341,2342,2343,2344, 861,2345,2346,2347,2348,2349,2350, 395, 2351,1490,1491, 62, 535, 166, 225,2352,2353, 668, 419,1241, 138, 604, 928,2354, 1181,2355,1492,1493,2356,2357,2358,1143,2359, 696,2360, 387, 307,1309, 682, 476, 2361,2362, 332, 12, 222, 156,2363, 232,2364, 641, 276, 656, 517,1494,1495,1035, 416, 736,1496,2365,1017, 586,2366,2367,2368,1497,2369, 242,2370,2371,2372,1498, 2373, 965, 713,2374,2375,2376,2377, 740, 982,1499, 944,1500,1007,2378,2379,1310, 1501,2380,2381,2382, 785, 329,2383,2384,1502,2385,2386,2387, 932,2388,1503,2389, 2390,2391,2392,1242,2393,2394,2395,2396,2397, 994, 950,2398,2399,2400,2401,1504, 1311,2402,2403,2404,2405,1049, 749,2406,2407, 853, 718,1144,1312,2408,1182,1505, 2409,2410, 255, 516, 479, 564, 550, 214,1506,1507,1313, 413, 239, 444, 339,1145, 1036,1508,1509,1314,1037,1510,1315,2411,1511,2412,2413,2414, 176, 703, 497, 624, 593, 921, 302,2415, 341, 165,1103,1512,2416,1513,2417,2418,2419, 376,2420, 700, 2421,2422,2423, 258, 768,1316,2424,1183,2425, 995, 608,2426,2427,2428,2429, 221, 2430,2431,2432,2433,2434,2435,2436,2437, 195, 323, 726, 188, 897, 983,1317, 377, 644,1050, 879,2438, 452,2439,2440,2441,2442,2443,2444, 914,2445,2446,2447,2448, 915, 489,2449,1514,1184,2450,2451, 515, 64, 427, 495,2452, 583,2453, 483, 485, 1038, 562, 213,1515, 748, 666,2454,2455,2456,2457, 334,2458, 780, 996,1008, 705, 1243,2459,2460,2461,2462,2463, 114,2464, 493,1146, 366, 163,1516, 961,1104,2465, 291,2466,1318,1105,2467,1517, 365,2468, 355, 951,1244,2469,1319,2470, 631,2471, 2472, 218,1320, 364, 320, 756,1518,1519,1321,1520,1322,2473,2474,2475,2476, 997, 2477,2478,2479,2480, 665,1185,2481, 916,1521,2482,2483,2484, 584, 684,2485,2486, 797,2487,1051,1186,2488,2489,2490,1522,2491,2492, 370,2493,1039,1187, 65,2494, 434, 205, 463,1188,2495, 125, 812, 391, 402, 826, 699, 286, 398, 155, 781, 771, 585,2496, 590, 505,1073,2497, 599, 244, 219, 917,1018, 952, 646,1523,2498,1323, 2499,2500, 49, 984, 354, 741,2501, 625,2502,1324,2503,1019, 190, 357, 757, 491, 95, 782, 868,2504,2505,2506,2507,2508,2509, 134,1524,1074, 422,1525, 898,2510, 161,2511,2512,2513,2514, 769,2515,1526,2516,2517, 411,1325,2518, 472,1527,2519, 2520,2521,2522,2523,2524, 985,2525,2526,2527,2528,2529,2530, 764,2531,1245,2532, 2533, 25, 204, 311,2534, 496,2535,1052,2536,2537,2538,2539,2540,2541,2542, 199, 704, 504, 468, 758, 657,1528, 196, 44, 839,1246, 272, 750,2543, 765, 862,2544, 2545,1326,2546, 132, 615, 933,2547, 732,2548,2549,2550,1189,1529,2551, 283,1247, 1053, 607, 929,2552,2553,2554, 930, 183, 872, 616,1040,1147,2555,1148,1020, 441, 249,1075,2556,2557,2558, 466, 743,2559,2560,2561, 92, 514, 426, 420, 526,2562, 2563,2564,2565,2566,2567,2568, 185,2569,2570,2571,2572, 776,1530, 658,2573, 362, 2574, 361, 922,1076, 793,2575,2576,2577,2578,2579,2580,1531, 251,2581,2582,2583, 2584,1532, 54, 612, 237,1327,2585,2586, 275, 408, 647, 111,2587,1533,1106, 465, 3, 458, 9, 38,2588, 107, 110, 890, 209, 26, 737, 498,2589,1534,2590, 431, 202, 88,1535, 356, 287,1107, 660,1149,2591, 381,1536, 986,1150, 445,1248,1151, 974,2592,2593, 846,2594, 446, 953, 184,1249,1250, 727,2595, 923, 193, 883,2596, 2597,2598, 102, 324, 539, 817,2599, 421,1041,2600, 832,2601, 94, 175, 197, 406, 2602, 459,2603,2604,2605,2606,2607, 330, 555,2608,2609,2610, 706,1108, 389,2611, 2612,2613,2614, 233,2615, 833, 558, 931, 954,1251,2616,2617,1537, 546,2618,2619, 1009,2620,2621,2622,1538, 690,1328,2623, 955,2624,1539,2625,2626, 772,2627,2628, 2629,2630,2631, 924, 648, 863, 603,2632,2633, 934,1540, 864, 865,2634, 642,1042, 670,1190,2635,2636,2637,2638, 168,2639, 652, 873, 542,1054,1541,2640,2641,2642, # 512, 256 #Everything below is of no interest for detection purpose 2643,2644,2645,2646,2647,2648,2649,2650,2651,2652,2653,2654,2655,2656,2657,2658, 2659,2660,2661,2662,2663,2664,2665,2666,2667,2668,2669,2670,2671,2672,2673,2674, 2675,2676,2677,2678,2679,2680,2681,2682,2683,2684,2685,2686,2687,2688,2689,2690, 2691,2692,2693,2694,2695,2696,2697,2698,2699,1542, 880,2700,2701,2702,2703,2704, 2705,2706,2707,2708,2709,2710,2711,2712,2713,2714,2715,2716,2717,2718,2719,2720, 2721,2722,2723,2724,2725,1543,2726,2727,2728,2729,2730,2731,2732,1544,2733,2734, 2735,2736,2737,2738,2739,2740,2741,2742,2743,2744,2745,2746,2747,2748,2749,2750, 2751,2752,2753,2754,1545,2755,2756,2757,2758,2759,2760,2761,2762,2763,2764,2765, 2766,1546,2767,1547,2768,2769,2770,2771,2772,2773,2774,2775,2776,2777,2778,2779, 2780,2781,2782,2783,2784,2785,2786,1548,2787,2788,2789,1109,2790,2791,2792,2793, 2794,2795,2796,2797,2798,2799,2800,2801,2802,2803,2804,2805,2806,2807,2808,2809, 2810,2811,2812,1329,2813,2814,2815,2816,2817,2818,2819,2820,2821,2822,2823,2824, 2825,2826,2827,2828,2829,2830,2831,2832,2833,2834,2835,2836,2837,2838,2839,2840, 2841,2842,2843,2844,2845,2846,2847,2848,2849,2850,2851,2852,2853,2854,2855,2856, 1549,2857,2858,2859,2860,1550,2861,2862,1551,2863,2864,2865,2866,2867,2868,2869, 2870,2871,2872,2873,2874,1110,1330,2875,2876,2877,2878,2879,2880,2881,2882,2883, 2884,2885,2886,2887,2888,2889,2890,2891,2892,2893,2894,2895,2896,2897,2898,2899, 2900,2901,2902,2903,2904,2905,2906,2907,2908,2909,2910,2911,2912,2913,2914,2915, 2916,2917,2918,2919,2920,2921,2922,2923,2924,2925,2926,2927,2928,2929,2930,1331, 2931,2932,2933,2934,2935,2936,2937,2938,2939,2940,2941,2942,2943,1552,2944,2945, 2946,2947,2948,2949,2950,2951,2952,2953,2954,2955,2956,2957,2958,2959,2960,2961, 2962,2963,2964,1252,2965,2966,2967,2968,2969,2970,2971,2972,2973,2974,2975,2976, 2977,2978,2979,2980,2981,2982,2983,2984,2985,2986,2987,2988,2989,2990,2991,2992, 2993,2994,2995,2996,2997,2998,2999,3000,3001,3002,3003,3004,3005,3006,3007,3008, 3009,3010,3011,3012,1553,3013,3014,3015,3016,3017,1554,3018,1332,3019,3020,3021, 3022,3023,3024,3025,3026,3027,3028,3029,3030,3031,3032,3033,3034,3035,3036,3037, 3038,3039,3040,3041,3042,3043,3044,3045,3046,3047,3048,3049,3050,1555,3051,3052, 3053,1556,1557,3054,3055,3056,3057,3058,3059,3060,3061,3062,3063,3064,3065,3066, 3067,1558,3068,3069,3070,3071,3072,3073,3074,3075,3076,1559,3077,3078,3079,3080, 3081,3082,3083,1253,3084,3085,3086,3087,3088,3089,3090,3091,3092,3093,3094,3095, 3096,3097,3098,3099,3100,3101,3102,3103,3104,3105,3106,3107,3108,1152,3109,3110, 3111,3112,3113,1560,3114,3115,3116,3117,1111,3118,3119,3120,3121,3122,3123,3124, 3125,3126,3127,3128,3129,3130,3131,3132,3133,3134,3135,3136,3137,3138,3139,3140, 3141,3142,3143,3144,3145,3146,3147,3148,3149,3150,3151,3152,3153,3154,3155,3156, 3157,3158,3159,3160,3161,3162,3163,3164,3165,3166,3167,3168,3169,3170,3171,3172, 3173,3174,3175,3176,1333,3177,3178,3179,3180,3181,3182,3183,3184,3185,3186,3187, 3188,3189,1561,3190,3191,1334,3192,3193,3194,3195,3196,3197,3198,3199,3200,3201, 3202,3203,3204,3205,3206,3207,3208,3209,3210,3211,3212,3213,3214,3215,3216,3217, 3218,3219,3220,3221,3222,3223,3224,3225,3226,3227,3228,3229,3230,3231,3232,3233, 3234,1562,3235,3236,3237,3238,3239,3240,3241,3242,3243,3244,3245,3246,3247,3248, 3249,3250,3251,3252,3253,3254,3255,3256,3257,3258,3259,3260,3261,3262,3263,3264, 3265,3266,3267,3268,3269,3270,3271,3272,3273,3274,3275,3276,3277,1563,3278,3279, 3280,3281,3282,3283,3284,3285,3286,3287,3288,3289,3290,3291,3292,3293,3294,3295, 3296,3297,3298,3299,3300,3301,3302,3303,3304,3305,3306,3307,3308,3309,3310,3311, 3312,3313,3314,3315,3316,3317,3318,3319,3320,3321,3322,3323,3324,3325,3326,3327, 3328,3329,3330,3331,3332,3333,3334,3335,3336,3337,3338,3339,3340,3341,3342,3343, 3344,3345,3346,3347,3348,3349,3350,3351,3352,3353,3354,3355,3356,3357,3358,3359, 3360,3361,3362,3363,3364,1335,3365,3366,3367,3368,3369,3370,3371,3372,3373,3374, 3375,3376,3377,3378,3379,3380,3381,3382,3383,3384,3385,3386,3387,1336,3388,3389, 3390,3391,3392,3393,3394,3395,3396,3397,3398,3399,3400,3401,3402,3403,3404,3405, 3406,3407,3408,3409,3410,3411,3412,3413,3414,1337,3415,3416,3417,3418,3419,1338, 3420,3421,3422,1564,1565,3423,3424,3425,3426,3427,3428,3429,3430,3431,1254,3432, 3433,3434,1339,3435,3436,3437,3438,3439,1566,3440,3441,3442,3443,3444,3445,3446, 3447,3448,3449,3450,3451,3452,3453,3454,1255,3455,3456,3457,3458,3459,1567,1191, 3460,1568,1569,3461,3462,3463,1570,3464,3465,3466,3467,3468,1571,3469,3470,3471, 3472,3473,1572,3474,3475,3476,3477,3478,3479,3480,3481,3482,3483,3484,3485,3486, 1340,3487,3488,3489,3490,3491,3492,1021,3493,3494,3495,3496,3497,3498,1573,3499, 1341,3500,3501,3502,3503,3504,3505,3506,3507,3508,3509,3510,3511,1342,3512,3513, 3514,3515,3516,1574,1343,3517,3518,3519,1575,3520,1576,3521,3522,3523,3524,3525, 3526,3527,3528,3529,3530,3531,3532,3533,3534,3535,3536,3537,3538,3539,3540,3541, 3542,3543,3544,3545,3546,3547,3548,3549,3550,3551,3552,3553,3554,3555,3556,3557, 3558,3559,3560,3561,3562,3563,3564,3565,3566,3567,3568,3569,3570,3571,3572,3573, 3574,3575,3576,3577,3578,3579,3580,1577,3581,3582,1578,3583,3584,3585,3586,3587, 3588,3589,3590,3591,3592,3593,3594,3595,3596,3597,3598,3599,3600,3601,3602,3603, 3604,1579,3605,3606,3607,3608,3609,3610,3611,3612,3613,3614,3615,3616,3617,3618, 3619,3620,3621,3622,3623,3624,3625,3626,3627,3628,3629,1580,3630,3631,1581,3632, 3633,3634,3635,3636,3637,3638,3639,3640,3641,3642,3643,3644,3645,3646,3647,3648, 3649,3650,3651,3652,3653,3654,3655,3656,1582,3657,3658,3659,3660,3661,3662,3663, 3664,3665,3666,3667,3668,3669,3670,3671,3672,3673,3674,3675,3676,3677,3678,3679, 3680,3681,3682,3683,3684,3685,3686,3687,3688,3689,3690,3691,3692,3693,3694,3695, 3696,3697,3698,3699,3700,1192,3701,3702,3703,3704,1256,3705,3706,3707,3708,1583, 1257,3709,3710,3711,3712,3713,3714,3715,3716,1584,3717,3718,3719,3720,3721,3722, 3723,3724,3725,3726,3727,3728,3729,3730,3731,3732,3733,3734,3735,3736,3737,3738, 3739,3740,3741,3742,3743,3744,3745,1344,3746,3747,3748,3749,3750,3751,3752,3753, 3754,3755,3756,1585,3757,3758,3759,3760,3761,3762,3763,3764,3765,3766,1586,3767, 3768,3769,3770,3771,3772,3773,3774,3775,3776,3777,3778,1345,3779,3780,3781,3782, 3783,3784,3785,3786,3787,3788,3789,3790,3791,3792,3793,3794,3795,1346,1587,3796, 3797,1588,3798,3799,3800,3801,3802,3803,3804,3805,3806,1347,3807,3808,3809,3810, 3811,1589,3812,3813,3814,3815,3816,3817,3818,3819,3820,3821,1590,3822,3823,1591, 1348,3824,3825,3826,3827,3828,3829,3830,1592,3831,3832,1593,3833,3834,3835,3836, 3837,3838,3839,3840,3841,3842,3843,3844,1349,3845,3846,3847,3848,3849,3850,3851, 3852,3853,3854,3855,3856,3857,3858,1594,3859,3860,3861,3862,3863,3864,3865,3866, 3867,3868,3869,1595,3870,3871,3872,3873,1596,3874,3875,3876,3877,3878,3879,3880, 3881,3882,3883,3884,3885,3886,1597,3887,3888,3889,3890,3891,3892,3893,3894,3895, 1598,3896,3897,3898,1599,1600,3899,1350,3900,1351,3901,3902,1352,3903,3904,3905, 3906,3907,3908,3909,3910,3911,3912,3913,3914,3915,3916,3917,3918,3919,3920,3921, 3922,3923,3924,1258,3925,3926,3927,3928,3929,3930,3931,1193,3932,1601,3933,3934, 3935,3936,3937,3938,3939,3940,3941,3942,3943,1602,3944,3945,3946,3947,3948,1603, 3949,3950,3951,3952,3953,3954,3955,3956,3957,3958,3959,3960,3961,3962,3963,3964, 3965,1604,3966,3967,3968,3969,3970,3971,3972,3973,3974,3975,3976,3977,1353,3978, 3979,3980,3981,3982,3983,3984,3985,3986,3987,3988,3989,3990,3991,1354,3992,3993, 3994,3995,3996,3997,3998,3999,4000,4001,4002,4003,4004,4005,4006,4007,4008,4009, 4010,4011,4012,4013,4014,4015,4016,4017,4018,4019,4020,4021,4022,4023,1355,4024, 4025,4026,4027,4028,4029,4030,4031,4032,4033,4034,4035,4036,4037,4038,4039,4040, 1605,4041,4042,4043,4044,4045,4046,4047,4048,4049,4050,4051,4052,4053,4054,4055, 4056,4057,4058,4059,4060,1606,4061,4062,4063,4064,1607,4065,4066,4067,4068,4069, 4070,4071,4072,4073,4074,4075,4076,1194,4077,4078,1608,4079,4080,4081,4082,4083, 4084,4085,4086,4087,1609,4088,4089,4090,4091,4092,4093,4094,4095,4096,4097,4098, 4099,4100,4101,4102,4103,4104,4105,4106,4107,4108,1259,4109,4110,4111,4112,4113, 4114,4115,4116,4117,4118,4119,4120,4121,4122,4123,4124,1195,4125,4126,4127,1610, 4128,4129,4130,4131,4132,4133,4134,4135,4136,4137,1356,4138,4139,4140,4141,4142, 4143,4144,1611,4145,4146,4147,4148,4149,4150,4151,4152,4153,4154,4155,4156,4157, 4158,4159,4160,4161,4162,4163,4164,4165,4166,4167,4168,4169,4170,4171,4172,4173, 4174,4175,4176,4177,4178,4179,4180,4181,4182,4183,4184,4185,4186,4187,4188,4189, 4190,4191,4192,4193,4194,4195,4196,4197,4198,4199,4200,4201,4202,4203,4204,4205, 4206,4207,4208,4209,4210,4211,4212,4213,4214,4215,4216,4217,4218,4219,1612,4220, 4221,4222,4223,4224,4225,4226,4227,1357,4228,1613,4229,4230,4231,4232,4233,4234, 4235,4236,4237,4238,4239,4240,4241,4242,4243,1614,4244,4245,4246,4247,4248,4249, 4250,4251,4252,4253,4254,4255,4256,4257,4258,4259,4260,4261,4262,4263,4264,4265, 4266,4267,4268,4269,4270,1196,1358,4271,4272,4273,4274,4275,4276,4277,4278,4279, 4280,4281,4282,4283,4284,4285,4286,4287,1615,4288,4289,4290,4291,4292,4293,4294, 4295,4296,4297,4298,4299,4300,4301,4302,4303,4304,4305,4306,4307,4308,4309,4310, 4311,4312,4313,4314,4315,4316,4317,4318,4319,4320,4321,4322,4323,4324,4325,4326, 4327,4328,4329,4330,4331,4332,4333,4334,1616,4335,4336,4337,4338,4339,4340,4341, 4342,4343,4344,4345,4346,4347,4348,4349,4350,4351,4352,4353,4354,4355,4356,4357, 4358,4359,4360,1617,4361,4362,4363,4364,4365,1618,4366,4367,4368,4369,4370,4371, 4372,4373,4374,4375,4376,4377,4378,4379,4380,4381,4382,4383,4384,4385,4386,4387, 4388,4389,4390,4391,4392,4393,4394,4395,4396,4397,4398,4399,4400,4401,4402,4403, 4404,4405,4406,4407,4408,4409,4410,4411,4412,4413,4414,4415,4416,1619,4417,4418, 4419,4420,4421,4422,4423,4424,4425,1112,4426,4427,4428,4429,4430,1620,4431,4432, 4433,4434,4435,4436,4437,4438,4439,4440,4441,4442,1260,1261,4443,4444,4445,4446, 4447,4448,4449,4450,4451,4452,4453,4454,4455,1359,4456,4457,4458,4459,4460,4461, 4462,4463,4464,4465,1621,4466,4467,4468,4469,4470,4471,4472,4473,4474,4475,4476, 4477,4478,4479,4480,4481,4482,4483,4484,4485,4486,4487,4488,4489,1055,4490,4491, 4492,4493,4494,4495,4496,4497,4498,4499,4500,4501,4502,4503,4504,4505,4506,4507, 4508,4509,4510,4511,4512,4513,4514,4515,4516,4517,4518,1622,4519,4520,4521,1623, 4522,4523,4524,4525,4526,4527,4528,4529,4530,4531,4532,4533,4534,4535,1360,4536, 4537,4538,4539,4540,4541,4542,4543, 975,4544,4545,4546,4547,4548,4549,4550,4551, 4552,4553,4554,4555,4556,4557,4558,4559,4560,4561,4562,4563,4564,4565,4566,4567, 4568,4569,4570,4571,1624,4572,4573,4574,4575,4576,1625,4577,4578,4579,4580,4581, 4582,4583,4584,1626,4585,4586,4587,4588,4589,4590,4591,4592,4593,4594,4595,1627, 4596,4597,4598,4599,4600,4601,4602,4603,4604,4605,4606,4607,4608,4609,4610,4611, 4612,4613,4614,4615,1628,4616,4617,4618,4619,4620,4621,4622,4623,4624,4625,4626, 4627,4628,4629,4630,4631,4632,4633,4634,4635,4636,4637,4638,4639,4640,4641,4642, 4643,4644,4645,4646,4647,4648,4649,1361,4650,4651,4652,4653,4654,4655,4656,4657, 4658,4659,4660,4661,1362,4662,4663,4664,4665,4666,4667,4668,4669,4670,4671,4672, 4673,4674,4675,4676,4677,4678,4679,4680,4681,4682,1629,4683,4684,4685,4686,4687, 1630,4688,4689,4690,4691,1153,4692,4693,4694,1113,4695,4696,4697,4698,4699,4700, 4701,4702,4703,4704,4705,4706,4707,4708,4709,4710,4711,1197,4712,4713,4714,4715, 4716,4717,4718,4719,4720,4721,4722,4723,4724,4725,4726,4727,4728,4729,4730,4731, 4732,4733,4734,4735,1631,4736,1632,4737,4738,4739,4740,4741,4742,4743,4744,1633, 4745,4746,4747,4748,4749,1262,4750,4751,4752,4753,4754,1363,4755,4756,4757,4758, 4759,4760,4761,4762,4763,4764,4765,4766,4767,4768,1634,4769,4770,4771,4772,4773, 4774,4775,4776,4777,4778,1635,4779,4780,4781,4782,4783,4784,4785,4786,4787,4788, 4789,1636,4790,4791,4792,4793,4794,4795,4796,4797,4798,4799,4800,4801,4802,4803, 4804,4805,4806,1637,4807,4808,4809,1638,4810,4811,4812,4813,4814,4815,4816,4817, 4818,1639,4819,4820,4821,4822,4823,4824,4825,4826,4827,4828,4829,4830,4831,4832, 4833,1077,4834,4835,4836,4837,4838,4839,4840,4841,4842,4843,4844,4845,4846,4847, 4848,4849,4850,4851,4852,4853,4854,4855,4856,4857,4858,4859,4860,4861,4862,4863, 4864,4865,4866,4867,4868,4869,4870,4871,4872,4873,4874,4875,4876,4877,4878,4879, 4880,4881,4882,4883,1640,4884,4885,1641,4886,4887,4888,4889,4890,4891,4892,4893, 4894,4895,4896,4897,4898,4899,4900,4901,4902,4903,4904,4905,4906,4907,4908,4909, 4910,4911,1642,4912,4913,4914,1364,4915,4916,4917,4918,4919,4920,4921,4922,4923, 4924,4925,4926,4927,4928,4929,4930,4931,1643,4932,4933,4934,4935,4936,4937,4938, 4939,4940,4941,4942,4943,4944,4945,4946,4947,4948,4949,4950,4951,4952,4953,4954, 4955,4956,4957,4958,4959,4960,4961,4962,4963,4964,4965,4966,4967,4968,4969,4970, 4971,4972,4973,4974,4975,4976,4977,4978,4979,4980,1644,4981,4982,4983,4984,1645, 4985,4986,1646,4987,4988,4989,4990,4991,4992,4993,4994,4995,4996,4997,4998,4999, 5000,5001,5002,5003,5004,5005,1647,5006,1648,5007,5008,5009,5010,5011,5012,1078, 5013,5014,5015,5016,5017,5018,5019,5020,5021,5022,5023,5024,5025,5026,5027,5028, 1365,5029,5030,5031,5032,5033,5034,5035,5036,5037,5038,5039,1649,5040,5041,5042, 5043,5044,5045,1366,5046,5047,5048,5049,5050,5051,5052,5053,5054,5055,1650,5056, 5057,5058,5059,5060,5061,5062,5063,5064,5065,5066,5067,5068,5069,5070,5071,5072, 5073,5074,5075,5076,5077,1651,5078,5079,5080,5081,5082,5083,5084,5085,5086,5087, 5088,5089,5090,5091,5092,5093,5094,5095,5096,5097,5098,5099,5100,5101,5102,5103, 5104,5105,5106,5107,5108,5109,5110,1652,5111,5112,5113,5114,5115,5116,5117,5118, 1367,5119,5120,5121,5122,5123,5124,5125,5126,5127,5128,5129,1653,5130,5131,5132, 5133,5134,5135,5136,5137,5138,5139,5140,5141,5142,5143,5144,5145,5146,5147,5148, 5149,1368,5150,1654,5151,1369,5152,5153,5154,5155,5156,5157,5158,5159,5160,5161, 5162,5163,5164,5165,5166,5167,5168,5169,5170,5171,5172,5173,5174,5175,5176,5177, 5178,1370,5179,5180,5181,5182,5183,5184,5185,5186,5187,5188,5189,5190,5191,5192, 5193,5194,5195,5196,5197,5198,1655,5199,5200,5201,5202,1656,5203,5204,5205,5206, 1371,5207,1372,5208,5209,5210,5211,1373,5212,5213,1374,5214,5215,5216,5217,5218, 5219,5220,5221,5222,5223,5224,5225,5226,5227,5228,5229,5230,5231,5232,5233,5234, 5235,5236,5237,5238,5239,5240,5241,5242,5243,5244,5245,5246,5247,1657,5248,5249, 5250,5251,1658,1263,5252,5253,5254,5255,5256,1375,5257,5258,5259,5260,5261,5262, 5263,5264,5265,5266,5267,5268,5269,5270,5271,5272,5273,5274,5275,5276,5277,5278, 5279,5280,5281,5282,5283,1659,5284,5285,5286,5287,5288,5289,5290,5291,5292,5293, 5294,5295,5296,5297,5298,5299,5300,1660,5301,5302,5303,5304,5305,5306,5307,5308, 5309,5310,5311,5312,5313,5314,5315,5316,5317,5318,5319,5320,5321,1376,5322,5323, 5324,5325,5326,5327,5328,5329,5330,5331,5332,5333,1198,5334,5335,5336,5337,5338, 5339,5340,5341,5342,5343,1661,5344,5345,5346,5347,5348,5349,5350,5351,5352,5353, 5354,5355,5356,5357,5358,5359,5360,5361,5362,5363,5364,5365,5366,5367,5368,5369, 5370,5371,5372,5373,5374,5375,5376,5377,5378,5379,5380,5381,5382,5383,5384,5385, 5386,5387,5388,5389,5390,5391,5392,5393,5394,5395,5396,5397,5398,1264,5399,5400, 5401,5402,5403,5404,5405,5406,5407,5408,5409,5410,5411,5412,1662,5413,5414,5415, 5416,1663,5417,5418,5419,5420,5421,5422,5423,5424,5425,5426,5427,5428,5429,5430, 5431,5432,5433,5434,5435,5436,5437,5438,1664,5439,5440,5441,5442,5443,5444,5445, 5446,5447,5448,5449,5450,5451,5452,5453,5454,5455,5456,5457,5458,5459,5460,5461, 5462,5463,5464,5465,5466,5467,5468,5469,5470,5471,5472,5473,5474,5475,5476,5477, 5478,1154,5479,5480,5481,5482,5483,5484,5485,1665,5486,5487,5488,5489,5490,5491, 5492,5493,5494,5495,5496,5497,5498,5499,5500,5501,5502,5503,5504,5505,5506,5507, 5508,5509,5510,5511,5512,5513,5514,5515,5516,5517,5518,5519,5520,5521,5522,5523, 5524,5525,5526,5527,5528,5529,5530,5531,5532,5533,5534,5535,5536,5537,5538,5539, 5540,5541,5542,5543,5544,5545,5546,5547,5548,1377,5549,5550,5551,5552,5553,5554, 5555,5556,5557,5558,5559,5560,5561,5562,5563,5564,5565,5566,5567,5568,5569,5570, 1114,5571,5572,5573,5574,5575,5576,5577,5578,5579,5580,5581,5582,5583,5584,5585, 5586,5587,5588,5589,5590,5591,5592,1378,5593,5594,5595,5596,5597,5598,5599,5600, 5601,5602,5603,5604,5605,5606,5607,5608,5609,5610,5611,5612,5613,5614,1379,5615, 5616,5617,5618,5619,5620,5621,5622,5623,5624,5625,5626,5627,5628,5629,5630,5631, 5632,5633,5634,1380,5635,5636,5637,5638,5639,5640,5641,5642,5643,5644,5645,5646, 5647,5648,5649,1381,1056,5650,5651,5652,5653,5654,5655,5656,5657,5658,5659,5660, 1666,5661,5662,5663,5664,5665,5666,5667,5668,1667,5669,1668,5670,5671,5672,5673, 5674,5675,5676,5677,5678,1155,5679,5680,5681,5682,5683,5684,5685,5686,5687,5688, 5689,5690,5691,5692,5693,5694,5695,5696,5697,5698,1669,5699,5700,5701,5702,5703, 5704,5705,1670,5706,5707,5708,5709,5710,1671,5711,5712,5713,5714,1382,5715,5716, 5717,5718,5719,5720,5721,5722,5723,5724,5725,1672,5726,5727,1673,1674,5728,5729, 5730,5731,5732,5733,5734,5735,5736,1675,5737,5738,5739,5740,5741,5742,5743,5744, 1676,5745,5746,5747,5748,5749,5750,5751,1383,5752,5753,5754,5755,5756,5757,5758, 5759,5760,5761,5762,5763,5764,5765,5766,5767,5768,1677,5769,5770,5771,5772,5773, 1678,5774,5775,5776, 998,5777,5778,5779,5780,5781,5782,5783,5784,5785,1384,5786, 5787,5788,5789,5790,5791,5792,5793,5794,5795,5796,5797,5798,5799,5800,1679,5801, 5802,5803,1115,1116,5804,5805,5806,5807,5808,5809,5810,5811,5812,5813,5814,5815, 5816,5817,5818,5819,5820,5821,5822,5823,5824,5825,5826,5827,5828,5829,5830,5831, 5832,5833,5834,5835,5836,5837,5838,5839,5840,5841,5842,5843,5844,5845,5846,5847, 5848,5849,5850,5851,5852,5853,5854,5855,1680,5856,5857,5858,5859,5860,5861,5862, 5863,5864,1681,5865,5866,5867,1682,5868,5869,5870,5871,5872,5873,5874,5875,5876, 5877,5878,5879,1683,5880,1684,5881,5882,5883,5884,1685,5885,5886,5887,5888,5889, 5890,5891,5892,5893,5894,5895,5896,5897,5898,5899,5900,5901,5902,5903,5904,5905, 5906,5907,1686,5908,5909,5910,5911,5912,5913,5914,5915,5916,5917,5918,5919,5920, 5921,5922,5923,5924,5925,5926,5927,5928,5929,5930,5931,5932,5933,5934,5935,1687, 5936,5937,5938,5939,5940,5941,5942,5943,5944,5945,5946,5947,5948,5949,5950,5951, 5952,1688,1689,5953,1199,5954,5955,5956,5957,5958,5959,5960,5961,1690,5962,5963, 5964,5965,5966,5967,5968,5969,5970,5971,5972,5973,5974,5975,5976,5977,5978,5979, 5980,5981,1385,5982,1386,5983,5984,5985,5986,5987,5988,5989,5990,5991,5992,5993, 5994,5995,5996,5997,5998,5999,6000,6001,6002,6003,6004,6005,6006,6007,6008,6009, 6010,6011,6012,6013,6014,6015,6016,6017,6018,6019,6020,6021,6022,6023,6024,6025, 6026,6027,1265,6028,6029,1691,6030,6031,6032,6033,6034,6035,6036,6037,6038,6039, 6040,6041,6042,6043,6044,6045,6046,6047,6048,6049,6050,6051,6052,6053,6054,6055, 6056,6057,6058,6059,6060,6061,6062,6063,6064,6065,6066,6067,6068,6069,6070,6071, 6072,6073,6074,6075,6076,6077,6078,6079,6080,6081,6082,6083,6084,1692,6085,6086, 6087,6088,6089,6090,6091,6092,6093,6094,6095,6096,6097,6098,6099,6100,6101,6102, 6103,6104,6105,6106,6107,6108,6109,6110,6111,6112,6113,6114,6115,6116,6117,6118, 6119,6120,6121,6122,6123,6124,6125,6126,6127,6128,6129,6130,6131,1693,6132,6133, 6134,6135,6136,1694,6137,6138,6139,6140,6141,1695,6142,6143,6144,6145,6146,6147, 6148,6149,6150,6151,6152,6153,6154,6155,6156,6157,6158,6159,6160,6161,6162,6163, 6164,6165,6166,6167,6168,6169,6170,6171,6172,6173,6174,6175,6176,6177,6178,6179, 6180,6181,6182,6183,6184,6185,1696,6186,6187,6188,6189,6190,6191,6192,6193,6194, 6195,6196,6197,6198,6199,6200,6201,6202,6203,6204,6205,6206,6207,6208,6209,6210, 6211,6212,6213,6214,6215,6216,6217,6218,6219,1697,6220,6221,6222,6223,6224,6225, 6226,6227,6228,6229,6230,6231,6232,6233,6234,6235,6236,6237,6238,6239,6240,6241, 6242,6243,6244,6245,6246,6247,6248,6249,6250,6251,6252,6253,1698,6254,6255,6256, 6257,6258,6259,6260,6261,6262,6263,1200,6264,6265,6266,6267,6268,6269,6270,6271, #1024 6272,6273,6274,6275,6276,6277,6278,6279,6280,6281,6282,6283,6284,6285,6286,6287, 6288,6289,6290,6291,6292,6293,6294,6295,6296,6297,6298,6299,6300,6301,6302,1699, 6303,6304,1700,6305,6306,6307,6308,6309,6310,6311,6312,6313,6314,6315,6316,6317, 6318,6319,6320,6321,6322,6323,6324,6325,6326,6327,6328,6329,6330,6331,6332,6333, 6334,6335,6336,6337,6338,6339,1701,6340,6341,6342,6343,6344,1387,6345,6346,6347, 6348,6349,6350,6351,6352,6353,6354,6355,6356,6357,6358,6359,6360,6361,6362,6363, 6364,6365,6366,6367,6368,6369,6370,6371,6372,6373,6374,6375,6376,6377,6378,6379, 6380,6381,6382,6383,6384,6385,6386,6387,6388,6389,6390,6391,6392,6393,6394,6395, 6396,6397,6398,6399,6400,6401,6402,6403,6404,6405,6406,6407,6408,6409,6410,6411, 6412,6413,1702,6414,6415,6416,6417,6418,6419,6420,6421,6422,1703,6423,6424,6425, 6426,6427,6428,6429,6430,6431,6432,6433,6434,6435,6436,6437,6438,1704,6439,6440, 6441,6442,6443,6444,6445,6446,6447,6448,6449,6450,6451,6452,6453,6454,6455,6456, 6457,6458,6459,6460,6461,6462,6463,6464,6465,6466,6467,6468,6469,6470,6471,6472, 6473,6474,6475,6476,6477,6478,6479,6480,6481,6482,6483,6484,6485,6486,6487,6488, 6489,6490,6491,6492,6493,6494,6495,6496,6497,6498,6499,6500,6501,6502,6503,1266, 6504,6505,6506,6507,6508,6509,6510,6511,6512,6513,6514,6515,6516,6517,6518,6519, 6520,6521,6522,6523,6524,6525,6526,6527,6528,6529,6530,6531,6532,6533,6534,6535, 6536,6537,6538,6539,6540,6541,6542,6543,6544,6545,6546,6547,6548,6549,6550,6551, 1705,1706,6552,6553,6554,6555,6556,6557,6558,6559,6560,6561,6562,6563,6564,6565, 6566,6567,6568,6569,6570,6571,6572,6573,6574,6575,6576,6577,6578,6579,6580,6581, 6582,6583,6584,6585,6586,6587,6588,6589,6590,6591,6592,6593,6594,6595,6596,6597, 6598,6599,6600,6601,6602,6603,6604,6605,6606,6607,6608,6609,6610,6611,6612,6613, 6614,6615,6616,6617,6618,6619,6620,6621,6622,6623,6624,6625,6626,6627,6628,6629, 6630,6631,6632,6633,6634,6635,6636,6637,1388,6638,6639,6640,6641,6642,6643,6644, 1707,6645,6646,6647,6648,6649,6650,6651,6652,6653,6654,6655,6656,6657,6658,6659, 6660,6661,6662,6663,1708,6664,6665,6666,6667,6668,6669,6670,6671,6672,6673,6674, 1201,6675,6676,6677,6678,6679,6680,6681,6682,6683,6684,6685,6686,6687,6688,6689, 6690,6691,6692,6693,6694,6695,6696,6697,6698,6699,6700,6701,6702,6703,6704,6705, 6706,6707,6708,6709,6710,6711,6712,6713,6714,6715,6716,6717,6718,6719,6720,6721, 6722,6723,6724,6725,1389,6726,6727,6728,6729,6730,6731,6732,6733,6734,6735,6736, 1390,1709,6737,6738,6739,6740,6741,6742,1710,6743,6744,6745,6746,1391,6747,6748, 6749,6750,6751,6752,6753,6754,6755,6756,6757,1392,6758,6759,6760,6761,6762,6763, 6764,6765,6766,6767,6768,6769,6770,6771,6772,6773,6774,6775,6776,6777,6778,6779, 6780,1202,6781,6782,6783,6784,6785,6786,6787,6788,6789,6790,6791,6792,6793,6794, 6795,6796,6797,6798,6799,6800,6801,6802,6803,6804,6805,6806,6807,6808,6809,1711, 6810,6811,6812,6813,6814,6815,6816,6817,6818,6819,6820,6821,6822,6823,6824,6825, 6826,6827,6828,6829,6830,6831,6832,6833,6834,6835,6836,1393,6837,6838,6839,6840, 6841,6842,6843,6844,6845,6846,6847,6848,6849,6850,6851,6852,6853,6854,6855,6856, 6857,6858,6859,6860,6861,6862,6863,6864,6865,6866,6867,6868,6869,6870,6871,6872, 6873,6874,6875,6876,6877,6878,6879,6880,6881,6882,6883,6884,6885,6886,6887,6888, 6889,6890,6891,6892,6893,6894,6895,6896,6897,6898,6899,6900,6901,6902,1712,6903, 6904,6905,6906,6907,6908,6909,6910,1713,6911,6912,6913,6914,6915,6916,6917,6918, 6919,6920,6921,6922,6923,6924,6925,6926,6927,6928,6929,6930,6931,6932,6933,6934, 6935,6936,6937,6938,6939,6940,6941,6942,6943,6944,6945,6946,6947,6948,6949,6950, 6951,6952,6953,6954,6955,6956,6957,6958,6959,6960,6961,6962,6963,6964,6965,6966, 6967,6968,6969,6970,6971,6972,6973,6974,1714,6975,6976,6977,6978,6979,6980,6981, 6982,6983,6984,6985,6986,6987,6988,1394,6989,6990,6991,6992,6993,6994,6995,6996, 6997,6998,6999,7000,1715,7001,7002,7003,7004,7005,7006,7007,7008,7009,7010,7011, 7012,7013,7014,7015,7016,7017,7018,7019,7020,7021,7022,7023,7024,7025,7026,7027, 7028,1716,7029,7030,7031,7032,7033,7034,7035,7036,7037,7038,7039,7040,7041,7042, 7043,7044,7045,7046,7047,7048,7049,7050,7051,7052,7053,7054,7055,7056,7057,7058, 7059,7060,7061,7062,7063,7064,7065,7066,7067,7068,7069,7070,7071,7072,7073,7074, 7075,7076,7077,7078,7079,7080,7081,7082,7083,7084,7085,7086,7087,7088,7089,7090, 7091,7092,7093,7094,7095,7096,7097,7098,7099,7100,7101,7102,7103,7104,7105,7106, 7107,7108,7109,7110,7111,7112,7113,7114,7115,7116,7117,7118,7119,7120,7121,7122, 7123,7124,7125,7126,7127,7128,7129,7130,7131,7132,7133,7134,7135,7136,7137,7138, 7139,7140,7141,7142,7143,7144,7145,7146,7147,7148,7149,7150,7151,7152,7153,7154, 7155,7156,7157,7158,7159,7160,7161,7162,7163,7164,7165,7166,7167,7168,7169,7170, 7171,7172,7173,7174,7175,7176,7177,7178,7179,7180,7181,7182,7183,7184,7185,7186, 7187,7188,7189,7190,7191,7192,7193,7194,7195,7196,7197,7198,7199,7200,7201,7202, 7203,7204,7205,7206,7207,1395,7208,7209,7210,7211,7212,7213,1717,7214,7215,7216, 7217,7218,7219,7220,7221,7222,7223,7224,7225,7226,7227,7228,7229,7230,7231,7232, 7233,7234,7235,7236,7237,7238,7239,7240,7241,7242,7243,7244,7245,7246,7247,7248, 7249,7250,7251,7252,7253,7254,7255,7256,7257,7258,7259,7260,7261,7262,7263,7264, 7265,7266,7267,7268,7269,7270,7271,7272,7273,7274,7275,7276,7277,7278,7279,7280, 7281,7282,7283,7284,7285,7286,7287,7288,7289,7290,7291,7292,7293,7294,7295,7296, 7297,7298,7299,7300,7301,7302,7303,7304,7305,7306,7307,7308,7309,7310,7311,7312, 7313,1718,7314,7315,7316,7317,7318,7319,7320,7321,7322,7323,7324,7325,7326,7327, 7328,7329,7330,7331,7332,7333,7334,7335,7336,7337,7338,7339,7340,7341,7342,7343, 7344,7345,7346,7347,7348,7349,7350,7351,7352,7353,7354,7355,7356,7357,7358,7359, 7360,7361,7362,7363,7364,7365,7366,7367,7368,7369,7370,7371,7372,7373,7374,7375, 7376,7377,7378,7379,7380,7381,7382,7383,7384,7385,7386,7387,7388,7389,7390,7391, 7392,7393,7394,7395,7396,7397,7398,7399,7400,7401,7402,7403,7404,7405,7406,7407, 7408,7409,7410,7411,7412,7413,7414,7415,7416,7417,7418,7419,7420,7421,7422,7423, 7424,7425,7426,7427,7428,7429,7430,7431,7432,7433,7434,7435,7436,7437,7438,7439, 7440,7441,7442,7443,7444,7445,7446,7447,7448,7449,7450,7451,7452,7453,7454,7455, 7456,7457,7458,7459,7460,7461,7462,7463,7464,7465,7466,7467,7468,7469,7470,7471, 7472,7473,7474,7475,7476,7477,7478,7479,7480,7481,7482,7483,7484,7485,7486,7487, 7488,7489,7490,7491,7492,7493,7494,7495,7496,7497,7498,7499,7500,7501,7502,7503, 7504,7505,7506,7507,7508,7509,7510,7511,7512,7513,7514,7515,7516,7517,7518,7519, 7520,7521,7522,7523,7524,7525,7526,7527,7528,7529,7530,7531,7532,7533,7534,7535, 7536,7537,7538,7539,7540,7541,7542,7543,7544,7545,7546,7547,7548,7549,7550,7551, 7552,7553,7554,7555,7556,7557,7558,7559,7560,7561,7562,7563,7564,7565,7566,7567, 7568,7569,7570,7571,7572,7573,7574,7575,7576,7577,7578,7579,7580,7581,7582,7583, 7584,7585,7586,7587,7588,7589,7590,7591,7592,7593,7594,7595,7596,7597,7598,7599, 7600,7601,7602,7603,7604,7605,7606,7607,7608,7609,7610,7611,7612,7613,7614,7615, 7616,7617,7618,7619,7620,7621,7622,7623,7624,7625,7626,7627,7628,7629,7630,7631, 7632,7633,7634,7635,7636,7637,7638,7639,7640,7641,7642,7643,7644,7645,7646,7647, 7648,7649,7650,7651,7652,7653,7654,7655,7656,7657,7658,7659,7660,7661,7662,7663, 7664,7665,7666,7667,7668,7669,7670,7671,7672,7673,7674,7675,7676,7677,7678,7679, 7680,7681,7682,7683,7684,7685,7686,7687,7688,7689,7690,7691,7692,7693,7694,7695, 7696,7697,7698,7699,7700,7701,7702,7703,7704,7705,7706,7707,7708,7709,7710,7711, 7712,7713,7714,7715,7716,7717,7718,7719,7720,7721,7722,7723,7724,7725,7726,7727, 7728,7729,7730,7731,7732,7733,7734,7735,7736,7737,7738,7739,7740,7741,7742,7743, 7744,7745,7746,7747,7748,7749,7750,7751,7752,7753,7754,7755,7756,7757,7758,7759, 7760,7761,7762,7763,7764,7765,7766,7767,7768,7769,7770,7771,7772,7773,7774,7775, 7776,7777,7778,7779,7780,7781,7782,7783,7784,7785,7786,7787,7788,7789,7790,7791, 7792,7793,7794,7795,7796,7797,7798,7799,7800,7801,7802,7803,7804,7805,7806,7807, 7808,7809,7810,7811,7812,7813,7814,7815,7816,7817,7818,7819,7820,7821,7822,7823, 7824,7825,7826,7827,7828,7829,7830,7831,7832,7833,7834,7835,7836,7837,7838,7839, 7840,7841,7842,7843,7844,7845,7846,7847,7848,7849,7850,7851,7852,7853,7854,7855, 7856,7857,7858,7859,7860,7861,7862,7863,7864,7865,7866,7867,7868,7869,7870,7871, 7872,7873,7874,7875,7876,7877,7878,7879,7880,7881,7882,7883,7884,7885,7886,7887, 7888,7889,7890,7891,7892,7893,7894,7895,7896,7897,7898,7899,7900,7901,7902,7903, 7904,7905,7906,7907,7908,7909,7910,7911,7912,7913,7914,7915,7916,7917,7918,7919, 7920,7921,7922,7923,7924,7925,7926,7927,7928,7929,7930,7931,7932,7933,7934,7935, 7936,7937,7938,7939,7940,7941,7942,7943,7944,7945,7946,7947,7948,7949,7950,7951, 7952,7953,7954,7955,7956,7957,7958,7959,7960,7961,7962,7963,7964,7965,7966,7967, 7968,7969,7970,7971,7972,7973,7974,7975,7976,7977,7978,7979,7980,7981,7982,7983, 7984,7985,7986,7987,7988,7989,7990,7991,7992,7993,7994,7995,7996,7997,7998,7999, 8000,8001,8002,8003,8004,8005,8006,8007,8008,8009,8010,8011,8012,8013,8014,8015, 8016,8017,8018,8019,8020,8021,8022,8023,8024,8025,8026,8027,8028,8029,8030,8031, 8032,8033,8034,8035,8036,8037,8038,8039,8040,8041,8042,8043,8044,8045,8046,8047, 8048,8049,8050,8051,8052,8053,8054,8055,8056,8057,8058,8059,8060,8061,8062,8063, 8064,8065,8066,8067,8068,8069,8070,8071,8072,8073,8074,8075,8076,8077,8078,8079, 8080,8081,8082,8083,8084,8085,8086,8087,8088,8089,8090,8091,8092,8093,8094,8095, 8096,8097,8098,8099,8100,8101,8102,8103,8104,8105,8106,8107,8108,8109,8110,8111, 8112,8113,8114,8115,8116,8117,8118,8119,8120,8121,8122,8123,8124,8125,8126,8127, 8128,8129,8130,8131,8132,8133,8134,8135,8136,8137,8138,8139,8140,8141,8142,8143, 8144,8145,8146,8147,8148,8149,8150,8151,8152,8153,8154,8155,8156,8157,8158,8159, 8160,8161,8162,8163,8164,8165,8166,8167,8168,8169,8170,8171,8172,8173,8174,8175, 8176,8177,8178,8179,8180,8181,8182,8183,8184,8185,8186,8187,8188,8189,8190,8191, 8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8203,8204,8205,8206,8207, 8208,8209,8210,8211,8212,8213,8214,8215,8216,8217,8218,8219,8220,8221,8222,8223, 8224,8225,8226,8227,8228,8229,8230,8231,8232,8233,8234,8235,8236,8237,8238,8239, 8240,8241,8242,8243,8244,8245,8246,8247,8248,8249,8250,8251,8252,8253,8254,8255, 8256,8257,8258,8259,8260,8261,8262,8263,8264,8265,8266,8267,8268,8269,8270,8271, 8272,8273,8274,8275,8276,8277,8278,8279,8280,8281,8282,8283,8284,8285,8286,8287, 8288,8289,8290,8291,8292,8293,8294,8295,8296,8297,8298,8299,8300,8301,8302,8303, 8304,8305,8306,8307,8308,8309,8310,8311,8312,8313,8314,8315,8316,8317,8318,8319, 8320,8321,8322,8323,8324,8325,8326,8327,8328,8329,8330,8331,8332,8333,8334,8335, 8336,8337,8338,8339,8340,8341,8342,8343,8344,8345,8346,8347,8348,8349,8350,8351, 8352,8353,8354,8355,8356,8357,8358,8359,8360,8361,8362,8363,8364,8365,8366,8367, 8368,8369,8370,8371,8372,8373,8374,8375,8376,8377,8378,8379,8380,8381,8382,8383, 8384,8385,8386,8387,8388,8389,8390,8391,8392,8393,8394,8395,8396,8397,8398,8399, 8400,8401,8402,8403,8404,8405,8406,8407,8408,8409,8410,8411,8412,8413,8414,8415, 8416,8417,8418,8419,8420,8421,8422,8423,8424,8425,8426,8427,8428,8429,8430,8431, 8432,8433,8434,8435,8436,8437,8438,8439,8440,8441,8442,8443,8444,8445,8446,8447, 8448,8449,8450,8451,8452,8453,8454,8455,8456,8457,8458,8459,8460,8461,8462,8463, 8464,8465,8466,8467,8468,8469,8470,8471,8472,8473,8474,8475,8476,8477,8478,8479, 8480,8481,8482,8483,8484,8485,8486,8487,8488,8489,8490,8491,8492,8493,8494,8495, 8496,8497,8498,8499,8500,8501,8502,8503,8504,8505,8506,8507,8508,8509,8510,8511, 8512,8513,8514,8515,8516,8517,8518,8519,8520,8521,8522,8523,8524,8525,8526,8527, 8528,8529,8530,8531,8532,8533,8534,8535,8536,8537,8538,8539,8540,8541,8542,8543, 8544,8545,8546,8547,8548,8549,8550,8551,8552,8553,8554,8555,8556,8557,8558,8559, 8560,8561,8562,8563,8564,8565,8566,8567,8568,8569,8570,8571,8572,8573,8574,8575, 8576,8577,8578,8579,8580,8581,8582,8583,8584,8585,8586,8587,8588,8589,8590,8591, 8592,8593,8594,8595,8596,8597,8598,8599,8600,8601,8602,8603,8604,8605,8606,8607, 8608,8609,8610,8611,8612,8613,8614,8615,8616,8617,8618,8619,8620,8621,8622,8623, 8624,8625,8626,8627,8628,8629,8630,8631,8632,8633,8634,8635,8636,8637,8638,8639, 8640,8641,8642,8643,8644,8645,8646,8647,8648,8649,8650,8651,8652,8653,8654,8655, 8656,8657,8658,8659,8660,8661,8662,8663,8664,8665,8666,8667,8668,8669,8670,8671, 8672,8673,8674,8675,8676,8677,8678,8679,8680,8681,8682,8683,8684,8685,8686,8687, 8688,8689,8690,8691,8692,8693,8694,8695,8696,8697,8698,8699,8700,8701,8702,8703, 8704,8705,8706,8707,8708,8709,8710,8711,8712,8713,8714,8715,8716,8717,8718,8719, 8720,8721,8722,8723,8724,8725,8726,8727,8728,8729,8730,8731,8732,8733,8734,8735, 8736,8737,8738,8739,8740,8741) # flake8: noqa
mit
Qinusty/rethinkdb
test/interface/detect_netsplit.py
21
2877
#!/usr/bin/env python # Copyright 2010-2015 RethinkDB, all rights reserved. import os, sys, time sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir, 'common'))) import driver, scenario_common, utils, vcoptparse op = vcoptparse.OptParser() scenario_common.prepare_option_parser_mode_flags(op) _, command_prefix, serve_options = scenario_common.parse_mode_flags(op.parse(sys.argv)) r = utils.import_python_driver() with driver.Metacluster() as metacluster: cluster1 = driver.Cluster(metacluster) utils.print_with_time("Spinning up two processes") serverA = driver.Process(cluster1, console_output=True, command_prefix=command_prefix, extra_options=serve_options) serverB = driver.Process(cluster1, console_output=True, command_prefix=command_prefix, extra_options=serve_options) cluster1.wait_until_ready() cluster1.check() utils.print_with_time("Establishing ReQL connections") connA = r.connect(host=serverA.host, port=serverA.driver_port) connB = r.connect(host=serverB.host, port=serverB.driver_port) utils.print_with_time("Checking that both servers see each other") serverAOutput = list(r.db('rethinkdb').table('server_status').pluck('id', 'name').run(connA)) serverBOutput = list(r.db('rethinkdb').table('server_status').pluck('id', 'name').run(connB)) assert serverAOutput == serverBOutput, 'Output did not match:\n%s\n\tvs.\n%s' % (repr(serverAOutput), repr(serverBOutput)) assert sorted([serverA.uuid, serverB.uuid]) == sorted([x['id'] for x in serverAOutput]) utils.print_with_time("Splitting cluster") cluster2 = driver.Cluster(metacluster) metacluster.move_processes(cluster1, cluster2, [serverB]) utils.print_with_time("Watching up to 40 seconds to see that they detected the netsplit") deadline = time.time() + 40 query = r.db('rethinkdb').table('server_status').count().eq(1) while time.time() < deadline: if all([query.run(connA), query.run(connB)]): break time.sleep(.1) else: assert False, 'Servers did not detect the netsplit after 40 seconds' cluster1.check() cluster2.check() utils.print_with_time("Joining cluster") metacluster.move_processes(cluster2, cluster1, [serverB]) utils.print_with_time("Watching up to 10 seconds to see that they detected the resolution") deadline = time.time() + 10 query = r.db('rethinkdb').table('server_status').count().eq(2) while time.time() < deadline: if all([query.run(connA), query.run(connB)]): break time.sleep(.1) else: assert False, 'Servers did not detect the netsplit resolution after 10 seconds' cluster1.check() cluster2.check() utils.print_with_time("Cleaning up") utils.print_with_time("Done")
agpl-3.0
canard0328/malss
malss/app/error.py
1
1058
# coding: utf-8 from PyQt5.QtWidgets import (QHBoxLayout, QPushButton) from PyQt5.QtCore import QCoreApplication from .content import Content class Error(Content): def __init__(self, parent=None, button_func=None, params=None): super().__init__(parent, 'Error', params) if self.params.lang == 'en': text = ('Unexpected error occured.\n' 'Please exit the application and solve the problem.') else: text = ('予期せぬエラーが発生しました。\n' 'アプリケーションを終了し,問題を解決してください。') self.set_paragraph('Unexpected error', text=text) self.set_paragraph('Traceback log', text=self.params.error) self.vbox.addStretch(1) btn = QPushButton('Exit', self.inner) btn.setStyleSheet('QPushButton{font: bold; font-size: 15pt; background-color: white;};') btn.clicked.connect(QCoreApplication.instance().quit) self.vbox.addWidget(btn)
mit
mohamedhagag/community-addons
hr_loan_management/models/hr_employee.py
1
1557
# -*- coding: utf-8 -*- # Copyright 2016 OpenSynergy Indonesia # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from openerp import models, fields, api class HrEmployee(models.Model): _inherit = "hr.employee" @api.multi @api.depends( "loan_ids", "payment_schedule_ids") def _compute_loan(self): obj_loan = self.env["hr.loan"] obj_schedule = self.env["hr.loan.payment.schedule"] for employee in self: criteria = [ ("employee_id", "=", employee.id), ] loan_criteria = [ ("state", "in", ["active", "done"]) ] + criteria self.loan_count = obj_loan.search_count( loan_criteria) schedule_criteria = [ ("loan_id.state", "in", ["active", "done"]) ] + criteria self.loan_payment_schedule_count = \ obj_schedule.search_count( schedule_criteria) loan_ids = fields.One2many( string="Loan(s)", comodel_name="hr.loan", inverse_name="employee_id", ) payment_schedule_ids = fields.One2many( string="Loan Repayment Schedule(s)", comodel_name="hr.loan.payment.schedule", inverse_name="employee_id", ) loan_count = fields.Integer( string="Loan Count", compute="_compute_loan", ) loan_payment_schedule_count = fields.Integer( string="Loan Repayment Schedule Count", compute="_compute_loan", )
agpl-3.0