repo_name stringlengths 6 100 | path stringlengths 4 294 | copies stringlengths 1 5 | size stringlengths 4 6 | content stringlengths 606 896k | license stringclasses 15
values |
|---|---|---|---|---|---|
gonboy/sl4a | python/src/Lib/lib2to3/fixes/fix_tuple_params.py | 53 | 5405 | """Fixer for function definitions with tuple parameters.
def func(((a, b), c), d):
...
->
def func(x, d):
((a, b), c) = x
...
It will also support lambdas:
lambda (x, y): x + y -> lambda t: t[0] + t[1]
# The parens are a syntax error in Python 3
lambda (x): x + y -> lambda x: x + y
"""
# Author: Collin Winter
# Local imports
from .. import pytree
from ..pgen2 import token
from .. import fixer_base
from ..fixer_util import Assign, Name, Newline, Number, Subscript, syms
def is_docstring(stmt):
return isinstance(stmt, pytree.Node) and \
stmt.children[0].type == token.STRING
class FixTupleParams(fixer_base.BaseFix):
PATTERN = """
funcdef< 'def' any parameters< '(' args=any ')' >
['->' any] ':' suite=any+ >
|
lambda=
lambdef< 'lambda' args=vfpdef< '(' inner=any ')' >
':' body=any
>
"""
def transform(self, node, results):
if "lambda" in results:
return self.transform_lambda(node, results)
new_lines = []
suite = results["suite"]
args = results["args"]
# This crap is so "def foo(...): x = 5; y = 7" is handled correctly.
# TODO(cwinter): suite-cleanup
if suite[0].children[1].type == token.INDENT:
start = 2
indent = suite[0].children[1].value
end = Newline()
else:
start = 0
indent = "; "
end = pytree.Leaf(token.INDENT, "")
# We need access to self for new_name(), and making this a method
# doesn't feel right. Closing over self and new_lines makes the
# code below cleaner.
def handle_tuple(tuple_arg, add_prefix=False):
n = Name(self.new_name())
arg = tuple_arg.clone()
arg.set_prefix("")
stmt = Assign(arg, n.clone())
if add_prefix:
n.set_prefix(" ")
tuple_arg.replace(n)
new_lines.append(pytree.Node(syms.simple_stmt,
[stmt, end.clone()]))
if args.type == syms.tfpdef:
handle_tuple(args)
elif args.type == syms.typedargslist:
for i, arg in enumerate(args.children):
if arg.type == syms.tfpdef:
# Without add_prefix, the emitted code is correct,
# just ugly.
handle_tuple(arg, add_prefix=(i > 0))
if not new_lines:
return node
# This isn't strictly necessary, but it plays nicely with other fixers.
# TODO(cwinter) get rid of this when children becomes a smart list
for line in new_lines:
line.parent = suite[0]
# TODO(cwinter) suite-cleanup
after = start
if start == 0:
new_lines[0].set_prefix(" ")
elif is_docstring(suite[0].children[start]):
new_lines[0].set_prefix(indent)
after = start + 1
suite[0].children[after:after] = new_lines
for i in range(after+1, after+len(new_lines)+1):
suite[0].children[i].set_prefix(indent)
suite[0].changed()
def transform_lambda(self, node, results):
args = results["args"]
body = results["body"]
inner = simplify_args(results["inner"])
# Replace lambda ((((x)))): x with lambda x: x
if inner.type == token.NAME:
inner = inner.clone()
inner.set_prefix(" ")
args.replace(inner)
return
params = find_params(args)
to_index = map_to_index(params)
tup_name = self.new_name(tuple_name(params))
new_param = Name(tup_name, prefix=" ")
args.replace(new_param.clone())
for n in body.post_order():
if n.type == token.NAME and n.value in to_index:
subscripts = [c.clone() for c in to_index[n.value]]
new = pytree.Node(syms.power,
[new_param.clone()] + subscripts)
new.set_prefix(n.get_prefix())
n.replace(new)
### Helper functions for transform_lambda()
def simplify_args(node):
if node.type in (syms.vfplist, token.NAME):
return node
elif node.type == syms.vfpdef:
# These look like vfpdef< '(' x ')' > where x is NAME
# or another vfpdef instance (leading to recursion).
while node.type == syms.vfpdef:
node = node.children[1]
return node
raise RuntimeError("Received unexpected node %s" % node)
def find_params(node):
if node.type == syms.vfpdef:
return find_params(node.children[1])
elif node.type == token.NAME:
return node.value
return [find_params(c) for c in node.children if c.type != token.COMMA]
def map_to_index(param_list, prefix=[], d=None):
if d is None:
d = {}
for i, obj in enumerate(param_list):
trailer = [Subscript(Number(i))]
if isinstance(obj, list):
map_to_index(obj, trailer, d=d)
else:
d[obj] = prefix + trailer
return d
def tuple_name(param_list):
l = []
for obj in param_list:
if isinstance(obj, list):
l.append(tuple_name(obj))
else:
l.append(obj)
return "_".join(l)
| apache-2.0 |
DataSploit/datasploit | domain/domain_checkpunkspider.py | 3 | 1584 | #!/usr/bin/env python
import base
import requests
import sys
import json
import warnings
from termcolor import colored
import time
ENABLED = True
class style:
BOLD = '\033[1m'
END = '\033[0m'
warnings.filterwarnings("ignore")
def checkpunkspider(reversed_domain):
time.sleep(0.5)
req = requests.post("http://www.punkspider.org/service/search/detail/" + reversed_domain, verify=False)
try:
return json.loads(req.content)
except:
return {}
def banner():
print colored(style.BOLD + '\n---> Trying luck with PunkSpider\n' + style.END, 'blue')
def main(domain):
reversed_domain = ""
for x in reversed(domain.split(".")):
reversed_domain = reversed_domain + "." + x
reversed_domain = reversed_domain[1:]
return checkpunkspider(reversed_domain)
def output(data, domain=""):
if data is not None:
if 'data' in data.keys() and len(data['data']) >= 1:
print colored("Few vulnerabilities found at Punkspider", 'green')
for x in data['data']:
print "==> ", x['bugType']
print "Method:", x['verb'].upper()
print "URL:\n" + x['vulnerabilityUrl']
print "Param:", x['parameter']
else:
print colored("[-] No Vulnerabilities found on PunkSpider\n", 'red')
if __name__ == "__main__":
try:
domain = sys.argv[1]
banner()
result = main(domain)
output(result, domain)
except Exception as e:
print e
print "Please provide a domain name as argument"
| gpl-3.0 |
cevaris/pants | contrib/cpp/src/python/pants/contrib/cpp/targets/cpp_binary.py | 14 | 1101 | # coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from pants.base.payload import Payload
from pants.base.payload_field import PrimitiveField
from pants.contrib.cpp.targets.cpp_target import CppTarget
class CppBinary(CppTarget):
"""A C++ binary."""
def __init__(self,
libraries=None,
*args,
**kwargs):
"""
:param libraries: Libraries that this target depends on that are not pants targets.
For example, 'm' or 'rt' that are expected to be installed on the local system.
:type libraries: List of libraries to link against.
"""
payload = Payload()
payload.add_fields({
'libraries': PrimitiveField(libraries)
})
super(CppBinary, self).__init__(payload=payload, **kwargs)
@property
def libraries(self):
return self.payload.get_field_value('libraries')
| apache-2.0 |
xen0l/ansible | lib/ansible/modules/cloud/amazon/ec2_eip.py | 33 | 16618 | #!/usr/bin/python
# Copyright: Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'certified'}
DOCUMENTATION = '''
---
module: ec2_eip
short_description: manages EC2 elastic IP (EIP) addresses.
description:
- This module can allocate or release an EIP.
- This module can associate/disassociate an EIP with instances or network interfaces.
version_added: "1.4"
options:
device_id:
description:
- The id of the device for the EIP. Can be an EC2 Instance id or Elastic Network Interface (ENI) id.
required: false
aliases: [ instance_id ]
version_added: "2.0"
public_ip:
description:
- The IP address of a previously allocated EIP.
- If present and device is specified, the EIP is associated with the device.
- If absent and device is specified, the EIP is disassociated from the device.
aliases: [ ip ]
state:
description:
- If present, allocate an EIP or associate an existing EIP with a device.
- If absent, disassociate the EIP from the device and optionally release it.
choices: ['present', 'absent']
default: present
in_vpc:
description:
- Allocate an EIP inside a VPC or not. Required if specifying an ENI.
default: 'no'
version_added: "1.4"
reuse_existing_ip_allowed:
description:
- Reuse an EIP that is not associated to a device (when available), instead of allocating a new one.
default: 'no'
version_added: "1.6"
release_on_disassociation:
description:
- whether or not to automatically release the EIP when it is disassociated
default: 'no'
version_added: "2.0"
private_ip_address:
description:
- The primary or secondary private IP address to associate with the Elastic IP address.
version_added: "2.3"
allow_reassociation:
description:
- Specify this option to allow an Elastic IP address that is already associated with another
network interface or instance to be re-associated with the specified instance or interface.
default: 'no'
version_added: "2.5"
extends_documentation_fragment:
- aws
- ec2
author: "Rick Mendes (@rickmendes) <rmendes@illumina.com>"
notes:
- There may be a delay between the time the EIP is assigned and when
the cloud instance is reachable via the new address. Use wait_for and
pause to delay further playbook execution until the instance is reachable,
if necessary.
- This module returns multiple changed statuses on disassociation or release.
It returns an overall status based on any changes occurring. It also returns
individual changed statuses for disassociation and release.
'''
EXAMPLES = '''
# Note: These examples do not set authentication details, see the AWS Guide for details.
- name: associate an elastic IP with an instance
ec2_eip:
device_id: i-1212f003
ip: 93.184.216.119
- name: associate an elastic IP with a device
ec2_eip:
device_id: eni-c8ad70f3
ip: 93.184.216.119
- name: associate an elastic IP with a device and allow reassociation
ec2_eip:
device_id: eni-c8ad70f3
public_ip: 93.184.216.119
allow_reassociation: yes
- name: disassociate an elastic IP from an instance
ec2_eip:
device_id: i-1212f003
ip: 93.184.216.119
state: absent
- name: disassociate an elastic IP with a device
ec2_eip:
device_id: eni-c8ad70f3
ip: 93.184.216.119
state: absent
- name: allocate a new elastic IP and associate it with an instance
ec2_eip:
device_id: i-1212f003
- name: allocate a new elastic IP without associating it to anything
ec2_eip:
state: present
register: eip
- name: output the IP
debug:
msg: "Allocated IP is {{ eip.public_ip }}"
- name: provision new instances with ec2
ec2:
keypair: mykey
instance_type: c1.medium
image: ami-40603AD1
wait: yes
group: webserver
count: 3
register: ec2
- name: associate new elastic IPs with each of the instances
ec2_eip:
device_id: "{{ item }}"
with_items: "{{ ec2.instance_ids }}"
- name: allocate a new elastic IP inside a VPC in us-west-2
ec2_eip:
region: us-west-2
in_vpc: yes
register: eip
- name: output the IP
debug:
msg: "Allocated IP inside a VPC is {{ eip.public_ip }}"
'''
RETURN = '''
allocation_id:
description: allocation_id of the elastic ip
returned: on success
type: string
sample: eipalloc-51aa3a6c
public_ip:
description: an elastic ip address
returned: on success
type: string
sample: 52.88.159.209
'''
try:
import boto.exception
except ImportError:
pass # Taken care of by ec2.HAS_BOTO
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ec2 import HAS_BOTO, ec2_argument_spec, ec2_connect
class EIPException(Exception):
pass
def associate_ip_and_device(ec2, address, private_ip_address, device_id, allow_reassociation, check_mode, isinstance=True):
if address_is_associated_with_device(ec2, address, device_id, isinstance):
return {'changed': False}
# If we're in check mode, nothing else to do
if not check_mode:
if isinstance:
if address.domain == "vpc":
res = ec2.associate_address(device_id,
allocation_id=address.allocation_id,
private_ip_address=private_ip_address,
allow_reassociation=allow_reassociation)
else:
res = ec2.associate_address(device_id,
public_ip=address.public_ip,
private_ip_address=private_ip_address,
allow_reassociation=allow_reassociation)
else:
res = ec2.associate_address(network_interface_id=device_id,
allocation_id=address.allocation_id,
private_ip_address=private_ip_address,
allow_reassociation=allow_reassociation)
if not res:
raise EIPException('association failed')
return {'changed': True}
def disassociate_ip_and_device(ec2, address, device_id, check_mode, isinstance=True):
if not address_is_associated_with_device(ec2, address, device_id, isinstance):
return {'changed': False}
# If we're in check mode, nothing else to do
if not check_mode:
if address.domain == 'vpc':
res = ec2.disassociate_address(
association_id=address.association_id)
else:
res = ec2.disassociate_address(public_ip=address.public_ip)
if not res:
raise EIPException('disassociation failed')
return {'changed': True}
def _find_address_by_ip(ec2, public_ip):
try:
return ec2.get_all_addresses([public_ip])[0]
except boto.exception.EC2ResponseError as e:
if "Address '{}' not found.".format(public_ip) not in e.message:
raise
def _find_address_by_device_id(ec2, device_id, isinstance=True):
if isinstance:
addresses = ec2.get_all_addresses(None, {'instance-id': device_id})
else:
addresses = ec2.get_all_addresses(None, {'network-interface-id': device_id})
if addresses:
return addresses[0]
def find_address(ec2, public_ip, device_id, isinstance=True):
""" Find an existing Elastic IP address """
if public_ip:
return _find_address_by_ip(ec2, public_ip)
elif device_id and isinstance:
return _find_address_by_device_id(ec2, device_id)
elif device_id:
return _find_address_by_device_id(ec2, device_id, isinstance=False)
def address_is_associated_with_device(ec2, address, device_id, isinstance=True):
""" Check if the elastic IP is currently associated with the device """
address = ec2.get_all_addresses(address.public_ip)
if address:
if isinstance:
return address and address[0].instance_id == device_id
else:
return address and address[0].network_interface_id == device_id
return False
def allocate_address(ec2, domain, reuse_existing_ip_allowed):
""" Allocate a new elastic IP address (when needed) and return it """
if reuse_existing_ip_allowed:
domain_filter = {'domain': domain or 'standard'}
all_addresses = ec2.get_all_addresses(filters=domain_filter)
if domain == 'vpc':
unassociated_addresses = [a for a in all_addresses
if not a.association_id]
else:
unassociated_addresses = [a for a in all_addresses
if not a.instance_id]
if unassociated_addresses:
return unassociated_addresses[0], False
return ec2.allocate_address(domain=domain), True
def release_address(ec2, address, check_mode):
""" Release a previously allocated elastic IP address """
# If we're in check mode, nothing else to do
if not check_mode:
if not address.release():
EIPException('release failed')
return {'changed': True}
def find_device(ec2, module, device_id, isinstance=True):
""" Attempt to find the EC2 instance and return it """
if isinstance:
try:
reservations = ec2.get_all_reservations(instance_ids=[device_id])
except boto.exception.EC2ResponseError as e:
module.fail_json(msg=str(e))
if len(reservations) == 1:
instances = reservations[0].instances
if len(instances) == 1:
return instances[0]
else:
try:
interfaces = ec2.get_all_network_interfaces(network_interface_ids=[device_id])
except boto.exception.EC2ResponseError as e:
module.fail_json(msg=str(e))
if len(interfaces) == 1:
return interfaces[0]
raise EIPException("could not find instance" + device_id)
def ensure_present(ec2, module, domain, address, private_ip_address, device_id,
reuse_existing_ip_allowed, allow_reassociation, check_mode, isinstance=True):
changed = False
# Return the EIP object since we've been given a public IP
if not address:
if check_mode:
return {'changed': True}
address, changed = allocate_address(ec2, domain, reuse_existing_ip_allowed)
if device_id:
# Allocate an IP for instance since no public_ip was provided
if isinstance:
instance = find_device(ec2, module, device_id)
if reuse_existing_ip_allowed:
if instance.vpc_id and len(instance.vpc_id) > 0 and domain is None:
raise EIPException("You must set 'in_vpc' to true to associate an instance with an existing ip in a vpc")
# Associate address object (provided or allocated) with instance
assoc_result = associate_ip_and_device(ec2, address, private_ip_address, device_id, allow_reassociation,
check_mode)
else:
instance = find_device(ec2, module, device_id, isinstance=False)
# Associate address object (provided or allocated) with instance
assoc_result = associate_ip_and_device(ec2, address, private_ip_address, device_id, allow_reassociation,
check_mode, isinstance=False)
if instance.vpc_id:
domain = 'vpc'
changed = changed or assoc_result['changed']
return {'changed': changed, 'public_ip': address.public_ip, 'allocation_id': address.allocation_id}
def ensure_absent(ec2, domain, address, device_id, check_mode, isinstance=True):
if not address:
return {'changed': False}
# disassociating address from instance
if device_id:
if isinstance:
return disassociate_ip_and_device(ec2, address, device_id,
check_mode)
else:
return disassociate_ip_and_device(ec2, address, device_id,
check_mode, isinstance=False)
# releasing address
else:
return release_address(ec2, address, check_mode)
def main():
argument_spec = ec2_argument_spec()
argument_spec.update(dict(
device_id=dict(required=False, aliases=['instance_id']),
public_ip=dict(required=False, aliases=['ip']),
state=dict(required=False, default='present',
choices=['present', 'absent']),
in_vpc=dict(required=False, type='bool', default=False),
reuse_existing_ip_allowed=dict(required=False, type='bool',
default=False),
release_on_disassociation=dict(required=False, type='bool', default=False),
allow_reassociation=dict(type='bool', default=False),
wait_timeout=dict(default=300),
private_ip_address=dict(required=False, default=None, type='str')
))
module = AnsibleModule(
argument_spec=argument_spec,
supports_check_mode=True
)
if not HAS_BOTO:
module.fail_json(msg='boto required for this module')
ec2 = ec2_connect(module)
device_id = module.params.get('device_id')
instance_id = module.params.get('instance_id')
public_ip = module.params.get('public_ip')
private_ip_address = module.params.get('private_ip_address')
state = module.params.get('state')
in_vpc = module.params.get('in_vpc')
domain = 'vpc' if in_vpc else None
reuse_existing_ip_allowed = module.params.get('reuse_existing_ip_allowed')
release_on_disassociation = module.params.get('release_on_disassociation')
allow_reassociation = module.params.get('allow_reassociation')
# Parameter checks
if private_ip_address is not None and device_id is None:
module.fail_json(msg="parameters are required together: ('device_id', 'private_ip_address')")
if instance_id:
warnings = ["instance_id is no longer used, please use device_id going forward"]
is_instance = True
device_id = instance_id
else:
if device_id and device_id.startswith('i-'):
is_instance = True
elif device_id:
if device_id.startswith('eni-') and not in_vpc:
module.fail_json(msg="If you are specifying an ENI, in_vpc must be true")
is_instance = False
try:
if device_id:
address = find_address(ec2, public_ip, device_id, isinstance=is_instance)
else:
address = find_address(ec2, public_ip, None)
if state == 'present':
if device_id:
result = ensure_present(ec2, module, domain, address, private_ip_address, device_id,
reuse_existing_ip_allowed, allow_reassociation,
module.check_mode, isinstance=is_instance)
else:
if address:
changed = False
else:
address, changed = allocate_address(ec2, domain, reuse_existing_ip_allowed)
result = {'changed': changed, 'public_ip': address.public_ip, 'allocation_id': address.allocation_id}
else:
if device_id:
disassociated = ensure_absent(ec2, domain, address, device_id, module.check_mode, isinstance=is_instance)
if release_on_disassociation and disassociated['changed']:
released = release_address(ec2, address, module.check_mode)
result = {'changed': True, 'disassociated': disassociated, 'released': released}
else:
result = {'changed': disassociated['changed'], 'disassociated': disassociated, 'released': {'changed': False}}
else:
released = release_address(ec2, address, module.check_mode)
result = {'changed': released['changed'], 'disassociated': {'changed': False}, 'released': released}
except (boto.exception.EC2ResponseError, EIPException) as e:
module.fail_json(msg=str(e))
if instance_id:
result['warnings'] = warnings
module.exit_json(**result)
if __name__ == '__main__':
main()
| gpl-3.0 |
SiPiggles/djangae | djangae/tests/test_query_transform.py | 6 | 20184 | from django.db.models.sql.datastructures import EmptyResultSet
from django.db import models, connections
from djangae.test import TestCase
from djangae.db.backends.appengine.query import transform_query, Query, WhereNode
from django.db.models.query import Q
from google.appengine.api import datastore
class TransformTestModel(models.Model):
field1 = models.CharField(max_length=255)
field2 = models.CharField(max_length=255, unique=True)
field3 = models.CharField(null=True, max_length=255)
field4 = models.TextField()
class Meta:
app_label = "djangae"
class InheritedModel(TransformTestModel):
class Meta:
app_label = "djangae"
class TransformQueryTest(TestCase):
def test_polymodel_filter_applied(self):
query = transform_query(
connections['default'],
InheritedModel.objects.filter(field1="One").all().query
)
query.prepare()
self.assertEqual(2, len(query.where.children))
self.assertTrue(query.where.children[0].children[0].is_leaf)
self.assertTrue(query.where.children[1].children[0].is_leaf)
self.assertEqual("class", query.where.children[0].children[0].column)
self.assertEqual("field1", query.where.children[1].children[0].column)
def test_basic_query(self):
query = transform_query(
connections['default'],
TransformTestModel.objects.all().query
)
self.assertEqual(query.model, TransformTestModel)
self.assertEqual(query.kind, 'SELECT')
self.assertEqual(query.tables, [ TransformTestModel._meta.db_table ])
self.assertIsNone(query.where)
def test_and_filter(self):
query = transform_query(
connections['default'],
TransformTestModel.objects.filter(field1="One", field2="Two").all().query
)
self.assertEqual(query.model, TransformTestModel)
self.assertEqual(query.kind, 'SELECT')
self.assertEqual(query.tables, [ TransformTestModel._meta.db_table ])
self.assertTrue(query.where)
self.assertEqual(2, len(query.where.children)) # Two child nodes
def test_exclude_filter(self):
query = transform_query(
connections['default'],
TransformTestModel.objects.exclude(field1="One").all().query
)
self.assertEqual(query.model, TransformTestModel)
self.assertEqual(query.kind, 'SELECT')
self.assertEqual(query.tables, [ TransformTestModel._meta.db_table ])
self.assertTrue(query.where)
self.assertEqual(1, len(query.where.children)) # One child node
self.assertTrue(query.where.children[0].negated)
self.assertEqual(1, len(query.where.children[0].children))
def test_ordering(self):
query = transform_query(
connections['default'],
TransformTestModel.objects.filter(field1="One", field2="Two").order_by("field1", "-field2").query
)
self.assertEqual(query.model, TransformTestModel)
self.assertEqual(query.kind, 'SELECT')
self.assertEqual(query.tables, [ TransformTestModel._meta.db_table ])
self.assertTrue(query.where)
self.assertEqual(2, len(query.where.children)) # Two child nodes
self.assertEqual(["field1", "-field2"], query.order_by)
def test_projection(self):
query = transform_query(
connections['default'],
TransformTestModel.objects.only("field1").query
)
self.assertItemsEqual(["id", "field1"], query.columns)
query = transform_query(
connections['default'],
TransformTestModel.objects.values_list("field1").query
)
self.assertEqual(["field1"], query.columns)
query = transform_query(
connections['default'],
TransformTestModel.objects.defer("field1", "field4").query
)
self.assertItemsEqual(["id", "field2", "field3"], query.columns)
def test_no_results_returns_emptyresultset(self):
self.assertRaises(
EmptyResultSet,
transform_query,
connections['default'],
TransformTestModel.objects.none().query
)
def test_offset_and_limit(self):
query = transform_query(
connections['default'],
TransformTestModel.objects.all()[5:10].query
)
self.assertEqual(5, query.low_mark)
self.assertEqual(10, query.high_mark)
def test_isnull(self):
query = transform_query(
connections['default'],
TransformTestModel.objects.filter(field3__isnull=True).all()[5:10].query
)
self.assertTrue(query.where.children[0].value)
self.assertEqual("ISNULL", query.where.children[0].operator)
def test_distinct(self):
query = transform_query(
connections['default'],
TransformTestModel.objects.distinct("field2", "field3").query
)
self.assertTrue(query.distinct)
self.assertEqual(query.columns, ["field2", "field3"])
query = transform_query(
connections['default'],
TransformTestModel.objects.distinct().values("field2", "field3").query
)
self.assertTrue(query.distinct)
self.assertEqual(query.columns, ["field2", "field3"])
def test_order_by_pk(self):
query = transform_query(
connections['default'],
TransformTestModel.objects.order_by("pk").query
)
self.assertEqual("__key__", query.order_by[0])
query = transform_query(
connections['default'],
TransformTestModel.objects.order_by("-pk").query
)
self.assertEqual("-__key__", query.order_by[0])
def test_reversed_ordering(self):
query = transform_query(
connections['default'],
TransformTestModel.objects.order_by("pk").reverse().query
)
self.assertEqual("-__key__", query.order_by[0])
def test_clear_ordering(self):
query = transform_query(
connections['default'],
TransformTestModel.objects.order_by("pk").order_by().query
)
self.assertFalse(query.order_by)
def test_projection_on_textfield_disabled(self):
query = transform_query(
connections['default'],
TransformTestModel.objects.values_list("field4").query
)
self.assertFalse(query.columns)
self.assertFalse(query.projection_possible)
from djangae.tests.test_connector import Relation
from djangae.db.backends.appengine.dnf import normalize_query
class QueryNormalizationTests(TestCase):
"""
The parse_dnf function takes a Django where tree, and converts it
into a tree of one of the following forms:
[ (column, operator, value), (column, operator, value) ] <- AND only query
[ [(column, operator, value)], [(column, operator, value) ]] <- OR query, of multiple ANDs
"""
def test_and_with_child_or_promoted(self):
from .test_connector import TestUser
"""
Given the following tree:
AND
/ | \
A B OR
/ \
C D
The OR should be promoted, so the resulting tree is
OR
/ \
AND AND
/ | \ / | \
A B C A B D
"""
query = Query(TestUser, "SELECT")
query.where = WhereNode()
query.where.children.append(WhereNode())
query.where.children[-1].column = "A"
query.where.children[-1].operator = "="
query.where.children.append(WhereNode())
query.where.children[-1].column = "B"
query.where.children[-1].operator = "="
query.where.children.append(WhereNode())
query.where.children[-1].connector = "OR"
query.where.children[-1].children.append(WhereNode())
query.where.children[-1].children[-1].column = "C"
query.where.children[-1].children[-1].operator = "="
query.where.children[-1].children.append(WhereNode())
query.where.children[-1].children[-1].column = "D"
query.where.children[-1].children[-1].operator = "="
query = normalize_query(query)
self.assertEqual(query.where.connector, "OR")
self.assertEqual(2, len(query.where.children))
self.assertFalse(query.where.children[0].is_leaf)
self.assertFalse(query.where.children[1].is_leaf)
self.assertEqual(query.where.children[0].connector, "AND")
self.assertEqual(query.where.children[1].connector, "AND")
self.assertEqual(3, len(query.where.children[0].children))
self.assertEqual(3, len(query.where.children[1].children))
def test_and_queries(self):
from .test_connector import TestUser
qs = TestUser.objects.filter(username="test").all()
query = normalize_query(transform_query(
connections['default'],
qs.query
))
self.assertTrue(1, len(query.where.children))
self.assertEqual(query.where.children[0].children[0].column, "username")
self.assertEqual(query.where.children[0].children[0].operator, "=")
self.assertEqual(query.where.children[0].children[0].value, "test")
qs = TestUser.objects.filter(username="test", email="test@example.com")
query = normalize_query(transform_query(
connections['default'],
qs.query
))
self.assertTrue(2, len(query.where.children[0].children))
self.assertEqual(query.where.connector, "OR")
self.assertEqual(query.where.children[0].connector, "AND")
self.assertEqual(query.where.children[0].children[0].column, "username")
self.assertEqual(query.where.children[0].children[0].operator, "=")
self.assertEqual(query.where.children[0].children[0].value, "test")
self.assertEqual(query.where.children[0].children[1].column, "email")
self.assertEqual(query.where.children[0].children[1].operator, "=")
self.assertEqual(query.where.children[0].children[1].value, "test@example.com")
qs = TestUser.objects.filter(username="test").exclude(email="test@example.com")
query = normalize_query(transform_query(
connections['default'],
qs.query
))
self.assertTrue(2, len(query.where.children[0].children))
self.assertEqual(query.where.connector, "OR")
self.assertEqual(query.where.children[0].connector, "AND")
self.assertEqual(query.where.children[0].children[0].column, "username")
self.assertEqual(query.where.children[0].children[0].operator, "=")
self.assertEqual(query.where.children[0].children[0].value, "test")
self.assertEqual(query.where.children[0].children[1].column, "email")
self.assertEqual(query.where.children[0].children[1].operator, "<")
self.assertEqual(query.where.children[0].children[1].value, "test@example.com")
self.assertEqual(query.where.children[1].children[0].column, "username")
self.assertEqual(query.where.children[1].children[0].operator, "=")
self.assertEqual(query.where.children[1].children[0].value, "test")
self.assertEqual(query.where.children[1].children[1].column, "email")
self.assertEqual(query.where.children[1].children[1].operator, ">")
self.assertEqual(query.where.children[1].children[1].value, "test@example.com")
instance = Relation(pk=1)
qs = instance.related_set.filter(headline__startswith='Fir')
query = normalize_query(transform_query(
connections['default'],
qs.query
))
self.assertTrue(2, len(query.where.children[0].children))
self.assertEqual(query.where.connector, "OR")
self.assertEqual(query.where.children[0].connector, "AND")
self.assertEqual(query.where.children[0].children[0].column, "relation_id")
self.assertEqual(query.where.children[0].children[0].operator, "=")
self.assertEqual(query.where.children[0].children[0].value, 1)
self.assertEqual(query.where.children[0].children[1].column, "_idx_startswith_headline")
self.assertEqual(query.where.children[0].children[1].operator, "=")
self.assertEqual(query.where.children[0].children[1].value, u"Fir")
def test_or_queries(self):
from .test_connector import TestUser
qs = TestUser.objects.filter(
username="python").filter(
Q(username__in=["ruby", "jruby"]) | (Q(username="php") & ~Q(username="perl"))
)
query = normalize_query(transform_query(
connections['default'],
qs.query
))
# After IN and != explosion, we have...
# (AND: (username='python', OR: (username='ruby', username='jruby', AND: (username='php', AND: (username < 'perl', username > 'perl')))))
# Working backwards,
# AND: (username < 'perl', username > 'perl') can't be simplified
# AND: (username='php', AND: (username < 'perl', username > 'perl')) can become (OR: (AND: username = 'php', username < 'perl'), (AND: username='php', username > 'perl'))
# OR: (username='ruby', username='jruby', (OR: (AND: username = 'php', username < 'perl'), (AND: username='php', username > 'perl')) can't be simplified
# (AND: (username='python', OR: (username='ruby', username='jruby', (OR: (AND: username = 'php', username < 'perl'), (AND: username='php', username > 'perl'))
# becomes...
# (OR: (AND: username='python', username = 'ruby'), (AND: username='python', username='jruby'), (AND: username='python', username='php', username < 'perl') \
# (AND: username='python', username='php', username > 'perl')
self.assertTrue(4, len(query.where.children[0].children))
self.assertEqual(query.where.children[0].connector, "AND")
self.assertEqual(query.where.children[0].children[0].column, "username")
self.assertEqual(query.where.children[0].children[0].operator, "=")
self.assertEqual(query.where.children[0].children[0].value, "python")
self.assertEqual(query.where.children[0].children[1].column, "username")
self.assertEqual(query.where.children[0].children[1].operator, "=")
self.assertEqual(query.where.children[0].children[1].value, "php")
self.assertEqual(query.where.children[0].children[2].column, "username")
self.assertEqual(query.where.children[0].children[2].operator, "<")
self.assertEqual(query.where.children[0].children[2].value, "perl")
self.assertEqual(query.where.children[1].connector, "AND")
self.assertEqual(query.where.children[1].children[0].column, "username")
self.assertEqual(query.where.children[1].children[0].operator, "=")
self.assertEqual(query.where.children[1].children[0].value, "python")
self.assertEqual(query.where.children[1].children[1].column, "username")
self.assertEqual(query.where.children[1].children[1].operator, "=")
self.assertEqual(query.where.children[1].children[1].value, "jruby")
self.assertEqual(query.where.children[2].connector, "AND")
self.assertEqual(query.where.children[2].children[0].column, "username")
self.assertEqual(query.where.children[2].children[0].operator, "=")
self.assertEqual(query.where.children[2].children[0].value, "python")
self.assertEqual(query.where.children[2].children[1].column, "username")
self.assertEqual(query.where.children[2].children[1].operator, "=")
self.assertEqual(query.where.children[2].children[1].value, "php")
self.assertEqual(query.where.children[2].children[2].column, "username")
self.assertEqual(query.where.children[2].children[2].operator, ">")
self.assertEqual(query.where.children[2].children[2].value, "perl")
self.assertEqual(query.where.connector, "OR")
self.assertEqual(query.where.children[3].connector, "AND")
self.assertEqual(query.where.children[3].children[0].column, "username")
self.assertEqual(query.where.children[3].children[0].operator, "=")
self.assertEqual(query.where.children[3].children[0].value, "python")
self.assertEqual(query.where.children[3].children[1].column, "username")
self.assertEqual(query.where.children[3].children[1].operator, "=")
self.assertEqual(query.where.children[3].children[1].value, "ruby")
qs = TestUser.objects.filter(username="test") | TestUser.objects.filter(username="cheese")
query = normalize_query(transform_query(
connections['default'],
qs.query
))
self.assertEqual(query.where.connector, "OR")
self.assertEqual(2, len(query.where.children))
self.assertTrue(query.where.children[0].is_leaf)
self.assertEqual("cheese", query.where.children[0].value)
self.assertTrue(query.where.children[1].is_leaf)
self.assertEqual("test", query.where.children[1].value)
qs = TestUser.objects.using("default").filter(username__in=set()).values_list('email')
with self.assertRaises(EmptyResultSet):
query = normalize_query(transform_query(
connections['default'],
qs.query
))
qs = TestUser.objects.filter(username__startswith='Hello') | TestUser.objects.filter(username__startswith='Goodbye')
query = normalize_query(transform_query(
connections['default'],
qs.query
))
self.assertEqual(2, len(query.where.children))
self.assertEqual("_idx_startswith_username", query.where.children[0].column)
self.assertEqual(u"Goodbye", query.where.children[0].value)
self.assertEqual("_idx_startswith_username", query.where.children[1].column)
self.assertEqual(u"Hello", query.where.children[1].value)
qs = TestUser.objects.filter(pk__in=[1, 2, 3])
query = normalize_query(transform_query(
connections['default'],
qs.query
))
self.assertEqual(3, len(query.where.children))
self.assertEqual("__key__", query.where.children[0].column)
self.assertEqual("__key__", query.where.children[1].column)
self.assertEqual("__key__", query.where.children[2].column)
self.assertEqual({
datastore.Key.from_path(TestUser._meta.db_table, 1),
datastore.Key.from_path(TestUser._meta.db_table, 2),
datastore.Key.from_path(TestUser._meta.db_table, 3),
}, {
query.where.children[0].value,
query.where.children[1].value,
query.where.children[2].value,
}
)
qs = TestUser.objects.filter(pk__in=[1, 2, 3]).filter(username="test")
query = normalize_query(transform_query(
connections['default'],
qs.query
))
self.assertEqual(3, len(query.where.children))
self.assertEqual("__key__", query.where.children[0].children[0].column)
self.assertEqual("test", query.where.children[0].children[1].value)
self.assertEqual("__key__", query.where.children[1].children[0].column)
self.assertEqual("test", query.where.children[0].children[1].value)
self.assertEqual("__key__", query.where.children[2].children[0].column)
self.assertEqual("test", query.where.children[0].children[1].value)
self.assertEqual({
datastore.Key.from_path(TestUser._meta.db_table, 1),
datastore.Key.from_path(TestUser._meta.db_table, 2),
datastore.Key.from_path(TestUser._meta.db_table, 3),
}, {
query.where.children[0].children[0].value,
query.where.children[1].children[0].value,
query.where.children[2].children[0].value,
}
) | bsd-3-clause |
isvaldo/Ola_Bemobenses | tests/Selenium/environment/lib/python3.4/site-packages/selenium/webdriver/phantomjs/service.py | 55 | 3837 | # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC 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 platform
import subprocess
import time
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.common import utils
class Service(object):
"""
Object that manages the starting and stopping of PhantomJS / Ghostdriver
"""
def __init__(self, executable_path, port=0, service_args=None, log_path=None):
"""
Creates a new instance of the Service
:Args:
- executable_path : Path to PhantomJS binary
- port : Port the service is running on
- service_args : A List of other command line options to pass to PhantomJS
- log_path: Path for PhantomJS service to log to
"""
self.port = port
self.path = executable_path
self.service_args= service_args
if self.port == 0:
self.port = utils.free_port()
if self.service_args is None:
self.service_args = []
else:
self.service_args=service_args[:]
self.service_args.insert(0, self.path)
self.service_args.append("--webdriver=%d" % self.port)
self.process = None
if not log_path:
log_path = "ghostdriver.log"
self._log = open(log_path, 'w')
def __del__(self):
# subprocess.Popen doesn't send signal on __del__;
# we have to try to stop the launched process.
self.stop()
def start(self):
"""
Starts PhantomJS with GhostDriver.
:Exceptions:
- WebDriverException : Raised either when it can't start the service
or when it can't connect to the service.
"""
try:
self.process = subprocess.Popen(self.service_args, stdin=subprocess.PIPE,
close_fds=platform.system() != 'Windows',
stdout=self._log, stderr=self._log)
except Exception as e:
raise WebDriverException("Unable to start phantomjs with ghostdriver: %s" % e)
count = 0
while not utils.is_connectable(self.port):
count += 1
time.sleep(1)
if count == 30:
raise WebDriverException(
"Can not connect to GhostDriver on port {}".format(self.port))
@property
def service_url(self):
"""
Gets the url of the GhostDriver Service
"""
return "http://localhost:%d/wd/hub" % self.port
def stop(self):
"""
Cleans up the process
"""
if self._log:
self._log.close()
self._log = None
#If its dead dont worry
if self.process is None:
return
#Tell the Server to properly die in case
try:
if self.process:
self.process.stdin.close()
self.process.kill()
self.process.wait()
self.process = None
except OSError:
# kill may not be available under windows environment
pass
| cc0-1.0 |
nightjean/Deep-Learning | tensorflow/python/summary/plugin_asset_test.py | 152 | 2859 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import ops
from tensorflow.python.framework import test_util
from tensorflow.python.platform import googletest
from tensorflow.python.summary import plugin_asset
class _UnnamedPluginAsset(plugin_asset.PluginAsset):
"""An example asset with a dummy serialize method provided, but no name."""
def assets(self):
return {}
class _ExamplePluginAsset(_UnnamedPluginAsset):
"""Simple example asset."""
plugin_name = "_ExamplePluginAsset"
class _OtherExampleAsset(_UnnamedPluginAsset):
"""Simple example asset."""
plugin_name = "_OtherExampleAsset"
class _ExamplePluginThatWillCauseCollision(_UnnamedPluginAsset):
plugin_name = "_ExamplePluginAsset"
class PluginAssetTest(test_util.TensorFlowTestCase):
def testGetPluginAsset(self):
epa = plugin_asset.get_plugin_asset(_ExamplePluginAsset)
self.assertIsInstance(epa, _ExamplePluginAsset)
epa2 = plugin_asset.get_plugin_asset(_ExamplePluginAsset)
self.assertIs(epa, epa2)
opa = plugin_asset.get_plugin_asset(_OtherExampleAsset)
self.assertIsNot(epa, opa)
def testUnnamedPluginFails(self):
with self.assertRaises(ValueError):
plugin_asset.get_plugin_asset(_UnnamedPluginAsset)
def testPluginCollisionDetected(self):
plugin_asset.get_plugin_asset(_ExamplePluginAsset)
with self.assertRaises(ValueError):
plugin_asset.get_plugin_asset(_ExamplePluginThatWillCauseCollision)
def testGetAllPluginAssets(self):
epa = plugin_asset.get_plugin_asset(_ExamplePluginAsset)
opa = plugin_asset.get_plugin_asset(_OtherExampleAsset)
self.assertItemsEqual(plugin_asset.get_all_plugin_assets(), [epa, opa])
def testRespectsGraphArgument(self):
g1 = ops.Graph()
g2 = ops.Graph()
e1 = plugin_asset.get_plugin_asset(_ExamplePluginAsset, g1)
e2 = plugin_asset.get_plugin_asset(_ExamplePluginAsset, g2)
self.assertEqual(e1, plugin_asset.get_all_plugin_assets(g1)[0])
self.assertEqual(e2, plugin_asset.get_all_plugin_assets(g2)[0])
if __name__ == "__main__":
googletest.main()
| apache-2.0 |
loco-odoo/localizacion_co | openerp/service/websrv_lib.py | 380 | 7780 | # -*- coding: utf-8 -*-
#
# Copyright P. Christeas <p_christ@hol.gr> 2008-2010
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsibility of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# guarantees and support are strongly advised to contract a Free Software
# Service Company
#
# 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
###############################################################################
""" Framework for generic http servers
This library contains *no* OpenERP-specific functionality. It should be
usable in other projects, too.
"""
import logging
import SocketServer
from BaseHTTPServer import *
from SimpleHTTPServer import SimpleHTTPRequestHandler
_logger = logging.getLogger(__name__)
class AuthRequiredExc(Exception):
def __init__(self,atype,realm):
Exception.__init__(self)
self.atype = atype
self.realm = realm
class AuthRejectedExc(Exception):
pass
class AuthProvider:
def __init__(self,realm):
self.realm = realm
def authenticate(self, user, passwd, client_address):
return False
def log(self, msg):
print msg
def checkRequest(self,handler,path = '/'):
""" Check if we are allowed to process that request
"""
pass
class HTTPHandler(SimpleHTTPRequestHandler):
def __init__(self,request, client_address, server):
SimpleHTTPRequestHandler.__init__(self,request,client_address,server)
# print "Handler for %s inited" % str(client_address)
self.protocol_version = 'HTTP/1.1'
self.connection = dummyconn()
def handle(self):
""" Classes here should NOT handle inside their constructor
"""
pass
def finish(self):
pass
def setup(self):
pass
# A list of HTTPDir.
handlers = []
class HTTPDir:
""" A dispatcher class, like a virtual folder in httpd
"""
def __init__(self, path, handler, auth_provider=None, secure_only=False):
self.path = path
self.handler = handler
self.auth_provider = auth_provider
self.secure_only = secure_only
def matches(self, request):
""" Test if some request matches us. If so, return
the matched path. """
if request.startswith(self.path):
return self.path
return False
def instanciate_handler(self, request, client_address, server):
handler = self.handler(noconnection(request), client_address, server)
if self.auth_provider:
handler.auth_provider = self.auth_provider()
return handler
def reg_http_service(path, handler, auth_provider=None, secure_only=False):
""" Register a HTTP handler at a given path.
The auth_provider will be instanciated and set on the handler instances.
"""
global handlers
service = HTTPDir(path, handler, auth_provider, secure_only)
pos = len(handlers)
lastpos = pos
while pos > 0:
pos -= 1
if handlers[pos].matches(service.path):
lastpos = pos
# we won't break here, but search all way to the top, to
# ensure there is no lesser entry that will shadow the one
# we are inserting.
handlers.insert(lastpos, service)
def list_http_services(protocol=None):
global handlers
ret = []
for svc in handlers:
if protocol is None or protocol == 'http' or svc.secure_only:
ret.append((svc.path, str(svc.handler)))
return ret
def find_http_service(path, secure=False):
global handlers
for vdir in handlers:
p = vdir.matches(path)
if p == False or (vdir.secure_only and not secure):
continue
return vdir
return None
class noconnection(object):
""" a class to use instead of the real connection
"""
def __init__(self, realsocket=None):
self.__hidden_socket = realsocket
def makefile(self, mode, bufsize):
return None
def close(self):
pass
def getsockname(self):
""" We need to return info about the real socket that is used for the request
"""
if not self.__hidden_socket:
raise AttributeError("No-connection class cannot tell real socket")
return self.__hidden_socket.getsockname()
class dummyconn:
def shutdown(self, tru):
pass
def _quote_html(html):
return html.replace("&", "&").replace("<", "<").replace(">", ">")
class FixSendError:
#error_message_format = """ """
def send_error(self, code, message=None):
#overriden from BaseHTTPRequestHandler, we also send the content-length
try:
short, long = self.responses[code]
except KeyError:
short, long = '???', '???'
if message is None:
message = short
explain = long
_logger.error("code %d, message %s", code, message)
# using _quote_html to prevent Cross Site Scripting attacks (see bug #1100201)
content = (self.error_message_format %
{'code': code, 'message': _quote_html(message), 'explain': explain})
self.send_response(code, message)
self.send_header("Content-Type", self.error_content_type)
self.send_header('Connection', 'close')
self.send_header('Content-Length', len(content) or 0)
self.end_headers()
if hasattr(self, '_flush'):
self._flush()
if self.command != 'HEAD' and code >= 200 and code not in (204, 304):
self.wfile.write(content)
class HttpOptions:
_HTTP_OPTIONS = {'Allow': ['OPTIONS' ] }
def do_OPTIONS(self):
"""return the list of capabilities """
opts = self._HTTP_OPTIONS
nopts = self._prep_OPTIONS(opts)
if nopts:
opts = nopts
self.send_response(200)
self.send_header("Content-Length", 0)
if 'Microsoft' in self.headers.get('User-Agent', ''):
self.send_header('MS-Author-Via', 'DAV')
# Microsoft's webdav lib ass-umes that the server would
# be a FrontPage(tm) one, unless we send a non-standard
# header that we are not an elephant.
# http://www.ibm.com/developerworks/rational/library/2089.html
for key, value in opts.items():
if isinstance(value, basestring):
self.send_header(key, value)
elif isinstance(value, (tuple, list)):
self.send_header(key, ', '.join(value))
self.end_headers()
def _prep_OPTIONS(self, opts):
"""Prepare the OPTIONS response, if needed
Sometimes, like in special DAV folders, the OPTIONS may contain
extra keywords, perhaps also dependant on the request url.
:param opts: MUST be copied before being altered
:returns: the updated options.
"""
return opts
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
fzza/rdio-sock | src/rdiosock/metadata.py | 1 | 3693 | from rdiosock.exceptions import RdioApiError
from rdiosock.objects.collection import RdioList
class SEARCH_TYPES:
"""Metadata search types"""
NONE = 0
ARTIST = 1
ALBUM = 2
TRACK = 4
PLAYLIST = 8
USER = 16
LABEL = 32
ALL = (
ARTIST |
ALBUM |
TRACK |
PLAYLIST |
USER |
LABEL
)
_MAP = {
ARTIST: 'Artist',
ALBUM: 'Album',
TRACK: 'Track',
PLAYLIST: 'Playlist',
USER: 'User',
LABEL: 'Label'
}
@classmethod
def parse(cls, value):
if type(value) is int:
value = cls._parse_bit(value)
items = []
for key in value:
items.append(cls._MAP[key])
return items
@classmethod
def _parse_bit(cls, value):
items = []
for key in cls._MAP:
if (value & key) == key:
items.append(key)
return items
class SEARCH_EXTRAS:
"""Metadata search extras"""
NONE = 0
LOCATION = 1
USERNAME = 2
STATIONS = 4
DESCRIPTION = 8
FOLLOWER_COUNT = 16
FOLLOWING_COUNT = 32
FAVORITE_COUNT = 64
SET_COUNT = 128
ICON_250x375 = 256
ICON_500x750 = 512
ICON_250x333 = 1024
ICON_500x667 = 2048
ALL = (
LOCATION |
USERNAME |
STATIONS |
DESCRIPTION |
FOLLOWER_COUNT |
FOLLOWING_COUNT |
FAVORITE_COUNT |
SET_COUNT |
ICON_250x375 |
ICON_500x750 |
ICON_250x333 |
ICON_500x667
)
_MAP = {
LOCATION: 'location',
USERNAME: 'username',
STATIONS: 'stations',
DESCRIPTION: 'description',
FOLLOWER_COUNT: 'followerCount',
FOLLOWING_COUNT: 'followingCount',
FAVORITE_COUNT: 'favoriteCount',
SET_COUNT: 'setCount',
ICON_250x375: 'icon250x375',
ICON_500x750: 'icon500x750',
ICON_250x333: 'icon250x333',
ICON_500x667: 'icon500x667'
}
@classmethod
def parse(cls, value):
if type(value) is int:
value = cls._parse_bit(value)
items = []
for key in value:
items.append(cls._MAP[key])
return items
@classmethod
def _parse_bit(cls, value):
items = []
for key in cls._MAP:
if (value & key) == key:
items.append(key)
return items
class RdioMetadata(object):
def __init__(self, sock):
"""
:type sock: RdioSock
"""
self._sock = sock
def search(self, query, search_types=SEARCH_TYPES.ALL, search_extras=SEARCH_EXTRAS.ALL):
"""Search for media item.
:param query: Search query
:type query: str
:param search_types: Search type (:class:`rdiosock.metadata.SEARCH_TYPES` bitwise-OR or list)
:type search_types: int or list of int
:param search_extras: Search result extras to include (:class:`rdiosock.metadata.SEARCH_EXTRAS` bitwise-OR or list)
:type search_extras: int or list of int
"""
result = self._sock._api_post('search', {
'query': query,
'types[]': SEARCH_TYPES.parse(search_types)
}, secure=False, extras=SEARCH_EXTRAS.parse(search_extras))
if result['status'] == 'error':
raise RdioApiError(result)
result = result['result']
if result['type'] == 'list':
return RdioList.parse(result)
else:
raise NotImplementedError()
| gpl-3.0 |
mahak/ansible | test/lib/ansible_test/_data/sanity/pylint/plugins/string_format.py | 68 | 3117 | # (c) 2018, Matt Martz <matt@sivel.net>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import sys
import six
import astroid
from pylint.interfaces import IAstroidChecker
from pylint.checkers import BaseChecker
from pylint.checkers import utils
from pylint.checkers.utils import check_messages
try:
from pylint.checkers.utils import parse_format_method_string
except ImportError:
# noinspection PyUnresolvedReferences
from pylint.checkers.strings import parse_format_method_string
_PY3K = sys.version_info[:2] >= (3, 0)
MSGS = {
'E9305': ("Format string contains automatic field numbering "
"specification",
"ansible-format-automatic-specification",
"Used when a PEP 3101 format string contains automatic "
"field numbering (e.g. '{}').",
{'minversion': (2, 6)}),
'E9390': ("bytes object has no .format attribute",
"ansible-no-format-on-bytestring",
"Used when a bytestring was used as a PEP 3101 format string "
"as Python3 bytestrings do not have a .format attribute",
{'minversion': (3, 0)}),
}
class AnsibleStringFormatChecker(BaseChecker):
"""Checks string formatting operations to ensure that the format string
is valid and the arguments match the format string.
"""
__implements__ = (IAstroidChecker,)
name = 'string'
msgs = MSGS
@check_messages(*(MSGS.keys()))
def visit_call(self, node):
func = utils.safe_infer(node.func)
if (isinstance(func, astroid.BoundMethod)
and isinstance(func.bound, astroid.Instance)
and func.bound.name in ('str', 'unicode', 'bytes')):
if func.name == 'format':
self._check_new_format(node, func)
def _check_new_format(self, node, func):
""" Check the new string formatting """
if (isinstance(node.func, astroid.Attribute)
and not isinstance(node.func.expr, astroid.Const)):
return
try:
strnode = next(func.bound.infer())
except astroid.InferenceError:
return
if not isinstance(strnode, astroid.Const):
return
if _PY3K and isinstance(strnode.value, six.binary_type):
self.add_message('ansible-no-format-on-bytestring', node=node)
return
if not isinstance(strnode.value, six.string_types):
return
if node.starargs or node.kwargs:
return
try:
num_args = parse_format_method_string(strnode.value)[1]
except utils.IncompleteFormatString:
return
if num_args:
self.add_message('ansible-format-automatic-specification',
node=node)
return
def register(linter):
"""required method to auto register this checker """
linter.register_checker(AnsibleStringFormatChecker(linter))
| gpl-3.0 |
raschuetz/foundations-homework | 07/data-analysis/bin/activate_this.py | 1076 | 1137 | """By using execfile(this_file, dict(__file__=this_file)) you will
activate this virtualenv environment.
This can be used when you must use an existing Python interpreter, not
the virtualenv bin/python
"""
try:
__file__
except NameError:
raise AssertionError(
"You must run this like execfile('path/to/activate_this.py', dict(__file__='path/to/activate_this.py'))")
import sys
import os
old_os_path = os.environ.get('PATH', '')
os.environ['PATH'] = os.path.dirname(os.path.abspath(__file__)) + os.pathsep + old_os_path
base = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if sys.platform == 'win32':
site_packages = os.path.join(base, 'Lib', 'site-packages')
else:
site_packages = os.path.join(base, 'lib', 'python%s' % sys.version[:3], 'site-packages')
prev_sys_path = list(sys.path)
import site
site.addsitedir(site_packages)
sys.real_prefix = sys.prefix
sys.prefix = base
# Move the added items to the front of the path:
new_sys_path = []
for item in list(sys.path):
if item not in prev_sys_path:
new_sys_path.append(item)
sys.path.remove(item)
sys.path[:0] = new_sys_path
| mit |
350dotorg/Django | django/contrib/gis/db/backends/spatialite/operations.py | 282 | 14391 | import re
from decimal import Decimal
from django.contrib.gis.db.backends.base import BaseSpatialOperations
from django.contrib.gis.db.backends.util import SpatialOperation, SpatialFunction
from django.contrib.gis.db.backends.spatialite.adapter import SpatiaLiteAdapter
from django.contrib.gis.geometry.backend import Geometry
from django.contrib.gis.measure import Distance
from django.core.exceptions import ImproperlyConfigured
from django.db.backends.sqlite3.base import DatabaseOperations
from django.db.utils import DatabaseError
class SpatiaLiteOperator(SpatialOperation):
"For SpatiaLite operators (e.g. `&&`, `~`)."
def __init__(self, operator):
super(SpatiaLiteOperator, self).__init__(operator=operator)
class SpatiaLiteFunction(SpatialFunction):
"For SpatiaLite function calls."
def __init__(self, function, **kwargs):
super(SpatiaLiteFunction, self).__init__(function, **kwargs)
class SpatiaLiteFunctionParam(SpatiaLiteFunction):
"For SpatiaLite functions that take another parameter."
sql_template = '%(function)s(%(geo_col)s, %(geometry)s, %%s)'
class SpatiaLiteDistance(SpatiaLiteFunction):
"For SpatiaLite distance operations."
dist_func = 'Distance'
sql_template = '%(function)s(%(geo_col)s, %(geometry)s) %(operator)s %%s'
def __init__(self, operator):
super(SpatiaLiteDistance, self).__init__(self.dist_func,
operator=operator)
class SpatiaLiteRelate(SpatiaLiteFunctionParam):
"For SpatiaLite Relate(<geom>, <pattern>) calls."
pattern_regex = re.compile(r'^[012TF\*]{9}$')
def __init__(self, pattern):
if not self.pattern_regex.match(pattern):
raise ValueError('Invalid intersection matrix pattern "%s".' % pattern)
super(SpatiaLiteRelate, self).__init__('Relate')
# Valid distance types and substitutions
dtypes = (Decimal, Distance, float, int, long)
def get_dist_ops(operator):
"Returns operations for regular distances; spherical distances are not currently supported."
return (SpatiaLiteDistance(operator),)
class SpatiaLiteOperations(DatabaseOperations, BaseSpatialOperations):
compiler_module = 'django.contrib.gis.db.models.sql.compiler'
name = 'spatialite'
spatialite = True
version_regex = re.compile(r'^(?P<major>\d)\.(?P<minor1>\d)\.(?P<minor2>\d+)')
valid_aggregates = dict([(k, None) for k in ('Extent', 'Union')])
Adapter = SpatiaLiteAdapter
Adaptor = Adapter # Backwards-compatibility alias.
area = 'Area'
centroid = 'Centroid'
contained = 'MbrWithin'
difference = 'Difference'
distance = 'Distance'
envelope = 'Envelope'
intersection = 'Intersection'
length = 'GLength' # OpenGis defines Length, but this conflicts with an SQLite reserved keyword
num_geom = 'NumGeometries'
num_points = 'NumPoints'
point_on_surface = 'PointOnSurface'
scale = 'ScaleCoords'
svg = 'AsSVG'
sym_difference = 'SymDifference'
transform = 'Transform'
translate = 'ShiftCoords'
union = 'GUnion' # OpenGis defines Union, but this conflicts with an SQLite reserved keyword
unionagg = 'GUnion'
from_text = 'GeomFromText'
from_wkb = 'GeomFromWKB'
select = 'AsText(%s)'
geometry_functions = {
'equals' : SpatiaLiteFunction('Equals'),
'disjoint' : SpatiaLiteFunction('Disjoint'),
'touches' : SpatiaLiteFunction('Touches'),
'crosses' : SpatiaLiteFunction('Crosses'),
'within' : SpatiaLiteFunction('Within'),
'overlaps' : SpatiaLiteFunction('Overlaps'),
'contains' : SpatiaLiteFunction('Contains'),
'intersects' : SpatiaLiteFunction('Intersects'),
'relate' : (SpatiaLiteRelate, basestring),
# Retruns true if B's bounding box completely contains A's bounding box.
'contained' : SpatiaLiteFunction('MbrWithin'),
# Returns true if A's bounding box completely contains B's bounding box.
'bbcontains' : SpatiaLiteFunction('MbrContains'),
# Returns true if A's bounding box overlaps B's bounding box.
'bboverlaps' : SpatiaLiteFunction('MbrOverlaps'),
# These are implemented here as synonyms for Equals
'same_as' : SpatiaLiteFunction('Equals'),
'exact' : SpatiaLiteFunction('Equals'),
}
distance_functions = {
'distance_gt' : (get_dist_ops('>'), dtypes),
'distance_gte' : (get_dist_ops('>='), dtypes),
'distance_lt' : (get_dist_ops('<'), dtypes),
'distance_lte' : (get_dist_ops('<='), dtypes),
}
geometry_functions.update(distance_functions)
def __init__(self, connection):
super(DatabaseOperations, self).__init__()
self.connection = connection
# Determine the version of the SpatiaLite library.
try:
vtup = self.spatialite_version_tuple()
version = vtup[1:]
if version < (2, 3, 0):
raise ImproperlyConfigured('GeoDjango only supports SpatiaLite versions '
'2.3.0 and above')
self.spatial_version = version
except ImproperlyConfigured:
raise
except Exception, msg:
raise ImproperlyConfigured('Cannot determine the SpatiaLite version for the "%s" '
'database (error was "%s"). Was the SpatiaLite initialization '
'SQL loaded on this database?' %
(self.connection.settings_dict['NAME'], msg))
# Creating the GIS terms dictionary.
gis_terms = ['isnull']
gis_terms += self.geometry_functions.keys()
self.gis_terms = dict([(term, None) for term in gis_terms])
def check_aggregate_support(self, aggregate):
"""
Checks if the given aggregate name is supported (that is, if it's
in `self.valid_aggregates`).
"""
agg_name = aggregate.__class__.__name__
return agg_name in self.valid_aggregates
def convert_geom(self, wkt, geo_field):
"""
Converts geometry WKT returned from a SpatiaLite aggregate.
"""
if wkt:
return Geometry(wkt, geo_field.srid)
else:
return None
def geo_db_type(self, f):
"""
Returns None because geometry columnas are added via the
`AddGeometryColumn` stored procedure on SpatiaLite.
"""
return None
def get_distance(self, f, value, lookup_type):
"""
Returns the distance parameters for the given geometry field,
lookup value, and lookup type. SpatiaLite only supports regular
cartesian-based queries (no spheroid/sphere calculations for point
geometries like PostGIS).
"""
if not value:
return []
value = value[0]
if isinstance(value, Distance):
if f.geodetic(self.connection):
raise ValueError('SpatiaLite does not support distance queries on '
'geometry fields with a geodetic coordinate system. '
'Distance objects; use a numeric value of your '
'distance in degrees instead.')
else:
dist_param = getattr(value, Distance.unit_attname(f.units_name(self.connection)))
else:
dist_param = value
return [dist_param]
def get_geom_placeholder(self, f, value):
"""
Provides a proper substitution value for Geometries that are not in the
SRID of the field. Specifically, this routine will substitute in the
Transform() and GeomFromText() function call(s).
"""
def transform_value(value, srid):
return not (value is None or value.srid == srid)
if hasattr(value, 'expression'):
if transform_value(value, f.srid):
placeholder = '%s(%%s, %s)' % (self.transform, f.srid)
else:
placeholder = '%s'
# No geometry value used for F expression, substitue in
# the column name instead.
return placeholder % '%s.%s' % tuple(map(self.quote_name, value.cols[value.expression]))
else:
if transform_value(value, f.srid):
# Adding Transform() to the SQL placeholder.
return '%s(%s(%%s,%s), %s)' % (self.transform, self.from_text, value.srid, f.srid)
else:
return '%s(%%s,%s)' % (self.from_text, f.srid)
def _get_spatialite_func(self, func):
"""
Helper routine for calling SpatiaLite functions and returning
their result.
"""
cursor = self.connection._cursor()
try:
try:
cursor.execute('SELECT %s' % func)
row = cursor.fetchone()
except:
# Responsibility of caller to perform error handling.
raise
finally:
cursor.close()
return row[0]
def geos_version(self):
"Returns the version of GEOS used by SpatiaLite as a string."
return self._get_spatialite_func('geos_version()')
def proj4_version(self):
"Returns the version of the PROJ.4 library used by SpatiaLite."
return self._get_spatialite_func('proj4_version()')
def spatialite_version(self):
"Returns the SpatiaLite library version as a string."
return self._get_spatialite_func('spatialite_version()')
def spatialite_version_tuple(self):
"""
Returns the SpatiaLite version as a tuple (version string, major,
minor, subminor).
"""
# Getting the SpatiaLite version.
try:
version = self.spatialite_version()
except DatabaseError:
# The `spatialite_version` function first appeared in version 2.3.1
# of SpatiaLite, so doing a fallback test for 2.3.0 (which is
# used by popular Debian/Ubuntu packages).
version = None
try:
tmp = self._get_spatialite_func("X(GeomFromText('POINT(1 1)'))")
if tmp == 1.0: version = '2.3.0'
except DatabaseError:
pass
# If no version string defined, then just re-raise the original
# exception.
if version is None: raise
m = self.version_regex.match(version)
if m:
major = int(m.group('major'))
minor1 = int(m.group('minor1'))
minor2 = int(m.group('minor2'))
else:
raise Exception('Could not parse SpatiaLite version string: %s' % version)
return (version, major, minor1, minor2)
def spatial_aggregate_sql(self, agg):
"""
Returns the spatial aggregate SQL template and function for the
given Aggregate instance.
"""
agg_name = agg.__class__.__name__
if not self.check_aggregate_support(agg):
raise NotImplementedError('%s spatial aggregate is not implmented for this backend.' % agg_name)
agg_name = agg_name.lower()
if agg_name == 'union': agg_name += 'agg'
sql_template = self.select % '%(function)s(%(field)s)'
sql_function = getattr(self, agg_name)
return sql_template, sql_function
def spatial_lookup_sql(self, lvalue, lookup_type, value, field, qn):
"""
Returns the SpatiaLite-specific SQL for the given lookup value
[a tuple of (alias, column, db_type)], lookup type, lookup
value, the model field, and the quoting function.
"""
alias, col, db_type = lvalue
# Getting the quoted field as `geo_col`.
geo_col = '%s.%s' % (qn(alias), qn(col))
if lookup_type in self.geometry_functions:
# See if a SpatiaLite geometry function matches the lookup type.
tmp = self.geometry_functions[lookup_type]
# Lookup types that are tuples take tuple arguments, e.g., 'relate' and
# distance lookups.
if isinstance(tmp, tuple):
# First element of tuple is the SpatiaLiteOperation instance, and the
# second element is either the type or a tuple of acceptable types
# that may passed in as further parameters for the lookup type.
op, arg_type = tmp
# Ensuring that a tuple _value_ was passed in from the user
if not isinstance(value, (tuple, list)):
raise ValueError('Tuple required for `%s` lookup type.' % lookup_type)
# Geometry is first element of lookup tuple.
geom = value[0]
# Number of valid tuple parameters depends on the lookup type.
if len(value) != 2:
raise ValueError('Incorrect number of parameters given for `%s` lookup type.' % lookup_type)
# Ensuring the argument type matches what we expect.
if not isinstance(value[1], arg_type):
raise ValueError('Argument type should be %s, got %s instead.' % (arg_type, type(value[1])))
# For lookup type `relate`, the op instance is not yet created (has
# to be instantiated here to check the pattern parameter).
if lookup_type == 'relate':
op = op(value[1])
elif lookup_type in self.distance_functions:
op = op[0]
else:
op = tmp
geom = value
# Calling the `as_sql` function on the operation instance.
return op.as_sql(geo_col, self.get_geom_placeholder(field, geom))
elif lookup_type == 'isnull':
# Handling 'isnull' lookup type
return "%s IS %sNULL" % (geo_col, (not value and 'NOT ' or ''))
raise TypeError("Got invalid lookup_type: %s" % repr(lookup_type))
# Routines for getting the OGC-compliant models.
def geometry_columns(self):
from django.contrib.gis.db.backends.spatialite.models import GeometryColumns
return GeometryColumns
def spatial_ref_sys(self):
from django.contrib.gis.db.backends.spatialite.models import SpatialRefSys
return SpatialRefSys
| bsd-3-clause |
vilorious/pyload | module/lib/thrift/protocol/TCompactProtocol.py | 62 | 10926 | #
# 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.
#
from TProtocol import *
from struct import pack, unpack
__all__ = ['TCompactProtocol', 'TCompactProtocolFactory']
CLEAR = 0
FIELD_WRITE = 1
VALUE_WRITE = 2
CONTAINER_WRITE = 3
BOOL_WRITE = 4
FIELD_READ = 5
CONTAINER_READ = 6
VALUE_READ = 7
BOOL_READ = 8
def make_helper(v_from, container):
def helper(func):
def nested(self, *args, **kwargs):
assert self.state in (v_from, container), (self.state, v_from, container)
return func(self, *args, **kwargs)
return nested
return helper
writer = make_helper(VALUE_WRITE, CONTAINER_WRITE)
reader = make_helper(VALUE_READ, CONTAINER_READ)
def makeZigZag(n, bits):
return (n << 1) ^ (n >> (bits - 1))
def fromZigZag(n):
return (n >> 1) ^ -(n & 1)
def writeVarint(trans, n):
out = []
while True:
if n & ~0x7f == 0:
out.append(n)
break
else:
out.append((n & 0xff) | 0x80)
n = n >> 7
trans.write(''.join(map(chr, out)))
def readVarint(trans):
result = 0
shift = 0
while True:
x = trans.readAll(1)
byte = ord(x)
result |= (byte & 0x7f) << shift
if byte >> 7 == 0:
return result
shift += 7
class CompactType:
STOP = 0x00
TRUE = 0x01
FALSE = 0x02
BYTE = 0x03
I16 = 0x04
I32 = 0x05
I64 = 0x06
DOUBLE = 0x07
BINARY = 0x08
LIST = 0x09
SET = 0x0A
MAP = 0x0B
STRUCT = 0x0C
CTYPES = {TType.STOP: CompactType.STOP,
TType.BOOL: CompactType.TRUE, # used for collection
TType.BYTE: CompactType.BYTE,
TType.I16: CompactType.I16,
TType.I32: CompactType.I32,
TType.I64: CompactType.I64,
TType.DOUBLE: CompactType.DOUBLE,
TType.STRING: CompactType.BINARY,
TType.STRUCT: CompactType.STRUCT,
TType.LIST: CompactType.LIST,
TType.SET: CompactType.SET,
TType.MAP: CompactType.MAP
}
TTYPES = {}
for k, v in CTYPES.items():
TTYPES[v] = k
TTYPES[CompactType.FALSE] = TType.BOOL
del k
del v
class TCompactProtocol(TProtocolBase):
"Compact implementation of the Thrift protocol driver."
PROTOCOL_ID = 0x82
VERSION = 1
VERSION_MASK = 0x1f
TYPE_MASK = 0xe0
TYPE_SHIFT_AMOUNT = 5
def __init__(self, trans):
TProtocolBase.__init__(self, trans)
self.state = CLEAR
self.__last_fid = 0
self.__bool_fid = None
self.__bool_value = None
self.__structs = []
self.__containers = []
def __writeVarint(self, n):
writeVarint(self.trans, n)
def writeMessageBegin(self, name, type, seqid):
assert self.state == CLEAR
self.__writeUByte(self.PROTOCOL_ID)
self.__writeUByte(self.VERSION | (type << self.TYPE_SHIFT_AMOUNT))
self.__writeVarint(seqid)
self.__writeString(name)
self.state = VALUE_WRITE
def writeMessageEnd(self):
assert self.state == VALUE_WRITE
self.state = CLEAR
def writeStructBegin(self, name):
assert self.state in (CLEAR, CONTAINER_WRITE, VALUE_WRITE), self.state
self.__structs.append((self.state, self.__last_fid))
self.state = FIELD_WRITE
self.__last_fid = 0
def writeStructEnd(self):
assert self.state == FIELD_WRITE
self.state, self.__last_fid = self.__structs.pop()
def writeFieldStop(self):
self.__writeByte(0)
def __writeFieldHeader(self, type, fid):
delta = fid - self.__last_fid
if 0 < delta <= 15:
self.__writeUByte(delta << 4 | type)
else:
self.__writeByte(type)
self.__writeI16(fid)
self.__last_fid = fid
def writeFieldBegin(self, name, type, fid):
assert self.state == FIELD_WRITE, self.state
if type == TType.BOOL:
self.state = BOOL_WRITE
self.__bool_fid = fid
else:
self.state = VALUE_WRITE
self.__writeFieldHeader(CTYPES[type], fid)
def writeFieldEnd(self):
assert self.state in (VALUE_WRITE, BOOL_WRITE), self.state
self.state = FIELD_WRITE
def __writeUByte(self, byte):
self.trans.write(pack('!B', byte))
def __writeByte(self, byte):
self.trans.write(pack('!b', byte))
def __writeI16(self, i16):
self.__writeVarint(makeZigZag(i16, 16))
def __writeSize(self, i32):
self.__writeVarint(i32)
def writeCollectionBegin(self, etype, size):
assert self.state in (VALUE_WRITE, CONTAINER_WRITE), self.state
if size <= 14:
self.__writeUByte(size << 4 | CTYPES[etype])
else:
self.__writeUByte(0xf0 | CTYPES[etype])
self.__writeSize(size)
self.__containers.append(self.state)
self.state = CONTAINER_WRITE
writeSetBegin = writeCollectionBegin
writeListBegin = writeCollectionBegin
def writeMapBegin(self, ktype, vtype, size):
assert self.state in (VALUE_WRITE, CONTAINER_WRITE), self.state
if size == 0:
self.__writeByte(0)
else:
self.__writeSize(size)
self.__writeUByte(CTYPES[ktype] << 4 | CTYPES[vtype])
self.__containers.append(self.state)
self.state = CONTAINER_WRITE
def writeCollectionEnd(self):
assert self.state == CONTAINER_WRITE, self.state
self.state = self.__containers.pop()
writeMapEnd = writeCollectionEnd
writeSetEnd = writeCollectionEnd
writeListEnd = writeCollectionEnd
def writeBool(self, bool):
if self.state == BOOL_WRITE:
if bool:
ctype = CompactType.TRUE
else:
ctype = CompactType.FALSE
self.__writeFieldHeader(ctype, self.__bool_fid)
elif self.state == CONTAINER_WRITE:
if bool:
self.__writeByte(CompactType.TRUE)
else:
self.__writeByte(CompactType.FALSE)
else:
raise AssertionError, "Invalid state in compact protocol"
writeByte = writer(__writeByte)
writeI16 = writer(__writeI16)
@writer
def writeI32(self, i32):
self.__writeVarint(makeZigZag(i32, 32))
@writer
def writeI64(self, i64):
self.__writeVarint(makeZigZag(i64, 64))
@writer
def writeDouble(self, dub):
self.trans.write(pack('!d', dub))
def __writeString(self, s):
self.__writeSize(len(s))
self.trans.write(s)
writeString = writer(__writeString)
def readFieldBegin(self):
assert self.state == FIELD_READ, self.state
type = self.__readUByte()
if type & 0x0f == TType.STOP:
return (None, 0, 0)
delta = type >> 4
if delta == 0:
fid = self.__readI16()
else:
fid = self.__last_fid + delta
self.__last_fid = fid
type = type & 0x0f
if type == CompactType.TRUE:
self.state = BOOL_READ
self.__bool_value = True
elif type == CompactType.FALSE:
self.state = BOOL_READ
self.__bool_value = False
else:
self.state = VALUE_READ
return (None, self.__getTType(type), fid)
def readFieldEnd(self):
assert self.state in (VALUE_READ, BOOL_READ), self.state
self.state = FIELD_READ
def __readUByte(self):
result, = unpack('!B', self.trans.readAll(1))
return result
def __readByte(self):
result, = unpack('!b', self.trans.readAll(1))
return result
def __readVarint(self):
return readVarint(self.trans)
def __readZigZag(self):
return fromZigZag(self.__readVarint())
def __readSize(self):
result = self.__readVarint()
if result < 0:
raise TException("Length < 0")
return result
def readMessageBegin(self):
assert self.state == CLEAR
proto_id = self.__readUByte()
if proto_id != self.PROTOCOL_ID:
raise TProtocolException(TProtocolException.BAD_VERSION,
'Bad protocol id in the message: %d' % proto_id)
ver_type = self.__readUByte()
type = (ver_type & self.TYPE_MASK) >> self.TYPE_SHIFT_AMOUNT
version = ver_type & self.VERSION_MASK
if version != self.VERSION:
raise TProtocolException(TProtocolException.BAD_VERSION,
'Bad version: %d (expect %d)' % (version, self.VERSION))
seqid = self.__readVarint()
name = self.__readString()
return (name, type, seqid)
def readMessageEnd(self):
assert self.state == CLEAR
assert len(self.__structs) == 0
def readStructBegin(self):
assert self.state in (CLEAR, CONTAINER_READ, VALUE_READ), self.state
self.__structs.append((self.state, self.__last_fid))
self.state = FIELD_READ
self.__last_fid = 0
def readStructEnd(self):
assert self.state == FIELD_READ
self.state, self.__last_fid = self.__structs.pop()
def readCollectionBegin(self):
assert self.state in (VALUE_READ, CONTAINER_READ), self.state
size_type = self.__readUByte()
size = size_type >> 4
type = self.__getTType(size_type)
if size == 15:
size = self.__readSize()
self.__containers.append(self.state)
self.state = CONTAINER_READ
return type, size
readSetBegin = readCollectionBegin
readListBegin = readCollectionBegin
def readMapBegin(self):
assert self.state in (VALUE_READ, CONTAINER_READ), self.state
size = self.__readSize()
types = 0
if size > 0:
types = self.__readUByte()
vtype = self.__getTType(types)
ktype = self.__getTType(types >> 4)
self.__containers.append(self.state)
self.state = CONTAINER_READ
return (ktype, vtype, size)
def readCollectionEnd(self):
assert self.state == CONTAINER_READ, self.state
self.state = self.__containers.pop()
readSetEnd = readCollectionEnd
readListEnd = readCollectionEnd
readMapEnd = readCollectionEnd
def readBool(self):
if self.state == BOOL_READ:
return self.__bool_value == CompactType.TRUE
elif self.state == CONTAINER_READ:
return self.__readByte() == CompactType.TRUE
else:
raise AssertionError, "Invalid state in compact protocol: %d" % self.state
readByte = reader(__readByte)
__readI16 = __readZigZag
readI16 = reader(__readZigZag)
readI32 = reader(__readZigZag)
readI64 = reader(__readZigZag)
@reader
def readDouble(self):
buff = self.trans.readAll(8)
val, = unpack('!d', buff)
return val
def __readString(self):
len = self.__readSize()
return self.trans.readAll(len)
readString = reader(__readString)
def __getTType(self, byte):
return TTYPES[byte & 0x0f]
class TCompactProtocolFactory:
def __init__(self):
pass
def getProtocol(self, trans):
return TCompactProtocol(trans)
| gpl-3.0 |
jart/tensorflow | tensorflow/python/framework/error_interpolation.py | 2 | 8229 | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Function for interpolating formatted errors from the TensorFlow runtime.
Exposes the function `interpolate` to interpolate messages with tags of the form
^^type:name:format^^.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import itertools
import os
import re
import string
import six
from tensorflow.python.util import tf_stack
_NAME_REGEX = r"[A-Za-z0-9.][A-Za-z0-9_.\-/]*?"
_FORMAT_REGEX = r"[A-Za-z0-9_.\-/${}:]+"
_TAG_REGEX = r"\^\^({name}):({name}):({fmt})\^\^".format(
name=_NAME_REGEX, fmt=_FORMAT_REGEX)
_INTERPOLATION_REGEX = r"^(.*?)({tag})".format(tag=_TAG_REGEX)
_INTERPOLATION_PATTERN = re.compile(_INTERPOLATION_REGEX)
_ParseTag = collections.namedtuple("_ParseTag", ["type", "name", "format"])
_BAD_FILE_SUBSTRINGS = [
os.path.join("tensorflow", "python"),
"<embedded",
]
def _parse_message(message):
"""Parses the message.
Splits the message into separators and tags. Tags are named tuples
representing the string ^^type:name:format^^ and they are separated by
separators. For example, in
"123^^node:Foo:${file}^^456^^node:Bar:${line}^^789", there are two tags and
three separators. The separators are the numeric characters.
Supported tags after node:<node_name>
file: Replaced with the filename in which the node was defined.
line: Replaced by the line number at which the node was defined.
colocations: Replaced by a multi-line message describing the file and
line numbers at which this node was colocated with other nodes.
Args:
message: String to parse
Returns:
(list of separator strings, list of _ParseTags).
For example, if message is "123^^node:Foo:${file}^^456" then this function
returns (["123", "456"], [_ParseTag("node", "Foo", "${file}")])
"""
seps = []
tags = []
pos = 0
while pos < len(message):
match = re.match(_INTERPOLATION_PATTERN, message[pos:])
if match:
seps.append(match.group(1))
tags.append(_ParseTag(match.group(3), match.group(4), match.group(5)))
pos += match.end()
else:
break
seps.append(message[pos:])
return seps, tags
def _compute_colocation_summary_from_dict(colocation_dict, prefix=""):
"""Return a summary of an op's colocation stack.
Args:
colocation_dict: The op._colocation_dict.
prefix: An optional string prefix used before each line of the multi-
line string returned by this function.
Returns:
A multi-line string similar to:
Node-device colocations active during op creation:
with tf.colocate_with(test_node_1): <test_1.py:27>
with tf.colocate_with(test_node_2): <test_2.py:38>
The first line will have no padding to its left by default. Subsequent
lines will have two spaces of left-padding. Use the prefix argument
to increase indentation.
"""
if not colocation_dict:
message = "No node-device colocations were active during op creation."
return prefix + message
str_list = []
str_list.append("%sNode-device colocations active during op creation:"
% prefix)
for name, location in colocation_dict.items():
location_summary = "<{file}:{line}>".format(file=location.filename,
line=location.lineno)
subs = {
"prefix": prefix,
"indent": " ",
"name": name,
"loc": location_summary,
}
str_list.append(
"{prefix}{indent}with tf.colocate_with({name}): {loc}".format(**subs))
return "\n".join(str_list)
def _compute_colocation_summary_from_op(op, prefix=""):
"""Fetch colocation file, line, and nesting and return a summary string."""
if not op:
return ""
# pylint: disable=protected-access
return _compute_colocation_summary_from_dict(op._colocation_dict, prefix)
# pylint: enable=protected-access
def _find_index_of_defining_frame_for_op(op):
"""Return index in op._traceback with first 'useful' frame.
This method reads through the stack stored in op._traceback looking for the
innermost frame which (hopefully) belongs to the caller. It accomplishes this
by rejecting frames whose filename appears to come from TensorFlow (see
error_interpolation._BAD_FILE_SUBSTRINGS for the list of rejected substrings).
Args:
op: the Operation object for which we would like to find the defining
location.
Returns:
Integer index into op._traceback where the first non-TF file was found
(innermost to outermost), or 0 (for the outermost stack frame) if all files
came from TensorFlow.
"""
# pylint: disable=protected-access
# Index 0 of tf_traceback is the outermost frame.
tf_traceback = tf_stack.convert_stack(op._traceback)
size = len(tf_traceback)
# pylint: enable=protected-access
filenames = [frame[tf_stack.TB_FILENAME] for frame in tf_traceback]
# We process the filenames from the innermost frame to outermost.
for idx, filename in enumerate(reversed(filenames)):
contains_bad_substrings = [ss in filename for ss in _BAD_FILE_SUBSTRINGS]
if not any(contains_bad_substrings):
return size - idx - 1
return 0
def _get_defining_frame_from_op(op):
"""Find and return stack frame where op was defined."""
frame = None
if op:
# pylint: disable=protected-access
frame_index = _find_index_of_defining_frame_for_op(op)
frame = op._traceback[frame_index]
# pylint: enable=protected-access
return frame
def _compute_field_dict(op):
"""Return a dictionary mapping interpolation tokens to values.
Args:
op: op.Operation object having a _traceback member.
Returns:
A dictionary mapping string tokens to string values. The keys are shown
below along with example values.
{
"file": "tool_utils.py",
"line": "124",
"colocations":
'''Node-device colocations active during op creation:
with tf.colocate_with(test_node_1): <test_1.py:27>
with tf.colocate_with(test_node_2): <test_2.py:38>'''
}
If op is None or lacks a _traceback field, the returned values will be
"<NA>".
"""
default_value = "<NA>"
field_dict = {
"file": default_value,
"line": default_value,
"colocations": default_value,
}
frame = _get_defining_frame_from_op(op)
if frame:
field_dict["file"] = frame[tf_stack.TB_FILENAME]
field_dict["line"] = frame[tf_stack.TB_LINENO]
colocation_summary = _compute_colocation_summary_from_op(op)
if colocation_summary:
field_dict["colocations"] = colocation_summary
return field_dict
def interpolate(error_message, graph):
"""Interpolates an error message.
The error message can contain tags of the form ^^type:name:format^^ which will
be replaced.
Args:
error_message: A string to interpolate.
graph: ops.Graph object containing all nodes referenced in the error
message.
Returns:
The string with tags of the form ^^type:name:format^^ interpolated.
"""
seps, tags = _parse_message(error_message)
node_name_to_substitution_dict = {}
for name in [t.name for t in tags]:
try:
op = graph.get_operation_by_name(name)
except KeyError:
op = None
node_name_to_substitution_dict[name] = _compute_field_dict(op)
subs = [
string.Template(tag.format).safe_substitute(
node_name_to_substitution_dict[tag.name]) for tag in tags
]
return "".join(
itertools.chain(*six.moves.zip_longest(seps, subs, fillvalue="")))
| apache-2.0 |
brucetsao/arduino-ameba | build/windows/work/hardware/tools/gcc-arm-none-eabi-4.8.3-2014q1/arm-none-eabi/lib/armv7e-m/softfp/libstdc++.a-gdb.py | 3 | 2405 | # -*- python -*-
# Copyright (C) 2009-2013 Free Software Foundation, 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/>.
import sys
import gdb
import os
import os.path
pythondir = '/home/build/work/GCC-4-8-build/install-native/share/gcc-arm-none-eabi'
libdir = '/home/build/work/GCC-4-8-build/install-native/arm-none-eabi/lib/armv7e-m/softfp'
# This file might be loaded when there is no current objfile. This
# can happen if the user loads it manually. In this case we don't
# update sys.path; instead we just hope the user managed to do that
# beforehand.
if gdb.current_objfile () is not None:
# Update module path. We want to find the relative path from libdir
# to pythondir, and then we want to apply that relative path to the
# directory holding the objfile with which this file is associated.
# This preserves relocatability of the gcc tree.
# Do a simple normalization that removes duplicate separators.
pythondir = os.path.normpath (pythondir)
libdir = os.path.normpath (libdir)
prefix = os.path.commonprefix ([libdir, pythondir])
# In some bizarre configuration we might have found a match in the
# middle of a directory name.
if prefix[-1] != '/':
prefix = os.path.dirname (prefix) + '/'
# Strip off the prefix.
pythondir = pythondir[len (prefix):]
libdir = libdir[len (prefix):]
# Compute the ".."s needed to get from libdir to the prefix.
dotdots = ('..' + os.sep) * len (libdir.split (os.sep))
objfile = gdb.current_objfile ().filename
dir_ = os.path.join (os.path.dirname (objfile), dotdots, pythondir)
if not dir_ in sys.path:
sys.path.insert(0, dir_)
# Load the pretty-printers.
from libstdcxx.v6.printers import register_libstdcxx_printers
register_libstdcxx_printers (gdb.current_objfile ())
| lgpl-2.1 |
ciarams87/PyU4V | PyU4V/tests/ci_tests/test_pyu4v_ci_snapshot_policy.py | 1 | 15453 | # Copyright (c) 2020 Dell Inc. or its subsidiaries.
#
# 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.
"""test_pyu4v_ci_snapshot_policy.py."""
import testtools
import time
from PyU4V.tests.ci_tests import base
from PyU4V.utils import constants
class CITestSnapshotPolicy(base.TestBaseTestCase, testtools.TestCase):
"""Test Snapshot Policy Functions."""
def setUp(self):
"""SetUp."""
super(CITestSnapshotPolicy, self).setUp()
self.snapshot_policy = self.conn.snapshot_policy
self.provision = self.conn.provisioning
self.snapshot_policy_name_for_test = (
constants.SNAPSHOT_POLICY_NAME_FOR_TEST)
def test_get_snapshot_policy(self):
"""Test get_snapshot_policy."""
snapshot_policy_name = self.create_snapshot_policy()
snapshot_policy_info = self.snapshot_policy.get_snapshot_policy(
snapshot_policy_name)
self.assertEqual(snapshot_policy_name,
snapshot_policy_info.get('snapshot_policy_name'))
def test_get_snapshot_policy_list(self):
"""Test get_snapshot_policy_list."""
snapshot_policy_name = self.create_snapshot_policy()
snapshot_policy_list = self.snapshot_policy.get_snapshot_policy_list()
self.assertIn(snapshot_policy_name, snapshot_policy_list)
def test_create_snapshot_policy_local_snapshot_policy_details(self):
"""Test create_snapshot_policy with local snapshot policy."""
snapshot_policy_name = self.generate_name(object_type='sp')
snapshot_policy_interval = '1 Day'
job = self.snapshot_policy.create_snapshot_policy(
snapshot_policy_name, snapshot_policy_interval,
local_snapshot_policy_snapshot_count=30,
offset_mins=5, compliance_count_warning=30,
compliance_count_critical=5,
_async=True)
self.conn.common.wait_for_job_complete(job)
snapshot_policy_info = (
self.snapshot_policy.get_snapshot_policy(snapshot_policy_name))
self.assertEqual(snapshot_policy_name,
snapshot_policy_info.get('snapshot_policy_name'))
self.assertEqual(1440, snapshot_policy_info.get('interval_minutes'))
self.assertEqual(30, snapshot_policy_info.get('snapshot_count'))
self.assertFalse(snapshot_policy_info.get('secure'))
self.snapshot_policy.delete_snapshot_policy(snapshot_policy_name)
def test_modify_snapshot_policy_name_change(self):
"""Test modify_snapshot_policy name change."""
original_snapshot_policy_name = self.create_snapshot_policy()
modified_snapshot_policy_name = self.generate_name(object_type='sp')
self.snapshot_policy.modify_snapshot_policy_properties(
original_snapshot_policy_name,
new_snapshot_policy_name=modified_snapshot_policy_name)
snapshot_policy_info = (
self.snapshot_policy.get_snapshot_policy(
modified_snapshot_policy_name))
self.assertEqual(modified_snapshot_policy_name,
snapshot_policy_info.get('snapshot_policy_name'))
self.snapshot_policy.modify_snapshot_policy_properties(
modified_snapshot_policy_name,
new_snapshot_policy_name=original_snapshot_policy_name)
def test_associate_disassociate_snapshot_policy(self):
"""Test associate and disassociate to/from storage groups."""
snapshot_policy_name = self.create_snapshot_policy()
storage_group_name = self.create_empty_storage_group()
self.snapshot_policy.associate_to_storage_groups(
snapshot_policy_name, storage_group_names=[storage_group_name])
snapshot_policy_info = (
self.snapshot_policy.get_snapshot_policy(
snapshot_policy_name))
self.assertEqual(1, snapshot_policy_info.get('storage_group_count'))
self.snapshot_policy.disassociate_from_storage_groups(
snapshot_policy_name, storage_group_names=[storage_group_name])
snapshot_policy_info = (
self.snapshot_policy.get_snapshot_policy(
snapshot_policy_name))
self.assertIsNone(snapshot_policy_info.get('storage_group_count'))
def test_suspend_resume_snapshot_policy(self):
"""Test suspend_snapshot_policy and resume_snapshot_policy."""
snapshot_policy_name = self.create_snapshot_policy()
self.snapshot_policy.suspend_snapshot_policy(
snapshot_policy_name)
snapshot_policy_info = (
self.snapshot_policy.get_snapshot_policy(
snapshot_policy_name))
self.assertTrue(snapshot_policy_info.get('suspended'))
self.snapshot_policy.resume_snapshot_policy(
snapshot_policy_name)
snapshot_policy_info = (
self.snapshot_policy.get_snapshot_policy(
snapshot_policy_name))
self.assertFalse(snapshot_policy_info.get('suspended'))
def test_modify_snapshot_policy_properties_extra_settings(self):
"""Test modify_snapshot_policy_properties extra settings."""
snapshot_policy_name = self.create_snapshot_policy()
job = self.snapshot_policy.modify_snapshot_policy_properties(
snapshot_policy_name,
offset_mins=5, compliance_count_warning=30,
compliance_count_critical=5, interval='12 Minutes',
snapshot_count=40, _async=True)
self.conn.common.wait_for_job_complete(job)
snapshot_policy_info = (
self.snapshot_policy.get_snapshot_policy(
snapshot_policy_name))
self.assertEqual(5, snapshot_policy_info.get('offset_minutes'))
self.assertEqual(12, snapshot_policy_info.get('interval_minutes'))
self.assertEqual(
30, snapshot_policy_info.get('compliance_count_warning'))
self.assertEqual(
5, snapshot_policy_info.get('compliance_count_critical'))
def test_create_storage_group_with_snapshot_policy(self):
"""Test create_storage_group with snapshot policy."""
snapshot_policy_name, storage_group_details = (
self.get_storage_group_and_associated_snapshot_policy())
self.assertEqual(
[snapshot_policy_name],
storage_group_details.get('snapshot_policies'))
storage_group_name = storage_group_details.get('storageGroupId')
self.cleanup_snapshot_policy_and_storage_group(
snapshot_policy_name, storage_group_name)
def get_storage_group_and_associated_snapshot_policy(self):
snapshot_policy_name = self.create_snapshot_policy()
storage_group_name = self.generate_name(object_type='sg')
volume_name = self.generate_name()
self.provision.create_storage_group(
self.SRP, storage_group_name, self.SLO, None, False, 1, 1, 'GB',
False, False, volume_name,
snapshot_policy_ids=[snapshot_policy_name])
storage_group_details = self.provision.get_storage_group(
storage_group_name)
return snapshot_policy_name, storage_group_details
def cleanup_snapshot_policy_and_storage_group(
self, snapshot_policy_name, storage_group_name):
self.snapshot_policy.modify_snapshot_policy(
snapshot_policy_name, constants.DISASSOCIATE_FROM_STORAGE_GROUPS,
storage_group_names=[storage_group_name])
self.addCleanup(self.delete_storage_group, storage_group_name)
def test_get_snapshot_policy_compliance(self):
"""Test get_snapshot_policy_compliance."""
snapshot_policy_name, storage_group_details = (
self.get_storage_group_and_associated_snapshot_policy())
storage_group_name = storage_group_details.get('storageGroupId')
compliance_details = (
self.snapshot_policy.get_snapshot_policy_compliance(
storage_group_name))
self.assertEqual(storage_group_name, compliance_details.get(
'storage_group_name'))
self.assertEqual('NONE', compliance_details.get('compliance'))
self.cleanup_snapshot_policy_and_storage_group(
snapshot_policy_name, storage_group_name)
def test_get_snapshot_policy_compliance_epoch_time_seconds(self):
"""Test get_snapshot_policy_compliance epoch time."""
from_epoch = str(int(time.time()))
snapshot_policy_name, storage_group_details = (
self.get_storage_group_and_associated_snapshot_policy())
storage_group_name = storage_group_details.get('storageGroupId')
to_epoch = str(int(time.time()))
compliance_details = (
self.snapshot_policy.get_snapshot_policy_compliance_epoch(
storage_group_name, from_epoch=from_epoch, to_epoch=to_epoch))
self.assertEqual(storage_group_name, compliance_details.get(
'storage_group_name'))
self.assertEqual('NONE', compliance_details.get('compliance'))
self.cleanup_snapshot_policy_and_storage_group(
snapshot_policy_name, storage_group_name)
def test_get_snapshot_policy_compliance_epoch_time_milliseconds(self):
"""Test get_snapshot_policy_compliance epoch time."""
from_epoch = str(int(time.time() * 1000))
snapshot_policy_name, storage_group_details = (
self.get_storage_group_and_associated_snapshot_policy())
storage_group_name = storage_group_details.get('storageGroupId')
to_epoch = str(int(time.time() * 1000))
compliance_details = (
self.snapshot_policy.get_snapshot_policy_compliance_epoch(
storage_group_name, from_epoch=from_epoch, to_epoch=to_epoch))
self.assertEqual(storage_group_name, compliance_details.get(
'storage_group_name'))
self.assertEqual('NONE', compliance_details.get('compliance'))
self.cleanup_snapshot_policy_and_storage_group(
snapshot_policy_name, storage_group_name)
def test_get_snapshot_policy_compliance_human_readable_time(self):
"""Test get_snapshot_policy_compliance human readable time."""
ts = time.gmtime()
from_time_string = time.strftime("%Y-%m-%d %H:%M", ts)
snapshot_policy_name, storage_group_details = (
self.get_storage_group_and_associated_snapshot_policy())
storage_group_name = storage_group_details.get('storageGroupId')
ts = time.gmtime()
to_time_string = time.strftime("%Y-%m-%d %H:%M", ts)
sp = self.snapshot_policy
compliance_details = (
sp.get_snapshot_policy_compliance_human_readable_time(
storage_group_name, from_time_string=from_time_string,
to_time_string=to_time_string))
self.assertEqual(storage_group_name, compliance_details.get(
'storage_group_name'))
self.assertEqual('NONE', compliance_details.get('compliance'))
self.cleanup_snapshot_policy_and_storage_group(
snapshot_policy_name, storage_group_name)
def test_get_snapshot_policy_compliance_mixed_time(self):
"""Test get_snapshot_policy_compliance human readable time."""
self.skipTest(reason='from human readable to to epoch bug')
ts = time.gmtime()
from_time_string = time.strftime("%Y-%m-%d %H:%M", ts)
snapshot_policy_name, storage_group_details = (
self.get_storage_group_and_associated_snapshot_policy())
storage_group_name = storage_group_details.get('storageGroupId')
to_epoch = str(int(time.time()))
compliance_details = (
self.snapshot_policy.get_snapshot_policy_compliance(
storage_group_name, from_time_string=from_time_string,
to_epoch=to_epoch))
self.assertEqual(storage_group_name, compliance_details.get(
'storage_group_name'))
self.assertEqual('NONE', compliance_details.get('compliance'))
self.cleanup_snapshot_policy_and_storage_group(
snapshot_policy_name, storage_group_name)
def test_get_snapshot_policy_compliance_mixed_time_2(self):
"""Test get_snapshot_policy_compliance human readable time."""
from_epoch = str(int(time.time()))
snapshot_policy_name, storage_group_details = (
self.get_storage_group_and_associated_snapshot_policy())
storage_group_name = storage_group_details.get('storageGroupId')
ts = time.gmtime()
to_time_string = time.strftime("%Y-%m-%d %H:%M", ts)
compliance_details = (
self.snapshot_policy.get_snapshot_policy_compliance(
storage_group_name, from_epoch=from_epoch,
to_time_string=to_time_string))
self.assertEqual(storage_group_name, compliance_details.get(
'storage_group_name'))
self.assertEqual('NONE', compliance_details.get('compliance'))
self.cleanup_snapshot_policy_and_storage_group(
snapshot_policy_name, storage_group_name)
def test_get_snapshot_policy_compliance_last_week(self):
"""Test get_snapshot_policy_compliance last week."""
snapshot_policy_name, storage_group_details = (
self.get_storage_group_and_associated_snapshot_policy())
storage_group_name = storage_group_details.get('storageGroupId')
compliance_details = (
self.snapshot_policy.get_snapshot_policy_compliance_last_week(
storage_group_name))
self.assertEqual(storage_group_name, compliance_details.get(
'storage_group_name'))
self.assertEqual('NONE', compliance_details.get('compliance'))
self.cleanup_snapshot_policy_and_storage_group(
snapshot_policy_name, storage_group_name)
def test_get_snapshot_policy_compliance_last_four_weeks(self):
"""Test get_snapshot_policy_compliance last four weeks."""
snapshot_policy_name, storage_group_details = (
self.get_storage_group_and_associated_snapshot_policy())
storage_group_name = storage_group_details.get('storageGroupId')
sp = self.snapshot_policy
compliance_details = (
sp.get_snapshot_policy_compliance_last_four_weeks(
storage_group_name))
self.assertEqual(storage_group_name, compliance_details.get(
'storage_group_name'))
self.assertEqual('NONE', compliance_details.get('compliance'))
self.cleanup_snapshot_policy_and_storage_group(
snapshot_policy_name, storage_group_name)
def test_get_snapshot_policy_storage_group_list(self):
"""Test get_snapshot_policy_storage_group_list"""
sp = self.snapshot_policy
snapshot_policy_name = 'DailyDefault'
snap_list = (
sp.get_snapshot_policy_storage_group_list(
snapshot_policy_name=snapshot_policy_name))
self.assertIsInstance(snap_list, list)
| mit |
drufat/vispy | vispy.proxy.py | 18 | 1563 | # -*- coding: utf-8 -*-
# Copyright (c) 2013, Almar Klein
# (new) BSD License.
"""
This module provides an easy way to enable importing a package event
if it's not on sys.path. The main use case is to import a package
from its developmment repository without having to install it.
This module is sort of like a symlink for Python modules.
To install:
1) Copy this file to a directory that is on the PYTHONPATH
2) Rename the file to "yourpackage.py".
If the real package is in "yourpackage/yourpackage" relative to this file,
you're done. Otherwise modify PARENT_DIR_OF_MODULE.
"""
import os
import sys
# Determine directory and package name
THIS_DIR = os.path.abspath(os.path.dirname(__file__))
MODULE_NAME = __name__
# Override if necessary
PARENT_DIR_OF_MODULE = os.path.join(THIS_DIR, MODULE_NAME)
# Insert in sys.path, so we can import the *real* package
if not PARENT_DIR_OF_MODULE in sys.path:
sys.path.insert(0, PARENT_DIR_OF_MODULE)
# Remove *this* module from sys.modules, so we can import that name again
# (keep reference to avoid premature cleanup)
_old = sys.modules.pop(MODULE_NAME, None)
# Import the *real* package. This will put the new package in
# sys.modules. Note that the new package is injected in the namespace
# from which "import package" is called; we do not need to import *.
try:
__import__(MODULE_NAME, level=0)
except Exception as err:
sys.modules[MODULE_NAME] = _old # Prevent KeyError
raise
# Clean up after ourselves
if PARENT_DIR_OF_MODULE in sys.path:
sys.path.remove(PARENT_DIR_OF_MODULE)
| bsd-3-clause |
ArcherSys/ArcherSys | Lib/site-packages/pkginfo/commandline.py | 3 | 6604 | """Print the metadata for one or more Python package distributions.
Usage: %prog [options] path+
Each 'path' entry can be one of the following:
o a source distribution: in this case, 'path' should point to an existing
archive file (.tar.gz, .tar.bz2, or .zip) as generated by 'setup.py sdist'.
o a binary distribution: in this case, 'path' should point to an existing
archive file (.egg)
o a "develop" checkout: in ths case, 'path' should point to a directory
intialized via 'setup.py develop' (under setuptools).
o an installed package: in this case, 'path' should be the importable name
of the package.
"""
try:
from configparser import ConfigParser
except ImportError: # pragma: NO COVER
from ConfigParser import ConfigParser
from csv import writer
import optparse
import os
import sys
from pkginfo import get_metadata
def _parse_options(args=None):
parser = optparse.OptionParser(usage=__doc__)
parser.add_option("-m", "--metadata-version", default=None,
help="Override metadata version")
parser.add_option("-f", "--field", dest="fields", action="append",
help="Specify an output field (repeatable)",
)
parser.add_option("-d", "--download-url-prefix",
dest="download_url_prefix",
help="Download URL prefix",
)
parser.add_option("--simple", dest="output", action="store_const",
const='simple', default='simple',
help="Output as simple key-value pairs",
)
parser.add_option("-s", "--skip", dest="skip", action="store_true",
default=True,
help="Skip missing values in simple output",
)
parser.add_option("-S", "--no-skip", dest="skip", action="store_false",
help="Don't skip missing values in simple output",
)
parser.add_option("--single", dest="output", action="store_const",
const='single',
help="Output delimited values",
)
parser.add_option("--item-delim", dest="item_delim", action="store",
default=';',
help="Delimiter for fields in single-line output",
)
parser.add_option("--sequence-delim", dest="sequence_delim",
action="store", default=',',
help="Delimiter for multi-valued fields",
)
parser.add_option("--csv", dest="output", action="store_const",
const='csv',
help="Output as CSV",
)
parser.add_option("--ini", dest="output", action="store_const",
const='ini',
help="Output as INI",
)
options, args = parser.parse_args(args)
if len(args)==0:
parser.error("Pass one or more files or directories as arguments.")
else:
return options, args
class Base(object):
_fields = None
def __init__(self, options):
if options.fields:
self._fields = options.fields
def finish(self): # pragma: NO COVER
pass
class Simple(Base):
def __init__(self, options):
super(Simple, self).__init__(options)
self._skip = options.skip
def __call__(self, meta):
for field in self._fields or list(meta):
value = getattr(meta, field)
if (not self._skip) or (value is not None and value!=()):
print("%s: %s" % (field, value))
class SingleLine(Base):
_fields = None
def __init__(self, options):
super(SingleLine, self).__init__(options)
self._item_delim = options.item_delim
self._sequence_delim = options.sequence_delim
def __call__(self, meta):
if self._fields is None:
self._fields = list(meta)
values = []
for field in self._fields:
value = getattr(meta, field)
if isinstance(value, (tuple, list)):
value = self._sequence_delim.join(value)
else:
value = str(value)
values.append(value)
print(self._item_delim.join(values))
class CSV(Base):
_writer = None
def __init__(self, options):
super(CSV, self).__init__(options)
self._sequence_delim = options.sequence_delim
def __call__(self, meta):
if self._fields is None:
self._fields = list(meta) # first dist wins
fields = self._fields
if self._writer is None:
self._writer = writer(sys.stdout)
self._writer.writerow(fields)
values = []
for field in fields:
value = getattr(meta, field)
if isinstance(value, (tuple, list)):
value = self._sequence_delim.join(value)
else:
value = str(value)
values.append(value)
self._writer.writerow(values)
class INI(Base):
_fields = None
def __init__(self, options):
super(INI, self).__init__(options)
self._parser = ConfigParser()
def __call__(self, meta):
name = meta.name
version = meta.version
section = '%s-%s' % (name, version)
if self._parser.has_section(section):
raise ValueError('Duplicate distribution: %s' % section)
self._parser.add_section(section)
for field in self._fields or list(meta):
value = getattr(meta, field)
if isinstance(value, (tuple, list)):
value = '\n\t'.join(value)
self._parser.set(section, field, value)
def finish(self):
self._parser.write(sys.stdout) # pragma: NO COVER
_FORMATTERS = {
'simple': Simple,
'single': SingleLine,
'csv': CSV,
'ini': INI,
}
def main(args=None):
"""Entry point for pkginfo tool
"""
options, paths = _parse_options(args)
format = getattr(options, 'output', 'simple')
formatter = _FORMATTERS[format](options)
for path in paths:
meta = get_metadata(path, options.metadata_version)
if meta is None:
continue
if options.download_url_prefix:
if meta.download_url is None:
filename = os.path.basename(path)
meta.download_url = '%s/%s' % (options.download_url_prefix,
filename)
formatter(meta)
formatter.finish()
| mit |
akash1808/nova_test_latest | nova/tests/unit/api/openstack/compute/contrib/test_baremetal_nodes.py | 34 | 9194 | # Copyright (c) 2013 NTT DOCOMO, 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.
import mock
import six
from webob import exc
from ironicclient import exc as ironic_exc
from nova.api.openstack.compute.contrib import baremetal_nodes as b_nodes_v2
from nova.api.openstack.compute.plugins.v3 import baremetal_nodes \
as b_nodes_v21
from nova.api.openstack import extensions
from nova import context
from nova import test
from nova.tests.unit.virt.ironic import utils as ironic_utils
class FakeRequest(object):
def __init__(self, context):
self.environ = {"nova.context": context}
def fake_node(**updates):
node = {
'id': 1,
'service_host': "host",
'cpus': 8,
'memory_mb': 8192,
'local_gb': 128,
'pm_address': "10.1.2.3",
'pm_user': "pm_user",
'pm_password': "pm_pass",
'terminal_port': 8000,
'interfaces': [],
'instance_uuid': 'fake-instance-uuid',
}
if updates:
node.update(updates)
return node
def fake_node_ext_status(**updates):
node = fake_node(uuid='fake-uuid',
task_state='fake-task-state',
updated_at='fake-updated-at',
pxe_config_path='fake-pxe-config-path')
if updates:
node.update(updates)
return node
FAKE_IRONIC_CLIENT = ironic_utils.FakeClient()
@mock.patch.object(b_nodes_v21, '_get_ironic_client',
lambda *_: FAKE_IRONIC_CLIENT)
class BareMetalNodesTestV21(test.NoDBTestCase):
mod = b_nodes_v21
def setUp(self):
super(BareMetalNodesTestV21, self).setUp()
self._setup()
self.context = context.get_admin_context()
self.request = FakeRequest(self.context)
def _setup(self):
self.controller = b_nodes_v21.BareMetalNodeController()
@mock.patch.object(FAKE_IRONIC_CLIENT.node, 'list')
def test_index_ironic(self, mock_list):
properties = {'cpus': 2, 'memory_mb': 1024, 'local_gb': 20}
node = ironic_utils.get_test_node(properties=properties)
mock_list.return_value = [node]
res_dict = self.controller.index(self.request)
expected_output = {'nodes':
[{'memory_mb': properties['memory_mb'],
'host': 'IRONIC MANAGED',
'disk_gb': properties['local_gb'],
'interfaces': [],
'task_state': None,
'id': node.uuid,
'cpus': properties['cpus']}]}
self.assertEqual(expected_output, res_dict)
mock_list.assert_called_once_with(detail=True)
@mock.patch.object(FAKE_IRONIC_CLIENT.node, 'list')
def test_index_ironic_missing_properties(self, mock_list):
properties = {'cpus': 2}
node = ironic_utils.get_test_node(properties=properties)
mock_list.return_value = [node]
res_dict = self.controller.index(self.request)
expected_output = {'nodes':
[{'memory_mb': 0,
'host': 'IRONIC MANAGED',
'disk_gb': 0,
'interfaces': [],
'task_state': None,
'id': node.uuid,
'cpus': properties['cpus']}]}
self.assertEqual(expected_output, res_dict)
mock_list.assert_called_once_with(detail=True)
def test_index_ironic_not_implemented(self):
with mock.patch.object(self.mod, 'ironic_client', None):
self.assertRaises(exc.HTTPNotImplemented,
self.controller.index,
self.request)
@mock.patch.object(FAKE_IRONIC_CLIENT.node, 'list_ports')
@mock.patch.object(FAKE_IRONIC_CLIENT.node, 'get')
def test_show_ironic(self, mock_get, mock_list_ports):
properties = {'cpus': 1, 'memory_mb': 512, 'local_gb': 10}
node = ironic_utils.get_test_node(properties=properties)
port = ironic_utils.get_test_port()
mock_get.return_value = node
mock_list_ports.return_value = [port]
res_dict = self.controller.show(self.request, node.uuid)
expected_output = {'node':
{'memory_mb': properties['memory_mb'],
'instance_uuid': None,
'host': 'IRONIC MANAGED',
'disk_gb': properties['local_gb'],
'interfaces': [{'address': port.address}],
'task_state': None,
'id': node.uuid,
'cpus': properties['cpus']}}
self.assertEqual(expected_output, res_dict)
mock_get.assert_called_once_with(node.uuid)
mock_list_ports.assert_called_once_with(node.uuid)
@mock.patch.object(FAKE_IRONIC_CLIENT.node, 'list_ports')
@mock.patch.object(FAKE_IRONIC_CLIENT.node, 'get')
def test_show_ironic_no_properties(self, mock_get, mock_list_ports):
properties = {}
node = ironic_utils.get_test_node(properties=properties)
port = ironic_utils.get_test_port()
mock_get.return_value = node
mock_list_ports.return_value = [port]
res_dict = self.controller.show(self.request, node.uuid)
expected_output = {'node':
{'memory_mb': 0,
'instance_uuid': None,
'host': 'IRONIC MANAGED',
'disk_gb': 0,
'interfaces': [{'address': port.address}],
'task_state': None,
'id': node.uuid,
'cpus': 0}}
self.assertEqual(expected_output, res_dict)
mock_get.assert_called_once_with(node.uuid)
mock_list_ports.assert_called_once_with(node.uuid)
@mock.patch.object(FAKE_IRONIC_CLIENT.node, 'list_ports')
@mock.patch.object(FAKE_IRONIC_CLIENT.node, 'get')
def test_show_ironic_no_interfaces(self, mock_get, mock_list_ports):
properties = {'cpus': 1, 'memory_mb': 512, 'local_gb': 10}
node = ironic_utils.get_test_node(properties=properties)
mock_get.return_value = node
mock_list_ports.return_value = []
res_dict = self.controller.show(self.request, node.uuid)
self.assertEqual([], res_dict['node']['interfaces'])
mock_get.assert_called_once_with(node.uuid)
mock_list_ports.assert_called_once_with(node.uuid)
@mock.patch.object(FAKE_IRONIC_CLIENT.node, 'get',
side_effect=ironic_exc.NotFound())
def test_show_ironic_node_not_found(self, mock_get):
error = self.assertRaises(exc.HTTPNotFound, self.controller.show,
self.request, 'fake-uuid')
self.assertIn('fake-uuid', six.text_type(error))
def test_show_ironic_not_implemented(self):
with mock.patch.object(self.mod, 'ironic_client', None):
properties = {'cpus': 1, 'memory_mb': 512, 'local_gb': 10}
node = ironic_utils.get_test_node(properties=properties)
self.assertRaises(exc.HTTPNotImplemented, self.controller.show,
self.request, node.uuid)
def test_create_ironic_not_supported(self):
self.assertRaises(exc.HTTPBadRequest,
self.controller.create,
self.request, {'node': object()})
def test_delete_ironic_not_supported(self):
self.assertRaises(exc.HTTPBadRequest,
self.controller.delete,
self.request, 'fake-id')
def test_add_interface_ironic_not_supported(self):
self.assertRaises(exc.HTTPBadRequest,
self.controller._add_interface,
self.request, 'fake-id', 'fake-body')
def test_remove_interface_ironic_not_supported(self):
self.assertRaises(exc.HTTPBadRequest,
self.controller._remove_interface,
self.request, 'fake-id', 'fake-body')
@mock.patch.object(b_nodes_v2, '_get_ironic_client',
lambda *_: FAKE_IRONIC_CLIENT)
class BareMetalNodesTestV2(BareMetalNodesTestV21):
mod = b_nodes_v2
def _setup(self):
self.ext_mgr = self.mox.CreateMock(extensions.ExtensionManager)
self.controller = b_nodes_v2.BareMetalNodeController(self.ext_mgr)
| apache-2.0 |
postvakje/sympy | sympy/diffgeom/tests/test_class_structure.py | 126 | 1124 | from sympy.diffgeom import Manifold, Patch, CoordSystem, Point
from sympy import symbols, Function
m = Manifold('m', 2)
p = Patch('p', m)
cs = CoordSystem('cs', p, ['a', 'b'])
cs_noname = CoordSystem('cs', p)
x, y = symbols('x y')
f = Function('f')
s1, s2 = cs.coord_functions()
v1, v2 = cs.base_vectors()
f1, f2 = cs.base_oneforms()
def test_point():
point = Point(cs, [x, y])
assert point == point.func(*point.args)
assert point != Point(cs, [2, y])
#TODO assert point.subs(x, 2) == Point(cs, [2, y])
#TODO assert point.free_symbols == set([x, y])
def test_rebuild():
assert m == m.func(*m.args)
assert p == p.func(*p.args)
assert cs == cs.func(*cs.args)
assert cs_noname == cs_noname.func(*cs_noname.args)
assert s1 == s1.func(*s1.args)
assert v1 == v1.func(*v1.args)
assert f1 == f1.func(*f1.args)
def test_subs():
assert s1.subs(s1, s2) == s2
assert v1.subs(v1, v2) == v2
assert f1.subs(f1, f2) == f2
assert (x*f(s1) + y).subs(s1, s2) == x*f(s2) + y
assert (f(s1)*v1).subs(v1, v2) == f(s1)*v2
assert (y*f(s1)*f1).subs(f1, f2) == y*f(s1)*f2
| bsd-3-clause |
mdehollander/bioconda-recipes | recipes/biopet-vcfstats/1.0/biopet-vcfstats.py | 44 | 3367 | #!/usr/bin/env python
#
# Wrapper script for starting the biopet-vcfstats JAR package
#
# This script is written for use with the Conda package manager and is copied
# from the peptide-shaker wrapper. Only the parameters are changed.
# (https://github.com/bioconda/bioconda-recipes/blob/master/recipes/peptide-shaker/peptide-shaker.py)
#
# This file was automatically generated by the sbt-bioconda plugin.
import os
import subprocess
import sys
import shutil
from os import access
from os import getenv
from os import X_OK
jar_file = 'VcfStats-assembly-1.0.jar'
default_jvm_mem_opts = []
# !!! End of parameter section. No user-serviceable code below this line !!!
def real_dirname(path):
"""Return the symlink-resolved, canonicalized directory-portion of path."""
return os.path.dirname(os.path.realpath(path))
def java_executable():
"""Return the executable name of the Java interpreter."""
java_home = getenv('JAVA_HOME')
java_bin = os.path.join('bin', 'java')
if java_home and access(os.path.join(java_home, java_bin), X_OK):
return os.path.join(java_home, java_bin)
else:
return 'java'
def jvm_opts(argv):
"""Construct list of Java arguments based on our argument list.
The argument list passed in argv must not include the script name.
The return value is a 3-tuple lists of strings of the form:
(memory_options, prop_options, passthrough_options)
"""
mem_opts = []
prop_opts = []
pass_args = []
exec_dir = None
for arg in argv:
if arg.startswith('-D'):
prop_opts.append(arg)
elif arg.startswith('-XX'):
prop_opts.append(arg)
elif arg.startswith('-Xm'):
mem_opts.append(arg)
elif arg.startswith('--exec_dir='):
exec_dir = arg.split('=')[1].strip('"').strip("'")
if not os.path.exists(exec_dir):
shutil.copytree(real_dirname(sys.argv[0]), exec_dir, symlinks=False, ignore=None)
else:
pass_args.append(arg)
# In the original shell script the test coded below read:
# if [ "$jvm_mem_opts" == "" ] && [ -z ${_JAVA_OPTIONS+x} ]
# To reproduce the behaviour of the above shell code fragment
# it is important to explictly check for equality with None
# in the second condition, so a null envar value counts as True!
if mem_opts == [] and getenv('_JAVA_OPTIONS') is None:
mem_opts = default_jvm_mem_opts
return (mem_opts, prop_opts, pass_args, exec_dir)
def main():
"""
PeptideShaker updates files relative to the path of the jar file.
In a multiuser setting, the option --exec_dir="exec_dir"
can be used as the location for the peptide-shaker distribution.
If the exec_dir dies not exist,
we copy the jar file, lib, and resources to the exec_dir directory.
"""
java = java_executable()
(mem_opts, prop_opts, pass_args, exec_dir) = jvm_opts(sys.argv[1:])
jar_dir = exec_dir if exec_dir else real_dirname(sys.argv[0])
if pass_args != [] and pass_args[0].startswith('eu'):
jar_arg = '-cp'
else:
jar_arg = '-jar'
jar_path = os.path.join(jar_dir, jar_file)
java_args = [java] + mem_opts + prop_opts + [jar_arg] + [jar_path] + pass_args
sys.exit(subprocess.call(java_args))
if __name__ == '__main__':
main()
| mit |
martinbuc/missionplanner | Lib/string.py | 55 | 21398 | """A collection of string operations (most are no longer used).
Warning: most of the code you see here isn't normally used nowadays.
Beginning with Python 1.6, many of these functions are implemented as
methods on the standard string object. They used to be implemented by
a built-in module called strop, but strop is now obsolete itself.
Public module variables:
whitespace -- a string containing all characters considered whitespace
lowercase -- a string containing all characters considered lowercase letters
uppercase -- a string containing all characters considered uppercase letters
letters -- a string containing all characters considered letters
digits -- a string containing all characters considered decimal digits
hexdigits -- a string containing all characters considered hexadecimal digits
octdigits -- a string containing all characters considered octal digits
punctuation -- a string containing all characters considered punctuation
printable -- a string containing all characters considered printable
"""
# Some strings for ctype-style character classification
whitespace = ' \t\n\r\v\f'
lowercase = 'abcdefghijklmnopqrstuvwxyz'
uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
letters = lowercase + uppercase
ascii_lowercase = lowercase
ascii_uppercase = uppercase
ascii_letters = ascii_lowercase + ascii_uppercase
digits = '0123456789'
hexdigits = digits + 'abcdef' + 'ABCDEF'
octdigits = '01234567'
punctuation = """!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""
printable = digits + letters + punctuation + whitespace
# Case conversion helpers
# Use str to convert Unicode literal in case of -U
l = map(chr, xrange(256))
_idmap = str('').join(l)
del l
# Functions which aren't available as string methods.
# Capitalize the words in a string, e.g. " aBc dEf " -> "Abc Def".
def capwords(s, sep=None):
"""capwords(s [,sep]) -> string
Split the argument into words using split, capitalize each
word using capitalize, and join the capitalized words using
join. If the optional second argument sep is absent or None,
runs of whitespace characters are replaced by a single space
and leading and trailing whitespace are removed, otherwise
sep is used to split and join the words.
"""
return (sep or ' ').join(x.capitalize() for x in s.split(sep))
# Construct a translation string
_idmapL = None
def maketrans(fromstr, tostr):
"""maketrans(frm, to) -> string
Return a translation table (a string of 256 bytes long)
suitable for use in string.translate. The strings frm and to
must be of the same length.
"""
if len(fromstr) != len(tostr):
raise ValueError, "maketrans arguments must have same length"
global _idmapL
if not _idmapL:
_idmapL = list(_idmap)
L = _idmapL[:]
fromstr = map(ord, fromstr)
for i in range(len(fromstr)):
L[fromstr[i]] = tostr[i]
return ''.join(L)
####################################################################
import re as _re
class _multimap:
"""Helper class for combining multiple mappings.
Used by .{safe_,}substitute() to combine the mapping and keyword
arguments.
"""
def __init__(self, primary, secondary):
self._primary = primary
self._secondary = secondary
def __getitem__(self, key):
try:
return self._primary[key]
except KeyError:
return self._secondary[key]
class _TemplateMetaclass(type):
pattern = r"""
%(delim)s(?:
(?P<escaped>%(delim)s) | # Escape sequence of two delimiters
(?P<named>%(id)s) | # delimiter and a Python identifier
{(?P<braced>%(id)s)} | # delimiter and a braced identifier
(?P<invalid>) # Other ill-formed delimiter exprs
)
"""
def __init__(cls, name, bases, dct):
super(_TemplateMetaclass, cls).__init__(name, bases, dct)
if 'pattern' in dct:
pattern = cls.pattern
else:
pattern = _TemplateMetaclass.pattern % {
'delim' : _re.escape(cls.delimiter),
'id' : cls.idpattern,
}
cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE)
class Template:
"""A string class for supporting $-substitutions."""
__metaclass__ = _TemplateMetaclass
delimiter = '$'
idpattern = r'[_a-z][_a-z0-9]*'
def __init__(self, template):
self.template = template
# Search for $$, $identifier, ${identifier}, and any bare $'s
def _invalid(self, mo):
i = mo.start('invalid')
lines = self.template[:i].splitlines(True)
if not lines:
colno = 1
lineno = 1
else:
colno = i - len(''.join(lines[:-1]))
lineno = len(lines)
raise ValueError('Invalid placeholder in string: line %d, col %d' %
(lineno, colno))
def substitute(self, *args, **kws):
if len(args) > 1:
raise TypeError('Too many positional arguments')
if not args:
mapping = kws
elif kws:
mapping = _multimap(kws, args[0])
else:
mapping = args[0]
# Helper function for .sub()
def convert(mo):
# Check the most common path first.
named = mo.group('named') or mo.group('braced')
if named is not None:
val = mapping[named]
# We use this idiom instead of str() because the latter will
# fail if val is a Unicode containing non-ASCII characters.
return '%s' % (val,)
if mo.group('escaped') is not None:
return self.delimiter
if mo.group('invalid') is not None:
self._invalid(mo)
raise ValueError('Unrecognized named group in pattern',
self.pattern)
return self.pattern.sub(convert, self.template)
def safe_substitute(self, *args, **kws):
if len(args) > 1:
raise TypeError('Too many positional arguments')
if not args:
mapping = kws
elif kws:
mapping = _multimap(kws, args[0])
else:
mapping = args[0]
# Helper function for .sub()
def convert(mo):
named = mo.group('named')
if named is not None:
try:
# We use this idiom instead of str() because the latter
# will fail if val is a Unicode containing non-ASCII
return '%s' % (mapping[named],)
except KeyError:
return self.delimiter + named
braced = mo.group('braced')
if braced is not None:
try:
return '%s' % (mapping[braced],)
except KeyError:
return self.delimiter + '{' + braced + '}'
if mo.group('escaped') is not None:
return self.delimiter
if mo.group('invalid') is not None:
return self.delimiter
raise ValueError('Unrecognized named group in pattern',
self.pattern)
return self.pattern.sub(convert, self.template)
####################################################################
# NOTE: Everything below here is deprecated. Use string methods instead.
# This stuff will go away in Python 3.0.
# Backward compatible names for exceptions
index_error = ValueError
atoi_error = ValueError
atof_error = ValueError
atol_error = ValueError
# convert UPPER CASE letters to lower case
def lower(s):
"""lower(s) -> string
Return a copy of the string s converted to lowercase.
"""
return s.lower()
# Convert lower case letters to UPPER CASE
def upper(s):
"""upper(s) -> string
Return a copy of the string s converted to uppercase.
"""
return s.upper()
# Swap lower case letters and UPPER CASE
def swapcase(s):
"""swapcase(s) -> string
Return a copy of the string s with upper case characters
converted to lowercase and vice versa.
"""
return s.swapcase()
# Strip leading and trailing tabs and spaces
def strip(s, chars=None):
"""strip(s [,chars]) -> string
Return a copy of the string s with leading and trailing
whitespace removed.
If chars is given and not None, remove characters in chars instead.
If chars is unicode, S will be converted to unicode before stripping.
"""
return s.strip(chars)
# Strip leading tabs and spaces
def lstrip(s, chars=None):
"""lstrip(s [,chars]) -> string
Return a copy of the string s with leading whitespace removed.
If chars is given and not None, remove characters in chars instead.
"""
return s.lstrip(chars)
# Strip trailing tabs and spaces
def rstrip(s, chars=None):
"""rstrip(s [,chars]) -> string
Return a copy of the string s with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
"""
return s.rstrip(chars)
# Split a string into a list of space/tab-separated words
def split(s, sep=None, maxsplit=-1):
"""split(s [,sep [,maxsplit]]) -> list of strings
Return a list of the words in the string s, using sep as the
delimiter string. If maxsplit is given, splits at no more than
maxsplit places (resulting in at most maxsplit+1 words). If sep
is not specified or is None, any whitespace string is a separator.
(split and splitfields are synonymous)
"""
return s.split(sep, maxsplit)
splitfields = split
# Split a string into a list of space/tab-separated words
def rsplit(s, sep=None, maxsplit=-1):
"""rsplit(s [,sep [,maxsplit]]) -> list of strings
Return a list of the words in the string s, using sep as the
delimiter string, starting at the end of the string and working
to the front. If maxsplit is given, at most maxsplit splits are
done. If sep is not specified or is None, any whitespace string
is a separator.
"""
return s.rsplit(sep, maxsplit)
# Join fields with optional separator
def join(words, sep = ' '):
"""join(list [,sep]) -> string
Return a string composed of the words in list, with
intervening occurrences of sep. The default separator is a
single space.
(joinfields and join are synonymous)
"""
return sep.join(words)
joinfields = join
# Find substring, raise exception if not found
def index(s, *args):
"""index(s, sub [,start [,end]]) -> int
Like find but raises ValueError when the substring is not found.
"""
return s.index(*args)
# Find last substring, raise exception if not found
def rindex(s, *args):
"""rindex(s, sub [,start [,end]]) -> int
Like rfind but raises ValueError when the substring is not found.
"""
return s.rindex(*args)
# Count non-overlapping occurrences of substring
def count(s, *args):
"""count(s, sub[, start[,end]]) -> int
Return the number of occurrences of substring sub in string
s[start:end]. Optional arguments start and end are
interpreted as in slice notation.
"""
return s.count(*args)
# Find substring, return -1 if not found
def find(s, *args):
"""find(s, sub [,start [,end]]) -> in
Return the lowest index in s where substring sub is found,
such that sub is contained within s[start,end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
"""
return s.find(*args)
# Find last substring, return -1 if not found
def rfind(s, *args):
"""rfind(s, sub [,start [,end]]) -> int
Return the highest index in s where substring sub is found,
such that sub is contained within s[start,end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
"""
return s.rfind(*args)
# for a bit of speed
_float = float
_int = int
_long = long
# Convert string to float
def atof(s):
"""atof(s) -> float
Return the floating point number represented by the string s.
"""
return _float(s)
# Convert string to integer
def atoi(s , base=10):
"""atoi(s [,base]) -> int
Return the integer represented by the string s in the given
base, which defaults to 10. The string s must consist of one
or more digits, possibly preceded by a sign. If base is 0, it
is chosen from the leading characters of s, 0 for octal, 0x or
0X for hexadecimal. If base is 16, a preceding 0x or 0X is
accepted.
"""
return _int(s, base)
# Convert string to long integer
def atol(s, base=10):
"""atol(s [,base]) -> long
Return the long integer represented by the string s in the
given base, which defaults to 10. The string s must consist
of one or more digits, possibly preceded by a sign. If base
is 0, it is chosen from the leading characters of s, 0 for
octal, 0x or 0X for hexadecimal. If base is 16, a preceding
0x or 0X is accepted. A trailing L or l is not accepted,
unless base is 0.
"""
return _long(s, base)
# Left-justify a string
def ljust(s, width, *args):
"""ljust(s, width[, fillchar]) -> string
Return a left-justified version of s, in a field of the
specified width, padded with spaces as needed. The string is
never truncated. If specified the fillchar is used instead of spaces.
"""
return s.ljust(width, *args)
# Right-justify a string
def rjust(s, width, *args):
"""rjust(s, width[, fillchar]) -> string
Return a right-justified version of s, in a field of the
specified width, padded with spaces as needed. The string is
never truncated. If specified the fillchar is used instead of spaces.
"""
return s.rjust(width, *args)
# Center a string
def center(s, width, *args):
"""center(s, width[, fillchar]) -> string
Return a center version of s, in a field of the specified
width. padded with spaces as needed. The string is never
truncated. If specified the fillchar is used instead of spaces.
"""
return s.center(width, *args)
# Zero-fill a number, e.g., (12, 3) --> '012' and (-3, 3) --> '-03'
# Decadent feature: the argument may be a string or a number
# (Use of this is deprecated; it should be a string as with ljust c.s.)
def zfill(x, width):
"""zfill(x, width) -> string
Pad a numeric string x with zeros on the left, to fill a field
of the specified width. The string x is never truncated.
"""
if not isinstance(x, basestring):
x = repr(x)
return x.zfill(width)
# Expand tabs in a string.
# Doesn't take non-printing chars into account, but does understand \n.
def expandtabs(s, tabsize=8):
"""expandtabs(s [,tabsize]) -> string
Return a copy of the string s with all tab characters replaced
by the appropriate number of spaces, depending on the current
column, and the tabsize (default 8).
"""
return s.expandtabs(tabsize)
# Character translation through look-up table.
def translate(s, table, deletions=""):
"""translate(s,table [,deletions]) -> string
Return a copy of the string s, where all characters occurring
in the optional argument deletions are removed, and the
remaining characters have been mapped through the given
translation table, which must be a string of length 256. The
deletions argument is not allowed for Unicode strings.
"""
if deletions or table is None:
return s.translate(table, deletions)
else:
# Add s[:0] so that if s is Unicode and table is an 8-bit string,
# table is converted to Unicode. This means that table *cannot*
# be a dictionary -- for that feature, use u.translate() directly.
return s.translate(table + s[:0])
# Capitalize a string, e.g. "aBc dEf" -> "Abc def".
def capitalize(s):
"""capitalize(s) -> string
Return a copy of the string s with only its first character
capitalized.
"""
return s.capitalize()
# Substring replacement (global)
def replace(s, old, new, maxreplace=-1):
"""replace (str, old, new[, maxreplace]) -> string
Return a copy of string str with all occurrences of substring
old replaced by new. If the optional argument maxreplace is
given, only the first maxreplace occurrences are replaced.
"""
return s.replace(old, new, maxreplace)
# Try importing optional built-in module "strop" -- if it exists,
# it redefines some string operations that are 100-1000 times faster.
# It also defines values for whitespace, lowercase and uppercase
# that match <ctype.h>'s definitions.
try:
from strop import maketrans, lowercase, uppercase, whitespace
letters = lowercase + uppercase
except ImportError:
pass # Use the original versions
########################################################################
# the Formatter class
# see PEP 3101 for details and purpose of this class
# The hard parts are reused from the C implementation. They're exposed as "_"
# prefixed methods of str and unicode.
# The overall parser is implemented in str._formatter_parser.
# The field name parser is implemented in str._formatter_field_name_split
class Formatter(object):
def format(self, format_string, *args, **kwargs):
return self.vformat(format_string, args, kwargs)
def vformat(self, format_string, args, kwargs):
used_args = set()
result = self._vformat(format_string, args, kwargs, used_args, 2)
self.check_unused_args(used_args, args, kwargs)
return result
def _vformat(self, format_string, args, kwargs, used_args, recursion_depth):
if recursion_depth < 0:
raise ValueError('Max string recursion exceeded')
result = []
for literal_text, field_name, format_spec, conversion in \
self.parse(format_string):
# output the literal text
if literal_text:
result.append(literal_text)
# if there's a field, output it
if field_name is not None:
# this is some markup, find the object and do
# the formatting
# given the field_name, find the object it references
# and the argument it came from
obj, arg_used = self.get_field(field_name, args, kwargs)
used_args.add(arg_used)
# do any conversion on the resulting object
obj = self.convert_field(obj, conversion)
# expand the format spec, if needed
format_spec = self._vformat(format_spec, args, kwargs,
used_args, recursion_depth-1)
# format the object and append to the result
result.append(self.format_field(obj, format_spec))
return ''.join(result)
def get_value(self, key, args, kwargs):
if isinstance(key, (int, long)):
return args[key]
else:
return kwargs[key]
def check_unused_args(self, used_args, args, kwargs):
pass
def format_field(self, value, format_spec):
return format(value, format_spec)
def convert_field(self, value, conversion):
# do any conversion on the resulting object
if conversion == 'r':
return repr(value)
elif conversion == 's':
return str(value)
elif conversion is None:
return value
raise ValueError("Unknown conversion specifier {0!s}".format(conversion))
# returns an iterable that contains tuples of the form:
# (literal_text, field_name, format_spec, conversion)
# literal_text can be zero length
# field_name can be None, in which case there's no
# object to format and output
# if field_name is not None, it is looked up, formatted
# with format_spec and conversion and then used
def parse(self, format_string):
return format_string._formatter_parser()
# given a field_name, find the object it references.
# field_name: the field being looked up, e.g. "0.name"
# or "lookup[3]"
# used_args: a set of which args have been used
# args, kwargs: as passed in to vformat
def get_field(self, field_name, args, kwargs):
first, rest = field_name._formatter_field_name_split()
obj = self.get_value(first, args, kwargs)
# loop through the rest of the field_name, doing
# getattr or getitem as needed
for is_attr, i in rest:
if is_attr:
obj = getattr(obj, i)
else:
obj = obj[i]
return obj, first
| gpl-3.0 |
thnee/ansible | lib/ansible/modules/network/skydive/skydive_edge.py | 38 | 4950 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2019, Ansible by Red Hat, inc
# 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': 'network'}
DOCUMENTATION = """
---
module: skydive_edge
version_added: "2.8"
author:
- "Sumit Jaiswal (@sjaiswal)"
short_description: Module to add edges to Skydive topology
description:
- This module handles setting up edges between two nodes based on the
relationship type to the Skydive topology.
requirements:
- skydive-client
extends_documentation_fragment: skydive
options:
parent_node:
description:
- To defined the first node of the link, it can be either an ID or
a gremlin expression
required: true
child_node:
description:
- To defined the second node of the link, it can be either an ID or
a gremlin expression
required: true
relation_type:
description:
- To define relation type of the node I(ownership, layer2, layer3).
required: true
host:
description:
- To define the host of the node.
default: ""
required: False
metadata:
description:
- To define metadata for the edge.
required: false
state:
description:
- State of the Skydive Edge. If value is I(present) new edge
will be created else if it is I(absent) it will be deleted.
default: present
choices:
- present
- absent
"""
EXAMPLES = """
- name: create tor
skydive_node:
name: 'TOR'
node_type: "fabric"
seed: TOR
metadata:
Model: Cisco xxxx
provider:
endpoint: localhost:8082
username: admin
password: admin
register: tor_result
- name: create port 1
skydive_node:
name: 'PORT1'
node_type: 'fabric'
seed: PORT1
provider:
endpoint: localhost:8082
username: admin
password: admin
register: port1_result
- name: create port 2
skydive_node:
name: 'PORT2'
node_type: 'fabric'
seed: PORT2
provider:
endpoint: localhost:8082
username: admin
password: admin
register: port2_result
- name: link node tor and port 1
skydive_edge:
parent_node: "{{ tor_result.UUID }}"
child_node: "{{ port1_result.UUID }}"
relation_type: ownership
state: present
provider:
endpoint: localhost:8082
username: admin
password: admin
- name: link node tor and port 2
skydive_edge:
parent_node: "{{ tor_result.UUID }}"
child_node: "{{ port2_result.UUID }}"
relation_type: ownership
state: present
provider:
endpoint: localhost:8082
username: admin
password: admin
- name: update link node tor and port 1 relation
skydive_edge:
parent_node: "{{ tor_result.UUID }}"
child_node: "{{ port2_result.UUID }}"
relation_type: layer2
state: upadte
provider:
endpoint: localhost:8082
username: admin
password: admin
- name: Unlink tor and port 2
skydive_edge:
parent_node: "{{ tor_result.UUID }}"
child_node: "{{ port2_result.UUID }}"
relation_type: ownership
state: absent
provider:
endpoint: localhost:8082
username: admin
password: admin
- name: link tor and port 2 via Gremlin expression
skydive_edge:
parent_node: G.V().Has('Name', 'TOR')
child_node: G.V().Has('Name', 'PORT2')
relation_type: ownership
state: present
provider:
endpoint: localhost:8082
username: admin
password: admin
- name: Unlink tor and port 2 via Gremlin expression
skydive_edge:
parent_node: G.V().Has('Name', 'TOR')
child_node: G.V().Has('Name', 'PORT2')
relation_type: ownership
state: absent
provider:
endpoint: localhost:8082
username: admin
password: admin
"""
RETURN = """ # """
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.network.skydive.api import skydive_edge
def main():
''' Main entry point for module execution
'''
ib_spec = dict(
relation_type=dict(type='str', required=True),
parent_node=dict(type='str', required=True),
child_node=dict(type='str', required=True),
host=dict(type='str', default=""),
metadata=dict(type='dict', default=dict())
)
argument_spec = dict(
provider=dict(required=False),
state=dict(default='present', choices=['present', 'absent'])
)
argument_spec.update(ib_spec)
argument_spec.update(skydive_edge.provider_spec)
module = AnsibleModule(argument_spec=argument_spec,
supports_check_mode=True)
skydive_obj = skydive_edge(module)
result = skydive_obj.run()
module.exit_json(**result)
if __name__ == '__main__':
main()
| gpl-3.0 |
nhomar/odoo | addons/account/wizard/account_open_closed_fiscalyear.py | 104 | 2341 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import fields, osv
from openerp.tools.translate import _
class account_open_closed_fiscalyear(osv.osv_memory):
_name = "account.open.closed.fiscalyear"
_description = "Choose Fiscal Year"
_columns = {
'fyear_id': fields.many2one('account.fiscalyear', \
'Fiscal Year', required=True, help='Select Fiscal Year which you want to remove entries for its End of year entries journal'),
}
def remove_entries(self, cr, uid, ids, context=None):
move_obj = self.pool.get('account.move')
data = self.browse(cr, uid, ids, context=context)[0]
period_journal = data.fyear_id.end_journal_period_id or False
if not period_journal:
raise osv.except_osv(_('Error!'), _("You have to set the 'End of Year Entries Journal' for this Fiscal Year which is set after generating opening entries from 'Generate Opening Entries'."))
ids_move = move_obj.search(cr, uid, [('journal_id','=',period_journal.journal_id.id),('period_id','=',period_journal.period_id.id)])
if ids_move:
cr.execute('delete from account_move where id IN %s', (tuple(ids_move),))
self.invalidate_cache(cr, uid, context=context)
return {'type': 'ir.actions.act_window_close'}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
toshywoshy/ansible | lib/ansible/modules/cloud/openstack/os_recordset.py | 21 | 7442 | #!/usr/bin/python
# Copyright (c) 2016 Hewlett-Packard Enterprise
# 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: os_recordset
short_description: Manage OpenStack DNS recordsets
extends_documentation_fragment: openstack
version_added: "2.2"
author: "Ricardo Carrillo Cruz (@rcarrillocruz)"
description:
- Manage OpenStack DNS recordsets. Recordsets can be created, deleted or
updated. Only the I(records), I(description), and I(ttl) values
can be updated.
options:
zone:
description:
- Zone managing the recordset
required: true
name:
description:
- Name of the recordset
required: true
recordset_type:
description:
- Recordset type
required: true
records:
description:
- List of recordset definitions
required: true
description:
description:
- Description of the recordset
ttl:
description:
- TTL (Time To Live) value in seconds
state:
description:
- Should the resource be present or absent.
choices: [present, absent]
default: present
availability_zone:
description:
- Ignored. Present for backwards compatibility
requirements:
- "python >= 2.7"
- "openstacksdk"
'''
EXAMPLES = '''
# Create a recordset named "www.example.net."
- os_recordset:
cloud: mycloud
state: present
zone: example.net.
name: www
recordset_type: primary
records: ['10.1.1.1']
description: test recordset
ttl: 3600
# Update the TTL on existing "www.example.net." recordset
- os_recordset:
cloud: mycloud
state: present
zone: example.net.
name: www
ttl: 7200
# Delete recordset named "www.example.net."
- os_recordset:
cloud: mycloud
state: absent
zone: example.net.
name: www
'''
RETURN = '''
recordset:
description: Dictionary describing the recordset.
returned: On success when I(state) is 'present'.
type: complex
contains:
id:
description: Unique recordset ID
type: str
sample: "c1c530a3-3619-46f3-b0f6-236927b2618c"
name:
description: Recordset name
type: str
sample: "www.example.net."
zone_id:
description: Zone id
type: str
sample: 9508e177-41d8-434e-962c-6fe6ca880af7
type:
description: Recordset type
type: str
sample: "A"
description:
description: Recordset description
type: str
sample: "Test description"
ttl:
description: Zone TTL value
type: int
sample: 3600
records:
description: Recordset records
type: list
sample: ['10.0.0.1']
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.openstack import openstack_full_argument_spec, openstack_module_kwargs, openstack_cloud_from_module
def _system_state_change(state, records, description, ttl, zone, recordset):
if state == 'present':
if recordset is None:
return True
if records is not None and recordset['records'] != records:
return True
if description is not None and recordset['description'] != description:
return True
if ttl is not None and recordset['ttl'] != ttl:
return True
if state == 'absent' and recordset:
return True
return False
def main():
argument_spec = openstack_full_argument_spec(
zone=dict(required=True),
name=dict(required=True),
recordset_type=dict(required=False),
records=dict(required=False, type='list'),
description=dict(required=False, default=None),
ttl=dict(required=False, default=None, type='int'),
state=dict(default='present', choices=['absent', 'present']),
)
module_kwargs = openstack_module_kwargs()
module = AnsibleModule(argument_spec,
required_if=[
('state', 'present',
['recordset_type', 'records'])],
supports_check_mode=True,
**module_kwargs)
zone = module.params.get('zone')
name = module.params.get('name')
state = module.params.get('state')
sdk, cloud = openstack_cloud_from_module(module)
try:
recordset_type = module.params.get('recordset_type')
recordset_filter = {'type': recordset_type}
recordsets = cloud.search_recordsets(zone, name_or_id=name, filters=recordset_filter)
if len(recordsets) == 1:
recordset = recordsets[0]
try:
recordset_id = recordset['id']
except KeyError as e:
module.fail_json(msg=str(e))
else:
# recordsets is filtered by type and should never be more than 1 return
recordset = None
if state == 'present':
records = module.params.get('records')
description = module.params.get('description')
ttl = module.params.get('ttl')
if module.check_mode:
module.exit_json(changed=_system_state_change(state,
records, description,
ttl, zone,
recordset))
if recordset is None:
recordset = cloud.create_recordset(
zone=zone, name=name, recordset_type=recordset_type,
records=records, description=description, ttl=ttl)
changed = True
else:
if records is None:
records = []
pre_update_recordset = recordset
changed = _system_state_change(state, records,
description, ttl,
zone, pre_update_recordset)
if changed:
zone = cloud.update_recordset(
zone, recordset_id,
records=records,
description=description,
ttl=ttl)
module.exit_json(changed=changed, recordset=recordset)
elif state == 'absent':
if module.check_mode:
module.exit_json(changed=_system_state_change(state,
None, None,
None,
None, recordset))
if recordset is None:
changed = False
else:
cloud.delete_recordset(zone, recordset_id)
changed = True
module.exit_json(changed=changed)
except sdk.exceptions.OpenStackCloudException as e:
module.fail_json(msg=str(e))
if __name__ == '__main__':
main()
| gpl-3.0 |
pamfilos/invenio | modules/websession/lib/password_migration_kit.py | 28 | 6510 | # -*- coding: utf-8 -*-
##
## Every db-related function of module webmessage
##
## This file is part of Invenio.
## Copyright (C) 2007, 2008, 2010, 2011 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.
""" Migration from local clear password [v0.92.1] to local encrypted
password_migration_kit
Usage: python password_migration_kit.py
This utility will encrypt all the local passwords stored in the database.
The encryption is not optional with the current Invenio code if local accounts
are used.
A backup copy of the user table will be created before the migration just in
case something goes wrong.
"""
__revision__ = "$Id$"
from invenio.dbquery import run_sql
from invenio.textutils import wrap_text_in_a_box
import sys
def migrate_passwords():
print wrap_text_in_a_box(title="Password migration kit (for Invenio prior to v0.92.1)", style='conclusion')
print "Checking your installation..."
if __check_update_possibility():
print "Tables are OK."
else:
print "No need to update."
sys.exit(1)
admin_pwd = __get_admin_pwd()
print "There are %i passwords to migrate (including guest users)" % __count_current_passwords()
print "========================================================="
print "Creating backup...",
sys.stdout.flush()
if __creating_backup():
print "OK"
else:
__print_error()
print "Migrating all Null password to ''...",
sys.stdout.flush()
if __migrate_passwords_from_null_to_empty_quotes():
print "OK"
else:
__print_error(True)
print "Changing the column type from string to blob...",
sys.stdout.flush()
if __migrate_column_from_string_to_blob():
print "OK"
else:
__print_error(True)
print "Encrypting passwords...",
sys.stdout.flush()
if __encrypt_password():
print "OK"
else:
__print_error(True)
print "Checking that admin could enter...",
sys.stdout.flush()
if __check_admin(admin_pwd):
print "OK"
else:
__print_error(True)
print "Removing backup...",
sys.stdout.flush()
if __removing_backup():
print "OK"
else:
__print_error()
print "========================================================="
print "Migration to encrypted local passwords has been successful."
def __check_update_possibility():
res = run_sql("SHOW COLUMNS FROM user LIKE 'password'");
if res:
return res[0][1] not in ('tinyblob', 'blob')
print "User table is broken or Invenio Database is not functional."
def __count_current_passwords():
query = "SELECT count(*) FROM user"
return run_sql(query)[0][0]
def __get_admin_pwd():
query = "SELECT password FROM user WHERE nickname='admin'"
return run_sql(query)[0][0]
def __migrate_passwords_from_null_to_empty_quotes():
query = "UPDATE user SET password='' WHERE password IS NULL"
try:
run_sql(query)
except Exception, msg:
print 'The query "%s" produced: %s' % (query, msg)
return False
return True
def __migrate_column_from_string_to_blob():
query = "ALTER TABLE user CHANGE password password BLOB NOT NULL"
try:
run_sql(query)
except Exception, msg:
print 'The query "%s" produced: %s' % (query, msg)
return False
return True
def __encrypt_password():
query = "UPDATE user SET password=AES_ENCRYPT(email,password)"
try:
run_sql(query)
except Exception, msg:
print 'The query "%s" produced: %s' % (query, msg)
return False
return True
def __check_admin(admin_pwd):
query = "SELECT nickname FROM user WHERE nickname='admin' AND password=AES_ENCRYPT(email, %s)"
try:
if run_sql(query, (admin_pwd, ))[0][0] == 'admin':
return True
else:
return False
except Exception, msg:
print 'The query "%s" produced: %s' % (query, msg)
return False
def __creating_backup():
query = "CREATE TABLE user_backup (PRIMARY KEY id (id)) SELECT id, email, password, note, settings, nickname, last_login FROM user"
try:
run_sql(query)
except Exception, msg:
print 'The query "%s" produced: %s' % (query, msg)
return False
return True
def __removing_backup():
query = "DROP TABLE user_backup"
try:
run_sql(query)
except Exception, msg:
print 'The query "%s" produced: %s' % (query, msg)
return False
return True
def __restoring_from_backup():
query = "UPDATE user SET password=''"
try:
run_sql(query)
except Exception, msg:
print 'The query "%s" produced: %s' % (query, msg)
return False
query = "ALTER TABLE user CHANGE password password varchar(20) NULL default NULL"
try:
run_sql(query)
except Exception, msg:
print 'The query "%s" produced: %s' % (query, msg)
return False
query = "UPDATE user,user_backup SET user.password=user_backup.password WHERE user.id=user_backup.id AND user.nickname=user_backup.nickname"
try:
run_sql(query)
except Exception, msg:
print 'The query "%s" produced: %s' % (query, msg)
return False
return True
def __print_error(restore_backup=False):
print wrap_text_in_a_box("The kit encountered errors in migrating passwords. Please contact The Invenio developers in order to get support providing all the printed messages.")
if restore_backup:
if __restoring_from_backup():
print wrap_text_in_a_box("Passwords were restored from the backup, but you still need to migrate them in order to use this version of Invenio.")
else:
print wrap_text_in_a_box("The kit was't unable to restore passwords from the backup")
sys.exit(1)
if __name__ == '__main__':
migrate_passwords()
| gpl-2.0 |
fidomason/kbengine | kbe/res/scripts/common/Lib/test/test_macpath.py | 101 | 4932 | import macpath
from test import support, test_genericpath
import unittest
class MacPathTestCase(unittest.TestCase):
def test_abspath(self):
self.assertEqual(macpath.abspath("xx:yy"), "xx:yy")
def test_isabs(self):
isabs = macpath.isabs
self.assertTrue(isabs("xx:yy"))
self.assertTrue(isabs("xx:yy:"))
self.assertTrue(isabs("xx:"))
self.assertFalse(isabs("foo"))
self.assertFalse(isabs(":foo"))
self.assertFalse(isabs(":foo:bar"))
self.assertFalse(isabs(":foo:bar:"))
self.assertTrue(isabs(b"xx:yy"))
self.assertTrue(isabs(b"xx:yy:"))
self.assertTrue(isabs(b"xx:"))
self.assertFalse(isabs(b"foo"))
self.assertFalse(isabs(b":foo"))
self.assertFalse(isabs(b":foo:bar"))
self.assertFalse(isabs(b":foo:bar:"))
def test_split(self):
split = macpath.split
self.assertEqual(split("foo:bar"),
('foo:', 'bar'))
self.assertEqual(split("conky:mountpoint:foo:bar"),
('conky:mountpoint:foo', 'bar'))
self.assertEqual(split(":"), ('', ''))
self.assertEqual(split(":conky:mountpoint:"),
(':conky:mountpoint', ''))
self.assertEqual(split(b"foo:bar"),
(b'foo:', b'bar'))
self.assertEqual(split(b"conky:mountpoint:foo:bar"),
(b'conky:mountpoint:foo', b'bar'))
self.assertEqual(split(b":"), (b'', b''))
self.assertEqual(split(b":conky:mountpoint:"),
(b':conky:mountpoint', b''))
def test_join(self):
join = macpath.join
self.assertEqual(join('a', 'b'), ':a:b')
self.assertEqual(join('', 'a:b'), 'a:b')
self.assertEqual(join('a:b', 'c'), 'a:b:c')
self.assertEqual(join('a:b', ':c'), 'a:b:c')
self.assertEqual(join('a', ':b', ':c'), ':a:b:c')
self.assertEqual(join(b'a', b'b'), b':a:b')
self.assertEqual(join(b'', b'a:b'), b'a:b')
self.assertEqual(join(b'a:b', b'c'), b'a:b:c')
self.assertEqual(join(b'a:b', b':c'), b'a:b:c')
self.assertEqual(join(b'a', b':b', b':c'), b':a:b:c')
def test_splitext(self):
splitext = macpath.splitext
self.assertEqual(splitext(":foo.ext"), (':foo', '.ext'))
self.assertEqual(splitext("foo:foo.ext"), ('foo:foo', '.ext'))
self.assertEqual(splitext(".ext"), ('.ext', ''))
self.assertEqual(splitext("foo.ext:foo"), ('foo.ext:foo', ''))
self.assertEqual(splitext(":foo.ext:"), (':foo.ext:', ''))
self.assertEqual(splitext(""), ('', ''))
self.assertEqual(splitext("foo.bar.ext"), ('foo.bar', '.ext'))
self.assertEqual(splitext(b":foo.ext"), (b':foo', b'.ext'))
self.assertEqual(splitext(b"foo:foo.ext"), (b'foo:foo', b'.ext'))
self.assertEqual(splitext(b".ext"), (b'.ext', b''))
self.assertEqual(splitext(b"foo.ext:foo"), (b'foo.ext:foo', b''))
self.assertEqual(splitext(b":foo.ext:"), (b':foo.ext:', b''))
self.assertEqual(splitext(b""), (b'', b''))
self.assertEqual(splitext(b"foo.bar.ext"), (b'foo.bar', b'.ext'))
def test_ismount(self):
ismount = macpath.ismount
self.assertEqual(ismount("a:"), True)
self.assertEqual(ismount("a:b"), False)
self.assertEqual(ismount("a:b:"), True)
self.assertEqual(ismount(""), False)
self.assertEqual(ismount(":"), False)
self.assertEqual(ismount(b"a:"), True)
self.assertEqual(ismount(b"a:b"), False)
self.assertEqual(ismount(b"a:b:"), True)
self.assertEqual(ismount(b""), False)
self.assertEqual(ismount(b":"), False)
def test_normpath(self):
normpath = macpath.normpath
self.assertEqual(normpath("a:b"), "a:b")
self.assertEqual(normpath("a"), ":a")
self.assertEqual(normpath("a:b::c"), "a:c")
self.assertEqual(normpath("a:b:c:::d"), "a:d")
self.assertRaises(macpath.norm_error, normpath, "a::b")
self.assertRaises(macpath.norm_error, normpath, "a:b:::c")
self.assertEqual(normpath(":"), ":")
self.assertEqual(normpath("a:"), "a:")
self.assertEqual(normpath("a:b:"), "a:b")
self.assertEqual(normpath(b"a:b"), b"a:b")
self.assertEqual(normpath(b"a"), b":a")
self.assertEqual(normpath(b"a:b::c"), b"a:c")
self.assertEqual(normpath(b"a:b:c:::d"), b"a:d")
self.assertRaises(macpath.norm_error, normpath, b"a::b")
self.assertRaises(macpath.norm_error, normpath, b"a:b:::c")
self.assertEqual(normpath(b":"), b":")
self.assertEqual(normpath(b"a:"), b"a:")
self.assertEqual(normpath(b"a:b:"), b"a:b")
class MacCommonTest(test_genericpath.CommonTest, unittest.TestCase):
pathmodule = macpath
if __name__ == "__main__":
unittest.main()
| lgpl-3.0 |
cjh1/StarCluster | starcluster/node.py | 9 | 44355 | # Copyright 2009-2014 Justin Riley
#
# This file is part of StarCluster.
#
# StarCluster is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# StarCluster 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 StarCluster. If not, see <http://www.gnu.org/licenses/>.
import re
import time
import stat
import base64
import socket
import posixpath
import subprocess
from starcluster import utils
from starcluster import static
from starcluster import sshutils
from starcluster import awsutils
from starcluster import managers
from starcluster import userdata
from starcluster import exception
from starcluster.logger import log
class NodeManager(managers.Manager):
"""
Manager class for Node objects
"""
def ssh_to_node(self, node_id, user='root', command=None,
forward_x11=False, forward_agent=False):
node = self.get_node(node_id, user=user)
return node.shell(user=user, command=command, forward_x11=forward_x11,
forward_agent=forward_agent)
def get_node(self, node_id, user='root'):
"""Factory for Node class"""
instances = self.ec2.get_all_instances()
node = None
for instance in instances:
if instance.dns_name == node_id:
node = instance
break
elif instance.id == node_id:
node = instance
break
if not node:
raise exception.InstanceDoesNotExist(node_id)
key = self.cfg.get_key(node.key_name)
node = Node(node, key.key_location, user=user)
return node
class Node(object):
"""
This class represents a single compute node in a StarCluster.
It contains all useful metadata for the node such as the internal/external
hostnames, ips, etc. as well as an ssh object for executing commands,
creating/modifying files on the node.
'instance' arg must be an instance of boto.ec2.instance.Instance
'key_location' arg is a string that contains the full path to the
private key corresponding to the keypair used to launch this node
'alias' keyword arg optionally names the node. If no alias is provided,
the alias is retrieved from the node's user_data based on the node's
launch index
'user' keyword optionally specifies user to ssh as (defaults to root)
"""
def __init__(self, instance, key_location, alias=None, user='root'):
self.instance = instance
self.ec2 = awsutils.EasyEC2(instance.connection.aws_access_key_id,
instance.connection.aws_secret_access_key,
connection=instance.connection)
self.key_location = key_location
self.user = user
self._alias = alias
self._groups = None
self._ssh = None
self._num_procs = None
self._memory = None
self._user_data = None
def __repr__(self):
return '<Node: %s (%s)>' % (self.alias, self.id)
def _get_user_data(self, tries=5):
tries = range(tries)
last_try = tries[-1]
for i in tries:
try:
user_data = self.ec2.get_instance_user_data(self.id)
return user_data
except exception.InstanceDoesNotExist:
if i == last_try:
log.debug("failed fetching user data")
raise
log.debug("InvalidInstanceID.NotFound: "
"retrying fetching user data (tries: %s)" % (i + 1))
time.sleep(5)
@property
def user_data(self):
if not self._user_data:
try:
raw = self._get_user_data()
self._user_data = userdata.unbundle_userdata(raw)
except IOError, e:
parent_cluster = self.parent_cluster
if self.parent_cluster:
raise exception.IncompatibleCluster(parent_cluster)
else:
raise exception.BaseException(
"Error occurred unbundling userdata: %s" % e)
return self._user_data
@property
def alias(self):
"""
Fetches the node's alias stored in a tag from either the instance
or the instance's parent spot request. If no alias tag is found an
exception is raised.
"""
if not self._alias:
alias = self.tags.get('alias')
if not alias:
aliasestxt = self.user_data.get(static.UD_ALIASES_FNAME, '')
aliases = aliasestxt.splitlines()[2:]
index = self.ami_launch_index
try:
alias = aliases[index]
except IndexError:
alias = None
log.debug("invalid aliases file in user_data:\n%s" %
aliasestxt)
if not alias:
raise exception.BaseException(
"instance %s has no alias" % self.id)
self.add_tag('alias', alias)
if not self.tags.get('Name'):
self.add_tag('Name', alias)
self._alias = alias
return self._alias
def get_plugins(self):
plugstxt = self.user_data.get(static.UD_PLUGINS_FNAME)
payload = plugstxt.split('\n', 2)[2]
plugins_metadata = utils.decode_uncompress_load(payload)
plugs = []
for klass, args, kwargs in plugins_metadata:
mod_path, klass_name = klass.rsplit('.', 1)
try:
mod = __import__(mod_path, fromlist=[klass_name])
plug = getattr(mod, klass_name)(*args, **kwargs)
except SyntaxError, e:
raise exception.PluginSyntaxError(
"Plugin %s (%s) contains a syntax error at line %s" %
(klass_name, e.filename, e.lineno))
except ImportError, e:
raise exception.PluginLoadError(
"Failed to import plugin %s: %s" %
(klass_name, e[0]))
except Exception as exc:
log.error("Error occured:", exc_info=True)
raise exception.PluginLoadError(
"Failed to load plugin %s with "
"the following error: %s - %s" %
(klass_name, exc.__class__.__name__, exc.message))
plugs.append(plug)
return plugs
def get_volumes(self):
volstxt = self.user_data.get(static.UD_VOLUMES_FNAME)
payload = volstxt.split('\n', 2)[2]
return utils.decode_uncompress_load(payload)
def _remove_all_tags(self):
tags = self.tags.keys()[:]
for t in tags:
self.remove_tag(t)
@property
def tags(self):
return self.instance.tags
def add_tag(self, key, value=None):
return self.instance.add_tag(key, value)
def remove_tag(self, key, value=None):
return self.instance.remove_tag(key, value)
@property
def groups(self):
if not self._groups:
groups = map(lambda x: x.name, self.instance.groups)
self._groups = self.ec2.get_all_security_groups(groupnames=groups)
return self._groups
@property
def cluster_groups(self):
sg_prefix = static.SECURITY_GROUP_PREFIX
return filter(lambda x: x.name.startswith(sg_prefix), self.groups)
@property
def parent_cluster(self):
try:
return self.cluster_groups[0]
except IndexError:
pass
@property
def num_processors(self):
if not self._num_procs:
self._num_procs = int(
self.ssh.execute(
'cat /proc/cpuinfo | grep processor | wc -l')[0])
return self._num_procs
@property
def memory(self):
if not self._memory:
self._memory = float(
self.ssh.execute(
"free -m | grep -i mem | awk '{print $2}'")[0])
return self._memory
@property
def ip_address(self):
return self.instance.ip_address
@property
def public_dns_name(self):
return self.instance.public_dns_name
@property
def private_ip_address(self):
return self.instance.private_ip_address
@property
def private_dns_name(self):
return self.instance.private_dns_name
@property
def private_dns_name_short(self):
return self.instance.private_dns_name.split('.')[0]
@property
def id(self):
return self.instance.id
@property
def block_device_mapping(self):
return self.instance.block_device_mapping
@property
def dns_name(self):
return self.instance.dns_name
@property
def state(self):
return self.instance.state
@property
def launch_time(self):
return self.instance.launch_time
@property
def local_launch_time(self):
ltime = utils.iso_to_localtime_tuple(self.launch_time)
return time.strftime("%Y-%m-%d %H:%M:%S", ltime.timetuple())
@property
def uptime(self):
return utils.get_elapsed_time(self.launch_time)
@property
def ami_launch_index(self):
try:
return int(self.instance.ami_launch_index)
except TypeError:
log.error("instance %s (state: %s) has no ami_launch_index" %
(self.id, self.state))
log.error("returning 0 as ami_launch_index...")
return 0
@property
def key_name(self):
return self.instance.key_name
@property
def arch(self):
return self.instance.architecture
@property
def kernel(self):
return self.instance.kernel
@property
def ramdisk(self):
return self.instance.ramdisk
@property
def instance_type(self):
return self.instance.instance_type
@property
def image_id(self):
return self.instance.image_id
@property
def placement(self):
return self.instance.placement
@property
def region(self):
return self.instance.region
@property
def vpc_id(self):
return self.instance.vpc_id
@property
def subnet_id(self):
return self.instance.subnet_id
@property
def root_device_name(self):
root_dev = self.instance.root_device_name
bmap = self.block_device_mapping
if bmap and root_dev not in bmap and self.is_ebs_backed():
# Hack for misconfigured AMIs (e.g. CentOS 6.3 Marketplace) These
# AMIs have root device name set to /dev/sda1 but no /dev/sda1 in
# block device map - only /dev/sda. These AMIs somehow magically
# work so check if /dev/sda exists and return that instead to
# prevent detach_external_volumes() from trying to detach the root
# volume on these AMIs.
log.warn("Root device %s is not in the block device map" %
root_dev)
log.warn("This means the AMI was registered with either "
"an incorrect root device name or an incorrect block "
"device mapping")
sda, sda1 = '/dev/sda', '/dev/sda1'
if root_dev == sda1:
log.info("Searching for possible root device: %s" % sda)
if sda in self.block_device_mapping:
log.warn("Found '%s' - assuming its the real root device" %
sda)
root_dev = sda
else:
log.warn("Device %s isn't in the block device map either" %
sda)
return root_dev
@property
def root_device_type(self):
return self.instance.root_device_type
def add_user_to_group(self, user, group):
"""
Add user (if exists) to group (if exists)
"""
if user not in self.get_user_map():
raise exception.BaseException("user %s does not exist" % user)
if group in self.get_group_map():
self.ssh.execute('gpasswd -a %s %s' % (user, 'utmp'))
else:
raise exception.BaseException("group %s does not exist" % group)
def get_group_map(self, key_by_gid=False):
"""
Returns dictionary where keys are remote group names and values are
grp.struct_grp objects from the standard grp module
key_by_gid=True will use the integer gid as the returned dictionary's
keys instead of the group's name
"""
grp_file = self.ssh.remote_file('/etc/group', 'r')
groups = [l.strip().split(':') for l in grp_file.readlines()]
grp_file.close()
grp_map = {}
for group in groups:
name, passwd, gid, mems = group
gid = int(gid)
mems = mems.split(',')
key = name
if key_by_gid:
key = gid
grp_map[key] = utils.struct_group([name, passwd, gid, mems])
return grp_map
def get_user_map(self, key_by_uid=False):
"""
Returns dictionary where keys are remote usernames and values are
pwd.struct_passwd objects from the standard pwd module
key_by_uid=True will use the integer uid as the returned dictionary's
keys instead of the user's login name
"""
etc_passwd = self.ssh.remote_file('/etc/passwd', 'r')
users = [l.strip().split(':') for l in etc_passwd.readlines()]
etc_passwd.close()
user_map = {}
for user in users:
name, passwd, uid, gid, gecos, home, shell = user
uid = int(uid)
gid = int(gid)
key = name
if key_by_uid:
key = uid
user_map[key] = utils.struct_passwd([name, passwd, uid, gid, gecos,
home, shell])
return user_map
def getgrgid(self, gid):
"""
Remote version of the getgrgid method in the standard grp module
returns a grp.struct_group
"""
gmap = self.get_group_map(key_by_gid=True)
return gmap.get(gid)
def getgrnam(self, groupname):
"""
Remote version of the getgrnam method in the standard grp module
returns a grp.struct_group
"""
gmap = self.get_group_map()
return gmap.get(groupname)
def getpwuid(self, uid):
"""
Remote version of the getpwuid method in the standard pwd module
returns a pwd.struct_passwd
"""
umap = self.get_user_map(key_by_uid=True)
return umap.get(uid)
def getpwnam(self, username):
"""
Remote version of the getpwnam method in the standard pwd module
returns a pwd.struct_passwd
"""
umap = self.get_user_map()
return umap.get(username)
def add_user(self, name, uid=None, gid=None, shell="bash"):
"""
Add a user to the remote system.
name - the username of the user being added
uid - optional user id to use when creating new user
gid - optional group id to use when creating new user
shell - optional shell assign to new user (default: bash)
"""
if gid:
self.ssh.execute('groupadd -o -g %s %s' % (gid, name))
user_add_cmd = 'useradd -o '
if uid:
user_add_cmd += '-u %s ' % uid
if gid:
user_add_cmd += '-g %s ' % gid
if shell:
user_add_cmd += '-s `which %s` ' % shell
user_add_cmd += "-m %s" % name
self.ssh.execute(user_add_cmd)
def generate_key_for_user(self, username, ignore_existing=False,
auth_new_key=False, auth_conn_key=False):
"""
Generates an id_rsa/id_rsa.pub keypair combo for a user on the remote
machine.
ignore_existing - if False, any existing key combos will be used rather
than generating a new RSA key
auth_new_key - if True, add the newly generated public key to the
remote user's authorized_keys file
auth_conn_key - if True, add the public key used to establish this ssh
connection to the remote user's authorized_keys
"""
user = self.getpwnam(username)
home_folder = user.pw_dir
ssh_folder = posixpath.join(home_folder, '.ssh')
if not self.ssh.isdir(ssh_folder):
self.ssh.mkdir(ssh_folder)
self.ssh.chown(user.pw_uid, user.pw_gid, ssh_folder)
private_key = posixpath.join(ssh_folder, 'id_rsa')
public_key = private_key + '.pub'
authorized_keys = posixpath.join(ssh_folder, 'authorized_keys')
key_exists = self.ssh.isfile(private_key)
if key_exists and not ignore_existing:
log.debug("Using existing key: %s" % private_key)
key = self.ssh.load_remote_rsa_key(private_key)
else:
key = sshutils.generate_rsa_key()
pubkey_contents = sshutils.get_public_key(key)
if not key_exists or ignore_existing:
# copy public key to remote machine
pub_key = self.ssh.remote_file(public_key, 'w')
pub_key.write(pubkey_contents)
pub_key.chown(user.pw_uid, user.pw_gid)
pub_key.chmod(0400)
pub_key.close()
# copy private key to remote machine
priv_key = self.ssh.remote_file(private_key, 'w')
key.write_private_key(priv_key)
priv_key.chown(user.pw_uid, user.pw_gid)
priv_key.chmod(0400)
priv_key.close()
if not auth_new_key or not auth_conn_key:
return key
auth_keys_contents = ''
if self.ssh.isfile(authorized_keys):
auth_keys = self.ssh.remote_file(authorized_keys, 'r')
auth_keys_contents = auth_keys.read()
auth_keys.close()
auth_keys = self.ssh.remote_file(authorized_keys, 'a')
if auth_new_key:
# add newly generated public key to user's authorized_keys
if pubkey_contents not in auth_keys_contents:
log.debug("adding auth_key_contents")
auth_keys.write('%s\n' % pubkey_contents)
if auth_conn_key and self.ssh._pkey:
# add public key used to create the connection to user's
# authorized_keys
conn_key = self.ssh._pkey
conn_pubkey_contents = sshutils.get_public_key(conn_key)
if conn_pubkey_contents not in auth_keys_contents:
log.debug("adding conn_pubkey_contents")
auth_keys.write('%s\n' % conn_pubkey_contents)
auth_keys.chown(user.pw_uid, user.pw_gid)
auth_keys.chmod(0600)
auth_keys.close()
return key
def add_to_known_hosts(self, username, nodes, add_self=True):
"""
Populate user's known_hosts file with pub keys from hosts in nodes list
username - name of the user to add to known hosts for
nodes - the nodes to add to the user's known hosts file
add_self - add this Node to known_hosts in addition to nodes
"""
user = self.getpwnam(username)
known_hosts_file = posixpath.join(user.pw_dir, '.ssh', 'known_hosts')
khosts = []
if add_self and self not in nodes:
nodes.append(self)
self.remove_from_known_hosts(username, nodes)
for node in nodes:
server_pkey = node.ssh.get_server_public_key()
node_names = {}.fromkeys([node.alias, node.private_dns_name,
node.private_dns_name_short],
node.private_ip_address)
node_names[node.public_dns_name] = node.ip_address
for name, ip in node_names.items():
name_ip = "%s,%s" % (name, ip)
khosts.append(' '.join([name_ip, server_pkey.get_name(),
base64.b64encode(str(server_pkey))]))
khostsf = self.ssh.remote_file(known_hosts_file, 'a')
khostsf.write('\n'.join(khosts) + '\n')
khostsf.chown(user.pw_uid, user.pw_gid)
khostsf.close()
def remove_from_known_hosts(self, username, nodes):
"""
Remove all network names for nodes from username's known_hosts file
on this Node
"""
user = self.getpwnam(username)
known_hosts_file = posixpath.join(user.pw_dir, '.ssh', 'known_hosts')
hostnames = []
for node in nodes:
hostnames += [node.alias, node.private_dns_name,
node.private_dns_name_short, node.public_dns_name]
if self.ssh.isfile(known_hosts_file):
regex = '|'.join(hostnames)
self.ssh.remove_lines_from_file(known_hosts_file, regex)
def enable_passwordless_ssh(self, username, nodes):
"""
Configure passwordless ssh for user between this Node and nodes
"""
user = self.getpwnam(username)
ssh_folder = posixpath.join(user.pw_dir, '.ssh')
priv_key_file = posixpath.join(ssh_folder, 'id_rsa')
pub_key_file = priv_key_file + '.pub'
known_hosts_file = posixpath.join(ssh_folder, 'known_hosts')
auth_key_file = posixpath.join(ssh_folder, 'authorized_keys')
self.add_to_known_hosts(username, nodes)
# exclude this node from copying
nodes = filter(lambda n: n.id != self.id, nodes)
# copy private key and public key to node
self.copy_remote_file_to_nodes(priv_key_file, nodes)
self.copy_remote_file_to_nodes(pub_key_file, nodes)
# copy authorized_keys and known_hosts to node
self.copy_remote_file_to_nodes(auth_key_file, nodes)
self.copy_remote_file_to_nodes(known_hosts_file, nodes)
def copy_remote_file_to_node(self, remote_file, node, dest=None):
return self.copy_remote_file_to_nodes(remote_file, [node], dest=dest)
def copy_remote_file_to_nodes(self, remote_file, nodes, dest=None):
"""
Copies a remote file from this Node instance to another Node instance
without passwordless ssh between the two.
dest - path to store the data in on the node (defaults to remote_file)
"""
if not dest:
dest = remote_file
rf = self.ssh.remote_file(remote_file, 'r')
contents = rf.read()
sts = rf.stat()
mode = stat.S_IMODE(sts.st_mode)
uid = sts.st_uid
gid = sts.st_gid
rf.close()
for node in nodes:
if self.id == node.id and remote_file == dest:
log.warn("src and destination are the same: %s, skipping" %
remote_file)
continue
nrf = node.ssh.remote_file(dest, 'w')
nrf.write(contents)
nrf.chown(uid, gid)
nrf.chmod(mode)
nrf.close()
def remove_user(self, name):
"""
Remove a user from the remote system
"""
self.ssh.execute('userdel %s' % name)
self.ssh.execute('groupdel %s' % name)
def export_fs_to_nodes(self, nodes, export_paths):
"""
Export each path in export_paths to each node in nodes via NFS
nodes - list of nodes to export each path to
export_paths - list of paths on this remote host to export to each node
Example:
# export /home and /opt/sge6 to each node in nodes
$ node.start_nfs_server()
$ node.export_fs_to_nodes(nodes=[node1,node2],
export_paths=['/home', '/opt/sge6'])
"""
log.debug("Cleaning up potentially stale NFS entries")
self.stop_exporting_fs_to_nodes(nodes, paths=export_paths)
log.info("Configuring NFS exports path(s):\n%s" %
' '.join(export_paths))
nfs_export_settings = "(async,no_root_squash,no_subtree_check,rw)"
etc_exports = self.ssh.remote_file('/etc/exports', 'r')
contents = etc_exports.read()
etc_exports.close()
etc_exports = self.ssh.remote_file('/etc/exports', 'a')
for node in nodes:
for path in export_paths:
export_line = ' '.join(
[path, node.alias + nfs_export_settings + '\n'])
if export_line not in contents:
etc_exports.write(export_line)
etc_exports.close()
self.ssh.execute('exportfs -fra')
def stop_exporting_fs_to_nodes(self, nodes, paths=None):
"""
Removes nodes from this node's /etc/exportfs
nodes - list of nodes to stop
Example:
$ node.remove_export_fs_to_nodes(nodes=[node1,node2])
"""
if paths:
regex = '|'.join([' '.join([path, node.alias]) for path in paths
for node in nodes])
else:
regex = '|'.join([n.alias for n in nodes])
self.ssh.remove_lines_from_file('/etc/exports', regex)
self.ssh.execute('exportfs -fra')
def start_nfs_server(self):
log.info("Starting NFS server on %s" % self.alias)
self.ssh.execute('/etc/init.d/portmap start', ignore_exit_status=True)
self.ssh.execute('mount -t rpc_pipefs sunrpc /var/lib/nfs/rpc_pipefs/',
ignore_exit_status=True)
EXPORTSD = '/etc/exports.d'
DUMMY_EXPORT_DIR = '/dummy_export_for_broken_init_script'
DUMMY_EXPORT_LINE = ' '.join([DUMMY_EXPORT_DIR,
'127.0.0.1(ro,no_subtree_check)'])
DUMMY_EXPORT_FILE = posixpath.join(EXPORTSD, 'dummy.exports')
# Hack to get around broken debian nfs-kernel-server script
# http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=679274
self.ssh.execute("mkdir -p %s" % EXPORTSD)
self.ssh.execute("mkdir -p %s" % DUMMY_EXPORT_DIR)
with self.ssh.remote_file(DUMMY_EXPORT_FILE, 'w') as dummyf:
dummyf.write(DUMMY_EXPORT_LINE)
self.ssh.execute('/etc/init.d/nfs start')
self.ssh.execute('rm -f %s' % DUMMY_EXPORT_FILE)
self.ssh.execute('rm -rf %s' % DUMMY_EXPORT_DIR)
self.ssh.execute('exportfs -fra')
def mount_nfs_shares(self, server_node, remote_paths):
"""
Mount each path in remote_paths from the remote server_node
server_node - remote server node that is sharing the remote_paths
remote_paths - list of remote paths to mount from server_node
"""
self.ssh.execute('/etc/init.d/portmap start')
# TODO: move this fix for xterm somewhere else
self.ssh.execute('mount -t devpts none /dev/pts',
ignore_exit_status=True)
mount_map = self.get_mount_map()
mount_paths = []
for path in remote_paths:
network_device = "%s:%s" % (server_node.alias, path)
if network_device in mount_map:
mount_path, typ, options = mount_map.get(network_device)
log.debug('nfs share %s already mounted to %s on '
'node %s, skipping...' %
(network_device, mount_path, self.alias))
else:
mount_paths.append(path)
remote_paths = mount_paths
remote_paths_regex = '|'.join(map(lambda x: x.center(len(x) + 2),
remote_paths))
self.ssh.remove_lines_from_file('/etc/fstab', remote_paths_regex)
fstab = self.ssh.remote_file('/etc/fstab', 'a')
mount_opts = 'rw,exec,noauto'
for path in remote_paths:
fstab.write('%s:%s %s nfs %s 0 0\n' %
(server_node.alias, path, path, mount_opts))
fstab.close()
for path in remote_paths:
if not self.ssh.path_exists(path):
self.ssh.makedirs(path)
self.ssh.execute('mount %s' % path)
def get_mount_map(self):
mount_map = {}
mount_lines = self.ssh.execute('mount')
for line in mount_lines:
dev, on_label, path, type_label, fstype, options = line.split()
mount_map[dev] = [path, fstype, options]
return mount_map
def get_device_map(self):
"""
Returns a dictionary mapping devices->(# of blocks) based on
'fdisk -l' and /proc/partitions
"""
dev_regex = '/dev/[A-Za-z0-9/]+'
r = re.compile('Disk (%s):' % dev_regex)
fdiskout = '\n'.join(self.ssh.execute("fdisk -l 2>/dev/null"))
proc_parts = '\n'.join(self.ssh.execute("cat /proc/partitions"))
devmap = {}
for dev in r.findall(fdiskout):
short_name = dev.replace('/dev/', '')
r = re.compile("(\d+)\s+%s(?:\s+|$)" % short_name)
devmap[dev] = int(r.findall(proc_parts)[0])
return devmap
def get_partition_map(self, device=None):
"""
Returns a dictionary mapping partitions->(start, end, blocks, id) based
on 'fdisk -l'
"""
fdiskout = '\n'.join(self.ssh.execute("fdisk -l %s 2>/dev/null" %
(device or '')))
part_regex = '/dev/[A-Za-z0-9/]+'
r = re.compile('(%s)\s+\*?\s+'
'(\d+)(?:[-+])?\s+'
'(\d+)(?:[-+])?\s+'
'(\d+)(?:[-+])?\s+'
'([\da-fA-F][\da-fA-F]?)' % part_regex)
partmap = {}
for match in r.findall(fdiskout):
part, start, end, blocks, sys_id = match
partmap[part] = [int(start), int(end), int(blocks), sys_id]
return partmap
def mount_device(self, device, path):
"""
Mount device to path
"""
self.ssh.remove_lines_from_file('/etc/fstab',
path.center(len(path) + 2))
master_fstab = self.ssh.remote_file('/etc/fstab', mode='a')
master_fstab.write("%s %s auto noauto,defaults 0 0\n" %
(device, path))
master_fstab.close()
if not self.ssh.path_exists(path):
self.ssh.makedirs(path)
self.ssh.execute('mount %s' % path)
def add_to_etc_hosts(self, nodes):
"""
Adds all names for node in nodes arg to this node's /etc/hosts file
"""
self.remove_from_etc_hosts(nodes)
host_file = self.ssh.remote_file('/etc/hosts', 'a')
for node in nodes:
print >> host_file, node.get_hosts_entry()
host_file.close()
def remove_from_etc_hosts(self, nodes):
"""
Remove all network names for node in nodes arg from this node's
/etc/hosts file
"""
aliases = map(lambda x: x.alias, nodes)
self.ssh.remove_lines_from_file('/etc/hosts', '|'.join(aliases))
def set_hostname(self, hostname=None):
"""
Set this node's hostname to self.alias
hostname - optional hostname to set (defaults to self.alias)
"""
hostname = hostname or self.alias
hostname_file = self.ssh.remote_file("/etc/hostname", "w")
hostname_file.write(hostname)
hostname_file.close()
try:
self.ssh.execute('hostname -F /etc/hostname')
except:
if not utils.is_valid_hostname(hostname):
raise exception.InvalidHostname(
"Please terminate and recreate this cluster with a name"
" that is also a valid hostname. This hostname is"
" invalid: %s" % hostname)
else:
raise
@property
def network_names(self):
""" Returns all network names for this node in a dictionary"""
names = {}
names['INTERNAL_IP'] = self.private_ip_address
names['INTERNAL_NAME'] = self.private_dns_name
names['INTERNAL_NAME_SHORT'] = self.private_dns_name_short
names['INTERNAL_ALIAS'] = self.alias
return names
@property
def attached_vols(self):
"""
Returns a dictionary of all attached volumes minus the root device in
the case of EBS backed instances
"""
attached_vols = {}
attached_vols.update(self.block_device_mapping)
if self.is_ebs_backed():
# exclude the root device from the list
root_dev = self.root_device_name
if root_dev in attached_vols:
attached_vols.pop(root_dev)
return attached_vols
def detach_external_volumes(self):
"""
Detaches all volumes returned by self.attached_vols
"""
block_devs = self.attached_vols
for dev in block_devs:
vol_id = block_devs[dev].volume_id
vol = self.ec2.get_volume(vol_id)
log.info("Detaching volume %s from %s" % (vol.id, self.alias))
if vol.status not in ['available', 'detaching']:
vol.detach()
def delete_root_volume(self):
"""
Detach and destroy EBS root volume (EBS-backed node only)
"""
if not self.is_ebs_backed():
return
root_vol = self.block_device_mapping[self.root_device_name]
vol_id = root_vol.volume_id
vol = self.ec2.get_volume(vol_id)
vol.detach()
while vol.update() != 'available':
time.sleep(5)
log.info("Deleting node %s's root volume" % self.alias)
root_vol.delete()
@property
def spot_id(self):
if self.instance.spot_instance_request_id:
return self.instance.spot_instance_request_id
def get_spot_request(self):
spot = self.ec2.get_all_spot_requests(
filters={'spot-instance-request-id': self.spot_id})
if spot:
return spot[0]
def is_master(self):
return self.alias == 'master' or self.alias.endswith("-master")
def is_instance_store(self):
return self.instance.root_device_type == "instance-store"
def is_ebs_backed(self):
return self.instance.root_device_type == "ebs"
def is_cluster_compute(self):
return self.instance.instance_type in static.CLUSTER_COMPUTE_TYPES
def is_gpu_compute(self):
return self.instance.instance_type in static.CLUSTER_GPU_TYPES
def is_cluster_type(self):
return self.instance.instance_type in static.HVM_ONLY_TYPES
def is_spot(self):
return self.spot_id is not None
def is_stoppable(self):
return self.is_ebs_backed() and not self.is_spot()
def is_stopped(self):
return self.state == "stopped"
def start(self):
"""
Starts EBS-backed instance and puts it in the 'running' state.
Only works if this node is EBS-backed, raises
exception.InvalidOperation otherwise.
"""
if not self.is_ebs_backed():
raise exception.InvalidOperation(
"Only EBS-backed instances can be started")
return self.instance.start()
def stop(self):
"""
Shutdown EBS-backed instance and put it in the 'stopped' state.
Only works if this node is EBS-backed, raises
exception.InvalidOperation otherwise.
NOTE: The EBS root device will *not* be deleted and the instance can
be 'started' later on.
"""
if self.is_spot():
raise exception.InvalidOperation(
"spot instances can not be stopped")
elif not self.is_ebs_backed():
raise exception.InvalidOperation(
"Only EBS-backed instances can be stopped")
if not self.is_stopped():
log.info("Stopping node: %s (%s)" % (self.alias, self.id))
return self.instance.stop()
else:
log.info("Node '%s' is already stopped" % self.alias)
def terminate(self):
"""
Shutdown and destroy this instance. For EBS-backed nodes, this
will also destroy the node's EBS root device. Puts this node
into a 'terminated' state.
"""
if self.spot_id:
log.info("Canceling spot request %s" % self.spot_id)
self.get_spot_request().cancel()
log.info("Terminating node: %s (%s)" % (self.alias, self.id))
return self.instance.terminate()
def shutdown(self):
"""
Shutdown this instance. This method will terminate traditional
instance-store instances and stop EBS-backed instances
(i.e. not destroy EBS root dev)
"""
if self.is_stoppable():
self.stop()
else:
self.terminate()
def reboot(self):
"""
Reboot this instance.
"""
self.instance.reboot()
def is_ssh_up(self):
try:
return self.ssh.transport is not None
except exception.SSHError:
return False
except socket.error:
log.warning("error encountered while checking if {} is up:"
.format(self.alias), exc_info=True)
return False
def wait(self, interval=30):
while not self.is_up():
time.sleep(interval)
def is_up(self):
if self.update() != 'running':
return False
if not self.is_ssh_up():
return False
if self.private_ip_address is None:
log.debug("instance %s has no private_ip_address" % self.id)
log.debug("attempting to determine private_ip_address for "
"instance %s" % self.id)
try:
private_ip = self.ssh.execute(
'python -c '
'"import socket; print socket.gethostbyname(\'%s\')"' %
self.private_dns_name)[0].strip()
log.debug("determined instance %s's private ip to be %s" %
(self.id, private_ip))
self.instance.private_ip_address = private_ip
except Exception, e:
print e
return False
return True
def update(self):
res = self.ec2.get_all_instances(filters={'instance-id': self.id})
self.instance = res[0]
return self.state
@property
def addr(self):
"""
Returns the most widely accessible address for the instance. This
property first checks if dns_name is available, then the public ip, and
finally the private ip. If none of these addresses are available it
returns None.
"""
if not self.dns_name:
if self.ip_address:
return self.ip_address
else:
return self.private_ip_address
else:
return self.dns_name
@property
def ssh(self):
if not self._ssh:
self._ssh = sshutils.SSHClient(self.addr,
username=self.user,
private_key=self.key_location)
return self._ssh
def shell(self, user=None, forward_x11=False, forward_agent=False,
pseudo_tty=False, command=None):
"""
Attempts to launch an interactive shell by first trying the system's
ssh client. If the system does not have the ssh command it falls back
to a pure-python ssh shell.
"""
if self.update() != 'running':
try:
alias = self.alias
except exception.BaseException:
alias = None
label = 'instance'
if alias == "master":
label = "master"
alias = "node"
elif alias:
label = "node"
instance_id = alias or self.id
raise exception.InstanceNotRunning(instance_id, self.state,
label=label)
user = user or self.user
if utils.has_required(['ssh']):
log.debug("Using native OpenSSH client")
sshopts = '-i %s' % self.key_location
if forward_x11:
sshopts += ' -Y'
if forward_agent:
sshopts += ' -A'
if pseudo_tty:
sshopts += ' -t'
ssh_cmd = static.SSH_TEMPLATE % dict(opts=sshopts, user=user,
host=self.addr)
if command:
command = "'source /etc/profile && %s'" % command
ssh_cmd = ' '.join([ssh_cmd, command])
log.debug("ssh_cmd: %s" % ssh_cmd)
return subprocess.call(ssh_cmd, shell=True)
else:
log.debug("Using Pure-Python SSH client")
if forward_x11:
log.warn("X11 Forwarding not available in Python SSH client")
if forward_agent:
log.warn("Authentication agent forwarding not available in " +
"Python SSH client")
if pseudo_tty:
log.warn("Pseudo-tty allocation is not available in " +
"Python SSH client")
if command:
orig_user = self.ssh.get_current_user()
self.ssh.switch_user(user)
self.ssh.execute(command, silent=False)
self.ssh.switch_user(orig_user)
return self.ssh.get_last_status()
self.ssh.interactive_shell(user=user)
def get_hosts_entry(self):
""" Returns /etc/hosts entry for this node """
etc_hosts_line = "%(INTERNAL_IP)s %(INTERNAL_ALIAS)s"
etc_hosts_line = etc_hosts_line % self.network_names
return etc_hosts_line
def apt_command(self, cmd):
"""
Run an apt-get command with all the necessary options for
non-interactive use (DEBIAN_FRONTEND=interactive, -y, --force-yes, etc)
"""
dpkg_opts = "Dpkg::Options::='--force-confnew'"
cmd = "apt-get -o %s -y --force-yes %s" % (dpkg_opts, cmd)
cmd = "DEBIAN_FRONTEND='noninteractive' " + cmd
self.ssh.execute(cmd)
def apt_install(self, pkgs):
"""
Install a set of packages via apt-get.
pkgs is a string that contains one or more packages separated by a
space
"""
self.apt_command('update')
self.apt_command('install %s' % pkgs)
def yum_command(self, cmd):
"""
Run a yum command with all necessary options for non-interactive use.
"-d 0 -e 0 -y"
"""
yum_opts = ['-d', '0', '-e', '0', '-y']
cmd = "yum " + " ".join(yum_opts) + " " + cmd
self.ssh.execute(cmd)
def yum_install(self, pkgs):
"""
Install a set of packages via yum.
pkgs is a string that contains one or more packages separated by a
space
"""
self.yum_command('install %s' % pkgs)
@property
def package_provider(self):
"""
In order to determine which packaging system to use, check to see if
/usr/bin/apt exists on the node, and use apt if it exists. Otherwise
test to see if /usr/bin/yum exists and use that.
"""
if self.ssh.isfile('/usr/bin/apt-get'):
return "apt"
elif self.ssh.isfile('/usr/bin/yum'):
return "yum"
def package_install(self, pkgs):
"""
Provides a declarative install packages on systems, regardless
of the system's packging type (apt/yum).
"""
if self.package_provider == "apt":
self.apt_install(pkgs)
elif self.package_provider == "yum":
self.yum_install(pkgs)
def __del__(self):
if self._ssh:
self._ssh.close()
| gpl-3.0 |
oostende/dvbapp2-gui-egami | lib/python/Components/PackageInfo.py | 52 | 12835 | import xml.sax
from Tools.Directories import crawlDirectory, resolveFilename, SCOPE_CONFIG, SCOPE_SKIN, copyfile, copytree
from Components.NimManager import nimmanager
from Components.Ipkg import IpkgComponent
from Components.config import config, configfile
from boxbranding import getBoxType
from enigma import eConsoleAppContainer, eDVBDB
import os
class InfoHandlerParseError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class InfoHandler(xml.sax.ContentHandler):
def __init__(self, prerequisiteMet, directory):
self.attributes = {}
self.directory = directory
self.list = []
self.globalprerequisites = {}
self.prerequisites = {}
self.elements = []
self.validFileTypes = ["skin", "config", "services", "favourites", "package"]
self.prerequisitesMet = prerequisiteMet
self.data = ""
def printError(self, error):
raise InfoHandlerParseError, error
def startElement(self, name, attrs):
self.elements.append(name)
if name in ("hardware", "bcastsystem", "satellite", "tag", "flag"):
if not attrs.has_key("type"):
self.printError(str(name) + " tag with no type attribute")
if self.elements[-3] in ("default", "package"):
prerequisites = self.globalprerequisites
else:
prerequisites = self.prerequisites
if not prerequisites.has_key(name):
prerequisites[name] = []
prerequisites[name].append(str(attrs["type"]))
if name == "info":
self.foundTranslation = None
self.data = ""
if name == "files":
if attrs.has_key("type"):
if attrs["type"] == "directories":
self.attributes["filestype"] = "directories"
elif attrs["type"] == "package":
self.attributes["filestype"] = "package"
if name == "file":
self.prerequisites = {}
if not attrs.has_key("type"):
self.printError("file tag with no type attribute")
else:
if not attrs.has_key("name"):
self.printError("file tag with no name attribute")
else:
if not attrs.has_key("directory"):
directory = self.directory
type = attrs["type"]
if not type in self.validFileTypes:
self.printError("file tag with invalid type attribute")
else:
self.filetype = type
self.fileattrs = attrs
if name == "package":
if attrs.has_key("details"):
self.attributes["details"] = str(attrs["details"])
if attrs.has_key("name"):
self.attributes["name"] = str(attrs["name"])
if attrs.has_key("packagename"):
self.attributes["packagename"] = str(attrs["packagename"])
if attrs.has_key("packagetype"):
self.attributes["packagetype"] = str(attrs["packagetype"])
if attrs.has_key("needsRestart"):
self.attributes["needsRestart"] = str(attrs["needsRestart"])
if attrs.has_key("shortdescription"):
self.attributes["shortdescription"] = str(attrs["shortdescription"])
if name == "screenshot":
if attrs.has_key("src"):
self.attributes["screenshot"] = str(attrs["src"])
def endElement(self, name):
self.elements.pop()
if name == "file":
if len(self.prerequisites) == 0 or self.prerequisitesMet(self.prerequisites):
if not self.attributes.has_key(self.filetype):
self.attributes[self.filetype] = []
if self.fileattrs.has_key("directory"):
directory = str(self.fileattrs["directory"])
if len(directory) < 1 or directory[0] != "/":
directory = self.directory + directory
else:
directory = self.directory
self.attributes[self.filetype].append({ "name": str(self.fileattrs["name"]), "directory": directory })
if name in ( "default", "package" ):
self.list.append({"attributes": self.attributes, 'prerequisites': self.globalprerequisites})
self.attributes = {}
self.globalprerequisites = {}
def characters(self, data):
if self.elements[-1] == "author":
self.attributes["author"] = str(data)
if self.elements[-1] == "name":
self.attributes["name"] = str(data)
if self.elements[-1] == "packagename":
self.attributes["packagename"] = str(data)
if self.elements[-1] == "needsRestart":
self.attributes["needsRestart"] = str(data)
if self.elements[-1] == "shortdescription":
self.attributes["shortdescription"] = str(data)
if self.elements[-1] == "description":
self.data += data.strip()
self.attributes["description"] = str(self.data)
class PackageInfoHandler:
STATUS_WORKING = 0
STATUS_DONE = 1
STATUS_ERROR = 2
STATUS_INIT = 4
def __init__(self, statusCallback, blocking = False, neededTag = None, neededFlag = None):
self.directory = "/"
self.neededTag = neededTag
self.neededFlag = neededFlag
# caution: blocking should only be used, if further execution in enigma2 depends on the outcome of
# the installer!
self.blocking = blocking
self.currentlyInstallingMetaIndex = None
self.console = eConsoleAppContainer()
self.console.appClosed.append(self.installNext)
self.reloadFavourites = False
self.statusCallback = statusCallback
self.setStatus(self.STATUS_INIT)
self.packageslist = []
self.packagesIndexlist = []
self.packageDetails = []
def readInfo(self, directory, file):
handler = InfoHandler(self.prerequisiteMet, directory)
try:
xml.sax.parse(file, handler)
for entry in handler.list:
self.packageslist.append((entry,file))
except InfoHandlerParseError:
pass
def readIndex(self, directory, file):
handler = InfoHandler(self.prerequisiteMet, directory)
try:
xml.sax.parse(file, handler)
for entry in handler.list:
self.packagesIndexlist.append((entry,file))
except InfoHandlerParseError:
pass
def readDetails(self, directory, file):
self.packageDetails = []
handler = InfoHandler(self.prerequisiteMet, directory)
try:
xml.sax.parse(file, handler)
for entry in handler.list:
self.packageDetails.append((entry,file))
except InfoHandlerParseError:
pass
def fillPackagesList(self, prerequisites = True):
self.packageslist = []
packages = []
if not isinstance(self.directory, list):
self.directory = [self.directory]
for directory in self.directory:
packages += crawlDirectory(directory, ".*\.info$")
for package in packages:
self.readInfo(package[0] + "/", package[0] + "/" + package[1])
if prerequisites:
for package in self.packageslist[:]:
if not self.prerequisiteMet(package[0]["prerequisites"]):
self.packageslist.remove(package)
return self.packageslist
def fillPackagesIndexList(self, prerequisites = True):
self.packagesIndexlist = []
indexfileList = []
if not isinstance(self.directory, list):
self.directory = [self.directory]
for indexfile in os.listdir(self.directory[0]):
if indexfile.startswith("index-"):
if indexfile.endswith(".xml"):
if indexfile[-7:-6] == "_":
continue
indexfileList.append(indexfile)
if len(indexfileList):
for file in indexfileList:
neededFile = self.directory[0] + "/" + file
if os.path.isfile(neededFile):
self.readIndex(self.directory[0] + "/" , neededFile)
if prerequisites:
for package in self.packagesIndexlist[:]:
if not self.prerequisiteMet(package[0]["prerequisites"]):
self.packagesIndexlist.remove(package)
return self.packagesIndexlist
def fillPackageDetails(self, details = None):
self.packageDetails = []
detailsfile = details
if not isinstance(self.directory, list):
self.directory = [self.directory]
self.readDetails(self.directory[0] + "/", self.directory[0] + "/" + detailsfile)
return self.packageDetails
def prerequisiteMet(self, prerequisites):
met = True
if self.neededTag is None:
if prerequisites.has_key("tag"):
return False
elif self.neededTag == 'ALL_TAGS':
return True
else:
if prerequisites.has_key("tag"):
if not self.neededTag in prerequisites["tag"]:
return False
else:
return False
if self.neededFlag is None:
if prerequisites.has_key("flag"):
return False
else:
if prerequisites.has_key("flag"):
if not self.neededFlag in prerequisites["flag"]:
return False
else:
return True
if prerequisites.has_key("satellite"):
for sat in prerequisites["satellite"]:
if int(sat) not in nimmanager.getConfiguredSats():
return False
if prerequisites.has_key("bcastsystem"):
has_system = False
for bcastsystem in prerequisites["bcastsystem"]:
if nimmanager.hasNimType(bcastsystem):
has_system = True
if not has_system:
return False
if prerequisites.has_key("hardware"):
hardware_found = False
for hardware in prerequisites["hardware"]:
if hardware == getBoxType():
hardware_found = True
if not hardware_found:
return False
return True
def installPackages(self, indexes):
if len(indexes) == 0:
self.setStatus(self.STATUS_DONE)
return
self.installIndexes = indexes
self.currentlyInstallingMetaIndex = 0
self.installPackage(self.installIndexes[self.currentlyInstallingMetaIndex])
def installPackage(self, index):
if len(self.packageslist) <= index:
return
attributes = self.packageslist[index][0]["attributes"]
self.installingAttributes = attributes
self.attributeNames = ["skin", "config", "favourites", "package", "services"]
self.currentAttributeIndex = 0
self.currentIndex = -1
self.installNext()
def setStatus(self, status):
self.status = status
self.statusCallback(self.status, None)
def installNext(self, *args, **kwargs):
if self.reloadFavourites:
self.reloadFavourites = False
db = eDVBDB.getInstance().reloadBouquets()
self.currentIndex += 1
attributes = self.installingAttributes
if self.currentAttributeIndex >= len(self.attributeNames):
if self.currentlyInstallingMetaIndex is None or self.currentlyInstallingMetaIndex >= len(self.installIndexes) - 1:
self.setStatus(self.STATUS_DONE)
return
else:
self.currentlyInstallingMetaIndex += 1
self.currentAttributeIndex = 0
self.installPackage(self.installIndexes[self.currentlyInstallingMetaIndex])
return
self.setStatus(self.STATUS_WORKING)
currentAttribute = self.attributeNames[self.currentAttributeIndex]
if attributes.has_key(currentAttribute):
if self.currentIndex >= len(attributes[currentAttribute]):
self.currentIndex = -1
self.currentAttributeIndex += 1
self.installNext()
return
else:
self.currentIndex = -1
self.currentAttributeIndex += 1
self.installNext()
return
if currentAttribute == "skin":
skin = attributes["skin"][self.currentIndex]
self.installSkin(skin["directory"], skin["name"])
elif currentAttribute == "config":
if self.currentIndex == 0:
from Components.config import configfile
configfile.save()
config = attributes["config"][self.currentIndex]
self.mergeConfig(config["directory"], config["name"])
elif currentAttribute == "favourites":
favourite = attributes["favourites"][self.currentIndex]
self.installFavourites(favourite["directory"], favourite["name"])
elif currentAttribute == "package":
package = attributes["package"][self.currentIndex]
self.installIPK(package["directory"], package["name"])
elif currentAttribute == "services":
service = attributes["services"][self.currentIndex]
self.mergeServices(service["directory"], service["name"])
def readfile(self, filename):
if not os.path.isfile(filename):
return []
fd = open(filename)
lines = fd.readlines()
fd.close()
return lines
def mergeConfig(self, directory, name, merge = True):
if os.path.isfile(directory + name):
config.loadFromFile(directory + name, base_file=False)
configfile.save()
self.installNext()
def installIPK(self, directory, name):
if self.blocking:
os.system("opkg install " + directory + name)
self.installNext()
else:
self.ipkg = IpkgComponent()
self.ipkg.addCallback(self.ipkgCallback)
self.ipkg.startCmd(IpkgComponent.CMD_INSTALL, {'package': directory + name})
def ipkgCallback(self, event, param):
if event == IpkgComponent.EVENT_DONE:
self.installNext()
elif event == IpkgComponent.EVENT_ERROR:
self.installNext()
def installSkin(self, directory, name):
if self.blocking:
copytree(directory, resolveFilename(SCOPE_SKIN))
self.installNext()
else:
if self.console.execute("cp -a %s %s" % (directory, resolveFilename(SCOPE_SKIN))):
self.installNext()
def mergeServices(self, directory, name, merge = False):
if os.path.isfile(directory + name):
db = eDVBDB.getInstance()
db.reloadServicelist()
db.loadServicelist(directory + name)
db.saveServicelist()
self.installNext()
def installFavourites(self, directory, name):
self.reloadFavourites = True
if self.blocking:
copyfile(directory + name, resolveFilename(SCOPE_CONFIG))
self.installNext()
else:
if self.console.execute("cp %s %s" % ((directory + name), resolveFilename(SCOPE_CONFIG))):
self.installNext()
| gpl-2.0 |
dsanders11/easypost-python | examples/carrier_account.py | 2 | 1195 | import easypost
easypost.api_key = 'PRODUCTION API KEY'
original_num_cas = len(easypost.CarrierAccount.all())
created_ca = easypost.CarrierAccount.create(
type="UpsAccount",
description="A test Ups Account",
reference="PythonClientUpsTestAccount",
credentials={
"account_number": "A1A1A1",
"user_id": "UPSDOTCOM_USERNAME",
"password": "UPSDOTCOM_PASSWORD",
"access_license_number": "UPS_ACCESS_LICENSE_NUMBER"})
caid = created_ca["id"]
retrieved_ca = easypost.CarrierAccount.retrieve(caid)
retrieved_ca.description = "An updated description for a test Ups Account"
retrieved_ca.credentials = {
"account_number": "B2B2B2B2",
"user_id": "UPSDOTCOM_USERNAME",
"password": "UPSDOTCOM_PASSWORD",
"access_license_number": "UPS_ACCESS_LICENSE_NUMBER"
}
retrieved_ca.save()
updated_ca = easypost.CarrierAccount.retrieve(caid)
updated_ca.credentials["account_number"] = "C3C3C3C3C3"
updated_ca.credentials["user_id"] = "A_NEW_UPS_USERNAME"
updated_ca.save()
reupdated_ca = easypost.CarrierAccount.retrieve(caid)
# You can call save() with no unsaved changes, but it does nothing
final_ca = reupdated_ca.save()
final_ca.delete()
| mit |
bottompawn/kbengine | kbe/src/lib/python/Lib/email/mime/text.py | 83 | 1367 | # Copyright (C) 2001-2006 Python Software Foundation
# Author: Barry Warsaw
# Contact: email-sig@python.org
"""Class representing text/* type MIME documents."""
__all__ = ['MIMEText']
from email.mime.nonmultipart import MIMENonMultipart
class MIMEText(MIMENonMultipart):
"""Class for generating text/* type MIME documents."""
def __init__(self, _text, _subtype='plain', _charset=None):
"""Create a text/* type MIME document.
_text is the string for this message object.
_subtype is the MIME sub content type, defaulting to "plain".
_charset is the character set parameter added to the Content-Type
header. This defaults to "us-ascii". Note that as a side-effect, the
Content-Transfer-Encoding header will also be set.
"""
# If no _charset was specified, check to see if there are non-ascii
# characters present. If not, use 'us-ascii', otherwise use utf-8.
# XXX: This can be removed once #7304 is fixed.
if _charset is None:
try:
_text.encode('us-ascii')
_charset = 'us-ascii'
except UnicodeEncodeError:
_charset = 'utf-8'
MIMENonMultipart.__init__(self, 'text', _subtype,
**{'charset': _charset})
self.set_payload(_text, _charset)
| lgpl-3.0 |
Tehsmash/nova | nova/volume/encryptors/luks.py | 28 | 5164 | # Copyright (c) 2013 The Johns Hopkins University/Applied Physics Laboratory
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_concurrency import processutils
from oslo_log import log as logging
from nova.i18n import _LI
from nova.i18n import _LW
from nova import utils
from nova.volume.encryptors import cryptsetup
LOG = logging.getLogger(__name__)
def is_luks(device):
"""Checks if the specified device uses LUKS for encryption.
:param device: the device to check
:returns: true if the specified device uses LUKS; false otherwise
"""
try:
# check to see if the device uses LUKS: exit status is 0
# if the device is a LUKS partition and non-zero if not
utils.execute('cryptsetup', 'isLuks', '--verbose', device,
run_as_root=True, check_exit_code=True)
return True
except processutils.ProcessExecutionError as e:
LOG.warning(_LW("isLuks exited abnormally (status %(exit_code)s): "
"%(stderr)s"),
{"exit_code": e.exit_code, "stderr": e.stderr})
return False
class LuksEncryptor(cryptsetup.CryptsetupEncryptor):
"""A VolumeEncryptor based on LUKS.
This VolumeEncryptor uses dm-crypt to encrypt the specified volume.
"""
def __init__(self, connection_info, **kwargs):
super(LuksEncryptor, self).__init__(connection_info, **kwargs)
def _format_volume(self, passphrase, **kwargs):
"""Creates a LUKS header on the volume.
:param passphrase: the passphrase used to access the volume
"""
LOG.debug("formatting encrypted volume %s", self.dev_path)
# NOTE(joel-coffman): cryptsetup will strip trailing newlines from
# input specified on stdin unless --key-file=- is specified.
cmd = ["cryptsetup", "--batch-mode", "luksFormat", "--key-file=-"]
cipher = kwargs.get("cipher", None)
if cipher is not None:
cmd.extend(["--cipher", cipher])
key_size = kwargs.get("key_size", None)
if key_size is not None:
cmd.extend(["--key-size", key_size])
cmd.extend([self.dev_path])
utils.execute(*cmd, process_input=passphrase,
check_exit_code=True, run_as_root=True)
def _open_volume(self, passphrase, **kwargs):
"""Opens the LUKS partition on the volume using the specified
passphrase.
:param passphrase: the passphrase used to access the volume
"""
LOG.debug("opening encrypted volume %s", self.dev_path)
utils.execute('cryptsetup', 'luksOpen', '--key-file=-',
self.dev_path, self.dev_name, process_input=passphrase,
run_as_root=True, check_exit_code=True)
def attach_volume(self, context, **kwargs):
"""Shadows the device and passes an unencrypted version to the
instance.
Transparent disk encryption is achieved by mounting the volume via
dm-crypt and passing the resulting device to the instance. The
instance is unaware of the underlying encryption due to modifying the
original symbolic link to refer to the device mounted by dm-crypt.
"""
key = self._get_key(context).get_encoded()
# LUKS uses a passphrase rather than a raw key -- convert to string
passphrase = ''.join(hex(x).replace('0x', '') for x in key)
try:
self._open_volume(passphrase, **kwargs)
except processutils.ProcessExecutionError as e:
if e.exit_code == 1 and not is_luks(self.dev_path):
# the device has never been formatted; format it and try again
LOG.info(_LI("%s is not a valid LUKS device;"
" formatting device for first use"),
self.dev_path)
self._format_volume(passphrase, **kwargs)
self._open_volume(passphrase, **kwargs)
else:
raise
# modify the original symbolic link to refer to the decrypted device
utils.execute('ln', '--symbolic', '--force',
'/dev/mapper/%s' % self.dev_name, self.symlink_path,
run_as_root=True, check_exit_code=True)
def _close_volume(self, **kwargs):
"""Closes the device (effectively removes the dm-crypt mapping)."""
LOG.debug("closing encrypted volume %s", self.dev_path)
utils.execute('cryptsetup', 'luksClose', self.dev_name,
run_as_root=True, check_exit_code=True,
attempts=3)
| apache-2.0 |
MebiusHKU/flask-web | flask/lib/python2.7/site-packages/wtforms/ext/django/fields.py | 175 | 4580 | """
Useful form fields for use with the Django ORM.
"""
from __future__ import unicode_literals
import datetime
import operator
try:
from django.conf import settings
from django.utils import timezone
has_timezone = True
except ImportError:
has_timezone = False
from wtforms import fields, widgets
from wtforms.compat import string_types
from wtforms.validators import ValidationError
__all__ = (
'ModelSelectField', 'QuerySetSelectField', 'DateTimeField'
)
class QuerySetSelectField(fields.SelectFieldBase):
"""
Given a QuerySet either at initialization or inside a view, will display a
select drop-down field of choices. The `data` property actually will
store/keep an ORM model instance, not the ID. Submitting a choice which is
not in the queryset will result in a validation error.
Specify `get_label` to customize the label associated with each option. If
a string, this is the name of an attribute on the model object to use as
the label text. If a one-argument callable, this callable will be passed
model instance and expected to return the label text. Otherwise, the model
object's `__str__` or `__unicode__` will be used.
If `allow_blank` is set to `True`, then a blank choice will be added to the
top of the list. Selecting this choice will result in the `data` property
being `None`. The label for the blank choice can be set by specifying the
`blank_text` parameter.
"""
widget = widgets.Select()
def __init__(self, label=None, validators=None, queryset=None, get_label=None, allow_blank=False, blank_text='', **kwargs):
super(QuerySetSelectField, self).__init__(label, validators, **kwargs)
self.allow_blank = allow_blank
self.blank_text = blank_text
self._set_data(None)
if queryset is not None:
self.queryset = queryset.all() # Make sure the queryset is fresh
if get_label is None:
self.get_label = lambda x: x
elif isinstance(get_label, string_types):
self.get_label = operator.attrgetter(get_label)
else:
self.get_label = get_label
def _get_data(self):
if self._formdata is not None:
for obj in self.queryset:
if obj.pk == self._formdata:
self._set_data(obj)
break
return self._data
def _set_data(self, data):
self._data = data
self._formdata = None
data = property(_get_data, _set_data)
def iter_choices(self):
if self.allow_blank:
yield ('__None', self.blank_text, self.data is None)
for obj in self.queryset:
yield (obj.pk, self.get_label(obj), obj == self.data)
def process_formdata(self, valuelist):
if valuelist:
if valuelist[0] == '__None':
self.data = None
else:
self._data = None
self._formdata = int(valuelist[0])
def pre_validate(self, form):
if not self.allow_blank or self.data is not None:
for obj in self.queryset:
if self.data == obj:
break
else:
raise ValidationError(self.gettext('Not a valid choice'))
class ModelSelectField(QuerySetSelectField):
"""
Like a QuerySetSelectField, except takes a model class instead of a
queryset and lists everything in it.
"""
def __init__(self, label=None, validators=None, model=None, **kwargs):
super(ModelSelectField, self).__init__(label, validators, queryset=model._default_manager.all(), **kwargs)
class DateTimeField(fields.DateTimeField):
"""
Adds support for Django's timezone utilities.
Requires Django >= 1.5
"""
def __init__(self, *args, **kwargs):
if not has_timezone:
raise ImportError('DateTimeField requires Django >= 1.5')
super(DateTimeField, self).__init__(*args, **kwargs)
def process_formdata(self, valuelist):
super(DateTimeField, self).process_formdata(valuelist)
date = self.data
if settings.USE_TZ and date is not None and timezone.is_naive(date):
current_timezone = timezone.get_current_timezone()
self.data = timezone.make_aware(date, current_timezone)
def _value(self):
date = self.data
if settings.USE_TZ and isinstance(date, datetime.datetime) and timezone.is_aware(date):
self.data = timezone.localtime(date)
return super(DateTimeField, self)._value()
| bsd-3-clause |
fards/ainol_elfii_common | tools/perf/scripts/python/Perf-Trace-Util/lib/Perf/Trace/Core.py | 11088 | 3246 | # Core.py - Python extension for perf script, core functions
#
# Copyright (C) 2010 by Tom Zanussi <tzanussi@gmail.com>
#
# This software may be distributed under the terms of the GNU General
# Public License ("GPL") version 2 as published by the Free Software
# Foundation.
from collections import defaultdict
def autodict():
return defaultdict(autodict)
flag_fields = autodict()
symbolic_fields = autodict()
def define_flag_field(event_name, field_name, delim):
flag_fields[event_name][field_name]['delim'] = delim
def define_flag_value(event_name, field_name, value, field_str):
flag_fields[event_name][field_name]['values'][value] = field_str
def define_symbolic_field(event_name, field_name):
# nothing to do, really
pass
def define_symbolic_value(event_name, field_name, value, field_str):
symbolic_fields[event_name][field_name]['values'][value] = field_str
def flag_str(event_name, field_name, value):
string = ""
if flag_fields[event_name][field_name]:
print_delim = 0
keys = flag_fields[event_name][field_name]['values'].keys()
keys.sort()
for idx in keys:
if not value and not idx:
string += flag_fields[event_name][field_name]['values'][idx]
break
if idx and (value & idx) == idx:
if print_delim and flag_fields[event_name][field_name]['delim']:
string += " " + flag_fields[event_name][field_name]['delim'] + " "
string += flag_fields[event_name][field_name]['values'][idx]
print_delim = 1
value &= ~idx
return string
def symbol_str(event_name, field_name, value):
string = ""
if symbolic_fields[event_name][field_name]:
keys = symbolic_fields[event_name][field_name]['values'].keys()
keys.sort()
for idx in keys:
if not value and not idx:
string = symbolic_fields[event_name][field_name]['values'][idx]
break
if (value == idx):
string = symbolic_fields[event_name][field_name]['values'][idx]
break
return string
trace_flags = { 0x00: "NONE", \
0x01: "IRQS_OFF", \
0x02: "IRQS_NOSUPPORT", \
0x04: "NEED_RESCHED", \
0x08: "HARDIRQ", \
0x10: "SOFTIRQ" }
def trace_flag_str(value):
string = ""
print_delim = 0
keys = trace_flags.keys()
for idx in keys:
if not value and not idx:
string += "NONE"
break
if idx and (value & idx) == idx:
if print_delim:
string += " | ";
string += trace_flags[idx]
print_delim = 1
value &= ~idx
return string
def taskState(state):
states = {
0 : "R",
1 : "S",
2 : "D",
64: "DEAD"
}
if state not in states:
return "Unknown"
return states[state]
class EventHeaders:
def __init__(self, common_cpu, common_secs, common_nsecs,
common_pid, common_comm):
self.cpu = common_cpu
self.secs = common_secs
self.nsecs = common_nsecs
self.pid = common_pid
self.comm = common_comm
def ts(self):
return (self.secs * (10 ** 9)) + self.nsecs
def ts_format(self):
return "%d.%d" % (self.secs, int(self.nsecs / 1000))
| gpl-2.0 |
GauravSahu/odoo | addons/analytic/__openerp__.py | 302 | 1891 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name' : 'Analytic Accounting',
'version': '1.1',
'author' : 'OpenERP SA',
'website' : 'https://www.odoo.com/page/accounting',
'category': 'Hidden/Dependency',
'depends' : ['base', 'decimal_precision', 'mail'],
'description': """
Module for defining analytic accounting object.
===============================================
In OpenERP, analytic accounts are linked to general accounts but are treated
totally independently. So, you can enter various different analytic operations
that have no counterpart in the general financial accounts.
""",
'data': [
'security/analytic_security.xml',
'security/ir.model.access.csv',
'analytic_sequence.xml',
'analytic_view.xml',
'analytic_data.xml',
],
'demo': [],
'installable': True,
'auto_install': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
jeremiedecock/snippets | python/itertools/combinations.py | 1 | 1588 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2012 Jérémie DECOCK (http://www.jdhp.org)
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import itertools
def main():
"""Main function"""
# All possible permutations
# combinations(iterable, r) --> combinations object
#
# Return successive r-length combinations of elements in the iterable.
# combinations(range(4), 3) --> (0,1,2), (0,1,3), (0,2,3), (1,2,3)
for combination in itertools.combinations(range(4), 3):
print(combination)
if __name__ == '__main__':
main()
| mit |
Frederikssund/QGIS-impact-analysis | ImpactAnalysis2/test/test_init.py | 121 | 1860 | # coding=utf-8
"""Tests QGIS plugin init."""
__author__ = 'Tim Sutton <tim@linfiniti.com>'
__revision__ = '$Format:%H$'
__date__ = '17/10/2010'
__license__ = "GPL"
__copyright__ = 'Copyright 2012, Australia Indonesia Facility for '
__copyright__ += 'Disaster Reduction'
import os
import unittest
import logging
import ConfigParser
LOGGER = logging.getLogger('QGIS')
class TestInit(unittest.TestCase):
"""Test that the plugin init is usable for QGIS.
Based heavily on the validator class by Alessandro
Passoti available here:
http://github.com/qgis/qgis-django/blob/master/qgis-app/
plugins/validator.py
"""
def test_read_init(self):
"""Test that the plugin __init__ will validate on plugins.qgis.org."""
# You should update this list according to the latest in
# https://github.com/qgis/qgis-django/blob/master/qgis-app/
# plugins/validator.py
required_metadata = [
'name',
'description',
'version',
'qgisMinimumVersion',
'email',
'author']
file_path = os.path.abspath(os.path.join(
os.path.dirname(__file__), os.pardir,
'metadata.txt'))
LOGGER.info(file_path)
metadata = []
parser = ConfigParser.ConfigParser()
parser.optionxform = str
parser.read(file_path)
message = 'Cannot find a section named "general" in %s' % file_path
assert parser.has_section('general'), message
metadata.extend(parser.items('general'))
for expectation in required_metadata:
message = ('Cannot find metadata "%s" in metadata source (%s).' % (
expectation, file_path))
self.assertIn(expectation, dict(metadata), message)
if __name__ == '__main__':
unittest.main()
| gpl-3.0 |
microcom/odoo | openerp/report/render/html2html/html2html.py | 49 | 3282 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from openerp.report.render.rml2pdf import utils
import copy
import base64
import cStringIO
import re
from reportlab.lib.utils import ImageReader
_regex = re.compile('\[\[(.+?)\]\]')
utils._regex = re.compile('\[\[\s*(.+?)\s*\]\]',re.DOTALL)
class html2html(object):
def __init__(self, html, localcontext):
self.localcontext = localcontext
self.etree = html
self._node = None
def render(self):
def process_text(node,new_node):
if new_node.tag in ['story','tr','section']:
new_node.attrib.clear()
for child in utils._child_get(node, self):
new_child = copy.deepcopy(child)
new_node.append(new_child)
if len(child):
for n in new_child:
new_child.text = utils._process_text(self, child.text)
new_child.tail = utils._process_text(self, child.tail)
new_child.remove(n)
process_text(child, new_child)
else:
if new_child.tag=='img' and new_child.get('name'):
if _regex.findall(new_child.get('name')) :
src = utils._process_text(self, new_child.get('name'))
if src :
new_child.set('src','data:image/gif;base64,%s'%src)
output = cStringIO.StringIO(base64.decodestring(src))
img = ImageReader(output)
(width,height) = img.getSize()
if not new_child.get('width'):
new_child.set('width',str(width))
if not new_child.get('height') :
new_child.set('height',str(height))
else :
new_child.getparent().remove(new_child)
new_child.text = utils._process_text(self, child.text)
new_child.tail = utils._process_text(self, child.tail)
self._node = copy.deepcopy(self.etree)
for n in self._node:
self._node.remove(n)
process_text(self.etree, self._node)
return self._node
def url_modify(self,root):
for n in root:
if (n.text.find('<a ')>=0 or n.text.find('<a')>=0) and n.text.find('href')>=0 and n.text.find('style')<=0 :
node = (n.tag=='span' and n.getparent().tag=='u') and n.getparent().getparent() or ((n.tag=='span') and n.getparent()) or n
style = node.get('color') and "style='color:%s; text-decoration: none;'"%node.get('color') or ''
if n.text.find('<a')>=0:
t = '<a '
else :
t = '<a '
href = n.text.split(t)[-1]
n.text = ' '.join([t,style,href])
self.url_modify(n)
return root
def parseString(node, localcontext = {}):
r = html2html(node, localcontext)
root = r.render()
root = r.url_modify(root)
return root
| agpl-3.0 |
slightlymadphoenix/activityPointsApp | activitypoints/lib/python3.5/site-packages/django/db/models/fields/related.py | 45 | 71660 | from __future__ import unicode_literals
import inspect
import warnings
from functools import partial
from django import forms
from django.apps import apps
from django.core import checks, exceptions
from django.db import connection, router
from django.db.backends import utils
from django.db.models import Q
from django.db.models.constants import LOOKUP_SEP
from django.db.models.deletion import CASCADE, SET_DEFAULT, SET_NULL
from django.db.models.query_utils import PathInfo
from django.db.models.utils import make_model_tuple
from django.utils import six
from django.utils.deprecation import RemovedInDjango20Warning
from django.utils.encoding import force_text
from django.utils.functional import cached_property, curry
from django.utils.lru_cache import lru_cache
from django.utils.translation import ugettext_lazy as _
from django.utils.version import get_docs_version
from . import Field
from .related_descriptors import (
ForwardManyToOneDescriptor, ForwardOneToOneDescriptor,
ManyToManyDescriptor, ReverseManyToOneDescriptor,
ReverseOneToOneDescriptor,
)
from .related_lookups import (
RelatedExact, RelatedGreaterThan, RelatedGreaterThanOrEqual, RelatedIn,
RelatedIsNull, RelatedLessThan, RelatedLessThanOrEqual,
)
from .reverse_related import (
ForeignObjectRel, ManyToManyRel, ManyToOneRel, OneToOneRel,
)
RECURSIVE_RELATIONSHIP_CONSTANT = 'self'
def resolve_relation(scope_model, relation):
"""
Transform relation into a model or fully-qualified model string of the form
"app_label.ModelName", relative to scope_model.
The relation argument can be:
* RECURSIVE_RELATIONSHIP_CONSTANT, i.e. the string "self", in which case
the model argument will be returned.
* A bare model name without an app_label, in which case scope_model's
app_label will be prepended.
* An "app_label.ModelName" string.
* A model class, which will be returned unchanged.
"""
# Check for recursive relations
if relation == RECURSIVE_RELATIONSHIP_CONSTANT:
relation = scope_model
# Look for an "app.Model" relation
if isinstance(relation, six.string_types):
if "." not in relation:
relation = "%s.%s" % (scope_model._meta.app_label, relation)
return relation
def lazy_related_operation(function, model, *related_models, **kwargs):
"""
Schedule `function` to be called once `model` and all `related_models`
have been imported and registered with the app registry. `function` will
be called with the newly-loaded model classes as its positional arguments,
plus any optional keyword arguments.
The `model` argument must be a model class. Each subsequent positional
argument is another model, or a reference to another model - see
`resolve_relation()` for the various forms these may take. Any relative
references will be resolved relative to `model`.
This is a convenience wrapper for `Apps.lazy_model_operation` - the app
registry model used is the one found in `model._meta.apps`.
"""
models = [model] + [resolve_relation(model, rel) for rel in related_models]
model_keys = (make_model_tuple(m) for m in models)
apps = model._meta.apps
return apps.lazy_model_operation(partial(function, **kwargs), *model_keys)
def add_lazy_relation(cls, field, relation, operation):
warnings.warn(
"add_lazy_relation() has been superseded by lazy_related_operation() "
"and related methods on the Apps class.",
RemovedInDjango20Warning, stacklevel=2)
# Rearrange args for new Apps.lazy_model_operation
def function(local, related, field):
return operation(field, related, local)
lazy_related_operation(function, cls, relation, field=field)
class RelatedField(Field):
"""
Base class that all relational fields inherit from.
"""
# Field flags
one_to_many = False
one_to_one = False
many_to_many = False
many_to_one = False
@cached_property
def related_model(self):
# Can't cache this property until all the models are loaded.
apps.check_models_ready()
return self.remote_field.model
def check(self, **kwargs):
errors = super(RelatedField, self).check(**kwargs)
errors.extend(self._check_related_name_is_valid())
errors.extend(self._check_related_query_name_is_valid())
errors.extend(self._check_relation_model_exists())
errors.extend(self._check_referencing_to_swapped_model())
errors.extend(self._check_clashes())
return errors
def _check_related_name_is_valid(self):
import re
import keyword
related_name = self.remote_field.related_name
if related_name is None:
return []
is_valid_id = True
if keyword.iskeyword(related_name):
is_valid_id = False
if six.PY3:
if not related_name.isidentifier():
is_valid_id = False
else:
if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]*\Z', related_name):
is_valid_id = False
if not (is_valid_id or related_name.endswith('+')):
return [
checks.Error(
"The name '%s' is invalid related_name for field %s.%s" %
(self.remote_field.related_name, self.model._meta.object_name,
self.name),
hint="Related name must be a valid Python identifier or end with a '+'",
obj=self,
id='fields.E306',
)
]
return []
def _check_related_query_name_is_valid(self):
if self.remote_field.is_hidden():
return []
rel_query_name = self.related_query_name()
errors = []
if rel_query_name.endswith('_'):
errors.append(
checks.Error(
"Reverse query name '%s' must not end with an underscore."
% (rel_query_name,),
hint=("Add or change a related_name or related_query_name "
"argument for this field."),
obj=self,
id='fields.E308',
)
)
if LOOKUP_SEP in rel_query_name:
errors.append(
checks.Error(
"Reverse query name '%s' must not contain '%s'."
% (rel_query_name, LOOKUP_SEP),
hint=("Add or change a related_name or related_query_name "
"argument for this field."),
obj=self,
id='fields.E309',
)
)
return errors
def _check_relation_model_exists(self):
rel_is_missing = self.remote_field.model not in self.opts.apps.get_models()
rel_is_string = isinstance(self.remote_field.model, six.string_types)
model_name = self.remote_field.model if rel_is_string else self.remote_field.model._meta.object_name
if rel_is_missing and (rel_is_string or not self.remote_field.model._meta.swapped):
return [
checks.Error(
"Field defines a relation with model '%s', which is either "
"not installed, or is abstract." % model_name,
obj=self,
id='fields.E300',
)
]
return []
def _check_referencing_to_swapped_model(self):
if (self.remote_field.model not in self.opts.apps.get_models() and
not isinstance(self.remote_field.model, six.string_types) and
self.remote_field.model._meta.swapped):
model = "%s.%s" % (
self.remote_field.model._meta.app_label,
self.remote_field.model._meta.object_name
)
return [
checks.Error(
"Field defines a relation with the model '%s', which has "
"been swapped out." % model,
hint="Update the relation to point at 'settings.%s'." % self.remote_field.model._meta.swappable,
obj=self,
id='fields.E301',
)
]
return []
def _check_clashes(self):
"""
Check accessor and reverse query name clashes.
"""
from django.db.models.base import ModelBase
errors = []
opts = self.model._meta
# `f.remote_field.model` may be a string instead of a model. Skip if model name is
# not resolved.
if not isinstance(self.remote_field.model, ModelBase):
return []
# Consider that we are checking field `Model.foreign` and the models
# are:
#
# class Target(models.Model):
# model = models.IntegerField()
# model_set = models.IntegerField()
#
# class Model(models.Model):
# foreign = models.ForeignKey(Target)
# m2m = models.ManyToManyField(Target)
# rel_opts.object_name == "Target"
rel_opts = self.remote_field.model._meta
# If the field doesn't install a backward relation on the target model
# (so `is_hidden` returns True), then there are no clashes to check
# and we can skip these fields.
rel_is_hidden = self.remote_field.is_hidden()
rel_name = self.remote_field.get_accessor_name() # i. e. "model_set"
rel_query_name = self.related_query_name() # i. e. "model"
field_name = "%s.%s" % (opts.object_name, self.name) # i. e. "Model.field"
# Check clashes between accessor or reverse query name of `field`
# and any other field name -- i.e. accessor for Model.foreign is
# model_set and it clashes with Target.model_set.
potential_clashes = rel_opts.fields + rel_opts.many_to_many
for clash_field in potential_clashes:
clash_name = "%s.%s" % (rel_opts.object_name, clash_field.name) # i.e. "Target.model_set"
if not rel_is_hidden and clash_field.name == rel_name:
errors.append(
checks.Error(
"Reverse accessor for '%s' clashes with field name '%s'." % (field_name, clash_name),
hint=("Rename field '%s', or add/change a related_name "
"argument to the definition for field '%s'.") % (clash_name, field_name),
obj=self,
id='fields.E302',
)
)
if clash_field.name == rel_query_name:
errors.append(
checks.Error(
"Reverse query name for '%s' clashes with field name '%s'." % (field_name, clash_name),
hint=("Rename field '%s', or add/change a related_name "
"argument to the definition for field '%s'.") % (clash_name, field_name),
obj=self,
id='fields.E303',
)
)
# Check clashes between accessors/reverse query names of `field` and
# any other field accessor -- i. e. Model.foreign accessor clashes with
# Model.m2m accessor.
potential_clashes = (r for r in rel_opts.related_objects if r.field is not self)
for clash_field in potential_clashes:
clash_name = "%s.%s" % ( # i. e. "Model.m2m"
clash_field.related_model._meta.object_name,
clash_field.field.name)
if not rel_is_hidden and clash_field.get_accessor_name() == rel_name:
errors.append(
checks.Error(
"Reverse accessor for '%s' clashes with reverse accessor for '%s'." % (field_name, clash_name),
hint=("Add or change a related_name argument "
"to the definition for '%s' or '%s'.") % (field_name, clash_name),
obj=self,
id='fields.E304',
)
)
if clash_field.get_accessor_name() == rel_query_name:
errors.append(
checks.Error(
"Reverse query name for '%s' clashes with reverse query name for '%s'."
% (field_name, clash_name),
hint=("Add or change a related_name argument "
"to the definition for '%s' or '%s'.") % (field_name, clash_name),
obj=self,
id='fields.E305',
)
)
return errors
def db_type(self, connection):
# By default related field will not have a column as it relates to
# columns from another table.
return None
def contribute_to_class(self, cls, name, private_only=False, **kwargs):
super(RelatedField, self).contribute_to_class(cls, name, private_only=private_only, **kwargs)
self.opts = cls._meta
if not cls._meta.abstract:
if self.remote_field.related_name:
related_name = self.remote_field.related_name
else:
related_name = self.opts.default_related_name
if related_name:
related_name = force_text(related_name) % {
'class': cls.__name__.lower(),
'model_name': cls._meta.model_name.lower(),
'app_label': cls._meta.app_label.lower()
}
self.remote_field.related_name = related_name
if self.remote_field.related_query_name:
related_query_name = force_text(self.remote_field.related_query_name) % {
'class': cls.__name__.lower(),
'app_label': cls._meta.app_label.lower(),
}
self.remote_field.related_query_name = related_query_name
def resolve_related_class(model, related, field):
field.remote_field.model = related
field.do_related_class(related, model)
lazy_related_operation(resolve_related_class, cls, self.remote_field.model, field=self)
def get_forward_related_filter(self, obj):
"""
Return the keyword arguments that when supplied to
self.model.object.filter(), would select all instances related through
this field to the remote obj. This is used to build the querysets
returned by related descriptors. obj is an instance of
self.related_field.model.
"""
return {
'%s__%s' % (self.name, rh_field.name): getattr(obj, rh_field.attname)
for _, rh_field in self.related_fields
}
def get_reverse_related_filter(self, obj):
"""
Complement to get_forward_related_filter(). Return the keyword
arguments that when passed to self.related_field.model.object.filter()
select all instances of self.related_field.model related through
this field to obj. obj is an instance of self.model.
"""
base_filter = {
rh_field.attname: getattr(obj, lh_field.attname)
for lh_field, rh_field in self.related_fields
}
descriptor_filter = self.get_extra_descriptor_filter(obj)
base_q = Q(**base_filter)
if isinstance(descriptor_filter, dict):
return base_q & Q(**descriptor_filter)
elif descriptor_filter:
return base_q & descriptor_filter
return base_q
@property
def swappable_setting(self):
"""
Get the setting that this is powered from for swapping, or None
if it's not swapped in / marked with swappable=False.
"""
if self.swappable:
# Work out string form of "to"
if isinstance(self.remote_field.model, six.string_types):
to_string = self.remote_field.model
else:
to_string = self.remote_field.model._meta.label
return apps.get_swappable_settings_name(to_string)
return None
def set_attributes_from_rel(self):
self.name = (
self.name or
(self.remote_field.model._meta.model_name + '_' + self.remote_field.model._meta.pk.name)
)
if self.verbose_name is None:
self.verbose_name = self.remote_field.model._meta.verbose_name
self.remote_field.set_field_name()
def do_related_class(self, other, cls):
self.set_attributes_from_rel()
self.contribute_to_related_class(other, self.remote_field)
def get_limit_choices_to(self):
"""
Return ``limit_choices_to`` for this model field.
If it is a callable, it will be invoked and the result will be
returned.
"""
if callable(self.remote_field.limit_choices_to):
return self.remote_field.limit_choices_to()
return self.remote_field.limit_choices_to
def formfield(self, **kwargs):
"""
Pass ``limit_choices_to`` to the field being constructed.
Only passes it if there is a type that supports related fields.
This is a similar strategy used to pass the ``queryset`` to the field
being constructed.
"""
defaults = {}
if hasattr(self.remote_field, 'get_related_field'):
# If this is a callable, do not invoke it here. Just pass
# it in the defaults for when the form class will later be
# instantiated.
limit_choices_to = self.remote_field.limit_choices_to
defaults.update({
'limit_choices_to': limit_choices_to,
})
defaults.update(kwargs)
return super(RelatedField, self).formfield(**defaults)
def related_query_name(self):
"""
Define the name that can be used to identify this related object in a
table-spanning query.
"""
return self.remote_field.related_query_name or self.remote_field.related_name or self.opts.model_name
@property
def target_field(self):
"""
When filtering against this relation, returns the field on the remote
model against which the filtering should happen.
"""
target_fields = self.get_path_info()[-1].target_fields
if len(target_fields) > 1:
raise exceptions.FieldError(
"The relation has multiple target fields, but only single target field was asked for")
return target_fields[0]
class ForeignObject(RelatedField):
"""
Abstraction of the ForeignKey relation, supports multi-column relations.
"""
# Field flags
many_to_many = False
many_to_one = True
one_to_many = False
one_to_one = False
requires_unique_target = True
related_accessor_class = ReverseManyToOneDescriptor
forward_related_accessor_class = ForwardManyToOneDescriptor
rel_class = ForeignObjectRel
def __init__(self, to, on_delete, from_fields, to_fields, rel=None, related_name=None,
related_query_name=None, limit_choices_to=None, parent_link=False,
swappable=True, **kwargs):
if rel is None:
rel = self.rel_class(
self, to,
related_name=related_name,
related_query_name=related_query_name,
limit_choices_to=limit_choices_to,
parent_link=parent_link,
on_delete=on_delete,
)
super(ForeignObject, self).__init__(rel=rel, **kwargs)
self.from_fields = from_fields
self.to_fields = to_fields
self.swappable = swappable
def check(self, **kwargs):
errors = super(ForeignObject, self).check(**kwargs)
errors.extend(self._check_to_fields_exist())
errors.extend(self._check_unique_target())
return errors
def _check_to_fields_exist(self):
# Skip nonexistent models.
if isinstance(self.remote_field.model, six.string_types):
return []
errors = []
for to_field in self.to_fields:
if to_field:
try:
self.remote_field.model._meta.get_field(to_field)
except exceptions.FieldDoesNotExist:
errors.append(
checks.Error(
"The to_field '%s' doesn't exist on the related "
"model '%s'."
% (to_field, self.remote_field.model._meta.label),
obj=self,
id='fields.E312',
)
)
return errors
def _check_unique_target(self):
rel_is_string = isinstance(self.remote_field.model, six.string_types)
if rel_is_string or not self.requires_unique_target:
return []
try:
self.foreign_related_fields
except exceptions.FieldDoesNotExist:
return []
if not self.foreign_related_fields:
return []
unique_foreign_fields = {
frozenset([f.name])
for f in self.remote_field.model._meta.get_fields()
if getattr(f, 'unique', False)
}
unique_foreign_fields.update({
frozenset(ut)
for ut in self.remote_field.model._meta.unique_together
})
foreign_fields = {f.name for f in self.foreign_related_fields}
has_unique_constraint = any(u <= foreign_fields for u in unique_foreign_fields)
if not has_unique_constraint and len(self.foreign_related_fields) > 1:
field_combination = ', '.join(
"'%s'" % rel_field.name for rel_field in self.foreign_related_fields
)
model_name = self.remote_field.model.__name__
return [
checks.Error(
"No subset of the fields %s on model '%s' is unique."
% (field_combination, model_name),
hint=(
"Add unique=True on any of those fields or add at "
"least a subset of them to a unique_together constraint."
),
obj=self,
id='fields.E310',
)
]
elif not has_unique_constraint:
field_name = self.foreign_related_fields[0].name
model_name = self.remote_field.model.__name__
return [
checks.Error(
"'%s.%s' must set unique=True because it is referenced by "
"a foreign key." % (model_name, field_name),
obj=self,
id='fields.E311',
)
]
else:
return []
def deconstruct(self):
name, path, args, kwargs = super(ForeignObject, self).deconstruct()
kwargs['on_delete'] = self.remote_field.on_delete
kwargs['from_fields'] = self.from_fields
kwargs['to_fields'] = self.to_fields
if self.remote_field.related_name is not None:
kwargs['related_name'] = self.remote_field.related_name
if self.remote_field.related_query_name is not None:
kwargs['related_query_name'] = self.remote_field.related_query_name
if self.remote_field.parent_link:
kwargs['parent_link'] = self.remote_field.parent_link
# Work out string form of "to"
if isinstance(self.remote_field.model, six.string_types):
kwargs['to'] = self.remote_field.model
else:
kwargs['to'] = "%s.%s" % (
self.remote_field.model._meta.app_label,
self.remote_field.model._meta.object_name,
)
# If swappable is True, then see if we're actually pointing to the target
# of a swap.
swappable_setting = self.swappable_setting
if swappable_setting is not None:
# If it's already a settings reference, error
if hasattr(kwargs['to'], "setting_name"):
if kwargs['to'].setting_name != swappable_setting:
raise ValueError(
"Cannot deconstruct a ForeignKey pointing to a model "
"that is swapped in place of more than one model (%s and %s)"
% (kwargs['to'].setting_name, swappable_setting)
)
# Set it
from django.db.migrations.writer import SettingsReference
kwargs['to'] = SettingsReference(
kwargs['to'],
swappable_setting,
)
return name, path, args, kwargs
def resolve_related_fields(self):
if len(self.from_fields) < 1 or len(self.from_fields) != len(self.to_fields):
raise ValueError('Foreign Object from and to fields must be the same non-zero length')
if isinstance(self.remote_field.model, six.string_types):
raise ValueError('Related model %r cannot be resolved' % self.remote_field.model)
related_fields = []
for index in range(len(self.from_fields)):
from_field_name = self.from_fields[index]
to_field_name = self.to_fields[index]
from_field = (self if from_field_name == 'self'
else self.opts.get_field(from_field_name))
to_field = (self.remote_field.model._meta.pk if to_field_name is None
else self.remote_field.model._meta.get_field(to_field_name))
related_fields.append((from_field, to_field))
return related_fields
@property
def related_fields(self):
if not hasattr(self, '_related_fields'):
self._related_fields = self.resolve_related_fields()
return self._related_fields
@property
def reverse_related_fields(self):
return [(rhs_field, lhs_field) for lhs_field, rhs_field in self.related_fields]
@property
def local_related_fields(self):
return tuple(lhs_field for lhs_field, rhs_field in self.related_fields)
@property
def foreign_related_fields(self):
return tuple(rhs_field for lhs_field, rhs_field in self.related_fields if rhs_field)
def get_local_related_value(self, instance):
return self.get_instance_value_for_fields(instance, self.local_related_fields)
def get_foreign_related_value(self, instance):
return self.get_instance_value_for_fields(instance, self.foreign_related_fields)
@staticmethod
def get_instance_value_for_fields(instance, fields):
ret = []
opts = instance._meta
for field in fields:
# Gotcha: in some cases (like fixture loading) a model can have
# different values in parent_ptr_id and parent's id. So, use
# instance.pk (that is, parent_ptr_id) when asked for instance.id.
if field.primary_key:
possible_parent_link = opts.get_ancestor_link(field.model)
if (not possible_parent_link or
possible_parent_link.primary_key or
possible_parent_link.model._meta.abstract):
ret.append(instance.pk)
continue
ret.append(getattr(instance, field.attname))
return tuple(ret)
def get_attname_column(self):
attname, column = super(ForeignObject, self).get_attname_column()
return attname, None
def get_joining_columns(self, reverse_join=False):
source = self.reverse_related_fields if reverse_join else self.related_fields
return tuple((lhs_field.column, rhs_field.column) for lhs_field, rhs_field in source)
def get_reverse_joining_columns(self):
return self.get_joining_columns(reverse_join=True)
def get_extra_descriptor_filter(self, instance):
"""
Return an extra filter condition for related object fetching when
user does 'instance.fieldname', that is the extra filter is used in
the descriptor of the field.
The filter should be either a dict usable in .filter(**kwargs) call or
a Q-object. The condition will be ANDed together with the relation's
joining columns.
A parallel method is get_extra_restriction() which is used in
JOIN and subquery conditions.
"""
return {}
def get_extra_restriction(self, where_class, alias, related_alias):
"""
Return a pair condition used for joining and subquery pushdown. The
condition is something that responds to as_sql(compiler, connection)
method.
Note that currently referring both the 'alias' and 'related_alias'
will not work in some conditions, like subquery pushdown.
A parallel method is get_extra_descriptor_filter() which is used in
instance.fieldname related object fetching.
"""
return None
def get_path_info(self):
"""
Get path from this field to the related model.
"""
opts = self.remote_field.model._meta
from_opts = self.model._meta
return [PathInfo(from_opts, opts, self.foreign_related_fields, self, False, True)]
def get_reverse_path_info(self):
"""
Get path from the related model to this field's model.
"""
opts = self.model._meta
from_opts = self.remote_field.model._meta
pathinfos = [PathInfo(from_opts, opts, (opts.pk,), self.remote_field, not self.unique, False)]
return pathinfos
@classmethod
@lru_cache(maxsize=None)
def get_lookups(cls):
bases = inspect.getmro(cls)
bases = bases[:bases.index(ForeignObject) + 1]
class_lookups = [parent.__dict__.get('class_lookups', {}) for parent in bases]
return cls.merge_dicts(class_lookups)
def contribute_to_class(self, cls, name, private_only=False, **kwargs):
super(ForeignObject, self).contribute_to_class(cls, name, private_only=private_only, **kwargs)
setattr(cls, self.name, self.forward_related_accessor_class(self))
def contribute_to_related_class(self, cls, related):
# Internal FK's - i.e., those with a related name ending with '+' -
# and swapped models don't get a related descriptor.
if not self.remote_field.is_hidden() and not related.related_model._meta.swapped:
setattr(cls._meta.concrete_model, related.get_accessor_name(), self.related_accessor_class(related))
# While 'limit_choices_to' might be a callable, simply pass
# it along for later - this is too early because it's still
# model load time.
if self.remote_field.limit_choices_to:
cls._meta.related_fkey_lookups.append(self.remote_field.limit_choices_to)
ForeignObject.register_lookup(RelatedIn)
ForeignObject.register_lookup(RelatedExact)
ForeignObject.register_lookup(RelatedLessThan)
ForeignObject.register_lookup(RelatedGreaterThan)
ForeignObject.register_lookup(RelatedGreaterThanOrEqual)
ForeignObject.register_lookup(RelatedLessThanOrEqual)
ForeignObject.register_lookup(RelatedIsNull)
class ForeignKey(ForeignObject):
"""
Provide a many-to-one relation by adding a column to the local model
to hold the remote value.
By default ForeignKey will target the pk of the remote model but this
behavior can be changed by using the ``to_field`` argument.
"""
# Field flags
many_to_many = False
many_to_one = True
one_to_many = False
one_to_one = False
rel_class = ManyToOneRel
empty_strings_allowed = False
default_error_messages = {
'invalid': _('%(model)s instance with %(field)s %(value)r does not exist.')
}
description = _("Foreign Key (type determined by related field)")
def __init__(self, to, on_delete=None, related_name=None, related_query_name=None,
limit_choices_to=None, parent_link=False, to_field=None,
db_constraint=True, **kwargs):
try:
to._meta.model_name
except AttributeError:
assert isinstance(to, six.string_types), (
"%s(%r) is invalid. First parameter to ForeignKey must be "
"either a model, a model name, or the string %r" % (
self.__class__.__name__, to,
RECURSIVE_RELATIONSHIP_CONSTANT,
)
)
else:
# For backwards compatibility purposes, we need to *try* and set
# the to_field during FK construction. It won't be guaranteed to
# be correct until contribute_to_class is called. Refs #12190.
to_field = to_field or (to._meta.pk and to._meta.pk.name)
if on_delete is None:
warnings.warn(
"on_delete will be a required arg for %s in Django 2.0. Set "
"it to models.CASCADE on models and in existing migrations "
"if you want to maintain the current default behavior. "
"See https://docs.djangoproject.com/en/%s/ref/models/fields/"
"#django.db.models.ForeignKey.on_delete" % (
self.__class__.__name__,
get_docs_version(),
),
RemovedInDjango20Warning, 2)
on_delete = CASCADE
elif not callable(on_delete):
warnings.warn(
"The signature for {0} will change in Django 2.0. "
"Pass to_field='{1}' as a kwarg instead of as an arg.".format(
self.__class__.__name__,
on_delete,
),
RemovedInDjango20Warning, 2)
on_delete, to_field = to_field, on_delete
kwargs['rel'] = self.rel_class(
self, to, to_field,
related_name=related_name,
related_query_name=related_query_name,
limit_choices_to=limit_choices_to,
parent_link=parent_link,
on_delete=on_delete,
)
kwargs['db_index'] = kwargs.get('db_index', True)
super(ForeignKey, self).__init__(
to, on_delete, from_fields=['self'], to_fields=[to_field], **kwargs)
self.db_constraint = db_constraint
def check(self, **kwargs):
errors = super(ForeignKey, self).check(**kwargs)
errors.extend(self._check_on_delete())
errors.extend(self._check_unique())
return errors
def _check_on_delete(self):
on_delete = getattr(self.remote_field, 'on_delete', None)
if on_delete == SET_NULL and not self.null:
return [
checks.Error(
'Field specifies on_delete=SET_NULL, but cannot be null.',
hint='Set null=True argument on the field, or change the on_delete rule.',
obj=self,
id='fields.E320',
)
]
elif on_delete == SET_DEFAULT and not self.has_default():
return [
checks.Error(
'Field specifies on_delete=SET_DEFAULT, but has no default value.',
hint='Set a default value, or change the on_delete rule.',
obj=self,
id='fields.E321',
)
]
else:
return []
def _check_unique(self, **kwargs):
return [
checks.Warning(
'Setting unique=True on a ForeignKey has the same effect as using a OneToOneField.',
hint='ForeignKey(unique=True) is usually better served by a OneToOneField.',
obj=self,
id='fields.W342',
)
] if self.unique else []
def deconstruct(self):
name, path, args, kwargs = super(ForeignKey, self).deconstruct()
del kwargs['to_fields']
del kwargs['from_fields']
# Handle the simpler arguments
if self.db_index:
del kwargs['db_index']
else:
kwargs['db_index'] = False
if self.db_constraint is not True:
kwargs['db_constraint'] = self.db_constraint
# Rel needs more work.
to_meta = getattr(self.remote_field.model, "_meta", None)
if self.remote_field.field_name and (
not to_meta or (to_meta.pk and self.remote_field.field_name != to_meta.pk.name)):
kwargs['to_field'] = self.remote_field.field_name
return name, path, args, kwargs
@property
def target_field(self):
return self.foreign_related_fields[0]
def get_reverse_path_info(self):
"""
Get path from the related model to this field's model.
"""
opts = self.model._meta
from_opts = self.remote_field.model._meta
pathinfos = [PathInfo(from_opts, opts, (opts.pk,), self.remote_field, not self.unique, False)]
return pathinfos
def validate(self, value, model_instance):
if self.remote_field.parent_link:
return
super(ForeignKey, self).validate(value, model_instance)
if value is None:
return
using = router.db_for_read(self.remote_field.model, instance=model_instance)
qs = self.remote_field.model._default_manager.using(using).filter(
**{self.remote_field.field_name: value}
)
qs = qs.complex_filter(self.get_limit_choices_to())
if not qs.exists():
raise exceptions.ValidationError(
self.error_messages['invalid'],
code='invalid',
params={
'model': self.remote_field.model._meta.verbose_name, 'pk': value,
'field': self.remote_field.field_name, 'value': value,
}, # 'pk' is included for backwards compatibility
)
def get_attname(self):
return '%s_id' % self.name
def get_attname_column(self):
attname = self.get_attname()
column = self.db_column or attname
return attname, column
def get_default(self):
"Here we check if the default value is an object and return the to_field if so."
field_default = super(ForeignKey, self).get_default()
if isinstance(field_default, self.remote_field.model):
return getattr(field_default, self.target_field.attname)
return field_default
def get_db_prep_save(self, value, connection):
if value is None or (value == '' and
(not self.target_field.empty_strings_allowed or
connection.features.interprets_empty_strings_as_nulls)):
return None
else:
return self.target_field.get_db_prep_save(value, connection=connection)
def get_db_prep_value(self, value, connection, prepared=False):
return self.target_field.get_db_prep_value(value, connection, prepared)
def contribute_to_related_class(self, cls, related):
super(ForeignKey, self).contribute_to_related_class(cls, related)
if self.remote_field.field_name is None:
self.remote_field.field_name = cls._meta.pk.name
def formfield(self, **kwargs):
db = kwargs.pop('using', None)
if isinstance(self.remote_field.model, six.string_types):
raise ValueError("Cannot create form field for %r yet, because "
"its related model %r has not been loaded yet" %
(self.name, self.remote_field.model))
defaults = {
'form_class': forms.ModelChoiceField,
'queryset': self.remote_field.model._default_manager.using(db),
'to_field_name': self.remote_field.field_name,
}
defaults.update(kwargs)
return super(ForeignKey, self).formfield(**defaults)
def db_check(self, connection):
return []
def db_type(self, connection):
return self.target_field.rel_db_type(connection=connection)
def db_parameters(self, connection):
return {"type": self.db_type(connection), "check": self.db_check(connection)}
def convert_empty_strings(self, value, expression, connection, context):
if (not value) and isinstance(value, six.string_types):
return None
return value
def get_db_converters(self, connection):
converters = super(ForeignKey, self).get_db_converters(connection)
if connection.features.interprets_empty_strings_as_nulls:
converters += [self.convert_empty_strings]
return converters
def get_col(self, alias, output_field=None):
return super(ForeignKey, self).get_col(alias, output_field or self.target_field)
class OneToOneField(ForeignKey):
"""
A OneToOneField is essentially the same as a ForeignKey, with the exception
that it always carries a "unique" constraint with it and the reverse
relation always returns the object pointed to (since there will only ever
be one), rather than returning a list.
"""
# Field flags
many_to_many = False
many_to_one = False
one_to_many = False
one_to_one = True
related_accessor_class = ReverseOneToOneDescriptor
forward_related_accessor_class = ForwardOneToOneDescriptor
rel_class = OneToOneRel
description = _("One-to-one relationship")
def __init__(self, to, on_delete=None, to_field=None, **kwargs):
kwargs['unique'] = True
if on_delete is None:
warnings.warn(
"on_delete will be a required arg for %s in Django 2.0. Set "
"it to models.CASCADE on models and in existing migrations "
"if you want to maintain the current default behavior. "
"See https://docs.djangoproject.com/en/%s/ref/models/fields/"
"#django.db.models.ForeignKey.on_delete" % (
self.__class__.__name__,
get_docs_version(),
),
RemovedInDjango20Warning, 2)
on_delete = CASCADE
elif not callable(on_delete):
warnings.warn(
"The signature for {0} will change in Django 2.0. "
"Pass to_field='{1}' as a kwarg instead of as an arg.".format(
self.__class__.__name__,
on_delete,
),
RemovedInDjango20Warning, 2)
to_field = on_delete
on_delete = CASCADE # Avoid warning in superclass
super(OneToOneField, self).__init__(to, on_delete, to_field=to_field, **kwargs)
def deconstruct(self):
name, path, args, kwargs = super(OneToOneField, self).deconstruct()
if "unique" in kwargs:
del kwargs['unique']
return name, path, args, kwargs
def formfield(self, **kwargs):
if self.remote_field.parent_link:
return None
return super(OneToOneField, self).formfield(**kwargs)
def save_form_data(self, instance, data):
if isinstance(data, self.remote_field.model):
setattr(instance, self.name, data)
else:
setattr(instance, self.attname, data)
def _check_unique(self, **kwargs):
# Override ForeignKey since check isn't applicable here.
return []
def create_many_to_many_intermediary_model(field, klass):
from django.db import models
def set_managed(model, related, through):
through._meta.managed = model._meta.managed or related._meta.managed
to_model = resolve_relation(klass, field.remote_field.model)
name = '%s_%s' % (klass._meta.object_name, field.name)
lazy_related_operation(set_managed, klass, to_model, name)
to = make_model_tuple(to_model)[1]
from_ = klass._meta.model_name
if to == from_:
to = 'to_%s' % to
from_ = 'from_%s' % from_
meta = type(str('Meta'), (object,), {
'db_table': field._get_m2m_db_table(klass._meta),
'auto_created': klass,
'app_label': klass._meta.app_label,
'db_tablespace': klass._meta.db_tablespace,
'unique_together': (from_, to),
'verbose_name': _('%(from)s-%(to)s relationship') % {'from': from_, 'to': to},
'verbose_name_plural': _('%(from)s-%(to)s relationships') % {'from': from_, 'to': to},
'apps': field.model._meta.apps,
})
# Construct and return the new class.
return type(str(name), (models.Model,), {
'Meta': meta,
'__module__': klass.__module__,
from_: models.ForeignKey(
klass,
related_name='%s+' % name,
db_tablespace=field.db_tablespace,
db_constraint=field.remote_field.db_constraint,
on_delete=CASCADE,
),
to: models.ForeignKey(
to_model,
related_name='%s+' % name,
db_tablespace=field.db_tablespace,
db_constraint=field.remote_field.db_constraint,
on_delete=CASCADE,
)
})
class ManyToManyField(RelatedField):
"""
Provide a many-to-many relation by using an intermediary model that
holds two ForeignKey fields pointed at the two sides of the relation.
Unless a ``through`` model was provided, ManyToManyField will use the
create_many_to_many_intermediary_model factory to automatically generate
the intermediary model.
"""
# Field flags
many_to_many = True
many_to_one = False
one_to_many = False
one_to_one = False
rel_class = ManyToManyRel
description = _("Many-to-many relationship")
def __init__(self, to, related_name=None, related_query_name=None,
limit_choices_to=None, symmetrical=None, through=None,
through_fields=None, db_constraint=True, db_table=None,
swappable=True, **kwargs):
try:
to._meta
except AttributeError:
assert isinstance(to, six.string_types), (
"%s(%r) is invalid. First parameter to ManyToManyField must be "
"either a model, a model name, or the string %r" %
(self.__class__.__name__, to, RECURSIVE_RELATIONSHIP_CONSTANT)
)
# Class names must be ASCII in Python 2.x, so we forcibly coerce it
# here to break early if there's a problem.
to = str(to)
if symmetrical is None:
symmetrical = (to == RECURSIVE_RELATIONSHIP_CONSTANT)
if through is not None:
assert db_table is None, (
"Cannot specify a db_table if an intermediary model is used."
)
kwargs['rel'] = self.rel_class(
self, to,
related_name=related_name,
related_query_name=related_query_name,
limit_choices_to=limit_choices_to,
symmetrical=symmetrical,
through=through,
through_fields=through_fields,
db_constraint=db_constraint,
)
self.has_null_arg = 'null' in kwargs
super(ManyToManyField, self).__init__(**kwargs)
self.db_table = db_table
self.swappable = swappable
def check(self, **kwargs):
errors = super(ManyToManyField, self).check(**kwargs)
errors.extend(self._check_unique(**kwargs))
errors.extend(self._check_relationship_model(**kwargs))
errors.extend(self._check_ignored_options(**kwargs))
errors.extend(self._check_table_uniqueness(**kwargs))
return errors
def _check_unique(self, **kwargs):
if self.unique:
return [
checks.Error(
'ManyToManyFields cannot be unique.',
obj=self,
id='fields.E330',
)
]
return []
def _check_ignored_options(self, **kwargs):
warnings = []
if self.has_null_arg:
warnings.append(
checks.Warning(
'null has no effect on ManyToManyField.',
obj=self,
id='fields.W340',
)
)
if len(self._validators) > 0:
warnings.append(
checks.Warning(
'ManyToManyField does not support validators.',
obj=self,
id='fields.W341',
)
)
if (self.remote_field.limit_choices_to and self.remote_field.through and
not self.remote_field.through._meta.auto_created):
warnings.append(
checks.Warning(
'limit_choices_to has no effect on ManyToManyField '
'with a through model.',
obj=self,
id='fields.W343',
)
)
return warnings
def _check_relationship_model(self, from_model=None, **kwargs):
if hasattr(self.remote_field.through, '_meta'):
qualified_model_name = "%s.%s" % (
self.remote_field.through._meta.app_label, self.remote_field.through.__name__)
else:
qualified_model_name = self.remote_field.through
errors = []
if self.remote_field.through not in self.opts.apps.get_models(include_auto_created=True):
# The relationship model is not installed.
errors.append(
checks.Error(
"Field specifies a many-to-many relation through model "
"'%s', which has not been installed." % qualified_model_name,
obj=self,
id='fields.E331',
)
)
else:
assert from_model is not None, (
"ManyToManyField with intermediate "
"tables cannot be checked if you don't pass the model "
"where the field is attached to."
)
# Set some useful local variables
to_model = resolve_relation(from_model, self.remote_field.model)
from_model_name = from_model._meta.object_name
if isinstance(to_model, six.string_types):
to_model_name = to_model
else:
to_model_name = to_model._meta.object_name
relationship_model_name = self.remote_field.through._meta.object_name
self_referential = from_model == to_model
# Check symmetrical attribute.
if (self_referential and self.remote_field.symmetrical and
not self.remote_field.through._meta.auto_created):
errors.append(
checks.Error(
'Many-to-many fields with intermediate tables must not be symmetrical.',
obj=self,
id='fields.E332',
)
)
# Count foreign keys in intermediate model
if self_referential:
seen_self = sum(
from_model == getattr(field.remote_field, 'model', None)
for field in self.remote_field.through._meta.fields
)
if seen_self > 2 and not self.remote_field.through_fields:
errors.append(
checks.Error(
"The model is used as an intermediate model by "
"'%s', but it has more than two foreign keys "
"to '%s', which is ambiguous. You must specify "
"which two foreign keys Django should use via the "
"through_fields keyword argument." % (self, from_model_name),
hint="Use through_fields to specify which two foreign keys Django should use.",
obj=self.remote_field.through,
id='fields.E333',
)
)
else:
# Count foreign keys in relationship model
seen_from = sum(
from_model == getattr(field.remote_field, 'model', None)
for field in self.remote_field.through._meta.fields
)
seen_to = sum(
to_model == getattr(field.remote_field, 'model', None)
for field in self.remote_field.through._meta.fields
)
if seen_from > 1 and not self.remote_field.through_fields:
errors.append(
checks.Error(
("The model is used as an intermediate model by "
"'%s', but it has more than one foreign key "
"from '%s', which is ambiguous. You must specify "
"which foreign key Django should use via the "
"through_fields keyword argument.") % (self, from_model_name),
hint=(
'If you want to create a recursive relationship, '
'use ForeignKey("self", symmetrical=False, through="%s").'
) % relationship_model_name,
obj=self,
id='fields.E334',
)
)
if seen_to > 1 and not self.remote_field.through_fields:
errors.append(
checks.Error(
"The model is used as an intermediate model by "
"'%s', but it has more than one foreign key "
"to '%s', which is ambiguous. You must specify "
"which foreign key Django should use via the "
"through_fields keyword argument." % (self, to_model_name),
hint=(
'If you want to create a recursive relationship, '
'use ForeignKey("self", symmetrical=False, through="%s").'
) % relationship_model_name,
obj=self,
id='fields.E335',
)
)
if seen_from == 0 or seen_to == 0:
errors.append(
checks.Error(
"The model is used as an intermediate model by "
"'%s', but it does not have a foreign key to '%s' or '%s'." % (
self, from_model_name, to_model_name
),
obj=self.remote_field.through,
id='fields.E336',
)
)
# Validate `through_fields`.
if self.remote_field.through_fields is not None:
# Validate that we're given an iterable of at least two items
# and that none of them is "falsy".
if not (len(self.remote_field.through_fields) >= 2 and
self.remote_field.through_fields[0] and self.remote_field.through_fields[1]):
errors.append(
checks.Error(
"Field specifies 'through_fields' but does not provide "
"the names of the two link fields that should be used "
"for the relation through model '%s'." % qualified_model_name,
hint="Make sure you specify 'through_fields' as through_fields=('field1', 'field2')",
obj=self,
id='fields.E337',
)
)
# Validate the given through fields -- they should be actual
# fields on the through model, and also be foreign keys to the
# expected models.
else:
assert from_model is not None, (
"ManyToManyField with intermediate "
"tables cannot be checked if you don't pass the model "
"where the field is attached to."
)
source, through, target = from_model, self.remote_field.through, self.remote_field.model
source_field_name, target_field_name = self.remote_field.through_fields[:2]
for field_name, related_model in ((source_field_name, source),
(target_field_name, target)):
possible_field_names = []
for f in through._meta.fields:
if hasattr(f, 'remote_field') and getattr(f.remote_field, 'model', None) == related_model:
possible_field_names.append(f.name)
if possible_field_names:
hint = "Did you mean one of the following foreign keys to '%s': %s?" % (
related_model._meta.object_name,
', '.join(possible_field_names),
)
else:
hint = None
try:
field = through._meta.get_field(field_name)
except exceptions.FieldDoesNotExist:
errors.append(
checks.Error(
"The intermediary model '%s' has no field '%s'."
% (qualified_model_name, field_name),
hint=hint,
obj=self,
id='fields.E338',
)
)
else:
if not (hasattr(field, 'remote_field') and
getattr(field.remote_field, 'model', None) == related_model):
errors.append(
checks.Error(
"'%s.%s' is not a foreign key to '%s'." % (
through._meta.object_name, field_name,
related_model._meta.object_name,
),
hint=hint,
obj=self,
id='fields.E339',
)
)
return errors
def _check_table_uniqueness(self, **kwargs):
if isinstance(self.remote_field.through, six.string_types) or not self.remote_field.through._meta.managed:
return []
registered_tables = {
model._meta.db_table: model
for model in self.opts.apps.get_models(include_auto_created=True)
if model != self.remote_field.through and model._meta.managed
}
m2m_db_table = self.m2m_db_table()
model = registered_tables.get(m2m_db_table)
# The second condition allows multiple m2m relations on a model if
# some point to a through model that proxies another through model.
if model and model._meta.concrete_model != self.remote_field.through._meta.concrete_model:
if model._meta.auto_created:
def _get_field_name(model):
for field in model._meta.auto_created._meta.many_to_many:
if field.remote_field.through is model:
return field.name
opts = model._meta.auto_created._meta
clashing_obj = '%s.%s' % (opts.label, _get_field_name(model))
else:
clashing_obj = '%s' % model._meta.label
return [
checks.Error(
"The field's intermediary table '%s' clashes with the "
"table name of '%s'." % (m2m_db_table, clashing_obj),
obj=self,
id='fields.E340',
)
]
return []
def deconstruct(self):
name, path, args, kwargs = super(ManyToManyField, self).deconstruct()
# Handle the simpler arguments.
if self.db_table is not None:
kwargs['db_table'] = self.db_table
if self.remote_field.db_constraint is not True:
kwargs['db_constraint'] = self.remote_field.db_constraint
if self.remote_field.related_name is not None:
kwargs['related_name'] = self.remote_field.related_name
if self.remote_field.related_query_name is not None:
kwargs['related_query_name'] = self.remote_field.related_query_name
# Rel needs more work.
if isinstance(self.remote_field.model, six.string_types):
kwargs['to'] = self.remote_field.model
else:
kwargs['to'] = "%s.%s" % (
self.remote_field.model._meta.app_label,
self.remote_field.model._meta.object_name,
)
if getattr(self.remote_field, 'through', None) is not None:
if isinstance(self.remote_field.through, six.string_types):
kwargs['through'] = self.remote_field.through
elif not self.remote_field.through._meta.auto_created:
kwargs['through'] = "%s.%s" % (
self.remote_field.through._meta.app_label,
self.remote_field.through._meta.object_name,
)
# If swappable is True, then see if we're actually pointing to the target
# of a swap.
swappable_setting = self.swappable_setting
if swappable_setting is not None:
# If it's already a settings reference, error.
if hasattr(kwargs['to'], "setting_name"):
if kwargs['to'].setting_name != swappable_setting:
raise ValueError(
"Cannot deconstruct a ManyToManyField pointing to a "
"model that is swapped in place of more than one model "
"(%s and %s)" % (kwargs['to'].setting_name, swappable_setting)
)
from django.db.migrations.writer import SettingsReference
kwargs['to'] = SettingsReference(
kwargs['to'],
swappable_setting,
)
return name, path, args, kwargs
def _get_path_info(self, direct=False):
"""
Called by both direct and indirect m2m traversal.
"""
pathinfos = []
int_model = self.remote_field.through
linkfield1 = int_model._meta.get_field(self.m2m_field_name())
linkfield2 = int_model._meta.get_field(self.m2m_reverse_field_name())
if direct:
join1infos = linkfield1.get_reverse_path_info()
join2infos = linkfield2.get_path_info()
else:
join1infos = linkfield2.get_reverse_path_info()
join2infos = linkfield1.get_path_info()
# Get join infos between the last model of join 1 and the first model
# of join 2. Assume the only reason these may differ is due to model
# inheritance.
join1_final = join1infos[-1].to_opts
join2_initial = join2infos[0].from_opts
if join1_final is join2_initial:
intermediate_infos = []
elif issubclass(join1_final.model, join2_initial.model):
intermediate_infos = join1_final.get_path_to_parent(join2_initial.model)
else:
intermediate_infos = join2_initial.get_path_from_parent(join1_final.model)
pathinfos.extend(join1infos)
pathinfos.extend(intermediate_infos)
pathinfos.extend(join2infos)
return pathinfos
def get_path_info(self):
return self._get_path_info(direct=True)
def get_reverse_path_info(self):
return self._get_path_info(direct=False)
def _get_m2m_db_table(self, opts):
"""
Function that can be curried to provide the m2m table name for this
relation.
"""
if self.remote_field.through is not None:
return self.remote_field.through._meta.db_table
elif self.db_table:
return self.db_table
else:
m2m_table_name = '%s_%s' % (utils.strip_quotes(opts.db_table), self.name)
return utils.truncate_name(m2m_table_name, connection.ops.max_name_length())
def _get_m2m_attr(self, related, attr):
"""
Function that can be curried to provide the source accessor or DB
column name for the m2m table.
"""
cache_attr = '_m2m_%s_cache' % attr
if hasattr(self, cache_attr):
return getattr(self, cache_attr)
if self.remote_field.through_fields is not None:
link_field_name = self.remote_field.through_fields[0]
else:
link_field_name = None
for f in self.remote_field.through._meta.fields:
if (f.is_relation and f.remote_field.model == related.related_model and
(link_field_name is None or link_field_name == f.name)):
setattr(self, cache_attr, getattr(f, attr))
return getattr(self, cache_attr)
def _get_m2m_reverse_attr(self, related, attr):
"""
Function that can be curried to provide the related accessor or DB
column name for the m2m table.
"""
cache_attr = '_m2m_reverse_%s_cache' % attr
if hasattr(self, cache_attr):
return getattr(self, cache_attr)
found = False
if self.remote_field.through_fields is not None:
link_field_name = self.remote_field.through_fields[1]
else:
link_field_name = None
for f in self.remote_field.through._meta.fields:
if f.is_relation and f.remote_field.model == related.model:
if link_field_name is None and related.related_model == related.model:
# If this is an m2m-intermediate to self,
# the first foreign key you find will be
# the source column. Keep searching for
# the second foreign key.
if found:
setattr(self, cache_attr, getattr(f, attr))
break
else:
found = True
elif link_field_name is None or link_field_name == f.name:
setattr(self, cache_attr, getattr(f, attr))
break
return getattr(self, cache_attr)
def contribute_to_class(self, cls, name, **kwargs):
# To support multiple relations to self, it's useful to have a non-None
# related name on symmetrical relations for internal reasons. The
# concept doesn't make a lot of sense externally ("you want me to
# specify *what* on my non-reversible relation?!"), so we set it up
# automatically. The funky name reduces the chance of an accidental
# clash.
if self.remote_field.symmetrical and (
self.remote_field.model == "self" or self.remote_field.model == cls._meta.object_name):
self.remote_field.related_name = "%s_rel_+" % name
elif self.remote_field.is_hidden():
# If the backwards relation is disabled, replace the original
# related_name with one generated from the m2m field name. Django
# still uses backwards relations internally and we need to avoid
# clashes between multiple m2m fields with related_name == '+'.
self.remote_field.related_name = "_%s_%s_+" % (cls.__name__.lower(), name)
super(ManyToManyField, self).contribute_to_class(cls, name, **kwargs)
# The intermediate m2m model is not auto created if:
# 1) There is a manually specified intermediate, or
# 2) The class owning the m2m field is abstract.
# 3) The class owning the m2m field has been swapped out.
if not cls._meta.abstract:
if self.remote_field.through:
def resolve_through_model(_, model, field):
field.remote_field.through = model
lazy_related_operation(resolve_through_model, cls, self.remote_field.through, field=self)
elif not cls._meta.swapped:
self.remote_field.through = create_many_to_many_intermediary_model(self, cls)
# Add the descriptor for the m2m relation.
setattr(cls, self.name, ManyToManyDescriptor(self.remote_field, reverse=False))
# Set up the accessor for the m2m table name for the relation.
self.m2m_db_table = curry(self._get_m2m_db_table, cls._meta)
def contribute_to_related_class(self, cls, related):
# Internal M2Ms (i.e., those with a related name ending with '+')
# and swapped models don't get a related descriptor.
if not self.remote_field.is_hidden() and not related.related_model._meta.swapped:
setattr(cls, related.get_accessor_name(), ManyToManyDescriptor(self.remote_field, reverse=True))
# Set up the accessors for the column names on the m2m table.
self.m2m_column_name = curry(self._get_m2m_attr, related, 'column')
self.m2m_reverse_name = curry(self._get_m2m_reverse_attr, related, 'column')
self.m2m_field_name = curry(self._get_m2m_attr, related, 'name')
self.m2m_reverse_field_name = curry(self._get_m2m_reverse_attr, related, 'name')
get_m2m_rel = curry(self._get_m2m_attr, related, 'remote_field')
self.m2m_target_field_name = lambda: get_m2m_rel().field_name
get_m2m_reverse_rel = curry(self._get_m2m_reverse_attr, related, 'remote_field')
self.m2m_reverse_target_field_name = lambda: get_m2m_reverse_rel().field_name
def set_attributes_from_rel(self):
pass
def value_from_object(self, obj):
"""
Return the value of this field in the given model instance.
"""
if obj.pk is None:
return self.related_model.objects.none()
return getattr(obj, self.attname).all()
def save_form_data(self, instance, data):
getattr(instance, self.attname).set(data)
def formfield(self, **kwargs):
db = kwargs.pop('using', None)
defaults = {
'form_class': forms.ModelMultipleChoiceField,
'queryset': self.remote_field.model._default_manager.using(db),
}
defaults.update(kwargs)
# If initial is passed in, it's a list of related objects, but the
# MultipleChoiceField takes a list of IDs.
if defaults.get('initial') is not None:
initial = defaults['initial']
if callable(initial):
initial = initial()
defaults['initial'] = [i._get_pk_val() for i in initial]
return super(ManyToManyField, self).formfield(**defaults)
def db_check(self, connection):
return None
def db_type(self, connection):
# A ManyToManyField is not represented by a single column,
# so return None.
return None
def db_parameters(self, connection):
return {"type": None, "check": None}
| mit |
noxora/flask-base | flask/lib/python3.4/site-packages/pip/_vendor/html5lib/_inputstream.py | 328 | 32532 | from __future__ import absolute_import, division, unicode_literals
from pip._vendor.six import text_type, binary_type
from pip._vendor.six.moves import http_client, urllib
import codecs
import re
from pip._vendor import webencodings
from .constants import EOF, spaceCharacters, asciiLetters, asciiUppercase
from .constants import ReparseException
from . import _utils
from io import StringIO
try:
from io import BytesIO
except ImportError:
BytesIO = StringIO
# Non-unicode versions of constants for use in the pre-parser
spaceCharactersBytes = frozenset([item.encode("ascii") for item in spaceCharacters])
asciiLettersBytes = frozenset([item.encode("ascii") for item in asciiLetters])
asciiUppercaseBytes = frozenset([item.encode("ascii") for item in asciiUppercase])
spacesAngleBrackets = spaceCharactersBytes | frozenset([b">", b"<"])
invalid_unicode_no_surrogate = "[\u0001-\u0008\u000B\u000E-\u001F\u007F-\u009F\uFDD0-\uFDEF\uFFFE\uFFFF\U0001FFFE\U0001FFFF\U0002FFFE\U0002FFFF\U0003FFFE\U0003FFFF\U0004FFFE\U0004FFFF\U0005FFFE\U0005FFFF\U0006FFFE\U0006FFFF\U0007FFFE\U0007FFFF\U0008FFFE\U0008FFFF\U0009FFFE\U0009FFFF\U000AFFFE\U000AFFFF\U000BFFFE\U000BFFFF\U000CFFFE\U000CFFFF\U000DFFFE\U000DFFFF\U000EFFFE\U000EFFFF\U000FFFFE\U000FFFFF\U0010FFFE\U0010FFFF]" # noqa
if _utils.supports_lone_surrogates:
# Use one extra step of indirection and create surrogates with
# eval. Not using this indirection would introduce an illegal
# unicode literal on platforms not supporting such lone
# surrogates.
assert invalid_unicode_no_surrogate[-1] == "]" and invalid_unicode_no_surrogate.count("]") == 1
invalid_unicode_re = re.compile(invalid_unicode_no_surrogate[:-1] +
eval('"\\uD800-\\uDFFF"') + # pylint:disable=eval-used
"]")
else:
invalid_unicode_re = re.compile(invalid_unicode_no_surrogate)
non_bmp_invalid_codepoints = set([0x1FFFE, 0x1FFFF, 0x2FFFE, 0x2FFFF, 0x3FFFE,
0x3FFFF, 0x4FFFE, 0x4FFFF, 0x5FFFE, 0x5FFFF,
0x6FFFE, 0x6FFFF, 0x7FFFE, 0x7FFFF, 0x8FFFE,
0x8FFFF, 0x9FFFE, 0x9FFFF, 0xAFFFE, 0xAFFFF,
0xBFFFE, 0xBFFFF, 0xCFFFE, 0xCFFFF, 0xDFFFE,
0xDFFFF, 0xEFFFE, 0xEFFFF, 0xFFFFE, 0xFFFFF,
0x10FFFE, 0x10FFFF])
ascii_punctuation_re = re.compile("[\u0009-\u000D\u0020-\u002F\u003A-\u0040\u005B-\u0060\u007B-\u007E]")
# Cache for charsUntil()
charsUntilRegEx = {}
class BufferedStream(object):
"""Buffering for streams that do not have buffering of their own
The buffer is implemented as a list of chunks on the assumption that
joining many strings will be slow since it is O(n**2)
"""
def __init__(self, stream):
self.stream = stream
self.buffer = []
self.position = [-1, 0] # chunk number, offset
def tell(self):
pos = 0
for chunk in self.buffer[:self.position[0]]:
pos += len(chunk)
pos += self.position[1]
return pos
def seek(self, pos):
assert pos <= self._bufferedBytes()
offset = pos
i = 0
while len(self.buffer[i]) < offset:
offset -= len(self.buffer[i])
i += 1
self.position = [i, offset]
def read(self, bytes):
if not self.buffer:
return self._readStream(bytes)
elif (self.position[0] == len(self.buffer) and
self.position[1] == len(self.buffer[-1])):
return self._readStream(bytes)
else:
return self._readFromBuffer(bytes)
def _bufferedBytes(self):
return sum([len(item) for item in self.buffer])
def _readStream(self, bytes):
data = self.stream.read(bytes)
self.buffer.append(data)
self.position[0] += 1
self.position[1] = len(data)
return data
def _readFromBuffer(self, bytes):
remainingBytes = bytes
rv = []
bufferIndex = self.position[0]
bufferOffset = self.position[1]
while bufferIndex < len(self.buffer) and remainingBytes != 0:
assert remainingBytes > 0
bufferedData = self.buffer[bufferIndex]
if remainingBytes <= len(bufferedData) - bufferOffset:
bytesToRead = remainingBytes
self.position = [bufferIndex, bufferOffset + bytesToRead]
else:
bytesToRead = len(bufferedData) - bufferOffset
self.position = [bufferIndex, len(bufferedData)]
bufferIndex += 1
rv.append(bufferedData[bufferOffset:bufferOffset + bytesToRead])
remainingBytes -= bytesToRead
bufferOffset = 0
if remainingBytes:
rv.append(self._readStream(remainingBytes))
return b"".join(rv)
def HTMLInputStream(source, **kwargs):
# Work around Python bug #20007: read(0) closes the connection.
# http://bugs.python.org/issue20007
if (isinstance(source, http_client.HTTPResponse) or
# Also check for addinfourl wrapping HTTPResponse
(isinstance(source, urllib.response.addbase) and
isinstance(source.fp, http_client.HTTPResponse))):
isUnicode = False
elif hasattr(source, "read"):
isUnicode = isinstance(source.read(0), text_type)
else:
isUnicode = isinstance(source, text_type)
if isUnicode:
encodings = [x for x in kwargs if x.endswith("_encoding")]
if encodings:
raise TypeError("Cannot set an encoding with a unicode input, set %r" % encodings)
return HTMLUnicodeInputStream(source, **kwargs)
else:
return HTMLBinaryInputStream(source, **kwargs)
class HTMLUnicodeInputStream(object):
"""Provides a unicode stream of characters to the HTMLTokenizer.
This class takes care of character encoding and removing or replacing
incorrect byte-sequences and also provides column and line tracking.
"""
_defaultChunkSize = 10240
def __init__(self, source):
"""Initialises the HTMLInputStream.
HTMLInputStream(source, [encoding]) -> Normalized stream from source
for use by html5lib.
source can be either a file-object, local filename or a string.
The optional encoding parameter must be a string that indicates
the encoding. If specified, that encoding will be used,
regardless of any BOM or later declaration (such as in a meta
element)
"""
if not _utils.supports_lone_surrogates:
# Such platforms will have already checked for such
# surrogate errors, so no need to do this checking.
self.reportCharacterErrors = None
elif len("\U0010FFFF") == 1:
self.reportCharacterErrors = self.characterErrorsUCS4
else:
self.reportCharacterErrors = self.characterErrorsUCS2
# List of where new lines occur
self.newLines = [0]
self.charEncoding = (lookupEncoding("utf-8"), "certain")
self.dataStream = self.openStream(source)
self.reset()
def reset(self):
self.chunk = ""
self.chunkSize = 0
self.chunkOffset = 0
self.errors = []
# number of (complete) lines in previous chunks
self.prevNumLines = 0
# number of columns in the last line of the previous chunk
self.prevNumCols = 0
# Deal with CR LF and surrogates split over chunk boundaries
self._bufferedCharacter = None
def openStream(self, source):
"""Produces a file object from source.
source can be either a file object, local filename or a string.
"""
# Already a file object
if hasattr(source, 'read'):
stream = source
else:
stream = StringIO(source)
return stream
def _position(self, offset):
chunk = self.chunk
nLines = chunk.count('\n', 0, offset)
positionLine = self.prevNumLines + nLines
lastLinePos = chunk.rfind('\n', 0, offset)
if lastLinePos == -1:
positionColumn = self.prevNumCols + offset
else:
positionColumn = offset - (lastLinePos + 1)
return (positionLine, positionColumn)
def position(self):
"""Returns (line, col) of the current position in the stream."""
line, col = self._position(self.chunkOffset)
return (line + 1, col)
def char(self):
""" Read one character from the stream or queue if available. Return
EOF when EOF is reached.
"""
# Read a new chunk from the input stream if necessary
if self.chunkOffset >= self.chunkSize:
if not self.readChunk():
return EOF
chunkOffset = self.chunkOffset
char = self.chunk[chunkOffset]
self.chunkOffset = chunkOffset + 1
return char
def readChunk(self, chunkSize=None):
if chunkSize is None:
chunkSize = self._defaultChunkSize
self.prevNumLines, self.prevNumCols = self._position(self.chunkSize)
self.chunk = ""
self.chunkSize = 0
self.chunkOffset = 0
data = self.dataStream.read(chunkSize)
# Deal with CR LF and surrogates broken across chunks
if self._bufferedCharacter:
data = self._bufferedCharacter + data
self._bufferedCharacter = None
elif not data:
# We have no more data, bye-bye stream
return False
if len(data) > 1:
lastv = ord(data[-1])
if lastv == 0x0D or 0xD800 <= lastv <= 0xDBFF:
self._bufferedCharacter = data[-1]
data = data[:-1]
if self.reportCharacterErrors:
self.reportCharacterErrors(data)
# Replace invalid characters
data = data.replace("\r\n", "\n")
data = data.replace("\r", "\n")
self.chunk = data
self.chunkSize = len(data)
return True
def characterErrorsUCS4(self, data):
for _ in range(len(invalid_unicode_re.findall(data))):
self.errors.append("invalid-codepoint")
def characterErrorsUCS2(self, data):
# Someone picked the wrong compile option
# You lose
skip = False
for match in invalid_unicode_re.finditer(data):
if skip:
continue
codepoint = ord(match.group())
pos = match.start()
# Pretty sure there should be endianness issues here
if _utils.isSurrogatePair(data[pos:pos + 2]):
# We have a surrogate pair!
char_val = _utils.surrogatePairToCodepoint(data[pos:pos + 2])
if char_val in non_bmp_invalid_codepoints:
self.errors.append("invalid-codepoint")
skip = True
elif (codepoint >= 0xD800 and codepoint <= 0xDFFF and
pos == len(data) - 1):
self.errors.append("invalid-codepoint")
else:
skip = False
self.errors.append("invalid-codepoint")
def charsUntil(self, characters, opposite=False):
""" Returns a string of characters from the stream up to but not
including any character in 'characters' or EOF. 'characters' must be
a container that supports the 'in' method and iteration over its
characters.
"""
# Use a cache of regexps to find the required characters
try:
chars = charsUntilRegEx[(characters, opposite)]
except KeyError:
if __debug__:
for c in characters:
assert(ord(c) < 128)
regex = "".join(["\\x%02x" % ord(c) for c in characters])
if not opposite:
regex = "^%s" % regex
chars = charsUntilRegEx[(characters, opposite)] = re.compile("[%s]+" % regex)
rv = []
while True:
# Find the longest matching prefix
m = chars.match(self.chunk, self.chunkOffset)
if m is None:
# If nothing matched, and it wasn't because we ran out of chunk,
# then stop
if self.chunkOffset != self.chunkSize:
break
else:
end = m.end()
# If not the whole chunk matched, return everything
# up to the part that didn't match
if end != self.chunkSize:
rv.append(self.chunk[self.chunkOffset:end])
self.chunkOffset = end
break
# If the whole remainder of the chunk matched,
# use it all and read the next chunk
rv.append(self.chunk[self.chunkOffset:])
if not self.readChunk():
# Reached EOF
break
r = "".join(rv)
return r
def unget(self, char):
# Only one character is allowed to be ungotten at once - it must
# be consumed again before any further call to unget
if char is not None:
if self.chunkOffset == 0:
# unget is called quite rarely, so it's a good idea to do
# more work here if it saves a bit of work in the frequently
# called char and charsUntil.
# So, just prepend the ungotten character onto the current
# chunk:
self.chunk = char + self.chunk
self.chunkSize += 1
else:
self.chunkOffset -= 1
assert self.chunk[self.chunkOffset] == char
class HTMLBinaryInputStream(HTMLUnicodeInputStream):
"""Provides a unicode stream of characters to the HTMLTokenizer.
This class takes care of character encoding and removing or replacing
incorrect byte-sequences and also provides column and line tracking.
"""
def __init__(self, source, override_encoding=None, transport_encoding=None,
same_origin_parent_encoding=None, likely_encoding=None,
default_encoding="windows-1252", useChardet=True):
"""Initialises the HTMLInputStream.
HTMLInputStream(source, [encoding]) -> Normalized stream from source
for use by html5lib.
source can be either a file-object, local filename or a string.
The optional encoding parameter must be a string that indicates
the encoding. If specified, that encoding will be used,
regardless of any BOM or later declaration (such as in a meta
element)
"""
# Raw Stream - for unicode objects this will encode to utf-8 and set
# self.charEncoding as appropriate
self.rawStream = self.openStream(source)
HTMLUnicodeInputStream.__init__(self, self.rawStream)
# Encoding Information
# Number of bytes to use when looking for a meta element with
# encoding information
self.numBytesMeta = 1024
# Number of bytes to use when using detecting encoding using chardet
self.numBytesChardet = 100
# Things from args
self.override_encoding = override_encoding
self.transport_encoding = transport_encoding
self.same_origin_parent_encoding = same_origin_parent_encoding
self.likely_encoding = likely_encoding
self.default_encoding = default_encoding
# Determine encoding
self.charEncoding = self.determineEncoding(useChardet)
assert self.charEncoding[0] is not None
# Call superclass
self.reset()
def reset(self):
self.dataStream = self.charEncoding[0].codec_info.streamreader(self.rawStream, 'replace')
HTMLUnicodeInputStream.reset(self)
def openStream(self, source):
"""Produces a file object from source.
source can be either a file object, local filename or a string.
"""
# Already a file object
if hasattr(source, 'read'):
stream = source
else:
stream = BytesIO(source)
try:
stream.seek(stream.tell())
except: # pylint:disable=bare-except
stream = BufferedStream(stream)
return stream
def determineEncoding(self, chardet=True):
# BOMs take precedence over everything
# This will also read past the BOM if present
charEncoding = self.detectBOM(), "certain"
if charEncoding[0] is not None:
return charEncoding
# If we've been overriden, we've been overriden
charEncoding = lookupEncoding(self.override_encoding), "certain"
if charEncoding[0] is not None:
return charEncoding
# Now check the transport layer
charEncoding = lookupEncoding(self.transport_encoding), "certain"
if charEncoding[0] is not None:
return charEncoding
# Look for meta elements with encoding information
charEncoding = self.detectEncodingMeta(), "tentative"
if charEncoding[0] is not None:
return charEncoding
# Parent document encoding
charEncoding = lookupEncoding(self.same_origin_parent_encoding), "tentative"
if charEncoding[0] is not None and not charEncoding[0].name.startswith("utf-16"):
return charEncoding
# "likely" encoding
charEncoding = lookupEncoding(self.likely_encoding), "tentative"
if charEncoding[0] is not None:
return charEncoding
# Guess with chardet, if available
if chardet:
try:
from chardet.universaldetector import UniversalDetector
except ImportError:
pass
else:
buffers = []
detector = UniversalDetector()
while not detector.done:
buffer = self.rawStream.read(self.numBytesChardet)
assert isinstance(buffer, bytes)
if not buffer:
break
buffers.append(buffer)
detector.feed(buffer)
detector.close()
encoding = lookupEncoding(detector.result['encoding'])
self.rawStream.seek(0)
if encoding is not None:
return encoding, "tentative"
# Try the default encoding
charEncoding = lookupEncoding(self.default_encoding), "tentative"
if charEncoding[0] is not None:
return charEncoding
# Fallback to html5lib's default if even that hasn't worked
return lookupEncoding("windows-1252"), "tentative"
def changeEncoding(self, newEncoding):
assert self.charEncoding[1] != "certain"
newEncoding = lookupEncoding(newEncoding)
if newEncoding is None:
return
if newEncoding.name in ("utf-16be", "utf-16le"):
newEncoding = lookupEncoding("utf-8")
assert newEncoding is not None
elif newEncoding == self.charEncoding[0]:
self.charEncoding = (self.charEncoding[0], "certain")
else:
self.rawStream.seek(0)
self.charEncoding = (newEncoding, "certain")
self.reset()
raise ReparseException("Encoding changed from %s to %s" % (self.charEncoding[0], newEncoding))
def detectBOM(self):
"""Attempts to detect at BOM at the start of the stream. If
an encoding can be determined from the BOM return the name of the
encoding otherwise return None"""
bomDict = {
codecs.BOM_UTF8: 'utf-8',
codecs.BOM_UTF16_LE: 'utf-16le', codecs.BOM_UTF16_BE: 'utf-16be',
codecs.BOM_UTF32_LE: 'utf-32le', codecs.BOM_UTF32_BE: 'utf-32be'
}
# Go to beginning of file and read in 4 bytes
string = self.rawStream.read(4)
assert isinstance(string, bytes)
# Try detecting the BOM using bytes from the string
encoding = bomDict.get(string[:3]) # UTF-8
seek = 3
if not encoding:
# Need to detect UTF-32 before UTF-16
encoding = bomDict.get(string) # UTF-32
seek = 4
if not encoding:
encoding = bomDict.get(string[:2]) # UTF-16
seek = 2
# Set the read position past the BOM if one was found, otherwise
# set it to the start of the stream
if encoding:
self.rawStream.seek(seek)
return lookupEncoding(encoding)
else:
self.rawStream.seek(0)
return None
def detectEncodingMeta(self):
"""Report the encoding declared by the meta element
"""
buffer = self.rawStream.read(self.numBytesMeta)
assert isinstance(buffer, bytes)
parser = EncodingParser(buffer)
self.rawStream.seek(0)
encoding = parser.getEncoding()
if encoding is not None and encoding.name in ("utf-16be", "utf-16le"):
encoding = lookupEncoding("utf-8")
return encoding
class EncodingBytes(bytes):
"""String-like object with an associated position and various extra methods
If the position is ever greater than the string length then an exception is
raised"""
def __new__(self, value):
assert isinstance(value, bytes)
return bytes.__new__(self, value.lower())
def __init__(self, value):
# pylint:disable=unused-argument
self._position = -1
def __iter__(self):
return self
def __next__(self):
p = self._position = self._position + 1
if p >= len(self):
raise StopIteration
elif p < 0:
raise TypeError
return self[p:p + 1]
def next(self):
# Py2 compat
return self.__next__()
def previous(self):
p = self._position
if p >= len(self):
raise StopIteration
elif p < 0:
raise TypeError
self._position = p = p - 1
return self[p:p + 1]
def setPosition(self, position):
if self._position >= len(self):
raise StopIteration
self._position = position
def getPosition(self):
if self._position >= len(self):
raise StopIteration
if self._position >= 0:
return self._position
else:
return None
position = property(getPosition, setPosition)
def getCurrentByte(self):
return self[self.position:self.position + 1]
currentByte = property(getCurrentByte)
def skip(self, chars=spaceCharactersBytes):
"""Skip past a list of characters"""
p = self.position # use property for the error-checking
while p < len(self):
c = self[p:p + 1]
if c not in chars:
self._position = p
return c
p += 1
self._position = p
return None
def skipUntil(self, chars):
p = self.position
while p < len(self):
c = self[p:p + 1]
if c in chars:
self._position = p
return c
p += 1
self._position = p
return None
def matchBytes(self, bytes):
"""Look for a sequence of bytes at the start of a string. If the bytes
are found return True and advance the position to the byte after the
match. Otherwise return False and leave the position alone"""
p = self.position
data = self[p:p + len(bytes)]
rv = data.startswith(bytes)
if rv:
self.position += len(bytes)
return rv
def jumpTo(self, bytes):
"""Look for the next sequence of bytes matching a given sequence. If
a match is found advance the position to the last byte of the match"""
newPosition = self[self.position:].find(bytes)
if newPosition > -1:
# XXX: This is ugly, but I can't see a nicer way to fix this.
if self._position == -1:
self._position = 0
self._position += (newPosition + len(bytes) - 1)
return True
else:
raise StopIteration
class EncodingParser(object):
"""Mini parser for detecting character encoding from meta elements"""
def __init__(self, data):
"""string - the data to work on for encoding detection"""
self.data = EncodingBytes(data)
self.encoding = None
def getEncoding(self):
methodDispatch = (
(b"<!--", self.handleComment),
(b"<meta", self.handleMeta),
(b"</", self.handlePossibleEndTag),
(b"<!", self.handleOther),
(b"<?", self.handleOther),
(b"<", self.handlePossibleStartTag))
for _ in self.data:
keepParsing = True
for key, method in methodDispatch:
if self.data.matchBytes(key):
try:
keepParsing = method()
break
except StopIteration:
keepParsing = False
break
if not keepParsing:
break
return self.encoding
def handleComment(self):
"""Skip over comments"""
return self.data.jumpTo(b"-->")
def handleMeta(self):
if self.data.currentByte not in spaceCharactersBytes:
# if we have <meta not followed by a space so just keep going
return True
# We have a valid meta element we want to search for attributes
hasPragma = False
pendingEncoding = None
while True:
# Try to find the next attribute after the current position
attr = self.getAttribute()
if attr is None:
return True
else:
if attr[0] == b"http-equiv":
hasPragma = attr[1] == b"content-type"
if hasPragma and pendingEncoding is not None:
self.encoding = pendingEncoding
return False
elif attr[0] == b"charset":
tentativeEncoding = attr[1]
codec = lookupEncoding(tentativeEncoding)
if codec is not None:
self.encoding = codec
return False
elif attr[0] == b"content":
contentParser = ContentAttrParser(EncodingBytes(attr[1]))
tentativeEncoding = contentParser.parse()
if tentativeEncoding is not None:
codec = lookupEncoding(tentativeEncoding)
if codec is not None:
if hasPragma:
self.encoding = codec
return False
else:
pendingEncoding = codec
def handlePossibleStartTag(self):
return self.handlePossibleTag(False)
def handlePossibleEndTag(self):
next(self.data)
return self.handlePossibleTag(True)
def handlePossibleTag(self, endTag):
data = self.data
if data.currentByte not in asciiLettersBytes:
# If the next byte is not an ascii letter either ignore this
# fragment (possible start tag case) or treat it according to
# handleOther
if endTag:
data.previous()
self.handleOther()
return True
c = data.skipUntil(spacesAngleBrackets)
if c == b"<":
# return to the first step in the overall "two step" algorithm
# reprocessing the < byte
data.previous()
else:
# Read all attributes
attr = self.getAttribute()
while attr is not None:
attr = self.getAttribute()
return True
def handleOther(self):
return self.data.jumpTo(b">")
def getAttribute(self):
"""Return a name,value pair for the next attribute in the stream,
if one is found, or None"""
data = self.data
# Step 1 (skip chars)
c = data.skip(spaceCharactersBytes | frozenset([b"/"]))
assert c is None or len(c) == 1
# Step 2
if c in (b">", None):
return None
# Step 3
attrName = []
attrValue = []
# Step 4 attribute name
while True:
if c == b"=" and attrName:
break
elif c in spaceCharactersBytes:
# Step 6!
c = data.skip()
break
elif c in (b"/", b">"):
return b"".join(attrName), b""
elif c in asciiUppercaseBytes:
attrName.append(c.lower())
elif c is None:
return None
else:
attrName.append(c)
# Step 5
c = next(data)
# Step 7
if c != b"=":
data.previous()
return b"".join(attrName), b""
# Step 8
next(data)
# Step 9
c = data.skip()
# Step 10
if c in (b"'", b'"'):
# 10.1
quoteChar = c
while True:
# 10.2
c = next(data)
# 10.3
if c == quoteChar:
next(data)
return b"".join(attrName), b"".join(attrValue)
# 10.4
elif c in asciiUppercaseBytes:
attrValue.append(c.lower())
# 10.5
else:
attrValue.append(c)
elif c == b">":
return b"".join(attrName), b""
elif c in asciiUppercaseBytes:
attrValue.append(c.lower())
elif c is None:
return None
else:
attrValue.append(c)
# Step 11
while True:
c = next(data)
if c in spacesAngleBrackets:
return b"".join(attrName), b"".join(attrValue)
elif c in asciiUppercaseBytes:
attrValue.append(c.lower())
elif c is None:
return None
else:
attrValue.append(c)
class ContentAttrParser(object):
def __init__(self, data):
assert isinstance(data, bytes)
self.data = data
def parse(self):
try:
# Check if the attr name is charset
# otherwise return
self.data.jumpTo(b"charset")
self.data.position += 1
self.data.skip()
if not self.data.currentByte == b"=":
# If there is no = sign keep looking for attrs
return None
self.data.position += 1
self.data.skip()
# Look for an encoding between matching quote marks
if self.data.currentByte in (b'"', b"'"):
quoteMark = self.data.currentByte
self.data.position += 1
oldPosition = self.data.position
if self.data.jumpTo(quoteMark):
return self.data[oldPosition:self.data.position]
else:
return None
else:
# Unquoted value
oldPosition = self.data.position
try:
self.data.skipUntil(spaceCharactersBytes)
return self.data[oldPosition:self.data.position]
except StopIteration:
# Return the whole remaining value
return self.data[oldPosition:]
except StopIteration:
return None
def lookupEncoding(encoding):
"""Return the python codec name corresponding to an encoding or None if the
string doesn't correspond to a valid encoding."""
if isinstance(encoding, binary_type):
try:
encoding = encoding.decode("ascii")
except UnicodeDecodeError:
return None
if encoding is not None:
try:
return webencodings.lookup(encoding)
except AttributeError:
return None
else:
return None
| mit |
KohlsTechnology/ansible | lib/ansible/modules/system/lvg.py | 8 | 9852 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2013, Alexander Bulimov <lazywolf0@gmail.com>
# Based on lvol module by Jeroen Hoekx <jeroen.hoekx@dsquare.be>
# 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 = '''
---
author:
- Alexander Bulimov (@abulimov)
module: lvg
short_description: Configure LVM volume groups
description:
- This module creates, removes or resizes volume groups.
version_added: "1.1"
options:
vg:
description:
- The name of the volume group.
required: true
pvs:
description:
- List of comma-separated devices to use as physical devices in this volume group. Required when creating or resizing volume group.
- The module will take care of running pvcreate if needed.
pesize:
description:
- The size of the physical extent in megabytes. Must be a power of 2.
default: 4
pv_options:
description:
- Additional options to pass to C(pvcreate) when creating the volume group.
version_added: "2.4"
vg_options:
description:
- Additional options to pass to C(vgcreate) when creating the volume group.
version_added: "1.6"
state:
description:
- Control if the volume group exists.
choices: [ absent, present ]
default: present
force:
description:
- If C(yes), allows to remove volume group with logical volumes.
type: bool
default: 'no'
notes:
- This module does not modify PE size for already present volume group.
'''
EXAMPLES = '''
- name: Create a volume group on top of /dev/sda1 with physical extent size = 32MB
lvg:
vg: vg.services
pvs: /dev/sda1
pesize: 32
# If, for example, we already have VG vg.services on top of /dev/sdb1,
# this VG will be extended by /dev/sdc5. Or if vg.services was created on
# top of /dev/sda5, we first extend it with /dev/sdb1 and /dev/sdc5,
# and then reduce by /dev/sda5.
- name: Create or resize a volume group on top of /dev/sdb1 and /dev/sdc5.
lvg:
vg: vg.services
pvs: /dev/sdb1,/dev/sdc5
- name: Remove a volume group with name vg.services
lvg:
vg: vg.services
state: absent
'''
import os
from ansible.module_utils.basic import AnsibleModule
def parse_vgs(data):
vgs = []
for line in data.splitlines():
parts = line.strip().split(';')
vgs.append({
'name': parts[0],
'pv_count': int(parts[1]),
'lv_count': int(parts[2]),
})
return vgs
def find_mapper_device_name(module, dm_device):
dmsetup_cmd = module.get_bin_path('dmsetup', True)
mapper_prefix = '/dev/mapper/'
rc, dm_name, err = module.run_command("%s info -C --noheadings -o name %s" % (dmsetup_cmd, dm_device))
if rc != 0:
module.fail_json(msg="Failed executing dmsetup command.", rc=rc, err=err)
mapper_device = mapper_prefix + dm_name.rstrip()
return mapper_device
def parse_pvs(module, data):
pvs = []
dm_prefix = '/dev/dm-'
for line in data.splitlines():
parts = line.strip().split(';')
if parts[0].startswith(dm_prefix):
parts[0] = find_mapper_device_name(module, parts[0])
pvs.append({
'name': parts[0],
'vg_name': parts[1],
})
return pvs
def main():
module = AnsibleModule(
argument_spec=dict(
vg=dict(type='str', required=True),
pvs=dict(type='list'),
pesize=dict(type='int', default=4),
pv_options=dict(type='str', default=''),
vg_options=dict(type='str', default=''),
state=dict(type='str', default='present', choices=['absent', 'present']),
force=dict(type='bool', default=False),
),
supports_check_mode=True,
)
vg = module.params['vg']
state = module.params['state']
force = module.boolean(module.params['force'])
pesize = module.params['pesize']
pvoptions = module.params['pv_options'].split()
vgoptions = module.params['vg_options'].split()
dev_list = []
if module.params['pvs']:
dev_list = module.params['pvs']
elif state == 'present':
module.fail_json(msg="No physical volumes given.")
# LVM always uses real paths not symlinks so replace symlinks with actual path
for idx, dev in enumerate(dev_list):
dev_list[idx] = os.path.realpath(dev)
if state == 'present':
# check given devices
for test_dev in dev_list:
if not os.path.exists(test_dev):
module.fail_json(msg="Device %s not found." % test_dev)
# get pv list
pvs_cmd = module.get_bin_path('pvs', True)
if dev_list:
pvs_filter = ' || '. join(['pv_name = {0}'.format(x) for x in dev_list])
pvs_filter = "--select '%s'" % pvs_filter
else:
pvs_filter = ''
rc, current_pvs, err = module.run_command("%s --noheadings -o pv_name,vg_name --separator ';' %s" % (pvs_cmd, pvs_filter))
if rc != 0:
module.fail_json(msg="Failed executing pvs command.", rc=rc, err=err)
# check pv for devices
pvs = parse_pvs(module, current_pvs)
used_pvs = [pv for pv in pvs if pv['name'] in dev_list and pv['vg_name'] and pv['vg_name'] != vg]
if used_pvs:
module.fail_json(msg="Device %s is already in %s volume group." % (used_pvs[0]['name'], used_pvs[0]['vg_name']))
vgs_cmd = module.get_bin_path('vgs', True)
rc, current_vgs, err = module.run_command("%s --noheadings -o vg_name,pv_count,lv_count --separator ';'" % vgs_cmd)
if rc != 0:
module.fail_json(msg="Failed executing vgs command.", rc=rc, err=err)
changed = False
vgs = parse_vgs(current_vgs)
for test_vg in vgs:
if test_vg['name'] == vg:
this_vg = test_vg
break
else:
this_vg = None
if this_vg is None:
if state == 'present':
# create VG
if module.check_mode:
changed = True
else:
# create PV
pvcreate_cmd = module.get_bin_path('pvcreate', True)
for current_dev in dev_list:
rc, _, err = module.run_command([pvcreate_cmd] + pvoptions + ['-f', str(current_dev)])
if rc == 0:
changed = True
else:
module.fail_json(msg="Creating physical volume '%s' failed" % current_dev, rc=rc, err=err)
vgcreate_cmd = module.get_bin_path('vgcreate')
rc, _, err = module.run_command([vgcreate_cmd] + vgoptions + ['-s', str(pesize), vg] + dev_list)
if rc == 0:
changed = True
else:
module.fail_json(msg="Creating volume group '%s' failed" % vg, rc=rc, err=err)
else:
if state == 'absent':
if module.check_mode:
module.exit_json(changed=True)
else:
if this_vg['lv_count'] == 0 or force:
# remove VG
vgremove_cmd = module.get_bin_path('vgremove', True)
rc, _, err = module.run_command("%s --force %s" % (vgremove_cmd, vg))
if rc == 0:
module.exit_json(changed=True)
else:
module.fail_json(msg="Failed to remove volume group %s" % (vg), rc=rc, err=err)
else:
module.fail_json(msg="Refuse to remove non-empty volume group %s without force=yes" % (vg))
# resize VG
current_devs = [os.path.realpath(pv['name']) for pv in pvs if pv['vg_name'] == vg]
devs_to_remove = list(set(current_devs) - set(dev_list))
devs_to_add = list(set(dev_list) - set(current_devs))
if devs_to_add or devs_to_remove:
if module.check_mode:
changed = True
else:
if devs_to_add:
devs_to_add_string = ' '.join(devs_to_add)
# create PV
pvcreate_cmd = module.get_bin_path('pvcreate', True)
for current_dev in devs_to_add:
rc, _, err = module.run_command([pvcreate_cmd] + pvoptions + ['-f', str(current_dev)])
if rc == 0:
changed = True
else:
module.fail_json(msg="Creating physical volume '%s' failed" % current_dev, rc=rc, err=err)
# add PV to our VG
vgextend_cmd = module.get_bin_path('vgextend', True)
rc, _, err = module.run_command("%s %s %s" % (vgextend_cmd, vg, devs_to_add_string))
if rc == 0:
changed = True
else:
module.fail_json(msg="Unable to extend %s by %s." % (vg, devs_to_add_string), rc=rc, err=err)
# remove some PV from our VG
if devs_to_remove:
devs_to_remove_string = ' '.join(devs_to_remove)
vgreduce_cmd = module.get_bin_path('vgreduce', True)
rc, _, err = module.run_command("%s --force %s %s" % (vgreduce_cmd, vg, devs_to_remove_string))
if rc == 0:
changed = True
else:
module.fail_json(msg="Unable to reduce %s by %s." % (vg, devs_to_remove_string), rc=rc, err=err)
module.exit_json(changed=changed)
if __name__ == '__main__':
main()
| gpl-3.0 |
Hiestaa/3D-Lsystem | lsystem/Tree7.py | 1 | 1145 | from lsystem.LSystem import LSystem
import math
class Tree7(LSystem):
"""Fractale en forme d'arbre v7"""
def defineParams(self):
self.LSName = "Tree7"
self.LSAngle = math.pi / 4
self.LSSegment = 100
self.LSSteps = 9
self.LSStartingString = "T(x)"
self.LSStochastic = False
self.LSStochRange = 0.2
def createVars(self):
self.LSVars = {
'F': self.turtle.forward,
'T': self.turtle.forward,
'+': self.turtle.rotZ,
'-': self.turtle.irotZ,
'^': self.turtle.rotY,
'&': self.turtle.irotY,
'<': self.turtle.rotX,
'>': self.turtle.irotX,
'|': self.turtle.rotX,
'[': self.turtle.push,
']': self.turtle.pop,
'I': self.turtle.setColor,
'Y': self.turtle.setColor
}
self.LSParams = {
'x': self.LSSegment,
'+': self.LSAngle,
'-': self.LSAngle,
'&': self.LSAngle,
'^': self.LSAngle,
'<': self.LSAngle,
'>': self.LSAngle,
'|': self.LSAngle * 2,
'[': None,
']': None,
'I': (0.5,0.25,0),
'Y': (0, 0.5, 0)
}
def createRules(self):
self.LSRules = {
"T(x)": "IT(x*0.3)F(x*0.3)",
"F(x)": "IF(x)[+YF(x*0.5)][-YF(x*0.5)][<YF(x*0.5)][>YF(x*0.5)]"
}
| mit |
aquamatt/Peloton | src/peloton/exceptions.py | 1 | 1915 | # $Id: exceptions.py 117 2008-04-09 16:55:41Z mp $
#
# Copyright (c) 2007-2008 ReThought Limited and Peloton Contributors
# All Rights Reserved
# See LICENSE for details
""" All Peloton exceptions """
class PelotonError(Exception):
""" Base for all Peloton exceptions; can be used on its own
if no other exception is suitable. """
def __init__(self, msg='', rootException=None):
""" Initialise with an optional message and, optionally,
a root exception object - likely the underlying exception that resulted
in this exception being raised."""
Exception.__init__(self, msg)
self.rootException = rootException
def __str__(self):
""" Use base str but if there is a rootException add that message
to it. """
if self.rootException:
return "%s : Root exception: %s" % \
(Exception.__str__(self), str(self.rootException))
else:
return Exception.__str__(self)
class ConfigurationError(PelotonError):
"""To be raised when an error occurs reading a configuration file,
a profile file or similar; also any other configuration-related errors."""
pass
class PluginError(PelotonError):
""" To be raised on the whole if a general plugin error occurs; specific
plugins may wish to provide a little more specific exceptions. """
pass
class ServiceNotFoundError(PelotonError):
pass
class ServiceConfigurationError(PelotonError):
pass
class ServiceError(PelotonError):
pass
class MessagingError(PelotonError):
pass
class WorkerError(PelotonError):
""" Generic error raised if something untoward occurs in a worker
process. """
pass
class PelotonConnectionError(PelotonError):
pass
class NoWorkersError(PelotonError):
pass
class NoWorkersError(PelotonError):
pass
class DeadPeerError(PelotonError):
pass
class DeadProxyError(PelotonError):
pass | bsd-3-clause |
dennybaa/st2 | st2client/tests/unit/test_trace_commands.py | 8 | 8907 | # Licensed to the StackStorm, Inc ('StackStorm') 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 argparse
from tests import base
from st2client.commands import trace as trace_commands
from st2client.models import trace as trace_models
class TraceCommandTestCase(base.BaseCLITestCase):
def test_trace_get_filter_trace_components_executions(self):
trace = trace_models.Trace()
setattr(trace, 'action_executions',
[{'object_id': 'e1', 'caused_by': {'id': 'r1:t1', 'type': 'rule'}}])
setattr(trace, 'rules',
[{'object_id': 'r1', 'caused_by': {'id': 't1', 'type': 'trigger_instance'}}])
setattr(trace, 'trigger_instances',
[{'object_id': 't1', 'caused_by': {}},
{'object_id': 't2', 'caused_by': {'id': 'e1', 'type': 'execution'}}])
args = argparse.Namespace()
setattr(args, 'execution', 'e1')
setattr(args, 'show_executions', False)
setattr(args, 'show_rules', False)
setattr(args, 'show_trigger_instances', False)
setattr(args, 'hide_noop_triggers', False)
trace = trace_commands.TraceGetCommand._filter_trace_components(trace, args)
self.assertEquals(len(trace.action_executions), 1)
self.assertEquals(len(trace.rules), 1)
self.assertEquals(len(trace.trigger_instances), 1)
def test_trace_get_filter_trace_components_rules(self):
trace = trace_models.Trace()
setattr(trace, 'action_executions',
[{'object_id': 'e1', 'caused_by': {'id': 'r1:t1', 'type': 'rule'}}])
setattr(trace, 'rules',
[{'object_id': 'r1', 'caused_by': {'id': 't1', 'type': 'trigger_instance'}}])
setattr(trace, 'trigger_instances',
[{'object_id': 't1', 'caused_by': {}},
{'object_id': 't2', 'caused_by': {'id': 'e1', 'type': 'execution'}}])
args = argparse.Namespace()
setattr(args, 'execution', None)
setattr(args, 'rule', 'r1')
setattr(args, 'trigger_instance', None)
setattr(args, 'show_executions', False)
setattr(args, 'show_rules', False)
setattr(args, 'show_trigger_instances', False)
setattr(args, 'hide_noop_triggers', False)
trace = trace_commands.TraceGetCommand._filter_trace_components(trace, args)
self.assertEquals(len(trace.action_executions), 0)
self.assertEquals(len(trace.rules), 1)
self.assertEquals(len(trace.trigger_instances), 1)
def test_trace_get_filter_trace_components_trigger_instances(self):
trace = trace_models.Trace()
setattr(trace, 'action_executions',
[{'object_id': 'e1', 'caused_by': {'id': 'r1:t1', 'type': 'rule'}}])
setattr(trace, 'rules',
[{'object_id': 'r1', 'caused_by': {'id': 't1', 'type': 'trigger_instance'}}])
setattr(trace, 'trigger_instances',
[{'object_id': 't1', 'caused_by': {}},
{'object_id': 't2', 'caused_by': {'id': 'e1', 'type': 'execution'}}])
args = argparse.Namespace()
setattr(args, 'execution', None)
setattr(args, 'rule', None)
setattr(args, 'trigger_instance', 't1')
setattr(args, 'show_executions', False)
setattr(args, 'show_rules', False)
setattr(args, 'show_trigger_instances', False)
setattr(args, 'hide_noop_triggers', False)
trace = trace_commands.TraceGetCommand._filter_trace_components(trace, args)
self.assertEquals(len(trace.action_executions), 0)
self.assertEquals(len(trace.rules), 0)
self.assertEquals(len(trace.trigger_instances), 1)
def test_trace_get_apply_display_filters_show_executions(self):
trace = trace_models.Trace()
setattr(trace, 'action_executions', ['1'])
setattr(trace, 'rules', ['1'])
setattr(trace, 'trigger_instances', ['1'])
args = argparse.Namespace()
setattr(args, 'show_executions', True)
setattr(args, 'show_rules', False)
setattr(args, 'show_trigger_instances', False)
setattr(args, 'hide_noop_triggers', False)
trace = trace_commands.TraceGetCommand._apply_display_filters(trace, args)
self.assertTrue(trace.action_executions)
self.assertFalse(trace.rules)
self.assertFalse(trace.trigger_instances)
def test_trace_get_apply_display_filters_show_rules(self):
trace = trace_models.Trace()
setattr(trace, 'action_executions', ['1'])
setattr(trace, 'rules', ['1'])
setattr(trace, 'trigger_instances', ['1'])
args = argparse.Namespace()
setattr(args, 'show_executions', False)
setattr(args, 'show_rules', True)
setattr(args, 'show_trigger_instances', False)
setattr(args, 'hide_noop_triggers', False)
trace = trace_commands.TraceGetCommand._apply_display_filters(trace, args)
self.assertFalse(trace.action_executions)
self.assertTrue(trace.rules)
self.assertFalse(trace.trigger_instances)
def test_trace_get_apply_display_filters_show_trigger_instances(self):
trace = trace_models.Trace()
setattr(trace, 'action_executions', ['1'])
setattr(trace, 'rules', ['1'])
setattr(trace, 'trigger_instances', ['1'])
args = argparse.Namespace()
setattr(args, 'show_executions', False)
setattr(args, 'show_rules', False)
setattr(args, 'show_trigger_instances', True)
setattr(args, 'hide_noop_triggers', False)
trace = trace_commands.TraceGetCommand._apply_display_filters(trace, args)
self.assertFalse(trace.action_executions)
self.assertFalse(trace.rules)
self.assertTrue(trace.trigger_instances)
def test_trace_get_apply_display_filters_show_multiple(self):
trace = trace_models.Trace()
setattr(trace, 'action_executions', ['1'])
setattr(trace, 'rules', ['1'])
setattr(trace, 'trigger_instances', ['1'])
args = argparse.Namespace()
setattr(args, 'show_executions', True)
setattr(args, 'show_rules', True)
setattr(args, 'show_trigger_instances', False)
setattr(args, 'hide_noop_triggers', False)
trace = trace_commands.TraceGetCommand._apply_display_filters(trace, args)
self.assertTrue(trace.action_executions)
self.assertTrue(trace.rules)
self.assertFalse(trace.trigger_instances)
def test_trace_get_apply_display_filters_show_all(self):
trace = trace_models.Trace()
setattr(trace, 'action_executions', ['1'])
setattr(trace, 'rules', ['1'])
setattr(trace, 'trigger_instances', ['1'])
args = argparse.Namespace()
setattr(args, 'show_executions', False)
setattr(args, 'show_rules', False)
setattr(args, 'show_trigger_instances', False)
setattr(args, 'hide_noop_triggers', False)
trace = trace_commands.TraceGetCommand._apply_display_filters(trace, args)
self.assertEquals(len(trace.action_executions), 1)
self.assertEquals(len(trace.rules), 1)
self.assertEquals(len(trace.trigger_instances), 1)
def test_trace_get_apply_display_filters_hide_noop(self):
trace = trace_models.Trace()
setattr(trace, 'action_executions',
[{'object_id': 'e1', 'caused_by': {'id': 'r1:t1', 'type': 'rule'}}])
setattr(trace, 'rules',
[{'object_id': 'r1', 'caused_by': {'id': 't1', 'type': 'trigger_instance'}}])
setattr(trace, 'trigger_instances',
[{'object_id': 't1', 'caused_by': {}},
{'object_id': 't2', 'caused_by': {'id': 'e1', 'type': 'execution'}}])
args = argparse.Namespace()
setattr(args, 'show_executions', False)
setattr(args, 'show_rules', False)
setattr(args, 'show_trigger_instances', False)
setattr(args, 'hide_noop_triggers', True)
trace = trace_commands.TraceGetCommand._apply_display_filters(trace, args)
self.assertEquals(len(trace.action_executions), 1)
self.assertEquals(len(trace.rules), 1)
self.assertEquals(len(trace.trigger_instances), 1)
| apache-2.0 |
interactiveinstitute/elvis | server/tornado/test/wsgi_test.py | 40 | 3148 | from __future__ import absolute_import, division, print_function, with_statement
from wsgiref.validate import validator
from tornado.escape import json_decode
from tornado.test.httpserver_test import TypeCheckHandler
from tornado.testing import AsyncHTTPTestCase
from tornado.util import u
from tornado.web import RequestHandler
from tornado.wsgi import WSGIApplication, WSGIContainer
class WSGIContainerTest(AsyncHTTPTestCase):
def wsgi_app(self, environ, start_response):
status = "200 OK"
response_headers = [("Content-Type", "text/plain")]
start_response(status, response_headers)
return [b"Hello world!"]
def get_app(self):
return WSGIContainer(validator(self.wsgi_app))
def test_simple(self):
response = self.fetch("/")
self.assertEqual(response.body, b"Hello world!")
class WSGIApplicationTest(AsyncHTTPTestCase):
def get_app(self):
class HelloHandler(RequestHandler):
def get(self):
self.write("Hello world!")
class PathQuotingHandler(RequestHandler):
def get(self, path):
self.write(path)
# It would be better to run the wsgiref server implementation in
# another thread instead of using our own WSGIContainer, but this
# fits better in our async testing framework and the wsgiref
# validator should keep us honest
return WSGIContainer(validator(WSGIApplication([
("/", HelloHandler),
("/path/(.*)", PathQuotingHandler),
("/typecheck", TypeCheckHandler),
])))
def test_simple(self):
response = self.fetch("/")
self.assertEqual(response.body, b"Hello world!")
def test_path_quoting(self):
response = self.fetch("/path/foo%20bar%C3%A9")
self.assertEqual(response.body, u("foo bar\u00e9").encode("utf-8"))
def test_types(self):
headers = {"Cookie": "foo=bar"}
response = self.fetch("/typecheck?foo=bar", headers=headers)
data = json_decode(response.body)
self.assertEqual(data, {})
response = self.fetch("/typecheck", method="POST", body="foo=bar", headers=headers)
data = json_decode(response.body)
self.assertEqual(data, {})
# This is kind of hacky, but run some of the HTTPServer tests through
# WSGIContainer and WSGIApplication to make sure everything survives
# repeated disassembly and reassembly.
from tornado.test import httpserver_test
from tornado.test import web_test
class WSGIConnectionTest(httpserver_test.HTTPConnectionTest):
def get_app(self):
return WSGIContainer(validator(WSGIApplication(self.get_handlers())))
def wrap_web_tests():
result = {}
for cls in web_test.wsgi_safe_tests:
class WSGIWrappedTest(cls):
def get_app(self):
self.app = WSGIApplication(self.get_handlers(),
**self.get_app_kwargs())
return WSGIContainer(validator(self.app))
result["WSGIWrapped_" + cls.__name__] = WSGIWrappedTest
return result
globals().update(wrap_web_tests())
| gpl-3.0 |
kimjaejoong/nova | nova/api/openstack/compute/plugins/v3/tenant_networks.py | 18 | 8013 | # Copyright 2013 OpenStack Foundation
# 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.
import netaddr
import netaddr.core as netexc
from oslo_config import cfg
from oslo_log import log as logging
import six
from webob import exc
from nova.api.openstack.compute.schemas.v3 import tenant_networks as schema
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova.api import validation
from nova import context as nova_context
from nova import exception
from nova.i18n import _
from nova.i18n import _LE
import nova.network
from nova import quota
CONF = cfg.CONF
CONF.import_opt('enable_network_quota',
'nova.api.openstack.compute.contrib.os_tenant_networks')
CONF.import_opt('use_neutron_default_nets',
'nova.api.openstack.compute.contrib.os_tenant_networks')
CONF.import_opt('neutron_default_tenant_id',
'nova.api.openstack.compute.contrib.os_tenant_networks')
CONF.import_opt('quota_networks',
'nova.api.openstack.compute.contrib.os_tenant_networks')
ALIAS = 'os-tenant-networks'
QUOTAS = quota.QUOTAS
LOG = logging.getLogger(__name__)
authorize = extensions.os_compute_authorizer(ALIAS)
def network_dict(network):
# NOTE(danms): Here, network should be an object, which could have come
# from neutron and thus be missing most of the attributes. Providing a
# default to get() avoids trying to lazy-load missing attributes.
return {"id": network.get("uuid", None) or network.get("id", None),
"cidr": str(network.get("cidr", None)),
"label": network.get("label", None)}
class TenantNetworkController(wsgi.Controller):
def __init__(self, network_api=None):
self.network_api = nova.network.API(skip_policy_check=True)
self._default_networks = []
def _refresh_default_networks(self):
self._default_networks = []
if CONF.use_neutron_default_nets == "True":
try:
self._default_networks = self._get_default_networks()
except Exception:
LOG.exception(_LE("Failed to get default networks"))
def _get_default_networks(self):
project_id = CONF.neutron_default_tenant_id
ctx = nova_context.RequestContext(user_id=None,
project_id=project_id)
networks = {}
for n in self.network_api.get_all(ctx):
networks[n['id']] = n['label']
return [{'id': k, 'label': v} for k, v in six.iteritems(networks)]
@extensions.expected_errors(())
def index(self, req):
context = req.environ['nova.context']
authorize(context)
networks = list(self.network_api.get_all(context))
if not self._default_networks:
self._refresh_default_networks()
networks.extend(self._default_networks)
return {'networks': [network_dict(n) for n in networks]}
@extensions.expected_errors(404)
def show(self, req, id):
context = req.environ['nova.context']
authorize(context)
try:
network = self.network_api.get(context, id)
except exception.NetworkNotFound:
msg = _("Network not found")
raise exc.HTTPNotFound(explanation=msg)
return {'network': network_dict(network)}
@extensions.expected_errors((403, 404, 409))
@wsgi.response(202)
def delete(self, req, id):
context = req.environ['nova.context']
authorize(context)
reservation = None
try:
if CONF.enable_network_quota:
reservation = QUOTAS.reserve(context, networks=-1)
except Exception:
reservation = None
LOG.exception(_LE("Failed to update usages deallocating "
"network."))
def _rollback_quota(reservation):
if CONF.enable_network_quota and reservation:
QUOTAS.rollback(context, reservation)
try:
self.network_api.disassociate(context, id)
self.network_api.delete(context, id)
except exception.PolicyNotAuthorized as e:
_rollback_quota(reservation)
raise exc.HTTPForbidden(explanation=six.text_type(e))
except exception.NetworkInUse as e:
_rollback_quota(reservation)
raise exc.HTTPConflict(explanation=e.format_message())
except exception.NetworkNotFound:
_rollback_quota(reservation)
msg = _("Network not found")
raise exc.HTTPNotFound(explanation=msg)
if CONF.enable_network_quota and reservation:
QUOTAS.commit(context, reservation)
@extensions.expected_errors((400, 403, 503))
@validation.schema(schema.create)
def create(self, req, body):
context = req.environ["nova.context"]
authorize(context)
network = body["network"]
keys = ["cidr", "cidr_v6", "ipam", "vlan_start", "network_size",
"num_networks"]
kwargs = {k: network.get(k) for k in keys}
label = network["label"]
if kwargs["cidr"]:
try:
net = netaddr.IPNetwork(kwargs["cidr"])
if net.size < 4:
msg = _("Requested network does not contain "
"enough (2+) usable hosts")
raise exc.HTTPBadRequest(explanation=msg)
except netexc.AddrConversionError:
msg = _("Address could not be converted.")
raise exc.HTTPBadRequest(explanation=msg)
networks = []
try:
if CONF.enable_network_quota:
reservation = QUOTAS.reserve(context, networks=1)
except exception.OverQuota:
msg = _("Quota exceeded, too many networks.")
raise exc.HTTPBadRequest(explanation=msg)
kwargs['project_id'] = context.project_id
try:
networks = self.network_api.create(context,
label=label, **kwargs)
if CONF.enable_network_quota:
QUOTAS.commit(context, reservation)
except exception.PolicyNotAuthorized as e:
raise exc.HTTPForbidden(explanation=six.text_type(e))
except Exception:
if CONF.enable_network_quota:
QUOTAS.rollback(context, reservation)
msg = _("Create networks failed")
LOG.exception(msg, extra=network)
raise exc.HTTPServiceUnavailable(explanation=msg)
return {"network": network_dict(networks[0])}
class TenantNetworks(extensions.V3APIExtensionBase):
"""Tenant-based Network Management Extension."""
name = "OSTenantNetworks"
alias = ALIAS
version = 1
def get_resources(self):
ext = extensions.ResourceExtension(ALIAS, TenantNetworkController())
return [ext]
def get_controller_extensions(self):
return []
def _sync_networks(context, project_id, session):
ctx = nova_context.RequestContext(user_id=None, project_id=project_id)
ctx = ctx.elevated()
networks = nova.network.api.API().get_all(ctx)
return dict(networks=len(networks))
if CONF.enable_network_quota:
QUOTAS.register_resource(quota.ReservableResource('networks',
_sync_networks,
'quota_networks'))
| apache-2.0 |
vnsofthe/odoo | addons/base_report_designer/plugin/openerp_report_designer/bin/script/lib/actions.py | 382 | 3763 | ##########################################################################
#
# Copyright (c) 2003-2004 Danny Brewer d29583@groovegarden.com
# Copyright (C) 2004-2010 OpenERP SA (<http://openerp.com>).
#
# 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
#
# See: http://www.gnu.org/licenses/lgpl.html
#
##############################################################################
import uno
import unohelper
import os
#--------------------------------------------------
# An ActionListener adapter.
# This object implements com.sun.star.awt.XActionListener.
# When actionPerformed is called, this will call an arbitrary
# python procedure, passing it...
# 1. the oActionEvent
# 2. any other parameters you specified to this object's constructor (as a tuple).
if __name__<>"package":
os.system( "ooffice '-accept=socket,host=localhost,port=2002;urp;'" )
passwd=""
database=""
uid=""
loginstatus=False
from com.sun.star.awt import XActionListener
class ActionListenerProcAdapter( unohelper.Base, XActionListener ):
def __init__( self, oProcToCall, tParams=() ):
self.oProcToCall = oProcToCall # a python procedure
self.tParams = tParams # a tuple
# oActionEvent is a com.sun.star.awt.ActionEvent struct.
def actionPerformed( self, oActionEvent ):
if callable( self.oProcToCall ):
apply( self.oProcToCall, (oActionEvent,) + self.tParams )
#--------------------------------------------------
# An ItemListener adapter.
# This object implements com.sun.star.awt.XItemListener.
# When itemStateChanged is called, this will call an arbitrary
# python procedure, passing it...
# 1. the oItemEvent
# 2. any other parameters you specified to this object's constructor (as a tuple).
from com.sun.star.awt import XItemListener
class ItemListenerProcAdapter( unohelper.Base, XItemListener ):
def __init__( self, oProcToCall, tParams=() ):
self.oProcToCall = oProcToCall # a python procedure
self.tParams = tParams # a tuple
# oItemEvent is a com.sun.star.awt.ItemEvent struct.
def itemStateChanged( self, oItemEvent ):
if callable( self.oProcToCall ):
apply( self.oProcToCall, (oItemEvent,) + self.tParams )
#--------------------------------------------------
# An TextListener adapter.
# This object implements com.sun.star.awt.XTextistener.
# When textChanged is called, this will call an arbitrary
# python procedure, passing it...
# 1. the oTextEvent
# 2. any other parameters you specified to this object's constructor (as a tuple).
from com.sun.star.awt import XTextListener
class TextListenerProcAdapter( unohelper.Base, XTextListener ):
def __init__( self, oProcToCall, tParams=() ):
self.oProcToCall = oProcToCall # a python procedure
self.tParams = tParams # a tuple
# oTextEvent is a com.sun.star.awt.TextEvent struct.
def textChanged( self, oTextEvent ):
if callable( self.oProcToCall ):
apply( self.oProcToCall, (oTextEvent,) + self.tParams )
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
woodscn/scipy | scipy/sparse/linalg/tests/test_interface.py | 38 | 12724 | """Test functions for the sparse.linalg.interface module
"""
from __future__ import division, print_function, absolute_import
from functools import partial
from itertools import product
import operator
import nose
from numpy.testing import TestCase, assert_, assert_equal, \
assert_raises
import numpy as np
import scipy.sparse as sparse
from scipy.sparse.linalg import interface
# Only test matmul operator (A @ B) when available (Python 3.5+)
TEST_MATMUL = hasattr(operator, 'matmul')
class TestLinearOperator(TestCase):
def setUp(self):
self.A = np.array([[1,2,3],
[4,5,6]])
self.B = np.array([[1,2],
[3,4],
[5,6]])
self.C = np.array([[1,2],
[3,4]])
def test_matvec(self):
def get_matvecs(A):
return [{
'shape': A.shape,
'matvec': lambda x: np.dot(A, x).reshape(A.shape[0]),
'rmatvec': lambda x: np.dot(A.T.conj(),
x).reshape(A.shape[1])
},
{
'shape': A.shape,
'matvec': lambda x: np.dot(A, x),
'rmatvec': lambda x: np.dot(A.T.conj(), x),
'matmat': lambda x: np.dot(A, x)
}]
for matvecs in get_matvecs(self.A):
A = interface.LinearOperator(**matvecs)
assert_(A.args == ())
assert_equal(A.matvec(np.array([1,2,3])), [14,32])
assert_equal(A.matvec(np.array([[1],[2],[3]])), [[14],[32]])
assert_equal(A * np.array([1,2,3]), [14,32])
assert_equal(A * np.array([[1],[2],[3]]), [[14],[32]])
assert_equal(A.dot(np.array([1,2,3])), [14,32])
assert_equal(A.dot(np.array([[1],[2],[3]])), [[14],[32]])
assert_equal(A.matvec(np.matrix([[1],[2],[3]])), [[14],[32]])
assert_equal(A * np.matrix([[1],[2],[3]]), [[14],[32]])
assert_equal(A.dot(np.matrix([[1],[2],[3]])), [[14],[32]])
assert_equal((2*A)*[1,1,1], [12,30])
assert_equal((2*A).rmatvec([1,1]), [10, 14, 18])
assert_equal((2*A).H.matvec([1,1]), [10, 14, 18])
assert_equal((2*A)*[[1],[1],[1]], [[12],[30]])
assert_equal((2*A).matmat([[1],[1],[1]]), [[12],[30]])
assert_equal((A*2)*[1,1,1], [12,30])
assert_equal((A*2)*[[1],[1],[1]], [[12],[30]])
assert_equal((2j*A)*[1,1,1], [12j,30j])
assert_equal((A+A)*[1,1,1], [12, 30])
assert_equal((A+A).rmatvec([1,1]), [10, 14, 18])
assert_equal((A+A).H.matvec([1,1]), [10, 14, 18])
assert_equal((A+A)*[[1],[1],[1]], [[12], [30]])
assert_equal((A+A).matmat([[1],[1],[1]]), [[12], [30]])
assert_equal((-A)*[1,1,1], [-6,-15])
assert_equal((-A)*[[1],[1],[1]], [[-6],[-15]])
assert_equal((A-A)*[1,1,1], [0,0])
assert_equal((A-A)*[[1],[1],[1]], [[0],[0]])
z = A+A
assert_(len(z.args) == 2 and z.args[0] is A and z.args[1] is A)
z = 2*A
assert_(len(z.args) == 2 and z.args[0] is A and z.args[1] == 2)
assert_(isinstance(A.matvec([1, 2, 3]), np.ndarray))
assert_(isinstance(A.matvec(np.array([[1],[2],[3]])), np.ndarray))
assert_(isinstance(A * np.array([1,2,3]), np.ndarray))
assert_(isinstance(A * np.array([[1],[2],[3]]), np.ndarray))
assert_(isinstance(A.dot(np.array([1,2,3])), np.ndarray))
assert_(isinstance(A.dot(np.array([[1],[2],[3]])), np.ndarray))
assert_(isinstance(A.matvec(np.matrix([[1],[2],[3]])), np.ndarray))
assert_(isinstance(A * np.matrix([[1],[2],[3]]), np.ndarray))
assert_(isinstance(A.dot(np.matrix([[1],[2],[3]])), np.ndarray))
assert_(isinstance(2*A, interface._ScaledLinearOperator))
assert_(isinstance(2j*A, interface._ScaledLinearOperator))
assert_(isinstance(A+A, interface._SumLinearOperator))
assert_(isinstance(-A, interface._ScaledLinearOperator))
assert_(isinstance(A-A, interface._SumLinearOperator))
assert_((2j*A).dtype == np.complex_)
assert_raises(ValueError, A.matvec, np.array([1,2]))
assert_raises(ValueError, A.matvec, np.array([1,2,3,4]))
assert_raises(ValueError, A.matvec, np.array([[1],[2]]))
assert_raises(ValueError, A.matvec, np.array([[1],[2],[3],[4]]))
assert_raises(ValueError, lambda: A*A)
assert_raises(ValueError, lambda: A**2)
for matvecsA, matvecsB in product(get_matvecs(self.A),
get_matvecs(self.B)):
A = interface.LinearOperator(**matvecsA)
B = interface.LinearOperator(**matvecsB)
assert_equal((A*B)*[1,1], [50,113])
assert_equal((A*B)*[[1],[1]], [[50],[113]])
assert_equal((A*B).matmat([[1],[1]]), [[50],[113]])
assert_equal((A*B).rmatvec([1,1]), [71,92])
assert_equal((A*B).H.matvec([1,1]), [71,92])
assert_(isinstance(A*B, interface._ProductLinearOperator))
assert_raises(ValueError, lambda: A+B)
assert_raises(ValueError, lambda: A**2)
z = A*B
assert_(len(z.args) == 2 and z.args[0] is A and z.args[1] is B)
for matvecsC in get_matvecs(self.C):
C = interface.LinearOperator(**matvecsC)
assert_equal((C**2)*[1,1], [17,37])
assert_equal((C**2).rmatvec([1,1]), [22,32])
assert_equal((C**2).H.matvec([1,1]), [22,32])
assert_equal((C**2).matmat([[1],[1]]), [[17],[37]])
assert_(isinstance(C**2, interface._PowerLinearOperator))
def test_matmul(self):
if not TEST_MATMUL:
raise nose.SkipTest("matmul is only tested in Python 3.5+")
D = {'shape': self.A.shape,
'matvec': lambda x: np.dot(self.A, x).reshape(self.A.shape[0]),
'rmatvec': lambda x: np.dot(self.A.T.conj(),
x).reshape(self.A.shape[1]),
'matmat': lambda x: np.dot(self.A, x)}
A = interface.LinearOperator(**D)
B = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
b = B[0]
assert_equal(operator.matmul(A, b), A * b)
assert_equal(operator.matmul(A, B), A * B)
assert_raises(ValueError, operator.matmul, A, 2)
assert_raises(ValueError, operator.matmul, 2, A)
class TestAsLinearOperator(TestCase):
def setUp(self):
self.cases = []
def make_cases(dtype):
self.cases.append(np.matrix([[1,2,3],[4,5,6]], dtype=dtype))
self.cases.append(np.array([[1,2,3],[4,5,6]], dtype=dtype))
self.cases.append(sparse.csr_matrix([[1,2,3],[4,5,6]], dtype=dtype))
# Test default implementations of _adjoint and _rmatvec, which
# refer to each other.
def mv(x, dtype):
y = np.array([1 * x[0] + 2 * x[1] + 3 * x[2],
4 * x[0] + 5 * x[1] + 6 * x[2]], dtype=dtype)
if len(x.shape) == 2:
y = y.reshape(-1, 1)
return y
def rmv(x, dtype):
return np.array([1 * x[0] + 4 * x[1],
2 * x[0] + 5 * x[1],
3 * x[0] + 6 * x[1]], dtype=dtype)
class BaseMatlike(interface.LinearOperator):
def __init__(self, dtype):
self.dtype = np.dtype(dtype)
self.shape = (2,3)
def _matvec(self, x):
return mv(x, self.dtype)
class HasRmatvec(BaseMatlike):
def _rmatvec(self,x):
return rmv(x, self.dtype)
class HasAdjoint(BaseMatlike):
def _adjoint(self):
shape = self.shape[1], self.shape[0]
matvec = partial(rmv, dtype=self.dtype)
rmatvec = partial(mv, dtype=self.dtype)
return interface.LinearOperator(matvec=matvec,
rmatvec=rmatvec,
dtype=self.dtype,
shape=shape)
self.cases.append(HasRmatvec(dtype))
self.cases.append(HasAdjoint(dtype))
make_cases('int32')
make_cases('float32')
make_cases('float64')
def test_basic(self):
for M in self.cases:
A = interface.aslinearoperator(M)
M,N = A.shape
assert_equal(A.matvec(np.array([1,2,3])), [14,32])
assert_equal(A.matvec(np.array([[1],[2],[3]])), [[14],[32]])
assert_equal(A * np.array([1,2,3]), [14,32])
assert_equal(A * np.array([[1],[2],[3]]), [[14],[32]])
assert_equal(A.rmatvec(np.array([1,2])), [9,12,15])
assert_equal(A.rmatvec(np.array([[1],[2]])), [[9],[12],[15]])
assert_equal(A.H.matvec(np.array([1,2])), [9,12,15])
assert_equal(A.H.matvec(np.array([[1],[2]])), [[9],[12],[15]])
assert_equal(
A.matmat(np.array([[1,4],[2,5],[3,6]])),
[[14,32],[32,77]])
assert_equal(A * np.array([[1,4],[2,5],[3,6]]), [[14,32],[32,77]])
if hasattr(M,'dtype'):
assert_equal(A.dtype, M.dtype)
def test_dot(self):
for M in self.cases:
A = interface.aslinearoperator(M)
M,N = A.shape
assert_equal(A.dot(np.array([1,2,3])), [14,32])
assert_equal(A.dot(np.array([[1],[2],[3]])), [[14],[32]])
assert_equal(
A.dot(np.array([[1,4],[2,5],[3,6]])),
[[14,32],[32,77]])
def test_repr():
A = interface.LinearOperator(shape=(1, 1), matvec=lambda x: 1)
repr_A = repr(A)
assert_('unspecified dtype' not in repr_A, repr_A)
def test_identity():
ident = interface.IdentityOperator((3, 3))
assert_equal(ident * [1, 2, 3], [1, 2, 3])
assert_equal(ident.dot(np.arange(9).reshape(3, 3)).ravel(), np.arange(9))
assert_raises(ValueError, ident.matvec, [1, 2, 3, 4])
def test_attributes():
A = interface.aslinearoperator(np.arange(16).reshape(4, 4))
def always_four_ones(x):
x = np.asarray(x)
assert_(x.shape == (3,) or x.shape == (3, 1))
return np.ones(4)
B = interface.LinearOperator(shape=(4, 3), matvec=always_four_ones)
for op in [A, B, A * B, A.H, A + A, B + B, A ** 4]:
assert_(hasattr(op, "dtype"))
assert_(hasattr(op, "shape"))
assert_(hasattr(op, "_matvec"))
def matvec(x):
""" Needed for test_pickle as local functions are not pickleable """
return np.zeros(3)
def test_pickle():
import pickle
for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
A = interface.LinearOperator((3, 3), matvec)
s = pickle.dumps(A, protocol=protocol)
B = pickle.loads(s)
for k in A.__dict__:
assert_equal(getattr(A, k), getattr(B, k))
def test_inheritance():
class Empty(interface.LinearOperator):
pass
assert_raises(TypeError, Empty)
class Identity(interface.LinearOperator):
def __init__(self, n):
super(Identity, self).__init__(dtype=None, shape=(n, n))
def _matvec(self, x):
return x
id3 = Identity(3)
assert_equal(id3.matvec([1, 2, 3]), [1, 2, 3])
assert_raises(NotImplementedError, id3.rmatvec, [4, 5, 6])
class MatmatOnly(interface.LinearOperator):
def __init__(self, A):
super(MatmatOnly, self).__init__(A.dtype, A.shape)
self.A = A
def _matmat(self, x):
return self.A.dot(x)
mm = MatmatOnly(np.random.randn(5, 3))
assert_equal(mm.matvec(np.random.randn(3)).shape, (5,))
def test_dtypes_of_operator_sum():
# gh-6078
mat_complex = np.random.rand(2,2) + 1j * np.random.rand(2,2)
mat_real = np.random.rand(2,2)
complex_operator = interface.aslinearoperator(mat_complex)
real_operator = interface.aslinearoperator(mat_real)
sum_complex = complex_operator + complex_operator
sum_real = real_operator + real_operator
assert_equal(sum_real.dtype, np.float64)
assert_equal(sum_complex.dtype, np.complex128)
| bsd-3-clause |
kevinwchang/Minecraft-Overviewer | contrib/contributors.py | 8 | 4263 | #!/usr/bin/python2
"""Update the contributor list
Alias handling is done by git with .mailmap
New contributors are merged in the short-term list.
Moving them to a "higher" list should be a manual process.
"""
import fileinput
from subprocess import Popen, PIPE
def format_contributor(contributor):
return " * {0} {1}".format(
" ".join(contributor["name"]),
contributor["email"])
def main():
# generate list of contributors
contributors = []
p_git = Popen(["git", "shortlog", "-se"], stdout=PIPE)
for line in p_git.stdout:
contributors.append({
'count': int(line.split("\t")[0].strip()),
'name': line.split("\t")[1].split()[0:-1],
'email': line.split("\t")[1].split()[-1]
})
# cache listed contributors
old_contributors = []
with open("CONTRIBUTORS.rst", "r") as contrib_file:
for line in contrib_file:
if "@" in line:
old_contributors.append({
'name': line.split()[1:-1],
'email': line.split()[-1]
})
old = map(lambda x: (x['name'], x['email']), old_contributors)
old_emails = map(lambda x: x['email'], old_contributors)
old_names = map(lambda x: x['name'], old_contributors)
# check which contributors are new
new_contributors = []
update_mailmap = False
for contributor in contributors:
if (contributor['name'], contributor['email']) in old:
# this exact combination already in the list
pass
elif (contributor['email'] not in old_emails
and contributor['name'] not in old_names):
# name AND email are not in the list
new_contributors.append(contributor)
elif contributor['email'] in old_emails:
# email is listed, but with another name
old_name = filter(lambda x: x['email'] == contributor['email'],
old_contributors)[0]['name']
print "new alias %s for %s %s ?" % (
" ".join(contributor['name']),
" ".join(old_name),
contributor['email'])
update_mailmap = True
elif contributor['name'] in old_names:
# probably a new email for a previous contributor
other_mail = filter(lambda x: x['name'] == contributor['name'],
old_contributors)[0]['email']
print "new email %s for %s %s ?" % (
contributor['email'],
" ".join(contributor['name']),
other_mail)
update_mailmap = True
if update_mailmap:
print "Please update .mailmap"
# sort on the last word of the name
new_contributors = sorted(new_contributors,
key=lambda x: x['name'][-1].lower())
# show new contributors to be merged to the list
if new_contributors:
print "inserting:"
for contributor in new_contributors:
print format_contributor(contributor)
# merge with alphabetical (by last part of name) contributor list
i = 0
short_term_found = False
for line in fileinput.input("CONTRIBUTORS.rst", inplace=1):
if not short_term_found:
print line,
if "Short-term" in line:
short_term_found = True
else:
if i >= len(new_contributors) or "@" not in line:
print line,
else:
listed_name = line.split()[-2].lower()
contributor = new_contributors[i]
# insert all new contributors that fit here
while listed_name > contributor["name"][-1].lower():
print format_contributor(contributor)
i += 1
if i < len(new_contributors):
contributor = new_contributors[i]
else:
break
print line,
# append remaining contributors
with open("CONTRIBUTORS.rst", "a") as contrib_file:
while i < len(new_contributors):
contrib_file.write(format_contributor(new_contributors[i]) + "\n")
i += 1
if __name__ == "__main__":
main()
| gpl-3.0 |
pieterlexis/pdns | regression-tests.recursor-dnssec/test_EDNS.py | 4 | 1483 | import dns
import os
import socket
import struct
import threading
import time
from recursortests import RecursorTest
from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor
ednsBufferReactorRunning = False
class EDNSTest(RecursorTest):
"""
These tests are designed to check if we respond correctly to EDNS queries
from clients. Note that buffer-size tests go into test_EDNSBufferSize
"""
_confdir = 'EDNS'
def testEDNSUnknownOpt(self):
"""
Ensure the recursor does not reply with an unknown option when one is
sent in the query
"""
query = dns.message.make_query('version.bind.', 'TXT', 'CH', use_edns=0,
payload=4096)
unknownOpt = dns.edns.GenericOption(65005, b'1234567890')
query.options = [unknownOpt]
response = self.sendUDPQuery(query)
self.assertRcodeEqual(response, dns.rcode.NOERROR)
self.assertEqual(response.options, [])
def testEDNSBadVers(self):
"""
Ensure the rcode is BADVERS when we send an unsupported EDNS version and
the query is not processed any further.
"""
query = dns.message.make_query('version.bind.', 'TXT', 'CH', use_edns=5,
payload=4096)
response = self.sendUDPQuery(query)
self.assertRcodeEqual(response, dns.rcode.BADVERS)
self.assertEqual(response.answer, [])
| gpl-2.0 |
louiskun/flaskGIT | venv/lib/python2.7/site-packages/jinja2/utils.py | 323 | 16560 | # -*- coding: utf-8 -*-
"""
jinja2.utils
~~~~~~~~~~~~
Utility functions.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD, see LICENSE for more details.
"""
import re
import errno
from collections import deque
from threading import Lock
from jinja2._compat import text_type, string_types, implements_iterator, \
url_quote
_word_split_re = re.compile(r'(\s+)')
_punctuation_re = re.compile(
'^(?P<lead>(?:%s)*)(?P<middle>.*?)(?P<trail>(?:%s)*)$' % (
'|'.join(map(re.escape, ('(', '<', '<'))),
'|'.join(map(re.escape, ('.', ',', ')', '>', '\n', '>')))
)
)
_simple_email_re = re.compile(r'^\S+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+$')
_striptags_re = re.compile(r'(<!--.*?-->|<[^>]*>)')
_entity_re = re.compile(r'&([^;]+);')
_letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
_digits = '0123456789'
# special singleton representing missing values for the runtime
missing = type('MissingType', (), {'__repr__': lambda x: 'missing'})()
# internal code
internal_code = set()
concat = u''.join
def contextfunction(f):
"""This decorator can be used to mark a function or method context callable.
A context callable is passed the active :class:`Context` as first argument when
called from the template. This is useful if a function wants to get access
to the context or functions provided on the context object. For example
a function that returns a sorted list of template variables the current
template exports could look like this::
@contextfunction
def get_exported_names(context):
return sorted(context.exported_vars)
"""
f.contextfunction = True
return f
def evalcontextfunction(f):
"""This decorator can be used to mark a function or method as an eval
context callable. This is similar to the :func:`contextfunction`
but instead of passing the context, an evaluation context object is
passed. For more information about the eval context, see
:ref:`eval-context`.
.. versionadded:: 2.4
"""
f.evalcontextfunction = True
return f
def environmentfunction(f):
"""This decorator can be used to mark a function or method as environment
callable. This decorator works exactly like the :func:`contextfunction`
decorator just that the first argument is the active :class:`Environment`
and not context.
"""
f.environmentfunction = True
return f
def internalcode(f):
"""Marks the function as internally used"""
internal_code.add(f.__code__)
return f
def is_undefined(obj):
"""Check if the object passed is undefined. This does nothing more than
performing an instance check against :class:`Undefined` but looks nicer.
This can be used for custom filters or tests that want to react to
undefined variables. For example a custom default filter can look like
this::
def default(var, default=''):
if is_undefined(var):
return default
return var
"""
from jinja2.runtime import Undefined
return isinstance(obj, Undefined)
def consume(iterable):
"""Consumes an iterable without doing anything with it."""
for event in iterable:
pass
def clear_caches():
"""Jinja2 keeps internal caches for environments and lexers. These are
used so that Jinja2 doesn't have to recreate environments and lexers all
the time. Normally you don't have to care about that but if you are
messuring memory consumption you may want to clean the caches.
"""
from jinja2.environment import _spontaneous_environments
from jinja2.lexer import _lexer_cache
_spontaneous_environments.clear()
_lexer_cache.clear()
def import_string(import_name, silent=False):
"""Imports an object based on a string. This is useful if you want to
use import paths as endpoints or something similar. An import path can
be specified either in dotted notation (``xml.sax.saxutils.escape``)
or with a colon as object delimiter (``xml.sax.saxutils:escape``).
If the `silent` is True the return value will be `None` if the import
fails.
:return: imported object
"""
try:
if ':' in import_name:
module, obj = import_name.split(':', 1)
elif '.' in import_name:
items = import_name.split('.')
module = '.'.join(items[:-1])
obj = items[-1]
else:
return __import__(import_name)
return getattr(__import__(module, None, None, [obj]), obj)
except (ImportError, AttributeError):
if not silent:
raise
def open_if_exists(filename, mode='rb'):
"""Returns a file descriptor for the filename if that file exists,
otherwise `None`.
"""
try:
return open(filename, mode)
except IOError as e:
if e.errno not in (errno.ENOENT, errno.EISDIR, errno.EINVAL):
raise
def object_type_repr(obj):
"""Returns the name of the object's type. For some recognized
singletons the name of the object is returned instead. (For
example for `None` and `Ellipsis`).
"""
if obj is None:
return 'None'
elif obj is Ellipsis:
return 'Ellipsis'
# __builtin__ in 2.x, builtins in 3.x
if obj.__class__.__module__ in ('__builtin__', 'builtins'):
name = obj.__class__.__name__
else:
name = obj.__class__.__module__ + '.' + obj.__class__.__name__
return '%s object' % name
def pformat(obj, verbose=False):
"""Prettyprint an object. Either use the `pretty` library or the
builtin `pprint`.
"""
try:
from pretty import pretty
return pretty(obj, verbose=verbose)
except ImportError:
from pprint import pformat
return pformat(obj)
def urlize(text, trim_url_limit=None, nofollow=False, target=None):
"""Converts any URLs in text into clickable links. Works on http://,
https:// and www. links. Links can have trailing punctuation (periods,
commas, close-parens) and leading punctuation (opening parens) and
it'll still do the right thing.
If trim_url_limit is not None, the URLs in link text will be limited
to trim_url_limit characters.
If nofollow is True, the URLs in link text will get a rel="nofollow"
attribute.
If target is not None, a target attribute will be added to the link.
"""
trim_url = lambda x, limit=trim_url_limit: limit is not None \
and (x[:limit] + (len(x) >=limit and '...'
or '')) or x
words = _word_split_re.split(text_type(escape(text)))
nofollow_attr = nofollow and ' rel="nofollow"' or ''
if target is not None and isinstance(target, string_types):
target_attr = ' target="%s"' % target
else:
target_attr = ''
for i, word in enumerate(words):
match = _punctuation_re.match(word)
if match:
lead, middle, trail = match.groups()
if middle.startswith('www.') or (
'@' not in middle and
not middle.startswith('http://') and
not middle.startswith('https://') and
len(middle) > 0 and
middle[0] in _letters + _digits and (
middle.endswith('.org') or
middle.endswith('.net') or
middle.endswith('.com')
)):
middle = '<a href="http://%s"%s%s>%s</a>' % (middle,
nofollow_attr, target_attr, trim_url(middle))
if middle.startswith('http://') or \
middle.startswith('https://'):
middle = '<a href="%s"%s%s>%s</a>' % (middle,
nofollow_attr, target_attr, trim_url(middle))
if '@' in middle and not middle.startswith('www.') and \
not ':' in middle and _simple_email_re.match(middle):
middle = '<a href="mailto:%s">%s</a>' % (middle, middle)
if lead + middle + trail != word:
words[i] = lead + middle + trail
return u''.join(words)
def generate_lorem_ipsum(n=5, html=True, min=20, max=100):
"""Generate some lorem ipsum for the template."""
from jinja2.constants import LOREM_IPSUM_WORDS
from random import choice, randrange
words = LOREM_IPSUM_WORDS.split()
result = []
for _ in range(n):
next_capitalized = True
last_comma = last_fullstop = 0
word = None
last = None
p = []
# each paragraph contains out of 20 to 100 words.
for idx, _ in enumerate(range(randrange(min, max))):
while True:
word = choice(words)
if word != last:
last = word
break
if next_capitalized:
word = word.capitalize()
next_capitalized = False
# add commas
if idx - randrange(3, 8) > last_comma:
last_comma = idx
last_fullstop += 2
word += ','
# add end of sentences
if idx - randrange(10, 20) > last_fullstop:
last_comma = last_fullstop = idx
word += '.'
next_capitalized = True
p.append(word)
# ensure that the paragraph ends with a dot.
p = u' '.join(p)
if p.endswith(','):
p = p[:-1] + '.'
elif not p.endswith('.'):
p += '.'
result.append(p)
if not html:
return u'\n\n'.join(result)
return Markup(u'\n'.join(u'<p>%s</p>' % escape(x) for x in result))
def unicode_urlencode(obj, charset='utf-8', for_qs=False):
"""URL escapes a single bytestring or unicode string with the
given charset if applicable to URL safe quoting under all rules
that need to be considered under all supported Python versions.
If non strings are provided they are converted to their unicode
representation first.
"""
if not isinstance(obj, string_types):
obj = text_type(obj)
if isinstance(obj, text_type):
obj = obj.encode(charset)
safe = for_qs and b'' or b'/'
rv = text_type(url_quote(obj, safe))
if for_qs:
rv = rv.replace('%20', '+')
return rv
class LRUCache(object):
"""A simple LRU Cache implementation."""
# this is fast for small capacities (something below 1000) but doesn't
# scale. But as long as it's only used as storage for templates this
# won't do any harm.
def __init__(self, capacity):
self.capacity = capacity
self._mapping = {}
self._queue = deque()
self._postinit()
def _postinit(self):
# alias all queue methods for faster lookup
self._popleft = self._queue.popleft
self._pop = self._queue.pop
self._remove = self._queue.remove
self._wlock = Lock()
self._append = self._queue.append
def __getstate__(self):
return {
'capacity': self.capacity,
'_mapping': self._mapping,
'_queue': self._queue
}
def __setstate__(self, d):
self.__dict__.update(d)
self._postinit()
def __getnewargs__(self):
return (self.capacity,)
def copy(self):
"""Return a shallow copy of the instance."""
rv = self.__class__(self.capacity)
rv._mapping.update(self._mapping)
rv._queue = deque(self._queue)
return rv
def get(self, key, default=None):
"""Return an item from the cache dict or `default`"""
try:
return self[key]
except KeyError:
return default
def setdefault(self, key, default=None):
"""Set `default` if the key is not in the cache otherwise
leave unchanged. Return the value of this key.
"""
self._wlock.acquire()
try:
try:
return self[key]
except KeyError:
self[key] = default
return default
finally:
self._wlock.release()
def clear(self):
"""Clear the cache."""
self._wlock.acquire()
try:
self._mapping.clear()
self._queue.clear()
finally:
self._wlock.release()
def __contains__(self, key):
"""Check if a key exists in this cache."""
return key in self._mapping
def __len__(self):
"""Return the current size of the cache."""
return len(self._mapping)
def __repr__(self):
return '<%s %r>' % (
self.__class__.__name__,
self._mapping
)
def __getitem__(self, key):
"""Get an item from the cache. Moves the item up so that it has the
highest priority then.
Raise a `KeyError` if it does not exist.
"""
self._wlock.acquire()
try:
rv = self._mapping[key]
if self._queue[-1] != key:
try:
self._remove(key)
except ValueError:
# if something removed the key from the container
# when we read, ignore the ValueError that we would
# get otherwise.
pass
self._append(key)
return rv
finally:
self._wlock.release()
def __setitem__(self, key, value):
"""Sets the value for an item. Moves the item up so that it
has the highest priority then.
"""
self._wlock.acquire()
try:
if key in self._mapping:
self._remove(key)
elif len(self._mapping) == self.capacity:
del self._mapping[self._popleft()]
self._append(key)
self._mapping[key] = value
finally:
self._wlock.release()
def __delitem__(self, key):
"""Remove an item from the cache dict.
Raise a `KeyError` if it does not exist.
"""
self._wlock.acquire()
try:
del self._mapping[key]
try:
self._remove(key)
except ValueError:
# __getitem__ is not locked, it might happen
pass
finally:
self._wlock.release()
def items(self):
"""Return a list of items."""
result = [(key, self._mapping[key]) for key in list(self._queue)]
result.reverse()
return result
def iteritems(self):
"""Iterate over all items."""
return iter(self.items())
def values(self):
"""Return a list of all values."""
return [x[1] for x in self.items()]
def itervalue(self):
"""Iterate over all values."""
return iter(self.values())
def keys(self):
"""Return a list of all keys ordered by most recent usage."""
return list(self)
def iterkeys(self):
"""Iterate over all keys in the cache dict, ordered by
the most recent usage.
"""
return reversed(tuple(self._queue))
__iter__ = iterkeys
def __reversed__(self):
"""Iterate over the values in the cache dict, oldest items
coming first.
"""
return iter(tuple(self._queue))
__copy__ = copy
# register the LRU cache as mutable mapping if possible
try:
from collections import MutableMapping
MutableMapping.register(LRUCache)
except ImportError:
pass
@implements_iterator
class Cycler(object):
"""A cycle helper for templates."""
def __init__(self, *items):
if not items:
raise RuntimeError('at least one item has to be provided')
self.items = items
self.reset()
def reset(self):
"""Resets the cycle."""
self.pos = 0
@property
def current(self):
"""Returns the current item."""
return self.items[self.pos]
def __next__(self):
"""Goes one item ahead and returns it."""
rv = self.current
self.pos = (self.pos + 1) % len(self.items)
return rv
class Joiner(object):
"""A joining helper for templates."""
def __init__(self, sep=u', '):
self.sep = sep
self.used = False
def __call__(self):
if not self.used:
self.used = True
return u''
return self.sep
# Imported here because that's where it was in the past
from markupsafe import Markup, escape, soft_unicode
| mit |
wasade/qiime | scripts/compare_distance_matrices.py | 1 | 11439 | #!/usr/bin/env python
from __future__ import division
__author__ = "Greg Caporaso"
__copyright__ = "Copyright 2012, The QIIME project"
__credits__ = ["Jai Ram Rideout", "Michael Dwan", "Logan Knecht",
"Damien Coy", "Levi McCracken", "Greg Caporaso"]
__license__ = "GPL"
__version__ = "1.8.0-dev"
__maintainer__ = "Jai Ram Rideout"
__email__ = "jai.rideout@gmail.com"
from os import path
from skbio.util import create_dir
from qiime.parse import fields_to_dict, parse_distmat
from qiime.util import (parse_command_line_parameters,
get_options_lookup,
make_option)
from qiime.compare_distance_matrices import (run_mantel_correlogram,
run_mantel_test)
options_lookup = get_options_lookup()
script_info = {}
script_info[
'brief_description'] = """Computes Mantel correlation tests between sets of distance matrices"""
script_info['script_description'] = """
This script compares two or more distance/dissimilarity matrices for \
correlation by providing the Mantel, partial Mantel, and Mantel correlogram \
matrix correlation tests.
The Mantel test will test the correlation between two matrices. The data \
often represents the "distance" between objects or samples.
The partial Mantel test is a first-order correlation analysis that utilizes \
three distance (dissimilarity) matrices. This test builds on the traditional \
Mantel test which is a procedure that tests the hypothesis that distances \
between the objects within a given matrix are linearly independent of the \
distances withing those same objects in a separate matrix. It builds on the \
traditional Mantel test by adding a third "control" matrix.
Mantel correlogram produces a plot of distance classes versus Mantel \
statistics. Briefly, an ecological distance matrix (e.g. UniFrac distance \
matrix) and a second distance matrix (e.g. spatial distances, pH distances, \
etc.) are provided. The second distance matrix has its distances split into a \
number of distance classes (the number of classes is determined by Sturge's \
rule). A Mantel test is run over these distance classes versus the ecological \
distance matrix. The Mantel statistics obtained from each of these tests are \
then plotted in a correlogram. A filled-in point on the plot indicates that \
the Mantel statistic was statistically significant (you may provide what \
alpha to use).
For more information and examples pertaining to this script, please refer to \
the accompanying tutorial, which can be found at \
http://qiime.org/tutorials/distance_matrix_comparison.html.
"""
script_info['script_usage'] = []
script_info['script_usage'].append(("Partial Mantel",
"Performs a partial Mantel test on two distance matrices, "
"using a third matrix as a control. Runs 99 permutations to calculate the "
"p-value.",
"%prog --method partial_mantel -i "
"weighted_unifrac_dm.txt,unweighted_unifrac_dm.txt -c PH_dm.txt "
"-o partial_mantel_out -n 99"))
script_info['script_usage'].append(("Mantel",
"Performs a Mantel test on all pairs of four distance matrices, "
"including 999 permutations for each test.",
"%prog --method mantel "
"-i weighted_unifrac_dm.txt,unweighted_unifrac_dm.txt,"
"weighted_unifrac_even100_dm.txt,unweighted_unifrac_even100_dm.txt "
"-o mantel_out -n 999"))
script_info['script_usage'].append(("Mantel Correlogram",
"This example computes a Mantel correlogram on two distance matrices "
"using 999 permutations in each Mantel test. Output is written to the "
"mantel_correlogram_out directory.",
"%prog --method mantel_corr -i unweighted_unifrac_dm.txt,PH_dm.txt -o "
"mantel_correlogram_out -n 999"))
script_info['output_description'] = """
Mantel: One file is created containing the Mantel 'r' statistic and p-value.
Partial Mantel: One file is created in the output directory, which contains \
the partial Mantel statistic and p-value.
Mantel Correlogram: Two files are created in the output directory: a text \
file containing information about the distance classes, their associated \
Mantel statistics and p-values, etc. and an image of the correlogram plot.
"""
script_info['required_options'] = [
# All methods use these
make_option('--method',
help='matrix correlation method to use. Valid options: '
'[mantel, partial_mantel, mantel_corr]',
type='choice',
choices=['mantel', 'partial_mantel', 'mantel_corr']),
make_option('-i', '--input_dms', type='existing_filepaths',
help='the input distance matrices, comma-separated. WARNING: Only '
'symmetric, hollow distance matrices may be used as input. Asymmetric '
'distance matrices, such as those obtained by the UniFrac Gain metric '
'(i.e. beta_diversity.py -m unifrac_g), should not be used as input'),
options_lookup['output_dir']
]
script_info['optional_options'] = [
# All methods use these
make_option('-n', '--num_permutations',
help='the number of permutations to perform when calculating the '
'p-value [default: %default]', default=100, type='int'),
make_option('-s', '--sample_id_map_fp', type='existing_filepath',
help='Map of original sample ids to new sample ids [default: '
'%default]', default=None),
# Standard Mantel specific, i.e., method == mantel
make_option('-t', '--tail_type',
help='the type of tail test to perform when calculating the p-value. '
'Valid options: [two-sided, less, greater]. "two-sided" is a two-tailed '
'test, while "less" tests for r statistics less than the observed r '
'statistic, and "greater" tests for r statistics greater than the '
'observed r statistic. Only applies when method is mantel [default: '
'%default]', default='two-sided', type='choice',
choices=['two-sided', 'greater', 'less']),
# Mantel Correlogram specific, i.e., method == mantel_corr
make_option('-a', '--alpha',
help='the value of alpha to use when denoting significance in the '
'correlogram plot. Only applies when method is mantel_corr',
default=0.05, type='float'),
make_option('-g', '--image_type',
help='the type of image to produce. Valid options: [png, svg, pdf]. '
'Only applies when method is mantel_corr [default: %default]',
default='pdf', type='choice', choices=['pdf', 'png', 'svg']),
make_option('--variable_size_distance_classes', action='store_true',
help='if this option is supplied, each distance class will have an '
'equal number of distances (i.e. pairwise comparisons), which may '
'result in variable sizes of distance classes (i.e. each distance '
'class may span a different range of distances). If this option is '
'not supplied, each distance class will have the same width, but may '
'contain varying numbers of pairwise distances in each class. This '
'option can help maintain statistical power if there are large '
'differences in the number of distances in each class. See '
'Darcy et al. 2011 (PLoS ONE) for an example of this type of '
'correlogram. Only applies when method is mantel_corr '
'[default: %default]', default=False),
# Partial Mantel specific, i.e., method == partial_mantel
make_option('-c', '--control_dm',
help='the control matrix. Only applies (and is *required*) when '
'method is partial_mantel. [default: %default]', default=None,
type='existing_filepath')
]
script_info['version'] = __version__
comment_mantel_pmantel = """\
# Number of entries refers to the number of rows (or cols) retained in each
# distance matrix after filtering the distance matrices to include only those
# samples that were in both distance matrices. p-value contains the correct
# number of significant digits.
"""
comment_corr = comment_mantel_pmantel[:-1] + \
"""
# Distance classes with values of None were in the second half of the distance
# classes and not all samples could be included in the distance class, so
# calculations were not performed.
"""
def main():
option_parser, opts, args = parse_command_line_parameters(**script_info)
if opts.num_permutations < 1:
option_parser.error(
"--num_permutations must be greater than or equal to 1.")
# Create the output dir if it doesn't already exist.
try:
if not path.exists(opts.output_dir):
create_dir(opts.output_dir)
except:
option_parser.error("Could not create or access output directory "
"specified with the -o option.")
sample_id_map = None
if opts.sample_id_map_fp:
sample_id_map = dict([(k, v[0])
for k, v in fields_to_dict(open(opts.sample_id_map_fp, "U")).items()])
input_dm_fps = opts.input_dms
distmats = [parse_distmat(open(dm_fp, 'U')) for dm_fp in input_dm_fps]
if opts.method == 'mantel':
output_f = open(path.join(opts.output_dir, 'mantel_results.txt'), 'w')
output_f.write(run_mantel_test('mantel', input_dm_fps, distmats,
opts.num_permutations, opts.tail_type,
comment_mantel_pmantel, sample_id_map=sample_id_map))
elif opts.method == 'partial_mantel':
output_f = open(path.join(opts.output_dir,
'partial_mantel_results.txt'), 'w')
output_f.write(run_mantel_test('partial_mantel', input_dm_fps,
distmats, opts.num_permutations, opts.tail_type,
comment_mantel_pmantel, control_dm_fp=opts.control_dm,
control_dm=parse_distmat(open(opts.control_dm, 'U')),
sample_id_map=sample_id_map))
elif opts.method == 'mantel_corr':
output_f = open(path.join(opts.output_dir,
'mantel_correlogram_results.txt'), 'w')
result_str, correlogram_fps, correlograms = run_mantel_correlogram(
input_dm_fps, distmats, opts.num_permutations, comment_corr,
opts.alpha, sample_id_map=sample_id_map,
variable_size_distance_classes=opts.variable_size_distance_classes)
output_f.write(result_str)
for corr_fp, corr in zip(correlogram_fps, correlograms):
corr.savefig(path.join(opts.output_dir, corr_fp + opts.image_type),
format=opts.image_type)
output_f.close()
if __name__ == "__main__":
main()
| gpl-2.0 |
sagiss/sardana | src/sardana/taurus/qt/qtgui/extra_hkl/hklscan.py | 1 | 15114 | #!/usr/bin/env python
##############################################################################
##
## This file is part of Sardana
##
## http://www.sardana-controls.org/
##
## Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain
##
## Sardana is free software: you can redistribute it and/or modify
## it under the terms of the GNU Lesser General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## Sardana 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 Sardana. If not, see <http://www.gnu.org/licenses/>.
##
##############################################################################
__docformat__ = 'restructuredtext'
import sys
import sardana
from taurus.external.qt import Qt
from taurus.qt.qtgui.container import TaurusWidget
from taurus.qt.qtgui.display import TaurusLabel
from taurus.qt.qtgui.base import TaurusBaseWidget
from taurus.external.qt import QtCore, QtGui
import taurus.core
from taurus.qt.qtcore.communication import SharedDataManager
from taurus.qt.qtgui.input import TaurusValueLineEdit
from displayscanangles import DisplayScanAngles
import taurus.core.util.argparse
import taurus.qt.qtgui.application
from taurus.qt.qtgui.util.ui import UILoadable
from PyTango import *
from sardana.taurus.qt.qtgui.extra_macroexecutor import TaurusMacroExecutorWidget, TaurusSequencerWidget, \
TaurusMacroConfigurationDialog, \
TaurusMacroDescriptionViewer, DoorOutput, DoorDebug, DoorResult
class EngineModesComboBox(Qt.QComboBox, TaurusBaseWidget):
"""ComboBox representing list of engine modes"""
def __init__(self, parent=None):
name = self.__class__.__name__
self.call__init__wo_kw(Qt.QComboBox, parent)
self.call__init__(TaurusBaseWidget, name)
self.setSizeAdjustPolicy(Qt.QComboBox.AdjustToContentsOnFirstShow)
self.setToolTip("Choose a engine mode ...")
QtCore.QMetaObject.connectSlotsByName(self)
def loadEngineModeNames(self, enginemodes):
self.clear()
self.addItems(enginemodes)
@UILoadable(with_ui="_ui")
class HKLScan(TaurusWidget):
def __init__(self, parent=None, designMode=False):
TaurusWidget.__init__(self, parent, designMode=designMode)
self.loadUi(filename="hklscan.ui")
self.connect(self._ui.hklStartScanButton,
Qt.SIGNAL("clicked()"), self.start_hklscan)
self.connect(self._ui.hklStopScanButton,
Qt.SIGNAL("clicked()"), self.stop_hklscan)
self.connect(self._ui.hklDisplayAnglesButton,
Qt.SIGNAL("clicked()"), self.display_angles)
self.connect(self._ui.MacroServerConnectionButton, Qt.SIGNAL(
"clicked()"), self.open_macroserver_connection_panel)
# Create a global SharedDataManager
Qt.qApp.SDM = SharedDataManager(self)
@classmethod
def getQtDesignerPluginInfo(cls):
ret = TaurusWidget.getQtDesignerPluginInfo()
ret['module'] = 'hklscan'
ret['group'] = 'Taurus Containers'
ret['container'] = ':/designer/frame.png'
ret['container'] = True
return ret
def setModel(self, model):
if model != None:
self.device = taurus.Device(model)
self.pseudo_motor_names = []
for motor in self.device.hklpseudomotorlist:
self.pseudo_motor_names.append(motor.split(' ')[0])
self.h_device_name = self.pseudo_motor_names[0]
self.h_device = taurus.Device(self.h_device_name)
self.k_device_name = self.pseudo_motor_names[1]
self.k_device = taurus.Device(self.k_device_name)
self.l_device_name = self.pseudo_motor_names[2]
self.l_device = taurus.Device(self.l_device_name)
# Add dynamically the angle widgets
motor_list = self.device.motorlist
motor_names = []
for motor in self.device.motorlist:
motor_names.append(motor.split(' ')[0])
self.nb_motors = len(motor_list)
angles_labels = []
angles_names = []
angles_taurus_label = []
gap_x = 800 / self.nb_motors
try:
angles_names = self.device.motorroles
except: # Only for compatibility
if self.nb_motors == 4:
angles_names.append("omega")
angles_names.append("chi")
angles_names.append("phi")
angles_names.append("theta")
elif self.nb_motors == 6:
angles_names.append("mu")
angles_names.append("th")
angles_names.append("chi")
angles_names.append("phi")
angles_names.append("gamma")
angles_names.append("delta")
for i in range(0, self.nb_motors):
angles_labels.append(QtGui.QLabel(self))
angles_labels[i].setGeometry(
QtCore.QRect(50 + gap_x * i, 290, 51, 17))
alname = "angleslabel" + str(i)
angles_labels[i].setObjectName(alname)
angles_labels[i].setText(QtGui.QApplication.translate(
"HKLScan", angles_names[i], None, QtGui.QApplication.UnicodeUTF8))
angles_taurus_label.append(TaurusLabel(self))
angles_taurus_label[i].setGeometry(
QtCore.QRect(50 + gap_x * i, 320, 81, 19))
atlname = "anglestauruslabel" + str(i)
angles_taurus_label[i].setObjectName(atlname)
angles_taurus_label[i].setModel(motor_names[i] + "/Position")
# Set model to hkl display
hmodel = self.h_device_name + "/Position"
self._ui.taurusValueLineH.setModel(hmodel)
self._ui.taurusLabelValueH.setModel(hmodel)
kmodel = self.k_device_name + "/Position"
self._ui.taurusValueLineK.setModel(kmodel)
self._ui.taurusLabelValueK.setModel(kmodel)
lmodel = self.l_device_name + "/Position"
self._ui.taurusValueLineL.setModel(lmodel)
self._ui.taurusLabelValueL.setModel(lmodel)
# Set model to engine and modes
enginemodel = model + '/engine'
self._ui.taurusLabelEngine.setModel(enginemodel)
enginemodemodel = model + '/enginemode'
self._ui.taurusLabelEngineMode.setModel(enginemodemodel)
self.enginemodescombobox = EngineModesComboBox(self)
self.enginemodescombobox.setGeometry(QtCore.QRect(150, 445, 221, 27))
self.enginemodescombobox.setObjectName("enginemodeslist")
self.enginemodescombobox.loadEngineModeNames(self.device.hklmodelist)
self.connect(self.enginemodescombobox, Qt.SIGNAL(
"currentIndexChanged(QString)"), self.onModeChanged)
def onModeChanged(self, modename):
if self.device.engine != "hkl":
self.device.write_attribute("engine", "hkl")
self.device.write_attribute("enginemode", str(modename))
def start_hklscan(self):
start_hkl = []
stop_hkl = []
start_hkl.append(float(self._ui.lineEditStartH.text()))
start_hkl.append(float(self._ui.lineEditStartK.text()))
start_hkl.append(float(self._ui.lineEditStartL.text()))
stop_hkl.append(float(self._ui.lineEditStopH.text()))
stop_hkl.append(float(self._ui.lineEditStopK.text()))
stop_hkl.append(float(self._ui.lineEditStopL.text()))
nb_points = int(self._ui.LineEditNbpoints.text())
sample_time = float(self._ui.LineEditSampleTime.text())
dim = 0
macro_name = ["ascan", "a2scan", "a3scan"]
macro_command = []
index_to_scan = []
if self.door_device != None:
for i in range(0, 3):
if start_hkl[i] != stop_hkl[i]:
dim = dim + 1
index_to_scan.append(i)
if dim > 0:
macro_command.append(macro_name[dim - 1])
for i in range(len(index_to_scan)):
macro_command.append(
str(self.pseudo_motor_names[index_to_scan[i]]))
macro_command.append(str(start_hkl[index_to_scan[i]]))
macro_command.append(str(stop_hkl[index_to_scan[i]]))
macro_command.append(str(nb_points))
macro_command.append(str(sample_time))
self.door_device.RunMacro(macro_command)
def stop_hklscan(self):
self.door_device.StopMacro()
def display_angles(self):
xangle = []
for i in range(0, 6):
xangle.append(40 + i * 100)
yhkl = 50
tr = self.device.selectedtrajectory
w = DisplayScanAngles()
angles_labels = []
angles_names = []
if self.nb_motors == 4:
angles_names.append("omega")
angles_names.append("chi")
angles_names.append("phi")
angles_names.append("theta")
elif self.nb_motors == 6:
angles_names.append("mu")
angles_names.append("th")
angles_names.append("chi")
angles_names.append("phi")
angles_names.append("gamma")
angles_names.append("delta")
dsa_label = []
for i in range(0, self.nb_motors):
dsa_label.append(QtGui.QLabel(w))
dsa_label[i].setGeometry(QtCore.QRect(xangle[i], yhkl, 51, 20))
label_name = "dsa_label_" + str(i)
dsa_label[i].setObjectName(label_name)
dsa_label[i].setText(QtGui.QApplication.translate(
"Form", angles_names[i], None, QtGui.QApplication.UnicodeUTF8))
start_hkl = []
stop_hkl = []
missed_values = 0
# TODO: This code will raise exception if one of the line edits is empty.
# But not all dimensions (H & K & L) are obligatory. One could try
# to display angles of just 1 or 2 dimensional scan.
try:
start_hkl.append(float(self._ui.lineEditStartH.text()))
start_hkl.append(float(self._ui.lineEditStartK.text()))
start_hkl.append(float(self._ui.lineEditStartL.text()))
stop_hkl.append(float(self._ui.lineEditStopH.text()))
stop_hkl.append(float(self._ui.lineEditStopK.text()))
stop_hkl.append(float(self._ui.lineEditStopL.text()))
nb_points = int(self._ui.LineEditNbpoints.text())
except:
nb_points = -1
missed_values = 1
increment_hkl = []
if nb_points > 0:
for i in range(0, 3):
increment_hkl.append((stop_hkl[i] - start_hkl[i]) / nb_points)
taurusValueAngle = []
for i in range(0, nb_points + 1):
hkl_temp = []
for j in range(0, 3):
hkl_temp.append(start_hkl[j] + i * increment_hkl[j])
no_trajectories = 0
try:
self.device.write_attribute("computetrajectoriessim", hkl_temp)
except:
no_trajectories = 1
if not no_trajectories:
angles_list = self.device.trajectorylist[tr]
taurusValueAngle.append([])
for iangle in range(0, self.nb_motors):
taurusValueAngle[i].append(TaurusValueLineEdit(w))
taurusValueAngle[i][iangle].setGeometry(
QtCore.QRect(xangle[iangle], yhkl + 30 * (i + 1), 80, 27))
taurusValueAngle[i][iangle].setReadOnly(True)
tva_name = "taurusValueAngle" + str(i) + "_" + str(iangle)
taurusValueAngle[i][iangle].setObjectName(tva_name)
taurusValueAngle[i][iangle].setValue(
"%10.4f" % angles_list[iangle])
else:
taurusValueAngle.append(TaurusValueLineEdit(w))
taurusValueAngle[i].setGeometry(QtCore.QRect(
xangle[0], yhkl + 30 * (i + 1), self.nb_motors * 120, 27))
taurusValueAngle[i].setReadOnly(True)
tva_name = "taurusValueAngle" + str(i)
taurusValueAngle[i].setObjectName(tva_name)
taurusValueAngle[i].setValue(
"... No angle solution for hkl values ...")
# TODO: not all dimensions (H & K & L) are obligatory. One could try
# to display angles of just 1 or 2 dimensional scan.
if nb_points == -1:
nb_points = 0
taurusValueAngle.append(TaurusValueLineEdit(w))
taurusValueAngle[0].setGeometry(QtCore.QRect(
xangle[0], yhkl + 30, self.nb_motors * 120, 27))
taurusValueAngle[0].setReadOnly(True)
tva_name = "taurusValueAngle"
taurusValueAngle[0].setObjectName(tva_name)
taurusValueAngle[0].setValue(
"... No scan parameters filled. Fill them in the main window ...")
w.resize(self.nb_motors * 140, 120 + nb_points * 40)
w.show()
w.show()
def open_macroserver_connection_panel(self):
w = TaurusMacroConfigurationDialog(self)
Qt.qApp.SDM.connectReader("macroserverName", w.selectMacroServer)
Qt.qApp.SDM.connectReader("doorName", w.selectDoor)
Qt.qApp.SDM.connectReader("doorName", self.onDoorChanged)
Qt.qApp.SDM.connectWriter(
"macroserverName", w, 'macroserverNameChanged')
Qt.qApp.SDM.connectWriter("doorName", w, 'doorNameChanged')
w.show()
def onDoorChanged(self, doorName):
if doorName != self.door_device_name:
self.door_device_name = doorName
self.door_device = taurus.Device(doorName)
def main():
parser = taurus.core.util.argparse.get_taurus_parser()
parser.usage = "%prog <model> [door_name]"
parser.set_description("a taurus application for performing hkl scans")
app = taurus.qt.qtgui.application.TaurusApplication(cmd_line_parser=parser,
app_version=sardana.Release.version)
app.setApplicationName("hklscan")
args = app.get_command_line_args()
if len(args) < 1:
msg = "model not set (requires diffractometer controller)"
parser.error(msg)
w = HKLScan()
w.model = args[0]
w.setModel(w.model)
w.door_device = None
w.door_device_name = None
if len(args) > 1:
w.onDoorChanged(args[1])
else:
print "WARNING: Not door name supplied. Connection to MacroServer/Door not automatically done"
w.show()
sys.exit(app.exec_())
# if len(sys.argv)>1: model=sys.argv[1]
# else: model = None
# app = Qt.QApplication(sys.argv)
# w = HKLScan()
# w.setModel(model)
# w.show()
# sys.exit(app.exec_())
if __name__ == "__main__":
main()
| lgpl-3.0 |
mlba-team/open-lighting | tools/rdm/DMXSender.py | 3 | 2219 | #!/usr/bin/python
# 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 Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
# DMXSenderThread.py
# Copyright (C) 2011 Simon Newton
__author__ = 'nomis52@gmail.com (Simon Newton)'
import array
import logging
class DMXSender(object):
def __init__(self, ola_wrapper, universe, frame_rate, slot_count):
"""Create a new DMXSender:
Args:
ola_wrapper: the ClientWrapper to use
universe: universe number to send on
frame_rate: frames per second
slot_count: number of slots to send
"""
self._wrapper = ola_wrapper
self._universe = universe
self._data = array.array('B')
self._frame_count = 0
self._slot_count = max(0, min(int(slot_count), 512))
self._send = True
if (frame_rate > 0 and slot_count > 0):
logging.info('Sending %d fps of DMX data with %d slots' %
(frame_rate, self._slot_count))
for i in xrange(0, self._slot_count):
self._data.append(0)
self._frame_interval = 1000 / frame_rate
self.SendDMXFrame()
def Stop(self):
self._send = False
def SendDMXFrame(self):
"""Send the next DMX Frame."""
for i in xrange(0, self._slot_count):
self._data[i] = self._frame_count % 255
self._frame_count += 1
self._wrapper.Client().SendDmx(self._universe,
self._data,
self.SendComplete)
if self._send:
self._wrapper.AddEvent(self._frame_interval, self.SendDMXFrame)
def SendComplete(self, state):
"""Called when the DMX send completes."""
| lgpl-2.1 |
Godiyos/python-for-android | python-build/python-libs/gdata/build/lib/gdata/client.py | 133 | 35227 | #!/usr/bin/env python
#
# Copyright (C) 2008, 2009 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# This module is used for version 2 of the Google Data APIs.
"""Provides a client to interact with Google Data API servers.
This module is used for version 2 of the Google Data APIs. The primary class
in this module is GDClient.
GDClient: handles auth and CRUD operations when communicating with servers.
GDataClient: deprecated client for version one services. Will be removed.
"""
__author__ = 'j.s@google.com (Jeff Scudder)'
import re
import atom.client
import atom.core
import atom.http_core
import gdata.gauth
import gdata.data
# Old imports
import gdata.service
import urllib
import urlparse
import gdata.auth
import atom
class Error(Exception):
pass
class RequestError(Error):
status = None
reason = None
body = None
headers = None
class RedirectError(RequestError):
pass
class CaptchaChallenge(RequestError):
captcha_url = None
captcha_token = None
class ClientLoginTokenMissing(Error):
pass
class MissingOAuthParameters(Error):
pass
class ClientLoginFailed(RequestError):
pass
class UnableToUpgradeToken(RequestError):
pass
class Unauthorized(Error):
pass
class BadAuthenticationServiceURL(RedirectError):
pass
class BadAuthentication(RequestError):
pass
def error_from_response(message, http_response, error_class, response_body=None):
"""Creates a new exception and sets the HTTP information in the error.
Args:
message: str human readable message to be displayed if the exception is
not caught.
http_response: The response from the server, contains error information.
error_class: The exception to be instantiated and populated with
information from the http_response
response_body: str (optional) specify if the response has already been read
from the http_response object.
"""
if response_body is None:
body = http_response.read()
else:
body = response_body
error = error_class('%s: %i, %s' % (message, http_response.status, body))
error.status = http_response.status
error.reason = http_response.reason
error.body = body
error.headers = http_response.getheaders()
return error
def get_xml_version(version):
"""Determines which XML schema to use based on the client API version.
Args:
version: string which is converted to an int. The version string is in
the form 'Major.Minor.x.y.z' and only the major version number
is considered. If None is provided assume version 1.
"""
if version is None:
return 1
return int(version.split('.')[0])
class GDClient(atom.client.AtomPubClient):
"""Communicates with Google Data servers to perform CRUD operations.
This class is currently experimental and may change in backwards
incompatible ways.
This class exists to simplify the following three areas involved in using
the Google Data APIs.
CRUD Operations:
The client provides a generic 'request' method for making HTTP requests.
There are a number of convenience methods which are built on top of
request, which include get_feed, get_entry, get_next, post, update, and
delete. These methods contact the Google Data servers.
Auth:
Reading user-specific private data requires authorization from the user as
do any changes to user data. An auth_token object can be passed into any
of the HTTP requests to set the Authorization header in the request.
You may also want to set the auth_token member to a an object which can
use modify_request to set the Authorization header in the HTTP request.
If you are authenticating using the email address and password, you can
use the client_login method to obtain an auth token and set the
auth_token member.
If you are using browser redirects, specifically AuthSub, you will want
to use gdata.gauth.AuthSubToken.from_url to obtain the token after the
redirect, and you will probably want to updgrade this since use token
to a multiple use (session) token using the upgrade_token method.
API Versions:
This client is multi-version capable and can be used with Google Data API
version 1 and version 2. The version should be specified by setting the
api_version member to a string, either '1' or '2'.
"""
# The gsessionid is used by Google Calendar to prevent redirects.
__gsessionid = None
api_version = None
# Name of the Google Data service when making a ClientLogin request.
auth_service = None
# URL prefixes which should be requested for AuthSub and OAuth.
auth_scopes = None
def request(self, method=None, uri=None, auth_token=None,
http_request=None, converter=None, desired_class=None,
redirects_remaining=4, **kwargs):
"""Make an HTTP request to the server.
See also documentation for atom.client.AtomPubClient.request.
If a 302 redirect is sent from the server to the client, this client
assumes that the redirect is in the form used by the Google Calendar API.
The same request URI and method will be used as in the original request,
but a gsessionid URL parameter will be added to the request URI with
the value provided in the server's 302 redirect response. If the 302
redirect is not in the format specified by the Google Calendar API, a
RedirectError will be raised containing the body of the server's
response.
The method calls the client's modify_request method to make any changes
required by the client before the request is made. For example, a
version 2 client could add a GData-Version: 2 header to the request in
its modify_request method.
Args:
method: str The HTTP verb for this request, usually 'GET', 'POST',
'PUT', or 'DELETE'
uri: atom.http_core.Uri, str, or unicode The URL being requested.
auth_token: An object which sets the Authorization HTTP header in its
modify_request method. Recommended classes include
gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
among others.
http_request: (optional) atom.http_core.HttpRequest
converter: function which takes the body of the response as it's only
argument and returns the desired object.
desired_class: class descended from atom.core.XmlElement to which a
successful response should be converted. If there is no
converter function specified (converter=None) then the
desired_class will be used in calling the
atom.core.parse function. If neither
the desired_class nor the converter is specified, an
HTTP reponse object will be returned.
redirects_remaining: (optional) int, if this number is 0 and the
server sends a 302 redirect, the request method
will raise an exception. This parameter is used in
recursive request calls to avoid an infinite loop.
Any additional arguments are passed through to
atom.client.AtomPubClient.request.
Returns:
An HTTP response object (see atom.http_core.HttpResponse for a
description of the object's interface) if no converter was
specified and no desired_class was specified. If a converter function
was provided, the results of calling the converter are returned. If no
converter was specified but a desired_class was provided, the response
body will be converted to the class using
atom.core.parse.
"""
if isinstance(uri, (str, unicode)):
uri = atom.http_core.Uri.parse_uri(uri)
# Add the gsession ID to the URL to prevent further redirects.
# TODO: If different sessions are using the same client, there will be a
# multitude of redirects and session ID shuffling.
# If the gsession ID is in the URL, adopt it as the standard location.
if uri is not None and uri.query is not None and 'gsessionid' in uri.query:
self.__gsessionid = uri.query['gsessionid']
# The gsession ID could also be in the HTTP request.
elif (http_request is not None and http_request.uri is not None
and http_request.uri.query is not None
and 'gsessionid' in http_request.uri.query):
self.__gsessionid = http_request.uri.query['gsessionid']
# If the gsession ID is stored in the client, and was not present in the
# URI then add it to the URI.
elif self.__gsessionid is not None:
uri.query['gsessionid'] = self.__gsessionid
# The AtomPubClient should call this class' modify_request before
# performing the HTTP request.
#http_request = self.modify_request(http_request)
response = atom.client.AtomPubClient.request(self, method=method,
uri=uri, auth_token=auth_token, http_request=http_request, **kwargs)
# On success, convert the response body using the desired converter
# function if present.
if response is None:
return None
if response.status == 200 or response.status == 201:
if converter is not None:
return converter(response)
elif desired_class is not None:
if self.api_version is not None:
return atom.core.parse(response.read(), desired_class,
version=get_xml_version(self.api_version))
else:
# No API version was specified, so allow parse to
# use the default version.
return atom.core.parse(response.read(), desired_class)
else:
return response
# TODO: move the redirect logic into the Google Calendar client once it
# exists since the redirects are only used in the calendar API.
elif response.status == 302:
if redirects_remaining > 0:
location = response.getheader('Location')
if location is not None:
m = re.compile('[\?\&]gsessionid=(\w*)').search(location)
if m is not None:
self.__gsessionid = m.group(1)
# Make a recursive call with the gsession ID in the URI to follow
# the redirect.
return self.request(method=method, uri=uri, auth_token=auth_token,
http_request=http_request, converter=converter,
desired_class=desired_class,
redirects_remaining=redirects_remaining-1,
**kwargs)
else:
raise error_from_response('302 received without Location header',
response, RedirectError)
else:
raise error_from_response('Too many redirects from server',
response, RedirectError)
elif response.status == 401:
raise error_from_response('Unauthorized - Server responded with',
response, Unauthorized)
# If the server's response was not a 200, 201, 302, or 401, raise an
# exception.
else:
raise error_from_response('Server responded with', response,
RequestError)
Request = request
def request_client_login_token(self, email, password, source, service=None,
account_type='HOSTED_OR_GOOGLE',
auth_url=atom.http_core.Uri.parse_uri(
'https://www.google.com/accounts/ClientLogin'),
captcha_token=None, captcha_response=None):
service = service or self.auth_service
# Set the target URL.
http_request = atom.http_core.HttpRequest(uri=auth_url, method='POST')
http_request.add_body_part(
gdata.gauth.generate_client_login_request_body(email=email,
password=password, service=service, source=source,
account_type=account_type, captcha_token=captcha_token,
captcha_response=captcha_response),
'application/x-www-form-urlencoded')
# Use the underlying http_client to make the request.
response = self.http_client.request(http_request)
response_body = response.read()
if response.status == 200:
token_string = gdata.gauth.get_client_login_token_string(response_body)
if token_string is not None:
return gdata.gauth.ClientLoginToken(token_string)
else:
raise ClientLoginTokenMissing(
'Recieved a 200 response to client login request,'
' but no token was present. %s' % (response_body,))
elif response.status == 403:
captcha_challenge = gdata.gauth.get_captcha_challenge(response_body)
if captcha_challenge:
challenge = CaptchaChallenge('CAPTCHA required')
challenge.captcha_url = captcha_challenge['url']
challenge.captcha_token = captcha_challenge['token']
raise challenge
elif response_body.splitlines()[0] == 'Error=BadAuthentication':
raise BadAuthentication('Incorrect username or password')
else:
raise error_from_response('Server responded with a 403 code',
response, RequestError, response_body)
elif response.status == 302:
# Google tries to redirect all bad URLs back to
# http://www.google.<locale>. If a redirect
# attempt is made, assume the user has supplied an incorrect
# authentication URL
raise error_from_response('Server responded with a redirect',
response, BadAuthenticationServiceURL,
response_body)
else:
raise error_from_response('Server responded to ClientLogin request',
response, ClientLoginFailed, response_body)
RequestClientLoginToken = request_client_login_token
def client_login(self, email, password, source, service=None,
account_type='HOSTED_OR_GOOGLE',
auth_url='https://www.google.com/accounts/ClientLogin',
captcha_token=None, captcha_response=None):
service = service or self.auth_service
self.auth_token = self.request_client_login_token(email, password,
source, service=service, account_type=account_type, auth_url=auth_url,
captcha_token=captcha_token, captcha_response=captcha_response)
ClientLogin = client_login
def upgrade_token(self, token=None, url=atom.http_core.Uri.parse_uri(
'https://www.google.com/accounts/AuthSubSessionToken')):
"""Asks the Google auth server for a multi-use AuthSub token.
For details on AuthSub, see:
http://code.google.com/apis/accounts/docs/AuthSub.html
Args:
token: gdata.gauth.AuthSubToken or gdata.gauth.SecureAuthSubToken
(optional) If no token is passed in, the client's auth_token member
is used to request the new token. The token object will be modified
to contain the new session token string.
url: str or atom.http_core.Uri (optional) The URL to which the token
upgrade request should be sent. Defaults to:
https://www.google.com/accounts/AuthSubSessionToken
Returns:
The upgraded gdata.gauth.AuthSubToken object.
"""
# Default to using the auth_token member if no token is provided.
if token is None:
token = self.auth_token
# We cannot upgrade a None token.
if token is None:
raise UnableToUpgradeToken('No token was provided.')
if not isinstance(token, gdata.gauth.AuthSubToken):
raise UnableToUpgradeToken(
'Cannot upgrade the token because it is not an AuthSubToken object.')
http_request = atom.http_core.HttpRequest(uri=url, method='GET')
token.modify_request(http_request)
# Use the lower level HttpClient to make the request.
response = self.http_client.request(http_request)
if response.status == 200:
token._upgrade_token(response.read())
return token
else:
raise UnableToUpgradeToken(
'Server responded to token upgrade request with %s: %s' % (
response.status, response.read()))
UpgradeToken = upgrade_token
def get_oauth_token(self, scopes, next, consumer_key, consumer_secret=None,
rsa_private_key=None,
url=gdata.gauth.REQUEST_TOKEN_URL):
"""Obtains an OAuth request token to allow the user to authorize this app.
Once this client has a request token, the user can authorize the request
token by visiting the authorization URL in their browser. After being
redirected back to this app at the 'next' URL, this app can then exchange
the authorized request token for an access token.
For more information see the documentation on Google Accounts with OAuth:
http://code.google.com/apis/accounts/docs/OAuth.html#AuthProcess
Args:
scopes: list of strings or atom.http_core.Uri objects which specify the
URL prefixes which this app will be accessing. For example, to access
the Google Calendar API, you would want to use scopes:
['https://www.google.com/calendar/feeds/',
'http://www.google.com/calendar/feeds/']
next: str or atom.http_core.Uri object, The URL which the user's browser
should be sent to after they authorize access to their data. This
should be a URL in your application which will read the token
information from the URL and upgrade the request token to an access
token.
consumer_key: str This is the identifier for this application which you
should have received when you registered your application with Google
to use OAuth.
consumer_secret: str (optional) The shared secret between your app and
Google which provides evidence that this request is coming from you
application and not another app. If present, this libraries assumes
you want to use an HMAC signature to verify requests. Keep this data
a secret.
rsa_private_key: str (optional) The RSA private key which is used to
generate a digital signature which is checked by Google's server. If
present, this library assumes that you want to use an RSA signature
to verify requests. Keep this data a secret.
url: The URL to which a request for a token should be made. The default
is Google's OAuth request token provider.
"""
http_request = None
if rsa_private_key is not None:
http_request = gdata.gauth.generate_request_for_request_token(
consumer_key, gdata.gauth.RSA_SHA1, scopes,
rsa_key=rsa_private_key, auth_server_url=url, next=next)
elif consumer_secret is not None:
http_request = gdata.gauth.generate_request_for_request_token(
consumer_key, gdata.gauth.HMAC_SHA1, scopes,
consumer_secret=consumer_secret, auth_server_url=url, next=next)
else:
raise MissingOAuthParameters(
'To request an OAuth token, you must provide your consumer secret'
' or your private RSA key.')
response = self.http_client.request(http_request)
response_body = response.read()
if response.status != 200:
raise error_from_response('Unable to obtain OAuth request token',
response, RequestError, response_body)
if rsa_private_key is not None:
return gdata.gauth.rsa_token_from_body(response_body, consumer_key,
rsa_private_key,
gdata.gauth.REQUEST_TOKEN)
elif consumer_secret is not None:
return gdata.gauth.hmac_token_from_body(response_body, consumer_key,
consumer_secret,
gdata.gauth.REQUEST_TOKEN)
GetOAuthToken = get_oauth_token
def get_access_token(self, request_token,
url=gdata.gauth.ACCESS_TOKEN_URL):
"""Exchanges an authorized OAuth request token for an access token.
Contacts the Google OAuth server to upgrade a previously authorized
request token. Once the request token is upgraded to an access token,
the access token may be used to access the user's data.
For more details, see the Google Accounts OAuth documentation:
http://code.google.com/apis/accounts/docs/OAuth.html#AccessToken
Args:
request_token: An OAuth token which has been authorized by the user.
url: (optional) The URL to which the upgrade request should be sent.
Defaults to: https://www.google.com/accounts/OAuthAuthorizeToken
"""
http_request = gdata.gauth.generate_request_for_access_token(
request_token, auth_server_url=url)
response = self.http_client.request(http_request)
response_body = response.read()
if response.status != 200:
raise error_from_response(
'Unable to upgrade OAuth request token to access token',
response, RequestError, response_body)
return gdata.gauth.upgrade_to_access_token(request_token, response_body)
GetAccessToken = get_access_token
def modify_request(self, http_request):
"""Adds or changes request before making the HTTP request.
This client will add the API version if it is specified.
Subclasses may override this method to add their own request
modifications before the request is made.
"""
http_request = atom.client.AtomPubClient.modify_request(self,
http_request)
if self.api_version is not None:
http_request.headers['GData-Version'] = self.api_version
return http_request
ModifyRequest = modify_request
def get_feed(self, uri, auth_token=None, converter=None,
desired_class=gdata.data.GDFeed, **kwargs):
return self.request(method='GET', uri=uri, auth_token=auth_token,
converter=converter, desired_class=desired_class,
**kwargs)
GetFeed = get_feed
def get_entry(self, uri, auth_token=None, converter=None,
desired_class=gdata.data.GDEntry, **kwargs):
return self.request(method='GET', uri=uri, auth_token=auth_token,
converter=converter, desired_class=desired_class,
**kwargs)
GetEntry = get_entry
def get_next(self, feed, auth_token=None, converter=None,
desired_class=None, **kwargs):
"""Fetches the next set of results from the feed.
When requesting a feed, the number of entries returned is capped at a
service specific default limit (often 25 entries). You can specify your
own entry-count cap using the max-results URL query parameter. If there
are more results than could fit under max-results, the feed will contain
a next link. This method performs a GET against this next results URL.
Returns:
A new feed object containing the next set of entries in this feed.
"""
if converter is None and desired_class is None:
desired_class = feed.__class__
return self.get_feed(feed.get_next_url(), auth_token=auth_token,
converter=converter, desired_class=desired_class,
**kwargs)
GetNext = get_next
# TODO: add a refresh method to re-fetch the entry/feed from the server
# if it has been updated.
def post(self, entry, uri, auth_token=None, converter=None,
desired_class=None, **kwargs):
if converter is None and desired_class is None:
desired_class = entry.__class__
http_request = atom.http_core.HttpRequest()
http_request.add_body_part(
entry.to_string(get_xml_version(self.api_version)),
'application/atom+xml')
return self.request(method='POST', uri=uri, auth_token=auth_token,
http_request=http_request, converter=converter,
desired_class=desired_class, **kwargs)
Post = post
def update(self, entry, auth_token=None, force=False, **kwargs):
"""Edits the entry on the server by sending the XML for this entry.
Performs a PUT and converts the response to a new entry object with a
matching class to the entry passed in.
Args:
entry:
auth_token:
force: boolean stating whether an update should be forced. Defaults to
False. Normally, if a change has been made since the passed in
entry was obtained, the server will not overwrite the entry since
the changes were based on an obsolete version of the entry.
Setting force to True will cause the update to silently
overwrite whatever version is present.
Returns:
A new Entry object of a matching type to the entry which was passed in.
"""
http_request = atom.http_core.HttpRequest()
http_request.add_body_part(
entry.to_string(get_xml_version(self.api_version)),
'application/atom+xml')
# Include the ETag in the request if this is version 2 of the API.
if self.api_version and self.api_version.startswith('2'):
if force:
http_request.headers['If-Match'] = '*'
elif hasattr(entry, 'etag') and entry.etag:
http_request.headers['If-Match'] = entry.etag
return self.request(method='PUT', uri=entry.find_edit_link(),
auth_token=auth_token, http_request=http_request,
desired_class=entry.__class__, **kwargs)
Update = update
def delete(self, entry_or_uri, auth_token=None, force=False, **kwargs):
# If the user passes in a URL, just delete directly, may not work as
# the service might require an ETag.
if isinstance(entry_or_uri, (str, unicode, atom.http_core.Uri)):
return self.request(method='DELETE', uri=entry_or_uri,
auth_token=auth_token, **kwargs)
http_request = atom.http_core.HttpRequest()
# Include the ETag in the request if this is version 2 of the API.
if self.api_version and self.api_version.startswith('2'):
if force:
http_request.headers['If-Match'] = '*'
elif hasattr(entry_or_uri, 'etag') and entry_or_uri.etag:
http_request.headers['If-Match'] = entry_or_uri.etag
return self.request(method='DELETE', uri=entry_or_uri.find_edit_link(),
http_request=http_request, auth_token=auth_token,
**kwargs)
Delete = delete
#TODO: implement batch requests.
#def batch(feed, uri, auth_token=None, converter=None, **kwargs):
# pass
# TODO: add a refresh method to request a conditional update to an entry
# or feed.
def _add_query_param(param_string, value, http_request):
if value:
http_request.uri.query[param_string] = value
class Query(object):
def __init__(self, text_query=None, categories=None, author=None, alt=None,
updated_min=None, updated_max=None, pretty_print=False,
published_min=None, published_max=None, start_index=None,
max_results=None, strict=False):
"""Constructs a Google Data Query to filter feed contents serverside.
Args:
text_query: Full text search str (optional)
categories: list of strings (optional). Each string is a required
category. To include an 'or' query, put a | in the string between
terms. For example, to find everything in the Fitz category and
the Laurie or Jane category (Fitz and (Laurie or Jane)) you would
set categories to ['Fitz', 'Laurie|Jane'].
author: str (optional) The service returns entries where the author
name and/or email address match your query string.
alt: str (optional) for the Alternative representation type you'd like
the feed in. If you don't specify an alt parameter, the service
returns an Atom feed. This is equivalent to alt='atom'.
alt='rss' returns an RSS 2.0 result feed.
alt='json' returns a JSON representation of the feed.
alt='json-in-script' Requests a response that wraps JSON in a script
tag.
alt='atom-in-script' Requests an Atom response that wraps an XML
string in a script tag.
alt='rss-in-script' Requests an RSS response that wraps an XML
string in a script tag.
updated_min: str (optional), RFC 3339 timestamp format, lower bounds.
For example: 2005-08-09T10:57:00-08:00
updated_max: str (optional) updated time must be earlier than timestamp.
pretty_print: boolean (optional) If True the server's XML response will
be indented to make it more human readable. Defaults to False.
published_min: str (optional), Similar to updated_min but for published
time.
published_max: str (optional), Similar to updated_max but for published
time.
start_index: int or str (optional) 1-based index of the first result to
be retrieved. Note that this isn't a general cursoring mechanism.
If you first send a query with ?start-index=1&max-results=10 and
then send another query with ?start-index=11&max-results=10, the
service cannot guarantee that the results are equivalent to
?start-index=1&max-results=20, because insertions and deletions
could have taken place in between the two queries.
max_results: int or str (optional) Maximum number of results to be
retrieved. Each service has a default max (usually 25) which can
vary from service to service. There is also a service-specific
limit to the max_results you can fetch in a request.
strict: boolean (optional) If True, the server will return an error if
the server does not recognize any of the parameters in the request
URL. Defaults to False.
"""
self.text_query = text_query
self.categories = categories or []
self.author = author
self.alt = alt
self.updated_min = updated_min
self.updated_max = updated_max
self.pretty_print = pretty_print
self.published_min = published_min
self.published_max = published_max
self.start_index = start_index
self.max_results = max_results
self.strict = strict
def modify_request(self, http_request):
_add_query_param('q', self.text_query, http_request)
if self.categories:
http_request.uri.query['categories'] = ','.join(self.categories)
_add_query_param('author', self.author, http_request)
_add_query_param('alt', self.alt, http_request)
_add_query_param('updated-min', self.updated_min, http_request)
_add_query_param('updated-max', self.updated_max, http_request)
if self.pretty_print:
http_request.uri.query['prettyprint'] = 'true'
_add_query_param('published-min', self.published_min, http_request)
_add_query_param('published-max', self.published_max, http_request)
if self.start_index is not None:
http_request.uri.query['start-index'] = str(self.start_index)
if self.max_results is not None:
http_request.uri.query['max-results'] = str(self.max_results)
if self.strict:
http_request.uri.query['strict'] = 'true'
ModifyRequest = modify_request
class GDQuery(atom.http_core.Uri):
def _get_text_query(self):
return self.query['q']
def _set_text_query(self, value):
self.query['q'] = value
text_query = property(_get_text_query, _set_text_query,
doc='The q parameter for searching for an exact text match on content')
# Version 1 code.
SCOPE_URL_PARAM_NAME = gdata.service.SCOPE_URL_PARAM_NAME
# Maps the service names used in ClientLogin to scope URLs.
CLIENT_LOGIN_SCOPES = gdata.service.CLIENT_LOGIN_SCOPES
class AuthorizationRequired(gdata.service.Error):
pass
class GDataClient(gdata.service.GDataService):
"""This class is deprecated.
All functionality has been migrated to gdata.service.GDataService.
"""
@atom.deprecated('This class will be removed, use GDClient instead.')
def __init__(self, application_name=None, tokens=None):
gdata.service.GDataService.__init__(self, source=application_name,
tokens=tokens)
@atom.deprecated('The GDataClient class will be removed in a future release'
', use GDClient.ClientLogin instead')
def ClientLogin(self, username, password, service_name, source=None,
account_type=None, auth_url=None, login_token=None, login_captcha=None):
gdata.service.GDataService.ClientLogin(self, username=username,
password=password, account_type=account_type, service=service_name,
auth_service_url=auth_url, source=source, captcha_token=login_token,
captcha_response=login_captcha)
@atom.deprecated('The GDataClient class will be removed in a future release'
', use GDClient.GetEntry or GDClient.GetFeed')
def Get(self, url, parser):
"""Simplified interface for Get.
Requires a parser function which takes the server response's body as
the only argument.
Args:
url: A string or something that can be converted to a string using str.
The URL of the requested resource.
parser: A function which takes the HTTP body from the server as it's
only result. Common values would include str,
gdata.GDataEntryFromString, and gdata.GDataFeedFromString.
Returns: The result of calling parser(http_response_body).
"""
return gdata.service.GDataService.Get(self, uri=url, converter=parser)
@atom.deprecated('The GDataClient class will be removed in a future release'
', use GDClient.Post instead')
def Post(self, data, url, parser, media_source=None):
"""Streamlined version of Post.
Requires a parser function which takes the server response's body as
the only argument.
"""
return gdata.service.GDataService.Post(self, data=data, uri=url,
media_source=media_source, converter=parser)
@atom.deprecated('The GDataClient class will be removed in a future release'
', use GDClient.Put instead')
def Put(self, data, url, parser, media_source=None):
"""Streamlined version of Put.
Requires a parser function which takes the server response's body as
the only argument.
"""
return gdata.service.GDataService.Put(self, data=data, uri=url,
media_source=media_source, converter=parser)
@atom.deprecated('The GDataClient class will be removed in a future release'
', use GDClient.Delete instead')
def Delete(self, url):
return gdata.service.GDataService.Delete(self, uri=url)
ExtractToken = gdata.service.ExtractToken
GenerateAuthSubRequestUrl = gdata.service.GenerateAuthSubRequestUrl
| apache-2.0 |
sertac/django | django/core/mail/backends/smtp.py | 477 | 5239 | """SMTP email backend class."""
import smtplib
import ssl
import threading
from django.conf import settings
from django.core.mail.backends.base import BaseEmailBackend
from django.core.mail.message import sanitize_address
from django.core.mail.utils import DNS_NAME
class EmailBackend(BaseEmailBackend):
"""
A wrapper that manages the SMTP network connection.
"""
def __init__(self, host=None, port=None, username=None, password=None,
use_tls=None, fail_silently=False, use_ssl=None, timeout=None,
ssl_keyfile=None, ssl_certfile=None,
**kwargs):
super(EmailBackend, self).__init__(fail_silently=fail_silently)
self.host = host or settings.EMAIL_HOST
self.port = port or settings.EMAIL_PORT
self.username = settings.EMAIL_HOST_USER if username is None else username
self.password = settings.EMAIL_HOST_PASSWORD if password is None else password
self.use_tls = settings.EMAIL_USE_TLS if use_tls is None else use_tls
self.use_ssl = settings.EMAIL_USE_SSL if use_ssl is None else use_ssl
self.timeout = settings.EMAIL_TIMEOUT if timeout is None else timeout
self.ssl_keyfile = settings.EMAIL_SSL_KEYFILE if ssl_keyfile is None else ssl_keyfile
self.ssl_certfile = settings.EMAIL_SSL_CERTFILE if ssl_certfile is None else ssl_certfile
if self.use_ssl and self.use_tls:
raise ValueError(
"EMAIL_USE_TLS/EMAIL_USE_SSL are mutually exclusive, so only set "
"one of those settings to True.")
self.connection = None
self._lock = threading.RLock()
def open(self):
"""
Ensures we have a connection to the email server. Returns whether or
not a new connection was required (True or False).
"""
if self.connection:
# Nothing to do if the connection is already open.
return False
connection_class = smtplib.SMTP_SSL if self.use_ssl else smtplib.SMTP
# If local_hostname is not specified, socket.getfqdn() gets used.
# For performance, we use the cached FQDN for local_hostname.
connection_params = {'local_hostname': DNS_NAME.get_fqdn()}
if self.timeout is not None:
connection_params['timeout'] = self.timeout
if self.use_ssl:
connection_params.update({
'keyfile': self.ssl_keyfile,
'certfile': self.ssl_certfile,
})
try:
self.connection = connection_class(self.host, self.port, **connection_params)
# TLS/SSL are mutually exclusive, so only attempt TLS over
# non-secure connections.
if not self.use_ssl and self.use_tls:
self.connection.ehlo()
self.connection.starttls(keyfile=self.ssl_keyfile, certfile=self.ssl_certfile)
self.connection.ehlo()
if self.username and self.password:
self.connection.login(self.username, self.password)
return True
except smtplib.SMTPException:
if not self.fail_silently:
raise
def close(self):
"""Closes the connection to the email server."""
if self.connection is None:
return
try:
try:
self.connection.quit()
except (ssl.SSLError, smtplib.SMTPServerDisconnected):
# This happens when calling quit() on a TLS connection
# sometimes, or when the connection was already disconnected
# by the server.
self.connection.close()
except smtplib.SMTPException:
if self.fail_silently:
return
raise
finally:
self.connection = None
def send_messages(self, email_messages):
"""
Sends one or more EmailMessage objects and returns the number of email
messages sent.
"""
if not email_messages:
return
with self._lock:
new_conn_created = self.open()
if not self.connection:
# We failed silently on open().
# Trying to send would be pointless.
return
num_sent = 0
for message in email_messages:
sent = self._send(message)
if sent:
num_sent += 1
if new_conn_created:
self.close()
return num_sent
def _send(self, email_message):
"""A helper method that does the actual sending."""
if not email_message.recipients():
return False
from_email = sanitize_address(email_message.from_email, email_message.encoding)
recipients = [sanitize_address(addr, email_message.encoding)
for addr in email_message.recipients()]
message = email_message.message()
try:
self.connection.sendmail(from_email, recipients, message.as_bytes(linesep='\r\n'))
except smtplib.SMTPException:
if not self.fail_silently:
raise
return False
return True
| bsd-3-clause |
numenta/htmresearch | htmresearch/support/lateral_pooler/utils.py | 4 | 5174 | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2017, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Affero Public License for more details.
#
# You should have received a copy of the GNU Affero Public License
# along with this program. If not, see http://www.gnu.org/licenses.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------
import numpy as np
import uuid
from scipy.stats import entropy
import pickle
import os
def get_permanence_vals(sp):
m = sp.getNumInputs()
n = np.prod(sp.getColumnDimensions())
W = np.zeros((n, m))
for i in range(sp._numColumns):
sp.getPermanence(i, W[i, :])
return W
def update_statistics(Y, P, beta=0.9):
"""
Args
----
Y:
2d array whose columns encode the
activity of the output units
P:
2d array encoding the pairwise average
activity of the output units
Returns
-------
The updated average activities
"""
(n, d) = Y.shape
A = np.expand_dims(Y, axis=1) * np.expand_dims(Y, axis=0)
assert(A.shape == (n, n, d))
Q = np.mean(A, axis=2)
Q[np.where(Q == 0.)] = 0.000001
assert(P.shape == Q.shape)
return beta*P + (1-beta)*Q
def compute_probabilities_from(Y):
(n, d) = Y.shape
A = np.expand_dims(Y, axis=1) * np.expand_dims(Y, axis=0)
P = np.mean(A, axis=2)
return P
def compute_conditional_probabilies(Y):
(n, d) = Y.shape
A = np.expand_dims(Y, axis=1) * np.expand_dims(Y, axis=0)
assert(A.shape == (n, n, d))
Q = np.mean(A, axis=2)
Q[np.where(Q == 0.)] = 0.000001
assert(P.shape == Q.shape)
Diag = Q.diagonal().reshape((n,1))
Q = Q / Diag
np.fill_diagonal(Q, 0.)
Q = Q + np.diag(Diag.reshape(-1))
return beta*P + (1-beta)*Q
def random_mini_batches(X, Y, minibatch_size, seed=None):
"""
Compute a list of minibatches from inputs X and targets Y.
A datapoint is expected to be represented as a column in
the data matrices X and Y.
"""
d = X.shape[1]
size = minibatch_size
minibatches = []
if Y is None:
Y = np.zeros((1, d))
np.random.seed(seed)
perm = np.random.permutation(d)
for t in range(0, d, size):
subset = perm[t: t+size]
minibatches.append((X[:, subset], Y[:, subset]))
return minibatches
def scalar_reconstruction(x):
# x = (x>0.05).astype(float)
v = [ x[i]*i for i in range(len(x))]
s = np.mean(v)
s = s/len(x)
return s
def trim_doc(docstring):
""""
Removes the indentation from a docstring.
Credit goes to:
http://codedump.tumblr.com/post/94712647/handling-python-docstring-indentation
"""
if not docstring:
return ''
lines = docstring.expandtabs().splitlines()
# Determine minimum indentation (first line doesn't count):
indent = sys.maxsize
for line in lines[1:]:
stripped = line.lstrip()
if stripped:
indent = min(indent, len(line) - len(stripped))
# Remove indentation (first line is special):
trimmed = [lines[0].strip()]
if indent < sys.maxsize:
for line in lines[1:]:
trimmed.append(line[indent:].rstrip())
# Strip off trailing and leading blank lines:while trimmed and not trimmed[-1]:
trimmed.pop()
while trimmed and not trimmed[0]:
trimmed.pop(0)
return '\n'.join(trimmed)
def random_id(length):
"""Returns a random id of specified length."""
assert(length < 10)
x = str(uuid.uuid4())
return x[:length]
def create_movie(fig, update_figure, filename, title, fps=15, dpi=100):
"""Helps us to create a movie."""
FFMpegWriter = manimation.writers['ffmpeg']
metadata = dict(title=title)
writer = FFMpegWriter(fps=fps, metadata=metadata)
with writer.saving(fig, filename, dpi):
t = 0
while True:
if update_figure(t):
writer.grab_frame()
t += 1
else:
break
def add_noise(X, noise_level = 0.05):
noisy_X = X.copy()
noise = (np.random.sample(X.shape) < noise_level)
mask = np.where( noise == True )
noisy_X[mask] = X[mask] + (-1.0)**X[mask]
assert(noisy_X.shape == X.shape)
return noisy_X
def add_noisy_bits(X, noise_level = 0.05):
noisy_X = X.copy()
noise = (np.random.sample(X.shape) < noise_level)
mask = np.where( noise == True )
noisy_X[mask] = 1.0
assert(noisy_X.shape == X.shape)
return noisy_X
def subtract_noisy_bits(X, noise_level = 0.05):
noisy_X = X.copy()
noise = (np.random.sample(X.shape) < noise_level)
mask = np.where( noise == True )
noisy_X[mask] = 0.0
assert(noisy_X.shape == X.shape)
return noisy_X
| agpl-3.0 |
ThinkOpen-Solutions/odoo | addons/l10n_be_hr_payroll_account/__init__.py | 430 | 1046 | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2011 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/>
#
##############################################################################
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
skybird6672/micropython | tools/insert-usb-ids.py | 32 | 1311 | # Reads the USB VID and PID from the file specifed by sys.arg[1] and then
# inserts those values into the template file specified by sys.argv[2],
# printing the result to stdout
from __future__ import print_function
import sys
import re
import string
def parse_usb_ids(filename):
rv = dict()
if filename == 'usbd_desc.c':
for line in open(filename).readlines():
line = line.rstrip('\r\n')
match = re.match('^#define\s+(\w+)\s+0x([0-9A-Fa-f]+)$', line)
if match:
if match.group(1) == 'USBD_VID':
rv['USB_VID'] = match.group(2)
elif match.group(1) == 'USBD_PID':
rv['USB_PID'] = match.group(2)
if 'USB_VID' in rv and 'USB_PID' in rv:
break
else:
raise Exception("Don't (yet) know how to parse USB IDs from %s" % filename)
for k in ('USB_PID', 'USB_VID'):
if k not in rv:
raise Exception("Unable to parse %s from %s" % (k, filename))
return rv
if __name__ == "__main__":
usb_ids_file = sys.argv[1]
template_file = sys.argv[2]
replacements = parse_usb_ids(usb_ids_file)
for line in open(template_file, 'r').readlines():
print(string.Template(line).safe_substitute(replacements), end='')
| mit |
creativcoder/servo | tests/wpt/css-tests/tools/pywebsocket/src/test/testdata/handlers/sub/wrong_transfer_sig_wsh.py | 499 | 1854 | # 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.
"""Wrong web_socket_transfer_data() signature.
"""
def web_socket_do_extra_handshake(request):
pass
def no_web_socket_transfer_data(request):
request.connection.write(
'sub/wrong_transfer_sig_wsh.py is called for %s, %s' %
(request.ws_resource, request.ws_protocol))
# vi:sts=4 sw=4 et
| mpl-2.0 |
qqzwc/XX-Net | code/default/python27/1.0/lib/encodings/cp856.py | 593 | 12679 | """ Python Character Mapping Codec cp856 generated from 'MAPPINGS/VENDORS/MISC/CP856.TXT' with gencodec.py.
"""#"
import codecs
### Codec APIs
class Codec(codecs.Codec):
def encode(self,input,errors='strict'):
return codecs.charmap_encode(input,errors,encoding_table)
def decode(self,input,errors='strict'):
return codecs.charmap_decode(input,errors,decoding_table)
class IncrementalEncoder(codecs.IncrementalEncoder):
def encode(self, input, final=False):
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
class IncrementalDecoder(codecs.IncrementalDecoder):
def decode(self, input, final=False):
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
class StreamWriter(Codec,codecs.StreamWriter):
pass
class StreamReader(Codec,codecs.StreamReader):
pass
### encodings module API
def getregentry():
return codecs.CodecInfo(
name='cp856',
encode=Codec().encode,
decode=Codec().decode,
incrementalencoder=IncrementalEncoder,
incrementaldecoder=IncrementalDecoder,
streamreader=StreamReader,
streamwriter=StreamWriter,
)
### Decoding Table
decoding_table = (
u'\x00' # 0x00 -> NULL
u'\x01' # 0x01 -> START OF HEADING
u'\x02' # 0x02 -> START OF TEXT
u'\x03' # 0x03 -> END OF TEXT
u'\x04' # 0x04 -> END OF TRANSMISSION
u'\x05' # 0x05 -> ENQUIRY
u'\x06' # 0x06 -> ACKNOWLEDGE
u'\x07' # 0x07 -> BELL
u'\x08' # 0x08 -> BACKSPACE
u'\t' # 0x09 -> HORIZONTAL TABULATION
u'\n' # 0x0A -> LINE FEED
u'\x0b' # 0x0B -> VERTICAL TABULATION
u'\x0c' # 0x0C -> FORM FEED
u'\r' # 0x0D -> CARRIAGE RETURN
u'\x0e' # 0x0E -> SHIFT OUT
u'\x0f' # 0x0F -> SHIFT IN
u'\x10' # 0x10 -> DATA LINK ESCAPE
u'\x11' # 0x11 -> DEVICE CONTROL ONE
u'\x12' # 0x12 -> DEVICE CONTROL TWO
u'\x13' # 0x13 -> DEVICE CONTROL THREE
u'\x14' # 0x14 -> DEVICE CONTROL FOUR
u'\x15' # 0x15 -> NEGATIVE ACKNOWLEDGE
u'\x16' # 0x16 -> SYNCHRONOUS IDLE
u'\x17' # 0x17 -> END OF TRANSMISSION BLOCK
u'\x18' # 0x18 -> CANCEL
u'\x19' # 0x19 -> END OF MEDIUM
u'\x1a' # 0x1A -> SUBSTITUTE
u'\x1b' # 0x1B -> ESCAPE
u'\x1c' # 0x1C -> FILE SEPARATOR
u'\x1d' # 0x1D -> GROUP SEPARATOR
u'\x1e' # 0x1E -> RECORD SEPARATOR
u'\x1f' # 0x1F -> UNIT SEPARATOR
u' ' # 0x20 -> SPACE
u'!' # 0x21 -> EXCLAMATION MARK
u'"' # 0x22 -> QUOTATION MARK
u'#' # 0x23 -> NUMBER SIGN
u'$' # 0x24 -> DOLLAR SIGN
u'%' # 0x25 -> PERCENT SIGN
u'&' # 0x26 -> AMPERSAND
u"'" # 0x27 -> APOSTROPHE
u'(' # 0x28 -> LEFT PARENTHESIS
u')' # 0x29 -> RIGHT PARENTHESIS
u'*' # 0x2A -> ASTERISK
u'+' # 0x2B -> PLUS SIGN
u',' # 0x2C -> COMMA
u'-' # 0x2D -> HYPHEN-MINUS
u'.' # 0x2E -> FULL STOP
u'/' # 0x2F -> SOLIDUS
u'0' # 0x30 -> DIGIT ZERO
u'1' # 0x31 -> DIGIT ONE
u'2' # 0x32 -> DIGIT TWO
u'3' # 0x33 -> DIGIT THREE
u'4' # 0x34 -> DIGIT FOUR
u'5' # 0x35 -> DIGIT FIVE
u'6' # 0x36 -> DIGIT SIX
u'7' # 0x37 -> DIGIT SEVEN
u'8' # 0x38 -> DIGIT EIGHT
u'9' # 0x39 -> DIGIT NINE
u':' # 0x3A -> COLON
u';' # 0x3B -> SEMICOLON
u'<' # 0x3C -> LESS-THAN SIGN
u'=' # 0x3D -> EQUALS SIGN
u'>' # 0x3E -> GREATER-THAN SIGN
u'?' # 0x3F -> QUESTION MARK
u'@' # 0x40 -> COMMERCIAL AT
u'A' # 0x41 -> LATIN CAPITAL LETTER A
u'B' # 0x42 -> LATIN CAPITAL LETTER B
u'C' # 0x43 -> LATIN CAPITAL LETTER C
u'D' # 0x44 -> LATIN CAPITAL LETTER D
u'E' # 0x45 -> LATIN CAPITAL LETTER E
u'F' # 0x46 -> LATIN CAPITAL LETTER F
u'G' # 0x47 -> LATIN CAPITAL LETTER G
u'H' # 0x48 -> LATIN CAPITAL LETTER H
u'I' # 0x49 -> LATIN CAPITAL LETTER I
u'J' # 0x4A -> LATIN CAPITAL LETTER J
u'K' # 0x4B -> LATIN CAPITAL LETTER K
u'L' # 0x4C -> LATIN CAPITAL LETTER L
u'M' # 0x4D -> LATIN CAPITAL LETTER M
u'N' # 0x4E -> LATIN CAPITAL LETTER N
u'O' # 0x4F -> LATIN CAPITAL LETTER O
u'P' # 0x50 -> LATIN CAPITAL LETTER P
u'Q' # 0x51 -> LATIN CAPITAL LETTER Q
u'R' # 0x52 -> LATIN CAPITAL LETTER R
u'S' # 0x53 -> LATIN CAPITAL LETTER S
u'T' # 0x54 -> LATIN CAPITAL LETTER T
u'U' # 0x55 -> LATIN CAPITAL LETTER U
u'V' # 0x56 -> LATIN CAPITAL LETTER V
u'W' # 0x57 -> LATIN CAPITAL LETTER W
u'X' # 0x58 -> LATIN CAPITAL LETTER X
u'Y' # 0x59 -> LATIN CAPITAL LETTER Y
u'Z' # 0x5A -> LATIN CAPITAL LETTER Z
u'[' # 0x5B -> LEFT SQUARE BRACKET
u'\\' # 0x5C -> REVERSE SOLIDUS
u']' # 0x5D -> RIGHT SQUARE BRACKET
u'^' # 0x5E -> CIRCUMFLEX ACCENT
u'_' # 0x5F -> LOW LINE
u'`' # 0x60 -> GRAVE ACCENT
u'a' # 0x61 -> LATIN SMALL LETTER A
u'b' # 0x62 -> LATIN SMALL LETTER B
u'c' # 0x63 -> LATIN SMALL LETTER C
u'd' # 0x64 -> LATIN SMALL LETTER D
u'e' # 0x65 -> LATIN SMALL LETTER E
u'f' # 0x66 -> LATIN SMALL LETTER F
u'g' # 0x67 -> LATIN SMALL LETTER G
u'h' # 0x68 -> LATIN SMALL LETTER H
u'i' # 0x69 -> LATIN SMALL LETTER I
u'j' # 0x6A -> LATIN SMALL LETTER J
u'k' # 0x6B -> LATIN SMALL LETTER K
u'l' # 0x6C -> LATIN SMALL LETTER L
u'm' # 0x6D -> LATIN SMALL LETTER M
u'n' # 0x6E -> LATIN SMALL LETTER N
u'o' # 0x6F -> LATIN SMALL LETTER O
u'p' # 0x70 -> LATIN SMALL LETTER P
u'q' # 0x71 -> LATIN SMALL LETTER Q
u'r' # 0x72 -> LATIN SMALL LETTER R
u's' # 0x73 -> LATIN SMALL LETTER S
u't' # 0x74 -> LATIN SMALL LETTER T
u'u' # 0x75 -> LATIN SMALL LETTER U
u'v' # 0x76 -> LATIN SMALL LETTER V
u'w' # 0x77 -> LATIN SMALL LETTER W
u'x' # 0x78 -> LATIN SMALL LETTER X
u'y' # 0x79 -> LATIN SMALL LETTER Y
u'z' # 0x7A -> LATIN SMALL LETTER Z
u'{' # 0x7B -> LEFT CURLY BRACKET
u'|' # 0x7C -> VERTICAL LINE
u'}' # 0x7D -> RIGHT CURLY BRACKET
u'~' # 0x7E -> TILDE
u'\x7f' # 0x7F -> DELETE
u'\u05d0' # 0x80 -> HEBREW LETTER ALEF
u'\u05d1' # 0x81 -> HEBREW LETTER BET
u'\u05d2' # 0x82 -> HEBREW LETTER GIMEL
u'\u05d3' # 0x83 -> HEBREW LETTER DALET
u'\u05d4' # 0x84 -> HEBREW LETTER HE
u'\u05d5' # 0x85 -> HEBREW LETTER VAV
u'\u05d6' # 0x86 -> HEBREW LETTER ZAYIN
u'\u05d7' # 0x87 -> HEBREW LETTER HET
u'\u05d8' # 0x88 -> HEBREW LETTER TET
u'\u05d9' # 0x89 -> HEBREW LETTER YOD
u'\u05da' # 0x8A -> HEBREW LETTER FINAL KAF
u'\u05db' # 0x8B -> HEBREW LETTER KAF
u'\u05dc' # 0x8C -> HEBREW LETTER LAMED
u'\u05dd' # 0x8D -> HEBREW LETTER FINAL MEM
u'\u05de' # 0x8E -> HEBREW LETTER MEM
u'\u05df' # 0x8F -> HEBREW LETTER FINAL NUN
u'\u05e0' # 0x90 -> HEBREW LETTER NUN
u'\u05e1' # 0x91 -> HEBREW LETTER SAMEKH
u'\u05e2' # 0x92 -> HEBREW LETTER AYIN
u'\u05e3' # 0x93 -> HEBREW LETTER FINAL PE
u'\u05e4' # 0x94 -> HEBREW LETTER PE
u'\u05e5' # 0x95 -> HEBREW LETTER FINAL TSADI
u'\u05e6' # 0x96 -> HEBREW LETTER TSADI
u'\u05e7' # 0x97 -> HEBREW LETTER QOF
u'\u05e8' # 0x98 -> HEBREW LETTER RESH
u'\u05e9' # 0x99 -> HEBREW LETTER SHIN
u'\u05ea' # 0x9A -> HEBREW LETTER TAV
u'\ufffe' # 0x9B -> UNDEFINED
u'\xa3' # 0x9C -> POUND SIGN
u'\ufffe' # 0x9D -> UNDEFINED
u'\xd7' # 0x9E -> MULTIPLICATION SIGN
u'\ufffe' # 0x9F -> UNDEFINED
u'\ufffe' # 0xA0 -> UNDEFINED
u'\ufffe' # 0xA1 -> UNDEFINED
u'\ufffe' # 0xA2 -> UNDEFINED
u'\ufffe' # 0xA3 -> UNDEFINED
u'\ufffe' # 0xA4 -> UNDEFINED
u'\ufffe' # 0xA5 -> UNDEFINED
u'\ufffe' # 0xA6 -> UNDEFINED
u'\ufffe' # 0xA7 -> UNDEFINED
u'\ufffe' # 0xA8 -> UNDEFINED
u'\xae' # 0xA9 -> REGISTERED SIGN
u'\xac' # 0xAA -> NOT SIGN
u'\xbd' # 0xAB -> VULGAR FRACTION ONE HALF
u'\xbc' # 0xAC -> VULGAR FRACTION ONE QUARTER
u'\ufffe' # 0xAD -> UNDEFINED
u'\xab' # 0xAE -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
u'\xbb' # 0xAF -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
u'\u2591' # 0xB0 -> LIGHT SHADE
u'\u2592' # 0xB1 -> MEDIUM SHADE
u'\u2593' # 0xB2 -> DARK SHADE
u'\u2502' # 0xB3 -> BOX DRAWINGS LIGHT VERTICAL
u'\u2524' # 0xB4 -> BOX DRAWINGS LIGHT VERTICAL AND LEFT
u'\ufffe' # 0xB5 -> UNDEFINED
u'\ufffe' # 0xB6 -> UNDEFINED
u'\ufffe' # 0xB7 -> UNDEFINED
u'\xa9' # 0xB8 -> COPYRIGHT SIGN
u'\u2563' # 0xB9 -> BOX DRAWINGS DOUBLE VERTICAL AND LEFT
u'\u2551' # 0xBA -> BOX DRAWINGS DOUBLE VERTICAL
u'\u2557' # 0xBB -> BOX DRAWINGS DOUBLE DOWN AND LEFT
u'\u255d' # 0xBC -> BOX DRAWINGS DOUBLE UP AND LEFT
u'\xa2' # 0xBD -> CENT SIGN
u'\xa5' # 0xBE -> YEN SIGN
u'\u2510' # 0xBF -> BOX DRAWINGS LIGHT DOWN AND LEFT
u'\u2514' # 0xC0 -> BOX DRAWINGS LIGHT UP AND RIGHT
u'\u2534' # 0xC1 -> BOX DRAWINGS LIGHT UP AND HORIZONTAL
u'\u252c' # 0xC2 -> BOX DRAWINGS LIGHT DOWN AND HORIZONTAL
u'\u251c' # 0xC3 -> BOX DRAWINGS LIGHT VERTICAL AND RIGHT
u'\u2500' # 0xC4 -> BOX DRAWINGS LIGHT HORIZONTAL
u'\u253c' # 0xC5 -> BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL
u'\ufffe' # 0xC6 -> UNDEFINED
u'\ufffe' # 0xC7 -> UNDEFINED
u'\u255a' # 0xC8 -> BOX DRAWINGS DOUBLE UP AND RIGHT
u'\u2554' # 0xC9 -> BOX DRAWINGS DOUBLE DOWN AND RIGHT
u'\u2569' # 0xCA -> BOX DRAWINGS DOUBLE UP AND HORIZONTAL
u'\u2566' # 0xCB -> BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL
u'\u2560' # 0xCC -> BOX DRAWINGS DOUBLE VERTICAL AND RIGHT
u'\u2550' # 0xCD -> BOX DRAWINGS DOUBLE HORIZONTAL
u'\u256c' # 0xCE -> BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL
u'\xa4' # 0xCF -> CURRENCY SIGN
u'\ufffe' # 0xD0 -> UNDEFINED
u'\ufffe' # 0xD1 -> UNDEFINED
u'\ufffe' # 0xD2 -> UNDEFINED
u'\ufffe' # 0xD3 -> UNDEFINEDS
u'\ufffe' # 0xD4 -> UNDEFINED
u'\ufffe' # 0xD5 -> UNDEFINED
u'\ufffe' # 0xD6 -> UNDEFINEDE
u'\ufffe' # 0xD7 -> UNDEFINED
u'\ufffe' # 0xD8 -> UNDEFINED
u'\u2518' # 0xD9 -> BOX DRAWINGS LIGHT UP AND LEFT
u'\u250c' # 0xDA -> BOX DRAWINGS LIGHT DOWN AND RIGHT
u'\u2588' # 0xDB -> FULL BLOCK
u'\u2584' # 0xDC -> LOWER HALF BLOCK
u'\xa6' # 0xDD -> BROKEN BAR
u'\ufffe' # 0xDE -> UNDEFINED
u'\u2580' # 0xDF -> UPPER HALF BLOCK
u'\ufffe' # 0xE0 -> UNDEFINED
u'\ufffe' # 0xE1 -> UNDEFINED
u'\ufffe' # 0xE2 -> UNDEFINED
u'\ufffe' # 0xE3 -> UNDEFINED
u'\ufffe' # 0xE4 -> UNDEFINED
u'\ufffe' # 0xE5 -> UNDEFINED
u'\xb5' # 0xE6 -> MICRO SIGN
u'\ufffe' # 0xE7 -> UNDEFINED
u'\ufffe' # 0xE8 -> UNDEFINED
u'\ufffe' # 0xE9 -> UNDEFINED
u'\ufffe' # 0xEA -> UNDEFINED
u'\ufffe' # 0xEB -> UNDEFINED
u'\ufffe' # 0xEC -> UNDEFINED
u'\ufffe' # 0xED -> UNDEFINED
u'\xaf' # 0xEE -> MACRON
u'\xb4' # 0xEF -> ACUTE ACCENT
u'\xad' # 0xF0 -> SOFT HYPHEN
u'\xb1' # 0xF1 -> PLUS-MINUS SIGN
u'\u2017' # 0xF2 -> DOUBLE LOW LINE
u'\xbe' # 0xF3 -> VULGAR FRACTION THREE QUARTERS
u'\xb6' # 0xF4 -> PILCROW SIGN
u'\xa7' # 0xF5 -> SECTION SIGN
u'\xf7' # 0xF6 -> DIVISION SIGN
u'\xb8' # 0xF7 -> CEDILLA
u'\xb0' # 0xF8 -> DEGREE SIGN
u'\xa8' # 0xF9 -> DIAERESIS
u'\xb7' # 0xFA -> MIDDLE DOT
u'\xb9' # 0xFB -> SUPERSCRIPT ONE
u'\xb3' # 0xFC -> SUPERSCRIPT THREE
u'\xb2' # 0xFD -> SUPERSCRIPT TWO
u'\u25a0' # 0xFE -> BLACK SQUARE
u'\xa0' # 0xFF -> NO-BREAK SPACE
)
### Encoding table
encoding_table=codecs.charmap_build(decoding_table)
| bsd-2-clause |
drawks/ansible | test/units/modules/network/f5/test_bigip_firewall_port_list.py | 38 | 4716 | # -*- coding: utf-8 -*-
#
# Copyright: (c) 2017, F5 Networks Inc.
# 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
import os
import json
import pytest
import sys
if sys.version_info < (2, 7):
pytestmark = pytest.mark.skip("F5 Ansible modules require Python >= 2.7")
from ansible.module_utils.basic import AnsibleModule
try:
from library.modules.bigip_firewall_port_list import ApiParameters
from library.modules.bigip_firewall_port_list import ModuleParameters
from library.modules.bigip_firewall_port_list import ModuleManager
from library.modules.bigip_firewall_port_list import ArgumentSpec
# In Ansible 2.8, Ansible changed import paths.
from test.units.compat import unittest
from test.units.compat.mock import Mock
from test.units.compat.mock import patch
from test.units.modules.utils import set_module_args
except ImportError:
from ansible.modules.network.f5.bigip_firewall_port_list import ApiParameters
from ansible.modules.network.f5.bigip_firewall_port_list import ModuleParameters
from ansible.modules.network.f5.bigip_firewall_port_list import ModuleManager
from ansible.modules.network.f5.bigip_firewall_port_list import ArgumentSpec
# Ansible 2.8 imports
from units.compat import unittest
from units.compat.mock import Mock
from units.compat.mock import patch
from units.modules.utils import set_module_args
fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures')
fixture_data = {}
def load_fixture(name):
path = os.path.join(fixture_path, name)
if path in fixture_data:
return fixture_data[path]
with open(path) as f:
data = f.read()
try:
data = json.loads(data)
except Exception:
pass
fixture_data[path] = data
return data
class TestParameters(unittest.TestCase):
def test_module_parameters(self):
args = dict(
name='foo',
description='this is a description',
ports=[1, 2, 3, 4],
port_ranges=['10-20', '30-40', '50-60'],
port_lists=['/Common/foo', 'foo']
)
p = ModuleParameters(params=args)
assert p.name == 'foo'
assert p.description == 'this is a description'
assert len(p.ports) == 4
assert len(p.port_ranges) == 3
assert len(p.port_lists) == 2
def test_api_parameters(self):
args = load_fixture('load_security_port_list_1.json')
p = ApiParameters(params=args)
assert len(p.ports) == 4
assert len(p.port_ranges) == 3
assert len(p.port_lists) == 1
assert sorted(p.ports) == [1, 2, 3, 4]
assert sorted(p.port_ranges) == ['10-20', '30-40', '50-60']
assert p.port_lists[0] == '/Common/_sys_self_allow_tcp_defaults'
class TestManager(unittest.TestCase):
def setUp(self):
self.spec = ArgumentSpec()
try:
self.p1 = patch('library.modules.bigip_firewall_port_list.module_provisioned')
self.m1 = self.p1.start()
self.m1.return_value = True
except Exception:
self.p1 = patch('ansible.modules.network.f5.bigip_firewall_port_list.module_provisioned')
self.m1 = self.p1.start()
self.m1.return_value = True
def tearDown(self):
self.p1.stop()
def test_create(self, *args):
set_module_args(dict(
name='foo',
description='this is a description',
ports=[1, 2, 3, 4],
port_ranges=['10-20', '30-40', '50-60'],
port_lists=['/Common/foo', 'foo'],
provider=dict(
server='localhost',
password='password',
user='admin'
)
))
module = AnsibleModule(
argument_spec=self.spec.argument_spec,
supports_check_mode=self.spec.supports_check_mode
)
mm = ModuleManager(module=module)
# Override methods to force specific logic in the module to happen
mm.exists = Mock(side_effect=[False, True])
mm.create_on_device = Mock(return_value=True)
mm.module_provisioned = Mock(return_value=True)
results = mm.exec_module()
assert results['changed'] is True
assert 'ports' in results
assert 'port_lists' in results
assert 'port_ranges' in results
assert len(results['ports']) == 4
assert len(results['port_ranges']) == 3
assert len(results['port_lists']) == 2
assert results['description'] == 'this is a description'
| gpl-3.0 |
ByteInternet/libcloud | libcloud/test/compute/test_dimensiondata_v2_4.py | 1 | 163733 | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
from types import GeneratorType
from libcloud.utils.py3 import httplib
from libcloud.utils.py3 import ET
from libcloud.common.types import InvalidCredsError
from libcloud.common.dimensiondata import DimensionDataAPIException, NetworkDomainServicePlan
from libcloud.common.dimensiondata import DimensionDataServerCpuSpecification, DimensionDataServerDisk, DimensionDataServerVMWareTools
from libcloud.common.dimensiondata import DimensionDataTag, DimensionDataTagKey
from libcloud.common.dimensiondata import DimensionDataIpAddress, \
DimensionDataIpAddressList, DimensionDataChildIpAddressList, \
DimensionDataPortList, DimensionDataPort, DimensionDataChildPortList
from libcloud.common.dimensiondata import TYPES_URN
from libcloud.compute.drivers.dimensiondata import DimensionDataNodeDriver as DimensionData
from libcloud.compute.drivers.dimensiondata import DimensionDataNic
from libcloud.compute.base import Node, NodeAuthPassword, NodeLocation
from libcloud.test import MockHttp, unittest
from libcloud.test.file_fixtures import ComputeFileFixtures
from libcloud.test.secrets import DIMENSIONDATA_PARAMS
from libcloud.utils.xml import fixxpath, findtext, findall
class DimensionData_v2_4_Tests(unittest.TestCase):
def setUp(self):
DimensionData.connectionCls.active_api_version = '2.4'
DimensionData.connectionCls.conn_class = DimensionDataMockHttp
DimensionDataMockHttp.type = None
self.driver = DimensionData(*DIMENSIONDATA_PARAMS)
def test_invalid_region(self):
with self.assertRaises(ValueError):
DimensionData(*DIMENSIONDATA_PARAMS, region='blah')
def test_invalid_creds(self):
DimensionDataMockHttp.type = 'UNAUTHORIZED'
with self.assertRaises(InvalidCredsError):
self.driver.list_nodes()
def test_get_account_details(self):
DimensionDataMockHttp.type = None
ret = self.driver.connection.get_account_details()
self.assertEqual(ret.full_name, 'Test User')
self.assertEqual(ret.first_name, 'Test')
self.assertEqual(ret.email, 'test@example.com')
def test_list_locations_response(self):
DimensionDataMockHttp.type = None
ret = self.driver.list_locations()
self.assertEqual(len(ret), 5)
first_loc = ret[0]
self.assertEqual(first_loc.id, 'NA3')
self.assertEqual(first_loc.name, 'US - West')
self.assertEqual(first_loc.country, 'US')
def test_list_nodes_response(self):
DimensionDataMockHttp.type = None
ret = self.driver.list_nodes()
self.assertEqual(len(ret), 7)
def test_node_extras(self):
DimensionDataMockHttp.type = None
ret = self.driver.list_nodes()
self.assertTrue(isinstance(ret[0].extra['vmWareTools'], DimensionDataServerVMWareTools))
self.assertTrue(isinstance(ret[0].extra['cpu'], DimensionDataServerCpuSpecification))
self.assertTrue(isinstance(ret[0].extra['disks'], list))
self.assertTrue(isinstance(ret[0].extra['disks'][0], DimensionDataServerDisk))
self.assertEqual(ret[0].extra['disks'][0].size_gb, 10)
self.assertTrue(isinstance(ret[1].extra['disks'], list))
self.assertTrue(isinstance(ret[1].extra['disks'][0], DimensionDataServerDisk))
self.assertEqual(ret[1].extra['disks'][0].size_gb, 10)
def test_server_states(self):
DimensionDataMockHttp.type = None
ret = self.driver.list_nodes()
self.assertTrue(ret[0].state == 'running')
self.assertTrue(ret[1].state == 'starting')
self.assertTrue(ret[2].state == 'stopping')
self.assertTrue(ret[3].state == 'reconfiguring')
self.assertTrue(ret[4].state == 'running')
self.assertTrue(ret[5].state == 'terminated')
self.assertTrue(ret[6].state == 'stopped')
self.assertEqual(len(ret), 7)
def test_list_nodes_response_PAGINATED(self):
DimensionDataMockHttp.type = 'PAGINATED'
ret = self.driver.list_nodes()
self.assertEqual(len(ret), 9)
def test_paginated_mcp2_call_EMPTY(self):
# cache org
self.driver.connection._get_orgId()
DimensionDataMockHttp.type = 'EMPTY'
node_list_generator = self.driver.connection.paginated_request_with_orgId_api_2('server/server')
empty_node_list = []
for node_list in node_list_generator:
empty_node_list.extend(node_list)
self.assertTrue(len(empty_node_list) == 0)
def test_paginated_mcp2_call_PAGED_THEN_EMPTY(self):
# cache org
self.driver.connection._get_orgId()
DimensionDataMockHttp.type = 'PAGED_THEN_EMPTY'
node_list_generator = self.driver.connection.paginated_request_with_orgId_api_2('server/server')
final_node_list = []
for node_list in node_list_generator:
final_node_list.extend(node_list)
self.assertTrue(len(final_node_list) == 2)
def test_paginated_mcp2_call_with_page_size(self):
# cache org
self.driver.connection._get_orgId()
DimensionDataMockHttp.type = 'PAGESIZE50'
node_list_generator = self.driver.connection.paginated_request_with_orgId_api_2('server/server', page_size=50)
self.assertTrue(isinstance(node_list_generator, GeneratorType))
# We're making sure here the filters make it to the URL
# See _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_server_ALLFILTERS for asserts
def test_list_nodes_response_strings_ALLFILTERS(self):
DimensionDataMockHttp.type = 'ALLFILTERS'
ret = self.driver.list_nodes(ex_location='fake_loc', ex_name='fake_name',
ex_ipv6='fake_ipv6', ex_ipv4='fake_ipv4', ex_vlan='fake_vlan',
ex_image='fake_image', ex_deployed=True,
ex_started=True, ex_state='fake_state',
ex_network='fake_network', ex_network_domain='fake_network_domain')
self.assertTrue(isinstance(ret, list))
self.assertEqual(len(ret), 7)
node = ret[3]
self.assertTrue(isinstance(node.extra['disks'], list))
self.assertTrue(isinstance(node.extra['disks'][0], DimensionDataServerDisk))
self.assertEqual(node.size.id, '1')
self.assertEqual(node.image.id, '3ebf3c0f-90fe-4a8b-8585-6e65b316592c')
self.assertEqual(node.image.name, 'WIN2008S/32')
disk = node.extra['disks'][0]
self.assertEqual(disk.id, "c2e1f199-116e-4dbc-9960-68720b832b0a")
self.assertEqual(disk.scsi_id, 0)
self.assertEqual(disk.size_gb, 50)
self.assertEqual(disk.speed, "STANDARD")
self.assertEqual(disk.state, "NORMAL")
def test_list_nodes_response_LOCATION(self):
DimensionDataMockHttp.type = None
ret = self.driver.list_locations()
first_loc = ret[0]
ret = self.driver.list_nodes(ex_location=first_loc)
for node in ret:
self.assertEqual(node.extra['datacenterId'], 'NA3')
def test_list_nodes_response_LOCATION_STR(self):
DimensionDataMockHttp.type = None
ret = self.driver.list_nodes(ex_location='NA3')
for node in ret:
self.assertEqual(node.extra['datacenterId'], 'NA3')
def test_list_sizes_response(self):
DimensionDataMockHttp.type = None
ret = self.driver.list_sizes()
self.assertEqual(len(ret), 1)
size = ret[0]
self.assertEqual(size.name, 'default')
def test_reboot_node_response(self):
node = Node(id='11', name=None, state=None,
public_ips=None, private_ips=None, driver=self.driver)
ret = node.reboot()
self.assertTrue(ret is True)
def test_reboot_node_response_INPROGRESS(self):
DimensionDataMockHttp.type = 'INPROGRESS'
node = Node(id='11', name=None, state=None,
public_ips=None, private_ips=None, driver=self.driver)
with self.assertRaises(DimensionDataAPIException):
node.reboot()
def test_destroy_node_response(self):
node = Node(id='11', name=None, state=None,
public_ips=None, private_ips=None, driver=self.driver)
ret = node.destroy()
self.assertTrue(ret is True)
def test_destroy_node_response_RESOURCE_BUSY(self):
DimensionDataMockHttp.type = 'INPROGRESS'
node = Node(id='11', name=None, state=None,
public_ips=None, private_ips=None, driver=self.driver)
with self.assertRaises(DimensionDataAPIException):
node.destroy()
def test_list_images(self):
images = self.driver.list_images()
self.assertEqual(len(images), 3)
self.assertEqual(images[0].name, 'RedHat 6 64-bit 2 CPU')
self.assertEqual(images[0].id, 'c14b1a46-2428-44c1-9c1a-b20e6418d08c')
self.assertEqual(images[0].extra['location'].id, 'NA9')
self.assertEqual(images[0].extra['cpu'].cpu_count, 2)
self.assertEqual(images[0].extra['OS_displayName'], 'REDHAT6/64')
def test_clean_failed_deployment_response_with_node(self):
node = Node(id='11', name=None, state=None,
public_ips=None, private_ips=None, driver=self.driver)
ret = self.driver.ex_clean_failed_deployment(node)
self.assertTrue(ret is True)
def test_clean_failed_deployment_response_with_node_id(self):
node = 'e75ead52-692f-4314-8725-c8a4f4d13a87'
ret = self.driver.ex_clean_failed_deployment(node)
self.assertTrue(ret is True)
def test_ex_list_customer_images(self):
images = self.driver.ex_list_customer_images()
self.assertEqual(len(images), 3)
self.assertEqual(images[0].name, 'ImportedCustomerImage')
self.assertEqual(images[0].id, '5234e5c7-01de-4411-8b6e-baeb8d91cf5d')
self.assertEqual(images[0].extra['location'].id, 'NA9')
self.assertEqual(images[0].extra['cpu'].cpu_count, 4)
self.assertEqual(images[0].extra['OS_displayName'], 'REDHAT6/64')
def test_create_mcp1_node_optional_param(self):
root_pw = NodeAuthPassword('pass123')
image = self.driver.list_images()[0]
network = self.driver.ex_list_networks()[0]
cpu_spec = DimensionDataServerCpuSpecification(cpu_count='4',
cores_per_socket='2',
performance='STANDARD')
disks = [DimensionDataServerDisk(scsi_id='0', speed='HIGHPERFORMANCE')]
node = self.driver.create_node(name='test2', image=image, auth=root_pw,
ex_description='test2 node',
ex_network=network,
ex_is_started=False,
ex_memory_gb=8,
ex_disks=disks,
ex_cpu_specification=cpu_spec,
ex_primary_dns='10.0.0.5',
ex_secondary_dns='10.0.0.6'
)
self.assertEqual(node.id, 'e75ead52-692f-4314-8725-c8a4f4d13a87')
self.assertEqual(node.extra['status'].action, 'DEPLOY_SERVER')
def test_create_mcp1_node_response_no_pass_random_gen(self):
image = self.driver.list_images()[0]
network = self.driver.ex_list_networks()[0]
node = self.driver.create_node(name='test2', image=image, auth=None,
ex_description='test2 node',
ex_network=network,
ex_is_started=False)
self.assertEqual(node.id, 'e75ead52-692f-4314-8725-c8a4f4d13a87')
self.assertEqual(node.extra['status'].action, 'DEPLOY_SERVER')
self.assertTrue('password' in node.extra)
def test_create_mcp1_node_response_no_pass_customer_windows(self):
image = self.driver.ex_list_customer_images()[1]
network = self.driver.ex_list_networks()[0]
node = self.driver.create_node(name='test2', image=image, auth=None,
ex_description='test2 node', ex_network=network,
ex_is_started=False)
self.assertEqual(node.id, 'e75ead52-692f-4314-8725-c8a4f4d13a87')
self.assertEqual(node.extra['status'].action, 'DEPLOY_SERVER')
self.assertTrue('password' in node.extra)
def test_create_mcp1_node_response_no_pass_customer_windows_STR(self):
image = self.driver.ex_list_customer_images()[1].id
network = self.driver.ex_list_networks()[0]
node = self.driver.create_node(name='test2', image=image, auth=None,
ex_description='test2 node', ex_network=network,
ex_is_started=False)
self.assertEqual(node.id, 'e75ead52-692f-4314-8725-c8a4f4d13a87')
self.assertEqual(node.extra['status'].action, 'DEPLOY_SERVER')
self.assertTrue('password' in node.extra)
def test_create_mcp1_node_response_no_pass_customer_linux(self):
image = self.driver.ex_list_customer_images()[0]
network = self.driver.ex_list_networks()[0]
node = self.driver.create_node(name='test2', image=image, auth=None,
ex_description='test2 node', ex_network=network,
ex_is_started=False)
self.assertEqual(node.id, 'e75ead52-692f-4314-8725-c8a4f4d13a87')
self.assertEqual(node.extra['status'].action, 'DEPLOY_SERVER')
self.assertTrue('password' not in node.extra)
def test_create_mcp1_node_response_no_pass_customer_linux_STR(self):
image = self.driver.ex_list_customer_images()[0].id
network = self.driver.ex_list_networks()[0]
node = self.driver.create_node(name='test2', image=image, auth=None,
ex_description='test2 node', ex_network=network,
ex_is_started=False)
self.assertEqual(node.id, 'e75ead52-692f-4314-8725-c8a4f4d13a87')
self.assertEqual(node.extra['status'].action, 'DEPLOY_SERVER')
self.assertTrue('password' not in node.extra)
def test_create_mcp1_node_response_STR(self):
rootPw = 'pass123'
image = self.driver.list_images()[0].id
network = self.driver.ex_list_networks()[0].id
node = self.driver.create_node(name='test2', image=image, auth=rootPw,
ex_description='test2 node', ex_network=network,
ex_is_started=False)
self.assertEqual(node.id, 'e75ead52-692f-4314-8725-c8a4f4d13a87')
self.assertEqual(node.extra['status'].action, 'DEPLOY_SERVER')
def test_create_node_response_network_domain(self):
rootPw = NodeAuthPassword('pass123')
location = self.driver.ex_get_location_by_id('NA9')
image = self.driver.list_images(location=location)[0]
network_domain = self.driver.ex_list_network_domains(location=location)[0]
vlan = self.driver.ex_list_vlans(location=location)[0]
cpu = DimensionDataServerCpuSpecification(
cpu_count=4,
cores_per_socket=1,
performance='HIGHPERFORMANCE'
)
node = self.driver.create_node(name='test2', image=image, auth=rootPw,
ex_description='test2 node',
ex_network_domain=network_domain,
ex_vlan=vlan,
ex_is_started=False, ex_cpu_specification=cpu,
ex_memory_gb=4)
self.assertEqual(node.id, 'e75ead52-692f-4314-8725-c8a4f4d13a87')
self.assertEqual(node.extra['status'].action, 'DEPLOY_SERVER')
def test_create_node_response_network_domain_STR(self):
rootPw = NodeAuthPassword('pass123')
location = self.driver.ex_get_location_by_id('NA9')
image = self.driver.list_images(location=location)[0]
network_domain = self.driver.ex_list_network_domains(location=location)[0].id
vlan = self.driver.ex_list_vlans(location=location)[0].id
cpu = DimensionDataServerCpuSpecification(
cpu_count=4,
cores_per_socket=1,
performance='HIGHPERFORMANCE'
)
node = self.driver.create_node(name='test2', image=image, auth=rootPw,
ex_description='test2 node',
ex_network_domain=network_domain,
ex_vlan=vlan,
ex_is_started=False, ex_cpu_specification=cpu,
ex_memory_gb=4)
self.assertEqual(node.id, 'e75ead52-692f-4314-8725-c8a4f4d13a87')
self.assertEqual(node.extra['status'].action, 'DEPLOY_SERVER')
def test_create_mcp1_node_no_network(self):
rootPw = NodeAuthPassword('pass123')
image = self.driver.list_images()[0]
with self.assertRaises(InvalidRequestError):
self.driver.create_node(name='test2',
image=image,
auth=rootPw,
ex_description='test2 node',
ex_network=None,
ex_is_started=False)
def test_create_node_mcp1_ipv4(self):
rootPw = NodeAuthPassword('pass123')
image = self.driver.list_images()[0]
node = self.driver.create_node(name='test2',
image=image,
auth=rootPw,
ex_description='test2 node',
ex_network='fakenetwork',
ex_primary_ipv4='10.0.0.1',
ex_is_started=False)
self.assertEqual(node.id, 'e75ead52-692f-4314-8725-c8a4f4d13a87')
self.assertEqual(node.extra['status'].action, 'DEPLOY_SERVER')
def test_create_node_mcp1_network(self):
rootPw = NodeAuthPassword('pass123')
image = self.driver.list_images()[0]
node = self.driver.create_node(name='test2',
image=image,
auth=rootPw,
ex_description='test2 node',
ex_network='fakenetwork',
ex_is_started=False)
self.assertEqual(node.id, 'e75ead52-692f-4314-8725-c8a4f4d13a87')
self.assertEqual(node.extra['status'].action, 'DEPLOY_SERVER')
def test_create_node_mcp2_vlan(self):
rootPw = NodeAuthPassword('pass123')
image = self.driver.list_images()[0]
node = self.driver.create_node(name='test2',
image=image,
auth=rootPw,
ex_description='test2 node',
ex_network_domain='fakenetworkdomain',
ex_vlan='fakevlan',
ex_is_started=False)
self.assertEqual(node.id, 'e75ead52-692f-4314-8725-c8a4f4d13a87')
self.assertEqual(node.extra['status'].action, 'DEPLOY_SERVER')
def test_create_node_mcp2_ipv4(self):
rootPw = NodeAuthPassword('pass123')
image = self.driver.list_images()[0]
node = self.driver.create_node(name='test2',
image=image,
auth=rootPw,
ex_description='test2 node',
ex_network_domain='fakenetworkdomain',
ex_primary_ipv4='10.0.0.1',
ex_is_started=False)
self.assertEqual(node.id, 'e75ead52-692f-4314-8725-c8a4f4d13a87')
self.assertEqual(node.extra['status'].action, 'DEPLOY_SERVER')
def test_create_node_network_domain_no_vlan_or_ipv4(self):
rootPw = NodeAuthPassword('pass123')
image = self.driver.list_images()[0]
with self.assertRaises(ValueError):
self.driver.create_node(name='test2',
image=image,
auth=rootPw,
ex_description='test2 node',
ex_network_domain='fake_network_domain',
ex_is_started=False)
def test_create_node_response(self):
rootPw = NodeAuthPassword('pass123')
image = self.driver.list_images()[0]
node = self.driver.create_node(
name='test3',
image=image,
auth=rootPw,
ex_network_domain='fakenetworkdomain',
ex_primary_nic_vlan='fakevlan'
)
self.assertEqual(node.id, 'e75ead52-692f-4314-8725-c8a4f4d13a87')
self.assertEqual(node.extra['status'].action, 'DEPLOY_SERVER')
def test_create_node_ms_time_zone(self):
rootPw = NodeAuthPassword('pass123')
image = self.driver.list_images()[0]
node = self.driver.create_node(
name='test3',
image=image,
auth=rootPw,
ex_network_domain='fakenetworkdomain',
ex_primary_nic_vlan='fakevlan',
ex_microsoft_time_zone='040'
)
self.assertEqual(node.id, 'e75ead52-692f-4314-8725-c8a4f4d13a87')
self.assertEqual(node.extra['status'].action, 'DEPLOY_SERVER')
def test_create_node_ambigious_mcps_fail(self):
rootPw = NodeAuthPassword('pass123')
image = self.driver.list_images()[0]
with self.assertRaises(ValueError):
self.driver.create_node(
name='test3',
image=image,
auth=rootPw,
ex_network_domain='fakenetworkdomain',
ex_network='fakenetwork',
ex_primary_nic_vlan='fakevlan'
)
def test_create_node_no_network_domain_fail(self):
rootPw = NodeAuthPassword('pass123')
image = self.driver.list_images()[0]
with self.assertRaises(ValueError):
self.driver.create_node(
name='test3',
image=image,
auth=rootPw,
ex_primary_nic_vlan='fakevlan'
)
def test_create_node_no_primary_nic_fail(self):
rootPw = NodeAuthPassword('pass123')
image = self.driver.list_images()[0]
with self.assertRaises(ValueError):
self.driver.create_node(
name='test3',
image=image,
auth=rootPw,
ex_network_domain='fakenetworkdomain'
)
def test_create_node_primary_vlan_nic(self):
rootPw = NodeAuthPassword('pass123')
image = self.driver.list_images()[0]
node = self.driver.create_node(
name='test3',
image=image,
auth=rootPw,
ex_network_domain='fakenetworkdomain',
ex_primary_nic_vlan='fakevlan',
ex_primary_nic_network_adapter='v1000'
)
self.assertEqual(node.id, 'e75ead52-692f-4314-8725-c8a4f4d13a87')
self.assertEqual(node.extra['status'].action, 'DEPLOY_SERVER')
def test_create_node_primary_ipv4(self):
rootPw = 'pass123'
image = self.driver.list_images()[0]
node = self.driver.create_node(
name='test3',
image=image,
auth=rootPw,
ex_network_domain='fakenetworkdomain',
ex_primary_nic_private_ipv4='10.0.0.1'
)
self.assertEqual(node.id, 'e75ead52-692f-4314-8725-c8a4f4d13a87')
self.assertEqual(node.extra['status'].action, 'DEPLOY_SERVER')
def test_create_node_both_primary_nic_and_vlan_fail(self):
rootPw = NodeAuthPassword('pass123')
image = self.driver.list_images()[0]
with self.assertRaises(ValueError):
self.driver.create_node(
name='test3',
image=image,
auth=rootPw,
ex_network_domain='fakenetworkdomain',
ex_primary_nic_private_ipv4='10.0.0.1',
ex_primary_nic_vlan='fakevlan'
)
def test_create_node_cpu_specification(self):
rootPw = NodeAuthPassword('pass123')
image = self.driver.list_images()[0]
cpu_spec = DimensionDataServerCpuSpecification(cpu_count='4',
cores_per_socket='2',
performance='STANDARD')
node = self.driver.create_node(name='test2',
image=image,
auth=rootPw,
ex_description='test2 node',
ex_network_domain='fakenetworkdomain',
ex_primary_nic_private_ipv4='10.0.0.1',
ex_is_started=False,
ex_cpu_specification=cpu_spec)
self.assertEqual(node.id, 'e75ead52-692f-4314-8725-c8a4f4d13a87')
self.assertEqual(node.extra['status'].action, 'DEPLOY_SERVER')
def test_create_node_memory(self):
rootPw = NodeAuthPassword('pass123')
image = self.driver.list_images()[0]
node = self.driver.create_node(name='test2',
image=image,
auth=rootPw,
ex_description='test2 node',
ex_network_domain='fakenetworkdomain',
ex_primary_nic_private_ipv4='10.0.0.1',
ex_is_started=False,
ex_memory_gb=8)
self.assertEqual(node.id, 'e75ead52-692f-4314-8725-c8a4f4d13a87')
self.assertEqual(node.extra['status'].action, 'DEPLOY_SERVER')
def test_create_node_disks(self):
rootPw = NodeAuthPassword('pass123')
image = self.driver.list_images()[0]
disks = [DimensionDataServerDisk(scsi_id='0', speed='HIGHPERFORMANCE')]
node = self.driver.create_node(name='test2',
image=image,
auth=rootPw,
ex_description='test2 node',
ex_network_domain='fakenetworkdomain',
ex_primary_nic_private_ipv4='10.0.0.1',
ex_is_started=False,
ex_disks=disks)
self.assertEqual(node.id, 'e75ead52-692f-4314-8725-c8a4f4d13a87')
self.assertEqual(node.extra['status'].action, 'DEPLOY_SERVER')
def test_create_node_disks_fail(self):
root_pw = NodeAuthPassword('pass123')
image = self.driver.list_images()[0]
disks = 'blah'
with self.assertRaises(TypeError):
self.driver.create_node(name='test2',
image=image,
auth=root_pw,
ex_description='test2 node',
ex_network_domain='fakenetworkdomain',
ex_primary_nic_private_ipv4='10.0.0.1',
ex_is_started=False,
ex_disks=disks)
def test_create_node_ipv4_gateway(self):
rootPw = NodeAuthPassword('pass123')
image = self.driver.list_images()[0]
node = self.driver.create_node(name='test2',
image=image,
auth=rootPw,
ex_description='test2 node',
ex_network_domain='fakenetworkdomain',
ex_primary_nic_private_ipv4='10.0.0.1',
ex_is_started=False,
ex_ipv4_gateway='10.2.2.2')
self.assertEqual(node.id, 'e75ead52-692f-4314-8725-c8a4f4d13a87')
self.assertEqual(node.extra['status'].action, 'DEPLOY_SERVER')
def test_create_node_network_domain_no_vlan_no_ipv4_fail(self):
rootPw = NodeAuthPassword('pass123')
image = self.driver.list_images()[0]
with self.assertRaises(ValueError):
self.driver.create_node(name='test2',
image=image,
auth=rootPw,
ex_description='test2 node',
ex_network_domain='fake_network_domain',
ex_is_started=False)
def test_create_node_mcp2_additional_nics_legacy(self):
rootPw = NodeAuthPassword('pass123')
image = self.driver.list_images()[0]
additional_vlans = ['fakevlan1', 'fakevlan2']
additional_ipv4 = ['10.0.0.2', '10.0.0.3']
node = self.driver.create_node(
name='test2',
image=image,
auth=rootPw,
ex_description='test2 node',
ex_network_domain='fakenetworkdomain',
ex_primary_ipv4='10.0.0.1',
ex_additional_nics_vlan=additional_vlans,
ex_additional_nics_ipv4=additional_ipv4,
ex_is_started=False)
self.assertEqual(node.id, 'e75ead52-692f-4314-8725-c8a4f4d13a87')
self.assertEqual(node.extra['status'].action, 'DEPLOY_SERVER')
def test_create_node_bad_additional_nics_ipv4(self):
rootPw = NodeAuthPassword('pass123')
image = self.driver.list_images()[0]
with self.assertRaises(TypeError):
self.driver.create_node(name='test2',
image=image,
auth=rootPw,
ex_description='test2 node',
ex_network_domain='fake_network_domain',
ex_vlan='fake_vlan',
ex_additional_nics_ipv4='badstring',
ex_is_started=False)
def test_create_node_additional_nics(self):
root_pw = NodeAuthPassword('pass123')
image = self.driver.list_images()[0]
nic1 = DimensionDataNic(vlan='fake_vlan',
network_adapter_name='v1000')
nic2 = DimensionDataNic(private_ip_v4='10.1.1.2',
network_adapter_name='v1000')
additional_nics = [nic1, nic2]
node = self.driver.create_node(name='test2',
image=image,
auth=root_pw,
ex_description='test2 node',
ex_network_domain='fakenetworkdomain',
ex_primary_nic_private_ipv4='10.0.0.1',
ex_additional_nics=additional_nics,
ex_is_started=False)
self.assertEqual(node.id, 'e75ead52-692f-4314-8725-c8a4f4d13a87')
self.assertEqual(node.extra['status'].action, 'DEPLOY_SERVER')
def test_create_node_additional_nics_vlan_ipv4_coexist_fail(self):
root_pw = NodeAuthPassword('pass123')
image = self.driver.list_images()[0]
nic1 = DimensionDataNic(private_ip_v4='10.1.1.1', vlan='fake_vlan',
network_adapter_name='v1000')
nic2 = DimensionDataNic(private_ip_v4='10.1.1.2', vlan='fake_vlan2',
network_adapter_name='v1000')
additional_nics = [nic1, nic2]
with self.assertRaises(ValueError):
self.driver.create_node(name='test2',
image=image,
auth=root_pw,
ex_description='test2 node',
ex_network_domain='fakenetworkdomain',
ex_primary_nic_private_ipv4='10.0.0.1',
ex_additional_nics=additional_nics,
ex_is_started=False
)
def test_create_node_additional_nics_invalid_input_fail(self):
root_pw = NodeAuthPassword('pass123')
image = self.driver.list_images()[0]
additional_nics = 'blah'
with self.assertRaises(TypeError):
self.driver.create_node(name='test2',
image=image,
auth=root_pw,
ex_description='test2 node',
ex_network_domain='fakenetworkdomain',
ex_primary_nic_private_ipv4='10.0.0.1',
ex_additional_nics=additional_nics,
ex_is_started=False
)
def test_create_node_additional_nics_vlan_ipv4_not_exist_fail(self):
root_pw = NodeAuthPassword('pass123')
image = self.driver.list_images()[0]
nic1 = DimensionDataNic(network_adapter_name='v1000')
nic2 = DimensionDataNic(network_adapter_name='v1000')
additional_nics = [nic1, nic2]
with self.assertRaises(ValueError):
self.driver.create_node(name='test2',
image=image,
auth=root_pw,
ex_description='test2 node',
ex_network_domain='fakenetworkdomain',
ex_primary_nic_private_ipv4='10.0.0.1',
ex_additional_nics=additional_nics,
ex_is_started=False)
def test_create_node_bad_additional_nics_vlan(self):
rootPw = NodeAuthPassword('pass123')
image = self.driver.list_images()[0]
with self.assertRaises(TypeError):
self.driver.create_node(name='test2',
image=image,
auth=rootPw,
ex_description='test2 node',
ex_network_domain='fake_network_domain',
ex_vlan='fake_vlan',
ex_additional_nics_vlan='badstring',
ex_is_started=False)
def test_create_node_mcp2_indicate_dns(self):
rootPw = NodeAuthPassword('pass123')
image = self.driver.list_images()[0]
node = self.driver.create_node(name='test2',
image=image,
auth=rootPw,
ex_description='test node dns',
ex_network_domain='fakenetworkdomain',
ex_primary_ipv4='10.0.0.1',
ex_primary_dns='8.8.8.8',
ex_secondary_dns='8.8.4.4',
ex_is_started=False)
self.assertEqual(node.id, 'e75ead52-692f-4314-8725-c8a4f4d13a87')
self.assertEqual(node.extra['status'].action, 'DEPLOY_SERVER')
def test_ex_shutdown_graceful(self):
node = Node(id='11', name=None, state=None,
public_ips=None, private_ips=None, driver=self.driver)
ret = self.driver.ex_shutdown_graceful(node)
self.assertTrue(ret is True)
def test_ex_shutdown_graceful_INPROGRESS(self):
DimensionDataMockHttp.type = 'INPROGRESS'
node = Node(id='11', name=None, state=None,
public_ips=None, private_ips=None, driver=self.driver)
with self.assertRaises(DimensionDataAPIException):
self.driver.ex_shutdown_graceful(node)
def test_ex_start_node(self):
node = Node(id='11', name=None, state=None,
public_ips=None, private_ips=None, driver=self.driver)
ret = self.driver.ex_start_node(node)
self.assertTrue(ret is True)
def test_ex_start_node_INPROGRESS(self):
DimensionDataMockHttp.type = 'INPROGRESS'
node = Node(id='11', name=None, state=None,
public_ips=None, private_ips=None, driver=self.driver)
with self.assertRaises(DimensionDataAPIException):
self.driver.ex_start_node(node)
def test_ex_power_off(self):
node = Node(id='11', name=None, state=None,
public_ips=None, private_ips=None, driver=self.driver)
ret = self.driver.ex_power_off(node)
self.assertTrue(ret is True)
def test_ex_update_vm_tools(self):
node = Node(id='11', name=None, state=None,
public_ips=None, private_ips=None, driver=self.driver)
ret = self.driver.ex_update_vm_tools(node)
self.assertTrue(ret is True)
def test_ex_power_off_INPROGRESS(self):
DimensionDataMockHttp.type = 'INPROGRESS'
node = Node(id='11', name=None, state='STOPPING',
public_ips=None, private_ips=None, driver=self.driver)
with self.assertRaises(DimensionDataAPIException):
self.driver.ex_power_off(node)
def test_ex_reset(self):
node = Node(id='11', name=None, state=None,
public_ips=None, private_ips=None, driver=self.driver)
ret = self.driver.ex_reset(node)
self.assertTrue(ret is True)
def test_ex_attach_node_to_vlan(self):
node = self.driver.ex_get_node_by_id('e75ead52-692f-4314-8725-c8a4f4d13a87')
vlan = self.driver.ex_get_vlan('0e56433f-d808-4669-821d-812769517ff8')
ret = self.driver.ex_attach_node_to_vlan(node, vlan)
self.assertTrue(ret is True)
def test_ex_destroy_nic(self):
node = self.driver.ex_destroy_nic('a202e51b-41c0-4cfc-add0-b1c62fc0ecf6')
self.assertTrue(node)
def test_list_networks(self):
nets = self.driver.list_networks()
self.assertEqual(nets[0].name, 'test-net1')
self.assertTrue(isinstance(nets[0].location, NodeLocation))
def test_ex_create_network(self):
location = self.driver.ex_get_location_by_id('NA9')
net = self.driver.ex_create_network(location, "Test Network", "test")
self.assertEqual(net.id, "208e3a8e-9d2f-11e2-b29c-001517c4643e")
self.assertEqual(net.name, "Test Network")
def test_ex_create_network_NO_DESCRIPTION(self):
location = self.driver.ex_get_location_by_id('NA9')
net = self.driver.ex_create_network(location, "Test Network")
self.assertEqual(net.id, "208e3a8e-9d2f-11e2-b29c-001517c4643e")
self.assertEqual(net.name, "Test Network")
def test_ex_delete_network(self):
net = self.driver.ex_list_networks()[0]
result = self.driver.ex_delete_network(net)
self.assertTrue(result)
def test_ex_rename_network(self):
net = self.driver.ex_list_networks()[0]
result = self.driver.ex_rename_network(net, "barry")
self.assertTrue(result)
def test_ex_create_network_domain(self):
location = self.driver.ex_get_location_by_id('NA9')
plan = NetworkDomainServicePlan.ADVANCED
net = self.driver.ex_create_network_domain(location=location,
name='test',
description='test',
service_plan=plan)
self.assertEqual(net.name, 'test')
self.assertTrue(net.id, 'f14a871f-9a25-470c-aef8-51e13202e1aa')
def test_ex_create_network_domain_NO_DESCRIPTION(self):
location = self.driver.ex_get_location_by_id('NA9')
plan = NetworkDomainServicePlan.ADVANCED
net = self.driver.ex_create_network_domain(location=location,
name='test',
service_plan=plan)
self.assertEqual(net.name, 'test')
self.assertTrue(net.id, 'f14a871f-9a25-470c-aef8-51e13202e1aa')
def test_ex_get_network_domain(self):
net = self.driver.ex_get_network_domain('8cdfd607-f429-4df6-9352-162cfc0891be')
self.assertEqual(net.id, '8cdfd607-f429-4df6-9352-162cfc0891be')
self.assertEqual(net.description, 'test2')
self.assertEqual(net.name, 'test')
def test_ex_update_network_domain(self):
net = self.driver.ex_get_network_domain('8cdfd607-f429-4df6-9352-162cfc0891be')
net.name = 'new name'
net2 = self.driver.ex_update_network_domain(net)
self.assertEqual(net2.name, 'new name')
def test_ex_delete_network_domain(self):
net = self.driver.ex_get_network_domain('8cdfd607-f429-4df6-9352-162cfc0891be')
result = self.driver.ex_delete_network_domain(net)
self.assertTrue(result)
def test_ex_list_networks(self):
nets = self.driver.ex_list_networks()
self.assertEqual(nets[0].name, 'test-net1')
self.assertTrue(isinstance(nets[0].location, NodeLocation))
def test_ex_list_network_domains(self):
nets = self.driver.ex_list_network_domains()
self.assertEqual(nets[0].name, 'Aurora')
self.assertTrue(isinstance(nets[0].location, NodeLocation))
def test_ex_list_network_domains_ALLFILTERS(self):
DimensionDataMockHttp.type = 'ALLFILTERS'
nets = self.driver.ex_list_network_domains(location='fake_location', name='fake_name',
service_plan='fake_plan', state='fake_state')
self.assertEqual(nets[0].name, 'Aurora')
self.assertTrue(isinstance(nets[0].location, NodeLocation))
def test_ex_list_vlans(self):
vlans = self.driver.ex_list_vlans()
self.assertEqual(vlans[0].name, "Primary")
def test_ex_list_vlans_ALLFILTERS(self):
DimensionDataMockHttp.type = 'ALLFILTERS'
vlans = self.driver.ex_list_vlans(location='fake_location', network_domain='fake_network_domain',
name='fake_name', ipv4_address='fake_ipv4', ipv6_address='fake_ipv6', state='fake_state')
self.assertEqual(vlans[0].name, "Primary")
def test_ex_create_vlan(self,):
net = self.driver.ex_get_network_domain('8cdfd607-f429-4df6-9352-162cfc0891be')
vlan = self.driver.ex_create_vlan(network_domain=net,
name='test',
private_ipv4_base_address='10.3.4.0',
private_ipv4_prefix_size='24',
description='test vlan')
self.assertEqual(vlan.id, '0e56433f-d808-4669-821d-812769517ff8')
def test_ex_create_vlan_NO_DESCRIPTION(self,):
net = self.driver.ex_get_network_domain('8cdfd607-f429-4df6-9352-162cfc0891be')
vlan = self.driver.ex_create_vlan(network_domain=net,
name='test',
private_ipv4_base_address='10.3.4.0',
private_ipv4_prefix_size='24')
self.assertEqual(vlan.id, '0e56433f-d808-4669-821d-812769517ff8')
def test_ex_get_vlan(self):
vlan = self.driver.ex_get_vlan('0e56433f-d808-4669-821d-812769517ff8')
self.assertEqual(vlan.id, '0e56433f-d808-4669-821d-812769517ff8')
self.assertEqual(vlan.description, 'test2')
self.assertEqual(vlan.status, 'NORMAL')
self.assertEqual(vlan.name, 'Production VLAN')
self.assertEqual(vlan.private_ipv4_range_address, '10.0.3.0')
self.assertEqual(vlan.private_ipv4_range_size, 24)
self.assertEqual(vlan.ipv6_range_size, 64)
self.assertEqual(vlan.ipv6_range_address, '2607:f480:1111:1153:0:0:0:0')
self.assertEqual(vlan.ipv4_gateway, '10.0.3.1')
self.assertEqual(vlan.ipv6_gateway, '2607:f480:1111:1153:0:0:0:1')
def test_ex_wait_for_state(self):
self.driver.ex_wait_for_state('NORMAL',
self.driver.ex_get_vlan,
vlan_id='0e56433f-d808-4669-821d-812769517ff8',
poll_interval=0.1)
def test_ex_wait_for_state_NODE(self):
self.driver.ex_wait_for_state('running',
self.driver.ex_get_node_by_id,
id='e75ead52-692f-4314-8725-c8a4f4d13a87',
poll_interval=0.1)
def test_ex_wait_for_state_FAIL(self):
with self.assertRaises(DimensionDataAPIException) as context:
self.driver.ex_wait_for_state('starting',
self.driver.ex_get_node_by_id,
id='e75ead52-692f-4314-8725-c8a4f4d13a87',
poll_interval=0.1,
timeout=0.1
)
self.assertEqual(context.exception.code, 'running')
self.assertTrue('timed out' in context.exception.msg)
def test_ex_update_vlan(self):
vlan = self.driver.ex_get_vlan('0e56433f-d808-4669-821d-812769517ff8')
vlan.name = 'new name'
vlan2 = self.driver.ex_update_vlan(vlan)
self.assertEqual(vlan2.name, 'new name')
def test_ex_delete_vlan(self):
vlan = self.driver.ex_get_vlan('0e56433f-d808-4669-821d-812769517ff8')
result = self.driver.ex_delete_vlan(vlan)
self.assertTrue(result)
def test_ex_expand_vlan(self):
vlan = self.driver.ex_get_vlan('0e56433f-d808-4669-821d-812769517ff8')
vlan.private_ipv4_range_size = '23'
vlan = self.driver.ex_expand_vlan(vlan)
self.assertEqual(vlan.private_ipv4_range_size, '23')
def test_ex_add_public_ip_block_to_network_domain(self):
net = self.driver.ex_get_network_domain('8cdfd607-f429-4df6-9352-162cfc0891be')
block = self.driver.ex_add_public_ip_block_to_network_domain(net)
self.assertEqual(block.id, '9945dc4a-bdce-11e4-8c14-b8ca3a5d9ef8')
def test_ex_list_public_ip_blocks(self):
net = self.driver.ex_get_network_domain('8cdfd607-f429-4df6-9352-162cfc0891be')
blocks = self.driver.ex_list_public_ip_blocks(net)
self.assertEqual(blocks[0].base_ip, '168.128.4.18')
self.assertEqual(blocks[0].size, '2')
self.assertEqual(blocks[0].id, '9945dc4a-bdce-11e4-8c14-b8ca3a5d9ef8')
self.assertEqual(blocks[0].location.id, 'NA9')
self.assertEqual(blocks[0].network_domain.id, net.id)
def test_ex_get_public_ip_block(self):
net = self.driver.ex_get_network_domain('8cdfd607-f429-4df6-9352-162cfc0891be')
block = self.driver.ex_get_public_ip_block('9945dc4a-bdce-11e4-8c14-b8ca3a5d9ef8')
self.assertEqual(block.base_ip, '168.128.4.18')
self.assertEqual(block.size, '2')
self.assertEqual(block.id, '9945dc4a-bdce-11e4-8c14-b8ca3a5d9ef8')
self.assertEqual(block.location.id, 'NA9')
self.assertEqual(block.network_domain.id, net.id)
def test_ex_delete_public_ip_block(self):
block = self.driver.ex_get_public_ip_block('9945dc4a-bdce-11e4-8c14-b8ca3a5d9ef8')
result = self.driver.ex_delete_public_ip_block(block)
self.assertTrue(result)
def test_ex_list_firewall_rules(self):
net = self.driver.ex_get_network_domain('8cdfd607-f429-4df6-9352-162cfc0891be')
rules = self.driver.ex_list_firewall_rules(net)
self.assertEqual(rules[0].id, '756cba02-b0bc-48f4-aea5-9445870b6148')
self.assertEqual(rules[0].network_domain.id, '8cdfd607-f429-4df6-9352-162cfc0891be')
self.assertEqual(rules[0].name, 'CCDEFAULT.BlockOutboundMailIPv4')
self.assertEqual(rules[0].action, 'DROP')
self.assertEqual(rules[0].ip_version, 'IPV4')
self.assertEqual(rules[0].protocol, 'TCP')
self.assertEqual(rules[0].source.ip_address, 'ANY')
self.assertTrue(rules[0].source.any_ip)
self.assertTrue(rules[0].destination.any_ip)
def test_ex_create_firewall_rule(self):
net = self.driver.ex_get_network_domain('8cdfd607-f429-4df6-9352-162cfc0891be')
rules = self.driver.ex_list_firewall_rules(net)
rule = self.driver.ex_create_firewall_rule(net, rules[0], 'FIRST')
self.assertEqual(rule.id, 'd0a20f59-77b9-4f28-a63b-e58496b73a6c')
def test_ex_create_firewall_rule_with_specific_source_ip(self):
net = self.driver.ex_get_network_domain('8cdfd607-f429-4df6-9352-162cfc0891be')
rules = self.driver.ex_list_firewall_rules(net)
specific_source_ip_rule = list(filter(lambda x: x.name == 'SpecificSourceIP',
rules))[0]
rule = self.driver.ex_create_firewall_rule(net, specific_source_ip_rule, 'FIRST')
self.assertEqual(rule.id, 'd0a20f59-77b9-4f28-a63b-e58496b73a6c')
def test_ex_create_firewall_rule_with_source_ip(self):
net = self.driver.ex_get_network_domain(
'8cdfd607-f429-4df6-9352-162cfc0891be')
rules = self.driver.ex_list_firewall_rules(net)
specific_source_ip_rule = \
list(filter(lambda x: x.name == 'SpecificSourceIP',
rules))[0]
specific_source_ip_rule.source.any_ip = False
specific_source_ip_rule.source.ip_address = '10.0.0.1'
specific_source_ip_rule.source.ip_prefix_size = '15'
rule = self.driver.ex_create_firewall_rule(net,
specific_source_ip_rule,
'FIRST')
self.assertEqual(rule.id, 'd0a20f59-77b9-4f28-a63b-e58496b73a6c')
def test_ex_create_firewall_rule_with_any_ip(self):
net = self.driver.ex_get_network_domain(
'8cdfd607-f429-4df6-9352-162cfc0891be')
rules = self.driver.ex_list_firewall_rules(net)
specific_source_ip_rule = \
list(filter(lambda x: x.name == 'SpecificSourceIP',
rules))[0]
specific_source_ip_rule.source.any_ip = True
rule = self.driver.ex_create_firewall_rule(net,
specific_source_ip_rule,
'FIRST')
self.assertEqual(rule.id, 'd0a20f59-77b9-4f28-a63b-e58496b73a6c')
def test_ex_create_firewall_rule_ip_prefix_size(self):
net = self.driver.ex_get_network_domain(
'8cdfd607-f429-4df6-9352-162cfc0891be')
rule = self.driver.ex_list_firewall_rules(net)[0]
rule.source.address_list_id = None
rule.source.any_ip = False
rule.source.ip_address = '10.2.1.1'
rule.source.ip_prefix_size = '10'
rule.destination.address_list_id = None
rule.destination.any_ip = False
rule.destination.ip_address = '10.0.0.1'
rule.destination.ip_prefix_size = '20'
self.driver.ex_create_firewall_rule(net, rule, 'LAST')
def test_ex_create_firewall_rule_address_list(self):
net = self.driver.ex_get_network_domain('8cdfd607-f429-4df6-9352-162cfc0891be')
rule = self.driver.ex_list_firewall_rules(net)[0]
rule.source.address_list_id = '12345'
rule.destination.address_list_id = '12345'
self.driver.ex_create_firewall_rule(net, rule, 'LAST')
def test_ex_create_firewall_rule_port_list(self):
net = self.driver.ex_get_network_domain('8cdfd607-f429-4df6-9352-162cfc0891be')
rule = self.driver.ex_list_firewall_rules(net)[0]
rule.source.port_list_id = '12345'
rule.destination.port_list_id = '12345'
self.driver.ex_create_firewall_rule(net, rule, 'LAST')
def test_ex_create_firewall_rule_port(self):
net = self.driver.ex_get_network_domain(
'8cdfd607-f429-4df6-9352-162cfc0891be')
rule = self.driver.ex_list_firewall_rules(net)[0]
rule.source.port_list_id = None
rule.source.port_begin = '8000'
rule.source.port_end = '8005'
rule.destination.port_list_id = None
rule.destination.port_begin = '7000'
rule.destination.port_end = '7005'
self.driver.ex_create_firewall_rule(net, rule, 'LAST')
def test_ex_create_firewall_rule_ALL_VALUES(self):
net = self.driver.ex_get_network_domain('8cdfd607-f429-4df6-9352-162cfc0891be')
rules = self.driver.ex_list_firewall_rules(net)
for rule in rules:
self.driver.ex_create_firewall_rule(net, rule, 'LAST')
def test_ex_create_firewall_rule_WITH_POSITION_RULE(self):
net = self.driver.ex_get_network_domain('8cdfd607-f429-4df6-9352-162cfc0891be')
rules = self.driver.ex_list_firewall_rules(net)
rule = self.driver.ex_create_firewall_rule(net, rules[-2], 'BEFORE', rules[-1])
self.assertEqual(rule.id, 'd0a20f59-77b9-4f28-a63b-e58496b73a6c')
def test_ex_create_firewall_rule_WITH_POSITION_RULE_STR(self):
net = self.driver.ex_get_network_domain('8cdfd607-f429-4df6-9352-162cfc0891be')
rules = self.driver.ex_list_firewall_rules(net)
rule = self.driver.ex_create_firewall_rule(net, rules[-2], 'BEFORE', 'RULE_WITH_SOURCE_AND_DEST')
self.assertEqual(rule.id, 'd0a20f59-77b9-4f28-a63b-e58496b73a6c')
def test_ex_create_firewall_rule_FAIL_POSITION(self):
net = self.driver.ex_get_network_domain('8cdfd607-f429-4df6-9352-162cfc0891be')
rules = self.driver.ex_list_firewall_rules(net)
with self.assertRaises(ValueError):
self.driver.ex_create_firewall_rule(net, rules[0], 'BEFORE')
def test_ex_create_firewall_rule_FAIL_POSITION_WITH_RULE(self):
net = self.driver.ex_get_network_domain('8cdfd607-f429-4df6-9352-162cfc0891be')
rules = self.driver.ex_list_firewall_rules(net)
with self.assertRaises(ValueError):
self.driver.ex_create_firewall_rule(net, rules[0], 'LAST', 'RULE_WITH_SOURCE_AND_DEST')
def test_ex_get_firewall_rule(self):
net = self.driver.ex_get_network_domain('8cdfd607-f429-4df6-9352-162cfc0891be')
rule = self.driver.ex_get_firewall_rule(net, 'd0a20f59-77b9-4f28-a63b-e58496b73a6c')
self.assertEqual(rule.id, 'd0a20f59-77b9-4f28-a63b-e58496b73a6c')
def test_ex_set_firewall_rule_state(self):
net = self.driver.ex_get_network_domain('8cdfd607-f429-4df6-9352-162cfc0891be')
rule = self.driver.ex_get_firewall_rule(net, 'd0a20f59-77b9-4f28-a63b-e58496b73a6c')
result = self.driver.ex_set_firewall_rule_state(rule, False)
self.assertTrue(result)
def test_ex_delete_firewall_rule(self):
net = self.driver.ex_get_network_domain('8cdfd607-f429-4df6-9352-162cfc0891be')
rule = self.driver.ex_get_firewall_rule(net, 'd0a20f59-77b9-4f28-a63b-e58496b73a6c')
result = self.driver.ex_delete_firewall_rule(rule)
self.assertTrue(result)
def test_ex_edit_firewall_rule(self):
net = self.driver.ex_get_network_domain(
'8cdfd607-f429-4df6-9352-162cfc0891be')
rule = self.driver.ex_get_firewall_rule(
net, 'd0a20f59-77b9-4f28-a63b-e58496b73a6c')
rule.source.any_ip = True
result = self.driver.ex_edit_firewall_rule(rule=rule, position='LAST')
self.assertTrue(result)
def test_ex_edit_firewall_rule_source_ipaddresslist(self):
net = self.driver.ex_get_network_domain(
'8cdfd607-f429-4df6-9352-162cfc0891be')
rule = self.driver.ex_get_firewall_rule(
net, 'd0a20f59-77b9-4f28-a63b-e58496b73a6c')
rule.source.address_list_id = '802abc9f-45a7-4efb-9d5a-810082368222'
rule.source.any_ip = False
rule.source.ip_address = '10.0.0.1'
rule.source.ip_prefix_size = 10
result = self.driver.ex_edit_firewall_rule(rule=rule, position='LAST')
self.assertTrue(result)
def test_ex_edit_firewall_rule_destination_ipaddresslist(self):
net = self.driver.ex_get_network_domain(
'8cdfd607-f429-4df6-9352-162cfc0891be')
rule = self.driver.ex_get_firewall_rule(
net, 'd0a20f59-77b9-4f28-a63b-e58496b73a6c')
rule.destination.address_list_id = '802abc9f-45a7-4efb-9d5a-810082368222'
rule.destination.any_ip = False
rule.destination.ip_address = '10.0.0.1'
rule.destination.ip_prefix_size = 10
result = self.driver.ex_edit_firewall_rule(rule=rule, position='LAST')
self.assertTrue(result)
def test_ex_edit_firewall_rule_destination_ipaddress(self):
net = self.driver.ex_get_network_domain(
'8cdfd607-f429-4df6-9352-162cfc0891be')
rule = self.driver.ex_get_firewall_rule(
net, 'd0a20f59-77b9-4f28-a63b-e58496b73a6c')
rule.source.address_list_id = None
rule.source.any_ip = False
rule.source.ip_address = '10.0.0.1'
rule.source.ip_prefix_size = '10'
result = self.driver.ex_edit_firewall_rule(rule=rule, position='LAST')
self.assertTrue(result)
def test_ex_edit_firewall_rule_source_ipaddress(self):
net = self.driver.ex_get_network_domain(
'8cdfd607-f429-4df6-9352-162cfc0891be')
rule = self.driver.ex_get_firewall_rule(
net, 'd0a20f59-77b9-4f28-a63b-e58496b73a6c')
rule.destination.address_list_id = None
rule.destination.any_ip = False
rule.destination.ip_address = '10.0.0.1'
rule.destination.ip_prefix_size = '10'
result = self.driver.ex_edit_firewall_rule(rule=rule, position='LAST')
self.assertTrue(result)
def test_ex_edit_firewall_rule_with_relative_rule(self):
net = self.driver.ex_get_network_domain(
'8cdfd607-f429-4df6-9352-162cfc0891be')
rule = self.driver.ex_get_firewall_rule(
net, 'd0a20f59-77b9-4f28-a63b-e58496b73a6c')
placement_rule = self.driver.ex_list_firewall_rules(
network_domain=net)[-1]
result = self.driver.ex_edit_firewall_rule(
rule=rule, position='BEFORE',
relative_rule_for_position=placement_rule)
self.assertTrue(result)
def test_ex_edit_firewall_rule_with_relative_rule_by_name(self):
net = self.driver.ex_get_network_domain(
'8cdfd607-f429-4df6-9352-162cfc0891be')
rule = self.driver.ex_get_firewall_rule(
net, 'd0a20f59-77b9-4f28-a63b-e58496b73a6c')
placement_rule = self.driver.ex_list_firewall_rules(
network_domain=net)[-1]
result = self.driver.ex_edit_firewall_rule(
rule=rule, position='BEFORE',
relative_rule_for_position=placement_rule.name)
self.assertTrue(result)
def test_ex_edit_firewall_rule_source_portlist(self):
net = self.driver.ex_get_network_domain(
'8cdfd607-f429-4df6-9352-162cfc0891be')
rule = self.driver.ex_get_firewall_rule(
net, 'd0a20f59-77b9-4f28-a63b-e58496b73a6c')
rule.source.port_list_id = '802abc9f-45a7-4efb-9d5a-810082368222'
result = self.driver.ex_edit_firewall_rule(rule=rule, position='LAST')
self.assertTrue(result)
def test_ex_edit_firewall_rule_source_port(self):
net = self.driver.ex_get_network_domain(
'8cdfd607-f429-4df6-9352-162cfc0891be')
rule = self.driver.ex_get_firewall_rule(
net, 'd0a20f59-77b9-4f28-a63b-e58496b73a6c')
rule.source.port_list_id = None
rule.source.port_begin = '3'
rule.source.port_end = '10'
result = self.driver.ex_edit_firewall_rule(rule=rule, position='LAST')
self.assertTrue(result)
def test_ex_edit_firewall_rule_destination_portlist(self):
net = self.driver.ex_get_network_domain(
'8cdfd607-f429-4df6-9352-162cfc0891be')
rule = self.driver.ex_get_firewall_rule(
net, 'd0a20f59-77b9-4f28-a63b-e58496b73a6c')
rule.destination.port_list_id = '802abc9f-45a7-4efb-9d5a-810082368222'
result = self.driver.ex_edit_firewall_rule(rule=rule, position='LAST')
self.assertTrue(result)
def test_ex_edit_firewall_rule_destination_port(self):
net = self.driver.ex_get_network_domain(
'8cdfd607-f429-4df6-9352-162cfc0891be')
rule = self.driver.ex_get_firewall_rule(
net, 'd0a20f59-77b9-4f28-a63b-e58496b73a6c')
rule.destination.port_list_id = None
rule.destination.port_begin = '3'
rule.destination.port_end = '10'
result = self.driver.ex_edit_firewall_rule(rule=rule, position='LAST')
self.assertTrue(result)
def test_ex_edit_firewall_rule_invalid_position_fail(self):
net = self.driver.ex_get_network_domain(
'8cdfd607-f429-4df6-9352-162cfc0891be')
rule = self.driver.ex_get_firewall_rule(
net, 'd0a20f59-77b9-4f28-a63b-e58496b73a6c')
with self.assertRaises(ValueError):
self.driver.ex_edit_firewall_rule(rule=rule, position='BEFORE')
def test_ex_edit_firewall_rule_invalid_position_relative_rule_fail(self):
net = self.driver.ex_get_network_domain(
'8cdfd607-f429-4df6-9352-162cfc0891be')
rule = self.driver.ex_get_firewall_rule(
net, 'd0a20f59-77b9-4f28-a63b-e58496b73a6c')
relative_rule = self.driver.ex_list_firewall_rules(
network_domain=net)[-1]
with self.assertRaises(ValueError):
self.driver.ex_edit_firewall_rule(rule=rule, position='FIRST',
relative_rule_for_position=relative_rule)
def test_ex_create_nat_rule(self):
net = self.driver.ex_get_network_domain('8cdfd607-f429-4df6-9352-162cfc0891be')
rule = self.driver.ex_create_nat_rule(net, '1.2.3.4', '4.3.2.1')
self.assertEqual(rule.id, 'd31c2db0-be6b-4d50-8744-9a7a534b5fba')
def test_ex_list_nat_rules(self):
net = self.driver.ex_get_network_domain('8cdfd607-f429-4df6-9352-162cfc0891be')
rules = self.driver.ex_list_nat_rules(net)
self.assertEqual(rules[0].id, '2187a636-7ebb-49a1-a2ff-5d617f496dce')
self.assertEqual(rules[0].internal_ip, '10.0.0.15')
self.assertEqual(rules[0].external_ip, '165.180.12.18')
def test_ex_get_nat_rule(self):
net = self.driver.ex_get_network_domain('8cdfd607-f429-4df6-9352-162cfc0891be')
rule = self.driver.ex_get_nat_rule(net, '2187a636-7ebb-49a1-a2ff-5d617f496dce')
self.assertEqual(rule.id, '2187a636-7ebb-49a1-a2ff-5d617f496dce')
self.assertEqual(rule.internal_ip, '10.0.0.16')
self.assertEqual(rule.external_ip, '165.180.12.19')
def test_ex_delete_nat_rule(self):
net = self.driver.ex_get_network_domain('8cdfd607-f429-4df6-9352-162cfc0891be')
rule = self.driver.ex_get_nat_rule(net, '2187a636-7ebb-49a1-a2ff-5d617f496dce')
result = self.driver.ex_delete_nat_rule(rule)
self.assertTrue(result)
def test_ex_enable_monitoring(self):
node = self.driver.list_nodes()[0]
result = self.driver.ex_enable_monitoring(node, "ADVANCED")
self.assertTrue(result)
def test_ex_disable_monitoring(self):
node = self.driver.list_nodes()[0]
result = self.driver.ex_disable_monitoring(node)
self.assertTrue(result)
def test_ex_change_monitoring_plan(self):
node = self.driver.list_nodes()[0]
result = self.driver.ex_update_monitoring_plan(node, "ESSENTIALS")
self.assertTrue(result)
def test_ex_add_storage_to_node(self):
node = self.driver.list_nodes()[0]
result = self.driver.ex_add_storage_to_node(node, 30, 'PERFORMANCE')
self.assertTrue(result)
def test_ex_remove_storage_from_node(self):
node = self.driver.list_nodes()[0]
result = self.driver.ex_remove_storage_from_node(node, 0)
self.assertTrue(result)
def test_ex_change_storage_speed(self):
node = self.driver.list_nodes()[0]
result = self.driver.ex_change_storage_speed(node, 1, 'PERFORMANCE')
self.assertTrue(result)
def test_ex_change_storage_size(self):
node = self.driver.list_nodes()[0]
result = self.driver.ex_change_storage_size(node, 1, 100)
self.assertTrue(result)
def test_ex_clone_node_to_image(self):
node = self.driver.list_nodes()[0]
result = self.driver.ex_clone_node_to_image(node, 'my image', 'a description')
self.assertTrue(result)
def test_ex_update_node(self):
node = self.driver.list_nodes()[0]
result = self.driver.ex_update_node(node, 'my new name', 'a description', 2, 4048)
self.assertTrue(result)
def test_ex_reconfigure_node(self):
node = self.driver.list_nodes()[0]
result = self.driver.ex_reconfigure_node(node, 4, 4, 1, 'HIGHPERFORMANCE')
self.assertTrue(result)
def test_ex_get_location_by_id(self):
location = self.driver.ex_get_location_by_id('NA9')
self.assertTrue(location.id, 'NA9')
def test_ex_get_location_by_id_NO_LOCATION(self):
location = self.driver.ex_get_location_by_id(None)
self.assertIsNone(location)
def test_ex_get_base_image_by_id(self):
image_id = self.driver.list_images()[0].id
image = self.driver.ex_get_base_image_by_id(image_id)
self.assertEqual(image.extra['OS_type'], 'UNIX')
def test_ex_get_customer_image_by_id(self):
image_id = self.driver.ex_list_customer_images()[1].id
image = self.driver.ex_get_customer_image_by_id(image_id)
self.assertEqual(image.extra['OS_type'], 'WINDOWS')
def test_ex_get_image_by_id_base_img(self):
image_id = self.driver.list_images()[1].id
image = self.driver.ex_get_base_image_by_id(image_id)
self.assertEqual(image.extra['OS_type'], 'WINDOWS')
def test_ex_get_image_by_id_customer_img(self):
image_id = self.driver.ex_list_customer_images()[0].id
image = self.driver.ex_get_customer_image_by_id(image_id)
self.assertEqual(image.extra['OS_type'], 'UNIX')
def test_ex_get_image_by_id_customer_FAIL(self):
image_id = 'FAKE_IMAGE_ID'
with self.assertRaises(DimensionDataAPIException):
self.driver.ex_get_base_image_by_id(image_id)
def test_ex_create_anti_affinity_rule(self):
node_list = self.driver.list_nodes()
success = self.driver.ex_create_anti_affinity_rule([node_list[0], node_list[1]])
self.assertTrue(success)
def test_ex_create_anti_affinity_rule_TUPLE(self):
node_list = self.driver.list_nodes()
success = self.driver.ex_create_anti_affinity_rule((node_list[0], node_list[1]))
self.assertTrue(success)
def test_ex_create_anti_affinity_rule_TUPLE_STR(self):
node_list = self.driver.list_nodes()
success = self.driver.ex_create_anti_affinity_rule((node_list[0].id, node_list[1].id))
self.assertTrue(success)
def test_ex_create_anti_affinity_rule_FAIL_STR(self):
node_list = 'string'
with self.assertRaises(TypeError):
self.driver.ex_create_anti_affinity_rule(node_list)
def test_ex_create_anti_affinity_rule_FAIL_EXISTING(self):
node_list = self.driver.list_nodes()
DimensionDataMockHttp.type = 'FAIL_EXISTING'
with self.assertRaises(DimensionDataAPIException):
self.driver.ex_create_anti_affinity_rule((node_list[0], node_list[1]))
def test_ex_delete_anti_affinity_rule(self):
net_domain = self.driver.ex_list_network_domains()[0]
rule = self.driver.ex_list_anti_affinity_rules(network_domain=net_domain)[0]
success = self.driver.ex_delete_anti_affinity_rule(rule)
self.assertTrue(success)
def test_ex_delete_anti_affinity_rule_STR(self):
net_domain = self.driver.ex_list_network_domains()[0]
rule = self.driver.ex_list_anti_affinity_rules(network_domain=net_domain)[0]
success = self.driver.ex_delete_anti_affinity_rule(rule.id)
self.assertTrue(success)
def test_ex_delete_anti_affinity_rule_FAIL(self):
net_domain = self.driver.ex_list_network_domains()[0]
rule = self.driver.ex_list_anti_affinity_rules(network_domain=net_domain)[0]
DimensionDataMockHttp.type = 'FAIL'
with self.assertRaises(DimensionDataAPIException):
self.driver.ex_delete_anti_affinity_rule(rule)
def test_ex_list_anti_affinity_rules_NETWORK_DOMAIN(self):
net_domain = self.driver.ex_list_network_domains()[0]
rules = self.driver.ex_list_anti_affinity_rules(network_domain=net_domain)
self.assertTrue(isinstance(rules, list))
self.assertEqual(len(rules), 2)
self.assertTrue(isinstance(rules[0].id, str))
self.assertTrue(isinstance(rules[0].node_list, list))
def test_ex_list_anti_affinity_rules_NETWORK(self):
network = self.driver.list_networks()[0]
rules = self.driver.ex_list_anti_affinity_rules(network=network)
self.assertTrue(isinstance(rules, list))
self.assertEqual(len(rules), 2)
self.assertTrue(isinstance(rules[0].id, str))
self.assertTrue(isinstance(rules[0].node_list, list))
def test_ex_list_anti_affinity_rules_NODE(self):
node = self.driver.list_nodes()[0]
rules = self.driver.ex_list_anti_affinity_rules(node=node)
self.assertTrue(isinstance(rules, list))
self.assertEqual(len(rules), 2)
self.assertTrue(isinstance(rules[0].id, str))
self.assertTrue(isinstance(rules[0].node_list, list))
def test_ex_list_anti_affinity_rules_PAGINATED(self):
net_domain = self.driver.ex_list_network_domains()[0]
DimensionDataMockHttp.type = 'PAGINATED'
rules = self.driver.ex_list_anti_affinity_rules(network_domain=net_domain)
self.assertTrue(isinstance(rules, list))
self.assertEqual(len(rules), 4)
self.assertTrue(isinstance(rules[0].id, str))
self.assertTrue(isinstance(rules[0].node_list, list))
def test_ex_list_anti_affinity_rules_ALLFILTERS(self):
net_domain = self.driver.ex_list_network_domains()[0]
DimensionDataMockHttp.type = 'ALLFILTERS'
rules = self.driver.ex_list_anti_affinity_rules(network_domain=net_domain, filter_id='FAKE_ID', filter_state='FAKE_STATE')
self.assertTrue(isinstance(rules, list))
self.assertEqual(len(rules), 2)
self.assertTrue(isinstance(rules[0].id, str))
self.assertTrue(isinstance(rules[0].node_list, list))
def test_ex_list_anti_affinity_rules_BAD_ARGS(self):
with self.assertRaises(ValueError):
self.driver.ex_list_anti_affinity_rules(network='fake_network', network_domain='fake_network_domain')
def test_ex_create_tag_key(self):
success = self.driver.ex_create_tag_key('MyTestKey')
self.assertTrue(success)
def test_ex_create_tag_key_ALLPARAMS(self):
self.driver.connection._get_orgId()
DimensionDataMockHttp.type = 'ALLPARAMS'
success = self.driver.ex_create_tag_key('MyTestKey', description="Test Key Desc.", value_required=False, display_on_report=False)
self.assertTrue(success)
def test_ex_create_tag_key_BADREQUEST(self):
self.driver.connection._get_orgId()
DimensionDataMockHttp.type = 'BADREQUEST'
with self.assertRaises(DimensionDataAPIException):
self.driver.ex_create_tag_key('MyTestKey')
def test_ex_list_tag_keys(self):
tag_keys = self.driver.ex_list_tag_keys()
self.assertTrue(isinstance(tag_keys, list))
self.assertTrue(isinstance(tag_keys[0], DimensionDataTagKey))
self.assertTrue(isinstance(tag_keys[0].id, str))
def test_ex_list_tag_keys_ALLFILTERS(self):
self.driver.connection._get_orgId()
DimensionDataMockHttp.type = 'ALLFILTERS'
self.driver.ex_list_tag_keys(id='fake_id', name='fake_name', value_required=False, display_on_report=False)
def test_ex_get_tag_by_id(self):
tag = self.driver.ex_get_tag_key_by_id('d047c609-93d7-4bc5-8fc9-732c85840075')
self.assertTrue(isinstance(tag, DimensionDataTagKey))
def test_ex_get_tag_by_id_NOEXIST(self):
self.driver.connection._get_orgId()
DimensionDataMockHttp.type = 'NOEXIST'
with self.assertRaises(DimensionDataAPIException):
self.driver.ex_get_tag_key_by_id('d047c609-93d7-4bc5-8fc9-732c85840075')
def test_ex_get_tag_by_name(self):
self.driver.connection._get_orgId()
DimensionDataMockHttp.type = 'SINGLE'
tag = self.driver.ex_get_tag_key_by_name('LibcloudTest')
self.assertTrue(isinstance(tag, DimensionDataTagKey))
def test_ex_get_tag_by_name_NOEXIST(self):
with self.assertRaises(ValueError):
self.driver.ex_get_tag_key_by_name('LibcloudTest')
def test_ex_modify_tag_key_NAME(self):
tag_key = self.driver.ex_list_tag_keys()[0]
DimensionDataMockHttp.type = 'NAME'
success = self.driver.ex_modify_tag_key(tag_key, name='NewName')
self.assertTrue(success)
def test_ex_modify_tag_key_NOTNAME(self):
tag_key = self.driver.ex_list_tag_keys()[0]
DimensionDataMockHttp.type = 'NOTNAME'
success = self.driver.ex_modify_tag_key(tag_key, description='NewDesc', value_required=False, display_on_report=True)
self.assertTrue(success)
def test_ex_modify_tag_key_NOCHANGE(self):
tag_key = self.driver.ex_list_tag_keys()[0]
DimensionDataMockHttp.type = 'NOCHANGE'
with self.assertRaises(DimensionDataAPIException):
self.driver.ex_modify_tag_key(tag_key)
def test_ex_remove_tag_key(self):
tag_key = self.driver.ex_list_tag_keys()[0]
success = self.driver.ex_remove_tag_key(tag_key)
self.assertTrue(success)
def test_ex_remove_tag_key_NOEXIST(self):
tag_key = self.driver.ex_list_tag_keys()[0]
DimensionDataMockHttp.type = 'NOEXIST'
with self.assertRaises(DimensionDataAPIException):
self.driver.ex_remove_tag_key(tag_key)
def test_ex_apply_tag_to_asset(self):
node = self.driver.list_nodes()[0]
success = self.driver.ex_apply_tag_to_asset(node, 'TagKeyName', 'FakeValue')
self.assertTrue(success)
def test_ex_apply_tag_to_asset_NOVALUE(self):
node = self.driver.list_nodes()[0]
DimensionDataMockHttp.type = 'NOVALUE'
success = self.driver.ex_apply_tag_to_asset(node, 'TagKeyName')
self.assertTrue(success)
def test_ex_apply_tag_to_asset_NOTAGKEY(self):
node = self.driver.list_nodes()[0]
DimensionDataMockHttp.type = 'NOTAGKEY'
with self.assertRaises(DimensionDataAPIException):
self.driver.ex_apply_tag_to_asset(node, 'TagKeyNam')
def test_ex_apply_tag_to_asset_BADASSETTYPE(self):
network = self.driver.list_networks()[0]
DimensionDataMockHttp.type = 'NOTAGKEY'
with self.assertRaises(TypeError):
self.driver.ex_apply_tag_to_asset(network, 'TagKeyNam')
def test_ex_remove_tag_from_asset(self):
node = self.driver.list_nodes()[0]
success = self.driver.ex_remove_tag_from_asset(node, 'TagKeyName')
self.assertTrue(success)
def test_ex_remove_tag_from_asset_NOTAG(self):
node = self.driver.list_nodes()[0]
DimensionDataMockHttp.type = 'NOTAG'
with self.assertRaises(DimensionDataAPIException):
self.driver.ex_remove_tag_from_asset(node, 'TagKeyNam')
def test_ex_list_tags(self):
tags = self.driver.ex_list_tags()
self.assertTrue(isinstance(tags, list))
self.assertTrue(isinstance(tags[0], DimensionDataTag))
self.assertTrue(len(tags) == 3)
def test_ex_list_tags_ALLPARAMS(self):
self.driver.connection._get_orgId()
DimensionDataMockHttp.type = 'ALLPARAMS'
tags = self.driver.ex_list_tags(asset_id='fake_asset_id', asset_type='fake_asset_type',
location='fake_location', tag_key_name='fake_tag_key_name',
tag_key_id='fake_tag_key_id', value='fake_value',
value_required=False, display_on_report=False)
self.assertTrue(isinstance(tags, list))
self.assertTrue(isinstance(tags[0], DimensionDataTag))
self.assertTrue(len(tags) == 3)
def test_priv_location_to_location_id(self):
location = self.driver.ex_get_location_by_id('NA9')
self.assertEqual(
self.driver._location_to_location_id(location),
'NA9'
)
def test_priv_location_to_location_id_STR(self):
self.assertEqual(
self.driver._location_to_location_id('NA9'),
'NA9'
)
def test_priv_location_to_location_id_TYPEERROR(self):
with self.assertRaises(TypeError):
self.driver._location_to_location_id([1, 2, 3])
def test_priv_image_needs_auth_os_img(self):
image = self.driver.list_images()[1]
self.assertTrue(self.driver._image_needs_auth(image))
def test_priv_image_needs_auth_os_img_STR(self):
image = self.driver.list_images()[1].id
self.assertTrue(self.driver._image_needs_auth(image))
def test_priv_image_needs_auth_cust_img_windows(self):
image = self.driver.ex_list_customer_images()[1]
self.assertTrue(self.driver._image_needs_auth(image))
def test_priv_image_needs_auth_cust_img_windows_STR(self):
image = self.driver.ex_list_customer_images()[1].id
self.assertTrue(self.driver._image_needs_auth(image))
def test_priv_image_needs_auth_cust_img_linux(self):
image = self.driver.ex_list_customer_images()[0]
self.assertTrue(not self.driver._image_needs_auth(image))
def test_priv_image_needs_auth_cust_img_linux_STR(self):
image = self.driver.ex_list_customer_images()[0].id
self.assertTrue(not self.driver._image_needs_auth(image))
def test_summary_usage_report(self):
report = self.driver.ex_summary_usage_report('2016-06-01', '2016-06-30')
report_content = report
self.assertEqual(len(report_content), 13)
self.assertEqual(len(report_content[0]), 6)
def test_detailed_usage_report(self):
report = self.driver.ex_detailed_usage_report('2016-06-01', '2016-06-30')
report_content = report
self.assertEqual(len(report_content), 42)
self.assertEqual(len(report_content[0]), 4)
def test_audit_log_report(self):
report = self.driver.ex_audit_log_report('2016-06-01', '2016-06-30')
report_content = report
self.assertEqual(len(report_content), 25)
self.assertEqual(report_content[2][2], 'OEC_SYSTEM')
def test_ex_list_ip_address_list(self):
net_domain = self.driver.ex_list_network_domains()[0]
ip_list = self.driver.ex_list_ip_address_list(
ex_network_domain=net_domain)
self.assertTrue(isinstance(ip_list, list))
self.assertEqual(len(ip_list), 4)
self.assertTrue(isinstance(ip_list[0].name, str))
self.assertTrue(isinstance(ip_list[0].description, str))
self.assertTrue(isinstance(ip_list[0].ip_version, str))
self.assertTrue(isinstance(ip_list[0].state, str))
self.assertTrue(isinstance(ip_list[0].create_time, str))
self.assertTrue(isinstance(ip_list[0].child_ip_address_lists, list))
self.assertEqual(len(ip_list[1].child_ip_address_lists), 1)
self.assertTrue(isinstance(ip_list[1].child_ip_address_lists[0].name,
str))
def test_ex_get_ip_address_list(self):
net_domain = self.driver.ex_list_network_domains()[0]
DimensionDataMockHttp.type = 'FILTERBYNAME'
ip_list = self.driver.ex_get_ip_address_list(
ex_network_domain=net_domain.id,
ex_ip_address_list_name='Test_IP_Address_List_3')
self.assertTrue(isinstance(ip_list, list))
self.assertEqual(len(ip_list), 1)
self.assertTrue(isinstance(ip_list[0].name, str))
self.assertTrue(isinstance(ip_list[0].description, str))
self.assertTrue(isinstance(ip_list[0].ip_version, str))
self.assertTrue(isinstance(ip_list[0].state, str))
self.assertTrue(isinstance(ip_list[0].create_time, str))
ips = ip_list[0].ip_address_collection
self.assertEqual(len(ips), 3)
self.assertTrue(isinstance(ips[0].begin, str))
self.assertTrue(isinstance(ips[0].prefix_size, str))
self.assertTrue(isinstance(ips[2].end, str))
def test_ex_create_ip_address_list_FAIL(self):
net_domain = self.driver.ex_list_network_domains()[0]
with self.assertRaises(TypeError):
self.driver.ex_create_ip_address_list(
ex_network_domain=net_domain.id)
def test_ex_create_ip_address_list(self):
name = "Test_IP_Address_List_3"
description = "Test Description"
ip_version = "IPV4"
child_ip_address_list_id = '0291ef78-4059-4bc1-b433-3f6ad698dc41'
child_ip_address_list = DimensionDataChildIpAddressList(
id=child_ip_address_list_id,
name="test_child_ip_addr_list")
net_domain = self.driver.ex_list_network_domains()[0]
ip_address_1 = DimensionDataIpAddress(begin='190.2.2.100')
ip_address_2 = DimensionDataIpAddress(begin='190.2.2.106',
end='190.2.2.108')
ip_address_3 = DimensionDataIpAddress(begin='190.2.2.0',
prefix_size='24')
ip_address_collection = [ip_address_1, ip_address_2,
ip_address_3]
# Create IP Address List
success = self.driver.ex_create_ip_address_list(
ex_network_domain=net_domain, name=name,
ip_version=ip_version, description=description,
ip_address_collection=ip_address_collection,
child_ip_address_list=child_ip_address_list)
self.assertTrue(success)
def test_ex_create_ip_address_list_STR(self):
name = "Test_IP_Address_List_3"
description = "Test Description"
ip_version = "IPV4"
child_ip_address_list_id = '0291ef78-4059-4bc1-b433-3f6ad698dc41'
net_domain = self.driver.ex_list_network_domains()[0]
ip_address_1 = DimensionDataIpAddress(begin='190.2.2.100')
ip_address_2 = DimensionDataIpAddress(begin='190.2.2.106',
end='190.2.2.108')
ip_address_3 = DimensionDataIpAddress(begin='190.2.2.0',
prefix_size='24')
ip_address_collection = [ip_address_1, ip_address_2,
ip_address_3]
# Create IP Address List
success = self.driver.ex_create_ip_address_list(
ex_network_domain=net_domain.id, name=name,
ip_version=ip_version, description=description,
ip_address_collection=ip_address_collection,
child_ip_address_list=child_ip_address_list_id)
self.assertTrue(success)
def test_ex_edit_ip_address_list(self):
ip_address_1 = DimensionDataIpAddress(begin='190.2.2.111')
ip_address_collection = [ip_address_1]
child_ip_address_list = DimensionDataChildIpAddressList(
id='2221ef78-4059-4bc1-b433-3f6ad698dc41',
name="test_child_ip_address_list edited")
ip_address_list = DimensionDataIpAddressList(
id='1111ef78-4059-4bc1-b433-3f6ad698d111',
name="test ip address list edited",
ip_version="IPv4", description="test",
ip_address_collection=ip_address_collection,
child_ip_address_lists=child_ip_address_list,
state="NORMAL",
create_time='2015-09-29T02:49:45'
)
success = self.driver.ex_edit_ip_address_list(
ex_ip_address_list=ip_address_list,
description="test ip address list",
ip_address_collection=ip_address_collection,
child_ip_address_lists=child_ip_address_list
)
self.assertTrue(success)
def test_ex_edit_ip_address_list_STR(self):
ip_address_1 = DimensionDataIpAddress(begin='190.2.2.111')
ip_address_collection = [ip_address_1]
child_ip_address_list = DimensionDataChildIpAddressList(
id='2221ef78-4059-4bc1-b433-3f6ad698dc41',
name="test_child_ip_address_list edited")
success = self.driver.ex_edit_ip_address_list(
ex_ip_address_list='84e34850-595d- 436e-a885-7cd37edb24a4',
description="test ip address list",
ip_address_collection=ip_address_collection,
child_ip_address_lists=child_ip_address_list
)
self.assertTrue(success)
def test_ex_delete_ip_address_list(self):
child_ip_address_list = DimensionDataChildIpAddressList(
id='2221ef78-4059-4bc1-b433-3f6ad698dc41',
name="test_child_ip_address_list edited")
ip_address_list = DimensionDataIpAddressList(
id='1111ef78-4059-4bc1-b433-3f6ad698d111',
name="test ip address list edited",
ip_version="IPv4", description="test",
ip_address_collection=None,
child_ip_address_lists=child_ip_address_list,
state="NORMAL",
create_time='2015-09-29T02:49:45'
)
success = self.driver.ex_delete_ip_address_list(
ex_ip_address_list=ip_address_list)
self.assertTrue(success)
def test_ex_delete_ip_address_list_STR(self):
success = self.driver.ex_delete_ip_address_list(
ex_ip_address_list='111ef78-4059-4bc1-b433-3f6ad698d111')
self.assertTrue(success)
def test_ex_list_portlist(self):
net_domain = self.driver.ex_list_network_domains()[0]
portlist = self.driver.ex_list_portlist(
ex_network_domain=net_domain)
self.assertTrue(isinstance(portlist, list))
self.assertEqual(len(portlist), 3)
self.assertTrue(isinstance(portlist[0].name, str))
self.assertTrue(isinstance(portlist[0].description, str))
self.assertTrue(isinstance(portlist[0].state, str))
self.assertTrue(isinstance(portlist[0].port_collection, list))
self.assertTrue(isinstance(portlist[0].port_collection[0].begin, str))
self.assertTrue(isinstance(portlist[0].port_collection[0].end, str))
self.assertTrue(isinstance(portlist[0].child_portlist_list, list))
self.assertTrue(isinstance(portlist[0].child_portlist_list[0].id,
str))
self.assertTrue(isinstance(portlist[0].child_portlist_list[0].name,
str))
self.assertTrue(isinstance(portlist[0].create_time, str))
def test_ex_get_port_list(self):
net_domain = self.driver.ex_list_network_domains()[0]
portlist_id = self.driver.ex_list_portlist(
ex_network_domain=net_domain)[0].id
portlist = self.driver.ex_get_portlist(
ex_portlist_id=portlist_id)
self.assertTrue(isinstance(portlist, DimensionDataPortList))
self.assertTrue(isinstance(portlist.name, str))
self.assertTrue(isinstance(portlist.description, str))
self.assertTrue(isinstance(portlist.state, str))
self.assertTrue(isinstance(portlist.port_collection, list))
self.assertTrue(isinstance(portlist.port_collection[0].begin, str))
self.assertTrue(isinstance(portlist.port_collection[0].end, str))
self.assertTrue(isinstance(portlist.child_portlist_list, list))
self.assertTrue(isinstance(portlist.child_portlist_list[0].id,
str))
self.assertTrue(isinstance(portlist.child_portlist_list[0].name,
str))
self.assertTrue(isinstance(portlist.create_time, str))
def test_ex_get_portlist_STR(self):
net_domain = self.driver.ex_list_network_domains()[0]
portlist = self.driver.ex_list_portlist(
ex_network_domain=net_domain)[0]
port_list = self.driver.ex_get_portlist(
ex_portlist_id=portlist.id)
self.assertTrue(isinstance(port_list, DimensionDataPortList))
self.assertTrue(isinstance(port_list.name, str))
self.assertTrue(isinstance(port_list.description, str))
self.assertTrue(isinstance(port_list.state, str))
self.assertTrue(isinstance(port_list.port_collection, list))
self.assertTrue(isinstance(port_list.port_collection[0].begin, str))
self.assertTrue(isinstance(port_list.port_collection[0].end, str))
self.assertTrue(isinstance(port_list.child_portlist_list, list))
self.assertTrue(isinstance(port_list.child_portlist_list[0].id,
str))
self.assertTrue(isinstance(port_list.child_portlist_list[0].name,
str))
self.assertTrue(isinstance(port_list.create_time, str))
def test_ex_create_portlist_NOCHILDPORTLIST(self):
name = "Test_Port_List"
description = "Test Description"
net_domain = self.driver.ex_list_network_domains()[0]
port_1 = DimensionDataPort(begin='8080')
port_2 = DimensionDataIpAddress(begin='8899',
end='9023')
port_collection = [port_1, port_2]
# Create IP Address List
success = self.driver.ex_create_portlist(
ex_network_domain=net_domain, name=name,
description=description,
port_collection=port_collection
)
self.assertTrue(success)
def test_ex_create_portlist(self):
name = "Test_Port_List"
description = "Test Description"
net_domain = self.driver.ex_list_network_domains()[0]
port_1 = DimensionDataPort(begin='8080')
port_2 = DimensionDataIpAddress(begin='8899',
end='9023')
port_collection = [port_1, port_2]
child_port_1 = DimensionDataChildPortList(
id="333174a2-ae74-4658-9e56-50fc90e086cf", name='test port 1')
child_port_2 = DimensionDataChildPortList(
id="311174a2-ae74-4658-9e56-50fc90e04444", name='test port 2')
child_ports = [child_port_1, child_port_2]
# Create IP Address List
success = self.driver.ex_create_portlist(
ex_network_domain=net_domain, name=name,
description=description,
port_collection=port_collection,
child_portlist_list=child_ports
)
self.assertTrue(success)
def test_ex_create_portlist_STR(self):
name = "Test_Port_List"
description = "Test Description"
net_domain = self.driver.ex_list_network_domains()[0]
port_1 = DimensionDataPort(begin='8080')
port_2 = DimensionDataIpAddress(begin='8899',
end='9023')
port_collection = [port_1, port_2]
child_port_1 = DimensionDataChildPortList(
id="333174a2-ae74-4658-9e56-50fc90e086cf", name='test port 1')
child_port_2 = DimensionDataChildPortList(
id="311174a2-ae74-4658-9e56-50fc90e04444", name='test port 2')
child_ports_ids = [child_port_1.id, child_port_2.id]
# Create IP Address List
success = self.driver.ex_create_portlist(
ex_network_domain=net_domain.id, name=name,
description=description,
port_collection=port_collection,
child_portlist_list=child_ports_ids
)
self.assertTrue(success)
def test_ex_edit_portlist(self):
net_domain = self.driver.ex_list_network_domains()[0]
portlist = self.driver.ex_list_portlist(net_domain)[0]
description = "Test Description"
port_1 = DimensionDataPort(begin='8080')
port_2 = DimensionDataIpAddress(begin='8899',
end='9023')
port_collection = [port_1, port_2]
child_port_1 = DimensionDataChildPortList(
id="333174a2-ae74-4658-9e56-50fc90e086cf", name='test port 1')
child_port_2 = DimensionDataChildPortList(
id="311174a2-ae74-4658-9e56-50fc90e04444", name='test port 2')
child_ports = [child_port_1.id, child_port_2.id]
# Create IP Address List
success = self.driver.ex_edit_portlist(
ex_portlist=portlist,
description=description,
port_collection=port_collection,
child_portlist_list=child_ports
)
self.assertTrue(success)
def test_ex_edit_portlist_STR(self):
portlist_id = "484174a2-ae74-4658-9e56-50fc90e086cf"
description = "Test Description"
port_1 = DimensionDataPort(begin='8080')
port_2 = DimensionDataIpAddress(begin='8899',
end='9023')
port_collection = [port_1, port_2]
child_port_1 = DimensionDataChildPortList(
id="333174a2-ae74-4658-9e56-50fc90e086cf", name='test port 1')
child_port_2 = DimensionDataChildPortList(
id="311174a2-ae74-4658-9e56-50fc90e04444", name='test port 2')
child_ports_ids = [child_port_1.id, child_port_2.id]
# Create IP Address List
success = self.driver.ex_edit_portlist(
ex_portlist=portlist_id,
description=description,
port_collection=port_collection,
child_portlist_list=child_ports_ids
)
self.assertTrue(success)
def test_ex_delete_portlist(self):
net_domain = self.driver.ex_list_network_domains()[0]
portlist = self.driver.ex_list_portlist(net_domain)[0]
success = self.driver.ex_delete_portlist(
ex_portlist=portlist)
self.assertTrue(success)
def test_ex_delete_portlist_STR(self):
net_domain = self.driver.ex_list_network_domains()[0]
portlist = self.driver.ex_list_portlist(net_domain)[0]
success = self.driver.ex_delete_portlist(
ex_portlist=portlist.id)
self.assertTrue(success)
def test_import_image(self):
tag_dictionaries = {'tagkey1_name': 'dev test', 'tagkey2_name': None}
success = self.driver.import_image(
ovf_package_name='aTestGocToNGoc2_export2.mf',
name='Libcloud NGOCImage_New 2',
description='test',
cluster_id='QA1_N2_VMWARE_1-01',
is_guest_os_customization='false',
tagkey_name_value_dictionaries=tag_dictionaries)
self.assertTrue(success)
def test_import_image_error_too_many_choice(self):
tag_dictionaries = {'tagkey1_name': 'dev test', 'tagkey2_name': None}
with self.assertRaises(ValueError):
self.driver.import_image(
ovf_package_name='aTestGocToNGoc2_export2.mf',
name='Libcloud NGOCImage_New 2',
description='test',
cluster_id='QA1_N2_VMWARE_1-01',
datacenter_id='QA1_N1_VMWARE_1',
is_guest_os_customization='false',
tagkey_name_value_dictionaries=tag_dictionaries)
def test_import_image_error_missing_choice(self):
tag_dictionaries = {'tagkey1_name': 'dev test', 'tagkey2_name': None}
with self.assertRaises(ValueError):
self.driver.import_image(
ovf_package_name='aTestGocToNGoc2_export2.mf',
name='Libcloud NGOCImage_New 2',
description='test',
cluster_id=None,
datacenter_id=None,
is_guest_os_customization='false',
tagkey_name_value_dictionaries=tag_dictionaries)
def test_exchange_nic_vlans(self):
success = self.driver.ex_exchange_nic_vlans(
nic_id_1='a4b4b42b-ccb5-416f-b052-ce7cb7fdff12',
nic_id_2='b39d09b8-ea65-424a-8fa6-c6f5a98afc69')
self.assertTrue(success)
def test_change_nic_network_adapter(self):
success = self.driver.ex_change_nic_network_adapter(
nic_id='0c55c269-20a5-4fec-8054-22a245a48fe4',
network_adapter_name='E1000')
self.assertTrue(success)
def test_ex_create_node_uncustomized_mcp2_using_vlan(self):
# Get VLAN
vlan = self.driver.ex_get_vlan('0e56433f-d808-4669-821d-812769517ff8')
# Create node using vlan instead of private IPv4
node = self.driver.ex_create_node_uncustomized(
name='test_server_05',
image='fake_customer_image',
ex_network_domain='fakenetworkdomain',
ex_is_started=False,
ex_description=None,
ex_cluster_id=None,
ex_cpu_specification=None,
ex_memory_gb=None,
ex_primary_nic_private_ipv4=None,
ex_primary_nic_vlan=vlan,
ex_primary_nic_network_adapter=None,
ex_additional_nics=None,
ex_disks=None,
ex_tagid_value_pairs=None,
ex_tagname_value_pairs=None)
self.assertEqual(node.id, 'e75ead52-692f-4314-8725-c8a4f4d13a87')
def test_ex_create_node_uncustomized_mcp2_using_ipv4(self):
node = self.driver.ex_create_node_uncustomized(
name='test_server_05',
image='fake_customer_image',
ex_network_domain='fakenetworkdomain',
ex_is_started=False,
ex_description=None,
ex_cluster_id=None,
ex_cpu_specification=None,
ex_memory_gb=None,
ex_primary_nic_private_ipv4='10.0.0.1',
ex_primary_nic_vlan=None,
ex_primary_nic_network_adapter=None,
ex_additional_nics=None,
ex_disks=None,
ex_tagid_value_pairs=None,
ex_tagname_value_pairs=None)
self.assertEqual(node.id, 'e75ead52-692f-4314-8725-c8a4f4d13a87')
class InvalidRequestError(Exception):
def __init__(self, tag):
super(InvalidRequestError, self).__init__("Invalid Request - %s" % tag)
class DimensionDataMockHttp(MockHttp):
fixtures = ComputeFileFixtures('dimensiondata')
def _oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_report_usage(self, method, url, body, headers):
body = self.fixtures.load(
'summary_usage_report.csv'
)
return (httplib.BAD_REQUEST, body, {}, httplib.responses[httplib.OK])
def _oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_report_usageDetailed(self, method, url, body, headers):
body = self.fixtures.load(
'detailed_usage_report.csv'
)
return (httplib.BAD_REQUEST, body, {}, httplib.responses[httplib.OK])
def _oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_auditlog(self, method, url, body, headers):
body = self.fixtures.load(
'audit_log.csv'
)
return (httplib.BAD_REQUEST, body, {}, httplib.responses[httplib.OK])
def _oec_0_9_myaccount_UNAUTHORIZED(self, method, url, body, headers):
return (httplib.UNAUTHORIZED, "", {}, httplib.responses[httplib.UNAUTHORIZED])
def _oec_0_9_myaccount(self, method, url, body, headers):
body = self.fixtures.load('oec_0_9_myaccount.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _oec_0_9_myaccount_INPROGRESS(self, method, url, body, headers):
body = self.fixtures.load('oec_0_9_myaccount.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _oec_0_9_myaccount_PAGINATED(self, method, url, body, headers):
body = self.fixtures.load('oec_0_9_myaccount.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _oec_0_9_myaccount_ALLFILTERS(self, method, url, body, headers):
body = self.fixtures.load('oec_0_9_myaccount.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _oec_0_9_base_image(self, method, url, body, headers):
body = self.fixtures.load('oec_0_9_base_image.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _oec_0_9_base_imageWithDiskSpeed(self, method, url, body, headers):
body = self.fixtures.load('oec_0_9_base_imageWithDiskSpeed.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_deployed(self, method, url, body, headers):
body = self.fixtures.load(
'oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_deployed.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_pendingDeploy(self, method, url, body, headers):
body = self.fixtures.load(
'oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_pendingDeploy.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_datacenter(self, method, url, body, headers):
body = self.fixtures.load(
'oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_datacenter.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_11(self, method, url, body, headers):
body = None
action = url.split('?')[-1]
if action == 'restart':
body = self.fixtures.load(
'oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_11_restart.xml')
elif action == 'shutdown':
body = self.fixtures.load(
'oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_11_shutdown.xml')
elif action == 'delete':
body = self.fixtures.load(
'oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_11_delete.xml')
elif action == 'start':
body = self.fixtures.load(
'oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_11_start.xml')
elif action == 'poweroff':
body = self.fixtures.load(
'oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_11_poweroff.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_11_INPROGRESS(self, method, url, body, headers):
body = None
action = url.split('?')[-1]
if action == 'restart':
body = self.fixtures.load(
'oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_11_restart_INPROGRESS.xml')
elif action == 'shutdown':
body = self.fixtures.load(
'oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_11_shutdown_INPROGRESS.xml')
elif action == 'delete':
body = self.fixtures.load(
'oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_11_delete_INPROGRESS.xml')
elif action == 'start':
body = self.fixtures.load(
'oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_11_start_INPROGRESS.xml')
elif action == 'poweroff':
body = self.fixtures.load(
'oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_11_poweroff_INPROGRESS.xml')
return (httplib.BAD_REQUEST, body, {}, httplib.responses[httplib.OK])
def _oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server(self, method, url, body, headers):
body = self.fixtures.load(
'_oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_networkWithLocation(self, method, url, body, headers):
if method is "POST":
request = ET.fromstring(body)
if request.tag != "{http://oec.api.opsource.net/schemas/network}NewNetworkWithLocation":
raise InvalidRequestError(request.tag)
body = self.fixtures.load(
'oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_networkWithLocation.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_networkWithLocation_NA9(self, method, url, body, headers):
body = self.fixtures.load(
'oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_networkWithLocation.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_4bba37be_506f_11e3_b29c_001517c4643e(self, method,
url, body, headers):
body = self.fixtures.load(
'oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_4bba37be_506f_11e3_b29c_001517c4643e.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_e75ead52_692f_4314_8725_c8a4f4d13a87_disk_1_changeSize(self, method, url, body, headers):
body = self.fixtures.load(
'oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_e75ead52_692f_4314_8725_c8a4f4d13a87_disk_1_changeSize.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_e75ead52_692f_4314_8725_c8a4f4d13a87_disk_1_changeSpeed(self, method, url, body, headers):
body = self.fixtures.load(
'oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_e75ead52_692f_4314_8725_c8a4f4d13a87_disk_1_changeSpeed.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_e75ead52_692f_4314_8725_c8a4f4d13a87_disk_1(self, method, url, body, headers):
action = url.split('?')[-1]
if action == 'delete':
body = self.fixtures.load(
'oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_e75ead52_692f_4314_8725_c8a4f4d13a87_disk_1.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_e75ead52_692f_4314_8725_c8a4f4d13a87(self, method, url, body, headers):
if method == 'GET':
body = self.fixtures.load(
'oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_e75ead52_692f_4314_8725_c8a4f4d13a87.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
if method == 'POST':
body = self.fixtures.load(
'oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_e75ead52_692f_4314_8725_c8a4f4d13a87_POST.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_antiAffinityRule(self, method, url, body, headers):
body = self.fixtures.load(
'oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_antiAffinityRule_create.xml'
)
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_antiAffinityRule_FAIL_EXISTING(self, method, url, body, headers):
body = self.fixtures.load(
'oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_antiAffinityRule_create_FAIL.xml'
)
return (httplib.BAD_REQUEST, body, {}, httplib.responses[httplib.OK])
def _oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_antiAffinityRule_07e3621a_a920_4a9a_943c_d8021f27f418(self, method, url, body, headers):
body = self.fixtures.load(
'oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_antiAffinityRule_delete.xml'
)
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_antiAffinityRule_07e3621a_a920_4a9a_943c_d8021f27f418_FAIL(self, method, url, body, headers):
body = self.fixtures.load(
'oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_antiAffinityRule_delete_FAIL.xml'
)
return (httplib.BAD_REQUEST, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server(self, method, url, body, headers):
body = self.fixtures.load(
'server.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_deleteServer(self, method, url, body, headers):
request = ET.fromstring(body)
if request.tag != "{urn:didata.com:api:cloud:types}deleteServer":
raise InvalidRequestError(request.tag)
body = self.fixtures.load(
'server_deleteServer.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_deleteServer_INPROGRESS(self, method, url, body, headers):
request = ET.fromstring(body)
if request.tag != "{urn:didata.com:api:cloud:types}deleteServer":
raise InvalidRequestError(request.tag)
body = self.fixtures.load(
'server_deleteServer_RESOURCEBUSY.xml')
return (httplib.BAD_REQUEST, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_rebootServer(self, method, url, body, headers):
request = ET.fromstring(body)
if request.tag != "{urn:didata.com:api:cloud:types}rebootServer":
raise InvalidRequestError(request.tag)
body = self.fixtures.load(
'server_rebootServer.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_rebootServer_INPROGRESS(self, method, url, body, headers):
request = ET.fromstring(body)
if request.tag != "{urn:didata.com:api:cloud:types}rebootServer":
raise InvalidRequestError(request.tag)
body = self.fixtures.load(
'server_rebootServer_RESOURCEBUSY.xml')
return (httplib.BAD_REQUEST, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_server(self, method, url, body, headers):
if url.endswith('datacenterId=NA3'):
body = self.fixtures.load(
'2.4/server_server_NA3.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
body = self.fixtures.load(
'2.4/server_server.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_server_PAGESIZE50(self, method, url, body, headers):
if not url.endswith('pageSize=50'):
raise ValueError("pageSize is not set as expected")
body = self.fixtures.load(
'2.4/server_server.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_server_EMPTY(self, method, url, body, headers):
body = self.fixtures.load(
'server_server_paginated_empty.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_server_PAGED_THEN_EMPTY(self, method, url, body, headers):
if 'pageNumber=2' in url:
body = self.fixtures.load(
'server_server_paginated_empty.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
else:
body = self.fixtures.load(
'2.4/server_server_paginated.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_server_PAGINATED(self, method, url, body, headers):
if 'pageNumber=2' in url:
body = self.fixtures.load(
'2.4/server_server.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
else:
body = self.fixtures.load(
'2.4/server_server_paginated.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_server_PAGINATEDEMPTY(self, method, url, body, headers):
body = self.fixtures.load(
'server_server_paginated_empty.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_server_ALLFILTERS(self, method, url, body, headers):
(_, params) = url.split('?')
parameters = params.split('&')
for parameter in parameters:
(key, value) = parameter.split('=')
if key == 'datacenterId':
assert value == 'fake_loc'
elif key == 'networkId':
assert value == 'fake_network'
elif key == 'networkDomainId':
assert value == 'fake_network_domain'
elif key == 'vlanId':
assert value == 'fake_vlan'
elif key == 'ipv6':
assert value == 'fake_ipv6'
elif key == 'privateIpv4':
assert value == 'fake_ipv4'
elif key == 'name':
assert value == 'fake_name'
elif key == 'state':
assert value == 'fake_state'
elif key == 'started':
assert value == 'True'
elif key == 'deployed':
assert value == 'True'
elif key == 'sourceImageId':
assert value == 'fake_image'
else:
raise ValueError("Could not find in url parameters {0}:{1}".format(key, value))
body = self.fixtures.load(
'2.4/server_server.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_antiAffinityRule(self, method, url, body, headers):
body = self.fixtures.load(
'server_antiAffinityRule_list.xml'
)
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_antiAffinityRule_ALLFILTERS(self, method, url, body, headers):
(_, params) = url.split('?')
parameters = params.split('&')
for parameter in parameters:
(key, value) = parameter.split('=')
if key == 'id':
assert value == 'FAKE_ID'
elif key == 'state':
assert value == 'FAKE_STATE'
elif key == 'pageSize':
assert value == '250'
elif key == 'networkDomainId':
pass
else:
raise ValueError("Could not find in url parameters {0}:{1}".format(key, value))
body = self.fixtures.load(
'server_antiAffinityRule_list.xml'
)
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_antiAffinityRule_PAGINATED(self, method, url, body, headers):
if 'pageNumber=2' in url:
body = self.fixtures.load(
'server_antiAffinityRule_list.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
else:
body = self.fixtures.load(
'server_antiAffinityRule_list_PAGINATED.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_infrastructure_datacenter(self, method, url, body, headers):
if url.endswith('id=NA9'):
body = self.fixtures.load(
'infrastructure_datacenter_NA9.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
body = self.fixtures.load(
'infrastructure_datacenter.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_infrastructure_datacenter_ALLFILTERS(self, method, url, body, headers):
if url.endswith('id=NA9'):
body = self.fixtures.load(
'infrastructure_datacenter_NA9.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
body = self.fixtures.load(
'infrastructure_datacenter.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_updateVmwareTools(self, method, url, body, headers):
request = ET.fromstring(body)
if request.tag != "{urn:didata.com:api:cloud:types}updateVmwareTools":
raise InvalidRequestError(request.tag)
body = self.fixtures.load(
'server_updateVmwareTools.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_startServer(self, method, url, body, headers):
request = ET.fromstring(body)
if request.tag != "{urn:didata.com:api:cloud:types}startServer":
raise InvalidRequestError(request.tag)
body = self.fixtures.load(
'server_startServer.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_startServer_INPROGRESS(self, method, url, body, headers):
request = ET.fromstring(body)
if request.tag != "{urn:didata.com:api:cloud:types}startServer":
raise InvalidRequestError(request.tag)
body = self.fixtures.load(
'server_startServer_INPROGRESS.xml')
return (httplib.BAD_REQUEST, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_shutdownServer(self, method, url, body, headers):
request = ET.fromstring(body)
if request.tag != "{urn:didata.com:api:cloud:types}shutdownServer":
raise InvalidRequestError(request.tag)
body = self.fixtures.load(
'server_shutdownServer.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_shutdownServer_INPROGRESS(self, method, url, body, headers):
request = ET.fromstring(body)
if request.tag != "{urn:didata.com:api:cloud:types}shutdownServer":
raise InvalidRequestError(request.tag)
body = self.fixtures.load(
'server_shutdownServer_INPROGRESS.xml')
return (httplib.BAD_REQUEST, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_resetServer(self, method, url, body, headers):
request = ET.fromstring(body)
if request.tag != "{urn:didata.com:api:cloud:types}resetServer":
raise InvalidRequestError(request.tag)
body = self.fixtures.load(
'server_resetServer.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_powerOffServer(self, method, url, body, headers):
request = ET.fromstring(body)
if request.tag != "{urn:didata.com:api:cloud:types}powerOffServer":
raise InvalidRequestError(request.tag)
body = self.fixtures.load(
'server_powerOffServer.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_powerOffServer_INPROGRESS(self, method, url, body, headers):
request = ET.fromstring(body)
if request.tag != "{urn:didata.com:api:cloud:types}powerOffServer":
raise InvalidRequestError(request.tag)
body = self.fixtures.load(
'server_powerOffServer_INPROGRESS.xml')
return (httplib.BAD_REQUEST, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_server_11_INPROGRESS(
self, method, url, body, headers):
body = self.fixtures.load('2.4/server_GetServer.xml')
return (httplib.BAD_REQUEST, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_networkDomain(self, method, url, body, headers):
body = self.fixtures.load(
'network_networkDomain.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_networkDomain_ALLFILTERS(self, method, url, body, headers):
(_, params) = url.split('?')
parameters = params.split('&')
for parameter in parameters:
(key, value) = parameter.split('=')
if key == 'datacenterId':
assert value == 'fake_location'
elif key == 'type':
assert value == 'fake_plan'
elif key == 'name':
assert value == 'fake_name'
elif key == 'state':
assert value == 'fake_state'
else:
raise ValueError("Could not find in url parameters {0}:{1}".format(key, value))
body = self.fixtures.load(
'network_networkDomain.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_vlan(self, method, url, body, headers):
body = self.fixtures.load(
'network_vlan.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_vlan_ALLFILTERS(self, method, url, body, headers):
(_, params) = url.split('?')
parameters = params.split('&')
for parameter in parameters:
(key, value) = parameter.split('=')
if key == 'datacenterId':
assert value == 'fake_location'
elif key == 'networkDomainId':
assert value == 'fake_network_domain'
elif key == 'ipv6Address':
assert value == 'fake_ipv6'
elif key == 'privateIpv4Address':
assert value == 'fake_ipv4'
elif key == 'name':
assert value == 'fake_name'
elif key == 'state':
assert value == 'fake_state'
else:
raise ValueError("Could not find in url parameters {0}:{1}".format(key, value))
body = self.fixtures.load(
'network_vlan.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_deployServer(self, method, url, body, headers):
request = ET.fromstring(body)
if request.tag != "{urn:didata.com:api:cloud:types}deployServer":
raise InvalidRequestError(request.tag)
# Make sure the we either have a network tag with an IP or networkId
# Or Network info with a primary nic that has privateip or vlanid
network = request.find(fixxpath('network', TYPES_URN))
network_info = request.find(fixxpath('networkInfo', TYPES_URN))
if network is not None:
if network_info is not None:
raise InvalidRequestError("Request has both MCP1 and MCP2 values")
ipv4 = findtext(network, 'privateIpv4', TYPES_URN)
networkId = findtext(network, 'networkId', TYPES_URN)
if ipv4 is None and networkId is None:
raise InvalidRequestError('Invalid request MCP1 requests need privateIpv4 or networkId')
elif network_info is not None:
if network is not None:
raise InvalidRequestError("Request has both MCP1 and MCP2 values")
primary_nic = network_info.find(fixxpath('primaryNic', TYPES_URN))
ipv4 = findtext(primary_nic, 'privateIpv4', TYPES_URN)
vlanId = findtext(primary_nic, 'vlanId', TYPES_URN)
if ipv4 is None and vlanId is None:
raise InvalidRequestError('Invalid request MCP2 requests need privateIpv4 or vlanId')
else:
raise InvalidRequestError('Invalid request, does not have network or network_info in XML')
body = self.fixtures.load(
'server_deployServer.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_server_e75ead52_692f_4314_8725_c8a4f4d13a87(self, method, url, body, headers):
body = self.fixtures.load(
'2.4/server_server_e75ead52_692f_4314_8725_c8a4f4d13a87.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_deployNetworkDomain(self, method, url, body, headers):
request = ET.fromstring(body)
if request.tag != "{urn:didata.com:api:cloud:types}deployNetworkDomain":
raise InvalidRequestError(request.tag)
body = self.fixtures.load(
'network_deployNetworkDomain.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_networkDomain_8cdfd607_f429_4df6_9352_162cfc0891be(self, method, url, body, headers):
body = self.fixtures.load(
'network_networkDomain_8cdfd607_f429_4df6_9352_162cfc0891be.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_networkDomain_8cdfd607_f429_4df6_9352_162cfc0891be_ALLFILTERS(self, method, url, body, headers):
body = self.fixtures.load(
'network_networkDomain_8cdfd607_f429_4df6_9352_162cfc0891be.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_editNetworkDomain(self, method, url, body, headers):
request = ET.fromstring(body)
if request.tag != "{urn:didata.com:api:cloud:types}editNetworkDomain":
raise InvalidRequestError(request.tag)
body = self.fixtures.load(
'network_editNetworkDomain.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_deleteNetworkDomain(self, method, url, body, headers):
request = ET.fromstring(body)
if request.tag != "{urn:didata.com:api:cloud:types}deleteNetworkDomain":
raise InvalidRequestError(request.tag)
body = self.fixtures.load(
'network_deleteNetworkDomain.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_deployVlan(self, method, url, body, headers):
request = ET.fromstring(body)
if request.tag != "{urn:didata.com:api:cloud:types}deployVlan":
raise InvalidRequestError(request.tag)
body = self.fixtures.load(
'network_deployVlan.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_vlan_0e56433f_d808_4669_821d_812769517ff8(self, method, url, body, headers):
body = self.fixtures.load(
'network_vlan_0e56433f_d808_4669_821d_812769517ff8.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_editVlan(self, method, url, body, headers):
request = ET.fromstring(body)
if request.tag != "{urn:didata.com:api:cloud:types}editVlan":
raise InvalidRequestError(request.tag)
body = self.fixtures.load(
'network_editVlan.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_deleteVlan(self, method, url, body, headers):
request = ET.fromstring(body)
if request.tag != "{urn:didata.com:api:cloud:types}deleteVlan":
raise InvalidRequestError(request.tag)
body = self.fixtures.load(
'network_deleteVlan.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_expandVlan(self, method, url, body, headers):
request = ET.fromstring(body)
if request.tag != "{urn:didata.com:api:cloud:types}expandVlan":
raise InvalidRequestError(request.tag)
body = self.fixtures.load(
'network_expandVlan.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_addPublicIpBlock(self, method, url, body, headers):
request = ET.fromstring(body)
if request.tag != "{urn:didata.com:api:cloud:types}addPublicIpBlock":
raise InvalidRequestError(request.tag)
body = self.fixtures.load(
'network_addPublicIpBlock.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_publicIpBlock_4487241a_f0ca_11e3_9315_d4bed9b167ba(self, method, url, body, headers):
body = self.fixtures.load(
'network_publicIpBlock_4487241a_f0ca_11e3_9315_d4bed9b167ba.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_publicIpBlock(self, method, url, body, headers):
body = self.fixtures.load(
'network_publicIpBlock.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_publicIpBlock_9945dc4a_bdce_11e4_8c14_b8ca3a5d9ef8(self, method, url, body, headers):
body = self.fixtures.load(
'network_publicIpBlock_9945dc4a_bdce_11e4_8c14_b8ca3a5d9ef8.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_removePublicIpBlock(self, method, url, body, headers):
request = ET.fromstring(body)
if request.tag != "{urn:didata.com:api:cloud:types}removePublicIpBlock":
raise InvalidRequestError(request.tag)
body = self.fixtures.load(
'network_removePublicIpBlock.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_firewallRule(self, method, url, body, headers):
body = self.fixtures.load(
'network_firewallRule.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_createFirewallRule(self, method, url, body, headers):
request = ET.fromstring(body)
if request.tag != "{urn:didata.com:api:cloud:types}createFirewallRule":
raise InvalidRequestError(request.tag)
body = self.fixtures.load(
'network_createFirewallRule.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_firewallRule_d0a20f59_77b9_4f28_a63b_e58496b73a6c(self, method, url, body, headers):
body = self.fixtures.load(
'network_firewallRule_d0a20f59_77b9_4f28_a63b_e58496b73a6c.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_editFirewallRule(self, method, url, body, headers):
request = ET.fromstring(body)
if request.tag != "{urn:didata.com:api:cloud:types}editFirewallRule":
raise InvalidRequestError(request.tag)
body = self.fixtures.load(
'network_editFirewallRule.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_deleteFirewallRule(self, method, url, body, headers):
request = ET.fromstring(body)
if request.tag != "{urn:didata.com:api:cloud:types}deleteFirewallRule":
raise InvalidRequestError(request.tag)
body = self.fixtures.load(
'network_deleteFirewallRule.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_createNatRule(self, method, url, body, headers):
request = ET.fromstring(body)
if request.tag != "{urn:didata.com:api:cloud:types}createNatRule":
raise InvalidRequestError(request.tag)
body = self.fixtures.load(
'network_createNatRule.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_natRule(self, method, url, body, headers):
body = self.fixtures.load(
'network_natRule.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_natRule_2187a636_7ebb_49a1_a2ff_5d617f496dce(self, method, url, body, headers):
body = self.fixtures.load(
'network_natRule_2187a636_7ebb_49a1_a2ff_5d617f496dce.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_deleteNatRule(self, method, url, body, headers):
request = ET.fromstring(body)
if request.tag != "{urn:didata.com:api:cloud:types}deleteNatRule":
raise InvalidRequestError(request.tag)
body = self.fixtures.load(
'network_deleteNatRule.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_addNic(self, method, url, body, headers):
request = ET.fromstring(body)
if request.tag != "{urn:didata.com:api:cloud:types}addNic":
raise InvalidRequestError(request.tag)
body = self.fixtures.load(
'server_addNic.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_removeNic(self, method, url, body, headers):
request = ET.fromstring(body)
if request.tag != "{urn:didata.com:api:cloud:types}removeNic":
raise InvalidRequestError(request.tag)
body = self.fixtures.load(
'server_removeNic.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_disableServerMonitoring(self, method, url, body, headers):
request = ET.fromstring(body)
if request.tag != "{urn:didata.com:api:cloud:types}disableServerMonitoring":
raise InvalidRequestError(request.tag)
body = self.fixtures.load(
'server_disableServerMonitoring.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_enableServerMonitoring(self, method, url, body, headers):
request = ET.fromstring(body)
if request.tag != "{urn:didata.com:api:cloud:types}enableServerMonitoring":
raise InvalidRequestError(request.tag)
body = self.fixtures.load(
'server_enableServerMonitoring.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_changeServerMonitoringPlan(self, method, url, body, headers):
request = ET.fromstring(body)
if request.tag != "{urn:didata.com:api:cloud:types}changeServerMonitoringPlan":
raise InvalidRequestError(request.tag)
body = self.fixtures.load(
'server_changeServerMonitoringPlan.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_image_osImage(self, method, url, body, headers):
body = self.fixtures.load(
'2.4/image_osImage.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_image_osImage_c14b1a46_2428_44c1_9c1a_b20e6418d08c(self, method, url, body, headers):
body = self.fixtures.load(
'2.4/image_osImage_c14b1a46_2428_44c1_9c1a_b20e6418d08c.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_image_osImage_6b4fb0c7_a57b_4f58_b59c_9958f94f971a(self, method, url, body, headers):
body = self.fixtures.load(
'2.4/image_osImage_6b4fb0c7_a57b_4f58_b59c_9958f94f971a.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_image_osImage_5234e5c7_01de_4411_8b6e_baeb8d91cf5d(self, method, url, body, headers):
body = self.fixtures.load(
'image_osImage_BAD_REQUEST.xml')
return (httplib.BAD_REQUEST, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_image_osImage_2ffa36c8_1848_49eb_b4fa_9d908775f68c(self, method, url, body, headers):
body = self.fixtures.load(
'image_osImage_BAD_REQUEST.xml')
return (httplib.BAD_REQUEST, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_image_osImage_FAKE_IMAGE_ID(self, method, url, body, headers):
body = self.fixtures.load(
'image_osImage_BAD_REQUEST.xml')
return (httplib.BAD_REQUEST, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_image_customerImage(self, method, url, body, headers):
body = self.fixtures.load(
'2.4/image_customerImage.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_image_customerImage_5234e5c7_01de_4411_8b6e_baeb8d91cf5d(self, method, url, body, headers):
body = self.fixtures.load(
'2.4/image_customerImage_5234e5c7_01de_4411_8b6e_baeb8d91cf5d.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_image_customerImage_2ffa36c8_1848_49eb_b4fa_9d908775f68c(self, method, url, body, headers):
body = self.fixtures.load(
'2.4/image_customerImage_2ffa36c8_1848_49eb_b4fa_9d908775f68c.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_image_customerImage_FAKE_IMAGE_ID(self, method, url, body, headers):
body = self.fixtures.load(
'image_customerImage_BAD_REQUEST.xml')
return (httplib.BAD_REQUEST, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_reconfigureServer(self, method, url, body, headers):
request = ET.fromstring(body)
if request.tag != "{urn:didata.com:api:cloud:types}reconfigureServer":
raise InvalidRequestError(request.tag)
body = self.fixtures.load(
'server_reconfigureServer.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_cleanServer(self, method, url, body, headers):
body = self.fixtures.load(
'server_cleanServer.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_addDisk(self, method, url, body, headers):
body = self.fixtures.load(
'server_addDisk.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_removeDisk(self, method, url, body, headers):
body = self.fixtures.load(
'server_removeDisk.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_createTagKey(self, method, url, body, headers):
request = ET.fromstring(body)
if request.tag != "{urn:didata.com:api:cloud:types}createTagKey":
raise InvalidRequestError(request.tag)
name = findtext(request, 'name', TYPES_URN)
description = findtext(request, 'description', TYPES_URN)
value_required = findtext(request, 'valueRequired', TYPES_URN)
display_on_report = findtext(request, 'displayOnReport', TYPES_URN)
if name is None:
raise ValueError("Name must have a value in the request")
if description is not None:
raise ValueError("Default description for a tag should be blank")
if value_required is None or value_required != 'true':
raise ValueError("Default valueRequired should be true")
if display_on_report is None or display_on_report != 'true':
raise ValueError("Default displayOnReport should be true")
body = self.fixtures.load(
'tag_createTagKey.xml'
)
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_createTagKey_ALLPARAMS(self, method, url, body, headers):
request = ET.fromstring(body)
if request.tag != "{urn:didata.com:api:cloud:types}createTagKey":
raise InvalidRequestError(request.tag)
name = findtext(request, 'name', TYPES_URN)
description = findtext(request, 'description', TYPES_URN)
value_required = findtext(request, 'valueRequired', TYPES_URN)
display_on_report = findtext(request, 'displayOnReport', TYPES_URN)
if name is None:
raise ValueError("Name must have a value in the request")
if description is None:
raise ValueError("Description should have a value")
if value_required is None or value_required != 'false':
raise ValueError("valueRequired should be false")
if display_on_report is None or display_on_report != 'false':
raise ValueError("displayOnReport should be false")
body = self.fixtures.load(
'tag_createTagKey.xml'
)
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_createTagKey_BADREQUEST(self, method, url, body, headers):
body = self.fixtures.load(
'tag_createTagKey_BADREQUEST.xml')
return (httplib.BAD_REQUEST, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_tagKey(self, method, url, body, headers):
body = self.fixtures.load(
'tag_tagKey_list.xml'
)
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_tagKey_SINGLE(self, method, url, body, headers):
body = self.fixtures.load(
'tag_tagKey_list_SINGLE.xml'
)
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_tagKey_ALLFILTERS(self, method, url, body, headers):
(_, params) = url.split('?')
parameters = params.split('&')
for parameter in parameters:
(key, value) = parameter.split('=')
if key == 'id':
assert value == 'fake_id'
elif key == 'name':
assert value == 'fake_name'
elif key == 'valueRequired':
assert value == 'false'
elif key == 'displayOnReport':
assert value == 'false'
elif key == 'pageSize':
assert value == '250'
else:
raise ValueError("Could not find in url parameters {0}:{1}".format(key, value))
body = self.fixtures.load(
'tag_tagKey_list.xml'
)
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_tagKey_d047c609_93d7_4bc5_8fc9_732c85840075(self, method, url, body, headers):
body = self.fixtures.load(
'tag_tagKey_5ab77f5f_5aa9_426f_8459_4eab34e03d54.xml'
)
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_tagKey_d047c609_93d7_4bc5_8fc9_732c85840075_NOEXIST(self, method, url, body, headers):
body = self.fixtures.load(
'tag_tagKey_5ab77f5f_5aa9_426f_8459_4eab34e03d54_BADREQUEST.xml'
)
return (httplib.BAD_REQUEST, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_editTagKey_NAME(self, method, url, body, headers):
request = ET.fromstring(body)
if request.tag != "{urn:didata.com:api:cloud:types}editTagKey":
raise InvalidRequestError(request.tag)
name = findtext(request, 'name', TYPES_URN)
description = findtext(request, 'description', TYPES_URN)
value_required = findtext(request, 'valueRequired', TYPES_URN)
display_on_report = findtext(request, 'displayOnReport', TYPES_URN)
if name is None:
raise ValueError("Name must have a value in the request")
if description is not None:
raise ValueError("Description should be empty")
if value_required is not None:
raise ValueError("valueRequired should be empty")
if display_on_report is not None:
raise ValueError("displayOnReport should be empty")
body = self.fixtures.load(
'tag_editTagKey.xml'
)
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_editTagKey_NOTNAME(self, method, url, body, headers):
request = ET.fromstring(body)
if request.tag != "{urn:didata.com:api:cloud:types}editTagKey":
raise InvalidRequestError(request.tag)
name = findtext(request, 'name', TYPES_URN)
description = findtext(request, 'description', TYPES_URN)
value_required = findtext(request, 'valueRequired', TYPES_URN)
display_on_report = findtext(request, 'displayOnReport', TYPES_URN)
if name is not None:
raise ValueError("Name should be empty")
if description is None:
raise ValueError("Description should not be empty")
if value_required is None:
raise ValueError("valueRequired should not be empty")
if display_on_report is None:
raise ValueError("displayOnReport should not be empty")
body = self.fixtures.load(
'tag_editTagKey.xml'
)
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_editTagKey_NOCHANGE(self, method, url, body, headers):
body = self.fixtures.load(
'tag_editTagKey_BADREQUEST.xml'
)
return (httplib.BAD_REQUEST, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_deleteTagKey(self, method, url, body, headers):
request = ET.fromstring(body)
if request.tag != "{urn:didata.com:api:cloud:types}deleteTagKey":
raise InvalidRequestError(request.tag)
body = self.fixtures.load(
'tag_deleteTagKey.xml'
)
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_deleteTagKey_NOEXIST(self, method, url, body, headers):
body = self.fixtures.load(
'tag_deleteTagKey_BADREQUEST.xml'
)
return (httplib.BAD_REQUEST, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_applyTags(self, method, url, body, headers):
request = ET.fromstring(body)
if request.tag != "{urn:didata.com:api:cloud:types}applyTags":
raise InvalidRequestError(request.tag)
asset_type = findtext(request, 'assetType', TYPES_URN)
asset_id = findtext(request, 'assetId', TYPES_URN)
tag = request.find(fixxpath('tag', TYPES_URN))
tag_key_name = findtext(tag, 'tagKeyName', TYPES_URN)
value = findtext(tag, 'value', TYPES_URN)
if asset_type is None:
raise ValueError("assetType should not be empty")
if asset_id is None:
raise ValueError("assetId should not be empty")
if tag_key_name is None:
raise ValueError("tagKeyName should not be empty")
if value is None:
raise ValueError("value should not be empty")
body = self.fixtures.load(
'tag_applyTags.xml'
)
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_applyTags_NOVALUE(self, method, url, body, headers):
request = ET.fromstring(body)
if request.tag != "{urn:didata.com:api:cloud:types}applyTags":
raise InvalidRequestError(request.tag)
asset_type = findtext(request, 'assetType', TYPES_URN)
asset_id = findtext(request, 'assetId', TYPES_URN)
tag = request.find(fixxpath('tag', TYPES_URN))
tag_key_name = findtext(tag, 'tagKeyName', TYPES_URN)
value = findtext(tag, 'value', TYPES_URN)
if asset_type is None:
raise ValueError("assetType should not be empty")
if asset_id is None:
raise ValueError("assetId should not be empty")
if tag_key_name is None:
raise ValueError("tagKeyName should not be empty")
if value is not None:
raise ValueError("value should be empty")
body = self.fixtures.load(
'tag_applyTags.xml'
)
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_applyTags_NOTAGKEY(self, method, url, body, headers):
body = self.fixtures.load(
'tag_applyTags_BADREQUEST.xml'
)
return (httplib.BAD_REQUEST, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_removeTags(self, method, url, body, headers):
request = ET.fromstring(body)
if request.tag != "{urn:didata.com:api:cloud:types}removeTags":
raise InvalidRequestError(request.tag)
body = self.fixtures.load(
'tag_removeTag.xml'
)
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_removeTags_NOTAG(self, method, url, body, headers):
body = self.fixtures.load(
'tag_removeTag_BADREQUEST.xml'
)
return (httplib.BAD_REQUEST, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_tag(self, method, url, body, headers):
body = self.fixtures.load(
'tag_tag_list.xml'
)
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_tag_ALLPARAMS(self, method, url, body, headers):
(_, params) = url.split('?')
parameters = params.split('&')
for parameter in parameters:
(key, value) = parameter.split('=')
if key == 'assetId':
assert value == 'fake_asset_id'
elif key == 'assetType':
assert value == 'fake_asset_type'
elif key == 'valueRequired':
assert value == 'false'
elif key == 'displayOnReport':
assert value == 'false'
elif key == 'pageSize':
assert value == '250'
elif key == 'datacenterId':
assert value == 'fake_location'
elif key == 'value':
assert value == 'fake_value'
elif key == 'tagKeyName':
assert value == 'fake_tag_key_name'
elif key == 'tagKeyId':
assert value == 'fake_tag_key_id'
else:
raise ValueError("Could not find in url parameters {0}:{1}".format(key, value))
body = self.fixtures.load(
'tag_tag_list.xml'
)
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_ipAddressList(
self, method, url, body, headers):
body = self.fixtures.load('ip_address_lists.xml')
return httplib.OK, body, {}, httplib.responses[httplib.OK]
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_ipAddressList_FILTERBYNAME(
self, method, url, body, headers):
body = self.fixtures.load('ip_address_lists_FILTERBYNAME.xml')
return httplib.OK, body, {}, httplib.responses[httplib.OK]
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_createIpAddressList(
self, method, url, body, headers):
request = ET.fromstring(body)
if request.tag != "{urn:didata.com:api:cloud:types}" \
"createIpAddressList":
raise InvalidRequestError(request.tag)
net_domain = findtext(request, 'networkDomainId', TYPES_URN)
if net_domain is None:
raise ValueError("Network Domain should not be empty")
name = findtext(request, 'name', TYPES_URN)
if name is None:
raise ValueError("Name should not be empty")
ip_version = findtext(request, 'ipVersion', TYPES_URN)
if ip_version is None:
raise ValueError("IP Version should not be empty")
ip_address_col_required = findall(request, 'ipAddress', TYPES_URN)
child_ip_address_required = findall(request, 'childIpAddressListId',
TYPES_URN)
if 0 == len(ip_address_col_required) and \
0 == len(child_ip_address_required):
raise ValueError("At least one ipAddress element or "
"one childIpAddressListId element must be "
"provided.")
if ip_address_col_required[0].get('begin') is None:
raise ValueError("IP Address should not be empty")
body = self.fixtures.load(
'ip_address_list_create.xml'
)
return httplib.OK, body, {}, httplib.responses[httplib.OK]
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_editIpAddressList(
self, method, url, body, headers):
request = ET.fromstring(body)
if request.tag != "{urn:didata.com:api:cloud:types}" \
"editIpAddressList":
raise InvalidRequestError(request.tag)
ip_address_list = request.get('id')
if ip_address_list is None:
raise ValueError("IpAddressList ID should not be empty")
name = findtext(request, 'name', TYPES_URN)
if name is not None:
raise ValueError("Name should not exists in request")
ip_version = findtext(request, 'ipVersion', TYPES_URN)
if ip_version is not None:
raise ValueError("IP Version should not exists in request")
ip_address_col_required = findall(request, 'ipAddress', TYPES_URN)
child_ip_address_required = findall(request, 'childIpAddressListId',
TYPES_URN)
if 0 == len(ip_address_col_required) and \
0 == len(child_ip_address_required):
raise ValueError("At least one ipAddress element or "
"one childIpAddressListId element must be "
"provided.")
if ip_address_col_required[0].get('begin') is None:
raise ValueError("IP Address should not be empty")
body = self.fixtures.load(
'ip_address_list_edit.xml'
)
return httplib.OK, body, {}, httplib.responses[httplib.OK]
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_deleteIpAddressList(
self, method, url, body, headers):
request = ET.fromstring(body)
if request.tag != "{urn:didata.com:api:cloud:types}" \
"deleteIpAddressList":
raise InvalidRequestError(request.tag)
ip_address_list = request.get('id')
if ip_address_list is None:
raise ValueError("IpAddressList ID should not be empty")
body = self.fixtures.load(
'ip_address_list_delete.xml'
)
return httplib.OK, body, {}, httplib.responses[httplib.OK]
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_portList(
self, method, url, body, headers):
body = self.fixtures.load(
'port_list_lists.xml'
)
return httplib.OK, body, {}, httplib.responses[httplib.OK]
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_portList_c8c92ea3_2da8_4d51_8153_f39bec794d69(
self, method, url, body, headers):
body = self.fixtures.load(
'port_list_get.xml'
)
return httplib.OK, body, {}, httplib.responses[httplib.OK]
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_createPortList(
self, method, url, body, headers):
request = ET.fromstring(body)
if request.tag != "{urn:didata.com:api:cloud:types}" \
"createPortList":
raise InvalidRequestError(request.tag)
net_domain = findtext(request, 'networkDomainId', TYPES_URN)
if net_domain is None:
raise ValueError("Network Domain should not be empty")
ports_required = findall(request, 'port', TYPES_URN)
child_port_list_required = findall(request, 'childPortListId',
TYPES_URN)
if 0 == len(ports_required) and \
0 == len(child_port_list_required):
raise ValueError("At least one port element or one "
"childPortListId element must be provided")
if ports_required[0].get('begin') is None:
raise ValueError("PORT begin value should not be empty")
body = self.fixtures.load(
'port_list_create.xml'
)
return httplib.OK, body, {}, httplib.responses[httplib.OK]
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_editPortList(
self, method, url, body, headers):
request = ET.fromstring(body)
if request.tag != "{urn:didata.com:api:cloud:types}" \
"editPortList":
raise InvalidRequestError(request.tag)
ports_required = findall(request, 'port', TYPES_URN)
child_port_list_required = findall(request, 'childPortListId',
TYPES_URN)
if 0 == len(ports_required) and \
0 == len(child_port_list_required):
raise ValueError("At least one port element or one "
"childPortListId element must be provided")
if ports_required[0].get('begin') is None:
raise ValueError("PORT begin value should not be empty")
body = self.fixtures.load(
'port_list_edit.xml'
)
return httplib.OK, body, {}, httplib.responses[httplib.OK]
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_deletePortList(
self, method, url, body, headers):
request = ET.fromstring(body)
if request.tag != "{urn:didata.com:api:cloud:types}" \
"deletePortList":
raise InvalidRequestError(request.tag)
port_list = request.get('id')
if port_list is None:
raise ValueError("Port List ID should not be empty")
body = self.fixtures.load(
'ip_address_list_delete.xml'
)
return httplib.OK, body, {}, httplib.responses[httplib.OK]
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_cloneServer(
self, method, url, body, headers):
body = self.fixtures.load(
'2.4/server_clone_response.xml'
)
return httplib.OK, body, {}, httplib.responses[httplib.OK]
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_image_importImage(
self, method, url, body, headers):
body = self.fixtures.load(
'2.4/import_image_response.xml'
)
return httplib.OK, body, {}, httplib.responses[httplib.OK]
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_exchangeNicVlans(
self, method, url, body, headers):
body = self.fixtures.load(
'2.4/exchange_nic_vlans_response.xml'
)
return httplib.OK, body, {}, httplib.responses[httplib.OK]
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_changeNetworkAdapter(
self, method, url, body, headers):
body = self.fixtures.load(
'2.4/change_nic_networkadapter_response.xml'
)
return httplib.OK, body, {}, httplib.responses[httplib.OK]
def _caas_2_4_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_deployUncustomizedServer(
self, method, url, body, headers):
body = self.fixtures.load(
'2.4/deploy_customised_server.xml'
)
return httplib.OK, body, {}, httplib.responses[httplib.OK]
if __name__ == '__main__':
sys.exit(unittest.main())
| apache-2.0 |
kenshay/ImageScripter | ProgramData/SystemFiles/Python/Lib/pydoc.py | 10 | 95607 | #!/usr/bin/env python
# -*- coding: latin-1 -*-
"""Generate Python documentation in HTML or text for interactive use.
In the Python interpreter, do "from pydoc import help" to provide online
help. Calling help(thing) on a Python object documents the object.
Or, at the shell command line outside of Python:
Run "pydoc <name>" to show documentation on something. <name> may be
the name of a function, module, package, or a dotted reference to a
class or function within a module or module in a package. If the
argument contains a path segment delimiter (e.g. slash on Unix,
backslash on Windows) it is treated as the path to a Python source file.
Run "pydoc -k <keyword>" to search for a keyword in the synopsis lines
of all available modules.
Run "pydoc -p <port>" to start an HTTP server on a given port on the
local machine to generate documentation web pages. Port number 0 can be
used to get an arbitrary unused port.
For platforms without a command line, "pydoc -g" starts the HTTP server
and also pops up a little window for controlling it.
Run "pydoc -w <name>" to write out the HTML documentation for a module
to a file named "<name>.html".
Module docs for core modules are assumed to be in
https://docs.python.org/library/
This can be overridden by setting the PYTHONDOCS environment variable
to a different URL or to a local directory containing the Library
Reference Manual pages.
"""
__author__ = "Ka-Ping Yee <ping@lfw.org>"
__date__ = "26 February 2001"
__version__ = "$Revision: 88564 $"
__credits__ = """Guido van Rossum, for an excellent programming language.
Tommy Burnette, the original creator of manpy.
Paul Prescod, for all his work on onlinehelp.
Richard Chamberlain, for the first implementation of textdoc.
"""
# Known bugs that can't be fixed here:
# - imp.load_module() cannot be prevented from clobbering existing
# loaded modules, so calling synopsis() on a binary module file
# changes the contents of any existing module with the same name.
# - If the __file__ attribute on a module is a relative path and
# the current directory is changed with os.chdir(), an incorrect
# path will be displayed.
import sys, imp, os, re, types, inspect, __builtin__, pkgutil, warnings
from repr import Repr
from string import expandtabs, find, join, lower, split, strip, rfind, rstrip
from traceback import extract_tb
try:
from collections import deque
except ImportError:
# Python 2.3 compatibility
class deque(list):
def popleft(self):
return self.pop(0)
# --------------------------------------------------------- common routines
def pathdirs():
"""Convert sys.path into a list of absolute, existing, unique paths."""
dirs = []
normdirs = []
for dir in sys.path:
dir = os.path.abspath(dir or '.')
normdir = os.path.normcase(dir)
if normdir not in normdirs and os.path.isdir(dir):
dirs.append(dir)
normdirs.append(normdir)
return dirs
def getdoc(object):
"""Get the doc string or comments for an object."""
result = inspect.getdoc(object) or inspect.getcomments(object)
result = _encode(result)
return result and re.sub('^ *\n', '', rstrip(result)) or ''
def splitdoc(doc):
"""Split a doc string into a synopsis line (if any) and the rest."""
lines = split(strip(doc), '\n')
if len(lines) == 1:
return lines[0], ''
elif len(lines) >= 2 and not rstrip(lines[1]):
return lines[0], join(lines[2:], '\n')
return '', join(lines, '\n')
def classname(object, modname):
"""Get a class name and qualify it with a module name if necessary."""
name = object.__name__
if object.__module__ != modname:
name = object.__module__ + '.' + name
return name
def isdata(object):
"""Check if an object is of a type that probably means it's data."""
return not (inspect.ismodule(object) or inspect.isclass(object) or
inspect.isroutine(object) or inspect.isframe(object) or
inspect.istraceback(object) or inspect.iscode(object))
def replace(text, *pairs):
"""Do a series of global replacements on a string."""
while pairs:
text = join(split(text, pairs[0]), pairs[1])
pairs = pairs[2:]
return text
def cram(text, maxlen):
"""Omit part of a string if needed to make it fit in a maximum length."""
if len(text) > maxlen:
pre = max(0, (maxlen-3)//2)
post = max(0, maxlen-3-pre)
return text[:pre] + '...' + text[len(text)-post:]
return text
_re_stripid = re.compile(r' at 0x[0-9a-f]{6,16}(>+)$', re.IGNORECASE)
def stripid(text):
"""Remove the hexadecimal id from a Python object representation."""
# The behaviour of %p is implementation-dependent in terms of case.
return _re_stripid.sub(r'\1', text)
def _is_some_method(obj):
return inspect.ismethod(obj) or inspect.ismethoddescriptor(obj)
def allmethods(cl):
methods = {}
for key, value in inspect.getmembers(cl, _is_some_method):
methods[key] = 1
for base in cl.__bases__:
methods.update(allmethods(base)) # all your base are belong to us
for key in methods.keys():
methods[key] = getattr(cl, key)
return methods
def _split_list(s, predicate):
"""Split sequence s via predicate, and return pair ([true], [false]).
The return value is a 2-tuple of lists,
([x for x in s if predicate(x)],
[x for x in s if not predicate(x)])
"""
yes = []
no = []
for x in s:
if predicate(x):
yes.append(x)
else:
no.append(x)
return yes, no
def visiblename(name, all=None, obj=None):
"""Decide whether to show documentation on a variable."""
# Certain special names are redundant.
_hidden_names = ('__builtins__', '__doc__', '__file__', '__path__',
'__module__', '__name__', '__slots__', '__package__')
if name in _hidden_names: return 0
# Private names are hidden, but special names are displayed.
if name.startswith('__') and name.endswith('__'): return 1
# Namedtuples have public fields and methods with a single leading underscore
if name.startswith('_') and hasattr(obj, '_fields'):
return 1
if all is not None:
# only document that which the programmer exported in __all__
return name in all
else:
return not name.startswith('_')
def classify_class_attrs(object):
"""Wrap inspect.classify_class_attrs, with fixup for data descriptors."""
def fixup(data):
name, kind, cls, value = data
if inspect.isdatadescriptor(value):
kind = 'data descriptor'
return name, kind, cls, value
return map(fixup, inspect.classify_class_attrs(object))
# ----------------------------------------------------- Unicode support helpers
try:
_unicode = unicode
except NameError:
# If Python is built without Unicode support, the unicode type
# will not exist. Fake one that nothing will match, and make
# the _encode function that do nothing.
class _unicode(object):
pass
_encoding = 'ascii'
def _encode(text, encoding='ascii'):
return text
else:
import locale
_encoding = locale.getpreferredencoding()
def _encode(text, encoding=None):
if isinstance(text, unicode):
return text.encode(encoding or _encoding, 'xmlcharrefreplace')
else:
return text
def _binstr(obj):
# Ensure that we have an encoded (binary) string representation of obj,
# even if it is a unicode string.
if isinstance(obj, _unicode):
return obj.encode(_encoding, 'xmlcharrefreplace')
return str(obj)
# ----------------------------------------------------- module manipulation
def ispackage(path):
"""Guess whether a path refers to a package directory."""
if os.path.isdir(path):
for ext in ('.py', '.pyc', '.pyo'):
if os.path.isfile(os.path.join(path, '__init__' + ext)):
return True
return False
def source_synopsis(file):
line = file.readline()
while line[:1] == '#' or not strip(line):
line = file.readline()
if not line: break
line = strip(line)
if line[:4] == 'r"""': line = line[1:]
if line[:3] == '"""':
line = line[3:]
if line[-1:] == '\\': line = line[:-1]
while not strip(line):
line = file.readline()
if not line: break
result = strip(split(line, '"""')[0])
else: result = None
return result
def synopsis(filename, cache={}):
"""Get the one-line summary out of a module file."""
mtime = os.stat(filename).st_mtime
lastupdate, result = cache.get(filename, (None, None))
if lastupdate is None or lastupdate < mtime:
info = inspect.getmoduleinfo(filename)
try:
file = open(filename)
except IOError:
# module can't be opened, so skip it
return None
if info and 'b' in info[2]: # binary modules have to be imported
try: module = imp.load_module('__temp__', file, filename, info[1:])
except: return None
result = module.__doc__.splitlines()[0] if module.__doc__ else None
del sys.modules['__temp__']
else: # text modules can be directly examined
result = source_synopsis(file)
file.close()
cache[filename] = (mtime, result)
return result
class ErrorDuringImport(Exception):
"""Errors that occurred while trying to import something to document it."""
def __init__(self, filename, exc_info):
exc, value, tb = exc_info
self.filename = filename
self.exc = exc
self.value = value
self.tb = tb
def __str__(self):
exc = self.exc
if type(exc) is types.ClassType:
exc = exc.__name__
return 'problem in %s - %s: %s' % (self.filename, exc, self.value)
def importfile(path):
"""Import a Python source file or compiled file given its path."""
magic = imp.get_magic()
file = open(path, 'r')
if file.read(len(magic)) == magic:
kind = imp.PY_COMPILED
else:
kind = imp.PY_SOURCE
file.close()
filename = os.path.basename(path)
name, ext = os.path.splitext(filename)
file = open(path, 'r')
try:
module = imp.load_module(name, file, path, (ext, 'r', kind))
except:
raise ErrorDuringImport(path, sys.exc_info())
file.close()
return module
def safeimport(path, forceload=0, cache={}):
"""Import a module; handle errors; return None if the module isn't found.
If the module *is* found but an exception occurs, it's wrapped in an
ErrorDuringImport exception and reraised. Unlike __import__, if a
package path is specified, the module at the end of the path is returned,
not the package at the beginning. If the optional 'forceload' argument
is 1, we reload the module from disk (unless it's a dynamic extension)."""
try:
# If forceload is 1 and the module has been previously loaded from
# disk, we always have to reload the module. Checking the file's
# mtime isn't good enough (e.g. the module could contain a class
# that inherits from another module that has changed).
if forceload and path in sys.modules:
if path not in sys.builtin_module_names:
# Avoid simply calling reload() because it leaves names in
# the currently loaded module lying around if they're not
# defined in the new source file. Instead, remove the
# module from sys.modules and re-import. Also remove any
# submodules because they won't appear in the newly loaded
# module's namespace if they're already in sys.modules.
subs = [m for m in sys.modules if m.startswith(path + '.')]
for key in [path] + subs:
# Prevent garbage collection.
cache[key] = sys.modules[key]
del sys.modules[key]
module = __import__(path)
except:
# Did the error occur before or after the module was found?
(exc, value, tb) = info = sys.exc_info()
if path in sys.modules:
# An error occurred while executing the imported module.
raise ErrorDuringImport(sys.modules[path].__file__, info)
elif exc is SyntaxError:
# A SyntaxError occurred before we could execute the module.
raise ErrorDuringImport(value.filename, info)
elif exc is ImportError and extract_tb(tb)[-1][2]=='safeimport':
# The import error occurred directly in this function,
# which means there is no such module in the path.
return None
else:
# Some other error occurred during the importing process.
raise ErrorDuringImport(path, sys.exc_info())
for part in split(path, '.')[1:]:
try: module = getattr(module, part)
except AttributeError: return None
return module
# ---------------------------------------------------- formatter base class
class Doc:
def document(self, object, name=None, *args):
"""Generate documentation for an object."""
args = (object, name) + args
# 'try' clause is to attempt to handle the possibility that inspect
# identifies something in a way that pydoc itself has issues handling;
# think 'super' and how it is a descriptor (which raises the exception
# by lacking a __name__ attribute) and an instance.
if inspect.isgetsetdescriptor(object): return self.docdata(*args)
if inspect.ismemberdescriptor(object): return self.docdata(*args)
try:
if inspect.ismodule(object): return self.docmodule(*args)
if inspect.isclass(object): return self.docclass(*args)
if inspect.isroutine(object): return self.docroutine(*args)
except AttributeError:
pass
if isinstance(object, property): return self.docproperty(*args)
return self.docother(*args)
def fail(self, object, name=None, *args):
"""Raise an exception for unimplemented types."""
message = "don't know how to document object%s of type %s" % (
name and ' ' + repr(name), type(object).__name__)
raise TypeError, message
docmodule = docclass = docroutine = docother = docproperty = docdata = fail
def getdocloc(self, object,
basedir=os.path.join(sys.exec_prefix, "lib",
"python"+sys.version[0:3])):
"""Return the location of module docs or None"""
try:
file = inspect.getabsfile(object)
except TypeError:
file = '(built-in)'
docloc = os.environ.get("PYTHONDOCS",
"https://docs.python.org/library")
basedir = os.path.normcase(basedir)
if (isinstance(object, type(os)) and
(object.__name__ in ('errno', 'exceptions', 'gc', 'imp',
'marshal', 'posix', 'signal', 'sys',
'thread', 'zipimport') or
(file.startswith(basedir) and
not file.startswith(os.path.join(basedir, 'site-packages')))) and
object.__name__ not in ('xml.etree', 'test.pydoc_mod')):
if docloc.startswith(("http://", "https://")):
docloc = "%s/%s" % (docloc.rstrip("/"), object.__name__.lower())
else:
docloc = os.path.join(docloc, object.__name__.lower() + ".html")
else:
docloc = None
return docloc
# -------------------------------------------- HTML documentation generator
class HTMLRepr(Repr):
"""Class for safely making an HTML representation of a Python object."""
def __init__(self):
Repr.__init__(self)
self.maxlist = self.maxtuple = 20
self.maxdict = 10
self.maxstring = self.maxother = 100
def escape(self, text):
return replace(text, '&', '&', '<', '<', '>', '>')
def repr(self, object):
return Repr.repr(self, object)
def repr1(self, x, level):
if hasattr(type(x), '__name__'):
methodname = 'repr_' + join(split(type(x).__name__), '_')
if hasattr(self, methodname):
return getattr(self, methodname)(x, level)
return self.escape(cram(stripid(repr(x)), self.maxother))
def repr_string(self, x, level):
test = cram(x, self.maxstring)
testrepr = repr(test)
if '\\' in test and '\\' not in replace(testrepr, r'\\', ''):
# Backslashes are only literal in the string and are never
# needed to make any special characters, so show a raw string.
return 'r' + testrepr[0] + self.escape(test) + testrepr[0]
return re.sub(r'((\\[\\abfnrtv\'"]|\\[0-9]..|\\x..|\\u....)+)',
r'<font color="#c040c0">\1</font>',
self.escape(testrepr))
repr_str = repr_string
def repr_instance(self, x, level):
try:
return self.escape(cram(stripid(repr(x)), self.maxstring))
except:
return self.escape('<%s instance>' % x.__class__.__name__)
repr_unicode = repr_string
class HTMLDoc(Doc):
"""Formatter class for HTML documentation."""
# ------------------------------------------- HTML formatting utilities
_repr_instance = HTMLRepr()
repr = _repr_instance.repr
escape = _repr_instance.escape
def page(self, title, contents):
"""Format an HTML page."""
return _encode('''
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html><head><title>Python: %s</title>
<meta charset="utf-8">
</head><body bgcolor="#f0f0f8">
%s
</body></html>''' % (title, contents), 'ascii')
def heading(self, title, fgcol, bgcol, extras=''):
"""Format a page heading."""
return '''
<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading">
<tr bgcolor="%s">
<td valign=bottom> <br>
<font color="%s" face="helvetica, arial"> <br>%s</font></td
><td align=right valign=bottom
><font color="%s" face="helvetica, arial">%s</font></td></tr></table>
''' % (bgcol, fgcol, title, fgcol, extras or ' ')
def section(self, title, fgcol, bgcol, contents, width=6,
prelude='', marginalia=None, gap=' '):
"""Format a section with a heading."""
if marginalia is None:
marginalia = '<tt>' + ' ' * width + '</tt>'
result = '''<p>
<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
<tr bgcolor="%s">
<td colspan=3 valign=bottom> <br>
<font color="%s" face="helvetica, arial">%s</font></td></tr>
''' % (bgcol, fgcol, title)
if prelude:
result = result + '''
<tr bgcolor="%s"><td rowspan=2>%s</td>
<td colspan=2>%s</td></tr>
<tr><td>%s</td>''' % (bgcol, marginalia, prelude, gap)
else:
result = result + '''
<tr><td bgcolor="%s">%s</td><td>%s</td>''' % (bgcol, marginalia, gap)
return result + '\n<td width="100%%">%s</td></tr></table>' % contents
def bigsection(self, title, *args):
"""Format a section with a big heading."""
title = '<big><strong>%s</strong></big>' % title
return self.section(title, *args)
def preformat(self, text):
"""Format literal preformatted text."""
text = self.escape(expandtabs(text))
return replace(text, '\n\n', '\n \n', '\n\n', '\n \n',
' ', ' ', '\n', '<br>\n')
def multicolumn(self, list, format, cols=4):
"""Format a list of items into a multi-column list."""
result = ''
rows = (len(list)+cols-1)//cols
for col in range(cols):
result = result + '<td width="%d%%" valign=top>' % (100//cols)
for i in range(rows*col, rows*col+rows):
if i < len(list):
result = result + format(list[i]) + '<br>\n'
result = result + '</td>'
return '<table width="100%%" summary="list"><tr>%s</tr></table>' % result
def grey(self, text): return '<font color="#909090">%s</font>' % text
def namelink(self, name, *dicts):
"""Make a link for an identifier, given name-to-URL mappings."""
for dict in dicts:
if name in dict:
return '<a href="%s">%s</a>' % (dict[name], name)
return name
def classlink(self, object, modname):
"""Make a link for a class."""
name, module = object.__name__, sys.modules.get(object.__module__)
if hasattr(module, name) and getattr(module, name) is object:
return '<a href="%s.html#%s">%s</a>' % (
module.__name__, name, classname(object, modname))
return classname(object, modname)
def modulelink(self, object):
"""Make a link for a module."""
return '<a href="%s.html">%s</a>' % (object.__name__, object.__name__)
def modpkglink(self, data):
"""Make a link for a module or package to display in an index."""
name, path, ispackage, shadowed = data
if shadowed:
return self.grey(name)
if path:
url = '%s.%s.html' % (path, name)
else:
url = '%s.html' % name
if ispackage:
text = '<strong>%s</strong> (package)' % name
else:
text = name
return '<a href="%s">%s</a>' % (url, text)
def markup(self, text, escape=None, funcs={}, classes={}, methods={}):
"""Mark up some plain text, given a context of symbols to look for.
Each context dictionary maps object names to anchor names."""
escape = escape or self.escape
results = []
here = 0
pattern = re.compile(r'\b((http|ftp)://\S+[\w/]|'
r'RFC[- ]?(\d+)|'
r'PEP[- ]?(\d+)|'
r'(self\.)?(\w+))')
while True:
match = pattern.search(text, here)
if not match: break
start, end = match.span()
results.append(escape(text[here:start]))
all, scheme, rfc, pep, selfdot, name = match.groups()
if scheme:
url = escape(all).replace('"', '"')
results.append('<a href="%s">%s</a>' % (url, url))
elif rfc:
url = 'http://www.rfc-editor.org/rfc/rfc%d.txt' % int(rfc)
results.append('<a href="%s">%s</a>' % (url, escape(all)))
elif pep:
url = 'http://www.python.org/dev/peps/pep-%04d/' % int(pep)
results.append('<a href="%s">%s</a>' % (url, escape(all)))
elif selfdot:
# Create a link for methods like 'self.method(...)'
# and use <strong> for attributes like 'self.attr'
if text[end:end+1] == '(':
results.append('self.' + self.namelink(name, methods))
else:
results.append('self.<strong>%s</strong>' % name)
elif text[end:end+1] == '(':
results.append(self.namelink(name, methods, funcs, classes))
else:
results.append(self.namelink(name, classes))
here = end
results.append(escape(text[here:]))
return join(results, '')
# ---------------------------------------------- type-specific routines
def formattree(self, tree, modname, parent=None):
"""Produce HTML for a class tree as given by inspect.getclasstree()."""
result = ''
for entry in tree:
if type(entry) is type(()):
c, bases = entry
result = result + '<dt><font face="helvetica, arial">'
result = result + self.classlink(c, modname)
if bases and bases != (parent,):
parents = []
for base in bases:
parents.append(self.classlink(base, modname))
result = result + '(' + join(parents, ', ') + ')'
result = result + '\n</font></dt>'
elif type(entry) is type([]):
result = result + '<dd>\n%s</dd>\n' % self.formattree(
entry, modname, c)
return '<dl>\n%s</dl>\n' % result
def docmodule(self, object, name=None, mod=None, *ignored):
"""Produce HTML documentation for a module object."""
name = object.__name__ # ignore the passed-in name
try:
all = object.__all__
except AttributeError:
all = None
parts = split(name, '.')
links = []
for i in range(len(parts)-1):
links.append(
'<a href="%s.html"><font color="#ffffff">%s</font></a>' %
(join(parts[:i+1], '.'), parts[i]))
linkedname = join(links + parts[-1:], '.')
head = '<big><big><strong>%s</strong></big></big>' % linkedname
try:
path = inspect.getabsfile(object)
url = path
if sys.platform == 'win32':
import nturl2path
url = nturl2path.pathname2url(path)
filelink = '<a href="file:%s">%s</a>' % (url, path)
except TypeError:
filelink = '(built-in)'
info = []
if hasattr(object, '__version__'):
version = _binstr(object.__version__)
if version[:11] == '$' + 'Revision: ' and version[-1:] == '$':
version = strip(version[11:-1])
info.append('version %s' % self.escape(version))
if hasattr(object, '__date__'):
info.append(self.escape(_binstr(object.__date__)))
if info:
head = head + ' (%s)' % join(info, ', ')
docloc = self.getdocloc(object)
if docloc is not None:
docloc = '<br><a href="%(docloc)s">Module Docs</a>' % locals()
else:
docloc = ''
result = self.heading(
head, '#ffffff', '#7799ee',
'<a href=".">index</a><br>' + filelink + docloc)
modules = inspect.getmembers(object, inspect.ismodule)
classes, cdict = [], {}
for key, value in inspect.getmembers(object, inspect.isclass):
# if __all__ exists, believe it. Otherwise use old heuristic.
if (all is not None or
(inspect.getmodule(value) or object) is object):
if visiblename(key, all, object):
classes.append((key, value))
cdict[key] = cdict[value] = '#' + key
for key, value in classes:
for base in value.__bases__:
key, modname = base.__name__, base.__module__
module = sys.modules.get(modname)
if modname != name and module and hasattr(module, key):
if getattr(module, key) is base:
if not key in cdict:
cdict[key] = cdict[base] = modname + '.html#' + key
funcs, fdict = [], {}
for key, value in inspect.getmembers(object, inspect.isroutine):
# if __all__ exists, believe it. Otherwise use old heuristic.
if (all is not None or
inspect.isbuiltin(value) or inspect.getmodule(value) is object):
if visiblename(key, all, object):
funcs.append((key, value))
fdict[key] = '#-' + key
if inspect.isfunction(value): fdict[value] = fdict[key]
data = []
for key, value in inspect.getmembers(object, isdata):
if visiblename(key, all, object):
data.append((key, value))
doc = self.markup(getdoc(object), self.preformat, fdict, cdict)
doc = doc and '<tt>%s</tt>' % doc
result = result + '<p>%s</p>\n' % doc
if hasattr(object, '__path__'):
modpkgs = []
for importer, modname, ispkg in pkgutil.iter_modules(object.__path__):
modpkgs.append((modname, name, ispkg, 0))
modpkgs.sort()
contents = self.multicolumn(modpkgs, self.modpkglink)
result = result + self.bigsection(
'Package Contents', '#ffffff', '#aa55cc', contents)
elif modules:
contents = self.multicolumn(
modules, lambda key_value, s=self: s.modulelink(key_value[1]))
result = result + self.bigsection(
'Modules', '#ffffff', '#aa55cc', contents)
if classes:
classlist = map(lambda key_value: key_value[1], classes)
contents = [
self.formattree(inspect.getclasstree(classlist, 1), name)]
for key, value in classes:
contents.append(self.document(value, key, name, fdict, cdict))
result = result + self.bigsection(
'Classes', '#ffffff', '#ee77aa', join(contents))
if funcs:
contents = []
for key, value in funcs:
contents.append(self.document(value, key, name, fdict, cdict))
result = result + self.bigsection(
'Functions', '#ffffff', '#eeaa77', join(contents))
if data:
contents = []
for key, value in data:
contents.append(self.document(value, key))
result = result + self.bigsection(
'Data', '#ffffff', '#55aa55', join(contents, '<br>\n'))
if hasattr(object, '__author__'):
contents = self.markup(_binstr(object.__author__), self.preformat)
result = result + self.bigsection(
'Author', '#ffffff', '#7799ee', contents)
if hasattr(object, '__credits__'):
contents = self.markup(_binstr(object.__credits__), self.preformat)
result = result + self.bigsection(
'Credits', '#ffffff', '#7799ee', contents)
return result
def docclass(self, object, name=None, mod=None, funcs={}, classes={},
*ignored):
"""Produce HTML documentation for a class object."""
realname = object.__name__
name = name or realname
bases = object.__bases__
contents = []
push = contents.append
# Cute little class to pump out a horizontal rule between sections.
class HorizontalRule:
def __init__(self):
self.needone = 0
def maybe(self):
if self.needone:
push('<hr>\n')
self.needone = 1
hr = HorizontalRule()
# List the mro, if non-trivial.
mro = deque(inspect.getmro(object))
if len(mro) > 2:
hr.maybe()
push('<dl><dt>Method resolution order:</dt>\n')
for base in mro:
push('<dd>%s</dd>\n' % self.classlink(base,
object.__module__))
push('</dl>\n')
def spill(msg, attrs, predicate):
ok, attrs = _split_list(attrs, predicate)
if ok:
hr.maybe()
push(msg)
for name, kind, homecls, value in ok:
try:
value = getattr(object, name)
except Exception:
# Some descriptors may meet a failure in their __get__.
# (bug #1785)
push(self._docdescriptor(name, value, mod))
else:
push(self.document(value, name, mod,
funcs, classes, mdict, object))
push('\n')
return attrs
def spilldescriptors(msg, attrs, predicate):
ok, attrs = _split_list(attrs, predicate)
if ok:
hr.maybe()
push(msg)
for name, kind, homecls, value in ok:
push(self._docdescriptor(name, value, mod))
return attrs
def spilldata(msg, attrs, predicate):
ok, attrs = _split_list(attrs, predicate)
if ok:
hr.maybe()
push(msg)
for name, kind, homecls, value in ok:
base = self.docother(getattr(object, name), name, mod)
if (hasattr(value, '__call__') or
inspect.isdatadescriptor(value)):
doc = getattr(value, "__doc__", None)
else:
doc = None
if doc is None:
push('<dl><dt>%s</dl>\n' % base)
else:
doc = self.markup(getdoc(value), self.preformat,
funcs, classes, mdict)
doc = '<dd><tt>%s</tt>' % doc
push('<dl><dt>%s%s</dl>\n' % (base, doc))
push('\n')
return attrs
attrs = filter(lambda data: visiblename(data[0], obj=object),
classify_class_attrs(object))
mdict = {}
for key, kind, homecls, value in attrs:
mdict[key] = anchor = '#' + name + '-' + key
try:
value = getattr(object, name)
except Exception:
# Some descriptors may meet a failure in their __get__.
# (bug #1785)
pass
try:
# The value may not be hashable (e.g., a data attr with
# a dict or list value).
mdict[value] = anchor
except TypeError:
pass
while attrs:
if mro:
thisclass = mro.popleft()
else:
thisclass = attrs[0][2]
attrs, inherited = _split_list(attrs, lambda t: t[2] is thisclass)
if thisclass is __builtin__.object:
attrs = inherited
continue
elif thisclass is object:
tag = 'defined here'
else:
tag = 'inherited from %s' % self.classlink(thisclass,
object.__module__)
tag += ':<br>\n'
# Sort attrs by name.
try:
attrs.sort(key=lambda t: t[0])
except TypeError:
attrs.sort(lambda t1, t2: cmp(t1[0], t2[0])) # 2.3 compat
# Pump out the attrs, segregated by kind.
attrs = spill('Methods %s' % tag, attrs,
lambda t: t[1] == 'method')
attrs = spill('Class methods %s' % tag, attrs,
lambda t: t[1] == 'class method')
attrs = spill('Static methods %s' % tag, attrs,
lambda t: t[1] == 'static method')
attrs = spilldescriptors('Data descriptors %s' % tag, attrs,
lambda t: t[1] == 'data descriptor')
attrs = spilldata('Data and other attributes %s' % tag, attrs,
lambda t: t[1] == 'data')
assert attrs == []
attrs = inherited
contents = ''.join(contents)
if name == realname:
title = '<a name="%s">class <strong>%s</strong></a>' % (
name, realname)
else:
title = '<strong>%s</strong> = <a name="%s">class %s</a>' % (
name, name, realname)
if bases:
parents = []
for base in bases:
parents.append(self.classlink(base, object.__module__))
title = title + '(%s)' % join(parents, ', ')
doc = self.markup(getdoc(object), self.preformat, funcs, classes, mdict)
doc = doc and '<tt>%s<br> </tt>' % doc
return self.section(title, '#000000', '#ffc8d8', contents, 3, doc)
def formatvalue(self, object):
"""Format an argument default value as text."""
return self.grey('=' + self.repr(object))
def docroutine(self, object, name=None, mod=None,
funcs={}, classes={}, methods={}, cl=None):
"""Produce HTML documentation for a function or method object."""
realname = object.__name__
name = name or realname
anchor = (cl and cl.__name__ or '') + '-' + name
note = ''
skipdocs = 0
if inspect.ismethod(object):
imclass = object.im_class
if cl:
if imclass is not cl:
note = ' from ' + self.classlink(imclass, mod)
else:
if object.im_self is not None:
note = ' method of %s instance' % self.classlink(
object.im_self.__class__, mod)
else:
note = ' unbound %s method' % self.classlink(imclass,mod)
object = object.im_func
if name == realname:
title = '<a name="%s"><strong>%s</strong></a>' % (anchor, realname)
else:
if (cl and realname in cl.__dict__ and
cl.__dict__[realname] is object):
reallink = '<a href="#%s">%s</a>' % (
cl.__name__ + '-' + realname, realname)
skipdocs = 1
else:
reallink = realname
title = '<a name="%s"><strong>%s</strong></a> = %s' % (
anchor, name, reallink)
if inspect.isfunction(object):
args, varargs, varkw, defaults = inspect.getargspec(object)
argspec = inspect.formatargspec(
args, varargs, varkw, defaults, formatvalue=self.formatvalue)
if realname == '<lambda>':
title = '<strong>%s</strong> <em>lambda</em> ' % name
argspec = argspec[1:-1] # remove parentheses
else:
argspec = '(...)'
decl = title + argspec + (note and self.grey(
'<font face="helvetica, arial">%s</font>' % note))
if skipdocs:
return '<dl><dt>%s</dt></dl>\n' % decl
else:
doc = self.markup(
getdoc(object), self.preformat, funcs, classes, methods)
doc = doc and '<dd><tt>%s</tt></dd>' % doc
return '<dl><dt>%s</dt>%s</dl>\n' % (decl, doc)
def _docdescriptor(self, name, value, mod):
results = []
push = results.append
if name:
push('<dl><dt><strong>%s</strong></dt>\n' % name)
if value.__doc__ is not None:
doc = self.markup(getdoc(value), self.preformat)
push('<dd><tt>%s</tt></dd>\n' % doc)
push('</dl>\n')
return ''.join(results)
def docproperty(self, object, name=None, mod=None, cl=None):
"""Produce html documentation for a property."""
return self._docdescriptor(name, object, mod)
def docother(self, object, name=None, mod=None, *ignored):
"""Produce HTML documentation for a data object."""
lhs = name and '<strong>%s</strong> = ' % name or ''
return lhs + self.repr(object)
def docdata(self, object, name=None, mod=None, cl=None):
"""Produce html documentation for a data descriptor."""
return self._docdescriptor(name, object, mod)
def index(self, dir, shadowed=None):
"""Generate an HTML index for a directory of modules."""
modpkgs = []
if shadowed is None: shadowed = {}
for importer, name, ispkg in pkgutil.iter_modules([dir]):
modpkgs.append((name, '', ispkg, name in shadowed))
shadowed[name] = 1
modpkgs.sort()
contents = self.multicolumn(modpkgs, self.modpkglink)
return self.bigsection(dir, '#ffffff', '#ee77aa', contents)
# -------------------------------------------- text documentation generator
class TextRepr(Repr):
"""Class for safely making a text representation of a Python object."""
def __init__(self):
Repr.__init__(self)
self.maxlist = self.maxtuple = 20
self.maxdict = 10
self.maxstring = self.maxother = 100
def repr1(self, x, level):
if hasattr(type(x), '__name__'):
methodname = 'repr_' + join(split(type(x).__name__), '_')
if hasattr(self, methodname):
return getattr(self, methodname)(x, level)
return cram(stripid(repr(x)), self.maxother)
def repr_string(self, x, level):
test = cram(x, self.maxstring)
testrepr = repr(test)
if '\\' in test and '\\' not in replace(testrepr, r'\\', ''):
# Backslashes are only literal in the string and are never
# needed to make any special characters, so show a raw string.
return 'r' + testrepr[0] + test + testrepr[0]
return testrepr
repr_str = repr_string
def repr_instance(self, x, level):
try:
return cram(stripid(repr(x)), self.maxstring)
except:
return '<%s instance>' % x.__class__.__name__
class TextDoc(Doc):
"""Formatter class for text documentation."""
# ------------------------------------------- text formatting utilities
_repr_instance = TextRepr()
repr = _repr_instance.repr
def bold(self, text):
"""Format a string in bold by overstriking."""
return join(map(lambda ch: ch + '\b' + ch, text), '')
def indent(self, text, prefix=' '):
"""Indent text by prepending a given prefix to each line."""
if not text: return ''
lines = split(text, '\n')
lines = map(lambda line, prefix=prefix: prefix + line, lines)
if lines: lines[-1] = rstrip(lines[-1])
return join(lines, '\n')
def section(self, title, contents):
"""Format a section with a given heading."""
return self.bold(title) + '\n' + rstrip(self.indent(contents)) + '\n\n'
# ---------------------------------------------- type-specific routines
def formattree(self, tree, modname, parent=None, prefix=''):
"""Render in text a class tree as returned by inspect.getclasstree()."""
result = ''
for entry in tree:
if type(entry) is type(()):
c, bases = entry
result = result + prefix + classname(c, modname)
if bases and bases != (parent,):
parents = map(lambda c, m=modname: classname(c, m), bases)
result = result + '(%s)' % join(parents, ', ')
result = result + '\n'
elif type(entry) is type([]):
result = result + self.formattree(
entry, modname, c, prefix + ' ')
return result
def docmodule(self, object, name=None, mod=None):
"""Produce text documentation for a given module object."""
name = object.__name__ # ignore the passed-in name
synop, desc = splitdoc(getdoc(object))
result = self.section('NAME', name + (synop and ' - ' + synop))
try:
all = object.__all__
except AttributeError:
all = None
try:
file = inspect.getabsfile(object)
except TypeError:
file = '(built-in)'
result = result + self.section('FILE', file)
docloc = self.getdocloc(object)
if docloc is not None:
result = result + self.section('MODULE DOCS', docloc)
if desc:
result = result + self.section('DESCRIPTION', desc)
classes = []
for key, value in inspect.getmembers(object, inspect.isclass):
# if __all__ exists, believe it. Otherwise use old heuristic.
if (all is not None
or (inspect.getmodule(value) or object) is object):
if visiblename(key, all, object):
classes.append((key, value))
funcs = []
for key, value in inspect.getmembers(object, inspect.isroutine):
# if __all__ exists, believe it. Otherwise use old heuristic.
if (all is not None or
inspect.isbuiltin(value) or inspect.getmodule(value) is object):
if visiblename(key, all, object):
funcs.append((key, value))
data = []
for key, value in inspect.getmembers(object, isdata):
if visiblename(key, all, object):
data.append((key, value))
modpkgs = []
modpkgs_names = set()
if hasattr(object, '__path__'):
for importer, modname, ispkg in pkgutil.iter_modules(object.__path__):
modpkgs_names.add(modname)
if ispkg:
modpkgs.append(modname + ' (package)')
else:
modpkgs.append(modname)
modpkgs.sort()
result = result + self.section(
'PACKAGE CONTENTS', join(modpkgs, '\n'))
# Detect submodules as sometimes created by C extensions
submodules = []
for key, value in inspect.getmembers(object, inspect.ismodule):
if value.__name__.startswith(name + '.') and key not in modpkgs_names:
submodules.append(key)
if submodules:
submodules.sort()
result = result + self.section(
'SUBMODULES', join(submodules, '\n'))
if classes:
classlist = map(lambda key_value: key_value[1], classes)
contents = [self.formattree(
inspect.getclasstree(classlist, 1), name)]
for key, value in classes:
contents.append(self.document(value, key, name))
result = result + self.section('CLASSES', join(contents, '\n'))
if funcs:
contents = []
for key, value in funcs:
contents.append(self.document(value, key, name))
result = result + self.section('FUNCTIONS', join(contents, '\n'))
if data:
contents = []
for key, value in data:
contents.append(self.docother(value, key, name, maxlen=70))
result = result + self.section('DATA', join(contents, '\n'))
if hasattr(object, '__version__'):
version = _binstr(object.__version__)
if version[:11] == '$' + 'Revision: ' and version[-1:] == '$':
version = strip(version[11:-1])
result = result + self.section('VERSION', version)
if hasattr(object, '__date__'):
result = result + self.section('DATE', _binstr(object.__date__))
if hasattr(object, '__author__'):
result = result + self.section('AUTHOR', _binstr(object.__author__))
if hasattr(object, '__credits__'):
result = result + self.section('CREDITS', _binstr(object.__credits__))
return result
def docclass(self, object, name=None, mod=None, *ignored):
"""Produce text documentation for a given class object."""
realname = object.__name__
name = name or realname
bases = object.__bases__
def makename(c, m=object.__module__):
return classname(c, m)
if name == realname:
title = 'class ' + self.bold(realname)
else:
title = self.bold(name) + ' = class ' + realname
if bases:
parents = map(makename, bases)
title = title + '(%s)' % join(parents, ', ')
doc = getdoc(object)
contents = doc and [doc + '\n'] or []
push = contents.append
# List the mro, if non-trivial.
mro = deque(inspect.getmro(object))
if len(mro) > 2:
push("Method resolution order:")
for base in mro:
push(' ' + makename(base))
push('')
# Cute little class to pump out a horizontal rule between sections.
class HorizontalRule:
def __init__(self):
self.needone = 0
def maybe(self):
if self.needone:
push('-' * 70)
self.needone = 1
hr = HorizontalRule()
def spill(msg, attrs, predicate):
ok, attrs = _split_list(attrs, predicate)
if ok:
hr.maybe()
push(msg)
for name, kind, homecls, value in ok:
try:
value = getattr(object, name)
except Exception:
# Some descriptors may meet a failure in their __get__.
# (bug #1785)
push(self._docdescriptor(name, value, mod))
else:
push(self.document(value,
name, mod, object))
return attrs
def spilldescriptors(msg, attrs, predicate):
ok, attrs = _split_list(attrs, predicate)
if ok:
hr.maybe()
push(msg)
for name, kind, homecls, value in ok:
push(self._docdescriptor(name, value, mod))
return attrs
def spilldata(msg, attrs, predicate):
ok, attrs = _split_list(attrs, predicate)
if ok:
hr.maybe()
push(msg)
for name, kind, homecls, value in ok:
if (hasattr(value, '__call__') or
inspect.isdatadescriptor(value)):
doc = getdoc(value)
else:
doc = None
push(self.docother(getattr(object, name),
name, mod, maxlen=70, doc=doc) + '\n')
return attrs
attrs = filter(lambda data: visiblename(data[0], obj=object),
classify_class_attrs(object))
while attrs:
if mro:
thisclass = mro.popleft()
else:
thisclass = attrs[0][2]
attrs, inherited = _split_list(attrs, lambda t: t[2] is thisclass)
if thisclass is __builtin__.object:
attrs = inherited
continue
elif thisclass is object:
tag = "defined here"
else:
tag = "inherited from %s" % classname(thisclass,
object.__module__)
# Sort attrs by name.
attrs.sort()
# Pump out the attrs, segregated by kind.
attrs = spill("Methods %s:\n" % tag, attrs,
lambda t: t[1] == 'method')
attrs = spill("Class methods %s:\n" % tag, attrs,
lambda t: t[1] == 'class method')
attrs = spill("Static methods %s:\n" % tag, attrs,
lambda t: t[1] == 'static method')
attrs = spilldescriptors("Data descriptors %s:\n" % tag, attrs,
lambda t: t[1] == 'data descriptor')
attrs = spilldata("Data and other attributes %s:\n" % tag, attrs,
lambda t: t[1] == 'data')
assert attrs == []
attrs = inherited
contents = '\n'.join(contents)
if not contents:
return title + '\n'
return title + '\n' + self.indent(rstrip(contents), ' | ') + '\n'
def formatvalue(self, object):
"""Format an argument default value as text."""
return '=' + self.repr(object)
def docroutine(self, object, name=None, mod=None, cl=None):
"""Produce text documentation for a function or method object."""
realname = object.__name__
name = name or realname
note = ''
skipdocs = 0
if inspect.ismethod(object):
imclass = object.im_class
if cl:
if imclass is not cl:
note = ' from ' + classname(imclass, mod)
else:
if object.im_self is not None:
note = ' method of %s instance' % classname(
object.im_self.__class__, mod)
else:
note = ' unbound %s method' % classname(imclass,mod)
object = object.im_func
if name == realname:
title = self.bold(realname)
else:
if (cl and realname in cl.__dict__ and
cl.__dict__[realname] is object):
skipdocs = 1
title = self.bold(name) + ' = ' + realname
if inspect.isfunction(object):
args, varargs, varkw, defaults = inspect.getargspec(object)
argspec = inspect.formatargspec(
args, varargs, varkw, defaults, formatvalue=self.formatvalue)
if realname == '<lambda>':
title = self.bold(name) + ' lambda '
argspec = argspec[1:-1] # remove parentheses
else:
argspec = '(...)'
decl = title + argspec + note
if skipdocs:
return decl + '\n'
else:
doc = getdoc(object) or ''
return decl + '\n' + (doc and rstrip(self.indent(doc)) + '\n')
def _docdescriptor(self, name, value, mod):
results = []
push = results.append
if name:
push(self.bold(name))
push('\n')
doc = getdoc(value) or ''
if doc:
push(self.indent(doc))
push('\n')
return ''.join(results)
def docproperty(self, object, name=None, mod=None, cl=None):
"""Produce text documentation for a property."""
return self._docdescriptor(name, object, mod)
def docdata(self, object, name=None, mod=None, cl=None):
"""Produce text documentation for a data descriptor."""
return self._docdescriptor(name, object, mod)
def docother(self, object, name=None, mod=None, parent=None, maxlen=None, doc=None):
"""Produce text documentation for a data object."""
repr = self.repr(object)
if maxlen:
line = (name and name + ' = ' or '') + repr
chop = maxlen - len(line)
if chop < 0: repr = repr[:chop] + '...'
line = (name and self.bold(name) + ' = ' or '') + repr
if doc is not None:
line += '\n' + self.indent(str(doc))
return line
# --------------------------------------------------------- user interfaces
def pager(text):
"""The first time this is called, determine what kind of pager to use."""
global pager
pager = getpager()
pager(text)
def getpager():
"""Decide what method to use for paging through text."""
if type(sys.stdout) is not types.FileType:
return plainpager
if not hasattr(sys.stdin, "isatty"):
return plainpager
if not sys.stdin.isatty() or not sys.stdout.isatty():
return plainpager
if 'PAGER' in os.environ:
if sys.platform == 'win32': # pipes completely broken in Windows
return lambda text: tempfilepager(plain(text), os.environ['PAGER'])
elif os.environ.get('TERM') in ('dumb', 'emacs'):
return lambda text: pipepager(plain(text), os.environ['PAGER'])
else:
return lambda text: pipepager(text, os.environ['PAGER'])
if os.environ.get('TERM') in ('dumb', 'emacs'):
return plainpager
if sys.platform == 'win32' or sys.platform.startswith('os2'):
return lambda text: tempfilepager(plain(text), 'more <')
if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:
return lambda text: pipepager(text, 'less')
import tempfile
(fd, filename) = tempfile.mkstemp()
os.close(fd)
try:
if hasattr(os, 'system') and os.system('more "%s"' % filename) == 0:
return lambda text: pipepager(text, 'more')
else:
return ttypager
finally:
os.unlink(filename)
def plain(text):
"""Remove boldface formatting from text."""
return re.sub('.\b', '', text)
def pipepager(text, cmd):
"""Page through text by feeding it to another program."""
pipe = os.popen(cmd, 'w')
try:
pipe.write(_encode(text))
pipe.close()
except IOError:
pass # Ignore broken pipes caused by quitting the pager program.
def tempfilepager(text, cmd):
"""Page through text by invoking a program on a temporary file."""
import tempfile
filename = tempfile.mktemp()
file = open(filename, 'w')
file.write(_encode(text))
file.close()
try:
os.system(cmd + ' "' + filename + '"')
finally:
os.unlink(filename)
def ttypager(text):
"""Page through text on a text terminal."""
lines = plain(_encode(plain(text), getattr(sys.stdout, 'encoding', _encoding))).split('\n')
try:
import tty
fd = sys.stdin.fileno()
old = tty.tcgetattr(fd)
tty.setcbreak(fd)
getchar = lambda: sys.stdin.read(1)
except (ImportError, AttributeError):
tty = None
getchar = lambda: sys.stdin.readline()[:-1][:1]
try:
try:
h = int(os.environ.get('LINES', 0))
except ValueError:
h = 0
if h <= 1:
h = 25
r = inc = h - 1
sys.stdout.write(join(lines[:inc], '\n') + '\n')
while lines[r:]:
sys.stdout.write('-- more --')
sys.stdout.flush()
c = getchar()
if c in ('q', 'Q'):
sys.stdout.write('\r \r')
break
elif c in ('\r', '\n'):
sys.stdout.write('\r \r' + lines[r] + '\n')
r = r + 1
continue
if c in ('b', 'B', '\x1b'):
r = r - inc - inc
if r < 0: r = 0
sys.stdout.write('\n' + join(lines[r:r+inc], '\n') + '\n')
r = r + inc
finally:
if tty:
tty.tcsetattr(fd, tty.TCSAFLUSH, old)
def plainpager(text):
"""Simply print unformatted text. This is the ultimate fallback."""
sys.stdout.write(_encode(plain(text), getattr(sys.stdout, 'encoding', _encoding)))
def describe(thing):
"""Produce a short description of the given thing."""
if inspect.ismodule(thing):
if thing.__name__ in sys.builtin_module_names:
return 'built-in module ' + thing.__name__
if hasattr(thing, '__path__'):
return 'package ' + thing.__name__
else:
return 'module ' + thing.__name__
if inspect.isbuiltin(thing):
return 'built-in function ' + thing.__name__
if inspect.isgetsetdescriptor(thing):
return 'getset descriptor %s.%s.%s' % (
thing.__objclass__.__module__, thing.__objclass__.__name__,
thing.__name__)
if inspect.ismemberdescriptor(thing):
return 'member descriptor %s.%s.%s' % (
thing.__objclass__.__module__, thing.__objclass__.__name__,
thing.__name__)
if inspect.isclass(thing):
return 'class ' + thing.__name__
if inspect.isfunction(thing):
return 'function ' + thing.__name__
if inspect.ismethod(thing):
return 'method ' + thing.__name__
if type(thing) is types.InstanceType:
return 'instance of ' + thing.__class__.__name__
return type(thing).__name__
def locate(path, forceload=0):
"""Locate an object by name or dotted path, importing as necessary."""
parts = [part for part in split(path, '.') if part]
module, n = None, 0
while n < len(parts):
nextmodule = safeimport(join(parts[:n+1], '.'), forceload)
if nextmodule: module, n = nextmodule, n + 1
else: break
if module:
object = module
else:
object = __builtin__
for part in parts[n:]:
try:
object = getattr(object, part)
except AttributeError:
return None
return object
# --------------------------------------- interactive interpreter interface
text = TextDoc()
html = HTMLDoc()
class _OldStyleClass: pass
_OLD_INSTANCE_TYPE = type(_OldStyleClass())
def resolve(thing, forceload=0):
"""Given an object or a path to an object, get the object and its name."""
if isinstance(thing, str):
object = locate(thing, forceload)
if object is None:
raise ImportError, 'no Python documentation found for %r' % thing
return object, thing
else:
name = getattr(thing, '__name__', None)
return thing, name if isinstance(name, str) else None
def render_doc(thing, title='Python Library Documentation: %s', forceload=0):
"""Render text documentation, given an object or a path to an object."""
object, name = resolve(thing, forceload)
desc = describe(object)
module = inspect.getmodule(object)
if name and '.' in name:
desc += ' in ' + name[:name.rfind('.')]
elif module and module is not object:
desc += ' in module ' + module.__name__
if type(object) is _OLD_INSTANCE_TYPE:
# If the passed object is an instance of an old-style class,
# document its available methods instead of its value.
object = object.__class__
elif not (inspect.ismodule(object) or
inspect.isclass(object) or
inspect.isroutine(object) or
inspect.isgetsetdescriptor(object) or
inspect.ismemberdescriptor(object) or
isinstance(object, property)):
# If the passed object is a piece of data or an instance,
# document its available methods instead of its value.
object = type(object)
desc += ' object'
return title % desc + '\n\n' + text.document(object, name)
def doc(thing, title='Python Library Documentation: %s', forceload=0):
"""Display text documentation, given an object or a path to an object."""
try:
pager(render_doc(thing, title, forceload))
except (ImportError, ErrorDuringImport), value:
print value
def writedoc(thing, forceload=0):
"""Write HTML documentation to a file in the current directory."""
try:
object, name = resolve(thing, forceload)
page = html.page(describe(object), html.document(object, name))
file = open(name + '.html', 'w')
file.write(page)
file.close()
print 'wrote', name + '.html'
except (ImportError, ErrorDuringImport), value:
print value
def writedocs(dir, pkgpath='', done=None):
"""Write out HTML documentation for all modules in a directory tree."""
if done is None: done = {}
for importer, modname, ispkg in pkgutil.walk_packages([dir], pkgpath):
writedoc(modname)
return
class Helper:
# These dictionaries map a topic name to either an alias, or a tuple
# (label, seealso-items). The "label" is the label of the corresponding
# section in the .rst file under Doc/ and an index into the dictionary
# in pydoc_data/topics.py.
#
# CAUTION: if you change one of these dictionaries, be sure to adapt the
# list of needed labels in Doc/tools/pyspecific.py and
# regenerate the pydoc_data/topics.py file by running
# make pydoc-topics
# in Doc/ and copying the output file into the Lib/ directory.
keywords = {
'and': 'BOOLEAN',
'as': 'with',
'assert': ('assert', ''),
'break': ('break', 'while for'),
'class': ('class', 'CLASSES SPECIALMETHODS'),
'continue': ('continue', 'while for'),
'def': ('function', ''),
'del': ('del', 'BASICMETHODS'),
'elif': 'if',
'else': ('else', 'while for'),
'except': 'try',
'exec': ('exec', ''),
'finally': 'try',
'for': ('for', 'break continue while'),
'from': 'import',
'global': ('global', 'NAMESPACES'),
'if': ('if', 'TRUTHVALUE'),
'import': ('import', 'MODULES'),
'in': ('in', 'SEQUENCEMETHODS2'),
'is': 'COMPARISON',
'lambda': ('lambda', 'FUNCTIONS'),
'not': 'BOOLEAN',
'or': 'BOOLEAN',
'pass': ('pass', ''),
'print': ('print', ''),
'raise': ('raise', 'EXCEPTIONS'),
'return': ('return', 'FUNCTIONS'),
'try': ('try', 'EXCEPTIONS'),
'while': ('while', 'break continue if TRUTHVALUE'),
'with': ('with', 'CONTEXTMANAGERS EXCEPTIONS yield'),
'yield': ('yield', ''),
}
# Either add symbols to this dictionary or to the symbols dictionary
# directly: Whichever is easier. They are merged later.
_symbols_inverse = {
'STRINGS' : ("'", "'''", "r'", "u'", '"""', '"', 'r"', 'u"'),
'OPERATORS' : ('+', '-', '*', '**', '/', '//', '%', '<<', '>>', '&',
'|', '^', '~', '<', '>', '<=', '>=', '==', '!=', '<>'),
'COMPARISON' : ('<', '>', '<=', '>=', '==', '!=', '<>'),
'UNARY' : ('-', '~'),
'AUGMENTEDASSIGNMENT' : ('+=', '-=', '*=', '/=', '%=', '&=', '|=',
'^=', '<<=', '>>=', '**=', '//='),
'BITWISE' : ('<<', '>>', '&', '|', '^', '~'),
'COMPLEX' : ('j', 'J')
}
symbols = {
'%': 'OPERATORS FORMATTING',
'**': 'POWER',
',': 'TUPLES LISTS FUNCTIONS',
'.': 'ATTRIBUTES FLOAT MODULES OBJECTS',
'...': 'ELLIPSIS',
':': 'SLICINGS DICTIONARYLITERALS',
'@': 'def class',
'\\': 'STRINGS',
'_': 'PRIVATENAMES',
'__': 'PRIVATENAMES SPECIALMETHODS',
'`': 'BACKQUOTES',
'(': 'TUPLES FUNCTIONS CALLS',
')': 'TUPLES FUNCTIONS CALLS',
'[': 'LISTS SUBSCRIPTS SLICINGS',
']': 'LISTS SUBSCRIPTS SLICINGS'
}
for topic, symbols_ in _symbols_inverse.iteritems():
for symbol in symbols_:
topics = symbols.get(symbol, topic)
if topic not in topics:
topics = topics + ' ' + topic
symbols[symbol] = topics
topics = {
'TYPES': ('types', 'STRINGS UNICODE NUMBERS SEQUENCES MAPPINGS '
'FUNCTIONS CLASSES MODULES FILES inspect'),
'STRINGS': ('strings', 'str UNICODE SEQUENCES STRINGMETHODS FORMATTING '
'TYPES'),
'STRINGMETHODS': ('string-methods', 'STRINGS FORMATTING'),
'FORMATTING': ('formatstrings', 'OPERATORS'),
'UNICODE': ('strings', 'encodings unicode SEQUENCES STRINGMETHODS '
'FORMATTING TYPES'),
'NUMBERS': ('numbers', 'INTEGER FLOAT COMPLEX TYPES'),
'INTEGER': ('integers', 'int range'),
'FLOAT': ('floating', 'float math'),
'COMPLEX': ('imaginary', 'complex cmath'),
'SEQUENCES': ('typesseq', 'STRINGMETHODS FORMATTING xrange LISTS'),
'MAPPINGS': 'DICTIONARIES',
'FUNCTIONS': ('typesfunctions', 'def TYPES'),
'METHODS': ('typesmethods', 'class def CLASSES TYPES'),
'CODEOBJECTS': ('bltin-code-objects', 'compile FUNCTIONS TYPES'),
'TYPEOBJECTS': ('bltin-type-objects', 'types TYPES'),
'FRAMEOBJECTS': 'TYPES',
'TRACEBACKS': 'TYPES',
'NONE': ('bltin-null-object', ''),
'ELLIPSIS': ('bltin-ellipsis-object', 'SLICINGS'),
'FILES': ('bltin-file-objects', ''),
'SPECIALATTRIBUTES': ('specialattrs', ''),
'CLASSES': ('types', 'class SPECIALMETHODS PRIVATENAMES'),
'MODULES': ('typesmodules', 'import'),
'PACKAGES': 'import',
'EXPRESSIONS': ('operator-summary', 'lambda or and not in is BOOLEAN '
'COMPARISON BITWISE SHIFTING BINARY FORMATTING POWER '
'UNARY ATTRIBUTES SUBSCRIPTS SLICINGS CALLS TUPLES '
'LISTS DICTIONARIES BACKQUOTES'),
'OPERATORS': 'EXPRESSIONS',
'PRECEDENCE': 'EXPRESSIONS',
'OBJECTS': ('objects', 'TYPES'),
'SPECIALMETHODS': ('specialnames', 'BASICMETHODS ATTRIBUTEMETHODS '
'CALLABLEMETHODS SEQUENCEMETHODS1 MAPPINGMETHODS '
'SEQUENCEMETHODS2 NUMBERMETHODS CLASSES'),
'BASICMETHODS': ('customization', 'cmp hash repr str SPECIALMETHODS'),
'ATTRIBUTEMETHODS': ('attribute-access', 'ATTRIBUTES SPECIALMETHODS'),
'CALLABLEMETHODS': ('callable-types', 'CALLS SPECIALMETHODS'),
'SEQUENCEMETHODS1': ('sequence-types', 'SEQUENCES SEQUENCEMETHODS2 '
'SPECIALMETHODS'),
'SEQUENCEMETHODS2': ('sequence-methods', 'SEQUENCES SEQUENCEMETHODS1 '
'SPECIALMETHODS'),
'MAPPINGMETHODS': ('sequence-types', 'MAPPINGS SPECIALMETHODS'),
'NUMBERMETHODS': ('numeric-types', 'NUMBERS AUGMENTEDASSIGNMENT '
'SPECIALMETHODS'),
'EXECUTION': ('execmodel', 'NAMESPACES DYNAMICFEATURES EXCEPTIONS'),
'NAMESPACES': ('naming', 'global ASSIGNMENT DELETION DYNAMICFEATURES'),
'DYNAMICFEATURES': ('dynamic-features', ''),
'SCOPING': 'NAMESPACES',
'FRAMES': 'NAMESPACES',
'EXCEPTIONS': ('exceptions', 'try except finally raise'),
'COERCIONS': ('coercion-rules','CONVERSIONS'),
'CONVERSIONS': ('conversions', 'COERCIONS'),
'IDENTIFIERS': ('identifiers', 'keywords SPECIALIDENTIFIERS'),
'SPECIALIDENTIFIERS': ('id-classes', ''),
'PRIVATENAMES': ('atom-identifiers', ''),
'LITERALS': ('atom-literals', 'STRINGS BACKQUOTES NUMBERS '
'TUPLELITERALS LISTLITERALS DICTIONARYLITERALS'),
'TUPLES': 'SEQUENCES',
'TUPLELITERALS': ('exprlists', 'TUPLES LITERALS'),
'LISTS': ('typesseq-mutable', 'LISTLITERALS'),
'LISTLITERALS': ('lists', 'LISTS LITERALS'),
'DICTIONARIES': ('typesmapping', 'DICTIONARYLITERALS'),
'DICTIONARYLITERALS': ('dict', 'DICTIONARIES LITERALS'),
'BACKQUOTES': ('string-conversions', 'repr str STRINGS LITERALS'),
'ATTRIBUTES': ('attribute-references', 'getattr hasattr setattr '
'ATTRIBUTEMETHODS'),
'SUBSCRIPTS': ('subscriptions', 'SEQUENCEMETHODS1'),
'SLICINGS': ('slicings', 'SEQUENCEMETHODS2'),
'CALLS': ('calls', 'EXPRESSIONS'),
'POWER': ('power', 'EXPRESSIONS'),
'UNARY': ('unary', 'EXPRESSIONS'),
'BINARY': ('binary', 'EXPRESSIONS'),
'SHIFTING': ('shifting', 'EXPRESSIONS'),
'BITWISE': ('bitwise', 'EXPRESSIONS'),
'COMPARISON': ('comparisons', 'EXPRESSIONS BASICMETHODS'),
'BOOLEAN': ('booleans', 'EXPRESSIONS TRUTHVALUE'),
'ASSERTION': 'assert',
'ASSIGNMENT': ('assignment', 'AUGMENTEDASSIGNMENT'),
'AUGMENTEDASSIGNMENT': ('augassign', 'NUMBERMETHODS'),
'DELETION': 'del',
'PRINTING': 'print',
'RETURNING': 'return',
'IMPORTING': 'import',
'CONDITIONAL': 'if',
'LOOPING': ('compound', 'for while break continue'),
'TRUTHVALUE': ('truth', 'if while and or not BASICMETHODS'),
'DEBUGGING': ('debugger', 'pdb'),
'CONTEXTMANAGERS': ('context-managers', 'with'),
}
def __init__(self, input=None, output=None):
self._input = input
self._output = output
input = property(lambda self: self._input or sys.stdin)
output = property(lambda self: self._output or sys.stdout)
def __repr__(self):
if inspect.stack()[1][3] == '?':
self()
return ''
return '<pydoc.Helper instance>'
_GoInteractive = object()
def __call__(self, request=_GoInteractive):
if request is not self._GoInteractive:
self.help(request)
else:
self.intro()
self.interact()
self.output.write('''
You are now leaving help and returning to the Python interpreter.
If you want to ask for help on a particular object directly from the
interpreter, you can type "help(object)". Executing "help('string')"
has the same effect as typing a particular string at the help> prompt.
''')
def interact(self):
self.output.write('\n')
while True:
try:
request = self.getline('help> ')
if not request: break
except (KeyboardInterrupt, EOFError):
break
request = strip(replace(request, '"', '', "'", ''))
if lower(request) in ('q', 'quit'): break
self.help(request)
def getline(self, prompt):
"""Read one line, using raw_input when available."""
if self.input is sys.stdin:
return raw_input(prompt)
else:
self.output.write(prompt)
self.output.flush()
return self.input.readline()
def help(self, request):
if type(request) is type(''):
request = request.strip()
if request == 'help': self.intro()
elif request == 'keywords': self.listkeywords()
elif request == 'symbols': self.listsymbols()
elif request == 'topics': self.listtopics()
elif request == 'modules': self.listmodules()
elif request[:8] == 'modules ':
self.listmodules(split(request)[1])
elif request in self.symbols: self.showsymbol(request)
elif request in self.keywords: self.showtopic(request)
elif request in self.topics: self.showtopic(request)
elif request: doc(request, 'Help on %s:')
elif isinstance(request, Helper): self()
else: doc(request, 'Help on %s:')
self.output.write('\n')
def intro(self):
self.output.write('''
Welcome to Python %s! This is the online help utility.
If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://docs.python.org/%s/tutorial/.
Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules. To quit this help utility and
return to the interpreter, just type "quit".
To get a list of available modules, keywords, or topics, type "modules",
"keywords", or "topics". Each module also comes with a one-line summary
of what it does; to list the modules whose summaries contain a given word
such as "spam", type "modules spam".
''' % tuple([sys.version[:3]]*2))
def list(self, items, columns=4, width=80):
items = items[:]
items.sort()
colw = width / columns
rows = (len(items) + columns - 1) / columns
for row in range(rows):
for col in range(columns):
i = col * rows + row
if i < len(items):
self.output.write(items[i])
if col < columns - 1:
self.output.write(' ' + ' ' * (colw-1 - len(items[i])))
self.output.write('\n')
def listkeywords(self):
self.output.write('''
Here is a list of the Python keywords. Enter any keyword to get more help.
''')
self.list(self.keywords.keys())
def listsymbols(self):
self.output.write('''
Here is a list of the punctuation symbols which Python assigns special meaning
to. Enter any symbol to get more help.
''')
self.list(self.symbols.keys())
def listtopics(self):
self.output.write('''
Here is a list of available topics. Enter any topic name to get more help.
''')
self.list(self.topics.keys())
def showtopic(self, topic, more_xrefs=''):
try:
import pydoc_data.topics
except ImportError:
self.output.write('''
Sorry, topic and keyword documentation is not available because the
module "pydoc_data.topics" could not be found.
''')
return
target = self.topics.get(topic, self.keywords.get(topic))
if not target:
self.output.write('no documentation found for %s\n' % repr(topic))
return
if type(target) is type(''):
return self.showtopic(target, more_xrefs)
label, xrefs = target
try:
doc = pydoc_data.topics.topics[label]
except KeyError:
self.output.write('no documentation found for %s\n' % repr(topic))
return
pager(strip(doc) + '\n')
if more_xrefs:
xrefs = (xrefs or '') + ' ' + more_xrefs
if xrefs:
import StringIO, formatter
buffer = StringIO.StringIO()
formatter.DumbWriter(buffer).send_flowing_data(
'Related help topics: ' + join(split(xrefs), ', ') + '\n')
self.output.write('\n%s\n' % buffer.getvalue())
def showsymbol(self, symbol):
target = self.symbols[symbol]
topic, _, xrefs = target.partition(' ')
self.showtopic(topic, xrefs)
def listmodules(self, key=''):
if key:
self.output.write('''
Here is a list of matching modules. Enter any module name to get more help.
''')
apropos(key)
else:
self.output.write('''
Please wait a moment while I gather a list of all available modules...
''')
modules = {}
def callback(path, modname, desc, modules=modules):
if modname and modname[-9:] == '.__init__':
modname = modname[:-9] + ' (package)'
if find(modname, '.') < 0:
modules[modname] = 1
def onerror(modname):
callback(None, modname, None)
ModuleScanner().run(callback, onerror=onerror)
self.list(modules.keys())
self.output.write('''
Enter any module name to get more help. Or, type "modules spam" to search
for modules whose descriptions contain the word "spam".
''')
help = Helper()
class Scanner:
"""A generic tree iterator."""
def __init__(self, roots, children, descendp):
self.roots = roots[:]
self.state = []
self.children = children
self.descendp = descendp
def next(self):
if not self.state:
if not self.roots:
return None
root = self.roots.pop(0)
self.state = [(root, self.children(root))]
node, children = self.state[-1]
if not children:
self.state.pop()
return self.next()
child = children.pop(0)
if self.descendp(child):
self.state.append((child, self.children(child)))
return child
class ModuleScanner:
"""An interruptible scanner that searches module synopses."""
def run(self, callback, key=None, completer=None, onerror=None):
if key: key = lower(key)
self.quit = False
seen = {}
for modname in sys.builtin_module_names:
if modname != '__main__':
seen[modname] = 1
if key is None:
callback(None, modname, '')
else:
desc = split(__import__(modname).__doc__ or '', '\n')[0]
if find(lower(modname + ' - ' + desc), key) >= 0:
callback(None, modname, desc)
for importer, modname, ispkg in pkgutil.walk_packages(onerror=onerror):
if self.quit:
break
if key is None:
callback(None, modname, '')
else:
loader = importer.find_module(modname)
if hasattr(loader,'get_source'):
import StringIO
desc = source_synopsis(
StringIO.StringIO(loader.get_source(modname))
) or ''
if hasattr(loader,'get_filename'):
path = loader.get_filename(modname)
else:
path = None
else:
module = loader.load_module(modname)
desc = module.__doc__.splitlines()[0] if module.__doc__ else ''
path = getattr(module,'__file__',None)
if find(lower(modname + ' - ' + desc), key) >= 0:
callback(path, modname, desc)
if completer:
completer()
def apropos(key):
"""Print all the one-line module summaries that contain a substring."""
def callback(path, modname, desc):
if modname[-9:] == '.__init__':
modname = modname[:-9] + ' (package)'
print modname, desc and '- ' + desc
def onerror(modname):
pass
with warnings.catch_warnings():
warnings.filterwarnings('ignore') # ignore problems during import
ModuleScanner().run(callback, key, onerror=onerror)
# --------------------------------------------------- web browser interface
def serve(port, callback=None, completer=None):
import BaseHTTPServer, mimetools, select
# Patch up mimetools.Message so it doesn't break if rfc822 is reloaded.
class Message(mimetools.Message):
def __init__(self, fp, seekable=1):
Message = self.__class__
Message.__bases__[0].__bases__[0].__init__(self, fp, seekable)
self.encodingheader = self.getheader('content-transfer-encoding')
self.typeheader = self.getheader('content-type')
self.parsetype()
self.parseplist()
class DocHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def send_document(self, title, contents):
try:
self.send_response(200)
self.send_header('Content-Type', 'text/html')
self.end_headers()
self.wfile.write(html.page(title, contents))
except IOError: pass
def do_GET(self):
path = self.path
if path[-5:] == '.html': path = path[:-5]
if path[:1] == '/': path = path[1:]
if path and path != '.':
try:
obj = locate(path, forceload=1)
except ErrorDuringImport, value:
self.send_document(path, html.escape(str(value)))
return
if obj:
self.send_document(describe(obj), html.document(obj, path))
else:
self.send_document(path,
'no Python documentation found for %s' % repr(path))
else:
heading = html.heading(
'<big><big><strong>Python: Index of Modules</strong></big></big>',
'#ffffff', '#7799ee')
def bltinlink(name):
return '<a href="%s.html">%s</a>' % (name, name)
names = filter(lambda x: x != '__main__',
sys.builtin_module_names)
contents = html.multicolumn(names, bltinlink)
indices = ['<p>' + html.bigsection(
'Built-in Modules', '#ffffff', '#ee77aa', contents)]
seen = {}
for dir in sys.path:
indices.append(html.index(dir, seen))
contents = heading + join(indices) + '''<p align=right>
<font color="#909090" face="helvetica, arial"><strong>
pydoc</strong> by Ka-Ping Yee <ping@lfw.org></font>'''
self.send_document('Index of Modules', contents)
def log_message(self, *args): pass
class DocServer(BaseHTTPServer.HTTPServer):
def __init__(self, port, callback):
host = 'localhost'
self.address = (host, port)
self.callback = callback
self.base.__init__(self, self.address, self.handler)
def serve_until_quit(self):
import select
self.quit = False
while not self.quit:
rd, wr, ex = select.select([self.socket.fileno()], [], [], 1)
if rd: self.handle_request()
def server_activate(self):
self.base.server_activate(self)
self.url = 'http://%s:%d/' % (self.address[0], self.server_port)
if self.callback: self.callback(self)
DocServer.base = BaseHTTPServer.HTTPServer
DocServer.handler = DocHandler
DocHandler.MessageClass = Message
try:
try:
DocServer(port, callback).serve_until_quit()
except (KeyboardInterrupt, select.error):
pass
finally:
if completer: completer()
# ----------------------------------------------------- graphical interface
def gui():
"""Graphical interface (starts web server and pops up a control window)."""
class GUI:
def __init__(self, window, port=7464):
self.window = window
self.server = None
self.scanner = None
import Tkinter
self.server_frm = Tkinter.Frame(window)
self.title_lbl = Tkinter.Label(self.server_frm,
text='Starting server...\n ')
self.open_btn = Tkinter.Button(self.server_frm,
text='open browser', command=self.open, state='disabled')
self.quit_btn = Tkinter.Button(self.server_frm,
text='quit serving', command=self.quit, state='disabled')
self.search_frm = Tkinter.Frame(window)
self.search_lbl = Tkinter.Label(self.search_frm, text='Search for')
self.search_ent = Tkinter.Entry(self.search_frm)
self.search_ent.bind('<Return>', self.search)
self.stop_btn = Tkinter.Button(self.search_frm,
text='stop', pady=0, command=self.stop, state='disabled')
if sys.platform == 'win32':
# Trying to hide and show this button crashes under Windows.
self.stop_btn.pack(side='right')
self.window.title('pydoc')
self.window.protocol('WM_DELETE_WINDOW', self.quit)
self.title_lbl.pack(side='top', fill='x')
self.open_btn.pack(side='left', fill='x', expand=1)
self.quit_btn.pack(side='right', fill='x', expand=1)
self.server_frm.pack(side='top', fill='x')
self.search_lbl.pack(side='left')
self.search_ent.pack(side='right', fill='x', expand=1)
self.search_frm.pack(side='top', fill='x')
self.search_ent.focus_set()
font = ('helvetica', sys.platform == 'win32' and 8 or 10)
self.result_lst = Tkinter.Listbox(window, font=font, height=6)
self.result_lst.bind('<Button-1>', self.select)
self.result_lst.bind('<Double-Button-1>', self.goto)
self.result_scr = Tkinter.Scrollbar(window,
orient='vertical', command=self.result_lst.yview)
self.result_lst.config(yscrollcommand=self.result_scr.set)
self.result_frm = Tkinter.Frame(window)
self.goto_btn = Tkinter.Button(self.result_frm,
text='go to selected', command=self.goto)
self.hide_btn = Tkinter.Button(self.result_frm,
text='hide results', command=self.hide)
self.goto_btn.pack(side='left', fill='x', expand=1)
self.hide_btn.pack(side='right', fill='x', expand=1)
self.window.update()
self.minwidth = self.window.winfo_width()
self.minheight = self.window.winfo_height()
self.bigminheight = (self.server_frm.winfo_reqheight() +
self.search_frm.winfo_reqheight() +
self.result_lst.winfo_reqheight() +
self.result_frm.winfo_reqheight())
self.bigwidth, self.bigheight = self.minwidth, self.bigminheight
self.expanded = 0
self.window.wm_geometry('%dx%d' % (self.minwidth, self.minheight))
self.window.wm_minsize(self.minwidth, self.minheight)
self.window.tk.willdispatch()
import threading
threading.Thread(
target=serve, args=(port, self.ready, self.quit)).start()
def ready(self, server):
self.server = server
self.title_lbl.config(
text='Python documentation server at\n' + server.url)
self.open_btn.config(state='normal')
self.quit_btn.config(state='normal')
def open(self, event=None, url=None):
url = url or self.server.url
try:
import webbrowser
webbrowser.open(url)
except ImportError: # pre-webbrowser.py compatibility
if sys.platform == 'win32':
os.system('start "%s"' % url)
else:
rc = os.system('netscape -remote "openURL(%s)" &' % url)
if rc: os.system('netscape "%s" &' % url)
def quit(self, event=None):
if self.server:
self.server.quit = 1
self.window.quit()
def search(self, event=None):
key = self.search_ent.get()
self.stop_btn.pack(side='right')
self.stop_btn.config(state='normal')
self.search_lbl.config(text='Searching for "%s"...' % key)
self.search_ent.forget()
self.search_lbl.pack(side='left')
self.result_lst.delete(0, 'end')
self.goto_btn.config(state='disabled')
self.expand()
import threading
if self.scanner:
self.scanner.quit = 1
self.scanner = ModuleScanner()
def onerror(modname):
pass
threading.Thread(target=self.scanner.run,
args=(self.update, key, self.done),
kwargs=dict(onerror=onerror)).start()
def update(self, path, modname, desc):
if modname[-9:] == '.__init__':
modname = modname[:-9] + ' (package)'
self.result_lst.insert('end',
modname + ' - ' + (desc or '(no description)'))
def stop(self, event=None):
if self.scanner:
self.scanner.quit = 1
self.scanner = None
def done(self):
self.scanner = None
self.search_lbl.config(text='Search for')
self.search_lbl.pack(side='left')
self.search_ent.pack(side='right', fill='x', expand=1)
if sys.platform != 'win32': self.stop_btn.forget()
self.stop_btn.config(state='disabled')
def select(self, event=None):
self.goto_btn.config(state='normal')
def goto(self, event=None):
selection = self.result_lst.curselection()
if selection:
modname = split(self.result_lst.get(selection[0]))[0]
self.open(url=self.server.url + modname + '.html')
def collapse(self):
if not self.expanded: return
self.result_frm.forget()
self.result_scr.forget()
self.result_lst.forget()
self.bigwidth = self.window.winfo_width()
self.bigheight = self.window.winfo_height()
self.window.wm_geometry('%dx%d' % (self.minwidth, self.minheight))
self.window.wm_minsize(self.minwidth, self.minheight)
self.expanded = 0
def expand(self):
if self.expanded: return
self.result_frm.pack(side='bottom', fill='x')
self.result_scr.pack(side='right', fill='y')
self.result_lst.pack(side='top', fill='both', expand=1)
self.window.wm_geometry('%dx%d' % (self.bigwidth, self.bigheight))
self.window.wm_minsize(self.minwidth, self.bigminheight)
self.expanded = 1
def hide(self, event=None):
self.stop()
self.collapse()
import Tkinter
try:
root = Tkinter.Tk()
# Tk will crash if pythonw.exe has an XP .manifest
# file and the root has is not destroyed explicitly.
# If the problem is ever fixed in Tk, the explicit
# destroy can go.
try:
gui = GUI(root)
root.mainloop()
finally:
root.destroy()
except KeyboardInterrupt:
pass
# -------------------------------------------------- command-line interface
def ispath(x):
return isinstance(x, str) and find(x, os.sep) >= 0
def cli():
"""Command-line interface (looks at sys.argv to decide what to do)."""
import getopt
class BadUsage: pass
# Scripts don't get the current directory in their path by default
# unless they are run with the '-m' switch
if '' not in sys.path:
scriptdir = os.path.dirname(sys.argv[0])
if scriptdir in sys.path:
sys.path.remove(scriptdir)
sys.path.insert(0, '.')
try:
opts, args = getopt.getopt(sys.argv[1:], 'gk:p:w')
writing = 0
for opt, val in opts:
if opt == '-g':
gui()
return
if opt == '-k':
apropos(val)
return
if opt == '-p':
try:
port = int(val)
except ValueError:
raise BadUsage
def ready(server):
print 'pydoc server ready at %s' % server.url
def stopped():
print 'pydoc server stopped'
serve(port, ready, stopped)
return
if opt == '-w':
writing = 1
if not args: raise BadUsage
for arg in args:
if ispath(arg) and not os.path.exists(arg):
print 'file %r does not exist' % arg
break
try:
if ispath(arg) and os.path.isfile(arg):
arg = importfile(arg)
if writing:
if ispath(arg) and os.path.isdir(arg):
writedocs(arg)
else:
writedoc(arg)
else:
help.help(arg)
except ErrorDuringImport, value:
print value
except (getopt.error, BadUsage):
cmd = os.path.basename(sys.argv[0])
print """pydoc - the Python documentation tool
%s <name> ...
Show text documentation on something. <name> may be the name of a
Python keyword, topic, function, module, or package, or a dotted
reference to a class or function within a module or module in a
package. If <name> contains a '%s', it is used as the path to a
Python source file to document. If name is 'keywords', 'topics',
or 'modules', a listing of these things is displayed.
%s -k <keyword>
Search for a keyword in the synopsis lines of all available modules.
%s -p <port>
Start an HTTP server on the given port on the local machine. Port
number 0 can be used to get an arbitrary unused port.
%s -g
Pop up a graphical interface for finding and serving documentation.
%s -w <name> ...
Write out the HTML documentation for a module to a file in the current
directory. If <name> contains a '%s', it is treated as a filename; if
it names a directory, documentation is written for all the contents.
""" % (cmd, os.sep, cmd, cmd, cmd, cmd, os.sep)
if __name__ == '__main__': cli()
| gpl-3.0 |
josephxsxn/alchemists_notepad | Tests.py | 1 | 6304 | #List all ENUMS
from Object.Ingredient import Ingredient
for i in Ingredient:
print(i)
from Object.PotionColor import PotionColor
for r in PotionColor:
print(r)
from Object.PotionSign import PotionSign
for r in PotionSign:
print(r)
#//TODO
#NEED TO ADD ALCHEMICAL ENUMS HERE
#Make a Potion and Fetch its values
from Object.Potion import Potion
from Object.PotionColor import PotionColor
from Object.PotionSign import PotionSign
flowertoad = Potion(Ingredient.TOAD, Ingredient.FLOWER, PotionColor.RED, PotionSign.POSITIVE)
print(flowertoad.get_ingredients())
print(flowertoad.get_color())
print(flowertoad.get_sign())
###Put some Potions in the List and Get back
from Object.PotionList import PotionList
polist = PotionList()
polist.add_potion(flowertoad)
pores = polist.get_potions()
for po in pores:
print(po.get_ingredients())
print(po.get_color())
print(po.get_sign())
#Get an exact one from the list
pores = polist.get_potion(0)
print(pores.get_ingredients())
print(pores.get_color())
print(pores.get_sign())
#fetch one that doesnt exist from the list
pores = polist.get_potion(1)
print(pores)
#make an few Alchemicals
from Object.Alchemical import Alchemical
from Object.AlchemicalColor import AlchemicalColor
from Object.AlchemicalSign import AlchemicalSign
from Object.AlchemicalSize import AlchemicalSize
#triplet one
redposlarge = Alchemical(AlchemicalColor.RED, AlchemicalSign.POSITIVE, AlchemicalSize.LARGE)
bluenegsmall = Alchemical(AlchemicalColor.BLUE, AlchemicalSign.NEGATIVE, AlchemicalSize.SMALL)
greennegsmall = Alchemical(AlchemicalColor.GREEN, AlchemicalSign.NEGATIVE, AlchemicalSize.SMALL)
#triplet two
redpossmall = Alchemical(AlchemicalColor.RED, AlchemicalSign.POSITIVE, AlchemicalSize.SMALL)
bluepossmall = Alchemical(AlchemicalColor.BLUE, AlchemicalSign.POSITIVE, AlchemicalSize.SMALL)
greenposlarge = Alchemical(AlchemicalColor.GREEN, AlchemicalSign.POSITIVE, AlchemicalSize.SMALL)
print('T1 ' + str(redposlarge.get_color()) + ' ' + str(redposlarge.get_sign()) + ' ' + str(redposlarge.get_size()))
print('T1 ' + str(bluenegsmall.get_color()) + ' ' + str(bluenegsmall.get_sign()) + ' ' + str(bluenegsmall.get_size()))
print('T1 ' + str(greennegsmall.get_color()) + ' ' + str(greennegsmall.get_sign()) + ' ' + str(greennegsmall.get_size()))
print('T2 ' + str(redpossmall.get_color()) + ' ' + str(redpossmall.get_sign()) + ' ' + str(redpossmall.get_size()))
print('T2 ' + str(bluepossmall.get_color()) + ' ' + str(bluepossmall.get_sign()) + ' ' + str(bluepossmall.get_size()))
print('T2 ' + str(greenposlarge.get_color()) + ' ' + str(greenposlarge.get_sign()) + ' ' + str(greenposlarge.get_size()))
#make a Triplet
from Object.AlchemicalTriplet import AlchemicalTriplet
triplet_one = AlchemicalTriplet([redposlarge, bluenegsmall, greennegsmall])
triplet_one_list = triplet_one.get_alchemicals()
for a in triplet_one_list:
print('Triplet_ONE ' + str(a.get_color()) + ' ' + str(a.get_sign()) + ' ' + str(a.get_size()))
triplet_two = AlchemicalTriplet([redpossmall, bluepossmall, greenposlarge])
triplet_two_list = triplet_two.get_alchemicals()
print(triplet_two_list)
for b in triplet_two_list:
print('Triplet_TWO ' + str(b.get_color()) + ' ' + str(b.get_sign()) + ' ' + str(b.get_size()))
#make some ingredients and properties
from Object.IngredientProperties import IngredientProperties
ip = IngredientProperties(Ingredient.TOAD)
print(str(ip.get_name()))
print(ip.get_alchemical_options())
ip.set_alchemical_options([triplet_one])
ip_triplet_list = ip.get_alchemical_options()
#for given ingredient list all triplet props
for l in ip_triplet_list:
for a in l.get_alchemicals():
print('IngredientProps ' + str(a.get_color()) + ' ' + str(a.get_sign()) + ' ' + str(a.get_size()))
#Alchemical Combinations Test
from Routine.AlchemicalCombinations import AlchemicalCombinations
ingredient_dic = {Ingredient.TOAD : ip}
print(ingredient_dic.keys())
triplet_list = ingredient_dic[Ingredient.TOAD].get_alchemical_options()
for triplet in triplet_list:
for a in triplet.get_alchemicals():
print('AC Combos ' + str(a.get_color()) + ' ' + str(a.get_sign()) + ' ' + str(a.get_size()))
ac = AlchemicalCombinations()
res = ac.reduce_potion_alchemicals(polist.get_potion(0), ingredient_dic)
print(polist.get_potion(0).get_ingredients())
print(polist.get_potion(0).get_sign())
print(polist.get_potion(0).get_color())
print(res.keys())
triplet_list = res[Ingredient.TOAD]
for triplet in triplet_list:
for a in triplet.get_alchemicals():
print('Filtered Toad Combos ' + str(a.get_color()) + ' ' + str(a.get_sign()) + ' ' + str(a.get_size()))
print(len(res[Ingredient.TOAD]))
print(len(res[Ingredient.FLOWER]))
#triplet_list = res[Ingredient.FLOWER]
#for triplet in triplet_list:
# for a in triplet.get_alchemicals():
# print('Filtered Flower Combos ' + str(a.get_color()) + ' ' + str(a.get_sign()) + ' ' + str(a.get_size()))
ip = IngredientProperties(Ingredient.FLOWER)
print(str(ip.get_name()))
print(ip.get_alchemical_options())
ip.set_alchemical_options(res[Ingredient.FLOWER])
ingredient_dic[Ingredient.FLOWER] = ip
print('TOAD LEN ' + str(len(ingredient_dic[Ingredient.TOAD].get_alchemical_options())))
print('FLOWER LEN ' + str(len(ingredient_dic[Ingredient.FLOWER].get_alchemical_options())))
initalTriplets = ac.inital_alchemical_options()
print(len(initalTriplets))
print(len(ac.potion_only_filter(initalTriplets, polist.get_potion(0).get_color(), polist.get_potion(0).get_sign())))
#################
###NEUTRAL POTION
#################
herbtoad = Potion(Ingredient.TOAD, Ingredient.HERB, PotionColor.NEUTRAL, PotionSign.NEUTRAL)
polist.add_potion(herbtoad)
#ac2 = AlchemicalCombinations()
res = ac.reduce_potion_alchemicals(herbtoad, ingredient_dic)
print(polist.get_potion(1).get_ingredients())
print(polist.get_potion(1).get_sign())
print(polist.get_potion(1).get_color())
print(res.keys())
print('TOAD LEN RES: ' + str(len(res[Ingredient.TOAD])))
print('HERB LEN RES: ' + str(len(res[Ingredient.HERB])))
ip = IngredientProperties(Ingredient.TOAD)
print(str(ip.get_name()))
ip.set_alchemical_options(res[Ingredient.TOAD])
ingredient_dic[Ingredient.TOAD] = ip
ip = IngredientProperties(Ingredient.HERB)
print(str(ip.get_name()))
ip.set_alchemical_options(res[Ingredient.HERB])
ingredient_dic[Ingredient.HERB] = ip
print(ingredient_dic.keys())
| apache-2.0 |
JustinSelig/CeRI-NLP-Comment-Evaluation | xlrd-0.9.3/tests/test_open_workbook.py | 9 | 1294 | from unittest import TestCase
import os
from xlrd import open_workbook
from .base import from_this_dir
class TestOpen(TestCase):
# test different uses of open_workbook
def test_names_demo(self):
# For now, we just check this doesn't raise an error.
open_workbook(
from_this_dir(os.path.join('..','xlrd','examples','namesdemo.xls'))
)
def test_ragged_rows_tidied_with_formatting(self):
# For now, we just check this doesn't raise an error.
open_workbook(from_this_dir('issue20.xls'),
formatting_info=True)
def test_BYTES_X00(self):
# For now, we just check this doesn't raise an error.
open_workbook(from_this_dir('picture_in_cell.xls'),
formatting_info=True)
def test_xlsx_simple(self):
# For now, we just check this doesn't raise an error.
open_workbook(from_this_dir('text_bar.xlsx'))
# we should make assertions here that data has been
# correctly processed.
def test_xlsx(self):
# For now, we just check this doesn't raise an error.
open_workbook(from_this_dir('reveng1.xlsx'))
# we should make assertions here that data has been
# correctly processed.
| mit |
therandomcode/WikiWriter | lib/requests/packages/urllib3/exceptions.py | 196 | 5440 | from __future__ import absolute_import
# Base Exceptions
class HTTPError(Exception):
"Base exception used by this module."
pass
class HTTPWarning(Warning):
"Base warning used by this module."
pass
class PoolError(HTTPError):
"Base exception for errors caused within a pool."
def __init__(self, pool, message):
self.pool = pool
HTTPError.__init__(self, "%s: %s" % (pool, message))
def __reduce__(self):
# For pickling purposes.
return self.__class__, (None, None)
class RequestError(PoolError):
"Base exception for PoolErrors that have associated URLs."
def __init__(self, pool, url, message):
self.url = url
PoolError.__init__(self, pool, message)
def __reduce__(self):
# For pickling purposes.
return self.__class__, (None, self.url, None)
class SSLError(HTTPError):
"Raised when SSL certificate fails in an HTTPS connection."
pass
class ProxyError(HTTPError):
"Raised when the connection to a proxy fails."
pass
class DecodeError(HTTPError):
"Raised when automatic decoding based on Content-Type fails."
pass
class ProtocolError(HTTPError):
"Raised when something unexpected happens mid-request/response."
pass
#: Renamed to ProtocolError but aliased for backwards compatibility.
ConnectionError = ProtocolError
# Leaf Exceptions
class MaxRetryError(RequestError):
"""Raised when the maximum number of retries is exceeded.
:param pool: The connection pool
:type pool: :class:`~urllib3.connectionpool.HTTPConnectionPool`
:param string url: The requested Url
:param exceptions.Exception reason: The underlying error
"""
def __init__(self, pool, url, reason=None):
self.reason = reason
message = "Max retries exceeded with url: %s (Caused by %r)" % (
url, reason)
RequestError.__init__(self, pool, url, message)
class HostChangedError(RequestError):
"Raised when an existing pool gets a request for a foreign host."
def __init__(self, pool, url, retries=3):
message = "Tried to open a foreign host with url: %s" % url
RequestError.__init__(self, pool, url, message)
self.retries = retries
class TimeoutStateError(HTTPError):
""" Raised when passing an invalid state to a timeout """
pass
class TimeoutError(HTTPError):
""" Raised when a socket timeout error occurs.
Catching this error will catch both :exc:`ReadTimeoutErrors
<ReadTimeoutError>` and :exc:`ConnectTimeoutErrors <ConnectTimeoutError>`.
"""
pass
class ReadTimeoutError(TimeoutError, RequestError):
"Raised when a socket timeout occurs while receiving data from a server"
pass
# This timeout error does not have a URL attached and needs to inherit from the
# base HTTPError
class ConnectTimeoutError(TimeoutError):
"Raised when a socket timeout occurs while connecting to a server"
pass
class NewConnectionError(ConnectTimeoutError, PoolError):
"Raised when we fail to establish a new connection. Usually ECONNREFUSED."
pass
class EmptyPoolError(PoolError):
"Raised when a pool runs out of connections and no more are allowed."
pass
class ClosedPoolError(PoolError):
"Raised when a request enters a pool after the pool has been closed."
pass
class LocationValueError(ValueError, HTTPError):
"Raised when there is something wrong with a given URL input."
pass
class LocationParseError(LocationValueError):
"Raised when get_host or similar fails to parse the URL input."
def __init__(self, location):
message = "Failed to parse: %s" % location
HTTPError.__init__(self, message)
self.location = location
class ResponseError(HTTPError):
"Used as a container for an error reason supplied in a MaxRetryError."
GENERIC_ERROR = 'too many error responses'
SPECIFIC_ERROR = 'too many {status_code} error responses'
class SecurityWarning(HTTPWarning):
"Warned when perfoming security reducing actions"
pass
class SubjectAltNameWarning(SecurityWarning):
"Warned when connecting to a host with a certificate missing a SAN."
pass
class InsecureRequestWarning(SecurityWarning):
"Warned when making an unverified HTTPS request."
pass
class SystemTimeWarning(SecurityWarning):
"Warned when system time is suspected to be wrong"
pass
class InsecurePlatformWarning(SecurityWarning):
"Warned when certain SSL configuration is not available on a platform."
pass
class SNIMissingWarning(HTTPWarning):
"Warned when making a HTTPS request without SNI available."
pass
class ResponseNotChunked(ProtocolError, ValueError):
"Response needs to be chunked in order to read it as chunks."
pass
class ProxySchemeUnknown(AssertionError, ValueError):
"ProxyManager does not support the supplied scheme"
# TODO(t-8ch): Stop inheriting from AssertionError in v2.0.
def __init__(self, scheme):
message = "Not supported proxy scheme %s" % scheme
super(ProxySchemeUnknown, self).__init__(message)
class HeaderParsingError(HTTPError):
"Raised by assert_header_parsing, but we convert it to a log.warning statement."
def __init__(self, defects, unparsed_data):
message = '%s, unparsed data: %r' % (defects or 'Unknown', unparsed_data)
super(HeaderParsingError, self).__init__(message)
| apache-2.0 |
houzhenggang/hiwifi-openwrt-HC5661-HC5761 | staging_dir/target-mipsel_r2_uClibc-0.9.33.2/root-ralink/usr/lib/python2.7/fpformat.py | 322 | 4699 | """General floating point formatting functions.
Functions:
fix(x, digits_behind)
sci(x, digits_behind)
Each takes a number or a string and a number of digits as arguments.
Parameters:
x: number to be formatted; or a string resembling a number
digits_behind: number of digits behind the decimal point
"""
from warnings import warnpy3k
warnpy3k("the fpformat module has been removed in Python 3.0", stacklevel=2)
del warnpy3k
import re
__all__ = ["fix","sci","NotANumber"]
# Compiled regular expression to "decode" a number
decoder = re.compile(r'^([-+]?)0*(\d*)((?:\.\d*)?)(([eE][-+]?\d+)?)$')
# \0 the whole thing
# \1 leading sign or empty
# \2 digits left of decimal point
# \3 fraction (empty or begins with point)
# \4 exponent part (empty or begins with 'e' or 'E')
try:
class NotANumber(ValueError):
pass
except TypeError:
NotANumber = 'fpformat.NotANumber'
def extract(s):
"""Return (sign, intpart, fraction, expo) or raise an exception:
sign is '+' or '-'
intpart is 0 or more digits beginning with a nonzero
fraction is 0 or more digits
expo is an integer"""
res = decoder.match(s)
if res is None: raise NotANumber, s
sign, intpart, fraction, exppart = res.group(1,2,3,4)
if sign == '+': sign = ''
if fraction: fraction = fraction[1:]
if exppart: expo = int(exppart[1:])
else: expo = 0
return sign, intpart, fraction, expo
def unexpo(intpart, fraction, expo):
"""Remove the exponent by changing intpart and fraction."""
if expo > 0: # Move the point left
f = len(fraction)
intpart, fraction = intpart + fraction[:expo], fraction[expo:]
if expo > f:
intpart = intpart + '0'*(expo-f)
elif expo < 0: # Move the point right
i = len(intpart)
intpart, fraction = intpart[:expo], intpart[expo:] + fraction
if expo < -i:
fraction = '0'*(-expo-i) + fraction
return intpart, fraction
def roundfrac(intpart, fraction, digs):
"""Round or extend the fraction to size digs."""
f = len(fraction)
if f <= digs:
return intpart, fraction + '0'*(digs-f)
i = len(intpart)
if i+digs < 0:
return '0'*-digs, ''
total = intpart + fraction
nextdigit = total[i+digs]
if nextdigit >= '5': # Hard case: increment last digit, may have carry!
n = i + digs - 1
while n >= 0:
if total[n] != '9': break
n = n-1
else:
total = '0' + total
i = i+1
n = 0
total = total[:n] + chr(ord(total[n]) + 1) + '0'*(len(total)-n-1)
intpart, fraction = total[:i], total[i:]
if digs >= 0:
return intpart, fraction[:digs]
else:
return intpart[:digs] + '0'*-digs, ''
def fix(x, digs):
"""Format x as [-]ddd.ddd with 'digs' digits after the point
and at least one digit before.
If digs <= 0, the point is suppressed."""
if type(x) != type(''): x = repr(x)
try:
sign, intpart, fraction, expo = extract(x)
except NotANumber:
return x
intpart, fraction = unexpo(intpart, fraction, expo)
intpart, fraction = roundfrac(intpart, fraction, digs)
while intpart and intpart[0] == '0': intpart = intpart[1:]
if intpart == '': intpart = '0'
if digs > 0: return sign + intpart + '.' + fraction
else: return sign + intpart
def sci(x, digs):
"""Format x as [-]d.dddE[+-]ddd with 'digs' digits after the point
and exactly one digit before.
If digs is <= 0, one digit is kept and the point is suppressed."""
if type(x) != type(''): x = repr(x)
sign, intpart, fraction, expo = extract(x)
if not intpart:
while fraction and fraction[0] == '0':
fraction = fraction[1:]
expo = expo - 1
if fraction:
intpart, fraction = fraction[0], fraction[1:]
expo = expo - 1
else:
intpart = '0'
else:
expo = expo + len(intpart) - 1
intpart, fraction = intpart[0], intpart[1:] + fraction
digs = max(0, digs)
intpart, fraction = roundfrac(intpart, fraction, digs)
if len(intpart) > 1:
intpart, fraction, expo = \
intpart[0], intpart[1:] + fraction[:-1], \
expo + len(intpart) - 1
s = sign + intpart
if digs > 0: s = s + '.' + fraction
e = repr(abs(expo))
e = '0'*(3-len(e)) + e
if expo < 0: e = '-' + e
else: e = '+' + e
return s + 'e' + e
def test():
"""Interactive test run."""
try:
while 1:
x, digs = input('Enter (x, digs): ')
print x, fix(x, digs), sci(x, digs)
except (EOFError, KeyboardInterrupt):
pass
| gpl-2.0 |
silvesterlee/linux | scripts/gdb/linux/symbols.py | 588 | 6302 | #
# gdb helper commands and functions for Linux kernel debugging
#
# load kernel and module symbols
#
# Copyright (c) Siemens AG, 2011-2013
#
# Authors:
# Jan Kiszka <jan.kiszka@siemens.com>
#
# This work is licensed under the terms of the GNU GPL version 2.
#
import gdb
import os
import re
from linux import modules
if hasattr(gdb, 'Breakpoint'):
class LoadModuleBreakpoint(gdb.Breakpoint):
def __init__(self, spec, gdb_command):
super(LoadModuleBreakpoint, self).__init__(spec, internal=True)
self.silent = True
self.gdb_command = gdb_command
def stop(self):
module = gdb.parse_and_eval("mod")
module_name = module['name'].string()
cmd = self.gdb_command
# enforce update if object file is not found
cmd.module_files_updated = False
# Disable pagination while reporting symbol (re-)loading.
# The console input is blocked in this context so that we would
# get stuck waiting for the user to acknowledge paged output.
show_pagination = gdb.execute("show pagination", to_string=True)
pagination = show_pagination.endswith("on.\n")
gdb.execute("set pagination off")
if module_name in cmd.loaded_modules:
gdb.write("refreshing all symbols to reload module "
"'{0}'\n".format(module_name))
cmd.load_all_symbols()
else:
cmd.load_module_symbols(module)
# restore pagination state
gdb.execute("set pagination %s" % ("on" if pagination else "off"))
return False
class LxSymbols(gdb.Command):
"""(Re-)load symbols of Linux kernel and currently loaded modules.
The kernel (vmlinux) is taken from the current working directly. Modules (.ko)
are scanned recursively, starting in the same directory. Optionally, the module
search path can be extended by a space separated list of paths passed to the
lx-symbols command."""
module_paths = []
module_files = []
module_files_updated = False
loaded_modules = []
breakpoint = None
def __init__(self):
super(LxSymbols, self).__init__("lx-symbols", gdb.COMMAND_FILES,
gdb.COMPLETE_FILENAME)
def _update_module_files(self):
self.module_files = []
for path in self.module_paths:
gdb.write("scanning for modules in {0}\n".format(path))
for root, dirs, files in os.walk(path):
for name in files:
if name.endswith(".ko"):
self.module_files.append(root + "/" + name)
self.module_files_updated = True
def _get_module_file(self, module_name):
module_pattern = ".*/{0}\.ko$".format(
module_name.replace("_", r"[_\-]"))
for name in self.module_files:
if re.match(module_pattern, name) and os.path.exists(name):
return name
return None
def _section_arguments(self, module):
try:
sect_attrs = module['sect_attrs'].dereference()
except gdb.error:
return ""
attrs = sect_attrs['attrs']
section_name_to_address = {
attrs[n]['name'].string(): attrs[n]['address']
for n in range(int(sect_attrs['nsections']))}
args = []
for section_name in [".data", ".data..read_mostly", ".rodata", ".bss"]:
address = section_name_to_address.get(section_name)
if address:
args.append(" -s {name} {addr}".format(
name=section_name, addr=str(address)))
return "".join(args)
def load_module_symbols(self, module):
module_name = module['name'].string()
module_addr = str(module['module_core']).split()[0]
module_file = self._get_module_file(module_name)
if not module_file and not self.module_files_updated:
self._update_module_files()
module_file = self._get_module_file(module_name)
if module_file:
gdb.write("loading @{addr}: {filename}\n".format(
addr=module_addr, filename=module_file))
cmdline = "add-symbol-file {filename} {addr}{sections}".format(
filename=module_file,
addr=module_addr,
sections=self._section_arguments(module))
gdb.execute(cmdline, to_string=True)
if module_name not in self.loaded_modules:
self.loaded_modules.append(module_name)
else:
gdb.write("no module object found for '{0}'\n".format(module_name))
def load_all_symbols(self):
gdb.write("loading vmlinux\n")
# Dropping symbols will disable all breakpoints. So save their states
# and restore them afterward.
saved_states = []
if hasattr(gdb, 'breakpoints') and not gdb.breakpoints() is None:
for bp in gdb.breakpoints():
saved_states.append({'breakpoint': bp, 'enabled': bp.enabled})
# drop all current symbols and reload vmlinux
gdb.execute("symbol-file", to_string=True)
gdb.execute("symbol-file vmlinux")
self.loaded_modules = []
module_list = modules.module_list()
if not module_list:
gdb.write("no modules found\n")
else:
[self.load_module_symbols(module) for module in module_list]
for saved_state in saved_states:
saved_state['breakpoint'].enabled = saved_state['enabled']
def invoke(self, arg, from_tty):
self.module_paths = arg.split()
self.module_paths.append(os.getcwd())
# enforce update
self.module_files = []
self.module_files_updated = False
self.load_all_symbols()
if hasattr(gdb, 'Breakpoint'):
if self.breakpoint is not None:
self.breakpoint.delete()
self.breakpoint = None
self.breakpoint = LoadModuleBreakpoint(
"kernel/module.c:do_init_module", self)
else:
gdb.write("Note: symbol update on module loading not supported "
"with this gdb version\n")
LxSymbols()
| gpl-2.0 |
GoogleChromeLabs/wasm-av1 | third_party/aom/tools/lint-hunks.py | 20 | 5088 | #!/usr/bin/python
##
## Copyright (c) 2016, Alliance for Open Media. All rights reserved
##
## This source code is subject to the terms of the BSD 2 Clause License and
## the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
## was not distributed with this source code in the LICENSE file, you can
## obtain it at www.aomedia.org/license/software. If the Alliance for Open
## Media Patent License 1.0 was not distributed with this source code in the
## PATENTS file, you can obtain it at www.aomedia.org/license/patent.
##
"""Performs style checking on each diff hunk."""
import getopt
import os
import StringIO
import subprocess
import sys
import diff
SHORT_OPTIONS = "h"
LONG_OPTIONS = ["help"]
TOPLEVEL_CMD = ["git", "rev-parse", "--show-toplevel"]
DIFF_CMD = ["git", "diff"]
DIFF_INDEX_CMD = ["git", "diff-index", "-u", "HEAD", "--"]
SHOW_CMD = ["git", "show"]
CPPLINT_FILTERS = ["-readability/casting"]
class Usage(Exception):
pass
class SubprocessException(Exception):
def __init__(self, args):
msg = "Failed to execute '%s'"%(" ".join(args))
super(SubprocessException, self).__init__(msg)
class Subprocess(subprocess.Popen):
"""Adds the notion of an expected returncode to Popen."""
def __init__(self, args, expected_returncode=0, **kwargs):
self._args = args
self._expected_returncode = expected_returncode
super(Subprocess, self).__init__(args, **kwargs)
def communicate(self, *args, **kwargs):
result = super(Subprocess, self).communicate(*args, **kwargs)
if self._expected_returncode is not None:
try:
ok = self.returncode in self._expected_returncode
except TypeError:
ok = self.returncode == self._expected_returncode
if not ok:
raise SubprocessException(self._args)
return result
def main(argv=None):
if argv is None:
argv = sys.argv
try:
try:
opts, args = getopt.getopt(argv[1:], SHORT_OPTIONS, LONG_OPTIONS)
except getopt.error, msg:
raise Usage(msg)
# process options
for o, _ in opts:
if o in ("-h", "--help"):
print __doc__
sys.exit(0)
if args and len(args) > 1:
print __doc__
sys.exit(0)
# Find the fully qualified path to the root of the tree
tl = Subprocess(TOPLEVEL_CMD, stdout=subprocess.PIPE)
tl = tl.communicate()[0].strip()
# See if we're working on the index or not.
if args:
diff_cmd = DIFF_CMD + [args[0] + "^!"]
else:
diff_cmd = DIFF_INDEX_CMD
# Build the command line to execute cpplint
cpplint_cmd = [os.path.join(tl, "tools", "cpplint.py"),
"--filter=" + ",".join(CPPLINT_FILTERS),
"-"]
# Get a list of all affected lines
file_affected_line_map = {}
p = Subprocess(diff_cmd, stdout=subprocess.PIPE)
stdout = p.communicate()[0]
for hunk in diff.ParseDiffHunks(StringIO.StringIO(stdout)):
filename = hunk.right.filename[2:]
if filename not in file_affected_line_map:
file_affected_line_map[filename] = set()
file_affected_line_map[filename].update(hunk.right.delta_line_nums)
# Run each affected file through cpplint
lint_failed = False
for filename, affected_lines in file_affected_line_map.iteritems():
if filename.split(".")[-1] not in ("c", "h", "cc"):
continue
if args:
# File contents come from git
show_cmd = SHOW_CMD + [args[0] + ":" + filename]
show = Subprocess(show_cmd, stdout=subprocess.PIPE)
lint = Subprocess(cpplint_cmd, expected_returncode=(0, 1),
stdin=show.stdout, stderr=subprocess.PIPE)
lint_out = lint.communicate()[1]
else:
# File contents come from the working tree
lint = Subprocess(cpplint_cmd, expected_returncode=(0, 1),
stdin=subprocess.PIPE, stderr=subprocess.PIPE)
stdin = open(os.path.join(tl, filename)).read()
lint_out = lint.communicate(stdin)[1]
for line in lint_out.split("\n"):
fields = line.split(":")
if fields[0] != "-":
continue
warning_line_num = int(fields[1])
if warning_line_num in affected_lines:
print "%s:%d:%s"%(filename, warning_line_num,
":".join(fields[2:]))
lint_failed = True
# Set exit code if any relevant lint errors seen
if lint_failed:
return 1
except Usage, err:
print >>sys.stderr, err
print >>sys.stderr, "for help use --help"
return 2
if __name__ == "__main__":
sys.exit(main())
| apache-2.0 |
Ditmar/plugin.video.pelisalacarta | lib/gdata/tlslite/integration/TLSSocketServerMixIn.py | 320 | 2203 | """TLS Lite + SocketServer."""
from gdata.tlslite.TLSConnection import TLSConnection
class TLSSocketServerMixIn:
"""
This class can be mixed in with any L{SocketServer.TCPServer} to
add TLS support.
To use this class, define a new class that inherits from it and
some L{SocketServer.TCPServer} (with the mix-in first). Then
implement the handshake() method, doing some sort of server
handshake on the connection argument. If the handshake method
returns True, the RequestHandler will be triggered. Below is a
complete example of a threaded HTTPS server::
from SocketServer import *
from BaseHTTPServer import *
from SimpleHTTPServer import *
from tlslite.api import *
s = open("./serverX509Cert.pem").read()
x509 = X509()
x509.parse(s)
certChain = X509CertChain([x509])
s = open("./serverX509Key.pem").read()
privateKey = parsePEMKey(s, private=True)
sessionCache = SessionCache()
class MyHTTPServer(ThreadingMixIn, TLSSocketServerMixIn,
HTTPServer):
def handshake(self, tlsConnection):
try:
tlsConnection.handshakeServer(certChain=certChain,
privateKey=privateKey,
sessionCache=sessionCache)
tlsConnection.ignoreAbruptClose = True
return True
except TLSError, error:
print "Handshake failure:", str(error)
return False
httpd = MyHTTPServer(('localhost', 443), SimpleHTTPRequestHandler)
httpd.serve_forever()
"""
def finish_request(self, sock, client_address):
tlsConnection = TLSConnection(sock)
if self.handshake(tlsConnection) == True:
self.RequestHandlerClass(tlsConnection, client_address, self)
tlsConnection.close()
#Implement this method to do some form of handshaking. Return True
#if the handshake finishes properly and the request is authorized.
def handshake(self, tlsConnection):
raise NotImplementedError()
| gpl-3.0 |
mapycz/mapnik | scons/scons-local-3.0.1/SCons/Options/BoolOption.py | 5 | 1993 | #
# Copyright (c) 2001 - 2017 The SCons Foundation
#
# 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.
#
__revision__ = "src/engine/SCons/Options/BoolOption.py 74b2c53bc42290e911b334a6b44f187da698a668 2017/11/14 13:16:53 bdbaddog"
__doc__ = """Place-holder for the old SCons.Options module hierarchy
This is for backwards compatibility. The new equivalent is the Variables/
class hierarchy. These will have deprecation warnings added (some day),
and will then be removed entirely (some day).
"""
import SCons.Variables
import SCons.Warnings
warned = False
def BoolOption(*args, **kw):
global warned
if not warned:
msg = "The BoolOption() function is deprecated; use the BoolVariable() function instead."
SCons.Warnings.warn(SCons.Warnings.DeprecatedOptionsWarning, msg)
warned = True
return SCons.Variables.BoolVariable(*args, **kw)
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| lgpl-2.1 |
kata198/VirtualEnvOnDemand | VirtualEnvOnDemand/utils.py | 1 | 4791 | # Copyright (c) 2015, 2016 Timothy Savannah under terms of LGPLv3. You should have received a copy of this with this distribution as "LICENSE"
'''
utils - Some general-purpose utility functions
'''
import re
__all__ = ('cmp_version', )
# Yes, cmp is DA BOMB. What a huge mistake removing it from the language!!
try:
cmp
except NameError:
def cmp(a, b):
if a < b:
return -1
elif a > b:
return 1
return 0
# ALPHA_OR_NUM_RE - groups of letters OR numbers
ALPHA_OR_NUM_RE = re.compile('([a-zA-Z]+)|([0-9]+)')
# The following method is slightly-modified from my Public Domain project, cmp_version
# https://pypi.python.org/pypi/cmp_version
# This is copied so as to retain the "all you need is virtualenv and this module" promise.
def cmp_version(version1, version2):
'''
cmp_version - Compare version1 and version2.
Returns cmp-style (C-style), i.e. < 0 if lefthand (version1) is less, 0 if equal, > 0 if righthand (version2) is greater.
@param version1 <str> - String of a version
@param version2 <str> - String of a version
@return <int> -
-1 if version1 is < version2
0 if version1 is = version2
1 if version1 is > version2
'''
version1 = str(version1)
version2 = str(version2)
if version1 == version2:
return 0
# Pad left or right if we have empty blocks
if version1.startswith('.'):
version1 = '0' + version1
if version1.endswith('.'):
version1 = version1 + '0'
if version2.startswith('.'):
version2 = '0' + version2
if version2.endswith('.'):
version2 = version2 + '0'
# Consider dots as separating "blocks", i.e. major/minor/patch/subpatch/monkey-finger, whatever.
version1Split = version1.split('.')
version2Split = version2.split('.')
version1Len = len(version1Split)
version2Len = len(version2Split)
# Ensure we have the same number of blocks in both versions, by padding '0' blocks on the end of the shorter.
# This ensures that "1.2" is equal to "1.2.0", and greatly simplifies the comparison loop below otherwise.
while version1Len < version2Len:
version1Split += ['0']
version1Len += 1
while version2Len < version1Len:
version2Split += ['0']
version2Len += 1
# See if the padding has made these equal
if version1Split == version2Split:
return 0
# Go through each block (they have same len at this point)
for i in range(version1Len):
try:
# Try to compare this block as an integer. If both are integers, but different,
# we have our answer.
cmpRes = cmp(int(version1Split[i]), int(version2Split[i]))
if cmpRes != 0:
return cmpRes
except ValueError:
# Some sort of letter in here
# So split up the sub-blocks of letters OR numbers for comparison
# Note, we don't try to pad here.
# i.e. "1.2a" < "1.2a0".
# This is subjective. I personaly think this is correct the way it is.
try1 = ALPHA_OR_NUM_RE.findall(version1Split[i])
try1Len = len(try1)
try2 = ALPHA_OR_NUM_RE.findall(version2Split[i])
try2Len = len(try2)
# Go block-by-block. Each block is a set of contiguous numbers or letters.
# Letters are greater than numbers.
for j in range(len(try1)):
if j >= try2Len:
return 1
testSet1 = try1[j]
testSet2 = try2[j]
res1 = cmp(testSet1[0], testSet2[0])
if res1 != 0:
return res1
res2 = 0
if testSet1[1].isdigit():
if testSet2[1].isdigit():
res2 = cmp(int(testSet1[1]), int(testSet2[1]))
else:
return 1
else:
if testSet2[1].isdigit():
return 1
if res2 != 0:
return res2
if try2Len > try1Len:
return -1
# Equal !
return 0
def writeStrToFile(filename, contents):
'''
writeStrToFile - Writes some data to a provided filename.
@param filename <str> - A path to a file
@param contents <str> - The contents to write to the file, replacing any previous contents.
@return <None/Exception> - None if all goes well, otherwise the Exception raised
'''
try:
with open(filename, 'wt') as f:
f.write(contents)
except Exception as e:
return e
return None
| lgpl-3.0 |
teltek/edx-platform | common/djangoapps/util/models.py | 16 | 1962 | """Models for the util app. """
import cStringIO
import gzip
import logging
from config_models.models import ConfigurationModel
from django.db import models
from django.utils.text import compress_string
from opaque_keys.edx.django.models import CreatorMixin
logger = logging.getLogger(__name__) # pylint: disable=invalid-name
class RateLimitConfiguration(ConfigurationModel):
"""Configuration flag to enable/disable rate limiting.
Applies to Django Rest Framework views.
This is useful for disabling rate limiting for performance tests.
When enabled, it will disable rate limiting on any view decorated
with the `can_disable_rate_limit` class decorator.
"""
class Meta(ConfigurationModel.Meta):
app_label = "util"
def decompress_string(value):
"""
Helper function to reverse CompressedTextField.get_prep_value.
"""
try:
val = value.encode('utf').decode('base64')
zbuf = cStringIO.StringIO(val)
zfile = gzip.GzipFile(fileobj=zbuf)
ret = zfile.read()
zfile.close()
except Exception as e:
logger.error('String decompression failed. There may be corrupted data in the database: %s', e)
ret = value
return ret
class CompressedTextField(CreatorMixin, models.TextField):
""" TextField that transparently compresses data when saving to the database, and decompresses the data
when retrieving it from the database. """
def get_prep_value(self, value):
""" Compress the text data. """
if value is not None:
if isinstance(value, unicode):
value = value.encode('utf8')
value = compress_string(value)
value = value.encode('base64').decode('utf8')
return value
def to_python(self, value):
""" Decompresses the value from the database. """
if isinstance(value, unicode):
value = decompress_string(value)
return value
| agpl-3.0 |
peeyush-tm/shinken | test/test_notification_master.py | 18 | 3470 | #!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
# Sebastien Coavoux, s.coavoux@free.fr
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
import time
from shinken_test import ShinkenTest, unittest
from shinken.notification import Notification
class TestMasterNotif(ShinkenTest):
# For a service, we generate a notification and a event handler.
# Each one got a specific reactionner_tag that we will look for.
def test_master_notif(self):
router = self.sched.hosts.find_by_name("test_router_0")
router.checks_in_progress = []
router.act_depend_of = [] # ignore the router
host = self.sched.hosts.find_by_name("test_host_0")
host.checks_in_progress = []
host.act_depend_of = [] # ignore the router
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
svc.checks_in_progress = []
svc.act_depend_of = [] # no hostchecks on critical checkresults
self.scheduler_loop(2, [[host, 0, 'UP | value1=1 value2=2'], [router, 0, 'UP | rtt=10'], [svc, 0, 'BAD | value1=0 value2=0']])
### hack Notification.__init__ to save the newly created instances :
_new_notifs = []
_old_notif_init = Notification.__init__
def _mock_notif_init(self, *a, **kw):
_old_notif_init(self, *a, **kw)
_new_notifs.append(self) # save it!
Notification.__init__ = _mock_notif_init
try:
# this scheduler_loop will create a new notification:
self.scheduler_loop(2, [[svc, 2, 'BAD | value1=0 value2=0']])
finally: # be courteous and always undo what we've mocked once we don't need it anymore:
Notification.__init__ = _old_notif_init
self.assertNotEqual(0, len(_new_notifs),
"A Notification should have been created !")
guessed_notif = _new_notifs[0] # and we hope that it's the good one..
self.assertIs(guessed_notif, self.sched.actions.get(guessed_notif.id, None),
"Our guessed notification does not match what's in scheduler actions dict !\n"
"guessed_notif=[%s] sched.actions=%r" % (guessed_notif, self.sched.actions))
guessed_notif.t_to_go = time.time() # Hack to set t_to_go now, so that the notification is processed
# Try to set master notif status to inpoller
actions = self.sched.get_to_run_checks(False, True)
# But no, still scheduled
self.assertEqual('scheduled', guessed_notif.status)
# And still no action for our receivers
self.assertEqual([], actions)
if __name__ == '__main__':
unittest.main()
| agpl-3.0 |
nanolearning/edx-platform | common/test/acceptance/fixtures/discussion.py | 11 | 2559 | """
Tools for creating discussion content fixture data.
"""
from datetime import datetime
import json
import factory
import requests
from . import COMMENTS_STUB_URL
class ContentFactory(factory.Factory):
FACTORY_FOR = dict
id = None
user_id = "dummy-user-id"
username = "dummy-username"
course_id = "dummy-course-id"
commentable_id = "dummy-commentable-id"
anonymous = False
anonymous_to_peers = False
at_position_list = []
abuse_flaggers = []
created_at = datetime.utcnow().isoformat()
updated_at = datetime.utcnow().isoformat()
endorsed = False
closed = False
votes = {"up_count": 0}
class Thread(ContentFactory):
comments_count = 0
unread_comments_count = 0
title = "dummy thread title"
body = "dummy thread body"
type = "thread"
group_id = None
pinned = False
read = False
class Comment(ContentFactory):
thread_id = None
depth = 0
type = "comment"
body = "dummy comment body"
class Response(Comment):
depth = 1
body = "dummy response body"
class SingleThreadViewFixture(object):
def __init__(self, thread):
self.thread = thread
def addResponse(self, response, comments=[]):
response['children'] = comments
self.thread.setdefault('children', []).append(response)
self.thread['comments_count'] += len(comments) + 1
def _get_comment_map(self):
"""
Generate a dict mapping each response/comment in the thread
by its `id`.
"""
def _visit(obj):
res = []
for child in obj.get('children', []):
res.append((child['id'], child))
if 'children' in child:
res += _visit(child)
return res
return dict(_visit(self.thread))
def push(self):
"""
Push the data to the stub comments service.
"""
requests.put(
'{}/set_config'.format(COMMENTS_STUB_URL),
data={
"threads": json.dumps({self.thread['id']: self.thread}),
"comments": json.dumps(self._get_comment_map())
}
)
class UserProfileViewFixture(object):
def __init__(self, threads):
self.threads = threads
def push(self):
"""
Push the data to the stub comments service.
"""
requests.put(
'{}/set_config'.format(COMMENTS_STUB_URL),
data={
"active_threads": json.dumps(self.threads),
}
)
| agpl-3.0 |
domain51/d51.django.apps.logger | d51/django/apps/logger/tests/views.py | 1 | 1154 | import datetime
from django.test import TestCase
from django.test.client import Client
from ..models import Hit
from .utils import build_hit_url, random_url
class TestOfHitView(TestCase):
def test_logs_hit(self):
url = random_url()
c = Client()
response = c.get(build_hit_url(url))
hit = Hit.objects.get(url=url)
def test_stores_current_time(self):
url = random_url()
response = Client().get(build_hit_url(url))
hit = Hit.objects.get(url=url)
self.assert_(isinstance(hit.created_on, datetime.datetime))
self.assert_((datetime.datetime.now() - hit.created_on).seconds < 1,
"Check creation time, might fail on slow machines/network connections.")
def test_redirects_to_url(self):
url = random_url()
response = Client().get(build_hit_url(url))
self.assertEquals(response.status_code, 302)
# TODO: refactor this - we can't use assertRedirect() because it
# tries to load crap, but this test should be simplified
self.assertEquals(response._headers['location'][1], url, "ensure redirection took place")
| gpl-3.0 |
gnmiller/craig-bot | craig-bot/lib/python3.6/site-packages/pip/_vendor/urllib3/contrib/ntlmpool.py | 63 | 4459 | """
NTLM authenticating pool, contributed by erikcederstran
Issue #10, see: http://code.google.com/p/urllib3/issues/detail?id=10
"""
from __future__ import absolute_import
from logging import getLogger
from ntlm import ntlm
from .. import HTTPSConnectionPool
from ..packages.six.moves.http_client import HTTPSConnection
log = getLogger(__name__)
class NTLMConnectionPool(HTTPSConnectionPool):
"""
Implements an NTLM authentication version of an urllib3 connection pool
"""
scheme = 'https'
def __init__(self, user, pw, authurl, *args, **kwargs):
"""
authurl is a random URL on the server that is protected by NTLM.
user is the Windows user, probably in the DOMAIN\\username format.
pw is the password for the user.
"""
super(NTLMConnectionPool, self).__init__(*args, **kwargs)
self.authurl = authurl
self.rawuser = user
user_parts = user.split('\\', 1)
self.domain = user_parts[0].upper()
self.user = user_parts[1]
self.pw = pw
def _new_conn(self):
# Performs the NTLM handshake that secures the connection. The socket
# must be kept open while requests are performed.
self.num_connections += 1
log.debug('Starting NTLM HTTPS connection no. %d: https://%s%s',
self.num_connections, self.host, self.authurl)
headers = {'Connection': 'Keep-Alive'}
req_header = 'Authorization'
resp_header = 'www-authenticate'
conn = HTTPSConnection(host=self.host, port=self.port)
# Send negotiation message
headers[req_header] = (
'NTLM %s' % ntlm.create_NTLM_NEGOTIATE_MESSAGE(self.rawuser))
log.debug('Request headers: %s', headers)
conn.request('GET', self.authurl, None, headers)
res = conn.getresponse()
reshdr = dict(res.getheaders())
log.debug('Response status: %s %s', res.status, res.reason)
log.debug('Response headers: %s', reshdr)
log.debug('Response data: %s [...]', res.read(100))
# Remove the reference to the socket, so that it can not be closed by
# the response object (we want to keep the socket open)
res.fp = None
# Server should respond with a challenge message
auth_header_values = reshdr[resp_header].split(', ')
auth_header_value = None
for s in auth_header_values:
if s[:5] == 'NTLM ':
auth_header_value = s[5:]
if auth_header_value is None:
raise Exception('Unexpected %s response header: %s' %
(resp_header, reshdr[resp_header]))
# Send authentication message
ServerChallenge, NegotiateFlags = \
ntlm.parse_NTLM_CHALLENGE_MESSAGE(auth_header_value)
auth_msg = ntlm.create_NTLM_AUTHENTICATE_MESSAGE(ServerChallenge,
self.user,
self.domain,
self.pw,
NegotiateFlags)
headers[req_header] = 'NTLM %s' % auth_msg
log.debug('Request headers: %s', headers)
conn.request('GET', self.authurl, None, headers)
res = conn.getresponse()
log.debug('Response status: %s %s', res.status, res.reason)
log.debug('Response headers: %s', dict(res.getheaders()))
log.debug('Response data: %s [...]', res.read()[:100])
if res.status != 200:
if res.status == 401:
raise Exception('Server rejected request: wrong '
'username or password')
raise Exception('Wrong server response: %s %s' %
(res.status, res.reason))
res.fp = None
log.debug('Connection established')
return conn
def urlopen(self, method, url, body=None, headers=None, retries=3,
redirect=True, assert_same_host=True):
if headers is None:
headers = {}
headers['Connection'] = 'Keep-Alive'
return super(NTLMConnectionPool, self).urlopen(method, url, body,
headers, retries,
redirect,
assert_same_host)
| mit |
jungle90/Openstack-Swift-I-O-throttler | build/lib.linux-x86_64-2.7/swift/account/utils.py | 17 | 4423 | # Copyright (c) 2010-2013 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.
import time
from xml.sax import saxutils
from swift.common.swob import HTTPOk, HTTPNoContent
from swift.common.utils import json, Timestamp
from swift.common.storage_policy import POLICIES
class FakeAccountBroker(object):
"""
Quacks like an account broker, but doesn't actually do anything. Responds
like an account broker would for a real, empty account with no metadata.
"""
def get_info(self):
now = Timestamp(time.time()).internal
return {'container_count': 0,
'object_count': 0,
'bytes_used': 0,
'created_at': now,
'put_timestamp': now}
def list_containers_iter(self, *_, **__):
return []
@property
def metadata(self):
return {}
def get_policy_stats(self):
return {}
def get_response_headers(broker):
info = broker.get_info()
resp_headers = {
'X-Account-Container-Count': info['container_count'],
'X-Account-Object-Count': info['object_count'],
'X-Account-Bytes-Used': info['bytes_used'],
'X-Timestamp': Timestamp(info['created_at']).normal,
'X-PUT-Timestamp': Timestamp(info['put_timestamp']).normal}
policy_stats = broker.get_policy_stats()
for policy_idx, stats in policy_stats.items():
policy = POLICIES.get_by_index(policy_idx)
if not policy:
continue
header_prefix = 'X-Account-Storage-Policy-%s-%%s' % policy.name
for key, value in stats.items():
header_name = header_prefix % key.replace('_', '-')
resp_headers[header_name] = value
resp_headers.update((key, value)
for key, (value, timestamp) in
broker.metadata.iteritems() if value != '')
return resp_headers
def account_listing_response(account, req, response_content_type, broker=None,
limit='', marker='', end_marker='', prefix='',
delimiter=''):
if broker is None:
broker = FakeAccountBroker()
resp_headers = get_response_headers(broker)
account_list = broker.list_containers_iter(limit, marker, end_marker,
prefix, delimiter)
if response_content_type == 'application/json':
data = []
for (name, object_count, bytes_used, is_subdir) in account_list:
if is_subdir:
data.append({'subdir': name})
else:
data.append({'name': name, 'count': object_count,
'bytes': bytes_used})
account_list = json.dumps(data)
elif response_content_type.endswith('/xml'):
output_list = ['<?xml version="1.0" encoding="UTF-8"?>',
'<account name=%s>' % saxutils.quoteattr(account)]
for (name, object_count, bytes_used, is_subdir) in account_list:
if is_subdir:
output_list.append(
'<subdir name=%s />' % saxutils.quoteattr(name))
else:
item = '<container><name>%s</name><count>%s</count>' \
'<bytes>%s</bytes></container>' % \
(saxutils.escape(name), object_count, bytes_used)
output_list.append(item)
output_list.append('</account>')
account_list = '\n'.join(output_list)
else:
if not account_list:
resp = HTTPNoContent(request=req, headers=resp_headers)
resp.content_type = response_content_type
resp.charset = 'utf-8'
return resp
account_list = '\n'.join(r[0] for r in account_list) + '\n'
ret = HTTPOk(body=account_list, request=req, headers=resp_headers)
ret.content_type = response_content_type
ret.charset = 'utf-8'
return ret
| apache-2.0 |
cpanelli/-git-clone-https-chromium.googlesource.com-chromium-tools-depot_tools | third_party/boto/gs/cors.py | 88 | 7731 | # Copyright 2012 Google Inc.
#
# 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 types
from boto.gs.user import User
from boto.exception import InvalidCorsError
from xml.sax import handler
# Relevant tags for the CORS XML document.
CORS_CONFIG = 'CorsConfig'
CORS = 'Cors'
ORIGINS = 'Origins'
ORIGIN = 'Origin'
METHODS = 'Methods'
METHOD = 'Method'
HEADERS = 'ResponseHeaders'
HEADER = 'ResponseHeader'
MAXAGESEC = 'MaxAgeSec'
class Cors(handler.ContentHandler):
"""Encapsulates the CORS configuration XML document"""
def __init__(self):
# List of CORS elements found within a CorsConfig element.
self.cors = []
# List of collections (e.g. Methods, ResponseHeaders, Origins)
# found within a CORS element. We use a list of lists here
# instead of a dictionary because the collections need to be
# preserved in the order in which they appear in the input XML
# document (and Python dictionary keys are inherently unordered).
# The elements on this list are two element tuples of the form
# (collection name, [list of collection contents]).
self.collections = []
# Lists of elements within a collection. Again a list is needed to
# preserve ordering but also because the same element may appear
# multiple times within a collection.
self.elements = []
# Dictionary mapping supported collection names to element types
# which may be contained within each.
self.legal_collections = {
ORIGINS : [ORIGIN],
METHODS : [METHOD],
HEADERS : [HEADER],
MAXAGESEC: []
}
# List of supported element types within any collection, used for
# checking validadity of a parsed element name.
self.legal_elements = [ORIGIN, METHOD, HEADER]
self.parse_level = 0
self.collection = None
self.element = None
def validateParseLevel(self, tag, level):
"""Verify parse level for a given tag."""
if self.parse_level != level:
raise InvalidCorsError('Invalid tag %s at parse level %d: ' %
(tag, self.parse_level))
def startElement(self, name, attrs, connection):
"""SAX XML logic for parsing new element found."""
if name == CORS_CONFIG:
self.validateParseLevel(name, 0)
self.parse_level += 1;
elif name == CORS:
self.validateParseLevel(name, 1)
self.parse_level += 1;
elif name in self.legal_collections:
self.validateParseLevel(name, 2)
self.parse_level += 1;
self.collection = name
elif name in self.legal_elements:
self.validateParseLevel(name, 3)
# Make sure this tag is found inside a collection tag.
if self.collection is None:
raise InvalidCorsError('Tag %s found outside collection' % name)
# Make sure this tag is allowed for the current collection tag.
if name not in self.legal_collections[self.collection]:
raise InvalidCorsError('Tag %s not allowed in %s collection' %
(name, self.collection))
self.element = name
else:
raise InvalidCorsError('Unsupported tag ' + name)
def endElement(self, name, value, connection):
"""SAX XML logic for parsing new element found."""
if name == CORS_CONFIG:
self.validateParseLevel(name, 1)
self.parse_level -= 1;
elif name == CORS:
self.validateParseLevel(name, 2)
self.parse_level -= 1;
# Terminating a CORS element, save any collections we found
# and re-initialize collections list.
self.cors.append(self.collections)
self.collections = []
elif name in self.legal_collections:
self.validateParseLevel(name, 3)
if name != self.collection:
raise InvalidCorsError('Mismatched start and end tags (%s/%s)' %
(self.collection, name))
self.parse_level -= 1;
if not self.legal_collections[name]:
# If this collection doesn't contain any sub-elements, store
# a tuple of name and this tag's element value.
self.collections.append((name, value.strip()))
else:
# Otherwise, we're terminating a collection of sub-elements,
# so store a tuple of name and list of contained elements.
self.collections.append((name, self.elements))
self.elements = []
self.collection = None
elif name in self.legal_elements:
self.validateParseLevel(name, 3)
# Make sure this tag is found inside a collection tag.
if self.collection is None:
raise InvalidCorsError('Tag %s found outside collection' % name)
# Make sure this end tag is allowed for the current collection tag.
if name not in self.legal_collections[self.collection]:
raise InvalidCorsError('Tag %s not allowed in %s collection' %
(name, self.collection))
if name != self.element:
raise InvalidCorsError('Mismatched start and end tags (%s/%s)' %
(self.element, name))
# Terminating an element tag, add it to the list of elements
# for the current collection.
self.elements.append((name, value.strip()))
self.element = None
else:
raise InvalidCorsError('Unsupported end tag ' + name)
def to_xml(self):
"""Convert CORS object into XML string representation."""
s = '<' + CORS_CONFIG + '>'
for collections in self.cors:
s += '<' + CORS + '>'
for (collection, elements_or_value) in collections:
assert collection is not None
s += '<' + collection + '>'
# If collection elements has type string, append atomic value,
# otherwise, append sequence of values in named tags.
if isinstance(elements_or_value, types.StringTypes):
s += elements_or_value
else:
for (name, value) in elements_or_value:
assert name is not None
assert value is not None
s += '<' + name + '>' + value + '</' + name + '>'
s += '</' + collection + '>'
s += '</' + CORS + '>'
s += '</' + CORS_CONFIG + '>'
return s
| bsd-3-clause |
epssy/hue | desktop/core/ext-py/pycrypto-2.6.1/lib/Crypto/SelfTest/Random/Fortuna/test_FortunaAccumulator.py | 116 | 8612 | # -*- coding: utf-8 -*-
#
# SelfTest/Random/Fortuna/test_FortunaAccumulator.py: Self-test for the FortunaAccumulator module
#
# Written in 2008 by Dwayne C. Litzenberger <dlitz@dlitz.net>
#
# ===================================================================
# The contents of this file are dedicated to the public domain. To
# the extent that dedication to the public domain is not available,
# everyone is granted a worldwide, perpetual, royalty-free,
# non-exclusive license to exercise all rights associated with the
# contents of this file for any purpose whatsoever.
# No rights are reserved.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# ===================================================================
"""Self-tests for Crypto.Random.Fortuna.FortunaAccumulator"""
__revision__ = "$Id$"
import sys
if sys.version_info[0] == 2 and sys.version_info[1] == 1:
from Crypto.Util.py21compat import *
from Crypto.Util.py3compat import *
import unittest
from binascii import b2a_hex
class FortunaAccumulatorTests(unittest.TestCase):
def setUp(self):
global FortunaAccumulator
from Crypto.Random.Fortuna import FortunaAccumulator
def test_FortunaPool(self):
"""FortunaAccumulator.FortunaPool"""
pool = FortunaAccumulator.FortunaPool()
self.assertEqual(0, pool.length)
self.assertEqual("5df6e0e2761359d30a8275058e299fcc0381534545f55cf43e41983f5d4c9456", pool.hexdigest())
pool.append(b('abc'))
self.assertEqual(3, pool.length)
self.assertEqual("4f8b42c22dd3729b519ba6f68d2da7cc5b2d606d05daed5ad5128cc03e6c6358", pool.hexdigest())
pool.append(b("dbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"))
self.assertEqual(56, pool.length)
self.assertEqual(b('0cffe17f68954dac3a84fb1458bd5ec99209449749b2b308b7cb55812f9563af'), b2a_hex(pool.digest()))
pool.reset()
self.assertEqual(0, pool.length)
pool.append(b('a') * 10**6)
self.assertEqual(10**6, pool.length)
self.assertEqual(b('80d1189477563e1b5206b2749f1afe4807e5705e8bd77887a60187a712156688'), b2a_hex(pool.digest()))
def test_which_pools(self):
"""FortunaAccumulator.which_pools"""
# which_pools(0) should fail
self.assertRaises(AssertionError, FortunaAccumulator.which_pools, 0)
self.assertEqual(FortunaAccumulator.which_pools(1), [0])
self.assertEqual(FortunaAccumulator.which_pools(2), [0, 1])
self.assertEqual(FortunaAccumulator.which_pools(3), [0])
self.assertEqual(FortunaAccumulator.which_pools(4), [0, 1, 2])
self.assertEqual(FortunaAccumulator.which_pools(5), [0])
self.assertEqual(FortunaAccumulator.which_pools(6), [0, 1])
self.assertEqual(FortunaAccumulator.which_pools(7), [0])
self.assertEqual(FortunaAccumulator.which_pools(8), [0, 1, 2, 3])
for i in range(1, 32):
self.assertEqual(FortunaAccumulator.which_pools(2L**i-1), [0])
self.assertEqual(FortunaAccumulator.which_pools(2L**i), range(i+1))
self.assertEqual(FortunaAccumulator.which_pools(2L**i+1), [0])
self.assertEqual(FortunaAccumulator.which_pools(2L**31), range(32))
self.assertEqual(FortunaAccumulator.which_pools(2L**32), range(32))
self.assertEqual(FortunaAccumulator.which_pools(2L**33), range(32))
self.assertEqual(FortunaAccumulator.which_pools(2L**34), range(32))
self.assertEqual(FortunaAccumulator.which_pools(2L**35), range(32))
self.assertEqual(FortunaAccumulator.which_pools(2L**36), range(32))
self.assertEqual(FortunaAccumulator.which_pools(2L**64), range(32))
self.assertEqual(FortunaAccumulator.which_pools(2L**128), range(32))
def test_accumulator(self):
"""FortunaAccumulator.FortunaAccumulator"""
fa = FortunaAccumulator.FortunaAccumulator()
# This should fail, because we haven't seeded the PRNG yet
self.assertRaises(AssertionError, fa.random_data, 1)
# Spread some test data across the pools (source number 42)
# This would be horribly insecure in a real system.
for p in range(32):
fa.add_random_event(42, p, b("X") * 32)
self.assertEqual(32+2, fa.pools[p].length)
# This should still fail, because we haven't seeded the PRNG with 64 bytes yet
self.assertRaises(AssertionError, fa.random_data, 1)
# Add more data
for p in range(32):
fa.add_random_event(42, p, b("X") * 32)
self.assertEqual((32+2)*2, fa.pools[p].length)
# The underlying RandomGenerator should get seeded with Pool 0
# s = SHAd256(chr(42) + chr(32) + "X"*32 + chr(42) + chr(32) + "X"*32)
# = SHA256(h'edd546f057b389155a31c32e3975e736c1dec030ddebb137014ecbfb32ed8c6f')
# = h'aef42a5dcbddab67e8efa118e1b47fde5d697f89beb971b99e6e8e5e89fbf064'
# The counter and the key before reseeding is:
# C_0 = 0
# K_0 = "\x00" * 32
# The counter after reseeding is 1, and the new key after reseeding is
# C_1 = 1
# K_1 = SHAd256(K_0 || s)
# = SHA256(h'0eae3e401389fab86640327ac919ecfcb067359d95469e18995ca889abc119a6')
# = h'aafe9d0409fbaaafeb0a1f2ef2014a20953349d3c1c6e6e3b962953bea6184dd'
# The first block of random data, therefore, is
# r_1 = AES-256(K_1, 1)
# = AES-256(K_1, h'01000000000000000000000000000000')
# = h'b7b86bd9a27d96d7bb4add1b6b10d157'
# The second block of random data is
# r_2 = AES-256(K_1, 2)
# = AES-256(K_1, h'02000000000000000000000000000000')
# = h'2350b1c61253db2f8da233be726dc15f'
# The third and fourth blocks of random data (which become the new key) are
# r_3 = AES-256(K_1, 3)
# = AES-256(K_1, h'03000000000000000000000000000000')
# = h'f23ad749f33066ff53d307914fbf5b21'
# r_4 = AES-256(K_1, 4)
# = AES-256(K_1, h'04000000000000000000000000000000')
# = h'da9667c7e86ba247655c9490e9d94a7c'
# K_2 = r_3 || r_4
# = h'f23ad749f33066ff53d307914fbf5b21da9667c7e86ba247655c9490e9d94a7c'
# The final counter value is 5.
self.assertEqual("aef42a5dcbddab67e8efa118e1b47fde5d697f89beb971b99e6e8e5e89fbf064",
fa.pools[0].hexdigest())
self.assertEqual(None, fa.generator.key)
self.assertEqual(0, fa.generator.counter.next_value())
result = fa.random_data(32)
self.assertEqual(b("b7b86bd9a27d96d7bb4add1b6b10d157" "2350b1c61253db2f8da233be726dc15f"), b2a_hex(result))
self.assertEqual(b("f23ad749f33066ff53d307914fbf5b21da9667c7e86ba247655c9490e9d94a7c"), b2a_hex(fa.generator.key))
self.assertEqual(5, fa.generator.counter.next_value())
def test_accumulator_pool_length(self):
"""FortunaAccumulator.FortunaAccumulator minimum pool length"""
fa = FortunaAccumulator.FortunaAccumulator()
# This test case is hard-coded to assume that FortunaAccumulator.min_pool_size is 64.
self.assertEqual(fa.min_pool_size, 64)
# The PRNG should not allow us to get random data from it yet
self.assertRaises(AssertionError, fa.random_data, 1)
# Add 60 bytes, 4 at a time (2 header + 2 payload) to each of the 32 pools
for i in range(15):
for p in range(32):
# Add the bytes to the pool
fa.add_random_event(2, p, b("XX"))
# The PRNG should not allow us to get random data from it yet
self.assertRaises(AssertionError, fa.random_data, 1)
# Add 4 more bytes to pool 0
fa.add_random_event(2, 0, b("XX"))
# We should now be able to get data from the accumulator
fa.random_data(1)
def get_tests(config={}):
from Crypto.SelfTest.st_common import list_test_cases
return list_test_cases(FortunaAccumulatorTests)
if __name__ == '__main__':
suite = lambda: unittest.TestSuite(get_tests())
unittest.main(defaultTest='suite')
# vim:set ts=4 sw=4 sts=4 expandtab:
| apache-2.0 |
chafique-delli/OpenUpgrade | addons/account_analytic_analysis/__init__.py | 425 | 1107 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import account_analytic_analysis
import res_config
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
publicloudapp/csrutil | linux-4.3/tools/perf/scripts/python/event_analyzing_sample.py | 4719 | 7393 | # event_analyzing_sample.py: general event handler in python
#
# Current perf report is already very powerful with the annotation integrated,
# and this script is not trying to be as powerful as perf report, but
# providing end user/developer a flexible way to analyze the events other
# than trace points.
#
# The 2 database related functions in this script just show how to gather
# the basic information, and users can modify and write their own functions
# according to their specific requirement.
#
# The first function "show_general_events" just does a basic grouping for all
# generic events with the help of sqlite, and the 2nd one "show_pebs_ll" is
# for a x86 HW PMU event: PEBS with load latency data.
#
import os
import sys
import math
import struct
import sqlite3
sys.path.append(os.environ['PERF_EXEC_PATH'] + \
'/scripts/python/Perf-Trace-Util/lib/Perf/Trace')
from perf_trace_context import *
from EventClass import *
#
# If the perf.data has a big number of samples, then the insert operation
# will be very time consuming (about 10+ minutes for 10000 samples) if the
# .db database is on disk. Move the .db file to RAM based FS to speedup
# the handling, which will cut the time down to several seconds.
#
con = sqlite3.connect("/dev/shm/perf.db")
con.isolation_level = None
def trace_begin():
print "In trace_begin:\n"
#
# Will create several tables at the start, pebs_ll is for PEBS data with
# load latency info, while gen_events is for general event.
#
con.execute("""
create table if not exists gen_events (
name text,
symbol text,
comm text,
dso text
);""")
con.execute("""
create table if not exists pebs_ll (
name text,
symbol text,
comm text,
dso text,
flags integer,
ip integer,
status integer,
dse integer,
dla integer,
lat integer
);""")
#
# Create and insert event object to a database so that user could
# do more analysis with simple database commands.
#
def process_event(param_dict):
event_attr = param_dict["attr"]
sample = param_dict["sample"]
raw_buf = param_dict["raw_buf"]
comm = param_dict["comm"]
name = param_dict["ev_name"]
# Symbol and dso info are not always resolved
if (param_dict.has_key("dso")):
dso = param_dict["dso"]
else:
dso = "Unknown_dso"
if (param_dict.has_key("symbol")):
symbol = param_dict["symbol"]
else:
symbol = "Unknown_symbol"
# Create the event object and insert it to the right table in database
event = create_event(name, comm, dso, symbol, raw_buf)
insert_db(event)
def insert_db(event):
if event.ev_type == EVTYPE_GENERIC:
con.execute("insert into gen_events values(?, ?, ?, ?)",
(event.name, event.symbol, event.comm, event.dso))
elif event.ev_type == EVTYPE_PEBS_LL:
event.ip &= 0x7fffffffffffffff
event.dla &= 0x7fffffffffffffff
con.execute("insert into pebs_ll values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
(event.name, event.symbol, event.comm, event.dso, event.flags,
event.ip, event.status, event.dse, event.dla, event.lat))
def trace_end():
print "In trace_end:\n"
# We show the basic info for the 2 type of event classes
show_general_events()
show_pebs_ll()
con.close()
#
# As the event number may be very big, so we can't use linear way
# to show the histogram in real number, but use a log2 algorithm.
#
def num2sym(num):
# Each number will have at least one '#'
snum = '#' * (int)(math.log(num, 2) + 1)
return snum
def show_general_events():
# Check the total record number in the table
count = con.execute("select count(*) from gen_events")
for t in count:
print "There is %d records in gen_events table" % t[0]
if t[0] == 0:
return
print "Statistics about the general events grouped by thread/symbol/dso: \n"
# Group by thread
commq = con.execute("select comm, count(comm) from gen_events group by comm order by -count(comm)")
print "\n%16s %8s %16s\n%s" % ("comm", "number", "histogram", "="*42)
for row in commq:
print "%16s %8d %s" % (row[0], row[1], num2sym(row[1]))
# Group by symbol
print "\n%32s %8s %16s\n%s" % ("symbol", "number", "histogram", "="*58)
symbolq = con.execute("select symbol, count(symbol) from gen_events group by symbol order by -count(symbol)")
for row in symbolq:
print "%32s %8d %s" % (row[0], row[1], num2sym(row[1]))
# Group by dso
print "\n%40s %8s %16s\n%s" % ("dso", "number", "histogram", "="*74)
dsoq = con.execute("select dso, count(dso) from gen_events group by dso order by -count(dso)")
for row in dsoq:
print "%40s %8d %s" % (row[0], row[1], num2sym(row[1]))
#
# This function just shows the basic info, and we could do more with the
# data in the tables, like checking the function parameters when some
# big latency events happen.
#
def show_pebs_ll():
count = con.execute("select count(*) from pebs_ll")
for t in count:
print "There is %d records in pebs_ll table" % t[0]
if t[0] == 0:
return
print "Statistics about the PEBS Load Latency events grouped by thread/symbol/dse/latency: \n"
# Group by thread
commq = con.execute("select comm, count(comm) from pebs_ll group by comm order by -count(comm)")
print "\n%16s %8s %16s\n%s" % ("comm", "number", "histogram", "="*42)
for row in commq:
print "%16s %8d %s" % (row[0], row[1], num2sym(row[1]))
# Group by symbol
print "\n%32s %8s %16s\n%s" % ("symbol", "number", "histogram", "="*58)
symbolq = con.execute("select symbol, count(symbol) from pebs_ll group by symbol order by -count(symbol)")
for row in symbolq:
print "%32s %8d %s" % (row[0], row[1], num2sym(row[1]))
# Group by dse
dseq = con.execute("select dse, count(dse) from pebs_ll group by dse order by -count(dse)")
print "\n%32s %8s %16s\n%s" % ("dse", "number", "histogram", "="*58)
for row in dseq:
print "%32s %8d %s" % (row[0], row[1], num2sym(row[1]))
# Group by latency
latq = con.execute("select lat, count(lat) from pebs_ll group by lat order by lat")
print "\n%32s %8s %16s\n%s" % ("latency", "number", "histogram", "="*58)
for row in latq:
print "%32s %8d %s" % (row[0], row[1], num2sym(row[1]))
def trace_unhandled(event_name, context, event_fields_dict):
print ' '.join(['%s=%s'%(k,str(v))for k,v in sorted(event_fields_dict.items())])
| mit |
ocampocj/cloud-custodian | tools/c7n_azure/tests/test_filters_marked-for-op.py | 3 | 1952 | # Copyright 2019 Microsoft Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import, division, print_function, unicode_literals
import datetime
import tools_tags as tools
from azure_common import BaseTest, arm_template
from c7n_azure.filters import TagActionFilter
from mock import Mock
class TagsTest(BaseTest):
def test_tag_schema_validate(self):
self.assertTrue(
self.load_policy(
tools.get_policy(filters=[
{'type': 'marked-for-op', 'op': 'delete', 'tag': 'custom'},
]), validate=True))
def _get_filter(self, data):
return TagActionFilter(data=data, manager=Mock)
@arm_template('vm.json')
def test_tag_filter(self):
date = self.get_test_date().strftime('%Y-%m-%d')
date_future = (self.get_test_date() + datetime.timedelta(days=1)).strftime('%Y-%m-%d')
resources = [tools.get_resource({'custodian_status': 'TTL: stop@{0}'.format(date)}),
tools.get_resource({'custom_status': 'TTL: stop@{0}'.format(date)}),
tools.get_resource({'custodian_status': 'TTL: stop@{0}'.format(date_future)})]
config = [({'op': 'stop'}, 1),
({'op': 'stop', 'tag': 'custom_status'}, 1)]
for c in config:
f = self._get_filter(c[0])
result = f.process(resources)
self.assertEqual(len(result), c[1])
| apache-2.0 |
dls-controls/scanpointgenerator | tests/test_core/test_get_points_performance.py | 1 | 5693 | import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
import unittest
import time
from test_util import ScanPointGeneratorTest
from scanpointgenerator import CompoundGenerator
from scanpointgenerator import LineGenerator, StaticPointGenerator, LissajousGenerator, SpiralGenerator
from scanpointgenerator import CircularROI, RectangularROI, ROIExcluder
from scanpointgenerator import RandomOffsetMutator
# Jython gets 3x as long
TIMELIMIT = 3 if os.name == "java" else 1
# Goal is 10khz, 1s per 10,000(10e4) points
class GetPointsPerformanceTest(ScanPointGeneratorTest):
def test_90_thousand_time_constraint(self):
z = LineGenerator("z", "mm", 0, 1, 300, True)
w = LineGenerator("w", "mm", 0, 1, 300, True)
g = CompoundGenerator([z, w], [], [])
g.prepare() # 9e4 points
start_time = time.time()
C = g.get_points(0, 90000)
end_time = time.time()
self.assertLess(end_time - start_time, TIMELIMIT*9)
def test_30_thousand_time_constraint_with_outer(self):
a = StaticPointGenerator(1)
z = LineGenerator("z", "mm", 0, 1, 300, True)
w = LineGenerator("w", "mm", 0, 1, 300, True)
g = CompoundGenerator([a, z, w], [], [])
g.prepare() # 9e4 points
start_time = time.time()
C = g.get_points(0, 30000)
end_time = time.time()
self.assertLess(end_time - start_time, TIMELIMIT*3)
def test_30_thousand_time_constraint_with_inner(self):
a = StaticPointGenerator(1)
z = LineGenerator("z", "mm", 0, 1, 300, True)
w = LineGenerator("w", "mm", 0, 1, 300, True)
g = CompoundGenerator([z, w, a], [], [])
g.prepare() # 9e4 points
start_time = time.time()
C = g.get_points(0, 30000)
end_time = time.time()
self.assertLess(end_time - start_time, TIMELIMIT*3)
@unittest.skip("Unsuitable")
def test_1_million_time_constraint_complex(self):
a = LineGenerator("a", "mm", 0, 1, 10, True)
b = LineGenerator("b", "mm", 0, 1, 10)
c = LineGenerator("c", "mm", 0, 1, 10)
d = LineGenerator("d", "mm", 0, 1, 10)
e = LineGenerator("e", "mm", 0, 1, 10)
f = LineGenerator("f", "mm", 0, 1, 10)
g = CompoundGenerator([b, c, d, e, f, a], [], [])
g.prepare() # 1e6 points
start_time = time.time()
C = g.get_points(0, 1000000)
end_time = time.time()
# if this test becomes problematic then we'll just have to remove it
self.assertLess(end_time - start_time, TIMELIMIT*100)
@unittest.skip("Unsuitable")
def test_small_time_constraint_complex(self):
a = LineGenerator("a", "mm", 0, 1, 10, True)
b = LineGenerator("b", "mm", 0, 1, 10)
c = LineGenerator("c", "mm", 0, 1, 10)
d = LineGenerator("d", "mm", 0, 1, 10)
e = LineGenerator("e", "mm", 0, 1, 10)
f = LineGenerator("f", "mm", 0, 1, 10)
g = CompoundGenerator([b, c, d, e, f, a], [], [])
g.prepare() # 1e6 points
start_time = time.time()
C = g.get_points(0, 1)
end_time = time.time()
# if this test becomes problematic then we'll just have to remove it
self.assertLess(end_time - start_time, TIMELIMIT*1e-4)
start_time = time.time()
C = g.get_points(0, 10)
end_time = time.time()
# if this test becomes problematic then we'll just have to remove it
self.assertLess(end_time - start_time, TIMELIMIT*1e-3)
start_time = time.time()
C = g.get_points(0, 100)
end_time = time.time()
# if this test becomes problematic then we'll just have to remove it
self.assertLess(end_time - start_time, TIMELIMIT*1e-2)
def test_roi_time_constraint(self):
a = LineGenerator("a", "mm", 0, 1, 300, True)
b = LineGenerator("b", "mm", 0, 1, 300)
r1 = CircularROI([0.25, 0.33], 0.1)
e1 = ROIExcluder([r1], ["a", "b"])
g = CompoundGenerator([b, a], [e1], [])
g.prepare() # ~2,800 points
start_time = time.time()
C = g.get_points(0, 1000)
end_time = time.time()
# if this test becomes problematic then we'll just have to remove it
self.assertLess(end_time - start_time, TIMELIMIT*0.1)
start_time = time.time()
C = g.get_points(0, 2800)
end_time = time.time()
# if this test becomes problematic then we'll just have to remove it
self.assertLess(end_time - start_time, TIMELIMIT*0.28)
@unittest.skip("Unsuitable")
def test_time_constraint_complex(self):
a = LineGenerator("a", "eV", 0, 1, 10)
b = LineGenerator("b", "rad", 0, 1, 10)
c = LissajousGenerator(["c", "d"], ["mm", "cm"], [0, 0], [5, 5], 3, 10)
d = SpiralGenerator(["e", "f"], ["mm", "s"], [10, 5], 7, 0.6)
e = LineGenerator("g", "mm", 0, 1, 10)
f = LineGenerator("h", "mm", 0, 5, 20)
r1 = CircularROI([0.2, 0.2], 0.1)
r2 = CircularROI([0.4, 0.2], 0.1)
r3 = CircularROI([0.6, 0.2], 0.1)
e1 = ROIExcluder([r1, r2, r3], ["a", "b"])
m1 = RandomOffsetMutator(12, ["a"], [0.1])
m2 = RandomOffsetMutator(200, ["c", "f"], [0.01, 0.5])
g = CompoundGenerator([c, d, e, f, b, a], [e1], [m1, m2])
g.prepare() # 1e6 points
for i in [1, 2, 3, 4, 5, 6]:
p = 10**i
start_time = time.time()
g.get_points(0, p)
end_time = time.time()
self.assertLess(end_time - start_time, TIMELIMIT*p/1e4)
if __name__ == "__main__":
unittest.main(verbosity=2)
| apache-2.0 |
fumen/gae-fumen | lib/jinja2/defaults.py | 130 | 1323 | # -*- coding: utf-8 -*-
"""
jinja2.defaults
~~~~~~~~~~~~~~~
Jinja default filters and tags.
:copyright: (c) 2017 by the Jinja Team.
:license: BSD, see LICENSE for more details.
"""
from jinja2._compat import range_type
from jinja2.utils import generate_lorem_ipsum, Cycler, Joiner
# defaults for the parser / lexer
BLOCK_START_STRING = '{%'
BLOCK_END_STRING = '%}'
VARIABLE_START_STRING = '{{'
VARIABLE_END_STRING = '}}'
COMMENT_START_STRING = '{#'
COMMENT_END_STRING = '#}'
LINE_STATEMENT_PREFIX = None
LINE_COMMENT_PREFIX = None
TRIM_BLOCKS = False
LSTRIP_BLOCKS = False
NEWLINE_SEQUENCE = '\n'
KEEP_TRAILING_NEWLINE = False
# default filters, tests and namespace
from jinja2.filters import FILTERS as DEFAULT_FILTERS
from jinja2.tests import TESTS as DEFAULT_TESTS
DEFAULT_NAMESPACE = {
'range': range_type,
'dict': dict,
'lipsum': generate_lorem_ipsum,
'cycler': Cycler,
'joiner': Joiner
}
# default policies
DEFAULT_POLICIES = {
'compiler.ascii_str': True,
'urlize.rel': 'noopener',
'urlize.target': None,
'truncate.leeway': 5,
'json.dumps_function': None,
'json.dumps_kwargs': {'sort_keys': True},
}
# export all constants
__all__ = tuple(x for x in locals().keys() if x.isupper())
| bsd-3-clause |
sambyers/o365_fmc | .venv/lib/python3.6/site-packages/pip/_vendor/requests/packages/chardet/latin1prober.py | 1778 | 5232 | ######################## 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 #########################
from .charsetprober import CharSetProber
from .constants import eNotMe
from .compat import wrap_ord
FREQ_CAT_NUM = 4
UDF = 0 # undefined
OTH = 1 # other
ASC = 2 # ascii capital letter
ASS = 3 # ascii small letter
ACV = 4 # accent capital vowel
ACO = 5 # accent capital other
ASV = 6 # accent small vowel
ASO = 7 # accent small other
CLASS_NUM = 8 # total classes
Latin1_CharToClass = (
OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 00 - 07
OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 08 - 0F
OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 10 - 17
OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 18 - 1F
OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 20 - 27
OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 28 - 2F
OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 30 - 37
OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 38 - 3F
OTH, ASC, ASC, ASC, ASC, ASC, ASC, ASC, # 40 - 47
ASC, ASC, ASC, ASC, ASC, ASC, ASC, ASC, # 48 - 4F
ASC, ASC, ASC, ASC, ASC, ASC, ASC, ASC, # 50 - 57
ASC, ASC, ASC, OTH, OTH, OTH, OTH, OTH, # 58 - 5F
OTH, ASS, ASS, ASS, ASS, ASS, ASS, ASS, # 60 - 67
ASS, ASS, ASS, ASS, ASS, ASS, ASS, ASS, # 68 - 6F
ASS, ASS, ASS, ASS, ASS, ASS, ASS, ASS, # 70 - 77
ASS, ASS, ASS, OTH, OTH, OTH, OTH, OTH, # 78 - 7F
OTH, UDF, OTH, ASO, OTH, OTH, OTH, OTH, # 80 - 87
OTH, OTH, ACO, OTH, ACO, UDF, ACO, UDF, # 88 - 8F
UDF, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 90 - 97
OTH, OTH, ASO, OTH, ASO, UDF, ASO, ACO, # 98 - 9F
OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # A0 - A7
OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # A8 - AF
OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # B0 - B7
OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # B8 - BF
ACV, ACV, ACV, ACV, ACV, ACV, ACO, ACO, # C0 - C7
ACV, ACV, ACV, ACV, ACV, ACV, ACV, ACV, # C8 - CF
ACO, ACO, ACV, ACV, ACV, ACV, ACV, OTH, # D0 - D7
ACV, ACV, ACV, ACV, ACV, ACO, ACO, ACO, # D8 - DF
ASV, ASV, ASV, ASV, ASV, ASV, ASO, ASO, # E0 - E7
ASV, ASV, ASV, ASV, ASV, ASV, ASV, ASV, # E8 - EF
ASO, ASO, ASV, ASV, ASV, ASV, ASV, OTH, # F0 - F7
ASV, ASV, ASV, ASV, ASV, ASO, ASO, ASO, # F8 - FF
)
# 0 : illegal
# 1 : very unlikely
# 2 : normal
# 3 : very likely
Latin1ClassModel = (
# UDF OTH ASC ASS ACV ACO ASV ASO
0, 0, 0, 0, 0, 0, 0, 0, # UDF
0, 3, 3, 3, 3, 3, 3, 3, # OTH
0, 3, 3, 3, 3, 3, 3, 3, # ASC
0, 3, 3, 3, 1, 1, 3, 3, # ASS
0, 3, 3, 3, 1, 2, 1, 2, # ACV
0, 3, 3, 3, 3, 3, 3, 3, # ACO
0, 3, 1, 3, 1, 1, 1, 3, # ASV
0, 3, 1, 3, 1, 1, 3, 3, # ASO
)
class Latin1Prober(CharSetProber):
def __init__(self):
CharSetProber.__init__(self)
self.reset()
def reset(self):
self._mLastCharClass = OTH
self._mFreqCounter = [0] * FREQ_CAT_NUM
CharSetProber.reset(self)
def get_charset_name(self):
return "windows-1252"
def feed(self, aBuf):
aBuf = self.filter_with_english_letters(aBuf)
for c in aBuf:
charClass = Latin1_CharToClass[wrap_ord(c)]
freq = Latin1ClassModel[(self._mLastCharClass * CLASS_NUM)
+ charClass]
if freq == 0:
self._mState = eNotMe
break
self._mFreqCounter[freq] += 1
self._mLastCharClass = charClass
return self.get_state()
def get_confidence(self):
if self.get_state() == eNotMe:
return 0.01
total = sum(self._mFreqCounter)
if total < 0.01:
confidence = 0.0
else:
confidence = ((self._mFreqCounter[3] - self._mFreqCounter[1] * 20.0)
/ total)
if confidence < 0.0:
confidence = 0.0
# lower the confidence of latin1 so that other more accurate
# detector can take priority.
confidence = confidence * 0.73
return confidence
| gpl-3.0 |
roam/machete | machete/endpoints.py | 1 | 25618 | # -*- coding: utf-8 -*-
from __future__ import (unicode_literals, print_function, division,
absolute_import)
import sys
import hashlib
from contextlib import contextmanager
from django.views.decorators.csrf import csrf_exempt
from django.db import transaction, models
from django.views.generic import View
from django.core.exceptions import ImproperlyConfigured
from django.core.urlresolvers import reverse
from django.http import HttpResponse, Http404
from django.utils.http import quote_etag, parse_etags
from .serializers import serialize
from .urls import create_resource_view_name
from .exceptions import (JsonApiError, MissingRequestBody, InvalidDataFormat,
IdMismatch, FormValidationError)
from .utils import (RequestContext, RequestWithResourceContext, pluck_ids,
RequestPayloadDescriptor)
from . import compat, json
@contextmanager
def not_atomic(using=None):
yield
class GetEndpoint(View):
"""
Extends a generic View to provide support for retrieving resources.
Some methods might seem convoluted, but they're mostly built that
way to provide useful points of extension/override. Methods are
rarely passed all information, but request-method methods
(get, post,...) should provide a context object containing the
necessary information under ``self.context``.
"""
context = None
content_type = 'application/json' # Default to this for now; works better in browsers
methods = ['get']
pks_url_key = 'pks'
pk_field = 'pk'
queryset = None
model = None
form_class = None
filter_class = None
include_link_to_self = False
etag_attribute = None
def __init__(self, *args, **kwargs):
super(GetEndpoint, self).__init__(*args, **kwargs)
# Django uses http_method_names to know which methods are
# supported, we always add options on top which will advertise
# the actual methods we support.
self.http_method_names = self.get_methods() + ['options']
@classmethod
def endpoint(cls, **initkwargs):
return csrf_exempt(cls.as_view(**initkwargs))
def dispatch(self, request, *args, **kwargs):
# Override dispatch to enable the handling or errors we can
# handle.
# Because Django 1.4 only sets the request parameters in
# dispatch we'll set them right now ourselves.
self.request = request
self.args = args
self.kwargs = kwargs
manager, m_args, m_kwargs = self.context_manager()
try:
with manager(*m_args, **m_kwargs):
return super(GetEndpoint, self).dispatch(request, *args, **kwargs)
except Exception as error:
et, ei, tb = sys.exc_info()
return self.handle_error(error, tb)
def options(self, request, *args, **kwargs):
# From the JSON API FAQ:
# http://jsonapi.org/faq/#how-to-discover-resource-possible-actions
self.context = self.create_get_context(request)
actions = self.possible_actions()
return HttpResponse(','.join(a.upper() for a in actions))
def possible_actions(self):
"""
Returns a list of allowed methods for this endpoint.
You can use the context (a GET context) to determine what's
possible. By default this simply returns all allowed methods.
"""
return self.get_methods()
def get(self, request, *args, **kwargs):
self.context = self.create_get_context(request)
if not self.has_etag_changed():
content_type = self.get_content_type()
return HttpResponse(status=304, content_type=content_type)
collection = False
if self.context.requested_single_resource:
data = self.get_resource()
else:
data = self.get_resources()
collection = True
return self.create_http_response(data, collection=collection, compound=True)
def has_etag_changed(self):
if not self.etag_attribute:
return True
etag = self.generate_etag()
if not etag:
return True
match = self.request.META.get('HTTP_IF_NONE_MATCH')
if match:
values = parse_etags(match)
for value in values:
# Django appends ";gzip" when gzip is enabled
clean_value = value.split(';')[0]
if clean_value == '*' or clean_value == etag:
return False
return True
def generate_etag(self):
if not self.etag_attribute:
return None
qs = self.get_filtered_queryset()
values = qs.values_list(self.etag_attribute, flat=True)
etag = ','.join('%s' % value for value in values)
return hashlib.md5(etag).hexdigest()
def create_http_response(self, data, collection=False, compound=False):
"""
Creates a HTTP response from the data.
The data might be an (a) HttpResponse object, (b) dict or (c)
object that can be serialized.
HttpResponse objects will simply be returned without further
processing, dicts will be turned into JSON and returned as a
response using the status attribute of the context. Other
objects will be serialized using ``serialize`` method.
"""
if isinstance(data, HttpResponse):
# No more processing necessary
return data
if isinstance(data, dict):
# How nice. Use it!
response_data = data
else:
# Everything else: run it through the serialization process
response_data = self.serialize(data, collection=collection, compound=compound)
json_data = self.create_json(response_data, indent=2)
status = self.context.status
content_type = self.get_content_type()
response = HttpResponse(json_data, content_type=content_type, status=status)
return self.postprocess_response(response, data, response_data, collection)
def serialize(self, data, collection=False, compound=False):
"""
Serializes the data.
Note that a serializer must have been registered with the name
of this resource or relationship, depending on the request type.
"""
name = self.get_resource_type()
context = self.context.__dict__
self_link = self.include_link_to_self
fields = self.context.resource_descriptor.fields
only = fields if fields else None
return serialize(name, data, many=collection, compound=compound, context=context, self_link=self_link, only=only)
def get_resource_type(self):
return self.resource_name
def handle_error(self, error, traceback=None):
# TODO Improve error reporting
error_object = {}
if isinstance(error, FormValidationError):
errors = []
for field, itemized_errors in error.form.errors.items():
composite = field == '__all__'
for e in itemized_errors:
detail = {'detail': '%s' % e}
if not composite:
detail['member'] = field
detail['member_label'] = '%s' % error.form.fields.get(field).label
errors.append(detail)
return HttpResponse(self.create_json({'errors': errors}), status=400)
if isinstance(error, Http404):
error_object['message'] = '%s' % error
return HttpResponse(self.create_json({'errors': [error_object]}), status=404)
if isinstance(error, JsonApiError):
error_object['message'] = '%s' % error
return HttpResponse(self.create_json({'errors': [error_object]}), status=500)
raise error.__class__, error, traceback
def postprocess_response(self, response, data, response_data, collection):
"""
If you need to do any further processing of the HttpResponse
objects, this is the place to do it.
"""
etag = self.generate_etag()
if etag:
response['ETag'] = quote_etag(etag)
response['Cache-Control'] = 'private, max-age=0'
return response
def get_resource(self):
"""
Grabs the resource for a resource request.
Maps to ``GET /posts/1``.
"""
filter = {self.get_pk_field(): self.context.pk}
return self.get_filtered_queryset().get(**filter)
def get_resources(self):
"""
Grabs the resources for a collection request.
Maps to ``GET /posts/1,2,3`` or ``GET /posts``.
"""
qs = self.get_filtered_queryset()
if self.context.pks:
filter = {'%s__in' % self.get_pk_field(): self.context.pks}
qs = qs.filter(**filter)
if self.context.pks and not qs.exists():
raise Http404()
return qs
def get_filtered_queryset(self):
qs = self.get_queryset()
if self.filter_class:
return self.filter_class(self.request.GET, queryset=qs).qs
return qs
def is_changed_besides(self, resource, model):
# TODO Perform simple diff of serialized model with resource
return False
def get_pk_field(self):
"""
Determines the name of the primary key field of the model.
Either set the ``pk_field`` on the class or override this method
when your model's primary key points to another field than the
default.
"""
return self.pk_field
def get_queryset(self):
"""
Get the list of items for this main resource.
This must be an iterable, and may be a queryset
(in which qs-specific behavior will be enabled).
"""
if self.queryset is not None:
queryset = self.queryset
if hasattr(queryset, '_clone'):
queryset = queryset._clone()
elif self.model is not None:
queryset = self.model._default_manager.all()
else:
raise ImproperlyConfigured("'%s' must define 'queryset' or 'model'"
% self.__class__.__name__)
return queryset
def get_content_type(self):
"""
Determines the content type of responses.
Override this method or set ``content_type`` on the class.
"""
return self.content_type
def create_get_context(self, request):
"""Creates the context for a GET request."""
pks = self.kwargs.get(self.pks_url_key, '')
pks = pks.split(',') if pks else []
fields = request.GET.get('fields')
fields = None if not fields else fields.split(',')
resource_descriptor = RequestContext.create_resource_descriptor(self.resource_name, pks, fields=fields)
context = RequestContext(request, resource_descriptor)
context.update_mode('GET')
return context
def extract_resources(self, request):
"""
Extracts resources from the request body.
This should probably be moved elsewhere since it doesn't make
sense in a GET request. But still.
"""
body = request.body
if not body:
raise MissingRequestBody()
resource_name = self.resource_name
try:
data = self.parse_json(body)
if not resource_name in data:
raise InvalidDataFormat('Missing %s as key' % resource_name)
obj = data[resource_name]
if isinstance(obj, list):
resource = None
resources = obj
else:
resource = obj
resources = [obj]
return RequestPayloadDescriptor(resource_name, resources, resource)
except ValueError:
raise InvalidDataFormat()
def parse_json(self, data):
return json.loads(data)
def create_json(self, data, *args, **kwargs):
return json.dumps(data, *args, **kwargs)
def get_methods(self):
return self.methods
def context_manager(self):
if self.request.method in ['POST', 'PUT', 'DELETE', 'PATCH']:
return (transaction.atomic, [], {})
return (not_atomic, [], {})
class GetLinkedEndpoint(GetEndpoint):
relationship_name = None
relationship_pks_url_keys = None
relationship_pk_fields = None
@classmethod
def endpoint(cls, relationship_name=None, **initkwargs):
initkwargs['relationship_name'] = relationship_name
return csrf_exempt(cls.as_view(**initkwargs))
def dispatch(self, request, *args, **kwargs):
if not self.relationship_name:
self.relationship_name = kwargs.get('relationship')
return super(GetLinkedEndpoint, self).dispatch(request, *args, **kwargs)
def get(self, request, *args, **kwargs):
self.context = self.create_get_context(request)
collection = False
# We're dealing with a request for a related resource
if self.context.requested_single_related_resource or not self.context.to_many:
# Either a single relationship id was passed in or the
# relationship is a to-one
data = self.get_related_resource()
else:
# Multiple relationship ids or a to-many relationship
data = self.get_related_resources()
collection = True
return self.create_http_response(data, collection=collection)
def get_related_resource(self):
"""
Handles the retrieval of a related resource.
This will be called when either a single relationship instance
was requested or the relationship is to-one.
"""
qs = self.get_related_queryset()
if not self.context.to_many:
# Since it's not a to-many, we can simply return the value
return qs
pk_field = self.get_relationship_pk_field()
filter = {pk_field: self.context.relationship_pk}
return qs.get(**filter)
def get_related_resources(self):
"""
Handles the retrieval of multiple related resources.
This will be called when either a multiple relationship
instances were requested or no ids were supplied.
"""
qs = self.get_related_queryset().all()
if self.context.relationship_pks:
pk_field = self.get_relationship_pk_field()
filter = {'%s__in' % pk_field: self.context.relationship_pks}
qs = qs.filter(**filter)
if not qs.exists():
raise Http404()
return qs
def get_related_queryset(self):
field_name = self.get_related_field_name()
resource = self.get_resource()
return getattr(resource, field_name)
def get_resource_type(self):
return self.relationship_name
def create_get_context(self, request):
"""Creates the context for a GET request."""
pks = self.kwargs.get(self.pks_url_key, '')
pks = pks.split(',') if pks else []
rel_pks_url_key = self.get_relationship_pks_url_key()
rel_pks = self.kwargs.get(rel_pks_url_key, '')
rel_pks = rel_pks.split(',') if rel_pks else []
many = self.is_to_many_relationship()
rel_descriptor = RequestContext.create_relationship_descriptor(self.relationship_name, rel_pks, many)
resource_descriptor = RequestContext.create_resource_descriptor(self.resource_name, pks, rel_descriptor)
context = RequestContext(request, resource_descriptor)
context.update_mode('GET')
return context
def get_related_field_name(self):
# TODO Use serializer to find correct name by default
return self.relationship_name
def get_relationship_pks_url_key(self):
rel_name = self.get_related_field_name()
keys = self.relationship_pks_url_keys
keys = keys if keys else {}
return keys.get(rel_name, 'rel_pks')
def get_relationship_pk_field(self):
rel_name = self.get_related_field_name()
fields = self.relationship_pk_fields
fields = fields if fields else {}
return fields.get(rel_name, 'pk')
def is_to_many_relationship(self):
rel_name = self.get_related_field_name()
if self.model:
model = self.model
elif self.queryset:
model = self.queryset.model
else:
model = self.get_queryset().model
meta = model._meta
field_object, model, direct, m2m = compat.get_field_by_name(meta, rel_name)
if direct:
return m2m
return field_object.field.rel.multiple
class WithFormMixin(object):
"""
Mixin supporting create and update of resources with a model form.
Note that it relies on some methods made available by the
GetEndpoint.
"""
form_class = None
def get_form_kwargs(self, **kwargs):
return kwargs
def get_form_class(self):
return self.form_class
def form_valid(self, form):
return form.save()
def form_invalid(self, form):
raise FormValidationError('', form=form)
def get_form(self, resource, instance=None):
"""Constructs a new form instance with the supplied data."""
data = self.prepare_form_data(resource, instance)
form_kwargs = {'data': data, 'instance': instance}
form_kwargs = self.get_form_kwargs(**form_kwargs)
form_class = self.get_form_class()
if not form_class:
raise ImproperlyConfigured('Missing form_class')
return form_class(**form_kwargs)
def prepare_form_data(self, resource, instance=None):
"""Last chance to tweak the data being passed to the form."""
if instance:
# The instance is converted to JSON and then loaded to ensure
# special encodings (like timezone-conversion) are performed
as_json = self.create_json(self.serialize(instance, compound=False))
original = json.loads(as_json)
original = original[self.resource_name]
merged = dict(original.items() + original.get('links', {}).items())
data = dict(resource.items() + resource.get('links', {}).items())
for field, value in data.items():
if value is None:
merged[field] = None
else:
merged[field] = value
return merged
return dict(resource.items() + resource.get('links', {}).items())
class PostMixin(object):
"""
Provides support for POST requests on resources.
The ``create_resource`` method must be implemented to actually do
something.
"""
def get_methods(self):
return super(PostMixin, self).get_methods() + ['post']
def post(self, request, *args, **kwargs):
self.context = self.create_post_context(request)
collection = False
payload = self.context.payload
if payload.many:
data = self.create_resources(payload.resources)
collection = True
else:
data = self.create_resource(payload.resource)
return self.create_http_response(data, collection=collection)
def create_post_context(self, request):
payload = self.extract_resources(request)
descriptor = RequestContext.create_resource_descriptor(self.resource_name)
context = RequestWithResourceContext(request, descriptor, payload, status=201)
context.update_mode('POST')
return context
def create_resources(self, resources):
return [self.create_resource(r) for r in resources]
def create_resource(self, resource):
"""Create the resource and return the corresponding model."""
pass
def postprocess_response(self, response, data, response_data, collection):
response = super(PostMixin, self).postprocess_response(response, data, response_data, collection)
if self.context.status != 201:
return response
pks = ','.join(pluck_ids(response_data, self.resource_name))
location = self.create_resource_url(pks)
response['Location'] = location
return response
def create_resource_url(self, pks):
kwargs = {self.pks_url_key: pks}
return reverse(self.get_url_name(), kwargs=kwargs)
def get_url_name(self):
return create_resource_view_name(self.resource_name)
class PostWithFormMixin(PostMixin, WithFormMixin):
"""
Provides an implementation of ``create_resource`` using a form.
"""
def create_resource(self, resource):
form = self.get_form(resource)
if form.is_valid():
return self.form_valid(form)
return self.form_invalid(form)
class PutMixin(object):
"""
Provides support for PUT requests on resources.
This supports both full and partial updates, on single and multiple
resources.
Requires ``update_resource`` to be implemented.
"""
def get_methods(self):
return super(PutMixin, self).get_methods() + ['put']
def put(self, request, *args, **kwargs):
self.context = self.create_put_context(request)
collection = False
payload = self.context.payload
if payload.many:
changed_more, data = self.update_resources(payload.resources)
collection = True
else:
changed_more, data = self.update_resource(payload.resource)
if not changed_more:
# > A server MUST return a 204 No Content status code if an update
# > is successful and the client's current attributes remain up to
# > date. This applies to PUT requests as well as POST and DELETE
# > requests that modify links without affecting other attributes
# > of a resource.
return HttpResponse(status=204)
return self.create_http_response(data, collection=collection)
def create_put_context(self, request):
pks = self.kwargs.get(self.pks_url_key, '')
pks = pks.split(',') if pks else []
payload = self.extract_resources(request)
descriptor = RequestContext.create_resource_descriptor(self.resource_name, pks)
context = RequestWithResourceContext(request, descriptor, payload, status=200)
context.update_mode('PUT')
return context
def update_resources(self, resources):
updated = []
changed = []
for res in resources:
changed_more, result = self.update_resource(res)
updated.append(result)
changed.append(changed_more)
return any(changed), updated
def update_resource(self, resource):
pass
class PutWithFormMixin(PutMixin, WithFormMixin):
"""
Provides an implementation of ``update_resource`` using a form.
"""
def update_resource(self, resource):
resource_id = resource['id']
if resource_id not in self.context.pks:
message = 'Id %s in request body but not in URL' % resource_id
raise IdMismatch(message)
filter = {self.get_pk_field(): resource_id}
instance = self.get_queryset().get(**filter)
form = self.get_form(resource, instance)
if form.is_valid():
model = self.form_valid(form)
return self.is_changed_besides(resource, model), model
return self.form_invalid(form)
class DeleteMixin(object):
"""
Provides support for DELETE request on single + multiple resources.
"""
def get_methods(self):
return super(DeleteMixin, self).get_methods() + ['delete']
def delete(self, request, *args, **kwargs):
self.context = self.create_delete_context(request)
if not self.context.pks:
raise Http404('Missing ids')
# Although the default implementation defers DELETE request for
# both single and multiple resources to the ``perform_delete``
# method, we still split based on
if self.context.requested_single_resource:
not_deleted = self.delete_resource()
else:
not_deleted = self.delete_resources()
if not_deleted:
raise Http404('Resources %s not found' % ','.join(not_deleted))
return HttpResponse(status=204)
def create_delete_context(self, request):
pks = self.kwargs.get(self.pks_url_key, '')
pks = pks.split(',') if pks else []
descriptor = RequestContext.create_resource_descriptor(self.resource_name, pks)
context = RequestContext(request, descriptor)
context.update_mode('DELETE')
return context
def delete_resources(self):
return self.perform_delete(self.context.pks)
def delete_resource(self):
return self.perform_delete(self.context.pks)
def perform_delete(self, pks):
not_deleted = pks[:]
filter = {'%s__in' % self.get_pk_field(): pks}
for item in self.get_queryset().filter(**filter).iterator():
# Fetch each item separately to actually trigger any logic
# performed in the delete method (like implicit deletes)
not_deleted.remove('%s' % item.pk)
item.delete()
return not_deleted
class Endpoint(PostWithFormMixin, PutWithFormMixin, DeleteMixin, GetEndpoint):
"""
Ties everything together.
Use this base class when you need to support GET, POST, PUT and
DELETE and want to use a form to process incoming data.
"""
pass
| bsd-2-clause |
lmazuel/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2017_08_01/models/application_gateway_path_rule_py3.py | 1 | 3100 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from .sub_resource import SubResource
class ApplicationGatewayPathRule(SubResource):
"""Path rule of URL path map of an application gateway.
:param id: Resource ID.
:type id: str
:param paths: Path rules of URL path map.
:type paths: list[str]
:param backend_address_pool: Backend address pool resource of URL path map
path rule.
:type backend_address_pool:
~azure.mgmt.network.v2017_08_01.models.SubResource
:param backend_http_settings: Backend http settings resource of URL path
map path rule.
:type backend_http_settings:
~azure.mgmt.network.v2017_08_01.models.SubResource
:param redirect_configuration: Redirect configuration resource of URL path
map path rule.
:type redirect_configuration:
~azure.mgmt.network.v2017_08_01.models.SubResource
:param provisioning_state: Path rule of URL path map resource. Possible
values are: 'Updating', 'Deleting', and 'Failed'.
:type provisioning_state: str
:param name: Name of the resource that is unique within a resource group.
This name can be used to access the resource.
:type name: str
:param etag: A unique read-only string that changes whenever the resource
is updated.
:type etag: str
:param type: Type of the resource.
:type type: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'paths': {'key': 'properties.paths', 'type': '[str]'},
'backend_address_pool': {'key': 'properties.backendAddressPool', 'type': 'SubResource'},
'backend_http_settings': {'key': 'properties.backendHttpSettings', 'type': 'SubResource'},
'redirect_configuration': {'key': 'properties.redirectConfiguration', 'type': 'SubResource'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
}
def __init__(self, *, id: str=None, paths=None, backend_address_pool=None, backend_http_settings=None, redirect_configuration=None, provisioning_state: str=None, name: str=None, etag: str=None, type: str=None, **kwargs) -> None:
super(ApplicationGatewayPathRule, self).__init__(id=id, **kwargs)
self.paths = paths
self.backend_address_pool = backend_address_pool
self.backend_http_settings = backend_http_settings
self.redirect_configuration = redirect_configuration
self.provisioning_state = provisioning_state
self.name = name
self.etag = etag
self.type = type
| mit |
deKupini/erp | addons/crm_partner_assign/crm_lead.py | 7 | 3002 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import osv
from openerp.tools.translate import _
from openerp.exceptions import UserError
class crm_lead(osv.osv):
_inherit = 'crm.lead'
def get_interested_action(self, cr, uid, interested, context=None):
try:
model, action_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'crm_partner_assign', 'crm_lead_channel_interested_act')
except ValueError:
raise UserError(_("The CRM Channel Interested Action is missing"))
action = self.pool[model].read(cr, uid, [action_id], context=context)[0]
action_context = eval(action['context'])
action_context['interested'] = interested
action['context'] = str(action_context)
return action
def case_interested(self, cr, uid, ids, context=None):
return self.get_interested_action(cr, uid, True, context=context)
def case_disinterested(self, cr, uid, ids, context=None):
return self.get_interested_action(cr, uid, False, context=context)
def assign_salesman_of_assigned_partner(self, cr, uid, ids, context=None):
salesmans_leads = {}
for lead in self.browse(cr, uid, ids, context=context):
if (lead.stage_id.probability > 0 and lead.stage_id.probability < 100) or lead.stage_id.sequence == 1:
if lead.partner_assigned_id and lead.partner_assigned_id.user_id and lead.partner_assigned_id.user_id != lead.user_id:
salesman_id = lead.partner_assigned_id.user_id.id
if salesmans_leads.get(salesman_id):
salesmans_leads[salesman_id].append(lead.id)
else:
salesmans_leads[salesman_id] = [lead.id]
for salesman_id, lead_ids in salesmans_leads.items():
salesteam_id = self.on_change_user(cr, uid, lead_ids, salesman_id, context=None)['value'].get('team_id')
self.write(cr, uid, lead_ids, {'user_id': salesman_id, 'team_id': salesteam_id}, context=context)
| agpl-3.0 |
VitalPet/c2c-rd-addons | stock_get_name_qty/sale.py | 4 | 2994 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
# Copyright (C) 2010-2012 ChriCar Beteiligungs- und Beratungs- GmbH (<http://www.camptocamp.at>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import fields, osv
import logging
from openerp.tools.translate import _
class product_product(osv.osv):
_inherit = 'product.product'
def name_get(self, cr, uid, ids, context=None):
if not context:
context = {}
_logger = logging.getLogger(__name__)
res= super(product_product, self).name_get(cr, uid, ids, context)
digits = self.pool.get('decimal.precision').precision_get(cr, uid, 'Product UoM')
#_logger.debug('FGF prod res %s' % (res))
#_logger.debug('FGF prod context %s ' % (context))
res1 =[]
if context.get('shop'):
context['location_id'] = self.pool.get('sale.shop').read(cr, uid, ['location_id'], [context['shop']])
for r in res:
for product in self.browse(cr, uid, [r[0]], context):
#_logger.debug('FGF prod context %s ' % (context))
uom_name = ' '+product.uom_id.name
qty = product.qty_available
qty_v = product.virtual_available
qty_str = str(round(qty,digits))
if qty_v != qty:
qty_str += ' / ' + str(round(qty_v,digits))
name_new = r[1] + ' [ ' + qty_str + uom_name + ' ]'
#_logger.debug('FGF prod name %s' % (name_new))
if product.packaging:
pack_name = []
for pack in product.packaging:
pack_name.append( '['+pack.ul.name + ' ' + _('á') + ' ' + str(pack.qty) +']' )
packs = ','.join(pack_name)
name_new += packs
l = (r[0],name_new)
res1.append(l)
#_logger.debug('FGF prod res1 %s' % (res1))
else:
res1 = res
return res1
product_product()
| agpl-3.0 |
krintoxi/NoobSec-Toolkit | NoobSecToolkit - MAC OSX/tools/inject/plugins/generic/entries.py | 5 | 22629 | #!/usr/bin/env python
"""
Copyright (c) 2006-2015 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""
import re
from lib.core.agent import agent
from lib.core.bigarray import BigArray
from lib.core.common import Backend
from lib.core.common import clearConsoleLine
from lib.core.common import getLimitRange
from lib.core.common import getSafeExString
from lib.core.common import getUnicode
from lib.core.common import isInferenceAvailable
from lib.core.common import isListLike
from lib.core.common import isNoneValue
from lib.core.common import isNumPosStrValue
from lib.core.common import isTechniqueAvailable
from lib.core.common import prioritySortColumns
from lib.core.common import readInput
from lib.core.common import safeSQLIdentificatorNaming
from lib.core.common import unArrayizeValue
from lib.core.common import unsafeSQLIdentificatorNaming
from lib.core.data import conf
from lib.core.data import kb
from lib.core.data import logger
from lib.core.data import queries
from lib.core.dicts import DUMP_REPLACEMENTS
from lib.core.enums import CHARSET_TYPE
from lib.core.enums import DBMS
from lib.core.enums import EXPECTED
from lib.core.enums import PAYLOAD
from lib.core.exception import SqlmapConnectionException
from lib.core.exception import SqlmapMissingMandatoryOptionException
from lib.core.exception import SqlmapNoneDataException
from lib.core.exception import SqlmapUnsupportedFeatureException
from lib.core.settings import CHECK_ZERO_COLUMNS_THRESHOLD
from lib.core.settings import CURRENT_DB
from lib.core.settings import NULL
from lib.request import inject
from lib.utils.hash import attackDumpedTable
from lib.utils.pivotdumptable import pivotDumpTable
from lib.utils.pivotdumptable import whereQuery
class Entries:
"""
This class defines entries' enumeration functionalities for plugins.
"""
def __init__(self):
pass
def dumpTable(self, foundData=None):
self.forceDbmsEnum()
if conf.db is None or conf.db == CURRENT_DB:
if conf.db is None:
warnMsg = "missing database parameter. sqlmap is going "
warnMsg += "to use the current database to enumerate "
warnMsg += "table(s) entries"
logger.warn(warnMsg)
conf.db = self.getCurrentDb()
elif conf.db is not None:
if Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2, DBMS.HSQLDB):
conf.db = conf.db.upper()
if ',' in conf.db:
errMsg = "only one database name is allowed when enumerating "
errMsg += "the tables' columns"
raise SqlmapMissingMandatoryOptionException(errMsg)
conf.db = safeSQLIdentificatorNaming(conf.db)
if conf.tbl:
if Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2, DBMS.HSQLDB):
conf.tbl = conf.tbl.upper()
tblList = conf.tbl.split(",")
else:
self.getTables()
if len(kb.data.cachedTables) > 0:
tblList = kb.data.cachedTables.values()
if isinstance(tblList[0], (set, tuple, list)):
tblList = tblList[0]
elif not conf.search:
errMsg = "unable to retrieve the tables "
errMsg += "in database '%s'" % unsafeSQLIdentificatorNaming(conf.db)
raise SqlmapNoneDataException(errMsg)
else:
return
for tbl in tblList:
tblList[tblList.index(tbl)] = safeSQLIdentificatorNaming(tbl, True)
for tbl in tblList:
conf.tbl = tbl
kb.data.dumpedTable = {}
if foundData is None:
kb.data.cachedColumns = {}
self.getColumns(onlyColNames=True, dumpMode=True)
else:
kb.data.cachedColumns = foundData
try:
kb.dumpTable = "%s.%s" % (conf.db, tbl)
if not safeSQLIdentificatorNaming(conf.db) in kb.data.cachedColumns \
or safeSQLIdentificatorNaming(tbl, True) not in \
kb.data.cachedColumns[safeSQLIdentificatorNaming(conf.db)] \
or not kb.data.cachedColumns[safeSQLIdentificatorNaming(conf.db)][safeSQLIdentificatorNaming(tbl, True)]:
warnMsg = "unable to enumerate the columns for table "
warnMsg += "'%s' in database" % unsafeSQLIdentificatorNaming(tbl)
warnMsg += " '%s'" % unsafeSQLIdentificatorNaming(conf.db)
warnMsg += ", skipping" if len(tblList) > 1 else ""
logger.warn(warnMsg)
continue
columns = kb.data.cachedColumns[safeSQLIdentificatorNaming(conf.db)][safeSQLIdentificatorNaming(tbl, True)]
colList = sorted(filter(None, columns.keys()))
if conf.excludeCol:
colList = [_ for _ in colList if _ not in conf.excludeCol.split(',')]
if not colList:
warnMsg = "skipping table '%s'" % unsafeSQLIdentificatorNaming(tbl)
warnMsg += " in database '%s'" % unsafeSQLIdentificatorNaming(conf.db)
warnMsg += " (no usable column names)"
logger.warn(warnMsg)
continue
colNames = colString = ", ".join(column for column in colList)
rootQuery = queries[Backend.getIdentifiedDbms()].dump_table
infoMsg = "fetching entries"
if conf.col:
infoMsg += " of column(s) '%s'" % colNames
infoMsg += " for table '%s'" % unsafeSQLIdentificatorNaming(tbl)
infoMsg += " in database '%s'" % unsafeSQLIdentificatorNaming(conf.db)
logger.info(infoMsg)
for column in colList:
_ = agent.preprocessField(tbl, column)
if _ != column:
colString = re.sub(r"\b%s\b" % re.escape(column), _, colString)
entriesCount = 0
if any(isTechniqueAvailable(_) for _ in (PAYLOAD.TECHNIQUE.UNION, PAYLOAD.TECHNIQUE.ERROR, PAYLOAD.TECHNIQUE.QUERY)) or conf.direct:
entries = []
query = None
if Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2):
query = rootQuery.inband.query % (colString, tbl.upper() if not conf.db else ("%s.%s" % (conf.db.upper(), tbl.upper())))
elif Backend.getIdentifiedDbms() in (DBMS.SQLITE, DBMS.ACCESS, DBMS.FIREBIRD, DBMS.MAXDB):
query = rootQuery.inband.query % (colString, tbl)
elif Backend.getIdentifiedDbms() in (DBMS.SYBASE, DBMS.MSSQL):
# Partial inband and error
if not (isTechniqueAvailable(PAYLOAD.TECHNIQUE.UNION) and kb.injection.data[PAYLOAD.TECHNIQUE.UNION].where == PAYLOAD.WHERE.ORIGINAL):
table = "%s.%s" % (conf.db, tbl)
retVal = pivotDumpTable(table, colList, blind=False)
if retVal:
entries, _ = retVal
entries = zip(*[entries[colName] for colName in colList])
else:
query = rootQuery.inband.query % (colString, conf.db, tbl)
elif Backend.getIdentifiedDbms() in (DBMS.MYSQL, DBMS.PGSQL, DBMS.HSQLDB):
query = rootQuery.inband.query % (colString, conf.db, tbl, prioritySortColumns(colList)[0])
else:
query = rootQuery.inband.query % (colString, conf.db, tbl)
query = whereQuery(query)
if not entries and query:
entries = inject.getValue(query, blind=False, time=False, dump=True)
if not isNoneValue(entries):
if isinstance(entries, basestring):
entries = [entries]
elif not isListLike(entries):
entries = []
entriesCount = len(entries)
for index, column in enumerate(colList):
if column not in kb.data.dumpedTable:
kb.data.dumpedTable[column] = {"length": len(column), "values": BigArray()}
for entry in entries:
if entry is None or len(entry) == 0:
continue
if isinstance(entry, basestring):
colEntry = entry
else:
colEntry = unArrayizeValue(entry[index]) if index < len(entry) else u''
_ = len(DUMP_REPLACEMENTS.get(getUnicode(colEntry), getUnicode(colEntry)))
maxLen = max(len(column), _)
if maxLen > kb.data.dumpedTable[column]["length"]:
kb.data.dumpedTable[column]["length"] = maxLen
kb.data.dumpedTable[column]["values"].append(colEntry)
if not kb.data.dumpedTable and isInferenceAvailable() and not conf.direct:
infoMsg = "fetching number of "
if conf.col:
infoMsg += "column(s) '%s' " % colNames
infoMsg += "entries for table '%s' " % unsafeSQLIdentificatorNaming(tbl)
infoMsg += "in database '%s'" % unsafeSQLIdentificatorNaming(conf.db)
logger.info(infoMsg)
if Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2):
query = rootQuery.blind.count % (tbl.upper() if not conf.db else ("%s.%s" % (conf.db.upper(), tbl.upper())))
elif Backend.getIdentifiedDbms() in (DBMS.SQLITE, DBMS.ACCESS, DBMS.FIREBIRD):
query = rootQuery.blind.count % tbl
elif Backend.getIdentifiedDbms() in (DBMS.SYBASE, DBMS.MSSQL):
query = rootQuery.blind.count % ("%s.%s" % (conf.db, tbl))
elif Backend.isDbms(DBMS.MAXDB):
query = rootQuery.blind.count % tbl
else:
query = rootQuery.blind.count % (conf.db, tbl)
query = whereQuery(query)
count = inject.getValue(query, union=False, error=False, expected=EXPECTED.INT, charsetType=CHARSET_TYPE.DIGITS)
lengths = {}
entries = {}
if count == 0:
warnMsg = "table '%s' " % unsafeSQLIdentificatorNaming(tbl)
warnMsg += "in database '%s' " % unsafeSQLIdentificatorNaming(conf.db)
warnMsg += "appears to be empty"
logger.warn(warnMsg)
for column in colList:
lengths[column] = len(column)
entries[column] = []
elif not isNumPosStrValue(count):
warnMsg = "unable to retrieve the number of "
if conf.col:
warnMsg += "column(s) '%s' " % colNames
warnMsg += "entries for table '%s' " % unsafeSQLIdentificatorNaming(tbl)
warnMsg += "in database '%s'" % unsafeSQLIdentificatorNaming(conf.db)
logger.warn(warnMsg)
continue
elif Backend.getIdentifiedDbms() in (DBMS.ACCESS, DBMS.SYBASE, DBMS.MAXDB, DBMS.MSSQL):
if Backend.isDbms(DBMS.ACCESS):
table = tbl
elif Backend.getIdentifiedDbms() in (DBMS.SYBASE, DBMS.MSSQL):
table = "%s.%s" % (conf.db, tbl)
elif Backend.isDbms(DBMS.MAXDB):
table = "%s.%s" % (conf.db, tbl)
retVal = pivotDumpTable(table, colList, count, blind=True)
if retVal:
entries, lengths = retVal
else:
emptyColumns = []
plusOne = Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2)
indexRange = getLimitRange(count, plusOne=plusOne)
if len(colList) < len(indexRange) > CHECK_ZERO_COLUMNS_THRESHOLD:
for column in colList:
if inject.getValue("SELECT COUNT(%s) FROM %s" % (column, kb.dumpTable), union=False, error=False) == '0':
emptyColumns.append(column)
debugMsg = "column '%s' of table '%s' will not be " % (column, kb.dumpTable)
debugMsg += "dumped as it appears to be empty"
logger.debug(debugMsg)
try:
for index in indexRange:
for column in colList:
value = ""
if column not in lengths:
lengths[column] = 0
if column not in entries:
entries[column] = BigArray()
if Backend.getIdentifiedDbms() in (DBMS.MYSQL, DBMS.PGSQL, DBMS.HSQLDB):
query = rootQuery.blind.query % (agent.preprocessField(tbl, column), conf.db, conf.tbl, sorted(colList, key=len)[0], index)
elif Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2):
query = rootQuery.blind.query % (agent.preprocessField(tbl, column),
tbl.upper() if not conf.db else ("%s.%s" % (conf.db.upper(), tbl.upper())),
index)
elif Backend.isDbms(DBMS.SQLITE):
query = rootQuery.blind.query % (agent.preprocessField(tbl, column), tbl, index)
elif Backend.isDbms(DBMS.FIREBIRD):
query = rootQuery.blind.query % (index, agent.preprocessField(tbl, column), tbl)
query = whereQuery(query)
value = NULL if column in emptyColumns else inject.getValue(query, union=False, error=False, dump=True)
value = '' if value is None else value
_ = DUMP_REPLACEMENTS.get(getUnicode(value), getUnicode(value))
lengths[column] = max(lengths[column], len(_))
entries[column].append(value)
except KeyboardInterrupt:
clearConsoleLine()
warnMsg = "Ctrl+C detected in dumping phase"
logger.warn(warnMsg)
for column, columnEntries in entries.items():
length = max(lengths[column], len(column))
kb.data.dumpedTable[column] = {"length": length, "values": columnEntries}
entriesCount = len(columnEntries)
if len(kb.data.dumpedTable) == 0 or (entriesCount == 0 and kb.permissionFlag):
warnMsg = "unable to retrieve the entries "
if conf.col:
warnMsg += "of columns '%s' " % colNames
warnMsg += "for table '%s' " % unsafeSQLIdentificatorNaming(tbl)
warnMsg += "in database '%s'%s" % (unsafeSQLIdentificatorNaming(conf.db), " (permission denied)" if kb.permissionFlag else "")
logger.warn(warnMsg)
else:
kb.data.dumpedTable["__infos__"] = {"count": entriesCount,
"table": safeSQLIdentificatorNaming(tbl, True),
"db": safeSQLIdentificatorNaming(conf.db)}
try:
attackDumpedTable()
except (IOError, OSError), ex:
errMsg = "an error occurred while attacking "
errMsg += "table dump ('%s')" % getSafeExString(ex)
logger.critical(errMsg)
conf.dumper.dbTableValues(kb.data.dumpedTable)
except SqlmapConnectionException, ex:
errMsg = "connection exception detected in dumping phase "
errMsg += "('%s')" % getSafeExString(ex)
logger.critical(errMsg)
finally:
kb.dumpTable = None
def dumpAll(self):
if conf.db is not None and conf.tbl is None:
self.dumpTable()
return
if Backend.isDbms(DBMS.MYSQL) and not kb.data.has_information_schema:
errMsg = "information_schema not available, "
errMsg += "back-end DBMS is MySQL < 5.0"
raise SqlmapUnsupportedFeatureException(errMsg)
infoMsg = "sqlmap will dump entries of all tables from all databases now"
logger.info(infoMsg)
conf.tbl = None
conf.col = None
self.getTables()
if kb.data.cachedTables:
if isinstance(kb.data.cachedTables, list):
kb.data.cachedTables = { None: kb.data.cachedTables }
for db, tables in kb.data.cachedTables.items():
conf.db = db
for table in tables:
try:
conf.tbl = table
kb.data.cachedColumns = {}
kb.data.dumpedTable = {}
self.dumpTable()
except SqlmapNoneDataException:
infoMsg = "skipping table '%s'" % unsafeSQLIdentificatorNaming(table)
logger.info(infoMsg)
def dumpFoundColumn(self, dbs, foundCols, colConsider):
message = "do you want to dump entries? [Y/n] "
output = readInput(message, default="Y")
if output and output[0] not in ("y", "Y"):
return
dumpFromDbs = []
message = "which database(s)?\n[a]ll (default)\n"
for db, tblData in dbs.items():
if tblData:
message += "[%s]\n" % unsafeSQLIdentificatorNaming(db)
message += "[q]uit"
test = readInput(message, default="a")
if not test or test in ("a", "A"):
dumpFromDbs = dbs.keys()
elif test in ("q", "Q"):
return
else:
dumpFromDbs = test.replace(" ", "").split(",")
for db, tblData in dbs.items():
if db not in dumpFromDbs or not tblData:
continue
conf.db = db
dumpFromTbls = []
message = "which table(s) of database '%s'?\n" % unsafeSQLIdentificatorNaming(db)
message += "[a]ll (default)\n"
for tbl in tblData:
message += "[%s]\n" % tbl
message += "[s]kip\n"
message += "[q]uit"
test = readInput(message, default="a")
if not test or test in ("a", "A"):
dumpFromTbls = tblData
elif test in ("s", "S"):
continue
elif test in ("q", "Q"):
return
else:
dumpFromTbls = test.replace(" ", "").split(",")
for table, columns in tblData.items():
if table not in dumpFromTbls:
continue
conf.tbl = table
colList = filter(None, sorted(columns))
if conf.excludeCol:
colList = [_ for _ in colList if _ not in conf.excludeCol.split(',')]
conf.col = ",".join(colList)
kb.data.cachedColumns = {}
kb.data.dumpedTable = {}
data = self.dumpTable(dbs)
if data:
conf.dumper.dbTableValues(data)
def dumpFoundTables(self, tables):
message = "do you want to dump tables' entries? [Y/n] "
output = readInput(message, default="Y")
if output and output[0].lower() != "y":
return
dumpFromDbs = []
message = "which database(s)?\n[a]ll (default)\n"
for db, tablesList in tables.items():
if tablesList:
message += "[%s]\n" % unsafeSQLIdentificatorNaming(db)
message += "[q]uit"
test = readInput(message, default="a")
if not test or test.lower() == "a":
dumpFromDbs = tables.keys()
elif test.lower() == "q":
return
else:
dumpFromDbs = test.replace(" ", "").split(",")
for db, tablesList in tables.items():
if db not in dumpFromDbs or not tablesList:
continue
conf.db = db
dumpFromTbls = []
message = "which table(s) of database '%s'?\n" % unsafeSQLIdentificatorNaming(db)
message += "[a]ll (default)\n"
for tbl in tablesList:
message += "[%s]\n" % unsafeSQLIdentificatorNaming(tbl)
message += "[s]kip\n"
message += "[q]uit"
test = readInput(message, default="a")
if not test or test.lower() == "a":
dumpFromTbls = tablesList
elif test.lower() == "s":
continue
elif test.lower() == "q":
return
else:
dumpFromTbls = test.replace(" ", "").split(",")
for table in dumpFromTbls:
conf.tbl = table
kb.data.cachedColumns = {}
kb.data.dumpedTable = {}
data = self.dumpTable()
if data:
conf.dumper.dbTableValues(data)
| gpl-2.0 |
krintoxi/NoobSec-Toolkit | NoobSecToolkit /tools/inject/plugins/dbms/sybase/enumeration.py | 10 | 9703 | #!/usr/bin/env python
"""
Copyright (c) 2006-2015 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""
from lib.core.common import Backend
from lib.core.common import filterPairValues
from lib.core.common import isTechniqueAvailable
from lib.core.common import randomStr
from lib.core.common import safeSQLIdentificatorNaming
from lib.core.common import unArrayizeValue
from lib.core.common import unsafeSQLIdentificatorNaming
from lib.core.data import conf
from lib.core.data import kb
from lib.core.data import logger
from lib.core.data import queries
from lib.core.dicts import SYBASE_TYPES
from lib.core.enums import PAYLOAD
from lib.core.exception import SqlmapMissingMandatoryOptionException
from lib.core.exception import SqlmapNoneDataException
from lib.core.settings import CURRENT_DB
from lib.utils.pivotdumptable import pivotDumpTable
from plugins.generic.enumeration import Enumeration as GenericEnumeration
class Enumeration(GenericEnumeration):
def __init__(self):
GenericEnumeration.__init__(self)
def getUsers(self):
infoMsg = "fetching database users"
logger.info(infoMsg)
rootQuery = queries[Backend.getIdentifiedDbms()].users
randStr = randomStr()
query = rootQuery.inband.query
if any(isTechniqueAvailable(_) for _ in (PAYLOAD.TECHNIQUE.UNION, PAYLOAD.TECHNIQUE.ERROR, PAYLOAD.TECHNIQUE.QUERY)) or conf.direct:
blinds = (False, True)
else:
blinds = (True,)
for blind in blinds:
retVal = pivotDumpTable("(%s) AS %s" % (query, randStr), ['%s.name' % randStr], blind=blind)
if retVal:
kb.data.cachedUsers = retVal[0].values()[0]
break
return kb.data.cachedUsers
def getPrivileges(self, *args):
warnMsg = "on Sybase it is not possible to fetch "
warnMsg += "database users privileges, sqlmap will check whether "
warnMsg += "or not the database users are database administrators"
logger.warn(warnMsg)
users = []
areAdmins = set()
if conf.user:
users = [conf.user]
elif not len(kb.data.cachedUsers):
users = self.getUsers()
else:
users = kb.data.cachedUsers
for user in users:
user = unArrayizeValue(user)
if user is None:
continue
isDba = self.isDba(user)
if isDba is True:
areAdmins.add(user)
kb.data.cachedUsersPrivileges[user] = None
return (kb.data.cachedUsersPrivileges, areAdmins)
def getDbs(self):
if len(kb.data.cachedDbs) > 0:
return kb.data.cachedDbs
infoMsg = "fetching database names"
logger.info(infoMsg)
rootQuery = queries[Backend.getIdentifiedDbms()].dbs
randStr = randomStr()
query = rootQuery.inband.query
if any(isTechniqueAvailable(_) for _ in (PAYLOAD.TECHNIQUE.UNION, PAYLOAD.TECHNIQUE.ERROR, PAYLOAD.TECHNIQUE.QUERY)) or conf.direct:
blinds = [False, True]
else:
blinds = [True]
for blind in blinds:
retVal = pivotDumpTable("(%s) AS %s" % (query, randStr), ['%s.name' % randStr], blind=blind)
if retVal:
kb.data.cachedDbs = retVal[0].values()[0]
break
if kb.data.cachedDbs:
kb.data.cachedDbs.sort()
return kb.data.cachedDbs
def getTables(self, bruteForce=None):
if len(kb.data.cachedTables) > 0:
return kb.data.cachedTables
self.forceDbmsEnum()
if conf.db == CURRENT_DB:
conf.db = self.getCurrentDb()
if conf.db:
dbs = conf.db.split(",")
else:
dbs = self.getDbs()
for db in dbs:
dbs[dbs.index(db)] = safeSQLIdentificatorNaming(db)
dbs = filter(None, dbs)
infoMsg = "fetching tables for database"
infoMsg += "%s: %s" % ("s" if len(dbs) > 1 else "", ", ".join(db if isinstance(db, basestring) else db[0] for db in sorted(dbs)))
logger.info(infoMsg)
if any(isTechniqueAvailable(_) for _ in (PAYLOAD.TECHNIQUE.UNION, PAYLOAD.TECHNIQUE.ERROR, PAYLOAD.TECHNIQUE.QUERY)) or conf.direct:
blinds = [False, True]
else:
blinds = [True]
rootQuery = queries[Backend.getIdentifiedDbms()].tables
for db in dbs:
for blind in blinds:
randStr = randomStr()
query = rootQuery.inband.query % db
retVal = pivotDumpTable("(%s) AS %s" % (query, randStr), ['%s.name' % randStr], blind=blind)
if retVal:
for table in retVal[0].values()[0]:
if db not in kb.data.cachedTables:
kb.data.cachedTables[db] = [table]
else:
kb.data.cachedTables[db].append(table)
break
for db, tables in kb.data.cachedTables.items():
kb.data.cachedTables[db] = sorted(tables) if tables else tables
return kb.data.cachedTables
def getColumns(self, onlyColNames=False):
self.forceDbmsEnum()
if conf.db is None or conf.db == CURRENT_DB:
if conf.db is None:
warnMsg = "missing database parameter. sqlmap is going "
warnMsg += "to use the current database to enumerate "
warnMsg += "table(s) columns"
logger.warn(warnMsg)
conf.db = self.getCurrentDb()
elif conf.db is not None:
if ',' in conf.db:
errMsg = "only one database name is allowed when enumerating "
errMsg += "the tables' columns"
raise SqlmapMissingMandatoryOptionException(errMsg)
conf.db = safeSQLIdentificatorNaming(conf.db)
if conf.col:
colList = conf.col.split(",")
else:
colList = []
if conf.excludeCol:
colList = [_ for _ in colList if _ not in conf.excludeCol.split(',')]
for col in colList:
colList[colList.index(col)] = safeSQLIdentificatorNaming(col)
if conf.tbl:
tblList = conf.tbl.split(",")
else:
self.getTables()
if len(kb.data.cachedTables) > 0:
tblList = kb.data.cachedTables.values()
if isinstance(tblList[0], (set, tuple, list)):
tblList = tblList[0]
else:
errMsg = "unable to retrieve the tables "
errMsg += "on database '%s'" % unsafeSQLIdentificatorNaming(conf.db)
raise SqlmapNoneDataException(errMsg)
for tbl in tblList:
tblList[tblList.index(tbl)] = safeSQLIdentificatorNaming(tbl)
rootQuery = queries[Backend.getIdentifiedDbms()].columns
if any(isTechniqueAvailable(_) for _ in (PAYLOAD.TECHNIQUE.UNION, PAYLOAD.TECHNIQUE.ERROR, PAYLOAD.TECHNIQUE.QUERY)) or conf.direct:
blinds = [False, True]
else:
blinds = [True]
for tbl in tblList:
if conf.db is not None and len(kb.data.cachedColumns) > 0 \
and conf.db in kb.data.cachedColumns and tbl in \
kb.data.cachedColumns[conf.db]:
infoMsg = "fetched tables' columns on "
infoMsg += "database '%s'" % unsafeSQLIdentificatorNaming(conf.db)
logger.info(infoMsg)
return {conf.db: kb.data.cachedColumns[conf.db]}
if colList:
table = {}
table[safeSQLIdentificatorNaming(tbl)] = dict((_, None) for _ in colList)
kb.data.cachedColumns[safeSQLIdentificatorNaming(conf.db)] = table
continue
infoMsg = "fetching columns "
infoMsg += "for table '%s' " % unsafeSQLIdentificatorNaming(tbl)
infoMsg += "on database '%s'" % unsafeSQLIdentificatorNaming(conf.db)
logger.info(infoMsg)
for blind in blinds:
randStr = randomStr()
query = rootQuery.inband.query % (conf.db, conf.db, conf.db, conf.db, conf.db, conf.db, conf.db, unsafeSQLIdentificatorNaming(tbl))
retVal = pivotDumpTable("(%s) AS %s" % (query, randStr), ['%s.name' % randStr, '%s.usertype' % randStr], blind=blind)
if retVal:
table = {}
columns = {}
for name, type_ in filterPairValues(zip(retVal[0]["%s.name" % randStr], retVal[0]["%s.usertype" % randStr])):
columns[name] = SYBASE_TYPES.get(type_, type_)
table[safeSQLIdentificatorNaming(tbl)] = columns
kb.data.cachedColumns[safeSQLIdentificatorNaming(conf.db)] = table
break
return kb.data.cachedColumns
def searchDb(self):
warnMsg = "on Sybase searching of databases is not implemented"
logger.warn(warnMsg)
return []
def searchTable(self):
warnMsg = "on Sybase searching of tables is not implemented"
logger.warn(warnMsg)
return []
def searchColumn(self):
warnMsg = "on Sybase searching of columns is not implemented"
logger.warn(warnMsg)
return []
def search(self):
warnMsg = "on Sybase search option is not available"
logger.warn(warnMsg)
def getHostname(self):
warnMsg = "on Sybase it is not possible to enumerate the hostname"
logger.warn(warnMsg)
| gpl-2.0 |
zchking/odoo | addons/account_budget/__init__.py | 444 | 1097 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import account_budget
import report
import wizard
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
RamonGuiuGou/l10n-spain | l10n_es_aeat_mod115/models/mod115.py | 2 | 5135 | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp import fields, models, api, _
class L10nEsAeatMod115Report(models.Model):
_description = 'AEAT 115 report'
_inherit = 'l10n.es.aeat.report.tax.mapping'
_name = 'l10n.es.aeat.mod115.report'
number = fields.Char(default='115')
casilla_01 = fields.Integer(
string='[01] Número de perceptores', readonly=True,
states={'calculated': [('readonly', False)]},
help="Casilla [01] Liquidación - Retenciones e ingresos a cuenta - "
"Número de perceptores")
casilla_02 = fields.Float(
string='[02] Base retenciones', readonly=True,
states={'calculated': [('readonly', False)]},
help="Casilla [02] Liquidación - Retenciones e ingresos a cuenta - "
"Base de las retenciones e ingresos a cuenta")
casilla_03 = fields.Float(
string='[03] Retenciones', readonly=True,
states={'calculated': [('readonly', False)]},
help="Casilla [03] Liquidación - Retenciones e ingresos a cuenta - "
"Retenciones e ingresos a cuenta")
casilla_04 = fields.Float(
string='[04] Resultados a ingresar anteriores', readonly=True,
states={'calculated': [('readonly', False)]},
help="Casilla [04] Liquidación - Retenciones e ingresos a cuenta - "
"A deducir (exclusivamente en caso de declaración "
"complementaria) Resultado a ingresar de la anterior o "
"anteriores declaraciones del mismo concepto, ejercicio y "
"período")
casilla_05 = fields.Float(
string='[05] Resultado a ingresar', readonly=True,
compute='get_casilla05',
help='Casilla [04] Liquidación - Retenciones e ingresos a cuenta - '
'Resultado a ingresar: ([03] - [04])')
move_lines_02 = fields.Many2many(
comodel_name='account.move.line',
relation='mod115_account_move_line02_rel',
column1='mod115', column2='account_move_line')
move_lines_03 = fields.Many2many(
comodel_name='account.move.line',
relation='mod115_account_move_line03_rel',
column1='mod115', column2='account_move_line')
currency_id = fields.Many2one(
comodel_name='res.currency', string='Moneda', readonly=True,
related='company_id.currency_id', store=True)
tipo_declaracion = fields.Selection(
selection=[('I', 'Ingreso'),
('U', 'Domiciliación'),
('G', 'Ingreso a anotar en CCT'),
('N', 'Negativa')],
string='Tipo de declaración', readonly=True,
states={'draft': [('readonly', False)]}, required=True)
@api.one
@api.depends('casilla_03', 'casilla_04')
def get_casilla05(self):
self.casilla_05 = self.casilla_03 - self.casilla_04
def __init__(self, pool, cr):
self._aeat_number = '115'
super(L10nEsAeatMod115Report, self).__init__(pool, cr)
@api.multi
def calculate(self):
self.ensure_one()
move_lines02 = self._get_tax_code_lines(['RBI'], periods=self.periods)
move_lines03 = self._get_tax_code_lines(
['RLC115'], periods=self.periods)
self.move_lines_02 = move_lines02.ids
self.move_lines_03 = move_lines03.ids
self.casilla_02 = sum(move_lines02.mapped('tax_amount'))
self.casilla_03 = sum(move_lines03.mapped('tax_amount'))
partners = (move_lines02 + move_lines03).mapped('partner_id')
self.casilla_01 = len(set(partners.ids))
@api.multi
def show_move_lines(self):
move_lines = []
if self.env.context.get('move_lines02', False):
move_lines = self.move_lines_02.ids
elif self.env.context.get('move_lines03', False):
move_lines = self.move_lines_03.ids
view_id = self.env.ref('l10n_es_aeat.view_move_line_tree')
return {'type': 'ir.actions.act_window',
'name': _('Account Move Lines'),
'view_mode': 'tree,form',
'view_type': 'form',
'views': [(view_id.id, 'tree')],
'view_id': False,
'res_model': 'account.move.line',
'domain': [('id', 'in', move_lines)]
}
| agpl-3.0 |
jpalladino84/roguelike-game | data/python_templates/outfits.py | 2 | 1520 | from characters.outfit import Outfit
from data.python_templates import items
from data.python_templates import material
def build_starter_warrior():
return Outfit(
"starter_warrior",
items_worn=[
items.helmet,
items.breastplate,
items.bracer,
items.bracer,
items.gauntlet,
items.gauntlet,
items.greave,
items.greave,
items.boot,
items.boot,
],
items_held=[
items.short_sword
]
)
def build_starter_thief():
leather_bracer_variant = items.bracer.copy()
leather_bracer_variant.material = material.Leather.copy()
leather_gauntlet_variant = items.gauntlet.copy()
leather_gauntlet_variant.material = material.Leather.copy()
leather_boot_variant = items.boot.copy()
leather_boot_variant.material = material.Leather.copy()
return Outfit(
"starter_thief",
items_worn=[
items.leather_hood,
items.leather_cuirass,
leather_bracer_variant,
leather_bracer_variant,
leather_gauntlet_variant,
leather_gauntlet_variant.copy(),
items.leather_pants,
leather_boot_variant,
leather_boot_variant.copy(),
],
items_held=[
items.short_sword
]
)
starter_warrior = build_starter_warrior()
starter_thief = build_starter_thief()
outfits = [starter_warrior, starter_thief]
| mit |
dnlove/ns3 | src/lte/bindings/callbacks_list.py | 21 | 1224 | callback_classes = [
['void', 'ns3::Ptr<ns3::Packet>', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'],
['void', 'ns3::Ptr<ns3::NetDevice>', 'ns3::Ptr<ns3::Packet const>', 'unsigned short', 'ns3::Address const&', 'ns3::Address const&', 'ns3::NetDevice::PacketType', 'ns3::empty', 'ns3::empty', 'ns3::empty'],
['void', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'],
['bool', 'ns3::Ptr<ns3::Packet>', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'],
['bool', 'ns3::Ptr<ns3::NetDevice>', 'ns3::Ptr<ns3::Packet const>', 'unsigned short', 'ns3::Address const&', 'ns3::Address const&', 'ns3::NetDevice::PacketType', 'ns3::empty', 'ns3::empty', 'ns3::empty'],
['bool', 'ns3::Ptr<ns3::NetDevice>', 'ns3::Ptr<ns3::Packet const>', 'unsigned short', 'ns3::Address const&', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'],
['void', 'ns3::Ptr<ns3::Packet const>', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'],
]
| gpl-2.0 |
mread/buck | third-party/py/twitter-commons/src/python/twitter/common/python/util.py | 23 | 5289 | from __future__ import absolute_import
import contextlib
import errno
from hashlib import sha1
import os
import shutil
import uuid
from pkg_resources import find_distributions
from .common import safe_open, safe_rmtree
from .finders import register_finders
class DistributionHelper(object):
@staticmethod
def walk_data(dist, path='/'):
"""Yields filename, stream for files identified as data in the distribution"""
for rel_fn in filter(None, dist.resource_listdir(path)):
full_fn = os.path.join(path, rel_fn)
if dist.resource_isdir(full_fn):
for fn, stream in DistributionHelper.walk_data(dist, full_fn):
yield fn, stream
else:
yield full_fn[1:], dist.get_resource_stream(dist._provider, full_fn)
@staticmethod
def zipsafe(dist):
"""Returns whether or not we determine a distribution is zip-safe."""
# zip-safety is only an attribute of eggs. wheels are considered never
# zip safe per implications of PEP 427.
if hasattr(dist, 'egg_info') and dist.egg_info.endswith('EGG-INFO'):
egg_metadata = dist.metadata_listdir('')
return 'zip-safe' in egg_metadata and 'native_libs.txt' not in egg_metadata
else:
return False
@classmethod
def distribution_from_path(cls, path, name=None):
"""Return a distribution from a path.
If name is provided, find the distribution. If none is found matching the name,
return None. If name is not provided and there is unambiguously a single
distribution, return that distribution otherwise None.
"""
# Monkeypatch pkg_resources finders should it not already be so.
register_finders()
if name is None:
distributions = list(find_distributions(path))
if len(distributions) == 1:
return distributions[0]
else:
for dist in find_distributions(path):
if dist.project_name == name:
return dist
class CacheHelper(object):
@classmethod
def update_hash(cls, filelike, digest):
"""Update the digest of a single file in a memory-efficient manner."""
block_size = digest.block_size * 1024
for chunk in iter(lambda: filelike.read(block_size), b''):
digest.update(chunk)
@classmethod
def hash(cls, path, digest=None, hasher=sha1):
"""Return the digest of a single file in a memory-efficient manner."""
if digest is None:
digest = hasher()
with open(path, 'rb') as fh:
cls.update_hash(fh, digest)
return digest.hexdigest()
@classmethod
def _compute_hash(cls, names, stream_factory):
digest = sha1()
digest.update(''.join(names).encode('utf-8'))
for name in names:
with contextlib.closing(stream_factory(name)) as fp:
cls.update_hash(fp, digest)
return digest.hexdigest()
@classmethod
def zip_hash(cls, zf, prefix=''):
"""Return the hash of the contents of a zipfile, comparable with a cls.dir_hash."""
prefix_length = len(prefix)
names = sorted(name[prefix_length:] for name in zf.namelist()
if name.startswith(prefix) and not name.endswith('.pyc') and not name.endswith('/'))
def stream_factory(name):
return zf.open(prefix + name)
return cls._compute_hash(names, stream_factory)
@classmethod
def _iter_files(cls, directory):
normpath = os.path.normpath(directory)
for root, _, files in os.walk(normpath):
for f in files:
yield os.path.relpath(os.path.join(root, f), normpath)
@classmethod
def pex_hash(cls, d):
"""Return a reproducible hash of the contents of a directory."""
names = sorted(f for f in cls._iter_files(d) if not (f.endswith('.pyc') or f.startswith('.')))
def stream_factory(name):
return open(os.path.join(d, name), 'rb')
return cls._compute_hash(names, stream_factory)
@classmethod
def dir_hash(cls, d):
"""Return a reproducible hash of the contents of a directory."""
names = sorted(f for f in cls._iter_files(d) if not f.endswith('.pyc'))
def stream_factory(name):
return open(os.path.join(d, name), 'rb')
return cls._compute_hash(names, stream_factory)
@classmethod
def cache_distribution(cls, zf, source, target_dir):
"""Possibly cache an egg from within a zipfile into target_cache.
Given a zipfile handle and a filename corresponding to an egg distribution within
that zip, maybe write to the target cache and return a Distribution."""
dependency_basename = os.path.basename(source)
if not os.path.exists(target_dir):
target_dir_tmp = target_dir + '.' + uuid.uuid4().hex
for name in zf.namelist():
if name.startswith(source) and not name.endswith('/'):
# strip off prefix + '/'
target_name = os.path.join(dependency_basename, name[len(source) + 1:])
with contextlib.closing(zf.open(name)) as zi:
with safe_open(os.path.join(target_dir_tmp, target_name), 'wb') as fp:
shutil.copyfileobj(zi, fp)
try:
os.rename(target_dir_tmp, target_dir)
except OSError as e:
if e.errno == errno.ENOTEMPTY:
safe_rmtree(target_dir_tmp)
else:
raise
dist = DistributionHelper.distribution_from_path(target_dir)
assert dist is not None, 'Failed to cache distribution %s' % source
return dist
| apache-2.0 |
unicri/edx-platform | lms/djangoapps/instructor_task/api_helper.py | 102 | 15417 | """
Helper lib for instructor_tasks API.
Includes methods to check args for rescoring task, encoding student input,
and task submission logic, including handling the Celery backend.
"""
import hashlib
import json
import logging
from django.utils.translation import ugettext as _
from celery.result import AsyncResult
from celery.states import READY_STATES, SUCCESS, FAILURE, REVOKED
from courseware.module_render import get_xqueue_callback_url_prefix
from courseware.courses import get_problems_in_section
from xmodule.modulestore.django import modulestore
from opaque_keys.edx.keys import UsageKey
from instructor_task.models import InstructorTask, PROGRESS
log = logging.getLogger(__name__)
class AlreadyRunningError(Exception):
"""Exception indicating that a background task is already running"""
pass
def _task_is_running(course_id, task_type, task_key):
"""Checks if a particular task is already running"""
running_tasks = InstructorTask.objects.filter(
course_id=course_id, task_type=task_type, task_key=task_key
)
# exclude states that are "ready" (i.e. not "running", e.g. failure, success, revoked):
for state in READY_STATES:
running_tasks = running_tasks.exclude(task_state=state)
return len(running_tasks) > 0
def _reserve_task(course_id, task_type, task_key, task_input, requester):
"""
Creates a database entry to indicate that a task is in progress.
Throws AlreadyRunningError if the task is already in progress.
Includes the creation of an arbitrary value for task_id, to be
submitted with the task call to celery.
The InstructorTask.create method makes sure the InstructorTask entry is committed.
When called from any view that is wrapped by TransactionMiddleware,
and thus in a "commit-on-success" transaction, an autocommit buried within here
will cause any pending transaction to be committed by a successful
save here. Any future database operations will take place in a
separate transaction.
Note that there is a chance of a race condition here, when two users
try to run the same task at almost exactly the same time. One user
could be after the check and before the create when the second user
gets to the check. At that point, both users are able to run their
tasks simultaneously. This is deemed a small enough risk to not
put in further safeguards.
"""
if _task_is_running(course_id, task_type, task_key):
log.warning("Duplicate task found for task_type %s and task_key %s", task_type, task_key)
raise AlreadyRunningError("requested task is already running")
try:
most_recent_id = InstructorTask.objects.latest('id').id
except InstructorTask.DoesNotExist:
most_recent_id = "None found"
finally:
log.warning(
"No duplicate tasks found: task_type %s, task_key %s, and most recent task_id = %s",
task_type,
task_key,
most_recent_id
)
# Create log entry now, so that future requests will know it's running.
return InstructorTask.create(course_id, task_type, task_key, task_input, requester)
def _get_xmodule_instance_args(request, task_id):
"""
Calculate parameters needed for instantiating xmodule instances.
The `request_info` will be passed to a tracking log function, to provide information
about the source of the task request. The `xqueue_callback_url_prefix` is used to
permit old-style xqueue callbacks directly to the appropriate module in the LMS.
The `task_id` is also passed to the tracking log function.
"""
request_info = {'username': request.user.username,
'ip': request.META['REMOTE_ADDR'],
'agent': request.META.get('HTTP_USER_AGENT', ''),
'host': request.META['SERVER_NAME'],
}
xmodule_instance_args = {'xqueue_callback_url_prefix': get_xqueue_callback_url_prefix(request),
'request_info': request_info,
'task_id': task_id,
}
return xmodule_instance_args
def _update_instructor_task(instructor_task, task_result):
"""
Updates and possibly saves a InstructorTask entry based on a task Result.
Used when updated status is requested.
The `instructor_task` that is passed in is updated in-place, but
is usually not saved. In general, tasks that have finished (either with
success or failure) should have their entries updated by the task itself,
so are not updated here. Tasks that are still running are not updated
and saved while they run. The one exception to the no-save rule are tasks that
are in a "revoked" state. This may mean that the task never had the
opportunity to update the InstructorTask entry.
Tasks that are in progress and have subtasks doing the processing do not look
to the task's AsyncResult object. When subtasks are running, the
InstructorTask object itself is updated with the subtasks' progress,
not any AsyncResult object. In this case, the InstructorTask is
not updated at all.
Calculates json to store in "task_output" field of the `instructor_task`,
as well as updating the task_state.
For a successful task, the json contains the output of the task result.
For a failed task, the json contains "exception", "message", and "traceback"
keys. A revoked task just has a "message" stating it was revoked.
"""
# Pull values out of the result object as close to each other as possible.
# If we wait and check the values later, the values for the state and result
# are more likely to have changed. Pull the state out first, and
# then code assuming that the result may not exactly match the state.
task_id = task_result.task_id
result_state = task_result.state
returned_result = task_result.result
result_traceback = task_result.traceback
# Assume we don't always save the InstructorTask entry if we don't have to,
# but that in most cases we will update the InstructorTask in-place with its
# current progress.
entry_needs_updating = True
entry_needs_saving = False
task_output = None
if instructor_task.task_state == PROGRESS and len(instructor_task.subtasks) > 0:
# This happens when running subtasks: the result object is marked with SUCCESS,
# meaning that the subtasks have successfully been defined. However, the InstructorTask
# will be marked as in PROGRESS, until the last subtask completes and marks it as SUCCESS.
# We want to ignore the parent SUCCESS if subtasks are still running, and just trust the
# contents of the InstructorTask.
entry_needs_updating = False
elif result_state in [PROGRESS, SUCCESS]:
# construct a status message directly from the task result's result:
# it needs to go back with the entry passed in.
log.info("background task (%s), state %s: result: %s", task_id, result_state, returned_result)
task_output = InstructorTask.create_output_for_success(returned_result)
elif result_state == FAILURE:
# on failure, the result's result contains the exception that caused the failure
exception = returned_result
traceback = result_traceback if result_traceback is not None else ''
log.warning("background task (%s) failed: %s %s", task_id, returned_result, traceback)
task_output = InstructorTask.create_output_for_failure(exception, result_traceback)
elif result_state == REVOKED:
# on revocation, the result's result doesn't contain anything
# but we cannot rely on the worker thread to set this status,
# so we set it here.
entry_needs_saving = True
log.warning("background task (%s) revoked.", task_id)
task_output = InstructorTask.create_output_for_revoked()
# save progress and state into the entry, even if it's not being saved:
# when celery is run in "ALWAYS_EAGER" mode, progress needs to go back
# with the entry passed in.
if entry_needs_updating:
instructor_task.task_state = result_state
if task_output is not None:
instructor_task.task_output = task_output
if entry_needs_saving:
instructor_task.save()
def get_updated_instructor_task(task_id):
"""
Returns InstructorTask object corresponding to a given `task_id`.
If the InstructorTask thinks the task is still running, then
the task's result is checked to return an updated state and output.
"""
# First check if the task_id is known
try:
instructor_task = InstructorTask.objects.get(task_id=task_id)
except InstructorTask.DoesNotExist:
log.warning("query for InstructorTask status failed: task_id=(%s) not found", task_id)
return None
# if the task is not already known to be done, then we need to query
# the underlying task's result object:
if instructor_task.task_state not in READY_STATES:
result = AsyncResult(task_id)
_update_instructor_task(instructor_task, result)
return instructor_task
def get_status_from_instructor_task(instructor_task):
"""
Get the status for a given InstructorTask entry.
Returns a dict, with the following keys:
'task_id': id assigned by LMS and used by celery.
'task_state': state of task as stored in celery's result store.
'in_progress': boolean indicating if task is still running.
'task_progress': dict containing progress information. This includes:
'attempted': number of attempts made
'succeeded': number of attempts that "succeeded"
'total': number of possible subtasks to attempt
'action_name': user-visible verb to use in status messages. Should be past-tense.
'duration_ms': how long the task has (or had) been running.
'exception': name of exception class raised in failed tasks.
'message': returned for failed and revoked tasks.
'traceback': optional, returned if task failed and produced a traceback.
"""
status = {}
if instructor_task is not None:
# status basic information matching what's stored in InstructorTask:
status['task_id'] = instructor_task.task_id
status['task_state'] = instructor_task.task_state
status['in_progress'] = instructor_task.task_state not in READY_STATES
if instructor_task.task_output is not None:
status['task_progress'] = json.loads(instructor_task.task_output)
return status
def check_arguments_for_rescoring(usage_key):
"""
Do simple checks on the descriptor to confirm that it supports rescoring.
Confirms first that the usage_key is defined (since that's currently typed
in). An ItemNotFoundException is raised if the corresponding module
descriptor doesn't exist. NotImplementedError is raised if the
corresponding module doesn't support rescoring calls.
"""
descriptor = modulestore().get_item(usage_key)
if not hasattr(descriptor, 'module_class') or not hasattr(descriptor.module_class, 'rescore_problem'):
msg = "Specified module does not support rescoring."
raise NotImplementedError(msg)
def check_entrance_exam_problems_for_rescoring(exam_key): # pylint: disable=invalid-name
"""
Grabs all problem descriptors in exam and checks each descriptor to
confirm that it supports re-scoring.
An ItemNotFoundException is raised if the corresponding module
descriptor doesn't exist for exam_key. NotImplementedError is raised if
any of the problem in entrance exam doesn't support re-scoring calls.
"""
problems = get_problems_in_section(exam_key).values()
if any(not hasattr(problem, 'module_class') or not hasattr(problem.module_class, 'rescore_problem')
for problem in problems):
msg = _("Not all problems in entrance exam support re-scoring.")
raise NotImplementedError(msg)
def encode_problem_and_student_input(usage_key, student=None): # pylint: disable=invalid-name
"""
Encode optional usage_key and optional student into task_key and task_input values.
Args:
usage_key (Location): The usage_key identifying the problem.
student (User): the student affected
"""
assert isinstance(usage_key, UsageKey)
if student is not None:
task_input = {'problem_url': usage_key.to_deprecated_string(), 'student': student.username}
task_key_stub = "{student}_{problem}".format(student=student.id, problem=usage_key.to_deprecated_string())
else:
task_input = {'problem_url': usage_key.to_deprecated_string()}
task_key_stub = "_{problem}".format(problem=usage_key.to_deprecated_string())
# create the key value by using MD5 hash:
task_key = hashlib.md5(task_key_stub).hexdigest()
return task_input, task_key
def encode_entrance_exam_and_student_input(usage_key, student=None): # pylint: disable=invalid-name
"""
Encode usage_key and optional student into task_key and task_input values.
Args:
usage_key (Location): The usage_key identifying the entrance exam.
student (User): the student affected
"""
assert isinstance(usage_key, UsageKey)
if student is not None:
task_input = {'entrance_exam_url': unicode(usage_key), 'student': student.username}
task_key_stub = "{student}_{entranceexam}".format(student=student.id, entranceexam=unicode(usage_key))
else:
task_input = {'entrance_exam_url': unicode(usage_key)}
task_key_stub = "_{entranceexam}".format(entranceexam=unicode(usage_key))
# create the key value by using MD5 hash:
task_key = hashlib.md5(task_key_stub).hexdigest()
return task_input, task_key
def submit_task(request, task_type, task_class, course_key, task_input, task_key):
"""
Helper method to submit a task.
Reserves the requested task, based on the `course_key`, `task_type`, and `task_key`,
checking to see if the task is already running. The `task_input` is also passed so that
it can be stored in the resulting InstructorTask entry. Arguments are extracted from
the `request` provided by the originating server request. Then the task is submitted to run
asynchronously, using the specified `task_class` and using the task_id constructed for it.
`AlreadyRunningError` is raised if the task is already running.
The _reserve_task method makes sure the InstructorTask entry is committed.
When called from any view that is wrapped by TransactionMiddleware,
and thus in a "commit-on-success" transaction, an autocommit buried within here
will cause any pending transaction to be committed by a successful
save here. Any future database operations will take place in a
separate transaction.
"""
# check to see if task is already running, and reserve it otherwise:
instructor_task = _reserve_task(course_key, task_type, task_key, task_input, request.user)
# submit task:
task_id = instructor_task.task_id
task_args = [instructor_task.id, _get_xmodule_instance_args(request, task_id)] # pylint: disable=no-member
task_class.apply_async(task_args, task_id=task_id)
return instructor_task
| agpl-3.0 |
StefanRijnhart/odoo | addons/project/wizard/project_task_delegate.py | 195 | 6463 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from lxml import etree
from openerp import tools
from openerp.tools.translate import _
from openerp.osv import fields, osv
class project_task_delegate(osv.osv_memory):
_name = 'project.task.delegate'
_description = 'Task Delegate'
_columns = {
'name': fields.char('Delegated Title', required=True, help="New title of the task delegated to the user"),
'prefix': fields.char('Your Task Title', help="Title for your validation task"),
'project_id': fields.many2one('project.project', 'Project', help="User you want to delegate this task to"),
'user_id': fields.many2one('res.users', 'Assign To', required=True, help="User you want to delegate this task to"),
'new_task_description': fields.text('New Task Description', help="Reinclude the description of the task in the task of the user"),
'planned_hours': fields.float('Planned Hours', help="Estimated time to close this task by the delegated user"),
'planned_hours_me': fields.float('Hours to Validate', help="Estimated time for you to validate the work done by the user to whom you delegate this task"),
'state': fields.selection([('pending','Pending'), ('done','Done'), ], 'Validation State', help="New state of your own task. Pending will be reopened automatically when the delegated task is closed")
}
def onchange_project_id(self, cr, uid, ids, project_id=False, context=None):
project_project = self.pool.get('project.project')
if not project_id:
return {'value':{'user_id': False}}
project = project_project.browse(cr, uid, project_id, context=context)
return {'value': {'user_id': project.user_id and project.user_id.id or False}}
def default_get(self, cr, uid, fields, context=None):
"""
This function gets default values
"""
res = super(project_task_delegate, self).default_get(cr, uid, fields, context=context)
if context is None:
context = {}
record_id = context and context.get('active_id', False) or False
if not record_id:
return res
task_pool = self.pool.get('project.task')
task = task_pool.browse(cr, uid, record_id, context=context)
task_name =tools.ustr(task.name)
if 'project_id' in fields:
res['project_id'] = int(task.project_id.id) if task.project_id else False
if 'name' in fields:
if task_name.startswith(_('CHECK: ')):
newname = tools.ustr(task_name).replace(_('CHECK: '), '')
else:
newname = tools.ustr(task_name or '')
res['name'] = newname
if 'planned_hours' in fields:
res['planned_hours'] = task.remaining_hours or 0.0
if 'prefix' in fields:
if task_name.startswith(_('CHECK: ')):
newname = tools.ustr(task_name).replace(_('CHECK: '), '')
else:
newname = tools.ustr(task_name or '')
prefix = _('CHECK: %s') % newname
res['prefix'] = prefix
if 'new_task_description' in fields:
res['new_task_description'] = task.description
return res
_defaults = {
'planned_hours_me': 1.0,
'state': 'pending',
}
def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
res = super(project_task_delegate, self).fields_view_get(cr, uid, view_id, view_type, context, toolbar, submenu=submenu)
users_pool = self.pool.get('res.users')
obj_tm = users_pool.browse(cr, uid, uid, context=context).company_id.project_time_mode_id
tm = obj_tm and obj_tm.name or 'Hours'
if tm in ['Hours','Hour']:
return res
eview = etree.fromstring(res['arch'])
def _check_rec(eview):
if eview.attrib.get('widget','') == 'float_time':
eview.set('widget','float')
for child in eview:
_check_rec(child)
return True
_check_rec(eview)
res['arch'] = etree.tostring(eview)
for field in res['fields']:
if 'Hours' in res['fields'][field]['string']:
res['fields'][field]['string'] = res['fields'][field]['string'].replace('Hours',tm)
return res
def delegate(self, cr, uid, ids, context=None):
if context is None:
context = {}
task_id = context.get('active_id', False)
task_pool = self.pool.get('project.task')
delegate_data = self.read(cr, uid, ids, context=context)[0]
delegated_tasks = task_pool.do_delegate(cr, uid, [task_id], delegate_data, context=context)
models_data = self.pool.get('ir.model.data')
action_model, action_id = models_data.get_object_reference(cr, uid, 'project', 'action_view_task')
view_model, task_view_form_id = models_data.get_object_reference(cr, uid, 'project', 'view_task_form2')
view_model, task_view_tree_id = models_data.get_object_reference(cr, uid, 'project', 'view_task_tree2')
action = self.pool[action_model].read(cr, uid, [action_id], context=context)[0]
action['res_id'] = delegated_tasks[task_id]
action['view_id'] = False
action['views'] = [(task_view_form_id, 'form'), (task_view_tree_id, 'tree')]
action['help'] = False
return action
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.