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 |
|---|---|---|---|---|---|
CapnBry/OctoPrint | src/octoprint/util/avr_isp/stk500v2.py | 56 | 4607 | import os, struct, sys, time
from serial import Serial
from serial import SerialException
import ispBase, intelHex
class Stk500v2(ispBase.IspBase):
def __init__(self):
self.serial = None
self.seq = 1
self.lastAddr = -1
self.progressCallback = None
def connect(self, port = 'COM22', speed = 115200):
if self.serial != None:
self.close()
try:
self.serial = Serial(str(port), speed, timeout=1, writeTimeout=10000)
except SerialException as e:
raise ispBase.IspError("Failed to open serial port")
except:
raise ispBase.IspError("Unexpected error while connecting to serial port:" + port + ":" + str(sys.exc_info()[0]))
self.seq = 1
#Reset the controller
self.serial.setDTR(1)
time.sleep(0.1)
self.serial.setDTR(0)
time.sleep(0.2)
self.sendMessage([1])
if self.sendMessage([0x10, 0xc8, 0x64, 0x19, 0x20, 0x00, 0x53, 0x03, 0xac, 0x53, 0x00, 0x00]) != [0x10, 0x00]:
self.close()
raise ispBase.IspError("Failed to enter programming mode")
def close(self):
if self.serial != None:
self.serial.close()
self.serial = None
#Leave ISP does not reset the serial port, only resets the device, and returns the serial port after disconnecting it from the programming interface.
# This allows you to use the serial port without opening it again.
def leaveISP(self):
if self.serial != None:
if self.sendMessage([0x11]) != [0x11, 0x00]:
raise ispBase.IspError("Failed to leave programming mode")
ret = self.serial
self.serial = None
return ret
return None
def isConnected(self):
return self.serial != None
def sendISP(self, data):
recv = self.sendMessage([0x1D, 4, 4, 0, data[0], data[1], data[2], data[3]])
return recv[2:6]
def writeFlash(self, flashData):
#Set load addr to 0, in case we have more then 64k flash we need to enable the address extension
pageSize = self.chip['pageSize'] * 2
flashSize = pageSize * self.chip['pageCount']
if flashSize > 0xFFFF:
self.sendMessage([0x06, 0x80, 0x00, 0x00, 0x00])
else:
self.sendMessage([0x06, 0x00, 0x00, 0x00, 0x00])
loadCount = (len(flashData) + pageSize - 1) / pageSize
for i in xrange(0, loadCount):
recv = self.sendMessage([0x13, pageSize >> 8, pageSize & 0xFF, 0xc1, 0x0a, 0x40, 0x4c, 0x20, 0x00, 0x00] + flashData[(i * pageSize):(i * pageSize + pageSize)])
if self.progressCallback != None:
self.progressCallback(i + 1, loadCount*2)
def verifyFlash(self, flashData):
#Set load addr to 0, in case we have more then 64k flash we need to enable the address extension
flashSize = self.chip['pageSize'] * 2 * self.chip['pageCount']
if flashSize > 0xFFFF:
self.sendMessage([0x06, 0x80, 0x00, 0x00, 0x00])
else:
self.sendMessage([0x06, 0x00, 0x00, 0x00, 0x00])
loadCount = (len(flashData) + 0xFF) / 0x100
for i in xrange(0, loadCount):
recv = self.sendMessage([0x14, 0x01, 0x00, 0x20])[2:0x102]
if self.progressCallback != None:
self.progressCallback(loadCount + i + 1, loadCount*2)
for j in xrange(0, 0x100):
if i * 0x100 + j < len(flashData) and flashData[i * 0x100 + j] != recv[j]:
raise ispBase.IspError('Verify error at: 0x%x' % (i * 0x100 + j))
def sendMessage(self, data):
message = struct.pack(">BBHB", 0x1B, self.seq, len(data), 0x0E)
for c in data:
message += struct.pack(">B", c)
checksum = 0
for c in message:
checksum ^= ord(c)
message += struct.pack(">B", checksum)
try:
self.serial.write(message)
self.serial.flush()
except SerialTimeoutException:
raise ispBase.IspError('Serial send timeout')
self.seq = (self.seq + 1) & 0xFF
return self.recvMessage()
def recvMessage(self):
state = 'Start'
checksum = 0
while True:
s = self.serial.read()
if len(s) < 1:
raise ispBase.IspError("Timeout")
b = struct.unpack(">B", s)[0]
checksum ^= b
#print(hex(b))
if state == 'Start':
if b == 0x1B:
state = 'GetSeq'
checksum = 0x1B
elif state == 'GetSeq':
state = 'MsgSize1'
elif state == 'MsgSize1':
msgSize = b << 8
state = 'MsgSize2'
elif state == 'MsgSize2':
msgSize |= b
state = 'Token'
elif state == 'Token':
if b != 0x0E:
state = 'Start'
else:
state = 'Data'
data = []
elif state == 'Data':
data.append(b)
if len(data) == msgSize:
state = 'Checksum'
elif state == 'Checksum':
if checksum != 0:
state = 'Start'
else:
return data
def main():
programmer = Stk500v2()
programmer.connect(port = sys.argv[1])
programmer.programChip(intelHex.readHex(sys.argv[2]))
sys.exit(1)
if __name__ == '__main__':
main()
| agpl-3.0 |
berrange/nova | nova/cells/state.py | 1 | 18361 | # Copyright (c) 2012 Rackspace Hosting
# 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.
"""
CellState Manager
"""
import copy
import datetime
import functools
import time
from oslo.config import cfg
from oslo.db import exception as db_exc
from nova.cells import rpc_driver
from nova import context
from nova.db import base
from nova import exception
from nova.i18n import _
from nova.openstack.common import fileutils
from nova.openstack.common import jsonutils
from nova.openstack.common import log as logging
from nova.openstack.common import timeutils
from nova.openstack.common import units
from nova import rpc
from nova import utils
cell_state_manager_opts = [
cfg.IntOpt('db_check_interval',
default=60,
help='Interval, in seconds, for getting fresh cell '
'information from the database.'),
cfg.StrOpt('cells_config',
help='Configuration file from which to read cells '
'configuration. If given, overrides reading cells '
'from the database.'),
]
LOG = logging.getLogger(__name__)
CONF = cfg.CONF
CONF.import_opt('name', 'nova.cells.opts', group='cells')
CONF.import_opt('reserve_percent', 'nova.cells.opts', group='cells')
CONF.import_opt('mute_child_interval', 'nova.cells.opts', group='cells')
CONF.register_opts(cell_state_manager_opts, group='cells')
class CellState(object):
"""Holds information for a particular cell."""
def __init__(self, cell_name, is_me=False):
self.name = cell_name
self.is_me = is_me
self.last_seen = datetime.datetime.min
self.capabilities = {}
self.capacities = {}
self.db_info = {}
# TODO(comstud): The DB will specify the driver to use to talk
# to this cell, but there's no column for this yet. The only
# available driver is the rpc driver.
self.driver = rpc_driver.CellsRPCDriver()
def update_db_info(self, cell_db_info):
"""Update cell credentials from db."""
self.db_info = dict(
[(k, v) for k, v in cell_db_info.iteritems()
if k != 'name'])
def update_capabilities(self, cell_metadata):
"""Update cell capabilities for a cell."""
self.last_seen = timeutils.utcnow()
self.capabilities = cell_metadata
def update_capacities(self, capacities):
"""Update capacity information for a cell."""
self.last_seen = timeutils.utcnow()
self.capacities = capacities
def get_cell_info(self):
"""Return subset of cell information for OS API use."""
db_fields_to_return = ['is_parent', 'weight_scale', 'weight_offset']
url_fields_to_return = {
'username': 'username',
'hostname': 'rpc_host',
'port': 'rpc_port',
}
cell_info = dict(name=self.name, capabilities=self.capabilities)
if self.db_info:
for field in db_fields_to_return:
cell_info[field] = self.db_info[field]
url = rpc.get_transport_url(self.db_info['transport_url'])
if url.hosts:
for field, canonical in url_fields_to_return.items():
cell_info[canonical] = getattr(url.hosts[0], field)
return cell_info
def send_message(self, message):
"""Send a message to a cell. Just forward this to the driver,
passing ourselves and the message as arguments.
"""
self.driver.send_message_to_cell(self, message)
def __repr__(self):
me = "me" if self.is_me else "not_me"
return "Cell '%s' (%s)" % (self.name, me)
def sync_before(f):
"""Use as a decorator to wrap methods that use cell information to
make sure they sync the latest information from the DB periodically.
"""
@functools.wraps(f)
def wrapper(self, *args, **kwargs):
self._cell_data_sync()
return f(self, *args, **kwargs)
return wrapper
def sync_after(f):
"""Use as a decorator to wrap methods that update cell information
in the database to make sure the data is synchronized immediately.
"""
@functools.wraps(f)
def wrapper(self, *args, **kwargs):
result = f(self, *args, **kwargs)
self._cell_data_sync(force=True)
return result
return wrapper
_unset = object()
class CellStateManager(base.Base):
def __new__(cls, cell_state_cls=None, cells_config=_unset):
if cls is not CellStateManager:
return super(CellStateManager, cls).__new__(cls)
if cells_config is _unset:
cells_config = CONF.cells.cells_config
if cells_config:
return CellStateManagerFile(cell_state_cls)
return CellStateManagerDB(cell_state_cls)
def __init__(self, cell_state_cls=None):
super(CellStateManager, self).__init__()
if not cell_state_cls:
cell_state_cls = CellState
self.cell_state_cls = cell_state_cls
self.my_cell_state = cell_state_cls(CONF.cells.name, is_me=True)
self.parent_cells = {}
self.child_cells = {}
self.last_cell_db_check = datetime.datetime.min
attempts = 0
while True:
try:
self._cell_data_sync(force=True)
break
except db_exc.DBError as e:
attempts += 1
if attempts > 120:
raise
LOG.exception(_('DB error: %s') % e)
time.sleep(30)
my_cell_capabs = {}
for cap in CONF.cells.capabilities:
name, value = cap.split('=', 1)
if ';' in value:
values = set(value.split(';'))
else:
values = set([value])
my_cell_capabs[name] = values
self.my_cell_state.update_capabilities(my_cell_capabs)
def _refresh_cells_from_dict(self, db_cells_dict):
"""Make our cell info map match the db."""
# Update current cells. Delete ones that disappeared
for cells_dict in (self.parent_cells, self.child_cells):
for cell_name, cell_info in cells_dict.items():
is_parent = cell_info.db_info['is_parent']
db_dict = db_cells_dict.get(cell_name)
if db_dict and is_parent == db_dict['is_parent']:
cell_info.update_db_info(db_dict)
else:
del cells_dict[cell_name]
# Add new cells
for cell_name, db_info in db_cells_dict.items():
if db_info['is_parent']:
cells_dict = self.parent_cells
else:
cells_dict = self.child_cells
if cell_name not in cells_dict:
cells_dict[cell_name] = self.cell_state_cls(cell_name)
cells_dict[cell_name].update_db_info(db_info)
def _time_to_sync(self):
"""Is it time to sync the DB against our memory cache?"""
diff = timeutils.utcnow() - self.last_cell_db_check
return diff.seconds >= CONF.cells.db_check_interval
def _update_our_capacity(self, ctxt=None):
"""Update our capacity in the self.my_cell_state CellState.
This will add/update 2 entries in our CellState.capacities,
'ram_free' and 'disk_free'.
The values of these are both dictionaries with the following
format:
{'total_mb': <total_memory_free_in_the_cell>,
'units_by_mb: <units_dictionary>}
<units_dictionary> contains the number of units that we can build for
every distinct memory or disk requirement that we have based on
instance types. This number is computed by looking at room available
on every compute_node.
Take the following instance_types as an example:
[{'memory_mb': 1024, 'root_gb': 10, 'ephemeral_gb': 100},
{'memory_mb': 2048, 'root_gb': 20, 'ephemeral_gb': 200}]
capacities['ram_free']['units_by_mb'] would contain the following:
{'1024': <number_of_instances_that_will_fit>,
'2048': <number_of_instances_that_will_fit>}
capacities['disk_free']['units_by_mb'] would contain the following:
{'122880': <number_of_instances_that_will_fit>,
'225280': <number_of_instances_that_will_fit>}
Units are in MB, so 122880 = (10 + 100) * 1024.
NOTE(comstud): Perhaps we should only report a single number
available per instance_type.
"""
if not ctxt:
ctxt = context.get_admin_context()
reserve_level = CONF.cells.reserve_percent / 100.0
compute_hosts = {}
def _get_compute_hosts():
compute_nodes = self.db.compute_node_get_all(ctxt)
for compute in compute_nodes:
service = compute['service']
if not service or service['disabled']:
continue
host = service['host']
compute_hosts[host] = {
'free_ram_mb': compute['free_ram_mb'],
'free_disk_mb': compute['free_disk_gb'] * 1024,
'total_ram_mb': compute['memory_mb'],
'total_disk_mb': compute['local_gb'] * 1024}
_get_compute_hosts()
if not compute_hosts:
self.my_cell_state.update_capacities({})
return
ram_mb_free_units = {}
disk_mb_free_units = {}
total_ram_mb_free = 0
total_disk_mb_free = 0
def _free_units(total, free, per_inst):
if per_inst:
min_free = total * reserve_level
free = max(0, free - min_free)
return int(free / per_inst)
else:
return 0
instance_types = self.db.flavor_get_all(ctxt)
memory_mb_slots = frozenset(
[inst_type['memory_mb'] for inst_type in instance_types])
disk_mb_slots = frozenset(
[(inst_type['root_gb'] + inst_type['ephemeral_gb']) * units.Ki
for inst_type in instance_types])
for compute_values in compute_hosts.values():
total_ram_mb_free += compute_values['free_ram_mb']
total_disk_mb_free += compute_values['free_disk_mb']
for memory_mb_slot in memory_mb_slots:
ram_mb_free_units.setdefault(str(memory_mb_slot), 0)
free_units = _free_units(compute_values['total_ram_mb'],
compute_values['free_ram_mb'], memory_mb_slot)
ram_mb_free_units[str(memory_mb_slot)] += free_units
for disk_mb_slot in disk_mb_slots:
disk_mb_free_units.setdefault(str(disk_mb_slot), 0)
free_units = _free_units(compute_values['total_disk_mb'],
compute_values['free_disk_mb'], disk_mb_slot)
disk_mb_free_units[str(disk_mb_slot)] += free_units
capacities = {'ram_free': {'total_mb': total_ram_mb_free,
'units_by_mb': ram_mb_free_units},
'disk_free': {'total_mb': total_disk_mb_free,
'units_by_mb': disk_mb_free_units}}
self.my_cell_state.update_capacities(capacities)
@sync_before
def get_cell_info_for_neighbors(self):
"""Return cell information for all neighbor cells."""
cell_list = [cell.get_cell_info()
for cell in self.child_cells.itervalues()]
cell_list.extend([cell.get_cell_info()
for cell in self.parent_cells.itervalues()])
return cell_list
@sync_before
def get_my_state(self):
"""Return information for my (this) cell."""
return self.my_cell_state
@sync_before
def get_child_cells(self):
"""Return list of child cell_infos."""
return self.child_cells.values()
@sync_before
def get_parent_cells(self):
"""Return list of parent cell_infos."""
return self.parent_cells.values()
@sync_before
def get_parent_cell(self, cell_name):
return self.parent_cells.get(cell_name)
@sync_before
def get_child_cell(self, cell_name):
return self.child_cells.get(cell_name)
@sync_before
def update_cell_capabilities(self, cell_name, capabilities):
"""Update capabilities for a cell."""
cell = (self.child_cells.get(cell_name) or
self.parent_cells.get(cell_name))
if not cell:
LOG.error(_("Unknown cell '%(cell_name)s' when trying to "
"update capabilities"),
{'cell_name': cell_name})
return
# Make sure capabilities are sets.
for capab_name, values in capabilities.items():
capabilities[capab_name] = set(values)
cell.update_capabilities(capabilities)
@sync_before
def update_cell_capacities(self, cell_name, capacities):
"""Update capacities for a cell."""
cell = (self.child_cells.get(cell_name) or
self.parent_cells.get(cell_name))
if not cell:
LOG.error(_("Unknown cell '%(cell_name)s' when trying to "
"update capacities"),
{'cell_name': cell_name})
return
cell.update_capacities(capacities)
@sync_before
def get_our_capabilities(self, include_children=True):
capabs = copy.deepcopy(self.my_cell_state.capabilities)
if include_children:
for cell in self.child_cells.values():
if timeutils.is_older_than(cell.last_seen,
CONF.cells.mute_child_interval):
continue
for capab_name, values in cell.capabilities.items():
if capab_name not in capabs:
capabs[capab_name] = set([])
capabs[capab_name] |= values
return capabs
def _add_to_dict(self, target, src):
for key, value in src.items():
if isinstance(value, dict):
target.setdefault(key, {})
self._add_to_dict(target[key], value)
continue
target.setdefault(key, 0)
target[key] += value
@sync_before
def get_our_capacities(self, include_children=True):
capacities = copy.deepcopy(self.my_cell_state.capacities)
if include_children:
for cell in self.child_cells.values():
self._add_to_dict(capacities, cell.capacities)
return capacities
@sync_before
def get_capacities(self, cell_name=None):
if not cell_name or cell_name == self.my_cell_state.name:
return self.get_our_capacities()
if cell_name in self.child_cells:
return self.child_cells[cell_name].capacities
raise exception.CellNotFound(cell_name=cell_name)
@sync_before
def cell_get(self, ctxt, cell_name):
for cells_dict in (self.parent_cells, self.child_cells):
if cell_name in cells_dict:
return cells_dict[cell_name]
raise exception.CellNotFound(cell_name=cell_name)
class CellStateManagerDB(CellStateManager):
@utils.synchronized('cell-db-sync')
def _cell_data_sync(self, force=False):
"""Update cell status for all cells from the backing data store
when necessary.
:param force: If True, cell status will be updated regardless
of whether it's time to do so.
"""
if force or self._time_to_sync():
LOG.debug("Updating cell cache from db.")
self.last_cell_db_check = timeutils.utcnow()
ctxt = context.get_admin_context()
db_cells = self.db.cell_get_all(ctxt)
db_cells_dict = dict((cell['name'], cell) for cell in db_cells)
self._refresh_cells_from_dict(db_cells_dict)
self._update_our_capacity(ctxt)
@sync_after
def cell_create(self, ctxt, values):
return self.db.cell_create(ctxt, values)
@sync_after
def cell_update(self, ctxt, cell_name, values):
return self.db.cell_update(ctxt, cell_name, values)
@sync_after
def cell_delete(self, ctxt, cell_name):
return self.db.cell_delete(ctxt, cell_name)
class CellStateManagerFile(CellStateManager):
def __init__(self, cell_state_cls=None):
cells_config = CONF.cells.cells_config
self.cells_config_path = CONF.find_file(cells_config)
if not self.cells_config_path:
raise cfg.ConfigFilesNotFoundError(config_files=[cells_config])
super(CellStateManagerFile, self).__init__(cell_state_cls)
def _cell_data_sync(self, force=False):
"""Update cell status for all cells from the backing data store
when necessary.
:param force: If True, cell status will be updated regardless
of whether it's time to do so.
"""
reloaded, data = fileutils.read_cached_file(self.cells_config_path,
force_reload=force)
if reloaded:
LOG.debug("Updating cell cache from config file.")
self.cells_config_data = jsonutils.loads(data)
self._refresh_cells_from_dict(self.cells_config_data)
if force or self._time_to_sync():
self.last_cell_db_check = timeutils.utcnow()
self._update_our_capacity()
def cell_create(self, ctxt, values):
raise exception.CellsUpdateUnsupported()
def cell_update(self, ctxt, cell_name, values):
raise exception.CellsUpdateUnsupported()
def cell_delete(self, ctxt, cell_name):
raise exception.CellsUpdateUnsupported()
| apache-2.0 |
vmax-feihu/hue | desktop/core/ext-py/django-openid-auth-0.5/django_openid_auth/management/commands/openid_cleanup.py | 45 | 1691 | # django-openid-auth - OpenID integration for django.contrib.auth
#
# Copyright (C) 2009-2013 Canonical Ltd.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
from django.core.management.base import NoArgsCommand
from django_openid_auth.store import DjangoOpenIDStore
class Command(NoArgsCommand):
help = 'Clean up stale OpenID associations and nonces'
def handle_noargs(self, **options):
store = DjangoOpenIDStore()
store.cleanup()
| apache-2.0 |
alexanderturner/ansible | lib/ansible/modules/cloud/ovirt/ovirt_external_providers.py | 13 | 9843 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2016 Red Hat, Inc.
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
DOCUMENTATION = '''
---
module: ovirt_external_providers
short_description: Module to manage external providers in oVirt
version_added: "2.3"
author: "Ondra Machacek (@machacekondra)"
description:
- "Module to manage external providers in oVirt"
options:
name:
description:
- "Name of the the external provider to manage."
state:
description:
- "Should the external be present or absent"
choices: ['present', 'absent']
default: present
description:
description:
- "Description of the external provider."
type:
description:
- "Type of the external provider."
choices: ['os_image', 'network', 'os_volume', 'foreman']
url:
description:
- "URL where external provider is hosted."
- "Applicable for those types: I(os_image), I(os_volume), I(network) and I(foreman)."
username:
description:
- "Username to be used for login to external provider."
- "Applicable for all types."
password:
description:
- "Password of the user specified in C(username) parameter."
- "Applicable for all types."
tenant_name:
description:
- "Name of the tenant."
- "Applicable for those types: I(os_image), I(os_volume) and I(network)."
aliases: ['tenant']
authentication_url:
description:
- "Keystone authentication URL of the openstack provider."
- "Applicable for those types: I(os_image), I(os_volume) and I(network)."
aliases: ['auth_url']
data_center:
description:
- "Name of the data center where provider should be attached."
- "Applicable for those type: I(os_volume)."
read_only:
description:
- "Specify if the network should be read only."
- "Applicable if C(type) is I(network)."
network_type:
description:
- "Type of the external network provider either external (for example OVN) or neutron."
- "Applicable if C(type) is I(network)."
choices: ['external', 'neutron']
default: ['external']
extends_documentation_fragment: ovirt
'''
EXAMPLES = '''
# Examples don't contain auth parameter for simplicity,
# look at ovirt_auth module to see how to reuse authentication:
# Add image external provider:
- ovirt_external_providers:
name: image_provider
type: os_image
url: http://10.34.63.71:9292
username: admin
password: 123456
tenant: admin
auth_url: http://10.34.63.71:35357/v2.0/
# Add foreman provider:
- ovirt_external_providers:
name: foreman_provider
type: foreman
url: https://foreman.example.com
username: admin
password: 123456
# Add external network provider for OVN:
- ovirt_external_providers:
name: ovn_provider
type: network
network_type: external
url: http://1.2.3.4:9696
# Remove image external provider:
- ovirt_external_providers:
state: absent
name: image_provider
type: os_image
'''
RETURN = '''
id:
description: ID of the external provider which is managed
returned: On success if external provider is found.
type: str
sample: 7de90f31-222c-436c-a1ca-7e655bd5b60c
external_host_provider:
description: "Dictionary of all the external_host_provider attributes. External provider attributes can be found on your oVirt instance
at following url: https://ovirt.example.com/ovirt-engine/api/model#types/external_host_provider."
returned: "On success and if parameter 'type: foreman' is used."
type: dictionary
openstack_image_provider:
description: "Dictionary of all the openstack_image_provider attributes. External provider attributes can be found on your oVirt instance
at following url: https://ovirt.example.com/ovirt-engine/api/model#types/openstack_image_provider."
returned: "On success and if parameter 'type: os_image' is used."
type: dictionary
openstack_volume_provider:
description: "Dictionary of all the openstack_volume_provider attributes. External provider attributes can be found on your oVirt instance
at following url: https://ovirt.example.com/ovirt-engine/api/model#types/openstack_volume_provider."
returned: "On success and if parameter 'type: os_volume' is used."
type: dictionary
openstack_network_provider:
description: "Dictionary of all the openstack_network_provider attributes. External provider attributes can be found on your oVirt instance
at following url: https://ovirt.example.com/ovirt-engine/api/model#types/openstack_network_provider."
returned: "On success and if parameter 'type: network' is used."
type: dictionary
'''
import traceback
try:
import ovirtsdk4.types as otypes
except ImportError:
pass
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ovirt import (
BaseModule,
check_params,
check_sdk,
create_connection,
equal,
ovirt_full_argument_spec,
)
class ExternalProviderModule(BaseModule):
def provider_type(self, provider_type):
self._provider_type = provider_type
def build_entity(self):
provider_type = self._provider_type(
requires_authentication=self._module.params.get('username') is not None,
)
if self._module.params.pop('type') == 'network':
setattr(
provider_type,
'type',
otypes.OpenStackNetworkProviderType(self._module.params.pop('network_type'))
)
for key, value in self._module.params.items():
if hasattr(provider_type, key):
setattr(provider_type, key, value)
return provider_type
def update_check(self, entity):
return (
equal(self._module.params.get('description'), entity.description) and
equal(self._module.params.get('url'), entity.url) and
equal(self._module.params.get('authentication_url'), entity.authentication_url) and
equal(self._module.params.get('tenant_name'), getattr(entity, 'tenant_name', None)) and
equal(self._module.params.get('username'), entity.username)
)
def _external_provider_service(provider_type, system_service):
if provider_type == 'os_image':
return otypes.OpenStackImageProvider, system_service.openstack_image_providers_service()
elif provider_type == 'network':
return otypes.OpenStackNetworkProvider, system_service.openstack_network_providers_service()
elif provider_type == 'os_volume':
return otypes.OpenStackVolumeProvider, system_service.openstack_volume_providers_service()
elif provider_type == 'foreman':
return otypes.ExternalHostProvider, system_service.external_host_providers_service()
def main():
argument_spec = ovirt_full_argument_spec(
state=dict(
choices=['present', 'absent'],
default='present',
),
name=dict(default=None),
description=dict(default=None),
type=dict(
default=None,
required=True,
choices=[
'os_image', 'network', 'os_volume', 'foreman',
],
aliases=['provider'],
),
url=dict(default=None),
username=dict(default=None),
password=dict(default=None, no_log=True),
tenant_name=dict(default=None, aliases=['tenant']),
authentication_url=dict(default=None, aliases=['auth_url']),
data_center=dict(default=None, aliases=['data_center']),
read_only=dict(default=None, type='bool'),
network_type=dict(
default='external',
choices=['external', 'neutron'],
),
)
module = AnsibleModule(
argument_spec=argument_spec,
supports_check_mode=True,
)
check_sdk(module)
check_params(module)
try:
connection = create_connection(module.params.pop('auth'))
provider_type, external_providers_service = _external_provider_service(
provider_type=module.params.get('type'),
system_service=connection.system_service(),
)
external_providers_module = ExternalProviderModule(
connection=connection,
module=module,
service=external_providers_service,
)
external_providers_module.provider_type(provider_type)
state = module.params.pop('state')
if state == 'absent':
ret = external_providers_module.remove()
elif state == 'present':
ret = external_providers_module.create()
module.exit_json(**ret)
except Exception as e:
module.fail_json(msg=str(e), exception=traceback.format_exc())
finally:
connection.close(logout=False)
if __name__ == "__main__":
main()
| gpl-3.0 |
apache/flink | flink-python/pyflink/common/watermark_strategy.py | 13 | 5378 | ################################################################################
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
################################################################################
import abc
from typing import Any
from pyflink.common.time import Duration
from pyflink.java_gateway import get_gateway
class WatermarkStrategy(object):
"""
The WatermarkStrategy defines how to generate Watermarks in the stream sources. The
WatermarkStrategy is a builder/factory for the WatermarkGenerator that generates the watermarks
and the TimestampAssigner which assigns the internal timestamp of a record.
The convenience methods, for example forBoundedOutOfOrderness(Duration), create a
WatermarkStrategy for common built in strategies.
"""
def __init__(self, j_watermark_strategy):
self._j_watermark_strategy = j_watermark_strategy
self._timestamp_assigner = None
def with_timestamp_assigner(self, timestamp_assigner: 'TimestampAssigner') -> \
'WatermarkStrategy':
"""
Creates a new WatermarkStrategy that wraps this strategy but instead uses the given a
TimestampAssigner by implementing TimestampAssigner interface.
::
>>> watermark_strategy = WatermarkStrategy.for_monotonous_timestamps()
>>> .with_timestamp_assigner(MyTimestampAssigner())
:param timestamp_assigner: The given TimestampAssigner.
:return: A WaterMarkStrategy that wraps a TimestampAssigner.
"""
self._timestamp_assigner = timestamp_assigner
return self
def with_idleness(self, idle_timeout: Duration) -> 'WatermarkStrategy':
"""
Creates a new enriched WatermarkStrategy that also does idleness detection in the created
WatermarkGenerator.
:param idle_timeout: The idle timeout.
:return: A new WatermarkStrategy with idle detection configured.
"""
self._j_watermark_strategy = self._j_watermark_strategy\
.withIdleness(idle_timeout._j_duration)
return self
@staticmethod
def for_monotonous_timestamps():
"""
Creates a watermark strategy for situations with monotonously ascending timestamps.
The watermarks are generated periodically and tightly follow the latest timestamp in the
data. The delay introduced by this strategy is mainly the periodic interval in which the
watermarks are generated.
"""
JWaterMarkStrategy = get_gateway().jvm\
.org.apache.flink.api.common.eventtime.WatermarkStrategy
return WatermarkStrategy(JWaterMarkStrategy.forMonotonousTimestamps())
@staticmethod
def for_bounded_out_of_orderness(max_out_of_orderness: Duration):
"""
Creates a watermark strategy for situations where records are out of order, but you can
place an upper bound on how far the events are out of order. An out-of-order bound B means
that once the an event with timestamp T was encountered, no events older than (T - B) will
follow any more.
"""
JWaterMarkStrategy = get_gateway().jvm \
.org.apache.flink.api.common.eventtime.WatermarkStrategy
return WatermarkStrategy(
JWaterMarkStrategy.forBoundedOutOfOrderness(max_out_of_orderness._j_duration))
class TimestampAssigner(abc.ABC):
"""
A TimestampAssigner assigns event time timestamps to elements. These timestamps are used by all
functions that operate on event time, for example event time windows.
Timestamps can be an arbitrary int value, but all built-in implementations represent it as the
milliseconds since the Epoch (midnight, January 1, 1970 UTC), the same way as time.time() does
it.
"""
@abc.abstractmethod
def extract_timestamp(self, value: Any, record_timestamp: int) -> int:
"""
Assigns a timestamp to an element, in milliseconds since the Epoch. This is independent of
any particular time zone or calendar.
The method is passed the previously assigned timestamp of the element.
That previous timestamp may have been assigned from a previous assigner. If the element did
not carry a timestamp before, this value is the minimum value of int type.
:param value: The element that the timestamp will be assigned to.
:param record_timestamp: The current internal timestamp of the element, or a negative value,
if no timestamp has been assigned yet.
:return: The new timestamp.
"""
pass
| apache-2.0 |
xbmc/xbmc-antiquated | xbmc/lib/libPython/Python/Lib/plat-mac/lib-scriptpackages/SystemEvents/System_Events_Suite.py | 82 | 3770 | """Suite System Events Suite: Terms and Events for controlling the System Events application
Level 1, version 1
Generated from /System/Library/CoreServices/System Events.app
AETE/AEUT resource version 1/0, language 0, script 0
"""
import aetools
import MacOS
_code = 'sevs'
class System_Events_Suite_Events:
def do_script(self, _object, _attributes={}, **_arguments):
"""do script: Execute an OSA script.
Required argument: the object for the command
Keyword argument _attributes: AppleEvent attribute dictionary
"""
_code = 'misc'
_subcode = 'dosc'
if _arguments: raise TypeError, 'No optional args expected'
_arguments['----'] = _object
_reply, _arguments, _attributes = self.send(_code, _subcode,
_arguments, _attributes)
if _arguments.get('errn', 0):
raise aetools.Error, aetools.decodeerror(_arguments)
# XXXX Optionally decode result
if _arguments.has_key('----'):
return _arguments['----']
class application(aetools.ComponentItem):
"""application - The System Events application """
want = 'capp'
class _Prop__3c_Inheritance_3e_(aetools.NProperty):
"""<Inheritance> - All of the properties of the superclass. """
which = 'c@#^'
want = 'capp'
_3c_Inheritance_3e_ = _Prop__3c_Inheritance_3e_()
class _Prop_folder_actions_enabled(aetools.NProperty):
"""folder actions enabled - Are Folder Actions currently being processed? """
which = 'faen'
want = 'bool'
folder_actions_enabled = _Prop_folder_actions_enabled()
class _Prop_properties(aetools.NProperty):
"""properties - every property of the System Events application """
which = 'pALL'
want = '****'
properties = _Prop_properties()
# element 'cdis' as ['name', 'indx', 'rele', 'rang', 'test']
# element 'cfol' as ['name', 'indx', 'rele', 'rang', 'test']
# element 'cobj' as ['name', 'indx', 'rele', 'rang', 'test']
# element 'cwin' as ['name', 'indx', 'rele', 'rang', 'test', 'ID ']
# element 'docu' as ['name', 'indx', 'rele', 'rang', 'test']
# element 'file' as ['name', 'indx', 'rele', 'rang', 'test']
# element 'foac' as ['name', 'indx', 'rele', 'rang', 'test']
# element 'logi' as ['name', 'indx', 'rele', 'rang', 'test']
# element 'pcap' as ['name', 'indx', 'rele', 'rang', 'test']
# element 'pcda' as ['name', 'indx', 'rele', 'rang', 'test']
# element 'prcs' as ['name', 'indx', 'rele', 'rang', 'test']
applications = application
application._superclassnames = []
import Disk_Folder_File_Suite
import Standard_Suite
import Folder_Actions_Suite
import Login_Items_Suite
import Processes_Suite
application._privpropdict = {
'_3c_Inheritance_3e_' : _Prop__3c_Inheritance_3e_,
'folder_actions_enabled' : _Prop_folder_actions_enabled,
'properties' : _Prop_properties,
}
application._privelemdict = {
'application_process' : Processes_Suite.application_process,
'desk_accessory_process' : Processes_Suite.desk_accessory_process,
'disk' : Disk_Folder_File_Suite.disk,
'document' : Standard_Suite.document,
'file' : Disk_Folder_File_Suite.file,
'folder' : Disk_Folder_File_Suite.folder,
'folder_action' : Folder_Actions_Suite.folder_action,
'item' : Disk_Folder_File_Suite.item,
'login_item' : Login_Items_Suite.login_item,
'process' : Processes_Suite.process,
'window' : Standard_Suite.window,
}
#
# Indices of types declared in this module
#
_classdeclarations = {
'capp' : application,
}
_propdeclarations = {
'c@#^' : _Prop__3c_Inheritance_3e_,
'faen' : _Prop_folder_actions_enabled,
'pALL' : _Prop_properties,
}
_compdeclarations = {
}
_enumdeclarations = {
}
| gpl-2.0 |
smunaut/gnuradio | gnuradio-runtime/examples/mp-sched/run_synthetic.py | 78 | 3989 | #!/usr/bin/env python
#
# Copyright 2008 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 this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
"""
Run synthetic.py for npipes in [1,16], nstages in [1,16]
"""
import re
import sys
import os
import tempfile
from optparse import OptionParser
def write_shell_script(f, data_filename, description, ncores, gflops, max_pipes_and_stages):
"""
f is the file to write the script to
data_filename is the where the data ends up
description describes the machine
ncores is the number of cores (used to size the workload)
gflops is the estimated GFLOPS per core (used to size the workload)
"""
f.write("#!/bin/sh\n")
f.write("(\n")
if description:
f.write("echo '#D %s'\n" % (description,))
for npipes in range(1, max_pipes_and_stages + 1):
for nstages in range(1, max_pipes_and_stages + 1):
# We'd like each run of synthetic to take ~10 seconds
desired_time_per_run = 10
est_gflops_avail = min(nstages * npipes, ncores) * gflops
nsamples = (est_gflops_avail * desired_time_per_run)/(512.0 * nstages * npipes)
nsamples = int(nsamples * 1e9)
cmd = "./synthetic.py -m -s %d -p %d -N %d\n" % (nstages, npipes, nsamples)
f.write(cmd)
f.write('if test $? -ge 128; then exit 128; fi\n')
f.write(") 2>&1 | grep --line-buffered -v '^>>>' | tee %s\n" % (data_filename,))
f.flush()
def main():
description = """%prog gathers multiprocessor scaling data using the ./synthetic.py benchmark.
All combinations of npipes and nstages between 1 and --max-pipes-and-stages are tried.
The -n and -f options provides hints used to size the workload. We'd like each run
of synthetic to take about 10 seconds. For the full 16x16 case this results in a
total runtime of about 43 minutes, assuming that your values for -n and -f are reasonable.
For x86 machines, assume 3 FLOPS per processor Hz. E.g., 3 GHz machine -> 9 GFLOPS.
plot_flops.py will make pretty graphs from the output data generated by %prog.
"""
usage = "usage: %prog [options] output.dat"
parser = OptionParser(usage=usage, description=description)
parser.add_option("-d", "--description", metavar="DESC",
help="machine description, e.g., \"Dual quad-core Xeon 3 GHz\"", default=None)
parser.add_option("-n", "--ncores", type="int", default=1,
help="number of processor cores [default=%default]")
parser.add_option("-g", "--gflops", metavar="GFLOPS", type="float", default=3.0,
help="estimated GFLOPS per core [default=%default]")
parser.add_option("-m", "--max-pipes-and-stages", metavar="MAX", type="int", default=16,
help="maximum number of pipes and stages to use [default=%default]")
(options, args) = parser.parse_args()
if len(args) != 1:
parser.print_help()
raise SystemExit, 1
output_filename = args[0]
shell = os.popen("/bin/sh", "w")
write_shell_script(shell,
output_filename,
options.description,
options.ncores,
options.gflops,
options.max_pipes_and_stages)
if __name__ == '__main__':
main()
| gpl-3.0 |
bastik/youtube-dl | youtube_dl/extractor/sexykarma.py | 90 | 4429 | # coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
unified_strdate,
parse_duration,
int_or_none,
)
class SexyKarmaIE(InfoExtractor):
IE_DESC = 'Sexy Karma and Watch Indian Porn'
_VALID_URL = r'https?://(?:www\.)?(?:sexykarma\.com|watchindianporn\.net)/(?:[^/]+/)*video/(?P<display_id>[^/]+)-(?P<id>[a-zA-Z0-9]+)\.html'
_TESTS = [{
'url': 'http://www.sexykarma.com/gonewild/video/taking-a-quick-pee-yHI70cOyIHt.html',
'md5': 'b9798e7d1ef1765116a8f516c8091dbd',
'info_dict': {
'id': 'yHI70cOyIHt',
'display_id': 'taking-a-quick-pee',
'ext': 'mp4',
'title': 'Taking a quick pee.',
'thumbnail': 're:^https?://.*\.jpg$',
'uploader': 'wildginger7',
'upload_date': '20141008',
'duration': 22,
'view_count': int,
'comment_count': int,
'categories': list,
'age_limit': 18,
}
}, {
'url': 'http://www.sexykarma.com/gonewild/video/pot-pixie-tribute-8Id6EZPbuHf.html',
'md5': 'dd216c68d29b49b12842b9babe762a5d',
'info_dict': {
'id': '8Id6EZPbuHf',
'display_id': 'pot-pixie-tribute',
'ext': 'mp4',
'title': 'pot_pixie tribute',
'thumbnail': 're:^https?://.*\.jpg$',
'uploader': 'banffite',
'upload_date': '20141013',
'duration': 16,
'view_count': int,
'comment_count': int,
'categories': list,
'age_limit': 18,
}
}, {
'url': 'http://www.watchindianporn.net/video/desi-dancer-namrata-stripping-completely-nude-and-dancing-on-a-hot-number-dW2mtctxJfs.html',
'md5': '9afb80675550406ed9a63ac2819ef69d',
'info_dict': {
'id': 'dW2mtctxJfs',
'display_id': 'desi-dancer-namrata-stripping-completely-nude-and-dancing-on-a-hot-number',
'ext': 'mp4',
'title': 'Desi dancer namrata stripping completely nude and dancing on a hot number',
'thumbnail': 're:^https?://.*\.jpg$',
'uploader': 'Don',
'upload_date': '20140213',
'duration': 83,
'view_count': int,
'comment_count': int,
'categories': list,
'age_limit': 18,
}
}]
def _real_extract(self, url):
mobj = re.match(self._VALID_URL, url)
video_id = mobj.group('id')
display_id = mobj.group('display_id')
webpage = self._download_webpage(url, display_id)
video_url = self._html_search_regex(
r"url: escape\('([^']+)'\)", webpage, 'url')
title = self._html_search_regex(
r'<h2 class="he2"><span>(.*?)</span>',
webpage, 'title')
thumbnail = self._html_search_regex(
r'<span id="container"><img\s+src="([^"]+)"',
webpage, 'thumbnail', fatal=False)
uploader = self._html_search_regex(
r'class="aupa">\s*(.*?)</a>',
webpage, 'uploader')
upload_date = unified_strdate(self._html_search_regex(
r'Added: <strong>(.+?)</strong>', webpage, 'upload date', fatal=False))
duration = parse_duration(self._search_regex(
r'<td>Time:\s*</td>\s*<td align="right"><span>\s*(.+?)\s*</span>',
webpage, 'duration', fatal=False))
view_count = int_or_none(self._search_regex(
r'<td>Views:\s*</td>\s*<td align="right"><span>\s*(\d+)\s*</span>',
webpage, 'view count', fatal=False))
comment_count = int_or_none(self._search_regex(
r'<td>Comments:\s*</td>\s*<td align="right"><span>\s*(\d+)\s*</span>',
webpage, 'comment count', fatal=False))
categories = re.findall(
r'<a href="[^"]+/search/video/desi"><span>([^<]+)</span></a>',
webpage)
return {
'id': video_id,
'display_id': display_id,
'url': video_url,
'title': title,
'thumbnail': thumbnail,
'uploader': uploader,
'upload_date': upload_date,
'duration': duration,
'view_count': view_count,
'comment_count': comment_count,
'categories': categories,
'age_limit': 18,
}
| unlicense |
vpodzime/pykickstart | tests/commands/services.py | 8 | 2119 | # Andy Lindeberg <alindebe@redhat.com>
#
# Copyright 2009 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use, modify,
# copy, or redistribute it subject to the terms and conditions of the GNU
# General Public License v.2. This program is distributed in the hope that it
# will be useful, but WITHOUT ANY WARRANTY expressed or implied, including the
# implied warranties 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. Any Red Hat
# trademarks that are incorporated in the source code or documentation are not
# subject to the GNU General Public License and may only be used or replicated
# with the express permission of Red Hat, Inc.
#
import unittest
from tests.baseclass import CommandTest
from pykickstart.errors import KickstartParseError
class FC6_TestCase(CommandTest):
command = "services"
def runTest(self):
# pass
self.assert_parse("services --enabled=WHEEITSASTRING", "services --enabled=\"WHEEITSASTRING\"\n")
self.assert_parse("services --disabled=WHEEANOTHERSTRING", "services --disabled=\"WHEEANOTHERSTRING\"\n")
self.assert_parse("services --enabled=thing1,thing2,thing3", "services --enabled=\"thing1,thing2,thing3\"\n")
self.assert_parse("services --enabled=\"thing1, thing2, thing3\"", "services --enabled=\"thing1,thing2,thing3\"\n")
self.assert_parse("services --disabled=thing1,thing2", "services --disabled=\"thing1,thing2\"\n")
self.assert_parse("services --disabled=\"thing1, thing2\"", "services --disabled=\"thing1,thing2\"\n")
# fail
self.assert_parse_error("services", KickstartParseError)
self.assert_parse_error("services --enabled", KickstartParseError)
self.assert_parse_error("services --disabled", KickstartParseError)
if __name__ == "__main__":
unittest.main()
| gpl-2.0 |
furatto-totsuka/gen_eventpaper | src/main.py | 1 | 7173 | # python
# -*- coding: utf-8 -*-
import argparse
import openpyxl
from data import EventManager, Day, EventList
from jinja2 import Environment, FileSystemLoader
from pprint import pprint
parser = argparse.ArgumentParser(description='ふらっとステーション・とつか ふらっとイベントだより生成ツール')
parser.add_argument('filename',
type=str,
nargs=None,
help=u'イベント表ファイルのパスを指定します')
parser.add_argument('-e', '--eventlist',
type=str,
required=True,
help=u'イベント詳細定義ファイルのパスを指定します')
parser.add_argument('-f', '--continue_is_fault',
default=False,
action='store_true',
help=u'イベント詳細が見つからない項目があった場合でも、そのままリストを生成します(省略時False)')
parser.add_argument('-n', '--notice',
type=str,
help=u'フッタに表示する通知文を指定します')
parser.add_argument('-t', '--template',
type=str,
default="doc",
help=u'テンプレートを指定します(省略時doc)')
parser.add_argument('-o', '--output',
type=str,
help=u'出力するファイル名を指定します(省略時は標準出力に出力します)')
parser.add_argument('-c', '--charset',
type=str,
default="utf-8",
help=u'ファイル出力時の文字コードを指定します(省略時UTF-8)')
def main(args):
# イベントリスト作成
events = EventManager(args.eventlist)
caldata = get_monthevent(args.filename, events, args.continue_is_fault)
caldata.insertHolidays()
# テンプレート展開
baseday = caldata.getMonthFirstDay()
vars = {
"year": baseday.year,
"month" : baseday.month,
"events": caldata.getEventListToRawData(),
"notice": args.notice
}
env = Environment(loader=FileSystemLoader('./tmpl/', encoding='utf8'))
tmpl= env.get_template(args.template + ".jinja2")
html = tmpl.render(vars)
if args.output == None:
print(html)
else:
import codecs
f = codecs.open(args.output, 'w', args.charset)
f.write(html)
f.close()
### イベント表をチェックする(振り分け関数)
def get_monthevent(filename, events, continue_is_fault):
book = openpyxl.load_workbook(filename)
sheet = book.active
if sheet['A1'].value == "No":
return get_monthevent_v1(sheet, events, continue_is_fault)
else:
return get_monthevent_v2(sheet, events, continue_is_fault)
def get_monthevent_v2(worksheet, events, continue_is_fault):
u"""イベント表をチェックする。v2フォーマット処理"""
ym = calcym(worksheet.title)
# 一回目スキャン(リストは並び替えられていない)
lw = []
ld = 0
for row in worksheet.rows:
if row[0].row != 1 and row[3].value != None and row[4].value != None and row[5].value != None:
if row[0] != None and row[0].value != None: # 日付がNoneの場合、直前のセルの日付を使う
ld = int(row[0].value)
d = ld
lw.append({
"date": d,
"week": row[1].value,
"time": row[2].value,
"mark": row[3].value[0],
"name": row[3].value[1:],
"content": row[4].value,
"type": row[5].value,
})
lw = sorted(lw, key=lambda c: c["date"])
# 二回目スキャン(リストは並び替え済み)
day = None
caldata = EventList()
daylist = []
errdata = []
from datetime import datetime
for row in lw:
try:
if day == None or day != row["date"]:
if len(daylist) != 0: # 前日の予定をイベントリストに追加
d = Day(datetime(ym[0], ym[1], day))
d.setEvents(list(daylist))
caldata.append(d)
day = row["date"]
daylist = []
e = events.createEvent(row["mark"], row["name"], row["content"], u"ふらっとステーション・とつか", row["type"])
if row["time"] != "": #時刻取得(時刻がないものについてはパースしない)
e.setTimeStr(row["time"])
daylist.append(e)
except KeyError as e:
# 取得エラーはあとで報告
errdata.append({
"date": datetime(ym[0], ym[1], row["date"]),
"name": row["name"],
"remark": u"イベント詳細定義ファイルに定義が見つからない"
})
# TODO: コードが二重に作成されている。重複を避ける方法はない?
if len(daylist) != 0: # 前日の予定をイベントリストに追加
d = Day(datetime(ym[0], ym[1], day))
d.setEvents(list(daylist))
caldata.append(d)
if len(errdata) != 0:
# エラー確認
import sys
print(u"エラーがありました。広報メンバーに確認してください", file=sys.stderr)
for err in errdata:
print(f"{err['date']:%m/%d}:{err['name']}({err['remark']})", file=sys.stderr)
if not continue_is_fault:
raise "処理に失敗しました"
return caldata
def calcym(wstitle):
u"""わくわくだよりのタイトルから、何年何月のわくわくだよりかチェックする"""
import re
go = re.match("(\d{4})(\d{2})", wstitle)
year = int(go.group(1))
month = int(go.group(2))
return (year, month)
### イベント表をチェックする
def get_monthevent_v1(worksheet, events, continue_is_fault):
caldata = EventList()
daylist = []
errdata = []
date = None
for row in worksheet.rows:
try:
if row[0].row != 1:
if date == None or date != row[1].value:
if len(daylist) != 0: # 前日の予定をイベントリストに追加
d = Day(date)
d.setEvents(list(daylist))
caldata.append(d)
date = row[1].value
daylist = []
e = events.createEvent(row[3].value, row[4].value)
if row[5].value != "": #時刻取得(時刻がないものについてはパースしない)
e.setTimeStr(row[5].value)
daylist.append(e)
except KeyError as e:
# 取得エラーはあとで報告
errdata.append({
"date": row[1].value,
"name": row[4].value
})
if len(errdata) != 0:
# エラー確認
import sys
print(u"イベント詳細に登録されていないイベントがあります。広報メンバーに確認してください", file=sys.stderr)
for err in errdata:
print(err["date"].strftime(u"%m/%d") + ":" + err["name"], file=sys.stderr)
if not continue_is_fault:
raise "処理に失敗しました"
return caldata
try:
args = parser.parse_args()
main(args)
except FileNotFoundError as fnfe:
print(u"引数に指定したファイルが存在しません。")
| apache-2.0 |
davido/buck | third-party/py/pex/pex/finders.py | 37 | 10270 | # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
"""The finders we wish we had in setuptools.
As of setuptools 3.3, the only finder for zip-based distributions is for eggs. The path-based
finder only searches paths ending in .egg and not in .whl (zipped or unzipped.)
pex.finders augments pkg_resources with additional finders to achieve functional
parity between wheels and eggs in terms of findability with find_distributions.
To use:
>>> from pex.finders import register_finders
>>> register_finders()
"""
import os
import pkgutil
import sys
import zipimport
import pkg_resources
if sys.version_info >= (3, 3) and sys.implementation.name == "cpython":
import importlib._bootstrap as importlib_bootstrap
else:
importlib_bootstrap = None
class ChainedFinder(object):
"""A utility to chain together multiple pkg_resources finders."""
@classmethod
def of(cls, *chained_finder_or_finder):
finders = []
for finder in chained_finder_or_finder:
if isinstance(finder, cls):
finders.extend(finder.finders)
else:
finders.append(finder)
return cls(finders)
def __init__(self, finders):
self.finders = finders
def __call__(self, importer, path_item, only=False):
for finder in self.finders:
for dist in finder(importer, path_item, only=only):
yield dist
def __eq__(self, other):
if not isinstance(other, ChainedFinder):
return False
return self.finders == other.finders
# The following methods are somewhat dangerous as pkg_resources._distribution_finders is not an
# exposed API. As it stands, pkg_resources doesn't provide an API to chain multiple distribution
# finders together. This is probably possible using importlib but that does us no good as the
# importlib machinery supporting this is only available in Python >= 3.1.
def _get_finder(importer):
if not hasattr(pkg_resources, '_distribution_finders'):
return None
return pkg_resources._distribution_finders.get(importer)
def _add_finder(importer, finder):
"""Register a new pkg_resources path finder that does not replace the existing finder."""
existing_finder = _get_finder(importer)
if not existing_finder:
pkg_resources.register_finder(importer, finder)
else:
pkg_resources.register_finder(importer, ChainedFinder.of(existing_finder, finder))
def _remove_finder(importer, finder):
"""Remove an existing finder from pkg_resources."""
existing_finder = _get_finder(importer)
if not existing_finder:
return
if isinstance(existing_finder, ChainedFinder):
try:
existing_finder.finders.remove(finder)
except ValueError:
return
if len(existing_finder.finders) == 1:
pkg_resources.register_finder(importer, existing_finder.finders[0])
elif len(existing_finder.finders) == 0:
pkg_resources.register_finder(importer, pkg_resources.find_nothing)
else:
pkg_resources.register_finder(importer, pkg_resources.find_nothing)
class WheelMetadata(pkg_resources.EggMetadata):
"""Metadata provider for zipped wheels."""
@classmethod
def _split_wheelname(cls, wheelname):
split_wheelname = wheelname.split('-')
return '-'.join(split_wheelname[:-3])
def _setup_prefix(self):
path = self.module_path
old = None
while path != old:
if path.lower().endswith('.whl'):
self.egg_name = os.path.basename(path)
# TODO(wickman) Test the regression where we have both upper and lower cased package
# names.
self.egg_info = os.path.join(path, '%s.dist-info' % self._split_wheelname(self.egg_name))
self.egg_root = path
break
old = path
path, base = os.path.split(path)
# See https://bitbucket.org/tarek/distribute/issue/274
class FixedEggMetadata(pkg_resources.EggMetadata):
"""An EggMetadata provider that has functional parity with the disk-based provider."""
@classmethod
def normalized_elements(cls, path):
path_split = path.split('/')
while path_split[-1] in ('', '.'):
path_split.pop(-1)
return path_split
def _fn(self, base, resource_name):
# super() does not work here as EggMetadata is an old-style class.
original_fn = pkg_resources.EggMetadata._fn(self, base, resource_name)
return '/'.join(self.normalized_elements(original_fn))
def _zipinfo_name(self, fspath):
fspath = self.normalized_elements(fspath)
zip_pre = self.normalized_elements(self.zip_pre)
if fspath[:len(zip_pre)] == zip_pre:
return '/'.join(fspath[len(zip_pre):])
assert "%s is not a subpath of %s" % (fspath, self.zip_pre)
def wheel_from_metadata(location, metadata):
if not metadata.has_metadata(pkg_resources.DistInfoDistribution.PKG_INFO):
return None
from email.parser import Parser
pkg_info = Parser().parsestr(metadata.get_metadata(pkg_resources.DistInfoDistribution.PKG_INFO))
return pkg_resources.DistInfoDistribution(
location=location,
metadata=metadata,
# TODO(wickman) Is this necessary or will they get picked up correctly?
project_name=pkg_info.get('Name'),
version=pkg_info.get('Version'),
platform=None)
def find_wheels_on_path(importer, path_item, only=False):
if not os.path.isdir(path_item) or not os.access(path_item, os.R_OK):
return
if not only:
for entry in os.listdir(path_item):
if entry.lower().endswith('.whl'):
for dist in pkg_resources.find_distributions(os.path.join(path_item, entry)):
yield dist
def find_eggs_in_zip(importer, path_item, only=False):
if importer.archive.endswith('.whl'):
# Defer to wheel importer
return
metadata = FixedEggMetadata(importer)
if metadata.has_metadata('PKG-INFO'):
yield pkg_resources.Distribution.from_filename(path_item, metadata=metadata)
if only:
return # don't yield nested distros
for subitem in metadata.resource_listdir('/'):
if subitem.endswith('.egg'):
subpath = os.path.join(path_item, subitem)
for dist in find_eggs_in_zip(zipimport.zipimporter(subpath), subpath):
yield dist
def find_wheels_in_zip(importer, path_item, only=False):
metadata = WheelMetadata(importer)
dist = wheel_from_metadata(path_item, metadata)
if dist:
yield dist
__PREVIOUS_FINDER = None
def register_finders():
"""Register finders necessary for PEX to function properly."""
# If the previous finder is set, then we've already monkeypatched, so skip.
global __PREVIOUS_FINDER
if __PREVIOUS_FINDER:
return
# save previous finder so that it can be restored
previous_finder = _get_finder(zipimport.zipimporter)
assert previous_finder, 'This appears to be using an incompatible setuptools.'
# replace the zip finder with our own implementation of find_eggs_in_zip which uses the correct
# metadata handler, in addition to find_wheels_in_zip
pkg_resources.register_finder(
zipimport.zipimporter, ChainedFinder.of(find_eggs_in_zip, find_wheels_in_zip))
# append the wheel finder
_add_finder(pkgutil.ImpImporter, find_wheels_on_path)
if importlib_bootstrap is not None:
_add_finder(importlib_bootstrap.FileFinder, find_wheels_on_path)
__PREVIOUS_FINDER = previous_finder
def unregister_finders():
"""Unregister finders necessary for PEX to function properly."""
global __PREVIOUS_FINDER
if not __PREVIOUS_FINDER:
return
pkg_resources.register_finder(zipimport.zipimporter, __PREVIOUS_FINDER)
_remove_finder(pkgutil.ImpImporter, find_wheels_on_path)
if importlib_bootstrap is not None:
_remove_finder(importlib_bootstrap.FileFinder, find_wheels_on_path)
__PREVIOUS_FINDER = None
def get_script_from_egg(name, dist):
"""Returns location, content of script in distribution or (None, None) if not there."""
if name in dist.metadata_listdir('scripts'):
return (
os.path.join(dist.egg_info, 'scripts', name),
dist.get_metadata('scripts/%s' % name).replace('\r\n', '\n').replace('\r', '\n'))
return None, None
def safer_name(name):
return name.replace('-', '_')
def get_script_from_whl(name, dist):
# This is true as of at least wheel==0.24. Might need to take into account the
# metadata version bundled with the wheel.
wheel_scripts_dir = '%s-%s.data/scripts' % (safer_name(dist.key), dist.version)
if dist.resource_isdir(wheel_scripts_dir) and name in dist.resource_listdir(wheel_scripts_dir):
script_path = os.path.join(wheel_scripts_dir, name)
return (
os.path.join(dist.egg_info, script_path),
dist.get_resource_string('', script_path).replace(b'\r\n', b'\n').replace(b'\r', b'\n'))
return None, None
def get_script_from_distribution(name, dist):
# PathMetadata: exploded distribution on disk.
if isinstance(dist._provider, pkg_resources.PathMetadata):
if dist.egg_info.endswith('EGG-INFO'):
return get_script_from_egg(name, dist)
elif dist.egg_info.endswith('.dist-info'):
return get_script_from_whl(name, dist)
else:
return None, None
# FixedEggMetadata: Zipped egg
elif isinstance(dist._provider, FixedEggMetadata):
return get_script_from_egg(name, dist)
# WheelMetadata: Zipped whl (in theory should not experience this at runtime.)
elif isinstance(dist._provider, WheelMetadata):
return get_script_from_whl(name, dist)
return None, None
def get_script_from_distributions(name, dists):
for dist in dists:
script_path, script_content = get_script_from_distribution(name, dist)
if script_path:
return dist, script_path, script_content
return None, None, None
def get_entry_point_from_console_script(script, dists):
# check all distributions for the console_script "script"
entries = frozenset(filter(None, (
dist.get_entry_map().get('console_scripts', {}).get(script) for dist in dists)))
# if multiple matches, freak out
if len(entries) > 1:
raise RuntimeError(
'Ambiguous script specification %s matches multiple entry points:%s' % (
script, ' '.join(map(str, entries))))
if entries:
entry_point = next(iter(entries))
# entry points are of the form 'foo = bar', we just want the 'bar' part:
return str(entry_point).split('=')[1].strip()
| apache-2.0 |
dahaic/outerspace | client/osci/dialog/ResearchDlg.py | 2 | 18708 | #
# Copyright 2001 - 2016 Ludek Smid [http://www.ospace.net/]
#
# This file is part of Outer Space.
#
# Outer Space 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.
#
# Outer Space 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 Outer Space; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
import math
import pygameui as ui
import ige
from ige.ospace import Rules, Utils, TechHandlers
import ige.ospace.Const as Const
from osci import client, res, gdata
from TechInfoDlg import TechInfoDlg
from ConfirmDlg import ConfirmDlg
class ResearchDlg:
def __init__(self, app):
self.app = app
self.techInfoDlg = TechInfoDlg(app)
self.confirmDlg = ConfirmDlg(app)
self.showCompleted = 0
self.showObsolete = 0
self.createUI()
def display(self):
self.win.vUnObs.enabled = 0
self.win.vObs.enabled = 0
self.show()
# show window
if not self.win.visible:
self.win.show()
# register for updates
if self not in gdata.updateDlgs:
gdata.updateDlgs.append(self)
def hide(self):
self.win.setStatus(_("Ready."))
self.win.hide()
# unregister updates
if self in gdata.updateDlgs:
gdata.updateDlgs.remove(self)
def update(self):
if self.win.visible:
self.show()
def _processResearchableTech(self, tech):
player = client.getPlayer()
item = ui.Item(tech.name, tLevel=tech.level, techID=tech.id)
item.tStruct = '*' if getattr(tech, 'isStructure', None) else ''
item.tShip = '*' if getattr(tech, 'isShipEquip', None) else ''
neededSci = Utils.getTechRCost(player, tech.id)
item.tETC = res.formatTime(float(neededSci) / player.effSciPoints) if player.effSciPoints > 0 else _("N/A")
item.foreground = None
if client.getFullTechInfo(tech.id).finishResearchHandler == TechHandlers.finishResTLAdvance:
item.foreground = gdata.sevColors[gdata.CRI]
elif getattr(tech, "researchDisables", None):
item.foreground = (0xff, 0xff, 0x00)
return item
def _processResearchable(self, disabled, queued):
player = client.getPlayer()
items = []
for techID in client.getAllTechIDs():
if techID in player.techs or techID in queued or techID in disabled:
continue
tech = client.getTechInfo(techID)
if not hasattr(tech, 'partialData') or not hasattr(tech, 'researchMod'):
continue
items.append(self._processResearchableTech(tech))
self.win.vRTechs.items = items
self.win.vRTechs.itemsChanged()
def _processResearchQueueTask(self, task):
player = client.getPlayer()
tech = client.getTechInfo(task.techID)
fulltech = client.getFullTechInfo(task.techID)
researchSci = Utils.getTechRCost(player, task.techID, task.improvement)
item = ui.Item(tech.name, techID=task.techID)
item.tooltipTitle = _("Details")
item.tooltip = _("Research points %d/%d, change %d pts/turn.") % (task.currSci, researchSci, task.changeSci)
item.statustip = item.tooltip
item.tImpToMax = "*" if task.improveToMax else ""
item.tImproveToMax = task.improveToMax
item.tProgress = _("%d %%") % int(task.currSci * 100 / researchSci) if task.currSci > 0 else _("-")
totalSci = 0
if task.changeSci > 0:
etc = float(researchSci - task.currSci) / max(task.changeSci, player.effSciPoints)
totalSci += researchSci - task.currSci
if player.effSciPoints > 0:
item.tETC = res.formatTime(etc)
else:
item.tETC = res.getNA()
elif task.changeSci < 0:
etc = - float(task.currSci) / min(task.changeSci, player.effSciPoints)
item.tETC = _("[%s]") % res.formatTime(etc)
elif player.effSciPoints > 0:
etc = float(researchSci) / player.effSciPoints
totalSci += researchSci
item.tETC = res.formatTime(etc)
else:
item.tETC = res.getNA()
if task.improveToMax:
for impr in range(task.improvement + 1, fulltech.maxImprovement + 1):
totalSci += Utils.getTechRCost(player, task.techID, impr)
item.tLevel = _("%d-%d") % (tech.level, task.improvement)
return item, totalSci
def _processResearchQueue(self):
player = client.getPlayer()
items = []
index = 0
queued = []
totalSci = 0
for task in player.rsrchQueue:
queued.append(task.techID)
item, taskSci = self._processResearchQueueTask(task)
item.index = index
items.append(item)
totalSci += taskSci
index += 1
totalSci = math.ceil(float(totalSci) / player.effSciPoints)
self.win.vRQueue.items = items
self.win.vRQueue.itemsChanged()
self.win.vRQueueTop.enabled = 0
self.win.vRQueueUp.enabled = 0
self.win.vRQueueDown.enabled = 0
self.win.vRQueueAbort.enabled = 0
self.win.vRQueueRepat.enabled = 0
self.win.vRQueueRepat.pressed = 0
self.win.vRQueueInfo.enabled = 0
self.win.vRTotal.text = res.formatTime(totalSci) if totalSci else _("N/A")
return queued
def _processImprovableTech(self, tech, scheduledIDs):
player = client.getPlayer()
item = ui.Item(tech.name,
techID=tech.id,
tLevel='%d-%d' % (tech.level, player.techs[tech.id]),
tStruct=(' ', '*')[tech.isStructure],
tShip=(' ', '*')[tech.isShipEquip])
neededSci = Utils.getTechRCost(player, tech.id)
item.tETC = res.formatTime(float(neededSci) / player.effSciPoints) if player.effSciPoints > 0 else _("N/A")
item.foreground = (0xd0, 0xd0, 0xd0) if tech.id in scheduledIDs else None
item.foreground = (0x80, 0x40, 0x40) if tech.id in player.obsoleteTechs else item.foreground
return item
def _processKnownTech(self):
player = client.getPlayer()
items = []
disabled = []
scheduledIDs = set([task.techID for task in player.rsrchQueue])
for techID in player.techs.keys():
if techID in player.obsoleteTechs and not self.showObsolete:
continue
tech = client.getTechInfo(techID)
improvement = player.techs[techID]
if improvement == tech.maxImprovement and not self.showCompleted:
continue
items.append(self._processImprovableTech(tech, scheduledIDs))
disabled.extend(tech.researchDisables)
self.win.vKTechs.items = items
self.win.vKTechs.itemsChanged()
return disabled
def show(self):
player = client.getPlayer()
# title
self.win.vRQueueTitle.text = _('Research queue [%d pts/turn]') % (
player.effSciPoints,
)
self.win.title = _("Research [TL%d]") % player.techLevel
disabled = self._processKnownTech()
queued = self._processResearchQueue()
self._processResearchable(disabled, queued)
def onSelectKTech(self, widget, action, data):
techID = self.win.vKTechs.selection[0].techID
player = client.getPlayer()
if techID in player.obsoleteTechs:
self.win.vObs.enabled = 0
self.win.vUnObs.enabled = 1
else:
self.win.vUnObs.enabled = 0
self.win.vObs.enabled = 1
def onKTechInfo(self, widget, action, data):
if self.win.vKTechs.selection:
self.techInfoDlg.display(self.win.vKTechs.selection[0].techID)
def onSelectRTech(self, widget, action, data):
# TODO implement
pass
def onRTechInfo(self, widget, action, data):
if self.win.vRTechs.selection:
self.techInfoDlg.display(self.win.vRTechs.selection[0].techID)
def onSelectRQueueTech(self, widget, action, data):
index = self.win.vRQueue.items.index(self.win.vRQueue.selection[0])
self.win.vRQueueTop.enabled = index > 0
self.win.vRQueueUp.enabled = index > 0
self.win.vRQueueDown.enabled = index < len(self.win.vRQueue.items) - 1
self.win.vRQueueAbort.enabled = 1
self.win.vRQueueRepat.enabled = 1
self.win.vRQueueRepat.pressed = self.win.vRQueue.selection[0].tImproveToMax
self.win.vRQueueInfo.enabled = 1
def onRQueueTechInfo(self, widget, action, data):
if self.win.vRQueue.selection:
self.techInfoDlg.display(self.win.vRQueue.selection[0].techID)
def onCloseDlg(self, widget, action, data):
self.hide()
def onStartResearch(self, widget, action, data):
if not self.win.vRTechs.selection:
self.win.setStatus(_('Select technology to research.'))
return
else:
techID = self.win.vRTechs.selection[0].techID
try:
self.win.setStatus(_('Executing START RESEARCH command...'))
player = client.getPlayer()
player.rsrchQueue = client.cmdProxy.startResearch(player.oid, techID)
self.win.setStatus(_('Command has been executed.'))
except ige.GameException, e:
self.win.setStatus(e.args[0])
return
self.update()
def onStartImprovement(self, widget, action, data):
if not self.win.vKTechs.selection:
self.win.setStatus(_('Select technology to improve.'))
return
else:
techID = self.win.vKTechs.selection[0].techID
try:
self.win.setStatus(_('Executing START RESEARCH command...'))
player = client.getPlayer()
player.rsrchQueue = client.cmdProxy.startResearch(player.oid, techID)
self.win.setStatus(_('Command has been executed.'))
except ige.GameException, e:
self.win.setStatus(e.args[0])
return
self.update()
def onRTaskMove(self, widget, action, data):
self.win.setStatus(_('Executing MOVE RESEARCH command...'))
player = client.getPlayer()
index = self.win.vRQueue.items.index(self.win.vRQueue.selection[0])
# fix -9999 (move to top)
amount = widget.data
if index + amount < 0: amount = - index
# execute command
player.rsrchQueue = client.cmdProxy.moveResearch(player.oid, index, amount)
self.update()
index += amount
self.win.vRQueue.selectItem(self.win.vRQueue.items[index])
self.win.setStatus(_('Command has been executed.'))
self.onSelectRQueueTech(widget, action, None)
def onRTaskRepeat(self, widget, action, data):
self.win.setStatus(_('Executing EDIT RESEARCH command...'))
player = client.getPlayer()
index = self.win.vRQueue.items.index(self.win.vRQueue.selection[0])
repeat = not self.win.vRQueue.selection[0].tImproveToMax
# execute command
player.rsrchQueue = client.cmdProxy.editResearch(player.oid, index, repeat)
self.update()
self.win.vRQueue.selectItem(self.win.vRQueue.items[index])
self.win.setStatus(_('Command has been executed.'))
self.onSelectRQueueTech(widget, action, None)
def onToggleCompleted(self, widget, action, data):
self.showCompleted = self.win.vSCompl.pressed
self.update()
def onRTaskAbort(self, widget, action, data):
self.confirmDlg.display(_("Abort this research task?"),
_("Yes"), _("No"), self.onRTaskAbortConfirmed)
def onRTaskAbortConfirmed(self):
self.win.setStatus(_('Executing ABORT RESEARCH command...'))
player = client.getPlayer()
index = self.win.vRQueue.items.index(self.win.vRQueue.selection[0])
player.rsrchQueue = client.cmdProxy.abortResearch(player.oid, index)
self.update()
self.win.setStatus(_('Command has been executed.'))
def onSetObsolete(self, widget, action, data):
if not self.win.vKTechs.selection:
self.win.setStatus(_('Select technology to obsolete.'))
return
else:
techID = self.win.vKTechs.selection[0].techID
try:
self.win.setStatus(_('Executing OBSOLETTE command...'))
player = client.getPlayer()
player.obsoleteTechs = client.cmdProxy.addObsoleteTechs(player.oid, techID)
self.win.setStatus(_('Command has been executed.'))
except ige.GameException, e:
self.win.setStatus(e.args[0])
return
self.update()
def onUnsetObsolete(self, widget, action, data):
if not self.win.vKTechs.selection:
self.win.setStatus(_('Select technology to un-obsolete.'))
return
else:
techID = self.win.vKTechs.selection[0].techID
try:
self.win.setStatus(_('Executing UN-OBSOLETTE command...'))
player = client.getPlayer()
player.obsoleteTechs = client.cmdProxy.delObsoleteTechs(player.oid, techID)
self.win.setStatus(_('Command has been executed.'))
except ige.GameException, e:
self.win.setStatus(e.args[0])
return
self.update()
def onToggleObsolete(self, widget, action, data):
self.showObsolete = self.win.vSObsl.pressed
self.update()
def createUI(self):
w, h = gdata.scrnSize
self.win = ui.Window(self.app,
modal=1,
escKeyClose=1,
titleOnly=w == 800 and h == 600,
movable=0,
title=_('Research'),
rect=ui.Rect((w - 800 - 4 * (w != 800)) / 2, (h - 600 - 4 * (h != 600)) / 2, 800 + 4 * (w != 800), 580 + 4 * (h != 600)),
layoutManager=ui.SimpleGridLM(),
)
self.win.subscribeAction('*', self)
ui.Title(self.win, layout=(0, 27, 35, 1), id='vStatusBar',
align=ui.ALIGN_W)
ui.TitleButton(self.win, layout=(35, 27, 5, 1), text=_('Close'),
action='onCloseDlg')
# known techs
ui.Title(self.win, layout=(0, 0, 20, 1), text=_('Known technologies'),
align=ui.ALIGN_W, font='normal-bold')
ui.Listbox(self.win, layout=(0, 1, 20, 24), id='vKTechs',
columns=((_('Name'), 'text', 10, ui.ALIGN_W), (_('Lvl'), 'tLevel', 1.5, 0),
(_('Str'), 'tStruct', 1, 0), (_('Sh'), 'tShip', 1, 0),
(_('ETC'), 'tETC', 0, ui.ALIGN_E)), columnLabels=1, action='onSelectKTech')
ui.Button(self.win, layout=(0, 25, 5, 1), text=_('Improve'),
action='onStartImprovement')
ui.Button(self.win, layout=(5, 25, 5, 1), id="vSCompl", text=_('Show completed'),
action='onToggleCompleted', toggle=1, pressed=0)
ui.Button(self.win, layout=(15, 25, 5, 1), text=_('Info'),
action='onKTechInfo')
ui.Button(self.win, layout=(0, 26, 5, 1), id='vUnObs', text=_('Un-Obsolete'),
action='onUnsetObsolete')
ui.Button(self.win, layout=(0, 26, 5, 1), id='vObs', text=_('Obsolete'),
action='onSetObsolete')
ui.Button(self.win, layout=(5, 26, 5, 1), id="vSObsl", text=_('Show obsolete'),
action='onToggleObsolete', toggle=1, pressed=0)
# unknown techs
ui.Title(self.win, layout=(20, 0, 20, 1), text=_('Researchable technologies'),
align=ui.ALIGN_W, font='normal-bold')
ui.Listbox(self.win, layout=(20, 1, 20, 12), id='vRTechs',
columns=((_('Name'), 'text', 10, ui.ALIGN_W), (_('Lvl'), 'tLevel', 1.5, 0),
(_('Str'), 'tStruct', 1, 0), (_('Sh'), 'tShip', 1, 0),
(_('ETC'), 'tETC', 0, ui.ALIGN_E)), columnLabels=1, action='onSelectRTech')
ui.Button(self.win, layout=(20, 13, 5, 1), text=_('Research'),
action='onStartResearch')
ui.Button(self.win, layout=(35, 13, 5, 1), text=_('Info'),
action='onRTechInfo')
# research queue
ui.Title(self.win, layout=(20, 14, 20, 1), text=_('Research queue'),
align=ui.ALIGN_W, id='vRQueueTitle', font='normal-bold')
ui.Listbox(self.win, layout=(20, 15, 20, 11), id='vRQueue',
columns=((_('R'), 'tImpToMax', 1, ui.ALIGN_NONE),
(_('Name'), 'text', 10, ui.ALIGN_W),
(_('Lvl'), 'tLevel', 1.5, 0),
(_('Progress'), 'tProgress', 3.5, ui.ALIGN_E),
(_('ETC'), 'tETC', 0, ui.ALIGN_E)),
columnLabels=1, action='onSelectRQueueTech', sortable=False)
ui.Button(self.win, layout=(20, 26, 2, 1), text=_("TOP"),
id='vRQueueTop', action='onRTaskMove', data=-9999,
tooltip=_("Move selected technology to the top of the queue."))
ui.ArrowButton(self.win, layout=(22, 26, 1, 1), direction=ui.ALIGN_N,
id='vRQueueUp', action='onRTaskMove', data=-1)
ui.ArrowButton(self.win, layout=(23, 26, 1, 1), direction=ui.ALIGN_S,
id='vRQueueDown', action='onRTaskMove', data=1)
ui.Button(self.win, layout=(24, 26, 4, 1), text=_('Repeat'),
id='vRQueueRepat', action='onRTaskRepeat', toggle=1,
tooltip=_("Repeat research of this technology until the technology is fully improved."))
ui.Button(self.win, layout=(28, 26, 3, 1), text=_('Abort'),
id='vRQueueAbort', action='onRTaskAbort')
ui.Button(self.win, layout=(31, 26, 4, 1), text=_('Info'),
id='vRQueueInfo', action='onRQueueTechInfo')
ui.Label(self.win, layout=(35, 26, 4, 1), id="vRTotal", align=ui.ALIGN_E,
tooltip=_("Total amount of time needed to research all technologies in the queue"))
| gpl-2.0 |
wmvanvliet/mne-python | mne/io/diff.py | 14 | 1219 | # Author: Alexandre Gramfort <alexandre.gramfort@inria.fr>
#
# License: BSD Style.
import numpy as np
from ..utils import logger, verbose
@verbose
def is_equal(first, second, verbose=None):
"""Check if 2 python structures are the same.
Designed to handle dict, list, np.ndarray etc.
"""
all_equal = True
# Check all keys in first dict
if type(first) != type(second):
all_equal = False
if isinstance(first, dict):
for key in first.keys():
if (key not in second):
logger.info("Missing key %s in %s" % (key, second))
all_equal = False
else:
if not is_equal(first[key], second[key]):
all_equal = False
elif isinstance(first, np.ndarray):
if not np.allclose(first, second):
all_equal = False
elif isinstance(first, list):
for a, b in zip(first, second):
if not is_equal(a, b):
logger.info('%s and\n%s are different' % (a, b))
all_equal = False
else:
if first != second:
logger.info('%s and\n%s are different' % (first, second))
all_equal = False
return all_equal
| bsd-3-clause |
bthirion/scikit-learn | examples/gaussian_process/plot_gpc.py | 103 | 3927 | """
====================================================================
Probabilistic predictions with Gaussian process classification (GPC)
====================================================================
This example illustrates the predicted probability of GPC for an RBF kernel
with different choices of the hyperparameters. The first figure shows the
predicted probability of GPC with arbitrarily chosen hyperparameters and with
the hyperparameters corresponding to the maximum log-marginal-likelihood (LML).
While the hyperparameters chosen by optimizing LML have a considerable larger
LML, they perform slightly worse according to the log-loss on test data. The
figure shows that this is because they exhibit a steep change of the class
probabilities at the class boundaries (which is good) but have predicted
probabilities close to 0.5 far away from the class boundaries (which is bad)
This undesirable effect is caused by the Laplace approximation used
internally by GPC.
The second figure shows the log-marginal-likelihood for different choices of
the kernel's hyperparameters, highlighting the two choices of the
hyperparameters used in the first figure by black dots.
"""
print(__doc__)
# Authors: Jan Hendrik Metzen <jhm@informatik.uni-bremen.de>
#
# License: BSD 3 clause
import numpy as np
from matplotlib import pyplot as plt
from sklearn.metrics.classification import accuracy_score, log_loss
from sklearn.gaussian_process import GaussianProcessClassifier
from sklearn.gaussian_process.kernels import RBF
# Generate data
train_size = 50
rng = np.random.RandomState(0)
X = rng.uniform(0, 5, 100)[:, np.newaxis]
y = np.array(X[:, 0] > 2.5, dtype=int)
# Specify Gaussian Processes with fixed and optimized hyperparameters
gp_fix = GaussianProcessClassifier(kernel=1.0 * RBF(length_scale=1.0),
optimizer=None)
gp_fix.fit(X[:train_size], y[:train_size])
gp_opt = GaussianProcessClassifier(kernel=1.0 * RBF(length_scale=1.0))
gp_opt.fit(X[:train_size], y[:train_size])
print("Log Marginal Likelihood (initial): %.3f"
% gp_fix.log_marginal_likelihood(gp_fix.kernel_.theta))
print("Log Marginal Likelihood (optimized): %.3f"
% gp_opt.log_marginal_likelihood(gp_opt.kernel_.theta))
print("Accuracy: %.3f (initial) %.3f (optimized)"
% (accuracy_score(y[:train_size], gp_fix.predict(X[:train_size])),
accuracy_score(y[:train_size], gp_opt.predict(X[:train_size]))))
print("Log-loss: %.3f (initial) %.3f (optimized)"
% (log_loss(y[:train_size], gp_fix.predict_proba(X[:train_size])[:, 1]),
log_loss(y[:train_size], gp_opt.predict_proba(X[:train_size])[:, 1])))
# Plot posteriors
plt.figure(0)
plt.scatter(X[:train_size, 0], y[:train_size], c='k', label="Train data")
plt.scatter(X[train_size:, 0], y[train_size:], c='g', label="Test data")
X_ = np.linspace(0, 5, 100)
plt.plot(X_, gp_fix.predict_proba(X_[:, np.newaxis])[:, 1], 'r',
label="Initial kernel: %s" % gp_fix.kernel_)
plt.plot(X_, gp_opt.predict_proba(X_[:, np.newaxis])[:, 1], 'b',
label="Optimized kernel: %s" % gp_opt.kernel_)
plt.xlabel("Feature")
plt.ylabel("Class 1 probability")
plt.xlim(0, 5)
plt.ylim(-0.25, 1.5)
plt.legend(loc="best")
# Plot LML landscape
plt.figure(1)
theta0 = np.logspace(0, 8, 30)
theta1 = np.logspace(-1, 1, 29)
Theta0, Theta1 = np.meshgrid(theta0, theta1)
LML = [[gp_opt.log_marginal_likelihood(np.log([Theta0[i, j], Theta1[i, j]]))
for i in range(Theta0.shape[0])] for j in range(Theta0.shape[1])]
LML = np.array(LML).T
plt.plot(np.exp(gp_fix.kernel_.theta)[0], np.exp(gp_fix.kernel_.theta)[1],
'ko', zorder=10)
plt.plot(np.exp(gp_opt.kernel_.theta)[0], np.exp(gp_opt.kernel_.theta)[1],
'ko', zorder=10)
plt.pcolor(Theta0, Theta1, LML)
plt.xscale("log")
plt.yscale("log")
plt.colorbar()
plt.xlabel("Magnitude")
plt.ylabel("Length-scale")
plt.title("Log-marginal-likelihood")
plt.show()
| bsd-3-clause |
vmindru/ansible | lib/ansible/plugins/httpapi/fortimanager.py | 42 | 13169 | # Copyright (c) 2018 Fortinet and/or its affiliates.
#
# 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/>.
#
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = """
---
author:
- Luke Weighall (@lweighall)
- Andrew Welsh (@Ghilli3)
- Jim Huber (@p4r4n0y1ng)
httpapi : fortimanager
short_description: HttpApi Plugin for Fortinet FortiManager Appliance or VM
description:
- This HttpApi plugin provides methods to connect to Fortinet FortiManager Appliance or VM via JSON RPC API
version_added: "2.8"
"""
import json
from ansible.plugins.httpapi import HttpApiBase
from ansible.module_utils.basic import to_text
from ansible.module_utils.network.fortimanager.common import BASE_HEADERS
from ansible.module_utils.network.fortimanager.common import FMGBaseException
from ansible.module_utils.network.fortimanager.common import FMGRCommon
from ansible.module_utils.network.fortimanager.common import FMGRMethods
class HttpApi(HttpApiBase):
def __init__(self, connection):
super(HttpApi, self).__init__(connection)
self._req_id = 0
self._sid = None
self._url = "/jsonrpc"
self._host = None
self._tools = FMGRCommon
self._debug = False
self._connected_fmgr = None
self._last_response_msg = None
self._last_response_code = None
self._last_data_payload = None
self._last_url = None
self._last_response_raw = None
self._locked_adom_list = list()
self._uses_workspace = False
self._uses_adoms = False
def set_become(self, become_context):
"""
ELEVATION IS NOT REQUIRED ON FORTINET DEVICES - SKIPPED
:param become_context: Unused input.
:return: None
"""
return None
def update_auth(self, response, response_data):
"""
TOKENS ARE NOT USED SO NO NEED TO UPDATE AUTH
:param response: Unused input.
:param response_data Unused_input.
:return: None
"""
return None
def login(self, username, password):
"""
This function will log the plugin into FortiManager, and return the results.
:param username: Username of FortiManager Admin
:param password: Password of FortiManager Admin
:return: Dictionary of status, if it logged in or not.
"""
self.send_request(FMGRMethods.EXEC, self._tools.format_request(FMGRMethods.EXEC, "sys/login/user",
passwd=password, user=username,))
if "FortiManager object connected to FortiManager" in self.__str__():
# If Login worked, then inspect the FortiManager for Workspace Mode, and it's system information.
self.inspect_fmgr()
return
else:
raise FMGBaseException(msg="Unknown error while logging in...connection was lost during login operation...."
" Exiting")
def inspect_fmgr(self):
# CHECK FOR WORKSPACE MODE TO SEE IF WE HAVE TO ENABLE ADOM LOCKS
self.check_mode()
# CHECK FOR SYSTEM STATUS -- SHOULD RETURN 0
status = self.get_system_status()
if status[0] == -11:
# THE CONNECTION GOT LOST SOMEHOW, REMOVE THE SID AND REPORT BAD LOGIN
self.logout()
raise FMGBaseException(msg="Error -11 -- the Session ID was likely malformed somehow. Contact authors."
" Exiting")
elif status[0] == 0:
try:
self._connected_fmgr = status[1]
self._host = self._connected_fmgr["Hostname"]
except BaseException:
pass
return
def logout(self):
"""
This function will logout of the FortiManager.
"""
if self.sid is not None:
if self.uses_workspace:
self.run_unlock()
ret_code, response = self.send_request(FMGRMethods.EXEC,
self._tools.format_request(FMGRMethods.EXEC, "sys/logout"))
self.sid = None
return ret_code, response
def send_request(self, method, params):
"""
Responsible for actual sending of data to the connection httpapi base plugin. Does some formatting as well.
:param params: A formatted dictionary that was returned by self.common_datagram_params()
before being called here.
:param method: The preferred API Request method (GET, ADD, POST, etc....)
:type method: basestring
:return: Dictionary of status, if it logged in or not.
"""
try:
if self.sid is None and params[0]["url"] != "sys/login/user":
raise FMGBaseException("An attempt was made to login with the SID None and URL != login url.")
except IndexError:
raise FMGBaseException("An attempt was made at communicating with a FMG with "
"no valid session and an incorrectly formatted request.")
except Exception:
raise FMGBaseException("An attempt was made at communicating with a FMG with "
"no valid session and an unexpected error was discovered.")
self._update_request_id()
json_request = {
"method": method,
"params": params,
"session": self.sid,
"id": self.req_id,
"verbose": 1
}
data = json.dumps(json_request, ensure_ascii=False).replace('\\\\', '\\')
try:
# Sending URL and Data in Unicode, per Ansible Specifications for Connection Plugins
response, response_data = self.connection.send(path=to_text(self._url), data=to_text(data),
headers=BASE_HEADERS)
# Get Unicode Response - Must convert from StringIO to unicode first so we can do a replace function below
result = json.loads(to_text(response_data.getvalue()))
self._update_self_from_response(result, self._url, data)
return self._handle_response(result)
except Exception as err:
raise FMGBaseException(err)
def _handle_response(self, response):
self._set_sid(response)
if isinstance(response["result"], list):
result = response["result"][0]
else:
result = response["result"]
if "data" in result:
return result["status"]["code"], result["data"]
else:
return result["status"]["code"], result
def _update_self_from_response(self, response, url, data):
self._last_response_raw = response
if isinstance(response["result"], list):
result = response["result"][0]
else:
result = response["result"]
if "status" in result:
self._last_response_code = result["status"]["code"]
self._last_response_msg = result["status"]["message"]
self._last_url = url
self._last_data_payload = data
def _set_sid(self, response):
if self.sid is None and "session" in response:
self.sid = response["session"]
def return_connected_fmgr(self):
"""
Returns the data stored under self._connected_fmgr
:return: dict
"""
try:
if self._connected_fmgr:
return self._connected_fmgr
except BaseException:
raise FMGBaseException("Couldn't Retrieve Connected FMGR Stats")
def get_system_status(self):
"""
Returns the system status page from the FortiManager, for logging and other uses.
return: status
"""
status = self.send_request(FMGRMethods.GET, self._tools.format_request(FMGRMethods.GET, "sys/status"))
return status
@property
def debug(self):
return self._debug
@debug.setter
def debug(self, val):
self._debug = val
@property
def req_id(self):
return self._req_id
@req_id.setter
def req_id(self, val):
self._req_id = val
def _update_request_id(self, reqid=0):
self.req_id = reqid if reqid != 0 else self.req_id + 1
@property
def sid(self):
return self._sid
@sid.setter
def sid(self, val):
self._sid = val
def __str__(self):
if self.sid is not None and self.connection._url is not None:
return "FortiManager object connected to FortiManager: " + str(self.connection._url)
return "FortiManager object with no valid connection to a FortiManager appliance."
##################################
# BEGIN DATABASE LOCK CONTEXT CODE
##################################
@property
def uses_workspace(self):
return self._uses_workspace
@uses_workspace.setter
def uses_workspace(self, val):
self._uses_workspace = val
@property
def uses_adoms(self):
return self._uses_adoms
@uses_adoms.setter
def uses_adoms(self, val):
self._uses_adoms = val
def add_adom_to_lock_list(self, adom):
if adom not in self._locked_adom_list:
self._locked_adom_list.append(adom)
def remove_adom_from_lock_list(self, adom):
if adom in self._locked_adom_list:
self._locked_adom_list.remove(adom)
def check_mode(self):
"""
Checks FortiManager for the use of Workspace mode
"""
url = "/cli/global/system/global"
code, resp_obj = self.send_request(FMGRMethods.GET, self._tools.format_request(FMGRMethods.GET, url,
fields=["workspace-mode",
"adom-status"]))
try:
if resp_obj["workspace-mode"] != 0:
self.uses_workspace = True
except KeyError:
self.uses_workspace = False
try:
if resp_obj["adom-status"] == 1:
self.uses_adoms = True
except KeyError:
self.uses_adoms = False
def run_unlock(self):
"""
Checks for ADOM status, if locked, it will unlock
"""
for adom_locked in self._locked_adom_list:
self.unlock_adom(adom_locked)
def lock_adom(self, adom=None, *args, **kwargs):
"""
Locks an ADOM for changes
"""
if adom:
if adom.lower() == "global":
url = "/dvmdb/global/workspace/lock/"
else:
url = "/dvmdb/adom/{adom}/workspace/lock/".format(adom=adom)
else:
url = "/dvmdb/adom/root/workspace/lock"
code, respobj = self.send_request(FMGRMethods.EXEC, self._tools.format_request(FMGRMethods.EXEC, url))
if code == 0 and respobj["status"]["message"].lower() == "ok":
self.add_adom_to_lock_list(adom)
return code, respobj
def unlock_adom(self, adom=None, *args, **kwargs):
"""
Unlocks an ADOM after changes
"""
if adom:
if adom.lower() == "global":
url = "/dvmdb/global/workspace/unlock/"
else:
url = "/dvmdb/adom/{adom}/workspace/unlock/".format(adom=adom)
else:
url = "/dvmdb/adom/root/workspace/unlock"
code, respobj = self.send_request(FMGRMethods.EXEC, self._tools.format_request(FMGRMethods.EXEC, url))
if code == 0 and respobj["status"]["message"].lower() == "ok":
self.remove_adom_from_lock_list(adom)
return code, respobj
def commit_changes(self, adom=None, aux=False, *args, **kwargs):
"""
Commits changes to an ADOM
"""
if adom:
if aux:
url = "/pm/config/adom/{adom}/workspace/commit".format(adom=adom)
else:
if adom.lower() == "global":
url = "/dvmdb/global/workspace/commit/"
else:
url = "/dvmdb/adom/{adom}/workspace/commit".format(adom=adom)
else:
url = "/dvmdb/adom/root/workspace/commit"
return self.send_request(FMGRMethods.EXEC, self._tools.format_request(FMGRMethods.EXEC, url))
################################
# END DATABASE LOCK CONTEXT CODE
################################
| gpl-3.0 |
machinecoin-project/machinecoin | test/util/machinecoin-util-test.py | 2 | 6744 | #!/usr/bin/env python3
# Copyright 2014 BitPay Inc.
# Copyright 2016-2017 The Machinecoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test framework for machinecoin utils.
Runs automatically during `make check`.
Can also be run manually."""
from __future__ import division,print_function,unicode_literals
import argparse
import binascii
try:
import configparser
except ImportError:
import ConfigParser as configparser
import difflib
import json
import logging
import os
import pprint
import subprocess
import sys
def main():
config = configparser.ConfigParser()
config.optionxform = str
config.readfp(open(os.path.join(os.path.dirname(__file__), "../config.ini"), encoding="utf8"))
env_conf = dict(config.items('environment'))
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('-v', '--verbose', action='store_true')
args = parser.parse_args()
verbose = args.verbose
if verbose:
level = logging.DEBUG
else:
level = logging.ERROR
formatter = '%(asctime)s - %(levelname)s - %(message)s'
# Add the format/level to the logger
logging.basicConfig(format=formatter, level=level)
bctester(os.path.join(env_conf["SRCDIR"], "test", "util", "data"), "machinecoin-util-test.json", env_conf)
def bctester(testDir, input_basename, buildenv):
""" Loads and parses the input file, runs all tests and reports results"""
input_filename = os.path.join(testDir, input_basename)
raw_data = open(input_filename, encoding="utf8").read()
input_data = json.loads(raw_data)
failed_testcases = []
for testObj in input_data:
try:
bctest(testDir, testObj, buildenv)
logging.info("PASSED: " + testObj["description"])
except:
logging.info("FAILED: " + testObj["description"])
failed_testcases.append(testObj["description"])
if failed_testcases:
error_message = "FAILED_TESTCASES:\n"
error_message += pprint.pformat(failed_testcases, width=400)
logging.error(error_message)
sys.exit(1)
else:
sys.exit(0)
def bctest(testDir, testObj, buildenv):
"""Runs a single test, comparing output and RC to expected output and RC.
Raises an error if input can't be read, executable fails, or output/RC
are not as expected. Error is caught by bctester() and reported.
"""
# Get the exec names and arguments
execprog = os.path.join(buildenv["BUILDDIR"], "src", testObj["exec"] + buildenv["EXEEXT"])
execargs = testObj['args']
execrun = [execprog] + execargs
# Read the input data (if there is any)
stdinCfg = None
inputData = None
if "input" in testObj:
filename = os.path.join(testDir, testObj["input"])
inputData = open(filename, encoding="utf8").read()
stdinCfg = subprocess.PIPE
# Read the expected output data (if there is any)
outputFn = None
outputData = None
outputType = None
if "output_cmp" in testObj:
outputFn = testObj['output_cmp']
outputType = os.path.splitext(outputFn)[1][1:] # output type from file extension (determines how to compare)
try:
outputData = open(os.path.join(testDir, outputFn), encoding="utf8").read()
except:
logging.error("Output file " + outputFn + " can not be opened")
raise
if not outputData:
logging.error("Output data missing for " + outputFn)
raise Exception
if not outputType:
logging.error("Output file %s does not have a file extension" % outputFn)
raise Exception
# Run the test
proc = subprocess.Popen(execrun, stdin=stdinCfg, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
try:
outs = proc.communicate(input=inputData)
except OSError:
logging.error("OSError, Failed to execute " + execprog)
raise
if outputData:
data_mismatch, formatting_mismatch = False, False
# Parse command output and expected output
try:
a_parsed = parse_output(outs[0], outputType)
except Exception as e:
logging.error('Error parsing command output as %s: %s' % (outputType, e))
raise
try:
b_parsed = parse_output(outputData, outputType)
except Exception as e:
logging.error('Error parsing expected output %s as %s: %s' % (outputFn, outputType, e))
raise
# Compare data
if a_parsed != b_parsed:
logging.error("Output data mismatch for " + outputFn + " (format " + outputType + ")")
data_mismatch = True
# Compare formatting
if outs[0] != outputData:
error_message = "Output formatting mismatch for " + outputFn + ":\n"
error_message += "".join(difflib.context_diff(outputData.splitlines(True),
outs[0].splitlines(True),
fromfile=outputFn,
tofile="returned"))
logging.error(error_message)
formatting_mismatch = True
assert not data_mismatch and not formatting_mismatch
# Compare the return code to the expected return code
wantRC = 0
if "return_code" in testObj:
wantRC = testObj['return_code']
if proc.returncode != wantRC:
logging.error("Return code mismatch for " + outputFn)
raise Exception
if "error_txt" in testObj:
want_error = testObj["error_txt"]
# Compare error text
# TODO: ideally, we'd compare the strings exactly and also assert
# That stderr is empty if no errors are expected. However, machinecoin-tx
# emits DISPLAY errors when running as a windows application on
# linux through wine. Just assert that the expected error text appears
# somewhere in stderr.
if want_error not in outs[1]:
logging.error("Error mismatch:\n" + "Expected: " + want_error + "\nReceived: " + outs[1].rstrip())
raise Exception
def parse_output(a, fmt):
"""Parse the output according to specified format.
Raise an error if the output can't be parsed."""
if fmt == 'json': # json: compare parsed data
return json.loads(a)
elif fmt == 'hex': # hex: parse and compare binary data
return binascii.a2b_hex(a.strip())
else:
raise NotImplementedError("Don't know how to compare %s" % fmt)
if __name__ == '__main__':
main()
| mit |
nhippenmeyer/django | django/conf/locale/nl/formats.py | 504 | 4472 | # -*- encoding: utf-8 -*-
# This file is distributed under the same license as the Django package.
#
from __future__ import unicode_literals
# The *_FORMAT strings use the Django date format syntax,
# see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATE_FORMAT = 'j F Y' # '20 januari 2009'
TIME_FORMAT = 'H:i' # '15:23'
DATETIME_FORMAT = 'j F Y H:i' # '20 januari 2009 15:23'
YEAR_MONTH_FORMAT = 'F Y' # 'januari 2009'
MONTH_DAY_FORMAT = 'j F' # '20 januari'
SHORT_DATE_FORMAT = 'j-n-Y' # '20-1-2009'
SHORT_DATETIME_FORMAT = 'j-n-Y H:i' # '20-1-2009 15:23'
FIRST_DAY_OF_WEEK = 1 # Monday (in Dutch 'maandag')
# The *_INPUT_FORMATS strings use the Python strftime format syntax,
# see http://docs.python.org/library/datetime.html#strftime-strptime-behavior
DATE_INPUT_FORMATS = [
'%d-%m-%Y', '%d-%m-%y', # '20-01-2009', '20-01-09'
'%d/%m/%Y', '%d/%m/%y', # '20/01/2009', '20/01/09'
# '%d %b %Y', '%d %b %y', # '20 jan 2009', '20 jan 09'
# '%d %B %Y', '%d %B %y', # '20 januari 2009', '20 januari 09'
]
# Kept ISO formats as one is in first position
TIME_INPUT_FORMATS = [
'%H:%M:%S', # '15:23:35'
'%H:%M:%S.%f', # '15:23:35.000200'
'%H.%M:%S', # '15.23:35'
'%H.%M:%S.%f', # '15.23:35.000200'
'%H.%M', # '15.23'
'%H:%M', # '15:23'
]
DATETIME_INPUT_FORMATS = [
# With time in %H:%M:%S :
'%d-%m-%Y %H:%M:%S', '%d-%m-%y %H:%M:%S', '%Y-%m-%d %H:%M:%S',
# '20-01-2009 15:23:35', '20-01-09 15:23:35', '2009-01-20 15:23:35'
'%d/%m/%Y %H:%M:%S', '%d/%m/%y %H:%M:%S', '%Y/%m/%d %H:%M:%S',
# '20/01/2009 15:23:35', '20/01/09 15:23:35', '2009/01/20 15:23:35'
# '%d %b %Y %H:%M:%S', '%d %b %y %H:%M:%S', # '20 jan 2009 15:23:35', '20 jan 09 15:23:35'
# '%d %B %Y %H:%M:%S', '%d %B %y %H:%M:%S', # '20 januari 2009 15:23:35', '20 januari 2009 15:23:35'
# With time in %H:%M:%S.%f :
'%d-%m-%Y %H:%M:%S.%f', '%d-%m-%y %H:%M:%S.%f', '%Y-%m-%d %H:%M:%S.%f',
# '20-01-2009 15:23:35.000200', '20-01-09 15:23:35.000200', '2009-01-20 15:23:35.000200'
'%d/%m/%Y %H:%M:%S.%f', '%d/%m/%y %H:%M:%S.%f', '%Y/%m/%d %H:%M:%S.%f',
# '20/01/2009 15:23:35.000200', '20/01/09 15:23:35.000200', '2009/01/20 15:23:35.000200'
# With time in %H.%M:%S :
'%d-%m-%Y %H.%M:%S', '%d-%m-%y %H.%M:%S', # '20-01-2009 15.23:35', '20-01-09 15.23:35'
'%d/%m/%Y %H.%M:%S', '%d/%m/%y %H.%M:%S', # '20/01/2009 15.23:35', '20/01/09 15.23:35'
# '%d %b %Y %H.%M:%S', '%d %b %y %H.%M:%S', # '20 jan 2009 15.23:35', '20 jan 09 15.23:35'
# '%d %B %Y %H.%M:%S', '%d %B %y %H.%M:%S', # '20 januari 2009 15.23:35', '20 januari 2009 15.23:35'
# With time in %H.%M:%S.%f :
'%d-%m-%Y %H.%M:%S.%f', '%d-%m-%y %H.%M:%S.%f', # '20-01-2009 15.23:35.000200', '20-01-09 15.23:35.000200'
'%d/%m/%Y %H.%M:%S.%f', '%d/%m/%y %H.%M:%S.%f', # '20/01/2009 15.23:35.000200', '20/01/09 15.23:35.000200'
# With time in %H:%M :
'%d-%m-%Y %H:%M', '%d-%m-%y %H:%M', '%Y-%m-%d %H:%M', # '20-01-2009 15:23', '20-01-09 15:23', '2009-01-20 15:23'
'%d/%m/%Y %H:%M', '%d/%m/%y %H:%M', '%Y/%m/%d %H:%M', # '20/01/2009 15:23', '20/01/09 15:23', '2009/01/20 15:23'
# '%d %b %Y %H:%M', '%d %b %y %H:%M', # '20 jan 2009 15:23', '20 jan 09 15:23'
# '%d %B %Y %H:%M', '%d %B %y %H:%M', # '20 januari 2009 15:23', '20 januari 2009 15:23'
# With time in %H.%M :
'%d-%m-%Y %H.%M', '%d-%m-%y %H.%M', # '20-01-2009 15.23', '20-01-09 15.23'
'%d/%m/%Y %H.%M', '%d/%m/%y %H.%M', # '20/01/2009 15.23', '20/01/09 15.23'
# '%d %b %Y %H.%M', '%d %b %y %H.%M', # '20 jan 2009 15.23', '20 jan 09 15.23'
# '%d %B %Y %H.%M', '%d %B %y %H.%M', # '20 januari 2009 15.23', '20 januari 2009 15.23'
# Without time :
'%d-%m-%Y', '%d-%m-%y', '%Y-%m-%d', # '20-01-2009', '20-01-09', '2009-01-20'
'%d/%m/%Y', '%d/%m/%y', '%Y/%m/%d', # '20/01/2009', '20/01/09', '2009/01/20'
# '%d %b %Y', '%d %b %y', # '20 jan 2009', '20 jan 09'
# '%d %B %Y', '%d %B %y', # '20 januari 2009', '20 januari 2009'
]
DECIMAL_SEPARATOR = ','
THOUSAND_SEPARATOR = '.'
NUMBER_GROUPING = 3
| bsd-3-clause |
qwertyjune/BethSaidaBible | venv/lib/python2.7/site-packages/pip/_vendor/requests/packages/chardet/euckrprober.py | 2931 | 1675 | ######################## BEGIN LICENSE BLOCK ########################
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 1998
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Mark Pilgrim - port to Python
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA
######################### END LICENSE BLOCK #########################
from .mbcharsetprober import MultiByteCharSetProber
from .codingstatemachine import CodingStateMachine
from .chardistribution import EUCKRDistributionAnalysis
from .mbcssm import EUCKRSMModel
class EUCKRProber(MultiByteCharSetProber):
def __init__(self):
MultiByteCharSetProber.__init__(self)
self._mCodingSM = CodingStateMachine(EUCKRSMModel)
self._mDistributionAnalyzer = EUCKRDistributionAnalysis()
self.reset()
def get_charset_name(self):
return "EUC-KR"
| gpl-3.0 |
mccredie/lostcities | lostcities/test/test_drawgameproxy.py | 1 | 2908 |
import unittest
from .. import drawgameproxy
from .. import game
from ..illeaglemoveerror import IlleagleMoveError
from . import test_gameproxybase
class MockGame:
def __init__(self):
self.draw_player = None
self.draw_from_player = None
self.draw_from_adventure = None
self.draw_from_return = None
def draw(self, player):
self.draw_player = player
def draw_from(self, player, adventure):
self.draw_from_player = player
self.draw_from_adventure = adventure
return self.draw_from_return
class StubGameRunner:
def __init__(self):
self.finish_draw_called = False
self.finish_draw_from_card = None
def finish_draw(self):
self.finish_draw_called = True
def finish_draw_from(self, card):
self.finish_draw_from_card = card
class DrawGameProxyTests(test_gameproxybase.GameProxyBaseTests):
@staticmethod
def class_under_test(g, p):
return drawgameproxy.DrawGameProxy(g, p, None)
def test_draw_calls_draw_with_player(self):
p1 = 1
g = MockGame()
r = StubGameRunner()
p = drawgameproxy.DrawGameProxy(g, p1, r)
p.draw()
self.assertEqual(p1, g.draw_player)
def test_draw_from_calls_draw_from_with_player(self):
p1 = 1
adventure = 'r'
g = MockGame()
r = StubGameRunner()
p = drawgameproxy.DrawGameProxy(g, p1, r)
p.draw_from(adventure)
self.assertEqual(p1, g.draw_from_player)
self.assertEqual(adventure, g.draw_from_adventure)
def test_draw_calls_finish_on_success(self):
p1 = 1
g = MockGame()
r = StubGameRunner()
p = drawgameproxy.DrawGameProxy(g, p1, r)
p.draw()
self.assertTrue(r.finish_draw_called)
def test_draw_from_calls_finish_with_correct_card(self):
p1 = 1
g = game.Game()
card_to_draw = suit, _ = 'r', 10
g.discards[suit].append(card_to_draw)
r = StubGameRunner()
p = drawgameproxy.DrawGameProxy(g, p1, r)
p.draw_from(suit)
self.assertEqual(card_to_draw, r.finish_draw_from_card)
def test_proxy_useless_after_draw_from(self):
p1 = 1
g = game.Game()
card_to_draw = suit, _ = 'r', 10
g.discards[suit].append(card_to_draw)
r = StubGameRunner()
p = drawgameproxy.DrawGameProxy(g, p1, r)
p.draw_from(suit)
self.assertRaises(IlleagleMoveError, p.draw)
def test_proxy_useless_after_play(self):
p1 = 1
g = game.Game()
card_to_draw = suit, _ = 'r', 10
g.deck[:] = [('g', 5)]
g.discards[suit].append(card_to_draw)
r = StubGameRunner()
p = drawgameproxy.DrawGameProxy(g, p1, r)
p.draw()
self.assertRaises(IlleagleMoveError, p.draw_from, suit)
| mit |
ejeschke/ginga | ginga/tests/test_cmap.py | 3 | 2925 | """Unit Tests for the cmap.py functions"""
import numpy as np
import pytest
import ginga.cmap
from ginga.cmap import ColorMap
class TestCmap(object):
def setup_class(self):
pass
def test_ColorMap_init(self):
test_clst = tuple([(x, x, x)
for x in np.linspace(0, 1, ginga.cmap.min_cmap_len)])
test_color_map = ColorMap('test-name', test_clst)
expected = 'test-name'
actual = test_color_map.name
assert expected == actual
expected = ginga.cmap.min_cmap_len
actual = len(test_color_map.clst)
assert expected == actual
expected = (0.0, 0.0, 0.0)
actual = test_color_map.clst[0]
assert np.allclose(expected, actual)
expected = (1.0, 1.0, 1.0)
actual = test_color_map.clst[-1]
assert np.allclose(expected, actual)
def test_ColorMap_init_exception(self):
with pytest.raises(TypeError):
ColorMap('test-name')
def test_cmaps(self):
count = 0
for attribute_name in dir(ginga.cmap):
if attribute_name.startswith('cmap_'):
count = count + 1
expected = count
actual = len(ginga.cmap.cmaps) # Can include matplotlib colormaps
assert expected <= actual
def test_add_cmap(self):
test_clst = tuple([(x, x, x)
for x in np.linspace(0, 1, ginga.cmap.min_cmap_len)])
ginga.cmap.add_cmap('test-name', test_clst)
expected = ColorMap('test-name', test_clst)
actual = ginga.cmap.cmaps['test-name']
assert expected.name == actual.name
assert expected.clst == actual.clst
# Teardown
del ginga.cmap.cmaps['test-name']
def test_add_cmap_exception(self):
test_clst = ((0.0, 0.0, 0.0), (1.0, 1.0, 1.0))
with pytest.raises(AssertionError):
ginga.cmap.add_cmap('test-name', test_clst)
def test_get_cmap(self):
test_clst = tuple([(x, x, x)
for x in np.linspace(0, 1, ginga.cmap.min_cmap_len)])
ginga.cmap.add_cmap('test-name', test_clst)
expected = ColorMap('test-name', test_clst)
actual = ginga.cmap.get_cmap('test-name')
assert expected.name == actual.name
assert expected.clst == actual.clst
# Teardown
del ginga.cmap.cmaps['test-name']
def test_get_cmap_exception(self):
with pytest.raises(KeyError):
ginga.cmap.get_cmap('non-existent-name')
def test_get_names(self):
names = []
for attribute_name in dir(ginga.cmap):
if attribute_name.startswith('cmap_'):
names.append(attribute_name[5:])
expected = set(names)
actual = set(ginga.cmap.get_names()) # Can include matplotlib names
assert expected <= actual
# TODO: Add tests for matplotlib functions
# END
| bsd-3-clause |
SteveXiSong/ECE757-SnoopingPredictions | src/python/m5/ticks.py | 57 | 3499 | # Copyright (c) 2007 The Regents of The University of Michigan
# 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 copyright holders 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.
#
# Authors: Nathan Binkert
import sys
from m5.util import warn
tps = 1.0e12 # default to 1 THz (1 Tick == 1 ps)
tps_fixed = False # once set to true, can't be changed
# fix the global frequency and tell C++ about it
def fixGlobalFrequency():
import internal
global tps, tps_fixed
if not tps_fixed:
tps_fixed = True
internal.core.setClockFrequency(int(tps))
print "Global frequency set at %d ticks per second" % int(tps)
def setGlobalFrequency(ticksPerSecond):
from m5.util import convert
global tps, tps_fixed
if tps_fixed:
raise AttributeError, \
"Global frequency already fixed at %f ticks/s." % tps
if isinstance(ticksPerSecond, (int, long)):
tps = ticksPerSecond
elif isinstance(ticksPerSecond, float):
tps = ticksPerSecond
elif isinstance(ticksPerSecond, str):
tps = round(convert.anyToFrequency(ticksPerSecond))
else:
raise TypeError, \
"wrong type '%s' for ticksPerSecond" % type(ticksPerSecond)
# how big does a rounding error need to be before we warn about it?
frequency_tolerance = 0.001 # 0.1%
def fromSeconds(value):
if not isinstance(value, float):
raise TypeError, "can't convert '%s' to type tick" % type(value)
# once someone needs to convert to seconds, the global frequency
# had better be fixed
if not tps_fixed:
raise AttributeError, \
"In order to do conversions, the global frequency must be fixed"
if value == 0:
return 0
# convert the value from time to ticks
value *= tps
int_value = int(round(value))
err = (value - int_value) / value
if err > frequency_tolerance:
warn("rounding error > tolerance\n %f rounded to %d", value,
int_value)
return int_value
__all__ = [ 'setGlobalFrequency', 'fixGlobalFrequency', 'fromSeconds',
'frequency_tolerance' ]
| bsd-3-clause |
teamtuga4/teamtuga4ever.repository | plugin.video.traquinas/resources/lib/resolvers/videopremium.py | 23 | 1858 | # -*- coding: utf-8 -*-
'''
Specto Add-on
Copyright (C) 2015 lambda
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
'''
import re,urllib,urlparse
from resources.lib.libraries import cloudflare
from resources.lib.libraries import client
def resolve(url):
try:
result = cloudflare.request(url)
post = {}
f = client.parseDOM(result, 'Form', attrs = {'action': '' })
k = client.parseDOM(f, 'input', ret='name', attrs = {'type': 'hidden'})
for i in k: post.update({i: client.parseDOM(f, 'input', ret='value', attrs = {'name': i})[0]})
post.update({'method_free': 'Watch Free!'})
result = cloudflare.request(url, post=post)
result = result.replace('\\/', '/').replace('\n', '').replace('\'', '"').replace(' ', '')
swfUrl = re.compile('\.embedSWF\("(.+?)"').findall(result)[0]
swfUrl = urlparse.urljoin(url, swfUrl)
streamer = re.compile('flashvars=.+?"file":"(.+?)"').findall(result)[0]
playpath = re.compile('flashvars=.+?p2pkey:"(.+?)"').findall(result)[0]
url = '%s playpath=%s conn=S:%s pageUrl=%s swfUrl=%s swfVfy=true timeout=20' % (streamer, playpath, playpath, url, swfUrl)
return url
except:
return
| gpl-2.0 |
aCOSMIC/aCOSMIC | cosmic/mp/progress.py | 1 | 1367 | # -*- coding: utf-8 -*-
# Copyright (C) Duncan Macleod (2017-2019)
#
# This file is part of GWpy.
#
# GWpy 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.
#
# GWpy 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 GWpy. If not, see <http://www.gnu.org/licenses/>.
"""Utilities for multi-processing
"""
import sys
from tqdm import tqdm
TQDM_BAR_FORMAT = ("{desc}: |{bar}| "
"{n_fmt}/{total_fmt} ({percentage:3.0f}%) "
"ETA {remaining:6s}")
def progress_bar(**kwargs):
"""Create a `tqdm.tqdm` progress bar
This is just a thin wrapper around `tqdm.tqdm` to set some updated defaults
"""
tqdm_kw = {
'desc': 'Processing',
'file': sys.stdout,
'bar_format': TQDM_BAR_FORMAT,
}
tqdm_kw.update(kwargs)
pbar = tqdm(**tqdm_kw)
if not pbar.disable:
pbar.desc = pbar.desc.rstrip(': ')
pbar.refresh()
return pbar
| gpl-3.0 |
meilinxiaoxue/flare-ida | examples/argtracker_example1.py | 6 | 3869 | #!/usr/bin/env python
# Jay Smith
# jay.smith@fireeye.com
#
########################################################################
# Copyright 2015 FireEye
# Copyright 2012 Mandiant
#
# FireEye licenses this file to you under the Apache License, Version
# 2.0 (the "License"); you may not use this file except in compliance with the
# License. You may obtain a copy of the License at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied. See the License for the specific language governing
# permissions and limitations under the License.
########################################################################
#
# gh0st custom thread runner identifier. Written for: 22958062524bb2a9dd6cf300d6ff4816
#
# gh0st variants tend to use a custom launcher for threads. This searches
# for a single xref to _beginthreadex, and then
#
#
# This expects the custom thread launcher to look like:
# HANDLE MyCreateThread (LPSECURITY_ATTRIBUTES lpThreadAttributes, // SD
# SIZE_T dwStackSize, // initial stack size
# LPTHREAD_START_ROUTINE lpStartAddress, // thread function
# LPVOID lpParameter, // thread argument
# DWORD dwCreationFlags, // creation option
# LPDWORD lpThreadId, bool bInteractive);
#
########################################################################
import idc
import idaapi
import idautils
import flare.jayutils as c_jayutils
import flare.argtracker as c_argtracker
#c_jayutils.configLogger('', logging.DEBUG)
c_jayutils.configLogger('', logging.INFO)
logger = c_jayutils.getLogger('')
def getFunctionArgumentCount(ea):
'''
Bit of a hack, since IDA doesn't seem to have a good way to get this information.
Gets the frame for a given function, and counts named members following the 'r'
member.
Note: IDA won't create a frame member for an unreferenced function arg... so you've
been warned.
'''
rFound = False
argCount = 0
sid = idc.GetFrame(ea)
midx = idc.GetFirstMember(sid)
while midx != idc.BADADDR:
name = idc.GetMemberName(sid, midx)
if rFound and name is not None:
argCount += 1
#print 'Found arg at 0x%x: "%s"' % (midx, name)
elif name == ' r':
#print 'Found r at 0x%x:' % midx
rFound = True
else:
#print 'Found nonarg at 0x%x: "%s"' % (midx, name)
pass
midx = idc.GetStrucNextOff(sid, midx)
return argCount
def handleCreateThread(ea):
logger.debug('handleCreateThread: starting up 0x%08x', ea)
vw = c_jayutils.loadWorkspace(c_jayutils.getInputFilepath())
logger.info('Loaded workspace')
tracker = c_argtracker.ArgTracker(vw)
interestingXrefs = idautils.CodeRefsTo(ea, 1)
for xref in interestingXrefs:
argsList = tracker.getPushArgs(xref, 7)
if len(argsList) == 0:
logger.error('Unable to get push args at: 0x%08x', xref)
else:
for argDict in argsList:
loadVa, funcVa = argDict[3]
print 'Found: 0x%08x: 0x%08x' % (loadVa, funcVa)
def main():
beginThreadExLoc = idc.LocByName('_beginthreadex')
if beginThreadExLoc == idc.BADADDR:
print 'Function "_beginthreadex" not found. Returning'
return
for xref in idautils.CodeRefsTo(beginThreadExLoc, 1):
if getFunctionArgumentCount(xref) == 7:
print 'Found likely MyCreateThread: 0x%08x' % xref
handleCreateThread(idc.GetFunctionAttr(xref, idc.FUNCATTR_START))
main()
| apache-2.0 |
datasciencebr/serenata-de-amor | research/src/fetch_tse_data.py | 2 | 9446 | """
This script downloads and format some data from TSE website.
The first objective with this data is to obtain a list of all politicians in Brazil.
In march 2017, the data available in TSE website contained information about elected people from the year 1994 to 2016.
Data before 1994 does not contains name of the politicians.
Further, they inform that data from 1994 to 2002 is insconsistent and they are working on it.
The data is available in csv format: one csv file per state, grouped in one zip file per year.
Some of the csv files from TSE contain headers.
Unfortunately, this is not the case for the files we are dealing with here.
For different years there are different numbers of columns, and consequently, different headers.
In this script, after downloading the files, we appropriately name the columns and select a useful subsample of columns to export for future use in Serenata Project.
"""
import pandas as pd
import numpy as np
import os
import urllib
import zipfile
import glob
from tempfile import mkdtemp
TEMP_PATH = mkdtemp()
FILENAME_PREFIX = 'consulta_cand_'
TSE_CANDIDATES_URL = 'http://agencia.tse.jus.br/estatistica/sead/odsele/consulta_cand/'
TODAY = pd.datetime.today().date()
OUTPUT_FILENAME = TODAY.isoformat() + '-tse-candidates.xz'
OUTPUT_DATASET_PATH = os.path.join('data', OUTPUT_FILENAME)
# setting year range from 2004 up to now. this will be modified further to
# include yearsfrom 1994 to 2002
year_list = [str(year) for year in (range(2004, TODAY.year + 1, 2))]
# Download files
for year in year_list:
filename = '{}{}.zip'.format(FILENAME_PREFIX, year)
file_url = TSE_CANDIDATES_URL + filename
output_file = os.path.join(TEMP_PATH, filename)
urllib.request.urlretrieve(file_url, output_file)
# Unzip downloaded files
for year in year_list:
filename = FILENAME_PREFIX + year + '.zip'
filepath = os.path.join(TEMP_PATH, filename)
zip_ref = zipfile.ZipFile(filepath, 'r')
zip_ref.extractall(TEMP_PATH)
zip_ref.close()
# ### Adding the headers
# The following headers were extracted from LEIAME.pdf in consulta_cand_2016.zip.
# headers commented with (*) can be used in the future to integrate with
# other TSE datasets
header_consulta_cand_till2010 = [
"DATA_GERACAO",
"HORA_GERACAO",
"ANO_ELEICAO",
"NUM_TURNO", # (*)
"DESCRICAO_ELEICAO", # (*)
"SIGLA_UF",
"SIGLA_UE", # (*)
"DESCRICAO_UE",
"CODIGO_CARGO", # (*)
"DESCRICAO_CARGO",
"NOME_CANDIDATO",
"SEQUENCIAL_CANDIDATO", # (*)
"NUMERO_CANDIDATO",
"CPF_CANDIDATO",
"NOME_URNA_CANDIDATO",
"COD_SITUACAO_CANDIDATURA",
"DES_SITUACAO_CANDIDATURA",
"NUMERO_PARTIDO",
"SIGLA_PARTIDO",
"NOME_PARTIDO",
"CODIGO_LEGENDA",
"SIGLA_LEGENDA",
"COMPOSICAO_LEGENDA",
"NOME_LEGENDA",
"CODIGO_OCUPACAO",
"DESCRICAO_OCUPACAO",
"DATA_NASCIMENTO",
"NUM_TITULO_ELEITORAL_CANDIDATO",
"IDADE_DATA_ELEICAO",
"CODIGO_SEXO",
"DESCRICAO_SEXO",
"COD_GRAU_INSTRUCAO",
"DESCRICAO_GRAU_INSTRUCAO",
"CODIGO_ESTADO_CIVIL",
"DESCRICAO_ESTADO_CIVIL",
"CODIGO_NACIONALIDADE",
"DESCRICAO_NACIONALIDADE",
"SIGLA_UF_NASCIMENTO",
"CODIGO_MUNICIPIO_NASCIMENTO",
"NOME_MUNICIPIO_NASCIMENTO",
"DESPESA_MAX_CAMPANHA",
"COD_SIT_TOT_TURNO",
"DESC_SIT_TOT_TURNO",
]
header_consulta_cand_at2012 = [
"DATA_GERACAO",
"HORA_GERACAO",
"ANO_ELEICAO",
"NUM_TURNO", # (*)
"DESCRICAO_ELEICAO", # (*)
"SIGLA_UF",
"SIGLA_UE", # (*)
"DESCRICAO_UE",
"CODIGO_CARGO", # (*)
"DESCRICAO_CARGO",
"NOME_CANDIDATO",
"SEQUENCIAL_CANDIDATO", # (*)
"NUMERO_CANDIDATO",
"CPF_CANDIDATO",
"NOME_URNA_CANDIDATO",
"COD_SITUACAO_CANDIDATURA",
"DES_SITUACAO_CANDIDATURA",
"NUMERO_PARTIDO",
"SIGLA_PARTIDO",
"NOME_PARTIDO",
"CODIGO_LEGENDA",
"SIGLA_LEGENDA",
"COMPOSICAO_LEGENDA",
"NOME_LEGENDA",
"CODIGO_OCUPACAO",
"DESCRICAO_OCUPACAO",
"DATA_NASCIMENTO",
"NUM_TITULO_ELEITORAL_CANDIDATO",
"IDADE_DATA_ELEICAO",
"CODIGO_SEXO",
"DESCRICAO_SEXO",
"COD_GRAU_INSTRUCAO",
"DESCRICAO_GRAU_INSTRUCAO",
"CODIGO_ESTADO_CIVIL",
"DESCRICAO_ESTADO_CIVIL",
"CODIGO_NACIONALIDADE",
"DESCRICAO_NACIONALIDADE",
"SIGLA_UF_NASCIMENTO",
"CODIGO_MUNICIPIO_NASCIMENTO",
"NOME_MUNICIPIO_NASCIMENTO",
"DESPESA_MAX_CAMPANHA",
"COD_SIT_TOT_TURNO",
"DESC_SIT_TOT_TURNO",
"NM_EMAIL",
]
header_consulta_cand_from2014 = [
"DATA_GERACAO",
"HORA_GERACAO",
"ANO_ELEICAO",
"NUM_TURNO", # (*)
"DESCRICAO_ELEICAO", # (*)
"SIGLA_UF",
"SIGLA_UE", # (*)
"DESCRICAO_UE",
"CODIGO_CARGO", # (*)
"DESCRICAO_CARGO",
"NOME_CANDIDATO",
"SEQUENCIAL_CANDIDATO", # (*)
"NUMERO_CANDIDATO",
"CPF_CANDIDATO",
"NOME_URNA_CANDIDATO",
"COD_SITUACAO_CANDIDATURA",
"DES_SITUACAO_CANDIDATURA",
"NUMERO_PARTIDO",
"SIGLA_PARTIDO",
"NOME_PARTIDO",
"CODIGO_LEGENDA",
"SIGLA_LEGENDA",
"COMPOSICAO_LEGENDA",
"NOME_LEGENDA",
"CODIGO_OCUPACAO",
"DESCRICAO_OCUPACAO",
"DATA_NASCIMENTO",
"NUM_TITULO_ELEITORAL_CANDIDATO",
"IDADE_DATA_ELEICAO",
"CODIGO_SEXO",
"DESCRICAO_SEXO",
"COD_GRAU_INSTRUCAO",
"DESCRICAO_GRAU_INSTRUCAO",
"CODIGO_ESTADO_CIVIL",
"DESCRICAO_ESTADO_CIVIL",
"CODIGO_COR_RACA",
"DESCRICAO_COR_RACA",
"CODIGO_NACIONALIDADE",
"DESCRICAO_NACIONALIDADE",
"SIGLA_UF_NASCIMENTO",
"CODIGO_MUNICIPIO_NASCIMENTO",
"NOME_MUNICIPIO_NASCIMENTO",
"DESPESA_MAX_CAMPANHA",
"COD_SIT_TOT_TURNO",
"DESC_SIT_TOT_TURNO",
"NM_EMAIL",
]
sel_columns = [
"ANO_ELEICAO",
"NUM_TURNO", # (*)
"DESCRICAO_ELEICAO", # (*)
"SIGLA_UF",
"DESCRICAO_UE",
"DESCRICAO_CARGO",
"NOME_CANDIDATO",
"SEQUENCIAL_CANDIDATO", # (*)
"CPF_CANDIDATO",
"NUM_TITULO_ELEITORAL_CANDIDATO",
"DESC_SIT_TOT_TURNO",
]
# Concatenate all files in one pandas dataframe
cand_df = pd.DataFrame()
for year in year_list:
filesname = FILENAME_PREFIX + year + '*.txt'
filespath = os.path.join(TEMP_PATH, filesname)
files_of_the_year = sorted(glob.glob(filespath))
for file_i in files_of_the_year:
# the following cases do not take into account next elections.
# hopefully, TSE will add headers to the files
if ('2014' in file_i) or ('2016' in file_i):
cand_df_i = pd.read_csv(
file_i,
sep=';',
header=None,
dtype=np.str,
names=header_consulta_cand_from2014,
encoding='iso-8859-1')
elif ('2012' in file_i):
cand_df_i = pd.read_csv(
file_i,
sep=';',
header=None,
dtype=np.str,
names=header_consulta_cand_at2012,
encoding='iso-8859-1')
else:
cand_df_i = pd.read_csv(
file_i,
sep=';',
header=None,
dtype=np.str,
names=header_consulta_cand_till2010,
encoding='iso-8859-1')
cand_df = cand_df.append(cand_df_i[sel_columns])
# this index contains no useful information
cand_df.index = cand_df.reset_index().index
# Translation
headers_translation = {
'ANO_ELEICAO': 'year',
'NUM_TURNO': 'phase', # first round or runoff
'DESCRICAO_ELEICAO': 'description',
'SIGLA_UF': 'state',
'DESCRICAO_UE': 'location',
'DESCRICAO_CARGO': 'post',
'NOME_CANDIDATO': 'name',
# This is not to be used as unique identifier
'SEQUENCIAL_CANDIDATO': 'electoral_id',
'CPF_CANDIDATO': 'cpf',
'NUM_TITULO_ELEITORAL_CANDIDATO': 'voter_id',
'DESC_SIT_TOT_TURNO': 'result',
}
post_translation = {
'VEREADOR': 'city_councilman',
'VICE-PREFEITO': 'vice_mayor',
'PREFEITO': 'mayor',
'DEPUTADO ESTADUAL': 'state_deputy',
'DEPUTADO FEDERAL': 'federal_deputy',
'DEPUTADO DISTRITAL': 'district_deputy',
'SENADOR': 'senator',
'VICE-GOVERNADOR': 'vice_governor',
'GOVERNADOR': 'governor',
'2º SUPLENTE SENADOR': 'senate_second_alternate',
'1º SUPLENTE SENADO': 'senate_first_alternate',
'2º SUPLENTE': 'senate_second_alternate',
'1º SUPLENTE': 'senate_first_alternate',
'VICE-PRESIDENTE': 'vice_president',
'PRESIDENTE': 'president',
}
result_translation = {
'SUPLENTE': 'alternate',
'NÃO ELEITO': 'not_elected',
'#NULO#': 'null',
'ELEITO': 'elected',
'ELEITO POR QP': 'elected_by_party_quota',
'MÉDIA': 'elected',
'ELEITO POR MÉDIA': 'elected',
'#NE#': 'null',
'REGISTRO NEGADO ANTES DA ELEIÇÃO': 'rejected',
'INDEFERIDO COM RECURSO': 'rejected',
'RENÚNCIA/FALECIMENTO/CASSAÇÃO ANTES DA ELEIÇÃO': 'rejected',
'2º TURNO': 'runoff',
'SUBSTITUÍDO': 'replaced',
'REGISTRO NEGADO APÓS A ELEIÇÃO': 'rejected',
'RENÚNCIA/FALECIMENTO COM SUBSTITUIÇÃO': 'replaced',
'RENÚNCIA/FALECIMENTO/CASSAÇÃO APÓS A ELEIÇÃO': 'rejected',
'CASSADO COM RECURSO': 'rejected',
}
cand_df = cand_df.rename(columns=headers_translation)
cand_df.post = cand_df.post.map(post_translation)
cand_df.result = cand_df.result.map(result_translation)
# Exporting data
cand_df.to_csv(
OUTPUT_DATASET_PATH,
encoding='utf-8',
compression='xz',
header=True,
index=False)
| mit |
amw2104/fireplace | fireplace/managers.py | 1 | 6952 | from hearthstone.enums import GameTag
from . import enums
class Manager(object):
def __init__(self, obj):
self.obj = obj
self.observers = []
def __getitem__(self, tag):
if self.map.get(tag):
return getattr(self.obj, self.map[tag], 0)
raise KeyError
def __setitem__(self, tag, value):
setattr(self.obj, self.map[tag], value)
def __iter__(self):
for k in self.map:
if self.map[k]:
yield k
def get(self, k, default=None):
return self[k] if k in self.map else default
def items(self):
for k, v in self.map.items():
if v is not None:
yield k, self[k]
def register(self, observer):
self.observers.append(observer)
def update(self, tags):
for k, v in tags.items():
if self.map.get(k) is not None:
self[k] = v
class GameManager(Manager):
map = {
GameTag.CARDTYPE: "type",
GameTag.NEXT_STEP: "next_step",
GameTag.NUM_MINIONS_KILLED_THIS_TURN: "minions_killed_this_turn",
GameTag.PROPOSED_ATTACKER: "proposed_attacker",
GameTag.PROPOSED_DEFENDER: "proposed_defender",
GameTag.STATE: "state",
GameTag.STEP: "step",
GameTag.TURN: "turn",
GameTag.ZONE: "zone",
}
def __init__(self, obj):
super().__init__(obj)
self.counter = 1
obj.entity_id = self.counter
def action(self, type, *args):
for observer in self.observers:
observer.action(type, args)
def action_end(self, type, *args):
for observer in self.observers:
observer.action_end(type, args)
def new_entity(self, entity):
self.counter += 1
entity.entity_id = self.counter
for observer in self.observers:
observer.new_entity(entity)
def start_game(self):
for observer in self.observers:
observer.start_game()
def step(self, step, next_step):
for observer in self.observers:
observer.game_step(step, next_step)
self.obj.step = step
self.obj.next_step = next_step
class PlayerManager(Manager):
map = {
GameTag.CANT_DRAW: "cant_draw",
GameTag.CARDTYPE: "type",
GameTag.COMBO_ACTIVE: "combo",
GameTag.CONTROLLER: "controller",
GameTag.CURRENT_PLAYER: "current_player",
GameTag.CURRENT_SPELLPOWER: "spellpower",
GameTag.FATIGUE: "fatigue_counter",
GameTag.FIRST_PLAYER: "first_player",
GameTag.HEALING_DOUBLE: "healing_double",
GameTag.HERO_ENTITY: "hero",
GameTag.LAST_CARD_PLAYED: "last_card_played",
GameTag.MAXHANDSIZE: "max_hand_size",
GameTag.MAXRESOURCES: "max_resources",
GameTag.NUM_CARDS_DRAWN_THIS_TURN: "cards_drawn_this_turn",
GameTag.NUM_CARDS_PLAYED_THIS_TURN: "cards_played_this_turn",
GameTag.NUM_MINIONS_PLAYED_THIS_TURN: "minions_played_this_turn",
GameTag.NUM_MINIONS_PLAYER_KILLED_THIS_TURN: "minions_killed_this_turn",
GameTag.NUM_TIMES_HERO_POWER_USED_THIS_GAME: "times_hero_power_used_this_game",
GameTag.OUTGOING_HEALING_ADJUSTMENT: "outgoing_healing_adjustment",
GameTag.OVERLOAD_LOCKED: "overload_locked",
GameTag.OVERLOAD_OWED: "overloaded",
GameTag.PLAYSTATE: "playstate",
GameTag.RESOURCES: "max_mana",
GameTag.RESOURCES_USED: "used_mana",
GameTag.SPELLPOWER_DOUBLE: "spellpower_double",
GameTag.STARTHANDSIZE: "start_hand_size",
GameTag.HERO_POWER_DOUBLE: "hero_power_double",
GameTag.TEMP_RESOURCES: "temp_mana",
GameTag.TIMEOUT: "timeout",
GameTag.TURN_START: "turn_start",
enums.CANT_OVERLOAD: "cant_overload",
}
CARD_ATTRIBUTE_MAP = {
GameTag.ADJACENT_BUFF: "adjacent_buff",
GameTag.ARMOR: "armor",
GameTag.ATK: "atk",
GameTag.ATTACKING: "attacking",
GameTag.ATTACHED: "owner",
GameTag.AURA: "aura",
GameTag.BATTLECRY: "has_battlecry",
GameTag.CANNOT_ATTACK_HEROES: "cannot_attack_heroes",
GameTag.CANT_ATTACK: "cant_attack",
GameTag.CANT_BE_ATTACKED: "cant_be_attacked",
GameTag.CANT_BE_DAMAGED: "cant_be_damaged",
GameTag.CANT_BE_TARGETED_BY_ABILITIES: "cant_be_targeted_by_abilities",
GameTag.CANT_BE_TARGETED_BY_HERO_POWERS: "cant_be_targeted_by_hero_powers",
GameTag.CANT_BE_TARGETED_BY_OPPONENTS: "cant_be_targeted_by_opponents",
GameTag.CANT_PLAY: "cant_play",
GameTag.CARD_ID: "id",
GameTag.CARD_TARGET: "target",
GameTag.CARDNAME: "name",
GameTag.CARDRACE: "race",
GameTag.CARDTYPE: "type",
GameTag.CHARGE: "charge",
GameTag.CLASS: "card_class",
GameTag.COMBO: "has_combo",
GameTag.CONTROLLER: "controller",
GameTag.COST: "cost",
GameTag.CREATOR: "creator",
GameTag.DAMAGE: "damage",
GameTag.DEATHRATTLE: "has_deathrattle",
GameTag.DEFENDING: "defending",
GameTag.DIVINE_SHIELD: "divine_shield",
GameTag.DURABILITY: "max_durability",
GameTag.ENRAGED: "enrage",
GameTag.EXHAUSTED: "exhausted",
GameTag.EXTRA_DEATHRATTLES: "extra_deathrattles",
GameTag.FORGETFUL: "forgetful",
GameTag.FROZEN: "frozen",
GameTag.HEALING_DOUBLE: "healing_double",
GameTag.HEALTH: "max_health",
GameTag.HEALTH_MINIMUM: "min_health",
GameTag.HEROPOWER_ADDITIONAL_ACTIVATIONS: "additional_activations",
GameTag.HEROPOWER_DAMAGE: "heropower_damage",
GameTag.INCOMING_DAMAGE_MULTIPLIER: "incoming_damage_multiplier",
GameTag.ImmuneToSpellpower: "immune_to_spellpower",
GameTag.IMMUNE_WHILE_ATTACKING: "immune_while_attacking",
GameTag.INSPIRE: "has_inspire",
GameTag.NUM_ATTACKS_THIS_TURN: "num_attacks",
GameTag.NUM_TURNS_IN_PLAY: "turns_in_play",
GameTag.TAG_ONE_TURN_EFFECT: "one_turn_effect",
GameTag.OUTGOING_HEALING_ADJUSTMENT: "outgoing_healing_adjustment",
GameTag.OVERLOAD: "overload",
GameTag.POISONOUS: "poisonous",
GameTag.POWERED_UP: "powered_up",
GameTag.RARITY: "rarity",
GameTag.RECEIVES_DOUBLE_SPELLDAMAGE_BONUS: "receives_double_spelldamage_bonus",
GameTag.SECRET: "secret",
GameTag.SHADOWFORM: "shadowform",
GameTag.SHOULDEXITCOMBAT: "should_exit_combat",
GameTag.SILENCED: "silenced",
GameTag.SPELLPOWER: "spellpower",
GameTag.SPELLPOWER_DOUBLE: "spellpower_double",
GameTag.STEALTH: "stealthed",
GameTag.TAG_AI_MUST_PLAY: "autocast",
GameTag.HERO_POWER_DOUBLE: "hero_power_double",
GameTag.TAUNT: "taunt",
GameTag.WINDFURY: "windfury",
GameTag.ZONE: "zone",
enums.ALWAYS_WINS_BRAWLS: "always_wins_brawls",
enums.EXTRA_BATTLECRIES: "extra_battlecries",
enums.KILLED_THIS_TURN: "killed_this_turn",
GameTag.AFFECTED_BY_SPELL_POWER: None,
GameTag.ARTISTNAME: None,
GameTag.AttackVisualType: None,
GameTag.CARD_SET: None,
GameTag.CARDTEXT_INHAND: None,
GameTag.CardTextInPlay: None,
GameTag.Collectible: None,
GameTag.DevState: None,
GameTag.ELITE: None,
GameTag.ENCHANTMENT_IDLE_VISUAL: None,
GameTag.ENCHANTMENT_BIRTH_VISUAL: None,
GameTag.EVIL_GLOW: None,
GameTag.FACTION: None,
GameTag.FLAVORTEXT: None,
GameTag.FREEZE: None,
GameTag.HealTarget: None,
GameTag.HIDE_COST: None,
GameTag.HOW_TO_EARN: None,
GameTag.HOW_TO_EARN_GOLDEN: None,
GameTag.InvisibleDeathrattle: None,
GameTag.MORPH: None,
GameTag.SILENCE: None,
GameTag.SUMMONED: None,
GameTag.SPARE_PART: None,
GameTag.SHOWN_HERO_POWER: None,
GameTag.TARGETING_ARROW_TEXT: None,
GameTag.TOPDECK: None,
GameTag.TAG_AI_MUST_PLAY: None,
GameTag.TRIGGER_VISUAL: None,
}
class CardManager(Manager):
map = CARD_ATTRIBUTE_MAP
| agpl-3.0 |
moma/TinasoftPytextminer | tinasoft/data/medline.py | 1 | 7859 | # -*- coding: utf-8 -*-
# Copyright (C) 2009-2011 CREA Lab, CNRS/Ecole Polytechnique UMR 7656 (Fr)
#
# 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/>.
__author__="elishowk@nonutc.fr"
from tinasoft.data import sourcefile
from tinasoft.pytextminer import document, corpus
import logging
_logger = logging.getLogger('TinaAppLogger')
class Record(dict):
"""A dictionary holding information from a Medline record.
All data are stored under the mnemonic appearing in the Medline
file. These mnemonics have the following interpretations:
Mnemonic Description
AB Abstract
CI Copyright Information
AD Affiliation
IRAD Investigator Affiliation
AID Article Identifier
AU Author
FAU Full Author
CN Corporate Author
DCOM Date Completed
DA Date Created
LR Date Last Revised
DEP Date of Electronic Publication
DP Date of Publication
EDAT Entrez Date
GS Gene Symbol
GN General Note
GR Grant Number
IR Investigator Name
FIR Full Investigator Name
IS ISSN
IP Issue
TA Journal Title Abbreviation
JT Journal Title
LA Language
LID Location Identifier
MID Manuscript Identifier
MHDA MeSH Date
MH MeSH Terms
JID NLM Unique ID
RF Number of References
OAB Other Abstract
OCI Other Copyright Information
OID Other ID
OT Other Term
OTO Other Term Owner
OWN Owner
PG Pagination
PS Personal Name as Subject
FPS Full Personal Name as Subject
PL Place of Publication
PHST Publication History Status
PST Publication Status
PT Publication Type
PUBM Publishing Model
PMC PubMed Central Identifier
PMID PubMed Unique Identifier
RN Registry Number/EC Number
NM Substance Name
SI Secondary Source ID
SO Source
SFM Space Flight Mission
STAT Status
SB Subset
TI Title
TT Transliterated Title
VI Volume
CON Comment on
CIN Comment in
EIN Erratum in
EFR Erratum for
CRI Corrected and Republished in
CRF Corrected and Republished from
PRIN Partial retraction in
PROF Partial retraction of
RPI Republished in
RPF Republished from
RIN Retraction in
ROF Retraction of
UIN Update in
UOF Update of
SPIN Summary for patients in
ORI Original report in
"""
def __init__(self):
# The __init__ function can be removed when we remove the old parser
self.id = ''
self.pubmed_id = ''
self.mesh_headings = []
self.mesh_tree_numbers = []
self.mesh_subheadings = []
self.abstract = ''
self.comments = []
self.abstract_author = ''
self.english_abstract = ''
self.source = ''
self.publication_types = []
self.number_of_references = ''
self.authors = []
self.no_author = ''
self.address = ''
self.journal_title_code = ''
self.title_abbreviation = ''
self.issn = ''
self.journal_subsets = []
self.country = ''
self.languages = []
self.title = ''
self.transliterated_title = ''
self.call_number = ''
self.issue_part_supplement = ''
self.volume_issue = ''
self.publication_date = ''
self.year = ''
self.pagination = ''
self.special_list = ''
self.substance_name = ''
self.gene_symbols = []
self.secondary_source_ids = []
self.identifications = []
self.registry_numbers = []
self.personal_name_as_subjects = []
self.record_originators = []
self.entry_date = ''
self.entry_month = ''
self.class_update_date = ''
self.last_revision_date = ''
self.major_revision_date = ''
self.undefined = []
class Importer(sourcefile.Importer):
"""
Medline file importer class
"""
# defaults
options = {
'period_size': 4,
'encoding': 'ascii'
}
def __init__(self, path, **options):
sourcefile.Importer.__init__(self, path, **options)
self.reader = self.get_record()
def get_record(self):
# These keys point to string values
textkeys = ("ID", "PMID", "SO", "RF", "NI", "JC", "TA", "IS", "CY", "TT",
"CA", "IP", "VI", "DP", "YR", "PG", "LID", "DA", "LR", "OWN",
"STAT", "DCOM", "PUBM", "DEP", "PL", "JID", "SB", "PMC",
"EDAT", "MHDA", "PST", "AB", "AD", "EA", "TI", "JT")
handle = iter(self.file)
self.line_num = 0
# Skip blank lines at the beginning
try:
for line in handle:
self.line_num+=1;
line = line.rstrip()
if line:
break
else:
continue
except Exception, exc:
_logger.error("medline error reading FIRST lines : %s"%exc)
record = Record()
while 1:
if line[:6]==" ": # continuation line
# there's already a key
if key not in record:
record[key] = []
record[key].append(line[6:])
elif line:
key = str(line[:4].rstrip())
if not key in record:
record[key] = []
record[key].append(line[6:])
try:
# next line
line = handle.next()
self.line_num+=1;
except StopIteration, si:
return
except Exception, exc:
_logger.error("medline error reading line %d : %s"%(self.line_num, exc))
continue
else:
# cleans line and jump to next iteration
line = line.rstrip()
if line:
continue
# Join each list of strings into one string.
for key in textkeys:
if key in record:
record[key] = " ".join(record[key])
record['DP'] = self._parse_period(record)
yield record
record = Record()
def _parse_period(self, record):
if self.fields['corpus_id'] not in record:
return None
return record[ self.fields['corpus_id'] ][ : self.period_size]
def next(self):
try:
row = self.reader.next()
except StopIteration, si:
raise StopIteration(si)
except Exception, ex:
_logger.error("basecsv reader error at line %d, reason : %s"%(self.reader.line_num, ex))
# returns None : child or using object should verify the returning value
return None
else:
return row
def __iter__(self):
return self | gpl-3.0 |
chokribr/invenio | invenio/modules/statistics/models.py | 13 | 1538 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2011, 2012 CERN.
#
# Invenio is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Invenio is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
"""
webstat database models.
"""
# General imports.
from invenio.ext.sqlalchemy import db
# Create your models here.
class StaEVENT(db.Model):
"""Represents a StaEVENT record."""
def __init__(self):
pass
__tablename__ = 'staEVENT'
id = db.Column(db.String(255), nullable=False,
primary_key=True)
number = db.Column(db.SmallInteger(2, unsigned=True, zerofill=True),
nullable=False, autoincrement=True, primary_key=True,
unique=True)
name = db.Column(db.String(255), nullable=True)
creation_time = db.Column(db.TIMESTAMP, nullable=False,
server_default=db.func.current_timestamp())
cols = db.Column(db.String(255), nullable=True)
__all__ = ['StaEVENT']
| gpl-2.0 |
sejalvarshney/stockkbot2 | app.py | 1 | 2255 | from __future__ import print_function
from future.standard_library import install_aliases
install_aliases()
from urllib.parse import urlparse, urlencode
#from urllib.request import urlopen, Request
from urllib.error import HTTPError
import urllib.request
import json
import os
import datetime
from flask import Flask
from flask import request
from flask import make_response
# Flask app should start in global layout
app = Flask(__name__)
@app.route('/webhook', methods=['POST'])
def webhook():
req = request.get_json(silent=True, force=True)
print("Request:")
print(json.dumps(req, indent=4))
res = processRequest(req)
res = json.dumps(res, indent=4)
print("Response:")
print(json.dumps(res, indent=4))
r = make_response(res)
r.headers['Content-Type'] = 'application/json'
return r
def processRequest(req):
if req.get("result").get("action") != "price":
return {}
baseurl = "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol="
alpha_query = makeAlphaQuery(req)
if alpha_query is None:
return {}
alpha_url = baseurl + alpha_query[0] + "&apikey=KO6S7F5GV15OQ4G7"
result1 = urllib.request.urlopen(alpha_url).read()
data = json.loads(result1)
res = makeWebhookResult(data,alpha_query[1])
return res
def makeAlphaQuery(req):
result = req.get("result")
parameters = result.get("parameters")
stock_symbol = str(parameters.get("stock_symbol"))
date = str(parameters.get("date"))
if stock_symbol is None:
return None
return [stock_symbol,date]
def makeWebhookResult(data,date):
timeseries = data.get("Time Series (Daily)")
ofdate = timeseries.get(str(date))
closevalue = str(ofdate.get("4. close"))
print(json.dumps(closevalue, indent=4))
speech = "The value of the stock as on " + date + " is: " + closevalue
print("Response:")
print(speech)
return {
"speech": speech,
"displayText": speech,
# "data": data,
# "contextOut": [],
"source": "stockkbot"
}
if __name__ == '__main__':
port = int(os.getenv('PORT', 5000))
print("Starting app on port %d" % port)
app.run(debug=False, port=port, host='0.0.0.0')
| apache-2.0 |
roubert/python-phonenumbers | python/phonenumbers/data/region_HR.py | 10 | 3499 | """Auto-generated file, do not edit by hand. HR metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_HR = PhoneMetadata(id='HR', country_code=385, international_prefix='00',
general_desc=PhoneNumberDesc(national_number_pattern='[1-7]\\d{5,8}|[89]\\d{6,11}', possible_number_pattern='\\d{6,12}'),
fixed_line=PhoneNumberDesc(national_number_pattern='1\\d{7}|(?:2[0-3]|3[1-5]|4[02-47-9]|5[1-3])\\d{6,7}', possible_number_pattern='\\d{6,9}', example_number='12345678'),
mobile=PhoneNumberDesc(national_number_pattern='9(?:[1-9]\\d{6,10}|01\\d{6,9})', possible_number_pattern='\\d{8,12}', example_number='912345678'),
toll_free=PhoneNumberDesc(national_number_pattern='80[01]\\d{4,7}', possible_number_pattern='\\d{7,10}', example_number='8001234567'),
premium_rate=PhoneNumberDesc(national_number_pattern='6(?:[01459]\\d{4,7})', possible_number_pattern='\\d{6,9}', example_number='611234'),
shared_cost=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'),
personal_number=PhoneNumberDesc(national_number_pattern='7[45]\\d{4,7}', possible_number_pattern='\\d{6,9}', example_number='741234567'),
voip=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'),
pager=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'),
uan=PhoneNumberDesc(national_number_pattern='[76]2\\d{6,7}', possible_number_pattern='\\d{8,9}', example_number='62123456'),
voicemail=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'),
no_international_dialling=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'),
national_prefix='0',
national_prefix_for_parsing='0',
number_format=[NumberFormat(pattern='(1)(\\d{4})(\\d{3})', format='\\1 \\2 \\3', leading_digits_pattern=['1'], national_prefix_formatting_rule='0\\1'),
NumberFormat(pattern='(6[09])(\\d{4})(\\d{3})', format='\\1 \\2 \\3', leading_digits_pattern=['6[09]'], national_prefix_formatting_rule='0\\1'),
NumberFormat(pattern='([67]2)(\\d{3})(\\d{3,4})', format='\\1 \\2 \\3', leading_digits_pattern=['[67]2'], national_prefix_formatting_rule='0\\1'),
NumberFormat(pattern='([2-5]\\d)(\\d{3})(\\d{3,4})', format='\\1 \\2 \\3', leading_digits_pattern=['[2-5]'], national_prefix_formatting_rule='0\\1'),
NumberFormat(pattern='(9\\d)(\\d{3})(\\d{3,4})', format='\\1 \\2 \\3', leading_digits_pattern=['9'], national_prefix_formatting_rule='0\\1'),
NumberFormat(pattern='(9\\d)(\\d{4})(\\d{4})', format='\\1 \\2 \\3', leading_digits_pattern=['9'], national_prefix_formatting_rule='0\\1'),
NumberFormat(pattern='(9\\d)(\\d{3,4})(\\d{3})(\\d{3})', format='\\1 \\2 \\3 \\4', leading_digits_pattern=['9'], national_prefix_formatting_rule='0\\1'),
NumberFormat(pattern='(\\d{2})(\\d{2})(\\d{2,3})', format='\\1 \\2 \\3', leading_digits_pattern=['6[0145]|7'], national_prefix_formatting_rule='0\\1'),
NumberFormat(pattern='(\\d{2})(\\d{3,4})(\\d{3})', format='\\1 \\2 \\3', leading_digits_pattern=['6[0145]|7'], national_prefix_formatting_rule='0\\1'),
NumberFormat(pattern='(80[01])(\\d{2})(\\d{2,3})', format='\\1 \\2 \\3', leading_digits_pattern=['8'], national_prefix_formatting_rule='0\\1'),
NumberFormat(pattern='(80[01])(\\d{3,4})(\\d{3})', format='\\1 \\2 \\3', leading_digits_pattern=['8'], national_prefix_formatting_rule='0\\1')],
mobile_number_portable_region=True)
| apache-2.0 |
tizianasellitto/servo | tests/wpt/web-platform-tests/tools/pywebsocket/src/test/test_handshake_hybi00.py | 466 | 17345 | #!/usr/bin/env python
#
# Copyright 2011, 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.
"""Tests for handshake.hybi00 module."""
import unittest
import set_sys_path # Update sys.path to locate mod_pywebsocket module.
from mod_pywebsocket.handshake._base import HandshakeException
from mod_pywebsocket.handshake.hybi00 import Handshaker
from mod_pywebsocket.handshake.hybi00 import _validate_subprotocol
from test import mock
_TEST_KEY1 = '4 @1 46546xW%0l 1 5'
_TEST_KEY2 = '12998 5 Y3 1 .P00'
_TEST_KEY3 = '^n:ds[4U'
_TEST_CHALLENGE_RESPONSE = '8jKS\'y:G*Co,Wxa-'
_GOOD_REQUEST = (
80,
'GET',
'/demo',
{
'Host': 'example.com',
'Connection': 'Upgrade',
'Sec-WebSocket-Key2': _TEST_KEY2,
'Sec-WebSocket-Protocol': 'sample',
'Upgrade': 'WebSocket',
'Sec-WebSocket-Key1': _TEST_KEY1,
'Origin': 'http://example.com',
},
_TEST_KEY3)
_GOOD_REQUEST_CAPITALIZED_HEADER_VALUES = (
80,
'GET',
'/demo',
{
'Host': 'example.com',
'Connection': 'UPGRADE',
'Sec-WebSocket-Key2': _TEST_KEY2,
'Sec-WebSocket-Protocol': 'sample',
'Upgrade': 'WEBSOCKET',
'Sec-WebSocket-Key1': _TEST_KEY1,
'Origin': 'http://example.com',
},
_TEST_KEY3)
_GOOD_REQUEST_CASE_MIXED_HEADER_NAMES = (
80,
'GET',
'/demo',
{
'hOsT': 'example.com',
'cOnNeCtIoN': 'Upgrade',
'sEc-wEbsOcKeT-kEy2': _TEST_KEY2,
'sEc-wEbsOcKeT-pRoToCoL': 'sample',
'uPgRaDe': 'WebSocket',
'sEc-wEbsOcKeT-kEy1': _TEST_KEY1,
'oRiGiN': 'http://example.com',
},
_TEST_KEY3)
_GOOD_RESPONSE_DEFAULT_PORT = (
'HTTP/1.1 101 WebSocket Protocol Handshake\r\n'
'Upgrade: WebSocket\r\n'
'Connection: Upgrade\r\n'
'Sec-WebSocket-Location: ws://example.com/demo\r\n'
'Sec-WebSocket-Origin: http://example.com\r\n'
'Sec-WebSocket-Protocol: sample\r\n'
'\r\n' +
_TEST_CHALLENGE_RESPONSE)
_GOOD_RESPONSE_SECURE = (
'HTTP/1.1 101 WebSocket Protocol Handshake\r\n'
'Upgrade: WebSocket\r\n'
'Connection: Upgrade\r\n'
'Sec-WebSocket-Location: wss://example.com/demo\r\n'
'Sec-WebSocket-Origin: http://example.com\r\n'
'Sec-WebSocket-Protocol: sample\r\n'
'\r\n' +
_TEST_CHALLENGE_RESPONSE)
_GOOD_REQUEST_NONDEFAULT_PORT = (
8081,
'GET',
'/demo',
{
'Host': 'example.com:8081',
'Connection': 'Upgrade',
'Sec-WebSocket-Key2': _TEST_KEY2,
'Sec-WebSocket-Protocol': 'sample',
'Upgrade': 'WebSocket',
'Sec-WebSocket-Key1': _TEST_KEY1,
'Origin': 'http://example.com',
},
_TEST_KEY3)
_GOOD_RESPONSE_NONDEFAULT_PORT = (
'HTTP/1.1 101 WebSocket Protocol Handshake\r\n'
'Upgrade: WebSocket\r\n'
'Connection: Upgrade\r\n'
'Sec-WebSocket-Location: ws://example.com:8081/demo\r\n'
'Sec-WebSocket-Origin: http://example.com\r\n'
'Sec-WebSocket-Protocol: sample\r\n'
'\r\n' +
_TEST_CHALLENGE_RESPONSE)
_GOOD_RESPONSE_SECURE_NONDEF = (
'HTTP/1.1 101 WebSocket Protocol Handshake\r\n'
'Upgrade: WebSocket\r\n'
'Connection: Upgrade\r\n'
'Sec-WebSocket-Location: wss://example.com:8081/demo\r\n'
'Sec-WebSocket-Origin: http://example.com\r\n'
'Sec-WebSocket-Protocol: sample\r\n'
'\r\n' +
_TEST_CHALLENGE_RESPONSE)
_GOOD_REQUEST_NO_PROTOCOL = (
80,
'GET',
'/demo',
{
'Host': 'example.com',
'Connection': 'Upgrade',
'Sec-WebSocket-Key2': _TEST_KEY2,
'Upgrade': 'WebSocket',
'Sec-WebSocket-Key1': _TEST_KEY1,
'Origin': 'http://example.com',
},
_TEST_KEY3)
_GOOD_RESPONSE_NO_PROTOCOL = (
'HTTP/1.1 101 WebSocket Protocol Handshake\r\n'
'Upgrade: WebSocket\r\n'
'Connection: Upgrade\r\n'
'Sec-WebSocket-Location: ws://example.com/demo\r\n'
'Sec-WebSocket-Origin: http://example.com\r\n'
'\r\n' +
_TEST_CHALLENGE_RESPONSE)
_GOOD_REQUEST_WITH_OPTIONAL_HEADERS = (
80,
'GET',
'/demo',
{
'Host': 'example.com',
'Connection': 'Upgrade',
'Sec-WebSocket-Key2': _TEST_KEY2,
'EmptyValue': '',
'Sec-WebSocket-Protocol': 'sample',
'AKey': 'AValue',
'Upgrade': 'WebSocket',
'Sec-WebSocket-Key1': _TEST_KEY1,
'Origin': 'http://example.com',
},
_TEST_KEY3)
# TODO(tyoshino): Include \r \n in key3, challenge response.
_GOOD_REQUEST_WITH_NONPRINTABLE_KEY = (
80,
'GET',
'/demo',
{
'Host': 'example.com',
'Connection': 'Upgrade',
'Sec-WebSocket-Key2': 'y R2 48 Q1O4 e|BV3 i5 1 u- 65',
'Sec-WebSocket-Protocol': 'sample',
'Upgrade': 'WebSocket',
'Sec-WebSocket-Key1': '36 7 74 i 92 2\'m 9 0G',
'Origin': 'http://example.com',
},
''.join(map(chr, [0x01, 0xd1, 0xdd, 0x3b, 0xd1, 0x56, 0x63, 0xff])))
_GOOD_RESPONSE_WITH_NONPRINTABLE_KEY = (
'HTTP/1.1 101 WebSocket Protocol Handshake\r\n'
'Upgrade: WebSocket\r\n'
'Connection: Upgrade\r\n'
'Sec-WebSocket-Location: ws://example.com/demo\r\n'
'Sec-WebSocket-Origin: http://example.com\r\n'
'Sec-WebSocket-Protocol: sample\r\n'
'\r\n' +
''.join(map(chr, [0x0b, 0x99, 0xfa, 0x55, 0xbd, 0x01, 0x23, 0x7b,
0x45, 0xa2, 0xf1, 0xd0, 0x87, 0x8a, 0xee, 0xeb])))
_GOOD_REQUEST_WITH_QUERY_PART = (
80,
'GET',
'/demo?e=mc2',
{
'Host': 'example.com',
'Connection': 'Upgrade',
'Sec-WebSocket-Key2': _TEST_KEY2,
'Sec-WebSocket-Protocol': 'sample',
'Upgrade': 'WebSocket',
'Sec-WebSocket-Key1': _TEST_KEY1,
'Origin': 'http://example.com',
},
_TEST_KEY3)
_GOOD_RESPONSE_WITH_QUERY_PART = (
'HTTP/1.1 101 WebSocket Protocol Handshake\r\n'
'Upgrade: WebSocket\r\n'
'Connection: Upgrade\r\n'
'Sec-WebSocket-Location: ws://example.com/demo?e=mc2\r\n'
'Sec-WebSocket-Origin: http://example.com\r\n'
'Sec-WebSocket-Protocol: sample\r\n'
'\r\n' +
_TEST_CHALLENGE_RESPONSE)
_BAD_REQUESTS = (
( # HTTP request
80,
'GET',
'/demo',
{
'Host': 'www.google.com',
'User-Agent': 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5;'
' en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3'
' GTB6 GTBA',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,'
'*/*;q=0.8',
'Accept-Language': 'en-us,en;q=0.5',
'Accept-Encoding': 'gzip,deflate',
'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
'Keep-Alive': '300',
'Connection': 'keep-alive',
}),
( # Wrong method
80,
'POST',
'/demo',
{
'Host': 'example.com',
'Connection': 'Upgrade',
'Sec-WebSocket-Key2': _TEST_KEY2,
'Sec-WebSocket-Protocol': 'sample',
'Upgrade': 'WebSocket',
'Sec-WebSocket-Key1': _TEST_KEY1,
'Origin': 'http://example.com',
},
_TEST_KEY3),
( # Missing Upgrade
80,
'GET',
'/demo',
{
'Host': 'example.com',
'Connection': 'Upgrade',
'Sec-WebSocket-Key2': _TEST_KEY2,
'Sec-WebSocket-Protocol': 'sample',
'Sec-WebSocket-Key1': _TEST_KEY1,
'Origin': 'http://example.com',
},
_TEST_KEY3),
( # Wrong Upgrade
80,
'GET',
'/demo',
{
'Host': 'example.com',
'Connection': 'Upgrade',
'Sec-WebSocket-Key2': _TEST_KEY2,
'Sec-WebSocket-Protocol': 'sample',
'Upgrade': 'NonWebSocket',
'Sec-WebSocket-Key1': _TEST_KEY1,
'Origin': 'http://example.com',
},
_TEST_KEY3),
( # Empty WebSocket-Protocol
80,
'GET',
'/demo',
{
'Host': 'example.com',
'Connection': 'Upgrade',
'Sec-WebSocket-Key2': _TEST_KEY2,
'Sec-WebSocket-Protocol': '',
'Upgrade': 'WebSocket',
'Sec-WebSocket-Key1': _TEST_KEY1,
'Origin': 'http://example.com',
},
_TEST_KEY3),
( # Wrong port number format
80,
'GET',
'/demo',
{
'Host': 'example.com:0x50',
'Connection': 'Upgrade',
'Sec-WebSocket-Key2': _TEST_KEY2,
'Sec-WebSocket-Protocol': 'sample',
'Upgrade': 'WebSocket',
'Sec-WebSocket-Key1': _TEST_KEY1,
'Origin': 'http://example.com',
},
_TEST_KEY3),
( # Header/connection port mismatch
8080,
'GET',
'/demo',
{
'Host': 'example.com',
'Connection': 'Upgrade',
'Sec-WebSocket-Key2': _TEST_KEY2,
'Sec-WebSocket-Protocol': 'sample',
'Upgrade': 'WebSocket',
'Sec-WebSocket-Key1': _TEST_KEY1,
'Origin': 'http://example.com',
},
_TEST_KEY3),
( # Illegal WebSocket-Protocol
80,
'GET',
'/demo',
{
'Host': 'example.com',
'Connection': 'Upgrade',
'Sec-WebSocket-Key2': _TEST_KEY2,
'Sec-WebSocket-Protocol': 'illegal\x09protocol',
'Upgrade': 'WebSocket',
'Sec-WebSocket-Key1': _TEST_KEY1,
'Origin': 'http://example.com',
},
_TEST_KEY3),
)
def _create_request(request_def):
data = ''
if len(request_def) > 4:
data = request_def[4]
conn = mock.MockConn(data)
conn.local_addr = ('0.0.0.0', request_def[0])
return mock.MockRequest(
method=request_def[1],
uri=request_def[2],
headers_in=request_def[3],
connection=conn)
def _create_get_memorized_lines(lines):
"""Creates a function that returns the given string."""
def get_memorized_lines():
return lines
return get_memorized_lines
def _create_requests_with_lines(request_lines_set):
requests = []
for lines in request_lines_set:
request = _create_request(_GOOD_REQUEST)
request.connection.get_memorized_lines = _create_get_memorized_lines(
lines)
requests.append(request)
return requests
class HyBi00HandshakerTest(unittest.TestCase):
def test_good_request_default_port(self):
request = _create_request(_GOOD_REQUEST)
handshaker = Handshaker(request, mock.MockDispatcher())
handshaker.do_handshake()
self.assertEqual(_GOOD_RESPONSE_DEFAULT_PORT,
request.connection.written_data())
self.assertEqual('/demo', request.ws_resource)
self.assertEqual('http://example.com', request.ws_origin)
self.assertEqual('ws://example.com/demo', request.ws_location)
self.assertEqual('sample', request.ws_protocol)
def test_good_request_capitalized_header_values(self):
request = _create_request(_GOOD_REQUEST_CAPITALIZED_HEADER_VALUES)
handshaker = Handshaker(request, mock.MockDispatcher())
handshaker.do_handshake()
self.assertEqual(_GOOD_RESPONSE_DEFAULT_PORT,
request.connection.written_data())
def test_good_request_case_mixed_header_names(self):
request = _create_request(_GOOD_REQUEST_CASE_MIXED_HEADER_NAMES)
handshaker = Handshaker(request, mock.MockDispatcher())
handshaker.do_handshake()
self.assertEqual(_GOOD_RESPONSE_DEFAULT_PORT,
request.connection.written_data())
def test_good_request_secure_default_port(self):
request = _create_request(_GOOD_REQUEST)
request.connection.local_addr = ('0.0.0.0', 443)
request.is_https_ = True
handshaker = Handshaker(request, mock.MockDispatcher())
handshaker.do_handshake()
self.assertEqual(_GOOD_RESPONSE_SECURE,
request.connection.written_data())
self.assertEqual('sample', request.ws_protocol)
def test_good_request_nondefault_port(self):
request = _create_request(_GOOD_REQUEST_NONDEFAULT_PORT)
handshaker = Handshaker(request,
mock.MockDispatcher())
handshaker.do_handshake()
self.assertEqual(_GOOD_RESPONSE_NONDEFAULT_PORT,
request.connection.written_data())
self.assertEqual('sample', request.ws_protocol)
def test_good_request_secure_non_default_port(self):
request = _create_request(_GOOD_REQUEST_NONDEFAULT_PORT)
request.is_https_ = True
handshaker = Handshaker(request, mock.MockDispatcher())
handshaker.do_handshake()
self.assertEqual(_GOOD_RESPONSE_SECURE_NONDEF,
request.connection.written_data())
self.assertEqual('sample', request.ws_protocol)
def test_good_request_default_no_protocol(self):
request = _create_request(_GOOD_REQUEST_NO_PROTOCOL)
handshaker = Handshaker(request, mock.MockDispatcher())
handshaker.do_handshake()
self.assertEqual(_GOOD_RESPONSE_NO_PROTOCOL,
request.connection.written_data())
self.assertEqual(None, request.ws_protocol)
def test_good_request_optional_headers(self):
request = _create_request(_GOOD_REQUEST_WITH_OPTIONAL_HEADERS)
handshaker = Handshaker(request, mock.MockDispatcher())
handshaker.do_handshake()
self.assertEqual('AValue',
request.headers_in['AKey'])
self.assertEqual('',
request.headers_in['EmptyValue'])
def test_good_request_with_nonprintable_key(self):
request = _create_request(_GOOD_REQUEST_WITH_NONPRINTABLE_KEY)
handshaker = Handshaker(request, mock.MockDispatcher())
handshaker.do_handshake()
self.assertEqual(_GOOD_RESPONSE_WITH_NONPRINTABLE_KEY,
request.connection.written_data())
self.assertEqual('sample', request.ws_protocol)
def test_good_request_with_query_part(self):
request = _create_request(_GOOD_REQUEST_WITH_QUERY_PART)
handshaker = Handshaker(request, mock.MockDispatcher())
handshaker.do_handshake()
self.assertEqual(_GOOD_RESPONSE_WITH_QUERY_PART,
request.connection.written_data())
self.assertEqual('ws://example.com/demo?e=mc2', request.ws_location)
def test_bad_requests(self):
for request in map(_create_request, _BAD_REQUESTS):
handshaker = Handshaker(request, mock.MockDispatcher())
self.assertRaises(HandshakeException, handshaker.do_handshake)
class HyBi00ValidateSubprotocolTest(unittest.TestCase):
def test_validate_subprotocol(self):
# should succeed.
_validate_subprotocol('sample')
_validate_subprotocol('Sample')
_validate_subprotocol('sample\x7eprotocol')
_validate_subprotocol('sample\x20protocol')
# should fail.
self.assertRaises(HandshakeException,
_validate_subprotocol,
'')
self.assertRaises(HandshakeException,
_validate_subprotocol,
'sample\x19protocol')
self.assertRaises(HandshakeException,
_validate_subprotocol,
'sample\x7fprotocol')
self.assertRaises(HandshakeException,
_validate_subprotocol,
# "Japan" in Japanese
u'\u65e5\u672c')
if __name__ == '__main__':
unittest.main()
# vi:sts=4 sw=4 et
| mpl-2.0 |
spring01/libPSI | doc/sphinxman/separate_userprogman.py | 1 | 2530 | #!/usr/bin/python
import sys
import os
import glob
DriverPath = ''
if (len(sys.argv) == 2):
DriverPath = sys.argv[1] + '/'
def separate_documents():
bhtmlall = False
bhtmluser = False
bhtmlprog = False
blatexuser = False
blatexprog = False
for line in ftemplate.readlines():
if line.startswith('.. #####'):
sline = line.split()
if (sline[2] == 'HTML-ALL') and (sline[3] == 'START'): bhtmlall = True
if (sline[2] == 'HTML-ALL') and (sline[3] == 'STOP'): bhtmlall = False
if (sline[2] == 'HTML-USER') and (sline[3] == 'START'): bhtmluser = True
if (sline[2] == 'HTML-USER') and (sline[3] == 'STOP'): bhtmluser = False
if (sline[2] == 'HTML-PROG') and (sline[3] == 'START'): bhtmlprog = True
if (sline[2] == 'HTML-PROG') and (sline[3] == 'STOP'): bhtmlprog = False
if (sline[2] == 'LATEX-USER') and (sline[3] == 'START'): blatexuser = True
if (sline[2] == 'LATEX-USER') and (sline[3] == 'STOP'): blatexuser = False
if (sline[2] == 'LATEX-PROG') and (sline[3] == 'START'): blatexprog = True
if (sline[2] == 'LATEX-PROG') and (sline[3] == 'STOP'): blatexprog = False
else:
if bhtmlall: fhtmlall.write(line)
if bhtmluser: fhtmluser.write(line)
if bhtmlprog: fhtmlprog.write(line)
if blatexuser: flatexuser.write(line)
if blatexprog: flatexprog.write(line)
ftemplate.close()
fhtmlall.close()
fhtmluser.close()
fhtmlprog.close()
flatexuser.close()
flatexprog.close()
# Partition template_index.rst to form index.rst
ftemplate = open(DriverPath + 'source/template_index.rst', 'r')
fhtmlall = open('source/autodoc_index_html.rst', 'w')
fhtmluser = open('source/autodoc_index_htmluser.rst', 'w')
fhtmlprog = open('source/autodoc_index_htmlprog.rst', 'w')
flatexuser = open('source/autodoc_index_latexuser.rst', 'w')
flatexprog = open('source/autodoc_index_latexprog.rst', 'w')
separate_documents()
# Partition template_appendices.rst to form appendices.rst
ftemplate = open(DriverPath + 'source/template_appendices.rst', 'r')
fhtmlall = open('source/autodoc_appendices_html.rst', 'w')
fhtmluser = open('source/autodoc_appendices_htmluser.rst', 'w')
fhtmlprog = open('source/autodoc_appendices_htmlprog.rst', 'w')
flatexuser = open('source/autodoc_appendices_latexuser.rst', 'w')
flatexprog = open('source/autodoc_appendices_latexprog.rst', 'w')
separate_documents()
| gpl-2.0 |
EzyInsights/Diamond | src/diamond/handler/hostedgraphite.py | 58 | 2501 | # coding=utf-8
"""
[Hosted Graphite](https://www.hostedgraphite.com/) is the powerful open-source
application metrics system used by hundreds of companies. We take away the
headaches of scaling, maintenance, and upgrades and let you do what you do
best - write great software.
#### Configuration
Enable this handler
* handlers = diamond.handler.hostedgraphite.HostedGraphiteHandler,
* apikey = API_KEY
"""
from Handler import Handler
from graphite import GraphiteHandler
class HostedGraphiteHandler(Handler):
def __init__(self, config=None):
"""
Create a new instance of the HostedGraphiteHandler class
"""
# Initialize Handler
Handler.__init__(self, config)
self.key = self.config['apikey'].lower().strip()
self.graphite = GraphiteHandler(self.config)
def get_default_config_help(self):
"""
Returns the help text for the configuration options for this handler
"""
config = super(HostedGraphiteHandler, self).get_default_config_help()
config.update({
'apikey': 'Api key to use',
'host': 'Hostname',
'port': 'Port',
'proto': 'udp or tcp',
'timeout': '',
'batch': 'How many to store before sending to the graphite server',
'max_backlog_multiplier': 'how many batches to store before trimming', # NOQA
'trim_backlog_multiplier': 'Trim down how many batches',
})
return config
def get_default_config(self):
"""
Return the default config for the handler
"""
config = super(HostedGraphiteHandler, self).get_default_config()
config.update({
'apikey': '',
'host': 'carbon.hostedgraphite.com',
'port': 2003,
'proto': 'tcp',
'timeout': 15,
'batch': 1,
'max_backlog_multiplier': 5,
'trim_backlog_multiplier': 4,
})
return config
def process(self, metric):
"""
Process a metric by sending it to graphite
"""
metric = self.key + '.' + str(metric)
self.graphite.process(metric)
def _process(self, metric):
"""
Process a metric by sending it to graphite
"""
metric = self.key + '.' + str(metric)
self.graphite._process(metric)
def _flush(self):
self.graphite._flush()
def flush(self):
self.graphite.flush()
| mit |
AlericInglewood/3p-google-breakpad | src/third_party/protobuf/protobuf/gtest/test/gtest_shuffle_test.py | 3023 | 12549 | #!/usr/bin/env python
#
# Copyright 2009 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.
"""Verifies that test shuffling works."""
__author__ = 'wan@google.com (Zhanyong Wan)'
import os
import gtest_test_utils
# Command to run the gtest_shuffle_test_ program.
COMMAND = gtest_test_utils.GetTestExecutablePath('gtest_shuffle_test_')
# The environment variables for test sharding.
TOTAL_SHARDS_ENV_VAR = 'GTEST_TOTAL_SHARDS'
SHARD_INDEX_ENV_VAR = 'GTEST_SHARD_INDEX'
TEST_FILTER = 'A*.A:A*.B:C*'
ALL_TESTS = []
ACTIVE_TESTS = []
FILTERED_TESTS = []
SHARDED_TESTS = []
SHUFFLED_ALL_TESTS = []
SHUFFLED_ACTIVE_TESTS = []
SHUFFLED_FILTERED_TESTS = []
SHUFFLED_SHARDED_TESTS = []
def AlsoRunDisabledTestsFlag():
return '--gtest_also_run_disabled_tests'
def FilterFlag(test_filter):
return '--gtest_filter=%s' % (test_filter,)
def RepeatFlag(n):
return '--gtest_repeat=%s' % (n,)
def ShuffleFlag():
return '--gtest_shuffle'
def RandomSeedFlag(n):
return '--gtest_random_seed=%s' % (n,)
def RunAndReturnOutput(extra_env, args):
"""Runs the test program and returns its output."""
environ_copy = os.environ.copy()
environ_copy.update(extra_env)
return gtest_test_utils.Subprocess([COMMAND] + args, env=environ_copy).output
def GetTestsForAllIterations(extra_env, args):
"""Runs the test program and returns a list of test lists.
Args:
extra_env: a map from environment variables to their values
args: command line flags to pass to gtest_shuffle_test_
Returns:
A list where the i-th element is the list of tests run in the i-th
test iteration.
"""
test_iterations = []
for line in RunAndReturnOutput(extra_env, args).split('\n'):
if line.startswith('----'):
tests = []
test_iterations.append(tests)
elif line.strip():
tests.append(line.strip()) # 'TestCaseName.TestName'
return test_iterations
def GetTestCases(tests):
"""Returns a list of test cases in the given full test names.
Args:
tests: a list of full test names
Returns:
A list of test cases from 'tests', in their original order.
Consecutive duplicates are removed.
"""
test_cases = []
for test in tests:
test_case = test.split('.')[0]
if not test_case in test_cases:
test_cases.append(test_case)
return test_cases
def CalculateTestLists():
"""Calculates the list of tests run under different flags."""
if not ALL_TESTS:
ALL_TESTS.extend(
GetTestsForAllIterations({}, [AlsoRunDisabledTestsFlag()])[0])
if not ACTIVE_TESTS:
ACTIVE_TESTS.extend(GetTestsForAllIterations({}, [])[0])
if not FILTERED_TESTS:
FILTERED_TESTS.extend(
GetTestsForAllIterations({}, [FilterFlag(TEST_FILTER)])[0])
if not SHARDED_TESTS:
SHARDED_TESTS.extend(
GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3',
SHARD_INDEX_ENV_VAR: '1'},
[])[0])
if not SHUFFLED_ALL_TESTS:
SHUFFLED_ALL_TESTS.extend(GetTestsForAllIterations(
{}, [AlsoRunDisabledTestsFlag(), ShuffleFlag(), RandomSeedFlag(1)])[0])
if not SHUFFLED_ACTIVE_TESTS:
SHUFFLED_ACTIVE_TESTS.extend(GetTestsForAllIterations(
{}, [ShuffleFlag(), RandomSeedFlag(1)])[0])
if not SHUFFLED_FILTERED_TESTS:
SHUFFLED_FILTERED_TESTS.extend(GetTestsForAllIterations(
{}, [ShuffleFlag(), RandomSeedFlag(1), FilterFlag(TEST_FILTER)])[0])
if not SHUFFLED_SHARDED_TESTS:
SHUFFLED_SHARDED_TESTS.extend(
GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3',
SHARD_INDEX_ENV_VAR: '1'},
[ShuffleFlag(), RandomSeedFlag(1)])[0])
class GTestShuffleUnitTest(gtest_test_utils.TestCase):
"""Tests test shuffling."""
def setUp(self):
CalculateTestLists()
def testShufflePreservesNumberOfTests(self):
self.assertEqual(len(ALL_TESTS), len(SHUFFLED_ALL_TESTS))
self.assertEqual(len(ACTIVE_TESTS), len(SHUFFLED_ACTIVE_TESTS))
self.assertEqual(len(FILTERED_TESTS), len(SHUFFLED_FILTERED_TESTS))
self.assertEqual(len(SHARDED_TESTS), len(SHUFFLED_SHARDED_TESTS))
def testShuffleChangesTestOrder(self):
self.assert_(SHUFFLED_ALL_TESTS != ALL_TESTS, SHUFFLED_ALL_TESTS)
self.assert_(SHUFFLED_ACTIVE_TESTS != ACTIVE_TESTS, SHUFFLED_ACTIVE_TESTS)
self.assert_(SHUFFLED_FILTERED_TESTS != FILTERED_TESTS,
SHUFFLED_FILTERED_TESTS)
self.assert_(SHUFFLED_SHARDED_TESTS != SHARDED_TESTS,
SHUFFLED_SHARDED_TESTS)
def testShuffleChangesTestCaseOrder(self):
self.assert_(GetTestCases(SHUFFLED_ALL_TESTS) != GetTestCases(ALL_TESTS),
GetTestCases(SHUFFLED_ALL_TESTS))
self.assert_(
GetTestCases(SHUFFLED_ACTIVE_TESTS) != GetTestCases(ACTIVE_TESTS),
GetTestCases(SHUFFLED_ACTIVE_TESTS))
self.assert_(
GetTestCases(SHUFFLED_FILTERED_TESTS) != GetTestCases(FILTERED_TESTS),
GetTestCases(SHUFFLED_FILTERED_TESTS))
self.assert_(
GetTestCases(SHUFFLED_SHARDED_TESTS) != GetTestCases(SHARDED_TESTS),
GetTestCases(SHUFFLED_SHARDED_TESTS))
def testShuffleDoesNotRepeatTest(self):
for test in SHUFFLED_ALL_TESTS:
self.assertEqual(1, SHUFFLED_ALL_TESTS.count(test),
'%s appears more than once' % (test,))
for test in SHUFFLED_ACTIVE_TESTS:
self.assertEqual(1, SHUFFLED_ACTIVE_TESTS.count(test),
'%s appears more than once' % (test,))
for test in SHUFFLED_FILTERED_TESTS:
self.assertEqual(1, SHUFFLED_FILTERED_TESTS.count(test),
'%s appears more than once' % (test,))
for test in SHUFFLED_SHARDED_TESTS:
self.assertEqual(1, SHUFFLED_SHARDED_TESTS.count(test),
'%s appears more than once' % (test,))
def testShuffleDoesNotCreateNewTest(self):
for test in SHUFFLED_ALL_TESTS:
self.assert_(test in ALL_TESTS, '%s is an invalid test' % (test,))
for test in SHUFFLED_ACTIVE_TESTS:
self.assert_(test in ACTIVE_TESTS, '%s is an invalid test' % (test,))
for test in SHUFFLED_FILTERED_TESTS:
self.assert_(test in FILTERED_TESTS, '%s is an invalid test' % (test,))
for test in SHUFFLED_SHARDED_TESTS:
self.assert_(test in SHARDED_TESTS, '%s is an invalid test' % (test,))
def testShuffleIncludesAllTests(self):
for test in ALL_TESTS:
self.assert_(test in SHUFFLED_ALL_TESTS, '%s is missing' % (test,))
for test in ACTIVE_TESTS:
self.assert_(test in SHUFFLED_ACTIVE_TESTS, '%s is missing' % (test,))
for test in FILTERED_TESTS:
self.assert_(test in SHUFFLED_FILTERED_TESTS, '%s is missing' % (test,))
for test in SHARDED_TESTS:
self.assert_(test in SHUFFLED_SHARDED_TESTS, '%s is missing' % (test,))
def testShuffleLeavesDeathTestsAtFront(self):
non_death_test_found = False
for test in SHUFFLED_ACTIVE_TESTS:
if 'DeathTest.' in test:
self.assert_(not non_death_test_found,
'%s appears after a non-death test' % (test,))
else:
non_death_test_found = True
def _VerifyTestCasesDoNotInterleave(self, tests):
test_cases = []
for test in tests:
[test_case, _] = test.split('.')
if test_cases and test_cases[-1] != test_case:
test_cases.append(test_case)
self.assertEqual(1, test_cases.count(test_case),
'Test case %s is not grouped together in %s' %
(test_case, tests))
def testShuffleDoesNotInterleaveTestCases(self):
self._VerifyTestCasesDoNotInterleave(SHUFFLED_ALL_TESTS)
self._VerifyTestCasesDoNotInterleave(SHUFFLED_ACTIVE_TESTS)
self._VerifyTestCasesDoNotInterleave(SHUFFLED_FILTERED_TESTS)
self._VerifyTestCasesDoNotInterleave(SHUFFLED_SHARDED_TESTS)
def testShuffleRestoresOrderAfterEachIteration(self):
# Get the test lists in all 3 iterations, using random seed 1, 2,
# and 3 respectively. Google Test picks a different seed in each
# iteration, and this test depends on the current implementation
# picking successive numbers. This dependency is not ideal, but
# makes the test much easier to write.
[tests_in_iteration1, tests_in_iteration2, tests_in_iteration3] = (
GetTestsForAllIterations(
{}, [ShuffleFlag(), RandomSeedFlag(1), RepeatFlag(3)]))
# Make sure running the tests with random seed 1 gets the same
# order as in iteration 1 above.
[tests_with_seed1] = GetTestsForAllIterations(
{}, [ShuffleFlag(), RandomSeedFlag(1)])
self.assertEqual(tests_in_iteration1, tests_with_seed1)
# Make sure running the tests with random seed 2 gets the same
# order as in iteration 2 above. Success means that Google Test
# correctly restores the test order before re-shuffling at the
# beginning of iteration 2.
[tests_with_seed2] = GetTestsForAllIterations(
{}, [ShuffleFlag(), RandomSeedFlag(2)])
self.assertEqual(tests_in_iteration2, tests_with_seed2)
# Make sure running the tests with random seed 3 gets the same
# order as in iteration 3 above. Success means that Google Test
# correctly restores the test order before re-shuffling at the
# beginning of iteration 3.
[tests_with_seed3] = GetTestsForAllIterations(
{}, [ShuffleFlag(), RandomSeedFlag(3)])
self.assertEqual(tests_in_iteration3, tests_with_seed3)
def testShuffleGeneratesNewOrderInEachIteration(self):
[tests_in_iteration1, tests_in_iteration2, tests_in_iteration3] = (
GetTestsForAllIterations(
{}, [ShuffleFlag(), RandomSeedFlag(1), RepeatFlag(3)]))
self.assert_(tests_in_iteration1 != tests_in_iteration2,
tests_in_iteration1)
self.assert_(tests_in_iteration1 != tests_in_iteration3,
tests_in_iteration1)
self.assert_(tests_in_iteration2 != tests_in_iteration3,
tests_in_iteration2)
def testShuffleShardedTestsPreservesPartition(self):
# If we run M tests on N shards, the same M tests should be run in
# total, regardless of the random seeds used by the shards.
[tests1] = GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3',
SHARD_INDEX_ENV_VAR: '0'},
[ShuffleFlag(), RandomSeedFlag(1)])
[tests2] = GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3',
SHARD_INDEX_ENV_VAR: '1'},
[ShuffleFlag(), RandomSeedFlag(20)])
[tests3] = GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3',
SHARD_INDEX_ENV_VAR: '2'},
[ShuffleFlag(), RandomSeedFlag(25)])
sorted_sharded_tests = tests1 + tests2 + tests3
sorted_sharded_tests.sort()
sorted_active_tests = []
sorted_active_tests.extend(ACTIVE_TESTS)
sorted_active_tests.sort()
self.assertEqual(sorted_active_tests, sorted_sharded_tests)
if __name__ == '__main__':
gtest_test_utils.Main()
| bsd-3-clause |
fitzgen/servo | tests/wpt/css-tests/tools/pywebsocket/src/test/test_handshake_hybi.py | 413 | 22552 | #!/usr/bin/env python
#
# Copyright 2011, 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.
"""Tests for handshake module."""
import unittest
import set_sys_path # Update sys.path to locate mod_pywebsocket module.
from mod_pywebsocket import common
from mod_pywebsocket.handshake._base import AbortedByUserException
from mod_pywebsocket.handshake._base import HandshakeException
from mod_pywebsocket.handshake._base import VersionException
from mod_pywebsocket.handshake.hybi import Handshaker
import mock
class RequestDefinition(object):
"""A class for holding data for constructing opening handshake strings for
testing the opening handshake processor.
"""
def __init__(self, method, uri, headers):
self.method = method
self.uri = uri
self.headers = headers
def _create_good_request_def():
return RequestDefinition(
'GET', '/demo',
{'Host': 'server.example.com',
'Upgrade': 'websocket',
'Connection': 'Upgrade',
'Sec-WebSocket-Key': 'dGhlIHNhbXBsZSBub25jZQ==',
'Sec-WebSocket-Version': '13',
'Origin': 'http://example.com'})
def _create_request(request_def):
conn = mock.MockConn('')
return mock.MockRequest(
method=request_def.method,
uri=request_def.uri,
headers_in=request_def.headers,
connection=conn)
def _create_handshaker(request):
handshaker = Handshaker(request, mock.MockDispatcher())
return handshaker
class SubprotocolChoosingDispatcher(object):
"""A dispatcher for testing. This dispatcher sets the i-th subprotocol
of requested ones to ws_protocol where i is given on construction as index
argument. If index is negative, default_value will be set to ws_protocol.
"""
def __init__(self, index, default_value=None):
self.index = index
self.default_value = default_value
def do_extra_handshake(self, conn_context):
if self.index >= 0:
conn_context.ws_protocol = conn_context.ws_requested_protocols[
self.index]
else:
conn_context.ws_protocol = self.default_value
def transfer_data(self, conn_context):
pass
class HandshakeAbortedException(Exception):
pass
class AbortingDispatcher(object):
"""A dispatcher for testing. This dispatcher raises an exception in
do_extra_handshake to reject the request.
"""
def do_extra_handshake(self, conn_context):
raise HandshakeAbortedException('An exception to reject the request')
def transfer_data(self, conn_context):
pass
class AbortedByUserDispatcher(object):
"""A dispatcher for testing. This dispatcher raises an
AbortedByUserException in do_extra_handshake to reject the request.
"""
def do_extra_handshake(self, conn_context):
raise AbortedByUserException('An AbortedByUserException to reject the '
'request')
def transfer_data(self, conn_context):
pass
_EXPECTED_RESPONSE = (
'HTTP/1.1 101 Switching Protocols\r\n'
'Upgrade: websocket\r\n'
'Connection: Upgrade\r\n'
'Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\n\r\n')
class HandshakerTest(unittest.TestCase):
"""A unittest for draft-ietf-hybi-thewebsocketprotocol-06 and later
handshake processor.
"""
def test_do_handshake(self):
request = _create_request(_create_good_request_def())
dispatcher = mock.MockDispatcher()
handshaker = Handshaker(request, dispatcher)
handshaker.do_handshake()
self.assertTrue(dispatcher.do_extra_handshake_called)
self.assertEqual(
_EXPECTED_RESPONSE, request.connection.written_data())
self.assertEqual('/demo', request.ws_resource)
self.assertEqual('http://example.com', request.ws_origin)
self.assertEqual(None, request.ws_protocol)
self.assertEqual(None, request.ws_extensions)
self.assertEqual(common.VERSION_HYBI_LATEST, request.ws_version)
def test_do_handshake_with_extra_headers(self):
request_def = _create_good_request_def()
# Add headers not related to WebSocket opening handshake.
request_def.headers['FooKey'] = 'BarValue'
request_def.headers['EmptyKey'] = ''
request = _create_request(request_def)
handshaker = _create_handshaker(request)
handshaker.do_handshake()
self.assertEqual(
_EXPECTED_RESPONSE, request.connection.written_data())
def test_do_handshake_with_capitalized_value(self):
request_def = _create_good_request_def()
request_def.headers['upgrade'] = 'WEBSOCKET'
request = _create_request(request_def)
handshaker = _create_handshaker(request)
handshaker.do_handshake()
self.assertEqual(
_EXPECTED_RESPONSE, request.connection.written_data())
request_def = _create_good_request_def()
request_def.headers['Connection'] = 'UPGRADE'
request = _create_request(request_def)
handshaker = _create_handshaker(request)
handshaker.do_handshake()
self.assertEqual(
_EXPECTED_RESPONSE, request.connection.written_data())
def test_do_handshake_with_multiple_connection_values(self):
request_def = _create_good_request_def()
request_def.headers['Connection'] = 'Upgrade, keep-alive, , '
request = _create_request(request_def)
handshaker = _create_handshaker(request)
handshaker.do_handshake()
self.assertEqual(
_EXPECTED_RESPONSE, request.connection.written_data())
def test_aborting_handshake(self):
handshaker = Handshaker(
_create_request(_create_good_request_def()),
AbortingDispatcher())
# do_extra_handshake raises an exception. Check that it's not caught by
# do_handshake.
self.assertRaises(HandshakeAbortedException, handshaker.do_handshake)
def test_do_handshake_with_protocol(self):
request_def = _create_good_request_def()
request_def.headers['Sec-WebSocket-Protocol'] = 'chat, superchat'
request = _create_request(request_def)
handshaker = Handshaker(request, SubprotocolChoosingDispatcher(0))
handshaker.do_handshake()
EXPECTED_RESPONSE = (
'HTTP/1.1 101 Switching Protocols\r\n'
'Upgrade: websocket\r\n'
'Connection: Upgrade\r\n'
'Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\n'
'Sec-WebSocket-Protocol: chat\r\n\r\n')
self.assertEqual(EXPECTED_RESPONSE, request.connection.written_data())
self.assertEqual('chat', request.ws_protocol)
def test_do_handshake_protocol_not_in_request_but_in_response(self):
request_def = _create_good_request_def()
request = _create_request(request_def)
handshaker = Handshaker(
request, SubprotocolChoosingDispatcher(-1, 'foobar'))
# No request has been made but ws_protocol is set. HandshakeException
# must be raised.
self.assertRaises(HandshakeException, handshaker.do_handshake)
def test_do_handshake_with_protocol_no_protocol_selection(self):
request_def = _create_good_request_def()
request_def.headers['Sec-WebSocket-Protocol'] = 'chat, superchat'
request = _create_request(request_def)
handshaker = _create_handshaker(request)
# ws_protocol is not set. HandshakeException must be raised.
self.assertRaises(HandshakeException, handshaker.do_handshake)
def test_do_handshake_with_extensions(self):
request_def = _create_good_request_def()
request_def.headers['Sec-WebSocket-Extensions'] = (
'permessage-compress; method=deflate, unknown')
EXPECTED_RESPONSE = (
'HTTP/1.1 101 Switching Protocols\r\n'
'Upgrade: websocket\r\n'
'Connection: Upgrade\r\n'
'Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\n'
'Sec-WebSocket-Extensions: permessage-compress; method=deflate\r\n'
'\r\n')
request = _create_request(request_def)
handshaker = _create_handshaker(request)
handshaker.do_handshake()
self.assertEqual(EXPECTED_RESPONSE, request.connection.written_data())
self.assertEqual(1, len(request.ws_extensions))
extension = request.ws_extensions[0]
self.assertEqual(common.PERMESSAGE_COMPRESSION_EXTENSION,
extension.name())
self.assertEqual(['method'], extension.get_parameter_names())
self.assertEqual('deflate', extension.get_parameter_value('method'))
self.assertEqual(1, len(request.ws_extension_processors))
self.assertEqual(common.PERMESSAGE_COMPRESSION_EXTENSION,
request.ws_extension_processors[0].name())
def test_do_handshake_with_permessage_compress(self):
request_def = _create_good_request_def()
request_def.headers['Sec-WebSocket-Extensions'] = (
'permessage-compress; method=deflate')
request = _create_request(request_def)
handshaker = _create_handshaker(request)
handshaker.do_handshake()
self.assertEqual(1, len(request.ws_extensions))
self.assertEqual(common.PERMESSAGE_COMPRESSION_EXTENSION,
request.ws_extensions[0].name())
self.assertEqual(1, len(request.ws_extension_processors))
self.assertEqual(common.PERMESSAGE_COMPRESSION_EXTENSION,
request.ws_extension_processors[0].name())
def test_do_handshake_with_quoted_extensions(self):
request_def = _create_good_request_def()
request_def.headers['Sec-WebSocket-Extensions'] = (
'permessage-compress; method=deflate, , '
'unknown; e = "mc^2"; ma="\r\n \\\rf "; pv=nrt')
request = _create_request(request_def)
handshaker = _create_handshaker(request)
handshaker.do_handshake()
self.assertEqual(2, len(request.ws_requested_extensions))
first_extension = request.ws_requested_extensions[0]
self.assertEqual('permessage-compress', first_extension.name())
self.assertEqual(['method'], first_extension.get_parameter_names())
self.assertEqual('deflate',
first_extension.get_parameter_value('method'))
second_extension = request.ws_requested_extensions[1]
self.assertEqual('unknown', second_extension.name())
self.assertEqual(
['e', 'ma', 'pv'], second_extension.get_parameter_names())
self.assertEqual('mc^2', second_extension.get_parameter_value('e'))
self.assertEqual(' \rf ', second_extension.get_parameter_value('ma'))
self.assertEqual('nrt', second_extension.get_parameter_value('pv'))
def test_do_handshake_with_optional_headers(self):
request_def = _create_good_request_def()
request_def.headers['EmptyValue'] = ''
request_def.headers['AKey'] = 'AValue'
request = _create_request(request_def)
handshaker = _create_handshaker(request)
handshaker.do_handshake()
self.assertEqual(
'AValue', request.headers_in['AKey'])
self.assertEqual(
'', request.headers_in['EmptyValue'])
def test_abort_extra_handshake(self):
handshaker = Handshaker(
_create_request(_create_good_request_def()),
AbortedByUserDispatcher())
# do_extra_handshake raises an AbortedByUserException. Check that it's
# not caught by do_handshake.
self.assertRaises(AbortedByUserException, handshaker.do_handshake)
def test_do_handshake_with_mux_and_deflate_frame(self):
request_def = _create_good_request_def()
request_def.headers['Sec-WebSocket-Extensions'] = ('%s, %s' % (
common.MUX_EXTENSION,
common.DEFLATE_FRAME_EXTENSION))
request = _create_request(request_def)
handshaker = _create_handshaker(request)
handshaker.do_handshake()
# mux should be rejected.
self.assertEqual(1, len(request.ws_extensions))
self.assertEqual(common.DEFLATE_FRAME_EXTENSION,
request.ws_extensions[0].name())
self.assertEqual(2, len(request.ws_extension_processors))
self.assertEqual(common.MUX_EXTENSION,
request.ws_extension_processors[0].name())
self.assertEqual(common.DEFLATE_FRAME_EXTENSION,
request.ws_extension_processors[1].name())
self.assertFalse(hasattr(request, 'mux_processor'))
def test_do_handshake_with_deflate_frame_and_mux(self):
request_def = _create_good_request_def()
request_def.headers['Sec-WebSocket-Extensions'] = ('%s, %s' % (
common.DEFLATE_FRAME_EXTENSION,
common.MUX_EXTENSION))
request = _create_request(request_def)
handshaker = _create_handshaker(request)
handshaker.do_handshake()
# mux should be rejected.
self.assertEqual(1, len(request.ws_extensions))
first_extension = request.ws_extensions[0]
self.assertEqual(common.DEFLATE_FRAME_EXTENSION,
first_extension.name())
self.assertEqual(2, len(request.ws_extension_processors))
self.assertEqual(common.DEFLATE_FRAME_EXTENSION,
request.ws_extension_processors[0].name())
self.assertEqual(common.MUX_EXTENSION,
request.ws_extension_processors[1].name())
self.assertFalse(hasattr(request, 'mux'))
def test_do_handshake_with_permessage_compress_and_mux(self):
request_def = _create_good_request_def()
request_def.headers['Sec-WebSocket-Extensions'] = (
'%s; method=deflate, %s' % (
common.PERMESSAGE_COMPRESSION_EXTENSION,
common.MUX_EXTENSION))
request = _create_request(request_def)
handshaker = _create_handshaker(request)
handshaker.do_handshake()
self.assertEqual(1, len(request.ws_extensions))
self.assertEqual(common.MUX_EXTENSION,
request.ws_extensions[0].name())
self.assertEqual(2, len(request.ws_extension_processors))
self.assertEqual(common.PERMESSAGE_COMPRESSION_EXTENSION,
request.ws_extension_processors[0].name())
self.assertEqual(common.MUX_EXTENSION,
request.ws_extension_processors[1].name())
self.assertTrue(hasattr(request, 'mux_processor'))
self.assertTrue(request.mux_processor.is_active())
mux_extensions = request.mux_processor.extensions()
self.assertEqual(1, len(mux_extensions))
self.assertEqual(common.PERMESSAGE_COMPRESSION_EXTENSION,
mux_extensions[0].name())
def test_do_handshake_with_mux_and_permessage_compress(self):
request_def = _create_good_request_def()
request_def.headers['Sec-WebSocket-Extensions'] = (
'%s, %s; method=deflate' % (
common.MUX_EXTENSION,
common.PERMESSAGE_COMPRESSION_EXTENSION))
request = _create_request(request_def)
handshaker = _create_handshaker(request)
handshaker.do_handshake()
# mux should be rejected.
self.assertEqual(1, len(request.ws_extensions))
first_extension = request.ws_extensions[0]
self.assertEqual(common.PERMESSAGE_COMPRESSION_EXTENSION,
first_extension.name())
self.assertEqual(2, len(request.ws_extension_processors))
self.assertEqual(common.MUX_EXTENSION,
request.ws_extension_processors[0].name())
self.assertEqual(common.PERMESSAGE_COMPRESSION_EXTENSION,
request.ws_extension_processors[1].name())
self.assertFalse(hasattr(request, 'mux_processor'))
def test_bad_requests(self):
bad_cases = [
('HTTP request',
RequestDefinition(
'GET', '/demo',
{'Host': 'www.google.com',
'User-Agent':
'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5;'
' en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3'
' GTB6 GTBA',
'Accept':
'text/html,application/xhtml+xml,application/xml;q=0.9,'
'*/*;q=0.8',
'Accept-Language': 'en-us,en;q=0.5',
'Accept-Encoding': 'gzip,deflate',
'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
'Keep-Alive': '300',
'Connection': 'keep-alive'}), None, True)]
request_def = _create_good_request_def()
request_def.method = 'POST'
bad_cases.append(('Wrong method', request_def, None, True))
request_def = _create_good_request_def()
del request_def.headers['Host']
bad_cases.append(('Missing Host', request_def, None, True))
request_def = _create_good_request_def()
del request_def.headers['Upgrade']
bad_cases.append(('Missing Upgrade', request_def, None, True))
request_def = _create_good_request_def()
request_def.headers['Upgrade'] = 'nonwebsocket'
bad_cases.append(('Wrong Upgrade', request_def, None, True))
request_def = _create_good_request_def()
del request_def.headers['Connection']
bad_cases.append(('Missing Connection', request_def, None, True))
request_def = _create_good_request_def()
request_def.headers['Connection'] = 'Downgrade'
bad_cases.append(('Wrong Connection', request_def, None, True))
request_def = _create_good_request_def()
del request_def.headers['Sec-WebSocket-Key']
bad_cases.append(('Missing Sec-WebSocket-Key', request_def, 400, True))
request_def = _create_good_request_def()
request_def.headers['Sec-WebSocket-Key'] = (
'dGhlIHNhbXBsZSBub25jZQ==garbage')
bad_cases.append(('Wrong Sec-WebSocket-Key (with garbage on the tail)',
request_def, 400, True))
request_def = _create_good_request_def()
request_def.headers['Sec-WebSocket-Key'] = 'YQ==' # BASE64 of 'a'
bad_cases.append(
('Wrong Sec-WebSocket-Key (decoded value is not 16 octets long)',
request_def, 400, True))
request_def = _create_good_request_def()
# The last character right before == must be any of A, Q, w and g.
request_def.headers['Sec-WebSocket-Key'] = (
'AQIDBAUGBwgJCgsMDQ4PEC==')
bad_cases.append(
('Wrong Sec-WebSocket-Key (padding bits are not zero)',
request_def, 400, True))
request_def = _create_good_request_def()
request_def.headers['Sec-WebSocket-Key'] = (
'dGhlIHNhbXBsZSBub25jZQ==,dGhlIHNhbXBsZSBub25jZQ==')
bad_cases.append(
('Wrong Sec-WebSocket-Key (multiple values)',
request_def, 400, True))
request_def = _create_good_request_def()
del request_def.headers['Sec-WebSocket-Version']
bad_cases.append(('Missing Sec-WebSocket-Version', request_def, None,
True))
request_def = _create_good_request_def()
request_def.headers['Sec-WebSocket-Version'] = '3'
bad_cases.append(('Wrong Sec-WebSocket-Version', request_def, None,
False))
request_def = _create_good_request_def()
request_def.headers['Sec-WebSocket-Version'] = '13, 13'
bad_cases.append(('Wrong Sec-WebSocket-Version (multiple values)',
request_def, 400, True))
request_def = _create_good_request_def()
request_def.headers['Sec-WebSocket-Protocol'] = 'illegal\x09protocol'
bad_cases.append(('Illegal Sec-WebSocket-Protocol',
request_def, 400, True))
request_def = _create_good_request_def()
request_def.headers['Sec-WebSocket-Protocol'] = ''
bad_cases.append(('Empty Sec-WebSocket-Protocol',
request_def, 400, True))
for (case_name, request_def, expected_status,
expect_handshake_exception) in bad_cases:
request = _create_request(request_def)
handshaker = Handshaker(request, mock.MockDispatcher())
try:
handshaker.do_handshake()
self.fail('No exception thrown for \'%s\' case' % case_name)
except HandshakeException, e:
self.assertTrue(expect_handshake_exception)
self.assertEqual(expected_status, e.status)
except VersionException, e:
self.assertFalse(expect_handshake_exception)
if __name__ == '__main__':
unittest.main()
# vi:sts=4 sw=4 et
| mpl-2.0 |
StormTrooper/osmc | package/mediacenter-skin-next-osmc/files/usr/share/kodi/addons/script.module.unidecode/lib/unidecode/x00a.py | 252 | 4121 | data = (
'[?]', # 0x00
'[?]', # 0x01
'N', # 0x02
'[?]', # 0x03
'[?]', # 0x04
'a', # 0x05
'aa', # 0x06
'i', # 0x07
'ii', # 0x08
'u', # 0x09
'uu', # 0x0a
'[?]', # 0x0b
'[?]', # 0x0c
'[?]', # 0x0d
'[?]', # 0x0e
'ee', # 0x0f
'ai', # 0x10
'[?]', # 0x11
'[?]', # 0x12
'oo', # 0x13
'au', # 0x14
'k', # 0x15
'kh', # 0x16
'g', # 0x17
'gh', # 0x18
'ng', # 0x19
'c', # 0x1a
'ch', # 0x1b
'j', # 0x1c
'jh', # 0x1d
'ny', # 0x1e
'tt', # 0x1f
'tth', # 0x20
'dd', # 0x21
'ddh', # 0x22
'nn', # 0x23
't', # 0x24
'th', # 0x25
'd', # 0x26
'dh', # 0x27
'n', # 0x28
'[?]', # 0x29
'p', # 0x2a
'ph', # 0x2b
'b', # 0x2c
'bb', # 0x2d
'm', # 0x2e
'y', # 0x2f
'r', # 0x30
'[?]', # 0x31
'l', # 0x32
'll', # 0x33
'[?]', # 0x34
'v', # 0x35
'sh', # 0x36
'[?]', # 0x37
's', # 0x38
'h', # 0x39
'[?]', # 0x3a
'[?]', # 0x3b
'\'', # 0x3c
'[?]', # 0x3d
'aa', # 0x3e
'i', # 0x3f
'ii', # 0x40
'u', # 0x41
'uu', # 0x42
'[?]', # 0x43
'[?]', # 0x44
'[?]', # 0x45
'[?]', # 0x46
'ee', # 0x47
'ai', # 0x48
'[?]', # 0x49
'[?]', # 0x4a
'oo', # 0x4b
'au', # 0x4c
'', # 0x4d
'[?]', # 0x4e
'[?]', # 0x4f
'[?]', # 0x50
'[?]', # 0x51
'[?]', # 0x52
'[?]', # 0x53
'[?]', # 0x54
'[?]', # 0x55
'[?]', # 0x56
'[?]', # 0x57
'[?]', # 0x58
'khh', # 0x59
'ghh', # 0x5a
'z', # 0x5b
'rr', # 0x5c
'[?]', # 0x5d
'f', # 0x5e
'[?]', # 0x5f
'[?]', # 0x60
'[?]', # 0x61
'[?]', # 0x62
'[?]', # 0x63
'[?]', # 0x64
'[?]', # 0x65
'0', # 0x66
'1', # 0x67
'2', # 0x68
'3', # 0x69
'4', # 0x6a
'5', # 0x6b
'6', # 0x6c
'7', # 0x6d
'8', # 0x6e
'9', # 0x6f
'N', # 0x70
'H', # 0x71
'', # 0x72
'', # 0x73
'G.E.O.', # 0x74
'[?]', # 0x75
'[?]', # 0x76
'[?]', # 0x77
'[?]', # 0x78
'[?]', # 0x79
'[?]', # 0x7a
'[?]', # 0x7b
'[?]', # 0x7c
'[?]', # 0x7d
'[?]', # 0x7e
'[?]', # 0x7f
'[?]', # 0x80
'N', # 0x81
'N', # 0x82
'H', # 0x83
'[?]', # 0x84
'a', # 0x85
'aa', # 0x86
'i', # 0x87
'ii', # 0x88
'u', # 0x89
'uu', # 0x8a
'R', # 0x8b
'[?]', # 0x8c
'eN', # 0x8d
'[?]', # 0x8e
'e', # 0x8f
'ai', # 0x90
'oN', # 0x91
'[?]', # 0x92
'o', # 0x93
'au', # 0x94
'k', # 0x95
'kh', # 0x96
'g', # 0x97
'gh', # 0x98
'ng', # 0x99
'c', # 0x9a
'ch', # 0x9b
'j', # 0x9c
'jh', # 0x9d
'ny', # 0x9e
'tt', # 0x9f
'tth', # 0xa0
'dd', # 0xa1
'ddh', # 0xa2
'nn', # 0xa3
't', # 0xa4
'th', # 0xa5
'd', # 0xa6
'dh', # 0xa7
'n', # 0xa8
'[?]', # 0xa9
'p', # 0xaa
'ph', # 0xab
'b', # 0xac
'bh', # 0xad
'm', # 0xae
'ya', # 0xaf
'r', # 0xb0
'[?]', # 0xb1
'l', # 0xb2
'll', # 0xb3
'[?]', # 0xb4
'v', # 0xb5
'sh', # 0xb6
'ss', # 0xb7
's', # 0xb8
'h', # 0xb9
'[?]', # 0xba
'[?]', # 0xbb
'\'', # 0xbc
'\'', # 0xbd
'aa', # 0xbe
'i', # 0xbf
'ii', # 0xc0
'u', # 0xc1
'uu', # 0xc2
'R', # 0xc3
'RR', # 0xc4
'eN', # 0xc5
'[?]', # 0xc6
'e', # 0xc7
'ai', # 0xc8
'oN', # 0xc9
'[?]', # 0xca
'o', # 0xcb
'au', # 0xcc
'', # 0xcd
'[?]', # 0xce
'[?]', # 0xcf
'AUM', # 0xd0
'[?]', # 0xd1
'[?]', # 0xd2
'[?]', # 0xd3
'[?]', # 0xd4
'[?]', # 0xd5
'[?]', # 0xd6
'[?]', # 0xd7
'[?]', # 0xd8
'[?]', # 0xd9
'[?]', # 0xda
'[?]', # 0xdb
'[?]', # 0xdc
'[?]', # 0xdd
'[?]', # 0xde
'[?]', # 0xdf
'RR', # 0xe0
'[?]', # 0xe1
'[?]', # 0xe2
'[?]', # 0xe3
'[?]', # 0xe4
'[?]', # 0xe5
'0', # 0xe6
'1', # 0xe7
'2', # 0xe8
'3', # 0xe9
'4', # 0xea
'5', # 0xeb
'6', # 0xec
'7', # 0xed
'8', # 0xee
'9', # 0xef
'[?]', # 0xf0
'[?]', # 0xf1
'[?]', # 0xf2
'[?]', # 0xf3
'[?]', # 0xf4
'[?]', # 0xf5
'[?]', # 0xf6
'[?]', # 0xf7
'[?]', # 0xf8
'[?]', # 0xf9
'[?]', # 0xfa
'[?]', # 0xfb
'[?]', # 0xfc
'[?]', # 0xfd
'[?]', # 0xfe
)
| gpl-2.0 |
ryanfobel/microdrop | microdrop/app.py | 1 | 24616 | """
Copyright 2011-2016 Ryan Fobel and Christian Fobel
This file is part of MicroDrop.
MicroDrop is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
Foundation, either version 3 of the License, or
(at your option) any later version.
MicroDrop 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 MicroDrop. If not, see <http://www.gnu.org/licenses/>.
"""
import sys
import os
import re
import subprocess
try:
import cPickle as pickle
except ImportError:
import pickle
import logging
from logging import DEBUG, INFO, WARNING, ERROR, CRITICAL
import traceback
import gtk
from path_helpers import path
import yaml
from flatland import Integer, Form, String, Enum, Boolean
from pygtkhelpers.ui.extra_widgets import Filepath
from pygtkhelpers.ui.form_view_dialog import FormViewDialog
from . import plugin_manager
from .protocol import Step
from .config import Config
from .plugin_manager import (ExtensionPoint, IPlugin, SingletonPlugin,
implements, PluginGlobals)
from .plugin_helpers import AppDataController, get_plugin_info
from .logger import CustomHandler
from . import base_path
logger = logging.getLogger(__name__)
PluginGlobals.push_env('microdrop')
def parse_args(args=None):
"""Parses arguments, returns (options, args)."""
from argparse import ArgumentParser
if args is None:
args = sys.argv
parser = ArgumentParser(description='MicroDrop: graphical user interface '
'for the DropBot Digital Microfluidics control '
'system.')
parser.add_argument('-c', '--config', type=path, default=None)
args = parser.parse_args()
return args
def test(*args, **kwargs):
print 'args=%s\nkwargs=%s' % (args, kwargs)
class App(SingletonPlugin, AppDataController):
implements(IPlugin)
'''
INFO: <Plugin App 'microdrop.app'>
INFO: <Plugin ConfigController 'microdrop.gui.config_controller'>
INFO: <Plugin DmfDeviceController 'microdrop.gui.dmf_device_controller'>
INFO: <Plugin ExperimentLogController
'microdrop.gui.experiment_log_controller'>
INFO: <Plugin MainWindowController 'microdrop.gui.main_window_controller'>
INFO: <Plugin ProtocolController 'microdrop.gui.protocol_controller'>
INFO: <Plugin ProtocolGridController 'microdrop.gui.protocol_grid_controller'>
'''
core_plugins = ['microdrop.app', 'microdrop.gui.config_controller',
'microdrop.gui.dmf_device_controller',
'microdrop.gui.experiment_log_controller',
'microdrop.gui.main_window_controller',
'microdrop.gui.protocol_controller',
'microdrop.gui.protocol_grid_controller',
'wheelerlab.zmq_hub_plugin',
'wheelerlab.electrode_controller_plugin',
'wheelerlab.device_info_plugin']
AppFields = Form.of(
Integer.named('x').using(default=None, optional=True,
properties={'show_in_gui': False}),
Integer.named('y').using(default=None, optional=True,
properties={'show_in_gui': False}),
Integer.named('width').using(default=400, optional=True,
properties={'show_in_gui': False}),
Integer.named('height').using(default=500, optional=True,
properties={'show_in_gui': False}),
Enum.named('update_automatically' #pylint: disable-msg=E1101,E1120
).using(default=1, optional=True
).valued('auto-update',
'check for updates, but ask before installing',
'''don't check for updates'''),
String.named('server_url').using( #pylint: disable-msg=E1120
default='http://microfluidics.utoronto.ca/update',
optional=True, properties=dict(show_in_gui=False)),
Boolean.named('realtime_mode').using( #pylint: disable-msg=E1120
default=False, optional=True,
properties=dict(show_in_gui=False)),
Filepath.named('log_file').using( #pylint: disable-msg=E1120
default='', optional=True,
properties={'action': gtk.FILE_CHOOSER_ACTION_SAVE}),
Boolean.named('log_enabled').using( #pylint: disable-msg=E1120
default=False, optional=True),
Enum.named('log_level').using( #pylint: disable-msg=E1101, E1120
default='info', optional=True
).valued('debug', 'info', 'warning', 'error', 'critical'),
)
def __init__(self):
args = parse_args()
print 'Arguments: %s' % args
self.name = "microdrop.app"
# get the version number
self.version = ""
try:
raise Exception
version = subprocess.Popen(['git','describe'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE).communicate()[0].rstrip()
m = re.match('v(\d+)\.(\d+)-(\d+)', version)
self.version = "%s.%s.%s" % (m.group(1), m.group(2), m.group(3))
branch = subprocess.Popen(['git','rev-parse', '--abbrev-ref', 'HEAD'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE).communicate()[0].rstrip()
if branch.strip() != 'master':
self.version += "-%s" % branch
except:
import pkg_resources
version = pkg_resources.get_distribution('microdrop').version
dev = ('dev' in version)
self.version = re.sub('\.dev.*', '',
re.sub('post', '', version))
if dev:
self.version += "-dev"
self.realtime_mode = False
self.running = False
self.builder = gtk.Builder()
self.signals = {}
self.plugin_data = {}
# these members are initialized by plugins
self.experiment_log_controller = None
self.config_controller = None
self.dmf_device_controller = None
self.protocol_controller = None
self.main_window_controller = None
# Enable custom logging handler
logging.getLogger().addHandler(CustomHandler())
self.log_file_handler = None
# config model
try:
self.config = Config(args.config)
except IOError:
logging.error('Could not read configuration file, `%s`. Make sure'
' it exists and is readable.', args.config)
raise SystemExit(-1)
# set the log level
if self.name in self.config.data and ('log_level' in
self.config.data[self.name]):
self._set_log_level(self.config.data[self.name]['log_level'])
logger.info('MicroDrop version: %s', self.version)
logger.info('Running in working directory: %s', os.getcwd())
# Run post install hooks for freshly installed plugins.
# It is necessary to delay the execution of these hooks here due to
# Windows file locking preventing the deletion of files that are in use.
post_install_queue_path = \
path(self.config.data['plugins']['directory']) \
.joinpath('post_install_queue.yml')
if post_install_queue_path.isfile():
post_install_queue = yaml.load(post_install_queue_path.bytes())
post_install_queue = map(path, post_install_queue)
logger.info('[App] processing post install hooks.')
for p in post_install_queue[:]:
try:
info = get_plugin_info(p)
logger.info(" running post install hook for %s" %
info.plugin_name)
plugin_manager.post_install(p)
except Exception:
logging.info(''.join(traceback.format_exc()))
logging.error('Error running post-install hook for %s.',
p.name, exc_info=True)
finally:
post_install_queue.remove(p)
post_install_queue_path.write_bytes(yaml.dump(post_install_queue))
# Delete paths that were marked during the uninstallation of a plugin.
# It is necessary to delay the deletion until here due to Windows file
# locking preventing the deletion of files that are in use.
deletions_path = path(self.config.data['plugins']['directory'])\
.joinpath('requested_deletions.yml')
if deletions_path.isfile():
requested_deletions = yaml.load(deletions_path.bytes())
requested_deletions = map(path, requested_deletions)
logger.info('[App] processing requested deletions.')
for p in requested_deletions[:]:
try:
if p != p.abspath():
logger.info(' (warning) ignoring path %s since it '
'is not absolute', p)
continue
if p.isdir():
info = get_plugin_info(p)
if info:
logger.info(' deleting %s' % p)
cwd = os.getcwd()
os.chdir(p.parent)
try:
path(p.name).rmtree() #ignore_errors=True)
except Exception, why:
logger.warning('Error deleting path %s (%s)',
p, why)
raise
os.chdir(cwd)
requested_deletions.remove(p)
else: # if the directory doesn't exist, remove it from the
# list
requested_deletions.remove(p)
except (AssertionError,):
logger.info(' NOT deleting %s' % (p))
continue
except (Exception,):
logger.info(' NOT deleting %s' % (p))
continue
deletions_path.write_bytes(yaml.dump(requested_deletions))
rename_queue_path = path(self.config.data['plugins']['directory'])\
.joinpath('rename_queue.yml')
if rename_queue_path.isfile():
rename_queue = yaml.load(rename_queue_path.bytes())
requested_renames = [(path(src), path(dst)) for src, dst in rename_queue]
logger.info('[App] processing requested renames.')
remaining_renames = []
for src, dst in requested_renames:
try:
if src.exists():
src.rename(dst)
logger.info(' renamed %s -> %s' % (src, dst))
except (AssertionError,):
logger.info(' rename unsuccessful: %s -> %s' % (src, dst))
remaining_renames.append((str(src), str(dst)))
continue
rename_queue_path.write_bytes(yaml.dump(remaining_renames))
# dmf device
self.dmf_device = None
# protocol
self.protocol = None
def get_data(self, plugin_name):
logger.debug('[App] plugin_data=%s' % self.plugin_data)
data = self.plugin_data.get(plugin_name)
if data:
return data
else:
return {}
def set_data(self, plugin_name, data):
self.plugin_data[plugin_name] = data
def on_app_options_changed(self, plugin_name):
if plugin_name == self.name:
data = self.get_data(self.name)
if 'realtime_mode' in data:
if self.realtime_mode != data['realtime_mode']:
self.realtime_mode = data['realtime_mode']
if self.protocol_controller:
self.protocol_controller.run_step()
if 'log_file' in data and 'log_enabled' in data:
self.apply_log_file_config(data['log_file'],
data['log_enabled'])
if 'log_level' in data:
self._set_log_level(data['log_level'])
if 'width' in data and 'height' in data:
self.main_window_controller.view.resize(data['width'],
data['height'])
# allow window to resize before other signals are processed
while gtk.events_pending():
gtk.main_iteration()
if data.get('x') is not None and data.get('y') is not None:
self.main_window_controller.view.move(data['x'], data['y'])
# allow window to resize before other signals are processed
while gtk.events_pending():
gtk.main_iteration()
def apply_log_file_config(self, log_file, enabled):
if enabled and not log_file:
logger.error('Log file can only be enabled if a path is selected.')
return False
self.update_log_file()
return True
@property
def plugins(self):
return set(self.plugin_data.keys())
def plugin_name_lookup(self, name, re_pattern=False):
if not re_pattern:
return name
for plugin_name in self.plugins:
if re.search(name, plugin_name):
return plugin_name
return None
def _update_setting(self):
if not self.config['microdrop.app'].get('update_automatically', None):
self.config['microdrop.app']['update_automatically'] = \
'check for updates, but ask before installing'
return self.config['microdrop.app']['update_automatically']
def update_plugins(self):
update_setting = self._update_setting()
if update_setting == 'auto-update':
# Auto-update
update = True
force = True
logger.info('Auto-update')
elif update_setting == 'check for updates, but ask before installing':
# Check for updates, but ask before installing
update = True
force = False
logger.info('Check for updates, but ask before installing')
else:
logger.info('Updates disabled')
update = False
if update:
service = \
(plugin_manager
.get_service_instance_by_name('microdrop.gui'
'.plugin_manager_controller',
env='microdrop'))
if service.update_all_plugins(force=force):
logger.warning('Plugins have been updated. The application '
'must be restarted.')
if self.main_window_controller is not None:
self.main_window_controller.on_destroy(None)
else:
logger.info('Closing app after plugins auto-upgrade')
# Use return code of `5` to signal program should be
# restarted.
self.main_window_controller.on_destroy(None, return_code=5)
else:
logger.info('No plugins have been updated')
def run(self):
from .gui.dmf_device_controller import DEVICE_FILENAME
# set realtime mode to false on startup
if self.name in self.config.data and \
'realtime_mode' in self.config.data[self.name]:
self.config.data[self.name]['realtime_mode'] = False
plugin_manager.emit_signal('on_plugin_enable')
log_file = self.get_app_values()['log_file']
if not log_file:
self.set_app_values({'log_file':
path(self.config['data_dir'])
.joinpath('microdrop.log')})
plugin_manager.load_plugins(self.config['plugins']['directory'])
self.update_log_file()
logger.info('User data directory: %s' % self.config['data_dir'])
logger.info('Plugins directory: %s' %
self.config['plugins']['directory'])
logger.info('Devices directory: %s' % self.get_device_directory())
FormViewDialog.default_parent = self.main_window_controller.view
self.builder.connect_signals(self.signals)
self.update_plugins()
observers = {}
# Enable plugins according to schedule requests
for package_name in self.config['plugins']['enabled']:
try:
service = plugin_manager. \
get_service_instance_by_package_name(package_name)
observers[service.name] = service
except Exception, e:
self.config['plugins']['enabled'].remove(package_name)
logger.error(e, exc_info=True)
schedule = plugin_manager.get_schedule(observers, "on_plugin_enable")
# Load optional plugins marked as enabled in config
for p in schedule:
try:
plugin_manager.enable(p)
except KeyError:
logger.warning('Requested plugin (%s) is not available.\n\n'
'Please check that it exists in the plugins '
'directory:\n\n %s' %
(p, self.config['plugins']['directory']),
exc_info=True)
plugin_manager.log_summary()
self.experiment_log = None
# save the protocol name from the config file because it is
# automatically overwritten when we load a new device
protocol_name = self.config['protocol']['name']
# if there is no device specified in the config file, try choosing one
# from the device directory by default
device_directory = path(self.get_device_directory())
if not self.config['dmf_device']['name']:
try:
self.config['dmf_device']['name'] = \
device_directory.dirs()[0].name
except:
pass
# load the device from the config file
if self.config['dmf_device']['name']:
if device_directory:
device_path = os.path.join(device_directory,
self.config['dmf_device']['name'],
DEVICE_FILENAME)
self.dmf_device_controller.load_device(device_path)
# if we successfully loaded a device
if self.dmf_device:
# reapply the protocol name to the config file
self.config['protocol']['name'] = protocol_name
# load the protocol
if self.config['protocol']['name']:
directory = self.get_device_directory()
if directory:
filename = os.path.join(directory,
self.config['dmf_device']['name'],
"protocols",
self.config['protocol']['name'])
self.protocol_controller.load_protocol(filename)
data = self.get_data("microdrop.app")
x = data.get('x', None)
y = data.get('y', None)
width = data.get('width', 400)
height = data.get('height', 600)
self.main_window_controller.view.resize(width, height)
if x is not None and y is not None:
self.main_window_controller.view.move(x, y)
plugin_manager.emit_signal('on_gui_ready')
self.main_window_controller.main()
def _set_log_level(self, level):
if level=='debug':
logger.setLevel(DEBUG)
elif level=='info':
logger.setLevel(INFO)
elif level=='warning':
logger.setLevel(WARNING)
elif level=='error':
logger.setLevel(ERROR)
elif level=='critical':
logger.setLevel(CRITICAL)
else:
raise TypeError
def _set_log_file_handler(self, log_file):
if self.log_file_handler:
self._destroy_log_file_handler()
try:
self.log_file_handler = (logging
.FileHandler(log_file,
disable_existing_loggers
=False))
except TypeError:
# Assume old version of `logging` module without support for
# `disable_existing_loggers` keyword argument.
self.log_file_handler = logging.FileHandler(log_file)
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
self.log_file_handler.setFormatter(formatter)
logger.addHandler(self.log_file_handler)
logger.info('[App] added log_file_handler: %s' % log_file)
def _destroy_log_file_handler(self):
if self.log_file_handler is None:
return
logger.info('[App] closing log_file_handler')
self.log_file_handler.close()
del self.log_file_handler
self.log_file_handler = None
def update_log_file(self):
plugin_name = 'microdrop.app'
values = AppDataController.get_plugin_app_values(plugin_name)
logger.debug('[App] update_log_file %s' % values)
required = set(['log_enabled', 'log_file'])
if values is None or required.intersection(values.keys()) != required:
return
# values contains both log_enabled and log_file
log_file = values['log_file']
log_enabled = values['log_enabled']
if self.log_file_handler is None:
if log_enabled:
self._set_log_file_handler(log_file)
logger.info('[App] logging enabled')
else:
# Log file handler already exists
if log_enabled:
if log_file != self.log_file_handler.baseFilename:
# Requested log file path has been changed
self._set_log_file_handler(log_file)
else:
self._destroy_log_file_handler()
def on_dmf_device_swapped(self, old_dmf_device, dmf_device):
self.dmf_device = dmf_device
def on_protocol_swapped(self, old_protocol, new_protocol):
self.protocol = new_protocol
def on_experiment_log_changed(self, experiment_log):
self.experiment_log = experiment_log
def get_device_directory(self):
observers = ExtensionPoint(IPlugin)
plugin_name = 'microdrop.gui.dmf_device_controller'
service = observers.service(plugin_name)
values = service.get_app_values()
if values and 'device_directory' in values:
directory = path(values['device_directory'])
if directory.isdir():
return directory
return None
def paste_steps(self, step_number=None):
if step_number is None:
# Default to pasting after the current step
step_number = self.protocol.current_step_number + 1
clipboard = gtk.clipboard_get()
try:
new_steps = pickle.loads(clipboard.wait_for_text())
for step in new_steps:
if not isinstance(step, Step):
# Invalid object type
return
except (Exception,), why:
logger.info('[paste_steps] invalid data: %s', why)
return
self.protocol.insert_steps(step_number, values=new_steps)
def copy_steps(self, step_ids):
steps = [self.protocol.steps[id] for id in step_ids]
if steps:
clipboard = gtk.clipboard_get()
clipboard.set_text(pickle.dumps(steps))
def delete_steps(self, step_ids):
self.protocol.delete_steps(step_ids)
def cut_steps(self, step_ids):
self.copy_steps(step_ids)
self.delete_steps(step_ids)
PluginGlobals.pop_env()
if __name__ == '__main__':
os.chdir(base_path())
| gpl-3.0 |
Slezhuk/ansible | lib/ansible/modules/network/nxos/nxos_vlan.py | 14 | 13903 | #!/usr/bin/python
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: nxos_vlan
extends_documentation_fragment: nxos
version_added: "2.1"
short_description: Manages VLAN resources and attributes.
description:
- Manages VLAN configurations on NX-OS switches.
author: Jason Edelman (@jedelman8)
options:
vlan_id:
description:
- Single VLAN ID.
required: false
default: null
vlan_range:
description:
- Range of VLANs such as 2-10 or 2,5,10-15, etc.
required: false
default: null
name:
description:
- Name of VLAN.
required: false
default: null
vlan_state:
description:
- Manage the vlan operational state of the VLAN
(equivalent to state {active | suspend} command.
required: false
default: active
choices: ['active','suspend']
admin_state:
description:
- Manage the VLAN administrative state of the VLAN equivalent
to shut/no shut in VLAN config mode.
required: false
default: up
choices: ['up','down']
mapped_vni:
description:
- The Virtual Network Identifier (VNI) ID that is mapped to the
VLAN. Valid values are integer and keyword 'default'.
required: false
default: null
version_added: "2.2"
state:
description:
- Manage the state of the resource.
required: false
default: present
choices: ['present','absent']
'''
EXAMPLES = '''
- name: Ensure a range of VLANs are not present on the switch
nxos_vlan:
vlan_range: "2-10,20,50,55-60,100-150"
host: 68.170.147.165
username: cisco
password: cisco
state: absent
transport: nxapi
- name: Ensure VLAN 50 exists with the name WEB and is in the shutdown state
nxos_vlan:
vlan_id: 50
host: 68.170.147.165
admin_state: down
name: WEB
transport: nxapi
username: cisco
password: cisco
- name: Ensure VLAN is NOT on the device
nxos_vlan:
vlan_id: 50
host: 68.170.147.165
state: absent
transport: nxapi
username: cisco
password: cisco
'''
RETURN = '''
proposed_vlans_list:
description: list of VLANs being proposed
returned: when debug enabled
type: list
sample: ["100"]
existing_vlans_list:
description: list of existing VLANs on the switch prior to making changes
returned: when debug enabled
type: list
sample: ["1", "2", "3", "4", "5", "20"]
end_state_vlans_list:
description: list of VLANs after the module is executed
returned: when debug enabled
type: list
sample: ["1", "2", "3", "4", "5", "20", "100"]
proposed:
description: k/v pairs of parameters passed into module (does not include
vlan_id or vlan_range)
returned: when debug enabled
type: dict or null
sample: {"admin_state": "down", "name": "app_vlan",
"vlan_state": "suspend", "mapped_vni": "5000"}
existing:
description: k/v pairs of existing vlan or null when using vlan_range
returned: when debug enabled
type: dict
sample: {"admin_state": "down", "name": "app_vlan",
"vlan_id": "20", "vlan_state": "suspend", "mapped_vni": ""}
end_state:
description: k/v pairs of the VLAN after executing module or null
when using vlan_range
returned: when debug enabled
type: dict or null
sample: {"admin_state": "down", "name": "app_vlan", "vlan_id": "20",
"vlan_state": "suspend", "mapped_vni": "5000"}
updates:
description: command string sent to the device
returned: always
type: list
sample: ["vlan 20", "vlan 55", "vn-segment 5000"]
commands:
description: command string sent to the device
returned: always
type: list
sample: ["vlan 20", "vlan 55", "vn-segment 5000"]
changed:
description: check to see if a change was made on the device
returned: always
type: boolean
sample: true
'''
from ansible.module_utils.nxos import get_config, load_config, run_commands
from ansible.module_utils.nxos import nxos_argument_spec, check_args
from ansible.module_utils.basic import AnsibleModule
import re
from ansible.module_utils.nxos import nxos_argument_spec, check_args
from ansible.module_utils.nxos import run_commands, load_config, get_config
from ansible.module_utils.basic import AnsibleModule
def vlan_range_to_list(vlans):
result = []
if vlans:
for part in vlans.split(','):
if part == 'none':
break
if '-' in part:
a, b = part.split('-')
a, b = int(a), int(b)
result.extend(range(a, b + 1))
else:
a = int(part)
result.append(a)
return numerical_sort(result)
return result
def numerical_sort(string_int_list):
"""Sort list of strings (VLAN IDs) that are digits in numerical order.
"""
as_int_list = []
as_str_list = []
for vlan in string_int_list:
as_int_list.append(int(vlan))
as_int_list.sort()
for vlan in as_int_list:
as_str_list.append(str(vlan))
return as_str_list
def build_commands(vlans, state):
commands = []
for vlan in vlans:
if state == 'present':
command = 'vlan {0}'.format(vlan)
commands.append(command)
elif state == 'absent':
command = 'no vlan {0}'.format(vlan)
commands.append(command)
return commands
def get_vlan_config_commands(vlan, vid):
"""Build command list required for VLAN configuration
"""
reverse_value_map = {
"admin_state": {
"down": "shutdown",
"up": "no shutdown"
}
}
if vlan.get('admin_state'):
# apply value map when making change to the admin state
# note: would need to be a loop or more in depth check if
# value map has more than 1 key
vlan = apply_value_map(reverse_value_map, vlan)
VLAN_ARGS = {
'name': 'name {0}',
'vlan_state': 'state {0}',
'admin_state': '{0}',
'mode': 'mode {0}',
'mapped_vni': 'vn-segment {0}'
}
commands = []
for param, value in vlan.items():
if param == 'mapped_vni' and value == 'default':
command = 'no vn-segment'
else:
command = VLAN_ARGS.get(param).format(vlan.get(param))
if command:
commands.append(command)
commands.insert(0, 'vlan ' + vid)
commands.append('exit')
return commands
def get_list_of_vlans(module):
body = run_commands(module, ['show vlan | json'])
vlan_list = []
vlan_table = body[0].get('TABLE_vlanbrief')['ROW_vlanbrief']
if isinstance(vlan_table, list):
for vlan in vlan_table:
vlan_list.append(str(vlan['vlanshowbr-vlanid-utf']))
else:
vlan_list.append('1')
return vlan_list
def get_vni(vlanid, module):
flags = str('all | section vlan.{0}'.format(vlanid)).split(' ')
body = get_config(module, flags=flags)
#command = 'show run all | section vlan.{0}'.format(vlanid)
#body = execute_show_command(command, module, command_type='cli_show_ascii')[0]
value = ''
if body:
REGEX = re.compile(r'(?:vn-segment\s)(?P<value>.*)$', re.M)
if 'vn-segment' in body:
value = REGEX.search(body).group('value')
return value
def get_vlan(vlanid, module):
"""Get instance of VLAN as a dictionary
"""
command = 'show vlan id %s | json' % vlanid
body = run_commands(module, [command])
#command = 'show vlan id ' + vlanid
#body = execute_show_command(command, module)
try:
vlan_table = body[0]['TABLE_vlanbriefid']['ROW_vlanbriefid']
except (TypeError, IndexError):
return {}
key_map = {
"vlanshowbr-vlanid-utf": "vlan_id",
"vlanshowbr-vlanname": "name",
"vlanshowbr-vlanstate": "vlan_state",
"vlanshowbr-shutstate": "admin_state"
}
vlan = apply_key_map(key_map, vlan_table)
value_map = {
"admin_state": {
"shutdown": "down",
"noshutdown": "up"
}
}
vlan = apply_value_map(value_map, vlan)
vlan['mapped_vni'] = get_vni(vlanid, module)
return vlan
def apply_key_map(key_map, table):
new_dict = {}
for key, value in table.items():
new_key = key_map.get(key)
if new_key:
new_dict[new_key] = str(value)
return new_dict
def apply_value_map(value_map, resource):
for key, value in value_map.items():
resource[key] = value[resource.get(key)]
return resource
def main():
argument_spec = dict(
vlan_id=dict(required=False, type='str'),
vlan_range=dict(required=False),
name=dict(required=False),
vlan_state=dict(choices=['active', 'suspend'], required=False),
mapped_vni=dict(required=False, type='str'),
state=dict(choices=['present', 'absent'], default='present',
required=False),
admin_state=dict(choices=['up', 'down'], required=False),
include_defaults=dict(default=False),
config=dict(),
save=dict(type='bool', default=False)
)
argument_spec.update(nxos_argument_spec)
argument_spec.update(nxos_argument_spec)
module = AnsibleModule(argument_spec=argument_spec,
mutually_exclusive=[['vlan_range', 'name'],
['vlan_id', 'vlan_range']],
supports_check_mode=True)
warnings = list()
check_args(module, warnings)
warnings = list()
check_args(module, warnings)
vlan_range = module.params['vlan_range']
vlan_id = module.params['vlan_id']
name = module.params['name']
vlan_state = module.params['vlan_state']
admin_state = module.params['admin_state']
mapped_vni = module.params['mapped_vni']
state = module.params['state']
changed = False
if vlan_id:
if not vlan_id.isdigit():
module.fail_json(msg='vlan_id must be a valid VLAN ID')
args = dict(name=name, vlan_state=vlan_state,
admin_state=admin_state, mapped_vni=mapped_vni)
proposed = dict((k, v) for k, v in args.items() if v is not None)
proposed_vlans_list = numerical_sort(vlan_range_to_list(
vlan_id or vlan_range))
existing_vlans_list = numerical_sort(get_list_of_vlans(module))
commands = []
existing = {}
if vlan_range:
if state == 'present':
# These are all of the VLANs being proposed that don't
# already exist on the switch
vlans_delta = list(
set(proposed_vlans_list).difference(existing_vlans_list))
commands = build_commands(vlans_delta, state)
elif state == 'absent':
# VLANs that are common between what is being proposed and
# what is on the switch
vlans_common = list(
set(proposed_vlans_list).intersection(existing_vlans_list))
commands = build_commands(vlans_common, state)
else:
existing = get_vlan(vlan_id, module)
if state == 'absent':
if existing:
commands = ['no vlan ' + vlan_id]
elif state == 'present':
if (existing.get('mapped_vni') == '0' and
proposed.get('mapped_vni') == 'default'):
proposed.pop('mapped_vni')
delta = dict(set(proposed.items()).difference(existing.items()))
if delta or not existing:
commands = get_vlan_config_commands(delta, vlan_id)
end_state = existing
end_state_vlans_list = existing_vlans_list
if commands:
if existing.get('mapped_vni') and state != 'absent':
if (existing.get('mapped_vni') != proposed.get('mapped_vni') and
existing.get('mapped_vni') != '0' and proposed.get('mapped_vni') != 'default'):
commands.insert(1, 'no vn-segment')
if module.check_mode:
module.exit_json(changed=True,
commands=commands)
else:
load_config(module, commands)
changed = True
end_state_vlans_list = numerical_sort(get_list_of_vlans(module))
if 'configure' in commands:
commands.pop(0)
if vlan_id:
end_state = get_vlan(vlan_id, module)
results = {
'commands': commands,
'updates': commands,
'changed': changed,
'warnings': warnings
}
if module._debug:
results.update({
'proposed_vlans_list': proposed_vlans_list,
'existing_vlans_list': existing_vlans_list,
'proposed': proposed,
'existing': existing,
'end_state': end_state,
'end_state_vlans_list': end_state_vlans_list
})
module.exit_json(**results)
if __name__ == '__main__':
main()
| gpl-3.0 |
scyclops/Readable-Feeds | chardet/gb2312prober.py | 236 | 1677 | ######################## BEGIN LICENSE BLOCK ########################
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 1998
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Mark Pilgrim - port to Python
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA
######################### END LICENSE BLOCK #########################
from mbcharsetprober import MultiByteCharSetProber
from codingstatemachine import CodingStateMachine
from chardistribution import GB2312DistributionAnalysis
from mbcssm import GB2312SMModel
class GB2312Prober(MultiByteCharSetProber):
def __init__(self):
MultiByteCharSetProber.__init__(self)
self._mCodingSM = CodingStateMachine(GB2312SMModel)
self._mDistributionAnalyzer = GB2312DistributionAnalysis()
self.reset()
def get_charset_name(self):
return "GB2312"
| gpl-3.0 |
Maximilian-Reuter/SickRage-1 | lib/twilio/rest/resources/ip_messaging/services.py | 23 | 1748 | from .channels import Channels
from .roles import Roles
from .users import Users
from twilio.rest.resources import NextGenInstanceResource, NextGenListResource
class Service(NextGenInstanceResource):
subresources = [
Channels,
Roles,
Users
]
def update(self, **kwargs):
"""
Updates this Service instance
:return: Updated instance
"""
return self.update_instance(**kwargs)
def delete(self):
"""
Delete this service
"""
return self.delete_instance()
class Services(NextGenListResource):
name = "Services"
instance = Service
def list(self, **kwargs):
"""
Returns a page of :class:`Service` resources as a list.
For paging information see :class:`ListResource`.
**NOTE**: Due to the potentially voluminous amount of data in an
alert, the full HTTP request and response data is only returned
in the Service instance resource representation.
"""
return self.get_instances(kwargs)
def create(self, friendly_name, **kwargs):
"""
Create a service.
:param str friendly_name: The friendly name for the service
:return: A :class:`Service` object
"""
kwargs["friendly_name"] = friendly_name
return self.create_instance(kwargs)
def delete(self, sid):
"""
Delete a given Service
"""
return self.delete_instance(sid)
def update(self, sid, **kwargs):
"""
Updates the Service instance identified by sid
:param sid: Service instance identifier
:return: Updated instance
"""
return self.update_instance(sid, kwargs)
| gpl-3.0 |
infinity0/pyptlib | pyptlib/test/test_server.py | 2 | 9185 | import os
import unittest
from pyptlib.config import EnvError, Config
from pyptlib.server_config import get_transport_options_impl
from pyptlib.server import ServerTransportPlugin
from pyptlib.test.test_core import PluginCoreTestMixin
from pyptlib.core import SUPPORTED_TRANSPORT_VERSIONS
# a good valid environment to base modifications from
# so it's clearer to see exactly why an environment fails
BASE_ENVIRON = {
"TOR_PT_STATE_LOCATION" : "/pt_stat",
"TOR_PT_MANAGED_TRANSPORT_VER" : "1",
"TOR_PT_EXTENDED_SERVER_PORT" : "",
"TOR_PT_ORPORT" : "127.0.0.1:43210",
"TOR_PT_SERVER_BINDADDR" : "dummy-127.0.0.1:5556,boom-127.0.0.1:6666",
"TOR_PT_SERVER_TRANSPORTS" : "dummy,boom"
}
class testServer(PluginCoreTestMixin, unittest.TestCase):
pluginType = ServerTransportPlugin
def test_fromEnv_legit(self):
"""Legit environment."""
os.environ = BASE_ENVIRON
self.plugin._loadConfigFromEnv()
self.assertOutputLinesEmpty()
def test_fromEnv_bad(self):
"""Missing TOR_PT_MANAGED_TRANSPORT_VER."""
TEST_ENVIRON = dict(BASE_ENVIRON)
TEST_ENVIRON.pop("TOR_PT_MANAGED_TRANSPORT_VER")
os.environ = TEST_ENVIRON
self.assertRaises(EnvError, self.plugin._loadConfigFromEnv)
self.assertOutputLinesStartWith("ENV-ERROR ")
def test_fromEnv_bad2(self):
"""Missing TOR_PT_ORPORT."""
TEST_ENVIRON = dict(BASE_ENVIRON)
TEST_ENVIRON.pop("TOR_PT_ORPORT")
os.environ = TEST_ENVIRON
self.assertRaises(EnvError, self.plugin._loadConfigFromEnv)
self.assertOutputLinesStartWith("ENV-ERROR ")
def test_fromEnv_bad3(self):
"""Missing TOR_PT_EXTENDED_SERVER_PORT."""
TEST_ENVIRON = dict(BASE_ENVIRON)
TEST_ENVIRON.pop("TOR_PT_EXTENDED_SERVER_PORT")
os.environ = TEST_ENVIRON
self.assertRaises(EnvError, self.plugin._loadConfigFromEnv)
self.assertOutputLinesStartWith("ENV-ERROR ")
def test_fromEnv_bad4(self):
"""TOR_PT_EXTENDED_SERVER_PORT not an addport."""
TEST_ENVIRON = dict(BASE_ENVIRON)
TEST_ENVIRON["TOR_PT_EXTENDED_SERVER_PORT"] = "cakez"
os.environ = TEST_ENVIRON
self.assertRaises(EnvError, self.plugin._loadConfigFromEnv)
self.assertOutputLinesStartWith("ENV-ERROR ")
def test_fromEnv_bad5(self):
"""TOR_PT_ORPORT not an addport."""
TEST_ENVIRON = dict(BASE_ENVIRON)
TEST_ENVIRON["TOR_PT_ORPORT"] = "lulz"
os.environ = TEST_ENVIRON
self.assertRaises(EnvError, self.plugin._loadConfigFromEnv)
self.assertOutputLinesStartWith("ENV-ERROR ")
def test_fromEnv_bad6(self):
"""TOR_PT_SERVER_BINDADDR not an addport."""
TEST_ENVIRON = dict(BASE_ENVIRON)
TEST_ENVIRON["TOR_PT_SERVER_BINDADDR"] = "dummy-lyrical_content,boom-127.0.0.1:6666"
os.environ = TEST_ENVIRON
self.assertRaises(EnvError, self.plugin._loadConfigFromEnv)
self.assertOutputLinesStartWith("ENV-ERROR ")
def test_fromEnv_bad7(self):
"""Assymetric TOR_PT_SERVER_TRANSPORTS and TOR_PT_SERVER_BINDADDR."""
TEST_ENVIRON = dict(BASE_ENVIRON)
TEST_ENVIRON["TOR_PT_SERVER_BINDADDR"] = "dummy-127.0.0.1:5556,laughs-127.0.0.1:6666"
TEST_ENVIRON["TOR_PT_SERVER_TRANSPORTS"] = "dummy,boom"
os.environ = TEST_ENVIRON
self.assertRaises(EnvError, self.plugin._loadConfigFromEnv)
self.assertOutputLinesStartWith("ENV-ERROR ")
def test_fromEnv_bad8(self):
"""Assymetric TOR_PT_SERVER_TRANSPORTS and TOR_PT_SERVER_BINDADDR."""
TEST_ENVIRON = dict(BASE_ENVIRON)
TEST_ENVIRON["TOR_PT_SERVER_BINDADDR"] = "dummy-127.0.0.1:5556,laughs-127.0.0.1:6666"
TEST_ENVIRON["TOR_PT_SERVER_TRANSPORTS"] = "dummy"
os.environ = TEST_ENVIRON
self.assertRaises(EnvError, self.plugin._loadConfigFromEnv)
self.assertOutputLinesStartWith("ENV-ERROR ")
def test_fromEnv_bad9(self):
"""Assymetric TOR_PT_SERVER_TRANSPORTS and TOR_PT_SERVER_BINDADDR."""
TEST_ENVIRON = dict(BASE_ENVIRON)
TEST_ENVIRON["TOR_PT_SERVER_BINDADDR"] = "dummy-127.0.0.1:5556"
TEST_ENVIRON["TOR_PT_SERVER_TRANSPORTS"] = "dummy,laughs"
os.environ = TEST_ENVIRON
self.assertRaises(EnvError, self.plugin._loadConfigFromEnv)
self.assertOutputLinesStartWith("ENV-ERROR ")
def test_fromEnv_disabled_extorport(self):
"""Disabled TOR_PT_EXTENDED_SERVER_PORT."""
os.environ = BASE_ENVIRON
config = self.plugin._loadConfigFromEnv()
self.assertIsNone(config.getExtendedORPort())
def test_fromEnv_ext_or_but_no_auth_cookie(self):
"""TOR_PT_EXTENDED_SERVER_PORT without TOR_PT_AUTH_COOKIE_FILE."""
TEST_ENVIRON = dict(BASE_ENVIRON)
TEST_ENVIRON["TOR_PT_EXTENDED_SERVER_PORT"] = "127.0.0.1:5555"
os.environ = TEST_ENVIRON
self.assertRaises(EnvError, self.plugin._loadConfigFromEnv)
def test_fromEnv_auth_cookie_but_no_ext_or(self):
"""TOR_PT_AUTH_COOKIE_FILE without TOR_PT_EXTENDED_SERVER_PORT."""
TEST_ENVIRON = dict(BASE_ENVIRON)
TEST_ENVIRON.pop("TOR_PT_EXTENDED_SERVER_PORT")
TEST_ENVIRON["TOR_PT_AUTH_COOKIE_FILE"] = "/lulzie"
os.environ = TEST_ENVIRON
self.assertRaises(EnvError, self.plugin.init, ["what"])
def test_init_correct_ext_orport(self):
"""Correct Extended ORPort configuration."""
TEST_ENVIRON = dict(BASE_ENVIRON)
TEST_ENVIRON["TOR_PT_EXTENDED_SERVER_PORT"] = "127.0.0.1:5555"
TEST_ENVIRON["TOR_PT_AUTH_COOKIE_FILE"] = "/lulzie"
os.environ = TEST_ENVIRON
self.plugin.init([])
self.assertEquals(self.plugin.config.getAuthCookieFile(), '/lulzie')
self.assertEquals(self.plugin.config.getExtendedORPort(), ('127.0.0.1', 5555))
self.assertOutputLinesStartWith("VERSION ")
def test_init_correct_transport_bindaddr(self):
"""Correct Extended ORPort configuration."""
os.environ = BASE_ENVIRON
self.plugin.init(["dummy", "boom"])
bindaddr = self.plugin.getBindAddresses()
self.assertEquals(bindaddr["dummy"], ('127.0.0.1', 5556))
self.assertEquals(bindaddr["boom"], ('127.0.0.1', 6666))
self.assertOutputLinesStartWith("VERSION ")
class testServerOutput(PluginCoreTestMixin, unittest.TestCase):
"""
Test the output of pyptlib. That is, test the SMETHOD lines, etc.
"""
pluginType = ServerTransportPlugin
def test_smethod_line(self):
"""Test output SMETHOD lines."""
os.environ = BASE_ENVIRON
self.plugin.init(["dummy", "boom"])
for transport, transport_bindaddr in self.plugin.getBindAddresses().items():
self.plugin.reportMethodSuccess(transport, transport_bindaddr, None)
self.plugin.reportMethodsEnd()
self.assertIn("SMETHOD dummy 127.0.0.1:5556\n", self.getOutputLines())
self.assertIn("SMETHOD boom 127.0.0.1:6666\n", self.getOutputLines())
self.assertIn("SMETHODS DONE\n", self.getOutputLines())
def test_smethod_line_args(self):
"""Test an SMETHOD line with extra arguments."""
TEST_ENVIRON = dict(BASE_ENVIRON)
TEST_ENVIRON["TOR_PT_SERVER_TRANSPORT_OPTIONS"] = "boom:roots=culture;random:no=care;boom:first=fire"
os.environ = TEST_ENVIRON
self.plugin.init(["dummy", "boom"])
for transport, transport_bindaddr in self.plugin.getBindAddresses().items():
self.plugin.reportMethodSuccess(transport, transport_bindaddr, None)
self.plugin.reportMethodsEnd()
self.assertIn("SMETHOD boom 127.0.0.1:6666 ARGS:roots=culture,first=fire\n", self.getOutputLines())
def test_smethod_line_explicit_args(self):
"""Test an SMETHOD line with extra arguments."""
os.environ = BASE_ENVIRON
self.plugin.init(["dummy", "boom"])
for transport, transport_bindaddr in self.plugin.getBindAddresses().items():
self.plugin.reportMethodSuccess(transport, transport_bindaddr, "roots=culture,first=fire")
self.plugin.reportMethodsEnd()
self.assertIn("SMETHOD boom 127.0.0.1:6666 ARGS:roots=culture,first=fire\n", self.getOutputLines())
class testUtils(unittest.TestCase):
def test_get_transport_options_wrong(self):
"""Invalid options string"""
to_parse = "trebuchet_secret=nou"
self.assertRaises(ValueError, get_transport_options_impl, to_parse)
def test_get_transport_options_wrong_2(self):
"""No k=v value"""
to_parse = "trebuchet:secret~nou"
self.assertRaises(ValueError, get_transport_options_impl, to_parse)
def test_get_transport_options_correct(self):
to_parse = "trebuchet:secret=nou;trebuchet:cache=/tmp/cache;ballista:secret=yes;ballista:fun=no;archer:bow=yes"
expected = {"trebuchet" : {"secret" : "nou", "cache" : "/tmp/cache"} , "ballista" : {"secret" : "yes", "fun" : "no"}, "archer" : {"bow" : "yes" } }
result = get_transport_options_impl(to_parse)
self.assertEquals(result, expected)
if __name__ == '__main__':
unittest.main()
| bsd-3-clause |
pschmitt/home-assistant | tests/components/homekit_controller/test_air_quality.py | 21 | 1783 | """Basic checks for HomeKit air quality sensor."""
from aiohomekit.model.characteristics import CharacteristicsTypes
from aiohomekit.model.services import ServicesTypes
from tests.components.homekit_controller.common import setup_test_component
def create_air_quality_sensor_service(accessory):
"""Define temperature characteristics."""
service = accessory.add_service(ServicesTypes.AIR_QUALITY_SENSOR)
cur_state = service.add_char(CharacteristicsTypes.AIR_QUALITY)
cur_state.value = 5
cur_state = service.add_char(CharacteristicsTypes.DENSITY_OZONE)
cur_state.value = 1111
cur_state = service.add_char(CharacteristicsTypes.DENSITY_NO2)
cur_state.value = 2222
cur_state = service.add_char(CharacteristicsTypes.DENSITY_SO2)
cur_state.value = 3333
cur_state = service.add_char(CharacteristicsTypes.DENSITY_PM25)
cur_state.value = 4444
cur_state = service.add_char(CharacteristicsTypes.DENSITY_PM10)
cur_state.value = 5555
cur_state = service.add_char(CharacteristicsTypes.DENSITY_VOC)
cur_state.value = 6666
async def test_air_quality_sensor_read_state(hass, utcnow):
"""Test reading the state of a HomeKit temperature sensor accessory."""
helper = await setup_test_component(hass, create_air_quality_sensor_service)
state = await helper.poll_and_get_state()
assert state.state == "4444"
assert state.attributes["air_quality_text"] == "poor"
assert state.attributes["ozone"] == 1111
assert state.attributes["nitrogen_dioxide"] == 2222
assert state.attributes["sulphur_dioxide"] == 3333
assert state.attributes["particulate_matter_2_5"] == 4444
assert state.attributes["particulate_matter_10"] == 5555
assert state.attributes["volatile_organic_compounds"] == 6666
| apache-2.0 |
sinhrks/scikit-learn | examples/model_selection/grid_search_digits.py | 44 | 2672 | """
============================================================
Parameter estimation using grid search with cross-validation
============================================================
This examples shows how a classifier is optimized by cross-validation,
which is done using the :class:`sklearn.model_selection.GridSearchCV` object
on a development set that comprises only half of the available labeled data.
The performance of the selected hyper-parameters and trained model is
then measured on a dedicated evaluation set that was not used during
the model selection step.
More details on tools available for model selection can be found in the
sections on :ref:`cross_validation` and :ref:`grid_search`.
"""
from __future__ import print_function
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import classification_report
from sklearn.svm import SVC
print(__doc__)
# Loading the Digits dataset
digits = datasets.load_digits()
# To apply an classifier on this data, we need to flatten the image, to
# turn the data in a (samples, feature) matrix:
n_samples = len(digits.images)
X = digits.images.reshape((n_samples, -1))
y = digits.target
# Split the dataset in two equal parts
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.5, random_state=0)
# Set the parameters by cross-validation
tuned_parameters = [{'kernel': ['rbf'], 'gamma': [1e-3, 1e-4],
'C': [1, 10, 100, 1000]},
{'kernel': ['linear'], 'C': [1, 10, 100, 1000]}]
scores = ['precision', 'recall']
for score in scores:
print("# Tuning hyper-parameters for %s" % score)
print()
clf = GridSearchCV(SVC(C=1), tuned_parameters, cv=5,
scoring='%s_weighted' % score)
clf.fit(X_train, y_train)
print("Best parameters set found on development set:")
print()
print(clf.best_params_)
print()
print("Grid scores on development set:")
print()
for params, mean_score, scores in clf.grid_scores_:
print("%0.3f (+/-%0.03f) for %r"
% (mean_score, scores.std() * 2, params))
print()
print("Detailed classification report:")
print()
print("The model is trained on the full development set.")
print("The scores are computed on the full evaluation set.")
print()
y_true, y_pred = y_test, clf.predict(X_test)
print(classification_report(y_true, y_pred))
print()
# Note the problem is too easy: the hyperparameter plateau is too flat and the
# output model is the same for precision and recall with ties in quality.
| bsd-3-clause |
arcean/telepathy-python | debian/python-telepathy/usr/share/pyshared/telepathy/_generated/Channel_Type_Stream_Tube.py | 4 | 3337 | # -*- coding: utf-8 -*-
# Generated from the Telepathy spec
"""Copyright © 2008-2009 Collabora Limited
Copyright © 2008-2009 Nokia Corporation
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""
import dbus.service
class ChannelTypeStreamTube(dbus.service.Interface):
"""\
A stream tube is a transport for ordered, reliable data transfer,
similar to SOCK_STREAM sockets.
When offering a stream tube, the initiating client creates a local
listening socket and offers it to the recipient client using the
Offer method. When a
recipient accepts a stream tube using the
Accept method, the
recipient's connection manager creates a new local listening socket.
Each time the recipient's client connects to this socket, the
initiator's connection manager proxies this connection to the
originally offered socket.
"""
@dbus.service.method('org.freedesktop.Telepathy.Channel.Type.StreamTube', in_signature='uvua{sv}', out_signature='')
def Offer(self, address_type, address, access_control, parameters):
"""
Offer a stream tube exporting the local socket specified.
"""
raise NotImplementedError
@dbus.service.method('org.freedesktop.Telepathy.Channel.Type.StreamTube', in_signature='uuv', out_signature='v')
def Accept(self, address_type, access_control, access_control_param):
"""
Accept a stream tube that's in the "local pending" state. The
connection manager will attempt to open the tube. The tube remains in
the "local pending" state until the TubeChannelStateChanged
signal is emitted.
"""
raise NotImplementedError
@dbus.service.signal('org.freedesktop.Telepathy.Channel.Type.StreamTube', signature='uvu')
def NewRemoteConnection(self, Handle, Connection_Param, Connection_ID):
"""
Emitted each time a participant opens a new connection to its
socket.
This signal is only fired on the offering side.
"""
pass
@dbus.service.signal('org.freedesktop.Telepathy.Channel.Type.StreamTube', signature='u')
def NewLocalConnection(self, Connection_ID):
"""
Emitted when the tube application connects to the CM's socket.
This signal is only fired on the accepting side.
"""
pass
@dbus.service.signal('org.freedesktop.Telepathy.Channel.Type.StreamTube', signature='uss')
def ConnectionClosed(self, Connection_ID, Error, Message):
"""
Emitted when a connection has been closed.
"""
pass
| lgpl-2.1 |
erjohnso/ansible | lib/ansible/plugins/lookup/cyberarkpassword.py | 53 | 6066 | # (c) 2017, Edward Nunez <edward.nunez@cyberark.com>
# (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = """
lookup: cyberarkpassword
version_added: "2.4"
short_description: get secrets from CyberArk AIM
requirements:
- CyberArk AIM tool installed
description:
options :
_command:
description: Cyberark CLI utility.
env:
- name: AIM_CLIPASSWORDSDK_CMD
default: '/opt/CARKaim/sdk/clipasswordsdk'
appid:
description: Defines the unique ID of the application that is issuing the password request.
required: True
query:
description: Describes the filter criteria for the password retrieval.
required: True
output:
description:
- Specifies the desired output fields separated by commas.
- "They could be: Password, PassProps.<property>, PasswordChangeInProcess"
default: 'password'
_extra:
description: for extra_parms values please check parameters for clipasswordsdk in CyberArk's "Credential Provider and ASCP Implementation Guide"
note:
- For Ansible on windows, please change the -parameters (-p, -d, and -o) to /parameters (/p, /d, and /o) and change the location of CLIPasswordSDK.exe
"""
EXAMPLES = """
- name: passing options to the lookup
debug: msg={{ lookup("cyberarkpassword", cyquery)}}
vars:
cyquery:
appid: "app_ansible"
query": "safe=CyberArk_Passwords;folder=root;object=AdminPass"
output: "Password,PassProps.UserName,PassProps.Address,PasswordChangeInProcess"
- name: used in a loop
debug: msg={{item}}
with_cyberarkpassword:
appid: 'app_ansible'
query: 'safe=CyberArk_Passwords;folder=root;object=AdminPass'
output: 'Password,PassProps.UserName,PassProps.Address,PasswordChangeInProcess'
"""
RETURN = """
password:
description:
- The actual value stored
passprops:
description: properties assigned to the entry
type: dictionary
passwordchangeinprocess:
description: did the password change?
"""
import os
import subprocess
from subprocess import PIPE
from subprocess import Popen
from ansible.errors import AnsibleError
from ansible.plugins.lookup import LookupBase
from ansible.parsing.splitter import parse_kv
from ansible.module_utils._text import to_text
try:
from __main__ import display
except ImportError:
from ansible.utils.display import Display
display = Display()
CLIPASSWORDSDK_CMD = os.getenv('AIM_CLIPASSWORDSDK_CMD', '/opt/CARKaim/sdk/clipasswordsdk')
class CyberarkPassword:
def __init__(self, appid=None, query=None, output=None, **kwargs):
self.appid = appid
self.query = query
self.output = output
# Support for Generic parameters to be able to specify
# FailRequestOnPasswordChange, Queryformat, Reason, etc.
self.extra_parms = []
for key, value in kwargs.items():
self.extra_parms.append('-p')
self.extra_parms.append("%s=%s" % (key, value))
if self.appid is None:
raise AnsibleError("CyberArk Error: No Application ID specified")
if self.query is None:
raise AnsibleError("CyberArk Error: No Vault query specified")
if self.output is None:
# If no output is specified, return at least the password
self.output = "password"
else:
# To avoid reference issues/confusion to values, all
# output 'keys' will be in lowercase.
self.output = self.output.lower()
self.delimiter = "@#@" # Known delimiter to split output results
def get(self):
result_dict = {}
try:
all_parms = [
CLIPASSWORDSDK_CMD,
'GetPassword',
'-p', 'AppDescs.AppID=%s' % self.appid,
'-p', 'Query=%s' % self.query,
'-o', self.output,
'-d', self.delimiter]
all_parms.extend(self.extra_parms)
credential = ""
tmp_output, tmp_error = Popen(all_parms, stdout=PIPE, stderr=PIPE, stdin=PIPE).communicate()
if tmp_output:
credential = tmp_output
if tmp_error:
raise AnsibleError("ERROR => %s " % (tmp_error))
if credential and credential.endswith(b'\n'):
credential = credential[:-1]
output_names = self.output.split(",")
output_values = credential.split(self.delimiter)
for i in range(len(output_names)):
if output_names[i].startswith("passprops."):
if "passprops" not in result_dict:
result_dict["passprops"] = {}
output_prop_name = output_names[i][10:]
result_dict["passprops"][output_prop_name] = output_values[i]
else:
result_dict[output_names[i]] = output_values[i]
except subprocess.CalledProcessError as e:
raise AnsibleError(e.output)
except OSError as e:
raise AnsibleError("ERROR - AIM not installed or clipasswordsdk not in standard location. ERROR=(%s) => %s " % (to_text(e.errno), e.strerror))
return [result_dict]
class LookupModule(LookupBase):
"""
USAGE:
"""
def run(self, terms, variables=None, **kwargs):
display.vvvv(terms)
if isinstance(terms, list):
return_values = []
for term in terms:
display.vvvv("Term: %s" % term)
cyberark_conn = CyberarkPassword(**term)
return_values.append(cyberark_conn.get())
return return_values
else:
cyberark_conn = CyberarkPassword(**terms)
result = cyberark_conn.get()
return result
| gpl-3.0 |
bintlabs/python-sync-db | dbsync/client/net.py | 1 | 6630 | """
Send HTTP requests and interpret responses.
The body returned by each procedure will be a python dictionary
obtained from parsing a response through a decoder, or ``None`` if the
decoder raises a ``ValueError``. The default encoder, decoder and
headers are meant to work with the JSON specification.
These procedures will raise a NetworkError in case of network failure.
"""
import requests
import cStringIO
import inspect
import json
class NetworkError(Exception):
pass
default_encoder = json.dumps
default_decoder = json.loads
default_headers = {"Content-Type": "application/json",
"Accept": "application/json"}
default_timeout = 10
authentication_callback = None
def _defaults(encode, decode, headers, timeout):
e = encode if not encode is None else default_encoder
if not inspect.isroutine(e):
raise ValueError("encoder must be a function", e)
d = decode if not decode is None else default_decoder
if not inspect.isroutine(d):
raise ValueError("decoder must be a function", d)
h = headers if not headers is None else default_headers
if h and not isinstance(h, dict):
raise ValueError("headers must be False or a python dictionary", h)
t = timeout if not timeout is None else default_timeout
if not isinstance(t, (int, long, float)):
raise ValueError("timeout must be a number")
if t <= 0:
t = None # Non-positive values are interpreted as no timeout
return (e, d, h, t)
def post_request(server_url, json_dict,
encode=None, decode=None, headers=None, timeout=None,
monitor=None):
"""
Sends a POST request to *server_url* with data *json_dict* and
returns a trio of (code, reason, body).
*encode* is a function that transforms a python dictionary into a
string.
*decode* is a function that transforms a string into a python
dictionary.
For all dictionaries d of simple types, decode(encode(d)) == d.
*headers* is a python dictionary with headers to send.
*timeout* is the number of seconds to wait for a response.
*monitor* is a routine that gets called for each chunk of the
response received, and is given a dictionary with information. The
key 'status' will always be in the dictionary, and other entries
will contain additional information. Check the source code to see
the variations.
"""
if not server_url.startswith("http://") and \
not server_url.startswith("https://"):
server_url = "http://" + server_url
enc, dec, hhs, tout = _defaults(encode, decode, headers, timeout)
stream = inspect.isroutine(monitor)
auth = authentication_callback(server_url) \
if authentication_callback is not None else None
try:
r = requests.post(server_url, data=enc(json_dict),
headers=hhs or None, stream=stream,
timeout=tout, auth=auth)
response = None
if stream:
total = r.headers.get('content-length', None)
partial = 0
monitor({'status': "connect", 'size': total})
chunks = cStringIO.StringIO()
for chunk in r:
partial += len(chunk)
monitor({'status': "downloading",
'size': total, 'received': partial})
chunks.write(chunk)
response = chunks.getvalue()
chunks.close()
else:
response = r.content
body = None
try:
body = dec(response)
except ValueError:
pass
result = (r.status_code, r.reason, body)
r.close()
return result
except requests.exceptions.RequestException as e:
if stream:
monitor({'status': "error", 'reason': "network error"})
raise NetworkError(*e.args)
except Exception as e:
if stream:
monitor({'status': "error", 'reason': "network error"})
raise NetworkError(*e.args)
def get_request(server_url, data=None,
encode=None, decode=None, headers=None, timeout=None,
monitor=None):
"""
Sends a GET request to *server_url*. If *data* is to be added, it
should be a python dictionary with simple pairs suitable for url
encoding. Returns a trio of (code, reason, body).
Read the docstring for ``post_request`` for information on the
rest.
"""
if not server_url.startswith("http://") and \
not server_url.startswith("https://"):
server_url = "http://" + server_url
enc, dec, hhs, tout = _defaults(encode, decode, headers, timeout)
stream = inspect.isroutine(monitor)
auth = authentication_callback(server_url) \
if authentication_callback is not None else None
try:
r = requests.get(server_url, params=data,
headers=hhs or None, stream=stream,
timeout=tout, auth=auth)
response = None
if stream:
total = r.headers.get('content-length', None)
partial = 0
monitor({'status': "connect", 'size': total})
chunks = cStringIO.StringIO()
for chunk in r:
partial += len(chunk)
monitor({'status': "downloading",
'size': total, 'received': partial})
chunks.write(chunk)
response = chunks.getvalue()
chunks.close()
else:
response = r.content
body = None
try:
body = dec(response)
except ValueError:
pass
result = (r.status_code, r.reason, body)
r.close()
return result
except requests.exceptions.RequestException as e:
if stream:
monitor({'status': "error", 'reason': "network error"})
raise NetworkError(*e.args)
except Exception as e:
if stream:
monitor({'status': "error", 'reason': "network error"})
raise NetworkError(*e.args)
def head_request(server_url):
"""
Sends a HEAD request to *server_url*.
Returns a pair of (code, reason).
"""
if not server_url.startswith("http://") and \
not server_url.startswith("https://"):
server_url = "http://" + server_url
try:
r = requests.head(server_url, timeout=default_timeout)
return (r.status_code, r.reason)
except requests.exceptions.RequestException as e:
raise NetworkError(*e.args)
except Exception as e:
raise NetworkError(*e.args)
| mit |
tmenjo/cinder-2015.1.1 | cinder/tests/api/contrib/test_volume_transfer.py | 3 | 26444 | # Copyright (C) 2012 Hewlett-Packard Development Company, L.P.
# 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 volume transfer code.
"""
import json
from xml.dom import minidom
from oslo_log import log as logging
import webob
from cinder.api.contrib import volume_transfer
from cinder import context
from cinder import db
from cinder import exception
from cinder import test
from cinder.tests.api import fakes
from cinder import transfer
import cinder.volume
LOG = logging.getLogger(__name__)
class VolumeTransferAPITestCase(test.TestCase):
"""Test Case for transfers API."""
def setUp(self):
super(VolumeTransferAPITestCase, self).setUp()
self.volume_transfer_api = transfer.API()
self.controller = volume_transfer.VolumeTransferController()
def _create_transfer(self, volume_id=1,
display_name='test_transfer'):
"""Create a transfer object."""
return self.volume_transfer_api.create(context.get_admin_context(),
volume_id,
display_name)
@staticmethod
def _create_volume(display_name='test_volume',
display_description='this is a test volume',
status='available',
size=1,
project_id='fake'):
"""Create a volume object."""
vol = {}
vol['host'] = 'fake_host'
vol['size'] = size
vol['user_id'] = 'fake'
vol['project_id'] = project_id
vol['status'] = status
vol['display_name'] = display_name
vol['display_description'] = display_description
vol['attach_status'] = status
return db.volume_create(context.get_admin_context(), vol)['id']
def test_show_transfer(self):
volume_id = self._create_volume(size=5)
transfer = self._create_transfer(volume_id)
LOG.debug('Created transfer with id %s' % transfer)
req = webob.Request.blank('/v2/fake/os-volume-transfer/%s' %
transfer['id'])
req.method = 'GET'
req.headers['Content-Type'] = 'application/json'
res = req.get_response(fakes.wsgi_app())
res_dict = json.loads(res.body)
self.assertEqual(res.status_int, 200)
self.assertEqual(res_dict['transfer']['name'], 'test_transfer')
self.assertEqual(res_dict['transfer']['id'], transfer['id'])
self.assertEqual(res_dict['transfer']['volume_id'], volume_id)
db.transfer_destroy(context.get_admin_context(), transfer['id'])
db.volume_destroy(context.get_admin_context(), volume_id)
def test_show_transfer_xml_content_type(self):
volume_id = self._create_volume(size=5)
transfer = self._create_transfer(volume_id)
req = webob.Request.blank('/v2/fake/os-volume-transfer/%s' %
transfer['id'])
req.method = 'GET'
req.headers['Content-Type'] = 'application/xml'
req.headers['Accept'] = 'application/xml'
res = req.get_response(fakes.wsgi_app())
self.assertEqual(res.status_int, 200)
dom = minidom.parseString(res.body)
transfer_xml = dom.getElementsByTagName('transfer')
name = transfer_xml.item(0).getAttribute('name')
self.assertEqual(name.strip(), "test_transfer")
db.transfer_destroy(context.get_admin_context(), transfer['id'])
db.volume_destroy(context.get_admin_context(), volume_id)
def test_show_transfer_with_transfer_NotFound(self):
req = webob.Request.blank('/v2/fake/os-volume-transfer/1234')
req.method = 'GET'
req.headers['Content-Type'] = 'application/json'
res = req.get_response(fakes.wsgi_app())
res_dict = json.loads(res.body)
self.assertEqual(res.status_int, 404)
self.assertEqual(res_dict['itemNotFound']['code'], 404)
self.assertEqual(res_dict['itemNotFound']['message'],
'Transfer 1234 could not be found.')
def test_list_transfers_json(self):
volume_id_1 = self._create_volume(size=5)
volume_id_2 = self._create_volume(size=5)
transfer1 = self._create_transfer(volume_id_1)
transfer2 = self._create_transfer(volume_id_2)
req = webob.Request.blank('/v2/fake/os-volume-transfer')
req.method = 'GET'
req.headers['Content-Type'] = 'application/json'
res = req.get_response(fakes.wsgi_app())
res_dict = json.loads(res.body)
self.assertEqual(res.status_int, 200)
self.assertEqual(len(res_dict['transfers'][0]), 4)
self.assertEqual(res_dict['transfers'][0]['id'], transfer1['id'])
self.assertEqual(res_dict['transfers'][0]['name'], 'test_transfer')
self.assertEqual(len(res_dict['transfers'][1]), 4)
self.assertEqual(res_dict['transfers'][1]['name'], 'test_transfer')
db.transfer_destroy(context.get_admin_context(), transfer2['id'])
db.transfer_destroy(context.get_admin_context(), transfer1['id'])
db.volume_destroy(context.get_admin_context(), volume_id_1)
db.volume_destroy(context.get_admin_context(), volume_id_2)
def test_list_transfers_xml(self):
volume_id_1 = self._create_volume(size=5)
volume_id_2 = self._create_volume(size=5)
transfer1 = self._create_transfer(volume_id_1)
transfer2 = self._create_transfer(volume_id_2)
req = webob.Request.blank('/v2/fake/os-volume-transfer')
req.method = 'GET'
req.headers['Content-Type'] = 'application/xml'
req.headers['Accept'] = 'application/xml'
res = req.get_response(fakes.wsgi_app())
self.assertEqual(res.status_int, 200)
dom = minidom.parseString(res.body)
transfer_list = dom.getElementsByTagName('transfer')
self.assertEqual(transfer_list.item(0).attributes.length, 3)
self.assertEqual(transfer_list.item(0).getAttribute('id'),
transfer1['id'])
self.assertEqual(transfer_list.item(1).attributes.length, 3)
self.assertEqual(transfer_list.item(1).getAttribute('id'),
transfer2['id'])
db.transfer_destroy(context.get_admin_context(), transfer2['id'])
db.transfer_destroy(context.get_admin_context(), transfer1['id'])
db.volume_destroy(context.get_admin_context(), volume_id_2)
db.volume_destroy(context.get_admin_context(), volume_id_1)
def test_list_transfers_detail_json(self):
volume_id_1 = self._create_volume(size=5)
volume_id_2 = self._create_volume(size=5)
transfer1 = self._create_transfer(volume_id_1)
transfer2 = self._create_transfer(volume_id_2)
req = webob.Request.blank('/v2/fake/os-volume-transfer/detail')
req.method = 'GET'
req.headers['Content-Type'] = 'application/json'
req.headers['Accept'] = 'application/json'
res = req.get_response(fakes.wsgi_app())
res_dict = json.loads(res.body)
self.assertEqual(res.status_int, 200)
self.assertEqual(len(res_dict['transfers'][0]), 5)
self.assertEqual(res_dict['transfers'][0]['name'],
'test_transfer')
self.assertEqual(res_dict['transfers'][0]['id'], transfer1['id'])
self.assertEqual(res_dict['transfers'][0]['volume_id'], volume_id_1)
self.assertEqual(len(res_dict['transfers'][1]), 5)
self.assertEqual(res_dict['transfers'][1]['name'],
'test_transfer')
self.assertEqual(res_dict['transfers'][1]['id'], transfer2['id'])
self.assertEqual(res_dict['transfers'][1]['volume_id'], volume_id_2)
db.transfer_destroy(context.get_admin_context(), transfer2['id'])
db.transfer_destroy(context.get_admin_context(), transfer1['id'])
db.volume_destroy(context.get_admin_context(), volume_id_2)
db.volume_destroy(context.get_admin_context(), volume_id_1)
def test_list_transfers_detail_xml(self):
volume_id_1 = self._create_volume(size=5)
volume_id_2 = self._create_volume(size=5)
transfer1 = self._create_transfer(volume_id_1)
transfer2 = self._create_transfer(volume_id_2)
req = webob.Request.blank('/v2/fake/os-volume-transfer/detail')
req.method = 'GET'
req.headers['Content-Type'] = 'application/xml'
req.headers['Accept'] = 'application/xml'
res = req.get_response(fakes.wsgi_app())
self.assertEqual(res.status_int, 200)
dom = minidom.parseString(res.body)
transfer_detail = dom.getElementsByTagName('transfer')
self.assertEqual(transfer_detail.item(0).attributes.length, 4)
self.assertEqual(
transfer_detail.item(0).getAttribute('name'), 'test_transfer')
self.assertEqual(
transfer_detail.item(0).getAttribute('id'), transfer1['id'])
self.assertEqual(transfer_detail.item(0).getAttribute('volume_id'),
volume_id_1)
self.assertEqual(transfer_detail.item(1).attributes.length, 4)
self.assertEqual(
transfer_detail.item(1).getAttribute('name'), 'test_transfer')
self.assertEqual(
transfer_detail.item(1).getAttribute('id'), transfer2['id'])
self.assertEqual(transfer_detail.item(1).getAttribute('volume_id'),
volume_id_2)
db.transfer_destroy(context.get_admin_context(), transfer2['id'])
db.transfer_destroy(context.get_admin_context(), transfer1['id'])
db.volume_destroy(context.get_admin_context(), volume_id_2)
db.volume_destroy(context.get_admin_context(), volume_id_1)
def test_list_transfers_with_all_tenants(self):
volume_id_1 = self._create_volume(size=5)
volume_id_2 = self._create_volume(size=5, project_id='fake1')
transfer1 = self._create_transfer(volume_id_1)
transfer2 = self._create_transfer(volume_id_2)
req = fakes.HTTPRequest.blank('/v2/fake/os-volume-transfer?'
'all_tenants=1',
use_admin_context=True)
res_dict = self.controller.index(req)
expected = [(transfer1['id'], 'test_transfer'),
(transfer2['id'], 'test_transfer')]
ret = []
for item in res_dict['transfers']:
ret.append((item['id'], item['name']))
self.assertEqual(set(expected), set(ret))
db.transfer_destroy(context.get_admin_context(), transfer2['id'])
db.transfer_destroy(context.get_admin_context(), transfer1['id'])
db.volume_destroy(context.get_admin_context(), volume_id_1)
def test_create_transfer_json(self):
volume_id = self._create_volume(status='available', size=5)
body = {"transfer": {"display_name": "transfer1",
"volume_id": volume_id}}
req = webob.Request.blank('/v2/fake/os-volume-transfer')
req.method = 'POST'
req.headers['Content-Type'] = 'application/json'
req.body = json.dumps(body)
res = req.get_response(fakes.wsgi_app())
res_dict = json.loads(res.body)
LOG.info(res_dict)
self.assertEqual(res.status_int, 202)
self.assertIn('id', res_dict['transfer'])
self.assertIn('auth_key', res_dict['transfer'])
self.assertIn('created_at', res_dict['transfer'])
self.assertIn('name', res_dict['transfer'])
self.assertIn('volume_id', res_dict['transfer'])
db.volume_destroy(context.get_admin_context(), volume_id)
def test_create_transfer_xml(self):
volume_size = 2
volume_id = self._create_volume(status='available', size=volume_size)
req = webob.Request.blank('/v2/fake/os-volume-transfer')
req.body = ('<transfer name="transfer-001" '
'volume_id="%s"/>' % volume_id)
req.method = 'POST'
req.headers['Content-Type'] = 'application/xml'
req.headers['Accept'] = 'application/xml'
res = req.get_response(fakes.wsgi_app())
self.assertEqual(res.status_int, 202)
dom = minidom.parseString(res.body)
transfer = dom.getElementsByTagName('transfer')
self.assertTrue(transfer.item(0).hasAttribute('id'))
self.assertTrue(transfer.item(0).hasAttribute('auth_key'))
self.assertTrue(transfer.item(0).hasAttribute('created_at'))
self.assertEqual(transfer.item(0).getAttribute('name'), 'transfer-001')
self.assertTrue(transfer.item(0).hasAttribute('volume_id'))
db.volume_destroy(context.get_admin_context(), volume_id)
def test_create_transfer_with_no_body(self):
req = webob.Request.blank('/v2/fake/os-volume-transfer')
req.body = json.dumps(None)
req.method = 'POST'
req.headers['Content-Type'] = 'application/json'
req.headers['Accept'] = 'application/json'
res = req.get_response(fakes.wsgi_app())
res_dict = json.loads(res.body)
self.assertEqual(res.status_int, 400)
self.assertEqual(res_dict['badRequest']['code'], 400)
self.assertEqual(res_dict['badRequest']['message'],
'The server could not comply with the request since'
' it is either malformed or otherwise incorrect.')
def test_create_transfer_with_body_KeyError(self):
body = {"transfer": {"display_name": "transfer1"}}
req = webob.Request.blank('/v2/fake/os-volume-transfer')
req.method = 'POST'
req.headers['Content-Type'] = 'application/json'
req.body = json.dumps(body)
res = req.get_response(fakes.wsgi_app())
res_dict = json.loads(res.body)
self.assertEqual(res.status_int, 400)
self.assertEqual(res_dict['badRequest']['code'], 400)
self.assertEqual(res_dict['badRequest']['message'],
'Incorrect request body format')
def test_create_transfer_with_VolumeNotFound(self):
body = {"transfer": {"display_name": "transfer1",
"volume_id": 1234}}
req = webob.Request.blank('/v2/fake/os-volume-transfer')
req.method = 'POST'
req.headers['Content-Type'] = 'application/json'
req.body = json.dumps(body)
res = req.get_response(fakes.wsgi_app())
res_dict = json.loads(res.body)
self.assertEqual(res.status_int, 404)
self.assertEqual(res_dict['itemNotFound']['code'], 404)
self.assertEqual(res_dict['itemNotFound']['message'],
'Volume 1234 could not be found.')
def test_create_transfer_with_InvalidVolume(self):
volume_id = self._create_volume(status='attached')
body = {"transfer": {"display_name": "transfer1",
"volume_id": volume_id}}
req = webob.Request.blank('/v2/fake/os-volume-transfer')
req.method = 'POST'
req.headers['Content-Type'] = 'application/json'
req.body = json.dumps(body)
res = req.get_response(fakes.wsgi_app())
res_dict = json.loads(res.body)
self.assertEqual(res.status_int, 400)
self.assertEqual(res_dict['badRequest']['code'], 400)
self.assertEqual(res_dict['badRequest']['message'],
'Invalid volume: status must be available')
db.volume_destroy(context.get_admin_context(), volume_id)
def test_delete_transfer_awaiting_transfer(self):
volume_id = self._create_volume()
transfer = self._create_transfer(volume_id)
req = webob.Request.blank('/v2/fake/os-volume-transfer/%s' %
transfer['id'])
req.method = 'DELETE'
req.headers['Content-Type'] = 'application/json'
res = req.get_response(fakes.wsgi_app())
self.assertEqual(res.status_int, 202)
# verify transfer has been deleted
req = webob.Request.blank('/v2/fake/os-volume-transfer/%s' %
transfer['id'])
req.method = 'GET'
req.headers['Content-Type'] = 'application/json'
res = req.get_response(fakes.wsgi_app())
res_dict = json.loads(res.body)
self.assertEqual(res.status_int, 404)
self.assertEqual(res_dict['itemNotFound']['code'], 404)
self.assertEqual(res_dict['itemNotFound']['message'],
'Transfer %s could not be found.' % transfer['id'])
self.assertEqual(db.volume_get(context.get_admin_context(),
volume_id)['status'], 'available')
db.volume_destroy(context.get_admin_context(), volume_id)
def test_delete_transfer_with_transfer_NotFound(self):
req = webob.Request.blank('/v2/fake/os-volume-transfer/9999')
req.method = 'DELETE'
req.headers['Content-Type'] = 'application/json'
res = req.get_response(fakes.wsgi_app())
res_dict = json.loads(res.body)
self.assertEqual(res.status_int, 404)
self.assertEqual(res_dict['itemNotFound']['code'], 404)
self.assertEqual(res_dict['itemNotFound']['message'],
'Transfer 9999 could not be found.')
def test_accept_transfer_volume_id_specified_json(self):
volume_id = self._create_volume()
transfer = self._create_transfer(volume_id)
svc = self.start_service('volume', host='fake_host')
body = {"accept": {"id": transfer['id'],
"auth_key": transfer['auth_key']}}
req = webob.Request.blank('/v2/fake/os-volume-transfer/%s/accept' %
transfer['id'])
req.method = 'POST'
req.headers['Content-Type'] = 'application/json'
req.body = json.dumps(body)
res = req.get_response(fakes.wsgi_app())
res_dict = json.loads(res.body)
self.assertEqual(res.status_int, 202)
self.assertEqual(res_dict['transfer']['id'], transfer['id'])
self.assertEqual(res_dict['transfer']['volume_id'], volume_id)
# cleanup
svc.stop()
def test_accept_transfer_volume_id_specified_xml(self):
volume_id = self._create_volume(size=5)
transfer = self._create_transfer(volume_id)
svc = self.start_service('volume', host='fake_host')
req = webob.Request.blank('/v2/fake/os-volume-transfer/%s/accept' %
transfer['id'])
req.body = '<accept auth_key="%s"/>' % transfer['auth_key']
req.method = 'POST'
req.headers['Content-Type'] = 'application/xml'
req.headers['Accept'] = 'application/xml'
res = req.get_response(fakes.wsgi_app())
self.assertEqual(res.status_int, 202)
dom = minidom.parseString(res.body)
accept = dom.getElementsByTagName('transfer')
self.assertEqual(accept.item(0).getAttribute('id'),
transfer['id'])
self.assertEqual(accept.item(0).getAttribute('volume_id'), volume_id)
db.volume_destroy(context.get_admin_context(), volume_id)
# cleanup
svc.stop()
def test_accept_transfer_with_no_body(self):
volume_id = self._create_volume(size=5)
transfer = self._create_transfer(volume_id)
req = webob.Request.blank('/v2/fake/os-volume-transfer/%s/accept' %
transfer['id'])
req.body = json.dumps(None)
req.method = 'POST'
req.headers['Content-Type'] = 'application/json'
req.headers['Accept'] = 'application/json'
res = req.get_response(fakes.wsgi_app())
res_dict = json.loads(res.body)
self.assertEqual(res.status_int, 400)
self.assertEqual(res_dict['badRequest']['code'], 400)
self.assertEqual(res_dict['badRequest']['message'],
'The server could not comply with the request since'
' it is either malformed or otherwise incorrect.')
db.volume_destroy(context.get_admin_context(), volume_id)
def test_accept_transfer_with_body_KeyError(self):
volume_id = self._create_volume(size=5)
transfer = self._create_transfer(volume_id)
req = webob.Request.blank('/v2/fake/os-volume-transfer/%s/accept' %
transfer['id'])
body = {"": {}}
req.method = 'POST'
req.headers['Content-Type'] = 'application/json'
req.headers['Accept'] = 'application/json'
req.body = json.dumps(body)
res = req.get_response(fakes.wsgi_app())
res_dict = json.loads(res.body)
self.assertEqual(res.status_int, 400)
self.assertEqual(res_dict['badRequest']['code'], 400)
self.assertEqual(res_dict['badRequest']['message'],
'The server could not comply with the request since'
' it is either malformed or otherwise incorrect.')
def test_accept_transfer_invalid_id_auth_key(self):
volume_id = self._create_volume()
transfer = self._create_transfer(volume_id)
body = {"accept": {"id": transfer['id'],
"auth_key": 1}}
req = webob.Request.blank('/v2/fake/os-volume-transfer/%s/accept' %
transfer['id'])
req.method = 'POST'
req.headers['Content-Type'] = 'application/json'
req.body = json.dumps(body)
res = req.get_response(fakes.wsgi_app())
res_dict = json.loads(res.body)
self.assertEqual(res.status_int, 400)
self.assertEqual(res_dict['badRequest']['code'], 400)
self.assertEqual(res_dict['badRequest']['message'],
'Invalid auth key: Attempt to transfer %s with '
'invalid auth key.' % transfer['id'])
db.transfer_destroy(context.get_admin_context(), transfer['id'])
db.volume_destroy(context.get_admin_context(), volume_id)
def test_accept_transfer_with_invalid_transfer(self):
volume_id = self._create_volume()
transfer = self._create_transfer(volume_id)
body = {"accept": {"id": transfer['id'],
"auth_key": 1}}
req = webob.Request.blank('/v2/fake/os-volume-transfer/1/accept')
req.method = 'POST'
req.headers['Content-Type'] = 'application/json'
req.body = json.dumps(body)
res = req.get_response(fakes.wsgi_app())
res_dict = json.loads(res.body)
self.assertEqual(res.status_int, 404)
self.assertEqual(res_dict['itemNotFound']['code'], 404)
self.assertEqual(res_dict['itemNotFound']['message'],
'TransferNotFound: Transfer 1 could not be found.')
db.transfer_destroy(context.get_admin_context(), transfer['id'])
db.volume_destroy(context.get_admin_context(), volume_id)
def test_accept_transfer_with_VolumeSizeExceedsAvailableQuota(self):
def fake_transfer_api_accept_throwing_VolumeSizeExceedsAvailableQuota(
cls, context, transfer, volume_id):
raise exception.VolumeSizeExceedsAvailableQuota(requested='2',
consumed='2',
quota='3')
self.stubs.Set(
cinder.transfer.API,
'accept',
fake_transfer_api_accept_throwing_VolumeSizeExceedsAvailableQuota)
volume_id = self._create_volume()
transfer = self._create_transfer(volume_id)
body = {"accept": {"id": transfer['id'],
"auth_key": transfer['auth_key']}}
req = webob.Request.blank('/v2/fake/os-volume-transfer/%s/accept' %
transfer['id'])
req.method = 'POST'
req.headers['Content-Type'] = 'application/json'
req.body = json.dumps(body)
res = req.get_response(fakes.wsgi_app())
res_dict = json.loads(res.body)
self.assertEqual(res.status_int, 413)
self.assertEqual(res_dict['overLimit']['code'], 413)
self.assertEqual(res_dict['overLimit']['message'],
'Requested volume or snapshot exceeds allowed '
'gigabytes quota. Requested 2G, quota is 3G and '
'2G has been consumed.')
def test_accept_transfer_with_VolumeLimitExceeded(self):
def fake_transfer_api_accept_throwing_VolumeLimitExceeded(cls,
context,
transfer,
volume_id):
raise exception.VolumeLimitExceeded(allowed=1)
self.stubs.Set(cinder.transfer.API, 'accept',
fake_transfer_api_accept_throwing_VolumeLimitExceeded)
volume_id = self._create_volume()
transfer = self._create_transfer(volume_id)
body = {"accept": {"id": transfer['id'],
"auth_key": transfer['auth_key']}}
req = webob.Request.blank('/v2/fake/os-volume-transfer/%s/accept' %
transfer['id'])
req.method = 'POST'
req.headers['Content-Type'] = 'application/json'
req.body = json.dumps(body)
res = req.get_response(fakes.wsgi_app())
res_dict = json.loads(res.body)
self.assertEqual(res.status_int, 413)
self.assertEqual(res_dict['overLimit']['code'], 413)
self.assertEqual(res_dict['overLimit']['message'],
'VolumeLimitExceeded: Maximum number of volumes '
'allowed (1) exceeded')
| apache-2.0 |
Ralitsa-Ts/Bookstore_and_Chart | book_information.py | 1 | 6347 | import sys
import os
sys.path.append("model")
from library import Library, Book
from PyQt4 import QtGui, QtCore
from functools import partial
class BookInformation(QtGui.QWidget):
def __init__(self):
super(BookInformation, self).__init__()
self.InitUI()
def InitUI(self):
self.table = QtGui.QTableWidget()
self.prepare_the_search()
self.prepare_the_folder_image()
self.fill_in_grid()
def fill_in_grid(self):
"""
Fill the gridLayout with all the widgets.
"""
self.grid = QtGui.QGridLayout()
self.grid.addLayout(self.search, 0, 0)
self.grid.addWidget(self.folder_image, 2, 0)
self.grid.setSpacing(10)
self.grid.setColumnStretch(0, 6)
self.grid.setRowStretch(1, 1)
self.grid.setRowStretch(2, 2)
vBoxlayout = QtGui.QVBoxLayout()
vBoxlayout.addLayout(self.grid)
self.setLayout(vBoxlayout)
def prepare_the_folder_image(self):
"""
Prepares the folder image so that it can be later added.
"""
self.folder_image = QtGui.QLabel()
self.folder_image.setPixmap(QtGui.QPixmap(
os.path.normpath("images/folder.jpg")))
self.folder_image.setFixedWidth(200)
self.folder_image.setFixedHeight(200)
def prepare_the_search(self):
"""
Prepares the search form.
"""
self.searchEdit = QtGui.QLineEdit()
self.searchEdit.setPlaceholderText("click to search")
self.Search = QtGui.QPushButton("Search")
self.Search.clicked.connect(self.update_table)
self.author = QtGui.QRadioButton("by author")
self.title = QtGui.QRadioButton("by title")
self.both = QtGui.QRadioButton("by both")
self.both.setChecked(True)
box = QtGui.QHBoxLayout()
box.addWidget(self.author)
box.addWidget(self.title)
box.addWidget(self.both)
self.search = QtGui.QGridLayout()
self.search.addWidget(self.searchEdit, 0, 0)
self.search.addWidget(self.Search, 0, 2)
self.search.addLayout(box, 1, 2)
self.search.setColumnStretch(0, 3)
self.search.setColumnStretch(3, 1)
def generate_book_by_row(self, row):
"""
Creates a book, which is in a certain row using the
information from the table cells.
"""
record = ""
for i in range(6):
data = self.table.item(row, i).text()
record += ("+" + data)
return Book.book_by_record(record[1:])
def get_a_copy(self, row):
"""
Take a copy of a certain book.
"""
if int(self.table.item(row, 5).text()) > 0:
book = Library.take_book(self.generate_book_by_row(row))
item = QtGui.QTableWidgetItem(str(book.number_of_copies))
self.table.setItem(row, 5, item)
def return_a_copy(self, row):
"""
Return a copy of a certain book.
"""
book = Library.return_book(self.generate_book_by_row(row))
item = QtGui.QTableWidgetItem(str(book.number_of_copies))
self.table.setItem(row, 5, item)
def like_a_book(self, row):
"""
Like a book-increases it's rating.
"""
book = Library.like_book(self.generate_book_by_row(row))
value = "%.2f" % book.rating
item = QtGui.QTableWidgetItem(str(value))
self.table.setItem(row, 4, item)
def dislike_a_book(self, row):
"""
Dislike a book-decreases it's rating.
"""
book = Library.dislike_book(self.generate_book_by_row(row))
value = "%.2f" % book.rating
item = QtGui.QTableWidgetItem(str(value))
self.table.setItem(row, 4, item)
def update_table(self):
"""
Update the table after clicking the Search button.
"""
self.table.setRowCount(0)
self.table.setColumnCount(0)
search = self.searchEdit.text()
if self.author.isChecked():
results = Library.book_information_by_author(search)
elif self.title.isChecked():
results = Library.book_information_by_title(search)
else:
results = Library.book_information_by_title_author(search)
self.table = QtGui.QTableWidget(len(results), 10, self)
headers = ("Title", "Author's name", "Published in", "Genre",
"Rating", "Copies", "Get", "Return", "Like", " Dislike")
self.table.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
self.table.setHorizontalHeaderLabels(headers)
self.table.resizeColumnsToContents()
self.table.resizeRowsToContents()
widths = [150, 150, 90, 80, 70, 60, 50, 60, 50, 70]
for col, width in zip(range(9), widths):
self.table.setColumnWidth(col, width)
self.table.horizontalHeader().setStretchLastSection(True)
for row in range(len(results)):
book = results[row]
col = 0
for column in (book.title, book.author, book.year, book.genre,
book.rating, book.number_of_copies):
item = QtGui.QTableWidgetItem(str(column))
self.table.setItem(row, col, item)
col += 1
for row in range(len(results)):
get_btn = QtGui.QPushButton("Get")
get_btn.setMinimumSize(50, 30)
get_btn.clicked.connect(partial(self.get_a_copy, row))
self.table.setCellWidget(row, 6, get_btn)
return_btn = QtGui.QPushButton("Return")
return_btn.setMinimumSize(50, 30)
return_btn.clicked.connect(partial(self.return_a_copy, row))
self.table.setCellWidget(row, 7, return_btn)
like_btn = QtGui.QPushButton("Like")
like_btn.setMinimumSize(50, 30)
like_btn.clicked.connect(partial(self.like_a_book, row))
self.table.setCellWidget(row, 8, like_btn)
dislike_btn = QtGui.QPushButton("Dislike")
dislike_btn.setMinimumSize(50, 30)
dislike_btn.clicked.connect(partial(self.dislike_a_book, row))
self.table.setCellWidget(row, 9, dislike_btn)
self.grid.addWidget(self.table, 1, 0)
| gpl-3.0 |
synctree/synctree-awsebcli | ebcli/controllers/config.py | 1 | 5151 | # Copyright 2014 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
import sys
from cement.core.controller import expose
from ..core.abstractcontroller import AbstractBaseController
from ..resources.strings import strings, flag_text
from ..core import io, fileoperations
from ..operations import saved_configs, commonops, configops
from ..objects.exceptions import InvalidSyntaxError, NotFoundError
from ..lib import utils
class ConfigController(AbstractBaseController):
class Meta:
label = 'config'
description = strings['config.info']
usage = 'eb config < |save|get|put|list|delete> <name> [options ...]'
arguments = [
(['name'], dict(action='store', nargs='?',
default=[],
help='environment_name|template_name')),
(['-nh', '--nohang'], dict(action='store_true',
help=flag_text['config.nohang'])),
(['--timeout'], dict(type=int, help=flag_text['general.timeout'])),
(['--cfg'], dict(help='name of configuration'))
]
epilog = strings['config.epilog']
def do_command(self):
app_name = self.get_app_name()
env_name = self.get_env_name(varname='name')
timeout = self.app.pargs.timeout
nohang = self.app.pargs.nohang
cfg = self.app.pargs.cfg
# input_exists = False
input_exists = not sys.stdin.isatty()
if not cfg and not input_exists:
# No input, run interactive editor
configops.update_environment_configuration(app_name, env_name,
nohang,
timeout=timeout)
return
if cfg:
cfg_name = saved_configs.resolve_config_name(app_name, cfg)
saved_configs.update_environment_with_config_file(env_name,
cfg_name, nohang,
timeout=timeout)
elif input_exists:
data = sys.stdin.read()
saved_configs.update_environment_with_config_data(env_name, data,
nohang,
timeout=timeout)
@expose(help='Save a configuration of the environment.')
def save(self):
cfg_name = self.app.pargs.cfg
env_name = self.get_env_name(varname='name',
cmd_example='eb config save')
app_name = self.get_app_name()
if not cfg_name:
cfg_name = self._choose_cfg_name(app_name, env_name)
saved_configs.create_config(app_name, env_name, cfg_name)
@expose(help='Upload a configuration to S3.')
def put(self):
app_name = self.get_app_name()
name = self._get_cfg_name('put')
platform = commonops.get_default_solution_stack()
platform = commonops.get_solution_stack(platform)
platform = platform.name
saved_configs.update_config(app_name, name)
saved_configs.validate_config_file(app_name, name, platform)
@expose(help='Download a configuration from S3.')
def get(self):
app_name = self.get_app_name()
name = self._get_cfg_name('get')
try:
saved_configs.download_config_from_s3(app_name, name)
except NotFoundError:
io.log_error(strings['config.notfound'].replace('{config-name}',
name))
@expose(help='Delete a configuration.')
def delete(self):
name = self._get_cfg_name('delete')
app_name = self.get_app_name()
saved_configs.delete_config(app_name, name)
@expose(help='List all configurations.')
def list(self):
app_name = self.get_app_name()
for c in saved_configs.get_configurations(app_name):
io.echo(c)
def _get_cfg_name(self, cmd):
name = self.app.pargs.name
if not name:
io.echo('usage: eb config', cmd, '[configuration_name]')
raise InvalidSyntaxError('too few arguments')
else:
return name
@staticmethod
def _choose_cfg_name(app_name, env_name):
configs = saved_configs.get_configurations(app_name)
io.echo()
io.echo('Enter desired name of configuration.')
default = utils.get_unique_name(env_name + '-sc', configs)
cfg_name = io.prompt_for_unique_name(default, configs)
return cfg_name
| apache-2.0 |
dfang/odoo | addons/website_hr_recruitment/controllers/main.py | 13 | 4316 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import http, _
from odoo.addons.website.models.website import slug
from odoo.http import request
class WebsiteHrRecruitment(http.Controller):
@http.route([
'/jobs',
'/jobs/country/<model("res.country"):country>',
'/jobs/department/<model("hr.department"):department>',
'/jobs/country/<model("res.country"):country>/department/<model("hr.department"):department>',
'/jobs/office/<int:office_id>',
'/jobs/country/<model("res.country"):country>/office/<int:office_id>',
'/jobs/department/<model("hr.department"):department>/office/<int:office_id>',
'/jobs/country/<model("res.country"):country>/department/<model("hr.department"):department>/office/<int:office_id>',
], type='http', auth="public", website=True)
def jobs(self, country=None, department=None, office_id=None, **kwargs):
env = request.env(context=dict(request.env.context, show_address=True, no_tag_br=True))
Country = env['res.country']
Jobs = env['hr.job']
# List jobs available to current UID
job_ids = Jobs.search([], order="website_published desc,no_of_recruitment desc").ids
# Browse jobs as superuser, because address is restricted
jobs = Jobs.sudo().browse(job_ids)
# Default search by user country
if not (country or department or office_id or kwargs.get('all_countries')):
country_code = request.session['geoip'].get('country_code')
if country_code:
countries_ = Country.search([('code', '=', country_code)])
country = countries_[0] if countries_ else None
if not any(j for j in jobs if j.address_id and j.address_id.country_id == country):
country = False
# Filter job / office for country
if country and not kwargs.get('all_countries'):
jobs = [j for j in jobs if j.address_id is None or j.address_id.country_id and j.address_id.country_id.id == country.id]
offices = set(j.address_id for j in jobs if j.address_id is None or j.address_id.country_id and j.address_id.country_id.id == country.id)
else:
offices = set(j.address_id for j in jobs if j.address_id)
# Deduce departments and countries offices of those jobs
departments = set(j.department_id for j in jobs if j.department_id)
countries = set(o.country_id for o in offices if o.country_id)
if department:
jobs = (j for j in jobs if j.department_id and j.department_id.id == department.id)
if office_id and office_id in map(lambda x: x.id, offices):
jobs = (j for j in jobs if j.address_id and j.address_id.id == office_id)
else:
office_id = False
# Render page
return request.render("website_hr_recruitment.index", {
'jobs': jobs,
'countries': countries,
'departments': departments,
'offices': offices,
'country_id': country,
'department_id': department,
'office_id': office_id,
})
@http.route('/jobs/add', type='http', auth="user", website=True)
def jobs_add(self, **kwargs):
job = request.env['hr.job'].create({
'name': _('Job Title'),
})
return request.redirect("/jobs/detail/%s?enable_editor=1" % slug(job))
@http.route('/jobs/detail/<model("hr.job"):job>', type='http', auth="public", website=True)
def jobs_detail(self, job, **kwargs):
return request.render("website_hr_recruitment.detail", {
'job': job,
'main_object': job,
})
@http.route('/jobs/apply/<model("hr.job"):job>', type='http', auth="public", website=True)
def jobs_apply(self, job, **kwargs):
error = {}
default = {}
if 'website_hr_recruitment_error' in request.session:
error = request.session.pop('website_hr_recruitment_error')
default = request.session.pop('website_hr_recruitment_default')
return request.render("website_hr_recruitment.apply", {
'job': job,
'error': error,
'default': default,
})
| agpl-3.0 |
leeseulstack/openstack | neutron/db/migration/alembic_migrations/agent_init_ops.py | 17 | 1725 | # Copyright 2014 OpenStack Foundation
#
# 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.
#
# Initial operations for agent management extension
# This module only manages the 'agents' table. Binding tables are created
# in the modules for relevant resources
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_table(
'agents',
sa.Column('id', sa.String(length=36), nullable=False),
sa.Column('agent_type', sa.String(length=255), nullable=False),
sa.Column('binary', sa.String(length=255), nullable=False),
sa.Column('topic', sa.String(length=255), nullable=False),
sa.Column('host', sa.String(length=255), nullable=False),
sa.Column('admin_state_up', sa.Boolean(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('started_at', sa.DateTime(), nullable=False),
sa.Column('heartbeat_timestamp', sa.DateTime(), nullable=False),
sa.Column('description', sa.String(length=255), nullable=True),
sa.Column('configurations', sa.String(length=4095), nullable=False),
sa.PrimaryKeyConstraint('id'))
def downgrade():
op.drop_table('agents')
| apache-2.0 |
dvberkel/servo | python/mozlog/mozlog/structured/formatters/xunit.py | 46 | 3804 | import types
from xml.etree import ElementTree
import base
def format_test_id(test_id):
"""Take a test id and return something that looks a bit like
a class path"""
if type(test_id) not in types.StringTypes:
#Not sure how to deal with reftests yet
raise NotImplementedError
#Turn a path into something like a class heirachy
return test_id.replace('.', '_').replace('/', ".")
class XUnitFormatter(base.BaseFormatter):
"""Formatter that produces XUnit-style XML output.
The tree is created in-memory so this formatter may be problematic
with very large log files.
Note that the data model isn't a perfect match. In
particular XUnit assumes that each test has a unittest-style
class name and function name, which isn't the case for us. The
implementation currently replaces path names with something that
looks like class names, but this doesn't work for test types that
actually produce class names, or for test types that have multiple
components in their test id (e.g. reftests)."""
def __init__(self):
self.tree = ElementTree.ElementTree()
self.root = None
self.suite_start_time = None
self.test_start_time = None
self.tests_run = 0
self.errors = 0
self.failures = 0
self.skips = 0
def suite_start(self, data):
self.root = ElementTree.Element("testsuite")
self.tree.root = self.root
self.suite_start_time = data["time"]
def test_start(self, data):
self.tests_run += 1
self.test_start_time = data["time"]
def _create_result(self, data):
test = ElementTree.SubElement(self.root, "testcase")
name = format_test_id(data["test"])
extra = data.get('extra') or {}
test.attrib["classname"] = extra.get('class_name') or name
if "subtest" in data:
test.attrib["name"] = data["subtest"]
# We generally don't know how long subtests take
test.attrib["time"] = "0"
else:
if "." in name:
test_name = name.rsplit(".", 1)[1]
else:
test_name = name
test.attrib["name"] = extra.get('method_name') or test_name
test.attrib["time"] = "%.2f" % ((data["time"] - self.test_start_time) / 1000.0)
if ("expected" in data and data["expected"] != data["status"]):
if data["status"] in ("NOTRUN", "ASSERT", "ERROR"):
result = ElementTree.SubElement(test, "error")
self.errors += 1
else:
result = ElementTree.SubElement(test, "failure")
self.failures += 1
result.attrib["message"] = "Expected %s, got %s" % (data["expected"], data["status"])
result.text = '%s\n%s' % (data.get('stack', ''), data.get('message', ''))
elif data["status"] == "SKIP":
result = ElementTree.SubElement(test, "skipped")
self.skips += 1
def test_status(self, data):
self._create_result(data)
def test_end(self, data):
self._create_result(data)
def suite_end(self, data):
self.root.attrib.update({"tests": str(self.tests_run),
"errors": str(self.errors),
"failures": str(self.failures),
"skips": str(self.skips),
"time": "%.2f" % (
(data["time"] - self.suite_start_time) / 1000.0)})
xml_string = ElementTree.tostring(self.root, encoding="utf8")
# pretty printing can not be done from xml.etree
from xml.dom import minidom
return minidom.parseString(xml_string).toprettyxml(encoding="utf8")
| mpl-2.0 |
stven/headphones | lib/requests/packages/chardet2/constants.py | 231 | 1374 | ######################## BEGIN LICENSE BLOCK ########################
# The Original Code is Mozilla Universal charset detector code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 2001
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Mark Pilgrim - port to Python
# Shy Shalom - original C code
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA
######################### END LICENSE BLOCK #########################
_debug = 0
eDetecting = 0
eFoundIt = 1
eNotMe = 2
eStart = 0
eError = 1
eItsMe = 2
SHORTCUT_THRESHOLD = 0.95
| gpl-3.0 |
sudikrt/costproML | testproject/temp/test.py | 1 | 3011 | '''
Import Libs
'''
import pandas as pd
import numpy as np
from pandas.tools.plotting import scatter_matrix
from sklearn import model_selection
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.naive_bayes import GaussianNB
from sklearn.svm import SVC
from sklearn.neighbors import KNeighborsClassifier
from sklearn.cross_validation import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
from math import sin, cos, sqrt, atan2, radians
def finddist (lat1,lon1,lat2,lon2):
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2
c = 2 * atan2(sqrt(a), sqrt(1 - a))
distance = R * c
return distance
#Read Data
dataset = pd.read_csv("damnm.csv", dtype={'supplydemand':'int','cost':'int'})
#print shape
print dataset.shape
#description
print dataset.describe()
#class
print (dataset.groupby('job').size())
print dataset.columns
dataset['lat'] = dataset['lat'].apply(lambda x: str(x))
dataset['lng'] = dataset['lng'].apply(lambda x: str(x))
#dataset['id'] = dataset['id'].apply(pd.to_numeric)
dataset['id'] = dataset['id'].apply(lambda x: int(x))
dataset['cost'] = dataset['cost'].apply(lambda x: int(x))
print dataset.dtypes
'''
print dataset.describe()
columns = dataset.columns.tolist()
job="Tester"
radius=10
df_ = pd.DataFrame()
for index, row in dataset.iterrows():
if (row["job"] == job):
df_.append(np.array(row))
print df_
columns = dataset.columns.tolist()
columns = [c for c in columns if c not in ["job", "place", "cost"]]
target = "cost"
train = dataset.sample(frac = 0.8, random_state = 1)
test = dataset.loc[~dataset.index.isin(train.index)]
print(train.shape)
print(test.shape)
model = LinearRegression()
model.fit(train[columns], train[target])
predictions = model.predict(test[columns])
print test["cost"]
print predictions
print 'Error rate', mean_squared_error(predictions, test[target])
'''
array = dataset.values
X = array[:,3:6]
Y = array[:,6]
print X
validation_size = 0.20
seed = 7
X_train, X_validation, Y_train, Y_validation = model_selection.train_test_split(X, Y, test_size=validation_size, random_state=seed)
knn = SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,
decision_function_shape=None, degree=3, gamma='auto', kernel='rbf',
max_iter=-1, probability=False, random_state=None, shrinking=True,
tol=0.001, verbose=False)
#knn = KNeighborsClassifier()
knn.fit(X_train, Y_train)
predictions = knn.predict(X_validation)
print(accuracy_score(Y_validation, predictions))
print(confusion_matrix(Y_validation, predictions))
print(classification_report(Y_validation, predictions))
| apache-2.0 |
syscoin/syscoin2 | test/functional/wallet_import_rescan.py | 1 | 10824 | #!/usr/bin/env python3
# Copyright (c) 2014-2019 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test wallet import RPCs.
Test rescan behavior of importaddress, importpubkey, importprivkey, and
importmulti RPCs with different types of keys and rescan options.
In the first part of the test, node 0 creates an address for each type of
import RPC call and sends SYS to it. Then other nodes import the addresses,
and the test makes listtransactions and getbalance calls to confirm that the
importing node either did or did not execute rescans picking up the send
transactions.
In the second part of the test, node 0 sends more SYS to each address, and the
test makes more listtransactions and getbalance calls to confirm that the
importing nodes pick up the new transactions regardless of whether rescans
happened previously.
"""
from test_framework.test_framework import SyscoinTestFramework
from test_framework.address import AddressType
from test_framework.util import (
connect_nodes,
assert_equal,
set_node_times,
)
import collections
from decimal import Decimal
import enum
import itertools
import random
Call = enum.Enum("Call", "single multiaddress multiscript")
Data = enum.Enum("Data", "address pub priv")
Rescan = enum.Enum("Rescan", "no yes late_timestamp")
class Variant(collections.namedtuple("Variant", "call data address_type rescan prune")):
"""Helper for importing one key and verifying scanned transactions."""
def do_import(self, timestamp):
"""Call one key import RPC."""
rescan = self.rescan == Rescan.yes
assert_equal(self.address["solvable"], True)
assert_equal(self.address["isscript"], self.address_type == AddressType.p2sh_segwit)
assert_equal(self.address["iswitness"], self.address_type == AddressType.bech32)
if self.address["isscript"]:
assert_equal(self.address["embedded"]["isscript"], False)
assert_equal(self.address["embedded"]["iswitness"], True)
if self.call == Call.single:
if self.data == Data.address:
response = self.node.importaddress(address=self.address["address"], label=self.label, rescan=rescan)
elif self.data == Data.pub:
response = self.node.importpubkey(pubkey=self.address["pubkey"], label=self.label, rescan=rescan)
elif self.data == Data.priv:
response = self.node.importprivkey(privkey=self.key, label=self.label, rescan=rescan)
assert_equal(response, None)
elif self.call in (Call.multiaddress, Call.multiscript):
request = {
"scriptPubKey": {
"address": self.address["address"]
} if self.call == Call.multiaddress else self.address["scriptPubKey"],
"timestamp": timestamp + TIMESTAMP_WINDOW + (1 if self.rescan == Rescan.late_timestamp else 0),
"pubkeys": [self.address["pubkey"]] if self.data == Data.pub else [],
"keys": [self.key] if self.data == Data.priv else [],
"label": self.label,
"watchonly": self.data != Data.priv
}
if self.address_type == AddressType.p2sh_segwit and self.data != Data.address:
# We need solving data when providing a pubkey or privkey as data
request.update({"redeemscript": self.address['embedded']['scriptPubKey']})
response = self.node.importmulti(
requests=[request],
options={"rescan": self.rescan in (Rescan.yes, Rescan.late_timestamp)},
)
assert_equal(response, [{"success": True}])
def check(self, txid=None, amount=None, confirmation_height=None):
"""Verify that listtransactions/listreceivedbyaddress return expected values."""
txs = self.node.listtransactions(label=self.label, count=10000, include_watchonly=True)
current_height = self.node.getblockcount()
assert_equal(len(txs), self.expected_txs)
addresses = self.node.listreceivedbyaddress(minconf=0, include_watchonly=True, address_filter=self.address['address'])
if self.expected_txs:
assert_equal(len(addresses[0]["txids"]), self.expected_txs)
if txid is not None:
tx, = [tx for tx in txs if tx["txid"] == txid]
assert_equal(tx["label"], self.label)
assert_equal(tx["address"], self.address["address"])
assert_equal(tx["amount"], amount)
assert_equal(tx["category"], "receive")
assert_equal(tx["label"], self.label)
assert_equal(tx["txid"], txid)
assert_equal(tx["confirmations"], 1 + current_height - confirmation_height)
assert_equal("trusted" not in tx, True)
address, = [ad for ad in addresses if txid in ad["txids"]]
assert_equal(address["address"], self.address["address"])
assert_equal(address["amount"], self.expected_balance)
assert_equal(address["confirmations"], 1 + current_height - confirmation_height)
# Verify the transaction is correctly marked watchonly depending on
# whether the transaction pays to an imported public key or
# imported private key. The test setup ensures that transaction
# inputs will not be from watchonly keys (important because
# involvesWatchonly will be true if either the transaction output
# or inputs are watchonly).
if self.data != Data.priv:
assert_equal(address["involvesWatchonly"], True)
else:
assert_equal("involvesWatchonly" not in address, True)
# List of Variants for each way a key or address could be imported.
IMPORT_VARIANTS = [Variant(*variants) for variants in itertools.product(Call, Data, AddressType, Rescan, (False, True))]
# List of nodes to import keys to. Half the nodes will have pruning disabled,
# half will have it enabled. Different nodes will be used for imports that are
# expected to cause rescans, and imports that are not expected to cause
# rescans, in order to prevent rescans during later imports picking up
# transactions associated with earlier imports. This makes it easier to keep
# track of expected balances and transactions.
ImportNode = collections.namedtuple("ImportNode", "prune rescan")
IMPORT_NODES = [ImportNode(*fields) for fields in itertools.product((False, True), repeat=2)]
# Rescans start at the earliest block up to 2 hours before the key timestamp.
TIMESTAMP_WINDOW = 2 * 60 * 60
AMOUNT_DUST = 0.00000546
def get_rand_amount():
r = random.uniform(AMOUNT_DUST, 1)
return Decimal(str(round(r, 8)))
class ImportRescanTest(SyscoinTestFramework):
def set_test_params(self):
self.num_nodes = 2 + len(IMPORT_NODES)
self.supports_cli = False
def skip_test_if_missing_module(self):
self.skip_if_no_wallet()
def setup_network(self):
self.extra_args = [[] for _ in range(self.num_nodes)]
for i, import_node in enumerate(IMPORT_NODES, 2):
if import_node.prune:
self.extra_args[i] += ["-prune=1"]
self.add_nodes(self.num_nodes, extra_args=self.extra_args)
# Import keys with pruning disabled
self.start_nodes(extra_args=[[]] * self.num_nodes)
for n in self.nodes:
n.importprivkey(privkey=n.get_deterministic_priv_key().key, label='coinbase')
self.stop_nodes()
self.start_nodes()
for i in range(1, self.num_nodes):
connect_nodes(self.nodes[i], 0)
def run_test(self):
# Create one transaction on node 0 with a unique amount for
# each possible type of wallet import RPC.
for i, variant in enumerate(IMPORT_VARIANTS):
variant.label = "label {} {}".format(i, variant)
variant.address = self.nodes[1].getaddressinfo(self.nodes[1].getnewaddress(
label=variant.label,
address_type=variant.address_type.value,
))
variant.key = self.nodes[1].dumpprivkey(variant.address["address"])
variant.initial_amount = get_rand_amount()
variant.initial_txid = self.nodes[0].sendtoaddress(variant.address["address"], variant.initial_amount)
self.nodes[0].generate(1) # Generate one block for each send
variant.confirmation_height = self.nodes[0].getblockcount()
variant.timestamp = self.nodes[0].getblockheader(self.nodes[0].getbestblockhash())["time"]
# Generate a block further in the future (past the rescan window).
assert_equal(self.nodes[0].getrawmempool(), [])
set_node_times(
self.nodes,
self.nodes[0].getblockheader(self.nodes[0].getbestblockhash())["time"] + TIMESTAMP_WINDOW + 1,
)
self.nodes[0].generate(1)
self.sync_all()
# For each variation of wallet key import, invoke the import RPC and
# check the results from getbalance and listtransactions.
for variant in IMPORT_VARIANTS:
self.log.info('Run import for variant {}'.format(variant))
expect_rescan = variant.rescan == Rescan.yes
variant.node = self.nodes[2 + IMPORT_NODES.index(ImportNode(variant.prune, expect_rescan))]
variant.do_import(variant.timestamp)
if expect_rescan:
variant.expected_balance = variant.initial_amount
variant.expected_txs = 1
variant.check(variant.initial_txid, variant.initial_amount, variant.confirmation_height)
else:
variant.expected_balance = 0
variant.expected_txs = 0
variant.check()
# Create new transactions sending to each address.
for i, variant in enumerate(IMPORT_VARIANTS):
variant.sent_amount = get_rand_amount()
variant.sent_txid = self.nodes[0].sendtoaddress(variant.address["address"], variant.sent_amount)
self.nodes[0].generate(1) # Generate one block for each send
variant.confirmation_height = self.nodes[0].getblockcount()
assert_equal(self.nodes[0].getrawmempool(), [])
self.sync_all()
# Check the latest results from getbalance and listtransactions.
for variant in IMPORT_VARIANTS:
self.log.info('Run check for variant {}'.format(variant))
variant.expected_balance += variant.sent_amount
variant.expected_txs += 1
variant.check(variant.sent_txid, variant.sent_amount, variant.confirmation_height)
if __name__ == "__main__":
ImportRescanTest().main()
| mit |
tbabej/freeipa | ipatests/test_install/test_updates.py | 1 | 12377 | # Authors:
# Rob Crittenden <rcritten@redhat.com>
#
# Copyright (C) 2009 Red Hat
# see file 'COPYING' for use and warranty information
#
# 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/>.
"""
Test the `ipaserver/install/ldapupdate.py` module.
"""
import unittest
import os
import nose
import pytest
from ipalib import api
from ipalib import errors
from ipaserver.install.ldapupdate import LDAPUpdate, BadSyntax
from ipaserver.install import installutils
from ipapython import ipautil, ipaldap
from ipaplatform.paths import paths
from ipapython.dn import DN
"""
The updater works through files only so this is just a thin-wrapper controlling
which file we test at any given point.
IMPORTANT NOTE: It is easy for these tests to get out of sync. Any changes
made to the update files may require changes to the test cases as well.
Some cases pull records from LDAP and do comparisons to ensure that updates
have occurred as expected.
The DM password needs to be set in ~/.ipa/.dmpw
"""
@pytest.mark.tier0
class test_update(unittest.TestCase):
"""
Test the LDAP updater.
"""
def setUp(self):
fqdn = installutils.get_fqdn()
pwfile = api.env.dot_ipa + os.sep + ".dmpw"
if ipautil.file_exists(pwfile):
fp = open(pwfile, "r")
self.dm_password = fp.read().rstrip()
fp.close()
else:
raise nose.SkipTest("No directory manager password")
self.updater = LDAPUpdate(dm_password=self.dm_password, sub_dict={})
self.ld = ipaldap.IPAdmin(fqdn)
self.ld.do_simple_bind(bindpw=self.dm_password)
if ipautil.file_exists("0_reset.update"):
self.testdir="./"
elif ipautil.file_exists("ipatests/test_install/0_reset.update"):
self.testdir= "./ipatests/test_install/"
else:
raise nose.SkipTest("Unable to find test update files")
self.container_dn = DN(self.updater._template_str('cn=test, cn=accounts, $SUFFIX'))
self.user_dn = DN(self.updater._template_str('uid=tuser, cn=test, cn=accounts, $SUFFIX'))
def tearDown(self):
if self.ld:
self.ld.unbind()
def test_0_reset(self):
"""
Reset the updater test data to a known initial state (test_0_reset)
"""
try:
modified = self.updater.update([self.testdir + "0_reset.update"])
except errors.NotFound:
# Just means the entry doesn't exist yet
modified = True
self.assertTrue(modified)
with self.assertRaises(errors.NotFound):
entries = self.ld.get_entries(
self.container_dn, self.ld.SCOPE_BASE, 'objectclass=*', ['*'])
with self.assertRaises(errors.NotFound):
entries = self.ld.get_entries(
self.user_dn, self.ld.SCOPE_BASE, 'objectclass=*', ['*'])
def test_1_add(self):
"""
Test the updater with an add directive (test_1_add)
"""
modified = self.updater.update([self.testdir + "1_add.update"])
self.assertTrue(modified)
entries = self.ld.get_entries(
self.container_dn, self.ld.SCOPE_BASE, 'objectclass=*', ['*'])
self.assertEqual(len(entries), 1)
entry = entries[0]
objectclasses = entry.get('objectclass')
for item in ('top', 'nsContainer'):
self.assertTrue(item in objectclasses)
self.assertEqual(entry.single_value['cn'], 'test')
entries = self.ld.get_entries(
self.user_dn, self.ld.SCOPE_BASE, 'objectclass=*', ['*'])
self.assertEqual(len(entries), 1)
entry = entries[0]
objectclasses = entry.get('objectclass')
for item in ('top', 'person', 'posixaccount', 'krbprincipalaux', 'inetuser'):
self.assertTrue(item in objectclasses)
self.assertEqual(entry.single_value['loginshell'], paths.BASH)
self.assertEqual(entry.single_value['sn'], 'User')
self.assertEqual(entry.single_value['uid'], 'tuser')
self.assertEqual(entry.single_value['cn'], 'Test User')
def test_2_update(self):
"""
Test the updater when adding an attribute to an existing entry (test_2_update)
"""
modified = self.updater.update([self.testdir + "2_update.update"])
self.assertTrue(modified)
entries = self.ld.get_entries(
self.user_dn, self.ld.SCOPE_BASE, 'objectclass=*', ['*'])
self.assertEqual(len(entries), 1)
entry = entries[0]
self.assertEqual(entry.single_value['gecos'], 'Test User')
def test_3_update(self):
"""
Test the updater forcing an attribute to a given value (test_3_update)
"""
modified = self.updater.update([self.testdir + "3_update.update"])
self.assertTrue(modified)
entries = self.ld.get_entries(
self.user_dn, self.ld.SCOPE_BASE, 'objectclass=*', ['*'])
self.assertEqual(len(entries), 1)
entry = entries[0]
self.assertEqual(entry.single_value['gecos'], 'Test User New')
def test_4_update(self):
"""
Test the updater adding a new value to a single-valued attribute (test_4_update)
"""
modified = self.updater.update([self.testdir + "4_update.update"])
self.assertTrue(modified)
entries = self.ld.get_entries(
self.user_dn, self.ld.SCOPE_BASE, 'objectclass=*', ['*'])
self.assertEqual(len(entries), 1)
entry = entries[0]
self.assertEqual(entry.single_value['gecos'], 'Test User New2')
def test_5_update(self):
"""
Test the updater adding a new value to a multi-valued attribute (test_5_update)
"""
modified = self.updater.update([self.testdir + "5_update.update"])
self.assertTrue(modified)
entries = self.ld.get_entries(
self.user_dn, self.ld.SCOPE_BASE, 'objectclass=*', ['*'])
self.assertEqual(len(entries), 1)
entry = entries[0]
self.assertEqual(sorted(entry.get('cn')), sorted(['Test User', 'Test User New']))
def test_6_update(self):
"""
Test the updater removing a value from a multi-valued attribute (test_6_update)
"""
modified = self.updater.update([self.testdir + "6_update.update"])
self.assertTrue(modified)
entries = self.ld.get_entries(
self.user_dn, self.ld.SCOPE_BASE, 'objectclass=*', ['*'])
self.assertEqual(len(entries), 1)
entry = entries[0]
self.assertEqual(sorted(entry.get('cn')), sorted(['Test User']))
def test_6_update_1(self):
"""
Test the updater removing a non-existent value from a multi-valued attribute (test_6_update_1)
"""
modified = self.updater.update([self.testdir + "6_update.update"])
self.assertFalse(modified)
entries = self.ld.get_entries(
self.user_dn, self.ld.SCOPE_BASE, 'objectclass=*', ['*'])
self.assertEqual(len(entries), 1)
entry = entries[0]
self.assertEqual(sorted(entry.get('cn')), sorted(['Test User']))
def test_7_cleanup(self):
"""
Reset the test data to a known initial state (test_7_cleanup)
"""
try:
modified = self.updater.update([self.testdir + "0_reset.update"])
except errors.NotFound:
# Just means the entry doesn't exist yet
modified = True
self.assertTrue(modified)
with self.assertRaises(errors.NotFound):
entries = self.ld.get_entries(
self.container_dn, self.ld.SCOPE_BASE, 'objectclass=*', ['*'])
with self.assertRaises(errors.NotFound):
entries = self.ld.get_entries(
self.user_dn, self.ld.SCOPE_BASE, 'objectclass=*', ['*'])
def test_8_badsyntax(self):
"""
Test the updater with an unknown keyword (test_8_badsyntax)
"""
with self.assertRaises(BadSyntax):
modified = self.updater.update([self.testdir + "8_badsyntax.update"])
def test_9_badsyntax(self):
"""
Test the updater with an incomplete line (test_9_badsyntax)
"""
with self.assertRaises(BadSyntax):
modified = self.updater.update([self.testdir + "9_badsyntax.update"])
def test_from_dict(self):
"""
Test updating from a dict.
This replicates what was done in test 1.
"""
# First make sure we're clean
with self.assertRaises(errors.NotFound):
entries = self.ld.get_entries(
self.container_dn, self.ld.SCOPE_BASE, 'objectclass=*', ['*'])
with self.assertRaises(errors.NotFound):
entries = self.ld.get_entries(
self.user_dn, self.ld.SCOPE_BASE, 'objectclass=*', ['*'])
update = {
self.container_dn:
{'dn': self.container_dn,
'updates': ['add:objectClass: top',
'add:objectClass: nsContainer',
'add:cn: test'
],
},
self.user_dn:
{'dn': self.user_dn,
'updates': ['add:objectclass: top',
'add:objectclass: person',
'add:objectclass: posixaccount',
'add:objectclass: krbprincipalaux',
'add:objectclass: inetuser',
'add:homedirectory: /home/tuser',
'add:loginshell: /bin/bash',
'add:sn: User',
'add:uid: tuser',
'add:uidnumber: 999',
'add:gidnumber: 999',
'add:cn: Test User',
],
},
}
modified = self.updater.update_from_dict(update)
self.assertTrue(modified)
entries = self.ld.get_entries(
self.container_dn, self.ld.SCOPE_BASE, 'objectclass=*', ['*'])
self.assertEqual(len(entries), 1)
entry = entries[0]
objectclasses = entry.get('objectclass')
for item in ('top', 'nsContainer'):
self.assertTrue(item in objectclasses)
self.assertEqual(entry.single_value['cn'], 'test')
entries = self.ld.get_entries(
self.user_dn, self.ld.SCOPE_BASE, 'objectclass=*', ['*'])
self.assertEqual(len(entries), 1)
entry = entries[0]
objectclasses = entry.get('objectclass')
for item in ('top', 'person', 'posixaccount', 'krbprincipalaux', 'inetuser'):
self.assertTrue(item in objectclasses)
self.assertEqual(entry.single_value['loginshell'], paths.BASH)
self.assertEqual(entry.single_value['sn'], 'User')
self.assertEqual(entry.single_value['uid'], 'tuser')
self.assertEqual(entry.single_value['cn'], 'Test User')
# Now delete
update = {
self.container_dn:
{'dn': self.container_dn,
'deleteentry': None,
},
self.user_dn:
{'dn': self.user_dn,
'deleteentry': 'deleteentry: reset: nada',
},
}
modified = self.updater.update_from_dict(update)
self.assertTrue(modified)
with self.assertRaises(errors.NotFound):
entries = self.ld.get_entries(
self.container_dn, self.ld.SCOPE_BASE, 'objectclass=*', ['*'])
with self.assertRaises(errors.NotFound):
entries = self.ld.get_entries(
self.user_dn, self.ld.SCOPE_BASE, 'objectclass=*', ['*'])
| gpl-3.0 |
Antiun/odoo | addons/gamification/models/__init__.py | 389 | 1038 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2013 OpenERP SA (<http://openerp.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import goal
import challenge
import res_users
import badge
| agpl-3.0 |
40223209/test | static/Brython3.1.1-20150328-091302/Lib/gc.py | 743 | 3548 | """This module provides access to the garbage collector for reference cycles.
enable() -- Enable automatic garbage collection.
disable() -- Disable automatic garbage collection.
isenabled() -- Returns true if automatic collection is enabled.
collect() -- Do a full collection right now.
get_count() -- Return the current collection counts.
set_debug() -- Set debugging flags.
get_debug() -- Get debugging flags.
set_threshold() -- Set the collection thresholds.
get_threshold() -- Return the current the collection thresholds.
get_objects() -- Return a list of all objects tracked by the collector.
is_tracked() -- Returns true if a given object is tracked.
get_referrers() -- Return the list of objects that refer to an object.
get_referents() -- Return the list of objects that an object refers to.
"""
DEBUG_COLLECTABLE = 2
DEBUG_LEAK = 38
DEBUG_SAVEALL = 32
DEBUG_STATS = 1
DEBUG_UNCOLLECTABLE = 4
class __loader__:
pass
callbacks = []
def collect(*args,**kw):
"""collect([generation]) -> n
With no arguments, run a full collection. The optional argument
may be an integer specifying which generation to collect. A ValueError
is raised if the generation number is invalid.
The number of unreachable objects is returned.
"""
pass
def disable(*args,**kw):
"""disable() -> None
Disable automatic garbage collection.
"""
pass
def enable(*args,**kw):
"""enable() -> None
Enable automatic garbage collection.
"""
pass
garbage = []
def get_count(*args,**kw):
"""get_count() -> (count0, count1, count2)
Return the current collection counts
"""
pass
def get_debug(*args,**kw):
"""get_debug() -> flags
Get the garbage collection debugging flags.
"""
pass
def get_objects(*args,**kw):
"""get_objects() -> [...]
Return a list of objects tracked by the collector (excluding the list
returned).
"""
pass
def get_referents(*args,**kw):
"""get_referents(*objs) -> list Return the list of objects that are directly referred to by objs."""
pass
def get_referrers(*args,**kw):
"""get_referrers(*objs) -> list Return the list of objects that directly refer to any of objs."""
pass
def get_threshold(*args,**kw):
"""get_threshold() -> (threshold0, threshold1, threshold2)
Return the current collection thresholds
"""
pass
def is_tracked(*args,**kw):
"""is_tracked(obj) -> bool
Returns true if the object is tracked by the garbage collector.
Simple atomic objects will return false.
"""
pass
def isenabled(*args,**kw):
"""isenabled() -> status
Returns true if automatic garbage collection is enabled.
"""
pass
def set_debug(*args,**kw):
"""set_debug(flags) -> None
Set the garbage collection debugging flags. Debugging information is
written to sys.stderr.
flags is an integer and can have the following bits turned on:
DEBUG_STATS - Print statistics during collection.
DEBUG_COLLECTABLE - Print collectable objects found.
DEBUG_UNCOLLECTABLE - Print unreachable but uncollectable objects found.
DEBUG_SAVEALL - Save objects to gc.garbage rather than freeing them.
DEBUG_LEAK - Debug leaking programs (everything but STATS).
"""
pass
def set_threshold(*args,**kw):
"""set_threshold(threshold0, [threshold1, threshold2]) -> None
Sets the collection thresholds. Setting threshold0 to zero disables
collection.
"""
pass
| agpl-3.0 |
pmghalvorsen/gramps_branch | gramps/gen/filters/rules/family/__init__.py | 2 | 2872 | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2002-2007 Donald N. Allingham
# Copyright (C) 2007-2008 Brian G. Matherly
# Copyright (C) 2011 Tim G L Lyons
#
# 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.
#
"""
Package providing filter rules for GRAMPS.
"""
from ._searchfathername import SearchFatherName
from ._searchmothername import SearchMotherName
from ._searchchildname import SearchChildName
from ._regexpfathername import RegExpFatherName
from ._regexpmothername import RegExpMotherName
from ._regexpchildname import RegExpChildName
from ._hasreltype import HasRelType
from ._allfamilies import AllFamilies
from ._hasgallery import HasGallery
from ._hasidof import HasIdOf
from ._haslds import HasLDS
from ._regexpidof import RegExpIdOf
from ._hasnote import HasNote
from ._hasnoteregexp import HasNoteRegexp
from ._hasnotematchingsubstringof import HasNoteMatchingSubstringOf
from ._hassourcecount import HasSourceCount
from ._hassourceof import HasSourceOf
from ._hasreferencecountof import HasReferenceCountOf
from ._hascitation import HasCitation
from ._familyprivate import FamilyPrivate
from ._hasattribute import HasAttribute
from ._hasevent import HasEvent
from ._isbookmarked import IsBookmarked
from ._matchesfilter import MatchesFilter
from ._matchessourceconfidence import MatchesSourceConfidence
from ._fatherhasnameof import FatherHasNameOf
from ._fatherhasidof import FatherHasIdOf
from ._motherhasnameof import MotherHasNameOf
from ._motherhasidof import MotherHasIdOf
from ._childhasnameof import ChildHasNameOf
from ._childhasidof import ChildHasIdOf
from ._changedsince import ChangedSince
from ._hastag import HasTag
from ._hastwins import HasTwins
editor_rule_list = [
AllFamilies,
HasRelType,
HasGallery,
HasIdOf,
HasLDS,
HasNote,
RegExpIdOf,
HasNoteRegexp,
HasReferenceCountOf,
HasSourceCount,
HasSourceOf,
HasCitation,
FamilyPrivate,
HasEvent,
HasAttribute,
IsBookmarked,
MatchesFilter,
MatchesSourceConfidence,
FatherHasNameOf,
FatherHasIdOf,
MotherHasNameOf,
MotherHasIdOf,
ChildHasNameOf,
ChildHasIdOf,
ChangedSince,
HasTag,
HasTwins,
]
| gpl-2.0 |
Orochimarufan/youtube-dl | youtube_dl/extractor/telequebec.py | 4 | 6981 | # coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..compat import compat_str
from ..utils import (
int_or_none,
smuggle_url,
try_get,
unified_timestamp,
)
class TeleQuebecBaseIE(InfoExtractor):
@staticmethod
def _limelight_result(media_id):
return {
'_type': 'url_transparent',
'url': smuggle_url(
'limelight:media:' + media_id, {'geo_countries': ['CA']}),
'ie_key': 'LimelightMedia',
}
class TeleQuebecIE(TeleQuebecBaseIE):
_VALID_URL = r'''(?x)
https?://
(?:
zonevideo\.telequebec\.tv/media|
coucou\.telequebec\.tv/videos
)/(?P<id>\d+)
'''
_TESTS = [{
# available till 01.01.2023
'url': 'http://zonevideo.telequebec.tv/media/37578/un-petit-choc-et-puis-repart/un-chef-a-la-cabane',
'info_dict': {
'id': '577116881b4b439084e6b1cf4ef8b1b3',
'ext': 'mp4',
'title': 'Un petit choc et puis repart!',
'description': 'md5:b04a7e6b3f74e32d7b294cffe8658374',
},
'params': {
'skip_download': True,
},
}, {
# no description
'url': 'http://zonevideo.telequebec.tv/media/30261',
'only_matching': True,
}, {
'url': 'https://coucou.telequebec.tv/videos/41788/idee-de-genie/l-heure-du-bain',
'only_matching': True,
}]
def _real_extract(self, url):
media_id = self._match_id(url)
media_data = self._download_json(
'https://mnmedias.api.telequebec.tv/api/v2/media/' + media_id,
media_id)['media']
info = self._limelight_result(media_data['streamInfo']['sourceId'])
info.update({
'title': media_data.get('title'),
'description': try_get(
media_data, lambda x: x['descriptions'][0]['text'], compat_str),
'duration': int_or_none(
media_data.get('durationInMilliseconds'), 1000),
})
return info
class TeleQuebecSquatIE(InfoExtractor):
_VALID_URL = r'https://squat\.telequebec\.tv/videos/(?P<id>\d+)'
_TESTS = [{
'url': 'https://squat.telequebec.tv/videos/9314',
'info_dict': {
'id': 'd59ae78112d542e793d83cc9d3a5b530',
'ext': 'mp4',
'title': 'Poupeflekta',
'description': 'md5:2f0718f8d2f8fece1646ee25fb7bce75',
'duration': 1351,
'timestamp': 1569057600,
'upload_date': '20190921',
'series': 'Miraculous : Les Aventures de Ladybug et Chat Noir',
'season': 'Saison 3',
'season_number': 3,
'episode_number': 57,
},
'params': {
'skip_download': True,
},
}]
def _real_extract(self, url):
video_id = self._match_id(url)
video = self._download_json(
'https://squat.api.telequebec.tv/v1/videos/%s' % video_id,
video_id)
media_id = video['sourceId']
return {
'_type': 'url_transparent',
'url': 'http://zonevideo.telequebec.tv/media/%s' % media_id,
'ie_key': TeleQuebecIE.ie_key(),
'id': media_id,
'title': video.get('titre'),
'description': video.get('description'),
'timestamp': unified_timestamp(video.get('datePublication')),
'series': video.get('container'),
'season': video.get('saison'),
'season_number': int_or_none(video.get('noSaison')),
'episode_number': int_or_none(video.get('episode')),
}
class TeleQuebecEmissionIE(TeleQuebecBaseIE):
_VALID_URL = r'''(?x)
https?://
(?:
[^/]+\.telequebec\.tv/emissions/|
(?:www\.)?telequebec\.tv/
)
(?P<id>[^?#&]+)
'''
_TESTS = [{
'url': 'http://lindicemcsween.telequebec.tv/emissions/100430013/des-soins-esthetiques-a-377-d-interets-annuels-ca-vous-tente',
'info_dict': {
'id': '66648a6aef914fe3badda25e81a4d50a',
'ext': 'mp4',
'title': "Des soins esthétiques à 377 % d'intérêts annuels, ça vous tente?",
'description': 'md5:369e0d55d0083f1fc9b71ffb640ea014',
'upload_date': '20171024',
'timestamp': 1508862118,
},
'params': {
'skip_download': True,
},
}, {
'url': 'http://bancpublic.telequebec.tv/emissions/emission-49/31986/jeunes-meres-sous-pression',
'only_matching': True,
}, {
'url': 'http://www.telequebec.tv/masha-et-michka/epi059masha-et-michka-3-053-078',
'only_matching': True,
}, {
'url': 'http://www.telequebec.tv/documentaire/bebes-sur-mesure/',
'only_matching': True,
}]
def _real_extract(self, url):
display_id = self._match_id(url)
webpage = self._download_webpage(url, display_id)
media_id = self._search_regex(
r'mediaUID\s*:\s*["\'][Ll]imelight_(?P<id>[a-z0-9]{32})', webpage,
'limelight id')
info = self._limelight_result(media_id)
info.update({
'title': self._og_search_title(webpage, default=None),
'description': self._og_search_description(webpage, default=None),
})
return info
class TeleQuebecLiveIE(InfoExtractor):
_VALID_URL = r'https?://zonevideo\.telequebec\.tv/(?P<id>endirect)'
_TEST = {
'url': 'http://zonevideo.telequebec.tv/endirect/',
'info_dict': {
'id': 'endirect',
'ext': 'mp4',
'title': 're:^Télé-Québec - En direct [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
'is_live': True,
},
'params': {
'skip_download': True,
},
}
def _real_extract(self, url):
video_id = self._match_id(url)
m3u8_url = None
webpage = self._download_webpage(
'https://player.telequebec.tv/Tq_VideoPlayer.js', video_id,
fatal=False)
if webpage:
m3u8_url = self._search_regex(
r'm3U8Url\s*:\s*(["\'])(?P<url>(?:(?!\1).)+)\1', webpage,
'm3u8 url', default=None, group='url')
if not m3u8_url:
m3u8_url = 'https://teleqmmd.mmdlive.lldns.net/teleqmmd/f386e3b206814e1f8c8c1c71c0f8e748/manifest.m3u8'
formats = self._extract_m3u8_formats(
m3u8_url, video_id, 'mp4', m3u8_id='hls')
self._sort_formats(formats)
return {
'id': video_id,
'title': self._live_title('Télé-Québec - En direct'),
'is_live': True,
'formats': formats,
}
| unlicense |
mstriemer/olympia | tests/ui/pages/desktop/home.py | 4 | 1217 | from pypom import Region
from selenium.webdriver.common.by import By
from base import Base
class Home(Base):
@property
def most_popular(self):
return self.MostPopular(self)
class MostPopular(Region):
"""Most popular extensions region"""
_root_locator = (By.ID, 'popular-extensions')
_extension_locator = (By.CSS_SELECTOR, '.toplist li')
@property
def extensions(self):
return [self.Extension(self.page, el) for el in self.find_elements(
*self._extension_locator)]
class Extension(Region):
_name_locator = (By.CLASS_NAME, 'name')
_users_locator = (By.TAG_NAME, 'small')
def __repr__(self):
return '{0.name} ({0.users:,} users)'.format(self)
@property
def name(self):
"""Extension name"""
return self.find_element(*self._name_locator).text
@property
def users(self):
"""Number of users that have downloaded the extension"""
users_str = self.find_element(*self._users_locator).text
return int(users_str.split()[0].replace(',', ''))
| bsd-3-clause |
chevanlol360/Kernel_LGE_X5 | tools/perf/scripts/python/check-perf-trace.py | 11214 | 2503 | # perf script event handlers, generated by perf script -g python
# (c) 2010, Tom Zanussi <tzanussi@gmail.com>
# Licensed under the terms of the GNU GPL License version 2
#
# This script tests basic functionality such as flag and symbol
# strings, common_xxx() calls back into perf, begin, end, unhandled
# events, etc. Basically, if this script runs successfully and
# displays expected results, Python scripting support should be ok.
import os
import sys
sys.path.append(os.environ['PERF_EXEC_PATH'] + \
'/scripts/python/Perf-Trace-Util/lib/Perf/Trace')
from Core import *
from perf_trace_context import *
unhandled = autodict()
def trace_begin():
print "trace_begin"
pass
def trace_end():
print_unhandled()
def irq__softirq_entry(event_name, context, common_cpu,
common_secs, common_nsecs, common_pid, common_comm,
vec):
print_header(event_name, common_cpu, common_secs, common_nsecs,
common_pid, common_comm)
print_uncommon(context)
print "vec=%s\n" % \
(symbol_str("irq__softirq_entry", "vec", vec)),
def kmem__kmalloc(event_name, context, common_cpu,
common_secs, common_nsecs, common_pid, common_comm,
call_site, ptr, bytes_req, bytes_alloc,
gfp_flags):
print_header(event_name, common_cpu, common_secs, common_nsecs,
common_pid, common_comm)
print_uncommon(context)
print "call_site=%u, ptr=%u, bytes_req=%u, " \
"bytes_alloc=%u, gfp_flags=%s\n" % \
(call_site, ptr, bytes_req, bytes_alloc,
flag_str("kmem__kmalloc", "gfp_flags", gfp_flags)),
def trace_unhandled(event_name, context, event_fields_dict):
try:
unhandled[event_name] += 1
except TypeError:
unhandled[event_name] = 1
def print_header(event_name, cpu, secs, nsecs, pid, comm):
print "%-20s %5u %05u.%09u %8u %-20s " % \
(event_name, cpu, secs, nsecs, pid, comm),
# print trace fields not included in handler args
def print_uncommon(context):
print "common_preempt_count=%d, common_flags=%s, common_lock_depth=%d, " \
% (common_pc(context), trace_flag_str(common_flags(context)), \
common_lock_depth(context))
def print_unhandled():
keys = unhandled.keys()
if not keys:
return
print "\nunhandled events:\n\n",
print "%-40s %10s\n" % ("event", "count"),
print "%-40s %10s\n" % ("----------------------------------------", \
"-----------"),
for event_name in keys:
print "%-40s %10d\n" % (event_name, unhandled[event_name])
| gpl-2.0 |
openqt/algorithms | leetcode/python/lc123-best-time-to-buy-and-sell-stock-iii.py | 1 | 2545 | # coding=utf-8
import unittest
"""123. Best Time to Buy and Sell Stock III
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/description/
Say you have an array for which the _i_ th element is the price of a given
stock on day _i_.
Design an algorithm to find the maximum profit. You may complete at most _two_
transactions.
**Note: **You may not engage in multiple transactions at the same time (i.e.,
you must sell the stock before you buy again).
**Example 1:**
**Input:** [3,3,5,0,0,3,1,4]
**Output:** 6
**Explanation:** Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.
**Example 2:**
**Input:** [1,2,3,4,5]
**Output:** 4
**Explanation:** Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
engaging multiple transactions at the same time. You must sell before buying again.
**Example 3:**
**Input:** [7,6,4,3,1]
**Output:** 0
**Explanation:** In this case, no transaction is done, i.e. max profit = 0.
Similar Questions:
Best Time to Buy and Sell Stock (best-time-to-buy-and-sell-stock)
Best Time to Buy and Sell Stock II (best-time-to-buy-and-sell-stock-ii)
Best Time to Buy and Sell Stock IV (best-time-to-buy-and-sell-stock-iv)
Maximum Sum of 3 Non-Overlapping Subarrays (maximum-sum-of-3-non-overlapping-subarrays)
"""
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
low = []
total, profit = [], 0
for i in range(1, len(prices)):
if prices[i] >= prices[i-1]:
pass
else:
low.append(prices[i])
total.append(profit)
profit = 0
total.append(profit)
print(total)
return sum(sorted(total, reverse=True)[:2])
class T(unittest.TestCase):
def _test(self):
s = Solution()
self.assertEqual(s.maxProfit([]), 0)
self.assertEqual(s.maxProfit([3,3,5,0,0,3,1,4]), 6)
self.assertEqual(s.maxProfit([1,2,3,4,5]), 4)
self.assertEqual(s.maxProfit([7,6,4,3,1]), 0)
def test2(self):
s = Solution()
self.assertEqual(s.maxProfit([1,2,4,2,5,7,2,4,9,0]), 13)
if __name__ == "__main__":
unittest.main()
| gpl-3.0 |
tequa/ammisoft | ammimain/WinPython-64bit-2.7.13.1Zero/python-2.7.13.amd64/Lib/site-packages/prompt_toolkit/styles/defaults.py | 20 | 3695 | """
The default styling.
"""
from __future__ import unicode_literals
from prompt_toolkit.token import Token
__all__ = (
'DEFAULT_STYLE_EXTENSIONS',
'default_style_extensions',
)
#: Styling of prompt-toolkit specific tokens, that are not know by the default
#: Pygments style.
DEFAULT_STYLE_EXTENSIONS = {
# Highlighting of search matches in document.
Token.SearchMatch: 'noinherit reverse',
Token.SearchMatch.Current: 'noinherit #ffffff bg:#448844 underline',
# Highlighting of select text in document.
Token.SelectedText: 'reverse',
Token.CursorColumn: 'bg:#dddddd',
Token.CursorLine: 'underline',
Token.ColorColumn: 'bg:#ccaacc',
# Highlighting of matching brackets.
Token.MatchingBracket: '',
Token.MatchingBracket.Other: '#000000 bg:#aacccc',
Token.MatchingBracket.Cursor: '#ff8888 bg:#880000',
Token.MultipleCursors.Cursor: '#000000 bg:#ccccaa',
# Line numbers.
Token.LineNumber: '#888888',
Token.LineNumber.Current: 'bold',
Token.Tilde: '#8888ff',
# Default prompt.
Token.Prompt: '',
Token.Prompt.Arg: 'noinherit',
Token.Prompt.Search: 'noinherit',
Token.Prompt.Search.Text: '',
# Search toolbar.
Token.Toolbar.Search: 'bold',
Token.Toolbar.Search.Text: 'nobold',
# System toolbar
Token.Toolbar.System: 'bold',
Token.Toolbar.System.Text: 'nobold',
# "arg" toolbar.
Token.Toolbar.Arg: 'bold',
Token.Toolbar.Arg.Text: 'nobold',
# Validation toolbar.
Token.Toolbar.Validation: 'bg:#550000 #ffffff',
Token.WindowTooSmall: 'bg:#550000 #ffffff',
# Completions toolbar.
Token.Toolbar.Completions: 'bg:#bbbbbb #000000',
Token.Toolbar.Completions.Arrow: 'bg:#bbbbbb #000000 bold',
Token.Toolbar.Completions.Completion: 'bg:#bbbbbb #000000',
Token.Toolbar.Completions.Completion.Current: 'bg:#444444 #ffffff',
# Completions menu.
Token.Menu.Completions: 'bg:#bbbbbb #000000',
Token.Menu.Completions.Completion: '',
Token.Menu.Completions.Completion.Current: 'bg:#888888 #ffffff',
Token.Menu.Completions.Meta: 'bg:#999999 #000000',
Token.Menu.Completions.Meta.Current: 'bg:#aaaaaa #000000',
Token.Menu.Completions.MultiColumnMeta: 'bg:#aaaaaa #000000',
# Scrollbars.
Token.Scrollbar: 'bg:#888888',
Token.Scrollbar.Button: 'bg:#444444',
Token.Scrollbar.Arrow: 'bg:#222222 #888888 bold',
# Auto suggestion text.
Token.AutoSuggestion: '#666666',
# Trailing whitespace and tabs.
Token.TrailingWhiteSpace: '#999999',
Token.Tab: '#999999',
# When Control-C has been pressed. Grayed.
Token.Aborted: '#888888',
# Entering a Vi digraph.
Token.Digraph: '#4444ff',
}
default_style_extensions = DEFAULT_STYLE_EXTENSIONS # Old name.
| bsd-3-clause |
diox/zamboni | mkt/api/tests/test_authentication.py | 19 | 8078 | from datetime import datetime
from django.conf import settings
from django.contrib.auth.models import AnonymousUser
from django.test.client import RequestFactory
from mock import Mock, patch
from multidb.pinning import this_thread_is_pinned, unpin_this_thread
from nose.tools import eq_, ok_
from rest_framework.request import Request
from mkt.access.models import Group, GroupUser
from mkt.api import authentication
from mkt.api.middleware import (APIBaseMiddleware, RestOAuthMiddleware,
RestSharedSecretMiddleware)
from mkt.api.models import Access
from mkt.api.tests.test_oauth import OAuthClient
from mkt.site.fixtures import fixture
from mkt.site.helpers import absolutify
from mkt.site.tests import TestCase
from mkt.users.models import UserProfile
class TestRestOAuthAuthentication(TestCase):
fixtures = fixture('user_2519', 'group_admin', 'group_editor')
def setUp(self):
self.api_name = 'foo'
self.profile = UserProfile.objects.get(pk=2519)
self.profile.update(read_dev_agreement=datetime.today())
self.access = Access.objects.create(key='test_oauth_key',
secret='super secret',
user=self.profile)
self.auth = authentication.RestOAuthAuthentication()
self.middlewares = [APIBaseMiddleware, RestOAuthMiddleware]
unpin_this_thread()
def call(self, client=None):
client = client or OAuthClient(self.access)
# Make a fake POST somewhere. We use POST in order to properly test db
# pinning after auth.
url = absolutify('/api/whatever')
req = RequestFactory().post(
url, HTTP_HOST='testserver',
HTTP_AUTHORIZATION=client.sign('POST', url)[1]['Authorization'])
req.user = AnonymousUser()
for m in self.middlewares:
m().process_request(req)
return req
def add_group_user(self, user, *names):
for name in names:
group = Group.objects.get(name=name)
GroupUser.objects.create(user=self.profile, group=group)
def test_accepted(self):
req = Request(self.call())
eq_(self.auth.authenticate(req), (self.profile, None))
def test_request_token_fake(self):
c = Mock()
c.key = self.access.key
c.secret = 'mom'
ok_(not self.auth.authenticate(
Request(self.call(client=OAuthClient(c)))))
ok_(not this_thread_is_pinned())
def test_request_admin(self):
self.add_group_user(self.profile, 'Admins')
ok_(not self.auth.authenticate(Request(self.call())))
def test_request_has_role(self):
self.add_group_user(self.profile, 'App Reviewers')
ok_(self.auth.authenticate(Request(self.call())))
class TestRestAnonymousAuthentication(TestCase):
def setUp(self):
self.auth = authentication.RestAnonymousAuthentication()
self.request = RequestFactory().post('/api/whatever')
unpin_this_thread()
def test_auth(self):
user, token = self.auth.authenticate(self.request)
ok_(isinstance(user, AnonymousUser))
eq_(token, None)
ok_(not this_thread_is_pinned())
@patch.object(settings, 'SECRET_KEY', 'gubbish')
class TestSharedSecretAuthentication(TestCase):
fixtures = fixture('user_2519')
def setUp(self):
self.auth = authentication.RestSharedSecretAuthentication()
self.profile = UserProfile.objects.get(pk=2519)
self.profile.update(email=self.profile.email)
self.middlewares = [APIBaseMiddleware,
RestSharedSecretMiddleware]
unpin_this_thread()
def test_session_auth_query(self):
req = RequestFactory().post(
'/api/?_user=cfinke@m.com,56b6f1a3dd735d962c56ce7d8f46e02ec1d4748d'
'2c00c407d75f0969d08bb9c68c31b3371aa8130317815c89e5072e31bb94b4121'
'c5c165f3515838d4d6c60c4,165d631d3c3045458b4516242dad7ae')
req.user = AnonymousUser()
for m in self.middlewares:
m().process_request(req)
ok_(self.auth.authenticate(Request(req)))
ok_(req.user.is_authenticated())
eq_(self.profile.pk, req.user.pk)
def test_failed_session_auth_query(self):
req = RequestFactory().post('/api/?_user=bogus')
req.user = AnonymousUser()
for m in self.middlewares:
m().process_request(req)
ok_(not self.auth.authenticate(Request(req)))
ok_(not req.user.is_authenticated())
def test_session_auth(self):
req = RequestFactory().post(
'/api/',
HTTP_AUTHORIZATION='mkt-shared-secret '
'cfinke@m.com,56b6f1a3dd735d962c56'
'ce7d8f46e02ec1d4748d2c00c407d75f0969d08bb'
'9c68c31b3371aa8130317815c89e5072e31bb94b4'
'121c5c165f3515838d4d6c60c4,165d631d3c3045'
'458b4516242dad7ae')
req.user = AnonymousUser()
for m in self.middlewares:
m().process_request(req)
ok_(self.auth.authenticate(Request(req)))
ok_(req.user.is_authenticated())
eq_(self.profile.pk, req.user.pk)
def test_failed_session_auth(self):
req = RequestFactory().post(
'/api/',
HTTP_AUTHORIZATION='mkt-shared-secret bogus')
req.user = AnonymousUser()
for m in self.middlewares:
m().process_request(req)
ok_(not self.auth.authenticate(Request(req)))
ok_(not req.user.is_authenticated())
def test_session_auth_no_post(self):
req = RequestFactory().post('/api/')
req.user = AnonymousUser()
for m in self.middlewares:
m().process_request(req)
ok_(not self.auth.authenticate(Request(req)))
ok_(not req.user.is_authenticated())
@patch.object(settings, 'SECRET_KEY', 'gubbish')
class TestMultipleAuthenticationDRF(TestCase):
fixtures = fixture('user_2519')
def setUp(self):
self.profile = UserProfile.objects.get(pk=2519)
def test_multiple_shared_works(self):
request = RequestFactory().post(
'/api',
HTTP_AUTHORIZATION='mkt-shared-secret '
'cfinke@m.com,56b6f1a3dd735d962c56'
'ce7d8f46e02ec1d4748d2c00c407d75f0969d08bb'
'9c68c31b3371aa8130317815c89e5072e31bb94b4'
'121c5c165f3515838d4d6c60c4,165d631d3c3045'
'458b4516242dad7ae')
request.user = AnonymousUser()
drf_request = Request(request)
# Start with an AnonymousUser on the request, because that's a classic
# situation: we already went through a middleware, it didn't find a
# session cookie, if set request.user = AnonymousUser(), and now we
# are going through the authentication code in the API.
request.user = AnonymousUser()
# Call middleware as they would normally be called.
APIBaseMiddleware().process_request(request)
RestSharedSecretMiddleware().process_request(request)
RestOAuthMiddleware().process_request(request)
drf_request.authenticators = (
authentication.RestSharedSecretAuthentication(),
authentication.RestOAuthAuthentication())
eq_(drf_request.user, self.profile)
eq_(drf_request._request.user, self.profile)
eq_(drf_request.user.is_authenticated(), True)
eq_(drf_request._request.user.is_authenticated(), True)
eq_(drf_request.user.pk, self.profile.pk)
eq_(drf_request._request.user.pk, self.profile.pk)
def test_multiple_fail(self):
request = RequestFactory().post('/api')
request.user = AnonymousUser()
drf_request = Request(request)
request.user = AnonymousUser()
drf_request.authenticators = (
authentication.RestSharedSecretAuthentication(),
authentication.RestOAuthAuthentication())
eq_(drf_request.user.is_authenticated(), False)
eq_(drf_request._request.user.is_authenticated(), False)
| bsd-3-clause |
openstack/solum | solum/api/controllers/v1/datamodel/types.py | 2 | 3486 | # Copyright 2013 - Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import string
import wsme
from wsme import types as wtypes
from solum.api.controllers import common_types
from solum.i18n import _
class Base(wtypes.Base):
"""Base class for all API types."""
uri = common_types.Uri
"URI to the resource."
# (devkulkarni) Added base_url to get around strict validation
# checking of WSME 0.8.0
# https://bugs.launchpad.net/solum/+bug/1491504
# https://bugs.launchpad.net/solum/+bug/1491499
base_url = common_types.Uri
"URI of the base resource."
uuid = wtypes.text
"Unique Identifier of the resource"
def get_name(self):
return self.__name
def set_name(self, value):
allowed_chars = string.ascii_letters + string.digits + '-_'
for ch in value:
if ch not in allowed_chars:
raise ValueError(_('Names must only contain a-z,A-Z,0-9,-,_'))
self.__name = value
name = wtypes.wsproperty(str, get_name, set_name, mandatory=True)
"Name of the resource."
type = wtypes.text
"The resource type."
description = wtypes.text
"Textual description of the resource."
tags = [wtypes.text]
"Tags for the resource."
project_id = wtypes.text
"The project that this resource belongs in."
user_id = wtypes.text
"The user that owns this resource."
def __init__(self, **kwds):
self.__name = wsme.Unset
super(Base, self).__init__(**kwds)
@classmethod
def from_db_model(cls, m, host_url):
json = m.as_dict()
json['type'] = m.__tablename__
json['uri'] = '%s/v1/%s/%s' % (host_url, m.__resource__, m.uuid)
del json['id']
return cls(**(json))
def as_dict(self, db_model):
valid_keys = (attr for attr in db_model.__dict__.keys()
if attr[:2] != '__' and attr != 'as_dict')
return self.as_dict_from_keys(valid_keys)
def as_dict_from_keys(self, keys):
return dict((k, getattr(self, k))
for k in keys
if hasattr(self, k) and
getattr(self, k) != wsme.Unset)
class MultiType(wtypes.UserType):
"""A complex type that represents one or more types.
Used for validating that a value is an instance of one of the types.
:param *types: Variable-length list of types.
"""
def __init__(self, *types):
self.types = types
def __str__(self):
return ' | '.join(map(str, self.types))
def validate(self, value):
for t in self.types:
try:
return wtypes.validate_value(t, value)
except (ValueError, TypeError):
pass
else:
raise ValueError(
_("Wrong type. Expected '%(type)s', got '%(value)s'")
% {'type': self.types, 'value': type(value)})
PortType = wtypes.IntegerType(minimum=1, maximum=65535)
| apache-2.0 |
grnet/synnefo | snf-astakos-app/astakos/im/migrations/old/0060_fix_uuids.py | 10 | 25609 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
import uuid
class Migration(DataMigration):
def forwards(self, orm):
users = orm.AstakosUser.objects.filter(uuid__isnull=True)
for user in users:
user.uuid = str(uuid.uuid4())
user.save()
def backwards(self, orm):
"Write your backwards methods here."
models = {
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'im.additionalmail': {
'Meta': {'object_name': 'AdditionalMail'},
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'owner': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['im.AstakosUser']"})
},
'im.approvalterms': {
'Meta': {'object_name': 'ApprovalTerms'},
'date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'db_index': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'location': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
'im.astakosuser': {
'Meta': {'object_name': 'AstakosUser', '_ormbases': ['auth.User']},
'accepted_email': ('django.db.models.fields.EmailField', [], {'default': 'None', 'max_length': '75', 'null': 'True', 'blank': 'True'}),
'accepted_policy': ('django.db.models.fields.CharField', [], {'default': 'None', 'max_length': '255', 'null': 'True', 'blank': 'True'}),
'activation_sent': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'affiliation': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'auth_token': ('django.db.models.fields.CharField', [], {'max_length': '64', 'unique': 'True', 'null': 'True', 'blank': 'True'}),
'auth_token_created': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
'auth_token_expires': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
'date_signed_terms': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'deactivated_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'deactivated_reason': ('django.db.models.fields.TextField', [], {'default': 'None', 'null': 'True'}),
'disturbed_quota': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}),
'email_verified': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'has_credits': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'has_signed_terms': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'invitations': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'is_rejected': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_verified': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'level': ('django.db.models.fields.IntegerField', [], {'default': '4'}),
'moderated': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'moderated_at': ('django.db.models.fields.DateTimeField', [], {'default': 'None', 'null': 'True', 'blank': 'True'}),
'moderated_data': ('django.db.models.fields.TextField', [], {'default': 'None', 'null': 'True', 'blank': 'True'}),
'policy': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['im.Resource']", 'null': 'True', 'through': "orm['im.AstakosUserQuota']", 'symmetrical': 'False'}),
'rejected_reason': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'updated': ('django.db.models.fields.DateTimeField', [], {}),
'user_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True', 'primary_key': 'True'}),
'uuid': ('django.db.models.fields.CharField', [], {'max_length': '255', 'unique': 'True', 'null': 'True'}),
'verification_code': ('django.db.models.fields.CharField', [], {'max_length': '255', 'unique': 'True', 'null': 'True'}),
'verified_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'})
},
'im.astakosuserauthprovider': {
'Meta': {'ordering': "('module', 'created')", 'unique_together': "(('identifier', 'module', 'user'),)", 'object_name': 'AstakosUserAuthProvider'},
'active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'affiliation': ('django.db.models.fields.CharField', [], {'default': 'None', 'max_length': '255', 'null': 'True', 'blank': 'True'}),
'auth_backend': ('django.db.models.fields.CharField', [], {'default': "'astakos'", 'max_length': '255'}),
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'identifier': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'info_data': ('django.db.models.fields.TextField', [], {'default': "''", 'null': 'True', 'blank': 'True'}),
'module': ('django.db.models.fields.CharField', [], {'default': "'local'", 'max_length': '255'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'auth_providers'", 'to': "orm['im.AstakosUser']"})
},
'im.astakosuserquota': {
'Meta': {'unique_together': "(('resource', 'user'),)", 'object_name': 'AstakosUserQuota'},
'capacity': ('django.db.models.fields.BigIntegerField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'resource': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['im.Resource']"}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['im.AstakosUser']"})
},
'im.authproviderpolicyprofile': {
'Meta': {'ordering': "['priority']", 'object_name': 'AuthProviderPolicyProfile'},
'active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'authpolicy_profiles'", 'symmetrical': 'False', 'to': "orm['auth.Group']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_exclusive': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}),
'policy_add': ('django.db.models.fields.NullBooleanField', [], {'default': 'None', 'null': 'True', 'blank': 'True'}),
'policy_automoderate': ('django.db.models.fields.NullBooleanField', [], {'default': 'None', 'null': 'True', 'blank': 'True'}),
'policy_create': ('django.db.models.fields.NullBooleanField', [], {'default': 'None', 'null': 'True', 'blank': 'True'}),
'policy_limit': ('django.db.models.fields.IntegerField', [], {'default': 'None', 'null': 'True'}),
'policy_login': ('django.db.models.fields.NullBooleanField', [], {'default': 'None', 'null': 'True', 'blank': 'True'}),
'policy_remove': ('django.db.models.fields.NullBooleanField', [], {'default': 'None', 'null': 'True', 'blank': 'True'}),
'policy_required': ('django.db.models.fields.NullBooleanField', [], {'default': 'None', 'null': 'True', 'blank': 'True'}),
'policy_switch': ('django.db.models.fields.NullBooleanField', [], {'default': 'None', 'null': 'True', 'blank': 'True'}),
'priority': ('django.db.models.fields.IntegerField', [], {'default': '1'}),
'provider': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'users': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'authpolicy_profiles'", 'symmetrical': 'False', 'to': "orm['im.AstakosUser']"})
},
'im.chain': {
'Meta': {'object_name': 'Chain'},
'chain': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
},
'im.component': {
'Meta': {'object_name': 'Component'},
'auth_token': ('django.db.models.fields.CharField', [], {'max_length': '64', 'unique': 'True', 'null': 'True', 'blank': 'True'}),
'auth_token_created': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
'auth_token_expires': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
'base_url': ('django.db.models.fields.CharField', [], {'max_length': '1024', 'null': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255', 'db_index': 'True'}),
'url': ('django.db.models.fields.CharField', [], {'max_length': '1024', 'null': 'True'})
},
'im.emailchange': {
'Meta': {'object_name': 'EmailChange'},
'activation_key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '40', 'db_index': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'new_email_address': ('django.db.models.fields.EmailField', [], {'max_length': '75'}),
'requested_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'emailchanges'", 'unique': 'True', 'to': "orm['im.AstakosUser']"})
},
'im.endpoint': {
'Meta': {'object_name': 'Endpoint'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'service': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'endpoints'", 'to': "orm['im.Service']"})
},
'im.endpointdata': {
'Meta': {'unique_together': "(('endpoint', 'key'),)", 'object_name': 'EndpointData'},
'endpoint': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'data'", 'to': "orm['im.Endpoint']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'key': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'value': ('django.db.models.fields.CharField', [], {'max_length': '1024'})
},
'im.invitation': {
'Meta': {'object_name': 'Invitation'},
'code': ('django.db.models.fields.BigIntegerField', [], {'db_index': 'True'}),
'consumed': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'inviter': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'invitations_sent'", 'null': 'True', 'to': "orm['im.AstakosUser']"}),
'is_consumed': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'realname': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'})
},
'im.pendingthirdpartyuser': {
'Meta': {'unique_together': "(('provider', 'third_party_identifier'),)", 'object_name': 'PendingThirdPartyUser'},
'affiliation': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'null': 'True', 'blank': 'True'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'null': 'True', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'info': ('django.db.models.fields.TextField', [], {'default': "''", 'null': 'True', 'blank': 'True'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'null': 'True', 'blank': 'True'}),
'provider': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
'third_party_identifier': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'token': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'im.project': {
'Meta': {'object_name': 'Project'},
'application': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "'project'", 'unique': 'True', 'to': "orm['im.ProjectApplication']"}),
'creation_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.BigIntegerField', [], {'primary_key': 'True', 'db_column': "'id'"}),
'members': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['im.AstakosUser']", 'through': "orm['im.ProjectMembership']", 'symmetrical': 'False'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '80', 'unique': 'True', 'null': 'True', 'db_index': 'True'}),
'state': ('django.db.models.fields.IntegerField', [], {'default': '1', 'db_index': 'True'})
},
'im.projectapplication': {
'Meta': {'unique_together': "(('chain', 'id'),)", 'object_name': 'ProjectApplication'},
'applicant': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'projects_applied'", 'to': "orm['im.AstakosUser']"}),
'chain': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'chained_apps'", 'db_column': "'chain'", 'to': "orm['im.Project']"}),
'comments': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'end_date': ('django.db.models.fields.DateTimeField', [], {}),
'homepage': ('django.db.models.fields.URLField', [], {'max_length': '255', 'null': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'issue_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'limit_on_members_number': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True'}),
'member_join_policy': ('django.db.models.fields.IntegerField', [], {}),
'member_leave_policy': ('django.db.models.fields.IntegerField', [], {}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '80'}),
'owner': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'projects_owned'", 'to': "orm['im.AstakosUser']"}),
'resource_grants': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['im.Resource']", 'null': 'True', 'through': "orm['im.ProjectResourceGrant']", 'blank': 'True'}),
'response': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'response_actor': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'responded_apps'", 'null': 'True', 'to': "orm['im.AstakosUser']"}),
'response_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'start_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'state': ('django.db.models.fields.IntegerField', [], {'default': '0', 'db_index': 'True'}),
'waive_actor': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'waived_apps'", 'null': 'True', 'to': "orm['im.AstakosUser']"}),
'waive_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'waive_reason': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'})
},
'im.projectlock': {
'Meta': {'object_name': 'ProjectLock'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
},
'im.projectlog': {
'Meta': {'object_name': 'ProjectLog'},
'actor': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['im.AstakosUser']", 'null': 'True'}),
'comments': ('django.db.models.fields.TextField', [], {'null': 'True'}),
'date': ('django.db.models.fields.DateTimeField', [], {}),
'from_state': ('django.db.models.fields.IntegerField', [], {'null': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'project': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'log'", 'to': "orm['im.Project']"}),
'reason': ('django.db.models.fields.TextField', [], {'null': 'True'}),
'to_state': ('django.db.models.fields.IntegerField', [], {})
},
'im.projectmembership': {
'Meta': {'unique_together': "(('person', 'project'),)", 'object_name': 'ProjectMembership'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'person': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['im.AstakosUser']"}),
'project': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['im.Project']"}),
'state': ('django.db.models.fields.IntegerField', [], {'default': '0', 'db_index': 'True'})
},
'im.projectmembershiplog': {
'Meta': {'object_name': 'ProjectMembershipLog'},
'actor': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['im.AstakosUser']", 'null': 'True'}),
'comments': ('django.db.models.fields.TextField', [], {'null': 'True'}),
'date': ('django.db.models.fields.DateTimeField', [], {}),
'from_state': ('django.db.models.fields.IntegerField', [], {'null': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'membership': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'log'", 'to': "orm['im.ProjectMembership']"}),
'reason': ('django.db.models.fields.TextField', [], {'null': 'True'}),
'to_state': ('django.db.models.fields.IntegerField', [], {})
},
'im.projectresourcegrant': {
'Meta': {'unique_together': "(('resource', 'project_application'),)", 'object_name': 'ProjectResourceGrant'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'member_capacity': ('django.db.models.fields.BigIntegerField', [], {'default': '0'}),
'project_application': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['im.ProjectApplication']", 'null': 'True'}),
'project_capacity': ('django.db.models.fields.BigIntegerField', [], {'null': 'True'}),
'resource': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['im.Resource']"})
},
'im.resource': {
'Meta': {'object_name': 'Resource'},
'api_visible': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'desc': ('django.db.models.fields.TextField', [], {'null': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}),
'service_origin': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}),
'service_type': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'ui_visible': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'unit': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}),
'uplimit': ('django.db.models.fields.BigIntegerField', [], {'default': '0'})
},
'im.service': {
'Meta': {'object_name': 'Service'},
'component': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['im.Component']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}),
'type': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
'im.sessioncatalog': {
'Meta': {'object_name': 'SessionCatalog'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'session_key': ('django.db.models.fields.CharField', [], {'max_length': '40'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'sessions'", 'null': 'True', 'to': "orm['im.AstakosUser']"})
},
'im.usersetting': {
'Meta': {'unique_together': "(('user', 'setting'),)", 'object_name': 'UserSetting'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'setting': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['im.AstakosUser']"}),
'value': ('django.db.models.fields.IntegerField', [], {})
}
}
complete_apps = ['im']
symmetrical = True
| gpl-3.0 |
bbreslauer/PySciPlot | src/ui/Ui_PlotTypeWidget.py | 1 | 1610 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'Ui_PlotTypeWidget.ui'
#
# Created: Sat May 28 00:16:58 2011
# by: PyQt4 UI code generator 4.8.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
class Ui_PlotTypeWidget(object):
def setupUi(self, PlotTypeWidget):
PlotTypeWidget.setObjectName(_fromUtf8("PlotTypeWidget"))
PlotTypeWidget.resize(400, 300)
self.verticalLayout = QtGui.QVBoxLayout(PlotTypeWidget)
self.verticalLayout.setMargin(0)
self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
self.tabWidget = QtGui.QTabWidget(PlotTypeWidget)
self.tabWidget.setObjectName(_fromUtf8("tabWidget"))
self.verticalLayout.addWidget(self.tabWidget)
self.buttons = QtGui.QDialogButtonBox(PlotTypeWidget)
self.buttons.setStandardButtons(QtGui.QDialogButtonBox.Apply|QtGui.QDialogButtonBox.Reset)
self.buttons.setCenterButtons(True)
self.buttons.setObjectName(_fromUtf8("buttons"))
self.verticalLayout.addWidget(self.buttons)
self.retranslateUi(PlotTypeWidget)
self.tabWidget.setCurrentIndex(-1)
QtCore.QObject.connect(self.buttons, QtCore.SIGNAL(_fromUtf8("clicked(QAbstractButton*)")), PlotTypeWidget.buttonClickHandler)
def retranslateUi(self, PlotTypeWidget):
PlotTypeWidget.setWindowTitle(QtGui.QApplication.translate("PlotTypeWidget", "Form", None, QtGui.QApplication.UnicodeUTF8))
| gpl-3.0 |
jm66/pyvmomi-community-samples | samples/change_vm_nic_state.py | 4 | 4015 | #!/usr/bin/env python
#
# Written by JM Lopez
# GitHub: https://github.com/jm66
# Email: jm@jmll.me
# Website: http://jose-manuel.me
#
# Note: Example code For testing purposes only
#
# This code has been released under the terms of the Apache-2.0 license
# http://opensource.org/licenses/Apache-2.0
#
import atexit
import requests
from tools import cli
from pyVmomi import vim
from pyVim.connect import SmartConnect, Disconnect
from tools import tasks
# disable urllib3 warnings
if hasattr(requests.packages.urllib3, 'disable_warnings'):
requests.packages.urllib3.disable_warnings()
def update_virtual_nic_state(si, vm_obj, nic_number, new_nic_state):
"""
:param si: Service Instance
:param vm_obj: Virtual Machine Object
:param nic_number: Network Interface Controller Number
:param new_nic_state: Either Connect, Disconnect or Delete
:return: True if success
"""
nic_prefix_label = 'Network adapter '
nic_label = nic_prefix_label + str(nic_number)
virtual_nic_device = None
for dev in vm_obj.config.hardware.device:
if isinstance(dev, vim.vm.device.VirtualEthernetCard) \
and dev.deviceInfo.label == nic_label:
virtual_nic_device = dev
if not virtual_nic_device:
raise RuntimeError('Virtual {} could not be found.'.format(nic_label))
virtual_nic_spec = vim.vm.device.VirtualDeviceSpec()
virtual_nic_spec.operation = \
vim.vm.device.VirtualDeviceSpec.Operation.remove \
if new_nic_state == 'delete' \
else vim.vm.device.VirtualDeviceSpec.Operation.edit
virtual_nic_spec.device = virtual_nic_device
virtual_nic_spec.device.key = virtual_nic_device.key
virtual_nic_spec.device.macAddress = virtual_nic_device.macAddress
virtual_nic_spec.device.backing = virtual_nic_device.backing
virtual_nic_spec.device.wakeOnLanEnabled = \
virtual_nic_device.wakeOnLanEnabled
connectable = vim.vm.device.VirtualDevice.ConnectInfo()
if new_nic_state == 'connect':
connectable.connected = True
connectable.startConnected = True
elif new_nic_state == 'disconnect':
connectable.connected = False
connectable.startConnected = False
else:
connectable = virtual_nic_device.connectable
virtual_nic_spec.device.connectable = connectable
dev_changes = []
dev_changes.append(virtual_nic_spec)
spec = vim.vm.ConfigSpec()
spec.deviceChange = dev_changes
task = vm_obj.ReconfigVM_Task(spec=spec)
tasks.wait_for_tasks(si, [task])
return True
def get_args():
parser = cli.build_arg_parser()
parser.add_argument('-n', '--vmname', required=True,
help="Name of the VirtualMachine you want to change.")
parser.add_argument('-m', '--unitnumber', required=True,
help='NIC number.', type=int)
parser.add_argument('-t', '--state', required=True,
choices=['delete', 'disconnect', 'connect'])
my_args = parser.parse_args()
return cli.prompt_for_password(my_args)
def get_obj(content, vim_type, name):
obj = None
container = content.viewManager.CreateContainerView(
content.rootFolder, vim_type, True)
for c in container.view:
if c.name == name:
obj = c
break
return obj
def main():
args = get_args()
# connect to vc
si = SmartConnect(
host=args.host,
user=args.user,
pwd=args.password,
port=args.port)
# disconnect vc
atexit.register(Disconnect, si)
content = si.RetrieveContent()
print 'Searching for VM {}'.format(args.vmname)
vm_obj = get_obj(content, [vim.VirtualMachine], args.vmname)
if vm_obj:
update_virtual_nic_state(si, vm_obj, args.unitnumber, args.state)
print 'VM NIC {} successfully' \
' state changed to {}'.format(args.unitnumber, args.state)
else:
print "VM not found"
# start
if __name__ == "__main__":
main()
| apache-2.0 |
ssvsergeyev/ZenPacks.zenoss.AWS | src/boto/boto/glacier/vault.py | 153 | 17601 | # -*- coding: utf-8 -*-
# Copyright (c) 2012 Thomas Parslow http://almostobsolete.net/
# Copyright (c) 2012 Robie Basak <robie@justgohome.co.uk>
#
# 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, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing 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 MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
import codecs
from boto.glacier.exceptions import UploadArchiveError
from boto.glacier.job import Job
from boto.glacier.writer import compute_hashes_from_fileobj, \
resume_file_upload, Writer
from boto.glacier.concurrent import ConcurrentUploader
from boto.glacier.utils import minimum_part_size, DEFAULT_PART_SIZE
import os.path
_MEGABYTE = 1024 * 1024
_GIGABYTE = 1024 * _MEGABYTE
MAXIMUM_ARCHIVE_SIZE = 10000 * 4 * _GIGABYTE
MAXIMUM_NUMBER_OF_PARTS = 10000
class Vault(object):
DefaultPartSize = DEFAULT_PART_SIZE
SingleOperationThreshold = 100 * _MEGABYTE
ResponseDataElements = (('VaultName', 'name', None),
('VaultARN', 'arn', None),
('CreationDate', 'creation_date', None),
('LastInventoryDate', 'last_inventory_date', None),
('SizeInBytes', 'size', 0),
('NumberOfArchives', 'number_of_archives', 0))
def __init__(self, layer1, response_data=None):
self.layer1 = layer1
if response_data:
for response_name, attr_name, default in self.ResponseDataElements:
value = response_data[response_name]
setattr(self, attr_name, value)
else:
for response_name, attr_name, default in self.ResponseDataElements:
setattr(self, attr_name, default)
def __repr__(self):
return 'Vault("%s")' % self.arn
def delete(self):
"""
Delete's this vault. WARNING!
"""
self.layer1.delete_vault(self.name)
def upload_archive(self, filename, description=None):
"""
Adds an archive to a vault. For archives greater than 100MB the
multipart upload will be used.
:type file: str
:param file: A filename to upload
:type description: str
:param description: An optional description for the archive.
:rtype: str
:return: The archive id of the newly created archive
"""
if os.path.getsize(filename) > self.SingleOperationThreshold:
return self.create_archive_from_file(filename, description=description)
return self._upload_archive_single_operation(filename, description)
def _upload_archive_single_operation(self, filename, description):
"""
Adds an archive to a vault in a single operation. It's recommended for
archives less than 100MB
:type file: str
:param file: A filename to upload
:type description: str
:param description: A description for the archive.
:rtype: str
:return: The archive id of the newly created archive
"""
with open(filename, 'rb') as fileobj:
linear_hash, tree_hash = compute_hashes_from_fileobj(fileobj)
fileobj.seek(0)
response = self.layer1.upload_archive(self.name, fileobj,
linear_hash, tree_hash,
description)
return response['ArchiveId']
def create_archive_writer(self, part_size=DefaultPartSize,
description=None):
"""
Create a new archive and begin a multi-part upload to it.
Returns a file-like object to which the data for the archive
can be written. Once all the data is written the file-like
object should be closed, you can then call the get_archive_id
method on it to get the ID of the created archive.
:type part_size: int
:param part_size: The part size for the multipart upload.
:type description: str
:param description: An optional description for the archive.
:rtype: :class:`boto.glacier.writer.Writer`
:return: A Writer object that to which the archive data
should be written.
"""
response = self.layer1.initiate_multipart_upload(self.name,
part_size,
description)
return Writer(self, response['UploadId'], part_size=part_size)
def create_archive_from_file(self, filename=None, file_obj=None,
description=None, upload_id_callback=None):
"""
Create a new archive and upload the data from the given file
or file-like object.
:type filename: str
:param filename: A filename to upload
:type file_obj: file
:param file_obj: A file-like object to upload
:type description: str
:param description: An optional description for the archive.
:type upload_id_callback: function
:param upload_id_callback: if set, call with the upload_id as the
only parameter when it becomes known, to enable future calls
to resume_archive_from_file in case resume is needed.
:rtype: str
:return: The archive id of the newly created archive
"""
part_size = self.DefaultPartSize
if not file_obj:
file_size = os.path.getsize(filename)
try:
part_size = minimum_part_size(file_size, part_size)
except ValueError:
raise UploadArchiveError("File size of %s bytes exceeds "
"40,000 GB archive limit of Glacier.")
file_obj = open(filename, "rb")
writer = self.create_archive_writer(
description=description,
part_size=part_size)
if upload_id_callback:
upload_id_callback(writer.upload_id)
while True:
data = file_obj.read(part_size)
if not data:
break
writer.write(data)
writer.close()
return writer.get_archive_id()
@staticmethod
def _range_string_to_part_index(range_string, part_size):
start, inside_end = [int(value) for value in range_string.split('-')]
end = inside_end + 1
length = end - start
if length == part_size + 1:
# Off-by-one bug in Amazon's Glacier implementation,
# see: https://forums.aws.amazon.com/thread.jspa?threadID=106866
# Workaround: since part_size is too big by one byte, adjust it
end -= 1
inside_end -= 1
length -= 1
assert not (start % part_size), (
"upload part start byte is not on a part boundary")
assert (length <= part_size), "upload part is bigger than part size"
return start // part_size
def resume_archive_from_file(self, upload_id, filename=None,
file_obj=None):
"""Resume upload of a file already part-uploaded to Glacier.
The resumption of an upload where the part-uploaded section is empty
is a valid degenerate case that this function can handle.
One and only one of filename or file_obj must be specified.
:type upload_id: str
:param upload_id: existing Glacier upload id of upload being resumed.
:type filename: str
:param filename: file to open for resume
:type fobj: file
:param fobj: file-like object containing local data to resume. This
must read from the start of the entire upload, not just from the
point being resumed. Use fobj.seek(0) to achieve this if necessary.
:rtype: str
:return: The archive id of the newly created archive
"""
part_list_response = self.list_all_parts(upload_id)
part_size = part_list_response['PartSizeInBytes']
part_hash_map = {}
for part_desc in part_list_response['Parts']:
part_index = self._range_string_to_part_index(
part_desc['RangeInBytes'], part_size)
part_tree_hash = codecs.decode(part_desc['SHA256TreeHash'], 'hex_codec')
part_hash_map[part_index] = part_tree_hash
if not file_obj:
file_obj = open(filename, "rb")
return resume_file_upload(
self, upload_id, part_size, file_obj, part_hash_map)
def concurrent_create_archive_from_file(self, filename, description,
**kwargs):
"""
Create a new archive from a file and upload the given
file.
This is a convenience method around the
:class:`boto.glacier.concurrent.ConcurrentUploader`
class. This method will perform a multipart upload
and upload the parts of the file concurrently.
:type filename: str
:param filename: A filename to upload
:param kwargs: Additional kwargs to pass through to
:py:class:`boto.glacier.concurrent.ConcurrentUploader`.
You can pass any argument besides the ``api`` and
``vault_name`` param (these arguments are already
passed to the ``ConcurrentUploader`` for you).
:raises: `boto.glacier.exception.UploadArchiveError` is an error
occurs during the upload process.
:rtype: str
:return: The archive id of the newly created archive
"""
uploader = ConcurrentUploader(self.layer1, self.name, **kwargs)
archive_id = uploader.upload(filename, description)
return archive_id
def retrieve_archive(self, archive_id, sns_topic=None,
description=None):
"""
Initiate a archive retrieval job to download the data from an
archive. You will need to wait for the notification from
Amazon (via SNS) before you can actually download the data,
this takes around 4 hours.
:type archive_id: str
:param archive_id: The id of the archive
:type description: str
:param description: An optional description for the job.
:type sns_topic: str
:param sns_topic: The Amazon SNS topic ARN where Amazon Glacier
sends notification when the job is completed and the output
is ready for you to download.
:rtype: :class:`boto.glacier.job.Job`
:return: A Job object representing the retrieval job.
"""
job_data = {'Type': 'archive-retrieval',
'ArchiveId': archive_id}
if sns_topic is not None:
job_data['SNSTopic'] = sns_topic
if description is not None:
job_data['Description'] = description
response = self.layer1.initiate_job(self.name, job_data)
return self.get_job(response['JobId'])
def retrieve_inventory(self, sns_topic=None,
description=None, byte_range=None,
start_date=None, end_date=None,
limit=None):
"""
Initiate a inventory retrieval job to list the items in the
vault. You will need to wait for the notification from
Amazon (via SNS) before you can actually download the data,
this takes around 4 hours.
:type description: str
:param description: An optional description for the job.
:type sns_topic: str
:param sns_topic: The Amazon SNS topic ARN where Amazon Glacier
sends notification when the job is completed and the output
is ready for you to download.
:type byte_range: str
:param byte_range: Range of bytes to retrieve.
:type start_date: DateTime
:param start_date: Beginning of the date range to query.
:type end_date: DateTime
:param end_date: End of the date range to query.
:type limit: int
:param limit: Limits the number of results returned.
:rtype: str
:return: The ID of the job
"""
job_data = {'Type': 'inventory-retrieval'}
if sns_topic is not None:
job_data['SNSTopic'] = sns_topic
if description is not None:
job_data['Description'] = description
if byte_range is not None:
job_data['RetrievalByteRange'] = byte_range
if start_date is not None or end_date is not None or limit is not None:
rparams = {}
if start_date is not None:
rparams['StartDate'] = start_date.strftime('%Y-%m-%dT%H:%M:%S%Z')
if end_date is not None:
rparams['EndDate'] = end_date.strftime('%Y-%m-%dT%H:%M:%S%Z')
if limit is not None:
rparams['Limit'] = limit
job_data['InventoryRetrievalParameters'] = rparams
response = self.layer1.initiate_job(self.name, job_data)
return response['JobId']
def retrieve_inventory_job(self, **kwargs):
"""
Identical to ``retrieve_inventory``, but returns a ``Job`` instance
instead of just the job ID.
:type description: str
:param description: An optional description for the job.
:type sns_topic: str
:param sns_topic: The Amazon SNS topic ARN where Amazon Glacier
sends notification when the job is completed and the output
is ready for you to download.
:type byte_range: str
:param byte_range: Range of bytes to retrieve.
:type start_date: DateTime
:param start_date: Beginning of the date range to query.
:type end_date: DateTime
:param end_date: End of the date range to query.
:type limit: int
:param limit: Limits the number of results returned.
:rtype: :class:`boto.glacier.job.Job`
:return: A Job object representing the retrieval job.
"""
job_id = self.retrieve_inventory(**kwargs)
return self.get_job(job_id)
def delete_archive(self, archive_id):
"""
This operation deletes an archive from the vault.
:type archive_id: str
:param archive_id: The ID for the archive to be deleted.
"""
return self.layer1.delete_archive(self.name, archive_id)
def get_job(self, job_id):
"""
Get an object representing a job in progress.
:type job_id: str
:param job_id: The ID of the job
:rtype: :class:`boto.glacier.job.Job`
:return: A Job object representing the job.
"""
response_data = self.layer1.describe_job(self.name, job_id)
return Job(self, response_data)
def list_jobs(self, completed=None, status_code=None):
"""
Return a list of Job objects related to this vault.
:type completed: boolean
:param completed: Specifies the state of the jobs to return.
If a value of True is passed, only completed jobs will
be returned. If a value of False is passed, only
uncompleted jobs will be returned. If no value is
passed, all jobs will be returned.
:type status_code: string
:param status_code: Specifies the type of job status to return.
Valid values are: InProgress|Succeeded|Failed. If not
specified, jobs with all status codes are returned.
:rtype: list of :class:`boto.glacier.job.Job`
:return: A list of Job objects related to this vault.
"""
response_data = self.layer1.list_jobs(self.name, completed,
status_code)
return [Job(self, jd) for jd in response_data['JobList']]
def list_all_parts(self, upload_id):
"""Automatically make and combine multiple calls to list_parts.
Call list_parts as necessary, combining the results in case multiple
calls were required to get data on all available parts.
"""
result = self.layer1.list_parts(self.name, upload_id)
marker = result['Marker']
while marker:
additional_result = self.layer1.list_parts(
self.name, upload_id, marker=marker)
result['Parts'].extend(additional_result['Parts'])
marker = additional_result['Marker']
# The marker makes no sense in an unpaginated result, and clearing it
# makes testing easier. This also has the nice property that the result
# is a normal (but expanded) response.
result['Marker'] = None
return result
| gpl-2.0 |
CoDEmanX/ArangoDB | 3rdParty/V8-4.3.61/third_party/python_26/Lib/test/test_gdbm.py | 58 | 2501 | import gdbm
import unittest
import os
from test.test_support import verbose, TESTFN, run_unittest, unlink
filename = TESTFN
class TestGdbm(unittest.TestCase):
def setUp(self):
self.g = None
def tearDown(self):
if self.g is not None:
self.g.close()
unlink(filename)
def test_key_methods(self):
self.g = gdbm.open(filename, 'c')
self.assertEqual(self.g.keys(), [])
self.g['a'] = 'b'
self.g['12345678910'] = '019237410982340912840198242'
key_set = set(self.g.keys())
self.assertEqual(key_set, frozenset(['a', '12345678910']))
self.assert_(self.g.has_key('a'))
key = self.g.firstkey()
while key:
self.assert_(key in key_set)
key_set.remove(key)
key = self.g.nextkey(key)
self.assertRaises(KeyError, lambda: self.g['xxx'])
def test_error_conditions(self):
# Try to open a non-existent database.
unlink(filename)
self.assertRaises(gdbm.error, gdbm.open, filename, 'r')
# Try to access a closed database.
self.g = gdbm.open(filename, 'c')
self.g.close()
self.assertRaises(gdbm.error, lambda: self.g['a'])
# try pass an invalid open flag
self.assertRaises(gdbm.error, lambda: gdbm.open(filename, 'rx').close())
def test_flags(self):
# Test the flag parameter open() by trying all supported flag modes.
all = set(gdbm.open_flags)
# Test standard flags (presumably "crwn").
modes = all - set('fsu')
for mode in modes:
self.g = gdbm.open(filename, mode)
self.g.close()
# Test additional flags (presumably "fsu").
flags = all - set('crwn')
for mode in modes:
for flag in flags:
self.g = gdbm.open(filename, mode + flag)
self.g.close()
def test_reorganize(self):
self.g = gdbm.open(filename, 'c')
size0 = os.path.getsize(filename)
self.g['x'] = 'x' * 10000
size1 = os.path.getsize(filename)
self.assert_(size0 < size1)
del self.g['x']
# 'size' is supposed to be the same even after deleting an entry.
self.assertEqual(os.path.getsize(filename), size1)
self.g.reorganize()
size2 = os.path.getsize(filename)
self.assert_(size1 > size2 >= size0)
def test_main():
run_unittest(TestGdbm)
if __name__ == '__main__':
test_main()
| apache-2.0 |
shoma/mycli | release.py | 13 | 2119 | #!/usr/bin/env python
from __future__ import print_function
import re
import ast
import subprocess
import sys
DEBUG = False
def version(version_file):
_version_re = re.compile(r'__version__\s+=\s+(.*)')
with open(version_file, 'rb') as f:
ver = str(ast.literal_eval(_version_re.search(
f.read().decode('utf-8')).group(1)))
return ver
def commit_for_release(version_file, ver):
cmd = ['git', 'reset']
print(' '.join(cmd))
subprocess.check_output(cmd)
cmd = ['git', 'add', version_file]
print(' '.join(cmd))
subprocess.check_output(cmd)
cmd = ['git', 'commit', '--message', 'Releasing version %s' % ver]
print(' '.join(cmd))
subprocess.check_output(cmd)
def create_git_tag(tag_name):
cmd = ['git', 'tag', tag_name]
print(' '.join(cmd))
subprocess.check_output(cmd)
def register_with_pypi():
cmd = ['python', 'setup.py', 'register']
print(' '.join(cmd))
subprocess.check_output(cmd)
def create_source_tarball():
cmd = ['python', 'setup.py', 'sdist']
print(' '.join(cmd))
subprocess.check_output(cmd)
def push_to_github():
cmd = ['git', 'push', 'origin', 'master']
print(' '.join(cmd))
subprocess.check_output(cmd)
def push_tags_to_github():
cmd = ['git', 'push', '--tags', 'origin']
print(' '.join(cmd))
subprocess.check_output(cmd)
def checklist(questions):
for question in questions:
choice = raw_input(question + ' (y/N)')
if choice.lower() != 'y':
sys.exit(1)
if __name__ == '__main__':
if DEBUG:
subprocess.check_output = lambda x: x
checks = ['Have you created the debian package?',
'Have you updated the AUTHORS file?',
]
checklist(checks)
ver = version('mycli/__init__.py')
print('Releasing Version:', ver)
choice = raw_input('Are you sure? (y/N)')
if choice.lower() != 'y':
sys.exit(1)
commit_for_release('mycli/__init__.py', ver)
create_git_tag('v%s' % ver)
register_with_pypi()
create_source_tarball()
push_to_github()
push_tags_to_github()
| bsd-3-clause |
GiovanniConserva/TestDeploy | venv/Lib/site-packages/yaml/events.py | 985 | 2445 |
# Abstract classes.
class Event(object):
def __init__(self, start_mark=None, end_mark=None):
self.start_mark = start_mark
self.end_mark = end_mark
def __repr__(self):
attributes = [key for key in ['anchor', 'tag', 'implicit', 'value']
if hasattr(self, key)]
arguments = ', '.join(['%s=%r' % (key, getattr(self, key))
for key in attributes])
return '%s(%s)' % (self.__class__.__name__, arguments)
class NodeEvent(Event):
def __init__(self, anchor, start_mark=None, end_mark=None):
self.anchor = anchor
self.start_mark = start_mark
self.end_mark = end_mark
class CollectionStartEvent(NodeEvent):
def __init__(self, anchor, tag, implicit, start_mark=None, end_mark=None,
flow_style=None):
self.anchor = anchor
self.tag = tag
self.implicit = implicit
self.start_mark = start_mark
self.end_mark = end_mark
self.flow_style = flow_style
class CollectionEndEvent(Event):
pass
# Implementations.
class StreamStartEvent(Event):
def __init__(self, start_mark=None, end_mark=None, encoding=None):
self.start_mark = start_mark
self.end_mark = end_mark
self.encoding = encoding
class StreamEndEvent(Event):
pass
class DocumentStartEvent(Event):
def __init__(self, start_mark=None, end_mark=None,
explicit=None, version=None, tags=None):
self.start_mark = start_mark
self.end_mark = end_mark
self.explicit = explicit
self.version = version
self.tags = tags
class DocumentEndEvent(Event):
def __init__(self, start_mark=None, end_mark=None,
explicit=None):
self.start_mark = start_mark
self.end_mark = end_mark
self.explicit = explicit
class AliasEvent(NodeEvent):
pass
class ScalarEvent(NodeEvent):
def __init__(self, anchor, tag, implicit, value,
start_mark=None, end_mark=None, style=None):
self.anchor = anchor
self.tag = tag
self.implicit = implicit
self.value = value
self.start_mark = start_mark
self.end_mark = end_mark
self.style = style
class SequenceStartEvent(CollectionStartEvent):
pass
class SequenceEndEvent(CollectionEndEvent):
pass
class MappingStartEvent(CollectionStartEvent):
pass
class MappingEndEvent(CollectionEndEvent):
pass
| bsd-3-clause |
rven/odoo | addons/test_mail/tests/test_mail_mail.py | 4 | 4040 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import psycopg2
from odoo import api
from odoo.addons.base.models.ir_mail_server import MailDeliveryException
from odoo.addons.test_mail.tests.common import TestMailCommon
from odoo.tests import common
from odoo.tools import mute_logger
class TestMailMail(TestMailCommon):
@mute_logger('odoo.addons.mail.models.mail_mail')
def test_mail_message_notify_from_mail_mail(self):
# Due ot post-commit hooks, store send emails in every step
mail = self.env['mail.mail'].sudo().create({
'body_html': '<p>Test</p>',
'email_to': 'test@example.com',
'partner_ids': [(4, self.user_employee.partner_id.id)]
})
with self.mock_mail_gateway():
mail.send()
self.assertSentEmail(mail.env.user.partner_id, ['test@example.com'])
self.assertEqual(len(self._mails), 1)
class TestMailMailRace(common.TransactionCase):
@mute_logger('odoo.addons.mail.models.mail_mail')
def test_mail_bounce_during_send(self):
self.partner = self.env['res.partner'].create({
'name': 'Ernest Partner',
})
# we need to simulate a mail sent by the cron task, first create mail, message and notification by hand
mail = self.env['mail.mail'].sudo().create({
'body_html': '<p>Test</p>',
'notification': True,
'state': 'outgoing',
'recipient_ids': [(4, self.partner.id)]
})
message = self.env['mail.message'].create({
'subject': 'S',
'body': 'B',
'subtype_id': self.ref('mail.mt_comment'),
'notification_ids': [(0, 0, {
'res_partner_id': self.partner.id,
'mail_id': mail.id,
'notification_type': 'email',
'is_read': True,
'notification_status': 'ready',
})],
})
notif = self.env['mail.notification'].search([('res_partner_id', '=', self.partner.id)])
# we need to commit transaction or cr will keep the lock on notif
self.cr.commit()
# patch send_email in order to create a concurent update and check the notif is already locked by _send()
this = self # coding in javascript ruinned my life
bounce_deferred = []
@api.model
def send_email(self, message, *args, **kwargs):
with this.registry.cursor() as cr, mute_logger('odoo.sql_db'):
try:
# try ro aquire lock (no wait) on notification (should fail)
cr.execute("SELECT notification_status FROM mail_message_res_partner_needaction_rel WHERE id = %s FOR UPDATE NOWAIT", [notif.id])
except psycopg2.OperationalError:
# record already locked by send, all good
bounce_deferred.append(True)
else:
# this should trigger psycopg2.extensions.TransactionRollbackError in send().
# Only here to simulate the initial use case
# If the record is lock, this line would create a deadlock since we are in the same thread
# In practice, the update will wait the end of the send() transaction and set the notif as bounce, as expeced
cr.execute("UPDATE mail_message_res_partner_needaction_rel SET notification_status='bounce' WHERE id = %s", [notif.id])
return message['Message-Id']
self.env['ir.mail_server']._patch_method('send_email', send_email)
mail.send()
self.assertTrue(bounce_deferred, "The bounce should have been deferred")
self.assertEqual(notif.notification_status, 'sent')
# some cleaning since we commited the cr
self.env['ir.mail_server']._revert_method('send_email')
notif.unlink()
message.unlink()
mail.unlink()
self.partner.unlink()
self.env.cr.commit()
| agpl-3.0 |
elijah513/django | tests/template_tests/test_smartif.py | 580 | 2178 | import unittest
from django.template.smartif import IfParser
class SmartIfTests(unittest.TestCase):
def assertCalcEqual(self, expected, tokens):
self.assertEqual(expected, IfParser(tokens).parse().eval({}))
# We only test things here that are difficult to test elsewhere
# Many other tests are found in the main tests for builtin template tags
# Test parsing via the printed parse tree
def test_not(self):
var = IfParser(["not", False]).parse()
self.assertEqual("(not (literal False))", repr(var))
self.assertTrue(var.eval({}))
self.assertFalse(IfParser(["not", True]).parse().eval({}))
def test_or(self):
var = IfParser([True, "or", False]).parse()
self.assertEqual("(or (literal True) (literal False))", repr(var))
self.assertTrue(var.eval({}))
def test_in(self):
list_ = [1, 2, 3]
self.assertCalcEqual(True, [1, 'in', list_])
self.assertCalcEqual(False, [1, 'in', None])
self.assertCalcEqual(False, [None, 'in', list_])
def test_not_in(self):
list_ = [1, 2, 3]
self.assertCalcEqual(False, [1, 'not', 'in', list_])
self.assertCalcEqual(True, [4, 'not', 'in', list_])
self.assertCalcEqual(False, [1, 'not', 'in', None])
self.assertCalcEqual(True, [None, 'not', 'in', list_])
def test_precedence(self):
# (False and False) or True == True <- we want this one, like Python
# False and (False or True) == False
self.assertCalcEqual(True, [False, 'and', False, 'or', True])
# True or (False and False) == True <- we want this one, like Python
# (True or False) and False == False
self.assertCalcEqual(True, [True, 'or', False, 'and', False])
# (1 or 1) == 2 -> False
# 1 or (1 == 2) -> True <- we want this one
self.assertCalcEqual(True, [1, 'or', 1, '==', 2])
self.assertCalcEqual(True, [True, '==', True, 'or', True, '==', False])
self.assertEqual("(or (and (== (literal 1) (literal 2)) (literal 3)) (literal 4))",
repr(IfParser([1, '==', 2, 'and', 3, 'or', 4]).parse()))
| bsd-3-clause |
scrollback/kuma | vendor/packages/coverage/coverage/bytecode.py | 6 | 2086 | """Bytecode manipulation for coverage.py"""
import opcode, sys, types
class ByteCode(object):
"""A single bytecode."""
def __init__(self):
self.offset = -1
self.op = -1
self.arg = -1
self.next_offset = -1
self.jump_to = -1
class ByteCodes(object):
"""Iterator over byte codes in `code`.
Returns `ByteCode` objects.
"""
def __init__(self, code):
self.code = code
self.offset = 0
if sys.hexversion > 0x03000000:
def __getitem__(self, i):
return self.code[i]
else:
def __getitem__(self, i):
return ord(self.code[i])
def __iter__(self):
return self
def __next__(self):
if self.offset >= len(self.code):
raise StopIteration
bc = ByteCode()
bc.op = self[self.offset]
bc.offset = self.offset
next_offset = self.offset+1
if bc.op >= opcode.HAVE_ARGUMENT:
bc.arg = self[self.offset+1] + 256*self[self.offset+2]
next_offset += 2
label = -1
if bc.op in opcode.hasjrel:
label = next_offset + bc.arg
elif bc.op in opcode.hasjabs:
label = bc.arg
bc.jump_to = label
bc.next_offset = self.offset = next_offset
return bc
next = __next__ # Py2k uses an old-style non-dunder name.
class CodeObjects(object):
"""Iterate over all the code objects in `code`."""
def __init__(self, code):
self.stack = [code]
def __iter__(self):
return self
def __next__(self):
if self.stack:
# We're going to return the code object on the stack, but first
# push its children for later returning.
code = self.stack.pop()
for c in code.co_consts:
if isinstance(c, types.CodeType):
self.stack.append(c)
return code
raise StopIteration
next = __next__
| mpl-2.0 |
bearicc/3d-soil-vis | convert.py | 1 | 1196 | import scipy as sp
import numpy as np
import pandas as pd
from pyproj import *
import os
filename = ["data/05044572.xyzi",
"data/05044574.xyzi",
"data/05064572.xyzi",
"data/05064574.xyzi",
]
data_list = []
for i in range(len(filename)):
print("Load data "+filename[i]+" ...")
data_list.append(pd.read_csv(filename[i],delimiter=",",names=["x","y","z","i"]).values)
# convert UTM NAD83 Zone 15N to Lat/Lon
p = Proj(init='epsg:26915')
data_write_list = []
for i in range(len(filename)):
print("Convert data "+filename[i]+" ...")
lon,lat = p(data_list[i][:,0],data_list[i][:,1],inverse=True)
data_write = sp.zeros((data_list[i].shape[0],3))
data_write[:,0] = lon
data_write[:,1] = lat
data_write[:,2] = data_list[i][:,2]
#data_write[:,3] = data_list[i][:,3]
data_write_list.append(data_write)
#sp.save(os.path.splitext(filename[i])[0],data_write)
#sp.savetxt(os.path.splitext(filename[i])[0]+".llzi",data_write,fmt="%.8f",delimiter=",")
data_write = data_write_list[0]
for i in range(1,len(filename)):
data_write = sp.concatenate((data_write,data_write_list[i]),axis=0)
sp.save("data/data",data_write)
| gpl-3.0 |
auready/django | tests/template_tests/filter_tests/test_truncatewords.py | 235 | 1755 | from django.template.defaultfilters import truncatewords
from django.test import SimpleTestCase
from django.utils.safestring import mark_safe
from ..utils import setup
class TruncatewordsTests(SimpleTestCase):
@setup({
'truncatewords01': '{% autoescape off %}{{ a|truncatewords:"2" }} {{ b|truncatewords:"2"}}{% endautoescape %}'
})
def test_truncatewords01(self):
output = self.engine.render_to_string(
'truncatewords01', {'a': 'alpha & bravo', 'b': mark_safe('alpha & bravo')}
)
self.assertEqual(output, 'alpha & ... alpha & ...')
@setup({'truncatewords02': '{{ a|truncatewords:"2" }} {{ b|truncatewords:"2"}}'})
def test_truncatewords02(self):
output = self.engine.render_to_string(
'truncatewords02', {'a': 'alpha & bravo', 'b': mark_safe('alpha & bravo')}
)
self.assertEqual(output, 'alpha & ... alpha & ...')
class FunctionTests(SimpleTestCase):
def test_truncate(self):
self.assertEqual(truncatewords('A sentence with a few words in it', 1), 'A ...')
def test_truncate2(self):
self.assertEqual(
truncatewords('A sentence with a few words in it', 5),
'A sentence with a few ...',
)
def test_overtruncate(self):
self.assertEqual(
truncatewords('A sentence with a few words in it', 100),
'A sentence with a few words in it',
)
def test_invalid_number(self):
self.assertEqual(
truncatewords('A sentence with a few words in it', 'not a number'),
'A sentence with a few words in it',
)
def test_non_string_input(self):
self.assertEqual(truncatewords(123, 2), '123')
| bsd-3-clause |
alxgu/ansible | lib/ansible/modules/cloud/azure/azure_rm_servicebus_facts.py | 13 | 20194 | #!/usr/bin/python
#
# Copyright (c) 2018 Yuwei Zhou, <yuwzho@microsoft.com>
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: azure_rm_servicebus_facts
version_added: "2.8"
short_description: Get servicebus facts.
description:
- Get facts for a specific servicebus or all servicebus in a resource group or subscription.
options:
name:
description:
- Limit results to a specific servicebus.
resource_group:
description:
- Limit results in a specific resource group.
tags:
description:
- Limit results by providing a list of tags. Format tags as 'key' or 'key:value'.
namespace:
description:
- Servicebus namespace name.
- A namespace is a scoping container for all messaging components.
- Multiple queues and topics can reside within a single namespace, and namespaces often serve as application containers.
- Required when C(type) is not C(namespace).
type:
description:
- Type of the resource.
choices:
- namespace
- queue
- topic
- subscription
topic:
description:
- Topic name.
- Required when C(type) is C(subscription).
show_sas_policies:
description:
- Whether to show the SAS policies.
- Not support when C(type) is C(subscription).
- Note if enable this option, the facts module will raise two more HTTP call for each resources, need more network overhead.
type: bool
extends_documentation_fragment:
- azure
author:
- "Yuwei Zhou (@yuwzho)"
'''
EXAMPLES = '''
- name: Get all namespaces under a resource group
azure_rm_servicebus_facts:
resource_group: myResourceGroup
type: namespace
- name: Get all topics under a namespace
azure_rm_servicebus_facts:
resource_group: myResourceGroup
namespace: bar
type: topic
- name: Get a single queue with SAS policies
azure_rm_servicebus_facts:
resource_group: myResourceGroup
namespace: bar
type: queue
name: sbqueue
show_sas_policies: true
- name: Get all subscriptions under a resource group
azure_rm_servicebus_facts:
resource_group: myResourceGroup
type: subscription
namespace: bar
topic: sbtopic
'''
RETURN = '''
servicebuses:
description: List of servicebus dicts.
returned: always
type: list
contains:
id:
description:
- Resource Id
type: str
sample: "/subscriptions/XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX/resourceGroups/foo/providers/Microsoft.ServiceBus/
namespaces/bar/topics/baz/subscriptions/qux"
name:
description:
- Resource name
type: str
sample: qux
location:
description:
- The Geo-location where the resource lives.
type: str
sample: eastus
namespace:
description:
- Namespace name of the queue or topic, subscription.
type: str
sample: bar
topic:
description:
- Topic name of a subscription.
type: str
sample: baz
tags:
description:
- Resource tags.
type: str
sample: {env: sandbox}
sku:
description:
- Properties of namespace's sku.
type: str
sample: Standard
provisioning_state:
description:
- Provisioning state of the namespace.
type: str
sample: Succeeded
service_bus_endpoint:
description:
- Endpoint you can use to perform Service Bus operations.
type: str
sample: "https://bar.servicebus.windows.net:443/"
metric_id:
description:
- Identifier for Azure Insights metrics of namespace.
type: str
sample: "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX:bar"
type:
description:
- Resource type
- Namespace is a scoping container for all messaging components.
- Queue enables you to store messages until the receiving application is available to receive and process them.
- Topic and subscriptions enable 1:n relationships between publishers and subscribers.
sample: "Microsoft.ServiceBus/Namespaces/Topics"
type: str
created_at:
description:
- Exact time the message was created.
sample: "2019-01-25 02:46:55.543953+00:00"
type: str
updated_at:
description:
- The exact time the message was updated.
type: str
sample: "2019-01-25 02:46:55.543953+00:00"
accessed_at:
description:
- Last time the message was sent, or a request was received, for this topic.
type: str
sample: "2019-01-25 02:46:55.543953+00:00"
subscription_count:
description:
- Number of subscriptions under a topic.
type: int
sample: 1
count_details:
description:
- Message count deatils.
type: dict
contains:
active_message_count:
description:
- Number of active messages in the queue, topic, or subscription.
type: int
sample: 0
dead_letter_message_count:
description:
- Number of messages that are dead lettered.
type: int
sample: 0
scheduled_message_count:
description:
- Number of scheduled messages.
type: int
sample: 0
transfer_message_count:
description:
- Number of messages transferred to another queue, topic, or subscription.
type: int
sample: 0
transfer_dead_letter_message_count:
description:
- Number of messages transferred into dead letters.
type: int
sample: 0
support_ordering:
description:
- Value that indicates whether the topic supports ordering.
type: bool
sample: true
status:
description:
- The status of a messaging entity.
type: str
sample: active
requires_session:
description:
- A value that indicates whether the queue or topic supports the concept of sessions.
type: bool
sample: true
requires_duplicate_detection:
description:
- A value indicating if this queue or topic requires duplicate detection.
type: bool
sample: true
max_size_in_mb:
description:
- Maximum size of the queue or topic in megabytes, which is the size of the memory allocated for the topic.
type: int
sample: 5120
max_delivery_count:
description:
- The maximum delivery count.
- A message is automatically deadlettered after this number of deliveries.
type: int
sample: 10
lock_duration_in_seconds:
description:
- ISO 8601 timespan duration of a peek-lock.
- The amount of time that the message is locked for other receivers.
- The maximum value for LockDuration is 5 minutes.
type: int
sample: 60
forward_to:
description:
- Queue or topic name to forward the messages
type: str
sample: quux
forward_dead_lettered_messages_to:
description:
- Queue or topic name to forward the Dead Letter message
type: str
sample: corge
enable_partitioning:
description:
- Value that indicates whether the queue or topic to be partitioned across multiple message brokers is enabled.
type: bool
sample: true
enable_express:
description:
- Value that indicates whether Express Entities are enabled.
- An express topic holds a message in memory temporarily before writing it to persistent storage.
type: bool
sample: true
enable_batched_operations:
description:
- Value that indicates whether server-side batched operations are enabled.
type: bool
sample: true
duplicate_detection_time_in_seconds:
description:
- ISO 8601 timeSpan structure that defines the duration of the duplicate detection history.
type: int
sample: 600
default_message_time_to_live_seconds:
description:
- ISO 8061 Default message timespan to live value.
- This is the duration after which the message expires, starting from when the message is sent to Service Bus.
- This is the default value used when TimeToLive is not set on a message itself.
type: int
sample: 0
dead_lettering_on_message_expiration:
description:
- A value that indicates whether this queue or topic has dead letter support when a message expires.
type: int
sample: 0
dead_lettering_on_filter_evaluation_exceptions:
description:
- Value that indicates whether a subscription has dead letter support on filter evaluation exceptions.
type: int
sample: 0
auto_delete_on_idle_in_seconds:
description:
- ISO 8061 timeSpan idle interval after which the queue or topic is automatically deleted.
- The minimum duration is 5 minutes.
type: int
sample: true
size_in_bytes:
description:
- The size of the queue or topic, in bytes.
type: int
sample: 0
message_count:
description:
- Number of messages.
type: int
sample: 10
sas_policies:
description:
- Dict of SAS policies.
- Will not be returned until C(show_sas_policy) set
type: dict
sample: '{
"testpolicy1": {
"id": "/subscriptions/XXXXXXXX-XXXX-XXXX-XXXXXXXXXXXX/resourceGroups/
foo/providers/Microsoft.ServiceBus/namespaces/bar/queues/qux/authorizationRules/testpolicy1",
"keys": {
"key_name": "testpolicy1",
"primary_connection_string": "Endpoint=sb://bar.servicebus.windows.net/;
SharedAccessKeyName=testpolicy1;SharedAccessKey=XXXXXXXXXXXXXXXXX;EntityPath=qux",
"primary_key": "XXXXXXXXXXXXXXXXX",
"secondary_connection_string": "Endpoint=sb://bar.servicebus.windows.net/;
SharedAccessKeyName=testpolicy1;SharedAccessKey=XXXXXXXXXXXXXXX;EntityPath=qux",
"secondary_key": "XXXXXXXXXXXXXXX"
},
"name": "testpolicy1",
"rights": "listen_send",
"type": "Microsoft.ServiceBus/Namespaces/Queues/AuthorizationRules"
}
}'
'''
try:
from msrestazure.azure_exceptions import CloudError
except Exception:
# This is handled in azure_rm_common
pass
from ansible.module_utils.azure_rm_common import AzureRMModuleBase, azure_id_to_dict
from ansible.module_utils.common.dict_transformations import _camel_to_snake
from ansible.module_utils._text import to_native
from datetime import datetime, timedelta
duration_spec_map = dict(
default_message_time_to_live='default_message_time_to_live_seconds',
duplicate_detection_history_time_window='duplicate_detection_time_in_seconds',
auto_delete_on_idle='auto_delete_on_idle_in_seconds',
lock_duration='lock_duration_in_seconds'
)
def is_valid_timedelta(value):
if value == timedelta(10675199, 10085, 477581):
return None
return value
class AzureRMServiceBusFacts(AzureRMModuleBase):
def __init__(self):
self.module_arg_spec = dict(
name=dict(type='str'),
resource_group=dict(type='str'),
tags=dict(type='list'),
type=dict(type='str', required=True, choices=['namespace', 'topic', 'queue', 'subscription']),
namespace=dict(type='str'),
topic=dict(type='str'),
show_sas_policies=dict(type='bool')
)
required_if = [
('type', 'subscription', ['topic', 'resource_group', 'namespace']),
('type', 'topic', ['resource_group', 'namespace']),
('type', 'queue', ['resource_group', 'namespace'])
]
self.results = dict(
changed=False,
servicebuses=[]
)
self.name = None
self.resource_group = None
self.tags = None
self.type = None
self.namespace = None
self.topic = None
self.show_sas_policies = None
super(AzureRMServiceBusFacts, self).__init__(self.module_arg_spec,
supports_tags=False,
required_if=required_if,
facts_module=True)
def exec_module(self, **kwargs):
for key in self.module_arg_spec:
setattr(self, key, kwargs[key])
response = []
if self.name:
response = self.get_item()
elif self.resource_group:
response = self.list_items()
else:
response = self.list_all_items()
self.results['servicebuses'] = [self.instance_to_dict(x) for x in response]
return self.results
def instance_to_dict(self, instance):
result = dict()
instance_type = getattr(self.servicebus_models, 'SB{0}'.format(str.capitalize(self.type)))
attribute_map = instance_type._attribute_map
for attribute in attribute_map.keys():
value = getattr(instance, attribute)
if attribute_map[attribute]['type'] == 'duration':
if is_valid_timedelta(value):
key = duration_spec_map.get(attribute) or attribute
result[key] = int(value.total_seconds())
elif attribute == 'status':
result['status'] = _camel_to_snake(value)
elif isinstance(value, self.servicebus_models.MessageCountDetails):
result[attribute] = value.as_dict()
elif isinstance(value, self.servicebus_models.SBSku):
result[attribute] = value.name.lower()
elif isinstance(value, datetime):
result[attribute] = str(value)
elif isinstance(value, str):
result[attribute] = to_native(value)
elif attribute == 'max_size_in_megabytes':
result['max_size_in_mb'] = value
else:
result[attribute] = value
if self.show_sas_policies and self.type != 'subscription':
policies = self.get_auth_rules()
for name in policies.keys():
policies[name]['keys'] = self.get_sas_key(name)
result['sas_policies'] = policies
if self.namespace:
result['namespace'] = self.namespace
if self.topic:
result['topic'] = self.topic
return result
def _get_client(self):
return getattr(self.servicebus_client, '{0}s'.format(self.type))
def get_item(self):
try:
client = self._get_client()
if self.type == 'namespace':
item = client.get(self.resource_group, self.name)
return [item] if self.has_tags(item.tags, self.tags) else []
elif self.type == 'subscription':
return [client.get(self.resource_group, self.namespace, self.topic, self.name)]
else:
return [client.get(self.resource_group, self.namespace, self.name)]
except Exception:
pass
return []
def list_items(self):
try:
client = self._get_client()
if self.type == 'namespace':
response = client.list_by_resource_group(self.resource_group)
return [x for x in response if self.has_tags(x.tags, self.tags)]
elif self.type == 'subscription':
return client.list_by_topic(self.resource_group, self.namespace, self.topic)
else:
return client.list_by_namespace(self.resource_group, self.namespace)
except CloudError as exc:
self.fail("Failed to list items - {0}".format(str(exc)))
return []
def list_all_items(self):
self.log("List all items in subscription")
try:
if self.type != 'namespace':
return []
response = self.servicebus_client.namespaces.list()
return [x for x in response if self.has_tags(x.tags, self.tags)]
except CloudError as exc:
self.fail("Failed to list all items - {0}".format(str(exc)))
return []
def get_auth_rules(self):
result = dict()
try:
client = self._get_client()
if self.type == 'namespace':
rules = client.list_authorization_rules(self.resource_group, self.name)
else:
rules = client.list_authorization_rules(self.resource_group, self.namespace, self.name)
while True:
rule = rules.next()
result[rule.name] = self.policy_to_dict(rule)
except StopIteration:
pass
except Exception as exc:
self.fail('Error when getting SAS policies for {0} {1}: {2}'.format(self.type, self.name, exc.message or str(exc)))
return result
def get_sas_key(self, name):
try:
client = self._get_client()
if self.type == 'namespace':
return client.list_keys(self.resource_group, self.name, name).as_dict()
else:
return client.list_keys(self.resource_group, self.namespace, self.name, name).as_dict()
except Exception as exc:
self.fail('Error when getting SAS policy {0}\'s key - {1}'.format(name, exc.message or str(exc)))
return None
def policy_to_dict(self, rule):
result = rule.as_dict()
rights = result['rights']
if 'Manage' in rights:
result['rights'] = 'manage'
elif 'Listen' in rights and 'Send' in rights:
result['rights'] = 'listen_send'
else:
result['rights'] = rights[0].lower()
return result
def main():
AzureRMServiceBusFacts()
if __name__ == '__main__':
main()
| gpl-3.0 |
aterrel/dynd-python | dynd/tests/test_range_linspace.py | 1 | 5962 | import sys
import unittest
from dynd import nd, ndt
class TestArange(unittest.TestCase):
def test_simple(self):
self.assertEqual(nd.as_py(nd.range(10)), list(range(10)))
self.assertEqual(nd.as_py(nd.range(5, 10)), list(range(5, 10)))
self.assertEqual(nd.as_py(nd.range(5, 10, 3)), list(range(5, 10, 3)))
self.assertEqual(nd.as_py(nd.range(10, 5, -1)), list(range(10, 5, -1)))
self.assertEqual(nd.as_py(nd.range(stop=10, step=2)), list(range(0, 10, 2)))
def test_default_dtype(self):
# Defaults to int32 when given ints
self.assertEqual(nd.dtype_of(nd.range(10)), ndt.int32)
# Except if the input numbers don't fit, then returns int64
self.assertEqual(nd.dtype_of(nd.range(2**32, 2**32+10)), ndt.int64)
self.assertEqual(nd.dtype_of(nd.range(-2**32, -2**32+10)), ndt.int64)
# Gives float64 when given floats
self.assertEqual(nd.dtype_of(nd.range(10.0)), ndt.float64)
def test_specified_dtype(self):
# Must return the requested type
self.assertRaises(TypeError, nd.range, 10, dtype=ndt.bool)
self.assertEqual(nd.dtype_of(nd.range(10, dtype=ndt.int8)), ndt.int8)
self.assertEqual(nd.dtype_of(nd.range(10, dtype=ndt.int16)), ndt.int16)
self.assertEqual(nd.dtype_of(nd.range(10, dtype=ndt.int32)), ndt.int32)
self.assertEqual(nd.dtype_of(nd.range(10, dtype=ndt.int64)), ndt.int64)
self.assertEqual(nd.dtype_of(nd.range(10, dtype=ndt.uint8)), ndt.uint8)
self.assertEqual(nd.dtype_of(nd.range(10, dtype=ndt.uint16)), ndt.uint16)
self.assertEqual(nd.dtype_of(nd.range(10, dtype=ndt.uint32)), ndt.uint32)
self.assertEqual(nd.dtype_of(nd.range(10, dtype=ndt.uint64)), ndt.uint64)
self.assertEqual(nd.dtype_of(nd.range(10, dtype=ndt.float32)), ndt.float32)
self.assertEqual(nd.dtype_of(nd.range(10, dtype=ndt.float64)), ndt.float64)
# Maybe in the future add complex support when start.imag == stop.imag
# and step.imag == 0?
self.assertRaises(TypeError, nd.range, 10, dtype=ndt.complex_float32)
self.assertRaises(TypeError, nd.range, 10, dtype=ndt.complex_float64)
# Float/complex should convert when the dtype is specified
self.assertEqual(nd.dtype_of(nd.range(10.0, dtype=ndt.uint16)), ndt.uint16)
self.assertEqual(nd.dtype_of(nd.range(1.0, step=0.5+0j, dtype=ndt.float32)), ndt.float32)
def test_float_step(self):
# Should produce the correct count for 1.0/int steps
for i in range(1, 32):
a = nd.range(1.0, step=1.0/i)
self.assertEqual(len(a), i)
self.assertEqual(nd.as_py(a[0]), 0)
# For powers of two, should be getting exact answers
for i in range(5):
a = nd.range(1.0, step=1.0/2**i)
self.assertEqual(nd.as_py(a), [float(x)/2**i for x in range(2**i)])
def test_cast_errors(self):
# If a dtype is specified, the inputs must be convertible
self.assertRaises(RuntimeError, nd.range, 1.5, dtype=ndt.int32)
self.assertRaises(RuntimeError, nd.range, 1j, 10, 1, dtype=ndt.int32)
self.assertRaises(RuntimeError, nd.range, 0, 1j, 1, dtype=ndt.int32)
self.assertRaises(RuntimeError, nd.range, 0, 10, 1j, dtype=ndt.int32)
class TestLinspace(unittest.TestCase):
def test_simple(self):
# Default is a count of 50. For these simple cases of integers,
# the result should be exact
self.assertEqual(nd.as_py(nd.linspace(0, 49)), list(range(50)))
self.assertEqual(nd.as_py(nd.linspace(49, 0)), list(range(49, -1, -1)))
self.assertEqual(nd.as_py(nd.linspace(0, 10, count=11)), list(range(11)))
self.assertEqual(nd.as_py(nd.linspace(1, -1, count=2)), [1, -1])
self.assertEqual(nd.as_py(nd.linspace(1j, 50j)), [i*1j for i in range(1, 51)])
def test_default_dtype(self):
# Defaults to float64 when given ints
self.assertEqual(nd.dtype_of(nd.linspace(0, 1)), ndt.float64)
# Gives float64 when given floats
self.assertEqual(nd.dtype_of(nd.linspace(0, 1.0)), ndt.float64)
self.assertEqual(nd.dtype_of(nd.linspace(0.0, 1)), ndt.float64)
# Gives complex[float64] when given complex
self.assertEqual(nd.dtype_of(nd.linspace(1.0, 1.0j)), ndt.complex_float64)
self.assertEqual(nd.dtype_of(nd.linspace(0.0j, 1.0)), ndt.complex_float64)
def test_specified_dtype(self):
# Linspace only supports real-valued outputs
self.assertRaises(RuntimeError, nd.linspace, 0, 1, dtype=ndt.bool)
self.assertRaises(RuntimeError, nd.linspace, 0, 1, dtype=ndt.int8)
self.assertRaises(RuntimeError, nd.linspace, 0, 1, dtype=ndt.int16)
self.assertRaises(RuntimeError, nd.linspace, 0, 1, dtype=ndt.int32)
self.assertRaises(RuntimeError, nd.linspace, 0, 1, dtype=ndt.int64)
self.assertRaises(RuntimeError, nd.linspace, 0, 1, dtype=ndt.uint8)
self.assertRaises(RuntimeError, nd.linspace, 0, 1, dtype=ndt.uint16)
self.assertRaises(RuntimeError, nd.linspace, 0, 1, dtype=ndt.uint32)
self.assertRaises(RuntimeError, nd.linspace, 0, 1, dtype=ndt.uint64)
# Should obey the float/complex type requests
self.assertEqual(nd.dtype_of(nd.linspace(0, 1, dtype=ndt.float32)), ndt.float32)
self.assertEqual(nd.dtype_of(nd.linspace(0, 1, dtype=ndt.float64)), ndt.float64)
self.assertEqual(nd.dtype_of(nd.linspace(0, 1, dtype=ndt.complex_float32)), ndt.complex_float32)
self.assertEqual(nd.dtype_of(nd.linspace(0, 1, dtype=ndt.complex_float64)), ndt.complex_float64)
def test_cast_errors(self):
# If a dtype is specified, the inputs must be convertible
self.assertRaises(RuntimeError, nd.linspace, 0j, 1j, dtype=ndt.float32)
self.assertRaises(RuntimeError, nd.linspace, 0j, 1j, dtype=ndt.float64)
if __name__ == '__main__':
unittest.main()
| bsd-2-clause |
asomya/test | horizon/dashboards/nova/access_and_security/floating_ips/tests.py | 4 | 7541 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
# Copyright (c) 2012 X.commerce, a business unit of eBay 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.
from django import http
from django.core.urlresolvers import reverse
from mox import IsA
from novaclient import exceptions as novaclient_exceptions
from horizon import api
from horizon import test
INDEX_URL = reverse('horizon:nova:access_and_security:index')
NAMESPACE = "horizon:nova:access_and_security:floating_ips"
class FloatingIpViewTests(test.TestCase):
def test_associate(self):
floating_ip = self.floating_ips.first()
self.mox.StubOutWithMock(api, 'server_list')
self.mox.StubOutWithMock(api, 'tenant_floating_ip_get')
api.server_list(IsA(http.HttpRequest)).AndReturn(self.servers.list())
api.tenant_floating_ip_get(IsA(http.HttpRequest),
floating_ip.id).AndReturn(floating_ip)
self.mox.ReplayAll()
url = reverse('%s:associate' % NAMESPACE, args=[floating_ip.id])
res = self.client.get(url)
self.assertTemplateUsed(res,
'nova/access_and_security/floating_ips/associate.html')
def test_associate_post(self):
floating_ip = self.floating_ips.first()
server = self.servers.first()
self.mox.StubOutWithMock(api, 'server_list')
self.mox.StubOutWithMock(api, 'tenant_floating_ip_list')
self.mox.StubOutWithMock(api, 'server_add_floating_ip')
self.mox.StubOutWithMock(api, 'tenant_floating_ip_get')
api.server_list(IsA(http.HttpRequest)).AndReturn(self.servers.list())
api.tenant_floating_ip_list(IsA(http.HttpRequest)) \
.AndReturn(self.floating_ips.list())
api.server_add_floating_ip(IsA(http.HttpRequest),
server.id,
floating_ip.id)
api.tenant_floating_ip_get(IsA(http.HttpRequest),
floating_ip.id).AndReturn(floating_ip)
self.mox.ReplayAll()
form_data = {'instance_id': server.id,
'floating_ip_id': floating_ip.id,
'floating_ip': floating_ip.ip,
'method': 'FloatingIpAssociate'}
url = reverse('%s:associate' % NAMESPACE, args=[floating_ip.id])
res = self.client.post(url, form_data)
self.assertRedirects(res, INDEX_URL)
def test_associate_post_with_exception(self):
floating_ip = self.floating_ips.first()
server = self.servers.first()
self.mox.StubOutWithMock(api, 'server_list')
self.mox.StubOutWithMock(api, 'tenant_floating_ip_list')
self.mox.StubOutWithMock(api, 'security_group_list')
self.mox.StubOutWithMock(api.nova, 'keypair_list')
self.mox.StubOutWithMock(api, 'server_add_floating_ip')
self.mox.StubOutWithMock(api, 'tenant_floating_ip_get')
api.server_list(IsA(http.HttpRequest)).AndReturn(self.servers.list())
api.tenant_floating_ip_list(IsA(http.HttpRequest)) \
.AndReturn(self.floating_ips.list())
api.security_group_list(IsA(http.HttpRequest)) \
.AndReturn(self.security_groups.list())
api.nova.keypair_list(IsA(http.HttpRequest)) \
.AndReturn(self.keypairs.list())
exc = novaclient_exceptions.ClientException('ClientException')
api.server_add_floating_ip(IsA(http.HttpRequest),
server.id,
floating_ip.id).AndRaise(exc)
api.tenant_floating_ip_get(IsA(http.HttpRequest),
floating_ip.id).AndReturn(floating_ip)
self.mox.ReplayAll()
url = reverse('%s:associate' % NAMESPACE, args=[floating_ip.id])
res = self.client.post(url,
{'instance_id': 1,
'floating_ip_id': floating_ip.id,
'floating_ip': floating_ip.ip,
'method': 'FloatingIpAssociate'})
self.assertRaises(novaclient_exceptions.ClientException)
self.assertRedirects(res, INDEX_URL)
def test_disassociate_post(self):
floating_ip = self.floating_ips.first()
server = self.servers.first()
self.mox.StubOutWithMock(api.nova, 'keypair_list')
self.mox.StubOutWithMock(api, 'security_group_list')
self.mox.StubOutWithMock(api, 'tenant_floating_ip_list')
self.mox.StubOutWithMock(api, 'tenant_floating_ip_get')
self.mox.StubOutWithMock(api, 'server_remove_floating_ip')
api.nova.keypair_list(IsA(http.HttpRequest)) \
.AndReturn(self.keypairs.list())
api.security_group_list(IsA(http.HttpRequest)) \
.AndReturn(self.security_groups.list())
api.tenant_floating_ip_list(IsA(http.HttpRequest)) \
.AndReturn(self.floating_ips.list())
api.server_remove_floating_ip(IsA(http.HttpRequest),
server.id,
floating_ip.id)
self.mox.ReplayAll()
action = "floating_ips__disassociate__%s" % floating_ip.id
res = self.client.post(INDEX_URL, {"action": action})
self.assertMessageCount(success=1)
self.assertRedirectsNoFollow(res, INDEX_URL)
def test_disassociate_post_with_exception(self):
floating_ip = self.floating_ips.first()
server = self.servers.first()
self.mox.StubOutWithMock(api.nova, 'keypair_list')
self.mox.StubOutWithMock(api, 'security_group_list')
self.mox.StubOutWithMock(api, 'tenant_floating_ip_list')
self.mox.StubOutWithMock(api, 'tenant_floating_ip_get')
self.mox.StubOutWithMock(api, 'server_remove_floating_ip')
api.nova.keypair_list(IsA(http.HttpRequest)) \
.AndReturn(self.keypairs.list())
api.security_group_list(IsA(http.HttpRequest)) \
.AndReturn(self.security_groups.list())
api.tenant_floating_ip_list(IsA(http.HttpRequest)) \
.AndReturn(self.floating_ips.list())
exc = novaclient_exceptions.ClientException('ClientException')
api.server_remove_floating_ip(IsA(http.HttpRequest),
server.id,
floating_ip.id).AndRaise(exc)
self.mox.ReplayAll()
action = "floating_ips__disassociate__%s" % floating_ip.id
res = self.client.post(INDEX_URL, {"action": action})
self.assertRaises(novaclient_exceptions.ClientException)
self.assertRedirectsNoFollow(res, INDEX_URL)
| apache-2.0 |
izonder/intellij-community | plugins/hg4idea/testData/bin/mercurial/changegroup.py | 91 | 8282 | # changegroup.py - Mercurial changegroup manipulation functions
#
# Copyright 2006 Matt Mackall <mpm@selenic.com>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
from i18n import _
from node import nullrev
import mdiff, util
import struct, os, bz2, zlib, tempfile
_BUNDLE10_DELTA_HEADER = "20s20s20s20s"
def readexactly(stream, n):
'''read n bytes from stream.read and abort if less was available'''
s = stream.read(n)
if len(s) < n:
raise util.Abort(_("stream ended unexpectedly"
" (got %d bytes, expected %d)")
% (len(s), n))
return s
def getchunk(stream):
"""return the next chunk from stream as a string"""
d = readexactly(stream, 4)
l = struct.unpack(">l", d)[0]
if l <= 4:
if l:
raise util.Abort(_("invalid chunk length %d") % l)
return ""
return readexactly(stream, l - 4)
def chunkheader(length):
"""return a changegroup chunk header (string)"""
return struct.pack(">l", length + 4)
def closechunk():
"""return a changegroup chunk header (string) for a zero-length chunk"""
return struct.pack(">l", 0)
class nocompress(object):
def compress(self, x):
return x
def flush(self):
return ""
bundletypes = {
"": ("", nocompress), # only when using unbundle on ssh and old http servers
# since the unification ssh accepts a header but there
# is no capability signaling it.
"HG10UN": ("HG10UN", nocompress),
"HG10BZ": ("HG10", lambda: bz2.BZ2Compressor()),
"HG10GZ": ("HG10GZ", lambda: zlib.compressobj()),
}
# hgweb uses this list to communicate its preferred type
bundlepriority = ['HG10GZ', 'HG10BZ', 'HG10UN']
def writebundle(cg, filename, bundletype):
"""Write a bundle file and return its filename.
Existing files will not be overwritten.
If no filename is specified, a temporary file is created.
bz2 compression can be turned off.
The bundle file will be deleted in case of errors.
"""
fh = None
cleanup = None
try:
if filename:
fh = open(filename, "wb")
else:
fd, filename = tempfile.mkstemp(prefix="hg-bundle-", suffix=".hg")
fh = os.fdopen(fd, "wb")
cleanup = filename
header, compressor = bundletypes[bundletype]
fh.write(header)
z = compressor()
# parse the changegroup data, otherwise we will block
# in case of sshrepo because we don't know the end of the stream
# an empty chunkgroup is the end of the changegroup
# a changegroup has at least 2 chunkgroups (changelog and manifest).
# after that, an empty chunkgroup is the end of the changegroup
empty = False
count = 0
while not empty or count <= 2:
empty = True
count += 1
while True:
chunk = getchunk(cg)
if not chunk:
break
empty = False
fh.write(z.compress(chunkheader(len(chunk))))
pos = 0
while pos < len(chunk):
next = pos + 2**20
fh.write(z.compress(chunk[pos:next]))
pos = next
fh.write(z.compress(closechunk()))
fh.write(z.flush())
cleanup = None
return filename
finally:
if fh is not None:
fh.close()
if cleanup is not None:
os.unlink(cleanup)
def decompressor(fh, alg):
if alg == 'UN':
return fh
elif alg == 'GZ':
def generator(f):
zd = zlib.decompressobj()
for chunk in util.filechunkiter(f):
yield zd.decompress(chunk)
elif alg == 'BZ':
def generator(f):
zd = bz2.BZ2Decompressor()
zd.decompress("BZ")
for chunk in util.filechunkiter(f, 4096):
yield zd.decompress(chunk)
else:
raise util.Abort("unknown bundle compression '%s'" % alg)
return util.chunkbuffer(generator(fh))
class unbundle10(object):
deltaheader = _BUNDLE10_DELTA_HEADER
deltaheadersize = struct.calcsize(deltaheader)
def __init__(self, fh, alg):
self._stream = decompressor(fh, alg)
self._type = alg
self.callback = None
def compressed(self):
return self._type != 'UN'
def read(self, l):
return self._stream.read(l)
def seek(self, pos):
return self._stream.seek(pos)
def tell(self):
return self._stream.tell()
def close(self):
return self._stream.close()
def chunklength(self):
d = readexactly(self._stream, 4)
l = struct.unpack(">l", d)[0]
if l <= 4:
if l:
raise util.Abort(_("invalid chunk length %d") % l)
return 0
if self.callback:
self.callback()
return l - 4
def changelogheader(self):
"""v10 does not have a changelog header chunk"""
return {}
def manifestheader(self):
"""v10 does not have a manifest header chunk"""
return {}
def filelogheader(self):
"""return the header of the filelogs chunk, v10 only has the filename"""
l = self.chunklength()
if not l:
return {}
fname = readexactly(self._stream, l)
return dict(filename=fname)
def _deltaheader(self, headertuple, prevnode):
node, p1, p2, cs = headertuple
if prevnode is None:
deltabase = p1
else:
deltabase = prevnode
return node, p1, p2, deltabase, cs
def deltachunk(self, prevnode):
l = self.chunklength()
if not l:
return {}
headerdata = readexactly(self._stream, self.deltaheadersize)
header = struct.unpack(self.deltaheader, headerdata)
delta = readexactly(self._stream, l - self.deltaheadersize)
node, p1, p2, deltabase, cs = self._deltaheader(header, prevnode)
return dict(node=node, p1=p1, p2=p2, cs=cs,
deltabase=deltabase, delta=delta)
class headerlessfixup(object):
def __init__(self, fh, h):
self._h = h
self._fh = fh
def read(self, n):
if self._h:
d, self._h = self._h[:n], self._h[n:]
if len(d) < n:
d += readexactly(self._fh, n - len(d))
return d
return readexactly(self._fh, n)
def readbundle(fh, fname):
header = readexactly(fh, 6)
if not fname:
fname = "stream"
if not header.startswith('HG') and header.startswith('\0'):
fh = headerlessfixup(fh, header)
header = "HG10UN"
magic, version, alg = header[0:2], header[2:4], header[4:6]
if magic != 'HG':
raise util.Abort(_('%s: not a Mercurial bundle') % fname)
if version != '10':
raise util.Abort(_('%s: unknown bundle version %s') % (fname, version))
return unbundle10(fh, alg)
class bundle10(object):
deltaheader = _BUNDLE10_DELTA_HEADER
def __init__(self, lookup):
self._lookup = lookup
def close(self):
return closechunk()
def fileheader(self, fname):
return chunkheader(len(fname)) + fname
def revchunk(self, revlog, rev, prev):
node = revlog.node(rev)
p1, p2 = revlog.parentrevs(rev)
base = prev
prefix = ''
if base == nullrev:
delta = revlog.revision(node)
prefix = mdiff.trivialdiffheader(len(delta))
else:
delta = revlog.revdiff(base, rev)
linknode = self._lookup(revlog, node)
p1n, p2n = revlog.parents(node)
basenode = revlog.node(base)
meta = self.builddeltaheader(node, p1n, p2n, basenode, linknode)
meta += prefix
l = len(meta) + len(delta)
yield chunkheader(l)
yield meta
yield delta
def builddeltaheader(self, node, p1n, p2n, basenode, linknode):
# do nothing with basenode, it is implicitly the previous one in HG10
return struct.pack(self.deltaheader, node, p1n, p2n, linknode)
| apache-2.0 |
Lyrositor/moul-scripts | Python/ki/__init__.py | 1 | 337790 | # -*- coding: utf-8 -*-
""" *==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
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/>.
Additional permissions under GNU GPL version 3 section 7
If you modify this Program, or any covered work, by linking or
combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK,
NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent
JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK
(or a modified version of those libraries),
containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA,
PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG
JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the
licensors of this Program grant you additional
permission to convey the resulting work. Corresponding Source for a
non-source form of such a combination shall include the source code for
the parts of OpenSSL and IJG JPEG Library used as well as that of the covered
work.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==* """
MaxVersionNumber = 58
MinorVersionNumber = 52
# Plasma engine.
from Plasma import *
from PlasmaTypes import *
from PlasmaKITypes import *
from PlasmaConstants import *
from PlasmaVaultConstants import *
from PlasmaNetConstants import *
import time
import string
import xCensor
import xLinkingBookDefs
import xBookGUIs
import re # Used for CoD Fix.
import os # Used for saving pictures locally.
import glob # Used for saving pictures locally.
import math
import xLocTools
import xEnum
# Personal age SDL helper.
from xPsnlVaultSDL import *
# Jalak constants.
from jlakConstants import *
# xKI sub-modules.
import xKIExtChatCommands
import xKIChat
from xKIConstants import *
from xKIHelpers import *
# Marker Game thingies
import xMarkerMgr
# Define the attributes that will be entered in Max.
KIBlackbar = ptAttribGUIDialog(1, "The Blackbar dialog")
xKIChat.KIBlackbar = KIBlackbar
KIMini = ptAttribGUIDialog(2, "The KIMini dialog")
xKIChat.KIMini = KIMini
KIYesNo = ptAttribGUIDialog(3, "The KIYesNo dialog")
BigKI = ptAttribGUIDialog(5, "The BigKI (Mr. BigStuff)")
xKIChat.BigKI = BigKI
NewItemAlert = ptAttribGUIDialog(7, "The new item alert dialog")
KIListModeDialog = ptAttribGUIDialog(9, "The list mode dialog")
KIPictureExpanded = ptAttribGUIDialog(10, "The Picture expanded dialog")
KIJournalExpanded = ptAttribGUIDialog(11, "The journal entry expanded dialog")
KIOnAnim = ptAttribAnimation(12, "Turn on/off the KI on animation")
KIOnResp = ptAttribResponder(13, "Turn On responder")
KIOffResp = ptAttribResponder(14, "Turn Off responder")
KIPlayerExpanded = ptAttribGUIDialog(17, "The player expanded dialog")
KIMicroBlackbar = ptAttribGUIDialog(18, "The micro Blackbar dialog")
KIMicro = ptAttribGUIDialog(19, "The micro KI dialog")
xKIChat.KIMicro = KIMicro
KIVolumeExpanded = ptAttribGUIDialog(21, "The volume control dialog")
KIAgeOwnerExpanded = ptAttribGUIDialog(22, "The Age Owner settings dialog")
# Disabled: KIRateIt = ptAttribGUIDialog(23, "The Rate It dialog")
KISettings = ptAttribGUIDialog(24, "The KI settings dialog")
KIMarkerFolderExpanded = ptAttribGUIDialog(27, "The Marker Folder dialog")
KIMarkerFolderPopupMenu = ptAttribGUIPopUpMenu(28, "The MarkerFolder Time Popup Menu")
# Disabled: KIQuestionNote = ptAttribGUIDialog(29, "The Question Note dialog")
# Disabled: KIMarkerTypePopupMenu = ptAttribGUIPopUpMenu(30, "The MarkerFolder Type Popup Menu")
KICreateMarkerGameGUI = ptAttribGUIDialog(31, "The Marker Game Creation GUI")
KIMarkerGameGUIOpen = ptAttribResponder(32, "Marker Game GUI Open Responder")
KIMarkerGameGUIClose = ptAttribResponder(33, "Marker Game GUI Close Responder")
KIJalakMiniIconOn = ptAttribResponder(34, "Jalak KIMini icon 'on/off' resp", ["on", "off"])
KIJalakGUIDialog = ptAttribGUIDialog(35, "The Jalak GUI dialog")
KIJalakGUIOpen = ptAttribResponder(36, "Jalak GUI 'open' resp")
KIJalakGUIClose = ptAttribResponder(37, "Jalak GUI 'close' resp")
KIJalakBtnLights = ptAttribResponder(38, "Jalak GUI btn lights resp", statelist=JalakBtnStates, netForce=0)
## The master class handling all of Uru's GUI.
# This includes the KI itself, the blackbar, the Jalak GUI...
class xKI(ptModifier):
## Initialize the KI.
# Called only once during Uru execution when the game is started. At this
# stage, Plasma is not yet initialized.
def __init__(self):
# Set up the KI.
ptModifier.__init__(self)
self.id = 199
self.version = MaxVersionNumber
self.folderOfDevices = DeviceFolder(PtGetLocalizedString("KI.Folders.Devices"))
PtDebugPrint(u"xKI: Max version {} - minor version {}.".format(MaxVersionNumber, MinorVersionNumber))
# Prepare the GUI's default state.
self.KIGUIInitialized = False
self.KIDisabled = False
self.KIHardDisabled = False
self.isPlayingLookingAtKIMode = False
self.miniKIWasUp = False
self.sawTheKIAtLeastOnce = False
self.miniKIFirstTimeShow = True
# Set the default KI levels.
self.censorLevel = 0
self.gKIMarkerLevel = 0
self.KILevel = kMicroKI # Assume the KI is at the lowest level.
self.MGKILevel = 0
# Player state.
self.onlyGetPMsFromBuddies = False
self.onlyAllowBuddiesOnRequest = False
self.takingAPicture = False
self.waitingForAnimation = False
# Transparency settings.
self.originalForeAlpha = 1.0
self.originalSelectAlpha = 1.0
self.originalminiKICenter = None
self.lastminiKICenter = None
#~~~~~~~#
# BigKI #
#~~~~~~~#
self.previousTime = "20:20"
self.timeBlinker = True
self.BKPlayerList = []
self.BKPlayerSelected = None
self.previouslySelectedPlayer = None
self.BKJournalFolderDict = {}
self.BKJournalListOrder = []
self.BKJournalFolderSelected = 0
self.BKJournalFolderTopLine = 0
self.BKPlayerFolderDict = {}
self.BKPlayerListOrder = []
self.BKPlayerFolderSelected = 0
self.BKPlayerFolderTopLine = 0
self.BKConfigFolderDict = {}
self.BKConfigListOrder = [PtGetLocalizedString("KI.Config.Settings")]
self.BKConfigDefaultListOrder = [PtGetLocalizedString("KI.Config.Settings")]
self.BKConfigFolderSelected = 0
self.BKConfigFolderTopLine = 0
self.BKFolderLineDict = self.BKJournalFolderDict
self.BKFolderListOrder = self.BKJournalListOrder
self.BKFolderSelected = self.BKJournalFolderSelected
self.BKFolderTopLine = self.BKJournalFolderTopLine
self.BKFolderSelectChanged = False
self.BKIncomingFolder = None
self.BKNewItemsInInbox = 0
self.BKCurrentContent = None
self.BKContentList = []
self.BKContentListTopLine = 0
self.BKInEditMode = False
self.BKEditContent = None
self.BKEditField = -1
self.BKGettingPlayerID = False
self.BKRightSideMode = kGUI.BKListMode
self.BKAgeOwnerEditDescription = False
# New item alert.
self.alertTimerActive = False
self.alertTimeToUse = kAlertTimeDefault
# Yes/No dialog globals.
self.YNWhatReason = kGUI.YNQuit
self.YNOutsideSender = None
# Player book globals.
self.bookOfferer = None
self.offerLinkFromWho = None
self.offeredBookMode = 0
self.psnlOfferedAgeInfo = None
# The ptBook Yeesha book object.
self.isEntireYeeshaBookEnabled = True
self.isYeeshaBookEnabled = True
self.yeeshaBook = None
# KI light state.
self.lightOn = False
self.lightStop = 0
# Pellet score operations.
self.scoreOpCur = kPellets.ScoreNoOp
self.scoreOps = []
# KI usage values.
self.numberOfPictures = 0
self.numberOfNotes = 0
self.numberOfMarkerFolders = 0
self.numberOfMarkers = 0
# Marker Games state.
self.currentPlayingMarkerGame = None
self.markerGameState = kGames.MGNotActive
self.markerGameTimeID = 0
self.markerJoinRequests = []
self.MFdialogMode = kGames.MFOverview
# New Marker Game dialog globals.
self.markerGameDefaultColor = ""
self.markerGameSelectedColor = ""
self.selectedMGType = 0
# GZ missions state.
self.gGZPlaying = 0
self.gGZMarkerInRange = 0
self.gGZMarkerInRangeRepy = None
self.gMarkerToGetColor = "off"
self.gMarkerGottenColor = "off"
self.gMarkerToGetNumber = 0
self.gMarkerGottenNumber = 0
# Jalak GUI globals.
self.jalakGUIButtons = []
self.jalakGUIState = False
self.jalakScript = None
# Miscellaneous.
self.imagerMap = {}
self.pelletImager = ""
## Auto-completion manager.
self.autocompleteState = AutocompleteState()
## The chatting manager.
self.chatMgr = xKIChat.xKIChat(self.StartFadeTimer, self.ResetFadeState, self.FadeCompletely, self.GetCensorLevel)
## Unloads any loaded dialogs upon exit.
def __del__(self):
PtUnloadDialog("KIMicroBlackBar")
PtUnloadDialog("KIMicro")
PtUnloadDialog("KIMini")
PtUnloadDialog("KIMain")
PtUnloadDialog("KIListMode")
PtUnloadDialog("KIJournalExpanded")
PtUnloadDialog("KIPictureExpanded")
PtUnloadDialog("KIPlayerExpanded")
PtUnloadDialog("KIAgeOwnerSettings")
PtUnloadDialog("KISettings")
PtUnloadDialog("KIMarkerFolder")
PtUnloadDialog("KIMarkerTimeMenu")
PtUnloadDialog("KIMarkerTypeMenu")
PtUnloadDialog("KIYesNo")
PtUnloadDialog("KINewItemAlert")
PtUnloadDialog("OptionsMenuGUI")
PtUnloadDialog("IntroBahroBgGUI")
PtUnloadDialog("KIHelp")
PtUnloadDialog("KIHelpMenu")
PtUnloadDialog("KeyMapDialog")
PtUnloadDialog("GameSettingsDialog")
PtUnloadDialog("CalibrationGUI")
PtUnloadDialog("TrailerPreviewGUI")
PtUnloadDialog("KeyMap2Dialog")
PtUnloadDialog("AdvancedGameSettingsDialog")
PtUnloadDialog("OptionsHelpGUI")
PtUnloadDialog("bkNotebook")
PtUnloadDialog("bkBahroRockBook")
PtUnloadDialog("YeeshaPageGUI")
PtUnloadDialog("KIMiniMarkers")
if PtGetAgeName() == "Jalak":
PtDebugPrint(u"xKI: Unloading Jalak GUI dialog.", level=kWarningLevel)
KIJalakMiniIconOn.run(self.key, state="off", netPropagate=0, fastforward=1)
ptGUIControlButton(KIMini.dialog.getControlFromTag(kJalakMiniIconBtn)).disable()
ptGUIControlButton(KIMini.dialog.getControlFromTag(kJalakMiniIconBtn)).hide()
PtUnloadDialog("jalakControlPanel")
#~~~~~~~~~~~~~~~~~~#
# Plasma Functions #
#~~~~~~~~~~~~~~~~~~#
## Called by Plasma on receipt of the first PythonFileMod message.
# Preloads all the GUI dialogs.
def OnInit(self):
# Preload all the dialogs.
PtLoadDialog("KIBlackBar", self.key)
PtLoadDialog("KIMicroBlackBar", self.key)
PtLoadDialog("KIMicro", self.key)
PtLoadDialog("KIMini", self.key)
PtLoadDialog("KIMain", self.key)
PtLoadDialog("KIListMode", self.key)
PtLoadDialog("KIJournalExpanded", self.key)
PtLoadDialog("KIPictureExpanded", self.key)
PtLoadDialog("KIPlayerExpanded", self.key)
PtLoadDialog("KIAgeOwnerSettings", self.key)
PtLoadDialog("KISettings", self.key)
PtLoadDialog("KIMarkerFolder", self.key)
PtLoadDialog("KIMarkerTimeMenu", self.key)
PtLoadDialog("KIMarkerTypeMenu", self.key)
PtLoadDialog("KIYesNo", self.key)
PtLoadDialog("KINewItemAlert", self.key)
PtLoadDialog("OptionsMenuGUI")
PtLoadDialog("IntroBahroBgGUI")
PtLoadDialog("KIHelp")
PtLoadDialog("KIHelpMenu")
PtLoadDialog("KeyMapDialog")
PtLoadDialog("GameSettingsDialog")
PtLoadDialog("CalibrationGUI")
PtLoadDialog("TrailerPreviewGUI")
PtLoadDialog("KeyMap2Dialog")
PtLoadDialog("AdvancedGameSettingsDialog")
PtLoadDialog("OptionsHelpGUI")
PtLoadDialog("bkNotebook")
PtLoadDialog("bkBahroRockBook")
PtLoadDialog("YeeshaPageGUI")
PtLoadDialog("KIMiniMarkers", self.key)
self.markerGameManager = xMarkerMgr.MarkerGameManager()
# Pass the newly-initialized key to the modules.
self.chatMgr.key = self.key
## Called by Plasma on receipt of the first plEvalMsg.
# Loads all the dialogs for the first update.
def OnFirstUpdate(self):
# Create the dnicoordinate keeper.
self.dniCoords = ptDniCoordinates()
# To start with, use randized numbers instead of the real thing.
self.chatMgr.logFile = ptStatusLog()
xBookGUIs.LoadAllBookGUIs()
logoutText = ptGUIControlTextBox(KIYesNo.dialog.getControlFromTag(kGUI.YesNoLogoutTextID))
logoutText.hide()
logoutButton = ptGUIControlButton(KIYesNo.dialog.getControlFromTag(kGUI.YesNoLogoutButtonID))
logoutButton.hide()
## Called by Plasma when the player updates his account.
# This includes switching avatars and changing passwords. Because the KI
# gets started at initial load time, the KI needs to be re-initialized once
# the playerID has been updated, triggering this function.
def OnAccountUpdate(self, updateType, result, playerID):
if updateType == PtAccountUpdateType.kActivePlayer and result == 0 and playerID != 0:
PtDebugPrint(u"xKI.OnAccountUpdate(): Active player set. Clear to re-init KI GUI.", level=kDebugDumpLevel)
self.KIGUIInitialized = False
elif updateType == PtAccountUpdateType.kChangePassword:
if result == 0:
self.chatMgr.DisplayStatusMessage(PtGetLocalizedString("KI.Messages.PasswordChangeSuccess"))
else:
self.chatMgr.DisplayStatusMessage(PtGetLocalizedString("KI.Messages.PasswordChangeFailure"))
## Called by Plasma when the Age state has been fully received.
# This function re-initializes Marker Games, puts away the KI and performs
# various other preparations.
def OnServerInitComplete(self):
# Force any open KIs to close.
self.ToggleMiniKI()
self.CheckKILight()
ageName = PtGetAgeName()
PtDebugPrint(u"xKI.OnServerInitComplete(): Age = ", ageName, level=kDebugDumpLevel)
if ageName.lower() != "startup":
self.markerGameManager.OnServerInitComplete()
# Set up Jalak GUI.
if ageName == "Jalak":
PtDebugPrint(u"xKI.OnServerInitComplete(): Loading Jalak GUI dialog.", level=kWarningLevel)
PtLoadDialog("jalakControlPanel", self.key)
KIJalakMiniIconOn.run(self.key, state="on", netPropagate=0)
ptGUIControlButton(KIMini.dialog.getControlFromTag(kJalakMiniIconBtn)).show()
ptGUIControlButton(KIMini.dialog.getControlFromTag(kJalakMiniIconBtn)).enable()
self.AlertKIStart()
else:
KIJalakMiniIconOn.run(self.key, state="off", netPropagate=0, fastforward=1)
ptGUIControlButton(KIMini.dialog.getControlFromTag(kJalakMiniIconBtn)).disable()
ptGUIControlButton(KIMini.dialog.getControlFromTag(kJalakMiniIconBtn)).hide()
## Called by Plasma when the avatar is linked out of an Age.
# Depending on the Age the avatar was linking out, the Jalak GUI will be
# disabled and the KI light turned off.
def BeginAgeUnLoad(self, avObj):
ageName = PtGetAgeName()
if ageName == "Descent":
return
elif ageName == "Jalak":
if self.jalakGUIState:
self.JalakGUIToggle(1)
if not self.lightOn:
return
local = 0
try:
local = PtGetLocalAvatar()
except:
PtDebugPrint(u"xKI.BeginAgeUnLoad(): Failed to get local avatar.")
return
if local == avObj:
PtDebugPrint(u"xKI.BeginAgeUnLoad(): Avatar page out.", level=kDebugDumpLevel)
curTime = PtGetDniTime()
timeRemaining = (self.lightStop - curTime)
if timeRemaining > 0:
self.DoKILight(0, 1, timeRemaining)
LocalAvatar = PtGetLocalAvatar()
avatarKey = LocalAvatar.getKey()
PtSetLightAnimStart(avatarKey, kKILightObjectName, False)
## Get any leftover, unwanted keystrokes.
def OnDefaultKeyCaught(self, ch, isDown, isRepeat, isShift, isCtrl, keycode):
if ord(ch) != 0:
if not ord(ch) in kDefaultKeyIgnoreList:
if isDown and not isCtrl and not isRepeat:
if not self.KIDisabled and not PtIsEnterChatModeKeyBound():
self.chatMgr.ToggleChatMode(1, firstChar=ch)
## Called by Plasma on receipt of a plNotifyMsg.
# This big function deals with the various responses sent upon a triggered
# event, such as a book being offered.
def OnNotify(self, state, ID, events):
PtDebugPrint(u"xKI.OnNotify(): Notify state = {}, ID = {}.".format(state, ID), level=kDebugDumpLevel)
# Is it a notification from the scene input interface or PlayerBook?
for event in events:
if event[0] == kOfferLinkingBook:
if self.KILevel == kMicroKI:
plybkCB = ptGUIControlCheckBox(KIMicroBlackbar.dialog.getControlFromTag(kGUI.PlayerBookCBID))
else:
plybkCB = ptGUIControlCheckBox(KIBlackbar.dialog.getControlFromTag(kGUI.PlayerBookCBID))
# Make sure we get the events back if someone else used the PlayerBook.
if event[2] == -999:
# If waiting for offeree to accept.
if self.offeredBookMode == kGUI.Offeree:
# Then take the offered PlayerBook.
self.yeeshaBook.hide()
PtToggleAvatarClickability(True)
plybkCB.setChecked(0)
# Else, they were too late.
self.offeredBookMode = kGUI.NotOffering
self.bookOfferer = None
PtDebugPrint(u"xKI.OnNotify(): Offerer is rescinding the book offer.", level=kDebugDumpLevel)
PtToggleAvatarClickability(True)
return
# The book is being offered by someone else.
elif event[2] == 999:
self.bookOfferer = event[1]
avID = PtGetClientIDFromAvatarKey(self.bookOfferer.getKey())
if ptVault().getIgnoreListFolder().playerlistHasPlayer(avID):
self.offeredBookMode = kGUI.NotOffering
PtNotifyOffererLinkRejected(avID)
self.bookOfferer = None
PtToggleAvatarClickability(True)
return
else:
self.offeredBookMode = kGUI.Offeree
PtDebugPrint(u"xKI.OnNotify(): Offered book by ", self.bookOfferer.getName(), level=kDebugDumpLevel)
self.ShowYeeshaBook()
PtToggleAvatarClickability(False)
return
# Is it from the YeeshaBook?
elif event[0] == PtEventType.kBook:
if self.KILevel == kMicroKI:
plybkCB = ptGUIControlCheckBox(KIMicroBlackbar.dialog.getControlFromTag(kGUI.PlayerBookCBID))
else:
plybkCB = ptGUIControlCheckBox(KIBlackbar.dialog.getControlFromTag(kGUI.PlayerBookCBID))
if event[1] == PtBookEventTypes.kNotifyImageLink:
if event[2] == xLinkingBookDefs.kYeeshaBookShareID:
if self.isYeeshaBookEnabled:
# Rescind any previous offers.
PtClearOfferBookMode()
if self.offeredBookMode == kGUI.NotOffering:
# Take the PlayerBook.
self.yeeshaBook.hide()
PtToggleAvatarClickability(True)
plybkCB.setChecked(0)
# Prepare to choose who to offer the link to.
PtSetOfferBookMode(self.key, "Personal", "Relto")
elif event[2] == xLinkingBookDefs.kYeeshaBookLinkID:
if self.isYeeshaBookEnabled:
self.yeeshaBook.hide()
plybkCB.setChecked(0)
if self.offeredBookMode == kGUI.Offeree:
self.offeredBookMode = kGUI.NotOffering
avID = PtGetClientIDFromAvatarKey(self.bookOfferer.getKey())
PtNotifyOffererLinkAccepted(avID)
PtNotifyOffererLinkCompleted(avID)
self.bookOfferer = None
else:
# Is the player on a ladder or something?
curBrainMode = PtGetLocalAvatar().avatar.getCurrentMode()
if self.isEntireYeeshaBookEnabled and (curBrainMode == PtBrainModes.kNonGeneric or curBrainMode == PtBrainModes.kAFK or curBrainMode == PtBrainModes.kSit):
linkmgr = ptNetLinkingMgr()
linkmgr.linkToMyPersonalAgeWithYeeshaBook()
PtToggleAvatarClickability(True)
elif event[2] >= xLinkingBookDefs.kYeeshaPageStartID:
whatpage = event[2] - xLinkingBookDefs.kYeeshaPageStartID
sdlvar = xLinkingBookDefs.xYeeshaPages[whatpage][0]
self.ToggleYeeshaPageSDL(sdlvar, 1)
elif event[1] == PtBookEventTypes.kNotifyShow:
pass
elif event[1] == PtBookEventTypes.kNotifyHide:
PtToggleAvatarClickability(True)
plybkCB.setChecked(0)
if self.offeredBookMode == kGUI.Offeree:
self.offeredBookMode = kGUI.NotOffering
avID = PtGetClientIDFromAvatarKey(self.bookOfferer.getKey())
PtNotifyOffererLinkRejected(avID)
self.bookOfferer = None
elif event[1] == PtBookEventTypes.kNotifyNextPage:
pass
elif event[1] == PtBookEventTypes.kNotifyPreviousPage:
pass
elif event[1] == PtBookEventTypes.kNotifyCheckUnchecked:
if event[2] >= xLinkingBookDefs.kYeeshaPageStartID:
whatpage = event[2] - xLinkingBookDefs.kYeeshaPageStartID
sdlvar = xLinkingBookDefs.xYeeshaPages[whatpage][0]
self.ToggleYeeshaPageSDL(sdlvar, 0)
return
if state:
# Is it one of the responders that are displaying the BigKI?
if ID == KIOnResp.id:
self.ShowBigKIMode()
self.waitingForAnimation = False
toggleCB = ptGUIControlCheckBox(KIMini.dialog.getControlFromTag(kGUI.miniToggleBtnID))
toggleCB.enable()
elif ID == KIOffResp.id:
BigKI.dialog.hide()
self.waitingForAnimation = False
toggleCB = ptGUIControlCheckBox(KIMini.dialog.getControlFromTag(kGUI.miniToggleBtnID))
toggleCB.enable()
if ID == KIMarkerGameGUIClose.id:
PtHideDialog("KIMiniMarkers")
if ID == KIJalakGUIClose.id:
PtHideDialog("jalakControlPanel")
ptGUIControlButton(KIMini.dialog.getControlFromTag(kJalakMiniIconBtn)).enable()
elif ID == KIJalakGUIOpen.id:
KIJalakGUIDialog.dialog.enable()
ptGUIControlButton(KIMini.dialog.getControlFromTag(kJalakMiniIconBtn)).enable()
elif ID == KIJalakBtnLights.id:
btnID = int(KIJalakBtnLights.getState())
SendNote(self.key, self.jalakScript, "{}".format(btnID))
PtAtTimeCallback(self.key, kJalakBtnDelaySeconds, kTimers.JalakBtnDelay)
## Called by Plasma when a page has been loaded.
# This is used to delay the display of objects until something is paged in.
def OnPageLoad(self, what, room):
if not self.KIGUIInitialized:
self.KIGUIInitialized = True
self.SetupKI()
# When we unload the page, then the device we have must be gone.
if what == kUnloaded:
self.folderOfDevices.removeAll()
# Remove any selected player.
if self.KILevel == kNormalKI:
self.BKPlayerSelected = None
sendToField = ptGUIControlTextBox(BigKI.dialog.getControlFromTag(kGUI.BKIPlayerLine))
sendToField.setString(" ")
if self.gGZMarkerInRange:
self.gGZMarkerInRange = 0
self.gGZMarkerInRangeRepy = None
self.RefreshMiniKIMarkerDisplay()
NewItemAlert.dialog.hide()
kialert = ptGUIControlButton(NewItemAlert.dialog.getControlFromTag(kAlertKIAlert))
kialert.hide()
if self.pelletImager != "":
self.pelletImager = ""
ptGUIControlButton(KIMini.dialog.getControlFromTag(kGUI.PelletScoreButton)).hide()
## Called by Plasma when a GUI event occurs.
# Delegates the appropriate response to the correct handler.
def OnGUINotify(self, ID, control, event):
PtDebugPrint(u"xKI.OnGUINotify(): ID = {}, event = {}, control = {}.".format(ID, event, control), level=kDebugDumpLevel)
if ID == KIBlackbar.id:
self.ProcessNotifyBlackbar(control, event)
elif ID == KIMicroBlackbar.id:
self.ProcessNotifyMicroBlackbar(control, event)
elif ID == KIMicro.id:
self.ProcessNotifyMicro(control, event)
elif ID == KIMini.id:
self.ProcessNotifyMini(control, event)
elif ID == BigKI.id:
self.ProcessNotifyBigKI(control, event)
elif ID == KIListModeDialog.id:
self.ProcessNotifyListMode(control, event)
elif ID == KIPictureExpanded.id:
self.ProcessNotifyPictureExpanded(control, event)
elif ID == KIJournalExpanded.id:
self.ProcessNotifyJournalExpanded(control, event)
elif ID == KIPlayerExpanded.id:
self.ProcessNotifyPlayerExpanded(control, event)
elif ID == KISettings.id:
self.ProcessNotifySettingsExpanded(control, event)
elif ID == KIVolumeExpanded.id:
self.ProcessNotifyVolumeExpanded(control, event)
elif ID == KIAgeOwnerExpanded.id:
self.ProcessNotifyAgeOwnerExpanded(control, event)
elif ID == KIYesNo.id:
self.ProcessNotifyYesNo(control, event)
elif ID == NewItemAlert.id:
self.ProcessNotifyNewItemAlert(control, event)
elif ID == KICreateMarkerGameGUI.id:
self.ProcessNotifyCreateMarkerGameGUI(control, event)
elif ID == KIMarkerFolderExpanded.id:
self.ProcessNotifyMarkerFolderExpanded(control, event)
elif ID == KIMarkerFolderPopupMenu.id:
self.ProcessNotifyMarkerFolderPopupMenu(control, event)
elif ID == KIJalakGUIDialog.id:
self.ProcessNotifyJalakGUI(control, event)
## Called by Plasma on receipt of a KI message.
# These are messages which instruct xKI to perform a certain command like
# enabling or disabling the KI, showing a Yes/No dialog, etc.. These
# messages can also be sent from the Python to Plasma and back.
def OnKIMsg(self, command, value):
PtDebugPrint(u"xKI.OnKIMsg(): command = {} value = {}.".format(command, value), level=kDebugDumpLevel)
if self.markerGameManager.OnKIMsg(command, value):
return
if command == kEnterChatMode and not self.KIDisabled:
self.chatMgr.ToggleChatMode(1)
elif command == kSetChatFadeDelay:
self.chatMgr.ticksOnFull = value
elif command == kSetTextChatAdminMode:
self.chatMgr.isAdmin = value
elif command == kDisableKIandBB:
self.KIDisabled = True
self.chatMgr.KIDisabled = True
self.KIHardDisabled = True
if self.KILevel == kMicroKI:
KIMicroBlackbar.dialog.hide()
if KIMicro.dialog.isEnabled():
self.miniKIWasUp = True
KIMicro.dialog.hide()
else:
self.miniKIWasUp = False
else:
KIBlackbar.dialog.hide()
if KIMini.dialog.isEnabled():
self.miniKIWasUp = True
KIMini.dialog.hide()
else:
self.miniKIWasUp = False
if not self.waitingForAnimation:
# Hide all dialogs on the right side of the BigKI and hide it.
KIListModeDialog.dialog.hide()
KIPictureExpanded.dialog.hide()
KIJournalExpanded.dialog.hide()
KIPlayerExpanded.dialog.hide()
BigKI.dialog.hide()
KIOnAnim.animation.skipToTime(1.5)
# If an outsider has a Yes/No up, tell them No.
if self.YNWhatReason == kGUI.YNOutside:
if self.YNOutsideSender is not None:
note = ptNotify(self.key)
note.clearReceivers()
note.addReceiver(self.YNOutsideSender)
note.netPropagate(0)
note.netForce(0)
note.setActivate(0)
note.addVarNumber("YesNo", 0)
note.send()
self.YNOutsideSender = None
# Hide the Yeesha Book.
if self.yeeshaBook:
self.yeeshaBook.hide()
PtToggleAvatarClickability(True)
plybkCB = ptGUIControlCheckBox(KIBlackbar.dialog.getControlFromTag(kGUI.PlayerBookCBID))
plybkCB.setChecked(0)
self.YNWhatReason = kGUI.YNQuit
KIYesNo.dialog.hide()
elif command == kEnableKIandBB:
self.KIDisabled = False
self.chatMgr.KIDisabled = False
self.KIHardDisabled = False
if self.KILevel == kMicroKI:
KIMicroBlackbar.dialog.show()
if self.miniKIWasUp:
KIMicro.dialog.show()
else:
KIBlackbar.dialog.show()
if self.miniKIWasUp:
self.chatMgr.ClearBBMini(0)
KIMini.dialog.show()
elif command == kTempDisableKIandBB:
self.KIDisabled = True
self.chatMgr.KIDisabled = True
if self.KILevel == kMicroKI:
KIMicroBlackbar.dialog.hide()
else:
KIBlackbar.dialog.hide()
if self.yeeshaBook:
self.yeeshaBook.hide()
PtToggleAvatarClickability(True)
plybkCB = ptGUIControlCheckBox(KIBlackbar.dialog.getControlFromTag(kGUI.PlayerBookCBID))
plybkCB.setChecked(0)
elif command == kTempEnableKIandBB and not self.KIHardDisabled:
self.KIDisabled = False
self.chatMgr.KIDisabled = False
if self.KILevel == kMicroKI:
KIMicroBlackbar.dialog.showNoReset()
else:
KIBlackbar.dialog.showNoReset()
elif command == kYesNoDialog:
self.YNWhatReason = kGUI.YNOutside
self.YNOutsideSender = value[1]
yesText = ptGUIControlTextBox(KIYesNo.dialog.getControlFromTag(kGUI.YesNoTextID))
yesText.setStringW(value[0])
self.LocalizeDialog(1)
KIYesNo.dialog.show()
elif command == kAddPlayerDevice:
if "<p>" in value:
self.pelletImager = value.rstrip("<p>")
ptGUIControlButton(KIMini.dialog.getControlFromTag(kGUI.PelletScoreButton)).show()
PtDebugPrint(u"Pellet Imager:", self.pelletImager, level=kDebugDumpLevel)
return
try:
self.folderOfDevices.index(Device(value))
except ValueError:
self.folderOfDevices.append(Device(value))
self.RefreshPlayerList()
elif command == kRemovePlayerDevice:
if "<p>" in value:
self.pelletImager = ""
ptGUIControlButton(KIMini.dialog.getControlFromTag(kGUI.PelletScoreButton)).hide()
return
try:
self.folderOfDevices.remove(Device(value))
except ValueError:
pass
self.RefreshPlayerList()
elif command == kUpgradeKILevel:
if value >= kLowestKILevel and value <= kHighestKILevel:
if value > self.KILevel:
PtDebugPrint(u"xKI.OnKIMsg(): Upgrading from KI level {} to new KI level of {}.".format(self.KILevel, value), level=kWarningLevel)
self.RemoveKILevel(self.KILevel)
self.KILevel = value
self.chatMgr.KILevel = self.KILevel
self.UpdateKILevelChronicle()
self.WearKILevel(self.KILevel)
else:
PtDebugPrint(u"xKI.OnKIMsg(): Ignoring, trying to upgrade from KI level {} to new KI level of {}.".format(self.KILevel, value), level=kWarningLevel)
self.MakeSureWeWereKILevel()
else:
PtDebugPrint(u"xKI.OnKIMsg(): Invalid KI level {}.".format(value), level=kErrorLevel)
elif command == kDowngradeKILevel:
if value == self.KILevel:
PtDebugPrint(u"xKI.OnKIMsg(): Remove KI level of {}.".format(value), level=kWarningLevel)
if value == kNormalKI:
self.RemoveKILevel(kNormalKI)
self.KILevel = kMicroKI
self.chatMgr.KILevel = self.KILevel
self.UpdateKILevelChronicle()
self.WearKILevel(self.KILevel)
else:
PtDebugPrint(u"xKI.OnKIMsg(): Ignoring, can't remove to any lower than {}.".format(value), level=kWarningLevel)
else:
PtDebugPrint(u"xKI.OnKIMsg(): Ignoring, trying to remove KI Level {}, but currently at {}.".format(value, self.KILevel), level=kWarningLevel)
elif command == kSetPrivateChatChannel:
self.chatMgr.privateChatChannel = value
elif command == kUnsetPrivateChatChannel:
self.chatMgr.privateChatChannel = 0
elif command == kStartBookAlert:
self.AlertBookStart()
elif command == kStartKIAlert:
self.AlertKIStart()
elif command == kUpdatePelletScore:
self.UpdatePelletScore()
self.AlertKIStart()
elif command == kMiniBigKIToggle:
self.ToggleKISize()
elif command == kKIPutAway:
self.ToggleMiniKI()
elif command == kChatAreaPageUp:
self.chatMgr.ScrollChatArea(PtGUIMultiLineDirection.kPageUp)
elif command == kChatAreaPageDown:
self.chatMgr.ScrollChatArea(PtGUIMultiLineDirection.kPageDown)
elif command == kChatAreaGoToBegin:
self.chatMgr.ScrollChatArea(PtGUIMultiLineDirection.kBufferStart)
elif command == kChatAreaGoToEnd:
self.chatMgr.ScrollChatArea(PtGUIMultiLineDirection.kBufferEnd)
elif command == kKITakePicture:
self.TakePicture()
elif command == kKICreateJournalNote:
self.MiniKICreateJournalNote()
elif command == kKIToggleFade:
if self.chatMgr.IsFaded():
self.ResetFadeState()
else:
self.FadeCompletely()
elif command == kKIToggleFadeEnable:
self.KillFadeTimer()
if self.chatMgr.fadeEnableFlag:
self.chatMgr.fadeEnableFlag = False
else:
self.chatMgr.fadeEnableFlag = True
self.StartFadeTimer()
elif command == kKIChatStatusMsg:
self.chatMgr.DisplayStatusMessage(value, 1)
elif command == kKILocalChatStatusMsg:
self.chatMgr.DisplayStatusMessage(value, 0)
elif command == kKILocalChatErrorMsg:
self.chatMgr.AddChatLine(None, value, kChat.SystemMessage)
elif command == kKIUpSizeFont:
self.ChangeFontSize(1)
elif command == kKIDownSizeFont:
self.ChangeFontSize(-1)
elif command == kKIOpenYeehsaBook:
nm = ptNetLinkingMgr()
if self.KILevel >= kMicroKI and not self.KIDisabled and not self.waitingForAnimation and nm.isEnabled():
curBrainMode = PtGetLocalAvatar().avatar.getCurrentMode()
if self.isEntireYeeshaBookEnabled and (curBrainMode == PtBrainModes.kNonGeneric or curBrainMode == PtBrainModes.kAFK or curBrainMode == PtBrainModes.kSit):
self.ShowYeeshaBook()
if self.KILevel == kMicroKI:
plybkCB = ptGUIControlCheckBox(KIMicroBlackbar.dialog.getControlFromTag(kGUI.PlayerBookCBID))
else:
plybkCB = ptGUIControlCheckBox(KIBlackbar.dialog.getControlFromTag(kGUI.PlayerBookCBID))
plybkCB.setChecked(1)
elif command == kKIOpenKI:
if not self.waitingForAnimation:
if not KIMini.dialog.isEnabled():
self.ToggleMiniKI(1)
elif not BigKI.dialog.isEnabled():
if self.chatMgr.fadeEnableFlag and self.chatMgr.IsFaded():
self.ResetFadeState()
else:
self.ToggleKISize()
else:
self.ToggleMiniKI()
elif command == kKIShowOptionsMenu:
if self.yeeshaBook:
self.yeeshaBook.hide()
PtToggleAvatarClickability(True)
if self.KILevel == kMicroKI:
plybkCB = ptGUIControlCheckBox(KIMicroBlackbar.dialog.getControlFromTag(kGUI.PlayerBookCBID))
plybkCB.setChecked(0)
elif self.KILevel > kMicroKI:
plybkCB = ptGUIControlCheckBox(KIBlackbar.dialog.getControlFromTag(kGUI.PlayerBookCBID))
plybkCB.setChecked(0)
if not self.waitingForAnimation and not self.KIDisabled:
PtShowDialog("OptionsMenuGUI")
elif command == kKIOKDialog or command == kKIOKDialogNoQuit:
reasonField = ptGUIControlTextBox(KIYesNo.dialog.getControlFromTag(kGUI.YesNoTextID))
try:
localized = kLoc.OKDialogDict[value]
except KeyError:
localized = U"UNTRANSLATED: " + unicode(value)
reasonField.setStringW(localized)
noButton = ptGUIControlButton(KIYesNo.dialog.getControlFromTag(kGUI.NoButtonID))
noButton.hide()
noBtnText = ptGUIControlTextBox(KIYesNo.dialog.getControlFromTag(kGUI.NoButtonTextID))
noBtnText.hide()
yesBtnText = ptGUIControlTextBox(KIYesNo.dialog.getControlFromTag(kGUI.YesButtonTextID))
yesBtnText.setStringW(PtGetLocalizedString("KI.YesNoDialog.OKButton"))
self.YNWhatReason = kGUI.YNQuit
if command == kKIOKDialogNoQuit:
self.YNWhatReason = kGUI.YNNoReason
KIYesNo.dialog.show()
elif command == kDisableYeeshaBook:
self.isYeeshaBookEnabled = False
elif command == kEnableYeeshaBook:
self.isYeeshaBookEnabled = True
elif command == kQuitDialog:
yesText = ptGUIControlTextBox(KIYesNo.dialog.getControlFromTag(kGUI.YesNoTextID))
yesText.setStringW(PtGetLocalizedString("KI.Messages.LeaveGame"))
self.LocalizeDialog()
logoutText = ptGUIControlTextBox(KIYesNo.dialog.getControlFromTag(kGUI.YesNoLogoutTextID))
logoutText.show()
logoutButton = ptGUIControlButton(KIYesNo.dialog.getControlFromTag(kGUI.YesNoLogoutButtonID))
logoutButton.show()
KIYesNo.dialog.show()
elif command == kDisableEntireYeeshaBook:
self.isEntireYeeshaBookEnabled = False
elif command == kEnableEntireYeeshaBook:
self.isEntireYeeshaBookEnabled = True
elif command == kUpgradeKIMarkerLevel:
self.UpgradeKIMarkerLevel(value)
self.RefreshMiniKIMarkerDisplay()
elif command == kKIShowMiniKI:
if self.KILevel >= kNormalKI:
self.chatMgr.ClearBBMini(0)
elif command == kFriendInviteSent:
if value == 0:
self.chatMgr.DisplayStatusMessage(PtGetLocalizedString("KI.Messages.InviteSuccess"))
else:
if value == 30:
msg = PtGetLocalizedString("KI.Errors.InvitesDisabled")
else:
msg = "Error occured trying to send invite: " + str(value)
self.chatMgr.AddChatLine(None, msg, kChat.SystemMessage)
elif command == kRegisterImager:
self.imagerMap[value[0]] = value[1]
#~~~~~~~~~~~~~~~~~~~~~#
# GZ Markers messages #
#~~~~~~~~~~~~~~~~~~~~~#
elif command == kGZUpdated:
if value != 0:
# Setting the max in the GZ marker chronicle.
vault = ptVault()
entry = vault.findChronicleEntry(kChronicleGZMarkersAquired)
if entry is not None:
markers = entry.chronicleGetValue()
if len(markers) < value:
# Need to increase the capacity of the markers; start as active.
markers += kGZMarkerAvailable * (value - len(markers))
entry.chronicleSetValue(markers)
entry.save()
else:
# If there are none, then just add another entry; start as active.
markers = kGZMarkerAvailable * value
vault.addChronicleEntry(kChronicleGZMarkersAquired, kChronicleGZMarkersAquiredType, markers)
self.DetermineKILevel()
self.DetermineGZ()
self.RefreshMiniKIMarkerDisplay()
elif command == kGZFlashUpdate:
try:
args = value.split()
GZGame = int(args[0])
except:
PtDebugPrint(u"xKI.OnKIMsg(): Cannot Update Marker Display, invalid Parameters: {}.".format(value))
return
if GZGame == -1:
self.GZFlashUpdate(value)
else:
self.DetermineKILevel()
if self.gKIMarkerLevel > kKIMarkerNotUpgraded and self.gKIMarkerLevel < kKIMarkerNormalLevel:
self.GZFlashUpdate(value)
self.RefreshMiniKIMarkerDisplay()
elif command == kGZInRange:
# Only say markers are in range if there are more markers to get.
if self.gMarkerToGetNumber > self.gMarkerGottenNumber:
self.gGZMarkerInRange = value[0]
self.gGZMarkerInRangeRepy = value[1]
self.RefreshMiniKIMarkerDisplay()
# Show alert
NewItemAlert.dialog.show()
KIAlert = ptGUIControlButton(NewItemAlert.dialog.getControlFromTag(kAlertKIAlert))
KIAlert.show()
elif command == kGZOutRange:
self.gGZMarkerInRange = 0
self.gGZMarkerInRangeRepy = None
self.RefreshMiniKIMarkerDisplay()
NewItemAlert.dialog.hide()
KIAlert = ptGUIControlButton(NewItemAlert.dialog.getControlFromTag(kAlertKIAlert))
KIAlert.hide()
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# User-created Marker Games messages #
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
elif command == kKICreateMarker:
self.CreateAMarker()
elif command == kKICreateMarkerFolder:
self.CreateMarkerGame()
## Called by Plasma on receipt of a backdoor message.
# These backdoor messages can trigger various actions.
def OnBackdoorMsg(self, target, param):
if target == "ki" and param == "refresh":
self.BKFolderLineDict = self.BKJournalFolderDict
self.BKFolderListOrder = self.BKJournalListOrder
self.BKFolderSelected = self.BKJournalFolderSelected
self.BKFolderTopLine = self.BKJournalFolderTopLine
self.BigKIRefreshFolderList()
self.BigKIRefreshFolderDisplay()
self.BigKIRefreshContentList()
self.BigKIRefreshContentListDisplay()
self.ChangeBigKIMode(kGUI.BKListMode)
if target.lower() == "cgz":
self.markerGameManager.OnBackdoorMsg(target, param)
## Called by Plasma on receipt of a chat message.
# This does not get called if the user sends a chat message through the KI,
# only if he's getting a new message from another player.
def OnRTChat(self, player, message, flags):
if message is not None:
cFlags = xKIChat.ChatFlags(flags)
# Is it a private channel message that can't be listened to?
if cFlags.broadcast and cFlags.channel != self.chatMgr.privateChatChannel:
return
# Is the message from an ignored plaer?
vault = ptVault()
ignores = vault.getIgnoreListFolder()
if ignores is not None and ignores.playerlistHasPlayer(player.getPlayerID()):
return
# Display the message if it passed all the above checks.
self.chatMgr.AddChatLine(player, message, cFlags, forceKI=not self.sawTheKIAtLeastOnce)
# If they are AFK and the message was directly to them, send back their state to sender.
try:
if self.KIDisabled or PtGetLocalAvatar().avatar.getCurrentMode() == PtBrainModes.kAFK and cFlags.private and not cFlags.toSelf:
myself = PtGetLocalPlayer()
AFKSelf = ptPlayer(myself.getPlayerName() + PtGetLocalizedString("KI.Chat.AFK"), myself.getPlayerID())
PtSendRTChat(AFKSelf, [player], " ", cFlags.flags)
except NameError:
pass
## Called by Plasma when a timer is running.
# Used to handle fading and the current time in the BigKI.
def OnTimer(self, ID):
# Chat fading.
if ID == kTimers.Fade:
# If it is fading, fade a tick.
if self.chatMgr.fadeMode == kChat.FadeFullDisp:
self.chatMgr.currentFadeTick -= 1
# Setup call for next second.
if self.chatMgr.currentFadeTick > 0:
PtAtTimeCallback(self.key, kChat.FullTickTime, kTimers.Fade)
else:
self.chatMgr.fadeMode = kChat.FadeDoingFade
self.chatMgr.currentFadeTick = kChat.TicksOnFade
PtAtTimeCallback(self.key, kChat.FadeTickTime, kTimers.Fade)
elif self.chatMgr.fadeMode == kChat.FadeDoingFade:
self.chatMgr.currentFadeTick -= 1
if self.chatMgr.currentFadeTick > 0:
# Fade a little.
if self.KILevel < kNormalKI:
mKIdialog = KIMicro.dialog
else:
mKIdialog = KIMini.dialog
mKIdialog.setForeColor(-1, -1, -1, self.originalForeAlpha * self.chatMgr.currentFadeTick / kChat.TicksOnFade)
mKIdialog.setSelectColor(-1, -1, -1, self.originalSelectAlpha * self.chatMgr.currentFadeTick / kChat.TicksOnFade)
mKIdialog.refreshAllControls()
# Setup call for next second.
PtAtTimeCallback(self.key, kChat.FadeTickTime, kTimers.Fade)
else:
# Completely fade out.
self.chatMgr.FadeCompletely()
elif self.chatMgr.fadeMode == kChat.FadeStopping:
self.chatMgr.fadeMode = kChat.FadeNotActive
# Time of day.
elif ID == kTimers.BKITODCheck and BigKI.dialog.isEnabled():
self.BigKISetChanging()
# Time of the currently played Marker Game.
elif ID == kTimers.MarkerGame and self.currentPlayingMarkerGame is not None:
self.currentPlayingMarkerGame.updateGameTime()
PtAtTimeCallback(self.key, 1, kTimers.MarkerGame)
# Stop an alert.
elif ID == kTimers.AlertHide:
self.AlertStop()
# Take a snapshot after a waiting period.
elif ID == kTimers.TakeSnapShot:
PtDebugPrint(u"xKI.OnTimer(): Taking snapshot.")
PtStartScreenCapture(self.key)
# Dump the open logs.
elif ID == kTimers.DumpLogs:
if (PtDumpLogs(self.chatMgr.logDumpDest)):
self.chatMgr.DisplayStatusMessage(PtGetLocalizedString("KI.Messages.LogDumpSuccess", [self.chatMgr.logDumpDest]))
else:
self.chatMgr.DisplayStatusMessage(PtGetLocalizedString("KI.Messages.LogDumpFailed", [self.chatMgr.logDumpDest]))
# Turn off the KI light.
elif ID == kTimers.LightStop:
self.DoKILight(0, 0)
# Turn on the Jalak GUI buttons.
elif ID == kTimers.JalakBtnDelay:
self.SetJalakGUIButtons(1)
## Called by Plasma when a screen capture is done.
# This gets called once the screen capture is performed and ready to be
# processed by the KI.
def OnScreenCaptureDone(self, image):
PtDebugPrint(u"xKI.OnScreenCaptureDone(): Snapshot is ready to be processed.")
self.BigKICreateJournalImage(image)
# Only show the KI if there isn't a dialog in the way.
if not PtIsGUIModal():
# Make sure that we are in journal mode.
if self.BKFolderLineDict is not self.BKJournalFolderDict:
modeselector = ptGUIControlRadioGroup(BigKI.dialog.getControlFromTag(kGUI.BKRadioModeID))
modeselector.setValue(0)
# Hide any previously opened picture.
if self.BKRightSideMode != kGUI.BKPictureExpanded:
self.HideBigKIMode()
self.BKRightSideMode = kGUI.BKPictureExpanded
# Reset the top line and selection.
self.BigKIRefreshFolderDisplay()
# Prepare to edit the caption of the picture.
self.BigKIEnterEditMode(kGUI.BKEditFieldPICTitle)
BigKI.dialog.show()
# Was just the miniKI showing?
if self.lastminiKICenter is None and self.originalminiKICenter is not None:
dragBar = ptGUIControlDragBar(KIMini.dialog.getControlFromTag(kGUI.miniDragBar))
self.lastminiKICenter = dragBar.getObjectCenter()
dragBar.setObjectCenter(self.originalminiKICenter)
dragBar.anchor()
KIMini.dialog.show()
else:
# If the KI isn't supposed to be displayed, at least flash it so they know something happened.
self.AlertKIStart()
self.takingAPicture = False
# Save the image to the filesystem.
if "saveAsPNG" in dir(image):
preferredExtension = "png"
else:
preferredExtension = "jpg"
basePath = os.path.join(PtGetUserPath(), kImages.Directory)
if not PtCreateDir(basePath):
PtDebugPrint(u"xKI.OnScreenCaptureDone(): Unable to create \"{}\" directory. Image not saved to disk.".formatZ(basePath))
return
imageList = glob.iglob(os.path.join(basePath, "{}[0-9][0-9][0-9][0-9].{}".format(kImages.FileNameTemplate, preferredExtension)))
imageNumbers = [int(os.path.basename(img)[7:-4]) for img in imageList] + [0]
missingNumbers = set(range(1, max(imageNumbers))).difference(set(imageNumbers))
if len(missingNumbers) > 0:
firstMissing = min(missingNumbers)
else:
firstMissing = max(imageNumbers) + 1
tryName = os.path.join(basePath, U"{}{:04d}.{}".format(kImages.FileNameTemplate, firstMissing, preferredExtension))
PtDebugPrint(u"xKI.OnScreenCaptureDone(): Saving image to \"{}\".".format(tryName), level=kWarningLevel)
if "saveAsPNG" in dir(image):
image.saveAsPNG(tryName)
else:
image.saveAsJPEG(tryName, 90)
## Called by Plasma when the player list has been updated.
# This makes sure that everything is updated and refreshed.
def OnMemberUpdate(self):
PtDebugPrint(u"xKI.OnMemberUpdate(): Refresh player list.", level=kDebugDumpLevel)
if PtIsDialogLoaded("KIMini"):
self.RefreshPlayerList()
## Called by Plasma when a new player is selected in the player list.
def OnRemoteAvatarInfo(self, player):
if self.KILevel < kNormalKI:
return
avatarSet = 0
if isinstance(player, ptPlayer):
avatarSet = 1
self.BKPlayerSelected = player
sendToField = ptGUIControlTextBox(BigKI.dialog.getControlFromTag(kGUI.BKIPlayerLine))
sendToField.setString(player.getPlayerName())
self.SetBigKIToButtons()
# Find the player in the list and select them.
for pidx in range(len(self.BKPlayerList)):
if isinstance(self.BKPlayerList[pidx], ptPlayer) and self.BKPlayerList[pidx] == player:
playerlist = ptGUIControlListBox(KIMini.dialog.getControlFromTag(kGUI.PlayerList))
playerlist.setSelection(pidx)
# Set the caret for the chat.
caret = ptGUIControlTextBox(KIMini.dialog.getControlFromTag(kGUI.ChatCaretID))
caret.setStringW(PtGetLocalizedString("KI.Chat.TOPrompt") + unicode(player.getPlayerName()) + U" >")
privateChbox = ptGUIControlCheckBox(KIMini.dialog.getControlFromTag(kGUI.miniPrivateToggle))
privateChbox.setChecked(1)
break
if avatarSet:
if not KIMini.dialog.isEnabled():
KIMini.dialog.show()
self.ResetFadeState()
## Called by Plasma on receipt of a high-level player vault event.
def OnVaultNotify(self, event, tupData):
PtDebugPrint(u"xKI.OnVaultNotify(): Event = {} and data = {}.".format(event, tupData), level=kDebugDumpLevel)
if not tupData:
PtDebugPrint(u"xKI.OnVaultNotify(): Bailing, no Age data.")
return
if PtIsDialogLoaded("KIMain"):
if event == PtVaultNotifyTypes.kRegisteredOwnedAge or event == PtVaultNotifyTypes.kUnRegisteredOwnedAge or event == PtVaultNotifyTypes.kRegisteredVisitAge or event == PtVaultNotifyTypes.kUnRegisteredVisitAge:
if self.KILevel > kMicroKI:
# A new owned Age was added, refresh its folders.
if isinstance(tupData[0], ptVaultAgeLinkNode):
# Is it the neighborhood?
ownedAge = tupData[0].getAgeInfo()
if ownedAge is not None:
if self.IsAgeMyNeighborhood(ownedAge):
self.BigKIRefreshHoodStatics(ownedAge)
self.RefreshPlayerList()
# Rebuild the player folder list because it might have changed.
self.BigKIRefreshFolderList()
self.BigKIRefreshFolderDisplay()
self.BigKIRefreshContentList()
self.BigKIRefreshContentListDisplay()
self.RefreshAgeOwnerSettings()
else:
PtDebugPrint(u"xKI.OnVaultNotify(): No ageInfo. ", level=kErrorLevel)
else:
PtDebugPrint(u"xKI.OnVaultNotify(): Unknown tuple data type. ", level=kErrorLevel)
else:
PtDebugPrint(u"xKI.OnVaultNotify(): Unknown event {}.".format(event), level=kWarningLevel)
else:
PtDebugPrint(u"xKI.OnVaultNotify(): BigKI dialog was not loaded, waiting.", level=kDebugDumpLevel)
## Called by Plasma on receipt of a low-level player vault event.
def OnVaultEvent(self, event, tupData):
PtDebugPrint(u"xKI.VaultEvent(): Event = {} and data = {}.".format(event, tupData), level=kDebugDumpLevel)
self.HandleVaultTypeEvents(event, tupData)
## Called by Plasma on receipt of a low-level Age vault event.
def OnAgeVaultEvent(self, event, tupData):
PtDebugPrint(u"xKI.OnAgeVaultEvent(): Event = {} and data = {}.".format(event, tupData), level=kDebugDumpLevel)
self.HandleVaultTypeEvents(event, tupData)
## Called by Plasma when a marker has been captured by the player.
def OnMarkerMsg(self, msgType, tupData):
self.markerGameManager.OnMarkerMsg(msgType, tupData)
## Called by Plasma on receipt of a game score message.
# This is used for handling pellet scoring.
def OnGameScoreMsg(self, msg):
if isinstance(msg, ptGameScoreListMsg):
pelletTextBox = ptGUIControlTextBox(BigKI.dialog.getControlFromTag(kGUI.BKIPelletDrop))
try:
score = msg.getScores()[0]
points = score.getPoints()
if self.scoreOpCur == kPellets.ScoreFetchForDisplay:
if points < 0:
points = 0
pelletTextBox.setString(str(points))
PtDebugPrint(u"xKI.OnGameScoreMsg(): PelletDrop score: {}.".format(points), level=kWarningLevel)
elif self.scoreOpCur == kPellets.ScoreFetchMineForUpload:
self.scoreSource = score
self.DoScoreOp(kPellets.ScoreFetchUploadDestination)
elif self.scoreOpCur == kPellets.ScoreFetchUploadDestination:
self.scoreDestination = score
self.scoreUploaded = self.scoreSource.getPoints()
self.DoScoreOp(kPellets.ScoreTransfer)
except:
if self.scoreOpCur == kPellets.ScoreFetchForDisplay:
pelletTextBox.setString("000")
elif self.scoreOpCur == kPellets.ScoreFetchUploadDestination:
self.DoScoreOp(kPellets.ScoreCreateUploadDestination)
elif isinstance(msg, ptGameScoreTransferMsg):
pelletTextBox = ptGUIControlTextBox(BigKI.dialog.getControlFromTag(kGUI.BKIPelletDrop))
pelletTextBox.setString("000")
self.UploadPelletScore(self.scoreUploaded)
del self.scoreDestination
del self.scoreSource
self.scoreUploaded = 0
elif isinstance(msg, ptGameScoreUpdateMsg):
if self.scoreOpCur == kPellets.ScoreCreateUploadDestination:
self.scoreDestination = msg.getScore()
self.scoreUploaded = self.scoreSource.getPoints()
self.DoScoreOp(kPellets.ScoreTransfer)
# Process any remaining queued ops.
self.ProcessScoreOps()
#~~~~~~~~~~#
# KI Setup #
#~~~~~~~~~~#
## Sets up the KI for a given player.
# Goes through all the steps required to ensure the player's KI is
# appropriately up-to-date when a user starts playing.
def SetupKI(self):
self.BKPlayerList = []
self.BKPlayerSelected = None
self.previouslySelectedPlayer = None
self.BKJournalFolderDict = {}
self.BKJournalListOrder = []
self.BKJournalFolderSelected = 0
self.BKJournalFolderTopLine = 0
self.BKPlayerFolderDict = {}
self.BKPlayerListOrder = []
self.BKPlayerFolderSelected = 0
self.BKPlayerFolderTopLine = 0
self.BKConfigFolderDict = {}
self.BKConfigFolderSelected = 0
self.BKConfigFolderTopLine = 0
self.BKFolderLineDict = self.BKJournalFolderDict
self.BKFolderListOrder = self.BKJournalListOrder
self.BKFolderSelected = self.BKJournalFolderSelected
self.BKFolderTopLine = self.BKJournalFolderTopLine
self.BKFolderSelectChanged = False
self.BKIncomingFolder = None
self.BKNewItemsInInbox = 0
self.BKCurrentContent = None
self.BKContentList = []
self.BKContentListTopLine = 0
self.isYeeshaBookEnabled = True
self.isEntireYeeshaBookEnabled = True
self.DetermineCensorLevel()
self.DetermineKILevel()
self.DetermineKIFlags()
self.DetermineGZ()
# Hide all dialogs first.
KIMicroBlackbar.dialog.hide()
KIMicro.dialog.hide()
KIMini.dialog.hide()
KIBlackbar.dialog.hide()
BigKI.dialog.hide()
self.chatMgr.ToggleChatMode(0)
# Remove unneeded kFontShadowed flags (as long as we can't do that directly in the PRPs)
for dialogAttr in (BigKI, KIListModeDialog, KIJournalExpanded, KIPictureExpanded, KIPlayerExpanded, KIAgeOwnerExpanded, KISettings, KIMarkerFolderExpanded, KICreateMarkerGameGUI):
for i in xrange(dialogAttr.dialog.getNumControls()):
f = ptGUIControl(dialogAttr.dialog.getControlFromIndex(i))
# call this on all controls, even those that use the color scheme of the
# dialog and would already report the flag cleared after the first one,
# as they still need the setFontFlags call to refresh themselves
f.setFontFlags(f.getFontFlags() & ~int(PtFontFlags.kFontShadowed))
if self.KILevel == kMicroKI:
# Show the microBlackbar.
KIMicroBlackbar.dialog.show()
# Show the microKI.
KIMicro.dialog.show()
elif self.KILevel == kNormalKI:
# Show the normal Blackbar.
KIBlackbar.dialog.show()
self.chatMgr.ClearBBMini()
# Check for unseen messages.
self.CheckInboxForUnseen()
self.ToggleMiniKI()
modeselector = ptGUIControlRadioGroup(BigKI.dialog.getControlFromTag(kGUI.BKRadioModeID))
modeselector.setValue(0)
self.BigKIRefreshFolderList()
self.BigKIRefreshFolderDisplay()
self.BigKIRefreshContentList()
self.BigKIRefreshContentListDisplay()
self.ChangeBigKIMode(kGUI.BKListMode)
# Load the ding dang marker game
if self.gKIMarkerLevel == kKIMarkerNormalLevel:
self.markerGameManager.LoadFromVault()
#~~~~~~~~~~#
# KI Flags #
#~~~~~~~~~~#
## Sets the KI Flags from the Chronicle.
# KI Flags are settings for the player's KI (pertaining to Buddies).
def DetermineKIFlags(self):
vault = ptVault()
# Only get PMs and KI Mails from Buddies.
entry = vault.findChronicleEntry(kChron.OnlyPMs)
if entry is None:
# Not found, set to 0 by default.
vault.addChronicleEntry(kChron.OnlyPMs, kChron.OnlyPMsType, str(int(self.onlyGetPMsFromBuddies)))
else:
self.onlyGetPMsFromBuddies = int(entry.chronicleGetValue())
# Only allow the player to be buddied on request.
entry = vault.findChronicleEntry(kChron.BuddiesOnRequest)
if entry is None:
# Not found, set to 0 by default.
vault.addChronicleEntry(kChron.BuddiesOnRequest, kChron.BuddiesOnRequestType, str(int(self.onlyAllowBuddiesOnRequest)))
else:
self.onlyAllowBuddiesOnRequest = int(entry.chronicleGetValue())
## Save the KI Flags to the Chronicle.
def SaveKIFlags(self):
vault = ptVault()
# Only get PMs and KI Mails from Buddies.
entry = vault.findChronicleEntry(kChron.OnlyPMs)
if entry is not None:
entry.chronicleSetValue(str(int(self.onlyGetPMsFromBuddies)))
entry.save()
else:
vault.addChronicleEntry(kChron.OnlyPMs, kChron.OnlyPMsType, str(int(self.onlyGetPMsFromBuddies)))
# Only allow the player to be buddied on request.
entry = vault.findChronicleEntry(kChron.BuddiesOnRequest)
if entry is not None:
entry.chronicleSetValue(str(int(self.onlyAllowBuddiesOnRequest)))
entry.save()
else:
vault.addChronicleEntry(kChron.BuddiesOnRequest, kChron.BuddiesOnRequestType, str(int(self.onlyAllowBuddiesOnRequest)))
#~~~~~~~~~~#
# KI Light #
#~~~~~~~~~~#
## Finds out what the current KI light state is.
def CheckKILight(self):
timeRemaining = self.GetKILightChron()
if not timeRemaining:
PtDebugPrint(u"xKI.CheckKILight(): Had KI light, but it's currently off.", level=kDebugDumpLevel)
self.DoKILight(0, 1)
elif timeRemaining > 0:
PtDebugPrint(u"xKI.CheckKILight(): Have KI light, time remaining = ", timeRemaining, level=kDebugDumpLevel)
self.DoKILight(1, 1, timeRemaining)
self.SetKILightChron(0)
else:
PtDebugPrint(u"No KI light.", level=kDebugDumpLevel)
## Get the KI light remaining time from the chronicle.
def GetKILightChron(self):
vault = ptVault()
entry = vault.findChronicleEntry("KILightStop")
if entry is not None:
entryValue = entry.chronicleGetValue()
remaining = int(entryValue)
return remaining
else:
PtDebugPrint(u"xKI.GetKILightChron(): No KI light.", level=kDebugDumpLevel)
return -1
## Set the KI light remaining time in the chronicle.
def SetKILightChron(self, remaining):
vault = ptVault()
entry = vault.findChronicleEntry("KILightStop")
if entry is not None:
entryValue = entry.chronicleGetValue()
oldVal = int(entryValue)
if remaining == oldVal:
return
PtDebugPrint(u"xKI.SetKILightChron(): Set KI light chron to: ", remaining, level=kDebugDumpLevel)
entry.chronicleSetValue(str(int(remaining)))
entry.save()
## Manages the KI light.
def DoKILight(self, state, ff, remaining=0):
thisResp = kListLightResps[state]
LocalAvatar = PtGetLocalAvatar()
avatarKey = LocalAvatar.getKey()
avatarObj = avatarKey.getSceneObject()
respList = avatarObj.getResponders()
if len(respList) > 0:
PtDebugPrint(u"xKI.DoKILight(): Responder list:", level=kDebugDumpLevel)
for resp in respList:
PtDebugPrint(u" {}".format(resp.getName()))
if resp.getName() == thisResp:
PtDebugPrint(u"xKI.DoKILight(): Found KI light resp: {}.".format(thisResp), level=kDebugDumpLevel)
atResp = ptAttribResponder(42)
atResp.__setvalue__(resp)
atResp.run(self.key, avatar=LocalAvatar, fastforward=ff)
if state:
PtAtTimeCallback(self.key, remaining, kTimers.LightStop)
PtDebugPrint(u"xKI.DoKILight(): Light was on in previous age, turning on for remaining ", remaining, " seconds.", level=kWarningLevel)
curTime = PtGetDniTime()
self.lightStop = (remaining + curTime)
self.lightOn = True
else:
PtDebugPrint(u"xKI.DoKILight(): Light is shut off, updating chron.", level=kWarningLevel)
self.SetKILightChron(remaining)
self.lightOn = False
PtSetLightAnimStart(avatarKey, kKILightObjectName, False)
break
else:
PtDebugPrint(u"xKI.DoKILight(): Couldn't find any responders.", level=kErrorLevel)
#~~~~~~~~~~~~~~#
# Localization #
#~~~~~~~~~~~~~~#
## Gets the appropriate localized values for a Yes/No dialog.
def LocalizeDialog(self, dialog_type=0):
confirm = "KI.YesNoDialog.QuitButton"
if dialog_type == 1:
confirm = "KI.YesNoDialog.YESButton"
yesButton = ptGUIControlTextBox(KIYesNo.dialog.getControlFromTag(kGUI.YesButtonTextID))
noButton = ptGUIControlTextBox(KIYesNo.dialog.getControlFromTag(kGUI.NoButtonTextID))
yesButton.setStringW(PtGetLocalizedString(confirm))
noButton.setStringW(PtGetLocalizedString("KI.YesNoDialog.NoButton"))
#~~~~~~~~~#
# Pellets #
#~~~~~~~~~#
## Perform an operation on the pellet score.
def DoScoreOp(self, op):
self.scoreOps.append(op)
if self.scoreOpCur == kPellets.ScoreNoOp:
self.ProcessScoreOps()
## Process the stored score operations.
def ProcessScoreOps(self):
if not len(self.scoreOps):
self.scoreOpCur = kPellets.ScoreNoOp
return
self.scoreOpCur = self.scoreOps.pop(0)
if self.scoreOpCur == kPellets.ScoreFetchForDisplay:
ptGameScore.findPlayerScores("PelletDrop", self.key)
elif self.scoreOpCur == kPellets.ScoreFetchMineForUpload:
ptGameScore.findPlayerScores("PelletDrop", self.key)
elif self.scoreOpCur == kPellets.ScoreFetchUploadDestination:
ptGameScore.findAgeScores("PelletDrop", self.key)
elif self.scoreOpCur == kPellets.ScoreCreateUploadDestination:
ptGameScore.createAgeScore("PelletDrop", PtGameScoreTypes.kAccumulative, 0, self.key)
elif self.scoreOpCur == kPellets.ScoreTransfer:
self.scoreSource.transferPoints(self.scoreDestination, key=self.key)
## Update the pellet score to the specified value.
# If no value is specified, fetch the current score for display.
def UpdatePelletScore(self, points=0):
pelletTextBox = ptGUIControlTextBox(BigKI.dialog.getControlFromTag(kGUI.BKIPelletDrop))
if points:
pelletTextBox.setString(str(points))
else:
pelletTextBox.setString("...") # Fetching from server.
self.DoScoreOp(kPellets.ScoreFetchForDisplay)
## Upload the new pellet score to the server.
def UploadPelletScore(self, score=None):
if score:
hoodInfoUpdate = PtFindActivator("PythHoodInfoImagerUpdater")
PtDebugPrint(u"xKI.UploadPelletScore(): HoodInfoUpdate: {}.".format(hoodInfoUpdate), level=kDebugDumpLevel)
if hoodInfoUpdate:
notify = ptNotify(self.key)
notify.clearReceivers()
notify.addReceiver(hoodInfoUpdate)
notify.netPropagate(1)
notify.netForce(1)
notify.setActivate(1.0)
sName = "Score={}".format(PtGetLocalPlayer().getPlayerName())
notify.addVarNumber(sName, score)
notify.send()
PtDebugPrint(u"xKI.UploadPelletScore(): Sending score notify: {} {}.".format(sName, score), level=kDebugDumpLevel)
else:
self.DoScoreOp(kPellets.ScoreFetchMineForUpload)
#~~~~~~~~~~~~~~~#
# Auto-complete #
#~~~~~~~~~~~~~~~#
## Auto-completes the text for a given editing control.
def Autocomplete(self, control):
text = control.getStringW()
proposition = self.autocompleteState.pickNext(text)
if proposition is not None:
control.setStringW(proposition)
control.end()
control.refresh()
return
players = set()
for item in self.BKPlayerList:
if isinstance(item, ptPlayer):
players.add(item.getPlayerName())
elif isinstance(item, ptVaultNodeRef):
player = item.getChild()
playerInfo = player.upcastToPlayerInfoNode()
if playerInfo is not None:
players.add(playerInfo.playerGetName())
proposition = self.autocompleteState.pickFirst(text, players)
if proposition is not None:
control.setStringW(proposition)
control.end()
control.refresh()
#~~~~~~~~~~~~~~~~~#
# Message History #
#~~~~~~~~~~~~~~~~~#
## Set a control's text to a log entry in the message history
def MessageHistory(self, control, set):
if (set == "up"):
if (self.chatMgr.MessageHistoryIs < len(self.chatMgr.MessageHistoryList)-1):
self.chatMgr.MessageHistoryIs = self.chatMgr.MessageHistoryIs +1
control.setStringW(self.chatMgr.MessageHistoryList[self.chatMgr.MessageHistoryIs])
control.end()
control.refresh()
elif (set == "down"):
if (self.chatMgr.MessageHistoryIs > 0):
self.chatMgr.MessageHistoryIs = self.chatMgr.MessageHistoryIs -1
control.setStringW(self.chatMgr.MessageHistoryList[self.chatMgr.MessageHistoryIs])
control.end()
control.refresh()
#~~~~~~~~~~#
# GZ Games #
#~~~~~~~~~~#
## Sets the GZ globals from the Chronicle.
def DetermineGZ(self):
if self.gKIMarkerLevel > kKIMarkerNotUpgraded:
if self.gKIMarkerLevel < kKIMarkerNormalLevel:
vault = ptVault()
entry = vault.findChronicleEntry(kChronicleGZGames)
error = 0
if entry is not None:
gameString = entry.chronicleGetValue()
PtDebugPrint(u"xKI.DetermineGZ(): Game string is: \"{}\".".format(gameString), level=kWarningLevel)
args = gameString.split()
if len(args) == 3:
try:
self.gGZPlaying = int(args[0])
colors = args[1].split(":")
outof = args[2].split(":")
# Check for corrupted entry.
if len(colors) != 2 or len(outof) != 2:
PtDebugPrint(u"xKI.DetermineGZ(): Invalid color field or marker field.")
raise ValueError
# Check for invalid entry.
if (colors[0] == "red" or colors[0] == "green") and int(outof[1]) > 15:
PtDebugPrint(u"xKI.DetermineGZ(): Invalid marker number entry (i.e. 1515 bug).")
raise ValueError
self.gMarkerGottenColor = colors[0]
self.gMarkerToGetColor = colors[1]
self.gMarkerGottenNumber = int(outof[0])
self.gMarkerToGetNumber = int(outof[1])
return
except:
PtDebugPrint(u"xKI.DetermineGZ(): Could not read GZ Games Chronicle.", level=kErrorLevel)
error = 1
else:
PtDebugPrint(u"xKI.DetermineGZ(): Invalid GZ Games string formation.", level=kErrorLevel)
error = 1
# If there was a problem, reset everything to "off".
self.gGZPlaying = 0
self.gMarkerToGetColor = "off"
self.gMarkerGottenColor = "off"
self.gMarkerToGetNumber = 0
self.gMarkerGottenNumber = 0
# Reset Marker Games if a corrupted vault occurred.
if error:
PtDebugPrint(u"xKI.DetermineGZ(): Vault corrupted, resetting all Marker Game data.", level=kErrorLevel)
import grtzKIMarkerMachine
grtzKIMarkerMachine.ResetMarkerGame()
else:
# Can't be playing a GZ Game.
self.gGZPlaying = 0
# Clear only if there are no currently active games.
if self.markerGameState == kGames.MGNotActive or self.currentPlayingMarkerGame is None:
self.gMarkerToGetColor = "off"
self.gMarkerGottenColor = "off"
self.gMarkerToGetNumber = 0
self.gMarkerGottenNumber = 0
else:
# Reset everything to "off".
self.gGZPlaying = 0
self.gMarkerToGetColor = "off"
self.gMarkerGottenColor = "off"
self.gMarkerToGetNumber = 0
self.gMarkerGottenNumber = 0
## Update the GZ globals using provided values, not the Chronicle.
def GZFlashUpdate(self, gameString):
PtDebugPrint(u"xKI.GZFlashUpdate(): Game string is: \"{}\".".format(gameString), level=kWarningLevel)
args = gameString.split()
if len(args) == 3:
try:
GZPlaying = int(args[0])
colors = args[1].split(":")
outof = args[2].split(":")
# Check for corrupted entry.
if len(colors) != 2 or len(outof) != 2:
PtDebugPrint(u"xKI.GZFlashUpdate(): Invalid color field or marker field.")
raise ValueError
MarkerGottenColor = colors[0]
MarkerToGetColor = colors[1]
MarkerGottenNumber = int(outof[0])
MarkerToGetNumber = int(outof[1])
# Check for invalid entry.
if (colors[0] == "red" or colors[0] == "green") and MarkerToGetNumber > 15:
PtDebugPrint(u"xKI.GZFlashUpdate(): Invalid marker number entry (i.e. 1515 bug).")
raise ValueError
# Make sure the player is playing a GZ Game.
if GZPlaying != -1:
self.gGZPlaying = GZPlaying
self.gMarkerGottenColor = MarkerGottenColor
self.gMarkerToGetColor = MarkerToGetColor
self.gMarkerGottenNumber = MarkerGottenNumber
self.gMarkerToGetNumber = MarkerToGetNumber
return
except:
PtDebugPrint(u"xKI.GZFlashUpdate(): Could not read GZ Games Chronicle. Checking Chronicle for corruption.", level=kErrorLevel)
else:
PtDebugPrint(u"xKI.GZFlashUpdate(): Invalid GZ Games string formation. Checking Chronicle for corruption.", level=kErrorLevel)
vault = ptVault()
entry = vault.findChronicleEntry(kChronicleGZGames)
if entry is not None:
if gameString == entry.chronicleGetValue():
PtDebugPrint(u"xKI.GZFlashUpdate(): Vault corrupted: trying to gracefully reset to a default state.", level=kErrorLevel)
import grtzKIMarkerMachine
grtzKIMarkerMachine.ResetMarkerGame()
return
## Update the Chronicle's GZ Games values.
# This takes the form of a series of values, separated by ":".
def UpdateGZGamesChronicle(self):
if self.gGZPlaying:
vault = ptVault()
entry = vault.findChronicleEntry(kChronicleGZGames)
upString = "{} {}:{} {}:{}".format(self.gGZPlaying, self.gMarkerGottenColor, self.gMarkerToGetColor, self.gMarkerGottenNumber, self.gMarkerToGetNumber)
if entry is not None:
entry.chronicleSetValue(upString)
entry.save()
else:
vault.addChronicleEntry(kChronicleGZGames, kChronicleGZGamesType, upString)
## Register a captured GZ marker.
def CaptureGZMarker(self):
if self.gGZPlaying and self.gMarkerToGetNumber > self.gMarkerGottenNumber:
# Set the marker status to "captured" in the Chronicle.
vault = ptVault()
entry = vault.findChronicleEntry(kChronicleGZMarkersAquired)
if entry is not None:
markers = entry.chronicleGetValue()
markerIdx = self.gGZMarkerInRange - 1
if markerIdx >= 0 and markerIdx < len(markers):
if len(markers) - (markerIdx + 1) != 0:
markers = markers[:markerIdx] + kGZMarkerCaptured + markers[-(len(markers) - (markerIdx + 1)):]
else:
markers = markers[:markerIdx] + kGZMarkerCaptured
entry.chronicleSetValue(markers)
entry.save()
# Update the "marker gotten" count.
totalGotten = markers.count(kGZMarkerCaptured)
if self.gKIMarkerLevel > kKIMarkerFirstLevel:
# Is this the second wave of markers (or beyond)?
totalGotten -= 15
if totalGotten < 0:
totalGotten = 0
if totalGotten > self.gMarkerToGetNumber:
totalGotten = self.gMarkerToGetNumber
self.gMarkerGottenNumber = totalGotten
# Save update to Chronicle.
self.UpdateGZGamesChronicle()
else:
PtDebugPrint(u"xKI.CaptureGZMarker(): Invalid marker serial number of {}.".format(self.gGZMarkerInRange))
return
else:
PtDebugPrint(u"xKI.CaptureGZMarker(): No Chronicle entry found.")
return
# Start building the notify message to go back to the orignator.
if self.gGZMarkerInRangeRepy is not None:
note = ptNotify(self.key)
note.clearReceivers()
note.addReceiver(self.gGZMarkerInRangeRepy)
note.netPropagate(0)
note.netForce(0)
note.setActivate(1)
note.addVarNumber("Captured", 1)
note.send()
self.gGZMarkerInRangeRepy = None
self.gGZMarkerInRange = 0
#~~~~~~~~~~~~~~#
# Marker Games #
#~~~~~~~~~~~~~~#
## Selects a new Marker Game type.
def SelectMarkerType(self, tagID):
dlgObj = KICreateMarkerGameGUI
if tagID and self.selectedMGType != tagID and self.selectedMGType != 0:
PtDebugPrint(u"xKI.SelectMarkerType(): Old Marker Game type ID: ", self.selectedMGType, level=kDebugDumpLevel)
ptGUIControlButton(dlgObj.dialog.getControlFromTag(self.selectedMGType)).enable()
self.ChangeMarkerTypeColor(self.selectedMGType)
self.selectedMGType = tagID
PtDebugPrint(u"xKI.SelectMarkerType(): Selecting new Marker Game type: ", self.selectedMGType, level=kDebugDumpLevel)
ptGUIControlButton(dlgObj.dialog.getControlFromTag(self.selectedMGType)).disable()
self.ChangeMarkerTypeColor(tagID)
## Change the Marker Game type color.
def ChangeMarkerTypeColor(self, tagID):
dlgObj = KICreateMarkerGameGUI
currentColor = ptGUIControlTextBox(dlgObj.dialog.getControlFromTag(tagID + 5)).getForeColor()
if currentColor == self.markerGameDefaultColor:
ptGUIControlTextBox(dlgObj.dialog.getControlFromTag(tagID + 5)).setForeColor(self.markerGameSelectedColor)
elif currentColor == self.markerGameSelectedColor:
ptGUIControlTextBox(dlgObj.dialog.getControlFromTag(tagID + 5)).setForeColor(self.markerGameDefaultColor)
## Initialize the Marker Game creation GUI.
def InitMarkerGameGUI(self):
dlgObj = KICreateMarkerGameGUI
self.selectedMGType = kGUI.MarkerGameType1
if self.MGKILevel == 2:
ptGUIControlButton(dlgObj.dialog.getControlFromTag(kGUI.MarkerGameType1)).disable()
ptGUIControlButton(dlgObj.dialog.getControlFromTag(kGUI.MarkerGameType2)).enable()
ptGUIControlButton(dlgObj.dialog.getControlFromTag(kGUI.MarkerGameType2)).show()
ptGUIControlTextBox(dlgObj.dialog.getControlFromTag(kGUI.MarkerGameLabel2)).show()
ptGUIControlButton(dlgObj.dialog.getControlFromTag(kGUI.MarkerGameType3)).enable()
ptGUIControlButton(dlgObj.dialog.getControlFromTag(kGUI.MarkerGameType3)).show()
ptGUIControlTextBox(dlgObj.dialog.getControlFromTag(kGUI.MarkerGameLabel3)).show()
elif self.MGKILevel == 1:
ptGUIControlButton(dlgObj.dialog.getControlFromTag(kGUI.MarkerGameType1)).disable()
ptGUIControlButton(dlgObj.dialog.getControlFromTag(kGUI.MarkerGameType2)).enable()
ptGUIControlButton(dlgObj.dialog.getControlFromTag(kGUI.MarkerGameType2)).show()
ptGUIControlTextBox(dlgObj.dialog.getControlFromTag(kGUI.MarkerGameLabel2)).show()
ptGUIControlButton(dlgObj.dialog.getControlFromTag(kGUI.MarkerGameType3)).hide()
ptGUIControlTextBox(dlgObj.dialog.getControlFromTag(kGUI.MarkerGameLabel3)).hide()
elif self.MGKILevel == 0:
ptGUIControlButton(dlgObj.dialog.getControlFromTag(kGUI.MarkerGameType1)).disable()
ptGUIControlButton(dlgObj.dialog.getControlFromTag(kGUI.MarkerGameType2)).hide()
ptGUIControlTextBox(dlgObj.dialog.getControlFromTag(kGUI.MarkerGameLabel2)).hide()
ptGUIControlButton(dlgObj.dialog.getControlFromTag(kGUI.MarkerGameType3)).hide()
ptGUIControlTextBox(dlgObj.dialog.getControlFromTag(kGUI.MarkerGameLabel3)).hide()
ptGUIControlTextBox(dlgObj.dialog.getControlFromTag(kGUI.MarkerGameLabel1)).setForeColor(self.markerGameSelectedColor)
ptGUIControlTextBox(dlgObj.dialog.getControlFromTag(kGUI.MarkerGameLabel2)).setForeColor(self.markerGameDefaultColor)
ptGUIControlTextBox(dlgObj.dialog.getControlFromTag(kGUI.MarkerGameLabel3)).setForeColor(self.markerGameDefaultColor)
playerName = PtGetLocalPlayer().getPlayerName()
if playerName[-1] == "s":
addToName = "'"
else:
addToName = "'s"
gameName = playerName + addToName + " Marker Game"
ptGUIControlEditBox(KICreateMarkerGameGUI.dialog.getControlFromTag(kGUI.CreateMarkerGameNameEB)).setString(gameName)
## Begin the creation of a new Marker Game.
def CreateMarkerGame(self):
# Make sure the player's KI Level is appropriately high.
if self.KILevel <= kMicroKI or self.KIDisabled:
PtDebugPrint(u"xKI.CreateMarkerGame(): Aborting Marker Game creation request, player does not have the KI.", level=kDebugDumpLevel)
return
# Make sure the player's KI Marker Level is appropriately high.
if self.gKIMarkerLevel < kKIMarkerNormalLevel:
PtDebugPrint(u"xKI.CreateMarkerGame(): Aborting Marker Game creation request, player does not have sufficient privileges.", level=kDebugDumpLevel)
return
# The player cannot be doing another task.
if self.takingAPicture or self.waitingForAnimation:
PtDebugPrint(u"xKI.CreateMarkerGame(): Aborting Marker Game creation request, player is busy.", level=kDebugDumpLevel)
return
# The player cannot create a game if one is already in progress.
if self.markerGameManager.playing:
PtDebugPrint(u"xKI.CreateMarkerGame(): Aborting Marker Game creation request, a game is already in progress.", level=kDebugDumpLevel)
self.chatMgr.AddChatLine(None, PtGetLocalizedString("KI.MarkerGame.createErrorExistingGame"), kChat.SystemMessage)
return
# Make sure the player has enough room.
if not self.CanMakeMarkerGame():
PtDebugPrint(u"xKI.CreateMarkerGame(): Aborting Marker Game creation request, player has reached the limit of Marker Games.", level=kDebugDumpLevel)
self.ShowKIFullErrorMsg(PtGetLocalizedString("KI.Messages.FullMarkerGames"))
return
# The player can now launch the Marker Game creation GUI.
self.HideBigKI()
PtShowDialog("KIMiniMarkers")
KIMarkerGameGUIOpen.run(self.key, netPropagate=0)
## Finishes creating the Marker Game after the asynchronous mini-game
# server registers the parameters.
def FinishCreateMarkerGame(self, gameName):
# Get the current Age's Journal folder.
load = 0
while load < 2:
try:
journal = self.BKJournalFolderDict[self.GetAgeInstanceName()]
if journal is None:
raise
load = 2
except:
if load == 1:
# Failed twice in a row, it's hopeless.
## @todo Create the folder in case this happens.
PtDebugPrint(u"xKI.FinishCreateMarkerGame(): Could not load Age's Journal Folder, Marker Game creation failed.", level=kErrorLevel)
return
load += 1
self.BigKIRefreshFolderList()
# Hide the blackbar, just in case.
KIBlackbar.dialog.hide()
# Put the toggle button back to the BigKI setting.
toggleCB = ptGUIControlCheckBox(KIMini.dialog.getControlFromTag(kGUI.miniToggleBtnID))
toggleCB.setChecked(1)
# Set the current mode to the Age's Journal folder.
modeSelector = ptGUIControlRadioGroup(BigKI.dialog.getControlFromTag(kGUI.BKRadioModeID))
modeSelector.setValue(0)
self.BKFolderTopLine = self.BKJournalFolderTopLine = 0
self.BKFolderSelected = self.BKJournalFolderSelected = self.BKJournalListOrder.index(self.GetAgeInstanceName())
self.BigKIRefreshFolderDisplay()
# Create the Marker Game node.
PtDebugPrint(u"xKI.FinishCreateMarkerGame(): Creating Vault node with name = \"{}\".".format(gameName), level=kDebugDumpLevel)
markerGameNode = ptVaultMarkerGameNode()
markerGameNode.setCreatorNodeID(PtGetLocalClientID())
markerGameNode.setGameName(gameName)
self.BKCurrentContent = journal.addNode(markerGameNode)
# Change to display current content.
self.ChangeBigKIMode(kGUI.BKMarkerListExpanded)
if BigKI.dialog.isEnabled():
self.ShowBigKIMode()
else:
KIMini.dialog.hide()
BigKI.dialog.show()
KIMini.dialog.show()
if self.lastminiKICenter is None:
if self.originalminiKICenter is not None:
dragbar = ptGUIControlDragBar(KIMini.dialog.getControlFromTag(kGUI.miniDragBar))
self.lastminiKICenter = dragbar.getObjectCenter()
dragbar.setObjectCenter(self.originalminiKICenter)
dragbar.anchor()
## Add a new marker to the existing Marker Game.
def CreateAMarker(self):
if not self.takingAPicture and not self.waitingForAnimation:
if self.KILevel > kMicroKI and not self.KIDisabled:
self.UpdateKIUsage()
if self.CanMakeMarker():
markerName = u"{} marker".format(self.markerGameManager.game_name)
avaCoord = PtGetLocalAvatar().position()
self.markerGameManager.AddMarker(PtGetAgeName(), avaCoord, markerName)
PtDebugPrint(u"xKI.CreateAMarker(): Creating marker at: ({}, {}, {}).".format(avaCoord.getX(), avaCoord.getY(), avaCoord.getZ()))
else:
self.ShowKIFullErrorMsg(PtGetLocalizedString("KI.Messages.FullMarkers"))
## Perform the necessary operations to switch to a Marker Game.
def SetWorkingToCurrentMarkerGame(self):
if self.BKCurrentContent is None:
PtDebugPrint(u"xKI.SetWorkingToCurrentMarkerGame(): Cannot set working game, as there is no Vault folder.")
return
element = self.BKCurrentContent.getChild()
if element is None:
PtDebugPrint(u"xKI.SetWorkingToCurrentMarkerGame(): Cannot set working game, as there is no Vault node.")
return
element = element.upcastToMarkerGameNode()
if element is None:
PtDebugPrint(u"xKI.SetWorkingToCurrentMarkerGame(): Cannot set working game, as the Vault node is of the wrong type.")
return
# Refresh the content.
self.RefreshPlayerList()
self.BigKICheckContentRefresh(self.BKCurrentContent)
## Reset from the working Marker Game to None.
def ResetWorkingMarkerGame(self):
MGmgr = ptMarkerMgr()
# Don't delete any markers necessary for an existing game.
if not self.markerGameManager.is_game_loaded:
MGmgr.hideMarkersLocal()
# Refresh the content.
self.RefreshPlayerList()
self.BigKICheckContentRefresh(self.BKCurrentContent)
#~~~~~~~#
# Jalak #
#~~~~~~~#
## Initialize the Jalak KI GUI.
def JalakGUIInit(self):
jlakRandom = ptGUIControlButton(KIJalakGUIDialog.dialog.getControlFromTag(kJalakRandomBtn))
jlakExtreme = ptGUIControlButton(KIJalakGUIDialog.dialog.getControlFromTag(kJalakExtremeBtn))
jlakWall = ptGUIControlButton(KIJalakGUIDialog.dialog.getControlFromTag(kJalakWallToggleBtn))
jlakAllLow = ptGUIControlButton(KIJalakGUIDialog.dialog.getControlFromTag(kJalakColumnsLowBtn))
jlakAllMed = ptGUIControlButton(KIJalakGUIDialog.dialog.getControlFromTag(kJalakColumnsMedBtn))
jlakAllHigh = ptGUIControlButton(KIJalakGUIDialog.dialog.getControlFromTag(kJalakColumnsHighBtn))
jlakRamp = ptGUIControlButton(KIJalakGUIDialog.dialog.getControlFromTag(kJalakRampBtn))
jlakSphere = ptGUIControlButton(KIJalakGUIDialog.dialog.getControlFromTag(kJalakSphereBtn))
jlakBigBox = ptGUIControlButton(KIJalakGUIDialog.dialog.getControlFromTag(kJalakBigBoxBtn))
jlakLilBox = ptGUIControlButton(KIJalakGUIDialog.dialog.getControlFromTag(kJalakLilBoxBtn))
jlakRect = ptGUIControlButton(KIJalakGUIDialog.dialog.getControlFromTag(kJalakRectangleBtn))
jlakDestroy = ptGUIControlButton(KIJalakGUIDialog.dialog.getControlFromTag(kJalakDestroyBtn))
self.jalakGUIButtons = [jlakRandom, jlakExtreme, jlakWall, jlakAllLow, jlakAllMed, jlakAllHigh,
jlakRamp, jlakSphere, jlakBigBox, jlakLilBox, jlakRect, jlakDestroy]
obj = PtFindSceneobject("JalakDONOTTOUCH", "Jalak")
pythonScripts = obj.getPythonMods()
for script in pythonScripts:
if script.getName() == kJalakPythonComponent:
self.jalakScript = script
PtDebugPrint(u"xKI.JalakGUIInit(): Found Jalak's python component.", level=kDebugDumpLevel)
return
PtDebugPrint(u"xKI.JalakGUIInit(): Did not find Jalak's python component.", level=kErrorLevel)
## Toggle on/off the Jalak KI GUI.
def JalakGUIToggle(self, ff=0):
PtDebugPrint(u"xKI.JalakGUIToggle(): toggling GUI.", level=kDebugDumpLevel)
ptGUIControlButton(KIMini.dialog.getControlFromTag(kJalakMiniIconBtn)).disable()
if PtGetAgeName() != "Jalak":
self.jalakGUIState = False
return
if self.jalakGUIState:
self.jalakGUIState = False
KIJalakGUIClose.run(self.key, netPropagate=0, fastforward=ff)
if ff:
PtHideDialog("jalakControlPanel")
else:
# User cannot be busy doing some other task.
if self.takingAPicture or self.waitingForAnimation:
PtDebugPrint(u"xKI.JalakGUIToggle(): Aborting request for Jalak GUI: user is busy.", level=kDebugDumpLevel)
return
# Only those that have Gahreesen KI can create a game.
if self.KILevel <= kMicroKI or self.KIDisabled:
PtDebugPrint(u"xKI.JalakGUIToggle(): Aborting request for Jalak GUI: user does not have the KI.", level=kDebugDumpLevel)
return
self.jalakGUIState = True
PtShowDialog("jalakControlPanel")
KIJalakGUIOpen.run(self.key, netPropagate=0)
## Activate or deactivate all the buttons in the Jalak GUI.
def SetJalakGUIButtons(self, state):
for btn in self.jalakGUIButtons:
if state:
btn.enable()
else:
btn.disable()
#~~~~~~~~~~~#
# KI Levels #
#~~~~~~~~~~~#
## Make sure all the parts of the KI specific to this level are undone.
def RemoveKILevel(self, level):
# Is it removing the micro while upgrading?
if level == kMicroKI:
# Change the display to be the normal KI.
KIMicroBlackbar.dialog.hide()
KIMicro.dialog.hide()
# Is it going from normal back to micro?
elif level == kNormalKI:
avatar = PtGetLocalAvatar()
gender = avatar.avatar.getAvatarClothingGroup()
if gender > kFemaleClothingGroup:
gender = kMaleClothingGroup
avatar.netForce(1)
if gender == kFemaleClothingGroup:
avatar.avatar.removeClothingItem("FAccKI")
else:
avatar.avatar.removeClothingItem("MAccKI")
avatar.avatar.saveClothing()
# Fill in the listbox so that the test is near the enter box.
chatArea = ptGUIControlMultiLineEdit(KIMini.dialog.getControlFromTag(kGUI.ChatDisplayArea))
chatArea.lock() # Make the chat display immutable.
chatArea.unclickable() # Make the chat display non-clickable.
chatArea.moveCursor(PtGUIMultiLineDirection.kBufferEnd)
chatArea.disableScrollControl()
# Hide everything specific to the normalKI.
KIBlackbar.dialog.hide()
KIMini.dialog.hide()
KIListModeDialog.dialog.hide()
KIPictureExpanded.dialog.hide()
KIJournalExpanded.dialog.hide()
KIPlayerExpanded.dialog.hide()
BigKI.dialog.hide()
KIOnAnim.animation.skipToTime(1.5)
## Perform all operations associated with the newly-obtained KI level.
def WearKILevel(self, level):
if level == kMicroKI:
avatar = PtGetLocalAvatar()
gender = avatar.avatar.getAvatarClothingGroup()
if gender > kFemaleClothingGroup:
gender = kMaleClothingGroup
avatar.netForce(1)
if gender == kFemaleClothingGroup:
avatar.avatar.wearClothingItem("FAccPlayerBook")
else:
avatar.avatar.wearClothingItem("MAccPlayerBook")
avatar.avatar.saveClothing()
# Show the microKI.
KIMicroBlackbar.dialog.show()
self.chatMgr.ClearBBMini()
KIMicro.dialog.show()
self.chatMgr.ToggleChatMode(0)
elif level == kNormalKI:
avatar = PtGetLocalAvatar()
gender = avatar.avatar.getAvatarClothingGroup()
if gender > kFemaleClothingGroup:
gender = kMaleClothingGroup
avatar.netForce(1)
if gender == kFemaleClothingGroup:
avatar.avatar.wearClothingItem("FAccKI")
else:
avatar.avatar.wearClothingItem("MAccKI")
avatar.avatar.saveClothing()
# Change the display to match the normal KI.
KIBlackbar.dialog.show()
self.chatMgr.ClearBBMini()
KIOnAnim.animation.skipToTime(1.5)
# Alert the user to the newly-available KI.
self.AlertKIStart()
# Check the player's inbox.
self.CheckInboxForUnseen()
# Refresh the folders, which will create the age journal for this Age.
self.BigKIRefreshFolderList()
## Forcefully make sure the avatar is wearing the current KI level.
# This ensures the player is wearing either the Yeesha Book, or the Yeesha
# Book and the Gahreesen KI.
def MakeSureWeWereKILevel(self):
if self.KILevel == kMicroKI:
try:
avatar = PtGetLocalAvatar()
gender = avatar.avatar.getAvatarClothingGroup()
if gender > kFemaleClothingGroup:
gender = kMaleClothingGroup
avatar.netForce(1)
if gender == kFemaleClothingGroup:
avatar.avatar.wearClothingItem("FAccPlayerBook")
else:
avatar.avatar.wearClothingItem("MAccPlayerBook")
avatar.avatar.saveClothing()
except NameError:
pass
elif self.KILevel == kNormalKI:
try:
avatar = PtGetLocalAvatar()
gender = avatar.avatar.getAvatarClothingGroup()
if gender > kFemaleClothingGroup:
gender = kMaleClothingGroup
avatar.netForce(1)
if gender == kFemaleClothingGroup:
avatar.avatar.wearClothingItem("FAccPlayerBook")
avatar.avatar.wearClothingItem("FAccKI")
else:
avatar.avatar.wearClothingItem("MAccPlayerBook")
avatar.avatar.wearClothingItem("MAccKI")
avatar.avatar.saveClothing()
except NameError:
pass
## Sets the current KI level from the Chronicle.
# Also sets the current KI Marker Level.
def DetermineKILevel(self):
# Set the global KI Level.
self.KILevel = kMicroKI
vault = ptVault()
entry = vault.findChronicleEntry(kChronicleKILevel)
if entry is None:
# Not found, set to MicroKI by default.
vault.addChronicleEntry(kChronicleKILevel, kChronicleKILevelType, str(self.KILevel))
else:
oldLevel = int(entry.chronicleGetValue())
if oldLevel >= kLowestKILevel and oldLevel <= kHighestKILevel:
self.KILevel = oldLevel
elif oldLevel < kLowestKILevel:
# Make sure that the user has at least a microKI.
self.UpdateKILevelChronicle()
self.chatMgr.KILevel = self.KILevel
PtDebugPrint(u"xKI.DetermineKILevel(): The KI Level is {}.".format(self.KILevel), level=kWarningLevel)
# Set the KI Marker Level.
self.gKIMarkerLevel = 0
entry = vault.findChronicleEntry(kChronicleKIMarkerLevel)
if entry is None:
# Not found, set to 0 by default.
vault.addChronicleEntry(kChronicleKIMarkerLevel, kChronicleKIMarkerLevelType, str(self.gKIMarkerLevel))
else:
try:
self.gKIMarkerLevel = int(entry.chronicleGetValue())
except:
PtDebugPrint(u"xKI.DetermineKILevel(): Chronicle entry error with the KI's Marker Level, resetting to the default value.", level=kErrorLevel)
entry.chronicleSetValue(str(self.gKIMarkerLevel))
entry.save()
PtDebugPrint(u"xKI.DetermineKILevel(): The KI Marker Level is {}.".format(self.gKIMarkerLevel), level=kWarningLevel)
entry = vault.findChronicleEntry("feather")
if entry is None:
self.chatMgr.gFeather = 0
else:
try:
self.chatMgr.gFeather = int(entry.chronicleGetValue())
except ValueError:
self.chatMgr.gFeather = 0
## Upgrade the KI Marker Level to a new setting.
def UpgradeKIMarkerLevel(self, newLevel):
PtDebugPrint(u"xKI.UpgradeKIMarkerLevel(): KI Marker Level going from {} to {}.".format(self.gKIMarkerLevel, newLevel), level=kWarningLevel)
if self.KILevel > kMicroKI and newLevel > self.gKIMarkerLevel:
self.gKIMarkerLevel = newLevel
vault = ptVault()
entry = vault.findChronicleEntry(kChronicleKIMarkerLevel)
if entry is None:
PtDebugPrint(u"xKI.UpgradeKIMarkerLevel(): Chronicle entry not found, set to {}.".format(self.gKIMarkerLevel), level=kWarningLevel)
vault.addChronicleEntry(kChronicleKIMarkerLevel, kChronicleKIMarkerLevelType, str(self.gKIMarkerLevel))
else:
PtDebugPrint(u"xKI.UpgradeKIMarkerLevel(): Upgrading existing KI Marker Level to {}.".format(self.gKIMarkerLevel), level=kWarningLevel)
entry.chronicleSetValue(str(self.gKIMarkerLevel))
entry.save()
## Updates the KI level's Chronicle value.
def UpdateKILevelChronicle(self):
vault = ptVault()
entry = vault.findChronicleEntry(kChronicleKILevel)
if entry is not None:
entry.chronicleSetValue(str(self.KILevel))
entry.save()
else:
vault.addChronicleEntry(kChronicleKILevel, kChronicleKILevelType, str(self.KILevel))
#~~~~~~~~~~~~~#
# Yeesha Book #
#~~~~~~~~~~~~~#
## Show the Yeesha Book to the player, in accordance with its status.
def ShowYeeshaBook(self):
if self.KILevel >= kMicroKI and not self.KIDisabled and not self.waitingForAnimation:
if BigKI.dialog.isEnabled() or KIMini.dialog.isEnabled():
self.ToggleMiniKI()
startOpen = False
if self.isYeeshaBookEnabled:
if self.offeredBookMode == kGUI.NotOffering:
YeeshaBDef = xLinkingBookDefs.xYeeshaBookBase + self.GetYeeshaPageDefs()
else:
YeeshaBDef = xLinkingBookDefs.xYeeshaBookNoShare
startOpen = True
else:
YeeshaBDef = xLinkingBookDefs.xYeeshaBookBroke + self.GetYeeshaPageDefs()
self.yeeshaBook = ptBook(YeeshaBDef, self.key)
self.yeeshaBook.setSize(xLinkingBookDefs.YeeshaBookSizeWidth, xLinkingBookDefs.YeeshaBookSizeHeight)
self.yeeshaBook.show(startOpen)
PtToggleAvatarClickability(False)
## Returns the definitions for the Yeesha pages.
# Gets called whenever the Relto's Age GUI is drawn.
def GetYeeshaPageDefs(self):
pageDefs = ""
vault = ptVault()
if vault is not None:
psnlSDL = vault.getPsnlAgeSDL()
if psnlSDL:
for SDLVar, page in xLinkingBookDefs.xYeeshaPages:
FoundValue = psnlSDL.findVar(SDLVar)
if FoundValue is not None:
PtDebugPrint(u"xKI.GetYeeshaPageDefs(): The previous value of the SDL variable \"{}\" is {}.".format(SDLVar, FoundValue.getInt()), level=kDebugDumpLevel)
state = FoundValue.getInt() % 10
if state != 0:
active = 1
if state == 2 or state == 3:
active = 0
try:
pageDefs += page % (active)
except LookupError:
pageDefs += "<pb><pb>Bogus page {}".format(SDLVar)
else:
PtDebugPrint(u"xKI.GetYeeshaPageDefs(): Trying to access the Chronicle psnlSDL failed: psnlSDL = \"{}\".".format(psnlSDL), level=kErrorLevel)
else:
PtDebugPrint(u"xKI.GetYeeshaPageDefs(): Trying to access the Vault failed, can't access YeeshaPageChanges Chronicle.", level=kErrorLevel)
return pageDefs
## Turns on and off the Yeesha pages' SDL values.
def ToggleYeeshaPageSDL(self, varName, on):
vault = ptVault()
if vault is not None:
psnlSDL = vault.getPsnlAgeSDL()
if psnlSDL:
ypageSDL = psnlSDL.findVar(varName)
if ypageSDL:
size, state = divmod(ypageSDL.getInt(), 10)
value = None
if state == 1 and not on:
value = 3
elif state == 3 and on:
value = 1
elif state == 2 and on:
value = 4
elif state == 4 and not on:
value = 2
if value is not None:
PtDebugPrint(u"xKI.ToggleYeeshaPageSDL(): Setting {} to {}.".format(varName, value), level=kDebugDumpLevel)
ypageSDL.setInt((size * 10) + value)
vault.updatePsnlAgeSDL(psnlSDL)
#~~~~~~~~~~~#
# Censoring #
#~~~~~~~~~~~#
## Sets the censor level.
# By default, it's set at PG, but it fetches the real value from the
# chronicle. If it is not found in the chronicle, it will set it to PG.
def DetermineCensorLevel(self):
self.censorLevel = xCensor.xRatedPG
vault = ptVault()
entry = vault.findChronicleEntry(kChronicleCensorLevel)
if entry is None:
vault.addChronicleEntry(kChronicleCensorLevel, kChronicleCensorLevelType, str(self.censorLevel))
else:
self.censorLevel = int(entry.chronicleGetValue())
PtDebugPrint(u"xKI.DetermineCensorLevel(): The censor level is {}.".format(self.censorLevel), level=kWarningLevel)
def GetCensorLevel(self):
return self.censorLevel
#~~~~~~~#
# Fonts #
#~~~~~~~#
## Sets the current font size from the Chronicle.
def DetermineFontSize(self):
fontSize = self.GetFontSize()
vault = ptVault()
entry = vault.findChronicleEntry(kChron.FontSize)
if entry is None:
# Not found, add the current size to the Chronicle.
vault.addChronicleEntry(kChron.FontSize, kChron.FontSizeType, str(fontSize))
else:
fontSize = int(entry.chronicleGetValue())
self.SetFontSize(fontSize)
PtDebugPrint(u"xKI.DetermineFontSize(): The saved font size is {}.".format(fontSize), level=kWarningLevel)
## Saves the current font size to the Chronicle.
def SaveFontSize(self):
fontSize = self.GetFontSize()
vault = ptVault()
entry = vault.findChronicleEntry(kChron.FontSize)
if entry is not None:
entry.chronicleSetValue(str(fontSize))
entry.save()
else:
vault.addChronicleEntry(kChron.FontSize, kChron.FontSizeType, str(fontSize))
PtDebugPrint(u"xKI.SaveFontSize(): Saving font size of {}.".format(fontSize), level=kWarningLevel)
## Returns the font size currently applied to the KI.
def GetFontSize(self):
if self.KILevel < kNormalKI:
mKIdialog = KIMicro.dialog
else:
mKIdialog = KIMini.dialog
miniChatArea = ptGUIControlMultiLineEdit(mKIdialog.getControlFromTag(kGUI.ChatDisplayArea))
return miniChatArea.getFontSize()
## Applies the specified font size.
def SetFontSize(self, fontSize):
PtDebugPrint(u"xKI.SetFontSize(): Setting font size to {}.".format(fontSize), level=kWarningLevel)
if self.KILevel < kNormalKI:
mKIdialog = KIMicro.dialog
else:
mKIdialog = KIMini.dialog
miniChatArea = ptGUIControlMultiLineEdit(mKIdialog.getControlFromTag(kGUI.ChatDisplayArea))
miniChatArea.setFontSize(fontSize)
miniChatArea.refresh()
microChatArea = ptGUIControlMultiLineEdit(mKIdialog.getControlFromTag(kGUI.ChatDisplayArea))
microChatArea.setFontSize(fontSize)
microChatArea.refresh()
noteArea = ptGUIControlMultiLineEdit(KIJournalExpanded.dialog.getControlFromTag(kGUI.BKIJRNNote))
noteArea.setFontSize(fontSize)
noteArea.refresh()
ownerNotes = ptGUIControlMultiLineEdit(KIAgeOwnerExpanded.dialog.getControlFromTag(kGUI.BKAgeOwnerDescription))
ownerNotes.setFontSize(fontSize)
ownerNotes.refresh()
## Changes the font size currently in effect.
def ChangeFontSize(self, new):
size = self.GetFontSize()
if new == 1:
fontRange = range(len(kChat.FontSizeList) - 1)
elif new == -1:
fontRange = range(len(kChat.FontSizeList) - 1, 0, -1)
for i in fontRange:
if size <= kChat.FontSizeList[i] and new == 1:
size = kChat.FontSizeList[i + 1]
break
size = kChat.FontSizeList[i - 1]
break
self.SetFontSize(size)
self.SaveFontSize()
self.RefreshKISettings()
#~~~~~~~~#
# Fading #
#~~~~~~~~#
## Gets the current fading time from the Chronicle.
def DetermineFadeTime(self):
vault = ptVault()
entry = vault.findChronicleEntry(kChron.FadeTime)
if entry is None:
# Not found, add the current fade time to the Chronicle.
vault.addChronicleEntry(kChron.FadeTime, kChron.FadeTimeType, str(self.chatMgr.ticksOnFull))
else:
self.chatMgr.ticksOnFull = int(entry.chronicleGetValue())
if self.chatMgr.ticksOnFull == kChat.FadeTimeMax:
# Disable the fade altogether.
self.chatMgr.fadeEnableFlag = False
self.KillFadeTimer()
PtDebugPrint(u"xKI.DetermineFadeTime(): Fade time disabled.", level=kWarningLevel)
else:
self.chatMgr.fadeEnableFlag = True
PtDebugPrint(u"xKI.DetermineFadeTime(): The saved fade time is {}.".format(self.chatMgr.ticksOnFull), level=kWarningLevel)
## Saves the current fading time to the Chronicle.
def SaveFadeTime(self):
vault = ptVault()
entry = vault.findChronicleEntry(kChron.FadeTime)
if entry is not None:
entry.chronicleSetValue(str(self.chatMgr.ticksOnFull))
entry.save()
else:
vault.addChronicleEntry(kChron.FadeTime, kChron.FadeTimeType, str(self.chatMgr.ticksOnFull))
PtDebugPrint(u"xKI.SaveFadeTime(): Saving Fade Time of {}.".format(self.chatMgr.ticksOnFull), level=kWarningLevel)
## Start the fade timer.
# This gets called each time the user does something in relation to the
# chat to keep it alive.
def StartFadeTimer(self):
if not self.chatMgr.fadeEnableFlag:
return
if not BigKI.dialog.isEnabled():
if self.chatMgr.fadeMode in (kChat.FadeNotActive, kChat.FadeDone):
PtAtTimeCallback(self.key, kChat.FullTickTime, kTimers.Fade)
self.chatMgr.fadeMode = kChat.FadeFullDisp
self.currentFadeTick = self.chatMgr.ticksOnFull
## End the currently-active timer.
def KillFadeTimer(self):
if self.KILevel < kNormalKI:
mKIdialog = KIMicro.dialog
else:
mKIdialog = KIMini.dialog
# Optimization: only do this if we are fading or have faded
if self.chatMgr.fadeMode in (kChat.FadeDoingFade, kChat.FadeDone, kChat.FadeNotActive):
mKIdialog.setForeColor(-1, -1, -1, self.originalForeAlpha)
mKIdialog.setSelectColor(-1, -1, -1, self.originalSelectAlpha)
if self.KILevel == kNormalKI:
playerlist = ptGUIControlListBox(mKIdialog.getControlFromTag(kGUI.PlayerList))
playerlist.show()
chatArea = ptGUIControlMultiLineEdit(mKIdialog.getControlFromTag(kGUI.ChatDisplayArea))
chatArea.enableScrollControl()
mKIdialog.refreshAllControls()
# Toggle state
if self.chatMgr.fadeMode not in (kChat.FadeNotActive, kChat.FadeDone):
self.chatMgr.fadeMode = kChat.FadeStopping
self.currentFadeTick = self.chatMgr.ticksOnFull
def ResetFadeState(self, force=False):
"""This turns the chat fade OFF and resets it if the user is not chatting.
Use this instead of calling `KillFadeTimer()` and `StartFadeTimer()` to toggle the state.
Use `force` to disable checking of the chatting status (why would you do that?)
"""
# I'm cheating.
self.KillFadeTimer()
if not self.chatMgr.isChatting or force:
self.StartFadeTimer()
## Make the miniKI lists completely faded out.
def FadeCompletely(self):
if self.KILevel < kNormalKI:
mKIdialog = KIMicro.dialog
else:
mKIdialog = KIMini.dialog
# If the BigKI is enabled, make the chat opaque once more.
if BigKI.dialog.isEnabled():
mKIdialog.setForeColor(-1, -1, -1, self.originalForeAlpha)
mKIdialog.setSelectColor(-1, -1, -1, self.originalSelectAlpha)
mKIdialog.refreshAllControls()
# Otherwise, add full transparency and hide everything.
else:
mKIdialog.setForeColor(-1, -1, -1, 0)
mKIdialog.setSelectColor(-1, -1, -1, 0)
mKIdialog.refreshAllControls()
if self.KILevel == kNormalKI:
playerlist = ptGUIControlListBox(mKIdialog.getControlFromTag(kGUI.PlayerList))
playerlist.hide()
self.chatMgr.fadeMode = kChat.FadeDone
#~~~~~~#
# Ages #
#~~~~~~#
## Determines whether or not the player can invite visitors to an Age.
def CanAgeInviteVistors(self, ageInfo, link):
# Make sure it's not a special Age.
try:
for Age in kAges.NoInvite:
if Age == ageInfo.getAgeFilename():
return False
except AttributeError:
pass
# Make sure that the Age has not been deleted.
if link.getVolatile():
return False
# Make sure the player has a default link to this Age.
# If not, the Age has not yet been finished.
spawnPoints = link.getSpawnPoints()
for spawnlink in spawnPoints:
if spawnlink.getTitle() == "Default":
return True
return False
## Determines if the Age is the player's Neighborhood.
def IsAgeMyNeighborhood(self, ageInfo):
try:
hoodGUID = ptVault().getLinkToMyNeighborhood().getAgeInfo().getAgeInstanceGuid()
if not isinstance(hoodGUID, str) or not hoodGUID:
PtDebugPrint(u"xKI.IsAgeMyNeighborhood(): Neighborhood GUID not valid.", level=kWarningLevel)
# Can't trust this test, try a different one.
if ageInfo.getAgeFilename() == "Neighborhood":
return True
else:
if ageInfo.getAgeInstanceGuid() == hoodGUID:
return True
except AttributeError:
pass
return False
#~~~~~~~~~~~#
# Age Names #
#~~~~~~~~~~~#
## Returns the formatted and filtered name of an Age instance.
def GetAgeInstanceName(self, ageInfo=None):
if ageInfo is None:
ageInfo = PtGetAgeInfo()
if ageInfo is not None:
if ageInfo.getAgeInstanceName() == "D'ni-Rudenna":
sdl = xPsnlVaultSDL()
if sdl["TeledahnPoleState"][0] > 5 or sdl["KadishPoleState"][0] > 5 or sdl["GardenPoleState"][0] > 5 or sdl["GarrisonPoleState"][0] > 5:
pass
else:
return "Unknown"
if ageInfo.getAgeInstanceName() == "Ae'gura":
return "D'ni-Ae'gura"
return FilterAgeName(ageInfo.getAgeInstanceName())
else:
return "?UNKNOWN?"
## Returns the file name of the specified Age.
def GetAgeFileName(self, ageInfo=None):
if ageInfo is None:
ageInfo = PtGetAgeInfo()
if ageInfo is not None:
return ageInfo.getAgeFilename()
else:
return "?UNKNOWN?"
#~~~~~~~~#
# Limits #
#~~~~~~~~#
## Update the used-up space on the KI.
def UpdateKIUsage(self):
usage = ptVault().getKIUsage()
self.numberOfPictures = usage[0]
self.numberOfNotes = usage[1]
self.numberOfMarkerFolders = usage[2]
try:
self.numberOfMarkers = self.markerGameManager.marker_total
except:
self.numberOfMarkers = -1
## Check if the player has reached his limit of picture space.
def CanTakePicture(self):
self.UpdateKIUsage()
if kLimits.MaxPictures == -1 or self.numberOfPictures < kLimits.MaxPictures:
return True
return False
## Check if the player has reached his limit of journal notes space.
def CanMakeNote(self):
self.UpdateKIUsage()
if kLimits.MaxNotes == -1 or self.numberOfNotes < kLimits.MaxNotes:
return True
return False
## Check if the player has reached his limit of Marker Games.
def CanMakeMarkerGame(self):
self.UpdateKIUsage()
if kLimits.MaxMarkerFolders == -1 or self.numberOfMarkerFolders < kLimits.MaxMarkerFolders:
return True
return False
## Check if the player has reached his limit of markers for a Marker Game.
def CanMakeMarker(self):
self.UpdateKIUsage()
if kLimits.MaxMarkers == -1 or self.numberOfMarkers < kLimits.MaxMarkers:
return True
return False
#~~~~~~~~#
# Errors #
#~~~~~~~~#
## Displays a OK dialog-based error message to the player.
def ShowKIFullErrorMsg(self, msg):
self.YNWhatReason = kGUI.YNKIFull
reasonField = ptGUIControlTextBox(KIYesNo.dialog.getControlFromTag(kGUI.YesNoTextID))
reasonField.setStringW(msg)
yesButton = ptGUIControlButton(KIYesNo.dialog.getControlFromTag(kGUI.YesButtonID))
yesButton.hide()
yesBtnText = ptGUIControlTextBox(KIYesNo.dialog.getControlFromTag(kGUI.YesButtonTextID))
yesBtnText.hide()
noBtnText = ptGUIControlTextBox(KIYesNo.dialog.getControlFromTag(kGUI.NoButtonTextID))
noBtnText.setStringW(PtGetLocalizedString("KI.YesNoDialog.OKButton"))
KIYesNo.dialog.show()
## Display an error message in the SendTo field.
def SetSendToErrorMessage(self, message):
self.BKPlayerSelected = None
sendToField = ptGUIControlTextBox(BigKI.dialog.getControlFromTag(kGUI.BKIPlayerLine))
sendToField.setStringW(U"<" + unicode(message) + U">")
sendToButton = ptGUIControlButton(BigKI.dialog.getControlFromTag(kGUI.BKIToPlayerButton))
sendToButton.hide()
#~~~~~~~~~~~~~#
# Invitations #
#~~~~~~~~~~~~~#
## Invite another player to visit the player's Age.
def InviteToVisit(self, playerID, ageInfo):
whereToLink = ptAgeLinkStruct()
whereToLink.setAgeInfo(ageInfo.asAgeInfoStruct())
ptVault().invitePlayerToAge(whereToLink, playerID)
self.SendInviteRevoke(playerID, ageInfo.getDisplayName(), "KI.Invitation.VisitTitle", "KI.Invitation.VisitBody")
## Send an invitation or a revocation to another player.
def SendInviteRevoke(self, playerID, ageName, title, message):
localPlayer = PtGetLocalPlayer()
invite = ptVaultTextNoteNode(0)
invite.noteSetText(PtGetLocalizedString(message, [ageName, localPlayer.getPlayerName()]))
invite.noteSetTitle(PtGetLocalizedString(title, [ageName]))
invite.sendTo(playerID)
#~~~~~~~~~~~~~~~~~#
# New Item Alerts #
#~~~~~~~~~~~~~~~~~#
## Check the Inbox for unseen messages.
def CheckInboxForUnseen(self):
inFolder = ptVault().getInbox()
if inFolder is not None:
inRefList = inFolder.getChildNodeRefList()
for inRef in inRefList:
if not inRef.beenSeen():
self.AlertKIStart()
## Start the KI Alert if it's not already active.
def AlertKIStart(self):
if self.KILevel >= kNormalKI:
PtFlashWindow()
if not self.alertTimerActive:
PtDebugPrint(u"xKI.AlertKIStart(): Show KI alert.", level=kDebugDumpLevel)
NewItemAlert.dialog.show()
KIAlert = ptGUIControlButton(NewItemAlert.dialog.getControlFromTag(kAlertKIAlert))
self.alertTimeToUse = kAlertTimeDefault
KIAlert.show()
## Start the Book Alert if it's not already active.
def AlertBookStart(self, time=kAlertTimeDefault):
if not self.alertTimerActive:
PtDebugPrint(u"xKI.AlertBookStart(): Show Book Alert.", level=kDebugDumpLevel)
NewItemAlert.dialog.show()
bookAlert = ptGUIControlButton(NewItemAlert.dialog.getControlFromTag(kAlertBookAlert))
self.alertTimeToUse = time
bookAlert.show()
## Stop all alerts, by hiding their dialogs.
def AlertStop(self):
self.alertTimerActive = False
NewItemAlert.dialog.hide()
KIAlert = ptGUIControlButton(NewItemAlert.dialog.getControlFromTag(kAlertKIAlert))
KIAlert.hide()
bookAlert = ptGUIControlButton(NewItemAlert.dialog.getControlFromTag(kAlertBookAlert))
bookAlert.hide()
## Starts the alert timer if it's not already active.
def AlertStartTimer(self):
if not self.alertTimerActive:
self.alertTimerActive = True
PtAtTimeCallback(self.key, self.alertTimeToUse, kTimers.AlertHide)
#~~~~~~~~~~~~~#
# Player List #
#~~~~~~~~~~~~~#
## Tries to scroll up the list of players.
def ScrollPlayerList(self, direction):
if self.KILevel == kMicroKI:
return
elif self.KILevel == kMicroKI:
mKIdialog = KIMicro.dialog
else:
mKIdialog = KIMini.dialog
control = ptGUIControlListBox(KIMini.dialog.getControlFromTag(kGUI.PlayerList))
currPos = control.getScrollPos()
if direction == 1:
if currPos < control.getScrollRange():
PtDebugPrint(u"xKI.ScrollPlayerList(): Scrolling player list up from {} to {}.".format(currPos, currPos + 1), level=kDebugDumpLevel)
control.setScrollPos(currPos + 1)
else:
PtDebugPrint(u"xKI.ScrollPlayerList(): Not scrolling player list up from {}.".format(currPos), level=kDebugDumpLevel)
else:
if currPos > 0:
PtDebugPrint(u"xKI.ScrollPlayerList(): Scrolling player list down from {} to {}.".format(currPos, currPos - 1), level=kDebugDumpLevel)
control.setScrollPos(currPos - 1)
else:
PtDebugPrint(u"xKI.ScrollPlayerList(): Not scrolling player list down from {}.".format(currPos), level=kDebugDumpLevel)
self.CheckScrollButtons()
mKIdialog.refreshAllControls()
self.ResetFadeState()
## Checks to see if the player list scroll buttons should be visible.
def CheckScrollButtons(self):
if self.KILevel == kMicroKI:
return
elif self.KILevel == kMicroKI:
mKIdialog = KIMicro.dialog
else:
mKIdialog = KIMini.dialog
control = ptGUIControlListBox(KIMini.dialog.getControlFromTag(kGUI.PlayerList))
currentPos = control.getScrollPos()
PtDebugPrint(u"xKI.CheckScrollButtons(): Current position = {} and range = {}.".format(currentPos, control.getScrollRange()), level=kDebugDumpLevel)
try:
dbtn = ptGUIControlButton(mKIdialog.getControlFromTag(kGUI.miniPlayerListDown))
if currentPos == 0:
dbtn.hide()
else:
dbtn.show()
ubtn = ptGUIControlButton(mKIdialog.getControlFromTag(kGUI.miniPlayerListUp))
if currentPos >= control.getScrollRange():
ubtn.hide()
else:
ubtn.show()
except KeyError:
pass
## Reloads the player list with the latest values and displays them.
def RefreshPlayerList(self, forceSmall=False):
PtDebugPrint(u"xKI.RefreshPlayerList(): Refreshing.", level=kDebugDumpLevel)
playerlist = ptGUIControlListBox(KIMini.dialog.getControlFromTag(kGUI.PlayerList))
select = playerlist.getSelection()
if select >= 0 and select < len(self.BKPlayerList):
self.previouslySelectedPlayer = self.BKPlayerList[select]
# Vault node refs change frequently, so get the unique ID instead.
if isinstance(self.previouslySelectedPlayer, ptVaultNodeRef):
PtDebugPrint(u"xKI.RefreshPlayerList(): Getting the vault node ID of the selected player.", level=kDebugDumpLevel)
self.previouslySelectedPlayer = self.previouslySelectedPlayer.getChild().getID()
else:
self.previouslySelectedPlayer = None
self.BKPlayerList = []
vault = ptVault()
# Age Players
ageMembers = KIFolder(PtVaultStandardNodes.kAgeMembersFolder)
if ageMembers is not None:
self.BKPlayerList.append(ageMembers)
self.BKPlayerList += PtGetPlayerListDistanceSorted()
else:
self.BKPlayerList.append("?NOAgeMembers?")
# Buddies List
buddies = vault.getBuddyListFolder()
if buddies is not None:
self.BKPlayerList.append(buddies)
self.BKPlayerList += self.RemoveOfflinePlayers(buddies.getChildNodeRefList())
else:
self.BKPlayerList.append("?NOBuddies?")
# Neighbors List
neighbors = GetNeighbors()
if neighbors is not None:
self.BKPlayerList.append(neighbors)
onlinePlayers = self.RemoveOfflinePlayers(neighbors.getChildNodeRefList())
FilterPlayerInfoList(onlinePlayers)
self.BKPlayerList += onlinePlayers
else:
self.BKPlayerList.append("NEIGHBORS")
# All Players (INTERNAL CLIENT ONLY)
if PtIsInternalRelease():
allPlayers = vault.getAllPlayersFolder()
if allPlayers:
self.BKPlayerList.append(allPlayers)
onlinePlayers = self.RemoveOfflinePlayers(allPlayers.getChildNodeRefList())
FilterPlayerInfoList(onlinePlayers)
self.BKPlayerList += onlinePlayers
# don't append a dummy -- we don't care if our vault doesn't have a copy of AllPlayers
# Age Devices
if self.folderOfDevices and BigKI.dialog.isEnabled() and not forceSmall:
self.BKPlayerList.append(self.folderOfDevices)
for device in self.folderOfDevices:
self.BKPlayerList.append(device)
# Pass the new value to the chat manager.
self.chatMgr.BKPlayerList = self.BKPlayerList
# Refresh the display.
self.RefreshPlayerListDisplay()
## Removes the offline players in a list of players.
def RemoveOfflinePlayers(self, playerlist):
onlineList = []
ignores = ptVault().getIgnoreListFolder()
for plyr in playerlist:
if isinstance(plyr, ptVaultNodeRef):
PLR = plyr.getChild()
PLR = PLR.upcastToPlayerInfoNode()
if PLR is not None and PLR.getType() == PtVaultNodeTypes.kPlayerInfoNode:
if PLR.playerIsOnline():
if not ignores.playerlistHasPlayer(PLR.playerGetID()):
onlineList.append(plyr)
return onlineList
## Refresh the display of the player list.
def RefreshPlayerListDisplay(self):
playerlist = ptGUIControlListBox(KIMini.dialog.getControlFromTag(kGUI.PlayerList))
scrollPos = playerlist.getScrollPos()
playerlist.lock()
playerlist.clearAllElements()
newSelection = -1 # Assume no selection.
idx = 0
for plyr in self.BKPlayerList:
if isinstance(plyr, DeviceFolder):
playerlist.closeBranch()
playerlist.addBranchW(plyr.name.upper(), 1)
elif isinstance(plyr, Device):
playerlist.addStringWithColor(plyr.name, kColors.DniSelectable, kSelectUseGUIColor)
elif isinstance(plyr, ptVaultNodeRef):
PLR = plyr.getChild()
PLR = PLR.upcastToPlayerInfoNode()
if PLR is not None and PLR.getType() == PtVaultNodeTypes.kPlayerInfoNode:
if PLR.playerIsOnline():
playerlist.addStringWithColor(PLR.playerGetName(), kColors.DniSelectable, kSelectUseGUIColor)
else:
playerlist.addStringWithColor(PLR.playerGetName(), kColors.AgenBlueDk,kSelectDetermined)
else:
PtDebugPrint(u"xKI.RefreshPlayerListDisplay(): Unknown player element type {}.".format(PLR.getType()), level=kErrorLevel)
elif isinstance(plyr, ptPlayer):
preText = " "
postText = " "
if plyr.getPlayerID() != 0:
if plyr.getDistanceSq() < PtMaxListenDistSq():
preText = ">"
postText = "<"
if plyr.getPlayerName() != "":
playerlist.addStringWithColor(preText + plyr.getPlayerName() + postText, kColors.DniSelectable, kSelectUseGUIColor)
else:
if plyr.getPlayerID() != 0:
playerlist.addStringWithColor(preText + "[ID:{:08d}]".format(plyr.getPlayerID()) + postText, kColors.DniSelectable, kSelectDetermined)
else:
playerlist.addStringWithColor(preText + "?unknown user?" + postText, kColors.DniSelectable, kSelectDetermined)
elif isinstance(plyr, KIFolder):
playerlist.closeBranch()
playerlist.addBranchW(plyr.name.upper(), 1)
elif isinstance(plyr, ptVaultPlayerInfoListNode):
# It's a player list, display its name.
fldrType = plyr.folderGetType()
if fldrType == PtVaultStandardNodes.kAgeOwnersFolder:
fldrType = PtVaultStandardNodes.kHoodMembersFolder
playerlist.closeBranch()
playerlist.addBranchW(xLocTools.FolderIDToFolderName(fldrType).upper(), 1)
elif isinstance(plyr, ptVaultMarkerGameNode):
# its a marker list, display its name
playerlist.closeBranch()
playerlist.addBranchW(plyr.folderGetName(), 1)
elif isinstance(plyr, str):
playerlist.closeBranch()
playerlist.addBranchW(plyr, 1)
else:
PtDebugPrint(u"xKI.RefreshPlayerListDisplay(): Unknown list type ", plyr, level=kErrorLevel)
# Is it the selected player?
if self.previouslySelectedPlayer is not None:
PtDebugPrint(u"xKI.RefreshPlayerListDisplay(): A previously selected player.", self.previouslySelectedPlayer, level=kDebugDumpLevel)
# Fix for vaultNodeRef comparisons (which no longer work).
if isinstance(self.previouslySelectedPlayer, long) and isinstance(plyr, ptVaultNodeRef):
plyr = plyr.getChild().getID() # Set to the ID; let the testing begin.
# Was it the same class?
if self.previouslySelectedPlayer.__class__ == plyr.__class__:
PtDebugPrint(u"xKI.RefreshPlayerListDisplay(): Previous player matches class.", level=kDebugDumpLevel)
# And finally, was it the same object?
if self.previouslySelectedPlayer == plyr:
PtDebugPrint(u"xKI.RefreshPlayerListDisplay(): Previous player matches object, setting to {}.".format(idx), level=kDebugDumpLevel)
newSelection = idx
# Found him, stop looking.
self.previouslySelectedPlayer = None
else:
PtDebugPrint(u"xKI.RefreshPlayerListDisplay(): Previous player does not match object.", level=kDebugDumpLevel)
else:
PtDebugPrint(u"xKI.RefreshPlayerListDisplay(): Previous player does not match class.", level=kDebugDumpLevel)
idx += 1
# Is there no selection?
if newSelection == -1:
# Select the first item in the list.
newSelection = 0
# Put the caret back to the regular prompt.
caret = ptGUIControlTextBox(KIMini.dialog.getControlFromTag(kGUI.ChatCaretID))
caret.setString(">")
PtDebugPrint(u"xKI.RefreshPlayerListDisplay(): Setting new selection to {}.".format(newSelection), level=kDebugDumpLevel)
playerlist.setSelection(newSelection)
self.previouslySelectedPlayer = None
# Re-establish the selection the player had before.
playerlist.setScrollPos(scrollPos)
playerlist.unlock()
self.CheckScrollButtons()
# Set the SendTo button.
sendToButton = ptGUIControlButton(BigKI.dialog.getControlFromTag(kGUI.BKIToPlayerButton))
if self.BKPlayerSelected is None:
sendToButton.hide()
else:
# Make sure that the person is still here (this shouldn't happen).
if isinstance(self.BKPlayerSelected, DeviceFolder):
self.BKPlayerSelected = None
sendToField = ptGUIControlTextBox(BigKI.dialog.getControlFromTag(kGUI.BKIPlayerLine))
sendToField.setString(" ")
sendToButton.hide()
# Otherwise see if the device is still in range.
elif isinstance(self.BKPlayerSelected, Device):
try:
self.folderOfDevices.index(self.BKPlayerSelected)
except ValueError:
# No longer in the list of devices; remove it.
self.BKPlayerSelected = None
sendToField = ptGUIControlTextBox(BigKI.dialog.getControlFromTag(kGUI.BKIPlayerLine))
sendToField.setString(" ")
sendToButton.hide()
#~~~~~~~~~~#
# Settings #
#~~~~~~~~~~#
## Refresh the KI configuration settings to match the current values.
def RefreshKISettings(self):
fontSizeSlider = ptGUIControlKnob(KISettings.dialog.getControlFromTag(kGUI.BKIKIFontSize))
fontSize = self.GetFontSize()
# Find font size in font table.
whichFont = 0
for fs in kChat.FontSizeList:
if fontSize <= fs:
break
whichFont += 1
if whichFont >= len(kChat.FontSizeList):
whichFont = len(kChat.FontSizeList) - 1
slidePerFont = float(fontSizeSlider.getMax() - fontSizeSlider.getMin() + 1.0) / float(len(kChat.FontSizeList))
FSslider = int(slidePerFont * whichFont + 0.25)
fontSizeSlider.setValue(FSslider)
fadeTimeSlider = ptGUIControlKnob(KISettings.dialog.getControlFromTag(kGUI.BKIKIFadeTime))
slidePerTime = float(fadeTimeSlider.getMax() - fadeTimeSlider.getMin()) / float(kChat.FadeTimeMax)
if not self.chatMgr.fadeEnableFlag:
self.chatMgr.ticksOnFull = kChat.FadeTimeMax
FTslider = slidePerTime * self.chatMgr.ticksOnFull
fadeTimeSlider.setValue(FTslider)
onlyPMCheckbox = ptGUIControlCheckBox(KISettings.dialog.getControlFromTag(kGUI.BKIKIOnlyPM))
onlyPMCheckbox.setChecked(self.onlyGetPMsFromBuddies)
## Refresh the volume settings to match the current values.
def RefreshVolumeSettings(self):
audio = ptAudioControl()
soundFX = ptGUIControlValue(KIVolumeExpanded.dialog.getControlFromTag(kGUI.BKISoundFXVolSlider))
setting = audio.getSoundFXVolume()
soundFX.setValue(setting * 10)
music = ptGUIControlValue(KIVolumeExpanded.dialog.getControlFromTag(kGUI.BKIMusicVolSlider))
setting = audio.getMusicVolume()
music.setValue(setting * 10)
voice = ptGUIControlValue(KIVolumeExpanded.dialog.getControlFromTag(kGUI.BKIVoiceVolSlider))
setting = audio.getVoiceVolume()
voice.setValue(setting * 10)
ambience = ptGUIControlValue(KIVolumeExpanded.dialog.getControlFromTag(kGUI.BKIAmbienceVolSlider))
setting = audio.getAmbienceVolume()
ambience.setValue(setting * 10)
miclevel = ptGUIControlValue(KIVolumeExpanded.dialog.getControlFromTag(kGUI.BKIMicLevelSlider))
setting = audio.getMicLevel()
miclevel.setValue(setting * 10)
guivolume = ptGUIControlValue(KIVolumeExpanded.dialog.getControlFromTag(kGUI.BKIGUIVolSlider))
setting = audio.getGUIVolume()
guivolume.setValue(setting * 10)
## Refresh the Age Owner settings to match the current values.
def RefreshAgeOwnerSettings(self):
# Is it actually going to display, or is it just an update?
if BigKI.dialog.isEnabled() and self.BKRightSideMode == kGUI.BKAgeOwnerExpanded:
try:
# Get the selected Age config setting.
myAge = self.BKConfigFolderDict[self.BKConfigListOrder[self.BKFolderSelected]]
except LookupError:
myAge = None
if myAge is not None:
title = ptGUIControlTextBox(KIAgeOwnerExpanded.dialog.getControlFromTag(kGUI.BKAgeOwnerTitleTB))
title.setString(GetAgeName(myAge))
titlebtn = ptGUIControlButton(KIAgeOwnerExpanded.dialog.getControlFromTag(kGUI.BKAgeOwnerTitleBtn))
titlebtn.enable()
titleEdit = ptGUIControlEditBox(KIAgeOwnerExpanded.dialog.getControlFromTag(kGUI.BKAgeOwnerTitleEditbox))
titleEdit.hide()
status = ptGUIControlTextBox(KIAgeOwnerExpanded.dialog.getControlFromTag(kGUI.BKAgeOwnerStatusTB))
visitors = myAge.getCanVisitFolder()
owners = myAge.getAgeOwnersFolder()
numvisitors = visitors.getChildNodeCount()
numowners = owners.getChildNodeCount()
vsess = "s"
if numvisitors == 1:
vsess = ""
osess = "s"
if numowners == 1:
osess = ""
# For now, Ages can be made public/private only through the Nexus.
makepublicTB = ptGUIControlTextBox(KIAgeOwnerExpanded.dialog.getControlFromTag(kGUI.BKAgeOwnerMakePublicTB))
makepublicBtn = ptGUIControlButton(KIAgeOwnerExpanded.dialog.getControlFromTag(kGUI.BKAgeOwnerMakePublicBtn))
makepublicBtn.disable()
makepublicTB.hide()
makepublicTB.setString(" ")
status.setStringW(PtGetLocalizedString("KI.Neighborhood.AgeOwnedStatus", [str(numowners), str(osess), str(numvisitors), str(vsess)]))
descript = ptGUIControlMultiLineEdit(KIAgeOwnerExpanded.dialog.getControlFromTag(kGUI.BKAgeOwnerDescription))
encoded = buffer(myAge.getAgeDescription())
descript.setEncodedBuffer(encoded)
#~~~~~~~~#
# miniKI #
#~~~~~~~~#
## Refresh the display of the miniKI indicator bars.
def RefreshMiniKIMarkerDisplay(self):
PtDebugPrint(u"xKI.RefreshMiniKIMarkerDisplay(): Refreshing {}:{}.".format(self.gMarkerGottenNumber, self.gMarkerToGetNumber), level=kDebugDumpLevel)
if self.KILevel > kMicroKI:
if self.gMarkerGottenNumber == self.gMarkerToGetNumber and (self.gMarkerToGetNumber % 25) == 0:
xMyMaxMarkers = self.gMarkerToGetNumber
xMyGotMarkers = self.gMarkerGottenNumber
else:
xMyGotMarkers = self.gMarkerGottenNumber % 25
if self.gMarkerGottenNumber >= math.floor((self.gMarkerToGetNumber / 25)) * 25:
xMyMaxMarkers = self.gMarkerToGetNumber % 25
else:
xMyMaxMarkers = 25
for mcbID in range(kGUI.miniMarkerIndicator01, kGUI.miniMarkerIndicatorLast + 1):
mcb = ptGUIControlProgress(KIMini.dialog.getControlFromTag(mcbID))
markerNumber = mcbID - kGUI.miniMarkerIndicator01 + 1
try:
if not self.gKIMarkerLevel or markerNumber > xMyMaxMarkers:
mcb.setValue(kGUI.miniMarkerColors["off"])
elif markerNumber <= xMyMaxMarkers and markerNumber > xMyGotMarkers:
mcb.setValue(kGUI.miniMarkerColors[self.gMarkerToGetColor])
else:
mcb.setValue(kGUI.miniMarkerColors[self.gMarkerGottenColor])
except LookupError:
PtDebugPrint(u"xKI.RefreshMiniKIMarkerDisplay(): Couldn't find color, defaulting to off.", level=kWarningLevel)
mcb.setValue(kGUI.miniMarkerColors["off"])
btnmtDrip = ptGUIControlButton(KIMini.dialog.getControlFromTag(kGUI.miniGZDrip))
btnmtActive = ptGUIControlButton(KIMini.dialog.getControlFromTag(kGUI.miniGZActive))
btnmtPlaying = ptGUIControlButton(KIMini.dialog.getControlFromTag(kGUI.miniGZMarkerGameActive))
btnmtInRange = ptGUIControlButton(KIMini.dialog.getControlFromTag(kGUI.miniGZMarkerInRange))
btnmgNewMarker = ptGUIControlButton(KIMini.dialog.getControlFromTag(kGUI.miniMGNewMarker))
btnmgNewGame = ptGUIControlButton(KIMini.dialog.getControlFromTag(kGUI.miniMGNewGame))
btnmgInactive = ptGUIControlButton(KIMini.dialog.getControlFromTag(kGUI.miniMGInactive))
if self.gKIMarkerLevel:
btnmtDrip.hide()
if self.gMarkerToGetNumber > self.gMarkerGottenNumber:
if self.gGZMarkerInRange:
btnmtInRange.show()
btnmtPlaying.hide()
btnmtActive.hide()
else:
btnmtInRange.hide()
btnmtPlaying.show()
btnmtActive.hide()
else:
btnmtPlaying.hide()
btnmtInRange.hide()
btnmtActive.show()
else:
btnmtDrip.hide()
btnmtActive.hide()
btnmtPlaying.hide()
btnmtInRange.hide()
# Should the Marker Game GUI be displayed?
if self.gKIMarkerLevel >= kKIMarkerNormalLevel and not self.markerGameManager.is_cgz:
btnmtDrip.hide()
btnmtActive.hide()
btnmtPlaying.hide()
btnmtInRange.hide()
try:
showMarkers = self.markerGameManager.markers_visible
except:
showMarkers = False
try:
selectedMarker = self.markerGameManager.selected_marker_id
except :
selectedMarker = -1
if self.markerGameManager.playing:
btnmgNewMarker.hide()
btnmgNewGame.hide()
btnmgInactive.show()
elif showMarkers and selectedMarker < 0:
btnmgNewMarker.show()
btnmgNewGame.hide()
btnmgInactive.hide()
else:
btnmgNewMarker.hide()
btnmgNewGame.show()
btnmgInactive.hide()
else:
btnmgNewMarker.hide()
btnmgNewGame.hide()
btnmgInactive.hide()
## Toggle between the miniKI and the BigKI.
def ToggleKISize(self):
if self.KILevel > kMicroKI and (not self.KIDisabled or BigKI.dialog.isEnabled()):
if self.KIDisabled and BigKI.dialog.isEnabled():
self.ToggleMiniKI()
return
if not self.waitingForAnimation:
toggleCB = ptGUIControlCheckBox(KIMini.dialog.getControlFromTag(kGUI.miniToggleBtnID))
if BigKI.dialog.isEnabled():
self.HideBigKI()
# Can't be chatting.
self.chatMgr.ToggleChatMode(0)
KIBlackbar.dialog.show()
if self.lastminiKICenter is not None:
dragbar = ptGUIControlDragBar(KIMini.dialog.getControlFromTag(kGUI.miniDragBar))
dragbar.setObjectCenter(self.lastminiKICenter)
dragbar.unanchor()
self.lastminiKICenter = None
# Refresh the player list, because it will be the shorter version.
self.RefreshPlayerList(True)
toggleCB.setChecked(0)
else:
# If there is nothing showing, just bring up the miniKI.
if not KIMini.dialog.isEnabled():
self.chatMgr.ClearBBMini(0)
# Bring up the BigKI, then the miniKI.
else:
self.waitingForAnimation = True
KIBlackbar.dialog.hide()
KIMini.dialog.hide()
# Can't be chatting.
self.chatMgr.ToggleChatMode(0)
# Show the BigKI.
BigKI.dialog.show()
# Save current location and snap back to original.
if self.originalminiKICenter is not None:
dragbar = ptGUIControlDragBar(KIMini.dialog.getControlFromTag(kGUI.miniDragBar))
self.lastminiKICenter = dragbar.getObjectCenter()
PtDebugPrint(u"xKI.ToggleKISize(): Distance to original = {}.".format(self.lastminiKICenter.distance(self.originalminiKICenter)), level=kDebugDumpLevel)
# If they are close, then snap it to original.
if self.lastminiKICenter.distance(self.originalminiKICenter) < 0.027:
self.lastminiKICenter = self.originalminiKICenter
dragbar.setObjectCenter(self.originalminiKICenter)
dragbar.anchor()
KIMini.dialog.show()
toggleCB.setChecked(1)
## Put away the miniKI (and the BigKI, if up).
def ToggleMiniKI(self, forceOpen = 0):
if self.KILevel > kMicroKI and (not self.KIDisabled or KIMini.dialog.isEnabled()):
if KIMini.dialog.isEnabled():
KIMini.dialog.hide()
# Put the miniKI back where it used to be.
if self.lastminiKICenter is not None:
dragbar = ptGUIControlDragBar(KIMini.dialog.getControlFromTag(kGUI.miniDragBar))
dragbar.setObjectCenter(self.lastminiKICenter)
dragbar.unanchor()
self.lastminiKICenter = None
if BigKI.dialog.isEnabled():
self.HideBigKI()
KIBlackbar.dialog.show()
self.chatMgr.ClearBBMini(-1)
# Put the toggle button back to the miniKI setting.
toggleCB = ptGUIControlCheckBox(KIMini.dialog.getControlFromTag(kGUI.miniToggleBtnID))
toggleCB.setChecked(0)
self.sawTheKIAtleastOnce = True
else:
# If the miniKI is hidden, show it.
if forceOpen:
self.chatMgr.ClearBBMini(0)
## Take a screenshot through the miniKI.
def TakePicture(self):
if not self.takingAPicture and not self.waitingForAnimation:
# Ignoring the KIDisabled flag here, because screenshots can be
# taken even with certain GUIs showing.
if self.KILevel > kMicroKI:
if self.CanTakePicture():
self.takingAPicture = True
if not PtIsGUIModal():
# Hide everything to take a picture.
KIBlackbar.dialog.hide()
KIMini.dialog.hide()
self.HideBigKIMode()
BigKI.dialog.hide()
# Put the toggle button back to BigKI.
toggleCB = ptGUIControlCheckBox(KIMini.dialog.getControlFromTag(kGUI.miniToggleBtnID))
toggleCB.setChecked(1)
# Wait a moment, then take the picture.
PtAtTimeCallback(self.key, 0.25, kTimers.TakeSnapShot)
else:
# Put up an error message.
self.ShowKIFullErrorMsg(PtGetLocalizedString("KI.Messages.FullImages"))
## Create a new Journal entry through the miniKI.
def MiniKICreateJournalNote(self):
if self.takingAPicture or self.waitingForAnimation:
return
if self.KILevel > kMicroKI and not self.KIDisabled:
if self.CanMakeNote():
KIBlackbar.dialog.hide()
# Put the toggle button back to BigKI.
toggleCB = ptGUIControlCheckBox(KIMini.dialog.getControlFromTag(kGUI.miniToggleBtnID))
toggleCB.setChecked(1)
# Create the actual journal entry.
self.BigKICreateJournalNote()
# Make sure that the player is in Journal mode.
modeselector = ptGUIControlRadioGroup(BigKI.dialog.getControlFromTag(kGUI.BKRadioModeID))
modeselector.setValue(0)
# Set things up so that when the BigKI shows, it goes into edit mode.
if self.BKRightSideMode != kGUI.BKJournalExpanded:
self.HideBigKIMode()
self.BKRightSideMode = kGUI.BKJournalExpanded
# Reset the top line and selection.
self.BigKIRefreshFolderDisplay()
self.BigKIDisplayJournalEntry()
# Setup to edit the caption of the note.
self.BigKIEnterEditMode(kGUI.BKEditFieldJRNTitle)
if BigKI.dialog.isEnabled():
self.ShowBigKIMode()
else:
# Put the miniKI on top.
KIMini.dialog.hide()
BigKI.dialog.show()
KIMini.dialog.show()
# Was just the miniKI showing?
if self.lastminiKICenter is None:
if self.originalminiKICenter is not None:
dragbar = ptGUIControlDragBar(KIMini.dialog.getControlFromTag(kGUI.miniDragBar))
self.lastminiKICenter = dragbar.getObjectCenter()
dragbar.setObjectCenter(self.originalminiKICenter)
dragbar.anchor()
else:
# Put up an error message.
self.ShowKIFullErrorMsg(PtGetLocalizedString("KI.Messages.FullNotes"))
#~~~~~~~#
# BigKI #
#~~~~~~~#
## Open up and show the BigKI.
def ShowBigKI(self):
self.waitingForAnimation = True
curBrainMode = PtGetLocalAvatar().avatar.getCurrentMode()
toggleCB = ptGUIControlCheckBox(KIMini.dialog.getControlFromTag(kGUI.miniToggleBtnID))
toggleCB.disable()
if curBrainMode == PtBrainModes.kNonGeneric:
PtDebugPrint(u"xKI.ShowBigKI(): Entering LookingAtKI mode.", level=kDebugDumpLevel)
PtAvatarEnterLookingAtKI()
self.isPlayingLookingAtKIMode = True
PtDisableMovementKeys()
KIOnResp.run(self.key, netPropagate=0)
## Close and hide the BigKI.
def HideBigKI(self):
self.waitingForAnimation = True
toggleCB = ptGUIControlCheckBox(KIMini.dialog.getControlFromTag(kGUI.miniToggleBtnID))
toggleCB.disable()
self.HideBigKIMode()
# Make sure the player was actually looking at the KI.
if self.isPlayingLookingAtKIMode:
PtDebugPrint(u"xKI.HideBigKI(): Leaving LookingAtKI mode.", level=kDebugDumpLevel)
PtAvatarExitLookingAtKI()
self.isPlayingLookingAtKIMode = False
PtEnableMovementKeys()
KIOffResp.run(self.key, netPropagate=0)
## Show a new mode inside the BigKI.
# This can be an expanded picture, a player entry, a list...
def ShowBigKIMode(self):
if BigKI.dialog.isEnabled():
# Hide up/down scroll buttons.
upbtn = ptGUIControlButton(BigKI.dialog.getControlFromTag(kGUI.BKLMUpButton))
upbtn.hide()
dwnbtn = ptGUIControlButton(BigKI.dialog.getControlFromTag(kGUI.BKLMDownButton))
dwnbtn.hide()
if self.BKRightSideMode == kGUI.BKListMode:
KIListModeDialog.dialog.show()
self.BigKIOnlySelectedToButtons()
self.BKCurrentContent = None
self.BKGettingPlayerID = False
elif self.BKRightSideMode == kGUI.BKJournalExpanded:
KIJournalExpanded.dialog.show()
if self.IsContentMutable(self.BKCurrentContent):
self.BigKIInvertToFolderButtons()
else:
self.BigKIOnlySelectedToButtons()
self.BKGettingPlayerID = False
elif self.BKRightSideMode == kGUI.BKPictureExpanded:
KIPictureExpanded.dialog.show()
if self.IsContentMutable(self.BKCurrentContent):
self.BigKIInvertToFolderButtons()
else:
self.BigKIOnlySelectedToButtons()
self.BKGettingPlayerID = False
elif self.BKRightSideMode == kGUI.BKPlayerExpanded:
KIPlayerExpanded.dialog.show()
# If the expanded player is ourselves, then no move buttons.
localPlayer = PtGetLocalPlayer()
if self.BKCurrentContent is not None:
if isinstance(self.BKCurrentContent, ptPlayer):
if self.BKCurrentContent.getPlayerID() == localPlayer.getPlayerID():
self.BigKIOnlySelectedToButtons()
return
# Otherwise assume that it's a plVaultNodeRef.
else:
elem = self.BKCurrentContent.getChild()
if elem.getType() == PtVaultNodeTypes.kPlayerInfoNode:
elem = elem.upcastToPlayerInfoNode()
if elem.playerGetID() == localPlayer.getPlayerID():
self.BigKIOnlySelectedToButtons()
return
self.BigKIInvertToFolderButtons()
elif self.BKRightSideMode == kGUI.BKVolumeExpanded:
KIVolumeExpanded.dialog.show()
self.BigKIOnlySelectedToButtons()
self.BKCurrentContent = None
self.BKGettingPlayerID = False
elif self.BKRightSideMode == kGUI.BKKIExpanded:
KISettings.dialog.show()
self.BigKIOnlySelectedToButtons()
self.BKCurrentContent = None
self.BKGettingPlayerID = False
elif self.BKRightSideMode == kGUI.BKAgeOwnerExpanded:
KIAgeOwnerExpanded.dialog.show()
self.BigKIOnlySelectedToButtons()
self.BKCurrentContent = None
self.BKGettingPlayerID = False
elif self.BKRightSideMode == kGUI.BKMarkerListExpanded:
KIMarkerFolderExpanded.dialog.show()
if self.IsContentMutable(self.BKCurrentContent):
self.BigKIInvertToFolderButtons()
else:
self.BigKIOnlySelectedToButtons()
self.BKGettingPlayerID = False
## Hide an open mode in the BigKI.
def HideBigKIMode(self):
if self.BKRightSideMode == kGUI.BKListMode:
KIListModeDialog.dialog.hide()
elif self.BKRightSideMode == kGUI.BKJournalExpanded:
KIJournalExpanded.dialog.hide()
elif self.BKRightSideMode == kGUI.BKPictureExpanded:
KIPictureExpanded.dialog.hide()
elif self.BKRightSideMode == kGUI.BKPlayerExpanded:
KIPlayerExpanded.dialog.hide()
elif self.BKRightSideMode == kGUI.BKVolumeExpanded:
KIVolumeExpanded.dialog.hide()
elif self.BKRightSideMode == kGUI.BKKIExpanded:
KISettings.dialog.hide()
elif self.BKRightSideMode == kGUI.BKAgeOwnerExpanded:
KIAgeOwnerExpanded.dialog.hide()
elif self.BKRightSideMode == kGUI.BKMarkerListExpanded:
KIMarkerFolderExpanded.dialog.hide()
## Switch to a new mode in the BigKI.
# This hides the old mode and displays the new one, or just refreshes
# the content list if it's a selection change.
def ChangeBigKIMode(self, newMode):
# Is the player switching to a new mode?
if newMode != self.BKRightSideMode:
self.HideBigKIMode()
self.BKRightSideMode = newMode
self.ShowBigKIMode()
# Or is he changing the selection?
elif newMode == kGUI.BKListMode:
self.BigKIOnlySelectedToButtons()
## Set the SendTo buttons appropriately.
# This will set all the little glowing arrows next to items in accordance
# with the currently displayed mode.
def SetBigKIToButtons(self):
if self.BKRightSideMode == kGUI.BKListMode:
self.BigKIOnlySelectedToButtons()
elif self.BKRightSideMode == kGUI.BKJournalExpanded:
if self.IsContentMutable(self.BKCurrentContent):
self.BigKIInvertToFolderButtons()
else:
self.BigKIOnlySelectedToButtons()
elif self.BKRightSideMode == kGUI.BKPictureExpanded:
if self.IsContentMutable(self.BKCurrentContent):
self.BigKIInvertToFolderButtons()
else:
self.BigKIOnlySelectedToButtons()
elif self.BKRightSideMode == kGUI.BKPlayerExpanded:
localPlayer = PtGetLocalPlayer()
if self.BKCurrentContent is not None:
if isinstance(self.BKCurrentContent, ptPlayer):
if self.BKCurrentContent.getPlayerID() == localPlayer.getPlayerID():
self.BigKIOnlySelectedToButtons()
return
# Otherwise assume that it's a plVaultNodeRef.
else:
elem = self.BKCurrentContent.getChild()
if elem.getType() == PtVaultNodeTypes.kPlayerInfoNode:
elem = elem.upcastToPlayerInfoNode()
if elem.playerGetID() == localPlayer.getPlayerID():
self.BigKIOnlySelectedToButtons()
return
self.BigKIInvertToFolderButtons()
elif self.BKRightSideMode == kGUI.BKVolumeExpanded:
self.BigKIOnlySelectedToButtons()
elif self.BKRightSideMode == kGUI.BKKIExpanded:
self.BigKIOnlySelectedToButtons()
elif self.BKRightSideMode == kGUI.BKAgeOwnerExpanded:
self.BigKIOnlySelectedToButtons()
elif self.BKRightSideMode == kGUI.BKMarkerListExpanded:
if self.MFdialogMode not in (kGames.MFEditing, kGames.MFEditingMarker) and self.IsContentMutable(self.BKCurrentContent):
self.BigKIInvertToFolderButtons()
else:
self.BigKIOnlySelectedToButtons()
## Show only the selected SendTo buttons.
def BigKIOnlySelectedToButtons(self):
toPlayerBtn = ptGUIControlButton(BigKI.dialog.getControlFromTag(kGUI.BKIToPlayerButton))
toPlayerBtn.hide()
self.BigKIRefreshFolderDisplay()
# Hide all the buttons.
for ID in range(kGUI.BKIToIncomingButton, kGUI.BKIToFolderButtonLast + 1):
toFolder = ptGUIControlButton(BigKI.dialog.getControlFromTag(ID))
toFolder.hide()
self.BigKINewContentList()
## Determines if the selected content can be sent to someone.
def BigKICanShowSendToPlayer(self):
# Make sure that there is a selected player.
if self.BKPlayerSelected is None:
return False
# Make sure that it's something that can be sent to a player.
if self.BKRightSideMode == kGUI.BKPlayerExpanded or self.BKRightSideMode == kGUI.BKVolumeExpanded or self.BKRightSideMode == kGUI.BKAgeOwnerExpanded:
return False
# Make sure that it's not the player.
if isinstance(self.BKPlayerSelected, ptVaultNodeRef):
plyrElement = self.BKPlayerSelected.getChild()
if plyrElement is not None and plyrElement.getType() == PtVaultNodeTypes.kPlayerInfoNode:
plyrElement = plyrElement.upcastToPlayerInfoNode()
if plyrElement.playerGetID() == PtGetLocalClientID():
return False
return True
## Hides or shows the ToPlayer buttons.
def BigKIInvertToFolderButtons(self):
# Setup ToPlayer button.
toPlayerBtn = ptGUIControlButton(BigKI.dialog.getControlFromTag(kGUI.BKIToPlayerButton))
if self.BigKICanShowSendToPlayer():
toPlayerBtn.show()
else:
toPlayerBtn.hide()
# Add the ToPlayer button to the elements.
selectedButton = self.BKFolderSelected - self.BKFolderTopLine + kGUI.BKIToIncomingButton
for ID in range(kGUI.BKIToIncomingButton, kGUI.BKIToFolderButtonLast + 1):
toFolder = ptGUIControlButton(BigKI.dialog.getControlFromTag(ID))
if ID == selectedButton:
toFolder.hide()
else:
# Don't show on elements that are not there or immutable.
if ID - kGUI.BKIToIncomingButton <= len(self.BKFolderListOrder) - 1 - self.BKFolderTopLine:
try:
if self.IsFolderContentMutable(self.BKFolderLineDict[self.BKFolderListOrder[ID - kGUI.BKIToIncomingButton + self.BKFolderTopLine]]):
toFolder.show()
else:
toFolder.hide()
except LookupError:
toFolder.hide()
else:
toFolder.hide()
## Check incoming content for the sender, and set the SendTo field.
def CheckContentForSender(self, content):
folder = content.getParent()
if folder:
folder = folder.upcastToFolderNode()
if folder is not None and folder.folderGetType() == PtVaultStandardNodes.kInboxFolder:
sender = content.getSaver()
if sender is not None and sender.getType() == PtVaultNodeTypes.kPlayerInfoNode:
sendToField = ptGUIControlTextBox(BigKI.dialog.getControlFromTag(kGUI.BKIPlayerLine))
curSendTo = sendToField.getString().strip()
if not curSendTo:
self.BKPlayerSelected = sender
sendToField.setString(sender.playerGetName())
#~~~~~~~~~~~~~~~#
# BigKI Content #
#~~~~~~~~~~~~~~~#
## Determines whether the specified folder can be modified.
def IsFolderContentMutable(self, folder):
# Make sure there is a real folder there to play with.
if folder is None or not isinstance(folder, ptVaultNode):
return False
# If it's not really a folder but an AgeInfoNode, then it's for the canVisit player list.
if folder.getType() == PtVaultNodeTypes.kAgeInfoNode:
return True
if folder.getType() != PtVaultNodeTypes.kPlayerInfoListNode and folder.getType() != PtVaultNodeTypes.kFolderNode:
return False
# Check for the incoming folder.
if folder.folderGetType() == PtVaultStandardNodes.kInboxFolder:
return False
# Check against the AgeMembers folder.
if folder.folderGetType() == PtVaultStandardNodes.kAgeMembersFolder:
return False
# Check for the neighborhood members folder.
if folder.folderGetType() == PtVaultStandardNodes.kHoodMembersFolder:
return False
# Oh hayll no, you can't change AllPlayers
if folder.folderGetType() == PtVaultStandardNodes.kAllPlayersFolder:
return False
# Check for neighborhood CanVisit folder (actually half-mutable, they can delete).
if folder.folderGetType() == PtVaultStandardNodes.kAgeOwnersFolder:
return False
# It's not a special folder, so it's mutable.
return True
## Determines whether this is a hidden folder.
def IsFolderHidden(self, ageFolder):
if ageFolder.folderGetName() == "Hidden":
return True
return False
## Determines whether the content Node Reference is mutable.
def IsContentMutable(self, nodeRef):
# Get its parent folder.
if isinstance(nodeRef, ptVaultNodeRef):
folder = self.BKCurrentContent.getParent()
if folder:
folder = folder.upcastToFolderNode()
if folder:
if folder.folderGetType() == PtVaultStandardNodes.kGlobalInboxFolder:
return False
return True
#~~~~~~~~~~~~~~#
# BigKI Values #
#~~~~~~~~~~~~~~#
## Sets some global values for the KI should never change.
def BigKISetStatics(self):
ageText = ptGUIControlTextBox(BigKI.dialog.getControlFromTag(kGUI.BKICurAgeNameID))
ageName = GetAgeName().replace("(null)", "").strip()
PtDebugPrint(u"xKI.BigKISetStatics(): Displaying age name of {}.".format(ageName), level=kDebugDumpLevel)
ageText.setStringW(ageName)
playerText = ptGUIControlTextBox(BigKI.dialog.getControlFromTag(kGUI.BKPlayerName))
IDText = ptGUIControlTextBox(BigKI.dialog.getControlFromTag(kGUI.BKPlayerID))
localPlayer = PtGetLocalPlayer()
playerText.setString(localPlayer.getPlayerName())
IDText.setString("[ID:{:08d}]".format(localPlayer.getPlayerID()))
self.UpdatePelletScore()
self.BigKIRefreshHoodStatics()
## Sets some Neighborhood-specific values for the KI that won't change.
def BigKIRefreshHoodStatics(self, neighborhood=None):
neighborText = ptGUIControlTextBox(BigKI.dialog.getControlFromTag(kGUI.BKNeighborhoodAndID))
# If a neighborhood was not specified, get the one from the player's Vault.
if not neighborhood:
neighborhood = GetNeighborhood()
if neighborhood is not None:
neighborName = xLocTools.LocalizeAgeName(neighborhood.getDisplayName())
if neighborName == U"":
neighborName = PtGetLocalizedString("KI.Neighborhood.NoName")
neighborText.setStringW(PtGetLocalizedString("KI.Neighborhood.BottomLine", [xLocTools.MemberStatusString(), neighborName]))
else:
neighborText.setStringW(PtGetLocalizedString("KI.Neighborhood.None"))
## Sets some global changing values for the KI.
def BigKISetChanging(self):
# Use the D'ni time for this Age.
dniTime = PtGetDniTime()
if dniTime:
tupTime = time.gmtime(dniTime)
if self.timeBlinker:
curTime = unicode(time.strftime(PtGetLocalizedString("Global.Formats.DateTime"), tupTime))
self.timeBlinker = False
else:
curTime = unicode(time.strftime(PtGetLocalizedString("Global.Formats.DateTime"), tupTime))
self.timeBlinker = True
else:
curTime = PtGetLocalizedString("KI.Errors.TimeBroke")
if curTime != self.previousTime:
timeText = ptGUIControlTextBox(BigKI.dialog.getControlFromTag(kGUI.BKICurTimeID))
timeText.setStringW(curTime)
self.previousTime = curTime
# Set the D'ni GPS coordinates.
gps1 = ptGUIControlTextBox(BigKI.dialog.getControlFromTag(kGUI.BKIGPS1TextID))
gps2 = ptGUIControlTextBox(BigKI.dialog.getControlFromTag(kGUI.BKIGPS2TextID))
gps3 = ptGUIControlTextBox(BigKI.dialog.getControlFromTag(kGUI.BKIGPS3TextID))
self.dniCoords.update()
if self.gKIMarkerLevel == kKIMarkerNormalLevel:
sdl = xPsnlVaultSDL()
if sdl["GPSEnabled"][0]:
gps1.setString(str(self.dniCoords.getTorans()))
gps2.setString(str(self.dniCoords.getHSpans()))
gps3.setString(str(self.dniCoords.getVSpans()))
else:
gps1.setString("0")
gps2.setString("0")
gps3.setString("0")
else:
gps1.setString("0")
gps2.setString("0")
gps3.setString("0")
PtAtTimeCallback(self.key, 5, kTimers.BKITODCheck)
#~~~~~~~~~~~~~~~~~~#
# BigKI Refreshing #
#~~~~~~~~~~~~~~~~~~#
## Check to see if a folder needs to be refreshed.
def BigKICheckFolderRefresh(self, folder=None):
if folder is not None:
if folder.getType() == PtVaultNodeTypes.kPlayerInfoListNode:
self.RefreshPlayerList()
# Otherwise, check everything just in case.
else:
self.RefreshPlayerList()
# Check content refresh only if using the BigKI.
if self.KILevel > kMicroKI:
self.BigKIRefreshContentList()
self.BigKIRefreshContentListDisplay()
## Check to see if the current content has changed since.
def BigKICheckContentRefresh(self, content):
if self.BKCurrentContent is not None and content == self.BKCurrentContent:
if self.BKRightSideMode == kGUI.BKListMode:
self.BigKIRefreshContentListDisplay()
elif self.BKRightSideMode == kGUI.BKJournalExpanded:
self.BigKIDisplayJournalEntry()
elif self.BKRightSideMode == kGUI.BKPictureExpanded:
self.BigKIDisplayPicture()
elif self.BKRightSideMode == kGUI.BKPlayerExpanded:
self.BigKIDisplayPlayerEntry()
elif self.BKRightSideMode == kGUI.BKMarkerListExpanded:
self.BigKIDisplayMarkerGame()
## Check to see if the current content element has changed since.
def BigKICheckElementRefresh(self, element):
if self.BKCurrentContent is not None:
if isinstance(self.BKCurrentContent,ptVaultNodeRef) and element == self.BKCurrentContent.getChild():
if self.BKRightSideMode == kGUI.BKListMode:
self.BigKIRefreshContentListDisplay()
elif self.BKRightSideMode == kGUI.BKJournalExpanded:
self.BigKIDisplayJournalEntry()
elif self.BKRightSideMode == kGUI.BKPictureExpanded:
self.BigKIDisplayPicture()
elif self.BKRightSideMode == kGUI.BKPlayerExpanded:
self.BigKIDisplayPlayerEntry()
elif self.BKRightSideMode == kGUI.BKMarkerListExpanded:
self.BigKIDisplayMarkerGame()
## Refresh the list of folders for the Inbox and Age Journal folders.
def BigKIRefreshFolderList(self):
# Remember selected and what position in the list the player is at.
vault = ptVault()
# Get Journal folder information.
if xLocTools.FolderIDToFolderName(PtVaultStandardNodes.kInboxFolder) not in self.BKJournalFolderDict:
inFolder = vault.getInbox()
if inFolder is not None:
self.BKJournalListOrder.insert(0, xLocTools.FolderIDToFolderName(PtVaultStandardNodes.kInboxFolder))
self.BKJournalFolderDict[xLocTools.FolderIDToFolderName(PtVaultStandardNodes.kInboxFolder)] = inFolder
# Get the Age Journal folders and add any new ones.
masterAgeFolder = vault.getAgeJournalsFolder()
if masterAgeFolder is not None:
ageFolderRefs = masterAgeFolder.getChildNodeRefList()
for ageFolderRef in ageFolderRefs:
ageFolder = ageFolderRef.getChild()
ageFolder = ageFolder.upcastToFolderNode()
if ageFolder is not None:
if not self.IsFolderHidden(ageFolder):
ageFolderName = ageFolder.folderGetName()
if ageFolderName == "":
ageFolderName = "[invalid]"
ageFolderName = FilterAgeName(ageFolderName)
if ageFolderName in kAges.Hide:
continue
if ageFolderName not in self.BKJournalFolderDict:
# New Age folder, add it.
self.BKJournalListOrder.append(ageFolderName)
self.BKJournalFolderDict[ageFolderName] = ageFolder
# Make sure the current Age is at the top of the list.
try:
line = self.BKJournalListOrder.index(self.GetAgeInstanceName())
if line != 1:
# It's not at the top of the list, so put it at the top.
self.BKJournalListOrder.remove(self.GetAgeInstanceName())
self.BKJournalListOrder.insert(1, self.GetAgeInstanceName())
# If the player is looking at a Journal entry then switch to list mode.
if self.BKRightSideMode == kGUI.BKJournalExpanded or self.BKRightSideMode == kGUI.BKPictureExpanded or self.BKRightSideMode == kGUI.BKMarkerListExpanded:
self.ChangeBigKIMode(kGUI.BKListMode)
except ValueError:
# Create a folder for most Ages.
ageName = self.GetAgeFileName().lower()
if ageName != "startup" and ageName != "avatarcustomization" and ageName != "unknown age" and self.GetAgeInstanceName() != "?unknown?":
entry = vault.findChronicleEntry("CleftSolved")
cleftSolved = False
if entry is not None:
if entry.chronicleGetValue() == "yes":
cleftSolved = True
if self.GetAgeInstanceName() != "D'ni-Riltagamin" or cleftSolved:
instAgeName = self.GetAgeInstanceName()
createAgeFolder = True
ageFolderRefs = masterAgeFolder.getChildNodeRefList()
for ageFolderRef in ageFolderRefs:
ageFolder = ageFolderRef.getChild()
ageFolder = ageFolder.upcastToFolderNode()
if ageFolder is not None and ageFolder.getFolderNameW() == instAgeName:
createAgeFolder = False
break
if instAgeName and createAgeFolder:
nFolder = ptVaultFolderNode(0)
if nFolder is not None:
nFolder.setFolderNameW(self.GetAgeInstanceName())
nFolder.folderSetType(PtVaultStandardNodes.kAgeTypeJournalFolder)
# Add to the master Age folder folder.
masterAgeFolder.addNode(nFolder)
else:
PtDebugPrint(u"xKI.BigKIRefreshFolderList(): Could not create folder for {}.".format(self.GetAgeInstanceName()), level=kErrorLevel)
else:
PtDebugPrint(u"xKI.BigKIRefreshFolderList(): Could not find the Master Age jounal folder.", level=kErrorLevel)
# Get the player lists.
self.BKPlayerFolderDict.clear()
self.BKPlayerListOrder = []
ageMembers = KIFolder(PtVaultStandardNodes.kAgeMembersFolder)
if ageMembers is not None:
if xLocTools.FolderIDToFolderName(PtVaultStandardNodes.kAgeMembersFolder) not in self.BKPlayerFolderDict:
# Add the new player folder.
self.BKPlayerListOrder.append(xLocTools.FolderIDToFolderName(PtVaultStandardNodes.kAgeMembersFolder))
self.BKPlayerFolderDict[xLocTools.FolderIDToFolderName(PtVaultStandardNodes.kAgeMembersFolder)] = ageMembers
PtDebugPrint(u"xKI.BigKIRefreshFolderList(): Updating ageMembers.", level=kDebugDumpLevel)
else:
PtDebugPrint(u"xKI.BigKIRefreshFolderList(): AgeMembers folder is missing.", level=kWarningLevel)
buddies = vault.getBuddyListFolder()
if buddies is not None:
if xLocTools.FolderIDToFolderName(PtVaultStandardNodes.kBuddyListFolder) not in self.BKPlayerFolderDict:
# Add the new player folder.
self.BKPlayerListOrder.append(xLocTools.FolderIDToFolderName(PtVaultStandardNodes.kBuddyListFolder))
self.BKPlayerFolderDict[xLocTools.FolderIDToFolderName(PtVaultStandardNodes.kBuddyListFolder)] = buddies
else:
PtDebugPrint(u"xKI.BigKIRefreshFolderList(): Buddies folder is missing.", level=kWarningLevel)
# Update the neighborhood folder.
self.BigKIRefreshNeighborFolder()
# Update the Recent people folder.
PIKA = vault.getPeopleIKnowAboutFolder()
if PIKA is not None:
if xLocTools.FolderIDToFolderName(PtVaultStandardNodes.kPeopleIKnowAboutFolder) not in self.BKPlayerFolderDict:
# Add the new player folder.
self.BKPlayerListOrder.append(xLocTools.FolderIDToFolderName(PtVaultStandardNodes.kPeopleIKnowAboutFolder))
self.BKPlayerFolderDict[xLocTools.FolderIDToFolderName(PtVaultStandardNodes.kPeopleIKnowAboutFolder)] = PIKA
else:
PtDebugPrint(u"xKI.BigKIRefreshFolderList(): PeopleIKnowAbout folder is missing.", level=kWarningLevel)
ignores = vault.getIgnoreListFolder()
if ignores is not None:
if xLocTools.FolderIDToFolderName(PtVaultStandardNodes.kIgnoreListFolder) not in self.BKPlayerFolderDict:
# Add the new player folder.
self.BKPlayerListOrder.append(xLocTools.FolderIDToFolderName(PtVaultStandardNodes.kIgnoreListFolder))
self.BKPlayerFolderDict[xLocTools.FolderIDToFolderName(PtVaultStandardNodes.kIgnoreListFolder)] = ignores
else:
PtDebugPrint(u"xKI.BigKIRefreshFolderList(): IgnoreList folder is missing.", level=kWarningLevel)
# All Players
if PtIsInternalRelease():
ap = vault.getAllPlayersFolder()
if ap:
name = xLocTools.FolderIDToFolderName(PtVaultStandardNodes.kAllPlayersFolder)
if name not in self.BKPlayerFolderDict:
# Add the new player folder.
self.BKPlayerListOrder.append(name)
self.BKPlayerFolderDict[name] = ap
# Age Visitors.
visSep = SeparatorFolder(PtGetLocalizedString("KI.Folders.VisLists"))
self.BKPlayerListOrder.append(visSep.name)
self.BKPlayerFolderDict[visSep.name] = visSep
self.BigKIRefreshAgeVisitorFolders()
# Age Owners.
self.BigKIRefreshAgesOwnedFolder()
## Refresh the Neighbors folder.
def BigKIRefreshNeighborFolder(self):
neighborhood = GetNeighborhood()
try:
neighbors = neighborhood.getAgeOwnersFolder()
if xLocTools.FolderIDToFolderName(PtVaultStandardNodes.kHoodMembersFolder) not in self.BKPlayerFolderDict:
# Add the new Neighbors folder.
self.BKPlayerListOrder.append(xLocTools.FolderIDToFolderName(PtVaultStandardNodes.kHoodMembersFolder))
PtDebugPrint(u"xKI.BigKIRefreshNeighborFolder(): Got the neighbors player folder.", level=kDebugDumpLevel)
self.BKPlayerFolderDict[xLocTools.FolderIDToFolderName(PtVaultStandardNodes.kHoodMembersFolder)] = neighbors
except AttributeError:
PtDebugPrint(u"xKI.BigKIRefreshNeighborFolder(): Neighbors folder is missing.", level=kWarningLevel)
## Refresh the Age Visitors folders for Ages the player owns.
def BigKIRefreshAgeVisitorFolders(self):
vault = ptVault()
try:
myAgesFolder = vault.getAgesIOwnFolder()
listOfMyAgeLinks = myAgesFolder.getChildNodeRefList()
for myAgeLinkRef in listOfMyAgeLinks:
myAgeLink = myAgeLinkRef.getChild()
myAgeLink = myAgeLink.upcastToAgeLinkNode()
myAge = myAgeLink.getAgeInfo()
if myAge is not None:
if self.CanAgeInviteVistors(myAge, myAgeLink) and myAge.getAgeFilename() not in kAges.Hide:
PtDebugPrint(u"xKI.BigKIRefreshAgeVisitorFolders(): Refreshing visitor list for {}.".format(GetAgeName(myAge)), level=kDebugDumpLevel)
folderName = xCensor.xCensor(PtGetLocalizedString("KI.Config.OwnerVisitors", [GetAgeName(myAge)]), self.censorLevel)
if folderName not in self.BKPlayerFolderDict:
# Add the new Age Visitors folder.
PtDebugPrint(u"xKI.BigKIRefreshAgeVisitorFolders(): Adding visitor list for {}.".format(GetAgeName(myAge)), level=kDebugDumpLevel)
self.BKPlayerListOrder.append(folderName)
self.BKPlayerFolderDict[folderName] = myAge
else:
PtDebugPrint(u"xKI.BigKIRefreshAgeVisitorFolders(): Age info for {} is not ready yet.".format(myAgeLink.getUserDefinedName()), level=kErrorLevel)
except AttributeError:
PtDebugPrint(u"xKI.BigKIRefreshAgeVisitorFolders(): Error finding Age Visitors folder.", level=kErrorLevel)
## Refresh the configuration folder listing for owned Ages.
# This is currently only used for Neighborhoods.
def BigKIRefreshAgesOwnedFolder(self):
# First, get rid of all the Age config entries, in case one of them got deleted.
self.BKConfigFolderDict.clear()
self.BKConfigListOrder = []
for config in self.BKConfigDefaultListOrder:
self.BKConfigListOrder.append(config)
vault = ptVault()
try:
myAgesFolder = vault.getAgesIOwnFolder()
listOfMyAgeLinks = myAgesFolder.getChildNodeRefList()
for myAgeLinkRef in listOfMyAgeLinks:
myAgeLink = myAgeLinkRef.getChild()
myAgeLink = myAgeLink.upcastToAgeLinkNode()
myAge = myAgeLink.getAgeInfo()
if myAge is not None:
if myAge.getAgeFilename() == "Neighborhood":
PtDebugPrint(u"xKI.BigKIRefreshAgesOwnedFolder(): Refreshing owner configuration for Age {}.".format(GetAgeName(myAge)), level=kDebugDumpLevel)
configName = xCensor.xCensor(PtGetLocalizedString("KI.Config.OwnerConfig", [GetAgeName(myAge)]), self.censorLevel)
if configName not in self.BKConfigFolderDict:
# Add the new Age configuration.
PtDebugPrint(u"xKI: adding owner config for Age {}.".format(GetAgeName(myAge)), level=kDebugDumpLevel)
self.BKConfigListOrder.append(configName)
self.BKConfigFolderDict[configName] = myAge
else:
PtDebugPrint(u"xKI.BigKIRefreshAgesOwnedFolder(): Age info for {} is not ready yet.".format(myAgeLink.getUserDefinedName()), level=kErrorLevel)
except AttributeError:
PtDebugPrint(u"xKI.BigKIRefreshAgesOwnedFolder(): Error finding Age folder.", level=kErrorLevel)
## Reget the contents of the selected content list.
def BigKINewContentList(self):
try:
folderName = self.BKFolderListOrder[self.BKFolderSelected]
folder = self.BKFolderLineDict[folderName]
if folder is not None:
if isinstance(folder, ptVaultNode):
if folder.getType() == PtVaultNodeTypes.kAgeInfoNode:
try:
self.BKContentList = folder.getCanVisitFolder().getChildNodeRefList()
except AttributeError:
self.BKContentList = []
else:
self.BKContentList = folder.getChildNodeRefList()
self.BigKIProcessContentList(True)
if self.BKFolderSelectChanged:
self.BKContentListTopLine = 0
elif isinstance(folder, KIFolder):
self.BKContentList = PtGetPlayerListDistanceSorted()
self.BigKIProcessContentList(True)
if self.BKFolderSelectChanged:
self.BKContentListTopLine = 0
else:
# Shouldn't happen because the player can't click on these.
self.BKContentList = []
except (IndexError, KeyError):
self.BKContentList = []
self.BigKIRefreshContentListDisplay()
## Refreshes the contents of the selected content list.
def BigKIRefreshContentList(self):
try:
folderName = self.BKFolderListOrder[self.BKFolderSelected]
folder = self.BKFolderLineDict[folderName]
if folder is not None:
if isinstance(folder, ptVaultNode):
if folder.getType() == PtVaultNodeTypes.kAgeInfoNode:
try:
self.BKContentList = folder.getCanVisitFolder().getChildNodeRefList()
except AttributeError:
self.BKContentList = []
else:
self.BKContentList = folder.getChildNodeRefList()
self.BigKIProcessContentList()
elif isinstance(folder, KIFolder):
self.BKContentList = PtGetPlayerListDistanceSorted()
self.BigKIProcessContentList()
else:
self.BKContentList = []
except LookupError:
pass
#~~~~~~~~~~~~~~~~~~~~~~~~~~#
# BigKI Display Refreshing #
#~~~~~~~~~~~~~~~~~~~~~~~~~~#
## Refresh the display of the folders and the selection.
def BigKIRefreshFolderDisplay(self):
# Refresh the display of the folders.
ID = kGUI.BKIIncomingLine
if self.BKFolderListOrder:
# Make sure that it is a valid index.
if self.BKFolderTopLine >= len(self.BKFolderListOrder):
self.BKFolderTopLine = len(self.BKFolderListOrder) - 1
# If the selected is off the screen, go to the top then (only in list mode).
## @todo Note when the self.BKFolderSelected has changed, refresh the content display.
if self.BKRightSideMode == kGUI.BKListMode:
if self.BKFolderSelected < self.BKFolderTopLine:
self.BKFolderSelected = self.BKFolderTopLine
if self.BKFolderSelected > self.BKFolderTopLine + (kGUI.BKIFolderLineLast - kGUI.BKIIncomingLine):
self.BKFolderSelected = self.BKFolderTopLine + (kGUI.BKIFolderLineLast - kGUI.BKIIncomingLine)
if self.BKFolderSelected > self.BKFolderTopLine + len(self.BKFolderListOrder[self.BKFolderTopLine:]) - 1:
self.BKFolderSelected = self.BKFolderTopLine + len(self.BKFolderListOrder[self.BKFolderTopLine]) - 1
selectedFolder = self.BKFolderSelected - self.BKFolderTopLine + kGUI.BKIIncomingLine
for folderName in self.BKFolderListOrder[self.BKFolderTopLine:]:
folderField = ptGUIControlTextBox(BigKI.dialog.getControlFromTag(ID))
longFolderField = ptGUIControlTextBox(BigKI.dialog.getControlFromTag(ID + 500))
buttonID = ID - kGUI.BKIFolderLine01+kGUI.BKIFolderLineBtn01
folderButton = ptGUIControlButton(BigKI.dialog.getControlFromTag(buttonID))
# Make sure it's not a separator folder.
if folderName in self.BKFolderLineDict and isinstance(self.BKFolderLineDict[folderName], SeparatorFolder):
# This button can't be clicked.
folderButton.hide()
folderField.setStringJustify(kLeftJustify)
folderField.setForeColor(kColors.DniStatic)
else:
folderButton.show()
folderField.setStringJustify(kRightJustify)
if ID == selectedFolder:
folderField.setForeColor(kColors.DniSelected)
longFolderField.setForeColor(kColors.DniSelected)
else:
folderField.setForeColor(kColors.DniSelectable)
longFolderField.setForeColor(kColors.DniSelectable)
folderField.setStringW(folderName)
longFolderField.setStringW(folderName)
ID += 1
if ID > kGUI.BKIFolderLineLast:
break
# Set the up and down buttons, if needed.
upbtn = ptGUIControlButton(BigKI.dialog.getControlFromTag(kGUI.BKFolderUpLine))
if self.BKFolderTopLine > 0:
upbtn.show()
else:
upbtn.hide()
dwnbtn = ptGUIControlButton(BigKI.dialog.getControlFromTag(kGUI.BKFolderDownLine))
# Has the listbox been filled up?
if ID > kGUI.BKIFolderLineLast:
dwnbtn.show()
else:
dwnbtn.hide()
# If there are more folder lines, fill them out to be blank and disable
# their button fields.
for tagID in range(ID, kGUI.BKIFolderLineLast + 1):
folderField = ptGUIControlTextBox(BigKI.dialog.getControlFromTag(tagID))
folderField.setForeColor(kColors.DniSelectable)
folderField.setString(" ")
buttonID = tagID - kGUI.BKIFolderLine01 + kGUI.BKIFolderLineBtn01
folderButton = ptGUIControlButton(BigKI.dialog.getControlFromTag(buttonID))
folderButton.hide()
## Do some extra processing on the content list.
def BigKIProcessContentList(self, removeInboxStuff=False):
# Start with nothing in the removeList (remove from current content list).
removeList = []
# If it's a player list.
if self.BKFolderLineDict is self.BKPlayerFolderDict:
ignores = ptVault().getIgnoreListFolder()
# Make sure there are some players to process.
if len(self.BKContentList) > 0:
# If this is a ptPlayer.
if isinstance(self.BKContentList[0], ptPlayer):
# Sort the list of Age players.
try:
self.BKContentList.sort(lambda a, b: cmp(a.getPlayerName().lower(), b.getPlayerName().lower()))
except:
PtDebugPrint(u"xKI.BigKIProcessContentList(): Unable to sort Age players, but don't break the list.", level=kErrorLevel)
for idx in range(len(self.BKContentList)):
player = self.BKContentList[idx]
if isinstance(player, ptPlayer):
if ignores.playerlistHasPlayer(player.getPlayerID()):
# Remove ignored player.
removeList.insert(0, idx)
else:
# Not a player, remove from the list.
removeList.insert(0, idx)
else:
# Sort the list of players, online first.
self.BKContentList.sort(CMPplayerOnline)
# Remove all the unnamed players and ignored people.
for idx in range(len(self.BKContentList)):
ref = self.BKContentList[idx]
elem = ref.getChild()
if elem is not None:
if elem.getType() == PtVaultNodeTypes.kPlayerInfoNode:
elem = elem.upcastToPlayerInfoNode()
if elem.playerGetName() == "":
# Put them in reverse order in the removeList.
removeList.insert(0, idx)
# Check if they are in the ignore list.
elif ignores.playerlistHasPlayer(elem.playerGetID()):
# Get parent; in some folders the player has to be still visible.
parent = ref.getParent()
if parent:
parent = parent.upcastToFolderNode()
if parent is None:
# Make sure this is not the IgnoreList.
if parent.folderGetType() != PtVaultStandardNodes.kIgnoreListFolder:
# Put in them in reverse order in the removeList.
removeList.insert(0, idx)
else:
removeList.insert(0, idx)
else:
removeList.insert(0, idx)
elif self.BKFolderListOrder[self.BKFolderSelected] == xLocTools.FolderIDToFolderName(PtVaultStandardNodes.kInboxFolder):
# Look for KI-Mail from non-Buddies if the player only wants KI-Mail from Buddies.
vault = ptVault()
inbox = vault.getInbox()
buddies = vault.getBuddyListFolder()
ignores = vault.getIgnoreListFolder()
for idx in range(len(self.BKContentList)):
ref = self.BKContentList[idx]
if ref is not None:
if ref.getSaver() is None or ref.getSaverID() == 0:
continue
if (self.onlyGetPMsFromBuddies and not buddies.playerlistHasPlayer(ref.getSaverID())) or ignores.playerlistHasPlayer(ref.getSaverID()):
PtDebugPrint(u"xKI.BigKIProcessContentList(): Remove from inbox because it's from {}.".format(ref.getSaver().playerGetName()), level=kWarningLevel)
# Remove from the list.
removeList.insert(0, idx)
# Only remove from inbox if specified.
if removeInboxStuff:
PtDebugPrint(u"xKI.BigKIProcessContentList(): Really removed from inbox because it's from {}, this time.".format(ref.getSaver().playerGetName()), level=kWarningLevel)
# Remove from inbox (how will this work?).
element = ref.getChild()
inbox.removeNode(element)
if removeList:
PtDebugPrint(u"xKI.BigKIProcessContentList(): Removing {} contents from being displayed.".format(len(removeList)), level=kWarningLevel)
for removeidx in removeList:
del self.BKContentList[removeidx]
if self.BKFolderListOrder[self.BKFolderSelected] == xLocTools.FolderIDToFolderName(PtVaultStandardNodes.kInboxFolder):
self.BKContentList = self.markerJoinRequests + self.BKContentList
# Also add in the GlobalInbox stuff here.
vault = ptVault()
gInbox = vault.getGlobalInbox()
if gInbox is not None:
self.BKContentList = gInbox.getChildNodeRefList() + self.BKContentList
self.BKContentList.sort(CMPNodeDate)
removeList = []
for contentidx in range(len(self.BKContentList)):
content = self.BKContentList[contentidx]
if isinstance(content, ptVaultNodeRef):
element = content.getChild()
if element is not None:
if element.getType() == PtVaultNodeTypes.kFolderNode or element.getType() == PtVaultNodeTypes.kChronicleNode:
removeList.insert(0, contentidx)
for removeidx in removeList:
del self.BKContentList[removeidx]
## Refresh the display of the selected content list.
def BigKIRefreshContentListDisplay(self):
if self.BKRightSideMode == kGUI.BKListMode:
createField = ptGUIControlTextBox(KIListModeDialog.dialog.getControlFromTag(kGUI.BKILMTitleCreateLine))
createBtn = ptGUIControlButton(KIListModeDialog.dialog.getControlFromTag(kGUI.BKIListModeCreateBtn))
try:
if self.BKFolderLineDict is self.BKPlayerFolderDict:
if self.BKFolderListOrder[self.BKFolderSelected] == xLocTools.FolderIDToFolderName(PtVaultStandardNodes.kBuddyListFolder):
createField.setStringW(PtGetLocalizedString("KI.Player.CreateBuddyTitle"))
createBtn.show()
else:
createField.setString(" ")
createBtn.hide()
else:
createField.setString(" ")
createBtn.hide()
except IndexError:
createField.setString(" ")
createBtn.hide()
if len(self.BKFolderListOrder) != 0:
PtDebugPrint(u"xKI.BigKIRefreshContentListDisplay(): Index error: self.BKFolderSelected = {} and list = {}.".format(self.BKFolderSelected, self.BKFolderListOrder), level=kWarningLevel)
return
ID = kGUI.BKILMOffsetLine01
if len(self.BKContentList) != 0:
if self.BKContentListTopLine >= len(self.BKContentList):
self.BKContentListTopLine = len(self.BKContentList) - 1
for content in self.BKContentList[self.BKContentListTopLine:]:
if content is not None:
# Add the new line.
contentIconJ = ptGUIControlButton(KIListModeDialog.dialog.getControlFromTag(ID + kGUI.BKILMIconJournalOffset))
contentIconAva = ptGUIControlButton(KIListModeDialog.dialog.getControlFromTag(ID + kGUI.BKILMIconPersonOffset))
contentIconP = ptGUIControlDynamicText(KIListModeDialog.dialog.getControlFromTag(ID + kGUI.BKILMIconPictureOffset))
contentTitle = ptGUIControlTextBox(KIListModeDialog.dialog.getControlFromTag(ID + kGUI.BKILMTitleOffset))
contentDate = ptGUIControlTextBox(KIListModeDialog.dialog.getControlFromTag(ID + kGUI.BKILMDateOffset))
contentFrom = ptGUIControlTextBox(KIListModeDialog.dialog.getControlFromTag(ID + kGUI.BKILMFromOffset))
if isinstance(content, ptPlayer):
contentIconAva.show()
contentIconJ.hide()
contentIconP.hide()
contentTitle.setForeColor(kColors.DniSelectable)
contentTitle.setString(xCensor.xCensor(content.getPlayerName(), self.censorLevel))
contentTitle.show()
contentDate.hide()
contentFrom.setForeColor(kColors.DniSelectable)
contentFrom.setFontSize(10)
contentFrom.setString(GetAgeName())
contentFrom.show()
# Find the button to enable it.
lmButton = ptGUIControlButton(KIListModeDialog.dialog.getControlFromTag(((ID - 100) / 10) + kGUI.BKIListModeCreateBtn))
lmButton.show()
ID += 10
if ID > kGUI.BKILMOffsetLineLast:
break
else:
element = content.getChild()
if element is not None:
if element.getType() == PtVaultNodeTypes.kTextNoteNode:
element = element.upcastToTextNoteNode()
contentIconJ.show()
contentIconP.hide()
contentIconAva.hide()
elif element.getType() == PtVaultNodeTypes.kImageNode:
element = element.upcastToImageNode()
contentIconJ.hide()
contentIconAva.hide()
if contentIconP.getNumMaps() > 0:
dynMap = contentIconP.getMap(0)
image = element.imageGetImage()
dynMap.clearToColor(ptColor(.1, .1, .1, .1))
if image is not None:
dynMap.drawImage(kGUI.BKIImageStartX, kGUI.BKIImageStartY, image, 0)
dynMap.flush()
contentIconP.show()
elif element.getType() == PtVaultNodeTypes.kPlayerInfoNode:
element = element.upcastToPlayerInfoNode()
contentIconAva.show()
contentIconJ.hide()
contentIconP.hide()
elif element.getType() == PtVaultNodeTypes.kMarkerGameNode:
element = element.upcastToMarkerGameNode()
# No icon for Marker Game.
contentIconAva.hide()
contentIconJ.hide()
contentIconP.hide()
elif element.getType() == PtVaultNodeTypes.kFolderNode:
continue
else:
contentIconAva.hide()
contentIconJ.hide()
contentIconP.hide()
if isinstance(element, ptVaultPlayerInfoNode):
# If it's a player, use the title for the player name.
contentTitle.setForeColor(kColors.DniSelectable)
contentTitle.setString(xCensor.xCensor(element.playerGetName(), self.censorLevel))
contentTitle.show()
contentDate.hide()
contentFrom.setForeColor(kColors.DniSelectable)
contentFrom.setFontSize(10)
if element.playerIsOnline():
contentFrom.setString(FilterAgeName(element.playerGetAgeInstanceName()))
else:
contentFrom.setString(" ")
contentFrom.show()
else:
# Otherwise it's an image or a text note.
if content.getSaverID() == 0:
# Must be from the DRC.
contentTitle.setForeColor(kColors.DniStatic)
contentDate.setForeColor(kColors.DniStatic)
else:
contentTitle.setForeColor(kColors.DniSelectable)
contentDate.setForeColor(kColors.DniSelectable)
if isinstance(element, ptVaultImageNode):
contentTitle.setString(xCensor.xCensor(element.imageGetTitle(), self.censorLevel))
elif isinstance(element, ptVaultTextNoteNode):
contentTitle.setString(xCensor.xCensor(element.noteGetTitle(), self.censorLevel))
elif isinstance(element, ptVaultMarkerGameNode):
contentTitle.setString(xCensor.xCensor(element.getGameName(), self.censorLevel))
else:
# Probably still downloading because of lag.
contentTitle.setString("--[Downloading]--")
contentTitle.setForeColor(kColors.DniYellow)
PtDebugPrint(u"xKI.BigKIRefreshContentListDisplay(): Unknown data type in content list: type = {}.".format(element.getType()), level=kErrorLevel)
contentTitle.show()
try:
tupTime = time.gmtime(PtGMTtoDniTime(element.getModifyTime()))
curTime = time.strftime(PtGetLocalizedString("Global.Formats.Date"), tupTime)
except:
curTime = ""
contentDate.setString(curTime)
contentDate.show()
sender = content.getSaver()
# See if the saver was the player.
localPlayer = PtGetLocalPlayer()
if sender is not None and localPlayer.getPlayerID() != sender.playerGetID():
if content.getSaverID() == 0:
# Must be from the DRC.
contentFrom.setForeColor(kColors.DniStatic)
contentFrom.setFontSize(13)
contentFrom.setString("DRC")
else:
contentFrom.setForeColor(kColors.DniSelectable)
contentFrom.setFontSize(10)
contentFrom.setString(sender.playerGetName())
contentFrom.show()
else:
if content.getSaverID() == 0:
# Must be from the DRC.
contentFrom.setString("DRC")
contentFrom.show()
else:
contentFrom.setString(" ")
contentFrom.hide()
# Find the button to enable it.
lmButton = ptGUIControlButton(KIListModeDialog.dialog.getControlFromTag(((ID - 100) / 10) + kGUI.BKIListModeCreateBtn))
lmButton.show()
ID += 10
if ID > kGUI.BKILMOffsetLineLast:
break
else:
PtDebugPrint(u"xKI.BigKIRefreshContentListDisplay: No element inside the content.", level=kErrorLevel)
else:
PtDebugPrint(u"xKI.BigKIRefreshContentListDisplay: No content, even though the folder said there was.", level=kErrorLevel)
# Set the up and down buttons if needed.
upBtn = ptGUIControlButton(BigKI.dialog.getControlFromTag(kGUI.BKLMUpButton))
if self.BKContentListTopLine > 0:
upBtn.show()
else:
upBtn.hide()
dwnBtn = ptGUIControlButton(BigKI.dialog.getControlFromTag(kGUI.BKLMDownButton))
# Has the ListBox been filled up?
if ID > kGUI.BKILMOffsetLineLast:
dwnBtn.show()
else:
dwnBtn.hide()
# If there are more content lines, fill them out to be blank
# and disable the button fields.
for tagID in range(ID,kGUI.BKILMOffsetLineLast + 10, 10):
iconPic = ptGUIControlDynamicText(KIListModeDialog.dialog.getControlFromTag(tagID + kGUI.BKILMIconPictureOffset))
iconPic.hide()
iconJrn = ptGUIControlButton(KIListModeDialog.dialog.getControlFromTag(tagID + kGUI.BKILMIconJournalOffset))
iconJrn.hide()
iconAva = ptGUIControlButton(KIListModeDialog.dialog.getControlFromTag(tagID + kGUI.BKILMIconPersonOffset))
iconAva.hide()
titleField = ptGUIControlTextBox(KIListModeDialog.dialog.getControlFromTag(tagID + kGUI.BKILMTitleOffset))
titleField.hide()
dateField = ptGUIControlTextBox(KIListModeDialog.dialog.getControlFromTag(tagID + kGUI.BKILMDateOffset))
dateField.hide()
fromField = ptGUIControlTextBox(KIListModeDialog.dialog.getControlFromTag(tagID + kGUI.BKILMFromOffset))
fromField.hide()
# Find the button to disable it.
lmButton = ptGUIControlButton(KIListModeDialog.dialog.getControlFromTag(((tagID - 100) / 10) + kGUI.BKIListModeCreateBtn))
lmButton.hide()
#~~~~~~~~~~~~~~~~~~~~~~~#
# BigKI Content Display #
#~~~~~~~~~~~~~~~~~~~~~~~#
## Display a text Journal entry in the KI.
def BigKIDisplayJournalEntry(self):
jrnAgeName = ptGUIControlTextBox(KIJournalExpanded.dialog.getControlFromTag(kGUI.BKIJRNAgeName))
jrnAgeName.hide()
jrnDate = ptGUIControlTextBox(KIJournalExpanded.dialog.getControlFromTag(kGUI.BKIJRNDate))
jrnDate.hide()
jrnTitle = ptGUIControlTextBox(KIJournalExpanded.dialog.getControlFromTag(kGUI.BKIJRNTitle))
jrnTitle.hide()
jrnNote = ptGUIControlMultiLineEdit(KIJournalExpanded.dialog.getControlFromTag(kGUI.BKIJRNNote))
jrnNote.hide()
jrnNote.setBufferLimit(kLimits.JournalTextSize)
jrnDeleteBtn = ptGUIControlButton(KIJournalExpanded.dialog.getControlFromTag(kGUI.BKIJRNDeleteButton))
jrnDeleteBtn.hide()
jrnTitleBtn = ptGUIControlButton(KIJournalExpanded.dialog.getControlFromTag(kGUI.BKIJRNTitleButton))
if self.BKCurrentContent is None:
PtDebugPrint(u"xKI.BigKIDisplayJournalEntry(): self.BKCurrentContent is None.", level=kErrorLevel)
return
if self.IsContentMutable(self.BKCurrentContent):
jrnDeleteBtn.show()
jrnNote.unlock()
if not self.BKInEditMode or self.BKEditField != kGUI.BKEditFieldJRNTitle:
jrnTitleBtn.show()
else:
jrnNote.lock()
jrnTitleBtn.hide()
element = self.BKCurrentContent.getChild()
if element is None:
PtDebugPrint(u"xKI.BigKIDisplayJournalEntry(): Element is None.", level=kErrorLevel)
return
dataType = element.getType()
if dataType != PtVaultNodeTypes.kTextNoteNode:
PtDebugPrint(u"xKI.BigKIDisplayJournalEntry(): Wrong element type {}.".format(dataType), level=kErrorLevel)
return
element = element.upcastToTextNoteNode()
# Display the content on the screen.
jrnAgeName.setString(FilterAgeName(xCensor.xCensor(element.getCreateAgeName(), self.censorLevel)))
jrnAgeName.show()
tupTime = time.gmtime(PtGMTtoDniTime(element.getModifyTime()))
curTime = time.strftime(PtGetLocalizedString("Global.Formats.Date"), tupTime)
jrnDate.setString(curTime)
jrnDate.show()
if not self.BKInEditMode or self.BKEditField != kGUI.BKEditFieldJRNTitle:
jrnTitle.setString(xCensor.xCensor(element.noteGetTitle(), self.censorLevel))
jrnTitle.show()
if not self.BKInEditMode or self.BKEditField != kGUI.BKEditFieldJRNNote:
encoded = buffer(xCensor.xCensor(element.noteGetText(), self.censorLevel))
jrnNote.setEncodedBuffer(encoded)
jrnNote.show()
self.BigKISetSeen(self.BKCurrentContent)
# If it came from someone else, add them to the SendTo field.
self.CheckContentForSender(self.BKCurrentContent)
## Create and display a new note in the Journal.
def BigKICreateJournalNote(self):
PtDebugPrint(u"xKI.BigKICreateJournalNote(): Create text note message.", level=kDebugDumpLevel)
# If there is no folder list, then make one.
if not self.BKFolderListOrder:
self.BigKIRefreshFolderList()
try:
journal = self.BKJournalFolderDict[self.GetAgeInstanceName()]
if journal is not None:
# Make sure that the age folder is selected.
self.BKFolderTopLine = self.BKJournalFolderTopLine = 0 # Scroll back to the top.
self.BKFolderSelected = self.BKJournalFolderSelected = self.BKJournalListOrder.index(self.GetAgeInstanceName())
# Create the note.
note = ptVaultTextNoteNode(0)
note.setTextW(PtGetLocalizedString("KI.Journal.InitialMessage"))
note.setTitleW(PtGetLocalizedString("KI.Journal.InitialTitle"))
self.BKCurrentContent = journal.addNode(note)
return self.BKCurrentContent
else:
PtDebugPrint(u"xKI.BigKICreateJournalNote(): Journal not ready.", level=kErrorLevel)
return None
except KeyError:
PtDebugPrint(u"xKI.BigKICreateJournalNote(): Could not find journal for this Age: {}.".format(self.GetAgeInstanceName()), level=kErrorLevel)
## Display a KI Picture in the KI.
def BigKIDisplayPicture(self):
picAgeName = ptGUIControlTextBox(KIPictureExpanded.dialog.getControlFromTag(kGUI.BKIPICAgeName))
picAgeName.hide()
picDate = ptGUIControlTextBox(KIPictureExpanded.dialog.getControlFromTag(kGUI.BKIPICDate))
picDate.hide()
picTitle = ptGUIControlTextBox(KIPictureExpanded.dialog.getControlFromTag(kGUI.BKIPICTitle))
picTitle.hide()
picImage = ptGUIControlDynamicText(KIPictureExpanded.dialog.getControlFromTag(kGUI.BKIPICImage))
picImage.hide()
picDeleteBtn = ptGUIControlButton(KIPictureExpanded.dialog.getControlFromTag(kGUI.BKIPICDeleteButton))
picDeleteBtn.hide()
picTitleBtn = ptGUIControlButton(KIPictureExpanded.dialog.getControlFromTag(kGUI.BKIPICTitleButton))
if self.BKCurrentContent is None:
PtDebugPrint(u"xKI.BigKIDisplayPicture(): self.BKCurrentContent is None.", level=kErrorLevel)
return
if self.IsContentMutable(self.BKCurrentContent):
picDeleteBtn.show()
if not self.BKInEditMode or self.BKEditField != kGUI.BKEditFieldPICTitle:
picTitleBtn.show()
else:
picTitleBtn.hide()
element = self.BKCurrentContent.getChild()
if element is None:
PtDebugPrint(u"xKI.BigKIDisplayPicture(): Element is None.", level=kErrorLevel)
return
dataType = element.getType()
if dataType != PtVaultNodeTypes.kImageNode:
PtDebugPrint(u"xKI.BigKIDisplayPicture(): Wrong element type {}.".format(dataType), level=kErrorLevel)
return
element = element.upcastToImageNode()
# Display the content on the screen.
picAgeName.setString(FilterAgeName(xCensor.xCensor(element.getCreateAgeName(), self.censorLevel)))
picAgeName.show()
tupTime = time.gmtime(PtGMTtoDniTime(element.getModifyTime()))
curTime = time.strftime(PtGetLocalizedString("Global.Formats.Date"), tupTime)
picDate.setString(curTime)
picDate.show()
if not self.BKInEditMode or self.BKEditField != kGUI.BKEditFieldPICTitle:
picTitle.setString(xCensor.xCensor(element.imageGetTitle(), self.censorLevel))
picTitle.show()
if picImage.getNumMaps() > 0:
dynMap = picImage.getMap(0)
image = element.imageGetImage()
dynMap.clearToColor(ptColor(.1, .1, .1, .3))
if image is not None:
dynMap.drawImage(kGUI.BKIImageStartX, kGUI.BKIImageStartY, image, 0)
else:
dynMap.fillRect(kGUI.BKIImageStartX, kGUI.BKIImageStartY, kGUI.BKIImageStartX + 800, kGUI.BKIImageStartY + 600, ptColor(.2, .2, .2, .1))
dynMap.flush()
picImage.show()
self.BigKISetSeen(self.BKCurrentContent)
# If it came from someone else, add them to the SendTo field.
self.CheckContentForSender(self.BKCurrentContent)
## Create and display a new KI Picture in the Journal.
def BigKICreateJournalImage(self, image, useScreenShot=False):
PtDebugPrint(u"xKI.BigKICreateJournalImage(): Create a KI Picture from {}.".format(image), level=kDebugDumpLevel)
# If there is no folder list, then make one.
if not self.BKFolderListOrder:
self.BigKIRefreshFolderList()
try:
journal = self.BKJournalFolderDict[self.GetAgeInstanceName()]
if journal is not None:
# Make sure that the age folder is selected.
self.BKFolderTopLine = self.BKJournalFolderTopLine = 0 # Scroll back to the top.
self.BKFolderSelected = self.BKJournalFolderSelected = self.BKJournalListOrder.index(self.GetAgeInstanceName())
# Create the image entry.
imgElem = ptVaultImageNode(0)
if useScreenShot:
imgElem.setImageFromScrShot()
else:
imgElem.imageSetImage(image)
imgElem.setTitleW(PtGetLocalizedString("KI.Image.InitialTitle"))
self.BKCurrentContent = journal.addNode(imgElem)
return self.BKCurrentContent
else:
PtDebugPrint(u"xKI.BigKICreateJournalImage(): Journal not ready.", level=kErrorLevel)
return None
except KeyError:
PtDebugPrint(u"xKI.BigKICreateJournalImage(): Could not find journal for this Age: {}.".format(self.GetAgeInstanceName()), level=kErrorLevel)
## Display a player entry.
def BigKIDisplayPlayerEntry(self):
plyName = ptGUIControlTextBox(KIPlayerExpanded.dialog.getControlFromTag(kGUI.BKIPLYName))
plyName.hide()
plyID = ptGUIControlTextBox(KIPlayerExpanded.dialog.getControlFromTag(kGUI.BKIPLYID))
plyID.hide()
plyIDedit = ptGUIControlEditBox(KIPlayerExpanded.dialog.getControlFromTag(kGUI.BKIPLYPlayerIDEditBox))
plyIDedit.hide()
plyDetail = ptGUIControlTextBox(KIPlayerExpanded.dialog.getControlFromTag(kGUI.BKIPLYDetail))
plyDetail.hide()
plyDeleteBtn = ptGUIControlButton(KIPlayerExpanded.dialog.getControlFromTag(kGUI.BKIPLYDeleteButton))
plyDeleteBtn.hide()
# Is the player asking for a player ID number?
if self.BKGettingPlayerID:
plyName.setStringW(PtGetLocalizedString("KI.Player.EnterID"))
plyName.show()
plyIDedit.setString("")
plyIDedit.show()
plyIDedit.focus()
KIPlayerExpanded.dialog.setFocus(plyIDedit.getKey())
return
if self.BKCurrentContent is None:
PtDebugPrint(u"xKI.BigKIDisplayPlayerEntry(): self.BKCurrentContent is None.", level=kErrorLevel)
return
if isinstance(self.BKCurrentContent, ptPlayer):
# Display the content on the screen.
plyName.setString(xCensor.xCensor(self.BKCurrentContent.getPlayerName(), self.censorLevel))
plyName.show()
IDText = "{:08d}".format(self.BKCurrentContent.getPlayerID())
plyID.setString(IDText)
plyID.show()
plyDetail.setStringW(PtGetLocalizedString("KI.Player.InAge", [GetAgeName()]))
plyDetail.show()
sendToField = ptGUIControlTextBox(BigKI.dialog.getControlFromTag(kGUI.BKIPlayerLine))
self.BKPlayerSelected = self.BKCurrentContent
sendToField.setString(self.BKCurrentContent.getPlayerName())
return
element = self.BKCurrentContent.getChild()
if element is None:
PtDebugPrint(u"xKI.BigKIDisplayPlayerEntry(): Element is None.", level=kErrorLevel)
return
dataType = element.getType()
if dataType != PtVaultNodeTypes.kPlayerInfoNode:
PtDebugPrint(u"xKI.BigKIDisplayPlayerEntry(): Wrong element type {}.".format(dataType), level=kErrorLevel)
return
element = element.upcastToPlayerInfoNode()
# Display the content on the screen.
plyName.setString(xCensor.xCensor(element.playerGetName(), self.censorLevel))
plyName.show()
IDText = "{:08d}".format(element.playerGetID())
plyID.setString(IDText)
plyID.show()
if element.playerIsOnline():
if element.playerGetAgeInstanceName() == "Cleft":
plyDetail.setStringW(PtGetLocalizedString("KI.Player.InCleft"))
elif element.playerGetAgeInstanceName() == "AvatarCustomization":
plyDetail.setStringW(PtGetLocalizedString("KI.Player.InCloset"))
else:
plyDetail.setStringW(PtGetLocalizedString("KI.Player.InAge", [FilterAgeName(element.playerGetAgeInstanceName())]))
else:
plyDetail.setStringW(PtGetLocalizedString("KI.Player.Offline"))
plyDetail.show()
# Determine if this player can be removed from this folder.
folder = self.BKCurrentContent.getParent()
if folder:
folder = folder.upcastToFolderNode()
if folder and self.IsFolderContentMutable(folder):
plyDeleteBtn.show()
sendToField = ptGUIControlTextBox(BigKI.dialog.getControlFromTag(kGUI.BKIPlayerLine))
self.BKPlayerSelected = self.BKCurrentContent
sendToField.setString(element.playerGetName())
## Save after a player was edited.
def BigKICheckSavePlayer(self):
if self.BKGettingPlayerID:
# Create and save a player element into Buddies.
self.BKGettingPlayerID = False
plyIDedit = ptGUIControlEditBox(KIPlayerExpanded.dialog.getControlFromTag(kGUI.BKIPLYPlayerIDEditBox))
if not plyIDedit.wasEscaped():
ID = self.chatMgr.commandsProcessor.GetPID(plyIDedit.getString())
if ID:
localPlayer = PtGetLocalPlayer()
if ID != localPlayer.getPlayerID():
vault = ptVault()
buddies = vault.getBuddyListFolder()
if buddies is not None:
if buddies.playerlistHasPlayer(ID):
plyDetail = ptGUIControlTextBox(KIPlayerExpanded.dialog.getControlFromTag(kGUI.BKIPLYDetail))
plyDetail.setStringW(PtGetLocalizedString("KI.Player.AlreadyAdded"))
plyDetail.show()
self.BKGettingPlayerID = True
else:
buddies.playerlistAddPlayer(ID)
self.chatMgr.DisplayStatusMessage(PtGetLocalizedString("KI.Player.Added"))
if not self.BKGettingPlayerID:
self.ChangeBigKIMode(kGUI.BKListMode)
else:
plyDetail = ptGUIControlTextBox(KIPlayerExpanded.dialog.getControlFromTag(kGUI.BKIPLYDetail))
plyDetail.setStringW(PtGetLocalizedString("KI.Player.NotYourself"))
plyDetail.show()
self.BKGettingPlayerID = True
else:
plyDetail = ptGUIControlTextBox(KIPlayerExpanded.dialog.getControlFromTag(kGUI.BKIPLYDetail))
plyDetail.setStringW(PtGetLocalizedString("KI.Player.NumberOnly"))
plyDetail.show()
self.BKGettingPlayerID = True
else:
# Nothing here, just go back to list mode.
self.ChangeBigKIMode(kGUI.BKListMode)
## Prepares the display of a marker game, as it may be loading.
def BigKIDisplayMarkerGame(self):
# Make sure that the player can view this game.
if self.gKIMarkerLevel < kKIMarkerNormalLevel:
self.BigKIDisplayMarkerGameMessage(PtGetLocalizedString("KI.MarkerGame.pendingActionUpgradeKI"))
return
# Save some typing.
mgr = self.markerGameManager
getControl = KIMarkerFolderExpanded.dialog.getControlFromTag
# Initialize the markerGameDisplay to the currently selected game.
# But first, ensure that the player meets all the necessary criteria.
if self.BKCurrentContent is None:
PtDebugPrint(u"xKI.BigKIDisplayMarkerGame(): Could not find the current selected content selected.", level=kErrorLevel)
return
element = self.BKCurrentContent.getChild()
if element is None:
PtDebugPrint(u"xKI.BigKIDisplayMarkerGame(): Could not find the current content's child node.", level=kErrorLevel)
return
dataType = element.getType()
if dataType != PtVaultNodeTypes.kMarkerGameNode:
PtDebugPrint(u"xKI.BigKIDisplayMarkerGame(): Cannot process this node, wrong data type: {}.".format(element.getType()), level=kErrorLevel)
return
element = element.upcastToMarkerGameNode()
PtDebugPrint(u"xKI.BigKIDisplayMarkerGame(): Starting Marker Game KI Display Manager, loading game: {}.".format(element.getGameName()), level=kDebugDumpLevel)
## This was previously BigKIFinishDisplayMarkerGame()
questGameFinished = False
# A game is in progress, restrict access.
if mgr.AmIPlaying(element):
self.MFdialogMode = kGames.MFPlaying
# Are we editing this game? If so, how?
elif mgr.IsActive(element) and mgr.edit_mode:
if mgr.selected_marker_id != -1:
self.MFdialogMode = kGames.MFEditingMarker
else:
self.MFdialogMode = kGames.MFEditing
# Whatever.
else:
self.MFdialogMode = kGames.MFOverview
# Refresh miniKI.
self.RefreshMiniKIMarkerDisplay()
self.SetBigKIToButtons()
# Hide the invite buttons controls.
ptGUIControlButton(getControl(kGUI.MarkerFolderInvitePlayer)).hide()
mtbInvitePlayer = ptGUIControlTextBox(getControl(kGUI.MarkerFolderInvitePlayerTB))
mtbInvitePlayer.setForeColor(kColors.Clear)
mtbInvitePlayer.setString(" ")
mbtnEditStart = ptGUIControlButton(getControl(kGUI.MarkerFolderEditStartGame))
mbtnPlayEnd = ptGUIControlButton(getControl(kGUI.MarkerFolderPlayEndGame))
mrkfldOwner = ptGUIControlTextBox(getControl(kGUI.MarkerFolderOwner))
mtbEditStart = ptGUIControlTextBox(getControl(kGUI.MarkerFolderEditStartGameTB))
mtbPlayEnd = ptGUIControlTextBox(getControl(kGUI.MarkerFolderPlayEndGameTB))
mrkfldStatus = ptGUIControlTextBox(getControl(kGUI.MarkerFolderStatus))
mrkfldTitle = ptGUIControlTextBox(getControl(kGUI.MarkerFolderTitleText))
mrkfldTitleBtn = ptGUIControlButton(getControl(kGUI.MarkerFolderTitleBtn))
mbtnDelete = ptGUIControlButton(getControl(kGUI.MarkerFolderDeleteBtn))
mbtnGameTimePullD = ptGUIControlButton(getControl(kGUI.MarkerFolderTimePullDownBtn))
mtbGameType = ptGUIControlTextBox(getControl(kGUI.MarkerFolderGameTypeTB))
mbtnGameTypePullD = ptGUIControlButton(getControl(kGUI.MarkerFolderTypePullDownBtn))
mbtnGameTypePullD.hide()
mbtnGameTimeArrow = ptGUIControlButton(getControl(kGUI.MarkerFolderTimeArrow))
mbtnGameTypeArrow = ptGUIControlButton(getControl(kGUI.MarkerFolderTypeArrow))
mbtnGameTypeArrow.hide()
mtbGameTime = ptGUIControlTextBox(getControl(kGUI.MarkerFolderGameTimeTB))
mtbGameTimeTitle = ptGUIControlTextBox(getControl(kGUI.MarkerFolderGameTimeTitleTB))
mtbGameTimeTitle.setStringW(PtGetLocalizedString("KI.MarkerGame.Time"))
mlbMarkerList = ptGUIControlListBox(getControl(kGUI.MarkerFolderMarkListbox))
mlbMarkerTextTB = ptGUIControlTextBox(getControl(kGUI.MarkerFolderMarkerTextTB))
mbtnMarkerText = ptGUIControlTextBox(getControl(kGUI.MarkerFolderMarkerTextBtn))
mbtnToran = ptGUIControlButton(getControl(kGUI.MarkerFolderToranIcon))
mbtnToran.disable()
mbtnHSpan = ptGUIControlButton(getControl(kGUI.MarkerFolderHSpanIcon))
mbtnHSpan.disable()
mbtnVSpan = ptGUIControlButton(getControl(kGUI.MarkerFolderVSpanIcon))
mbtnVSpan.disable()
mtbToran = ptGUIControlTextBox(getControl(kGUI.MarkerFolderToranTB))
mtbHSPan = ptGUIControlTextBox(getControl(kGUI.MarkerFolderHSpanTB))
mtbVSpan = ptGUIControlTextBox(getControl(kGUI.MarkerFolderVSpanTB))
## FIXME: non quest game types
mtbGameType.setStringW(PtGetLocalizedString("KI.MarkerGame.NameQuest").title())
mbtnEditStart.show()
mbtnPlayEnd.show()
# Is the player merely looking at a Marker Game?
if self.MFdialogMode == kGames.MFOverview:
mrkfldTitleBtn.disable()
mbtnDelete.show()
mbtnGameTimePullD.hide()
mbtnGameTimeArrow.hide()
if element.getCreatorNodeID() == PtGetLocalClientID():
mbtnEditStart.show()
mtbEditStart.setForeColor(kColors.DniShowBtn)
else:
mbtnEditStart.hide()
mtbEditStart.setForeColor(kColors.DniGhostBtn)
mtbEditStart.setStringW(PtGetLocalizedString("KI.MarkerGame.EditButton"))
mtbEditStart.show()
mbtnPlayEnd.show()
mtbPlayEnd.setForeColor(kColors.DniShowBtn)
mtbPlayEnd.setString(PtGetLocalizedString("KI.MarkerGame.PlayButton"))
mtbPlayEnd.show()
mlbMarkerList.hide()
mlbMarkerTextTB.hide()
mbtnToran.hide()
mbtnHSpan.hide()
mbtnVSpan.hide()
mtbToran.hide()
mtbHSPan.hide()
mtbVSpan.hide()
mbtnMarkerText.disable()
# Is the player editing a Marker Game?
elif self.MFdialogMode == kGames.MFEditing or self.MFdialogMode == kGames.MFEditingMarker:
mrkfldTitleBtn.enable()
mbtnDelete.hide()
mbtnGameTimePullD.hide()
mbtnGameTimeArrow.hide()
mbtnEditStart.show()
mtbEditStart.setForeColor(kColors.DniShowBtn)
mbtnPlayEnd.show()
mtbPlayEnd.setForeColor(kColors.DniShowBtn)
# Is the player editing the entire game?
if self.MFdialogMode == kGames.MFEditing:
mtbEditStart.setStringW(PtGetLocalizedString("KI.MarkerGame.DoneEditButton"))
mtbEditStart.show()
mtbPlayEnd.setStringW(PtGetLocalizedString("KI.MarkerGame.AddMarkerButton"))
mtbPlayEnd.show()
mlbMarkerList.clearAllElements()
mlbMarkerList.show()
# Add the Markers to the list.
for idx, age, pos, desc in mgr.markers:
coord = ptDniCoordinates()
coord.fromPoint(pos)
torans = coord.getTorans()
hSpans = coord.getHSpans()
vSpans = coord.getVSpans()
mlbMarkerList.addStringW(u"[{}:{},{},{}] {}".format(FilterAgeName(age), torans, hSpans, vSpans, xCensor.xCensor(desc, self.censorLevel)))
mlbMarkerTextTB.hide()
mbtnToran.hide()
mbtnHSpan.hide()
mbtnVSpan.hide()
mtbToran.hide()
mtbHSPan.hide()
mtbVSpan.hide()
mbtnMarkerText.disable()
# Or just editing one of the Markers?
else:
selectedMarker = mgr.selected_marker
if selectedMarker is not None:
idx, age, pos, desc = selectedMarker
# Must be editing a Marker.
mtbEditStart.setStringW(PtGetLocalizedString("KI.MarkerGame.MarkerListButton"))
mtbEditStart.show()
mtbPlayEnd.setStringW(PtGetLocalizedString("KI.MarkerGame.RemoveMarkerButton"))
mtbPlayEnd.show()
mlbMarkerList.hide()
mlbMarkerTextTB.show()
# don't censor here... we don't want censored stuff saved to the vault
mlbMarkerTextTB.setStringW(desc)
mbtnToran.show()
mbtnHSpan.show()
mbtnVSpan.show()
mtbToran.show()
mtbHSPan.show()
mtbVSpan.show()
# Get the selected Marker's coordinates.
coord = ptDniCoordinates()
coord.fromPoint(pos)
mtbToran.setString(str(coord.getTorans()))
mtbHSPan.setString(str(coord.getHSpans()))
mtbVSpan.setString(str(coord.getVSpans()))
mbtnMarkerText.show()
mbtnMarkerText.enable()
else:
# Error...
PtDebugPrint(u"xKI.BigKIFinishDisplayMarkerGame(): Could not find selected marker.", level=kErrorLevel)
mtbEditStart.setStringW(PtGetLocalizedString("KI.MarkerGame.GoBackButton"))
mtbEditStart.show()
mtbPlayEnd.setString(" ")
mtbPlayEnd.show()
mlbMarkerList.hide()
mlbMarkerTextTB.show()
mlbMarkerTextTB.setString("?Unknown Marker?")
mbtnToran.hide()
mbtnHSpan.hide()
mbtnVSpan.hide()
mtbToran.hide()
mtbHSPan.hide()
mtbVSpan.hide()
# Is the player currently playing a Marker Game?
elif self.MFdialogMode == kGames.MFPlaying:
mrkfldTitleBtn.disable()
mbtnDelete.hide()
mbtnGameTimePullD.hide()
mbtnGameTimeArrow.hide()
mbtnToran.hide()
mbtnHSpan.hide()
mbtnVSpan.hide()
mtbToran.hide()
mtbHSPan.hide()
mtbVSpan.hide()
mbtnMarkerText.disable()
mbtnEditStart.show()
mtbEditStart.setForeColor(kColors.DniShowBtn)
mtbEditStart.setString(PtGetLocalizedString("KI.MarkerGame.StopPlayingButton"))
mtbEditStart.show()
mbtnPlayEnd.show()
mtbPlayEnd.setForeColor(kColors.DniShowBtn)
mtbPlayEnd.setString(PtGetLocalizedString("KI.MarkerGame.ResetGameButton"))
mtbPlayEnd.show()
mlbMarkerList.clearAllElements()
mlbMarkerList.show()
# Assume that the game is finished, unless an unseen Marker is still left.
questGameFinished = True
# Add the Markers into the list.
for idx, age, pos, desc in mgr.markers:
if mgr.IsMarkerCaptured(idx):
coord = ptDniCoordinates()
coord.fromPoint(pos)
torans = coord.getTorans()
hSpans = coord.getHSpans()
vSpans = coord.getVSpans()
mlbMarkerList.addStringW(u"[{}:{},{},{}] {}".format(FilterAgeName(age), torans, hSpans, vSpans, xCensor.xCensor(desc, self.censorLevel)))
else:
questGameFinished = False
mlbMarkerTextTB.hide()
# Refresh the text of the buttons (color changed).
mtbEditStart.refresh()
mtbPlayEnd.refresh()
# Display the content on the screen.
mrkfldTitle.setStringW(xCensor.xCensor(element.getGameName(), self.censorLevel))
mrkfldTitle.show()
# Enable the editable Title.
mrkfldTitleBtn.show()
mrkfldTitleBtn.enable()
count = mgr.marker_total
if self.MFdialogMode == kGames.MFEditing or self.MFdialogMode == kGames.MFEditingMarker:
if count == 0:
statusLine = PtGetLocalizedString("KI.MarkerGame.StatusNoMarkers")
elif count == 1:
statusLine = PtGetLocalizedString("KI.MarkerGame.StatusOneMarker")
else:
statusLine = PtGetLocalizedString("KI.MarkerGame.StatusNMarkers", [str(count)])
else:
if questGameFinished:
statusLine = PtGetLocalizedString("KI.MarkerGame.StatusAllFound")
else:
statusLine = PtGetLocalizedString("KI.MarkerGame.StatusNotAllFound")
mrkfldStatus.setStringW(statusLine)
mrkfldStatus.show()
creatorID = element.getCreatorNodeID()
tempNode = ptVaultPlayerInfoNode()
tempNode.playerSetID(creatorID)
try:
vault = ptVault()
creatorName = vault.findNode(tempNode).upcastToPlayerInfoNode().playerGetName()
except:
creatorName = ""
mrkfldOwner.setStringW(PtGetLocalizedString("KI.MarkerGame.OwnerTitle") + U" {} [ID:{:08d}]".format(creatorName, creatorID))
mrkfldOwner.show()
# TODO: time limit
mtbGameTime.hide()
mtbGameTimeTitle.hide()
def BigKIDisplayMarkerGameMessage(self, msg):
"""Displays some message in the Marker Folder subdialog"""
# Save some typing.
getControl = KIMarkerFolderExpanded.dialog.getControlFromTag
# Disable all controls until we need them.
mrkfldTitle = ptGUIControlTextBox(getControl(kGUI.MarkerFolderTitleText))
mrkfldTitle.hide()
ptGUIControlTextBox(getControl(kGUI.MarkerFolderStatus)).hide()
ptGUIControlTextBox(getControl(kGUI.MarkerFolderOwner)).hide()
# Hide the scroll buttons for the Marker list; the scroll control will turn them back on.
ptGUIControlButton(getControl(kGUI.MarkerFolderMarkerListUpBtn)).hide()
ptGUIControlButton(getControl(kGUI.MarkerFolderMarkerListDownBtn)).hide()
ptGUIControlButton(getControl(kGUI.MarkerFolderInvitePlayer)).hide()
ptGUIControlButton(getControl(kGUI.MarkerFolderEditStartGame)).hide()
ptGUIControlButton(getControl(kGUI.MarkerFolderPlayEndGame)).hide()
ptGUIControlTextBox(getControl(kGUI.MarkerFolderInvitePlayerTB)).hide()
ptGUIControlTextBox(getControl(kGUI.MarkerFolderEditStartGameTB)).hide()
ptGUIControlTextBox(getControl(kGUI.MarkerFolderPlayEndGameTB)).hide()
ptGUIControlButton(getControl(kGUI.MarkerFolderTitleBtn)).hide()
ptGUIControlButton(getControl(kGUI.MarkerFolderDeleteBtn)).hide()
ptGUIControlButton(getControl(kGUI.MarkerFolderTimePullDownBtn)).hide()
ptGUIControlButton(getControl(kGUI.MarkerFolderTypePullDownBtn)).hide()
ptGUIControlButton(getControl(kGUI.MarkerFolderTypePullDownBtn)).disable()
ptGUIControlButton(getControl(kGUI.MarkerFolderTimeArrow)).hide()
ptGUIControlButton(getControl(kGUI.MarkerFolderTypeArrow)).hide()
ptGUIControlTextBox(getControl(kGUI.MarkerFolderGameTimeTB)).hide()
ptGUIControlTextBox(getControl(kGUI.MarkerFolderGameTimeTitleTB)).hide()
ptGUIControlTextBox(getControl(kGUI.MarkerFolderGameTypeTB)).hide()
ptGUIControlListBox(getControl(kGUI.MarkerFolderMarkListbox)).hide()
ptGUIControlTextBox(getControl(kGUI.MarkerFolderMarkerTextTB)).hide()
ptGUIControlTextBox(getControl(kGUI.MarkerFolderMarkerTextBtn)).hide()
ptGUIControlButton(getControl(kGUI.MarkerFolderToranIcon)).disable()
ptGUIControlButton(getControl(kGUI.MarkerFolderHSpanIcon)).disable()
ptGUIControlButton(getControl(kGUI.MarkerFolderVSpanIcon)).disable()
ptGUIControlTextBox(getControl(kGUI.MarkerFolderToranTB)).hide()
ptGUIControlTextBox(getControl(kGUI.MarkerFolderHSpanTB)).hide()
ptGUIControlTextBox(getControl(kGUI.MarkerFolderVSpanTB)).hide()
# Show the status.
mrkfldTitle.setStringW(msg)
mrkfldTitle.show()
mrkfldTitle.refresh()
## Show the selected configuration screen.
def ShowSelectedConfig(self):
if self.BKConfigListOrder[self.BKFolderSelected] == PtGetLocalizedString("KI.Config.Settings"):
self.ChangeBigKIMode(kGUI.BKKIExpanded)
elif self.BKConfigListOrder[self.BKFolderSelected] == PtGetLocalizedString("KI.Config.Volume"):
self.ChangeBigKIMode(kGUI.BKVolumeExpanded)
else:
# Is the dialog hidden?
if self.BKRightSideMode != kGUI.BKAgeOwnerExpanded:
self.ChangeBigKIMode(kGUI.BKAgeOwnerExpanded)
# Otherwise, refresh it.
else:
self.RefreshAgeOwnerSettings()
self.BigKIOnlySelectedToButtons()
## Enter edit mode for a particular field.
def BigKIEnterEditMode(self, whichField):
# Can't be in chatting mode.
self.chatMgr.ToggleChatMode(0)
# If the player was already in edit mode, save the values before re-entering.
if self.BKInEditMode:
self.BigKISaveEdit()
if whichField == kGUI.BKEditFieldJRNTitle:
textBox = ptGUIControlTextBox(KIJournalExpanded.dialog.getControlFromTag(kGUI.BKEditFieldIDs[whichField][kGUI.BKEditIDtextbox]))
button = ptGUIControlButton(KIJournalExpanded.dialog.getControlFromTag(kGUI.BKEditFieldIDs[whichField][kGUI.BKEditIDbutton]))
editBox = ptGUIControlEditBox(KIJournalExpanded.dialog.getControlFromTag(kGUI.BKEditFieldIDs[whichField][kGUI.BKEditIDeditbox]))
elif whichField == kGUI.BKEditFieldPICTitle:
textBox = ptGUIControlTextBox(KIPictureExpanded.dialog.getControlFromTag(kGUI.BKEditFieldIDs[whichField][kGUI.BKEditIDtextbox]))
button = ptGUIControlButton(KIPictureExpanded.dialog.getControlFromTag(kGUI.BKEditFieldIDs[whichField][kGUI.BKEditIDbutton]))
editBox = ptGUIControlEditBox(KIPictureExpanded.dialog.getControlFromTag(kGUI.BKEditFieldIDs[whichField][kGUI.BKEditIDeditbox]))
editBox.setStringSize(56)
else:
textBox = None
button = None
editBox = None
# Make sure it is a valid field to edit.
if textBox is not None:
if self.BKCurrentContent is not None:
edElement = self.BKCurrentContent.getChild()
else:
edElement = None
if edElement is not None:
self.BKInEditMode = True
self.BKEditContent = self.BKCurrentContent
self.BKEditField = whichField
# Hide the TextBox and the button.
textBox.hide()
button.hide()
# Set the edit box and display it.
if self.BKEditField == kGUI.BKEditFieldJRNTitle:
edElement = edElement.upcastToTextNoteNode()
editBox.setString(xCensor.xCensor(edElement.noteGetTitle(), self.censorLevel))
KIJournalExpanded.dialog.setFocus(editBox.getKey())
elif self.BKEditField == kGUI.BKEditFieldPICTitle:
edElement = edElement.upcastToImageNode()
editBox.setString(xCensor.xCensor(edElement.imageGetTitle(), self.censorLevel))
KIPictureExpanded.dialog.setFocus(editBox.getKey())
else:
editBox.setString("")
editBox.end()
editBox.show()
editBox.focus()
if whichField == kGUI.BKEditFieldJRNTitle or whichField == kGUI.BKEditFieldJRNNote:
KIJournalExpanded.dialog.refreshAllControls()
elif whichField == kGUI.BKEditFieldPICTitle:
KIPictureExpanded.dialog.refreshAllControls()
else:
PtDebugPrint(u"xKI.BigKIEnterEditMode(): Content has no element to edit.", level=kErrorLevel)
else:
# Is it for the journal edit?
if whichField == kGUI.BKEditFieldJRNNote:
# If so, then it's sort of automatically in edit mode.
self.BKInEditMode = True
self.BKEditContent = self.BKCurrentContent
self.BKEditField = whichField
## Save what the player was editing to the right place.
def BigKISaveEdit(self, noExitEditMode=False):
if self.BKInEditMode:
if self.BKEditField == kGUI.BKEditFieldJRNTitle:
textBox = ptGUIControlTextBox(KIJournalExpanded.dialog.getControlFromTag(kGUI.BKEditFieldIDs[self.BKEditField][kGUI.BKEditIDtextbox]))
button = ptGUIControlButton(KIJournalExpanded.dialog.getControlFromTag(kGUI.BKEditFieldIDs[self.BKEditField][kGUI.BKEditIDbutton]))
editBox = ptGUIControlEditBox(KIJournalExpanded.dialog.getControlFromTag(kGUI.BKEditFieldIDs[self.BKEditField][kGUI.BKEditIDeditbox]))
elif self.BKEditField == kGUI.BKEditFieldJRNNote:
textBox = ptGUIControlMultiLineEdit(KIJournalExpanded.dialog.getControlFromTag(kGUI.BKEditFieldIDs[self.BKEditField][kGUI.BKEditIDtextbox]))
button = None
editBox = None
elif self.BKEditField == kGUI.BKEditFieldPICTitle:
textBox = ptGUIControlTextBox(KIPictureExpanded.dialog.getControlFromTag(kGUI.BKEditFieldIDs[self.BKEditField][kGUI.BKEditIDtextbox]))
button = ptGUIControlButton(KIPictureExpanded.dialog.getControlFromTag(kGUI.BKEditFieldIDs[self.BKEditField][kGUI.BKEditIDbutton]))
editBox = ptGUIControlEditBox(KIPictureExpanded.dialog.getControlFromTag(kGUI.BKEditFieldIDs[self.BKEditField][kGUI.BKEditIDeditbox]))
else:
textBox = None
button = None
editBox = None
# Make sure that it can be edited.
if textBox is not None:
if self.BKEditContent is not None:
edElement = self.BKEditContent.getChild()
if edElement is not None:
if editBox is not None:
if not editBox.wasEscaped():
textBox.setString(editBox.getString())
if self.BKEditField == kGUI.BKEditFieldJRNTitle:
edElement = edElement.upcastToTextNoteNode()
jTitle = editBox.getStringW()
if jTitle[:len(PtGetLocalizedString("KI.Journal.InitialTitle"))] == PtGetLocalizedString("KI.Journal.InitialTitle"):
# Make sure that the player actually added something (so as not to get a blank title).
if jTitle != PtGetLocalizedString("KI.Journal.InitialTitle"):
jTitle = jTitle[len(PtGetLocalizedString("KI.Journal.InitialTitle")):]
edElement.setTitleW(jTitle)
elif self.BKEditField == kGUI.BKEditFieldPICTitle:
edElement = edElement.upcastToImageNode()
pTitle = editBox.getStringW()
if pTitle[:len(PtGetLocalizedString("KI.Image.InitialTitle"))] == PtGetLocalizedString("KI.Image.InitialTitle"):
# Make sure that the player actually added something (so as not to get a blank title).
if pTitle != PtGetLocalizedString("KI.Image.InitialTitle"):
pTitle = pTitle[len(PtGetLocalizedString("KI.Image.InitialTitle")):]
edElement.setTitleW(pTitle)
edElement.save()
else:
if self.BKEditField == kGUI.BKEditFieldJRNNote:
buf = textBox.getEncodedBufferW()
if buf[:len(PtGetLocalizedString("KI.Journal.InitialMessage"))] == PtGetLocalizedString("KI.Journal.InitialMessage"):
buf = buf[len(PtGetLocalizedString("KI.Journal.InitialMessage")):]
edElement = edElement.upcastToTextNoteNode()
edElement.setTextW(buf)
edElement.save()
if self.BKEditField != kGUI.BKEditFieldJRNNote:
# Put the fields back into no-edit mode.
textBox.show()
button.show()
editBox.hide()
if not noExitEditMode:
# Stop editing.
self.BKInEditMode = False
self.BKEditContent = None
self.BKEditField = -1
## If the focus has changed, check to see if editing should be stopped.
def BigKICheckFocusChange(self):
if self.BKInEditMode:
if self.BKEditField == kGUI.BKEditFieldJRNTitle:
editBox = ptGUIControlEditBox(KIJournalExpanded.dialog.getControlFromTag(kGUI.BKEditFieldIDs[self.BKEditField][kGUI.BKEditIDeditbox]))
elif self.BKEditField == kGUI.BKEditFieldPICTitle:
editBox = ptGUIControlEditBox(KIPictureExpanded.dialog.getControlFromTag(kGUI.BKEditFieldIDs[self.BKEditField][kGUI.BKEditIDeditbox]))
else:
editBox = None
if editBox is not None:
if editBox.isFocused():
return
self.BigKISaveEdit()
## Mark a content as seen (unimplemented) in the BigKI.
def BigKISetSeen(self, content):
if BigKI.dialog.isEnabled():
content.setSeen()
#~~~~~~~~~~~~~~#
# BigKI Saving #
#~~~~~~~~~~~~~~#
## Save the player-editted name of an Age.
def SaveAgeNameFromEdit(self, control):
newTitle = ""
try:
# Get the selected Age config setting.
myAge = self.BKConfigFolderDict[self.BKConfigListOrder[self.BKFolderSelected]]
if not control.wasEscaped():
# Set the new title.
myAge.setAgeUserDefinedName(control.getStringW())
myAge.save()
PtDebugPrint(u"xKI.SaveAgeNameFromEdit(): Updating title to \"{}\".".format(control.getStringW()), level=kDebugDumpLevel )
else:
PtDebugPrint(u"xKI.SaveAgeNameFromEdit(): Escape hit.", level=kDebugDumpLevel )
newTitle = myAge.getDisplayName()
except LookupError:
PtDebugPrint(u"xKI.SaveAgeNameFromEdit(): The current Age could not be found.", level=kDebugDumpLevel )
myAge = None
control.hide()
# Re-enable the button and text.
title = ptGUIControlTextBox(KIAgeOwnerExpanded.dialog.getControlFromTag(kGUI.BKAgeOwnerTitleTB))
title.setStringW(newTitle)
title.show()
titlebtn = ptGUIControlButton(KIAgeOwnerExpanded.dialog.getControlFromTag(kGUI.BKAgeOwnerTitleBtn))
titlebtn.enable()
## Save the new name of the Marker Game.
# This saves it both in the Vault and on the Game Server.
def SaveMarkerGameNameFromEdit(self, control):
title = ptGUIControlTextBox(KIMarkerFolderExpanded.dialog.getControlFromTag(kGUI.MarkerFolderTitleText))
if self.BKCurrentContent is not None:
element = self.BKCurrentContent.getChild()
if element is not None:
dataType = element.getType()
if dataType == PtVaultNodeTypes.kMarkerGameNode:
element = element.upcastToMarkerGameNode()
if element is not None:
if not control.wasEscaped() and control.getString() != "":
# Set the new title.
newText = xCensor.xCensor(control.getStringW(), self.censorLevel)
element.setGameName(control.getStringW())
title.setString(control.getStringW())
element.save()
PtDebugPrint(u"xKI.SaveMarkerGameNameFromEdit(): Updating title to \"{}\".".format(newText), level=kDebugDumpLevel)
self.RefreshPlayerList()
else:
PtDebugPrint(u"xKI.SaveMarkerGameNameFromEdit(): Escape hit.", level=kDebugDumpLevel)
control.hide()
# Re-enable the button and text.
titlebtn = ptGUIControlTextBox(KIMarkerFolderExpanded.dialog.getControlFromTag(kGUI.MarkerFolderTitleBtn))
titlebtn.enable()
title.show()
## Save the text of a Marker on the Game Server.
def SaveMarkerTextFromEdit(self, control):
title = ptGUIControlTextBox(KIMarkerFolderExpanded.dialog.getControlFromTag(kGUI.MarkerFolderMarkerTextTB))
if self.BKCurrentContent is not None:
element = self.BKCurrentContent.getChild()
if element is not None:
dataType = element.getType()
if dataType == PtVaultNodeTypes.kMarkerGameNode:
element = element.upcastToMarkerGameNode()
if element is not None:
name = control.getStringW()
if not control.wasEscaped() and name:
self.markerGameManager.selected_marker_name = name
else:
PtDebugPrint(u"xKI.SaveMarkerTextFromEdit(): escape hit!", level=kDebugDumpLevel )
control.hide()
# Re-enable the button and text.
titlebtn = ptGUIControlTextBox(KIMarkerFolderExpanded.dialog.getControlFromTag(kGUI.MarkerFolderMarkerTextBtn))
titlebtn.enable()
title.show()
#~~~~~~~~~~~~~~~~~~~#
# GUI Notifications #
#~~~~~~~~~~~~~~~~~~~#
## Process notifications originating from the Blackbar.
# This handles objects like the Yeesha book icon, the quitting icon, the
# options menu icon and the miniKI icon, when the KI has been obtained.
def ProcessNotifyBlackbar(self, control, event):
if event == kDialogLoaded:
pass
elif event == kAction or event == kValueChanged:
bbID = control.getTagID()
if bbID == kGUI.MiniMaximizeRGID:
if control.getValue() == 0:
if PtIsDialogLoaded("KIMini"):
KIMini.dialog.show()
elif control.getValue() == -1:
if PtIsDialogLoaded("KIMini"):
KIMini.dialog.hide()
elif bbID == kGUI.ExitButtonID:
yesText = ptGUIControlTextBox(KIYesNo.dialog.getControlFromTag(kGUI.YesNoTextID))
yesText.setStringW(PtGetLocalizedString("KI.Messages.LeaveGame"))
self.LocalizeDialog(0)
logoutText = ptGUIControlTextBox(KIYesNo.dialog.getControlFromTag(kGUI.YesNoLogoutTextID))
logoutText.show()
logoutButton = ptGUIControlButton(KIYesNo.dialog.getControlFromTag(kGUI.YesNoLogoutButtonID))
logoutButton.show()
KIYesNo.dialog.show()
elif bbID == kGUI.PlayerBookCBID:
if control.isChecked():
curBrainMode = PtGetLocalAvatar().avatar.getCurrentMode()
if self.isEntireYeeshaBookEnabled and (curBrainMode == PtBrainModes.kNonGeneric or curBrainMode == PtBrainModes.kAFK or curBrainMode == PtBrainModes.kSit):
if not self.waitingForAnimation:
self.ShowYeeshaBook()
else:
control.setChecked(0)
else:
control.setChecked(0)
elif bbID == kGUI.OptionsMenuButtonID:
PtShowDialog("OptionsMenuGUI")
else:
PtDebugPrint(u"xKI.ProcessNotifyBlackbar(): Don't know this control bbID = {}.".format(bbID), level=kDebugDumpLevel)
elif event == kInterestingEvent:
plybkCB = ptGUIControlCheckBox(KIBlackbar.dialog.getControlFromTag(kGUI.PlayerBookCBID))
try:
curBrainMode = PtGetLocalAvatar().avatar.getCurrentMode()
if self.isEntireYeeshaBookEnabled and (curBrainMode == PtBrainModes.kNonGeneric or curBrainMode == PtBrainModes.kAFK or curBrainMode == PtBrainModes.kSit):
PtDebugPrint(u"xKI.ProcessNotifyBlackbar(): Show PlayerBook.", level=kDebugDumpLevel)
plybkCB.show()
else:
PtDebugPrint(u"xKI.ProcessNotifyBlackbar(): On ladder, hide PlayerBook.", level=kDebugDumpLevel)
plybkCB.hide()
except NameError:
if self.isEntireYeeshaBookEnabled:
PtDebugPrint(u"xKI.ProcessNotifyBlackbar(): Show PlayerBook.", level=kDebugDumpLevel)
plybkCB.show()
else:
PtDebugPrint(u"xKI.ProcessNotifyBlackbar(): On ladder, hide PlayerBook.", level=kDebugDumpLevel)
plybkCB.hide()
## Process notifications originating from the microKI's Blackbar.
# This takes care of the same duties at the Blackbar processor, with the
# sole difference that it is used only while the user does not yet possess
# a full KI from Gahreesen (thus there is no miniKI icon).
def ProcessNotifyMicroBlackbar(self, control, event):
if event == kDialogLoaded:
rollBtn = ptGUIControlButton(KIMicroBlackbar.dialog.getControlFromTag(kGUI.RolloverLeftID))
rollBtn.setNotifyOnInteresting(1)
rollBtn = ptGUIControlButton(KIMicroBlackbar.dialog.getControlFromTag(kGUI.RolloverRightID))
rollBtn.setNotifyOnInteresting(1)
elif event == kAction or event == kValueChanged:
bbID = control.getTagID()
if bbID == kGUI.ExitButtonID:
yesText = ptGUIControlTextBox(KIYesNo.dialog.getControlFromTag(kGUI.YesNoTextID))
yesText.setStringW(PtGetLocalizedString("KI.Messages.LeaveGame"))
self.LocalizeDialog(0)
logoutText = ptGUIControlTextBox(KIYesNo.dialog.getControlFromTag(kGUI.YesNoLogoutTextID))
logoutText.show()
logoutButton = ptGUIControlButton(KIYesNo.dialog.getControlFromTag(kGUI.YesNoLogoutButtonID))
logoutButton.show()
KIYesNo.dialog.show()
elif bbID == kGUI.PlayerBookCBID:
if control.isChecked():
curBrainMode = PtGetLocalAvatar().avatar.getCurrentMode()
if self.isEntireYeeshaBookEnabled and (curBrainMode == PtBrainModes.kNonGeneric or curBrainMode == PtBrainModes.kAFK or curBrainMode == PtBrainModes.kSit):
if not self.waitingForAnimation:
self.ShowYeeshaBook()
else:
control.setChecked(0)
else:
control.setChecked(0)
elif bbID == kGUI.OptionsMenuButtonID:
PtShowDialog("OptionsMenuGUI")
else:
PtDebugPrint(u"xKI.ProcessNotifyMicroBlackbar(): Don't know this control bbID = {}.".format(bbID), level=kDebugDumpLevel)
elif event == kInterestingEvent:
plybkCB = ptGUIControlCheckBox(KIMicroBlackbar.dialog.getControlFromTag(kGUI.PlayerBookCBID))
try:
curBrainMode = PtGetLocalAvatar().avatar.getCurrentMode()
if self.isEntireYeeshaBookEnabled and (curBrainMode == PtBrainModes.kNonGeneric or curBrainMode == PtBrainModes.kAFK or curBrainMode == PtBrainModes.kSit):
PtDebugPrint(u"xKI.ProcessNotifyMicroBlackbar(): Show PlayerBook.", level=kDebugDumpLevel)
plybkCB.show()
else:
PtDebugPrint(u"xKI.ProcessNotifyMicroBlackbar(): On ladder, hide PlayerBook.", level=kDebugDumpLevel)
plybkCB.hide()
except NameError:
if self.isEntireYeeshaBookEnabled:
PtDebugPrint(u"xKI.ProcessNotifyMicroBlackbar(): Show PlayerBook.", level=kDebugDumpLevel)
plybkCB.show()
else:
PtDebugPrint(u"xKI.ProcessNotifyMicroBlackbar(): On ladder, hide PlayerBook.", level=kDebugDumpLevel)
plybkCB.hide()
## Process notifications originating from the microKI.
# These notifications get called when using the basic chat mode available
# only until the user obtains a real KI from Gahreesen (thus the name,
# microKI).
def ProcessNotifyMicro(self, control, event):
if event == kDialogLoaded:
# Fill in the listbox so that the test is near the enter box.
chatArea = ptGUIControlMultiLineEdit(KIMicro.dialog.getControlFromTag(kGUI.ChatDisplayArea))
chatArea.lock() # Make the chat display immutable.
chatArea.unclickable() # Make the chat display non-clickable.
chatArea.moveCursor(PtGUIMultiLineDirection.kBufferEnd)
chatArea.disableScrollControl()
btnUp = ptGUIControlButton(KIMicro.dialog.getControlFromTag(kGUI.miniChatScrollUp))
btnUp.show()
btnUp.hide()
# Set the edit box buffer size to something larger.
chatedit = ptGUIControlEditBox(KIMicro.dialog.getControlFromTag(kGUI.ChatEditboxID))
chatedit.setStringSize(500)
chatedit.setChatMode(1)
elif event == kShowHide:
if control.isEnabled():
if not self.chatMgr.isChatting:
self.FadeCompletely()
elif event == kAction or event == kValueChanged:
ctrlID = control.getTagID()
if ctrlID == kGUI.ChatEditboxID:
if not control.wasEscaped() and control.getStringW() != "":
self.chatMgr.SendMessage(control.getStringW())
self.chatMgr.ToggleChatMode(0)
elif ctrlID == kGUI.ChatDisplayArea:
self.ResetFadeState()
elif event == kFocusChange:
# If they are chatting, get the focus back.
if self.chatMgr.isChatting:
KIMicro.dialog.setFocus(KIMicro.dialog.getControlFromTag(kGUI.ChatEditboxID))
elif event == kSpecialAction:
ctrlID = control.getTagID()
if ctrlID == kGUI.ChatEditboxID:
self.Autocomplete(control)
## Process notifications originating from the miniKI.
# The miniKI is the display in the top-left corner of the screen (by
# default); these notifications are triggered through interaction with the
# various buttons on it. It also takes care of the floating player list.
def ProcessNotifyMini(self, control, event):
if event == kDialogLoaded:
# Get the original position of the miniKI.
dragbar = ptGUIControlDragBar(KIMini.dialog.getControlFromTag(kGUI.miniDragBar))
self.originalminiKICenter = dragbar.getObjectCenter()
# Retreive the original alpha.
fore = control.getForeColor()
self.originalForeAlpha = fore.getAlpha()
sel = control.getSelectColor()
self.originalSelectAlpha = sel.getAlpha()
# Fill in the listbox so that the test is near the enter box.
chatArea = ptGUIControlMultiLineEdit(KIMini.dialog.getControlFromTag(kGUI.ChatDisplayArea))
chatArea.lock() # Make the chat display immutable.
chatArea.unclickable() # Make the chat display non-clickable.
chatArea.moveCursor(PtGUIMultiLineDirection.kBufferEnd)
# Hide the chat scroll buttons (should be nothing in chat area yet anyhow).
chatArea.disableScrollControl()
btnUp = ptGUIControlButton(KIMini.dialog.getControlFromTag(kGUI.miniChatScrollUp))
btnUp.show()
privateChbox = ptGUIControlCheckBox(KIMini.dialog.getControlFromTag(kGUI.miniPrivateToggle))
privateChbox.disable()
# Set the edit box buffer size to something larger.
chatedit = ptGUIControlEditBox(KIMini.dialog.getControlFromTag(kGUI.ChatEditboxID))
chatedit.setStringSize(500)
chatedit.setChatMode(1)
# Default the marker tag stuff to be off.
btnmt = ptGUIControlButton(KIMini.dialog.getControlFromTag(kGUI.miniGZDrip))
btnmt.hide()
btnmt = ptGUIControlButton(KIMini.dialog.getControlFromTag(kGUI.miniGZActive))
btnmt.hide()
btnmt = ptGUIControlButton(KIMini.dialog.getControlFromTag(kGUI.miniGZMarkerGameActive))
btnmt.hide()
btnmt = ptGUIControlButton(KIMini.dialog.getControlFromTag(kGUI.miniGZMarkerInRange))
btnmt.hide()
ptGUIControlButton(KIMini.dialog.getControlFromTag(kGUI.miniMGNewMarker)).hide()
ptGUIControlButton(KIMini.dialog.getControlFromTag(kGUI.miniMGNewGame)).hide()
ptGUIControlButton(KIMini.dialog.getControlFromTag(kGUI.miniMGInactive)).hide()
ptGUIControlButton(KIMini.dialog.getControlFromTag(kGUI.miniMGInactive)).disable()
ptGUIControlButton(KIMini.dialog.getControlFromTag(kGUI.PelletScoreButton)).hide()
# Set the color to the off color.
for mcbID in range(kGUI.miniMarkerIndicator01, kGUI.miniMarkerIndicatorLast + 1):
mcb = ptGUIControlProgress(KIMini.dialog.getControlFromTag(mcbID))
mcb.setValue(kGUI.miniMarkerColors["off"])
elif event == kShowHide:
if control.isEnabled():
if self.pelletImager != "":
ptGUIControlButton(KIMini.dialog.getControlFromTag(kGUI.PelletScoreButton)).show()
if self.miniKIFirstTimeShow:
# Set the font size and fade time.
self.DetermineFontSize()
self.DetermineFadeTime()
# If we are chatting then just let it happen.
if not self.chatMgr.isChatting:
self.chatMgr.ToggleChatMode(0)
self.FadeCompletely()
self.miniKIFirstTimeShow = False
self.RefreshPlayerList()
self.RefreshMiniKIMarkerDisplay()
else:
self.chatMgr.ToggleChatMode(0)
self.chatMgr.ClearBBMini()
elif event == kAction or event == kValueChanged:
ctrlID = control.getTagID()
if ctrlID == kGUI.ChatEditboxID:
if not control.wasEscaped() and control.getStringW() != u"":
self.chatMgr.SendMessage(control.getStringW())
self.chatMgr.ToggleChatMode(0)
self.StartFadeTimer()
elif ctrlID == kGUI.PlayerList:
# Make sure they don't click outside what's there.
plyrsel = control.getSelection()
if plyrsel >= control.getNumElements():
control.setSelection(0)
plyrsel = 0
# Place selected player in SendTo textbox.
sendToField = ptGUIControlTextBox(BigKI.dialog.getControlFromTag(kGUI.BKIPlayerLine))
caret = ptGUIControlTextBox(KIMini.dialog.getControlFromTag(kGUI.ChatCaretID))
caret.setString(">")
privateChbox = ptGUIControlCheckBox(KIMini.dialog.getControlFromTag(kGUI.miniPrivateToggle))
privateChbox.setChecked(0)
if plyrsel == -1:
self.BKPlayerSelected = None
else:
self.BKPlayerSelected = self.BKPlayerList[plyrsel]
# Is it a Device Folder or just a string?
if isinstance(self.BKPlayerSelected, DeviceFolder) or isinstance(self.BKPlayerSelected, str):
# Can't be sent to.
pass
elif isinstance(self.BKPlayerSelected, Device):
sendToField.setString(self.BKPlayerSelected.name)
# Is it a specific player info node?
elif isinstance(self.BKPlayerSelected, ptVaultNodeRef):
plyrInfoNode = self.BKPlayerSelected.getChild()
plyrInfo = plyrInfoNode.upcastToPlayerInfoNode()
if plyrInfo is not None:
sendToField.setString(plyrInfo.playerGetName())
# Set private caret.
caret.setStringW(PtGetLocalizedString("KI.Chat.TOPrompt") + unicode(plyrInfo.playerGetName()) + U" >")
privateChbox.setChecked(1)
else:
self.BKPlayerSelected = None
# Is it a specific player?
elif isinstance(self.BKPlayerSelected, ptPlayer):
sendToField.setString(self.BKPlayerSelected.getPlayerName())
caret.setStringW(PtGetLocalizedString("KI.Chat.TOPrompt") + unicode(self.BKPlayerSelected.getPlayerName()) + U" >")
privateChbox.setChecked(1)
# Is it a list of players?
elif isinstance(self.BKPlayerSelected, ptVaultPlayerInfoListNode):
fldrType = self.BKPlayerSelected.folderGetType()
# Is it not the All Players folder?
if fldrType != PtVaultStandardNodes.kAgeMembersFolder:
# If it's a list of age owners, it's a list of neighbors.
if fldrType == PtVaultStandardNodes.kAgeOwnersFolder:
fldrType = PtVaultStandardNodes.kHoodMembersFolder
caret.setStringW(PtGetLocalizedString("KI.Chat.TOPrompt") + xLocTools.FolderIDToFolderName(fldrType) + U" >")
# It's not private and no player is selected.
privateChbox.setChecked(0)
self.BKPlayerSelected = None
if self.BKPlayerSelected is None:
sendToField.setString(" ")
self.SetBigKIToButtons()
# No need to keep the focus.
if self.chatMgr.isChatting:
chatedit = ptGUIControlEditBox(KIMini.dialog.getControlFromTag(kGUI.ChatEditboxID))
KIMini.dialog.setFocus(chatedit.getKey())
# They're playing with the player list, so reset the fade.
self.ResetFadeState()
elif ctrlID == kGUI.miniPutAwayID:
self.ToggleMiniKI()
elif ctrlID == kGUI.miniToggleBtnID:
self.ToggleKISize()
elif ctrlID == kGUI.miniTakePicture:
self.TakePicture()
elif ctrlID == kGUI.miniCreateJournal:
self.MiniKICreateJournalNote()
elif ctrlID == kGUI.miniMuteAll:
# Hit the mute button, and set mute depending on control.
audio = ptAudioControl()
if control.isChecked():
audio.muteAll()
else:
audio.unmuteAll()
elif ctrlID == kGUI.miniPlayerListUp:
# Scroll the player list up one line.
self.ScrollPlayerList(1)
elif ctrlID == kGUI.miniPlayerListDown:
# Scroll the player list down one line.
self.ScrollPlayerList(-1)
elif ctrlID == kGUI.miniGZMarkerInRange:
self.CaptureGZMarker()
self.RefreshMiniKIMarkerDisplay()
elif ctrlID == kGUI.ChatDisplayArea:
self.ResetFadeState()
elif ctrlID == kGUI.miniMGNewMarker:
self.CreateAMarker()
elif ctrlID == kGUI.miniMGNewGame:
self.CreateMarkerGame()
elif ctrlID == kJalakMiniIconBtn:
if PtGetAgeName() == "Jalak":
self.JalakGUIToggle()
else:
ptGUIControlButton(KIMini.dialog.getControlFromTag(kJalakMiniIconBtn)).disable()
elif ctrlID == kGUI.PelletScoreButton:
self.UploadPelletScore()
elif event == kFocusChange:
# If they are chatting, get the focus back.
if self.chatMgr.isChatting:
# If the bigKI is up then let the focus go where it wants.
# Otherwise put the focus back to the chat line.
if not BigKI.dialog.isEnabled():
KIMini.dialog.setFocus(KIMini.dialog.getControlFromTag(kGUI.ChatEditboxID))
else:
if not self.BKInEditMode:
KIMini.dialog.setFocus(KIMini.dialog.getControlFromTag(kGUI.ChatEditboxID))
elif event == kSpecialAction:
ctrlID = control.getTagID()
if ctrlID == kGUI.ChatEditboxID:
self.Autocomplete(control)
# Up or Down key to scroll in the chat history
elif event == kMessageHistoryUp:
ctrlID = control.getTagID()
if ctrlID == kGUI.ChatEditboxID:
self.MessageHistory(control, "up")
elif event == kMessageHistoryDown:
ctrlID = control.getTagID()
if ctrlID == kGUI.ChatEditboxID:
self.MessageHistory(control, "down")
## Process notifications originating from the BigKI itself.
# This does not process notifications specific to an expanded view - each
# view gets its own function, to avoid bloat. This rather deals with
# controls such as the scroll button, the mode switcher, etc., anything
# related to the navigation interface.
def ProcessNotifyBigKI(self, control, event):
if event == kDialogLoaded:
self.BKInEditMode = False
# Put animation at off position, so there is no pop when the animation plays.
KIOnAnim.animation.skipToTime(1.5)
pdisable = ptGUIControlButton(BigKI.dialog.getControlFromTag(kGUI.BKDisabledPeopleButton))
pdisable.disable()
gdisable = ptGUIControlButton(BigKI.dialog.getControlFromTag(kGUI.BKDisabledGearButton))
gdisable.disable()
for ID in range(kGUI.BKIIncomingBtn, kGUI.BKIFolderLineBtnLast):
overBtn = ptGUIControlButton(BigKI.dialog.getControlFromTag(ID))
overBtn.setNotifyOnInteresting(1)
elif event == kShowHide:
if control.isEnabled():
# Hide the long folder names.
for ID in range(kGUI.LONGBKIIncomingLine,kGUI.LONGBKIFolderLineLast+1):
longTB = ptGUIControlTextBox(BigKI.dialog.getControlFromTag(ID))
longTB.hide()
self.BigKISetStatics()
self.BigKISetChanging()
self.RefreshPlayerList()
self.KillFadeTimer()
self.BigKIRefreshFolderList()
self.BigKIRefreshFolderDisplay()
self.ShowBigKI()
else:
self.StartFadeTimer()
elif event == kAction or event == kValueChanged:
bkID = control.getTagID()
# Is it one of the folder buttons?
if bkID >= kGUI.BKIIncomingBtn and bkID <= kGUI.BKIFolderLineBtnLast:
if self.BKFolderLineDict is self.BKConfigFolderDict:
self.BKFolderSelected = bkID - kGUI.BKIIncomingBtn + self.BKFolderTopLine
self.ShowSelectedConfig()
else:
oldselect = self.BKFolderSelected
self.BKFolderSelected = bkID - kGUI.BKIIncomingBtn + self.BKFolderTopLine
if oldselect != self.BKFolderSelected:
self.BKFolderSelectChanged = True
else:
self.BKFolderSelectChanged = False
self.ChangeBigKIMode(kGUI.BKListMode)
# Is it the scroll folder up button?
elif bkID == kGUI.BKFolderUpLine:
if self.BKFolderTopLine > 0:
self.BKFolderTopLine -= 1
self.BigKIRefreshFolderDisplay()
self.SetBigKIToButtons()
# Is it the scroll folder down button?
elif bkID == kGUI.BKFolderDownLine:
self.BKFolderTopLine += 1
self.BigKIRefreshFolderDisplay()
self.SetBigKIToButtons()
elif bkID == kGUI.BKLMUpButton:
if self.BKRightSideMode == kGUI.BKListMode:
if self.BKContentListTopLine > 0:
self.BKContentListTopLine -= kContentListScrollSize
if self.BKContentListTopLine < 0:
self.BKContentListTopLine = 0
self.BigKIRefreshContentListDisplay()
elif bkID == kGUI.BKLMDownButton:
if self.BKRightSideMode == kGUI.BKListMode:
self.BKContentListTopLine += kContentListScrollSize
self.BigKIRefreshContentListDisplay()
elif bkID >= kGUI.BKIToIncomingButton and bkID <= kGUI.BKIToFolderButtonLast:
toFolderNum = bkID - kGUI.BKIToFolderButton01 + self.BKFolderTopLine + 1
# If they are in an expanded mode, then they can move the element to another folder.
if self.BKRightSideMode != kGUI.BKListMode and self.BKCurrentContent is not None:
# Move the current content to the selected folder.
if isinstance(self.BKCurrentContent, ptPlayer):
# Add to new folder.
try:
newFolderName = self.BKFolderListOrder[toFolderNum]
newFolder = self.BKFolderLineDict[newFolderName]
playerID = self.BKCurrentContent.getPlayerID()
localPlayerID = PtGetLocalPlayer().getPlayerID()
if newFolder is not None and playerID != localPlayerID:
if newFolder.getType() == PtVaultNodeTypes.kAgeInfoNode:
self.InviteToVisit(playerID, newFolder)
elif newFolder.getType() == PtVaultNodeTypes.kPlayerInfoListNode:
newFolder.playerlistAddPlayer(playerID)
except (IndexError, KeyError):
# If there was an error, display whatever was already selected.
toFolderNum = self.BKFolderSelected
else:
oldFolder = self.BKCurrentContent.getParent()
theElement = self.BKCurrentContent.getChild()
if theElement is not None:
# Add to new folder.
try:
newFolderName = self.BKFolderListOrder[toFolderNum]
newFolder = self.BKFolderLineDict[newFolderName]
localPlayerID = PtGetLocalPlayer().getPlayerID()
if newFolder is not None:
if newFolder.getType() == PtVaultNodeTypes.kAgeInfoNode:
theElement = theElement.upcastToPlayerInfoNode()
if theElement is not None and theElement.playerGetID() != localPlayerID:
self.InviteToVisit(theElement.playerGetID(), newFolder)
elif newFolder.getType() == PtVaultNodeTypes.kPlayerInfoListNode:
theElement = theElement.upcastToPlayerInfoNode()
if theElement is not None and theElement.playerGetID() != localPlayerID:
theElement = theElement.upcastToPlayerInfoNode()
newFolder.playerlistAddPlayer(theElement.playerGetID())
else:
self.BKCurrentContent = newFolder.addNode(theElement)
if oldFolder is not None:
oldFolder.removeNode(theElement)
except (IndexError, KeyError):
# If there was an error, display whatever was already selected.
toFolderNum = self.BKFolderSelected
# Leave it at the folder they are on.
self.BKFolderSelectChanged = True
self.ChangeBigKIMode(kGUI.BKListMode)
# They could have copied a player, so refresh list.
self.RefreshPlayerList()
elif bkID == kGUI.BKRadioModeID:
# Save the previous selected and top line.
if self.BKFolderLineDict is self.BKJournalFolderDict:
self.BKJournalFolderSelected = self.BKFolderSelected
self.BKJournalFolderTopLine = self.BKFolderTopLine
elif self.BKFolderLineDict is self.BKPlayerFolderDict:
self.BKPlayerFolderSelected = self.BKFolderSelected
self.BKPlayerFolderTopLine = self.BKFolderTopLine
elif self.BKFolderLineDict is self.BKConfigFolderDict:
self.BKConfigFolderSelected = self.BKFolderSelected
self.BKConfigFolderTopLine = self.BKFolderTopLine
modeselect = control.getValue()
# Is it journal mode?
if modeselect == 0:
self.BKFolderLineDict = self.BKJournalFolderDict
self.BKFolderListOrder = self.BKJournalListOrder
self.BKFolderSelected = self.BKJournalFolderSelected
self.BKFolderTopLine = self.BKJournalFolderTopLine
# Is it player list mode?
elif modeselect == 1:
self.BKFolderLineDict = self.BKPlayerFolderDict
self.BKFolderListOrder = self.BKPlayerListOrder
self.BKFolderSelected = self.BKPlayerFolderSelected
self.BKFolderTopLine = self.BKPlayerFolderTopLine
# It is configuration mode.
else:
self.BKFolderLineDict = self.BKConfigFolderDict
self.BKFolderListOrder = self.BKConfigListOrder
self.BKFolderSelected = self.BKConfigFolderSelected
self.BKFolderTopLine = self.BKConfigFolderTopLine
# Reset the top line and selection.
self.BigKIRefreshFolderDisplay()
if modeselect == 0 and (self.BKRightSideMode == kGUI.BKPictureExpanded or self.BKRightSideMode == kGUI.BKJournalExpanded or self.BKRightSideMode == kGUI.BKMarkerListExpanded):
# The player is taking a picture.
self.BigKIInvertToFolderButtons()
else:
# Is the player switching to configuration mode?
if modeselect == 2:
self.ShowSelectedConfig()
# Otherwise, make sure the player is in list mode.
else:
self.ChangeBigKIMode(kGUI.BKListMode)
elif bkID == kGUI.BKIToPlayerButton:
if self.BKCurrentContent is not None and self.BKPlayerSelected is not None:
sendElement = self.BKCurrentContent.getChild()
toPlayerBtn = ptGUIControlButton(BigKI.dialog.getControlFromTag(kGUI.BKIToPlayerButton))
if sendElement is not None:
if isinstance(self.BKPlayerSelected, DeviceFolder):
pass
elif isinstance(self.BKPlayerSelected, Device):
if self.BKPlayerSelected.name in self.imagerMap:
sName = "Upload={}".format(self.BKPlayerSelected.name)
SendNote(self.key, self.imagerMap[self.BKPlayerSelected.name], sName, sendElement.getID())
toPlayerBtn.hide()
elif isinstance(self.BKPlayerSelected, ptVaultNode):
if self.BKPlayerSelected.getType() == PtVaultNodeTypes.kPlayerInfoListNode:
plyrRefList = self.BKPlayerSelected.getChildNodeRefList()
for plyrRef in plyrRefList:
plyr = plyrRef.getChild()
plyr = plyr.upcastToPlayerInfoNode()
if plyr is not None:
sendElement.sendTo(plyr.playerGetID())
elif self.BKPlayerSelected.getType() == PtVaultNodeTypes.kPlayerInfoNode:
sendElement.sendTo(self.BKPlayerSelected.playerGetID())
else:
self.SetSendToErrorMessage(PtGetLocalizedString("KI.Errors.CantSend"))
toPlayerBtn.hide()
elif isinstance(self.BKPlayerSelected, ptVaultNodeRef):
plyrElement = self.BKPlayerSelected.getChild()
if plyrElement is not None and plyrElement.getType() == PtVaultNodeTypes.kPlayerInfoNode:
plyrElement = plyrElement.upcastToPlayerInfoNode()
sendElement.sendTo(plyrElement.playerGetID())
else:
self.SetSendToErrorMessage(PtGetLocalizedString("KI.Errors.PlayerNotFound"))
toPlayerBtn.hide()
elif isinstance(self.BKPlayerSelected, ptPlayer):
sendElement.sendTo(self.BKPlayerSelected.getPlayerID())
toPlayerBtn.hide()
else:
self.SetSendToErrorMessage(PtGetLocalizedString("KI.Errors.UnknownPlayerType"))
else:
self.SetSendToErrorMessage(PtGetLocalizedString("KI.Errors.BadJournalElement"))
elif event == kInterestingEvent:
if control is not None:
shortTB = ptGUIControlTextBox(BigKI.dialog.getControlFromTag(control.getTagID() + 21))
longTB = ptGUIControlTextBox(BigKI.dialog.getControlFromTag(control.getTagID() + 521))
if shortTB.getStringJustify() == kRightJustify and control.isInteresting():
# Switch to long versions.
longTB.setForeColor(shortTB.getForeColor())
longTB.setString(shortTB.getString())
shortTB.hide()
longTB.show()
else:
shortTB.show()
longTB.hide()
## Process notifications originating from a list mode in the BigKI.
# Handles navigation from a list mode (like a list of players or notes) to
# the specified content (a picture, a note, a marker game...). Also takes
# care of creating a new entry when asked.
def ProcessNotifyListMode(self, control, event):
if event == kAction or event == kValueChanged:
lmID = control.getTagID()
if lmID >= kGUI.BKIListModeLineBtn01 and lmID <= kGUI.BKIListModeLineBtnLast:
# Find out which button was clicked and its associated content.
whichOne = lmID - kGUI.BKIListModeLineBtn01 + self.BKContentListTopLine
if whichOne < len(self.BKContentList):
theContent = self.BKContentList[whichOne]
if theContent is not None:
self.BKCurrentContent = theContent
if isinstance(self.BKCurrentContent, ptPlayer):
nextMode = kGUI.BKPlayerExpanded
self.ChangeBigKIMode(nextMode)
else:
theElement = theContent.getChild()
if theElement is not None:
dataType = theElement.getType()
if dataType == PtVaultNodeTypes.kTextNoteNode:
nextMode = kGUI.BKJournalExpanded
elif dataType == PtVaultNodeTypes.kImageNode:
nextMode = kGUI.BKPictureExpanded
elif dataType == PtVaultNodeTypes.kPlayerInfoNode:
nextMode = kGUI.BKPlayerExpanded
elif dataType == PtVaultNodeTypes.kMarkerGameNode:
nextMode = kGUI.BKMarkerListExpanded
else:
self.BKCurrentContent = None
nextMode = kGUI.BKListMode
self.ChangeBigKIMode(nextMode)
else:
PtDebugPrint(u"xKI.ProcessNotifyListMode(): List Mode: content is None for element!", level=kErrorLevel)
elif lmID == kGUI.BKIListModeCreateBtn:
if self.BKFolderLineDict is self.BKPlayerFolderDict:
self.BKGettingPlayerID = True
self.ChangeBigKIMode(kGUI.BKPlayerExpanded)
else:
self.BigKICreateJournalNote()
self.ChangeBigKIMode(kGUI.BKJournalExpanded)
self.BigKIDisplayJournalEntry()
self.BigKIEnterEditMode(kGUI.BKEditFieldJRNTitle)
## Process notifications originating from an expanded picture mode in the BigKI.
# This essentially deals with the taking of new pictures and the editing of
# existing ones, as well as their deletion.
def ProcessNotifyPictureExpanded(self, control, event):
if event == kDialogLoaded:
editBox = ptGUIControlEditBox(KIPictureExpanded.dialog.getControlFromTag(kGUI.BKEditFieldIDs[kGUI.BKEditFieldPICTitle][kGUI.BKEditIDeditbox]))
editBox.hide()
elif event == kShowHide:
if control.isEnabled():
self.BigKIDisplayPicture()
elif event == kAction or event == kValueChanged:
peID = control.getTagID()
if peID == kGUI.BKIPICTitleButton:
if self.IsContentMutable(self.BKCurrentContent):
self.BigKIEnterEditMode(kGUI.BKEditFieldPICTitle)
elif peID == kGUI.BKIPICDeleteButton:
self.YNWhatReason = kGUI.YNDelete
elem = self.BKCurrentContent.getChild()
elem = elem.upcastToImageNode()
if elem is not None:
picTitle = elem.imageGetTitle()
else:
picTitle = "<unknown>"
yesText = ptGUIControlTextBox(KIYesNo.dialog.getControlFromTag(kGUI.YesNoTextID))
yesText.setStringW(PtGetLocalizedString("KI.Messages.DeletePicture", [xCensor.xCensor(picTitle, self.censorLevel)]))
self.LocalizeDialog(1)
KIYesNo.dialog.show()
elif peID == kGUI.BKIPICTitleEdit:
self.BigKISaveEdit(1)
elif event == kFocusChange:
if self.IsContentMutable(self.BKCurrentContent):
self.BigKICheckFocusChange()
## Process notifications originating from an expanded journal mode in the BigKI.
# Handles note creation, editing and deletion.
def ProcessNotifyJournalExpanded(self, control, event):
if event == kDialogLoaded:
editBox = ptGUIControlEditBox(KIJournalExpanded.dialog.getControlFromTag(kGUI.BKEditFieldIDs[kGUI.BKEditFieldJRNTitle][kGUI.BKEditIDeditbox]))
editBox.hide()
elif event == kShowHide:
if control.isEnabled():
self.BigKIDisplayJournalEntry()
elif event == kAction or event == kValueChanged:
jeID = control.getTagID()
# Is it one of the buttons?
if jeID == kGUI.BKIJRNTitleButton:
if self.IsContentMutable(self.BKCurrentContent):
self.BigKIEnterEditMode(kGUI.BKEditFieldJRNTitle)
elif jeID == kGUI.BKIJRNNoteButton:
if self.IsContentMutable(self.BKCurrentContent):
self.BigKIEnterEditMode(kGUI.BKEditFieldJRNNote)
elif jeID == kGUI.BKIJRNDeleteButton:
self.YNWhatReason = kGUI.YNDelete
elem = self.BKCurrentContent.getChild()
elem = elem.upcastToTextNoteNode()
if elem is not None:
jrnTitle = elem.noteGetTitle()
else:
jrnTitle = "<unknown>"
yesText = ptGUIControlTextBox(KIYesNo.dialog.getControlFromTag(kGUI.YesNoTextID))
yesText.setStringW(PtGetLocalizedString("KI.Messages.DeleteJournal", [xCensor.xCensor(jrnTitle, self.censorLevel)]))
self.LocalizeDialog(1)
KIYesNo.dialog.show()
# Is it one of the editing boxes?
elif jeID == kGUI.BKIJRNTitleEdit or jeID == kGUI.BKIJRNNoteEdit:
if self.IsContentMutable(self.BKCurrentContent):
self.BigKISaveEdit(1)
elif event == kFocusChange:
if self.IsContentMutable(self.BKCurrentContent):
if control is not None:
# If the focus is changing to the multiline, the plaer is entering edit mode.
jeID = control.getTagID()
if jeID == kGUI.BKIJRNNote:
self.BigKIEnterEditMode(kGUI.BKEditFieldJRNNote)
return
self.BigKICheckFocusChange()
## Process notifications originating from an expanded player mode in the BigKI.
# Handles deletion of a player's entry.
def ProcessNotifyPlayerExpanded(self, control, event):
if event == kShowHide:
if control.isEnabled():
self.BigKIDisplayPlayerEntry()
elif event == kAction or event == kValueChanged:
plID = control.getTagID()
# Is it one of the buttons?
if plID == kGUI.BKIPLYDeleteButton:
self.YNWhatReason = kGUI.YNDelete
elem = self.BKCurrentContent.getChild()
elem = elem.upcastToPlayerInfoNode()
if elem is not None:
plyrName = elem.playerGetName()
else:
plyrName = "<unknown>"
try:
pfldName = self.BKFolderListOrder[self.BKFolderSelected]
except LookupError:
pfldName = "<unknown>"
yesText = ptGUIControlTextBox(KIYesNo.dialog.getControlFromTag(kGUI.YesNoTextID))
yesText.setStringW(PtGetLocalizedString("KI.Messages.DeletePlayer", [xCensor.xCensor(plyrName, self.censorLevel), pfldName]))
self.LocalizeDialog(1)
KIYesNo.dialog.show()
elif plID == kGUI.BKIPLYPlayerIDEditBox:
self.BigKICheckSavePlayer()
elif event == kFocusChange:
if self.BKGettingPlayerID:
if KIPlayerExpanded.dialog.isEnabled():
plyIDedit = ptGUIControlEditBox(KIPlayerExpanded.dialog.getControlFromTag(kGUI.BKIPLYPlayerIDEditBox))
plyIDedit.focus()
KIPlayerExpanded.dialog.setFocus(plyIDedit.getKey())
else:
self.BKGettingPlayerID = False
self.ChangeBigKIMode(kGUI.BKListMode)
## Process notifications originating from an expanded settings mode in the BigKI.
# Handles the processing tied to settings modification.
def ProcessNotifySettingsExpanded(self, control, event):
if event == kShowHide:
if control.isEnabled():
tfield = ptGUIControlTextBox(KISettings.dialog.getControlFromTag(kGUI.BKIKISettingsText))
tfield.setStringW(PtGetLocalizedString("KI.Config.Settings"))
tfield = ptGUIControlTextBox(KISettings.dialog.getControlFromTag(kGUI.BKIKIFontSizeText))
tfield.setStringW(PtGetLocalizedString("KI.Config.FontSize"))
tfield = ptGUIControlTextBox(KISettings.dialog.getControlFromTag(kGUI.BKIKIFadeTimeText))
tfield.setStringW(PtGetLocalizedString("KI.Config.ChatFadeTime"))
tfield = ptGUIControlTextBox(KISettings.dialog.getControlFromTag(kGUI.BKIKIOnlyPMText))
tfield.setStringW(PtGetLocalizedString("KI.Config.OnlyBuddies"))
self.RefreshKISettings()
else:
self.SaveFontSize()
self.SaveFadeTime()
self.SaveKIFlags()
elif event == kAction or event == kValueChanged:
kiID = control.getTagID()
if kiID == kGUI.BKIKIFontSize:
slidePerFont = float(control.getMax() - control.getMin() + 1.0) / float(len(kChat.FontSizeList))
fontIndex = int(control.getValue() / slidePerFont + 0.25)
if fontIndex >= len(kChat.FontSizeList):
fontIndex = len(kChat.FontSizeList) - 1
self.SetFontSize(kChat.FontSizeList[fontIndex])
elif kiID == kGUI.BKIKIFadeTime:
slidePerTime = float(control.getMax() - control.getMin()) / float(kChat.FadeTimeMax)
self.chatMgr.ticksOnFull = int(control.getValue() / slidePerTime + 0.25)
PtDebugPrint(u"xKI.ProcessNotifySettingsExpanded(): FadeTime set to {}.".format(self.chatMgr.ticksOnFull), level=kDebugDumpLevel)
if self.chatMgr.ticksOnFull == kChat.FadeTimeMax:
self.chatMgr.fadeEnableFlag = False
PtDebugPrint(u"KISettings: FadeTime disabled.", level=kDebugDumpLevel)
else:
self.chatMgr.fadeEnableFlag = True
PtDebugPrint(u"KISettings: FadeTime enabled.", level=kDebugDumpLevel)
elif kiID == kGUI.BKIKIOnlyPM:
self.onlyGetPMsFromBuddies = control.isChecked()
elif kiID == kGUI.BKIKIBuddyCheck:
self.onlyAllowBuddiesOnRequest = control.isChecked()
## Process notifications originating from an expanded settings mode in the BigKI.
# Handles the sound controls from the options menu being modified.
def ProcessNotifyVolumeExpanded(self, control, event):
if event == kShowHide:
if control.isEnabled():
self.RefreshVolumeSettings()
elif event == kAction or event == kValueChanged:
plID = control.getTagID()
audio = ptAudioControl()
if plID == kGUI.BKISoundFXVolSlider:
setting = control.getValue()
PtDebugPrint(u"xKI.ProcessNotifyVolumeExpanded(): SoundFX being changed to {:g} (into {:g}).".format(setting, setting / 10), level=kDebugDumpLevel)
audio.setSoundFXVolume(setting / 10)
elif plID == kGUI.BKIMusicVolSlider:
setting = control.getValue()
PtDebugPrint(u"xKI.ProcessNotifyVolumeExpanded(): Music being changed to {:g} (into {:g}).".format(setting, setting / 10), level=kDebugDumpLevel)
audio.setMusicVolume(setting / 10)
elif plID == kGUI.BKIVoiceVolSlider:
setting = control.getValue()
PtDebugPrint(u"xKI.ProcessNotifyVolumeExpanded(): Voice being changed to {:g} (into {:g}).".format(setting, setting / 10), level=kDebugDumpLevel)
audio.setVoiceVolume(setting / 10)
elif plID == kGUI.BKIAmbienceVolSlider:
setting = control.getValue()
PtDebugPrint(u"xKI.ProcessNotifyVolumeExpanded(): Ambience being changed to {:g} (into {:g}).".format(setting, setting / 10), level=kDebugDumpLevel)
audio.setAmbienceVolume(setting / 10)
elif plID == kGUI.BKIMicLevelSlider:
setting = control.getValue()
PtDebugPrint(u"xKI.ProcessNotifyVolumeExpanded(): MicLevel being changed to {:g} (into {:g}).".format(setting, setting / 10), level=kDebugDumpLevel)
audio.setMicLevel(setting / 10)
elif plID == kGUI.BKIGUIVolSlider:
setting = control.getValue()
PtDebugPrint(u"xKI.ProcessNotifyVolumeExpanded(): MicLevel being changed to {:g} (into {:g}).".format(setting, setting / 10), level=kDebugDumpLevel)
audio.setGUIVolume(setting / 10)
## Process notifications originating from an expanded Age Owner mode in the BigKI.
# Processes owned Ages (currently only applies to Neighborhoods). Note that
# the public/private feature is currently available only through the Nexus.
# This mostly handles description modifications for now.
def ProcessNotifyAgeOwnerExpanded(self, control, event):
if event == kShowHide:
if control.isEnabled():
tField = ptGUIControlTextBox(KIAgeOwnerExpanded.dialog.getControlFromTag(kGUI.BKAgeOwnerDescriptionTitle))
tField.setStringW(PtGetLocalizedString("KI.Config.Description"))
titleEdit = ptGUIControlEditBox(KIAgeOwnerExpanded.dialog.getControlFromTag(kGUI.BKAgeOwnerTitleEditbox))
titleEdit.hide()
self.RefreshAgeOwnerSettings()
elif event == kAction or event == kValueChanged:
plID = control.getTagID()
if plID == kGUI.BKAgeOwnerMakePublicBtn:
# This feature is not currently available in the BigKI.
try:
vault = ptVault()
myAge = self.BKConfigFolderDict[self.BKConfigListOrder[self.BKFolderSelected]]
myAgeStruct = myAge.asAgeInfoStruct()
makePublic = 1
if myAge.isPublic():
makePublic = 0
PtDebugPrint(u"xKI.ProcessNotifyAgeOwnerExpanded(): Making {} private.".format(myAge.getDisplayName()), level=kDebugDumpLevel)
else:
PtDebugPrint(u"xKI.ProcessNotifyAgeOwnerExpanded(): Making {} public.".format(myAge.getDisplayName()), level=kDebugDumpLevel)
vault.setAgePublic(myAgeStruct, makePublic)
# Let the refresh re-enable the public button.
control.disable()
except AttributeError:
PtDebugPrint(u"xKI.ProcessNotifyAgeOwnerExpanded(): Couldn't toggle public/private.", level=kErrorLevel)
elif plID == kGUI.BKAgeOwnerTitleBtn:
PtDebugPrint(u"xKI.ProcessNotifyAgeOwnerExpanded(): Change title button hit.", level=kDebugDumpLevel)
control.disable()
title = ptGUIControlTextBox(KIAgeOwnerExpanded.dialog.getControlFromTag(kGUI.BKAgeOwnerTitleTB))
title.hide()
titleEdit = ptGUIControlEditBox(KIAgeOwnerExpanded.dialog.getControlFromTag(kGUI.BKAgeOwnerTitleEditbox))
try:
# Get the selected Age config setting.
myAge = self.BKConfigFolderDict[self.BKConfigListOrder[self.BKFolderSelected]]
titleEdit.setString(myAge.getAgeUserDefinedName())
except LookupError:
titleEdit.setString("")
titleEdit.show()
titleEdit.end()
KIAgeOwnerExpanded.dialog.setFocus(titleEdit.getKey())
elif plID == kGUI.BKAgeOwnerTitleEditbox:
PtDebugPrint(u"xKI.ProcessNotifyAgeOwnerExpanded(): edit field set.", level=kDebugDumpLevel)
self.SaveAgeNameFromEdit(control)
elif event == kFocusChange:
PtDebugPrint(u"xKI.ProcessNotifyAgeOwnerExpanded(): Focus change.", level=kDebugDumpLevel)
titleEdit = ptGUIControlEditBox(KIAgeOwnerExpanded.dialog.getControlFromTag(kGUI.BKAgeOwnerTitleEditbox))
if titleEdit.isVisible():
if control is None or (control.getTagID() != kGUI.BKAgeOwnerTitleEditbox and control.getTagID() != kGUI.BKAgeOwnerTitleBtn):
self.SaveAgeNameFromEdit(titleEdit)
if control is not None:
# Check if the decription was updated.
plID = control.getTagID()
if plID == kGUI.BKAgeOwnerDescription:
self.BKAgeOwnerEditDescription = True
PtDebugPrint(u"xKI.ProcessNotifyAgeOwnerExpanded(): Start editing description.", level=kDebugDumpLevel)
else:
if self.BKAgeOwnerEditDescription:
descript = ptGUIControlMultiLineEdit(KIAgeOwnerExpanded.dialog.getControlFromTag(kGUI.BKAgeOwnerDescription))
myAge = self.BKConfigFolderDict[self.BKConfigListOrder[self.BKFolderSelected]]
if myAge is not None:
PtDebugPrint(u"xKI.ProcessNotifyAgeOwnerExpanded(): Age description updated for {}.".format(myAge.getDisplayName()), level=kDebugDumpLevel)
myAge.setAgeDescription(descript.getString())
myAge.save()
else:
PtDebugPrint(u"xKI.ProcessNotifyAgeOwnerExpanded(): Neighborhood is None while trying to update description.", level=kDebugDumpLevel)
self.BKAgeOwnerEditDescription = False
else:
if self.BKAgeOwnerEditDescription:
descript = ptGUIControlMultiLineEdit(KIAgeOwnerExpanded.dialog.getControlFromTag(kGUI.BKAgeOwnerDescription))
myAge = self.BKConfigFolderDict[self.BKConfigListOrder[self.BKFolderSelected]]
if myAge is not None:
PtDebugPrint(u"xKI.ProcessNotifyAgeOwnerExpanded(): Age description updated for {}.".format(myAge.getDisplayName()), level=kDebugDumpLevel)
buff = descript.getEncodedBuffer()
myAge.setAgeDescription(str(buff))
myAge.save()
else:
PtDebugPrint(u"xKI.ProcessNotifyAgeOwnerExpanded(): Neighborhood is None while trying to update description.", level=kDebugDumpLevel)
self.BKAgeOwnerEditDescription = False
## Process notifications originating from a YesNo dialog.
# Yes/No dialogs are omnipresent throughout Uru. Those processed here are:
# - Quitting dialog (quit/logout/cancel).
# - Deleting dialog (yes/no); various such dialogs.
# - Link offer dialog (yes/no).
# - Outside sender dialog (?).
# - KI Full dialog (OK); just a notification.
def ProcessNotifyYesNo(self, control, event):
if event == kAction or event == kValueChanged:
ynID = control.getTagID()
if self.YNWhatReason == kGUI.YNQuit:
if ynID == kGUI.YesButtonID:
PtConsole("App.Quit")
elif ynID == kGUI.NoButtonID:
KIYesNo.dialog.hide()
logoutText = ptGUIControlTextBox(KIYesNo.dialog.getControlFromTag(kGUI.YesNoLogoutTextID))
logoutText.hide()
logoutButton = ptGUIControlButton(KIYesNo.dialog.getControlFromTag(kGUI.YesNoLogoutButtonID))
logoutButton.hide()
elif ynID == kGUI.YesNoLogoutButtonID:
KIYesNo.dialog.hide()
logoutText = ptGUIControlTextBox(KIYesNo.dialog.getControlFromTag(kGUI.YesNoLogoutTextID))
logoutText.hide()
logoutButton = ptGUIControlButton(KIYesNo.dialog.getControlFromTag(kGUI.YesNoLogoutButtonID))
logoutButton.hide()
# Clear out all chat on microKI.
chatArea = ptGUIControlMultiLineEdit(KIMicro.dialog.getControlFromTag(kGUI.ChatDisplayArea))
chatArea.setString("")
chatArea.moveCursor(PtGUIMultiLineDirection.kBufferStart)
KIMicro.dialog.refreshAllControls()
# Clear out all chat on miniKI.
chatArea = ptGUIControlMultiLineEdit(KIMini.dialog.getControlFromTag(kGUI.ChatDisplayArea))
chatArea.setString("")
chatArea.moveCursor(PtGUIMultiLineDirection.kBufferStart)
KIMini.dialog.refreshAllControls()
linkmgr = ptNetLinkingMgr()
ageLink = ptAgeLinkStruct()
ageInfo = ptAgeInfoStruct()
ageInfo.setAgeFilename("StartUp")
spawnPoint = ptSpawnPointInfo()
spawnPoint.setName("LinkInPointDefault")
ageLink.setAgeInfo(ageInfo)
ageLink.setSpawnPoint(spawnPoint)
ageLink.setLinkingRules(PtLinkingRules.kBasicLink)
linkmgr.linkToAge(ageLink)
elif self.YNWhatReason == kGUI.YNDelete:
if ynID == kGUI.YesButtonID:
# Remove the current element
if self.BKCurrentContent is not None:
delFolder = self.BKCurrentContent.getParent()
delElem = self.BKCurrentContent.getChild()
if delFolder is not None and delElem is not None:
# Are we removing a visitor from an Age we own?
tFolder = delFolder.upcastToFolderNode()
if tFolder is not None and tFolder.folderGetType() == PtVaultStandardNodes.kCanVisitFolder:
PtDebugPrint(u"xKI.ProcessNotifyYesNo(): Revoking visitor.", level=kDebugDumpLevel)
delElem = delElem.upcastToPlayerInfoNode()
# Need to refind the folder that has the ageInfo in it.
ageFolderName = self.BKFolderListOrder[self.BKFolderSelected]
ageFolder = self.BKFolderLineDict[ageFolderName]
# Revoke invite.
ptVault().unInvitePlayerToAge(ageFolder.getAgeInstanceGuid(), delElem.playerGetID())
# Are we removing a player from a player list?
elif delFolder.getType() == PtVaultNodeTypes.kPlayerInfoListNode and delElem.getType() == PtVaultNodeTypes.kPlayerInfoNode:
PtDebugPrint(u"xKI.ProcessNotifyYesNo(): Removing player from folder.", level=kDebugDumpLevel)
delFolder = delFolder.upcastToPlayerInfoListNode()
delElem = delElem.upcastToPlayerInfoNode()
delFolder.playerlistRemovePlayer(delElem.playerGetID())
self.BKPlayerSelected = None
sendToField = ptGUIControlTextBox(BigKI.dialog.getControlFromTag(kGUI.BKIPlayerLine))
sendToField.setString(" ")
# Are we removing a journal entry?
else:
# See if this is a Marker Game folder that is being deleted.
if delElem.getType() == PtVaultNodeTypes.kMarkerGameNode:
if self.markerGameManager.IsActive(delElem):
self.markerGameManager.StopGame()
self.BKCurrentContent = None
delFolder.removeNode(delElem)
PtDebugPrint(u"xKI.ProcessNotifyYesNo(): Deleting element from folder.", level=kDebugDumpLevel)
else:
PtDebugPrint(u"xKI.ProcessNotifyYesNo(): Tried to delete bad Vault node or delete from bad folder.", level=kErrorLevel)
self.ChangeBigKIMode(kGUI.BKListMode)
self.RefreshPlayerList()
self.YNWhatReason = kGUI.YNQuit
KIYesNo.dialog.hide()
elif self.YNWhatReason == kGUI.YNOfferLink:
self.YNWhatReason = kGUI.YNQuit
KIYesNo.dialog.hide()
if ynID == kGUI.YesButtonID:
if self.offerLinkFromWho is not None:
PtDebugPrint(u"xKI.ProcessNotifyYesNo(): Linking to offered age {}.".format(self.offerLinkFromWho.getDisplayName()), level=kDebugDumpLevel)
link = ptAgeLinkStruct()
link.setLinkingRules(PtLinkingRules.kBasicLink)
link.setAgeInfo(self.offerLinkFromWho)
ptNetLinkingMgr().linkToAge(link)
self.offerLinkFromWho = None
self.offerLinkFromWho = None
elif self.YNWhatReason == kGUI.YNOutside:
self.YNWhatReason = kGUI.YNQuit
KIYesNo.dialog.hide()
if self.YNOutsideSender is not None:
note = ptNotify(self.key)
note.clearReceivers()
note.addReceiver(self.YNOutsideSender)
note.netPropagate(0)
note.netForce(0)
# Is it a good return?
if ynID == kGUI.YesButtonID:
note.setActivate(1)
note.addVarNumber("YesNo", 1)
# Or a bad return?
elif ynID == kGUI.NoButtonID:
note.setActivate(0)
note.addVarNumber("YesNo", 0)
note.send()
self.YNOutsideSender = None
elif self.YNWhatReason == kGUI.YNKIFull:
KIYesNo.dialog.hide()
yesButton = ptGUIControlButton(KIYesNo.dialog.getControlFromTag(kGUI.YesButtonID))
yesButton.show()
yesBtnText = ptGUIControlTextBox(KIYesNo.dialog.getControlFromTag(kGUI.YesButtonTextID))
yesBtnText.show()
noBtnText = ptGUIControlTextBox(KIYesNo.dialog.getControlFromTag(kGUI.NoButtonTextID))
noBtnText.setStringW(PtGetLocalizedString("KI.YesNoDialog.NOButton"))
self.YNWhatReason = kGUI.YNQuit
else:
self.YNWhatReason = kGUI.YNQuit
KIYesNo.dialog.hide()
self.YNOutsideSender = None
elif event == kExitMode:
self.YNWhatReason = kGUI.YNQuit
KIYesNo.dialog.hide()
self.YNOutsideSender = None
## Process notifications originating from a new item alert dialog.
# Such alerts make either the KI's icon or the Yeesha Book icon
# flash for a while.
def ProcessNotifyNewItemAlert(self, control, event):
if event == kDialogLoaded:
kiAlert = ptGUIControlButton(NewItemAlert.dialog.getControlFromTag(kAlertKIAlert))
kiAlert.disable()
kiAlert.hide()
bookalert = ptGUIControlButton(NewItemAlert.dialog.getControlFromTag(kAlertBookAlert))
bookalert.disable()
bookalert.hide()
elif event == kShowHide:
if control.isEnabled():
self.AlertStartTimer()
## Process notifications originating from the Marker Game creation GUI.
# This gets the values submitted by the player and passes them to the
# Marker Game manager.
def ProcessNotifyCreateMarkerGameGUI(self, control, event):
if control:
tagID = control.getTagID()
if event == kDialogLoaded:
self.markerGameDefaultColor = ptGUIControlTextBox(KICreateMarkerGameGUI.dialog.getControlFromTag(kGUI.MarkerGameLabel1)).getForeColor()
self.markerGameSelectedColor = ptGUIControlTextBox(KICreateMarkerGameGUI.dialog.getControlFromTag(kGUI.MarkerGameLabel1)).getSelectColor()
elif event == kShowHide:
self.InitMarkerGameGUI()
PtDebugPrint(u"xKI.ProcessNotifyCreateMarkerGameGUI(): Marker Game dialog is showing or hiding.", level=kDebugDumpLevel)
elif event == kAction or event == kValueChanged:
if tagID == kGUI.MarkerGameType1 or tagID == kGUI.MarkerGameType2 or tagID == kGUI.MarkerGameType3:
self.SelectMarkerType(tagID)
elif tagID == kGUI.CreateMarkerGameCancelBT:
KIMarkerGameGUIClose.run(self.key, netPropagate=0)
elif kGUI.CreateMarkerGameSubmitBT:
markerGameNameText = ptGUIControlEditBox(KICreateMarkerGameGUI.dialog.getControlFromTag(kGUI.CreateMarkerGameNameEB)).getStringW()
try:
markerGameType = kGUI.MarkerGameStates[self.selectedMGType]
except:
markerGameType = 0
PtDebugPrint(u"xKI.ProcessNotifyCreateMarkerGameGUI(): Couldn't find marker game type, so setting it to Quest Mode.", level=kWarningLevel)
self.FinishCreateMarkerGame(markerGameNameText)
KIMarkerGameGUIClose.run(self.key, netPropagate=0)
## Processes notifications originating from an expanded Marker Game mode in the BigKI.
# This handles the edit buttons, marker saving buttons, deletion buttons,
# etc..
def ProcessNotifyMarkerFolderExpanded(self, control, event):
mgr = self.markerGameManager
if event == kDialogLoaded:
typeField = ptGUIControlTextBox(KIMarkerFolderExpanded.dialog.getControlFromTag(kGUI.MarkerFolderGameTimeTB))
typeField.setString(kLoc.MarkerFolderPopupMenu[self.markerGameTimeID][0])
elif event == kShowHide:
# Reset the edit text lines.
if control.isEnabled():
titleEdit = ptGUIControlEditBox(KIMarkerFolderExpanded.dialog.getControlFromTag(kGUI.MarkerFolderTitleEB))
titleEdit.hide()
markerEdit = ptGUIControlEditBox(KIMarkerFolderExpanded.dialog.getControlFromTag(kGUI.MarkerFolderMarkerTextEB))
markerEdit.hide()
self.BigKIDisplayMarkerGame()
elif event == kAction or event == kValueChanged:
mFldrID = control.getTagID()
if mFldrID == kGUI.MarkerFolderEditStartGame:
mgr.LoadGame(self.BKCurrentContent)
# Is it the "Edit" button?
if self.MFdialogMode == kGames.MFOverview:
mgr.BeginEditingMarkers()
self.SetWorkingToCurrentMarkerGame()
# Is it the "Done Editing" button?
elif self.MFdialogMode == kGames.MFEditing:
mgr.FinishEditingMarkers()
self.ResetWorkingMarkerGame()
# Is it the "Stop Game" button?
elif self.MFdialogMode == kGames.MFPlaying:
mgr.StopGame(reset=False)
# Is it the "Save Marker" button?
elif self.MFdialogMode == kGames.MFEditingMarker:
# Should already be saved, just clear selection for now.
mgr.selected_marker_id = -1
self.BigKICheckContentRefresh(self.BKCurrentContent)
elif mFldrID == kGUI.MarkerFolderPlayEndGame:
mgr.LoadGame(self.BKCurrentContent)
# Is it the "Play Game" button?
if self.MFdialogMode == kGames.MFOverview:
mgr.Play()
# Is it the "Add Marker" button?
elif self.MFdialogMode == kGames.MFEditing:
self.CreateAMarker()
# Is it the "Reset Game" button?
elif self.MFdialogMode == kGames.MFPlaying:
mgr.StopGame(reset=True)
# Is it the "Remove Marker" button?
elif self.MFdialogMode == kGames.MFEditingMarker:
mgr.DeleteMarker(mgr.selected_marker_id)
self.BigKICheckContentRefresh(self.BKCurrentContent)
elif mFldrID == kGUI.MarkerFolderMarkListbox:
mgr.LoadGame(self.BKCurrentContent)
if not mgr.playing:
# NOTE: We must use selected_marker_index because marker IDs don't necessarily
# match up with the indices used in the GUI
mgr.selected_marker_index = control.getSelection()
self.BigKICheckContentRefresh(self.BKCurrentContent)
elif mFldrID == kGUI.MarkerFolderTitleBtn:
control.disable()
title = ptGUIControlTextBox(KIMarkerFolderExpanded.dialog.getControlFromTag(kGUI.MarkerFolderTitleText))
titleEdit = ptGUIControlEditBox(KIMarkerFolderExpanded.dialog.getControlFromTag(kGUI.MarkerFolderTitleEB))
titleEdit.setStringW(title.getStringW())
title.hide()
titleEdit.show()
titleEdit.end()
KIMarkerFolderExpanded.dialog.setFocus(titleEdit.getKey())
elif mFldrID == kGUI.MarkerFolderTitleEB:
self.SaveMarkerGameNameFromEdit(control)
self.BigKICheckContentRefresh(self.BKCurrentContent)
elif mFldrID == kGUI.MarkerFolderMarkerTextBtn:
control.disable()
title = ptGUIControlTextBox(KIMarkerFolderExpanded.dialog.getControlFromTag(kGUI.MarkerFolderMarkerTextTB))
titleEdit = ptGUIControlEditBox(KIMarkerFolderExpanded.dialog.getControlFromTag(kGUI.MarkerFolderMarkerTextEB))
titleEdit.setStringW(title.getStringW())
title.hide()
titleEdit.show()
titleEdit.end()
KIMarkerFolderExpanded.dialog.setFocus(titleEdit.getKey())
elif mFldrID == kGUI.MarkerFolderMarkerTextEB:
self.SaveMarkerTextFromEdit(control)
self.BigKICheckContentRefresh(self.BKCurrentContent)
elif mFldrID == kGUI.MarkerFolderTimePullDownBtn or mFldrID == kGUI.MarkerFolderTimeArrow:
KIMarkerFolderPopupMenu.menu.show()
elif mFldrID == kGUI.MarkerFolderDeleteBtn:
self.YNWhatReason = kGUI.YNDelete
elem = self.BKCurrentContent.getChild()
elem = elem.upcastToMarkerGameNode()
if elem is not None:
mfTitle = elem.getGameName()
else:
mfTitle = "<unknown>"
yesText = ptGUIControlTextBox(KIYesNo.dialog.getControlFromTag(kGUI.YesNoTextID))
yesText.setStringW(PtGetLocalizedString("KI.Messages.DeletePicture", [xCensor.xCensor(mfTitle, self.censorLevel)]))
self.LocalizeDialog(1)
KIYesNo.dialog.show()
elif event == kFocusChange:
titleEdit = ptGUIControlEditBox(KIMarkerFolderExpanded.dialog.getControlFromTag(kGUI.MarkerFolderTitleEB))
# Is the editbox enabled and something other than the button is getting the focus?
if titleEdit.isVisible():
if control is None or (control.getTagID() != kGUI.MarkerFolderTitleEB and control.getTagID() != kGUI.MarkerFolderTitleBtn):
self.SaveMarkerGameNameFromEdit(titleEdit)
if self.MFdialogMode == kGames.MFEditingMarker:
titleEdit = ptGUIControlEditBox(KIMarkerFolderExpanded.dialog.getControlFromTag(kGUI.MarkerFolderMarkerTextEB))
# Is the editbox enabled and something other than the button is getting the focus?
if titleEdit.isVisible():
if control is None or (control.getTagID() != kGUI.MarkerFolderMarkerTextEB and control.getTagID() != kGUI.MarkerFolderMarkerTextBtn):
self.SaveMarkerTextFromEdit(titleEdit)
self.BigKICheckContentRefresh(self.BKCurrentContent)
## Processes notifications originating from the Marker Game popup menu.
# (What is this? Is it used?)
def ProcessNotifyMarkerFolderPopupMenu(self, control, event):
if event == kDialogLoaded:
for menuItem in kLoc.MarkerFolderPopupMenu:
KIMarkerFolderPopupMenu.menu.addNotifyItem(menuItem[0])
elif event == kAction:
menuID = control.getTagID()
self.markerGameTimeID = menuID
typeField = ptGUIControlTextBox(KIMarkerFolderExpanded.dialog.getControlFromTag(kGUI.MarkerFolderGameTimeTB))
typeField.setString(kLoc.MarkerFolderPopupMenu[self.markerGameTimeID][0])
# Save the current Marker Game to this type of game.
if self.BKCurrentContent is not None:
element = self.BKCurrentContent.getChild()
if element is not None:
datatype = element.getType()
if datatype == PtVaultNodeTypes.kMarkerGameNode:
element = element.upcastToMarkerGameNode()
if element:
element.setRoundLength(kLoc.MarkerFolderPopupMenu[self.markerGameTimeID][1])
element.save()
elif event == kExitMode:
if KIMarkerFolderPopupMenu.menu.isEnabled():
KIMarkerFolderPopupMenu.menu.hide()
## Processes notifications originating from the Jalak GUI.
# These controls are only used within the Age of Jalak, obviously.
def ProcessNotifyJalakGUI(self, control, event):
if event == kDialogLoaded:
self.JalakGUIInit()
elif event == kAction or event == kValueChanged:
if control is not None:
tagID = control.getTagID()
btn = str(tagID)
if btn in JalakBtnStates:
KIJalakBtnLights.run(self.key, state=btn, netPropagate=0)
self.SetJalakGUIButtons(0)
#~~~~~~~~~~~~~~~~~~~#
# Vault Type Events #
#~~~~~~~~~~~~~~~~~~~#
## Handles the passed vault type event.
# This is used to react to saved nodes, new nodes, etc.
def HandleVaultTypeEvents(self, event, tupData):
# Make sure that the BigKI dialog is loaded before trying to update it.
if not PtIsDialogLoaded("KIMain"):
PtDebugPrint(u"xKI.HandleVaultTypeEvents(): BigKI dialog was not loaded, waiting.", level=kDebugDumpLevel)
return
if event == PtVaultCallbackTypes.kVaultConnected:
PtDebugPrint(u"xKI.HandleVaultTypeEvents(): Connected to the Vault.", level=kDebugDumpLevel)
elif event == PtVaultCallbackTypes.kVaultDisconnected:
PtDebugPrint(u"xKI.HandleVaultTypeEvents(): Disconnected from the Vault.", level=kDebugDumpLevel)
elif event == PtVaultCallbackTypes.kVaultNodeSaved:
PtDebugPrint(u"xKI.HandleVaultTypeEvents(): A node is being saved (ID = {}, type = {}).".format(tupData[0].getID(), tupData[0].getType()), level=kDebugDumpLevel)
if tupData[0].getType() == PtVaultNodeTypes.kPlayerInfoNode:
self.RefreshPlayerList()
elif tupData[0].getType() == PtVaultNodeTypes.kAgeInfoNode:
self.BigKISetStatics()
self.BigKIRefreshFolderList()
self.BigKIOnlySelectedToButtons()
self.RefreshAgeOwnerSettings()
self.BigKIRefreshContentList()
self.BigKIRefreshContentListDisplay()
elif event == PtVaultCallbackTypes.kVaultNodeInitialized:
PtDebugPrint(u"xKI.HandleVaultTypeEvents(): A node has been initalized (ID = {}, type = {}).".format(tupData[0].getID(), tupData[0].getType()), level=kDebugDumpLevel)
if self.KILevel > kMicroKI:
self.BigKICheckElementRefresh(tupData[0])
elif event == PtVaultCallbackTypes.kVaultNodeAdded:
PtDebugPrint(u"xKI.HandleVaultTypeEvents(): A node has been added.", level=kDebugDumpLevel)
elif event == PtVaultCallbackTypes.kVaultNodeRefAdded:
PtDebugPrint(u"xKI.HandleVaultTypeEvents(): A node reference has been added (childID = {}, parentID = {}).".format(tupData[0].getChildID(), tupData[0].getParentID()), level=kDebugDumpLevel)
if self.KILevel > kMicroKI:
folder = tupData[0].getParent()
folder = folder.upcastToFolderNode()
# If the parent of this ref is the Inbox, then it's incoming mail.
if folder is not None and folder.folderGetType() == PtVaultStandardNodes.kInboxFolder:
self.AlertKIStart()
# Note: beenSeen() is not yet implemented.
if not tupData[0].beenSeen():
if self.onlyGetPMsFromBuddies:
vault = ptVault()
buddies = vault.getBuddyListFolder()
if buddies.playerlistHasPlayer(tupData[0].getSaverID()):
# then show alert
self.AlertKIStart()
else:
self.AlertKIStart()
child = tupData[0].getChild()
child = child.upcastToFolderNode()
if child is not None:
PtDebugPrint(u"xKI.HandleVaultTypeEvents(): Adding a folder, refresh folder list.", level=kDebugDumpLevel)
self.BigKIRefreshFolderList()
self.BigKICheckFolderRefresh(folder)
elif event == PtVaultCallbackTypes.kVaultRemovingNodeRef:
PtDebugPrint(u"xKI.HandleVaultTypeEvents(): A node reference is being removed (childID = {}, parentID = {}).".format(tupData[0].getChildID(), tupData[0].getParentID()), level=kDebugDumpLevel)
elif event == PtVaultCallbackTypes.kVaultNodeRefRemoved:
PtDebugPrint(u"xKI.HandleVaultTypeEvents(): A node reference has been removed (childID, parentID): ", tupData, level=kDebugDumpLevel)
if self.KILevel > kMicroKI:
if self.BKRightSideMode == kGUI.BKMarkerListExpanded:
self.BigKIDisplayMarkerGame()
self.BigKICheckFolderRefresh()
elif event == PtVaultCallbackTypes.kVaultOperationFailed:
PtDebugPrint(u"xKI.HandleVaultTypeEvents(): A Vault operation failed (operation, resultCode): ", tupData, level=kDebugDumpLevel)
else:
PtDebugPrint(u"xKI.HandleVaultTypeEvents(): Unknown Vault event: {}.".format(event), level=kWarningLevel)
| gpl-3.0 |
matthewlent/ng-boilerplate-flask | venv/lib/python2.7/site-packages/setuptools/command/install_egg_info.py | 115 | 3825 | from setuptools import Command
from setuptools.archive_util import unpack_archive
from distutils import log, dir_util
import os, pkg_resources
class install_egg_info(Command):
"""Install an .egg-info directory for the package"""
description = "Install an .egg-info directory for the package"
user_options = [
('install-dir=', 'd', "directory to install to"),
]
def initialize_options(self):
self.install_dir = None
def finalize_options(self):
self.set_undefined_options('install_lib',('install_dir','install_dir'))
ei_cmd = self.get_finalized_command("egg_info")
basename = pkg_resources.Distribution(
None, None, ei_cmd.egg_name, ei_cmd.egg_version
).egg_name()+'.egg-info'
self.source = ei_cmd.egg_info
self.target = os.path.join(self.install_dir, basename)
self.outputs = [self.target]
def run(self):
self.run_command('egg_info')
target = self.target
if os.path.isdir(self.target) and not os.path.islink(self.target):
dir_util.remove_tree(self.target, dry_run=self.dry_run)
elif os.path.exists(self.target):
self.execute(os.unlink,(self.target,),"Removing "+self.target)
if not self.dry_run:
pkg_resources.ensure_directory(self.target)
self.execute(self.copytree, (),
"Copying %s to %s" % (self.source, self.target)
)
self.install_namespaces()
def get_outputs(self):
return self.outputs
def copytree(self):
# Copy the .egg-info tree to site-packages
def skimmer(src,dst):
# filter out source-control directories; note that 'src' is always
# a '/'-separated path, regardless of platform. 'dst' is a
# platform-specific path.
for skip in '.svn/','CVS/':
if src.startswith(skip) or '/'+skip in src:
return None
self.outputs.append(dst)
log.debug("Copying %s to %s", src, dst)
return dst
unpack_archive(self.source, self.target, skimmer)
def install_namespaces(self):
nsp = self._get_all_ns_packages()
if not nsp: return
filename,ext = os.path.splitext(self.target)
filename += '-nspkg.pth'; self.outputs.append(filename)
log.info("Installing %s",filename)
if not self.dry_run:
f = open(filename,'wt')
for pkg in nsp:
# ensure pkg is not a unicode string under Python 2.7
pkg = str(pkg)
pth = tuple(pkg.split('.'))
trailer = '\n'
if '.' in pkg:
trailer = (
"; m and setattr(sys.modules[%r], %r, m)\n"
% ('.'.join(pth[:-1]), pth[-1])
)
f.write(
"import sys,types,os; "
"p = os.path.join(sys._getframe(1).f_locals['sitedir'], "
"*%(pth)r); "
"ie = os.path.exists(os.path.join(p,'__init__.py')); "
"m = not ie and "
"sys.modules.setdefault(%(pkg)r,types.ModuleType(%(pkg)r)); "
"mp = (m or []) and m.__dict__.setdefault('__path__',[]); "
"(p not in mp) and mp.append(p)%(trailer)s"
% locals()
)
f.close()
def _get_all_ns_packages(self):
nsp = {}
for pkg in self.distribution.namespace_packages or []:
pkg = pkg.split('.')
while pkg:
nsp['.'.join(pkg)] = 1
pkg.pop()
nsp=list(nsp)
nsp.sort() # set up shorter names first
return nsp
| mit |
jeremiahyan/odoo | addons/web_unsplash/controllers/main.py | 5 | 6003 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import base64
import logging
import mimetypes
import requests
import werkzeug.utils
from odoo import http, tools, _
from odoo.http import request
from odoo.tools.mimetypes import guess_mimetype
from werkzeug.urls import url_encode
logger = logging.getLogger(__name__)
class Web_Unsplash(http.Controller):
def _get_access_key(self):
if request.env.user._has_unsplash_key_rights():
return request.env['ir.config_parameter'].sudo().get_param('unsplash.access_key')
raise werkzeug.exceptions.NotFound()
def _notify_download(self, url):
''' Notifies Unsplash from an image download. (API requirement)
:param url: the download_url of the image to be notified
This method won't return anything. This endpoint should just be
pinged with a simple GET request for Unsplash to increment the image
view counter.
'''
try:
if not url.startswith('https://api.unsplash.com/photos/'):
raise Exception(_("ERROR: Unknown Unsplash notify URL!"))
access_key = self._get_access_key()
requests.get(url, params=url_encode({'client_id': access_key}))
except Exception as e:
logger.exception("Unsplash download notification failed: " + str(e))
# ------------------------------------------------------
# add unsplash image url
# ------------------------------------------------------
@http.route('/web_unsplash/attachment/add', type='json', auth='user', methods=['POST'])
def save_unsplash_url(self, unsplashurls=None, **kwargs):
"""
unsplashurls = {
image_id1: {
url: image_url,
download_url: download_url,
},
image_id2: {
url: image_url,
download_url: download_url,
},
.....
}
"""
def slugify(s):
''' Keeps only alphanumeric characters, hyphens and spaces from a string.
The string will also be truncated to 1024 characters max.
:param s: the string to be filtered
:return: the sanitized string
'''
return "".join([c for c in s if c.isalnum() or c in list("- ")])[:1024]
if not unsplashurls:
return []
uploads = []
Attachments = request.env['ir.attachment']
query = kwargs.get('query', '')
query = slugify(query)
res_model = kwargs.get('res_model', 'ir.ui.view')
if res_model != 'ir.ui.view' and kwargs.get('res_id'):
res_id = int(kwargs['res_id'])
else:
res_id = None
for key, value in unsplashurls.items():
url = value.get('url')
try:
if not url.startswith('https://images.unsplash.com/'):
logger.exception("ERROR: Unknown Unsplash URL!: " + url)
raise Exception(_("ERROR: Unknown Unsplash URL!"))
req = requests.get(url)
if req.status_code != requests.codes.ok:
continue
# get mime-type of image url because unsplash url dosn't contains mime-types in url
image_base64 = base64.b64encode(req.content)
except requests.exceptions.ConnectionError as e:
logger.exception("Connection Error: " + str(e))
continue
except requests.exceptions.Timeout as e:
logger.exception("Timeout: " + str(e))
continue
image_base64 = tools.image_process(image_base64, verify_resolution=True)
mimetype = guess_mimetype(base64.b64decode(image_base64))
# append image extension in name
query += mimetypes.guess_extension(mimetype) or ''
# /unsplash/5gR788gfd/lion
url_frags = ['unsplash', key, query]
attachment = Attachments.create({
'name': '_'.join(url_frags),
'url': '/' + '/'.join(url_frags),
'mimetype': mimetype,
'datas': image_base64,
'public': res_model == 'ir.ui.view',
'res_id': res_id,
'res_model': res_model,
'description': value.get('description'),
})
attachment.generate_access_token()
uploads.append(attachment._get_media_info())
# Notifies Unsplash from an image download. (API requirement)
self._notify_download(value.get('download_url'))
return uploads
@http.route("/web_unsplash/fetch_images", type='json', auth="user")
def fetch_unsplash_images(self, **post):
access_key = self._get_access_key()
app_id = self.get_unsplash_app_id()
if not access_key or not app_id:
return {'error': 'key_not_found'}
post['client_id'] = access_key
response = requests.get('https://api.unsplash.com/search/photos/', params=url_encode(post))
if response.status_code == requests.codes.ok:
return response.json()
else:
return {'error': response.status_code}
@http.route("/web_unsplash/get_app_id", type='json', auth="public")
def get_unsplash_app_id(self, **post):
return request.env['ir.config_parameter'].sudo().get_param('unsplash.app_id')
@http.route("/web_unsplash/save_unsplash", type='json', auth="user")
def save_unsplash(self, **post):
if request.env.user._has_unsplash_key_rights():
request.env['ir.config_parameter'].sudo().set_param('unsplash.app_id', post.get('appId'))
request.env['ir.config_parameter'].sudo().set_param('unsplash.access_key', post.get('key'))
return True
raise werkzeug.exceptions.NotFound()
| gpl-3.0 |
grnet/synnefo | snf-astakos-app/setup.py | 1 | 2986 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2010-2016 GRNET S.A.
#
# 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/>.
"""Packaging module for snf-astakos-app"""
import os
from imp import load_source
from setuptools import setup, find_packages
HERE = os.path.abspath(os.path.normpath(os.path.dirname(__file__)))
VERSION_PY = os.path.join(HERE, 'astakos', 'version.py')
# Package info
VERSION = getattr(load_source('version', VERSION_PY), '__version__')
SHORT_DESCRIPTION = 'Synnefo Identity Management component'
PACKAGES_ROOT = '.'
PACKAGES = find_packages(PACKAGES_ROOT)
# Package meta
CLASSIFIERS = [
'Development Status :: 3 - Alpha',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Utilities',
'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',
]
# Package requirements
INSTALL_REQUIRES = [
'Django>=1.7, <1.8',
'httplib2>=0.6.0',
'python-dateutil>=1.4.1',
'snf-common',
'django-tables2',
'recaptcha-client>=1.0.5',
'django-ratelimit',
'requests',
'requests-oauthlib',
'snf-django-lib',
'snf-branding',
'snf-webproject',
]
EXTRAS_REQUIRES = {
}
TESTS_REQUIRES = [
]
setup(
name='snf-astakos-app',
version=VERSION,
license='GNU GPLv3',
url='http://www.synnefo.org/',
description=SHORT_DESCRIPTION,
classifiers=CLASSIFIERS,
author='Synnefo development team',
author_email='synnefo-devel@googlegroups.com',
maintainer='Synnefo development team',
maintainer_email='synnefo-devel@googlegroups.com',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=INSTALL_REQUIRES,
dependency_links=['http://www.synnefo.org/packages/pypi'],
scripts=['astakos/scripts/snf-component-register'],
entry_points={
'synnefo': [
'default_settings = astakos.synnefo_settings',
'web_apps = astakos.synnefo_settings:installed_apps',
'web_middleware = astakos.synnefo_settings:middlware_classes',
'web_context_processors = astakos.synnefo_settings:context_processors',
'urls = astakos.urls:urlpatterns',
'web_static = astakos.synnefo_settings:static_files'
],
'console_scripts': [
'snf-service-export = astakos.scripts.snf_service_export:main',
],
}
)
| gpl-3.0 |
zhanqxun/cv_fish | numpy/distutils/tests/test_misc_util.py | 47 | 3348 | #!/usr/bin/env python
from __future__ import division, absolute_import, print_function
from os.path import join, sep, dirname
from numpy.distutils.misc_util import (
appendpath, minrelpath, gpaths, get_shared_lib_extension, get_info
)
from numpy.testing import (
TestCase, run_module_suite, assert_, assert_equal
)
ajoin = lambda *paths: join(*((sep,)+paths))
class TestAppendpath(TestCase):
def test_1(self):
assert_equal(appendpath('prefix', 'name'), join('prefix', 'name'))
assert_equal(appendpath('/prefix', 'name'), ajoin('prefix', 'name'))
assert_equal(appendpath('/prefix', '/name'), ajoin('prefix', 'name'))
assert_equal(appendpath('prefix', '/name'), join('prefix', 'name'))
def test_2(self):
assert_equal(appendpath('prefix/sub', 'name'),
join('prefix', 'sub', 'name'))
assert_equal(appendpath('prefix/sub', 'sup/name'),
join('prefix', 'sub', 'sup', 'name'))
assert_equal(appendpath('/prefix/sub', '/prefix/name'),
ajoin('prefix', 'sub', 'name'))
def test_3(self):
assert_equal(appendpath('/prefix/sub', '/prefix/sup/name'),
ajoin('prefix', 'sub', 'sup', 'name'))
assert_equal(appendpath('/prefix/sub/sub2', '/prefix/sup/sup2/name'),
ajoin('prefix', 'sub', 'sub2', 'sup', 'sup2', 'name'))
assert_equal(appendpath('/prefix/sub/sub2', '/prefix/sub/sup/name'),
ajoin('prefix', 'sub', 'sub2', 'sup', 'name'))
class TestMinrelpath(TestCase):
def test_1(self):
n = lambda path: path.replace('/', sep)
assert_equal(minrelpath(n('aa/bb')), n('aa/bb'))
assert_equal(minrelpath('..'), '..')
assert_equal(minrelpath(n('aa/..')), '')
assert_equal(minrelpath(n('aa/../bb')), 'bb')
assert_equal(minrelpath(n('aa/bb/..')), 'aa')
assert_equal(minrelpath(n('aa/bb/../..')), '')
assert_equal(minrelpath(n('aa/bb/../cc/../dd')), n('aa/dd'))
assert_equal(minrelpath(n('.././..')), n('../..'))
assert_equal(minrelpath(n('aa/bb/.././../dd')), n('dd'))
class TestGpaths(TestCase):
def test_gpaths(self):
local_path = minrelpath(join(dirname(__file__), '..'))
ls = gpaths('command/*.py', local_path)
assert_(join(local_path, 'command', 'build_src.py') in ls, repr(ls))
f = gpaths('system_info.py', local_path)
assert_(join(local_path, 'system_info.py') == f[0], repr(f))
class TestSharedExtension(TestCase):
def test_get_shared_lib_extension(self):
import sys
ext = get_shared_lib_extension(is_python_ext=False)
if sys.platform.startswith('linux'):
assert_equal(ext, '.so')
elif sys.platform.startswith('gnukfreebsd'):
assert_equal(ext, '.so')
elif sys.platform.startswith('darwin'):
assert_equal(ext, '.dylib')
elif sys.platform.startswith('win'):
assert_equal(ext, '.dll')
# just check for no crash
assert_(get_shared_lib_extension(is_python_ext=True))
def test_installed_npymath_ini():
# Regression test for gh-7707. If npymath.ini wasn't installed, then this
# will give an error.
info = get_info('npymath')
if __name__ == "__main__":
run_module_suite()
| apache-2.0 |
JimCircadian/ansible | lib/ansible/modules/cloud/vmware/vmware_tag_facts.py | 10 | 3867 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, Ansible Project
# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: vmware_tag_facts
short_description: Manage VMware tag facts
description:
- This module can be used to collect facts about VMware tags.
- Tag feature is introduced in vSphere 6 version, so this module is not supported in the earlier versions of vSphere.
- All variables and VMware object names are case sensitive.
version_added: '2.6'
author:
- Abhijeet Kasurde (@Akasurde)
notes:
- Tested on vSphere 6.5
requirements:
- python >= 2.6
- PyVmomi
- vSphere Automation SDK
- vCloud Suite SDK
extends_documentation_fragment: vmware_rest_client.documentation
'''
EXAMPLES = r'''
- name: Get facts about tag
vmware_tag_facts:
hostname: 10.65.223.91
username: administrator@vsphere.local
password: Esxi@123$
validate_certs: False
- name: Get category id from the given tag
vmware_tag_facts:
hostname: 10.65.223.91
username: administrator@vsphere.local
password: Esxi@123$
validate_certs: False
register: tag_details
- debug:
msg: "{{ tag_details.tag_facts['fedora_machines']['tag_category_id'] }}"
'''
RETURN = r'''
results:
description: dictionary of tag metadata
returned: on success
type: dict
sample: {
"Sample_Tag_0002": {
"tag_category_id": "urn:vmomi:InventoryServiceCategory:6de17f28-7694-43ec-a783-d09c141819ae:GLOBAL",
"tag_description": "Sample Description",
"tag_id": "urn:vmomi:InventoryServiceTag:a141f212-0f82-4f05-8eb3-c49647c904c5:GLOBAL",
"tag_used_by": []
},
"fedora_machines": {
"tag_category_id": "urn:vmomi:InventoryServiceCategory:baa90bae-951b-4e87-af8c-be681a1ba30c:GLOBAL",
"tag_description": "",
"tag_id": "urn:vmomi:InventoryServiceTag:7d27d182-3ecd-4200-9d72-410cc6398a8a:GLOBAL",
"tag_used_by": []
},
"ubuntu_machines": {
"tag_category_id": "urn:vmomi:InventoryServiceCategory:89573410-29b4-4cac-87a4-127c084f3d50:GLOBAL",
"tag_description": "",
"tag_id": "urn:vmomi:InventoryServiceTag:7f3516d5-a750-4cb9-8610-6747eb39965d:GLOBAL",
"tag_used_by": []
}
}
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.vmware_rest_client import VmwareRestClient
try:
from com.vmware.cis.tagging_client import Tag
except ImportError:
pass
class VmTagFactManager(VmwareRestClient):
def __init__(self, module):
"""Constructor."""
super(VmTagFactManager, self).__init__(module)
self.tag_service = Tag(self.connect)
self.global_tags = dict()
def get_all_tags(self):
"""Function to retrieve all tag information."""
for tag in self.tag_service.list():
tag_obj = self.tag_service.get(tag)
self.global_tags[tag_obj.name] = dict(
tag_description=tag_obj.description,
tag_used_by=tag_obj.used_by,
tag_category_id=tag_obj.category_id,
tag_id=tag_obj.id
)
self.module.exit_json(changed=False, tag_facts=self.global_tags)
def main():
argument_spec = VmwareRestClient.vmware_client_argument_spec()
module = AnsibleModule(argument_spec=argument_spec,
supports_check_mode=True)
vmware_tag_facts = VmTagFactManager(module)
vmware_tag_facts.get_all_tags()
if __name__ == '__main__':
main()
| gpl-3.0 |
williamfdevine/PrettyLinux | tools/perf/tests/attr.py | 1266 | 9424 | #! /usr/bin/python
import os
import sys
import glob
import optparse
import tempfile
import logging
import shutil
import ConfigParser
class Fail(Exception):
def __init__(self, test, msg):
self.msg = msg
self.test = test
def getMsg(self):
return '\'%s\' - %s' % (self.test.path, self.msg)
class Unsup(Exception):
def __init__(self, test):
self.test = test
def getMsg(self):
return '\'%s\'' % self.test.path
class Event(dict):
terms = [
'cpu',
'flags',
'type',
'size',
'config',
'sample_period',
'sample_type',
'read_format',
'disabled',
'inherit',
'pinned',
'exclusive',
'exclude_user',
'exclude_kernel',
'exclude_hv',
'exclude_idle',
'mmap',
'comm',
'freq',
'inherit_stat',
'enable_on_exec',
'task',
'watermark',
'precise_ip',
'mmap_data',
'sample_id_all',
'exclude_host',
'exclude_guest',
'exclude_callchain_kernel',
'exclude_callchain_user',
'wakeup_events',
'bp_type',
'config1',
'config2',
'branch_sample_type',
'sample_regs_user',
'sample_stack_user',
]
def add(self, data):
for key, val in data:
log.debug(" %s = %s" % (key, val))
self[key] = val
def __init__(self, name, data, base):
log.debug(" Event %s" % name);
self.name = name;
self.group = ''
self.add(base)
self.add(data)
def compare_data(self, a, b):
# Allow multiple values in assignment separated by '|'
a_list = a.split('|')
b_list = b.split('|')
for a_item in a_list:
for b_item in b_list:
if (a_item == b_item):
return True
elif (a_item == '*') or (b_item == '*'):
return True
return False
def equal(self, other):
for t in Event.terms:
log.debug(" [%s] %s %s" % (t, self[t], other[t]));
if not self.has_key(t) or not other.has_key(t):
return False
if not self.compare_data(self[t], other[t]):
return False
return True
def diff(self, other):
for t in Event.terms:
if not self.has_key(t) or not other.has_key(t):
continue
if not self.compare_data(self[t], other[t]):
log.warning("expected %s=%s, got %s" % (t, self[t], other[t]))
# Test file description needs to have following sections:
# [config]
# - just single instance in file
# - needs to specify:
# 'command' - perf command name
# 'args' - special command arguments
# 'ret' - expected command return value (0 by default)
#
# [eventX:base]
# - one or multiple instances in file
# - expected values assignments
class Test(object):
def __init__(self, path, options):
parser = ConfigParser.SafeConfigParser()
parser.read(path)
log.warning("running '%s'" % path)
self.path = path
self.test_dir = options.test_dir
self.perf = options.perf
self.command = parser.get('config', 'command')
self.args = parser.get('config', 'args')
try:
self.ret = parser.get('config', 'ret')
except:
self.ret = 0
self.expect = {}
self.result = {}
log.debug(" loading expected events");
self.load_events(path, self.expect)
def is_event(self, name):
if name.find("event") == -1:
return False
else:
return True
def load_events(self, path, events):
parser_event = ConfigParser.SafeConfigParser()
parser_event.read(path)
# The event record section header contains 'event' word,
# optionaly followed by ':' allowing to load 'parent
# event' first as a base
for section in filter(self.is_event, parser_event.sections()):
parser_items = parser_event.items(section);
base_items = {}
# Read parent event if there's any
if (':' in section):
base = section[section.index(':') + 1:]
parser_base = ConfigParser.SafeConfigParser()
parser_base.read(self.test_dir + '/' + base)
base_items = parser_base.items('event')
e = Event(section, parser_items, base_items)
events[section] = e
def run_cmd(self, tempdir):
cmd = "PERF_TEST_ATTR=%s %s %s -o %s/perf.data %s" % (tempdir,
self.perf, self.command, tempdir, self.args)
ret = os.WEXITSTATUS(os.system(cmd))
log.info(" '%s' ret %d " % (cmd, ret))
if ret != int(self.ret):
raise Unsup(self)
def compare(self, expect, result):
match = {}
log.debug(" compare");
# For each expected event find all matching
# events in result. Fail if there's not any.
for exp_name, exp_event in expect.items():
exp_list = []
log.debug(" matching [%s]" % exp_name)
for res_name, res_event in result.items():
log.debug(" to [%s]" % res_name)
if (exp_event.equal(res_event)):
exp_list.append(res_name)
log.debug(" ->OK")
else:
log.debug(" ->FAIL");
log.debug(" match: [%s] matches %s" % (exp_name, str(exp_list)))
# we did not any matching event - fail
if (not exp_list):
exp_event.diff(res_event)
raise Fail(self, 'match failure');
match[exp_name] = exp_list
# For each defined group in the expected events
# check we match the same group in the result.
for exp_name, exp_event in expect.items():
group = exp_event.group
if (group == ''):
continue
for res_name in match[exp_name]:
res_group = result[res_name].group
if res_group not in match[group]:
raise Fail(self, 'group failure')
log.debug(" group: [%s] matches group leader %s" %
(exp_name, str(match[group])))
log.debug(" matched")
def resolve_groups(self, events):
for name, event in events.items():
group_fd = event['group_fd'];
if group_fd == '-1':
continue;
for iname, ievent in events.items():
if (ievent['fd'] == group_fd):
event.group = iname
log.debug('[%s] has group leader [%s]' % (name, iname))
break;
def run(self):
tempdir = tempfile.mkdtemp();
try:
# run the test script
self.run_cmd(tempdir);
# load events expectation for the test
log.debug(" loading result events");
for f in glob.glob(tempdir + '/event*'):
self.load_events(f, self.result);
# resolve group_fd to event names
self.resolve_groups(self.expect);
self.resolve_groups(self.result);
# do the expectation - results matching - both ways
self.compare(self.expect, self.result)
self.compare(self.result, self.expect)
finally:
# cleanup
shutil.rmtree(tempdir)
def run_tests(options):
for f in glob.glob(options.test_dir + '/' + options.test):
try:
Test(f, options).run()
except Unsup, obj:
log.warning("unsupp %s" % obj.getMsg())
def setup_log(verbose):
global log
level = logging.CRITICAL
if verbose == 1:
level = logging.WARNING
if verbose == 2:
level = logging.INFO
if verbose >= 3:
level = logging.DEBUG
log = logging.getLogger('test')
log.setLevel(level)
ch = logging.StreamHandler()
ch.setLevel(level)
formatter = logging.Formatter('%(message)s')
ch.setFormatter(formatter)
log.addHandler(ch)
USAGE = '''%s [OPTIONS]
-d dir # tests dir
-p path # perf binary
-t test # single test
-v # verbose level
''' % sys.argv[0]
def main():
parser = optparse.OptionParser(usage=USAGE)
parser.add_option("-t", "--test",
action="store", type="string", dest="test")
parser.add_option("-d", "--test-dir",
action="store", type="string", dest="test_dir")
parser.add_option("-p", "--perf",
action="store", type="string", dest="perf")
parser.add_option("-v", "--verbose",
action="count", dest="verbose")
options, args = parser.parse_args()
if args:
parser.error('FAILED wrong arguments %s' % ' '.join(args))
return -1
setup_log(options.verbose)
if not options.test_dir:
print 'FAILED no -d option specified'
sys.exit(-1)
if not options.test:
options.test = 'test*'
try:
run_tests(options)
except Fail, obj:
print "FAILED %s" % obj.getMsg();
sys.exit(-1)
sys.exit(0)
if __name__ == '__main__':
main()
| gpl-3.0 |
LavyshAlexander/namebench | libnamebench/provider_extensions.py | 174 | 1713 | # Copyright 2009 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tricks that depend on a certain DNS provider.
Tricks that require inheritence by nameserver.py must go here, otherwise,
see providers.py for externally available functions.
"""
__author__ = 'tstromberg@google.com (Thomas Stromberg)'
class NameServerProvider(object):
"""Inherited by nameserver."""
# myresolver.info
def GetMyResolverIpWithDuration(self):
return self.GetIpFromNameWithDuration('self.myresolver.info.')
def GetMyResolverHostNameWithDuration(self):
return self.GetNameFromNameWithDuration('self.myresolver.info.')
# OpenDNS
def GetOpenDnsNodeWithDuration(self):
return self.GetTxtRecordWithDuration('which.opendns.com.')[0:2]
def GetOpenDnsInterceptionStateWithDuration(self):
"""Check if our packets are actually getting to the correct servers."""
(node_id, duration) = self.GetOpenDnsNodeWithDuration()
if node_id and 'I am not an OpenDNS resolver' in node_id:
return (True, duration)
return (False, duration)
# UltraDNS
def GetUltraDnsNodeWithDuration(self):
return self.GetNameFromNameWithDuration('whoareyou.ultradns.net.')
| apache-2.0 |
peterfpeterson/mantid | Framework/PythonInterface/mantid/__init__.py | 3 | 3994 | # Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
# NScD Oak Ridge National Laboratory, European Spallation Source,
# Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
# SPDX - License - Identifier: GPL - 3.0 +
"""
Mantid
======
http://www.mantidproject.org
The Mantid project provides a platform that supports high-performance computing
on neutron and muon data. The framework provides a set of common services,
algorithms and data objects that are:
- Instrument or technique independent;
- Supported on multiple target platforms (Windows, Linux, Mac OS X);
- Easily extensible by Instruments Scientists/Users;
- Open source and freely redistributable to visiting scientists;
- Provides functionalities for Scripting, Visualization, Data transformation,
Implementing Algorithms, Virtual Instrument Geometry.
"""
import os
import sys
import site
from .buildconfig import check_python_version
check_python_version()
def apiVersion():
"""Indicates that this is version 2
of the API
"""
return 2
def _bin_dirs():
"""
Generate a list of possible paths that contain the Mantid.properties file
"""
_moduledir = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))
# standard packaged install
yield _moduledir
# conda layout
yield os.path.dirname(sys.executable)
# iterate over the PYTHONPATH, to scan all possible bin dirs
for path in sys.path:
yield path
# Bail out early if a Mantid.properties files is not found in
# one of the expected places - it indicates a broken installation or build.
_bindir = None
for path in _bin_dirs():
if os.path.exists(os.path.join(path, "Mantid.properties")):
_bindir = path
break
if _bindir is None:
raise ImportError(
"Broken installation! Unable to find Mantid.properties file.\n"
"Directories searched: {}".format(', '.join(_bin_dirs())))
# Windows doesn't have rpath settings so make sure the C-extensions can find the rest of the
# mantid dlls. We assume they will be next to the properties file.
if sys.platform == "win32":
os.environ["PATH"] = _bindir + ";" + os.environ.get("PATH", "")
# Make sure the config service loads this properties file
os.environ["MANTIDPATH"] = _bindir
# Add directory as a site directory to process the .pth files
site.addsitedir(_bindir)
try:
# Flag indicating whether mantidplot layer is loaded.
import _qti # noqa: F401
__gui__ = True
except ImportError:
__gui__ = False
# Set deprecation warnings back to default (they are ignored in 2.7)
import warnings as _warnings # noqa: E402
# Default we see everything
_warnings.filterwarnings("default", category=DeprecationWarning,
module="mantid.*")
# We can't do anything about numpy.oldnumeric being deprecated but
# still used in other libraries, e.g scipy, so just ignore those
_warnings.filterwarnings("ignore", category=DeprecationWarning,
module="numpy.oldnumeric")
###############################################################################
# Load all non-plugin subpackages that contain a C-extension. The boost.python
# registry will be missing entries if all are not loaded.
###############################################################################
from mantid import kernel as _kernel # noqa: F401, E402
from mantid import api as _api # noqa: F401, E402
from mantid import geometry as _geometry # noqa: F401, E402
from mantid import dataobjects as _dataobjects # noqa: F401, E402
# Make the aliases from each module accessible in the mantid namespace
from mantid.kernel._aliases import * # noqa: F401, E402
from mantid.api._aliases import * # noqa: F401, E402
# Make the version string accessible in the standard way
from mantid.kernel import version_str as _version_str # noqa: E402
__version__ = _version_str()
| gpl-3.0 |
jakobj/python-neo | neo/test/coretest/test_event.py | 7 | 5682 | # -*- coding: utf-8 -*-
"""
Tests of the neo.core.event.Event class
"""
try:
import unittest2 as unittest
except ImportError:
import unittest
import numpy as np
import quantities as pq
try:
from IPython.lib.pretty import pretty
except ImportError as err:
HAVE_IPYTHON = False
else:
HAVE_IPYTHON = True
from neo.core.event import Event
from neo.core import Segment
from neo.test.tools import assert_neo_object_is_compliant, assert_arrays_equal
from neo.test.generate_datasets import (get_fake_value, get_fake_values,
fake_neo, TEST_ANNOTATIONS)
class Test__generate_datasets(unittest.TestCase):
def setUp(self):
np.random.seed(0)
self.annotations = dict([(str(x), TEST_ANNOTATIONS[x]) for x in
range(len(TEST_ANNOTATIONS))])
def test__get_fake_values(self):
self.annotations['seed'] = 0
time = get_fake_value('time', pq.Quantity, seed=0, dim=0)
label = get_fake_value('label', str, seed=1)
name = get_fake_value('name', str, seed=2, obj=Event)
description = get_fake_value('description', str, seed=3, obj='Event')
file_origin = get_fake_value('file_origin', str)
attrs1 = {'label': label,
'name': name,
'description': description,
'file_origin': file_origin}
attrs2 = attrs1.copy()
attrs2.update(self.annotations)
res11 = get_fake_values(Event, annotate=False, seed=0)
res12 = get_fake_values('Event', annotate=False, seed=0)
res21 = get_fake_values(Event, annotate=True, seed=0)
res22 = get_fake_values('Event', annotate=True, seed=0)
assert_arrays_equal(res11.pop('time'), time)
assert_arrays_equal(res12.pop('time'), time)
assert_arrays_equal(res21.pop('time'), time)
assert_arrays_equal(res22.pop('time'), time)
self.assertEqual(res11, attrs1)
self.assertEqual(res12, attrs1)
self.assertEqual(res21, attrs2)
self.assertEqual(res22, attrs2)
def test__fake_neo__cascade(self):
self.annotations['seed'] = None
obj_type = 'Event'
cascade = True
res = fake_neo(obj_type=obj_type, cascade=cascade)
self.assertTrue(isinstance(res, Event))
assert_neo_object_is_compliant(res)
self.assertEqual(res.annotations, self.annotations)
def test__fake_neo__nocascade(self):
self.annotations['seed'] = None
obj_type = Event
cascade = False
res = fake_neo(obj_type=obj_type, cascade=cascade)
self.assertTrue(isinstance(res, Event))
assert_neo_object_is_compliant(res)
self.assertEqual(res.annotations, self.annotations)
class TestEvent(unittest.TestCase):
def test_Event_creation(self):
params = {'test2': 'y1', 'test3': True}
evt = Event(1.5*pq.ms,
label='test epoch', name='test', description='tester',
file_origin='test.file',
test1=1, **params)
evt.annotate(test1=1.1, test0=[1, 2])
assert_neo_object_is_compliant(evt)
self.assertEqual(evt.time, 1.5*pq.ms)
self.assertEqual(evt.label, 'test epoch')
self.assertEqual(evt.name, 'test')
self.assertEqual(evt.description, 'tester')
self.assertEqual(evt.file_origin, 'test.file')
self.assertEqual(evt.annotations['test0'], [1, 2])
self.assertEqual(evt.annotations['test1'], 1.1)
self.assertEqual(evt.annotations['test2'], 'y1')
self.assertTrue(evt.annotations['test3'])
def test_epoch_merge_NotImplementedError(self):
evt1 = Event(1.5*pq.ms,
label='test epoch', name='test', description='tester',
file_origin='test.file', test1=1)
evt2 = Event(1.5*pq.ms,
label='test epoch', name='test', description='tester',
file_origin='test.file', test1=1)
self.assertRaises(NotImplementedError, evt1.merge, evt2)
def test__children(self):
params = {'test2': 'y1', 'test3': True}
evt = Event(1.5*pq.ms,
label='test epoch', name='test', description='tester',
file_origin='test.file',
test1=1, **params)
evt.annotate(test1=1.1, test0=[1, 2])
assert_neo_object_is_compliant(evt)
segment = Segment(name='seg1')
segment.events = [evt]
segment.create_many_to_one_relationship()
self.assertEqual(evt._single_parent_objects, ('Segment',))
self.assertEqual(evt._multi_parent_objects, ())
self.assertEqual(evt._single_parent_containers, ('segment',))
self.assertEqual(evt._multi_parent_containers, ())
self.assertEqual(evt._parent_objects, ('Segment',))
self.assertEqual(evt._parent_containers, ('segment',))
self.assertEqual(len(evt.parents), 1)
self.assertEqual(evt.parents[0].name, 'seg1')
assert_neo_object_is_compliant(evt)
@unittest.skipUnless(HAVE_IPYTHON, "requires IPython")
def test__pretty(self):
evt = Event(1.5*pq.ms,
label='test epoch', name='test', description='tester',
file_origin='test.file')
evt.annotate(targ1=1.1, targ0=[1])
assert_neo_object_is_compliant(evt)
prepr = pretty(evt)
targ = ("Event\nname: '%s'\ndescription: '%s'\nannotations: %s" %
(evt.name, evt.description, pretty(evt.annotations)))
self.assertEqual(prepr, targ)
if __name__ == "__main__":
unittest.main()
| bsd-3-clause |
charlesvdv/servo | tests/wpt/css-tests/tools/py/setup.py | 161 | 1425 | import os, sys
from setuptools import setup
def main():
setup(
name='py',
description='library with cross-python path, ini-parsing, io, code, log facilities',
long_description = open('README.txt').read(),
version='1.4.31',
url='http://pylib.readthedocs.org/',
license='MIT license',
platforms=['unix', 'linux', 'osx', 'cygwin', 'win32'],
author='holger krekel, Ronny Pfannschmidt, Benjamin Peterson and others',
author_email='pytest-dev@python.org',
classifiers=['Development Status :: 6 - Mature',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX',
'Operating System :: Microsoft :: Windows',
'Operating System :: MacOS :: MacOS X',
'Topic :: Software Development :: Testing',
'Topic :: Software Development :: Libraries',
'Topic :: Utilities',
'Programming Language :: Python',
'Programming Language :: Python :: 3'],
packages=['py',
'py._code',
'py._io',
'py._log',
'py._path',
'py._process',
],
zip_safe=False,
)
if __name__ == '__main__':
main()
| mpl-2.0 |
shaileshgoogler/pyglet | contrib/layout/layout/gl/image.py | 29 | 2336 | #!/usr/bin/env python
'''
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import warnings
from pyglet.gl import *
from pyglet import image
from layout.frame import *
class ImageReplacedElementFactory(ReplacedElementFactory):
accept_names = ['img']
def __init__(self, locator):
self.locator = locator
self.cache = {}
def create_drawable(self, element):
file = None
if 'src' not in element.attributes:
warnings.warn('Image does not have src attribute')
return None
src = element.attributes['src']
# TODO move cache onto context.
if src in self.cache:
return ImageReplacedElementDrawable(self.cache[src])
file = self.locator.get_stream(src)
if not file:
# TODO broken image if not file
warnings.warn('Image not loaded: "%s"' % attrs['src'])
return None
img = image.load('', file=file)
self.cache[src] = img
return ImageReplacedElementDrawable(img)
class ImageReplacedElementDrawable(ReplacedElementDrawable):
def __init__(self, image):
self.texture = image.texture
self.intrinsic_width = image.width
self.intrinsic_height = image.height
self.intrinsic_ratio = image.width / float(image.height)
def draw(self, frame, render_device, left, top, right, bottom):
glPushAttrib(GL_ENABLE_BIT | GL_CURRENT_BIT | GL_COLOR_BUFFER_BIT)
glColor3f(1, 1, 1)
glEnable(GL_TEXTURE_2D)
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
glBindTexture(GL_TEXTURE_2D, self.texture.id)
# Create interleaved array in T4F_V4F format
t = self.texture.tex_coords
array = (GLfloat * 32)(
t[0], t[1], t[2], 1.,
left, bottom, 0, 1.,
t[3], t[4], t[5], 1.,
right, bottom, 0, 1.,
t[6], t[7], t[8], 1.,
right, top, 0, 1.,
t[9], t[10], t[11], 1.,
left, top, 0, 1.)
glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT)
glInterleavedArrays(GL_T4F_V4F, 0, array)
glDrawArrays(GL_QUADS, 0, 4)
glPopClientAttrib()
glPopAttrib()
| bsd-3-clause |
diofeher/django-nfa | tests/regressiontests/modeladmin/models.py | 1 | 7616 | # coding: utf-8
from django.db import models
from datetime import date
class Band(models.Model):
name = models.CharField(max_length=100)
bio = models.TextField()
sign_date = models.DateField()
def __unicode__(self):
return self.name
class Concert(models.Model):
main_band = models.ForeignKey(Band, related_name='main_concerts')
opening_band = models.ForeignKey(Band, related_name='opening_concerts',
blank=True)
day = models.CharField(max_length=3, choices=((1, 'Fri'), (2, 'Sat')))
transport = models.CharField(max_length=100, choices=(
(1, 'Plane'),
(2, 'Train'),
(3, 'Bus')
), blank=True)
__test__ = {'API_TESTS': """
>>> from django.contrib.admin.options import ModelAdmin, HORIZONTAL, VERTICAL
>>> from django.contrib.admin.sites import AdminSite
None of the following tests really depend on the content of the request, so
we'll just pass in None.
>>> request = None
# the sign_date is not 100 percent accurate ;)
>>> band = Band(name='The Doors', bio='', sign_date=date(1965, 1, 1))
>>> band.save()
Under the covers, the admin system will initialize ModelAdmin with a Model
class and an AdminSite instance, so let's just go ahead and do that manually
for testing.
>>> site = AdminSite()
>>> ma = ModelAdmin(Band, site)
>>> ma.get_form(request).base_fields.keys()
['name', 'bio', 'sign_date']
# form/fields/fieldsets interaction ##########################################
fieldsets_add and fieldsets_change should return a special data structure that
is used in the templates. They should generate the "right thing" whether we
have specified a custom form, the fields arugment, or nothing at all.
Here's the default case. There are no custom form_add/form_change methods,
no fields argument, and no fieldsets argument.
>>> ma = ModelAdmin(Band, site)
>>> ma.get_fieldsets(request)
[(None, {'fields': ['name', 'bio', 'sign_date']})]
>>> ma.get_fieldsets(request, band)
[(None, {'fields': ['name', 'bio', 'sign_date']})]
If we specify the fields argument, fieldsets_add and fielsets_change should
just stick the fields into a formsets structure and return it.
>>> class BandAdmin(ModelAdmin):
... fields = ['name']
>>> ma = BandAdmin(Band, site)
>>> ma.get_fieldsets(request)
[(None, {'fields': ['name']})]
>>> ma.get_fieldsets(request, band)
[(None, {'fields': ['name']})]
If we specify fields or fieldsets, it should exclude fields on the Form class
to the fields specified. This may cause errors to be raised in the db layer if
required model fields arent in fields/fieldsets, but that's preferable to
ghost errors where you have a field in your Form class that isn't being
displayed because you forgot to add it to fields/fielsets
>>> class BandAdmin(ModelAdmin):
... fields = ['name']
>>> ma = BandAdmin(Band, site)
>>> ma.get_form(request).base_fields.keys()
['name']
>>> ma.get_form(request, band).base_fields.keys()
['name']
>>> class BandAdmin(ModelAdmin):
... fieldsets = [(None, {'fields': ['name']})]
>>> ma = BandAdmin(Band, site)
>>> ma.get_form(request).base_fields.keys()
['name']
>>> ma.get_form(request, band).base_fields.keys()
['name']
If we specify a form, it should use it allowing custom validation to work
properly. This won't, however, break any of the admin widgets or media.
>>> from django import newforms as forms
>>> class AdminBandForm(forms.ModelForm):
... delete = forms.BooleanField()
...
... class Meta:
... model = Band
>>> class BandAdmin(ModelAdmin):
... form = AdminBandForm
>>> ma = BandAdmin(Band, site)
>>> ma.get_form(request).base_fields.keys()
['name', 'bio', 'sign_date', 'delete']
>>> type(ma.get_form(request).base_fields['sign_date'].widget)
<class 'django.contrib.admin.widgets.AdminDateWidget'>
If we need to override the queryset of a ModelChoiceField in our custom form
make sure that RelatedFieldWidgetWrapper doesn't mess that up.
>>> band2 = Band(name='The Beetles', bio='', sign_date=date(1962, 1, 1))
>>> band2.save()
>>> class AdminConcertForm(forms.ModelForm):
... class Meta:
... model = Concert
...
... def __init__(self, *args, **kwargs):
... super(AdminConcertForm, self).__init__(*args, **kwargs)
... self.fields["main_band"].queryset = Band.objects.filter(name='The Doors')
>>> class ConcertAdmin(ModelAdmin):
... form = AdminConcertForm
>>> ma = ConcertAdmin(Concert, site)
>>> form = ma.get_form(request)()
>>> print form["main_band"]
<select name="main_band" id="id_main_band">
<option value="" selected="selected">---------</option>
<option value="1">The Doors</option>
</select>
>>> band2.delete()
# radio_fields behavior ################################################
First, without any radio_fields specified, the widgets for ForeignKey
and fields with choices specified ought to be a basic Select widget.
ForeignKey widgets in the admin are wrapped with RelatedFieldWidgetWrapper so
they need to be handled properly when type checking. For Select fields, all of
the choices lists have a first entry of dashes.
>>> cma = ModelAdmin(Concert, site)
>>> cmafa = cma.get_form(request)
>>> type(cmafa.base_fields['main_band'].widget.widget)
<class 'django.newforms.widgets.Select'>
>>> list(cmafa.base_fields['main_band'].widget.choices)
[(u'', u'---------'), (1, u'The Doors')]
>>> type(cmafa.base_fields['opening_band'].widget.widget)
<class 'django.newforms.widgets.Select'>
>>> list(cmafa.base_fields['opening_band'].widget.choices)
[(u'', u'---------'), (1, u'The Doors')]
>>> type(cmafa.base_fields['day'].widget)
<class 'django.newforms.widgets.Select'>
>>> list(cmafa.base_fields['day'].widget.choices)
[('', '---------'), (1, 'Fri'), (2, 'Sat')]
>>> type(cmafa.base_fields['transport'].widget)
<class 'django.newforms.widgets.Select'>
>>> list(cmafa.base_fields['transport'].widget.choices)
[('', '---------'), (1, 'Plane'), (2, 'Train'), (3, 'Bus')]
Now specify all the fields as radio_fields. Widgets should now be
RadioSelect, and the choices list should have a first entry of 'None' if
blank=True for the model field. Finally, the widget should have the
'radiolist' attr, and 'inline' as well if the field is specified HORIZONTAL.
>>> class ConcertAdmin(ModelAdmin):
... radio_fields = {
... 'main_band': HORIZONTAL,
... 'opening_band': VERTICAL,
... 'day': VERTICAL,
... 'transport': HORIZONTAL,
... }
>>> cma = ConcertAdmin(Concert, site)
>>> cmafa = cma.get_form(request)
>>> type(cmafa.base_fields['main_band'].widget.widget)
<class 'django.contrib.admin.widgets.AdminRadioSelect'>
>>> cmafa.base_fields['main_band'].widget.attrs
{'class': 'radiolist inline'}
>>> list(cmafa.base_fields['main_band'].widget.choices)
[(1, u'The Doors')]
>>> type(cmafa.base_fields['opening_band'].widget.widget)
<class 'django.contrib.admin.widgets.AdminRadioSelect'>
>>> cmafa.base_fields['opening_band'].widget.attrs
{'class': 'radiolist'}
>>> list(cmafa.base_fields['opening_band'].widget.choices)
[(u'', u'None'), (1, u'The Doors')]
>>> type(cmafa.base_fields['day'].widget)
<class 'django.contrib.admin.widgets.AdminRadioSelect'>
>>> cmafa.base_fields['day'].widget.attrs
{'class': 'radiolist'}
>>> list(cmafa.base_fields['day'].widget.choices)
[(1, 'Fri'), (2, 'Sat')]
>>> type(cmafa.base_fields['transport'].widget)
<class 'django.contrib.admin.widgets.AdminRadioSelect'>
>>> cmafa.base_fields['transport'].widget.attrs
{'class': 'radiolist inline'}
>>> list(cmafa.base_fields['transport'].widget.choices)
[('', u'None'), (1, 'Plane'), (2, 'Train'), (3, 'Bus')]
>>> band.delete()
"""
}
| bsd-3-clause |
yigitguler/django | django/contrib/formtools/tests/tests.py | 32 | 7417 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import datetime
import os
import unittest
import warnings
from django import http
from django.contrib.formtools import preview, utils
from django.test import TestCase, override_settings
from django.utils._os import upath
from django.contrib.formtools.tests.forms import (
HashTestBlankForm, HashTestForm, TestForm,
)
success_string = "Done was called!"
success_string_encoded = success_string.encode()
class TestFormPreview(preview.FormPreview):
def get_context(self, request, form):
context = super(TestFormPreview, self).get_context(request, form)
context.update({'custom_context': True})
return context
def get_initial(self, request):
return {'field1': 'Works!'}
def done(self, request, cleaned_data):
return http.HttpResponse(success_string)
@override_settings(
TEMPLATE_DIRS=(
os.path.join(os.path.dirname(upath(__file__)), 'templates'),
),
ROOT_URLCONF='django.contrib.formtools.tests.urls',
)
class PreviewTests(TestCase):
def setUp(self):
super(PreviewTests, self).setUp()
# Create a FormPreview instance to share between tests
self.preview = preview.FormPreview(TestForm)
input_template = '<input type="hidden" name="%s" value="%s" />'
self.input = input_template % (self.preview.unused_name('stage'), "%d")
self.test_data = {'field1': 'foo', 'field1_': 'asdf'}
def test_unused_name(self):
"""
Verifies name mangling to get uniue field name.
"""
self.assertEqual(self.preview.unused_name('field1'), 'field1__')
def test_form_get(self):
"""
Test contrib.formtools.preview form retrieval.
Use the client library to see if we can successfully retrieve
the form (mostly testing the setup ROOT_URLCONF
process). Verify that an additional hidden input field
is created to manage the stage.
"""
response = self.client.get('/preview/')
stage = self.input % 1
self.assertContains(response, stage, 1)
self.assertEqual(response.context['custom_context'], True)
self.assertEqual(response.context['form'].initial, {'field1': 'Works!'})
def test_form_preview(self):
"""
Test contrib.formtools.preview form preview rendering.
Use the client library to POST to the form to see if a preview
is returned. If we do get a form back check that the hidden
value is correctly managing the state of the form.
"""
# Pass strings for form submittal and add stage variable to
# show we previously saw first stage of the form.
self.test_data.update({'stage': 1, 'date1': datetime.date(2006, 10, 25)})
response = self.client.post('/preview/', self.test_data)
# Check to confirm stage is set to 2 in output form.
stage = self.input % 2
self.assertContains(response, stage, 1)
def test_form_submit(self):
"""
Test contrib.formtools.preview form submittal.
Use the client library to POST to the form with stage set to 3
to see if our forms done() method is called. Check first
without the security hash, verify failure, retry with security
hash and verify success.
"""
# Pass strings for form submittal and add stage variable to
# show we previously saw first stage of the form.
self.test_data.update({'stage': 2, 'date1': datetime.date(2006, 10, 25)})
response = self.client.post('/preview/', self.test_data)
self.assertNotEqual(response.content, success_string_encoded)
hash = self.preview.security_hash(None, TestForm(self.test_data))
self.test_data.update({'hash': hash})
response = self.client.post('/preview/', self.test_data)
self.assertEqual(response.content, success_string_encoded)
def test_bool_submit(self):
"""
Test contrib.formtools.preview form submittal when form contains:
BooleanField(required=False)
Ticket: #6209 - When an unchecked BooleanField is previewed, the preview
form's hash would be computed with no value for ``bool1``. However, when
the preview form is rendered, the unchecked hidden BooleanField would be
rendered with the string value 'False'. So when the preview form is
resubmitted, the hash would be computed with the value 'False' for
``bool1``. We need to make sure the hashes are the same in both cases.
"""
self.test_data.update({'stage': 2})
hash = self.preview.security_hash(None, TestForm(self.test_data))
self.test_data.update({'hash': hash, 'bool1': 'False'})
with warnings.catch_warnings(record=True):
response = self.client.post('/preview/', self.test_data)
self.assertEqual(response.content, success_string_encoded)
def test_form_submit_good_hash(self):
"""
Test contrib.formtools.preview form submittal, using a correct
hash
"""
# Pass strings for form submittal and add stage variable to
# show we previously saw first stage of the form.
self.test_data.update({'stage': 2})
response = self.client.post('/preview/', self.test_data)
self.assertNotEqual(response.content, success_string_encoded)
hash = utils.form_hmac(TestForm(self.test_data))
self.test_data.update({'hash': hash})
response = self.client.post('/preview/', self.test_data)
self.assertEqual(response.content, success_string_encoded)
def test_form_submit_bad_hash(self):
"""
Test contrib.formtools.preview form submittal does not proceed
if the hash is incorrect.
"""
# Pass strings for form submittal and add stage variable to
# show we previously saw first stage of the form.
self.test_data.update({'stage': 2})
response = self.client.post('/preview/', self.test_data)
self.assertEqual(response.status_code, 200)
self.assertNotEqual(response.content, success_string_encoded)
hash = utils.form_hmac(TestForm(self.test_data)) + "bad"
self.test_data.update({'hash': hash})
response = self.client.post('/previewpreview/', self.test_data)
self.assertNotEqual(response.content, success_string_encoded)
class FormHmacTests(unittest.TestCase):
def test_textfield_hash(self):
"""
Regression test for #10034: the hash generation function should ignore
leading/trailing whitespace so as to be friendly to broken browsers that
submit it (usually in textareas).
"""
f1 = HashTestForm({'name': 'joe', 'bio': 'Speaking español.'})
f2 = HashTestForm({'name': ' joe', 'bio': 'Speaking español. '})
hash1 = utils.form_hmac(f1)
hash2 = utils.form_hmac(f2)
self.assertEqual(hash1, hash2)
def test_empty_permitted(self):
"""
Regression test for #10643: the security hash should allow forms with
empty_permitted = True, or forms where data has not changed.
"""
f1 = HashTestBlankForm({})
f2 = HashTestForm({}, empty_permitted=True)
hash1 = utils.form_hmac(f1)
hash2 = utils.form_hmac(f2)
self.assertEqual(hash1, hash2)
| bsd-3-clause |
ruiliLaMeilleure/11ad-backhaul | src/visualizer/visualizer/core.py | 88 | 60468 | # -*- Mode: python; coding: utf-8 -*-
from __future__ import division
#from __future__ import with_statement
LAYOUT_ALGORITHM = 'neato' # ['neato'|'dot'|'twopi'|'circo'|'fdp'|'nop']
REPRESENT_CHANNELS_AS_NODES = 1
DEFAULT_NODE_SIZE = 3.0 # default node size in meters
DEFAULT_TRANSMISSIONS_MEMORY = 5 # default number of of past intervals whose transmissions are remembered
BITRATE_FONT_SIZE = 10
# internal constants, normally not meant to be changed
SAMPLE_PERIOD = 0.1
PRIORITY_UPDATE_MODEL = -100
PRIORITY_UPDATE_VIEW = 200
import platform
if platform.system() == "Windows":
SHELL_FONT = "Lucida Console 9"
else:
SHELL_FONT = "Luxi Mono 10"
import ns.core
import ns.network
import ns.visualizer
import ns.internet
import ns.mobility
import math
import os
import sys
import gobject
import time
try:
import pygraphviz
import gtk
import pango
import goocanvas
import cairo
import threading
import hud
#import time
import cairo
from higcontainer import HIGContainer
gobject.threads_init()
try:
import svgitem
except ImportError:
svgitem = None
except ImportError, _import_error:
import dummy_threading as threading
else:
_import_error = None
try:
import ipython_view
except ImportError:
ipython_view = None
from base import InformationWindow, PyVizObject, Link, lookup_netdevice_traits, PIXELS_PER_METER
from base import transform_distance_simulation_to_canvas, transform_point_simulation_to_canvas
from base import transform_distance_canvas_to_simulation, transform_point_canvas_to_simulation
from base import load_plugins, register_plugin, plugins
PI_OVER_2 = math.pi/2
PI_TIMES_2 = math.pi*2
class Node(PyVizObject):
__gsignals__ = {
# signal emitted whenever a tooltip is about to be shown for the node
# the first signal parameter is a python list of strings, to which information can be appended
'query-extra-tooltip-info': (gobject.SIGNAL_RUN_LAST, None, (object,)),
}
def __init__(self, visualizer, node_index):
super(Node, self).__init__()
self.visualizer = visualizer
self.node_index = node_index
self.canvas_item = goocanvas.Ellipse()
self.canvas_item.set_data("pyviz-object", self)
self.links = []
self._has_mobility = None
self._selected = False
self._highlighted = False
self._color = 0x808080ff
self._size = DEFAULT_NODE_SIZE
self.canvas_item.connect("enter-notify-event", self.on_enter_notify_event)
self.canvas_item.connect("leave-notify-event", self.on_leave_notify_event)
self.menu = None
self.svg_item = None
self.svg_align_x = None
self.svg_align_y = None
self._label = None
self._label_canvas_item = None
self._update_appearance() # call this last
def set_svg_icon(self, file_base_name, width=None, height=None, align_x=0.5, align_y=0.5):
"""
Set a background SVG icon for the node.
@param file_base_name: base file name, including .svg
extension, of the svg file. Place the file in the folder
src/contrib/visualizer/resource.
@param width: scale to the specified width, in meters
@param width: scale to the specified height, in meters
@param align_x: horizontal alignment of the icon relative to
the node position, from 0 (icon fully to the left of the node)
to 1.0 (icon fully to the right of the node)
@param align_y: vertical alignment of the icon relative to the
node position, from 0 (icon fully to the top of the node) to
1.0 (icon fully to the bottom of the node)
"""
if width is None and height is None:
raise ValueError("either width or height must be given")
rsvg_handle = svgitem.rsvg_handle_factory(file_base_name)
x = self.canvas_item.props.center_x
y = self.canvas_item.props.center_y
self.svg_item = svgitem.SvgItem(x, y, rsvg_handle)
self.svg_item.props.parent = self.visualizer.canvas.get_root_item()
self.svg_item.props.pointer_events = 0
self.svg_item.lower(None)
self.svg_item.props.visibility = goocanvas.ITEM_VISIBLE_ABOVE_THRESHOLD
if width is not None:
self.svg_item.props.width = transform_distance_simulation_to_canvas(width)
if height is not None:
self.svg_item.props.height = transform_distance_simulation_to_canvas(height)
#threshold1 = 10.0/self.svg_item.props.height
#threshold2 = 10.0/self.svg_item.props.width
#self.svg_item.props.visibility_threshold = min(threshold1, threshold2)
self.svg_align_x = align_x
self.svg_align_y = align_y
self._update_svg_position(x, y)
self._update_appearance()
def set_label(self, label):
assert isinstance(label, basestring)
self._label = label
self._update_appearance()
def _update_svg_position(self, x, y):
w = self.svg_item.width
h = self.svg_item.height
self.svg_item.set_properties(x=(x - (1-self.svg_align_x)*w),
y=(y - (1-self.svg_align_y)*h))
def tooltip_query(self, tooltip):
self.visualizer.simulation.lock.acquire()
try:
ns3_node = ns.network.NodeList.GetNode(self.node_index)
ipv4 = ns3_node.GetObject(ns.internet.Ipv4.GetTypeId())
ipv6 = ns3_node.GetObject(ns.internet.Ipv6.GetTypeId())
name = '<b><u>Node %i</u></b>' % self.node_index
node_name = ns.core.Names.FindName (ns3_node)
if len(node_name)!=0:
name += ' <b>(' + node_name + ')</b>'
lines = [name]
lines.append('')
self.emit("query-extra-tooltip-info", lines)
mob = ns3_node.GetObject(ns.mobility.MobilityModel.GetTypeId())
if mob is not None:
lines.append(' <b>Mobility Model</b>: %s' % mob.GetInstanceTypeId().GetName())
for devI in range(ns3_node.GetNDevices()):
lines.append('')
lines.append(' <u>NetDevice %i:</u>' % devI)
dev = ns3_node.GetDevice(devI)
name = ns.core.Names.FindName(dev)
if name:
lines.append(' <b>Name:</b> %s' % name)
devname = dev.GetInstanceTypeId().GetName()
lines.append(' <b>Type:</b> %s' % devname)
if ipv4 is not None:
ipv4_idx = ipv4.GetInterfaceForDevice(dev)
if ipv4_idx != -1:
addresses = [
'%s/%s' % (ipv4.GetAddress(ipv4_idx, i).GetLocal(),
ipv4.GetAddress(ipv4_idx, i).GetMask())
for i in range(ipv4.GetNAddresses(ipv4_idx))]
lines.append(' <b>IPv4 Addresses:</b> %s' % '; '.join(addresses))
if ipv6 is not None:
ipv6_idx = ipv6.GetInterfaceForDevice(dev)
if ipv6_idx != -1:
addresses = [
'%s/%s' % (ipv6.GetAddress(ipv6_idx, i).GetAddress(),
ipv6.GetAddress(ipv6_idx, i).GetPrefix())
for i in range(ipv6.GetNAddresses(ipv6_idx))]
lines.append(' <b>IPv6 Addresses:</b> %s' % '; '.join(addresses))
lines.append(' <b>MAC Address:</b> %s' % (dev.GetAddress(),))
tooltip.set_markup('\n'.join(lines))
finally:
self.visualizer.simulation.lock.release()
def on_enter_notify_event(self, view, target, event):
self.highlighted = True
def on_leave_notify_event(self, view, target, event):
self.highlighted = False
def _set_selected(self, value):
self._selected = value
self._update_appearance()
def _get_selected(self):
return self._selected
selected = property(_get_selected, _set_selected)
def _set_highlighted(self, value):
self._highlighted = value
self._update_appearance()
def _get_highlighted(self):
return self._highlighted
highlighted = property(_get_highlighted, _set_highlighted)
def set_size(self, size):
self._size = size
self._update_appearance()
def _update_appearance(self):
"""Update the node aspect to reflect the selected/highlighted state"""
size = transform_distance_simulation_to_canvas(self._size)
if self.svg_item is not None:
alpha = 0x80
else:
alpha = 0xff
fill_color_rgba = (self._color & 0xffffff00) | alpha
self.canvas_item.set_properties(radius_x=size, radius_y=size,
fill_color_rgba=fill_color_rgba)
if self._selected:
line_width = size*.3
else:
line_width = size*.15
if self.highlighted:
stroke_color = 'yellow'
else:
stroke_color = 'black'
self.canvas_item.set_properties(line_width=line_width, stroke_color=stroke_color)
if self._label is not None:
if self._label_canvas_item is None:
self._label_canvas_item = goocanvas.Text(visibility_threshold=0.5,
font="Sans Serif 10",
fill_color_rgba=0x808080ff,
alignment=pango.ALIGN_CENTER,
anchor=gtk.ANCHOR_N,
parent=self.visualizer.canvas.get_root_item(),
pointer_events=0)
self._label_canvas_item.lower(None)
self._label_canvas_item.set_properties(visibility=goocanvas.ITEM_VISIBLE_ABOVE_THRESHOLD,
text=self._label)
self._update_position()
def set_position(self, x, y):
self.canvas_item.set_property("center_x", x)
self.canvas_item.set_property("center_y", y)
if self.svg_item is not None:
self._update_svg_position(x, y)
for link in self.links:
link.update_points()
if self._label_canvas_item is not None:
self._label_canvas_item.set_properties(x=x, y=(y+self._size*3))
def get_position(self):
return (self.canvas_item.get_property("center_x"), self.canvas_item.get_property("center_y"))
def _update_position(self):
x, y = self.get_position()
self.set_position(x, y)
def set_color(self, color):
if isinstance(color, str):
color = gtk.gdk.color_parse(color)
color = ((color.red>>8) << 24) | ((color.green>>8) << 16) | ((color.blue>>8) << 8) | 0xff
self._color = color
self._update_appearance()
def add_link(self, link):
assert isinstance(link, Link)
self.links.append(link)
def remove_link(self, link):
assert isinstance(link, Link)
self.links.remove(link)
@property
def has_mobility(self):
if self._has_mobility is None:
node = ns.network.NodeList.GetNode(self.node_index)
mobility = node.GetObject(ns.mobility.MobilityModel.GetTypeId())
self._has_mobility = (mobility is not None)
return self._has_mobility
class Channel(PyVizObject):
def __init__(self, channel):
self.channel = channel
self.canvas_item = goocanvas.Ellipse(radius_x=30, radius_y=30,
fill_color="white",
stroke_color="grey", line_width=2.0,
line_dash=goocanvas.LineDash([10.0, 10.0 ]),
visibility=goocanvas.ITEM_VISIBLE)
self.canvas_item.set_data("pyviz-object", self)
self.links = []
def set_position(self, x, y):
self.canvas_item.set_property("center_x", x)
self.canvas_item.set_property("center_y", y)
for link in self.links:
link.update_points()
def get_position(self):
return (self.canvas_item.get_property("center_x"), self.canvas_item.get_property("center_y"))
class WiredLink(Link):
def __init__(self, node1, node2):
assert isinstance(node1, Node)
assert isinstance(node2, (Node, Channel))
self.node1 = node1
self.node2 = node2
self.canvas_item = goocanvas.Path(line_width=1.0, stroke_color="black")
self.canvas_item.set_data("pyviz-object", self)
self.node1.links.append(self)
self.node2.links.append(self)
def update_points(self):
pos1_x, pos1_y = self.node1.get_position()
pos2_x, pos2_y = self.node2.get_position()
self.canvas_item.set_property("data", "M %r %r L %r %r" % (pos1_x, pos1_y, pos2_x, pos2_y))
class SimulationThread(threading.Thread):
def __init__(self, viz):
super(SimulationThread, self).__init__()
assert isinstance(viz, Visualizer)
self.viz = viz # Visualizer object
self.lock = threading.Lock()
self.go = threading.Event()
self.go.clear()
self.target_time = 0 # in seconds
self.quit = False
self.sim_helper = ns.visualizer.PyViz()
self.pause_messages = []
def set_nodes_of_interest(self, nodes):
self.lock.acquire()
try:
self.sim_helper.SetNodesOfInterest(nodes)
finally:
self.lock.release()
def run(self):
while not self.quit:
#print "sim: Wait for go"
self.go.wait() # wait until the main (view) thread gives us the go signal
self.go.clear()
if self.quit:
break
#self.go.clear()
#print "sim: Acquire lock"
self.lock.acquire()
try:
if 0:
if ns3.core.Simulator.IsFinished():
self.viz.play_button.set_sensitive(False)
break
#print "sim: Current time is %f; Run until: %f" % (ns3.Simulator.Now ().GetSeconds (), self.target_time)
#if ns3.Simulator.Now ().GetSeconds () > self.target_time:
# print "skipping, model is ahead of view!"
self.sim_helper.SimulatorRunUntil(ns.core.Seconds(self.target_time))
#print "sim: Run until ended at current time: ", ns3.Simulator.Now ().GetSeconds ()
self.pause_messages.extend(self.sim_helper.GetPauseMessages())
gobject.idle_add(self.viz.update_model, priority=PRIORITY_UPDATE_MODEL)
#print "sim: Run until: ", self.target_time, ": finished."
finally:
self.lock.release()
#print "sim: Release lock, loop."
# enumeration
class ShowTransmissionsMode(object):
__slots__ = []
ShowTransmissionsMode.ALL = ShowTransmissionsMode()
ShowTransmissionsMode.NONE = ShowTransmissionsMode()
ShowTransmissionsMode.SELECTED = ShowTransmissionsMode()
class Visualizer(gobject.GObject):
INSTANCE = None
if _import_error is None:
__gsignals__ = {
# signal emitted whenever a right-click-on-node popup menu is being constructed
'populate-node-menu': (gobject.SIGNAL_RUN_LAST, None, (object, gtk.Menu,)),
# signal emitted after every simulation period (SAMPLE_PERIOD seconds of simulated time)
# the simulation lock is acquired while the signal is emitted
'simulation-periodic-update': (gobject.SIGNAL_RUN_LAST, None, ()),
# signal emitted right after the topology is scanned
'topology-scanned': (gobject.SIGNAL_RUN_LAST, None, ()),
# signal emitted when it's time to update the view objects
'update-view': (gobject.SIGNAL_RUN_LAST, None, ()),
}
def __init__(self):
assert Visualizer.INSTANCE is None
Visualizer.INSTANCE = self
super(Visualizer, self).__init__()
self.nodes = {} # node index -> Node
self.channels = {} # id(ns3.Channel) -> Channel
self.window = None # toplevel window
self.canvas = None # goocanvas.Canvas
self.time_label = None # gtk.Label
self.play_button = None # gtk.ToggleButton
self.zoom = None # gtk.Adjustment
self._scrolled_window = None # gtk.ScrolledWindow
self.links_group = goocanvas.Group()
self.channels_group = goocanvas.Group()
self.nodes_group = goocanvas.Group()
self._update_timeout_id = None
self.simulation = SimulationThread(self)
self.selected_node = None # node currently selected
self.speed = 1.0
self.information_windows = []
self._transmission_arrows = []
self._last_transmissions = []
self._drop_arrows = []
self._last_drops = []
self._show_transmissions_mode = None
self.set_show_transmissions_mode(ShowTransmissionsMode.ALL)
self._panning_state = None
self.node_size_adjustment = None
self.transmissions_smoothing_adjustment = None
self.sample_period = SAMPLE_PERIOD
self.node_drag_state = None
self.follow_node = None
self.shell_window = None
self.create_gui()
for plugin in plugins:
plugin(self)
def set_show_transmissions_mode(self, mode):
assert isinstance(mode, ShowTransmissionsMode)
self._show_transmissions_mode = mode
if self._show_transmissions_mode == ShowTransmissionsMode.ALL:
self.simulation.set_nodes_of_interest(range(ns.network.NodeList.GetNNodes()))
elif self._show_transmissions_mode == ShowTransmissionsMode.NONE:
self.simulation.set_nodes_of_interest([])
elif self._show_transmissions_mode == ShowTransmissionsMode.SELECTED:
if self.selected_node is None:
self.simulation.set_nodes_of_interest([])
else:
self.simulation.set_nodes_of_interest([self.selected_node.node_index])
def _create_advanced_controls(self):
expander = gtk.Expander("Advanced")
expander.show()
main_vbox = gobject.new(gtk.VBox, border_width=8, visible=True)
expander.add(main_vbox)
main_hbox1 = gobject.new(gtk.HBox, border_width=8, visible=True)
main_vbox.pack_start(main_hbox1)
show_transmissions_group = HIGContainer("Show transmissions")
show_transmissions_group.show()
main_hbox1.pack_start(show_transmissions_group, False, False, 8)
vbox = gtk.VBox(True, 4)
vbox.show()
show_transmissions_group.add(vbox)
all_nodes = gtk.RadioButton(None)
all_nodes.set_label("All nodes")
all_nodes.set_active(True)
all_nodes.show()
vbox.add(all_nodes)
selected_node = gtk.RadioButton(all_nodes)
selected_node.show()
selected_node.set_label("Selected node")
selected_node.set_active(False)
vbox.add(selected_node)
no_node = gtk.RadioButton(all_nodes)
no_node.show()
no_node.set_label("Disabled")
no_node.set_active(False)
vbox.add(no_node)
def toggled(radio):
if radio.get_active():
self.set_show_transmissions_mode(ShowTransmissionsMode.ALL)
all_nodes.connect("toggled", toggled)
def toggled(radio):
if radio.get_active():
self.set_show_transmissions_mode(ShowTransmissionsMode.NONE)
no_node.connect("toggled", toggled)
def toggled(radio):
if radio.get_active():
self.set_show_transmissions_mode(ShowTransmissionsMode.SELECTED)
selected_node.connect("toggled", toggled)
# -- misc settings
misc_settings_group = HIGContainer("Misc Settings")
misc_settings_group.show()
main_hbox1.pack_start(misc_settings_group, False, False, 8)
settings_hbox = gobject.new(gtk.HBox, border_width=8, visible=True)
misc_settings_group.add(settings_hbox)
# --> node size
vbox = gobject.new(gtk.VBox, border_width=0, visible=True)
scale = gobject.new(gtk.HScale, visible=True, digits=2)
vbox.pack_start(scale, True, True, 0)
vbox.pack_start(gobject.new(gtk.Label, label="Node Size", visible=True), True, True, 0)
settings_hbox.pack_start(vbox, False, False, 6)
self.node_size_adjustment = scale.get_adjustment()
def node_size_changed(adj):
for node in self.nodes.itervalues():
node.set_size(adj.value)
self.node_size_adjustment.connect("value-changed", node_size_changed)
self.node_size_adjustment.set_all(DEFAULT_NODE_SIZE, 0.01, 20, 0.1)
# --> transmissions smooth factor
vbox = gobject.new(gtk.VBox, border_width=0, visible=True)
scale = gobject.new(gtk.HScale, visible=True, digits=1)
vbox.pack_start(scale, True, True, 0)
vbox.pack_start(gobject.new(gtk.Label, label="Tx. Smooth Factor (s)", visible=True), True, True, 0)
settings_hbox.pack_start(vbox, False, False, 6)
self.transmissions_smoothing_adjustment = scale.get_adjustment()
self.transmissions_smoothing_adjustment.set_all(DEFAULT_TRANSMISSIONS_MEMORY*0.1, 0.1, 10, 0.1)
return expander
class _PanningState(object):
__slots__ = ['initial_mouse_pos', 'initial_canvas_pos', 'motion_signal']
def _begin_panning(self, widget, event):
self.canvas.window.set_cursor(gtk.gdk.Cursor(gtk.gdk.FLEUR))
self._panning_state = self._PanningState()
x, y, dummy = widget.window.get_pointer()
self._panning_state.initial_mouse_pos = (x, y)
x = self._scrolled_window.get_hadjustment().value
y = self._scrolled_window.get_vadjustment().value
self._panning_state.initial_canvas_pos = (x, y)
self._panning_state.motion_signal = self.canvas.connect("motion-notify-event", self._panning_motion)
def _end_panning(self, event):
if self._panning_state is None:
return
self.canvas.window.set_cursor(None)
self.canvas.disconnect(self._panning_state.motion_signal)
self._panning_state = None
def _panning_motion(self, widget, event):
assert self._panning_state is not None
if event.is_hint:
x, y, dummy = widget.window.get_pointer()
else:
x, y = event.x, event.y
hadj = self._scrolled_window.get_hadjustment()
vadj = self._scrolled_window.get_vadjustment()
mx0, my0 = self._panning_state.initial_mouse_pos
cx0, cy0 = self._panning_state.initial_canvas_pos
dx = x - mx0
dy = y - my0
hadj.value = cx0 - dx
vadj.value = cy0 - dy
return True
def _canvas_button_press(self, widget, event):
if event.button == 2:
self._begin_panning(widget, event)
return True
return False
def _canvas_button_release(self, dummy_widget, event):
if event.button == 2:
self._end_panning(event)
return True
return False
def _canvas_scroll_event(self, dummy_widget, event):
if event.direction == gtk.gdk.SCROLL_UP:
self.zoom.value *= 1.25
return True
elif event.direction == gtk.gdk.SCROLL_DOWN:
self.zoom.value /= 1.25
return True
return False
def get_hadjustment(self):
return self._scrolled_window.get_hadjustment()
def get_vadjustment(self):
return self._scrolled_window.get_vadjustment()
def create_gui(self):
self.window = gtk.Window()
vbox = gtk.VBox(); vbox.show()
self.window.add(vbox)
# canvas
self.canvas = goocanvas.Canvas()
self.canvas.connect_after("button-press-event", self._canvas_button_press)
self.canvas.connect_after("button-release-event", self._canvas_button_release)
self.canvas.connect("scroll-event", self._canvas_scroll_event)
self.canvas.props.has_tooltip = True
self.canvas.connect("query-tooltip", self._canvas_tooltip_cb)
self.canvas.show()
sw = gtk.ScrolledWindow(); sw.show()
self._scrolled_window = sw
sw.add(self.canvas)
vbox.pack_start(sw, True, True, 4)
self.canvas.set_size_request(600, 450)
self.canvas.set_bounds(-10000, -10000, 10000, 10000)
self.canvas.scroll_to(0, 0)
self.canvas.get_root_item().add_child(self.links_group)
self.links_group.set_property("visibility", goocanvas.ITEM_VISIBLE)
self.canvas.get_root_item().add_child(self.channels_group)
self.channels_group.set_property("visibility", goocanvas.ITEM_VISIBLE)
self.channels_group.raise_(self.links_group)
self.canvas.get_root_item().add_child(self.nodes_group)
self.nodes_group.set_property("visibility", goocanvas.ITEM_VISIBLE)
self.nodes_group.raise_(self.channels_group)
self.hud = hud.Axes(self)
hbox = gtk.HBox(); hbox.show()
vbox.pack_start(hbox, False, False, 4)
# zoom
zoom_adj = gtk.Adjustment(1.0, 0.01, 10.0, 0.02, 1.0, 0)
self.zoom = zoom_adj
def _zoom_changed(adj):
self.canvas.set_scale(adj.value)
zoom_adj.connect("value-changed", _zoom_changed)
zoom = gtk.SpinButton(zoom_adj)
zoom.set_digits(3)
zoom.show()
hbox.pack_start(gobject.new(gtk.Label, label=" Zoom:", visible=True), False, False, 4)
hbox.pack_start(zoom, False, False, 4)
_zoom_changed(zoom_adj)
# speed
speed_adj = gtk.Adjustment(1.0, 0.01, 10.0, 0.02, 1.0, 0)
def _speed_changed(adj):
self.speed = adj.value
self.sample_period = SAMPLE_PERIOD*adj.value
self._start_update_timer()
speed_adj.connect("value-changed", _speed_changed)
speed = gtk.SpinButton(speed_adj)
speed.set_digits(3)
speed.show()
hbox.pack_start(gobject.new(gtk.Label, label=" Speed:", visible=True), False, False, 4)
hbox.pack_start(speed, False, False, 4)
_speed_changed(speed_adj)
# Current time
self.time_label = gobject.new(gtk.Label, label=" Speed:", visible=True)
self.time_label.set_width_chars(20)
hbox.pack_start(self.time_label, False, False, 4)
# Screenshot button
screenshot_button = gobject.new(gtk.Button,
label="Snapshot",
relief=gtk.RELIEF_NONE, focus_on_click=False,
visible=True)
hbox.pack_start(screenshot_button, False, False, 4)
def load_button_icon(button, icon_name):
try:
import gnomedesktop
except ImportError:
sys.stderr.write("Could not load icon %s due to missing gnomedesktop Python module\n" % icon_name)
else:
icon = gnomedesktop.find_icon(gtk.icon_theme_get_default(), icon_name, 16, 0)
if icon is not None:
button.props.image = gobject.new(gtk.Image, file=icon, visible=True)
load_button_icon(screenshot_button, "applets-screenshooter")
screenshot_button.connect("clicked", self._take_screenshot)
# Shell button
if ipython_view is not None:
shell_button = gobject.new(gtk.Button,
label="Shell",
relief=gtk.RELIEF_NONE, focus_on_click=False,
visible=True)
hbox.pack_start(shell_button, False, False, 4)
load_button_icon(shell_button, "gnome-terminal")
shell_button.connect("clicked", self._start_shell)
# Play button
self.play_button = gobject.new(gtk.ToggleButton,
image=gobject.new(gtk.Image, stock=gtk.STOCK_MEDIA_PLAY, visible=True),
label="Simulate (F3)",
relief=gtk.RELIEF_NONE, focus_on_click=False,
use_stock=True, visible=True)
accel_group = gtk.AccelGroup()
self.window.add_accel_group(accel_group)
self.play_button.add_accelerator("clicked", accel_group,
gtk.keysyms.F3, 0, gtk.ACCEL_VISIBLE)
self.play_button.connect("toggled", self._on_play_button_toggled)
hbox.pack_start(self.play_button, False, False, 4)
self.canvas.get_root_item().connect("button-press-event", self.on_root_button_press_event)
vbox.pack_start(self._create_advanced_controls(), False, False, 4)
self.window.show()
def scan_topology(self):
print "scanning topology: %i nodes..." % (ns.network.NodeList.GetNNodes(),)
graph = pygraphviz.AGraph()
seen_nodes = 0
for nodeI in range(ns.network.NodeList.GetNNodes()):
seen_nodes += 1
if seen_nodes == 100:
print "scan topology... %i nodes visited (%.1f%%)" % (nodeI, 100*nodeI/ns.network.NodeList.GetNNodes())
seen_nodes = 0
node = ns.network.NodeList.GetNode(nodeI)
node_name = "Node %i" % nodeI
node_view = self.get_node(nodeI)
mobility = node.GetObject(ns.mobility.MobilityModel.GetTypeId())
if mobility is not None:
node_view.set_color("red")
pos = mobility.GetPosition()
node_view.set_position(*transform_point_simulation_to_canvas(pos.x, pos.y))
#print "node has mobility position -> ", "%f,%f" % (pos.x, pos.y)
else:
graph.add_node(node_name)
for devI in range(node.GetNDevices()):
device = node.GetDevice(devI)
device_traits = lookup_netdevice_traits(type(device))
if device_traits.is_wireless:
continue
if device_traits.is_virtual:
continue
channel = device.GetChannel()
if channel.GetNDevices() > 2:
if REPRESENT_CHANNELS_AS_NODES:
# represent channels as white nodes
if mobility is None:
channel_name = "Channel %s" % id(channel)
graph.add_edge(node_name, channel_name)
self.get_channel(channel)
self.create_link(self.get_node(nodeI), self.get_channel(channel))
else:
# don't represent channels, just add links between nodes in the same channel
for otherDevI in range(channel.GetNDevices()):
otherDev = channel.GetDevice(otherDevI)
otherNode = otherDev.GetNode()
otherNodeView = self.get_node(otherNode.GetId())
if otherNode is not node:
if mobility is None and not otherNodeView.has_mobility:
other_node_name = "Node %i" % otherNode.GetId()
graph.add_edge(node_name, other_node_name)
self.create_link(self.get_node(nodeI), otherNodeView)
else:
for otherDevI in range(channel.GetNDevices()):
otherDev = channel.GetDevice(otherDevI)
otherNode = otherDev.GetNode()
otherNodeView = self.get_node(otherNode.GetId())
if otherNode is not node:
if mobility is None and not otherNodeView.has_mobility:
other_node_name = "Node %i" % otherNode.GetId()
graph.add_edge(node_name, other_node_name)
self.create_link(self.get_node(nodeI), otherNodeView)
print "scanning topology: calling graphviz layout"
graph.layout(LAYOUT_ALGORITHM)
for node in graph.iternodes():
#print node, "=>", node.attr['pos']
node_type, node_id = node.split(' ')
pos_x, pos_y = [float(s) for s in node.attr['pos'].split(',')]
if node_type == 'Node':
obj = self.nodes[int(node_id)]
elif node_type == 'Channel':
obj = self.channels[int(node_id)]
obj.set_position(pos_x, pos_y)
print "scanning topology: all done."
self.emit("topology-scanned")
def get_node(self, index):
try:
return self.nodes[index]
except KeyError:
node = Node(self, index)
self.nodes[index] = node
self.nodes_group.add_child(node.canvas_item)
node.canvas_item.connect("button-press-event", self.on_node_button_press_event, node)
node.canvas_item.connect("button-release-event", self.on_node_button_release_event, node)
return node
def get_channel(self, ns3_channel):
try:
return self.channels[id(ns3_channel)]
except KeyError:
channel = Channel(ns3_channel)
self.channels[id(ns3_channel)] = channel
self.channels_group.add_child(channel.canvas_item)
return channel
def create_link(self, node, node_or_channel):
link = WiredLink(node, node_or_channel)
self.links_group.add_child(link.canvas_item)
link.canvas_item.lower(None)
def update_view(self):
#print "update_view"
self.time_label.set_text("Time: %f s" % ns.core.Simulator.Now().GetSeconds())
self._update_node_positions()
# Update information
for info_win in self.information_windows:
info_win.update()
self._update_transmissions_view()
self._update_drops_view()
self.emit("update-view")
def _update_node_positions(self):
for node in self.nodes.itervalues():
if node.has_mobility:
ns3_node = ns.network.NodeList.GetNode(node.node_index)
mobility = ns3_node.GetObject(ns.mobility.MobilityModel.GetTypeId())
if mobility is not None:
pos = mobility.GetPosition()
x, y = transform_point_simulation_to_canvas(pos.x, pos.y)
node.set_position(x, y)
if node is self.follow_node:
hadj = self._scrolled_window.get_hadjustment()
vadj = self._scrolled_window.get_vadjustment()
px, py = self.canvas.convert_to_pixels(x, y)
hadj.value = px - hadj.page_size/2
vadj.value = py - vadj.page_size/2
def center_on_node(self, node):
if isinstance(node, ns.network.Node):
node = self.nodes[node.GetId()]
elif isinstance(node, (int, long)):
node = self.nodes[node]
elif isinstance(node, Node):
pass
else:
raise TypeError("expected int, viz.Node or ns.network.Node, not %r" % node)
x, y = node.get_position()
hadj = self._scrolled_window.get_hadjustment()
vadj = self._scrolled_window.get_vadjustment()
px, py = self.canvas.convert_to_pixels(x, y)
hadj.value = px - hadj.page_size/2
vadj.value = py - vadj.page_size/2
def update_model(self):
self.simulation.lock.acquire()
try:
self.emit("simulation-periodic-update")
finally:
self.simulation.lock.release()
def do_simulation_periodic_update(self):
smooth_factor = int(self.transmissions_smoothing_adjustment.value*10)
transmissions = self.simulation.sim_helper.GetTransmissionSamples()
self._last_transmissions.append(transmissions)
while len(self._last_transmissions) > smooth_factor:
self._last_transmissions.pop(0)
drops = self.simulation.sim_helper.GetPacketDropSamples()
self._last_drops.append(drops)
while len(self._last_drops) > smooth_factor:
self._last_drops.pop(0)
def _get_label_over_line_position(self, pos1_x, pos1_y, pos2_x, pos2_y):
hadj = self._scrolled_window.get_hadjustment()
vadj = self._scrolled_window.get_vadjustment()
bounds_x1, bounds_y1 = self.canvas.convert_from_pixels(hadj.value, vadj.value)
bounds_x2, bounds_y2 = self.canvas.convert_from_pixels(hadj.value + hadj.page_size,
vadj.value + vadj.page_size)
pos1_x, pos1_y, pos2_x, pos2_y = ns.visualizer.PyViz.LineClipping(bounds_x1, bounds_y1,
bounds_x2, bounds_y2,
pos1_x, pos1_y,
pos2_x, pos2_y)
return (pos1_x + pos2_x)/2, (pos1_y + pos2_y)/2
def _update_transmissions_view(self):
transmissions_average = {}
for transmission_set in self._last_transmissions:
for transmission in transmission_set:
key = (transmission.transmitter.GetId(), transmission.receiver.GetId())
rx_bytes, count = transmissions_average.get(key, (0, 0))
rx_bytes += transmission.bytes
count += 1
transmissions_average[key] = rx_bytes, count
old_arrows = self._transmission_arrows
for arrow, label in old_arrows:
arrow.set_property("visibility", goocanvas.ITEM_HIDDEN)
label.set_property("visibility", goocanvas.ITEM_HIDDEN)
new_arrows = []
k = self.node_size_adjustment.value/5
for (transmitter_id, receiver_id), (rx_bytes, rx_count) in transmissions_average.iteritems():
transmitter = self.get_node(transmitter_id)
receiver = self.get_node(receiver_id)
try:
arrow, label = old_arrows.pop()
except IndexError:
arrow = goocanvas.Polyline(line_width=2.0, stroke_color_rgba=0x00C000C0, close_path=False, end_arrow=True)
arrow.set_property("parent", self.canvas.get_root_item())
arrow.props.pointer_events = 0
arrow.raise_(None)
label = goocanvas.Text(parent=self.canvas.get_root_item(), pointer_events=0)
label.raise_(None)
arrow.set_property("visibility", goocanvas.ITEM_VISIBLE)
line_width = max(0.1, math.log(float(rx_bytes)/rx_count/self.sample_period)*k)
arrow.set_property("line-width", line_width)
pos1_x, pos1_y = transmitter.get_position()
pos2_x, pos2_y = receiver.get_position()
points = goocanvas.Points([(pos1_x, pos1_y), (pos2_x, pos2_y)])
arrow.set_property("points", points)
kbps = float(rx_bytes*8)/1e3/rx_count/self.sample_period
label.set_properties(visibility=goocanvas.ITEM_VISIBLE_ABOVE_THRESHOLD,
visibility_threshold=0.5,
font=("Sans Serif %f" % int(1+BITRATE_FONT_SIZE*k)))
angle = math.atan2((pos2_y - pos1_y), (pos2_x - pos1_x))
if -PI_OVER_2 <= angle <= PI_OVER_2:
label.set_properties(text=("%.2f kbit/s →" % (kbps,)),
alignment=pango.ALIGN_CENTER,
anchor=gtk.ANCHOR_S,
x=0, y=-line_width/2)
M = cairo.Matrix()
M.translate(*self._get_label_over_line_position(pos1_x, pos1_y, pos2_x, pos2_y))
M.rotate(angle)
label.set_transform(M)
else:
label.set_properties(text=("← %.2f kbit/s" % (kbps,)),
alignment=pango.ALIGN_CENTER,
anchor=gtk.ANCHOR_N,
x=0, y=line_width/2)
M = cairo.Matrix()
M.translate(*self._get_label_over_line_position(pos1_x, pos1_y, pos2_x, pos2_y))
M.rotate(angle)
M.scale(-1, -1)
label.set_transform(M)
new_arrows.append((arrow, label))
self._transmission_arrows = new_arrows + old_arrows
def _update_drops_view(self):
drops_average = {}
for drop_set in self._last_drops:
for drop in drop_set:
key = drop.transmitter.GetId()
drop_bytes, count = drops_average.get(key, (0, 0))
drop_bytes += drop.bytes
count += 1
drops_average[key] = drop_bytes, count
old_arrows = self._drop_arrows
for arrow, label in old_arrows:
arrow.set_property("visibility", goocanvas.ITEM_HIDDEN)
label.set_property("visibility", goocanvas.ITEM_HIDDEN)
new_arrows = []
# get the coordinates for the edge of screen
vadjustment = self._scrolled_window.get_vadjustment()
bottom_y = vadjustment.value + vadjustment.page_size
dummy, edge_y = self.canvas.convert_from_pixels(0, bottom_y)
k = self.node_size_adjustment.value/5
for transmitter_id, (drop_bytes, drop_count) in drops_average.iteritems():
transmitter = self.get_node(transmitter_id)
try:
arrow, label = old_arrows.pop()
except IndexError:
arrow = goocanvas.Polyline(line_width=2.0, stroke_color_rgba=0xC00000C0, close_path=False, end_arrow=True)
arrow.props.pointer_events = 0
arrow.set_property("parent", self.canvas.get_root_item())
arrow.raise_(None)
label = goocanvas.Text()#, fill_color_rgba=0x00C000C0)
label.props.pointer_events = 0
label.set_property("parent", self.canvas.get_root_item())
label.raise_(None)
arrow.set_property("visibility", goocanvas.ITEM_VISIBLE)
arrow.set_property("line-width", max(0.1, math.log(float(drop_bytes)/drop_count/self.sample_period)*k))
pos1_x, pos1_y = transmitter.get_position()
pos2_x, pos2_y = pos1_x, edge_y
points = goocanvas.Points([(pos1_x, pos1_y), (pos2_x, pos2_y)])
arrow.set_property("points", points)
label.set_properties(visibility=goocanvas.ITEM_VISIBLE_ABOVE_THRESHOLD,
visibility_threshold=0.5,
font=("Sans Serif %i" % int(1+BITRATE_FONT_SIZE*k)),
text=("%.2f kbit/s" % (float(drop_bytes*8)/1e3/drop_count/self.sample_period,)),
alignment=pango.ALIGN_CENTER,
x=(pos1_x + pos2_x)/2,
y=(pos1_y + pos2_y)/2)
new_arrows.append((arrow, label))
self._drop_arrows = new_arrows + old_arrows
def update_view_timeout(self):
#print "view: update_view_timeout called at real time ", time.time()
# while the simulator is busy, run the gtk event loop
while not self.simulation.lock.acquire(False):
while gtk.events_pending():
gtk.main_iteration()
pause_messages = self.simulation.pause_messages
self.simulation.pause_messages = []
try:
self.update_view()
self.simulation.target_time = ns.core.Simulator.Now ().GetSeconds () + self.sample_period
#print "view: target time set to %f" % self.simulation.target_time
finally:
self.simulation.lock.release()
if pause_messages:
#print pause_messages
dialog = gtk.MessageDialog(parent=self.window, flags=0, type=gtk.MESSAGE_WARNING, buttons=gtk.BUTTONS_OK,
message_format='\n'.join(pause_messages))
dialog.connect("response", lambda d, r: d.destroy())
dialog.show()
self.play_button.set_active(False)
# if we're paused, stop the update timer
if not self.play_button.get_active():
self._update_timeout_id = None
return False
#print "view: self.simulation.go.set()"
self.simulation.go.set()
#print "view: done."
return True
def _start_update_timer(self):
if self._update_timeout_id is not None:
gobject.source_remove(self._update_timeout_id)
#print "start_update_timer"
self._update_timeout_id = gobject.timeout_add(int(SAMPLE_PERIOD/min(self.speed, 1)*1e3),
self.update_view_timeout,
priority=PRIORITY_UPDATE_VIEW)
def _on_play_button_toggled(self, button):
if button.get_active():
self._start_update_timer()
else:
if self._update_timeout_id is not None:
gobject.source_remove(self._update_timeout_id)
def _quit(self, *dummy_args):
if self._update_timeout_id is not None:
gobject.source_remove(self._update_timeout_id)
self._update_timeout_id = None
self.simulation.quit = True
self.simulation.go.set()
self.simulation.join()
gtk.main_quit()
def _monkey_patch_ipython(self):
# The user may want to access the NS 3 simulation state, but
# NS 3 is not thread safe, so it could cause serious problems.
# To work around this, monkey-patch IPython to automatically
# acquire and release the simulation lock around each code
# that is executed.
original_runcode = self.ipython.runcode
def runcode(ip, *args):
#print "lock"
self.simulation.lock.acquire()
try:
return original_runcode(*args)
finally:
#print "unlock"
self.simulation.lock.release()
import types
self.ipython.runcode = types.MethodType(runcode, self.ipython)
def autoscale_view(self):
if not self.nodes:
return
self._update_node_positions()
positions = [node.get_position() for node in self.nodes.itervalues()]
min_x, min_y = min(x for (x,y) in positions), min(y for (x,y) in positions)
max_x, max_y = max(x for (x,y) in positions), max(y for (x,y) in positions)
min_x_px, min_y_px = self.canvas.convert_to_pixels(min_x, min_y)
max_x_px, max_y_px = self.canvas.convert_to_pixels(max_x, max_y)
dx = max_x - min_x
dy = max_y - min_y
dx_px = max_x_px - min_x_px
dy_px = max_y_px - min_y_px
hadj = self._scrolled_window.get_hadjustment()
vadj = self._scrolled_window.get_vadjustment()
new_dx, new_dy = 1.5*dx_px, 1.5*dy_px
if new_dx == 0 or new_dy == 0:
return
self.zoom.value = min(hadj.page_size/new_dx, vadj.page_size/new_dy)
x1, y1 = self.canvas.convert_from_pixels(hadj.value, vadj.value)
x2, y2 = self.canvas.convert_from_pixels(hadj.value+hadj.page_size, vadj.value+vadj.page_size)
width = x2 - x1
height = y2 - y1
center_x = (min_x + max_x) / 2
center_y = (min_y + max_y) / 2
self.canvas.scroll_to(center_x - width/2, center_y - height/2)
return False
def start(self):
self.scan_topology()
self.window.connect("delete-event", self._quit)
#self._start_update_timer()
gobject.timeout_add(200, self.autoscale_view)
self.simulation.start()
try:
__IPYTHON__
except NameError:
pass
else:
self._monkey_patch_ipython()
gtk.main()
def on_root_button_press_event(self, view, target, event):
if event.button == 1:
self.select_node(None)
return True
def on_node_button_press_event(self, view, target, event, node):
if event.button == 1:
self.select_node(node)
return True
elif event.button == 3:
self.popup_node_menu(node, event)
return True
elif event.button == 2:
self.begin_node_drag(node)
return True
return False
def on_node_button_release_event(self, view, target, event, node):
if event.button == 2:
self.end_node_drag(node)
return True
return False
class NodeDragState(object):
def __init__(self, canvas_x0, canvas_y0, sim_x0, sim_y0):
self.canvas_x0 = canvas_x0
self.canvas_y0 = canvas_y0
self.sim_x0 = sim_x0
self.sim_y0 = sim_y0
self.motion_signal = None
def begin_node_drag(self, node):
self.simulation.lock.acquire()
try:
ns3_node = ns.network.NodeList.GetNode(node.node_index)
mob = ns3_node.GetObject(ns.mobility.MobilityModel.GetTypeId())
if mob is None:
return
if self.node_drag_state is not None:
return
pos = mob.GetPosition()
finally:
self.simulation.lock.release()
x, y, dummy = self.canvas.window.get_pointer()
x0, y0 = self.canvas.convert_from_pixels(x, y)
self.node_drag_state = self.NodeDragState(x0, y0, pos.x, pos.y)
self.node_drag_state.motion_signal = node.canvas_item.connect("motion-notify-event", self.node_drag_motion, node)
def node_drag_motion(self, item, targe_item, event, node):
self.simulation.lock.acquire()
try:
ns3_node = ns.network.NodeList.GetNode(node.node_index)
mob = ns3_node.GetObject(ns.mobility.MobilityModel.GetTypeId())
if mob is None:
return False
if self.node_drag_state is None:
return False
x, y, dummy = self.canvas.window.get_pointer()
canvas_x, canvas_y = self.canvas.convert_from_pixels(x, y)
dx = (canvas_x - self.node_drag_state.canvas_x0)
dy = (canvas_y - self.node_drag_state.canvas_y0)
pos = mob.GetPosition()
pos.x = self.node_drag_state.sim_x0 + transform_distance_canvas_to_simulation(dx)
pos.y = self.node_drag_state.sim_y0 + transform_distance_canvas_to_simulation(dy)
#print "SetPosition(%G, %G)" % (pos.x, pos.y)
mob.SetPosition(pos)
node.set_position(*transform_point_simulation_to_canvas(pos.x, pos.y))
finally:
self.simulation.lock.release()
return True
def end_node_drag(self, node):
if self.node_drag_state is None:
return
node.canvas_item.disconnect(self.node_drag_state.motion_signal)
self.node_drag_state = None
def popup_node_menu(self, node, event):
menu = gtk.Menu()
self.emit("populate-node-menu", node, menu)
menu.popup(None, None, None, event.button, event.time)
def _update_ipython_selected_node(self):
# If we are running under ipython -gthread, make this new
# selected node available as a global 'selected_node'
# variable.
try:
__IPYTHON__
except NameError:
pass
else:
if self.selected_node is None:
ns3_node = None
else:
self.simulation.lock.acquire()
try:
ns3_node = ns.network.NodeList.GetNode(self.selected_node.node_index)
finally:
self.simulation.lock.release()
self.ipython.updateNamespace({'selected_node': ns3_node})
def select_node(self, node):
if isinstance(node, ns.network.Node):
node = self.nodes[node.GetId()]
elif isinstance(node, (int, long)):
node = self.nodes[node]
elif isinstance(node, Node):
pass
elif node is None:
pass
else:
raise TypeError("expected None, int, viz.Node or ns.network.Node, not %r" % node)
if node is self.selected_node:
return
if self.selected_node is not None:
self.selected_node.selected = False
self.selected_node = node
if self.selected_node is not None:
self.selected_node.selected = True
if self._show_transmissions_mode == ShowTransmissionsMode.SELECTED:
if self.selected_node is None:
self.simulation.set_nodes_of_interest([])
else:
self.simulation.set_nodes_of_interest([self.selected_node.node_index])
self._update_ipython_selected_node()
def add_information_window(self, info_win):
self.information_windows.append(info_win)
self.simulation.lock.acquire()
try:
info_win.update()
finally:
self.simulation.lock.release()
def remove_information_window(self, info_win):
self.information_windows.remove(info_win)
def _canvas_tooltip_cb(self, canvas, x, y, keyboard_mode, tooltip):
#print "tooltip query: ", x, y
hadj = self._scrolled_window.get_hadjustment()
vadj = self._scrolled_window.get_vadjustment()
x, y = self.canvas.convert_from_pixels(hadj.value + x, vadj.value + y)
item = self.canvas.get_item_at(x, y, True)
#print "items at (%f, %f): %r | keyboard_mode=%r" % (x, y, item, keyboard_mode)
if not item:
return False
while item is not None:
obj = item.get_data("pyviz-object")
if obj is not None:
obj.tooltip_query(tooltip)
return True
item = item.props.parent
return False
def _get_export_file_name(self):
sel = gtk.FileChooserDialog("Save...", self.canvas.get_toplevel(),
gtk.FILE_CHOOSER_ACTION_SAVE,
(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
gtk.STOCK_SAVE, gtk.RESPONSE_OK))
sel.set_default_response(gtk.RESPONSE_OK)
sel.set_local_only(True)
sel.set_do_overwrite_confirmation(True)
sel.set_current_name("Unnamed.pdf")
filter = gtk.FileFilter()
filter.set_name("Embedded PostScript")
filter.add_mime_type("image/x-eps")
sel.add_filter(filter)
filter = gtk.FileFilter()
filter.set_name("Portable Document Graphics")
filter.add_mime_type("application/pdf")
sel.add_filter(filter)
filter = gtk.FileFilter()
filter.set_name("Scalable Vector Graphics")
filter.add_mime_type("image/svg+xml")
sel.add_filter(filter)
resp = sel.run()
if resp != gtk.RESPONSE_OK:
sel.destroy()
return None
file_name = sel.get_filename()
sel.destroy()
return file_name
def _take_screenshot(self, dummy_button):
#print "Cheese!"
file_name = self._get_export_file_name()
if file_name is None:
return
# figure out the correct bounding box for what is visible on screen
x1 = self._scrolled_window.get_hadjustment().value
y1 = self._scrolled_window.get_vadjustment().value
x2 = x1 + self._scrolled_window.get_hadjustment().page_size
y2 = y1 + self._scrolled_window.get_vadjustment().page_size
bounds = goocanvas.Bounds()
bounds.x1, bounds.y1 = self.canvas.convert_from_pixels(x1, y1)
bounds.x2, bounds.y2 = self.canvas.convert_from_pixels(x2, y2)
dest_width = bounds.x2 - bounds.x1
dest_height = bounds.y2 - bounds.y1
#print bounds.x1, bounds.y1, " -> ", bounds.x2, bounds.y2
dummy, extension = os.path.splitext(file_name)
extension = extension.lower()
if extension == '.eps':
surface = cairo.PSSurface(file_name, dest_width, dest_height)
elif extension == '.pdf':
surface = cairo.PDFSurface(file_name, dest_width, dest_height)
elif extension == '.svg':
surface = cairo.SVGSurface(file_name, dest_width, dest_height)
else:
dialog = gtk.MessageDialog(parent = self.canvas.get_toplevel(),
flags = gtk.DIALOG_DESTROY_WITH_PARENT,
type = gtk.MESSAGE_ERROR,
buttons = gtk.BUTTONS_OK,
message_format = "Unknown extension '%s' (valid extensions are '.eps', '.svg', and '.pdf')"
% (extension,))
dialog.run()
dialog.destroy()
return
# draw the canvas to a printing context
cr = cairo.Context(surface)
cr.translate(-bounds.x1, -bounds.y1)
self.canvas.render(cr, bounds, self.zoom.value)
cr.show_page()
surface.finish()
def set_follow_node(self, node):
if isinstance(node, ns.network.Node):
node = self.nodes[node.GetId()]
self.follow_node = node
def _start_shell(self, dummy_button):
if self.shell_window is not None:
self.shell_window.present()
return
self.shell_window = gtk.Window()
self.shell_window.set_size_request(750,550)
self.shell_window.set_resizable(True)
scrolled_window = gtk.ScrolledWindow()
scrolled_window.set_policy(gtk.POLICY_AUTOMATIC,gtk.POLICY_AUTOMATIC)
self.ipython = ipython_view.IPythonView()
self.ipython.modify_font(pango.FontDescription(SHELL_FONT))
self.ipython.set_wrap_mode(gtk.WRAP_CHAR)
self.ipython.show()
scrolled_window.add(self.ipython)
scrolled_window.show()
self.shell_window.add(scrolled_window)
self.shell_window.show()
self.shell_window.connect('destroy', self._on_shell_window_destroy)
self._update_ipython_selected_node()
self.ipython.updateNamespace({'viz': self})
def _on_shell_window_destroy(self, window):
self.shell_window = None
initialization_hooks = []
def add_initialization_hook(hook, *args):
"""
Adds a callback to be called after
the visualizer is initialized, like this::
initialization_hook(visualizer, *args)
"""
global initialization_hooks
initialization_hooks.append((hook, args))
def set_bounds(x1, y1, x2, y2):
assert x2>x1
assert y2>y1
def hook(viz):
cx1, cy1 = transform_point_simulation_to_canvas(x1, y1)
cx2, cy2 = transform_point_simulation_to_canvas(x2, y2)
viz.canvas.set_bounds(cx1, cy1, cx2, cy2)
add_initialization_hook(hook)
def start():
assert Visualizer.INSTANCE is None
if _import_error is not None:
import sys
print >> sys.stderr, "No visualization support (%s)." % (str(_import_error),)
ns.core.Simulator.Run()
return
load_plugins()
viz = Visualizer()
for hook, args in initialization_hooks:
gobject.idle_add(hook, viz, *args)
ns.network.Packet.EnablePrinting()
viz.start()
| gpl-2.0 |
julioeiras/django-rest-auth | rest_auth/views.py | 20 | 5140 | from django.contrib.auth import login, logout
from django.conf import settings
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.generics import GenericAPIView
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework.authtoken.models import Token
from rest_framework.generics import RetrieveUpdateAPIView
from .app_settings import (
TokenSerializer, UserDetailsSerializer, LoginSerializer,
PasswordResetSerializer, PasswordResetConfirmSerializer,
PasswordChangeSerializer
)
class LoginView(GenericAPIView):
"""
Check the credentials and return the REST Token
if the credentials are valid and authenticated.
Calls Django Auth login method to register User ID
in Django session framework
Accept the following POST parameters: username, password
Return the REST Framework Token Object's key.
"""
permission_classes = (AllowAny,)
serializer_class = LoginSerializer
token_model = Token
response_serializer = TokenSerializer
def login(self):
self.user = self.serializer.validated_data['user']
self.token, created = self.token_model.objects.get_or_create(
user=self.user)
if getattr(settings, 'REST_SESSION_LOGIN', True):
login(self.request, self.user)
def get_response(self):
return Response(
self.response_serializer(self.token).data, status=status.HTTP_200_OK
)
def get_error_response(self):
return Response(
self.serializer.errors, status=status.HTTP_400_BAD_REQUEST
)
def post(self, request, *args, **kwargs):
self.serializer = self.get_serializer(data=self.request.data)
if not self.serializer.is_valid():
return self.get_error_response()
self.login()
return self.get_response()
class LogoutView(APIView):
"""
Calls Django logout method and delete the Token object
assigned to the current User object.
Accepts/Returns nothing.
"""
permission_classes = (AllowAny,)
def post(self, request):
try:
request.user.auth_token.delete()
except:
pass
logout(request)
return Response({"success": "Successfully logged out."},
status=status.HTTP_200_OK)
class UserDetailsView(RetrieveUpdateAPIView):
"""
Returns User's details in JSON format.
Accepts the following GET parameters: token
Accepts the following POST parameters:
Required: token
Optional: email, first_name, last_name and UserProfile fields
Returns the updated UserProfile and/or User object.
"""
serializer_class = UserDetailsSerializer
permission_classes = (IsAuthenticated,)
def get_object(self):
return self.request.user
class PasswordResetView(GenericAPIView):
"""
Calls Django Auth PasswordResetForm save method.
Accepts the following POST parameters: email
Returns the success/fail message.
"""
serializer_class = PasswordResetSerializer
permission_classes = (AllowAny,)
def post(self, request, *args, **kwargs):
# Create a serializer with request.data
serializer = self.get_serializer(data=request.data)
if not serializer.is_valid():
return Response(serializer.errors,
status=status.HTTP_400_BAD_REQUEST)
serializer.save()
# Return the success message with OK HTTP status
return Response(
{"success": "Password reset e-mail has been sent."},
status=status.HTTP_200_OK
)
class PasswordResetConfirmView(GenericAPIView):
"""
Password reset e-mail link is confirmed, therefore this resets the user's password.
Accepts the following POST parameters: new_password1, new_password2
Accepts the following Django URL arguments: token, uid
Returns the success/fail message.
"""
serializer_class = PasswordResetConfirmSerializer
permission_classes = (AllowAny,)
def post(self, request):
serializer = self.get_serializer(data=request.data)
if not serializer.is_valid():
return Response(
serializer.errors, status=status.HTTP_400_BAD_REQUEST
)
serializer.save()
return Response({"success": "Password has been reset with the new password."})
class PasswordChangeView(GenericAPIView):
"""
Calls Django Auth SetPasswordForm save method.
Accepts the following POST parameters: new_password1, new_password2
Returns the success/fail message.
"""
serializer_class = PasswordChangeSerializer
permission_classes = (IsAuthenticated,)
def post(self, request):
serializer = self.get_serializer(data=request.data)
if not serializer.is_valid():
return Response(
serializer.errors, status=status.HTTP_400_BAD_REQUEST
)
serializer.save()
return Response({"success": "New password has been saved."})
| mit |
64studio/smart | smart/channels/mirrors.py | 8 | 2662 | #
# Copyright (c) 2004 Conectiva, Inc.
#
# Written by Gustavo Niemeyer <niemeyer@conectiva.com>
#
# This file is part of Smart Package Manager.
#
# Smart Package Manager 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.
#
# Smart Package Manager 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 Smart Package Manager; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
from smart.const import SUCCEEDED, FAILED, NEVER
from smart.channel import MirrorsChannel
from smart import *
import posixpath
class StandardMirrorsChannel(MirrorsChannel):
def __init__(self, url, *args):
super(StandardMirrorsChannel, self).__init__(*args)
self._url = url
def getFetchSteps(self):
return 1
def fetch(self, fetcher, progress):
mirrors = self._mirrors
mirrors.clear()
fetcher.reset()
item = fetcher.enqueue(self._url, uncomp=True)
fetcher.run(progress=progress)
if item.getStatus() == SUCCEEDED:
localpath = item.getTargetPath()
origin = None
for line in open(localpath):
if line[0].isspace():
if origin:
mirror = line.strip()
if mirror:
if origin in mirrors:
if mirror not in mirrors[origin]:
mirrors[origin].append(mirror)
else:
mirrors[origin] = [mirror]
else:
origin = line.strip()
elif fetcher.getCaching() is NEVER:
lines = [_("Failed acquiring information for '%s':") % self,
u"%s: %s" % (item.getURL(), item.getFailedReason())]
raise Error, "\n".join(lines)
return True
def create(alias, data):
return StandardMirrorsChannel(data["url"],
data["type"],
alias,
data["name"],
data["manual"],
data["removable"])
# vim:ts=4:sw=4:et
| gpl-2.0 |
pluser/nikola_plugins | v6/spell_check/spell_check.py | 4 | 3572 | # -*- coding: utf-8 -*-
# Copyright © 2014 Puneeth Chaganti
# 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 __future__ import print_function, unicode_literals
from nikola.plugin_categories import LateTask
from nikola.utils import config_changed, LOGGER
import enchant
from enchant.checker import SpellChecker
from enchant.tokenize import EmailFilter, URLFilter
class RenderPosts(LateTask):
""" Run spell check on any post that may have changed. """
name = 'spell_check'
def __init__(self):
super(RenderPosts, self).__init__()
self._dicts = dict()
self._langs = enchant.list_languages()
def gen_tasks(self):
""" Run spell check on any post that may have changed. """
self.site.scan_posts()
kw = {'translations': self.site.config['TRANSLATIONS']}
yield self.group_task()
for lang in kw['translations']:
for post in self.site.timeline[:]:
path = post.fragment_deps(lang)
task = {
'basename': self.name,
'name': path,
'file_dep': path,
'actions': [(self.spell_check, (post, lang, ))],
'clean': True,
'uptodate': [config_changed(kw)],
}
yield task
def spell_check(self, post, lang):
""" Check spellings for the given post and given language. """
if enchant.dict_exists(lang):
checker = SpellChecker(lang, filters=[EmailFilter, URLFilter])
checker.set_text(post.text(lang=lang, strip_html=True))
words = [error.word for error in checker]
words = [
word for word in words if
self._not_in_other_dictionaries(word, lang)
]
LOGGER.notice(
'Mis-spelt words in %s: %s' % (
post.fragment_deps(lang), ', '.join(words)
)
)
else:
LOGGER.notice('No dictionary found for %s' % lang)
def _not_in_other_dictionaries(self, word, lang):
""" Return True if the word is not present any dictionary for the lang.
"""
for language in self._langs:
if language.startswith('%s_' % lang): # look for en_GB, en_US, ...
dictionary = self._dicts.setdefault(
language, enchant.Dict(language)
)
if dictionary.check(word):
return False
return True
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.