repo_name stringlengths 5 100 | path stringlengths 4 294 | copies stringclasses 990
values | size stringlengths 4 7 | content stringlengths 666 1M | license stringclasses 15
values |
|---|---|---|---|---|---|
talkincode/txradius | txradius/openvpn/__init__.py | 1 | 1476 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import random
import time
import ConfigParser
from decimal import Decimal
from txradius import client
from txradius.radius import dictionary
from twisted.python import log
from twisted.python.logfile import DailyLogFile
CONFIG_FILE = '/etc/openvpn/txovpn.conf'
DICTIONARY_FILE = os.path.join(os.path.dirname(client.__file__), "dictionary/ovpn_dictionary")
ACCT_START = 1
ACCT_STOP = 2
ACCT_UPDATE = 3
get_dictionary = lambda : dictionary.Dictionary(DICTIONARY_FILE)
get_challenge = lambda : ''.join(chr(b) for b in [random.SystemRandom().randrange(0, 256) for i in range(16)])
__defconfig__ = dict(
nas_id='txovpn',
nas_coa_port='3799',
nas_addr='127.0.0.1',
radius_addr='127.0.0.1',
radius_auth_port='1812',
radius_acct_port='1813',
radius_secret='secret',
radius_timeout='3',
acct_interval='60',
session_timeout='864000',
logfile='/var/log/txovpn.log',
statusfile='/etc/openvpn/openvpn-status.log',
statusdb='/etc/openvpn/txovpn.db',
client_config_dir="/etc/openvpn/ccd",
server_manage_addr="127.0.0.1:7505",
debug="true",
)
def init_config(cfgfile):
config = ConfigParser.SafeConfigParser(__defconfig__)
config.read(cfgfile)
if config.getboolean('DEFAULT', 'debug'):
log.startLogging(sys.stdout)
else:
log.startLogging(DailyLogFile.fromFullPath(config.get("DEFAULT",'logfile')))
return config
| lgpl-3.0 |
krieger-od/webrtc | tools/barcode_tools/barcode_encoder.py | 43 | 15542 | #!/usr/bin/env python
# Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
#
# Use of this source code is governed by a BSD-style license
# that can be found in the LICENSE file in the root of the source
# tree. An additional intellectual property rights grant can be found
# in the file PATENTS. All contributing project authors may
# be found in the AUTHORS file in the root of the source tree.
import optparse
import os
import sys
import helper_functions
_DEFAULT_BARCODE_WIDTH = 352
_DEFAULT_BARCODES_FILE = 'barcodes.yuv'
def generate_upca_barcodes(number_of_barcodes, barcode_width, barcode_height,
output_directory='.',
path_to_zxing='zxing-read-only'):
"""Generates UPC-A barcodes.
This function generates a number_of_barcodes UPC-A barcodes. The function
calls an example Java encoder from the Zxing library. The barcodes are
generated as PNG images. The width of the barcodes shouldn't be less than 102
pixels because otherwise Zxing can't properly generate the barcodes.
Args:
number_of_barcodes(int): The number of barcodes to generate.
barcode_width(int): Width of barcode in pixels.
barcode_height(int): Height of barcode in pixels.
output_directory(string): Output directory where to store generated
barcodes.
path_to_zxing(string): The path to Zxing.
Return:
(bool): True if the conversion is successful.
"""
base_file_name = os.path.join(output_directory, "barcode_")
jars = _form_jars_string(path_to_zxing)
command_line_encoder = 'com.google.zxing.client.j2se.CommandLineEncoder'
barcode_width = str(barcode_width)
barcode_height = str(barcode_height)
errors = False
for i in range(number_of_barcodes):
suffix = helper_functions.zero_pad(i)
# Barcodes starting from 0
content = helper_functions.zero_pad(i, 11)
output_file_name = base_file_name + suffix + ".png"
command = ["java", "-cp", jars, command_line_encoder,
"--barcode_format=UPC_A", "--height=%s" % barcode_height,
"--width=%s" % barcode_width,
"--output=%s" % (output_file_name), "%s" % (content)]
try:
helper_functions.run_shell_command(
command, fail_msg=('Error during barcode %s generation' % content))
except helper_functions.HelperError as err:
print >> sys.stderr, err
errors = True
return not errors
def convert_png_to_yuv_barcodes(input_directory='.', output_directory='.'):
"""Converts PNG barcodes to YUV barcode images.
This function reads all the PNG files from the input directory which are in
the format frame_xxxx.png, where xxxx is the number of the frame, starting
from 0000. The frames should be consecutive numbers. The output YUV file is
named frame_xxxx.yuv. The function uses ffmpeg to do the conversion.
Args:
input_directory(string): The input direcotry to read the PNG barcodes from.
output_directory(string): The putput directory to write the YUV files to.
Return:
(bool): True if the conversion was without errors.
"""
return helper_functions.perform_action_on_all_files(
input_directory, 'barcode_', 'png', 0, _convert_to_yuv_and_delete,
output_directory=output_directory, pattern='barcode_')
def _convert_to_yuv_and_delete(output_directory, file_name, pattern):
"""Converts a PNG file to a YUV file and deletes the PNG file.
Args:
output_directory(string): The output directory for the YUV file.
file_name(string): The PNG file name.
pattern(string): The file pattern of the PNG/YUV file. The PNG/YUV files are
named patternxx..x.png/yuv, where xx..x are digits starting from 00..0.
Return:
(bool): True upon successful conversion, false otherwise.
"""
# Pattern should be in file name
if not pattern in file_name:
return False
pattern_position = file_name.rfind(pattern)
# Strip the path to the PNG file and replace the png extension with yuv
yuv_file_name = file_name[pattern_position:-3] + 'yuv'
yuv_file_name = os.path.join(output_directory, yuv_file_name)
command = ['ffmpeg', '-i', '%s' % (file_name), '-pix_fmt', 'yuv420p',
'%s' % (yuv_file_name)]
try:
helper_functions.run_shell_command(
command, fail_msg=('Error during PNG to YUV conversion of %s' %
file_name))
os.remove(file_name)
except helper_functions.HelperError as err:
print >> sys.stderr, err
return False
return True
def combine_yuv_frames_into_one_file(output_file_name, input_directory='.'):
"""Combines several YUV frames into one YUV video file.
The function combines the YUV frames from input_directory into one YUV video
file. The frames should be named in the format frame_xxxx.yuv where xxxx
stands for the frame number. The numbers have to be consecutive and start from
0000. The YUV frames are removed after they have been added to the video.
Args:
output_file_name(string): The name of the file to produce.
input_directory(string): The directory from which the YUV frames are read.
Return:
(bool): True if the frame stitching went OK.
"""
output_file = open(output_file_name, "wb")
success = helper_functions.perform_action_on_all_files(
input_directory, 'barcode_', 'yuv', 0, _add_to_file_and_delete,
output_file=output_file)
output_file.close()
return success
def _add_to_file_and_delete(output_file, file_name):
"""Adds the contents of a file to a previously opened file.
Args:
output_file(file): The ouput file, previously opened.
file_name(string): The file name of the file to add to the output file.
Return:
(bool): True if successful, False otherwise.
"""
input_file = open(file_name, "rb")
input_file_contents = input_file.read()
output_file.write(input_file_contents)
input_file.close()
try:
os.remove(file_name)
except OSError as e:
print >> sys.stderr, 'Error deleting file %s.\nError: %s' % (file_name, e)
return False
return True
def _overlay_barcode_and_base_frames(barcodes_file, base_file, output_file,
barcodes_component_sizes,
base_component_sizes):
"""Overlays the next YUV frame from a file with a barcode.
Args:
barcodes_file(FileObject): The YUV file containing the barcodes (opened).
base_file(FileObject): The base YUV file (opened).
output_file(FileObject): The output overlaid file (opened).
barcodes_component_sizes(list of tuples): The width and height of each Y, U
and V plane of the barcodes YUV file.
base_component_sizes(list of tuples): The width and height of each Y, U and
V plane of the base YUV file.
Return:
(bool): True if there are more planes (i.e. frames) in the base file, false
otherwise.
"""
# We will loop three times - once for the Y, U and V planes
for ((barcode_comp_width, barcode_comp_height),
(base_comp_width, base_comp_height)) in zip(barcodes_component_sizes,
base_component_sizes):
for base_row in range(base_comp_height):
barcode_plane_traversed = False
if (base_row < barcode_comp_height) and not barcode_plane_traversed:
barcode_plane = barcodes_file.read(barcode_comp_width)
if barcode_plane == "":
barcode_plane_traversed = True
else:
barcode_plane_traversed = True
base_plane = base_file.read(base_comp_width)
if base_plane == "":
return False
if not barcode_plane_traversed:
# Substitute part of the base component with the top component
output_file.write(barcode_plane)
base_plane = base_plane[barcode_comp_width:]
output_file.write(base_plane)
return True
def overlay_yuv_files(barcode_width, barcode_height, base_width, base_height,
barcodes_file_name, base_file_name, output_file_name):
"""Overlays two YUV files starting from the upper left corner of both.
Args:
barcode_width(int): The width of the barcode (to be overlaid).
barcode_height(int): The height of the barcode (to be overlaid).
base_width(int): The width of a frame of the base file.
base_height(int): The height of a frame of the base file.
barcodes_file_name(string): The name of the YUV file containing the YUV
barcodes.
base_file_name(string): The name of the base YUV file.
output_file_name(string): The name of the output file where the overlaid
video will be written.
"""
# Component sizes = [Y_sizes, U_sizes, V_sizes]
barcodes_component_sizes = [(barcode_width, barcode_height),
(barcode_width/2, barcode_height/2),
(barcode_width/2, barcode_height/2)]
base_component_sizes = [(base_width, base_height),
(base_width/2, base_height/2),
(base_width/2, base_height/2)]
barcodes_file = open(barcodes_file_name, 'rb')
base_file = open(base_file_name, 'rb')
output_file = open(output_file_name, 'wb')
data_left = True
while data_left:
data_left = _overlay_barcode_and_base_frames(barcodes_file, base_file,
output_file,
barcodes_component_sizes,
base_component_sizes)
barcodes_file.close()
base_file.close()
output_file.close()
def calculate_frames_number_from_yuv(yuv_width, yuv_height, file_name):
"""Calculates the number of frames of a YUV video.
Args:
yuv_width(int): Width of a frame of the yuv file.
yuv_height(int): Height of a frame of the YUV file.
file_name(string): The name of the YUV file.
Return:
(int): The number of frames in the YUV file.
"""
file_size = os.path.getsize(file_name)
y_plane_size = yuv_width * yuv_height
u_plane_size = (yuv_width/2) * (yuv_height/2) # Equals to V plane size too
frame_size = y_plane_size + (2 * u_plane_size)
return int(file_size/frame_size) # Should be int anyway
def _form_jars_string(path_to_zxing):
"""Forms the the Zxing core and javase jars argument.
Args:
path_to_zxing(string): The path to the Zxing checkout folder.
Return:
(string): The newly formed jars argument.
"""
javase_jar = os.path.join(path_to_zxing, "javase", "javase.jar")
core_jar = os.path.join(path_to_zxing, "core", "core.jar")
delimiter = ':'
if os.name != 'posix':
delimiter = ';'
return javase_jar + delimiter + core_jar
def _parse_args():
"""Registers the command-line options."""
usage = "usage: %prog [options]"
parser = optparse.OptionParser(usage=usage)
parser.add_option('--barcode_width', type='int',
default=_DEFAULT_BARCODE_WIDTH,
help=('Width of the barcodes to be overlaid on top of the'
' base file. Default: %default'))
parser.add_option('--barcode_height', type='int', default=32,
help=('Height of the barcodes to be overlaid on top of the'
' base file. Default: %default'))
parser.add_option('--base_frame_width', type='int', default=352,
help=('Width of the base YUV file\'s frames. '
'Default: %default'))
parser.add_option('--base_frame_height', type='int', default=288,
help=('Height of the top YUV file\'s frames. '
'Default: %default'))
parser.add_option('--barcodes_yuv', type='string',
default=_DEFAULT_BARCODES_FILE,
help=('The YUV file with the barcodes in YUV. '
'Default: %default'))
parser.add_option('--base_yuv', type='string', default='base.yuv',
help=('The base YUV file to be overlaid. '
'Default: %default'))
parser.add_option('--output_yuv', type='string', default='output.yuv',
help=('The output YUV file containing the base overlaid'
' with the barcodes. Default: %default'))
parser.add_option('--png_barcodes_output_dir', type='string', default='.',
help=('Output directory where the PNG barcodes will be '
'generated. Default: %default'))
parser.add_option('--png_barcodes_input_dir', type='string', default='.',
help=('Input directory from where the PNG barcodes will be '
'read. Default: %default'))
parser.add_option('--yuv_barcodes_output_dir', type='string', default='.',
help=('Output directory where the YUV barcodes will be '
'generated. Default: %default'))
parser.add_option('--yuv_frames_input_dir', type='string', default='.',
help=('Input directory from where the YUV will be '
'read before combination. Default: %default'))
parser.add_option('--zxing_dir', type='string', default='zxing',
help=('Path to the Zxing barcodes library. '
'Default: %default'))
options = parser.parse_args()[0]
return options
def _main():
"""The main function.
A simple invocation will be:
./webrtc/tools/barcode_tools/barcode_encoder.py --barcode_height=32
--base_frame_width=352 --base_frame_height=288
--base_yuv=<path_and_name_of_base_file>
--output_yuv=<path and name_of_output_file>
"""
options = _parse_args()
# The barcodes with will be different than the base frame width only if
# explicitly specified at the command line.
if options.barcode_width == _DEFAULT_BARCODE_WIDTH:
options.barcode_width = options.base_frame_width
# If the user provides a value for the barcodes YUV video file, we will keep
# it. Otherwise we create a temp file which is removed after it has been used.
keep_barcodes_yuv_file = False
if options.barcodes_yuv != _DEFAULT_BARCODES_FILE:
keep_barcodes_yuv_file = True
# Calculate the number of barcodes - it is equal to the number of frames in
# the base file.
number_of_barcodes = calculate_frames_number_from_yuv(
options.base_frame_width, options.base_frame_height, options.base_yuv)
script_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
zxing_dir = os.path.join(script_dir, 'third_party', 'zxing')
# Generate barcodes - will generate them in PNG.
generate_upca_barcodes(number_of_barcodes, options.barcode_width,
options.barcode_height,
output_directory=options.png_barcodes_output_dir,
path_to_zxing=zxing_dir)
# Convert the PNG barcodes to to YUV format.
convert_png_to_yuv_barcodes(options.png_barcodes_input_dir,
options.yuv_barcodes_output_dir)
# Combine the YUV barcodes into one YUV file.
combine_yuv_frames_into_one_file(options.barcodes_yuv,
input_directory=options.yuv_frames_input_dir)
# Overlay the barcodes over the base file.
overlay_yuv_files(options.barcode_width, options.barcode_height,
options.base_frame_width, options.base_frame_height,
options.barcodes_yuv, options.base_yuv, options.output_yuv)
if not keep_barcodes_yuv_file:
# Remove the temporary barcodes YUV file
os.remove(options.barcodes_yuv)
if __name__ == '__main__':
sys.exit(_main())
| bsd-3-clause |
garyjyao1/ansible | lib/ansible/modules/core/utilities/helper/fireball.py | 132 | 8066 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2012, Michael DeHaan <michael.dehaan@gmail.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/>.
DOCUMENTATION = '''
---
module: fireball
short_description: Enable fireball mode on remote node
description:
- This modules launches an ephemeral I(fireball) ZeroMQ message bus daemon on the remote node which
Ansible can use to communicate with nodes at high speed.
- The daemon listens on a configurable port for a configurable amount of time.
- Starting a new fireball as a given user terminates any existing user fireballs.
- Fireball mode is AES encrypted
version_added: "0.9"
options:
port:
description:
- TCP port for ZeroMQ
required: false
default: 5099
aliases: []
minutes:
description:
- The I(fireball) listener daemon is started on nodes and will stay around for
this number of minutes before turning itself off.
required: false
default: 30
notes:
- See the advanced playbooks chapter for more about using fireball mode.
requirements: [ "zmq", "keyczar" ]
author:
- "Ansible Core Team"
- "Michael DeHaan"
'''
EXAMPLES = '''
# This example playbook has two plays: the first launches 'fireball' mode on all hosts via SSH, and
# the second actually starts using it for subsequent management over the fireball connection
- hosts: devservers
gather_facts: false
connection: ssh
sudo: yes
tasks:
- action: fireball
- hosts: devservers
connection: fireball
tasks:
- command: /usr/bin/anything
'''
import os
import sys
import shutil
import time
import base64
import syslog
import signal
import time
import signal
import traceback
syslog.openlog('ansible-%s' % os.path.basename(__file__))
PIDFILE = os.path.expanduser("~/.fireball.pid")
def log(msg):
syslog.syslog(syslog.LOG_NOTICE, msg)
if os.path.exists(PIDFILE):
try:
data = int(open(PIDFILE).read())
try:
os.kill(data, signal.SIGKILL)
except OSError:
pass
except ValueError:
pass
os.unlink(PIDFILE)
HAS_ZMQ = False
try:
import zmq
HAS_ZMQ = True
except ImportError:
pass
HAS_KEYCZAR = False
try:
from keyczar.keys import AesKey
HAS_KEYCZAR = True
except ImportError:
pass
# NOTE: this shares a fair amount of code in common with async_wrapper, if async_wrapper were a new module we could move
# this into utils.module_common and probably should anyway
def daemonize_self(module, password, port, minutes):
# daemonizing code: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66012
try:
pid = os.fork()
if pid > 0:
log("exiting pid %s" % pid)
# exit first parent
module.exit_json(msg="daemonized fireball on port %s for %s minutes" % (port, minutes))
except OSError, e:
log("fork #1 failed: %d (%s)" % (e.errno, e.strerror))
sys.exit(1)
# decouple from parent environment
os.chdir("/")
os.setsid()
os.umask(022)
# do second fork
try:
pid = os.fork()
if pid > 0:
log("daemon pid %s, writing %s" % (pid, PIDFILE))
pid_file = open(PIDFILE, "w")
pid_file.write("%s" % pid)
pid_file.close()
log("pidfile written")
sys.exit(0)
except OSError, e:
log("fork #2 failed: %d (%s)" % (e.errno, e.strerror))
sys.exit(1)
dev_null = file('/dev/null','rw')
os.dup2(dev_null.fileno(), sys.stdin.fileno())
os.dup2(dev_null.fileno(), sys.stdout.fileno())
os.dup2(dev_null.fileno(), sys.stderr.fileno())
log("daemonizing successful (%s,%s)" % (password, port))
def command(module, data):
if 'cmd' not in data:
return dict(failed=True, msg='internal error: cmd is required')
if 'tmp_path' not in data:
return dict(failed=True, msg='internal error: tmp_path is required')
if 'executable' not in data:
return dict(failed=True, msg='internal error: executable is required')
log("executing: %s" % data['cmd'])
rc, stdout, stderr = module.run_command(data['cmd'], executable=data['executable'], close_fds=True)
if stdout is None:
stdout = ''
if stderr is None:
stderr = ''
log("got stdout: %s" % stdout)
return dict(rc=rc, stdout=stdout, stderr=stderr)
def fetch(data):
if 'in_path' not in data:
return dict(failed=True, msg='internal error: in_path is required')
# FIXME: should probably support chunked file transfer for binary files
# at some point. For now, just base64 encodes the file
# so don't use it to move ISOs, use rsync.
fh = open(data['in_path'])
data = base64.b64encode(fh.read())
return dict(data=data)
def put(data):
if 'data' not in data:
return dict(failed=True, msg='internal error: data is required')
if 'out_path' not in data:
return dict(failed=True, msg='internal error: out_path is required')
# FIXME: should probably support chunked file transfer for binary files
# at some point. For now, just base64 encodes the file
# so don't use it to move ISOs, use rsync.
fh = open(data['out_path'], 'w')
fh.write(base64.b64decode(data['data']))
fh.close()
return dict()
def serve(module, password, port, minutes):
log("serving")
context = zmq.Context()
socket = context.socket(zmq.REP)
addr = "tcp://*:%s" % port
log("zmq serving on %s" % addr)
socket.bind(addr)
# password isn't so much a password but a serialized AesKey object that we xferred over SSH
# password as a variable in ansible is never logged though, so it serves well
key = AesKey.Read(password)
while True:
data = socket.recv()
try:
data = key.Decrypt(data)
except:
continue
data = json.loads(data)
mode = data['mode']
response = {}
if mode == 'command':
response = command(module, data)
elif mode == 'put':
response = put(data)
elif mode == 'fetch':
response = fetch(data)
data2 = json.dumps(response)
data2 = key.Encrypt(data2)
socket.send(data2)
def daemonize(module, password, port, minutes):
try:
daemonize_self(module, password, port, minutes)
def catcher(signum, _):
module.exit_json(msg='timer expired')
signal.signal(signal.SIGALRM, catcher)
signal.setitimer(signal.ITIMER_REAL, 60 * minutes)
serve(module, password, port, minutes)
except Exception, e:
tb = traceback.format_exc()
log("exception caught, exiting fireball mode: %s\n%s" % (e, tb))
sys.exit(0)
def main():
module = AnsibleModule(
argument_spec = dict(
port=dict(required=False, default=5099),
password=dict(required=True),
minutes=dict(required=False, default=30),
),
supports_check_mode=True
)
password = base64.b64decode(module.params['password'])
port = module.params['port']
minutes = int(module.params['minutes'])
if not HAS_ZMQ:
module.fail_json(msg="zmq is not installed")
if not HAS_KEYCZAR:
module.fail_json(msg="keyczar is not installed")
daemonize(module, password, port, minutes)
# import module snippets
from ansible.module_utils.basic import *
main()
| gpl-3.0 |
cchurch/ansible | test/units/modules/network/ios/test_ios_system.py | 68 | 5372 | #
# (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/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from units.compat.mock import patch
from ansible.modules.network.ios import ios_system
from units.modules.utils import set_module_args
from .ios_module import TestIosModule, load_fixture
class TestIosSystemModule(TestIosModule):
module = ios_system
def setUp(self):
super(TestIosSystemModule, self).setUp()
self.mock_get_config = patch('ansible.modules.network.ios.ios_system.get_config')
self.get_config = self.mock_get_config.start()
self.mock_load_config = patch('ansible.modules.network.ios.ios_system.load_config')
self.load_config = self.mock_load_config.start()
def tearDown(self):
super(TestIosSystemModule, self).tearDown()
self.mock_get_config.stop()
self.mock_load_config.stop()
def load_fixtures(self, commands=None):
self.get_config.return_value = load_fixture('ios_system_config.cfg')
self.load_config.return_value = None
def test_ios_system_hostname_changed(self):
set_module_args(dict(hostname='foo'))
commands = ['hostname foo']
self.execute_module(changed=True, commands=commands)
def test_ios_system_domain_name(self):
set_module_args(dict(domain_name=['test.com']))
commands = ['ip domain name test.com',
'no ip domain name eng.example.net',
'no ip domain name vrf management eng.example.net']
self.execute_module(changed=True, commands=commands)
def test_ios_system_domain_name_complex(self):
set_module_args(dict(domain_name=[{'name': 'test.com', 'vrf': 'test'},
{'name': 'eng.example.net'}]))
commands = ['ip domain name vrf test test.com',
'no ip domain name vrf management eng.example.net']
self.execute_module(changed=True, commands=commands)
def test_ios_system_domain_search(self):
set_module_args(dict(domain_search=['ansible.com', 'redhat.com']))
commands = ['no ip domain list vrf management example.net',
'no ip domain list example.net',
'no ip domain list example.com',
'ip domain list ansible.com',
'ip domain list redhat.com']
self.execute_module(changed=True, commands=commands, sort=False)
def test_ios_system_domain_search_complex(self):
set_module_args(dict(domain_search=[{'name': 'ansible.com', 'vrf': 'test'}]))
commands = ['no ip domain list vrf management example.net',
'no ip domain list example.net',
'no ip domain list example.com',
'ip domain list vrf test ansible.com']
self.execute_module(changed=True, commands=commands, sort=False)
def test_ios_system_lookup_source(self):
set_module_args(dict(lookup_source='Ethernet1'))
commands = ['ip domain lookup source-interface Ethernet1']
self.execute_module(changed=True, commands=commands)
def test_ios_system_name_servers(self):
name_servers = ['8.8.8.8', '8.8.4.4']
set_module_args(dict(name_servers=name_servers))
commands = ['no ip name-server vrf management 8.8.8.8',
'ip name-server 8.8.4.4']
self.execute_module(changed=True, commands=commands, sort=False)
def rest_ios_system_name_servers_complex(self):
name_servers = dict(server='8.8.8.8', vrf='test')
set_module_args(dict(name_servers=name_servers))
commands = ['no name-server 8.8.8.8',
'no name-server vrf management 8.8.8.8',
'ip name-server vrf test 8.8.8.8']
self.execute_module(changed=True, commands=commands, sort=False)
def test_ios_system_state_absent(self):
set_module_args(dict(state='absent'))
commands = ['no hostname',
'no ip domain lookup source-interface GigabitEthernet0/0',
'no ip domain list vrf management', 'no ip domain list',
'no ip domain name vrf management', 'no ip domain name',
'no ip name-server vrf management', 'no ip name-server']
self.execute_module(changed=True, commands=commands)
def test_ios_system_no_change(self):
set_module_args(dict(hostname='ios01'))
self.execute_module(commands=[])
def test_ios_system_missing_vrf(self):
name_servers = dict(server='8.8.8.8', vrf='missing')
set_module_args(dict(name_servers=name_servers))
self.execute_module(failed=True)
| gpl-3.0 |
arlewis/galaxy_cutouts | versions/extract_stamp_v1.py | 1 | 13653 | import astropy.io.fits as pyfits
import astropy.wcs as pywcs
import os
import numpy as np
from pdb import set_trace
import montage_wrapper as montage
import shutil
import sys
_TOP_DIR = '/data/tycho/0/leroy.42/allsky/'
_INDEX_DIR = os.path.join(_TOP_DIR, 'code/')
_HOME_DIR = '/n/home00/lewis.1590/research/galbase_allsky/'
_MOSAIC_DIR = os.path.join(_HOME_DIR, 'cutouts')
def counts2jy(norm_mag, calibration_value, pix_as):
# convert counts to Jy
val = 10.**((norm_mag + calibration_value) / -2.5)
val *= 3631.0
# then to MJy
val /= 1e6
# then to MJy/sr
val /= np.radians(pix_as / 3600.)**2
return val
def counts2jy_galex(counts, cal, pix_as):
# first convert to abmag
abmag = -2.5 * np.log10(counts) + cal
# then convert to Jy
f_nu = 10**(abmag/-2.5) * 3631.
# then to MJy
f_nu *= 1e-6
# then to MJy/sr
val = f_nu / (np.radians(pix_as/3600))**2
return val
#val = flux / MJYSR2JYARCSEC / pixel_area / 1e-23 / C * FUV_LAMBDA**2
def calc_tile_overlap(ra_ctr, dec_ctr, pad=0.0, min_ra=0., max_ra=180., min_dec=-90., max_dec=90.):
overlap = ((min_dec - pad) < dec_ctr) & ((max_dec + pad) > dec_ctr)
#TRAP HIGH LATITUDE CASE AND (I GUESS) TOSS BACK ALL TILES. DO BETTER LATER
mean_dec = (min_dec + max_dec) * 0.5
if np.abs(dec_ctr) + pad > 88.0:
return overlap
ra_pad = pad / np.cos(np.radians(mean_dec))
# MERIDIAN CASES
merid = np.where(max_ra < min_ra)
overlap[merid] = overlap[merid] & ( ((min_ra-ra_pad) < ra_ctr) | ((max_ra+ra_pad) > ra_ctr) )[merid]
# BORING CASE
normal = np.where(max_ra > min_ra)
overlap[normal] = overlap[normal] & ((((min_ra-ra_pad) < ra_ctr) & ((max_ra+ra_pad) > ra_ctr)))[normal]
return overlap
def make_axes(hdr, quiet=False, novec=False, vonly=False, simple=False):
# PULL THE IMAGE/CUBE SIZES FROM THE HEADER
naxis = hdr['NAXIS']
naxis1 = hdr['NAXIS1']
naxis2 = hdr['NAXIS2']
if naxis > 2:
naxis3 = hdr['NAXIS3']
## EXTRACT FITS ASTROMETRY STRUCTURE
ww = pywcs.WCS(hdr)
#IF DATASET IS A CUBE THEN WE MAKE THE THIRD AXIS IN THE SIMPLEST WAY POSSIBLE (NO COMPLICATED ASTROMETRY WORRIES FOR FREQUENCY INFORMATION)
if naxis > 3:
#GRAB THE RELEVANT INFORMATION FROM THE ASTROMETRY HEADER
cd = ww.wcs.cd
crpix = ww.wcs.crpix
cdelt = ww.wcs.crelt
crval = ww.wcs.crval
if naxis > 2:
# MAKE THE VELOCITY AXIS (WILL BE M/S)
v = np.arange(naxis3) * 1.0
vdif = v - (hdr['CRPIX3']-1)
vaxis = (vdif * hdr['CDELT3'] + hdr['CRVAL3'])
# CUT OUT HERE IF WE ONLY WANT VELOCITY INFO
if vonly:
return vaxis
#IF 'SIMPLE' IS CALLED THEN DO THE REALLY TRIVIAL THING:
if simple:
print('Using simple aproach to make axes.')
print('BE SURE THIS IS WHAT YOU WANT! It probably is not.')
raxis = np.arange(naxis1) * 1.0
rdif = raxis - (hdr['CRPIX1'] - 1)
raxis = (rdif * hdr['CDELT1'] + hdr['CRVAL1'])
daxis = np.arange(naxis2) * 1.0
ddif = daxis - (hdr['CRPIX1'] - 1)
daxis = (ddif * hdr['CDELT1'] + hdr['CRVAL1'])
rimg = raxis # (fltarr(naxis2) + 1.)
dimg = (np.asarray(naxis1) + 1.) # daxis
return rimg, dimg
# OBNOXIOUS SFL/GLS THING
glspos = ww.wcs.ctype[0].find('GLS')
if glspos != -1:
ctstr = ww.wcs.ctype[0]
newtype = 'SFL'
ctstr.replace('GLS', 'SFL')
ww.wcs.ctype[0] = ctstr
print('Replaced GLS with SFL; CTYPE1 now =' + ww.wcs.ctype[0])
glspos = ww.wcs.ctype[1].find('GLS')
if glspos != -1:
ctstr = ww.wcs.ctype[1]
newtype = 'SFL'
ctstr.replace('GLS', 'SFL')
ww.wcs.ctype[1] = ctstr
print('Replaced GLS with SFL; CTYPE2 now = ' + ww.wcs.ctype[1])
# CALL 'xy2ad' TO FIND THE RA AND DEC FOR EVERY POINT IN THE IMAGE
if novec:
rimg = np.zeros((naxis1, naxis2))
dimg = np.zeros((naxis1, naxis2))
for i in range(naxis1):
j = np.asarray([0 for i in xrange(naxis2)])
pixcrd = np.array([[zip(float(i), float(j))]], numpy.float_)
ra, dec = ww.all_pix2world(pixcrd, 1)
rimg[i, :] = ra
dimg[i, :] = dec
else:
ximg = np.arange(naxis1) * 1.0
yimg = np.arange(naxis1) * 1.0
X, Y = np.meshgrid(ximg, yimg, indexing='xy')
ss = X.shape
xx, yy = X.flatten(), Y.flatten()
pixcrd = np.array(zip(xx, yy), np.float_)
img_new = ww.all_pix2world(pixcrd, 0)
rimg_new, dimg_new = img_new[:,0], img_new[:,1]
rimg = rimg_new.reshape(ss)
dimg = dimg_new.reshape(ss)
# GET AXES FROM THE IMAGES. USE THE CENTRAL COLUMN AND CENTRAL ROW
raxis = np.squeeze(rimg[:, naxis2/2.])
daxis = np.squeeze(dimg[naxis1/2., :])
return rimg, dimg
def write_headerfile(header_file, header):
f = open(header_file, 'w')
for iii in range(len(header)):
outline = str(header[iii:iii+1]).strip().rstrip('END').strip()+'\n'
f.write(outline)
f.close()
def reprojection(orig_file, im, old_hdr, new_hdr, data_dir, name=None):
montage_dir = os.path.join(data_dir, '_montage')
## write im (in MJy/sr) to a file
newfile = orig_file.split('/')[-1].replace('.fits', '_to_mjysr.fits')
imfile = os.path.join(_HOME_DIR, newfile)
if not os.path.exists(imfile):
pyfits.writeto(imfile, im, old_hdr)
#hdu = pyfits.PrimaryHDU(im, header=old_hdr)
#hdu.writeto(imfile)
# wrie new_hdr to a file
hdr_file = os.path.join(_HOME_DIR, 'template.hdr')
if name is not None:
hdr_file = os.path.join(_HOME_DIR, name + '_template.hdr')
write_headerfile(hdr_file, new_hdr)
# reproject with new imfile and headerfile
outfile = imfile.replace('.fits', '_reproj.fits')
montage.mProject(imfile, outfile, hdr_file)
#new_hdu = montage.reproject_hdu(hdu, header=hdr_file)
#return outfile
return new_hdu.data
def create_hdr(ra_ctr, dec_ctr, pix_len, pix_scale):
hdr = pyfits.Header()
hdr['NAXIS'] = 2
hdr['NAXIS1'] = pix_len
hdr['NAXIS2'] = pix_len
hdr['CTYPE1'] = 'RA---TAN'
hdr['CRVAL1'] = float(ra_ctr)
hdr['CRPIX1'] = (pix_len / 2.) * 1.
hdr['CDELT1'] = -1.0 * pix_scale
hdr['CTYPE2'] = 'DEC--TAN'
hdr['CRVAL2'] = float(dec_ctr)
hdr['CRPIX2'] = (pix_len / 2.) * 1.
hdr['CDELT2'] = pix_scale
hdr['EQUINOX'] = 2000
return hdr
def unwise(band=1, ra_ctr=None, dec_ctr=None, size_deg=None, index=None, name=None):
tel = 'unwise'
data_dir = os.path.join(_TOP_DIR, tel, 'sorted_tiles')
# READ THE INDEX FILE (IF NOT PASSED IN)
if index is None:
indexfile = os.path.join(_INDEX_DIR, tel + '_index_file.fits')
ext = 1
index, hdr = pyfits.getdata(indexfile, ext, header=True)
# CALIBRATION TO GO FROM VEGAS TO ABMAG
w1_vtoab = 2.683
w2_vtoab = 3.319
w3_vtoab = 5.242
w4_vtoab = 6.604
# NORMALIZATION OF UNITY IN VEGAS MAG
norm_mag = 22.5
pix_as = 2.75 #arcseconds - native detector pixel size wise docs
# COUNTS TO JY CONVERSION
w1_to_mjysr = counts2jy(norm_mag, w1_vtoab, pix_as)
w2_to_mjysr = counts2jy(norm_mag, w2_vtoab, pix_as)
w3_to_mjysr = counts2jy(norm_mag, w3_vtoab, pix_as)
w4_to_mjysr = counts2jy(norm_mag, w4_vtoab, pix_as)
# MAKE A HEADER
pix_scale = 2.0 / 3600. # 2.0 arbitrary
pix_len = size_deg / pix_scale
# this should automatically populate SIMPLE and NAXIS keywords
target_hdr = create_hdr(ra_ctr, dec_ctr, pix_len, pix_scale)
# CALCULATE TILE OVERLAP
tile_overlaps = calc_tile_overlap(ra_ctr, dec_ctr, pad=size_deg,
min_ra=index['MIN_RA'],
max_ra=index['MAX_RA'],
min_dec=index['MIN_DEC'],
max_dec=index['MAX_DEC'])
# FIND OVERLAPPING TILES WITH RIGHT BAND
# index file set up such that index['BAND'] = 1, 2, 3, 4 depending on wise band
ind = np.where((index['BAND'] == band) & tile_overlaps)
ct_overlap = len(ind[0])
# SET UP THE OUTPUT
ri_targ, di_targ = make_axes(target_hdr)
sz_out = ri_targ.shape
outim = ri_targ * np.nan
# LOOP OVER OVERLAPPING TILES AND STITCH ONTO TARGET HEADER
for ii in range(0, ct_overlap):
infile = os.path.join(data_dir, index[ind[ii]]['FNAME'])
im, hdr = pyfits.getdata(infile, header=True)
ri, di = make_axes(hdr)
hh = pywcs.WCS(target_hdr)
x, y = ww.all_world2pix(zip(ri, di), 1)
in_image = (x > 0 & x < (sz_out[0]-1)) & (y > 0 and y < (sz_out[1]-1))
if np.sum(in_image) == 0:
print("No overlap. Proceeding.")
continue
if band == 1:
im *= w1_to_mjysr
if band == 2:
im *= w2_to_mjysr
if band == 3:
im *= w3_to_mjysr
if band == 4:
im *= w4_to_mjysr
target_hdr['BUNIT'] = 'MJY/SR'
newimfile = reprojection(infile, im, hdr, target_hdr, data_dir)
im, new_hdr = pyfits.getdata(newimfile, header=True)
useful = np.where(np.isfinite(im))
outim[useful] = im[useful]
return outim, target_hdr
def galex(band='fuv', ra_ctr=None, dec_ctr=None, size_deg=None, index=None, name=None):
tel = 'galex'
data_dir = os.path.join(_TOP_DIR, tel, 'sorted_tiles')
problem_file = os.path.join(_HOME_DIR, 'problem_galaxies.txt')
galaxy_mosaic_file = os.path.join(_MOSAIC_DIR, '_'.join([name, band]).upper() + '.FITS')
#if not os.path.exists(galaxy_mosaic_file):
if name:
# READ THE INDEX FILE (IF NOT PASSED IN)
if index is None:
indexfile = os.path.join(_INDEX_DIR, tel + '_index_file.fits')
ext = 1
index, hdr = pyfits.getdata(indexfile, ext, header=True)
# CALIBRATION FROM COUNTS TO ABMAG
fuv_toab = 18.82
nuv_toab = 20.08
# PIXEL SCALE IN ARCSECONDS
pix_as = 1.5 # galex pixel scale -- from galex docs
# MAKE A HEADER
pix_scale = 1.5 / 3600. # 1.5 arbitrary: how should I set it?
pix_len = size_deg / pix_scale
target_hdr = create_hdr(ra_ctr, dec_ctr, pix_len, pix_scale)
# CALCULATE TILE OVERLAP
tile_overlaps = calc_tile_overlap(ra_ctr, dec_ctr, pad=size_deg,
min_ra=index['MIN_RA'],
max_ra=index['MAX_RA'],
min_dec=index['MIN_DEC'],
max_dec=index['MAX_DEC'])
# FIND OVERLAPPING TILES WITH RIGHT BAND
# index file set up such that index['fuv'] = 1 where fuv and
# index['nuv'] = 1 where nuv
ind = np.where((index[band]) & tile_overlaps)
ct_overlap = len(ind[0])
# MAKE SURE THERE ARE OVERLAPPING TILES
if ct_overlap == 0:
with open(problem_file, 'a') as myfile:
myfile.write(name + ': ' + 'No overlapping tiles\n')
return
# SET UP THE OUTPUT
ri_targ, di_targ = make_axes(target_hdr)
sz_out = ri_targ.shape
outim = ri_targ * np.nan
prihdu = pyfits.PrimaryHDU(data=outim, header=target_hdr)
target_hdr = prihdu.header
# CREATE NEW DIRECTORY TO STORE TEMPORARY FILES
gal_dir = os.path.join(_HOME_DIR, name)
os.makedirs(gal_dir)
infiles = infiles = index[ind[0]]['fname']
infiles = [data_dir + '/' + f for f in infiles]
# CREATE SUBDIRECTORY INSIDE TEMP DIRECTORY FOR THE INPUT FILES
input_dir = os.path.join(gal_dir, 'input')
os.makedirs(input_dir)
outfiles = [os.path.join(input_dir, f.split('/')[-1].replace('.fits', '_mjysr.fits')) for f in infiles]
# CONVERT TO MJY/SR AND WRITE NEW FILES INTO TEMPORARY DIRECTORY
for i in range(len(infiles)):
im, hdr = pyfits.getdata(infiles[i], header=True)
if band.lower() == 'fuv':
im = counts2jy_galex(im, fuv_toab, pix_as)
if band.lower() == 'nuv':
im = counts2jy_galex(im, nuv_toab, pix_as)
if not os.path.exists(outfiles[i]):
pyfits.writeto(outfiles[i], im, hdr)
# APPEND UNIT INFORMATION TO THE NEW HEADER
target_hdr['BUNIT'] = 'MJY/SR'
# WRITE OUT A HEADER FILE
hdr_file = os.path.join(gal_dir, name + '_template.hdr')
write_headerfile(hdr_file, target_hdr)
final_dir = os.path.join(gal_dir, 'mosaic')
# MOSAIC THE TILES FOR THIS GALAXY
try:
montage.mosaic(input_dir, final_dir, header=hdr_file,background_match=False, combine='count')
set_trace()
# COPY MOSAIC FILE TO CUTOUTS DIRECTORY
mosaic_file = os.path.join(final_dir, 'mosaic.fits')
newfile = '_'.join([name, band]).upper() + '.FITS'
new_mosaic_file = os.path.join(_MOSAIC_DIR, newfile)
shutil.copy(mosaic_file, new_mosaic_file)
# REMOVE GALAXY DIRECTORY AND EXTRA FILES
shutil.rmtree(gal_dir)
except Exception as inst:
me = sys.exc_info()[0]
problem_file = os.path.join(_HOME_DIR, 'problem_galaxies.txt')
with open(problem_file, 'a') as myfile:
myfile.write(name + ': ' + str(me) + ': ' + str(inst) + '\n')
shutil.rmtree(gal_dir)
return
| mit |
SlimLP-Y300/chil360-kernel | arch/ia64/scripts/unwcheck.py | 13143 | 1714 | #!/usr/bin/python
#
# Usage: unwcheck.py FILE
#
# This script checks the unwind info of each function in file FILE
# and verifies that the sum of the region-lengths matches the total
# length of the function.
#
# Based on a shell/awk script originally written by Harish Patil,
# which was converted to Perl by Matthew Chapman, which was converted
# to Python by David Mosberger.
#
import os
import re
import sys
if len(sys.argv) != 2:
print "Usage: %s FILE" % sys.argv[0]
sys.exit(2)
readelf = os.getenv("READELF", "readelf")
start_pattern = re.compile("<([^>]*)>: \[0x([0-9a-f]+)-0x([0-9a-f]+)\]")
rlen_pattern = re.compile(".*rlen=([0-9]+)")
def check_func (func, slots, rlen_sum):
if slots != rlen_sum:
global num_errors
num_errors += 1
if not func: func = "[%#x-%#x]" % (start, end)
print "ERROR: %s: %lu slots, total region length = %lu" % (func, slots, rlen_sum)
return
num_funcs = 0
num_errors = 0
func = False
slots = 0
rlen_sum = 0
for line in os.popen("%s -u %s" % (readelf, sys.argv[1])):
m = start_pattern.match(line)
if m:
check_func(func, slots, rlen_sum)
func = m.group(1)
start = long(m.group(2), 16)
end = long(m.group(3), 16)
slots = 3 * (end - start) / 16
rlen_sum = 0L
num_funcs += 1
else:
m = rlen_pattern.match(line)
if m:
rlen_sum += long(m.group(1))
check_func(func, slots, rlen_sum)
if num_errors == 0:
print "No errors detected in %u functions." % num_funcs
else:
if num_errors > 1:
err="errors"
else:
err="error"
print "%u %s detected in %u functions." % (num_errors, err, num_funcs)
sys.exit(1)
| gpl-2.0 |
ramcn/demo3 | venv/lib/python3.4/site-packages/requests/packages/urllib3/packages/ssl_match_hostname/_implementation.py | 2360 | 3778 | """The match_hostname() function from Python 3.3.3, essential when using SSL."""
# Note: This file is under the PSF license as the code comes from the python
# stdlib. http://docs.python.org/3/license.html
import re
__version__ = '3.4.0.2'
class CertificateError(ValueError):
pass
def _dnsname_match(dn, hostname, max_wildcards=1):
"""Matching according to RFC 6125, section 6.4.3
http://tools.ietf.org/html/rfc6125#section-6.4.3
"""
pats = []
if not dn:
return False
# Ported from python3-syntax:
# leftmost, *remainder = dn.split(r'.')
parts = dn.split(r'.')
leftmost = parts[0]
remainder = parts[1:]
wildcards = leftmost.count('*')
if wildcards > max_wildcards:
# Issue #17980: avoid denials of service by refusing more
# than one wildcard per fragment. A survey of established
# policy among SSL implementations showed it to be a
# reasonable choice.
raise CertificateError(
"too many wildcards in certificate DNS name: " + repr(dn))
# speed up common case w/o wildcards
if not wildcards:
return dn.lower() == hostname.lower()
# RFC 6125, section 6.4.3, subitem 1.
# The client SHOULD NOT attempt to match a presented identifier in which
# the wildcard character comprises a label other than the left-most label.
if leftmost == '*':
# When '*' is a fragment by itself, it matches a non-empty dotless
# fragment.
pats.append('[^.]+')
elif leftmost.startswith('xn--') or hostname.startswith('xn--'):
# RFC 6125, section 6.4.3, subitem 3.
# The client SHOULD NOT attempt to match a presented identifier
# where the wildcard character is embedded within an A-label or
# U-label of an internationalized domain name.
pats.append(re.escape(leftmost))
else:
# Otherwise, '*' matches any dotless string, e.g. www*
pats.append(re.escape(leftmost).replace(r'\*', '[^.]*'))
# add the remaining fragments, ignore any wildcards
for frag in remainder:
pats.append(re.escape(frag))
pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
return pat.match(hostname)
def match_hostname(cert, hostname):
"""Verify that *cert* (in decoded format as returned by
SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125
rules are followed, but IP addresses are not accepted for *hostname*.
CertificateError is raised on failure. On success, the function
returns nothing.
"""
if not cert:
raise ValueError("empty or no certificate")
dnsnames = []
san = cert.get('subjectAltName', ())
for key, value in san:
if key == 'DNS':
if _dnsname_match(value, hostname):
return
dnsnames.append(value)
if not dnsnames:
# The subject is only checked when there is no dNSName entry
# in subjectAltName
for sub in cert.get('subject', ()):
for key, value in sub:
# XXX according to RFC 2818, the most specific Common Name
# must be used.
if key == 'commonName':
if _dnsname_match(value, hostname):
return
dnsnames.append(value)
if len(dnsnames) > 1:
raise CertificateError("hostname %r "
"doesn't match either of %s"
% (hostname, ', '.join(map(repr, dnsnames))))
elif len(dnsnames) == 1:
raise CertificateError("hostname %r "
"doesn't match %r"
% (hostname, dnsnames[0]))
else:
raise CertificateError("no appropriate commonName or "
"subjectAltName fields were found")
| mit |
vendasta/appengine-mapreduce | python/test/mapreduce/datastore_range_iterators_test.py | 15 | 11177 | #!/usr/bin/env python
# pylint: disable=g-bad-name
import os
import unittest
from google.appengine.ext import ndb
from google.appengine.api import datastore
from google.appengine.api import namespace_manager
from google.appengine.ext import db
from google.appengine.ext import key_range
from google.appengine.ext import testbed
from mapreduce import datastore_range_iterators as db_iters
from mapreduce import key_ranges
from mapreduce import model
from mapreduce import namespace_range
from mapreduce import property_range
from mapreduce import util
class TestEntity(db.Model):
bar = db.IntegerProperty()
class NdbTestEntity(ndb.Model):
bar = ndb.IntegerProperty()
class IteratorTest(unittest.TestCase):
def setUp(self):
self.testbed = testbed.Testbed()
self.app = "foo"
os.environ["APPLICATION_ID"] = self.app
self.testbed.activate()
self.testbed.init_datastore_v3_stub()
self.testbed.init_memcache_stub()
self.namespaces = [str(i) for i in range(5)]
self.filters = [("bar", "=", 0)]
self.key_names = [str(i) for i in range(10)]
self.bar_values = [0]*5 + list(range(1, 6))
def tearDown(self):
self.testbed.deactivate()
def _create_entities(self):
"""In each ns create 10 entities with bar values."""
entities = []
old_ns = namespace_manager.get_namespace()
for namespace in self.namespaces:
namespace_manager.set_namespace(namespace)
for key_name, bar in zip(self.key_names, self.bar_values):
entity = TestEntity(key_name=key_name, bar=bar)
entities.append(entity)
entity.put()
namespace_manager.set_namespace(old_ns)
return entities
def _create_ndb_entities(self):
entities = []
for namespace in self.namespaces:
for key_name, bar in zip(self.key_names, self.bar_values):
key = ndb.Key("NdbTestEntity", key_name, namespace=namespace)
entity = NdbTestEntity(key=key, bar=bar)
entities.append(entity)
entity.put()
return entities
def _serializeAndAssertEquals(self, itr, expected, get_key):
"""AssertEquals helper.
Consume iterator, serialize and deserialize on every next call,
check returned values are expected.
Args:
itr: a serializable object that implement __iter__.
expected: a list of expected keys.
get_key: a function that is applied to every iterator returned value
to get entity key.
"""
# Perform an initial serialization before you iterate.
itr = itr.__class__.from_json_str(itr.to_json_str())
results = []
for _ in expected:
key = get_key(iter(itr).next())
results.append(key)
# Convert to str to test everything is indeed json compatible.
itr = itr.__class__.from_json_str(itr.to_json_str())
# Convert twice to check consistency.
itr = itr.__class__.from_json_str(itr.to_json_str())
results.sort()
self.assertEquals(expected, results)
self.assertRaises(StopIteration, iter(itr).next)
def _AssertEquals(self, itr, expected, get_key):
"""AssertEquals helper.
Consume iterator without serialization.
Check returned values are expected.
Args:
itr: a serializable object that implement __iter__.
expected: a list of expected keys.
get_key: a function that is applied to every iterator returned value
to get entity key.
"""
results = [get_key(i) for i in itr]
results.sort()
self.assertEquals(expected, results)
class PropertyRangeIteratorTest(IteratorTest):
def setUp(self):
super(PropertyRangeIteratorTest, self).setUp()
self.filters = [("bar", "<=", 4), ("bar", ">", 2)]
def _create_iter(self, entity_kind):
query_spec = model.QuerySpec(entity_kind=util.get_short_name(entity_kind),
batch_size=10,
filters=self.filters,
model_class_path=entity_kind)
p_range = property_range.PropertyRange(self.filters,
entity_kind)
ns_range = namespace_range.NamespaceRange(self.namespaces[0],
self.namespaces[-1])
itr = db_iters.RangeIteratorFactory.create_property_range_iterator(
p_range, ns_range, query_spec)
return itr
def testE2e(self):
entities = self._create_entities()
expected = [e.key() for e in entities if e.bar in [3, 4]]
expected.sort()
itr = self._create_iter("__main__.TestEntity")
self._serializeAndAssertEquals(itr, expected, lambda e: e.key())
itr = self._create_iter("__main__.TestEntity")
self._AssertEquals(itr, expected, lambda e: e.key())
def testE2eNdb(self):
entities = self._create_ndb_entities()
expected = [e.key for e in entities if e.bar in [3, 4]]
expected.sort()
itr = self._create_iter("__main__.NdbTestEntity")
self._serializeAndAssertEquals(itr, expected, lambda e: e.key)
itr = self._create_iter("__main__.NdbTestEntity")
self._AssertEquals(itr, expected, lambda e: e.key)
class KeyRangesIteratorTest(IteratorTest):
"""Tests for db_iters._KeyRangesIterator."""
def _create_iter(self, iter_cls, entity_kind):
kranges = [key_range.KeyRange(namespace=ns) for ns in self.namespaces]
kranges = key_ranges.KeyRangesFactory.create_from_list(kranges)
query_spec = model.QuerySpec(entity_kind=util.get_short_name(entity_kind),
batch_size=10,
filters=self.filters,
model_class_path=entity_kind)
itr = db_iters.RangeIteratorFactory.create_key_ranges_iterator(
kranges, query_spec, iter_cls)
return itr
def testE2e(self):
entities = self._create_entities()
expected = [e.key() for e in entities if e.bar == 0]
expected.sort()
itr = self._create_iter(db_iters.KeyRangeModelIterator,
"__main__.TestEntity")
self._serializeAndAssertEquals(itr, expected, lambda e: e.key())
itr = self._create_iter(db_iters.KeyRangeModelIterator,
"__main__.TestEntity")
self._AssertEquals(itr, expected, lambda e: e.key())
itr = self._create_iter(db_iters.KeyRangeEntityIterator,
"TestEntity")
self._serializeAndAssertEquals(itr, expected, lambda e: e.key())
itr = self._create_iter(db_iters.KeyRangeEntityIterator,
"TestEntity")
self._AssertEquals(itr, expected, lambda e: e.key())
itr = self._create_iter(db_iters.KeyRangeKeyIterator,
"TestEntity")
self._serializeAndAssertEquals(itr, expected, lambda e: e)
itr = self._create_iter(db_iters.KeyRangeKeyIterator,
"TestEntity")
self._AssertEquals(itr, expected, lambda e: e)
def testE2eNdb(self):
entities = self._create_ndb_entities()
expected = [e.key for e in entities if e.bar == 0]
expected.sort()
itr = self._create_iter(db_iters.KeyRangeModelIterator,
"__main__.NdbTestEntity")
self._serializeAndAssertEquals(itr, expected, lambda e: e.key)
itr = self._create_iter(db_iters.KeyRangeModelIterator,
"__main__.NdbTestEntity")
self._AssertEquals(itr, expected, lambda e: e.key)
class KeyRangeIteratorTestBase(IteratorTest):
"""Base class for db_iters.KeyRange*Iterator tests."""
def setUp(self):
super(KeyRangeIteratorTestBase, self).setUp()
self.namespace = "foo_ns"
self.namespaces = [self.namespace]
def _create_iter(self, iter_cls, entity_kind):
key_start = db.Key.from_path(util.get_short_name(entity_kind),
"0",
namespace=self.namespace)
key_end = db.Key.from_path(util.get_short_name(entity_kind),
"999",
namespace=self.namespace)
krange = key_range.KeyRange(key_start,
key_end,
include_start=True,
include_end=True,
namespace=self.namespace)
query_spec = model.QuerySpec(entity_kind=util.get_short_name(entity_kind),
batch_size=10,
filters=self.filters,
model_class_path=entity_kind)
return iter_cls(krange, query_spec)
class KeyRangeModelIteratorTest(KeyRangeIteratorTestBase):
"""Tests for KeyRangeModelIterator."""
def testE2e(self):
entities = self._create_entities()
expected = [e.key() for e in entities if e.bar == 0]
expected.sort()
itr = self._create_iter(db_iters.KeyRangeModelIterator,
"__main__.TestEntity")
self._serializeAndAssertEquals(itr, expected, lambda e: e.key())
itr = self._create_iter(db_iters.KeyRangeModelIterator,
"__main__.TestEntity")
self._AssertEquals(itr, expected, lambda e: e.key())
def testE2eNdb(self):
entities = self._create_ndb_entities()
expected = [e.key for e in entities if e.bar == 0]
expected.sort()
itr = self._create_iter(db_iters.KeyRangeModelIterator,
"__main__.NdbTestEntity")
self._serializeAndAssertEquals(itr, expected, lambda e: e.key)
itr = self._create_iter(db_iters.KeyRangeModelIterator,
"__main__.NdbTestEntity")
self._AssertEquals(itr, expected, lambda e: e.key)
class KeyRangeRawEntityIteratorTest(KeyRangeIteratorTestBase):
"""Tests for KeyRangeEntityIterator and KeyRangeKeyIterator."""
def testE2e(self):
entities = self._create_entities()
expected = [e.key() for e in entities if e.bar == 0]
expected.sort()
def get_key(item):
# Test the returned value is low level datastore API's Entity.
self.assertTrue(isinstance(item, datastore.Entity))
return item.key()
itr = self._create_iter(db_iters.KeyRangeEntityIterator, "TestEntity")
self._serializeAndAssertEquals(itr, expected, get_key)
itr = self._create_iter(db_iters.KeyRangeEntityIterator, "TestEntity")
self._AssertEquals(itr, expected, get_key)
itr = self._create_iter(db_iters.KeyRangeKeyIterator, "TestEntity")
self._serializeAndAssertEquals(itr, expected, lambda e: e)
itr = self._create_iter(db_iters.KeyRangeKeyIterator, "TestEntity")
self._AssertEquals(itr, expected, lambda e: e)
class KeyRangeEntityProtoIteratorTest(KeyRangeIteratorTestBase):
"""Tests for KeyRangeEntityProtoIterator."""
def testE2e(self):
entities = self._create_entities()
expected = [e.key() for e in entities if e.bar == 0]
expected.sort()
def get_key(item):
return datastore.Entity._FromPb(item).key()
itr = self._create_iter(db_iters.KeyRangeEntityProtoIterator, "TestEntity")
self._serializeAndAssertEquals(itr, expected, get_key)
itr = self._create_iter(db_iters.KeyRangeEntityProtoIterator, "TestEntity")
self._AssertEquals(itr, expected, get_key)
if __name__ == "__main__":
unittest.main()
| apache-2.0 |
wd5/jangr | openid/yadis/services.py | 167 | 1838 | # -*- test-case-name: openid.test.test_services -*-
from openid.yadis.filters import mkFilter
from openid.yadis.discover import discover, DiscoveryFailure
from openid.yadis.etxrd import parseXRDS, iterServices, XRDSError
def getServiceEndpoints(input_url, flt=None):
"""Perform the Yadis protocol on the input URL and return an
iterable of resulting endpoint objects.
@param flt: A filter object or something that is convertable to
a filter object (using mkFilter) that will be used to generate
endpoint objects. This defaults to generating BasicEndpoint
objects.
@param input_url: The URL on which to perform the Yadis protocol
@return: The normalized identity URL and an iterable of endpoint
objects generated by the filter function.
@rtype: (str, [endpoint])
@raises DiscoveryFailure: when Yadis fails to obtain an XRDS document.
"""
result = discover(input_url)
try:
endpoints = applyFilter(result.normalized_uri,
result.response_text, flt)
except XRDSError, err:
raise DiscoveryFailure(str(err), None)
return (result.normalized_uri, endpoints)
def applyFilter(normalized_uri, xrd_data, flt=None):
"""Generate an iterable of endpoint objects given this input data,
presumably from the result of performing the Yadis protocol.
@param normalized_uri: The input URL, after following redirects,
as in the Yadis protocol.
@param xrd_data: The XML text the XRDS file fetched from the
normalized URI.
@type xrd_data: str
"""
flt = mkFilter(flt)
et = parseXRDS(xrd_data)
endpoints = []
for service_element in iterServices(et):
endpoints.extend(
flt.getServiceEndpoints(normalized_uri, service_element))
return endpoints
| bsd-3-clause |
spxtr/bazel | tools/android/resource_extractor_test.py | 13 | 2400 | # Copyright 2016 The Bazel 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 resource_extractor."""
import StringIO
import unittest
import zipfile
from tools.android import resource_extractor
class ResourceExtractorTest(unittest.TestCase):
"""Unit tests for resource_extractor.py."""
def testJarWithEverything(self):
input_jar = zipfile.ZipFile(StringIO.StringIO(), "w")
for path in (
# Should not be included
"foo.aidl",
"tmp/foo.aidl",
"tmp/foo.java",
"tmp/foo.java.swp",
"tmp/foo.class",
"tmp/flags.xml",
"tilde~",
"tmp/flags.xml~",
".gitignore",
"tmp/.gitignore",
"META-INF/",
"tmp/META-INF/",
"META-INF/MANIFEST.MF",
"tmp/META-INF/services/foo",
"bar/",
"CVS/bar/",
"tmp/CVS/bar/",
".svn/CVS/bar/",
"tmp/.svn/CVS/bar/",
# Should be included
"bar/a",
"a/b",
"c",
"a/not_package.html",
"not_CVS/include",
"META-INF/services/foo"):
input_jar.writestr(path, "")
output_zip = zipfile.ZipFile(StringIO.StringIO(), "w")
resource_extractor.ExtractResources(input_jar, output_zip)
self.assertItemsEqual(("c", "a/b", "bar/a", "a/not_package.html",
"not_CVS/include", "META-INF/services/foo"),
output_zip.namelist())
def testTimestampsAreTheSame(self):
input_jar = zipfile.ZipFile(StringIO.StringIO(), "w")
entry_info = zipfile.ZipInfo("a", (1982, 1, 1, 0, 0, 0))
input_jar.writestr(entry_info, "")
output_zip = zipfile.ZipFile(StringIO.StringIO(), "w")
resource_extractor.ExtractResources(input_jar, output_zip)
self.assertEqual((1982, 1, 1, 0, 0, 0), output_zip.getinfo("a").date_time)
if __name__ == "__main__":
unittest.main()
| apache-2.0 |
kuiwei/edx-platform | cms/envs/bok_choy.py | 13 | 2535 | """
Settings for bok choy tests
"""
import os
from path import path
########################## Prod-like settings ###################################
# These should be as close as possible to the settings we use in production.
# As in prod, we read in environment and auth variables from JSON files.
# Unlike in prod, we use the JSON files stored in this repo.
# This is a convenience for ensuring (a) that we can consistently find the files
# and (b) that the files are the same in Jenkins as in local dev.
os.environ['SERVICE_VARIANT'] = 'bok_choy'
os.environ['CONFIG_ROOT'] = path(__file__).abspath().dirname() # pylint: disable=E1120
from .aws import * # pylint: disable=W0401, W0614
######################### Testing overrides ####################################
# Needed for the reset database management command
INSTALLED_APPS += ('django_extensions',)
# Redirect to the test_root folder within the repo
TEST_ROOT = CONFIG_ROOT.dirname().dirname() / "test_root" # pylint: disable=E1120
GITHUB_REPO_ROOT = (TEST_ROOT / "data").abspath()
LOG_DIR = (TEST_ROOT / "log").abspath()
# Configure modulestore to use the test folder within the repo
update_module_store_settings(
MODULESTORE,
module_store_options={
'fs_root': (TEST_ROOT / "data").abspath(), # pylint: disable=E1120
},
xml_store_options={
'data_dir': (TEST_ROOT / "data").abspath(),
},
default_store=os.environ.get('DEFAULT_STORE', 'draft'),
)
# Enable django-pipeline and staticfiles
STATIC_ROOT = (TEST_ROOT / "staticfiles").abspath()
# Silence noisy logs
import logging
LOG_OVERRIDES = [
('track.middleware', logging.CRITICAL),
('edx.discussion', logging.CRITICAL),
]
for log_name, log_level in LOG_OVERRIDES:
logging.getLogger(log_name).setLevel(log_level)
# Use the auto_auth workflow for creating users and logging them in
FEATURES['AUTOMATIC_AUTH_FOR_TESTING'] = True
# Unfortunately, we need to use debug mode to serve staticfiles
DEBUG = True
# Point the URL used to test YouTube availability to our stub YouTube server
YOUTUBE_PORT = 9080
YOUTUBE['API'] = "127.0.0.1:{0}/get_youtube_api/".format(YOUTUBE_PORT)
YOUTUBE['TEST_URL'] = "127.0.0.1:{0}/test_youtube/".format(YOUTUBE_PORT)
YOUTUBE['TEXT_API']['url'] = "127.0.0.1:{0}/test_transcripts_youtube/".format(YOUTUBE_PORT)
#####################################################################
# Lastly, see if the developer has any local overrides.
try:
from .private import * # pylint: disable=F0401
except ImportError:
pass
| agpl-3.0 |
JuantAldea/LUT-2013-CSPA-Reversi | src/GameServerTCP.py | 1 | 3892 | # Reversi is a multiplayer reversi game with dedicated server
# Copyright (C) 2012-2013, Juan Antonio Aldea Armenteros
# 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/>.
# -*- coding: utf8 -*-
#################################
# Juan Antonio Aldea Armenteros #
# CSPA - LUT - 2013 #
#################################
import signal
import select
import socket
from ITCPReq import ITCPReq
class GameServerTCP(ITCPReq):
def __init__(self, port):
self.game_server = None
self.port = port
self.listening_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.listening_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.listening_socket.bind(('', self.port))
self.listening_socket.listen(10)
signal.signal(signal.SIGCHLD, signal.SIG_IGN)
self.running = True
self.waitting_players = 0
self.connected_clients = []
def set_indication(self, game_server):
self.game_server = game_server
def run(self):
try:
while self.running:
input_ready, output_ready, except_ready = select.select([self.listening_socket] + self.connected_clients, [], [])
print "[TCPServer] Activity"
for client in input_ready:
if client == self.listening_socket:
print "[TCPServer] New connection"
client, (ip, address) = self.listening_socket.accept()
client.setblocking(0)
print client, ip, address
self.connected_clients += [client]
elif client in self.connected_clients:
peek = client.recv(1, socket.MSG_PEEK)
if len(peek) == 0:
# disconnection
print "[TCPServer] Client disconnected"
self.game_server.disconnection_ind(client)
client.close()
self.connected_clients.remove(client)
else:
print "[TCPServer] Data received"
raw_data = client.recv(4096)
self.game_server.recv_ind(client, raw_data)
try:
while len(client.recv(4096)) > 0:
pass
except:
pass
except KeyboardInterrupt:
print "Shutting down..."
self.shutdown()
return
def shutdown(self):
print "[TCPServer] Closing listening socket"
if self.listening_socket > 0:
self.listening_socket.close()
self.listening_socket = -1
# ITCPReq implementation
def shutdown_req(self):
self.shutdown()
def send_req(self, client, data):
# server doesn't send anything to clients
return
def disconnect_req(self, client):
print "[TCPServer] CloseReq, removing client from list"
client.close()
try:
self.connected_clients.remove(client)
except ValueError:
print "Remove called but client is unknown"
| gpl-3.0 |
Schrolli91/BOSWatch | plugins/Sms77/Sms77.py | 1 | 3361 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
SMS77-Plugin to send FMS-, ZVEI- and POCSAG - messages to SMS77
@author: Ricardo Krippner
@requires: SMS77-Configuration has to be set in the config.ini
"""
import logging # Global logger
import httplib #for the HTTP request
import urllib
from includes import globalVars # Global variables
#from includes.helper import timeHandler
from includes.helper import configHandler
##
#
# onLoad (init) function of plugin
# will be called one time by the pluginLoader on start
#
def onLoad():
"""
While loading the plugins by pluginLoader.loadPlugins()
this onLoad() routine is called one time for initialize the plugin
@requires: nothing
@return: nothing
"""
# nothing to do for this plugin
return
##
#
# Main function of SMS77-plugin
# will be called by the alarmHandler
#
def run(typ,freq,data):
"""
This function is the implementation of the Sms77-Plugin.
It will send the data to Sms77 API
@type typ: string (FMS|ZVEI|POC)
@param typ: Typ of the dataset
@type data: map of data (structure see readme.md in plugin folder)
@param data: Contains the parameter
@type freq: string
@keyword freq: frequency of the SDR Stick
@requires: Sms77-Configuration has to be set in the config.ini
@return: nothing
"""
try:
if configHandler.checkConfig("Sms77"): #read and debug the config
# create an empty message an fill it with the required information
message = "Alarm"
if typ == "FMS":
logging.debug("FMS detected, building message")
message = data["description"]+"<br>"+data["status"]
elif typ == "ZVEI":
logging.debug("ZVEI detected, building message")
message = data["zvei"]+" - "+data["description"]
elif typ == "POC":
logging.debug("POC detected, building message")
message = data["description"]+"<br>"+data["msg"].replace(";", "<br>")
else:
logging.warning("Invalid typ - use empty message")
try:
#
# Sms77-Request
#
logging.debug("send Sms77 %s", typ)
conn = httplib.HTTPSConnection("gateway.sms77.io",443)
conn.request("POST", "/api/sms",
urllib.urlencode({
"u": globalVars.config.get("Sms77", "user"),
"p": globalVars.config.get("Sms77", "password"),
"to": globalVars.config.get("Sms77", "to"),
"from": globalVars.config.get("Sms77", "from"),
"type": globalVars.config.get("Sms77", "type"),
"text": message
}),{"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"})
except:
logging.error("cannot send SMS77 request")
logging.debug("cannot send SMS77 request", exc_info=True)
return
else:
try:
#
# check Sms77-Response
#
response = conn.getresponse()
if str(response.status) == "200": #Check Sms77 Response and print a Log or Error
logging.debug("SMS77 response: %s - %s" , str(response.status), str(response.reason))
else:
logging.warning("SMS77 response: %s - %s" , str(response.status), str(response.reason))
except: #otherwise
logging.error("cannot get SMS77 response")
logging.debug("cannot get SMS77 response", exc_info=True)
return
finally:
logging.debug("close Sms77-Connection")
try:
request.close()
except:
pass
except:
logging.error("unknown error")
logging.debug("unknown error", exc_info=True)
| gpl-2.0 |
zubron/servo | components/script/dom/bindings/codegen/parser/tests/test_variadic_constraints.py | 170 | 1564 | def WebIDLTest(parser, harness):
threw = False
try:
parser.parse("""
interface VariadicConstraints1 {
void foo(byte... arg1, byte arg2);
};
""")
results = parser.finish()
except:
threw = True
harness.ok(threw,
"Should have thrown on variadic argument followed by required "
"argument.")
parser = parser.reset()
threw = False
try:
parser.parse("""
interface VariadicConstraints2 {
void foo(byte... arg1, optional byte arg2);
};
""")
results = parser.finish();
except:
threw = True
harness.ok(threw,
"Should have thrown on variadic argument followed by optional "
"argument.")
parser = parser.reset()
threw = False
try:
parser.parse("""
interface VariadicConstraints3 {
void foo(optional byte... arg1);
};
""")
results = parser.finish()
except:
threw = True
harness.ok(threw,
"Should have thrown on variadic argument explicitly flagged as "
"optional.")
parser = parser.reset()
threw = False
try:
parser.parse("""
interface VariadicConstraints4 {
void foo(byte... arg1 = 0);
};
""")
results = parser.finish()
except:
threw = True
harness.ok(threw, "Should have thrown on variadic argument with default value.")
| mpl-2.0 |
sinnwerkstatt/landmatrix | apps/grid/forms/base_form.py | 1 | 24246 | import re
from collections import OrderedDict
from django import forms
from django.core.exceptions import ObjectDoesNotExist
from django.urls import reverse
from django.utils.datastructures import MultiValueDict
from django.utils.translation import ugettext_lazy as _
from apps.grid.fields import (
ActorsField,
AreaField,
MultiCharField,
NestedMultipleChoiceField,
YearBasedField,
)
from apps.grid.utils import get_display_value
class FieldsDisplayFormMixin(object):
def get_fields_display(self, user=None):
"""Return fields for detail view"""
output = []
tg_title = ""
tg_items = []
for i, (field_name, field) in enumerate(self.base_fields.items()):
if field_name.startswith("tg_") and not field_name.endswith("_comment"):
# value = self.initial.get(self.prefix and "%s-%s"%(self.prefix, field_name) or field_name, [])
# if field_name == 'tg_nature_comment':
# raise IOError(value)
# if value:
# tg_items.append(field.label, value))
# continue
if len(tg_items) > 0:
output.append({"name": "tg", "label": "", "value": tg_title})
output.extend(tg_items)
tg_title = field.initial
tg_items = []
continue
if isinstance(field, NestedMultipleChoiceField):
value = self.get_display_value_nested_multiple_choice_field(
field, field_name
)
elif isinstance(
field, (forms.ModelMultipleChoiceField, forms.MultipleChoiceField)
):
value = self.get_display_value_multiple_choice_field(field, field_name)
elif isinstance(field, forms.ModelChoiceField):
value = self.get_display_value_model_choice_field(field, field_name)
elif isinstance(field, forms.ChoiceField):
value = self.get_display_value_choice_field(field, field_name)
elif isinstance(field, AreaField):
value = self.get_display_value_area_field(field, field_name)
elif isinstance(field, forms.MultiValueField):
value = self.get_display_value_multi_value_field(field, field_name)
elif isinstance(field, forms.FileField):
value = self.get_display_value_file_field(field, field_name)
elif isinstance(field, forms.BooleanField):
value = self.get_display_value_boolean_field(field, field_name)
else:
value = self.initial.get(field_name, "")
if value:
tg_items.append(
{
"name": field_name,
"label": field.label,
"value": value,
# 'value': '%s %s' % (value, field.help_text),
}
)
if len(tg_items) > 0:
output.append({"name": "tg", "label": "", "value": tg_title})
output.extend(tg_items)
return output
def get_display_value_boolean_field(self, field, field_name):
data = self.initial.get(
field_name, ""
) # self.prefix and "%s-%s" % (self.prefix, field_name) or field_name, '')
if data == "True":
return _("Yes")
elif data == "False":
return _("No")
return ""
def get_display_value_file_field(self, field, field_name):
value = self.initial.get(field_name, "")
return value
def get_display_value_multi_value_field(self, field, field_name):
# todo - fails with historical deals?
data = self.initial.get(
field_name, ""
) # self.prefix and "%s-%s" % (self.prefix, field_name) or field_name, '')
values = []
if data:
for value in data.split("#"):
date_values = value.split(":")
current = date_values.pop() if date_values else None
date = date_values.pop() if date_values else None
if date_values:
# Replace value with label for choice fields
if isinstance(field.fields[0], forms.ChoiceField):
selected = date_values[0].split(",")
# Grouped choice field?
if isinstance(
list(field.fields[0].choices)[0][1], (list, tuple)
):
date_values[0] = []
for group, items in field.fields[0].choices:
date_value = ", ".join(
[str(l) for v, l in items if str(v) in selected]
)
if date_value:
date_values[0].append(date_value)
date_values[0] = ", ".join(date_values[0])
else:
date_values[0] = ", ".join(
[
str(l)
for v, l in field.fields[0].choices
if str(v) in selected
]
)
value = ""
if date or current:
value += "[%s] " % ", ".join(
filter(None, [date, (current and "current" or "")])
)
value += date_values[0]
if len(date_values) > 1:
value2 = ", ".join(filter(None, date_values[1:]))
if value2:
value += _(" (%s %s)") % (
value2,
hasattr(field, "placeholder")
and field.placeholder
or "ha",
)
else:
value = ""
if value:
values.append(value)
return "<br>".join(values)
def get_display_value_choice_field(self, field, field_name):
data = self.initial.get(field_name)
if not data:
data = []
value = "<br>".join([str(l) for v, l in field.choices if v and str(v) in data])
return value
# def get_list_from_initial(self, field_name):
# if isinstance(self.initial, MultiValueDict):
# return self.initial.getlist(field_name, [])#self.prefix and "%s-%s" % (self.prefix, field_name) or field_name, [])
# data = self.initial.get(field_name, [])#self.prefix and "%s-%s" % (self.prefix, field_name) or field_name, [])
# if data: data = [data]
# return data
def get_display_value_area_field(self, field, field_name):
data = self.initial.get(
field_name, []
) # self.prefix and "%s-%s" % (self.prefix, field_name) or field_name, [])
if data:
# Return serialized value for map
widget = field.widget.widgets[0]
context = widget.get_context("contract_area", data)
return {"srid": widget.map_srid, "serialized": context["serialized"]}
else:
return {}
def get_display_value_multiple_choice_field(self, field, field_name):
data = self.initial.get(
field_name, []
) # self.prefix and "%s-%s" % (self.prefix, field_name) or field_name, [])
value = "<br>".join([str(l) for v, l in field.choices if str(v) in data])
return value
def get_display_value_nested_multiple_choice_field(self, field, field_name):
data = self.initial.get(
field_name, []
) # self.prefix and "%s-%s" % (self.prefix, field_name) or field_name, [])
values = []
for v, l, c in field.choices:
value = ""
if str(v) in data:
value = str(l)
if c:
choices = ", ".join([str(l) for v, l in c if str(v) in data])
value = (value and "%s (%s)" % (value, choices)) or choices
if value:
values.append(value)
value = "<br>".join(values)
return value
def get_display_value_model_choice_field(self, field, field_name):
value = self.initial.get(
field_name, []
) # self.prefix and "%s-%s" % (self.prefix, field_name) or field_name, [])
if value:
try:
# Use base queryset to handle none() querysets (used with ajax based widgets)
object = field.queryset.model.objects.get(pk=value)
except (ValueError, AttributeError, ObjectDoesNotExist):
return ""
# Return links for some specific fields, maybe better move to the respective form
if field_name in ("operational_stakeholder", "fk_investor"):
url = reverse(
"investor_detail",
kwargs={
"investor_id": object.investor_identifier,
#'history_id': object.id,
},
)
value = '<a href="%s">%s</a>' % (url, str(object))
else:
value = str(object)
else:
value = ""
return value
@classmethod
def get_display_properties(cls, doc, formset=None):
"""Get field display values for ES"""
output = {}
for name, field in cls.base_fields.items():
# Title field?
if name.startswith("tg_") and not name.endswith("_comment"):
continue
key = "%s_display" % name
values = doc.get(name)
if not values:
output[key] = []
continue
if not isinstance(values, (list, tuple)):
values = [values]
attr_key = "%s_attr" % name
attributes = attr_key in doc and doc.get(attr_key) or None
value = get_display_value(field, values, attributes, formset=formset)
if value:
output[key] = value
return output
class BaseForm(FieldsDisplayFormMixin, forms.Form):
error_css_class = "error"
def get_attributes(self, request=None):
"""
Get posted form data, for saving to the database.
For activity or stakeholder, using attribute group only - if given
(for formsets)
"""
attributes = OrderedDict()
for i, (n, f) in enumerate(self.fields.items()):
name = str(n)
# New tag group?
if n.startswith("tg_") and not n.endswith("_comment"):
continue
if isinstance(
f, (forms.ModelMultipleChoiceField, forms.MultipleChoiceField)
):
# Create tags for each value
value = self.data.getlist(
self.prefix and "%s-%s" % (self.prefix, n) or n, []
)
values = []
for v in list(value):
if v:
try:
# Save display value
# FIXME: We should save the value instead, now that we have _display fields
value = str(dict([i[:2] for i in f.choices])[v])
except (ValueError, TypeError, KeyError):
value = None
if isinstance(f, NestedMultipleChoiceField) and not value:
for choice in f.choices:
try:
value = str(dict([i[:2] for i in choice[2]])[v])
if value:
break
except (ValueError, TypeError, KeyError):
value = None
if not value:
value = v
if value:
values.append({"value": value})
if values:
attributes[name] = values
elif isinstance(f, forms.ModelChoiceField):
value = self.data.get(self.prefix and "%s-%s" % (self.prefix, n) or n)
if value:
# Save pk of object
attributes[name] = {"value": value}
elif isinstance(f, forms.ChoiceField):
value = self.data.get(self.prefix and "%s-%s" % (self.prefix, n) or n)
if value:
# Save display value
# FIXME: We should save the value instead, now that we have _display fields
value = str(dict(f.choices).get(value))
if value:
attributes[name] = {"value": value}
# Year based data (or Actors field)?
elif isinstance(f, (YearBasedField, ActorsField)):
# Grab last item and enumerate, since there can be gaps
# because of checkboxes not submitting data
prefix = self.prefix and "%s-%s" % (self.prefix, n) or "%s" % n
keys = [
int(k.replace(name + "_", ""))
for k in self.data.keys()
if re.match("%s_\d" % prefix, k)
]
count = len(keys) > 0 and max(keys) + 1 or 0
widget_count = len(f.widget.get_widgets())
if count % widget_count > 0:
count += 1
values = []
for i in range(count):
key = "%s_%i" % (prefix, i)
if i % widget_count == 0:
widget_values = self.data.getlist(key)
value2 = None
year = None
is_current = False
# Value / Value2 / Date / is current
if widget_count > 3:
value2 = self.data.get("%s_%i" % (prefix, i + 1))
year = self.data.get("%s_%i" % (prefix, i + 2))
is_current = "%s_%i" % (prefix, i + 3) in self.data
# Value / Date / is current
elif widget_count > 2:
year = self.data.get("%s_%i" % (prefix, i + 1))
is_current = "%s_%i" % (prefix, i + 2) in self.data
# Value / Value2 (e.g. Actors field)
elif widget_count == 2:
value2 = self.data.get("%s_%i" % (prefix, i + 1))
for value in widget_values:
if value or value2 or year:
values.append(
{
"value": value,
"value2": value2,
"date": year,
"is_current": is_current,
}
)
if values:
attributes[name] = values
elif isinstance(f, forms.FileField):
value = self.get_display_value_file_field(f, n)
if value:
attributes[name] = {"value": value}
elif isinstance(f, forms.DecimalField):
value = (
self.is_valid()
and self.cleaned_data.get(n)
or self.data.get(self.prefix and "%s-%s" % (self.prefix, n) or n)
)
if value:
attributes[name] = {"value": str(value)}
elif isinstance(f, forms.FloatField):
value = (
self.is_valid()
and self.cleaned_data.get(n)
or self.data.get(self.prefix and "%s-%s" % (self.prefix, n) or n)
)
if value:
# Save integer if whole number
if str(value).isdigit():
value = int(value)
attributes[name] = {"value": str(value)}
else:
value = (
self.is_valid()
and self.cleaned_data.get(n)
or self.data.get(self.prefix and "%s-%s" % (self.prefix, n) or n)
)
if value:
attributes[name] = {"value": value}
return attributes
@classmethod
def get_data(cls, activity, group=None, prefix=""):
"""
Load previously saved attributes from the database.
Returns:
{
'Name of attribute 1': {
value: 'Value for attribute',
value2: 'Optional second value for attribute, e.g. ha for crops',
date: 'Date of value for year based fields',
},
'Name of attribute 2': {
...
}
}
"""
data = MultiValueDict()
# Create attributes dict
queryset = activity.attributes.order_by("id")
if group:
queryset = queryset.filter(fk_group__name=group)
attributes = OrderedDict()
for aa in queryset.all():
if aa.name in attributes:
attributes[aa.name].append(aa)
else:
attributes[aa.name] = [aa]
for (field_name, field) in cls().base_fields.items():
# Group title?
name = prefix and "%s-%s" % (prefix, field_name) or field_name
if field_name.startswith("tg_") and not field_name.endswith("comment"):
continue
# tags, group = cls.get_tags(field_name, activity, group)
attribute = attributes.get(field_name, [])
if not attribute:
continue
value = attribute[0].value
# Multiple choice?
if isinstance(
field, (forms.MultipleChoiceField, forms.ModelMultipleChoiceField)
):
value = cls.get_multiple_choice_data(field, field_name, attribute)
# Year based data (or Actors field/MultiCharField)?
# TODO: check if the other two should be included
elif isinstance(field, (YearBasedField, MultiCharField, ActorsField)):
value = cls.get_year_based_data(field, field_name, attribute)
# Choice field?
elif isinstance(field, forms.ChoiceField):
for k, v in field.choices:
if v == value:
value = str(k)
break
if value:
data[name] = value
return data
@classmethod
def get_multiple_choice_data(cls, field, field_name, attributes):
values = []
for attribute in attributes:
value = cls.get_multiple_choice_value(field, attribute.value)
if value:
values.append(value)
return values
@classmethod
def get_multiple_choice_value(cls, field, tag_value):
value = cls.get_choice_value(field, tag_value)
if isinstance(field, NestedMultipleChoiceField) and not value:
value = cls.get_nested_choice_value(field, tag_value)
return value
@classmethod
def get_nested_choice_value(cls, field, tag_value):
for choice in field.choices:
for k, v in [i[:2] for i in choice[2] or []]:
if k == tag_value or (tag_value.isdigit() and k == int(tag_value)):
return str(k)
# FIXME: Save raw values to the database and remove this after
if v == tag_value or (tag_value.isdigit() and v == int(tag_value)):
return str(k)
return None
@classmethod
def get_choice_value(cls, field, tag_value):
for k, v in [i[:2] for i in field.choices]:
if k == tag_value or (tag_value.isdigit() and k == int(tag_value)):
return str(k)
# FIXME: Save raw values to the database and remove this after
if v == tag_value or (tag_value.isdigit() and v == int(tag_value)):
return str(k)
return None
@classmethod
def get_year_based_data(cls, field, field_name, attributes):
# Group all attributes by date
attributes_by_date = OrderedDict()
# Some year based fields take 2 values, e.g. crops and area
widgets = field.widget.get_widgets()
multiple = field.widget.get_multiple()
values_count = len(widgets) - 1
values = []
# Collect all attributes for date (for multiple choice fields)
if multiple[0]:
for attribute in attributes:
key = "%s:%s" % (
attribute.date or "",
values_count > 2 and attribute.value2 or "",
)
if key in attributes_by_date:
if attribute.value:
attributes_by_date[key][1] += "," + attribute.value
else:
is_current = attribute.is_current and "1" or ""
attributes_by_date[key] = [is_current, attribute.value]
if values_count > 2:
values = [
":".join([a[1], d.split(":")[1], d.split(":")[0], a[0]])
for d, a in attributes_by_date.items()
]
else:
values = [
":".join([a[1], d or "", a[0]])
for d, a in attributes_by_date.items()
] # pragma: no cover
else:
for attribute in attributes:
is_current = attribute.is_current and "1" or ""
# Value:Value2:Date:Is current
if values_count > 2: # pragma: no cover
values.append(
":".join(
[
attribute.value,
attribute.value2,
attribute.date or "",
is_current,
]
)
)
# Value:Date:Is current
elif values_count > 1:
values.append(
":".join([attribute.value, attribute.date or "", is_current])
)
# Value:Value2 (e.g. Actors field)
else:
values.append(":".join([attribute.value, attribute.value2 or ""]))
return "#".join(values)
@property
def meta(self):
# Required for template access to Meta class
return hasattr(self, "Meta") and self.Meta or None
class Meta:
exclude = ()
fields = ()
readonly_fields = ()
name = ""
def __init__(self, *args, **kwargs):
super(BaseForm, self).__init__(*args, **kwargs)
if hasattr(self.Meta, "exclude"):
for field in self.Meta.exclude:
del self.fields[field]
if hasattr(self.Meta, "fields") and self.Meta.fields:
fields = OrderedDict()
for field in self.Meta.fields:
fields[field] = self.fields[field]
self.fields = fields
if hasattr(self.Meta, "readonly_fields") and self.Meta.readonly_fields:
for n in self.Meta.readonly_fields:
f = self.fields[n]
if isinstance(f.widget, forms.Select):
self.fields[n].widget.attrs["disabled"] = "disabled"
else:
self.fields[n].widget.attrs["readonly"] = True
| agpl-3.0 |
sassoftware/conary | conary/dbstore/_mangle.py | 2 | 2419 | #
# Copyright (c) SAS Institute Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import re
SUBST_IDENTIFIER = re.compile(r'([ (,]):([a-zA-Z_][a-zA-Z0-9_]*)')
def quoteIdentifier(name):
name = name.replace('"', '""')
return '"%s"' % (name,)
def _swapOnce(query):
query = query.replace('?', '%s')
query = SUBST_IDENTIFIER.sub(r'\1%(\2)s', query)
return query
def _min(*args):
"""Returns the smallest non-negative argument."""
args = [x for x in args if x > -1]
if args:
return min(args)
else:
return -1
def swapPlaceholders(query):
"""Change ? to %s and :foo to %(foo)s while honoring quoting rules."""
# This is worth optimizing at some point, but it currently takes on the
# order of 0.1ms per conversion so it's not too significant next to the
# actual database call.
out = []
# Mangle positional markers, while careful to ignore quoted sections.
while query:
# Find the first token
squote = query.find("'")
dquote = query.find('"')
comment = query.find('--')
start = _min(squote, dquote, comment)
# Mangle everything before the token
if start > 0:
out.append(_swapOnce(query[:start]))
elif start == -1:
out.append(_swapOnce(query))
break
# Copy stuff from one token to the next, unharmed.
if start == comment:
end = query.find('\n', start + 2)
elif start == squote or start == dquote:
whichQuote = query[start]
end = query.find(whichQuote, start + 1)
if end == -1:
raise ValueError("Mismatched %r quote" % (whichQuote,))
if end == -1:
out.append(query[start:])
break
else:
out.append(query[start:end+1])
query = query[end+1:]
value = ''.join(out)
return value
| apache-2.0 |
zhuyongyong/crosswalk-test-suite | webapi/tct-csp-w3c-tests/csp-py/csp_img-src_cross-origin_multi_blocked_int-manual.py | 30 | 2461 | def main(request, response):
import simplejson as json
f = file('config.json')
source = f.read()
s = json.JSONDecoder().decode(source)
url1 = "http://" + s['host'] + ":" + str(s['ports']['http'][1])
url2 = "http://" + s['host'] + ":" + str(s['ports']['http'][0])
_CSP = "img-src https://tizen.org " + url1
response.headers.set("Content-Security-Policy", _CSP)
response.headers.set("X-Content-Security-Policy", _CSP)
response.headers.set("X-WebKit-CSP", _CSP)
return """<!DOCTYPE html>
<!--
Copyright (c) 2013 Intel Corporation.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of works must retain the original copyright notice, this list
of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the original 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 Intel Corporation nor the names of its contributors
may be used to endorse or promote products derived from this work without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY INTEL CORPORATION "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 INTEL CORPORATION 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.
Authors:
Hao, Yunfei <yunfeix.hao@intel.com>
-->
<html>
<head>
<title>CSP Test: csp_img-src_cross-origin_multi_blocked_int</title>
<link rel="author" title="Intel" href="http://www.intel.com"/>
<link rel="help" href="http://www.w3.org/TR/2012/CR-CSP-20121115/#img-src"/>
<meta name="flags" content=""/>
<meta charset="utf-8"/>
</head>
<body>
<p>Test passes if there is <strong>no red</strong>.</p>
<img src="support/red-100x100.png"/>
</body>
</html> """
| bsd-3-clause |
switchboardOp/ansible | lib/ansible/modules/network/vyos/vyos_linkagg.py | 8 | 7224 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2017, Ansible by Red Hat, inc
#
# This file is part of Ansible by Red Hat
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'core'}
DOCUMENTATION = """
---
module: vyos_linkagg
version_added: "2.4"
author: "Ricardo Carrillo Cruz (@rcarrillocruz)"
short_description: Manage link aggregation groups on VyOS network devices
description:
- This module provides declarative management of link aggregation groups
on VyOS network devices.
options:
name:
description:
- Name of the link aggregation group.
required: true
mode:
description:
- Mode of the link aggregation group.
choices: ['802.3ad', 'active-backup', 'broadcast',
'round-robin', 'transmit-load-balance',
'adaptive-load-balance', 'xor-hash', 'on']
members:
description:
- List of members of the link aggregation group.
collection:
description: List of link aggregation definitions.
purge:
description:
- Purge link aggregation groups not defined in the collections parameter.
default: no
state:
description:
- State of the link aggregation group.
default: present
choices: ['present', 'absent', 'up', 'down']
"""
EXAMPLES = """
- name: configure link aggregation group
vyos_linkagg:
name: bond0
members:
- eth0
- eth1
- name: remove configuration
vyos_linkagg:
name: bond0
state: absent
"""
RETURN = """
commands:
description: The list of configuration mode commands to send to the device
returned: always, except for the platforms that use Netconf transport to manage the device.
type: list
sample:
- set interfaces bonding bond0
- set interfaces ethernet eth0 bond-group 'bond0'
- set interfaces ethernet eth1 bond-group 'bond0'
"""
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.vyos import load_config, run_commands
from ansible.module_utils.vyos import vyos_argument_spec, check_args
def search_obj_in_list(name, lst):
for o in lst:
if o['name'] == name:
return o
return None
def map_obj_to_commands(updates, module):
commands = list()
want, have = updates
for w in want:
name = w['name']
members = w.get('members') or []
mode = w['mode']
if mode == 'on':
mode = '802.3ad'
state = w['state']
obj_in_have = search_obj_in_list(name, have)
if state == 'absent':
if obj_in_have:
for m in obj_in_have['members']:
commands.append('delete interfaces ethernet ' + m + ' bond-group')
commands.append('delete interfaces bonding ' + name)
else:
if not obj_in_have:
commands.append('set interfaces bonding ' + name + ' mode ' + mode)
for m in members:
commands.append('set interfaces ethernet ' + m + ' bond-group ' + name)
if state == 'down':
commands.append('set interfaces bonding ' + name + ' disable')
else:
if mode != obj_in_have['mode']:
commands.append('set interfaces bonding ' + name + ' mode ' + mode)
missing_members = list(set(members) - set(obj_in_have['members']))
for m in missing_members:
commands.append('set interfaces ethernet ' + m + ' bond-group ' + name)
if state == 'down' and obj_in_have['state'] == 'up':
commands.append('set interfaces bonding ' + name + ' disable')
elif state == 'up' and obj_in_have['state'] == 'down':
commands.append('delete interfaces bonding ' + name + ' disable')
return commands
def map_config_to_obj(module):
obj = []
output = run_commands(module, ['show interfaces bonding slaves'])
lines = output[0].splitlines()
if len(lines) > 1:
for line in lines[1:]:
splitted_line = line.split()
name = splitted_line[0]
mode = splitted_line[1]
state = splitted_line[2]
if len(splitted_line) > 4:
members = splitted_line[4:]
else:
members = []
obj.append({'name': name,
'mode': mode,
'members': members,
'state': state})
return obj
def map_params_to_obj(module):
obj = []
if 'collection' in module.params and module.params['collection']:
for c in module.params['collection']:
d = c.copy()
if 'state' not in d:
d['state'] = module.params['state']
if 'mode' not in d:
d['mode'] = module.params['mode']
obj.append(d)
else:
obj.append({
'name': module.params['name'],
'mode': module.params['mode'],
'members': module.params['members'],
'state': module.params['state']
})
return obj
def main():
""" main entry point for module execution
"""
argument_spec = dict(
name=dict(),
mode=dict(choices=['802.3ad', 'active-backup', 'broadcast',
'round-robin', 'transmit-load-balance',
'adaptive-load-balance', 'xor-hash', 'on'],
default='802.3ad'),
members=dict(type='list'),
collection=dict(type='list'),
purge=dict(default=False, type='bool'),
state=dict(default='present',
choices=['present', 'absent', 'up', 'down'])
)
argument_spec.update(vyos_argument_spec)
required_one_of = [['name', 'collection']]
mutually_exclusive = [['name', 'collection']]
module = AnsibleModule(argument_spec=argument_spec,
required_one_of=required_one_of,
supports_check_mode=True)
warnings = list()
check_args(module, warnings)
result = {'changed': False}
if warnings:
result['warnings'] = warnings
want = map_params_to_obj(module)
have = map_config_to_obj(module)
commands = map_obj_to_commands((want, have), module)
result['commands'] = commands
if commands:
commit = not module.check_mode
load_config(module, commands, commit=commit)
result['changed'] = True
module.exit_json(**result)
if __name__ == '__main__':
main()
| gpl-3.0 |
t0in4/django | tests/migrations/test_base.py | 292 | 4620 | import os
import shutil
import tempfile
from contextlib import contextmanager
from importlib import import_module
from django.apps import apps
from django.db import connection
from django.db.migrations.recorder import MigrationRecorder
from django.test import TransactionTestCase
from django.test.utils import extend_sys_path
from django.utils.module_loading import module_dir
class MigrationTestBase(TransactionTestCase):
"""
Contains an extended set of asserts for testing migrations and schema operations.
"""
available_apps = ["migrations"]
def tearDown(self):
# Reset applied-migrations state.
recorder = MigrationRecorder(connection)
recorder.migration_qs.filter(app='migrations').delete()
def get_table_description(self, table):
with connection.cursor() as cursor:
return connection.introspection.get_table_description(cursor, table)
def assertTableExists(self, table):
with connection.cursor() as cursor:
self.assertIn(table, connection.introspection.table_names(cursor))
def assertTableNotExists(self, table):
with connection.cursor() as cursor:
self.assertNotIn(table, connection.introspection.table_names(cursor))
def assertColumnExists(self, table, column):
self.assertIn(column, [c.name for c in self.get_table_description(table)])
def assertColumnNotExists(self, table, column):
self.assertNotIn(column, [c.name for c in self.get_table_description(table)])
def assertColumnNull(self, table, column):
self.assertEqual([c.null_ok for c in self.get_table_description(table) if c.name == column][0], True)
def assertColumnNotNull(self, table, column):
self.assertEqual([c.null_ok for c in self.get_table_description(table) if c.name == column][0], False)
def assertIndexExists(self, table, columns, value=True):
with connection.cursor() as cursor:
self.assertEqual(
value,
any(
c["index"]
for c in connection.introspection.get_constraints(cursor, table).values()
if c['columns'] == list(columns)
),
)
def assertIndexNotExists(self, table, columns):
return self.assertIndexExists(table, columns, False)
def assertFKExists(self, table, columns, to, value=True):
with connection.cursor() as cursor:
self.assertEqual(
value,
any(
c["foreign_key"] == to
for c in connection.introspection.get_constraints(cursor, table).values()
if c['columns'] == list(columns)
),
)
def assertFKNotExists(self, table, columns, to, value=True):
return self.assertFKExists(table, columns, to, False)
@contextmanager
def temporary_migration_module(self, app_label='migrations', module=None):
"""
Allows testing management commands in a temporary migrations module.
Wrap all invocations to makemigrations and squashmigrations with this
context manager in order to avoid creating migration files in your
source tree inadvertently.
Takes the application label that will be passed to makemigrations or
squashmigrations and the Python path to a migrations module.
The migrations module is used as a template for creating the temporary
migrations module. If it isn't provided, the application's migrations
module is used, if it exists.
Returns the filesystem path to the temporary migrations module.
"""
temp_dir = tempfile.mkdtemp()
try:
target_dir = tempfile.mkdtemp(dir=temp_dir)
with open(os.path.join(target_dir, '__init__.py'), 'w'):
pass
target_migrations_dir = os.path.join(target_dir, 'migrations')
if module is None:
module = apps.get_app_config(app_label).name + '.migrations'
try:
source_migrations_dir = module_dir(import_module(module))
except (ImportError, ValueError):
pass
else:
shutil.copytree(source_migrations_dir, target_migrations_dir)
with extend_sys_path(temp_dir):
new_module = os.path.basename(target_dir) + '.migrations'
with self.settings(MIGRATION_MODULES={app_label: new_module}):
yield target_migrations_dir
finally:
shutil.rmtree(temp_dir)
| bsd-3-clause |
lychyi/color-tools | node_modules/node-gyp/gyp/pylib/gyp/xcode_ninja.py | 1789 | 10585 | # Copyright (c) 2014 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.
"""Xcode-ninja wrapper project file generator.
This updates the data structures passed to the Xcode gyp generator to build
with ninja instead. The Xcode project itself is transformed into a list of
executable targets, each with a build step to build with ninja, and a target
with every source and resource file. This appears to sidestep some of the
major performance headaches experienced using complex projects and large number
of targets within Xcode.
"""
import errno
import gyp.generator.ninja
import os
import re
import xml.sax.saxutils
def _WriteWorkspace(main_gyp, sources_gyp, params):
""" Create a workspace to wrap main and sources gyp paths. """
(build_file_root, build_file_ext) = os.path.splitext(main_gyp)
workspace_path = build_file_root + '.xcworkspace'
options = params['options']
if options.generator_output:
workspace_path = os.path.join(options.generator_output, workspace_path)
try:
os.makedirs(workspace_path)
except OSError, e:
if e.errno != errno.EEXIST:
raise
output_string = '<?xml version="1.0" encoding="UTF-8"?>\n' + \
'<Workspace version = "1.0">\n'
for gyp_name in [main_gyp, sources_gyp]:
name = os.path.splitext(os.path.basename(gyp_name))[0] + '.xcodeproj'
name = xml.sax.saxutils.quoteattr("group:" + name)
output_string += ' <FileRef location = %s></FileRef>\n' % name
output_string += '</Workspace>\n'
workspace_file = os.path.join(workspace_path, "contents.xcworkspacedata")
try:
with open(workspace_file, 'r') as input_file:
input_string = input_file.read()
if input_string == output_string:
return
except IOError:
# Ignore errors if the file doesn't exist.
pass
with open(workspace_file, 'w') as output_file:
output_file.write(output_string)
def _TargetFromSpec(old_spec, params):
""" Create fake target for xcode-ninja wrapper. """
# Determine ninja top level build dir (e.g. /path/to/out).
ninja_toplevel = None
jobs = 0
if params:
options = params['options']
ninja_toplevel = \
os.path.join(options.toplevel_dir,
gyp.generator.ninja.ComputeOutputDir(params))
jobs = params.get('generator_flags', {}).get('xcode_ninja_jobs', 0)
target_name = old_spec.get('target_name')
product_name = old_spec.get('product_name', target_name)
product_extension = old_spec.get('product_extension')
ninja_target = {}
ninja_target['target_name'] = target_name
ninja_target['product_name'] = product_name
if product_extension:
ninja_target['product_extension'] = product_extension
ninja_target['toolset'] = old_spec.get('toolset')
ninja_target['default_configuration'] = old_spec.get('default_configuration')
ninja_target['configurations'] = {}
# Tell Xcode to look in |ninja_toplevel| for build products.
new_xcode_settings = {}
if ninja_toplevel:
new_xcode_settings['CONFIGURATION_BUILD_DIR'] = \
"%s/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)" % ninja_toplevel
if 'configurations' in old_spec:
for config in old_spec['configurations'].iterkeys():
old_xcode_settings = \
old_spec['configurations'][config].get('xcode_settings', {})
if 'IPHONEOS_DEPLOYMENT_TARGET' in old_xcode_settings:
new_xcode_settings['CODE_SIGNING_REQUIRED'] = "NO"
new_xcode_settings['IPHONEOS_DEPLOYMENT_TARGET'] = \
old_xcode_settings['IPHONEOS_DEPLOYMENT_TARGET']
ninja_target['configurations'][config] = {}
ninja_target['configurations'][config]['xcode_settings'] = \
new_xcode_settings
ninja_target['mac_bundle'] = old_spec.get('mac_bundle', 0)
ninja_target['ios_app_extension'] = old_spec.get('ios_app_extension', 0)
ninja_target['ios_watchkit_extension'] = \
old_spec.get('ios_watchkit_extension', 0)
ninja_target['ios_watchkit_app'] = old_spec.get('ios_watchkit_app', 0)
ninja_target['type'] = old_spec['type']
if ninja_toplevel:
ninja_target['actions'] = [
{
'action_name': 'Compile and copy %s via ninja' % target_name,
'inputs': [],
'outputs': [],
'action': [
'env',
'PATH=%s' % os.environ['PATH'],
'ninja',
'-C',
new_xcode_settings['CONFIGURATION_BUILD_DIR'],
target_name,
],
'message': 'Compile and copy %s via ninja' % target_name,
},
]
if jobs > 0:
ninja_target['actions'][0]['action'].extend(('-j', jobs))
return ninja_target
def IsValidTargetForWrapper(target_extras, executable_target_pattern, spec):
"""Limit targets for Xcode wrapper.
Xcode sometimes performs poorly with too many targets, so only include
proper executable targets, with filters to customize.
Arguments:
target_extras: Regular expression to always add, matching any target.
executable_target_pattern: Regular expression limiting executable targets.
spec: Specifications for target.
"""
target_name = spec.get('target_name')
# Always include targets matching target_extras.
if target_extras is not None and re.search(target_extras, target_name):
return True
# Otherwise just show executable targets.
if spec.get('type', '') == 'executable' and \
spec.get('product_extension', '') != 'bundle':
# If there is a filter and the target does not match, exclude the target.
if executable_target_pattern is not None:
if not re.search(executable_target_pattern, target_name):
return False
return True
return False
def CreateWrapper(target_list, target_dicts, data, params):
"""Initialize targets for the ninja wrapper.
This sets up the necessary variables in the targets to generate Xcode projects
that use ninja as an external builder.
Arguments:
target_list: List of target pairs: 'base/base.gyp:base'.
target_dicts: Dict of target properties keyed on target pair.
data: Dict of flattened build files keyed on gyp path.
params: Dict of global options for gyp.
"""
orig_gyp = params['build_files'][0]
for gyp_name, gyp_dict in data.iteritems():
if gyp_name == orig_gyp:
depth = gyp_dict['_DEPTH']
# Check for custom main gyp name, otherwise use the default CHROMIUM_GYP_FILE
# and prepend .ninja before the .gyp extension.
generator_flags = params.get('generator_flags', {})
main_gyp = generator_flags.get('xcode_ninja_main_gyp', None)
if main_gyp is None:
(build_file_root, build_file_ext) = os.path.splitext(orig_gyp)
main_gyp = build_file_root + ".ninja" + build_file_ext
# Create new |target_list|, |target_dicts| and |data| data structures.
new_target_list = []
new_target_dicts = {}
new_data = {}
# Set base keys needed for |data|.
new_data[main_gyp] = {}
new_data[main_gyp]['included_files'] = []
new_data[main_gyp]['targets'] = []
new_data[main_gyp]['xcode_settings'] = \
data[orig_gyp].get('xcode_settings', {})
# Normally the xcode-ninja generator includes only valid executable targets.
# If |xcode_ninja_executable_target_pattern| is set, that list is reduced to
# executable targets that match the pattern. (Default all)
executable_target_pattern = \
generator_flags.get('xcode_ninja_executable_target_pattern', None)
# For including other non-executable targets, add the matching target name
# to the |xcode_ninja_target_pattern| regular expression. (Default none)
target_extras = generator_flags.get('xcode_ninja_target_pattern', None)
for old_qualified_target in target_list:
spec = target_dicts[old_qualified_target]
if IsValidTargetForWrapper(target_extras, executable_target_pattern, spec):
# Add to new_target_list.
target_name = spec.get('target_name')
new_target_name = '%s:%s#target' % (main_gyp, target_name)
new_target_list.append(new_target_name)
# Add to new_target_dicts.
new_target_dicts[new_target_name] = _TargetFromSpec(spec, params)
# Add to new_data.
for old_target in data[old_qualified_target.split(':')[0]]['targets']:
if old_target['target_name'] == target_name:
new_data_target = {}
new_data_target['target_name'] = old_target['target_name']
new_data_target['toolset'] = old_target['toolset']
new_data[main_gyp]['targets'].append(new_data_target)
# Create sources target.
sources_target_name = 'sources_for_indexing'
sources_target = _TargetFromSpec(
{ 'target_name' : sources_target_name,
'toolset': 'target',
'default_configuration': 'Default',
'mac_bundle': '0',
'type': 'executable'
}, None)
# Tell Xcode to look everywhere for headers.
sources_target['configurations'] = {'Default': { 'include_dirs': [ depth ] } }
sources = []
for target, target_dict in target_dicts.iteritems():
base = os.path.dirname(target)
files = target_dict.get('sources', []) + \
target_dict.get('mac_bundle_resources', [])
for action in target_dict.get('actions', []):
files.extend(action.get('inputs', []))
# Remove files starting with $. These are mostly intermediate files for the
# build system.
files = [ file for file in files if not file.startswith('$')]
# Make sources relative to root build file.
relative_path = os.path.dirname(main_gyp)
sources += [ os.path.relpath(os.path.join(base, file), relative_path)
for file in files ]
sources_target['sources'] = sorted(set(sources))
# Put sources_to_index in it's own gyp.
sources_gyp = \
os.path.join(os.path.dirname(main_gyp), sources_target_name + ".gyp")
fully_qualified_target_name = \
'%s:%s#target' % (sources_gyp, sources_target_name)
# Add to new_target_list, new_target_dicts and new_data.
new_target_list.append(fully_qualified_target_name)
new_target_dicts[fully_qualified_target_name] = sources_target
new_data_target = {}
new_data_target['target_name'] = sources_target['target_name']
new_data_target['_DEPTH'] = depth
new_data_target['toolset'] = "target"
new_data[sources_gyp] = {}
new_data[sources_gyp]['targets'] = []
new_data[sources_gyp]['included_files'] = []
new_data[sources_gyp]['xcode_settings'] = \
data[orig_gyp].get('xcode_settings', {})
new_data[sources_gyp]['targets'].append(new_data_target)
# Write workspace to file.
_WriteWorkspace(main_gyp, sources_gyp, params)
return (new_target_list, new_target_dicts, new_data)
| apache-2.0 |
balazsdukai/GEO1005-StormManager | SpatialDecision/test/test_resources.py | 9 | 1052 | # coding=utf-8
"""Resources test.
.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
"""
__author__ = 'j.a.lopesgil@tudelft.nl'
__date__ = '2015-11-02'
__copyright__ = 'Copyright 2015, Jorge Gil, TU Delft'
import unittest
from PyQt4.QtGui import QIcon
class SpatialDecisionDialogTest(unittest.TestCase):
"""Test rerources work."""
def setUp(self):
"""Runs before each test."""
pass
def tearDown(self):
"""Runs after each test."""
pass
def test_icon_png(self):
"""Test we can click OK."""
path = ':/plugins/SpatialDecision/icon.png'
icon = QIcon(path)
self.assertFalse(icon.isNull())
if __name__ == "__main__":
suite = unittest.makeSuite(SpatialDecisionResourcesTest)
runner = unittest.TextTestRunner(verbosity=2)
runner.run(suite)
| gpl-2.0 |
incaser/odoo-odoo | addons/account_analytic_default/account_analytic_default.py | 256 | 8118 | # -*- 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/>.
#
##############################################################################
import time
from openerp.osv import fields, osv
class account_analytic_default(osv.osv):
_name = "account.analytic.default"
_description = "Analytic Distribution"
_rec_name = "analytic_id"
_order = "sequence"
_columns = {
'sequence': fields.integer('Sequence', help="Gives the sequence order when displaying a list of analytic distribution"),
'analytic_id': fields.many2one('account.analytic.account', 'Analytic Account'),
'product_id': fields.many2one('product.product', 'Product', ondelete='cascade', help="Select a product which will use analytic account specified in analytic default (e.g. create new customer invoice or Sales order if we select this product, it will automatically take this as an analytic account)"),
'partner_id': fields.many2one('res.partner', 'Partner', ondelete='cascade', help="Select a partner which will use analytic account specified in analytic default (e.g. create new customer invoice or Sales order if we select this partner, it will automatically take this as an analytic account)"),
'user_id': fields.many2one('res.users', 'User', ondelete='cascade', help="Select a user which will use analytic account specified in analytic default."),
'company_id': fields.many2one('res.company', 'Company', ondelete='cascade', help="Select a company which will use analytic account specified in analytic default (e.g. create new customer invoice or Sales order if we select this company, it will automatically take this as an analytic account)"),
'date_start': fields.date('Start Date', help="Default start date for this Analytic Account."),
'date_stop': fields.date('End Date', help="Default end date for this Analytic Account."),
}
def account_get(self, cr, uid, product_id=None, partner_id=None, user_id=None, date=None, company_id=None, context=None):
domain = []
if product_id:
domain += ['|', ('product_id', '=', product_id)]
domain += [('product_id','=', False)]
if partner_id:
domain += ['|', ('partner_id', '=', partner_id)]
domain += [('partner_id', '=', False)]
if company_id:
domain += ['|', ('company_id', '=', company_id)]
domain += [('company_id', '=', False)]
if user_id:
domain += ['|',('user_id', '=', user_id)]
domain += [('user_id','=', False)]
if date:
domain += ['|', ('date_start', '<=', date), ('date_start', '=', False)]
domain += ['|', ('date_stop', '>=', date), ('date_stop', '=', False)]
best_index = -1
res = False
for rec in self.browse(cr, uid, self.search(cr, uid, domain, context=context), context=context):
index = 0
if rec.product_id: index += 1
if rec.partner_id: index += 1
if rec.company_id: index += 1
if rec.user_id: index += 1
if rec.date_start: index += 1
if rec.date_stop: index += 1
if index > best_index:
res = rec
best_index = index
return res
class account_invoice_line(osv.osv):
_inherit = "account.invoice.line"
_description = "Invoice Line"
def product_id_change(self, cr, uid, ids, product, uom_id, qty=0, name='', type='out_invoice', partner_id=False, fposition_id=False, price_unit=False, currency_id=False, company_id=None, context=None):
res_prod = super(account_invoice_line, self).product_id_change(cr, uid, ids, product, uom_id, qty, name, type, partner_id, fposition_id, price_unit, currency_id=currency_id, company_id=company_id, context=context)
rec = self.pool.get('account.analytic.default').account_get(cr, uid, product, partner_id, uid, time.strftime('%Y-%m-%d'), company_id=company_id, context=context)
if rec:
res_prod['value'].update({'account_analytic_id': rec.analytic_id.id})
else:
res_prod['value'].update({'account_analytic_id': False})
return res_prod
class stock_picking(osv.osv):
_inherit = "stock.picking"
def _get_account_analytic_invoice(self, cursor, user, picking, move_line):
partner_id = picking.partner_id and picking.partner_id.id or False
rec = self.pool.get('account.analytic.default').account_get(cursor, user, move_line.product_id.id, partner_id, user, time.strftime('%Y-%m-%d'))
if rec:
return rec.analytic_id.id
return super(stock_picking, self)._get_account_analytic_invoice(cursor, user, picking, move_line)
class sale_order_line(osv.osv):
_inherit = "sale.order.line"
# Method overridden to set the analytic account by default on criterion match
def invoice_line_create(self, cr, uid, ids, context=None):
create_ids = super(sale_order_line, self).invoice_line_create(cr, uid, ids, context=context)
if not ids:
return create_ids
sale_line = self.browse(cr, uid, ids[0], context=context)
inv_line_obj = self.pool.get('account.invoice.line')
anal_def_obj = self.pool.get('account.analytic.default')
for line in inv_line_obj.browse(cr, uid, create_ids, context=context):
rec = anal_def_obj.account_get(cr, uid, line.product_id.id, sale_line.order_id.partner_id.id, sale_line.order_id.user_id.id, time.strftime('%Y-%m-%d'), context=context)
if rec:
inv_line_obj.write(cr, uid, [line.id], {'account_analytic_id': rec.analytic_id.id}, context=context)
return create_ids
class product_product(osv.Model):
_inherit = 'product.product'
def _rules_count(self, cr, uid, ids, field_name, arg, context=None):
Analytic = self.pool['account.analytic.default']
return {
product_id: Analytic.search_count(cr, uid, [('product_id', '=', product_id)], context=context)
for product_id in ids
}
_columns = {
'rules_count': fields.function(_rules_count, string='# Analytic Rules', type='integer'),
}
class product_template(osv.Model):
_inherit = 'product.template'
def _rules_count(self, cr, uid, ids, field_name, arg, context=None):
Analytic = self.pool['account.analytic.default']
res = {}
for product_tmpl_id in self.browse(cr, uid, ids, context=context):
res[product_tmpl_id.id] = sum([p.rules_count for p in product_tmpl_id.product_variant_ids])
return res
_columns = {
'rules_count': fields.function(_rules_count, string='# Analytic Rules', type='integer'),
}
def action_view_rules(self, cr, uid, ids, context=None):
products = self._get_products(cr, uid, ids, context=context)
result = self._get_act_window_dict(cr, uid, 'account_analytic_default.action_product_default_list', context=context)
result['domain'] = "[('product_id','in',[" + ','.join(map(str, products)) + "])]"
# Remove context so it is not going to filter on product_id with active_id of template
result['context'] = "{}"
return result
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
catapult-project/catapult | dashboard/dashboard/get_histogram.py | 3 | 1276 | # Copyright 2017 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.
"""URL endpoint for getting a histogram."""
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import json
from google.appengine.ext import ndb
from dashboard.common import request_handler
class GetHistogramHandler(request_handler.RequestHandler):
"""URL endpoint to get histogramby guid."""
def post(self):
"""Fetches a histogram by guid.
Request parameters:
guid: GUID of requested histogram.
Outputs:
JSON serialized Histogram.
"""
guid = self.request.get('guid')
if not guid:
self.ReportError('Missing "guid" parameter', status=400)
return
histogram_key = ndb.Key('Histogram', guid)
try:
histogram_entity = histogram_key.get()
except AssertionError:
# Thrown if accessing internal_only as an external user.
self.ReportError('Histogram "%s" not found' % guid, status=400)
return
if not histogram_entity:
self.ReportError('Histogram "%s" not found' % guid, status=400)
return
self.response.out.write(json.dumps(histogram_entity.data))
| bsd-3-clause |
chaosblog/pyload | module/plugins/hoster/GoogledriveCom.py | 7 | 1674 | # -*- coding: utf-8 -*
#
# Test links:
# https://drive.google.com/file/d/0B6RNTe4ygItBQm15RnJiTmMyckU/view?pli=1
import re
import urlparse
from module.plugins.internal.SimpleHoster import SimpleHoster, create_getInfo
from module.utils import html_unescape
class GoogledriveCom(SimpleHoster):
__name__ = "GoogledriveCom"
__type__ = "hoster"
__version__ = "0.14"
__status__ = "testing"
__pattern__ = r'https?://(?:www\.)?(drive|docs)\.google\.com/(file/d/\w+|uc\?.*id=)'
__config__ = [("use_premium", "bool", "Use premium account if available", True)]
__description__ = """Drive.google.com hoster plugin"""
__license__ = "GPLv3"
__authors__ = [("zapp-brannigan", "fuerst.reinje@web.de")]
NAME_PATTERN = r'(?:<title>|class="uc-name-size".*>)(?P<N>.+?)(?: - Google Drive</title>|</a> \()'
OFFLINE_PATTERN = r'align="center"><p class="errorMessage"'
LINK_FREE_PATTERN = r'"([^"]+uc\?.*?)"'
def setup(self):
self.multiDL = True
self.resume_download = True
self.chunk_limit = 1
def handle_free(self, pyfile):
for _i in xrange(2):
m = re.search(self.LINK_FREE_PATTERN, self.html)
if m is None:
self.error(_("Free download link not found"))
else:
link = self.fixurl(link, "https://docs.google.com/")
direct_link = self.direct_link(link, False)
if not direct_link:
self.html = self.load(link)
else:
self.link = direct_link
break
getInfo = create_getInfo(GoogledriveCom)
| gpl-3.0 |
Learningtribes/edx-platform | cms/djangoapps/contentstore/features/problem-editor.py | 32 | 12791 | # disable missing docstring
# pylint: disable=missing-docstring
import json
from lettuce import world, step
from nose.tools import assert_equal, assert_true
from common import type_in_codemirror, open_new_course
from advanced_settings import change_value, ADVANCED_MODULES_KEY
from course_import import import_file
DISPLAY_NAME = "Display Name"
MAXIMUM_ATTEMPTS = "Maximum Attempts"
PROBLEM_WEIGHT = "Problem Weight"
RANDOMIZATION = 'Randomization'
SHOW_ANSWER = "Show Answer"
SHOW_RESET_BUTTON = "Show Reset Button"
TIMER_BETWEEN_ATTEMPTS = "Timer Between Attempts"
MATLAB_API_KEY = "Matlab API key"
@step('I have created a Blank Common Problem$')
def i_created_blank_common_problem(step):
step.given('I am in Studio editing a new unit')
step.given("I have created another Blank Common Problem")
@step('I have created a unit with advanced module "(.*)"$')
def i_created_unit_with_advanced_module(step, advanced_module):
step.given('I am in Studio editing a new unit')
url = world.browser.url
step.given("I select the Advanced Settings")
change_value(step, ADVANCED_MODULES_KEY, '["{}"]'.format(advanced_module))
world.visit(url)
world.wait_for_xmodule()
@step('I have created an advanced component "(.*)" of type "(.*)"')
def i_create_new_advanced_component(step, component_type, advanced_component):
world.create_component_instance(
step=step,
category='advanced',
component_type=component_type,
advanced_component=advanced_component
)
@step('I have created another Blank Common Problem$')
def i_create_new_common_problem(step):
world.create_component_instance(
step=step,
category='problem',
component_type='Blank Common Problem'
)
@step('when I mouseover on "(.*)"')
def i_mouseover_on_html_component(step, element_class):
action_css = '.{}'.format(element_class)
world.trigger_event(action_css, event='mouseover')
@step(u'I can see Reply to Annotation link$')
def i_see_reply_to_annotation_link(_step):
css_selector = 'a.annotatable-reply'
world.wait_for_visible(css_selector)
@step(u'I see that page has scrolled "(.*)" when I click on "(.*)" link$')
def i_see_annotation_problem_page_scrolls(_step, scroll_direction, link_css):
scroll_js = "$(window).scrollTop();"
scroll_height_before = world.browser.evaluate_script(scroll_js)
world.css_click("a.{}".format(link_css))
scroll_height_after = world.browser.evaluate_script(scroll_js)
if scroll_direction == "up":
assert scroll_height_after < scroll_height_before
elif scroll_direction == "down":
assert scroll_height_after > scroll_height_before
@step('I have created an advanced problem of type "(.*)"$')
def i_create_new_advanced_problem(step, component_type):
world.create_component_instance(
step=step,
category='problem',
component_type=component_type,
is_advanced=True
)
@step('I edit and select Settings$')
def i_edit_and_select_settings(_step):
world.edit_component_and_select_settings()
@step('I see the advanced settings and their expected values$')
def i_see_advanced_settings_with_values(step):
world.verify_all_setting_entries(
[
[DISPLAY_NAME, "Blank Common Problem", True],
[MATLAB_API_KEY, "", False],
[MAXIMUM_ATTEMPTS, "", False],
[PROBLEM_WEIGHT, "", False],
[RANDOMIZATION, "Never", False],
[SHOW_ANSWER, "Finished", False],
[SHOW_RESET_BUTTON, "False", False],
[TIMER_BETWEEN_ATTEMPTS, "0", False],
])
@step('I can modify the display name')
def i_can_modify_the_display_name(_step):
# Verifying that the display name can be a string containing a floating point value
# (to confirm that we don't throw an error because it is of the wrong type).
index = world.get_setting_entry_index(DISPLAY_NAME)
world.set_field_value(index, '3.4')
verify_modified_display_name()
@step('my display name change is persisted on save')
def my_display_name_change_is_persisted_on_save(step):
world.save_component_and_reopen(step)
verify_modified_display_name()
@step('the problem display name is "(.*)"$')
def verify_problem_display_name(step, name):
"""
name is uppercased because the heading styles are uppercase in css
"""
assert_equal(name, world.browser.find_by_css('.problem-header').text)
@step('I can specify special characters in the display name')
def i_can_modify_the_display_name_with_special_chars(_step):
index = world.get_setting_entry_index(DISPLAY_NAME)
world.set_field_value(index, "updated ' \" &")
verify_modified_display_name_with_special_chars()
@step('I can specify html in the display name and save')
def i_can_modify_the_display_name_with_html(_step):
"""
If alert appear on save then UnexpectedAlertPresentException
will occur and test will fail.
"""
index = world.get_setting_entry_index(DISPLAY_NAME)
world.set_field_value(index, "<script>alert('test')</script>")
verify_modified_display_name_with_html()
world.save_component()
@step('my special characters and persisted on save')
def special_chars_persisted_on_save(step):
world.save_component_and_reopen(step)
verify_modified_display_name_with_special_chars()
@step('I can revert the display name to unset')
def can_revert_display_name_to_unset(_step):
world.revert_setting_entry(DISPLAY_NAME)
verify_unset_display_name()
@step('my display name is unset on save')
def my_display_name_is_persisted_on_save(step):
world.save_component_and_reopen(step)
verify_unset_display_name()
@step('I can select Per Student for Randomization')
def i_can_select_per_student_for_randomization(_step):
world.browser.select(RANDOMIZATION, "Per Student")
verify_modified_randomization()
@step('my change to randomization is persisted')
def my_change_to_randomization_is_persisted(step):
world.save_component_and_reopen(step)
verify_modified_randomization()
@step('I can revert to the default value for randomization')
def i_can_revert_to_default_for_randomization(step):
world.revert_setting_entry(RANDOMIZATION)
world.save_component_and_reopen(step)
world.verify_setting_entry(world.get_setting_entry(RANDOMIZATION), RANDOMIZATION, "Never", False)
@step('I can set the weight to "(.*)"?')
def i_can_set_weight(_step, weight):
set_weight(weight)
verify_modified_weight()
@step('my change to weight is persisted')
def my_change_to_weight_is_persisted(step):
world.save_component_and_reopen(step)
verify_modified_weight()
@step('I can revert to the default value of unset for weight')
def i_can_revert_to_default_for_unset_weight(step):
world.revert_setting_entry(PROBLEM_WEIGHT)
world.save_component_and_reopen(step)
world.verify_setting_entry(world.get_setting_entry(PROBLEM_WEIGHT), PROBLEM_WEIGHT, "", False)
@step('if I set the weight to "(.*)", it remains unset')
def set_the_weight_to_abc(step, bad_weight):
set_weight(bad_weight)
# We show the clear button immediately on type, hence the "True" here.
world.verify_setting_entry(world.get_setting_entry(PROBLEM_WEIGHT), PROBLEM_WEIGHT, "", True)
world.save_component_and_reopen(step)
# But no change was actually ever sent to the model, so on reopen, explicitly_set is False
world.verify_setting_entry(world.get_setting_entry(PROBLEM_WEIGHT), PROBLEM_WEIGHT, "", False)
@step('if I set the max attempts to "(.*)", it will persist as a valid integer$')
def set_the_max_attempts(step, max_attempts_set):
# on firefox with selenium, the behavior is different.
# eg 2.34 displays as 2.34 and is persisted as 2
index = world.get_setting_entry_index(MAXIMUM_ATTEMPTS)
world.set_field_value(index, max_attempts_set)
world.save_component_and_reopen(step)
value = world.css_value('input.setting-input', index=index)
assert value != "", "max attempts is blank"
assert int(value) >= 0
@step('Edit High Level Source is not visible')
def edit_high_level_source_not_visible(step):
verify_high_level_source_links(step, False)
@step('Edit High Level Source is visible')
def edit_high_level_source_links_visible(step):
verify_high_level_source_links(step, True)
@step('If I press Cancel my changes are not persisted')
def cancel_does_not_save_changes(step):
world.cancel_component(step)
step.given("I edit and select Settings")
step.given("I see the advanced settings and their expected values")
@step('I have enabled latex compiler')
def enable_latex_compiler(step):
url = world.browser.url
step.given("I select the Advanced Settings")
change_value(step, 'Enable LaTeX Compiler', 'true')
world.visit(url)
world.wait_for_xmodule()
@step('I have created a LaTeX Problem')
def create_latex_problem(step):
step.given('I am in Studio editing a new unit')
step.given('I have enabled latex compiler')
world.create_component_instance(
step=step,
category='problem',
component_type='Problem Written in LaTeX',
is_advanced=True
)
@step('I edit and compile the High Level Source')
def edit_latex_source(_step):
open_high_level_source()
type_in_codemirror(1, "hi")
world.css_click('.hls-compile')
@step('my change to the High Level Source is persisted')
def high_level_source_persisted(_step):
def verify_text(driver):
css_sel = '.problem div>span'
return world.css_text(css_sel) == 'hi'
world.wait_for(verify_text, timeout=10)
@step('I view the High Level Source I see my changes')
def high_level_source_in_editor(_step):
open_high_level_source()
assert_equal('hi', world.css_value('.source-edit-box'))
@step(u'I have an empty course')
def i_have_empty_course(step):
open_new_course()
@step(u'I import the file "([^"]*)"$')
def i_import_the_file(_step, filename):
import_file(filename)
@step(u'I go to the vertical "([^"]*)"$')
def i_go_to_vertical(_step, vertical):
world.css_click("span:contains('{0}')".format(vertical))
@step(u'I go to the unit "([^"]*)"$')
def i_go_to_unit(_step, unit):
loc = "window.location = $(\"span:contains('{0}')\").closest('a').attr('href')".format(unit)
world.browser.execute_script(loc)
@step(u'I see a message that says "([^"]*)"$')
def i_can_see_message(_step, msg):
msg = json.dumps(msg) # escape quotes
world.css_has_text("h2.title", msg)
@step(u'I can edit the problem$')
def i_can_edit_problem(_step):
world.edit_component()
@step(u'I edit first blank advanced problem for annotation response$')
def i_edit_blank_problem_for_annotation_response(_step):
world.edit_component(1)
text = """
<problem>
<annotationresponse>
<annotationinput><text>Text of annotation</text></annotationinput>
</annotationresponse>
</problem>"""
type_in_codemirror(0, text)
world.save_component()
@step(u'I can see cheatsheet$')
def verify_cheat_sheet_displaying(_step):
world.css_click(".cheatsheet-toggle")
css_selector = '.simple-editor-cheatsheet'
world.wait_for_visible(css_selector)
def verify_high_level_source_links(step, visible):
if visible:
assert_true(world.is_css_present('.launch-latex-compiler'),
msg="Expected to find the latex button but it is not present.")
else:
assert_true(world.is_css_not_present('.launch-latex-compiler'),
msg="Expected not to find the latex button but it is present.")
world.cancel_component(step)
def verify_modified_weight():
world.verify_setting_entry(world.get_setting_entry(PROBLEM_WEIGHT), PROBLEM_WEIGHT, "3.5", True)
def verify_modified_randomization():
world.verify_setting_entry(world.get_setting_entry(RANDOMIZATION), RANDOMIZATION, "Per Student", True)
def verify_modified_display_name():
world.verify_setting_entry(world.get_setting_entry(DISPLAY_NAME), DISPLAY_NAME, '3.4', True)
def verify_modified_display_name_with_special_chars():
world.verify_setting_entry(world.get_setting_entry(DISPLAY_NAME), DISPLAY_NAME, "updated ' \" &", True)
def verify_modified_display_name_with_html():
world.verify_setting_entry(world.get_setting_entry(DISPLAY_NAME), DISPLAY_NAME, "<script>alert('test')</script>", True)
def verify_unset_display_name():
world.verify_setting_entry(world.get_setting_entry(DISPLAY_NAME), DISPLAY_NAME, 'Blank Advanced Problem', False)
def set_weight(weight):
index = world.get_setting_entry_index(PROBLEM_WEIGHT)
world.set_field_value(index, weight)
def open_high_level_source():
world.edit_component()
world.css_click('.launch-latex-compiler > a')
| agpl-3.0 |
BigBrother1984/android_external_chromium_org | chrome/common/extensions/docs/server2/path_canonicalizer.py | 24 | 4413 | # Copyright 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.
import logging
import os
import posixpath
import traceback
from branch_utility import BranchUtility
from file_system import FileNotFoundError
from third_party.json_schema_compiler.model import UnixName
import svn_constants
def _SimplifyFileName(file_name):
return (posixpath.splitext(file_name)[0]
.lower()
.replace('.', '')
.replace('-', '')
.replace('_', ''))
class PathCanonicalizer(object):
'''Transforms paths into their canonical forms. Since the dev server has had
many incarnations - e.g. there didn't use to be apps/ - there may be old
paths lying around the webs. We try to redirect those to where they are now.
'''
def __init__(self, compiled_fs_factory):
# Map of simplified API names (for typo detection) to their real paths.
def make_public_apis(_, file_names):
return dict((_SimplifyFileName(name), name) for name in file_names)
self._public_apis = compiled_fs_factory.Create(make_public_apis,
PathCanonicalizer)
def Canonicalize(self, path):
'''Returns the canonical path for |path|, and whether that path is a
permanent canonicalisation (e.g. when we redirect from a channel to a
channel-less URL) or temporary (e.g. when we redirect from an apps-only API
to an extensions one - we may at some point enable it for extensions).
'''
class ReturnType(object):
def __init__(self, path, permanent):
self.path = path
self.permanent = permanent
# Catch incorrect comparisons by disabling ==/!=.
def __eq__(self, _): raise NotImplementedError()
def __ne__(self, _): raise NotImplementedError()
# Strip any channel info off it. There are no channels anymore.
for channel_name in BranchUtility.GetAllChannelNames():
channel_prefix = channel_name + '/'
if path.startswith(channel_prefix):
# Redirect now so that we can set the permanent-redirect bit. Channel
# redirects are the only things that should be permanent redirects;
# anything else *could* change, so is temporary.
return ReturnType(path[len(channel_prefix):], True)
# No further work needed for static.
if path.startswith('static/'):
return ReturnType(path, False)
# People go to just "extensions" or "apps". Redirect to the directory.
if path in ('extensions', 'apps'):
return ReturnType(path + '/', False)
# The rest of this function deals with trying to figure out what API page
# for extensions/apps to redirect to, if any. We see a few different cases
# here:
# - Unqualified names ("browserAction.html"). These are easy to resolve;
# figure out whether it's an extension or app API and redirect.
# - but what if it's both? Well, assume extensions. Maybe later we can
# check analytics and see which is more popular.
# - Wrong names ("apps/browserAction.html"). This really does happen,
# damn it, so do the above logic but record which is the default.
if path.startswith(('extensions/', 'apps/')):
default_platform, reference_path = path.split('/', 1)
else:
default_platform, reference_path = ('extensions', path)
try:
apps_public = self._public_apis.GetFromFileListing(
'/'.join((svn_constants.PUBLIC_TEMPLATE_PATH, 'apps')))
extensions_public = self._public_apis.GetFromFileListing(
'/'.join((svn_constants.PUBLIC_TEMPLATE_PATH, 'extensions')))
except FileNotFoundError:
# Probably offline.
logging.warning(traceback.format_exc())
return ReturnType(path, False)
simple_reference_path = _SimplifyFileName(reference_path)
apps_path = apps_public.get(simple_reference_path)
extensions_path = extensions_public.get(simple_reference_path)
if apps_path is None:
if extensions_path is None:
# No idea. Just return the original path. It'll probably 404.
pass
else:
path = 'extensions/%s' % extensions_path
else:
if extensions_path is None:
path = 'apps/%s' % apps_path
else:
assert apps_path == extensions_path
path = '%s/%s' % (default_platform, apps_path)
return ReturnType(path, False)
| bsd-3-clause |
jbassen/edx-platform | lms/djangoapps/psychometrics/psychoanalyze.py | 68 | 11511 | #
# File: psychometrics/psychoanalyze.py
#
# generate pyschometrics plots from PsychometricData
from __future__ import division
import datetime
import logging
import json
import math
import numpy as np
from opaque_keys.edx.locator import BlockUsageLocator
from scipy.optimize import curve_fit
from django.conf import settings
from django.db.models import Sum, Max
from psychometrics.models import PsychometricData
from courseware.models import StudentModule
from pytz import UTC
log = logging.getLogger("edx.psychometrics")
#db = "ocwtutor" # for debugging
#db = "default"
db = getattr(settings, 'DATABASE_FOR_PSYCHOMETRICS', 'default')
#-----------------------------------------------------------------------------
# fit functions
def func_2pl(x, a, b):
"""
2-parameter logistic function
"""
D = 1.7
edax = np.exp(D * a * (x - b))
return edax / (1 + edax)
#-----------------------------------------------------------------------------
# statistics class
class StatVar(object):
"""
Simple statistics on floating point numbers: avg, sdv, var, min, max
"""
def __init__(self, unit=1):
self.sum = 0
self.sum2 = 0
self.cnt = 0
self.unit = unit
self.min = None
self.max = None
def add(self, x):
if x is None:
return
if self.min is None:
self.min = x
else:
if x < self.min:
self.min = x
if self.max is None:
self.max = x
else:
if x > self.max:
self.max = x
self.sum += x
self.sum2 += x ** 2
self.cnt += 1
def avg(self):
if self.cnt is None:
return 0
return self.sum / 1.0 / self.cnt / self.unit
def var(self):
if self.cnt is None:
return 0
return (self.sum2 / 1.0 / self.cnt / (self.unit ** 2)) - (self.avg() ** 2)
def sdv(self):
v = self.var()
if v > 0:
return math.sqrt(v)
else:
return 0
def __str__(self):
return 'cnt=%d, avg=%f, sdv=%f' % (self.cnt, self.avg(), self.sdv())
def __add__(self, x):
self.add(x)
return self
#-----------------------------------------------------------------------------
# histogram generator
def make_histogram(ydata, bins=None):
'''
Generate histogram of ydata using bins provided, or by default bins
from 0 to 100 by 10. bins should be ordered in increasing order.
returns dict with keys being bins, and values being counts.
special: hist['bins'] = bins
'''
if bins is None:
bins = range(0, 100, 10)
nbins = len(bins)
hist = dict(zip(bins, [0] * nbins))
for y in ydata:
for b in bins[::-1]: # in reverse order
if y > b:
hist[b] += 1
break
# hist['bins'] = bins
return hist
#-----------------------------------------------------------------------------
def problems_with_psychometric_data(course_id):
'''
Return dict of {problems (location urls): count} for which psychometric data is available.
Does this for a given course_id.
'''
pmdset = PsychometricData.objects.using(db).filter(studentmodule__course_id=course_id)
plist = [p['studentmodule__module_state_key'] for p in pmdset.values('studentmodule__module_state_key').distinct()]
problems = dict(
(
p,
pmdset.filter(
studentmodule__module_state_key=BlockUsageLocator.from_string(p)
).count()
) for p in plist
)
return problems
#-----------------------------------------------------------------------------
def generate_plots_for_problem(problem):
pmdset = PsychometricData.objects.using(db).filter(
studentmodule__module_state_key=BlockUsageLocator.from_string(problem)
)
nstudents = pmdset.count()
msg = ""
plots = []
if nstudents < 2:
msg += "%s nstudents=%d --> skipping, too few" % (problem, nstudents)
return msg, plots
max_grade = pmdset[0].studentmodule.max_grade
agdat = pmdset.aggregate(Sum('attempts'), Max('attempts'))
max_attempts = agdat['attempts__max']
total_attempts = agdat['attempts__sum'] # not used yet
msg += "max attempts = %d" % max_attempts
xdat = range(1, max_attempts + 1)
dataset = {'xdat': xdat}
# compute grade statistics
grades = [pmd.studentmodule.grade for pmd in pmdset]
gsv = StatVar()
for g in grades:
gsv += g
msg += "<br><p><font color='blue'>Grade distribution: %s</font></p>" % gsv
# generate grade histogram
ghist = []
axisopts = """{
xaxes: [{
axisLabel: 'Grade'
}],
yaxes: [{
position: 'left',
axisLabel: 'Count'
}]
}"""
if gsv.max > max_grade:
msg += "<br/><p><font color='red'>Something is wrong: max_grade=%s, but max(grades)=%s</font></p>" % (max_grade, gsv.max)
max_grade = gsv.max
if max_grade > 1:
ghist = make_histogram(grades, np.linspace(0, max_grade, max_grade + 1))
ghist_json = json.dumps(ghist.items())
plot = {'title': "Grade histogram for %s" % problem,
'id': 'histogram',
'info': '',
'data': "var dhist = %s;\n" % ghist_json,
'cmd': '[ {data: dhist, bars: { show: true, align: "center" }} ], %s' % axisopts,
}
plots.append(plot)
else:
msg += "<br/>Not generating histogram: max_grade=%s" % max_grade
# histogram of time differences between checks
# Warning: this is inefficient - doesn't scale to large numbers of students
dtset = [] # time differences in minutes
dtsv = StatVar()
for pmd in pmdset:
try:
checktimes = eval(pmd.checktimes) # update log of attempt timestamps
except:
continue
if len(checktimes) < 2:
continue
ct0 = checktimes[0]
for ct in checktimes[1:]:
dt = (ct - ct0).total_seconds() / 60.0
if dt < 20: # ignore if dt too long
dtset.append(dt)
dtsv += dt
ct0 = ct
if dtsv.cnt > 2:
msg += "<br/><p><font color='brown'>Time differences between checks: %s</font></p>" % dtsv
bins = np.linspace(0, 1.5 * dtsv.sdv(), 30)
dbar = bins[1] - bins[0]
thist = make_histogram(dtset, bins)
thist_json = json.dumps(sorted(thist.items(), key=lambda(x): x[0]))
axisopts = """{ xaxes: [{ axisLabel: 'Time (min)'}], yaxes: [{position: 'left',axisLabel: 'Count'}]}"""
plot = {'title': "Histogram of time differences between checks",
'id': 'thistogram',
'info': '',
'data': "var thist = %s;\n" % thist_json,
'cmd': '[ {data: thist, bars: { show: true, align: "center", barWidth:%f }} ], %s' % (dbar, axisopts),
}
plots.append(plot)
# one IRT plot curve for each grade received (TODO: this assumes integer grades)
for grade in range(1, int(max_grade) + 1):
yset = {}
gset = pmdset.filter(studentmodule__grade=grade)
ngset = gset.count()
if ngset == 0:
continue
ydat = []
ylast = 0
for x in xdat:
y = gset.filter(attempts=x).count() / ngset
ydat.append(y + ylast)
ylast = y + ylast
yset['ydat'] = ydat
if len(ydat) > 3: # try to fit to logistic function if enough data points
try:
cfp = curve_fit(func_2pl, xdat, ydat, [1.0, max_attempts / 2.0])
yset['fitparam'] = cfp
yset['fitpts'] = func_2pl(np.array(xdat), *cfp[0])
yset['fiterr'] = [yd - yf for (yd, yf) in zip(ydat, yset['fitpts'])]
fitx = np.linspace(xdat[0], xdat[-1], 100)
yset['fitx'] = fitx
yset['fity'] = func_2pl(np.array(fitx), *cfp[0])
except Exception as err:
log.debug('Error in psychoanalyze curve fitting: %s', err)
dataset['grade_%d' % grade] = yset
axisopts = """{
xaxes: [{
axisLabel: 'Number of Attempts'
}],
yaxes: [{
max:1.0,
position: 'left',
axisLabel: 'Probability of correctness'
}]
}"""
# generate points for flot plot
for grade in range(1, int(max_grade) + 1):
jsdata = ""
jsplots = []
gkey = 'grade_%d' % grade
if gkey in dataset:
yset = dataset[gkey]
jsdata += "var d%d = %s;\n" % (grade, json.dumps(zip(xdat, yset['ydat'])))
jsplots.append('{ data: d%d, lines: { show: false }, points: { show: true}, color: "red" }' % grade)
if 'fitpts' in yset:
jsdata += 'var fit = %s;\n' % (json.dumps(zip(yset['fitx'], yset['fity'])))
jsplots.append('{ data: fit, lines: { show: true }, color: "blue" }')
(a, b) = yset['fitparam'][0]
irtinfo = "(2PL: D=1.7, a=%6.3f, b=%6.3f)" % (a, b)
else:
irtinfo = ""
plots.append({'title': 'IRT Plot for grade=%s %s' % (grade, irtinfo),
'id': "irt%s" % grade,
'info': '',
'data': jsdata,
'cmd': '[%s], %s' % (','.join(jsplots), axisopts),
})
#log.debug('plots = %s' % plots)
return msg, plots
#-----------------------------------------------------------------------------
def make_psychometrics_data_update_handler(course_id, user, module_state_key):
"""
Construct and return a procedure which may be called to update
the PsychometricData instance for the given StudentModule instance.
"""
sm, status = StudentModule.objects.get_or_create(
course_id=course_id,
student=user,
module_state_key=module_state_key,
defaults={'state': '{}', 'module_type': 'problem'},
)
try:
pmd = PsychometricData.objects.using(db).get(studentmodule=sm)
except PsychometricData.DoesNotExist:
pmd = PsychometricData(studentmodule=sm)
def psychometrics_data_update_handler(state):
"""
This function may be called each time a problem is successfully checked
(eg on save_problem_check events in capa_module).
state = instance state (a nice, uniform way to interface - for more future psychometric feature extraction)
"""
try:
state = json.loads(sm.state)
done = state['done']
except:
log.exception("Oops, failed to eval state for %s (state=%s)", sm, sm.state)
return
pmd.done = done
try:
pmd.attempts = state.get('attempts', 0)
except:
log.exception("no attempts for %s (state=%s)", sm, sm.state)
try:
checktimes = eval(pmd.checktimes) # update log of attempt timestamps
except:
checktimes = []
checktimes.append(datetime.datetime.now(UTC))
pmd.checktimes = checktimes
try:
pmd.save()
except:
log.exception("Error in updating psychometrics data for %s", sm)
return psychometrics_data_update_handler
| agpl-3.0 |
DemocracyClub/UK-Polling-Stations | polling_stations/apps/data_importers/management/commands/import_newham.py | 1 | 1481 | from data_importers.management.commands import BaseXpressDemocracyClubCsvImporter
class Command(BaseXpressDemocracyClubCsvImporter):
council_id = "NWM"
addresses_name = "2021-03-22T13:30:16.944061/Democracy_Club__06May2021.CSV"
stations_name = "2021-03-22T13:30:16.944061/Democracy_Club__06May2021.CSV"
elections = ["2021-05-06"]
def station_record_to_dict(self, record):
# Fix from: 890908:polling_stations/apps/data_importers/management/commands/misc_fixes.py:224
# Carpenters and Docklands Centre 98 Gibbins Road Stratford London
if record.polling_place_id == "5614":
record = record._replace(polling_place_easting="538526.11")
record = record._replace(polling_place_northing="184252.81")
return super().station_record_to_dict(record)
def address_record_to_dict(self, record):
uprn = record.property_urn.strip().lstrip("0")
if uprn in [
"46003425", # 499A BARKING ROAD, LONDON
"10090756873", # FLAT 1 23 NOTTINGHAM AVENUE, WEST BECKTON, LONDON
"10009012301", # 140B BARKING ROAD, LONDON
"10034508484", # FLAT ABOVE 33 VICARAGE LANE, EAST HAM, LONDON
"10009012905", # 62A TREE ROAD, WEST BECKTON, LONDON
"10008988958",
"10094371250",
]:
return None # in an otherwise multiple station postcode, so safe to remove
return super().address_record_to_dict(record)
| bsd-3-clause |
DKarev/isolation-forest | clearcut_utils.py | 1 | 2088 | #!/usr/bin/env python
import pandas as pd
import numpy as np
def load_brofile(filename, fields_to_use):
fields = ['ts',
'uid',
'orig_h',
'orig_p',
'resp_h',
'resp_p',
'trans_depth',
'method',
'host',
'uri',
'referrer',
'user_agent',
'request_body_len',
'response_body_len',
'status_code',
'status_msg',
'info_code',
'info_msg',
'filename',
'tags',
'username',
'password',
'proxied orig_fuids',
'orig_mime_types',
'resp_fuids',
'resp_mime_types']
df = pd.read_csv(filename,
header=None,
sep='\t',
names=fields,
skiprows=8,
skipfooter=1,
index_col=False,
quotechar=None,
quoting=3,
engine='python')
return df[fields_to_use]
def create_noise_contrast(df, num_samples):
"""
Create a noise contrasted dataframe from a dataframe. We do this
by sampling columns with replacement one at a time from the original
data, and then stitching those columns together into de-correlated rows.
Parameters
----------
df : dataframe
The enhanced HTTP log dataframe
num_samples : int
Number of new rows to create
Returns
-------
newDf : dataframe
"""
newDf = None
for field in list(df):
#sample the column with replacement.
df1 = df[[field]].sample(n=num_samples, replace=True).reset_index(drop=True)
#add the new column to the answer (or start a new df if this is the first column)
if (newDf is not None):
newDf = pd.concat([newDf, df1], axis = 1)
else:
newDf = df1
return newDf
| apache-2.0 |
Knightfang/The_Music_Man | run.py | 13 | 6247 | from __future__ import print_function
import os
import gc
import sys
import time
import traceback
import subprocess
class GIT(object):
@classmethod
def works(cls):
try:
return bool(subprocess.check_output('git --version', shell=True))
except:
return False
class PIP(object):
@classmethod
def run(cls, command, check_output=False):
if not cls.works():
raise RuntimeError("Could not import pip.")
try:
return PIP.run_python_m(*command.split(), check_output=check_output)
except subprocess.CalledProcessError as e:
return e.returncode
except:
traceback.print_exc()
print("Error using -m method")
@classmethod
def run_python_m(cls, *args, **kwargs):
check_output = kwargs.pop('check_output', False)
check = subprocess.check_output if check_output else subprocess.check_call
return check([sys.executable, '-m', 'pip'] + list(args))
@classmethod
def run_pip_main(cls, *args, **kwargs):
import pip
args = list(args)
check_output = kwargs.pop('check_output', False)
if check_output:
from io import StringIO
out = StringIO()
sys.stdout = out
try:
pip.main(args)
except:
traceback.print_exc()
finally:
sys.stdout = sys.__stdout__
out.seek(0)
pipdata = out.read()
out.close()
print(pipdata)
return pipdata
else:
return pip.main(args)
@classmethod
def run_install(cls, cmd, quiet=False, check_output=False):
return cls.run("install %s%s" % ('-q ' if quiet else '', cmd), check_output)
@classmethod
def run_show(cls, cmd, check_output=False):
return cls.run("show %s" % cmd, check_output)
@classmethod
def works(cls):
try:
import pip
return True
except ImportError:
return False
# noinspection PyTypeChecker
@classmethod
def get_module_version(cls, mod):
try:
out = cls.run_show(mod, check_output=True)
if isinstance(out, bytes):
out = out.decode()
datas = out.replace('\r\n', '\n').split('\n')
expectedversion = datas[3]
if expectedversion.startswith('Version: '):
return expectedversion.split()[1]
else:
return [x.split()[1] for x in datas if x.startswith("Version: ")][0]
except:
pass
def main():
if not sys.version_info >= (3, 5):
print("Python 3.5+ is required. This version is %s" % sys.version.split()[0])
print("Attempting to locate python 3.5...")
pycom = None
# Maybe I should check for if the current dir is the musicbot folder, just in case
if sys.platform.startswith('win'):
try:
subprocess.check_output('py -3.5 -c "exit()"', shell=True)
pycom = 'py -3.5'
except:
try:
subprocess.check_output('python3 -c "exit()"', shell=True)
pycom = 'python3'
except:
pass
if pycom:
print("Python 3 found. Launching bot...")
os.system('start cmd /k %s run.py' % pycom)
sys.exit(0)
else:
try:
pycom = subprocess.check_output(['which', 'python3.5']).strip().decode()
except:
pass
if pycom:
print("\nPython 3 found. Re-launching bot using: ")
print(" %s run.py\n" % pycom)
os.execlp(pycom, pycom, 'run.py')
print("Please run the bot using python 3.5")
input("Press enter to continue . . .")
return
import asyncio
tried_requirementstxt = False
tryagain = True
loops = 0
max_wait_time = 60
while tryagain:
# Maybe I need to try to import stuff first, then actually import stuff
# It'd save me a lot of pain with all that awful exception type checking
m = None
try:
from musicbot import MusicBot
m = MusicBot()
print("Connecting...", end='', flush=True)
m.run()
except SyntaxError:
traceback.print_exc()
break
except ImportError as e:
if not tried_requirementstxt:
tried_requirementstxt = True
# TODO: Better output
print(e)
print("Attempting to install dependencies...")
err = PIP.run_install('--upgrade -r requirements.txt')
if err:
print("\nYou may need to %s to install dependencies." %
['use sudo', 'run as admin'][sys.platform.startswith('win')])
break
else:
print("\nOk lets hope it worked\n")
else:
traceback.print_exc()
print("Unknown ImportError, exiting.")
break
except Exception as e:
if hasattr(e, '__module__') and e.__module__ == 'musicbot.exceptions':
if e.__class__.__name__ == 'HelpfulError':
print(e.message)
break
elif e.__class__.__name__ == "TerminateSignal":
break
elif e.__class__.__name__ == "RestartSignal":
loops = -1
else:
traceback.print_exc()
finally:
if not m or not m.init_ok:
break
asyncio.set_event_loop(asyncio.new_event_loop())
loops += 1
print("Cleaning up... ", end='')
gc.collect()
print("Done.")
sleeptime = min(loops * 2, max_wait_time)
if sleeptime:
print("Restarting in {} seconds...".format(loops*2))
time.sleep(sleeptime)
if __name__ == '__main__':
main()
| mit |
tst-ppenev/earthenterprise | earth_enterprise/src/fusion/portableglobe/cutter/cgi-bin/geecheck_tests/common.py | 1 | 5276 | #!/usr/bin/env python
#
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import glob
import os
import platform
import socket
LATEST_VERSION = '5.3.0'
SUPPORTED_OS_LIST = {
'redhat': {'min_release': '6.0',
'max_release': '7.4'},
'Ubuntu': {'min_release': '10.04',
'max_release': '16.04'},
'CentOS': {'min_release': '6.0',
'max_release': '7.4'}
}
BAD_HOSTNAMES = ['', 'linux', 'localhost', 'dhcp', 'bootp']
SERVICES = ['gesystemmanager',
'geresourceprovider',
'gehttpd',
'/opt/google/bin/postgres']
PROC_PATH = '/proc'
PROCESS_INFO_LIST = ['cmdline']
def GetHostInfo():
"""Get information about the host."""
hostname = GetFQDN()
if hostname in BAD_HOSTNAMES:
raise AssertionError('Hostname cannot be one of %s' % ','.join(BAD_HOSTNAMES))
ipaddr = GetIP(hostname)
host_check, host_aliases, _ = socket.gethostbyaddr(ipaddr)
return hostname, ipaddr, host_aliases + [host_check]
def IsFusionInstalled():
"""Check if Fusion is installed."""
fusion_start_script = '/etc/init.d/gefusion'
return os.path.exists(fusion_start_script)
def IsGeeServerInstalled():
"""Check if GEE Server is installed."""
gee_server_start_script = '/etc/init.d/gefusion'
return os.path.exists(gee_server_start_script)
def GetFusionVersion():
"""Get the version of Fusion."""
fusion_version_file_path = '/etc/opt/google/fusion_version'
try:
with open(fusion_version_file_path, 'r') as f:
version = f.readline().rstrip()
return version
except IOError:
raise AssertionError('Fusion version not available.')
return version
def GetGeeServerVersion():
"""Get the version of GEE Server."""
gee_server_version_file_path = '/etc/opt/google/fusion_server_version'
try:
with open(gee_server_version_file_path, 'r') as f:
version = f.readline().rstrip()
return version
except IOError:
raise AssertionError('GEE Server version not available.')
return version
def GetLatestVersion():
"""Get the Latest version."""
return LATEST_VERSION
def GetHostname():
return socket.gethostname()
def GetFQDN():
return socket.getfqdn()
def GetIP(hostname):
return socket.gethostbyname(hostname)
def GetLinuxDetails():
"""Get Linux distribution details."""
# eg. ('Ubuntu', '14.04', 'trusty')
# platform.linux_distribution() and platform.dist() were deprecated, they
# return 'debian' as the os, didn't find an elegant alternative and the
# functions use the files in /etc/ to do their magic.
#
# This has become further complicated by changes in how CentOS 7 uses the
# /etc files.
# This block works well for RHEL and CentOS.
try:
with open("/etc/redhat-release") as f:
line = f.read()
os = line.split()[0]
if os == "Red":
os = "redhat"
version = line.split(" release ")[1].split()[0]
return [os, version]
# Now try for Ubuntu.
except IOError:
try:
with open("/etc/lsb-release") as f:
line = f.read()
# Parse lines like "DISTRIB_ID=Ubuntu\n".
os = line.split()[0].split("=")[1]
version = line.split()[1].split("=")[1]
return [os, version]
# Final fail case.
except IOError:
raise AssertionError('Linux distribution details not available.')
def GetLinuxArchitecture():
"""Get Linux architecture."""
try:
return platform.architecture()[0]
except IOError:
raise AssertionError('Linux architecture not available.')
def GetOSDistro():
"""Get OS distribution."""
try:
return GetLinuxDetails()[0]
except IOError:
raise AssertionError('Linux OS distribution not available.')
def GetOSRelease():
"""Get OS release."""
try:
return GetLinuxDetails()[1]
except IOError:
raise AssertionError('Linux OS release not available.')
def GetOSPlatform():
"""Get OS platform."""
try:
return platform.system().lower()
except IOError:
raise AssertionError('Linux OS release not available.')
def GetProcessesDetails():
"""Get details about running processes."""
processes_details = {}
# Loop only through the first directory level
for process_folder in glob.glob('/proc/[0-9]*'):
process_id = os.path.basename(process_folder)
process_details = {}
for info in PROCESS_INFO_LIST:
process_details[info] = GetProcessDetails(process_id, info)
if process_details:
processes_details[process_id] = process_details
return processes_details
def GetProcessDetails(pid, info):
"""Get the process detail needed."""
path = os.path.join(PROC_PATH, pid, info)
if os.path.exists(path):
with open(path, 'r') as process_file:
return process_file.readline().replace('\x00', ' ')
return ''
| apache-2.0 |
jymannob/CouchPotatoServer | libs/suds/sudsobject.py | 201 | 11165 | # This program is free software; you can redistribute it and/or modify
# it under the terms of the (LGPL) GNU Lesser 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 Library Lesser General Public License for more details at
# ( http://www.gnu.org/licenses/lgpl.html ).
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
# written by: Jeff Ortel ( jortel@redhat.com )
"""
The I{sudsobject} module provides a collection of suds objects
that are primarily used for the highly dynamic interactions with
wsdl/xsd defined types.
"""
from logging import getLogger
from suds import *
from new import classobj
log = getLogger(__name__)
def items(sobject):
"""
Extract the I{items} from a suds object much like the
items() method works on I{dict}.
@param sobject: A suds object
@type sobject: L{Object}
@return: A list of items contained in I{sobject}.
@rtype: [(key, value),...]
"""
for item in sobject:
yield item
def asdict(sobject):
"""
Convert a sudsobject into a dictionary.
@param sobject: A suds object
@type sobject: L{Object}
@return: A python dictionary containing the
items contained in I{sobject}.
@rtype: dict
"""
return dict(items(sobject))
def merge(a, b):
"""
Merge all attributes and metadata from I{a} to I{b}.
@param a: A I{source} object
@type a: L{Object}
@param b: A I{destination} object
@type b: L{Object}
"""
for item in a:
setattr(b, item[0], item[1])
b.__metadata__ = b.__metadata__
return b
def footprint(sobject):
"""
Get the I{virtual footprint} of the object.
This is really a count of the attributes in the branch with a significant value.
@param sobject: A suds object.
@type sobject: L{Object}
@return: The branch footprint.
@rtype: int
"""
n = 0
for a in sobject.__keylist__:
v = getattr(sobject, a)
if v is None: continue
if isinstance(v, Object):
n += footprint(v)
continue
if hasattr(v, '__len__'):
if len(v): n += 1
continue
n +=1
return n
class Factory:
cache = {}
@classmethod
def subclass(cls, name, bases, dict={}):
if not isinstance(bases, tuple):
bases = (bases,)
name = name.encode('utf-8')
key = '.'.join((name, str(bases)))
subclass = cls.cache.get(key)
if subclass is None:
subclass = classobj(name, bases, dict)
cls.cache[key] = subclass
return subclass
@classmethod
def object(cls, classname=None, dict={}):
if classname is not None:
subclass = cls.subclass(classname, Object)
inst = subclass()
else:
inst = Object()
for a in dict.items():
setattr(inst, a[0], a[1])
return inst
@classmethod
def metadata(cls):
return Metadata()
@classmethod
def property(cls, name, value=None):
subclass = cls.subclass(name, Property)
return subclass(value)
class Object:
def __init__(self):
self.__keylist__ = []
self.__printer__ = Printer()
self.__metadata__ = Metadata()
def __setattr__(self, name, value):
builtin = name.startswith('__') and name.endswith('__')
if not builtin and \
name not in self.__keylist__:
self.__keylist__.append(name)
self.__dict__[name] = value
def __delattr__(self, name):
try:
del self.__dict__[name]
builtin = name.startswith('__') and name.endswith('__')
if not builtin:
self.__keylist__.remove(name)
except:
cls = self.__class__.__name__
raise AttributeError, "%s has no attribute '%s'" % (cls, name)
def __getitem__(self, name):
if isinstance(name, int):
name = self.__keylist__[int(name)]
return getattr(self, name)
def __setitem__(self, name, value):
setattr(self, name, value)
def __iter__(self):
return Iter(self)
def __len__(self):
return len(self.__keylist__)
def __contains__(self, name):
return name in self.__keylist__
def __repr__(self):
return str(self)
def __str__(self):
return unicode(self).encode('utf-8')
def __unicode__(self):
return self.__printer__.tostr(self)
class Iter:
def __init__(self, sobject):
self.sobject = sobject
self.keylist = self.__keylist(sobject)
self.index = 0
def next(self):
keylist = self.keylist
nkeys = len(self.keylist)
while self.index < nkeys:
k = keylist[self.index]
self.index += 1
if hasattr(self.sobject, k):
v = getattr(self.sobject, k)
return (k, v)
raise StopIteration()
def __keylist(self, sobject):
keylist = sobject.__keylist__
try:
keyset = set(keylist)
ordering = sobject.__metadata__.ordering
ordered = set(ordering)
if not ordered.issuperset(keyset):
log.debug(
'%s must be superset of %s, ordering ignored',
keylist,
ordering)
raise KeyError()
return ordering
except:
return keylist
def __iter__(self):
return self
class Metadata(Object):
def __init__(self):
self.__keylist__ = []
self.__printer__ = Printer()
class Facade(Object):
def __init__(self, name):
Object.__init__(self)
md = self.__metadata__
md.facade = name
class Property(Object):
def __init__(self, value):
Object.__init__(self)
self.value = value
def items(self):
for item in self:
if item[0] != 'value':
yield item
def get(self):
return self.value
def set(self, value):
self.value = value
return self
class Printer:
"""
Pretty printing of a Object object.
"""
@classmethod
def indent(cls, n): return '%*s'%(n*3,' ')
def tostr(self, object, indent=-2):
""" get s string representation of object """
history = []
return self.process(object, history, indent)
def process(self, object, h, n=0, nl=False):
""" print object using the specified indent (n) and newline (nl). """
if object is None:
return 'None'
if isinstance(object, Object):
if len(object) == 0:
return '<empty>'
else:
return self.print_object(object, h, n+2, nl)
if isinstance(object, dict):
if len(object) == 0:
return '<empty>'
else:
return self.print_dictionary(object, h, n+2, nl)
if isinstance(object, (list,tuple)):
if len(object) == 0:
return '<empty>'
else:
return self.print_collection(object, h, n+2)
if isinstance(object, basestring):
return '"%s"' % tostr(object)
return '%s' % tostr(object)
def print_object(self, d, h, n, nl=False):
""" print complex using the specified indent (n) and newline (nl). """
s = []
cls = d.__class__
md = d.__metadata__
if d in h:
s.append('(')
s.append(cls.__name__)
s.append(')')
s.append('...')
return ''.join(s)
h.append(d)
if nl:
s.append('\n')
s.append(self.indent(n))
if cls != Object:
s.append('(')
if isinstance(d, Facade):
s.append(md.facade)
else:
s.append(cls.__name__)
s.append(')')
s.append('{')
for item in d:
if self.exclude(d, item):
continue
item = self.unwrap(d, item)
s.append('\n')
s.append(self.indent(n+1))
if isinstance(item[1], (list,tuple)):
s.append(item[0])
s.append('[]')
else:
s.append(item[0])
s.append(' = ')
s.append(self.process(item[1], h, n, True))
s.append('\n')
s.append(self.indent(n))
s.append('}')
h.pop()
return ''.join(s)
def print_dictionary(self, d, h, n, nl=False):
""" print complex using the specified indent (n) and newline (nl). """
if d in h: return '{}...'
h.append(d)
s = []
if nl:
s.append('\n')
s.append(self.indent(n))
s.append('{')
for item in d.items():
s.append('\n')
s.append(self.indent(n+1))
if isinstance(item[1], (list,tuple)):
s.append(tostr(item[0]))
s.append('[]')
else:
s.append(tostr(item[0]))
s.append(' = ')
s.append(self.process(item[1], h, n, True))
s.append('\n')
s.append(self.indent(n))
s.append('}')
h.pop()
return ''.join(s)
def print_collection(self, c, h, n):
""" print collection using the specified indent (n) and newline (nl). """
if c in h: return '[]...'
h.append(c)
s = []
for item in c:
s.append('\n')
s.append(self.indent(n))
s.append(self.process(item, h, n-2))
s.append(',')
h.pop()
return ''.join(s)
def unwrap(self, d, item):
""" translate (unwrap) using an optional wrapper function """
nopt = ( lambda x: x )
try:
md = d.__metadata__
pmd = getattr(md, '__print__', None)
if pmd is None:
return item
wrappers = getattr(pmd, 'wrappers', {})
fn = wrappers.get(item[0], nopt)
return (item[0], fn(item[1]))
except:
pass
return item
def exclude(self, d, item):
""" check metadata for excluded items """
try:
md = d.__metadata__
pmd = getattr(md, '__print__', None)
if pmd is None:
return False
excludes = getattr(pmd, 'excludes', [])
return ( item[0] in excludes )
except:
pass
return False | gpl-3.0 |
marcuskelly/recover | Lib/site-packages/Crypto/SelfTest/Cipher/test_ARC4.py | 4 | 24728 | # -*- coding: utf-8 -*-
#
# SelfTest/Cipher/ARC4.py: Self-test for the Alleged-RC4 cipher
#
# Written in 2008 by Dwayne C. Litzenberger <dlitz@dlitz.net>
#
# ===================================================================
# The contents of this file are dedicated to the public domain. To
# the extent that dedication to the public domain is not available,
# everyone is granted a worldwide, perpetual, royalty-free,
# non-exclusive license to exercise all rights associated with the
# contents of this file for any purpose whatsoever.
# No rights are reserved.
#
# 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.
# ===================================================================
"""Self-test suite for Crypto.Cipher.ARC4"""
__revision__ = "$Id$"
from Crypto.Util.py3compat import *
from Crypto.SelfTest.st_common import *
from binascii import unhexlify
from Crypto.Cipher import ARC4
# This is a list of (plaintext, ciphertext, key[, description]) tuples.
test_data = [
# Test vectors from Eric Rescorla's message with the subject
# "RC4 compatibility testing", sent to the cipherpunks mailing list on
# September 13, 1994.
# http://cypherpunks.venona.com/date/1994/09/msg00420.html
('0123456789abcdef', '75b7878099e0c596', '0123456789abcdef',
'Test vector 0'),
('0000000000000000', '7494c2e7104b0879', '0123456789abcdef',
'Test vector 1'),
('0000000000000000', 'de188941a3375d3a', '0000000000000000',
'Test vector 2'),
#('00000000000000000000', 'd6a141a7ec3c38dfbd61', 'ef012345',
# 'Test vector 3'),
('01' * 512,
'7595c3e6114a09780c4ad452338e1ffd9a1be9498f813d76533449b6778dcad8'
+ 'c78a8d2ba9ac66085d0e53d59c26c2d1c490c1ebbe0ce66d1b6b1b13b6b919b8'
+ '47c25a91447a95e75e4ef16779cde8bf0a95850e32af9689444fd377108f98fd'
+ 'cbd4e726567500990bcc7e0ca3c4aaa304a387d20f3b8fbbcd42a1bd311d7a43'
+ '03dda5ab078896ae80c18b0af66dff319616eb784e495ad2ce90d7f772a81747'
+ 'b65f62093b1e0db9e5ba532fafec47508323e671327df9444432cb7367cec82f'
+ '5d44c0d00b67d650a075cd4b70dedd77eb9b10231b6b5b741347396d62897421'
+ 'd43df9b42e446e358e9c11a9b2184ecbef0cd8e7a877ef968f1390ec9b3d35a5'
+ '585cb009290e2fcde7b5ec66d9084be44055a619d9dd7fc3166f9487f7cb2729'
+ '12426445998514c15d53a18c864ce3a2b7555793988126520eacf2e3066e230c'
+ '91bee4dd5304f5fd0405b35bd99c73135d3d9bc335ee049ef69b3867bf2d7bd1'
+ 'eaa595d8bfc0066ff8d31509eb0c6caa006c807a623ef84c3d33c195d23ee320'
+ 'c40de0558157c822d4b8c569d849aed59d4e0fd7f379586b4b7ff684ed6a189f'
+ '7486d49b9c4bad9ba24b96abf924372c8a8fffb10d55354900a77a3db5f205e1'
+ 'b99fcd8660863a159ad4abe40fa48934163ddde542a6585540fd683cbfd8c00f'
+ '12129a284deacc4cdefe58be7137541c047126c8d49e2755ab181ab7e940b0c0',
'0123456789abcdef',
"Test vector 4"),
]
class RFC6229_Tests(unittest.TestCase):
# Test vectors from RFC 6229. Each test vector is a tuple with two items:
# the ARC4 key and a dictionary. The dictionary has keystream offsets as keys
# and the 16-byte keystream starting at the relevant offset as value.
rfc6229_data = [
# Page 3
(
'0102030405',
{
0: 'b2 39 63 05 f0 3d c0 27 cc c3 52 4a 0a 11 18 a8',
16: '69 82 94 4f 18 fc 82 d5 89 c4 03 a4 7a 0d 09 19',
240: '28 cb 11 32 c9 6c e2 86 42 1d ca ad b8 b6 9e ae',
256: '1c fc f6 2b 03 ed db 64 1d 77 df cf 7f 8d 8c 93',
496: '42 b7 d0 cd d9 18 a8 a3 3d d5 17 81 c8 1f 40 41',
512: '64 59 84 44 32 a7 da 92 3c fb 3e b4 98 06 61 f6',
752: 'ec 10 32 7b de 2b ee fd 18 f9 27 76 80 45 7e 22',
768: 'eb 62 63 8d 4f 0b a1 fe 9f ca 20 e0 5b f8 ff 2b',
1008:'45 12 90 48 e6 a0 ed 0b 56 b4 90 33 8f 07 8d a5',
1024:'30 ab bc c7 c2 0b 01 60 9f 23 ee 2d 5f 6b b7 df',
1520:'32 94 f7 44 d8 f9 79 05 07 e7 0f 62 e5 bb ce ea',
1536:'d8 72 9d b4 18 82 25 9b ee 4f 82 53 25 f5 a1 30',
2032:'1e b1 4a 0c 13 b3 bf 47 fa 2a 0b a9 3a d4 5b 8b',
2048:'cc 58 2f 8b a9 f2 65 e2 b1 be 91 12 e9 75 d2 d7',
3056:'f2 e3 0f 9b d1 02 ec bf 75 aa ad e9 bc 35 c4 3c',
3072:'ec 0e 11 c4 79 dc 32 9d c8 da 79 68 fe 96 56 81',
4080:'06 83 26 a2 11 84 16 d2 1f 9d 04 b2 cd 1c a0 50',
4096:'ff 25 b5 89 95 99 67 07 e5 1f bd f0 8b 34 d8 75'
}
),
# Page 4
(
'01020304050607',
{
0: '29 3f 02 d4 7f 37 c9 b6 33 f2 af 52 85 fe b4 6b',
16: 'e6 20 f1 39 0d 19 bd 84 e2 e0 fd 75 20 31 af c1',
240: '91 4f 02 53 1c 92 18 81 0d f6 0f 67 e3 38 15 4c',
256: 'd0 fd b5 83 07 3c e8 5a b8 39 17 74 0e c0 11 d5',
496: '75 f8 14 11 e8 71 cf fa 70 b9 0c 74 c5 92 e4 54',
512: '0b b8 72 02 93 8d ad 60 9e 87 a5 a1 b0 79 e5 e4',
752: 'c2 91 12 46 b6 12 e7 e7 b9 03 df ed a1 da d8 66',
768: '32 82 8f 91 50 2b 62 91 36 8d e8 08 1d e3 6f c2',
1008:'f3 b9 a7 e3 b2 97 bf 9a d8 04 51 2f 90 63 ef f1',
1024:'8e cb 67 a9 ba 1f 55 a5 a0 67 e2 b0 26 a3 67 6f',
1520:'d2 aa 90 2b d4 2d 0d 7c fd 34 0c d4 58 10 52 9f',
1536:'78 b2 72 c9 6e 42 ea b4 c6 0b d9 14 e3 9d 06 e3',
2032:'f4 33 2f d3 1a 07 93 96 ee 3c ee 3f 2a 4f f0 49',
2048:'05 45 97 81 d4 1f da 7f 30 c1 be 7e 12 46 c6 23',
3056:'ad fd 38 68 b8 e5 14 85 d5 e6 10 01 7e 3d d6 09',
3072:'ad 26 58 1c 0c 5b e4 5f 4c ea 01 db 2f 38 05 d5',
4080:'f3 17 2c ef fc 3b 3d 99 7c 85 cc d5 af 1a 95 0c',
4096:'e7 4b 0b 97 31 22 7f d3 7c 0e c0 8a 47 dd d8 b8'
}
),
(
'0102030405060708',
{
0: '97 ab 8a 1b f0 af b9 61 32 f2 f6 72 58 da 15 a8',
16: '82 63 ef db 45 c4 a1 86 84 ef 87 e6 b1 9e 5b 09',
240: '96 36 eb c9 84 19 26 f4 f7 d1 f3 62 bd df 6e 18',
256: 'd0 a9 90 ff 2c 05 fe f5 b9 03 73 c9 ff 4b 87 0a',
496: '73 23 9f 1d b7 f4 1d 80 b6 43 c0 c5 25 18 ec 63',
512: '16 3b 31 99 23 a6 bd b4 52 7c 62 61 26 70 3c 0f',
752: '49 d6 c8 af 0f 97 14 4a 87 df 21 d9 14 72 f9 66',
768: '44 17 3a 10 3b 66 16 c5 d5 ad 1c ee 40 c8 63 d0',
1008:'27 3c 9c 4b 27 f3 22 e4 e7 16 ef 53 a4 7d e7 a4',
1024:'c6 d0 e7 b2 26 25 9f a9 02 34 90 b2 61 67 ad 1d',
1520:'1f e8 98 67 13 f0 7c 3d 9a e1 c1 63 ff 8c f9 d3',
1536:'83 69 e1 a9 65 61 0b e8 87 fb d0 c7 91 62 aa fb',
2032:'0a 01 27 ab b4 44 84 b9 fb ef 5a bc ae 1b 57 9f',
2048:'c2 cd ad c6 40 2e 8e e8 66 e1 f3 7b db 47 e4 2c',
3056:'26 b5 1e a3 7d f8 e1 d6 f7 6f c3 b6 6a 74 29 b3',
3072:'bc 76 83 20 5d 4f 44 3d c1 f2 9d da 33 15 c8 7b',
4080:'d5 fa 5a 34 69 d2 9a aa f8 3d 23 58 9d b8 c8 5b',
4096:'3f b4 6e 2c 8f 0f 06 8e dc e8 cd cd 7d fc 58 62'
}
),
# Page 5
(
'0102030405060708090a',
{
0: 'ed e3 b0 46 43 e5 86 cc 90 7d c2 18 51 70 99 02',
16: '03 51 6b a7 8f 41 3b eb 22 3a a5 d4 d2 df 67 11',
240: '3c fd 6c b5 8e e0 fd de 64 01 76 ad 00 00 04 4d',
256: '48 53 2b 21 fb 60 79 c9 11 4c 0f fd 9c 04 a1 ad',
496: '3e 8c ea 98 01 71 09 97 90 84 b1 ef 92 f9 9d 86',
512: 'e2 0f b4 9b db 33 7e e4 8b 8d 8d c0 f4 af ef fe',
752: '5c 25 21 ea cd 79 66 f1 5e 05 65 44 be a0 d3 15',
768: 'e0 67 a7 03 19 31 a2 46 a6 c3 87 5d 2f 67 8a cb',
1008:'a6 4f 70 af 88 ae 56 b6 f8 75 81 c0 e2 3e 6b 08',
1024:'f4 49 03 1d e3 12 81 4e c6 f3 19 29 1f 4a 05 16',
1520:'bd ae 85 92 4b 3c b1 d0 a2 e3 3a 30 c6 d7 95 99',
1536:'8a 0f ed db ac 86 5a 09 bc d1 27 fb 56 2e d6 0a',
2032:'b5 5a 0a 5b 51 a1 2a 8b e3 48 99 c3 e0 47 51 1a',
2048:'d9 a0 9c ea 3c e7 5f e3 96 98 07 03 17 a7 13 39',
3056:'55 22 25 ed 11 77 f4 45 84 ac 8c fa 6c 4e b5 fc',
3072:'7e 82 cb ab fc 95 38 1b 08 09 98 44 21 29 c2 f8',
4080:'1f 13 5e d1 4c e6 0a 91 36 9d 23 22 be f2 5e 3c',
4096:'08 b6 be 45 12 4a 43 e2 eb 77 95 3f 84 dc 85 53'
}
),
(
'0102030405060708090a0b0c0d0e0f10',
{
0: '9a c7 cc 9a 60 9d 1e f7 b2 93 28 99 cd e4 1b 97',
16: '52 48 c4 95 90 14 12 6a 6e 8a 84 f1 1d 1a 9e 1c',
240: '06 59 02 e4 b6 20 f6 cc 36 c8 58 9f 66 43 2f 2b',
256: 'd3 9d 56 6b c6 bc e3 01 07 68 15 15 49 f3 87 3f',
496: 'b6 d1 e6 c4 a5 e4 77 1c ad 79 53 8d f2 95 fb 11',
512: 'c6 8c 1d 5c 55 9a 97 41 23 df 1d bc 52 a4 3b 89',
752: 'c5 ec f8 8d e8 97 fd 57 fe d3 01 70 1b 82 a2 59',
768: 'ec cb e1 3d e1 fc c9 1c 11 a0 b2 6c 0b c8 fa 4d',
1008:'e7 a7 25 74 f8 78 2a e2 6a ab cf 9e bc d6 60 65',
1024:'bd f0 32 4e 60 83 dc c6 d3 ce dd 3c a8 c5 3c 16',
1520:'b4 01 10 c4 19 0b 56 22 a9 61 16 b0 01 7e d2 97',
1536:'ff a0 b5 14 64 7e c0 4f 63 06 b8 92 ae 66 11 81',
2032:'d0 3d 1b c0 3c d3 3d 70 df f9 fa 5d 71 96 3e bd',
2048:'8a 44 12 64 11 ea a7 8b d5 1e 8d 87 a8 87 9b f5',
3056:'fa be b7 60 28 ad e2 d0 e4 87 22 e4 6c 46 15 a3',
3072:'c0 5d 88 ab d5 03 57 f9 35 a6 3c 59 ee 53 76 23',
4080:'ff 38 26 5c 16 42 c1 ab e8 d3 c2 fe 5e 57 2b f8',
4096:'a3 6a 4c 30 1a e8 ac 13 61 0c cb c1 22 56 ca cc'
}
),
# Page 6
(
'0102030405060708090a0b0c0d0e0f101112131415161718',
{
0: '05 95 e5 7f e5 f0 bb 3c 70 6e da c8 a4 b2 db 11',
16: 'df de 31 34 4a 1a f7 69 c7 4f 07 0a ee 9e 23 26',
240: 'b0 6b 9b 1e 19 5d 13 d8 f4 a7 99 5c 45 53 ac 05',
256: '6b d2 37 8e c3 41 c9 a4 2f 37 ba 79 f8 8a 32 ff',
496: 'e7 0b ce 1d f7 64 5a db 5d 2c 41 30 21 5c 35 22',
512: '9a 57 30 c7 fc b4 c9 af 51 ff da 89 c7 f1 ad 22',
752: '04 85 05 5f d4 f6 f0 d9 63 ef 5a b9 a5 47 69 82',
768: '59 1f c6 6b cd a1 0e 45 2b 03 d4 55 1f 6b 62 ac',
1008:'27 53 cc 83 98 8a fa 3e 16 88 a1 d3 b4 2c 9a 02',
1024:'93 61 0d 52 3d 1d 3f 00 62 b3 c2 a3 bb c7 c7 f0',
1520:'96 c2 48 61 0a ad ed fe af 89 78 c0 3d e8 20 5a',
1536:'0e 31 7b 3d 1c 73 b9 e9 a4 68 8f 29 6d 13 3a 19',
2032:'bd f0 e6 c3 cc a5 b5 b9 d5 33 b6 9c 56 ad a1 20',
2048:'88 a2 18 b6 e2 ec e1 e6 24 6d 44 c7 59 d1 9b 10',
3056:'68 66 39 7e 95 c1 40 53 4f 94 26 34 21 00 6e 40',
3072:'32 cb 0a 1e 95 42 c6 b3 b8 b3 98 ab c3 b0 f1 d5',
4080:'29 a0 b8 ae d5 4a 13 23 24 c6 2e 42 3f 54 b4 c8',
4096:'3c b0 f3 b5 02 0a 98 b8 2a f9 fe 15 44 84 a1 68'
}
),
(
'0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20',
{
0: 'ea a6 bd 25 88 0b f9 3d 3f 5d 1e 4c a2 61 1d 91',
16: 'cf a4 5c 9f 7e 71 4b 54 bd fa 80 02 7c b1 43 80',
240: '11 4a e3 44 de d7 1b 35 f2 e6 0f eb ad 72 7f d8',
256: '02 e1 e7 05 6b 0f 62 39 00 49 64 22 94 3e 97 b6',
496: '91 cb 93 c7 87 96 4e 10 d9 52 7d 99 9c 6f 93 6b',
512: '49 b1 8b 42 f8 e8 36 7c be b5 ef 10 4b a1 c7 cd',
752: '87 08 4b 3b a7 00 ba de 95 56 10 67 27 45 b3 74',
768: 'e7 a7 b9 e9 ec 54 0d 5f f4 3b db 12 79 2d 1b 35',
1008:'c7 99 b5 96 73 8f 6b 01 8c 76 c7 4b 17 59 bd 90',
1024:'7f ec 5b fd 9f 9b 89 ce 65 48 30 90 92 d7 e9 58',
1520:'40 f2 50 b2 6d 1f 09 6a 4a fd 4c 34 0a 58 88 15',
1536:'3e 34 13 5c 79 db 01 02 00 76 76 51 cf 26 30 73',
2032:'f6 56 ab cc f8 8d d8 27 02 7b 2c e9 17 d4 64 ec',
2048:'18 b6 25 03 bf bc 07 7f ba bb 98 f2 0d 98 ab 34',
3056:'8a ed 95 ee 5b 0d cb fb ef 4e b2 1d 3a 3f 52 f9',
3072:'62 5a 1a b0 0e e3 9a 53 27 34 6b dd b0 1a 9c 18',
4080:'a1 3a 7c 79 c7 e1 19 b5 ab 02 96 ab 28 c3 00 b9',
4096:'f3 e4 c0 a2 e0 2d 1d 01 f7 f0 a7 46 18 af 2b 48'
}
),
# Page 7
(
'833222772a',
{
0: '80 ad 97 bd c9 73 df 8a 2e 87 9e 92 a4 97 ef da',
16: '20 f0 60 c2 f2 e5 12 65 01 d3 d4 fe a1 0d 5f c0',
240: 'fa a1 48 e9 90 46 18 1f ec 6b 20 85 f3 b2 0e d9',
256: 'f0 da f5 ba b3 d5 96 83 98 57 84 6f 73 fb fe 5a',
496: '1c 7e 2f c4 63 92 32 fe 29 75 84 b2 96 99 6b c8',
512: '3d b9 b2 49 40 6c c8 ed ff ac 55 cc d3 22 ba 12',
752: 'e4 f9 f7 e0 06 61 54 bb d1 25 b7 45 56 9b c8 97',
768: '75 d5 ef 26 2b 44 c4 1a 9c f6 3a e1 45 68 e1 b9',
1008:'6d a4 53 db f8 1e 82 33 4a 3d 88 66 cb 50 a1 e3',
1024:'78 28 d0 74 11 9c ab 5c 22 b2 94 d7 a9 bf a0 bb',
1520:'ad b8 9c ea 9a 15 fb e6 17 29 5b d0 4b 8c a0 5c',
1536:'62 51 d8 7f d4 aa ae 9a 7e 4a d5 c2 17 d3 f3 00',
2032:'e7 11 9b d6 dd 9b 22 af e8 f8 95 85 43 28 81 e2',
2048:'78 5b 60 fd 7e c4 e9 fc b6 54 5f 35 0d 66 0f ab',
3056:'af ec c0 37 fd b7 b0 83 8e b3 d7 0b cd 26 83 82',
3072:'db c1 a7 b4 9d 57 35 8c c9 fa 6d 61 d7 3b 7c f0',
4080:'63 49 d1 26 a3 7a fc ba 89 79 4f 98 04 91 4f dc',
4096:'bf 42 c3 01 8c 2f 7c 66 bf de 52 49 75 76 81 15'
}
),
(
'1910833222772a',
{
0: 'bc 92 22 db d3 27 4d 8f c6 6d 14 cc bd a6 69 0b',
16: '7a e6 27 41 0c 9a 2b e6 93 df 5b b7 48 5a 63 e3',
240: '3f 09 31 aa 03 de fb 30 0f 06 01 03 82 6f 2a 64',
256: 'be aa 9e c8 d5 9b b6 81 29 f3 02 7c 96 36 11 81',
496: '74 e0 4d b4 6d 28 64 8d 7d ee 8a 00 64 b0 6c fe',
512: '9b 5e 81 c6 2f e0 23 c5 5b e4 2f 87 bb f9 32 b8',
752: 'ce 17 8f c1 82 6e fe cb c1 82 f5 79 99 a4 61 40',
768: '8b df 55 cd 55 06 1c 06 db a6 be 11 de 4a 57 8a',
1008:'62 6f 5f 4d ce 65 25 01 f3 08 7d 39 c9 2c c3 49',
1024:'42 da ac 6a 8f 9a b9 a7 fd 13 7c 60 37 82 56 82',
1520:'cc 03 fd b7 91 92 a2 07 31 2f 53 f5 d4 dc 33 d9',
1536:'f7 0f 14 12 2a 1c 98 a3 15 5d 28 b8 a0 a8 a4 1d',
2032:'2a 3a 30 7a b2 70 8a 9c 00 fe 0b 42 f9 c2 d6 a1',
2048:'86 26 17 62 7d 22 61 ea b0 b1 24 65 97 ca 0a e9',
3056:'55 f8 77 ce 4f 2e 1d db bf 8e 13 e2 cd e0 fd c8',
3072:'1b 15 56 cb 93 5f 17 33 37 70 5f bb 5d 50 1f c1',
4080:'ec d0 e9 66 02 be 7f 8d 50 92 81 6c cc f2 c2 e9',
4096:'02 78 81 fa b4 99 3a 1c 26 20 24 a9 4f ff 3f 61'
}
),
# Page 8
(
'641910833222772a',
{
0: 'bb f6 09 de 94 13 17 2d 07 66 0c b6 80 71 69 26',
16: '46 10 1a 6d ab 43 11 5d 6c 52 2b 4f e9 36 04 a9',
240: 'cb e1 ff f2 1c 96 f3 ee f6 1e 8f e0 54 2c bd f0',
256: '34 79 38 bf fa 40 09 c5 12 cf b4 03 4b 0d d1 a7',
496: '78 67 a7 86 d0 0a 71 47 90 4d 76 dd f1 e5 20 e3',
512: '8d 3e 9e 1c ae fc cc b3 fb f8 d1 8f 64 12 0b 32',
752: '94 23 37 f8 fd 76 f0 fa e8 c5 2d 79 54 81 06 72',
768: 'b8 54 8c 10 f5 16 67 f6 e6 0e 18 2f a1 9b 30 f7',
1008:'02 11 c7 c6 19 0c 9e fd 12 37 c3 4c 8f 2e 06 c4',
1024:'bd a6 4f 65 27 6d 2a ac b8 f9 02 12 20 3a 80 8e',
1520:'bd 38 20 f7 32 ff b5 3e c1 93 e7 9d 33 e2 7c 73',
1536:'d0 16 86 16 86 19 07 d4 82 e3 6c da c8 cf 57 49',
2032:'97 b0 f0 f2 24 b2 d2 31 71 14 80 8f b0 3a f7 a0',
2048:'e5 96 16 e4 69 78 79 39 a0 63 ce ea 9a f9 56 d1',
3056:'c4 7e 0d c1 66 09 19 c1 11 01 20 8f 9e 69 aa 1f',
3072:'5a e4 f1 28 96 b8 37 9a 2a ad 89 b5 b5 53 d6 b0',
4080:'6b 6b 09 8d 0c 29 3b c2 99 3d 80 bf 05 18 b6 d9',
4096:'81 70 cc 3c cd 92 a6 98 62 1b 93 9d d3 8f e7 b9'
}
),
(
'8b37641910833222772a',
{
0: 'ab 65 c2 6e dd b2 87 60 0d b2 fd a1 0d 1e 60 5c',
16: 'bb 75 90 10 c2 96 58 f2 c7 2d 93 a2 d1 6d 29 30',
240: 'b9 01 e8 03 6e d1 c3 83 cd 3c 4c 4d d0 a6 ab 05',
256: '3d 25 ce 49 22 92 4c 55 f0 64 94 33 53 d7 8a 6c',
496: '12 c1 aa 44 bb f8 7e 75 e6 11 f6 9b 2c 38 f4 9b',
512: '28 f2 b3 43 4b 65 c0 98 77 47 00 44 c6 ea 17 0d',
752: 'bd 9e f8 22 de 52 88 19 61 34 cf 8a f7 83 93 04',
768: '67 55 9c 23 f0 52 15 84 70 a2 96 f7 25 73 5a 32',
1008:'8b ab 26 fb c2 c1 2b 0f 13 e2 ab 18 5e ab f2 41',
1024:'31 18 5a 6d 69 6f 0c fa 9b 42 80 8b 38 e1 32 a2',
1520:'56 4d 3d ae 18 3c 52 34 c8 af 1e 51 06 1c 44 b5',
1536:'3c 07 78 a7 b5 f7 2d 3c 23 a3 13 5c 7d 67 b9 f4',
2032:'f3 43 69 89 0f cf 16 fb 51 7d ca ae 44 63 b2 dd',
2048:'02 f3 1c 81 e8 20 07 31 b8 99 b0 28 e7 91 bf a7',
3056:'72 da 64 62 83 22 8c 14 30 08 53 70 17 95 61 6f',
3072:'4e 0a 8c 6f 79 34 a7 88 e2 26 5e 81 d6 d0 c8 f4',
4080:'43 8d d5 ea fe a0 11 1b 6f 36 b4 b9 38 da 2a 68',
4096:'5f 6b fc 73 81 58 74 d9 71 00 f0 86 97 93 57 d8'
}
),
# Page 9
(
'ebb46227c6cc8b37641910833222772a',
{
0: '72 0c 94 b6 3e df 44 e1 31 d9 50 ca 21 1a 5a 30',
16: 'c3 66 fd ea cf 9c a8 04 36 be 7c 35 84 24 d2 0b',
240: 'b3 39 4a 40 aa bf 75 cb a4 22 82 ef 25 a0 05 9f',
256: '48 47 d8 1d a4 94 2d bc 24 9d ef c4 8c 92 2b 9f',
496: '08 12 8c 46 9f 27 53 42 ad da 20 2b 2b 58 da 95',
512: '97 0d ac ef 40 ad 98 72 3b ac 5d 69 55 b8 17 61',
752: '3c b8 99 93 b0 7b 0c ed 93 de 13 d2 a1 10 13 ac',
768: 'ef 2d 67 6f 15 45 c2 c1 3d c6 80 a0 2f 4a db fe',
1008:'b6 05 95 51 4f 24 bc 9f e5 22 a6 ca d7 39 36 44',
1024:'b5 15 a8 c5 01 17 54 f5 90 03 05 8b db 81 51 4e',
1520:'3c 70 04 7e 8c bc 03 8e 3b 98 20 db 60 1d a4 95',
1536:'11 75 da 6e e7 56 de 46 a5 3e 2b 07 56 60 b7 70',
2032:'00 a5 42 bb a0 21 11 cc 2c 65 b3 8e bd ba 58 7e',
2048:'58 65 fd bb 5b 48 06 41 04 e8 30 b3 80 f2 ae de',
3056:'34 b2 1a d2 ad 44 e9 99 db 2d 7f 08 63 f0 d9 b6',
3072:'84 a9 21 8f c3 6e 8a 5f 2c cf be ae 53 a2 7d 25',
4080:'a2 22 1a 11 b8 33 cc b4 98 a5 95 40 f0 54 5f 4a',
4096:'5b be b4 78 7d 59 e5 37 3f db ea 6c 6f 75 c2 9b'
}
),
(
'c109163908ebe51debb46227c6cc8b37641910833222772a',
{
0: '54 b6 4e 6b 5a 20 b5 e2 ec 84 59 3d c7 98 9d a7',
16: 'c1 35 ee e2 37 a8 54 65 ff 97 dc 03 92 4f 45 ce',
240: 'cf cc 92 2f b4 a1 4a b4 5d 61 75 aa bb f2 d2 01',
256: '83 7b 87 e2 a4 46 ad 0e f7 98 ac d0 2b 94 12 4f',
496: '17 a6 db d6 64 92 6a 06 36 b3 f4 c3 7a 4f 46 94',
512: '4a 5f 9f 26 ae ee d4 d4 a2 5f 63 2d 30 52 33 d9',
752: '80 a3 d0 1e f0 0c 8e 9a 42 09 c1 7f 4e eb 35 8c',
768: 'd1 5e 7d 5f fa aa bc 02 07 bf 20 0a 11 77 93 a2',
1008:'34 96 82 bf 58 8e aa 52 d0 aa 15 60 34 6a ea fa',
1024:'f5 85 4c db 76 c8 89 e3 ad 63 35 4e 5f 72 75 e3',
1520:'53 2c 7c ec cb 39 df 32 36 31 84 05 a4 b1 27 9c',
1536:'ba ef e6 d9 ce b6 51 84 22 60 e0 d1 e0 5e 3b 90',
2032:'e8 2d 8c 6d b5 4e 3c 63 3f 58 1c 95 2b a0 42 07',
2048:'4b 16 e5 0a bd 38 1b d7 09 00 a9 cd 9a 62 cb 23',
3056:'36 82 ee 33 bd 14 8b d9 f5 86 56 cd 8f 30 d9 fb',
3072:'1e 5a 0b 84 75 04 5d 9b 20 b2 62 86 24 ed fd 9e',
4080:'63 ed d6 84 fb 82 62 82 fe 52 8f 9c 0e 92 37 bc',
4096:'e4 dd 2e 98 d6 96 0f ae 0b 43 54 54 56 74 33 91'
}
),
# Page 10
(
'1ada31d5cf688221c109163908ebe51debb46227c6cc8b37641910833222772a',
{
0: 'dd 5b cb 00 18 e9 22 d4 94 75 9d 7c 39 5d 02 d3',
16: 'c8 44 6f 8f 77 ab f7 37 68 53 53 eb 89 a1 c9 eb',
240: 'af 3e 30 f9 c0 95 04 59 38 15 15 75 c3 fb 90 98',
256: 'f8 cb 62 74 db 99 b8 0b 1d 20 12 a9 8e d4 8f 0e',
496: '25 c3 00 5a 1c b8 5d e0 76 25 98 39 ab 71 98 ab',
512: '9d cb c1 83 e8 cb 99 4b 72 7b 75 be 31 80 76 9c',
752: 'a1 d3 07 8d fa 91 69 50 3e d9 d4 49 1d ee 4e b2',
768: '85 14 a5 49 58 58 09 6f 59 6e 4b cd 66 b1 06 65',
1008:'5f 40 d5 9e c1 b0 3b 33 73 8e fa 60 b2 25 5d 31',
1024:'34 77 c7 f7 64 a4 1b ac ef f9 0b f1 4f 92 b7 cc',
1520:'ac 4e 95 36 8d 99 b9 eb 78 b8 da 8f 81 ff a7 95',
1536:'8c 3c 13 f8 c2 38 8b b7 3f 38 57 6e 65 b7 c4 46',
2032:'13 c4 b9 c1 df b6 65 79 ed dd 8a 28 0b 9f 73 16',
2048:'dd d2 78 20 55 01 26 69 8e fa ad c6 4b 64 f6 6e',
3056:'f0 8f 2e 66 d2 8e d1 43 f3 a2 37 cf 9d e7 35 59',
3072:'9e a3 6c 52 55 31 b8 80 ba 12 43 34 f5 7b 0b 70',
4080:'d5 a3 9e 3d fc c5 02 80 ba c4 a6 b5 aa 0d ca 7d',
4096:'37 0b 1c 1f e6 55 91 6d 97 fd 0d 47 ca 1d 72 b8'
}
)
]
def test_keystream(self):
for tv in self.rfc6229_data:
key = unhexlify(b((tv[0])))
cipher = ARC4.new(key)
count = 0
for offset in range(0,4096+1,16):
ct = cipher.encrypt(b('\x00')*16)
expected = tv[1].get(offset)
if expected:
expected = unhexlify(b(expected.replace(" ",'')))
self.assertEqual(ct, expected)
count += 1
self.assertEqual(count, len(tv[1]))
class Drop_Tests(unittest.TestCase):
key = b('\xAA')*16
data = b('\x00')*5000
def setUp(self):
self.cipher = ARC4.new(self.key)
def test_drop256_encrypt(self):
cipher_drop = ARC4.new(self.key, 256)
ct_drop = cipher_drop.encrypt(self.data[:16])
ct = self.cipher.encrypt(self.data)[256:256+16]
self.assertEqual(ct_drop, ct)
def test_drop256_decrypt(self):
cipher_drop = ARC4.new(self.key, 256)
pt_drop = cipher_drop.decrypt(self.data[:16])
pt = self.cipher.decrypt(self.data)[256:256+16]
self.assertEqual(pt_drop, pt)
class KeyLength(unittest.TestCase):
def runTest(self):
self.assertRaises(ValueError, ARC4.new, bchr(0) * 4)
self.assertRaises(ValueError, ARC4.new, bchr(0) * 257)
def get_tests(config={}):
from .common import make_stream_tests
tests = make_stream_tests(ARC4, "ARC4", test_data)
tests += list_test_cases(RFC6229_Tests)
tests += list_test_cases(Drop_Tests)
tests.append(KeyLength())
return tests
if __name__ == '__main__':
import unittest
suite = lambda: unittest.TestSuite(get_tests())
unittest.main(defaultTest='suite')
# vim:set ts=4 sw=4 sts=4 expandtab:
| bsd-2-clause |
GeoMop/GeoMop | testing/Analysis/pipeline/test_workflow_actions.py | 1 | 5903 | from Analysis.pipeline.parametrized_actions import *
from Analysis.pipeline.generator_actions import *
from Analysis.pipeline.wrapper_actions import *
from Analysis.pipeline.data_types_tree import *
from Analysis.pipeline.workflow_actions import *
from Analysis.pipeline.pipeline import *
from .pomfce import *
import Analysis.pipeline.action_types as action
import os
this_source_dir = os.path.dirname(os.path.realpath(__file__))
def test_workflow_code_init(request, change_dir_back):
def clear_backup():
pass
request.addfinalizer(clear_backup)
os.chdir(this_source_dir)
# test workflow with more action
action.__action_counter__ = 0
vg = VariableGenerator(Variable=Struct(a=String("test"), b=Int(3)))
workflow = Workflow(Inputs=[vg])
f1 = Flow123dAction(Inputs=[workflow.input()], YAMLFile="resources/test1.yaml")
f2 = Flow123dAction(Inputs=[f1], YAMLFile="resources/test2.yaml")
workflow.set_config(OutputAction=f2, InputAction=f1)
workflow._inicialize()
vg._inicialize()
f1._output = Struct()
test = workflow._get_settings_script()
compare_with_file(os.path.join("results", "workflow3.py"), test)
# test validation
err = workflow.validate()
assert len(err) == 0
# test _get_hashes_list()
hlist = workflow._get_hashes_list()
assert sorted(hlist.keys()) == ["2", "3", "4"]
# test workflow with more action where is side effect action in separate branch
action.__action_counter__ = 0
vg = VariableGenerator(Variable=Struct(a=String("test"), b=Int(3)))
vg2 = VariableGenerator(Variable=Struct(a=String("test2"), b=Int(5)))
workflow = Workflow(Inputs=[vg2])
flow = Flow123dAction(Inputs=[workflow.input()], YAMLFile="resources/test1.yaml")
side = Flow123dAction(Inputs=[vg], YAMLFile="resources/test2.yaml")
workflow.set_config(OutputAction=flow, InputAction=flow, ResultActions=[side])
flow._output = String()
workflow._inicialize()
vg2._inicialize()
test = workflow._get_settings_script()
compare_with_file(os.path.join("results", "workflow4.py"), test)
# test validation
err = workflow.validate()
assert len(err) == 0
# test _get_hashes_list()
hlist = workflow._get_hashes_list()
assert sorted(hlist.keys()) == ["1", "3", "4", "5"]
# test workflow duplication
action.__action_counter__ = 0
workflow = Workflow()
flow = Flow123dAction(Inputs=[workflow.input()], YAMLFile="resources/test1.yaml")
workflow.set_config(OutputAction=flow, InputAction=flow)
vg = VariableGenerator(Variable=Struct(a=String("test"), b=Int(3)))
w1 = workflow.duplicate()
w1.set_inputs([vg])
w2 = workflow.duplicate()
w2.set_inputs([w1])
pipeline = Pipeline(ResultActions=[w2])
pipeline._inicialize()
test = pipeline._get_settings_script()
compare_with_file(os.path.join("results", "workflow5.py"), test)
# test validation
err = pipeline.validate()
assert len(err) == 0
# test _get_hashes_list()
hlist = pipeline._get_hashes_list()
assert sorted(hlist.keys()) == ["3", "4", "5", "6", "7", "8"]
# test workflow v 2xForEach in each other
action.__action_counter__ = 0
items = [
{'name':'a', 'value':1, 'step':0.1, 'n_plus':1, 'n_minus':1,'exponential':False},
{'name':'b', 'value':10, 'step':1, 'n_plus':2, 'n_minus':0,'exponential':True}
]
items2 = [
{'name': 'x', 'value': 1, 'step': 0.1, 'n_plus': 1, 'n_minus': 1, 'exponential': False},
{'name': 'y', 'value': 10, 'step': 1, 'n_plus': 2, 'n_minus': 0, 'exponential': True}
]
gen = RangeGenerator(Items=items)
gen2 = RangeGenerator(Items=items2)
workflow = Workflow()
workflow2 = Workflow()
flow = Flow123dAction(Inputs=[workflow2.input()], YAMLFile="resources/test1.yaml")
workflow2.set_config(OutputAction=flow, InputAction=flow)
foreach2 = ForEach(Inputs=[gen2], WrappedAction=workflow2)
workflow.set_config(OutputAction=foreach2, InputAction=foreach2)
foreach = ForEach(Inputs=[gen], WrappedAction=workflow)
pipeline = Pipeline(ResultActions=[foreach])
flow._output = String()
pipeline._inicialize()
test = pipeline._get_settings_script()
compare_with_file(os.path.join("results", "workflow6.py"), test)
# test validation
err = pipeline.validate()
assert len(err) == 0
# test _get_hashes_list()
hlist = pipeline._get_hashes_list()
assert sorted(hlist.keys()) == ["1", "2", "3", "4", "5", "6", "7", "8"]
# test workflow with one direct input
action.__action_counter__ = 0
vg = VariableGenerator(Variable=Struct(a=String("test"), b=Int(3)))
workflow = Workflow(Inputs=[vg])
flow = Flow123dAction(Inputs=[workflow.input()], YAMLFile="resources/test1.yaml")
workflow.set_config(OutputAction=flow, InputAction=flow)
workflow._inicialize()
vg._inicialize()
test = workflow._get_settings_script()
compare_with_file(os.path.join("results", "workflow7.py"), test)
# test validation
err = workflow.validate()
assert len(err) == 0
# test _get_hashes_list()
hlist = workflow._get_hashes_list()
assert sorted(hlist.keys()) == ["2", "3"]
# test comparation of workflow hash
action.__action_counter__ = 0
workflow = Workflow()
f1 = Flow123dAction(Inputs=[workflow.input()], YAMLFile="resources/test1.yaml")
f2 = Flow123dAction(Inputs=[f1], YAMLFile="resources/test2.yaml")
workflow.set_config(OutputAction=f2, InputAction=f1)
workflow._inicialize()
workflow2 = Workflow()
f12 = Flow123dAction(Inputs=[workflow2.input()], YAMLFile="resources/test1.yaml")
f22 = Flow123dAction(Inputs=[f12], YAMLFile="resources/test2.yaml")
workflow2.set_config(OutputAction=f22, InputAction=f12)
workflow2._inicialize()
assert workflow._get_hash() == workflow2._get_hash()
| gpl-3.0 |
ceph/Diamond | src/diamond/test/testmetric.py | 5 | 2914 | #!/usr/bin/python
# coding=utf-8
################################################################################
from test import unittest
from diamond.metric import Metric
class TestMetric(unittest.TestCase):
def testgetPathPrefix(self):
metric = Metric('servers.com.example.www.cpu.total.idle',
0,
host='com.example.www')
actual_value = metric.getPathPrefix()
expected_value = 'servers'
message = 'Actual %s, expected %s' % (actual_value, expected_value)
self.assertEqual(actual_value, expected_value, message)
def testgetPathPrefixCustom(self):
metric = Metric('custom.path.prefix.com.example.www.cpu.total.idle',
0,
host='com.example.www')
actual_value = metric.getPathPrefix()
expected_value = 'custom.path.prefix'
message = 'Actual %s, expected %s' % (actual_value, expected_value)
self.assertEqual(actual_value, expected_value, message)
def testgetCollectorPath(self):
metric = Metric('servers.com.example.www.cpu.total.idle',
0,
host='com.example.www')
actual_value = metric.getCollectorPath()
expected_value = 'cpu'
message = 'Actual %s, expected %s' % (actual_value, expected_value)
self.assertEqual(actual_value, expected_value, message)
def testgetMetricPath(self):
metric = Metric('servers.com.example.www.cpu.total.idle',
0,
host='com.example.www')
actual_value = metric.getMetricPath()
expected_value = 'total.idle'
message = 'Actual %s, expected %s' % (actual_value, expected_value)
self.assertEqual(actual_value, expected_value, message)
# Test hostname of none
def testgetPathPrefixHostNone(self):
metric = Metric('servers.host.cpu.total.idle',
0)
actual_value = metric.getPathPrefix()
expected_value = 'servers'
message = 'Actual %s, expected %s' % (actual_value, expected_value)
self.assertEqual(actual_value, expected_value, message)
def testgetCollectorPathHostNone(self):
metric = Metric('servers.host.cpu.total.idle',
0)
actual_value = metric.getCollectorPath()
expected_value = 'cpu'
message = 'Actual %s, expected %s' % (actual_value, expected_value)
self.assertEqual(actual_value, expected_value, message)
def testgetMetricPathHostNone(self):
metric = Metric('servers.host.cpu.total.idle',
0)
actual_value = metric.getMetricPath()
expected_value = 'total.idle'
message = 'Actual %s, expected %s' % (actual_value, expected_value)
self.assertEqual(actual_value, expected_value, message)
| mit |
flar2/m7wl-ElementalX | Documentation/networking/cxacru-cf.py | 14668 | 1626 | #!/usr/bin/env python
# Copyright 2009 Simon Arlott
#
# 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., 59
# Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
# Usage: cxacru-cf.py < cxacru-cf.bin
# Output: values string suitable for the sysfs adsl_config attribute
#
# Warning: cxacru-cf.bin with MD5 hash cdbac2689969d5ed5d4850f117702110
# contains mis-aligned values which will stop the modem from being able
# to make a connection. If the first and last two bytes are removed then
# the values become valid, but the modulation will be forced to ANSI
# T1.413 only which may not be appropriate.
#
# The original binary format is a packed list of le32 values.
import sys
import struct
i = 0
while True:
buf = sys.stdin.read(4)
if len(buf) == 0:
break
elif len(buf) != 4:
sys.stdout.write("\n")
sys.stderr.write("Error: read {0} not 4 bytes\n".format(len(buf)))
sys.exit(1)
if i > 0:
sys.stdout.write(" ")
sys.stdout.write("{0:x}={1}".format(i, struct.unpack("<I", buf)[0]))
i += 1
sys.stdout.write("\n")
| gpl-2.0 |
s0lst1ce/twisted-intro | blocking-client/get-poetry.py | 11 | 2489 | # This is the blocking Get Poetry Now! client.
import datetime, optparse, socket
def parse_args():
usage = """usage: %prog [options] [hostname]:port ...
This is the Get Poetry Now! client, blocking edition.
Run it like this:
python get-poetry.py port1 port2 port3 ...
If you are in the base directory of the twisted-intro package,
you could run it like this:
python blocking-client/get-poetry.py 10001 10002 10003
to grab poetry from servers on ports 10001, 10002, and 10003.
Of course, there need to be servers listening on those ports
for that to work.
"""
parser = optparse.OptionParser(usage)
_, addresses = parser.parse_args()
if not addresses:
print parser.format_help()
parser.exit()
def parse_address(addr):
if ':' not in addr:
host = '127.0.0.1'
port = addr
else:
host, port = addr.split(':', 1)
if not port.isdigit():
parser.error('Ports must be integers.')
return host, int(port)
return map(parse_address, addresses)
def get_poetry(address):
"""Download a piece of poetry from the given address."""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(address)
poem = ''
while True:
# This is the 'blocking' call in this synchronous program.
# The recv() method will block for an indeterminate period
# of time waiting for bytes to be received from the server.
data = sock.recv(1024)
if not data:
sock.close()
break
poem += data
return poem
def format_address(address):
host, port = address
return '%s:%s' % (host or '127.0.0.1', port)
def main():
addresses = parse_args()
elapsed = datetime.timedelta()
for i, address in enumerate(addresses):
addr_fmt = format_address(address)
print 'Task %d: get poetry from: %s' % (i + 1, addr_fmt)
start = datetime.datetime.now()
# Each execution of 'get_poetry' corresponds to the
# execution of one synchronous task in Figure 1 here:
# http://krondo.com/?p=1209#figure1
poem = get_poetry(address)
time = datetime.datetime.now() - start
msg = 'Task %d: got %d bytes of poetry from %s in %s'
print msg % (i + 1, len(poem), addr_fmt, time)
elapsed += time
print 'Got %d poems in %s' % (len(addresses), elapsed)
if __name__ == '__main__':
main()
| mit |
celiafish/VisTrails | vistrails/packages/vtk/vtk_parser.py | 2 | 20795 | ###############################################################################
##
## Copyright (C) 2011-2014, NYU-Poly.
## Copyright (C) 2006-2011, University of Utah.
## All rights reserved.
## Contact: contact@vistrails.org
##
## This file is part of VisTrails.
##
## "Redistribution and use in source and binary forms, with or without
## modification, are permitted provided that the following conditions are met:
##
## - Redistributions of source code must retain the above copyright notice,
## this list of conditions and the following disclaimer.
## - Redistributions in binary form must reproduce the above copyright
## notice, this list of conditions and the following disclaimer in the
## documentation and/or other materials provided with the distribution.
## - Neither the name of the University of Utah 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 HOLDER 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."
##
###############################################################################
# Author: Prabhu Ramachandran
# Copyright (c) 2004, Enthought, Inc.
# License: BSD Style.
# Modified for VisTrails by the VisTrails team.
"""This module parses the VTK methods, obtains the argument and return
type information, and organizes them.
"""
from ast import literal_eval
import re
import vtk
import class_tree
import vistrails.core.debug
log = vistrails.core.debug.log
warning = vistrails.core.debug.warning
critical = vistrails.core.debug.critical
debug = vistrails.core.debug.debug
class VTKMethodParser(object):
"""This class provides useful methods for parsing methods of a VTK
class or instance.
The class allows one to categorize the methods of the VTK class
and also obtain the method signatures in a form that is easy to
use. When the `parse` method is called, it in turn calls the
`_organize_methods` method. This method organizes the VTK methods
into different instance variables described in the following.
`self.toggle_meths` contains a dictionary of all the boolean
methods of the form <Value>On/Off. The dictionary keys are
strings with the <Value>'s and the value of each item is the
default value (0/1) of the item (the example below will clarify
this). `self.state_meths` contains a dictionary which collects
the Set<Prop>To<Value> type of methods. The key is the <Prop> and
the value is a list containing the different string <Value>'s and
their corresponding mapped value. The first value in these is the
default value of the <Prop>. `self.get_set_meths` will contain a
dictionary which collects all the methods of the form
Set/Get<Prop> that are not already specified in
`self.toggle_meths` or `self.state_meths`. The default value of
the Get<Prop> is stored. If the value accepted by the method has
a range (via the methods `Get<Prop>MinValue` and
`Get<Prop>MaxValue`), then that range is computed and stored.
`self.get_meths` stores the methods that are of the form
`Get<Prop>`. `self.other_meths` stores the remaining methods.
The parsing is quite fast. Parsing every class in the VTK API
takes a couple of seconds (on a Pentium III @ 450Mhz).
Here is an example::
>>> import vtk
>>> p = VTKMethodParser()
>>> p.parse(vtk.vtkProperty)
>>> print p.get_toggle_methods()
{'EdgeVisibility': 0, 'BackfaceCulling': 0, 'FrontfaceCulling': 0}
>>> print p.get_state_methods()['Representation']
[['Surface', 2], ['Points', 0], ['Surface', 2], ['Wireframe', 1]]
>>> print p.get_get_set_methods()['Opacity']
(1.0, (0.0, 1.0))
>>> print p.get_get_methods()
['GetClassName']
>>> print p.get_other_methods()[:3]
['BackfaceRender', 'DeepCopy', 'IsA']
The class also provides a method called `get_method_signature`
that obtains the Python method signature given the VTK method
object. Here is an example::
>>> import vtk
>>> p = VTKMethodParser()
>>> o = vtk.vtkProperty
>>> print p.get_method_signature(o.GetClassName)
[(['string'], None)]
>>> print p.get_method_signature(o.GetColor)[0]
([('float', 'float', 'float')], None)
>>> print p.get_method_signature(o.GetColor)[1]
([None], (('float', 'float', 'float'),))
The `get_method_signature` is fairly efficient and obtaining the
signature for every method in every class in the VTK API takes
around 6 seconds (on a Pentium III @ 450Mhz).
"""
def __init__(self, use_tree=True):
"""Initializes the object.
Parameters
----------
- use_tree : `bool`
If True (default), use a ClassTree instance to obtain a
concrete subclass for an abstract base class. This is used
only to find the range and default values for some of the
methods. If False, no ClassTree instance is created.
This is optional because, creating a ClassTree is expensive.
The parser functionality can be very useful even without the
use of a ClassTree. For example, if one wants to save the
state of a VTK object one only needs to know the names of
the methods and not their default values, ranges etc. In
that case using a parser should be cheap.
"""
# The ClassTree is needed to find an instantiable child class
# for an abstract VTK parent class. This instance is used to
# obtain the state values and the ranges of the arguments
# accepted by the Get/Set methods that have a
# Get<Prop>{MaxValue,MinValue} method.
if use_tree:
self._tree = class_tree.ClassTree(vtk)
self._tree.create()
else:
self._tree = None
self._state_patn = re.compile('To[A-Z0-9]')
self._initialize()
#################################################################
# 'VTKMethodParser' interface.
#################################################################
def parse(self, obj, no_warn=True):
"""Parse the methods for a given VTK object/class.
Given a VTK class or object, this method parses the methods
and orgaizes them into useful categories. The categories and
their usage is documented in the documentation for the class.
Parameters
----------
- obj : VTK class or instance
- no_warn : `bool` (default: True)
If True (default), it suppresses any warnings generated by
the VTK object when parsing the methods. This is safe to
use.
"""
if not hasattr(obj, '__bases__'):
klass = obj.__class__
else:
klass = obj
methods = self.get_methods(klass)
if no_warn:
# Save warning setting and shut it off before parsing.
warn = vtk.vtkObject.GetGlobalWarningDisplay()
if klass.__name__ <> 'vtkObject':
vtk.vtkObject.GlobalWarningDisplayOff()
self._organize_methods(klass, methods)
if no_warn:
# Reset warning status.
vtk.vtkObject.SetGlobalWarningDisplay(warn)
def get_methods(self, klass):
"""Returns all the relevant methods of the given VTK class."""
methods = dir(klass)[:]
if hasattr(klass, '__members__'):
# Only VTK versions < 4.5 have these.
for m in klass.__members__:
methods.remove(m)
return methods
def get_toggle_methods(self):
"""Returns a dictionary of the parsed <Value>On/Off methods
along with the default value.
"""
return self.toggle_meths
def get_state_methods(self):
"""Returns a dict of the parsed Set<Prop>To<Value>.
The keys are the <Prop> string with a list of the different
<Value> strings along with their corresponding value (if
obtainable). The first value is the default value of the
state.
"""
return self.state_meths
def get_get_set_methods(self):
"""Returns a dict of the parsed Get/Set<Value> methods.
The keys of the dict are the <Value> strings and contain a
two-tuple containing the default value (or None if it is not
obtainable for some reason) and a pair of numbers specifying
an acceptable range of values (or None if not obtainable).
"""
return self.get_set_meths
def get_get_methods(self):
"""Return a list of parsed Get<Value> methods.
All of these methods do NOT have a corresponding Set<Value>.
"""
return self.get_meths
def get_other_methods(self):
"""Return list of all other methods, that are not
categorizable.
"""
return self.other_meths
def get_method_signature(self, method):
"""Returns information on the Python method signature given
the VTK method.
The doc string of the given method object to get the method
signature. The method returns a list of tuples, each of which
contains 2 items, the first is a list representing the return
value the second represents the arguments to be passed to the
function. If the method supports different return values and
arguments, this function returns all of their signatures.
Parameters
----------
- method : `method`
A VTK method object.
"""
doc = method.__doc__
doc = doc[:doc.find('\n\n')]
sig = doc.split('\n')
sig = [x.strip() for x in sig]
# Remove all the C++ function signatures.
for i in sig[:]:
if i[:4] == 'C++:':
sig.remove(i)
# Remove the V.<method_name>
sig = [x.replace('V.' + method.__name__, '') for x in sig]
pat = re.compile(r'\b')
# Split into [return_value, arguments] after processing them.
tmp = list(sig)
sig = []
for i in tmp:
# Split to get return values.
x = i.split('->')
# Strip each part.
x = [y.strip() for y in x]
if len(x) == 1: # No return value
x = [None, x[0]]
else:
x.reverse()
ret, arg = x
# Remove leading and trailing parens for arguments.
arg = arg[1:-1]
if not arg:
arg = None
if arg and arg[-1] == ')':
arg = arg + ','
# Now quote the args and eval them. Easy!
if ret:
ret = literal_eval(pat.sub('\"', ret))
if arg:
arg = literal_eval(pat.sub('\"', arg))
if isinstance(arg, basestring):
arg = [arg]
sig.append(([ret], arg))
return sig
def get_tree(self):
"""Return the ClassTree instance used by this class."""
return self._tree
#################################################################
# Non-public interface.
#################################################################
def _initialize(self):
"""Initializes the method categories."""
# Collects the <Value>On/Off methods.
self.toggle_meths = {}
# Collects the Set<Prop>To<Value> methods.
self.state_meths = {}
# Collects the Set/Get<Value> pairs.
self.get_set_meths = {}
# Collects the Get<Value> methods.
self.get_meths = []
# Collects all the remaining methods.
self.other_meths = []
def _organize_methods(self, klass, methods):
"""Organizes the given methods of a VTK class into different
categories.
Parameters
----------
- klass : A VTK class
- methods : `list` of `str`
A list of the methods to be categorized.
"""
self._initialize()
meths = methods[:]
meths = self._find_toggle_methods(klass, meths)
meths = self._find_state_methods(klass, meths)
meths = self._find_get_set_methods(klass, meths)
meths = self._find_get_methods(klass, meths)
self.other_meths = [x for x in meths if '__' not in x]
def _remove_method(self, meths, method):
try:
meths.remove(method)
except ValueError:
pass
def _find_toggle_methods(self, klass, methods):
"""Find/store methods of the form <Value>{On,Off} in the given
`methods`. Returns the remaining list of methods.
"""
meths = methods[:]
tm = self.toggle_meths
for method in meths[:]:
if method[-2:] == 'On':
key = method[:-2]
if (key + 'Off') in meths and ('Get' + key) in meths:
tm[key] = None
meths.remove(method)
meths.remove(key + 'Off')
self._remove_method(meths, 'Set' + key)
self._remove_method(meths, 'Get' + key)
# get defaults
if tm:
obj = self._get_instance(klass)
if obj:
for key in tm:
try:
tm[key] = getattr(obj, 'Get%s'%key)()
except TypeError, e:
log("Type error during parsing: class %s will not expose method %s " % (klass.__name__, key))
except AttributeError, e:
log("Attribute error during parsing: class %s will not expose method %s " % (klass.__name__, key))
return meths
def _find_state_methods(self, klass, methods):
"""Find/store methods of the form Set<Prop>To<Value> in the
given `methods`. Returns the remaining list of methods. The
method also computes the mapped value of the different
<Values>.
"""
# These ignored ones are really not state methods.
ignore = ['SetUpdateExtentToWholeExtent']
meths = methods[:]
sm = self.state_meths
for method in meths[:]:
if method not in ignore and method[:3] == 'Set':
# Methods of form Set<Prop>To<Value>
match = self._state_patn.search(method)
# Second cond. ensures that this is not an accident.
if match and (('Get'+method[3:]) not in meths):
key = method[3:match.start()] # The <Prop> part.
if (('Get' + key) in methods):
val = method[match.start()+2:] # <Value> part.
meths.remove(method)
if sm.has_key(key):
sm[key].append([val, None])
else:
sm[key] = [[val, None]]
meths.remove('Get'+ key)
self._remove_method(meths, 'Set'+ key)
if ('Get' + key + 'MaxValue') in meths:
meths.remove('Get' + key + 'MaxValue')
meths.remove('Get' + key + 'MinValue')
try:
meths.remove('Get' + key + 'AsString')
except ValueError:
pass
# Find the values for each of the states, i.e. find that
# vtkProperty.SetRepresentationToWireframe() corresponds to
# vtkProperty.SetRepresentation(1).
if sm:
obj = self._get_instance(klass)
if obj:
for key, values in sm.items():
default = getattr(obj, 'Get%s'%key)()
for x in values[:]:
try:
getattr(obj, 'Set%sTo%s'%(key, x[0]))()
except Exception:
continue
val = getattr(obj, 'Get%s'%key)()
x[1] = val
if val == default:
values.insert(0, [x[0], val])
return meths
def _find_get_set_methods(self, klass, methods):
"""Find/store methods of the form {Get,Set}Prop in the given
`methods` and returns the remaining list of methods.
Note that it makes sense to call this *after*
`_find_state_methods` is called in order to avoid incorrect
duplication. This method also computes the default value and
the ranges of the arguments (when possible) by using the
Get<Prop>{MaxValue,MinValue} methods.
"""
meths = methods[:]
gsm = self.get_set_meths
for method in meths[:]:
# Methods of the Set/Get form.
if method in ['Get', 'Set']:
# This occurs with the vtkInformation class.
continue
elif (method[:3] == 'Set') and ('Get' + method[3:]) in methods:
key = method[3:]
meths.remove('Set' + key)
meths.remove('Get' + key)
if ('Get' + key + 'MaxValue') in meths:
meths.remove('Get' + key + 'MaxValue')
meths.remove('Get' + key + 'MinValue')
gsm[key] = 1
else:
gsm[key] = None
# Find the default and range of the values.
if gsm:
obj = self._get_instance(klass)
if obj:
klass_name = klass.__name__
for key, value in gsm.items():
if klass_name == 'vtkPolyData':
# Evil hack, this class segfaults!
default = None
else:
try:
default = getattr(obj, 'Get%s'%key)()
except TypeError:
default = None
if value:
low = getattr(obj, 'Get%sMinValue'%key)()
high = getattr(obj, 'Get%sMaxValue'%key)()
gsm[key] = (default, (low, high))
else:
gsm[key] = (default, None)
else:
# We still might have methods that have a default range.
for key, value in gsm.items():
if value == 1:
gsm[key] = None
return meths
def _find_get_methods(self, klass, methods):
"""Find/store methods of the form Get<Value> in the given
`methods` and returns the remaining list of methods.
"""
meths = methods[:]
gm = self.get_meths
for method in meths[:]:
if method == 'Get':
# Occurs with vtkInformation
continue
elif method[:3] == 'Get':
gm.append(method)
meths.remove(method)
return meths
def _get_instance(self, klass):
"""Given a VTK class, `klass`, returns an instance of the
class.
If the class is abstract, it uses the class tree to return an
instantiable subclass. This is necessary to get the values of
the 'state' methods and the ranges for the Get/Set methods.
"""
obj = None
try:
obj = klass()
except (TypeError, NotImplementedError):
if self._tree:
t = self._tree
n = t.get_node(klass.__name__)
for c in n.children:
obj = self._get_instance(t.get_class(c.name))
if obj:
break
return obj
| bsd-3-clause |
NJ-zero/Android | Request/try.py | 1 | 3835 | # coding=utf-8
import requests,json
import ssl
import unittest
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
url='https://test.waiqin365.com/portal/logon.action'
password = 'a111111'
name = 'dongshichao'
code = 'dong'
context = ssl._create_unverified_context()
headers = {"Connection": "keep-alive",
'Referer': 'https://test.waiqin365.com/layout_new/login.jsp?url=https://test.waiqin365.com',
"Accept-Language": "zh-CN",
"x-requested-with": "XMLHttpRequest",
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
"Accept-Encoding": "gzip, deflate",
"Pragm": "=no-cache",
"Accept": "application/json, text/javascript, */*; q=0.01",
"User-Agent": "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.3)",
"Content-Length": "195",
"Host":'https://test.waiqin365.com'
}
data={'identifiers.password': password,
'identifiers.tenantname': name,
'identifiers.code': code,
'identifiers.type':'1',
'identifiers.src': 'waiqin365',
'refer': 'https://test.waiqin365.com',
}
r = requests.post(url=url,headers=headers,data=data,)
print r.status_code
print r.content
'''
url1="http://172.31.3.73:6020/portal/logon.action"
headers1 = {"Connection": "keep-alive",
"Referer": "http://172.31.3.73:6020/layout_new/login.jsp?url=http://172.31.3.73:6020/layout_new/login.html",
"Accept-Language": "zh-CN",
"x-requested-with": "XMLHttpReques",
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
"Accept-Encoding": "gzip, deflate",
"Pragm": "=no-cache",
"Accept": "application/json, text/javascript, */*; q=0.01",
"User-Agent": "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.3)",
"Content-Length": "195",
"Host": "172.31.3.73:6020"
}
data={'identifiers.src': 'waiqin365',
'identifiers.password': 'a111111',
'refer': 'http://172.31.3.73:6020/layout_new/login.html',
'identifiers.type': '1',
'identifiers.tenantname': 'dongshichao',
'identifiers.code': 'dong'
}
r1=requests.post(url=url1, headers=headers1, data=data)
print r1.headers
print r1.content
print r1.status_code
print r1.cookies
cookie=r1.cookies.get_dict()
cookie1="WQSESSIONID="+"".join(cookie["WQSESSIONID"])
Session =cookie['WQSESSIONID']
print cookie,Session,cookie1
# cookies =dict(cookie_are="working")
url2="http://172.31.3.73:6020/app/pd/web/pd_tree.action"
headers2 = {"Connection": "keep-alive",
"Referer":"http://172.31.3.73:6020/app/pd/web/pd_list.action?menuId=102030",
"Accept-Language": "zh-CN",
"x-requested-with": "XMLHttpReques",
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
"Accept-Encoding": "gzip, deflate",
"Pragm": "=no-cache",
"Accept": "application/json, text/javascript, */*; q=0.01",
"User-Agent": "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.3)",
"Host": "172.31.3.73:6020",
"Cookie":cookie1
}
r2=requests.post(url=url2,headers=headers2)
print r2.headers
print r2.content
print r2.status_code
''' | mit |
davidko/evolspyse | tut/hello.py | 2 | 1079 | #!/usr/bin/env python
"""Hello World example program from the Spyse tutorial"""
from spyse.core.agents.agent import Agent
from spyse.core.behaviours.behaviours import Behaviour
from spyse.app.app import App
# Define a custom behaviour class
class HelloBehaviour(Behaviour):
# Customize the Behaviour class by overriding action()
def action(self):
# The action:
print "Hello, world"
# Mark this behaviour as finished so that it will be removed
# from the agent's behaviour list.
self.set_done()
# Define a custom agent class
class HelloAgent(Agent):
# Customize the Agent class by overriding setup()
def setup(self):
# Add the custom behaviour for the agent to perform.
# An agent will die as soon as all its behaviours are complete.
self.add_behaviour(HelloBehaviour())
# Define a custom application class
class MyApp(App):
# Customize it by overriding run()
def run(self, args):
self.start_agent(HelloAgent)
# Instantiate and run MyApp
if __name__ == "__main__":
MyApp()
| lgpl-2.1 |
nickeubank/python-igraph | igraph/drawing/colors.py | 3 | 122559 | # vim:ts=4:sw=4:sts=4:et
# -*- coding: utf-8 -*-
"""
Color handling functions.
"""
__license__ = u"""\
Copyright (C) 2006-2012 Tamás Nepusz <ntamas@gmail.com>
Pázmány Péter sétány 1/a, 1117 Budapest, Hungary
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA
"""
from igraph.datatypes import Matrix
from igraph.utils import str_to_orientation
from math import ceil
__all__ = ["Palette", "GradientPalette", "AdvancedGradientPalette", \
"RainbowPalette", "PrecalculatedPalette", "ClusterColoringPalette", \
"color_name_to_rgb", "color_name_to_rgba", \
"hsv_to_rgb", "hsva_to_rgba", "hsl_to_rgb", "hsla_to_rgba", \
"rgb_to_hsv", "rgba_to_hsva", "rgb_to_hsl", "rgba_to_hsla", \
"palettes", "known_colors"]
class Palette(object):
"""Base class of color palettes.
Color palettes are mappings that assign integers from the range
0..M{n-1} to colors (4-tuples). M{n} is called the size or length
of the palette. C{igraph} comes with a number of predefined palettes,
so this class is useful for you only if you want to define your
own palette. This can be done by subclassing this class and implementing
the L{Palette._get} method as necessary.
Palettes can also be used as lists or dicts, for the C{__getitem__}
method is overridden properly to call L{Palette.get}.
"""
def __init__(self, n):
self._length = n
self._cache = {}
def clear_cache(self):
"""Clears the result cache.
The return values of L{Palette.get} are cached. Use this method
to clear the cache.
"""
self._cache = {}
def get(self, v):
"""Returns the given color from the palette.
Values are cached: if the specific value given has already been
looked up, its value will be returned from the cache instead of
calculating it again. Use L{Palette.clear_cache} to clear the cache
if necessary.
@note: you shouldn't override this method in subclasses, override
L{_get} instead. If you override this method, lookups in the
L{known_colors} dict won't work, so you won't be able to refer to
colors by names or RGBA quadruplets, only by integer indices. The
caching functionality will disappear as well. However,
feel free to override this method if this is exactly the behaviour
you want.
@param v: the color to be retrieved. If it is an integer, it is
passed to L{Palette._get} to be translated to an RGBA quadruplet.
Otherwise it is passed to L{color_name_to_rgb()} to determine the
RGBA values.
@return: the color as an RGBA quadruplet"""
if isinstance(v, list):
v = tuple(v)
try:
return self._cache[v]
except KeyError:
pass
if isinstance(v, (int, long)):
if v < 0:
raise IndexError("color index must be non-negative")
if v >= self._length:
raise IndexError("color index too large")
result = self._get(v)
else:
result = color_name_to_rgba(v)
self._cache[v] = result
return result
def get_many(self, colors):
"""Returns multiple colors from the palette.
Values are cached: if the specific value given has already been
looked upon, its value will be returned from the cache instead of
calculating it again. Use L{Palette.clear_cache} to clear the cache
if necessary.
@param colors: the list of colors to be retrieved. The palette class
tries to make an educated guess here: if it is not possible to
interpret the value you passed here as a list of colors, the
class will simply try to interpret it as a single color by
forwarding the value to L{Palette.get}.
@return: the colors as a list of RGBA quadruplets. The result will
be a list even if you passed a single color index or color name.
"""
if isinstance(colors, (basestring, int, long)):
# Single color name or index
return [self.get(colors)]
# Multiple colors
return [self.get(color) for color in colors]
def _get(self, v):
"""Override this method in a subclass to create a custom palette.
You can safely assume that v is an integer in the range 0..M{n-1}
where M{n} is the size of the palette.
@param v: numerical index of the color to be retrieved
@return: a 4-tuple containing the RGBA values"""
raise NotImplementedError("abstract class")
__getitem__ = get
@property
def length(self):
"""Returns the number of colors in this palette"""
return self._length
def __len__(self):
"""Returns the number of colors in this palette"""
return self._length
def __plot__(self, context, bbox, palette, *args, **kwds):
"""Plots the colors of the palette on the given Cairo context
Supported keyword arguments are:
- C{border_width}: line width of the border shown around the palette.
If zero or negative, the border is turned off. Default is C{1}.
- C{grid_width}: line width of the grid that separates palette cells.
If zero or negative, the grid is turned off. The grid is also
turned off if the size of a cell is less than three times the given
line width. Default is C{0}. Fractional widths are also allowed.
- C{orientation}: the orientation of the palette. Must be one of
the following values: C{left-right}, C{bottom-top}, C{right-left}
or C{top-bottom}. Possible aliases: C{horizontal} = C{left-right},
C{vertical} = C{bottom-top}, C{lr} = C{left-right},
C{rl} = C{right-left}, C{tb} = C{top-bottom}, C{bt} = C{bottom-top}.
The default is C{left-right}.
"""
border_width = float(kwds.get("border_width", 1.))
grid_width = float(kwds.get("grid_width", 0.))
orientation = str_to_orientation(kwds.get("orientation", "lr"))
# Construct a matrix and plot that
indices = range(len(self))
if orientation in ("rl", "bt"):
indices.reverse()
if orientation in ("lr", "rl"):
matrix = Matrix([indices])
else:
matrix = Matrix([[i] for i in indices])
return matrix.__plot__(context, bbox, self, style="palette",
square=False, grid_width=grid_width,
border_width=border_width)
def __repr__(self):
return "<%s with %d colors>" % (self.__class__.__name__, self._length)
class GradientPalette(Palette):
"""Base class for gradient palettes
Gradient palettes contain a gradient between two given colors.
Example:
>>> pal = GradientPalette("red", "blue", 5)
>>> pal.get(0)
(1.0, 0.0, 0.0, 1.0)
>>> pal.get(2)
(0.5, 0.0, 0.5, 1.0)
>>> pal.get(4)
(0.0, 0.0, 1.0, 1.0)
"""
def __init__(self, color1, color2, n=256):
"""Creates a gradient palette.
@param color1: the color where the gradient starts.
@param color2: the color where the gradient ends.
@param n: the number of colors in the palette.
"""
Palette.__init__(self, n)
self._color1 = color_name_to_rgba(color1)
self._color2 = color_name_to_rgba(color2)
def _get(self, v):
"""Returns the color corresponding to the given color index.
@param v: numerical index of the color to be retrieved
@return: a 4-tuple containing the RGBA values"""
ratio = float(v)/(len(self)-1)
return tuple(self._color1[x]*(1-ratio) + \
self._color2[x]*ratio for x in range(4))
class AdvancedGradientPalette(Palette):
"""Advanced gradient that consists of more than two base colors.
Example:
>>> pal = AdvancedGradientPalette(["red", "black", "blue"], n=9)
>>> pal.get(2)
(0.5, 0.0, 0.0, 1.0)
>>> pal.get(7)
(0.0, 0.0, 0.75, 1.0)
"""
def __init__(self, colors, indices=None, n=256):
"""Creates an advanced gradient palette
@param colors: the colors in the gradient.
@param indices: the color indices belonging to the given colors. If
C{None}, the colors are distributed equidistantly
@param n: the total number of colors in the palette
"""
Palette.__init__(self, n)
if indices is None:
diff = float(n-1) / (len(colors)-1)
indices = [i * diff for i in xrange(len(colors))]
elif not hasattr(indices, "__iter__"):
indices = [float(x) for x in indices]
self._indices, self._colors = zip(*sorted(zip(indices, colors)))
self._colors = [color_name_to_rgba(color) for color in self._colors]
self._dists = [curr-prev for curr, prev in \
zip(self._indices[1:], self._indices)]
def _get(self, v):
"""Returns the color corresponding to the given color index.
@param v: numerical index of the color to be retrieved
@return: a 4-tuple containing the RGBA values"""
colors = self._colors
for i in xrange(len(self._indices)-1):
if self._indices[i] <= v and self._indices[i+1] >= v:
dist = self._dists[i]
ratio = float(v-self._indices[i])/dist
return tuple([colors[i][x]*(1-ratio)+colors[i+1][x]*ratio \
for x in range(4)])
return (0., 0., 0., 1.)
class RainbowPalette(Palette):
"""A palette that varies the hue of the colors along a scale.
Colors in a rainbow palette all have the same saturation, value and
alpha components, while the hue is varied between two given extremes
linearly. This palette has the advantage that it wraps around nicely
if the hue is varied between zero and one (which is the default).
Example:
>>> pal = RainbowPalette(n=120)
>>> pal.get(0)
(1.0, 0.0, 0.0, 1.0)
>>> pal.get(20)
(1.0, 1.0, 0.0, 1.0)
>>> pal.get(40)
(0.0, 1.0, 0.0, 1.0)
>>> pal = RainbowPalette(n=120, s=1, v=0.5, alpha=0.75)
>>> pal.get(60)
(0.0, 0.5, 0.5, 0.75)
>>> pal.get(80)
(0.0, 0.0, 0.5, 0.75)
>>> pal.get(100)
(0.5, 0.0, 0.5, 0.75)
>>> pal = RainbowPalette(n=120)
>>> pal2 = RainbowPalette(n=120, start=0.5, end=0.5)
>>> pal.get(60) == pal2.get(0)
True
>>> pal.get(90) == pal2.get(30)
True
This palette was modeled after the C{rainbow} command of R.
"""
def __init__(self, n=256, s=1, v=1, start=0, end=1, alpha=1):
"""Creates a rainbow palette.
@param n: the number of colors in the palette.
@param s: the saturation of the colors in the palette.
@param v: the value component of the colors in the palette.
@param start: the hue at which the rainbow begins (between 0 and 1).
@param end: the hue at which the rainbow ends (between 0 and 1).
@param alpha: the alpha component of the colors in the palette.
"""
Palette.__init__(self, n)
self._s = float(clamp(s, 0, 1))
self._v = float(clamp(v, 0, 1))
self._alpha = float(clamp(alpha, 0, 1))
self._start = float(start)
if end == self._start:
end += 1
self._dh = (end - self._start) / n
def _get(self, v):
"""Returns the color corresponding to the given color index.
@param v: numerical index of the color to be retrieved
@return: a 4-tuple containing the RGBA values"""
return hsva_to_rgba(self._start + v * self._dh,
self._s, self._v, self._alpha)
class PrecalculatedPalette(Palette):
"""A palette that returns colors from a pre-calculated list of colors"""
def __init__(self, l):
"""Creates the palette backed by the given list. The list must contain
RGBA quadruplets or color names, which will be resolved first by
L{color_name_to_rgba()}. Anything that is understood by
L{color_name_to_rgba()} is OK here."""
Palette.__init__(self, len(l))
for idx, color in enumerate(l):
if isinstance(color, basestring):
color = color_name_to_rgba(color)
self._cache[idx] = color
def _get(self, v):
"""This method will only be called if the requested color index is
outside the size of the palette. In that case, we throw an exception"""
raise ValueError("palette index outside bounds: %s" % v)
class ClusterColoringPalette(PrecalculatedPalette):
"""A palette suitable for coloring vertices when plotting a clustering.
This palette tries to make sure that the colors are easily distinguishable.
This is achieved by using a set of base colors and their lighter and darker
variants, depending on the number of elements in the palette.
When the desired size of the palette is less than or equal to the number of
base colors (denoted by M{n}), only the bsae colors will be used. When the
size of the palette is larger than M{n} but less than M{2*n}, the base colors
and their lighter variants will be used. Between M{2*n} and M{3*n}, the
base colors and their lighter and darker variants will be used. Above M{3*n},
more darker and lighter variants will be generated, but this makes the individual
colors less and less distinguishable.
"""
def __init__(self, n):
base_colors = ["red", "green", "blue", "yellow", \
"magenta", "cyan", "#808080"]
base_colors = [color_name_to_rgba(name) for name in base_colors]
num_base_colors = len(base_colors)
colors = base_colors[:]
blocks_to_add = ceil(float(n - num_base_colors) / num_base_colors)
ratio_increment = 1.0 / (ceil(blocks_to_add / 2.0) + 1)
adding_darker = True
ratio = ratio_increment
while len(colors) < n:
if adding_darker:
new_block = [darken(color, ratio) for color in base_colors]
else:
new_block = [lighten(color, ratio) for color in base_colors]
ratio += ratio_increment
colors.extend(new_block)
adding_darker = not adding_darker
colors = colors[0:n]
PrecalculatedPalette.__init__(self, colors)
def clamp(value, min_value, max_value):
"""Clamps the given value between min and max"""
if value > max_value:
return max_value
if value < min_value:
return min_value
return value
def color_name_to_rgb(color, palette=None):
"""Converts a color given in one of the supported color formats to
R-G-B values.
This is done by calling L{color_name_to_rgba} and then throwing away
the alpha value.
@see: color_name_to_rgba for more details about what formats are
understood by this function.
"""
return color_name_to_rgba(color, palette)[:3]
def color_name_to_rgba(color, palette=None):
"""Converts a color given in one of the supported color formats to
R-G-B-A values.
Examples:
>>> color_name_to_rgba("red")
(1.0, 0.0, 0.0, 1.0)
>>> color_name_to_rgba("#ff8000") == (1.0, 128/255.0, 0.0, 1.0)
True
>>> color_name_to_rgba("#ff800080") == (1.0, 128/255.0, 0.0, 128/255.0)
True
>>> color_name_to_rgba("#08f") == (0.0, 136/255.0, 1.0, 1.0)
True
>>> color_name_to_rgba("rgb(100%, 50%, 0%)")
(1.0, 0.5, 0.0, 1.0)
>>> color_name_to_rgba("rgba(100%, 50%, 0%, 25%)")
(1.0, 0.5, 0.0, 0.25)
>>> color_name_to_rgba("hsla(120, 100%, 50%, 0.5)")
(0.0, 1.0, 0.0, 0.5)
>>> color_name_to_rgba("hsl(60, 100%, 50%)")
(1.0, 1.0, 0.0, 1.0)
>>> color_name_to_rgba("hsv(60, 100%, 100%)")
(1.0, 1.0, 0.0, 1.0)
@param color: the color to be converted in one of the following formats:
- B{CSS3 color specification}: C{#rrggbb}, C{#rgb}, C{#rrggbbaa}, C{#rgba},
C{rgb(red, green, blue)}, C{rgba(red, green, blue, alpha)},
C{hsl(hue, saturation, lightness)}, C{hsla(hue, saturation, lightness, alpha)},
C{hsv(hue, saturation, value)} and C{hsva(hue, saturation, value, alpha)}
where the components are given as hexadecimal numbers in the first four
cases and as decimals or percentages (0%-100%) in the remaining cases.
Red, green and blue components are between 0 and 255; hue is between 0
and 360; saturation, lightness and value is between 0 and 100; alpha is
between 0 and 1.
- B{Valid HTML color names}, i.e. those that are present in the HTML 4.0
specification
- B{Valid X11 color names}, see U{http://en.wikipedia.org/wiki/X11_color_names}
- B{Red-green-blue components} given separately in either a comma-, slash- or
whitespace-separated string or a list or a tuple, in the range of 0-255.
An alpha value of 255 (maximal opacity) will be assumed.
- B{Red-green-blue-alpha components} given separately in either a comma-, slash-
or whitespace-separated string or a list or a tuple, in the range of 0-255
- B{A single palette index} given either as a string or a number. Uses
the palette given in the C{palette} parameter of the method call.
@param palette: the palette to be used if a single number is passed to
the method. Must be an instance of L{colors.Palette}.
@return: the RGBA values corresponding to the given color in a 4-tuple.
Since these colors are primarily used by Cairo routines, the tuples
contain floats in the range 0.0-1.0
"""
if not isinstance(color, basestring):
if hasattr(color, "__iter__"):
components = list(color)
else:
# A single index is given as a number
try:
components = palette.get(color)
except AttributeError:
raise ValueError("palette index used when no palette was given")
if len(components) < 4:
components += [1.] * (4 - len(components))
else:
if color[0] == '#':
color = color[1:]
if len(color) == 3:
components = [int(i, 16) * 17. / 255. for i in color]
components.append(1.0)
elif len(color) == 4:
components = [int(i, 16) * 17. / 255. for i in color]
elif len(color) == 6:
components = [int(color[i:i+2], 16) / 255. for i in (0, 2, 4)]
components.append(1.0)
elif len(color) == 8:
components = [int(color[i:i+2], 16) / 255. for i in (0, 2, 4, 6)]
else:
color_mode = "rgba"
maximums = (255.0, 255.0, 255.0, 1.0)
for mode in ["rgb(", "rgba(", "hsv(", "hsva(", "hsl(", "hsla("]:
if color.startswith(mode) and color[-1] == ")":
color = color[len(mode):-1]
color_mode = mode[:-1]
if mode[0] == "h":
maximums = (360.0, 100.0, 100.0, 1.0)
break
if " " in color or "/" in color or "," in color:
color = color.replace(",", " ").replace("/", " ")
components = color.split()
for idx, comp in enumerate(components):
if comp[-1] == "%":
components[idx] = float(comp[:-1])/100.
else:
components[idx] = float(comp)/maximums[idx]
if len(components) < 4:
components += [1.] * (4 - len(components))
if color_mode[:3] == "hsv":
components = hsva_to_rgba(*components)
elif color_mode[:3] == "hsl":
components = hsla_to_rgba(*components)
else:
try:
components = palette.get(int(color))
except (ValueError, AttributeError):
components = known_colors[color.lower()]
# At this point, the components are floats
return tuple(clamp(val, 0., 1.) for val in components)
def color_to_html_format(color):
"""Formats a color given as a 3-tuple or 4-tuple in HTML format.
The HTML format is simply given by C{#rrggbbaa}, where C{rr} gives
the red component in hexadecimal format, C{gg} gives the green
component C{bb} gives the blue component and C{gg} gives the
alpha level. The alpha level is optional.
"""
color = [int(clamp(component * 256, 0, 255)) for component in color]
if len(color) == 4:
return "#{0:02X}{1:02X}{2:02X}{3:02X}".format(*color)
return "#{0:02X}{1:02X}{2:02X}".format(*color)
def darken(color, ratio=0.5):
"""Creates a darker version of a color given by an RGB triplet.
This is done by mixing the original color with black using the given
ratio. A ratio of 1.0 will yield a completely black color, a ratio
of 0.0 will yield the original color. The alpha values are left intact.
"""
ratio = 1.0 - ratio
red, green, blue, alpha = color
return (red * ratio, green * ratio, blue * ratio, alpha)
def hsla_to_rgba(h, s, l, alpha = 1.0):
"""Converts a color given by its HSLA coordinates (hue, saturation,
lightness, alpha) to RGBA coordinates.
Each of the HSLA coordinates must be in the range [0, 1].
"""
# This is based on the formulae found at:
# http://en.wikipedia.org/wiki/HSL_and_HSV
c = s*(1 - 2*abs(l - 0.5))
h1 = (h*6) % 6
x = c*(1 - abs(h1 % 2 - 1))
m = l - c/2.
h1 = int(h1)
if h1 < 3:
if h1 < 1:
return (c+m, x+m, m, alpha)
elif h1 < 2:
return (x+m, c+m, m, alpha)
else:
return (m, c+m, x+m, alpha)
else:
if h1 < 4:
return (m, x+m, c+m, alpha)
elif h1 < 5:
return (x+m, m, c+m, alpha)
else:
return (c+m, m, x+m, alpha)
def hsl_to_rgb(h, s, l):
"""Converts a color given by its HSL coordinates (hue, saturation,
lightness) to RGB coordinates.
Each of the HSL coordinates must be in the range [0, 1].
"""
return hsla_to_rgba(h, s, l)[:3]
def hsva_to_rgba(h, s, v, alpha = 1.0):
"""Converts a color given by its HSVA coordinates (hue, saturation,
value, alpha) to RGB coordinates.
Each of the HSVA coordinates must be in the range [0, 1].
"""
# This is based on the formulae found at:
# http://en.wikipedia.org/wiki/HSL_and_HSV
c = v*s
h1 = (h*6) % 6
x = c*(1 - abs(h1 % 2 - 1))
m = v-c
h1 = int(h1)
if h1 < 3:
if h1 < 1:
return (c+m, x+m, m, alpha)
elif h1 < 2:
return (x+m, c+m, m, alpha)
else:
return (m, c+m, x+m, alpha)
else:
if h1 < 4:
return (m, x+m, c+m, alpha)
elif h1 < 5:
return (x+m, m, c+m, alpha)
else:
return (c+m, m, x+m, alpha)
def hsv_to_rgb(h, s, v):
"""Converts a color given by its HSV coordinates (hue, saturation,
value) to RGB coordinates.
Each of the HSV coordinates must be in the range [0, 1].
"""
return hsva_to_rgba(h, s, v)[:3]
def rgba_to_hsla(r, g, b, alpha=1.0):
"""Converts a color given by its RGBA coordinates to HSLA coordinates
(hue, saturation, lightness, alpha).
Each of the RGBA coordinates must be in the range [0, 1].
"""
alpha = float(alpha)
rgb_min, rgb_max = float(min(r, g, b)), float(max(r, g, b))
if rgb_min == rgb_max:
return 0.0, 0.0, rgb_min, alpha
lightness = (rgb_min + rgb_max) / 2.0
d = rgb_max - rgb_min
if lightness > 0.5:
sat = d / (2 - rgb_max - rgb_min)
else:
sat = d / (rgb_max + rgb_min)
d *= 6.0
if rgb_max == r:
hue = (g - b) / d
if g < b:
hue += 1
elif rgb_max == g:
hue = 1/3.0 + (b - r) / d
else:
hue = 2/3.0 + (r - g) / d
return hue, sat, lightness, alpha
def rgba_to_hsva(r, g, b, alpha=1.0):
"""Converts a color given by its RGBA coordinates to HSVA coordinates
(hue, saturation, value, alpha).
Each of the RGBA coordinates must be in the range [0, 1].
"""
# This is based on the formulae found at:
# http://en.literateprograms.org/RGB_to_HSV_color_space_conversion_(C)
rgb_min, rgb_max = float(min(r, g, b)), float(max(r, g, b))
alpha = float(alpha)
value = float(rgb_max)
if value <= 0:
return 0.0, 0.0, 0.0, alpha
sat = 1.0 - rgb_min / value
if sat <= 0:
return 0.0, 0.0, value, alpha
d = rgb_max - rgb_min
r = (r - rgb_min) / d
g = (g - rgb_min) / d
b = (b - rgb_min) / d
rgb_max = max(r, g, b)
if rgb_max == r:
hue = 0.0 + (g - b) / 6.0
if hue < 0:
hue += 1
elif rgb_max == g:
hue = 1/3.0 + (b - r) / 6.0
else:
hue = 2/3.0 + (r - g) / 6.0
return hue, sat, value, alpha
def rgb_to_hsl(r, g, b):
"""Converts a color given by its RGB coordinates to HSL coordinates
(hue, saturation, lightness).
Each of the RGB coordinates must be in the range [0, 1].
"""
return rgba_to_hsla(r, g, b)[:3]
def rgb_to_hsv(r, g, b):
"""Converts a color given by its RGB coordinates to HSV coordinates
(hue, saturation, value).
Each of the RGB coordinates must be in the range [0, 1].
"""
return rgba_to_hsva(r, g, b)[:3]
def lighten(color, ratio=0.5):
"""Creates a lighter version of a color given by an RGB triplet.
This is done by mixing the original color with white using the given
ratio. A ratio of 1.0 will yield a completely white color, a ratio
of 0.0 will yield the original color.
"""
red, green, blue, alpha = color
return (red + (1.0 - red) * ratio, green + (1.0 - green) * ratio,
blue + (1.0 - blue) * ratio, alpha)
known_colors = \
{ 'alice blue': (0.94117647058823528, 0.97254901960784312, 1.0, 1.0),
'aliceblue': (0.94117647058823528, 0.97254901960784312, 1.0, 1.0),
'antique white': ( 0.98039215686274506,
0.92156862745098034,
0.84313725490196079,
1.0),
'antiquewhite': ( 0.98039215686274506,
0.92156862745098034,
0.84313725490196079,
1.0),
'antiquewhite1': (1.0, 0.93725490196078431, 0.85882352941176465, 1.0),
'antiquewhite2': ( 0.93333333333333335,
0.87450980392156863,
0.80000000000000004,
1.0),
'antiquewhite3': ( 0.80392156862745101,
0.75294117647058822,
0.69019607843137254,
1.0),
'antiquewhite4': ( 0.54509803921568623,
0.51372549019607838,
0.47058823529411764,
1.0),
'aqua': (0.0, 1.0, 1.0, 1.0),
'aquamarine': (0.49803921568627452, 1.0, 0.83137254901960789, 1.0),
'aquamarine1': (0.49803921568627452, 1.0, 0.83137254901960789, 1.0),
'aquamarine2': ( 0.46274509803921571,
0.93333333333333335,
0.77647058823529413,
1.0),
'aquamarine3': ( 0.40000000000000002,
0.80392156862745101,
0.66666666666666663,
1.0),
'aquamarine4': ( 0.27058823529411763,
0.54509803921568623,
0.45490196078431372,
1.0),
'azure': (0.94117647058823528, 1.0, 1.0, 1.0),
'azure1': (0.94117647058823528, 1.0, 1.0, 1.0),
'azure2': ( 0.8784313725490196,
0.93333333333333335,
0.93333333333333335,
1.0),
'azure3': ( 0.75686274509803919,
0.80392156862745101,
0.80392156862745101,
1.0),
'azure4': ( 0.51372549019607838,
0.54509803921568623,
0.54509803921568623,
1.0),
'beige': ( 0.96078431372549022,
0.96078431372549022,
0.86274509803921573,
1.0),
'bisque': (1.0, 0.89411764705882357, 0.7686274509803922, 1.0),
'bisque1': (1.0, 0.89411764705882357, 0.7686274509803922, 1.0),
'bisque2': ( 0.93333333333333335,
0.83529411764705885,
0.71764705882352942,
1.0),
'bisque3': ( 0.80392156862745101,
0.71764705882352942,
0.61960784313725492,
1.0),
'bisque4': ( 0.54509803921568623,
0.49019607843137253,
0.41960784313725491,
1.0),
'black': (0.0, 0.0, 0.0, 1.0),
'blanched almond': (1.0, 0.92156862745098034, 0.80392156862745101, 1.0),
'blanchedalmond': (1.0, 0.92156862745098034, 0.80392156862745101, 1.0),
'blue': (0.0, 0.0, 1.0, 1.0),
'blue violet': ( 0.54117647058823526,
0.16862745098039217,
0.88627450980392153,
1.0),
'blue1': (0.0, 0.0, 1.0, 1.0),
'blue2': (0.0, 0.0, 0.93333333333333335, 1.0),
'blue3': (0.0, 0.0, 0.80392156862745101, 1.0),
'blue4': (0.0, 0.0, 0.54509803921568623, 1.0),
'blueviolet': ( 0.54117647058823526,
0.16862745098039217,
0.88627450980392153,
1.0),
'brown': ( 0.6470588235294118,
0.16470588235294117,
0.16470588235294117,
1.0),
'brown1': (1.0, 0.25098039215686274, 0.25098039215686274, 1.0),
'brown2': ( 0.93333333333333335,
0.23137254901960785,
0.23137254901960785,
1.0),
'brown3': ( 0.80392156862745101,
0.20000000000000001,
0.20000000000000001,
1.0),
'brown4': ( 0.54509803921568623,
0.13725490196078433,
0.13725490196078433,
1.0),
'burlywood': ( 0.87058823529411766,
0.72156862745098038,
0.52941176470588236,
1.0),
'burlywood1': (1.0, 0.82745098039215681, 0.60784313725490191, 1.0),
'burlywood2': ( 0.93333333333333335,
0.77254901960784317,
0.56862745098039214,
1.0),
'burlywood3': ( 0.80392156862745101,
0.66666666666666663,
0.49019607843137253,
1.0),
'burlywood4': ( 0.54509803921568623,
0.45098039215686275,
0.33333333333333331,
1.0),
'cadet blue': ( 0.37254901960784315,
0.61960784313725492,
0.62745098039215685,
1.0),
'cadetblue': ( 0.37254901960784315,
0.61960784313725492,
0.62745098039215685,
1.0),
'cadetblue1': (0.59607843137254901, 0.96078431372549022, 1.0, 1.0),
'cadetblue2': ( 0.55686274509803924,
0.89803921568627454,
0.93333333333333335,
1.0),
'cadetblue3': ( 0.47843137254901963,
0.77254901960784317,
0.80392156862745101,
1.0),
'cadetblue4': ( 0.32549019607843138,
0.52549019607843139,
0.54509803921568623,
1.0),
'chartreuse': (0.49803921568627452, 1.0, 0.0, 1.0),
'chartreuse1': (0.49803921568627452, 1.0, 0.0, 1.0),
'chartreuse2': (0.46274509803921571, 0.93333333333333335, 0.0, 1.0),
'chartreuse3': (0.40000000000000002, 0.80392156862745101, 0.0, 1.0),
'chartreuse4': (0.27058823529411763, 0.54509803921568623, 0.0, 1.0),
'chocolate': ( 0.82352941176470584,
0.41176470588235292,
0.11764705882352941,
1.0),
'chocolate1': (1.0, 0.49803921568627452, 0.14117647058823529, 1.0),
'chocolate2': ( 0.93333333333333335,
0.46274509803921571,
0.12941176470588237,
1.0),
'chocolate3': ( 0.80392156862745101,
0.40000000000000002,
0.11372549019607843,
1.0),
'chocolate4': ( 0.54509803921568623,
0.27058823529411763,
0.074509803921568626,
1.0),
'coral': (1.0, 0.49803921568627452, 0.31372549019607843, 1.0),
'coral1': (1.0, 0.44705882352941179, 0.33725490196078434, 1.0),
'coral2': ( 0.93333333333333335,
0.41568627450980394,
0.31372549019607843,
1.0),
'coral3': ( 0.80392156862745101,
0.35686274509803922,
0.27058823529411763,
1.0),
'coral4': ( 0.54509803921568623,
0.24313725490196078,
0.18431372549019609,
1.0),
'cornflower blue': ( 0.39215686274509803,
0.58431372549019611,
0.92941176470588238,
1.0),
'cornflowerblue': ( 0.39215686274509803,
0.58431372549019611,
0.92941176470588238,
1.0),
'cornsilk': (1.0, 0.97254901960784312, 0.86274509803921573, 1.0),
'cornsilk1': (1.0, 0.97254901960784312, 0.86274509803921573, 1.0),
'cornsilk2': ( 0.93333333333333335,
0.90980392156862744,
0.80392156862745101,
1.0),
'cornsilk3': ( 0.80392156862745101,
0.78431372549019607,
0.69411764705882351,
1.0),
'cornsilk4': ( 0.54509803921568623,
0.53333333333333333,
0.47058823529411764,
1.0),
'cyan': (0.0, 1.0, 1.0, 1.0),
'cyan1': (0.0, 1.0, 1.0, 1.0),
'cyan2': (0.0, 0.93333333333333335, 0.93333333333333335, 1.0),
'cyan3': (0.0, 0.80392156862745101, 0.80392156862745101, 1.0),
'cyan4': (0.0, 0.54509803921568623, 0.54509803921568623, 1.0),
'dark blue': (0.0, 0.0, 0.54509803921568623, 1.0),
'dark cyan': (0.0, 0.54509803921568623, 0.54509803921568623, 1.0),
'dark goldenrod': ( 0.72156862745098038,
0.52549019607843139,
0.043137254901960784,
1.0),
'dark gray': ( 0.66274509803921566,
0.66274509803921566,
0.66274509803921566,
1.0),
'dark green': (0.0, 0.39215686274509803, 0.0, 1.0),
'dark grey': ( 0.66274509803921566,
0.66274509803921566,
0.66274509803921566,
1.0),
'dark khaki': ( 0.74117647058823533,
0.71764705882352942,
0.41960784313725491,
1.0),
'dark magenta': (0.54509803921568623, 0.0, 0.54509803921568623, 1.0),
'dark olive green': ( 0.33333333333333331,
0.41960784313725491,
0.18431372549019609,
1.0),
'dark orange': (1.0, 0.5490196078431373, 0.0, 1.0),
'dark orchid': ( 0.59999999999999998,
0.19607843137254902,
0.80000000000000004,
1.0),
'dark red': (0.54509803921568623, 0.0, 0.0, 1.0),
'dark salmon': ( 0.9137254901960784,
0.58823529411764708,
0.47843137254901963,
1.0),
'dark sea green': ( 0.5607843137254902,
0.73725490196078436,
0.5607843137254902,
1.0),
'dark slate blue': ( 0.28235294117647058,
0.23921568627450981,
0.54509803921568623,
1.0),
'dark slate gray': ( 0.18431372549019609,
0.30980392156862746,
0.30980392156862746,
1.0),
'dark slate grey': ( 0.18431372549019609,
0.30980392156862746,
0.30980392156862746,
1.0),
'dark turquoise': (0.0, 0.80784313725490198, 0.81960784313725488, 1.0),
'dark violet': (0.58039215686274515, 0.0, 0.82745098039215681, 1.0),
'darkblue': (0.0, 0.0, 0.54509803921568623, 1.0),
'darkcyan': (0.0, 0.54509803921568623, 0.54509803921568623, 1.0),
'darkgoldenrod': ( 0.72156862745098038,
0.52549019607843139,
0.043137254901960784,
1.0),
'darkgoldenrod1': (1.0, 0.72549019607843135, 0.058823529411764705, 1.0),
'darkgoldenrod2': ( 0.93333333333333335,
0.67843137254901964,
0.054901960784313725,
1.0),
'darkgoldenrod3': ( 0.80392156862745101,
0.58431372549019611,
0.047058823529411764,
1.0),
'darkgoldenrod4': ( 0.54509803921568623,
0.396078431372549,
0.031372549019607843,
1.0),
'darkgray': ( 0.66274509803921566,
0.66274509803921566,
0.66274509803921566,
1.0),
'darkgreen': (0.0, 0.39215686274509803, 0.0, 1.0),
'darkgrey': ( 0.66274509803921566,
0.66274509803921566,
0.66274509803921566,
1.0),
'darkkhaki': ( 0.74117647058823533,
0.71764705882352942,
0.41960784313725491,
1.0),
'darkmagenta': (0.54509803921568623, 0.0, 0.54509803921568623, 1.0),
'darkolivegreen': ( 0.33333333333333331,
0.41960784313725491,
0.18431372549019609,
1.0),
'darkolivegreen1': (0.792156862745098, 1.0, 0.4392156862745098, 1.0),
'darkolivegreen2': ( 0.73725490196078436,
0.93333333333333335,
0.40784313725490196,
1.0),
'darkolivegreen3': ( 0.63529411764705879,
0.80392156862745101,
0.35294117647058826,
1.0),
'darkolivegreen4': ( 0.43137254901960786,
0.54509803921568623,
0.23921568627450981,
1.0),
'darkorange': (1.0, 0.5490196078431373, 0.0, 1.0),
'darkorange1': (1.0, 0.49803921568627452, 0.0, 1.0),
'darkorange2': (0.93333333333333335, 0.46274509803921571, 0.0, 1.0),
'darkorange3': (0.80392156862745101, 0.40000000000000002, 0.0, 1.0),
'darkorange4': (0.54509803921568623, 0.27058823529411763, 0.0, 1.0),
'darkorchid': ( 0.59999999999999998,
0.19607843137254902,
0.80000000000000004,
1.0),
'darkorchid1': (0.74901960784313726, 0.24313725490196078, 1.0, 1.0),
'darkorchid2': ( 0.69803921568627447,
0.22745098039215686,
0.93333333333333335,
1.0),
'darkorchid3': ( 0.60392156862745094,
0.19607843137254902,
0.80392156862745101,
1.0),
'darkorchid4': ( 0.40784313725490196,
0.13333333333333333,
0.54509803921568623,
1.0),
'darkred': (0.54509803921568623, 0.0, 0.0, 1.0),
'darksalmon': ( 0.9137254901960784,
0.58823529411764708,
0.47843137254901963,
1.0),
'darkseagreen': ( 0.5607843137254902,
0.73725490196078436,
0.5607843137254902,
1.0),
'darkseagreen1': (0.75686274509803919, 1.0, 0.75686274509803919, 1.0),
'darkseagreen2': ( 0.70588235294117652,
0.93333333333333335,
0.70588235294117652,
1.0),
'darkseagreen3': ( 0.60784313725490191,
0.80392156862745101,
0.60784313725490191,
1.0),
'darkseagreen4': ( 0.41176470588235292,
0.54509803921568623,
0.41176470588235292,
1.0),
'darkslateblue': ( 0.28235294117647058,
0.23921568627450981,
0.54509803921568623,
1.0),
'darkslategray': ( 0.18431372549019609,
0.30980392156862746,
0.30980392156862746,
1.0),
'darkslategray1': (0.59215686274509804, 1.0, 1.0, 1.0),
'darkslategray2': ( 0.55294117647058827,
0.93333333333333335,
0.93333333333333335,
1.0),
'darkslategray3': ( 0.47450980392156861,
0.80392156862745101,
0.80392156862745101,
1.0),
'darkslategray4': ( 0.32156862745098042,
0.54509803921568623,
0.54509803921568623,
1.0),
'darkslategrey': ( 0.18431372549019609,
0.30980392156862746,
0.30980392156862746,
1.0),
'darkturquoise': (0.0, 0.80784313725490198, 0.81960784313725488, 1.0),
'darkviolet': (0.58039215686274515, 0.0, 0.82745098039215681, 1.0),
'deep pink': (1.0, 0.078431372549019607, 0.57647058823529407, 1.0),
'deep sky blue': (0.0, 0.74901960784313726, 1.0, 1.0),
'deeppink': (1.0, 0.078431372549019607, 0.57647058823529407, 1.0),
'deeppink1': (1.0, 0.078431372549019607, 0.57647058823529407, 1.0),
'deeppink2': ( 0.93333333333333335,
0.070588235294117646,
0.53725490196078429,
1.0),
'deeppink3': ( 0.80392156862745101,
0.062745098039215685,
0.46274509803921571,
1.0),
'deeppink4': ( 0.54509803921568623,
0.039215686274509803,
0.31372549019607843,
1.0),
'deepskyblue': (0.0, 0.74901960784313726, 1.0, 1.0),
'deepskyblue1': (0.0, 0.74901960784313726, 1.0, 1.0),
'deepskyblue2': (0.0, 0.69803921568627447, 0.93333333333333335, 1.0),
'deepskyblue3': (0.0, 0.60392156862745094, 0.80392156862745101, 1.0),
'deepskyblue4': (0.0, 0.40784313725490196, 0.54509803921568623, 1.0),
'dim gray': ( 0.41176470588235292,
0.41176470588235292,
0.41176470588235292,
1.0),
'dim grey': ( 0.41176470588235292,
0.41176470588235292,
0.41176470588235292,
1.0),
'dimgray': ( 0.41176470588235292,
0.41176470588235292,
0.41176470588235292,
1.0),
'dimgrey': ( 0.41176470588235292,
0.41176470588235292,
0.41176470588235292,
1.0),
'dodger blue': (0.11764705882352941, 0.56470588235294117, 1.0, 1.0),
'dodgerblue': (0.11764705882352941, 0.56470588235294117, 1.0, 1.0),
'dodgerblue1': (0.11764705882352941, 0.56470588235294117, 1.0, 1.0),
'dodgerblue2': ( 0.10980392156862745,
0.52549019607843139,
0.93333333333333335,
1.0),
'dodgerblue3': ( 0.094117647058823528,
0.45490196078431372,
0.80392156862745101,
1.0),
'dodgerblue4': ( 0.062745098039215685,
0.30588235294117649,
0.54509803921568623,
1.0),
'firebrick': ( 0.69803921568627447,
0.13333333333333333,
0.13333333333333333,
1.0),
'firebrick1': (1.0, 0.18823529411764706, 0.18823529411764706, 1.0),
'firebrick2': ( 0.93333333333333335,
0.17254901960784313,
0.17254901960784313,
1.0),
'firebrick3': ( 0.80392156862745101,
0.14901960784313725,
0.14901960784313725,
1.0),
'firebrick4': ( 0.54509803921568623,
0.10196078431372549,
0.10196078431372549,
1.0),
'floral white': (1.0, 0.98039215686274506, 0.94117647058823528, 1.0),
'floralwhite': (1.0, 0.98039215686274506, 0.94117647058823528, 1.0),
'forest green': ( 0.13333333333333333,
0.54509803921568623,
0.13333333333333333,
1.0),
'forestgreen': ( 0.13333333333333333,
0.54509803921568623,
0.13333333333333333,
1.0),
'fuchsia': (1.0, 0.0, 1.0, 1.0),
'gainsboro': ( 0.86274509803921573,
0.86274509803921573,
0.86274509803921573,
1.0),
'ghost white': (0.97254901960784312, 0.97254901960784312, 1.0, 1.0),
'ghostwhite': (0.97254901960784312, 0.97254901960784312, 1.0, 1.0),
'gold': (1.0, 0.84313725490196079, 0.0, 1.0),
'gold1': (1.0, 0.84313725490196079, 0.0, 1.0),
'gold2': (0.93333333333333335, 0.78823529411764703, 0.0, 1.0),
'gold3': (0.80392156862745101, 0.67843137254901964, 0.0, 1.0),
'gold4': (0.54509803921568623, 0.45882352941176469, 0.0, 1.0),
'goldenrod': ( 0.85490196078431369,
0.6470588235294118,
0.12549019607843137,
1.0),
'goldenrod1': (1.0, 0.75686274509803919, 0.14509803921568629, 1.0),
'goldenrod2': ( 0.93333333333333335,
0.70588235294117652,
0.13333333333333333,
1.0),
'goldenrod3': ( 0.80392156862745101,
0.60784313725490191,
0.11372549019607843,
1.0),
'goldenrod4': ( 0.54509803921568623,
0.41176470588235292,
0.078431372549019607,
1.0),
'gray': ( 0.74509803921568629,
0.74509803921568629,
0.74509803921568629,
1.0),
'gray0': (0.0, 0.0, 0.0, 1.0),
'gray1': ( 0.011764705882352941,
0.011764705882352941,
0.011764705882352941,
1.0),
'gray10': ( 0.10196078431372549,
0.10196078431372549,
0.10196078431372549,
1.0),
'gray100': (1.0, 1.0, 1.0, 1.0),
'gray11': ( 0.10980392156862745,
0.10980392156862745,
0.10980392156862745,
1.0),
'gray12': ( 0.12156862745098039,
0.12156862745098039,
0.12156862745098039,
1.0),
'gray13': ( 0.12941176470588237,
0.12941176470588237,
0.12941176470588237,
1.0),
'gray14': ( 0.14117647058823529,
0.14117647058823529,
0.14117647058823529,
1.0),
'gray15': ( 0.14901960784313725,
0.14901960784313725,
0.14901960784313725,
1.0),
'gray16': ( 0.16078431372549021,
0.16078431372549021,
0.16078431372549021,
1.0),
'gray17': ( 0.16862745098039217,
0.16862745098039217,
0.16862745098039217,
1.0),
'gray18': ( 0.1803921568627451,
0.1803921568627451,
0.1803921568627451,
1.0),
'gray19': ( 0.18823529411764706,
0.18823529411764706,
0.18823529411764706,
1.0),
'gray2': ( 0.019607843137254902,
0.019607843137254902,
0.019607843137254902,
1.0),
'gray20': ( 0.20000000000000001,
0.20000000000000001,
0.20000000000000001,
1.0),
'gray21': ( 0.21176470588235294,
0.21176470588235294,
0.21176470588235294,
1.0),
'gray22': ( 0.2196078431372549,
0.2196078431372549,
0.2196078431372549,
1.0),
'gray23': ( 0.23137254901960785,
0.23137254901960785,
0.23137254901960785,
1.0),
'gray24': ( 0.23921568627450981,
0.23921568627450981,
0.23921568627450981,
1.0),
'gray25': ( 0.25098039215686274,
0.25098039215686274,
0.25098039215686274,
1.0),
'gray26': ( 0.25882352941176473,
0.25882352941176473,
0.25882352941176473,
1.0),
'gray27': ( 0.27058823529411763,
0.27058823529411763,
0.27058823529411763,
1.0),
'gray28': ( 0.27843137254901962,
0.27843137254901962,
0.27843137254901962,
1.0),
'gray29': ( 0.29019607843137257,
0.29019607843137257,
0.29019607843137257,
1.0),
'gray3': ( 0.031372549019607843,
0.031372549019607843,
0.031372549019607843,
1.0),
'gray30': ( 0.30196078431372547,
0.30196078431372547,
0.30196078431372547,
1.0),
'gray31': ( 0.30980392156862746,
0.30980392156862746,
0.30980392156862746,
1.0),
'gray32': ( 0.32156862745098042,
0.32156862745098042,
0.32156862745098042,
1.0),
'gray33': ( 0.32941176470588235,
0.32941176470588235,
0.32941176470588235,
1.0),
'gray34': ( 0.3411764705882353,
0.3411764705882353,
0.3411764705882353,
1.0),
'gray35': ( 0.34901960784313724,
0.34901960784313724,
0.34901960784313724,
1.0),
'gray36': ( 0.36078431372549019,
0.36078431372549019,
0.36078431372549019,
1.0),
'gray37': ( 0.36862745098039218,
0.36862745098039218,
0.36862745098039218,
1.0),
'gray38': ( 0.38039215686274508,
0.38039215686274508,
0.38039215686274508,
1.0),
'gray39': ( 0.38823529411764707,
0.38823529411764707,
0.38823529411764707,
1.0),
'gray4': ( 0.039215686274509803,
0.039215686274509803,
0.039215686274509803,
1.0),
'gray40': ( 0.40000000000000002,
0.40000000000000002,
0.40000000000000002,
1.0),
'gray41': ( 0.41176470588235292,
0.41176470588235292,
0.41176470588235292,
1.0),
'gray42': ( 0.41960784313725491,
0.41960784313725491,
0.41960784313725491,
1.0),
'gray43': ( 0.43137254901960786,
0.43137254901960786,
0.43137254901960786,
1.0),
'gray44': ( 0.4392156862745098,
0.4392156862745098,
0.4392156862745098,
1.0),
'gray45': ( 0.45098039215686275,
0.45098039215686275,
0.45098039215686275,
1.0),
'gray46': ( 0.45882352941176469,
0.45882352941176469,
0.45882352941176469,
1.0),
'gray47': ( 0.47058823529411764,
0.47058823529411764,
0.47058823529411764,
1.0),
'gray48': ( 0.47843137254901963,
0.47843137254901963,
0.47843137254901963,
1.0),
'gray49': ( 0.49019607843137253,
0.49019607843137253,
0.49019607843137253,
1.0),
'gray5': ( 0.050980392156862744,
0.050980392156862744,
0.050980392156862744,
1.0),
'gray50': ( 0.49803921568627452,
0.49803921568627452,
0.49803921568627452,
1.0),
'gray51': ( 0.50980392156862742,
0.50980392156862742,
0.50980392156862742,
1.0),
'gray52': ( 0.52156862745098043,
0.52156862745098043,
0.52156862745098043,
1.0),
'gray53': ( 0.52941176470588236,
0.52941176470588236,
0.52941176470588236,
1.0),
'gray54': ( 0.54117647058823526,
0.54117647058823526,
0.54117647058823526,
1.0),
'gray55': ( 0.5490196078431373,
0.5490196078431373,
0.5490196078431373,
1.0),
'gray56': ( 0.5607843137254902,
0.5607843137254902,
0.5607843137254902,
1.0),
'gray57': ( 0.56862745098039214,
0.56862745098039214,
0.56862745098039214,
1.0),
'gray58': ( 0.58039215686274515,
0.58039215686274515,
0.58039215686274515,
1.0),
'gray59': ( 0.58823529411764708,
0.58823529411764708,
0.58823529411764708,
1.0),
'gray6': ( 0.058823529411764705,
0.058823529411764705,
0.058823529411764705,
1.0),
'gray60': ( 0.59999999999999998,
0.59999999999999998,
0.59999999999999998,
1.0),
'gray61': ( 0.61176470588235299,
0.61176470588235299,
0.61176470588235299,
1.0),
'gray62': ( 0.61960784313725492,
0.61960784313725492,
0.61960784313725492,
1.0),
'gray63': ( 0.63137254901960782,
0.63137254901960782,
0.63137254901960782,
1.0),
'gray64': ( 0.63921568627450975,
0.63921568627450975,
0.63921568627450975,
1.0),
'gray65': ( 0.65098039215686276,
0.65098039215686276,
0.65098039215686276,
1.0),
'gray66': ( 0.6588235294117647,
0.6588235294117647,
0.6588235294117647,
1.0),
'gray67': ( 0.6705882352941176,
0.6705882352941176,
0.6705882352941176,
1.0),
'gray68': ( 0.67843137254901964,
0.67843137254901964,
0.67843137254901964,
1.0),
'gray69': ( 0.69019607843137254,
0.69019607843137254,
0.69019607843137254,
1.0),
'gray7': ( 0.070588235294117646,
0.070588235294117646,
0.070588235294117646,
1.0),
'gray70': ( 0.70196078431372544,
0.70196078431372544,
0.70196078431372544,
1.0),
'gray71': ( 0.70980392156862748,
0.70980392156862748,
0.70980392156862748,
1.0),
'gray72': ( 0.72156862745098038,
0.72156862745098038,
0.72156862745098038,
1.0),
'gray73': ( 0.72941176470588232,
0.72941176470588232,
0.72941176470588232,
1.0),
'gray74': ( 0.74117647058823533,
0.74117647058823533,
0.74117647058823533,
1.0),
'gray75': ( 0.74901960784313726,
0.74901960784313726,
0.74901960784313726,
1.0),
'gray76': ( 0.76078431372549016,
0.76078431372549016,
0.76078431372549016,
1.0),
'gray77': ( 0.7686274509803922,
0.7686274509803922,
0.7686274509803922,
1.0),
'gray78': ( 0.7803921568627451,
0.7803921568627451,
0.7803921568627451,
1.0),
'gray79': ( 0.78823529411764703,
0.78823529411764703,
0.78823529411764703,
1.0),
'gray8': ( 0.078431372549019607,
0.078431372549019607,
0.078431372549019607,
1.0),
'gray80': ( 0.80000000000000004,
0.80000000000000004,
0.80000000000000004,
1.0),
'gray81': ( 0.81176470588235294,
0.81176470588235294,
0.81176470588235294,
1.0),
'gray82': ( 0.81960784313725488,
0.81960784313725488,
0.81960784313725488,
1.0),
'gray83': ( 0.83137254901960789,
0.83137254901960789,
0.83137254901960789,
1.0),
'gray84': ( 0.83921568627450982,
0.83921568627450982,
0.83921568627450982,
1.0),
'gray85': ( 0.85098039215686272,
0.85098039215686272,
0.85098039215686272,
1.0),
'gray86': ( 0.85882352941176465,
0.85882352941176465,
0.85882352941176465,
1.0),
'gray87': ( 0.87058823529411766,
0.87058823529411766,
0.87058823529411766,
1.0),
'gray88': ( 0.8784313725490196,
0.8784313725490196,
0.8784313725490196,
1.0),
'gray89': ( 0.8901960784313725,
0.8901960784313725,
0.8901960784313725,
1.0),
'gray9': ( 0.090196078431372548,
0.090196078431372548,
0.090196078431372548,
1.0),
'gray90': ( 0.89803921568627454,
0.89803921568627454,
0.89803921568627454,
1.0),
'gray91': ( 0.90980392156862744,
0.90980392156862744,
0.90980392156862744,
1.0),
'gray92': ( 0.92156862745098034,
0.92156862745098034,
0.92156862745098034,
1.0),
'gray93': ( 0.92941176470588238,
0.92941176470588238,
0.92941176470588238,
1.0),
'gray94': ( 0.94117647058823528,
0.94117647058823528,
0.94117647058823528,
1.0),
'gray95': ( 0.94901960784313721,
0.94901960784313721,
0.94901960784313721,
1.0),
'gray96': ( 0.96078431372549022,
0.96078431372549022,
0.96078431372549022,
1.0),
'gray97': ( 0.96862745098039216,
0.96862745098039216,
0.96862745098039216,
1.0),
'gray98': ( 0.98039215686274506,
0.98039215686274506,
0.98039215686274506,
1.0),
'gray99': ( 0.9882352941176471,
0.9882352941176471,
0.9882352941176471,
1.0),
'green': (0.0, 1.0, 0.0, 1.0),
'green yellow': (0.67843137254901964, 1.0, 0.18431372549019609, 1.0),
'green1': (0.0, 1.0, 0.0, 1.0),
'green2': (0.0, 0.93333333333333335, 0.0, 1.0),
'green3': (0.0, 0.80392156862745101, 0.0, 1.0),
'green4': (0.0, 0.54509803921568623, 0.0, 1.0),
'greenyellow': (0.67843137254901964, 1.0, 0.18431372549019609, 1.0),
'grey': ( 0.74509803921568629,
0.74509803921568629,
0.74509803921568629,
1.0),
'grey0': (0.0, 0.0, 0.0, 1.0),
'grey1': ( 0.011764705882352941,
0.011764705882352941,
0.011764705882352941,
1.0),
'grey10': ( 0.10196078431372549,
0.10196078431372549,
0.10196078431372549,
1.0),
'grey100': (1.0, 1.0, 1.0, 1.0),
'grey11': ( 0.10980392156862745,
0.10980392156862745,
0.10980392156862745,
1.0),
'grey12': ( 0.12156862745098039,
0.12156862745098039,
0.12156862745098039,
1.0),
'grey13': ( 0.12941176470588237,
0.12941176470588237,
0.12941176470588237,
1.0),
'grey14': ( 0.14117647058823529,
0.14117647058823529,
0.14117647058823529,
1.0),
'grey15': ( 0.14901960784313725,
0.14901960784313725,
0.14901960784313725,
1.0),
'grey16': ( 0.16078431372549021,
0.16078431372549021,
0.16078431372549021,
1.0),
'grey17': ( 0.16862745098039217,
0.16862745098039217,
0.16862745098039217,
1.0),
'grey18': ( 0.1803921568627451,
0.1803921568627451,
0.1803921568627451,
1.0),
'grey19': ( 0.18823529411764706,
0.18823529411764706,
0.18823529411764706,
1.0),
'grey2': ( 0.019607843137254902,
0.019607843137254902,
0.019607843137254902,
1.0),
'grey20': ( 0.20000000000000001,
0.20000000000000001,
0.20000000000000001,
1.0),
'grey21': ( 0.21176470588235294,
0.21176470588235294,
0.21176470588235294,
1.0),
'grey22': ( 0.2196078431372549,
0.2196078431372549,
0.2196078431372549,
1.0),
'grey23': ( 0.23137254901960785,
0.23137254901960785,
0.23137254901960785,
1.0),
'grey24': ( 0.23921568627450981,
0.23921568627450981,
0.23921568627450981,
1.0),
'grey25': ( 0.25098039215686274,
0.25098039215686274,
0.25098039215686274,
1.0),
'grey26': ( 0.25882352941176473,
0.25882352941176473,
0.25882352941176473,
1.0),
'grey27': ( 0.27058823529411763,
0.27058823529411763,
0.27058823529411763,
1.0),
'grey28': ( 0.27843137254901962,
0.27843137254901962,
0.27843137254901962,
1.0),
'grey29': ( 0.29019607843137257,
0.29019607843137257,
0.29019607843137257,
1.0),
'grey3': ( 0.031372549019607843,
0.031372549019607843,
0.031372549019607843,
1.0),
'grey30': ( 0.30196078431372547,
0.30196078431372547,
0.30196078431372547,
1.0),
'grey31': ( 0.30980392156862746,
0.30980392156862746,
0.30980392156862746,
1.0),
'grey32': ( 0.32156862745098042,
0.32156862745098042,
0.32156862745098042,
1.0),
'grey33': ( 0.32941176470588235,
0.32941176470588235,
0.32941176470588235,
1.0),
'grey34': ( 0.3411764705882353,
0.3411764705882353,
0.3411764705882353,
1.0),
'grey35': ( 0.34901960784313724,
0.34901960784313724,
0.34901960784313724,
1.0),
'grey36': ( 0.36078431372549019,
0.36078431372549019,
0.36078431372549019,
1.0),
'grey37': ( 0.36862745098039218,
0.36862745098039218,
0.36862745098039218,
1.0),
'grey38': ( 0.38039215686274508,
0.38039215686274508,
0.38039215686274508,
1.0),
'grey39': ( 0.38823529411764707,
0.38823529411764707,
0.38823529411764707,
1.0),
'grey4': ( 0.039215686274509803,
0.039215686274509803,
0.039215686274509803,
1.0),
'grey40': ( 0.40000000000000002,
0.40000000000000002,
0.40000000000000002,
1.0),
'grey41': ( 0.41176470588235292,
0.41176470588235292,
0.41176470588235292,
1.0),
'grey42': ( 0.41960784313725491,
0.41960784313725491,
0.41960784313725491,
1.0),
'grey43': ( 0.43137254901960786,
0.43137254901960786,
0.43137254901960786,
1.0),
'grey44': ( 0.4392156862745098,
0.4392156862745098,
0.4392156862745098,
1.0),
'grey45': ( 0.45098039215686275,
0.45098039215686275,
0.45098039215686275,
1.0),
'grey46': ( 0.45882352941176469,
0.45882352941176469,
0.45882352941176469,
1.0),
'grey47': ( 0.47058823529411764,
0.47058823529411764,
0.47058823529411764,
1.0),
'grey48': ( 0.47843137254901963,
0.47843137254901963,
0.47843137254901963,
1.0),
'grey49': ( 0.49019607843137253,
0.49019607843137253,
0.49019607843137253,
1.0),
'grey5': ( 0.050980392156862744,
0.050980392156862744,
0.050980392156862744,
1.0),
'grey50': ( 0.49803921568627452,
0.49803921568627452,
0.49803921568627452,
1.0),
'grey51': ( 0.50980392156862742,
0.50980392156862742,
0.50980392156862742,
1.0),
'grey52': ( 0.52156862745098043,
0.52156862745098043,
0.52156862745098043,
1.0),
'grey53': ( 0.52941176470588236,
0.52941176470588236,
0.52941176470588236,
1.0),
'grey54': ( 0.54117647058823526,
0.54117647058823526,
0.54117647058823526,
1.0),
'grey55': ( 0.5490196078431373,
0.5490196078431373,
0.5490196078431373,
1.0),
'grey56': ( 0.5607843137254902,
0.5607843137254902,
0.5607843137254902,
1.0),
'grey57': ( 0.56862745098039214,
0.56862745098039214,
0.56862745098039214,
1.0),
'grey58': ( 0.58039215686274515,
0.58039215686274515,
0.58039215686274515,
1.0),
'grey59': ( 0.58823529411764708,
0.58823529411764708,
0.58823529411764708,
1.0),
'grey6': ( 0.058823529411764705,
0.058823529411764705,
0.058823529411764705,
1.0),
'grey60': ( 0.59999999999999998,
0.59999999999999998,
0.59999999999999998,
1.0),
'grey61': ( 0.61176470588235299,
0.61176470588235299,
0.61176470588235299,
1.0),
'grey62': ( 0.61960784313725492,
0.61960784313725492,
0.61960784313725492,
1.0),
'grey63': ( 0.63137254901960782,
0.63137254901960782,
0.63137254901960782,
1.0),
'grey64': ( 0.63921568627450975,
0.63921568627450975,
0.63921568627450975,
1.0),
'grey65': ( 0.65098039215686276,
0.65098039215686276,
0.65098039215686276,
1.0),
'grey66': ( 0.6588235294117647,
0.6588235294117647,
0.6588235294117647,
1.0),
'grey67': ( 0.6705882352941176,
0.6705882352941176,
0.6705882352941176,
1.0),
'grey68': ( 0.67843137254901964,
0.67843137254901964,
0.67843137254901964,
1.0),
'grey69': ( 0.69019607843137254,
0.69019607843137254,
0.69019607843137254,
1.0),
'grey7': ( 0.070588235294117646,
0.070588235294117646,
0.070588235294117646,
1.0),
'grey70': ( 0.70196078431372544,
0.70196078431372544,
0.70196078431372544,
1.0),
'grey71': ( 0.70980392156862748,
0.70980392156862748,
0.70980392156862748,
1.0),
'grey72': ( 0.72156862745098038,
0.72156862745098038,
0.72156862745098038,
1.0),
'grey73': ( 0.72941176470588232,
0.72941176470588232,
0.72941176470588232,
1.0),
'grey74': ( 0.74117647058823533,
0.74117647058823533,
0.74117647058823533,
1.0),
'grey75': ( 0.74901960784313726,
0.74901960784313726,
0.74901960784313726,
1.0),
'grey76': ( 0.76078431372549016,
0.76078431372549016,
0.76078431372549016,
1.0),
'grey77': ( 0.7686274509803922,
0.7686274509803922,
0.7686274509803922,
1.0),
'grey78': ( 0.7803921568627451,
0.7803921568627451,
0.7803921568627451,
1.0),
'grey79': ( 0.78823529411764703,
0.78823529411764703,
0.78823529411764703,
1.0),
'grey8': ( 0.078431372549019607,
0.078431372549019607,
0.078431372549019607,
1.0),
'grey80': ( 0.80000000000000004,
0.80000000000000004,
0.80000000000000004,
1.0),
'grey81': ( 0.81176470588235294,
0.81176470588235294,
0.81176470588235294,
1.0),
'grey82': ( 0.81960784313725488,
0.81960784313725488,
0.81960784313725488,
1.0),
'grey83': ( 0.83137254901960789,
0.83137254901960789,
0.83137254901960789,
1.0),
'grey84': ( 0.83921568627450982,
0.83921568627450982,
0.83921568627450982,
1.0),
'grey85': ( 0.85098039215686272,
0.85098039215686272,
0.85098039215686272,
1.0),
'grey86': ( 0.85882352941176465,
0.85882352941176465,
0.85882352941176465,
1.0),
'grey87': ( 0.87058823529411766,
0.87058823529411766,
0.87058823529411766,
1.0),
'grey88': ( 0.8784313725490196,
0.8784313725490196,
0.8784313725490196,
1.0),
'grey89': ( 0.8901960784313725,
0.8901960784313725,
0.8901960784313725,
1.0),
'grey9': ( 0.090196078431372548,
0.090196078431372548,
0.090196078431372548,
1.0),
'grey90': ( 0.89803921568627454,
0.89803921568627454,
0.89803921568627454,
1.0),
'grey91': ( 0.90980392156862744,
0.90980392156862744,
0.90980392156862744,
1.0),
'grey92': ( 0.92156862745098034,
0.92156862745098034,
0.92156862745098034,
1.0),
'grey93': ( 0.92941176470588238,
0.92941176470588238,
0.92941176470588238,
1.0),
'grey94': ( 0.94117647058823528,
0.94117647058823528,
0.94117647058823528,
1.0),
'grey95': ( 0.94901960784313721,
0.94901960784313721,
0.94901960784313721,
1.0),
'grey96': ( 0.96078431372549022,
0.96078431372549022,
0.96078431372549022,
1.0),
'grey97': ( 0.96862745098039216,
0.96862745098039216,
0.96862745098039216,
1.0),
'grey98': ( 0.98039215686274506,
0.98039215686274506,
0.98039215686274506,
1.0),
'grey99': ( 0.9882352941176471,
0.9882352941176471,
0.9882352941176471,
1.0),
'honeydew': (0.94117647058823528, 1.0, 0.94117647058823528, 1.0),
'honeydew1': (0.94117647058823528, 1.0, 0.94117647058823528, 1.0),
'honeydew2': ( 0.8784313725490196,
0.93333333333333335,
0.8784313725490196,
1.0),
'honeydew3': ( 0.75686274509803919,
0.80392156862745101,
0.75686274509803919,
1.0),
'honeydew4': ( 0.51372549019607838,
0.54509803921568623,
0.51372549019607838,
1.0),
'hot pink': (1.0, 0.41176470588235292, 0.70588235294117652, 1.0),
'hotpink': (1.0, 0.41176470588235292, 0.70588235294117652, 1.0),
'hotpink1': (1.0, 0.43137254901960786, 0.70588235294117652, 1.0),
'hotpink2': ( 0.93333333333333335,
0.41568627450980394,
0.65490196078431373,
1.0),
'hotpink3': ( 0.80392156862745101,
0.37647058823529411,
0.56470588235294117,
1.0),
'hotpink4': ( 0.54509803921568623,
0.22745098039215686,
0.3843137254901961,
1.0),
'indian red': ( 0.80392156862745101,
0.36078431372549019,
0.36078431372549019,
1.0),
'indianred': ( 0.80392156862745101,
0.36078431372549019,
0.36078431372549019,
1.0),
'indianred1': (1.0, 0.41568627450980394, 0.41568627450980394, 1.0),
'indianred2': ( 0.93333333333333335,
0.38823529411764707,
0.38823529411764707,
1.0),
'indianred3': ( 0.80392156862745101,
0.33333333333333331,
0.33333333333333331,
1.0),
'indianred4': ( 0.54509803921568623,
0.22745098039215686,
0.22745098039215686,
1.0),
'ivory': (1.0, 1.0, 0.94117647058823528, 1.0),
'ivory1': (1.0, 1.0, 0.94117647058823528, 1.0),
'ivory2': ( 0.93333333333333335,
0.93333333333333335,
0.8784313725490196,
1.0),
'ivory3': ( 0.80392156862745101,
0.80392156862745101,
0.75686274509803919,
1.0),
'ivory4': ( 0.54509803921568623,
0.54509803921568623,
0.51372549019607838,
1.0),
'khaki': ( 0.94117647058823528,
0.90196078431372551,
0.5490196078431373,
1.0),
'khaki1': (1.0, 0.96470588235294119, 0.5607843137254902, 1.0),
'khaki2': ( 0.93333333333333335,
0.90196078431372551,
0.52156862745098043,
1.0),
'khaki3': ( 0.80392156862745101,
0.77647058823529413,
0.45098039215686275,
1.0),
'khaki4': ( 0.54509803921568623,
0.52549019607843139,
0.30588235294117649,
1.0),
'lavender': ( 0.90196078431372551,
0.90196078431372551,
0.98039215686274506,
1.0),
'lavender blush': (1.0, 0.94117647058823528, 0.96078431372549022, 1.0),
'lavenderblush': (1.0, 0.94117647058823528, 0.96078431372549022, 1.0),
'lavenderblush1': (1.0, 0.94117647058823528, 0.96078431372549022, 1.0),
'lavenderblush2': ( 0.93333333333333335,
0.8784313725490196,
0.89803921568627454,
1.0),
'lavenderblush3': ( 0.80392156862745101,
0.75686274509803919,
0.77254901960784317,
1.0),
'lavenderblush4': ( 0.54509803921568623,
0.51372549019607838,
0.52549019607843139,
1.0),
'lawn green': (0.48627450980392156, 0.9882352941176471, 0.0, 1.0),
'lawngreen': (0.48627450980392156, 0.9882352941176471, 0.0, 1.0),
'lemon chiffon': (1.0, 0.98039215686274506, 0.80392156862745101, 1.0),
'lemonchiffon': (1.0, 0.98039215686274506, 0.80392156862745101, 1.0),
'lemonchiffon1': (1.0, 0.98039215686274506, 0.80392156862745101, 1.0),
'lemonchiffon2': ( 0.93333333333333335,
0.9137254901960784,
0.74901960784313726,
1.0),
'lemonchiffon3': ( 0.80392156862745101,
0.78823529411764703,
0.6470588235294118,
1.0),
'lemonchiffon4': ( 0.54509803921568623,
0.53725490196078429,
0.4392156862745098,
1.0),
'light blue': ( 0.67843137254901964,
0.84705882352941175,
0.90196078431372551,
1.0),
'light coral': ( 0.94117647058823528,
0.50196078431372548,
0.50196078431372548,
1.0),
'light cyan': (0.8784313725490196, 1.0, 1.0, 1.0),
'light goldenrod': ( 0.93333333333333335,
0.8666666666666667,
0.50980392156862742,
1.0),
'light goldenrod yellow': ( 0.98039215686274506,
0.98039215686274506,
0.82352941176470584,
1.0),
'light gray': ( 0.82745098039215681,
0.82745098039215681,
0.82745098039215681,
1.0),
'light green': ( 0.56470588235294117,
0.93333333333333335,
0.56470588235294117,
1.0),
'light grey': ( 0.82745098039215681,
0.82745098039215681,
0.82745098039215681,
1.0),
'light pink': (1.0, 0.71372549019607845, 0.75686274509803919, 1.0),
'light salmon': (1.0, 0.62745098039215685, 0.47843137254901963, 1.0),
'light sea green': ( 0.12549019607843137,
0.69803921568627447,
0.66666666666666663,
1.0),
'light sky blue': ( 0.52941176470588236,
0.80784313725490198,
0.98039215686274506,
1.0),
'light slate blue': (0.51764705882352946, 0.4392156862745098, 1.0, 1.0),
'light slate gray': ( 0.46666666666666667,
0.53333333333333333,
0.59999999999999998,
1.0),
'light slate grey': ( 0.46666666666666667,
0.53333333333333333,
0.59999999999999998,
1.0),
'light steel blue': ( 0.69019607843137254,
0.7686274509803922,
0.87058823529411766,
1.0),
'light yellow': (1.0, 1.0, 0.8784313725490196, 1.0),
'lightblue': ( 0.67843137254901964,
0.84705882352941175,
0.90196078431372551,
1.0),
'lightblue1': (0.74901960784313726, 0.93725490196078431, 1.0, 1.0),
'lightblue2': ( 0.69803921568627447,
0.87450980392156863,
0.93333333333333335,
1.0),
'lightblue3': ( 0.60392156862745094,
0.75294117647058822,
0.80392156862745101,
1.0),
'lightblue4': ( 0.40784313725490196,
0.51372549019607838,
0.54509803921568623,
1.0),
'lightcoral': ( 0.94117647058823528,
0.50196078431372548,
0.50196078431372548,
1.0),
'lightcyan': (0.8784313725490196, 1.0, 1.0, 1.0),
'lightcyan1': (0.8784313725490196, 1.0, 1.0, 1.0),
'lightcyan2': ( 0.81960784313725488,
0.93333333333333335,
0.93333333333333335,
1.0),
'lightcyan3': ( 0.70588235294117652,
0.80392156862745101,
0.80392156862745101,
1.0),
'lightcyan4': ( 0.47843137254901963,
0.54509803921568623,
0.54509803921568623,
1.0),
'lightgoldenrod': ( 0.93333333333333335,
0.8666666666666667,
0.50980392156862742,
1.0),
'lightgoldenrod1': (1.0, 0.92549019607843142, 0.54509803921568623, 1.0),
'lightgoldenrod2': ( 0.93333333333333335,
0.86274509803921573,
0.50980392156862742,
1.0),
'lightgoldenrod3': ( 0.80392156862745101,
0.74509803921568629,
0.4392156862745098,
1.0),
'lightgoldenrod4': ( 0.54509803921568623,
0.50588235294117645,
0.29803921568627451,
1.0),
'lightgoldenrodyellow': ( 0.98039215686274506,
0.98039215686274506,
0.82352941176470584,
1.0),
'lightgray': ( 0.82745098039215681,
0.82745098039215681,
0.82745098039215681,
1.0),
'lightgreen': ( 0.56470588235294117,
0.93333333333333335,
0.56470588235294117,
1.0),
'lightgrey': ( 0.82745098039215681,
0.82745098039215681,
0.82745098039215681,
1.0),
'lightpink': (1.0, 0.71372549019607845, 0.75686274509803919, 1.0),
'lightpink1': (1.0, 0.68235294117647061, 0.72549019607843135, 1.0),
'lightpink2': ( 0.93333333333333335,
0.63529411764705879,
0.67843137254901964,
1.0),
'lightpink3': ( 0.80392156862745101,
0.5490196078431373,
0.58431372549019611,
1.0),
'lightpink4': ( 0.54509803921568623,
0.37254901960784315,
0.396078431372549,
1.0),
'lightsalmon': (1.0, 0.62745098039215685, 0.47843137254901963, 1.0),
'lightsalmon1': (1.0, 0.62745098039215685, 0.47843137254901963, 1.0),
'lightsalmon2': ( 0.93333333333333335,
0.58431372549019611,
0.44705882352941179,
1.0),
'lightsalmon3': ( 0.80392156862745101,
0.50588235294117645,
0.3843137254901961,
1.0),
'lightsalmon4': ( 0.54509803921568623,
0.3411764705882353,
0.25882352941176473,
1.0),
'lightseagreen': ( 0.12549019607843137,
0.69803921568627447,
0.66666666666666663,
1.0),
'lightskyblue': ( 0.52941176470588236,
0.80784313725490198,
0.98039215686274506,
1.0),
'lightskyblue1': (0.69019607843137254, 0.88627450980392153, 1.0, 1.0),
'lightskyblue2': ( 0.64313725490196083,
0.82745098039215681,
0.93333333333333335,
1.0),
'lightskyblue3': ( 0.55294117647058827,
0.71372549019607845,
0.80392156862745101,
1.0),
'lightskyblue4': ( 0.37647058823529411,
0.4823529411764706,
0.54509803921568623,
1.0),
'lightslateblue': (0.51764705882352946, 0.4392156862745098, 1.0, 1.0),
'lightslategray': ( 0.46666666666666667,
0.53333333333333333,
0.59999999999999998,
1.0),
'lightslategrey': ( 0.46666666666666667,
0.53333333333333333,
0.59999999999999998,
1.0),
'lightsteelblue': ( 0.69019607843137254,
0.7686274509803922,
0.87058823529411766,
1.0),
'lightsteelblue1': (0.792156862745098, 0.88235294117647056, 1.0, 1.0),
'lightsteelblue2': ( 0.73725490196078436,
0.82352941176470584,
0.93333333333333335,
1.0),
'lightsteelblue3': ( 0.63529411764705879,
0.70980392156862748,
0.80392156862745101,
1.0),
'lightsteelblue4': ( 0.43137254901960786,
0.4823529411764706,
0.54509803921568623,
1.0),
'lightyellow': (1.0, 1.0, 0.8784313725490196, 1.0),
'lightyellow1': (1.0, 1.0, 0.8784313725490196, 1.0),
'lightyellow2': ( 0.93333333333333335,
0.93333333333333335,
0.81960784313725488,
1.0),
'lightyellow3': ( 0.80392156862745101,
0.80392156862745101,
0.70588235294117652,
1.0),
'lightyellow4': ( 0.54509803921568623,
0.54509803921568623,
0.47843137254901963,
1.0),
'lime': (0.0, 1.0, 0.0, 1.0),
'lime green': ( 0.19607843137254902,
0.80392156862745101,
0.19607843137254902,
1.0),
'limegreen': ( 0.19607843137254902,
0.80392156862745101,
0.19607843137254902,
1.0),
'linen': ( 0.98039215686274506,
0.94117647058823528,
0.90196078431372551,
1.0),
'magenta': (1.0, 0.0, 1.0, 1.0),
'magenta1': (1.0, 0.0, 1.0, 1.0),
'magenta2': (0.93333333333333335, 0.0, 0.93333333333333335, 1.0),
'magenta3': (0.80392156862745101, 0.0, 0.80392156862745101, 1.0),
'magenta4': (0.54509803921568623, 0.0, 0.54509803921568623, 1.0),
'maroon': ( 0.69019607843137254,
0.18823529411764706,
0.37647058823529411,
1.0),
'maroon1': (1.0, 0.20392156862745098, 0.70196078431372544, 1.0),
'maroon2': ( 0.93333333333333335,
0.18823529411764706,
0.65490196078431373,
1.0),
'maroon3': ( 0.80392156862745101,
0.16078431372549021,
0.56470588235294117,
1.0),
'maroon4': ( 0.54509803921568623,
0.10980392156862745,
0.3843137254901961,
1.0),
'medium aquamarine': ( 0.40000000000000002,
0.80392156862745101,
0.66666666666666663,
1.0),
'medium blue': (0.0, 0.0, 0.80392156862745101, 1.0),
'medium orchid': ( 0.72941176470588232,
0.33333333333333331,
0.82745098039215681,
1.0),
'medium purple': ( 0.57647058823529407,
0.4392156862745098,
0.85882352941176465,
1.0),
'medium sea green': ( 0.23529411764705882,
0.70196078431372544,
0.44313725490196076,
1.0),
'medium slate blue': ( 0.4823529411764706,
0.40784313725490196,
0.93333333333333335,
1.0),
'medium spring green': ( 0.0,
0.98039215686274506,
0.60392156862745094,
1.0),
'medium turquoise': ( 0.28235294117647058,
0.81960784313725488,
0.80000000000000004,
1.0),
'medium violet red': ( 0.7803921568627451,
0.082352941176470587,
0.52156862745098043,
1.0),
'mediumaquamarine': ( 0.40000000000000002,
0.80392156862745101,
0.66666666666666663,
1.0),
'mediumblue': (0.0, 0.0, 0.80392156862745101, 1.0),
'mediumorchid': ( 0.72941176470588232,
0.33333333333333331,
0.82745098039215681,
1.0),
'mediumorchid1': (0.8784313725490196, 0.40000000000000002, 1.0, 1.0),
'mediumorchid2': ( 0.81960784313725488,
0.37254901960784315,
0.93333333333333335,
1.0),
'mediumorchid3': ( 0.70588235294117652,
0.32156862745098042,
0.80392156862745101,
1.0),
'mediumorchid4': ( 0.47843137254901963,
0.21568627450980393,
0.54509803921568623,
1.0),
'mediumpurple': ( 0.57647058823529407,
0.4392156862745098,
0.85882352941176465,
1.0),
'mediumpurple1': (0.6705882352941176, 0.50980392156862742, 1.0, 1.0),
'mediumpurple2': ( 0.62352941176470589,
0.47450980392156861,
0.93333333333333335,
1.0),
'mediumpurple3': ( 0.53725490196078429,
0.40784313725490196,
0.80392156862745101,
1.0),
'mediumpurple4': ( 0.36470588235294116,
0.27843137254901962,
0.54509803921568623,
1.0),
'mediumseagreen': ( 0.23529411764705882,
0.70196078431372544,
0.44313725490196076,
1.0),
'mediumslateblue': ( 0.4823529411764706,
0.40784313725490196,
0.93333333333333335,
1.0),
'mediumspringgreen': (0.0, 0.98039215686274506, 0.60392156862745094, 1.0),
'mediumturquoise': ( 0.28235294117647058,
0.81960784313725488,
0.80000000000000004,
1.0),
'mediumvioletred': ( 0.7803921568627451,
0.082352941176470587,
0.52156862745098043,
1.0),
'midnight blue': ( 0.098039215686274508,
0.098039215686274508,
0.4392156862745098,
1.0),
'midnightblue': ( 0.098039215686274508,
0.098039215686274508,
0.4392156862745098,
1.0),
'mint cream': (0.96078431372549022, 1.0, 0.98039215686274506, 1.0),
'mintcream': (0.96078431372549022, 1.0, 0.98039215686274506, 1.0),
'misty rose': (1.0, 0.89411764705882357, 0.88235294117647056, 1.0),
'mistyrose': (1.0, 0.89411764705882357, 0.88235294117647056, 1.0),
'mistyrose1': (1.0, 0.89411764705882357, 0.88235294117647056, 1.0),
'mistyrose2': ( 0.93333333333333335,
0.83529411764705885,
0.82352941176470584,
1.0),
'mistyrose3': ( 0.80392156862745101,
0.71764705882352942,
0.70980392156862748,
1.0),
'mistyrose4': ( 0.54509803921568623,
0.49019607843137253,
0.4823529411764706,
1.0),
'moccasin': (1.0, 0.89411764705882357, 0.70980392156862748, 1.0),
'navajo white': (1.0, 0.87058823529411766, 0.67843137254901964, 1.0),
'navajowhite': (1.0, 0.87058823529411766, 0.67843137254901964, 1.0),
'navajowhite1': (1.0, 0.87058823529411766, 0.67843137254901964, 1.0),
'navajowhite2': ( 0.93333333333333335,
0.81176470588235294,
0.63137254901960782,
1.0),
'navajowhite3': ( 0.80392156862745101,
0.70196078431372544,
0.54509803921568623,
1.0),
'navajowhite4': ( 0.54509803921568623,
0.47450980392156861,
0.36862745098039218,
1.0),
'navy': (0.0, 0.0, 0.50196078431372548, 1.0),
'navy blue': (0.0, 0.0, 0.50196078431372548, 1.0),
'navyblue': (0.0, 0.0, 0.50196078431372548, 1.0),
'old lace': ( 0.99215686274509807,
0.96078431372549022,
0.90196078431372551,
1.0),
'oldlace': ( 0.99215686274509807,
0.96078431372549022,
0.90196078431372551,
1.0),
'olive': (0.5, 0.5, 0.0, 1.0),
'olive drab': ( 0.41960784313725491,
0.55686274509803924,
0.13725490196078433,
1.0),
'olivedrab': ( 0.41960784313725491,
0.55686274509803924,
0.13725490196078433,
1.0),
'olivedrab1': (0.75294117647058822, 1.0, 0.24313725490196078, 1.0),
'olivedrab2': ( 0.70196078431372544,
0.93333333333333335,
0.22745098039215686,
1.0),
'olivedrab3': ( 0.60392156862745094,
0.80392156862745101,
0.19607843137254902,
1.0),
'olivedrab4': ( 0.41176470588235292,
0.54509803921568623,
0.13333333333333333,
1.0),
'orange': (1.0, 0.6470588235294118, 0.0, 1.0),
'orange red': (1.0, 0.27058823529411763, 0.0, 1.0),
'orange1': (1.0, 0.6470588235294118, 0.0, 1.0),
'orange2': (0.93333333333333335, 0.60392156862745094, 0.0, 1.0),
'orange3': (0.80392156862745101, 0.52156862745098043, 0.0, 1.0),
'orange4': (0.54509803921568623, 0.35294117647058826, 0.0, 1.0),
'orangered': (1.0, 0.27058823529411763, 0.0, 1.0),
'orangered1': (1.0, 0.27058823529411763, 0.0, 1.0),
'orangered2': (0.93333333333333335, 0.25098039215686274, 0.0, 1.0),
'orangered3': (0.80392156862745101, 0.21568627450980393, 0.0, 1.0),
'orangered4': (0.54509803921568623, 0.14509803921568629, 0.0, 1.0),
'orchid': ( 0.85490196078431369,
0.4392156862745098,
0.83921568627450982,
1.0),
'orchid1': (1.0, 0.51372549019607838, 0.98039215686274506, 1.0),
'orchid2': ( 0.93333333333333335,
0.47843137254901963,
0.9137254901960784,
1.0),
'orchid3': ( 0.80392156862745101,
0.41176470588235292,
0.78823529411764703,
1.0),
'orchid4': ( 0.54509803921568623,
0.27843137254901962,
0.53725490196078429,
1.0),
'pale goldenrod': ( 0.93333333333333335,
0.90980392156862744,
0.66666666666666663,
1.0),
'pale green': ( 0.59607843137254901,
0.98431372549019602,
0.59607843137254901,
1.0),
'pale turquoise': ( 0.68627450980392157,
0.93333333333333335,
0.93333333333333335,
1.0),
'pale violet red': ( 0.85882352941176465,
0.4392156862745098,
0.57647058823529407,
1.0),
'palegoldenrod': ( 0.93333333333333335,
0.90980392156862744,
0.66666666666666663,
1.0),
'palegreen': ( 0.59607843137254901,
0.98431372549019602,
0.59607843137254901,
1.0),
'palegreen1': (0.60392156862745094, 1.0, 0.60392156862745094, 1.0),
'palegreen2': ( 0.56470588235294117,
0.93333333333333335,
0.56470588235294117,
1.0),
'palegreen3': ( 0.48627450980392156,
0.80392156862745101,
0.48627450980392156,
1.0),
'palegreen4': ( 0.32941176470588235,
0.54509803921568623,
0.32941176470588235,
1.0),
'paleturquoise': ( 0.68627450980392157,
0.93333333333333335,
0.93333333333333335,
1.0),
'paleturquoise1': (0.73333333333333328, 1.0, 1.0, 1.0),
'paleturquoise2': ( 0.68235294117647061,
0.93333333333333335,
0.93333333333333335,
1.0),
'paleturquoise3': ( 0.58823529411764708,
0.80392156862745101,
0.80392156862745101,
1.0),
'paleturquoise4': ( 0.40000000000000002,
0.54509803921568623,
0.54509803921568623,
1.0),
'palevioletred': ( 0.85882352941176465,
0.4392156862745098,
0.57647058823529407,
1.0),
'palevioletred1': (1.0, 0.50980392156862742, 0.6705882352941176, 1.0),
'palevioletred2': ( 0.93333333333333335,
0.47450980392156861,
0.62352941176470589,
1.0),
'palevioletred3': ( 0.80392156862745101,
0.40784313725490196,
0.53725490196078429,
1.0),
'palevioletred4': ( 0.54509803921568623,
0.27843137254901962,
0.36470588235294116,
1.0),
'papaya whip': (1.0, 0.93725490196078431, 0.83529411764705885, 1.0),
'papayawhip': (1.0, 0.93725490196078431, 0.83529411764705885, 1.0),
'peach puff': (1.0, 0.85490196078431369, 0.72549019607843135, 1.0),
'peachpuff': (1.0, 0.85490196078431369, 0.72549019607843135, 1.0),
'peachpuff1': (1.0, 0.85490196078431369, 0.72549019607843135, 1.0),
'peachpuff2': ( 0.93333333333333335,
0.79607843137254897,
0.67843137254901964,
1.0),
'peachpuff3': ( 0.80392156862745101,
0.68627450980392157,
0.58431372549019611,
1.0),
'peachpuff4': ( 0.54509803921568623,
0.46666666666666667,
0.396078431372549,
1.0),
'peru': ( 0.80392156862745101,
0.52156862745098043,
0.24705882352941178,
1.0),
'pink': (1.0, 0.75294117647058822, 0.79607843137254897, 1.0),
'pink1': (1.0, 0.70980392156862748, 0.77254901960784317, 1.0),
'pink2': ( 0.93333333333333335,
0.66274509803921566,
0.72156862745098038,
1.0),
'pink3': ( 0.80392156862745101,
0.56862745098039214,
0.61960784313725492,
1.0),
'pink4': ( 0.54509803921568623,
0.38823529411764707,
0.42352941176470588,
1.0),
'plum': (0.8666666666666667, 0.62745098039215685, 0.8666666666666667, 1.0),
'plum1': (1.0, 0.73333333333333328, 1.0, 1.0),
'plum2': ( 0.93333333333333335,
0.68235294117647061,
0.93333333333333335,
1.0),
'plum3': ( 0.80392156862745101,
0.58823529411764708,
0.80392156862745101,
1.0),
'plum4': ( 0.54509803921568623,
0.40000000000000002,
0.54509803921568623,
1.0),
'powder blue': ( 0.69019607843137254,
0.8784313725490196,
0.90196078431372551,
1.0),
'powderblue': ( 0.69019607843137254,
0.8784313725490196,
0.90196078431372551,
1.0),
'purple': ( 0.62745098039215685,
0.12549019607843137,
0.94117647058823528,
1.0),
'purple1': (0.60784313725490191, 0.18823529411764706, 1.0, 1.0),
'purple2': ( 0.56862745098039214,
0.17254901960784313,
0.93333333333333335,
1.0),
'purple3': ( 0.49019607843137253,
0.14901960784313725,
0.80392156862745101,
1.0),
'purple4': ( 0.33333333333333331,
0.10196078431372549,
0.54509803921568623,
1.0),
'red': (1.0, 0.0, 0.0, 1.0),
'red1': (1.0, 0.0, 0.0, 1.0),
'red2': (0.93333333333333335, 0.0, 0.0, 1.0),
'red3': (0.80392156862745101, 0.0, 0.0, 1.0),
'red4': (0.54509803921568623, 0.0, 0.0, 1.0),
'rosy brown': ( 0.73725490196078436,
0.5607843137254902,
0.5607843137254902,
1.0),
'rosybrown': ( 0.73725490196078436,
0.5607843137254902,
0.5607843137254902,
1.0),
'rosybrown1': (1.0, 0.75686274509803919, 0.75686274509803919, 1.0),
'rosybrown2': ( 0.93333333333333335,
0.70588235294117652,
0.70588235294117652,
1.0),
'rosybrown3': ( 0.80392156862745101,
0.60784313725490191,
0.60784313725490191,
1.0),
'rosybrown4': ( 0.54509803921568623,
0.41176470588235292,
0.41176470588235292,
1.0),
'royal blue': ( 0.25490196078431371,
0.41176470588235292,
0.88235294117647056,
1.0),
'royalblue': ( 0.25490196078431371,
0.41176470588235292,
0.88235294117647056,
1.0),
'royalblue1': (0.28235294117647058, 0.46274509803921571, 1.0, 1.0),
'royalblue2': ( 0.2627450980392157,
0.43137254901960786,
0.93333333333333335,
1.0),
'royalblue3': ( 0.22745098039215686,
0.37254901960784315,
0.80392156862745101,
1.0),
'royalblue4': ( 0.15294117647058825,
0.25098039215686274,
0.54509803921568623,
1.0),
'saddle brown': ( 0.54509803921568623,
0.27058823529411763,
0.074509803921568626,
1.0),
'saddlebrown': ( 0.54509803921568623,
0.27058823529411763,
0.074509803921568626,
1.0),
'salmon': ( 0.98039215686274506,
0.50196078431372548,
0.44705882352941179,
1.0),
'salmon1': (1.0, 0.5490196078431373, 0.41176470588235292, 1.0),
'salmon2': ( 0.93333333333333335,
0.50980392156862742,
0.3843137254901961,
1.0),
'salmon3': ( 0.80392156862745101,
0.4392156862745098,
0.32941176470588235,
1.0),
'salmon4': ( 0.54509803921568623,
0.29803921568627451,
0.22352941176470589,
1.0),
'sandy brown': ( 0.95686274509803926,
0.64313725490196083,
0.37647058823529411,
1.0),
'sandybrown': ( 0.95686274509803926,
0.64313725490196083,
0.37647058823529411,
1.0),
'sea green': ( 0.1803921568627451,
0.54509803921568623,
0.3411764705882353,
1.0),
'seagreen': ( 0.1803921568627451,
0.54509803921568623,
0.3411764705882353,
1.0),
'seagreen1': (0.32941176470588235, 1.0, 0.62352941176470589, 1.0),
'seagreen2': ( 0.30588235294117649,
0.93333333333333335,
0.58039215686274515,
1.0),
'seagreen3': ( 0.2627450980392157,
0.80392156862745101,
0.50196078431372548,
1.0),
'seagreen4': ( 0.1803921568627451,
0.54509803921568623,
0.3411764705882353,
1.0),
'seashell': (1.0, 0.96078431372549022, 0.93333333333333335, 1.0),
'seashell1': (1.0, 0.96078431372549022, 0.93333333333333335, 1.0),
'seashell2': ( 0.93333333333333335,
0.89803921568627454,
0.87058823529411766,
1.0),
'seashell3': ( 0.80392156862745101,
0.77254901960784317,
0.74901960784313726,
1.0),
'seashell4': ( 0.54509803921568623,
0.52549019607843139,
0.50980392156862742,
1.0),
'sienna': ( 0.62745098039215685,
0.32156862745098042,
0.17647058823529413,
1.0),
'sienna1': (1.0, 0.50980392156862742, 0.27843137254901962, 1.0),
'sienna2': ( 0.93333333333333335,
0.47450980392156861,
0.25882352941176473,
1.0),
'sienna3': ( 0.80392156862745101,
0.40784313725490196,
0.22352941176470589,
1.0),
'sienna4': ( 0.54509803921568623,
0.27843137254901962,
0.14901960784313725,
1.0),
'silver': (0.75, 0.75, 0.75, 1.0),
'sky blue': ( 0.52941176470588236,
0.80784313725490198,
0.92156862745098034,
1.0),
'skyblue': ( 0.52941176470588236,
0.80784313725490198,
0.92156862745098034,
1.0),
'skyblue1': (0.52941176470588236, 0.80784313725490198, 1.0, 1.0),
'skyblue2': ( 0.49411764705882355,
0.75294117647058822,
0.93333333333333335,
1.0),
'skyblue3': ( 0.42352941176470588,
0.65098039215686276,
0.80392156862745101,
1.0),
'skyblue4': ( 0.29019607843137257,
0.4392156862745098,
0.54509803921568623,
1.0),
'slate blue': ( 0.41568627450980394,
0.35294117647058826,
0.80392156862745101,
1.0),
'slate gray': ( 0.4392156862745098,
0.50196078431372548,
0.56470588235294117,
1.0),
'slate grey': ( 0.4392156862745098,
0.50196078431372548,
0.56470588235294117,
1.0),
'slateblue': ( 0.41568627450980394,
0.35294117647058826,
0.80392156862745101,
1.0),
'slateblue1': (0.51372549019607838, 0.43529411764705883, 1.0, 1.0),
'slateblue2': ( 0.47843137254901963,
0.40392156862745099,
0.93333333333333335,
1.0),
'slateblue3': ( 0.41176470588235292,
0.34901960784313724,
0.80392156862745101,
1.0),
'slateblue4': ( 0.27843137254901962,
0.23529411764705882,
0.54509803921568623,
1.0),
'slategray': ( 0.4392156862745098,
0.50196078431372548,
0.56470588235294117,
1.0),
'slategray1': (0.77647058823529413, 0.88627450980392153, 1.0, 1.0),
'slategray2': ( 0.72549019607843135,
0.82745098039215681,
0.93333333333333335,
1.0),
'slategray3': ( 0.62352941176470589,
0.71372549019607845,
0.80392156862745101,
1.0),
'slategray4': ( 0.42352941176470588,
0.4823529411764706,
0.54509803921568623,
1.0),
'slategrey': ( 0.4392156862745098,
0.50196078431372548,
0.56470588235294117,
1.0),
'snow': (1.0, 0.98039215686274506, 0.98039215686274506, 1.0),
'snow1': (1.0, 0.98039215686274506, 0.98039215686274506, 1.0),
'snow2': ( 0.93333333333333335,
0.9137254901960784,
0.9137254901960784,
1.0),
'snow3': ( 0.80392156862745101,
0.78823529411764703,
0.78823529411764703,
1.0),
'snow4': ( 0.54509803921568623,
0.53725490196078429,
0.53725490196078429,
1.0),
'spring green': (0.0, 1.0, 0.49803921568627452, 1.0),
'springgreen': (0.0, 1.0, 0.49803921568627452, 1.0),
'springgreen1': (0.0, 1.0, 0.49803921568627452, 1.0),
'springgreen2': (0.0, 0.93333333333333335, 0.46274509803921571, 1.0),
'springgreen3': (0.0, 0.80392156862745101, 0.40000000000000002, 1.0),
'springgreen4': (0.0, 0.54509803921568623, 0.27058823529411763, 1.0),
'steel blue': ( 0.27450980392156865,
0.50980392156862742,
0.70588235294117652,
1.0),
'steelblue': ( 0.27450980392156865,
0.50980392156862742,
0.70588235294117652,
1.0),
'steelblue1': (0.38823529411764707, 0.72156862745098038, 1.0, 1.0),
'steelblue2': ( 0.36078431372549019,
0.67450980392156867,
0.93333333333333335,
1.0),
'steelblue3': ( 0.30980392156862746,
0.58039215686274515,
0.80392156862745101,
1.0),
'steelblue4': ( 0.21176470588235294,
0.39215686274509803,
0.54509803921568623,
1.0),
'tan': (0.82352941176470584, 0.70588235294117652, 0.5490196078431373, 1.0),
'tan1': (1.0, 0.6470588235294118, 0.30980392156862746, 1.0),
'tan2': ( 0.93333333333333335,
0.60392156862745094,
0.28627450980392155,
1.0),
'tan3': ( 0.80392156862745101,
0.52156862745098043,
0.24705882352941178,
1.0),
'tan4': ( 0.54509803921568623,
0.35294117647058826,
0.16862745098039217,
1.0),
'teal': (0.0, 0.5, 0.5, 1.0),
'thistle': ( 0.84705882352941175,
0.74901960784313726,
0.84705882352941175,
1.0),
'thistle1': (1.0, 0.88235294117647056, 1.0, 1.0),
'thistle2': ( 0.93333333333333335,
0.82352941176470584,
0.93333333333333335,
1.0),
'thistle3': ( 0.80392156862745101,
0.70980392156862748,
0.80392156862745101,
1.0),
'thistle4': ( 0.54509803921568623,
0.4823529411764706,
0.54509803921568623,
1.0),
'tomato': (1.0, 0.38823529411764707, 0.27843137254901962, 1.0),
'tomato1': (1.0, 0.38823529411764707, 0.27843137254901962, 1.0),
'tomato2': ( 0.93333333333333335,
0.36078431372549019,
0.25882352941176473,
1.0),
'tomato3': ( 0.80392156862745101,
0.30980392156862746,
0.22352941176470589,
1.0),
'tomato4': ( 0.54509803921568623,
0.21176470588235294,
0.14901960784313725,
1.0),
'turquoise': ( 0.25098039215686274,
0.8784313725490196,
0.81568627450980391,
1.0),
'turquoise1': (0.0, 0.96078431372549022, 1.0, 1.0),
'turquoise2': (0.0, 0.89803921568627454, 0.93333333333333335, 1.0),
'turquoise3': (0.0, 0.77254901960784317, 0.80392156862745101, 1.0),
'turquoise4': (0.0, 0.52549019607843139, 0.54509803921568623, 1.0),
'violet': ( 0.93333333333333335,
0.50980392156862742,
0.93333333333333335,
1.0),
'violet red': ( 0.81568627450980391,
0.12549019607843137,
0.56470588235294117,
1.0),
'violetred': ( 0.81568627450980391,
0.12549019607843137,
0.56470588235294117,
1.0),
'violetred1': (1.0, 0.24313725490196078, 0.58823529411764708, 1.0),
'violetred2': ( 0.93333333333333335,
0.22745098039215686,
0.5490196078431373,
1.0),
'violetred3': ( 0.80392156862745101,
0.19607843137254902,
0.47058823529411764,
1.0),
'violetred4': ( 0.54509803921568623,
0.13333333333333333,
0.32156862745098042,
1.0),
'wheat': ( 0.96078431372549022,
0.87058823529411766,
0.70196078431372544,
1.0),
'wheat1': (1.0, 0.90588235294117647, 0.72941176470588232, 1.0),
'wheat2': ( 0.93333333333333335,
0.84705882352941175,
0.68235294117647061,
1.0),
'wheat3': ( 0.80392156862745101,
0.72941176470588232,
0.58823529411764708,
1.0),
'wheat4': ( 0.54509803921568623,
0.49411764705882355,
0.40000000000000002,
1.0),
'white': (1.0, 1.0, 1.0, 1.0),
'white smoke': ( 0.96078431372549022,
0.96078431372549022,
0.96078431372549022,
1.0),
'whitesmoke': ( 0.96078431372549022,
0.96078431372549022,
0.96078431372549022,
1.0),
'yellow': (1.0, 1.0, 0.0, 1.0),
'yellow green': ( 0.60392156862745094,
0.80392156862745101,
0.19607843137254902,
1.0),
'yellow1': (1.0, 1.0, 0.0, 1.0),
'yellow2': (0.93333333333333335, 0.93333333333333335, 0.0, 1.0),
'yellow3': (0.80392156862745101, 0.80392156862745101, 0.0, 1.0),
'yellow4': (0.54509803921568623, 0.54509803921568623, 0.0, 1.0),
'yellowgreen': ( 0.60392156862745094,
0.80392156862745101,
0.19607843137254902,
1.0)}
palettes = {
"gray": GradientPalette("black", "white"),
"red-blue": GradientPalette("red", "blue"),
"red-purple-blue": AdvancedGradientPalette(["red", "purple", "blue"]),
"red-green": GradientPalette("red", "green"),
"red-yellow-green": AdvancedGradientPalette(["red", "yellow", "green"]),
"red-black-green": AdvancedGradientPalette(["red", "black", "green"]),
"rainbow": RainbowPalette(),
"heat": AdvancedGradientPalette(["red", "yellow", "white"],
indices=[0, 192, 255]),
"terrain": AdvancedGradientPalette(["hsv(120, 100%, 65%)",
"hsv(60, 100%, 90%)", "hsv(0, 0%, 95%)"])
}
| gpl-2.0 |
ohspite/spectral | spectral/database/aster.py | 2 | 18692 | #########################################################################
#
# aster.py - This file is part of the Spectral Python (SPy) package.
#
# Copyright (C) 2010 Thomas Boggs
#
# Spectral Python 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.
#
# Spectral Python 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 software; if not, write to
#
# Free Software Foundation, Inc.
# 59 Temple Place, Suite 330
# Boston, MA 02111-1307
# USA
#
#########################################################################
#
# Send comments to:
# Thomas Boggs, tboggs@users.sourceforge.net
#
from __future__ import division, print_function, unicode_literals
from spectral.utilities.python23 import IS_PYTHON3
if IS_PYTHON3:
readline = lambda fin: fin.readline()
open_file = lambda filename: open(filename, encoding='iso-8859-1')
else:
readline = lambda fin: fin.readline().decode('iso-8859-1')
open_file = lambda filename: open(filename)
table_schemas = [
'CREATE TABLE Samples (SampleID INTEGER PRIMARY KEY, Name TEXT, Type TEXT, Class TEXT, SubClass TEXT, '
'ParticleSize TEXT, SampleNum TEXT, Owner TEXT, Origin TEXT, Phase TEXT, Description TEXT)',
'CREATE TABLE Spectra (SpectrumID INTEGER PRIMARY KEY, SampleID INTEGER, SensorCalibrationID INTEGER, '
'Instrument TEXT, Environment TEXT, Measurement TEXT, '
'XUnit TEXT, YUnit TEXT, MinWavelength FLOAT, MaxWavelength FLOAT, '
'NumValues INTEGER, XData BLOB, YData BLOB)',
]
arraytypecode = chr(ord('f'))
# These files contained malformed signature data and will be ignored.
bad_files = [
'jhu.nicolet.mineral.silicate.tectosilicate.fine.albite1.spectrum.txt',
'usgs.perknic.rock.igneous.mafic.colid.me3.spectrum.txt'
]
def read_pair(fin, num_lines=1):
'''Reads a colon-delimited attribute-value pair from the file stream.'''
s = ''
for i in range(num_lines):
s += " " + readline(fin).strip()
return [x.strip().lower() for x in s.split(':')]
class Signature:
'''Object to store sample/measurement metadata, as well as wavelength-signatrure vectors.'''
def __init__(self):
self.sample = {}
self.measurement = {}
def read_file(filename):
'''Reads an ASTER 2.x spectrum file.'''
fin = open_file(filename)
s = Signature()
# Number of lines per metadata attribute value
lpv = [1] * 8 + [2] + [6]
# A few files have an additional "Colleted by" sample metadata field, which
# sometimes affects the number of header lines
haveCollectedBy = False
for i in range(30):
line = readline(fin).strip()
if line.find('Collected by:') >= 0:
haveCollectedBy = True
collectedByLineNum = i
if line.startswith('Description:'):
descriptionLineNum = i
if line.startswith('Measurement:'):
measurementLineNum = i
if haveCollectedBy:
lpv = [1] * 10 + [measurementLineNum - descriptionLineNum]
# Read sample metadata
fin.seek(0)
for i in range(len(lpv)):
pair = read_pair(fin, lpv[i])
s.sample[pair[0].lower()] = pair[1]
# Read measurement metadata
lpv = [1] * 8 + [2]
for i in range(len(lpv)):
pair = read_pair(fin, lpv[i])
if len(pair) < 2:
print(pair)
s.measurement[pair[0].lower()] = pair[1]
# Read signature spectrum
pairs = []
for line in fin.readlines():
line = line.strip()
if len(line) == 0:
continue
pair = line.split()
nItems = len(pair)
# Try to handle invalid values on signature lines
if nItems == 1:
# print 'single item (%s) on signature line, %s' \
# % (pair[0], filename)
continue
elif nItems > 2:
print('more than 2 values on signature line,', filename)
continue
try:
x = float(pair[0])
except:
print('corrupt signature line,', filename)
if x == 0:
# print 'Zero wavelength value', filename
continue
elif x < 0:
print('Negative wavelength value,', filename)
continue
pairs.append(pair)
[x, y] = [list(v) for v in zip(*pairs)]
# Make sure wavelengths are ascending
if float(x[0]) > float(x[-1]):
x.reverse()
y.reverse()
s.x = [float(val) for val in x]
s.y = [float(val) for val in y]
s.measurement['first x value'] = x[0]
s.measurement['last x value'] = x[-1]
s.measurement['number of x values'] = len(x)
fin.close()
return s
class AsterDatabase:
schemas = table_schemas
def _add_sample(self, name, sampleType, sampleClass, subClass,
particleSize, sampleNumber, owner, origin, phase,
description):
sql = '''INSERT INTO Samples (Name, Type, Class, SubClass, ParticleSize, SampleNum, Owner, Origin, Phase, Description)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'''
self.cursor.execute(sql, (name, sampleType, sampleClass, subClass,
particleSize, sampleNumber, owner, origin,
phase, description))
rowId = self.cursor.lastrowid
self.db.commit()
return rowId
def _add_signature(
self, sampleID, calibrationID, instrument, environment, measurement,
xUnit, yUnit, minWavelength, maxWavelength, xData, yData):
import sqlite3
import array
sql = '''INSERT INTO Spectra (SampleID, SensorCalibrationID, Instrument,
Environment, Measurement, XUnit, YUnit, MinWavelength, MaxWavelength,
NumValues, XData, YData) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'''
xBlob = sqlite3.Binary(array.array(arraytypecode, xData).tostring())
yBlob = sqlite3.Binary(array.array(arraytypecode, yData).tostring())
numValues = len(xData)
self.cursor.execute(
sql, (
sampleID, calibrationID, instrument, environment, measurement,
xUnit, yUnit, minWavelength, maxWavelength, numValues, xBlob,
yBlob))
rowId = self.cursor.lastrowid
self.db.commit()
return rowId
@classmethod
def create(cls, filename, aster_data_dir=None):
'''Creates an ASTER relational database by parsing ASTER data files.
Arguments:
`filename` (str):
Name of the new sqlite database file to create.
`aster_data_dir` (str):
Path to the directory containing ASTER library data files. If
this argument is not provided, no data will be imported.
Returns:
An :class:`~spectral.database.AsterDatabase` object.
Example::
>>> AsterDatabase.create("aster_lib.db", "/CDROM/ASTER2.0/data")
This is a class method (it does not require instantiating an
AsterDatabase object) that creates a new database by parsing all of the
files in the ASTER library data directory. Normally, this should only
need to be called once. Subsequently, a corresponding database object
can be created by instantiating a new AsterDatabase object with the
path the database file as its argument. For example::
>>> from spectral.database.aster import AsterDatabase
>>> db = AsterDatabase("aster_lib.db")
'''
import os
if os.path.isfile(filename):
raise Exception('Error: Specified file already exists.')
db = AsterDatabase()
db._connect(filename)
for schema in cls.schemas:
db.cursor.execute(schema)
if aster_data_dir:
db._import_aster_files(aster_data_dir)
return db
def __init__(self, sqlite_filename=None):
'''Creates a database object to interface an existing database.
Arguments:
`sqlite_filename` (str):
Name of the database file. If this argument is not provided,
an interface to a database file will not be established.
Returns:
An :class:`~spectral.AsterDatabase` connected to the database.
'''
from spectral.io.spyfile import find_file_path
if sqlite_filename:
self._connect(find_file_path(sqlite_filename))
else:
self.db = None
self.cursor = None
def _import_aster_files(self, aster_data_dir):
'''Read each file in the ASTER library and convert to AVIRIS bands.'''
from glob import glob
import numpy
import os
if not os.path.isdir(aster_data_dir):
raise Exception('Error: Invalid directory name specified.')
filesToIgnore = [aster_data_dir + '/' + f for f in bad_files]
numFiles = 0
numIgnored = 0
sigID = 1
class Sig:
pass
sigs = []
for f in glob(aster_data_dir + '/*spectrum.txt'):
if f in filesToIgnore:
numIgnored += 1
continue
print(('Importing %s.' % f))
numFiles += 1
sig = read_file(f)
s = sig.sample
if s['particle size'].lower == 'liquid':
phase = 'liquid'
else:
phase = 'solid'
if 'sample no.' in s:
sampleNum = s['sample no.']
else:
sampleNum = ''
id = self._add_sample(
s['name'], s['type'], s['class'], s[
'subclass'], s['particle size'],
sampleNum, s['owner'], s['origin'], phase, s['description'])
instrument = os.path.basename(f).split('.')[1]
environment = 'lab'
m = sig.measurement
# Correct numerous mispellings of "reflectance" and "transmittance"
yUnit = m['y units']
if yUnit.find('reflectence') > -1:
yUnit = 'reflectance (percent)'
elif yUnit.find('trans') == 0:
yUnit = 'transmittance (percent)'
measurement = m['measurement']
if measurement[0] == 't':
measurement = 'transmittance'
self._add_signature(id, -1, instrument, environment, measurement,
m['x units'], yUnit, m['first x value'],
m['last x value'], sig.x, sig.y)
if numFiles == 0:
print('No ASTER data files were found in directory "%s".' \
% aster_data_dir)
else:
print('Processed %d files.' % numFiles)
if numIgnored > 0:
print('Ignored the following %d bad files:' % (numIgnored))
for f in filesToIgnore:
print('\t' + f)
return sigs
def _connect(self, sqlite_filename):
'''Establishes a connection to the Specbase sqlite database.'''
import sqlite3
self.db = sqlite3.connect(sqlite_filename)
self.cursor = self.db.cursor()
def get_spectrum(self, spectrumID):
'''Returns a spectrum from the database.
Usage:
(x, y) = aster.get_spectrum(spectrumID)
Arguments:
`spectrumID` (int):
The **SpectrumID** value for the desired spectrum from the
**Spectra** table in the database.
Returns:
`x` (list):
Band centers for the spectrum.
`y` (list):
Spectrum data values for each band.
Returns a pair of vectors containing the wavelengths and measured
values values of a measurment. For additional metadata, call
"get_signature" instead.
'''
import array
query = '''SELECT XData, YData FROM Spectra WHERE SpectrumID = ?'''
result = self.cursor.execute(query, (spectrumID,))
rows = result.fetchall()
if len(rows) < 1:
raise 'Measurement record not found'
x = array.array(arraytypecode)
x.fromstring(rows[0][0])
y = array.array(arraytypecode)
y.fromstring(rows[0][1])
return (list(x), list(y))
def get_signature(self, spectrumID):
'''Returns a spectrum with some additional metadata.
Usage::
sig = aster.get_signature(spectrumID)
Arguments:
`spectrumID` (int):
The **SpectrumID** value for the desired spectrum from the
**Spectra** table in the database.
Returns:
`sig` (:class:`~spectral.database.aster.Signature`):
An object with the following attributes:
============== ===== ========================================
Attribute Type Description
============== ===== ========================================
measurement_id int SpectrumID value from Spectra table
sample_name str **Sample** from the **Samples** table
sample_id int **SampleID** from the **Samples** table
x list list of band center wavelengths
y list list of spectrum values for each band
============== ===== ========================================
'''
import array
# Retrieve spectrum from Spectra table
query = '''SELECT Samples.Name, Samples.SampleID, XData, YData
FROM Samples, Spectra WHERE Samples.SampleID = Spectra.SampleID
AND Spectra.SpectrumID = ?'''
result = self.cursor.execute(query, (spectrumID,))
results = result.fetchall()
if len(results) < 1:
raise "Measurement record not found"
sig = Signature()
sig.measurement_id = spectrumID
sig.sample_name = results[0][0]
sig.sample_id = results[0][1]
x = array.array(arraytypecode)
x.fromstring(results[0][2])
sig.x = list(x)
y = array.array(arraytypecode)
y.fromstring(results[0][3])
sig.y = list(y)
return sig
def query(self, sql, args=None):
'''Returns the result of an arbitrary SQL statement.
Arguments:
`sql` (str):
An SQL statement to be passed to the database. Use "?" for
variables passed into the statement.
`args` (tuple):
Optional arguments which will replace the "?" placeholders in
the `sql` argument.
Returns:
An :class:`sqlite3.Cursor` object with the query results.
Example::
>>> sql = r'SELECT SpectrumID, Name FROM Samples, Spectra ' +
... 'WHERE Spectra.SampleID = Samples.SampleID ' +
... 'AND Name LIKE "%grass%" AND MinWavelength < ?'
>>> args = (0.5,)
>>> cur = db.query(sql, args)
>>> for row in cur:
... print row
...
(356, u'dry grass')
(357, u'grass')
'''
if args:
return self.cursor.execute(sql, args)
else:
return self.cursor.execute(sql)
def print_query(self, sql, args=None):
'''Prints the text result of an arbitrary SQL statement.
Arguments:
`sql` (str):
An SQL statement to be passed to the database. Use "?" for
variables passed into the statement.
`args` (tuple):
Optional arguments which will replace the "?" placeholders in
the `sql` argument.
This function performs the same query function as
:meth:`spectral.database.Asterdatabase.query` except query results are
printed to **stdout** instead of returning a cursor object.
Example:
>>> sql = r'SELECT SpectrumID, Name FROM Samples, Spectra ' +
... 'WHERE Spectra.SampleID = Samples.SampleID ' +
... 'AND Name LIKE "%grass%" AND MinWavelength < ?'
>>> args = (0.5,)
>>> db.print_query(sql, args)
356|dry grass
357|grass
'''
ret = self.query(sql, args)
for row in ret:
print("|".join([str(x) for x in row]))
def create_envi_spectral_library(self, spectrumIDs, bandInfo):
'''Creates an ENVI-formatted spectral library for a list of spectra.
Arguments:
`spectrumIDs` (list of ints):
List of **SpectrumID** values for of spectra in the "Spectra"
table of the ASTER database.
`bandInfo` (:class:`~spectral.BandInfo`):
The spectral bands to which the original ASTER library spectra
will be resampled.
Returns:
A :class:`~spectral.io.envi.SpectralLibrary` object.
The IDs passed to the method should correspond to the SpectrumID field
of the ASTER database "Spectra" table. All specified spectra will be
resampled to the same discretization specified by the bandInfo
parameter. See :class:`spectral.BandResampler` for details on the
resampling method used.
'''
from spectral.algorithms.resampling import BandResampler
from spectral.io.envi import SpectralLibrary
import numpy
spectra = numpy.empty((len(spectrumIDs), len(bandInfo.centers)))
names = []
for i in range(len(spectrumIDs)):
sig = self.get_signature(spectrumIDs[i])
resample = BandResampler(
sig.x, bandInfo.centers, None, bandInfo.bandwidths)
spectra[i] = resample(sig.y)
names.append(sig.sample_name)
header = {}
header['wavelength units'] = 'um'
header['spectra names'] = names
header['wavelength'] = bandInfo.centers
header['fwhm'] = bandInfo.bandwidths
return SpectralLibrary(spectra, header, {})
| gpl-2.0 |
18padx08/PPTex | PPTexEnv_x86_64/lib/python2.7/site-packages/matplotlib/backends/backend_macosx.py | 11 | 15754 | from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
import os
import numpy
from matplotlib._pylab_helpers import Gcf
from matplotlib.backend_bases import RendererBase, GraphicsContextBase,\
FigureManagerBase, FigureCanvasBase, NavigationToolbar2, TimerBase
from matplotlib.backend_bases import ShowBase
from matplotlib.cbook import maxdict
from matplotlib.figure import Figure
from matplotlib.path import Path
from matplotlib.mathtext import MathTextParser
from matplotlib.colors import colorConverter
from matplotlib import rcParams
from matplotlib.widgets import SubplotTool
import matplotlib
from matplotlib.backends import _macosx
class Show(ShowBase):
def mainloop(self):
_macosx.show()
show = Show()
class RendererMac(RendererBase):
"""
The renderer handles drawing/rendering operations. Most of the renderer's
methods forward the command to the renderer's graphics context. The
renderer does not wrap a C object and is written in pure Python.
"""
texd = maxdict(50) # a cache of tex image rasters
def __init__(self, dpi, width, height):
RendererBase.__init__(self)
self.dpi = dpi
self.width = width
self.height = height
self.gc = GraphicsContextMac()
self.gc.set_dpi(self.dpi)
self.mathtext_parser = MathTextParser('MacOSX')
def set_width_height (self, width, height):
self.width, self.height = width, height
def draw_path(self, gc, path, transform, rgbFace=None):
if rgbFace is not None:
rgbFace = tuple(rgbFace)
linewidth = gc.get_linewidth()
gc.draw_path(path, transform, linewidth, rgbFace)
def draw_markers(self, gc, marker_path, marker_trans, path, trans, rgbFace=None):
if rgbFace is not None:
rgbFace = tuple(rgbFace)
linewidth = gc.get_linewidth()
gc.draw_markers(marker_path, marker_trans, path, trans, linewidth, rgbFace)
def draw_path_collection(self, gc, master_transform, paths, all_transforms,
offsets, offsetTrans, facecolors, edgecolors,
linewidths, linestyles, antialiaseds, urls,
offset_position):
if offset_position=='data':
offset_position = True
else:
offset_position = False
path_ids = []
for path, transform in self._iter_collection_raw_paths(
master_transform, paths, all_transforms):
path_ids.append((path, transform))
master_transform = master_transform.get_matrix()
offsetTrans = offsetTrans.get_matrix()
gc.draw_path_collection(master_transform, path_ids, all_transforms,
offsets, offsetTrans, facecolors, edgecolors,
linewidths, linestyles, antialiaseds,
offset_position)
def draw_quad_mesh(self, gc, master_transform, meshWidth, meshHeight,
coordinates, offsets, offsetTrans, facecolors,
antialiased, edgecolors):
gc.draw_quad_mesh(master_transform.get_matrix(),
meshWidth,
meshHeight,
coordinates,
offsets,
offsetTrans.get_matrix(),
facecolors,
antialiased,
edgecolors)
def new_gc(self):
self.gc.save()
self.gc.set_hatch(None)
self.gc._alpha = 1.0
self.gc._forced_alpha = False # if True, _alpha overrides A from RGBA
return self.gc
def draw_gouraud_triangle(self, gc, points, colors, transform):
points = transform.transform(points)
gc.draw_gouraud_triangle(points, colors)
def get_image_magnification(self):
return self.gc.get_image_magnification()
def draw_image(self, gc, x, y, im):
im.flipud_out()
nrows, ncols, data = im.as_rgba_str()
gc.draw_image(x, y, nrows, ncols, data)
im.flipud_out()
def draw_tex(self, gc, x, y, s, prop, angle, ismath='TeX!', mtext=None):
# todo, handle props, angle, origins
scale = self.gc.get_image_magnification()
size = prop.get_size_in_points()
texmanager = self.get_texmanager()
key = s, size, self.dpi, angle, texmanager.get_font_config()
im = self.texd.get(key) # Not sure what this does; just copied from backend_agg.py
if im is None:
Z = texmanager.get_grey(s, size, self.dpi*scale)
Z = numpy.array(255.0 - Z * 255.0, numpy.uint8)
gc.draw_mathtext(x, y, angle, Z)
def _draw_mathtext(self, gc, x, y, s, prop, angle):
scale = self.gc.get_image_magnification()
ox, oy, width, height, descent, image, used_characters = \
self.mathtext_parser.parse(s, self.dpi*scale, prop)
gc.draw_mathtext(x, y, angle, 255 - image.as_array())
def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
if ismath:
self._draw_mathtext(gc, x, y, s, prop, angle)
else:
family = prop.get_family()
weight = prop.get_weight()
style = prop.get_style()
points = prop.get_size_in_points()
size = self.points_to_pixels(points)
gc.draw_text(x, y, six.text_type(s), family, size, weight, style, angle)
def get_text_width_height_descent(self, s, prop, ismath):
if ismath=='TeX':
# todo: handle props
texmanager = self.get_texmanager()
fontsize = prop.get_size_in_points()
w, h, d = texmanager.get_text_width_height_descent(s, fontsize,
renderer=self)
return w, h, d
if ismath:
ox, oy, width, height, descent, fonts, used_characters = \
self.mathtext_parser.parse(s, self.dpi, prop)
return width, height, descent
family = prop.get_family()
weight = prop.get_weight()
style = prop.get_style()
points = prop.get_size_in_points()
size = self.points_to_pixels(points)
width, height, descent = self.gc.get_text_width_height_descent(
six.text_type(s), family, size, weight, style)
return width, height, 0.0*descent
def flipy(self):
return False
def points_to_pixels(self, points):
return points/72.0 * self.dpi
def option_image_nocomposite(self):
return True
class GraphicsContextMac(_macosx.GraphicsContext, GraphicsContextBase):
"""
The GraphicsContext wraps a Quartz graphics context. All methods
are implemented at the C-level in macosx.GraphicsContext. These
methods set drawing properties such as the line style, fill color,
etc. The actual drawing is done by the Renderer, which draws into
the GraphicsContext.
"""
def __init__(self):
GraphicsContextBase.__init__(self)
_macosx.GraphicsContext.__init__(self)
def set_alpha(self, alpha):
GraphicsContextBase.set_alpha(self, alpha)
_alpha = self.get_alpha()
_macosx.GraphicsContext.set_alpha(self, _alpha, self.get_forced_alpha())
rgb = self.get_rgb()
_macosx.GraphicsContext.set_foreground(self, rgb)
def set_foreground(self, fg, isRGBA=False):
GraphicsContextBase.set_foreground(self, fg, isRGBA)
rgb = self.get_rgb()
_macosx.GraphicsContext.set_foreground(self, rgb)
def set_graylevel(self, fg):
GraphicsContextBase.set_graylevel(self, fg)
_macosx.GraphicsContext.set_graylevel(self, fg)
def set_clip_rectangle(self, box):
GraphicsContextBase.set_clip_rectangle(self, box)
if not box: return
_macosx.GraphicsContext.set_clip_rectangle(self, box.bounds)
def set_clip_path(self, path):
GraphicsContextBase.set_clip_path(self, path)
if not path: return
path = path.get_fully_transformed_path()
_macosx.GraphicsContext.set_clip_path(self, path)
########################################################################
#
# The following functions and classes are for pylab and implement
# window/figure managers, etc...
#
########################################################################
def draw_if_interactive():
"""
For performance reasons, we don't want to redraw the figure after
each draw command. Instead, we mark the figure as invalid, so that
it will be redrawn as soon as the event loop resumes via PyOS_InputHook.
This function should be called after each draw event, even if
matplotlib is not running interactively.
"""
if matplotlib.is_interactive():
figManager = Gcf.get_active()
if figManager is not None:
figManager.canvas.invalidate()
def new_figure_manager(num, *args, **kwargs):
"""
Create a new figure manager instance
"""
FigureClass = kwargs.pop('FigureClass', Figure)
figure = FigureClass(*args, **kwargs)
return new_figure_manager_given_figure(num, figure)
def new_figure_manager_given_figure(num, figure):
"""
Create a new figure manager instance for the given figure.
"""
canvas = FigureCanvasMac(figure)
manager = FigureManagerMac(canvas, num)
return manager
class TimerMac(_macosx.Timer, TimerBase):
'''
Subclass of :class:`backend_bases.TimerBase` that uses CoreFoundation
run loops for timer events.
Attributes:
* interval: The time between timer events in milliseconds. Default
is 1000 ms.
* single_shot: Boolean flag indicating whether this timer should
operate as single shot (run once and then stop). Defaults to False.
* callbacks: Stores list of (func, args) tuples that will be called
upon timer events. This list can be manipulated directly, or the
functions add_callback and remove_callback can be used.
'''
# completely implemented at the C-level (in _macosx.Timer)
class FigureCanvasMac(_macosx.FigureCanvas, FigureCanvasBase):
"""
The canvas the figure renders into. Calls the draw and print fig
methods, creates the renderers, etc...
Public attribute
figure - A Figure instance
Events such as button presses, mouse movements, and key presses
are handled in the C code and the base class methods
button_press_event, button_release_event, motion_notify_event,
key_press_event, and key_release_event are called from there.
"""
filetypes = FigureCanvasBase.filetypes.copy()
filetypes['bmp'] = 'Windows bitmap'
filetypes['jpeg'] = 'JPEG'
filetypes['jpg'] = 'JPEG'
filetypes['gif'] = 'Graphics Interchange Format'
filetypes['tif'] = 'Tagged Image Format File'
filetypes['tiff'] = 'Tagged Image Format File'
def __init__(self, figure):
FigureCanvasBase.__init__(self, figure)
width, height = self.get_width_height()
self.renderer = RendererMac(figure.dpi, width, height)
_macosx.FigureCanvas.__init__(self, width, height)
def resize(self, width, height):
self.renderer.set_width_height(width, height)
dpi = self.figure.dpi
width /= dpi
height /= dpi
self.figure.set_size_inches(width, height)
def _print_bitmap(self, filename, *args, **kwargs):
# In backend_bases.py, print_figure changes the dpi of the figure.
# But since we are essentially redrawing the picture, we need the
# original dpi. Pick it up from the renderer.
dpi = kwargs['dpi']
old_dpi = self.figure.dpi
self.figure.dpi = self.renderer.dpi
width, height = self.figure.get_size_inches()
width, height = width*dpi, height*dpi
filename = six.text_type(filename)
self.write_bitmap(filename, width, height, dpi)
self.figure.dpi = old_dpi
def print_bmp(self, filename, *args, **kwargs):
self._print_bitmap(filename, *args, **kwargs)
def print_jpg(self, filename, *args, **kwargs):
self._print_bitmap(filename, *args, **kwargs)
def print_jpeg(self, filename, *args, **kwargs):
self._print_bitmap(filename, *args, **kwargs)
def print_tif(self, filename, *args, **kwargs):
self._print_bitmap(filename, *args, **kwargs)
def print_tiff(self, filename, *args, **kwargs):
self._print_bitmap(filename, *args, **kwargs)
def print_gif(self, filename, *args, **kwargs):
self._print_bitmap(filename, *args, **kwargs)
def new_timer(self, *args, **kwargs):
"""
Creates a new backend-specific subclass of :class:`backend_bases.Timer`.
This is useful for getting periodic events through the backend's native
event loop. Implemented only for backends with GUIs.
optional arguments:
*interval*
Timer interval in milliseconds
*callbacks*
Sequence of (func, args, kwargs) where func(*args, **kwargs) will
be executed by the timer every *interval*.
"""
return TimerMac(*args, **kwargs)
class FigureManagerMac(_macosx.FigureManager, FigureManagerBase):
"""
Wrap everything up into a window for the pylab interface
"""
def __init__(self, canvas, num):
FigureManagerBase.__init__(self, canvas, num)
title = "Figure %d" % num
_macosx.FigureManager.__init__(self, canvas, title)
if rcParams['toolbar']=='toolbar2':
self.toolbar = NavigationToolbar2Mac(canvas)
else:
self.toolbar = None
if self.toolbar is not None:
self.toolbar.update()
def notify_axes_change(fig):
'this will be called whenever the current axes is changed'
if self.toolbar != None: self.toolbar.update()
self.canvas.figure.add_axobserver(notify_axes_change)
if matplotlib.is_interactive():
self.show()
def close(self):
Gcf.destroy(self.num)
class NavigationToolbar2Mac(_macosx.NavigationToolbar2, NavigationToolbar2):
def __init__(self, canvas):
NavigationToolbar2.__init__(self, canvas)
def _init_toolbar(self):
basedir = os.path.join(rcParams['datapath'], "images")
_macosx.NavigationToolbar2.__init__(self, basedir)
def draw_rubberband(self, event, x0, y0, x1, y1):
self.canvas.set_rubberband(int(x0), int(y0), int(x1), int(y1))
def release(self, event):
self.canvas.remove_rubberband()
def set_cursor(self, cursor):
_macosx.set_cursor(cursor)
def save_figure(self, *args):
filename = _macosx.choose_save_file('Save the figure',
self.canvas.get_default_filename())
if filename is None: # Cancel
return
self.canvas.print_figure(filename)
def prepare_configure_subplots(self):
toolfig = Figure(figsize=(6,3))
canvas = FigureCanvasMac(toolfig)
toolfig.subplots_adjust(top=0.9)
tool = SubplotTool(self.canvas.figure, toolfig)
return canvas
def set_message(self, message):
_macosx.NavigationToolbar2.set_message(self, message.encode('utf-8'))
def dynamic_update(self):
self.canvas.draw_idle()
########################################################################
#
# Now just provide the standard names that backend.__init__ is expecting
#
########################################################################
FigureCanvas = FigureCanvasMac
FigureManager = FigureManagerMac
| mit |
sq5bpf/osmo-tetra-sq5bpf | src/demod/python/tetra-demod.py | 9 | 2701 | #!/usr/bin/env python
import sys
import math
from gnuradio import gr, gru, audio, eng_notation, blks2, optfir
from gnuradio.eng_option import eng_option
from optparse import OptionParser
# Load it locally or from the module
try:
import cqpsk
except:
from tetra_demod import cqpsk
# accepts an input file in complex format
# applies frequency translation, resampling (interpolation/decimation)
class my_top_block(gr.top_block):
def __init__(self):
gr.top_block.__init__(self)
parser = OptionParser(option_class=eng_option)
parser.add_option("-c", "--calibration", type="eng_float", default=0, help="freq offset")
parser.add_option("-i", "--input-file", type="string", default="in.dat", help="specify the input file")
parser.add_option("-l", "--log", action="store_true", default=False, help="dump debug .dat files")
parser.add_option("-L", "--low-pass", type="eng_float", default=25e3, help="low pass cut-off", metavar="Hz")
parser.add_option("-o", "--output-file", type="string", default="out.dat", help="specify the output file")
parser.add_option("-s", "--sample-rate", type="int", default=100000000/512, help="input sample rate")
parser.add_option("-v", "--verbose", action="store_true", default=False, help="dump demodulation data")
(options, args) = parser.parse_args()
sample_rate = options.sample_rate
symbol_rate = 18000
sps = 2
# output rate will be 36,000
ntaps = 11 * sps
new_sample_rate = symbol_rate * sps
channel_taps = gr.firdes.low_pass(1.0, sample_rate, options.low_pass, options.low_pass * 0.1, gr.firdes.WIN_HANN)
FILTER = gr.freq_xlating_fir_filter_ccf(1, channel_taps, options.calibration, sample_rate)
sys.stderr.write("sample rate: %d\n" %(sample_rate))
IN = gr.file_source(gr.sizeof_gr_complex, options.input_file)
DEMOD = cqpsk.cqpsk_demod( samples_per_symbol = sps,
excess_bw=0.35,
costas_alpha=0.03,
gain_mu=0.05,
mu=0.05,
omega_relative_limit=0.05,
log=options.log,
verbose=options.verbose)
OUT = gr.file_sink(gr.sizeof_float, options.output_file)
r = float(sample_rate) / float(new_sample_rate)
INTERPOLATOR = gr.fractional_interpolator_cc(0, r)
self.connect(IN, FILTER, INTERPOLATOR, DEMOD, OUT)
if __name__ == "__main__":
try:
my_top_block().run()
except KeyboardInterrupt:
tb.stop()
| agpl-3.0 |
miguelparaiso/OdooAccessible | addons/share/res_users.py | 269 | 3038 | # -*- 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/>.
#
##############################################################################
from openerp.osv import fields, osv
from openerp import SUPERUSER_ID
class res_users(osv.osv):
_name = 'res.users'
_inherit = 'res.users'
def _is_share(self, cr, uid, ids, name, args, context=None):
res = {}
for user in self.browse(cr, uid, ids, context=context):
res[user.id] = not self.has_group(cr, user.id, 'base.group_user')
return res
def _get_users_from_group(self, cr, uid, ids, context=None):
result = set()
groups = self.pool['res.groups'].browse(cr, uid, ids, context=context)
# Clear cache to avoid perf degradation on databases with thousands of users
groups.invalidate_cache()
for group in groups:
result.update(user.id for user in group.users)
return list(result)
_columns = {
'share': fields.function(_is_share, string='Share User', type='boolean',
store={
'res.users': (lambda self, cr, uid, ids, c={}: ids, None, 50),
'res.groups': (_get_users_from_group, None, 50),
}, help="External user with limited access, created only for the purpose of sharing data."),
}
class res_groups(osv.osv):
_name = "res.groups"
_inherit = 'res.groups'
_columns = {
'share': fields.boolean('Share Group', readonly=True,
help="Group created to set access rights for sharing data with some users.")
}
def init(self, cr):
# force re-generation of the user groups view without the shared groups
self.update_user_groups_view(cr, SUPERUSER_ID)
parent_class = super(res_groups, self)
if hasattr(parent_class, 'init'):
parent_class.init(cr)
def get_application_groups(self, cr, uid, domain=None, context=None):
if domain is None:
domain = []
domain.append(('share', '=', False))
return super(res_groups, self).get_application_groups(cr, uid, domain=domain, context=context)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
kwilliams-mo/iris | lib/iris/experimental/regrid.py | 1 | 40106 | # (C) British Crown Copyright 2013, Met Office
#
# This file is part of Iris.
#
# Iris 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 3 of the License, or
# (at your option) any later version.
#
# Iris 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 Iris. If not, see <http://www.gnu.org/licenses/>.
"""
Regridding functions.
"""
import collections
import copy
import warnings
import numpy as np
import numpy.ma as ma
import iris.analysis.cartography
import iris.coords
import iris.coord_systems
import iris.cube
import iris.unit
def _get_xy_dim_coords(cube):
"""
Return the x and y dimension coordinates from a cube.
This function raises a ValueError if the cube does not contain one and
only one set of x and y dimension coordinates. It also raises a ValueError
if the identified x and y coordinates do not have coordinate systems that
are equal.
Args:
* cube:
An instance of :class:`iris.cube.Cube`.
Returns:
A tuple containing the cube's x and y dimension coordinates.
"""
x_coords = cube.coords(axis='x', dim_coords=True)
if len(x_coords) != 1:
raise ValueError('Cube {!r} must contain a single 1D x '
'coordinate.'.format(cube.name()))
x_coord = x_coords[0]
y_coords = cube.coords(axis='y', dim_coords=True)
if len(y_coords) != 1:
raise ValueError('Cube {!r} must contain a single 1D y '
'coordinate.'.format(cube.name()))
y_coord = y_coords[0]
if x_coord.coord_system != y_coord.coord_system:
raise ValueError("The cube's x ({!r}) and y ({!r}) "
"coordinates must have the same coordinate "
"system.".format(x_coord.name(), y_coord.name()))
return x_coord, y_coord
def _get_xy_coords(cube):
"""
Return the x and y coordinates from a cube.
This function will preferentially return a pair of dimension
coordinates (if there are more than one potential x or y dimension
coordinates a ValueError will be raised). If the cube does not have
a pair of x and y dimension coordinates it will return 1D auxiliary
coordinates (including scalars). If there is not one and only one set
of x and y auxiliary coordinates a ValueError will be raised.
Having identified the x and y coordinates, the function checks that they
have equal coordinate systems and that they do not occupy the same
dimension on the cube.
Args:
* cube:
An instance of :class:`iris.cube.Cube`.
Returns:
A tuple containing the cube's x and y coordinates.
"""
# Look for a suitable dimension coords first.
x_coords = cube.coords(axis='x', dim_coords=True)
if not x_coords:
# If there is no x coord in dim_coords look for scalars or
# monotonic coords in aux_coords.
x_coords = [coord for coord in cube.coords(axis='x', dim_coords=False)
if coord.ndim == 1 and coord.is_monotonic()]
if len(x_coords) != 1:
raise ValueError('Cube {!r} must contain a single 1D x '
'coordinate.'.format(cube.name()))
x_coord = x_coords[0]
# Look for a suitable dimension coords first.
y_coords = cube.coords(axis='y', dim_coords=True)
if not y_coords:
# If there is no y coord in dim_coords look for scalars or
# monotonic coords in aux_coords.
y_coords = [coord for coord in cube.coords(axis='y', dim_coords=False)
if coord.ndim == 1 and coord.is_monotonic()]
if len(y_coords) != 1:
raise ValueError('Cube {!r} must contain a single 1D y '
'coordinate.'.format(cube.name()))
y_coord = y_coords[0]
if x_coord.coord_system != y_coord.coord_system:
raise ValueError("The cube's x ({!r}) and y ({!r}) "
"coordinates must have the same coordinate "
"system.".format(x_coord.name(), y_coord.name()))
# The x and y coordinates must describe different dimensions
# or be scalar coords.
x_dims = cube.coord_dims(x_coord)
x_dim = None
if x_dims:
x_dim = x_dims[0]
y_dims = cube.coord_dims(y_coord)
y_dim = None
if y_dims:
y_dim = y_dims[0]
if x_dim is not None and y_dim == x_dim:
raise ValueError("The cube's x and y coords must not describe the "
"same data dimension.")
return x_coord, y_coord
def _sample_grid(src_coord_system, grid_x_coord, grid_y_coord):
"""
Convert the rectilinear grid coordinates to a curvilinear grid in
the source coordinate system.
The `grid_x_coord` and `grid_y_coord` must share a common coordinate
system.
Args:
* src_coord_system:
The :class:`iris.coord_system.CoordSystem` for the grid of the
source Cube.
* grid_x_coord:
The :class:`iris.coords.DimCoord` for the X coordinate.
* grid_y_coord:
The :class:`iris.coords.DimCoord` for the Y coordinate.
Returns:
A tuple of the X and Y coordinate values as 2-dimensional
arrays.
"""
src_crs = src_coord_system.as_cartopy_crs()
grid_crs = grid_x_coord.coord_system.as_cartopy_crs()
grid_x, grid_y = np.meshgrid(grid_x_coord.points, grid_y_coord.points)
# Skip the CRS transform if we can to avoid precision problems.
if src_crs == grid_crs:
sample_grid_x = grid_x
sample_grid_y = grid_y
else:
sample_xyz = src_crs.transform_points(grid_crs, grid_x, grid_y)
sample_grid_x = sample_xyz[..., 0]
sample_grid_y = sample_xyz[..., 1]
return sample_grid_x, sample_grid_y
def _regrid_bilinear_array(src_data, x_dim, y_dim, src_x_coord, src_y_coord,
sample_grid_x, sample_grid_y):
"""
Regrid the given data from the src grid to the sample grid.
Args:
* src_data:
An N-dimensional NumPy array.
* x_dim:
The X dimension within `src_data`.
* y_dim:
The Y dimension within `src_data`.
* src_x_coord:
The X :class:`iris.coords.DimCoord`.
* src_y_coord:
The Y :class:`iris.coords.DimCoord`.
* sample_grid_x:
A 2-dimensional array of sample X values.
* sample_grid_y:
A 2-dimensional array of sample Y values.
Returns:
The regridded data as an N-dimensional NumPy array. The lengths
of the X and Y dimensions will now match those of the sample
grid.
"""
if sample_grid_x.shape != sample_grid_y.shape:
raise ValueError('Inconsistent sample grid shapes.')
if sample_grid_x.ndim != 2:
raise ValueError('Sample grid must be 2-dimensional.')
# Prepare the result data array
shape = list(src_data.shape)
shape[y_dim] = sample_grid_x.shape[0]
shape[x_dim] = sample_grid_x.shape[1]
# If we're given integer values, convert them to the smallest
# possible float dtype that can accurately preserve the values.
dtype = src_data.dtype
if dtype.kind == 'i':
dtype = np.promote_types(dtype, np.float16)
data = np.empty(shape, dtype=dtype)
# TODO: Replace ... see later comment.
# A crummy, temporary hack using iris.analysis.interpolate.linear()
# The faults include, but are not limited to:
# 1) It uses a nested `for` loop.
# 2) It is doing lots of unncessary metadata faffing.
# 3) It ends up performing two linear interpolations for each
# column of results, and the first linear interpolation does a lot
# more work than we'd ideally do, as most of the interpolated data
# is irrelevant to the second interpolation.
src = iris.cube.Cube(src_data)
src.add_dim_coord(src_x_coord, x_dim)
src.add_dim_coord(src_y_coord, y_dim)
indices = [slice(None)] * data.ndim
linear = iris.analysis.interpolate.linear
for yx_index in np.ndindex(sample_grid_x.shape):
x = sample_grid_x[yx_index]
y = sample_grid_y[yx_index]
column_pos = [(src_x_coord, x), (src_y_coord, y)]
column_data = linear(src, column_pos, 'nan').data
indices[y_dim] = yx_index[0]
indices[x_dim] = yx_index[1]
data[tuple(indices)] = column_data
# TODO:
# Altenative:
# Locate the four pairs of src x and y indices relevant to each grid
# location:
# => x_indices.shape == (4, ny, nx); y_indices.shape == (4, ny, nx)
# Calculate the relative weight of each corner:
# => weights.shape == (4, ny, nx)
# Extract the src data relevant to the grid locations:
# => raw_data = src.data[..., y_indices, x_indices]
# NB. Can't rely on this index order in general.
# => raw_data.shape == (..., 4, ny, nx)
# Weight it:
# => Reshape `weights` to broadcast against `raw_data`.
# => weighted_data = raw_data * weights
# => weighted_data.shape == (..., 4, ny, nx)
# Sum over the `4` dimension:
# => data = weighted_data.sum(axis=sample_axis)
# => data.shape == (..., ny, nx)
# Should be able to re-use the weights to calculate the interpolated
# values for auxiliary coordinates as well.
return data
def _regrid_reference_surface(src_surface_coord, surface_dims, x_dim, y_dim,
src_x_coord, src_y_coord,
sample_grid_x, sample_grid_y, regrid_callback):
"""
Return a new reference surface coordinate appropriate to the sample
grid.
Args:
* src_surface_coord:
The :class:`iris.coords.Coord` containing the source reference
surface.
* surface_dims:
The tuple of the data dimensions relevant to the source
reference surface coordinate.
* x_dim:
The X dimension within the source Cube.
* y_dim:
The Y dimension within the source Cube.
* src_x_coord:
The X :class:`iris.coords.DimCoord`.
* src_y_coord:
The Y :class:`iris.coords.DimCoord`.
* sample_grid_x:
A 2-dimensional array of sample X values.
* sample_grid_y:
A 2-dimensional array of sample Y values.
* regrid_callback:
The routine that will be used to calculate the interpolated
values for the new reference surface.
Returns:
The new reference surface coordinate.
"""
# Determine which of the reference surface's dimensions span the X
# and Y dimensions of the source cube.
surface_x_dim = surface_dims.index(x_dim)
surface_y_dim = surface_dims.index(y_dim)
surface = regrid_callback(src_surface_coord.points,
surface_x_dim, surface_y_dim,
src_x_coord, src_y_coord,
sample_grid_x, sample_grid_y)
surface_coord = src_surface_coord.copy(surface)
return surface_coord
def _create_cube(data, src, x_dim, y_dim, src_x_coord, src_y_coord,
grid_x_coord, grid_y_coord, sample_grid_x, sample_grid_y,
regrid_callback):
"""
Return a new Cube for the result of regridding the source Cube onto
the new grid.
All the metadata and coordinates of the result Cube are copied from
the source Cube, with two exceptions:
- Grid dimension coordinates are copied from the grid Cube.
- Auxiliary coordinates which span the grid dimensions are
ignored, except where they provide a reference surface for an
:class:`iris.aux_factory.AuxCoordFactory`.
Args:
* data:
The regridded data as an N-dimensional NumPy array.
* src:
The source Cube.
* x_dim:
The X dimension within the source Cube.
* y_dim:
The Y dimension within the source Cube.
* src_x_coord:
The X :class:`iris.coords.DimCoord`.
* src_y_coord:
The Y :class:`iris.coords.DimCoord`.
* grid_x_coord:
The :class:`iris.coords.DimCoord` for the new grid's X
coordinate.
* grid_y_coord:
The :class:`iris.coords.DimCoord` for the new grid's Y
coordinate.
* sample_grid_x:
A 2-dimensional array of sample X values.
* sample_grid_y:
A 2-dimensional array of sample Y values.
* regrid_callback:
The routine that will be used to calculate the interpolated
values of any reference surfaces.
Returns:
The new, regridded Cube.
"""
# Create a result cube with the appropriate metadata
result = iris.cube.Cube(data)
result.metadata = copy.deepcopy(src.metadata)
# Copy across all the coordinates which don't span the grid.
# Record a mapping from old coordinate IDs to new coordinates,
# for subsequent use in creating updated aux_factories.
coord_mapping = {}
def copy_coords(src_coords, add_method):
for coord in src_coords:
dims = src.coord_dims(coord)
if coord is src_x_coord:
coord = grid_x_coord
elif coord is src_y_coord:
coord = grid_y_coord
elif x_dim in dims or y_dim in dims:
continue
result_coord = coord.copy()
add_method(result_coord, dims)
coord_mapping[id(coord)] = result_coord
copy_coords(src.dim_coords, result.add_dim_coord)
copy_coords(src.aux_coords, result.add_aux_coord)
# Copy across any AuxFactory instances, and regrid their reference
# surfaces where required.
for factory in src.aux_factories:
for coord in factory.dependencies.itervalues():
if coord is None:
continue
dims = src.coord_dims(coord)
if x_dim in dims and y_dim in dims:
result_coord = _regrid_reference_surface(
coord, dims, x_dim, y_dim, src_x_coord, src_y_coord,
sample_grid_x, sample_grid_y, regrid_callback)
result.add_aux_coord(result_coord, dims)
coord_mapping[id(coord)] = result_coord
try:
result.add_aux_factory(factory.updated(coord_mapping))
except KeyError:
msg = 'Cannot update aux_factory {!r} because of dropped' \
' coordinates.'.format(factory.name())
warnings.warn(msg)
return result
def regrid_bilinear_rectilinear_src_and_grid(src, grid):
"""
Return a new Cube that is the result of regridding the source Cube
onto the grid of the grid Cube using bilinear interpolation.
Both the source and grid Cubes must be defined on rectilinear grids.
Auxiliary coordinates which span the grid dimensions are ignored,
except where they provide a reference surface for an
:class:`iris.aux_factory.AuxCoordFactory`.
Args:
* src:
The source :class:`iris.cube.Cube` providing the data.
* grid:
The :class:`iris.cube.Cube` which defines the new grid.
Returns:
The :class:`iris.cube.Cube` resulting from regridding the source
data onto the grid defined by the grid Cube.
"""
# Validity checks
if not isinstance(src, iris.cube.Cube):
raise TypeError("'src' must be a Cube")
if not isinstance(grid, iris.cube.Cube):
raise TypeError("'grid' must be a Cube")
src_x_coord, src_y_coord = _get_xy_dim_coords(src)
grid_x_coord, grid_y_coord = _get_xy_dim_coords(grid)
src_cs = src_x_coord.coord_system
grid_cs = grid_x_coord.coord_system
if src_cs is None or grid_cs is None:
raise ValueError("Both 'src' and 'grid' Cubes must have a"
" coordinate system for their rectilinear grid"
" coordinates.")
def _valid_units(coord):
if isinstance(coord.coord_system, (iris.coord_systems.GeogCS,
iris.coord_systems.RotatedGeogCS)):
valid_units = 'degrees'
else:
valid_units = 'm'
return coord.units == valid_units
if not all(_valid_units(coord) for coord in (src_x_coord, src_y_coord,
grid_x_coord, grid_y_coord)):
raise ValueError("Unsupported units: must be 'degrees' or 'm'.")
# Convert the grid to a 2D sample grid in the src CRS.
sample_grid_x, sample_grid_y = _sample_grid(src_cs,
grid_x_coord, grid_y_coord)
# Compute the interpolated data values.
x_dim = src.coord_dims(src_x_coord)[0]
y_dim = src.coord_dims(src_y_coord)[0]
src_data = src.data
fill_value = None
if np.ma.isMaskedArray(src_data):
# Since we're using iris.analysis.interpolate.linear which
# doesn't respect the mask, we replace masked values with NaN.
fill_value = src_data.fill_value
src_data = src_data.filled(np.nan)
data = _regrid_bilinear_array(src_data, x_dim, y_dim,
src_x_coord, src_y_coord,
sample_grid_x, sample_grid_y)
# Convert NaN based results to masked array where appropriate.
mask = np.isnan(data)
if np.any(mask):
data = np.ma.MaskedArray(data, mask, fill_value=fill_value)
# Wrap up the data as a Cube.
result = _create_cube(data, src, x_dim, y_dim, src_x_coord, src_y_coord,
grid_x_coord, grid_y_coord,
sample_grid_x, sample_grid_y,
_regrid_bilinear_array)
return result
def _within_bounds(bounds, lower, upper):
"""
Return whether both lower and upper lie within the extremes
of bounds.
"""
min_bound = np.min(bounds)
max_bound = np.max(bounds)
return (min_bound <= lower <= max_bound) and \
(min_bound <= upper <= max_bound)
def _cropped_bounds(bounds, lower, upper):
"""
Return a new bounds array and corresponding slice object (or indices)
that result from cropping the provided bounds between the specified lower
and upper values. The bounds at the extremities will be truncated so that
they start and end with lower and upper.
This function will return an empty NumPy array and slice if there is no
overlap between the region covered by bounds and the region from lower to
upper.
If lower > upper the resulting bounds may not be contiguous and the
indices object will be a tuple of indices rather than a slice object.
Args:
* bounds:
An (n, 2) shaped array of monotonic contiguous bounds.
* lower:
Lower bound at which to crop the bounds array.
* upper:
Upper bound at which to crop the bounds array.
Returns:
A tuple of the new bounds array and the corresponding slice object or
indices from the zeroth axis of the original array.
"""
reversed_flag = False
# Ensure order is increasing.
if bounds[0, 0] > bounds[-1, 0]:
# Reverse bounds
bounds = bounds[::-1, ::-1]
reversed_flag = True
# Number of bounds.
n = bounds.shape[0]
if lower <= upper:
if lower > bounds[-1, 1] or upper < bounds[0, 0]:
new_bounds = bounds[0:0]
indices = slice(0, 0)
else:
# A single region lower->upper.
if lower < bounds[0, 0]:
# Region extends below bounds so use first lower bound.
l = 0
lower = bounds[0, 0]
else:
# Index of last lower bound less than or equal to lower.
l = np.nonzero(bounds[:, 0] <= lower)[0][-1]
if upper > bounds[-1, 1]:
# Region extends above bounds so use last upper bound.
u = n - 1
upper = bounds[-1, 1]
else:
# Index of first upper bound greater than or equal to
# upper.
u = np.nonzero(bounds[:, 1] >= upper)[0][0]
# Extract the bounds in our region defined by lower->upper.
new_bounds = np.copy(bounds[l:(u + 1), :])
# Replace first and last values with specified bounds.
new_bounds[0, 0] = lower
new_bounds[-1, 1] = upper
if reversed_flag:
indices = slice(n - (u + 1), n - l)
else:
indices = slice(l, u + 1)
else:
# Two regions [0]->upper, lower->[-1]
# [0]->upper
if upper < bounds[0, 0]:
# Region outside src bounds.
new_bounds_left = bounds[0:0]
indices_left = tuple()
slice_left = slice(0, 0)
else:
if upper > bounds[-1, 1]:
# Whole of bounds.
u = n - 1
upper = bounds[-1, 1]
else:
# Index of first upper bound greater than or equal to upper.
u = np.nonzero(bounds[:, 1] >= upper)[0][0]
# Extract the bounds in our region defined by [0]->upper.
new_bounds_left = np.copy(bounds[0:(u + 1), :])
# Replace last value with specified bound.
new_bounds_left[-1, 1] = upper
if reversed_flag:
indices_left = tuple(range(n - (u + 1), n))
slice_left = slice(n - (u + 1), n)
else:
indices_left = tuple(range(0, u + 1))
slice_left = slice(0, u + 1)
# lower->[-1]
if lower > bounds[-1, 1]:
# Region is outside src bounds.
new_bounds_right = bounds[0:0]
indices_right = tuple()
slice_right = slice(0, 0)
else:
if lower < bounds[0, 0]:
# Whole of bounds.
l = 0
lower = bounds[0, 0]
else:
# Index of last lower bound less than or equal to lower.
l = np.nonzero(bounds[:, 0] <= lower)[0][-1]
# Extract the bounds in our region defined by lower->[-1].
new_bounds_right = np.copy(bounds[l:, :])
# Replace first value with specified bound.
new_bounds_right[0, 0] = lower
if reversed_flag:
indices_right = tuple(range(0, n - l))
slice_right = slice(0, n - l)
else:
indices_right = tuple(range(l, n))
slice_right = slice(l, None)
if reversed_flag:
# Flip everything around.
indices_left, indices_right = indices_right, indices_left
slice_left, slice_right = slice_right, slice_left
# Combine regions.
new_bounds = np.concatenate((new_bounds_left, new_bounds_right))
# Use slices if possible, but if we have two regions use indices.
if indices_left and indices_right:
indices = indices_left + indices_right
elif indices_left:
indices = slice_left
elif indices_right:
indices = slice_right
else:
indices = slice(0, 0)
if reversed_flag:
new_bounds = new_bounds[::-1, ::-1]
return new_bounds, indices
def _cartesian_area(y_bounds, x_bounds):
"""
Return an array of the areas of each cell given two arrays
of cartesian bounds.
Args:
* y_bounds:
An (n, 2) shaped NumPy array.
* x_bounds:
An (m, 2) shaped NumPy array.
Returns:
An (n, m) shaped Numpy array of areas.
"""
heights = y_bounds[:, 1] - y_bounds[:, 0]
widths = x_bounds[:, 1] - x_bounds[:, 0]
return np.abs(np.outer(heights, widths))
def _spherical_area(y_bounds, x_bounds, radius=1.0):
"""
Return an array of the areas of each cell on a sphere
given two arrays of latitude and longitude bounds in radians.
Args:
* y_bounds:
An (n, 2) shaped NumPy array of latitide bounds in radians.
* x_bounds:
An (m, 2) shaped NumPy array of longitude bounds in radians.
* radius:
Radius of the sphere. Default is 1.0.
Returns:
An (n, m) shaped Numpy array of areas.
"""
return iris.analysis.cartography._quadrant_area(
y_bounds + np.pi / 2.0, x_bounds, radius)
def _get_bounds_in_units(coord, units, dtype):
"""Return a copy of coord's bounds in the specified units and dtype."""
# The bounds are cast to dtype before conversion to prevent issues when
# mixing float32 and float64 types.
return coord.units.convert(coord.bounds.astype(dtype), units).astype(dtype)
def _regrid_area_weighted_array(src_data, x_dim, y_dim,
src_x_bounds, src_y_bounds,
grid_x_bounds, grid_y_bounds,
grid_x_decreasing, grid_y_decreasing,
area_func, circular=False):
"""
Regrid the given data from its source grid to a new grid using
an area weighted mean to determine the resulting data values.
Args:
* src_data:
An N-dimensional NumPy array.
* x_dim:
The X dimension within `src_data`.
* y_dim:
The Y dimension within `src_data`.
* src_x_bounds:
A NumPy array of bounds along the X axis defining the source grid.
* src_y_bounds:
A NumPy array of bounds along the Y axis defining the source grid.
* grid_x_bounds:
A NumPy array of bounds along the X axis defining the new grid.
* grid_y_bounds:
A NumPy array of bounds along the Y axis defining the new grid.
* grid_x_decreasing:
Boolean indicating whether the X coordinate of the new grid is
in descending order.
* grid_y_decreasing:
Boolean indicating whether the Y coordinate of the new grid is
in descending order.
* area_func:
A function that returns an (p, q) array of weights given an (p, 2)
shaped array of Y bounds and an (q, 2) shaped array of X bounds.
* circular:
A boolean indicating whether the `src_x_bounds` are periodic. Default
is False.
Returns:
The regridded data as an N-dimensional NumPy array. The lengths
of the X and Y dimensions will now match those of the target
grid.
"""
# Create empty data array to match the new grid.
# Note that dtype is not preserved and that the array is
# masked to allow for regions that do not overlap.
new_shape = list(src_data.shape)
if x_dim is not None:
new_shape[x_dim] = grid_x_bounds.shape[0]
if y_dim is not None:
new_shape[y_dim] = grid_y_bounds.shape[0]
# Flag to indicate whether the original data was a masked array.
src_masked = ma.isMaskedArray(src_data)
if src_masked:
new_data = ma.zeros(new_shape, fill_value=src_data.fill_value)
else:
new_data = ma.zeros(new_shape)
# Assign to mask to explode it, allowing indexed assignment.
new_data.mask = False
# Simple for loop approach.
indices = [slice(None)] * new_data.ndim
for j, (y_0, y_1) in enumerate(grid_y_bounds):
# Reverse lower and upper if dest grid is decreasing.
if grid_y_decreasing:
y_0, y_1 = y_1, y_0
y_bounds, y_indices = _cropped_bounds(src_y_bounds, y_0, y_1)
for i, (x_0, x_1) in enumerate(grid_x_bounds):
# Reverse lower and upper if dest grid is decreasing.
if grid_x_decreasing:
x_0, x_1 = x_1, x_0
x_bounds, x_indices = _cropped_bounds(src_x_bounds, x_0, x_1)
# Determine whether to mask element i, j based on overlap with
# src.
# If x_0 > x_1 then we want [0]->x_1 and x_0->[0] + mod in the case
# of wrapped longitudes. However if the src grid is not global
# (i.e. circular) this new cell would include a region outside of
# the extent of the src grid and should therefore be masked.
outside_extent = x_0 > x_1 and not circular
if (outside_extent or not _within_bounds(src_y_bounds, y_0, y_1) or
not _within_bounds(src_x_bounds, x_0, x_1)):
# Mask out element(s) in new_data
if x_dim is not None:
indices[x_dim] = i
if y_dim is not None:
indices[y_dim] = j
new_data[tuple(indices)] = ma.masked
else:
# Calculate weighted mean of data points.
# Slice out relevant data (this may or may not be a view()
# depending on x_indices being a slice or not).
if x_dim is not None:
indices[x_dim] = x_indices
if y_dim is not None:
indices[y_dim] = y_indices
if isinstance(x_indices, tuple) and \
isinstance(y_indices, tuple):
raise RuntimeError('Cannot handle split bounds '
'in both x and y.')
data = src_data[tuple(indices)]
# Calculate weights based on areas of cropped bounds.
weights = area_func(y_bounds, x_bounds)
# Numpy 1.7 allows the axis keyword arg to be a tuple.
# If the version of NumPy is less than 1.7 manipulate the axes
# of the data so the x and y dimensions can be flattened.
Version = collections.namedtuple('Version',
('major', 'minor', 'micro'))
np_version = Version(*(int(val) for val in
np.version.version.split('.')))
if np_version.minor < 7:
if y_dim is not None and x_dim is not None:
flattened_shape = list(data.shape)
if y_dim > x_dim:
data = np.rollaxis(data, y_dim, data.ndim)
data = np.rollaxis(data, x_dim, data.ndim)
del flattened_shape[y_dim]
del flattened_shape[x_dim]
else:
data = np.rollaxis(data, x_dim, data.ndim)
data = np.rollaxis(data, y_dim, data.ndim)
del flattened_shape[x_dim]
del flattened_shape[y_dim]
weights = weights.T
flattened_shape.append(-1)
data = data.reshape(*flattened_shape)
elif y_dim is not None:
flattened_shape = list(data.shape)
del flattened_shape[y_dim]
flattened_shape.append(-1)
data = data.swapaxes(y_dim, -1).reshape(
*flattened_shape)
elif x_dim is not None:
flattened_shape = list(data.shape)
del flattened_shape[x_dim]
flattened_shape.append(-1)
data = data.swapaxes(x_dim, -1).reshape(
*flattened_shape)
# Axes of data over which the weighted mean is calculated.
axis = -1
new_data_pt = ma.average(data, weights=weights.ravel(),
axis=axis)
else:
# Transpose weights to match dim ordering in data.
weights_shape_y = weights.shape[0]
weights_shape_x = weights.shape[1]
if x_dim is not None and y_dim is not None and \
x_dim < y_dim:
weights = weights.T
# Broadcast the weights array to allow numpy's ma.average
# to be called.
weights_padded_shape = [1] * data.ndim
axes = []
if y_dim is not None:
weights_padded_shape[y_dim] = weights_shape_y
axes.append(y_dim)
if x_dim is not None:
weights_padded_shape[x_dim] = weights_shape_x
axes.append(x_dim)
# Assign new shape to raise error on copy.
weights.shape = weights_padded_shape
# Broadcast weights to match shape of data.
_, broadcasted_weights = np.broadcast_arrays(data, weights)
# Axes of data over which the weighted mean is calculated.
axis = tuple(axes)
# Calculate weighted mean taking into account missing data.
new_data_pt = ma.average(data, weights=broadcasted_weights,
axis=axis)
# Determine suitable mask for data associated with cell.
# Could use all() here.
if src_masked:
# data.mask may be a bool, if not collapse via any().
if data.mask.ndim:
new_data_pt_mask = data.mask.any(axis=axis)
else:
new_data_pt_mask = data.mask
# Insert data (and mask) values into new array.
if x_dim is not None:
indices[x_dim] = i
if y_dim is not None:
indices[y_dim] = j
new_data[tuple(indices)] = new_data_pt
if src_masked:
new_data.mask[tuple(indices)] = new_data_pt_mask
# Remove new mask if original data was not masked
# and no values in the new array are masked.
if not src_masked and not new_data.mask.any():
new_data = new_data.data
return new_data
def regrid_area_weighted_rectilinear_src_and_grid(src_cube, grid_cube):
"""
Return a new cube with data values calculated using the area weighted
mean of data values from src_grid regridded onto the horizontal grid of
grid_cube.
This function requires that the horizontal grids of both cubes are
rectilinear (i.e. expressed in terms of two orthogonal 1D coordinates)
and that these grids are in the same coordinate system. This function
also requires that the coordinates describing the horizontal grids
all have bounds.
Args:
* src_cube:
An instance of :class:`iris.cube.Cube` that supplies the data,
metadata and coordinates.
* grid_cube:
An instance of :class:`iris.cube.Cube` that supplies the desired
horizontal grid definition.
Returns:
A new :class:`iris.cube.Cube` instance.
"""
# Get the 1d monotonic (or scalar) src and grid coordinates.
src_x, src_y = _get_xy_coords(src_cube)
grid_x, grid_y = _get_xy_coords(grid_cube)
# Condition 1: All x and y coordinates must have contiguous bounds to
# define areas.
if not src_x.is_contiguous() or not src_y.is_contiguous() or \
not grid_x.is_contiguous() or not grid_y.is_contiguous():
raise ValueError("The horizontal grid coordinates of both the source "
"and grid cubes must have contiguous bounds.")
# Condition 2: Everything must have the same coordinate system.
src_cs = src_x.coord_system
grid_cs = grid_x.coord_system
if src_cs != grid_cs:
raise ValueError("The horizontal grid coordinates of both the source "
"and grid cubes must have the same coordinate "
"system.")
# Condition 3: cannot create vector coords from scalars.
src_x_dims = src_cube.coord_dims(src_x)
src_x_dim = None
if src_x_dims:
src_x_dim = src_x_dims[0]
src_y_dims = src_cube.coord_dims(src_y)
src_y_dim = None
if src_y_dims:
src_y_dim = src_y_dims[0]
if src_x_dim is None and grid_x.shape[0] != 1 or \
src_y_dim is None and grid_y.shape[0] != 1:
raise ValueError('The horizontal grid coordinates of source cube '
'includes scalar coordinates, but the new grid does '
'not. The new grid must not require additional data '
'dimensions to be created.')
# Determine whether to calculate flat or spherical areas.
# Don't only rely on coord system as it may be None.
spherical = (isinstance(src_cs, (iris.coord_systems.GeogCS,
iris.coord_systems.RotatedGeogCS)) or
src_x.units == 'degrees' or src_x.units == 'radians')
# Get src and grid bounds in the same units.
x_units = iris.unit.Unit('radians') if spherical else src_x.units
y_units = iris.unit.Unit('radians') if spherical else src_y.units
# Operate in highest precision.
src_dtype = np.promote_types(src_x.bounds.dtype, src_y.bounds.dtype)
grid_dtype = np.promote_types(grid_x.bounds.dtype, grid_y.bounds.dtype)
dtype = np.promote_types(src_dtype, grid_dtype)
src_x_bounds = _get_bounds_in_units(src_x, x_units, dtype)
src_y_bounds = _get_bounds_in_units(src_y, y_units, dtype)
grid_x_bounds = _get_bounds_in_units(grid_x, x_units, dtype)
grid_y_bounds = _get_bounds_in_units(grid_y, y_units, dtype)
# Determine whether target grid bounds are decreasing. This must
# be determined prior to wrap_lons being called.
grid_x_decreasing = grid_x_bounds[-1, 0] < grid_x_bounds[0, 0]
grid_y_decreasing = grid_y_bounds[-1, 0] < grid_y_bounds[0, 0]
# Wrapping of longitudes.
if spherical:
base = np.min(src_x_bounds)
modulus = x_units.modulus
# Only wrap if necessary to avoid introducing floating
# point errors.
if np.min(grid_x_bounds) < base or \
np.max(grid_x_bounds) > (base + modulus):
grid_x_bounds = iris.analysis.cartography.wrap_lons(grid_x_bounds,
base, modulus)
# Determine whether the src_x coord has periodic boundary conditions.
circular = getattr(src_x, 'circular', False)
# Use simple cartesian area function or one that takes into
# account the curved surface if coord system is spherical.
if spherical:
area_func = _spherical_area
else:
area_func = _cartesian_area
# Calculate new data array for regridded cube.
new_data = _regrid_area_weighted_array(src_cube.data, src_x_dim, src_y_dim,
src_x_bounds, src_y_bounds,
grid_x_bounds, grid_y_bounds,
grid_x_decreasing,
grid_y_decreasing,
area_func, circular)
# Wrap up the data as a Cube.
# Create 2d meshgrids as required by _create_cube func.
meshgrid_x, meshgrid_y = np.meshgrid(grid_x.points, grid_y.points)
new_cube = _create_cube(new_data, src_cube, src_x_dim, src_y_dim,
src_x, src_y, grid_x, grid_y,
meshgrid_x, meshgrid_y,
_regrid_bilinear_array)
# Slice out any length 1 dimensions.
indices = [slice(None, None)] * new_data.ndim
if src_x_dim is not None and new_cube.shape[src_x_dim] == 1:
indices[src_x_dim] = 0
if src_y_dim is not None and new_cube.shape[src_y_dim] == 1:
indices[src_y_dim] = 0
if 0 in indices:
new_cube = new_cube[tuple(indices)]
return new_cube
| gpl-3.0 |
RPGOne/Skynet | scikit-learn-c604ac39ad0e5b066d964df3e8f31ba7ebda1e0e/doc/sphinxext/github_link.py | 314 | 2661 | from operator import attrgetter
import inspect
import subprocess
import os
import sys
from functools import partial
REVISION_CMD = 'git rev-parse --short HEAD'
def _get_git_revision():
try:
revision = subprocess.check_output(REVISION_CMD.split()).strip()
except subprocess.CalledProcessError:
print('Failed to execute git to get revision')
return None
return revision.decode('utf-8')
def _linkcode_resolve(domain, info, package, url_fmt, revision):
"""Determine a link to online source for a class/method/function
This is called by sphinx.ext.linkcode
An example with a long-untouched module that everyone has
>>> _linkcode_resolve('py', {'module': 'tty',
... 'fullname': 'setraw'},
... package='tty',
... url_fmt='http://hg.python.org/cpython/file/'
... '{revision}/Lib/{package}/{path}#L{lineno}',
... revision='xxxx')
'http://hg.python.org/cpython/file/xxxx/Lib/tty/tty.py#L18'
"""
if revision is None:
return
if domain not in ('py', 'pyx'):
return
if not info.get('module') or not info.get('fullname'):
return
class_name = info['fullname'].split('.')[0]
if type(class_name) != str:
# Python 2 only
class_name = class_name.encode('utf-8')
module = __import__(info['module'], fromlist=[class_name])
obj = attrgetter(info['fullname'])(module)
try:
fn = inspect.getsourcefile(obj)
except Exception:
fn = None
if not fn:
try:
fn = inspect.getsourcefile(sys.modules[obj.__module__])
except Exception:
fn = None
if not fn:
return
fn = os.path.relpath(fn,
start=os.path.dirname(__import__(package).__file__))
try:
lineno = inspect.getsourcelines(obj)[1]
except Exception:
lineno = ''
return url_fmt.format(revision=revision, package=package,
path=fn, lineno=lineno)
def make_linkcode_resolve(package, url_fmt):
"""Returns a linkcode_resolve function for the given URL format
revision is a git commit reference (hash or name)
package is the name of the root module of the package
url_fmt is along the lines of ('https://github.com/USER/PROJECT/'
'blob/{revision}/{package}/'
'{path}#L{lineno}')
"""
revision = _get_git_revision()
return partial(_linkcode_resolve, revision=revision, package=package,
url_fmt=url_fmt)
| bsd-3-clause |
wodji/mbed | workspace_tools/export/simplicityv3.py | 36 | 5565 | """
mbed SDK
Copyright (c) 2014 ARM Limited
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from exporters import Exporter
from os.path import split,splitext, basename
class Folder:
def __init__(self, name):
self.name = name
self.children = []
def contains(self, folderName):
for child in self.children:
if child.name == folderName:
return True
return False
def __str__(self):
retval = self.name + " "
if len(self.children) > 0:
retval += "[ "
for child in self.children:
retval += child.__str__()
retval += " ]"
return retval
def findChild(self, folderName):
for child in self.children:
if child.name == folderName:
return child
return None
def addChild(self, folderName):
if folderName == '':
return None
if not self.contains(folderName):
self.children.append(Folder(folderName))
return self.findChild(folderName)
class SimplicityV3(Exporter):
NAME = 'SimplicityV3'
TOOLCHAIN = 'GCC_ARM'
TARGETS = [
'EFM32GG_STK3700',
'EFM32ZG_STK3200',
'EFM32LG_STK3600',
'EFM32WG_STK3800',
'EFM32HG_STK3400'
]
PARTS = {
'EFM32GG_STK3700': 'com.silabs.mcu.si32.efm32.efm32gg.efm32gg990f1024',
'EFM32ZG_STK3200': 'com.silabs.mcu.si32.efm32.efm32zg.efm32zg222f32',
'EFM32LG_STK3600': 'com.silabs.mcu.si32.efm32.efm32lg.efm32lg990f256',
'EFM32WG_STK3800': 'com.silabs.mcu.si32.efm32.efm32wg.efm32wg990f256',
'EFM32HG_STK3400': 'com.silabs.mcu.si32.efm32.efm32hg.efm32hg322f64'
}
KITS = {
'EFM32GG_STK3700': 'com.silabs.kit.si32.efm32.efm32gg.stk3700',
'EFM32ZG_STK3200': 'com.silabs.kit.si32.efm32.efm32zg.stk3200',
'EFM32LG_STK3600': 'com.silabs.kit.si32.efm32.efm32lg.stk3600',
'EFM32WG_STK3800': 'com.silabs.kit.si32.efm32.efm32wg.stk3800',
'EFM32HG_STK3400': 'com.silabs.kit.si32.efm32.efm32hg.slstk3400a'
}
FILE_TYPES = {
'c_sources':'1',
'cpp_sources':'1',
's_sources':'1'
}
EXCLUDED_LIBS = [
'm',
'c',
'gcc',
'nosys',
'supc++',
'stdc++'
]
DOT_IN_RELATIVE_PATH = False
orderedPaths = Folder("Root")
def check_and_add_path(self, path):
levels = path.split('/')
base = self.orderedPaths
for level in levels:
if base.contains(level):
base = base.findChild(level)
else:
base.addChild(level)
base = base.findChild(level)
def generate(self):
# "make" wants Unix paths
self.resources.win_to_unix()
main_files = []
EXCLUDED_LIBS = [
'm',
'c',
'gcc',
'nosys',
'supc++',
'stdc++'
]
for r_type in ['s_sources', 'c_sources', 'cpp_sources']:
r = getattr(self.resources, r_type)
if r:
for source in r:
self.check_and_add_path(split(source)[0])
if not ('/' in source):
main_files.append(source)
libraries = []
for lib in self.resources.libraries:
l, _ = splitext(basename(lib))
if l[3:] not in EXCLUDED_LIBS:
libraries.append(l[3:])
defines = []
for define in self.get_symbols():
if '=' in define:
keyval = define.split('=')
defines.append( (keyval[0], keyval[1]) )
else:
defines.append( (define, '') )
self.check_and_add_path(split(self.resources.linker_script)[0])
ctx = {
'name': self.program_name,
'main_files': main_files,
'recursiveFolders': self.orderedPaths,
'object_files': self.resources.objects,
'include_paths': self.resources.inc_dirs,
'library_paths': self.resources.lib_dirs,
'linker_script': self.resources.linker_script,
'libraries': libraries,
'symbols': self.get_symbols(),
'defines': defines,
'part': self.PARTS[self.target],
'kit': self.KITS[self.target],
'loopcount': 0
}
## Strip main folder from include paths because ssproj is not capable of handling it
if '.' in ctx['include_paths']:
ctx['include_paths'].remove('.')
'''
Suppress print statements
print('\n')
print(self.target)
print('\n')
print(ctx)
print('\n')
print(self.orderedPaths)
for path in self.orderedPaths.children:
print(path.name + "\n")
for bpath in path.children:
print("\t" + bpath.name + "\n")
'''
self.gen_file('simplicityv3_slsproj.tmpl', ctx, '%s.slsproj' % self.program_name)
| apache-2.0 |
SpectreJan/gnuradio | gnuradio-runtime/python/gnuradio/gru/gnuplot_freqz.py | 59 | 4137 | #!/usr/bin/env python
#
# Copyright 2005,2007 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# GNU Radio is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GNU Radio; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
__all__ = ['gnuplot_freqz']
import tempfile
import os
import math
import numpy
from gnuradio import gr
from gnuradio.gru.freqz import freqz
def gnuplot_freqz (hw, Fs=None, logfreq=False):
"""hw is a tuple of the form (h, w) where h is sequence of complex
freq responses, and w is a sequence of corresponding frequency
points. Plot the frequency response using gnuplot. If Fs is
provide, use it as the sampling frequency, else use 2*pi.
Returns a handle to the gnuplot graph. When the handle is reclaimed
the graph is torn down."""
data_file = tempfile.NamedTemporaryFile ()
cmd_file = os.popen ('gnuplot', 'w')
h, w = hw
ampl = 20 * numpy.log10 (numpy.absolute (h) + 1e-9)
phase = map (lambda x: math.atan2 (x.imag, x.real), h)
if Fs:
w *= (Fs/(2*math.pi))
for freq, a, ph in zip (w, ampl, phase):
data_file.write ("%g\t%g\t%g\n" % (freq, a, ph))
data_file.flush ()
cmd_file.write ("set grid\n")
if logfreq:
cmd_file.write ("set logscale x\n")
else:
cmd_file.write ("unset logscale x\n")
cmd_file.write ("plot '%s' using 1:2 with lines\n" % (data_file.name,))
cmd_file.flush ()
return (cmd_file, data_file)
def test_plot ():
sample_rate = 2.0e6
#taps = firdes.low_pass(1, sample_rate, 200000, 100000, firdes.WIN_HAMMING)
taps = (0.0007329441141337156, 0.0007755281985737383, 0.0005323155201040208,
-7.679847761841656e-19, -0.0007277769618667662, -0.001415981911122799,
-0.0017135187517851591, -0.001282231998629868, 1.61239866282397e-18,
0.0018589380197227001, 0.0035909228026866913, 0.004260237794369459,
0.00310456077568233, -3.0331308923229716e-18, -0.004244099836796522,
-0.007970594801008701, -0.009214458055794239, -0.006562007591128349,
4.714311174044374e-18, 0.008654761128127575, 0.01605774275958538,
0.01841980405151844, 0.013079923577606678, -6.2821650235090215e-18,
-0.017465557903051376, -0.032989680767059326, -0.03894065320491791,
-0.028868533670902252, 7.388111706347014e-18, 0.04517475143074989,
0.09890196472406387, 0.14991308748722076, 0.18646684288978577,
0.19974154233932495, 0.18646684288978577, 0.14991308748722076,
0.09890196472406387, 0.04517475143074989, 7.388111706347014e-18,
-0.028868533670902252, -0.03894065320491791, -0.032989680767059326,
-0.017465557903051376, -6.2821650235090215e-18, 0.013079923577606678,
0.01841980405151844, 0.01605774275958538, 0.008654761128127575,
4.714311174044374e-18, -0.006562007591128349, -0.009214458055794239,
-0.007970594801008701, -0.004244099836796522, -3.0331308923229716e-18,
0.00310456077568233, 0.004260237794369459, 0.0035909228026866913,
0.0018589380197227001, 1.61239866282397e-18, -0.001282231998629868,
-0.0017135187517851591, -0.001415981911122799, -0.0007277769618667662,
-7.679847761841656e-19, 0.0005323155201040208, 0.0007755281985737383,
0.0007329441141337156)
# print len (taps)
return gnuplot_freqz (freqz (taps, 1), sample_rate)
if __name__ == '__main__':
handle = test_plot ()
raw_input ('Press Enter to continue: ')
| gpl-3.0 |
joelagnel/ns-3 | bindings/python/apidefs/gcc-ILP32/ns3_module_dsdv.py | 6 | 38296 | from pybindgen import Module, FileCodeSink, param, retval, cppclass, typehandlers
def register_types(module):
root_module = module.get_root()
## dsdv-helper.h: ns3::DsdvHelper [class]
module.add_class('DsdvHelper', parent=root_module['ns3::Ipv4RoutingHelper'])
## Register a nested module for the namespace Config
nested_module = module.add_cpp_namespace('Config')
register_types_ns3_Config(nested_module)
## Register a nested module for the namespace FatalImpl
nested_module = module.add_cpp_namespace('FatalImpl')
register_types_ns3_FatalImpl(nested_module)
## Register a nested module for the namespace addressUtils
nested_module = module.add_cpp_namespace('addressUtils')
register_types_ns3_addressUtils(nested_module)
## Register a nested module for the namespace aodv
nested_module = module.add_cpp_namespace('aodv')
register_types_ns3_aodv(nested_module)
## Register a nested module for the namespace dot11s
nested_module = module.add_cpp_namespace('dot11s')
register_types_ns3_dot11s(nested_module)
## Register a nested module for the namespace dsdv
nested_module = module.add_cpp_namespace('dsdv')
register_types_ns3_dsdv(nested_module)
## Register a nested module for the namespace flame
nested_module = module.add_cpp_namespace('flame')
register_types_ns3_flame(nested_module)
## Register a nested module for the namespace internal
nested_module = module.add_cpp_namespace('internal')
register_types_ns3_internal(nested_module)
## Register a nested module for the namespace olsr
nested_module = module.add_cpp_namespace('olsr')
register_types_ns3_olsr(nested_module)
def register_types_ns3_Config(module):
root_module = module.get_root()
def register_types_ns3_FatalImpl(module):
root_module = module.get_root()
def register_types_ns3_addressUtils(module):
root_module = module.get_root()
def register_types_ns3_aodv(module):
root_module = module.get_root()
def register_types_ns3_dot11s(module):
root_module = module.get_root()
def register_types_ns3_dsdv(module):
root_module = module.get_root()
## dsdv-rtable.h: ns3::dsdv::RouteFlags [enumeration]
module.add_enum('RouteFlags', ['VALID', 'INVALID'])
## dsdv-packet.h: ns3::dsdv::DsdvHeader [class]
module.add_class('DsdvHeader', parent=root_module['ns3::Header'])
## dsdv-packet-queue.h: ns3::dsdv::PacketQueue [class]
module.add_class('PacketQueue')
## dsdv-packet-queue.h: ns3::dsdv::QueueEntry [class]
module.add_class('QueueEntry')
## dsdv-routing-protocol.h: ns3::dsdv::RoutingProtocol [class]
module.add_class('RoutingProtocol', parent=root_module['ns3::Ipv4RoutingProtocol'])
## dsdv-rtable.h: ns3::dsdv::RoutingTable [class]
module.add_class('RoutingTable')
## dsdv-rtable.h: ns3::dsdv::RoutingTableEntry [class]
module.add_class('RoutingTableEntry')
module.add_container('std::map< ns3::Ipv4Address, ns3::dsdv::RoutingTableEntry >', ('ns3::Ipv4Address', 'ns3::dsdv::RoutingTableEntry'), container_type='map')
def register_types_ns3_flame(module):
root_module = module.get_root()
def register_types_ns3_internal(module):
root_module = module.get_root()
def register_types_ns3_olsr(module):
root_module = module.get_root()
def register_methods(root_module):
register_Ns3DsdvHelper_methods(root_module, root_module['ns3::DsdvHelper'])
register_Ns3DsdvDsdvHeader_methods(root_module, root_module['ns3::dsdv::DsdvHeader'])
register_Ns3DsdvPacketQueue_methods(root_module, root_module['ns3::dsdv::PacketQueue'])
register_Ns3DsdvQueueEntry_methods(root_module, root_module['ns3::dsdv::QueueEntry'])
register_Ns3DsdvRoutingProtocol_methods(root_module, root_module['ns3::dsdv::RoutingProtocol'])
register_Ns3DsdvRoutingTable_methods(root_module, root_module['ns3::dsdv::RoutingTable'])
register_Ns3DsdvRoutingTableEntry_methods(root_module, root_module['ns3::dsdv::RoutingTableEntry'])
return
def register_Ns3DsdvHelper_methods(root_module, cls):
## dsdv-helper.h: ns3::DsdvHelper::DsdvHelper(ns3::DsdvHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DsdvHelper const &', 'arg0')])
## dsdv-helper.h: ns3::DsdvHelper::DsdvHelper() [constructor]
cls.add_constructor([])
## dsdv-helper.h: ns3::DsdvHelper * ns3::DsdvHelper::Copy() const [member function]
cls.add_method('Copy',
'ns3::DsdvHelper *',
[],
is_const=True, is_virtual=True)
## dsdv-helper.h: ns3::Ptr<ns3::Ipv4RoutingProtocol> ns3::DsdvHelper::Create(ns3::Ptr<ns3::Node> node) const [member function]
cls.add_method('Create',
'ns3::Ptr< ns3::Ipv4RoutingProtocol >',
[param('ns3::Ptr< ns3::Node >', 'node')],
is_const=True, is_virtual=True)
## dsdv-helper.h: void ns3::DsdvHelper::Set(std::string name, ns3::AttributeValue const & value) [member function]
cls.add_method('Set',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
return
def register_Ns3DsdvDsdvHeader_methods(root_module, cls):
cls.add_output_stream_operator()
## dsdv-packet.h: ns3::dsdv::DsdvHeader::DsdvHeader(ns3::dsdv::DsdvHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::dsdv::DsdvHeader const &', 'arg0')])
## dsdv-packet.h: ns3::dsdv::DsdvHeader::DsdvHeader(ns3::Ipv4Address dst=ns3::Ipv4Address(), uint32_t hopcount=0, uint32_t dstSeqNo=0) [constructor]
cls.add_constructor([param('ns3::Ipv4Address', 'dst', default_value='ns3::Ipv4Address()'), param('uint32_t', 'hopcount', default_value='0'), param('uint32_t', 'dstSeqNo', default_value='0')])
## dsdv-packet.h: uint32_t ns3::dsdv::DsdvHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## dsdv-packet.h: ns3::Ipv4Address ns3::dsdv::DsdvHeader::GetDst() const [member function]
cls.add_method('GetDst',
'ns3::Ipv4Address',
[],
is_const=True)
## dsdv-packet.h: uint32_t ns3::dsdv::DsdvHeader::GetDstSeqno() const [member function]
cls.add_method('GetDstSeqno',
'uint32_t',
[],
is_const=True)
## dsdv-packet.h: uint32_t ns3::dsdv::DsdvHeader::GetHopCount() const [member function]
cls.add_method('GetHopCount',
'uint32_t',
[],
is_const=True)
## dsdv-packet.h: ns3::TypeId ns3::dsdv::DsdvHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## dsdv-packet.h: uint32_t ns3::dsdv::DsdvHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## dsdv-packet.h: static ns3::TypeId ns3::dsdv::DsdvHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## dsdv-packet.h: void ns3::dsdv::DsdvHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## dsdv-packet.h: void ns3::dsdv::DsdvHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## dsdv-packet.h: void ns3::dsdv::DsdvHeader::SetDst(ns3::Ipv4Address destination) [member function]
cls.add_method('SetDst',
'void',
[param('ns3::Ipv4Address', 'destination')])
## dsdv-packet.h: void ns3::dsdv::DsdvHeader::SetDstSeqno(uint32_t sequenceNumber) [member function]
cls.add_method('SetDstSeqno',
'void',
[param('uint32_t', 'sequenceNumber')])
## dsdv-packet.h: void ns3::dsdv::DsdvHeader::SetHopCount(uint32_t hopCount) [member function]
cls.add_method('SetHopCount',
'void',
[param('uint32_t', 'hopCount')])
return
def register_Ns3DsdvPacketQueue_methods(root_module, cls):
## dsdv-packet-queue.h: ns3::dsdv::PacketQueue::PacketQueue(ns3::dsdv::PacketQueue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::dsdv::PacketQueue const &', 'arg0')])
## dsdv-packet-queue.h: ns3::dsdv::PacketQueue::PacketQueue() [constructor]
cls.add_constructor([])
## dsdv-packet-queue.h: bool ns3::dsdv::PacketQueue::Dequeue(ns3::Ipv4Address dst, ns3::dsdv::QueueEntry & entry) [member function]
cls.add_method('Dequeue',
'bool',
[param('ns3::Ipv4Address', 'dst'), param('ns3::dsdv::QueueEntry &', 'entry')])
## dsdv-packet-queue.h: void ns3::dsdv::PacketQueue::DropPacketWithDst(ns3::Ipv4Address dst) [member function]
cls.add_method('DropPacketWithDst',
'void',
[param('ns3::Ipv4Address', 'dst')])
## dsdv-packet-queue.h: bool ns3::dsdv::PacketQueue::Enqueue(ns3::dsdv::QueueEntry & entry) [member function]
cls.add_method('Enqueue',
'bool',
[param('ns3::dsdv::QueueEntry &', 'entry')])
## dsdv-packet-queue.h: bool ns3::dsdv::PacketQueue::Find(ns3::Ipv4Address dst) [member function]
cls.add_method('Find',
'bool',
[param('ns3::Ipv4Address', 'dst')])
## dsdv-packet-queue.h: uint32_t ns3::dsdv::PacketQueue::GetCountForPacketsWithDst(ns3::Ipv4Address dst) [member function]
cls.add_method('GetCountForPacketsWithDst',
'uint32_t',
[param('ns3::Ipv4Address', 'dst')])
## dsdv-packet-queue.h: uint32_t ns3::dsdv::PacketQueue::GetMaxPacketsPerDst() const [member function]
cls.add_method('GetMaxPacketsPerDst',
'uint32_t',
[],
is_const=True)
## dsdv-packet-queue.h: uint32_t ns3::dsdv::PacketQueue::GetMaxQueueLen() const [member function]
cls.add_method('GetMaxQueueLen',
'uint32_t',
[],
is_const=True)
## dsdv-packet-queue.h: ns3::Time ns3::dsdv::PacketQueue::GetQueueTimeout() const [member function]
cls.add_method('GetQueueTimeout',
'ns3::Time',
[],
is_const=True)
## dsdv-packet-queue.h: uint32_t ns3::dsdv::PacketQueue::GetSize() [member function]
cls.add_method('GetSize',
'uint32_t',
[])
## dsdv-packet-queue.h: void ns3::dsdv::PacketQueue::SetMaxPacketsPerDst(uint32_t len) [member function]
cls.add_method('SetMaxPacketsPerDst',
'void',
[param('uint32_t', 'len')])
## dsdv-packet-queue.h: void ns3::dsdv::PacketQueue::SetMaxQueueLen(uint32_t len) [member function]
cls.add_method('SetMaxQueueLen',
'void',
[param('uint32_t', 'len')])
## dsdv-packet-queue.h: void ns3::dsdv::PacketQueue::SetQueueTimeout(ns3::Time t) [member function]
cls.add_method('SetQueueTimeout',
'void',
[param('ns3::Time', 't')])
return
def register_Ns3DsdvQueueEntry_methods(root_module, cls):
cls.add_binary_comparison_operator('==')
## dsdv-packet-queue.h: ns3::dsdv::QueueEntry::QueueEntry(ns3::dsdv::QueueEntry const & arg0) [copy constructor]
cls.add_constructor([param('ns3::dsdv::QueueEntry const &', 'arg0')])
## dsdv-packet-queue.h: ns3::dsdv::QueueEntry::QueueEntry(ns3::Ptr<ns3::Packet const> pa=0, ns3::Ipv4Header const & h=ns3::Ipv4Header(), ns3::Callback<void, ns3::Ptr<ns3::Ipv4Route>, ns3::Ptr<ns3::Packet const>, ns3::Ipv4Header const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> ucb=ns3::Callback<void, ns3::Ptr<ns3::Ipv4Route>, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>(), ns3::Callback<void, ns3::Ptr<ns3::Packet const>, ns3::Ipv4Header const&, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> ecb=ns3::Callback<void, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header&, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>()) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::Packet const >', 'pa', default_value='0'), param('ns3::Ipv4Header const &', 'h', default_value='ns3::Ipv4Header()'), param('ns3::Callback< void, ns3::Ptr< ns3::Ipv4Route >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ucb', default_value='ns3::Callback<void, ns3::Ptr<ns3::Ipv4Route>, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>()'), param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ecb', default_value='ns3::Callback<void, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header&, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>()')])
## dsdv-packet-queue.h: ns3::Callback<void, ns3::Ptr<ns3::Packet const>, ns3::Ipv4Header const&, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> ns3::dsdv::QueueEntry::GetErrorCallback() const [member function]
cls.add_method('GetErrorCallback',
'ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >',
[],
is_const=True)
## dsdv-packet-queue.h: ns3::Time ns3::dsdv::QueueEntry::GetExpireTime() const [member function]
cls.add_method('GetExpireTime',
'ns3::Time',
[],
is_const=True)
## dsdv-packet-queue.h: ns3::Ipv4Header ns3::dsdv::QueueEntry::GetIpv4Header() const [member function]
cls.add_method('GetIpv4Header',
'ns3::Ipv4Header',
[],
is_const=True)
## dsdv-packet-queue.h: ns3::Ptr<ns3::Packet const> ns3::dsdv::QueueEntry::GetPacket() const [member function]
cls.add_method('GetPacket',
'ns3::Ptr< ns3::Packet const >',
[],
is_const=True)
## dsdv-packet-queue.h: ns3::Callback<void, ns3::Ptr<ns3::Ipv4Route>, ns3::Ptr<ns3::Packet const>, ns3::Ipv4Header const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> ns3::dsdv::QueueEntry::GetUnicastForwardCallback() const [member function]
cls.add_method('GetUnicastForwardCallback',
'ns3::Callback< void, ns3::Ptr< ns3::Ipv4Route >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >',
[],
is_const=True)
## dsdv-packet-queue.h: void ns3::dsdv::QueueEntry::SetErrorCallback(ns3::Callback<void, ns3::Ptr<ns3::Packet const>, ns3::Ipv4Header const&, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> ecb) [member function]
cls.add_method('SetErrorCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ecb')])
## dsdv-packet-queue.h: void ns3::dsdv::QueueEntry::SetExpireTime(ns3::Time exp) [member function]
cls.add_method('SetExpireTime',
'void',
[param('ns3::Time', 'exp')])
## dsdv-packet-queue.h: void ns3::dsdv::QueueEntry::SetIpv4Header(ns3::Ipv4Header h) [member function]
cls.add_method('SetIpv4Header',
'void',
[param('ns3::Ipv4Header', 'h')])
## dsdv-packet-queue.h: void ns3::dsdv::QueueEntry::SetPacket(ns3::Ptr<ns3::Packet const> p) [member function]
cls.add_method('SetPacket',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'p')])
## dsdv-packet-queue.h: void ns3::dsdv::QueueEntry::SetUnicastForwardCallback(ns3::Callback<void, ns3::Ptr<ns3::Ipv4Route>, ns3::Ptr<ns3::Packet const>, ns3::Ipv4Header const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> ucb) [member function]
cls.add_method('SetUnicastForwardCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Ipv4Route >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ucb')])
return
def register_Ns3DsdvRoutingProtocol_methods(root_module, cls):
## dsdv-routing-protocol.h: ns3::dsdv::RoutingProtocol::RoutingProtocol(ns3::dsdv::RoutingProtocol const & arg0) [copy constructor]
cls.add_constructor([param('ns3::dsdv::RoutingProtocol const &', 'arg0')])
## dsdv-routing-protocol.h: ns3::dsdv::RoutingProtocol::RoutingProtocol() [constructor]
cls.add_constructor([])
## dsdv-routing-protocol.h: void ns3::dsdv::RoutingProtocol::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
is_virtual=True)
## dsdv-routing-protocol.h: bool ns3::dsdv::RoutingProtocol::GetEnableBufferFlag() const [member function]
cls.add_method('GetEnableBufferFlag',
'bool',
[],
is_const=True)
## dsdv-routing-protocol.h: bool ns3::dsdv::RoutingProtocol::GetEnableRAFlag() const [member function]
cls.add_method('GetEnableRAFlag',
'bool',
[],
is_const=True)
## dsdv-routing-protocol.h: static ns3::TypeId ns3::dsdv::RoutingProtocol::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## dsdv-routing-protocol.h: bool ns3::dsdv::RoutingProtocol::GetWSTFlag() const [member function]
cls.add_method('GetWSTFlag',
'bool',
[],
is_const=True)
## dsdv-routing-protocol.h: void ns3::dsdv::RoutingProtocol::NotifyAddAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function]
cls.add_method('NotifyAddAddress',
'void',
[param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')],
is_virtual=True)
## dsdv-routing-protocol.h: void ns3::dsdv::RoutingProtocol::NotifyInterfaceDown(uint32_t interface) [member function]
cls.add_method('NotifyInterfaceDown',
'void',
[param('uint32_t', 'interface')],
is_virtual=True)
## dsdv-routing-protocol.h: void ns3::dsdv::RoutingProtocol::NotifyInterfaceUp(uint32_t interface) [member function]
cls.add_method('NotifyInterfaceUp',
'void',
[param('uint32_t', 'interface')],
is_virtual=True)
## dsdv-routing-protocol.h: void ns3::dsdv::RoutingProtocol::NotifyRemoveAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function]
cls.add_method('NotifyRemoveAddress',
'void',
[param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')],
is_virtual=True)
## dsdv-routing-protocol.h: void ns3::dsdv::RoutingProtocol::PrintRoutingTable(ns3::Ptr<ns3::OutputStreamWrapper> stream) const [member function]
cls.add_method('PrintRoutingTable',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')],
is_const=True, is_virtual=True)
## dsdv-routing-protocol.h: bool ns3::dsdv::RoutingProtocol::RouteInput(ns3::Ptr<ns3::Packet const> p, ns3::Ipv4Header const & header, ns3::Ptr<const ns3::NetDevice> idev, ns3::Callback<void, ns3::Ptr<ns3::Ipv4Route>, ns3::Ptr<ns3::Packet const>, ns3::Ipv4Header const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> ucb, ns3::Callback<void,ns3::Ptr<ns3::Ipv4MulticastRoute>,ns3::Ptr<const ns3::Packet>,const ns3::Ipv4Header&,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> mcb, ns3::Callback<void,ns3::Ptr<const ns3::Packet>,const ns3::Ipv4Header&,unsigned int,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> lcb, ns3::Callback<void, ns3::Ptr<ns3::Packet const>, ns3::Ipv4Header const&, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> ecb) [member function]
cls.add_method('RouteInput',
'bool',
[param('ns3::Ptr< ns3::Packet const >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice const >', 'idev'), param('ns3::Callback< void, ns3::Ptr< ns3::Ipv4Route >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ucb'), param('ns3::Callback< void, ns3::Ptr< ns3::Ipv4MulticastRoute >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'mcb'), param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'lcb'), param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ecb')],
is_virtual=True)
## dsdv-routing-protocol.h: ns3::Ptr<ns3::Ipv4Route> ns3::dsdv::RoutingProtocol::RouteOutput(ns3::Ptr<ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<ns3::NetDevice> oif, ns3::Socket::SocketErrno & sockerr) [member function]
cls.add_method('RouteOutput',
'ns3::Ptr< ns3::Ipv4Route >',
[param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice >', 'oif'), param('ns3::Socket::SocketErrno &', 'sockerr')],
is_virtual=True)
## dsdv-routing-protocol.h: void ns3::dsdv::RoutingProtocol::SetEnableBufferFlag(bool f) [member function]
cls.add_method('SetEnableBufferFlag',
'void',
[param('bool', 'f')])
## dsdv-routing-protocol.h: void ns3::dsdv::RoutingProtocol::SetEnableRAFlag(bool f) [member function]
cls.add_method('SetEnableRAFlag',
'void',
[param('bool', 'f')])
## dsdv-routing-protocol.h: void ns3::dsdv::RoutingProtocol::SetIpv4(ns3::Ptr<ns3::Ipv4> ipv4) [member function]
cls.add_method('SetIpv4',
'void',
[param('ns3::Ptr< ns3::Ipv4 >', 'ipv4')],
is_virtual=True)
## dsdv-routing-protocol.h: void ns3::dsdv::RoutingProtocol::SetWSTFlag(bool f) [member function]
cls.add_method('SetWSTFlag',
'void',
[param('bool', 'f')])
## dsdv-routing-protocol.h: ns3::dsdv::RoutingProtocol::DSDV_PORT [variable]
cls.add_static_attribute('DSDV_PORT', 'uint32_t const', is_const=True)
return
def register_Ns3DsdvRoutingTable_methods(root_module, cls):
## dsdv-rtable.h: ns3::dsdv::RoutingTable::RoutingTable(ns3::dsdv::RoutingTable const & arg0) [copy constructor]
cls.add_constructor([param('ns3::dsdv::RoutingTable const &', 'arg0')])
## dsdv-rtable.h: ns3::dsdv::RoutingTable::RoutingTable() [constructor]
cls.add_constructor([])
## dsdv-rtable.h: bool ns3::dsdv::RoutingTable::AddIpv4Event(ns3::Ipv4Address arg0, ns3::EventId arg1) [member function]
cls.add_method('AddIpv4Event',
'bool',
[param('ns3::Ipv4Address', 'arg0'), param('ns3::EventId', 'arg1')])
## dsdv-rtable.h: bool ns3::dsdv::RoutingTable::AddRoute(ns3::dsdv::RoutingTableEntry & r) [member function]
cls.add_method('AddRoute',
'bool',
[param('ns3::dsdv::RoutingTableEntry &', 'r')])
## dsdv-rtable.h: bool ns3::dsdv::RoutingTable::AnyRunningEvent(ns3::Ipv4Address address) [member function]
cls.add_method('AnyRunningEvent',
'bool',
[param('ns3::Ipv4Address', 'address')])
## dsdv-rtable.h: void ns3::dsdv::RoutingTable::Clear() [member function]
cls.add_method('Clear',
'void',
[])
## dsdv-rtable.h: void ns3::dsdv::RoutingTable::DeleteAllRoutesFromInterface(ns3::Ipv4InterfaceAddress iface) [member function]
cls.add_method('DeleteAllRoutesFromInterface',
'void',
[param('ns3::Ipv4InterfaceAddress', 'iface')])
## dsdv-rtable.h: bool ns3::dsdv::RoutingTable::DeleteIpv4Event(ns3::Ipv4Address address) [member function]
cls.add_method('DeleteIpv4Event',
'bool',
[param('ns3::Ipv4Address', 'address')])
## dsdv-rtable.h: bool ns3::dsdv::RoutingTable::DeleteRoute(ns3::Ipv4Address dst) [member function]
cls.add_method('DeleteRoute',
'bool',
[param('ns3::Ipv4Address', 'dst')])
## dsdv-rtable.h: bool ns3::dsdv::RoutingTable::ForceDeleteIpv4Event(ns3::Ipv4Address address) [member function]
cls.add_method('ForceDeleteIpv4Event',
'bool',
[param('ns3::Ipv4Address', 'address')])
## dsdv-rtable.h: ns3::EventId ns3::dsdv::RoutingTable::GetEventId(ns3::Ipv4Address address) [member function]
cls.add_method('GetEventId',
'ns3::EventId',
[param('ns3::Ipv4Address', 'address')])
## dsdv-rtable.h: void ns3::dsdv::RoutingTable::GetListOfAllRoutes(std::map<ns3::Ipv4Address, ns3::dsdv::RoutingTableEntry, std::less<ns3::Ipv4Address>, std::allocator<std::pair<ns3::Ipv4Address const, ns3::dsdv::RoutingTableEntry> > > & allRoutes) [member function]
cls.add_method('GetListOfAllRoutes',
'void',
[param('std::map< ns3::Ipv4Address, ns3::dsdv::RoutingTableEntry > &', 'allRoutes')])
## dsdv-rtable.h: void ns3::dsdv::RoutingTable::GetListOfDestinationWithNextHop(ns3::Ipv4Address nxtHp, std::map<ns3::Ipv4Address, ns3::dsdv::RoutingTableEntry, std::less<ns3::Ipv4Address>, std::allocator<std::pair<ns3::Ipv4Address const, ns3::dsdv::RoutingTableEntry> > > & dstList) [member function]
cls.add_method('GetListOfDestinationWithNextHop',
'void',
[param('ns3::Ipv4Address', 'nxtHp'), param('std::map< ns3::Ipv4Address, ns3::dsdv::RoutingTableEntry > &', 'dstList')])
## dsdv-rtable.h: ns3::Time ns3::dsdv::RoutingTable::Getholddowntime() const [member function]
cls.add_method('Getholddowntime',
'ns3::Time',
[],
is_const=True)
## dsdv-rtable.h: bool ns3::dsdv::RoutingTable::LookupRoute(ns3::Ipv4Address dst, ns3::dsdv::RoutingTableEntry & rt) [member function]
cls.add_method('LookupRoute',
'bool',
[param('ns3::Ipv4Address', 'dst'), param('ns3::dsdv::RoutingTableEntry &', 'rt')])
## dsdv-rtable.h: bool ns3::dsdv::RoutingTable::LookupRoute(ns3::Ipv4Address id, ns3::dsdv::RoutingTableEntry & rt, bool forRouteInput) [member function]
cls.add_method('LookupRoute',
'bool',
[param('ns3::Ipv4Address', 'id'), param('ns3::dsdv::RoutingTableEntry &', 'rt'), param('bool', 'forRouteInput')])
## dsdv-rtable.h: void ns3::dsdv::RoutingTable::Print(ns3::Ptr<ns3::OutputStreamWrapper> stream) const [member function]
cls.add_method('Print',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')],
is_const=True)
## dsdv-rtable.h: void ns3::dsdv::RoutingTable::Purge(std::map<ns3::Ipv4Address, ns3::dsdv::RoutingTableEntry, std::less<ns3::Ipv4Address>, std::allocator<std::pair<ns3::Ipv4Address const, ns3::dsdv::RoutingTableEntry> > > & removedAddresses) [member function]
cls.add_method('Purge',
'void',
[param('std::map< ns3::Ipv4Address, ns3::dsdv::RoutingTableEntry > &', 'removedAddresses')])
## dsdv-rtable.h: uint32_t ns3::dsdv::RoutingTable::RoutingTableSize() [member function]
cls.add_method('RoutingTableSize',
'uint32_t',
[])
## dsdv-rtable.h: void ns3::dsdv::RoutingTable::Setholddowntime(ns3::Time t) [member function]
cls.add_method('Setholddowntime',
'void',
[param('ns3::Time', 't')])
## dsdv-rtable.h: bool ns3::dsdv::RoutingTable::Update(ns3::dsdv::RoutingTableEntry & rt) [member function]
cls.add_method('Update',
'bool',
[param('ns3::dsdv::RoutingTableEntry &', 'rt')])
return
def register_Ns3DsdvRoutingTableEntry_methods(root_module, cls):
## dsdv-rtable.h: ns3::dsdv::RoutingTableEntry::RoutingTableEntry(ns3::dsdv::RoutingTableEntry const & arg0) [copy constructor]
cls.add_constructor([param('ns3::dsdv::RoutingTableEntry const &', 'arg0')])
## dsdv-rtable.h: ns3::dsdv::RoutingTableEntry::RoutingTableEntry(ns3::Ptr<ns3::NetDevice> dev=0, ns3::Ipv4Address dst=ns3::Ipv4Address(), u_int32_t m_seqNo=0, ns3::Ipv4InterfaceAddress iface=ns3::Ipv4InterfaceAddress(), u_int32_t hops=0, ns3::Ipv4Address nextHop=ns3::Ipv4Address(), ns3::Time lifetime=ns3::Simulator::Now( ), ns3::Time SettlingTime=ns3::Simulator::Now( ), bool changedEntries=false) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::NetDevice >', 'dev', default_value='0'), param('ns3::Ipv4Address', 'dst', default_value='ns3::Ipv4Address()'), param('u_int32_t', 'm_seqNo', default_value='0'), param('ns3::Ipv4InterfaceAddress', 'iface', default_value='ns3::Ipv4InterfaceAddress()'), param('u_int32_t', 'hops', default_value='0'), param('ns3::Ipv4Address', 'nextHop', default_value='ns3::Ipv4Address()'), param('ns3::Time', 'lifetime', default_value='ns3::Simulator::Now( )'), param('ns3::Time', 'SettlingTime', default_value='ns3::Simulator::Now( )'), param('bool', 'changedEntries', default_value='false')])
## dsdv-rtable.h: ns3::Ipv4Address ns3::dsdv::RoutingTableEntry::GetDestination() const [member function]
cls.add_method('GetDestination',
'ns3::Ipv4Address',
[],
is_const=True)
## dsdv-rtable.h: bool ns3::dsdv::RoutingTableEntry::GetEntriesChanged() const [member function]
cls.add_method('GetEntriesChanged',
'bool',
[],
is_const=True)
## dsdv-rtable.h: ns3::dsdv::RouteFlags ns3::dsdv::RoutingTableEntry::GetFlag() const [member function]
cls.add_method('GetFlag',
'ns3::dsdv::RouteFlags',
[],
is_const=True)
## dsdv-rtable.h: uint32_t ns3::dsdv::RoutingTableEntry::GetHop() const [member function]
cls.add_method('GetHop',
'uint32_t',
[],
is_const=True)
## dsdv-rtable.h: ns3::Ipv4InterfaceAddress ns3::dsdv::RoutingTableEntry::GetInterface() const [member function]
cls.add_method('GetInterface',
'ns3::Ipv4InterfaceAddress',
[],
is_const=True)
## dsdv-rtable.h: ns3::Time ns3::dsdv::RoutingTableEntry::GetLifeTime() const [member function]
cls.add_method('GetLifeTime',
'ns3::Time',
[],
is_const=True)
## dsdv-rtable.h: ns3::Ipv4Address ns3::dsdv::RoutingTableEntry::GetNextHop() const [member function]
cls.add_method('GetNextHop',
'ns3::Ipv4Address',
[],
is_const=True)
## dsdv-rtable.h: ns3::Ptr<ns3::NetDevice> ns3::dsdv::RoutingTableEntry::GetOutputDevice() const [member function]
cls.add_method('GetOutputDevice',
'ns3::Ptr< ns3::NetDevice >',
[],
is_const=True)
## dsdv-rtable.h: ns3::Ptr<ns3::Ipv4Route> ns3::dsdv::RoutingTableEntry::GetRoute() const [member function]
cls.add_method('GetRoute',
'ns3::Ptr< ns3::Ipv4Route >',
[],
is_const=True)
## dsdv-rtable.h: uint32_t ns3::dsdv::RoutingTableEntry::GetSeqNo() const [member function]
cls.add_method('GetSeqNo',
'uint32_t',
[],
is_const=True)
## dsdv-rtable.h: ns3::Time ns3::dsdv::RoutingTableEntry::GetSettlingTime() const [member function]
cls.add_method('GetSettlingTime',
'ns3::Time',
[],
is_const=True)
## dsdv-rtable.h: void ns3::dsdv::RoutingTableEntry::Print(ns3::Ptr<ns3::OutputStreamWrapper> stream) const [member function]
cls.add_method('Print',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')],
is_const=True)
## dsdv-rtable.h: void ns3::dsdv::RoutingTableEntry::SetEntriesChanged(bool entriesChanged) [member function]
cls.add_method('SetEntriesChanged',
'void',
[param('bool', 'entriesChanged')])
## dsdv-rtable.h: void ns3::dsdv::RoutingTableEntry::SetFlag(ns3::dsdv::RouteFlags flag) [member function]
cls.add_method('SetFlag',
'void',
[param('ns3::dsdv::RouteFlags', 'flag')])
## dsdv-rtable.h: void ns3::dsdv::RoutingTableEntry::SetHop(uint32_t hopCount) [member function]
cls.add_method('SetHop',
'void',
[param('uint32_t', 'hopCount')])
## dsdv-rtable.h: void ns3::dsdv::RoutingTableEntry::SetInterface(ns3::Ipv4InterfaceAddress iface) [member function]
cls.add_method('SetInterface',
'void',
[param('ns3::Ipv4InterfaceAddress', 'iface')])
## dsdv-rtable.h: void ns3::dsdv::RoutingTableEntry::SetLifeTime(ns3::Time lifeTime) [member function]
cls.add_method('SetLifeTime',
'void',
[param('ns3::Time', 'lifeTime')])
## dsdv-rtable.h: void ns3::dsdv::RoutingTableEntry::SetNextHop(ns3::Ipv4Address nextHop) [member function]
cls.add_method('SetNextHop',
'void',
[param('ns3::Ipv4Address', 'nextHop')])
## dsdv-rtable.h: void ns3::dsdv::RoutingTableEntry::SetOutputDevice(ns3::Ptr<ns3::NetDevice> device) [member function]
cls.add_method('SetOutputDevice',
'void',
[param('ns3::Ptr< ns3::NetDevice >', 'device')])
## dsdv-rtable.h: void ns3::dsdv::RoutingTableEntry::SetRoute(ns3::Ptr<ns3::Ipv4Route> route) [member function]
cls.add_method('SetRoute',
'void',
[param('ns3::Ptr< ns3::Ipv4Route >', 'route')])
## dsdv-rtable.h: void ns3::dsdv::RoutingTableEntry::SetSeqNo(uint32_t sequenceNumber) [member function]
cls.add_method('SetSeqNo',
'void',
[param('uint32_t', 'sequenceNumber')])
## dsdv-rtable.h: void ns3::dsdv::RoutingTableEntry::SetSettlingTime(ns3::Time settlingTime) [member function]
cls.add_method('SetSettlingTime',
'void',
[param('ns3::Time', 'settlingTime')])
return
def register_functions(root_module):
module = root_module
register_functions_ns3_Config(module.get_submodule('Config'), root_module)
register_functions_ns3_FatalImpl(module.get_submodule('FatalImpl'), root_module)
register_functions_ns3_addressUtils(module.get_submodule('addressUtils'), root_module)
register_functions_ns3_aodv(module.get_submodule('aodv'), root_module)
register_functions_ns3_dot11s(module.get_submodule('dot11s'), root_module)
register_functions_ns3_dsdv(module.get_submodule('dsdv'), root_module)
register_functions_ns3_flame(module.get_submodule('flame'), root_module)
register_functions_ns3_internal(module.get_submodule('internal'), root_module)
register_functions_ns3_olsr(module.get_submodule('olsr'), root_module)
return
def register_functions_ns3_Config(module, root_module):
return
def register_functions_ns3_FatalImpl(module, root_module):
return
def register_functions_ns3_addressUtils(module, root_module):
return
def register_functions_ns3_aodv(module, root_module):
return
def register_functions_ns3_dot11s(module, root_module):
return
def register_functions_ns3_dsdv(module, root_module):
return
def register_functions_ns3_flame(module, root_module):
return
def register_functions_ns3_internal(module, root_module):
return
def register_functions_ns3_olsr(module, root_module):
return
| gpl-2.0 |
epam-mooc/edx-platform | common/lib/capa/capa/customrender.py | 40 | 4429 | """
This has custom renderers: classes that know how to render certain problem tags (e.g. <math> and
<solution>) to html.
These tags do not have state, so they just get passed the system (for access to render_template),
and the xml element.
"""
from .registry import TagRegistry
import logging
import re
from cgi import escape as cgi_escape
from lxml import etree
import xml.sax.saxutils as saxutils
from .registry import TagRegistry
log = logging.getLogger(__name__)
registry = TagRegistry()
#-----------------------------------------------------------------------------
class MathRenderer(object):
tags = ['math']
def __init__(self, system, xml):
r"""
Render math using latex-like formatting.
Examples:
<math>$\displaystyle U(r)=4 U_0 $</math>
<math>$r_0$</math>
We convert these to [mathjax]...[/mathjax] and [mathjaxinline]...[/mathjaxinline]
TODO: use shorter tags (but this will require converting problem XML files!)
"""
self.system = system
self.xml = xml
mathstr = re.sub(r'\$(.*)\$', r'[mathjaxinline]\1[/mathjaxinline]', xml.text)
mtag = 'mathjax'
if not r'\displaystyle' in mathstr:
mtag += 'inline'
else:
mathstr = mathstr.replace(r'\displaystyle', '')
self.mathstr = mathstr.replace('mathjaxinline]', '%s]' % mtag)
def get_html(self):
"""
Return the contents of this tag, rendered to html, as an etree element.
"""
# TODO: why are there nested html tags here?? Why are there html tags at all, in fact?
html = '<html><html>%s</html><html>%s</html></html>' % (
self.mathstr, saxutils.escape(self.xml.tail))
try:
xhtml = etree.XML(html)
except Exception as err:
if self.system.DEBUG:
msg = '<html><div class="inline-error"><p>Error %s</p>' % (
str(err).replace('<', '<'))
msg += ('<p>Failed to construct math expression from <pre>%s</pre></p>' %
html.replace('<', '<'))
msg += "</div></html>"
log.error(msg)
return etree.XML(msg)
else:
raise
return xhtml
registry.register(MathRenderer)
#-----------------------------------------------------------------------------
class SolutionRenderer(object):
"""
A solution is just a <span>...</span> which is given an ID, that is used for displaying an
extended answer (a problem "solution") after "show answers" is pressed.
Note that the solution content is NOT rendered and returned in the HTML. It is obtained by an
ajax call.
"""
tags = ['solution']
def __init__(self, system, xml):
self.system = system
self.id = xml.get('id')
def get_html(self):
context = {'id': self.id}
html = self.system.render_template("solutionspan.html", context)
return etree.XML(html)
registry.register(SolutionRenderer)
#-----------------------------------------------------------------------------
class TargetedFeedbackRenderer(object):
"""
A targeted feedback is just a <span>...</span> that is used for displaying an
extended piece of feedback to students if they incorrectly answered a question.
"""
tags = ['targetedfeedback']
def __init__(self, system, xml):
self.system = system
self.xml = xml
def get_html(self):
"""
Return the contents of this tag, rendered to html, as an etree element.
"""
html = '<section class="targeted-feedback-span"><span>{}</span></section>'.format(etree.tostring(self.xml))
try:
xhtml = etree.XML(html)
except Exception as err: # pylint: disable=broad-except
if self.system.DEBUG:
msg = """
<html>
<div class="inline-error">
<p>Error {err}</p>
<p>Failed to construct targeted feedback from <pre>{html}</pre></p>
</div>
</html>
""".format(err=cgi_escape(err), html=cgi_escape(html))
log.error(msg)
return etree.XML(msg)
else:
raise
return xhtml
registry.register(TargetedFeedbackRenderer)
| agpl-3.0 |
mrbox/django | tests/admin_widgets/tests.py | 3 | 60012 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import gettext
import os
from datetime import datetime, timedelta
from importlib import import_module
from unittest import skipIf
from django import forms
from django.conf import settings
from django.contrib import admin
from django.contrib.admin import widgets
from django.contrib.admin.tests import AdminSeleniumWebDriverTestCase
from django.contrib.auth.models import User
from django.core.files.storage import default_storage
from django.core.files.uploadedfile import SimpleUploadedFile
from django.db.models import CharField, DateField
from django.test import SimpleTestCase, TestCase, override_settings
from django.urls import reverse
from django.utils import six, translation
from . import models
from .widgetadmin import site as widget_admin_site
try:
import pytz
except ImportError:
pytz = None
class TestDataMixin(object):
@classmethod
def setUpTestData(cls):
cls.u1 = User.objects.create(
pk=100, username='super', first_name='Super', last_name='User', email='super@example.com',
password='sha1$995a3$6011485ea3834267d719b4c801409b8b1ddd0158', is_active=True, is_superuser=True,
is_staff=True, last_login=datetime(2007, 5, 30, 13, 20, 10),
date_joined=datetime(2007, 5, 30, 13, 20, 10)
)
cls.u2 = User.objects.create(
pk=101, username='testser', first_name='Add', last_name='User', email='auser@example.com',
password='sha1$995a3$6011485ea3834267d719b4c801409b8b1ddd0158', is_active=True, is_superuser=False,
is_staff=True, last_login=datetime(2007, 5, 30, 13, 20, 10),
date_joined=datetime(2007, 5, 30, 13, 20, 10)
)
models.Car.objects.create(id=1, owner=cls.u1, make='Volkswagen', model='Passat')
models.Car.objects.create(id=2, owner=cls.u2, make='BMW', model='M3')
class SeleniumDataMixin(object):
def setUp(self):
self.u1 = User.objects.create(
pk=100, username='super', first_name='Super', last_name='User', email='super@example.com',
password='sha1$995a3$6011485ea3834267d719b4c801409b8b1ddd0158', is_active=True, is_superuser=True,
is_staff=True, last_login=datetime(2007, 5, 30, 13, 20, 10),
date_joined=datetime(2007, 5, 30, 13, 20, 10)
)
class AdminFormfieldForDBFieldTests(SimpleTestCase):
"""
Tests for correct behavior of ModelAdmin.formfield_for_dbfield
"""
def assertFormfield(self, model, fieldname, widgetclass, **admin_overrides):
"""
Helper to call formfield_for_dbfield for a given model and field name
and verify that the returned formfield is appropriate.
"""
# Override any settings on the model admin
class MyModelAdmin(admin.ModelAdmin):
pass
for k in admin_overrides:
setattr(MyModelAdmin, k, admin_overrides[k])
# Construct the admin, and ask it for a formfield
ma = MyModelAdmin(model, admin.site)
ff = ma.formfield_for_dbfield(model._meta.get_field(fieldname), request=None)
# "unwrap" the widget wrapper, if needed
if isinstance(ff.widget, widgets.RelatedFieldWidgetWrapper):
widget = ff.widget.widget
else:
widget = ff.widget
# Check that we got a field of the right type
self.assertTrue(
isinstance(widget, widgetclass),
"Wrong widget for %s.%s: expected %s, got %s" % (
model.__class__.__name__,
fieldname,
widgetclass,
type(widget),
)
)
# Return the formfield so that other tests can continue
return ff
def test_DateField(self):
self.assertFormfield(models.Event, 'start_date', widgets.AdminDateWidget)
def test_DateTimeField(self):
self.assertFormfield(models.Member, 'birthdate', widgets.AdminSplitDateTime)
def test_TimeField(self):
self.assertFormfield(models.Event, 'start_time', widgets.AdminTimeWidget)
def test_TextField(self):
self.assertFormfield(models.Event, 'description', widgets.AdminTextareaWidget)
def test_URLField(self):
self.assertFormfield(models.Event, 'link', widgets.AdminURLFieldWidget)
def test_IntegerField(self):
self.assertFormfield(models.Event, 'min_age', widgets.AdminIntegerFieldWidget)
def test_CharField(self):
self.assertFormfield(models.Member, 'name', widgets.AdminTextInputWidget)
def test_EmailField(self):
self.assertFormfield(models.Member, 'email', widgets.AdminEmailInputWidget)
def test_FileField(self):
self.assertFormfield(models.Album, 'cover_art', widgets.AdminFileWidget)
def test_ForeignKey(self):
self.assertFormfield(models.Event, 'main_band', forms.Select)
def test_raw_id_ForeignKey(self):
self.assertFormfield(models.Event, 'main_band', widgets.ForeignKeyRawIdWidget,
raw_id_fields=['main_band'])
def test_radio_fields_ForeignKey(self):
ff = self.assertFormfield(models.Event, 'main_band', widgets.AdminRadioSelect,
radio_fields={'main_band': admin.VERTICAL})
self.assertEqual(ff.empty_label, None)
def test_many_to_many(self):
self.assertFormfield(models.Band, 'members', forms.SelectMultiple)
def test_raw_id_many_to_many(self):
self.assertFormfield(models.Band, 'members', widgets.ManyToManyRawIdWidget,
raw_id_fields=['members'])
def test_filtered_many_to_many(self):
self.assertFormfield(models.Band, 'members', widgets.FilteredSelectMultiple,
filter_vertical=['members'])
def test_formfield_overrides(self):
self.assertFormfield(models.Event, 'start_date', forms.TextInput,
formfield_overrides={DateField: {'widget': forms.TextInput}})
def test_formfield_overrides_widget_instances(self):
"""
Test that widget instances in formfield_overrides are not shared between
different fields. (#19423)
"""
class BandAdmin(admin.ModelAdmin):
formfield_overrides = {
CharField: {'widget': forms.TextInput(attrs={'size': '10'})}
}
ma = BandAdmin(models.Band, admin.site)
f1 = ma.formfield_for_dbfield(models.Band._meta.get_field('name'), request=None)
f2 = ma.formfield_for_dbfield(models.Band._meta.get_field('style'), request=None)
self.assertNotEqual(f1.widget, f2.widget)
self.assertEqual(f1.widget.attrs['maxlength'], '100')
self.assertEqual(f2.widget.attrs['maxlength'], '20')
self.assertEqual(f2.widget.attrs['size'], '10')
def test_field_with_choices(self):
self.assertFormfield(models.Member, 'gender', forms.Select)
def test_choices_with_radio_fields(self):
self.assertFormfield(models.Member, 'gender', widgets.AdminRadioSelect,
radio_fields={'gender': admin.VERTICAL})
def test_inheritance(self):
self.assertFormfield(models.Album, 'backside_art', widgets.AdminFileWidget)
def test_m2m_widgets(self):
"""m2m fields help text as it applies to admin app (#9321)."""
class AdvisorAdmin(admin.ModelAdmin):
filter_vertical = ['companies']
self.assertFormfield(models.Advisor, 'companies', widgets.FilteredSelectMultiple,
filter_vertical=['companies'])
ma = AdvisorAdmin(models.Advisor, admin.site)
f = ma.formfield_for_dbfield(models.Advisor._meta.get_field('companies'), request=None)
self.assertEqual(
six.text_type(f.help_text),
'Hold down "Control", or "Command" on a Mac, to select more than one.'
)
@override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'],
ROOT_URLCONF='admin_widgets.urls')
class AdminFormfieldForDBFieldWithRequestTests(TestDataMixin, TestCase):
def test_filter_choices_by_request_user(self):
"""
Ensure the user can only see their own cars in the foreign key dropdown.
"""
self.client.login(username="super", password="secret")
response = self.client.get(reverse('admin:admin_widgets_cartire_add'))
self.assertNotContains(response, "BMW M3")
self.assertContains(response, "Volkswagen Passat")
@override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'],
ROOT_URLCONF='admin_widgets.urls')
class AdminForeignKeyWidgetChangeList(TestDataMixin, TestCase):
def setUp(self):
self.client.login(username="super", password="secret")
def test_changelist_ForeignKey(self):
response = self.client.get(reverse('admin:admin_widgets_car_changelist'))
self.assertContains(response, '/auth/user/add/')
@override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'],
ROOT_URLCONF='admin_widgets.urls')
class AdminForeignKeyRawIdWidget(TestDataMixin, TestCase):
def setUp(self):
self.client.login(username="super", password="secret")
def test_nonexistent_target_id(self):
band = models.Band.objects.create(name='Bogey Blues')
pk = band.pk
band.delete()
post_data = {
"main_band": '%s' % pk,
}
# Try posting with a non-existent pk in a raw id field: this
# should result in an error message, not a server exception.
response = self.client.post(reverse('admin:admin_widgets_event_add'), post_data)
self.assertContains(response,
'Select a valid choice. That choice is not one of the available choices.')
def test_invalid_target_id(self):
for test_str in ('Iñtërnâtiônàlizætiøn', "1234'", -1234):
# This should result in an error message, not a server exception.
response = self.client.post(reverse('admin:admin_widgets_event_add'),
{"main_band": test_str})
self.assertContains(response,
'Select a valid choice. That choice is not one of the available choices.')
def test_url_params_from_lookup_dict_any_iterable(self):
lookup1 = widgets.url_params_from_lookup_dict({'color__in': ('red', 'blue')})
lookup2 = widgets.url_params_from_lookup_dict({'color__in': ['red', 'blue']})
self.assertEqual(lookup1, {'color__in': 'red,blue'})
self.assertEqual(lookup1, lookup2)
def test_url_params_from_lookup_dict_callable(self):
def my_callable():
return 'works'
lookup1 = widgets.url_params_from_lookup_dict({'myfield': my_callable})
lookup2 = widgets.url_params_from_lookup_dict({'myfield': my_callable()})
self.assertEqual(lookup1, lookup2)
class FilteredSelectMultipleWidgetTest(SimpleTestCase):
def test_render(self):
# Backslash in verbose_name to ensure it is JavaScript escaped.
w = widgets.FilteredSelectMultiple('test\\', False)
self.assertHTMLEqual(
w.render('test', 'test'),
'<select multiple="multiple" name="test" class="selectfilter" '
'data-field-name="test\\" data-is-stacked="0">\n</select>'
)
def test_stacked_render(self):
# Backslash in verbose_name to ensure it is JavaScript escaped.
w = widgets.FilteredSelectMultiple('test\\', True)
self.assertHTMLEqual(
w.render('test', 'test'),
'<select multiple="multiple" name="test" class="selectfilterstacked" '
'data-field-name="test\\" data-is-stacked="1">\n</select>'
)
class AdminDateWidgetTest(SimpleTestCase):
def test_attrs(self):
"""
Ensure that user-supplied attrs are used.
Refs #12073.
"""
w = widgets.AdminDateWidget()
self.assertHTMLEqual(
w.render('test', datetime(2007, 12, 1, 9, 30)),
'<input value="2007-12-01" type="text" class="vDateField" name="test" size="10" />',
)
# pass attrs to widget
w = widgets.AdminDateWidget(attrs={'size': 20, 'class': 'myDateField'})
self.assertHTMLEqual(
w.render('test', datetime(2007, 12, 1, 9, 30)),
'<input value="2007-12-01" type="text" class="myDateField" name="test" size="20" />',
)
class AdminTimeWidgetTest(SimpleTestCase):
def test_attrs(self):
"""
Ensure that user-supplied attrs are used.
Refs #12073.
"""
w = widgets.AdminTimeWidget()
self.assertHTMLEqual(
w.render('test', datetime(2007, 12, 1, 9, 30)),
'<input value="09:30:00" type="text" class="vTimeField" name="test" size="8" />',
)
# pass attrs to widget
w = widgets.AdminTimeWidget(attrs={'size': 20, 'class': 'myTimeField'})
self.assertHTMLEqual(
w.render('test', datetime(2007, 12, 1, 9, 30)),
'<input value="09:30:00" type="text" class="myTimeField" name="test" size="20" />',
)
class AdminSplitDateTimeWidgetTest(SimpleTestCase):
def test_render(self):
w = widgets.AdminSplitDateTime()
self.assertHTMLEqual(
w.render('test', datetime(2007, 12, 1, 9, 30)),
'<p class="datetime">'
'Date: <input value="2007-12-01" type="text" class="vDateField" '
'name="test_0" size="10" /><br />'
'Time: <input value="09:30:00" type="text" class="vTimeField" '
'name="test_1" size="8" /></p>'
)
def test_localization(self):
w = widgets.AdminSplitDateTime()
with self.settings(USE_L10N=True), translation.override('de-at'):
w.is_localized = True
self.assertHTMLEqual(
w.render('test', datetime(2007, 12, 1, 9, 30)),
'<p class="datetime">'
'Datum: <input value="01.12.2007" type="text" '
'class="vDateField" name="test_0"size="10" /><br />'
'Zeit: <input value="09:30:00" type="text" class="vTimeField" '
'name="test_1" size="8" /></p>'
)
class AdminURLWidgetTest(SimpleTestCase):
def test_render(self):
w = widgets.AdminURLFieldWidget()
self.assertHTMLEqual(
w.render('test', ''),
'<input class="vURLField" name="test" type="url" />'
)
self.assertHTMLEqual(
w.render('test', 'http://example.com'),
'<p class="url">Currently:<a href="http://example.com">'
'http://example.com</a><br />'
'Change:<input class="vURLField" name="test" type="url" '
'value="http://example.com" /></p>'
)
def test_render_idn(self):
w = widgets.AdminURLFieldWidget()
self.assertHTMLEqual(
w.render('test', 'http://example-äüö.com'),
'<p class="url">Currently: <a href="http://xn--example--7za4pnc.com">'
'http://example-äüö.com</a><br />'
'Change:<input class="vURLField" name="test" type="url" '
'value="http://example-äüö.com" /></p>'
)
def test_render_quoting(self):
# WARNING: Don't use assertHTMLEqual in that testcase!
# assertHTMLEqual will get rid of some escapes which are tested here!
w = widgets.AdminURLFieldWidget()
self.assertEqual(
w.render('test', 'http://example.com/<sometag>some text</sometag>'),
'<p class="url">Currently: '
'<a href="http://example.com/%3Csometag%3Esome%20text%3C/sometag%3E">'
'http://example.com/<sometag>some text</sometag></a><br />'
'Change: <input class="vURLField" name="test" type="url" '
'value="http://example.com/<sometag>some text</sometag>" /></p>'
)
self.assertEqual(
w.render('test', 'http://example-äüö.com/<sometag>some text</sometag>'),
'<p class="url">Currently: '
'<a href="http://xn--example--7za4pnc.com/%3Csometag%3Esome%20text%3C/sometag%3E">'
'http://example-äüö.com/<sometag>some text</sometag></a><br />'
'Change: <input class="vURLField" name="test" type="url" '
'value="http://example-äüö.com/<sometag>some text</sometag>" /></p>'
)
self.assertEqual(
w.render('test', 'http://www.example.com/%C3%A4"><script>alert("XSS!")</script>"'),
'<p class="url">Currently: '
'<a href="http://www.example.com/%C3%A4%22%3E%3Cscript%3Ealert(%22XSS!%22)%3C/script%3E%22">'
'http://www.example.com/%C3%A4"><script>'
'alert("XSS!")</script>"</a><br />'
'Change: <input class="vURLField" name="test" type="url" '
'value="http://www.example.com/%C3%A4"><script>'
'alert("XSS!")</script>"" /></p>'
)
@override_settings(
PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'],
ROOT_URLCONF='admin_widgets.urls',
)
class AdminFileWidgetTests(TestDataMixin, TestCase):
@classmethod
def setUpTestData(cls):
super(AdminFileWidgetTests, cls).setUpTestData()
band = models.Band.objects.create(name='Linkin Park')
cls.album = band.album_set.create(
name='Hybrid Theory', cover_art=r'albums\hybrid_theory.jpg'
)
def test_render(self):
w = widgets.AdminFileWidget()
self.assertHTMLEqual(
w.render('test', self.album.cover_art),
'<p class="file-upload">Currently: <a href="%(STORAGE_URL)salbums/'
'hybrid_theory.jpg">albums\hybrid_theory.jpg</a> '
'<span class="clearable-file-input">'
'<input type="checkbox" name="test-clear" id="test-clear_id" /> '
'<label for="test-clear_id">Clear</label></span><br />'
'Change: <input type="file" name="test" /></p>' % {
'STORAGE_URL': default_storage.url(''),
},
)
self.assertHTMLEqual(
w.render('test', SimpleUploadedFile('test', b'content')),
'<input type="file" name="test" />',
)
def test_readonly_fields(self):
"""
File widgets should render as a link when they're marked "read only."
"""
self.client.login(username="super", password="secret")
response = self.client.get(reverse('admin:admin_widgets_album_change', args=(self.album.id,)))
self.assertContains(
response,
'<p><a href="%(STORAGE_URL)salbums/hybrid_theory.jpg">'
'albums\hybrid_theory.jpg</a></p>' % {'STORAGE_URL': default_storage.url('')},
html=True,
)
self.assertNotContains(
response,
'<input type="file" name="cover_art" id="id_cover_art" />',
html=True,
)
response = self.client.get(reverse('admin:admin_widgets_album_add'))
self.assertContains(
response,
'<p></p>',
html=True,
)
@override_settings(ROOT_URLCONF='admin_widgets.urls')
class ForeignKeyRawIdWidgetTest(TestCase):
def test_render(self):
band = models.Band.objects.create(name='Linkin Park')
band.album_set.create(
name='Hybrid Theory', cover_art=r'albums\hybrid_theory.jpg'
)
rel = models.Album._meta.get_field('band').remote_field
w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site)
self.assertHTMLEqual(
w.render('test', band.pk, attrs={}),
'<input type="text" name="test" value="%(bandpk)s" '
'class="vForeignKeyRawIdAdminField" />'
'<a href="/admin_widgets/band/?_to_field=id" class="related-lookup" '
'id="lookup_id_test" title="Lookup"></a> <strong>Linkin Park</strong>'
% {'bandpk': band.pk}
)
def test_relations_to_non_primary_key(self):
# Check that ForeignKeyRawIdWidget works with fields which aren't
# related to the model's primary key.
apple = models.Inventory.objects.create(barcode=86, name='Apple')
models.Inventory.objects.create(barcode=22, name='Pear')
core = models.Inventory.objects.create(
barcode=87, name='Core', parent=apple
)
rel = models.Inventory._meta.get_field('parent').remote_field
w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site)
self.assertHTMLEqual(
w.render('test', core.parent_id, attrs={}),
'<input type="text" name="test" value="86" '
'class="vForeignKeyRawIdAdminField" />'
'<a href="/admin_widgets/inventory/?_to_field=barcode" '
'class="related-lookup" id="lookup_id_test" title="Lookup"></a>'
' <strong>Apple</strong>'
)
def test_fk_related_model_not_in_admin(self):
# FK to a model not registered with admin site. Raw ID widget should
# have no magnifying glass link. See #16542
big_honeycomb = models.Honeycomb.objects.create(location='Old tree')
big_honeycomb.bee_set.create()
rel = models.Bee._meta.get_field('honeycomb').remote_field
w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site)
self.assertHTMLEqual(
w.render('honeycomb_widget', big_honeycomb.pk, attrs={}),
'<input type="text" name="honeycomb_widget" value="%(hcombpk)s" />'
' <strong>Honeycomb object</strong>'
% {'hcombpk': big_honeycomb.pk}
)
def test_fk_to_self_model_not_in_admin(self):
# FK to self, not registered with admin site. Raw ID widget should have
# no magnifying glass link. See #16542
subject1 = models.Individual.objects.create(name='Subject #1')
models.Individual.objects.create(name='Child', parent=subject1)
rel = models.Individual._meta.get_field('parent').remote_field
w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site)
self.assertHTMLEqual(
w.render('individual_widget', subject1.pk, attrs={}),
'<input type="text" name="individual_widget" value="%(subj1pk)s" />'
' <strong>Individual object</strong>'
% {'subj1pk': subject1.pk}
)
def test_proper_manager_for_label_lookup(self):
# see #9258
rel = models.Inventory._meta.get_field('parent').remote_field
w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site)
hidden = models.Inventory.objects.create(
barcode=93, name='Hidden', hidden=True
)
child_of_hidden = models.Inventory.objects.create(
barcode=94, name='Child of hidden', parent=hidden
)
self.assertHTMLEqual(
w.render('test', child_of_hidden.parent_id, attrs={}),
'<input type="text" name="test" value="93" class="vForeignKeyRawIdAdminField" />'
'<a href="/admin_widgets/inventory/?_to_field=barcode" '
'class="related-lookup" id="lookup_id_test" title="Lookup"></a>'
' <strong>Hidden</strong>'
)
@override_settings(ROOT_URLCONF='admin_widgets.urls')
class ManyToManyRawIdWidgetTest(TestCase):
def test_render(self):
band = models.Band.objects.create(name='Linkin Park')
m1 = models.Member.objects.create(name='Chester')
m2 = models.Member.objects.create(name='Mike')
band.members.add(m1, m2)
rel = models.Band._meta.get_field('members').remote_field
w = widgets.ManyToManyRawIdWidget(rel, widget_admin_site)
self.assertHTMLEqual(
w.render('test', [m1.pk, m2.pk], attrs={}), (
'<input type="text" name="test" value="%(m1pk)s,%(m2pk)s" class="vManyToManyRawIdAdminField" />'
'<a href="/admin_widgets/member/" class="related-lookup" id="lookup_id_test" title="Lookup"></a>'
) % dict(m1pk=m1.pk, m2pk=m2.pk)
)
self.assertHTMLEqual(
w.render('test', [m1.pk]), (
'<input type="text" name="test" value="%(m1pk)s" class="vManyToManyRawIdAdminField">'
'<a href="/admin_widgets/member/" class="related-lookup" id="lookup_id_test" title="Lookup"></a>'
) % dict(m1pk=m1.pk)
)
def test_m2m_related_model_not_in_admin(self):
# M2M relationship with model not registered with admin site. Raw ID
# widget should have no magnifying glass link. See #16542
consultor1 = models.Advisor.objects.create(name='Rockstar Techie')
c1 = models.Company.objects.create(name='Doodle')
c2 = models.Company.objects.create(name='Pear')
consultor1.companies.add(c1, c2)
rel = models.Advisor._meta.get_field('companies').remote_field
w = widgets.ManyToManyRawIdWidget(rel, widget_admin_site)
self.assertHTMLEqual(
w.render('company_widget1', [c1.pk, c2.pk], attrs={}),
'<input type="text" name="company_widget1" value="%(c1pk)s,%(c2pk)s" />' % {'c1pk': c1.pk, 'c2pk': c2.pk}
)
self.assertHTMLEqual(
w.render('company_widget2', [c1.pk]),
'<input type="text" name="company_widget2" value="%(c1pk)s" />' % {'c1pk': c1.pk}
)
class RelatedFieldWidgetWrapperTests(SimpleTestCase):
def test_no_can_add_related(self):
rel = models.Individual._meta.get_field('parent').remote_field
w = widgets.AdminRadioSelect()
# Used to fail with a name error.
w = widgets.RelatedFieldWidgetWrapper(w, rel, widget_admin_site)
self.assertFalse(w.can_add_related)
def test_select_multiple_widget_cant_change_delete_related(self):
rel = models.Individual._meta.get_field('parent').remote_field
widget = forms.SelectMultiple()
wrapper = widgets.RelatedFieldWidgetWrapper(
widget, rel, widget_admin_site,
can_add_related=True,
can_change_related=True,
can_delete_related=True,
)
self.assertTrue(wrapper.can_add_related)
self.assertFalse(wrapper.can_change_related)
self.assertFalse(wrapper.can_delete_related)
def test_on_delete_cascade_rel_cant_delete_related(self):
rel = models.Individual._meta.get_field('soulmate').remote_field
widget = forms.Select()
wrapper = widgets.RelatedFieldWidgetWrapper(
widget, rel, widget_admin_site,
can_add_related=True,
can_change_related=True,
can_delete_related=True,
)
self.assertTrue(wrapper.can_add_related)
self.assertTrue(wrapper.can_change_related)
self.assertFalse(wrapper.can_delete_related)
@override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'],
ROOT_URLCONF='admin_widgets.urls')
class DateTimePickerSeleniumFirefoxTests(SeleniumDataMixin, AdminSeleniumWebDriverTestCase):
available_apps = ['admin_widgets'] + AdminSeleniumWebDriverTestCase.available_apps
webdriver_class = 'selenium.webdriver.firefox.webdriver.WebDriver'
def test_show_hide_date_time_picker_widgets(self):
"""
Ensure that pressing the ESC key closes the date and time picker
widgets.
Refs #17064.
"""
from selenium.webdriver.common.keys import Keys
self.admin_login(username='super', password='secret', login_url='/')
# Open a page that has a date and time picker widgets
self.selenium.get('%s%s' % (self.live_server_url,
reverse('admin:admin_widgets_member_add')))
# First, with the date picker widget ---------------------------------
# Check that the date picker is hidden
self.assertEqual(
self.get_css_value('#calendarbox0', 'display'), 'none')
# Click the calendar icon
self.selenium.find_element_by_id('calendarlink0').click()
# Check that the date picker is visible
self.assertEqual(
self.get_css_value('#calendarbox0', 'display'), 'block')
# Press the ESC key
self.selenium.find_element_by_tag_name('body').send_keys([Keys.ESCAPE])
# Check that the date picker is hidden again
self.assertEqual(
self.get_css_value('#calendarbox0', 'display'), 'none')
# Then, with the time picker widget ----------------------------------
# Check that the time picker is hidden
self.assertEqual(
self.get_css_value('#clockbox0', 'display'), 'none')
# Click the time icon
self.selenium.find_element_by_id('clocklink0').click()
# Check that the time picker is visible
self.assertEqual(
self.get_css_value('#clockbox0', 'display'), 'block')
self.assertEqual(
[
x.text for x in
self.selenium.find_elements_by_xpath("//ul[@class='timelist']/li/a")
],
['Now', 'Midnight', '6 a.m.', 'Noon', '6 p.m.']
)
# Press the ESC key
self.selenium.find_element_by_tag_name('body').send_keys([Keys.ESCAPE])
# Check that the time picker is hidden again
self.assertEqual(
self.get_css_value('#clockbox0', 'display'), 'none')
def test_calendar_nonday_class(self):
"""
Ensure cells that are not days of the month have the `nonday` CSS class.
Refs #4574.
"""
self.admin_login(username='super', password='secret', login_url='/')
# Open a page that has a date and time picker widgets
self.selenium.get('%s%s' % (self.live_server_url,
reverse('admin:admin_widgets_member_add')))
# fill in the birth date.
self.selenium.find_element_by_id('id_birthdate_0').send_keys('2013-06-01')
# Click the calendar icon
self.selenium.find_element_by_id('calendarlink0').click()
# get all the tds within the calendar
calendar0 = self.selenium.find_element_by_id('calendarin0')
tds = calendar0.find_elements_by_tag_name('td')
# make sure the first and last 6 cells have class nonday
for td in tds[:6] + tds[-6:]:
self.assertEqual(td.get_attribute('class'), 'nonday')
def test_calendar_selected_class(self):
"""
Ensure cell for the day in the input has the `selected` CSS class.
Refs #4574.
"""
self.admin_login(username='super', password='secret', login_url='/')
# Open a page that has a date and time picker widgets
self.selenium.get('%s%s' % (self.live_server_url,
reverse('admin:admin_widgets_member_add')))
# fill in the birth date.
self.selenium.find_element_by_id('id_birthdate_0').send_keys('2013-06-01')
# Click the calendar icon
self.selenium.find_element_by_id('calendarlink0').click()
# get all the tds within the calendar
calendar0 = self.selenium.find_element_by_id('calendarin0')
tds = calendar0.find_elements_by_tag_name('td')
# verify the selected cell
selected = tds[6]
self.assertEqual(selected.get_attribute('class'), 'selected')
self.assertEqual(selected.text, '1')
def test_calendar_no_selected_class(self):
"""
Ensure no cells are given the selected class when the field is empty.
Refs #4574.
"""
self.admin_login(username='super', password='secret', login_url='/')
# Open a page that has a date and time picker widgets
self.selenium.get('%s%s' % (self.live_server_url,
reverse('admin:admin_widgets_member_add')))
# Click the calendar icon
self.selenium.find_element_by_id('calendarlink0').click()
# get all the tds within the calendar
calendar0 = self.selenium.find_element_by_id('calendarin0')
tds = calendar0.find_elements_by_tag_name('td')
# verify there are no cells with the selected class
selected = [td for td in tds if td.get_attribute('class') == 'selected']
self.assertEqual(len(selected), 0)
def test_calendar_show_date_from_input(self):
"""
Ensure that the calendar show the date from the input field for every
locale supported by django.
"""
self.admin_login(username='super', password='secret', login_url='/')
# Enter test data
member = models.Member.objects.create(name='Bob', birthdate=datetime(1984, 5, 15), gender='M')
# Get month name translations for every locale
month_string = 'May'
path = os.path.join(os.path.dirname(import_module('django.contrib.admin').__file__), 'locale')
for language_code, language_name in settings.LANGUAGES:
try:
catalog = gettext.translation('djangojs', path, [language_code])
except IOError:
continue
if month_string in catalog._catalog:
month_name = catalog._catalog[month_string]
else:
month_name = month_string
# Get the expected caption
may_translation = month_name
expected_caption = '{0:s} {1:d}'.format(may_translation.upper(), 1984)
# Test with every locale
with override_settings(LANGUAGE_CODE=language_code, USE_L10N=True):
# Open a page that has a date picker widget
self.selenium.get('{}{}'.format(self.live_server_url,
reverse('admin:admin_widgets_member_change', args=(member.pk,))))
# Click on the calendar icon
self.selenium.find_element_by_id('calendarlink0').click()
# Make sure that the right month and year are displayed
self.wait_for_text('#calendarin0 caption', expected_caption)
class DateTimePickerSeleniumChromeTests(DateTimePickerSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver'
class DateTimePickerSeleniumIETests(DateTimePickerSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver'
@skipIf(pytz is None, "this test requires pytz")
@override_settings(TIME_ZONE='Asia/Singapore')
@override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'],
ROOT_URLCONF='admin_widgets.urls')
class DateTimePickerShortcutsSeleniumFirefoxTests(SeleniumDataMixin, AdminSeleniumWebDriverTestCase):
available_apps = ['admin_widgets'] + AdminSeleniumWebDriverTestCase.available_apps
webdriver_class = 'selenium.webdriver.firefox.webdriver.WebDriver'
def test_date_time_picker_shortcuts(self):
"""
Ensure that date/time/datetime picker shortcuts work in the current time zone.
Refs #20663.
This test case is fairly tricky, it relies on selenium still running the browser
in the default time zone "America/Chicago" despite `override_settings` changing
the time zone to "Asia/Singapore".
"""
self.admin_login(username='super', password='secret', login_url='/')
error_margin = timedelta(seconds=10)
# If we are neighbouring a DST, we add an hour of error margin.
tz = pytz.timezone('America/Chicago')
utc_now = datetime.now(pytz.utc)
tz_yesterday = (utc_now - timedelta(days=1)).astimezone(tz).tzname()
tz_tomorrow = (utc_now + timedelta(days=1)).astimezone(tz).tzname()
if tz_yesterday != tz_tomorrow:
error_margin += timedelta(hours=1)
now = datetime.now()
self.selenium.get('%s%s' % (self.live_server_url,
reverse('admin:admin_widgets_member_add')))
self.selenium.find_element_by_id('id_name').send_keys('test')
# Click on the "today" and "now" shortcuts.
shortcuts = self.selenium.find_elements_by_css_selector(
'.field-birthdate .datetimeshortcuts')
for shortcut in shortcuts:
shortcut.find_element_by_tag_name('a').click()
# Check that there is a time zone mismatch warning.
# Warning: This would effectively fail if the TIME_ZONE defined in the
# settings has the same UTC offset as "Asia/Singapore" because the
# mismatch warning would be rightfully missing from the page.
self.selenium.find_elements_by_css_selector(
'.field-birthdate .timezonewarning')
# Submit the form.
self.selenium.find_element_by_tag_name('form').submit()
self.wait_page_loaded()
# Make sure that "now" in javascript is within 10 seconds
# from "now" on the server side.
member = models.Member.objects.get(name='test')
self.assertGreater(member.birthdate, now - error_margin)
self.assertLess(member.birthdate, now + error_margin)
class DateTimePickerShortcutsSeleniumChromeTests(DateTimePickerShortcutsSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver'
class DateTimePickerShortcutsSeleniumIETests(DateTimePickerShortcutsSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver'
# The above tests run with Asia/Singapore which are on the positive side of
# UTC. Here we test with a timezone on the negative side.
@override_settings(TIME_ZONE='US/Eastern')
class DateTimePickerAltTimezoneSeleniumFirefoxTests(DateTimePickerShortcutsSeleniumFirefoxTests):
pass
class DateTimePickerAltTimezoneSeleniumChromeTests(DateTimePickerAltTimezoneSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver'
class DateTimePickerAltTimezoneSeleniumIETests(DateTimePickerAltTimezoneSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver'
@override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'],
ROOT_URLCONF='admin_widgets.urls')
class HorizontalVerticalFilterSeleniumFirefoxTests(SeleniumDataMixin, AdminSeleniumWebDriverTestCase):
available_apps = ['admin_widgets'] + AdminSeleniumWebDriverTestCase.available_apps
webdriver_class = 'selenium.webdriver.firefox.webdriver.WebDriver'
def setUp(self):
super(HorizontalVerticalFilterSeleniumFirefoxTests, self).setUp()
self.lisa = models.Student.objects.create(name='Lisa')
self.john = models.Student.objects.create(name='John')
self.bob = models.Student.objects.create(name='Bob')
self.peter = models.Student.objects.create(name='Peter')
self.jenny = models.Student.objects.create(name='Jenny')
self.jason = models.Student.objects.create(name='Jason')
self.cliff = models.Student.objects.create(name='Cliff')
self.arthur = models.Student.objects.create(name='Arthur')
self.school = models.School.objects.create(name='School of Awesome')
def assertActiveButtons(self, mode, field_name, choose, remove,
choose_all=None, remove_all=None):
choose_link = '#id_%s_add_link' % field_name
choose_all_link = '#id_%s_add_all_link' % field_name
remove_link = '#id_%s_remove_link' % field_name
remove_all_link = '#id_%s_remove_all_link' % field_name
self.assertEqual(self.has_css_class(choose_link, 'active'), choose)
self.assertEqual(self.has_css_class(remove_link, 'active'), remove)
if mode == 'horizontal':
self.assertEqual(self.has_css_class(choose_all_link, 'active'), choose_all)
self.assertEqual(self.has_css_class(remove_all_link, 'active'), remove_all)
def execute_basic_operations(self, mode, field_name):
from_box = '#id_%s_from' % field_name
to_box = '#id_%s_to' % field_name
choose_link = 'id_%s_add_link' % field_name
choose_all_link = 'id_%s_add_all_link' % field_name
remove_link = 'id_%s_remove_link' % field_name
remove_all_link = 'id_%s_remove_all_link' % field_name
# Initial positions ---------------------------------------------------
self.assertSelectOptions(from_box,
[str(self.arthur.id), str(self.bob.id),
str(self.cliff.id), str(self.jason.id),
str(self.jenny.id), str(self.john.id)])
self.assertSelectOptions(to_box,
[str(self.lisa.id), str(self.peter.id)])
self.assertActiveButtons(mode, field_name, False, False, True, True)
# Click 'Choose all' --------------------------------------------------
if mode == 'horizontal':
self.selenium.find_element_by_id(choose_all_link).click()
elif mode == 'vertical':
# There 's no 'Choose all' button in vertical mode, so individually
# select all options and click 'Choose'.
for option in self.selenium.find_elements_by_css_selector(from_box + ' > option'):
option.click()
self.selenium.find_element_by_id(choose_link).click()
self.assertSelectOptions(from_box, [])
self.assertSelectOptions(to_box,
[str(self.lisa.id), str(self.peter.id),
str(self.arthur.id), str(self.bob.id),
str(self.cliff.id), str(self.jason.id),
str(self.jenny.id), str(self.john.id)])
self.assertActiveButtons(mode, field_name, False, False, False, True)
# Click 'Remove all' --------------------------------------------------
if mode == 'horizontal':
self.selenium.find_element_by_id(remove_all_link).click()
elif mode == 'vertical':
# There 's no 'Remove all' button in vertical mode, so individually
# select all options and click 'Remove'.
for option in self.selenium.find_elements_by_css_selector(to_box + ' > option'):
option.click()
self.selenium.find_element_by_id(remove_link).click()
self.assertSelectOptions(from_box,
[str(self.lisa.id), str(self.peter.id),
str(self.arthur.id), str(self.bob.id),
str(self.cliff.id), str(self.jason.id),
str(self.jenny.id), str(self.john.id)])
self.assertSelectOptions(to_box, [])
self.assertActiveButtons(mode, field_name, False, False, True, False)
# Choose some options ------------------------------------------------
from_lisa_select_option = self.get_select_option(from_box, str(self.lisa.id))
# Check the title attribute is there for tool tips: ticket #20821
self.assertEqual(from_lisa_select_option.get_attribute('title'), from_lisa_select_option.get_attribute('text'))
from_lisa_select_option.click()
self.get_select_option(from_box, str(self.jason.id)).click()
self.get_select_option(from_box, str(self.bob.id)).click()
self.get_select_option(from_box, str(self.john.id)).click()
self.assertActiveButtons(mode, field_name, True, False, True, False)
self.selenium.find_element_by_id(choose_link).click()
self.assertActiveButtons(mode, field_name, False, False, True, True)
self.assertSelectOptions(from_box,
[str(self.peter.id), str(self.arthur.id),
str(self.cliff.id), str(self.jenny.id)])
self.assertSelectOptions(to_box,
[str(self.lisa.id), str(self.bob.id),
str(self.jason.id), str(self.john.id)])
# Check the tooltip is still there after moving: ticket #20821
to_lisa_select_option = self.get_select_option(to_box, str(self.lisa.id))
self.assertEqual(to_lisa_select_option.get_attribute('title'), to_lisa_select_option.get_attribute('text'))
# Remove some options -------------------------------------------------
self.get_select_option(to_box, str(self.lisa.id)).click()
self.get_select_option(to_box, str(self.bob.id)).click()
self.assertActiveButtons(mode, field_name, False, True, True, True)
self.selenium.find_element_by_id(remove_link).click()
self.assertActiveButtons(mode, field_name, False, False, True, True)
self.assertSelectOptions(from_box,
[str(self.peter.id), str(self.arthur.id),
str(self.cliff.id), str(self.jenny.id),
str(self.lisa.id), str(self.bob.id)])
self.assertSelectOptions(to_box,
[str(self.jason.id), str(self.john.id)])
# Choose some more options --------------------------------------------
self.get_select_option(from_box, str(self.arthur.id)).click()
self.get_select_option(from_box, str(self.cliff.id)).click()
self.selenium.find_element_by_id(choose_link).click()
self.assertSelectOptions(from_box,
[str(self.peter.id), str(self.jenny.id),
str(self.lisa.id), str(self.bob.id)])
self.assertSelectOptions(to_box,
[str(self.jason.id), str(self.john.id),
str(self.arthur.id), str(self.cliff.id)])
def test_basic(self):
self.school.students.set([self.lisa, self.peter])
self.school.alumni.set([self.lisa, self.peter])
self.admin_login(username='super', password='secret', login_url='/')
self.selenium.get('%s%s' % (
self.live_server_url, reverse('admin:admin_widgets_school_change', args=(self.school.id,))))
self.wait_page_loaded()
self.execute_basic_operations('vertical', 'students')
self.execute_basic_operations('horizontal', 'alumni')
# Save and check that everything is properly stored in the database ---
self.selenium.find_element_by_xpath('//input[@value="Save"]').click()
self.wait_page_loaded()
self.school = models.School.objects.get(id=self.school.id) # Reload from database
self.assertEqual(list(self.school.students.all()),
[self.arthur, self.cliff, self.jason, self.john])
self.assertEqual(list(self.school.alumni.all()),
[self.arthur, self.cliff, self.jason, self.john])
def test_filter(self):
"""
Ensure that typing in the search box filters out options displayed in
the 'from' box.
"""
from selenium.webdriver.common.keys import Keys
self.school.students.set([self.lisa, self.peter])
self.school.alumni.set([self.lisa, self.peter])
self.admin_login(username='super', password='secret', login_url='/')
self.selenium.get(
'%s%s' % (self.live_server_url, reverse('admin:admin_widgets_school_change', args=(self.school.id,))))
for field_name in ['students', 'alumni']:
from_box = '#id_%s_from' % field_name
to_box = '#id_%s_to' % field_name
choose_link = '#id_%s_add_link' % field_name
remove_link = '#id_%s_remove_link' % field_name
input = self.selenium.find_element_by_css_selector('#id_%s_input' % field_name)
# Initial values
self.assertSelectOptions(from_box,
[str(self.arthur.id), str(self.bob.id),
str(self.cliff.id), str(self.jason.id),
str(self.jenny.id), str(self.john.id)])
# Typing in some characters filters out non-matching options
input.send_keys('a')
self.assertSelectOptions(from_box, [str(self.arthur.id), str(self.jason.id)])
input.send_keys('R')
self.assertSelectOptions(from_box, [str(self.arthur.id)])
# Clearing the text box makes the other options reappear
input.send_keys([Keys.BACK_SPACE])
self.assertSelectOptions(from_box, [str(self.arthur.id), str(self.jason.id)])
input.send_keys([Keys.BACK_SPACE])
self.assertSelectOptions(from_box,
[str(self.arthur.id), str(self.bob.id),
str(self.cliff.id), str(self.jason.id),
str(self.jenny.id), str(self.john.id)])
# -----------------------------------------------------------------
# Check that choosing a filtered option sends it properly to the
# 'to' box.
input.send_keys('a')
self.assertSelectOptions(from_box, [str(self.arthur.id), str(self.jason.id)])
self.get_select_option(from_box, str(self.jason.id)).click()
self.selenium.find_element_by_css_selector(choose_link).click()
self.assertSelectOptions(from_box, [str(self.arthur.id)])
self.assertSelectOptions(to_box,
[str(self.lisa.id), str(self.peter.id),
str(self.jason.id)])
self.get_select_option(to_box, str(self.lisa.id)).click()
self.selenium.find_element_by_css_selector(remove_link).click()
self.assertSelectOptions(from_box,
[str(self.arthur.id), str(self.lisa.id)])
self.assertSelectOptions(to_box,
[str(self.peter.id), str(self.jason.id)])
input.send_keys([Keys.BACK_SPACE]) # Clear text box
self.assertSelectOptions(from_box,
[str(self.arthur.id), str(self.bob.id),
str(self.cliff.id), str(self.jenny.id),
str(self.john.id), str(self.lisa.id)])
self.assertSelectOptions(to_box,
[str(self.peter.id), str(self.jason.id)])
# -----------------------------------------------------------------
# Check that pressing enter on a filtered option sends it properly
# to the 'to' box.
self.get_select_option(to_box, str(self.jason.id)).click()
self.selenium.find_element_by_css_selector(remove_link).click()
input.send_keys('ja')
self.assertSelectOptions(from_box, [str(self.jason.id)])
input.send_keys([Keys.ENTER])
self.assertSelectOptions(to_box, [str(self.peter.id), str(self.jason.id)])
input.send_keys([Keys.BACK_SPACE, Keys.BACK_SPACE])
# Save and check that everything is properly stored in the database ---
self.selenium.find_element_by_xpath('//input[@value="Save"]').click()
self.wait_page_loaded()
self.school = models.School.objects.get(id=self.school.id) # Reload from database
self.assertEqual(list(self.school.students.all()),
[self.jason, self.peter])
self.assertEqual(list(self.school.alumni.all()),
[self.jason, self.peter])
def test_back_button_bug(self):
"""
Some browsers had a bug where navigating away from the change page
and then clicking the browser's back button would clear the
filter_horizontal/filter_vertical widgets (#13614).
"""
self.school.students.set([self.lisa, self.peter])
self.school.alumni.set([self.lisa, self.peter])
self.admin_login(username='super', password='secret', login_url='/')
change_url = reverse('admin:admin_widgets_school_change', args=(self.school.id,))
self.selenium.get(self.live_server_url + change_url)
# Navigate away and go back to the change form page.
self.selenium.find_element_by_link_text('Home').click()
self.selenium.back()
self.wait_for('#id_students_from')
expected_unselected_values = [
str(self.arthur.id), str(self.bob.id), str(self.cliff.id),
str(self.jason.id), str(self.jenny.id), str(self.john.id),
]
expected_selected_values = [str(self.lisa.id), str(self.peter.id)]
# Check that everything is still in place
self.assertSelectOptions('#id_students_from', expected_unselected_values)
self.assertSelectOptions('#id_students_to', expected_selected_values)
self.assertSelectOptions('#id_alumni_from', expected_unselected_values)
self.assertSelectOptions('#id_alumni_to', expected_selected_values)
class HorizontalVerticalFilterSeleniumChromeTests(HorizontalVerticalFilterSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver'
class HorizontalVerticalFilterSeleniumIETests(HorizontalVerticalFilterSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver'
@override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'],
ROOT_URLCONF='admin_widgets.urls')
class AdminRawIdWidgetSeleniumFirefoxTests(SeleniumDataMixin, AdminSeleniumWebDriverTestCase):
available_apps = ['admin_widgets'] + AdminSeleniumWebDriverTestCase.available_apps
webdriver_class = 'selenium.webdriver.firefox.webdriver.WebDriver'
def setUp(self):
super(AdminRawIdWidgetSeleniumFirefoxTests, self).setUp()
models.Band.objects.create(id=42, name='Bogey Blues')
models.Band.objects.create(id=98, name='Green Potatoes')
def test_ForeignKey(self):
self.admin_login(username='super', password='secret', login_url='/')
self.selenium.get(
'%s%s' % (self.live_server_url, reverse('admin:admin_widgets_event_add')))
main_window = self.selenium.current_window_handle
# No value has been selected yet
self.assertEqual(
self.selenium.find_element_by_id('id_main_band').get_attribute('value'),
'')
# Open the popup window and click on a band
self.selenium.find_element_by_id('lookup_id_main_band').click()
self.wait_for_popup()
self.selenium.switch_to.window('id_main_band')
link = self.selenium.find_element_by_link_text('Bogey Blues')
self.assertIn('/band/42/', link.get_attribute('href'))
link.click()
# The field now contains the selected band's id
self.selenium.switch_to.window(main_window)
self.wait_for_value('#id_main_band', '42')
# Reopen the popup window and click on another band
self.selenium.find_element_by_id('lookup_id_main_band').click()
self.wait_for_popup()
self.selenium.switch_to.window('id_main_band')
link = self.selenium.find_element_by_link_text('Green Potatoes')
self.assertIn('/band/98/', link.get_attribute('href'))
link.click()
# The field now contains the other selected band's id
self.selenium.switch_to.window(main_window)
self.wait_for_value('#id_main_band', '98')
def test_many_to_many(self):
self.admin_login(username='super', password='secret', login_url='/')
self.selenium.get(
'%s%s' % (self.live_server_url, reverse('admin:admin_widgets_event_add')))
main_window = self.selenium.current_window_handle
# No value has been selected yet
self.assertEqual(
self.selenium.find_element_by_id('id_supporting_bands').get_attribute('value'),
'')
# Open the popup window and click on a band
self.selenium.find_element_by_id('lookup_id_supporting_bands').click()
self.wait_for_popup()
self.selenium.switch_to.window('id_supporting_bands')
link = self.selenium.find_element_by_link_text('Bogey Blues')
self.assertIn('/band/42/', link.get_attribute('href'))
link.click()
# The field now contains the selected band's id
self.selenium.switch_to.window(main_window)
self.wait_for_value('#id_supporting_bands', '42')
# Reopen the popup window and click on another band
self.selenium.find_element_by_id('lookup_id_supporting_bands').click()
self.wait_for_popup()
self.selenium.switch_to.window('id_supporting_bands')
link = self.selenium.find_element_by_link_text('Green Potatoes')
self.assertIn('/band/98/', link.get_attribute('href'))
link.click()
# The field now contains the two selected bands' ids
self.selenium.switch_to.window(main_window)
self.wait_for_value('#id_supporting_bands', '42,98')
class AdminRawIdWidgetSeleniumChromeTests(AdminRawIdWidgetSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver'
class AdminRawIdWidgetSeleniumIETests(AdminRawIdWidgetSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver'
@override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'],
ROOT_URLCONF='admin_widgets.urls')
class RelatedFieldWidgetSeleniumFirefoxTests(SeleniumDataMixin, AdminSeleniumWebDriverTestCase):
available_apps = ['admin_widgets'] + AdminSeleniumWebDriverTestCase.available_apps
webdriver_class = 'selenium.webdriver.firefox.webdriver.WebDriver'
def test_ForeignKey_using_to_field(self):
self.admin_login(username='super', password='secret', login_url='/')
self.selenium.get('%s%s' % (
self.live_server_url,
reverse('admin:admin_widgets_profile_add')))
main_window = self.selenium.current_window_handle
# Click the Add User button to add new
self.selenium.find_element_by_id('add_id_user').click()
self.wait_for_popup()
self.selenium.switch_to.window('id_user')
self.wait_for('#id_password')
password_field = self.selenium.find_element_by_id('id_password')
password_field.send_keys('password')
username_field = self.selenium.find_element_by_id('id_username')
username_value = 'newuser'
username_field.send_keys(username_value)
save_button_css_selector = '.submit-row > input[type=submit]'
self.selenium.find_element_by_css_selector(save_button_css_selector).click()
self.selenium.switch_to.window(main_window)
# The field now contains the new user
self.wait_for('#id_user option[value="newuser"]')
# Click the Change User button to change it
self.selenium.find_element_by_id('change_id_user').click()
self.wait_for_popup()
self.selenium.switch_to.window('id_user')
self.wait_for('#id_username')
username_field = self.selenium.find_element_by_id('id_username')
username_value = 'changednewuser'
username_field.clear()
username_field.send_keys(username_value)
save_button_css_selector = '.submit-row > input[type=submit]'
self.selenium.find_element_by_css_selector(save_button_css_selector).click()
self.selenium.switch_to.window(main_window)
# Wait up to 2 seconds for the new option to show up after clicking save in the popup.
self.selenium.implicitly_wait(2)
self.selenium.find_element_by_css_selector('#id_user option[value=changednewuser]')
self.selenium.implicitly_wait(0)
# Go ahead and submit the form to make sure it works
self.selenium.find_element_by_css_selector(save_button_css_selector).click()
self.wait_for_text('li.success', 'The profile "changednewuser" was added successfully.')
profiles = models.Profile.objects.all()
self.assertEqual(len(profiles), 1)
self.assertEqual(profiles[0].user.username, username_value)
class RelatedFieldWidgetSeleniumChromeTests(RelatedFieldWidgetSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver'
class RelatedFieldWidgetSeleniumIETests(RelatedFieldWidgetSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver'
| bsd-3-clause |
raajitr/django_hangman | env/lib/python2.7/site-packages/pip/_vendor/html5lib/_ihatexml.py | 354 | 16705 | 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]') # noqa
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]') # noqa
# 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,
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):
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("--", "- -")
if data.endswith("-"):
warnings.warn("Comments cannot end in a dash", DataLossWarning)
data += " "
return data
def coerceCharacters(self, data):
if self.replaceFormFeedCharacters:
for _ 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))
| mit |
Ballz0fSteel/Umeko | lib/youtube_dl/extractor/dfb.py | 87 | 2255 | from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import unified_strdate
class DFBIE(InfoExtractor):
IE_NAME = 'tv.dfb.de'
_VALID_URL = r'https?://tv\.dfb\.de/video/(?P<display_id>[^/]+)/(?P<id>\d+)'
_TEST = {
'url': 'http://tv.dfb.de/video/u-19-em-stimmen-zum-spiel-gegen-russland/11633/',
'md5': 'ac0f98a52a330f700b4b3034ad240649',
'info_dict': {
'id': '11633',
'display_id': 'u-19-em-stimmen-zum-spiel-gegen-russland',
'ext': 'mp4',
'title': 'U 19-EM: Stimmen zum Spiel gegen Russland',
'upload_date': '20150714',
},
}
def _real_extract(self, url):
display_id, video_id = re.match(self._VALID_URL, url).groups()
player_info = self._download_xml(
'http://tv.dfb.de/server/hd_video.php?play=%s' % video_id,
display_id)
video_info = player_info.find('video')
stream_access_url = self._proto_relative_url(video_info.find('url').text.strip())
formats = []
# see http://tv.dfb.de/player/js/ajax.js for the method to extract m3u8 formats
for sa_url in (stream_access_url, stream_access_url + '&area=&format=iphone'):
stream_access_info = self._download_xml(sa_url, display_id)
token_el = stream_access_info.find('token')
manifest_url = token_el.attrib['url'] + '?' + 'hdnea=' + token_el.attrib['auth']
if '.f4m' in manifest_url:
formats.extend(self._extract_f4m_formats(
manifest_url + '&hdcore=3.2.0',
display_id, f4m_id='hds', fatal=False))
else:
formats.extend(self._extract_m3u8_formats(
manifest_url, display_id, 'mp4',
'm3u8_native', m3u8_id='hls', fatal=False))
self._sort_formats(formats)
return {
'id': video_id,
'display_id': display_id,
'title': video_info.find('title').text,
'thumbnail': 'http://tv.dfb.de/images/%s_640x360.jpg' % video_id,
'upload_date': unified_strdate(video_info.find('time_date').text),
'formats': formats,
}
| gpl-3.0 |
azureplus/hue | desktop/core/ext-py/Django-1.6.10/django/utils/translation/__init__.py | 114 | 6588 | """
Internationalization support.
"""
from __future__ import unicode_literals
from django.utils.encoding import force_text
from django.utils.functional import lazy
from django.utils import six
__all__ = [
'activate', 'deactivate', 'override', 'deactivate_all',
'get_language', 'get_language_from_request',
'get_language_info', 'get_language_bidi',
'check_for_language', 'to_locale', 'templatize', 'string_concat',
'gettext', 'gettext_lazy', 'gettext_noop',
'ugettext', 'ugettext_lazy', 'ugettext_noop',
'ngettext', 'ngettext_lazy',
'ungettext', 'ungettext_lazy',
'pgettext', 'pgettext_lazy',
'npgettext', 'npgettext_lazy',
]
class TranslatorCommentWarning(SyntaxWarning):
pass
# Here be dragons, so a short explanation of the logic won't hurt:
# We are trying to solve two problems: (1) access settings, in particular
# settings.USE_I18N, as late as possible, so that modules can be imported
# without having to first configure Django, and (2) if some other code creates
# a reference to one of these functions, don't break that reference when we
# replace the functions with their real counterparts (once we do access the
# settings).
class Trans(object):
"""
The purpose of this class is to store the actual translation function upon
receiving the first call to that function. After this is done, changes to
USE_I18N will have no effect to which function is served upon request. If
your tests rely on changing USE_I18N, you can delete all the functions
from _trans.__dict__.
Note that storing the function with setattr will have a noticeable
performance effect, as access to the function goes the normal path,
instead of using __getattr__.
"""
def __getattr__(self, real_name):
from django.conf import settings
if settings.USE_I18N:
from django.utils.translation import trans_real as trans
else:
from django.utils.translation import trans_null as trans
setattr(self, real_name, getattr(trans, real_name))
return getattr(trans, real_name)
_trans = Trans()
# The Trans class is no more needed, so remove it from the namespace.
del Trans
def gettext_noop(message):
return _trans.gettext_noop(message)
ugettext_noop = gettext_noop
def gettext(message):
return _trans.gettext(message)
def ngettext(singular, plural, number):
return _trans.ngettext(singular, plural, number)
def ugettext(message):
return _trans.ugettext(message)
def ungettext(singular, plural, number):
return _trans.ungettext(singular, plural, number)
def pgettext(context, message):
return _trans.pgettext(context, message)
def npgettext(context, singular, plural, number):
return _trans.npgettext(context, singular, plural, number)
gettext_lazy = lazy(gettext, str)
ugettext_lazy = lazy(ugettext, six.text_type)
pgettext_lazy = lazy(pgettext, six.text_type)
def lazy_number(func, resultclass, number=None, **kwargs):
if isinstance(number, int):
kwargs['number'] = number
proxy = lazy(func, resultclass)(**kwargs)
else:
class NumberAwareString(resultclass):
def __mod__(self, rhs):
if isinstance(rhs, dict) and number:
try:
number_value = rhs[number]
except KeyError:
raise KeyError('Your dictionary lacks key \'%s\'. '
'Please provide it, because it is required to '
'determine whether string is singular or plural.'
% number)
else:
number_value = rhs
kwargs['number'] = number_value
translated = func(**kwargs)
try:
translated = translated % rhs
except TypeError:
# String doesn't contain a placeholder for the number
pass
return translated
proxy = lazy(lambda **kwargs: NumberAwareString(), NumberAwareString)(**kwargs)
return proxy
def ngettext_lazy(singular, plural, number=None):
return lazy_number(ngettext, str, singular=singular, plural=plural, number=number)
def ungettext_lazy(singular, plural, number=None):
return lazy_number(ungettext, six.text_type, singular=singular, plural=plural, number=number)
def npgettext_lazy(context, singular, plural, number=None):
return lazy_number(npgettext, six.text_type, context=context, singular=singular, plural=plural, number=number)
def activate(language):
return _trans.activate(language)
def deactivate():
return _trans.deactivate()
class override(object):
def __init__(self, language, deactivate=False):
self.language = language
self.deactivate = deactivate
self.old_language = get_language()
def __enter__(self):
if self.language is not None:
activate(self.language)
else:
deactivate_all()
def __exit__(self, exc_type, exc_value, traceback):
if self.deactivate:
deactivate()
else:
activate(self.old_language)
def get_language():
return _trans.get_language()
def get_language_bidi():
return _trans.get_language_bidi()
def check_for_language(lang_code):
return _trans.check_for_language(lang_code)
def to_locale(language):
return _trans.to_locale(language)
def get_language_from_request(request, check_path=False):
return _trans.get_language_from_request(request, check_path)
def get_language_from_path(path, supported=None):
return _trans.get_language_from_path(path, supported=supported)
def templatize(src, origin=None):
return _trans.templatize(src, origin)
def deactivate_all():
return _trans.deactivate_all()
def _string_concat(*strings):
"""
Lazy variant of string concatenation, needed for translations that are
constructed from multiple parts.
"""
return ''.join([force_text(s) for s in strings])
string_concat = lazy(_string_concat, six.text_type)
def get_language_info(lang_code):
from django.conf.locale import LANG_INFO
try:
return LANG_INFO[lang_code]
except KeyError:
if '-' not in lang_code:
raise KeyError("Unknown language code %s." % lang_code)
generic_lang_code = lang_code.split('-')[0]
try:
return LANG_INFO[generic_lang_code]
except KeyError:
raise KeyError("Unknown language code %s and %s." % (lang_code, generic_lang_code))
| apache-2.0 |
thiagopnts/servo | tests/wpt/web-platform-tests/websockets/handlers/simple_handshake_wsh.py | 39 | 1276 | #!/usr/bin/python
from mod_pywebsocket import common, stream
from mod_pywebsocket.handshake import AbortedByUserException, hybi
def web_socket_do_extra_handshake(request):
# Send simple response header. This test implements the handshake
# manually. It's not clear why.
request.connection.write('HTTP/1.1 101 Switching Protocols:\x0D\x0AConnection: Upgrade\x0D\x0AUpgrade: WebSocket\x0D\x0ASet-Cookie: ws_test=test\x0D\x0ASec-WebSocket-Origin: '+request.ws_origin+'\x0D\x0ASec-WebSocket-Accept: '+hybi.compute_accept(request.headers_in.get(common.SEC_WEBSOCKET_KEY_HEADER))[0]+'\x0D\x0A\x0D\x0A')
# Send a clean close frame.
body = stream.create_closing_handshake_body(1000, '')
request.connection.write(stream.create_close_frame(body));
# Wait for the responding close frame from the user agent. It's not possible
# to use the stream methods at this point because the stream hasn't been
# established from pywebsocket's point of view. Instead just read the
# appropriate number of bytes and assume they are correct.
request.connection.read(8)
# Close the socket without pywebsocket sending its own handshake response.
raise AbortedByUserException('Abort the connection')
def web_socket_transfer_data(request):
pass
| mpl-2.0 |
enitihas/SAC-Website | venv/bin/venv/lib/python2.7/site-packages/flask/__init__.py | 425 | 1674 | # -*- coding: utf-8 -*-
"""
flask
~~~~~
A microframework based on Werkzeug. It's extensively documented
and follows best practice patterns.
:copyright: (c) 2011 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
__version__ = '0.10.1'
# utilities we import from Werkzeug and Jinja2 that are unused
# in the module but are exported as public interface.
from werkzeug.exceptions import abort
from werkzeug.utils import redirect
from jinja2 import Markup, escape
from .app import Flask, Request, Response
from .config import Config
from .helpers import url_for, flash, send_file, send_from_directory, \
get_flashed_messages, get_template_attribute, make_response, safe_join, \
stream_with_context
from .globals import current_app, g, request, session, _request_ctx_stack, \
_app_ctx_stack
from .ctx import has_request_context, has_app_context, \
after_this_request, copy_current_request_context
from .module import Module
from .blueprints import Blueprint
from .templating import render_template, render_template_string
# the signals
from .signals import signals_available, template_rendered, request_started, \
request_finished, got_request_exception, request_tearing_down, \
appcontext_tearing_down, appcontext_pushed, \
appcontext_popped, message_flashed
# We're not exposing the actual json module but a convenient wrapper around
# it.
from . import json
# This was the only thing that flask used to export at one point and it had
# a more generic name.
jsonify = json.jsonify
# backwards compat, goes away in 1.0
from .sessions import SecureCookieSession as Session
json_available = True
| apache-2.0 |
idegtiarov/ceilometer | ceilometer/storage/hbase/inmemory.py | 8 | 9554 | #
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
""" This is a very crude version of "in-memory HBase", which implements just
enough functionality of HappyBase API to support testing of our driver.
"""
import copy
import re
from oslo_log import log
import six
import ceilometer
LOG = log.getLogger(__name__)
class MTable(object):
"""HappyBase.Table mock."""
def __init__(self, name, families):
self.name = name
self.families = families
self._rows_with_ts = {}
def row(self, key, columns=None):
if key not in self._rows_with_ts:
return {}
res = copy.copy(sorted(six.iteritems(
self._rows_with_ts.get(key)))[-1][1])
if columns:
keys = res.keys()
for key in keys:
if key not in columns:
res.pop(key)
return res
def rows(self, keys):
return ((k, self.row(k)) for k in keys)
def put(self, key, data, ts=None):
# Note: Now we use 'timestamped' but only for one Resource table.
# That's why we may put ts='0' in case when ts is None. If it is
# needed to use 2 types of put in one table ts=0 cannot be used.
if ts is None:
ts = "0"
if key not in self._rows_with_ts:
self._rows_with_ts[key] = {ts: data}
else:
if ts in self._rows_with_ts[key]:
self._rows_with_ts[key][ts].update(data)
else:
self._rows_with_ts[key].update({ts: data})
def delete(self, key):
del self._rows_with_ts[key]
def _get_latest_dict(self, row):
# The idea here is to return latest versions of columns.
# In _rows_with_ts we store {row: {ts_1: {data}, ts_2: {data}}}.
# res will contain a list of tuples [(ts_1, {data}), (ts_2, {data})]
# sorted by ts, i.e. in this list ts_2 is the most latest.
# To get result as HBase provides we should iterate in reverse order
# and get from "latest" data only key-values that are not in newer data
data = {}
for i in sorted(six.iteritems(self._rows_with_ts[row])):
data.update(i[1])
return data
def scan(self, filter=None, columns=None, row_start=None, row_stop=None,
limit=None):
columns = columns or []
sorted_keys = sorted(self._rows_with_ts)
# copy data between row_start and row_stop into a dict
rows = {}
for row in sorted_keys:
if row_start and row < row_start:
continue
if row_stop and row > row_stop:
break
rows[row] = self._get_latest_dict(row)
if columns:
ret = {}
for row, data in six.iteritems(rows):
for key in data:
if key in columns:
ret[row] = data
rows = ret
if filter:
# TODO(jdanjou): we should really parse this properly,
# but at the moment we are only going to support AND here
filters = filter.split('AND')
for f in filters:
# Extract filter name and its arguments
g = re.search("(.*)\((.*),?\)", f)
fname = g.group(1).strip()
fargs = [s.strip().replace('\'', '')
for s in g.group(2).split(',')]
m = getattr(self, fname)
if callable(m):
# overwrite rows for filtering to take effect
# in case of multiple filters
rows = m(fargs, rows)
else:
raise ceilometer.NotImplementedError(
"%s filter is not implemented, "
"you may want to add it!")
for k in sorted(rows)[:limit]:
yield k, rows[k]
@staticmethod
def SingleColumnValueFilter(args, rows):
"""This is filter for testing "in-memory HBase".
This method is called from scan() when 'SingleColumnValueFilter'
is found in the 'filter' argument.
"""
op = args[2]
column = "%s:%s" % (args[0], args[1])
value = args[3]
if value.startswith('binary:'):
value = value[7:]
r = {}
for row in rows:
data = rows[row]
if op == '=':
if column in data and data[column] == value:
r[row] = data
elif op == '<':
if column in data and data[column] < value:
r[row] = data
elif op == '<=':
if column in data and data[column] <= value:
r[row] = data
elif op == '>':
if column in data and data[column] > value:
r[row] = data
elif op == '>=':
if column in data and data[column] >= value:
r[row] = data
elif op == '!=':
if column in data and data[column] != value:
r[row] = data
return r
@staticmethod
def ColumnPrefixFilter(args, rows):
"""This is filter for testing "in-memory HBase".
This method is called from scan() when 'ColumnPrefixFilter' is found
in the 'filter' argument.
:param args: a list of filter arguments, contain prefix of column
:param rows: a dict of row prefixes for filtering
"""
value = args[0]
column = 'f:' + value
r = {}
for row, data in rows.items():
column_dict = {}
for key in data:
if key.startswith(column):
column_dict[key] = data[key]
r[row] = column_dict
return r
@staticmethod
def RowFilter(args, rows):
"""This is filter for testing "in-memory HBase".
This method is called from scan() when 'RowFilter' is found in the
'filter' argument.
:param args: a list of filter arguments, it contains operator and
sought string
:param rows: a dict of rows which are filtered
"""
op = args[0]
value = args[1]
if value.startswith('regexstring:'):
value = value[len('regexstring:'):]
r = {}
for row, data in rows.items():
try:
g = re.search(value, row).group()
if op == '=':
if g == row:
r[row] = data
else:
raise ceilometer.NotImplementedError(
"In-memory "
"RowFilter doesn't support "
"the %s operation yet" % op)
except AttributeError:
pass
return r
@staticmethod
def QualifierFilter(args, rows):
"""This is filter for testing "in-memory HBase".
This method is called from scan() when 'QualifierFilter' is found in
the 'filter' argument
"""
op = args[0]
value = args[1]
is_regex = False
if value.startswith('binaryprefix:'):
value = value[len('binaryprefix:'):]
if value.startswith('regexstring:'):
value = value[len('regexstring:'):]
is_regex = True
column = 'f:' + value
r = {}
for row in rows:
data = rows[row]
r_data = {}
for key in data:
if ((op == '=' and key.startswith(column)) or
(op == '>=' and key >= column) or
(op == '<=' and key <= column) or
(op == '>' and key > column) or
(op == '<' and key < column) or
(is_regex and re.search(value, key))):
r_data[key] = data[key]
else:
raise ceilometer.NotImplementedError(
"In-memory QualifierFilter "
"doesn't support the %s "
"operation yet" % op)
if r_data:
r[row] = r_data
return r
class MConnectionPool(object):
def __init__(self):
self.conn = MConnection()
def connection(self):
return self.conn
class MConnection(object):
"""HappyBase.Connection mock."""
def __init__(self):
self.tables = {}
def __enter__(self, *args, **kwargs):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
pass
@staticmethod
def open():
LOG.debug("Opening in-memory HBase connection")
def create_table(self, n, families=None):
families = families or {}
if n in self.tables:
return self.tables[n]
t = MTable(n, families)
self.tables[n] = t
return t
def delete_table(self, name, use_prefix=True):
del self.tables[name]
def table(self, name):
return self.create_table(name)
| apache-2.0 |
JohanComparat/nbody-npt-functions | bin/bin_SMHMr/measure_SMF.py | 1 | 3645 | #import StellarMass
import XrayLuminosity
import numpy as n
from scipy.stats import norm
from scipy.integrate import quad
from scipy.interpolate import interp1d
import matplotlib
matplotlib.use('pdf')
import matplotlib.pyplot as p
import glob
import astropy.io.fits as fits
import os
import time
import numpy as n
import sys
print " set up box, and redshift "
#MD 1 hlist_0.74980_SAM_Nb_0.fits
#MD 25 hlist_0.75440_SAM_Nb_10.fits
#duty_cycle = 0.01
bins = n.arange(6,13,0.1)
xb = (bins[1:] + bins[:-1]) / 2.
def measureSMF(snap_name, env='MD10', volume=1000.**3., out_dir="../"):
fileList = n.array(glob.glob(os.path.join(os.environ[env], "work_agn", "out_"+snap_name+"_SAM_Nb_*_Ms.fits")))
fileList.sort()
print fileList
Hall = n.zeros((len(fileList), len(bins)-1))
for ii, fileN in enumerate(fileList):
print fileN
hh = fits.open(fileN)
mass = hh[1].data['stellar_mass_Mo13_mvir']
print mass
selection = (mass>0) # (hh[1].data['stellar_mass_reliable'])&(mass>0)
Hall[ii], bb = n.histogram(hh[1].data['stellar_mass_Mo13_mvir'], bins=bins)
counts = n.sum(Hall, axis=0)
dN_dVdlogM = counts*0.6777**3./(bins[1:]-bins[:-1])/volume/n.log(10)
data = n.transpose([bins[:-1], bins[1:], counts, dN_dVdlogM ])
n.savetxt(os.path.join(out_dir, "out_"+snap_name+"_SMF.txt"), data, header = "logMs_low logMs_up counts dN_dVdlogM")
def measureSMF_tracer(snap_name, tracer_name, env='MD10', volume=1000.**3., out_dir="../"):
out_file = os.path.join(out_dir, "out_"+snap_name+"_"+tracer_name+"_SMF.txt")
#if os.path.isfile(out_file)==False:
fileList = n.array(glob.glob(os.path.join(os.environ[env], "work_agn", "out_"+snap_name+"_SAM_Nb_*_Ms.fits")))
fileList.sort()
fileList_T = n.array(glob.glob(os.path.join(os.environ[env], "work_agn", "out_"+snap_name+"_SAM_Nb_*_"+tracer_name+".fits")))
fileList_T.sort()
tracer_name
print fileList, fileList_T
if len(fileList_T)==len(fileList):
Hall = n.zeros((len(fileList), len(bins)-1))
for ii, fileN in enumerate(fileList):
print fileN
hh = fits.open(fileN)
lines = fits.open(fileList_T[ii])[1].data['line_number']
mass = hh[1].data['stellar_mass_Mo13_mvir'][lines]
Hall[ii], bb = n.histogram(mass, bins=bins)
counts = n.sum(Hall, axis=0)
dN_dVdlogM = counts*0.6777**3./(bins[1:]-bins[:-1])/volume/n.log(10)
data = n.transpose([bins[:-1], bins[1:], counts, dN_dVdlogM ])
n.savetxt(out_file, data, header = "logMs_low logMs_up counts dN_dVdlogM")
# open the output file_type
summ = fits.open(os.path.join(os.environ["MD10"], 'output_MD_1.0Gpc.fits'))[1].data
out_dir = os.path.join(os.path.join(os.environ['MD10'], "duty_cycle"))
for el in summ[::-1]:
print el
measureSMF(snap_name=el["snap_name"], env='MD10', volume=1000.**3., out_dir = out_dir)
#measureSMF_tracer(snap_name=el["snap_name"], tracer_name="4MOST_S5_BCG", env='MD10', volume=1000.**3., out_dir = out_dir)
#measureSMF_tracer(snap_name=el["snap_name"], tracer_name="4MOST_S5_GAL", env='MD10', volume=1000.**3., out_dir = out_dir)
#measureSMF_tracer(snap_name=el["snap_name"], tracer_name="4MOST_S6_AGN", env='MD10', volume=1000.**3., out_dir = out_dir)
#measureSMF_tracer(snap_name=el["snap_name"], tracer_name="4MOST_S8_BG1", env='MD10', volume=1000.**3., out_dir = out_dir)
#measureSMF_tracer(snap_name=el["snap_name"], tracer_name="4MOST_S8_BG2", env='MD10', volume=1000.**3., out_dir = out_dir)
#measureSMF_tracer(snap_name=el["snap_name"], tracer_name="4MOST_S8_ELG", env='MD10', volume=1000.**3., out_dir = out_dir)
#measureSMF_tracer(snap_name=el["snap_name"], tracer_name="4MOST_S8_QSO", env='MD10', volume=1000.**3., out_dir = out_dir)
| cc0-1.0 |
ojonatan/udacity.com-nd004-p2-multi-user-blog | udpyblog_test.py | 1 | 29305 | #!/usr/bin/env python
# -*- coding: utf-8 -*
"""UdPyBlog Tests"""
from webtest import TestApp
import unittest
from main import app
from google.appengine.ext import testbed
from google.appengine.api import memcache, apiproxy_stub_map, datastore_file_stub
from google.appengine.api.app_identity import app_identity_stub
from google.appengine.ext import db
import string
import random
import sys
from cookielib import CookieJar
import time
import hashlib
import re
import os
import logging
import json
import copy
import udpyblog_config
path = os.path.dirname(os.path.realpath(__file__))
# Helper functions
def merge_copy_dict(d1, d2):
result = copy.deepcopy(d1)
merge_dict(result, d2)
return result
def merge_dict(d1, d2):
for k in d2:
if k in d1 and isinstance(d1[k], dict) and isinstance(d2[k], dict):
merge_dict(d1[k], d2[k])
else:
d1[k] = d2[k]
def deunicodify_hook(pairs):
new_pairs = []
for key, value in pairs:
if isinstance(value, unicode):
value = value.encode('utf-8')
if isinstance(key, unicode):
key = key.encode('utf-8')
new_pairs.append((key, value))
return dict(new_pairs)
class ExpectingTestCase(unittest.TestCase):
tests_run = 0
def run(self, result=None):
self._result = result
self._num_expectations = 0
super(ExpectingTestCase, self).run(result)
def _fail(self, failure):
try:
raise failure
except failure.__class__:
self._result.addFailure(self, sys.exc_info())
def _expect(self, scenario, response):
negate = "negate" in scenario and scenario["negate"]
subtest = 0
test = scenario["subject"]
if "data" in scenario:
test = scenario["subject"].format(**scenario["data"])
self.results[self.testcase]["tests"][scenario["id"]]["test"] = test
# register assertions
id = 0
for type in scenario["assertions"]:
for assertion in scenario["assertions"][type]:
self._register_assertion(
scenario,
"{}:{}:{}".format(
scenario["id"],
type,
id
),
assertion,
type
)
id += 1
extras = [ "", " not" ]
for assertion_id in self.results[self.testcase]['tests'][scenario["id"]]['assertions']:
assertion = self.results[self.testcase]['tests'][scenario["id"]]['assertions'][assertion_id]
subtest += 1
self.tests_run += 1
self._num_expectations += 1
yes = True
if assertion["type"] == "in":
check_func = lambda assertion,data: bool(data.find(assertion["assertion"]) > -1)
elif assertion["type"] == "not_in":
yes = False
check_func = lambda assertion,data: bool(data.find(assertion["assertion"]) == -1)
if assertion["type"] == "re":
check_func = lambda assertion,data: bool(re.search(assertion["assertion"], data, re.MULTILINE|re.DOTALL))
if assertion["type"] == "not_re":
yes = False
check_func = lambda assertion,data: bool(not re.search(assertion["assertion"], data, re.MULTILINE|re.DOTALL))
extra = extras[int(yes == negate)]
# evaluating the tests itself. each test can contain x subtests
test_result = check_func(assertion, response.body)
result = (test_result != bool(negate))
self._report_assertion(assertion, result)
if not result:
self._dump(
re.sub(r'[^a-zA-Z0-9,]','_',scenario["subject"]),
assertion["assertion"],
response
)
msg = self._format_error(
**{
"msg": scenario["subject"],
"extra": extra,
"assertion": assertion["assertion"],
"html": response.body
}
)
self._fail(self.failureException(msg))
def _format_error(self, **args):
errors = self._extract_errors(args["html"])
error_messages = ""
if errors:
error_messages = "\n------------------------------\n Errors in form:\n ...... {errors}".format(
errors="\n ...... ".join(errors)
)
msg = """
Test({counter}): {msg} expected{extra} to contain '{assertion}'.{error_messages}
""".format(
**{
"counter": self._num_expectations,
"msg": args["msg"],
"extra": args["extra"],
"assertion": args["assertion"],
"error_messages": error_messages
}
)
return msg
def _extract_errors(self, html):
return [
"{}: {}".format(
error[2].upper(),
error[3]
) for error in re.findall(
r'<(?P<tag>[a-z1-6]+)\s((?!>|data-blog-error).)*data-blog-error="([^"]+)"[^>]*>((?!</(?P=tag)).+)</(?P=tag)',
html
)
]
def _dump(self, filename, needle, response):
dump_file = open(
os.path.join(
'dumps',
"{}{}-{}.dump".format(
TestUdPyBlog.prefix,
filename,
self.tests_run
)
),
'w+'
)
dump_file.write(
"""
Needle: {}
-----------------------
Header:
-----------------------
{}
Body:
------------------
{}
""".format(
needle,
response.headers,
response.body
)
)
dump_file.close()
class TestUdPyBlogTools():
def makeString(self, params):
return "".join( random.choice(string.letters + string.digits) for x in xrange(params["length"]) )
def makeTimestamp(self):
return int(time.time())
def getBlogEntityContext(self, params):
return TestUdPyBlog._get_blog_entity_context(params)
class TestUdPyBlog(ExpectingTestCase):
"""
Testing the UdPyBlog module. Multiple tests can be configured
stored in the self.tests dictionary to test multiple scenarios
1) Plain form has no error messages
Test if error containers are present and empty
2) Plain form features all nescessary input elements
Test if all inputs required for registration are present
3) Signup works
Test if user signup works given the submission of valid field data
4) Username exists
Tests, if the repeated, fresh submission of the same field data as in 3)
yields an error message in the username field
"""
prefix = 'tests-{}-'.format(int(time.time()))
if os.path.isfile(
os.path.join(
path,
"udpyblog_test_prefix.py"
)
):
import udpyblog_test_prefix
prefix = udpyblog_test_prefix.prefix
blog_entity_context = {}
nosegae_datastore_v3 = True
nosegae_datastore_v3_kwargs = {
'datastore_file': os.path.join(
'tests',
'nosegae.sqlite3'
),
'use_sqlite': True
}
def setUp(self):
# load tests/scenarios
import udpyblog_test_scenarios
self.tests = copy.deepcopy(udpyblog_test_scenarios.tests)
self.scenarios = copy.deepcopy(udpyblog_test_scenarios.scenarios)
self.app = TestApp(app,cookiejar=CookieJar())
self.testbed = testbed.Testbed()
self.testbed.activate()
self.testbed.setup_env(app_id='dev~None') #udacity-160512
self.testbed.init_datastore_v3_stub(
datastore_file=os.path.join(
'tests',
'datastore.sqlite3'
),
use_sqlite=True
)
self.tools = TestUdPyBlogTools()
self.testbed.init_blobstore_stub()
self.testbed.init_memcache_stub()
self.testbed.init_app_identity_stub()
self.results = {}
self.testcase = None
for test_func in self.tests:
self.results[test_func] = {
"function": test_func,
"desc": self.tests[test_func]["desc"],
"tests": {},
"scores": {
"OK": 0,
"NOT TESTED": 0,
"FAIL": 0
}
}
# assertion level, scenario level, testcase lebvel
# w
for test_case in self.tests[test_func]["scenarios"]:
id = 0
for test_scenario in self.scenarios[test_case["scenario"]]:
test_scenario["id"] = "{}:{}".format(test_case["scenario"],id)
id += 1
if "filter" in test_scenario and test_scenario["filter"]["selected"] != "*" and test_scenario["filter"]["selected"] != test_scenario[test_scenario["scope"]]:
continue
self.results[test_func]["tests"][test_scenario["id"]] = {
"id": test_scenario["id"],
"test": test_scenario["subject"],
"url": None,
"result": None,
"assertions": {}, # each assertion will be added like {assertion, result}
"scores": {
"OK": 0,
"NOT TESTED": 0,
"FAIL": 0
},
"status": "NOT TESTED",
"time": 0
}
if "data" in test_case:
data = test_case["data"]
if "statements" in data:
for statement in data["statements"]:
exec(statement,{"data": data})
test_case["data"] = data
logging.info(self.results)
self.scenarios_md5 = hashlib.md5(json.dumps(self.scenarios)).hexdigest()
def tearDown(self):
# prepare results, build summaries etc
report_filename = os.path.join(
os.path.dirname(__file__),
'tests',
"{}{}-report.json".format(TestUdPyBlog.prefix,self.testcase)
)
self._prepare_results()
self.report = open(report_filename,'a+')
self.report.write(json.dumps(self.results[self.testcase]))
self.report.close()
report_index = os.path.join(
os.path.dirname(__file__),
'tests',
"{}reports".format(TestUdPyBlog.prefix)
)
self.index = open(report_index,'a+')
self.index.write(report_filename + "\n")
self.index.close()
self.testbed.deactivate()
self.app.cookies.clear()
def _prepare_results(self):
for test_id in self.results[self.testcase]["tests"]:
result = True
test_case = self.results[self.testcase]["tests"][test_id]
for assertion_id in test_case["assertions"]:
assertion = test_case["assertions"][assertion_id]
test_case["scores"][assertion["status"]] += 1
if not assertion["result"]:
result = False
if len(test_case["assertions"]) == test_case["scores"]["NOT TESTED"]:
test_case["status"] = "NOT TESTED"
else:
test_case["result"] = len(test_case["assertions"]) == test_case["scores"]["OK"]
test_case["status"] = "FAIL"
if test_case["result"]:
test_case["status"] = "OK"
self.results[self.testcase]["scores"][test_case["status"]] += 1
if len(self.results[self.testcase]["tests"]) == self.results[self.testcase]["scores"]["NOT TESTED"]:
self.results[self.testcase]["status"] = "NOT TESTED"
else:
self.results[self.testcase]["result"] = (len(self.results[self.testcase]["tests"]) == self.results[self.testcase]["scores"]["OK"])
self.results[self.testcase]["status"] = "FAIL"
if self.results[self.testcase]["result"]:
self.results[self.testcase]["status"] = "OK"
def _register_assertion(self, scenario, id, assertion, type):
self.results[self.testcase]['tests'][scenario["id"]]['assertions'][id] = {
'id': id,
'assertion': assertion,
'type': type,
'result': None,
'status': 'NOT TESTED'
}
def _get_assertions(self, id):
return self.results[self.testcase]['tests'][id]['assertions']
def _report_assertion(self, assertion, result):
assertion["result"] = result
assertion["status"] = "FAIL"
if result:
assertion["status"] = "OK"
def test_000_signup_signup_post_works(self):
"""Test if user signup works - creating initial testuser for later use"""
self._run_tests("test_000_signup_signup_post_works")
def test_101_logout_after_login_works(self):
"""Log out right after login works"""
self._run_tests("test_101_logout_after_login_works")
def test_002_signup_signup_post_functional_error_handling(self):
"""Submitting signups with bad data"""
self._run_tests("test_002_signup_signup_post_functional_error_handling")
def test_003_home_page_logged_out(self):
"""Testing, if the initial view features the logged out view of the blog"""
self._run_tests("test_003_home_page_logged_out")
def test_100_login_works(self):
"""Log in with existing user works"""
self._run_tests("test_100_login_works")
def test_101_logout_after_login_works(self):
"""Log out right after login works"""
self._run_tests("test_101_logout_after_login_works")
def test_102_logout_after_signup_works(self):
"""Log out right after signup works"""
self._run_tests("test_102_logout_after_signup_works")
def test_103_create_blog_post_form_works(self):
"""The create blog post form is there and ready for input"""
self._run_tests("test_103_create_blog_post_form_works")
def test_104_create_blog_post_submit_error_handling(self):
"""Post too short input for a blog post and see 3 errors"""
self._run_tests("test_104_create_blog_post_submit_error_handling")
def test_105_create_blog_post_submit_works(self):
"""Create a poisoned but formal correct new blog post and verify sanitization"""
self._run_tests("test_105_create_blog_post_submit_works")
def test_106_users_can_only_like_posts_from_authors_other_then_themselves(self):
"""Users can only like/unlike posts from authors other then themselves"""
self._run_tests("test_106_users_can_only_like_posts_from_authors_other_then_themselves")
def test_107_update_blog_post_and_verify_changes(self):
"""Update blog post and verify changes"""
self._run_tests("test_107_update_blog_post_and_verify_changes")
def test_108_redirect_to_protected_url_after_captive_login_success(self):
"""Redirect to protected URL after successful login using the captive login form"""
self._run_tests("test_108_redirect_to_protected_url_after_captive_login_success")
def _run_tests(self, testcase):
self.testcase = testcase
result = True
desc = self.tests[testcase]["desc"]
scenarios_selected = []
for selector in self.tests[testcase]["scenarios"]:
group_selector = selector["scenario"]
logging.info("Adding scenarios from the <<{}>> selector ({} scenarios available)".format(group_selector,len(self.scenarios[group_selector])))
# selected scenarios might be a key with an empty dict. in this case the scenario is just taken as is
if "filter" in selector:
scenario_filter = selector["filter"]
# overrides exist!
subset_selector = "*"
if "selected" in scenario_filter:
subset_selector = scenario_filter["selected"]
if subset_selector != "*":
logging.info("ALEEEEEEEEEERT: " + subset_selector + " SELECTOR FOUND!")
# a specific numeric offset. good for random selection
if subset_selector.isdigit():
if subset_selector >= 0:
if subset_selector < len(self.scenarios[group_selector]):
# we want the overrides to be applied at a later point. or inside the testfunc
scenario = copy.deepcopy(self.scenarios[group_selector][subset_selector])
if "overrides" in scenario_filter:
if "scope" not in scenario or "*" in scenario_filter["overrides"] or scenario["scope"] in scenario_filter["overrides"]:
scenario["overrides"] = copy.deepcopy(scenario_filter["overrides"])
scenarios_selected.append(scenario)
else:
logging.info("Subset selector '{}' out of range. Group cotains only {} scenarios".format(subset_selector,len(self.scenarios[group_selector])))
# subset_selector is negative. getting only the last x entries
else:
if abs(subset_selector) < len(self.scenarios[group_selector]):
for scenario_ref in range(self.scenarios[group_selector][(subset_selector):]):
scenario = copy.deepcopy(scenario_ref)
if "overrides" in scenario_filter:
if "scope" not in scenario or "*" in scenario_filter["overrides"] or scenario["scope"] in scenario_filter["overrides"]:
scenario["overrides"] = copy.deepcopy(scenario_filter["overrides"])
scenarios_selected.append(scenario)
logging.info("Subset selector '{}' out of range. Group cotains only {} scenarios".format(subset_selector,len(self.scenarios[group_selector])))
# only the first x scenarios
elif subset_selector[0] == ":" and subset_selector[1:].isdigit():
if subset_selector[1:] < len(self.scenarios[group_selector]):
for scenario_ref in range(self.scenarios[group_selector][(subset_selector):]):
scenario = copy.deepcopy(scenario_ref)
if "overrides" in scenario_filter:
if "scope" not in scenario or "*" in scenario_filter["overrides"] or scenario["scope"] in scenario_filter["overrides"]:
scenario["overrides"] = copy.deepcopy(scenario_filter["overrides"])
scenarios_selected.append(scenario)
logging.info("Subset selector '{}' out of range. Group cotains only {} scenarios".format(subset_selector[1:],len(self.scenarios[group_selector])))
else:
for i in range(len(self.scenarios[group_selector])):
if subset_selector == "*" or self.scenarios[group_selector][i]["scope"] == subset_selector:
scenario = copy.deepcopy(self.scenarios[group_selector][i])
if "overrides" in scenario_filter:
if "*" in scenario_filter["overrides"] or ("scope" in scenario and scenario["scope"] in scenario_filter["overrides"]):
scenario["overrides"] = copy.deepcopy(scenario_filter["overrides"])
scenarios_selected.append(scenario)
elif group_selector in self.scenarios:
for scenario_ref in self.scenarios[group_selector]:
scenario = copy.deepcopy(scenario_ref)
scenarios_selected.append(scenario)
if not scenarios_selected:
return False
logging.info("Running {} subtests".format(len(scenarios_selected)))
for scenario in scenarios_selected:
self._scenario_override(scenario)
logging.info(scenario)
if scenario["reset"] == True:
logging.info("clearing cookies")
self.app.cookiejar.clear()
response = None
if scenario["request"]:
url = "{}{}".format(
udpyblog_config.config["udpyblog"]["blog_prefix"],
scenario["request"]["url"]
)
logging.info("Accessing handler for <<{}>>!".format(scenario["request"]["url"]))
if scenario["request"]["method"] == "get":
response = self.app.get(
url
)
else:
logging.info(">>>>>>>>>>>>>>>>>POST:")
logging.info(self._prepare_data(scenario["data"]))
status=None
if "code" in scenario["request"]:
status=scenario["request"]["code"]
logging.info(">>>>>>>>>>>>>>>>>>expecting " + str(status))
expect_errors = False
if "expect_errors" in scenario:
expect_errors = scenario["expect_errors"]
response = self.app.post(
url,
self._prepare_data(scenario["data"]),
status=status,
expect_errors=expect_errors
)
logging.info("returning " + str(response.status_code))
logging.info(response.headers)
if "Blog-Entity-Context" in dict(response.headers):
context = json.loads(dict(response.headers)["Blog-Entity-Context"], object_pairs_hook=deunicodify_hook)
logging.info("Blog-Entity-Context HEADER FOUND " + str(context))
if "scope" in scenario:
TestUdPyBlog._add_blog_entity_context(scenario["scope"], context)
logging.info(TestUdPyBlog.blog_entity_context)
# if "code" in scenario["request"]:
# if response.status_code != scenario["request"]["code"]:
# # the right return code is only one aspect
# pass
if response.status_code == 302:
response = self.app.get(
dict(response.headers)["Location"]
)
self._expect(scenario, response)
return result
def _scenario_override(self, scenario):
"""
Interpolate data with current test context
"""
logging.info("<<<<<<<<<<<<<<<<<<<<<<< BLOG CONTEXT ")
logging.info(TestUdPyBlog.blog_entity_context)
scenario_overridden = scenario
if not scenario["overrides"]:
logging.info("!!!!!!!!!!!!!!!!!!!!!!! EMPTY OVERRRIDE <<" + scenario["subject"] + ">>?!?!?!? ")
logging.info(scenario["overrides"])
for scope in scenario["overrides"]:
logging.info("CHECKIG SCOPE " + scope)
if scope == "*" or scope in scenario["overrides"]:
overrides = scenario["overrides"][scope]
args = {}
for override in overrides:
for replace_field in override["replace"]:
args[replace_field] = ""
for replacer in override["replace"][replace_field]:
if "tool" in replacer:
func = getattr(self.tools,replacer["tool"])
if func:
params = None
if "tool_args" in replacer:
params = replacer["tool_args"]
args[replacer["field"]] = func(params)
else:
args[replacer["field"]] = func()
logging.info("!!!!!!!!!!!!!!AAAAAAAAAAAEG")
logging.info(args)
scenario_cursor = scenario_overridden
logging.info("######### LOOOOOOOOOOOOOOOOOOOOOOOOOOP AAEG -- FIED {}".format(replace_field))
logging.info(scenario_overridden)
context_scope = "_root"
if override["target"]:
context_scope = override["target"][0]
path = override["target"][:]
while path:
fragment = path.pop(0)
if fragment not in scenario_cursor:
logging.info("BAD FRAGMENT DETECTED: " + fragment)
logging.info(scenario_cursor)
scenario_cursor = scenario_cursor[fragment]
logging.info("######### LOOOOOOOOOOOOOOOOOOOOOOOOOOP sub")
logging.info(scenario_cursor)
if isinstance(scenario_cursor[override["field"]], list):
context = {
"key": "out",
"scope": context_scope,
replace_field: override["template"].format(**args)
}
TestUdPyBlog._add_blog_entity_context(scope, context)
scenario_cursor[override["field"]].append(context[replace_field])
logging.info("---------adding {} to {} [ARGS BELO]".format(context[replace_field],scenario_cursor[override["field"]] ) )
logging.info(args )
else:
context = {
"key": "out",
"scope": context_scope,
replace_field: override["template"].format(**args)
}
TestUdPyBlog._add_blog_entity_context(scope, context)
scenario_cursor[override["field"]] = context[replace_field]
logging.info("overriding " + override["template"] + " with " + scenario_cursor[override["field"]] )
logging.info("+-+-+-+-ARGS+-+-+-+-+")
logging.info(args)
logging.info("+-+-+-+-OVERRIDE+-+-+-+-+")
logging.info(scenario_cursor)
return scenario_overridden
@classmethod
def _get_blog_entity_context(cls, context):
"""
Retrieves the context information retrieved from the header
for use in other methods. Usually only the most recent value
is needed.
"""
key = "in"
if "key" in context:
key = context["key"]
logging.info(">>>>>>>>>>>>>>ssss>>>>>>>>>>>>>>>>" )
logging.info(context )
if key in cls.blog_entity_context:
if context["scope"] in cls.blog_entity_context[key]:
if context["field"] in cls.blog_entity_context[key][context["scope"]]:
return cls.blog_entity_context[key][context["scope"]][context["field"]][-1]
return ""
@classmethod
def _add_blog_entity_context(cls, scope, context):
"""
Stores the context information retrieved from the header in an array
for use in other methods
"""
key = "in"
if "key" in context:
key = context["key"]
if not key in TestUdPyBlog.blog_entity_context:
TestUdPyBlog.blog_entity_context[key] = {}
if not scope in TestUdPyBlog.blog_entity_context[key]:
TestUdPyBlog.blog_entity_context[key][scope] = {}
for field in context:
if field == "key":
continue
logging.info("adding json field: " + field)
if not field in TestUdPyBlog.blog_entity_context[key][scope]:
TestUdPyBlog.blog_entity_context[key][scope][field] = []
TestUdPyBlog.blog_entity_context[key][scope][field].append(context[field])
def _prepare_data(self, context):
if "submit" in context:
return dict(((field, context[field]) for field in context["submit"]))
return {}
def _verify_tests(self):
if hashlib.md5(json.dumps(self.scenarios)).hexdigest() == self.scenarios_md5:
return True
return False
| mit |
entropy1337/infernal-twin | Modules/build/pip/build/lib.linux-i686-2.7/pip/_vendor/requests/packages/urllib3/__init__.py | 482 | 2055 | """
urllib3 - Thread-safe connection pooling and re-using.
"""
__author__ = 'Andrey Petrov (andrey.petrov@shazow.net)'
__license__ = 'MIT'
__version__ = '1.10.4'
from .connectionpool import (
HTTPConnectionPool,
HTTPSConnectionPool,
connection_from_url
)
from . import exceptions
from .filepost import encode_multipart_formdata
from .poolmanager import PoolManager, ProxyManager, proxy_from_url
from .response import HTTPResponse
from .util.request import make_headers
from .util.url import get_host
from .util.timeout import Timeout
from .util.retry import Retry
# Set default logging handler to avoid "No handler found" warnings.
import logging
try: # Python 2.7+
from logging import NullHandler
except ImportError:
class NullHandler(logging.Handler):
def emit(self, record):
pass
logging.getLogger(__name__).addHandler(NullHandler())
def add_stderr_logger(level=logging.DEBUG):
"""
Helper for quickly adding a StreamHandler to the logger. Useful for
debugging.
Returns the handler after adding it.
"""
# This method needs to be in this __init__.py to get the __name__ correct
# even if urllib3 is vendored within another package.
logger = logging.getLogger(__name__)
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s'))
logger.addHandler(handler)
logger.setLevel(level)
logger.debug('Added a stderr logging handler to logger: %s' % __name__)
return handler
# ... Clean up.
del NullHandler
import warnings
# SecurityWarning's always go off by default.
warnings.simplefilter('always', exceptions.SecurityWarning, append=True)
# InsecurePlatformWarning's don't vary between requests, so we keep it default.
warnings.simplefilter('default', exceptions.InsecurePlatformWarning,
append=True)
def disable_warnings(category=exceptions.HTTPWarning):
"""
Helper for quickly disabling all urllib3 warnings.
"""
warnings.simplefilter('ignore', category)
| gpl-3.0 |
kivhift/pu | src/tests/test_serializer.py | 1 | 2749 | #
# Copyright (c) 2012 Joshua Hughes <kivhift@gmail.com>
#
from nose.tools import assert_raises
import os
import StringIO
import tempfile
import pu.serializer
_data_dir = 'data'
def _path(name):
return os.path.join(_data_dir, name)
class EqHelper(pu.serializer.SelfSerializer):
def __eq__(self, other):
if set(self.__dict__) != set(other.__dict__):
return False
for k, v in self.__dict__.iteritems():
if other.__dict__[k] != v:
return False
if type(other.__dict__[k]) != type(v):
return False
return True
def __ne__(self, other):
return not self.__eq__(other)
def test_serializability():
s = EqHelper()
# ints
s.a = 0
s.b = 0x2ff
s.c = -77
s.d = 1<<163
s.e = -1 * s.d
# float
s.f = 0.0
s.g = 3.14159
s.h = -1.0 * s.g
# str
s.i = ''
s.j = '\0\x01\x02\x03hi'
s.k = '\x0f.\xf7D\x8buL2\xce\xc2p\x95\xfa'
# list
s.l = []
s.m = [''] * 4
s.n = [[]] * 3
s.o = list('abcd')
s.p = [{}]
# dict
s.q = {}
s.r = {0 : '0', 'a' : 1, 'b' : 2, 'c' : {}, 'd' : []}
f = tempfile.TemporaryFile()
s.dump(f)
s.dump(f)
f.seek(0)
s0, s1 = EqHelper(), EqHelper()
s0.load(f)
s1.load(f)
assert s == s0
assert s == s1
assert s0 == s1
def test_append():
s = EqHelper()
s.eg = '\x00this is some text...'
s.ex = 1234
fout = tempfile.NamedTemporaryFile(delete = False)
fout.close()
s.dump(fout.name)
s.dump(fout.name)
s0, s1 = EqHelper(), EqHelper()
s0.load(fout.name)
with open(fout.name, 'rb') as f:
s1.load(f)
s1.load(f)
os.remove(fout.name)
assert s == s0
assert s == s1
assert s0 == s1
def test_exceptions():
s = EqHelper()
s.s = EqHelper()
with assert_raises(pu.serializer.SelfSerializerError):
s.dump(tempfile.TemporaryFile())
with assert_raises(pu.serializer.SelfSerializerError):
s.load(_path('bad-item-count'))
with assert_raises(pu.serializer.SelfSerializerError):
s.load(_path('bad-length'))
with assert_raises(pu.serializer.SelfSerializerError):
s.load(_path('bad-name'))
with assert_raises(pu.serializer.SelfSerializerError):
s.load(_path('bad-record-sep'))
def test_load():
s, s0 = EqHelper(), EqHelper()
s0.eg_flt = 0.0
s0.eg_int = -1
s0.eg_str = 'This is some text.'
s.load(_path('good'))
assert s0 == s
def test_interaction_with_file_likes():
s, s0 = EqHelper(), EqHelper()
buf = StringIO.StringIO()
s.some_text = 'Will this work?'
s.an_integer = 0
s.dump(buf)
buf.seek(0)
s0.load(buf)
assert s == s0
| mit |
pepetreshere/odoo | addons/sale/models/utm.py | 2 | 3482 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models, api, SUPERUSER_ID
class UtmCampaign(models.Model):
_inherit = 'utm.campaign'
_description = 'UTM Campaign'
quotation_count = fields.Integer('Quotation Count', groups='sales_team.group_sale_salesman', compute="_compute_quotation_count")
invoiced_amount = fields.Integer(default=0, compute="_compute_sale_invoiced_amount", string="Revenues generated by the campaign")
company_id = fields.Many2one('res.company', string='Company', readonly=True, states={'draft': [('readonly', False)], 'refused': [('readonly', False)]}, default=lambda self: self.env.company)
currency_id = fields.Many2one('res.currency', related='company_id.currency_id', string='Currency')
def _compute_quotation_count(self):
quotation_data = self.env['sale.order'].read_group([
('campaign_id', 'in', self.ids)],
['campaign_id'], ['campaign_id'])
data_map = {datum['campaign_id'][0]: datum['campaign_id_count'] for datum in quotation_data}
for campaign in self:
campaign.quotation_count = data_map.get(campaign.id, 0)
def _compute_sale_invoiced_amount(self):
self.env['account.move.line'].flush(['balance', 'move_id', 'account_id', 'exclude_from_invoice_tab'])
self.env['account.move'].flush(['state', 'campaign_id', 'move_type'])
query = """SELECT move.campaign_id, -SUM(line.balance) as price_subtotal
FROM account_move_line line
INNER JOIN account_move move ON line.move_id = move.id
WHERE move.state not in ('draft', 'cancel')
AND move.campaign_id IN %s
AND move.move_type IN ('out_invoice', 'out_refund', 'in_invoice', 'in_refund', 'out_receipt', 'in_receipt')
AND line.account_id IS NOT NULL
AND NOT line.exclude_from_invoice_tab
GROUP BY move.campaign_id
"""
self._cr.execute(query, [tuple(self.ids)])
query_res = self._cr.dictfetchall()
campaigns = self.browse()
for datum in query_res:
campaign = self.browse(datum['campaign_id'])
campaign.invoiced_amount = datum['price_subtotal']
campaigns |= campaign
for campaign in (self - campaigns):
campaign.invoiced_amount = 0
def action_redirect_to_quotations(self):
action = self.env["ir.actions.actions"]._for_xml_id("sale.action_quotations_with_onboarding")
action['domain'] = [('campaign_id', '=', self.id)]
action['context'] = {
'create': False,
'edit': False,
'default_campaign_id': self.id
}
return action
def action_redirect_to_invoiced(self):
action = self.env["ir.actions.actions"]._for_xml_id("account.action_move_journal_line")
invoices = self.env['account.move'].search([('campaign_id', '=', self.id)])
action['context'] = {
'create': False,
'edit': False,
'view_no_maturity': True
}
action['domain'] = [
('id', 'in', invoices.ids),
('move_type', 'in', ('out_invoice', 'out_refund', 'in_invoice', 'in_refund', 'out_receipt', 'in_receipt')),
('state', 'not in', ['draft', 'cancel'])
]
return action
| agpl-3.0 |
joliet0l/python-for-android | src/buildlib/argparse.py | 37 | 89696 | # -*- coding: utf-8 -*-
# Copyright © 2006-2009 Steven J. Bethard <steven.bethard@gmail.com>.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy
# of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Command-line parsing library
This module is an optparse-inspired command-line parsing library that:
- handles both optional and positional arguments
- produces highly informative usage messages
- supports parsers that dispatch to sub-parsers
The following is a simple usage example that sums integers from the
command-line and writes the result to a file::
parser = argparse.ArgumentParser(
description='sum the integers at the command line')
parser.add_argument(
'integers', metavar='int', nargs='+', type=int,
help='an integer to be summed')
parser.add_argument(
'--log', default=sys.stdout, type=argparse.FileType('w'),
help='the file where the sum should be written')
args = parser.parse_args()
args.log.write('%s' % sum(args.integers))
args.log.close()
The module contains the following public classes:
- ArgumentParser -- The main entry point for command-line parsing. As the
example above shows, the add_argument() method is used to populate
the parser with actions for optional and positional arguments. Then
the parse_args() method is invoked to convert the args at the
command-line into an object with attributes.
- ArgumentError -- The exception raised by ArgumentParser objects when
there are errors with the parser's actions. Errors raised while
parsing the command-line are caught by ArgumentParser and emitted
as command-line messages.
- FileType -- A factory for defining types of files to be created. As the
example above shows, instances of FileType are typically passed as
the type= argument of add_argument() calls.
- Action -- The base class for parser actions. Typically actions are
selected by passing strings like 'store_true' or 'append_const' to
the action= argument of add_argument(). However, for greater
customization of ArgumentParser actions, subclasses of Action may
be defined and passed as the action= argument.
- HelpFormatter, RawDescriptionHelpFormatter, RawTextHelpFormatter,
ArgumentDefaultsHelpFormatter -- Formatter classes which
may be passed as the formatter_class= argument to the
ArgumentParser constructor. HelpFormatter is the default,
RawDescriptionHelpFormatter and RawTextHelpFormatter tell the parser
not to change the formatting for help text, and
ArgumentDefaultsHelpFormatter adds information about argument defaults
to the help.
All other classes in this module are considered implementation details.
(Also note that HelpFormatter and RawDescriptionHelpFormatter are only
considered public as object names -- the API of the formatter objects is
still considered an implementation detail.)
"""
__version__ = '1.1'
__all__ = [
'ArgumentParser',
'ArgumentError',
'Namespace',
'Action',
'FileType',
'HelpFormatter',
'RawDescriptionHelpFormatter',
'RawTextHelpFormatter',
'ArgumentDefaultsHelpFormatter',
]
import copy as _copy
import os as _os
import re as _re
import sys as _sys
import textwrap as _textwrap
def _(s):
return s
try:
_set = set
except NameError:
from sets import Set as _set
try:
_basestring = basestring
except NameError:
_basestring = str
try:
_sorted = sorted
except NameError:
def _sorted(iterable, reverse=False):
result = list(iterable)
result.sort()
if reverse:
result.reverse()
return result
def _callable(obj):
return hasattr(obj, '__call__') or hasattr(obj, '__bases__')
# silence Python 2.6 buggy warnings about Exception.message
if _sys.version_info[:2] == (2, 6):
import warnings
warnings.filterwarnings(
action='ignore',
message='BaseException.message has been deprecated as of Python 2.6',
category=DeprecationWarning,
module='argparse')
SUPPRESS = '==SUPPRESS=='
OPTIONAL = '?'
ZERO_OR_MORE = '*'
ONE_OR_MORE = '+'
PARSER = 'A...'
REMAINDER = '...'
# =============================
# Utility functions and classes
# =============================
class _AttributeHolder(object):
"""Abstract base class that provides __repr__.
The __repr__ method returns a string in the format::
ClassName(attr=name, attr=name, ...)
The attributes are determined either by a class-level attribute,
'_kwarg_names', or by inspecting the instance __dict__.
"""
def __repr__(self):
type_name = type(self).__name__
arg_strings = []
for arg in self._get_args():
arg_strings.append(repr(arg))
for name, value in self._get_kwargs():
arg_strings.append('%s=%r' % (name, value))
return '%s(%s)' % (type_name, ', '.join(arg_strings))
def _get_kwargs(self):
return _sorted(self.__dict__.items())
def _get_args(self):
return []
def _ensure_value(namespace, name, value):
if getattr(namespace, name, None) is None:
setattr(namespace, name, value)
return getattr(namespace, name)
# ===============
# Formatting Help
# ===============
class HelpFormatter(object):
"""Formatter for generating usage messages and argument help strings.
Only the name of this class is considered a public API. All the methods
provided by the class are considered an implementation detail.
"""
def __init__(self,
prog,
indent_increment=2,
max_help_position=24,
width=None):
# default setting for width
if width is None:
try:
width = int(_os.environ['COLUMNS'])
except (KeyError, ValueError):
width = 80
width -= 2
self._prog = prog
self._indent_increment = indent_increment
self._max_help_position = max_help_position
self._width = width
self._current_indent = 0
self._level = 0
self._action_max_length = 0
self._root_section = self._Section(self, None)
self._current_section = self._root_section
self._whitespace_matcher = _re.compile(r'\s+')
self._long_break_matcher = _re.compile(r'\n\n\n+')
# ===============================
# Section and indentation methods
# ===============================
def _indent(self):
self._current_indent += self._indent_increment
self._level += 1
def _dedent(self):
self._current_indent -= self._indent_increment
assert self._current_indent >= 0, 'Indent decreased below 0.'
self._level -= 1
class _Section(object):
def __init__(self, formatter, parent, heading=None):
self.formatter = formatter
self.parent = parent
self.heading = heading
self.items = []
def format_help(self):
# format the indented section
if self.parent is not None:
self.formatter._indent()
join = self.formatter._join_parts
for func, args in self.items:
func(*args)
item_help = join([func(*args) for func, args in self.items])
if self.parent is not None:
self.formatter._dedent()
# return nothing if the section was empty
if not item_help:
return ''
# add the heading if the section was non-empty
if self.heading is not SUPPRESS and self.heading is not None:
current_indent = self.formatter._current_indent
heading = '%*s%s:\n' % (current_indent, '', self.heading)
else:
heading = ''
# join the section-initial newline, the heading and the help
return join(['\n', heading, item_help, '\n'])
def _add_item(self, func, args):
self._current_section.items.append((func, args))
# ========================
# Message building methods
# ========================
def start_section(self, heading):
self._indent()
section = self._Section(self, self._current_section, heading)
self._add_item(section.format_help, [])
self._current_section = section
def end_section(self):
self._current_section = self._current_section.parent
self._dedent()
def add_text(self, text):
if text is not SUPPRESS and text is not None:
self._add_item(self._format_text, [text])
def add_usage(self, usage, actions, groups, prefix=None):
if usage is not SUPPRESS:
args = usage, actions, groups, prefix
self._add_item(self._format_usage, args)
def add_argument(self, action):
if action.help is not SUPPRESS:
# find all invocations
get_invocation = self._format_action_invocation
invocations = [get_invocation(action)]
for subaction in self._iter_indented_subactions(action):
invocations.append(get_invocation(subaction))
# update the maximum item length
invocation_length = max([len(s) for s in invocations])
action_length = invocation_length + self._current_indent
self._action_max_length = max(self._action_max_length,
action_length)
# add the item to the list
self._add_item(self._format_action, [action])
def add_arguments(self, actions):
for action in actions:
self.add_argument(action)
# =======================
# Help-formatting methods
# =======================
def format_help(self):
help = self._root_section.format_help()
if help:
help = self._long_break_matcher.sub('\n\n', help)
help = help.strip('\n') + '\n'
return help
def _join_parts(self, part_strings):
return ''.join([part
for part in part_strings
if part and part is not SUPPRESS])
def _format_usage(self, usage, actions, groups, prefix):
if prefix is None:
prefix = _('usage: ')
# if usage is specified, use that
if usage is not None:
usage = usage % dict(prog=self._prog)
# if no optionals or positionals are available, usage is just prog
elif usage is None and not actions:
usage = '%(prog)s' % dict(prog=self._prog)
# if optionals and positionals are available, calculate usage
elif usage is None:
prog = '%(prog)s' % dict(prog=self._prog)
# split optionals from positionals
optionals = []
positionals = []
for action in actions:
if action.option_strings:
optionals.append(action)
else:
positionals.append(action)
# build full usage string
format = self._format_actions_usage
action_usage = format(optionals + positionals, groups)
usage = ' '.join([s for s in [prog, action_usage] if s])
# wrap the usage parts if it's too long
text_width = self._width - self._current_indent
if len(prefix) + len(usage) > text_width:
# break usage into wrappable parts
part_regexp = r'\(.*?\)+|\[.*?\]+|\S+'
opt_usage = format(optionals, groups)
pos_usage = format(positionals, groups)
opt_parts = _re.findall(part_regexp, opt_usage)
pos_parts = _re.findall(part_regexp, pos_usage)
assert ' '.join(opt_parts) == opt_usage
assert ' '.join(pos_parts) == pos_usage
# helper for wrapping lines
def get_lines(parts, indent, prefix=None):
lines = []
line = []
if prefix is not None:
line_len = len(prefix) - 1
else:
line_len = len(indent) - 1
for part in parts:
if line_len + 1 + len(part) > text_width:
lines.append(indent + ' '.join(line))
line = []
line_len = len(indent) - 1
line.append(part)
line_len += len(part) + 1
if line:
lines.append(indent + ' '.join(line))
if prefix is not None:
lines[0] = lines[0][len(indent):]
return lines
# if prog is short, follow it with optionals or positionals
if len(prefix) + len(prog) <= 0.75 * text_width:
indent = ' ' * (len(prefix) + len(prog) + 1)
if opt_parts:
lines = get_lines([prog] + opt_parts, indent, prefix)
lines.extend(get_lines(pos_parts, indent))
elif pos_parts:
lines = get_lines([prog] + pos_parts, indent, prefix)
else:
lines = [prog]
# if prog is long, put it on its own line
else:
indent = ' ' * len(prefix)
parts = opt_parts + pos_parts
lines = get_lines(parts, indent)
if len(lines) > 1:
lines = []
lines.extend(get_lines(opt_parts, indent))
lines.extend(get_lines(pos_parts, indent))
lines = [prog] + lines
# join lines into usage
usage = '\n'.join(lines)
# prefix with 'usage:'
return '%s%s\n\n' % (prefix, usage)
def _format_actions_usage(self, actions, groups):
# find group indices and identify actions in groups
group_actions = _set()
inserts = {}
for group in groups:
try:
start = actions.index(group._group_actions[0])
except ValueError:
continue
else:
end = start + len(group._group_actions)
if actions[start:end] == group._group_actions:
for action in group._group_actions:
group_actions.add(action)
if not group.required:
inserts[start] = '['
inserts[end] = ']'
else:
inserts[start] = '('
inserts[end] = ')'
for i in range(start + 1, end):
inserts[i] = '|'
# collect all actions format strings
parts = []
for i, action in enumerate(actions):
# suppressed arguments are marked with None
# remove | separators for suppressed arguments
if action.help is SUPPRESS:
parts.append(None)
if inserts.get(i) == '|':
inserts.pop(i)
elif inserts.get(i + 1) == '|':
inserts.pop(i + 1)
# produce all arg strings
elif not action.option_strings:
part = self._format_args(action, action.dest)
# if it's in a group, strip the outer []
if action in group_actions:
if part[0] == '[' and part[-1] == ']':
part = part[1:-1]
# add the action string to the list
parts.append(part)
# produce the first way to invoke the option in brackets
else:
option_string = action.option_strings[0]
# if the Optional doesn't take a value, format is:
# -s or --long
if action.nargs == 0:
part = '%s' % option_string
# if the Optional takes a value, format is:
# -s ARGS or --long ARGS
else:
default = action.dest.upper()
args_string = self._format_args(action, default)
part = '%s %s' % (option_string, args_string)
# make it look optional if it's not required or in a group
if not action.required and action not in group_actions:
part = '[%s]' % part
# add the action string to the list
parts.append(part)
# insert things at the necessary indices
for i in _sorted(inserts, reverse=True):
parts[i:i] = [inserts[i]]
# join all the action items with spaces
text = ' '.join([item for item in parts if item is not None])
# clean up separators for mutually exclusive groups
open = r'[\[(]'
close = r'[\])]'
text = _re.sub(r'(%s) ' % open, r'\1', text)
text = _re.sub(r' (%s)' % close, r'\1', text)
text = _re.sub(r'%s *%s' % (open, close), r'', text)
text = _re.sub(r'\(([^|]*)\)', r'\1', text)
text = text.strip()
# return the text
return text
def _format_text(self, text):
if '%(prog)' in text:
text = text % dict(prog=self._prog)
text_width = self._width - self._current_indent
indent = ' ' * self._current_indent
return self._fill_text(text, text_width, indent) + '\n\n'
def _format_action(self, action):
# determine the required width and the entry label
help_position = min(self._action_max_length + 2,
self._max_help_position)
help_width = self._width - help_position
action_width = help_position - self._current_indent - 2
action_header = self._format_action_invocation(action)
# ho nelp; start on same line and add a final newline
if not action.help:
tup = self._current_indent, '', action_header
action_header = '%*s%s\n' % tup
# short action name; start on the same line and pad two spaces
elif len(action_header) <= action_width:
tup = self._current_indent, '', action_width, action_header
action_header = '%*s%-*s ' % tup
indent_first = 0
# long action name; start on the next line
else:
tup = self._current_indent, '', action_header
action_header = '%*s%s\n' % tup
indent_first = help_position
# collect the pieces of the action help
parts = [action_header]
# if there was help for the action, add lines of help text
if action.help:
help_text = self._expand_help(action)
help_lines = self._split_lines(help_text, help_width)
parts.append('%*s%s\n' % (indent_first, '', help_lines[0]))
for line in help_lines[1:]:
parts.append('%*s%s\n' % (help_position, '', line))
# or add a newline if the description doesn't end with one
elif not action_header.endswith('\n'):
parts.append('\n')
# if there are any sub-actions, add their help as well
for subaction in self._iter_indented_subactions(action):
parts.append(self._format_action(subaction))
# return a single string
return self._join_parts(parts)
def _format_action_invocation(self, action):
if not action.option_strings:
metavar, = self._metavar_formatter(action, action.dest)(1)
return metavar
else:
parts = []
# if the Optional doesn't take a value, format is:
# -s, --long
if action.nargs == 0:
parts.extend(action.option_strings)
# if the Optional takes a value, format is:
# -s ARGS, --long ARGS
else:
default = action.dest.upper()
args_string = self._format_args(action, default)
for option_string in action.option_strings:
parts.append('%s %s' % (option_string, args_string))
return ', '.join(parts)
def _metavar_formatter(self, action, default_metavar):
if action.metavar is not None:
result = action.metavar
elif action.choices is not None:
choice_strs = [str(choice) for choice in action.choices]
result = '{%s}' % ','.join(choice_strs)
else:
result = default_metavar
def format(tuple_size):
if isinstance(result, tuple):
return result
else:
return (result, ) * tuple_size
return format
def _format_args(self, action, default_metavar):
get_metavar = self._metavar_formatter(action, default_metavar)
if action.nargs is None:
result = '%s' % get_metavar(1)
elif action.nargs == OPTIONAL:
result = '[%s]' % get_metavar(1)
elif action.nargs == ZERO_OR_MORE:
result = '[%s [%s ...]]' % get_metavar(2)
elif action.nargs == ONE_OR_MORE:
result = '%s [%s ...]' % get_metavar(2)
elif action.nargs == REMAINDER:
result = '...'
elif action.nargs == PARSER:
result = '%s ...' % get_metavar(1)
else:
formats = ['%s' for _ in range(action.nargs)]
result = ' '.join(formats) % get_metavar(action.nargs)
return result
def _expand_help(self, action):
params = dict(vars(action), prog=self._prog)
for name in list(params):
if params[name] is SUPPRESS:
del params[name]
for name in list(params):
if hasattr(params[name], '__name__'):
params[name] = params[name].__name__
if params.get('choices') is not None:
choices_str = ', '.join([str(c) for c in params['choices']])
params['choices'] = choices_str
return self._get_help_string(action) % params
def _iter_indented_subactions(self, action):
try:
get_subactions = action._get_subactions
except AttributeError:
pass
else:
self._indent()
for subaction in get_subactions():
yield subaction
self._dedent()
def _split_lines(self, text, width):
text = self._whitespace_matcher.sub(' ', text).strip()
return _textwrap.wrap(text, width)
def _fill_text(self, text, width, indent):
text = self._whitespace_matcher.sub(' ', text).strip()
return _textwrap.fill(text, width, initial_indent=indent,
subsequent_indent=indent)
def _get_help_string(self, action):
return action.help
class RawDescriptionHelpFormatter(HelpFormatter):
"""Help message formatter which retains any formatting in descriptions.
Only the name of this class is considered a public API. All the methods
provided by the class are considered an implementation detail.
"""
def _fill_text(self, text, width, indent):
return ''.join([indent + line for line in text.splitlines(True)])
class RawTextHelpFormatter(RawDescriptionHelpFormatter):
"""Help message formatter which retains formatting of all help text.
Only the name of this class is considered a public API. All the methods
provided by the class are considered an implementation detail.
"""
def _split_lines(self, text, width):
return text.splitlines()
class ArgumentDefaultsHelpFormatter(HelpFormatter):
"""Help message formatter which adds default values to argument help.
Only the name of this class is considered a public API. All the methods
provided by the class are considered an implementation detail.
"""
def _get_help_string(self, action):
help = action.help
if '%(default)' not in action.help:
if action.default is not SUPPRESS:
defaulting_nargs = [OPTIONAL, ZERO_OR_MORE]
if action.option_strings or action.nargs in defaulting_nargs:
help += ' (default: %(default)s)'
return help
# =====================
# Options and Arguments
# =====================
def _get_action_name(argument):
if argument is None:
return None
elif argument.option_strings:
return '/'.join(argument.option_strings)
elif argument.metavar not in (None, SUPPRESS):
return argument.metavar
elif argument.dest not in (None, SUPPRESS):
return argument.dest
else:
return None
class ArgumentError(Exception):
"""An error from creating or using an argument (optional or positional).
The string value of this exception is the message, augmented with
information about the argument that caused it.
"""
def __init__(self, argument, message):
self.argument_name = _get_action_name(argument)
self.message = message
def __str__(self):
if self.argument_name is None:
format = '%(message)s'
else:
format = 'argument %(argument_name)s: %(message)s'
return format % dict(message=self.message,
argument_name=self.argument_name)
class ArgumentTypeError(Exception):
"""An error from trying to convert a command line string to a type."""
pass
# ==============
# Action classes
# ==============
class Action(_AttributeHolder):
"""Information about how to convert command line strings to Python objects.
Action objects are used by an ArgumentParser to represent the information
needed to parse a single argument from one or more strings from the
command line. The keyword arguments to the Action constructor are also
all attributes of Action instances.
Keyword Arguments:
- option_strings -- A list of command-line option strings which
should be associated with this action.
- dest -- The name of the attribute to hold the created object(s)
- nargs -- The number of command-line arguments that should be
consumed. By default, one argument will be consumed and a single
value will be produced. Other values include:
- N (an integer) consumes N arguments (and produces a list)
- '?' consumes zero or one arguments
- '*' consumes zero or more arguments (and produces a list)
- '+' consumes one or more arguments (and produces a list)
Note that the difference between the default and nargs=1 is that
with the default, a single value will be produced, while with
nargs=1, a list containing a single value will be produced.
- const -- The value to be produced if the option is specified and the
option uses an action that takes no values.
- default -- The value to be produced if the option is not specified.
- type -- The type which the command-line arguments should be converted
to, should be one of 'string', 'int', 'float', 'complex' or a
callable object that accepts a single string argument. If None,
'string' is assumed.
- choices -- A container of values that should be allowed. If not None,
after a command-line argument has been converted to the appropriate
type, an exception will be raised if it is not a member of this
collection.
- required -- True if the action must always be specified at the
command line. This is only meaningful for optional command-line
arguments.
- help -- The help string describing the argument.
- metavar -- The name to be used for the option's argument with the
help string. If None, the 'dest' value will be used as the name.
"""
def __init__(self,
option_strings,
dest,
nargs=None,
const=None,
default=None,
type=None,
choices=None,
required=False,
help=None,
metavar=None):
self.option_strings = option_strings
self.dest = dest
self.nargs = nargs
self.const = const
self.default = default
self.type = type
self.choices = choices
self.required = required
self.help = help
self.metavar = metavar
def _get_kwargs(self):
names = [
'option_strings',
'dest',
'nargs',
'const',
'default',
'type',
'choices',
'help',
'metavar',
]
return [(name, getattr(self, name)) for name in names]
def __call__(self, parser, namespace, values, option_string=None):
raise NotImplementedError(_('.__call__() not defined'))
class _StoreAction(Action):
def __init__(self,
option_strings,
dest,
nargs=None,
const=None,
default=None,
type=None,
choices=None,
required=False,
help=None,
metavar=None):
if nargs == 0:
raise ValueError('nargs for store actions must be > 0; if you '
'have nothing to store, actions such as store '
'true or store const may be more appropriate')
if const is not None and nargs != OPTIONAL:
raise ValueError('nargs must be %r to supply const' % OPTIONAL)
super(_StoreAction, self).__init__(
option_strings=option_strings,
dest=dest,
nargs=nargs,
const=const,
default=default,
type=type,
choices=choices,
required=required,
help=help,
metavar=metavar)
def __call__(self, parser, namespace, values, option_string=None):
setattr(namespace, self.dest, values)
class _StoreConstAction(Action):
def __init__(self,
option_strings,
dest,
const,
default=None,
required=False,
help=None,
metavar=None):
super(_StoreConstAction, self).__init__(
option_strings=option_strings,
dest=dest,
nargs=0,
const=const,
default=default,
required=required,
help=help)
def __call__(self, parser, namespace, values, option_string=None):
setattr(namespace, self.dest, self.const)
class _StoreTrueAction(_StoreConstAction):
def __init__(self,
option_strings,
dest,
default=False,
required=False,
help=None):
super(_StoreTrueAction, self).__init__(
option_strings=option_strings,
dest=dest,
const=True,
default=default,
required=required,
help=help)
class _StoreFalseAction(_StoreConstAction):
def __init__(self,
option_strings,
dest,
default=True,
required=False,
help=None):
super(_StoreFalseAction, self).__init__(
option_strings=option_strings,
dest=dest,
const=False,
default=default,
required=required,
help=help)
class _AppendAction(Action):
def __init__(self,
option_strings,
dest,
nargs=None,
const=None,
default=None,
type=None,
choices=None,
required=False,
help=None,
metavar=None):
if nargs == 0:
raise ValueError('nargs for append actions must be > 0; if arg '
'strings are not supplying the value to append, '
'the append const action may be more appropriate')
if const is not None and nargs != OPTIONAL:
raise ValueError('nargs must be %r to supply const' % OPTIONAL)
super(_AppendAction, self).__init__(
option_strings=option_strings,
dest=dest,
nargs=nargs,
const=const,
default=default,
type=type,
choices=choices,
required=required,
help=help,
metavar=metavar)
def __call__(self, parser, namespace, values, option_string=None):
items = _copy.copy(_ensure_value(namespace, self.dest, []))
items.append(values)
setattr(namespace, self.dest, items)
class _AppendConstAction(Action):
def __init__(self,
option_strings,
dest,
const,
default=None,
required=False,
help=None,
metavar=None):
super(_AppendConstAction, self).__init__(
option_strings=option_strings,
dest=dest,
nargs=0,
const=const,
default=default,
required=required,
help=help,
metavar=metavar)
def __call__(self, parser, namespace, values, option_string=None):
items = _copy.copy(_ensure_value(namespace, self.dest, []))
items.append(self.const)
setattr(namespace, self.dest, items)
class _CountAction(Action):
def __init__(self,
option_strings,
dest,
default=None,
required=False,
help=None):
super(_CountAction, self).__init__(
option_strings=option_strings,
dest=dest,
nargs=0,
default=default,
required=required,
help=help)
def __call__(self, parser, namespace, values, option_string=None):
new_count = _ensure_value(namespace, self.dest, 0) + 1
setattr(namespace, self.dest, new_count)
class _HelpAction(Action):
def __init__(self,
option_strings,
dest=SUPPRESS,
default=SUPPRESS,
help=None):
super(_HelpAction, self).__init__(
option_strings=option_strings,
dest=dest,
default=default,
nargs=0,
help=help)
def __call__(self, parser, namespace, values, option_string=None):
parser.print_help()
parser.exit()
class _VersionAction(Action):
def __init__(self,
option_strings,
version=None,
dest=SUPPRESS,
default=SUPPRESS,
help=None):
super(_VersionAction, self).__init__(
option_strings=option_strings,
dest=dest,
default=default,
nargs=0,
help=help)
self.version = version
def __call__(self, parser, namespace, values, option_string=None):
version = self.version
if version is None:
version = parser.version
formatter = parser._get_formatter()
formatter.add_text(version)
parser.exit(message=formatter.format_help())
class _SubParsersAction(Action):
class _ChoicesPseudoAction(Action):
def __init__(self, name, help):
sup = super(_SubParsersAction._ChoicesPseudoAction, self)
sup.__init__(option_strings=[], dest=name, help=help)
def __init__(self,
option_strings,
prog,
parser_class,
dest=SUPPRESS,
help=None,
metavar=None):
self._prog_prefix = prog
self._parser_class = parser_class
self._name_parser_map = {}
self._choices_actions = []
super(_SubParsersAction, self).__init__(
option_strings=option_strings,
dest=dest,
nargs=PARSER,
choices=self._name_parser_map,
help=help,
metavar=metavar)
def add_parser(self, name, **kwargs):
# set prog from the existing prefix
if kwargs.get('prog') is None:
kwargs['prog'] = '%s %s' % (self._prog_prefix, name)
# create a pseudo-action to hold the choice help
if 'help' in kwargs:
help = kwargs.pop('help')
choice_action = self._ChoicesPseudoAction(name, help)
self._choices_actions.append(choice_action)
# create the parser and add it to the map
parser = self._parser_class(**kwargs)
self._name_parser_map[name] = parser
return parser
def _get_subactions(self):
return self._choices_actions
def __call__(self, parser, namespace, values, option_string=None):
parser_name = values[0]
arg_strings = values[1:]
# set the parser name if requested
if self.dest is not SUPPRESS:
setattr(namespace, self.dest, parser_name)
# select the parser
try:
parser = self._name_parser_map[parser_name]
except KeyError:
tup = parser_name, ', '.join(self._name_parser_map)
msg = _('unknown parser %r (choices: %s)' % tup)
raise ArgumentError(self, msg)
# parse all the remaining options into the namespace
parser.parse_args(arg_strings, namespace)
# ==============
# Type classes
# ==============
class FileType(object):
"""Factory for creating file object types
Instances of FileType are typically passed as type= arguments to the
ArgumentParser add_argument() method.
Keyword Arguments:
- mode -- A string indicating how the file is to be opened. Accepts the
same values as the builtin open() function.
- bufsize -- The file's desired buffer size. Accepts the same values as
the builtin open() function.
"""
def __init__(self, mode='r', bufsize=None):
self._mode = mode
self._bufsize = bufsize
def __call__(self, string):
# the special argument "-" means sys.std{in,out}
if string == '-':
if 'r' in self._mode:
return _sys.stdin
elif 'w' in self._mode:
return _sys.stdout
else:
msg = _('argument "-" with mode %r' % self._mode)
raise ValueError(msg)
# all other arguments are used as file names
if self._bufsize:
return open(string, self._mode, self._bufsize)
else:
return open(string, self._mode)
def __repr__(self):
args = [self._mode, self._bufsize]
args_str = ', '.join([repr(arg) for arg in args if arg is not None])
return '%s(%s)' % (type(self).__name__, args_str)
# ===========================
# Optional and Positional Parsing
# ===========================
class Namespace(_AttributeHolder):
"""Simple object for storing attributes.
Implements equality by attribute names and values, and provides a simple
string representation.
"""
def __init__(self, **kwargs):
for name in kwargs:
setattr(self, name, kwargs[name])
def __eq__(self, other):
return vars(self) == vars(other)
def __ne__(self, other):
return not (self == other)
def __contains__(self, key):
return key in self.__dict__
class _ActionsContainer(object):
def __init__(self,
description,
prefix_chars,
argument_default,
conflict_handler):
super(_ActionsContainer, self).__init__()
self.description = description
self.argument_default = argument_default
self.prefix_chars = prefix_chars
self.conflict_handler = conflict_handler
# set up registries
self._registries = {}
# register actions
self.register('action', None, _StoreAction)
self.register('action', 'store', _StoreAction)
self.register('action', 'store_const', _StoreConstAction)
self.register('action', 'store_true', _StoreTrueAction)
self.register('action', 'store_false', _StoreFalseAction)
self.register('action', 'append', _AppendAction)
self.register('action', 'append_const', _AppendConstAction)
self.register('action', 'count', _CountAction)
self.register('action', 'help', _HelpAction)
self.register('action', 'version', _VersionAction)
self.register('action', 'parsers', _SubParsersAction)
# raise an exception if the conflict handler is invalid
self._get_handler()
# action storage
self._actions = []
self._option_string_actions = {}
# groups
self._action_groups = []
self._mutually_exclusive_groups = []
# defaults storage
self._defaults = {}
# determines whether an "option" looks like a negative number
self._negative_number_matcher = _re.compile(r'^-\d+$|^-\d*\.\d+$')
# whether or not there are any optionals that look like negative
# numbers -- uses a list so it can be shared and edited
self._has_negative_number_optionals = []
# ====================
# Registration methods
# ====================
def register(self, registry_name, value, object):
registry = self._registries.setdefault(registry_name, {})
registry[value] = object
def _registry_get(self, registry_name, value, default=None):
return self._registries[registry_name].get(value, default)
# ==================================
# Namespace default accessor methods
# ==================================
def set_defaults(self, **kwargs):
self._defaults.update(kwargs)
# if these defaults match any existing arguments, replace
# the previous default on the object with the new one
for action in self._actions:
if action.dest in kwargs:
action.default = kwargs[action.dest]
def get_default(self, dest):
for action in self._actions:
if action.dest == dest and action.default is not None:
return action.default
return self._defaults.get(dest, None)
# =======================
# Adding argument actions
# =======================
def add_argument(self, *args, **kwargs):
"""
add_argument(dest, ..., name=value, ...)
add_argument(option_string, option_string, ..., name=value, ...)
"""
# if no positional args are supplied or only one is supplied and
# it doesn't look like an option string, parse a positional
# argument
chars = self.prefix_chars
if not args or len(args) == 1 and args[0][0] not in chars:
if args and 'dest' in kwargs:
raise ValueError('dest supplied twice for positional argument')
kwargs = self._get_positional_kwargs(*args, **kwargs)
# otherwise, we're adding an optional argument
else:
kwargs = self._get_optional_kwargs(*args, **kwargs)
# if no default was supplied, use the parser-level default
if 'default' not in kwargs:
dest = kwargs['dest']
if dest in self._defaults:
kwargs['default'] = self._defaults[dest]
elif self.argument_default is not None:
kwargs['default'] = self.argument_default
# create the action object, and add it to the parser
action_class = self._pop_action_class(kwargs)
if not _callable(action_class):
raise ValueError('unknown action "%s"' % action_class)
action = action_class(**kwargs)
# raise an error if the action type is not callable
type_func = self._registry_get('type', action.type, action.type)
if not _callable(type_func):
raise ValueError('%r is not callable' % type_func)
return self._add_action(action)
def add_argument_group(self, *args, **kwargs):
group = _ArgumentGroup(self, *args, **kwargs)
self._action_groups.append(group)
return group
def add_mutually_exclusive_group(self, **kwargs):
group = _MutuallyExclusiveGroup(self, **kwargs)
self._mutually_exclusive_groups.append(group)
return group
def _add_action(self, action):
# resolve any conflicts
self._check_conflict(action)
# add to actions list
self._actions.append(action)
action.container = self
# index the action by any option strings it has
for option_string in action.option_strings:
self._option_string_actions[option_string] = action
# set the flag if any option strings look like negative numbers
for option_string in action.option_strings:
if self._negative_number_matcher.match(option_string):
if not self._has_negative_number_optionals:
self._has_negative_number_optionals.append(True)
# return the created action
return action
def _remove_action(self, action):
self._actions.remove(action)
def _add_container_actions(self, container):
# collect groups by titles
title_group_map = {}
for group in self._action_groups:
if group.title in title_group_map:
msg = _('cannot merge actions - two groups are named %r')
raise ValueError(msg % (group.title))
title_group_map[group.title] = group
# map each action to its group
group_map = {}
for group in container._action_groups:
# if a group with the title exists, use that, otherwise
# create a new group matching the container's group
if group.title not in title_group_map:
title_group_map[group.title] = self.add_argument_group(
title=group.title,
description=group.description,
conflict_handler=group.conflict_handler)
# map the actions to their new group
for action in group._group_actions:
group_map[action] = title_group_map[group.title]
# add container's mutually exclusive groups
# NOTE: if add_mutually_exclusive_group ever gains title= and
# description= then this code will need to be expanded as above
for group in container._mutually_exclusive_groups:
mutex_group = self.add_mutually_exclusive_group(
required=group.required)
# map the actions to their new mutex group
for action in group._group_actions:
group_map[action] = mutex_group
# add all actions to this container or their group
for action in container._actions:
group_map.get(action, self)._add_action(action)
def _get_positional_kwargs(self, dest, **kwargs):
# make sure required is not specified
if 'required' in kwargs:
msg = _("'required' is an invalid argument for positionals")
raise TypeError(msg)
# mark positional arguments as required if at least one is
# always required
if kwargs.get('nargs') not in [OPTIONAL, ZERO_OR_MORE]:
kwargs['required'] = True
if kwargs.get('nargs') == ZERO_OR_MORE and 'default' not in kwargs:
kwargs['required'] = True
# return the keyword arguments with no option strings
return dict(kwargs, dest=dest, option_strings=[])
def _get_optional_kwargs(self, *args, **kwargs):
# determine short and long option strings
option_strings = []
long_option_strings = []
for option_string in args:
# error on strings that don't start with an appropriate prefix
if not option_string[0] in self.prefix_chars:
msg = _('invalid option string %r: '
'must start with a character %r')
tup = option_string, self.prefix_chars
raise ValueError(msg % tup)
# strings starting with two prefix characters are long options
option_strings.append(option_string)
if option_string[0] in self.prefix_chars:
if len(option_string) > 1:
if option_string[1] in self.prefix_chars:
long_option_strings.append(option_string)
# infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x'
dest = kwargs.pop('dest', None)
if dest is None:
if long_option_strings:
dest_option_string = long_option_strings[0]
else:
dest_option_string = option_strings[0]
dest = dest_option_string.lstrip(self.prefix_chars)
if not dest:
msg = _('dest= is required for options like %r')
raise ValueError(msg % option_string)
dest = dest.replace('-', '_')
# return the updated keyword arguments
return dict(kwargs, dest=dest, option_strings=option_strings)
def _pop_action_class(self, kwargs, default=None):
action = kwargs.pop('action', default)
return self._registry_get('action', action, action)
def _get_handler(self):
# determine function from conflict handler string
handler_func_name = '_handle_conflict_%s' % self.conflict_handler
try:
return getattr(self, handler_func_name)
except AttributeError:
msg = _('invalid conflict_resolution value: %r')
raise ValueError(msg % self.conflict_handler)
def _check_conflict(self, action):
# find all options that conflict with this option
confl_optionals = []
for option_string in action.option_strings:
if option_string in self._option_string_actions:
confl_optional = self._option_string_actions[option_string]
confl_optionals.append((option_string, confl_optional))
# resolve any conflicts
if confl_optionals:
conflict_handler = self._get_handler()
conflict_handler(action, confl_optionals)
def _handle_conflict_error(self, action, conflicting_actions):
message = _('conflicting option string(s): %s')
conflict_string = ', '.join([option_string
for option_string, action
in conflicting_actions])
raise ArgumentError(action, message % conflict_string)
def _handle_conflict_resolve(self, action, conflicting_actions):
# remove all conflicting options
for option_string, action in conflicting_actions:
# remove the conflicting option
action.option_strings.remove(option_string)
self._option_string_actions.pop(option_string, None)
# if the option now has no option string, remove it from the
# container holding it
if not action.option_strings:
action.container._remove_action(action)
class _ArgumentGroup(_ActionsContainer):
def __init__(self, container, title=None, description=None, **kwargs):
# add any missing keyword arguments by checking the container
update = kwargs.setdefault
update('conflict_handler', container.conflict_handler)
update('prefix_chars', container.prefix_chars)
update('argument_default', container.argument_default)
super_init = super(_ArgumentGroup, self).__init__
super_init(description=description, **kwargs)
# group attributes
self.title = title
self._group_actions = []
# share most attributes with the container
self._registries = container._registries
self._actions = container._actions
self._option_string_actions = container._option_string_actions
self._defaults = container._defaults
self._has_negative_number_optionals = \
container._has_negative_number_optionals
def _add_action(self, action):
action = super(_ArgumentGroup, self)._add_action(action)
self._group_actions.append(action)
return action
def _remove_action(self, action):
super(_ArgumentGroup, self)._remove_action(action)
self._group_actions.remove(action)
class _MutuallyExclusiveGroup(_ArgumentGroup):
def __init__(self, container, required=False):
super(_MutuallyExclusiveGroup, self).__init__(container)
self.required = required
self._container = container
def _add_action(self, action):
if action.required:
msg = _('mutually exclusive arguments must be optional')
raise ValueError(msg)
action = self._container._add_action(action)
self._group_actions.append(action)
return action
def _remove_action(self, action):
self._container._remove_action(action)
self._group_actions.remove(action)
class ArgumentParser(_AttributeHolder, _ActionsContainer):
"""Object for parsing command line strings into Python objects.
Keyword Arguments:
- prog -- The name of the program (default: sys.argv[0])
- usage -- A usage message (default: auto-generated from arguments)
- description -- A description of what the program does
- epilog -- Text following the argument descriptions
- parents -- Parsers whose arguments should be copied into this one
- formatter_class -- HelpFormatter class for printing help messages
- prefix_chars -- Characters that prefix optional arguments
- fromfile_prefix_chars -- Characters that prefix files containing
additional arguments
- argument_default -- The default value for all arguments
- conflict_handler -- String indicating how to handle conflicts
- add_help -- Add a -h/-help option
"""
def __init__(self,
prog=None,
usage=None,
description=None,
epilog=None,
version=None,
parents=[],
formatter_class=HelpFormatter,
prefix_chars='-',
fromfile_prefix_chars=None,
argument_default=None,
conflict_handler='error',
add_help=True):
if version is not None:
import warnings
warnings.warn(
"""The "version" argument to ArgumentParser is deprecated. """
"""Please use """
""""add_argument(..., action='version', version="N", ...)" """
"""instead""", DeprecationWarning)
superinit = super(ArgumentParser, self).__init__
superinit(description=description,
prefix_chars=prefix_chars,
argument_default=argument_default,
conflict_handler=conflict_handler)
# default setting for prog
if prog is None:
prog = _os.path.basename(_sys.argv[0])
self.prog = prog
self.usage = usage
self.epilog = epilog
self.version = version
self.formatter_class = formatter_class
self.fromfile_prefix_chars = fromfile_prefix_chars
self.add_help = add_help
add_group = self.add_argument_group
self._positionals = add_group(_('positional arguments'))
self._optionals = add_group(_('optional arguments'))
self._subparsers = None
# register types
def identity(string):
return string
self.register('type', None, identity)
# add help and version arguments if necessary
# (using explicit default to override global argument_default)
if self.add_help:
self.add_argument(
'-h', '--help', action='help', default=SUPPRESS,
help=_('show this help message and exit'))
if self.version:
self.add_argument(
'-v', '--version', action='version', default=SUPPRESS,
version=self.version,
help=_("show program's version number and exit"))
# add parent arguments and defaults
for parent in parents:
self._add_container_actions(parent)
try:
defaults = parent._defaults
except AttributeError:
pass
else:
self._defaults.update(defaults)
# =======================
# Pretty __repr__ methods
# =======================
def _get_kwargs(self):
names = [
'prog',
'usage',
'description',
'version',
'formatter_class',
'conflict_handler',
'add_help',
]
return [(name, getattr(self, name)) for name in names]
# ==================================
# Optional/Positional adding methods
# ==================================
def add_subparsers(self, **kwargs):
if self._subparsers is not None:
self.error(_('cannot have multiple subparser arguments'))
# add the parser class to the arguments if it's not present
kwargs.setdefault('parser_class', type(self))
if 'title' in kwargs or 'description' in kwargs:
title = _(kwargs.pop('title', 'subcommands'))
description = _(kwargs.pop('description', None))
self._subparsers = self.add_argument_group(title, description)
else:
self._subparsers = self._positionals
# prog defaults to the usage message of this parser, skipping
# optional arguments and with no "usage:" prefix
if kwargs.get('prog') is None:
formatter = self._get_formatter()
positionals = self._get_positional_actions()
groups = self._mutually_exclusive_groups
formatter.add_usage(self.usage, positionals, groups, '')
kwargs['prog'] = formatter.format_help().strip()
# create the parsers action and add it to the positionals list
parsers_class = self._pop_action_class(kwargs, 'parsers')
action = parsers_class(option_strings=[], **kwargs)
self._subparsers._add_action(action)
# return the created parsers action
return action
def _add_action(self, action):
if action.option_strings:
self._optionals._add_action(action)
else:
self._positionals._add_action(action)
return action
def _get_optional_actions(self):
return [action
for action in self._actions
if action.option_strings]
def _get_positional_actions(self):
return [action
for action in self._actions
if not action.option_strings]
# =====================================
# Command line argument parsing methods
# =====================================
def parse_args(self, args=None, namespace=None):
args, argv = self.parse_known_args(args, namespace)
if argv:
msg = _('unrecognized arguments: %s')
self.error(msg % ' '.join(argv))
return args
def parse_known_args(self, args=None, namespace=None):
# args default to the system args
if args is None:
args = _sys.argv[1:]
# default Namespace built from parser defaults
if namespace is None:
namespace = Namespace()
# add any action defaults that aren't present
for action in self._actions:
if action.dest is not SUPPRESS:
if not hasattr(namespace, action.dest):
if action.default is not SUPPRESS:
default = action.default
if isinstance(action.default, _basestring):
default = self._get_value(action, default)
setattr(namespace, action.dest, default)
# add any parser defaults that aren't present
for dest in self._defaults:
if not hasattr(namespace, dest):
setattr(namespace, dest, self._defaults[dest])
# parse the arguments and exit if there are any errors
try:
return self._parse_known_args(args, namespace)
except ArgumentError:
err = _sys.exc_info()[1]
self.error(str(err))
def _parse_known_args(self, arg_strings, namespace):
# replace arg strings that are file references
if self.fromfile_prefix_chars is not None:
arg_strings = self._read_args_from_files(arg_strings)
# map all mutually exclusive arguments to the other arguments
# they can't occur with
action_conflicts = {}
for mutex_group in self._mutually_exclusive_groups:
group_actions = mutex_group._group_actions
for i, mutex_action in enumerate(mutex_group._group_actions):
conflicts = action_conflicts.setdefault(mutex_action, [])
conflicts.extend(group_actions[:i])
conflicts.extend(group_actions[i + 1:])
# find all option indices, and determine the arg_string_pattern
# which has an 'O' if there is an option at an index,
# an 'A' if there is an argument, or a '-' if there is a '--'
option_string_indices = {}
arg_string_pattern_parts = []
arg_strings_iter = iter(arg_strings)
for i, arg_string in enumerate(arg_strings_iter):
# all args after -- are non-options
if arg_string == '--':
arg_string_pattern_parts.append('-')
for arg_string in arg_strings_iter:
arg_string_pattern_parts.append('A')
# otherwise, add the arg to the arg strings
# and note the index if it was an option
else:
option_tuple = self._parse_optional(arg_string)
if option_tuple is None:
pattern = 'A'
else:
option_string_indices[i] = option_tuple
pattern = 'O'
arg_string_pattern_parts.append(pattern)
# join the pieces together to form the pattern
arg_strings_pattern = ''.join(arg_string_pattern_parts)
# converts arg strings to the appropriate and then takes the action
seen_actions = _set()
seen_non_default_actions = _set()
def take_action(action, argument_strings, option_string=None):
seen_actions.add(action)
argument_values = self._get_values(action, argument_strings)
# error if this argument is not allowed with other previously
# seen arguments, assuming that actions that use the default
# value don't really count as "present"
if argument_values is not action.default:
seen_non_default_actions.add(action)
for conflict_action in action_conflicts.get(action, []):
if conflict_action in seen_non_default_actions:
msg = _('not allowed with argument %s')
action_name = _get_action_name(conflict_action)
raise ArgumentError(action, msg % action_name)
# take the action if we didn't receive a SUPPRESS value
# (e.g. from a default)
if argument_values is not SUPPRESS:
action(self, namespace, argument_values, option_string)
# function to convert arg_strings into an optional action
def consume_optional(start_index):
# get the optional identified at this index
option_tuple = option_string_indices[start_index]
action, option_string, explicit_arg = option_tuple
# identify additional optionals in the same arg string
# (e.g. -xyz is the same as -x -y -z if no args are required)
match_argument = self._match_argument
action_tuples = []
while True:
# if we found no optional action, skip it
if action is None:
extras.append(arg_strings[start_index])
return start_index + 1
# if there is an explicit argument, try to match the
# optional's string arguments to only this
if explicit_arg is not None:
arg_count = match_argument(action, 'A')
# if the action is a single-dash option and takes no
# arguments, try to parse more single-dash options out
# of the tail of the option string
chars = self.prefix_chars
if arg_count == 0 and option_string[1] not in chars:
action_tuples.append((action, [], option_string))
for char in self.prefix_chars:
option_string = char + explicit_arg[0]
explicit_arg = explicit_arg[1:] or None
optionals_map = self._option_string_actions
if option_string in optionals_map:
action = optionals_map[option_string]
break
else:
msg = _('ignored explicit argument %r')
raise ArgumentError(action, msg % explicit_arg)
# if the action expect exactly one argument, we've
# successfully matched the option; exit the loop
elif arg_count == 1:
stop = start_index + 1
args = [explicit_arg]
action_tuples.append((action, args, option_string))
break
# error if a double-dash option did not use the
# explicit argument
else:
msg = _('ignored explicit argument %r')
raise ArgumentError(action, msg % explicit_arg)
# if there is no explicit argument, try to match the
# optional's string arguments with the following strings
# if successful, exit the loop
else:
start = start_index + 1
selected_patterns = arg_strings_pattern[start:]
arg_count = match_argument(action, selected_patterns)
stop = start + arg_count
args = arg_strings[start:stop]
action_tuples.append((action, args, option_string))
break
# add the Optional to the list and return the index at which
# the Optional's string args stopped
assert action_tuples
for action, args, option_string in action_tuples:
take_action(action, args, option_string)
return stop
# the list of Positionals left to be parsed; this is modified
# by consume_positionals()
positionals = self._get_positional_actions()
# function to convert arg_strings into positional actions
def consume_positionals(start_index):
# match as many Positionals as possible
match_partial = self._match_arguments_partial
selected_pattern = arg_strings_pattern[start_index:]
arg_counts = match_partial(positionals, selected_pattern)
# slice off the appropriate arg strings for each Positional
# and add the Positional and its args to the list
for action, arg_count in zip(positionals, arg_counts):
args = arg_strings[start_index: start_index + arg_count]
start_index += arg_count
take_action(action, args)
# slice off the Positionals that we just parsed and return the
# index at which the Positionals' string args stopped
positionals[:] = positionals[len(arg_counts):]
return start_index
# consume Positionals and Optionals alternately, until we have
# passed the last option string
extras = []
start_index = 0
if option_string_indices:
max_option_string_index = max(option_string_indices)
else:
max_option_string_index = -1
while start_index <= max_option_string_index:
# consume any Positionals preceding the next option
next_option_string_index = min([
index
for index in option_string_indices
if index >= start_index])
if start_index != next_option_string_index:
positionals_end_index = consume_positionals(start_index)
# only try to parse the next optional if we didn't consume
# the option string during the positionals parsing
if positionals_end_index > start_index:
start_index = positionals_end_index
continue
else:
start_index = positionals_end_index
# if we consumed all the positionals we could and we're not
# at the index of an option string, there were extra arguments
if start_index not in option_string_indices:
strings = arg_strings[start_index:next_option_string_index]
extras.extend(strings)
start_index = next_option_string_index
# consume the next optional and any arguments for it
start_index = consume_optional(start_index)
# consume any positionals following the last Optional
stop_index = consume_positionals(start_index)
# if we didn't consume all the argument strings, there were extras
extras.extend(arg_strings[stop_index:])
# if we didn't use all the Positional objects, there were too few
# arg strings supplied.
if positionals:
self.error(_('too few arguments'))
# make sure all required actions were present
for action in self._actions:
if action.required:
if action not in seen_actions:
name = _get_action_name(action)
self.error(_('argument %s is required') % name)
# make sure all required groups had one option present
for group in self._mutually_exclusive_groups:
if group.required:
for action in group._group_actions:
if action in seen_non_default_actions:
break
# if no actions were used, report the error
else:
names = [_get_action_name(action)
for action in group._group_actions
if action.help is not SUPPRESS]
msg = _('one of the arguments %s is required')
self.error(msg % ' '.join(names))
# return the updated namespace and the extra arguments
return namespace, extras
def _read_args_from_files(self, arg_strings):
# expand arguments referencing files
new_arg_strings = []
for arg_string in arg_strings:
# for regular arguments, just add them back into the list
if arg_string[0] not in self.fromfile_prefix_chars:
new_arg_strings.append(arg_string)
# replace arguments referencing files with the file content
else:
try:
args_file = open(arg_string[1:])
try:
arg_strings = []
for arg_line in args_file.read().splitlines():
for arg in self.convert_arg_line_to_args(arg_line):
arg_strings.append(arg)
arg_strings = self._read_args_from_files(arg_strings)
new_arg_strings.extend(arg_strings)
finally:
args_file.close()
except IOError:
err = _sys.exc_info()[1]
self.error(str(err))
# return the modified argument list
return new_arg_strings
def convert_arg_line_to_args(self, arg_line):
return [arg_line]
def _match_argument(self, action, arg_strings_pattern):
# match the pattern for this action to the arg strings
nargs_pattern = self._get_nargs_pattern(action)
match = _re.match(nargs_pattern, arg_strings_pattern)
# raise an exception if we weren't able to find a match
if match is None:
nargs_errors = {
None: _('expected one argument'),
OPTIONAL: _('expected at most one argument'),
ONE_OR_MORE: _('expected at least one argument'),
}
default = _('expected %s argument(s)') % action.nargs
msg = nargs_errors.get(action.nargs, default)
raise ArgumentError(action, msg)
# return the number of arguments matched
return len(match.group(1))
def _match_arguments_partial(self, actions, arg_strings_pattern):
# progressively shorten the actions list by slicing off the
# final actions until we find a match
result = []
for i in range(len(actions), 0, -1):
actions_slice = actions[:i]
pattern = ''.join([self._get_nargs_pattern(action)
for action in actions_slice])
match = _re.match(pattern, arg_strings_pattern)
if match is not None:
result.extend([len(string) for string in match.groups()])
break
# return the list of arg string counts
return result
def _parse_optional(self, arg_string):
# if it's an empty string, it was meant to be a positional
if not arg_string:
return None
# if it doesn't start with a prefix, it was meant to be positional
if not arg_string[0] in self.prefix_chars:
return None
# if the option string is present in the parser, return the action
if arg_string in self._option_string_actions:
action = self._option_string_actions[arg_string]
return action, arg_string, None
# if it's just a single character, it was meant to be positional
if len(arg_string) == 1:
return None
# if the option string before the "=" is present, return the action
if '=' in arg_string:
option_string, explicit_arg = arg_string.split('=', 1)
if option_string in self._option_string_actions:
action = self._option_string_actions[option_string]
return action, option_string, explicit_arg
# search through all possible prefixes of the option string
# and all actions in the parser for possible interpretations
option_tuples = self._get_option_tuples(arg_string)
# if multiple actions match, the option string was ambiguous
if len(option_tuples) > 1:
options = ', '.join([option_string
for action, option_string, explicit_arg in option_tuples])
tup = arg_string, options
self.error(_('ambiguous option: %s could match %s') % tup)
# if exactly one action matched, this segmentation is good,
# so return the parsed action
elif len(option_tuples) == 1:
option_tuple, = option_tuples
return option_tuple
# if it was not found as an option, but it looks like a negative
# number, it was meant to be positional
# unless there are negative-number-like options
if self._negative_number_matcher.match(arg_string):
if not self._has_negative_number_optionals:
return None
# if it contains a space, it was meant to be a positional
if ' ' in arg_string:
return None
# it was meant to be an optional but there is no such option
# in this parser (though it might be a valid option in a subparser)
return None, arg_string, None
def _get_option_tuples(self, option_string):
result = []
# option strings starting with two prefix characters are only
# split at the '='
chars = self.prefix_chars
if option_string[0] in chars and option_string[1] in chars:
if '=' in option_string:
option_prefix, explicit_arg = option_string.split('=', 1)
else:
option_prefix = option_string
explicit_arg = None
for option_string in self._option_string_actions:
if option_string.startswith(option_prefix):
action = self._option_string_actions[option_string]
tup = action, option_string, explicit_arg
result.append(tup)
# single character options can be concatenated with their arguments
# but multiple character options always have to have their argument
# separate
elif option_string[0] in chars and option_string[1] not in chars:
option_prefix = option_string
explicit_arg = None
short_option_prefix = option_string[:2]
short_explicit_arg = option_string[2:]
for option_string in self._option_string_actions:
if option_string == short_option_prefix:
action = self._option_string_actions[option_string]
tup = action, option_string, short_explicit_arg
result.append(tup)
elif option_string.startswith(option_prefix):
action = self._option_string_actions[option_string]
tup = action, option_string, explicit_arg
result.append(tup)
# shouldn't ever get here
else:
self.error(_('unexpected option string: %s') % option_string)
# return the collected option tuples
return result
def _get_nargs_pattern(self, action):
# in all examples below, we have to allow for '--' args
# which are represented as '-' in the pattern
nargs = action.nargs
# the default (None) is assumed to be a single argument
if nargs is None:
nargs_pattern = '(-*A-*)'
# allow zero or one arguments
elif nargs == OPTIONAL:
nargs_pattern = '(-*A?-*)'
# allow zero or more arguments
elif nargs == ZERO_OR_MORE:
nargs_pattern = '(-*[A-]*)'
# allow one or more arguments
elif nargs == ONE_OR_MORE:
nargs_pattern = '(-*A[A-]*)'
# allow any number of options or arguments
elif nargs == REMAINDER:
nargs_pattern = '([-AO]*)'
# allow one argument followed by any number of options or arguments
elif nargs == PARSER:
nargs_pattern = '(-*A[-AO]*)'
# all others should be integers
else:
nargs_pattern = '(-*%s-*)' % '-*'.join('A' * nargs)
# if this is an optional action, -- is not allowed
if action.option_strings:
nargs_pattern = nargs_pattern.replace('-*', '')
nargs_pattern = nargs_pattern.replace('-', '')
# return the pattern
return nargs_pattern
# ========================
# Value conversion methods
# ========================
def _get_values(self, action, arg_strings):
# for everything but PARSER args, strip out '--'
if action.nargs not in [PARSER, REMAINDER]:
arg_strings = [s for s in arg_strings if s != '--']
# optional argument produces a default when not present
if not arg_strings and action.nargs == OPTIONAL:
if action.option_strings:
value = action.const
else:
value = action.default
if isinstance(value, _basestring):
value = self._get_value(action, value)
self._check_value(action, value)
# when nargs='*' on a positional, if there were no command-line
# args, use the default if it is anything other than None
elif (not arg_strings and action.nargs == ZERO_OR_MORE and
not action.option_strings):
if action.default is not None:
value = action.default
else:
value = arg_strings
self._check_value(action, value)
# single argument or optional argument produces a single value
elif len(arg_strings) == 1 and action.nargs in [None, OPTIONAL]:
arg_string, = arg_strings
value = self._get_value(action, arg_string)
self._check_value(action, value)
# REMAINDER arguments convert all values, checking none
elif action.nargs == REMAINDER:
value = [self._get_value(action, v) for v in arg_strings]
# PARSER arguments convert all values, but check only the first
elif action.nargs == PARSER:
value = [self._get_value(action, v) for v in arg_strings]
self._check_value(action, value[0])
# all other types of nargs produce a list
else:
value = [self._get_value(action, v) for v in arg_strings]
for v in value:
self._check_value(action, v)
# return the converted value
return value
def _get_value(self, action, arg_string):
type_func = self._registry_get('type', action.type, action.type)
if not _callable(type_func):
msg = _('%r is not callable')
raise ArgumentError(action, msg % type_func)
# convert the value to the appropriate type
try:
result = type_func(arg_string)
# ArgumentTypeErrors indicate errors
except ArgumentTypeError:
name = getattr(action.type, '__name__', repr(action.type))
msg = str(_sys.exc_info()[1])
raise ArgumentError(action, msg)
# TypeErrors or ValueErrors also indicate errors
except (TypeError, ValueError):
name = getattr(action.type, '__name__', repr(action.type))
msg = _('invalid %s value: %r')
raise ArgumentError(action, msg % (name, arg_string))
# return the converted value
return result
def _check_value(self, action, value):
# converted value must be one of the choices (if specified)
if action.choices is not None and value not in action.choices:
tup = value, ', '.join(map(repr, action.choices))
msg = _('invalid choice: %r (choose from %s)') % tup
raise ArgumentError(action, msg)
# =======================
# Help-formatting methods
# =======================
def format_usage(self):
formatter = self._get_formatter()
formatter.add_usage(self.usage, self._actions,
self._mutually_exclusive_groups)
return formatter.format_help()
def format_help(self):
formatter = self._get_formatter()
# usage
formatter.add_usage(self.usage, self._actions,
self._mutually_exclusive_groups)
# description
formatter.add_text(self.description)
# positionals, optionals and user-defined groups
for action_group in self._action_groups:
formatter.start_section(action_group.title)
formatter.add_text(action_group.description)
formatter.add_arguments(action_group._group_actions)
formatter.end_section()
# epilog
formatter.add_text(self.epilog)
# determine help from format above
return formatter.format_help()
def format_version(self):
import warnings
warnings.warn(
'The format_version method is deprecated -- the "version" '
'argument to ArgumentParser is no longer supported.',
DeprecationWarning)
formatter = self._get_formatter()
formatter.add_text(self.version)
return formatter.format_help()
def _get_formatter(self):
return self.formatter_class(prog=self.prog)
# =====================
# Help-printing methods
# =====================
def print_usage(self, file=None):
if file is None:
file = _sys.stdout
self._print_message(self.format_usage(), file)
def print_help(self, file=None):
if file is None:
file = _sys.stdout
self._print_message(self.format_help(), file)
def print_version(self, file=None):
import warnings
warnings.warn(
'The print_version method is deprecated -- the "version" '
'argument to ArgumentParser is no longer supported.',
DeprecationWarning)
self._print_message(self.format_version(), file)
def _print_message(self, message, file=None):
if message:
if file is None:
file = _sys.stderr
file.write(message)
# ===============
# Exiting methods
# ===============
def exit(self, status=0, message=None):
if message:
self._print_message(message, _sys.stderr)
_sys.exit(status)
def error(self, message):
"""error(message: string)
Prints a usage message incorporating the message to stderr and
exits.
If you override this in a subclass, it should not return -- it
should either exit or raise an exception.
"""
self.print_usage(_sys.stderr)
self.exit(2, _('%s: error: %s\n') % (self.prog, message))
| mit |
firebase/grpc-SwiftPM | examples/python/metadata/helloworld_pb2.py | 146 | 3912 | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: helloworld.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.protobuf import descriptor_pb2
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='helloworld.proto',
package='helloworld',
syntax='proto3',
serialized_pb=_b('\n\x10helloworld.proto\x12\nhelloworld\"\x1c\n\x0cHelloRequest\x12\x0c\n\x04name\x18\x01 \x01(\t\"\x1d\n\nHelloReply\x12\x0f\n\x07message\x18\x01 \x01(\t2I\n\x07Greeter\x12>\n\x08SayHello\x12\x18.helloworld.HelloRequest\x1a\x16.helloworld.HelloReply\"\x00\x42\x36\n\x1bio.grpc.examples.helloworldB\x0fHelloWorldProtoP\x01\xa2\x02\x03HLWb\x06proto3')
)
_HELLOREQUEST = _descriptor.Descriptor(
name='HelloRequest',
full_name='helloworld.HelloRequest',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='name', full_name='helloworld.HelloRequest.name', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=32,
serialized_end=60,
)
_HELLOREPLY = _descriptor.Descriptor(
name='HelloReply',
full_name='helloworld.HelloReply',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='message', full_name='helloworld.HelloReply.message', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=62,
serialized_end=91,
)
DESCRIPTOR.message_types_by_name['HelloRequest'] = _HELLOREQUEST
DESCRIPTOR.message_types_by_name['HelloReply'] = _HELLOREPLY
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
HelloRequest = _reflection.GeneratedProtocolMessageType('HelloRequest', (_message.Message,), dict(
DESCRIPTOR = _HELLOREQUEST,
__module__ = 'helloworld_pb2'
# @@protoc_insertion_point(class_scope:helloworld.HelloRequest)
))
_sym_db.RegisterMessage(HelloRequest)
HelloReply = _reflection.GeneratedProtocolMessageType('HelloReply', (_message.Message,), dict(
DESCRIPTOR = _HELLOREPLY,
__module__ = 'helloworld_pb2'
# @@protoc_insertion_point(class_scope:helloworld.HelloReply)
))
_sym_db.RegisterMessage(HelloReply)
DESCRIPTOR.has_options = True
DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\n\033io.grpc.examples.helloworldB\017HelloWorldProtoP\001\242\002\003HLW'))
_GREETER = _descriptor.ServiceDescriptor(
name='Greeter',
full_name='helloworld.Greeter',
file=DESCRIPTOR,
index=0,
options=None,
serialized_start=93,
serialized_end=166,
methods=[
_descriptor.MethodDescriptor(
name='SayHello',
full_name='helloworld.Greeter.SayHello',
index=0,
containing_service=None,
input_type=_HELLOREQUEST,
output_type=_HELLOREPLY,
options=None,
),
])
_sym_db.RegisterServiceDescriptor(_GREETER)
DESCRIPTOR.services_by_name['Greeter'] = _GREETER
# @@protoc_insertion_point(module_scope)
| apache-2.0 |
bestmjh47/ActiveKernel_S220 | tools/perf/scripts/python/futex-contention.py | 11261 | 1486 | # futex contention
# (c) 2010, Arnaldo Carvalho de Melo <acme@redhat.com>
# Licensed under the terms of the GNU GPL License version 2
#
# Translation of:
#
# http://sourceware.org/systemtap/wiki/WSFutexContention
#
# to perf python scripting.
#
# Measures futex contention
import os, sys
sys.path.append(os.environ['PERF_EXEC_PATH'] + '/scripts/python/Perf-Trace-Util/lib/Perf/Trace')
from Util import *
process_names = {}
thread_thislock = {}
thread_blocktime = {}
lock_waits = {} # long-lived stats on (tid,lock) blockage elapsed time
process_names = {} # long-lived pid-to-execname mapping
def syscalls__sys_enter_futex(event, ctxt, cpu, s, ns, tid, comm,
nr, uaddr, op, val, utime, uaddr2, val3):
cmd = op & FUTEX_CMD_MASK
if cmd != FUTEX_WAIT:
return # we don't care about originators of WAKE events
process_names[tid] = comm
thread_thislock[tid] = uaddr
thread_blocktime[tid] = nsecs(s, ns)
def syscalls__sys_exit_futex(event, ctxt, cpu, s, ns, tid, comm,
nr, ret):
if thread_blocktime.has_key(tid):
elapsed = nsecs(s, ns) - thread_blocktime[tid]
add_stats(lock_waits, (tid, thread_thislock[tid]), elapsed)
del thread_blocktime[tid]
del thread_thislock[tid]
def trace_begin():
print "Press control+C to stop and show the summary"
def trace_end():
for (tid, lock) in lock_waits:
min, max, avg, count = lock_waits[tid, lock]
print "%s[%d] lock %x contended %d times, %d avg ns" % \
(process_names[tid], tid, lock, count, avg)
| gpl-2.0 |
mnahm5/django-estore | Lib/site-packages/django/contrib/flatpages/templatetags/flatpages.py | 472 | 3632 | from django import template
from django.conf import settings
from django.contrib.flatpages.models import FlatPage
from django.contrib.sites.shortcuts import get_current_site
register = template.Library()
class FlatpageNode(template.Node):
def __init__(self, context_name, starts_with=None, user=None):
self.context_name = context_name
if starts_with:
self.starts_with = template.Variable(starts_with)
else:
self.starts_with = None
if user:
self.user = template.Variable(user)
else:
self.user = None
def render(self, context):
if 'request' in context:
site_pk = get_current_site(context['request']).pk
else:
site_pk = settings.SITE_ID
flatpages = FlatPage.objects.filter(sites__id=site_pk)
# If a prefix was specified, add a filter
if self.starts_with:
flatpages = flatpages.filter(
url__startswith=self.starts_with.resolve(context))
# If the provided user is not authenticated, or no user
# was provided, filter the list to only public flatpages.
if self.user:
user = self.user.resolve(context)
if not user.is_authenticated():
flatpages = flatpages.filter(registration_required=False)
else:
flatpages = flatpages.filter(registration_required=False)
context[self.context_name] = flatpages
return ''
@register.tag
def get_flatpages(parser, token):
"""
Retrieves all flatpage objects available for the current site and
visible to the specific user (or visible to all users if no user is
specified). Populates the template context with them in a variable
whose name is defined by the ``as`` clause.
An optional ``for`` clause can be used to control the user whose
permissions are to be used in determining which flatpages are visible.
An optional argument, ``starts_with``, can be applied to limit the
returned flatpages to those beginning with a particular base URL.
This argument can be passed as a variable or a string, as it resolves
from the template context.
Syntax::
{% get_flatpages ['url_starts_with'] [for user] as context_name %}
Example usage::
{% get_flatpages as flatpages %}
{% get_flatpages for someuser as flatpages %}
{% get_flatpages '/about/' as about_pages %}
{% get_flatpages prefix as about_pages %}
{% get_flatpages '/about/' for someuser as about_pages %}
"""
bits = token.split_contents()
syntax_message = ("%(tag_name)s expects a syntax of %(tag_name)s "
"['url_starts_with'] [for user] as context_name" %
dict(tag_name=bits[0]))
# Must have at 3-6 bits in the tag
if len(bits) >= 3 and len(bits) <= 6:
# If there's an even number of bits, there's no prefix
if len(bits) % 2 == 0:
prefix = bits[1]
else:
prefix = None
# The very last bit must be the context name
if bits[-2] != 'as':
raise template.TemplateSyntaxError(syntax_message)
context_name = bits[-1]
# If there are 5 or 6 bits, there is a user defined
if len(bits) >= 5:
if bits[-4] != 'for':
raise template.TemplateSyntaxError(syntax_message)
user = bits[-3]
else:
user = None
return FlatpageNode(context_name, starts_with=prefix, user=user)
else:
raise template.TemplateSyntaxError(syntax_message)
| mit |
hoglet67/ElectronFpga | tools/program_mgc_roms.py | 1 | 1978 | from __future__ import print_function
import os, sys
import program_flash
if sys.version_info < (3, 0):
print("WARNING: This script is no longer tested under Python 2. "
"Running under Python 3 is highly recommended.")
HERE = os.path.abspath(os.path.split(sys.argv[0])[0])
start_addr = 4 * 1024 * 1024
romsize = 16 * 1024
# My MGC dumper program sets page_latch from 0-127 and saves the two
# ROM banks as page_latch*2 and page_latch*2+1. Actually it should
# have saved them as page_latch and page_latch+128.
# As such to translate from a page latch value to a filename, use
# (bank & 0x7f) * 2 + (bank & 128 ? 1 : 0)
# MGC quirk: the bank ID is inverted for single-bank roms... so
# 3d dotty (page latch 89, RBS 0) is actually in bank 89+128 and file 89*2+1=179
def translate(romid):
bank = ((romid & 0x7f) << 1) | (1 if (romid & 128) else 0)
print("translate romid %d (%02x) -> %d (%02x)" % (romid, romid, bank, bank))
return bank
assert translate(0) == 0
assert translate(1) == 2 # arcadians
assert translate(1+128) == 3 # arcadians
assert translate(72) == 144
assert translate(72+128) == 145
assert translate(89+128) == 179 # 3d dotty
assert translate(90+128) == 181
assert translate(91+128) == 183 # alien dropout
assert translate(217-128) == 178 # hopper
assert translate(218-128) == 180 # hunchback
assert translate(219-128) == 182 # jet power jack
def fn(romid):
# I extracted the roms in a different order...
translated_romid = translate(romid)
return '%s/../../../electron/elkjs/elkjs/mgc/mgc_%d.bin' % (HERE, translated_romid)
print("programming 256 mgc roms at %d" % start_addr)
for romid in range(256):
romfn = fn(romid)
romstart = start_addr + romid * romsize
print("- program %s in as rom id %d" % (romfn, romid))
program_flash.upload(open(romfn, "rb").read(),
romstart,
romsize,
program=True,
)
| gpl-3.0 |
cneill/designate | designate/storage/impl_sqlalchemy/migrate_repo/versions/050_drop_servers.py | 8 | 1211 | # Copyright (c) 2015 Rackspace Hosting
#
# Author: Betsy Luzader <betsy.luzader@rackspace.com>
#
# 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 sqlalchemy.schema import Table, MetaData
meta = MetaData()
# No downgrade is possible because once the table is dropped, because there is
# no way to recreate the table with the original data. All data was migrated
# to the PoolAttributes table in the previous migration, however a database
# backup should still be done before the migration
def upgrade(migrate_engine):
meta.bind = migrate_engine
# Load the database tables
servers_table = Table('servers', meta, autoload=True)
servers_table.drop()
def downgrade(migrate_engine):
pass | apache-2.0 |
hyperized/ansible | lib/ansible/modules/network/cnos/cnos_vrf.py | 34 | 11917 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
#
# Copyright (C) 2019 Lenovo.
# (c) 2017, Ansible by 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/>.
#
# Module to work on management of local users on Lenovo CNOS Switches
# Lenovo Networking
#
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = """
---
module: cnos_vrf
version_added: "2.8"
author: "Anil Kumar Muraleedharan (@amuraleedhar)"
short_description: Manage VRFs on Lenovo CNOS network devices
description:
- This module provides declarative management of VRFs
on Lenovo CNOS network devices.
notes:
- Tested against CNOS 10.9.1
options:
name:
description:
- Name of the VRF.
required: true
rd:
description:
- Route distinguisher of the VRF
interfaces:
description:
- Identifies the set of interfaces that
should be configured in the VRF. Interfaces must be routed
interfaces in order to be placed into a VRF. The name of interface
should be in expanded format and not abbreviated.
associated_interfaces:
description:
- This is a intent option and checks the operational state of the for
given vrf C(name) for associated interfaces. If the value in the
C(associated_interfaces) does not match with the operational state of
vrf interfaces on device it will result in failure.
aggregate:
description: List of VRFs contexts
purge:
description:
- Purge VRFs not defined in the I(aggregate) parameter.
default: no
type: bool
delay:
description:
- Time in seconds to wait before checking for the operational state on
remote device. This wait is applicable for operational state arguments.
default: 10
state:
description:
- State of the VRF configuration.
default: present
choices: ['present', 'absent']
"""
EXAMPLES = """
- name: Create vrf
cnos_vrf:
name: test
rd: 1:200
interfaces:
- Ethernet1/33
state: present
- name: Delete VRFs
cnos_vrf:
name: test
state: absent
- name: Create aggregate of VRFs with purge
cnos_vrf:
aggregate:
- { name: test4, rd: "1:204" }
- { name: test5, rd: "1:205" }
state: present
purge: yes
- name: Delete aggregate of VRFs
cnos_vrf:
aggregate:
- name: test2
- name: test3
- name: test4
- name: test5
state: absent
"""
RETURN = """
commands:
description: The list of configuration mode commands to send to the device
returned: always
type: list
sample:
- vrf context test
- rd 1:100
- interface Ethernet1/44
- vrf member test
"""
import re
import time
from copy import deepcopy
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.network.common.utils import remove_default_spec
from ansible.module_utils.network.cnos.cnos import load_config, run_commands
from ansible.module_utils.network.cnos.cnos import cnos_argument_spec, check_args
def search_obj_in_list(name, lst):
for o in lst:
if o['name'] == name:
return o
def get_interface_type(interface):
intf_type = 'unknown'
if interface.upper()[:2] in ('ET', 'GI', 'FA', 'TE', 'FO', 'HU', 'TWE'):
intf_type = 'ethernet'
elif interface.upper().startswith('VL'):
intf_type = 'svi'
elif interface.upper().startswith('LO'):
intf_type = 'loopback'
elif interface.upper()[:2] in ('MG', 'MA'):
intf_type = 'management'
elif interface.upper().startswith('PO'):
intf_type = 'portchannel'
elif interface.upper().startswith('NV'):
intf_type = 'nve'
return intf_type
def is_switchport(name, module):
intf_type = get_interface_type(name)
if intf_type in ('ethernet', 'portchannel'):
config = run_commands(module,
['show interface {0} switchport'.format(name)])[0]
match = re.search(r'Switchport : enabled', config)
return bool(match)
return False
def map_obj_to_commands(updates, module):
commands = list()
want, have = updates
state = module.params['state']
purge = module.params['purge']
for w in want:
name = w['name']
rd = w['rd']
interfaces = w['interfaces']
obj_in_have = search_obj_in_list(name, have)
if name == 'default':
module.fail_json(msg='VRF context default is reserved')
elif len(name) > 63:
module.fail_json(msg='VRF name is too long')
if state == 'absent':
if name == 'management':
module.fail_json(msg='Management VRF context cannot be deleted')
if obj_in_have:
commands.append('no vrf context %s' % name)
elif state == 'present':
if not obj_in_have:
commands.append('vrf context %s' % name)
if rd is not None:
commands.append('rd %s' % rd)
if w['interfaces']:
for i in w['interfaces']:
commands.append('interface %s' % i)
commands.append('vrf member %s' % w['name'])
else:
if w['rd'] is not None and w['rd'] != obj_in_have['rd']:
commands.append('vrf context %s' % w['name'])
commands.append('rd %s' % w['rd'])
if w['interfaces']:
if not obj_in_have['interfaces']:
for i in w['interfaces']:
commands.append('interface %s' % i)
commands.append('vrf member %s' % w['name'])
elif set(w['interfaces']) != obj_in_have['interfaces']:
missing_interfaces = list(set(w['interfaces']) - set(obj_in_have['interfaces']))
for i in missing_interfaces:
commands.append('interface %s' % i)
commands.append('vrf member %s' % w['name'])
if purge:
for h in have:
obj_in_want = search_obj_in_list(h['name'], want)
if not obj_in_want:
commands.append('no vrf context %s' % h['name'])
return commands
def map_config_to_obj(module):
objs = []
output = run_commands(module, {'command': 'show vrf'})
if output is not None:
vrfText = output[0].strip()
vrfList = vrfText.split('VRF')
for vrfItem in vrfList:
if 'FIB ID' in vrfItem:
obj = dict()
list_of_words = vrfItem.split()
vrfName = list_of_words[0]
obj['name'] = vrfName[:-1]
obj['rd'] = list_of_words[list_of_words.index('RD') + 1]
start = False
obj['interfaces'] = []
for intName in list_of_words:
if 'Interfaces' in intName:
start = True
if start is True:
if '!' not in intName and 'Interfaces' not in intName:
obj['interfaces'].append(intName.strip().lower())
objs.append(obj)
else:
module.fail_json(msg='Could not fetch VRF details from device')
return objs
def map_params_to_obj(module):
obj = []
aggregate = module.params.get('aggregate')
if aggregate:
for item in aggregate:
for key in item:
if item.get(key) is None:
item[key] = module.params[key]
if item.get('interfaces'):
item['interfaces'] = [intf.replace(" ", "").lower() for intf in item.get('interfaces') if intf]
if item.get('associated_interfaces'):
item['associated_interfaces'] = [intf.replace(" ", "").lower() for intf in item.get('associated_interfaces') if intf]
obj.append(item.copy())
else:
obj.append({
'name': module.params['name'],
'state': module.params['state'],
'rd': module.params['rd'],
'interfaces': [intf.replace(" ", "").lower() for intf in module.params['interfaces']] if module.params['interfaces'] else [],
'associated_interfaces': [intf.replace(" ", "").lower() for intf in
module.params['associated_interfaces']] if module.params['associated_interfaces'] else []
})
return obj
def check_declarative_intent_params(want, module, result):
have = None
is_delay = False
for w in want:
if w.get('associated_interfaces') is None:
continue
if result['changed'] and not is_delay:
time.sleep(module.params['delay'])
is_delay = True
if have is None:
have = map_config_to_obj(module)
for i in w['associated_interfaces']:
obj_in_have = search_obj_in_list(w['name'], have)
if obj_in_have:
interfaces = obj_in_have.get('interfaces')
if interfaces is not None and i not in interfaces:
module.fail_json(msg="Interface %s not configured on vrf %s" % (i, w['name']))
def main():
""" main entry point for module execution
"""
element_spec = dict(
name=dict(),
interfaces=dict(type='list'),
associated_interfaces=dict(type='list'),
delay=dict(default=10, type='int'),
rd=dict(),
state=dict(default='present', choices=['present', 'absent'])
)
aggregate_spec = deepcopy(element_spec)
# remove default in aggregate spec, to handle common arguments
remove_default_spec(aggregate_spec)
argument_spec = dict(
aggregate=dict(type='list', elements='dict', options=aggregate_spec),
purge=dict(default=False, type='bool')
)
argument_spec.update(element_spec)
required_one_of = [['name', 'aggregate']]
mutually_exclusive = [['name', 'aggregate']]
module = AnsibleModule(argument_spec=argument_spec,
required_one_of=required_one_of,
mutually_exclusive=mutually_exclusive,
supports_check_mode=True)
warnings = list()
check_args(module, warnings)
result = {'changed': False}
if warnings:
result['warnings'] = warnings
want = map_params_to_obj(module)
for w in want:
name = w['name']
name = name.lower()
if is_switchport(name, module):
module.fail_json(msg='Ensure interface is configured to be a L3'
'\nport first before using this module. You can use'
'\nthe cnos_interface module for this.')
have = map_config_to_obj(module)
commands = map_obj_to_commands((want, have), module)
result['commands'] = commands
if commands:
if not module.check_mode:
load_config(module, commands)
result['changed'] = True
check_declarative_intent_params(want, module, result)
module.exit_json(**result)
if __name__ == '__main__':
main()
| gpl-3.0 |
jekkos/android_kernel_htc_msm8960 | scripts/gcc-wrapper.py | 234 | 4095 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2011-2012, The Linux Foundation. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of The Linux Foundation 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, FITNESS FOR A PARTICULAR PURPOSE AND
# NON-INFRINGEMENT 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.
# Invoke gcc, looking for warnings, and causing a failure if there are
# non-whitelisted warnings.
import errno
import re
import os
import sys
import subprocess
# Note that gcc uses unicode, which may depend on the locale. TODO:
# force LANG to be set to en_US.UTF-8 to get consistent warnings.
allowed_warnings = set([
"alignment.c:327",
"mmu.c:602",
"return_address.c:62",
"swab.h:49",
"SemaLambda.cpp:946",
"CGObjCGNU.cpp:1414",
"BugReporter.h:146",
"RegionStore.cpp:1904",
"SymbolManager.cpp:484",
"RewriteObjCFoundationAPI.cpp:737",
"RewriteObjCFoundationAPI.cpp:696",
"CommentParser.cpp:394",
"CommentParser.cpp:391",
"CommentParser.cpp:356",
"LegalizeDAG.cpp:3646",
"IRBuilder.h:844",
"DataLayout.cpp:193",
"transport.c:653",
"xt_socket.c:307",
"xt_socket.c:161",
"inet_hashtables.h:356",
"xc4000.c:1049",
"xc4000.c:1063",
"f_qdss.c:586",
"mipi_tc358764_dsi2lvds.c:746",
"dynamic_debug.h:75",
"hci_conn.c:407",
"f_qdss.c:740",
"mipi_novatek.c:569",
"swab.h:34",
])
# Capture the name of the object file, can find it.
ofile = None
warning_re = re.compile(r'''(.*/|)([^/]+\.[a-z]+:\d+):(\d+:)? warning:''')
def interpret_warning(line):
"""Decode the message from gcc. The messages we care about have a filename, and a warning"""
line = line.rstrip('\n')
m = warning_re.match(line)
if m and m.group(2) not in allowed_warnings:
print "error, forbidden warning:", m.group(2)
# If there is a warning, remove any object if it exists.
if ofile:
try:
os.remove(ofile)
except OSError:
pass
sys.exit(1)
def run_gcc():
args = sys.argv[1:]
# Look for -o
try:
i = args.index('-o')
global ofile
ofile = args[i+1]
except (ValueError, IndexError):
pass
compiler = sys.argv[0]
try:
proc = subprocess.Popen(args, stderr=subprocess.PIPE)
for line in proc.stderr:
print line,
interpret_warning(line)
result = proc.wait()
except OSError as e:
result = e.errno
if result == errno.ENOENT:
print args[0] + ':',e.strerror
print 'Is your PATH set correctly?'
else:
print ' '.join(args), str(e)
return result
if __name__ == '__main__':
status = run_gcc()
sys.exit(status)
| gpl-2.0 |
dosiecki/NewsBlur | vendor/opml/__init__.py | 20 | 1701 | import lxml.etree
class OutlineElement(object):
"""A single outline object."""
def __init__(self, root):
"""Initialize from the root <outline> node."""
self._root = root
def __getattr__(self, attr):
if attr in self._root.attrib:
return self._root.attrib[attr]
raise AttributeError()
@property
def _outlines(self):
"""Return the available sub-outline objects as a seqeunce."""
return [OutlineElement(n) for n in self._root.xpath('./outline')]
def __len__(self):
return len(self._outlines)
def __getitem__(self, index):
return self._outlines[index]
class Opml(object):
"""Python representation of an OPML file."""
def __init__(self, xml_tree):
"""Initialize the object using the parsed XML tree."""
self._tree = xml_tree
def __getattr__(self, attr):
"""Fall back attribute handler -- attempt to find the attribute in
the OPML <head>."""
result = self._tree.xpath('/opml/head/%s/text()' % attr)
if len(result) == 1:
return result[0]
raise AttributeError()
@property
def _outlines(self):
"""Return the available sub-outline objects as a seqeunce."""
return [OutlineElement(n) for n in self._tree.xpath(
'/opml/body/outline')]
def __len__(self):
return len(self._outlines)
def __getitem__(self, index):
return self._outlines[index]
def from_string(opml_text):
parser = lxml.etree.XMLParser(recover=True)
return Opml(lxml.etree.fromstring(opml_text, parser))
def parse(opml_url):
return Opml(lxml.etree.parse(opml_url))
| mit |
joram/sickbeard-orange | lib/unidecode/x0c6.py | 253 | 4490 | data = (
'yeoss', # 0x00
'yeong', # 0x01
'yeoj', # 0x02
'yeoc', # 0x03
'yeok', # 0x04
'yeot', # 0x05
'yeop', # 0x06
'yeoh', # 0x07
'ye', # 0x08
'yeg', # 0x09
'yegg', # 0x0a
'yegs', # 0x0b
'yen', # 0x0c
'yenj', # 0x0d
'yenh', # 0x0e
'yed', # 0x0f
'yel', # 0x10
'yelg', # 0x11
'yelm', # 0x12
'yelb', # 0x13
'yels', # 0x14
'yelt', # 0x15
'yelp', # 0x16
'yelh', # 0x17
'yem', # 0x18
'yeb', # 0x19
'yebs', # 0x1a
'yes', # 0x1b
'yess', # 0x1c
'yeng', # 0x1d
'yej', # 0x1e
'yec', # 0x1f
'yek', # 0x20
'yet', # 0x21
'yep', # 0x22
'yeh', # 0x23
'o', # 0x24
'og', # 0x25
'ogg', # 0x26
'ogs', # 0x27
'on', # 0x28
'onj', # 0x29
'onh', # 0x2a
'od', # 0x2b
'ol', # 0x2c
'olg', # 0x2d
'olm', # 0x2e
'olb', # 0x2f
'ols', # 0x30
'olt', # 0x31
'olp', # 0x32
'olh', # 0x33
'om', # 0x34
'ob', # 0x35
'obs', # 0x36
'os', # 0x37
'oss', # 0x38
'ong', # 0x39
'oj', # 0x3a
'oc', # 0x3b
'ok', # 0x3c
'ot', # 0x3d
'op', # 0x3e
'oh', # 0x3f
'wa', # 0x40
'wag', # 0x41
'wagg', # 0x42
'wags', # 0x43
'wan', # 0x44
'wanj', # 0x45
'wanh', # 0x46
'wad', # 0x47
'wal', # 0x48
'walg', # 0x49
'walm', # 0x4a
'walb', # 0x4b
'wals', # 0x4c
'walt', # 0x4d
'walp', # 0x4e
'walh', # 0x4f
'wam', # 0x50
'wab', # 0x51
'wabs', # 0x52
'was', # 0x53
'wass', # 0x54
'wang', # 0x55
'waj', # 0x56
'wac', # 0x57
'wak', # 0x58
'wat', # 0x59
'wap', # 0x5a
'wah', # 0x5b
'wae', # 0x5c
'waeg', # 0x5d
'waegg', # 0x5e
'waegs', # 0x5f
'waen', # 0x60
'waenj', # 0x61
'waenh', # 0x62
'waed', # 0x63
'wael', # 0x64
'waelg', # 0x65
'waelm', # 0x66
'waelb', # 0x67
'waels', # 0x68
'waelt', # 0x69
'waelp', # 0x6a
'waelh', # 0x6b
'waem', # 0x6c
'waeb', # 0x6d
'waebs', # 0x6e
'waes', # 0x6f
'waess', # 0x70
'waeng', # 0x71
'waej', # 0x72
'waec', # 0x73
'waek', # 0x74
'waet', # 0x75
'waep', # 0x76
'waeh', # 0x77
'oe', # 0x78
'oeg', # 0x79
'oegg', # 0x7a
'oegs', # 0x7b
'oen', # 0x7c
'oenj', # 0x7d
'oenh', # 0x7e
'oed', # 0x7f
'oel', # 0x80
'oelg', # 0x81
'oelm', # 0x82
'oelb', # 0x83
'oels', # 0x84
'oelt', # 0x85
'oelp', # 0x86
'oelh', # 0x87
'oem', # 0x88
'oeb', # 0x89
'oebs', # 0x8a
'oes', # 0x8b
'oess', # 0x8c
'oeng', # 0x8d
'oej', # 0x8e
'oec', # 0x8f
'oek', # 0x90
'oet', # 0x91
'oep', # 0x92
'oeh', # 0x93
'yo', # 0x94
'yog', # 0x95
'yogg', # 0x96
'yogs', # 0x97
'yon', # 0x98
'yonj', # 0x99
'yonh', # 0x9a
'yod', # 0x9b
'yol', # 0x9c
'yolg', # 0x9d
'yolm', # 0x9e
'yolb', # 0x9f
'yols', # 0xa0
'yolt', # 0xa1
'yolp', # 0xa2
'yolh', # 0xa3
'yom', # 0xa4
'yob', # 0xa5
'yobs', # 0xa6
'yos', # 0xa7
'yoss', # 0xa8
'yong', # 0xa9
'yoj', # 0xaa
'yoc', # 0xab
'yok', # 0xac
'yot', # 0xad
'yop', # 0xae
'yoh', # 0xaf
'u', # 0xb0
'ug', # 0xb1
'ugg', # 0xb2
'ugs', # 0xb3
'un', # 0xb4
'unj', # 0xb5
'unh', # 0xb6
'ud', # 0xb7
'ul', # 0xb8
'ulg', # 0xb9
'ulm', # 0xba
'ulb', # 0xbb
'uls', # 0xbc
'ult', # 0xbd
'ulp', # 0xbe
'ulh', # 0xbf
'um', # 0xc0
'ub', # 0xc1
'ubs', # 0xc2
'us', # 0xc3
'uss', # 0xc4
'ung', # 0xc5
'uj', # 0xc6
'uc', # 0xc7
'uk', # 0xc8
'ut', # 0xc9
'up', # 0xca
'uh', # 0xcb
'weo', # 0xcc
'weog', # 0xcd
'weogg', # 0xce
'weogs', # 0xcf
'weon', # 0xd0
'weonj', # 0xd1
'weonh', # 0xd2
'weod', # 0xd3
'weol', # 0xd4
'weolg', # 0xd5
'weolm', # 0xd6
'weolb', # 0xd7
'weols', # 0xd8
'weolt', # 0xd9
'weolp', # 0xda
'weolh', # 0xdb
'weom', # 0xdc
'weob', # 0xdd
'weobs', # 0xde
'weos', # 0xdf
'weoss', # 0xe0
'weong', # 0xe1
'weoj', # 0xe2
'weoc', # 0xe3
'weok', # 0xe4
'weot', # 0xe5
'weop', # 0xe6
'weoh', # 0xe7
'we', # 0xe8
'weg', # 0xe9
'wegg', # 0xea
'wegs', # 0xeb
'wen', # 0xec
'wenj', # 0xed
'wenh', # 0xee
'wed', # 0xef
'wel', # 0xf0
'welg', # 0xf1
'welm', # 0xf2
'welb', # 0xf3
'wels', # 0xf4
'welt', # 0xf5
'welp', # 0xf6
'welh', # 0xf7
'wem', # 0xf8
'web', # 0xf9
'webs', # 0xfa
'wes', # 0xfb
'wess', # 0xfc
'weng', # 0xfd
'wej', # 0xfe
'wec', # 0xff
)
| gpl-3.0 |
MaxHalford/Prince | setup.py | 1 | 3727 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Note: To use the 'upload' functionality of this file, you must:
# $ pip install twine
import io
import os
import sys
from shutil import rmtree
from setuptools import find_packages, setup, Command
# Package meta-data.
NAME = 'prince'
DESCRIPTION = 'Statistical factor analysis in Python'
LONG_DESCRIPTION_CONTENT_TYPE = 'text/markdown'
URL = 'https://github.com/MaxHalford/prince'
EMAIL = 'maxhalford25@gmail.com'
AUTHOR = 'Max Halford'
REQUIRES_PYTHON = '>=3.4.0'
VERSION = None
# What packages are required for this module to be executed?
REQUIRED = [
'matplotlib>=3.0.2',
'numpy>=1.16.1',
'pandas>=0.24.0',
'scipy>=1.1.0',
'scikit-learn>=0.20.1'
]
# The rest you shouldn't have to touch too much :)
# ------------------------------------------------
# Except, perhaps the License and Trove Classifiers!
# If you do change the License, remember to change the Trove Classifier for that!
here = os.path.abspath(os.path.dirname(__file__))
# Import the README and use it as the long-description.
# Note: this will only work if 'README.rst' is present in your MANIFEST.in file!
with io.open(os.path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = '\n' + f.read()
# Load the package's __version__.py module as a dictionary.
about = {}
if not VERSION:
with open(os.path.join(here, NAME, '__version__.py')) as f:
exec(f.read(), about)
else:
about['__version__'] = VERSION
class UploadCommand(Command):
"""Support setup.py upload."""
description = 'Build and publish the package.'
user_options = []
@staticmethod
def status(s):
"""Prints things in bold."""
print('\033[1m{0}\033[0m'.format(s))
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
try:
self.status('Removing previous builds…')
rmtree(os.path.join(here, 'dist'))
except OSError:
pass
self.status('Building Source and Wheel (universal) distribution…')
os.system('{0} setup.py sdist bdist_wheel --universal'.format(sys.executable))
self.status('Uploading the package to PyPi via Twine…')
os.system('twine upload dist/*')
self.status('Pushing git tags…')
os.system('git tag v{0}'.format(about['__version__']))
os.system('git push --tags')
sys.exit()
# Where the magic happens:
setup(
name=NAME,
version=about['__version__'],
description=DESCRIPTION,
long_description=long_description,
long_description_content_type=LONG_DESCRIPTION_CONTENT_TYPE,
author=AUTHOR,
author_email=EMAIL,
python_requires=REQUIRES_PYTHON,
url=URL,
packages=find_packages(exclude=('tests',)),
# If your package is a single module, use this instead of 'packages':
# py_modules=['mypackage'],
# entry_points={
# 'console_scripts': ['mycli=mymodule:cli'],
# },
install_requires=REQUIRED,
include_package_data=True,
license='MIT',
classifiers=[
# Trove classifiers
# Full list: https://pypi.python.org/pypi?%3Aaction=list_classifiers
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy'
],
# $ setup.py publish support.
cmdclass={
'upload': UploadCommand,
},
)
| mit |
jeffery9/mixprint_addons | account/report/account_entries_report.py | 5 | 8268 | # -*- 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/>.
#
##############################################################################
from openerp import tools
from openerp.osv import fields,osv
import openerp.addons.decimal_precision as dp
class account_entries_report(osv.osv):
_name = "account.entries.report"
_description = "Journal Items Analysis"
_auto = False
_rec_name = 'date'
_columns = {
'date': fields.date('Effective Date', readonly=True),
'date_created': fields.date('Date Created', readonly=True),
'date_maturity': fields.date('Date Maturity', readonly=True),
'ref': fields.char('Reference', size=64, readonly=True),
'nbr': fields.integer('# of Items', readonly=True),
'debit': fields.float('Debit', readonly=True),
'credit': fields.float('Credit', readonly=True),
'balance': fields.float('Balance', readonly=True),
'day': fields.char('Day', size=128, readonly=True),
'year': fields.char('Year', size=4, readonly=True),
'date': fields.date('Date', size=128, readonly=True),
'currency_id': fields.many2one('res.currency', 'Currency', readonly=True),
'amount_currency': fields.float('Amount Currency', digits_compute=dp.get_precision('Account'), readonly=True),
'month':fields.selection([('01','January'), ('02','February'), ('03','March'), ('04','April'),
('05','May'), ('06','June'), ('07','July'), ('08','August'), ('09','September'),
('10','October'), ('11','November'), ('12','December')], 'Month', readonly=True),
'period_id': fields.many2one('account.period', 'Period', readonly=True),
'account_id': fields.many2one('account.account', 'Account', readonly=True),
'journal_id': fields.many2one('account.journal', 'Journal', readonly=True),
'fiscalyear_id': fields.many2one('account.fiscalyear', 'Fiscal Year', readonly=True),
'product_id': fields.many2one('product.product', 'Product', readonly=True),
'product_uom_id': fields.many2one('product.uom', 'Product Unit of Measure', readonly=True),
'move_state': fields.selection([('draft','Unposted'), ('posted','Posted')], 'Status', readonly=True),
'move_line_state': fields.selection([('draft','Unbalanced'), ('valid','Valid')], 'State of Move Line', readonly=True),
'reconcile_id': fields.many2one('account.move.reconcile', readonly=True),
'partner_id': fields.many2one('res.partner','Partner', readonly=True),
'analytic_account_id': fields.many2one('account.analytic.account', 'Analytic Account', readonly=True),
'quantity': fields.float('Products Quantity', digits=(16,2), readonly=True),
'user_type': fields.many2one('account.account.type', 'Account Type', readonly=True),
'type': fields.selection([
('receivable', 'Receivable'),
('payable', 'Payable'),
('cash', 'Cash'),
('view', 'View'),
('consolidation', 'Consolidation'),
('other', 'Regular'),
('closed', 'Closed'),
], 'Internal Type', readonly=True, help="This type is used to differentiate types with "\
"special effects in OpenERP: view can not have entries, consolidation are accounts that "\
"can have children accounts for multi-company consolidations, payable/receivable are for "\
"partners accounts (for debit/credit computations), closed for depreciated accounts."),
'company_id': fields.many2one('res.company', 'Company', readonly=True),
}
_order = 'date desc'
def search(self, cr, uid, args, offset=0, limit=None, order=None,
context=None, count=False):
fiscalyear_obj = self.pool.get('account.fiscalyear')
period_obj = self.pool.get('account.period')
for arg in args:
if arg[0] == 'period_id' and arg[2] == 'current_period':
current_period = period_obj.find(cr, uid)[0]
args.append(['period_id','in',[current_period]])
break
elif arg[0] == 'period_id' and arg[2] == 'current_year':
current_year = fiscalyear_obj.find(cr, uid)
ids = fiscalyear_obj.read(cr, uid, [current_year], ['period_ids'])[0]['period_ids']
args.append(['period_id','in',ids])
for a in [['period_id','in','current_year'], ['period_id','in','current_period']]:
if a in args:
args.remove(a)
return super(account_entries_report, self).search(cr, uid, args=args, offset=offset, limit=limit, order=order,
context=context, count=count)
def read_group(self, cr, uid, domain, fields, groupby, offset=0, limit=None, context=None, orderby=False):
if context is None:
context = {}
fiscalyear_obj = self.pool.get('account.fiscalyear')
period_obj = self.pool.get('account.period')
if context.get('period', False) == 'current_period':
current_period = period_obj.find(cr, uid)[0]
domain.append(['period_id','in',[current_period]])
elif context.get('year', False) == 'current_year':
current_year = fiscalyear_obj.find(cr, uid)
ids = fiscalyear_obj.read(cr, uid, [current_year], ['period_ids'])[0]['period_ids']
domain.append(['period_id','in',ids])
else:
domain = domain
return super(account_entries_report, self).read_group(cr, uid, domain, fields, groupby, offset, limit, context, orderby)
def init(self, cr):
tools.drop_view_if_exists(cr, 'account_entries_report')
cr.execute("""
create or replace view account_entries_report as (
select
l.id as id,
am.date as date,
l.date_maturity as date_maturity,
l.date_created as date_created,
am.ref as ref,
am.state as move_state,
l.state as move_line_state,
l.reconcile_id as reconcile_id,
to_char(am.date, 'YYYY') as year,
to_char(am.date, 'MM') as month,
to_char(am.date, 'YYYY-MM-DD') as day,
l.partner_id as partner_id,
l.product_id as product_id,
l.product_uom_id as product_uom_id,
am.company_id as company_id,
am.journal_id as journal_id,
p.fiscalyear_id as fiscalyear_id,
am.period_id as period_id,
l.account_id as account_id,
l.analytic_account_id as analytic_account_id,
a.type as type,
a.user_type as user_type,
1 as nbr,
l.quantity as quantity,
l.currency_id as currency_id,
l.amount_currency as amount_currency,
l.debit as debit,
l.credit as credit,
l.debit-l.credit as balance
from
account_move_line l
left join account_account a on (l.account_id = a.id)
left join account_move am on (am.id=l.move_id)
left join account_period p on (am.period_id=p.id)
where l.state != 'draft'
)
""")
account_entries_report()
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
Nikoli/youtube-dl | youtube_dl/extractor/nationalgeographic.py | 18 | 1419 | from __future__ import unicode_literals
from .common import InfoExtractor
from ..utils import (
smuggle_url,
url_basename,
)
class NationalGeographicIE(InfoExtractor):
_VALID_URL = r'http://video\.nationalgeographic\.com/video/.*?'
_TEST = {
'url': 'http://video.nationalgeographic.com/video/news/150210-news-crab-mating-vin?source=featuredvideo',
'info_dict': {
'id': '4DmDACA6Qtk_',
'ext': 'flv',
'title': 'Mating Crabs Busted by Sharks',
'description': 'md5:16f25aeffdeba55aaa8ec37e093ad8b3',
},
'add_ie': ['ThePlatform'],
}
def _real_extract(self, url):
name = url_basename(url)
webpage = self._download_webpage(url, name)
feed_url = self._search_regex(r'data-feed-url="([^"]+)"', webpage, 'feed url')
guid = self._search_regex(r'data-video-guid="([^"]+)"', webpage, 'guid')
feed = self._download_xml('%s?byGuid=%s' % (feed_url, guid), name)
content = feed.find('.//{http://search.yahoo.com/mrss/}content')
theplatform_id = url_basename(content.attrib.get('url'))
return self.url_result(smuggle_url(
'http://link.theplatform.com/s/ngs/%s?format=SMIL&formats=MPEG4&manifest=f4m' % theplatform_id,
# For some reason, the normal links don't work and we must force the use of f4m
{'force_smil_url': True}))
| unlicense |
DirtyUnicorns/android_external_chromium-org | chrome/common/extensions/docs/server2/intro_data_source.py | 23 | 2178 | # Copyright (c) 2012 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.
import os
from compiled_file_system import Unicode
from data_source import DataSource
from docs_server_utils import FormatKey
from extensions_paths import INTROS_TEMPLATES, ARTICLES_TEMPLATES
from file_system import FileNotFoundError
from future import Future
from third_party.handlebar import Handlebar
# TODO(kalman): rename this HTMLDataSource or other, then have separate intro
# article data sources created as instances of it.
class IntroDataSource(DataSource):
'''This class fetches the intros for a given API. From this intro, a table
of contents dictionary is created, which contains the headings in the intro.
'''
def __init__(self, server_instance, request):
self._request = request
self._cache = server_instance.compiled_fs_factory.Create(
server_instance.host_file_system_provider.GetTrunk(),
self._MakeIntro,
IntroDataSource)
self._ref_resolver = server_instance.ref_resolver_factory.Create()
@Unicode
def _MakeIntro(self, intro_path, intro):
# Guess the name of the API from the path to the intro.
api_name = os.path.splitext(intro_path.split('/')[-1])[0]
return Handlebar(
self._ref_resolver.ResolveAllLinks(intro,
relative_to=self._request.path,
namespace=api_name),
name=intro_path)
def get(self, key):
path = FormatKey(key)
def get_from_base_path(base_path):
return self._cache.GetFromFile('%s/%s' % (base_path, path)).Get()
base_paths = (INTROS_TEMPLATES, ARTICLES_TEMPLATES)
for base_path in base_paths:
try:
return get_from_base_path(base_path)
except FileNotFoundError:
continue
# Not found. Do the first operation again so that we get a stack trace - we
# know that it'll fail.
get_from_base_path(base_paths[0])
raise AssertionError()
def Cron(self):
# TODO(kalman): Walk through the intros and articles directory.
return Future(value=())
| bsd-3-clause |
ujenmr/ansible | lib/ansible/modules/windows/win_defrag.py | 52 | 2718 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: 2017, Dag Wieers (@dagwieers) <dag@wieers.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: win_defrag
version_added: '2.4'
short_description: Consolidate fragmented files on local volumes
description:
- Locates and consolidates fragmented files on local volumes to improve system performance.
- 'More information regarding C(win_defrag) is available from: U(https://technet.microsoft.com/en-us/library/cc731650(v=ws.11).aspx)'
requirements:
- defrag.exe
options:
include_volumes:
description:
- A list of drive letters or mount point paths of the volumes to be defragmented.
- If this parameter is omitted, all volumes (not excluded) will be fragmented.
type: list
exclude_volumes:
description:
- A list of drive letters or mount point paths to exclude from defragmentation.
type: list
freespace_consolidation:
description:
- Perform free space consolidation on the specified volumes.
type: bool
default: no
priority:
description:
- Run the operation at low or normal priority.
type: str
choices: [ low, normal ]
default: low
parallel:
description:
- Run the operation on each volume in parallel in the background.
type: bool
default: no
author:
- Dag Wieers (@dagwieers)
'''
EXAMPLES = r'''
- name: Defragment all local volumes (in parallel)
win_defrag:
parallel: yes
- name: 'Defragment all local volumes, except C: and D:'
win_defrag:
exclude_volumes: [ C, D ]
- name: 'Defragment volume D: with normal priority'
win_defrag:
include_volumes: D
priority: normal
- name: Consolidate free space (useful when reducing volumes)
win_defrag:
freespace_consolidation: yes
'''
RETURN = r'''
cmd:
description: The complete command line used by the module.
returned: always
type: str
sample: defrag.exe /C /V
rc:
description: The return code for the command.
returned: always
type: int
sample: 0
stdout:
description: The standard output from the command.
returned: always
type: str
sample: Success.
stderr:
description: The error output from the command.
returned: always
type: str
sample:
msg:
description: Possible error message on failure.
returned: failed
type: str
sample: Command 'defrag.exe' not found in $env:PATH.
changed:
description: Whether or not any changes were made.
returned: always
type: bool
sample: true
'''
| gpl-3.0 |
tafaRU/odoo | addons/marketing_campaign/__openerp__.py | 45 | 3271 | # -*- 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': 'Marketing Campaigns',
'version': '1.1',
'depends': ['marketing',
'document',
'email_template',
'decimal_precision'
],
'author': 'OpenERP SA',
'category': 'Marketing',
'description': """
This module provides leads automation through marketing campaigns (campaigns can in fact be defined on any resource, not just CRM Leads).
=========================================================================================================================================
The campaigns are dynamic and multi-channels. The process is as follows:
------------------------------------------------------------------------
* Design marketing campaigns like workflows, including email templates to
send, reports to print and send by email, custom actions
* Define input segments that will select the items that should enter the
campaign (e.g leads from certain countries.)
* Run you campaign in simulation mode to test it real-time or accelerated,
and fine-tune it
* You may also start the real campaign in manual mode, where each action
requires manual validation
* Finally launch your campaign live, and watch the statistics as the
campaign does everything fully automatically.
While the campaign runs you can of course continue to fine-tune the parameters,
input segments, workflow.
**Note:** If you need demo data, you can install the marketing_campaign_crm_demo
module, but this will also install the CRM application as it depends on
CRM Leads.
""",
'website': 'https://www.odoo.com/page/lead-automation',
'data': [
'marketing_campaign_view.xml',
'marketing_campaign_data.xml',
'marketing_campaign_workflow.xml',
'report/campaign_analysis_view.xml',
'security/marketing_campaign_security.xml',
'security/ir.model.access.csv'
],
'demo': ['marketing_campaign_demo.xml'],
'test': ['test/marketing_campaign.yml'],
'installable': True,
'auto_install': False,
'images': ['images/campaign.png', 'images/campaigns.jpeg','images/email_account.jpeg','images/email_templates.jpeg','images/segments.jpeg'],
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
seankelly/buildbot | master/buildbot/process/debug.py | 11 | 2024 | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
from __future__ import absolute_import
from __future__ import print_function
from twisted.internet import defer
from buildbot.util import service
class DebugServices(service.ReconfigurableServiceMixin, service.AsyncMultiService):
name = 'debug_services'
def __init__(self):
service.AsyncMultiService.__init__(self)
self.debug_port = None
self.debug_password = None
self.debug_registration = None
self.manhole = None
@defer.inlineCallbacks
def reconfigServiceWithBuildbotConfig(self, new_config):
if new_config.manhole != self.manhole:
if self.manhole:
yield self.manhole.disownServiceParent()
self.manhole = None
if new_config.manhole:
self.manhole = new_config.manhole
yield self.manhole.setServiceParent(self)
# chain up
yield service.ReconfigurableServiceMixin.reconfigServiceWithBuildbotConfig(self,
new_config)
@defer.inlineCallbacks
def stopService(self):
# manhole will get stopped as a sub-service
yield service.AsyncMultiService.stopService(self)
# clean up
if self.manhole:
self.manhole = None
| gpl-2.0 |
industrydive/mezzanine | mezzanine/core/views.py | 20 | 8655 | from __future__ import absolute_import, unicode_literals
from future.builtins import int, open, str
import os
from json import dumps
try:
from urllib.parse import urljoin, urlparse
except ImportError:
from urlparse import urljoin, urlparse
from django.apps import apps
from django.contrib import admin
from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.admin.options import ModelAdmin
from django.contrib.staticfiles import finders
from django.core.exceptions import PermissionDenied
from django.core.urlresolvers import reverse
from django.http import (HttpResponse, HttpResponseServerError,
HttpResponseNotFound)
from django.shortcuts import redirect
from django.template import RequestContext
from django.template.loader import get_template
from django.utils.translation import ugettext_lazy as _
from django.views.decorators.csrf import requires_csrf_token
from mezzanine.conf import settings
from mezzanine.core.forms import get_edit_form
from mezzanine.core.models import Displayable, SitePermission
from mezzanine.utils.cache import add_cache_bypass
from mezzanine.utils.views import is_editable, paginate, render, set_cookie
from mezzanine.utils.sites import has_site_permission
from mezzanine.utils.urls import next_url
def set_device(request, device=""):
"""
Sets a device name in a cookie when a user explicitly wants to go
to the site for a particular device (eg mobile).
"""
response = redirect(add_cache_bypass(next_url(request) or "/"))
set_cookie(response, "mezzanine-device", device, 60 * 60 * 24 * 365)
return response
@staff_member_required
def set_site(request):
"""
Put the selected site ID into the session - posted to from
the "Select site" drop-down in the header of the admin. The
site ID is then used in favour of the current request's
domain in ``mezzanine.core.managers.CurrentSiteManager``.
"""
site_id = int(request.GET["site_id"])
if not request.user.is_superuser:
try:
SitePermission.objects.get(user=request.user, sites=site_id)
except SitePermission.DoesNotExist:
raise PermissionDenied
request.session["site_id"] = site_id
admin_url = reverse("admin:index")
next = next_url(request) or admin_url
# Don't redirect to a change view for an object that won't exist
# on the selected site - go to its list view instead.
if next.startswith(admin_url):
parts = next.split("/")
if len(parts) > 4 and parts[4].isdigit():
next = "/".join(parts[:4])
return redirect(next)
def direct_to_template(request, template, extra_context=None, **kwargs):
"""
Replacement for Django's ``direct_to_template`` that uses
``TemplateResponse`` via ``mezzanine.utils.views.render``.
"""
context = extra_context or {}
context["params"] = kwargs
for (key, value) in context.items():
if callable(value):
context[key] = value()
return render(request, template, context)
@staff_member_required
def edit(request):
"""
Process the inline editing form.
"""
model = apps.get_model(request.POST["app"], request.POST["model"])
obj = model.objects.get(id=request.POST["id"])
form = get_edit_form(obj, request.POST["fields"], data=request.POST,
files=request.FILES)
if not (is_editable(obj, request) and has_site_permission(request.user)):
response = _("Permission denied")
elif form.is_valid():
form.save()
model_admin = ModelAdmin(model, admin.site)
message = model_admin.construct_change_message(request, form, None)
model_admin.log_change(request, obj, message)
response = ""
else:
response = list(form.errors.values())[0][0]
return HttpResponse(response)
def search(request, template="search_results.html", extra_context=None):
"""
Display search results. Takes an optional "contenttype" GET parameter
in the form "app-name.ModelName" to limit search results to a single model.
"""
query = request.GET.get("q", "")
page = request.GET.get("page", 1)
per_page = settings.SEARCH_PER_PAGE
max_paging_links = settings.MAX_PAGING_LINKS
try:
parts = request.GET.get("type", "").split(".", 1)
search_model = apps.get_model(*parts)
search_model.objects.search # Attribute check
except (ValueError, TypeError, LookupError, AttributeError):
search_model = Displayable
search_type = _("Everything")
else:
search_type = search_model._meta.verbose_name_plural.capitalize()
results = search_model.objects.search(query, for_user=request.user)
paginated = paginate(results, page, per_page, max_paging_links)
context = {"query": query, "results": paginated,
"search_type": search_type}
context.update(extra_context or {})
return render(request, template, context)
@staff_member_required
def static_proxy(request):
"""
Serves TinyMCE plugins inside the inline popups and the uploadify
SWF, as these are normally static files, and will break with
cross-domain JavaScript errors if ``STATIC_URL`` is an external
host. URL for the file is passed in via querystring in the inline
popup plugin template, and we then attempt to pull out the relative
path to the file, so that we can serve it locally via Django.
"""
normalize = lambda u: ("//" + u.split("://")[-1]) if "://" in u else u
url = normalize(request.GET["u"])
host = "//" + request.get_host()
static_url = normalize(settings.STATIC_URL)
for prefix in (host, static_url, "/"):
if url.startswith(prefix):
url = url.replace(prefix, "", 1)
response = ""
content_type = ""
path = finders.find(url)
if path:
if isinstance(path, (list, tuple)):
path = path[0]
if url.endswith(".htm"):
# Inject <base href="{{ STATIC_URL }}"> into TinyMCE
# plugins, since the path static files in these won't be
# on the same domain.
static_url = settings.STATIC_URL + os.path.split(url)[0] + "/"
if not urlparse(static_url).scheme:
static_url = urljoin(host, static_url)
base_tag = "<base href='%s'>" % static_url
content_type = "text/html"
with open(path, "r") as f:
response = f.read().replace("<head>", "<head>" + base_tag)
else:
content_type = "application/octet-stream"
with open(path, "rb") as f:
response = f.read()
return HttpResponse(response, content_type=content_type)
def displayable_links_js(request):
"""
Renders a list of url/title pairs for all ``Displayable`` subclass
instances into JSON that's used to populate a list of links in
TinyMCE.
"""
links = []
if "mezzanine.pages" in settings.INSTALLED_APPS:
from mezzanine.pages.models import Page
is_page = lambda obj: isinstance(obj, Page)
else:
is_page = lambda obj: False
# For each item's title, we use its model's verbose_name, but in the
# case of Page subclasses, we just use "Page", and then sort the items
# by whether they're a Page subclass or not, then by their URL.
for url, obj in Displayable.objects.url_map(for_user=request.user).items():
title = getattr(obj, "titles", obj.title)
real = hasattr(obj, "id")
page = is_page(obj)
if real:
verbose_name = _("Page") if page else obj._meta.verbose_name
title = "%s: %s" % (verbose_name, title)
links.append((not page and real, {"title": str(title), "value": url}))
sorted_links = sorted(links, key=lambda link: (link[0], link[1]['value']))
return HttpResponse(dumps([link[1] for link in sorted_links]))
@requires_csrf_token
def page_not_found(request, template_name="errors/404.html"):
"""
Mimics Django's 404 handler but with a different template path.
"""
context = RequestContext(request, {
"STATIC_URL": settings.STATIC_URL,
"request_path": request.path,
})
t = get_template(template_name)
return HttpResponseNotFound(t.render(context))
@requires_csrf_token
def server_error(request, template_name="errors/500.html"):
"""
Mimics Django's error handler but adds ``STATIC_URL`` to the
context.
"""
context = RequestContext(request, {"STATIC_URL": settings.STATIC_URL})
t = get_template(template_name)
return HttpResponseServerError(t.render(context))
| bsd-2-clause |
ekhdkv/vboxweb | lib/VirtualBox_wrappers.py | 8 | 445876 | # Copyright (C) 2008-2010 Oracle Corporation
#
# This file is part of a free software library; you can redistribute
# it and/or modify it under the terms of the GNU Lesser General
# Public License version 2.1 as published by the Free Software
# Foundation and shipped in the "COPYING.LIB" file with this library.
# The library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY of any kind.
#
# Oracle LGPL Disclaimer: For the avoidance of doubt, except that if
# any license choice other than GPL or LGPL is available it will
# apply instead, Oracle elects to use only the Lesser General Public
# License version 2.1 (LGPLv2) at this time for any software where
# a choice of LGPL license versions is made available with the
# language indicating that LGPLv2 or any later version may be used,
# or where a choice of which version of the LGPL is applied is
# otherwise unspecified.
#
# This file is autogenerated from VirtualBox.xidl, DO NOT EDIT!
#
"""
from VirtualBox_services import *
try:
from VirtualBox_client import *
except:
pass
"""
class ManagedManager:
def __init__(self):
self.map = {}
def register(self,handle):
if handle == None:
return
c = self.map.get(handle,0)
c = c + 1
self.map[handle]=c
def unregister(self,handle):
if handle == None:
return
c = self.map.get(handle,-1)
if c == -1:
raise Error, 'wrong refcount'
c = c - 1
if c == 0:
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
self.map[handle] = -1
else:
self.map[handle] = c
class String:
def __init__(self, mgr, handle, isarray = False):
self.handle = handle
self.mgr = mgr
self.isarray = isarray
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return String(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return str(self.handle)
def __eq__(self,other):
if self.isarray:
return isinstance(other,String) and self.handle == other.handle
if isinstance(other,String):
return self.handle == other.handle
if isinstance(other,basestring):
return self.handle == other
return False
def __ne__(self,other):
if self.isarray:
return not isinstance(other,String) or self.handle != other.handle
if isinstance(other,String):
return self.handle != other.handle
if isinstance(other,basestring):
return self.handle != other
return True
def __add__(self,other):
return str(self.handle)+str(other)
class Boolean:
def __init__(self, mgr, handle, isarray = False):
self.handle = handle
if self.handle == "false":
self.handle = None
self.mgr = mgr
self.isarray = isarray
def __str__(self):
if self.handle:
return "true"
else:
return "false"
def __eq__(self,other):
if isinstance(other,Bool):
return self.handle == other.value
if isinstance(other,bool):
return self.handle == other
return False
def __ne__(self,other):
if isinstance(other,Bool):
return self.handle != other.handle
if isinstance(other,bool):
return self.handle != other
return True
def __int__(self):
if self.handle:
return 1
else:
return 0
def __long__(self):
if self.handle:
return 1
else:
return 0
def __nonzero__(self):
if self.handle:
return True
else:
return False
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return Boolean(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
class Number:
def __init__(self, mgr, handle, isarray = False):
self.handle = handle
self.mgr = mgr
self.isarray = isarray
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __str__(self):
return str(self.handle)
def __int__(self):
return int(self.handle)
def __long__(self):
return long(self.handle)
def __float__(self):
return float(self.handle)
def __lt__(self, other):
if self.isarray:
return NotImplemented
else:
return self.handle < other
def __le__(self, other):
if self.isarray:
return NotImplemented
else:
return self.handle <= other
def __eq__(self, other):
return self.handle == other
def __ne__(self, other):
return self.handle != other
def __gt__(self, other):
if self.isarray:
return NotImplemented
else:
return self.handle > other
def __ge__(self, other):
if self.isarray:
return NotImplemented
else:
return self.handle >= other
import struct
class Octet(Number):
def __init__(self, mgr, handle, isarray = False):
self.handle = handle
self.mgr = mgr
self.isarray = isarray
def __getitem__(self, index):
if self.isarray:
return Octet(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
if self.isarray:
# array of octets is binary data
list = map (None, self.handle)
return struct.pack("%dB" % (len(list)), *list)
else:
return str(self.handle)
class UnsignedInt(Number):
def __init__(self, mgr, handle, isarray = False):
self.handle = handle
self.mgr = mgr
self.isarray = isarray
def __getitem__(self, index):
if self.isarray:
return UnsignedInt(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
class Int(Number):
def __init__(self, mgr, handle, isarray = False):
self.handle = handle
self.mgr = mgr
self.isarray = isarray
def __getitem__(self, index):
if self.isarray:
return Int(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
class UnsignedShort(Number):
def __init__(self, mgr, handle, isarray = False):
self.handle = handle
self.mgr = mgr
self.isarray = isarray
def __getitem__(self, index):
if self.isarray:
return UnsignedShort(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
class Short(Number):
def __init__(self, mgr, handle, isarray = False):
self.handle = handle
self.mgr = mgr
self.isarray = isarray
def __getitem__(self, index):
if self.isarray:
return Short(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
class UnsignedLong(Number):
def __init__(self, mgr, handle, isarray = False):
self.handle = handle
self.mgr = mgr
self.isarray = isarray
def __getitem__(self, index):
if self.isarray:
return UnsignedLong(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
class Long(Number):
def __init__(self, mgr, handle, isarray = False):
self.handle = handle
self.mgr = mgr
self.isarray = isarray
def __getitem__(self, index):
if self.isarray:
return Long(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
class Double(Number):
def __init__(self, mgr, handle, isarray = False):
self.handle = handle
self.mgr = mgr
self.isarray = isarray
def __getitem__(self, index):
if self.isarray:
return Double(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
class Float(Number):
def __init__(self, mgr, handle, isarray = False):
self.handle = handle
self.mgr = mgr
self.isarray = isarray
def __getitem__(self, index):
if self.isarray:
return Float(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
class IUnknown:
def __init__(self, mgr, handle, isarray = False):
self.handle = handle
self.mgr = mgr
self.isarray = isarray
def __nonzero__(self):
if self.handle != "":
return True
else:
return False
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IUnknown(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return str(self.handle)
def __eq__(self, other):
return self.handle == other
def __ne__(self, other):
return self.handle != other
def __getattr__(self,attr):
if self.__class__.__dict__.get(attr) != None:
return self.__class__.__dict__.get(attr)
if self.__dict__.get(attr) != None:
return self.__dict__.get(attr)
raise AttributeError
class IVirtualBoxErrorInfo(IUnknown):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IVirtualBoxErrorInfo(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IVirtualBoxErrorInfo._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IUnknown.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IVirtualBoxErrorInfo._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def getResultCode(self):
req=IVirtualBoxErrorInfo_getResultCodeRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IVirtualBoxErrorInfo_getResultCode(req)
return Int(self.mgr,val._returnval)
def getInterfaceID(self):
req=IVirtualBoxErrorInfo_getInterfaceIDRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IVirtualBoxErrorInfo_getInterfaceID(req)
return String(self.mgr,val._returnval)
def getComponent(self):
req=IVirtualBoxErrorInfo_getComponentRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IVirtualBoxErrorInfo_getComponent(req)
return String(self.mgr,val._returnval)
def getText(self):
req=IVirtualBoxErrorInfo_getTextRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IVirtualBoxErrorInfo_getText(req)
return String(self.mgr,val._returnval)
def getNext(self):
req=IVirtualBoxErrorInfo_getNextRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IVirtualBoxErrorInfo_getNext(req)
return IVirtualBoxErrorInfo(self.mgr,val._returnval)
_Attrs_={ 'resultCode':[getResultCode,None],
'interfaceID':[getInterfaceID,None],
'component':[getComponent,None],
'text':[getText,None],
'next':[getNext,None]}
class IDHCPServer(IUnknown):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IDHCPServer(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IDHCPServer._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IUnknown.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IDHCPServer._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def setConfiguration(self, _arg_IPAddress, _arg_networkMask, _arg_FromIPAddress, _arg_ToIPAddress):
req=IDHCPServer_setConfigurationRequestMsg()
req._this=self.handle
req._IPAddress=_arg_IPAddress
req._networkMask=_arg_networkMask
req._FromIPAddress=_arg_FromIPAddress
req._ToIPAddress=_arg_ToIPAddress
val=self.mgr.getPort().IDHCPServer_setConfiguration(req)
return
def start(self, _arg_networkName, _arg_trunkName, _arg_trunkType):
req=IDHCPServer_startRequestMsg()
req._this=self.handle
req._networkName=_arg_networkName
req._trunkName=_arg_trunkName
req._trunkType=_arg_trunkType
val=self.mgr.getPort().IDHCPServer_start(req)
return
def stop(self):
req=IDHCPServer_stopRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IDHCPServer_stop(req)
return
def getEnabled(self):
req=IDHCPServer_getEnabledRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IDHCPServer_getEnabled(req)
return Boolean(self.mgr,val._returnval)
def setEnabled(self, value):
req=IDHCPServer_setEnabledRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._enabled = value
else:
req._enabled = value.handle
self.mgr.getPort().IDHCPServer_setEnabled(req)
def getIPAddress(self):
req=IDHCPServer_getIPAddressRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IDHCPServer_getIPAddress(req)
return String(self.mgr,val._returnval)
def getNetworkMask(self):
req=IDHCPServer_getNetworkMaskRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IDHCPServer_getNetworkMask(req)
return String(self.mgr,val._returnval)
def getNetworkName(self):
req=IDHCPServer_getNetworkNameRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IDHCPServer_getNetworkName(req)
return String(self.mgr,val._returnval)
def getLowerIP(self):
req=IDHCPServer_getLowerIPRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IDHCPServer_getLowerIP(req)
return String(self.mgr,val._returnval)
def getUpperIP(self):
req=IDHCPServer_getUpperIPRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IDHCPServer_getUpperIP(req)
return String(self.mgr,val._returnval)
_Attrs_={ 'enabled':[getEnabled,setEnabled,
],
'IPAddress':[getIPAddress,None],
'networkMask':[getNetworkMask,None],
'networkName':[getNetworkName,None],
'lowerIP':[getLowerIP,None],
'upperIP':[getUpperIP,None]}
class IVirtualBox(IUnknown):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IVirtualBox(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IVirtualBox._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IUnknown.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IVirtualBox._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def composeMachineFilename(self, _arg_name, _arg_baseFolder):
req=IVirtualBox_composeMachineFilenameRequestMsg()
req._this=self.handle
req._name=_arg_name
req._baseFolder=_arg_baseFolder
val=self.mgr.getPort().IVirtualBox_composeMachineFilename(req)
return String(self.mgr,val._returnval)
def createMachine(self, _arg_settingsFile, _arg_name, _arg_osTypeId, _arg_id, _arg_forceOverwrite):
req=IVirtualBox_createMachineRequestMsg()
req._this=self.handle
req._settingsFile=_arg_settingsFile
req._name=_arg_name
req._osTypeId=_arg_osTypeId
req._id=_arg_id
req._forceOverwrite=_arg_forceOverwrite
val=self.mgr.getPort().IVirtualBox_createMachine(req)
return IMachine(self.mgr,val._returnval)
def openMachine(self, _arg_settingsFile):
req=IVirtualBox_openMachineRequestMsg()
req._this=self.handle
req._settingsFile=_arg_settingsFile
val=self.mgr.getPort().IVirtualBox_openMachine(req)
return IMachine(self.mgr,val._returnval)
def registerMachine(self, _arg_machine):
req=IVirtualBox_registerMachineRequestMsg()
req._this=self.handle
req._machine=_arg_machine
val=self.mgr.getPort().IVirtualBox_registerMachine(req)
return
def findMachine(self, _arg_nameOrId):
req=IVirtualBox_findMachineRequestMsg()
req._this=self.handle
req._nameOrId=_arg_nameOrId
val=self.mgr.getPort().IVirtualBox_findMachine(req)
return IMachine(self.mgr,val._returnval)
def createAppliance(self):
req=IVirtualBox_createApplianceRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IVirtualBox_createAppliance(req)
return IAppliance(self.mgr,val._returnval)
def createHardDisk(self, _arg_format, _arg_location):
req=IVirtualBox_createHardDiskRequestMsg()
req._this=self.handle
req._format=_arg_format
req._location=_arg_location
val=self.mgr.getPort().IVirtualBox_createHardDisk(req)
return IMedium(self.mgr,val._returnval)
def openMedium(self, _arg_location, _arg_deviceType, _arg_accessMode):
req=IVirtualBox_openMediumRequestMsg()
req._this=self.handle
req._location=_arg_location
req._deviceType=_arg_deviceType
req._accessMode=_arg_accessMode
val=self.mgr.getPort().IVirtualBox_openMedium(req)
return IMedium(self.mgr,val._returnval)
def findMedium(self, _arg_location, _arg_type):
req=IVirtualBox_findMediumRequestMsg()
req._this=self.handle
req._location=_arg_location
req._type=_arg_type
val=self.mgr.getPort().IVirtualBox_findMedium(req)
return IMedium(self.mgr,val._returnval)
def getGuestOSType(self, _arg_id):
req=IVirtualBox_getGuestOSTypeRequestMsg()
req._this=self.handle
req._id=_arg_id
val=self.mgr.getPort().IVirtualBox_getGuestOSType(req)
return IGuestOSType(self.mgr,val._returnval)
def createSharedFolder(self, _arg_name, _arg_hostPath, _arg_writable, _arg_automount):
req=IVirtualBox_createSharedFolderRequestMsg()
req._this=self.handle
req._name=_arg_name
req._hostPath=_arg_hostPath
req._writable=_arg_writable
req._automount=_arg_automount
val=self.mgr.getPort().IVirtualBox_createSharedFolder(req)
return
def removeSharedFolder(self, _arg_name):
req=IVirtualBox_removeSharedFolderRequestMsg()
req._this=self.handle
req._name=_arg_name
val=self.mgr.getPort().IVirtualBox_removeSharedFolder(req)
return
def getExtraDataKeys(self):
req=IVirtualBox_getExtraDataKeysRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IVirtualBox_getExtraDataKeys(req)
return String(self.mgr,val._returnval, True)
def getExtraData(self, _arg_key):
req=IVirtualBox_getExtraDataRequestMsg()
req._this=self.handle
req._key=_arg_key
val=self.mgr.getPort().IVirtualBox_getExtraData(req)
return String(self.mgr,val._returnval)
def setExtraData(self, _arg_key, _arg_value):
req=IVirtualBox_setExtraDataRequestMsg()
req._this=self.handle
req._key=_arg_key
req._value=_arg_value
val=self.mgr.getPort().IVirtualBox_setExtraData(req)
return
def createDHCPServer(self, _arg_name):
req=IVirtualBox_createDHCPServerRequestMsg()
req._this=self.handle
req._name=_arg_name
val=self.mgr.getPort().IVirtualBox_createDHCPServer(req)
return IDHCPServer(self.mgr,val._returnval)
def findDHCPServerByNetworkName(self, _arg_name):
req=IVirtualBox_findDHCPServerByNetworkNameRequestMsg()
req._this=self.handle
req._name=_arg_name
val=self.mgr.getPort().IVirtualBox_findDHCPServerByNetworkName(req)
return IDHCPServer(self.mgr,val._returnval)
def removeDHCPServer(self, _arg_server):
req=IVirtualBox_removeDHCPServerRequestMsg()
req._this=self.handle
req._server=_arg_server
val=self.mgr.getPort().IVirtualBox_removeDHCPServer(req)
return
def checkFirmwarePresent(self, _arg_firmwareType, _arg_version):
req=IVirtualBox_checkFirmwarePresentRequestMsg()
req._this=self.handle
req._firmwareType=_arg_firmwareType
req._version=_arg_version
val=self.mgr.getPort().IVirtualBox_checkFirmwarePresent(req)
return Boolean(self.mgr,val._returnval), String(self.mgr,val._url), String(self.mgr,val._file)
def VRDERegisterLibrary(self, _arg_name):
req=IVirtualBox_VRDERegisterLibraryRequestMsg()
req._this=self.handle
req._name=_arg_name
val=self.mgr.getPort().IVirtualBox_VRDERegisterLibrary(req)
return
def VRDEUnregisterLibrary(self, _arg_name):
req=IVirtualBox_VRDEUnregisterLibraryRequestMsg()
req._this=self.handle
req._name=_arg_name
val=self.mgr.getPort().IVirtualBox_VRDEUnregisterLibrary(req)
return
def VRDEListLibraries(self):
req=IVirtualBox_VRDEListLibrariesRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IVirtualBox_VRDEListLibraries(req)
return String(self.mgr,val._returnval, True)
def getVersion(self):
req=IVirtualBox_getVersionRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IVirtualBox_getVersion(req)
return String(self.mgr,val._returnval)
def getRevision(self):
req=IVirtualBox_getRevisionRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IVirtualBox_getRevision(req)
return UnsignedInt(self.mgr,val._returnval)
def getPackageType(self):
req=IVirtualBox_getPackageTypeRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IVirtualBox_getPackageType(req)
return String(self.mgr,val._returnval)
def getHomeFolder(self):
req=IVirtualBox_getHomeFolderRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IVirtualBox_getHomeFolder(req)
return String(self.mgr,val._returnval)
def getSettingsFilePath(self):
req=IVirtualBox_getSettingsFilePathRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IVirtualBox_getSettingsFilePath(req)
return String(self.mgr,val._returnval)
def getHost(self):
req=IVirtualBox_getHostRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IVirtualBox_getHost(req)
return IHost(self.mgr,val._returnval)
def getSystemProperties(self):
req=IVirtualBox_getSystemPropertiesRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IVirtualBox_getSystemProperties(req)
return ISystemProperties(self.mgr,val._returnval)
def getMachines(self):
req=IVirtualBox_getMachinesRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IVirtualBox_getMachines(req)
return IMachine(self.mgr,val._returnval, True)
def getHardDisks(self):
req=IVirtualBox_getHardDisksRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IVirtualBox_getHardDisks(req)
return IMedium(self.mgr,val._returnval, True)
def getDVDImages(self):
req=IVirtualBox_getDVDImagesRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IVirtualBox_getDVDImages(req)
return IMedium(self.mgr,val._returnval, True)
def getFloppyImages(self):
req=IVirtualBox_getFloppyImagesRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IVirtualBox_getFloppyImages(req)
return IMedium(self.mgr,val._returnval, True)
def getProgressOperations(self):
req=IVirtualBox_getProgressOperationsRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IVirtualBox_getProgressOperations(req)
return IProgress(self.mgr,val._returnval, True)
def getGuestOSTypes(self):
req=IVirtualBox_getGuestOSTypesRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IVirtualBox_getGuestOSTypes(req)
return IGuestOSType(self.mgr,val._returnval, True)
def getSharedFolders(self):
req=IVirtualBox_getSharedFoldersRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IVirtualBox_getSharedFolders(req)
return ISharedFolder(self.mgr,val._returnval, True)
def getPerformanceCollector(self):
req=IVirtualBox_getPerformanceCollectorRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IVirtualBox_getPerformanceCollector(req)
return IPerformanceCollector(self.mgr,val._returnval)
def getDHCPServers(self):
req=IVirtualBox_getDHCPServersRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IVirtualBox_getDHCPServers(req)
return IDHCPServer(self.mgr,val._returnval, True)
def getEventSource(self):
req=IVirtualBox_getEventSourceRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IVirtualBox_getEventSource(req)
return IEventSource(self.mgr,val._returnval)
_Attrs_={ 'version':[getVersion,None],
'revision':[getRevision,None],
'packageType':[getPackageType,None],
'homeFolder':[getHomeFolder,None],
'settingsFilePath':[getSettingsFilePath,None],
'host':[getHost,None],
'systemProperties':[getSystemProperties,None],
'machines':[getMachines,None],
'hardDisks':[getHardDisks,None],
'DVDImages':[getDVDImages,None],
'floppyImages':[getFloppyImages,None],
'progressOperations':[getProgressOperations,None],
'guestOSTypes':[getGuestOSTypes,None],
'sharedFolders':[getSharedFolders,None],
'performanceCollector':[getPerformanceCollector,None],
'DHCPServers':[getDHCPServers,None],
'eventSource':[getEventSource,None]}
class IVFSExplorer(IUnknown):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IVFSExplorer(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IVFSExplorer._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IUnknown.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IVFSExplorer._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def update(self):
req=IVFSExplorer_updateRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IVFSExplorer_update(req)
return IProgress(self.mgr,val._returnval)
def cd(self, _arg_aDir):
req=IVFSExplorer_cdRequestMsg()
req._this=self.handle
req._aDir=_arg_aDir
val=self.mgr.getPort().IVFSExplorer_cd(req)
return IProgress(self.mgr,val._returnval)
def cdUp(self):
req=IVFSExplorer_cdUpRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IVFSExplorer_cdUp(req)
return IProgress(self.mgr,val._returnval)
def entryList(self):
req=IVFSExplorer_entryListRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IVFSExplorer_entryList(req)
return String(self.mgr,val._aNames, True), UnsignedInt(self.mgr,val._aTypes, True)
def exists(self, _arg_aNames):
req=IVFSExplorer_existsRequestMsg()
req._this=self.handle
req._aNames=_arg_aNames
val=self.mgr.getPort().IVFSExplorer_exists(req)
return String(self.mgr,val._returnval, True)
def remove(self, _arg_aNames):
req=IVFSExplorer_removeRequestMsg()
req._this=self.handle
req._aNames=_arg_aNames
val=self.mgr.getPort().IVFSExplorer_remove(req)
return IProgress(self.mgr,val._returnval)
def getPath(self):
req=IVFSExplorer_getPathRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IVFSExplorer_getPath(req)
return String(self.mgr,val._returnval)
def getType(self):
req=IVFSExplorer_getTypeRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IVFSExplorer_getType(req)
return VFSType(self.mgr,val._returnval)
_Attrs_={ 'path':[getPath,None],
'type':[getType,None]}
class IAppliance(IUnknown):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IAppliance(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IAppliance._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IUnknown.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IAppliance._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def read(self, _arg_file):
req=IAppliance_readRequestMsg()
req._this=self.handle
req._file=_arg_file
val=self.mgr.getPort().IAppliance_read(req)
return IProgress(self.mgr,val._returnval)
def interpret(self):
req=IAppliance_interpretRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IAppliance_interpret(req)
return
def importMachines(self):
req=IAppliance_importMachinesRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IAppliance_importMachines(req)
return IProgress(self.mgr,val._returnval)
def createVFSExplorer(self, _arg_aUri):
req=IAppliance_createVFSExplorerRequestMsg()
req._this=self.handle
req._aUri=_arg_aUri
val=self.mgr.getPort().IAppliance_createVFSExplorer(req)
return IVFSExplorer(self.mgr,val._returnval)
def write(self, _arg_format, _arg_manifest, _arg_path):
req=IAppliance_writeRequestMsg()
req._this=self.handle
req._format=_arg_format
req._manifest=_arg_manifest
req._path=_arg_path
val=self.mgr.getPort().IAppliance_write(req)
return IProgress(self.mgr,val._returnval)
def getWarnings(self):
req=IAppliance_getWarningsRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IAppliance_getWarnings(req)
return String(self.mgr,val._returnval, True)
def getPath(self):
req=IAppliance_getPathRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IAppliance_getPath(req)
return String(self.mgr,val._returnval)
def getDisks(self):
req=IAppliance_getDisksRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IAppliance_getDisks(req)
return String(self.mgr,val._returnval, True)
def getVirtualSystemDescriptions(self):
req=IAppliance_getVirtualSystemDescriptionsRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IAppliance_getVirtualSystemDescriptions(req)
return IVirtualSystemDescription(self.mgr,val._returnval, True)
def getMachines(self):
req=IAppliance_getMachinesRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IAppliance_getMachines(req)
return String(self.mgr,val._returnval, True)
_Attrs_={ 'path':[getPath,None],
'disks':[getDisks,None],
'virtualSystemDescriptions':[getVirtualSystemDescriptions,None],
'machines':[getMachines,None]}
class IVirtualSystemDescription(IUnknown):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IVirtualSystemDescription(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IVirtualSystemDescription._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IUnknown.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IVirtualSystemDescription._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def getDescription(self):
req=IVirtualSystemDescription_getDescriptionRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IVirtualSystemDescription_getDescription(req)
return VirtualSystemDescriptionType(self.mgr,val._aTypes, True), String(self.mgr,val._aRefs, True), String(self.mgr,val._aOvfValues, True), String(self.mgr,val._aVBoxValues, True), String(self.mgr,val._aExtraConfigValues, True)
def getDescriptionByType(self, _arg_aType):
req=IVirtualSystemDescription_getDescriptionByTypeRequestMsg()
req._this=self.handle
req._aType=_arg_aType
val=self.mgr.getPort().IVirtualSystemDescription_getDescriptionByType(req)
return VirtualSystemDescriptionType(self.mgr,val._aTypes, True), String(self.mgr,val._aRefs, True), String(self.mgr,val._aOvfValues, True), String(self.mgr,val._aVBoxValues, True), String(self.mgr,val._aExtraConfigValues, True)
def getValuesByType(self, _arg_aType, _arg_aWhich):
req=IVirtualSystemDescription_getValuesByTypeRequestMsg()
req._this=self.handle
req._aType=_arg_aType
req._aWhich=_arg_aWhich
val=self.mgr.getPort().IVirtualSystemDescription_getValuesByType(req)
return String(self.mgr,val._returnval, True)
def setFinalValues(self, _arg_aEnabled, _arg_aVBoxValues, _arg_aExtraConfigValues):
req=IVirtualSystemDescription_setFinalValuesRequestMsg()
req._this=self.handle
req._aEnabled=_arg_aEnabled
req._aVBoxValues=_arg_aVBoxValues
req._aExtraConfigValues=_arg_aExtraConfigValues
val=self.mgr.getPort().IVirtualSystemDescription_setFinalValues(req)
return
def addDescription(self, _arg_aType, _arg_aVBoxValue, _arg_aExtraConfigValue):
req=IVirtualSystemDescription_addDescriptionRequestMsg()
req._this=self.handle
req._aType=_arg_aType
req._aVBoxValue=_arg_aVBoxValue
req._aExtraConfigValue=_arg_aExtraConfigValue
val=self.mgr.getPort().IVirtualSystemDescription_addDescription(req)
return
def getCount(self):
req=IVirtualSystemDescription_getCountRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IVirtualSystemDescription_getCount(req)
return UnsignedInt(self.mgr,val._returnval)
_Attrs_={ 'count':[getCount,None]}
class IBIOSSettings(IUnknown):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IBIOSSettings(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IBIOSSettings._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IUnknown.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IBIOSSettings._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def getLogoFadeIn(self):
req=IBIOSSettings_getLogoFadeInRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IBIOSSettings_getLogoFadeIn(req)
return Boolean(self.mgr,val._returnval)
def setLogoFadeIn(self, value):
req=IBIOSSettings_setLogoFadeInRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._logoFadeIn = value
else:
req._logoFadeIn = value.handle
self.mgr.getPort().IBIOSSettings_setLogoFadeIn(req)
def getLogoFadeOut(self):
req=IBIOSSettings_getLogoFadeOutRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IBIOSSettings_getLogoFadeOut(req)
return Boolean(self.mgr,val._returnval)
def setLogoFadeOut(self, value):
req=IBIOSSettings_setLogoFadeOutRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._logoFadeOut = value
else:
req._logoFadeOut = value.handle
self.mgr.getPort().IBIOSSettings_setLogoFadeOut(req)
def getLogoDisplayTime(self):
req=IBIOSSettings_getLogoDisplayTimeRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IBIOSSettings_getLogoDisplayTime(req)
return UnsignedInt(self.mgr,val._returnval)
def setLogoDisplayTime(self, value):
req=IBIOSSettings_setLogoDisplayTimeRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._logoDisplayTime = value
else:
req._logoDisplayTime = value.handle
self.mgr.getPort().IBIOSSettings_setLogoDisplayTime(req)
def getLogoImagePath(self):
req=IBIOSSettings_getLogoImagePathRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IBIOSSettings_getLogoImagePath(req)
return String(self.mgr,val._returnval)
def setLogoImagePath(self, value):
req=IBIOSSettings_setLogoImagePathRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._logoImagePath = value
else:
req._logoImagePath = value.handle
self.mgr.getPort().IBIOSSettings_setLogoImagePath(req)
def getBootMenuMode(self):
req=IBIOSSettings_getBootMenuModeRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IBIOSSettings_getBootMenuMode(req)
return BIOSBootMenuMode(self.mgr,val._returnval)
def setBootMenuMode(self, value):
req=IBIOSSettings_setBootMenuModeRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._bootMenuMode = value
else:
req._bootMenuMode = value.handle
self.mgr.getPort().IBIOSSettings_setBootMenuMode(req)
def getACPIEnabled(self):
req=IBIOSSettings_getACPIEnabledRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IBIOSSettings_getACPIEnabled(req)
return Boolean(self.mgr,val._returnval)
def setACPIEnabled(self, value):
req=IBIOSSettings_setACPIEnabledRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._ACPIEnabled = value
else:
req._ACPIEnabled = value.handle
self.mgr.getPort().IBIOSSettings_setACPIEnabled(req)
def getIOAPICEnabled(self):
req=IBIOSSettings_getIOAPICEnabledRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IBIOSSettings_getIOAPICEnabled(req)
return Boolean(self.mgr,val._returnval)
def setIOAPICEnabled(self, value):
req=IBIOSSettings_setIOAPICEnabledRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._IOAPICEnabled = value
else:
req._IOAPICEnabled = value.handle
self.mgr.getPort().IBIOSSettings_setIOAPICEnabled(req)
def getTimeOffset(self):
req=IBIOSSettings_getTimeOffsetRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IBIOSSettings_getTimeOffset(req)
return Long(self.mgr,val._returnval)
def setTimeOffset(self, value):
req=IBIOSSettings_setTimeOffsetRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._timeOffset = value
else:
req._timeOffset = value.handle
self.mgr.getPort().IBIOSSettings_setTimeOffset(req)
def getPXEDebugEnabled(self):
req=IBIOSSettings_getPXEDebugEnabledRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IBIOSSettings_getPXEDebugEnabled(req)
return Boolean(self.mgr,val._returnval)
def setPXEDebugEnabled(self, value):
req=IBIOSSettings_setPXEDebugEnabledRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._PXEDebugEnabled = value
else:
req._PXEDebugEnabled = value.handle
self.mgr.getPort().IBIOSSettings_setPXEDebugEnabled(req)
_Attrs_={ 'logoFadeIn':[getLogoFadeIn,setLogoFadeIn,
],
'logoFadeOut':[getLogoFadeOut,setLogoFadeOut,
],
'logoDisplayTime':[getLogoDisplayTime,setLogoDisplayTime,
],
'logoImagePath':[getLogoImagePath,setLogoImagePath,
],
'bootMenuMode':[getBootMenuMode,setBootMenuMode,
],
'ACPIEnabled':[getACPIEnabled,setACPIEnabled,
],
'IOAPICEnabled':[getIOAPICEnabled,setIOAPICEnabled,
],
'timeOffset':[getTimeOffset,setTimeOffset,
],
'PXEDebugEnabled':[getPXEDebugEnabled,setPXEDebugEnabled,
]}
class IMachine(IUnknown):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IMachine(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IMachine._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IUnknown.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IMachine._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def lockMachine(self, _arg_session, _arg_lockType):
req=IMachine_lockMachineRequestMsg()
req._this=self.handle
req._session=_arg_session
req._lockType=_arg_lockType
val=self.mgr.getPort().IMachine_lockMachine(req)
return
def launchVMProcess(self, _arg_session, _arg_type, _arg_environment):
req=IMachine_launchVMProcessRequestMsg()
req._this=self.handle
req._session=_arg_session
req._type=_arg_type
req._environment=_arg_environment
val=self.mgr.getPort().IMachine_launchVMProcess(req)
return IProgress(self.mgr,val._returnval)
def setBootOrder(self, _arg_position, _arg_device):
req=IMachine_setBootOrderRequestMsg()
req._this=self.handle
req._position=_arg_position
req._device=_arg_device
val=self.mgr.getPort().IMachine_setBootOrder(req)
return
def getBootOrder(self, _arg_position):
req=IMachine_getBootOrderRequestMsg()
req._this=self.handle
req._position=_arg_position
val=self.mgr.getPort().IMachine_getBootOrder(req)
return DeviceType(self.mgr,val._returnval)
def attachDevice(self, _arg_name, _arg_controllerPort, _arg_device, _arg_type, _arg_medium):
req=IMachine_attachDeviceRequestMsg()
req._this=self.handle
req._name=_arg_name
req._controllerPort=_arg_controllerPort
req._device=_arg_device
req._type=_arg_type
req._medium=_arg_medium
val=self.mgr.getPort().IMachine_attachDevice(req)
return
def detachDevice(self, _arg_name, _arg_controllerPort, _arg_device):
req=IMachine_detachDeviceRequestMsg()
req._this=self.handle
req._name=_arg_name
req._controllerPort=_arg_controllerPort
req._device=_arg_device
val=self.mgr.getPort().IMachine_detachDevice(req)
return
def passthroughDevice(self, _arg_name, _arg_controllerPort, _arg_device, _arg_passthrough):
req=IMachine_passthroughDeviceRequestMsg()
req._this=self.handle
req._name=_arg_name
req._controllerPort=_arg_controllerPort
req._device=_arg_device
req._passthrough=_arg_passthrough
val=self.mgr.getPort().IMachine_passthroughDevice(req)
return
def mountMedium(self, _arg_name, _arg_controllerPort, _arg_device, _arg_medium, _arg_force):
req=IMachine_mountMediumRequestMsg()
req._this=self.handle
req._name=_arg_name
req._controllerPort=_arg_controllerPort
req._device=_arg_device
req._medium=_arg_medium
req._force=_arg_force
val=self.mgr.getPort().IMachine_mountMedium(req)
return
def getMedium(self, _arg_name, _arg_controllerPort, _arg_device):
req=IMachine_getMediumRequestMsg()
req._this=self.handle
req._name=_arg_name
req._controllerPort=_arg_controllerPort
req._device=_arg_device
val=self.mgr.getPort().IMachine_getMedium(req)
return IMedium(self.mgr,val._returnval)
def getMediumAttachmentsOfController(self, _arg_name):
req=IMachine_getMediumAttachmentsOfControllerRequestMsg()
req._this=self.handle
req._name=_arg_name
val=self.mgr.getPort().IMachine_getMediumAttachmentsOfController(req)
return IMediumAttachment(self.mgr,val._returnval, True)
def getMediumAttachment(self, _arg_name, _arg_controllerPort, _arg_device):
req=IMachine_getMediumAttachmentRequestMsg()
req._this=self.handle
req._name=_arg_name
req._controllerPort=_arg_controllerPort
req._device=_arg_device
val=self.mgr.getPort().IMachine_getMediumAttachment(req)
return IMediumAttachment(self.mgr,val._returnval)
def getNetworkAdapter(self, _arg_slot):
req=IMachine_getNetworkAdapterRequestMsg()
req._this=self.handle
req._slot=_arg_slot
val=self.mgr.getPort().IMachine_getNetworkAdapter(req)
return INetworkAdapter(self.mgr,val._returnval)
def addStorageController(self, _arg_name, _arg_connectionType):
req=IMachine_addStorageControllerRequestMsg()
req._this=self.handle
req._name=_arg_name
req._connectionType=_arg_connectionType
val=self.mgr.getPort().IMachine_addStorageController(req)
return IStorageController(self.mgr,val._returnval)
def getStorageControllerByName(self, _arg_name):
req=IMachine_getStorageControllerByNameRequestMsg()
req._this=self.handle
req._name=_arg_name
val=self.mgr.getPort().IMachine_getStorageControllerByName(req)
return IStorageController(self.mgr,val._returnval)
def getStorageControllerByInstance(self, _arg_instance):
req=IMachine_getStorageControllerByInstanceRequestMsg()
req._this=self.handle
req._instance=_arg_instance
val=self.mgr.getPort().IMachine_getStorageControllerByInstance(req)
return IStorageController(self.mgr,val._returnval)
def removeStorageController(self, _arg_name):
req=IMachine_removeStorageControllerRequestMsg()
req._this=self.handle
req._name=_arg_name
val=self.mgr.getPort().IMachine_removeStorageController(req)
return
def getSerialPort(self, _arg_slot):
req=IMachine_getSerialPortRequestMsg()
req._this=self.handle
req._slot=_arg_slot
val=self.mgr.getPort().IMachine_getSerialPort(req)
return ISerialPort(self.mgr,val._returnval)
def getParallelPort(self, _arg_slot):
req=IMachine_getParallelPortRequestMsg()
req._this=self.handle
req._slot=_arg_slot
val=self.mgr.getPort().IMachine_getParallelPort(req)
return IParallelPort(self.mgr,val._returnval)
def getExtraDataKeys(self):
req=IMachine_getExtraDataKeysRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getExtraDataKeys(req)
return String(self.mgr,val._returnval, True)
def getExtraData(self, _arg_key):
req=IMachine_getExtraDataRequestMsg()
req._this=self.handle
req._key=_arg_key
val=self.mgr.getPort().IMachine_getExtraData(req)
return String(self.mgr,val._returnval)
def setExtraData(self, _arg_key, _arg_value):
req=IMachine_setExtraDataRequestMsg()
req._this=self.handle
req._key=_arg_key
req._value=_arg_value
val=self.mgr.getPort().IMachine_setExtraData(req)
return
def getCPUProperty(self, _arg_property):
req=IMachine_getCPUPropertyRequestMsg()
req._this=self.handle
req._property=_arg_property
val=self.mgr.getPort().IMachine_getCPUProperty(req)
return Boolean(self.mgr,val._returnval)
def setCPUProperty(self, _arg_property, _arg_value):
req=IMachine_setCPUPropertyRequestMsg()
req._this=self.handle
req._property=_arg_property
req._value=_arg_value
val=self.mgr.getPort().IMachine_setCPUProperty(req)
return
def getCPUIDLeaf(self, _arg_id):
req=IMachine_getCPUIDLeafRequestMsg()
req._this=self.handle
req._id=_arg_id
val=self.mgr.getPort().IMachine_getCPUIDLeaf(req)
return UnsignedInt(self.mgr,val._valEax), UnsignedInt(self.mgr,val._valEbx), UnsignedInt(self.mgr,val._valEcx), UnsignedInt(self.mgr,val._valEdx)
def setCPUIDLeaf(self, _arg_id, _arg_valEax, _arg_valEbx, _arg_valEcx, _arg_valEdx):
req=IMachine_setCPUIDLeafRequestMsg()
req._this=self.handle
req._id=_arg_id
req._valEax=_arg_valEax
req._valEbx=_arg_valEbx
req._valEcx=_arg_valEcx
req._valEdx=_arg_valEdx
val=self.mgr.getPort().IMachine_setCPUIDLeaf(req)
return
def removeCPUIDLeaf(self, _arg_id):
req=IMachine_removeCPUIDLeafRequestMsg()
req._this=self.handle
req._id=_arg_id
val=self.mgr.getPort().IMachine_removeCPUIDLeaf(req)
return
def removeAllCPUIDLeaves(self):
req=IMachine_removeAllCPUIDLeavesRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_removeAllCPUIDLeaves(req)
return
def getHWVirtExProperty(self, _arg_property):
req=IMachine_getHWVirtExPropertyRequestMsg()
req._this=self.handle
req._property=_arg_property
val=self.mgr.getPort().IMachine_getHWVirtExProperty(req)
return Boolean(self.mgr,val._returnval)
def setHWVirtExProperty(self, _arg_property, _arg_value):
req=IMachine_setHWVirtExPropertyRequestMsg()
req._this=self.handle
req._property=_arg_property
req._value=_arg_value
val=self.mgr.getPort().IMachine_setHWVirtExProperty(req)
return
def saveSettings(self):
req=IMachine_saveSettingsRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_saveSettings(req)
return
def discardSettings(self):
req=IMachine_discardSettingsRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_discardSettings(req)
return
def unregister(self, _arg_cleanupMode):
req=IMachine_unregisterRequestMsg()
req._this=self.handle
req._cleanupMode=_arg_cleanupMode
val=self.mgr.getPort().IMachine_unregister(req)
return IMedium(self.mgr,val._returnval, True)
def delete(self, _arg_aMedia):
req=IMachine_deleteRequestMsg()
req._this=self.handle
req._aMedia=_arg_aMedia
val=self.mgr.getPort().IMachine_delete(req)
return IProgress(self.mgr,val._returnval)
def export(self, _arg_aAppliance, _arg_location):
req=IMachine_exportRequestMsg()
req._this=self.handle
req._aAppliance=_arg_aAppliance
req._location=_arg_location
val=self.mgr.getPort().IMachine_export(req)
return IVirtualSystemDescription(self.mgr,val._returnval)
def findSnapshot(self, _arg_nameOrId):
req=IMachine_findSnapshotRequestMsg()
req._this=self.handle
req._nameOrId=_arg_nameOrId
val=self.mgr.getPort().IMachine_findSnapshot(req)
return ISnapshot(self.mgr,val._returnval)
def createSharedFolder(self, _arg_name, _arg_hostPath, _arg_writable, _arg_automount):
req=IMachine_createSharedFolderRequestMsg()
req._this=self.handle
req._name=_arg_name
req._hostPath=_arg_hostPath
req._writable=_arg_writable
req._automount=_arg_automount
val=self.mgr.getPort().IMachine_createSharedFolder(req)
return
def removeSharedFolder(self, _arg_name):
req=IMachine_removeSharedFolderRequestMsg()
req._this=self.handle
req._name=_arg_name
val=self.mgr.getPort().IMachine_removeSharedFolder(req)
return
def canShowConsoleWindow(self):
req=IMachine_canShowConsoleWindowRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_canShowConsoleWindow(req)
return Boolean(self.mgr,val._returnval)
def showConsoleWindow(self):
req=IMachine_showConsoleWindowRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_showConsoleWindow(req)
return Long(self.mgr,val._returnval)
def getGuestProperty(self, _arg_name):
req=IMachine_getGuestPropertyRequestMsg()
req._this=self.handle
req._name=_arg_name
val=self.mgr.getPort().IMachine_getGuestProperty(req)
return String(self.mgr,val._value), Long(self.mgr,val._timestamp), String(self.mgr,val._flags)
def getGuestPropertyValue(self, _arg_property):
req=IMachine_getGuestPropertyValueRequestMsg()
req._this=self.handle
req._property=_arg_property
val=self.mgr.getPort().IMachine_getGuestPropertyValue(req)
return String(self.mgr,val._returnval)
def getGuestPropertyTimestamp(self, _arg_property):
req=IMachine_getGuestPropertyTimestampRequestMsg()
req._this=self.handle
req._property=_arg_property
val=self.mgr.getPort().IMachine_getGuestPropertyTimestamp(req)
return Long(self.mgr,val._returnval)
def setGuestProperty(self, _arg_property, _arg_value, _arg_flags):
req=IMachine_setGuestPropertyRequestMsg()
req._this=self.handle
req._property=_arg_property
req._value=_arg_value
req._flags=_arg_flags
val=self.mgr.getPort().IMachine_setGuestProperty(req)
return
def setGuestPropertyValue(self, _arg_property, _arg_value):
req=IMachine_setGuestPropertyValueRequestMsg()
req._this=self.handle
req._property=_arg_property
req._value=_arg_value
val=self.mgr.getPort().IMachine_setGuestPropertyValue(req)
return
def enumerateGuestProperties(self, _arg_patterns):
req=IMachine_enumerateGuestPropertiesRequestMsg()
req._this=self.handle
req._patterns=_arg_patterns
val=self.mgr.getPort().IMachine_enumerateGuestProperties(req)
return String(self.mgr,val._name, True), String(self.mgr,val._value, True), Long(self.mgr,val._timestamp, True), String(self.mgr,val._flags, True)
def querySavedGuestSize(self, _arg_screenId):
req=IMachine_querySavedGuestSizeRequestMsg()
req._this=self.handle
req._screenId=_arg_screenId
val=self.mgr.getPort().IMachine_querySavedGuestSize(req)
return UnsignedInt(self.mgr,val._width), UnsignedInt(self.mgr,val._height)
def querySavedThumbnailSize(self, _arg_screenId):
req=IMachine_querySavedThumbnailSizeRequestMsg()
req._this=self.handle
req._screenId=_arg_screenId
val=self.mgr.getPort().IMachine_querySavedThumbnailSize(req)
return UnsignedInt(self.mgr,val._size), UnsignedInt(self.mgr,val._width), UnsignedInt(self.mgr,val._height)
def readSavedThumbnailToArray(self, _arg_screenId, _arg_BGR):
req=IMachine_readSavedThumbnailToArrayRequestMsg()
req._this=self.handle
req._screenId=_arg_screenId
req._BGR=_arg_BGR
val=self.mgr.getPort().IMachine_readSavedThumbnailToArray(req)
return Octet(self.mgr,val._returnval, True), UnsignedInt(self.mgr,val._width), UnsignedInt(self.mgr,val._height)
def readSavedThumbnailPNGToArray(self, _arg_screenId):
req=IMachine_readSavedThumbnailPNGToArrayRequestMsg()
req._this=self.handle
req._screenId=_arg_screenId
val=self.mgr.getPort().IMachine_readSavedThumbnailPNGToArray(req)
return Octet(self.mgr,val._returnval, True), UnsignedInt(self.mgr,val._width), UnsignedInt(self.mgr,val._height)
def querySavedScreenshotPNGSize(self, _arg_screenId):
req=IMachine_querySavedScreenshotPNGSizeRequestMsg()
req._this=self.handle
req._screenId=_arg_screenId
val=self.mgr.getPort().IMachine_querySavedScreenshotPNGSize(req)
return UnsignedInt(self.mgr,val._size), UnsignedInt(self.mgr,val._width), UnsignedInt(self.mgr,val._height)
def readSavedScreenshotPNGToArray(self, _arg_screenId):
req=IMachine_readSavedScreenshotPNGToArrayRequestMsg()
req._this=self.handle
req._screenId=_arg_screenId
val=self.mgr.getPort().IMachine_readSavedScreenshotPNGToArray(req)
return Octet(self.mgr,val._returnval, True), UnsignedInt(self.mgr,val._width), UnsignedInt(self.mgr,val._height)
def hotPlugCPU(self, _arg_cpu):
req=IMachine_hotPlugCPURequestMsg()
req._this=self.handle
req._cpu=_arg_cpu
val=self.mgr.getPort().IMachine_hotPlugCPU(req)
return
def hotUnplugCPU(self, _arg_cpu):
req=IMachine_hotUnplugCPURequestMsg()
req._this=self.handle
req._cpu=_arg_cpu
val=self.mgr.getPort().IMachine_hotUnplugCPU(req)
return
def getCPUStatus(self, _arg_cpu):
req=IMachine_getCPUStatusRequestMsg()
req._this=self.handle
req._cpu=_arg_cpu
val=self.mgr.getPort().IMachine_getCPUStatus(req)
return Boolean(self.mgr,val._returnval)
def queryLogFilename(self, _arg_idx):
req=IMachine_queryLogFilenameRequestMsg()
req._this=self.handle
req._idx=_arg_idx
val=self.mgr.getPort().IMachine_queryLogFilename(req)
return String(self.mgr,val._returnval)
def readLog(self, _arg_idx, _arg_offset, _arg_size):
req=IMachine_readLogRequestMsg()
req._this=self.handle
req._idx=_arg_idx
req._offset=_arg_offset
req._size=_arg_size
val=self.mgr.getPort().IMachine_readLog(req)
return Octet(self.mgr,val._returnval, True)
def getParent(self):
req=IMachine_getParentRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getParent(req)
return IVirtualBox(self.mgr,val._returnval)
def getAccessible(self):
req=IMachine_getAccessibleRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getAccessible(req)
return Boolean(self.mgr,val._returnval)
def getAccessError(self):
req=IMachine_getAccessErrorRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getAccessError(req)
return IVirtualBoxErrorInfo(self.mgr,val._returnval)
def getName(self):
req=IMachine_getNameRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getName(req)
return String(self.mgr,val._returnval)
def setName(self, value):
req=IMachine_setNameRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._name = value
else:
req._name = value.handle
self.mgr.getPort().IMachine_setName(req)
def getDescription(self):
req=IMachine_getDescriptionRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getDescription(req)
return String(self.mgr,val._returnval)
def setDescription(self, value):
req=IMachine_setDescriptionRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._description = value
else:
req._description = value.handle
self.mgr.getPort().IMachine_setDescription(req)
def getId(self):
req=IMachine_getIdRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getId(req)
return String(self.mgr,val._returnval)
def getOSTypeId(self):
req=IMachine_getOSTypeIdRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getOSTypeId(req)
return String(self.mgr,val._returnval)
def setOSTypeId(self, value):
req=IMachine_setOSTypeIdRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._OSTypeId = value
else:
req._OSTypeId = value.handle
self.mgr.getPort().IMachine_setOSTypeId(req)
def getHardwareVersion(self):
req=IMachine_getHardwareVersionRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getHardwareVersion(req)
return String(self.mgr,val._returnval)
def setHardwareVersion(self, value):
req=IMachine_setHardwareVersionRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._HardwareVersion = value
else:
req._HardwareVersion = value.handle
self.mgr.getPort().IMachine_setHardwareVersion(req)
def getHardwareUUID(self):
req=IMachine_getHardwareUUIDRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getHardwareUUID(req)
return String(self.mgr,val._returnval)
def setHardwareUUID(self, value):
req=IMachine_setHardwareUUIDRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._hardwareUUID = value
else:
req._hardwareUUID = value.handle
self.mgr.getPort().IMachine_setHardwareUUID(req)
def getCPUCount(self):
req=IMachine_getCPUCountRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getCPUCount(req)
return UnsignedInt(self.mgr,val._returnval)
def setCPUCount(self, value):
req=IMachine_setCPUCountRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._CPUCount = value
else:
req._CPUCount = value.handle
self.mgr.getPort().IMachine_setCPUCount(req)
def getCPUHotPlugEnabled(self):
req=IMachine_getCPUHotPlugEnabledRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getCPUHotPlugEnabled(req)
return Boolean(self.mgr,val._returnval)
def setCPUHotPlugEnabled(self, value):
req=IMachine_setCPUHotPlugEnabledRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._CPUHotPlugEnabled = value
else:
req._CPUHotPlugEnabled = value.handle
self.mgr.getPort().IMachine_setCPUHotPlugEnabled(req)
def getCPUExecutionCap(self):
req=IMachine_getCPUExecutionCapRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getCPUExecutionCap(req)
return UnsignedInt(self.mgr,val._returnval)
def setCPUExecutionCap(self, value):
req=IMachine_setCPUExecutionCapRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._CPUExecutionCap = value
else:
req._CPUExecutionCap = value.handle
self.mgr.getPort().IMachine_setCPUExecutionCap(req)
def getMemorySize(self):
req=IMachine_getMemorySizeRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getMemorySize(req)
return UnsignedInt(self.mgr,val._returnval)
def setMemorySize(self, value):
req=IMachine_setMemorySizeRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._memorySize = value
else:
req._memorySize = value.handle
self.mgr.getPort().IMachine_setMemorySize(req)
def getMemoryBalloonSize(self):
req=IMachine_getMemoryBalloonSizeRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getMemoryBalloonSize(req)
return UnsignedInt(self.mgr,val._returnval)
def setMemoryBalloonSize(self, value):
req=IMachine_setMemoryBalloonSizeRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._memoryBalloonSize = value
else:
req._memoryBalloonSize = value.handle
self.mgr.getPort().IMachine_setMemoryBalloonSize(req)
def getPageFusionEnabled(self):
req=IMachine_getPageFusionEnabledRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getPageFusionEnabled(req)
return Boolean(self.mgr,val._returnval)
def setPageFusionEnabled(self, value):
req=IMachine_setPageFusionEnabledRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._PageFusionEnabled = value
else:
req._PageFusionEnabled = value.handle
self.mgr.getPort().IMachine_setPageFusionEnabled(req)
def getVRAMSize(self):
req=IMachine_getVRAMSizeRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getVRAMSize(req)
return UnsignedInt(self.mgr,val._returnval)
def setVRAMSize(self, value):
req=IMachine_setVRAMSizeRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._VRAMSize = value
else:
req._VRAMSize = value.handle
self.mgr.getPort().IMachine_setVRAMSize(req)
def getAccelerate3DEnabled(self):
req=IMachine_getAccelerate3DEnabledRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getAccelerate3DEnabled(req)
return Boolean(self.mgr,val._returnval)
def setAccelerate3DEnabled(self, value):
req=IMachine_setAccelerate3DEnabledRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._accelerate3DEnabled = value
else:
req._accelerate3DEnabled = value.handle
self.mgr.getPort().IMachine_setAccelerate3DEnabled(req)
def getAccelerate2DVideoEnabled(self):
req=IMachine_getAccelerate2DVideoEnabledRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getAccelerate2DVideoEnabled(req)
return Boolean(self.mgr,val._returnval)
def setAccelerate2DVideoEnabled(self, value):
req=IMachine_setAccelerate2DVideoEnabledRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._accelerate2DVideoEnabled = value
else:
req._accelerate2DVideoEnabled = value.handle
self.mgr.getPort().IMachine_setAccelerate2DVideoEnabled(req)
def getMonitorCount(self):
req=IMachine_getMonitorCountRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getMonitorCount(req)
return UnsignedInt(self.mgr,val._returnval)
def setMonitorCount(self, value):
req=IMachine_setMonitorCountRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._monitorCount = value
else:
req._monitorCount = value.handle
self.mgr.getPort().IMachine_setMonitorCount(req)
def getBIOSSettings(self):
req=IMachine_getBIOSSettingsRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getBIOSSettings(req)
return IBIOSSettings(self.mgr,val._returnval)
def getFirmwareType(self):
req=IMachine_getFirmwareTypeRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getFirmwareType(req)
return FirmwareType(self.mgr,val._returnval)
def setFirmwareType(self, value):
req=IMachine_setFirmwareTypeRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._firmwareType = value
else:
req._firmwareType = value.handle
self.mgr.getPort().IMachine_setFirmwareType(req)
def getPointingHidType(self):
req=IMachine_getPointingHidTypeRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getPointingHidType(req)
return PointingHidType(self.mgr,val._returnval)
def setPointingHidType(self, value):
req=IMachine_setPointingHidTypeRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._pointingHidType = value
else:
req._pointingHidType = value.handle
self.mgr.getPort().IMachine_setPointingHidType(req)
def getKeyboardHidType(self):
req=IMachine_getKeyboardHidTypeRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getKeyboardHidType(req)
return KeyboardHidType(self.mgr,val._returnval)
def setKeyboardHidType(self, value):
req=IMachine_setKeyboardHidTypeRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._keyboardHidType = value
else:
req._keyboardHidType = value.handle
self.mgr.getPort().IMachine_setKeyboardHidType(req)
def getHpetEnabled(self):
req=IMachine_getHpetEnabledRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getHpetEnabled(req)
return Boolean(self.mgr,val._returnval)
def setHpetEnabled(self, value):
req=IMachine_setHpetEnabledRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._hpetEnabled = value
else:
req._hpetEnabled = value.handle
self.mgr.getPort().IMachine_setHpetEnabled(req)
def getChipsetType(self):
req=IMachine_getChipsetTypeRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getChipsetType(req)
return ChipsetType(self.mgr,val._returnval)
def setChipsetType(self, value):
req=IMachine_setChipsetTypeRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._chipsetType = value
else:
req._chipsetType = value.handle
self.mgr.getPort().IMachine_setChipsetType(req)
def getSnapshotFolder(self):
req=IMachine_getSnapshotFolderRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getSnapshotFolder(req)
return String(self.mgr,val._returnval)
def setSnapshotFolder(self, value):
req=IMachine_setSnapshotFolderRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._snapshotFolder = value
else:
req._snapshotFolder = value.handle
self.mgr.getPort().IMachine_setSnapshotFolder(req)
def getVRDEServer(self):
req=IMachine_getVRDEServerRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getVRDEServer(req)
return IVRDEServer(self.mgr,val._returnval)
def getMediumAttachments(self):
req=IMachine_getMediumAttachmentsRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getMediumAttachments(req)
return IMediumAttachment(self.mgr,val._returnval, True)
def getUSBController(self):
req=IMachine_getUSBControllerRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getUSBController(req)
return IUSBController(self.mgr,val._returnval)
def getAudioAdapter(self):
req=IMachine_getAudioAdapterRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getAudioAdapter(req)
return IAudioAdapter(self.mgr,val._returnval)
def getStorageControllers(self):
req=IMachine_getStorageControllersRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getStorageControllers(req)
return IStorageController(self.mgr,val._returnval, True)
def getSettingsFilePath(self):
req=IMachine_getSettingsFilePathRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getSettingsFilePath(req)
return String(self.mgr,val._returnval)
def getSettingsModified(self):
req=IMachine_getSettingsModifiedRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getSettingsModified(req)
return Boolean(self.mgr,val._returnval)
def getSessionState(self):
req=IMachine_getSessionStateRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getSessionState(req)
return SessionState(self.mgr,val._returnval)
def getSessionType(self):
req=IMachine_getSessionTypeRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getSessionType(req)
return String(self.mgr,val._returnval)
def getSessionPid(self):
req=IMachine_getSessionPidRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getSessionPid(req)
return UnsignedInt(self.mgr,val._returnval)
def getState(self):
req=IMachine_getStateRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getState(req)
return MachineState(self.mgr,val._returnval)
def getLastStateChange(self):
req=IMachine_getLastStateChangeRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getLastStateChange(req)
return Long(self.mgr,val._returnval)
def getStateFilePath(self):
req=IMachine_getStateFilePathRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getStateFilePath(req)
return String(self.mgr,val._returnval)
def getLogFolder(self):
req=IMachine_getLogFolderRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getLogFolder(req)
return String(self.mgr,val._returnval)
def getCurrentSnapshot(self):
req=IMachine_getCurrentSnapshotRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getCurrentSnapshot(req)
return ISnapshot(self.mgr,val._returnval)
def getSnapshotCount(self):
req=IMachine_getSnapshotCountRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getSnapshotCount(req)
return UnsignedInt(self.mgr,val._returnval)
def getCurrentStateModified(self):
req=IMachine_getCurrentStateModifiedRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getCurrentStateModified(req)
return Boolean(self.mgr,val._returnval)
def getSharedFolders(self):
req=IMachine_getSharedFoldersRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getSharedFolders(req)
return ISharedFolder(self.mgr,val._returnval, True)
def getClipboardMode(self):
req=IMachine_getClipboardModeRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getClipboardMode(req)
return ClipboardMode(self.mgr,val._returnval)
def setClipboardMode(self, value):
req=IMachine_setClipboardModeRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._clipboardMode = value
else:
req._clipboardMode = value.handle
self.mgr.getPort().IMachine_setClipboardMode(req)
def getGuestPropertyNotificationPatterns(self):
req=IMachine_getGuestPropertyNotificationPatternsRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getGuestPropertyNotificationPatterns(req)
return String(self.mgr,val._returnval)
def setGuestPropertyNotificationPatterns(self, value):
req=IMachine_setGuestPropertyNotificationPatternsRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._guestPropertyNotificationPatterns = value
else:
req._guestPropertyNotificationPatterns = value.handle
self.mgr.getPort().IMachine_setGuestPropertyNotificationPatterns(req)
def getTeleporterEnabled(self):
req=IMachine_getTeleporterEnabledRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getTeleporterEnabled(req)
return Boolean(self.mgr,val._returnval)
def setTeleporterEnabled(self, value):
req=IMachine_setTeleporterEnabledRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._teleporterEnabled = value
else:
req._teleporterEnabled = value.handle
self.mgr.getPort().IMachine_setTeleporterEnabled(req)
def getTeleporterPort(self):
req=IMachine_getTeleporterPortRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getTeleporterPort(req)
return UnsignedInt(self.mgr,val._returnval)
def setTeleporterPort(self, value):
req=IMachine_setTeleporterPortRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._teleporterPort = value
else:
req._teleporterPort = value.handle
self.mgr.getPort().IMachine_setTeleporterPort(req)
def getTeleporterAddress(self):
req=IMachine_getTeleporterAddressRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getTeleporterAddress(req)
return String(self.mgr,val._returnval)
def setTeleporterAddress(self, value):
req=IMachine_setTeleporterAddressRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._teleporterAddress = value
else:
req._teleporterAddress = value.handle
self.mgr.getPort().IMachine_setTeleporterAddress(req)
def getTeleporterPassword(self):
req=IMachine_getTeleporterPasswordRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getTeleporterPassword(req)
return String(self.mgr,val._returnval)
def setTeleporterPassword(self, value):
req=IMachine_setTeleporterPasswordRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._teleporterPassword = value
else:
req._teleporterPassword = value.handle
self.mgr.getPort().IMachine_setTeleporterPassword(req)
def getFaultToleranceState(self):
req=IMachine_getFaultToleranceStateRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getFaultToleranceState(req)
return FaultToleranceState(self.mgr,val._returnval)
def setFaultToleranceState(self, value):
req=IMachine_setFaultToleranceStateRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._faultToleranceState = value
else:
req._faultToleranceState = value.handle
self.mgr.getPort().IMachine_setFaultToleranceState(req)
def getFaultTolerancePort(self):
req=IMachine_getFaultTolerancePortRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getFaultTolerancePort(req)
return UnsignedInt(self.mgr,val._returnval)
def setFaultTolerancePort(self, value):
req=IMachine_setFaultTolerancePortRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._faultTolerancePort = value
else:
req._faultTolerancePort = value.handle
self.mgr.getPort().IMachine_setFaultTolerancePort(req)
def getFaultToleranceAddress(self):
req=IMachine_getFaultToleranceAddressRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getFaultToleranceAddress(req)
return String(self.mgr,val._returnval)
def setFaultToleranceAddress(self, value):
req=IMachine_setFaultToleranceAddressRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._faultToleranceAddress = value
else:
req._faultToleranceAddress = value.handle
self.mgr.getPort().IMachine_setFaultToleranceAddress(req)
def getFaultTolerancePassword(self):
req=IMachine_getFaultTolerancePasswordRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getFaultTolerancePassword(req)
return String(self.mgr,val._returnval)
def setFaultTolerancePassword(self, value):
req=IMachine_setFaultTolerancePasswordRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._faultTolerancePassword = value
else:
req._faultTolerancePassword = value.handle
self.mgr.getPort().IMachine_setFaultTolerancePassword(req)
def getFaultToleranceSyncInterval(self):
req=IMachine_getFaultToleranceSyncIntervalRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getFaultToleranceSyncInterval(req)
return UnsignedInt(self.mgr,val._returnval)
def setFaultToleranceSyncInterval(self, value):
req=IMachine_setFaultToleranceSyncIntervalRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._faultToleranceSyncInterval = value
else:
req._faultToleranceSyncInterval = value.handle
self.mgr.getPort().IMachine_setFaultToleranceSyncInterval(req)
def getRTCUseUTC(self):
req=IMachine_getRTCUseUTCRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getRTCUseUTC(req)
return Boolean(self.mgr,val._returnval)
def setRTCUseUTC(self, value):
req=IMachine_setRTCUseUTCRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._RTCUseUTC = value
else:
req._RTCUseUTC = value.handle
self.mgr.getPort().IMachine_setRTCUseUTC(req)
def getIoCacheEnabled(self):
req=IMachine_getIoCacheEnabledRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getIoCacheEnabled(req)
return Boolean(self.mgr,val._returnval)
def setIoCacheEnabled(self, value):
req=IMachine_setIoCacheEnabledRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._ioCacheEnabled = value
else:
req._ioCacheEnabled = value.handle
self.mgr.getPort().IMachine_setIoCacheEnabled(req)
def getIoCacheSize(self):
req=IMachine_getIoCacheSizeRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachine_getIoCacheSize(req)
return UnsignedInt(self.mgr,val._returnval)
def setIoCacheSize(self, value):
req=IMachine_setIoCacheSizeRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._ioCacheSize = value
else:
req._ioCacheSize = value.handle
self.mgr.getPort().IMachine_setIoCacheSize(req)
_Attrs_={ 'parent':[getParent,None],
'accessible':[getAccessible,None],
'accessError':[getAccessError,None],
'name':[getName,setName,
],
'description':[getDescription,setDescription,
],
'id':[getId,None],
'OSTypeId':[getOSTypeId,setOSTypeId,
],
'HardwareVersion':[getHardwareVersion,setHardwareVersion,
],
'hardwareUUID':[getHardwareUUID,setHardwareUUID,
],
'CPUCount':[getCPUCount,setCPUCount,
],
'CPUHotPlugEnabled':[getCPUHotPlugEnabled,setCPUHotPlugEnabled,
],
'CPUExecutionCap':[getCPUExecutionCap,setCPUExecutionCap,
],
'memorySize':[getMemorySize,setMemorySize,
],
'memoryBalloonSize':[getMemoryBalloonSize,setMemoryBalloonSize,
],
'PageFusionEnabled':[getPageFusionEnabled,setPageFusionEnabled,
],
'VRAMSize':[getVRAMSize,setVRAMSize,
],
'accelerate3DEnabled':[getAccelerate3DEnabled,setAccelerate3DEnabled,
],
'accelerate2DVideoEnabled':[getAccelerate2DVideoEnabled,setAccelerate2DVideoEnabled,
],
'monitorCount':[getMonitorCount,setMonitorCount,
],
'BIOSSettings':[getBIOSSettings,None],
'firmwareType':[getFirmwareType,setFirmwareType,
],
'pointingHidType':[getPointingHidType,setPointingHidType,
],
'keyboardHidType':[getKeyboardHidType,setKeyboardHidType,
],
'hpetEnabled':[getHpetEnabled,setHpetEnabled,
],
'chipsetType':[getChipsetType,setChipsetType,
],
'snapshotFolder':[getSnapshotFolder,setSnapshotFolder,
],
'VRDEServer':[getVRDEServer,None],
'mediumAttachments':[getMediumAttachments,None],
'USBController':[getUSBController,None],
'audioAdapter':[getAudioAdapter,None],
'storageControllers':[getStorageControllers,None],
'settingsFilePath':[getSettingsFilePath,None],
'settingsModified':[getSettingsModified,None],
'sessionState':[getSessionState,None],
'sessionType':[getSessionType,None],
'sessionPid':[getSessionPid,None],
'state':[getState,None],
'lastStateChange':[getLastStateChange,None],
'stateFilePath':[getStateFilePath,None],
'logFolder':[getLogFolder,None],
'currentSnapshot':[getCurrentSnapshot,None],
'snapshotCount':[getSnapshotCount,None],
'currentStateModified':[getCurrentStateModified,None],
'sharedFolders':[getSharedFolders,None],
'clipboardMode':[getClipboardMode,setClipboardMode,
],
'guestPropertyNotificationPatterns':[getGuestPropertyNotificationPatterns,setGuestPropertyNotificationPatterns,
],
'teleporterEnabled':[getTeleporterEnabled,setTeleporterEnabled,
],
'teleporterPort':[getTeleporterPort,setTeleporterPort,
],
'teleporterAddress':[getTeleporterAddress,setTeleporterAddress,
],
'teleporterPassword':[getTeleporterPassword,setTeleporterPassword,
],
'faultToleranceState':[getFaultToleranceState,setFaultToleranceState,
],
'faultTolerancePort':[getFaultTolerancePort,setFaultTolerancePort,
],
'faultToleranceAddress':[getFaultToleranceAddress,setFaultToleranceAddress,
],
'faultTolerancePassword':[getFaultTolerancePassword,setFaultTolerancePassword,
],
'faultToleranceSyncInterval':[getFaultToleranceSyncInterval,setFaultToleranceSyncInterval,
],
'RTCUseUTC':[getRTCUseUTC,setRTCUseUTC,
],
'ioCacheEnabled':[getIoCacheEnabled,setIoCacheEnabled,
],
'ioCacheSize':[getIoCacheSize,setIoCacheSize,
]}
class IConsole(IUnknown):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IConsole(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IConsole._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IUnknown.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IConsole._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def powerUp(self):
req=IConsole_powerUpRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IConsole_powerUp(req)
return IProgress(self.mgr,val._returnval)
def powerUpPaused(self):
req=IConsole_powerUpPausedRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IConsole_powerUpPaused(req)
return IProgress(self.mgr,val._returnval)
def powerDown(self):
req=IConsole_powerDownRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IConsole_powerDown(req)
return IProgress(self.mgr,val._returnval)
def reset(self):
req=IConsole_resetRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IConsole_reset(req)
return
def pause(self):
req=IConsole_pauseRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IConsole_pause(req)
return
def resume(self):
req=IConsole_resumeRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IConsole_resume(req)
return
def powerButton(self):
req=IConsole_powerButtonRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IConsole_powerButton(req)
return
def sleepButton(self):
req=IConsole_sleepButtonRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IConsole_sleepButton(req)
return
def getPowerButtonHandled(self):
req=IConsole_getPowerButtonHandledRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IConsole_getPowerButtonHandled(req)
return Boolean(self.mgr,val._returnval)
def getGuestEnteredACPIMode(self):
req=IConsole_getGuestEnteredACPIModeRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IConsole_getGuestEnteredACPIMode(req)
return Boolean(self.mgr,val._returnval)
def saveState(self):
req=IConsole_saveStateRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IConsole_saveState(req)
return IProgress(self.mgr,val._returnval)
def adoptSavedState(self, _arg_savedStateFile):
req=IConsole_adoptSavedStateRequestMsg()
req._this=self.handle
req._savedStateFile=_arg_savedStateFile
val=self.mgr.getPort().IConsole_adoptSavedState(req)
return
def discardSavedState(self, _arg_fRemoveFile):
req=IConsole_discardSavedStateRequestMsg()
req._this=self.handle
req._fRemoveFile=_arg_fRemoveFile
val=self.mgr.getPort().IConsole_discardSavedState(req)
return
def getDeviceActivity(self, _arg_type):
req=IConsole_getDeviceActivityRequestMsg()
req._this=self.handle
req._type=_arg_type
val=self.mgr.getPort().IConsole_getDeviceActivity(req)
return DeviceActivity(self.mgr,val._returnval)
def attachUSBDevice(self, _arg_id):
req=IConsole_attachUSBDeviceRequestMsg()
req._this=self.handle
req._id=_arg_id
val=self.mgr.getPort().IConsole_attachUSBDevice(req)
return
def detachUSBDevice(self, _arg_id):
req=IConsole_detachUSBDeviceRequestMsg()
req._this=self.handle
req._id=_arg_id
val=self.mgr.getPort().IConsole_detachUSBDevice(req)
return IUSBDevice(self.mgr,val._returnval)
def findUSBDeviceByAddress(self, _arg_name):
req=IConsole_findUSBDeviceByAddressRequestMsg()
req._this=self.handle
req._name=_arg_name
val=self.mgr.getPort().IConsole_findUSBDeviceByAddress(req)
return IUSBDevice(self.mgr,val._returnval)
def findUSBDeviceById(self, _arg_id):
req=IConsole_findUSBDeviceByIdRequestMsg()
req._this=self.handle
req._id=_arg_id
val=self.mgr.getPort().IConsole_findUSBDeviceById(req)
return IUSBDevice(self.mgr,val._returnval)
def createSharedFolder(self, _arg_name, _arg_hostPath, _arg_writable, _arg_automount):
req=IConsole_createSharedFolderRequestMsg()
req._this=self.handle
req._name=_arg_name
req._hostPath=_arg_hostPath
req._writable=_arg_writable
req._automount=_arg_automount
val=self.mgr.getPort().IConsole_createSharedFolder(req)
return
def removeSharedFolder(self, _arg_name):
req=IConsole_removeSharedFolderRequestMsg()
req._this=self.handle
req._name=_arg_name
val=self.mgr.getPort().IConsole_removeSharedFolder(req)
return
def takeSnapshot(self, _arg_name, _arg_description):
req=IConsole_takeSnapshotRequestMsg()
req._this=self.handle
req._name=_arg_name
req._description=_arg_description
val=self.mgr.getPort().IConsole_takeSnapshot(req)
return IProgress(self.mgr,val._returnval)
def deleteSnapshot(self, _arg_id):
req=IConsole_deleteSnapshotRequestMsg()
req._this=self.handle
req._id=_arg_id
val=self.mgr.getPort().IConsole_deleteSnapshot(req)
return IProgress(self.mgr,val._returnval)
def restoreSnapshot(self, _arg_snapshot):
req=IConsole_restoreSnapshotRequestMsg()
req._this=self.handle
req._snapshot=_arg_snapshot
val=self.mgr.getPort().IConsole_restoreSnapshot(req)
return IProgress(self.mgr,val._returnval)
def teleport(self, _arg_hostname, _arg_tcpport, _arg_password, _arg_maxDowntime):
req=IConsole_teleportRequestMsg()
req._this=self.handle
req._hostname=_arg_hostname
req._tcpport=_arg_tcpport
req._password=_arg_password
req._maxDowntime=_arg_maxDowntime
val=self.mgr.getPort().IConsole_teleport(req)
return IProgress(self.mgr,val._returnval)
def getMachine(self):
req=IConsole_getMachineRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IConsole_getMachine(req)
return IMachine(self.mgr,val._returnval)
def getState(self):
req=IConsole_getStateRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IConsole_getState(req)
return MachineState(self.mgr,val._returnval)
def getGuest(self):
req=IConsole_getGuestRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IConsole_getGuest(req)
return IGuest(self.mgr,val._returnval)
def getKeyboard(self):
req=IConsole_getKeyboardRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IConsole_getKeyboard(req)
return IKeyboard(self.mgr,val._returnval)
def getMouse(self):
req=IConsole_getMouseRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IConsole_getMouse(req)
return IMouse(self.mgr,val._returnval)
def getDisplay(self):
req=IConsole_getDisplayRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IConsole_getDisplay(req)
return IDisplay(self.mgr,val._returnval)
def getUSBDevices(self):
req=IConsole_getUSBDevicesRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IConsole_getUSBDevices(req)
return IUSBDevice(self.mgr,val._returnval, True)
def getRemoteUSBDevices(self):
req=IConsole_getRemoteUSBDevicesRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IConsole_getRemoteUSBDevices(req)
return IHostUSBDevice(self.mgr,val._returnval, True)
def getSharedFolders(self):
req=IConsole_getSharedFoldersRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IConsole_getSharedFolders(req)
return ISharedFolder(self.mgr,val._returnval, True)
def getVRDEServerInfo(self):
req=IConsole_getVRDEServerInfoRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IConsole_getVRDEServerInfo(req)
return IVRDEServerInfo(self.mgr,val._returnval)
def getEventSource(self):
req=IConsole_getEventSourceRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IConsole_getEventSource(req)
return IEventSource(self.mgr,val._returnval)
_Attrs_={ 'machine':[getMachine,None],
'state':[getState,None],
'guest':[getGuest,None],
'keyboard':[getKeyboard,None],
'mouse':[getMouse,None],
'display':[getDisplay,None],
'USBDevices':[getUSBDevices,None],
'remoteUSBDevices':[getRemoteUSBDevices,None],
'sharedFolders':[getSharedFolders,None],
'VRDEServerInfo':[getVRDEServerInfo,None],
'eventSource':[getEventSource,None]}
class IHostNetworkInterface(IUnknown):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IHostNetworkInterface(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IHostNetworkInterface._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IUnknown.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IHostNetworkInterface._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def enableStaticIpConfig(self, _arg_IPAddress, _arg_networkMask):
req=IHostNetworkInterface_enableStaticIpConfigRequestMsg()
req._this=self.handle
req._IPAddress=_arg_IPAddress
req._networkMask=_arg_networkMask
val=self.mgr.getPort().IHostNetworkInterface_enableStaticIpConfig(req)
return
def enableStaticIpConfigV6(self, _arg_IPV6Address, _arg_IPV6NetworkMaskPrefixLength):
req=IHostNetworkInterface_enableStaticIpConfigV6RequestMsg()
req._this=self.handle
req._IPV6Address=_arg_IPV6Address
req._IPV6NetworkMaskPrefixLength=_arg_IPV6NetworkMaskPrefixLength
val=self.mgr.getPort().IHostNetworkInterface_enableStaticIpConfigV6(req)
return
def enableDynamicIpConfig(self):
req=IHostNetworkInterface_enableDynamicIpConfigRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IHostNetworkInterface_enableDynamicIpConfig(req)
return
def dhcpRediscover(self):
req=IHostNetworkInterface_dhcpRediscoverRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IHostNetworkInterface_dhcpRediscover(req)
return
def getName(self):
req=IHostNetworkInterface_getNameRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IHostNetworkInterface_getName(req)
return String(self.mgr,val._returnval)
def getId(self):
req=IHostNetworkInterface_getIdRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IHostNetworkInterface_getId(req)
return String(self.mgr,val._returnval)
def getNetworkName(self):
req=IHostNetworkInterface_getNetworkNameRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IHostNetworkInterface_getNetworkName(req)
return String(self.mgr,val._returnval)
def getDhcpEnabled(self):
req=IHostNetworkInterface_getDhcpEnabledRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IHostNetworkInterface_getDhcpEnabled(req)
return Boolean(self.mgr,val._returnval)
def getIPAddress(self):
req=IHostNetworkInterface_getIPAddressRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IHostNetworkInterface_getIPAddress(req)
return String(self.mgr,val._returnval)
def getNetworkMask(self):
req=IHostNetworkInterface_getNetworkMaskRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IHostNetworkInterface_getNetworkMask(req)
return String(self.mgr,val._returnval)
def getIPV6Supported(self):
req=IHostNetworkInterface_getIPV6SupportedRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IHostNetworkInterface_getIPV6Supported(req)
return Boolean(self.mgr,val._returnval)
def getIPV6Address(self):
req=IHostNetworkInterface_getIPV6AddressRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IHostNetworkInterface_getIPV6Address(req)
return String(self.mgr,val._returnval)
def getIPV6NetworkMaskPrefixLength(self):
req=IHostNetworkInterface_getIPV6NetworkMaskPrefixLengthRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IHostNetworkInterface_getIPV6NetworkMaskPrefixLength(req)
return UnsignedInt(self.mgr,val._returnval)
def getHardwareAddress(self):
req=IHostNetworkInterface_getHardwareAddressRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IHostNetworkInterface_getHardwareAddress(req)
return String(self.mgr,val._returnval)
def getMediumType(self):
req=IHostNetworkInterface_getMediumTypeRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IHostNetworkInterface_getMediumType(req)
return HostNetworkInterfaceMediumType(self.mgr,val._returnval)
def getStatus(self):
req=IHostNetworkInterface_getStatusRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IHostNetworkInterface_getStatus(req)
return HostNetworkInterfaceStatus(self.mgr,val._returnval)
def getInterfaceType(self):
req=IHostNetworkInterface_getInterfaceTypeRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IHostNetworkInterface_getInterfaceType(req)
return HostNetworkInterfaceType(self.mgr,val._returnval)
_Attrs_={ 'name':[getName,None],
'id':[getId,None],
'networkName':[getNetworkName,None],
'dhcpEnabled':[getDhcpEnabled,None],
'IPAddress':[getIPAddress,None],
'networkMask':[getNetworkMask,None],
'IPV6Supported':[getIPV6Supported,None],
'IPV6Address':[getIPV6Address,None],
'IPV6NetworkMaskPrefixLength':[getIPV6NetworkMaskPrefixLength,None],
'hardwareAddress':[getHardwareAddress,None],
'mediumType':[getMediumType,None],
'status':[getStatus,None],
'interfaceType':[getInterfaceType,None]}
class IHost(IUnknown):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IHost(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IHost._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IUnknown.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IHost._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def getProcessorSpeed(self, _arg_cpuId):
req=IHost_getProcessorSpeedRequestMsg()
req._this=self.handle
req._cpuId=_arg_cpuId
val=self.mgr.getPort().IHost_getProcessorSpeed(req)
return UnsignedInt(self.mgr,val._returnval)
def getProcessorFeature(self, _arg_feature):
req=IHost_getProcessorFeatureRequestMsg()
req._this=self.handle
req._feature=_arg_feature
val=self.mgr.getPort().IHost_getProcessorFeature(req)
return Boolean(self.mgr,val._returnval)
def getProcessorDescription(self, _arg_cpuId):
req=IHost_getProcessorDescriptionRequestMsg()
req._this=self.handle
req._cpuId=_arg_cpuId
val=self.mgr.getPort().IHost_getProcessorDescription(req)
return String(self.mgr,val._returnval)
def getProcessorCPUIDLeaf(self, _arg_cpuId, _arg_leaf, _arg_subLeaf):
req=IHost_getProcessorCPUIDLeafRequestMsg()
req._this=self.handle
req._cpuId=_arg_cpuId
req._leaf=_arg_leaf
req._subLeaf=_arg_subLeaf
val=self.mgr.getPort().IHost_getProcessorCPUIDLeaf(req)
return UnsignedInt(self.mgr,val._valEax), UnsignedInt(self.mgr,val._valEbx), UnsignedInt(self.mgr,val._valEcx), UnsignedInt(self.mgr,val._valEdx)
def createHostOnlyNetworkInterface(self):
req=IHost_createHostOnlyNetworkInterfaceRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IHost_createHostOnlyNetworkInterface(req)
return IProgress(self.mgr,val._returnval), IHostNetworkInterface(self.mgr,val._hostInterface)
def removeHostOnlyNetworkInterface(self, _arg_id):
req=IHost_removeHostOnlyNetworkInterfaceRequestMsg()
req._this=self.handle
req._id=_arg_id
val=self.mgr.getPort().IHost_removeHostOnlyNetworkInterface(req)
return IProgress(self.mgr,val._returnval)
def createUSBDeviceFilter(self, _arg_name):
req=IHost_createUSBDeviceFilterRequestMsg()
req._this=self.handle
req._name=_arg_name
val=self.mgr.getPort().IHost_createUSBDeviceFilter(req)
return IHostUSBDeviceFilter(self.mgr,val._returnval)
def insertUSBDeviceFilter(self, _arg_position, _arg_filter):
req=IHost_insertUSBDeviceFilterRequestMsg()
req._this=self.handle
req._position=_arg_position
req._filter=_arg_filter
val=self.mgr.getPort().IHost_insertUSBDeviceFilter(req)
return
def removeUSBDeviceFilter(self, _arg_position):
req=IHost_removeUSBDeviceFilterRequestMsg()
req._this=self.handle
req._position=_arg_position
val=self.mgr.getPort().IHost_removeUSBDeviceFilter(req)
return
def findHostDVDDrive(self, _arg_name):
req=IHost_findHostDVDDriveRequestMsg()
req._this=self.handle
req._name=_arg_name
val=self.mgr.getPort().IHost_findHostDVDDrive(req)
return IMedium(self.mgr,val._returnval)
def findHostFloppyDrive(self, _arg_name):
req=IHost_findHostFloppyDriveRequestMsg()
req._this=self.handle
req._name=_arg_name
val=self.mgr.getPort().IHost_findHostFloppyDrive(req)
return IMedium(self.mgr,val._returnval)
def findHostNetworkInterfaceByName(self, _arg_name):
req=IHost_findHostNetworkInterfaceByNameRequestMsg()
req._this=self.handle
req._name=_arg_name
val=self.mgr.getPort().IHost_findHostNetworkInterfaceByName(req)
return IHostNetworkInterface(self.mgr,val._returnval)
def findHostNetworkInterfaceById(self, _arg_id):
req=IHost_findHostNetworkInterfaceByIdRequestMsg()
req._this=self.handle
req._id=_arg_id
val=self.mgr.getPort().IHost_findHostNetworkInterfaceById(req)
return IHostNetworkInterface(self.mgr,val._returnval)
def findHostNetworkInterfacesOfType(self, _arg_type):
req=IHost_findHostNetworkInterfacesOfTypeRequestMsg()
req._this=self.handle
req._type=_arg_type
val=self.mgr.getPort().IHost_findHostNetworkInterfacesOfType(req)
return IHostNetworkInterface(self.mgr,val._returnval, True)
def findUSBDeviceById(self, _arg_id):
req=IHost_findUSBDeviceByIdRequestMsg()
req._this=self.handle
req._id=_arg_id
val=self.mgr.getPort().IHost_findUSBDeviceById(req)
return IHostUSBDevice(self.mgr,val._returnval)
def findUSBDeviceByAddress(self, _arg_name):
req=IHost_findUSBDeviceByAddressRequestMsg()
req._this=self.handle
req._name=_arg_name
val=self.mgr.getPort().IHost_findUSBDeviceByAddress(req)
return IHostUSBDevice(self.mgr,val._returnval)
def getDVDDrives(self):
req=IHost_getDVDDrivesRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IHost_getDVDDrives(req)
return IMedium(self.mgr,val._returnval, True)
def getFloppyDrives(self):
req=IHost_getFloppyDrivesRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IHost_getFloppyDrives(req)
return IMedium(self.mgr,val._returnval, True)
def getUSBDevices(self):
req=IHost_getUSBDevicesRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IHost_getUSBDevices(req)
return IHostUSBDevice(self.mgr,val._returnval, True)
def getUSBDeviceFilters(self):
req=IHost_getUSBDeviceFiltersRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IHost_getUSBDeviceFilters(req)
return IHostUSBDeviceFilter(self.mgr,val._returnval, True)
def getNetworkInterfaces(self):
req=IHost_getNetworkInterfacesRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IHost_getNetworkInterfaces(req)
return IHostNetworkInterface(self.mgr,val._returnval, True)
def getProcessorCount(self):
req=IHost_getProcessorCountRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IHost_getProcessorCount(req)
return UnsignedInt(self.mgr,val._returnval)
def getProcessorOnlineCount(self):
req=IHost_getProcessorOnlineCountRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IHost_getProcessorOnlineCount(req)
return UnsignedInt(self.mgr,val._returnval)
def getProcessorCoreCount(self):
req=IHost_getProcessorCoreCountRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IHost_getProcessorCoreCount(req)
return UnsignedInt(self.mgr,val._returnval)
def getMemorySize(self):
req=IHost_getMemorySizeRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IHost_getMemorySize(req)
return UnsignedInt(self.mgr,val._returnval)
def getMemoryAvailable(self):
req=IHost_getMemoryAvailableRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IHost_getMemoryAvailable(req)
return UnsignedInt(self.mgr,val._returnval)
def getOperatingSystem(self):
req=IHost_getOperatingSystemRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IHost_getOperatingSystem(req)
return String(self.mgr,val._returnval)
def getOSVersion(self):
req=IHost_getOSVersionRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IHost_getOSVersion(req)
return String(self.mgr,val._returnval)
def getUTCTime(self):
req=IHost_getUTCTimeRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IHost_getUTCTime(req)
return Long(self.mgr,val._returnval)
def getAcceleration3DAvailable(self):
req=IHost_getAcceleration3DAvailableRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IHost_getAcceleration3DAvailable(req)
return Boolean(self.mgr,val._returnval)
_Attrs_={ 'DVDDrives':[getDVDDrives,None],
'floppyDrives':[getFloppyDrives,None],
'USBDevices':[getUSBDevices,None],
'USBDeviceFilters':[getUSBDeviceFilters,None],
'networkInterfaces':[getNetworkInterfaces,None],
'processorCount':[getProcessorCount,None],
'processorOnlineCount':[getProcessorOnlineCount,None],
'processorCoreCount':[getProcessorCoreCount,None],
'memorySize':[getMemorySize,None],
'memoryAvailable':[getMemoryAvailable,None],
'operatingSystem':[getOperatingSystem,None],
'OSVersion':[getOSVersion,None],
'UTCTime':[getUTCTime,None],
'Acceleration3DAvailable':[getAcceleration3DAvailable,None]}
class ISystemProperties(IUnknown):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return ISystemProperties(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = ISystemProperties._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IUnknown.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = ISystemProperties._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def getMaxDevicesPerPortForStorageBus(self, _arg_bus):
req=ISystemProperties_getMaxDevicesPerPortForStorageBusRequestMsg()
req._this=self.handle
req._bus=_arg_bus
val=self.mgr.getPort().ISystemProperties_getMaxDevicesPerPortForStorageBus(req)
return UnsignedInt(self.mgr,val._returnval)
def getMinPortCountForStorageBus(self, _arg_bus):
req=ISystemProperties_getMinPortCountForStorageBusRequestMsg()
req._this=self.handle
req._bus=_arg_bus
val=self.mgr.getPort().ISystemProperties_getMinPortCountForStorageBus(req)
return UnsignedInt(self.mgr,val._returnval)
def getMaxPortCountForStorageBus(self, _arg_bus):
req=ISystemProperties_getMaxPortCountForStorageBusRequestMsg()
req._this=self.handle
req._bus=_arg_bus
val=self.mgr.getPort().ISystemProperties_getMaxPortCountForStorageBus(req)
return UnsignedInt(self.mgr,val._returnval)
def getMaxInstancesOfStorageBus(self, _arg_bus):
req=ISystemProperties_getMaxInstancesOfStorageBusRequestMsg()
req._this=self.handle
req._bus=_arg_bus
val=self.mgr.getPort().ISystemProperties_getMaxInstancesOfStorageBus(req)
return UnsignedInt(self.mgr,val._returnval)
def getDeviceTypesForStorageBus(self, _arg_bus):
req=ISystemProperties_getDeviceTypesForStorageBusRequestMsg()
req._this=self.handle
req._bus=_arg_bus
val=self.mgr.getPort().ISystemProperties_getDeviceTypesForStorageBus(req)
return DeviceType(self.mgr,val._returnval, True)
def getDefaultIoCacheSettingForStorageController(self, _arg_controllerType):
req=ISystemProperties_getDefaultIoCacheSettingForStorageControllerRequestMsg()
req._this=self.handle
req._controllerType=_arg_controllerType
val=self.mgr.getPort().ISystemProperties_getDefaultIoCacheSettingForStorageController(req)
return Boolean(self.mgr,val._returnval)
def getMinGuestRAM(self):
req=ISystemProperties_getMinGuestRAMRequestMsg()
req._this=self.handle
val=self.mgr.getPort().ISystemProperties_getMinGuestRAM(req)
return UnsignedInt(self.mgr,val._returnval)
def getMaxGuestRAM(self):
req=ISystemProperties_getMaxGuestRAMRequestMsg()
req._this=self.handle
val=self.mgr.getPort().ISystemProperties_getMaxGuestRAM(req)
return UnsignedInt(self.mgr,val._returnval)
def getMinGuestVRAM(self):
req=ISystemProperties_getMinGuestVRAMRequestMsg()
req._this=self.handle
val=self.mgr.getPort().ISystemProperties_getMinGuestVRAM(req)
return UnsignedInt(self.mgr,val._returnval)
def getMaxGuestVRAM(self):
req=ISystemProperties_getMaxGuestVRAMRequestMsg()
req._this=self.handle
val=self.mgr.getPort().ISystemProperties_getMaxGuestVRAM(req)
return UnsignedInt(self.mgr,val._returnval)
def getMinGuestCPUCount(self):
req=ISystemProperties_getMinGuestCPUCountRequestMsg()
req._this=self.handle
val=self.mgr.getPort().ISystemProperties_getMinGuestCPUCount(req)
return UnsignedInt(self.mgr,val._returnval)
def getMaxGuestCPUCount(self):
req=ISystemProperties_getMaxGuestCPUCountRequestMsg()
req._this=self.handle
val=self.mgr.getPort().ISystemProperties_getMaxGuestCPUCount(req)
return UnsignedInt(self.mgr,val._returnval)
def getMaxGuestMonitors(self):
req=ISystemProperties_getMaxGuestMonitorsRequestMsg()
req._this=self.handle
val=self.mgr.getPort().ISystemProperties_getMaxGuestMonitors(req)
return UnsignedInt(self.mgr,val._returnval)
def getInfoVDSize(self):
req=ISystemProperties_getInfoVDSizeRequestMsg()
req._this=self.handle
val=self.mgr.getPort().ISystemProperties_getInfoVDSize(req)
return Long(self.mgr,val._returnval)
def getNetworkAdapterCount(self):
req=ISystemProperties_getNetworkAdapterCountRequestMsg()
req._this=self.handle
val=self.mgr.getPort().ISystemProperties_getNetworkAdapterCount(req)
return UnsignedInt(self.mgr,val._returnval)
def getSerialPortCount(self):
req=ISystemProperties_getSerialPortCountRequestMsg()
req._this=self.handle
val=self.mgr.getPort().ISystemProperties_getSerialPortCount(req)
return UnsignedInt(self.mgr,val._returnval)
def getParallelPortCount(self):
req=ISystemProperties_getParallelPortCountRequestMsg()
req._this=self.handle
val=self.mgr.getPort().ISystemProperties_getParallelPortCount(req)
return UnsignedInt(self.mgr,val._returnval)
def getMaxBootPosition(self):
req=ISystemProperties_getMaxBootPositionRequestMsg()
req._this=self.handle
val=self.mgr.getPort().ISystemProperties_getMaxBootPosition(req)
return UnsignedInt(self.mgr,val._returnval)
def getDefaultMachineFolder(self):
req=ISystemProperties_getDefaultMachineFolderRequestMsg()
req._this=self.handle
val=self.mgr.getPort().ISystemProperties_getDefaultMachineFolder(req)
return String(self.mgr,val._returnval)
def setDefaultMachineFolder(self, value):
req=ISystemProperties_setDefaultMachineFolderRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._defaultMachineFolder = value
else:
req._defaultMachineFolder = value.handle
self.mgr.getPort().ISystemProperties_setDefaultMachineFolder(req)
def getMediumFormats(self):
req=ISystemProperties_getMediumFormatsRequestMsg()
req._this=self.handle
val=self.mgr.getPort().ISystemProperties_getMediumFormats(req)
return IMediumFormat(self.mgr,val._returnval, True)
def getDefaultHardDiskFormat(self):
req=ISystemProperties_getDefaultHardDiskFormatRequestMsg()
req._this=self.handle
val=self.mgr.getPort().ISystemProperties_getDefaultHardDiskFormat(req)
return String(self.mgr,val._returnval)
def setDefaultHardDiskFormat(self, value):
req=ISystemProperties_setDefaultHardDiskFormatRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._defaultHardDiskFormat = value
else:
req._defaultHardDiskFormat = value.handle
self.mgr.getPort().ISystemProperties_setDefaultHardDiskFormat(req)
def getFreeDiskSpaceWarning(self):
req=ISystemProperties_getFreeDiskSpaceWarningRequestMsg()
req._this=self.handle
val=self.mgr.getPort().ISystemProperties_getFreeDiskSpaceWarning(req)
return Long(self.mgr,val._returnval)
def setFreeDiskSpaceWarning(self, value):
req=ISystemProperties_setFreeDiskSpaceWarningRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._freeDiskSpaceWarning = value
else:
req._freeDiskSpaceWarning = value.handle
self.mgr.getPort().ISystemProperties_setFreeDiskSpaceWarning(req)
def getFreeDiskSpacePercentWarning(self):
req=ISystemProperties_getFreeDiskSpacePercentWarningRequestMsg()
req._this=self.handle
val=self.mgr.getPort().ISystemProperties_getFreeDiskSpacePercentWarning(req)
return UnsignedInt(self.mgr,val._returnval)
def setFreeDiskSpacePercentWarning(self, value):
req=ISystemProperties_setFreeDiskSpacePercentWarningRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._freeDiskSpacePercentWarning = value
else:
req._freeDiskSpacePercentWarning = value.handle
self.mgr.getPort().ISystemProperties_setFreeDiskSpacePercentWarning(req)
def getFreeDiskSpaceError(self):
req=ISystemProperties_getFreeDiskSpaceErrorRequestMsg()
req._this=self.handle
val=self.mgr.getPort().ISystemProperties_getFreeDiskSpaceError(req)
return Long(self.mgr,val._returnval)
def setFreeDiskSpaceError(self, value):
req=ISystemProperties_setFreeDiskSpaceErrorRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._freeDiskSpaceError = value
else:
req._freeDiskSpaceError = value.handle
self.mgr.getPort().ISystemProperties_setFreeDiskSpaceError(req)
def getFreeDiskSpacePercentError(self):
req=ISystemProperties_getFreeDiskSpacePercentErrorRequestMsg()
req._this=self.handle
val=self.mgr.getPort().ISystemProperties_getFreeDiskSpacePercentError(req)
return UnsignedInt(self.mgr,val._returnval)
def setFreeDiskSpacePercentError(self, value):
req=ISystemProperties_setFreeDiskSpacePercentErrorRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._freeDiskSpacePercentError = value
else:
req._freeDiskSpacePercentError = value.handle
self.mgr.getPort().ISystemProperties_setFreeDiskSpacePercentError(req)
def getVRDEAuthLibrary(self):
req=ISystemProperties_getVRDEAuthLibraryRequestMsg()
req._this=self.handle
val=self.mgr.getPort().ISystemProperties_getVRDEAuthLibrary(req)
return String(self.mgr,val._returnval)
def setVRDEAuthLibrary(self, value):
req=ISystemProperties_setVRDEAuthLibraryRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._VRDEAuthLibrary = value
else:
req._VRDEAuthLibrary = value.handle
self.mgr.getPort().ISystemProperties_setVRDEAuthLibrary(req)
def getWebServiceAuthLibrary(self):
req=ISystemProperties_getWebServiceAuthLibraryRequestMsg()
req._this=self.handle
val=self.mgr.getPort().ISystemProperties_getWebServiceAuthLibrary(req)
return String(self.mgr,val._returnval)
def setWebServiceAuthLibrary(self, value):
req=ISystemProperties_setWebServiceAuthLibraryRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._webServiceAuthLibrary = value
else:
req._webServiceAuthLibrary = value.handle
self.mgr.getPort().ISystemProperties_setWebServiceAuthLibrary(req)
def getDefaultVRDELibrary(self):
req=ISystemProperties_getDefaultVRDELibraryRequestMsg()
req._this=self.handle
val=self.mgr.getPort().ISystemProperties_getDefaultVRDELibrary(req)
return String(self.mgr,val._returnval)
def setDefaultVRDELibrary(self, value):
req=ISystemProperties_setDefaultVRDELibraryRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._defaultVRDELibrary = value
else:
req._defaultVRDELibrary = value.handle
self.mgr.getPort().ISystemProperties_setDefaultVRDELibrary(req)
def getLogHistoryCount(self):
req=ISystemProperties_getLogHistoryCountRequestMsg()
req._this=self.handle
val=self.mgr.getPort().ISystemProperties_getLogHistoryCount(req)
return UnsignedInt(self.mgr,val._returnval)
def setLogHistoryCount(self, value):
req=ISystemProperties_setLogHistoryCountRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._LogHistoryCount = value
else:
req._LogHistoryCount = value.handle
self.mgr.getPort().ISystemProperties_setLogHistoryCount(req)
def getDefaultAudioDriver(self):
req=ISystemProperties_getDefaultAudioDriverRequestMsg()
req._this=self.handle
val=self.mgr.getPort().ISystemProperties_getDefaultAudioDriver(req)
return AudioDriverType(self.mgr,val._returnval)
_Attrs_={ 'minGuestRAM':[getMinGuestRAM,None],
'maxGuestRAM':[getMaxGuestRAM,None],
'minGuestVRAM':[getMinGuestVRAM,None],
'maxGuestVRAM':[getMaxGuestVRAM,None],
'minGuestCPUCount':[getMinGuestCPUCount,None],
'maxGuestCPUCount':[getMaxGuestCPUCount,None],
'maxGuestMonitors':[getMaxGuestMonitors,None],
'infoVDSize':[getInfoVDSize,None],
'networkAdapterCount':[getNetworkAdapterCount,None],
'serialPortCount':[getSerialPortCount,None],
'parallelPortCount':[getParallelPortCount,None],
'maxBootPosition':[getMaxBootPosition,None],
'defaultMachineFolder':[getDefaultMachineFolder,setDefaultMachineFolder,
],
'mediumFormats':[getMediumFormats,None],
'defaultHardDiskFormat':[getDefaultHardDiskFormat,setDefaultHardDiskFormat,
],
'freeDiskSpaceWarning':[getFreeDiskSpaceWarning,setFreeDiskSpaceWarning,
],
'freeDiskSpacePercentWarning':[getFreeDiskSpacePercentWarning,setFreeDiskSpacePercentWarning,
],
'freeDiskSpaceError':[getFreeDiskSpaceError,setFreeDiskSpaceError,
],
'freeDiskSpacePercentError':[getFreeDiskSpacePercentError,setFreeDiskSpacePercentError,
],
'VRDEAuthLibrary':[getVRDEAuthLibrary,setVRDEAuthLibrary,
],
'webServiceAuthLibrary':[getWebServiceAuthLibrary,setWebServiceAuthLibrary,
],
'defaultVRDELibrary':[getDefaultVRDELibrary,setDefaultVRDELibrary,
],
'LogHistoryCount':[getLogHistoryCount,setLogHistoryCount,
],
'defaultAudioDriver':[getDefaultAudioDriver,None]}
class IGuest(IUnknown):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IGuest(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IGuest._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IUnknown.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IGuest._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def internalGetStatistics(self):
req=IGuest_internalGetStatisticsRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IGuest_internalGetStatistics(req)
return UnsignedInt(self.mgr,val._cpuUser), UnsignedInt(self.mgr,val._cpuKernel), UnsignedInt(self.mgr,val._cpuIdle), UnsignedInt(self.mgr,val._memTotal), UnsignedInt(self.mgr,val._memFree), UnsignedInt(self.mgr,val._memBalloon), UnsignedInt(self.mgr,val._memShared), UnsignedInt(self.mgr,val._memCache), UnsignedInt(self.mgr,val._pagedTotal), UnsignedInt(self.mgr,val._memAllocTotal), UnsignedInt(self.mgr,val._memFreeTotal), UnsignedInt(self.mgr,val._memBalloonTotal), UnsignedInt(self.mgr,val._memSharedTotal)
def getAdditionsStatus(self, _arg_level):
req=IGuest_getAdditionsStatusRequestMsg()
req._this=self.handle
req._level=_arg_level
val=self.mgr.getPort().IGuest_getAdditionsStatus(req)
return Boolean(self.mgr,val._returnval)
def setCredentials(self, _arg_userName, _arg_password, _arg_domain, _arg_allowInteractiveLogon):
req=IGuest_setCredentialsRequestMsg()
req._this=self.handle
req._userName=_arg_userName
req._password=_arg_password
req._domain=_arg_domain
req._allowInteractiveLogon=_arg_allowInteractiveLogon
val=self.mgr.getPort().IGuest_setCredentials(req)
return
def executeProcess(self, _arg_execName, _arg_flags, _arg_arguments, _arg_environment, _arg_userName, _arg_password, _arg_timeoutMS):
req=IGuest_executeProcessRequestMsg()
req._this=self.handle
req._execName=_arg_execName
req._flags=_arg_flags
req._arguments=_arg_arguments
req._environment=_arg_environment
req._userName=_arg_userName
req._password=_arg_password
req._timeoutMS=_arg_timeoutMS
val=self.mgr.getPort().IGuest_executeProcess(req)
return IProgress(self.mgr,val._returnval), UnsignedInt(self.mgr,val._pid)
def getProcessOutput(self, _arg_pid, _arg_flags, _arg_timeoutMS, _arg_size):
req=IGuest_getProcessOutputRequestMsg()
req._this=self.handle
req._pid=_arg_pid
req._flags=_arg_flags
req._timeoutMS=_arg_timeoutMS
req._size=_arg_size
val=self.mgr.getPort().IGuest_getProcessOutput(req)
return Octet(self.mgr,val._returnval, True)
def getProcessStatus(self, _arg_pid):
req=IGuest_getProcessStatusRequestMsg()
req._this=self.handle
req._pid=_arg_pid
val=self.mgr.getPort().IGuest_getProcessStatus(req)
return UnsignedInt(self.mgr,val._returnval), UnsignedInt(self.mgr,val._exitcode), UnsignedInt(self.mgr,val._flags)
def copyToGuest(self, _arg_source, _arg_dest, _arg_userName, _arg_password, _arg_flags):
req=IGuest_copyToGuestRequestMsg()
req._this=self.handle
req._source=_arg_source
req._dest=_arg_dest
req._userName=_arg_userName
req._password=_arg_password
req._flags=_arg_flags
val=self.mgr.getPort().IGuest_copyToGuest(req)
return IProgress(self.mgr,val._returnval)
def setProcessInput(self, _arg_pid, _arg_flags, _arg_data):
req=IGuest_setProcessInputRequestMsg()
req._this=self.handle
req._pid=_arg_pid
req._flags=_arg_flags
req._data=_arg_data
val=self.mgr.getPort().IGuest_setProcessInput(req)
return UnsignedInt(self.mgr,val._returnval)
def getOSTypeId(self):
req=IGuest_getOSTypeIdRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IGuest_getOSTypeId(req)
return String(self.mgr,val._returnval)
def getAdditionsRunLevel(self):
req=IGuest_getAdditionsRunLevelRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IGuest_getAdditionsRunLevel(req)
return AdditionsRunLevelType(self.mgr,val._returnval)
def getAdditionsVersion(self):
req=IGuest_getAdditionsVersionRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IGuest_getAdditionsVersion(req)
return String(self.mgr,val._returnval)
def getSupportsSeamless(self):
req=IGuest_getSupportsSeamlessRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IGuest_getSupportsSeamless(req)
return Boolean(self.mgr,val._returnval)
def getSupportsGraphics(self):
req=IGuest_getSupportsGraphicsRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IGuest_getSupportsGraphics(req)
return Boolean(self.mgr,val._returnval)
def getMemoryBalloonSize(self):
req=IGuest_getMemoryBalloonSizeRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IGuest_getMemoryBalloonSize(req)
return UnsignedInt(self.mgr,val._returnval)
def setMemoryBalloonSize(self, value):
req=IGuest_setMemoryBalloonSizeRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._memoryBalloonSize = value
else:
req._memoryBalloonSize = value.handle
self.mgr.getPort().IGuest_setMemoryBalloonSize(req)
def getStatisticsUpdateInterval(self):
req=IGuest_getStatisticsUpdateIntervalRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IGuest_getStatisticsUpdateInterval(req)
return UnsignedInt(self.mgr,val._returnval)
def setStatisticsUpdateInterval(self, value):
req=IGuest_setStatisticsUpdateIntervalRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._statisticsUpdateInterval = value
else:
req._statisticsUpdateInterval = value.handle
self.mgr.getPort().IGuest_setStatisticsUpdateInterval(req)
_Attrs_={ 'OSTypeId':[getOSTypeId,None],
'additionsRunLevel':[getAdditionsRunLevel,None],
'additionsVersion':[getAdditionsVersion,None],
'supportsSeamless':[getSupportsSeamless,None],
'supportsGraphics':[getSupportsGraphics,None],
'memoryBalloonSize':[getMemoryBalloonSize,setMemoryBalloonSize,
],
'statisticsUpdateInterval':[getStatisticsUpdateInterval,setStatisticsUpdateInterval,
]}
class IProgress(IUnknown):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IProgress(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IProgress._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IUnknown.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IProgress._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def setCurrentOperationProgress(self, _arg_percent):
req=IProgress_setCurrentOperationProgressRequestMsg()
req._this=self.handle
req._percent=_arg_percent
val=self.mgr.getPort().IProgress_setCurrentOperationProgress(req)
return
def setNextOperation(self, _arg_nextOperationDescription, _arg_nextOperationsWeight):
req=IProgress_setNextOperationRequestMsg()
req._this=self.handle
req._nextOperationDescription=_arg_nextOperationDescription
req._nextOperationsWeight=_arg_nextOperationsWeight
val=self.mgr.getPort().IProgress_setNextOperation(req)
return
def waitForCompletion(self, _arg_timeout):
req=IProgress_waitForCompletionRequestMsg()
req._this=self.handle
req._timeout=_arg_timeout
val=self.mgr.getPort().IProgress_waitForCompletion(req)
return
def waitForOperationCompletion(self, _arg_operation, _arg_timeout):
req=IProgress_waitForOperationCompletionRequestMsg()
req._this=self.handle
req._operation=_arg_operation
req._timeout=_arg_timeout
val=self.mgr.getPort().IProgress_waitForOperationCompletion(req)
return
def cancel(self):
req=IProgress_cancelRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IProgress_cancel(req)
return
def getId(self):
req=IProgress_getIdRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IProgress_getId(req)
return String(self.mgr,val._returnval)
def getDescription(self):
req=IProgress_getDescriptionRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IProgress_getDescription(req)
return String(self.mgr,val._returnval)
def getInitiator(self):
req=IProgress_getInitiatorRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IProgress_getInitiator(req)
return IUnknown(self.mgr,val._returnval)
def getCancelable(self):
req=IProgress_getCancelableRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IProgress_getCancelable(req)
return Boolean(self.mgr,val._returnval)
def getPercent(self):
req=IProgress_getPercentRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IProgress_getPercent(req)
return UnsignedInt(self.mgr,val._returnval)
def getTimeRemaining(self):
req=IProgress_getTimeRemainingRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IProgress_getTimeRemaining(req)
return Int(self.mgr,val._returnval)
def getCompleted(self):
req=IProgress_getCompletedRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IProgress_getCompleted(req)
return Boolean(self.mgr,val._returnval)
def getCanceled(self):
req=IProgress_getCanceledRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IProgress_getCanceled(req)
return Boolean(self.mgr,val._returnval)
def getResultCode(self):
req=IProgress_getResultCodeRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IProgress_getResultCode(req)
return Int(self.mgr,val._returnval)
def getErrorInfo(self):
req=IProgress_getErrorInfoRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IProgress_getErrorInfo(req)
return IVirtualBoxErrorInfo(self.mgr,val._returnval)
def getOperationCount(self):
req=IProgress_getOperationCountRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IProgress_getOperationCount(req)
return UnsignedInt(self.mgr,val._returnval)
def getOperation(self):
req=IProgress_getOperationRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IProgress_getOperation(req)
return UnsignedInt(self.mgr,val._returnval)
def getOperationDescription(self):
req=IProgress_getOperationDescriptionRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IProgress_getOperationDescription(req)
return String(self.mgr,val._returnval)
def getOperationPercent(self):
req=IProgress_getOperationPercentRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IProgress_getOperationPercent(req)
return UnsignedInt(self.mgr,val._returnval)
def getOperationWeight(self):
req=IProgress_getOperationWeightRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IProgress_getOperationWeight(req)
return UnsignedInt(self.mgr,val._returnval)
def getTimeout(self):
req=IProgress_getTimeoutRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IProgress_getTimeout(req)
return UnsignedInt(self.mgr,val._returnval)
def setTimeout(self, value):
req=IProgress_setTimeoutRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._timeout = value
else:
req._timeout = value.handle
self.mgr.getPort().IProgress_setTimeout(req)
_Attrs_={ 'id':[getId,None],
'description':[getDescription,None],
'initiator':[getInitiator,None],
'cancelable':[getCancelable,None],
'percent':[getPercent,None],
'timeRemaining':[getTimeRemaining,None],
'completed':[getCompleted,None],
'canceled':[getCanceled,None],
'resultCode':[getResultCode,None],
'errorInfo':[getErrorInfo,None],
'operationCount':[getOperationCount,None],
'operation':[getOperation,None],
'operationDescription':[getOperationDescription,None],
'operationPercent':[getOperationPercent,None],
'operationWeight':[getOperationWeight,None],
'timeout':[getTimeout,setTimeout,
]}
class ISnapshot(IUnknown):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return ISnapshot(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = ISnapshot._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IUnknown.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = ISnapshot._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def getId(self):
req=ISnapshot_getIdRequestMsg()
req._this=self.handle
val=self.mgr.getPort().ISnapshot_getId(req)
return String(self.mgr,val._returnval)
def getName(self):
req=ISnapshot_getNameRequestMsg()
req._this=self.handle
val=self.mgr.getPort().ISnapshot_getName(req)
return String(self.mgr,val._returnval)
def setName(self, value):
req=ISnapshot_setNameRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._name = value
else:
req._name = value.handle
self.mgr.getPort().ISnapshot_setName(req)
def getDescription(self):
req=ISnapshot_getDescriptionRequestMsg()
req._this=self.handle
val=self.mgr.getPort().ISnapshot_getDescription(req)
return String(self.mgr,val._returnval)
def setDescription(self, value):
req=ISnapshot_setDescriptionRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._description = value
else:
req._description = value.handle
self.mgr.getPort().ISnapshot_setDescription(req)
def getTimeStamp(self):
req=ISnapshot_getTimeStampRequestMsg()
req._this=self.handle
val=self.mgr.getPort().ISnapshot_getTimeStamp(req)
return Long(self.mgr,val._returnval)
def getOnline(self):
req=ISnapshot_getOnlineRequestMsg()
req._this=self.handle
val=self.mgr.getPort().ISnapshot_getOnline(req)
return Boolean(self.mgr,val._returnval)
def getMachine(self):
req=ISnapshot_getMachineRequestMsg()
req._this=self.handle
val=self.mgr.getPort().ISnapshot_getMachine(req)
return IMachine(self.mgr,val._returnval)
def getParent(self):
req=ISnapshot_getParentRequestMsg()
req._this=self.handle
val=self.mgr.getPort().ISnapshot_getParent(req)
return ISnapshot(self.mgr,val._returnval)
def getChildren(self):
req=ISnapshot_getChildrenRequestMsg()
req._this=self.handle
val=self.mgr.getPort().ISnapshot_getChildren(req)
return ISnapshot(self.mgr,val._returnval, True)
_Attrs_={ 'id':[getId,None],
'name':[getName,setName,
],
'description':[getDescription,setDescription,
],
'timeStamp':[getTimeStamp,None],
'online':[getOnline,None],
'machine':[getMachine,None],
'parent':[getParent,None],
'children':[getChildren,None]}
class IMedium(IUnknown):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IMedium(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IMedium._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IUnknown.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IMedium._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def setIDs(self, _arg_setImageId, _arg_imageId, _arg_setParentId, _arg_parentId):
req=IMedium_setIDsRequestMsg()
req._this=self.handle
req._setImageId=_arg_setImageId
req._imageId=_arg_imageId
req._setParentId=_arg_setParentId
req._parentId=_arg_parentId
val=self.mgr.getPort().IMedium_setIDs(req)
return
def refreshState(self):
req=IMedium_refreshStateRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMedium_refreshState(req)
return MediumState(self.mgr,val._returnval)
def getSnapshotIds(self, _arg_machineId):
req=IMedium_getSnapshotIdsRequestMsg()
req._this=self.handle
req._machineId=_arg_machineId
val=self.mgr.getPort().IMedium_getSnapshotIds(req)
return String(self.mgr,val._returnval, True)
def lockRead(self):
req=IMedium_lockReadRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMedium_lockRead(req)
return MediumState(self.mgr,val._returnval)
def unlockRead(self):
req=IMedium_unlockReadRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMedium_unlockRead(req)
return MediumState(self.mgr,val._returnval)
def lockWrite(self):
req=IMedium_lockWriteRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMedium_lockWrite(req)
return MediumState(self.mgr,val._returnval)
def unlockWrite(self):
req=IMedium_unlockWriteRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMedium_unlockWrite(req)
return MediumState(self.mgr,val._returnval)
def close(self):
req=IMedium_closeRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMedium_close(req)
return
def getProperty(self, _arg_name):
req=IMedium_getPropertyRequestMsg()
req._this=self.handle
req._name=_arg_name
val=self.mgr.getPort().IMedium_getProperty(req)
return String(self.mgr,val._returnval)
def setProperty(self, _arg_name, _arg_value):
req=IMedium_setPropertyRequestMsg()
req._this=self.handle
req._name=_arg_name
req._value=_arg_value
val=self.mgr.getPort().IMedium_setProperty(req)
return
def getProperties(self, _arg_names):
req=IMedium_getPropertiesRequestMsg()
req._this=self.handle
req._names=_arg_names
val=self.mgr.getPort().IMedium_getProperties(req)
return String(self.mgr,val._returnval, True), String(self.mgr,val._returnNames, True)
def setProperties(self, _arg_names, _arg_values):
req=IMedium_setPropertiesRequestMsg()
req._this=self.handle
req._names=_arg_names
req._values=_arg_values
val=self.mgr.getPort().IMedium_setProperties(req)
return
def createBaseStorage(self, _arg_logicalSize, _arg_variant):
req=IMedium_createBaseStorageRequestMsg()
req._this=self.handle
req._logicalSize=_arg_logicalSize
req._variant=_arg_variant
val=self.mgr.getPort().IMedium_createBaseStorage(req)
return IProgress(self.mgr,val._returnval)
def deleteStorage(self):
req=IMedium_deleteStorageRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMedium_deleteStorage(req)
return IProgress(self.mgr,val._returnval)
def createDiffStorage(self, _arg_target, _arg_variant):
req=IMedium_createDiffStorageRequestMsg()
req._this=self.handle
req._target=_arg_target
req._variant=_arg_variant
val=self.mgr.getPort().IMedium_createDiffStorage(req)
return IProgress(self.mgr,val._returnval)
def mergeTo(self, _arg_target):
req=IMedium_mergeToRequestMsg()
req._this=self.handle
req._target=_arg_target
val=self.mgr.getPort().IMedium_mergeTo(req)
return IProgress(self.mgr,val._returnval)
def cloneTo(self, _arg_target, _arg_variant, _arg_parent):
req=IMedium_cloneToRequestMsg()
req._this=self.handle
req._target=_arg_target
req._variant=_arg_variant
req._parent=_arg_parent
val=self.mgr.getPort().IMedium_cloneTo(req)
return IProgress(self.mgr,val._returnval)
def compact(self):
req=IMedium_compactRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMedium_compact(req)
return IProgress(self.mgr,val._returnval)
def resize(self, _arg_logicalSize):
req=IMedium_resizeRequestMsg()
req._this=self.handle
req._logicalSize=_arg_logicalSize
val=self.mgr.getPort().IMedium_resize(req)
return IProgress(self.mgr,val._returnval)
def reset(self):
req=IMedium_resetRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMedium_reset(req)
return IProgress(self.mgr,val._returnval)
def getId(self):
req=IMedium_getIdRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMedium_getId(req)
return String(self.mgr,val._returnval)
def getDescription(self):
req=IMedium_getDescriptionRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMedium_getDescription(req)
return String(self.mgr,val._returnval)
def setDescription(self, value):
req=IMedium_setDescriptionRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._description = value
else:
req._description = value.handle
self.mgr.getPort().IMedium_setDescription(req)
def getState(self):
req=IMedium_getStateRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMedium_getState(req)
return MediumState(self.mgr,val._returnval)
def getVariant(self):
req=IMedium_getVariantRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMedium_getVariant(req)
return MediumVariant(self.mgr,val._returnval)
def getLocation(self):
req=IMedium_getLocationRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMedium_getLocation(req)
return String(self.mgr,val._returnval)
def setLocation(self, value):
req=IMedium_setLocationRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._location = value
else:
req._location = value.handle
self.mgr.getPort().IMedium_setLocation(req)
def getName(self):
req=IMedium_getNameRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMedium_getName(req)
return String(self.mgr,val._returnval)
def getDeviceType(self):
req=IMedium_getDeviceTypeRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMedium_getDeviceType(req)
return DeviceType(self.mgr,val._returnval)
def getHostDrive(self):
req=IMedium_getHostDriveRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMedium_getHostDrive(req)
return Boolean(self.mgr,val._returnval)
def getSize(self):
req=IMedium_getSizeRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMedium_getSize(req)
return Long(self.mgr,val._returnval)
def getFormat(self):
req=IMedium_getFormatRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMedium_getFormat(req)
return String(self.mgr,val._returnval)
def getMediumFormat(self):
req=IMedium_getMediumFormatRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMedium_getMediumFormat(req)
return IMediumFormat(self.mgr,val._returnval)
def getType(self):
req=IMedium_getTypeRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMedium_getType(req)
return MediumType(self.mgr,val._returnval)
def setType(self, value):
req=IMedium_setTypeRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._type = value
else:
req._type = value.handle
self.mgr.getPort().IMedium_setType(req)
def getParent(self):
req=IMedium_getParentRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMedium_getParent(req)
return IMedium(self.mgr,val._returnval)
def getChildren(self):
req=IMedium_getChildrenRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMedium_getChildren(req)
return IMedium(self.mgr,val._returnval, True)
def getBase(self):
req=IMedium_getBaseRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMedium_getBase(req)
return IMedium(self.mgr,val._returnval)
def getReadOnly(self):
req=IMedium_getReadOnlyRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMedium_getReadOnly(req)
return Boolean(self.mgr,val._returnval)
def getLogicalSize(self):
req=IMedium_getLogicalSizeRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMedium_getLogicalSize(req)
return Long(self.mgr,val._returnval)
def getAutoReset(self):
req=IMedium_getAutoResetRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMedium_getAutoReset(req)
return Boolean(self.mgr,val._returnval)
def setAutoReset(self, value):
req=IMedium_setAutoResetRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._autoReset = value
else:
req._autoReset = value.handle
self.mgr.getPort().IMedium_setAutoReset(req)
def getLastAccessError(self):
req=IMedium_getLastAccessErrorRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMedium_getLastAccessError(req)
return String(self.mgr,val._returnval)
def getMachineIds(self):
req=IMedium_getMachineIdsRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMedium_getMachineIds(req)
return String(self.mgr,val._returnval, True)
_Attrs_={ 'id':[getId,None],
'description':[getDescription,setDescription,
],
'state':[getState,None],
'variant':[getVariant,None],
'location':[getLocation,setLocation,
],
'name':[getName,None],
'deviceType':[getDeviceType,None],
'hostDrive':[getHostDrive,None],
'size':[getSize,None],
'format':[getFormat,None],
'mediumFormat':[getMediumFormat,None],
'type':[getType,setType,
],
'parent':[getParent,None],
'children':[getChildren,None],
'base':[getBase,None],
'readOnly':[getReadOnly,None],
'logicalSize':[getLogicalSize,None],
'autoReset':[getAutoReset,setAutoReset,
],
'lastAccessError':[getLastAccessError,None],
'machineIds':[getMachineIds,None]}
class IMediumFormat(IUnknown):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IMediumFormat(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IMediumFormat._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IUnknown.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IMediumFormat._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def describeProperties(self):
req=IMediumFormat_describePropertiesRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMediumFormat_describeProperties(req)
return String(self.mgr,val._names, True), String(self.mgr,val._description, True), DataType(self.mgr,val._types, True), UnsignedInt(self.mgr,val._flags, True), String(self.mgr,val._defaults, True)
def getId(self):
req=IMediumFormat_getIdRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMediumFormat_getId(req)
return String(self.mgr,val._returnval)
def getName(self):
req=IMediumFormat_getNameRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMediumFormat_getName(req)
return String(self.mgr,val._returnval)
def getFileExtensions(self):
req=IMediumFormat_getFileExtensionsRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMediumFormat_getFileExtensions(req)
return String(self.mgr,val._returnval, True)
def getCapabilities(self):
req=IMediumFormat_getCapabilitiesRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMediumFormat_getCapabilities(req)
return UnsignedInt(self.mgr,val._returnval)
_Attrs_={ 'id':[getId,None],
'name':[getName,None],
'fileExtensions':[getFileExtensions,None],
'capabilities':[getCapabilities,None]}
class IKeyboard(IUnknown):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IKeyboard(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IKeyboard._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IUnknown.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IKeyboard._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def putScancode(self, _arg_scancode):
req=IKeyboard_putScancodeRequestMsg()
req._this=self.handle
req._scancode=_arg_scancode
val=self.mgr.getPort().IKeyboard_putScancode(req)
return
def putScancodes(self, _arg_scancodes):
req=IKeyboard_putScancodesRequestMsg()
req._this=self.handle
req._scancodes=_arg_scancodes
val=self.mgr.getPort().IKeyboard_putScancodes(req)
return UnsignedInt(self.mgr,val._returnval)
def putCAD(self):
req=IKeyboard_putCADRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IKeyboard_putCAD(req)
return
def getEventSource(self):
req=IKeyboard_getEventSourceRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IKeyboard_getEventSource(req)
return IEventSource(self.mgr,val._returnval)
_Attrs_={ 'eventSource':[getEventSource,None]}
class IMouse(IUnknown):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IMouse(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IMouse._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IUnknown.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IMouse._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def putMouseEvent(self, _arg_dx, _arg_dy, _arg_dz, _arg_dw, _arg_buttonState):
req=IMouse_putMouseEventRequestMsg()
req._this=self.handle
req._dx=_arg_dx
req._dy=_arg_dy
req._dz=_arg_dz
req._dw=_arg_dw
req._buttonState=_arg_buttonState
val=self.mgr.getPort().IMouse_putMouseEvent(req)
return
def putMouseEventAbsolute(self, _arg_x, _arg_y, _arg_dz, _arg_dw, _arg_buttonState):
req=IMouse_putMouseEventAbsoluteRequestMsg()
req._this=self.handle
req._x=_arg_x
req._y=_arg_y
req._dz=_arg_dz
req._dw=_arg_dw
req._buttonState=_arg_buttonState
val=self.mgr.getPort().IMouse_putMouseEventAbsolute(req)
return
def getAbsoluteSupported(self):
req=IMouse_getAbsoluteSupportedRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMouse_getAbsoluteSupported(req)
return Boolean(self.mgr,val._returnval)
def getRelativeSupported(self):
req=IMouse_getRelativeSupportedRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMouse_getRelativeSupported(req)
return Boolean(self.mgr,val._returnval)
def getNeedsHostCursor(self):
req=IMouse_getNeedsHostCursorRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMouse_getNeedsHostCursor(req)
return Boolean(self.mgr,val._returnval)
def getEventSource(self):
req=IMouse_getEventSourceRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMouse_getEventSource(req)
return IEventSource(self.mgr,val._returnval)
_Attrs_={ 'absoluteSupported':[getAbsoluteSupported,None],
'relativeSupported':[getRelativeSupported,None],
'needsHostCursor':[getNeedsHostCursor,None],
'eventSource':[getEventSource,None]}
class IDisplay(IUnknown):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IDisplay(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IDisplay._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IUnknown.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IDisplay._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def getScreenResolution(self, _arg_screenId):
req=IDisplay_getScreenResolutionRequestMsg()
req._this=self.handle
req._screenId=_arg_screenId
val=self.mgr.getPort().IDisplay_getScreenResolution(req)
return UnsignedInt(self.mgr,val._width), UnsignedInt(self.mgr,val._height), UnsignedInt(self.mgr,val._bitsPerPixel)
def setFramebuffer(self, _arg_screenId, _arg_framebuffer):
req=IDisplay_setFramebufferRequestMsg()
req._this=self.handle
req._screenId=_arg_screenId
req._framebuffer=_arg_framebuffer
val=self.mgr.getPort().IDisplay_setFramebuffer(req)
return
def getFramebuffer(self, _arg_screenId):
req=IDisplay_getFramebufferRequestMsg()
req._this=self.handle
req._screenId=_arg_screenId
val=self.mgr.getPort().IDisplay_getFramebuffer(req)
return IFramebuffer(self.mgr,val._framebuffer), Int(self.mgr,val._xOrigin), Int(self.mgr,val._yOrigin)
def setVideoModeHint(self, _arg_width, _arg_height, _arg_bitsPerPixel, _arg_display):
req=IDisplay_setVideoModeHintRequestMsg()
req._this=self.handle
req._width=_arg_width
req._height=_arg_height
req._bitsPerPixel=_arg_bitsPerPixel
req._display=_arg_display
val=self.mgr.getPort().IDisplay_setVideoModeHint(req)
return
def setSeamlessMode(self, _arg_enabled):
req=IDisplay_setSeamlessModeRequestMsg()
req._this=self.handle
req._enabled=_arg_enabled
val=self.mgr.getPort().IDisplay_setSeamlessMode(req)
return
def takeScreenShot(self, _arg_screenId, _arg_address, _arg_width, _arg_height):
req=IDisplay_takeScreenShotRequestMsg()
req._this=self.handle
req._screenId=_arg_screenId
req._address=_arg_address
req._width=_arg_width
req._height=_arg_height
val=self.mgr.getPort().IDisplay_takeScreenShot(req)
return
def takeScreenShotToArray(self, _arg_screenId, _arg_width, _arg_height):
req=IDisplay_takeScreenShotToArrayRequestMsg()
req._this=self.handle
req._screenId=_arg_screenId
req._width=_arg_width
req._height=_arg_height
val=self.mgr.getPort().IDisplay_takeScreenShotToArray(req)
return Octet(self.mgr,val._returnval, True)
def takeScreenShotPNGToArray(self, _arg_screenId, _arg_width, _arg_height):
req=IDisplay_takeScreenShotPNGToArrayRequestMsg()
req._this=self.handle
req._screenId=_arg_screenId
req._width=_arg_width
req._height=_arg_height
val=self.mgr.getPort().IDisplay_takeScreenShotPNGToArray(req)
return Octet(self.mgr,val._returnval, True)
def drawToScreen(self, _arg_screenId, _arg_address, _arg_x, _arg_y, _arg_width, _arg_height):
req=IDisplay_drawToScreenRequestMsg()
req._this=self.handle
req._screenId=_arg_screenId
req._address=_arg_address
req._x=_arg_x
req._y=_arg_y
req._width=_arg_width
req._height=_arg_height
val=self.mgr.getPort().IDisplay_drawToScreen(req)
return
def invalidateAndUpdate(self):
req=IDisplay_invalidateAndUpdateRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IDisplay_invalidateAndUpdate(req)
return
def resizeCompleted(self, _arg_screenId):
req=IDisplay_resizeCompletedRequestMsg()
req._this=self.handle
req._screenId=_arg_screenId
val=self.mgr.getPort().IDisplay_resizeCompleted(req)
return
def completeVHWACommand(self, _arg_command):
req=IDisplay_completeVHWACommandRequestMsg()
req._this=self.handle
req._command=_arg_command
val=self.mgr.getPort().IDisplay_completeVHWACommand(req)
return
_Attrs_={}
class INetworkAdapter(IUnknown):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return INetworkAdapter(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = INetworkAdapter._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IUnknown.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = INetworkAdapter._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def attachToNAT(self):
req=INetworkAdapter_attachToNATRequestMsg()
req._this=self.handle
val=self.mgr.getPort().INetworkAdapter_attachToNAT(req)
return
def attachToBridgedInterface(self):
req=INetworkAdapter_attachToBridgedInterfaceRequestMsg()
req._this=self.handle
val=self.mgr.getPort().INetworkAdapter_attachToBridgedInterface(req)
return
def attachToInternalNetwork(self):
req=INetworkAdapter_attachToInternalNetworkRequestMsg()
req._this=self.handle
val=self.mgr.getPort().INetworkAdapter_attachToInternalNetwork(req)
return
def attachToHostOnlyInterface(self):
req=INetworkAdapter_attachToHostOnlyInterfaceRequestMsg()
req._this=self.handle
val=self.mgr.getPort().INetworkAdapter_attachToHostOnlyInterface(req)
return
def attachToVDE(self):
req=INetworkAdapter_attachToVDERequestMsg()
req._this=self.handle
val=self.mgr.getPort().INetworkAdapter_attachToVDE(req)
return
def detach(self):
req=INetworkAdapter_detachRequestMsg()
req._this=self.handle
val=self.mgr.getPort().INetworkAdapter_detach(req)
return
def getAdapterType(self):
req=INetworkAdapter_getAdapterTypeRequestMsg()
req._this=self.handle
val=self.mgr.getPort().INetworkAdapter_getAdapterType(req)
return NetworkAdapterType(self.mgr,val._returnval)
def setAdapterType(self, value):
req=INetworkAdapter_setAdapterTypeRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._adapterType = value
else:
req._adapterType = value.handle
self.mgr.getPort().INetworkAdapter_setAdapterType(req)
def getSlot(self):
req=INetworkAdapter_getSlotRequestMsg()
req._this=self.handle
val=self.mgr.getPort().INetworkAdapter_getSlot(req)
return UnsignedInt(self.mgr,val._returnval)
def getEnabled(self):
req=INetworkAdapter_getEnabledRequestMsg()
req._this=self.handle
val=self.mgr.getPort().INetworkAdapter_getEnabled(req)
return Boolean(self.mgr,val._returnval)
def setEnabled(self, value):
req=INetworkAdapter_setEnabledRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._enabled = value
else:
req._enabled = value.handle
self.mgr.getPort().INetworkAdapter_setEnabled(req)
def getMACAddress(self):
req=INetworkAdapter_getMACAddressRequestMsg()
req._this=self.handle
val=self.mgr.getPort().INetworkAdapter_getMACAddress(req)
return String(self.mgr,val._returnval)
def setMACAddress(self, value):
req=INetworkAdapter_setMACAddressRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._MACAddress = value
else:
req._MACAddress = value.handle
self.mgr.getPort().INetworkAdapter_setMACAddress(req)
def getAttachmentType(self):
req=INetworkAdapter_getAttachmentTypeRequestMsg()
req._this=self.handle
val=self.mgr.getPort().INetworkAdapter_getAttachmentType(req)
return NetworkAttachmentType(self.mgr,val._returnval)
def getHostInterface(self):
req=INetworkAdapter_getHostInterfaceRequestMsg()
req._this=self.handle
val=self.mgr.getPort().INetworkAdapter_getHostInterface(req)
return String(self.mgr,val._returnval)
def setHostInterface(self, value):
req=INetworkAdapter_setHostInterfaceRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._hostInterface = value
else:
req._hostInterface = value.handle
self.mgr.getPort().INetworkAdapter_setHostInterface(req)
def getInternalNetwork(self):
req=INetworkAdapter_getInternalNetworkRequestMsg()
req._this=self.handle
val=self.mgr.getPort().INetworkAdapter_getInternalNetwork(req)
return String(self.mgr,val._returnval)
def setInternalNetwork(self, value):
req=INetworkAdapter_setInternalNetworkRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._internalNetwork = value
else:
req._internalNetwork = value.handle
self.mgr.getPort().INetworkAdapter_setInternalNetwork(req)
def getNATNetwork(self):
req=INetworkAdapter_getNATNetworkRequestMsg()
req._this=self.handle
val=self.mgr.getPort().INetworkAdapter_getNATNetwork(req)
return String(self.mgr,val._returnval)
def setNATNetwork(self, value):
req=INetworkAdapter_setNATNetworkRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._NATNetwork = value
else:
req._NATNetwork = value.handle
self.mgr.getPort().INetworkAdapter_setNATNetwork(req)
def getVDENetwork(self):
req=INetworkAdapter_getVDENetworkRequestMsg()
req._this=self.handle
val=self.mgr.getPort().INetworkAdapter_getVDENetwork(req)
return String(self.mgr,val._returnval)
def setVDENetwork(self, value):
req=INetworkAdapter_setVDENetworkRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._VDENetwork = value
else:
req._VDENetwork = value.handle
self.mgr.getPort().INetworkAdapter_setVDENetwork(req)
def getCableConnected(self):
req=INetworkAdapter_getCableConnectedRequestMsg()
req._this=self.handle
val=self.mgr.getPort().INetworkAdapter_getCableConnected(req)
return Boolean(self.mgr,val._returnval)
def setCableConnected(self, value):
req=INetworkAdapter_setCableConnectedRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._cableConnected = value
else:
req._cableConnected = value.handle
self.mgr.getPort().INetworkAdapter_setCableConnected(req)
def getLineSpeed(self):
req=INetworkAdapter_getLineSpeedRequestMsg()
req._this=self.handle
val=self.mgr.getPort().INetworkAdapter_getLineSpeed(req)
return UnsignedInt(self.mgr,val._returnval)
def setLineSpeed(self, value):
req=INetworkAdapter_setLineSpeedRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._lineSpeed = value
else:
req._lineSpeed = value.handle
self.mgr.getPort().INetworkAdapter_setLineSpeed(req)
def getTraceEnabled(self):
req=INetworkAdapter_getTraceEnabledRequestMsg()
req._this=self.handle
val=self.mgr.getPort().INetworkAdapter_getTraceEnabled(req)
return Boolean(self.mgr,val._returnval)
def setTraceEnabled(self, value):
req=INetworkAdapter_setTraceEnabledRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._traceEnabled = value
else:
req._traceEnabled = value.handle
self.mgr.getPort().INetworkAdapter_setTraceEnabled(req)
def getTraceFile(self):
req=INetworkAdapter_getTraceFileRequestMsg()
req._this=self.handle
val=self.mgr.getPort().INetworkAdapter_getTraceFile(req)
return String(self.mgr,val._returnval)
def setTraceFile(self, value):
req=INetworkAdapter_setTraceFileRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._traceFile = value
else:
req._traceFile = value.handle
self.mgr.getPort().INetworkAdapter_setTraceFile(req)
def getNatDriver(self):
req=INetworkAdapter_getNatDriverRequestMsg()
req._this=self.handle
val=self.mgr.getPort().INetworkAdapter_getNatDriver(req)
return INATEngine(self.mgr,val._returnval)
def getBootPriority(self):
req=INetworkAdapter_getBootPriorityRequestMsg()
req._this=self.handle
val=self.mgr.getPort().INetworkAdapter_getBootPriority(req)
return UnsignedInt(self.mgr,val._returnval)
def setBootPriority(self, value):
req=INetworkAdapter_setBootPriorityRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._bootPriority = value
else:
req._bootPriority = value.handle
self.mgr.getPort().INetworkAdapter_setBootPriority(req)
def getBandwidthLimit(self):
req=INetworkAdapter_getBandwidthLimitRequestMsg()
req._this=self.handle
val=self.mgr.getPort().INetworkAdapter_getBandwidthLimit(req)
return UnsignedInt(self.mgr,val._returnval)
def setBandwidthLimit(self, value):
req=INetworkAdapter_setBandwidthLimitRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._bandwidthLimit = value
else:
req._bandwidthLimit = value.handle
self.mgr.getPort().INetworkAdapter_setBandwidthLimit(req)
_Attrs_={ 'adapterType':[getAdapterType,setAdapterType,
],
'slot':[getSlot,None],
'enabled':[getEnabled,setEnabled,
],
'MACAddress':[getMACAddress,setMACAddress,
],
'attachmentType':[getAttachmentType,None],
'hostInterface':[getHostInterface,setHostInterface,
],
'internalNetwork':[getInternalNetwork,setInternalNetwork,
],
'NATNetwork':[getNATNetwork,setNATNetwork,
],
'VDENetwork':[getVDENetwork,setVDENetwork,
],
'cableConnected':[getCableConnected,setCableConnected,
],
'lineSpeed':[getLineSpeed,setLineSpeed,
],
'traceEnabled':[getTraceEnabled,setTraceEnabled,
],
'traceFile':[getTraceFile,setTraceFile,
],
'natDriver':[getNatDriver,None],
'bootPriority':[getBootPriority,setBootPriority,
],
'bandwidthLimit':[getBandwidthLimit,setBandwidthLimit,
]}
class ISerialPort(IUnknown):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return ISerialPort(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = ISerialPort._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IUnknown.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = ISerialPort._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def getSlot(self):
req=ISerialPort_getSlotRequestMsg()
req._this=self.handle
val=self.mgr.getPort().ISerialPort_getSlot(req)
return UnsignedInt(self.mgr,val._returnval)
def getEnabled(self):
req=ISerialPort_getEnabledRequestMsg()
req._this=self.handle
val=self.mgr.getPort().ISerialPort_getEnabled(req)
return Boolean(self.mgr,val._returnval)
def setEnabled(self, value):
req=ISerialPort_setEnabledRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._enabled = value
else:
req._enabled = value.handle
self.mgr.getPort().ISerialPort_setEnabled(req)
def getIOBase(self):
req=ISerialPort_getIOBaseRequestMsg()
req._this=self.handle
val=self.mgr.getPort().ISerialPort_getIOBase(req)
return UnsignedInt(self.mgr,val._returnval)
def setIOBase(self, value):
req=ISerialPort_setIOBaseRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._IOBase = value
else:
req._IOBase = value.handle
self.mgr.getPort().ISerialPort_setIOBase(req)
def getIRQ(self):
req=ISerialPort_getIRQRequestMsg()
req._this=self.handle
val=self.mgr.getPort().ISerialPort_getIRQ(req)
return UnsignedInt(self.mgr,val._returnval)
def setIRQ(self, value):
req=ISerialPort_setIRQRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._IRQ = value
else:
req._IRQ = value.handle
self.mgr.getPort().ISerialPort_setIRQ(req)
def getHostMode(self):
req=ISerialPort_getHostModeRequestMsg()
req._this=self.handle
val=self.mgr.getPort().ISerialPort_getHostMode(req)
return PortMode(self.mgr,val._returnval)
def setHostMode(self, value):
req=ISerialPort_setHostModeRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._hostMode = value
else:
req._hostMode = value.handle
self.mgr.getPort().ISerialPort_setHostMode(req)
def getServer(self):
req=ISerialPort_getServerRequestMsg()
req._this=self.handle
val=self.mgr.getPort().ISerialPort_getServer(req)
return Boolean(self.mgr,val._returnval)
def setServer(self, value):
req=ISerialPort_setServerRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._server = value
else:
req._server = value.handle
self.mgr.getPort().ISerialPort_setServer(req)
def getPath(self):
req=ISerialPort_getPathRequestMsg()
req._this=self.handle
val=self.mgr.getPort().ISerialPort_getPath(req)
return String(self.mgr,val._returnval)
def setPath(self, value):
req=ISerialPort_setPathRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._path = value
else:
req._path = value.handle
self.mgr.getPort().ISerialPort_setPath(req)
_Attrs_={ 'slot':[getSlot,None],
'enabled':[getEnabled,setEnabled,
],
'IOBase':[getIOBase,setIOBase,
],
'IRQ':[getIRQ,setIRQ,
],
'hostMode':[getHostMode,setHostMode,
],
'server':[getServer,setServer,
],
'path':[getPath,setPath,
]}
class IParallelPort(IUnknown):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IParallelPort(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IParallelPort._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IUnknown.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IParallelPort._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def getSlot(self):
req=IParallelPort_getSlotRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IParallelPort_getSlot(req)
return UnsignedInt(self.mgr,val._returnval)
def getEnabled(self):
req=IParallelPort_getEnabledRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IParallelPort_getEnabled(req)
return Boolean(self.mgr,val._returnval)
def setEnabled(self, value):
req=IParallelPort_setEnabledRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._enabled = value
else:
req._enabled = value.handle
self.mgr.getPort().IParallelPort_setEnabled(req)
def getIOBase(self):
req=IParallelPort_getIOBaseRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IParallelPort_getIOBase(req)
return UnsignedInt(self.mgr,val._returnval)
def setIOBase(self, value):
req=IParallelPort_setIOBaseRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._IOBase = value
else:
req._IOBase = value.handle
self.mgr.getPort().IParallelPort_setIOBase(req)
def getIRQ(self):
req=IParallelPort_getIRQRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IParallelPort_getIRQ(req)
return UnsignedInt(self.mgr,val._returnval)
def setIRQ(self, value):
req=IParallelPort_setIRQRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._IRQ = value
else:
req._IRQ = value.handle
self.mgr.getPort().IParallelPort_setIRQ(req)
def getPath(self):
req=IParallelPort_getPathRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IParallelPort_getPath(req)
return String(self.mgr,val._returnval)
def setPath(self, value):
req=IParallelPort_setPathRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._path = value
else:
req._path = value.handle
self.mgr.getPort().IParallelPort_setPath(req)
_Attrs_={ 'slot':[getSlot,None],
'enabled':[getEnabled,setEnabled,
],
'IOBase':[getIOBase,setIOBase,
],
'IRQ':[getIRQ,setIRQ,
],
'path':[getPath,setPath,
]}
class IUSBController(IUnknown):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IUSBController(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IUSBController._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IUnknown.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IUSBController._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def createDeviceFilter(self, _arg_name):
req=IUSBController_createDeviceFilterRequestMsg()
req._this=self.handle
req._name=_arg_name
val=self.mgr.getPort().IUSBController_createDeviceFilter(req)
return IUSBDeviceFilter(self.mgr,val._returnval)
def insertDeviceFilter(self, _arg_position, _arg_filter):
req=IUSBController_insertDeviceFilterRequestMsg()
req._this=self.handle
req._position=_arg_position
req._filter=_arg_filter
val=self.mgr.getPort().IUSBController_insertDeviceFilter(req)
return
def removeDeviceFilter(self, _arg_position):
req=IUSBController_removeDeviceFilterRequestMsg()
req._this=self.handle
req._position=_arg_position
val=self.mgr.getPort().IUSBController_removeDeviceFilter(req)
return IUSBDeviceFilter(self.mgr,val._returnval)
def getEnabled(self):
req=IUSBController_getEnabledRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IUSBController_getEnabled(req)
return Boolean(self.mgr,val._returnval)
def setEnabled(self, value):
req=IUSBController_setEnabledRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._enabled = value
else:
req._enabled = value.handle
self.mgr.getPort().IUSBController_setEnabled(req)
def getEnabledEhci(self):
req=IUSBController_getEnabledEhciRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IUSBController_getEnabledEhci(req)
return Boolean(self.mgr,val._returnval)
def setEnabledEhci(self, value):
req=IUSBController_setEnabledEhciRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._enabledEhci = value
else:
req._enabledEhci = value.handle
self.mgr.getPort().IUSBController_setEnabledEhci(req)
def getProxyAvailable(self):
req=IUSBController_getProxyAvailableRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IUSBController_getProxyAvailable(req)
return Boolean(self.mgr,val._returnval)
def getUSBStandard(self):
req=IUSBController_getUSBStandardRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IUSBController_getUSBStandard(req)
return UnsignedShort(self.mgr,val._returnval)
def getDeviceFilters(self):
req=IUSBController_getDeviceFiltersRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IUSBController_getDeviceFilters(req)
return IUSBDeviceFilter(self.mgr,val._returnval, True)
_Attrs_={ 'enabled':[getEnabled,setEnabled,
],
'enabledEhci':[getEnabledEhci,setEnabledEhci,
],
'proxyAvailable':[getProxyAvailable,None],
'USBStandard':[getUSBStandard,None],
'deviceFilters':[getDeviceFilters,None]}
class IUSBDevice(IUnknown):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IUSBDevice(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IUSBDevice._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IUnknown.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IUSBDevice._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def getId(self):
req=IUSBDevice_getIdRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IUSBDevice_getId(req)
return String(self.mgr,val._returnval)
def getVendorId(self):
req=IUSBDevice_getVendorIdRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IUSBDevice_getVendorId(req)
return UnsignedShort(self.mgr,val._returnval)
def getProductId(self):
req=IUSBDevice_getProductIdRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IUSBDevice_getProductId(req)
return UnsignedShort(self.mgr,val._returnval)
def getRevision(self):
req=IUSBDevice_getRevisionRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IUSBDevice_getRevision(req)
return UnsignedShort(self.mgr,val._returnval)
def getManufacturer(self):
req=IUSBDevice_getManufacturerRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IUSBDevice_getManufacturer(req)
return String(self.mgr,val._returnval)
def getProduct(self):
req=IUSBDevice_getProductRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IUSBDevice_getProduct(req)
return String(self.mgr,val._returnval)
def getSerialNumber(self):
req=IUSBDevice_getSerialNumberRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IUSBDevice_getSerialNumber(req)
return String(self.mgr,val._returnval)
def getAddress(self):
req=IUSBDevice_getAddressRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IUSBDevice_getAddress(req)
return String(self.mgr,val._returnval)
def getPort(self):
req=IUSBDevice_getPortRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IUSBDevice_getPort(req)
return UnsignedShort(self.mgr,val._returnval)
def getVersion(self):
req=IUSBDevice_getVersionRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IUSBDevice_getVersion(req)
return UnsignedShort(self.mgr,val._returnval)
def getPortVersion(self):
req=IUSBDevice_getPortVersionRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IUSBDevice_getPortVersion(req)
return UnsignedShort(self.mgr,val._returnval)
def getRemote(self):
req=IUSBDevice_getRemoteRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IUSBDevice_getRemote(req)
return Boolean(self.mgr,val._returnval)
_Attrs_={ 'id':[getId,None],
'vendorId':[getVendorId,None],
'productId':[getProductId,None],
'revision':[getRevision,None],
'manufacturer':[getManufacturer,None],
'product':[getProduct,None],
'serialNumber':[getSerialNumber,None],
'address':[getAddress,None],
'port':[getPort,None],
'version':[getVersion,None],
'portVersion':[getPortVersion,None],
'remote':[getRemote,None]}
class IUSBDeviceFilter(IUnknown):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IUSBDeviceFilter(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IUSBDeviceFilter._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IUnknown.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IUSBDeviceFilter._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def getName(self):
req=IUSBDeviceFilter_getNameRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IUSBDeviceFilter_getName(req)
return String(self.mgr,val._returnval)
def setName(self, value):
req=IUSBDeviceFilter_setNameRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._name = value
else:
req._name = value.handle
self.mgr.getPort().IUSBDeviceFilter_setName(req)
def getActive(self):
req=IUSBDeviceFilter_getActiveRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IUSBDeviceFilter_getActive(req)
return Boolean(self.mgr,val._returnval)
def setActive(self, value):
req=IUSBDeviceFilter_setActiveRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._active = value
else:
req._active = value.handle
self.mgr.getPort().IUSBDeviceFilter_setActive(req)
def getVendorId(self):
req=IUSBDeviceFilter_getVendorIdRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IUSBDeviceFilter_getVendorId(req)
return String(self.mgr,val._returnval)
def setVendorId(self, value):
req=IUSBDeviceFilter_setVendorIdRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._vendorId = value
else:
req._vendorId = value.handle
self.mgr.getPort().IUSBDeviceFilter_setVendorId(req)
def getProductId(self):
req=IUSBDeviceFilter_getProductIdRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IUSBDeviceFilter_getProductId(req)
return String(self.mgr,val._returnval)
def setProductId(self, value):
req=IUSBDeviceFilter_setProductIdRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._productId = value
else:
req._productId = value.handle
self.mgr.getPort().IUSBDeviceFilter_setProductId(req)
def getRevision(self):
req=IUSBDeviceFilter_getRevisionRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IUSBDeviceFilter_getRevision(req)
return String(self.mgr,val._returnval)
def setRevision(self, value):
req=IUSBDeviceFilter_setRevisionRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._revision = value
else:
req._revision = value.handle
self.mgr.getPort().IUSBDeviceFilter_setRevision(req)
def getManufacturer(self):
req=IUSBDeviceFilter_getManufacturerRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IUSBDeviceFilter_getManufacturer(req)
return String(self.mgr,val._returnval)
def setManufacturer(self, value):
req=IUSBDeviceFilter_setManufacturerRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._manufacturer = value
else:
req._manufacturer = value.handle
self.mgr.getPort().IUSBDeviceFilter_setManufacturer(req)
def getProduct(self):
req=IUSBDeviceFilter_getProductRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IUSBDeviceFilter_getProduct(req)
return String(self.mgr,val._returnval)
def setProduct(self, value):
req=IUSBDeviceFilter_setProductRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._product = value
else:
req._product = value.handle
self.mgr.getPort().IUSBDeviceFilter_setProduct(req)
def getSerialNumber(self):
req=IUSBDeviceFilter_getSerialNumberRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IUSBDeviceFilter_getSerialNumber(req)
return String(self.mgr,val._returnval)
def setSerialNumber(self, value):
req=IUSBDeviceFilter_setSerialNumberRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._serialNumber = value
else:
req._serialNumber = value.handle
self.mgr.getPort().IUSBDeviceFilter_setSerialNumber(req)
def getPort(self):
req=IUSBDeviceFilter_getPortRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IUSBDeviceFilter_getPort(req)
return String(self.mgr,val._returnval)
def setPort(self, value):
req=IUSBDeviceFilter_setPortRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._port = value
else:
req._port = value.handle
self.mgr.getPort().IUSBDeviceFilter_setPort(req)
def getRemote(self):
req=IUSBDeviceFilter_getRemoteRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IUSBDeviceFilter_getRemote(req)
return String(self.mgr,val._returnval)
def setRemote(self, value):
req=IUSBDeviceFilter_setRemoteRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._remote = value
else:
req._remote = value.handle
self.mgr.getPort().IUSBDeviceFilter_setRemote(req)
def getMaskedInterfaces(self):
req=IUSBDeviceFilter_getMaskedInterfacesRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IUSBDeviceFilter_getMaskedInterfaces(req)
return UnsignedInt(self.mgr,val._returnval)
def setMaskedInterfaces(self, value):
req=IUSBDeviceFilter_setMaskedInterfacesRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._maskedInterfaces = value
else:
req._maskedInterfaces = value.handle
self.mgr.getPort().IUSBDeviceFilter_setMaskedInterfaces(req)
_Attrs_={ 'name':[getName,setName,
],
'active':[getActive,setActive,
],
'vendorId':[getVendorId,setVendorId,
],
'productId':[getProductId,setProductId,
],
'revision':[getRevision,setRevision,
],
'manufacturer':[getManufacturer,setManufacturer,
],
'product':[getProduct,setProduct,
],
'serialNumber':[getSerialNumber,setSerialNumber,
],
'port':[getPort,setPort,
],
'remote':[getRemote,setRemote,
],
'maskedInterfaces':[getMaskedInterfaces,setMaskedInterfaces,
]}
class IHostUSBDevice(IUSBDevice):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IHostUSBDevice(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IHostUSBDevice._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IUSBDevice.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IHostUSBDevice._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def getState(self):
req=IHostUSBDevice_getStateRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IHostUSBDevice_getState(req)
return USBDeviceState(self.mgr,val._returnval)
_Attrs_={ 'state':[getState,None]}
class IHostUSBDeviceFilter(IUSBDeviceFilter):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IHostUSBDeviceFilter(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IHostUSBDeviceFilter._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IUSBDeviceFilter.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IHostUSBDeviceFilter._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def getAction(self):
req=IHostUSBDeviceFilter_getActionRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IHostUSBDeviceFilter_getAction(req)
return USBDeviceFilterAction(self.mgr,val._returnval)
def setAction(self, value):
req=IHostUSBDeviceFilter_setActionRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._action = value
else:
req._action = value.handle
self.mgr.getPort().IHostUSBDeviceFilter_setAction(req)
_Attrs_={ 'action':[getAction,setAction,
]}
class IAudioAdapter(IUnknown):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IAudioAdapter(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IAudioAdapter._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IUnknown.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IAudioAdapter._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def getEnabled(self):
req=IAudioAdapter_getEnabledRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IAudioAdapter_getEnabled(req)
return Boolean(self.mgr,val._returnval)
def setEnabled(self, value):
req=IAudioAdapter_setEnabledRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._enabled = value
else:
req._enabled = value.handle
self.mgr.getPort().IAudioAdapter_setEnabled(req)
def getAudioController(self):
req=IAudioAdapter_getAudioControllerRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IAudioAdapter_getAudioController(req)
return AudioControllerType(self.mgr,val._returnval)
def setAudioController(self, value):
req=IAudioAdapter_setAudioControllerRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._audioController = value
else:
req._audioController = value.handle
self.mgr.getPort().IAudioAdapter_setAudioController(req)
def getAudioDriver(self):
req=IAudioAdapter_getAudioDriverRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IAudioAdapter_getAudioDriver(req)
return AudioDriverType(self.mgr,val._returnval)
def setAudioDriver(self, value):
req=IAudioAdapter_setAudioDriverRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._audioDriver = value
else:
req._audioDriver = value.handle
self.mgr.getPort().IAudioAdapter_setAudioDriver(req)
_Attrs_={ 'enabled':[getEnabled,setEnabled,
],
'audioController':[getAudioController,setAudioController,
],
'audioDriver':[getAudioDriver,setAudioDriver,
]}
class IVRDEServer(IUnknown):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IVRDEServer(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IVRDEServer._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IUnknown.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IVRDEServer._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def setVRDEProperty(self, _arg_key, _arg_value):
req=IVRDEServer_setVRDEPropertyRequestMsg()
req._this=self.handle
req._key=_arg_key
req._value=_arg_value
val=self.mgr.getPort().IVRDEServer_setVRDEProperty(req)
return
def getVRDEProperty(self, _arg_key):
req=IVRDEServer_getVRDEPropertyRequestMsg()
req._this=self.handle
req._key=_arg_key
val=self.mgr.getPort().IVRDEServer_getVRDEProperty(req)
return String(self.mgr,val._returnval)
def getEnabled(self):
req=IVRDEServer_getEnabledRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IVRDEServer_getEnabled(req)
return Boolean(self.mgr,val._returnval)
def setEnabled(self, value):
req=IVRDEServer_setEnabledRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._enabled = value
else:
req._enabled = value.handle
self.mgr.getPort().IVRDEServer_setEnabled(req)
def getAuthType(self):
req=IVRDEServer_getAuthTypeRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IVRDEServer_getAuthType(req)
return AuthType(self.mgr,val._returnval)
def setAuthType(self, value):
req=IVRDEServer_setAuthTypeRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._authType = value
else:
req._authType = value.handle
self.mgr.getPort().IVRDEServer_setAuthType(req)
def getAuthTimeout(self):
req=IVRDEServer_getAuthTimeoutRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IVRDEServer_getAuthTimeout(req)
return UnsignedInt(self.mgr,val._returnval)
def setAuthTimeout(self, value):
req=IVRDEServer_setAuthTimeoutRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._authTimeout = value
else:
req._authTimeout = value.handle
self.mgr.getPort().IVRDEServer_setAuthTimeout(req)
def getAllowMultiConnection(self):
req=IVRDEServer_getAllowMultiConnectionRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IVRDEServer_getAllowMultiConnection(req)
return Boolean(self.mgr,val._returnval)
def setAllowMultiConnection(self, value):
req=IVRDEServer_setAllowMultiConnectionRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._allowMultiConnection = value
else:
req._allowMultiConnection = value.handle
self.mgr.getPort().IVRDEServer_setAllowMultiConnection(req)
def getReuseSingleConnection(self):
req=IVRDEServer_getReuseSingleConnectionRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IVRDEServer_getReuseSingleConnection(req)
return Boolean(self.mgr,val._returnval)
def setReuseSingleConnection(self, value):
req=IVRDEServer_setReuseSingleConnectionRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._reuseSingleConnection = value
else:
req._reuseSingleConnection = value.handle
self.mgr.getPort().IVRDEServer_setReuseSingleConnection(req)
def getVideoChannel(self):
req=IVRDEServer_getVideoChannelRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IVRDEServer_getVideoChannel(req)
return Boolean(self.mgr,val._returnval)
def setVideoChannel(self, value):
req=IVRDEServer_setVideoChannelRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._videoChannel = value
else:
req._videoChannel = value.handle
self.mgr.getPort().IVRDEServer_setVideoChannel(req)
def getVideoChannelQuality(self):
req=IVRDEServer_getVideoChannelQualityRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IVRDEServer_getVideoChannelQuality(req)
return UnsignedInt(self.mgr,val._returnval)
def setVideoChannelQuality(self, value):
req=IVRDEServer_setVideoChannelQualityRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._videoChannelQuality = value
else:
req._videoChannelQuality = value.handle
self.mgr.getPort().IVRDEServer_setVideoChannelQuality(req)
_Attrs_={ 'enabled':[getEnabled,setEnabled,
],
'authType':[getAuthType,setAuthType,
],
'authTimeout':[getAuthTimeout,setAuthTimeout,
],
'allowMultiConnection':[getAllowMultiConnection,setAllowMultiConnection,
],
'reuseSingleConnection':[getReuseSingleConnection,setReuseSingleConnection,
],
'videoChannel':[getVideoChannel,setVideoChannel,
],
'videoChannelQuality':[getVideoChannelQuality,setVideoChannelQuality,
]}
class ISession(IUnknown):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return ISession(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = ISession._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IUnknown.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = ISession._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def unlockMachine(self):
req=ISession_unlockMachineRequestMsg()
req._this=self.handle
val=self.mgr.getPort().ISession_unlockMachine(req)
return
def getState(self):
req=ISession_getStateRequestMsg()
req._this=self.handle
val=self.mgr.getPort().ISession_getState(req)
return SessionState(self.mgr,val._returnval)
def getType(self):
req=ISession_getTypeRequestMsg()
req._this=self.handle
val=self.mgr.getPort().ISession_getType(req)
return SessionType(self.mgr,val._returnval)
def getMachine(self):
req=ISession_getMachineRequestMsg()
req._this=self.handle
val=self.mgr.getPort().ISession_getMachine(req)
return IMachine(self.mgr,val._returnval)
def getConsole(self):
req=ISession_getConsoleRequestMsg()
req._this=self.handle
val=self.mgr.getPort().ISession_getConsole(req)
return IConsole(self.mgr,val._returnval)
_Attrs_={ 'state':[getState,None],
'type':[getType,None],
'machine':[getMachine,None],
'console':[getConsole,None]}
class IStorageController(IUnknown):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IStorageController(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IStorageController._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IUnknown.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IStorageController._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def getIDEEmulationPort(self, _arg_devicePosition):
req=IStorageController_getIDEEmulationPortRequestMsg()
req._this=self.handle
req._devicePosition=_arg_devicePosition
val=self.mgr.getPort().IStorageController_getIDEEmulationPort(req)
return Int(self.mgr,val._returnval)
def setIDEEmulationPort(self, _arg_devicePosition, _arg_portNumber):
req=IStorageController_setIDEEmulationPortRequestMsg()
req._this=self.handle
req._devicePosition=_arg_devicePosition
req._portNumber=_arg_portNumber
val=self.mgr.getPort().IStorageController_setIDEEmulationPort(req)
return
def getName(self):
req=IStorageController_getNameRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IStorageController_getName(req)
return String(self.mgr,val._returnval)
def getMaxDevicesPerPortCount(self):
req=IStorageController_getMaxDevicesPerPortCountRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IStorageController_getMaxDevicesPerPortCount(req)
return UnsignedInt(self.mgr,val._returnval)
def getMinPortCount(self):
req=IStorageController_getMinPortCountRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IStorageController_getMinPortCount(req)
return UnsignedInt(self.mgr,val._returnval)
def getMaxPortCount(self):
req=IStorageController_getMaxPortCountRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IStorageController_getMaxPortCount(req)
return UnsignedInt(self.mgr,val._returnval)
def getInstance(self):
req=IStorageController_getInstanceRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IStorageController_getInstance(req)
return UnsignedInt(self.mgr,val._returnval)
def setInstance(self, value):
req=IStorageController_setInstanceRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._instance = value
else:
req._instance = value.handle
self.mgr.getPort().IStorageController_setInstance(req)
def getPortCount(self):
req=IStorageController_getPortCountRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IStorageController_getPortCount(req)
return UnsignedInt(self.mgr,val._returnval)
def setPortCount(self, value):
req=IStorageController_setPortCountRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._portCount = value
else:
req._portCount = value.handle
self.mgr.getPort().IStorageController_setPortCount(req)
def getBus(self):
req=IStorageController_getBusRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IStorageController_getBus(req)
return StorageBus(self.mgr,val._returnval)
def getControllerType(self):
req=IStorageController_getControllerTypeRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IStorageController_getControllerType(req)
return StorageControllerType(self.mgr,val._returnval)
def setControllerType(self, value):
req=IStorageController_setControllerTypeRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._controllerType = value
else:
req._controllerType = value.handle
self.mgr.getPort().IStorageController_setControllerType(req)
def getUseHostIOCache(self):
req=IStorageController_getUseHostIOCacheRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IStorageController_getUseHostIOCache(req)
return Boolean(self.mgr,val._returnval)
def setUseHostIOCache(self, value):
req=IStorageController_setUseHostIOCacheRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._useHostIOCache = value
else:
req._useHostIOCache = value.handle
self.mgr.getPort().IStorageController_setUseHostIOCache(req)
_Attrs_={ 'name':[getName,None],
'maxDevicesPerPortCount':[getMaxDevicesPerPortCount,None],
'minPortCount':[getMinPortCount,None],
'maxPortCount':[getMaxPortCount,None],
'instance':[getInstance,setInstance,
],
'portCount':[getPortCount,setPortCount,
],
'bus':[getBus,None],
'controllerType':[getControllerType,setControllerType,
],
'useHostIOCache':[getUseHostIOCache,setUseHostIOCache,
]}
class IManagedObjectRef(IUnknown):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IManagedObjectRef(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IManagedObjectRef._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IUnknown.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IManagedObjectRef._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def getInterfaceName(self):
req=IManagedObjectRef_getInterfaceNameRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IManagedObjectRef_getInterfaceName(req)
return String(self.mgr,val._returnval)
def release(self):
req=IManagedObjectRef_releaseRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IManagedObjectRef_release(req)
return
_Attrs_={}
class IWebsessionManager(IUnknown):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IWebsessionManager(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IWebsessionManager._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IUnknown.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IWebsessionManager._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def logon(self, _arg_username, _arg_password):
req=IWebsessionManager_logonRequestMsg()
req._this=self.handle
req._username=_arg_username
req._password=_arg_password
val=self.mgr.getPort().IWebsessionManager_logon(req)
return IVirtualBox(self.mgr,val._returnval)
def getSessionObject(self, _arg_refIVirtualBox):
req=IWebsessionManager_getSessionObjectRequestMsg()
req._this=self.handle
req._refIVirtualBox=_arg_refIVirtualBox
val=self.mgr.getPort().IWebsessionManager_getSessionObject(req)
return ISession(self.mgr,val._returnval)
def logoff(self, _arg_refIVirtualBox):
req=IWebsessionManager_logoffRequestMsg()
req._this=self.handle
req._refIVirtualBox=_arg_refIVirtualBox
val=self.mgr.getPort().IWebsessionManager_logoff(req)
return
_Attrs_={}
class IPerformanceMetric(IUnknown):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IPerformanceMetric(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IPerformanceMetric._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IUnknown.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IPerformanceMetric._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def getMetricName(self):
req=IPerformanceMetric_getMetricNameRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IPerformanceMetric_getMetricName(req)
return String(self.mgr,val._returnval)
def getObject(self):
req=IPerformanceMetric_getObjectRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IPerformanceMetric_getObject(req)
return IUnknown(self.mgr,val._returnval)
def getDescription(self):
req=IPerformanceMetric_getDescriptionRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IPerformanceMetric_getDescription(req)
return String(self.mgr,val._returnval)
def getPeriod(self):
req=IPerformanceMetric_getPeriodRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IPerformanceMetric_getPeriod(req)
return UnsignedInt(self.mgr,val._returnval)
def getCount(self):
req=IPerformanceMetric_getCountRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IPerformanceMetric_getCount(req)
return UnsignedInt(self.mgr,val._returnval)
def getUnit(self):
req=IPerformanceMetric_getUnitRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IPerformanceMetric_getUnit(req)
return String(self.mgr,val._returnval)
def getMinimumValue(self):
req=IPerformanceMetric_getMinimumValueRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IPerformanceMetric_getMinimumValue(req)
return Int(self.mgr,val._returnval)
def getMaximumValue(self):
req=IPerformanceMetric_getMaximumValueRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IPerformanceMetric_getMaximumValue(req)
return Int(self.mgr,val._returnval)
_Attrs_={ 'metricName':[getMetricName,None],
'object':[getObject,None],
'description':[getDescription,None],
'period':[getPeriod,None],
'count':[getCount,None],
'unit':[getUnit,None],
'minimumValue':[getMinimumValue,None],
'maximumValue':[getMaximumValue,None]}
class IPerformanceCollector(IUnknown):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IPerformanceCollector(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IPerformanceCollector._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IUnknown.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IPerformanceCollector._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def getMetrics(self, _arg_metricNames, _arg_objects):
req=IPerformanceCollector_getMetricsRequestMsg()
req._this=self.handle
req._metricNames=_arg_metricNames
req._objects=_arg_objects
val=self.mgr.getPort().IPerformanceCollector_getMetrics(req)
return IPerformanceMetric(self.mgr,val._returnval, True)
def setupMetrics(self, _arg_metricNames, _arg_objects, _arg_period, _arg_count):
req=IPerformanceCollector_setupMetricsRequestMsg()
req._this=self.handle
req._metricNames=_arg_metricNames
req._objects=_arg_objects
req._period=_arg_period
req._count=_arg_count
val=self.mgr.getPort().IPerformanceCollector_setupMetrics(req)
return IPerformanceMetric(self.mgr,val._returnval, True)
def enableMetrics(self, _arg_metricNames, _arg_objects):
req=IPerformanceCollector_enableMetricsRequestMsg()
req._this=self.handle
req._metricNames=_arg_metricNames
req._objects=_arg_objects
val=self.mgr.getPort().IPerformanceCollector_enableMetrics(req)
return IPerformanceMetric(self.mgr,val._returnval, True)
def disableMetrics(self, _arg_metricNames, _arg_objects):
req=IPerformanceCollector_disableMetricsRequestMsg()
req._this=self.handle
req._metricNames=_arg_metricNames
req._objects=_arg_objects
val=self.mgr.getPort().IPerformanceCollector_disableMetrics(req)
return IPerformanceMetric(self.mgr,val._returnval, True)
def queryMetricsData(self, _arg_metricNames, _arg_objects):
req=IPerformanceCollector_queryMetricsDataRequestMsg()
req._this=self.handle
req._metricNames=_arg_metricNames
req._objects=_arg_objects
val=self.mgr.getPort().IPerformanceCollector_queryMetricsData(req)
return Int(self.mgr,val._returnval, True), String(self.mgr,val._returnMetricNames, True), IUnknown(self.mgr,val._returnObjects, True), String(self.mgr,val._returnUnits, True), UnsignedInt(self.mgr,val._returnScales, True), UnsignedInt(self.mgr,val._returnSequenceNumbers, True), UnsignedInt(self.mgr,val._returnDataIndices, True), UnsignedInt(self.mgr,val._returnDataLengths, True)
def getMetricNames(self):
req=IPerformanceCollector_getMetricNamesRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IPerformanceCollector_getMetricNames(req)
return String(self.mgr,val._returnval, True)
_Attrs_={ 'metricNames':[getMetricNames,None]}
class INATEngine(IUnknown):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return INATEngine(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = INATEngine._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IUnknown.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = INATEngine._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def setNetworkSettings(self, _arg_mtu, _arg_sockSnd, _arg_sockRcv, _arg_TcpWndSnd, _arg_TcpWndRcv):
req=INATEngine_setNetworkSettingsRequestMsg()
req._this=self.handle
req._mtu=_arg_mtu
req._sockSnd=_arg_sockSnd
req._sockRcv=_arg_sockRcv
req._TcpWndSnd=_arg_TcpWndSnd
req._TcpWndRcv=_arg_TcpWndRcv
val=self.mgr.getPort().INATEngine_setNetworkSettings(req)
return
def getNetworkSettings(self):
req=INATEngine_getNetworkSettingsRequestMsg()
req._this=self.handle
val=self.mgr.getPort().INATEngine_getNetworkSettings(req)
return UnsignedInt(self.mgr,val._mtu), UnsignedInt(self.mgr,val._sockSnd), UnsignedInt(self.mgr,val._sockRcv), UnsignedInt(self.mgr,val._TcpWndSnd), UnsignedInt(self.mgr,val._TcpWndRcv)
def addRedirect(self, _arg_name, _arg_proto, _arg_hostIp, _arg_hostPort, _arg_guestIp, _arg_guestPort):
req=INATEngine_addRedirectRequestMsg()
req._this=self.handle
req._name=_arg_name
req._proto=_arg_proto
req._hostIp=_arg_hostIp
req._hostPort=_arg_hostPort
req._guestIp=_arg_guestIp
req._guestPort=_arg_guestPort
val=self.mgr.getPort().INATEngine_addRedirect(req)
return
def removeRedirect(self, _arg_name):
req=INATEngine_removeRedirectRequestMsg()
req._this=self.handle
req._name=_arg_name
val=self.mgr.getPort().INATEngine_removeRedirect(req)
return
def getNetwork(self):
req=INATEngine_getNetworkRequestMsg()
req._this=self.handle
val=self.mgr.getPort().INATEngine_getNetwork(req)
return String(self.mgr,val._returnval)
def setNetwork(self, value):
req=INATEngine_setNetworkRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._network = value
else:
req._network = value.handle
self.mgr.getPort().INATEngine_setNetwork(req)
def getHostIP(self):
req=INATEngine_getHostIPRequestMsg()
req._this=self.handle
val=self.mgr.getPort().INATEngine_getHostIP(req)
return String(self.mgr,val._returnval)
def setHostIP(self, value):
req=INATEngine_setHostIPRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._hostIP = value
else:
req._hostIP = value.handle
self.mgr.getPort().INATEngine_setHostIP(req)
def getTftpPrefix(self):
req=INATEngine_getTftpPrefixRequestMsg()
req._this=self.handle
val=self.mgr.getPort().INATEngine_getTftpPrefix(req)
return String(self.mgr,val._returnval)
def setTftpPrefix(self, value):
req=INATEngine_setTftpPrefixRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._tftpPrefix = value
else:
req._tftpPrefix = value.handle
self.mgr.getPort().INATEngine_setTftpPrefix(req)
def getTftpBootFile(self):
req=INATEngine_getTftpBootFileRequestMsg()
req._this=self.handle
val=self.mgr.getPort().INATEngine_getTftpBootFile(req)
return String(self.mgr,val._returnval)
def setTftpBootFile(self, value):
req=INATEngine_setTftpBootFileRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._tftpBootFile = value
else:
req._tftpBootFile = value.handle
self.mgr.getPort().INATEngine_setTftpBootFile(req)
def getTftpNextServer(self):
req=INATEngine_getTftpNextServerRequestMsg()
req._this=self.handle
val=self.mgr.getPort().INATEngine_getTftpNextServer(req)
return String(self.mgr,val._returnval)
def setTftpNextServer(self, value):
req=INATEngine_setTftpNextServerRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._tftpNextServer = value
else:
req._tftpNextServer = value.handle
self.mgr.getPort().INATEngine_setTftpNextServer(req)
def getAliasMode(self):
req=INATEngine_getAliasModeRequestMsg()
req._this=self.handle
val=self.mgr.getPort().INATEngine_getAliasMode(req)
return UnsignedInt(self.mgr,val._returnval)
def setAliasMode(self, value):
req=INATEngine_setAliasModeRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._aliasMode = value
else:
req._aliasMode = value.handle
self.mgr.getPort().INATEngine_setAliasMode(req)
def getDnsPassDomain(self):
req=INATEngine_getDnsPassDomainRequestMsg()
req._this=self.handle
val=self.mgr.getPort().INATEngine_getDnsPassDomain(req)
return Boolean(self.mgr,val._returnval)
def setDnsPassDomain(self, value):
req=INATEngine_setDnsPassDomainRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._dnsPassDomain = value
else:
req._dnsPassDomain = value.handle
self.mgr.getPort().INATEngine_setDnsPassDomain(req)
def getDnsProxy(self):
req=INATEngine_getDnsProxyRequestMsg()
req._this=self.handle
val=self.mgr.getPort().INATEngine_getDnsProxy(req)
return Boolean(self.mgr,val._returnval)
def setDnsProxy(self, value):
req=INATEngine_setDnsProxyRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._dnsProxy = value
else:
req._dnsProxy = value.handle
self.mgr.getPort().INATEngine_setDnsProxy(req)
def getDnsUseHostResolver(self):
req=INATEngine_getDnsUseHostResolverRequestMsg()
req._this=self.handle
val=self.mgr.getPort().INATEngine_getDnsUseHostResolver(req)
return Boolean(self.mgr,val._returnval)
def setDnsUseHostResolver(self, value):
req=INATEngine_setDnsUseHostResolverRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._dnsUseHostResolver = value
else:
req._dnsUseHostResolver = value.handle
self.mgr.getPort().INATEngine_setDnsUseHostResolver(req)
def getRedirects(self):
req=INATEngine_getRedirectsRequestMsg()
req._this=self.handle
val=self.mgr.getPort().INATEngine_getRedirects(req)
return String(self.mgr,val._returnval, True)
_Attrs_={ 'network':[getNetwork,setNetwork,
],
'hostIP':[getHostIP,setHostIP,
],
'tftpPrefix':[getTftpPrefix,setTftpPrefix,
],
'tftpBootFile':[getTftpBootFile,setTftpBootFile,
],
'tftpNextServer':[getTftpNextServer,setTftpNextServer,
],
'aliasMode':[getAliasMode,setAliasMode,
],
'dnsPassDomain':[getDnsPassDomain,setDnsPassDomain,
],
'dnsProxy':[getDnsProxy,setDnsProxy,
],
'dnsUseHostResolver':[getDnsUseHostResolver,setDnsUseHostResolver,
],
'redirects':[getRedirects,None]}
class IEventSource(IUnknown):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IEventSource(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IEventSource._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IUnknown.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IEventSource._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def createListener(self):
req=IEventSource_createListenerRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IEventSource_createListener(req)
return IEventListener(self.mgr,val._returnval)
def createAggregator(self, _arg_subordinates):
req=IEventSource_createAggregatorRequestMsg()
req._this=self.handle
req._subordinates=_arg_subordinates
val=self.mgr.getPort().IEventSource_createAggregator(req)
return IEventSource(self.mgr,val._returnval)
def registerListener(self, _arg_listener, _arg_interesting, _arg_active):
req=IEventSource_registerListenerRequestMsg()
req._this=self.handle
req._listener=_arg_listener
req._interesting=_arg_interesting
req._active=_arg_active
val=self.mgr.getPort().IEventSource_registerListener(req)
return
def unregisterListener(self, _arg_listener):
req=IEventSource_unregisterListenerRequestMsg()
req._this=self.handle
req._listener=_arg_listener
val=self.mgr.getPort().IEventSource_unregisterListener(req)
return
def fireEvent(self, _arg_event, _arg_timeout):
req=IEventSource_fireEventRequestMsg()
req._this=self.handle
req._event=_arg_event
req._timeout=_arg_timeout
val=self.mgr.getPort().IEventSource_fireEvent(req)
return Boolean(self.mgr,val._returnval)
def getEvent(self, _arg_listener, _arg_timeout):
req=IEventSource_getEventRequestMsg()
req._this=self.handle
req._listener=_arg_listener
req._timeout=_arg_timeout
val=self.mgr.getPort().IEventSource_getEvent(req)
return IEvent(self.mgr,val._returnval)
def eventProcessed(self, _arg_listener, _arg_event):
req=IEventSource_eventProcessedRequestMsg()
req._this=self.handle
req._listener=_arg_listener
req._event=_arg_event
val=self.mgr.getPort().IEventSource_eventProcessed(req)
return
_Attrs_={}
class IEventListener(IUnknown):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IEventListener(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IEventListener._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IUnknown.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IEventListener._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def handleEvent(self, _arg_event):
req=IEventListener_handleEventRequestMsg()
req._this=self.handle
req._event=_arg_event
val=self.mgr.getPort().IEventListener_handleEvent(req)
return
_Attrs_={}
class IEvent(IUnknown):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IEvent(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IEvent._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IUnknown.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IEvent._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def setProcessed(self):
req=IEvent_setProcessedRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IEvent_setProcessed(req)
return
def waitProcessed(self, _arg_timeout):
req=IEvent_waitProcessedRequestMsg()
req._this=self.handle
req._timeout=_arg_timeout
val=self.mgr.getPort().IEvent_waitProcessed(req)
return Boolean(self.mgr,val._returnval)
def getType(self):
req=IEvent_getTypeRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IEvent_getType(req)
return VBoxEventType(self.mgr,val._returnval)
def getSource(self):
req=IEvent_getSourceRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IEvent_getSource(req)
return IEventSource(self.mgr,val._returnval)
def getWaitable(self):
req=IEvent_getWaitableRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IEvent_getWaitable(req)
return Boolean(self.mgr,val._returnval)
_Attrs_={ 'type':[getType,None],
'source':[getSource,None],
'waitable':[getWaitable,None]}
class IReusableEvent(IEvent):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IReusableEvent(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IReusableEvent._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IEvent.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IReusableEvent._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def reuse(self):
req=IReusableEvent_reuseRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IReusableEvent_reuse(req)
return
def getGeneration(self):
req=IReusableEvent_getGenerationRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IReusableEvent_getGeneration(req)
return UnsignedInt(self.mgr,val._returnval)
_Attrs_={ 'generation':[getGeneration,None]}
class IMachineEvent(IEvent):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IMachineEvent(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IMachineEvent._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IEvent.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IMachineEvent._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def getMachineId(self):
req=IMachineEvent_getMachineIdRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachineEvent_getMachineId(req)
return String(self.mgr,val._returnval)
_Attrs_={ 'machineId':[getMachineId,None]}
class IMachineStateChangedEvent(IMachineEvent):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IMachineStateChangedEvent(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IMachineStateChangedEvent._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IMachineEvent.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IMachineStateChangedEvent._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def getState(self):
req=IMachineStateChangedEvent_getStateRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachineStateChangedEvent_getState(req)
return MachineState(self.mgr,val._returnval)
_Attrs_={ 'state':[getState,None]}
class IMachineDataChangedEvent(IMachineEvent):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IMachineDataChangedEvent(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IMachineDataChangedEvent._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IMachineEvent.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IMachineDataChangedEvent._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
_Attrs_={}
class IMediumRegisteredEvent(IEvent):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IMediumRegisteredEvent(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IMediumRegisteredEvent._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IEvent.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IMediumRegisteredEvent._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def getMediumId(self):
req=IMediumRegisteredEvent_getMediumIdRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMediumRegisteredEvent_getMediumId(req)
return String(self.mgr,val._returnval)
def getMediumType(self):
req=IMediumRegisteredEvent_getMediumTypeRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMediumRegisteredEvent_getMediumType(req)
return DeviceType(self.mgr,val._returnval)
def getRegistered(self):
req=IMediumRegisteredEvent_getRegisteredRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMediumRegisteredEvent_getRegistered(req)
return Boolean(self.mgr,val._returnval)
_Attrs_={ 'mediumId':[getMediumId,None],
'mediumType':[getMediumType,None],
'registered':[getRegistered,None]}
class IMachineRegisteredEvent(IMachineEvent):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IMachineRegisteredEvent(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IMachineRegisteredEvent._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IMachineEvent.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IMachineRegisteredEvent._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def getRegistered(self):
req=IMachineRegisteredEvent_getRegisteredRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMachineRegisteredEvent_getRegistered(req)
return Boolean(self.mgr,val._returnval)
_Attrs_={ 'registered':[getRegistered,None]}
class ISessionStateChangedEvent(IMachineEvent):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return ISessionStateChangedEvent(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = ISessionStateChangedEvent._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IMachineEvent.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = ISessionStateChangedEvent._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def getState(self):
req=ISessionStateChangedEvent_getStateRequestMsg()
req._this=self.handle
val=self.mgr.getPort().ISessionStateChangedEvent_getState(req)
return SessionState(self.mgr,val._returnval)
_Attrs_={ 'state':[getState,None]}
class IGuestPropertyChangedEvent(IMachineEvent):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IGuestPropertyChangedEvent(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IGuestPropertyChangedEvent._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IMachineEvent.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IGuestPropertyChangedEvent._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def getName(self):
req=IGuestPropertyChangedEvent_getNameRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IGuestPropertyChangedEvent_getName(req)
return String(self.mgr,val._returnval)
def getValue(self):
req=IGuestPropertyChangedEvent_getValueRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IGuestPropertyChangedEvent_getValue(req)
return String(self.mgr,val._returnval)
def getFlags(self):
req=IGuestPropertyChangedEvent_getFlagsRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IGuestPropertyChangedEvent_getFlags(req)
return String(self.mgr,val._returnval)
_Attrs_={ 'name':[getName,None],
'value':[getValue,None],
'flags':[getFlags,None]}
class ISnapshotEvent(IMachineEvent):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return ISnapshotEvent(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = ISnapshotEvent._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IMachineEvent.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = ISnapshotEvent._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def getSnapshotId(self):
req=ISnapshotEvent_getSnapshotIdRequestMsg()
req._this=self.handle
val=self.mgr.getPort().ISnapshotEvent_getSnapshotId(req)
return String(self.mgr,val._returnval)
_Attrs_={ 'snapshotId':[getSnapshotId,None]}
class ISnapshotTakenEvent(ISnapshotEvent):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return ISnapshotTakenEvent(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = ISnapshotTakenEvent._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return ISnapshotEvent.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = ISnapshotTakenEvent._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
_Attrs_={}
class ISnapshotDeletedEvent(ISnapshotEvent):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return ISnapshotDeletedEvent(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = ISnapshotDeletedEvent._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return ISnapshotEvent.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = ISnapshotDeletedEvent._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
_Attrs_={}
class ISnapshotChangedEvent(ISnapshotEvent):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return ISnapshotChangedEvent(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = ISnapshotChangedEvent._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return ISnapshotEvent.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = ISnapshotChangedEvent._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
_Attrs_={}
class IMousePointerShapeChangedEvent(IEvent):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IMousePointerShapeChangedEvent(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IMousePointerShapeChangedEvent._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IEvent.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IMousePointerShapeChangedEvent._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def getVisible(self):
req=IMousePointerShapeChangedEvent_getVisibleRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMousePointerShapeChangedEvent_getVisible(req)
return Boolean(self.mgr,val._returnval)
def getAlpha(self):
req=IMousePointerShapeChangedEvent_getAlphaRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMousePointerShapeChangedEvent_getAlpha(req)
return Boolean(self.mgr,val._returnval)
def getXhot(self):
req=IMousePointerShapeChangedEvent_getXhotRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMousePointerShapeChangedEvent_getXhot(req)
return UnsignedInt(self.mgr,val._returnval)
def getYhot(self):
req=IMousePointerShapeChangedEvent_getYhotRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMousePointerShapeChangedEvent_getYhot(req)
return UnsignedInt(self.mgr,val._returnval)
def getWidth(self):
req=IMousePointerShapeChangedEvent_getWidthRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMousePointerShapeChangedEvent_getWidth(req)
return UnsignedInt(self.mgr,val._returnval)
def getHeight(self):
req=IMousePointerShapeChangedEvent_getHeightRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMousePointerShapeChangedEvent_getHeight(req)
return UnsignedInt(self.mgr,val._returnval)
def getShape(self):
req=IMousePointerShapeChangedEvent_getShapeRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMousePointerShapeChangedEvent_getShape(req)
return Octet(self.mgr,val._returnval, True)
_Attrs_={ 'visible':[getVisible,None],
'alpha':[getAlpha,None],
'xhot':[getXhot,None],
'yhot':[getYhot,None],
'width':[getWidth,None],
'height':[getHeight,None],
'shape':[getShape,None]}
class IMouseCapabilityChangedEvent(IEvent):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IMouseCapabilityChangedEvent(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IMouseCapabilityChangedEvent._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IEvent.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IMouseCapabilityChangedEvent._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def getSupportsAbsolute(self):
req=IMouseCapabilityChangedEvent_getSupportsAbsoluteRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMouseCapabilityChangedEvent_getSupportsAbsolute(req)
return Boolean(self.mgr,val._returnval)
def getSupportsRelative(self):
req=IMouseCapabilityChangedEvent_getSupportsRelativeRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMouseCapabilityChangedEvent_getSupportsRelative(req)
return Boolean(self.mgr,val._returnval)
def getNeedsHostCursor(self):
req=IMouseCapabilityChangedEvent_getNeedsHostCursorRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMouseCapabilityChangedEvent_getNeedsHostCursor(req)
return Boolean(self.mgr,val._returnval)
_Attrs_={ 'supportsAbsolute':[getSupportsAbsolute,None],
'supportsRelative':[getSupportsRelative,None],
'needsHostCursor':[getNeedsHostCursor,None]}
class IKeyboardLedsChangedEvent(IEvent):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IKeyboardLedsChangedEvent(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IKeyboardLedsChangedEvent._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IEvent.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IKeyboardLedsChangedEvent._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def getNumLock(self):
req=IKeyboardLedsChangedEvent_getNumLockRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IKeyboardLedsChangedEvent_getNumLock(req)
return Boolean(self.mgr,val._returnval)
def getCapsLock(self):
req=IKeyboardLedsChangedEvent_getCapsLockRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IKeyboardLedsChangedEvent_getCapsLock(req)
return Boolean(self.mgr,val._returnval)
def getScrollLock(self):
req=IKeyboardLedsChangedEvent_getScrollLockRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IKeyboardLedsChangedEvent_getScrollLock(req)
return Boolean(self.mgr,val._returnval)
_Attrs_={ 'numLock':[getNumLock,None],
'capsLock':[getCapsLock,None],
'scrollLock':[getScrollLock,None]}
class IStateChangedEvent(IEvent):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IStateChangedEvent(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IStateChangedEvent._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IEvent.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IStateChangedEvent._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def getState(self):
req=IStateChangedEvent_getStateRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IStateChangedEvent_getState(req)
return MachineState(self.mgr,val._returnval)
_Attrs_={ 'state':[getState,None]}
class IAdditionsStateChangedEvent(IEvent):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IAdditionsStateChangedEvent(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IAdditionsStateChangedEvent._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IEvent.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IAdditionsStateChangedEvent._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
_Attrs_={}
class INetworkAdapterChangedEvent(IEvent):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return INetworkAdapterChangedEvent(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = INetworkAdapterChangedEvent._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IEvent.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = INetworkAdapterChangedEvent._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def getNetworkAdapter(self):
req=INetworkAdapterChangedEvent_getNetworkAdapterRequestMsg()
req._this=self.handle
val=self.mgr.getPort().INetworkAdapterChangedEvent_getNetworkAdapter(req)
return INetworkAdapter(self.mgr,val._returnval)
_Attrs_={ 'networkAdapter':[getNetworkAdapter,None]}
class ISerialPortChangedEvent(IEvent):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return ISerialPortChangedEvent(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = ISerialPortChangedEvent._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IEvent.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = ISerialPortChangedEvent._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def getSerialPort(self):
req=ISerialPortChangedEvent_getSerialPortRequestMsg()
req._this=self.handle
val=self.mgr.getPort().ISerialPortChangedEvent_getSerialPort(req)
return ISerialPort(self.mgr,val._returnval)
_Attrs_={ 'serialPort':[getSerialPort,None]}
class IParallelPortChangedEvent(IEvent):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IParallelPortChangedEvent(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IParallelPortChangedEvent._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IEvent.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IParallelPortChangedEvent._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def getParallelPort(self):
req=IParallelPortChangedEvent_getParallelPortRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IParallelPortChangedEvent_getParallelPort(req)
return IParallelPort(self.mgr,val._returnval)
_Attrs_={ 'parallelPort':[getParallelPort,None]}
class IStorageControllerChangedEvent(IEvent):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IStorageControllerChangedEvent(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IStorageControllerChangedEvent._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IEvent.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IStorageControllerChangedEvent._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
_Attrs_={}
class IMediumChangedEvent(IEvent):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IMediumChangedEvent(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IMediumChangedEvent._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IEvent.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IMediumChangedEvent._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def getMediumAttachment(self):
req=IMediumChangedEvent_getMediumAttachmentRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IMediumChangedEvent_getMediumAttachment(req)
return IMediumAttachment(self.mgr,val._returnval)
_Attrs_={ 'mediumAttachment':[getMediumAttachment,None]}
class ICPUChangedEvent(IEvent):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return ICPUChangedEvent(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = ICPUChangedEvent._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IEvent.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = ICPUChangedEvent._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def getCpu(self):
req=ICPUChangedEvent_getCpuRequestMsg()
req._this=self.handle
val=self.mgr.getPort().ICPUChangedEvent_getCpu(req)
return UnsignedInt(self.mgr,val._returnval)
def getAdd(self):
req=ICPUChangedEvent_getAddRequestMsg()
req._this=self.handle
val=self.mgr.getPort().ICPUChangedEvent_getAdd(req)
return Boolean(self.mgr,val._returnval)
_Attrs_={ 'cpu':[getCpu,None],
'add':[getAdd,None]}
class ICPUExecutionCapChangedEvent(IEvent):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return ICPUExecutionCapChangedEvent(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = ICPUExecutionCapChangedEvent._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IEvent.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = ICPUExecutionCapChangedEvent._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def getExecutionCap(self):
req=ICPUExecutionCapChangedEvent_getExecutionCapRequestMsg()
req._this=self.handle
val=self.mgr.getPort().ICPUExecutionCapChangedEvent_getExecutionCap(req)
return UnsignedInt(self.mgr,val._returnval)
_Attrs_={ 'executionCap':[getExecutionCap,None]}
class IGuestKeyboardEvent(IEvent):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IGuestKeyboardEvent(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IGuestKeyboardEvent._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IEvent.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IGuestKeyboardEvent._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def getScancodes(self):
req=IGuestKeyboardEvent_getScancodesRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IGuestKeyboardEvent_getScancodes(req)
return Int(self.mgr,val._returnval, True)
_Attrs_={ 'scancodes':[getScancodes,None]}
class IGuestMouseEvent(IReusableEvent):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IGuestMouseEvent(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IGuestMouseEvent._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IReusableEvent.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IGuestMouseEvent._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def getAbsolute(self):
req=IGuestMouseEvent_getAbsoluteRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IGuestMouseEvent_getAbsolute(req)
return Boolean(self.mgr,val._returnval)
def getX(self):
req=IGuestMouseEvent_getXRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IGuestMouseEvent_getX(req)
return Int(self.mgr,val._returnval)
def getY(self):
req=IGuestMouseEvent_getYRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IGuestMouseEvent_getY(req)
return Int(self.mgr,val._returnval)
def getZ(self):
req=IGuestMouseEvent_getZRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IGuestMouseEvent_getZ(req)
return Int(self.mgr,val._returnval)
def getW(self):
req=IGuestMouseEvent_getWRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IGuestMouseEvent_getW(req)
return Int(self.mgr,val._returnval)
def getButtons(self):
req=IGuestMouseEvent_getButtonsRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IGuestMouseEvent_getButtons(req)
return Int(self.mgr,val._returnval)
_Attrs_={ 'absolute':[getAbsolute,None],
'x':[getX,None],
'y':[getY,None],
'z':[getZ,None],
'w':[getW,None],
'buttons':[getButtons,None]}
class IVRDEServerChangedEvent(IEvent):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IVRDEServerChangedEvent(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IVRDEServerChangedEvent._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IEvent.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IVRDEServerChangedEvent._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
_Attrs_={}
class IVRDEServerInfoChangedEvent(IEvent):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IVRDEServerInfoChangedEvent(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IVRDEServerInfoChangedEvent._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IEvent.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IVRDEServerInfoChangedEvent._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
_Attrs_={}
class IUSBControllerChangedEvent(IEvent):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IUSBControllerChangedEvent(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IUSBControllerChangedEvent._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IEvent.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IUSBControllerChangedEvent._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
_Attrs_={}
class IUSBDeviceStateChangedEvent(IEvent):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IUSBDeviceStateChangedEvent(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IUSBDeviceStateChangedEvent._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IEvent.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IUSBDeviceStateChangedEvent._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def getDevice(self):
req=IUSBDeviceStateChangedEvent_getDeviceRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IUSBDeviceStateChangedEvent_getDevice(req)
return IUSBDevice(self.mgr,val._returnval)
def getAttached(self):
req=IUSBDeviceStateChangedEvent_getAttachedRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IUSBDeviceStateChangedEvent_getAttached(req)
return Boolean(self.mgr,val._returnval)
def getError(self):
req=IUSBDeviceStateChangedEvent_getErrorRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IUSBDeviceStateChangedEvent_getError(req)
return IVirtualBoxErrorInfo(self.mgr,val._returnval)
_Attrs_={ 'device':[getDevice,None],
'attached':[getAttached,None],
'error':[getError,None]}
class ISharedFolderChangedEvent(IEvent):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return ISharedFolderChangedEvent(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = ISharedFolderChangedEvent._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IEvent.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = ISharedFolderChangedEvent._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def getScope(self):
req=ISharedFolderChangedEvent_getScopeRequestMsg()
req._this=self.handle
val=self.mgr.getPort().ISharedFolderChangedEvent_getScope(req)
return Scope(self.mgr,val._returnval)
_Attrs_={ 'scope':[getScope,None]}
class IRuntimeErrorEvent(IEvent):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IRuntimeErrorEvent(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IRuntimeErrorEvent._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IEvent.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IRuntimeErrorEvent._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def getFatal(self):
req=IRuntimeErrorEvent_getFatalRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IRuntimeErrorEvent_getFatal(req)
return Boolean(self.mgr,val._returnval)
def getId(self):
req=IRuntimeErrorEvent_getIdRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IRuntimeErrorEvent_getId(req)
return String(self.mgr,val._returnval)
def getMessage(self):
req=IRuntimeErrorEvent_getMessageRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IRuntimeErrorEvent_getMessage(req)
return String(self.mgr,val._returnval)
_Attrs_={ 'fatal':[getFatal,None],
'id':[getId,None],
'message':[getMessage,None]}
class IEventSourceChangedEvent(IEvent):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IEventSourceChangedEvent(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IEventSourceChangedEvent._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IEvent.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IEventSourceChangedEvent._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def getListener(self):
req=IEventSourceChangedEvent_getListenerRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IEventSourceChangedEvent_getListener(req)
return IEventListener(self.mgr,val._returnval)
def getAdd(self):
req=IEventSourceChangedEvent_getAddRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IEventSourceChangedEvent_getAdd(req)
return Boolean(self.mgr,val._returnval)
_Attrs_={ 'listener':[getListener,None],
'add':[getAdd,None]}
class IExtraDataChangedEvent(IEvent):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IExtraDataChangedEvent(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IExtraDataChangedEvent._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IEvent.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IExtraDataChangedEvent._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def getMachineId(self):
req=IExtraDataChangedEvent_getMachineIdRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IExtraDataChangedEvent_getMachineId(req)
return String(self.mgr,val._returnval)
def getKey(self):
req=IExtraDataChangedEvent_getKeyRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IExtraDataChangedEvent_getKey(req)
return String(self.mgr,val._returnval)
def getValue(self):
req=IExtraDataChangedEvent_getValueRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IExtraDataChangedEvent_getValue(req)
return String(self.mgr,val._returnval)
_Attrs_={ 'machineId':[getMachineId,None],
'key':[getKey,None],
'value':[getValue,None]}
class IVetoEvent(IEvent):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IVetoEvent(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IVetoEvent._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IEvent.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IVetoEvent._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def addVeto(self, _arg_reason):
req=IVetoEvent_addVetoRequestMsg()
req._this=self.handle
req._reason=_arg_reason
val=self.mgr.getPort().IVetoEvent_addVeto(req)
return
def isVetoed(self):
req=IVetoEvent_isVetoedRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IVetoEvent_isVetoed(req)
return Boolean(self.mgr,val._returnval)
def getVetos(self):
req=IVetoEvent_getVetosRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IVetoEvent_getVetos(req)
return String(self.mgr,val._returnval, True)
_Attrs_={}
class IExtraDataCanChangeEvent(IVetoEvent):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IExtraDataCanChangeEvent(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IExtraDataCanChangeEvent._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IVetoEvent.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IExtraDataCanChangeEvent._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def getMachineId(self):
req=IExtraDataCanChangeEvent_getMachineIdRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IExtraDataCanChangeEvent_getMachineId(req)
return String(self.mgr,val._returnval)
def getKey(self):
req=IExtraDataCanChangeEvent_getKeyRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IExtraDataCanChangeEvent_getKey(req)
return String(self.mgr,val._returnval)
def getValue(self):
req=IExtraDataCanChangeEvent_getValueRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IExtraDataCanChangeEvent_getValue(req)
return String(self.mgr,val._returnval)
_Attrs_={ 'machineId':[getMachineId,None],
'key':[getKey,None],
'value':[getValue,None]}
class ICanShowWindowEvent(IVetoEvent):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return ICanShowWindowEvent(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = ICanShowWindowEvent._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IVetoEvent.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = ICanShowWindowEvent._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
_Attrs_={}
class IShowWindowEvent(IEvent):
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
if handle is None:
raise Exception("bad handle: "+str(handle))
self.handle = handle
self.isarray = isarray
def releaseRemote(self):
try:
req=IManagedObjectRef_releaseRequestMsg()
req._this=handle
self.mgr.getPort().IManagedObjectRef_release(req)
except:
pass
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IShowWindowEvent(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
def __str__(self):
return self.handle
def isValid(self):
return self.handle != None and self.handle != ''
def __getattr__(self,name):
hndl = IShowWindowEvent._Attrs_.get(name, None)
if hndl != None:
if hndl[0] != None:
return hndl[0](self)
else:
raise AttributeError
else:
return IEvent.__getattr__(self, name)
def __setattr__(self, name, val):
hndl = IShowWindowEvent._Attrs_.get(name, None)
if (hndl != None and hndl[1] != None):
hndl[1](self,val)
else:
self.__dict__[name] = val
def getWinId(self):
req=IShowWindowEvent_getWinIdRequestMsg()
req._this=self.handle
val=self.mgr.getPort().IShowWindowEvent_getWinId(req)
return Long(self.mgr,val._returnval)
def setWinId(self, value):
req=IShowWindowEvent_setWinIdRequestMsg()
req._this=self.handle
if type(value) in [int, bool, basestring, str]:
req._winId = value
else:
req._winId = value.handle
self.mgr.getPort().IShowWindowEvent_setWinId(req)
_Attrs_={ 'winId':[getWinId,setWinId,
]}
class IVRDEServerInfo:
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
self.isarray = isarray
if isarray:
self.handle = handle
else:
self.active = Boolean(self.mgr, handle._active)
self.port = Int(self.mgr, handle._port)
self.numberOfClients = UnsignedInt(self.mgr, handle._numberOfClients)
self.beginTime = Long(self.mgr, handle._beginTime)
self.endTime = Long(self.mgr, handle._endTime)
self.bytesSent = Long(self.mgr, handle._bytesSent)
self.bytesSentTotal = Long(self.mgr, handle._bytesSentTotal)
self.bytesReceived = Long(self.mgr, handle._bytesReceived)
self.bytesReceivedTotal = Long(self.mgr, handle._bytesReceivedTotal)
self.user = String(self.mgr, handle._user)
self.domain = String(self.mgr, handle._domain)
self.clientName = String(self.mgr, handle._clientName)
self.clientIP = String(self.mgr, handle._clientIP)
self.clientVersion = UnsignedInt(self.mgr, handle._clientVersion)
self.encryptionStyle = UnsignedInt(self.mgr, handle._encryptionStyle)
pass
def getActive(self):
return self.active
def setActive(self):
raise Error, 'setters not supported'
def getPort(self):
return self.port
def setPort(self):
raise Error, 'setters not supported'
def getNumberOfClients(self):
return self.numberOfClients
def setNumberOfClients(self):
raise Error, 'setters not supported'
def getBeginTime(self):
return self.beginTime
def setBeginTime(self):
raise Error, 'setters not supported'
def getEndTime(self):
return self.endTime
def setEndTime(self):
raise Error, 'setters not supported'
def getBytesSent(self):
return self.bytesSent
def setBytesSent(self):
raise Error, 'setters not supported'
def getBytesSentTotal(self):
return self.bytesSentTotal
def setBytesSentTotal(self):
raise Error, 'setters not supported'
def getBytesReceived(self):
return self.bytesReceived
def setBytesReceived(self):
raise Error, 'setters not supported'
def getBytesReceivedTotal(self):
return self.bytesReceivedTotal
def setBytesReceivedTotal(self):
raise Error, 'setters not supported'
def getUser(self):
return self.user
def setUser(self):
raise Error, 'setters not supported'
def getDomain(self):
return self.domain
def setDomain(self):
raise Error, 'setters not supported'
def getClientName(self):
return self.clientName
def setClientName(self):
raise Error, 'setters not supported'
def getClientIP(self):
return self.clientIP
def setClientIP(self):
raise Error, 'setters not supported'
def getClientVersion(self):
return self.clientVersion
def setClientVersion(self):
raise Error, 'setters not supported'
def getEncryptionStyle(self):
return self.encryptionStyle
def setEncryptionStyle(self):
raise Error, 'setters not supported'
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IVRDEServerInfo(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
class IGuestOSType:
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
self.isarray = isarray
if isarray:
self.handle = handle
else:
self.familyId = String(self.mgr, handle._familyId)
self.familyDescription = String(self.mgr, handle._familyDescription)
self.id = String(self.mgr, handle._id)
self.description = String(self.mgr, handle._description)
self.is64Bit = Boolean(self.mgr, handle._is64Bit)
self.recommendedIOAPIC = Boolean(self.mgr, handle._recommendedIOAPIC)
self.recommendedVirtEx = Boolean(self.mgr, handle._recommendedVirtEx)
self.recommendedRAM = UnsignedInt(self.mgr, handle._recommendedRAM)
self.recommendedVRAM = UnsignedInt(self.mgr, handle._recommendedVRAM)
self.recommendedHDD = Long(self.mgr, handle._recommendedHDD)
self.adapterType = NetworkAdapterType(self.mgr, handle._adapterType)
self.recommendedPae = Boolean(self.mgr, handle._recommendedPae)
self.recommendedDvdStorageController = StorageControllerType(self.mgr, handle._recommendedDvdStorageController)
self.recommendedDvdStorageBus = StorageBus(self.mgr, handle._recommendedDvdStorageBus)
self.recommendedHdStorageController = StorageControllerType(self.mgr, handle._recommendedHdStorageController)
self.recommendedHdStorageBus = StorageBus(self.mgr, handle._recommendedHdStorageBus)
self.recommendedFirmware = FirmwareType(self.mgr, handle._recommendedFirmware)
self.recommendedUsbHid = Boolean(self.mgr, handle._recommendedUsbHid)
self.recommendedHpet = Boolean(self.mgr, handle._recommendedHpet)
self.recommendedUsbTablet = Boolean(self.mgr, handle._recommendedUsbTablet)
self.recommendedRtcUseUtc = Boolean(self.mgr, handle._recommendedRtcUseUtc)
self.recommendedChipset = ChipsetType(self.mgr, handle._recommendedChipset)
self.recommendedAudioController = AudioControllerType(self.mgr, handle._recommendedAudioController)
pass
def getFamilyId(self):
return self.familyId
def setFamilyId(self):
raise Error, 'setters not supported'
def getFamilyDescription(self):
return self.familyDescription
def setFamilyDescription(self):
raise Error, 'setters not supported'
def getId(self):
return self.id
def setId(self):
raise Error, 'setters not supported'
def getDescription(self):
return self.description
def setDescription(self):
raise Error, 'setters not supported'
def getIs64Bit(self):
return self.is64Bit
def setIs64Bit(self):
raise Error, 'setters not supported'
def getRecommendedIOAPIC(self):
return self.recommendedIOAPIC
def setRecommendedIOAPIC(self):
raise Error, 'setters not supported'
def getRecommendedVirtEx(self):
return self.recommendedVirtEx
def setRecommendedVirtEx(self):
raise Error, 'setters not supported'
def getRecommendedRAM(self):
return self.recommendedRAM
def setRecommendedRAM(self):
raise Error, 'setters not supported'
def getRecommendedVRAM(self):
return self.recommendedVRAM
def setRecommendedVRAM(self):
raise Error, 'setters not supported'
def getRecommendedHDD(self):
return self.recommendedHDD
def setRecommendedHDD(self):
raise Error, 'setters not supported'
def getAdapterType(self):
return self.adapterType
def setAdapterType(self):
raise Error, 'setters not supported'
def getRecommendedPae(self):
return self.recommendedPae
def setRecommendedPae(self):
raise Error, 'setters not supported'
def getRecommendedDvdStorageController(self):
return self.recommendedDvdStorageController
def setRecommendedDvdStorageController(self):
raise Error, 'setters not supported'
def getRecommendedDvdStorageBus(self):
return self.recommendedDvdStorageBus
def setRecommendedDvdStorageBus(self):
raise Error, 'setters not supported'
def getRecommendedHdStorageController(self):
return self.recommendedHdStorageController
def setRecommendedHdStorageController(self):
raise Error, 'setters not supported'
def getRecommendedHdStorageBus(self):
return self.recommendedHdStorageBus
def setRecommendedHdStorageBus(self):
raise Error, 'setters not supported'
def getRecommendedFirmware(self):
return self.recommendedFirmware
def setRecommendedFirmware(self):
raise Error, 'setters not supported'
def getRecommendedUsbHid(self):
return self.recommendedUsbHid
def setRecommendedUsbHid(self):
raise Error, 'setters not supported'
def getRecommendedHpet(self):
return self.recommendedHpet
def setRecommendedHpet(self):
raise Error, 'setters not supported'
def getRecommendedUsbTablet(self):
return self.recommendedUsbTablet
def setRecommendedUsbTablet(self):
raise Error, 'setters not supported'
def getRecommendedRtcUseUtc(self):
return self.recommendedRtcUseUtc
def setRecommendedRtcUseUtc(self):
raise Error, 'setters not supported'
def getRecommendedChipset(self):
return self.recommendedChipset
def setRecommendedChipset(self):
raise Error, 'setters not supported'
def getRecommendedAudioController(self):
return self.recommendedAudioController
def setRecommendedAudioController(self):
raise Error, 'setters not supported'
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IGuestOSType(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
class IMediumAttachment:
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
self.isarray = isarray
if isarray:
self.handle = handle
else:
self.medium = IMedium(self.mgr, handle._medium)
self.controller = String(self.mgr, handle._controller)
self.port = Int(self.mgr, handle._port)
self.device = Int(self.mgr, handle._device)
self.type = DeviceType(self.mgr, handle._type)
self.passthrough = Boolean(self.mgr, handle._passthrough)
self.bandwidthLimit = UnsignedInt(self.mgr, handle._bandwidthLimit)
pass
def getMedium(self):
return self.medium
def setMedium(self):
raise Error, 'setters not supported'
def getController(self):
return self.controller
def setController(self):
raise Error, 'setters not supported'
def getPort(self):
return self.port
def setPort(self):
raise Error, 'setters not supported'
def getDevice(self):
return self.device
def setDevice(self):
raise Error, 'setters not supported'
def getType(self):
return self.type
def setType(self):
raise Error, 'setters not supported'
def getPassthrough(self):
return self.passthrough
def setPassthrough(self):
raise Error, 'setters not supported'
def getBandwidthLimit(self):
return self.bandwidthLimit
def setBandwidthLimit(self):
raise Error, 'setters not supported'
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return IMediumAttachment(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
class ISharedFolder:
def __init__(self, mgr, handle, isarray = False):
self.mgr = mgr
self.isarray = isarray
if isarray:
self.handle = handle
else:
self.name = String(self.mgr, handle._name)
self.hostPath = String(self.mgr, handle._hostPath)
self.accessible = Boolean(self.mgr, handle._accessible)
self.writable = Boolean(self.mgr, handle._writable)
self.autoMount = Boolean(self.mgr, handle._autoMount)
self.lastAccessError = String(self.mgr, handle._lastAccessError)
pass
def getName(self):
return self.name
def setName(self):
raise Error, 'setters not supported'
def getHostPath(self):
return self.hostPath
def setHostPath(self):
raise Error, 'setters not supported'
def getAccessible(self):
return self.accessible
def setAccessible(self):
raise Error, 'setters not supported'
def getWritable(self):
return self.writable
def setWritable(self):
raise Error, 'setters not supported'
def getAutoMount(self):
return self.autoMount
def setAutoMount(self):
raise Error, 'setters not supported'
def getLastAccessError(self):
return self.lastAccessError
def setLastAccessError(self):
raise Error, 'setters not supported'
def __next(self):
if self.isarray:
return self.handle.__next()
raise TypeError, "iteration over non-sequence"
def __size(self):
if self.isarray:
return self.handle.__size()
raise TypeError, "iteration over non-sequence"
def __len__(self):
if self.isarray:
return self.handle.__len__()
raise TypeError, "iteration over non-sequence"
def __getitem__(self, index):
if self.isarray:
return ISharedFolder(self.mgr, self.handle[index])
raise TypeError, "iteration over non-sequence"
class SettingsVersion:
def __init__(self,mgr,handle):
self.mgr=mgr
if isinstance(handle,basestring):
self.handle=SettingsVersion._ValueMap[handle]
else:
self.handle=handle
def __eq__(self,other):
if isinstance(other,SettingsVersion):
return self.handle == other.handle
if isinstance(other,int):
return self.handle == other
if isinstance(other,basestring):
return str(self) == other
return False
def __ne__(self,other):
if isinstance(other,SettingsVersion):
return self.handle != other.handle
if isinstance(other,int):
return self.handle != other
if isinstance(other,basestring):
return str(self) != other
return True
def __str__(self):
return SettingsVersion._NameMap[self.handle]
def __int__(self):
return self.handle
_NameMap={0:'Null',1:'v1_0',2:'v1_1',3:'v1_2',4:'v1_3pre',5:'v1_3',6:'v1_4',7:'v1_5',8:'v1_6',9:'v1_7',10:'v1_8',11:'v1_9',12:'v1_10',13:'v1_11',99999:'Future'}
_ValueMap={
'Null':0,
'v1_0':1,
'v1_1':2,
'v1_2':3,
'v1_3pre':4,
'v1_3':5,
'v1_4':6,
'v1_5':7,
'v1_6':8,
'v1_7':9,
'v1_8':10,
'v1_9':11,
'v1_10':12,
'v1_11':13,
'Future':99999}
Null=0
v1_0=1
v1_1=2
v1_2=3
v1_3pre=4
v1_3=5
v1_4=6
v1_5=7
v1_6=8
v1_7=9
v1_8=10
v1_9=11
v1_10=12
v1_11=13
Future=99999
class AccessMode:
def __init__(self,mgr,handle):
self.mgr=mgr
if isinstance(handle,basestring):
self.handle=AccessMode._ValueMap[handle]
else:
self.handle=handle
def __eq__(self,other):
if isinstance(other,AccessMode):
return self.handle == other.handle
if isinstance(other,int):
return self.handle == other
if isinstance(other,basestring):
return str(self) == other
return False
def __ne__(self,other):
if isinstance(other,AccessMode):
return self.handle != other.handle
if isinstance(other,int):
return self.handle != other
if isinstance(other,basestring):
return str(self) != other
return True
def __str__(self):
return AccessMode._NameMap[self.handle]
def __int__(self):
return self.handle
_NameMap={1:'ReadOnly',2:'ReadWrite'}
_ValueMap={
'ReadOnly':1,
'ReadWrite':2}
ReadOnly=1
ReadWrite=2
class MachineState:
def __init__(self,mgr,handle):
self.mgr=mgr
if isinstance(handle,basestring):
self.handle=MachineState._ValueMap[handle]
else:
self.handle=handle
def __eq__(self,other):
if isinstance(other,MachineState):
return self.handle == other.handle
if isinstance(other,int):
return self.handle == other
if isinstance(other,basestring):
return str(self) == other
return False
def __ne__(self,other):
if isinstance(other,MachineState):
return self.handle != other.handle
if isinstance(other,int):
return self.handle != other
if isinstance(other,basestring):
return str(self) != other
return True
def __str__(self):
return MachineState._NameMap[self.handle]
def __int__(self):
return self.handle
_NameMap={0:'Null',1:'PoweredOff',2:'Saved',3:'Teleported',4:'Aborted',5:'Running',6:'Paused',7:'Stuck',8:'Teleporting',9:'LiveSnapshotting',10:'Starting',11:'Stopping',12:'Saving',13:'Restoring',14:'TeleportingPausedVM',15:'TeleportingIn',16:'FaultTolerantSyncing',17:'DeletingSnapshotOnline',18:'DeletingSnapshotPaused',19:'RestoringSnapshot',20:'DeletingSnapshot',21:'SettingUp',8:'FirstTransient',21:'LastTransient'}
_ValueMap={
'Null':0,
'PoweredOff':1,
'Saved':2,
'Teleported':3,
'Aborted':4,
'Running':5,
'Paused':6,
'Stuck':7,
'Teleporting':8,
'LiveSnapshotting':9,
'Starting':10,
'Stopping':11,
'Saving':12,
'Restoring':13,
'TeleportingPausedVM':14,
'TeleportingIn':15,
'FaultTolerantSyncing':16,
'DeletingSnapshotOnline':17,
'DeletingSnapshotPaused':18,
'RestoringSnapshot':19,
'DeletingSnapshot':20,
'SettingUp':21,
'FirstOnline':5,
'LastOnline':18,
'FirstTransient':8,
'LastTransient':21}
Null=0
PoweredOff=1
Saved=2
Teleported=3
Aborted=4
Running=5
Paused=6
Stuck=7
Teleporting=8
LiveSnapshotting=9
Starting=10
Stopping=11
Saving=12
Restoring=13
TeleportingPausedVM=14
TeleportingIn=15
FaultTolerantSyncing=16
DeletingSnapshotOnline=17
DeletingSnapshotPaused=18
RestoringSnapshot=19
DeletingSnapshot=20
SettingUp=21
FirstOnline=5
LastOnline=18
FirstTransient=8
LastTransient=21
class SessionState:
def __init__(self,mgr,handle):
self.mgr=mgr
if isinstance(handle,basestring):
self.handle=SessionState._ValueMap[handle]
else:
self.handle=handle
def __eq__(self,other):
if isinstance(other,SessionState):
return self.handle == other.handle
if isinstance(other,int):
return self.handle == other
if isinstance(other,basestring):
return str(self) == other
return False
def __ne__(self,other):
if isinstance(other,SessionState):
return self.handle != other.handle
if isinstance(other,int):
return self.handle != other
if isinstance(other,basestring):
return str(self) != other
return True
def __str__(self):
return SessionState._NameMap[self.handle]
def __int__(self):
return self.handle
_NameMap={0:'Null',1:'Unlocked',2:'Locked',3:'Spawning',4:'Unlocking'}
_ValueMap={
'Null':0,
'Unlocked':1,
'Locked':2,
'Spawning':3,
'Unlocking':4}
Null=0
Unlocked=1
Locked=2
Spawning=3
Unlocking=4
class CPUPropertyType:
def __init__(self,mgr,handle):
self.mgr=mgr
if isinstance(handle,basestring):
self.handle=CPUPropertyType._ValueMap[handle]
else:
self.handle=handle
def __eq__(self,other):
if isinstance(other,CPUPropertyType):
return self.handle == other.handle
if isinstance(other,int):
return self.handle == other
if isinstance(other,basestring):
return str(self) == other
return False
def __ne__(self,other):
if isinstance(other,CPUPropertyType):
return self.handle != other.handle
if isinstance(other,int):
return self.handle != other
if isinstance(other,basestring):
return str(self) != other
return True
def __str__(self):
return CPUPropertyType._NameMap[self.handle]
def __int__(self):
return self.handle
_NameMap={0:'Null',1:'PAE',2:'Synthetic'}
_ValueMap={
'Null':0,
'PAE':1,
'Synthetic':2}
Null=0
PAE=1
Synthetic=2
class HWVirtExPropertyType:
def __init__(self,mgr,handle):
self.mgr=mgr
if isinstance(handle,basestring):
self.handle=HWVirtExPropertyType._ValueMap[handle]
else:
self.handle=handle
def __eq__(self,other):
if isinstance(other,HWVirtExPropertyType):
return self.handle == other.handle
if isinstance(other,int):
return self.handle == other
if isinstance(other,basestring):
return str(self) == other
return False
def __ne__(self,other):
if isinstance(other,HWVirtExPropertyType):
return self.handle != other.handle
if isinstance(other,int):
return self.handle != other
if isinstance(other,basestring):
return str(self) != other
return True
def __str__(self):
return HWVirtExPropertyType._NameMap[self.handle]
def __int__(self):
return self.handle
_NameMap={0:'Null',1:'Enabled',2:'Exclusive',3:'VPID',4:'NestedPaging',5:'LargePages',6:'Force'}
_ValueMap={
'Null':0,
'Enabled':1,
'Exclusive':2,
'VPID':3,
'NestedPaging':4,
'LargePages':5,
'Force':6}
Null=0
Enabled=1
Exclusive=2
VPID=3
NestedPaging=4
LargePages=5
Force=6
class FaultToleranceState:
def __init__(self,mgr,handle):
self.mgr=mgr
if isinstance(handle,basestring):
self.handle=FaultToleranceState._ValueMap[handle]
else:
self.handle=handle
def __eq__(self,other):
if isinstance(other,FaultToleranceState):
return self.handle == other.handle
if isinstance(other,int):
return self.handle == other
if isinstance(other,basestring):
return str(self) == other
return False
def __ne__(self,other):
if isinstance(other,FaultToleranceState):
return self.handle != other.handle
if isinstance(other,int):
return self.handle != other
if isinstance(other,basestring):
return str(self) != other
return True
def __str__(self):
return FaultToleranceState._NameMap[self.handle]
def __int__(self):
return self.handle
_NameMap={1:'Inactive',2:'Master',3:'Standby'}
_ValueMap={
'Inactive':1,
'Master':2,
'Standby':3}
Inactive=1
Master=2
Standby=3
class LockType:
def __init__(self,mgr,handle):
self.mgr=mgr
if isinstance(handle,basestring):
self.handle=LockType._ValueMap[handle]
else:
self.handle=handle
def __eq__(self,other):
if isinstance(other,LockType):
return self.handle == other.handle
if isinstance(other,int):
return self.handle == other
if isinstance(other,basestring):
return str(self) == other
return False
def __ne__(self,other):
if isinstance(other,LockType):
return self.handle != other.handle
if isinstance(other,int):
return self.handle != other
if isinstance(other,basestring):
return str(self) != other
return True
def __str__(self):
return LockType._NameMap[self.handle]
def __int__(self):
return self.handle
_NameMap={2:'Write',1:'Shared'}
_ValueMap={
'Write':2,
'Shared':1}
Write=2
Shared=1
class SessionType:
def __init__(self,mgr,handle):
self.mgr=mgr
if isinstance(handle,basestring):
self.handle=SessionType._ValueMap[handle]
else:
self.handle=handle
def __eq__(self,other):
if isinstance(other,SessionType):
return self.handle == other.handle
if isinstance(other,int):
return self.handle == other
if isinstance(other,basestring):
return str(self) == other
return False
def __ne__(self,other):
if isinstance(other,SessionType):
return self.handle != other.handle
if isinstance(other,int):
return self.handle != other
if isinstance(other,basestring):
return str(self) != other
return True
def __str__(self):
return SessionType._NameMap[self.handle]
def __int__(self):
return self.handle
_NameMap={0:'Null',1:'WriteLock',2:'Remote',3:'Shared'}
_ValueMap={
'Null':0,
'WriteLock':1,
'Remote':2,
'Shared':3}
Null=0
WriteLock=1
Remote=2
Shared=3
class DeviceType:
def __init__(self,mgr,handle):
self.mgr=mgr
if isinstance(handle,basestring):
self.handle=DeviceType._ValueMap[handle]
else:
self.handle=handle
def __eq__(self,other):
if isinstance(other,DeviceType):
return self.handle == other.handle
if isinstance(other,int):
return self.handle == other
if isinstance(other,basestring):
return str(self) == other
return False
def __ne__(self,other):
if isinstance(other,DeviceType):
return self.handle != other.handle
if isinstance(other,int):
return self.handle != other
if isinstance(other,basestring):
return str(self) != other
return True
def __str__(self):
return DeviceType._NameMap[self.handle]
def __int__(self):
return self.handle
_NameMap={0:'Null',1:'Floppy',2:'DVD',3:'HardDisk',4:'Network',5:'USB',6:'SharedFolder'}
_ValueMap={
'Null':0,
'Floppy':1,
'DVD':2,
'HardDisk':3,
'Network':4,
'USB':5,
'SharedFolder':6}
Null=0
Floppy=1
DVD=2
HardDisk=3
Network=4
USB=5
SharedFolder=6
class DeviceActivity:
def __init__(self,mgr,handle):
self.mgr=mgr
if isinstance(handle,basestring):
self.handle=DeviceActivity._ValueMap[handle]
else:
self.handle=handle
def __eq__(self,other):
if isinstance(other,DeviceActivity):
return self.handle == other.handle
if isinstance(other,int):
return self.handle == other
if isinstance(other,basestring):
return str(self) == other
return False
def __ne__(self,other):
if isinstance(other,DeviceActivity):
return self.handle != other.handle
if isinstance(other,int):
return self.handle != other
if isinstance(other,basestring):
return str(self) != other
return True
def __str__(self):
return DeviceActivity._NameMap[self.handle]
def __int__(self):
return self.handle
_NameMap={0:'Null',1:'Idle',2:'Reading',3:'Writing'}
_ValueMap={
'Null':0,
'Idle':1,
'Reading':2,
'Writing':3}
Null=0
Idle=1
Reading=2
Writing=3
class ClipboardMode:
def __init__(self,mgr,handle):
self.mgr=mgr
if isinstance(handle,basestring):
self.handle=ClipboardMode._ValueMap[handle]
else:
self.handle=handle
def __eq__(self,other):
if isinstance(other,ClipboardMode):
return self.handle == other.handle
if isinstance(other,int):
return self.handle == other
if isinstance(other,basestring):
return str(self) == other
return False
def __ne__(self,other):
if isinstance(other,ClipboardMode):
return self.handle != other.handle
if isinstance(other,int):
return self.handle != other
if isinstance(other,basestring):
return str(self) != other
return True
def __str__(self):
return ClipboardMode._NameMap[self.handle]
def __int__(self):
return self.handle
_NameMap={0:'Disabled',1:'HostToGuest',2:'GuestToHost',3:'Bidirectional'}
_ValueMap={
'Disabled':0,
'HostToGuest':1,
'GuestToHost':2,
'Bidirectional':3}
Disabled=0
HostToGuest=1
GuestToHost=2
Bidirectional=3
class Scope:
def __init__(self,mgr,handle):
self.mgr=mgr
if isinstance(handle,basestring):
self.handle=Scope._ValueMap[handle]
else:
self.handle=handle
def __eq__(self,other):
if isinstance(other,Scope):
return self.handle == other.handle
if isinstance(other,int):
return self.handle == other
if isinstance(other,basestring):
return str(self) == other
return False
def __ne__(self,other):
if isinstance(other,Scope):
return self.handle != other.handle
if isinstance(other,int):
return self.handle != other
if isinstance(other,basestring):
return str(self) != other
return True
def __str__(self):
return Scope._NameMap[self.handle]
def __int__(self):
return self.handle
_NameMap={0:'Global',1:'Machine',2:'Session'}
_ValueMap={
'Global':0,
'Machine':1,
'Session':2}
Global=0
Machine=1
Session=2
class BIOSBootMenuMode:
def __init__(self,mgr,handle):
self.mgr=mgr
if isinstance(handle,basestring):
self.handle=BIOSBootMenuMode._ValueMap[handle]
else:
self.handle=handle
def __eq__(self,other):
if isinstance(other,BIOSBootMenuMode):
return self.handle == other.handle
if isinstance(other,int):
return self.handle == other
if isinstance(other,basestring):
return str(self) == other
return False
def __ne__(self,other):
if isinstance(other,BIOSBootMenuMode):
return self.handle != other.handle
if isinstance(other,int):
return self.handle != other
if isinstance(other,basestring):
return str(self) != other
return True
def __str__(self):
return BIOSBootMenuMode._NameMap[self.handle]
def __int__(self):
return self.handle
_NameMap={0:'Disabled',1:'MenuOnly',2:'MessageAndMenu'}
_ValueMap={
'Disabled':0,
'MenuOnly':1,
'MessageAndMenu':2}
Disabled=0
MenuOnly=1
MessageAndMenu=2
class ProcessorFeature:
def __init__(self,mgr,handle):
self.mgr=mgr
if isinstance(handle,basestring):
self.handle=ProcessorFeature._ValueMap[handle]
else:
self.handle=handle
def __eq__(self,other):
if isinstance(other,ProcessorFeature):
return self.handle == other.handle
if isinstance(other,int):
return self.handle == other
if isinstance(other,basestring):
return str(self) == other
return False
def __ne__(self,other):
if isinstance(other,ProcessorFeature):
return self.handle != other.handle
if isinstance(other,int):
return self.handle != other
if isinstance(other,basestring):
return str(self) != other
return True
def __str__(self):
return ProcessorFeature._NameMap[self.handle]
def __int__(self):
return self.handle
_NameMap={0:'HWVirtEx',1:'PAE',2:'LongMode',3:'NestedPaging'}
_ValueMap={
'HWVirtEx':0,
'PAE':1,
'LongMode':2,
'NestedPaging':3}
HWVirtEx=0
PAE=1
LongMode=2
NestedPaging=3
class FirmwareType:
def __init__(self,mgr,handle):
self.mgr=mgr
if isinstance(handle,basestring):
self.handle=FirmwareType._ValueMap[handle]
else:
self.handle=handle
def __eq__(self,other):
if isinstance(other,FirmwareType):
return self.handle == other.handle
if isinstance(other,int):
return self.handle == other
if isinstance(other,basestring):
return str(self) == other
return False
def __ne__(self,other):
if isinstance(other,FirmwareType):
return self.handle != other.handle
if isinstance(other,int):
return self.handle != other
if isinstance(other,basestring):
return str(self) != other
return True
def __str__(self):
return FirmwareType._NameMap[self.handle]
def __int__(self):
return self.handle
_NameMap={1:'BIOS',2:'EFI',3:'EFI32',4:'EFI64',5:'EFIDUAL'}
_ValueMap={
'BIOS':1,
'EFI':2,
'EFI32':3,
'EFI64':4,
'EFIDUAL':5}
BIOS=1
EFI=2
EFI32=3
EFI64=4
EFIDUAL=5
class PointingHidType:
def __init__(self,mgr,handle):
self.mgr=mgr
if isinstance(handle,basestring):
self.handle=PointingHidType._ValueMap[handle]
else:
self.handle=handle
def __eq__(self,other):
if isinstance(other,PointingHidType):
return self.handle == other.handle
if isinstance(other,int):
return self.handle == other
if isinstance(other,basestring):
return str(self) == other
return False
def __ne__(self,other):
if isinstance(other,PointingHidType):
return self.handle != other.handle
if isinstance(other,int):
return self.handle != other
if isinstance(other,basestring):
return str(self) != other
return True
def __str__(self):
return PointingHidType._NameMap[self.handle]
def __int__(self):
return self.handle
_NameMap={1:'None',2:'PS2Mouse',3:'USBMouse',4:'USBTablet',5:'ComboMouse'}
_ValueMap={
'None':1,
'PS2Mouse':2,
'USBMouse':3,
'USBTablet':4,
'ComboMouse':5}
_None=1
PS2Mouse=2
USBMouse=3
USBTablet=4
ComboMouse=5
class KeyboardHidType:
def __init__(self,mgr,handle):
self.mgr=mgr
if isinstance(handle,basestring):
self.handle=KeyboardHidType._ValueMap[handle]
else:
self.handle=handle
def __eq__(self,other):
if isinstance(other,KeyboardHidType):
return self.handle == other.handle
if isinstance(other,int):
return self.handle == other
if isinstance(other,basestring):
return str(self) == other
return False
def __ne__(self,other):
if isinstance(other,KeyboardHidType):
return self.handle != other.handle
if isinstance(other,int):
return self.handle != other
if isinstance(other,basestring):
return str(self) != other
return True
def __str__(self):
return KeyboardHidType._NameMap[self.handle]
def __int__(self):
return self.handle
_NameMap={1:'None',2:'PS2Keyboard',3:'USBKeyboard',4:'ComboKeyboard'}
_ValueMap={
'None':1,
'PS2Keyboard':2,
'USBKeyboard':3,
'ComboKeyboard':4}
_None=1
PS2Keyboard=2
USBKeyboard=3
ComboKeyboard=4
class VFSType:
def __init__(self,mgr,handle):
self.mgr=mgr
if isinstance(handle,basestring):
self.handle=VFSType._ValueMap[handle]
else:
self.handle=handle
def __eq__(self,other):
if isinstance(other,VFSType):
return self.handle == other.handle
if isinstance(other,int):
return self.handle == other
if isinstance(other,basestring):
return str(self) == other
return False
def __ne__(self,other):
if isinstance(other,VFSType):
return self.handle != other.handle
if isinstance(other,int):
return self.handle != other
if isinstance(other,basestring):
return str(self) != other
return True
def __str__(self):
return VFSType._NameMap[self.handle]
def __int__(self):
return self.handle
_NameMap={1:'File',2:'Cloud',3:'S3',4:'WebDav'}
_ValueMap={
'File':1,
'Cloud':2,
'S3':3,
'WebDav':4}
File=1
Cloud=2
S3=3
WebDav=4
class VFSFileType:
def __init__(self,mgr,handle):
self.mgr=mgr
if isinstance(handle,basestring):
self.handle=VFSFileType._ValueMap[handle]
else:
self.handle=handle
def __eq__(self,other):
if isinstance(other,VFSFileType):
return self.handle == other.handle
if isinstance(other,int):
return self.handle == other
if isinstance(other,basestring):
return str(self) == other
return False
def __ne__(self,other):
if isinstance(other,VFSFileType):
return self.handle != other.handle
if isinstance(other,int):
return self.handle != other
if isinstance(other,basestring):
return str(self) != other
return True
def __str__(self):
return VFSFileType._NameMap[self.handle]
def __int__(self):
return self.handle
_NameMap={1:'Unknown',2:'Fifo',3:'DevChar',4:'Directory',5:'DevBlock',6:'File',7:'SymLink',8:'Socket',9:'WhiteOut'}
_ValueMap={
'Unknown':1,
'Fifo':2,
'DevChar':3,
'Directory':4,
'DevBlock':5,
'File':6,
'SymLink':7,
'Socket':8,
'WhiteOut':9}
Unknown=1
Fifo=2
DevChar=3
Directory=4
DevBlock=5
File=6
SymLink=7
Socket=8
WhiteOut=9
class VirtualSystemDescriptionType:
def __init__(self,mgr,handle,isarray=False):
self.mgr=mgr
self.isarray = isarray
if isinstance(handle,basestring):
self.handle=VirtualSystemDescriptionType._ValueMap[handle]
else:
self.handle=handle
def __eq__(self,other):
if isinstance(other,VirtualSystemDescriptionType):
return self.handle == other.handle
if isinstance(other,int):
return self.handle == other
if isinstance(other,basestring):
return str(self) == other
return False
def __ne__(self,other):
if isinstance(other,VirtualSystemDescriptionType):
return self.handle != other.handle
if isinstance(other,int):
return self.handle != other
if isinstance(other,basestring):
return str(self) != other
return True
def __str__(self):
return VirtualSystemDescriptionType._NameMap[self.handle]
def __int__(self):
return self.handle
_NameMap={1:'Ignore',2:'OS',3:'Name',4:'Product',5:'Vendor',6:'Version',7:'ProductUrl',8:'VendorUrl',9:'Description',10:'License',11:'Miscellaneous',12:'CPU',13:'Memory',14:'HardDiskControllerIDE',15:'HardDiskControllerSATA',16:'HardDiskControllerSCSI',17:'HardDiskControllerSAS',18:'HardDiskImage',19:'Floppy',20:'CDROM',21:'NetworkAdapter',22:'USBController',23:'SoundCard'}
_ValueMap={
'Ignore':1,
'OS':2,
'Name':3,
'Product':4,
'Vendor':5,
'Version':6,
'ProductUrl':7,
'VendorUrl':8,
'Description':9,
'License':10,
'Miscellaneous':11,
'CPU':12,
'Memory':13,
'HardDiskControllerIDE':14,
'HardDiskControllerSATA':15,
'HardDiskControllerSCSI':16,
'HardDiskControllerSAS':17,
'HardDiskImage':18,
'Floppy':19,
'CDROM':20,
'NetworkAdapter':21,
'USBController':22,
'SoundCard':23}
Ignore=1
OS=2
Name=3
Product=4
Vendor=5
Version=6
ProductUrl=7
VendorUrl=8
Description=9
License=10
Miscellaneous=11
CPU=12
Memory=13
HardDiskControllerIDE=14
HardDiskControllerSATA=15
HardDiskControllerSCSI=16
HardDiskControllerSAS=17
HardDiskImage=18
Floppy=19
CDROM=20
NetworkAdapter=21
USBController=22
SoundCard=23
class VirtualSystemDescriptionValueType:
def __init__(self,mgr,handle):
self.mgr=mgr
if isinstance(handle,basestring):
self.handle=VirtualSystemDescriptionValueType._ValueMap[handle]
else:
self.handle=handle
def __eq__(self,other):
if isinstance(other,VirtualSystemDescriptionValueType):
return self.handle == other.handle
if isinstance(other,int):
return self.handle == other
if isinstance(other,basestring):
return str(self) == other
return False
def __ne__(self,other):
if isinstance(other,VirtualSystemDescriptionValueType):
return self.handle != other.handle
if isinstance(other,int):
return self.handle != other
if isinstance(other,basestring):
return str(self) != other
return True
def __str__(self):
return VirtualSystemDescriptionValueType._NameMap[self.handle]
def __int__(self):
return self.handle
_NameMap={1:'Reference',2:'Original',3:'Auto',4:'ExtraConfig'}
_ValueMap={
'Reference':1,
'Original':2,
'Auto':3,
'ExtraConfig':4}
Reference=1
Original=2
Auto=3
ExtraConfig=4
class CleanupMode:
def __init__(self,mgr,handle):
self.mgr=mgr
if isinstance(handle,basestring):
self.handle=CleanupMode._ValueMap[handle]
else:
self.handle=handle
def __eq__(self,other):
if isinstance(other,CleanupMode):
return self.handle == other.handle
if isinstance(other,int):
return self.handle == other
if isinstance(other,basestring):
return str(self) == other
return False
def __ne__(self,other):
if isinstance(other,CleanupMode):
return self.handle != other.handle
if isinstance(other,int):
return self.handle != other
if isinstance(other,basestring):
return str(self) != other
return True
def __str__(self):
return CleanupMode._NameMap[self.handle]
def __int__(self):
return self.handle
_NameMap={1:'UnregisterOnly',2:'DetachAllReturnNone',3:'DetachAllReturnHardDisksOnly',4:'Full'}
_ValueMap={
'UnregisterOnly':1,
'DetachAllReturnNone':2,
'DetachAllReturnHardDisksOnly':3,
'Full':4}
UnregisterOnly=1
DetachAllReturnNone=2
DetachAllReturnHardDisksOnly=3
Full=4
class HostNetworkInterfaceMediumType:
def __init__(self,mgr,handle):
self.mgr=mgr
if isinstance(handle,basestring):
self.handle=HostNetworkInterfaceMediumType._ValueMap[handle]
else:
self.handle=handle
def __eq__(self,other):
if isinstance(other,HostNetworkInterfaceMediumType):
return self.handle == other.handle
if isinstance(other,int):
return self.handle == other
if isinstance(other,basestring):
return str(self) == other
return False
def __ne__(self,other):
if isinstance(other,HostNetworkInterfaceMediumType):
return self.handle != other.handle
if isinstance(other,int):
return self.handle != other
if isinstance(other,basestring):
return str(self) != other
return True
def __str__(self):
return HostNetworkInterfaceMediumType._NameMap[self.handle]
def __int__(self):
return self.handle
_NameMap={0:'Unknown',1:'Ethernet',2:'PPP',3:'SLIP'}
_ValueMap={
'Unknown':0,
'Ethernet':1,
'PPP':2,
'SLIP':3}
Unknown=0
Ethernet=1
PPP=2
SLIP=3
class HostNetworkInterfaceStatus:
def __init__(self,mgr,handle):
self.mgr=mgr
if isinstance(handle,basestring):
self.handle=HostNetworkInterfaceStatus._ValueMap[handle]
else:
self.handle=handle
def __eq__(self,other):
if isinstance(other,HostNetworkInterfaceStatus):
return self.handle == other.handle
if isinstance(other,int):
return self.handle == other
if isinstance(other,basestring):
return str(self) == other
return False
def __ne__(self,other):
if isinstance(other,HostNetworkInterfaceStatus):
return self.handle != other.handle
if isinstance(other,int):
return self.handle != other
if isinstance(other,basestring):
return str(self) != other
return True
def __str__(self):
return HostNetworkInterfaceStatus._NameMap[self.handle]
def __int__(self):
return self.handle
_NameMap={0:'Unknown',1:'Up',2:'Down'}
_ValueMap={
'Unknown':0,
'Up':1,
'Down':2}
Unknown=0
Up=1
Down=2
class HostNetworkInterfaceType:
def __init__(self,mgr,handle):
self.mgr=mgr
if isinstance(handle,basestring):
self.handle=HostNetworkInterfaceType._ValueMap[handle]
else:
self.handle=handle
def __eq__(self,other):
if isinstance(other,HostNetworkInterfaceType):
return self.handle == other.handle
if isinstance(other,int):
return self.handle == other
if isinstance(other,basestring):
return str(self) == other
return False
def __ne__(self,other):
if isinstance(other,HostNetworkInterfaceType):
return self.handle != other.handle
if isinstance(other,int):
return self.handle != other
if isinstance(other,basestring):
return str(self) != other
return True
def __str__(self):
return HostNetworkInterfaceType._NameMap[self.handle]
def __int__(self):
return self.handle
_NameMap={1:'Bridged',2:'HostOnly'}
_ValueMap={
'Bridged':1,
'HostOnly':2}
Bridged=1
HostOnly=2
class AdditionsRunLevelType:
def __init__(self,mgr,handle):
self.mgr=mgr
if isinstance(handle,basestring):
self.handle=AdditionsRunLevelType._ValueMap[handle]
else:
self.handle=handle
def __eq__(self,other):
if isinstance(other,AdditionsRunLevelType):
return self.handle == other.handle
if isinstance(other,int):
return self.handle == other
if isinstance(other,basestring):
return str(self) == other
return False
def __ne__(self,other):
if isinstance(other,AdditionsRunLevelType):
return self.handle != other.handle
if isinstance(other,int):
return self.handle != other
if isinstance(other,basestring):
return str(self) != other
return True
def __str__(self):
return AdditionsRunLevelType._NameMap[self.handle]
def __int__(self):
return self.handle
_NameMap={0:'None',1:'System',2:'Userland',3:'Desktop'}
_ValueMap={
'None':0,
'System':1,
'Userland':2,
'Desktop':3}
_None=0
System=1
Userland=2
Desktop=3
class ExecuteProcessFlag:
def __init__(self,mgr,handle):
self.mgr=mgr
if isinstance(handle,basestring):
self.handle=ExecuteProcessFlag._ValueMap[handle]
else:
self.handle=handle
def __eq__(self,other):
if isinstance(other,ExecuteProcessFlag):
return self.handle == other.handle
if isinstance(other,int):
return self.handle == other
if isinstance(other,basestring):
return str(self) == other
return False
def __ne__(self,other):
if isinstance(other,ExecuteProcessFlag):
return self.handle != other.handle
if isinstance(other,int):
return self.handle != other
if isinstance(other,basestring):
return str(self) != other
return True
def __str__(self):
return ExecuteProcessFlag._NameMap[self.handle]
def __int__(self):
return self.handle
_NameMap={0:'None',2:'IgnoreOrphanedProcesses'}
_ValueMap={
'None':0,
'IgnoreOrphanedProcesses':2}
_None=0
IgnoreOrphanedProcesses=2
class ProcessInputFlag:
def __init__(self,mgr,handle):
self.mgr=mgr
if isinstance(handle,basestring):
self.handle=ProcessInputFlag._ValueMap[handle]
else:
self.handle=handle
def __eq__(self,other):
if isinstance(other,ProcessInputFlag):
return self.handle == other.handle
if isinstance(other,int):
return self.handle == other
if isinstance(other,basestring):
return str(self) == other
return False
def __ne__(self,other):
if isinstance(other,ProcessInputFlag):
return self.handle != other.handle
if isinstance(other,int):
return self.handle != other
if isinstance(other,basestring):
return str(self) != other
return True
def __str__(self):
return ProcessInputFlag._NameMap[self.handle]
def __int__(self):
return self.handle
_NameMap={0:'None',1:'EndOfFile'}
_ValueMap={
'None':0,
'EndOfFile':1}
_None=0
EndOfFile=1
class CopyFileFlag:
def __init__(self,mgr,handle):
self.mgr=mgr
if isinstance(handle,basestring):
self.handle=CopyFileFlag._ValueMap[handle]
else:
self.handle=handle
def __eq__(self,other):
if isinstance(other,CopyFileFlag):
return self.handle == other.handle
if isinstance(other,int):
return self.handle == other
if isinstance(other,basestring):
return str(self) == other
return False
def __ne__(self,other):
if isinstance(other,CopyFileFlag):
return self.handle != other.handle
if isinstance(other,int):
return self.handle != other
if isinstance(other,basestring):
return str(self) != other
return True
def __str__(self):
return CopyFileFlag._NameMap[self.handle]
def __int__(self):
return self.handle
_NameMap={0:'None',1:'Recursive',2:'Update',4:'FollowLinks'}
_ValueMap={
'None':0,
'Recursive':1,
'Update':2,
'FollowLinks':4}
_None=0
Recursive=1
Update=2
FollowLinks=4
class MediumState:
def __init__(self,mgr,handle):
self.mgr=mgr
if isinstance(handle,basestring):
self.handle=MediumState._ValueMap[handle]
else:
self.handle=handle
def __eq__(self,other):
if isinstance(other,MediumState):
return self.handle == other.handle
if isinstance(other,int):
return self.handle == other
if isinstance(other,basestring):
return str(self) == other
return False
def __ne__(self,other):
if isinstance(other,MediumState):
return self.handle != other.handle
if isinstance(other,int):
return self.handle != other
if isinstance(other,basestring):
return str(self) != other
return True
def __str__(self):
return MediumState._NameMap[self.handle]
def __int__(self):
return self.handle
_NameMap={0:'NotCreated',1:'Created',2:'LockedRead',3:'LockedWrite',4:'Inaccessible',5:'Creating',6:'Deleting'}
_ValueMap={
'NotCreated':0,
'Created':1,
'LockedRead':2,
'LockedWrite':3,
'Inaccessible':4,
'Creating':5,
'Deleting':6}
NotCreated=0
Created=1
LockedRead=2
LockedWrite=3
Inaccessible=4
Creating=5
Deleting=6
class MediumType:
def __init__(self,mgr,handle):
self.mgr=mgr
if isinstance(handle,basestring):
self.handle=MediumType._ValueMap[handle]
else:
self.handle=handle
def __eq__(self,other):
if isinstance(other,MediumType):
return self.handle == other.handle
if isinstance(other,int):
return self.handle == other
if isinstance(other,basestring):
return str(self) == other
return False
def __ne__(self,other):
if isinstance(other,MediumType):
return self.handle != other.handle
if isinstance(other,int):
return self.handle != other
if isinstance(other,basestring):
return str(self) != other
return True
def __str__(self):
return MediumType._NameMap[self.handle]
def __int__(self):
return self.handle
_NameMap={0:'Normal',1:'Immutable',2:'Writethrough',3:'Shareable',4:'Readonly'}
_ValueMap={
'Normal':0,
'Immutable':1,
'Writethrough':2,
'Shareable':3,
'Readonly':4}
Normal=0
Immutable=1
Writethrough=2
Shareable=3
Readonly=4
class MediumVariant:
def __init__(self,mgr,handle):
self.mgr=mgr
if isinstance(handle,basestring):
self.handle=MediumVariant._ValueMap[handle]
else:
self.handle=handle
def __eq__(self,other):
if isinstance(other,MediumVariant):
return self.handle == other.handle
if isinstance(other,int):
return self.handle == other
if isinstance(other,basestring):
return str(self) == other
return False
def __ne__(self,other):
if isinstance(other,MediumVariant):
return self.handle != other.handle
if isinstance(other,int):
return self.handle != other
if isinstance(other,basestring):
return str(self) != other
return True
def __str__(self):
return MediumVariant._NameMap[self.handle]
def __int__(self):
return self.handle
_NameMap={0:'Standard',0x01:'VmdkSplit2G',0x04:'VmdkStreamOptimized',0x08:'VmdkESX',0x10000:'Fixed',0x20000:'Diff'}
_ValueMap={
'Standard':0,
'VmdkSplit2G':0x01,
'VmdkStreamOptimized':0x04,
'VmdkESX':0x08,
'Fixed':0x10000,
'Diff':0x20000}
Standard=0
VmdkSplit2G=0x01
VmdkStreamOptimized=0x04
VmdkESX=0x08
Fixed=0x10000
Diff=0x20000
class DataType:
def __init__(self,mgr,handle):
self.mgr=mgr
if isinstance(handle,basestring):
self.handle=DataType._ValueMap[handle]
else:
self.handle=handle
def __eq__(self,other):
if isinstance(other,DataType):
return self.handle == other.handle
if isinstance(other,int):
return self.handle == other
if isinstance(other,basestring):
return str(self) == other
return False
def __ne__(self,other):
if isinstance(other,DataType):
return self.handle != other.handle
if isinstance(other,int):
return self.handle != other
if isinstance(other,basestring):
return str(self) != other
return True
def __str__(self):
return DataType._NameMap[self.handle]
def __int__(self):
return self.handle
_NameMap={0:'Int32',1:'Int8',2:'String'}
_ValueMap={
'Int32':0,
'Int8':1,
'String':2}
Int32=0
Int8=1
String=2
class DataFlags:
def __init__(self,mgr,handle):
self.mgr=mgr
if isinstance(handle,basestring):
self.handle=DataFlags._ValueMap[handle]
else:
self.handle=handle
def __eq__(self,other):
if isinstance(other,DataFlags):
return self.handle == other.handle
if isinstance(other,int):
return self.handle == other
if isinstance(other,basestring):
return str(self) == other
return False
def __ne__(self,other):
if isinstance(other,DataFlags):
return self.handle != other.handle
if isinstance(other,int):
return self.handle != other
if isinstance(other,basestring):
return str(self) != other
return True
def __str__(self):
return DataFlags._NameMap[self.handle]
def __int__(self):
return self.handle
_NameMap={0x00:'None',0x01:'Mandatory',0x02:'Expert',0x04:'Array',0x07:'FlagMask'}
_ValueMap={
'None':0x00,
'Mandatory':0x01,
'Expert':0x02,
'Array':0x04,
'FlagMask':0x07}
_None=0x00
Mandatory=0x01
Expert=0x02
Array=0x04
FlagMask=0x07
class MediumFormatCapabilities:
def __init__(self,mgr,handle):
self.mgr=mgr
if isinstance(handle,basestring):
self.handle=MediumFormatCapabilities._ValueMap[handle]
else:
self.handle=handle
def __eq__(self,other):
if isinstance(other,MediumFormatCapabilities):
return self.handle == other.handle
if isinstance(other,int):
return self.handle == other
if isinstance(other,basestring):
return str(self) == other
return False
def __ne__(self,other):
if isinstance(other,MediumFormatCapabilities):
return self.handle != other.handle
if isinstance(other,int):
return self.handle != other
if isinstance(other,basestring):
return str(self) != other
return True
def __str__(self):
return MediumFormatCapabilities._NameMap[self.handle]
def __int__(self):
return self.handle
_NameMap={0x01:'Uuid',0x02:'CreateFixed',0x04:'CreateDynamic',0x08:'CreateSplit2G',0x10:'Differencing',0x20:'Asynchronous',0x40:'File',0x80:'Properties',0x100:'TcpNetworking',0x200:'VFS',0x3FF:'CapabilityMask'}
_ValueMap={
'Uuid':0x01,
'CreateFixed':0x02,
'CreateDynamic':0x04,
'CreateSplit2G':0x08,
'Differencing':0x10,
'Asynchronous':0x20,
'File':0x40,
'Properties':0x80,
'TcpNetworking':0x100,
'VFS':0x200,
'CapabilityMask':0x3FF}
Uuid=0x01
CreateFixed=0x02
CreateDynamic=0x04
CreateSplit2G=0x08
Differencing=0x10
Asynchronous=0x20
File=0x40
Properties=0x80
TcpNetworking=0x100
VFS=0x200
CapabilityMask=0x3FF
class MouseButtonState:
def __init__(self,mgr,handle):
self.mgr=mgr
if isinstance(handle,basestring):
self.handle=MouseButtonState._ValueMap[handle]
else:
self.handle=handle
def __eq__(self,other):
if isinstance(other,MouseButtonState):
return self.handle == other.handle
if isinstance(other,int):
return self.handle == other
if isinstance(other,basestring):
return str(self) == other
return False
def __ne__(self,other):
if isinstance(other,MouseButtonState):
return self.handle != other.handle
if isinstance(other,int):
return self.handle != other
if isinstance(other,basestring):
return str(self) != other
return True
def __str__(self):
return MouseButtonState._NameMap[self.handle]
def __int__(self):
return self.handle
_NameMap={0x01:'LeftButton',0x02:'RightButton',0x04:'MiddleButton',0x08:'WheelUp',0x10:'WheelDown',0x20:'XButton1',0x40:'XButton2',0x7F:'MouseStateMask'}
_ValueMap={
'LeftButton':0x01,
'RightButton':0x02,
'MiddleButton':0x04,
'WheelUp':0x08,
'WheelDown':0x10,
'XButton1':0x20,
'XButton2':0x40,
'MouseStateMask':0x7F}
LeftButton=0x01
RightButton=0x02
MiddleButton=0x04
WheelUp=0x08
WheelDown=0x10
XButton1=0x20
XButton2=0x40
MouseStateMask=0x7F
class FramebufferPixelFormat:
def __init__(self,mgr,handle):
self.mgr=mgr
if isinstance(handle,basestring):
self.handle=FramebufferPixelFormat._ValueMap[handle]
else:
self.handle=handle
def __eq__(self,other):
if isinstance(other,FramebufferPixelFormat):
return self.handle == other.handle
if isinstance(other,int):
return self.handle == other
if isinstance(other,basestring):
return str(self) == other
return False
def __ne__(self,other):
if isinstance(other,FramebufferPixelFormat):
return self.handle != other.handle
if isinstance(other,int):
return self.handle != other
if isinstance(other,basestring):
return str(self) != other
return True
def __str__(self):
return FramebufferPixelFormat._NameMap[self.handle]
def __int__(self):
return self.handle
_NameMap={0:'Opaque',0x32424752:'FOURCC_RGB'}
_ValueMap={
'Opaque':0,
'FOURCC_RGB':0x32424752}
Opaque=0
FOURCC_RGB=0x32424752
class NetworkAttachmentType:
def __init__(self,mgr,handle):
self.mgr=mgr
if isinstance(handle,basestring):
self.handle=NetworkAttachmentType._ValueMap[handle]
else:
self.handle=handle
def __eq__(self,other):
if isinstance(other,NetworkAttachmentType):
return self.handle == other.handle
if isinstance(other,int):
return self.handle == other
if isinstance(other,basestring):
return str(self) == other
return False
def __ne__(self,other):
if isinstance(other,NetworkAttachmentType):
return self.handle != other.handle
if isinstance(other,int):
return self.handle != other
if isinstance(other,basestring):
return str(self) != other
return True
def __str__(self):
return NetworkAttachmentType._NameMap[self.handle]
def __int__(self):
return self.handle
_NameMap={0:'Null',1:'NAT',2:'Bridged',3:'Internal',4:'HostOnly',5:'VDE'}
_ValueMap={
'Null':0,
'NAT':1,
'Bridged':2,
'Internal':3,
'HostOnly':4,
'VDE':5}
Null=0
NAT=1
Bridged=2
Internal=3
HostOnly=4
VDE=5
class NetworkAdapterType:
def __init__(self,mgr,handle):
self.mgr=mgr
if isinstance(handle,basestring):
self.handle=NetworkAdapterType._ValueMap[handle]
else:
self.handle=handle
def __eq__(self,other):
if isinstance(other,NetworkAdapterType):
return self.handle == other.handle
if isinstance(other,int):
return self.handle == other
if isinstance(other,basestring):
return str(self) == other
return False
def __ne__(self,other):
if isinstance(other,NetworkAdapterType):
return self.handle != other.handle
if isinstance(other,int):
return self.handle != other
if isinstance(other,basestring):
return str(self) != other
return True
def __str__(self):
return NetworkAdapterType._NameMap[self.handle]
def __int__(self):
return self.handle
_NameMap={0:'Null',1:'Am79C970A',2:'Am79C973',3:'I82540EM',4:'I82543GC',5:'I82545EM',6:'Virtio'}
_ValueMap={
'Null':0,
'Am79C970A':1,
'Am79C973':2,
'I82540EM':3,
'I82543GC':4,
'I82545EM':5,
'Virtio':6}
Null=0
Am79C970A=1
Am79C973=2
I82540EM=3
I82543GC=4
I82545EM=5
Virtio=6
class PortMode:
def __init__(self,mgr,handle):
self.mgr=mgr
if isinstance(handle,basestring):
self.handle=PortMode._ValueMap[handle]
else:
self.handle=handle
def __eq__(self,other):
if isinstance(other,PortMode):
return self.handle == other.handle
if isinstance(other,int):
return self.handle == other
if isinstance(other,basestring):
return str(self) == other
return False
def __ne__(self,other):
if isinstance(other,PortMode):
return self.handle != other.handle
if isinstance(other,int):
return self.handle != other
if isinstance(other,basestring):
return str(self) != other
return True
def __str__(self):
return PortMode._NameMap[self.handle]
def __int__(self):
return self.handle
_NameMap={0:'Disconnected',1:'HostPipe',2:'HostDevice',3:'RawFile'}
_ValueMap={
'Disconnected':0,
'HostPipe':1,
'HostDevice':2,
'RawFile':3}
Disconnected=0
HostPipe=1
HostDevice=2
RawFile=3
class USBDeviceState:
def __init__(self,mgr,handle):
self.mgr=mgr
if isinstance(handle,basestring):
self.handle=USBDeviceState._ValueMap[handle]
else:
self.handle=handle
def __eq__(self,other):
if isinstance(other,USBDeviceState):
return self.handle == other.handle
if isinstance(other,int):
return self.handle == other
if isinstance(other,basestring):
return str(self) == other
return False
def __ne__(self,other):
if isinstance(other,USBDeviceState):
return self.handle != other.handle
if isinstance(other,int):
return self.handle != other
if isinstance(other,basestring):
return str(self) != other
return True
def __str__(self):
return USBDeviceState._NameMap[self.handle]
def __int__(self):
return self.handle
_NameMap={0:'NotSupported',1:'Unavailable',2:'Busy',3:'Available',4:'Held',5:'Captured'}
_ValueMap={
'NotSupported':0,
'Unavailable':1,
'Busy':2,
'Available':3,
'Held':4,
'Captured':5}
NotSupported=0
Unavailable=1
Busy=2
Available=3
Held=4
Captured=5
class USBDeviceFilterAction:
def __init__(self,mgr,handle):
self.mgr=mgr
if isinstance(handle,basestring):
self.handle=USBDeviceFilterAction._ValueMap[handle]
else:
self.handle=handle
def __eq__(self,other):
if isinstance(other,USBDeviceFilterAction):
return self.handle == other.handle
if isinstance(other,int):
return self.handle == other
if isinstance(other,basestring):
return str(self) == other
return False
def __ne__(self,other):
if isinstance(other,USBDeviceFilterAction):
return self.handle != other.handle
if isinstance(other,int):
return self.handle != other
if isinstance(other,basestring):
return str(self) != other
return True
def __str__(self):
return USBDeviceFilterAction._NameMap[self.handle]
def __int__(self):
return self.handle
_NameMap={0:'Null',1:'Ignore',2:'Hold'}
_ValueMap={
'Null':0,
'Ignore':1,
'Hold':2}
Null=0
Ignore=1
Hold=2
class AudioDriverType:
def __init__(self,mgr,handle):
self.mgr=mgr
if isinstance(handle,basestring):
self.handle=AudioDriverType._ValueMap[handle]
else:
self.handle=handle
def __eq__(self,other):
if isinstance(other,AudioDriverType):
return self.handle == other.handle
if isinstance(other,int):
return self.handle == other
if isinstance(other,basestring):
return str(self) == other
return False
def __ne__(self,other):
if isinstance(other,AudioDriverType):
return self.handle != other.handle
if isinstance(other,int):
return self.handle != other
if isinstance(other,basestring):
return str(self) != other
return True
def __str__(self):
return AudioDriverType._NameMap[self.handle]
def __int__(self):
return self.handle
_NameMap={0:'Null',1:'WinMM',2:'OSS',3:'ALSA',4:'DirectSound',5:'CoreAudio',6:'MMPM',7:'Pulse',8:'SolAudio'}
_ValueMap={
'Null':0,
'WinMM':1,
'OSS':2,
'ALSA':3,
'DirectSound':4,
'CoreAudio':5,
'MMPM':6,
'Pulse':7,
'SolAudio':8}
Null=0
WinMM=1
OSS=2
ALSA=3
DirectSound=4
CoreAudio=5
MMPM=6
Pulse=7
SolAudio=8
class AudioControllerType:
def __init__(self,mgr,handle):
self.mgr=mgr
if isinstance(handle,basestring):
self.handle=AudioControllerType._ValueMap[handle]
else:
self.handle=handle
def __eq__(self,other):
if isinstance(other,AudioControllerType):
return self.handle == other.handle
if isinstance(other,int):
return self.handle == other
if isinstance(other,basestring):
return str(self) == other
return False
def __ne__(self,other):
if isinstance(other,AudioControllerType):
return self.handle != other.handle
if isinstance(other,int):
return self.handle != other
if isinstance(other,basestring):
return str(self) != other
return True
def __str__(self):
return AudioControllerType._NameMap[self.handle]
def __int__(self):
return self.handle
_NameMap={0:'AC97',1:'SB16',2:'HDA'}
_ValueMap={
'AC97':0,
'SB16':1,
'HDA':2}
AC97=0
SB16=1
HDA=2
class AuthType:
def __init__(self,mgr,handle):
self.mgr=mgr
if isinstance(handle,basestring):
self.handle=AuthType._ValueMap[handle]
else:
self.handle=handle
def __eq__(self,other):
if isinstance(other,AuthType):
return self.handle == other.handle
if isinstance(other,int):
return self.handle == other
if isinstance(other,basestring):
return str(self) == other
return False
def __ne__(self,other):
if isinstance(other,AuthType):
return self.handle != other.handle
if isinstance(other,int):
return self.handle != other
if isinstance(other,basestring):
return str(self) != other
return True
def __str__(self):
return AuthType._NameMap[self.handle]
def __int__(self):
return self.handle
_NameMap={0:'Null',1:'External',2:'Guest'}
_ValueMap={
'Null':0,
'External':1,
'Guest':2}
Null=0
External=1
Guest=2
class StorageBus:
def __init__(self,mgr,handle):
self.mgr=mgr
if isinstance(handle,basestring):
self.handle=StorageBus._ValueMap[handle]
else:
self.handle=handle
def __eq__(self,other):
if isinstance(other,StorageBus):
return self.handle == other.handle
if isinstance(other,int):
return self.handle == other
if isinstance(other,basestring):
return str(self) == other
return False
def __ne__(self,other):
if isinstance(other,StorageBus):
return self.handle != other.handle
if isinstance(other,int):
return self.handle != other
if isinstance(other,basestring):
return str(self) != other
return True
def __str__(self):
return StorageBus._NameMap[self.handle]
def __int__(self):
return self.handle
_NameMap={0:'Null',1:'IDE',2:'SATA',3:'SCSI',4:'Floppy',5:'SAS'}
_ValueMap={
'Null':0,
'IDE':1,
'SATA':2,
'SCSI':3,
'Floppy':4,
'SAS':5}
Null=0
IDE=1
SATA=2
SCSI=3
Floppy=4
SAS=5
class StorageControllerType:
def __init__(self,mgr,handle):
self.mgr=mgr
if isinstance(handle,basestring):
self.handle=StorageControllerType._ValueMap[handle]
else:
self.handle=handle
def __eq__(self,other):
if isinstance(other,StorageControllerType):
return self.handle == other.handle
if isinstance(other,int):
return self.handle == other
if isinstance(other,basestring):
return str(self) == other
return False
def __ne__(self,other):
if isinstance(other,StorageControllerType):
return self.handle != other.handle
if isinstance(other,int):
return self.handle != other
if isinstance(other,basestring):
return str(self) != other
return True
def __str__(self):
return StorageControllerType._NameMap[self.handle]
def __int__(self):
return self.handle
_NameMap={0:'Null',1:'LsiLogic',2:'BusLogic',3:'IntelAhci',4:'PIIX3',5:'PIIX4',6:'ICH6',7:'I82078',8:'LsiLogicSas'}
_ValueMap={
'Null':0,
'LsiLogic':1,
'BusLogic':2,
'IntelAhci':3,
'PIIX3':4,
'PIIX4':5,
'ICH6':6,
'I82078':7,
'LsiLogicSas':8}
Null=0
LsiLogic=1
BusLogic=2
IntelAhci=3
PIIX3=4
PIIX4=5
ICH6=6
I82078=7
LsiLogicSas=8
class ChipsetType:
def __init__(self,mgr,handle):
self.mgr=mgr
if isinstance(handle,basestring):
self.handle=ChipsetType._ValueMap[handle]
else:
self.handle=handle
def __eq__(self,other):
if isinstance(other,ChipsetType):
return self.handle == other.handle
if isinstance(other,int):
return self.handle == other
if isinstance(other,basestring):
return str(self) == other
return False
def __ne__(self,other):
if isinstance(other,ChipsetType):
return self.handle != other.handle
if isinstance(other,int):
return self.handle != other
if isinstance(other,basestring):
return str(self) != other
return True
def __str__(self):
return ChipsetType._NameMap[self.handle]
def __int__(self):
return self.handle
_NameMap={0:'Null',1:'PIIX3',2:'ICH9'}
_ValueMap={
'Null':0,
'PIIX3':1,
'ICH9':2}
Null=0
PIIX3=1
ICH9=2
class NATAliasMode:
def __init__(self,mgr,handle):
self.mgr=mgr
if isinstance(handle,basestring):
self.handle=NATAliasMode._ValueMap[handle]
else:
self.handle=handle
def __eq__(self,other):
if isinstance(other,NATAliasMode):
return self.handle == other.handle
if isinstance(other,int):
return self.handle == other
if isinstance(other,basestring):
return str(self) == other
return False
def __ne__(self,other):
if isinstance(other,NATAliasMode):
return self.handle != other.handle
if isinstance(other,int):
return self.handle != other
if isinstance(other,basestring):
return str(self) != other
return True
def __str__(self):
return NATAliasMode._NameMap[self.handle]
def __int__(self):
return self.handle
_NameMap={0x1:'AliasLog',0x02:'AliasProxyOnly',0x04:'AliasUseSamePorts'}
_ValueMap={
'AliasLog':0x1,
'AliasProxyOnly':0x02,
'AliasUseSamePorts':0x04}
AliasLog=0x1
AliasProxyOnly=0x02
AliasUseSamePorts=0x04
class NATProtocol:
def __init__(self,mgr,handle):
self.mgr=mgr
if isinstance(handle,basestring):
self.handle=NATProtocol._ValueMap[handle]
else:
self.handle=handle
def __eq__(self,other):
if isinstance(other,NATProtocol):
return self.handle == other.handle
if isinstance(other,int):
return self.handle == other
if isinstance(other,basestring):
return str(self) == other
return False
def __ne__(self,other):
if isinstance(other,NATProtocol):
return self.handle != other.handle
if isinstance(other,int):
return self.handle != other
if isinstance(other,basestring):
return str(self) != other
return True
def __str__(self):
return NATProtocol._NameMap[self.handle]
def __int__(self):
return self.handle
_NameMap={0:'UDP',1:'TCP'}
_ValueMap={
'UDP':0,
'TCP':1}
UDP=0
TCP=1
class VBoxEventType:
def __init__(self,mgr,handle):
self.mgr=mgr
if isinstance(handle,basestring):
self.handle=VBoxEventType._ValueMap[handle]
else:
self.handle=handle
def __eq__(self,other):
if isinstance(other,VBoxEventType):
return self.handle == other.handle
if isinstance(other,int):
return self.handle == other
if isinstance(other,basestring):
return str(self) == other
return False
def __ne__(self,other):
if isinstance(other,VBoxEventType):
return self.handle != other.handle
if isinstance(other,int):
return self.handle != other
if isinstance(other,basestring):
return str(self) != other
return True
def __str__(self):
return VBoxEventType._NameMap[self.handle]
def __int__(self):
return self.handle
_NameMap={0:'Invalid',1:'Any',2:'Vetoable',3:'MachineEvent',4:'SnapshotEvent',5:'InputEvent',31:'LastWildcard',32:'OnMachineStateChanged',33:'OnMachineDataChanged',34:'OnExtraDataChanged',35:'OnExtraDataCanChange',36:'OnMediumRegistered',37:'OnMachineRegistered',38:'OnSessionStateChanged',39:'OnSnapshotTaken',40:'OnSnapshotDeleted',41:'OnSnapshotChanged',42:'OnGuestPropertyChanged',43:'OnMousePointerShapeChanged',44:'OnMouseCapabilityChanged',45:'OnKeyboardLedsChanged',46:'OnStateChanged',47:'OnAdditionsStateChanged',48:'OnNetworkAdapterChanged',49:'OnSerialPortChanged',50:'OnParallelPortChanged',51:'OnStorageControllerChanged',52:'OnMediumChanged',53:'OnVRDEServerChanged',54:'OnUSBControllerChanged',55:'OnUSBDeviceStateChanged',56:'OnSharedFolderChanged',57:'OnRuntimeError',58:'OnCanShowWindow',59:'OnShowWindow',60:'OnCPUChanged',61:'OnVRDEServerInfoChanged',62:'OnEventSourceChanged',63:'OnCPUExecutionCapChanged',64:'OnGuestKeyboardEvent',65:'OnGuestMouseEvent',66:'Last'}
_ValueMap={
'Invalid':0,
'Any':1,
'Vetoable':2,
'MachineEvent':3,
'SnapshotEvent':4,
'InputEvent':5,
'LastWildcard':31,
'OnMachineStateChanged':32,
'OnMachineDataChanged':33,
'OnExtraDataChanged':34,
'OnExtraDataCanChange':35,
'OnMediumRegistered':36,
'OnMachineRegistered':37,
'OnSessionStateChanged':38,
'OnSnapshotTaken':39,
'OnSnapshotDeleted':40,
'OnSnapshotChanged':41,
'OnGuestPropertyChanged':42,
'OnMousePointerShapeChanged':43,
'OnMouseCapabilityChanged':44,
'OnKeyboardLedsChanged':45,
'OnStateChanged':46,
'OnAdditionsStateChanged':47,
'OnNetworkAdapterChanged':48,
'OnSerialPortChanged':49,
'OnParallelPortChanged':50,
'OnStorageControllerChanged':51,
'OnMediumChanged':52,
'OnVRDEServerChanged':53,
'OnUSBControllerChanged':54,
'OnUSBDeviceStateChanged':55,
'OnSharedFolderChanged':56,
'OnRuntimeError':57,
'OnCanShowWindow':58,
'OnShowWindow':59,
'OnCPUChanged':60,
'OnVRDEServerInfoChanged':61,
'OnEventSourceChanged':62,
'OnCPUExecutionCapChanged':63,
'OnGuestKeyboardEvent':64,
'OnGuestMouseEvent':65,
'Last':66}
Invalid=0
Any=1
Vetoable=2
MachineEvent=3
SnapshotEvent=4
InputEvent=5
LastWildcard=31
OnMachineStateChanged=32
OnMachineDataChanged=33
OnExtraDataChanged=34
OnExtraDataCanChange=35
OnMediumRegistered=36
OnMachineRegistered=37
OnSessionStateChanged=38
OnSnapshotTaken=39
OnSnapshotDeleted=40
OnSnapshotChanged=41
OnGuestPropertyChanged=42
OnMousePointerShapeChanged=43
OnMouseCapabilityChanged=44
OnKeyboardLedsChanged=45
OnStateChanged=46
OnAdditionsStateChanged=47
OnNetworkAdapterChanged=48
OnSerialPortChanged=49
OnParallelPortChanged=50
OnStorageControllerChanged=51
OnMediumChanged=52
OnVRDEServerChanged=53
OnUSBControllerChanged=54
OnUSBDeviceStateChanged=55
OnSharedFolderChanged=56
OnRuntimeError=57
OnCanShowWindow=58
OnShowWindow=59
OnCPUChanged=60
OnVRDEServerInfoChanged=61
OnEventSourceChanged=62
OnCPUExecutionCapChanged=63
OnGuestKeyboardEvent=64
OnGuestMouseEvent=65
Last=66
class IWebsessionManager2(IWebsessionManager):
def __init__(self, url):
self.url = url
self.port = None
self.handle = None
self.mgr = self
def getPort(self):
if self.port is None:
try:
self.port = vboxServiceLocator().getvboxPortType(self.url)
except:
self.port = vboxServiceLocator().getvboxServicePort(self.url)
return self.port
def logoff(self, _arg_refIVirtualBox):
req=IWebsessionManager_logoffRequestMsg()
req._this=self.handle
req._refIVirtualBox=_arg_refIVirtualBox
val=self.mgr.getPort().IWebsessionManager_logoff(req)
""" Important!!! """
self.port.binding.h.close()
return
| mit |
chafique-delli/OpenUpgrade | addons/mrp/__init__.py | 437 | 1165 | # -*- 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/>.
#
##############################################################################
import mrp
import stock
import product
import wizard
import report
import company
import procurement
import res_config
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
Sorsly/subtle | google-cloud-sdk/lib/third_party/setuptools/sandbox.py | 44 | 14315 | import os
import sys
import tempfile
import operator
import functools
import itertools
import re
import contextlib
import pickle
import six
from six.moves import builtins, map
import pkg_resources
if sys.platform.startswith('java'):
import org.python.modules.posix.PosixModule as _os
else:
_os = sys.modules[os.name]
try:
_file = file
except NameError:
_file = None
_open = open
from distutils.errors import DistutilsError
from pkg_resources import working_set
__all__ = [
"AbstractSandbox", "DirectorySandbox", "SandboxViolation", "run_setup",
]
def _execfile(filename, globals, locals=None):
"""
Python 3 implementation of execfile.
"""
mode = 'rb'
with open(filename, mode) as stream:
script = stream.read()
# compile() function in Python 2.6 and 3.1 requires LF line endings.
if sys.version_info[:2] < (2, 7) or sys.version_info[:2] >= (3, 0) and sys.version_info[:2] < (3, 2):
script = script.replace(b'\r\n', b'\n')
script = script.replace(b'\r', b'\n')
if locals is None:
locals = globals
code = compile(script, filename, 'exec')
exec(code, globals, locals)
@contextlib.contextmanager
def save_argv(repl=None):
saved = sys.argv[:]
if repl is not None:
sys.argv[:] = repl
try:
yield saved
finally:
sys.argv[:] = saved
@contextlib.contextmanager
def save_path():
saved = sys.path[:]
try:
yield saved
finally:
sys.path[:] = saved
@contextlib.contextmanager
def override_temp(replacement):
"""
Monkey-patch tempfile.tempdir with replacement, ensuring it exists
"""
if not os.path.isdir(replacement):
os.makedirs(replacement)
saved = tempfile.tempdir
tempfile.tempdir = replacement
try:
yield
finally:
tempfile.tempdir = saved
@contextlib.contextmanager
def pushd(target):
saved = os.getcwd()
os.chdir(target)
try:
yield saved
finally:
os.chdir(saved)
class UnpickleableException(Exception):
"""
An exception representing another Exception that could not be pickled.
"""
@staticmethod
def dump(type, exc):
"""
Always return a dumped (pickled) type and exc. If exc can't be pickled,
wrap it in UnpickleableException first.
"""
try:
return pickle.dumps(type), pickle.dumps(exc)
except Exception:
# get UnpickleableException inside the sandbox
from setuptools.sandbox import UnpickleableException as cls
return cls.dump(cls, cls(repr(exc)))
class ExceptionSaver:
"""
A Context Manager that will save an exception, serialized, and restore it
later.
"""
def __enter__(self):
return self
def __exit__(self, type, exc, tb):
if not exc:
return
# dump the exception
self._saved = UnpickleableException.dump(type, exc)
self._tb = tb
# suppress the exception
return True
def resume(self):
"restore and re-raise any exception"
if '_saved' not in vars(self):
return
type, exc = map(pickle.loads, self._saved)
six.reraise(type, exc, self._tb)
@contextlib.contextmanager
def save_modules():
"""
Context in which imported modules are saved.
Translates exceptions internal to the context into the equivalent exception
outside the context.
"""
saved = sys.modules.copy()
with ExceptionSaver() as saved_exc:
yield saved
sys.modules.update(saved)
# remove any modules imported since
del_modules = (
mod_name for mod_name in sys.modules
if mod_name not in saved
# exclude any encodings modules. See #285
and not mod_name.startswith('encodings.')
)
_clear_modules(del_modules)
saved_exc.resume()
def _clear_modules(module_names):
for mod_name in list(module_names):
del sys.modules[mod_name]
@contextlib.contextmanager
def save_pkg_resources_state():
saved = pkg_resources.__getstate__()
try:
yield saved
finally:
pkg_resources.__setstate__(saved)
@contextlib.contextmanager
def setup_context(setup_dir):
temp_dir = os.path.join(setup_dir, 'temp')
with save_pkg_resources_state():
with save_modules():
hide_setuptools()
with save_path():
with save_argv():
with override_temp(temp_dir):
with pushd(setup_dir):
# ensure setuptools commands are available
__import__('setuptools')
yield
def _needs_hiding(mod_name):
"""
>>> _needs_hiding('setuptools')
True
>>> _needs_hiding('pkg_resources')
True
>>> _needs_hiding('setuptools_plugin')
False
>>> _needs_hiding('setuptools.__init__')
True
>>> _needs_hiding('distutils')
True
>>> _needs_hiding('os')
False
>>> _needs_hiding('Cython')
True
"""
pattern = re.compile('(setuptools|pkg_resources|distutils|Cython)(\.|$)')
return bool(pattern.match(mod_name))
def hide_setuptools():
"""
Remove references to setuptools' modules from sys.modules to allow the
invocation to import the most appropriate setuptools. This technique is
necessary to avoid issues such as #315 where setuptools upgrading itself
would fail to find a function declared in the metadata.
"""
modules = filter(_needs_hiding, sys.modules)
_clear_modules(modules)
def run_setup(setup_script, args):
"""Run a distutils setup script, sandboxed in its directory"""
setup_dir = os.path.abspath(os.path.dirname(setup_script))
with setup_context(setup_dir):
try:
sys.argv[:] = [setup_script] + list(args)
sys.path.insert(0, setup_dir)
# reset to include setup dir, w/clean callback list
working_set.__init__()
working_set.callbacks.append(lambda dist: dist.activate())
# __file__ should be a byte string on Python 2 (#712)
dunder_file = (
setup_script
if isinstance(setup_script, str) else
setup_script.encode(sys.getfilesystemencoding())
)
def runner():
ns = dict(__file__=dunder_file, __name__='__main__')
_execfile(setup_script, ns)
DirectorySandbox(setup_dir).run(runner)
except SystemExit as v:
if v.args and v.args[0]:
raise
# Normal exit, just return
class AbstractSandbox:
"""Wrap 'os' module and 'open()' builtin for virtualizing setup scripts"""
_active = False
def __init__(self):
self._attrs = [
name for name in dir(_os)
if not name.startswith('_') and hasattr(self, name)
]
def _copy(self, source):
for name in self._attrs:
setattr(os, name, getattr(source, name))
def run(self, func):
"""Run 'func' under os sandboxing"""
try:
self._copy(self)
if _file:
builtins.file = self._file
builtins.open = self._open
self._active = True
return func()
finally:
self._active = False
if _file:
builtins.file = _file
builtins.open = _open
self._copy(_os)
def _mk_dual_path_wrapper(name):
original = getattr(_os, name)
def wrap(self, src, dst, *args, **kw):
if self._active:
src, dst = self._remap_pair(name, src, dst, *args, **kw)
return original(src, dst, *args, **kw)
return wrap
for name in ["rename", "link", "symlink"]:
if hasattr(_os, name):
locals()[name] = _mk_dual_path_wrapper(name)
def _mk_single_path_wrapper(name, original=None):
original = original or getattr(_os, name)
def wrap(self, path, *args, **kw):
if self._active:
path = self._remap_input(name, path, *args, **kw)
return original(path, *args, **kw)
return wrap
if _file:
_file = _mk_single_path_wrapper('file', _file)
_open = _mk_single_path_wrapper('open', _open)
for name in [
"stat", "listdir", "chdir", "open", "chmod", "chown", "mkdir",
"remove", "unlink", "rmdir", "utime", "lchown", "chroot", "lstat",
"startfile", "mkfifo", "mknod", "pathconf", "access"
]:
if hasattr(_os, name):
locals()[name] = _mk_single_path_wrapper(name)
def _mk_single_with_return(name):
original = getattr(_os, name)
def wrap(self, path, *args, **kw):
if self._active:
path = self._remap_input(name, path, *args, **kw)
return self._remap_output(name, original(path, *args, **kw))
return original(path, *args, **kw)
return wrap
for name in ['readlink', 'tempnam']:
if hasattr(_os, name):
locals()[name] = _mk_single_with_return(name)
def _mk_query(name):
original = getattr(_os, name)
def wrap(self, *args, **kw):
retval = original(*args, **kw)
if self._active:
return self._remap_output(name, retval)
return retval
return wrap
for name in ['getcwd', 'tmpnam']:
if hasattr(_os, name):
locals()[name] = _mk_query(name)
def _validate_path(self, path):
"""Called to remap or validate any path, whether input or output"""
return path
def _remap_input(self, operation, path, *args, **kw):
"""Called for path inputs"""
return self._validate_path(path)
def _remap_output(self, operation, path):
"""Called for path outputs"""
return self._validate_path(path)
def _remap_pair(self, operation, src, dst, *args, **kw):
"""Called for path pairs like rename, link, and symlink operations"""
return (
self._remap_input(operation + '-from', src, *args, **kw),
self._remap_input(operation + '-to', dst, *args, **kw)
)
if hasattr(os, 'devnull'):
_EXCEPTIONS = [os.devnull,]
else:
_EXCEPTIONS = []
class DirectorySandbox(AbstractSandbox):
"""Restrict operations to a single subdirectory - pseudo-chroot"""
write_ops = dict.fromkeys([
"open", "chmod", "chown", "mkdir", "remove", "unlink", "rmdir",
"utime", "lchown", "chroot", "mkfifo", "mknod", "tempnam",
])
_exception_patterns = [
# Allow lib2to3 to attempt to save a pickled grammar object (#121)
'.*lib2to3.*\.pickle$',
]
"exempt writing to paths that match the pattern"
def __init__(self, sandbox, exceptions=_EXCEPTIONS):
self._sandbox = os.path.normcase(os.path.realpath(sandbox))
self._prefix = os.path.join(self._sandbox, '')
self._exceptions = [
os.path.normcase(os.path.realpath(path))
for path in exceptions
]
AbstractSandbox.__init__(self)
def _violation(self, operation, *args, **kw):
from setuptools.sandbox import SandboxViolation
raise SandboxViolation(operation, args, kw)
if _file:
def _file(self, path, mode='r', *args, **kw):
if mode not in ('r', 'rt', 'rb', 'rU', 'U') and not self._ok(path):
self._violation("file", path, mode, *args, **kw)
return _file(path, mode, *args, **kw)
def _open(self, path, mode='r', *args, **kw):
if mode not in ('r', 'rt', 'rb', 'rU', 'U') and not self._ok(path):
self._violation("open", path, mode, *args, **kw)
return _open(path, mode, *args, **kw)
def tmpnam(self):
self._violation("tmpnam")
def _ok(self, path):
active = self._active
try:
self._active = False
realpath = os.path.normcase(os.path.realpath(path))
return (
self._exempted(realpath)
or realpath == self._sandbox
or realpath.startswith(self._prefix)
)
finally:
self._active = active
def _exempted(self, filepath):
start_matches = (
filepath.startswith(exception)
for exception in self._exceptions
)
pattern_matches = (
re.match(pattern, filepath)
for pattern in self._exception_patterns
)
candidates = itertools.chain(start_matches, pattern_matches)
return any(candidates)
def _remap_input(self, operation, path, *args, **kw):
"""Called for path inputs"""
if operation in self.write_ops and not self._ok(path):
self._violation(operation, os.path.realpath(path), *args, **kw)
return path
def _remap_pair(self, operation, src, dst, *args, **kw):
"""Called for path pairs like rename, link, and symlink operations"""
if not self._ok(src) or not self._ok(dst):
self._violation(operation, src, dst, *args, **kw)
return (src, dst)
def open(self, file, flags, mode=0o777, *args, **kw):
"""Called for low-level os.open()"""
if flags & WRITE_FLAGS and not self._ok(file):
self._violation("os.open", file, flags, mode, *args, **kw)
return _os.open(file, flags, mode, *args, **kw)
WRITE_FLAGS = functools.reduce(
operator.or_, [getattr(_os, a, 0) for a in
"O_WRONLY O_RDWR O_APPEND O_CREAT O_TRUNC O_TEMPORARY".split()]
)
class SandboxViolation(DistutilsError):
"""A setup script attempted to modify the filesystem outside the sandbox"""
def __str__(self):
return """SandboxViolation: %s%r %s
The package setup script has attempted to modify files on your system
that are not within the EasyInstall build area, and has been aborted.
This package cannot be safely installed by EasyInstall, and may not
support alternate installation locations even if you run its setup
script by hand. Please inform the package's author and the EasyInstall
maintainers to find out if a fix or workaround is available.""" % self.args
#
| mit |
CiscoSystems/horizon | openstack_dashboard/dashboards/admin/networks/urls.py | 66 | 2280 | # Copyright 2012 NEC Corporation
#
# 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 django.conf.urls import include
from django.conf.urls import patterns
from django.conf.urls import url
from openstack_dashboard.dashboards.admin.networks.agents \
import views as agent_views
from openstack_dashboard.dashboards.admin.networks.ports \
import urls as port_urls
from openstack_dashboard.dashboards.admin.networks.ports \
import views as port_views
from openstack_dashboard.dashboards.admin.networks.subnets \
import urls as subnet_urls
from openstack_dashboard.dashboards.admin.networks.subnets \
import views as subnet_views
from openstack_dashboard.dashboards.admin.networks import views
NETWORKS = r'^(?P<network_id>[^/]+)/%s$'
urlpatterns = patterns(
'',
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^create/$', views.CreateView.as_view(), name='create'),
url(NETWORKS % 'update', views.UpdateView.as_view(), name='update'),
# for detail view
url(NETWORKS % 'detail', views.DetailView.as_view(), name='detail'),
url(NETWORKS % 'agents/add',
agent_views.AddView.as_view(), name='adddhcpagent'),
url(NETWORKS % 'subnets/create',
subnet_views.CreateView.as_view(), name='addsubnet'),
url(NETWORKS % 'ports/create',
port_views.CreateView.as_view(), name='addport'),
url(r'^(?P<network_id>[^/]+)/subnets/(?P<subnet_id>[^/]+)/update$',
subnet_views.UpdateView.as_view(), name='editsubnet'),
url(r'^(?P<network_id>[^/]+)/ports/(?P<port_id>[^/]+)/update$',
port_views.UpdateView.as_view(), name='editport'),
url(r'^subnets/', include(subnet_urls, namespace='subnets')),
url(r'^ports/', include(port_urls, namespace='ports')))
| apache-2.0 |
gzamboni/sdnResilience | loxi/of12/const.py | 1 | 18791 | # Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior University
# Copyright (c) 2011, 2012 Open Networking Foundation
# Copyright (c) 2012, 2013 Big Switch Networks, Inc.
# See the file LICENSE.pyloxi which should have been included in the source distribution
# Automatically generated by LOXI from template const.py
# Do not modify
OFP_VERSION = 3
# Identifiers from group macro_definitions
OFP_MAX_TABLE_NAME_LEN = 32
OFP_MAX_PORT_NAME_LEN = 16
OFP_TCP_PORT = 6653
OFP_SSL_PORT = 6653
OFP_ETH_ALEN = 6
OFP_DEFAULT_MISS_SEND_LEN = 128
OFP_VLAN_NONE = 0
OFP_FLOW_PERMANENT = 0
OFP_DEFAULT_PRIORITY = 32768
OFP_NO_BUFFER = 4294967295
DESC_STR_LEN = 256
SERIAL_NUM_LEN = 32
OFPQ_ALL = 4294967295
OFPQ_MIN_RATE_UNCFG = 65535
OFPQ_MAX_RATE_UNCFG = 65535
# Identifiers from group of_bsn_pdu_slot_num
BSN_PDU_SLOT_NUM_ANY = 255
of_bsn_pdu_slot_num_map = {
255: 'BSN_PDU_SLOT_NUM_ANY',
}
# Identifiers from group ofp_action_type
OFPAT_OUTPUT = 0
OFPAT_COPY_TTL_OUT = 11
OFPAT_COPY_TTL_IN = 12
OFPAT_SET_MPLS_TTL = 15
OFPAT_DEC_MPLS_TTL = 16
OFPAT_PUSH_VLAN = 17
OFPAT_POP_VLAN = 18
OFPAT_PUSH_MPLS = 19
OFPAT_POP_MPLS = 20
OFPAT_SET_QUEUE = 21
OFPAT_GROUP = 22
OFPAT_SET_NW_TTL = 23
OFPAT_DEC_NW_TTL = 24
OFPAT_SET_FIELD = 25
OFPAT_EXPERIMENTER = 65535
ofp_action_type_map = {
0: 'OFPAT_OUTPUT',
11: 'OFPAT_COPY_TTL_OUT',
12: 'OFPAT_COPY_TTL_IN',
15: 'OFPAT_SET_MPLS_TTL',
16: 'OFPAT_DEC_MPLS_TTL',
17: 'OFPAT_PUSH_VLAN',
18: 'OFPAT_POP_VLAN',
19: 'OFPAT_PUSH_MPLS',
20: 'OFPAT_POP_MPLS',
21: 'OFPAT_SET_QUEUE',
22: 'OFPAT_GROUP',
23: 'OFPAT_SET_NW_TTL',
24: 'OFPAT_DEC_NW_TTL',
25: 'OFPAT_SET_FIELD',
65535: 'OFPAT_EXPERIMENTER',
}
# Identifiers from group ofp_bad_action_code
OFPBAC_BAD_TYPE = 0
OFPBAC_BAD_LEN = 1
OFPBAC_BAD_EXPERIMENTER = 2
OFPBAC_BAD_EXPERIMENTER_TYPE = 3
OFPBAC_BAD_OUT_PORT = 4
OFPBAC_BAD_ARGUMENT = 5
OFPBAC_EPERM = 6
OFPBAC_TOO_MANY = 7
OFPBAC_BAD_QUEUE = 8
OFPBAC_BAD_OUT_GROUP = 9
OFPBAC_MATCH_INCONSISTENT = 10
OFPBAC_UNSUPPORTED_ORDER = 11
OFPBAC_BAD_TAG = 12
OFPBAC_BAD_SET_TYPE = 13
OFPBAC_BAD_SET_LEN = 14
OFPBAC_BAD_SET_ARGUMENT = 15
ofp_bad_action_code_map = {
0: 'OFPBAC_BAD_TYPE',
1: 'OFPBAC_BAD_LEN',
2: 'OFPBAC_BAD_EXPERIMENTER',
3: 'OFPBAC_BAD_EXPERIMENTER_TYPE',
4: 'OFPBAC_BAD_OUT_PORT',
5: 'OFPBAC_BAD_ARGUMENT',
6: 'OFPBAC_EPERM',
7: 'OFPBAC_TOO_MANY',
8: 'OFPBAC_BAD_QUEUE',
9: 'OFPBAC_BAD_OUT_GROUP',
10: 'OFPBAC_MATCH_INCONSISTENT',
11: 'OFPBAC_UNSUPPORTED_ORDER',
12: 'OFPBAC_BAD_TAG',
13: 'OFPBAC_BAD_SET_TYPE',
14: 'OFPBAC_BAD_SET_LEN',
15: 'OFPBAC_BAD_SET_ARGUMENT',
}
# Identifiers from group ofp_bad_instruction_code
OFPBIC_UNKNOWN_INST = 0
OFPBIC_UNSUP_INST = 1
OFPBIC_BAD_TABLE_ID = 2
OFPBIC_UNSUP_METADATA = 3
OFPBIC_UNSUP_METADATA_MASK = 4
OFPBIC_BAD_EXPERIMENTER = 5
OFPBIC_BAD_EXPERIMENTER_TYPE = 6
OFPBIC_BAD_LEN = 7
OFPBIC_EPERM = 8
ofp_bad_instruction_code_map = {
0: 'OFPBIC_UNKNOWN_INST',
1: 'OFPBIC_UNSUP_INST',
2: 'OFPBIC_BAD_TABLE_ID',
3: 'OFPBIC_UNSUP_METADATA',
4: 'OFPBIC_UNSUP_METADATA_MASK',
5: 'OFPBIC_BAD_EXPERIMENTER',
6: 'OFPBIC_BAD_EXPERIMENTER_TYPE',
7: 'OFPBIC_BAD_LEN',
8: 'OFPBIC_EPERM',
}
# Identifiers from group ofp_bad_match_code
OFPBMC_BAD_TYPE = 0
OFPBMC_BAD_LEN = 1
OFPBMC_BAD_TAG = 2
OFPBMC_BAD_DL_ADDR_MASK = 3
OFPBMC_BAD_NW_ADDR_MASK = 4
OFPBMC_BAD_WILDCARDS = 5
OFPBMC_BAD_FIELD = 6
OFPBMC_BAD_VALUE = 7
OFPBMC_BAD_MASK = 8
OFPBMC_BAD_PREREQ = 9
OFPBMC_DUP_FIELD = 10
OFPBMC_EPERM = 11
ofp_bad_match_code_map = {
0: 'OFPBMC_BAD_TYPE',
1: 'OFPBMC_BAD_LEN',
2: 'OFPBMC_BAD_TAG',
3: 'OFPBMC_BAD_DL_ADDR_MASK',
4: 'OFPBMC_BAD_NW_ADDR_MASK',
5: 'OFPBMC_BAD_WILDCARDS',
6: 'OFPBMC_BAD_FIELD',
7: 'OFPBMC_BAD_VALUE',
8: 'OFPBMC_BAD_MASK',
9: 'OFPBMC_BAD_PREREQ',
10: 'OFPBMC_DUP_FIELD',
11: 'OFPBMC_EPERM',
}
# Identifiers from group ofp_bad_request_code
OFPBRC_BAD_VERSION = 0
OFPBRC_BAD_TYPE = 1
OFPBRC_BAD_STAT = 2
OFPBRC_BAD_EXPERIMENTER = 3
OFPBRC_BAD_EXPERIMENTER_TYPE = 4
OFPBRC_EPERM = 5
OFPBRC_BAD_LEN = 6
OFPBRC_BUFFER_EMPTY = 7
OFPBRC_BUFFER_UNKNOWN = 8
OFPBRC_BAD_TABLE_ID = 9
OFPBRC_IS_SLAVE = 10
OFPBRC_BAD_PORT = 11
OFPBRC_BAD_PACKET = 12
ofp_bad_request_code_map = {
0: 'OFPBRC_BAD_VERSION',
1: 'OFPBRC_BAD_TYPE',
2: 'OFPBRC_BAD_STAT',
3: 'OFPBRC_BAD_EXPERIMENTER',
4: 'OFPBRC_BAD_EXPERIMENTER_TYPE',
5: 'OFPBRC_EPERM',
6: 'OFPBRC_BAD_LEN',
7: 'OFPBRC_BUFFER_EMPTY',
8: 'OFPBRC_BUFFER_UNKNOWN',
9: 'OFPBRC_BAD_TABLE_ID',
10: 'OFPBRC_IS_SLAVE',
11: 'OFPBRC_BAD_PORT',
12: 'OFPBRC_BAD_PACKET',
}
# Identifiers from group ofp_bsn_tcp_flag
OFP_BSN_TCP_FLAG_FIN = 1
OFP_BSN_TCP_FLAG_SYN = 2
OFP_BSN_TCP_FLAG_RST = 4
OFP_BSN_TCP_FLAG_PSH = 8
OFP_BSN_TCP_FLAG_ACK = 16
OFP_BSN_TCP_FLAG_URG = 32
OFP_BSN_TCP_FLAG_ECE = 64
OFP_BSN_TCP_FLAG_CWR = 128
OFP_BSN_TCP_FLAG_NS = 256
ofp_bsn_tcp_flag_map = {
1: 'OFP_BSN_TCP_FLAG_FIN',
2: 'OFP_BSN_TCP_FLAG_SYN',
4: 'OFP_BSN_TCP_FLAG_RST',
8: 'OFP_BSN_TCP_FLAG_PSH',
16: 'OFP_BSN_TCP_FLAG_ACK',
32: 'OFP_BSN_TCP_FLAG_URG',
64: 'OFP_BSN_TCP_FLAG_ECE',
128: 'OFP_BSN_TCP_FLAG_CWR',
256: 'OFP_BSN_TCP_FLAG_NS',
}
# Identifiers from group ofp_bsn_vport_l2gre_flags
OF_BSN_VPORT_L2GRE_LOCAL_MAC_IS_VALID = 1
OF_BSN_VPORT_L2GRE_DSCP_ASSIGN = 2
OF_BSN_VPORT_L2GRE_DSCP_COPY = 4
OF_BSN_VPORT_L2GRE_LOOPBACK_IS_VALID = 8
OF_BSN_VPORT_L2GRE_RATE_LIMIT_IS_VALID = 16
ofp_bsn_vport_l2gre_flags_map = {
1: 'OF_BSN_VPORT_L2GRE_LOCAL_MAC_IS_VALID',
2: 'OF_BSN_VPORT_L2GRE_DSCP_ASSIGN',
4: 'OF_BSN_VPORT_L2GRE_DSCP_COPY',
8: 'OF_BSN_VPORT_L2GRE_LOOPBACK_IS_VALID',
16: 'OF_BSN_VPORT_L2GRE_RATE_LIMIT_IS_VALID',
}
# Identifiers from group ofp_bsn_vport_q_in_q_untagged
OF_BSN_VPORT_Q_IN_Q_UNTAGGED = 65535
ofp_bsn_vport_q_in_q_untagged_map = {
65535: 'OF_BSN_VPORT_Q_IN_Q_UNTAGGED',
}
# Identifiers from group ofp_bsn_vport_status
OF_BSN_VPORT_STATUS_OK = 0
OF_BSN_VPORT_STATUS_FAILED = 1
ofp_bsn_vport_status_map = {
0: 'OF_BSN_VPORT_STATUS_OK',
1: 'OF_BSN_VPORT_STATUS_FAILED',
}
# Identifiers from group ofp_capabilities
OFPC_FLOW_STATS = 1
OFPC_TABLE_STATS = 2
OFPC_PORT_STATS = 4
OFPC_GROUP_STATS = 8
OFPC_IP_REASM = 32
OFPC_QUEUE_STATS = 64
OFPC_PORT_BLOCKED = 256
ofp_capabilities_map = {
1: 'OFPC_FLOW_STATS',
2: 'OFPC_TABLE_STATS',
4: 'OFPC_PORT_STATS',
8: 'OFPC_GROUP_STATS',
32: 'OFPC_IP_REASM',
64: 'OFPC_QUEUE_STATS',
256: 'OFPC_PORT_BLOCKED',
}
# Identifiers from group ofp_config_flags
OFPC_FRAG_NORMAL = 0
OFPC_FRAG_DROP = 1
OFPC_FRAG_REASM = 2
OFPC_FRAG_MASK = 3
OFPC_INVALID_TTL_TO_CONTROLLER = 4
ofp_config_flags_map = {
0: 'OFPC_FRAG_NORMAL',
1: 'OFPC_FRAG_DROP',
2: 'OFPC_FRAG_REASM',
3: 'OFPC_FRAG_MASK',
4: 'OFPC_INVALID_TTL_TO_CONTROLLER',
}
# Identifiers from group ofp_controller_max_len
OFPCML_MAX = 65509
OFPCML_NO_BUFFER = 65535
ofp_controller_max_len_map = {
65509: 'OFPCML_MAX',
65535: 'OFPCML_NO_BUFFER',
}
# Identifiers from group ofp_controller_role
OFPCR_ROLE_NOCHANGE = 0
OFPCR_ROLE_EQUAL = 1
OFPCR_ROLE_MASTER = 2
OFPCR_ROLE_SLAVE = 3
ofp_controller_role_map = {
0: 'OFPCR_ROLE_NOCHANGE',
1: 'OFPCR_ROLE_EQUAL',
2: 'OFPCR_ROLE_MASTER',
3: 'OFPCR_ROLE_SLAVE',
}
# Identifiers from group ofp_error_type
OFPET_HELLO_FAILED = 0
OFPET_BAD_REQUEST = 1
OFPET_BAD_ACTION = 2
OFPET_BAD_INSTRUCTION = 3
OFPET_BAD_MATCH = 4
OFPET_FLOW_MOD_FAILED = 5
OFPET_GROUP_MOD_FAILED = 6
OFPET_PORT_MOD_FAILED = 7
OFPET_TABLE_MOD_FAILED = 8
OFPET_QUEUE_OP_FAILED = 9
OFPET_SWITCH_CONFIG_FAILED = 10
OFPET_ROLE_REQUEST_FAILED = 11
OFPET_EXPERIMENTER = 65535
ofp_error_type_map = {
0: 'OFPET_HELLO_FAILED',
1: 'OFPET_BAD_REQUEST',
2: 'OFPET_BAD_ACTION',
3: 'OFPET_BAD_INSTRUCTION',
4: 'OFPET_BAD_MATCH',
5: 'OFPET_FLOW_MOD_FAILED',
6: 'OFPET_GROUP_MOD_FAILED',
7: 'OFPET_PORT_MOD_FAILED',
8: 'OFPET_TABLE_MOD_FAILED',
9: 'OFPET_QUEUE_OP_FAILED',
10: 'OFPET_SWITCH_CONFIG_FAILED',
11: 'OFPET_ROLE_REQUEST_FAILED',
65535: 'OFPET_EXPERIMENTER',
}
# Identifiers from group ofp_flow_mod_command
OFPFC_ADD = 0
OFPFC_MODIFY = 1
OFPFC_MODIFY_STRICT = 2
OFPFC_DELETE = 3
OFPFC_DELETE_STRICT = 4
ofp_flow_mod_command_map = {
0: 'OFPFC_ADD',
1: 'OFPFC_MODIFY',
2: 'OFPFC_MODIFY_STRICT',
3: 'OFPFC_DELETE',
4: 'OFPFC_DELETE_STRICT',
}
# Identifiers from group ofp_flow_mod_failed_code
OFPFMFC_UNKNOWN = 0
OFPFMFC_TABLE_FULL = 1
OFPFMFC_BAD_TABLE_ID = 2
OFPFMFC_OVERLAP = 3
OFPFMFC_EPERM = 4
OFPFMFC_BAD_TIMEOUT = 5
OFPFMFC_BAD_COMMAND = 6
OFPFMFC_BAD_FLAGS = 7
ofp_flow_mod_failed_code_map = {
0: 'OFPFMFC_UNKNOWN',
1: 'OFPFMFC_TABLE_FULL',
2: 'OFPFMFC_BAD_TABLE_ID',
3: 'OFPFMFC_OVERLAP',
4: 'OFPFMFC_EPERM',
5: 'OFPFMFC_BAD_TIMEOUT',
6: 'OFPFMFC_BAD_COMMAND',
7: 'OFPFMFC_BAD_FLAGS',
}
# Identifiers from group ofp_flow_mod_flags
OFPFF_SEND_FLOW_REM = 1
OFPFF_CHECK_OVERLAP = 2
OFPFF_RESET_COUNTS = 4
ofp_flow_mod_flags_map = {
1: 'OFPFF_SEND_FLOW_REM',
2: 'OFPFF_CHECK_OVERLAP',
4: 'OFPFF_RESET_COUNTS',
}
# Identifiers from group ofp_flow_removed_reason
OFPRR_IDLE_TIMEOUT = 0
OFPRR_HARD_TIMEOUT = 1
OFPRR_DELETE = 2
OFPRR_GROUP_DELETE = 3
ofp_flow_removed_reason_map = {
0: 'OFPRR_IDLE_TIMEOUT',
1: 'OFPRR_HARD_TIMEOUT',
2: 'OFPRR_DELETE',
3: 'OFPRR_GROUP_DELETE',
}
# Identifiers from group ofp_group
OFPG_MAX = 4294967040
OFPG_ALL = 4294967292
OFPG_ANY = 4294967295
ofp_group_map = {
4294967040: 'OFPG_MAX',
4294967292: 'OFPG_ALL',
4294967295: 'OFPG_ANY',
}
# Identifiers from group ofp_group_capabilities
OFPGFC_SELECT_WEIGHT = 1
OFPGFC_SELECT_LIVENESS = 2
OFPGFC_CHAINING = 4
OFPGFC_CHAINING_CHECKS = 8
ofp_group_capabilities_map = {
1: 'OFPGFC_SELECT_WEIGHT',
2: 'OFPGFC_SELECT_LIVENESS',
4: 'OFPGFC_CHAINING',
8: 'OFPGFC_CHAINING_CHECKS',
}
# Identifiers from group ofp_group_mod_command
OFPGC_ADD = 0
OFPGC_MODIFY = 1
OFPGC_DELETE = 2
ofp_group_mod_command_map = {
0: 'OFPGC_ADD',
1: 'OFPGC_MODIFY',
2: 'OFPGC_DELETE',
}
# Identifiers from group ofp_group_mod_failed_code
OFPGMFC_GROUP_EXISTS = 0
OFPGMFC_INVALID_GROUP = 1
OFPGMFC_WEIGHT_UNSUPPORTED = 2
OFPGMFC_OUT_OF_GROUPS = 3
OFPGMFC_OUT_OF_BUCKETS = 4
OFPGMFC_CHAINING_UNSUPPORTED = 5
OFPGMFC_WATCH_UNSUPPORTED = 6
OFPGMFC_LOOP = 7
OFPGMFC_UNKNOWN_GROUP = 8
OFPGMFC_CHAINED_GROUP = 9
OFPGMFC_BAD_TYPE = 10
OFPGMFC_BAD_COMMAND = 11
OFPGMFC_BAD_BUCKET = 12
OFPGMFC_BAD_WATCH = 13
OFPGMFC_EPERM = 14
ofp_group_mod_failed_code_map = {
0: 'OFPGMFC_GROUP_EXISTS',
1: 'OFPGMFC_INVALID_GROUP',
2: 'OFPGMFC_WEIGHT_UNSUPPORTED',
3: 'OFPGMFC_OUT_OF_GROUPS',
4: 'OFPGMFC_OUT_OF_BUCKETS',
5: 'OFPGMFC_CHAINING_UNSUPPORTED',
6: 'OFPGMFC_WATCH_UNSUPPORTED',
7: 'OFPGMFC_LOOP',
8: 'OFPGMFC_UNKNOWN_GROUP',
9: 'OFPGMFC_CHAINED_GROUP',
10: 'OFPGMFC_BAD_TYPE',
11: 'OFPGMFC_BAD_COMMAND',
12: 'OFPGMFC_BAD_BUCKET',
13: 'OFPGMFC_BAD_WATCH',
14: 'OFPGMFC_EPERM',
}
# Identifiers from group ofp_group_type
OFPGT_ALL = 0
OFPGT_SELECT = 1
OFPGT_INDIRECT = 2
OFPGT_FF = 3
ofp_group_type_map = {
0: 'OFPGT_ALL',
1: 'OFPGT_SELECT',
2: 'OFPGT_INDIRECT',
3: 'OFPGT_FF',
}
# Identifiers from group ofp_hello_failed_code
OFPHFC_INCOMPATIBLE = 0
OFPHFC_EPERM = 1
ofp_hello_failed_code_map = {
0: 'OFPHFC_INCOMPATIBLE',
1: 'OFPHFC_EPERM',
}
# Identifiers from group ofp_instruction_type
OFPIT_GOTO_TABLE = 1
OFPIT_WRITE_METADATA = 2
OFPIT_WRITE_ACTIONS = 3
OFPIT_APPLY_ACTIONS = 4
OFPIT_CLEAR_ACTIONS = 5
OFPIT_EXPERIMENTER = 65535
ofp_instruction_type_map = {
1: 'OFPIT_GOTO_TABLE',
2: 'OFPIT_WRITE_METADATA',
3: 'OFPIT_WRITE_ACTIONS',
4: 'OFPIT_APPLY_ACTIONS',
5: 'OFPIT_CLEAR_ACTIONS',
65535: 'OFPIT_EXPERIMENTER',
}
# Identifiers from group ofp_match_type
OFPMT_STANDARD = 0
OFPMT_OXM = 1
ofp_match_type_map = {
0: 'OFPMT_STANDARD',
1: 'OFPMT_OXM',
}
# Identifiers from group ofp_oxm_class
OFPXMC_NXM_0 = 0
OFPXMC_NXM_1 = 1
OFPXMC_OPENFLOW_BASIC = 32768
OFPXMC_EXPERIMENTER = 65535
ofp_oxm_class_map = {
0: 'OFPXMC_NXM_0',
1: 'OFPXMC_NXM_1',
32768: 'OFPXMC_OPENFLOW_BASIC',
65535: 'OFPXMC_EXPERIMENTER',
}
# Identifiers from group ofp_packet_in_reason
OFPR_NO_MATCH = 0
OFPR_ACTION = 1
OFPR_INVALID_TTL = 2
ofp_packet_in_reason_map = {
0: 'OFPR_NO_MATCH',
1: 'OFPR_ACTION',
2: 'OFPR_INVALID_TTL',
}
# Identifiers from group ofp_port
OFPP_MAX = 4294967040
OFPP_IN_PORT = 4294967288
OFPP_TABLE = 4294967289
OFPP_NORMAL = 4294967290
OFPP_FLOOD = 4294967291
OFPP_ALL = 4294967292
OFPP_CONTROLLER = 4294967293
OFPP_LOCAL = 4294967294
OFPP_ANY = 4294967295
ofp_port_map = {
4294967040: 'OFPP_MAX',
4294967288: 'OFPP_IN_PORT',
4294967289: 'OFPP_TABLE',
4294967290: 'OFPP_NORMAL',
4294967291: 'OFPP_FLOOD',
4294967292: 'OFPP_ALL',
4294967293: 'OFPP_CONTROLLER',
4294967294: 'OFPP_LOCAL',
4294967295: 'OFPP_ANY',
}
# Identifiers from group ofp_port_config
OFPPC_PORT_DOWN = 1
OFPPC_NO_RECV = 4
OFPPC_NO_FWD = 32
OFPPC_NO_PACKET_IN = 64
OFPPC_BSN_MIRROR_DEST = 2147483648
ofp_port_config_map = {
1: 'OFPPC_PORT_DOWN',
4: 'OFPPC_NO_RECV',
32: 'OFPPC_NO_FWD',
64: 'OFPPC_NO_PACKET_IN',
2147483648: 'OFPPC_BSN_MIRROR_DEST',
}
# Identifiers from group ofp_port_features
OFPPF_10MB_HD = 1
OFPPF_10MB_FD = 2
OFPPF_100MB_HD = 4
OFPPF_100MB_FD = 8
OFPPF_1GB_HD = 16
OFPPF_1GB_FD = 32
OFPPF_10GB_FD = 64
OFPPF_40GB_FD = 128
OFPPF_100GB_FD = 256
OFPPF_1TB_FD = 512
OFPPF_OTHER = 1024
OFPPF_COPPER = 2048
OFPPF_FIBER = 4096
OFPPF_AUTONEG = 8192
OFPPF_PAUSE = 16384
OFPPF_PAUSE_ASYM = 32768
ofp_port_features_map = {
1: 'OFPPF_10MB_HD',
2: 'OFPPF_10MB_FD',
4: 'OFPPF_100MB_HD',
8: 'OFPPF_100MB_FD',
16: 'OFPPF_1GB_HD',
32: 'OFPPF_1GB_FD',
64: 'OFPPF_10GB_FD',
128: 'OFPPF_40GB_FD',
256: 'OFPPF_100GB_FD',
512: 'OFPPF_1TB_FD',
1024: 'OFPPF_OTHER',
2048: 'OFPPF_COPPER',
4096: 'OFPPF_FIBER',
8192: 'OFPPF_AUTONEG',
16384: 'OFPPF_PAUSE',
32768: 'OFPPF_PAUSE_ASYM',
}
# Identifiers from group ofp_port_mod_failed_code
OFPPMFC_BAD_PORT = 0
OFPPMFC_BAD_HW_ADDR = 1
OFPPMFC_BAD_CONFIG = 2
OFPPMFC_BAD_ADVERTISE = 3
OFPPMFC_EPERM = 4
ofp_port_mod_failed_code_map = {
0: 'OFPPMFC_BAD_PORT',
1: 'OFPPMFC_BAD_HW_ADDR',
2: 'OFPPMFC_BAD_CONFIG',
3: 'OFPPMFC_BAD_ADVERTISE',
4: 'OFPPMFC_EPERM',
}
# Identifiers from group ofp_port_reason
OFPPR_ADD = 0
OFPPR_DELETE = 1
OFPPR_MODIFY = 2
ofp_port_reason_map = {
0: 'OFPPR_ADD',
1: 'OFPPR_DELETE',
2: 'OFPPR_MODIFY',
}
# Identifiers from group ofp_port_state
OFPPS_LINK_DOWN = 1
OFPPS_BLOCKED = 2
OFPPS_LIVE = 4
ofp_port_state_map = {
1: 'OFPPS_LINK_DOWN',
2: 'OFPPS_BLOCKED',
4: 'OFPPS_LIVE',
}
# Identifiers from group ofp_queue_op_failed_code
OFPQOFC_BAD_PORT = 0
OFPQOFC_BAD_QUEUE = 1
OFPQOFC_EPERM = 2
ofp_queue_op_failed_code_map = {
0: 'OFPQOFC_BAD_PORT',
1: 'OFPQOFC_BAD_QUEUE',
2: 'OFPQOFC_EPERM',
}
# Identifiers from group ofp_queue_properties
OFPQT_MIN_RATE = 1
OFPQT_MAX_RATE = 2
OFPQT_EXPERIMENTER = 65535
ofp_queue_properties_map = {
1: 'OFPQT_MIN_RATE',
2: 'OFPQT_MAX_RATE',
65535: 'OFPQT_EXPERIMENTER',
}
# Identifiers from group ofp_role_request_failed_code
OFPRRFC_STALE = 0
OFPRRFC_UNSUP = 1
OFPRRFC_BAD_ROLE = 2
ofp_role_request_failed_code_map = {
0: 'OFPRRFC_STALE',
1: 'OFPRRFC_UNSUP',
2: 'OFPRRFC_BAD_ROLE',
}
# Identifiers from group ofp_stats_reply_flags
OFPSF_REPLY_MORE = 1
ofp_stats_reply_flags_map = {
1: 'OFPSF_REPLY_MORE',
}
# Identifiers from group ofp_stats_request_flags
ofp_stats_request_flags_map = {
}
# Identifiers from group ofp_stats_type
OFPST_DESC = 0
OFPST_FLOW = 1
OFPST_AGGREGATE = 2
OFPST_TABLE = 3
OFPST_PORT = 4
OFPST_QUEUE = 5
OFPST_GROUP = 6
OFPST_GROUP_DESC = 7
OFPST_GROUP_FEATURES = 8
OFPST_EXPERIMENTER = 65535
ofp_stats_type_map = {
0: 'OFPST_DESC',
1: 'OFPST_FLOW',
2: 'OFPST_AGGREGATE',
3: 'OFPST_TABLE',
4: 'OFPST_PORT',
5: 'OFPST_QUEUE',
6: 'OFPST_GROUP',
7: 'OFPST_GROUP_DESC',
8: 'OFPST_GROUP_FEATURES',
65535: 'OFPST_EXPERIMENTER',
}
# Identifiers from group ofp_switch_config_failed_code
OFPSCFC_BAD_FLAGS = 0
OFPSCFC_BAD_LEN = 1
OFPSCFC_EPERM = 2
ofp_switch_config_failed_code_map = {
0: 'OFPSCFC_BAD_FLAGS',
1: 'OFPSCFC_BAD_LEN',
2: 'OFPSCFC_EPERM',
}
# Identifiers from group ofp_table
OFPTT_MAX = 254
OFPTT_ALL = 255
ofp_table_map = {
254: 'OFPTT_MAX',
255: 'OFPTT_ALL',
}
# Identifiers from group ofp_table_config
OFPTC_TABLE_MISS_CONTROLLER = 0
OFPTC_TABLE_MISS_CONTINUE = 1
OFPTC_TABLE_MISS_DROP = 2
OFPTC_TABLE_MISS_MASK = 3
ofp_table_config_map = {
0: 'OFPTC_TABLE_MISS_CONTROLLER',
1: 'OFPTC_TABLE_MISS_CONTINUE',
2: 'OFPTC_TABLE_MISS_DROP',
3: 'OFPTC_TABLE_MISS_MASK',
}
# Identifiers from group ofp_table_mod_failed_code
OFPTMFC_BAD_TABLE = 0
OFPTMFC_BAD_CONFIG = 1
OFPTMFC_EPERM = 2
ofp_table_mod_failed_code_map = {
0: 'OFPTMFC_BAD_TABLE',
1: 'OFPTMFC_BAD_CONFIG',
2: 'OFPTMFC_EPERM',
}
# Identifiers from group ofp_type
OFPT_HELLO = 0
OFPT_ERROR = 1
OFPT_ECHO_REQUEST = 2
OFPT_ECHO_REPLY = 3
OFPT_EXPERIMENTER = 4
OFPT_FEATURES_REQUEST = 5
OFPT_FEATURES_REPLY = 6
OFPT_GET_CONFIG_REQUEST = 7
OFPT_GET_CONFIG_REPLY = 8
OFPT_SET_CONFIG = 9
OFPT_PACKET_IN = 10
OFPT_FLOW_REMOVED = 11
OFPT_PORT_STATUS = 12
OFPT_PACKET_OUT = 13
OFPT_FLOW_MOD = 14
OFPT_GROUP_MOD = 15
OFPT_PORT_MOD = 16
OFPT_TABLE_MOD = 17
OFPT_STATS_REQUEST = 18
OFPT_STATS_REPLY = 19
OFPT_BARRIER_REQUEST = 20
OFPT_BARRIER_REPLY = 21
OFPT_QUEUE_GET_CONFIG_REQUEST = 22
OFPT_QUEUE_GET_CONFIG_REPLY = 23
OFPT_ROLE_REQUEST = 24
OFPT_ROLE_REPLY = 25
ofp_type_map = {
0: 'OFPT_HELLO',
1: 'OFPT_ERROR',
2: 'OFPT_ECHO_REQUEST',
3: 'OFPT_ECHO_REPLY',
4: 'OFPT_EXPERIMENTER',
5: 'OFPT_FEATURES_REQUEST',
6: 'OFPT_FEATURES_REPLY',
7: 'OFPT_GET_CONFIG_REQUEST',
8: 'OFPT_GET_CONFIG_REPLY',
9: 'OFPT_SET_CONFIG',
10: 'OFPT_PACKET_IN',
11: 'OFPT_FLOW_REMOVED',
12: 'OFPT_PORT_STATUS',
13: 'OFPT_PACKET_OUT',
14: 'OFPT_FLOW_MOD',
15: 'OFPT_GROUP_MOD',
16: 'OFPT_PORT_MOD',
17: 'OFPT_TABLE_MOD',
18: 'OFPT_STATS_REQUEST',
19: 'OFPT_STATS_REPLY',
20: 'OFPT_BARRIER_REQUEST',
21: 'OFPT_BARRIER_REPLY',
22: 'OFPT_QUEUE_GET_CONFIG_REQUEST',
23: 'OFPT_QUEUE_GET_CONFIG_REPLY',
24: 'OFPT_ROLE_REQUEST',
25: 'OFPT_ROLE_REPLY',
}
# Identifiers from group ofp_vlan_id
OFPVID_NONE = 0
OFPVID_PRESENT = 4096
ofp_vlan_id_map = {
0: 'OFPVID_NONE',
4096: 'OFPVID_PRESENT',
}
| gpl-2.0 |
axbaretto/beam | sdks/python/.tox/lint/lib/python2.7/encodings/cp860.py | 593 | 34937 | """ Python Character Mapping Codec generated from 'VENDORS/MICSFT/PC/CP860.TXT' with gencodec.py.
"""#"
import codecs
### Codec APIs
class Codec(codecs.Codec):
def encode(self,input,errors='strict'):
return codecs.charmap_encode(input,errors,encoding_map)
def decode(self,input,errors='strict'):
return codecs.charmap_decode(input,errors,decoding_table)
class IncrementalEncoder(codecs.IncrementalEncoder):
def encode(self, input, final=False):
return codecs.charmap_encode(input,self.errors,encoding_map)[0]
class IncrementalDecoder(codecs.IncrementalDecoder):
def decode(self, input, final=False):
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
class StreamWriter(Codec,codecs.StreamWriter):
pass
class StreamReader(Codec,codecs.StreamReader):
pass
### encodings module API
def getregentry():
return codecs.CodecInfo(
name='cp860',
encode=Codec().encode,
decode=Codec().decode,
incrementalencoder=IncrementalEncoder,
incrementaldecoder=IncrementalDecoder,
streamreader=StreamReader,
streamwriter=StreamWriter,
)
### Decoding Map
decoding_map = codecs.make_identity_dict(range(256))
decoding_map.update({
0x0080: 0x00c7, # LATIN CAPITAL LETTER C WITH CEDILLA
0x0081: 0x00fc, # LATIN SMALL LETTER U WITH DIAERESIS
0x0082: 0x00e9, # LATIN SMALL LETTER E WITH ACUTE
0x0083: 0x00e2, # LATIN SMALL LETTER A WITH CIRCUMFLEX
0x0084: 0x00e3, # LATIN SMALL LETTER A WITH TILDE
0x0085: 0x00e0, # LATIN SMALL LETTER A WITH GRAVE
0x0086: 0x00c1, # LATIN CAPITAL LETTER A WITH ACUTE
0x0087: 0x00e7, # LATIN SMALL LETTER C WITH CEDILLA
0x0088: 0x00ea, # LATIN SMALL LETTER E WITH CIRCUMFLEX
0x0089: 0x00ca, # LATIN CAPITAL LETTER E WITH CIRCUMFLEX
0x008a: 0x00e8, # LATIN SMALL LETTER E WITH GRAVE
0x008b: 0x00cd, # LATIN CAPITAL LETTER I WITH ACUTE
0x008c: 0x00d4, # LATIN CAPITAL LETTER O WITH CIRCUMFLEX
0x008d: 0x00ec, # LATIN SMALL LETTER I WITH GRAVE
0x008e: 0x00c3, # LATIN CAPITAL LETTER A WITH TILDE
0x008f: 0x00c2, # LATIN CAPITAL LETTER A WITH CIRCUMFLEX
0x0090: 0x00c9, # LATIN CAPITAL LETTER E WITH ACUTE
0x0091: 0x00c0, # LATIN CAPITAL LETTER A WITH GRAVE
0x0092: 0x00c8, # LATIN CAPITAL LETTER E WITH GRAVE
0x0093: 0x00f4, # LATIN SMALL LETTER O WITH CIRCUMFLEX
0x0094: 0x00f5, # LATIN SMALL LETTER O WITH TILDE
0x0095: 0x00f2, # LATIN SMALL LETTER O WITH GRAVE
0x0096: 0x00da, # LATIN CAPITAL LETTER U WITH ACUTE
0x0097: 0x00f9, # LATIN SMALL LETTER U WITH GRAVE
0x0098: 0x00cc, # LATIN CAPITAL LETTER I WITH GRAVE
0x0099: 0x00d5, # LATIN CAPITAL LETTER O WITH TILDE
0x009a: 0x00dc, # LATIN CAPITAL LETTER U WITH DIAERESIS
0x009b: 0x00a2, # CENT SIGN
0x009c: 0x00a3, # POUND SIGN
0x009d: 0x00d9, # LATIN CAPITAL LETTER U WITH GRAVE
0x009e: 0x20a7, # PESETA SIGN
0x009f: 0x00d3, # LATIN CAPITAL LETTER O WITH ACUTE
0x00a0: 0x00e1, # LATIN SMALL LETTER A WITH ACUTE
0x00a1: 0x00ed, # LATIN SMALL LETTER I WITH ACUTE
0x00a2: 0x00f3, # LATIN SMALL LETTER O WITH ACUTE
0x00a3: 0x00fa, # LATIN SMALL LETTER U WITH ACUTE
0x00a4: 0x00f1, # LATIN SMALL LETTER N WITH TILDE
0x00a5: 0x00d1, # LATIN CAPITAL LETTER N WITH TILDE
0x00a6: 0x00aa, # FEMININE ORDINAL INDICATOR
0x00a7: 0x00ba, # MASCULINE ORDINAL INDICATOR
0x00a8: 0x00bf, # INVERTED QUESTION MARK
0x00a9: 0x00d2, # LATIN CAPITAL LETTER O WITH GRAVE
0x00aa: 0x00ac, # NOT SIGN
0x00ab: 0x00bd, # VULGAR FRACTION ONE HALF
0x00ac: 0x00bc, # VULGAR FRACTION ONE QUARTER
0x00ad: 0x00a1, # INVERTED EXCLAMATION MARK
0x00ae: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
0x00af: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
0x00b0: 0x2591, # LIGHT SHADE
0x00b1: 0x2592, # MEDIUM SHADE
0x00b2: 0x2593, # DARK SHADE
0x00b3: 0x2502, # BOX DRAWINGS LIGHT VERTICAL
0x00b4: 0x2524, # BOX DRAWINGS LIGHT VERTICAL AND LEFT
0x00b5: 0x2561, # BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE
0x00b6: 0x2562, # BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE
0x00b7: 0x2556, # BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE
0x00b8: 0x2555, # BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE
0x00b9: 0x2563, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT
0x00ba: 0x2551, # BOX DRAWINGS DOUBLE VERTICAL
0x00bb: 0x2557, # BOX DRAWINGS DOUBLE DOWN AND LEFT
0x00bc: 0x255d, # BOX DRAWINGS DOUBLE UP AND LEFT
0x00bd: 0x255c, # BOX DRAWINGS UP DOUBLE AND LEFT SINGLE
0x00be: 0x255b, # BOX DRAWINGS UP SINGLE AND LEFT DOUBLE
0x00bf: 0x2510, # BOX DRAWINGS LIGHT DOWN AND LEFT
0x00c0: 0x2514, # BOX DRAWINGS LIGHT UP AND RIGHT
0x00c1: 0x2534, # BOX DRAWINGS LIGHT UP AND HORIZONTAL
0x00c2: 0x252c, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL
0x00c3: 0x251c, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT
0x00c4: 0x2500, # BOX DRAWINGS LIGHT HORIZONTAL
0x00c5: 0x253c, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL
0x00c6: 0x255e, # BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE
0x00c7: 0x255f, # BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE
0x00c8: 0x255a, # BOX DRAWINGS DOUBLE UP AND RIGHT
0x00c9: 0x2554, # BOX DRAWINGS DOUBLE DOWN AND RIGHT
0x00ca: 0x2569, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL
0x00cb: 0x2566, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL
0x00cc: 0x2560, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT
0x00cd: 0x2550, # BOX DRAWINGS DOUBLE HORIZONTAL
0x00ce: 0x256c, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL
0x00cf: 0x2567, # BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE
0x00d0: 0x2568, # BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE
0x00d1: 0x2564, # BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE
0x00d2: 0x2565, # BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE
0x00d3: 0x2559, # BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE
0x00d4: 0x2558, # BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE
0x00d5: 0x2552, # BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE
0x00d6: 0x2553, # BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE
0x00d7: 0x256b, # BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE
0x00d8: 0x256a, # BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE
0x00d9: 0x2518, # BOX DRAWINGS LIGHT UP AND LEFT
0x00da: 0x250c, # BOX DRAWINGS LIGHT DOWN AND RIGHT
0x00db: 0x2588, # FULL BLOCK
0x00dc: 0x2584, # LOWER HALF BLOCK
0x00dd: 0x258c, # LEFT HALF BLOCK
0x00de: 0x2590, # RIGHT HALF BLOCK
0x00df: 0x2580, # UPPER HALF BLOCK
0x00e0: 0x03b1, # GREEK SMALL LETTER ALPHA
0x00e1: 0x00df, # LATIN SMALL LETTER SHARP S
0x00e2: 0x0393, # GREEK CAPITAL LETTER GAMMA
0x00e3: 0x03c0, # GREEK SMALL LETTER PI
0x00e4: 0x03a3, # GREEK CAPITAL LETTER SIGMA
0x00e5: 0x03c3, # GREEK SMALL LETTER SIGMA
0x00e6: 0x00b5, # MICRO SIGN
0x00e7: 0x03c4, # GREEK SMALL LETTER TAU
0x00e8: 0x03a6, # GREEK CAPITAL LETTER PHI
0x00e9: 0x0398, # GREEK CAPITAL LETTER THETA
0x00ea: 0x03a9, # GREEK CAPITAL LETTER OMEGA
0x00eb: 0x03b4, # GREEK SMALL LETTER DELTA
0x00ec: 0x221e, # INFINITY
0x00ed: 0x03c6, # GREEK SMALL LETTER PHI
0x00ee: 0x03b5, # GREEK SMALL LETTER EPSILON
0x00ef: 0x2229, # INTERSECTION
0x00f0: 0x2261, # IDENTICAL TO
0x00f1: 0x00b1, # PLUS-MINUS SIGN
0x00f2: 0x2265, # GREATER-THAN OR EQUAL TO
0x00f3: 0x2264, # LESS-THAN OR EQUAL TO
0x00f4: 0x2320, # TOP HALF INTEGRAL
0x00f5: 0x2321, # BOTTOM HALF INTEGRAL
0x00f6: 0x00f7, # DIVISION SIGN
0x00f7: 0x2248, # ALMOST EQUAL TO
0x00f8: 0x00b0, # DEGREE SIGN
0x00f9: 0x2219, # BULLET OPERATOR
0x00fa: 0x00b7, # MIDDLE DOT
0x00fb: 0x221a, # SQUARE ROOT
0x00fc: 0x207f, # SUPERSCRIPT LATIN SMALL LETTER N
0x00fd: 0x00b2, # SUPERSCRIPT TWO
0x00fe: 0x25a0, # BLACK SQUARE
0x00ff: 0x00a0, # NO-BREAK SPACE
})
### Decoding Table
decoding_table = (
u'\x00' # 0x0000 -> NULL
u'\x01' # 0x0001 -> START OF HEADING
u'\x02' # 0x0002 -> START OF TEXT
u'\x03' # 0x0003 -> END OF TEXT
u'\x04' # 0x0004 -> END OF TRANSMISSION
u'\x05' # 0x0005 -> ENQUIRY
u'\x06' # 0x0006 -> ACKNOWLEDGE
u'\x07' # 0x0007 -> BELL
u'\x08' # 0x0008 -> BACKSPACE
u'\t' # 0x0009 -> HORIZONTAL TABULATION
u'\n' # 0x000a -> LINE FEED
u'\x0b' # 0x000b -> VERTICAL TABULATION
u'\x0c' # 0x000c -> FORM FEED
u'\r' # 0x000d -> CARRIAGE RETURN
u'\x0e' # 0x000e -> SHIFT OUT
u'\x0f' # 0x000f -> SHIFT IN
u'\x10' # 0x0010 -> DATA LINK ESCAPE
u'\x11' # 0x0011 -> DEVICE CONTROL ONE
u'\x12' # 0x0012 -> DEVICE CONTROL TWO
u'\x13' # 0x0013 -> DEVICE CONTROL THREE
u'\x14' # 0x0014 -> DEVICE CONTROL FOUR
u'\x15' # 0x0015 -> NEGATIVE ACKNOWLEDGE
u'\x16' # 0x0016 -> SYNCHRONOUS IDLE
u'\x17' # 0x0017 -> END OF TRANSMISSION BLOCK
u'\x18' # 0x0018 -> CANCEL
u'\x19' # 0x0019 -> END OF MEDIUM
u'\x1a' # 0x001a -> SUBSTITUTE
u'\x1b' # 0x001b -> ESCAPE
u'\x1c' # 0x001c -> FILE SEPARATOR
u'\x1d' # 0x001d -> GROUP SEPARATOR
u'\x1e' # 0x001e -> RECORD SEPARATOR
u'\x1f' # 0x001f -> UNIT SEPARATOR
u' ' # 0x0020 -> SPACE
u'!' # 0x0021 -> EXCLAMATION MARK
u'"' # 0x0022 -> QUOTATION MARK
u'#' # 0x0023 -> NUMBER SIGN
u'$' # 0x0024 -> DOLLAR SIGN
u'%' # 0x0025 -> PERCENT SIGN
u'&' # 0x0026 -> AMPERSAND
u"'" # 0x0027 -> APOSTROPHE
u'(' # 0x0028 -> LEFT PARENTHESIS
u')' # 0x0029 -> RIGHT PARENTHESIS
u'*' # 0x002a -> ASTERISK
u'+' # 0x002b -> PLUS SIGN
u',' # 0x002c -> COMMA
u'-' # 0x002d -> HYPHEN-MINUS
u'.' # 0x002e -> FULL STOP
u'/' # 0x002f -> SOLIDUS
u'0' # 0x0030 -> DIGIT ZERO
u'1' # 0x0031 -> DIGIT ONE
u'2' # 0x0032 -> DIGIT TWO
u'3' # 0x0033 -> DIGIT THREE
u'4' # 0x0034 -> DIGIT FOUR
u'5' # 0x0035 -> DIGIT FIVE
u'6' # 0x0036 -> DIGIT SIX
u'7' # 0x0037 -> DIGIT SEVEN
u'8' # 0x0038 -> DIGIT EIGHT
u'9' # 0x0039 -> DIGIT NINE
u':' # 0x003a -> COLON
u';' # 0x003b -> SEMICOLON
u'<' # 0x003c -> LESS-THAN SIGN
u'=' # 0x003d -> EQUALS SIGN
u'>' # 0x003e -> GREATER-THAN SIGN
u'?' # 0x003f -> QUESTION MARK
u'@' # 0x0040 -> COMMERCIAL AT
u'A' # 0x0041 -> LATIN CAPITAL LETTER A
u'B' # 0x0042 -> LATIN CAPITAL LETTER B
u'C' # 0x0043 -> LATIN CAPITAL LETTER C
u'D' # 0x0044 -> LATIN CAPITAL LETTER D
u'E' # 0x0045 -> LATIN CAPITAL LETTER E
u'F' # 0x0046 -> LATIN CAPITAL LETTER F
u'G' # 0x0047 -> LATIN CAPITAL LETTER G
u'H' # 0x0048 -> LATIN CAPITAL LETTER H
u'I' # 0x0049 -> LATIN CAPITAL LETTER I
u'J' # 0x004a -> LATIN CAPITAL LETTER J
u'K' # 0x004b -> LATIN CAPITAL LETTER K
u'L' # 0x004c -> LATIN CAPITAL LETTER L
u'M' # 0x004d -> LATIN CAPITAL LETTER M
u'N' # 0x004e -> LATIN CAPITAL LETTER N
u'O' # 0x004f -> LATIN CAPITAL LETTER O
u'P' # 0x0050 -> LATIN CAPITAL LETTER P
u'Q' # 0x0051 -> LATIN CAPITAL LETTER Q
u'R' # 0x0052 -> LATIN CAPITAL LETTER R
u'S' # 0x0053 -> LATIN CAPITAL LETTER S
u'T' # 0x0054 -> LATIN CAPITAL LETTER T
u'U' # 0x0055 -> LATIN CAPITAL LETTER U
u'V' # 0x0056 -> LATIN CAPITAL LETTER V
u'W' # 0x0057 -> LATIN CAPITAL LETTER W
u'X' # 0x0058 -> LATIN CAPITAL LETTER X
u'Y' # 0x0059 -> LATIN CAPITAL LETTER Y
u'Z' # 0x005a -> LATIN CAPITAL LETTER Z
u'[' # 0x005b -> LEFT SQUARE BRACKET
u'\\' # 0x005c -> REVERSE SOLIDUS
u']' # 0x005d -> RIGHT SQUARE BRACKET
u'^' # 0x005e -> CIRCUMFLEX ACCENT
u'_' # 0x005f -> LOW LINE
u'`' # 0x0060 -> GRAVE ACCENT
u'a' # 0x0061 -> LATIN SMALL LETTER A
u'b' # 0x0062 -> LATIN SMALL LETTER B
u'c' # 0x0063 -> LATIN SMALL LETTER C
u'd' # 0x0064 -> LATIN SMALL LETTER D
u'e' # 0x0065 -> LATIN SMALL LETTER E
u'f' # 0x0066 -> LATIN SMALL LETTER F
u'g' # 0x0067 -> LATIN SMALL LETTER G
u'h' # 0x0068 -> LATIN SMALL LETTER H
u'i' # 0x0069 -> LATIN SMALL LETTER I
u'j' # 0x006a -> LATIN SMALL LETTER J
u'k' # 0x006b -> LATIN SMALL LETTER K
u'l' # 0x006c -> LATIN SMALL LETTER L
u'm' # 0x006d -> LATIN SMALL LETTER M
u'n' # 0x006e -> LATIN SMALL LETTER N
u'o' # 0x006f -> LATIN SMALL LETTER O
u'p' # 0x0070 -> LATIN SMALL LETTER P
u'q' # 0x0071 -> LATIN SMALL LETTER Q
u'r' # 0x0072 -> LATIN SMALL LETTER R
u's' # 0x0073 -> LATIN SMALL LETTER S
u't' # 0x0074 -> LATIN SMALL LETTER T
u'u' # 0x0075 -> LATIN SMALL LETTER U
u'v' # 0x0076 -> LATIN SMALL LETTER V
u'w' # 0x0077 -> LATIN SMALL LETTER W
u'x' # 0x0078 -> LATIN SMALL LETTER X
u'y' # 0x0079 -> LATIN SMALL LETTER Y
u'z' # 0x007a -> LATIN SMALL LETTER Z
u'{' # 0x007b -> LEFT CURLY BRACKET
u'|' # 0x007c -> VERTICAL LINE
u'}' # 0x007d -> RIGHT CURLY BRACKET
u'~' # 0x007e -> TILDE
u'\x7f' # 0x007f -> DELETE
u'\xc7' # 0x0080 -> LATIN CAPITAL LETTER C WITH CEDILLA
u'\xfc' # 0x0081 -> LATIN SMALL LETTER U WITH DIAERESIS
u'\xe9' # 0x0082 -> LATIN SMALL LETTER E WITH ACUTE
u'\xe2' # 0x0083 -> LATIN SMALL LETTER A WITH CIRCUMFLEX
u'\xe3' # 0x0084 -> LATIN SMALL LETTER A WITH TILDE
u'\xe0' # 0x0085 -> LATIN SMALL LETTER A WITH GRAVE
u'\xc1' # 0x0086 -> LATIN CAPITAL LETTER A WITH ACUTE
u'\xe7' # 0x0087 -> LATIN SMALL LETTER C WITH CEDILLA
u'\xea' # 0x0088 -> LATIN SMALL LETTER E WITH CIRCUMFLEX
u'\xca' # 0x0089 -> LATIN CAPITAL LETTER E WITH CIRCUMFLEX
u'\xe8' # 0x008a -> LATIN SMALL LETTER E WITH GRAVE
u'\xcd' # 0x008b -> LATIN CAPITAL LETTER I WITH ACUTE
u'\xd4' # 0x008c -> LATIN CAPITAL LETTER O WITH CIRCUMFLEX
u'\xec' # 0x008d -> LATIN SMALL LETTER I WITH GRAVE
u'\xc3' # 0x008e -> LATIN CAPITAL LETTER A WITH TILDE
u'\xc2' # 0x008f -> LATIN CAPITAL LETTER A WITH CIRCUMFLEX
u'\xc9' # 0x0090 -> LATIN CAPITAL LETTER E WITH ACUTE
u'\xc0' # 0x0091 -> LATIN CAPITAL LETTER A WITH GRAVE
u'\xc8' # 0x0092 -> LATIN CAPITAL LETTER E WITH GRAVE
u'\xf4' # 0x0093 -> LATIN SMALL LETTER O WITH CIRCUMFLEX
u'\xf5' # 0x0094 -> LATIN SMALL LETTER O WITH TILDE
u'\xf2' # 0x0095 -> LATIN SMALL LETTER O WITH GRAVE
u'\xda' # 0x0096 -> LATIN CAPITAL LETTER U WITH ACUTE
u'\xf9' # 0x0097 -> LATIN SMALL LETTER U WITH GRAVE
u'\xcc' # 0x0098 -> LATIN CAPITAL LETTER I WITH GRAVE
u'\xd5' # 0x0099 -> LATIN CAPITAL LETTER O WITH TILDE
u'\xdc' # 0x009a -> LATIN CAPITAL LETTER U WITH DIAERESIS
u'\xa2' # 0x009b -> CENT SIGN
u'\xa3' # 0x009c -> POUND SIGN
u'\xd9' # 0x009d -> LATIN CAPITAL LETTER U WITH GRAVE
u'\u20a7' # 0x009e -> PESETA SIGN
u'\xd3' # 0x009f -> LATIN CAPITAL LETTER O WITH ACUTE
u'\xe1' # 0x00a0 -> LATIN SMALL LETTER A WITH ACUTE
u'\xed' # 0x00a1 -> LATIN SMALL LETTER I WITH ACUTE
u'\xf3' # 0x00a2 -> LATIN SMALL LETTER O WITH ACUTE
u'\xfa' # 0x00a3 -> LATIN SMALL LETTER U WITH ACUTE
u'\xf1' # 0x00a4 -> LATIN SMALL LETTER N WITH TILDE
u'\xd1' # 0x00a5 -> LATIN CAPITAL LETTER N WITH TILDE
u'\xaa' # 0x00a6 -> FEMININE ORDINAL INDICATOR
u'\xba' # 0x00a7 -> MASCULINE ORDINAL INDICATOR
u'\xbf' # 0x00a8 -> INVERTED QUESTION MARK
u'\xd2' # 0x00a9 -> LATIN CAPITAL LETTER O WITH GRAVE
u'\xac' # 0x00aa -> NOT SIGN
u'\xbd' # 0x00ab -> VULGAR FRACTION ONE HALF
u'\xbc' # 0x00ac -> VULGAR FRACTION ONE QUARTER
u'\xa1' # 0x00ad -> INVERTED EXCLAMATION MARK
u'\xab' # 0x00ae -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
u'\xbb' # 0x00af -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
u'\u2591' # 0x00b0 -> LIGHT SHADE
u'\u2592' # 0x00b1 -> MEDIUM SHADE
u'\u2593' # 0x00b2 -> DARK SHADE
u'\u2502' # 0x00b3 -> BOX DRAWINGS LIGHT VERTICAL
u'\u2524' # 0x00b4 -> BOX DRAWINGS LIGHT VERTICAL AND LEFT
u'\u2561' # 0x00b5 -> BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE
u'\u2562' # 0x00b6 -> BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE
u'\u2556' # 0x00b7 -> BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE
u'\u2555' # 0x00b8 -> BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE
u'\u2563' # 0x00b9 -> BOX DRAWINGS DOUBLE VERTICAL AND LEFT
u'\u2551' # 0x00ba -> BOX DRAWINGS DOUBLE VERTICAL
u'\u2557' # 0x00bb -> BOX DRAWINGS DOUBLE DOWN AND LEFT
u'\u255d' # 0x00bc -> BOX DRAWINGS DOUBLE UP AND LEFT
u'\u255c' # 0x00bd -> BOX DRAWINGS UP DOUBLE AND LEFT SINGLE
u'\u255b' # 0x00be -> BOX DRAWINGS UP SINGLE AND LEFT DOUBLE
u'\u2510' # 0x00bf -> BOX DRAWINGS LIGHT DOWN AND LEFT
u'\u2514' # 0x00c0 -> BOX DRAWINGS LIGHT UP AND RIGHT
u'\u2534' # 0x00c1 -> BOX DRAWINGS LIGHT UP AND HORIZONTAL
u'\u252c' # 0x00c2 -> BOX DRAWINGS LIGHT DOWN AND HORIZONTAL
u'\u251c' # 0x00c3 -> BOX DRAWINGS LIGHT VERTICAL AND RIGHT
u'\u2500' # 0x00c4 -> BOX DRAWINGS LIGHT HORIZONTAL
u'\u253c' # 0x00c5 -> BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL
u'\u255e' # 0x00c6 -> BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE
u'\u255f' # 0x00c7 -> BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE
u'\u255a' # 0x00c8 -> BOX DRAWINGS DOUBLE UP AND RIGHT
u'\u2554' # 0x00c9 -> BOX DRAWINGS DOUBLE DOWN AND RIGHT
u'\u2569' # 0x00ca -> BOX DRAWINGS DOUBLE UP AND HORIZONTAL
u'\u2566' # 0x00cb -> BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL
u'\u2560' # 0x00cc -> BOX DRAWINGS DOUBLE VERTICAL AND RIGHT
u'\u2550' # 0x00cd -> BOX DRAWINGS DOUBLE HORIZONTAL
u'\u256c' # 0x00ce -> BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL
u'\u2567' # 0x00cf -> BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE
u'\u2568' # 0x00d0 -> BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE
u'\u2564' # 0x00d1 -> BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE
u'\u2565' # 0x00d2 -> BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE
u'\u2559' # 0x00d3 -> BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE
u'\u2558' # 0x00d4 -> BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE
u'\u2552' # 0x00d5 -> BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE
u'\u2553' # 0x00d6 -> BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE
u'\u256b' # 0x00d7 -> BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE
u'\u256a' # 0x00d8 -> BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE
u'\u2518' # 0x00d9 -> BOX DRAWINGS LIGHT UP AND LEFT
u'\u250c' # 0x00da -> BOX DRAWINGS LIGHT DOWN AND RIGHT
u'\u2588' # 0x00db -> FULL BLOCK
u'\u2584' # 0x00dc -> LOWER HALF BLOCK
u'\u258c' # 0x00dd -> LEFT HALF BLOCK
u'\u2590' # 0x00de -> RIGHT HALF BLOCK
u'\u2580' # 0x00df -> UPPER HALF BLOCK
u'\u03b1' # 0x00e0 -> GREEK SMALL LETTER ALPHA
u'\xdf' # 0x00e1 -> LATIN SMALL LETTER SHARP S
u'\u0393' # 0x00e2 -> GREEK CAPITAL LETTER GAMMA
u'\u03c0' # 0x00e3 -> GREEK SMALL LETTER PI
u'\u03a3' # 0x00e4 -> GREEK CAPITAL LETTER SIGMA
u'\u03c3' # 0x00e5 -> GREEK SMALL LETTER SIGMA
u'\xb5' # 0x00e6 -> MICRO SIGN
u'\u03c4' # 0x00e7 -> GREEK SMALL LETTER TAU
u'\u03a6' # 0x00e8 -> GREEK CAPITAL LETTER PHI
u'\u0398' # 0x00e9 -> GREEK CAPITAL LETTER THETA
u'\u03a9' # 0x00ea -> GREEK CAPITAL LETTER OMEGA
u'\u03b4' # 0x00eb -> GREEK SMALL LETTER DELTA
u'\u221e' # 0x00ec -> INFINITY
u'\u03c6' # 0x00ed -> GREEK SMALL LETTER PHI
u'\u03b5' # 0x00ee -> GREEK SMALL LETTER EPSILON
u'\u2229' # 0x00ef -> INTERSECTION
u'\u2261' # 0x00f0 -> IDENTICAL TO
u'\xb1' # 0x00f1 -> PLUS-MINUS SIGN
u'\u2265' # 0x00f2 -> GREATER-THAN OR EQUAL TO
u'\u2264' # 0x00f3 -> LESS-THAN OR EQUAL TO
u'\u2320' # 0x00f4 -> TOP HALF INTEGRAL
u'\u2321' # 0x00f5 -> BOTTOM HALF INTEGRAL
u'\xf7' # 0x00f6 -> DIVISION SIGN
u'\u2248' # 0x00f7 -> ALMOST EQUAL TO
u'\xb0' # 0x00f8 -> DEGREE SIGN
u'\u2219' # 0x00f9 -> BULLET OPERATOR
u'\xb7' # 0x00fa -> MIDDLE DOT
u'\u221a' # 0x00fb -> SQUARE ROOT
u'\u207f' # 0x00fc -> SUPERSCRIPT LATIN SMALL LETTER N
u'\xb2' # 0x00fd -> SUPERSCRIPT TWO
u'\u25a0' # 0x00fe -> BLACK SQUARE
u'\xa0' # 0x00ff -> NO-BREAK SPACE
)
### Encoding Map
encoding_map = {
0x0000: 0x0000, # NULL
0x0001: 0x0001, # START OF HEADING
0x0002: 0x0002, # START OF TEXT
0x0003: 0x0003, # END OF TEXT
0x0004: 0x0004, # END OF TRANSMISSION
0x0005: 0x0005, # ENQUIRY
0x0006: 0x0006, # ACKNOWLEDGE
0x0007: 0x0007, # BELL
0x0008: 0x0008, # BACKSPACE
0x0009: 0x0009, # HORIZONTAL TABULATION
0x000a: 0x000a, # LINE FEED
0x000b: 0x000b, # VERTICAL TABULATION
0x000c: 0x000c, # FORM FEED
0x000d: 0x000d, # CARRIAGE RETURN
0x000e: 0x000e, # SHIFT OUT
0x000f: 0x000f, # SHIFT IN
0x0010: 0x0010, # DATA LINK ESCAPE
0x0011: 0x0011, # DEVICE CONTROL ONE
0x0012: 0x0012, # DEVICE CONTROL TWO
0x0013: 0x0013, # DEVICE CONTROL THREE
0x0014: 0x0014, # DEVICE CONTROL FOUR
0x0015: 0x0015, # NEGATIVE ACKNOWLEDGE
0x0016: 0x0016, # SYNCHRONOUS IDLE
0x0017: 0x0017, # END OF TRANSMISSION BLOCK
0x0018: 0x0018, # CANCEL
0x0019: 0x0019, # END OF MEDIUM
0x001a: 0x001a, # SUBSTITUTE
0x001b: 0x001b, # ESCAPE
0x001c: 0x001c, # FILE SEPARATOR
0x001d: 0x001d, # GROUP SEPARATOR
0x001e: 0x001e, # RECORD SEPARATOR
0x001f: 0x001f, # UNIT SEPARATOR
0x0020: 0x0020, # SPACE
0x0021: 0x0021, # EXCLAMATION MARK
0x0022: 0x0022, # QUOTATION MARK
0x0023: 0x0023, # NUMBER SIGN
0x0024: 0x0024, # DOLLAR SIGN
0x0025: 0x0025, # PERCENT SIGN
0x0026: 0x0026, # AMPERSAND
0x0027: 0x0027, # APOSTROPHE
0x0028: 0x0028, # LEFT PARENTHESIS
0x0029: 0x0029, # RIGHT PARENTHESIS
0x002a: 0x002a, # ASTERISK
0x002b: 0x002b, # PLUS SIGN
0x002c: 0x002c, # COMMA
0x002d: 0x002d, # HYPHEN-MINUS
0x002e: 0x002e, # FULL STOP
0x002f: 0x002f, # SOLIDUS
0x0030: 0x0030, # DIGIT ZERO
0x0031: 0x0031, # DIGIT ONE
0x0032: 0x0032, # DIGIT TWO
0x0033: 0x0033, # DIGIT THREE
0x0034: 0x0034, # DIGIT FOUR
0x0035: 0x0035, # DIGIT FIVE
0x0036: 0x0036, # DIGIT SIX
0x0037: 0x0037, # DIGIT SEVEN
0x0038: 0x0038, # DIGIT EIGHT
0x0039: 0x0039, # DIGIT NINE
0x003a: 0x003a, # COLON
0x003b: 0x003b, # SEMICOLON
0x003c: 0x003c, # LESS-THAN SIGN
0x003d: 0x003d, # EQUALS SIGN
0x003e: 0x003e, # GREATER-THAN SIGN
0x003f: 0x003f, # QUESTION MARK
0x0040: 0x0040, # COMMERCIAL AT
0x0041: 0x0041, # LATIN CAPITAL LETTER A
0x0042: 0x0042, # LATIN CAPITAL LETTER B
0x0043: 0x0043, # LATIN CAPITAL LETTER C
0x0044: 0x0044, # LATIN CAPITAL LETTER D
0x0045: 0x0045, # LATIN CAPITAL LETTER E
0x0046: 0x0046, # LATIN CAPITAL LETTER F
0x0047: 0x0047, # LATIN CAPITAL LETTER G
0x0048: 0x0048, # LATIN CAPITAL LETTER H
0x0049: 0x0049, # LATIN CAPITAL LETTER I
0x004a: 0x004a, # LATIN CAPITAL LETTER J
0x004b: 0x004b, # LATIN CAPITAL LETTER K
0x004c: 0x004c, # LATIN CAPITAL LETTER L
0x004d: 0x004d, # LATIN CAPITAL LETTER M
0x004e: 0x004e, # LATIN CAPITAL LETTER N
0x004f: 0x004f, # LATIN CAPITAL LETTER O
0x0050: 0x0050, # LATIN CAPITAL LETTER P
0x0051: 0x0051, # LATIN CAPITAL LETTER Q
0x0052: 0x0052, # LATIN CAPITAL LETTER R
0x0053: 0x0053, # LATIN CAPITAL LETTER S
0x0054: 0x0054, # LATIN CAPITAL LETTER T
0x0055: 0x0055, # LATIN CAPITAL LETTER U
0x0056: 0x0056, # LATIN CAPITAL LETTER V
0x0057: 0x0057, # LATIN CAPITAL LETTER W
0x0058: 0x0058, # LATIN CAPITAL LETTER X
0x0059: 0x0059, # LATIN CAPITAL LETTER Y
0x005a: 0x005a, # LATIN CAPITAL LETTER Z
0x005b: 0x005b, # LEFT SQUARE BRACKET
0x005c: 0x005c, # REVERSE SOLIDUS
0x005d: 0x005d, # RIGHT SQUARE BRACKET
0x005e: 0x005e, # CIRCUMFLEX ACCENT
0x005f: 0x005f, # LOW LINE
0x0060: 0x0060, # GRAVE ACCENT
0x0061: 0x0061, # LATIN SMALL LETTER A
0x0062: 0x0062, # LATIN SMALL LETTER B
0x0063: 0x0063, # LATIN SMALL LETTER C
0x0064: 0x0064, # LATIN SMALL LETTER D
0x0065: 0x0065, # LATIN SMALL LETTER E
0x0066: 0x0066, # LATIN SMALL LETTER F
0x0067: 0x0067, # LATIN SMALL LETTER G
0x0068: 0x0068, # LATIN SMALL LETTER H
0x0069: 0x0069, # LATIN SMALL LETTER I
0x006a: 0x006a, # LATIN SMALL LETTER J
0x006b: 0x006b, # LATIN SMALL LETTER K
0x006c: 0x006c, # LATIN SMALL LETTER L
0x006d: 0x006d, # LATIN SMALL LETTER M
0x006e: 0x006e, # LATIN SMALL LETTER N
0x006f: 0x006f, # LATIN SMALL LETTER O
0x0070: 0x0070, # LATIN SMALL LETTER P
0x0071: 0x0071, # LATIN SMALL LETTER Q
0x0072: 0x0072, # LATIN SMALL LETTER R
0x0073: 0x0073, # LATIN SMALL LETTER S
0x0074: 0x0074, # LATIN SMALL LETTER T
0x0075: 0x0075, # LATIN SMALL LETTER U
0x0076: 0x0076, # LATIN SMALL LETTER V
0x0077: 0x0077, # LATIN SMALL LETTER W
0x0078: 0x0078, # LATIN SMALL LETTER X
0x0079: 0x0079, # LATIN SMALL LETTER Y
0x007a: 0x007a, # LATIN SMALL LETTER Z
0x007b: 0x007b, # LEFT CURLY BRACKET
0x007c: 0x007c, # VERTICAL LINE
0x007d: 0x007d, # RIGHT CURLY BRACKET
0x007e: 0x007e, # TILDE
0x007f: 0x007f, # DELETE
0x00a0: 0x00ff, # NO-BREAK SPACE
0x00a1: 0x00ad, # INVERTED EXCLAMATION MARK
0x00a2: 0x009b, # CENT SIGN
0x00a3: 0x009c, # POUND SIGN
0x00aa: 0x00a6, # FEMININE ORDINAL INDICATOR
0x00ab: 0x00ae, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
0x00ac: 0x00aa, # NOT SIGN
0x00b0: 0x00f8, # DEGREE SIGN
0x00b1: 0x00f1, # PLUS-MINUS SIGN
0x00b2: 0x00fd, # SUPERSCRIPT TWO
0x00b5: 0x00e6, # MICRO SIGN
0x00b7: 0x00fa, # MIDDLE DOT
0x00ba: 0x00a7, # MASCULINE ORDINAL INDICATOR
0x00bb: 0x00af, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
0x00bc: 0x00ac, # VULGAR FRACTION ONE QUARTER
0x00bd: 0x00ab, # VULGAR FRACTION ONE HALF
0x00bf: 0x00a8, # INVERTED QUESTION MARK
0x00c0: 0x0091, # LATIN CAPITAL LETTER A WITH GRAVE
0x00c1: 0x0086, # LATIN CAPITAL LETTER A WITH ACUTE
0x00c2: 0x008f, # LATIN CAPITAL LETTER A WITH CIRCUMFLEX
0x00c3: 0x008e, # LATIN CAPITAL LETTER A WITH TILDE
0x00c7: 0x0080, # LATIN CAPITAL LETTER C WITH CEDILLA
0x00c8: 0x0092, # LATIN CAPITAL LETTER E WITH GRAVE
0x00c9: 0x0090, # LATIN CAPITAL LETTER E WITH ACUTE
0x00ca: 0x0089, # LATIN CAPITAL LETTER E WITH CIRCUMFLEX
0x00cc: 0x0098, # LATIN CAPITAL LETTER I WITH GRAVE
0x00cd: 0x008b, # LATIN CAPITAL LETTER I WITH ACUTE
0x00d1: 0x00a5, # LATIN CAPITAL LETTER N WITH TILDE
0x00d2: 0x00a9, # LATIN CAPITAL LETTER O WITH GRAVE
0x00d3: 0x009f, # LATIN CAPITAL LETTER O WITH ACUTE
0x00d4: 0x008c, # LATIN CAPITAL LETTER O WITH CIRCUMFLEX
0x00d5: 0x0099, # LATIN CAPITAL LETTER O WITH TILDE
0x00d9: 0x009d, # LATIN CAPITAL LETTER U WITH GRAVE
0x00da: 0x0096, # LATIN CAPITAL LETTER U WITH ACUTE
0x00dc: 0x009a, # LATIN CAPITAL LETTER U WITH DIAERESIS
0x00df: 0x00e1, # LATIN SMALL LETTER SHARP S
0x00e0: 0x0085, # LATIN SMALL LETTER A WITH GRAVE
0x00e1: 0x00a0, # LATIN SMALL LETTER A WITH ACUTE
0x00e2: 0x0083, # LATIN SMALL LETTER A WITH CIRCUMFLEX
0x00e3: 0x0084, # LATIN SMALL LETTER A WITH TILDE
0x00e7: 0x0087, # LATIN SMALL LETTER C WITH CEDILLA
0x00e8: 0x008a, # LATIN SMALL LETTER E WITH GRAVE
0x00e9: 0x0082, # LATIN SMALL LETTER E WITH ACUTE
0x00ea: 0x0088, # LATIN SMALL LETTER E WITH CIRCUMFLEX
0x00ec: 0x008d, # LATIN SMALL LETTER I WITH GRAVE
0x00ed: 0x00a1, # LATIN SMALL LETTER I WITH ACUTE
0x00f1: 0x00a4, # LATIN SMALL LETTER N WITH TILDE
0x00f2: 0x0095, # LATIN SMALL LETTER O WITH GRAVE
0x00f3: 0x00a2, # LATIN SMALL LETTER O WITH ACUTE
0x00f4: 0x0093, # LATIN SMALL LETTER O WITH CIRCUMFLEX
0x00f5: 0x0094, # LATIN SMALL LETTER O WITH TILDE
0x00f7: 0x00f6, # DIVISION SIGN
0x00f9: 0x0097, # LATIN SMALL LETTER U WITH GRAVE
0x00fa: 0x00a3, # LATIN SMALL LETTER U WITH ACUTE
0x00fc: 0x0081, # LATIN SMALL LETTER U WITH DIAERESIS
0x0393: 0x00e2, # GREEK CAPITAL LETTER GAMMA
0x0398: 0x00e9, # GREEK CAPITAL LETTER THETA
0x03a3: 0x00e4, # GREEK CAPITAL LETTER SIGMA
0x03a6: 0x00e8, # GREEK CAPITAL LETTER PHI
0x03a9: 0x00ea, # GREEK CAPITAL LETTER OMEGA
0x03b1: 0x00e0, # GREEK SMALL LETTER ALPHA
0x03b4: 0x00eb, # GREEK SMALL LETTER DELTA
0x03b5: 0x00ee, # GREEK SMALL LETTER EPSILON
0x03c0: 0x00e3, # GREEK SMALL LETTER PI
0x03c3: 0x00e5, # GREEK SMALL LETTER SIGMA
0x03c4: 0x00e7, # GREEK SMALL LETTER TAU
0x03c6: 0x00ed, # GREEK SMALL LETTER PHI
0x207f: 0x00fc, # SUPERSCRIPT LATIN SMALL LETTER N
0x20a7: 0x009e, # PESETA SIGN
0x2219: 0x00f9, # BULLET OPERATOR
0x221a: 0x00fb, # SQUARE ROOT
0x221e: 0x00ec, # INFINITY
0x2229: 0x00ef, # INTERSECTION
0x2248: 0x00f7, # ALMOST EQUAL TO
0x2261: 0x00f0, # IDENTICAL TO
0x2264: 0x00f3, # LESS-THAN OR EQUAL TO
0x2265: 0x00f2, # GREATER-THAN OR EQUAL TO
0x2320: 0x00f4, # TOP HALF INTEGRAL
0x2321: 0x00f5, # BOTTOM HALF INTEGRAL
0x2500: 0x00c4, # BOX DRAWINGS LIGHT HORIZONTAL
0x2502: 0x00b3, # BOX DRAWINGS LIGHT VERTICAL
0x250c: 0x00da, # BOX DRAWINGS LIGHT DOWN AND RIGHT
0x2510: 0x00bf, # BOX DRAWINGS LIGHT DOWN AND LEFT
0x2514: 0x00c0, # BOX DRAWINGS LIGHT UP AND RIGHT
0x2518: 0x00d9, # BOX DRAWINGS LIGHT UP AND LEFT
0x251c: 0x00c3, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT
0x2524: 0x00b4, # BOX DRAWINGS LIGHT VERTICAL AND LEFT
0x252c: 0x00c2, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL
0x2534: 0x00c1, # BOX DRAWINGS LIGHT UP AND HORIZONTAL
0x253c: 0x00c5, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL
0x2550: 0x00cd, # BOX DRAWINGS DOUBLE HORIZONTAL
0x2551: 0x00ba, # BOX DRAWINGS DOUBLE VERTICAL
0x2552: 0x00d5, # BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE
0x2553: 0x00d6, # BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE
0x2554: 0x00c9, # BOX DRAWINGS DOUBLE DOWN AND RIGHT
0x2555: 0x00b8, # BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE
0x2556: 0x00b7, # BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE
0x2557: 0x00bb, # BOX DRAWINGS DOUBLE DOWN AND LEFT
0x2558: 0x00d4, # BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE
0x2559: 0x00d3, # BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE
0x255a: 0x00c8, # BOX DRAWINGS DOUBLE UP AND RIGHT
0x255b: 0x00be, # BOX DRAWINGS UP SINGLE AND LEFT DOUBLE
0x255c: 0x00bd, # BOX DRAWINGS UP DOUBLE AND LEFT SINGLE
0x255d: 0x00bc, # BOX DRAWINGS DOUBLE UP AND LEFT
0x255e: 0x00c6, # BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE
0x255f: 0x00c7, # BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE
0x2560: 0x00cc, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT
0x2561: 0x00b5, # BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE
0x2562: 0x00b6, # BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE
0x2563: 0x00b9, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT
0x2564: 0x00d1, # BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE
0x2565: 0x00d2, # BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE
0x2566: 0x00cb, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL
0x2567: 0x00cf, # BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE
0x2568: 0x00d0, # BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE
0x2569: 0x00ca, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL
0x256a: 0x00d8, # BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE
0x256b: 0x00d7, # BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE
0x256c: 0x00ce, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL
0x2580: 0x00df, # UPPER HALF BLOCK
0x2584: 0x00dc, # LOWER HALF BLOCK
0x2588: 0x00db, # FULL BLOCK
0x258c: 0x00dd, # LEFT HALF BLOCK
0x2590: 0x00de, # RIGHT HALF BLOCK
0x2591: 0x00b0, # LIGHT SHADE
0x2592: 0x00b1, # MEDIUM SHADE
0x2593: 0x00b2, # DARK SHADE
0x25a0: 0x00fe, # BLACK SQUARE
}
| apache-2.0 |
TNT-Samuel/Coding-Projects | DNS Server/Source/Lib/site-packages/joblib/externals/loky/backend/popen_loky_posix.py | 4 | 7132 | ###############################################################################
# Popen for LokyProcess.
#
# author: Thomas Moreau and Olivier Grisel
#
import os
import sys
import signal
import pickle
from io import BytesIO
from . import reduction, spawn
from .context import get_spawning_popen, set_spawning_popen
from multiprocessing import util, process
if sys.version_info[:2] < (3, 3):
ProcessLookupError = OSError
if sys.platform != "win32":
from . import semaphore_tracker
__all__ = []
if sys.platform != "win32":
#
# Wrapper for an fd used while launching a process
#
class _DupFd(object):
def __init__(self, fd):
self.fd = reduction._mk_inheritable(fd)
def detach(self):
return self.fd
#
# Start child process using subprocess.Popen
#
__all__.append('Popen')
class Popen(object):
method = 'loky'
DupFd = _DupFd
def __init__(self, process_obj):
sys.stdout.flush()
sys.stderr.flush()
self.returncode = None
self._fds = []
self._launch(process_obj)
if sys.version_info < (3, 4):
@classmethod
def duplicate_for_child(cls, fd):
popen = get_spawning_popen()
popen._fds.append(fd)
return reduction._mk_inheritable(fd)
else:
def duplicate_for_child(self, fd):
self._fds.append(fd)
return reduction._mk_inheritable(fd)
def poll(self, flag=os.WNOHANG):
if self.returncode is None:
while True:
try:
pid, sts = os.waitpid(self.pid, flag)
except OSError as e:
# Child process not yet created. See #1731717
# e.errno == errno.ECHILD == 10
return None
else:
break
if pid == self.pid:
if os.WIFSIGNALED(sts):
self.returncode = -os.WTERMSIG(sts)
else:
assert os.WIFEXITED(sts)
self.returncode = os.WEXITSTATUS(sts)
return self.returncode
def wait(self, timeout=None):
if sys.version_info < (3, 3):
import time
if timeout is None:
return self.poll(0)
deadline = time.time() + timeout
delay = 0.0005
while 1:
res = self.poll()
if res is not None:
break
remaining = deadline - time.time()
if remaining <= 0:
break
delay = min(delay * 2, remaining, 0.05)
time.sleep(delay)
return res
if self.returncode is None:
if timeout is not None:
from multiprocessing.connection import wait
if not wait([self.sentinel], timeout):
return None
# This shouldn't block if wait() returned successfully.
return self.poll(os.WNOHANG if timeout == 0.0 else 0)
return self.returncode
def terminate(self):
if self.returncode is None:
try:
os.kill(self.pid, signal.SIGTERM)
except ProcessLookupError:
pass
except OSError:
if self.wait(timeout=0.1) is None:
raise
def _launch(self, process_obj):
tracker_fd = semaphore_tracker._semaphore_tracker.getfd()
fp = BytesIO()
set_spawning_popen(self)
try:
prep_data = spawn.get_preparation_data(
process_obj._name, process_obj.init_main_module)
reduction.dump(prep_data, fp)
reduction.dump(process_obj, fp)
finally:
set_spawning_popen(None)
try:
parent_r, child_w = os.pipe()
child_r, parent_w = os.pipe()
# for fd in self._fds:
# _mk_inheritable(fd)
cmd_python = [sys.executable]
cmd_python += ['-m', self.__module__]
cmd_python += ['--process-name', str(process_obj.name)]
cmd_python += ['--pipe',
str(reduction._mk_inheritable(child_r))]
reduction._mk_inheritable(child_w)
if tracker_fd is not None:
cmd_python += ['--semaphore',
str(reduction._mk_inheritable(tracker_fd))]
self._fds.extend([child_r, child_w, tracker_fd])
util.debug("launch python with cmd:\n%s" % cmd_python)
from .fork_exec import fork_exec
pid = fork_exec(cmd_python, self._fds)
self.sentinel = parent_r
method = 'getbuffer'
if not hasattr(fp, method):
method = 'getvalue'
with os.fdopen(parent_w, 'wb') as f:
f.write(getattr(fp, method)())
self.pid = pid
finally:
if parent_r is not None:
util.Finalize(self, os.close, (parent_r,))
for fd in (child_r, child_w):
if fd is not None:
os.close(fd)
@staticmethod
def thread_is_spawning():
return True
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser('Command line parser')
parser.add_argument('--pipe', type=int, required=True,
help='File handle for the pipe')
parser.add_argument('--semaphore', type=int, required=True,
help='File handle name for the semaphore tracker')
parser.add_argument('--process-name', type=str, default=None,
help='Identifier for debugging purpose')
args = parser.parse_args()
info = dict()
semaphore_tracker._semaphore_tracker._fd = args.semaphore
exitcode = 1
try:
with os.fdopen(args.pipe, 'rb') as from_parent:
process.current_process()._inheriting = True
try:
prep_data = pickle.load(from_parent)
spawn.prepare(prep_data)
process_obj = pickle.load(from_parent)
finally:
del process.current_process()._inheriting
exitcode = process_obj._bootstrap()
except Exception as e:
print('\n\n' + '-' * 80)
print('{} failed with traceback: '.format(args.process_name))
print('-' * 80)
import traceback
print(traceback.format_exc())
print('\n' + '-' * 80)
finally:
if from_parent is not None:
from_parent.close()
sys.exit(exitcode)
| gpl-3.0 |
johnkit/vtk-dev | ThirdParty/Twisted/twisted/trial/test/test_assertions.py | 23 | 42547 | # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Tests for assertions provided by C{SynchronousTestCase} and C{TestCase},
provided by L{twisted.trial.unittest}.
L{TestFailureTests} demonstrates that L{SynchronousTestCase.fail} works, so that
is the only method on C{twisted.trial.unittest.SynchronousTestCase} that is
initially assumed to work. The test classes are arranged so that the methods
demonstrated to work earlier in the file are used by those later in the file
(even though the runner will probably not run the tests in this order).
"""
from __future__ import division, absolute_import
import warnings
from pprint import pformat
import unittest as pyunit
from twisted.python.util import FancyEqMixin
from twisted.python.reflect import prefixedMethods, accumulateMethods
from twisted.python.deprecate import deprecated
from twisted.python.versions import Version, getVersionString
from twisted.python.failure import Failure
from twisted.trial import unittest
from twisted.internet.defer import Deferred, fail, succeed
class MockEquality(FancyEqMixin, object):
compareAttributes = ("name",)
def __init__(self, name):
self.name = name
def __repr__(self):
return "MockEquality(%s)" % (self.name,)
class ComparisonError(object):
"""
An object which raises exceptions from its comparison methods.
"""
def _error(self, other):
raise ValueError("Comparison is broken")
__eq__ = __ne__ = _error
class TestFailureTests(pyunit.TestCase):
"""
Tests for the most basic functionality of L{SynchronousTestCase}, for
failing tests.
This class contains tests to demonstrate that L{SynchronousTestCase.fail}
can be used to fail a test, and that that failure is reflected in the test
result object. This should be sufficient functionality so that further
tests can be built on L{SynchronousTestCase} instead of
L{unittest.TestCase}. This depends on L{unittest.TestCase} working.
"""
class FailingTest(unittest.SynchronousTestCase):
def test_fails(self):
self.fail("This test fails.")
def setUp(self):
"""
Load a suite of one test which can be used to exercise the failure
handling behavior.
"""
components = [
__name__, self.__class__.__name__, self.FailingTest.__name__]
self.loader = pyunit.TestLoader()
self.suite = self.loader.loadTestsFromName(".".join(components))
self.test = list(self.suite)[0]
def test_fail(self):
"""
L{SynchronousTestCase.fail} raises
L{SynchronousTestCase.failureException} with the given argument.
"""
try:
self.test.fail("failed")
except self.test.failureException as result:
self.assertEqual("failed", str(result))
else:
self.fail(
"SynchronousTestCase.fail method did not raise "
"SynchronousTestCase.failureException")
def test_failingExceptionFails(self):
"""
When a test method raises L{SynchronousTestCase.failureException}, the test is
marked as having failed on the L{TestResult}.
"""
result = pyunit.TestResult()
self.suite.run(result)
self.failIf(result.wasSuccessful())
self.assertEqual(result.errors, [])
self.assertEqual(len(result.failures), 1)
self.assertEqual(result.failures[0][0], self.test)
class AssertFalseTests(unittest.SynchronousTestCase):
"""
Tests for L{SynchronousTestCase}'s C{assertFalse} and C{failIf} assertion
methods.
This is pretty paranoid. Still, a certain paranoia is healthy if you
are testing a unit testing framework.
@note: As of 11.2, C{assertFalse} is preferred over C{failIf}.
"""
def _assertFalseFalse(self, method):
"""
Perform the positive case test for C{failIf} or C{assertFalse}.
@param method: The test method to test.
"""
for notTrue in [0, 0.0, False, None, (), []]:
result = method(notTrue, "failed on %r" % (notTrue,))
if result != notTrue:
self.fail("Did not return argument %r" % (notTrue,))
def _assertFalseTrue(self, method):
"""
Perform the negative case test for C{failIf} or C{assertFalse}.
@param method: The test method to test.
"""
for true in [1, True, 'cat', [1,2], (3,4)]:
try:
method(true, "failed on %r" % (true,))
except self.failureException as e:
if str(e) != "failed on %r" % (true,):
self.fail("Raised incorrect exception on %r: %r" % (true, e))
else:
self.fail("Call to failIf(%r) didn't fail" % (true,))
def test_failIfFalse(self):
"""
L{SynchronousTestCase.failIf} returns its argument if its argument is
not considered true.
"""
self._assertFalseFalse(self.failIf)
def test_assertFalseFalse(self):
"""
L{SynchronousTestCase.assertFalse} returns its argument if its argument
is not considered true.
"""
self._assertFalseFalse(self.assertFalse)
def test_failIfTrue(self):
"""
L{SynchronousTestCase.failIf} raises
L{SynchronousTestCase.failureException} if its argument is considered
true.
"""
self._assertFalseTrue(self.failIf)
def test_assertFalseTrue(self):
"""
L{SynchronousTestCase.assertFalse} raises
L{SynchronousTestCase.failureException} if its argument is considered
true.
"""
self._assertFalseTrue(self.assertFalse)
class AssertTrueTests(unittest.SynchronousTestCase):
"""
Tests for L{SynchronousTestCase}'s C{assertTrue} and C{failUnless} assertion
methods.
This is pretty paranoid. Still, a certain paranoia is healthy if you
are testing a unit testing framework.
@note: As of 11.2, C{assertTrue} is preferred over C{failUnless}.
"""
def _assertTrueFalse(self, method):
"""
Perform the negative case test for C{assertTrue} and C{failUnless}.
@param method: The test method to test.
"""
for notTrue in [0, 0.0, False, None, (), []]:
try:
method(notTrue, "failed on %r" % (notTrue,))
except self.failureException as e:
if str(e) != "failed on %r" % (notTrue,):
self.fail(
"Raised incorrect exception on %r: %r" % (notTrue, e))
else:
self.fail(
"Call to %s(%r) didn't fail" % (method.__name__, notTrue,))
def _assertTrueTrue(self, method):
"""
Perform the positive case test for C{assertTrue} and C{failUnless}.
@param method: The test method to test.
"""
for true in [1, True, 'cat', [1,2], (3,4)]:
result = method(true, "failed on %r" % (true,))
if result != true:
self.fail("Did not return argument %r" % (true,))
def test_assertTrueFalse(self):
"""
L{SynchronousTestCase.assertTrue} raises
L{SynchronousTestCase.failureException} if its argument is not
considered true.
"""
self._assertTrueFalse(self.assertTrue)
def test_failUnlessFalse(self):
"""
L{SynchronousTestCase.failUnless} raises
L{SynchronousTestCase.failureException} if its argument is not
considered true.
"""
self._assertTrueFalse(self.failUnless)
def test_assertTrueTrue(self):
"""
L{SynchronousTestCase.assertTrue} returns its argument if its argument
is considered true.
"""
self._assertTrueTrue(self.assertTrue)
def test_failUnlessTrue(self):
"""
L{SynchronousTestCase.failUnless} returns its argument if its argument
is considered true.
"""
self._assertTrueTrue(self.failUnless)
class TestSynchronousAssertions(unittest.SynchronousTestCase):
"""
Tests for L{SynchronousTestCase}'s assertion methods. That is, failUnless*,
failIf*, assert* (not covered by other more specific test classes).
Note: As of 11.2, assertEqual is preferred over the failUnlessEqual(s)
variants. Tests have been modified to reflect this preference.
This is pretty paranoid. Still, a certain paranoia is healthy if you are
testing a unit testing framework.
"""
def _testEqualPair(self, first, second):
x = self.assertEqual(first, second)
if x != first:
self.fail("assertEqual should return first parameter")
def _testUnequalPair(self, first, second):
try:
self.assertEqual(first, second)
except self.failureException as e:
expected = 'not equal:\na = %s\nb = %s\n' % (
pformat(first), pformat(second))
if str(e) != expected:
self.fail("Expected: %r; Got: %s" % (expected, str(e)))
else:
self.fail("Call to assertEqual(%r, %r) didn't fail"
% (first, second))
def test_assertEqual_basic(self):
self._testEqualPair('cat', 'cat')
self._testUnequalPair('cat', 'dog')
self._testEqualPair([1], [1])
self._testUnequalPair([1], 'orange')
def test_assertEqual_custom(self):
x = MockEquality('first')
y = MockEquality('second')
z = MockEquality('first')
self._testEqualPair(x, x)
self._testEqualPair(x, z)
self._testUnequalPair(x, y)
self._testUnequalPair(y, z)
def test_assertEqualMessage(self):
"""
When a message is passed to L{assertEqual}, it is included in the
error message.
"""
exception = self.assertRaises(
self.failureException, self.assertEqual,
'foo', 'bar', 'message')
self.assertEqual(
str(exception),
"message\nnot equal:\na = 'foo'\nb = 'bar'\n")
def test_assertEqualNoneMessage(self):
"""
If a message is specified as C{None}, it is not included in the error
message of L{assertEqual}.
"""
exception = self.assertRaises(
self.failureException, self.assertEqual, 'foo', 'bar', None)
self.assertEqual(str(exception), "not equal:\na = 'foo'\nb = 'bar'\n")
def test_assertEqual_incomparable(self):
apple = ComparisonError()
orange = ["orange"]
try:
self.assertEqual(apple, orange)
except self.failureException:
self.fail("Fail raised when ValueError ought to have been raised.")
except ValueError:
# good. error not swallowed
pass
else:
self.fail("Comparing %r and %r should have raised an exception"
% (apple, orange))
def _raiseError(self, error):
raise error
def test_failUnlessRaises_expected(self):
x = self.failUnlessRaises(ValueError, self._raiseError, ValueError)
self.failUnless(isinstance(x, ValueError),
"Expect failUnlessRaises to return instance of raised "
"exception.")
def test_failUnlessRaises_unexpected(self):
try:
self.failUnlessRaises(ValueError, self._raiseError, TypeError)
except TypeError:
self.fail("failUnlessRaises shouldn't re-raise unexpected "
"exceptions")
except self.failureException:
# what we expect
pass
else:
self.fail("Expected exception wasn't raised. Should have failed")
def test_failUnlessRaises_noException(self):
try:
self.failUnlessRaises(ValueError, lambda : None)
except self.failureException as e:
self.assertEqual(str(e),
'ValueError not raised (None returned)')
else:
self.fail("Exception not raised. Should have failed")
def test_failUnlessRaises_failureException(self):
x = self.failUnlessRaises(self.failureException, self._raiseError,
self.failureException)
self.failUnless(isinstance(x, self.failureException),
"Expected %r instance to be returned"
% (self.failureException,))
try:
x = self.failUnlessRaises(self.failureException, self._raiseError,
ValueError)
except self.failureException:
# what we expect
pass
else:
self.fail("Should have raised exception")
def test_failIfEqual_basic(self):
x, y, z = [1], [2], [1]
ret = self.failIfEqual(x, y)
self.assertEqual(ret, x,
"failIfEqual should return first parameter")
self.failUnlessRaises(self.failureException,
self.failIfEqual, x, x)
self.failUnlessRaises(self.failureException,
self.failIfEqual, x, z)
def test_failIfEqual_customEq(self):
x = MockEquality('first')
y = MockEquality('second')
z = MockEquality('fecund')
ret = self.failIfEqual(x, y)
self.assertEqual(ret, x,
"failIfEqual should return first parameter")
self.failUnlessRaises(self.failureException,
self.failIfEqual, x, x)
self.failIfEqual(x, z, "__ne__ should make these not equal")
def test_failIfIdenticalPositive(self):
"""
C{failIfIdentical} returns its first argument if its first and second
arguments are not the same object.
"""
x = object()
y = object()
result = self.failIfIdentical(x, y)
self.assertEqual(x, result)
def test_failIfIdenticalNegative(self):
"""
C{failIfIdentical} raises C{failureException} if its first and second
arguments are the same object.
"""
x = object()
self.failUnlessRaises(self.failureException,
self.failIfIdentical, x, x)
def test_failUnlessIdentical(self):
x, y, z = [1], [1], [2]
ret = self.failUnlessIdentical(x, x)
self.assertEqual(ret, x,
'failUnlessIdentical should return first '
'parameter')
self.failUnlessRaises(self.failureException,
self.failUnlessIdentical, x, y)
self.failUnlessRaises(self.failureException,
self.failUnlessIdentical, x, z)
def test_failUnlessApproximates(self):
x, y, z = 1.0, 1.1, 1.2
self.failUnlessApproximates(x, x, 0.2)
ret = self.failUnlessApproximates(x, y, 0.2)
self.assertEqual(ret, x, "failUnlessApproximates should return "
"first parameter")
self.failUnlessRaises(self.failureException,
self.failUnlessApproximates, x, z, 0.1)
self.failUnlessRaises(self.failureException,
self.failUnlessApproximates, x, y, 0.1)
def test_failUnlessAlmostEqual(self):
precision = 5
x = 8.000001
y = 8.00001
z = 8.000002
self.failUnlessAlmostEqual(x, x, precision)
ret = self.failUnlessAlmostEqual(x, z, precision)
self.assertEqual(ret, x, "failUnlessAlmostEqual should return "
"first parameter (%r, %r)" % (ret, x))
self.failUnlessRaises(self.failureException,
self.failUnlessAlmostEqual, x, y, precision)
def test_failIfAlmostEqual(self):
precision = 5
x = 8.000001
y = 8.00001
z = 8.000002
ret = self.failIfAlmostEqual(x, y, precision)
self.assertEqual(ret, x, "failIfAlmostEqual should return "
"first parameter (%r, %r)" % (ret, x))
self.failUnlessRaises(self.failureException,
self.failIfAlmostEqual, x, x, precision)
self.failUnlessRaises(self.failureException,
self.failIfAlmostEqual, x, z, precision)
def test_failUnlessSubstring(self):
x = "cat"
y = "the dog sat"
z = "the cat sat"
self.failUnlessSubstring(x, x)
ret = self.failUnlessSubstring(x, z)
self.assertEqual(ret, x, 'should return first parameter')
self.failUnlessRaises(self.failureException,
self.failUnlessSubstring, x, y)
self.failUnlessRaises(self.failureException,
self.failUnlessSubstring, z, x)
def test_failIfSubstring(self):
x = "cat"
y = "the dog sat"
z = "the cat sat"
self.failIfSubstring(z, x)
ret = self.failIfSubstring(x, y)
self.assertEqual(ret, x, 'should return first parameter')
self.failUnlessRaises(self.failureException,
self.failIfSubstring, x, x)
self.failUnlessRaises(self.failureException,
self.failIfSubstring, x, z)
def test_assertIs(self):
"""
L{assertIs} passes if two objects are identical.
"""
a = MockEquality("first")
self.assertIs(a, a)
def test_assertIsError(self):
"""
L{assertIs} fails if two objects are not identical.
"""
a, b = MockEquality("first"), MockEquality("first")
self.assertEqual(a, b)
self.assertRaises(self.failureException, self.assertIs, a, b)
def test_assertIsNot(self):
"""
L{assertIsNot} passes if two objects are not identical.
"""
a, b = MockEquality("first"), MockEquality("first")
self.assertEqual(a, b)
self.assertIsNot(a, b)
def test_assertIsNotError(self):
"""
L{assertIsNot} fails if two objects are identical.
"""
a = MockEquality("first")
self.assertRaises(self.failureException, self.assertIsNot, a, a)
def test_assertIsInstance(self):
"""
Test a true condition of assertIsInstance.
"""
A = type('A', (object,), {})
a = A()
self.assertIsInstance(a, A)
def test_assertIsInstanceMultipleClasses(self):
"""
Test a true condition of assertIsInstance with multiple classes.
"""
A = type('A', (object,), {})
B = type('B', (object,), {})
a = A()
self.assertIsInstance(a, (A, B))
def test_assertIsInstanceError(self):
"""
Test an error with assertIsInstance.
"""
A = type('A', (object,), {})
B = type('B', (object,), {})
a = A()
self.assertRaises(self.failureException, self.assertIsInstance, a, B)
def test_assertIsInstanceErrorMultipleClasses(self):
"""
Test an error with assertIsInstance and multiple classes.
"""
A = type('A', (object,), {})
B = type('B', (object,), {})
C = type('C', (object,), {})
a = A()
self.assertRaises(self.failureException, self.assertIsInstance, a, (B, C))
def test_assertIsInstanceCustomMessage(self):
"""
If L{TestCase.assertIsInstance} is passed a custom message as its 3rd
argument, the message is included in the failure exception raised when
the assertion fails.
"""
exc = self.assertRaises(
self.failureException,
self.assertIsInstance, 3, str, "Silly assertion")
self.assertIn("Silly assertion", str(exc))
def test_assertNotIsInstance(self):
"""
Test a true condition of assertNotIsInstance.
"""
A = type('A', (object,), {})
B = type('B', (object,), {})
a = A()
self.assertNotIsInstance(a, B)
def test_assertNotIsInstanceMultipleClasses(self):
"""
Test a true condition of assertNotIsInstance and multiple classes.
"""
A = type('A', (object,), {})
B = type('B', (object,), {})
C = type('C', (object,), {})
a = A()
self.assertNotIsInstance(a, (B, C))
def test_assertNotIsInstanceError(self):
"""
Test an error with assertNotIsInstance.
"""
A = type('A', (object,), {})
a = A()
error = self.assertRaises(self.failureException,
self.assertNotIsInstance, a, A)
self.assertEqual(str(error), "%r is an instance of %s" % (a, A))
def test_assertNotIsInstanceErrorMultipleClasses(self):
"""
Test an error with assertNotIsInstance and multiple classes.
"""
A = type('A', (object,), {})
B = type('B', (object,), {})
a = A()
self.assertRaises(self.failureException, self.assertNotIsInstance, a, (A, B))
def test_assertDictEqual(self):
"""
L{twisted.trial.unittest.TestCase} supports the C{assertDictEqual}
method inherited from the standard library in Python 2.7.
"""
self.assertDictEqual({'a': 1}, {'a': 1})
if getattr(unittest.SynchronousTestCase, 'assertDictEqual', None) is None:
test_assertDictEqual.skip = (
"assertDictEqual is not available on this version of Python")
class WarningAssertionTests(unittest.SynchronousTestCase):
def test_assertWarns(self):
"""
Test basic assertWarns report.
"""
def deprecated(a):
warnings.warn("Woo deprecated", category=DeprecationWarning)
return a
r = self.assertWarns(DeprecationWarning, "Woo deprecated", __file__,
deprecated, 123)
self.assertEqual(r, 123)
def test_assertWarnsRegistryClean(self):
"""
Test that assertWarns cleans the warning registry, so the warning is
not swallowed the second time.
"""
def deprecated(a):
warnings.warn("Woo deprecated", category=DeprecationWarning)
return a
r1 = self.assertWarns(DeprecationWarning, "Woo deprecated", __file__,
deprecated, 123)
self.assertEqual(r1, 123)
# The warning should be raised again
r2 = self.assertWarns(DeprecationWarning, "Woo deprecated", __file__,
deprecated, 321)
self.assertEqual(r2, 321)
def test_assertWarnsError(self):
"""
Test assertWarns failure when no warning is generated.
"""
def normal(a):
return a
self.assertRaises(self.failureException,
self.assertWarns, DeprecationWarning, "Woo deprecated", __file__,
normal, 123)
def test_assertWarnsWrongCategory(self):
"""
Test assertWarns failure when the category is wrong.
"""
def deprecated(a):
warnings.warn("Foo deprecated", category=DeprecationWarning)
return a
self.assertRaises(self.failureException,
self.assertWarns, UserWarning, "Foo deprecated", __file__,
deprecated, 123)
def test_assertWarnsWrongMessage(self):
"""
Test assertWarns failure when the message is wrong.
"""
def deprecated(a):
warnings.warn("Foo deprecated", category=DeprecationWarning)
return a
self.assertRaises(self.failureException,
self.assertWarns, DeprecationWarning, "Bar deprecated", __file__,
deprecated, 123)
def test_assertWarnsWrongFile(self):
"""
If the warning emitted by a function refers to a different file than is
passed to C{assertWarns}, C{failureException} is raised.
"""
def deprecated(a):
# stacklevel=2 points at the direct caller of the function. The
# way assertRaises is invoked below, the direct caller will be
# something somewhere in trial, not something in this file. In
# Python 2.5 and earlier, stacklevel of 0 resulted in a warning
# pointing to the warnings module itself. Starting in Python 2.6,
# stacklevel of 0 and 1 both result in a warning pointing to *this*
# file, presumably due to the fact that the warn function is
# implemented in C and has no convenient Python
# filename/linenumber.
warnings.warn(
"Foo deprecated", category=DeprecationWarning, stacklevel=2)
self.assertRaises(
self.failureException,
# Since the direct caller isn't in this file, try to assert that
# the warning *does* point to this file, so that assertWarns raises
# an exception.
self.assertWarns, DeprecationWarning, "Foo deprecated", __file__,
deprecated, 123)
def test_assertWarnsOnClass(self):
"""
Test assertWarns works when creating a class instance.
"""
class Warn:
def __init__(self):
warnings.warn("Do not call me", category=RuntimeWarning)
r = self.assertWarns(RuntimeWarning, "Do not call me", __file__,
Warn)
self.assertTrue(isinstance(r, Warn))
r = self.assertWarns(RuntimeWarning, "Do not call me", __file__,
Warn)
self.assertTrue(isinstance(r, Warn))
def test_assertWarnsOnMethod(self):
"""
Test assertWarns works when used on an instance method.
"""
class Warn:
def deprecated(self, a):
warnings.warn("Bar deprecated", category=DeprecationWarning)
return a
w = Warn()
r = self.assertWarns(DeprecationWarning, "Bar deprecated", __file__,
w.deprecated, 321)
self.assertEqual(r, 321)
r = self.assertWarns(DeprecationWarning, "Bar deprecated", __file__,
w.deprecated, 321)
self.assertEqual(r, 321)
def test_assertWarnsOnCall(self):
"""
Test assertWarns works on instance with C{__call__} method.
"""
class Warn:
def __call__(self, a):
warnings.warn("Egg deprecated", category=DeprecationWarning)
return a
w = Warn()
r = self.assertWarns(DeprecationWarning, "Egg deprecated", __file__,
w, 321)
self.assertEqual(r, 321)
r = self.assertWarns(DeprecationWarning, "Egg deprecated", __file__,
w, 321)
self.assertEqual(r, 321)
def test_assertWarnsFilter(self):
"""
Test assertWarns on a warning filterd by default.
"""
def deprecated(a):
warnings.warn("Woo deprecated", category=PendingDeprecationWarning)
return a
r = self.assertWarns(PendingDeprecationWarning, "Woo deprecated",
__file__, deprecated, 123)
self.assertEqual(r, 123)
def test_assertWarnsMultipleWarnings(self):
"""
C{assertWarns} does not raise an exception if the function it is passed
triggers the same warning more than once.
"""
def deprecated():
warnings.warn("Woo deprecated", category=PendingDeprecationWarning)
def f():
deprecated()
deprecated()
self.assertWarns(
PendingDeprecationWarning, "Woo deprecated", __file__, f)
def test_assertWarnsDifferentWarnings(self):
"""
For now, assertWarns is unable to handle multiple different warnings,
so it should raise an exception if it's the case.
"""
def deprecated(a):
warnings.warn("Woo deprecated", category=DeprecationWarning)
warnings.warn("Another one", category=PendingDeprecationWarning)
e = self.assertRaises(self.failureException,
self.assertWarns, DeprecationWarning, "Woo deprecated",
__file__, deprecated, 123)
self.assertEqual(str(e), "Can't handle different warnings")
def test_assertWarnsAfterUnassertedWarning(self):
"""
Warnings emitted before L{TestCase.assertWarns} is called do not get
flushed and do not alter the behavior of L{TestCase.assertWarns}.
"""
class TheWarning(Warning):
pass
def f(message):
warnings.warn(message, category=TheWarning)
f("foo")
self.assertWarns(TheWarning, "bar", __file__, f, "bar")
[warning] = self.flushWarnings([f])
self.assertEqual(warning['message'], "foo")
class TestResultOfAssertions(unittest.SynchronousTestCase):
"""
Tests for L{SynchronousTestCase.successResultOf},
L{SynchronousTestCase.failureResultOf}, and
L{SynchronousTestCase.assertNoResult}.
"""
result = object()
failure = Failure(Exception("Bad times"))
def test_withoutSuccessResult(self):
"""
L{SynchronousTestCase.successResultOf} raises
L{SynchronousTestCase.failureException} when called with a L{Deferred}
with no current result.
"""
self.assertRaises(
self.failureException, self.successResultOf, Deferred())
def test_successResultOfWithFailure(self):
"""
L{SynchronousTestCase.successResultOf} raises
L{SynchronousTestCase.failureException} when called with a L{Deferred}
with a failure result.
"""
self.assertRaises(
self.failureException, self.successResultOf, fail(self.failure))
def test_successResultOfWithFailureHasTraceback(self):
"""
L{SynchronousTestCase.successResultOf} raises a
L{SynchronousTestCase.failureException} that has the original failure
traceback when called with a L{Deferred} with a failure result.
"""
try:
self.successResultOf(fail(self.failure))
except self.failureException as e:
self.assertIn(self.failure.getTraceback(), str(e))
def test_withoutFailureResult(self):
"""
L{SynchronousTestCase.failureResultOf} raises
L{SynchronousTestCase.failureException} when called with a L{Deferred}
with no current result.
"""
self.assertRaises(
self.failureException, self.failureResultOf, Deferred())
def test_failureResultOfWithSuccess(self):
"""
L{SynchronousTestCase.failureResultOf} raises
L{SynchronousTestCase.failureException} when called with a L{Deferred}
with a success result.
"""
self.assertRaises(
self.failureException, self.failureResultOf, succeed(self.result))
def test_failureResultOfWithWrongFailure(self):
"""
L{SynchronousTestCase.failureResultOf} raises
L{SynchronousTestCase.failureException} when called with a L{Deferred}
with a failure type that was not expected.
"""
self.assertRaises(
self.failureException, self.failureResultOf, fail(self.failure),
KeyError)
def test_failureResultOfWithWrongFailureOneExpectedFailure(self):
"""
L{SynchronousTestCase.failureResultOf} raises
L{SynchronousTestCase.failureException} when called with a L{Deferred}
with a failure type that was not expected, and the
L{SynchronousTestCase.failureException} message contains the original
failure traceback as well as the expected failure type
"""
try:
self.failureResultOf(fail(self.failure), KeyError)
except self.failureException as e:
self.assertIn(self.failure.getTraceback(), str(e))
self.assertIn(
"Failure of type ({0}.{1}) expected on".format(
KeyError.__module__, KeyError.__name__),
str(e))
def test_failureResultOfWithWrongFailureMultiExpectedFailure(self):
"""
L{SynchronousTestCase.failureResultOf} raises
L{SynchronousTestCase.failureException} when called with a L{Deferred}
with a failure type that was not expected, and the
L{SynchronousTestCase.failureException} message contains the original
failure traceback as well as the expected failure types in the error
message
"""
try:
self.failureResultOf(fail(self.failure), KeyError, IOError)
except self.failureException as e:
self.assertIn(self.failure.getTraceback(), str(e))
self.assertIn(
"Failure of type ({0}.{1} or {2}.{3}) expected on".format(
KeyError.__module__, KeyError.__name__,
IOError.__module__, IOError.__name__),
str(e))
def test_withSuccessResult(self):
"""
When passed a L{Deferred} which currently has a result (ie,
L{Deferred.addCallback} would cause the added callback to be called
before C{addCallback} returns), L{SynchronousTestCase.successResultOf}
returns that result.
"""
self.assertIdentical(
self.result, self.successResultOf(succeed(self.result)))
def test_withExpectedFailureResult(self):
"""
When passed a L{Deferred} which currently has a L{Failure} result (ie,
L{Deferred.addErrback} would cause the added errback to be called
before C{addErrback} returns), L{SynchronousTestCase.failureResultOf}
returns that L{Failure} if that L{Failure}'s type is expected.
"""
self.assertIdentical(
self.failure,
self.failureResultOf(fail(self.failure), self.failure.type,
KeyError))
def test_withFailureResult(self):
"""
When passed a L{Deferred} which currently has a L{Failure} result
(ie, L{Deferred.addErrback} would cause the added errback to be called
before C{addErrback} returns), L{SynchronousTestCase.failureResultOf}
returns that L{Failure}.
"""
self.assertIdentical(
self.failure, self.failureResultOf(fail(self.failure)))
def test_assertNoResultSuccess(self):
"""
When passed a L{Deferred} which currently has a success result (see
L{test_withSuccessResult}), L{SynchronousTestCase.assertNoResult} raises
L{SynchronousTestCase.failureException}.
"""
self.assertRaises(
self.failureException, self.assertNoResult, succeed(self.result))
def test_assertNoResultFailure(self):
"""
When passed a L{Deferred} which currently has a failure result (see
L{test_withFailureResult}), L{SynchronousTestCase.assertNoResult} raises
L{SynchronousTestCase.failureException}.
"""
self.assertRaises(
self.failureException, self.assertNoResult, fail(self.failure))
def test_assertNoResult(self):
"""
When passed a L{Deferred} with no current result,
"""
self.assertNoResult(Deferred())
def test_assertNoResultPropagatesSuccess(self):
"""
When passed a L{Deferred} with no current result, which is then
fired with a success result, L{SynchronousTestCase.assertNoResult}
doesn't modify the result of the L{Deferred}.
"""
d = Deferred()
self.assertNoResult(d)
d.callback(self.result)
self.assertEqual(self.result, self.successResultOf(d))
def test_assertNoResultPropagatesLaterFailure(self):
"""
When passed a L{Deferred} with no current result, which is then
fired with a L{Failure} result, L{SynchronousTestCase.assertNoResult}
doesn't modify the result of the L{Deferred}.
"""
d = Deferred()
self.assertNoResult(d)
d.errback(self.failure)
self.assertEqual(self.failure, self.failureResultOf(d))
def test_assertNoResultSwallowsImmediateFailure(self):
"""
When passed a L{Deferred} which currently has a L{Failure} result,
L{SynchronousTestCase.assertNoResult} changes the result of the
L{Deferred} to a success.
"""
d = fail(self.failure)
try:
self.assertNoResult(d)
except self.failureException:
pass
self.assertEqual(None, self.successResultOf(d))
class TestAssertionNames(unittest.SynchronousTestCase):
"""
Tests for consistency of naming within TestCase assertion methods
"""
def _getAsserts(self):
dct = {}
accumulateMethods(self, dct, 'assert')
return [ dct[k] for k in dct if not k.startswith('Not') and k != '_' ]
def _name(self, x):
return x.__name__
def test_failUnlessMatchesAssert(self):
"""
The C{failUnless*} test methods are a subset of the C{assert*} test
methods. This is intended to ensure that methods using the
I{failUnless} naming scheme are not added without corresponding methods
using the I{assert} naming scheme. The I{assert} naming scheme is
preferred, and new I{assert}-prefixed methods may be added without
corresponding I{failUnless}-prefixed methods.
"""
asserts = set(self._getAsserts())
failUnlesses = set(prefixedMethods(self, 'failUnless'))
self.assertEqual(
failUnlesses, asserts.intersection(failUnlesses))
def test_failIf_matches_assertNot(self):
asserts = prefixedMethods(unittest.SynchronousTestCase, 'assertNot')
failIfs = prefixedMethods(unittest.SynchronousTestCase, 'failIf')
self.assertEqual(sorted(asserts, key=self._name),
sorted(failIfs, key=self._name))
def test_equalSpelling(self):
for name, value in vars(self).items():
if not callable(value):
continue
if name.endswith('Equal'):
self.failUnless(hasattr(self, name+'s'),
"%s but no %ss" % (name, name))
self.assertEqual(value, getattr(self, name+'s'))
if name.endswith('Equals'):
self.failUnless(hasattr(self, name[:-1]),
"%s but no %s" % (name, name[:-1]))
self.assertEqual(value, getattr(self, name[:-1]))
class TestCallDeprecated(unittest.SynchronousTestCase):
"""
Test use of the L{SynchronousTestCase.callDeprecated} method with version objects.
"""
version = Version('Twisted', 8, 0, 0)
def test_callDeprecatedSuppressesWarning(self):
"""
callDeprecated calls a deprecated callable, suppressing the
deprecation warning.
"""
self.callDeprecated(self.version, oldMethod, 'foo')
self.assertEqual(
self.flushWarnings(), [], "No warnings should be shown")
def test_callDeprecatedCallsFunction(self):
"""
L{callDeprecated} actually calls the callable passed to it, and
forwards the result.
"""
result = self.callDeprecated(self.version, oldMethod, 'foo')
self.assertEqual('foo', result)
def test_failsWithoutDeprecation(self):
"""
L{callDeprecated} raises a test failure if the callable is not
deprecated.
"""
def notDeprecated():
pass
exception = self.assertRaises(
self.failureException,
self.callDeprecated, self.version, notDeprecated)
self.assertEqual(
"%r is not deprecated." % notDeprecated, str(exception))
def test_failsWithIncorrectDeprecation(self):
"""
callDeprecated raises a test failure if the callable was deprecated
at a different version to the one expected.
"""
differentVersion = Version('Foo', 1, 2, 3)
exception = self.assertRaises(
self.failureException,
self.callDeprecated,
differentVersion, oldMethod, 'foo')
self.assertIn(getVersionString(self.version), str(exception))
self.assertIn(getVersionString(differentVersion), str(exception))
def test_nestedDeprecation(self):
"""
L{callDeprecated} ignores all deprecations apart from the first.
Multiple warnings are generated when a deprecated function calls
another deprecated function. The first warning is the one generated by
the explicitly called function. That's the warning that we care about.
"""
differentVersion = Version('Foo', 1, 2, 3)
def nestedDeprecation(*args):
return oldMethod(*args)
nestedDeprecation = deprecated(differentVersion)(nestedDeprecation)
self.callDeprecated(differentVersion, nestedDeprecation, 24)
# The oldMethod deprecation should have been emitted too, not captured
# by callDeprecated. Flush it now to make sure it did happen and to
# prevent it from showing up on stdout.
warningsShown = self.flushWarnings()
self.assertEqual(len(warningsShown), 1)
def test_callDeprecationWithMessage(self):
"""
L{callDeprecated} can take a message argument used to check the warning
emitted.
"""
self.callDeprecated((self.version, "newMethod"),
oldMethodReplaced, 1)
def test_callDeprecationWithWrongMessage(self):
"""
If the message passed to L{callDeprecated} doesn't match,
L{callDeprecated} raises a test failure.
"""
exception = self.assertRaises(
self.failureException,
self.callDeprecated,
(self.version, "something.wrong"),
oldMethodReplaced, 1)
self.assertIn(getVersionString(self.version), str(exception))
self.assertIn("please use newMethod instead", str(exception))
@deprecated(TestCallDeprecated.version)
def oldMethod(x):
"""
Deprecated method for testing.
"""
return x
@deprecated(TestCallDeprecated.version, replacement="newMethod")
def oldMethodReplaced(x):
"""
Another deprecated method, which has been deprecated in favor of the
mythical 'newMethod'.
"""
return 2 * x
| bsd-3-clause |
rledisez/shinken | shinken/macroresolver.py | 17 | 17626 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
# Gregory Starck, g.starck@gmail.com
# Hartmut Goebel, h.goebel@goebel-consult.de
#
# This file is part of Shinken.
#
# Shinken 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.
#
# Shinken 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 Shinken. If not, see <http://www.gnu.org/licenses/>.
# This class resolve Macro in commands by looking at the macros list
# in Class of elements. It give a property that call be callable or not.
# It not callable, it's a simple property and replace the macro with the value
# If callable, it's a method that is called to get the value. for example, to
# get the number of service in a host, you call a method to get the
# len(host.services)
import re
import time
from shinken.borg import Borg
class MacroResolver(Borg):
"""Please Add a Docstring to describe the class here"""
my_type = 'macroresolver'
# Global macros
macros = {
'TOTALHOSTSUP': '_get_total_hosts_up',
'TOTALHOSTSDOWN': '_get_total_hosts_down',
'TOTALHOSTSUNREACHABLE': '_get_total_hosts_unreachable',
'TOTALHOSTSDOWNUNHANDLED': '_get_total_hosts_unhandled',
'TOTALHOSTSUNREACHABLEUNHANDLED': '_get_total_hosts_unreachable_unhandled',
'TOTALHOSTPROBLEMS': '_get_total_host_problems',
'TOTALHOSTPROBLEMSUNHANDLED': '_get_total_host_problems_unhandled',
'TOTALSERVICESOK': '_get_total_service_ok',
'TOTALSERVICESWARNING': '_get_total_services_warning',
'TOTALSERVICESCRITICAL': '_get_total_services_critical',
'TOTALSERVICESUNKNOWN': '_get_total_services_unknown',
'TOTALSERVICESWARNINGUNHANDLED': '_get_total_services_warning_unhandled',
'TOTALSERVICESCRITICALUNHANDLED': '_get_total_services_critical_unhandled',
'TOTALSERVICESUNKNOWNUNHANDLED': '_get_total_services_unknown_unhandled',
'TOTALSERVICEPROBLEMS': '_get_total_service_problems',
'TOTALSERVICEPROBLEMSUNHANDLED': '_get_total_service_problems_unhandled',
'LONGDATETIME': '_get_long_date_time',
'SHORTDATETIME': '_get_short_date_time',
'DATE': '_get_date',
'TIME': '_get_time',
'TIMET': '_get_timet',
'PROCESSSTARTTIME': '_get_process_start_time',
'EVENTSTARTTIME': '_get_events_start_time',
}
output_macros = [
'HOSTOUTPUT',
'HOSTPERFDATA',
'HOSTACKAUTHOR',
'HOSTACKCOMMENT',
'SERVICEOUTPUT',
'SERVICEPERFDATA',
'SERVICEACKAUTHOR',
'SERVICEACKCOMMENT'
]
# This must be called ONCE. It just put links for elements
# by scheduler
def init(self, conf):
# For searching class and elements for ondemand
# we need link to types
self.conf = conf
self.lists_on_demand = []
self.hosts = conf.hosts
# For special void host_name handling...
self.host_class = self.hosts.inner_class
self.lists_on_demand.append(self.hosts)
self.services = conf.services
self.contacts = conf.contacts
self.lists_on_demand.append(self.contacts)
self.hostgroups = conf.hostgroups
self.lists_on_demand.append(self.hostgroups)
self.commands = conf.commands
self.servicegroups = conf.servicegroups
self.lists_on_demand.append(self.servicegroups)
self.contactgroups = conf.contactgroups
self.lists_on_demand.append(self.contactgroups)
self.illegal_macro_output_chars = conf.illegal_macro_output_chars
# Try cache :)
# self.cache = {}
# Return all macros of a string, so cut the $
# And create a dict with it:
# val: value, not set here
# type: type of macro, like class one, or ARGN one
def _get_macros(self, s):
# if s in self.cache:
# return self.cache[s]
p = re.compile(r'(\$)')
elts = p.split(s)
macros = {}
in_macro = False
for elt in elts:
if elt == '$':
in_macro = not in_macro
elif in_macro:
macros[elt] = {'val': '', 'type': 'unknown'}
# self.cache[s] = macros
if '' in macros:
del macros['']
return macros
# Get a value from a property of a element
# Prop can be a function or a property
# So we call it or not
def _get_value_from_element(self, elt, prop):
try:
value = getattr(elt, prop)
if callable(value):
return unicode(value())
else:
return unicode(value)
except AttributeError, exp:
# Return no value
return ''
except UnicodeError, exp:
if isinstance(value, str):
return unicode(value, 'utf8', errors='ignore')
else:
return ''
# For some macros, we need to delete unwanted characters
def _delete_unwanted_caracters(self, s):
for c in self.illegal_macro_output_chars:
s = s.replace(c, '')
return s
# return a dict with all environment variable came from
# the macros of the datas object
def get_env_macros(self, data):
env = {}
for o in data:
cls = o.__class__
macros = cls.macros
for macro in macros:
if macro.startswith("USER"):
break
prop = macros[macro]
value = self._get_value_from_element(o, prop)
env['NAGIOS_%s' % macro] = value
if hasattr(o, 'customs'):
# make NAGIOS__HOSTMACADDR from _MACADDR
for cmacro in o.customs:
new_env_name = 'NAGIOS__' + o.__class__.__name__.upper() + cmacro[1:].upper()
env[new_env_name] = o.customs[cmacro]
return env
# This function will look at elements in data (and args if it filled)
# to replace the macros in c_line with real value.
def resolve_simple_macros_in_string(self, c_line, data, args=None):
# Now we prepare the classes for looking at the class.macros
data.append(self) # For getting global MACROS
if hasattr(self, 'conf'):
data.append(self.conf) # For USERN macros
clss = [d.__class__ for d in data]
# we should do some loops for nested macros
# like $USER1$ hiding like a ninja in a $ARG2$ Macro. And if
# $USER1$ is pointing to $USER34$ etc etc, we should loop
# until we reach the bottom. So the last loop is when we do
# not still have macros :)
still_got_macros = True
nb_loop = 0
while still_got_macros:
nb_loop += 1
# Ok, we want the macros in the command line
macros = self._get_macros(c_line)
# We can get out if we do not have macros this loop
still_got_macros = (len(macros) != 0)
# print "Still go macros:", still_got_macros
# Put in the macros the type of macro for all macros
self._get_type_of_macro(macros, clss)
# Now we get values from elements
for macro in macros:
# If type ARGN, look at ARGN cutting
if macros[macro]['type'] == 'ARGN' and args is not None:
macros[macro]['val'] = self._resolve_argn(macro, args)
macros[macro]['type'] = 'resolved'
# If class, get value from properties
if macros[macro]['type'] == 'class':
cls = macros[macro]['class']
for elt in data:
if elt is not None and elt.__class__ == cls:
prop = cls.macros[macro]
macros[macro]['val'] = self._get_value_from_element(elt, prop)
# Now check if we do not have a 'output' macro. If so, we must
# delete all special characters that can be dangerous
if macro in self.output_macros:
macros[macro]['val'] = \
self._delete_unwanted_caracters(macros[macro]['val'])
if macros[macro]['type'] == 'CUSTOM':
cls_type = macros[macro]['class']
# Beware : only cut the first _HOST value, so the macro name can have it on it..
macro_name = re.split('_' + cls_type, macro, 1)[1].upper()
# Ok, we've got the macro like MAC_ADDRESS for _HOSTMAC_ADDRESS
# Now we get the element in data that have the type HOST
# and we check if it got the custom value
for elt in data:
if elt is not None and elt.__class__.my_type.upper() == cls_type:
if '_' + macro_name in elt.customs:
macros[macro]['val'] = elt.customs['_' + macro_name]
# Then look on the macromodulations, in reserver order, so
# the last to set, will be the firt to have. (yes, don't want to play
# with break and such things sorry...)
mms = getattr(elt, 'macromodulations', [])
for mm in mms[::-1]:
# Look if the modulation got the value,
# but also if it's currently active
if '_' + macro_name in mm.customs and mm.is_active():
macros[macro]['val'] = mm.customs['_' + macro_name]
if macros[macro]['type'] == 'ONDEMAND':
macros[macro]['val'] = self._resolve_ondemand(macro, data)
# We resolved all we can, now replace the macro in the command call
for macro in macros:
c_line = c_line.replace('$' + macro + '$', macros[macro]['val'])
# A $$ means we want a $, it's not a macro!
# We replace $$ by a big dirty thing to be sure to not misinterpret it
c_line = c_line.replace("$$", "DOUBLEDOLLAR")
if nb_loop > 32: # too much loop, we exit
still_got_macros = False
# We now replace the big dirty token we made by only a simple $
c_line = c_line.replace("DOUBLEDOLLAR", "$")
# print "Retuning c_line", c_line.strip()
return c_line.strip()
# Resolve a command with macro by looking at data classes.macros
# And get macro from item properties.
def resolve_command(self, com, data):
c_line = com.command.command_line
return self.resolve_simple_macros_in_string(c_line, data, args=com.args)
# For all Macros in macros, set the type by looking at the
# MACRO name (ARGN? -> argn_type,
# HOSTBLABLA -> class one and set Host in class)
# _HOSTTOTO -> HOST CUSTOM MACRO TOTO
# $SERVICESTATEID:srv-1:Load$ -> MACRO SERVICESTATEID of
# the service Load of host srv-1
def _get_type_of_macro(self, macros, clss):
for macro in macros:
# ARGN Macros
if re.match('ARG\d', macro):
macros[macro]['type'] = 'ARGN'
continue
# USERN macros
# are managed in the Config class, so no
# need to look that here
elif re.match('_HOST\w', macro):
macros[macro]['type'] = 'CUSTOM'
macros[macro]['class'] = 'HOST'
continue
elif re.match('_SERVICE\w', macro):
macros[macro]['type'] = 'CUSTOM'
macros[macro]['class'] = 'SERVICE'
# value of macro: re.split('_HOST', '_HOSTMAC_ADDRESS')[1]
continue
elif re.match('_CONTACT\w', macro):
macros[macro]['type'] = 'CUSTOM'
macros[macro]['class'] = 'CONTACT'
continue
# On demand macro
elif len(macro.split(':')) > 1:
macros[macro]['type'] = 'ONDEMAND'
continue
# OK, classical macro...
for cls in clss:
if macro in cls.macros:
macros[macro]['type'] = 'class'
macros[macro]['class'] = cls
continue
# Resolve MACROS for the ARGN
def _resolve_argn(self, macro, args):
# first, get the number of args
id = None
r = re.search('ARG(?P<id>\d+)', macro)
if r is not None:
id = int(r.group('id')) - 1
try:
return args[id]
except IndexError:
return ''
# Resolve on-demand macro, quite hard in fact
def _resolve_ondemand(self, macro, data):
# print "\nResolving macro", macro
elts = macro.split(':')
nb_parts = len(elts)
macro_name = elts[0]
# Len 3 == service, 2 = all others types...
if nb_parts == 3:
val = ''
# print "Got a Service on demand asking...", elts
(host_name, service_description) = (elts[1], elts[2])
# host_name can be void, so it's the host in data
# that is important. We use our self.host_class to
# find the host in the data :)
if host_name == '':
for elt in data:
if elt is not None and elt.__class__ == self.host_class:
host_name = elt.host_name
# Ok now we get service
s = self.services.find_srv_by_name_and_hostname(host_name, service_description)
if s is not None:
cls = s.__class__
prop = cls.macros[macro_name]
val = self._get_value_from_element(s, prop)
# print "Got val:", val
return val
# Ok, service was easy, now hard part
else:
val = ''
elt_name = elts[1]
# Special case: elt_name can be void
# so it's the host where it apply
if elt_name == '':
for elt in data:
if elt is not None and elt.__class__ == self.host_class:
elt_name = elt.host_name
for list in self.lists_on_demand:
cls = list.inner_class
# We search our type by looking at the macro
if macro_name in cls.macros:
prop = cls.macros[macro_name]
i = list.find_by_name(elt_name)
if i is not None:
val = self._get_value_from_element(i, prop)
# Ok we got our value :)
break
return val
return ''
# Get Fri 15 May 11:42:39 CEST 2009
def _get_long_date_time(self):
return time.strftime("%a %d %b %H:%M:%S %Z %Y").decode('UTF-8', 'ignore')
# Get 10-13-2000 00:30:28
def _get_short_date_time(self):
return time.strftime("%d-%m-%Y %H:%M:%S")
# Get 10-13-2000
def _get_date(self):
return time.strftime("%d-%m-%Y")
# Get 00:30:28
def _get_time(self):
return time.strftime("%H:%M:%S")
# Get epoch time
def _get_timet(self):
return str(int(time.time()))
def _get_total_hosts_up(self):
return len([h for h in self.hosts if h.state == 'UP'])
def _get_total_hosts_down(self):
return len([h for h in self.hosts if h.state == 'DOWN'])
def _get_total_hosts_unreachable(self):
return len([h for h in self.hosts if h.state == 'UNREACHABLE'])
# TODO
def _get_total_hosts_unreachable_unhandled(self):
return 0
def _get_total_hosts_problems(self):
return len([h for h in self.hosts if h.is_problem])
def _get_total_hosts_problems_unhandled(self):
return 0
def _get_total_service_ok(self):
return len([s for s in self.services if s.state == 'OK'])
def _get_total_services_warning(self):
return len([s for s in self.services if s.state == 'WARNING'])
def _get_total_services_critical(self):
return len([s for s in self.services if s.state == 'CRITICAL'])
def _get_total_services_unknown(self):
return len([s for s in self.services if s.state == 'UNKNOWN'])
# TODO
def _get_total_services_warning_unhandled(self):
return 0
def _get_total_services_critical_unhandled(self):
return 0
def _get_total_services_unknown_unhandled(self):
return 0
def _get_total_service_problems(self):
return len([s for s in self.services if s.is_problem])
def _get_total_service_problems_unhandled(self):
return 0
def _get_process_start_time(self):
return 0
def _get_events_start_time(self):
return 0
| agpl-3.0 |
lumig242/Hue-Integration-with-CDAP | desktop/core/ext-py/lxml-3.3.6/src/lxml/tests/test_doctestcompare.py | 16 | 2948 | import sys
import unittest
from lxml import etree
from lxml.tests.common_imports import HelperTestCase
from lxml.doctestcompare import LXMLOutputChecker, PARSE_HTML, PARSE_XML
class DummyInput:
def __init__(self, **kw):
for name, value in kw.items():
setattr(self, name, value)
def indent(elem, level=0):
i = "\n" + level*" "
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + " "
if not elem.tail or not elem.tail.strip():
elem.tail = i
for elem in elem:
indent(elem, level+1)
if not elem.tail or not elem.tail.strip():
elem.tail = i
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = i
class DoctestCompareTest(HelperTestCase):
_checker = LXMLOutputChecker()
def compare(self, want, got, html=False):
if html:
options = PARSE_HTML
else:
options = PARSE_XML
parse = self._checker.get_parser(want, got, options)
want_doc = parse(want)
got_doc = parse(got)
return self._checker.collect_diff(
want_doc, got_doc, html, indent=0).lstrip()
def assert_diff(self, want, got, diff, html=False):
self.assertEqual(self.compare(want, got, html), diff)
def assert_nodiff(self, want, got, html=False):
root = etree.fromstring(want)
root.tail = '\n'
indent(root)
diff = etree.tostring(
root, encoding='unicode', method=html and 'html' or 'xml')
self.assert_diff(want, got, diff, html=html)
def test_equal_input(self):
self.assert_nodiff(
'<p title="expected">Expected</p>',
'<p title="expected">Expected</p>')
def test_differing_tags(self):
self.assert_diff(
'<p title="expected">Expected</p>',
'<b title="expected">Expected</b>',
'<p (got: b) title="expected">Expected</p (got: b)>\n')
def test_tags_upper_lower_case(self):
self.assert_diff(
'<p title="expected">Expected</p>',
'<P title="expected">Expected</P>',
'<p (got: P) title="expected">Expected</p (got: P)>\n')
def test_tags_upper_lower_case_html(self):
self.assert_nodiff(
'<html><body><p title="expected">Expected</p></body></html>',
'<HTML><BODY><P title="expected">Expected</P></BODY></HTML>',
html=True)
def test_differing_attributes(self):
self.assert_diff(
'<p title="expected">Expected</p>',
'<p title="actual">Actual</p>',
'<p title="expected (got: actual)">Expected (got: Actual)</p>\n')
def test_suite():
suite = unittest.TestSuite()
if sys.version_info >= (2,4):
suite.addTests([unittest.makeSuite(DoctestCompareTest)])
return suite
if __name__ == '__main__':
unittest.main()
| apache-2.0 |
town-hall-pinball/project-omega | tests/lib/test_simulator.py | 1 | 5370 | # Copyright (c) 2014 - 2016 townhallpinball.org
#
# 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 pin.lib import p
import unittest
from tests import fixtures
from mock import Mock
class TestSimulator(unittest.TestCase):
def setUp(self):
fixtures.reset()
p.data["simulator_enabled"] = True
self.sim = p.modes["simulator"]
fixtures.loop()
def test_initial(self):
self.assertTrue(p.switches["trough"].active)
self.assertTrue(p.switches["trough_2"].active)
self.assertTrue(p.switches["trough_3"].active)
self.assertTrue(p.switches["popper"].active)
def test_stop(self):
p.data["simulator_enabled"] = False
fixtures.loop()
self.assertFalse(p.switches["trough"].active)
self.assertFalse(p.switches["trough_2"].active)
self.assertFalse(p.switches["trough_3"].active)
self.assertFalse(p.switches["popper"].active)
def test_trough_feed(self):
p.coils["trough"].pulse()
fixtures.loop()
self.assertTrue(p.switches["trough"].active)
self.assertTrue(p.switches["trough_2"].active)
self.assertFalse(p.switches["trough_3"].active)
self.assertTrue(p.switches["popper"].active)
self.assertTrue(p.switches["shooter_lane"].active)
self.assertEquals(0, self.sim.free)
def test_launch(self):
p.coils["trough"].pulse()
p.coils["auto_plunger"].pulse()
fixtures.loop()
self.assertTrue(p.switches["trough"].active)
self.assertTrue(p.switches["trough_2"].active)
self.assertFalse(p.switches["trough_3"].active)
self.assertTrue(p.switches["popper"].active)
self.assertFalse(p.switches["shooter_lane"].active)
self.assertEquals(1, self.sim.free)
def test_drain(self):
p.coils["trough"].pulse()
p.coils["auto_plunger"].pulse()
p.switches["trough_4"].activate()
fixtures.loop()
self.assertTrue(p.switches["trough"].active)
self.assertTrue(p.switches["trough_2"].active)
self.assertTrue(p.switches["trough_3"].active)
self.assertFalse(p.switches["trough_4"].active)
self.assertTrue(p.switches["popper"].active)
self.assertFalse(p.switches["shooter_lane"].active)
self.assertEquals(0, self.sim.free)
def test_disable(self):
switch = p.switches["drop_target"]
switch.activate()
fixtures.loop()
self.assertTrue(switch.active)
p.coils["drop_target_up"].pulse()
fixtures.loop()
self.assertFalse(switch.active)
def test_enable(self):
switch = p.switches["drop_target"]
switch.deactivate()
fixtures.loop()
self.assertFalse(switch.active)
p.coils["drop_target_down"].pulse()
fixtures.loop()
self.assertTrue(switch.active)
def test_no_free_balls(self):
p.switches["trough_4"].activate()
fixtures.loop()
p.switches["trough_4"].deactivate()
fixtures.loop()
self.assertTrue(p.switches["trough_3"].active)
self.assertFalse(p.switches["trough_4"].active)
self.assertEquals(0, self.sim.free)
def test_ball_not_at_source(self):
p.coils["popper"].pulse()
p.now = 1
fixtures.loop()
self.assertEquals(1, self.sim.free)
p.now = 2
fixtures.loop()
p.coils["popper"].pulse()
p.now = 3
fixtures.loop()
self.assertEquals(1, self.sim.free)
def test_switch_hit(self):
listener = Mock()
p.events.on("switch_slingshot_left", listener)
p.coils["trough"].pulse()
p.now = 1
fixtures.loop()
p.coils["auto_plunger"].pulse()
p.now = 2
fixtures.loop()
p.now = 3
fixtures.loop()
self.assertTrue(listener.called)
def test_reset(self):
p.switches["trough_2"].deactivate()
p.switches["trough_3"].deactivate()
p.switches["popper_2"].activate()
fixtures.loop()
p.now = 1
p.events.post("simulator_reset")
fixtures.loop()
self.assertTrue(p.switches["trough"].active)
self.assertTrue(p.switches["trough_2"].active)
self.assertTrue(p.switches["trough_3"].active)
self.assertTrue(p.switches["popper"].active)
| mit |
kobejean/tensorflow | tensorflow/python/kernel_tests/self_adjoint_eig_op_test.py | 22 | 9533 | # 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 tensorflow.ops.math_ops.matrix_inverse."""
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 as dtypes_lib
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import gradient_checker
from tensorflow.python.ops import linalg_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import random_ops
from tensorflow.python.platform import test
def _AddTest(test_class, op_name, testcase_name, fn):
test_name = "_".join(["test", op_name, testcase_name])
if hasattr(test_class, test_name):
raise RuntimeError("Test %s defined more than once" % test_name)
setattr(test_class, test_name, fn)
class SelfAdjointEigTest(test.TestCase):
def testWrongDimensions(self):
# The input to self_adjoint_eig should be a tensor of
# at least rank 2.
scalar = constant_op.constant(1.)
with self.assertRaises(ValueError):
linalg_ops.self_adjoint_eig(scalar)
vector = constant_op.constant([1., 2.])
with self.assertRaises(ValueError):
linalg_ops.self_adjoint_eig(vector)
def testConcurrentExecutesWithoutError(self):
all_ops = []
with self.test_session(use_gpu=True) as sess:
for compute_v_ in True, False:
matrix1 = random_ops.random_normal([5, 5], seed=42)
matrix2 = random_ops.random_normal([5, 5], seed=42)
if compute_v_:
e1, v1 = linalg_ops.self_adjoint_eig(matrix1)
e2, v2 = linalg_ops.self_adjoint_eig(matrix2)
all_ops += [e1, v1, e2, v2]
else:
e1 = linalg_ops.self_adjoint_eigvals(matrix1)
e2 = linalg_ops.self_adjoint_eigvals(matrix2)
all_ops += [e1, e2]
val = sess.run(all_ops)
self.assertAllEqual(val[0], val[2])
# The algorithm is slightly different for compute_v being True and False,
# so require approximate equality only here.
self.assertAllClose(val[2], val[4])
self.assertAllEqual(val[4], val[5])
self.assertAllEqual(val[1], val[3])
def testMatrixThatFailsWhenFlushingDenormsToZero(self):
# Test a 32x32 matrix which is known to fail if denorm floats are flushed to
# zero.
matrix = np.genfromtxt(
test.test_src_dir_path(
"python/kernel_tests/testdata/"
"self_adjoint_eig_fail_if_denorms_flushed.txt")).astype(np.float32)
self.assertEqual(matrix.shape, (32, 32))
matrix_tensor = constant_op.constant(matrix)
with self.test_session(use_gpu=True) as sess:
(e, v) = sess.run(linalg_ops.self_adjoint_eig(matrix_tensor))
self.assertEqual(e.size, 32)
self.assertAllClose(
np.matmul(v, v.transpose()), np.eye(32, dtype=np.float32), atol=2e-3)
self.assertAllClose(matrix,
np.matmul(np.matmul(v, np.diag(e)), v.transpose()))
def SortEigenDecomposition(e, v):
if v.ndim < 2:
return e, v
else:
perm = np.argsort(e, -1)
return np.take(e, perm, -1), np.take(v, perm, -1)
def EquilibrateEigenVectorPhases(x, y):
"""Equilibrate the phase of the Eigenvectors in the columns of `x` and `y`.
Eigenvectors are only unique up to an arbitrary phase. This function rotates x
such that it matches y. Precondition: The coluns of x and y differ by a
multiplicative complex phase factor only.
Args:
x: `np.ndarray` with Eigenvectors
y: `np.ndarray` with Eigenvectors
Returns:
`np.ndarray` containing an equilibrated version of x.
"""
phases = np.sum(np.conj(x) * y, -2, keepdims=True)
phases /= np.abs(phases)
return phases * x
def _GetSelfAdjointEigTest(dtype_, shape_, compute_v_):
def CompareEigenVectors(self, x, y, tol):
x = EquilibrateEigenVectorPhases(x, y)
self.assertAllClose(x, y, atol=tol)
def CompareEigenDecompositions(self, x_e, x_v, y_e, y_v, tol):
num_batches = int(np.prod(x_e.shape[:-1]))
n = x_e.shape[-1]
x_e = np.reshape(x_e, [num_batches] + [n])
x_v = np.reshape(x_v, [num_batches] + [n, n])
y_e = np.reshape(y_e, [num_batches] + [n])
y_v = np.reshape(y_v, [num_batches] + [n, n])
for i in range(num_batches):
x_ei, x_vi = SortEigenDecomposition(x_e[i, :], x_v[i, :, :])
y_ei, y_vi = SortEigenDecomposition(y_e[i, :], y_v[i, :, :])
self.assertAllClose(x_ei, y_ei, atol=tol, rtol=tol)
CompareEigenVectors(self, x_vi, y_vi, tol)
def Test(self):
np.random.seed(1)
n = shape_[-1]
batch_shape = shape_[:-2]
np_dtype = dtype_.as_numpy_dtype
a = np.random.uniform(
low=-1.0, high=1.0, size=n * n).reshape([n, n]).astype(np_dtype)
if dtype_.is_complex:
a += 1j * np.random.uniform(
low=-1.0, high=1.0, size=n * n).reshape([n, n]).astype(np_dtype)
a += np.conj(a.T)
a = np.tile(a, batch_shape + (1, 1))
if dtype_ in (dtypes_lib.float32, dtypes_lib.complex64):
atol = 1e-4
else:
atol = 1e-12
np_e, np_v = np.linalg.eigh(a)
with self.test_session(use_gpu=True):
if compute_v_:
tf_e, tf_v = linalg_ops.self_adjoint_eig(constant_op.constant(a))
# Check that V*diag(E)*V^T is close to A.
a_ev = math_ops.matmul(
math_ops.matmul(tf_v, array_ops.matrix_diag(tf_e)),
tf_v,
adjoint_b=True)
self.assertAllClose(a_ev.eval(), a, atol=atol)
# Compare to numpy.linalg.eigh.
CompareEigenDecompositions(self, np_e, np_v,
tf_e.eval(), tf_v.eval(), atol)
else:
tf_e = linalg_ops.self_adjoint_eigvals(constant_op.constant(a))
self.assertAllClose(
np.sort(np_e, -1), np.sort(tf_e.eval(), -1), atol=atol)
return Test
class SelfAdjointEigGradTest(test.TestCase):
pass # Filled in below
def _GetSelfAdjointEigGradTest(dtype_, shape_, compute_v_):
def Test(self):
np.random.seed(1)
n = shape_[-1]
batch_shape = shape_[:-2]
np_dtype = dtype_.as_numpy_dtype
a = np.random.uniform(
low=-1.0, high=1.0, size=n * n).reshape([n, n]).astype(np_dtype)
if dtype_.is_complex:
a += 1j * np.random.uniform(
low=-1.0, high=1.0, size=n * n).reshape([n, n]).astype(np_dtype)
a += np.conj(a.T)
a = np.tile(a, batch_shape + (1, 1))
# Optimal stepsize for central difference is O(epsilon^{1/3}).
epsilon = np.finfo(np_dtype).eps
delta = 0.1 * epsilon**(1.0 / 3.0)
# tolerance obtained by looking at actual differences using
# np.linalg.norm(theoretical-numerical, np.inf) on -mavx build
if dtype_ in (dtypes_lib.float32, dtypes_lib.complex64):
tol = 1e-2
else:
tol = 1e-7
with self.test_session(use_gpu=True):
tf_a = constant_op.constant(a)
if compute_v_:
tf_e, tf_v = linalg_ops.self_adjoint_eig(tf_a)
# (complex) Eigenvectors are only unique up to an arbitrary phase
# We normalize the vectors such that the first component has phase 0.
top_rows = tf_v[..., 0:1, :]
if tf_a.dtype.is_complex:
angle = -math_ops.angle(top_rows)
phase = math_ops.complex(math_ops.cos(angle), math_ops.sin(angle))
else:
phase = math_ops.sign(top_rows)
tf_v *= phase
outputs = [tf_e, tf_v]
else:
tf_e = linalg_ops.self_adjoint_eigvals(tf_a)
outputs = [tf_e]
for b in outputs:
x_init = np.random.uniform(
low=-1.0, high=1.0, size=n * n).reshape([n, n]).astype(np_dtype)
if dtype_.is_complex:
x_init += 1j * np.random.uniform(
low=-1.0, high=1.0, size=n * n).reshape([n, n]).astype(np_dtype)
x_init += np.conj(x_init.T)
x_init = np.tile(x_init, batch_shape + (1, 1))
theoretical, numerical = gradient_checker.compute_gradient(
tf_a,
tf_a.get_shape().as_list(),
b,
b.get_shape().as_list(),
x_init_value=x_init,
delta=delta)
self.assertAllClose(theoretical, numerical, atol=tol, rtol=tol)
return Test
if __name__ == "__main__":
for compute_v in True, False:
for dtype in (dtypes_lib.float32, dtypes_lib.float64, dtypes_lib.complex64,
dtypes_lib.complex128):
for size in 1, 2, 5, 10:
for batch_dims in [(), (3,)] + [(3, 2)] * (max(size, size) < 10):
shape = batch_dims + (size, size)
name = "%s_%s_%s" % (dtype, "_".join(map(str, shape)), compute_v)
_AddTest(SelfAdjointEigTest, "SelfAdjointEig", name,
_GetSelfAdjointEigTest(dtype, shape, compute_v))
_AddTest(SelfAdjointEigGradTest, "SelfAdjointEigGrad", name,
_GetSelfAdjointEigGradTest(dtype, shape, compute_v))
test.main()
| apache-2.0 |
nischalsheth/contrail-controller | src/container/mesos-cni/setup.py | 3 | 1568 | #
# Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
#
import setuptools, re
import os
class RunTestsCommand(setuptools.Command):
description = "Test command to run testr in virtualenv"
user_options = [
('coverage', 'c',
"Generate code coverage report"),
]
boolean_options = ['coverage']
def initialize_options(self):
self.cwd = None
self.coverage = False
def finalize_options(self):
self.cwd = os.getcwd()
def run(self):
logfname = 'test.log'
args = '-V'
if self.coverage:
logfname = 'coveragetest.log'
args += ' -c'
rc_sig = os.system('./run_tests.sh %s' % args)
if rc_sig >> 8:
os._exit(rc_sig>>8)
with open(logfname) as f:
if not re.search('\nOK', ''.join(f.readlines())):
os._exit(1)
setuptools.setup(
name='mesos_cni',
version='0.1dev',
packages=setuptools.find_packages(),
package_data={'': ['*.html', '*.css', '*.xml', '*.yml']},
# metadata
author="OpenContrail",
author_email="dev@lists.opencontrail.org",
license="Apache Software License",
url="http://www.opencontrail.org/",
long_description="Mesos CNI Plugin",
test_suite='mesos_cni.tests',
entry_points = {
# Please update sandesh/common/vns.sandesh on process name change
'console_scripts' : [
'contrail-mesos-cni = mesos_cni.mesos_cni:main',
],
},
cmdclass={
'run_tests': RunTestsCommand,
},
)
| apache-2.0 |
silburt/rebound2 | python_examples/outersolarsystem/problem.py | 6 | 1903 | # Import the rebound module
import rebound
import os
# Create a REBOUND simulation
sim = rebound.Simulation()
# Set variables (defaults are G=1, t=0, dt=0.01)
k = 0.01720209895 # Gaussian constant
sim.G = k*k # Gravitational constant
# Setup particles (data taken from NASA Horizons)
# This could also be easily read in from a file.
sim.add( m=1.00000597682, x=-4.06428567034226e-3, y=-6.08813756435987e-3, z=-1.66162304225834e-6, vx=+6.69048890636161e-6, vy=-6.33922479583593e-6, vz=-3.13202145590767e-9) # Sun
sim.add( m=1./1047.355, x=+3.40546614227466e+0, y=+3.62978190075864e+0, z=+3.42386261766577e-2, vx=-5.59797969310664e-3, vy=+5.51815399480116e-3, vz=-2.66711392865591e-6) # Jupiter
sim.add( m=1./3501.6, x=+6.60801554403466e+0, y=+6.38084674585064e+0, z=-1.36145963724542e-1, vx=-4.17354020307064e-3, vy=+3.99723751748116e-3, vz=+1.67206320571441e-5) # Saturn
sim.add( m=1./22869., x=+1.11636331405597e+1, y=+1.60373479057256e+1, z=+3.61783279369958e-1, vx=-3.25884806151064e-3, vy=+2.06438412905916e-3, vz=-2.17699042180559e-5) # Uranus
sim.add( m=1./19314., x=-3.01777243405203e+1, y=+1.91155314998064e+0, z=-1.53887595621042e-1, vx=-2.17471785045538e-4, vy=-3.11361111025884e-3, vz=+3.58344705491441e-5) # Neptune
sim.add( m=0, x=-2.13858977531573e+1, y=+3.20719104739886e+1, z=+2.49245689556096e+0, vx=-1.76936577252484e-3, vy=-2.06720938381724e-3, vz=+6.58091931493844e-4) # Pluto
# Set the center of momentum to be at the origin
sim.move_to_com()
# timestep counter
steps = 0
# Integrate until t=1e4 (unit of time in this example is days)
for i in range(100):
tmax = 1.0e2*i
sim.integrate(tmax)
if 'TRAVIS' not in os.environ: # Don't output anything in test build
# Print particle positions
for p in sim.particles:
# time x y z
print(sim.t, p.x, p.y, p.z)
| gpl-3.0 |
SensibilityTestbed/clearinghouse | website/tests/ut_website_interface_renewvessels.py | 1 | 5110 | """
Tests the interface.renew_vessels and interface.renew_all_vessels calls.
"""
#pragma out
#pragma error OK
# The clearinghouse testlib must be imported first.
from clearinghouse.tests import testlib
from clearinghouse.tests import mocklib
from clearinghouse.common.api import maindb
from clearinghouse.common.exceptions import *
from clearinghouse.website.control import interface
from clearinghouse.website.tests import testutil
import datetime
import unittest
mocklib.mock_lockserver_calls()
class SeattleGeniTestCase(unittest.TestCase):
def setUp(self):
# Setup a fresh database for each test.
testlib.setup_test_db()
def tearDown(self):
# Cleanup the test database.
testlib.teardown_test_db()
def test_renew_vessels_insufficient_vessel_credits(self):
# Create a user who will be doing the acquiring.
user = maindb.create_user("testuser", "password", "example@example.com", "affiliation", "1 2", "2 2 2", "3 4")
userport = user.usable_vessel_port
vesselcount = 4
# Have every vessel acquisition to the backend request succeed.
calls_results = [True] * vesselcount
mocklib.mock_backend_acquire_vessel(calls_results)
testutil.create_nodes_on_different_subnets(vesselcount, [userport])
# Acquire all of the vessels the user can acquire.
vessel_list = interface.acquire_vessels(user, vesselcount, 'rand')
# Decrease the user's vessel credits to one less than the number of vessels
# they have acquired.
user.free_vessel_credits = 0
user.save()
func = interface.renew_vessels
args = (user, vessel_list)
self.assertRaises(InsufficientUserResourcesError, func, *args)
func = interface.renew_all_vessels
args = (user,)
self.assertRaises(InsufficientUserResourcesError, func, *args)
def test_renew_some_of_users_vessel(self):
# Create a user who will be doing the acquiring.
user = maindb.create_user("testuser", "password", "example@example.com", "affiliation", "1 2", "2 2 2", "3 4")
userport = user.usable_vessel_port
vesselcount = 4
# Have every vessel acquisition to the backend request succeed.
calls_results = [True] * vesselcount
mocklib.mock_backend_acquire_vessel(calls_results)
testutil.create_nodes_on_different_subnets(vesselcount, [userport])
# Acquire all of the vessels the user can acquire.
vessel_list = interface.acquire_vessels(user, vesselcount, 'rand')
renew_vessels_list = vessel_list[:2]
not_renewed_vessels_list = vessel_list[2:]
interface.renew_vessels(user, renew_vessels_list)
now = datetime.datetime.now()
timedelta_oneday = datetime.timedelta(days=1)
for vessel in renew_vessels_list:
self.assertTrue(vessel.date_expires - now > timedelta_oneday)
for vessel in not_renewed_vessels_list:
self.assertTrue(vessel.date_expires - now < timedelta_oneday)
def test_renew_vessels_dont_belong_to_user(self):
# Create a user who will be doing the acquiring.
user = maindb.create_user("testuser", "password", "example@example.com", "affiliation", "1 2", "2 2 2", "3 4")
userport = user.usable_vessel_port
# Create a second user.
user2 = maindb.create_user("user2", "password", "user2@example.com", "affiliation", "1 2", "2 2 2", "3 4")
vesselcount = 4
# Have every vessel acquisition to the backend request succeed.
calls_results = [True] * vesselcount
mocklib.mock_backend_acquire_vessel(calls_results)
testutil.create_nodes_on_different_subnets(vesselcount, [userport])
# Acquire all of the vessels the user can acquire.
vessel_list = interface.acquire_vessels(user, vesselcount, 'rand')
release_vessel = vessel_list[0]
interface.release_vessels(user, [release_vessel])
# Manually fiddle with one of the vessels to make it owned by user2.
user2_vessel = vessel_list[1]
user2_vessel.acquired_by_user = user2
user2_vessel.save()
# Try to renew all of the originally acquired vessels, including the ones
# that were released. We expect these to just be ignored.
interface.renew_vessels(user, vessel_list)
# Get fresh vessel objects that reflect the renewal.
remaining_vessels = interface.get_acquired_vessels(user)
release_vessel = maindb.get_vessel(release_vessel.node.node_identifier, release_vessel.name)
user2_vessel = maindb.get_vessel(user2_vessel.node.node_identifier, user2_vessel.name)
now = datetime.datetime.now()
timedelta_oneday = datetime.timedelta(days=1)
# Ensure that the vessels the user still has were renewed but that the ones
# the user released were ignored (not renewed).
for vessel in remaining_vessels:
self.assertTrue(vessel.date_expires - now > timedelta_oneday)
self.assertTrue(user2_vessel.date_expires - now < timedelta_oneday)
self.assertEqual(release_vessel.date_expires, None)
def run_test():
unittest.main()
if __name__ == "__main__":
run_test()
| mit |
nvoron23/avos | openstack_dashboard/dashboards/admin/networks/forms.py | 10 | 12027 | # Copyright 2012 NEC Corporation
#
# 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 logging
from django.conf import settings
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon import forms
from horizon import messages
from openstack_dashboard import api
LOG = logging.getLogger(__name__)
PROVIDER_TYPES = [('local', _('Local')), ('flat', _('Flat')),
('vlan', _('VLAN')), ('gre', _('GRE')),
('vxlan', _('VXLAN'))]
SEGMENTATION_ID_RANGE = {'vlan': [1, 4094], 'gre': [0, (2 ** 32) - 1],
'vxlan': [0, (2 ** 24) - 1]}
class CreateNetwork(forms.SelfHandlingForm):
name = forms.CharField(max_length=255,
label=_("Name"),
required=False)
tenant_id = forms.ChoiceField(label=_("Project"))
if api.neutron.is_port_profiles_supported():
widget = None
else:
widget = forms.HiddenInput()
net_profile_id = forms.ChoiceField(label=_("Network Profile"),
required=False,
widget=widget)
network_type = forms.ChoiceField(
label=_("Provider Network Type"),
help_text=_("The physical mechanism by which the virtual "
"network is implemented."),
widget=forms.Select(attrs={
'class': 'switchable',
'data-slug': 'network_type'
}))
physical_network = forms.CharField(
max_length=255,
label=_("Physical Network"),
help_text=_("The name of the physical network over which the "
"virtual network is implemented."),
initial='default',
widget=forms.TextInput(attrs={
'class': 'switched',
'data-switch-on': 'network_type',
'data-network_type-flat': _('Physical Network'),
'data-network_type-vlan': _('Physical Network')
}))
segmentation_id = forms.IntegerField(
label=_("Segmentation ID"),
widget=forms.TextInput(attrs={
'class': 'switched',
'data-switch-on': 'network_type',
'data-network_type-vlan': _('Segmentation ID'),
'data-network_type-gre': _('Segmentation ID'),
'data-network_type-vxlan': _('Segmentation ID')
}))
admin_state = forms.ChoiceField(choices=[(True, _('UP')),
(False, _('DOWN'))],
label=_("Admin State"))
shared = forms.BooleanField(label=_("Shared"),
initial=False, required=False)
external = forms.BooleanField(label=_("External Network"),
initial=False, required=False)
@classmethod
def _instantiate(cls, request, *args, **kwargs):
return cls(request, *args, **kwargs)
def __init__(self, request, *args, **kwargs):
super(CreateNetwork, self).__init__(request, *args, **kwargs)
tenant_choices = [('', _("Select a project"))]
tenants, has_more = api.keystone.tenant_list(request)
for tenant in tenants:
if tenant.enabled:
tenant_choices.append((tenant.id, tenant.name))
self.fields['tenant_id'].choices = tenant_choices
if api.neutron.is_port_profiles_supported():
self.fields['net_profile_id'].choices = (
self.get_network_profile_choices(request))
if api.neutron.is_extension_supported(request, 'provider'):
neutron_settings = getattr(settings,
'OPENSTACK_NEUTRON_NETWORK', {})
seg_id_range = neutron_settings.get('segmentation_id_range', {})
self.seg_id_range = {
'vlan': seg_id_range.get('vlan',
SEGMENTATION_ID_RANGE.get('vlan')),
'gre': seg_id_range.get('gre',
SEGMENTATION_ID_RANGE.get('gre')),
'vxlan': seg_id_range.get('vxlan',
SEGMENTATION_ID_RANGE.get('vxlan'))
}
seg_id_help = (
_("For VLAN networks, the VLAN VID on the physical "
"network that realizes the virtual network. Valid VLAN VIDs "
"are %(vlan_min)s through %(vlan_max)s. For GRE or VXLAN "
"networks, the tunnel ID. Valid tunnel IDs for GRE networks "
"are %(gre_min)s through %(gre_max)s. For VXLAN networks, "
"%(vxlan_min)s through %(vxlan_max)s.")
% {'vlan_min': self.seg_id_range['vlan'][0],
'vlan_max': self.seg_id_range['vlan'][1],
'gre_min': self.seg_id_range['gre'][0],
'gre_max': self.seg_id_range['gre'][1],
'vxlan_min': self.seg_id_range['vxlan'][0],
'vxlan_max': self.seg_id_range['vxlan'][1]})
self.fields['segmentation_id'].help_text = seg_id_help
supported_provider_types = neutron_settings.get(
'supported_provider_types', ['*'])
if supported_provider_types == ['*']:
network_type_choices = PROVIDER_TYPES
else:
network_type_choices = [
net_type for net_type in PROVIDER_TYPES
if net_type[0] in supported_provider_types]
if len(network_type_choices) == 0:
self._hide_provider_network_type()
else:
self.fields['network_type'].choices = network_type_choices
else:
self._hide_provider_network_type()
def get_network_profile_choices(self, request):
profile_choices = [('', _("Select a profile"))]
for profile in self._get_profiles(request, 'network'):
profile_choices.append((profile.id, profile.name))
return profile_choices
def _get_profiles(self, request, type_p):
profiles = []
try:
profiles = api.neutron.profile_list(request, type_p)
except Exception:
msg = _('Network Profiles could not be retrieved.')
exceptions.handle(request, msg)
return profiles
def _hide_provider_network_type(self):
self.fields['network_type'].widget = forms.HiddenInput()
self.fields['physical_network'].widget = forms.HiddenInput()
self.fields['segmentation_id'].widget = forms.HiddenInput()
self.fields['network_type'].required = False
self.fields['physical_network'].required = False
self.fields['segmentation_id'].required = False
def handle(self, request, data):
try:
params = {'name': data['name'],
'tenant_id': data['tenant_id'],
'admin_state_up': (data['admin_state'] == 'True'),
'shared': data['shared'],
'router:external': data['external']}
if api.neutron.is_port_profiles_supported():
params['net_profile_id'] = data['net_profile_id']
if api.neutron.is_extension_supported(request, 'provider'):
network_type = data['network_type']
params['provider:network_type'] = network_type
if network_type in ['flat', 'vlan']:
params['provider:physical_network'] = (
data['physical_network'])
if network_type in ['vlan', 'gre', 'vxlan']:
params['provider:segmentation_id'] = (
data['segmentation_id'])
network = api.neutron.network_create(request, **params)
msg = _('Network %s was successfully created.') % data['name']
LOG.debug(msg)
messages.success(request, msg)
return network
except Exception:
redirect = reverse('horizon:admin:networks:index')
msg = _('Failed to create network %s') % data['name']
exceptions.handle(request, msg, redirect=redirect)
def clean(self):
cleaned_data = super(CreateNetwork, self).clean()
self._clean_physical_network(cleaned_data)
self._clean_segmentation_id(cleaned_data)
return cleaned_data
def _clean_physical_network(self, data):
network_type = data.get('network_type')
if 'physical_network' in self._errors and (
network_type in ['local', 'gre']):
# In this case the physical network is not required, so we can
# ignore any errors.
del self._errors['physical_network']
def _clean_segmentation_id(self, data):
network_type = data.get('network_type')
if 'segmentation_id' in self._errors:
if network_type in ['local', 'flat']:
# In this case the segmentation ID is not required, so we can
# ignore any errors.
del self._errors['segmentation_id']
elif network_type in ['vlan', 'gre', 'vxlan']:
seg_id = data.get('segmentation_id')
seg_id_range = {'min': self.seg_id_range[network_type][0],
'max': self.seg_id_range[network_type][1]}
if seg_id < seg_id_range['min'] or seg_id > seg_id_range['max']:
if network_type == 'vlan':
msg = _('For VLAN networks, valid VLAN IDs are %(min)s '
'through %(max)s.') % seg_id_range
elif network_type == 'gre':
msg = _('For GRE networks, valid tunnel IDs are %(min)s '
'through %(max)s.') % seg_id_range
elif network_type == 'vxlan':
msg = _('For VXLAN networks, valid tunnel IDs are %(min)s '
'through %(max)s.') % seg_id_range
self._errors['segmentation_id'] = self.error_class([msg])
class UpdateNetwork(forms.SelfHandlingForm):
name = forms.CharField(label=_("Name"), required=False)
tenant_id = forms.CharField(widget=forms.HiddenInput)
admin_state = forms.ChoiceField(choices=[(True, _('UP')),
(False, _('DOWN'))],
label=_("Admin State"))
shared = forms.BooleanField(label=_("Shared"), required=False)
external = forms.BooleanField(label=_("External Network"), required=False)
failure_url = 'horizon:admin:networks:index'
def handle(self, request, data):
try:
params = {'name': data['name'],
'admin_state_up': (data['admin_state'] == 'True'),
'shared': data['shared'],
'router:external': data['external']}
network = api.neutron.network_update(request,
self.initial['network_id'],
**params)
msg = _('Network %s was successfully updated.') % data['name']
LOG.debug(msg)
messages.success(request, msg)
return network
except Exception:
msg = _('Failed to update network %s') % data['name']
LOG.info(msg)
redirect = reverse(self.failure_url)
exceptions.handle(request, msg, redirect=redirect)
| apache-2.0 |
ku3o/coala-bears | bears/natural_language/AlexBear.py | 3 | 1923 | import subprocess
import sys
from coalib.bearlib.abstractions.Linter import linter
from coalib.bears.requirements.NpmRequirement import NpmRequirement
@linter(executable='alex',
output_format='regex',
output_regex=r'(?P<line>\d+):(?P<column>\d+)-(?P<end_line>\d+):'
r'(?P<end_column>\d+)\s+(?P<severity>warning)\s+'
r'(?P<message>.+)')
class AlexBear:
"""
Checks the markdown file with Alex - Catch insensitive, inconsiderate
writing.
"""
LANGUAGES = {"Natural Language"}
REQUIREMENTS = {NpmRequirement('alex', '3')}
AUTHORS = {'The coala developers'}
AUTHORS_EMAILS = {'coala-devel@googlegroups.com'}
LICENSE = 'AGPL-3.0'
@classmethod
def check_prerequisites(cls):
parent_prereqs = super().check_prerequisites()
if parent_prereqs is not True: # pragma: no cover
return parent_prereqs
incorrect_pkg_msg = (
"Please ensure that the package that has been installed is the "
"one to 'Catch insensitive, inconsiderate writing'. This can be "
"verified by running `alex --help` and seeing what it does.")
try:
output = subprocess.check_output(("alex", "--help"),
stderr=subprocess.STDOUT)
except (OSError, subprocess.CalledProcessError):
return ("The `alex` package could not be verified. " +
incorrect_pkg_msg)
else:
output = output.decode(sys.getfilesystemencoding())
if "Catch insensitive, inconsiderate writing" in output:
return True
else:
return ("The `alex` package that's been installed seems to "
"be incorrect. " + incorrect_pkg_msg)
@staticmethod
def create_arguments(filename, file, config_file):
return filename,
| agpl-3.0 |
hgl888/crosswalk-android-extensions | build/idl-generator/third_party/WebKit/Tools/Scripts/webkitpy/common/system/filesystem.py | 61 | 9571 | # Copyright (C) 2010 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.
"""Wrapper object for the file system / source tree."""
import codecs
import errno
import exceptions
import glob
import hashlib
import os
import shutil
import sys
import tempfile
import time
class FileSystem(object):
"""FileSystem interface for webkitpy.
Unless otherwise noted, all paths are allowed to be either absolute
or relative."""
sep = os.sep
pardir = os.pardir
def abspath(self, path):
return os.path.abspath(path)
def realpath(self, path):
return os.path.realpath(path)
def path_to_module(self, module_name):
"""A wrapper for all calls to __file__ to allow easy unit testing."""
# FIXME: This is the only use of sys in this file. It's possible this function should move elsewhere.
return sys.modules[module_name].__file__ # __file__ is always an absolute path.
def expanduser(self, path):
return os.path.expanduser(path)
def basename(self, path):
return os.path.basename(path)
def chdir(self, path):
return os.chdir(path)
def copyfile(self, source, destination):
shutil.copyfile(source, destination)
def dirname(self, path):
return os.path.dirname(path)
def exists(self, path):
return os.path.exists(path)
def files_under(self, path, dirs_to_skip=[], file_filter=None):
"""Return the list of all files under the given path in topdown order.
Args:
dirs_to_skip: a list of directories to skip over during the
traversal (e.g., .svn, resources, etc.)
file_filter: if not None, the filter will be invoked
with the filesystem object and the dirname and basename of
each file found. The file is included in the result if the
callback returns True.
"""
def filter_all(fs, dirpath, basename):
return True
file_filter = file_filter or filter_all
files = []
if self.isfile(path):
if file_filter(self, self.dirname(path), self.basename(path)):
files.append(path)
return files
if self.basename(path) in dirs_to_skip:
return []
for (dirpath, dirnames, filenames) in os.walk(path):
for d in dirs_to_skip:
if d in dirnames:
dirnames.remove(d)
for filename in filenames:
if file_filter(self, dirpath, filename):
files.append(self.join(dirpath, filename))
return files
def getcwd(self):
return os.getcwd()
def glob(self, path):
return glob.glob(path)
def isabs(self, path):
return os.path.isabs(path)
def isfile(self, path):
return os.path.isfile(path)
def isdir(self, path):
return os.path.isdir(path)
def join(self, *comps):
return os.path.join(*comps)
def listdir(self, path):
return os.listdir(path)
def walk(self, top):
return os.walk(top)
def mkdtemp(self, **kwargs):
"""Create and return a uniquely named directory.
This is like tempfile.mkdtemp, but if used in a with statement
the directory will self-delete at the end of the block (if the
directory is empty; non-empty directories raise errors). The
directory can be safely deleted inside the block as well, if so
desired.
Note that the object returned is not a string and does not support all of the string
methods. If you need a string, coerce the object to a string and go from there.
"""
class TemporaryDirectory(object):
def __init__(self, **kwargs):
self._kwargs = kwargs
self._directory_path = tempfile.mkdtemp(**self._kwargs)
def __str__(self):
return self._directory_path
def __enter__(self):
return self._directory_path
def __exit__(self, type, value, traceback):
# Only self-delete if necessary.
# FIXME: Should we delete non-empty directories?
if os.path.exists(self._directory_path):
os.rmdir(self._directory_path)
return TemporaryDirectory(**kwargs)
def maybe_make_directory(self, *path):
"""Create the specified directory if it doesn't already exist."""
try:
os.makedirs(self.join(*path))
except OSError, e:
if e.errno != errno.EEXIST:
raise
def move(self, source, destination):
shutil.move(source, destination)
def mtime(self, path):
return os.stat(path).st_mtime
def normpath(self, path):
return os.path.normpath(path)
def open_binary_tempfile(self, suffix):
"""Create, open, and return a binary temp file. Returns a tuple of the file and the name."""
temp_fd, temp_name = tempfile.mkstemp(suffix)
f = os.fdopen(temp_fd, 'wb')
return f, temp_name
def open_binary_file_for_reading(self, path):
return codecs.open(path, 'rb')
def read_binary_file(self, path):
"""Return the contents of the file at the given path as a byte string."""
with file(path, 'rb') as f:
return f.read()
def write_binary_file(self, path, contents):
with file(path, 'wb') as f:
f.write(contents)
def open_text_file_for_reading(self, path):
# Note: There appears to be an issue with the returned file objects
# not being seekable. See http://stackoverflow.com/questions/1510188/can-seek-and-tell-work-with-utf-8-encoded-documents-in-python .
return codecs.open(path, 'r', 'utf8')
def open_text_file_for_writing(self, path):
return codecs.open(path, 'w', 'utf8')
def read_text_file(self, path):
"""Return the contents of the file at the given path as a Unicode string.
The file is read assuming it is a UTF-8 encoded file with no BOM."""
with codecs.open(path, 'r', 'utf8') as f:
return f.read()
def write_text_file(self, path, contents):
"""Write the contents to the file at the given location.
The file is written encoded as UTF-8 with no BOM."""
with codecs.open(path, 'w', 'utf8') as f:
f.write(contents)
def sha1(self, path):
contents = self.read_binary_file(path)
return hashlib.sha1(contents).hexdigest()
def relpath(self, path, start='.'):
return os.path.relpath(path, start)
class _WindowsError(exceptions.OSError):
"""Fake exception for Linux and Mac."""
pass
def remove(self, path, osremove=os.remove):
"""On Windows, if a process was recently killed and it held on to a
file, the OS will hold on to the file for a short while. This makes
attempts to delete the file fail. To work around that, this method
will retry for a few seconds until Windows is done with the file."""
try:
exceptions.WindowsError
except AttributeError:
exceptions.WindowsError = FileSystem._WindowsError
retry_timeout_sec = 3.0
sleep_interval = 0.1
while True:
try:
osremove(path)
return True
except exceptions.WindowsError, e:
time.sleep(sleep_interval)
retry_timeout_sec -= sleep_interval
if retry_timeout_sec < 0:
raise e
def rmtree(self, path):
"""Delete the directory rooted at path, whether empty or not."""
shutil.rmtree(path, ignore_errors=True)
def copytree(self, source, destination):
shutil.copytree(source, destination)
def split(self, path):
"""Return (dirname, basename + '.' + ext)"""
return os.path.split(path)
def splitext(self, path):
"""Return (dirname + os.sep + basename, '.' + ext)"""
return os.path.splitext(path)
| bsd-3-clause |
henniggroup/MPInterfaces | mpinterfaces/scripts/smart_rlaunch.py | 2 | 4169 | from __future__ import division, unicode_literals, print_function, \
absolute_import
from six.moves import range
import mmap
import os
import time
from argparse import ArgumentParser
from fabric.api import settings, run
from fireworks import LaunchPad
from fireworks.fw_config import LAUNCHPAD_LOC
MAILDIR = os.path.join(os.path.expanduser('~'), ".fireworks/mail/hipergator/")
def check_done(job_id):
for fname in os.listdir(MAILDIR):
# print fname, os.path.getmtime(MAILDIR+fname) - time.time()
if present_id(job_id, MAILDIR + fname):
print('id in mail {0} = {1}'.format(fname, job_id))
return True
def present_id(job_id, fname, search_string=b"Execution terminated"):
with open(fname, 'r') as f:
fm = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
n = len(fm)
if fm.rfind(search_string, 0, n) > 0:
i = fm.rfind(b"PBS Job Id:", 0, n)
j = fm.rfind(b"Job Name:", i, n)
jid = fm[i:j].split()[-1]
return job_id == jid
else:
return False
def launch():
descr = "Smart rocket launcher." \
"Uses the execution termination emails send by the batch system to " \
"launch fireworks that depend on other fireworks i.e fireworks that " \
"have 'cal_objs' in their spec." \
"Takes in fw_ids of fireworks to be launched. " \
"Range specification of fw_ids is also supported." \
"All the jobs are launched to hipergator remotely using fabric." \
"Note: Ensure that the submit scripts have the appropriate email settings and " \
"that the mail daemon is fetching emails to the folder polled by this script." \
"Note: All rocket launches take place in the home directory. If " \
"_launch_dir spec is set for the firework the job files will be written to " \
"that folder and jobs to the batch system will be done from there."
parser = ArgumentParser(description=descr)
parser.add_argument('-f', '--fw_ids', help='one or more of fw_ids to run',
default=None, type=int, nargs='+')
parser.add_argument('-r', '--r_fw_ids',
help='start and end fw_ids of the range of fw_ids to run',
default=None, type=int, nargs=2)
args = parser.parse_args()
fw_ids = args.fw_ids
if args.r_fw_ids is not None:
fw_ids += list(range(args.r_fw_ids[0], args.r_fw_ids[1]))
job_ids = None
lp = LaunchPad.from_file(LAUNCHPAD_LOC)
print('Firework ids: ', fw_ids)
if fw_ids is None:
print('No fw ids given')
return
for fid in fw_ids:
m_fw = lp._get_a_fw_to_run(fw_id=fid, checkout=False)
if m_fw is None:
print('No firework with that id')
return
fw_spec = dict(m_fw.spec)
done = []
if fw_spec.get('cal_objs', None) is not None:
for calparams in fw_spec['cal_objs']:
if calparams.get('job_ids', None) is not None:
job_ids = calparams.get('job_ids', None)
print(fid, ' depends on jobs with ids : ', job_ids)
if job_ids is not None:
for jid in job_ids:
done.append(check_done(jid))
else:
print('job_ids not set')
else:
print('This firework doesnt depend on any other fireworks.')
done.append(True)
if done and all(done):
print('Launching ', fid, ' ...')
with settings(host_string='username@hipergator.rc.ufl.edu'):
run("ssh dev1 rlaunch singleshot -f " + str(fid))
else:
print(
"Haven't recieved execution termination confirmation for the jobs in the firework from hipergator resource manager")
time.sleep(3)
return
if __name__ == '__main__':
launch()
##test
# print(check_done('10995522.moab.ufhpc'))
# print(check_done('10995523.moab.ufhpc'))
# print(check_done('10995520.moab.ufhpc'))
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.