repo_name
stringlengths 5
100
| ref
stringlengths 12
67
| path
stringlengths 4
244
| copies
stringlengths 1
8
| content
stringlengths 0
1.05M
⌀ |
---|---|---|---|---|
TripleDogDare/RadioWCSpy | refs/heads/master | backend/env/lib/python2.7/sre_compile.py | 4 | /usr/lib/python2.7/sre_compile.py |
sclabs/sitestatus-nonrel | refs/heads/master | django/contrib/localflavor/sk/forms.py | 344 | """
Slovak-specific form helpers
"""
from django.forms.fields import Select, RegexField
from django.utils.translation import ugettext_lazy as _
class SKRegionSelect(Select):
"""
A select widget widget with list of Slovak regions as choices.
"""
def __init__(self, attrs=None):
from sk_regions import REGION_CHOICES
super(SKRegionSelect, self).__init__(attrs, choices=REGION_CHOICES)
class SKDistrictSelect(Select):
"""
A select widget with list of Slovak districts as choices.
"""
def __init__(self, attrs=None):
from sk_districts import DISTRICT_CHOICES
super(SKDistrictSelect, self).__init__(attrs, choices=DISTRICT_CHOICES)
class SKPostalCodeField(RegexField):
"""
A form field that validates its input as Slovak postal code.
Valid form is XXXXX or XXX XX, where X represents integer.
"""
default_error_messages = {
'invalid': _(u'Enter a postal code in the format XXXXX or XXX XX.'),
}
def __init__(self, *args, **kwargs):
super(SKPostalCodeField, self).__init__(r'^\d{5}$|^\d{3} \d{2}$',
max_length=None, min_length=None, *args, **kwargs)
def clean(self, value):
"""
Validates the input and returns a string that contains only numbers.
Returns an empty string for empty values.
"""
v = super(SKPostalCodeField, self).clean(value)
return v.replace(' ', '')
|
alephu5/Soundbyte | refs/heads/master | environment/lib/python3.3/site-packages/tornado/simple_httpclient.py | 18 | #!/usr/bin/env python
from __future__ import absolute_import, division, print_function, with_statement
from tornado.escape import utf8, _unicode, native_str
from tornado.httpclient import HTTPResponse, HTTPError, AsyncHTTPClient, main, _RequestProxy
from tornado.httputil import HTTPHeaders
from tornado.iostream import IOStream, SSLIOStream
from tornado.netutil import Resolver, OverrideResolver
from tornado.log import gen_log
from tornado import stack_context
from tornado.util import GzipDecompressor
import base64
import collections
import copy
import functools
import os.path
import re
import socket
import ssl
import sys
try:
from io import BytesIO # python 3
except ImportError:
from cStringIO import StringIO as BytesIO # python 2
try:
import urlparse # py2
except ImportError:
import urllib.parse as urlparse # py3
_DEFAULT_CA_CERTS = os.path.dirname(__file__) + '/ca-certificates.crt'
class SimpleAsyncHTTPClient(AsyncHTTPClient):
"""Non-blocking HTTP client with no external dependencies.
This class implements an HTTP 1.1 client on top of Tornado's IOStreams.
It does not currently implement all applicable parts of the HTTP
specification, but it does enough to work with major web service APIs.
Some features found in the curl-based AsyncHTTPClient are not yet
supported. In particular, proxies are not supported, connections
are not reused, and callers cannot select the network interface to be
used.
"""
def initialize(self, io_loop, max_clients=10,
hostname_mapping=None, max_buffer_size=104857600,
resolver=None, defaults=None):
"""Creates a AsyncHTTPClient.
Only a single AsyncHTTPClient instance exists per IOLoop
in order to provide limitations on the number of pending connections.
force_instance=True may be used to suppress this behavior.
max_clients is the number of concurrent requests that can be
in progress. Note that this arguments are only used when the
client is first created, and will be ignored when an existing
client is reused.
hostname_mapping is a dictionary mapping hostnames to IP addresses.
It can be used to make local DNS changes when modifying system-wide
settings like /etc/hosts is not possible or desirable (e.g. in
unittests).
max_buffer_size is the number of bytes that can be read by IOStream. It
defaults to 100mb.
"""
super(SimpleAsyncHTTPClient, self).initialize(io_loop,
defaults=defaults)
self.max_clients = max_clients
self.queue = collections.deque()
self.active = {}
self.waiting = {}
self.max_buffer_size = max_buffer_size
if resolver:
self.resolver = resolver
self.own_resolver = False
else:
self.resolver = Resolver(io_loop=io_loop)
self.own_resolver = True
if hostname_mapping is not None:
self.resolver = OverrideResolver(resolver=self.resolver,
mapping=hostname_mapping)
def close(self):
super(SimpleAsyncHTTPClient, self).close()
if self.own_resolver:
self.resolver.close()
def fetch_impl(self, request, callback):
key = object()
self.queue.append((key, request, callback))
if not len(self.active) < self.max_clients:
timeout_handle = self.io_loop.add_timeout(
self.io_loop.time() + min(request.connect_timeout,
request.request_timeout),
functools.partial(self._on_timeout, key))
else:
timeout_handle = None
self.waiting[key] = (request, callback, timeout_handle)
self._process_queue()
if self.queue:
gen_log.debug("max_clients limit reached, request queued. "
"%d active, %d queued requests." % (
len(self.active), len(self.queue)))
def _process_queue(self):
with stack_context.NullContext():
while self.queue and len(self.active) < self.max_clients:
key, request, callback = self.queue.popleft()
if key not in self.waiting:
continue
self._remove_timeout(key)
self.active[key] = (request, callback)
release_callback = functools.partial(self._release_fetch, key)
self._handle_request(request, release_callback, callback)
def _handle_request(self, request, release_callback, final_callback):
_HTTPConnection(self.io_loop, self, request, release_callback,
final_callback, self.max_buffer_size, self.resolver)
def _release_fetch(self, key):
del self.active[key]
self._process_queue()
def _remove_timeout(self, key):
if key in self.waiting:
request, callback, timeout_handle = self.waiting[key]
if timeout_handle is not None:
self.io_loop.remove_timeout(timeout_handle)
del self.waiting[key]
def _on_timeout(self, key):
request, callback, timeout_handle = self.waiting[key]
self.queue.remove((key, request, callback))
timeout_response = HTTPResponse(
request, 599, error=HTTPError(599, "Timeout"),
request_time=self.io_loop.time() - request.start_time)
self.io_loop.add_callback(callback, timeout_response)
del self.waiting[key]
class _HTTPConnection(object):
_SUPPORTED_METHODS = set(["GET", "HEAD", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"])
def __init__(self, io_loop, client, request, release_callback,
final_callback, max_buffer_size, resolver):
self.start_time = io_loop.time()
self.io_loop = io_loop
self.client = client
self.request = request
self.release_callback = release_callback
self.final_callback = final_callback
self.max_buffer_size = max_buffer_size
self.resolver = resolver
self.code = None
self.headers = None
self.chunks = None
self._decompressor = None
# Timeout handle returned by IOLoop.add_timeout
self._timeout = None
with stack_context.ExceptionStackContext(self._handle_exception):
self.parsed = urlparse.urlsplit(_unicode(self.request.url))
if self.parsed.scheme not in ("http", "https"):
raise ValueError("Unsupported url scheme: %s" %
self.request.url)
# urlsplit results have hostname and port results, but they
# didn't support ipv6 literals until python 2.7.
netloc = self.parsed.netloc
if "@" in netloc:
userpass, _, netloc = netloc.rpartition("@")
match = re.match(r'^(.+):(\d+)$', netloc)
if match:
host = match.group(1)
port = int(match.group(2))
else:
host = netloc
port = 443 if self.parsed.scheme == "https" else 80
if re.match(r'^\[.*\]$', host):
# raw ipv6 addresses in urls are enclosed in brackets
host = host[1:-1]
self.parsed_hostname = host # save final host for _on_connect
if request.allow_ipv6:
af = socket.AF_UNSPEC
else:
# We only try the first IP we get from getaddrinfo,
# so restrict to ipv4 by default.
af = socket.AF_INET
timeout = min(self.request.connect_timeout, self.request.request_timeout)
if timeout:
self._timeout = self.io_loop.add_timeout(
self.start_time + timeout,
stack_context.wrap(self._on_timeout))
self.resolver.resolve(host, port, af, callback=self._on_resolve)
def _on_resolve(self, addrinfo):
if self.final_callback is None:
# final_callback is cleared if we've hit our timeout
return
self.stream = self._create_stream(addrinfo)
self.stream.set_close_callback(self._on_close)
# ipv6 addresses are broken (in self.parsed.hostname) until
# 2.7, here is correctly parsed value calculated in __init__
sockaddr = addrinfo[0][1]
self.stream.connect(sockaddr, self._on_connect,
server_hostname=self.parsed_hostname)
def _create_stream(self, addrinfo):
af = addrinfo[0][0]
if self.parsed.scheme == "https":
ssl_options = {}
if self.request.validate_cert:
ssl_options["cert_reqs"] = ssl.CERT_REQUIRED
if self.request.ca_certs is not None:
ssl_options["ca_certs"] = self.request.ca_certs
else:
ssl_options["ca_certs"] = _DEFAULT_CA_CERTS
if self.request.client_key is not None:
ssl_options["keyfile"] = self.request.client_key
if self.request.client_cert is not None:
ssl_options["certfile"] = self.request.client_cert
# SSL interoperability is tricky. We want to disable
# SSLv2 for security reasons; it wasn't disabled by default
# until openssl 1.0. The best way to do this is to use
# the SSL_OP_NO_SSLv2, but that wasn't exposed to python
# until 3.2. Python 2.7 adds the ciphers argument, which
# can also be used to disable SSLv2. As a last resort
# on python 2.6, we set ssl_version to TLSv1. This is
# more narrow than we'd like since it also breaks
# compatibility with servers configured for SSLv3 only,
# but nearly all servers support both SSLv3 and TLSv1:
# http://blog.ivanristic.com/2011/09/ssl-survey-protocol-support.html
if sys.version_info >= (2, 7):
ssl_options["ciphers"] = "DEFAULT:!SSLv2"
else:
# This is really only necessary for pre-1.0 versions
# of openssl, but python 2.6 doesn't expose version
# information.
ssl_options["ssl_version"] = ssl.PROTOCOL_TLSv1
return SSLIOStream(socket.socket(af),
io_loop=self.io_loop,
ssl_options=ssl_options,
max_buffer_size=self.max_buffer_size)
else:
return IOStream(socket.socket(af),
io_loop=self.io_loop,
max_buffer_size=self.max_buffer_size)
def _on_timeout(self):
self._timeout = None
if self.final_callback is not None:
raise HTTPError(599, "Timeout")
def _remove_timeout(self):
if self._timeout is not None:
self.io_loop.remove_timeout(self._timeout)
self._timeout = None
def _on_connect(self):
self._remove_timeout()
if self.final_callback is None:
return
if self.request.request_timeout:
self._timeout = self.io_loop.add_timeout(
self.start_time + self.request.request_timeout,
stack_context.wrap(self._on_timeout))
if (self.request.method not in self._SUPPORTED_METHODS and
not self.request.allow_nonstandard_methods):
raise KeyError("unknown method %s" % self.request.method)
for key in ('network_interface',
'proxy_host', 'proxy_port',
'proxy_username', 'proxy_password'):
if getattr(self.request, key, None):
raise NotImplementedError('%s not supported' % key)
if "Connection" not in self.request.headers:
self.request.headers["Connection"] = "close"
if "Host" not in self.request.headers:
if '@' in self.parsed.netloc:
self.request.headers["Host"] = self.parsed.netloc.rpartition('@')[-1]
else:
self.request.headers["Host"] = self.parsed.netloc
username, password = None, None
if self.parsed.username is not None:
username, password = self.parsed.username, self.parsed.password
elif self.request.auth_username is not None:
username = self.request.auth_username
password = self.request.auth_password or ''
if username is not None:
if self.request.auth_mode not in (None, "basic"):
raise ValueError("unsupported auth_mode %s",
self.request.auth_mode)
auth = utf8(username) + b":" + utf8(password)
self.request.headers["Authorization"] = (b"Basic " +
base64.b64encode(auth))
if self.request.user_agent:
self.request.headers["User-Agent"] = self.request.user_agent
if not self.request.allow_nonstandard_methods:
if self.request.method in ("POST", "PATCH", "PUT"):
if self.request.body is None:
raise AssertionError(
'Body must not be empty for "%s" request'
% self.request.method)
else:
if self.request.body is not None:
raise AssertionError(
'Body must be empty for "%s" request'
% self.request.method)
if self.request.body is not None:
self.request.headers["Content-Length"] = str(len(
self.request.body))
if (self.request.method == "POST" and
"Content-Type" not in self.request.headers):
self.request.headers["Content-Type"] = "application/x-www-form-urlencoded"
if self.request.use_gzip:
self.request.headers["Accept-Encoding"] = "gzip"
req_path = ((self.parsed.path or '/') +
(('?' + self.parsed.query) if self.parsed.query else ''))
request_lines = [utf8("%s %s HTTP/1.1" % (self.request.method,
req_path))]
for k, v in self.request.headers.get_all():
line = utf8(k) + b": " + utf8(v)
if b'\n' in line:
raise ValueError('Newline in header: ' + repr(line))
request_lines.append(line)
request_str = b"\r\n".join(request_lines) + b"\r\n\r\n"
if self.request.body is not None:
request_str += self.request.body
self.stream.set_nodelay(True)
self.stream.write(request_str)
self.stream.read_until_regex(b"\r?\n\r?\n", self._on_headers)
def _release(self):
if self.release_callback is not None:
release_callback = self.release_callback
self.release_callback = None
release_callback()
def _run_callback(self, response):
self._release()
if self.final_callback is not None:
final_callback = self.final_callback
self.final_callback = None
self.io_loop.add_callback(final_callback, response)
def _handle_exception(self, typ, value, tb):
if self.final_callback:
self._remove_timeout()
self._run_callback(HTTPResponse(self.request, 599, error=value,
request_time=self.io_loop.time() - self.start_time,
))
if hasattr(self, "stream"):
self.stream.close()
return True
else:
# If our callback has already been called, we are probably
# catching an exception that is not caused by us but rather
# some child of our callback. Rather than drop it on the floor,
# pass it along.
return False
def _on_close(self):
if self.final_callback is not None:
message = "Connection closed"
if self.stream.error:
message = str(self.stream.error)
raise HTTPError(599, message)
def _handle_1xx(self, code):
self.stream.read_until_regex(b"\r?\n\r?\n", self._on_headers)
def _on_headers(self, data):
data = native_str(data.decode("latin1"))
first_line, _, header_data = data.partition("\n")
match = re.match("HTTP/1.[01] ([0-9]+) ([^\r]*)", first_line)
assert match
code = int(match.group(1))
self.headers = HTTPHeaders.parse(header_data)
if 100 <= code < 200:
self._handle_1xx(code)
return
else:
self.code = code
self.reason = match.group(2)
if "Content-Length" in self.headers:
if "," in self.headers["Content-Length"]:
# Proxies sometimes cause Content-Length headers to get
# duplicated. If all the values are identical then we can
# use them but if they differ it's an error.
pieces = re.split(r',\s*', self.headers["Content-Length"])
if any(i != pieces[0] for i in pieces):
raise ValueError("Multiple unequal Content-Lengths: %r" %
self.headers["Content-Length"])
self.headers["Content-Length"] = pieces[0]
content_length = int(self.headers["Content-Length"])
else:
content_length = None
if self.request.header_callback is not None:
# re-attach the newline we split on earlier
self.request.header_callback(first_line + _)
for k, v in self.headers.get_all():
self.request.header_callback("%s: %s\r\n" % (k, v))
self.request.header_callback('\r\n')
if self.request.method == "HEAD" or self.code == 304:
# HEAD requests and 304 responses never have content, even
# though they may have content-length headers
self._on_body(b"")
return
if 100 <= self.code < 200 or self.code == 204:
# These response codes never have bodies
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.3
if ("Transfer-Encoding" in self.headers or
content_length not in (None, 0)):
raise ValueError("Response with code %d should not have body" %
self.code)
self._on_body(b"")
return
if (self.request.use_gzip and
self.headers.get("Content-Encoding") == "gzip"):
self._decompressor = GzipDecompressor()
if self.headers.get("Transfer-Encoding") == "chunked":
self.chunks = []
self.stream.read_until(b"\r\n", self._on_chunk_length)
elif content_length is not None:
self.stream.read_bytes(content_length, self._on_body)
else:
self.stream.read_until_close(self._on_body)
def _on_body(self, data):
self._remove_timeout()
original_request = getattr(self.request, "original_request",
self.request)
if (self.request.follow_redirects and
self.request.max_redirects > 0 and
self.code in (301, 302, 303, 307)):
assert isinstance(self.request, _RequestProxy)
new_request = copy.copy(self.request.request)
new_request.url = urlparse.urljoin(self.request.url,
self.headers["Location"])
new_request.max_redirects = self.request.max_redirects - 1
del new_request.headers["Host"]
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.4
# Client SHOULD make a GET request after a 303.
# According to the spec, 302 should be followed by the same
# method as the original request, but in practice browsers
# treat 302 the same as 303, and many servers use 302 for
# compatibility with pre-HTTP/1.1 user agents which don't
# understand the 303 status.
if self.code in (302, 303):
new_request.method = "GET"
new_request.body = None
for h in ["Content-Length", "Content-Type",
"Content-Encoding", "Transfer-Encoding"]:
try:
del self.request.headers[h]
except KeyError:
pass
new_request.original_request = original_request
final_callback = self.final_callback
self.final_callback = None
self._release()
self.client.fetch(new_request, final_callback)
self._on_end_request()
return
if self._decompressor:
data = (self._decompressor.decompress(data) +
self._decompressor.flush())
if self.request.streaming_callback:
if self.chunks is None:
# if chunks is not None, we already called streaming_callback
# in _on_chunk_data
self.request.streaming_callback(data)
buffer = BytesIO()
else:
buffer = BytesIO(data) # TODO: don't require one big string?
response = HTTPResponse(original_request,
self.code, reason=self.reason,
headers=self.headers,
request_time=self.io_loop.time() - self.start_time,
buffer=buffer,
effective_url=self.request.url)
self._run_callback(response)
self._on_end_request()
def _on_end_request(self):
self.stream.close()
def _on_chunk_length(self, data):
# TODO: "chunk extensions" http://tools.ietf.org/html/rfc2616#section-3.6.1
length = int(data.strip(), 16)
if length == 0:
if self._decompressor is not None:
tail = self._decompressor.flush()
if tail:
# I believe the tail will always be empty (i.e.
# decompress will return all it can). The purpose
# of the flush call is to detect errors such
# as truncated input. But in case it ever returns
# anything, treat it as an extra chunk
if self.request.streaming_callback is not None:
self.request.streaming_callback(tail)
else:
self.chunks.append(tail)
# all the data has been decompressed, so we don't need to
# decompress again in _on_body
self._decompressor = None
self._on_body(b''.join(self.chunks))
else:
self.stream.read_bytes(length + 2, # chunk ends with \r\n
self._on_chunk_data)
def _on_chunk_data(self, data):
assert data[-2:] == b"\r\n"
chunk = data[:-2]
if self._decompressor:
chunk = self._decompressor.decompress(chunk)
if self.request.streaming_callback is not None:
self.request.streaming_callback(chunk)
else:
self.chunks.append(chunk)
self.stream.read_until(b"\r\n", self._on_chunk_length)
if __name__ == "__main__":
AsyncHTTPClient.configure(SimpleAsyncHTTPClient)
main()
|
anhstudios/swganh | refs/heads/develop | data/scripts/templates/object/tangible/ship/components/weapon/shared_wpn_koensayr_ion_accelerator_2.py | 2 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/ship/components/weapon/shared_wpn_koensayr_ion_accelerator_2.iff"
result.attribute_template_id = 8
result.stfName("space/space_item","wpn_koensayr_ion_accelerator_2_n")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
AkaZuko/gstudio | refs/heads/mongokit | gnowsys-ndf/gnowsys_ndf/ndf/views/feeds.py | 6 | ''' -- Imports from python libraries -- '''
import datetime
import json
import pymongo
import re
''' -- imports from installed packages -- '''
from django.http import HttpResponseRedirect, HttpResponse, Http404
from django.shortcuts import render_to_response, redirect, render
from django.template import RequestContext
from django.template import TemplateDoesNotExist
from django.template.loader import render_to_string
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
from mongokit import paginator
from gnowsys_ndf.ndf.org2any import org2html
from gnowsys_ndf.ndf.models import *
from pymongo import Connection
from django.contrib.syndication.views import Feed
from django.core.urlresolvers import reverse
try:
from bson import ObjectId
except ImportError: # old pymongo
from pymongo.objectid import ObjectId
from gnowsys_ndf.ndf.views.methods import get_group_name_id
benchmark_collection = db[Benchmark.collection_name]
analytics_collection = db[Analytics.collection_name]
ins_objectid = ObjectId()
class activity_feed(Feed):
title_template = 'ndf/feed_updates_title.html'
description_template = 'ndf/feed_updates_description.html'
def title(self, obj):
group_name, group_id = get_group_name_id(obj['group_id'])
return "Updates for the group : "+ group_name+" @ MetaStudio"
def link(self, obj):
group_name, group_id = get_group_name_id(obj['group_id'])
return '/analytics/' + str(group_id) + '/summary/'
def description(self, obj):
group_name, group_id = get_group_name_id(obj['group_id'])
return "Changes and additions to group : " + group_name
author_name = 'MetaStudio'
author_link = 'http://metastudio.org'
feed_copyright = 'Ⓒ Homi Bhabha Centre for Science Education, TIFR'
def get_object(self, request, group_id) :
data = {}
data['group_id'] = group_id
return data
def get_context_data(self, **kwargs) :
context = super(activity_feed, self).get_context_data(**kwargs)
node = db['Nodes'].find_one({ "_id" : ObjectId(kwargs['item']['obj'][kwargs['item']['obj'].keys()[0]]['id'])})
try :
context['node'] = node
author = db['Nodes'].find_one({"_type" : "Author", "created_by" : node['created_by']})
try :
context['author'] = author
except :
pass
except :
pass
return context
def items(self, obj):
cursor = analytics_collection.find({"action.key" : { '$in' : ['create', 'edit']}, "group_id" : obj['group_id']}).sort("timestamp", -1)
return cursor
def item_link(self, item):
return "/"
def item_guid(self, item) :
return item['_id']
|
rofehr/enigma2 | refs/heads/wetek | lib/python/Components/Sources/RecordState.py | 30 | from Source import Source
from Components.Element import cached
from enigma import iRecordableService, pNavigation
import Components.RecordingConfig
from Components.config import config
class RecordState(Source):
def __init__(self, session):
Source.__init__(self)
self.records_running = 0
self.session = session
session.nav.record_event.append(self.gotRecordEvent)
self.gotRecordEvent(None, None) # get initial state
def gotRecordEvent(self, service, event):
prev_records = self.records_running
if event in (iRecordableService.evEnd, iRecordableService.evStart, None):
recs = self.session.nav.getRecordings(False,Components.RecordingConfig.recType(config.recording.show_rec_symbol_for_rec_types.getValue()))
self.records_running = len(recs)
if self.records_running != prev_records:
self.changed((self.CHANGED_ALL,))
def destroy(self):
self.session.nav.record_event.remove(self.gotRecordEvent)
Source.destroy(self)
@cached
def getBoolean(self):
return self.records_running and True or False
boolean = property(getBoolean)
@cached
def getValue(self):
return self.records_running
value = property(getValue)
|
tumbl3w33d/ansible | refs/heads/devel | lib/ansible/modules/cloud/openstack/os_nova_host_aggregate.py | 31 | #!/usr/bin/python
# Copyright 2016 Jakub Jursa <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: os_nova_host_aggregate
short_description: Manage OpenStack host aggregates
extends_documentation_fragment: openstack
author: "Jakub Jursa (@kuboj)"
version_added: "2.3"
description:
- Create, update, or delete OpenStack host aggregates. If a aggregate
with the supplied name already exists, it will be updated with the
new name, new availability zone, new metadata and new list of hosts.
options:
name:
description: Name of the aggregate.
required: true
metadata:
description: Metadata dict.
availability_zone:
description: Availability zone to create aggregate into.
hosts:
description: List of hosts to set for an aggregate.
state:
description: Should the resource be present or absent.
choices: [present, absent]
default: present
requirements:
- "python >= 2.7"
- "openstacksdk"
'''
EXAMPLES = '''
# Create a host aggregate
- os_nova_host_aggregate:
cloud: mycloud
state: present
name: db_aggregate
hosts:
- host1
- host2
metadata:
type: dbcluster
# Delete an aggregate
- os_nova_host_aggregate:
cloud: mycloud
state: absent
name: db_aggregate
'''
RETURN = '''
'''
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 _needs_update(module, aggregate):
new_metadata = (module.params['metadata'] or {})
if module.params['availability_zone'] is not None:
new_metadata['availability_zone'] = module.params['availability_zone']
if ((module.params['name'] != aggregate.name) or
(module.params['hosts'] is not None and set(module.params['hosts']) != set(aggregate.hosts)) or
(module.params['availability_zone'] is not None and module.params['availability_zone'] != aggregate.availability_zone) or
(module.params['metadata'] is not None and new_metadata != aggregate.metadata)):
return True
return False
def _system_state_change(module, aggregate):
state = module.params['state']
if state == 'absent' and aggregate:
return True
if state == 'present':
if aggregate is None:
return True
return _needs_update(module, aggregate)
return False
def main():
argument_spec = openstack_full_argument_spec(
name=dict(required=True),
metadata=dict(required=False, default=None, type='dict'),
availability_zone=dict(required=False, default=None),
hosts=dict(required=False, default=None, type='list'),
state=dict(default='present', choices=['absent', 'present']),
)
module_kwargs = openstack_module_kwargs()
module = AnsibleModule(argument_spec,
supports_check_mode=True,
**module_kwargs)
name = module.params['name']
metadata = module.params['metadata']
availability_zone = module.params['availability_zone']
hosts = module.params['hosts']
state = module.params['state']
if metadata is not None:
metadata.pop('availability_zone', None)
sdk, cloud = openstack_cloud_from_module(module)
try:
aggregates = cloud.search_aggregates(name_or_id=name)
if len(aggregates) == 1:
aggregate = aggregates[0]
elif len(aggregates) == 0:
aggregate = None
else:
raise Exception("Should not happen")
if module.check_mode:
module.exit_json(changed=_system_state_change(module, aggregate))
if state == 'present':
if aggregate is None:
aggregate = cloud.create_aggregate(name=name,
availability_zone=availability_zone)
if hosts:
for h in hosts:
cloud.add_host_to_aggregate(aggregate.id, h)
if metadata:
cloud.set_aggregate_metadata(aggregate.id, metadata)
changed = True
else:
if _needs_update(module, aggregate):
if availability_zone is not None:
aggregate = cloud.update_aggregate(aggregate.id, name=name,
availability_zone=availability_zone)
if metadata is not None:
metas = metadata
for i in (set(aggregate.metadata.keys()) - set(metadata.keys())):
if i != 'availability_zone':
metas[i] = None
cloud.set_aggregate_metadata(aggregate.id, metas)
if hosts is not None:
for i in (set(aggregate.hosts) - set(hosts)):
cloud.remove_host_from_aggregate(aggregate.id, i)
for i in (set(hosts) - set(aggregate.hosts)):
cloud.add_host_to_aggregate(aggregate.id, i)
changed = True
else:
changed = False
module.exit_json(changed=changed)
elif state == 'absent':
if aggregate is None:
changed = False
else:
if hosts:
for h in hosts:
cloud.remove_host_from_aggregate(aggregate.id, h)
cloud.delete_aggregate(aggregate.id)
changed = True
module.exit_json(changed=changed)
except sdk.exceptions.OpenStackCloudException as e:
module.fail_json(msg=str(e))
if __name__ == '__main__':
main()
|
AloneRoad/Inforlearn | refs/heads/1.0-rc3 | django/core/cache/backends/db.py | 17 | "Database cache backend."
from django.core.cache.backends.base import BaseCache
from django.db import connection, transaction, DatabaseError
import base64, time
from datetime import datetime
try:
import cPickle as pickle
except ImportError:
import pickle
class CacheClass(BaseCache):
def __init__(self, table, params):
BaseCache.__init__(self, params)
self._table = table
max_entries = params.get('max_entries', 300)
try:
self._max_entries = int(max_entries)
except (ValueError, TypeError):
self._max_entries = 300
cull_frequency = params.get('cull_frequency', 3)
try:
self._cull_frequency = int(cull_frequency)
except (ValueError, TypeError):
self._cull_frequency = 3
def get(self, key, default=None):
cursor = connection.cursor()
cursor.execute("SELECT cache_key, value, expires FROM %s WHERE cache_key = %%s" % self._table, [key])
row = cursor.fetchone()
if row is None:
return default
now = datetime.now()
if row[2] < now:
cursor.execute("DELETE FROM %s WHERE cache_key = %%s" % self._table, [key])
transaction.commit_unless_managed()
return default
return pickle.loads(base64.decodestring(row[1]))
def set(self, key, value, timeout=None):
self._base_set('set', key, value, timeout)
def add(self, key, value, timeout=None):
return self._base_set('add', key, value, timeout)
def _base_set(self, mode, key, value, timeout=None):
if timeout is None:
timeout = self.default_timeout
cursor = connection.cursor()
cursor.execute("SELECT COUNT(*) FROM %s" % self._table)
num = cursor.fetchone()[0]
now = datetime.now().replace(microsecond=0)
exp = datetime.fromtimestamp(time.time() + timeout).replace(microsecond=0)
if num > self._max_entries:
self._cull(cursor, now)
encoded = base64.encodestring(pickle.dumps(value, 2)).strip()
cursor.execute("SELECT cache_key FROM %s WHERE cache_key = %%s" % self._table, [key])
try:
if mode == 'set' and cursor.fetchone():
cursor.execute("UPDATE %s SET value = %%s, expires = %%s WHERE cache_key = %%s" % self._table, [encoded, str(exp), key])
else:
cursor.execute("INSERT INTO %s (cache_key, value, expires) VALUES (%%s, %%s, %%s)" % self._table, [key, encoded, str(exp)])
except DatabaseError:
# To be threadsafe, updates/inserts are allowed to fail silently
return False
else:
transaction.commit_unless_managed()
return True
def delete(self, key):
cursor = connection.cursor()
cursor.execute("DELETE FROM %s WHERE cache_key = %%s" % self._table, [key])
transaction.commit_unless_managed()
def has_key(self, key):
cursor = connection.cursor()
cursor.execute("SELECT cache_key FROM %s WHERE cache_key = %%s" % self._table, [key])
return cursor.fetchone() is not None
def _cull(self, cursor, now):
if self._cull_frequency == 0:
cursor.execute("DELETE FROM %s" % self._table)
else:
cursor.execute("DELETE FROM %s WHERE expires < %%s" % self._table, [str(now)])
cursor.execute("SELECT COUNT(*) FROM %s" % self._table)
num = cursor.fetchone()[0]
if num > self._max_entries:
cursor.execute("SELECT cache_key FROM %s ORDER BY cache_key LIMIT 1 OFFSET %%s" % self._table, [num / self._cull_frequency])
cursor.execute("DELETE FROM %s WHERE cache_key < %%s" % self._table, [cursor.fetchone()[0]])
|
lunafeng/django | refs/heads/master | django/utils/checksums.py | 310 | """
Common checksum routines.
"""
__all__ = ['luhn']
import warnings
from django.utils import six
from django.utils.deprecation import RemovedInDjango110Warning
warnings.warn(
"django.utils.checksums will be removed in Django 1.10. The "
"luhn() function is now included in django-localflavor 1.1+.",
RemovedInDjango110Warning
)
LUHN_ODD_LOOKUP = (0, 2, 4, 6, 8, 1, 3, 5, 7, 9) # sum_of_digits(index * 2)
def luhn(candidate):
"""
Checks a candidate number for validity according to the Luhn
algorithm (used in validation of, for example, credit cards).
Both numeric and string candidates are accepted.
"""
if not isinstance(candidate, six.string_types):
candidate = str(candidate)
try:
evens = sum(int(c) for c in candidate[-1::-2])
odds = sum(LUHN_ODD_LOOKUP[int(c)] for c in candidate[-2::-2])
return ((evens + odds) % 10 == 0)
except ValueError: # Raised if an int conversion fails
return False
|
La0/mozilla-relengapi | refs/heads/master | src/uplift/bot/tests/test_report.py | 2 | # -*- coding: utf-8 -*-
# Any copyright is dedicated to the Public Domain.
# http://creativecommons.org/publicdomain/zero/1.0/
import json
import responses
@responses.activate
def test_mail(mock_taskcluster_credentials):
'''
Test uplift merge failures email report
'''
from uplift_bot.report import Report
from uplift_bot.merge import MergeTest
def _check_email(request):
payload = json.loads(request.body)
assert payload['subject'] == '[test] Uplift bot detected 2 merge failures to beta, esr52'
assert payload['address'] == '[email protected]'
assert payload['template'] == 'fullscreen'
assert payload['content'].startswith('# Failed automated merge test')
return (200, {}, '') # ack
# Add mock taskcluster email to check output
responses.add_callback(
responses.POST,
'https://notify.taskcluster.net/v1/email',
callback=_check_email,
)
report = Report(['[email protected]'])
report.add_invalid_merge(MergeTest('123456', 'beta', []))
report.add_invalid_merge(MergeTest('123456', 'esr52', []))
report.send('test')
|
le9i0nx/ansible | refs/heads/devel | lib/ansible/modules/network/nxos/_nxos_mtu.py | 12 | #!/usr/bin/python
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['deprecated'],
'supported_by': 'network'}
DOCUMENTATION = '''
---
module: nxos_mtu
extends_documentation_fragment: nxos
version_added: "2.2"
deprecated: Deprecated in 2.3 use M(nxos_system)'s C(mtu) option.
short_description: Manages MTU settings on Nexus switch.
description:
- Manages MTU settings on Nexus switch.
author:
- Jason Edelman (@jedelman8)
notes:
- Tested against NXOSv 7.3.(0)D1(1) on VIRL
- Either C(sysmtu) param is required or (C(interface) AND C(mtu)) parameters are required.
- C(state=absent) unconfigures a given MTU if that value is currently present.
options:
interface:
description:
- Full name of interface, i.e. Ethernet1/1.
required: false
default: null
mtu:
description:
- MTU for a specific interface. Must be an even number between 576 and 9216.
required: false
default: null
sysmtu:
description:
- System jumbo MTU. Must be an even number between 576 and 9216.
required: false
default: null
state:
description:
- Specify desired state of the resource.
required: false
default: present
choices: ['present','absent']
'''
EXAMPLES = '''
# Ensure system mtu is 9126
- nxos_mtu:
sysmtu: 9216
host: "{{ inventory_hostname }}"
username: "{{ un }}"
password: "{{ pwd }}"
# Config mtu on Eth1/1 (routed interface)
- nxos_mtu:
interface: Ethernet1/1
mtu: 1600
host: "{{ inventory_hostname }}"
username: "{{ un }}"
password: "{{ pwd }}"
# Config mtu on Eth1/3 (switched interface)
- nxos_mtu:
interface: Ethernet1/3
mtu: 9216
host: "{{ inventory_hostname }}"
username: "{{ un }}"
password: "{{ pwd }}"
# Unconfigure mtu on a given interface
- nxos_mtu:
interface: Ethernet1/3
mtu: 9216
host: "{{ inventory_hostname }}"
username: "{{ un }}"
password: "{{ pwd }}"
state: absent
'''
RETURN = '''
proposed:
description: k/v pairs of parameters passed into module
returned: always
type: dict
sample: {"mtu": "1700"}
existing:
description:
- k/v pairs of existing mtu/sysmtu on the interface/system
returned: always
type: dict
sample: {"mtu": "1600", "sysmtu": "9216"}
end_state:
description: k/v pairs of mtu/sysmtu values after module execution
returned: always
type: dict
sample: {"mtu": "1700", sysmtu": "9216"}
updates:
description: command sent to the device
returned: always
type: list
sample: ["interface vlan10", "mtu 1700"]
changed:
description: check to see if a change was made on the device
returned: always
type: boolean
sample: true
'''
from ansible.module_utils.network.nxos.nxos import load_config, run_commands
from ansible.module_utils.network.nxos.nxos import nxos_argument_spec, check_args
from ansible.module_utils.basic import AnsibleModule
def execute_show_command(command, module):
if 'show run' not in command:
output = 'json'
else:
output = 'text'
cmds = [{
'command': command,
'output': output,
}]
body = run_commands(module, cmds)
return body
def flatten_list(command_lists):
flat_command_list = []
for command in command_lists:
if isinstance(command, list):
flat_command_list.extend(command)
else:
flat_command_list.append(command)
return flat_command_list
def get_mtu(interface, module):
command = 'show interface {0}'.format(interface)
mtu = {}
body = execute_show_command(command, module)
try:
mtu_table = body[0]['TABLE_interface']['ROW_interface']
mtu['mtu'] = str(
mtu_table.get('eth_mtu',
mtu_table.get('svi_mtu', 'unreadable_via_api')))
mtu['sysmtu'] = get_system_mtu(module)['sysmtu']
except KeyError:
mtu = {}
return mtu
def get_system_mtu(module):
command = 'show run all | inc jumbomtu'
sysmtu = ''
body = execute_show_command(command, module)
if body:
sysmtu = str(body[0].split(' ')[-1])
try:
sysmtu = int(sysmtu)
except:
sysmtu = ""
return dict(sysmtu=str(sysmtu))
def get_commands_config_mtu(delta, interface):
CONFIG_ARGS = {
'mtu': 'mtu {mtu}',
'sysmtu': 'system jumbomtu {sysmtu}',
}
commands = []
for param, value in delta.items():
command = CONFIG_ARGS.get(param, 'DNE').format(**delta)
if command and command != 'DNE':
commands.append(command)
command = None
mtu_check = delta.get('mtu', None)
if mtu_check:
commands.insert(0, 'interface {0}'.format(interface))
return commands
def get_commands_remove_mtu(delta, interface):
CONFIG_ARGS = {
'mtu': 'no mtu {mtu}',
'sysmtu': 'no system jumbomtu {sysmtu}',
}
commands = []
for param, value in delta.items():
command = CONFIG_ARGS.get(param, 'DNE').format(**delta)
if command and command != 'DNE':
commands.append(command)
command = None
mtu_check = delta.get('mtu', None)
if mtu_check:
commands.insert(0, 'interface {0}'.format(interface))
return commands
def get_interface_type(interface):
if interface.upper().startswith('ET'):
return 'ethernet'
elif interface.upper().startswith('VL'):
return 'svi'
elif interface.upper().startswith('LO'):
return 'loopback'
elif interface.upper().startswith('MG'):
return 'management'
elif interface.upper().startswith('MA'):
return 'management'
elif interface.upper().startswith('PO'):
return 'portchannel'
else:
return 'unknown'
def is_default(interface, module):
command = 'show run interface {0}'.format(interface)
try:
body = execute_show_command(command, module)[0]
if body == 'DNE':
return 'DNE'
else:
raw_list = body.split('\n')
if raw_list[-1].startswith('interface'):
return True
else:
return False
except (KeyError):
return 'DNE'
def get_interface_mode(interface, intf_type, module):
command = 'show interface {0}'.format(interface)
mode = 'unknown'
interface_table = {}
body = execute_show_command(command, module)
try:
interface_table = body[0]['TABLE_interface']['ROW_interface']
except (KeyError, AttributeError, IndexError):
return mode
if intf_type in ['ethernet', 'portchannel']:
mode = str(interface_table.get('eth_mode', 'layer3'))
if mode in ['access', 'trunk']:
mode = 'layer2'
elif mode == 'routed':
mode = 'layer3'
elif intf_type in ['loopback', 'svi']:
mode = 'layer3'
return mode
def main():
argument_spec = dict(
mtu=dict(type='str'),
interface=dict(type='str'),
sysmtu=dict(type='str'),
state=dict(choices=['absent', 'present'], default='present'),
)
argument_spec.update(nxos_argument_spec)
module = AnsibleModule(argument_spec=argument_spec,
required_together=[['mtu', 'interface']],
supports_check_mode=True)
warnings = list()
check_args(module, warnings)
interface = module.params['interface']
mtu = module.params['mtu']
sysmtu = module.params['sysmtu']
state = module.params['state']
if sysmtu and (interface or mtu):
module.fail_json(msg='Proper usage-- either just use the sysmtu param '
'or use interface AND mtu params')
if interface:
intf_type = get_interface_type(interface)
if intf_type != 'ethernet':
if is_default(interface, module) == 'DNE':
module.fail_json(msg='Invalid interface. It does not exist '
'on the switch.')
existing = get_mtu(interface, module)
else:
existing = get_system_mtu(module)
if interface and mtu:
if intf_type == 'loopback':
module.fail_json(msg='Cannot set MTU for loopback interface.')
mode = get_interface_mode(interface, intf_type, module)
if mode == 'layer2':
if intf_type in ['ethernet', 'portchannel']:
if mtu not in [existing['sysmtu'], '1500']:
module.fail_json(msg='MTU on L2 interfaces can only be set'
' to the system default (1500) or '
'existing sysmtu value which is '
' {0}'.format(existing['sysmtu']))
elif mode == 'layer3':
if intf_type in ['ethernet', 'portchannel', 'svi']:
if ((int(mtu) < 576 or int(mtu) > 9216) or
((int(mtu) % 2) != 0)):
module.fail_json(msg='Invalid MTU for Layer 3 interface'
'needs to be an even number between'
'576 and 9216')
if sysmtu:
if ((int(sysmtu) < 576 or int(sysmtu) > 9216 or
((int(sysmtu) % 2) != 0))):
module.fail_json(msg='Invalid MTU- needs to be an even '
'number between 576 and 9216')
args = dict(mtu=mtu, sysmtu=sysmtu)
proposed = dict((k, v) for k, v in args.items() if v is not None)
delta = dict(set(proposed.items()).difference(existing.items()))
changed = False
end_state = existing
commands = []
if state == 'present':
if delta:
command = get_commands_config_mtu(delta, interface)
commands.append(command)
elif state == 'absent':
common = set(proposed.items()).intersection(existing.items())
if common:
command = get_commands_remove_mtu(dict(common), interface)
commands.append(command)
cmds = flatten_list(commands)
if cmds:
if module.check_mode:
module.exit_json(changed=True, commands=cmds)
else:
changed = True
load_config(module, cmds)
if interface:
end_state = get_mtu(interface, module)
else:
end_state = get_system_mtu(module)
if 'configure' in cmds:
cmds.pop(0)
results = {}
results['proposed'] = proposed
results['existing'] = existing
results['end_state'] = end_state
results['updates'] = cmds
results['changed'] = changed
results['warnings'] = warnings
module.exit_json(**results)
if __name__ == '__main__':
main()
|
xyuanmu/XX-Net | refs/heads/master | python3.8.2/Lib/email/charset.py | 26 | # Copyright (C) 2001-2007 Python Software Foundation
# Author: Ben Gertzfield, Barry Warsaw
# Contact: [email protected]
__all__ = [
'Charset',
'add_alias',
'add_charset',
'add_codec',
]
from functools import partial
import email.base64mime
import email.quoprimime
from email import errors
from email.encoders import encode_7or8bit
# Flags for types of header encodings
QP = 1 # Quoted-Printable
BASE64 = 2 # Base64
SHORTEST = 3 # the shorter of QP and base64, but only for headers
# In "=?charset?q?hello_world?=", the =?, ?q?, and ?= add up to 7
RFC2047_CHROME_LEN = 7
DEFAULT_CHARSET = 'us-ascii'
UNKNOWN8BIT = 'unknown-8bit'
EMPTYSTRING = ''
# Defaults
CHARSETS = {
# input header enc body enc output conv
'iso-8859-1': (QP, QP, None),
'iso-8859-2': (QP, QP, None),
'iso-8859-3': (QP, QP, None),
'iso-8859-4': (QP, QP, None),
# iso-8859-5 is Cyrillic, and not especially used
# iso-8859-6 is Arabic, also not particularly used
# iso-8859-7 is Greek, QP will not make it readable
# iso-8859-8 is Hebrew, QP will not make it readable
'iso-8859-9': (QP, QP, None),
'iso-8859-10': (QP, QP, None),
# iso-8859-11 is Thai, QP will not make it readable
'iso-8859-13': (QP, QP, None),
'iso-8859-14': (QP, QP, None),
'iso-8859-15': (QP, QP, None),
'iso-8859-16': (QP, QP, None),
'windows-1252':(QP, QP, None),
'viscii': (QP, QP, None),
'us-ascii': (None, None, None),
'big5': (BASE64, BASE64, None),
'gb2312': (BASE64, BASE64, None),
'euc-jp': (BASE64, None, 'iso-2022-jp'),
'shift_jis': (BASE64, None, 'iso-2022-jp'),
'iso-2022-jp': (BASE64, None, None),
'koi8-r': (BASE64, BASE64, None),
'utf-8': (SHORTEST, BASE64, 'utf-8'),
}
# Aliases for other commonly-used names for character sets. Map
# them to the real ones used in email.
ALIASES = {
'latin_1': 'iso-8859-1',
'latin-1': 'iso-8859-1',
'latin_2': 'iso-8859-2',
'latin-2': 'iso-8859-2',
'latin_3': 'iso-8859-3',
'latin-3': 'iso-8859-3',
'latin_4': 'iso-8859-4',
'latin-4': 'iso-8859-4',
'latin_5': 'iso-8859-9',
'latin-5': 'iso-8859-9',
'latin_6': 'iso-8859-10',
'latin-6': 'iso-8859-10',
'latin_7': 'iso-8859-13',
'latin-7': 'iso-8859-13',
'latin_8': 'iso-8859-14',
'latin-8': 'iso-8859-14',
'latin_9': 'iso-8859-15',
'latin-9': 'iso-8859-15',
'latin_10':'iso-8859-16',
'latin-10':'iso-8859-16',
'cp949': 'ks_c_5601-1987',
'euc_jp': 'euc-jp',
'euc_kr': 'euc-kr',
'ascii': 'us-ascii',
}
# Map charsets to their Unicode codec strings.
CODEC_MAP = {
'gb2312': 'eucgb2312_cn',
'big5': 'big5_tw',
# Hack: We don't want *any* conversion for stuff marked us-ascii, as all
# sorts of garbage might be sent to us in the guise of 7-bit us-ascii.
# Let that stuff pass through without conversion to/from Unicode.
'us-ascii': None,
}
# Convenience functions for extending the above mappings
def add_charset(charset, header_enc=None, body_enc=None, output_charset=None):
"""Add character set properties to the global registry.
charset is the input character set, and must be the canonical name of a
character set.
Optional header_enc and body_enc is either Charset.QP for
quoted-printable, Charset.BASE64 for base64 encoding, Charset.SHORTEST for
the shortest of qp or base64 encoding, or None for no encoding. SHORTEST
is only valid for header_enc. It describes how message headers and
message bodies in the input charset are to be encoded. Default is no
encoding.
Optional output_charset is the character set that the output should be
in. Conversions will proceed from input charset, to Unicode, to the
output charset when the method Charset.convert() is called. The default
is to output in the same character set as the input.
Both input_charset and output_charset must have Unicode codec entries in
the module's charset-to-codec mapping; use add_codec(charset, codecname)
to add codecs the module does not know about. See the codecs module's
documentation for more information.
"""
if body_enc == SHORTEST:
raise ValueError('SHORTEST not allowed for body_enc')
CHARSETS[charset] = (header_enc, body_enc, output_charset)
def add_alias(alias, canonical):
"""Add a character set alias.
alias is the alias name, e.g. latin-1
canonical is the character set's canonical name, e.g. iso-8859-1
"""
ALIASES[alias] = canonical
def add_codec(charset, codecname):
"""Add a codec that map characters in the given charset to/from Unicode.
charset is the canonical name of a character set. codecname is the name
of a Python codec, as appropriate for the second argument to the unicode()
built-in, or to the encode() method of a Unicode string.
"""
CODEC_MAP[charset] = codecname
# Convenience function for encoding strings, taking into account
# that they might be unknown-8bit (ie: have surrogate-escaped bytes)
def _encode(string, codec):
if codec == UNKNOWN8BIT:
return string.encode('ascii', 'surrogateescape')
else:
return string.encode(codec)
class Charset:
"""Map character sets to their email properties.
This class provides information about the requirements imposed on email
for a specific character set. It also provides convenience routines for
converting between character sets, given the availability of the
applicable codecs. Given a character set, it will do its best to provide
information on how to use that character set in an email in an
RFC-compliant way.
Certain character sets must be encoded with quoted-printable or base64
when used in email headers or bodies. Certain character sets must be
converted outright, and are not allowed in email. Instances of this
module expose the following information about a character set:
input_charset: The initial character set specified. Common aliases
are converted to their `official' email names (e.g. latin_1
is converted to iso-8859-1). Defaults to 7-bit us-ascii.
header_encoding: If the character set must be encoded before it can be
used in an email header, this attribute will be set to
Charset.QP (for quoted-printable), Charset.BASE64 (for
base64 encoding), or Charset.SHORTEST for the shortest of
QP or BASE64 encoding. Otherwise, it will be None.
body_encoding: Same as header_encoding, but describes the encoding for the
mail message's body, which indeed may be different than the
header encoding. Charset.SHORTEST is not allowed for
body_encoding.
output_charset: Some character sets must be converted before they can be
used in email headers or bodies. If the input_charset is
one of them, this attribute will contain the name of the
charset output will be converted to. Otherwise, it will
be None.
input_codec: The name of the Python codec used to convert the
input_charset to Unicode. If no conversion codec is
necessary, this attribute will be None.
output_codec: The name of the Python codec used to convert Unicode
to the output_charset. If no conversion codec is necessary,
this attribute will have the same value as the input_codec.
"""
def __init__(self, input_charset=DEFAULT_CHARSET):
# RFC 2046, $4.1.2 says charsets are not case sensitive. We coerce to
# unicode because its .lower() is locale insensitive. If the argument
# is already a unicode, we leave it at that, but ensure that the
# charset is ASCII, as the standard (RFC XXX) requires.
try:
if isinstance(input_charset, str):
input_charset.encode('ascii')
else:
input_charset = str(input_charset, 'ascii')
except UnicodeError:
raise errors.CharsetError(input_charset)
input_charset = input_charset.lower()
# Set the input charset after filtering through the aliases
self.input_charset = ALIASES.get(input_charset, input_charset)
# We can try to guess which encoding and conversion to use by the
# charset_map dictionary. Try that first, but let the user override
# it.
henc, benc, conv = CHARSETS.get(self.input_charset,
(SHORTEST, BASE64, None))
if not conv:
conv = self.input_charset
# Set the attributes, allowing the arguments to override the default.
self.header_encoding = henc
self.body_encoding = benc
self.output_charset = ALIASES.get(conv, conv)
# Now set the codecs. If one isn't defined for input_charset,
# guess and try a Unicode codec with the same name as input_codec.
self.input_codec = CODEC_MAP.get(self.input_charset,
self.input_charset)
self.output_codec = CODEC_MAP.get(self.output_charset,
self.output_charset)
def __repr__(self):
return self.input_charset.lower()
def __eq__(self, other):
return str(self) == str(other).lower()
def get_body_encoding(self):
"""Return the content-transfer-encoding used for body encoding.
This is either the string `quoted-printable' or `base64' depending on
the encoding used, or it is a function in which case you should call
the function with a single argument, the Message object being
encoded. The function should then set the Content-Transfer-Encoding
header itself to whatever is appropriate.
Returns "quoted-printable" if self.body_encoding is QP.
Returns "base64" if self.body_encoding is BASE64.
Returns conversion function otherwise.
"""
assert self.body_encoding != SHORTEST
if self.body_encoding == QP:
return 'quoted-printable'
elif self.body_encoding == BASE64:
return 'base64'
else:
return encode_7or8bit
def get_output_charset(self):
"""Return the output character set.
This is self.output_charset if that is not None, otherwise it is
self.input_charset.
"""
return self.output_charset or self.input_charset
def header_encode(self, string):
"""Header-encode a string by converting it first to bytes.
The type of encoding (base64 or quoted-printable) will be based on
this charset's `header_encoding`.
:param string: A unicode string for the header. It must be possible
to encode this string to bytes using the character set's
output codec.
:return: The encoded string, with RFC 2047 chrome.
"""
codec = self.output_codec or 'us-ascii'
header_bytes = _encode(string, codec)
# 7bit/8bit encodings return the string unchanged (modulo conversions)
encoder_module = self._get_encoder(header_bytes)
if encoder_module is None:
return string
return encoder_module.header_encode(header_bytes, codec)
def header_encode_lines(self, string, maxlengths):
"""Header-encode a string by converting it first to bytes.
This is similar to `header_encode()` except that the string is fit
into maximum line lengths as given by the argument.
:param string: A unicode string for the header. It must be possible
to encode this string to bytes using the character set's
output codec.
:param maxlengths: Maximum line length iterator. Each element
returned from this iterator will provide the next maximum line
length. This parameter is used as an argument to built-in next()
and should never be exhausted. The maximum line lengths should
not count the RFC 2047 chrome. These line lengths are only a
hint; the splitter does the best it can.
:return: Lines of encoded strings, each with RFC 2047 chrome.
"""
# See which encoding we should use.
codec = self.output_codec or 'us-ascii'
header_bytes = _encode(string, codec)
encoder_module = self._get_encoder(header_bytes)
encoder = partial(encoder_module.header_encode, charset=codec)
# Calculate the number of characters that the RFC 2047 chrome will
# contribute to each line.
charset = self.get_output_charset()
extra = len(charset) + RFC2047_CHROME_LEN
# Now comes the hard part. We must encode bytes but we can't split on
# bytes because some character sets are variable length and each
# encoded word must stand on its own. So the problem is you have to
# encode to bytes to figure out this word's length, but you must split
# on characters. This causes two problems: first, we don't know how
# many octets a specific substring of unicode characters will get
# encoded to, and second, we don't know how many ASCII characters
# those octets will get encoded to. Unless we try it. Which seems
# inefficient. In the interest of being correct rather than fast (and
# in the hope that there will be few encoded headers in any such
# message), brute force it. :(
lines = []
current_line = []
maxlen = next(maxlengths) - extra
for character in string:
current_line.append(character)
this_line = EMPTYSTRING.join(current_line)
length = encoder_module.header_length(_encode(this_line, charset))
if length > maxlen:
# This last character doesn't fit so pop it off.
current_line.pop()
# Does nothing fit on the first line?
if not lines and not current_line:
lines.append(None)
else:
separator = (' ' if lines else '')
joined_line = EMPTYSTRING.join(current_line)
header_bytes = _encode(joined_line, codec)
lines.append(encoder(header_bytes))
current_line = [character]
maxlen = next(maxlengths) - extra
joined_line = EMPTYSTRING.join(current_line)
header_bytes = _encode(joined_line, codec)
lines.append(encoder(header_bytes))
return lines
def _get_encoder(self, header_bytes):
if self.header_encoding == BASE64:
return email.base64mime
elif self.header_encoding == QP:
return email.quoprimime
elif self.header_encoding == SHORTEST:
len64 = email.base64mime.header_length(header_bytes)
lenqp = email.quoprimime.header_length(header_bytes)
if len64 < lenqp:
return email.base64mime
else:
return email.quoprimime
else:
return None
def body_encode(self, string):
"""Body-encode a string by converting it first to bytes.
The type of encoding (base64 or quoted-printable) will be based on
self.body_encoding. If body_encoding is None, we assume the
output charset is a 7bit encoding, so re-encoding the decoded
string using the ascii codec produces the correct string version
of the content.
"""
if not string:
return string
if self.body_encoding is BASE64:
if isinstance(string, str):
string = string.encode(self.output_charset)
return email.base64mime.body_encode(string)
elif self.body_encoding is QP:
# quopromime.body_encode takes a string, but operates on it as if
# it were a list of byte codes. For a (minimal) history on why
# this is so, see changeset 0cf700464177. To correctly encode a
# character set, then, we must turn it into pseudo bytes via the
# latin1 charset, which will encode any byte as a single code point
# between 0 and 255, which is what body_encode is expecting.
if isinstance(string, str):
string = string.encode(self.output_charset)
string = string.decode('latin1')
return email.quoprimime.body_encode(string)
else:
if isinstance(string, str):
string = string.encode(self.output_charset).decode('ascii')
return string
|
crosswalk-project/web-testing-service | refs/heads/master | wts/tests/xmlhttprequest/w3c/resources/auth3/corsenabled.py | 367 | import imp
import os
def main(request, response):
response.headers.set('Access-Control-Allow-Origin', request.headers.get("origin"));
response.headers.set('Access-Control-Allow-Credentials', 'true');
response.headers.set('Access-Control-Allow-Methods', 'GET');
response.headers.set('Access-Control-Allow-Headers', 'authorization, x-user, x-pass');
response.headers.set('Access-Control-Expose-Headers', 'x-challenge, xhr-user, ses-user');
auth = imp.load_source("", os.path.join(os.path.abspath(os.curdir),
"XMLHttpRequest",
"resources",
"authentication.py"))
if request.method == "OPTIONS":
return ""
else:
return auth.main(request, response)
|
ingtechteam/pyticketswitch | refs/heads/master | setup.py | 1 | from distutils.core import setup
setup(
name='pyticketswitch',
version='1.6.3',
author='Ingresso',
author_email='[email protected]',
packages=[
'pyticketswitch',
'pyticketswitch.test',
'pyticketswitch.interface_objects'
],
license='LICENSE.txt',
description='A Python interface for the Ingresso XML Core API',
long_description=open('README.rst').read(),
classifiers=[
'Development Status :: 5 - Production/Stable',
'Programming Language :: Python :: 2.7',
],
)
|
ruediger/gcc-python-plugin | refs/heads/cpp | tests/cpychecker/refcounts/_PyObject_New/correct/script.py | 623 | # -*- coding: utf-8 -*-
# Copyright 2011 David Malcolm <[email protected]>
# Copyright 2011 Red Hat, Inc.
#
# This is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see
# <http://www.gnu.org/licenses/>.
from libcpychecker import main
main(verify_refcounting=True,
dump_traces=True,
show_traces=False)
|
petecummings/django | refs/heads/master | django/templatetags/tz.py | 277 | from datetime import datetime, tzinfo
from django.template import Library, Node, TemplateSyntaxError
from django.utils import six, timezone
try:
import pytz
except ImportError:
pytz = None
register = Library()
# HACK: datetime is an old-style class, create a new-style equivalent
# so we can define additional attributes.
class datetimeobject(datetime, object):
pass
# Template filters
@register.filter
def localtime(value):
"""
Converts a datetime to local time in the active time zone.
This only makes sense within a {% localtime off %} block.
"""
return do_timezone(value, timezone.get_current_timezone())
@register.filter
def utc(value):
"""
Converts a datetime to UTC.
"""
return do_timezone(value, timezone.utc)
@register.filter('timezone')
def do_timezone(value, arg):
"""
Converts a datetime to local time in a given time zone.
The argument must be an instance of a tzinfo subclass or a time zone name.
If it is a time zone name, pytz is required.
Naive datetimes are assumed to be in local time in the default time zone.
"""
if not isinstance(value, datetime):
return ''
# Obtain a timezone-aware datetime
try:
if timezone.is_naive(value):
default_timezone = timezone.get_default_timezone()
value = timezone.make_aware(value, default_timezone)
# Filters must never raise exceptions, and pytz' exceptions inherit
# Exception directly, not a specific subclass. So catch everything.
except Exception:
return ''
# Obtain a tzinfo instance
if isinstance(arg, tzinfo):
tz = arg
elif isinstance(arg, six.string_types) and pytz is not None:
try:
tz = pytz.timezone(arg)
except pytz.UnknownTimeZoneError:
return ''
else:
return ''
result = timezone.localtime(value, tz)
# HACK: the convert_to_local_time flag will prevent
# automatic conversion of the value to local time.
result = datetimeobject(result.year, result.month, result.day,
result.hour, result.minute, result.second,
result.microsecond, result.tzinfo)
result.convert_to_local_time = False
return result
# Template tags
class LocalTimeNode(Node):
"""
Template node class used by ``localtime_tag``.
"""
def __init__(self, nodelist, use_tz):
self.nodelist = nodelist
self.use_tz = use_tz
def render(self, context):
old_setting = context.use_tz
context.use_tz = self.use_tz
output = self.nodelist.render(context)
context.use_tz = old_setting
return output
class TimezoneNode(Node):
"""
Template node class used by ``timezone_tag``.
"""
def __init__(self, nodelist, tz):
self.nodelist = nodelist
self.tz = tz
def render(self, context):
with timezone.override(self.tz.resolve(context)):
output = self.nodelist.render(context)
return output
class GetCurrentTimezoneNode(Node):
"""
Template node class used by ``get_current_timezone_tag``.
"""
def __init__(self, variable):
self.variable = variable
def render(self, context):
context[self.variable] = timezone.get_current_timezone_name()
return ''
@register.tag('localtime')
def localtime_tag(parser, token):
"""
Forces or prevents conversion of datetime objects to local time,
regardless of the value of ``settings.USE_TZ``.
Sample usage::
{% localtime off %}{{ value_in_utc }}{% endlocaltime %}
"""
bits = token.split_contents()
if len(bits) == 1:
use_tz = True
elif len(bits) > 2 or bits[1] not in ('on', 'off'):
raise TemplateSyntaxError("%r argument should be 'on' or 'off'" %
bits[0])
else:
use_tz = bits[1] == 'on'
nodelist = parser.parse(('endlocaltime',))
parser.delete_first_token()
return LocalTimeNode(nodelist, use_tz)
@register.tag('timezone')
def timezone_tag(parser, token):
"""
Enables a given time zone just for this block.
The ``timezone`` argument must be an instance of a ``tzinfo`` subclass, a
time zone name, or ``None``. If is it a time zone name, pytz is required.
If it is ``None``, the default time zone is used within the block.
Sample usage::
{% timezone "Europe/Paris" %}
It is {{ now }} in Paris.
{% endtimezone %}
"""
bits = token.split_contents()
if len(bits) != 2:
raise TemplateSyntaxError("'%s' takes one argument (timezone)" %
bits[0])
tz = parser.compile_filter(bits[1])
nodelist = parser.parse(('endtimezone',))
parser.delete_first_token()
return TimezoneNode(nodelist, tz)
@register.tag("get_current_timezone")
def get_current_timezone_tag(parser, token):
"""
Stores the name of the current time zone in the context.
Usage::
{% get_current_timezone as TIME_ZONE %}
This will fetch the currently active time zone and put its name
into the ``TIME_ZONE`` context variable.
"""
# token.split_contents() isn't useful here because this tag doesn't accept variable as arguments
args = token.contents.split()
if len(args) != 3 or args[1] != 'as':
raise TemplateSyntaxError("'get_current_timezone' requires "
"'as variable' (got %r)" % args)
return GetCurrentTimezoneNode(args[2])
|
brakhane/panda3d | refs/heads/master | direct/src/gui/DirectScrollBar.py | 2 | """Undocumented Module"""
__all__ = ['DirectScrollBar']
from panda3d.core import *
from . import DirectGuiGlobals as DGG
from .DirectFrame import *
from .DirectButton import *
"""
import DirectScrollBar
d = DirectScrollBar(borderWidth=(0, 0))
"""
class DirectScrollBar(DirectFrame):
"""
DirectScrollBar -- a widget which represents a scroll bar the user can
use for paging through a large document or panel.
"""
def __init__(self, parent = None, **kw):
optiondefs = (
# Define type of DirectGuiWidget
('pgFunc', PGSliderBar, None),
('state', DGG.NORMAL, None),
('frameColor', (0.6, 0.6, 0.6, 1), None),
('range', (0, 1), self.setRange),
('value', 0, self.__setValue),
('scrollSize', 0.01, self.setScrollSize),
('pageSize', 0.1, self.setPageSize),
('orientation', DGG.HORIZONTAL, self.setOrientation),
('manageButtons', 1, self.setManageButtons),
('resizeThumb', 1, self.setResizeThumb),
# Function to be called repeatedly as the bar is scrolled
('command', None, None),
('extraArgs', [], None),
)
if kw.get('orientation') in (DGG.VERTICAL, DGG.VERTICAL_INVERTED):
# These are the default options for a vertical layout.
optiondefs += (
('frameSize', (-0.04, 0.04, -0.5, 0.5), None),
)
else:
# These are the default options for a horizontal layout.
optiondefs += (
('frameSize', (-0.5, 0.5, -0.04, 0.04), None),
)
# Merge keyword options with default options
self.defineoptions(kw, optiondefs)
# Initialize superclasses
DirectFrame.__init__(self, parent)
self.thumb = self.createcomponent(
"thumb", (), None,
DirectButton, (self,),
borderWidth = self['borderWidth'])
self.incButton = self.createcomponent(
"incButton", (), None,
DirectButton, (self,),
borderWidth = self['borderWidth'])
self.decButton = self.createcomponent(
"decButton", (), None,
DirectButton, (self,),
borderWidth = self['borderWidth'])
if self.decButton['frameSize'] == None and \
self.decButton.bounds == [0.0, 0.0, 0.0, 0.0]:
f = self['frameSize']
if self['orientation'] == DGG.HORIZONTAL:
self.decButton['frameSize'] = (f[0]*0.05, f[1]*0.05, f[2], f[3])
else:
self.decButton['frameSize'] = (f[0], f[1], f[2]*0.05, f[3]*0.05)
if self.incButton['frameSize'] == None and \
self.incButton.bounds == [0.0, 0.0, 0.0, 0.0]:
f = self['frameSize']
if self['orientation'] == DGG.HORIZONTAL:
self.incButton['frameSize'] = (f[0]*0.05, f[1]*0.05, f[2], f[3])
else:
self.incButton['frameSize'] = (f[0], f[1], f[2]*0.05, f[3]*0.05)
self.guiItem.setThumbButton(self.thumb.guiItem)
self.guiItem.setLeftButton(self.decButton.guiItem)
self.guiItem.setRightButton(self.incButton.guiItem)
# Bind command function
self.bind(DGG.ADJUST, self.commandFunc)
# Call option initialization functions
self.initialiseoptions(DirectScrollBar)
def setRange(self):
# Try to preserve the value across a setRange call.
v = self['value']
r = self['range']
self.guiItem.setRange(r[0], r[1])
self['value'] = v
def __setValue(self):
# This is the internal function that is called when
# self['value'] is directly assigned.
self.guiItem.setValue(self['value'])
def setValue(self, value):
# This is the public function that is meant to be called by a
# user that doesn't like to use (or doesn't understand) the
# preferred interface of self['value'].
self['value'] = value
def getValue(self):
return self.guiItem.getValue()
def getRatio(self):
return self.guiItem.getRatio()
def setScrollSize(self):
self.guiItem.setScrollSize(self['scrollSize'])
def setPageSize(self):
self.guiItem.setPageSize(self['pageSize'])
def scrollStep(self, stepCount):
"""Scrolls the indicated number of steps forward. If
stepCount is negative, scrolls backward."""
self['value'] = self.guiItem.getValue() + self.guiItem.getScrollSize() * stepCount
def scrollPage(self, pageCount):
"""Scrolls the indicated number of pages forward. If
pageCount is negative, scrolls backward."""
self['value'] = self.guiItem.getValue() + self.guiItem.getPageSize() * pageCount
def setOrientation(self):
if self['orientation'] == DGG.HORIZONTAL:
self.guiItem.setAxis(Vec3(1, 0, 0))
elif self['orientation'] == DGG.VERTICAL:
self.guiItem.setAxis(Vec3(0, 0, -1))
elif self['orientation'] == DGG.VERTICAL_INVERTED:
self.guiItem.setAxis(Vec3(0, 0, 1))
else:
raise ValueError('Invalid value for orientation: %s' % (self['orientation']))
def setManageButtons(self):
self.guiItem.setManagePieces(self['manageButtons'])
def setResizeThumb(self):
self.guiItem.setResizeThumb(self['resizeThumb'])
def destroy(self):
self.thumb.destroy()
del self.thumb
self.incButton.destroy()
del self.incButton
self.decButton.destroy()
del self.decButton
DirectFrame.destroy(self)
def commandFunc(self):
# Store the updated value in self['value']
self._optionInfo['value'][DGG._OPT_VALUE] = self.guiItem.getValue()
if self['command']:
self['command'](*self['extraArgs'])
|
hellerve/hawkweed | refs/heads/master | hawkweed/functional/primitives.py | 1 | """A collection of functional primitives"""
from functools import wraps, partial
from functools import reduce as _reduce
from inspect import getargspec
def curry(fun):
"""
A working but dirty version of a currying function/decorator.
"""
def _internal_curry(fun, original=None, given=0):
if original is None:
original = fun
spec = getargspec(original)
opt = len(spec.defaults or [])
needed = len(spec.args) - given - opt
@wraps(fun)
def internal(*args, **kwargs):
"""The internal currying function"""
if len(args) >= needed:
return fun(*args, **kwargs)
else:
return _internal_curry(wraps(fun)(partial(fun, *args, **kwargs)),
original,
given=len(args))
return internal
return _internal_curry(fun)
@curry
def map(fun, values):
"""
A function that maps a function to a list of values and returns the new generator.
Complexity: O(n*k) where k is the complexity of the given function
params:
fun: the function that should be applied
values: the list of values we should map over
returns:
the new generator
"""
return (fun(value) for value in values)
@curry
def filter(fun, values):
"""
A function that filters a list of values by a predicate function and returns
a generator.
Complexity: O(n*k) where k is the complexity of the given function
params:
fun: the fucntion that should be applied
values: the list of values we should filter
returns:
the new generator
"""
return (value for value in values if fun(value))
@curry
def reduce(fun, init, values=None):
"""
A function that reduces a list to a single value using a given function.
Complexity: O(n*k) where k is the complexity of the given function
params:
fun: the function that should be applied
values: the list of values we should reduce
returns:
the reduced value
"""
if values is None:
return _reduce(fun, init)
else:
return _reduce(fun, values, init)
@curry
def apply(fun, args, kwargs=None):
"""
applies a list of arguments (and an optional dict of keyword arguments)
to a function.
Complexity: O(k) where k is the complexity of the given function
params:
fun: the function that should be applied
args: the list of values we should reduce
returns:
the reduced value
"""
if kwargs is None:
kwargs = {}
return fun(*args, **kwargs)
def pipe(*funs):
"""
composes a bunch of functions. They will be applied one after the other.
Complexity: depends on the given functions
params:
*funs: the functions that should be chained
returns: the chained function
"""
def internal(*args, **kwargs):
"""The internal piping function"""
return reduce(lambda acc, fun: fun(acc),
funs[0](*args, **kwargs),
funs[1:])
return internal
def compose(*funs):
"""
composes a bunch of functions. They will be applied in reverse order
(so this function is the reverse of pipe).
Complexity: depends on the given functions
params:
*funs: the functions that should be chained
returns: the chained function
"""
return apply(pipe, reversed(funs))
def starpipe(*funs):
"""
composes a bunch of functions. They will be applied one after the other.
The arguments will be passed as star args.
Complexity: depends on the given functions
params:
*funs: the functions that should be chained
returns: the chained function
"""
def internal(*args, **kwargs):
"""The internal piping function"""
return reduce(lambda acc, fun: fun(*acc),
funs[0](*args, **kwargs),
funs[1:])
return internal
def starcompose(*funs):
"""
composes a bunch of functions. They will be applied in reverse order
(so this function is the reverse of starpipe). Like in starpipe, arguments
will be passed as starargs.
Complexity: depends on the given functions
params:
*funs: the functions that should be chained
returns: the chained function
"""
return apply(starpipe, reversed(funs))
def identity(value):
"""
The identity function. Takes a value and returns it.
Complexity: O(1)
params:
value: the value
returns: the value
"""
return value
@curry
def tap(fun, value):
"""
A function that takes a function and a value, applies the function
to the value and returns the value.
Complexity: O(k) where k is the complexity of the given function
params:
fun: the function
value: the value
returns: the value
"""
fun(value)
return value
def constantly(value):
"""
A generator that returns the given value forever.
Complexity: O(1)
params:
value: the value to return
returns: an infinite generator of the value
"""
while True:
yield value
def delay(fun, *args, **kwargs):
"""
A function that takes a function and its arguments and delays its execution
until it is needed. It also caches the executed return value and prevents
it from being executed again (always returning the first result).
params:
fun: the function
args: the function's args
kwargs: the function's keyword arguments
returns: the function result
"""
# this is a horrible hack around Python 2.x's lack of nonlocal
_int = ["__delay__unset"]
@wraps(fun)
def internal():
"""The internal delay function"""
if _int[0] == "__delay__unset":
_int[0] = fun(*args, **kwargs)
return _int[0]
return internal
@curry
def flip(fun, first, second, *args):
"""
Takes a function and applies its arguments in reverse order.
params:
fun: the function
first: the first argument
second: the second argument
args: the remaining args (this weird first, second, args thing
is there to prevent preemptive passing of arguments)
returns: the result of the function fun
"""
return apply(fun, reversed(args + (first, second)))
|
yuvipanda/deltas | refs/heads/master | deltas/tokenizers/tests/test_text_split.py | 1 | from nose.tools import eq_
from ..text_split import text_split
def test_simple_text_split():
input = "As a sentence, this includes punctuation. \n" + \
"\n" + \
"And then we have another sentence here!"
expected = ['As', ' ', 'a', ' ', 'sentence', ',', ' ', 'this', ' ',
'includes', ' ', 'punctuation', '.', ' \n\n', 'And', ' ',
'then', ' ', 'we', ' ', 'have', ' ', 'another', ' ', 'sentence',
' ', 'here', '!']
tokens = list(text_split.tokenize(input))
eq_(tokens, expected)
|
grupoprog3/proyecto_final | refs/heads/master | proyecto/flask/Lib/site-packages/sqlalchemy/dialects/oracle/__init__.py | 55 | # oracle/__init__.py
# Copyright (C) 2005-2016 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
from sqlalchemy.dialects.oracle import base, cx_oracle, zxjdbc
base.dialect = cx_oracle.dialect
from sqlalchemy.dialects.oracle.base import \
VARCHAR, NVARCHAR, CHAR, DATE, NUMBER,\
BLOB, BFILE, CLOB, NCLOB, TIMESTAMP, RAW,\
FLOAT, DOUBLE_PRECISION, LONG, dialect, INTERVAL,\
VARCHAR2, NVARCHAR2, ROWID, dialect
__all__ = (
'VARCHAR', 'NVARCHAR', 'CHAR', 'DATE', 'NUMBER',
'BLOB', 'BFILE', 'CLOB', 'NCLOB', 'TIMESTAMP', 'RAW',
'FLOAT', 'DOUBLE_PRECISION', 'LONG', 'dialect', 'INTERVAL',
'VARCHAR2', 'NVARCHAR2', 'ROWID'
)
|
aslihandincer/ibis | refs/heads/master | ibis/impala/tests/test_pandas_interop.py | 6 | # Copyright 2015 Cloudera Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
import pandas as pd
import pytest
import ibis
import ibis.expr.datatypes as dt
import ibis.expr.types as ir
from ibis.compat import unittest
from ibis.common import IbisTypeError
from ibis.impala.client import pandas_to_ibis_schema
from ibis.impala.tests.common import ImpalaE2E
functional_alltypes_with_nulls = pd.DataFrame({
'bigint_col': np.int64([0, 10, 20, 30, 40, 50, 60, 70, 80, 90]),
'bool_col': np.bool_([True, False, True, False, True, None,
True, False, True, False]),
'date_string_col': ['11/01/10', None, '11/01/10', '11/01/10',
'11/01/10', '11/01/10', '11/01/10', '11/01/10',
'11/01/10', '11/01/10'],
'double_col': np.float64([0.0, 10.1, None, 30.299999999999997,
40.399999999999999, 50.5, 60.599999999999994,
70.700000000000003, 80.799999999999997,
90.899999999999991]),
'float_col': np.float32([None, 1.1000000238418579, 2.2000000476837158,
3.2999999523162842, 4.4000000953674316, 5.5,
6.5999999046325684, 7.6999998092651367,
8.8000001907348633,
9.8999996185302734]),
'int_col': np.int32([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
'month': [11, 11, 11, 11, 2, 11, 11, 11, 11, 11],
'smallint_col': np.int16([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
'string_col': ['0', '1', None, '3', '4', '5', '6', '7', '8', '9'],
'timestamp_col': [pd.Timestamp('2010-11-01 00:00:00'),
None,
pd.Timestamp('2010-11-01 00:02:00.100000'),
pd.Timestamp('2010-11-01 00:03:00.300000'),
pd.Timestamp('2010-11-01 00:04:00.600000'),
pd.Timestamp('2010-11-01 00:05:00.100000'),
pd.Timestamp('2010-11-01 00:06:00.150000'),
pd.Timestamp('2010-11-01 00:07:00.210000'),
pd.Timestamp('2010-11-01 00:08:00.280000'),
pd.Timestamp('2010-11-01 00:09:00.360000')],
'tinyint_col': np.int8([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
'year': [2010, 2010, 2010, 2010, 2010, 2010, 2010, 2010, 2010, 2010]})
class TestPandasTypeInterop(unittest.TestCase):
def test_series_to_ibis_literal(self):
values = [1, 2, 3, 4]
s = pd.Series(values)
expr = ir.as_value_expr(s)
expected = ir.sequence(list(s))
assert expr.equals(expected)
class TestPandasSchemaInference(unittest.TestCase):
def test_dtype_bool(self):
df = pd.DataFrame({'col': [True, False, False]})
inferred = pandas_to_ibis_schema(df)
expected = ibis.schema([('col', 'boolean')])
assert inferred == expected
def test_dtype_int8(self):
df = pd.DataFrame({'col': np.int8([-3, 9, 17])})
inferred = pandas_to_ibis_schema(df)
expected = ibis.schema([('col', 'int8')])
assert inferred == expected
def test_dtype_int16(self):
df = pd.DataFrame({'col': np.int16([-5, 0, 12])})
inferred = pandas_to_ibis_schema(df)
expected = ibis.schema([('col', 'int16')])
assert inferred == expected
def test_dtype_int32(self):
df = pd.DataFrame({'col': np.int32([-12, 3, 25000])})
inferred = pandas_to_ibis_schema(df)
expected = ibis.schema([('col', 'int32')])
assert inferred == expected
def test_dtype_int64(self):
df = pd.DataFrame({'col': np.int64([102, 67228734, -0])})
inferred = pandas_to_ibis_schema(df)
expected = ibis.schema([('col', 'int64')])
assert inferred == expected
def test_dtype_float32(self):
df = pd.DataFrame({'col': np.float32([45e-3, -0.4, 99.])})
inferred = pandas_to_ibis_schema(df)
expected = ibis.schema([('col', 'float')])
assert inferred == expected
def test_dtype_float64(self):
df = pd.DataFrame({'col': np.float64([-3e43, 43., 10000000.])})
inferred = pandas_to_ibis_schema(df)
expected = ibis.schema([('col', 'double')])
assert inferred == expected
def test_dtype_uint8(self):
df = pd.DataFrame({'col': np.uint8([3, 0, 16])})
inferred = pandas_to_ibis_schema(df)
expected = ibis.schema([('col', 'int16')])
assert inferred == expected
def test_dtype_uint16(self):
df = pd.DataFrame({'col': np.uint16([5569, 1, 33])})
inferred = pandas_to_ibis_schema(df)
expected = ibis.schema([('col', 'int32')])
assert inferred == expected
def test_dtype_uint32(self):
df = pd.DataFrame({'col': np.uint32([100, 0, 6])})
inferred = pandas_to_ibis_schema(df)
expected = ibis.schema([('col', 'int64')])
assert inferred == expected
def test_dtype_uint64(self):
df = pd.DataFrame({'col': np.uint64([666, 2, 3])})
with self.assertRaises(IbisTypeError):
inferred = pandas_to_ibis_schema(df) # noqa
def test_dtype_datetime64(self):
df = pd.DataFrame({
'col': [pd.Timestamp('2010-11-01 00:01:00'),
pd.Timestamp('2010-11-01 00:02:00.1000'),
pd.Timestamp('2010-11-01 00:03:00.300000')]})
inferred = pandas_to_ibis_schema(df)
expected = ibis.schema([('col', 'timestamp')])
assert inferred == expected
def test_dtype_timedelta64(self):
df = pd.DataFrame({
'col': [pd.Timedelta('1 days'),
pd.Timedelta('-1 days 2 min 3us'),
pd.Timedelta('-2 days +23:57:59.999997')]})
inferred = pandas_to_ibis_schema(df)
expected = ibis.schema([('col', 'int64')])
assert inferred == expected
def test_dtype_string(self):
df = pd.DataFrame({'col': ['foo', 'bar', 'hello']})
inferred = pandas_to_ibis_schema(df)
expected = ibis.schema([('col', 'string')])
assert inferred == expected
def test_dtype_categorical(self):
df = pd.DataFrame({'col': ['a', 'b', 'c', 'a']}, dtype='category')
inferred = pandas_to_ibis_schema(df)
expected = ibis.schema([('col', dt.Category(3))])
assert inferred == expected
class TestPandasRoundTrip(ImpalaE2E, unittest.TestCase):
def test_round_trip(self):
pytest.skip('fails')
df1 = self.alltypes.execute()
df2 = self.con.pandas(df1, 'bamboo', database=self.tmp_db).execute()
assert (df1.columns == df2.columns).all()
assert (df1.dtypes == df2.dtypes).all()
assert (df1 == df2).all().all()
def test_round_trip_non_int_missing_data(self):
pytest.skip('WM: hangs -- will investigate later')
df1 = functional_alltypes_with_nulls
table = self.con.pandas(df1, 'fawn', database=self.tmp_db)
df2 = table.execute()
assert (df1.columns == df2.columns).all()
assert (df1.dtypes == df2.dtypes).all()
# bool/int cols should be exact
assert (df1.bool_col == df2.bool_col).all()
assert (df1.tinyint_col == df2.tinyint_col).all()
assert (df1.smallint_col == df2.smallint_col).all()
assert (df1.int_col == df2.int_col).all()
assert (df1.bigint_col == df2.bigint_col).all()
assert (df1.month == df2.month).all()
assert (df1.year == df2.year).all()
# string cols should be equal everywhere except for the NULLs
assert ((df1.string_col == df2.string_col) ==
[1, 1, 0, 1, 1, 1, 1, 1, 1, 1]).all()
assert ((df1.date_string_col == df2.date_string_col) ==
[1, 0, 1, 1, 1, 1, 1, 1, 1, 1]).all()
# float cols within tolerance, and NULLs should be False
assert ((df1.double_col - df2.double_col < 1e-9) ==
[1, 1, 0, 1, 1, 1, 1, 1, 1, 1]).all()
assert ((df1.float_col - df2.float_col < 1e-9) ==
[0, 1, 1, 1, 1, 1, 1, 1, 1, 1]).all()
def test_round_trip_missing_type_promotion(self):
pytest.skip('unfinished')
# prepare Impala table with missing ints
# TODO: switch to self.con.raw_sql once #412 is fixed
create_query = ('CREATE TABLE {0}.missing_ints '
' (tinyint_col TINYINT, bigint_col BIGINT) '
'STORED AS PARQUET'.format(self.tmp_db))
insert_query = ('INSERT INTO {0}.missing_ints '
'VALUES (NULL, 3), (-5, NULL), (19, 444444)'.format(
self.tmp_db))
self.con.con.cursor.execute(create_query)
self.con.con.cursor.execute(insert_query)
table = self.con.table('missing_ints', database=self.tmp_db)
df = table.execute() # noqa # REMOVE LATER
# WHAT NOW?
|
rokam/plugin.video.netflixbmc | refs/heads/master | resources/lib/pkg_resources/__init__.py | 8 | # This is a stub provided for ndg __init__.py
def declare_namespace(_):
pass
def resource_filename(a, b):
raise NotImplementedError |
jagguli/intellij-community | refs/heads/master | python/helpers/pydev/interpreterInfo.py | 45 | '''
This module was created to get information available in the interpreter, such as libraries,
paths, etc.
what is what:
sys.builtin_module_names: contains the builtin modules embeeded in python (rigth now, we specify all manually).
sys.prefix: A string giving the site-specific directory prefix where the platform independent Python files are installed
format is something as
EXECUTABLE:python.exe|libs@compiled_dlls$builtin_mods
all internal are separated by |
'''
import sys
try:
import os.path
def fullyNormalizePath(path):
'''fixes the path so that the format of the path really reflects the directories in the system
'''
return os.path.normpath(path)
join = os.path.join
except: # ImportError or AttributeError.
# See: http://stackoverflow.com/questions/10254353/error-while-installing-jython-for-pydev
def fullyNormalizePath(path):
'''fixes the path so that the format of the path really reflects the directories in the system
'''
return path
def join(a, b):
if a.endswith('/') or a.endswith('\\'):
return a + b
return a + '/' + b
IS_PYTHON_3K = 0
try:
if sys.version_info[0] == 3:
IS_PYTHON_3K = 1
except:
# That's OK, not all versions of python have sys.version_info
pass
try:
# Just check if False and True are defined (depends on version, not whether it's jython/python)
False
True
except:
exec ('True, False = 1,0') # An exec is used so that python 3k does not give a syntax error
if sys.platform == "cygwin":
try:
import ctypes # use from the system if available
except ImportError:
sys.path.append(join(sys.path[0], 'third_party/wrapped_for_pydev'))
import ctypes
def nativePath(path):
MAX_PATH = 512 # On cygwin NT, its 260 lately, but just need BIG ENOUGH buffer
'''Get the native form of the path, like c:\\Foo for /cygdrive/c/Foo'''
retval = ctypes.create_string_buffer(MAX_PATH)
path = fullyNormalizePath(path)
CCP_POSIX_TO_WIN_A = 0
ctypes.cdll.cygwin1.cygwin_conv_path(CCP_POSIX_TO_WIN_A, path, retval, MAX_PATH)
return retval.value
else:
def nativePath(path):
return fullyNormalizePath(path)
def __getfilesystemencoding():
'''
Note: there's a copy of this method in _pydev_filesystem_encoding.py
'''
try:
ret = sys.getfilesystemencoding()
if not ret:
raise RuntimeError('Unable to get encoding.')
return ret
except:
try:
# Handle Jython
from java.lang import System
env = System.getProperty("os.name").lower()
if env.find('win') != -1:
return 'ISO-8859-1' # mbcs does not work on Jython, so, use a (hopefully) suitable replacement
return 'utf-8'
except:
pass
# Only available from 2.3 onwards.
if sys.platform == 'win32':
return 'mbcs'
return 'utf-8'
def getfilesystemencoding():
try:
ret = __getfilesystemencoding()
#Check if the encoding is actually there to be used!
if hasattr('', 'encode'):
''.encode(ret)
if hasattr('', 'decode'):
''.decode(ret)
return ret
except:
return 'utf-8'
file_system_encoding = getfilesystemencoding()
def tounicode(s):
if hasattr(s, 'decode'):
# Depending on the platform variant we may have decode on string or not.
return s.decode(file_system_encoding)
return s
def toutf8(s):
if hasattr(s, 'encode'):
return s.encode('utf-8')
return s
def toasciimxl(s):
# output for xml without a declared encoding
# As the output is xml, we have to encode chars (< and > are ok as they're not accepted in the filesystem name --
# if it was allowed, we'd have to do things more selectively so that < and > don't get wrongly replaced).
s = s.replace("&", "&")
try:
ret = s.encode('ascii', 'xmlcharrefreplace')
except:
# use workaround
ret = ''
for c in s:
try:
ret += c.encode('ascii')
except:
try:
# Python 2: unicode is a valid identifier
ret += unicode("&#%d;") % ord(c)
except:
# Python 3: a string is already unicode, so, just doing it directly should work.
ret += "&#%d;" % ord(c)
return ret
if __name__ == '__main__':
try:
# just give some time to get the reading threads attached (just in case)
import time
time.sleep(0.1)
except:
pass
try:
executable = nativePath(sys.executable)
except:
executable = sys.executable
if sys.platform == "cygwin" and not executable.endswith('.exe'):
executable += '.exe'
try:
major = str(sys.version_info[0])
minor = str(sys.version_info[1])
except AttributeError:
# older versions of python don't have version_info
import string
s = string.split(sys.version, ' ')[0]
s = string.split(s, '.')
major = s[0]
minor = s[1]
s = tounicode('%s.%s') % (tounicode(major), tounicode(minor))
contents = [tounicode('<xml>')]
contents.append(tounicode('<version>%s</version>') % (tounicode(s),))
contents.append(tounicode('<executable>%s</executable>') % tounicode(executable))
# this is the new implementation to get the system folders
# (still need to check if it works in linux)
# (previously, we were getting the executable dir, but that is not always correct...)
prefix = tounicode(nativePath(sys.prefix))
# print_ 'prefix is', prefix
result = []
path_used = sys.path
try:
path_used = path_used[1:] # Use a copy (and don't include the directory of this script as a path.)
except:
pass # just ignore it...
for p in path_used:
p = tounicode(nativePath(p))
try:
import string # to be compatible with older versions
if string.find(p, prefix) == 0: # was startswith
result.append((p, True))
else:
result.append((p, False))
except (ImportError, AttributeError):
# python 3k also does not have it
# jython may not have it (depending on how are things configured)
if p.startswith(prefix): # was startswith
result.append((p, True))
else:
result.append((p, False))
for p, b in result:
if b:
contents.append(tounicode('<lib path="ins">%s</lib>') % (p,))
else:
contents.append(tounicode('<lib path="out">%s</lib>') % (p,))
# no compiled libs
# nor forced libs
for builtinMod in sys.builtin_module_names:
contents.append(tounicode('<forced_lib>%s</forced_lib>') % tounicode(builtinMod))
contents.append(tounicode('</xml>'))
unic = tounicode('\n').join(contents)
inasciixml = toasciimxl(unic)
if IS_PYTHON_3K:
# This is the 'official' way of writing binary output in Py3K (see: http://bugs.python.org/issue4571)
sys.stdout.buffer.write(inasciixml)
else:
sys.stdout.write(inasciixml)
try:
sys.stdout.flush()
sys.stderr.flush()
# and give some time to let it read things (just in case)
import time
time.sleep(0.1)
except:
pass
raise RuntimeError('Ok, this is so that it shows the output (ugly hack for some platforms, so that it releases the output).')
|
smcgrath/empathy-smcgrath | refs/heads/master | tools/glib-ginterface-gen.py | 9 | #!/usr/bin/python
# glib-ginterface-gen.py: service-side interface generator
#
# Generate dbus-glib 0.x service GInterfaces from the Telepathy specification.
# The master copy of this program is in the telepathy-glib repository -
# please make any changes there.
#
# Copyright (C) 2006, 2007 Collabora Limited
#
# 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
import sys
import os.path
import xml.dom.minidom
from libglibcodegen import Signature, type_to_gtype, cmp_by_name, \
camelcase_to_lower, NS_TP, dbus_gutils_wincaps_to_uscore, \
signal_to_marshal_name, method_to_glue_marshal_name
NS_TP = "http://telepathy.freedesktop.org/wiki/DbusSpec#extensions-v0"
class Generator(object):
def __init__(self, dom, prefix, basename, signal_marshal_prefix,
headers, end_headers, not_implemented_func,
allow_havoc):
self.dom = dom
self.__header = []
self.__body = []
assert prefix.endswith('_')
assert not signal_marshal_prefix.endswith('_')
# The main_prefix, sub_prefix thing is to get:
# FOO_ -> (FOO_, _)
# FOO_SVC_ -> (FOO_, _SVC_)
# but
# FOO_BAR/ -> (FOO_BAR_, _)
# FOO_BAR/SVC_ -> (FOO_BAR_, _SVC_)
if '/' in prefix:
main_prefix, sub_prefix = prefix.upper().split('/', 1)
prefix = prefix.replace('/', '_')
else:
main_prefix, sub_prefix = prefix.upper().split('_', 1)
self.MAIN_PREFIX_ = main_prefix + '_'
self._SUB_PREFIX_ = '_' + sub_prefix
self.Prefix_ = prefix
self.Prefix = prefix.replace('_', '')
self.prefix_ = prefix.lower()
self.PREFIX_ = prefix.upper()
self.signal_marshal_prefix = signal_marshal_prefix
self.headers = headers
self.end_headers = end_headers
self.not_implemented_func = not_implemented_func
self.allow_havoc = allow_havoc
def h(self, s):
self.__header.append(s)
def b(self, s):
self.__body.append(s)
def do_node(self, node):
node_name = node.getAttribute('name').replace('/', '')
node_name_mixed = self.node_name_mixed = node_name.replace('_', '')
node_name_lc = self.node_name_lc = node_name.lower()
node_name_uc = self.node_name_uc = node_name.upper()
interfaces = node.getElementsByTagName('interface')
assert len(interfaces) == 1, interfaces
interface = interfaces[0]
self.iface_name = interface.getAttribute('name')
tmp = interface.getAttribute('tp:implement-service')
if tmp == "no":
return
tmp = interface.getAttribute('tp:causes-havoc')
if tmp and not self.allow_havoc:
raise AssertionError('%s is %s' % (self.iface_name, tmp))
self.b('static const DBusGObjectInfo _%s%s_object_info;'
% (self.prefix_, node_name_lc))
self.b('')
methods = interface.getElementsByTagName('method')
signals = interface.getElementsByTagName('signal')
properties = interface.getElementsByTagName('property')
# Don't put properties in dbus-glib glue
glue_properties = []
self.b('struct _%s%sClass {' % (self.Prefix, node_name_mixed))
self.b(' GTypeInterface parent_class;')
for method in methods:
self.b(' %s %s;' % self.get_method_impl_names(method))
self.b('};')
self.b('')
if signals:
self.b('enum {')
for signal in signals:
self.b(' %s,' % self.get_signal_const_entry(signal))
self.b(' N_%s_SIGNALS' % node_name_uc)
self.b('};')
self.b('static guint %s_signals[N_%s_SIGNALS] = {0};'
% (node_name_lc, node_name_uc))
self.b('')
self.b('static void %s%s_base_init (gpointer klass);'
% (self.prefix_, node_name_lc))
self.b('')
self.b('GType')
self.b('%s%s_get_type (void)'
% (self.prefix_, node_name_lc))
self.b('{')
self.b(' static GType type = 0;')
self.b('')
self.b(' if (G_UNLIKELY (type == 0))')
self.b(' {')
self.b(' static const GTypeInfo info = {')
self.b(' sizeof (%s%sClass),' % (self.Prefix, node_name_mixed))
self.b(' %s%s_base_init, /* base_init */'
% (self.prefix_, node_name_lc))
self.b(' NULL, /* base_finalize */')
self.b(' NULL, /* class_init */')
self.b(' NULL, /* class_finalize */')
self.b(' NULL, /* class_data */')
self.b(' 0,')
self.b(' 0, /* n_preallocs */')
self.b(' NULL /* instance_init */')
self.b(' };')
self.b('')
self.b(' type = g_type_register_static (G_TYPE_INTERFACE,')
self.b(' "%s%s", &info, 0);' % (self.Prefix, node_name_mixed))
self.b(' }')
self.b('')
self.b(' return type;')
self.b('}')
self.b('')
self.h('/**')
self.h(' * %s%s:' % (self.Prefix, node_name_mixed))
self.h(' *')
self.h(' * Dummy typedef representing any implementation of this '
'interface.')
self.h(' */')
self.h('typedef struct _%s%s %s%s;'
% (self.Prefix, node_name_mixed, self.Prefix, node_name_mixed))
self.h('')
self.h('/**')
self.h(' * %s%sClass:' % (self.Prefix, node_name_mixed))
self.h(' *')
self.h(' * The class of %s%s.' % (self.Prefix, node_name_mixed))
self.h(' */')
self.h('typedef struct _%s%sClass %s%sClass;'
% (self.Prefix, node_name_mixed, self.Prefix, node_name_mixed))
self.h('')
self.h('GType %s%s_get_type (void);'
% (self.prefix_, node_name_lc))
gtype = self.current_gtype = \
self.MAIN_PREFIX_ + 'TYPE' + self._SUB_PREFIX_ + node_name_uc
classname = self.Prefix + node_name_mixed
self.h('#define %s \\\n (%s%s_get_type ())'
% (gtype, self.prefix_, node_name_lc))
self.h('#define %s%s(obj) \\\n'
' (G_TYPE_CHECK_INSTANCE_CAST((obj), %s, %s))'
% (self.PREFIX_, node_name_uc, gtype, classname))
self.h('#define %sIS%s%s(obj) \\\n'
' (G_TYPE_CHECK_INSTANCE_TYPE((obj), %s))'
% (self.MAIN_PREFIX_, self._SUB_PREFIX_, node_name_uc, gtype))
self.h('#define %s%s_GET_CLASS(obj) \\\n'
' (G_TYPE_INSTANCE_GET_INTERFACE((obj), %s, %sClass))'
% (self.PREFIX_, node_name_uc, gtype, classname))
self.h('')
self.h('')
base_init_code = []
for method in methods:
self.do_method(method)
for signal in signals:
base_init_code.extend(self.do_signal(signal))
self.b('static inline void')
self.b('%s%s_base_init_once (gpointer klass G_GNUC_UNUSED)'
% (self.prefix_, node_name_lc))
self.b('{')
self.b(' static TpDBusPropertiesMixinPropInfo properties[%d] = {'
% (len(properties) + 1))
for m in properties:
access = m.getAttribute('access')
assert access in ('read', 'write', 'readwrite')
if access == 'read':
flags = 'TP_DBUS_PROPERTIES_MIXIN_FLAG_READ'
elif access == 'write':
flags = 'TP_DBUS_PROPERTIES_MIXIN_FLAG_WRITE'
else:
flags = ('TP_DBUS_PROPERTIES_MIXIN_FLAG_READ | '
'TP_DBUS_PROPERTIES_MIXIN_FLAG_WRITE')
self.b(' { 0, %s, "%s", 0, NULL, NULL }, /* %s */'
% (flags, m.getAttribute('type'), m.getAttribute('name')))
self.b(' { 0, 0, NULL, 0, NULL, NULL }')
self.b(' };')
self.b(' static TpDBusPropertiesMixinIfaceInfo interface =')
self.b(' { 0, properties, NULL, NULL };')
self.b('')
self.b(' interface.dbus_interface = g_quark_from_static_string '
'("%s");' % self.iface_name)
for i, m in enumerate(properties):
self.b(' properties[%d].name = g_quark_from_static_string ("%s");'
% (i, m.getAttribute('name')))
self.b(' properties[%d].type = %s;'
% (i, type_to_gtype(m.getAttribute('type'))[1]))
self.b(' tp_svc_interface_set_dbus_properties_info (%s, &interface);'
% self.current_gtype)
self.b('')
for s in base_init_code:
self.b(s)
self.b(' dbus_g_object_type_install_info (%s%s_get_type (),'
% (self.prefix_, node_name_lc))
self.b(' &_%s%s_object_info);'
% (self.prefix_, node_name_lc))
self.b('}')
self.b('static void')
self.b('%s%s_base_init (gpointer klass)'
% (self.prefix_, node_name_lc))
self.b('{')
self.b(' static gboolean initialized = FALSE;')
self.b('')
self.b(' if (!initialized)')
self.b(' {')
self.b(' initialized = TRUE;')
self.b(' %s%s_base_init_once (klass);'
% (self.prefix_, node_name_lc))
self.b(' }')
# insert anything we need to do per implementation here
self.b('}')
self.h('')
self.b('static const DBusGMethodInfo _%s%s_methods[] = {'
% (self.prefix_, node_name_lc))
method_blob, offsets = self.get_method_glue(methods)
for method, offset in zip(methods, offsets):
self.do_method_glue(method, offset)
self.b('};')
self.b('')
self.b('static const DBusGObjectInfo _%s%s_object_info = {'
% (self.prefix_, node_name_lc))
self.b(' 0,') # version
self.b(' _%s%s_methods,' % (self.prefix_, node_name_lc))
self.b(' %d,' % len(methods))
self.b('"' + method_blob.replace('\0', '\\0') + '",')
self.b('"' + self.get_signal_glue(signals).replace('\0', '\\0') + '",')
self.b('"' +
self.get_property_glue(glue_properties).replace('\0', '\\0') +
'",')
self.b('};')
self.b('')
self.node_name_mixed = None
self.node_name_lc = None
self.node_name_uc = None
def get_method_glue(self, methods):
info = []
offsets = []
for method in methods:
offsets.append(len(''.join(info)))
info.append(self.iface_name + '\0')
info.append(method.getAttribute('name') + '\0')
info.append('A\0') # async
counter = 0
for arg in method.getElementsByTagName('arg'):
out = arg.getAttribute('direction') == 'out'
name = arg.getAttribute('name')
if not name:
assert out
name = 'arg%u' % counter
counter += 1
info.append(name + '\0')
if out:
info.append('O\0')
else:
info.append('I\0')
if out:
info.append('F\0') # not const
info.append('N\0') # not error or return
info.append(arg.getAttribute('type') + '\0')
info.append('\0')
return ''.join(info) + '\0', offsets
def do_method_glue(self, method, offset):
lc_name = camelcase_to_lower(method.getAttribute('name'))
marshaller = method_to_glue_marshal_name(method,
self.signal_marshal_prefix)
wrapper = self.prefix_ + self.node_name_lc + '_' + lc_name
self.b(" { (GCallback) %s, %s, %d }," % (wrapper, marshaller, offset))
def get_signal_glue(self, signals):
info = []
for signal in signals:
info.append(self.iface_name)
info.append(signal.getAttribute('name'))
return '\0'.join(info) + '\0\0'
# the implementation can be the same
get_property_glue = get_signal_glue
def get_method_impl_names(self, method):
dbus_method_name = method.getAttribute('name')
class_member_name = camelcase_to_lower(dbus_method_name)
stub_name = (self.prefix_ + self.node_name_lc + '_' +
class_member_name)
return (stub_name + '_impl', class_member_name)
def do_method(self, method):
assert self.node_name_mixed is not None
in_class = []
# Examples refer to Thing.DoStuff (su) -> ii
# DoStuff
dbus_method_name = method.getAttribute('name')
# do_stuff
class_member_name = camelcase_to_lower(dbus_method_name)
# void tp_svc_thing_do_stuff (TpSvcThing *, const char *, guint,
# DBusGMethodInvocation *);
stub_name = (self.prefix_ + self.node_name_lc + '_' +
class_member_name)
# typedef void (*tp_svc_thing_do_stuff_impl) (TpSvcThing *,
# const char *, guint, DBusGMethodInvocation);
impl_name = stub_name + '_impl'
# void tp_svc_thing_return_from_do_stuff (DBusGMethodInvocation *,
# gint, gint);
ret_name = (self.prefix_ + self.node_name_lc + '_return_from_' +
class_member_name)
# Gather arguments
in_args = []
out_args = []
for i in method.getElementsByTagName('arg'):
name = i.getAttribute('name')
direction = i.getAttribute('direction') or 'in'
dtype = i.getAttribute('type')
assert direction in ('in', 'out')
if name:
name = direction + '_' + name
elif direction == 'in':
name = direction + str(len(in_args))
else:
name = direction + str(len(out_args))
ctype, gtype, marshaller, pointer = type_to_gtype(dtype)
if pointer:
ctype = 'const ' + ctype
struct = (ctype, name)
if direction == 'in':
in_args.append(struct)
else:
out_args.append(struct)
# Implementation type declaration (in header, docs in body)
self.b('/**')
self.b(' * %s:' % impl_name)
self.b(' * @self: The object implementing this interface')
for (ctype, name) in in_args:
self.b(' * @%s: %s (FIXME, generate documentation)'
% (name, ctype))
self.b(' * @context: Used to return values or throw an error')
self.b(' *')
self.b(' * The signature of an implementation of the D-Bus method')
self.b(' * %s on interface %s.' % (dbus_method_name, self.iface_name))
self.b(' */')
self.h('typedef void (*%s) (%s%s *self,'
% (impl_name, self.Prefix, self.node_name_mixed))
for (ctype, name) in in_args:
self.h(' %s%s,' % (ctype, name))
self.h(' DBusGMethodInvocation *context);')
# Class member (in class definition)
in_class.append(' %s %s;' % (impl_name, class_member_name))
# Stub definition (in body only - it's static)
self.b('static void')
self.b('%s (%s%s *self,'
% (stub_name, self.Prefix, self.node_name_mixed))
for (ctype, name) in in_args:
self.b(' %s%s,' % (ctype, name))
self.b(' DBusGMethodInvocation *context)')
self.b('{')
self.b(' %s impl = (%s%s_GET_CLASS (self)->%s);'
% (impl_name, self.PREFIX_, self.node_name_uc, class_member_name))
self.b('')
self.b(' if (impl != NULL)')
tmp = ['self'] + [name for (ctype, name) in in_args] + ['context']
self.b(' {')
self.b(' (impl) (%s);' % ',\n '.join(tmp))
self.b(' }')
self.b(' else')
self.b(' {')
if self.not_implemented_func:
self.b(' %s (context);' % self.not_implemented_func)
else:
self.b(' GError e = { DBUS_GERROR, ')
self.b(' DBUS_GERROR_UNKNOWN_METHOD,')
self.b(' "Method not implemented" };')
self.b('')
self.b(' dbus_g_method_return_error (context, &e);')
self.b(' }')
self.b('}')
self.b('')
# Implementation registration (in both header and body)
self.h('void %s%s_implement_%s (%s%sClass *klass, %s impl);'
% (self.prefix_, self.node_name_lc, class_member_name,
self.Prefix, self.node_name_mixed, impl_name))
self.b('/**')
self.b(' * %s%s_implement_%s:'
% (self.prefix_, self.node_name_lc, class_member_name))
self.b(' * @klass: A class whose instances implement this interface')
self.b(' * @impl: A callback used to implement the %s D-Bus method'
% dbus_method_name)
self.b(' *')
self.b(' * Register an implementation for the %s method in the vtable'
% dbus_method_name)
self.b(' * of an implementation of this interface. To be called from')
self.b(' * the interface init function.')
self.b(' */')
self.b('void')
self.b('%s%s_implement_%s (%s%sClass *klass, %s impl)'
% (self.prefix_, self.node_name_lc, class_member_name,
self.Prefix, self.node_name_mixed, impl_name))
self.b('{')
self.b(' klass->%s = impl;' % class_member_name)
self.b('}')
self.b('')
# Return convenience function (static inline, in header)
self.h('/**')
self.h(' * %s:' % ret_name)
self.h(' * @context: The D-Bus method invocation context')
for (ctype, name) in out_args:
self.h(' * @%s: %s (FIXME, generate documentation)'
% (name, ctype))
self.h(' *')
self.h(' * Return successfully by calling dbus_g_method_return().')
self.h(' * This inline function exists only to provide type-safety.')
self.h(' */')
tmp = (['DBusGMethodInvocation *context'] +
[ctype + name for (ctype, name) in out_args])
self.h('static inline')
self.h('/* this comment is to stop gtkdoc realising this is static */')
self.h(('void %s (' % ret_name) + (',\n '.join(tmp)) + ');')
self.h('static inline void')
self.h(('%s (' % ret_name) + (',\n '.join(tmp)) + ')')
self.h('{')
tmp = ['context'] + [name for (ctype, name) in out_args]
self.h(' dbus_g_method_return (' + ',\n '.join(tmp) + ');')
self.h('}')
self.h('')
return in_class
def get_signal_const_entry(self, signal):
assert self.node_name_uc is not None
return ('SIGNAL_%s_%s'
% (self.node_name_uc, signal.getAttribute('name')))
def do_signal(self, signal):
assert self.node_name_mixed is not None
in_base_init = []
# for signal: Thing::StuffHappened (s, u)
# we want to emit:
# void tp_svc_thing_emit_stuff_happened (gpointer instance,
# const char *arg0, guint arg1);
dbus_name = signal.getAttribute('name')
stub_name = (self.prefix_ + self.node_name_lc + '_emit_' +
camelcase_to_lower(dbus_name))
const_name = self.get_signal_const_entry(signal)
# Gather arguments
args = []
for i in signal.getElementsByTagName('arg'):
name = i.getAttribute('name')
dtype = i.getAttribute('type')
tp_type = i.getAttribute('tp:type')
if name:
name = 'arg_' + name
else:
name = 'arg' + str(len(args))
ctype, gtype, marshaller, pointer = type_to_gtype(dtype)
if pointer:
ctype = 'const ' + ctype
struct = (ctype, name, gtype)
args.append(struct)
tmp = (['gpointer instance'] +
[ctype + name for (ctype, name, gtype) in args])
self.h(('void %s (' % stub_name) + (',\n '.join(tmp)) + ');')
# FIXME: emit docs
self.b('/**')
self.b(' * %s:' % stub_name)
self.b(' * @instance: The object implementing this interface')
for (ctype, name, gtype) in args:
self.b(' * @%s: %s (FIXME, generate documentation)'
% (name, ctype))
self.b(' *')
self.b(' * Type-safe wrapper around g_signal_emit to emit the')
self.b(' * %s signal on interface %s.'
% (dbus_name, self.iface_name))
self.b(' */')
self.b('void')
self.b(('%s (' % stub_name) + (',\n '.join(tmp)) + ')')
self.b('{')
self.b(' g_assert (instance != NULL);')
self.b(' g_assert (G_TYPE_CHECK_INSTANCE_TYPE (instance, %s));'
% (self.current_gtype))
tmp = (['instance', '%s_signals[%s]' % (self.node_name_lc, const_name),
'0'] + [name for (ctype, name, gtype) in args])
self.b(' g_signal_emit (' + ',\n '.join(tmp) + ');')
self.b('}')
self.b('')
signal_name = dbus_gutils_wincaps_to_uscore(dbus_name).replace('_',
'-')
in_base_init.append(' /**')
in_base_init.append(' * %s%s::%s:'
% (self.Prefix, self.node_name_mixed, signal_name))
for (ctype, name, gtype) in args:
in_base_init.append(' * @%s: %s (FIXME, generate documentation)'
% (name, ctype))
in_base_init.append(' *')
in_base_init.append(' * The %s D-Bus signal is emitted whenever '
'this GObject signal is.' % dbus_name)
in_base_init.append(' */')
in_base_init.append(' %s_signals[%s] ='
% (self.node_name_lc, const_name))
in_base_init.append(' g_signal_new ("%s",' % signal_name)
in_base_init.append(' G_OBJECT_CLASS_TYPE (klass),')
in_base_init.append(' G_SIGNAL_RUN_LAST|G_SIGNAL_DETAILED,')
in_base_init.append(' 0,')
in_base_init.append(' NULL, NULL,')
in_base_init.append(' %s,'
% signal_to_marshal_name(signal, self.signal_marshal_prefix))
in_base_init.append(' G_TYPE_NONE,')
tmp = ['%d' % len(args)] + [gtype for (ctype, name, gtype) in args]
in_base_init.append(' %s);' % ',\n '.join(tmp))
in_base_init.append('')
return in_base_init
def __call__(self):
self.h('#include <glib-object.h>')
self.h('#include <dbus/dbus-glib.h>')
self.h('#include <telepathy-glib/dbus-properties-mixin.h>')
self.h('')
self.h('G_BEGIN_DECLS')
self.h('')
self.b('#include "%s.h"' % basename)
self.b('')
for header in self.headers:
self.b('#include %s' % header)
self.b('')
nodes = self.dom.getElementsByTagName('node')
nodes.sort(cmp_by_name)
for node in nodes:
self.do_node(node)
self.h('')
self.h('G_END_DECLS')
self.b('')
for header in self.end_headers:
self.b('#include %s' % header)
self.h('')
self.b('')
open(basename + '.h', 'w').write('\n'.join(self.__header))
open(basename + '.c', 'w').write('\n'.join(self.__body))
def cmdline_error():
print """\
usage:
gen-ginterface [OPTIONS] xmlfile Prefix_
options:
--include='<header.h>' (may be repeated)
--include='"header.h"' (ditto)
--include-end='"header.h"' (ditto)
Include extra headers in the generated .c file
--signal-marshal-prefix='prefix'
Use the given prefix on generated signal marshallers (default is
prefix.lower()).
--filename='BASENAME'
Set the basename for the output files (default is prefix.lower()
+ 'ginterfaces')
--not-implemented-func='symbol'
Set action when methods not implemented in the interface vtable are
called. symbol must have signature
void symbol (DBusGMethodInvocation *context)
and return some sort of "not implemented" error via
dbus_g_method_return_error (context, ...)
"""
sys.exit(1)
if __name__ == '__main__':
from getopt import gnu_getopt
options, argv = gnu_getopt(sys.argv[1:], '',
['filename=', 'signal-marshal-prefix=',
'include=', 'include-end=',
'allow-unstable',
'not-implemented-func='])
try:
prefix = argv[1]
except IndexError:
cmdline_error()
basename = prefix.lower() + 'ginterfaces'
signal_marshal_prefix = prefix.lower().rstrip('_')
headers = []
end_headers = []
not_implemented_func = ''
allow_havoc = False
for option, value in options:
if option == '--filename':
basename = value
elif option == '--signal-marshal-prefix':
signal_marshal_prefix = value
elif option == '--include':
if value[0] not in '<"':
value = '"%s"' % value
headers.append(value)
elif option == '--include-end':
if value[0] not in '<"':
value = '"%s"' % value
end_headers.append(value)
elif option == '--not-implemented-func':
not_implemented_func = value
elif option == '--allow-unstable':
allow_havoc = True
try:
dom = xml.dom.minidom.parse(argv[0])
except IndexError:
cmdline_error()
Generator(dom, prefix, basename, signal_marshal_prefix, headers,
end_headers, not_implemented_func, allow_havoc)()
|
Creworker/FreeCAD | refs/heads/master | src/Mod/Test/InitGui.py | 9 | # Test gui init module
# (c) 2003 Juergen Riegel
#
#***************************************************************************
#* (c) Juergen Riegel ([email protected]) 2002 *
#* *
#* This file is part of the FreeCAD CAx development system. *
#* *
#* This program is free software; you can redistribute it and/or modify *
#* it under the terms of the GNU Lesser General Public License (LGPL) *
#* as published by the Free Software Foundation; either version 2 of *
#* the License, or (at your option) any later version. *
#* for detail see the LICENCE text file. *
#* *
#* FreeCAD 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 Library General Public *
#* License along with FreeCAD; if not, write to the Free Software *
#* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
#* USA *
#* *
#* Juergen Riegel 2002 *
#***************************************************************************/
class TestWorkbench ( Workbench ):
"Test workbench object"
Icon = """
/* XPM */
static const char *test_icon[]={
"16 16 2 1",
"a c #000000",
". c None",
"................",
"................",
"..############..",
"..############..",
"..############..",
"......####......",
"......####......",
"......####......",
"......####......",
"......####......",
"......####......",
"......####......",
"......####......",
"......####......",
"................",
"................"};
"""
MenuText = "Test framework"
ToolTip = "Test framework"
def Initialize(self):
import TestGui
list = ["Test_Test","Test_TestAll","Test_TestDoc","Test_TestBase"]
self.appendToolbar("TestTools",list)
menu = ["Test &Commands","TestToolsGui"]
list = ["Std_TestQM","Std_TestReloadQM","Test_Test","Test_TestAll","Test_TestDoc","Test_TestBase"]
self.appendCommandbar("TestToolsGui",list)
self.appendMenu(menu,list)
menu = ["Test &Commands","TestToolsText"]
list = ["Test_TestAllText","Test_TestDocText","Test_TestBaseText"]
self.appendCommandbar("TestToolsText",list)
self.appendMenu(menu,list)
menu = ["Test &Commands","TestToolsMenu"]
list = ["Test_TestCreateMenu", "Test_TestDeleteMenu", "Test_TestWork"]
self.appendCommandbar("TestToolsMenu",list)
self.appendMenu(menu,list)
menu = ["Test &Commands","TestFeatureMenu"]
list = ["Test_InsertFeature"]
self.appendCommandbar("TestFeature",list)
self.appendMenu(menu,list)
menu = ["Test &Commands","Progress bar"]
list = ["Std_TestProgress1", "Std_TestProgress2", "Std_TestProgress3", "Std_TestProgress4", "Std_TestProgress5"]
self.appendMenu(menu,list)
menu = ["Test &Commands","MDI"]
list = ["Std_MDITest1", "Std_MDITest2", "Std_MDITest3"]
self.appendMenu(menu,list)
list = ["Std_ViewExample1", "Std_ViewExample2", "Std_ViewExample3"]
self.appendMenu("Inventor View",list)
Gui.addWorkbench(TestWorkbench())
|
wakatime/sublime-wakatime | refs/heads/master | packages/wakatime/packages/py27/pygments/lexers/int_fiction.py | 4 | # -*- coding: utf-8 -*-
"""
pygments.lexers.int_fiction
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Lexers for interactive fiction languages.
:copyright: Copyright 2006-2019 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
from pygments.lexer import RegexLexer, include, bygroups, using, \
this, default, words
from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
Number, Punctuation, Error, Generic
__all__ = ['Inform6Lexer', 'Inform6TemplateLexer', 'Inform7Lexer',
'Tads3Lexer']
class Inform6Lexer(RegexLexer):
"""
For `Inform 6 <http://inform-fiction.org/>`_ source code.
.. versionadded:: 2.0
"""
name = 'Inform 6'
aliases = ['inform6', 'i6']
filenames = ['*.inf']
flags = re.MULTILINE | re.DOTALL | re.UNICODE
_name = r'[a-zA-Z_]\w*'
# Inform 7 maps these four character classes to their ASCII
# equivalents. To support Inform 6 inclusions within Inform 7,
# Inform6Lexer maps them too.
_dash = u'\\-\u2010-\u2014'
_dquote = u'"\u201c\u201d'
_squote = u"'\u2018\u2019"
_newline = u'\\n\u0085\u2028\u2029'
tokens = {
'root': [
(r'\A(!%%[^%s]*[%s])+' % (_newline, _newline), Comment.Preproc,
'directive'),
default('directive')
],
'_whitespace': [
(r'\s+', Text),
(r'![^%s]*' % _newline, Comment.Single)
],
'default': [
include('_whitespace'),
(r'\[', Punctuation, 'many-values'), # Array initialization
(r':|(?=;)', Punctuation, '#pop'),
(r'<', Punctuation), # Second angle bracket in an action statement
default(('expression', '_expression'))
],
# Expressions
'_expression': [
include('_whitespace'),
(r'(?=sp\b)', Text, '#pop'),
(r'(?=[%s%s$0-9#a-zA-Z_])' % (_dquote, _squote), Text,
('#pop', 'value')),
(r'\+\+|[%s]{1,2}(?!>)|~~?' % _dash, Operator),
(r'(?=[()\[%s,?@{:;])' % _dash, Text, '#pop')
],
'expression': [
include('_whitespace'),
(r'\(', Punctuation, ('expression', '_expression')),
(r'\)', Punctuation, '#pop'),
(r'\[', Punctuation, ('#pop', 'statements', 'locals')),
(r'>(?=(\s+|(![^%s]*))*[>;])' % _newline, Punctuation),
(r'\+\+|[%s]{2}(?!>)' % _dash, Operator),
(r',', Punctuation, '_expression'),
(r'&&?|\|\|?|[=~><]?=|[%s]{1,2}>?|\.\.?[&#]?|::|[<>+*/%%]' % _dash,
Operator, '_expression'),
(r'(has|hasnt|in|notin|ofclass|or|provides)\b', Operator.Word,
'_expression'),
(r'sp\b', Name),
(r'\?~?', Name.Label, 'label?'),
(r'[@{]', Error),
default('#pop')
],
'_assembly-expression': [
(r'\(', Punctuation, ('#push', '_expression')),
(r'[\[\]]', Punctuation),
(r'[%s]>' % _dash, Punctuation, '_expression'),
(r'sp\b', Keyword.Pseudo),
(r';', Punctuation, '#pop:3'),
include('expression')
],
'_for-expression': [
(r'\)', Punctuation, '#pop:2'),
(r':', Punctuation, '#pop'),
include('expression')
],
'_keyword-expression': [
(r'(from|near|to)\b', Keyword, '_expression'),
include('expression')
],
'_list-expression': [
(r',', Punctuation, '#pop'),
include('expression')
],
'_object-expression': [
(r'has\b', Keyword.Declaration, '#pop'),
include('_list-expression')
],
# Values
'value': [
include('_whitespace'),
# Strings
(r'[%s][^@][%s]' % (_squote, _squote), String.Char, '#pop'),
(r'([%s])(@\{[0-9a-fA-F]{1,4}\})([%s])' % (_squote, _squote),
bygroups(String.Char, String.Escape, String.Char), '#pop'),
(r'([%s])(@.{2})([%s])' % (_squote, _squote),
bygroups(String.Char, String.Escape, String.Char), '#pop'),
(r'[%s]' % _squote, String.Single, ('#pop', 'dictionary-word')),
(r'[%s]' % _dquote, String.Double, ('#pop', 'string')),
# Numbers
(r'\$[+%s][0-9]*\.?[0-9]*([eE][+%s]?[0-9]+)?' % (_dash, _dash),
Number.Float, '#pop'),
(r'\$[0-9a-fA-F]+', Number.Hex, '#pop'),
(r'\$\$[01]+', Number.Bin, '#pop'),
(r'[0-9]+', Number.Integer, '#pop'),
# Values prefixed by hashes
(r'(##|#a\$)(%s)' % _name, bygroups(Operator, Name), '#pop'),
(r'(#g\$)(%s)' % _name,
bygroups(Operator, Name.Variable.Global), '#pop'),
(r'#[nw]\$', Operator, ('#pop', 'obsolete-dictionary-word')),
(r'(#r\$)(%s)' % _name, bygroups(Operator, Name.Function), '#pop'),
(r'#', Name.Builtin, ('#pop', 'system-constant')),
# System functions
(words((
'child', 'children', 'elder', 'eldest', 'glk', 'indirect', 'metaclass',
'parent', 'random', 'sibling', 'younger', 'youngest'), suffix=r'\b'),
Name.Builtin, '#pop'),
# Metaclasses
(r'(?i)(Class|Object|Routine|String)\b', Name.Builtin, '#pop'),
# Veneer routines
(words((
'Box__Routine', 'CA__Pr', 'CDefArt', 'CInDefArt', 'Cl__Ms',
'Copy__Primitive', 'CP__Tab', 'DA__Pr', 'DB__Pr', 'DefArt', 'Dynam__String',
'EnglishNumber', 'Glk__Wrap', 'IA__Pr', 'IB__Pr', 'InDefArt', 'Main__',
'Meta__class', 'OB__Move', 'OB__Remove', 'OC__Cl', 'OP__Pr', 'Print__Addr',
'Print__PName', 'PrintShortName', 'RA__Pr', 'RA__Sc', 'RL__Pr', 'R_Process',
'RT__ChG', 'RT__ChGt', 'RT__ChLDB', 'RT__ChLDW', 'RT__ChPR', 'RT__ChPrintA',
'RT__ChPrintC', 'RT__ChPrintO', 'RT__ChPrintS', 'RT__ChPS', 'RT__ChR',
'RT__ChSTB', 'RT__ChSTW', 'RT__ChT', 'RT__Err', 'RT__TrPS', 'RV__Pr',
'Symb__Tab', 'Unsigned__Compare', 'WV__Pr', 'Z__Region'),
prefix='(?i)', suffix=r'\b'),
Name.Builtin, '#pop'),
# Other built-in symbols
(words((
'call', 'copy', 'create', 'DEBUG', 'destroy', 'DICT_CHAR_SIZE',
'DICT_ENTRY_BYTES', 'DICT_IS_UNICODE', 'DICT_WORD_SIZE', 'false',
'FLOAT_INFINITY', 'FLOAT_NAN', 'FLOAT_NINFINITY', 'GOBJFIELD_CHAIN',
'GOBJFIELD_CHILD', 'GOBJFIELD_NAME', 'GOBJFIELD_PARENT',
'GOBJFIELD_PROPTAB', 'GOBJFIELD_SIBLING', 'GOBJ_EXT_START',
'GOBJ_TOTAL_LENGTH', 'Grammar__Version', 'INDIV_PROP_START', 'INFIX',
'infix__watching', 'MODULE_MODE', 'name', 'nothing', 'NUM_ATTR_BYTES', 'print',
'print_to_array', 'recreate', 'remaining', 'self', 'sender', 'STRICT_MODE',
'sw__var', 'sys__glob0', 'sys__glob1', 'sys__glob2', 'sys_statusline_flag',
'TARGET_GLULX', 'TARGET_ZCODE', 'temp__global2', 'temp__global3',
'temp__global4', 'temp_global', 'true', 'USE_MODULES', 'WORDSIZE'),
prefix='(?i)', suffix=r'\b'),
Name.Builtin, '#pop'),
# Other values
(_name, Name, '#pop')
],
# Strings
'dictionary-word': [
(r'[~^]+', String.Escape),
(r'[^~^\\@({%s]+' % _squote, String.Single),
(r'[({]', String.Single),
(r'@\{[0-9a-fA-F]{,4}\}', String.Escape),
(r'@.{2}', String.Escape),
(r'[%s]' % _squote, String.Single, '#pop')
],
'string': [
(r'[~^]+', String.Escape),
(r'[^~^\\@({%s]+' % _dquote, String.Double),
(r'[({]', String.Double),
(r'\\', String.Escape),
(r'@(\\\s*[%s]\s*)*@((\\\s*[%s]\s*)*[0-9])*' %
(_newline, _newline), String.Escape),
(r'@(\\\s*[%s]\s*)*\{((\\\s*[%s]\s*)*[0-9a-fA-F]){,4}'
r'(\\\s*[%s]\s*)*\}' % (_newline, _newline, _newline),
String.Escape),
(r'@(\\\s*[%s]\s*)*.(\\\s*[%s]\s*)*.' % (_newline, _newline),
String.Escape),
(r'[%s]' % _dquote, String.Double, '#pop')
],
'plain-string': [
(r'[^~^\\({\[\]%s]+' % _dquote, String.Double),
(r'[~^({\[\]]', String.Double),
(r'\\', String.Escape),
(r'[%s]' % _dquote, String.Double, '#pop')
],
# Names
'_constant': [
include('_whitespace'),
(_name, Name.Constant, '#pop'),
include('value')
],
'_global': [
include('_whitespace'),
(_name, Name.Variable.Global, '#pop'),
include('value')
],
'label?': [
include('_whitespace'),
(_name, Name.Label, '#pop'),
default('#pop')
],
'variable?': [
include('_whitespace'),
(_name, Name.Variable, '#pop'),
default('#pop')
],
# Values after hashes
'obsolete-dictionary-word': [
(r'\S\w*', String.Other, '#pop')
],
'system-constant': [
include('_whitespace'),
(_name, Name.Builtin, '#pop')
],
# Directives
'directive': [
include('_whitespace'),
(r'#', Punctuation),
(r';', Punctuation, '#pop'),
(r'\[', Punctuation,
('default', 'statements', 'locals', 'routine-name?')),
(words((
'abbreviate', 'endif', 'dictionary', 'ifdef', 'iffalse', 'ifndef', 'ifnot',
'iftrue', 'ifv3', 'ifv5', 'release', 'serial', 'switches', 'system_file',
'version'), prefix='(?i)', suffix=r'\b'),
Keyword, 'default'),
(r'(?i)(array|global)\b', Keyword,
('default', 'directive-keyword?', '_global')),
(r'(?i)attribute\b', Keyword, ('default', 'alias?', '_constant')),
(r'(?i)class\b', Keyword,
('object-body', 'duplicates', 'class-name')),
(r'(?i)(constant|default)\b', Keyword,
('default', 'expression', '_constant')),
(r'(?i)(end\b)(.*)', bygroups(Keyword, Text)),
(r'(?i)(extend|verb)\b', Keyword, 'grammar'),
(r'(?i)fake_action\b', Keyword, ('default', '_constant')),
(r'(?i)import\b', Keyword, 'manifest'),
(r'(?i)(include|link)\b', Keyword,
('default', 'before-plain-string')),
(r'(?i)(lowstring|undef)\b', Keyword, ('default', '_constant')),
(r'(?i)message\b', Keyword, ('default', 'diagnostic')),
(r'(?i)(nearby|object)\b', Keyword,
('object-body', '_object-head')),
(r'(?i)property\b', Keyword,
('default', 'alias?', '_constant', 'property-keyword*')),
(r'(?i)replace\b', Keyword,
('default', 'routine-name?', 'routine-name?')),
(r'(?i)statusline\b', Keyword, ('default', 'directive-keyword?')),
(r'(?i)stub\b', Keyword, ('default', 'routine-name?')),
(r'(?i)trace\b', Keyword,
('default', 'trace-keyword?', 'trace-keyword?')),
(r'(?i)zcharacter\b', Keyword,
('default', 'directive-keyword?', 'directive-keyword?')),
(_name, Name.Class, ('object-body', '_object-head'))
],
# [, Replace, Stub
'routine-name?': [
include('_whitespace'),
(_name, Name.Function, '#pop'),
default('#pop')
],
'locals': [
include('_whitespace'),
(r';', Punctuation, '#pop'),
(r'\*', Punctuation),
(r'"', String.Double, 'plain-string'),
(_name, Name.Variable)
],
# Array
'many-values': [
include('_whitespace'),
(r';', Punctuation),
(r'\]', Punctuation, '#pop'),
(r':', Error),
default(('expression', '_expression'))
],
# Attribute, Property
'alias?': [
include('_whitespace'),
(r'alias\b', Keyword, ('#pop', '_constant')),
default('#pop')
],
# Class, Object, Nearby
'class-name': [
include('_whitespace'),
(r'(?=[,;]|(class|has|private|with)\b)', Text, '#pop'),
(_name, Name.Class, '#pop')
],
'duplicates': [
include('_whitespace'),
(r'\(', Punctuation, ('#pop', 'expression', '_expression')),
default('#pop')
],
'_object-head': [
(r'[%s]>' % _dash, Punctuation),
(r'(class|has|private|with)\b', Keyword.Declaration, '#pop'),
include('_global')
],
'object-body': [
include('_whitespace'),
(r';', Punctuation, '#pop:2'),
(r',', Punctuation),
(r'class\b', Keyword.Declaration, 'class-segment'),
(r'(has|private|with)\b', Keyword.Declaration),
(r':', Error),
default(('_object-expression', '_expression'))
],
'class-segment': [
include('_whitespace'),
(r'(?=[,;]|(class|has|private|with)\b)', Text, '#pop'),
(_name, Name.Class),
default('value')
],
# Extend, Verb
'grammar': [
include('_whitespace'),
(r'=', Punctuation, ('#pop', 'default')),
(r'\*', Punctuation, ('#pop', 'grammar-line')),
default('_directive-keyword')
],
'grammar-line': [
include('_whitespace'),
(r';', Punctuation, '#pop'),
(r'[/*]', Punctuation),
(r'[%s]>' % _dash, Punctuation, 'value'),
(r'(noun|scope)\b', Keyword, '=routine'),
default('_directive-keyword')
],
'=routine': [
include('_whitespace'),
(r'=', Punctuation, 'routine-name?'),
default('#pop')
],
# Import
'manifest': [
include('_whitespace'),
(r';', Punctuation, '#pop'),
(r',', Punctuation),
(r'(?i)global\b', Keyword, '_global'),
default('_global')
],
# Include, Link, Message
'diagnostic': [
include('_whitespace'),
(r'[%s]' % _dquote, String.Double, ('#pop', 'message-string')),
default(('#pop', 'before-plain-string', 'directive-keyword?'))
],
'before-plain-string': [
include('_whitespace'),
(r'[%s]' % _dquote, String.Double, ('#pop', 'plain-string'))
],
'message-string': [
(r'[~^]+', String.Escape),
include('plain-string')
],
# Keywords used in directives
'_directive-keyword!': [
include('_whitespace'),
(words((
'additive', 'alias', 'buffer', 'class', 'creature', 'data', 'error', 'fatalerror',
'first', 'has', 'held', 'initial', 'initstr', 'last', 'long', 'meta', 'multi',
'multiexcept', 'multiheld', 'multiinside', 'noun', 'number', 'only', 'private',
'replace', 'reverse', 'scope', 'score', 'special', 'string', 'table', 'terminating',
'time', 'topic', 'warning', 'with'), suffix=r'\b'),
Keyword, '#pop'),
(r'[%s]{1,2}>|[+=]' % _dash, Punctuation, '#pop')
],
'_directive-keyword': [
include('_directive-keyword!'),
include('value')
],
'directive-keyword?': [
include('_directive-keyword!'),
default('#pop')
],
'property-keyword*': [
include('_whitespace'),
(r'(additive|long)\b', Keyword),
default('#pop')
],
'trace-keyword?': [
include('_whitespace'),
(words((
'assembly', 'dictionary', 'expressions', 'lines', 'linker',
'objects', 'off', 'on', 'symbols', 'tokens', 'verbs'), suffix=r'\b'),
Keyword, '#pop'),
default('#pop')
],
# Statements
'statements': [
include('_whitespace'),
(r'\]', Punctuation, '#pop'),
(r'[;{}]', Punctuation),
(words((
'box', 'break', 'continue', 'default', 'give', 'inversion',
'new_line', 'quit', 'read', 'remove', 'return', 'rfalse', 'rtrue',
'spaces', 'string', 'until'), suffix=r'\b'),
Keyword, 'default'),
(r'(do|else)\b', Keyword),
(r'(font|style)\b', Keyword,
('default', 'miscellaneous-keyword?')),
(r'for\b', Keyword, ('for', '(?')),
(r'(if|switch|while)', Keyword,
('expression', '_expression', '(?')),
(r'(jump|save|restore)\b', Keyword, ('default', 'label?')),
(r'objectloop\b', Keyword,
('_keyword-expression', 'variable?', '(?')),
(r'print(_ret)?\b|(?=[%s])' % _dquote, Keyword, 'print-list'),
(r'\.', Name.Label, 'label?'),
(r'@', Keyword, 'opcode'),
(r'#(?![agrnw]\$|#)', Punctuation, 'directive'),
(r'<', Punctuation, 'default'),
(r'move\b', Keyword,
('default', '_keyword-expression', '_expression')),
default(('default', '_keyword-expression', '_expression'))
],
'miscellaneous-keyword?': [
include('_whitespace'),
(r'(bold|fixed|from|near|off|on|reverse|roman|to|underline)\b',
Keyword, '#pop'),
(r'(a|A|an|address|char|name|number|object|property|string|the|'
r'The)\b(?=(\s+|(![^%s]*))*\))' % _newline, Keyword.Pseudo,
'#pop'),
(r'%s(?=(\s+|(![^%s]*))*\))' % (_name, _newline), Name.Function,
'#pop'),
default('#pop')
],
'(?': [
include('_whitespace'),
(r'\(', Punctuation, '#pop'),
default('#pop')
],
'for': [
include('_whitespace'),
(r';', Punctuation, ('_for-expression', '_expression')),
default(('_for-expression', '_expression'))
],
'print-list': [
include('_whitespace'),
(r';', Punctuation, '#pop'),
(r':', Error),
default(('_list-expression', '_expression', '_list-expression', 'form'))
],
'form': [
include('_whitespace'),
(r'\(', Punctuation, ('#pop', 'miscellaneous-keyword?')),
default('#pop')
],
# Assembly
'opcode': [
include('_whitespace'),
(r'[%s]' % _dquote, String.Double, ('operands', 'plain-string')),
(_name, Keyword, 'operands')
],
'operands': [
(r':', Error),
default(('_assembly-expression', '_expression'))
]
}
def get_tokens_unprocessed(self, text):
# 'in' is either a keyword or an operator.
# If the token two tokens after 'in' is ')', 'in' is a keyword:
# objectloop(a in b)
# Otherwise, it is an operator:
# objectloop(a in b && true)
objectloop_queue = []
objectloop_token_count = -1
previous_token = None
for index, token, value in RegexLexer.get_tokens_unprocessed(self,
text):
if previous_token is Name.Variable and value == 'in':
objectloop_queue = [[index, token, value]]
objectloop_token_count = 2
elif objectloop_token_count > 0:
if token not in Comment and token not in Text:
objectloop_token_count -= 1
objectloop_queue.append((index, token, value))
else:
if objectloop_token_count == 0:
if objectloop_queue[-1][2] == ')':
objectloop_queue[0][1] = Keyword
while objectloop_queue:
yield objectloop_queue.pop(0)
objectloop_token_count = -1
yield index, token, value
if token not in Comment and token not in Text:
previous_token = token
while objectloop_queue:
yield objectloop_queue.pop(0)
class Inform7Lexer(RegexLexer):
"""
For `Inform 7 <http://inform7.com/>`_ source code.
.. versionadded:: 2.0
"""
name = 'Inform 7'
aliases = ['inform7', 'i7']
filenames = ['*.ni', '*.i7x']
flags = re.MULTILINE | re.DOTALL | re.UNICODE
_dash = Inform6Lexer._dash
_dquote = Inform6Lexer._dquote
_newline = Inform6Lexer._newline
_start = r'\A|(?<=[%s])' % _newline
# There are three variants of Inform 7, differing in how to
# interpret at signs and braces in I6T. In top-level inclusions, at
# signs in the first column are inweb syntax. In phrase definitions
# and use options, tokens in braces are treated as I7. Use options
# also interpret "{N}".
tokens = {}
token_variants = ['+i6t-not-inline', '+i6t-inline', '+i6t-use-option']
for level in token_variants:
tokens[level] = {
'+i6-root': list(Inform6Lexer.tokens['root']),
'+i6t-root': [ # For Inform6TemplateLexer
(r'[^%s]*' % Inform6Lexer._newline, Comment.Preproc,
('directive', '+p'))
],
'root': [
(r'(\|?\s)+', Text),
(r'\[', Comment.Multiline, '+comment'),
(r'[%s]' % _dquote, Generic.Heading,
('+main', '+titling', '+titling-string')),
default(('+main', '+heading?'))
],
'+titling-string': [
(r'[^%s]+' % _dquote, Generic.Heading),
(r'[%s]' % _dquote, Generic.Heading, '#pop')
],
'+titling': [
(r'\[', Comment.Multiline, '+comment'),
(r'[^%s.;:|%s]+' % (_dquote, _newline), Generic.Heading),
(r'[%s]' % _dquote, Generic.Heading, '+titling-string'),
(r'[%s]{2}|(?<=[\s%s])\|[\s%s]' % (_newline, _dquote, _dquote),
Text, ('#pop', '+heading?')),
(r'[.;:]|(?<=[\s%s])\|' % _dquote, Text, '#pop'),
(r'[|%s]' % _newline, Generic.Heading)
],
'+main': [
(r'(?i)[^%s:a\[(|%s]+' % (_dquote, _newline), Text),
(r'[%s]' % _dquote, String.Double, '+text'),
(r':', Text, '+phrase-definition'),
(r'(?i)\bas\b', Text, '+use-option'),
(r'\[', Comment.Multiline, '+comment'),
(r'(\([%s])(.*?)([%s]\))' % (_dash, _dash),
bygroups(Punctuation,
using(this, state=('+i6-root', 'directive'),
i6t='+i6t-not-inline'), Punctuation)),
(r'(%s|(?<=[\s;:.%s]))\|\s|[%s]{2,}' %
(_start, _dquote, _newline), Text, '+heading?'),
(r'(?i)[a(|%s]' % _newline, Text)
],
'+phrase-definition': [
(r'\s+', Text),
(r'\[', Comment.Multiline, '+comment'),
(r'(\([%s])(.*?)([%s]\))' % (_dash, _dash),
bygroups(Punctuation,
using(this, state=('+i6-root', 'directive',
'default', 'statements'),
i6t='+i6t-inline'), Punctuation), '#pop'),
default('#pop')
],
'+use-option': [
(r'\s+', Text),
(r'\[', Comment.Multiline, '+comment'),
(r'(\([%s])(.*?)([%s]\))' % (_dash, _dash),
bygroups(Punctuation,
using(this, state=('+i6-root', 'directive'),
i6t='+i6t-use-option'), Punctuation), '#pop'),
default('#pop')
],
'+comment': [
(r'[^\[\]]+', Comment.Multiline),
(r'\[', Comment.Multiline, '#push'),
(r'\]', Comment.Multiline, '#pop')
],
'+text': [
(r'[^\[%s]+' % _dquote, String.Double),
(r'\[.*?\]', String.Interpol),
(r'[%s]' % _dquote, String.Double, '#pop')
],
'+heading?': [
(r'(\|?\s)+', Text),
(r'\[', Comment.Multiline, '+comment'),
(r'[%s]{4}\s+' % _dash, Text, '+documentation-heading'),
(r'[%s]{1,3}' % _dash, Text),
(r'(?i)(volume|book|part|chapter|section)\b[^%s]*' % _newline,
Generic.Heading, '#pop'),
default('#pop')
],
'+documentation-heading': [
(r'\s+', Text),
(r'\[', Comment.Multiline, '+comment'),
(r'(?i)documentation\s+', Text, '+documentation-heading2'),
default('#pop')
],
'+documentation-heading2': [
(r'\s+', Text),
(r'\[', Comment.Multiline, '+comment'),
(r'[%s]{4}\s' % _dash, Text, '+documentation'),
default('#pop:2')
],
'+documentation': [
(r'(?i)(%s)\s*(chapter|example)\s*:[^%s]*' %
(_start, _newline), Generic.Heading),
(r'(?i)(%s)\s*section\s*:[^%s]*' % (_start, _newline),
Generic.Subheading),
(r'((%s)\t.*?[%s])+' % (_start, _newline),
using(this, state='+main')),
(r'[^%s\[]+|[%s\[]' % (_newline, _newline), Text),
(r'\[', Comment.Multiline, '+comment'),
],
'+i6t-not-inline': [
(r'(%s)@c( .*?)?([%s]|\Z)' % (_start, _newline),
Comment.Preproc),
(r'(%s)@([%s]+|Purpose:)[^%s]*' % (_start, _dash, _newline),
Comment.Preproc),
(r'(%s)@p( .*?)?([%s]|\Z)' % (_start, _newline),
Generic.Heading, '+p')
],
'+i6t-use-option': [
include('+i6t-not-inline'),
(r'(\{)(N)(\})', bygroups(Punctuation, Text, Punctuation))
],
'+i6t-inline': [
(r'(\{)(\S[^}]*)?(\})',
bygroups(Punctuation, using(this, state='+main'),
Punctuation))
],
'+i6t': [
(r'(\{[%s])(![^}]*)(\}?)' % _dash,
bygroups(Punctuation, Comment.Single, Punctuation)),
(r'(\{[%s])(lines)(:)([^}]*)(\}?)' % _dash,
bygroups(Punctuation, Keyword, Punctuation, Text,
Punctuation), '+lines'),
(r'(\{[%s])([^:}]*)(:?)([^}]*)(\}?)' % _dash,
bygroups(Punctuation, Keyword, Punctuation, Text,
Punctuation)),
(r'(\(\+)(.*?)(\+\)|\Z)',
bygroups(Punctuation, using(this, state='+main'),
Punctuation))
],
'+p': [
(r'[^@]+', Comment.Preproc),
(r'(%s)@c( .*?)?([%s]|\Z)' % (_start, _newline),
Comment.Preproc, '#pop'),
(r'(%s)@([%s]|Purpose:)' % (_start, _dash), Comment.Preproc),
(r'(%s)@p( .*?)?([%s]|\Z)' % (_start, _newline),
Generic.Heading),
(r'@', Comment.Preproc)
],
'+lines': [
(r'(%s)@c( .*?)?([%s]|\Z)' % (_start, _newline),
Comment.Preproc),
(r'(%s)@([%s]|Purpose:)[^%s]*' % (_start, _dash, _newline),
Comment.Preproc),
(r'(%s)@p( .*?)?([%s]|\Z)' % (_start, _newline),
Generic.Heading, '+p'),
(r'(%s)@\w*[ %s]' % (_start, _newline), Keyword),
(r'![^%s]*' % _newline, Comment.Single),
(r'(\{)([%s]endlines)(\})' % _dash,
bygroups(Punctuation, Keyword, Punctuation), '#pop'),
(r'[^@!{]+?([%s]|\Z)|.' % _newline, Text)
]
}
# Inform 7 can include snippets of Inform 6 template language,
# so all of Inform6Lexer's states are copied here, with
# modifications to account for template syntax. Inform7Lexer's
# own states begin with '+' to avoid name conflicts. Some of
# Inform6Lexer's states begin with '_': these are not modified.
# They deal with template syntax either by including modified
# states, or by matching r'' then pushing to modified states.
for token in Inform6Lexer.tokens:
if token == 'root':
continue
tokens[level][token] = list(Inform6Lexer.tokens[token])
if not token.startswith('_'):
tokens[level][token][:0] = [include('+i6t'), include(level)]
def __init__(self, **options):
level = options.get('i6t', '+i6t-not-inline')
if level not in self._all_tokens:
self._tokens = self.__class__.process_tokendef(level)
else:
self._tokens = self._all_tokens[level]
RegexLexer.__init__(self, **options)
class Inform6TemplateLexer(Inform7Lexer):
"""
For `Inform 6 template
<http://inform7.com/sources/src/i6template/Woven/index.html>`_ code.
.. versionadded:: 2.0
"""
name = 'Inform 6 template'
aliases = ['i6t']
filenames = ['*.i6t']
def get_tokens_unprocessed(self, text, stack=('+i6t-root',)):
return Inform7Lexer.get_tokens_unprocessed(self, text, stack)
class Tads3Lexer(RegexLexer):
"""
For `TADS 3 <http://www.tads.org/>`_ source code.
"""
name = 'TADS 3'
aliases = ['tads3']
filenames = ['*.t']
flags = re.DOTALL | re.MULTILINE
_comment_single = r'(?://(?:[^\\\n]|\\+[\w\W])*$)'
_comment_multiline = r'(?:/\*(?:[^*]|\*(?!/))*\*/)'
_escape = (r'(?:\\(?:[\n\\<>"\'^v bnrt]|u[\da-fA-F]{,4}|x[\da-fA-F]{,2}|'
r'[0-3]?[0-7]{1,2}))')
_name = r'(?:[_a-zA-Z]\w*)'
_no_quote = r'(?=\s|\\?>)'
_operator = (r'(?:&&|\|\||\+\+|--|\?\?|::|[.,@\[\]~]|'
r'(?:[=+\-*/%!&|^]|<<?|>>?>?)=?)')
_ws = r'(?:\\|\s|%s|%s)' % (_comment_single, _comment_multiline)
_ws_pp = r'(?:\\\n|[^\S\n]|%s|%s)' % (_comment_single, _comment_multiline)
def _make_string_state(triple, double, verbatim=None, _escape=_escape):
if verbatim:
verbatim = ''.join(['(?:%s|%s)' % (re.escape(c.lower()),
re.escape(c.upper()))
for c in verbatim])
char = r'"' if double else r"'"
token = String.Double if double else String.Single
escaped_quotes = r'+|%s(?!%s{2})' % (char, char) if triple else r''
prefix = '%s%s' % ('t' if triple else '', 'd' if double else 's')
tag_state_name = '%sqt' % prefix
state = []
if triple:
state += [
(r'%s{3,}' % char, token, '#pop'),
(r'\\%s+' % char, String.Escape),
(char, token)
]
else:
state.append((char, token, '#pop'))
state += [
include('s/verbatim'),
(r'[^\\<&{}%s]+' % char, token)
]
if verbatim:
# This regex can't use `(?i)` because escape sequences are
# case-sensitive. `<\XMP>` works; `<\xmp>` doesn't.
state.append((r'\\?<(/|\\\\|(?!%s)\\)%s(?=[\s=>])' %
(_escape, verbatim),
Name.Tag, ('#pop', '%sqs' % prefix, tag_state_name)))
else:
state += [
(r'\\?<!([^><\\%s]|<(?!<)|\\%s%s|%s|\\.)*>?' %
(char, char, escaped_quotes, _escape), Comment.Multiline),
(r'(?i)\\?<listing(?=[\s=>]|\\>)', Name.Tag,
('#pop', '%sqs/listing' % prefix, tag_state_name)),
(r'(?i)\\?<xmp(?=[\s=>]|\\>)', Name.Tag,
('#pop', '%sqs/xmp' % prefix, tag_state_name)),
(r'\\?<([^\s=><\\%s]|<(?!<)|\\%s%s|%s|\\.)*' %
(char, char, escaped_quotes, _escape), Name.Tag,
tag_state_name),
include('s/entity')
]
state += [
include('s/escape'),
(r'\{([^}<\\%s]|<(?!<)|\\%s%s|%s|\\.)*\}' %
(char, char, escaped_quotes, _escape), String.Interpol),
(r'[\\&{}<]', token)
]
return state
def _make_tag_state(triple, double, _escape=_escape):
char = r'"' if double else r"'"
quantifier = r'{3,}' if triple else r''
state_name = '%s%sqt' % ('t' if triple else '', 'd' if double else 's')
token = String.Double if double else String.Single
escaped_quotes = r'+|%s(?!%s{2})' % (char, char) if triple else r''
return [
(r'%s%s' % (char, quantifier), token, '#pop:2'),
(r'(\s|\\\n)+', Text),
(r'(=)(\\?")', bygroups(Punctuation, String.Double),
'dqs/%s' % state_name),
(r"(=)(\\?')", bygroups(Punctuation, String.Single),
'sqs/%s' % state_name),
(r'=', Punctuation, 'uqs/%s' % state_name),
(r'\\?>', Name.Tag, '#pop'),
(r'\{([^}<\\%s]|<(?!<)|\\%s%s|%s|\\.)*\}' %
(char, char, escaped_quotes, _escape), String.Interpol),
(r'([^\s=><\\%s]|<(?!<)|\\%s%s|%s|\\.)+' %
(char, char, escaped_quotes, _escape), Name.Attribute),
include('s/escape'),
include('s/verbatim'),
include('s/entity'),
(r'[\\{}&]', Name.Attribute)
]
def _make_attribute_value_state(terminator, host_triple, host_double,
_escape=_escape):
token = (String.Double if terminator == r'"' else
String.Single if terminator == r"'" else String.Other)
host_char = r'"' if host_double else r"'"
host_quantifier = r'{3,}' if host_triple else r''
host_token = String.Double if host_double else String.Single
escaped_quotes = (r'+|%s(?!%s{2})' % (host_char, host_char)
if host_triple else r'')
return [
(r'%s%s' % (host_char, host_quantifier), host_token, '#pop:3'),
(r'%s%s' % (r'' if token is String.Other else r'\\?', terminator),
token, '#pop'),
include('s/verbatim'),
include('s/entity'),
(r'\{([^}<\\%s]|<(?!<)|\\%s%s|%s|\\.)*\}' %
(host_char, host_char, escaped_quotes, _escape), String.Interpol),
(r'([^\s"\'<%s{}\\&])+' % (r'>' if token is String.Other else r''),
token),
include('s/escape'),
(r'["\'\s&{<}\\]', token)
]
tokens = {
'root': [
(u'\ufeff', Text),
(r'\{', Punctuation, 'object-body'),
(r';+', Punctuation),
(r'(?=(argcount|break|case|catch|continue|default|definingobj|'
r'delegated|do|else|for|foreach|finally|goto|if|inherited|'
r'invokee|local|nil|new|operator|replaced|return|self|switch|'
r'targetobj|targetprop|throw|true|try|while)\b)', Text, 'block'),
(r'(%s)(%s*)(\()' % (_name, _ws),
bygroups(Name.Function, using(this, state='whitespace'),
Punctuation),
('block?/root', 'more/parameters', 'main/parameters')),
include('whitespace'),
(r'\++', Punctuation),
(r'[^\s!"%-(*->@-_a-z{-~]+', Error), # Averts an infinite loop
(r'(?!\Z)', Text, 'main/root')
],
'main/root': [
include('main/basic'),
default(('#pop', 'object-body/no-braces', 'classes', 'class'))
],
'object-body/no-braces': [
(r';', Punctuation, '#pop'),
(r'\{', Punctuation, ('#pop', 'object-body')),
include('object-body')
],
'object-body': [
(r';', Punctuation),
(r'\{', Punctuation, '#push'),
(r'\}', Punctuation, '#pop'),
(r':', Punctuation, ('classes', 'class')),
(r'(%s?)(%s*)(\()' % (_name, _ws),
bygroups(Name.Function, using(this, state='whitespace'),
Punctuation),
('block?', 'more/parameters', 'main/parameters')),
(r'(%s)(%s*)(\{)' % (_name, _ws),
bygroups(Name.Function, using(this, state='whitespace'),
Punctuation), 'block'),
(r'(%s)(%s*)(:)' % (_name, _ws),
bygroups(Name.Variable, using(this, state='whitespace'),
Punctuation),
('object-body/no-braces', 'classes', 'class')),
include('whitespace'),
(r'->|%s' % _operator, Punctuation, 'main'),
default('main/object-body')
],
'main/object-body': [
include('main/basic'),
(r'(%s)(%s*)(=?)' % (_name, _ws),
bygroups(Name.Variable, using(this, state='whitespace'),
Punctuation), ('#pop', 'more', 'main')),
default('#pop:2')
],
'block?/root': [
(r'\{', Punctuation, ('#pop', 'block')),
include('whitespace'),
(r'(?=[\[\'"<(:])', Text, # It might be a VerbRule macro.
('#pop', 'object-body/no-braces', 'grammar', 'grammar-rules')),
# It might be a macro like DefineAction.
default(('#pop', 'object-body/no-braces'))
],
'block?': [
(r'\{', Punctuation, ('#pop', 'block')),
include('whitespace'),
default('#pop')
],
'block/basic': [
(r'[;:]+', Punctuation),
(r'\{', Punctuation, '#push'),
(r'\}', Punctuation, '#pop'),
(r'default\b', Keyword.Reserved),
(r'(%s)(%s*)(:)' % (_name, _ws),
bygroups(Name.Label, using(this, state='whitespace'),
Punctuation)),
include('whitespace')
],
'block': [
include('block/basic'),
(r'(?!\Z)', Text, ('more', 'main'))
],
'block/embed': [
(r'>>', String.Interpol, '#pop'),
include('block/basic'),
(r'(?!\Z)', Text, ('more/embed', 'main'))
],
'main/basic': [
include('whitespace'),
(r'\(', Punctuation, ('#pop', 'more', 'main')),
(r'\[', Punctuation, ('#pop', 'more/list', 'main')),
(r'\{', Punctuation, ('#pop', 'more/inner', 'main/inner',
'more/parameters', 'main/parameters')),
(r'\*|\.{3}', Punctuation, '#pop'),
(r'(?i)0x[\da-f]+', Number.Hex, '#pop'),
(r'(\d+\.(?!\.)\d*|\.\d+)([eE][-+]?\d+)?|\d+[eE][-+]?\d+',
Number.Float, '#pop'),
(r'0[0-7]+', Number.Oct, '#pop'),
(r'\d+', Number.Integer, '#pop'),
(r'"""', String.Double, ('#pop', 'tdqs')),
(r"'''", String.Single, ('#pop', 'tsqs')),
(r'"', String.Double, ('#pop', 'dqs')),
(r"'", String.Single, ('#pop', 'sqs')),
(r'R"""', String.Regex, ('#pop', 'tdqr')),
(r"R'''", String.Regex, ('#pop', 'tsqr')),
(r'R"', String.Regex, ('#pop', 'dqr')),
(r"R'", String.Regex, ('#pop', 'sqr')),
# Two-token keywords
(r'(extern)(%s+)(object\b)' % _ws,
bygroups(Keyword.Reserved, using(this, state='whitespace'),
Keyword.Reserved)),
(r'(function|method)(%s*)(\()' % _ws,
bygroups(Keyword.Reserved, using(this, state='whitespace'),
Punctuation),
('#pop', 'block?', 'more/parameters', 'main/parameters')),
(r'(modify)(%s+)(grammar\b)' % _ws,
bygroups(Keyword.Reserved, using(this, state='whitespace'),
Keyword.Reserved),
('#pop', 'object-body/no-braces', ':', 'grammar')),
(r'(new)(%s+(?=(?:function|method)\b))' % _ws,
bygroups(Keyword.Reserved, using(this, state='whitespace'))),
(r'(object)(%s+)(template\b)' % _ws,
bygroups(Keyword.Reserved, using(this, state='whitespace'),
Keyword.Reserved), ('#pop', 'template')),
(r'(string)(%s+)(template\b)' % _ws,
bygroups(Keyword, using(this, state='whitespace'),
Keyword.Reserved), ('#pop', 'function-name')),
# Keywords
(r'(argcount|definingobj|invokee|replaced|targetobj|targetprop)\b',
Name.Builtin, '#pop'),
(r'(break|continue|goto)\b', Keyword.Reserved, ('#pop', 'label')),
(r'(case|extern|if|intrinsic|return|static|while)\b',
Keyword.Reserved),
(r'catch\b', Keyword.Reserved, ('#pop', 'catch')),
(r'class\b', Keyword.Reserved,
('#pop', 'object-body/no-braces', 'class')),
(r'(default|do|else|finally|try)\b', Keyword.Reserved, '#pop'),
(r'(dictionary|property)\b', Keyword.Reserved,
('#pop', 'constants')),
(r'enum\b', Keyword.Reserved, ('#pop', 'enum')),
(r'export\b', Keyword.Reserved, ('#pop', 'main')),
(r'(for|foreach)\b', Keyword.Reserved,
('#pop', 'more/inner', 'main/inner')),
(r'(function|method)\b', Keyword.Reserved,
('#pop', 'block?', 'function-name')),
(r'grammar\b', Keyword.Reserved,
('#pop', 'object-body/no-braces', 'grammar')),
(r'inherited\b', Keyword.Reserved, ('#pop', 'inherited')),
(r'local\b', Keyword.Reserved,
('#pop', 'more/local', 'main/local')),
(r'(modify|replace|switch|throw|transient)\b', Keyword.Reserved,
'#pop'),
(r'new\b', Keyword.Reserved, ('#pop', 'class')),
(r'(nil|true)\b', Keyword.Constant, '#pop'),
(r'object\b', Keyword.Reserved, ('#pop', 'object-body/no-braces')),
(r'operator\b', Keyword.Reserved, ('#pop', 'operator')),
(r'propertyset\b', Keyword.Reserved,
('#pop', 'propertyset', 'main')),
(r'self\b', Name.Builtin.Pseudo, '#pop'),
(r'template\b', Keyword.Reserved, ('#pop', 'template')),
# Operators
(r'(__objref|defined)(%s*)(\()' % _ws,
bygroups(Operator.Word, using(this, state='whitespace'),
Operator), ('#pop', 'more/__objref', 'main')),
(r'delegated\b', Operator.Word),
# Compiler-defined macros and built-in properties
(r'(__DATE__|__DEBUG|__LINE__|__FILE__|'
r'__TADS_MACRO_FORMAT_VERSION|__TADS_SYS_\w*|__TADS_SYSTEM_NAME|'
r'__TADS_VERSION_MAJOR|__TADS_VERSION_MINOR|__TADS3|__TIME__|'
r'construct|finalize|grammarInfo|grammarTag|lexicalParent|'
r'miscVocab|sourceTextGroup|sourceTextGroupName|'
r'sourceTextGroupOrder|sourceTextOrder)\b', Name.Builtin, '#pop')
],
'main': [
include('main/basic'),
(_name, Name, '#pop'),
default('#pop')
],
'more/basic': [
(r'\(', Punctuation, ('more/list', 'main')),
(r'\[', Punctuation, ('more', 'main')),
(r'\.{3}', Punctuation),
(r'->|\.\.', Punctuation, 'main'),
(r'(?=;)|[:)\]]', Punctuation, '#pop'),
include('whitespace'),
(_operator, Operator, 'main'),
(r'\?', Operator, ('main', 'more/conditional', 'main')),
(r'(is|not)(%s+)(in\b)' % _ws,
bygroups(Operator.Word, using(this, state='whitespace'),
Operator.Word)),
(r'[^\s!"%-_a-z{-~]+', Error) # Averts an infinite loop
],
'more': [
include('more/basic'),
default('#pop')
],
# Then expression (conditional operator)
'more/conditional': [
(r':(?!:)', Operator, '#pop'),
include('more')
],
# Embedded expressions
'more/embed': [
(r'>>', String.Interpol, '#pop:2'),
include('more')
],
# For/foreach loop initializer or short-form anonymous function
'main/inner': [
(r'\(', Punctuation, ('#pop', 'more/inner', 'main/inner')),
(r'local\b', Keyword.Reserved, ('#pop', 'main/local')),
include('main')
],
'more/inner': [
(r'\}', Punctuation, '#pop'),
(r',', Punctuation, 'main/inner'),
(r'(in|step)\b', Keyword, 'main/inner'),
include('more')
],
# Local
'main/local': [
(_name, Name.Variable, '#pop'),
include('whitespace')
],
'more/local': [
(r',', Punctuation, 'main/local'),
include('more')
],
# List
'more/list': [
(r'[,:]', Punctuation, 'main'),
include('more')
],
# Parameter list
'main/parameters': [
(r'(%s)(%s*)(?=:)' % (_name, _ws),
bygroups(Name.Variable, using(this, state='whitespace')), '#pop'),
(r'(%s)(%s+)(%s)' % (_name, _ws, _name),
bygroups(Name.Class, using(this, state='whitespace'),
Name.Variable), '#pop'),
(r'\[+', Punctuation),
include('main/basic'),
(_name, Name.Variable, '#pop'),
default('#pop')
],
'more/parameters': [
(r'(:)(%s*(?=[?=,:)]))' % _ws,
bygroups(Punctuation, using(this, state='whitespace'))),
(r'[?\]]+', Punctuation),
(r'[:)]', Punctuation, ('#pop', 'multimethod?')),
(r',', Punctuation, 'main/parameters'),
(r'=', Punctuation, ('more/parameter', 'main')),
include('more')
],
'more/parameter': [
(r'(?=[,)])', Text, '#pop'),
include('more')
],
'multimethod?': [
(r'multimethod\b', Keyword, '#pop'),
include('whitespace'),
default('#pop')
],
# Statements and expressions
'more/__objref': [
(r',', Punctuation, 'mode'),
(r'\)', Operator, '#pop'),
include('more')
],
'mode': [
(r'(error|warn)\b', Keyword, '#pop'),
include('whitespace')
],
'catch': [
(r'\(+', Punctuation),
(_name, Name.Exception, ('#pop', 'variables')),
include('whitespace')
],
'enum': [
include('whitespace'),
(r'token\b', Keyword, ('#pop', 'constants')),
default(('#pop', 'constants'))
],
'grammar': [
(r'\)+', Punctuation),
(r'\(', Punctuation, 'grammar-tag'),
(r':', Punctuation, 'grammar-rules'),
(_name, Name.Class),
include('whitespace')
],
'grammar-tag': [
include('whitespace'),
(r'"""([^\\"<]|""?(?!")|\\"+|\\.|<(?!<))+("{3,}|<<)|'
r'R"""([^\\"]|""?(?!")|\\"+|\\.)+"{3,}|'
r"'''([^\\'<]|''?(?!')|\\'+|\\.|<(?!<))+('{3,}|<<)|"
r"R'''([^\\']|''?(?!')|\\'+|\\.)+'{3,}|"
r'"([^\\"<]|\\.|<(?!<))+("|<<)|R"([^\\"]|\\.)+"|'
r"'([^\\'<]|\\.|<(?!<))+('|<<)|R'([^\\']|\\.)+'|"
r"([^)\s\\/]|/(?![/*]))+|\)", String.Other, '#pop')
],
'grammar-rules': [
include('string'),
include('whitespace'),
(r'(\[)(%s*)(badness)' % _ws,
bygroups(Punctuation, using(this, state='whitespace'), Keyword),
'main'),
(r'->|%s|[()]' % _operator, Punctuation),
(_name, Name.Constant),
default('#pop:2')
],
':': [
(r':', Punctuation, '#pop')
],
'function-name': [
(r'(<<([^>]|>>>|>(?!>))*>>)+', String.Interpol),
(r'(?=%s?%s*[({])' % (_name, _ws), Text, '#pop'),
(_name, Name.Function, '#pop'),
include('whitespace')
],
'inherited': [
(r'<', Punctuation, ('#pop', 'classes', 'class')),
include('whitespace'),
(_name, Name.Class, '#pop'),
default('#pop')
],
'operator': [
(r'negate\b', Operator.Word, '#pop'),
include('whitespace'),
(_operator, Operator),
default('#pop')
],
'propertyset': [
(r'\(', Punctuation, ('more/parameters', 'main/parameters')),
(r'\{', Punctuation, ('#pop', 'object-body')),
include('whitespace')
],
'template': [
(r'(?=;)', Text, '#pop'),
include('string'),
(r'inherited\b', Keyword.Reserved),
include('whitespace'),
(r'->|\?|%s' % _operator, Punctuation),
(_name, Name.Variable)
],
# Identifiers
'class': [
(r'\*|\.{3}', Punctuation, '#pop'),
(r'object\b', Keyword.Reserved, '#pop'),
(r'transient\b', Keyword.Reserved),
(_name, Name.Class, '#pop'),
include('whitespace'),
default('#pop')
],
'classes': [
(r'[:,]', Punctuation, 'class'),
include('whitespace'),
(r'>', Punctuation, '#pop'),
default('#pop')
],
'constants': [
(r',+', Punctuation),
(r';', Punctuation, '#pop'),
(r'property\b', Keyword.Reserved),
(_name, Name.Constant),
include('whitespace')
],
'label': [
(_name, Name.Label, '#pop'),
include('whitespace'),
default('#pop')
],
'variables': [
(r',+', Punctuation),
(r'\)', Punctuation, '#pop'),
include('whitespace'),
(_name, Name.Variable)
],
# Whitespace and comments
'whitespace': [
(r'^%s*#(%s|[^\n]|(?<=\\)\n)*\n?' % (_ws_pp, _comment_multiline),
Comment.Preproc),
(_comment_single, Comment.Single),
(_comment_multiline, Comment.Multiline),
(r'\\+\n+%s*#?|\n+|([^\S\n]|\\)+' % _ws_pp, Text)
],
# Strings
'string': [
(r'"""', String.Double, 'tdqs'),
(r"'''", String.Single, 'tsqs'),
(r'"', String.Double, 'dqs'),
(r"'", String.Single, 'sqs')
],
's/escape': [
(r'\{\{|\}\}|%s' % _escape, String.Escape)
],
's/verbatim': [
(r'<<\s*(as\s+decreasingly\s+likely\s+outcomes|cycling|else|end|'
r'first\s+time|one\s+of|only|or|otherwise|'
r'(sticky|(then\s+)?(purely\s+)?at)\s+random|stopping|'
r'(then\s+)?(half\s+)?shuffled|\|\|)\s*>>', String.Interpol),
(r'<<(%%(_(%s|\\?.)|[\-+ ,#]|\[\d*\]?)*\d*\.?\d*(%s|\\?.)|'
r'\s*((else|otherwise)\s+)?(if|unless)\b)?' % (_escape, _escape),
String.Interpol, ('block/embed', 'more/embed', 'main'))
],
's/entity': [
(r'(?i)&(#(x[\da-f]+|\d+)|[a-z][\da-z]*);?', Name.Entity)
],
'tdqs': _make_string_state(True, True),
'tsqs': _make_string_state(True, False),
'dqs': _make_string_state(False, True),
'sqs': _make_string_state(False, False),
'tdqs/listing': _make_string_state(True, True, 'listing'),
'tsqs/listing': _make_string_state(True, False, 'listing'),
'dqs/listing': _make_string_state(False, True, 'listing'),
'sqs/listing': _make_string_state(False, False, 'listing'),
'tdqs/xmp': _make_string_state(True, True, 'xmp'),
'tsqs/xmp': _make_string_state(True, False, 'xmp'),
'dqs/xmp': _make_string_state(False, True, 'xmp'),
'sqs/xmp': _make_string_state(False, False, 'xmp'),
# Tags
'tdqt': _make_tag_state(True, True),
'tsqt': _make_tag_state(True, False),
'dqt': _make_tag_state(False, True),
'sqt': _make_tag_state(False, False),
'dqs/tdqt': _make_attribute_value_state(r'"', True, True),
'dqs/tsqt': _make_attribute_value_state(r'"', True, False),
'dqs/dqt': _make_attribute_value_state(r'"', False, True),
'dqs/sqt': _make_attribute_value_state(r'"', False, False),
'sqs/tdqt': _make_attribute_value_state(r"'", True, True),
'sqs/tsqt': _make_attribute_value_state(r"'", True, False),
'sqs/dqt': _make_attribute_value_state(r"'", False, True),
'sqs/sqt': _make_attribute_value_state(r"'", False, False),
'uqs/tdqt': _make_attribute_value_state(_no_quote, True, True),
'uqs/tsqt': _make_attribute_value_state(_no_quote, True, False),
'uqs/dqt': _make_attribute_value_state(_no_quote, False, True),
'uqs/sqt': _make_attribute_value_state(_no_quote, False, False),
# Regular expressions
'tdqr': [
(r'[^\\"]+', String.Regex),
(r'\\"*', String.Regex),
(r'"{3,}', String.Regex, '#pop'),
(r'"', String.Regex)
],
'tsqr': [
(r"[^\\']+", String.Regex),
(r"\\'*", String.Regex),
(r"'{3,}", String.Regex, '#pop'),
(r"'", String.Regex)
],
'dqr': [
(r'[^\\"]+', String.Regex),
(r'\\"?', String.Regex),
(r'"', String.Regex, '#pop')
],
'sqr': [
(r"[^\\']+", String.Regex),
(r"\\'?", String.Regex),
(r"'", String.Regex, '#pop')
]
}
def get_tokens_unprocessed(self, text, **kwargs):
pp = r'^%s*#%s*' % (self._ws_pp, self._ws_pp)
if_false_level = 0
for index, token, value in (
RegexLexer.get_tokens_unprocessed(self, text, **kwargs)):
if if_false_level == 0: # Not in a false #if
if (token is Comment.Preproc and
re.match(r'%sif%s+(0|nil)%s*$\n?' %
(pp, self._ws_pp, self._ws_pp), value)):
if_false_level = 1
else: # In a false #if
if token is Comment.Preproc:
if (if_false_level == 1 and
re.match(r'%sel(if|se)\b' % pp, value)):
if_false_level = 0
elif re.match(r'%sif' % pp, value):
if_false_level += 1
elif re.match(r'%sendif\b' % pp, value):
if_false_level -= 1
else:
token = Comment
yield index, token, value
|
naototty/pyflag | refs/heads/master | src/pyflag/ScannerUtils.py | 7 | #!/usr/bin/env python
""" Utilities related to scanners """
# Michael Cohen <[email protected]>
# David Collett <[email protected]>
#
# ******************************************************
# Version: FLAG $Version: 0.87-pre1 Date: Thu Jun 12 00:48:38 EST 2008$
# ******************************************************
#
# * This program is free software; you can redistribute it and/or
# * modify it under the terms of the GNU General Public License
# * as published by the Free Software Foundation; either version 2
# * of the License, or (at your option) any later version.
# *
# * This program is distributed in the hope that it will be useful,
# * but WITHOUT ANY WARRANTY; without even the implied warranty of
# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# * GNU General Public License for more details.
# *
# * You should have received a copy of the GNU General Public License
# * along with this program; if not, write to the Free Software
# * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
# ******************************************************
import pyflag.Registry as Registry
import pyflag.pyflaglog as pyflaglog
import pyflag.FlagFramework as FlagFramework
def scan_groups_gen():
""" A Generator yielding all the scan groups (those scanners with
a Draw subclass)
"""
for cls in Registry.SCANNERS.classes:
try:
drawer_cls = cls.Drawer
except AttributeError:
continue
yield cls
def fill_in_dependancies(scanners):
""" Will add scanner names to scanners to satisfy all dependancies.
Will also sort scanners in dependancy order - so that scanners
which depend on other scanners follow them in the list.
"""
result = []
dependancies = []
def find_dependencies(scanner, dependancies):
""" Fills in scanner's dependancies in dependancies """
try:
cls = Registry.SCANNERS.dispatch(scanner)
except ValueError:
return
if type(cls.depends)==type(''):
depends = [cls.depends]
else:
depends = cls.depends
for d in depends:
dependancies.append(d)
find_dependencies(d, dependancies)
groups = Registry.SCANNERS.get_groups()
for s in scanners:
## Is it a scanner that was specified?
if s in Registry.SCANNERS.class_names:
dependancies.append(s)
find_dependencies(s, dependancies)
elif s in groups:
for g in groups[s]:
print g
#name = ("%s" % g).split(".")[-1]
name = g.name
dependancies.append(name)
find_dependencies(name, dependancies)
for i in range(len(dependancies)):
if dependancies[i] not in dependancies[i+1:]:
result.append(dependancies[i])
result.reverse()
return result
|
HiroIshikawa/21playground | refs/heads/master | payblog/blog/lib/python3.5/site-packages/micawber/parsers.py | 1 | import re
from .compat import text_type
try:
import simplejson as json
except ImportError:
import json
try:
from BeautifulSoup import BeautifulSoup
bs_kwargs = {'convertEntities': BeautifulSoup.HTML_ENTITIES}
replace_kwargs = {}
except ImportError:
try:
from bs4 import BeautifulSoup
bs_kwargs = replace_kwargs = {'features': 'html.parser'}
except ImportError:
BeautifulSoup = None
from micawber.exceptions import ProviderException
url_pattern = '(https?://[-A-Za-z0-9+&@#/%?=~_()|!:,.;]*[-A-Za-z0-9+&@#/%=~_|])'
url_re = re.compile(url_pattern)
standalone_url_re = re.compile('^\s*' + url_pattern + '\s*$')
block_elements = set([
'address', 'blockquote', 'center', 'dir', 'div', 'dl', 'fieldset', 'form',
'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'isindex', 'menu', 'noframes',
'noscript', 'ol', 'p', 'pre', 'table', 'ul', 'dd', 'dt', 'frameset', 'li',
'tbody', 'td', 'tfoot', 'th', 'thead', 'tr', 'button', 'del', 'iframe',
'ins', 'map', 'object', 'script', '[document]'
])
skip_elements = set(['a', 'pre', 'code'])
def full_handler(url, response_data, **params):
if response_data['type'] == 'link':
return '<a href="%(url)s" title="%(title)s">%(title)s</a>' % response_data
elif response_data['type'] == 'photo':
return '<a href="%(url)s" title="%(title)s"><img alt="%(title)s" src="%(url)s" /></a>' % response_data
else:
return response_data['html']
def inline_handler(url, response_data, **params):
return '<a href="%(url)s" title="%(title)s">%(title)s</a>' % response_data
def urlize(url):
return '<a href="%s">%s</a>' % (url, url)
def extract(text, providers, **params):
all_urls = set()
urls = []
extracted_urls = {}
for url in re.findall(url_re, text):
if url in all_urls:
continue
all_urls.add(url)
urls.append(url)
try:
extracted_urls[url] = providers.request(url, **params)
except ProviderException:
pass
return urls, extracted_urls
def parse_text_full(text, providers, urlize_all=True, handler=full_handler, **params):
all_urls, extracted_urls = extract(text, providers, **params)
replacements = {}
for url in all_urls:
if url in extracted_urls:
replacements[url] = handler(url, extracted_urls[url], **params)
elif urlize_all:
replacements[url] = urlize(url)
# go through the text recording URLs that can be replaced
# taking note of their start & end indexes
urls = re.finditer(url_re, text)
matches = []
for match in urls:
if match.group() in replacements:
matches.append([match.start(), match.end(), match.group()])
# replace the URLs in order, offsetting the indices each go
for indx, (start, end, url) in enumerate(matches):
replacement = replacements[url]
difference = len(replacement) - len(url)
# insert the replacement between two slices of text surrounding the
# original url
text = text[:start] + replacement + text[end:]
# iterate through the rest of the matches offsetting their indices
# based on the difference between replacement/original
for j in range(indx + 1, len(matches)):
matches[j][0] += difference
matches[j][1] += difference
return text
def parse_text(text, providers, urlize_all=True, handler=full_handler, block_handler=inline_handler, **params):
lines = text.splitlines()
parsed = []
for line in lines:
if standalone_url_re.match(line):
url = line.strip()
try:
response = providers.request(url, **params)
except ProviderException:
if urlize_all:
line = urlize(url)
else:
line = handler(url, response, **params)
else:
line = parse_text_full(line, providers, urlize_all, block_handler, **params)
parsed.append(line)
return '\n'.join(parsed)
def parse_html(html, providers, urlize_all=True, handler=full_handler, block_handler=inline_handler, **params):
if not BeautifulSoup:
raise Exception('Unable to parse HTML, please install BeautifulSoup or use the text parser')
soup = BeautifulSoup(html, **bs_kwargs)
for url in soup.findAll(text=re.compile(url_re)):
if not _inside_skip(url):
if _is_standalone(url):
url_handler = handler
else:
url_handler = block_handler
url_unescaped = url.string
replacement = parse_text_full(url_unescaped, providers, urlize_all, url_handler, **params)
url.replaceWith(BeautifulSoup(replacement, **replace_kwargs))
return text_type(soup)
def extract_html(html, providers, **params):
if not BeautifulSoup:
raise Exception('Unable to parse HTML, please install BeautifulSoup or use the text parser')
soup = BeautifulSoup(html, **bs_kwargs)
all_urls = set()
urls = []
extracted_urls = {}
for url in soup.findAll(text=re.compile(url_re)):
if _inside_skip(url):
continue
block_all, block_ext = extract(text_type(url), providers, **params)
for extracted_url in block_all:
if extracted_url in all_urls:
continue
extracted_urls.update(block_ext)
urls.append(extracted_url)
all_urls.add(extracted_url)
return urls, extracted_urls
def _is_standalone(soup_elem):
if standalone_url_re.match(soup_elem):
return soup_elem.parent.name in block_elements
return False
def _inside_skip(soup_elem):
parent = soup_elem.parent
while parent is not None:
if parent.name in skip_elements:
return True
parent = parent.parent
return False
|
rigdenlab/ample | refs/heads/master | ample/util/options_processor.py | 1 | """Module coordinating the option checking"""
__author__ = "Jens Thomas, and Felix Simkovic"
__date__ = "01 Nov 2016"
__version__ = "1.0"
import glob
import logging
import os
import shutil
from ample.constants import AMPLE_PKL
from ample.ensembler.constants import (
SUBCLUSTER_RADIUS_THRESHOLDS,
SIDE_CHAIN_TREATMENTS,
ALLOWED_SIDE_CHAIN_TREATMENTS,
SPICKER_RMSD,
SPICKER_TM,
POLYALA,
RELIABLE,
ALLATOM,
)
from ample.ensembler.truncation_util import TRUNCATION_METHODS
from ample.modelling import rosetta_model
from ample.util import ample_util, contact_util, exit_util, mrbump_util, mtz_util, sequence_util
logger = logging.getLogger(__name__)
def check_mandatory_options(optd):
"""Check the mandatory options for correctness
Description
-----------
We check there here rather then with argparse as there doesn't seem
to be an easy way to get the logic to work of having overlapping
required and mutually exclusive options
"""
def _exit(msg, wdir):
raise RuntimeError(msg)
if not (optd['fasta'] or optd['restart_pkl']):
msg = "One of -fasta or -restart_pkl option is required."
_exit(msg, optd['work_dir'])
if (optd['contact_file'] or optd['bbcontacts_file']) and optd['restraints_file']:
msg = "Only one option of -contact_file or -restraints_file allowed."
_exit(msg, optd['work_dir'])
if not optd['restart_pkl'] and not (optd['mtz'] or optd['sf_cif']) and optd['do_mr']:
msg = "A crystallographic data file must be supplied with the -mtz or -sc_cif options."
_exit(msg, optd['work_dir'])
if optd['do_mr'] and (optd['mtz'] and optd['sf_cif']):
msg = "Please supply a single crystallographic data file. {}"
_exit(msg, optd['work_dir'])
if optd['devel_mode'] and optd['quick_mode']:
msg = "Only one of quick_mode or devel_mode is permitted"
_exit(msg, optd['work_dir'])
if optd['molrep_only'] and optd['phaser_only']:
msg = "Only one of molrep_only or phaser_only is permitted"
_exit(msg, optd['work_dir'])
return
def process_benchmark_options(optd):
# Benchmark Mode
if optd['native_pdb'] or optd['benchmark_mode']:
if optd['native_pdb'] and not os.path.isfile(optd['native_pdb']):
raise RuntimeError("Cannot find crystal structure PDB: {0}".format(optd['native_pdb']))
optd['benchmark_mode'] = True
optd['benchmark_dir'] = os.path.join(optd['work_dir'], "benchmark")
logger.info("*** AMPLE running in benchmark mode ***")
# See if we can find TMscore
if not optd['tmscore_exe']:
optd['tmscore_exe'] = 'TMscore' + ample_util.EXE_EXT
try:
optd['tmscore_exe'] = ample_util.find_exe(optd['tmscore_exe'])
except ample_util.FileNotFoundError:
logger.warning("Cannot find TMScore executable: %s", optd['tmscore_exe'])
optd['have_tmscore'] = False
else:
optd['have_tmscore'] = True
def process_ensemble_options(optd):
if optd['single_model_mode'] and optd['truncation_scorefile'] and optd['truncation_scorefile_header']:
optd['truncation_method'] = TRUNCATION_METHODS.SCORES
elif optd['single_model_mode']:
if not optd['truncation_method']:
optd['truncation_method'] = TRUNCATION_METHODS.BFACTORS
else:
optd['truncation_method'] = TRUNCATION_METHODS(optd['truncation_method'])
elif optd['percent_fixed_intervals']:
optd['truncation_method'] = TRUNCATION_METHODS.PERCENT_FIXED
else:
try:
optd['truncation_method'] = TRUNCATION_METHODS(optd['truncation_method'])
except ValueError:
raise RuntimeError(
"{} is not a valid truncation method. Use one of: {}".format(
optd['truncation_method'], [e.value for e in TRUNCATION_METHODS]
)
)
# Check we can find all the required programs
if optd['subcluster_program'] == 'gesamt':
if not optd['gesamt_exe']:
optd['gesamt_exe'] = os.path.join(os.environ['CCP4'], 'bin', 'gesamt' + ample_util.EXE_EXT)
try:
optd['gesamt_exe'] = ample_util.find_exe(optd['gesamt_exe'])
except ample_util.FileNotFoundError:
raise RuntimeError("Cannot find Gesamt executable: {0}".format(optd['gesamt_exe']))
# Ensemble options
if optd['cluster_method'] in [SPICKER_RMSD, SPICKER_TM]:
if not optd['spicker_exe']:
if optd['cluster_method'] == SPICKER_TM and optd['nproc'] > 1:
# We need to use the multicore version of SPICKER
optd['spicker_exe'] = 'spicker_omp' + ample_util.EXE_EXT
else:
optd['spicker_exe'] = 'spicker' + ample_util.EXE_EXT
try:
optd['spicker_exe'] = ample_util.find_exe(optd['spicker_exe'])
except ample_util.FileNotFoundError:
raise RuntimeError("Cannot find spicker executable: {0}".format(optd['spicker_exe']))
elif optd['cluster_method'] in ['fast_protein_cluster']:
if not optd['fast_protein_cluster_exe']:
optd['fast_protein_cluster_exe'] = 'fast_protein_cluster'
try:
optd['fast_protein_cluster_exe'] = ample_util.find_exe(optd['fast_protein_cluster_exe'])
except ample_util.FileNotFoundError:
raise RuntimeError(
"Cannot find fast_protein_cluster executable: {0}".format(optd['fast_protein_cluster_exe'])
)
elif optd['cluster_method'] in ['import', 'random', 'skip']:
pass
else:
raise RuntimeError("Unrecognised cluster_method: {0}".format(optd['cluster_method']))
if not optd['theseus_exe']:
optd['theseus_exe'] = os.path.join(os.environ['CCP4'], 'bin', 'theseus' + ample_util.EXE_EXT)
try:
optd['theseus_exe'] = ample_util.find_exe(optd['theseus_exe'])
except ample_util.FileNotFoundError:
raise RuntimeError("Cannot find theseus executable: {0}".format(optd['theseus_exe']))
# SCRWL - we always check for SCRWL as if we are processing QUARK models we want to add sidechains to them
if not optd['scwrl_exe']:
optd['scwrl_exe'] = os.path.join(os.environ['CCP4'], 'bin', 'Scwrl4' + ample_util.EXE_EXT)
try:
optd['scwrl_exe'] = ample_util.find_exe(optd['scwrl_exe'])
except ample_util.FileNotFoundError as e:
logger.info("Cannot find Scwrl executable: %s", optd['scwrl_exe'])
if optd['use_scwrl']:
raise (e)
if "subcluster_radius_thresholds" in optd and not optd["subcluster_radius_thresholds"]:
optd["subcluster_radius_thresholds"] = SUBCLUSTER_RADIUS_THRESHOLDS
# REM: This should really be disentangled and moved up to definition of all homologs options
# REM: but could cause confusion with defaults down here.
if "side_chain_treatments" in optd and not optd["side_chain_treatments"]:
if optd["homologs"]:
optd["side_chain_treatments"] = [POLYALA, RELIABLE, ALLATOM]
else:
optd["side_chain_treatments"] = SIDE_CHAIN_TREATMENTS
else:
optd["side_chain_treatments"] = map(str.lower, optd["side_chain_treatments"])
unrecognised_sidechains = set(optd["side_chain_treatments"]) - set(ALLOWED_SIDE_CHAIN_TREATMENTS)
if unrecognised_sidechains:
raise ("Unrecognised side_chain_treatments: {0}".format(unrecognised_sidechains))
return
def process_options(optd):
"""Process the initial options from the command-line/ample.ini file to set any additional options.
Description
-----------
This is where we take the options determining the type of run we are undertaking and set any additional
options required based on that runtype. All the major
"""
# Path for pickling results
optd['results_path'] = os.path.join(optd['work_dir'], AMPLE_PKL)
# FASTA processing
# Check to see if mr_sequence was given and if not mr_sequence defaults to fasta
if optd['mr_sequence'] != None:
if not (os.path.exists(str(optd['mr_sequence']))):
raise RuntimeError('Cannot find mr sequence file: {0}'.format(optd['mr_sequence']))
else:
optd['mr_sequence'] = optd['fasta']
# Process the fasta file and run all the checks on the sequence
sequence_util.process_fasta(optd, canonicalise=True)
# Not sure if name actually required - see make_fragments.pl
if optd['name'] and len(optd['name']) != 4:
raise RuntimeError('-name argument is the wrong length, use 4 chars eg ABCD')
# Underscore required by rosetta make_fragments.pl
optd['name'] += '_'
# MTZ file processing
if optd['do_mr']:
try:
mtz_util.processReflectionFile(optd)
except Exception as e:
raise RuntimeError("Error processing reflection file: {0}".format(e))
# Contact file processing
if optd['contact_file'] or optd['bbcontacts_file'] or not optd["no_contact_prediction"]:
contact_util.ContactUtil.check_options(optd)
optd['use_contacts'] = True
process_modelling_options(optd)
if optd['coiled_coil']:
# Add in Owen's fixes
optd['rg_reweight'] = 0.0
optd['domain_termini_distance'] = optd['fasta_length'] * 1.5
pkey = ['PKEYWORD', 'TNCS', 'USE', 'OFF']
if isinstance(optd['mr_keys'], list):
optd['mr_keys'].append(pkey)
else:
optd['mr_keys'] = [pkey]
process_ensemble_options(optd)
if optd['do_mr']:
process_mr_options(optd)
process_benchmark_options(optd)
if optd['submit_cluster'] and not optd['submit_qtype']:
raise RuntimeError(
'Must use -submit_qtype argument to specify queueing system (e.g. QSUB, LSF ) if submitting to a cluster.'
)
try:
optd['purge'] = int(optd['purge'])
except (ValueError, KeyError):
raise RuntimeError('Purge must be specified as an integer, got: {}'.format(optd['purge']))
if optd['purge'] > 0:
logger.info('*** Purge mode level %d specified - intermediate files will be deleted ***', optd['purge'])
return
def process_modelling_options(optd):
""" Modelling and ensemble options"""
# Set default name for modelling directory
optd['models_dir'] = os.path.join(optd['work_dir'], "models")
# Check if importing ensembles
if optd['ensembles']:
# checks are made in ensembles.import_ensembles
optd['import_ensembles'] = True
optd['make_frags'] = False
optd['make_models'] = False
elif optd['cluster_dir']:
if not os.path.isdir(optd['cluster_dir']):
raise RuntimeError("Import cluster cannot find directory: {0}".format(optd['cluster_dir']))
models = glob.glob(os.path.join(optd['cluster_dir'], "*.pdb"))
if not models:
raise RuntimeError("Import cluster cannot find pdbs in directory: {0}".format(optd['cluster_dir']))
logger.info("Importing pre-clustered models from directory: %s\n", optd['cluster_dir'])
optd['cluster_method'] = 'import'
optd['models'] = optd['cluster_dir']
optd['make_frags'] = False
optd['make_models'] = False
elif optd['ideal_helices'] or optd['helical_ensembles']:
optd['make_frags'] = False
optd['make_models'] = False
elif optd['homologs']:
optd['make_frags'] = False
optd['make_models'] = False
if not os.path.isfile(str(optd['alignment_file'])):
# We need to use gesamt or mustang to do the alignment
if optd['homolog_aligner'] == 'gesamt':
if not ample_util.is_exe(str(optd['gesamt_exe'])):
optd['gesamt_exe'] = os.path.join(os.environ['CCP4'], 'bin', 'gesamt' + ample_util.EXE_EXT)
if not ample_util.is_exe(str(optd['gesamt_exe'])):
raise RuntimeError(
'Using homologs without an alignment file and cannot find gesamt_exe: {0}'.format(
optd['gesamt_exe']
)
)
elif optd['homolog_aligner'] == 'mustang':
if not ample_util.is_exe(str(optd['mustang_exe'])):
raise RuntimeError(
'Using homologs without an alignment file and cannot find mustang_exe: {0}'.format(
optd['mustang_exe']
)
)
else:
raise RuntimeError('Unknown homolog_aligner: {0}'.format(optd['homolog_aligner']))
if not os.path.isdir(str(optd['models'])):
raise RuntimeError(
"Homologs option requires a directory of pdb models to be supplied\n"
+ "Please supply the models with the -models flag"
)
optd['import_models'] = True
elif optd['models']:
if not os.path.exists(optd['models']):
raise RuntimeError("Cannot find -models path: {}".format(optd['models']))
optd['import_models'] = True
optd['make_frags'] = False
optd['make_models'] = False
elif optd['single_model']:
optd['cluster_method'] = "skip"
optd['make_frags'] = False
optd['make_models'] = False
optd['single_model_mode'] = True
# Check import flags
if optd['import_ensembles'] and (optd['import_models']):
raise RuntimeError("Cannot import both models and ensembles/clusters!")
# NMR Checks
if optd['nmr_model_in']:
logger.info("Using nmr_model_in file: %s", optd['nmr_model_in'])
if not os.path.isfile(optd['nmr_model_in']):
msg = "nmr_model_in flag given, but cannot find file: {0}".format(optd['nmr_model_in'])
exit_util.exit_error(msg)
if optd['nmr_remodel']:
optd['make_models'] = True
if optd['nmr_remodel_fasta']:
if not os.path.isfile(optd['nmr_remodel_fasta']):
raise RuntimeError("Cannot find nmr_remodel_fasta file: {0}".format(optd['nmr_remodel_fasta']))
else:
optd['nmr_remodel_fasta'] = optd['fasta']
msg = "NMR model will be remodelled with ROSETTA using the sequence from: {0}".format(
optd['nmr_remodel_fasta']
)
logger.info(msg)
if not (optd['frags_3mers'] and optd['frags_9mers']):
optd['make_frags'] = True
msg = "nmr_remodel - will be making our own fragment files"
logger.info(msg)
else:
if not (os.path.isfile(optd['frags_3mers']) and os.path.isfile(optd['frags_9mers'])):
raise RuntimeError(
"frags_3mers and frag_9mers files given, but cannot locate them:\n{0}\n{1}\n".format(
optd['frags_3mers'], optd['frags_9mers']
)
)
optd['make_frags'] = False
else:
optd['make_frags'] = False
optd['make_models'] = False
msg = "Running in NMR truncate only mode"
logger.info(msg)
elif optd['make_models']:
if not os.path.isdir(optd['models_dir']):
os.mkdir(optd['models_dir'])
# If the user has given both fragment files we check they are ok and unset make_frags
if optd['frags_3mers'] and optd['frags_9mers']:
if not os.path.isfile(optd['frags_3mers']) or not os.path.isfile(optd['frags_9mers']):
raise RuntimeError(
"frags_3mers and frag_9mers files given, but cannot locate them:\n{0}\n{1}\n".format(
optd['frags_3mers'], optd['frags_9mers']
)
)
optd['make_frags'] = False
if optd['make_frags'] and (optd['frags_3mers'] or optd['frags_9mers']):
raise RuntimeError("make_frags set to true, but you have given the path to the frags_3mers or frags_9mers")
if not optd['make_frags'] and not (optd['frags_3mers'] and optd['frags_9mers']):
msg = """*** Missing fragment files! ***
Please supply the paths to the fragment files using the -frags_3mers and -frags_9mers flags.
These can be generated using the Robetta server: http://robetta.bakerlab.org
Please see the AMPLE documentation for further information."""
raise RuntimeError(msg)
if optd['make_frags']:
if optd['use_homs']:
logger.info('Making fragments (including homologues)')
else:
logger.info('Making fragments EXCLUDING HOMOLOGUES')
else:
logger.info('NOT making Fragments')
if optd['make_models']:
logger.info('\nMaking Rosetta Models')
else:
logger.info('NOT making Rosetta Models')
def process_mr_options(optd):
# Molecular Replacement Options
if optd['molrep_only']:
optd['phaser_only'] = False
if optd['molrep_only']:
optd['mrbump_programs'] = ['molrep']
elif optd['phaser_only']:
optd['mrbump_programs'] = ['phaser']
else:
optd['mrbump_programs'] = ['molrep', 'phaser']
if optd['phaser_rms'] != 'auto':
try:
phaser_rms = float(optd['phaser_rms'])
except ValueError as e:
msg = "Error converting phaser_rms '{0}' to floating point: {1}".format(optd['phaser_rms'], e)
exit_util.exit_error(msg)
else:
optd['phaser_rms'] = phaser_rms
# Disable all rebuilding if the resolution is too poor
if optd['mtz_min_resolution'] >= mrbump_util.REBUILD_MAX_PERMITTED_RESOLUTION:
logger.warning(
"!!! Disabling all rebuilding as maximum resolution of %f is too poor!!!".format(optd['mtz_min_resolution'])
)
optd['use_shelxe'] = False
optd['shelxe_rebuild'] = False
optd['shelxe_rebuild_arpwarp'] = False
optd['shelxe_rebuild_buccaneer'] = False
optd['refine_rebuild_arpwarp'] = False
optd['refine_rebuild_buccaneer'] = False
if float(optd['shelxe_max_resolution']) < 0.0:
if optd['coiled_coil']:
optd['shelxe_max_resolution'] = mrbump_util.SHELXE_MAX_PERMITTED_RESOLUTION_CC
else:
optd['shelxe_max_resolution'] = mrbump_util.SHELXE_MAX_PERMITTED_RESOLUTION
# We use shelxe by default so if we can't find it we just warn and set use_shelxe to False
if optd['use_shelxe']:
if float(optd['mtz_min_resolution']) > float(optd['shelxe_max_resolution']):
logger.warning(
"Disabling use of SHELXE as min resolution of %f is > accepted limit of %f",
optd['mtz_min_resolution'],
optd['shelxe_max_resolution'],
)
optd['use_shelxe'] = False
optd['shelxe_rebuild'] = False
optd['shelxe_rebuild_arpwarp'] = False
optd['shelxe_rebuild_buccaneer'] = False
if optd['use_shelxe']:
if not optd['shelxe_exe']:
optd['shelxe_exe'] = os.path.join(os.environ['CCP4'], 'bin', 'shelxe' + ample_util.EXE_EXT)
try:
optd['shelxe_exe'] = ample_util.find_exe(optd['shelxe_exe'])
except ample_util.FileNotFoundError:
msg = """*** Cannot find shelxe executable in PATH - turning off use of SHELXE. ***
SHELXE is recommended for the best chance of success. We recommend you install shelxe from:
http://shelx.uni-ac.gwdg.de/SHELX/
and install it in your PATH so that AMPLE can use it.
"""
logger.warning(msg)
optd['use_shelxe'] = False
if optd['shelxe_rebuild']:
optd['shelxe_rebuild_arpwarp'] = True
optd['shelxe_rebuild_buccaneer'] = True
# If shelxe_rebuild is set we need use_shelxe to be set
if (optd['shelxe_rebuild'] or optd['shelxe_rebuild_arpwarp'] or optd['shelxe_rebuild_buccaneer']) and not optd[
'use_shelxe'
]:
raise RuntimeError('shelxe_rebuild is set but use_shelxe is False. Please make sure you have shelxe installed.')
if optd['refine_rebuild_arpwarp'] or optd['shelxe_rebuild_arpwarp']:
auto_tracing_sh = None
if 'warpbin' in os.environ:
_path = os.path.join(os.environ['warpbin'], "auto_tracing.sh")
if os.path.isfile(_path):
auto_tracing_sh = _path
if auto_tracing_sh:
logger.info('Using arpwarp script: %s', auto_tracing_sh)
else:
logger.warn('Cannot find arpwarp script! Disabling use of arpwarp.')
optd['refine_rebuild_arpwarp'] = False
optd['shelxe_rebuild_arpwarp'] = False
if optd['refine_rebuild_arpwarp'] or optd['shelxe_rebuild_arpwarp']:
logger.info('Rebuilding in ARP/wARP')
else:
logger.info('Not rebuilding in ARP/wARP')
if optd['refine_rebuild_buccaneer'] or optd['shelxe_rebuild_buccaneer']:
logger.info('Rebuilding in Buccaneer')
else:
logger.info('Not rebuilding in Buccaneer')
def process_restart_options(optd):
"""Process the restart options
Description
-----------
For any new command-line options, we update the old dictionary with the new values
We then go through the new dictionary and set ant of the flags corresponding to the data we find:
if restart.pkl
- if completed mrbump jobs
make_frags, make_models, make_ensembles = False
make_mr = True
- if all jobs aren't completed, rerun the remaining mrbump jobs - IN THE OLD DIRECTORY?
- if all jobs are completed and we are in benchmark mode run the benchmarking
make_frags, make_models, make_ensembles, make_mr = False
make_benchmark = True
- END
- if ensemble files
- if no ensemble data, create ensemble data
make_frags, make_models, make_ensembles = False
make_mr = True
- create and run the mrbump jobs - see above
# Below all same as default
- if models and no ensembles
- create ensembles from the models
FLAGS
make_frags
make_models
make_ensembles
make_mr
make_benchmark
Notes
-----
We return the dictionary as we may need to change it and it seems we can't change the external
reference in this scope. I think?...
"""
if not optd['restart_pkl']:
return optd
logger.info('Restarting from existing pkl file: %s', optd['restart_pkl'])
# Go through and see what we need to do
# Reset all variables for doing stuff - otherwise we will always restart from the earliest point
optd['make_ensembles'] = False
# optd['import_ensembles'] = False # Needs thinking about - have to set so we don't just reimport models/ensembles
optd['import_models'] = False # Needs thinking about
optd['make_models'] = False
optd['make_frags'] = False
# First see if we should benchmark this job. The user may not have supplied a native_pdb with the original
# job and we only set benchmark mode on seeing the native_pdb
if optd['native_pdb']:
if not os.path.isfile(optd['native_pdb']):
raise RuntimeError("Cannot find native_pdb: {0}".format(optd['native_pdb']))
optd['benchmark_mode'] = True
logger.info('Restart using benchmark mode')
# We always check first to see if there are any mrbump jobs
optd['mrbump_scripts'] = []
if 'mrbump_dir' in optd:
optd['mrbump_scripts'] = mrbump_util.unfinished_scripts(optd)
if not optd['mrbump_scripts']:
optd['do_mr'] = False
if optd['do_mr']:
if len(optd['mrbump_scripts']):
logger.info('Restarting from unfinished mrbump scripts: %s', optd['mrbump_scripts'])
# Purge unfinished jobs
for spath in optd['mrbump_scripts']:
directory, script = os.path.split(spath)
name, _ = os.path.splitext(script)
# Hack to delete old job directories
logfile = os.path.join(directory, name + '.log')
if os.path.isfile(logfile):
os.unlink(logfile)
jobdir = os.path.join(directory, 'search_' + name + '_mrbump')
if os.path.isdir(jobdir):
shutil.rmtree(jobdir)
elif 'ensembles' in optd and optd['ensembles'] and len(optd['ensembles']):
# Rerun from ensembles - check for data/ensembles are ok?
logger.info('Restarting from existing ensembles: %s', optd['ensembles'])
elif 'models_dir' in optd and optd['models_dir'] and os.path.isdir(optd['models_dir']):
logger.info('Restarting from existing models: %s', optd['models_dir'])
optd['make_ensembles'] = True
elif optd['frags_3mers'] and optd['frags_9mers']:
logger.info('Restarting from existing fragments: %s, %s', optd['frags_3mers'], optd['frags_9mers'])
optd['make_models'] = True
return optd
def process_rosetta_options(optd):
# Create the rosetta modeller - this runs all the checks required
rosetta_modeller = None
if optd['make_models'] or optd['make_frags']: # only need Rosetta if making models
logger.info('Using ROSETTA so checking options')
try:
rosetta_modeller = rosetta_model.RosettaModel(optd=optd)
except Exception as e:
msg = "Error setting ROSETTA options: {0}".format(e)
exit_util.exit_error(msg)
optd['modelling_workdir'] = rosetta_modeller.work_dir
return rosetta_modeller
def restart_amoptd(optd):
"""Create an ample dictionary from a restart pkl file
Description
-----------
For any new command-line options, we update the old dictionary with the new values
We then go through the new dictionary and set any of the flags corresponding to the data we find:
Notes
-----
We return the dictionary as we may need to change it and it seems we can't change the external
reference in this scope. I think?...
"""
if not optd['restart_pkl']:
return optd
logger.info('Restarting from existing pkl file: %s', optd['restart_pkl'])
optd_old = ample_util.read_amoptd(optd['restart_pkl'])
for k in optd['cmdline_flags']:
logger.debug("Restart updating amopt variable: %s : %s", k, str(optd[k]))
optd_old[k] = optd[k]
optd = optd_old
return optd
|
todaychi/hue | refs/heads/master | desktop/core/ext-py/python-ldap-2.3.13/Lib/ldap/schema/subentry.py | 44 | """
ldap.schema.subentry - subschema subentry handling
See http://www.python-ldap.org/ for details.
\$Id: subentry.py,v 1.25 2010/04/30 08:39:38 stroeder Exp $
"""
import ldap.cidict,ldap.schema
from ldap.schema.models import *
from UserDict import UserDict
SCHEMA_CLASS_MAPPING = ldap.cidict.cidict()
SCHEMA_ATTR_MAPPING = {}
for _name in dir():
o = eval(_name)
if hasattr(o,'schema_attribute'):
SCHEMA_CLASS_MAPPING[o.schema_attribute] = o
SCHEMA_ATTR_MAPPING[o] = o.schema_attribute
SCHEMA_ATTRS = SCHEMA_CLASS_MAPPING.keys()
class SubSchema:
def __init__(self,sub_schema_sub_entry):
"""
sub_schema_sub_entry
Dictionary containing the sub schema sub entry
"""
# Initialize all dictionaries
self.name2oid = {}
self.sed = {}
for c in SCHEMA_CLASS_MAPPING.values():
self.name2oid[c] = ldap.cidict.cidict()
self.sed[c] = {}
e = ldap.cidict.cidict(sub_schema_sub_entry)
# Build the schema registry
for attr_type in SCHEMA_ATTRS:
if not e.has_key(attr_type) or \
not e[attr_type]:
continue
for attr_value in filter(None,e[attr_type]):
se_class = SCHEMA_CLASS_MAPPING[attr_type]
se_instance = se_class(attr_value)
self.sed[se_class][se_instance.get_id()] = se_instance
if hasattr(se_instance,'names'):
for name in se_instance.names:
self.name2oid[se_class][name] = se_instance.get_id()
return # subSchema.__init__()
def ldap_entry(self):
"""
Returns a dictionary containing the sub schema sub entry
"""
# Initialize the dictionary with empty lists
entry = {}
# Collect the schema elements and store them in
# entry's attributes
for se_class in self.sed.keys():
for se in self.sed[se_class].values():
se_str = str(se)
try:
entry[SCHEMA_ATTR_MAPPING[se_class]].append(se_str)
except KeyError:
entry[SCHEMA_ATTR_MAPPING[se_class]] = [ se_str ]
return entry
def listall(self,schema_element_class,schema_element_filters=None):
"""
Returns a list of OIDs of all available schema
elements of a given schema element class.
"""
avail_se = self.sed[schema_element_class]
if schema_element_filters:
result = []
for se_key in avail_se.keys():
se = avail_se[se_key]
for fk,fv in schema_element_filters:
try:
if getattr(se,fk) in fv:
result.append(se_key)
except AttributeError:
pass
else:
result = avail_se.keys()
return result
def tree(self,schema_element_class,schema_element_filters=None):
"""
Returns a ldap.cidict.cidict dictionary representing the
tree structure of the schema elements.
"""
assert schema_element_class in [ObjectClass,AttributeType]
avail_se = self.listall(schema_element_class,schema_element_filters)
top_node = '_'
tree = ldap.cidict.cidict({top_node:[]})
# 1. Pass: Register all nodes
for se in avail_se:
tree[se] = []
# 2. Pass: Register all sup references
for se_oid in avail_se:
se_obj = self.get_obj(schema_element_class,se_oid,None)
if se_obj.__class__!=schema_element_class:
# Ignore schema elements not matching schema_element_class.
# This helps with falsely assigned OIDs.
continue
assert se_obj.__class__==schema_element_class, \
"Schema element referenced by %s must be of class %s but was %s" % (
se_oid,schema_element_class.__name__,se_obj.__class__
)
for s in se_obj.sup or ('_',):
sup_oid = self.name2oid[schema_element_class].get(s,s)
try:
tree[sup_oid].append(se_oid)
except:
pass
return tree
def getoid(self,se_class,nameoroid):
"""
Get an OID by name or OID
"""
se_oid = nameoroid.split(';')[0].strip()
return self.name2oid[se_class].get(se_oid,se_oid)
def get_inheritedattr(self,se_class,nameoroid,name):
"""
Get a possibly inherited attribute specified by name
of a schema element specified by nameoroid.
Returns None if class attribute is not set at all.
Raises KeyError if no schema element is found by nameoroid.
"""
se = self.sed[se_class][self.getoid(se_class,nameoroid)]
try:
result = getattr(se,name)
except AttributeError:
result = None
if result is None and se.sup:
result = self.get_inheritedattr(se_class,se.sup[0],name)
return result
def get_obj(self,se_class,nameoroid,default=None):
"""
Get a schema element by name or OID
"""
return self.sed[se_class].get(self.getoid(se_class,nameoroid),default)
def get_inheritedobj(self,se_class,nameoroid,inherited=None):
"""
Get a schema element by name or OID with all class attributes
set including inherited class attributes
"""
import copy
inherited = inherited or []
se = copy.copy(self.sed[se_class].get(self.getoid(se_class,nameoroid)))
if se and hasattr(se,'sup'):
for class_attr_name in inherited:
setattr(se,class_attr_name,self.get_inheritedattr(se_class,nameoroid,class_attr_name))
return se
def get_syntax(self,nameoroid):
"""
Get the syntax of an attribute type specified by name or OID
"""
at_oid = self.getoid(AttributeType,nameoroid)
try:
at_obj = self.get_inheritedobj(AttributeType,at_oid)
except KeyError:
return None
else:
return at_obj.syntax
def get_structural_oc(self,oc_list):
"""
Returns OID of structural object class in object_class_list
if any is present. Returns None else.
"""
# Get tree of all STRUCTURAL object classes
oc_tree = self.tree(ObjectClass,[('kind',[0])])
# Filter all STRUCTURAL object classes
struct_ocs = {}
for oc_nameoroid in oc_list:
oc_se = self.get_obj(ObjectClass,oc_nameoroid,None)
if oc_se and oc_se.kind==0:
struct_ocs[oc_se.oid] = None
result = None
struct_oc_list = struct_ocs.keys()
while struct_oc_list:
oid = struct_oc_list.pop()
for child_oid in oc_tree[oid]:
if struct_ocs.has_key(self.getoid(ObjectClass,child_oid)):
break
else:
result = oid
return result
def get_applicable_aux_classes(self,nameoroid):
"""
Return a list of the applicable AUXILIARY object classes
for a STRUCTURAL object class specified by 'nameoroid'
if the object class is governed by a DIT content rule.
If there's no DIT content rule all available AUXILIARY
object classes are returned.
"""
content_rule = self.get_obj(DITContentRule,nameoroid)
if content_rule:
# Return AUXILIARY object classes from DITContentRule instance
return content_rule.aux
else:
# list all AUXILIARY object classes
return self.listall(ObjectClass,[('kind',[2])])
def attribute_types(
self,object_class_list,attr_type_filter=None,raise_keyerror=1,ignore_dit_content_rule=0
):
"""
Returns a 2-tuple of all must and may attributes including
all inherited attributes of superior object classes
by walking up classes along the SUP attribute.
The attributes are stored in a ldap.cidict.cidict dictionary.
object_class_list
list of strings specifying object class names or OIDs
attr_type_filter
list of 2-tuples containing lists of class attributes
which has to be matched
raise_keyerror
All KeyError exceptions for non-existent schema elements
are ignored
ignore_dit_content_rule
A DIT content rule governing the structural object class
is ignored
"""
AttributeType = ldap.schema.AttributeType
ObjectClass = ldap.schema.ObjectClass
# Map object_class_list to object_class_oids (list of OIDs)
object_class_oids = [
self.name2oid[ObjectClass].get(o,o)
for o in object_class_list
]
# Initialize
oid_cache = {}
r_must,r_may = ldap.cidict.cidict(),ldap.cidict.cidict()
if '1.3.6.1.4.1.1466.101.120.111' in object_class_oids:
# Object class 'extensibleObject' MAY carry every attribute type
for at_obj in self.sed[AttributeType].values():
r_may[at_obj.oid] = at_obj
# Loop over OIDs of all given object classes
while object_class_oids:
object_class_oid = object_class_oids.pop(0)
# Check whether the objectClass with this OID
# has already been processed
if oid_cache.has_key(object_class_oid):
continue
# Cache this OID as already being processed
oid_cache[object_class_oid] = None
try:
object_class = self.sed[ObjectClass][object_class_oid]
except KeyError:
if raise_keyerror:
raise
# Ignore this object class
continue
assert isinstance(object_class,ObjectClass)
assert hasattr(object_class,'must'),ValueError(object_class_oid)
assert hasattr(object_class,'may'),ValueError(object_class_oid)
for a in object_class.must:
try:
at_obj = self.sed[AttributeType][self.name2oid[AttributeType].get(a,a)]
except KeyError:
if raise_keyerror:
raise
else:
r_must[a] = None
else:
r_must[at_obj.oid] = at_obj
for a in object_class.may:
try:
at_obj = self.sed[AttributeType][self.name2oid[AttributeType].get(a,a)]
except KeyError:
if raise_keyerror:
raise
else:
r_may[a] = None
else:
r_may[at_obj.oid] = at_obj
object_class_oids.extend([
self.name2oid[ObjectClass].get(o,o)
for o in object_class.sup
])
# Removed all mandantory attribute types from
# optional attribute type list
for a in r_may.keys():
if r_must.has_key(a):
del r_may[a]
# Process DIT content rules
if not ignore_dit_content_rule:
structural_oc = self.get_structural_oc(object_class_list)
if structural_oc:
# Process applicable DIT content rule
dit_content_rule = self.get_obj(DITContentRule,structural_oc)
if dit_content_rule:
for a in dit_content_rule.must:
try:
at_obj = self.sed[AttributeType][self.name2oid[AttributeType].get(a,a)]
except KeyError:
if raise_keyerror:
raise
else:
r_must[a] = None
else:
r_must[at_obj.oid] = at_obj
for a in dit_content_rule.may:
try:
at_obj = self.sed[AttributeType][self.name2oid[AttributeType].get(a,a)]
except KeyError:
if raise_keyerror:
raise
else:
r_may[a] = None
else:
r_may[at_obj.oid] = at_obj
for a in dit_content_rule.nots:
a_oid = self.name2oid[AttributeType].get(a,a)
if not r_must.has_key(a_oid):
try:
at_obj = self.sed[AttributeType][a_oid]
except KeyError:
if raise_keyerror:
raise
else:
try:
del r_must[at_obj.oid]
except KeyError:
pass
try:
del r_may[at_obj.oid]
except KeyError:
pass
# Apply attr_type_filter to results
if attr_type_filter:
for l in [r_must,r_may]:
for a in l.keys():
for afk,afv in attr_type_filter:
try:
schema_attr_type = self.sed[AttributeType][a]
except KeyError:
if raise_keyerror:
raise KeyError,'No attribute type found in sub schema by name %s' % (a)
# If there's no schema element for this attribute type
# but still KeyError is to be ignored we filter it away
del l[a]
break
else:
if not getattr(schema_attr_type,afk) in afv:
del l[a]
break
return r_must,r_may # attribute_types()
def urlfetch(uri,trace_level=0):
"""
Fetches a parsed schema entry by uri.
If uri is a LDAP URL the LDAP server is queried directly.
Otherwise uri is assumed to point to a LDIF file which
is loaded with urllib.
"""
uri = uri.strip()
if uri.startswith('ldap:') or uri.startswith('ldaps:') or uri.startswith('ldapi:'):
import ldapurl
ldap_url = ldapurl.LDAPUrl(uri)
l=ldap.initialize(ldap_url.initializeUrl(),trace_level)
l.protocol_version = ldap.VERSION3
l.simple_bind_s(ldap_url.who or '', ldap_url.cred or '')
subschemasubentry_dn = l.search_subschemasubentry_s(ldap_url.dn)
if subschemasubentry_dn is None:
subschemasubentry_entry = None
else:
if ldap_url.attrs is None:
schema_attrs = SCHEMA_ATTRS
else:
schema_attrs = ldap_url.attrs
subschemasubentry_entry = l.read_subschemasubentry_s(
subschemasubentry_dn,attrs=schema_attrs
)
l.unbind_s()
del l
else:
import urllib,ldif
ldif_file = urllib.urlopen(uri)
ldif_parser = ldif.LDIFRecordList(ldif_file,max_entries=1)
ldif_parser.parse()
subschemasubentry_dn,subschemasubentry_entry = ldif_parser.all_records[0]
if subschemasubentry_dn!=None:
parsed_sub_schema = ldap.schema.SubSchema(subschemasubentry_entry)
else:
parsed_sub_schema = None
return subschemasubentry_dn, parsed_sub_schema
|
ahmadshahwan/cohorte-runtime | refs/heads/master | python/cohorte/composer/top/criteria/distance/configuration.py | 2 | #!/usr/bin/env python
# -- Content-Encoding: UTF-8 --
"""
Top Composer: Group by configuration
:author: Thomas Calmant
:license: Apache Software License 2.0
:version: 3.0.0
..
This file is part of Cohorte.
Cohorte 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.
Cohorte 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 Cohorte. If not, see <http://www.gnu.org/licenses/>.
"""
# iPOPO Decorators
from pelix.ipopo.decorators import ComponentFactory, Requires, Provides, \
Instantiate
# Composer
import cohorte
import cohorte.composer
# ------------------------------------------------------------------------------
# Module version
__version_info__ = (3, 0, 0)
__version__ = ".".join(str(x) for x in __version_info__)
# Documentation strings format
__docformat__ = "restructuredtext en"
# ------------------------------------------------------------------------------
@ComponentFactory()
@Provides(cohorte.composer.SERVICE_TOP_CRITERION_DISTANCE)
@Requires('_configuration', cohorte.SERVICE_CONFIGURATION_READER)
@Instantiate('cohorte-composer-criterion-distance-configuration')
class ConfigurationCriterion(object):
"""
Groups components by configuration
"""
def __init__(self):
"""
Sets up members
"""
self._configuration = None
def _get_isolate_node(self, isolate_name):
"""
Reads the configuration of the given isolate and returns the specified
node name, or None
:param isolate_name: Name of an isolate
:return: A node name or None
"""
try:
# Read the configuration, without logging file errors
config = self._configuration.read("{0}.js".format(isolate_name),
False)
# Return the indicated node
return config.get('node')
except IOError:
# Ignore I/O error: the isolate has no specific configuration
pass
def group(self, components, groups):
"""
Groups components according to their implementation language
:param components: List of components to group
:param groups: Dictionary of current groups
:return: A tuple:
* Dictionary of grouped components (group -> components)
* List of components that haven't been grouped
"""
nodes = {}
isolate_nodes = {}
remaining = set(components)
for component in components:
node = None
if component.node:
# Explicit node
node = component.node
elif component.isolate:
# Explicit isolate
try:
node = isolate_nodes[component.isolate]
except KeyError:
# Look for the node associated to the isolate
node = self._get_isolate_node(component.isolate)
# Store the information
isolate_nodes[component.isolate] = node
if node:
# Found a node
nodes.setdefault(node, set()).add(component)
remaining.remove(component)
# Return the result
return nodes, remaining
|
softlayer/softlayer-python | refs/heads/master | SoftLayer/CLI/hardware/power.py | 4 | """Power commands."""
# :license: MIT, see LICENSE for more details.
import click
import SoftLayer
from SoftLayer.CLI import environment
from SoftLayer.CLI import exceptions
from SoftLayer.CLI import formatting
from SoftLayer.CLI import helpers
@click.command()
@click.argument('identifier')
@environment.pass_env
def power_off(env, identifier):
"""Power off an active server."""
mgr = SoftLayer.HardwareManager(env.client)
hw_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'hardware')
if not (env.skip_confirmations or
formatting.confirm('This will power off the server with id %s '
'Continue?' % hw_id)):
raise exceptions.CLIAbort('Aborted.')
env.client['Hardware_Server'].powerOff(id=hw_id)
@click.command()
@click.argument('identifier')
@click.option('--hard/--soft',
default=None,
help="Perform a hard or soft reboot")
@environment.pass_env
def reboot(env, identifier, hard):
"""Reboot an active server."""
hardware_server = env.client['Hardware_Server']
mgr = SoftLayer.HardwareManager(env.client)
hw_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'hardware')
if not (env.skip_confirmations or
formatting.confirm('This will power off the server with id %s. '
'Continue?' % hw_id)):
raise exceptions.CLIAbort('Aborted.')
if hard is True:
hardware_server.rebootHard(id=hw_id)
elif hard is False:
hardware_server.rebootSoft(id=hw_id)
else:
hardware_server.rebootDefault(id=hw_id)
@click.command()
@click.argument('identifier')
@environment.pass_env
def power_on(env, identifier):
"""Power on a server."""
mgr = SoftLayer.HardwareManager(env.client)
hw_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'hardware')
env.client['Hardware_Server'].powerOn(id=hw_id)
@click.command()
@click.argument('identifier')
@environment.pass_env
def power_cycle(env, identifier):
"""Power cycle a server."""
mgr = SoftLayer.HardwareManager(env.client)
hw_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'hardware')
if not (env.skip_confirmations or
formatting.confirm('This will power off the server with id %s. '
'Continue?' % hw_id)):
raise exceptions.CLIAbort('Aborted.')
env.client['Hardware_Server'].powerCycle(id=hw_id)
@click.command()
@click.argument('identifier')
@environment.pass_env
def rescue(env, identifier):
"""Reboot server into a rescue image."""
mgr = SoftLayer.HardwareManager(env.client)
hw_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'hardware')
if not (env.skip_confirmations or
formatting.confirm("This action will reboot this server. Continue?")):
raise exceptions.CLIAbort('Aborted')
env.client['Hardware_Server'].bootToRescueLayer(id=hw_id)
|
web30s/odoo-9.0c-20160402 | refs/heads/master | hello/templates/openerp/addons/board/__init__.py | 47 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import board
import controllers
|
linspector/linspector.multicore | refs/heads/master | linspector/config/layouts.py | 2 | """
Copyright (c) 2011-2013 "Johannes Findeisen and Rafael Timmerberg"
This file is part of Linspector (http://linspector.org).
Linspector 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 logging import getLogger
logger = getLogger(__name__)
class LayoutException(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return repr(self.msg)
class Layout(object):
def __init__(self, name, enabled=False, hostgroups=None):
self._name = name
self._enabled = enabled
if hostgroups is None or len(hostgroups) <= 0:
raise LayoutException("Layout: " + self._name + " without hostgroups is useless")
else:
self._hostgroups = hostgroups
def _to_config_dict(self, configDict):
me = {}
me["hostgroups"] = [hg.name for hg in self.get_hostgroups()]
me["enabled"] = self.is_enabled()
configDict["layouts"][self.get_name()] = me
for hostgroup in self.get_hostgroups():
hostgroup._to_config_dict(configDict)
def get_name(self):
return self._name
def is_enabled(self):
return self._enabled
def get_hostgroups(self):
return self._hostgroups
def __str__(self):
ret = "Layout: 'Name:" + str(self.name) + "', 'Enabled: " + str(self.enabled) + " "
for group in self.hostgroups:
ret += str(group)
return ret |
OpenPLi/enigma2 | refs/heads/develop | lib/python/Components/Converter/TemplatedMultiContent.py | 4 | from Components.Converter.StringList import StringList
class TemplatedMultiContent(StringList):
"""Turns a python tuple list into a multi-content list which can be used in a listbox renderer."""
def __init__(self, args):
StringList.__init__(self, args)
from enigma import BT_SCALE, RT_HALIGN_CENTER, RT_HALIGN_LEFT, RT_HALIGN_RIGHT, RT_VALIGN_BOTTOM, RT_VALIGN_CENTER, RT_VALIGN_TOP, RT_WRAP, eListboxPythonMultiContent, gFont
from skin import parseFont, getSkinFactor
from Components.MultiContent import MultiContentEntryPixmap, MultiContentEntryPixmapAlphaBlend, MultiContentEntryPixmapAlphaTest, MultiContentEntryProgress, MultiContentEntryProgressPixmap, MultiContentEntryText, MultiContentTemplateColor
f = getSkinFactor()
loc = locals()
del loc["self"] # Cleanup locals a bit.
del loc["args"]
self.active_style = None
self.template = eval(args, {}, loc)
assert "fonts" in self.template
assert "itemHeight" in self.template
assert "template" in self.template or "templates" in self.template
assert "template" in self.template or "default" in self.template["templates"] # We need to have a default template.
if "template" not in self.template: # Default template can be ["template"] or ["templates"]["default"].
self.template["template"] = self.template["templates"]["default"][1]
self.template["itemHeight"] = self.template["template"][0]
def changed(self, what):
if not self.content:
from enigma import eListboxPythonMultiContent
self.content = eListboxPythonMultiContent()
for index, font in enumerate(self.template["fonts"]): # Setup fonts (also given by source).
self.content.setFont(index, font)
if what[0] == self.CHANGED_SPECIFIC and what[1] == "style": # If only template changed, don't reload list.
pass
elif self.source:
self.content.setList(self.source.list)
self.setTemplate()
self.downstream_elements.changed(what)
def setTemplate(self):
if self.source:
style = self.source.style
if style == self.active_style:
return
templates = self.template.get("templates") # If skin defined "templates", that means that it defines multiple styles in a dict. template should still be a default.
template = self.template.get("template")
itemheight = self.template["itemHeight"]
selectionEnabled = self.template.get("selectionEnabled", True)
scrollbarMode = self.template.get("scrollbarMode", "showOnDemand")
if templates and style and style in templates: # If we have a custom style defined in the source, and different templates in the skin, look it up
template = templates[style][1]
itemheight = templates[style][0]
if len(templates[style]) > 2:
selectionEnabled = templates[style][2]
if len(templates[style]) > 3:
scrollbarMode = templates[style][3]
self.content.setTemplate(template)
self.content.setItemHeight(int(itemheight))
self.selectionEnabled = selectionEnabled
self.scrollbarMode = scrollbarMode
self.active_style = style
|
jhogan/coniugare | refs/heads/master | noun.py | 1 | first= 'first'
second='second'
third= 'third'
fourth='fourth'
fifth= 'fifth'
vowels=('a', 'e', 'i', 'o', 'u')
singular = 'singular'
plural = 'plural'
f='female'
m='male'
null=None
true=True
false=False
class noun:
<<<<<<< .mine
def __init__(self, nominative, genitive_singular, gender):
self._nominative = nominative
=======
def __init__(self, nominative_singular, genitive_singular, gender):
self._nominative_singular = nominative_singular
self._genitive_singular = genitive_singular
>>>>>>> .r1025
self._gender = gender
self._genitive_singular = genitive_singular
<<<<<<< .mine
def setgenitive_singular(self, v):
dashix = v.find('-');
if (dashix > 0):
suf = v[dashix+1:]
def nominative(self): return self._nominative
=======
def gender(self): return self._gender
>>>>>>> .r1025
def stem(self):
gen = self._genitive_singular
dashix = gen.find('-')
if dashix != -1:
nom = self.nominative(singular)
if nom[-1:] in vowels:
stem = nom[0:-1]
elif nom[-2:] == 'us':
stem = nom[0:-2]
return stem
else:
if gen[-2:] in ('ae', 'is', 'us', 'ei'):
return gen[0:-2]
elif gen[-1:] == 'i':
return gen[0:-1]
<<<<<<< .mine
=======
def genitive_suffix(self):
gen = self._genitive_singular
dashix = gen.find('-')
if gen[0:1] == '-':
return gen[1:]
else:
if gen[-2:] in ('ae', 'is', 'us', 'ei'):
return gen[-2:]
elif gen[-1:] == 'i':
return gen[-1:]
>>>>>>> .r1025
def nominative(self, number=null):
# TODO Neuters follow the 'double neuter rule'
# but this isn't explained in the book
if (number==null):
return (self.nominative(singular), \
self.nominative(plural))
<<<<<<< .mine
def declination(self):
gencase = self.genitive_singular
if gencase[0:1] != "-":
stemchg
=======
if number == singular:
return self._nominative_singular
else:
dec = self.declension()
stem = self.stem()
if dec == first: return stem + "ae"
if dec == second: return stem + "i"
if dec == third: return stem + "Es"
if dec == fourth: return stem + "ae"
if dec == fifth: return stem + "ae"
>>>>>>> .r1025
def genitive(self, number=null):
if (number==null):
return (self.genitive(singular), \
self.genitive(plural))
stem = self.stem()
if number == singular:
gen = self._genitive_singular
if gen[0:1] == '-':
return stem + self.genitive_suffix()
else:
return gen
else:
dec = self.declension()
if dec == first: return stem + 'Arum'
if dec == second: return stem + 'Orum'
if dec == third: return stem + 'um'
if dec == fourth: return stem + 'uum'
if dec == fifth: return stem + 'Erum'
def dative(self, number=null):
if (number==null):
return (self.dative(singular), \
self.dative(plural))
dec = self.declension()
stem = self.stem()
if number == singular:
if dec == first: return stem + 'ae'
if dec == second: return stem + 'O'
if dec == third: return stem + 'I'
if dec == fourth: return stem + 'uI'
if dec == fifth: return stem + 'eI'
if number == plural:
if dec == first: return stem + 'Is'
if dec == second: return stem + 'Is'
if dec == third: return stem + 'ibus'
if dec == fourth: return stem + 'ibus'
if dec == fifth: return stem + 'Ebus'
def accusative(self, number=null):
if (number==null):
return (self.accusative(singular), \
self.accusative(plural))
dec = self.declension()
stem = self.stem()
if number == singular:
if dec == first: return stem + 'am'
if dec == second: return stem + 'um'
if dec == third: return stem + 'em'
if dec == fourth: return stem + 'um'
if dec == fifth: return stem + 'em'
if number == plural:
if dec == first: return stem + 'As'
if dec == second: return stem + 'Os'
if dec == third: return stem + 'Es'
if dec == fourth: return stem + 'Us'
if dec == fifth: return stem + 'Es'
def ablative(self, number=null):
if (number==null):
return (self.ablative(singular), \
self.ablative(plural))
dec = self.declension()
stem = self.stem()
if number == singular:
if dec == first: return stem + 'A'
if dec == second: return stem + 'O'
if dec == third: return stem + 'e'
if dec == fourth: return stem + 'u'
if dec == fifth: return stem + 'E'
if number == plural:
if dec == first: return stem + 'Is'
if dec == second: return stem + 'Is'
if dec == third: return stem + 'ibus'
if dec == fourth: return stem + 'Us'
if dec == fifth: return stem + 'Ebus'
def declension(self):
suffix = self.genitive_suffix()
if suffix == "ae": return first
if suffix == "i": return second
if suffix == "is": return third
if suffix == "us": return fourth
if suffix == "Ei": return fifth
def gender_acronym(self):
if self._gender == f: return 'f.'
if self._gender == m: return 'm.'
def str(self):
return self.nominative(singular) + ' ' + \
self._genitive_singular + ' ' + \
self.gender_acronym()
n = noun('ala', '-ae', m)
print n.str()
print "\nDeclension: %s\n" % n.declension()
print "Case Singular Plural"
print "Nominative %s %s" % n.nominative()
print "Genitive %s %s" % n.genitive()
print "Dative %s %s" % n.dative()
print "Accusative %s %s" % n.accusative()
print "Ablative %s %s" % n.ablative()
|
RadioFreeAsia/RDacity | refs/heads/master | lib-src/lv2/lilv/waflib/Tools/compiler_c.py | 343 | #! /usr/bin/env python
# encoding: utf-8
# WARNING! Do not edit! http://waf.googlecode.com/git/docs/wafbook/single.html#_obtaining_the_waf_file
import os,sys,imp,types
from waflib.Tools import ccroot
from waflib import Utils,Configure
from waflib.Logs import debug
c_compiler={'win32':['msvc','gcc'],'cygwin':['gcc'],'darwin':['gcc'],'aix':['xlc','gcc'],'linux':['gcc','icc'],'sunos':['suncc','gcc'],'irix':['gcc','irixcc'],'hpux':['gcc'],'gnu':['gcc'],'java':['gcc','msvc','icc'],'default':['gcc'],}
def configure(conf):
try:test_for_compiler=conf.options.check_c_compiler
except AttributeError:conf.fatal("Add options(opt): opt.load('compiler_c')")
for compiler in test_for_compiler.split():
conf.env.stash()
conf.start_msg('Checking for %r (c compiler)'%compiler)
try:
conf.load(compiler)
except conf.errors.ConfigurationError ,e:
conf.env.revert()
conf.end_msg(False)
debug('compiler_c: %r'%e)
else:
if conf.env['CC']:
conf.end_msg(conf.env.get_flat('CC'))
conf.env['COMPILER_CC']=compiler
break
conf.end_msg(False)
else:
conf.fatal('could not configure a c compiler!')
def options(opt):
opt.load_special_tools('c_*.py',ban=['c_dumbpreproc.py'])
global c_compiler
build_platform=Utils.unversioned_sys_platform()
possible_compiler_list=c_compiler[build_platform in c_compiler and build_platform or'default']
test_for_compiler=' '.join(possible_compiler_list)
cc_compiler_opts=opt.add_option_group("C Compiler Options")
cc_compiler_opts.add_option('--check-c-compiler',default="%s"%test_for_compiler,help='On this platform (%s) the following C-Compiler will be checked by default: "%s"'%(build_platform,test_for_compiler),dest="check_c_compiler")
for x in test_for_compiler.split():
opt.load('%s'%x)
|
DaTrollMon/pyNES | refs/heads/0.1.x | pynes/examples/movingsprite.py | 28 | import pynes
from pynes.bitbag import *
if __name__ == "__main__":
pynes.press_start()
exit()
palette = [ 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
0x0F, 48, 49, 50, 51, 53, 54, 55, 56, 57, 58, 59,
60, 61, 62, 63 ]
chr_asset = import_chr('player.chr')
sprite = define_sprite(128, 128, 0, 3)
def reset():
global palette, sprite
wait_vblank()
clearmem()
wait_vblank()
load_palette(palette)
load_sprite(sprite, 0)
def joypad1_up():
get_sprite(0).y -= 1
def joypad1_down():
get_sprite(0).y += 1
def joypad1_left():
get_sprite(0).x -=1
def joypad1_right():
get_sprite(0).x +=1
|
bally12345/enigma2 | refs/heads/master | lib/python/Screens/NetworkSetup.py | 1 | from Screens.Screen import Screen
from Screens.MessageBox import MessageBox
from Screens.InputBox import InputBox
from Screens.Standby import *
from Screens.VirtualKeyBoard import VirtualKeyBoard
from Screens.HelpMenu import HelpableScreen
from Components.About import about
from Components.Console import Console
from Components.Network import iNetwork
from Components.Sources.StaticText import StaticText
from Components.Sources.Boolean import Boolean
from Components.Sources.List import List
from Components.Label import Label,MultiColorLabel
from Components.ScrollLabel import ScrollLabel
from Components.Pixmap import Pixmap,MultiPixmap
from Components.MenuList import MenuList
from Components.config import config, ConfigSubsection, ConfigYesNo, ConfigIP, NoSave, ConfigText, ConfigPassword, ConfigSelection, getConfigListEntry, ConfigNothing, ConfigNumber, ConfigLocations, NoSave
from Components.ConfigList import ConfigListScreen
from Components.PluginComponent import plugins
from Components.MultiContent import MultiContentEntryText, MultiContentEntryPixmapAlphaTest
from Components.FileList import MultiFileSelectList
from Components.ActionMap import ActionMap, NumberActionMap, HelpableActionMap
from Tools.Directories import fileExists, resolveFilename, SCOPE_PLUGINS, SCOPE_CURRENT_SKIN
from Tools.LoadPixmap import LoadPixmap
from Plugins.Plugin import PluginDescriptor
from enigma import eTimer, ePoint, eSize, RT_HALIGN_LEFT, eListboxPythonMultiContent, gFont
from os import path as os_path, remove, symlink, unlink, rename, chmod
from shutil import move
from re import compile as re_compile, search as re_search
import time
class NetworkAdapterSelection(Screen,HelpableScreen):
def __init__(self, session):
Screen.__init__(self, session)
HelpableScreen.__init__(self)
Screen.setTitle(self, _("Network Setup"))
self.wlan_errortext = _("No working wireless network adapter found.\nPlease verify that you have attached a compatible WLAN device and your network is configured correctly.")
self.lan_errortext = _("No working local network adapter found.\nPlease verify that you have attached a network cable and your network is configured correctly.")
self.oktext = _("Press OK on your remote control to continue.")
self.edittext = _("Press OK to edit the settings.")
self.defaulttext = _("Press yellow to set this interface as default interface.")
self.restartLanRef = None
self["key_red"] = StaticText(_("Close"))
self["key_green"] = StaticText(_("Select"))
self["key_yellow"] = StaticText("")
self["key_blue"] = StaticText("")
self["introduction"] = StaticText(self.edittext)
self["OkCancelActions"] = HelpableActionMap(self, "OkCancelActions",
{
"cancel": (self.close, _("exit network interface list")),
"ok": (self.okbuttonClick, _("select interface")),
})
self["ColorActions"] = HelpableActionMap(self, "ColorActions",
{
"red": (self.close, _("exit network interface list")),
"green": (self.okbuttonClick, _("select interface")),
"blue": (self.openNetworkWizard, _("Use the Networkwizard to configure selected network adapter")),
})
self["DefaultInterfaceAction"] = HelpableActionMap(self, "ColorActions",
{
"yellow": (self.setDefaultInterface, [_("Set interface as default Interface"),_("* Only available if more than one interface is active.")] ),
})
self.adapters = [(iNetwork.getFriendlyAdapterName(x),x) for x in iNetwork.getAdapterList()]
if not self.adapters:
self.adapters = [(iNetwork.getFriendlyAdapterName(x),x) for x in iNetwork.getConfiguredAdapters()]
if len(self.adapters) == 0:
self.adapters = [(iNetwork.getFriendlyAdapterName(x),x) for x in iNetwork.getInstalledAdapters()]
self.onChangedEntry = [ ]
self.list = []
self["list"] = List(self.list)
self.updateList()
if not self.selectionChanged in self["list"].onSelectionChanged:
self["list"].onSelectionChanged.append(self.selectionChanged)
if len(self.adapters) == 1:
self.onFirstExecBegin.append(self.okbuttonClick)
self.onClose.append(self.cleanup)
def createSummary(self):
from Screens.PluginBrowser import PluginBrowserSummary
return PluginBrowserSummary
def selectionChanged(self):
item = self["list"].getCurrent()
if item:
name = item[0]
desc = item[1]
else:
name = ""
desc = ""
for cb in self.onChangedEntry:
cb(name, desc)
def buildInterfaceList(self,iface,name,default,active ):
divpng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/div-h.png"))
defaultpng = None
activepng = None
description = None
interfacepng = None
if not iNetwork.isWirelessInterface(iface):
if active is True:
interfacepng = LoadPixmap(resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/network_wired-active.png"))
elif active is False:
interfacepng = LoadPixmap(resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/network_wired-inactive.png"))
else:
interfacepng = LoadPixmap(resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/network_wired.png"))
elif iNetwork.isWirelessInterface(iface):
if active is True:
interfacepng = LoadPixmap(resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/network_wireless-active.png"))
elif active is False:
interfacepng = LoadPixmap(resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/network_wireless-inactive.png"))
else:
interfacepng = LoadPixmap(resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/network_wireless.png"))
num_configured_if = len(iNetwork.getConfiguredAdapters())
if num_configured_if >= 2:
if default is True:
defaultpng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/buttons/button_blue.png"))
elif default is False:
defaultpng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/buttons/button_blue_off.png"))
if active is True:
activepng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/lock_on.png"))
elif active is False:
activepng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/lock_error.png"))
description = iNetwork.getFriendlyAdapterDescription(iface)
return((iface, name, description, interfacepng, defaultpng, activepng, divpng))
def updateList(self):
self.list = []
default_gw = None
num_configured_if = len(iNetwork.getConfiguredAdapters())
if num_configured_if >= 2:
self["key_yellow"].setText(_("Default"))
self["introduction"].setText(self.defaulttext)
self["DefaultInterfaceAction"].setEnabled(True)
else:
self["key_yellow"].setText("")
self["introduction"].setText(self.edittext)
self["DefaultInterfaceAction"].setEnabled(False)
if num_configured_if < 2 and os_path.exists("/etc/default_gw"):
unlink("/etc/default_gw")
if os_path.exists("/etc/default_gw"):
fp = file('/etc/default_gw', 'r')
result = fp.read()
fp.close()
default_gw = result
for x in self.adapters:
if x[1] == default_gw:
default_int = True
else:
default_int = False
if iNetwork.getAdapterAttribute(x[1], 'up') is True:
active_int = True
else:
active_int = False
self.list.append(self.buildInterfaceList(x[1],_(x[0]),default_int,active_int ))
if os_path.exists(resolveFilename(SCOPE_PLUGINS, "SystemPlugins/NetworkWizard/networkwizard.xml")):
self["key_blue"].setText(_("NetworkWizard"))
self["list"].setList(self.list)
def setDefaultInterface(self):
selection = self["list"].getCurrent()
num_if = len(self.list)
old_default_gw = None
num_configured_if = len(iNetwork.getConfiguredAdapters())
if os_path.exists("/etc/default_gw"):
fp = open('/etc/default_gw', 'r')
old_default_gw = fp.read()
fp.close()
if num_configured_if > 1 and (not old_default_gw or old_default_gw != selection[0]):
fp = open('/etc/default_gw', 'w+')
fp.write(selection[0])
fp.close()
self.restartLan()
elif old_default_gw and num_configured_if < 2:
unlink("/etc/default_gw")
self.restartLan()
def okbuttonClick(self):
selection = self["list"].getCurrent()
if selection is not None:
self.session.openWithCallback(self.AdapterSetupClosed, AdapterSetupConfiguration, selection[0])
def AdapterSetupClosed(self, *ret):
if len(self.adapters) == 1:
self.close()
else:
self.updateList()
def cleanup(self):
iNetwork.stopLinkStateConsole()
iNetwork.stopRestartConsole()
iNetwork.stopGetInterfacesConsole()
def restartLan(self):
iNetwork.restartNetwork(self.restartLanDataAvail)
self.restartLanRef = self.session.openWithCallback(self.restartfinishedCB, MessageBox, _("Please wait while we configure your network..."), type = MessageBox.TYPE_INFO, enable_input = False)
def restartLanDataAvail(self, data):
if data is True:
iNetwork.getInterfaces(self.getInterfacesDataAvail)
def getInterfacesDataAvail(self, data):
if data is True:
self.restartLanRef.close(True)
def restartfinishedCB(self,data):
if data is True:
self.updateList()
self.session.open(MessageBox, _("Finished configuring your network"), type = MessageBox.TYPE_INFO, timeout = 10, default = False)
def openNetworkWizard(self):
if os_path.exists(resolveFilename(SCOPE_PLUGINS, "SystemPlugins/NetworkWizard/networkwizard.xml")):
try:
from Plugins.SystemPlugins.NetworkWizard.NetworkWizard import NetworkWizard
except ImportError:
self.session.open(MessageBox, _("The NetworkWizard extension is not installed!\nPlease install it."), type = MessageBox.TYPE_INFO,timeout = 10 )
else:
selection = self["list"].getCurrent()
if selection is not None:
self.session.openWithCallback(self.AdapterSetupClosed, NetworkWizard, selection[0])
class NameserverSetup(Screen, ConfigListScreen, HelpableScreen):
def __init__(self, session):
Screen.__init__(self, session)
HelpableScreen.__init__(self)
Screen.setTitle(self, _("Nameserver settings"))
self.backupNameserverList = iNetwork.getNameserverList()[:]
print "backup-list:", self.backupNameserverList
self["key_red"] = StaticText(_("Cancel"))
self["key_green"] = StaticText(_("Add"))
self["key_yellow"] = StaticText(_("Delete"))
self["introduction"] = StaticText(_("Press OK to activate the settings."))
self.createConfig()
self["OkCancelActions"] = HelpableActionMap(self, "OkCancelActions",
{
"cancel": (self.cancel, _("exit nameserver configuration")),
"ok": (self.ok, _("activate current configuration")),
})
self["ColorActions"] = HelpableActionMap(self, "ColorActions",
{
"red": (self.cancel, _("exit nameserver configuration")),
"green": (self.add, _("add a nameserver entry")),
"yellow": (self.remove, _("remove a nameserver entry")),
})
self["actions"] = NumberActionMap(["SetupActions"],
{
"ok": self.ok,
}, -2)
self.list = []
ConfigListScreen.__init__(self, self.list)
self.createSetup()
def createConfig(self):
self.nameservers = iNetwork.getNameserverList()
self.nameserverEntries = [ NoSave(ConfigIP(default=nameserver)) for nameserver in self.nameservers]
def createSetup(self):
self.list = []
i = 1
for x in self.nameserverEntries:
self.list.append(getConfigListEntry(_("Nameserver %d") % (i), x))
i += 1
self["config"].list = self.list
self["config"].l.setList(self.list)
def ok(self):
iNetwork.clearNameservers()
for nameserver in self.nameserverEntries:
iNetwork.addNameserver(nameserver.value)
iNetwork.writeNameserverConfig()
self.close()
def run(self):
self.ok()
def cancel(self):
iNetwork.clearNameservers()
print "backup-list:", self.backupNameserverList
for nameserver in self.backupNameserverList:
iNetwork.addNameserver(nameserver)
self.close()
def add(self):
iNetwork.addNameserver([0,0,0,0])
self.createConfig()
self.createSetup()
def remove(self):
print "currentIndex:", self["config"].getCurrentIndex()
index = self["config"].getCurrentIndex()
if index < len(self.nameservers):
iNetwork.removeNameserver(self.nameservers[index])
self.createConfig()
self.createSetup()
class AdapterSetup(Screen, ConfigListScreen, HelpableScreen):
def __init__(self, session, networkinfo, essid=None):
Screen.__init__(self, session)
HelpableScreen.__init__(self)
Screen.setTitle(self, _("Adapter settings"))
self.session = session
if isinstance(networkinfo, (list, tuple)):
self.iface = networkinfo[0]
self.essid = networkinfo[1]
else:
self.iface = networkinfo
self.essid = essid
self.extended = None
self.applyConfigRef = None
self.finished_cb = None
self.oktext = _("Press OK on your remote control to continue.")
self.oldInterfaceState = iNetwork.getAdapterAttribute(self.iface, "up")
self.createConfig()
self["OkCancelActions"] = HelpableActionMap(self, "OkCancelActions",
{
"cancel": (self.keyCancel, _("exit network adapter configuration")),
"ok": (self.keySave, _("activate network adapter configuration")),
})
self["ColorActions"] = HelpableActionMap(self, "ColorActions",
{
"red": (self.keyCancel, _("exit network adapter configuration")),
"blue": (self.KeyBlue, _("open nameserver configuration")),
})
self["actions"] = NumberActionMap(["SetupActions"],
{
"ok": self.keySave,
}, -2)
self.list = []
ConfigListScreen.__init__(self, self.list,session = self.session)
self.createSetup()
self.onLayoutFinish.append(self.layoutFinished)
self.onClose.append(self.cleanup)
self["DNS1text"] = StaticText(_("Primary DNS"))
self["DNS2text"] = StaticText(_("Secondary DNS"))
self["DNS1"] = StaticText()
self["DNS2"] = StaticText()
self["introduction"] = StaticText(_("Current settings:"))
self["IPtext"] = StaticText(_("IP Address"))
self["Netmasktext"] = StaticText(_("Netmask"))
self["Gatewaytext"] = StaticText(_("Gateway"))
self["IP"] = StaticText()
self["Mask"] = StaticText()
self["Gateway"] = StaticText()
self["Adaptertext"] = StaticText(_("Network:"))
self["Adapter"] = StaticText()
self["introduction2"] = StaticText(_("Press OK to activate the settings."))
self["key_red"] = StaticText(_("Cancel"))
self["key_blue"] = StaticText(_("Edit DNS"))
self["VKeyIcon"] = Boolean(False)
self["HelpWindow"] = Pixmap()
self["HelpWindow"].hide()
def layoutFinished(self):
self["DNS1"].setText(self.primaryDNS.getText())
self["DNS2"].setText(self.secondaryDNS.getText())
if self.ipConfigEntry.getText() is not None:
if self.ipConfigEntry.getText() == "0.0.0.0":
self["IP"].setText(_("N/A"))
else:
self["IP"].setText(self.ipConfigEntry.getText())
else:
self["IP"].setText(_("N/A"))
if self.netmaskConfigEntry.getText() is not None:
if self.netmaskConfigEntry.getText() == "0.0.0.0":
self["Mask"].setText(_("N/A"))
else:
self["Mask"].setText(self.netmaskConfigEntry.getText())
else:
self["IP"].setText(_("N/A"))
if iNetwork.getAdapterAttribute(self.iface, "gateway"):
if self.gatewayConfigEntry.getText() == "0.0.0.0":
self["Gatewaytext"].setText(_("Gateway"))
self["Gateway"].setText(_("N/A"))
else:
self["Gatewaytext"].setText(_("Gateway"))
self["Gateway"].setText(self.gatewayConfigEntry.getText())
else:
self["Gateway"].setText("")
self["Gatewaytext"].setText("")
self["Adapter"].setText(iNetwork.getFriendlyAdapterName(self.iface))
def createConfig(self):
self.InterfaceEntry = None
self.dhcpEntry = None
self.gatewayEntry = None
self.hiddenSSID = None
self.wlanSSID = None
self.encryption = None
self.encryptionType = None
self.encryptionKey = None
self.encryptionlist = None
self.weplist = None
self.wsconfig = None
self.default = None
if iNetwork.isWirelessInterface(self.iface):
from Plugins.SystemPlugins.WirelessLan.Wlan import wpaSupplicant
self.ws = wpaSupplicant()
self.encryptionlist = []
self.encryptionlist.append(("Unencrypted", _("Unencrypted")))
self.encryptionlist.append(("WEP", _("WEP")))
self.encryptionlist.append(("WPA", _("WPA")))
self.encryptionlist.append(("WPA/WPA2", _("WPA or WPA2")))
self.encryptionlist.append(("WPA2", _("WPA2")))
self.weplist = []
self.weplist.append("ASCII")
self.weplist.append("HEX")
self.wsconfig = self.ws.loadConfig(self.iface)
if self.essid is None:
self.essid = self.wsconfig['ssid']
config.plugins.wlan.hiddenessid = NoSave(ConfigYesNo(default = self.wsconfig['hiddenessid']))
config.plugins.wlan.essid = NoSave(ConfigText(default = self.essid, visible_width = 50, fixed_size = False))
config.plugins.wlan.encryption = NoSave(ConfigSelection(self.encryptionlist, default = self.wsconfig['encryption'] ))
config.plugins.wlan.wepkeytype = NoSave(ConfigSelection(self.weplist, default = self.wsconfig['wepkeytype'] ))
config.plugins.wlan.psk = NoSave(ConfigPassword(default = self.wsconfig['key'], visible_width = 50, fixed_size = False))
self.activateInterfaceEntry = NoSave(ConfigYesNo(default=iNetwork.getAdapterAttribute(self.iface, "up") or False))
self.dhcpConfigEntry = NoSave(ConfigYesNo(default=iNetwork.getAdapterAttribute(self.iface, "dhcp") or False))
self.ipConfigEntry = NoSave(ConfigIP(default=iNetwork.getAdapterAttribute(self.iface, "ip")) or [0,0,0,0])
self.netmaskConfigEntry = NoSave(ConfigIP(default=iNetwork.getAdapterAttribute(self.iface, "netmask") or [255,0,0,0]))
if iNetwork.getAdapterAttribute(self.iface, "gateway"):
self.dhcpdefault=True
else:
self.dhcpdefault=False
self.hasGatewayConfigEntry = NoSave(ConfigYesNo(default=self.dhcpdefault or False))
self.gatewayConfigEntry = NoSave(ConfigIP(default=iNetwork.getAdapterAttribute(self.iface, "gateway") or [0,0,0,0]))
nameserver = (iNetwork.getNameserverList() + [[0,0,0,0]] * 2)[0:2]
self.primaryDNS = NoSave(ConfigIP(default=nameserver[0]))
self.secondaryDNS = NoSave(ConfigIP(default=nameserver[1]))
def createSetup(self):
self.list = []
self.InterfaceEntry = getConfigListEntry(_("Use Interface"), self.activateInterfaceEntry)
self.list.append(self.InterfaceEntry)
if self.activateInterfaceEntry.value:
self.dhcpEntry = getConfigListEntry(_("Use DHCP"), self.dhcpConfigEntry)
self.list.append(self.dhcpEntry)
if not self.dhcpConfigEntry.value:
self.list.append(getConfigListEntry(_('IP Address'), self.ipConfigEntry))
self.list.append(getConfigListEntry(_('Netmask'), self.netmaskConfigEntry))
self.gatewayEntry = getConfigListEntry(_('Use a gateway'), self.hasGatewayConfigEntry)
self.list.append(self.gatewayEntry)
if self.hasGatewayConfigEntry.value:
self.list.append(getConfigListEntry(_('Gateway'), self.gatewayConfigEntry))
self.extended = None
self.configStrings = None
for p in plugins.getPlugins(PluginDescriptor.WHERE_NETWORKSETUP):
callFnc = p.__call__["ifaceSupported"](self.iface)
if callFnc is not None:
if p.__call__.has_key("WlanPluginEntry"): # internally used only for WLAN Plugin
self.extended = callFnc
if p.__call__.has_key("configStrings"):
self.configStrings = p.__call__["configStrings"]
self.hiddenSSID = getConfigListEntry(_("Hidden network"), config.plugins.wlan.hiddenessid)
self.list.append(self.hiddenSSID)
self.wlanSSID = getConfigListEntry(_("Networkname (SSID)"), config.plugins.wlan.essid)
self.list.append(self.wlanSSID)
self.encryption = getConfigListEntry(_("Encryption"), config.plugins.wlan.encryption)
self.list.append(self.encryption)
self.encryptionType = getConfigListEntry(_("Encryption Keytype"), config.plugins.wlan.wepkeytype)
self.encryptionKey = getConfigListEntry(_("Encryption Key"), config.plugins.wlan.psk)
if config.plugins.wlan.encryption.value != "Unencrypted":
if config.plugins.wlan.encryption.value == 'WEP':
self.list.append(self.encryptionType)
self.list.append(self.encryptionKey)
self["config"].list = self.list
self["config"].l.setList(self.list)
def KeyBlue(self):
self.session.openWithCallback(self.NameserverSetupClosed, NameserverSetup)
def newConfig(self):
if self["config"].getCurrent() == self.InterfaceEntry:
self.createSetup()
if self["config"].getCurrent() == self.dhcpEntry:
self.createSetup()
if self["config"].getCurrent() == self.gatewayEntry:
self.createSetup()
if iNetwork.isWirelessInterface(self.iface):
if self["config"].getCurrent() == self.encryption:
self.createSetup()
def keyLeft(self):
ConfigListScreen.keyLeft(self)
self.newConfig()
def keyRight(self):
ConfigListScreen.keyRight(self)
self.newConfig()
def keySave(self):
self.hideInputHelp()
if self["config"].isChanged():
self.session.openWithCallback(self.keySaveConfirm, MessageBox, (_("Are you sure you want to activate this network configuration?\n\n") + self.oktext ) )
else:
if self.finished_cb:
self.finished_cb()
else:
self.close('cancel')
def keySaveConfirm(self, ret = False):
if (ret == True):
num_configured_if = len(iNetwork.getConfiguredAdapters())
if num_configured_if >= 1:
if self.iface in iNetwork.getConfiguredAdapters():
self.applyConfig(True)
else:
self.session.openWithCallback(self.secondIfaceFoundCB, MessageBox, _("A second configured interface has been found.\n\nDo you want to disable the second network interface?"), default = True)
else:
self.applyConfig(True)
else:
self.keyCancel()
def secondIfaceFoundCB(self,data):
if data is False:
self.applyConfig(True)
else:
configuredInterfaces = iNetwork.getConfiguredAdapters()
for interface in configuredInterfaces:
if interface == self.iface:
continue
iNetwork.setAdapterAttribute(interface, "up", False)
iNetwork.deactivateInterface(configuredInterfaces,self.deactivateSecondInterfaceCB)
def deactivateSecondInterfaceCB(self, data):
if data is True:
self.applyConfig(True)
def applyConfig(self, ret = False):
if (ret == True):
self.applyConfigRef = None
iNetwork.setAdapterAttribute(self.iface, "up", self.activateInterfaceEntry.value)
iNetwork.setAdapterAttribute(self.iface, "dhcp", self.dhcpConfigEntry.value)
iNetwork.setAdapterAttribute(self.iface, "ip", self.ipConfigEntry.value)
iNetwork.setAdapterAttribute(self.iface, "netmask", self.netmaskConfigEntry.value)
if self.hasGatewayConfigEntry.value:
iNetwork.setAdapterAttribute(self.iface, "gateway", self.gatewayConfigEntry.value)
else:
iNetwork.removeAdapterAttribute(self.iface, "gateway")
if (self.extended is not None and self.configStrings is not None):
iNetwork.setAdapterAttribute(self.iface, "configStrings", self.configStrings(self.iface))
self.ws.writeConfig(self.iface)
if self.activateInterfaceEntry.value is False:
iNetwork.deactivateInterface(self.iface,self.deactivateInterfaceCB)
iNetwork.writeNetworkConfig()
self.applyConfigRef = self.session.openWithCallback(self.applyConfigfinishedCB, MessageBox, _("Please wait for activation of your network configuration..."), type = MessageBox.TYPE_INFO, enable_input = False)
else:
if self.oldInterfaceState is False:
iNetwork.activateInterface(self.iface,self.deactivateInterfaceCB)
else:
iNetwork.deactivateInterface(self.iface,self.activateInterfaceCB)
iNetwork.writeNetworkConfig()
self.applyConfigRef = self.session.openWithCallback(self.applyConfigfinishedCB, MessageBox, _("Please wait for activation of your network configuration..."), type = MessageBox.TYPE_INFO, enable_input = False)
else:
self.keyCancel()
def deactivateInterfaceCB(self, data):
if data is True:
self.applyConfigDataAvail(True)
def activateInterfaceCB(self, data):
if data is True:
iNetwork.activateInterface(self.iface,self.applyConfigDataAvail)
def applyConfigDataAvail(self, data):
if data is True:
iNetwork.getInterfaces(self.getInterfacesDataAvail)
def getInterfacesDataAvail(self, data):
if data is True:
self.applyConfigRef.close(True)
def applyConfigfinishedCB(self,data):
if data is True:
if self.finished_cb:
self.session.openWithCallback(lambda x : self.finished_cb(), MessageBox, _("Your network configuration has been activated."), type = MessageBox.TYPE_INFO, timeout = 10)
else:
self.session.openWithCallback(self.ConfigfinishedCB, MessageBox, _("Your network configuration has been activated."), type = MessageBox.TYPE_INFO, timeout = 10)
def ConfigfinishedCB(self,data):
if data is not None:
if data is True:
self.close('ok')
def keyCancelConfirm(self, result):
if not result:
return
if self.oldInterfaceState is False:
iNetwork.deactivateInterface(self.iface,self.keyCancelCB)
else:
self.close('cancel')
def keyCancel(self):
self.hideInputHelp()
if self["config"].isChanged():
self.session.openWithCallback(self.keyCancelConfirm, MessageBox, _("Really close without saving settings?"))
else:
self.close('cancel')
def keyCancelCB(self,data):
if data is not None:
if data is True:
self.close('cancel')
def runAsync(self, finished_cb):
self.finished_cb = finished_cb
self.keySave()
def NameserverSetupClosed(self, *ret):
iNetwork.loadNameserverConfig()
nameserver = (iNetwork.getNameserverList() + [[0,0,0,0]] * 2)[0:2]
self.primaryDNS = NoSave(ConfigIP(default=nameserver[0]))
self.secondaryDNS = NoSave(ConfigIP(default=nameserver[1]))
self.createSetup()
self.layoutFinished()
def cleanup(self):
iNetwork.stopLinkStateConsole()
def hideInputHelp(self):
current = self["config"].getCurrent()
if current == self.wlanSSID:
if current[1].help_window.instance is not None:
current[1].help_window.instance.hide()
elif current == self.encryptionKey and config.plugins.wlan.encryption.value is not "Unencrypted":
if current[1].help_window.instance is not None:
current[1].help_window.instance.hide()
class AdapterSetupConfiguration(Screen, HelpableScreen):
def __init__(self, session,iface):
Screen.__init__(self, session)
HelpableScreen.__init__(self)
Screen.setTitle(self, _("Network Setup"))
self.session = session
self.iface = iface
self.restartLanRef = None
self.LinkState = None
self.onChangedEntry = [ ]
self.mainmenu = ""
self["menulist"] = MenuList(self.mainmenu)
self["key_red"] = StaticText(_("Close"))
self["description"] = StaticText()
self["IFtext"] = StaticText()
self["IF"] = StaticText()
self["Statustext"] = StaticText()
self["statuspic"] = MultiPixmap()
self["statuspic"].hide()
self.oktext = _("Press OK on your remote control to continue.")
self.reboottext = _("Your STB will restart after pressing OK on your remote control.")
self.errortext = _("No working wireless network interface found.\n Please verify that you have attached a compatible WLAN device or enable your local network interface.")
self.missingwlanplugintxt = _("The wireless LAN plugin is not installed!\nPlease install it.")
self["WizardActions"] = HelpableActionMap(self, "WizardActions",
{
"up": (self.up, _("move up to previous entry")),
"down": (self.down, _("move down to next entry")),
"left": (self.left, _("move up to first entry")),
"right": (self.right, _("move down to last entry")),
})
self["OkCancelActions"] = HelpableActionMap(self, "OkCancelActions",
{
"cancel": (self.close, _("exit networkadapter setup menu")),
"ok": (self.ok, _("select menu entry")),
})
self["ColorActions"] = HelpableActionMap(self, "ColorActions",
{
"red": (self.close, _("exit networkadapter setup menu")),
})
self["actions"] = NumberActionMap(["WizardActions","ShortcutActions"],
{
"ok": self.ok,
"back": self.close,
"up": self.up,
"down": self.down,
"red": self.close,
"left": self.left,
"right": self.right,
}, -2)
self.updateStatusbar()
self.onClose.append(self.cleanup)
if not self.selectionChanged in self["menulist"].onSelectionChanged:
self["menulist"].onSelectionChanged.append(self.selectionChanged)
self.selectionChanged()
def createSummary(self):
from Screens.PluginBrowser import PluginBrowserSummary
return PluginBrowserSummary
def selectionChanged(self):
if self["menulist"].getCurrent()[1] == 'edit':
self["description"].setText(_("Edit the network configuration of your STB_BOX.\n" ) + self.oktext )
if self["menulist"].getCurrent()[1] == 'test':
self["description"].setText(_("Test the network configuration of your STB_BOX.\n" ) + self.oktext )
if self["menulist"].getCurrent()[1] == 'dns':
self["description"].setText(_("Edit the Nameserver configuration of your STB_BOX.\n" ) + self.oktext )
if self["menulist"].getCurrent()[1] == 'scanwlan':
self["description"].setText(_("Scan your network for wireless access points and connect to them using your selected wireless device.\n" ) + self.oktext )
if self["menulist"].getCurrent()[1] == 'wlanstatus':
self["description"].setText(_("Shows the state of your wireless LAN connection.\n" ) + self.oktext )
if self["menulist"].getCurrent()[1] == 'lanrestart':
self["description"].setText(_("Restart your network connection and interfaces.\n" ) + self.oktext )
if self["menulist"].getCurrent()[1] == 'openwizard':
self["description"].setText(_("Use the Networkwizard to configure your Network\n" ) + self.oktext )
if self["menulist"].getCurrent()[1][0] == 'extendedSetup':
self["description"].setText(_(self["menulist"].getCurrent()[1][1]) + self.oktext )
item = self["menulist"].getCurrent()
if item:
name = str(self["menulist"].getCurrent()[0])
desc = self["description"].text
else:
name = ""
desc = ""
for cb in self.onChangedEntry:
cb(name, desc)
def queryWirelessDevice(self,iface):
try:
from pythonwifi.iwlibs import Wireless
import errno
except ImportError:
return False
else:
try:
ifobj = Wireless(iface) # a Wireless NIC Object
wlanresponse = ifobj.getAPaddr()
except IOError, (error_no, error_str):
if error_no in (errno.EOPNOTSUPP, errno.ENODEV, errno.EPERM):
return False
else:
print "error: ",error_no,error_str
return True
else:
return True
def ok(self):
self.cleanup()
if self["menulist"].getCurrent()[1] == 'edit':
if iNetwork.isWirelessInterface(self.iface):
try:
from Plugins.SystemPlugins.WirelessLan.plugin import WlanScan
except ImportError:
self.session.open(MessageBox, self.missingwlanplugintxt, type = MessageBox.TYPE_INFO,timeout = 10 )
else:
if self.queryWirelessDevice(self.iface):
self.session.openWithCallback(self.AdapterSetupClosed, AdapterSetup,self.iface)
else:
self.showErrorMessage() # Display Wlan not available Message
else:
self.session.openWithCallback(self.AdapterSetupClosed, AdapterSetup,self.iface)
if self["menulist"].getCurrent()[1] == 'test':
self.session.open(NetworkAdapterTest,self.iface)
if self["menulist"].getCurrent()[1] == 'dns':
self.session.open(NameserverSetup)
if self["menulist"].getCurrent()[1] == 'scanwlan':
try:
from Plugins.SystemPlugins.WirelessLan.plugin import WlanScan
except ImportError:
self.session.open(MessageBox, self.missingwlanplugintxt, type = MessageBox.TYPE_INFO,timeout = 10 )
else:
if self.queryWirelessDevice(self.iface):
self.session.openWithCallback(self.WlanScanClosed, WlanScan, self.iface)
else:
self.showErrorMessage() # Display Wlan not available Message
if self["menulist"].getCurrent()[1] == 'wlanstatus':
try:
from Plugins.SystemPlugins.WirelessLan.plugin import WlanStatus
except ImportError:
self.session.open(MessageBox, self.missingwlanplugintxt, type = MessageBox.TYPE_INFO,timeout = 10 )
else:
if self.queryWirelessDevice(self.iface):
self.session.openWithCallback(self.WlanStatusClosed, WlanStatus,self.iface)
else:
self.showErrorMessage() # Display Wlan not available Message
if self["menulist"].getCurrent()[1] == 'lanrestart':
self.session.openWithCallback(self.restartLan, MessageBox, (_("Are you sure you want to restart your network interfaces?\n\n") + self.oktext ) )
if self["menulist"].getCurrent()[1] == 'openwizard':
from Plugins.SystemPlugins.NetworkWizard.NetworkWizard import NetworkWizard
self.session.openWithCallback(self.AdapterSetupClosed, NetworkWizard, self.iface)
if self["menulist"].getCurrent()[1][0] == 'extendedSetup':
self.extended = self["menulist"].getCurrent()[1][2]
self.extended(self.session, self.iface)
def up(self):
self["menulist"].up()
def down(self):
self["menulist"].down()
def left(self):
self["menulist"].pageUp()
def right(self):
self["menulist"].pageDown()
def updateStatusbar(self, data = None):
self.mainmenu = self.genMainMenu()
self["menulist"].l.setList(self.mainmenu)
self["IFtext"].setText(_("Network:"))
self["IF"].setText(iNetwork.getFriendlyAdapterName(self.iface))
self["Statustext"].setText(_("Link:"))
if iNetwork.isWirelessInterface(self.iface):
try:
from Plugins.SystemPlugins.WirelessLan.Wlan import iStatus
except:
self["statuspic"].setPixmapNum(1)
self["statuspic"].show()
else:
iStatus.getDataForInterface(self.iface,self.getInfoCB)
else:
iNetwork.getLinkState(self.iface,self.dataAvail)
def doNothing(self):
pass
def genMainMenu(self):
menu = []
menu.append((_("Adapter settings"), "edit"))
menu.append((_("Nameserver settings"), "dns"))
menu.append((_("Network test"), "test"))
menu.append((_("Restart network"), "lanrestart"))
self.extended = None
self.extendedSetup = None
for p in plugins.getPlugins(PluginDescriptor.WHERE_NETWORKSETUP):
callFnc = p.__call__["ifaceSupported"](self.iface)
if callFnc is not None:
self.extended = callFnc
if p.__call__.has_key("WlanPluginEntry"): # internally used only for WLAN Plugin
menu.append((_("Scan Wireless Networks"), "scanwlan"))
if iNetwork.getAdapterAttribute(self.iface, "up"):
menu.append((_("Show WLAN Status"), "wlanstatus"))
else:
if p.__call__.has_key("menuEntryName"):
menuEntryName = p.__call__["menuEntryName"](self.iface)
else:
menuEntryName = _('Extended Setup...')
if p.__call__.has_key("menuEntryDescription"):
menuEntryDescription = p.__call__["menuEntryDescription"](self.iface)
else:
menuEntryDescription = _('Extended Networksetup Plugin...')
self.extendedSetup = ('extendedSetup',menuEntryDescription, self.extended)
menu.append((menuEntryName,self.extendedSetup))
if os_path.exists(resolveFilename(SCOPE_PLUGINS, "SystemPlugins/NetworkWizard/networkwizard.xml")):
menu.append((_("NetworkWizard"), "openwizard"))
return menu
def AdapterSetupClosed(self, *ret):
if ret is not None and len(ret):
if ret[0] == 'ok' and (iNetwork.isWirelessInterface(self.iface) and iNetwork.getAdapterAttribute(self.iface, "up") is True):
try:
from Plugins.SystemPlugins.WirelessLan.plugin import WlanStatus
except ImportError:
self.session.open(MessageBox, self.missingwlanplugintxt, type = MessageBox.TYPE_INFO,timeout = 10 )
else:
if self.queryWirelessDevice(self.iface):
self.session.openWithCallback(self.WlanStatusClosed, WlanStatus,self.iface)
else:
self.showErrorMessage() # Display Wlan not available Message
else:
self.updateStatusbar()
else:
self.updateStatusbar()
def WlanStatusClosed(self, *ret):
if ret is not None and len(ret):
from Plugins.SystemPlugins.WirelessLan.Wlan import iStatus
iStatus.stopWlanConsole()
self.updateStatusbar()
def WlanScanClosed(self,*ret):
if ret[0] is not None:
self.session.openWithCallback(self.AdapterSetupClosed, AdapterSetup, self.iface,ret[0])
else:
from Plugins.SystemPlugins.WirelessLan.Wlan import iStatus
iStatus.stopWlanConsole()
self.updateStatusbar()
def restartLan(self, ret = False):
if (ret == True):
iNetwork.restartNetwork(self.restartLanDataAvail)
self.restartLanRef = self.session.openWithCallback(self.restartfinishedCB, MessageBox, _("Please wait while your network is restarting..."), type = MessageBox.TYPE_INFO, enable_input = False)
def restartLanDataAvail(self, data):
if data is True:
iNetwork.getInterfaces(self.getInterfacesDataAvail)
def getInterfacesDataAvail(self, data):
if data is True:
self.restartLanRef.close(True)
def restartfinishedCB(self,data):
if data is True:
self.updateStatusbar()
self.session.open(MessageBox, _("Finished restarting your network"), type = MessageBox.TYPE_INFO, timeout = 10, default = False)
def dataAvail(self,data):
self.LinkState = None
for line in data.splitlines():
line = line.strip()
if 'Link detected:' in line:
if "yes" in line:
self.LinkState = True
else:
self.LinkState = False
if self.LinkState == True:
iNetwork.checkNetworkState(self.checkNetworkCB)
else:
self["statuspic"].setPixmapNum(1)
self["statuspic"].show()
def showErrorMessage(self):
self.session.open(MessageBox, self.errortext, type = MessageBox.TYPE_INFO,timeout = 10 )
def cleanup(self):
iNetwork.stopLinkStateConsole()
iNetwork.stopDeactivateInterfaceConsole()
iNetwork.stopActivateInterfaceConsole()
iNetwork.stopPingConsole()
try:
from Plugins.SystemPlugins.WirelessLan.Wlan import iStatus
except ImportError:
pass
else:
iStatus.stopWlanConsole()
def getInfoCB(self,data,status):
self.LinkState = None
if data is not None:
if data is True:
if status is not None:
if status[self.iface]["essid"] == "off" or status[self.iface]["accesspoint"] == "Not-Associated" or status[self.iface]["accesspoint"] == False:
self.LinkState = False
self["statuspic"].setPixmapNum(1)
self["statuspic"].show()
else:
self.LinkState = True
iNetwork.checkNetworkState(self.checkNetworkCB)
def checkNetworkCB(self,data):
if iNetwork.getAdapterAttribute(self.iface, "up") is True:
if self.LinkState is True:
if data <= 2:
self["statuspic"].setPixmapNum(0)
else:
self["statuspic"].setPixmapNum(1)
self["statuspic"].show()
else:
self["statuspic"].setPixmapNum(1)
self["statuspic"].show()
else:
self["statuspic"].setPixmapNum(1)
self["statuspic"].show()
class NetworkAdapterTest(Screen):
def __init__(self, session,iface):
Screen.__init__(self, session)
Screen.setTitle(self, _("Network Test"))
self.iface = iface
self.oldInterfaceState = iNetwork.getAdapterAttribute(self.iface, "up")
self.setLabels()
self.onClose.append(self.cleanup)
self.onHide.append(self.cleanup)
self["updown_actions"] = NumberActionMap(["WizardActions","ShortcutActions"],
{
"ok": self.KeyOK,
"blue": self.KeyOK,
"up": lambda: self.updownhandler('up'),
"down": lambda: self.updownhandler('down'),
}, -2)
self["shortcuts"] = ActionMap(["ShortcutActions","WizardActions"],
{
"red": self.cancel,
"back": self.cancel,
}, -2)
self["infoshortcuts"] = ActionMap(["ShortcutActions","WizardActions"],
{
"red": self.closeInfo,
"back": self.closeInfo,
}, -2)
self["shortcutsgreen"] = ActionMap(["ShortcutActions"],
{
"green": self.KeyGreen,
}, -2)
self["shortcutsgreen_restart"] = ActionMap(["ShortcutActions"],
{
"green": self.KeyGreenRestart,
}, -2)
self["shortcutsyellow"] = ActionMap(["ShortcutActions"],
{
"yellow": self.KeyYellow,
}, -2)
self["shortcutsgreen_restart"].setEnabled(False)
self["updown_actions"].setEnabled(False)
self["infoshortcuts"].setEnabled(False)
self.onClose.append(self.delTimer)
self.onLayoutFinish.append(self.layoutFinished)
self.steptimer = False
self.nextstep = 0
self.activebutton = 0
self.nextStepTimer = eTimer()
self.nextStepTimer.callback.append(self.nextStepTimerFire)
def cancel(self):
if self.oldInterfaceState is False:
iNetwork.setAdapterAttribute(self.iface, "up", self.oldInterfaceState)
iNetwork.deactivateInterface(self.iface)
self.close()
def closeInfo(self):
self["shortcuts"].setEnabled(True)
self["infoshortcuts"].setEnabled(False)
self["InfoText"].hide()
self["InfoTextBorder"].hide()
self["key_red"].setText(_("Close"))
def delTimer(self):
del self.steptimer
del self.nextStepTimer
def nextStepTimerFire(self):
self.nextStepTimer.stop()
self.steptimer = False
self.runTest()
def updownhandler(self,direction):
if direction == 'up':
if self.activebutton >=2:
self.activebutton -= 1
else:
self.activebutton = 6
self.setActiveButton(self.activebutton)
if direction == 'down':
if self.activebutton <=5:
self.activebutton += 1
else:
self.activebutton = 1
self.setActiveButton(self.activebutton)
def setActiveButton(self,button):
if button == 1:
self["EditSettingsButton"].setPixmapNum(0)
self["EditSettings_Text"].setForegroundColorNum(0)
self["NetworkInfo"].setPixmapNum(0)
self["NetworkInfo_Text"].setForegroundColorNum(1)
self["AdapterInfo"].setPixmapNum(1) # active
self["AdapterInfo_Text"].setForegroundColorNum(2) # active
if button == 2:
self["AdapterInfo_Text"].setForegroundColorNum(1)
self["AdapterInfo"].setPixmapNum(0)
self["DhcpInfo"].setPixmapNum(0)
self["DhcpInfo_Text"].setForegroundColorNum(1)
self["NetworkInfo"].setPixmapNum(1) # active
self["NetworkInfo_Text"].setForegroundColorNum(2) # active
if button == 3:
self["NetworkInfo"].setPixmapNum(0)
self["NetworkInfo_Text"].setForegroundColorNum(1)
self["IPInfo"].setPixmapNum(0)
self["IPInfo_Text"].setForegroundColorNum(1)
self["DhcpInfo"].setPixmapNum(1) # active
self["DhcpInfo_Text"].setForegroundColorNum(2) # active
if button == 4:
self["DhcpInfo"].setPixmapNum(0)
self["DhcpInfo_Text"].setForegroundColorNum(1)
self["DNSInfo"].setPixmapNum(0)
self["DNSInfo_Text"].setForegroundColorNum(1)
self["IPInfo"].setPixmapNum(1) # active
self["IPInfo_Text"].setForegroundColorNum(2) # active
if button == 5:
self["IPInfo"].setPixmapNum(0)
self["IPInfo_Text"].setForegroundColorNum(1)
self["EditSettingsButton"].setPixmapNum(0)
self["EditSettings_Text"].setForegroundColorNum(0)
self["DNSInfo"].setPixmapNum(1) # active
self["DNSInfo_Text"].setForegroundColorNum(2) # active
if button == 6:
self["DNSInfo"].setPixmapNum(0)
self["DNSInfo_Text"].setForegroundColorNum(1)
self["EditSettingsButton"].setPixmapNum(1) # active
self["EditSettings_Text"].setForegroundColorNum(2) # active
self["AdapterInfo"].setPixmapNum(0)
self["AdapterInfo_Text"].setForegroundColorNum(1)
def runTest(self):
next = self.nextstep
if next == 0:
self.doStep1()
elif next == 1:
self.doStep2()
elif next == 2:
self.doStep3()
elif next == 3:
self.doStep4()
elif next == 4:
self.doStep5()
elif next == 5:
self.doStep6()
self.nextstep += 1
def doStep1(self):
self.steptimer = True
self.nextStepTimer.start(300)
self["key_yellow"].setText(_("Stop test"))
def doStep2(self):
self["Adapter"].setText(iNetwork.getFriendlyAdapterName(self.iface))
self["Adapter"].setForegroundColorNum(2)
self["Adaptertext"].setForegroundColorNum(1)
self["AdapterInfo_Text"].setForegroundColorNum(1)
self["AdapterInfo_OK"].show()
self.steptimer = True
self.nextStepTimer.start(300)
def doStep3(self):
self["Networktext"].setForegroundColorNum(1)
self["Network"].setText(_("Please wait..."))
self.getLinkState(self.iface)
self["NetworkInfo_Text"].setForegroundColorNum(1)
self.steptimer = True
self.nextStepTimer.start(1000)
def doStep4(self):
self["Dhcptext"].setForegroundColorNum(1)
if iNetwork.getAdapterAttribute(self.iface, 'dhcp') is True:
self["Dhcp"].setForegroundColorNum(2)
self["Dhcp"].setText(_("enabled"))
self["DhcpInfo_Check"].setPixmapNum(0)
else:
self["Dhcp"].setForegroundColorNum(1)
self["Dhcp"].setText(_("disabled"))
self["DhcpInfo_Check"].setPixmapNum(1)
self["DhcpInfo_Check"].show()
self["DhcpInfo_Text"].setForegroundColorNum(1)
self.steptimer = True
self.nextStepTimer.start(1000)
def doStep5(self):
self["IPtext"].setForegroundColorNum(1)
self["IP"].setText(_("Please wait..."))
iNetwork.checkNetworkState(self.NetworkStatedataAvail)
def doStep6(self):
self.steptimer = False
self.nextStepTimer.stop()
self["DNStext"].setForegroundColorNum(1)
self["DNS"].setText(_("Please wait..."))
iNetwork.checkDNSLookup(self.DNSLookupdataAvail)
def KeyGreen(self):
self["shortcutsgreen"].setEnabled(False)
self["shortcutsyellow"].setEnabled(True)
self["updown_actions"].setEnabled(False)
self["key_yellow"].setText("")
self["key_green"].setText("")
self.steptimer = True
self.nextStepTimer.start(1000)
def KeyGreenRestart(self):
self.nextstep = 0
self.layoutFinished()
self["Adapter"].setText((""))
self["Network"].setText((""))
self["Dhcp"].setText((""))
self["IP"].setText((""))
self["DNS"].setText((""))
self["AdapterInfo_Text"].setForegroundColorNum(0)
self["NetworkInfo_Text"].setForegroundColorNum(0)
self["DhcpInfo_Text"].setForegroundColorNum(0)
self["IPInfo_Text"].setForegroundColorNum(0)
self["DNSInfo_Text"].setForegroundColorNum(0)
self["shortcutsgreen_restart"].setEnabled(False)
self["shortcutsgreen"].setEnabled(False)
self["shortcutsyellow"].setEnabled(True)
self["updown_actions"].setEnabled(False)
self["key_yellow"].setText("")
self["key_green"].setText("")
self.steptimer = True
self.nextStepTimer.start(1000)
def KeyOK(self):
self["infoshortcuts"].setEnabled(True)
self["shortcuts"].setEnabled(False)
if self.activebutton == 1: # Adapter Check
self["InfoText"].setText(_("This test detects your configured LAN-Adapter."))
self["InfoTextBorder"].show()
self["InfoText"].show()
self["key_red"].setText(_("Back"))
if self.activebutton == 2: #LAN Check
self["InfoText"].setText(_("This test checks whether a network cable is connected to your LAN-Adapter.\nIf you get a \"disconnected\" message:\n- verify that a network cable is attached\n- verify that the cable is not broken"))
self["InfoTextBorder"].show()
self["InfoText"].show()
self["key_red"].setText(_("Back"))
if self.activebutton == 3: #DHCP Check
self["InfoText"].setText(_("This test checks whether your LAN Adapter is set up for automatic IP Address configuration with DHCP.\nIf you get a \"disabled\" message:\n - then your LAN Adapter is configured for manual IP Setup\n- verify thay you have entered correct IP informations in the AdapterSetup dialog.\nIf you get an \"enabeld\" message:\n-verify that you have a configured and working DHCP Server in your network."))
self["InfoTextBorder"].show()
self["InfoText"].show()
self["key_red"].setText(_("Back"))
if self.activebutton == 4: # IP Check
self["InfoText"].setText(_("This test checks whether a valid IP Address is found for your LAN Adapter.\nIf you get a \"unconfirmed\" message:\n- no valid IP Address was found\n- please check your DHCP, cabling and adapter setup"))
self["InfoTextBorder"].show()
self["InfoText"].show()
self["key_red"].setText(_("Back"))
if self.activebutton == 5: # DNS Check
self["InfoText"].setText(_("This test checks for configured Nameservers.\nIf you get a \"unconfirmed\" message:\n- please check your DHCP, cabling and Adapter setup\n- if you configured your Nameservers manually please verify your entries in the \"Nameserver\" Configuration"))
self["InfoTextBorder"].show()
self["InfoText"].show()
self["key_red"].setText(_("Back"))
if self.activebutton == 6: # Edit Settings
self.session.open(AdapterSetup,self.iface)
def KeyYellow(self):
self.nextstep = 0
self["shortcutsgreen_restart"].setEnabled(True)
self["shortcutsgreen"].setEnabled(False)
self["shortcutsyellow"].setEnabled(False)
self["key_green"].setText(_("Restart test"))
self["key_yellow"].setText("")
self.steptimer = False
self.nextStepTimer.stop()
def layoutFinished(self):
self.setTitle(_("Network test: ") + iNetwork.getFriendlyAdapterName(self.iface) )
self["shortcutsyellow"].setEnabled(False)
self["AdapterInfo_OK"].hide()
self["NetworkInfo_Check"].hide()
self["DhcpInfo_Check"].hide()
self["IPInfo_Check"].hide()
self["DNSInfo_Check"].hide()
self["EditSettings_Text"].hide()
self["EditSettingsButton"].hide()
self["InfoText"].hide()
self["InfoTextBorder"].hide()
self["key_yellow"].setText("")
def setLabels(self):
self["Adaptertext"] = MultiColorLabel(_("LAN Adapter"))
self["Adapter"] = MultiColorLabel()
self["AdapterInfo"] = MultiPixmap()
self["AdapterInfo_Text"] = MultiColorLabel(_("Show Info"))
self["AdapterInfo_OK"] = Pixmap()
if self.iface in iNetwork.wlan_interfaces:
self["Networktext"] = MultiColorLabel(_("Wireless Network"))
else:
self["Networktext"] = MultiColorLabel(_("Local Network"))
self["Network"] = MultiColorLabel()
self["NetworkInfo"] = MultiPixmap()
self["NetworkInfo_Text"] = MultiColorLabel(_("Show Info"))
self["NetworkInfo_Check"] = MultiPixmap()
self["Dhcptext"] = MultiColorLabel(_("DHCP"))
self["Dhcp"] = MultiColorLabel()
self["DhcpInfo"] = MultiPixmap()
self["DhcpInfo_Text"] = MultiColorLabel(_("Show Info"))
self["DhcpInfo_Check"] = MultiPixmap()
self["IPtext"] = MultiColorLabel(_("IP Address"))
self["IP"] = MultiColorLabel()
self["IPInfo"] = MultiPixmap()
self["IPInfo_Text"] = MultiColorLabel(_("Show Info"))
self["IPInfo_Check"] = MultiPixmap()
self["DNStext"] = MultiColorLabel(_("Nameserver"))
self["DNS"] = MultiColorLabel()
self["DNSInfo"] = MultiPixmap()
self["DNSInfo_Text"] = MultiColorLabel(_("Show Info"))
self["DNSInfo_Check"] = MultiPixmap()
self["EditSettings_Text"] = MultiColorLabel(_("Edit settings"))
self["EditSettingsButton"] = MultiPixmap()
self["key_red"] = StaticText(_("Close"))
self["key_green"] = StaticText(_("Start test"))
self["key_yellow"] = StaticText(_("Stop test"))
self["InfoTextBorder"] = Pixmap()
self["InfoText"] = Label()
def getLinkState(self,iface):
if iface in iNetwork.wlan_interfaces:
try:
from Plugins.SystemPlugins.WirelessLan.Wlan import iStatus
except:
self["Network"].setForegroundColorNum(1)
self["Network"].setText(_("disconnected"))
self["NetworkInfo_Check"].setPixmapNum(1)
self["NetworkInfo_Check"].show()
else:
iStatus.getDataForInterface(self.iface,self.getInfoCB)
else:
iNetwork.getLinkState(iface,self.LinkStatedataAvail)
def LinkStatedataAvail(self,data):
for item in data.splitlines():
if "Link detected:" in item:
if "yes" in item:
self["Network"].setForegroundColorNum(2)
self["Network"].setText(_("connected"))
self["NetworkInfo_Check"].setPixmapNum(0)
else:
self["Network"].setForegroundColorNum(1)
self["Network"].setText(_("disconnected"))
self["NetworkInfo_Check"].setPixmapNum(1)
break
else:
self["Network"].setText(_("unknown"))
self["NetworkInfo_Check"].show()
def NetworkStatedataAvail(self,data):
if data <= 2:
self["IP"].setForegroundColorNum(2)
self["IP"].setText(_("confirmed"))
self["IPInfo_Check"].setPixmapNum(0)
else:
self["IP"].setForegroundColorNum(1)
self["IP"].setText(_("unconfirmed"))
self["IPInfo_Check"].setPixmapNum(1)
self["IPInfo_Check"].show()
self["IPInfo_Text"].setForegroundColorNum(1)
self.steptimer = True
self.nextStepTimer.start(300)
def DNSLookupdataAvail(self,data):
if data <= 2:
self["DNS"].setForegroundColorNum(2)
self["DNS"].setText(_("confirmed"))
self["DNSInfo_Check"].setPixmapNum(0)
else:
self["DNS"].setForegroundColorNum(1)
self["DNS"].setText(_("unconfirmed"))
self["DNSInfo_Check"].setPixmapNum(1)
self["DNSInfo_Check"].show()
self["DNSInfo_Text"].setForegroundColorNum(1)
self["EditSettings_Text"].show()
self["EditSettingsButton"].setPixmapNum(1)
self["EditSettings_Text"].setForegroundColorNum(2) # active
self["EditSettingsButton"].show()
self["key_yellow"].setText("")
self["key_green"].setText(_("Restart test"))
self["shortcutsgreen"].setEnabled(False)
self["shortcutsgreen_restart"].setEnabled(True)
self["shortcutsyellow"].setEnabled(False)
self["updown_actions"].setEnabled(True)
self.activebutton = 6
def getInfoCB(self,data,status):
if data is not None:
if data is True:
if status is not None:
if status[self.iface]["essid"] == "off" or status[self.iface]["accesspoint"] == "Not-Associated" or status[self.iface]["accesspoint"] == False:
self["Network"].setForegroundColorNum(1)
self["Network"].setText(_("disconnected"))
self["NetworkInfo_Check"].setPixmapNum(1)
self["NetworkInfo_Check"].show()
else:
self["Network"].setForegroundColorNum(2)
self["Network"].setText(_("connected"))
self["NetworkInfo_Check"].setPixmapNum(0)
self["NetworkInfo_Check"].show()
def cleanup(self):
iNetwork.stopLinkStateConsole()
iNetwork.stopDNSConsole()
try:
from Plugins.SystemPlugins.WirelessLan.Wlan import iStatus
except ImportError:
pass
else:
iStatus.stopWlanConsole()
class NetworkMountsMenu(Screen,HelpableScreen):
skin = """
<screen name="NetworkMountsMenu" position="center,center" size="560,400" >
<ePixmap pixmap="skin_default/buttons/red.png" position="0,0" size="140,40" alphatest="on" />
<widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
<ePixmap pixmap="skin_default/border_menu.png" position="5,45" zPosition="1" size="250,300" transparent="1" alphatest="on" />
<widget name="menulist" position="15,55" size="230,260" zPosition="10" scrollbarMode="showOnDemand" />
<widget source="introduction" render="Label" position="305,50" size="230,300" font="Regular;19" halign="center" valign="center" backgroundColor="#25062748" transparent="1" />
</screen>"""
def __init__(self, session):
Screen.__init__(self, session)
HelpableScreen.__init__(self)
Screen.setTitle(self, _("Mounts Setup"))
self.session = session
self.onChangedEntry = [ ]
self.mainmenu = self.genMainMenu()
self["menulist"] = MenuList(self.mainmenu)
self["key_red"] = StaticText(_("Close"))
self["introduction"] = StaticText()
self["WizardActions"] = HelpableActionMap(self, "WizardActions",
{
"up": (self.up, _("move up to previous entry")),
"down": (self.down, _("move down to next entry")),
"left": (self.left, _("move up to first entry")),
"right": (self.right, _("move down to last entry")),
})
self["OkCancelActions"] = HelpableActionMap(self, "OkCancelActions",
{
"cancel": (self.close, _("exit mounts setup menu")),
"ok": (self.ok, _("select menu entry")),
})
self["ColorActions"] = HelpableActionMap(self, "ColorActions",
{
"red": (self.close, _("exit networkadapter setup menu")),
})
self["actions"] = NumberActionMap(["WizardActions","ShortcutActions"],
{
"ok": self.ok,
"back": self.close,
"up": self.up,
"down": self.down,
"red": self.close,
"left": self.left,
"right": self.right,
}, -2)
if not self.selectionChanged in self["menulist"].onSelectionChanged:
self["menulist"].onSelectionChanged.append(self.selectionChanged)
self.selectionChanged()
def createSummary(self):
from Screens.PluginBrowser import PluginBrowserSummary
return PluginBrowserSummary
def selectionChanged(self):
item = self["menulist"].getCurrent()
if item:
if item[1][0] == 'extendedSetup':
self["introduction"].setText(_(item[1][1]))
name = str(self["menulist"].getCurrent()[0])
desc = self["introduction"].text
else:
name = ""
desc = ""
for cb in self.onChangedEntry:
cb(name, desc)
def ok(self):
if self["menulist"].getCurrent()[1][0] == 'extendedSetup':
self.extended = self["menulist"].getCurrent()[1][2]
self.extended(self.session)
def up(self):
self["menulist"].up()
def down(self):
self["menulist"].down()
def left(self):
self["menulist"].pageUp()
def right(self):
self["menulist"].pageDown()
def genMainMenu(self):
menu = []
self.extended = None
self.extendedSetup = None
for p in plugins.getPlugins(PluginDescriptor.WHERE_NETWORKMOUNTS):
callFnc = p.__call__["ifaceSupported"](self)
if callFnc is not None:
self.extended = callFnc
if p.__call__.has_key("menuEntryName"):
menuEntryName = p.__call__["menuEntryName"](self)
else:
menuEntryName = _('Extended Setup...')
if p.__call__.has_key("menuEntryDescription"):
menuEntryDescription = p.__call__["menuEntryDescription"](self)
else:
menuEntryDescription = _('Extended Networksetup Plugin...')
self.extendedSetup = ('extendedSetup',menuEntryDescription, self.extended)
menu.append((menuEntryName,self.extendedSetup))
return menu
class NetworkAfp(Screen):
skin = """
<screen position="center,center" size="560,310" title="Samba Setup">
<widget name="lab1" position="20,90" size="150,30" font="Regular;20" valign="center" transparent="0"/>
<widget name="labactive" position="180,90" size="250,30" font="Regular;20" valign="center" transparent="0"/>
<widget name="lab2" position="20,160" size="150,30" font="Regular;20" valign="center" transparent="0"/>
<widget name="labstop" position="180,160" size="100,30" font="Regular;20" valign="center" halign="center" backgroundColor="red"/>
<widget name="labrun" position="180,160" size="100,30" zPosition="1" font="Regular;20" valign="center" halign="center" backgroundColor="green"/>
<ePixmap pixmap="skin_default/buttons/red.png" position="0,260" size="140,40" alphatest="on" />
<ePixmap pixmap="skin_default/buttons/green.png" position="140,260" size="140,40" alphatest="on" />
<ePixmap pixmap="skin_default/buttons/yellow.png" position="280,260" size="140,40" alphatest="on" />
<ePixmap pixmap="skin_default/buttons/blue.png" position="420,260" size="140,40" alphatest="on" />
<widget name="key_red" position="0,260" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
<widget name="key_green" position="140,260" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
<widget name="key_yellow" position="280,260" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#a08500" transparent="1" />
<widget name="key_blue" position="420,260" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#18188b" transparent="1" />
</screen>"""
def __init__(self, session):
Screen.__init__(self, session)
Screen.setTitle(self, _("AFP Setup"))
self.skinName = "NetworkServiceSetup"
self.onChangedEntry = [ ]
self['lab1'] = Label(_("Autostart:"))
self['labactive'] = Label(_(_("Disabled")))
self['lab2'] = Label(_("Current Status:"))
self['labstop'] = Label(_("Stopped"))
self['labrun'] = Label(_("Running"))
self['key_red'] = Label(_("Remove Service"))
self['key_green'] = Label(_("Start"))
self['key_yellow'] = Label(_("Autostart"))
self['key_blue'] = Label()
self['status_summary'] = StaticText()
self['autostartstatus_summary'] = StaticText()
self.Console = Console()
self.my_afp_active = False
self.my_afp_run = False
self['actions'] = ActionMap(['WizardActions', 'ColorActions'], {'ok': self.close, 'back': self.close, 'red': self.UninstallCheck, 'green': self.AfpStartStop, 'yellow': self.activateAfp})
self.service_name = 'task-base-appletalk netatalk'
self.InstallCheck()
def InstallCheck(self):
print 'INSTALL CHECK STARTED',self.service_name
self.Console.ePopen('/usr/bin/opkg list_installed ' + self.service_name, self.checkNetworkState)
def checkNetworkState(self, str, retval, extra_args):
print 'INSTALL CHECK FINISHED',str
if not str:
self.feedscheck = self.session.open(MessageBox,_('Please wait whilst feeds state is checked.'), MessageBox.TYPE_INFO, enable_input = False)
self.feedscheck.setTitle(_('Checking Feeds'))
cmd1 = "opkg update"
self.CheckConsole = Console()
self.CheckConsole.ePopen(cmd1, self.checkNetworkStateFinished)
else:
print 'INSTALL ALREADY INSTALLED'
self.updateService()
def checkNetworkStateFinished(self, result, retval,extra_args=None):
if (float(about.getImageVersionString()) < 3.0 and result.find('mipsel/Packages.gz, wget returned 1') != -1) or (float(about.getImageVersionString()) >= 3.0 and result.find('mips32el/Packages.gz, wget returned 1') != -1):
self.session.openWithCallback(self.InstallPackageFailed, MessageBox, _("Sorry feeds are down for maintenance, please try again later."), type=MessageBox.TYPE_INFO, timeout=10, close_on_any_key=True)
elif result.find('bad address') != -1:
self.session.openWithCallback(self.InstallPackageFailed, MessageBox, _("Your STB_BOX is not connected to the internet, please check your network settings and try again."), type=MessageBox.TYPE_INFO, timeout=10, close_on_any_key=True)
else:
self.session.openWithCallback(self.InstallPackage,MessageBox,_('Your STB_BOX will be restarted after the installation of service\nReady to install "%s" ?') % self.service_name, MessageBox.TYPE_YESNO)
def InstallPackage(self, val):
print 'INSTALL QUESTION FINISHED',val
if val:
print 'INSTALLING: ABOUT TO START',self.service_name
self.doInstall(self.installComplete, self.service_name)
else:
print 'INSTALL NO'
self.feedscheck.close()
self.close()
def InstallPackageFailed(self, val):
self.feedscheck.close()
self.close()
def doInstall(self, callback, pkgname):
print 'INSTALLING: SHOW PLEASE WAIT MESSAGE'
self.message = self.session.open(MessageBox,_("please wait..."), MessageBox.TYPE_INFO, enable_input = False)
self.message.setTitle(_('Installing Service'))
print 'INSTALLING: STARTED',pkgname
self.Console.ePopen('/usr/bin/opkg install ' + pkgname, callback)
def installComplete(self,result = None, retval = None, extra_args = None):
print 'INSTALLING: RE-ENABLING REMOTE'
from Screens.Standby import TryQuitMainloop
print 'INSTALLING: REBOOT'
self.session.open(TryQuitMainloop, 2)
def UninstallCheck(self):
self.Console.ePopen('/usr/bin/opkg list_installed ' + self.service_name, self.RemovedataAvail)
def RemovedataAvail(self, str, retval, extra_args):
if str:
restartbox = self.session.openWithCallback(self.RemovePackage,MessageBox,_('Your STB_BOX will be restarted after the removal of service\nDo you want to remove now ?'), MessageBox.TYPE_YESNO)
restartbox.setTitle(_('Ready to remove "%s" ?') % self.service_name)
else:
self.updateService()
def RemovePackage(self, val):
if val:
self.doRemove(self.removeComplete, self.service_name)
def doRemove(self, callback, pkgname):
self.message = self.session.open(MessageBox,_("please wait..."), MessageBox.TYPE_INFO, enable_input = False)
self.message.setTitle(_('Removing Service'))
self.Console.ePopen('/usr/bin/opkg remove ' + pkgname + ' --force-remove --autoremove', callback)
def removeComplete(self,result = None, retval = None, extra_args = None):
print 'INSTALLING: RE-ENABLING REMOTE'
from Screens.Standby import TryQuitMainloop
print 'INSTALLING: REBOOT'
self.session.open(TryQuitMainloop, 2)
def createSummary(self):
return NetworkServicesSummary
def AfpStartStop(self):
if self.my_afp_run == False:
self.Console.ePopen('/etc/init.d/atalk start')
time.sleep(3)
self.updateService()
elif self.my_afp_run == True:
self.Console.ePopen('/etc/init.d/atalk stop')
time.sleep(3)
self.updateService()
def activateAfp(self):
if fileExists('/etc/rc2.d/S20atalk'):
self.Console.ePopen('update-rc.d -f atalk remove')
else:
self.Console.ePopen('update-rc.d -f atalk defaults')
time.sleep(3)
self.updateService()
def updateService(self,result = None, retval = None, extra_args = None):
import process
p = process.ProcessList()
afp_process = str(p.named('afpd')).strip('[]')
self['labrun'].hide()
self['labstop'].hide()
self['labactive'].setText(_("Disabled"))
self.my_afp_active = False
self.my_afp_run = False
if fileExists('/etc/rc2.d/S20atalk'):
self['labactive'].setText(_("Enabled"))
self['labactive'].show()
self.my_afp_active = True
if afp_process:
self.my_afp_run = True
if self.my_afp_run == True:
self['labstop'].hide()
self['labactive'].show()
self['labrun'].show()
self['key_green'].setText(_("Stop"))
status_summary= self['lab2'].text + ' ' + self['labrun'].text
else:
self['labrun'].hide()
self['labstop'].show()
self['labactive'].show()
self['key_green'].setText(_("Start"))
status_summary= self['lab2'].text + ' ' + self['labstop'].text
title = _("AFP Setup")
autostartstatus_summary = self['lab1'].text + ' ' + self['labactive'].text
for cb in self.onChangedEntry:
cb(title, status_summary, autostartstatus_summary)
class NetworkFtp(Screen):
skin = """
<screen position="center,center" size="340,310" title="Ftp Setup">
<widget name="lab1" position="20,30" size="300,80" font="Regular;20" valign="center" transparent="1"/>
<widget name="lab2" position="20,150" size="150,30" font="Regular;20" valign="center" transparent="1"/>
<widget name="labstop" position="170,150" size="100,30" font="Regular;20" valign="center" halign="center" backgroundColor="red"/>
<widget name="labrun" position="170,150" size="100,30" zPosition="1" font="Regular;20" valign="center" halign="center" backgroundColor="green"/>
<ePixmap pixmap="skin_default/buttons/red.png" position="20,260" size="140,40" alphatest="on" />
<ePixmap pixmap="skin_default/buttons/green.png" position="180,260" size="140,40" alphatest="on" />
<widget name="key_red" position="20,260" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
<widget name="key_green" position="180,260" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
</screen>"""
def __init__(self, session):
Screen.__init__(self, session)
Screen.setTitle(self, _("FTP Setup"))
self.onChangedEntry = [ ]
self['lab1'] = Label(_("Ftpd service type: Vsftpd server"))
self['lab2'] = Label(_("Current Status:"))
self['labstop'] = Label(_("Stopped"))
self['labrun'] = Label(_("Running"))
self['key_green'] = Label(_("Enable"))
self['key_red'] = Label()
self.my_ftp_active = False
self.Console = Console()
self['actions'] = ActionMap(['WizardActions', 'ColorActions'], {'ok': self.close, 'back': self.close, 'green': self.FtpStartStop})
self.onLayoutFinish.append(self.updateService)
def createSummary(self):
return NetworkServicesSummary
def FtpStartStop(self):
if self.my_ftp_active == False:
if fileExists('/etc/inetd.conf'):
inme = open('/etc/inetd.conf', 'r')
out = open('/etc/inetd.tmp', 'w')
for line in inme.readlines():
if line.find('vsftpd') != -1:
line = line.replace('#', '')
out.write(line)
out.close()
inme.close()
if fileExists('/etc/inetd.tmp'):
move('/etc/inetd.tmp', '/etc/inetd.conf')
self.Console.ePopen('killall -HUP inetd')
self.updateService()
elif self.my_ftp_active == True:
if fileExists('/etc/inetd.conf'):
inme = open('/etc/inetd.conf', 'r')
out = open('/etc/inetd.tmp', 'w')
for line in inme.readlines():
if line.find('vsftpd') != -1:
line = '#' + line
out.write(line)
out.close()
inme.close()
if fileExists('/etc/inetd.tmp'):
move('/etc/inetd.tmp', '/etc/inetd.conf')
self.Console.ePopen('killall -HUP inetd')
self.updateService()
def updateService(self):
self['labrun'].hide()
self['labstop'].hide()
self.my_ftp_active = False
if fileExists('/etc/inetd.conf'):
f = open('/etc/inetd.conf', 'r')
for line in f.readlines():
parts = line.strip().split()
if parts[0] == 'ftp':
self.my_ftp_active = True
continue
f.close()
if self.my_ftp_active == True:
self['labstop'].hide()
self['labrun'].show()
self['key_green'].setText(_("Disable"))
status_summary= self['lab2'].text + ' ' + self['labrun'].text
else:
self['labstop'].show()
self['labrun'].hide()
self['key_green'].setText(_("Enable"))
status_summary= self['lab2'].text + ' ' + self['labstop'].text
title = _("FTP Setup")
autostartstatus_summary = ""
for cb in self.onChangedEntry:
cb(title, status_summary, autostartstatus_summary)
class NetworkNfs(Screen):
skin = """
<screen position="center,center" size="420,310" title="NFS Setup">
<widget name="lab1" position="20,50" size="200,30" font="Regular;20" valign="center" transparent="0"/>
<widget name="labactive" position="220,50" size="150,30" font="Regular;20" valign="center" transparent="0"/>
<widget name="lab2" position="20,100" size="200,30" font="Regular;20" valign="center" transparent="0"/>
<widget name="labstop" position="220,100" size="100,30" font="Regular;20" valign="center" halign="center" backgroundColor="red"/>
<widget name="labrun" position="220,100" size="100,30" zPosition="1" font="Regular;20" valign="center" halign="center" backgroundColor="green"/>
<ePixmap pixmap="skin_default/buttons/red.png" position="0,260" size="140,40" alphatest="on" />
<ePixmap pixmap="skin_default/buttons/green.png" position="140,260" size="140,40" alphatest="on" />
<ePixmap pixmap="skin_default/buttons/yellow.png" position="280,260" size="140,40" alphatest="on" />
<widget name="key_red" position="0,260" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
<widget name="key_green" position="140,260" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
<widget name="key_yellow" position="280,260" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#a08500" transparent="1" />
</screen>"""
def __init__(self, session):
Screen.__init__(self, session)
Screen.setTitle(self, _("NFS Setup"))
self.skinName = "NetworkServiceSetup"
self.onChangedEntry = [ ]
self['lab1'] = Label(_("Autostart:"))
self['labactive'] = Label(_(_("Disabled")))
self['lab2'] = Label(_("Current Status:"))
self['labstop'] = Label(_("Stopped"))
self['labrun'] = Label(_("Running"))
self['key_green'] = Label(_("Start"))
self['key_red'] = Label(_("Remove Service"))
self['key_yellow'] = Label(_("Autostart"))
self['key_blue'] = Label()
self.Console = Console()
self.my_nfs_active = False
self.my_nfs_run = False
self['actions'] = ActionMap(['WizardActions', 'ColorActions'], {'ok': self.close, 'back': self.close, 'red': self.UninstallCheck, 'green': self.NfsStartStop, 'yellow': self.Nfsset})
self.service_name = 'task-base-nfs'
self.InstallCheck()
def InstallCheck(self):
print 'INSTALL CHECK STARTED',self.service_name
self.Console.ePopen('/usr/bin/opkg list_installed ' + self.service_name, self.checkNetworkState)
def checkNetworkState(self, str, retval, extra_args):
print 'INSTALL CHECK FINISHED',str
if not str:
self.feedscheck = self.session.open(MessageBox,_('Please wait whilst feeds state is checked.'), MessageBox.TYPE_INFO, enable_input = False)
self.feedscheck.setTitle(_('Checking Feeds'))
cmd1 = "opkg update"
self.CheckConsole = Console()
self.CheckConsole.ePopen(cmd1, self.checkNetworkStateFinished)
else:
print 'INSTALL ALREADY INSTALLED'
self.updateService()
def checkNetworkStateFinished(self, result, retval,extra_args=None):
if (float(about.getImageVersionString()) < 3.0 and result.find('mipsel/Packages.gz, wget returned 1') != -1) or (float(about.getImageVersionString()) >= 3.0 and result.find('mips32el/Packages.gz, wget returned 1') != -1):
self.session.openWithCallback(self.InstallPackageFailed, MessageBox, _("Sorry feeds are down for maintenance, please try again later."), type=MessageBox.TYPE_INFO, timeout=10, close_on_any_key=True)
elif result.find('bad address') != -1:
self.session.openWithCallback(self.InstallPackageFailed, MessageBox, _("Your STB_BOX is not connected to the internet, please check your network settings and try again."), type=MessageBox.TYPE_INFO, timeout=10, close_on_any_key=True)
else:
self.session.openWithCallback(self.InstallPackage,MessageBox,_('Your STB_BOX will be restarted after the installation of service\nReady to install "%s" ?') % self.service_name, MessageBox.TYPE_YESNO)
def InstallPackage(self, val):
print 'INSTALL QUESTION FINISHED',val
if val:
print 'INSTALLING: ABOUT TO START',self.service_name
self.doInstall(self.installComplete, self.service_name)
else:
print 'INSTALL NO'
self.feedscheck.close()
self.close()
def InstallPackageFailed(self, val):
self.feedscheck.close()
self.close()
def doInstall(self, callback, pkgname):
print 'INSTALLING: DISABLING REMOTE'
self.message = self.session.open(MessageBox,_("please wait..."), MessageBox.TYPE_INFO, enable_input = False)
self.message.setTitle(_('Installing Service'))
print 'INSTALLING: SHOW PLEASE WAIT MESSAGE'
print 'INSTALLING: STARTED',pkgname
self.Console.ePopen('/usr/bin/opkg install ' + pkgname, callback)
def installComplete(self,result = None, retval = None, extra_args = None):
print 'INSTALLING: RE-ENABLING REMOTE'
from Screens.Standby import TryQuitMainloop
print 'INSTALLING: REBOOT'
self.session.open(TryQuitMainloop, 2)
def UninstallCheck(self):
self.Console.ePopen('/usr/bin/opkg list_installed ' + self.service_name, self.RemovedataAvail)
def RemovedataAvail(self, str, retval, extra_args):
if str:
restartbox = self.session.openWithCallback(self.RemovePackage,MessageBox,_('Your STB_BOX will be restarted after the removal of service\nDo you want to remove now ?'), MessageBox.TYPE_YESNO)
restartbox.setTitle(_('Ready to remove "%s" ?') % self.service_name)
else:
self.updateService()
def RemovePackage(self, val):
if val:
self.doRemove(self.removeComplete, self.service_name)
def doRemove(self, callback, pkgname):
self.message = self.session.open(MessageBox,_("please wait..."), MessageBox.TYPE_INFO, enable_input = False)
self.message.setTitle(_('Removing Service'))
self.Console.ePopen('/usr/bin/opkg remove ' + pkgname + ' --force-remove --autoremove', callback)
def removeComplete(self,result = None, retval = None, extra_args = None):
print 'INSTALLING: RE-ENABLING REMOTE'
from Screens.Standby import TryQuitMainloop
print 'INSTALLING: REBOOT'
self.session.open(TryQuitMainloop, 2)
def createSummary(self):
return NetworkServicesSummary
def NfsStartStop(self):
if self.my_nfs_run == False:
self.Console.ePopen('/etc/init.d/nfsserver start')
time.sleep(3)
self.updateService()
elif self.my_nfs_run == True:
self.Console.ePopen('/etc/init.d/nfsserver stop')
time.sleep(3)
self.updateService()
def Nfsset(self):
if fileExists('/etc/rc2.d/S20nfsserver'):
self.Console.ePopen('update-rc.d -f nfsserver remove')
else:
self.Console.ePopen('update-rc.d -f nfsserver defaults')
time.sleep(3)
self.updateService()
def updateService(self):
import process
p = process.ProcessList()
nfs_process = str(p.named('nfsd')).strip('[]')
self['labrun'].hide()
self['labstop'].hide()
self['labactive'].setText(_("Disabled"))
self.my_nfs_active = False
self.my_nfs_run = False
if fileExists('/etc/rc2.d/S20nfsserver'):
self['labactive'].setText(_("Enabled"))
self['labactive'].show()
self.my_nfs_active = True
if nfs_process:
self.my_nfs_run = True
if self.my_nfs_run == True:
self['labstop'].hide()
self['labrun'].show()
self['key_green'].setText(_("Stop"))
status_summary= self['lab2'].text + ' ' + self['labrun'].text
else:
self['labstop'].show()
self['labrun'].hide()
self['key_green'].setText(_("Start"))
status_summary= self['lab2'].text + ' ' + self['labstop'].text
title = _("NFS Setup")
autostartstatus_summary = self['lab1'].text + ' ' + self['labactive'].text
for cb in self.onChangedEntry:
cb(title, status_summary, autostartstatus_summary)
class NetworkOpenvpn(Screen):
skin = """
<screen position="center,center" size="560,310" title="OpenVpn Setup">
<widget name="lab1" position="20,90" size="150,30" font="Regular;20" valign="center" transparent="0"/>
<widget name="labactive" position="180,90" size="250,30" font="Regular;20" valign="center" transparent="0"/>
<widget name="lab2" position="20,160" size="150,30" font="Regular;20" valign="center" transparent="0"/>
<widget name="labstop" position="180,160" size="100,30" font="Regular;20" valign="center" halign="center" backgroundColor="red"/>
<widget name="labrun" position="180,160" size="100,30" zPosition="1" font="Regular;20" valign="center" halign="center" backgroundColor="green"/>
<ePixmap pixmap="skin_default/buttons/red.png" position="0,260" size="140,40" alphatest="on" />
<ePixmap pixmap="skin_default/buttons/green.png" position="140,260" size="140,40" alphatest="on" />
<ePixmap pixmap="skin_default/buttons/yellow.png" position="280,260" size="140,40" alphatest="on" />
<ePixmap pixmap="skin_default/buttons/blue.png" position="420,260" size="140,40" alphatest="on" />
<widget name="key_red" position="0,260" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
<widget name="key_green" position="140,260" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
<widget name="key_yellow" position="280,260" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#a08500" transparent="1" />
<widget name="key_blue" position="420,260" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#18188b" transparent="1" />
</screen>"""
def __init__(self, session):
Screen.__init__(self, session)
Screen.setTitle(self, _("OpenVpn Setup"))
self.skinName = "NetworkServiceSetup"
self.onChangedEntry = [ ]
self['lab1'] = Label(_("Autostart:"))
self['labactive'] = Label(_(_("Disabled")))
self['lab2'] = Label(_("Current Status:"))
self['labstop'] = Label(_("Stopped"))
self['labrun'] = Label(_("Running"))
self['key_green'] = Label(_("Start"))
self['key_red'] = Label(_("Remove Service"))
self['key_yellow'] = Label(_("Autostart"))
self['key_blue'] = Label(_("Show Log"))
self.Console = Console()
self.my_vpn_active = False
self.my_vpn_run = False
self['actions'] = ActionMap(['WizardActions', 'ColorActions'], {'ok': self.close, 'back': self.close, 'red': self.UninstallCheck, 'green': self.VpnStartStop, 'yellow': self.activateVpn, 'blue': self.Vpnshowlog})
self.service_name = 'openvpn'
self.InstallCheck()
def InstallCheck(self):
self.Console.ePopen('/usr/bin/opkg list_installed ' + self.service_name, self.checkNetworkState)
def checkNetworkState(self, str, retval, extra_args):
if not str:
self.feedscheck = self.session.open(MessageBox,_('Please wait whilst feeds state is checked.'), MessageBox.TYPE_INFO, enable_input = False)
self.feedscheck.setTitle(_('Checking Feeds'))
cmd1 = "opkg update"
self.CheckConsole = Console()
self.CheckConsole.ePopen(cmd1, self.checkNetworkStateFinished)
else:
self.updateService()
def checkNetworkStateFinished(self, result, retval,extra_args=None):
if (float(about.getImageVersionString()) < 3.0 and result.find('mipsel/Packages.gz, wget returned 1') != -1) or (float(about.getImageVersionString()) >= 3.0 and result.find('mips32el/Packages.gz, wget returned 1') != -1):
self.session.openWithCallback(self.InstallPackageFailed, MessageBox, _("Sorry feeds are down for maintenance, please try again later."), type=MessageBox.TYPE_INFO, timeout=10, close_on_any_key=True)
elif result.find('bad address') != -1:
self.session.openWithCallback(self.InstallPackageFailed, MessageBox, _("Your STB_BOX is not connected to the internet, please check your network settings and try again."), type=MessageBox.TYPE_INFO, timeout=10, close_on_any_key=True)
else:
self.session.openWithCallback(self.InstallPackage, MessageBox, _('Ready to install "%s" ?') % self.service_name, MessageBox.TYPE_YESNO)
def InstallPackage(self, val):
if val:
self.doInstall(self.installComplete, self.service_name)
else:
self.feedscheck.close()
self.close()
def InstallPackageFailed(self, val):
self.feedscheck.close()
self.close()
def doInstall(self, callback, pkgname):
self.message = self.session.open(MessageBox,_("please wait..."), MessageBox.TYPE_INFO, enable_input = False)
self.message.setTitle(_('Installing Service'))
self.Console.ePopen('/usr/bin/opkg install ' + pkgname, callback)
def installComplete(self,result = None, retval = None, extra_args = None):
self.message.close()
self.feedscheck.close()
self.updateService()
def UninstallCheck(self):
self.Console.ePopen('/usr/bin/opkg list_installed ' + self.service_name, self.RemovedataAvail)
def RemovedataAvail(self, str, retval, extra_args):
if str:
self.session.openWithCallback(self.RemovePackage, MessageBox, _('Ready to remove "%s" ?') % self.service_name, MessageBox.TYPE_YESNO)
else:
self.updateService()
def RemovePackage(self, val):
if val:
self.doRemove(self.removeComplete, self.service_name)
def doRemove(self, callback, pkgname):
self.message = self.session.open(MessageBox,_("please wait..."), MessageBox.TYPE_INFO, enable_input = False)
self.message.setTitle(_('Removing Service'))
self.Console.ePopen('/usr/bin/opkg remove ' + pkgname + ' --force-remove --autoremove', callback)
def removeComplete(self,result = None, retval = None, extra_args = None):
self.message.close()
self.updateService()
def createSummary(self):
return NetworkServicesSummary
def Vpnshowlog(self):
self.session.open(NetworkVpnLog)
def VpnStartStop(self):
if self.my_vpn_run == False:
self.Console.ePopen('/etc/init.d/openvpn start')
time.sleep(3)
self.updateService()
elif self.my_vpn_run == True:
self.Console.ePopen('/etc/init.d/openvpn stop')
time.sleep(3)
self.updatemy_Vpn()
def activateVpn(self):
if fileExists('/etc/rc2.d/S20openvpn'):
self.Console.ePopen('update-rc.d -f openvpn remove')
else:
self.Console.ePopen('update-rc.d -f openvpn defaults')
time.sleep(3)
self.updateService()
def updateService(self):
import process
p = process.ProcessList()
openvpn_process = str(p.named('openvpn')).strip('[]')
self['labrun'].hide()
self['labstop'].hide()
self['labactive'].setText(_("Disabled"))
self.my_Vpn_active = False
self.my_vpn_run = False
if fileExists('/etc/rc2.d/S20openvpn'):
self['labactive'].setText(_("Enabled"))
self['labactive'].show()
self.my_Vpn_active = True
if openvpn_process:
self.my_vpn_run = True
if self.my_vpn_run == True:
self['labstop'].hide()
self['labrun'].show()
self['key_green'].setText(_("Stop"))
status_summary= self['lab2'].text + ' ' + self['labrun'].text
else:
self['labstop'].show()
self['labrun'].hide()
self['key_green'].setText(_("Start"))
status_summary= self['lab2'].text + ' ' + self['labstop'].text
title = _("OpenVpn Setup")
autostartstatus_summary = self['lab1'].text + ' ' + self['labactive'].text
for cb in self.onChangedEntry:
cb(title, status_summary, autostartstatus_summary)
class NetworkVpnLog(Screen):
skin = """
<screen position="80,100" size="560,400" title="OpenVpn Log">
<widget name="infotext" position="10,10" size="540,380" font="Regular;18" />
</screen>"""
def __init__(self, session):
Screen.__init__(self, session)
Screen.setTitle(self, _("OpenVpn Log"))
self.skinName = "NetworkInadynLog"
self['infotext'] = ScrollLabel('')
self.Console = Console()
self['actions'] = ActionMap(['WizardActions', 'ColorActions'], {'ok': self.close, 'back': self.close, 'up': self['infotext'].pageUp, 'down': self['infotext'].pageDown})
strview = ''
self.Console.ePopen('tail /etc/openvpn/openvpn.log > /etc/openvpn/tmp.log')
time.sleep(1)
if fileExists('/etc/openvpn/tmp.log'):
f = open('/etc/openvpn/tmp.log', 'r')
for line in f.readlines():
strview += line
f.close()
remove('/etc/openvpn/tmp.log')
self['infotext'].setText(strview)
class NetworkSamba(Screen):
skin = """
<screen position="center,center" size="560,310" title="Samba Setup">
<widget name="lab1" position="20,90" size="150,30" font="Regular;20" valign="center" transparent="0"/>
<widget name="labactive" position="180,90" size="250,30" font="Regular;20" valign="center" transparent="0"/>
<widget name="lab2" position="20,160" size="150,30" font="Regular;20" valign="center" transparent="0"/>
<widget name="labstop" position="180,160" size="100,30" font="Regular;20" valign="center" halign="center" backgroundColor="red"/>
<widget name="labrun" position="180,160" size="100,30" zPosition="1" font="Regular;20" valign="center" halign="center" backgroundColor="green"/>
<ePixmap pixmap="skin_default/buttons/red.png" position="0,260" size="140,40" alphatest="on" />
<ePixmap pixmap="skin_default/buttons/green.png" position="140,260" size="140,40" alphatest="on" />
<ePixmap pixmap="skin_default/buttons/yellow.png" position="280,260" size="140,40" alphatest="on" />
<ePixmap pixmap="skin_default/buttons/blue.png" position="420,260" size="140,40" alphatest="on" />
<widget name="key_red" position="0,260" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
<widget name="key_green" position="140,260" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
<widget name="key_yellow" position="280,260" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#a08500" transparent="1" />
<widget name="key_blue" position="420,260" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#18188b" transparent="1" />
</screen>"""
def __init__(self, session):
Screen.__init__(self, session)
Screen.setTitle(self, _("Samba Setup"))
self.skinName = "NetworkServiceSetup"
self.onChangedEntry = [ ]
self['lab1'] = Label(_("Autostart:"))
self['labactive'] = Label(_(_("Disabled")))
self['lab2'] = Label(_("Current Status:"))
self['labstop'] = Label(_("Stopped"))
self['labrun'] = Label(_("Running"))
self['key_green'] = Label(_("Start"))
self['key_red'] = Label(_("Remove Service"))
self['key_yellow'] = Label(_("Autostart"))
self['key_blue'] = Label(_("Show Log"))
self.Console = Console()
self.my_Samba_active = False
self.my_Samba_run = False
self['actions'] = ActionMap(['WizardActions', 'ColorActions'], {'ok': self.close, 'back': self.close, 'red': self.UninstallCheck, 'green': self.SambaStartStop, 'yellow': self.activateSamba, 'blue': self.Sambashowlog})
self.service_name = 'task-base-smbfs'
self.InstallCheck()
def InstallCheck(self):
self.Console.ePopen('/usr/bin/opkg list_installed ' + self.service_name, self.checkNetworkState)
def checkNetworkState(self, str, retval, extra_args):
if not str:
self.feedscheck = self.session.open(MessageBox,_('Please wait whilst feeds state is checked.'), MessageBox.TYPE_INFO, enable_input = False)
self.feedscheck.setTitle(_('Checking Feeds'))
cmd1 = "opkg update"
self.CheckConsole = Console()
self.CheckConsole.ePopen(cmd1, self.checkNetworkStateFinished)
else:
self.updateService()
def checkNetworkStateFinished(self, result, retval,extra_args=None):
if (float(about.getImageVersionString()) < 3.0 and result.find('mipsel/Packages.gz, wget returned 1') != -1) or (float(about.getImageVersionString()) >= 3.0 and result.find('mips32el/Packages.gz, wget returned 1') != -1):
self.session.openWithCallback(self.InstallPackageFailed, MessageBox, _("Sorry feeds are down for maintenance, please try again later."), type=MessageBox.TYPE_INFO, timeout=10, close_on_any_key=True)
elif result.find('bad address') != -1:
self.session.openWithCallback(self.InstallPackageFailed, MessageBox, _("Your STB_BOX is not connected to the internet, please check your network settings and try again."), type=MessageBox.TYPE_INFO, timeout=10, close_on_any_key=True)
else:
self.session.openWithCallback(self.InstallPackage, MessageBox, _('Ready to install "%s" ?') % self.service_name, MessageBox.TYPE_YESNO)
def InstallPackage(self, val):
if val:
self.doInstall(self.installComplete, self.service_name)
else:
self.feedscheck.close()
self.close()
def InstallPackageFailed(self, val):
self.feedscheck.close()
self.close()
def doInstall(self, callback, pkgname):
self.message = self.session.open(MessageBox,_("please wait..."), MessageBox.TYPE_INFO, enable_input = False)
self.message.setTitle(_('Installing Service'))
self.Console.ePopen('/usr/bin/opkg install ' + pkgname, callback)
def installComplete(self,result = None, retval = None, extra_args = None):
self.message.close()
self.feedscheck.close()
self.updateService()
def UninstallCheck(self):
self.Console.ePopen('/usr/bin/opkg list_installed ' + self.service_name, self.RemovedataAvail)
def RemovedataAvail(self, str, retval, extra_args):
if str:
self.session.openWithCallback(self.RemovePackage, MessageBox, _('Ready to remove "%s" ?') % self.service_name, MessageBox.TYPE_YESNO)
else:
self.updateService()
def RemovePackage(self, val):
if val:
self.doRemove(self.removeComplete, self.service_name)
def doRemove(self, callback, pkgname):
self.message = self.session.open(MessageBox,_("please wait..."), MessageBox.TYPE_INFO, enable_input = False)
self.message.setTitle(_('Removing Service'))
self.Console.ePopen('/usr/bin/opkg remove ' + pkgname + ' --force-remove --autoremove', callback)
def removeComplete(self,result = None, retval = None, extra_args = None):
self.message.close()
self.updateService()
def createSummary(self):
return NetworkServicesSummary
def Sambashowlog(self):
self.session.open(NetworkSambaLog)
def SambaStartStop(self):
if self.my_Samba_run == False:
self.Console.ePopen('/etc/init.d/samba start')
time.sleep(3)
self.updateService()
elif self.my_Samba_run == True:
self.Console.ePopen('/etc/init.d/samba stop')
time.sleep(3)
self.updateService()
def activateSamba(self):
if fileExists('/etc/rc2.d/S20samba'):
self.Console.ePopen('update-rc.d -f samba remove')
else:
self.Console.ePopen('update-rc.d -f samba defaults')
time.sleep(3)
self.updateService()
def updateService(self):
import process
p = process.ProcessList()
samba_process = str(p.named('smbd')).strip('[]')
self['labrun'].hide()
self['labstop'].hide()
self['labactive'].setText(_("Disabled"))
self.my_Samba_active = False
self.my_Samba_run = False
if fileExists('/etc/rc2.d/S20samba'):
self['labactive'].setText(_("Enabled"))
self['labactive'].show()
self.my_Samba_active = True
if samba_process:
self.my_Samba_run = True
if self.my_Samba_run == True:
self['labstop'].hide()
self['labactive'].show()
self['labrun'].show()
self['key_green'].setText(_("Stop"))
status_summary = self['lab2'].text + ' ' + self['labrun'].text
else:
self['labrun'].hide()
self['labstop'].show()
self['labactive'].show()
self['key_green'].setText(_("Start"))
status_summary = self['lab2'].text + ' ' + self['labstop'].text
title = _("Samba Setup")
autostartstatus_summary = self['lab1'].text + ' ' + self['labactive'].text
for cb in self.onChangedEntry:
cb(title, status_summary, autostartstatus_summary)
class NetworkSambaLog(Screen):
skin = """
<screen position="80,100" size="560,400" title="Samba Log">
<widget name="infotext" position="10,10" size="540,380" font="Regular;18" />
</screen>"""
def __init__(self, session):
Screen.__init__(self, session)
Screen.setTitle(self, _("Samba Log"))
self.skinName = "NetworkInadynLog"
self['infotext'] = ScrollLabel('')
self.Console = Console()
self['actions'] = ActionMap(['WizardActions', 'ColorActions'], {'ok': self.close, 'back': self.close, 'up': self['infotext'].pageUp, 'down': self['infotext'].pageDown})
strview = ''
self.Console.ePopen('tail /tmp/smb.log > /tmp/tmp.log')
time.sleep(1)
if fileExists('/tmp/tmp.log'):
f = open('/tmp/tmp.log', 'r')
for line in f.readlines():
strview += line
f.close()
remove('/tmp/tmp.log')
self['infotext'].setText(strview)
class NetworkTelnet(Screen):
skin = """
<screen position="center,center" size="340,310" title="Telnet Setup">
<widget name="lab1" position="20,30" size="300,80" font="Regular;20" valign="center" transparent="1"/>
<widget name="lab2" position="20,150" size="150,30" font="Regular;20" valign="center" transparent="1"/>
<widget name="labstop" position="170,150" size="100,30" font="Regular;20" valign="center" halign="center" backgroundColor="red"/>
<widget name="labrun" position="170,150" size="100,30" zPosition="1" font="Regular;20" valign="center" halign="center" backgroundColor="green"/>
<ePixmap pixmap="skin_default/buttons/red.png" position="20,260" size="140,40" alphatest="on" />
<ePixmap pixmap="skin_default/buttons/green.png" position="180,260" size="140,40" alphatest="on" />
<widget name="key_red" position="20,260" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
<widget name="key_green" position="180,260" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
</screen>"""
def __init__(self, session):
Screen.__init__(self, session)
Screen.setTitle(self, _("Telnet Setup"))
self.onChangedEntry = [ ]
self['lab1'] = Label(_("You can disable Telnet Server and use ssh to login."))
self['lab2'] = Label(_("Current Status:"))
self['labstop'] = Label(_("Stopped"))
self['labrun'] = Label(_("Running"))
self['key_green'] = Label(_("Enable"))
self['key_red'] = Label()
self.Console = Console()
self.my_telnet_active = False
self['actions'] = ActionMap(['WizardActions', 'ColorActions'], {'ok': self.close, 'back': self.close, 'green': self.TelnetStartStop})
self.onLayoutFinish.append(self.updateService)
def createSummary(self):
return NetworkServicesSummary
def TelnetStartStop(self):
if self.my_telnet_active == False:
if fileExists('/etc/inetd.conf'):
inme = open('/etc/inetd.conf', 'r')
out = open('/etc/inetd.tmp', 'w')
for line in inme.readlines():
if line.find('telnetd') != -1:
line = line.replace('#', '')
out.write(line)
out.close()
inme.close()
if fileExists('/etc/inetd.tmp'):
move('/etc/inetd.tmp', '/etc/inetd.conf')
self.Console.ePopen('killall -HUP inetd')
elif self.my_telnet_active == True:
if fileExists('/etc/inetd.conf'):
inme = open('/etc/inetd.conf', 'r')
out = open('/etc/inetd.tmp', 'w')
for line in inme.readlines():
if line.find('telnetd') != -1:
line = '#' + line
out.write(line)
out.close()
inme.close()
if fileExists('/etc/inetd.tmp'):
move('/etc/inetd.tmp', '/etc/inetd.conf')
self.Console.ePopen('killall -HUP inetd')
self.updateService()
def updateService(self):
self['labrun'].hide()
self['labstop'].hide()
self.my_telnet_active = False
if fileExists('/etc/inetd.conf'):
f = open('/etc/inetd.conf', 'r')
for line in f.readlines():
parts = line.strip().split()
if parts[0] == 'telnet':
self.my_telnet_active = True
continue
f.close()
if self.my_telnet_active == True:
self['labstop'].hide()
self['labrun'].show()
self['key_green'].setText(_("Disable"))
status_summary= self['lab2'].text + ' ' + self['labrun'].text
else:
self['labstop'].show()
self['labrun'].hide()
self['key_green'].setText(_("Enable"))
status_summary= self['lab2'].text + ' ' + self['labstop'].text
title = _("Telnet Setup")
autostartstatus_summary = ""
for cb in self.onChangedEntry:
cb(title, status_summary, autostartstatus_summary)
class NetworkInadyn(Screen):
skin = """
<screen position="center,center" size="590,410" title="Inadyn Manager">
<widget name="autostart" position="10,0" size="100,24" font="Regular;20" valign="center" transparent="0" />
<widget name="labdisabled" position="110,0" size="100,24" font="Regular;20" valign="center" halign="center" backgroundColor="red" zPosition="1" />
<widget name="labactive" position="110,0" size="100,24" font="Regular;20" valign="center" halign="center" backgroundColor="green" zPosition="2" />
<widget name="status" position="240,0" size="150,24" font="Regular;20" valign="center" transparent="0" />
<widget name="labstop" position="390,0" size="100,24" font="Regular;20" valign="center" halign="center" backgroundColor="red" zPosition="1" />
<widget name="labrun" position="390,0" size="100,24" font="Regular;20" valign="center" halign="center" backgroundColor="green" zPosition="2"/>
<widget name="time" position="10,50" size="230,30" font="Regular;20" valign="center" transparent="1"/>
<widget name="labtime" position="240,50" size="100,30" font="Regular;20" valign="center" backgroundColor="#4D5375"/>
<widget name="username" position="10,100" size="150,30" font="Regular;20" valign="center" transparent="1"/>
<widget name="labuser" position="160,100" size="310,30" font="Regular;20" valign="center" backgroundColor="#4D5375"/>
<widget name="password" position="10,150" size="150,30" font="Regular;20" valign="center" transparent="1"/>
<widget name="labpass" position="160,150" size="310,30" font="Regular;20" valign="center" backgroundColor="#4D5375"/>
<widget name="alias" position="10,200" size="150,30" font="Regular;20" valign="center" transparent="1"/>
<widget name="labalias" position="160,200" size="310,30" font="Regular;20" valign="center" backgroundColor="#4D5375"/>
<widget name="sinactive" position="10,250" zPosition="1" pixmap="skin_default/icons/lock_off.png" size="32,32" alphatest="on" />
<widget name="sactive" position="10,250" zPosition="2" pixmap="skin_default/icons/lock_on.png" size="32,32" alphatest="on" />
<widget name="system" position="50,250" size="100,30" font="Regular;20" valign="center" transparent="1"/>
<widget name="labsys" position="160,250" size="310,30" font="Regular;20" valign="center" backgroundColor="#4D5375"/>
<ePixmap pixmap="skin_default/buttons/red.png" position="0,360" size="140,40" alphatest="on" />
<ePixmap pixmap="skin_default/buttons/green.png" position="150,360" size="140,40" alphatest="on" />
<ePixmap pixmap="skin_default/buttons/yellow.png" position="300,360" size="140,40" alphatest="on" />
<ePixmap pixmap="skin_default/buttons/blue.png" position="450,360" size="140,40" alphatest="on" />
<widget name="key_red" position="0,360" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
<widget name="key_green" position="150,360" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
<widget name="key_yellow" position="300,360" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#a08500" transparent="1" />
<widget name="key_blue" position="450,360" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#18188b" transparent="1" />
</screen>"""
def __init__(self, session):
Screen.__init__(self, session)
Screen.setTitle(self, _("Inadyn Setup"))
self.onChangedEntry = [ ]
self['autostart'] = Label(_("Autostart:"))
self['labactive'] = Label(_(_("Active")))
self['labdisabled'] = Label(_(_("Disabled")))
self['status'] = Label(_("Current Status:"))
self['labstop'] = Label(_("Stopped"))
self['labrun'] = Label(_("Running"))
self['time'] = Label(_("Time Update in Minutes:"))
self['labtime'] = Label()
self['username'] = Label(_("Username") + ":")
self['labuser'] = Label()
self['password'] = Label(_("Password") + ":")
self['labpass'] = Label()
self['alias'] = Label(_("Alias") + ":")
self['labalias'] = Label()
self['sactive'] = Pixmap()
self['sinactive'] = Pixmap()
self['system'] = Label(_("System") + ":")
self['labsys'] = Label()
self['key_red'] = Label(_("Remove Service"))
self['key_green'] = Label(_("Start"))
self['key_yellow'] = Label(_("Autostart"))
self['key_blue'] = Label(_("Show Log"))
self['actions'] = ActionMap(['WizardActions', 'ColorActions', 'SetupActions'], {'ok': self.setupinadyn, 'back': self.close, 'menu': self.setupinadyn, 'red': self.UninstallCheck, 'green': self.InadynStartStop, 'yellow': self.autostart, 'blue': self.inaLog})
self.Console = Console()
self.service_name = 'inadyn-mt'
self.InstallCheck()
def InstallCheck(self):
self.Console.ePopen('/usr/bin/opkg list_installed ' + self.service_name, self.checkNetworkState)
def checkNetworkState(self, str, retval, extra_args):
if not str:
self.feedscheck = self.session.open(MessageBox,_('Please wait whilst feeds state is checked.'), MessageBox.TYPE_INFO, enable_input = False)
self.feedscheck.setTitle(_('Checking Feeds'))
cmd1 = "opkg update"
self.CheckConsole = Console()
self.CheckConsole.ePopen(cmd1, self.checkNetworkStateFinished)
else:
self.updateService()
def checkNetworkStateFinished(self, result, retval,extra_args=None):
if (float(about.getImageVersionString()) < 3.0 and result.find('mipsel/Packages.gz, wget returned 1') != -1) or (float(about.getImageVersionString()) >= 3.0 and result.find('mips32el/Packages.gz, wget returned 1') != -1):
self.session.openWithCallback(self.InstallPackageFailed, MessageBox, _("Sorry feeds are down for maintenance, please try again later."), type=MessageBox.TYPE_INFO, timeout=10, close_on_any_key=True)
elif result.find('bad address') != -1:
self.session.openWithCallback(self.InstallPackageFailed, MessageBox, _("Your STB_BOX is not connected to the internet, please check your network settings and try again."), type=MessageBox.TYPE_INFO, timeout=10, close_on_any_key=True)
else:
self.session.openWithCallback(self.InstallPackage, MessageBox, _('Ready to install "%s" ?') % self.service_name, MessageBox.TYPE_YESNO)
def InstallPackage(self, val):
if val:
self.doInstall(self.installComplete, self.service_name)
else:
self.feedscheck.close()
self.close()
def InstallPackageFailed(self, val):
self.feedscheck.close()
self.close()
def doInstall(self, callback, pkgname):
self.message = self.session.open(MessageBox,_("please wait..."), MessageBox.TYPE_INFO, enable_input = False)
self.message.setTitle(_('Installing Service'))
self.Console.ePopen('/usr/bin/opkg install ' + pkgname, callback)
def installComplete(self,result = None, retval = None, extra_args = None):
self.message.close()
self.feedscheck.close()
self.updateService()
def UninstallCheck(self):
self.Console.ePopen('/usr/bin/opkg list_installed ' + self.service_name, self.RemovedataAvail)
def RemovedataAvail(self, str, retval, extra_args):
if str:
self.session.openWithCallback(self.RemovePackage, MessageBox, _('Ready to remove "%s" ?') % self.service_name, MessageBox.TYPE_YESNO)
else:
self.updateService()
def RemovePackage(self, val):
if val:
self.doRemove(self.removeComplete, self.service_name)
def doRemove(self, callback, pkgname):
self.message = self.session.open(MessageBox,_("please wait..."), MessageBox.TYPE_INFO, enable_input = False)
self.message.setTitle(_('Removing Service'))
self.Console.ePopen('/usr/bin/opkg remove ' + pkgname + ' --force-remove --autoremove', callback)
def removeComplete(self,result = None, retval = None, extra_args = None):
self.message.close()
self.updateService()
def createSummary(self):
return NetworkServicesSummary
def InadynStartStop(self):
if self.my_inadyn_run == False:
self.Console.ePopen('/etc/init.d/inadyn-mt start')
time.sleep(3)
self.updateService()
elif self.my_inadyn_run == True:
self.Console.ePopen('/etc/init.d/inadyn-mt stop')
time.sleep(3)
self.updateService()
def autostart(self):
if fileExists('/etc/rc2.d/S20inadyn-mt'):
self.Console.ePopen('update-rc.d -f inadyn-mt remove')
else:
self.Console.ePopen('update-rc.d -f inadyn-mt defaults')
time.sleep(3)
self.updateService()
def updateService(self):
import process
p = process.ProcessList()
inadyn_process = str(p.named('inadyn-mt')).strip('[]')
self['labrun'].hide()
self['labstop'].hide()
self['labactive'].hide()
self['labdisabled'].hide()
self['sactive'].hide()
self.my_inadyn_active = False
self.my_inadyn_run = False
if fileExists('/etc/rc2.d/S20inadyn-mt'):
self['labdisabled'].hide()
self['labactive'].show()
self.my_inadyn_active = True
autostartstatus_summary = self['autostart'].text + ' ' + self['labactive'].text
else:
self['labactive'].hide()
self['labdisabled'].show()
autostartstatus_summary = self['autostart'].text + ' ' + self['labdisabled'].text
if inadyn_process:
self.my_inadyn_run = True
if self.my_inadyn_run == True:
self['labstop'].hide()
self['labrun'].show()
self['key_green'].setText(_("Stop"))
status_summary = self['status'].text + ' ' + self['labrun'].text
else:
self['labstop'].show()
self['labrun'].hide()
self['key_green'].setText(_("Start"))
status_summary = self['status'].text + ' ' + self['labstop'].text
#self.my_nabina_state = False
if fileExists('/etc/inadyn.conf'):
f = open('/etc/inadyn.conf', 'r')
for line in f.readlines():
line = line.strip()
if line.startswith('username '):
line = line[9:]
self['labuser'].setText(line)
elif line.startswith('password '):
line = line[9:]
self['labpass'].setText(line)
elif line.startswith('alias '):
line = line[6:]
self['labalias'].setText(line)
elif line.startswith('update_period_sec '):
line = line[18:]
line = (int(line) / 60)
self['labtime'].setText(str(line))
elif line.startswith('dyndns_system ') or line.startswith('#dyndns_system '):
if line.startswith('#'):
line = line[15:]
self['sactive'].hide()
else:
line = line[14:]
self['sactive'].show()
self['labsys'].setText(line)
f.close()
title = _("Inadyn Setup")
for cb in self.onChangedEntry:
cb(title, status_summary, autostartstatus_summary)
def setupinadyn(self):
self.session.openWithCallback(self.updateService, NetworkInadynSetup)
def inaLog(self):
self.session.open(NetworkInadynLog)
class NetworkInadynSetup(Screen, ConfigListScreen):
skin = """
<screen name="InadynSetup" position="center,center" size="440,350" title="Inadyn Setup">
<widget name="config" position="10,10" size="420,240" scrollbarMode="showOnDemand" />
<widget name="HelpWindow" pixmap="skin_default/vkey_icon.png" position="170,300" zPosition="1" size="440,350" transparent="1" alphatest="on" />
<ePixmap pixmap="skin_default/buttons/red.png" position="130,310" size="140,40" alphatest="on" />
<widget name="key_red" position="130,310" size="140,40" zPosition="1" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
<ePixmap pixmap="skin_default/buttons/key_text.png" position="300,313" zPosition="4" size="35,25" alphatest="on" transparent="1" />
</screen>"""
def __init__(self, session):
Screen.__init__(self, session)
self.onChangedEntry = [ ]
self.list = []
ConfigListScreen.__init__(self, self.list, session = self.session, on_change = self.selectionChanged)
Screen.setTitle(self, _("Inadyn Setup"))
self['key_red'] = Label(_("Save"))
self['actions'] = ActionMap(['WizardActions', 'ColorActions', 'VirtualKeyboardActions'], {'red': self.saveIna, 'back': self.close, 'showVirtualKeyboard': self.KeyText})
self["HelpWindow"] = Pixmap()
self["HelpWindow"].hide()
self.updateList()
if not self.selectionChanged in self["config"].onSelectionChanged:
self["config"].onSelectionChanged.append(self.selectionChanged)
def createSummary(self):
from Screens.PluginBrowser import PluginBrowserSummary
return PluginBrowserSummary
def selectionChanged(self):
item = self["config"].getCurrent()
if item:
name = str(item[0])
desc = str(item[1].value)
else:
name = ""
desc = ""
for cb in self.onChangedEntry:
cb(name, desc)
def updateList(self):
self.ina_user = NoSave(ConfigText(fixed_size=False))
self.ina_pass = NoSave(ConfigText(fixed_size=False))
self.ina_alias = NoSave(ConfigText(fixed_size=False))
self.ina_period = NoSave(ConfigNumber())
self.ina_sysactive = NoSave(ConfigYesNo(default='False'))
self.ina_system = NoSave(ConfigSelection(default = "[email protected]", choices = [("[email protected]", "[email protected]"), ("[email protected]", "[email protected]"), ("[email protected]", "[email protected]"), ("[email protected]", "[email protected]")]))
if fileExists('/etc/inadyn.conf'):
f = open('/etc/inadyn.conf', 'r')
for line in f.readlines():
line = line.strip()
if line.startswith('username '):
line = line[9:]
self.ina_user.value = line
ina_user1 = getConfigListEntry(_("Username") + ":", self.ina_user)
self.list.append(ina_user1)
elif line.startswith('password '):
line = line[9:]
self.ina_pass.value = line
ina_pass1 = getConfigListEntry(_("Password") + ":", self.ina_pass)
self.list.append(ina_pass1)
elif line.startswith('alias '):
line = line[6:]
self.ina_alias.value = line
ina_alias1 = getConfigListEntry(_("Alias") + ":", self.ina_alias)
self.list.append(ina_alias1)
elif line.startswith('update_period_sec '):
line = line[18:]
line = (int(line) / 60)
self.ina_period.value = line
ina_period1 = getConfigListEntry(_("Time Update in Minutes") + ":", self.ina_period)
self.list.append(ina_period1)
elif line.startswith('dyndns_system ') or line.startswith('#dyndns_system '):
if not line.startswith('#'):
self.ina_sysactive.value = True
line = line[14:]
else:
self.ina_sysactive.value = False
line = line[15:]
ina_sysactive1 = getConfigListEntry(_("Set System") + ":", self.ina_sysactive)
self.list.append(ina_sysactive1)
self.ina_system.value = line
ina_system1 = getConfigListEntry(_("System") + ":", self.ina_system)
self.list.append(ina_system1)
f.close()
self['config'].list = self.list
self['config'].l.setList(self.list)
def KeyText(self):
sel = self['config'].getCurrent()
if sel:
if isinstance(self["config"].getCurrent()[1], ConfigText) or isinstance(self["config"].getCurrent()[1], ConfigPassword):
if self["config"].getCurrent()[1].help_window.instance is not None:
self["config"].getCurrent()[1].help_window.hide()
self.vkvar = sel[0]
if self.vkvar == _("Username") + ':' or self.vkvar == _("Password") + ':' or self.vkvar == _("Alias") + ':' or self.vkvar == _("System") + ':':
from Screens.VirtualKeyBoard import VirtualKeyBoard
self.session.openWithCallback(self.VirtualKeyBoardCallback, VirtualKeyBoard, title = self["config"].getCurrent()[0], text = self["config"].getCurrent()[1].getValue())
def VirtualKeyBoardCallback(self, callback = None):
if callback is not None and len(callback):
self["config"].getCurrent()[1].setValue(callback)
self["config"].invalidate(self["config"].getCurrent())
def saveIna(self):
if fileExists('/etc/inadyn.conf'):
inme = open('/etc/inadyn.conf', 'r')
out = open('/etc/inadyn.conf.tmp', 'w')
for line in inme.readlines():
line = line.replace('\n', '')
if line.startswith('username '):
line = ('username ' + self.ina_user.value.strip())
elif line.startswith('password '):
line = ('password ' + self.ina_pass.value.strip())
elif line.startswith('alias '):
line = ('alias ' + self.ina_alias.value.strip())
elif line.startswith('update_period_sec '):
strview = (self.ina_period.value * 60)
strview = str(strview)
line = ('update_period_sec ' + strview)
elif line.startswith('dyndns_system ') or line.startswith('#dyndns_system '):
if self.ina_sysactive.value == True:
line = ('dyndns_system ' + self.ina_system.value.strip())
else:
line = ('#dyndns_system ' + self.ina_system.value.strip())
out.write((line + '\n'))
out.close()
inme.close()
else:
self.session.open(MessageBox, _("Sorry Inadyn Config is Missing"), MessageBox.TYPE_INFO)
self.close()
if fileExists('/etc/inadyn.conf.tmp'):
rename('/etc/inadyn.conf.tmp', '/etc/inadyn.conf')
self.myStop()
def myStop(self):
self.close()
class NetworkInadynLog(Screen):
skin = """
<screen name="InadynLog" position="center,center" size="590,410" title="Inadyn Log">
<widget name="infotext" position="10,10" size="590,410" font="Console;16" />
</screen>"""
def __init__(self, session):
Screen.__init__(self, session)
Screen.setTitle(self, _("Inadyn Log"))
self['infotext'] = ScrollLabel('')
self['actions'] = ActionMap(['WizardActions', 'DirectionActions', 'ColorActions'], {'ok': self.close,
'back': self.close,
'up': self['infotext'].pageUp,
'down': self['infotext'].pageDown})
strview = ''
if fileExists('/var/log/inadyn.log'):
f = open('/var/log/inadyn.log', 'r')
for line in f.readlines():
strview += line
f.close()
self['infotext'].setText(strview)
config.networkushare = ConfigSubsection();
config.networkushare.mediafolders = NoSave(ConfigLocations(default=""))
class NetworkuShare(Screen):
skin = """
<screen position="center,center" size="590,410" title="uShare Manager">
<widget name="autostart" position="10,0" size="100,24" font="Regular;20" valign="center" transparent="0" />
<widget name="labdisabled" position="110,0" size="100,24" font="Regular;20" valign="center" halign="center" backgroundColor="red" zPosition="1" />
<widget name="labactive" position="110,0" size="100,24" font="Regular;20" valign="center" halign="center" backgroundColor="green" zPosition="2" />
<widget name="status" position="240,0" size="150,24" font="Regular;20" valign="center" transparent="0" />
<widget name="labstop" position="390,0" size="100,24" font="Regular;20" valign="center" halign="center" backgroundColor="red" zPosition="1" />
<widget name="labrun" position="390,0" size="100,24" font="Regular;20" valign="center" halign="center" backgroundColor="green" zPosition="2"/>
<widget name="username" position="10,50" size="150,30" font="Regular;20" valign="center" transparent="1"/>
<widget name="labuser" position="160,50" size="310,30" font="Regular;20" valign="center" backgroundColor="#4D5375"/>
<widget name="iface" position="10,90" size="150,30" font="Regular;20" valign="center" transparent="1"/>
<widget name="labiface" position="160,90" size="310,30" font="Regular;20" valign="center" backgroundColor="#4D5375"/>
<widget name="port" position="10,130" size="150,30" font="Regular;20" valign="center" transparent="1"/>
<widget name="labport" position="160,130" size="310,30" font="Regular;20" valign="center" backgroundColor="#4D5375"/>
<widget name="telnetport" position="10,170" size="150,30" font="Regular;20" valign="center" transparent="1"/>
<widget name="labtelnetport" position="160,170" size="310,30" font="Regular;20" valign="center" backgroundColor="#4D5375"/>
<widget name="sharedir" position="10,210" size="150,30" font="Regular;20" valign="center" transparent="1"/>
<widget name="labsharedir" position="160,210" size="310,90" font="Regular;20" valign="center" backgroundColor="#4D5375"/>
<widget name="web" position="10,300" size="180,30" font="Regular;20" valign="center" transparent="1"/>
<widget name="webinactive" position="200,300" zPosition="1" pixmap="skin_default/icons/lock_off.png" size="32,32" alphatest="on" />
<widget name="webactive" position="200,300" zPosition="2" pixmap="skin_default/icons/lock_on.png" size="32,32" alphatest="on" />
<widget name="telnet" position="10,330" size="180,30" font="Regular;20" valign="center" transparent="1"/>
<widget name="telnetinactive" position="200,330" zPosition="1" pixmap="skin_default/icons/lock_off.png" size="32,32" alphatest="on" />
<widget name="telnetactive" position="200,330" zPosition="2" pixmap="skin_default/icons/lock_on.png" size="32,32" alphatest="on" />
<widget name="xbox" position="250,300" size="200,30" font="Regular;20" valign="center" transparent="1"/>
<widget name="xboxinactive" position="470,300" zPosition="1" pixmap="skin_default/icons/lock_off.png" size="32,32" alphatest="on" />
<widget name="xboxactive" position="470,300" zPosition="2" pixmap="skin_default/icons/lock_on.png" size="32,32" alphatest="on" />
<widget name="dlna" position="250,330" size="200,30" font="Regular;20" valign="center" transparent="1"/>
<widget name="dlnainactive" position="470,330" zPosition="1" pixmap="skin_default/icons/lock_off.png" size="32,32" alphatest="on" />
<widget name="dlnaactive" position="470,330" zPosition="2" pixmap="skin_default/icons/lock_on.png" size="32,32" alphatest="on" />
<ePixmap pixmap="skin_default/buttons/red.png" position="0,360" size="140,40" alphatest="on" />
<ePixmap pixmap="skin_default/buttons/green.png" position="150,360" size="140,40" alphatest="on" />
<ePixmap pixmap="skin_default/buttons/yellow.png" position="300,360" size="140,40" alphatest="on" />
<ePixmap pixmap="skin_default/buttons/blue.png" position="450,360" size="140,40" alphatest="on" />
<widget name="key_red" position="0,360" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
<widget name="key_green" position="150,360" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
<widget name="key_yellow" position="300,360" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#a08500" transparent="1" />
<widget name="key_blue" position="450,360" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#18188b" transparent="1" />
</screen>"""
def __init__(self, session):
Screen.__init__(self, session)
Screen.setTitle(self, _("uShare Setup"))
self.onChangedEntry = [ ]
self['autostart'] = Label(_("Autostart:"))
self['labactive'] = Label(_(_("Active")))
self['labdisabled'] = Label(_(_("Disabled")))
self['status'] = Label(_("Current Status:"))
self['labstop'] = Label(_("Stopped"))
self['labrun'] = Label(_("Running"))
self['username'] = Label(_("uShare Name") + ":")
self['labuser'] = Label()
self['iface'] = Label(_("Interface") + ":")
self['labiface'] = Label()
self['port'] = Label(_("uShare Port") + ":")
self['labport'] = Label()
self['telnetport'] = Label(_("Telnet Port") + ":")
self['labtelnetport'] = Label()
self['sharedir'] = Label(_("Share Folder's") + ":")
self['labsharedir'] = Label()
self['web'] = Label(_("Web Interface") + ":")
self['webactive'] = Pixmap()
self['webinactive'] = Pixmap()
self['telnet'] = Label(_("Telnet Interface") + ":")
self['telnetactive'] = Pixmap()
self['telnetinactive'] = Pixmap()
self['xbox'] = Label(_("XBox 360 support") + ":")
self['xboxactive'] = Pixmap()
self['xboxinactive'] = Pixmap()
self['dlna'] = Label(_("DLNA support") + ":")
self['dlnaactive'] = Pixmap()
self['dlnainactive'] = Pixmap()
self['key_red'] = Label(_("Remove Service"))
self['key_green'] = Label(_("Start"))
self['key_yellow'] = Label(_("Autostart"))
self['key_blue'] = Label(_("Show Log"))
self['actions'] = ActionMap(['WizardActions', 'ColorActions', 'SetupActions'], {'ok': self.setupushare, 'back': self.close, 'menu': self.setupushare, 'red': self.UninstallCheck, 'green': self.uShareStartStop, 'yellow': self.autostart, 'blue': self.ushareLog})
self.Console = Console()
self.service_name = 'ushare'
self.InstallCheck()
def InstallCheck(self):
self.Console.ePopen('/usr/bin/opkg list_installed ' + self.service_name, self.checkNetworkState)
def checkNetworkState(self, str, retval, extra_args):
if not str:
self.feedscheck = self.session.open(MessageBox,_('Please wait whilst feeds state is checked.'), MessageBox.TYPE_INFO, enable_input = False)
self.feedscheck.setTitle(_('Checking Feeds'))
cmd1 = "opkg update"
self.CheckConsole = Console()
self.CheckConsole.ePopen(cmd1, self.checkNetworkStateFinished)
else:
self.updateService()
def checkNetworkStateFinished(self, result, retval,extra_args=None):
if (float(about.getImageVersionString()) < 3.0 and result.find('mipsel/Packages.gz, wget returned 1') != -1) or (float(about.getImageVersionString()) >= 3.0 and result.find('mips32el/Packages.gz, wget returned 1') != -1):
self.session.openWithCallback(self.InstallPackageFailed, MessageBox, _("Sorry feeds are down for maintenance, please try again later."), type=MessageBox.TYPE_INFO, timeout=10, close_on_any_key=True)
elif result.find('bad address') != -1:
self.session.openWithCallback(self.InstallPackageFailed, MessageBox, _("Your STB_BOX is not connected to the internet, please check your network settings and try again."), type=MessageBox.TYPE_INFO, timeout=10, close_on_any_key=True)
else:
self.session.openWithCallback(self.InstallPackage, MessageBox, _('Ready to install "%s" ?') % self.service_name, MessageBox.TYPE_YESNO)
def InstallPackage(self, val):
if val:
self.doInstall(self.installComplete, self.service_name)
else:
self.feedscheck.close()
self.close()
def InstallPackageFailed(self, val):
self.feedscheck.close()
self.close()
def doInstall(self, callback, pkgname):
self.message = self.session.open(MessageBox,_("please wait..."), MessageBox.TYPE_INFO, enable_input = False)
self.message.setTitle(_('Installing Service'))
self.Console.ePopen('/usr/bin/opkg install ' + pkgname, callback)
def installComplete(self,result = None, retval = None, extra_args = None):
self.message.close()
self.feedscheck.close()
self.updateService()
def UninstallCheck(self):
self.Console.ePopen('/usr/bin/opkg list_installed ' + self.service_name, self.RemovedataAvail)
def RemovedataAvail(self, str, retval, extra_args):
if str:
self.session.openWithCallback(self.RemovePackage, MessageBox, _('Ready to remove "%s" ?') % self.service_name, MessageBox.TYPE_YESNO)
else:
self.updateService()
def RemovePackage(self, val):
if val:
self.doRemove(self.removeComplete, self.service_name)
def doRemove(self, callback, pkgname):
self.message = self.session.open(MessageBox,_("please wait..."), MessageBox.TYPE_INFO, enable_input = False)
self.message.setTitle(_('Removing Service'))
self.Console.ePopen('/usr/bin/opkg remove ' + pkgname + ' --force-remove --autoremove', callback)
def removeComplete(self,result = None, retval = None, extra_args = None):
self.message.close()
self.updateService()
def createSummary(self):
return NetworkServicesSummary
def uShareStartStop(self):
if self.my_ushare_run == False:
self.Console.ePopen('/etc/init.d/ushare start >> /tmp/uShare.log')
time.sleep(3)
self.updateService()
elif self.my_ushare_run == True:
self.Console.ePopen('/etc/init.d/ushare stop >> /tmp/uShare.log')
time.sleep(3)
self.updateService()
def autostart(self):
if fileExists('/etc/rc2.d/S20ushare'):
self.Console.ePopen('update-rc.d -f ushare remove')
else:
self.Console.ePopen('update-rc.d -f ushare defaults')
time.sleep(3)
self.updateService()
def updateService(self):
import process
p = process.ProcessList()
ushare_process = str(p.named('ushare')).strip('[]')
self['labrun'].hide()
self['labstop'].hide()
self['labactive'].hide()
self['labdisabled'].hide()
self.my_ushare_active = False
self.my_ushare_run = False
if not fileExists('/tmp/uShare.log'):
open('/tmp/uShare.log', "w").write("")
if fileExists('/etc/rc2.d/S20ushare'):
self['labdisabled'].hide()
self['labactive'].show()
self.my_ushare_active = True
autostartstatus_summary = self['autostart'].text + ' ' + self['labactive'].text
else:
self['labactive'].hide()
self['labdisabled'].show()
autostartstatus_summary = self['autostart'].text + ' ' + self['labdisabled'].text
if ushare_process:
self.my_ushare_run = True
if self.my_ushare_run == True:
self['labstop'].hide()
self['labrun'].show()
self['key_green'].setText(_("Stop"))
status_summary= self['status'].text + ' ' + self['labstop'].text
else:
self['labstop'].show()
self['labrun'].hide()
self['key_green'].setText(_("Start"))
status_summary= self['status'].text + ' ' + self['labstop'].text
if fileExists('/etc/ushare.conf'):
f = open('/etc/ushare.conf', 'r')
for line in f.readlines():
line = line.strip()
if line.startswith('USHARE_NAME='):
line = line[12:]
self['labuser'].setText(line)
elif line.startswith('USHARE_IFACE='):
line = line[13:]
self['labiface'].setText(line)
elif line.startswith('USHARE_PORT='):
line = line[12:]
self['labport'].setText(line)
elif line.startswith('USHARE_TELNET_PORT='):
line = line[19:]
self['labtelnetport'].setText(line)
elif line.startswith('USHARE_DIR='):
line = line[11:]
self.mediafolders = line
self['labsharedir'].setText(line)
elif line.startswith('ENABLE_WEB='):
if line[11:] == 'no':
self['webactive'].hide()
self['webinactive'].show()
else:
self['webactive'].show()
self['webinactive'].hide()
elif line.startswith('ENABLE_TELNET='):
if line[14:] == 'no':
self['telnetactive'].hide()
self['telnetinactive'].show()
else:
self['telnetactive'].show()
self['telnetinactive'].hide()
elif line.startswith('ENABLE_XBOX='):
if line[12:] == 'no':
self['xboxactive'].hide()
self['xboxinactive'].show()
else:
self['xboxactive'].show()
self['xboxinactive'].hide()
elif line.startswith('ENABLE_DLNA='):
if line[12:] == 'no':
self['dlnaactive'].hide()
self['dlnainactive'].show()
else:
self['dlnaactive'].show()
self['dlnainactive'].hide()
f.close()
title = _("uShare Setup")
for cb in self.onChangedEntry:
cb(title, status_summary, autostartstatus_summary)
def setupushare(self):
self.session.openWithCallback(self.updateService, NetworkuShareSetup)
def ushareLog(self):
self.session.open(NetworkuShareLog)
class NetworkuShareSetup(Screen, ConfigListScreen):
skin = """
<screen name="uShareSetup" position="center,center" size="440,400">
<widget name="config" position="10,10" size="420,240" scrollbarMode="showOnDemand" />
<widget name="HelpWindow" pixmap="skin_default/vkey_icon.png" position="440,390" size="440,350" transparent="1" alphatest="on" />
<ePixmap pixmap="skin_default/buttons/red.png" position="0,360" size="140,40" alphatest="on" />
<ePixmap pixmap="skin_default/buttons/green.png" position="150,360" size="140,40" alphatest="on" />
<widget name="key_red" position="0,360" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
<widget name="key_green" position="150,360" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
<ePixmap pixmap="skin_default/buttons/key_text.png" position="320,366" zPosition="4" size="35,25" alphatest="on" transparent="1" />
</screen>"""
def __init__(self, session):
Screen.__init__(self, session)
Screen.setTitle(self, _("uShare Setup"))
self.onChangedEntry = [ ]
self.list = []
ConfigListScreen.__init__(self, self.list, session = self.session, on_change = self.selectionChanged)
Screen.setTitle(self, _("uShare Setup"))
self['key_red'] = Label(_("Save"))
self['key_green'] = Label(_("Shares"))
self['actions'] = ActionMap(['WizardActions', 'ColorActions', 'VirtualKeyboardActions'], {'red': self.saveuShare, 'green': self.selectfolders, 'back': self.close, 'showVirtualKeyboard': self.KeyText})
self["HelpWindow"] = Pixmap()
self["HelpWindow"].hide()
self.updateList()
if not self.selectionChanged in self["config"].onSelectionChanged:
self["config"].onSelectionChanged.append(self.selectionChanged)
def createSummary(self):
from Screens.PluginBrowser import PluginBrowserSummary
return PluginBrowserSummary
def selectionChanged(self):
item = self["config"].getCurrent()
if item:
name = str(item[0])
desc = str(item[1].value)
else:
name = ""
desc = ""
for cb in self.onChangedEntry:
cb(name, desc)
def updateList(self, ret=None):
self.list = []
self.ushare_user = NoSave(ConfigText(default=config.misc.boxtype.value,fixed_size=False))
self.ushare_iface = NoSave(ConfigText(fixed_size=False))
self.ushare_port = NoSave(ConfigNumber())
self.ushare_telnetport = NoSave(ConfigNumber())
self.ushare_web = NoSave(ConfigYesNo(default='True'))
self.ushare_telnet = NoSave(ConfigYesNo(default='True'))
self.ushare_xbox= NoSave(ConfigYesNo(default='True'))
self.ushare_ps3= NoSave(ConfigYesNo(default='True'))
self.ushare_system = NoSave(ConfigSelection(default = "[email protected]", choices = [("[email protected]", "[email protected]"), ("[email protected]", "[email protected]"), ("[email protected]", "[email protected]")]))
if fileExists('/etc/ushare.conf'):
f = open('/etc/ushare.conf', 'r')
for line in f.readlines():
line = line.strip()
if line.startswith('USHARE_NAME='):
line = line[12:]
self.ushare_user.value = line
ushare_user1 = getConfigListEntry(_("uShare Name") + ":", self.ushare_user)
self.list.append(ushare_user1)
elif line.startswith('USHARE_IFACE='):
line = line[13:]
self.ushare_iface.value = line
ushare_iface1 = getConfigListEntry(_("Interface") + ":", self.ushare_iface)
self.list.append(ushare_iface1)
elif line.startswith('USHARE_PORT='):
line = line[12:]
self.ushare_port.value = line
ushare_port1 = getConfigListEntry(_("uShare Port") + ":", self.ushare_port)
self.list.append(ushare_port1)
elif line.startswith('USHARE_TELNET_PORT='):
line = line[19:]
self.ushare_telnetport.value = line
ushare_telnetport1 = getConfigListEntry(_("Telnet Port") + ":", self.ushare_telnetport)
self.list.append(ushare_telnetport1)
elif line.startswith('ENABLE_WEB='):
if line[11:] == 'no':
self.ushare_web.value = False
else:
self.ushare_web.value = True
ushare_web1 = getConfigListEntry(_("Web Interface") + ":", self.ushare_web)
self.list.append(ushare_web1)
elif line.startswith('ENABLE_TELNET='):
if line[14:] == 'no':
self.ushare_telnet.value = False
else:
self.ushare_telnet.value = True
ushare_telnet1 = getConfigListEntry(_("Telnet Interface") + ":", self.ushare_telnet)
self.list.append(ushare_telnet1)
elif line.startswith('ENABLE_XBOX='):
if line[12:] == 'no':
self.ushare_xbox.value = False
else:
self.ushare_xbox.value = True
ushare_xbox1 = getConfigListEntry(_("XBox 360 support") + ":", self.ushare_xbox)
self.list.append(ushare_xbox1)
elif line.startswith('ENABLE_DLNA='):
if line[12:] == 'no':
self.ushare_ps3.value = False
else:
self.ushare_ps3.value = True
ushare_ps31 = getConfigListEntry(_("DLNA support") + ":", self.ushare_ps3)
self.list.append(ushare_ps31)
f.close()
self['config'].list = self.list
self['config'].l.setList(self.list)
def KeyText(self):
sel = self['config'].getCurrent()
if sel:
if isinstance(self["config"].getCurrent()[1], ConfigText) or isinstance(self["config"].getCurrent()[1], ConfigPassword):
if self["config"].getCurrent()[1].help_window.instance is not None:
self["config"].getCurrent()[1].help_window.hide()
self.vkvar = sel[0]
if self.vkvar == _("uShare Name") + ":" or self.vkvar == _("Share Folder's") + ":":
from Screens.VirtualKeyBoard import VirtualKeyBoard
self.session.openWithCallback(self.VirtualKeyBoardCallback, VirtualKeyBoard, title = self["config"].getCurrent()[0], text = self["config"].getCurrent()[1].getValue())
def VirtualKeyBoardCallback(self, callback = None):
if callback is not None and len(callback):
self["config"].getCurrent()[1].setValue(callback)
self["config"].invalidate(self["config"].getCurrent())
def saveuShare(self):
if fileExists('/etc/ushare.conf'):
inme = open('/etc/ushare.conf', 'r')
out = open('/etc/ushare.conf.tmp', 'w')
for line in inme.readlines():
line = line.replace('\n', '')
if line.startswith('USHARE_NAME='):
line = ('USHARE_NAME=' + self.ushare_user.value.strip())
elif line.startswith('USHARE_IFACE='):
line = ('USHARE_IFACE=' + self.ushare_iface.value.strip())
elif line.startswith('USHARE_PORT='):
line = ('USHARE_PORT=' + str(self.ushare_port.value))
elif line.startswith('USHARE_TELNET_PORT='):
line = ('USHARE_TELNET_PORT=' + str(self.ushare_telnetport.value))
elif line.startswith('USHARE_DIR='):
line = ('USHARE_DIR=' + ', '.join( config.networkushare.mediafolders.value ))
elif line.startswith('ENABLE_WEB='):
if not self.ushare_web.value:
line = 'ENABLE_WEB=no'
else:
line = 'ENABLE_WEB=yes'
elif line.startswith('ENABLE_TELNET='):
if not self.ushare_telnet.value:
line = 'ENABLE_TELNET=no'
else:
line = 'ENABLE_TELNET=yes'
elif line.startswith('ENABLE_XBOX='):
if not self.ushare_xbox.value:
line = 'ENABLE_XBOX=no'
else:
line = 'ENABLE_XBOX=yes'
elif line.startswith('ENABLE_DLNA='):
if not self.ushare_ps3.value:
line = 'ENABLE_DLNA=no'
else:
line = 'ENABLE_DLNA=yes'
out.write((line + '\n'))
out.close()
inme.close()
else:
open('/tmp/uShare.log', "a").write(_("Sorry uShare Config is Missing") + '\n')
self.session.open(MessageBox, _("Sorry uShare Config is Missing"), MessageBox.TYPE_INFO)
self.close()
if fileExists('/etc/ushare.conf.tmp'):
rename('/etc/ushare.conf.tmp', '/etc/ushare.conf')
self.myStop()
def myStop(self):
self.close()
def selectfolders(self):
self.session.openWithCallback(self.updateList,uShareSelection)
class uShareSelection(Screen):
skin = """
<screen name="uShareSelection" position="center,center" size="560,400" zPosition="3" >
<ePixmap pixmap="skin_default/buttons/red.png" position="0,0" size="140,40" alphatest="on" />
<ePixmap pixmap="skin_default/buttons/green.png" position="140,0" size="140,40" alphatest="on" />
<ePixmap pixmap="skin_default/buttons/yellow.png" position="280,0" size="140,40" alphatest="on" />
<widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
<widget source="key_green" render="Label" position="140,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
<widget source="key_yellow" render="Label" position="280,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#a08500" transparent="1" />
<widget name="checkList" position="5,50" size="550,350" transparent="1" scrollbarMode="showOnDemand" />
</screen>"""
def __init__(self, session):
Screen.__init__(self, session)
Screen.setTitle(self, _("Select folders"))
self["key_red"] = StaticText(_("Cancel"))
self["key_green"] = StaticText(_("Save"))
self["key_yellow"] = StaticText()
if fileExists('/etc/ushare.conf'):
f = open('/etc/ushare.conf', 'r')
for line in f.readlines():
line = line.strip()
if line.startswith('USHARE_DIR='):
line = line[11:]
self.mediafolders = line
self.selectedFiles = [str(n) for n in self.mediafolders.split(', ')]
defaultDir = '/media/'
self.filelist = MultiFileSelectList(self.selectedFiles, defaultDir,showFiles = False )
self["checkList"] = self.filelist
self["actions"] = ActionMap(["DirectionActions", "OkCancelActions", "ShortcutActions"],
{
"cancel": self.exit,
"red": self.exit,
"yellow": self.changeSelectionState,
"green": self.saveSelection,
"ok": self.okClicked,
"left": self.left,
"right": self.right,
"down": self.down,
"up": self.up
}, -1)
if not self.selectionChanged in self["checkList"].onSelectionChanged:
self["checkList"].onSelectionChanged.append(self.selectionChanged)
self.onLayoutFinish.append(self.layoutFinished)
def layoutFinished(self):
idx = 0
self["checkList"].moveToIndex(idx)
self.selectionChanged()
def selectionChanged(self):
current = self["checkList"].getCurrent()[0]
if current[2] is True:
self["key_yellow"].setText(_("Deselect"))
else:
self["key_yellow"].setText(_("Select"))
def up(self):
self["checkList"].up()
def down(self):
self["checkList"].down()
def left(self):
self["checkList"].pageUp()
def right(self):
self["checkList"].pageDown()
def changeSelectionState(self):
self["checkList"].changeSelectionState()
self.selectedFiles = self["checkList"].getSelectedList()
def saveSelection(self):
self.selectedFiles = self["checkList"].getSelectedList()
config.networkushare.mediafolders.value = self.selectedFiles
self.close(None)
def exit(self):
self.close(None)
def okClicked(self):
if self.filelist.canDescent():
self.filelist.descent()
class NetworkuShareLog(Screen):
skin = """
<screen position="80,100" size="560,400">
<widget name="infotext" position="10,10" size="540,380" font="Regular;18" />
</screen>"""
def __init__(self, session):
Screen.__init__(self, session)
self.skinName = "NetworkInadynLog"
Screen.setTitle(self, _("uShare Log"))
self['infotext'] = ScrollLabel('')
self.Console = Console()
self['actions'] = ActionMap(['WizardActions', 'ColorActions'], {'ok': self.close, 'back': self.close, 'up': self['infotext'].pageUp, 'down': self['infotext'].pageDown})
strview = ''
self.Console.ePopen('tail /tmp/uShare.log > /tmp/tmp.log')
time.sleep(1)
if fileExists('/tmp/tmp.log'):
f = open('/tmp/tmp.log', 'r')
for line in f.readlines():
strview += line
f.close()
remove('/tmp/tmp.log')
self['infotext'].setText(strview)
config.networkminidlna = ConfigSubsection();
config.networkminidlna.mediafolders = NoSave(ConfigLocations(default=""))
class NetworkMiniDLNA(Screen):
skin = """
<screen position="center,center" size="590,410" title="MiniDLNA Manager">
<widget name="autostart" position="10,0" size="100,24" font="Regular;20" valign="center" transparent="0" />
<widget name="labdisabled" position="110,0" size="100,24" font="Regular;20" valign="center" halign="center" backgroundColor="red" zPosition="1" />
<widget name="labactive" position="110,0" size="100,24" font="Regular;20" valign="center" halign="center" backgroundColor="green" zPosition="2" />
<widget name="status" position="240,0" size="150,24" font="Regular;20" valign="center" transparent="0" />
<widget name="labstop" position="390,0" size="100,24" font="Regular;20" valign="center" halign="center" backgroundColor="red" zPosition="1" />
<widget name="labrun" position="390,0" size="100,24" font="Regular;20" valign="center" halign="center" backgroundColor="green" zPosition="2"/>
<widget name="username" position="10,50" size="150,30" font="Regular;20" valign="center" transparent="1"/>
<widget name="labuser" position="160,50" size="310,30" font="Regular;20" valign="center" backgroundColor="#4D5375"/>
<widget name="iface" position="10,90" size="150,30" font="Regular;20" valign="center" transparent="1"/>
<widget name="labiface" position="160,90" size="310,30" font="Regular;20" valign="center" backgroundColor="#4D5375"/>
<widget name="port" position="10,130" size="150,30" font="Regular;20" valign="center" transparent="1"/>
<widget name="labport" position="160,130" size="310,30" font="Regular;20" valign="center" backgroundColor="#4D5375"/>
<widget name="serialno" position="10,170" size="150,30" font="Regular;20" valign="center" transparent="1"/>
<widget name="labserialno" position="160,170" size="310,30" font="Regular;20" valign="center" backgroundColor="#4D5375"/>
<widget name="sharedir" position="10,210" size="150,30" font="Regular;20" valign="center" transparent="1"/>
<widget name="labsharedir" position="160,210" size="310,90" font="Regular;20" valign="top" backgroundColor="#4D5375"/>
<widget name="inotify" position="10,300" size="180,30" font="Regular;20" valign="center" transparent="1"/>
<widget name="inotifyinactive" position="200,300" zPosition="1" pixmap="skin_default/icons/lock_off.png" size="32,32" alphatest="on" />
<widget name="inotifyactive" position="200,300" zPosition="2" pixmap="skin_default/icons/lock_on.png" size="32,32" alphatest="on" />
<widget name="tivo" position="10,330" size="180,30" font="Regular;20" valign="center" transparent="1"/>
<widget name="tivoinactive" position="200,330" zPosition="1" pixmap="skin_default/icons/lock_off.png" size="32,32" alphatest="on" />
<widget name="tivoactive" position="200,330" zPosition="2" pixmap="skin_default/icons/lock_on.png" size="32,32" alphatest="on" />
<widget name="dlna" position="250,300" size="200,30" font="Regular;20" valign="center" transparent="1"/>
<widget name="dlnainactive" position="470,300" zPosition="1" pixmap="skin_default/icons/lock_off.png" size="32,32" alphatest="on" />
<widget name="dlnaactive" position="470,300" zPosition="2" pixmap="skin_default/icons/lock_on.png" size="32,32" alphatest="on" />
<ePixmap pixmap="skin_default/buttons/red.png" position="0,360" size="140,40" alphatest="on" />
<ePixmap pixmap="skin_default/buttons/green.png" position="150,360" size="140,40" alphatest="on" />
<ePixmap pixmap="skin_default/buttons/yellow.png" position="300,360" size="140,40" alphatest="on" />
<ePixmap pixmap="skin_default/buttons/blue.png" position="450,360" size="140,40" alphatest="on" />
<widget name="key_red" position="0,360" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
<widget name="key_green" position="150,360" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
<widget name="key_yellow" position="300,360" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#a08500" transparent="1" />
<widget name="key_blue" position="450,360" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#18188b" transparent="1" />
</screen>"""
def __init__(self, session):
Screen.__init__(self, session)
Screen.setTitle(self, _("MiniDLNA Setup"))
self.onChangedEntry = [ ]
self['autostart'] = Label(_("Autostart:"))
self['labactive'] = Label(_(_("Active")))
self['labdisabled'] = Label(_(_("Disabled")))
self['status'] = Label(_("Current Status:"))
self['labstop'] = Label(_("Stopped"))
self['labrun'] = Label(_("Running"))
self['username'] = Label(_("Name") + ":")
self['labuser'] = Label()
self['iface'] = Label(_("Interface") + ":")
self['labiface'] = Label()
self['port'] = Label(_("Port") + ":")
self['labport'] = Label()
self['serialno'] = Label(_("Serial No") + ":")
self['labserialno'] = Label()
self['sharedir'] = Label(_("Share Folder's") + ":")
self['labsharedir'] = Label()
self['inotify'] = Label(_("Inotify Monitoring") + ":")
self['inotifyactive'] = Pixmap()
self['inotifyinactive'] = Pixmap()
self['tivo'] = Label(_("TiVo support") + ":")
self['tivoactive'] = Pixmap()
self['tivoinactive'] = Pixmap()
self['dlna'] = Label(_("Strict DLNA") + ":")
self['dlnaactive'] = Pixmap()
self['dlnainactive'] = Pixmap()
self['key_red'] = Label(_("Remove Service"))
self['key_green'] = Label(_("Start"))
self['key_yellow'] = Label(_("Autostart"))
self['key_blue'] = Label(_("Show Log"))
self['actions'] = ActionMap(['WizardActions', 'ColorActions', 'SetupActions'], {'ok': self.setupminidlna, 'back': self.close, 'menu': self.setupminidlna, 'red': self.UninstallCheck, 'green': self.MiniDLNAStartStop, 'yellow': self.autostart, 'blue': self.minidlnaLog})
self.Console = Console()
self.service_name = 'minidlna'
self.InstallCheck()
def InstallCheck(self):
self.Console.ePopen('/usr/bin/opkg list_installed ' + self.service_name, self.checkNetworkState)
def checkNetworkState(self, str, retval, extra_args):
if not str:
self.feedscheck = self.session.open(MessageBox,_('Please wait whilst feeds state is checked.'), MessageBox.TYPE_INFO, enable_input = False)
self.feedscheck.setTitle(_('Checking Feeds'))
cmd1 = "opkg update"
self.CheckConsole = Console()
self.CheckConsole.ePopen(cmd1, self.checkNetworkStateFinished)
else:
self.updateService()
def checkNetworkStateFinished(self, result, retval,extra_args=None):
if (float(about.getImageVersionString()) < 3.0 and result.find('mipsel/Packages.gz, wget returned 1') != -1) or (float(about.getImageVersionString()) >= 3.0 and result.find('mips32el/Packages.gz, wget returned 1') != -1):
self.session.openWithCallback(self.InstallPackageFailed, MessageBox, _("Sorry feeds are down for maintenance, please try again later."), type=MessageBox.TYPE_INFO, timeout=10, close_on_any_key=True)
elif result.find('bad address') != -1:
self.session.openWithCallback(self.InstallPackageFailed, MessageBox, _("Your STB_BOX is not connected to the internet, please check your network settings and try again."), type=MessageBox.TYPE_INFO, timeout=10, close_on_any_key=True)
else:
self.session.openWithCallback(self.InstallPackage, MessageBox, _('Ready to install "%s" ?') % self.service_name, MessageBox.TYPE_YESNO)
def InstallPackage(self, val):
if val:
self.doInstall(self.installComplete, self.service_name)
else:
self.feedscheck.close()
self.close()
def InstallPackageFailed(self, val):
self.feedscheck.close()
self.close()
def doInstall(self, callback, pkgname):
self.message = self.session.open(MessageBox,_("please wait..."), MessageBox.TYPE_INFO, enable_input = False)
self.message.setTitle(_('Installing Service'))
self.Console.ePopen('/usr/bin/opkg install ' + pkgname, callback)
def installComplete(self,result = None, retval = None, extra_args = None):
self.message.close()
self.feedscheck.close()
self.updateService()
def UninstallCheck(self):
self.Console.ePopen('/usr/bin/opkg list_installed ' + self.service_name, self.RemovedataAvail)
def RemovedataAvail(self, str, retval, extra_args):
if str:
self.session.openWithCallback(self.RemovePackage, MessageBox, _('Ready to remove "%s" ?') % self.service_name, MessageBox.TYPE_YESNO)
else:
self.updateService()
def RemovePackage(self, val):
if val:
self.doRemove(self.removeComplete, self.service_name)
def doRemove(self, callback, pkgname):
self.message = self.session.open(MessageBox,_("please wait..."), MessageBox.TYPE_INFO, enable_input = False)
self.message.setTitle(_('Removing Service'))
self.Console.ePopen('/usr/bin/opkg remove ' + pkgname + ' --force-remove --autoremove', callback)
def removeComplete(self,result = None, retval = None, extra_args = None):
self.message.close()
self.updateService()
def createSummary(self):
return NetworkServicesSummary
def MiniDLNAStartStop(self):
if self.my_minidlna_run == False:
self.Console.ePopen('/etc/init.d/minidlna start')
time.sleep(3)
self.updateService()
elif self.my_minidlna_run == True:
self.Console.ePopen('/etc/init.d/minidlna stop')
time.sleep(3)
self.updateService()
def autostart(self):
if fileExists('/etc/rc2.d/S20minidlna'):
self.Console.ePopen('update-rc.d -f minidlna remove')
else:
self.Console.ePopen('update-rc.d -f minidlna defaults')
time.sleep(3)
self.updateService()
def updateService(self):
import process
p = process.ProcessList()
minidlna_process = str(p.named('minidlna')).strip('[]')
self['labrun'].hide()
self['labstop'].hide()
self['labactive'].hide()
self['labdisabled'].hide()
self.my_minidlna_active = False
self.my_minidlna_run = False
if fileExists('/etc/rc2.d/S20minidlna'):
self['labdisabled'].hide()
self['labactive'].show()
self.my_minidlna_active = True
autostartstatus_summary = self['autostart'].text + ' ' + self['labactive'].text
else:
self['labactive'].hide()
self['labdisabled'].show()
autostartstatus_summary = self['autostart'].text + ' ' + self['labdisabled'].text
if minidlna_process:
self.my_minidlna_run = True
if self.my_minidlna_run == True:
self['labstop'].hide()
self['labrun'].show()
self['key_green'].setText(_("Stop"))
status_summary = self['status'].text + ' ' + self['labstop'].text
else:
self['labstop'].show()
self['labrun'].hide()
self['key_green'].setText(_("Start"))
status_summary = self['status'].text + ' ' + self['labstop'].text
if fileExists('/etc/minidlna.conf'):
f = open('/etc/minidlna.conf', 'r')
for line in f.readlines():
line = line.strip()
if line.startswith('friendly_name='):
line = line[14:]
self['labuser'].setText(line)
elif line.startswith('network_interface='):
line = line[18:]
self['labiface'].setText(line)
elif line.startswith('port='):
line = line[5:]
self['labport'].setText(line)
elif line.startswith('serial='):
line = line[7:]
self['labserialno'].setText(line)
elif line.startswith('media_dir='):
line = line[10:]
self.mediafolders = line
self['labsharedir'].setText(line)
elif line.startswith('inotify='):
if line[8:] == 'no':
self['inotifyactive'].hide()
self['inotifyinactive'].show()
else:
self['inotifyactive'].show()
self['inotifyinactive'].hide()
elif line.startswith('enable_tivo='):
if line[12:] == 'no':
self['tivoactive'].hide()
self['tivoinactive'].show()
else:
self['tivoactive'].show()
self['tivoinactive'].hide()
elif line.startswith('strict_dlna='):
if line[12:] == 'no':
self['dlnaactive'].hide()
self['dlnainactive'].show()
else:
self['dlnaactive'].show()
self['dlnainactive'].hide()
f.close()
title = _("MiniDLNA Setup")
for cb in self.onChangedEntry:
cb(title, status_summary, autostartstatus_summary)
def setupminidlna(self):
self.session.openWithCallback(self.updateService, NetworkMiniDLNASetup)
def minidlnaLog(self):
self.session.open(NetworkMiniDLNALog)
class NetworkMiniDLNASetup(Screen, ConfigListScreen):
skin = """
<screen name="MiniDLNASetup" position="center,center" size="440,400">
<widget name="config" position="10,10" size="420,240" scrollbarMode="showOnDemand" />
<widget name="HelpWindow" pixmap="skin_default/vkey_icon.png" position="440,390" size="440,350" transparent="1" alphatest="on" />
<ePixmap pixmap="skin_default/buttons/red.png" position="0,360" size="140,40" alphatest="on" />
<ePixmap pixmap="skin_default/buttons/green.png" position="150,360" size="140,40" alphatest="on" />
<widget name="key_red" position="0,360" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
<widget name="key_green" position="150,360" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
<ePixmap pixmap="skin_default/buttons/key_text.png" position="320,366" zPosition="4" size="35,25" alphatest="on" transparent="1" />
</screen>"""
def __init__(self, session):
Screen.__init__(self, session)
Screen.setTitle(self, _("MiniDLNA Setup"))
self.onChangedEntry = [ ]
self.list = []
ConfigListScreen.__init__(self, self.list, session = self.session, on_change = self.selectionChanged)
Screen.setTitle(self, _("MiniDLNA Setup"))
self.skinName = "NetworkuShareSetup"
self['key_red'] = Label(_("Save"))
self['key_green'] = Label(_("Shares"))
self['actions'] = ActionMap(['WizardActions', 'ColorActions', 'VirtualKeyboardActions'], {'red': self.saveMinidlna, 'green': self.selectfolders, 'back': self.close, 'showVirtualKeyboard': self.KeyText})
self["HelpWindow"] = Pixmap()
self["HelpWindow"].hide()
self.updateList()
if not self.selectionChanged in self["config"].onSelectionChanged:
self["config"].onSelectionChanged.append(self.selectionChanged)
def createSummary(self):
from Screens.PluginBrowser import PluginBrowserSummary
return PluginBrowserSummary
def selectionChanged(self):
item = self["config"].getCurrent()
if item:
name = str(item[0])
desc = str(item[1].value)
else:
name = ""
desc = ""
for cb in self.onChangedEntry:
cb(name, desc)
def updateList(self, ret=None):
self.list = []
self.minidlna_name = NoSave(ConfigText(default=config.misc.boxtype.value,fixed_size=False))
self.minidlna_iface = NoSave(ConfigText(fixed_size=False))
self.minidlna_port = NoSave(ConfigNumber())
self.minidlna_serialno = NoSave(ConfigNumber())
self.minidlna_web = NoSave(ConfigYesNo(default='True'))
self.minidlna_inotify = NoSave(ConfigYesNo(default='True'))
self.minidlna_tivo= NoSave(ConfigYesNo(default='True'))
self.minidlna_strictdlna= NoSave(ConfigYesNo(default='True'))
if fileExists('/etc/minidlna.conf'):
f = open('/etc/minidlna.conf', 'r')
for line in f.readlines():
line = line.strip()
if line.startswith('friendly_name='):
line = line[14:]
self.minidlna_name.value = line
minidlna_name1 = getConfigListEntry(_("Name") + ":", self.minidlna_name)
self.list.append(minidlna_name1)
elif line.startswith('network_interface='):
line = line[18:]
self.minidlna_iface.value = line
minidlna_iface1 = getConfigListEntry(_("Interface") + ":", self.minidlna_iface)
self.list.append(minidlna_iface1)
elif line.startswith('port='):
line = line[5:]
self.minidlna_port.value = line
minidlna_port1 = getConfigListEntry(_("Port") + ":", self.minidlna_port)
self.list.append(minidlna_port1)
elif line.startswith('serial='):
line = line[7:]
self.minidlna_serialno.value = line
minidlna_serialno1 = getConfigListEntry(_("Serial No") + ":", self.minidlna_serialno)
self.list.append(minidlna_serialno1)
elif line.startswith('inotify='):
if line[8:] == 'no':
self.minidlna_inotify.value = False
else:
self.minidlna_inotify.value = True
minidlna_inotify1 = getConfigListEntry(_("Inotify Monitoring") + ":", self.minidlna_inotify)
self.list.append(minidlna_inotify1)
elif line.startswith('enable_tivo='):
if line[12:] == 'no':
self.minidlna_tivo.value = False
else:
self.minidlna_tivo.value = True
minidlna_tivo1 = getConfigListEntry(_("TiVo support") + ":", self.minidlna_tivo)
self.list.append(minidlna_tivo1)
elif line.startswith('strict_dlna='):
if line[12:] == 'no':
self.minidlna_strictdlna.value = False
else:
self.minidlna_strictdlna.value = True
minidlna_strictdlna1 = getConfigListEntry(_("Strict DLNA") + ":", self.minidlna_strictdlna)
self.list.append(minidlna_strictdlna1)
f.close()
self['config'].list = self.list
self['config'].l.setList(self.list)
def KeyText(self):
sel = self['config'].getCurrent()
if sel:
if isinstance(self["config"].getCurrent()[1], ConfigText) or isinstance(self["config"].getCurrent()[1], ConfigPassword):
if self["config"].getCurrent()[1].help_window.instance is not None:
self["config"].getCurrent()[1].help_window.hide()
self.vkvar = sel[0]
if self.vkvar == _("Name") + ":" or self.vkvar == _("Share Folder's") + ":":
from Screens.VirtualKeyBoard import VirtualKeyBoard
self.session.openWithCallback(self.VirtualKeyBoardCallback, VirtualKeyBoard, title = self["config"].getCurrent()[0], text = self["config"].getCurrent()[1].getValue())
def VirtualKeyBoardCallback(self, callback = None):
if callback is not None and len(callback):
self["config"].getCurrent()[1].setValue(callback)
self["config"].invalidate(self["config"].getCurrent())
def saveMinidlna(self):
if fileExists('/etc/minidlna.conf'):
inme = open('/etc/minidlna.conf', 'r')
out = open('/etc/minidlna.conf.tmp', 'w')
for line in inme.readlines():
line = line.replace('\n', '')
if line.startswith('friendly_name='):
line = ('friendly_name=' + self.minidlna_name.value.strip())
elif line.startswith('network_interface='):
line = ('network_interface=' + self.minidlna_iface.value.strip())
elif line.startswith('port='):
line = ('port=' + str(self.minidlna_port.value))
elif line.startswith('serial='):
line = ('serial=' + str(self.minidlna_serialno.value))
elif line.startswith('media_dir='):
line = ('media_dir=' + ', '.join( config.networkminidlna.mediafolders.value ))
elif line.startswith('inotify='):
if not self.minidlna_inotify.value:
line = 'inotify=no'
else:
line = 'inotify=yes'
elif line.startswith('enable_tivo='):
if not self.minidlna_tivo.value:
line = 'enable_tivo=no'
else:
line = 'enable_tivo=yes'
elif line.startswith('strict_dlna='):
if not self.minidlna_strictdlna.value:
line = 'strict_dlna=no'
else:
line = 'strict_dlna=yes'
out.write((line + '\n'))
out.close()
inme.close()
else:
self.session.open(MessageBox, _("Sorry MiniDLNA Config is Missing"), MessageBox.TYPE_INFO)
self.close()
if fileExists('/etc/minidlna.conf.tmp'):
rename('/etc/minidlna.conf.tmp', '/etc/minidlna.conf')
self.myStop()
def myStop(self):
self.close()
def selectfolders(self):
self.session.openWithCallback(self.updateList,MiniDLNASelection)
class MiniDLNASelection(Screen):
skin = """
<screen name="MiniDLNASelection" position="center,center" size="560,400" zPosition="3" >
<ePixmap pixmap="skin_default/buttons/red.png" position="0,0" size="140,40" alphatest="on" />
<ePixmap pixmap="skin_default/buttons/green.png" position="140,0" size="140,40" alphatest="on" />
<ePixmap pixmap="skin_default/buttons/yellow.png" position="280,0" size="140,40" alphatest="on" />
<widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
<widget source="key_green" render="Label" position="140,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
<widget source="key_yellow" render="Label" position="280,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#a08500" transparent="1" />
<widget name="checkList" position="5,50" size="550,350" transparent="1" scrollbarMode="showOnDemand" />
</screen>"""
def __init__(self, session):
Screen.__init__(self, session)
Screen.setTitle(self, _("Select folders"))
self.skinName = "uShareSelection"
self["key_red"] = StaticText(_("Cancel"))
self["key_green"] = StaticText(_("Save"))
self["key_yellow"] = StaticText()
if fileExists('/etc/minidlna.conf'):
f = open('/etc/minidlna.conf', 'r')
for line in f.readlines():
line = line.strip()
if line.startswith('media_dir='):
line = line[11:]
self.mediafolders = line
self.selectedFiles = [str(n) for n in self.mediafolders.split(', ')]
defaultDir = '/media/'
self.filelist = MultiFileSelectList(self.selectedFiles, defaultDir,showFiles = False )
self["checkList"] = self.filelist
self["actions"] = ActionMap(["DirectionActions", "OkCancelActions", "ShortcutActions"],
{
"cancel": self.exit,
"red": self.exit,
"yellow": self.changeSelectionState,
"green": self.saveSelection,
"ok": self.okClicked,
"left": self.left,
"right": self.right,
"down": self.down,
"up": self.up
}, -1)
if not self.selectionChanged in self["checkList"].onSelectionChanged:
self["checkList"].onSelectionChanged.append(self.selectionChanged)
self.onLayoutFinish.append(self.layoutFinished)
def layoutFinished(self):
idx = 0
self["checkList"].moveToIndex(idx)
self.selectionChanged()
def selectionChanged(self):
current = self["checkList"].getCurrent()[0]
if current[2] is True:
self["key_yellow"].setText(_("Deselect"))
else:
self["key_yellow"].setText(_("Select"))
def up(self):
self["checkList"].up()
def down(self):
self["checkList"].down()
def left(self):
self["checkList"].pageUp()
def right(self):
self["checkList"].pageDown()
def changeSelectionState(self):
self["checkList"].changeSelectionState()
self.selectedFiles = self["checkList"].getSelectedList()
def saveSelection(self):
self.selectedFiles = self["checkList"].getSelectedList()
config.networkminidlna.mediafolders.value = self.selectedFiles
self.close(None)
def exit(self):
self.close(None)
def okClicked(self):
if self.filelist.canDescent():
self.filelist.descent()
class NetworkMiniDLNALog(Screen):
skin = """
<screen position="80,100" size="560,400">
<widget name="infotext" position="10,10" size="540,380" font="Regular;18" />
</screen>"""
def __init__(self, session):
Screen.__init__(self, session)
self.skinName = "NetworkInadynLog"
Screen.setTitle(self, _("MiniDLNA Log"))
self['infotext'] = ScrollLabel('')
self.Console = Console()
self['actions'] = ActionMap(['WizardActions', 'ColorActions'], {'ok': self.close, 'back': self.close, 'up': self['infotext'].pageUp, 'down': self['infotext'].pageDown})
strview = ''
self.Console.ePopen('tail /var/volatile/log/minidlna.log > /tmp/tmp.log')
time.sleep(1)
if fileExists('/tmp/tmp.log'):
f = open('/tmp/tmp.log', 'r')
for line in f.readlines():
strview += line
f.close()
remove('/tmp/tmp.log')
self['infotext'].setText(strview)
class NetworkServicesSummary(Screen):
def __init__(self, session, parent):
Screen.__init__(self, session, parent = parent)
self["title"] = StaticText("")
self["status_summary"] = StaticText("")
self["autostartstatus_summary"] = StaticText("")
self.onShow.append(self.addWatcher)
self.onHide.append(self.removeWatcher)
def addWatcher(self):
self.parent.onChangedEntry.append(self.selectionChanged)
self.parent.updateService()
def removeWatcher(self):
self.parent.onChangedEntry.remove(self.selectionChanged)
def selectionChanged(self, title, status_summary, autostartstatus_summary):
self["title"].text = title
self["status_summary"].text = status_summary
self["autostartstatus_summary"].text = autostartstatus_summary
|
snowzjx/ns3-buffer-management | refs/heads/master | src/core/bindings/modulegen__gcc_LP64.py | 35 | from pybindgen import Module, FileCodeSink, param, retval, cppclass, typehandlers
import pybindgen.settings
import warnings
class ErrorHandler(pybindgen.settings.ErrorHandler):
def handle_error(self, wrapper, exception, traceback_):
warnings.warn("exception %r in wrapper %s" % (exception, wrapper))
return True
pybindgen.settings.error_handler = ErrorHandler()
import sys
def module_init():
root_module = Module('ns.core', cpp_namespace='::ns3')
return root_module
def register_types(module):
root_module = module.get_root()
## log.h (module 'core'): ns3::LogLevel [enumeration]
module.add_enum('LogLevel', ['LOG_NONE', 'LOG_ERROR', 'LOG_LEVEL_ERROR', 'LOG_WARN', 'LOG_LEVEL_WARN', 'LOG_DEBUG', 'LOG_LEVEL_DEBUG', 'LOG_INFO', 'LOG_LEVEL_INFO', 'LOG_FUNCTION', 'LOG_LEVEL_FUNCTION', 'LOG_LOGIC', 'LOG_LEVEL_LOGIC', 'LOG_ALL', 'LOG_LEVEL_ALL', 'LOG_PREFIX_FUNC', 'LOG_PREFIX_TIME', 'LOG_PREFIX_NODE', 'LOG_PREFIX_LEVEL', 'LOG_PREFIX_ALL'])
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList [class]
module.add_class('AttributeConstructionList')
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item [struct]
module.add_class('Item', outer_class=root_module['ns3::AttributeConstructionList'])
## callback.h (module 'core'): ns3::CallbackBase [class]
module.add_class('CallbackBase')
## command-line.h (module 'core'): ns3::CommandLine [class]
module.add_class('CommandLine', allow_subclassing=True)
## system-mutex.h (module 'core'): ns3::CriticalSection [class]
module.add_class('CriticalSection')
## event-garbage-collector.h (module 'core'): ns3::EventGarbageCollector [class]
module.add_class('EventGarbageCollector')
## event-id.h (module 'core'): ns3::EventId [class]
module.add_class('EventId')
## global-value.h (module 'core'): ns3::GlobalValue [class]
module.add_class('GlobalValue')
## hash.h (module 'core'): ns3::Hasher [class]
module.add_class('Hasher')
## int-to-type.h (module 'core'): ns3::IntToType<0> [struct]
module.add_class('IntToType', template_parameters=['0'])
## int-to-type.h (module 'core'): ns3::IntToType<0>::v_e [enumeration]
module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 0 >'])
## int-to-type.h (module 'core'): ns3::IntToType<1> [struct]
module.add_class('IntToType', template_parameters=['1'])
## int-to-type.h (module 'core'): ns3::IntToType<1>::v_e [enumeration]
module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 1 >'])
## int-to-type.h (module 'core'): ns3::IntToType<2> [struct]
module.add_class('IntToType', template_parameters=['2'])
## int-to-type.h (module 'core'): ns3::IntToType<2>::v_e [enumeration]
module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 2 >'])
## int-to-type.h (module 'core'): ns3::IntToType<3> [struct]
module.add_class('IntToType', template_parameters=['3'])
## int-to-type.h (module 'core'): ns3::IntToType<3>::v_e [enumeration]
module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 3 >'])
## int-to-type.h (module 'core'): ns3::IntToType<4> [struct]
module.add_class('IntToType', template_parameters=['4'])
## int-to-type.h (module 'core'): ns3::IntToType<4>::v_e [enumeration]
module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 4 >'])
## int-to-type.h (module 'core'): ns3::IntToType<5> [struct]
module.add_class('IntToType', template_parameters=['5'])
## int-to-type.h (module 'core'): ns3::IntToType<5>::v_e [enumeration]
module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 5 >'])
## int-to-type.h (module 'core'): ns3::IntToType<6> [struct]
module.add_class('IntToType', template_parameters=['6'])
## int-to-type.h (module 'core'): ns3::IntToType<6>::v_e [enumeration]
module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 6 >'])
## log.h (module 'core'): ns3::LogComponent [class]
module.add_class('LogComponent')
## names.h (module 'core'): ns3::Names [class]
module.add_class('Names')
## non-copyable.h (module 'core'): ns3::NonCopyable [class]
module.add_class('NonCopyable', destructor_visibility='protected')
## object-base.h (module 'core'): ns3::ObjectBase [class]
module.add_class('ObjectBase', allow_subclassing=True)
## object.h (module 'core'): ns3::ObjectDeleter [struct]
module.add_class('ObjectDeleter')
## object-factory.h (module 'core'): ns3::ObjectFactory [class]
module.add_class('ObjectFactory')
## log.h (module 'core'): ns3::ParameterLogger [class]
module.add_class('ParameterLogger')
## random-variable-stream-helper.h (module 'core'): ns3::RandomVariableStreamHelper [class]
module.add_class('RandomVariableStreamHelper')
## rng-seed-manager.h (module 'core'): ns3::RngSeedManager [class]
module.add_class('RngSeedManager')
## rng-stream.h (module 'core'): ns3::RngStream [class]
module.add_class('RngStream')
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, template_parameters=['ns3::Object', 'ns3::ObjectBase', 'ns3::ObjectDeleter'], parent=root_module['ns3::ObjectBase'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simulator.h (module 'core'): ns3::Simulator [class]
module.add_class('Simulator', destructor_visibility='private')
## system-condition.h (module 'core'): ns3::SystemCondition [class]
module.add_class('SystemCondition')
## system-mutex.h (module 'core'): ns3::SystemMutex [class]
module.add_class('SystemMutex')
## system-wall-clock-ms.h (module 'core'): ns3::SystemWallClockMs [class]
module.add_class('SystemWallClockMs')
## nstime.h (module 'core'): ns3::TimeWithUnit [class]
module.add_class('TimeWithUnit')
## timer.h (module 'core'): ns3::Timer [class]
module.add_class('Timer')
## timer.h (module 'core'): ns3::Timer::DestroyPolicy [enumeration]
module.add_enum('DestroyPolicy', ['CANCEL_ON_DESTROY', 'REMOVE_ON_DESTROY', 'CHECK_ON_DESTROY'], outer_class=root_module['ns3::Timer'])
## timer.h (module 'core'): ns3::Timer::State [enumeration]
module.add_enum('State', ['RUNNING', 'EXPIRED', 'SUSPENDED'], outer_class=root_module['ns3::Timer'])
## timer-impl.h (module 'core'): ns3::TimerImpl [class]
module.add_class('TimerImpl', allow_subclassing=True)
## type-id.h (module 'core'): ns3::TypeId [class]
module.add_class('TypeId')
## type-id.h (module 'core'): ns3::TypeId::AttributeFlag [enumeration]
module.add_enum('AttributeFlag', ['ATTR_GET', 'ATTR_SET', 'ATTR_CONSTRUCT', 'ATTR_SGC'], outer_class=root_module['ns3::TypeId'])
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation [struct]
module.add_class('AttributeInformation', outer_class=root_module['ns3::TypeId'])
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation [struct]
module.add_class('TraceSourceInformation', outer_class=root_module['ns3::TypeId'])
## vector.h (module 'core'): ns3::Vector2D [class]
module.add_class('Vector2D')
## vector.h (module 'core'): ns3::Vector3D [class]
module.add_class('Vector3D')
## watchdog.h (module 'core'): ns3::Watchdog [class]
module.add_class('Watchdog')
## empty.h (module 'core'): ns3::empty [class]
module.add_class('empty')
## int64x64-double.h (module 'core'): ns3::int64x64_t [class]
module.add_class('int64x64_t')
## int64x64-double.h (module 'core'): ns3::int64x64_t::impl_type [enumeration]
module.add_enum('impl_type', ['int128_impl', 'cairo_impl', 'ld_impl'], outer_class=root_module['ns3::int64x64_t'])
## object.h (module 'core'): ns3::Object [class]
module.add_class('Object', parent=root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >'])
## object.h (module 'core'): ns3::Object::AggregateIterator [class]
module.add_class('AggregateIterator', outer_class=root_module['ns3::Object'])
## random-variable-stream.h (module 'core'): ns3::RandomVariableStream [class]
module.add_class('RandomVariableStream', parent=root_module['ns3::Object'])
## scheduler.h (module 'core'): ns3::Scheduler [class]
module.add_class('Scheduler', parent=root_module['ns3::Object'])
## scheduler.h (module 'core'): ns3::Scheduler::Event [struct]
module.add_class('Event', outer_class=root_module['ns3::Scheduler'])
## scheduler.h (module 'core'): ns3::Scheduler::EventKey [struct]
module.add_class('EventKey', outer_class=root_module['ns3::Scheduler'])
## random-variable-stream.h (module 'core'): ns3::SequentialRandomVariable [class]
module.add_class('SequentialRandomVariable', parent=root_module['ns3::RandomVariableStream'])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, template_parameters=['ns3::AttributeAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeAccessor>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, template_parameters=['ns3::AttributeChecker', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeChecker>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, template_parameters=['ns3::AttributeValue', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeValue>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, template_parameters=['ns3::CallbackImplBase', 'ns3::empty', 'ns3::DefaultDeleter<ns3::CallbackImplBase>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, template_parameters=['ns3::EventImpl', 'ns3::empty', 'ns3::DefaultDeleter<ns3::EventImpl>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::FdReader, ns3::empty, ns3::DefaultDeleter<ns3::FdReader> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, template_parameters=['ns3::FdReader', 'ns3::empty', 'ns3::DefaultDeleter<ns3::FdReader>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, template_parameters=['ns3::Hash::Implementation', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Hash::Implementation>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::RefCountBase, ns3::empty, ns3::DefaultDeleter<ns3::RefCountBase> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, template_parameters=['ns3::RefCountBase', 'ns3::empty', 'ns3::DefaultDeleter<ns3::RefCountBase>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::SystemThread, ns3::empty, ns3::DefaultDeleter<ns3::SystemThread> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, template_parameters=['ns3::SystemThread', 'ns3::empty', 'ns3::DefaultDeleter<ns3::SystemThread>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, template_parameters=['ns3::TraceSourceAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::TraceSourceAccessor>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simulator-impl.h (module 'core'): ns3::SimulatorImpl [class]
module.add_class('SimulatorImpl', parent=root_module['ns3::Object'])
## synchronizer.h (module 'core'): ns3::Synchronizer [class]
module.add_class('Synchronizer', parent=root_module['ns3::Object'])
## system-thread.h (module 'core'): ns3::SystemThread [class]
module.add_class('SystemThread', parent=root_module['ns3::SimpleRefCount< ns3::SystemThread, ns3::empty, ns3::DefaultDeleter<ns3::SystemThread> >'])
## nstime.h (module 'core'): ns3::Time [class]
module.add_class('Time')
## nstime.h (module 'core'): ns3::Time::Unit [enumeration]
module.add_enum('Unit', ['Y', 'D', 'H', 'MIN', 'S', 'MS', 'US', 'NS', 'PS', 'FS', 'LAST'], outer_class=root_module['ns3::Time'])
## nstime.h (module 'core'): ns3::Time [class]
root_module['ns3::Time'].implicitly_converts_to(root_module['ns3::int64x64_t'])
## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor [class]
module.add_class('TraceSourceAccessor', parent=root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >'])
## random-variable-stream.h (module 'core'): ns3::TriangularRandomVariable [class]
module.add_class('TriangularRandomVariable', parent=root_module['ns3::RandomVariableStream'])
## random-variable-stream.h (module 'core'): ns3::UniformRandomVariable [class]
module.add_class('UniformRandomVariable', parent=root_module['ns3::RandomVariableStream'])
## wall-clock-synchronizer.h (module 'core'): ns3::WallClockSynchronizer [class]
module.add_class('WallClockSynchronizer', parent=root_module['ns3::Synchronizer'])
## random-variable-stream.h (module 'core'): ns3::WeibullRandomVariable [class]
module.add_class('WeibullRandomVariable', parent=root_module['ns3::RandomVariableStream'])
## random-variable-stream.h (module 'core'): ns3::ZetaRandomVariable [class]
module.add_class('ZetaRandomVariable', parent=root_module['ns3::RandomVariableStream'])
## random-variable-stream.h (module 'core'): ns3::ZipfRandomVariable [class]
module.add_class('ZipfRandomVariable', parent=root_module['ns3::RandomVariableStream'])
## attribute.h (module 'core'): ns3::AttributeAccessor [class]
module.add_class('AttributeAccessor', parent=root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >'])
## attribute.h (module 'core'): ns3::AttributeChecker [class]
module.add_class('AttributeChecker', allow_subclassing=False, automatic_type_narrowing=True, parent=root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >'])
## attribute.h (module 'core'): ns3::AttributeValue [class]
module.add_class('AttributeValue', allow_subclassing=False, automatic_type_narrowing=True, parent=root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >'])
## boolean.h (module 'core'): ns3::BooleanChecker [class]
module.add_class('BooleanChecker', parent=root_module['ns3::AttributeChecker'])
## boolean.h (module 'core'): ns3::BooleanValue [class]
module.add_class('BooleanValue', parent=root_module['ns3::AttributeValue'])
## calendar-scheduler.h (module 'core'): ns3::CalendarScheduler [class]
module.add_class('CalendarScheduler', parent=root_module['ns3::Scheduler'])
## callback.h (module 'core'): ns3::CallbackChecker [class]
module.add_class('CallbackChecker', parent=root_module['ns3::AttributeChecker'])
## callback.h (module 'core'): ns3::CallbackImplBase [class]
module.add_class('CallbackImplBase', parent=root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >'])
## callback.h (module 'core'): ns3::CallbackValue [class]
module.add_class('CallbackValue', parent=root_module['ns3::AttributeValue'])
## random-variable-stream.h (module 'core'): ns3::ConstantRandomVariable [class]
module.add_class('ConstantRandomVariable', parent=root_module['ns3::RandomVariableStream'])
## default-simulator-impl.h (module 'core'): ns3::DefaultSimulatorImpl [class]
module.add_class('DefaultSimulatorImpl', parent=root_module['ns3::SimulatorImpl'])
## random-variable-stream.h (module 'core'): ns3::DeterministicRandomVariable [class]
module.add_class('DeterministicRandomVariable', parent=root_module['ns3::RandomVariableStream'])
## double.h (module 'core'): ns3::DoubleValue [class]
module.add_class('DoubleValue', parent=root_module['ns3::AttributeValue'])
## random-variable-stream.h (module 'core'): ns3::EmpiricalRandomVariable [class]
module.add_class('EmpiricalRandomVariable', parent=root_module['ns3::RandomVariableStream'])
## attribute.h (module 'core'): ns3::EmptyAttributeValue [class]
module.add_class('EmptyAttributeValue', parent=root_module['ns3::AttributeValue'])
## enum.h (module 'core'): ns3::EnumChecker [class]
module.add_class('EnumChecker', parent=root_module['ns3::AttributeChecker'])
## enum.h (module 'core'): ns3::EnumValue [class]
module.add_class('EnumValue', parent=root_module['ns3::AttributeValue'])
## random-variable-stream.h (module 'core'): ns3::ErlangRandomVariable [class]
module.add_class('ErlangRandomVariable', parent=root_module['ns3::RandomVariableStream'])
## event-impl.h (module 'core'): ns3::EventImpl [class]
module.add_class('EventImpl', parent=root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >'])
## random-variable-stream.h (module 'core'): ns3::ExponentialRandomVariable [class]
module.add_class('ExponentialRandomVariable', parent=root_module['ns3::RandomVariableStream'])
## unix-fd-reader.h (module 'core'): ns3::FdReader [class]
module.add_class('FdReader', parent=root_module['ns3::SimpleRefCount< ns3::FdReader, ns3::empty, ns3::DefaultDeleter<ns3::FdReader> >'])
## random-variable-stream.h (module 'core'): ns3::GammaRandomVariable [class]
module.add_class('GammaRandomVariable', parent=root_module['ns3::RandomVariableStream'])
## heap-scheduler.h (module 'core'): ns3::HeapScheduler [class]
module.add_class('HeapScheduler', parent=root_module['ns3::Scheduler'])
## integer.h (module 'core'): ns3::IntegerValue [class]
module.add_class('IntegerValue', parent=root_module['ns3::AttributeValue'])
## list-scheduler.h (module 'core'): ns3::ListScheduler [class]
module.add_class('ListScheduler', parent=root_module['ns3::Scheduler'])
## random-variable-stream.h (module 'core'): ns3::LogNormalRandomVariable [class]
module.add_class('LogNormalRandomVariable', parent=root_module['ns3::RandomVariableStream'])
## map-scheduler.h (module 'core'): ns3::MapScheduler [class]
module.add_class('MapScheduler', parent=root_module['ns3::Scheduler'])
## random-variable-stream.h (module 'core'): ns3::NormalRandomVariable [class]
module.add_class('NormalRandomVariable', parent=root_module['ns3::RandomVariableStream'])
## object-factory.h (module 'core'): ns3::ObjectFactoryChecker [class]
module.add_class('ObjectFactoryChecker', parent=root_module['ns3::AttributeChecker'])
## object-factory.h (module 'core'): ns3::ObjectFactoryValue [class]
module.add_class('ObjectFactoryValue', parent=root_module['ns3::AttributeValue'])
## object-ptr-container.h (module 'core'): ns3::ObjectPtrContainerAccessor [class]
module.add_class('ObjectPtrContainerAccessor', parent=root_module['ns3::AttributeAccessor'])
## object-ptr-container.h (module 'core'): ns3::ObjectPtrContainerChecker [class]
module.add_class('ObjectPtrContainerChecker', parent=root_module['ns3::AttributeChecker'])
## object-ptr-container.h (module 'core'): ns3::ObjectPtrContainerValue [class]
module.add_class('ObjectPtrContainerValue', parent=root_module['ns3::AttributeValue'])
## random-variable-stream.h (module 'core'): ns3::ParetoRandomVariable [class]
module.add_class('ParetoRandomVariable', parent=root_module['ns3::RandomVariableStream'])
## pointer.h (module 'core'): ns3::PointerChecker [class]
module.add_class('PointerChecker', parent=root_module['ns3::AttributeChecker'])
## pointer.h (module 'core'): ns3::PointerValue [class]
module.add_class('PointerValue', parent=root_module['ns3::AttributeValue'])
## realtime-simulator-impl.h (module 'core'): ns3::RealtimeSimulatorImpl [class]
module.add_class('RealtimeSimulatorImpl', parent=root_module['ns3::SimulatorImpl'])
## realtime-simulator-impl.h (module 'core'): ns3::RealtimeSimulatorImpl::SynchronizationMode [enumeration]
module.add_enum('SynchronizationMode', ['SYNC_BEST_EFFORT', 'SYNC_HARD_LIMIT'], outer_class=root_module['ns3::RealtimeSimulatorImpl'])
## ref-count-base.h (module 'core'): ns3::RefCountBase [class]
module.add_class('RefCountBase', parent=root_module['ns3::SimpleRefCount< ns3::RefCountBase, ns3::empty, ns3::DefaultDeleter<ns3::RefCountBase> >'])
## string.h (module 'core'): ns3::StringChecker [class]
module.add_class('StringChecker', parent=root_module['ns3::AttributeChecker'])
## string.h (module 'core'): ns3::StringValue [class]
module.add_class('StringValue', parent=root_module['ns3::AttributeValue'])
## nstime.h (module 'core'): ns3::TimeValue [class]
module.add_class('TimeValue', parent=root_module['ns3::AttributeValue'])
## type-id.h (module 'core'): ns3::TypeIdChecker [class]
module.add_class('TypeIdChecker', parent=root_module['ns3::AttributeChecker'])
## type-id.h (module 'core'): ns3::TypeIdValue [class]
module.add_class('TypeIdValue', parent=root_module['ns3::AttributeValue'])
## uinteger.h (module 'core'): ns3::UintegerValue [class]
module.add_class('UintegerValue', parent=root_module['ns3::AttributeValue'])
## vector.h (module 'core'): ns3::Vector2DChecker [class]
module.add_class('Vector2DChecker', parent=root_module['ns3::AttributeChecker'])
## vector.h (module 'core'): ns3::Vector2DValue [class]
module.add_class('Vector2DValue', parent=root_module['ns3::AttributeValue'])
## vector.h (module 'core'): ns3::Vector3DChecker [class]
module.add_class('Vector3DChecker', parent=root_module['ns3::AttributeChecker'])
## vector.h (module 'core'): ns3::Vector3DValue [class]
module.add_class('Vector3DValue', parent=root_module['ns3::AttributeValue'])
module.add_container('std::map< std::string, ns3::LogComponent * >', ('std::string', 'ns3::LogComponent *'), container_type=u'map')
typehandlers.add_type_alias(u'ns3::RngSeedManager', u'ns3::SeedManager')
typehandlers.add_type_alias(u'ns3::RngSeedManager*', u'ns3::SeedManager*')
typehandlers.add_type_alias(u'ns3::RngSeedManager&', u'ns3::SeedManager&')
module.add_typedef(root_module['ns3::RngSeedManager'], 'SeedManager')
typehandlers.add_type_alias(u'ns3::ObjectPtrContainerValue', u'ns3::ObjectVectorValue')
typehandlers.add_type_alias(u'ns3::ObjectPtrContainerValue*', u'ns3::ObjectVectorValue*')
typehandlers.add_type_alias(u'ns3::ObjectPtrContainerValue&', u'ns3::ObjectVectorValue&')
module.add_typedef(root_module['ns3::ObjectPtrContainerValue'], 'ObjectVectorValue')
typehandlers.add_type_alias(u'void ( * ) ( std::ostream & ) *', u'ns3::LogTimePrinter')
typehandlers.add_type_alias(u'void ( * ) ( std::ostream & ) **', u'ns3::LogTimePrinter*')
typehandlers.add_type_alias(u'void ( * ) ( std::ostream & ) *&', u'ns3::LogTimePrinter&')
typehandlers.add_type_alias(u'void ( * ) ( std::ostream & ) *', u'ns3::LogNodePrinter')
typehandlers.add_type_alias(u'void ( * ) ( std::ostream & ) **', u'ns3::LogNodePrinter*')
typehandlers.add_type_alias(u'void ( * ) ( std::ostream & ) *&', u'ns3::LogNodePrinter&')
typehandlers.add_type_alias(u'ns3::Vector3D', u'ns3::Vector')
typehandlers.add_type_alias(u'ns3::Vector3D*', u'ns3::Vector*')
typehandlers.add_type_alias(u'ns3::Vector3D&', u'ns3::Vector&')
module.add_typedef(root_module['ns3::Vector3D'], 'Vector')
typehandlers.add_type_alias(u'ns3::Vector3DValue', u'ns3::VectorValue')
typehandlers.add_type_alias(u'ns3::Vector3DValue*', u'ns3::VectorValue*')
typehandlers.add_type_alias(u'ns3::Vector3DValue&', u'ns3::VectorValue&')
module.add_typedef(root_module['ns3::Vector3DValue'], 'VectorValue')
typehandlers.add_type_alias(u'ns3::ObjectPtrContainerValue', u'ns3::ObjectMapValue')
typehandlers.add_type_alias(u'ns3::ObjectPtrContainerValue*', u'ns3::ObjectMapValue*')
typehandlers.add_type_alias(u'ns3::ObjectPtrContainerValue&', u'ns3::ObjectMapValue&')
module.add_typedef(root_module['ns3::ObjectPtrContainerValue'], 'ObjectMapValue')
typehandlers.add_type_alias(u'ns3::Vector3DChecker', u'ns3::VectorChecker')
typehandlers.add_type_alias(u'ns3::Vector3DChecker*', u'ns3::VectorChecker*')
typehandlers.add_type_alias(u'ns3::Vector3DChecker&', u'ns3::VectorChecker&')
module.add_typedef(root_module['ns3::Vector3DChecker'], 'VectorChecker')
## Register a nested module for the namespace CommandLineHelper
nested_module = module.add_cpp_namespace('CommandLineHelper')
register_types_ns3_CommandLineHelper(nested_module)
## Register a nested module for the namespace Config
nested_module = module.add_cpp_namespace('Config')
register_types_ns3_Config(nested_module)
## Register a nested module for the namespace FatalImpl
nested_module = module.add_cpp_namespace('FatalImpl')
register_types_ns3_FatalImpl(nested_module)
## Register a nested module for the namespace Hash
nested_module = module.add_cpp_namespace('Hash')
register_types_ns3_Hash(nested_module)
## Register a nested module for the namespace SystemPath
nested_module = module.add_cpp_namespace('SystemPath')
register_types_ns3_SystemPath(nested_module)
## Register a nested module for the namespace TracedValueCallback
nested_module = module.add_cpp_namespace('TracedValueCallback')
register_types_ns3_TracedValueCallback(nested_module)
## Register a nested module for the namespace internal
nested_module = module.add_cpp_namespace('internal')
register_types_ns3_internal(nested_module)
def register_types_ns3_CommandLineHelper(module):
root_module = module.get_root()
def register_types_ns3_Config(module):
root_module = module.get_root()
## config.h (module 'core'): ns3::Config::MatchContainer [class]
module.add_class('MatchContainer')
module.add_container('std::vector< ns3::Ptr< ns3::Object > >', 'ns3::Ptr< ns3::Object >', container_type=u'vector')
module.add_container('std::vector< std::string >', 'std::string', container_type=u'vector')
def register_types_ns3_FatalImpl(module):
root_module = module.get_root()
def register_types_ns3_Hash(module):
root_module = module.get_root()
## hash-function.h (module 'core'): ns3::Hash::Implementation [class]
module.add_class('Implementation', parent=root_module['ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >'])
typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, size_t ) *', u'ns3::Hash::Hash32Function_ptr')
typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, size_t ) **', u'ns3::Hash::Hash32Function_ptr*')
typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, size_t ) *&', u'ns3::Hash::Hash32Function_ptr&')
typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, size_t ) *', u'ns3::Hash::Hash64Function_ptr')
typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, size_t ) **', u'ns3::Hash::Hash64Function_ptr*')
typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, size_t ) *&', u'ns3::Hash::Hash64Function_ptr&')
## Register a nested module for the namespace Function
nested_module = module.add_cpp_namespace('Function')
register_types_ns3_Hash_Function(nested_module)
def register_types_ns3_Hash_Function(module):
root_module = module.get_root()
## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a [class]
module.add_class('Fnv1a', parent=root_module['ns3::Hash::Implementation'])
## hash-function.h (module 'core'): ns3::Hash::Function::Hash32 [class]
module.add_class('Hash32', parent=root_module['ns3::Hash::Implementation'])
## hash-function.h (module 'core'): ns3::Hash::Function::Hash64 [class]
module.add_class('Hash64', parent=root_module['ns3::Hash::Implementation'])
## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3 [class]
module.add_class('Murmur3', parent=root_module['ns3::Hash::Implementation'])
def register_types_ns3_SystemPath(module):
root_module = module.get_root()
module.add_container('std::list< std::string >', 'std::string', container_type=u'list')
def register_types_ns3_TracedValueCallback(module):
root_module = module.get_root()
typehandlers.add_type_alias(u'void ( * ) ( uint8_t, uint8_t ) *', u'ns3::TracedValueCallback::Uint8')
typehandlers.add_type_alias(u'void ( * ) ( uint8_t, uint8_t ) **', u'ns3::TracedValueCallback::Uint8*')
typehandlers.add_type_alias(u'void ( * ) ( uint8_t, uint8_t ) *&', u'ns3::TracedValueCallback::Uint8&')
typehandlers.add_type_alias(u'void ( * ) ( int8_t, int8_t ) *', u'ns3::TracedValueCallback::Int8')
typehandlers.add_type_alias(u'void ( * ) ( int8_t, int8_t ) **', u'ns3::TracedValueCallback::Int8*')
typehandlers.add_type_alias(u'void ( * ) ( int8_t, int8_t ) *&', u'ns3::TracedValueCallback::Int8&')
typehandlers.add_type_alias(u'void ( * ) ( double, double ) *', u'ns3::TracedValueCallback::Double')
typehandlers.add_type_alias(u'void ( * ) ( double, double ) **', u'ns3::TracedValueCallback::Double*')
typehandlers.add_type_alias(u'void ( * ) ( double, double ) *&', u'ns3::TracedValueCallback::Double&')
typehandlers.add_type_alias(u'void ( * ) ( uint32_t, uint32_t ) *', u'ns3::TracedValueCallback::Uint32')
typehandlers.add_type_alias(u'void ( * ) ( uint32_t, uint32_t ) **', u'ns3::TracedValueCallback::Uint32*')
typehandlers.add_type_alias(u'void ( * ) ( uint32_t, uint32_t ) *&', u'ns3::TracedValueCallback::Uint32&')
typehandlers.add_type_alias(u'void ( * ) ( ns3::Time, ns3::Time ) *', u'ns3::TracedValueCallback::Time')
typehandlers.add_type_alias(u'void ( * ) ( ns3::Time, ns3::Time ) **', u'ns3::TracedValueCallback::Time*')
typehandlers.add_type_alias(u'void ( * ) ( ns3::Time, ns3::Time ) *&', u'ns3::TracedValueCallback::Time&')
typehandlers.add_type_alias(u'void ( * ) ( bool, bool ) *', u'ns3::TracedValueCallback::Bool')
typehandlers.add_type_alias(u'void ( * ) ( bool, bool ) **', u'ns3::TracedValueCallback::Bool*')
typehandlers.add_type_alias(u'void ( * ) ( bool, bool ) *&', u'ns3::TracedValueCallback::Bool&')
typehandlers.add_type_alias(u'void ( * ) ( int16_t, int16_t ) *', u'ns3::TracedValueCallback::Int16')
typehandlers.add_type_alias(u'void ( * ) ( int16_t, int16_t ) **', u'ns3::TracedValueCallback::Int16*')
typehandlers.add_type_alias(u'void ( * ) ( int16_t, int16_t ) *&', u'ns3::TracedValueCallback::Int16&')
typehandlers.add_type_alias(u'void ( * ) ( int32_t, int32_t ) *', u'ns3::TracedValueCallback::Int32')
typehandlers.add_type_alias(u'void ( * ) ( int32_t, int32_t ) **', u'ns3::TracedValueCallback::Int32*')
typehandlers.add_type_alias(u'void ( * ) ( int32_t, int32_t ) *&', u'ns3::TracedValueCallback::Int32&')
typehandlers.add_type_alias(u'void ( * ) ( uint16_t, uint16_t ) *', u'ns3::TracedValueCallback::Uint16')
typehandlers.add_type_alias(u'void ( * ) ( uint16_t, uint16_t ) **', u'ns3::TracedValueCallback::Uint16*')
typehandlers.add_type_alias(u'void ( * ) ( uint16_t, uint16_t ) *&', u'ns3::TracedValueCallback::Uint16&')
def register_types_ns3_internal(module):
root_module = module.get_root()
def register_methods(root_module):
register_Ns3AttributeConstructionList_methods(root_module, root_module['ns3::AttributeConstructionList'])
register_Ns3AttributeConstructionListItem_methods(root_module, root_module['ns3::AttributeConstructionList::Item'])
register_Ns3CallbackBase_methods(root_module, root_module['ns3::CallbackBase'])
register_Ns3CommandLine_methods(root_module, root_module['ns3::CommandLine'])
register_Ns3CriticalSection_methods(root_module, root_module['ns3::CriticalSection'])
register_Ns3EventGarbageCollector_methods(root_module, root_module['ns3::EventGarbageCollector'])
register_Ns3EventId_methods(root_module, root_module['ns3::EventId'])
register_Ns3GlobalValue_methods(root_module, root_module['ns3::GlobalValue'])
register_Ns3Hasher_methods(root_module, root_module['ns3::Hasher'])
register_Ns3IntToType__0_methods(root_module, root_module['ns3::IntToType< 0 >'])
register_Ns3IntToType__1_methods(root_module, root_module['ns3::IntToType< 1 >'])
register_Ns3IntToType__2_methods(root_module, root_module['ns3::IntToType< 2 >'])
register_Ns3IntToType__3_methods(root_module, root_module['ns3::IntToType< 3 >'])
register_Ns3IntToType__4_methods(root_module, root_module['ns3::IntToType< 4 >'])
register_Ns3IntToType__5_methods(root_module, root_module['ns3::IntToType< 5 >'])
register_Ns3IntToType__6_methods(root_module, root_module['ns3::IntToType< 6 >'])
register_Ns3LogComponent_methods(root_module, root_module['ns3::LogComponent'])
register_Ns3Names_methods(root_module, root_module['ns3::Names'])
register_Ns3NonCopyable_methods(root_module, root_module['ns3::NonCopyable'])
register_Ns3ObjectBase_methods(root_module, root_module['ns3::ObjectBase'])
register_Ns3ObjectDeleter_methods(root_module, root_module['ns3::ObjectDeleter'])
register_Ns3ObjectFactory_methods(root_module, root_module['ns3::ObjectFactory'])
register_Ns3ParameterLogger_methods(root_module, root_module['ns3::ParameterLogger'])
register_Ns3RandomVariableStreamHelper_methods(root_module, root_module['ns3::RandomVariableStreamHelper'])
register_Ns3RngSeedManager_methods(root_module, root_module['ns3::RngSeedManager'])
register_Ns3RngStream_methods(root_module, root_module['ns3::RngStream'])
register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >'])
register_Ns3Simulator_methods(root_module, root_module['ns3::Simulator'])
register_Ns3SystemCondition_methods(root_module, root_module['ns3::SystemCondition'])
register_Ns3SystemMutex_methods(root_module, root_module['ns3::SystemMutex'])
register_Ns3SystemWallClockMs_methods(root_module, root_module['ns3::SystemWallClockMs'])
register_Ns3TimeWithUnit_methods(root_module, root_module['ns3::TimeWithUnit'])
register_Ns3Timer_methods(root_module, root_module['ns3::Timer'])
register_Ns3TimerImpl_methods(root_module, root_module['ns3::TimerImpl'])
register_Ns3TypeId_methods(root_module, root_module['ns3::TypeId'])
register_Ns3TypeIdAttributeInformation_methods(root_module, root_module['ns3::TypeId::AttributeInformation'])
register_Ns3TypeIdTraceSourceInformation_methods(root_module, root_module['ns3::TypeId::TraceSourceInformation'])
register_Ns3Vector2D_methods(root_module, root_module['ns3::Vector2D'])
register_Ns3Vector3D_methods(root_module, root_module['ns3::Vector3D'])
register_Ns3Watchdog_methods(root_module, root_module['ns3::Watchdog'])
register_Ns3Empty_methods(root_module, root_module['ns3::empty'])
register_Ns3Int64x64_t_methods(root_module, root_module['ns3::int64x64_t'])
register_Ns3Object_methods(root_module, root_module['ns3::Object'])
register_Ns3ObjectAggregateIterator_methods(root_module, root_module['ns3::Object::AggregateIterator'])
register_Ns3RandomVariableStream_methods(root_module, root_module['ns3::RandomVariableStream'])
register_Ns3Scheduler_methods(root_module, root_module['ns3::Scheduler'])
register_Ns3SchedulerEvent_methods(root_module, root_module['ns3::Scheduler::Event'])
register_Ns3SchedulerEventKey_methods(root_module, root_module['ns3::Scheduler::EventKey'])
register_Ns3SequentialRandomVariable_methods(root_module, root_module['ns3::SequentialRandomVariable'])
register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >'])
register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >'])
register_Ns3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >'])
register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >'])
register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >'])
register_Ns3SimpleRefCount__Ns3FdReader_Ns3Empty_Ns3DefaultDeleter__lt__ns3FdReader__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::FdReader, ns3::empty, ns3::DefaultDeleter<ns3::FdReader> >'])
register_Ns3SimpleRefCount__Ns3HashImplementation_Ns3Empty_Ns3DefaultDeleter__lt__ns3HashImplementation__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >'])
register_Ns3SimpleRefCount__Ns3RefCountBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3RefCountBase__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::RefCountBase, ns3::empty, ns3::DefaultDeleter<ns3::RefCountBase> >'])
register_Ns3SimpleRefCount__Ns3SystemThread_Ns3Empty_Ns3DefaultDeleter__lt__ns3SystemThread__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::SystemThread, ns3::empty, ns3::DefaultDeleter<ns3::SystemThread> >'])
register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >'])
register_Ns3SimulatorImpl_methods(root_module, root_module['ns3::SimulatorImpl'])
register_Ns3Synchronizer_methods(root_module, root_module['ns3::Synchronizer'])
register_Ns3SystemThread_methods(root_module, root_module['ns3::SystemThread'])
register_Ns3Time_methods(root_module, root_module['ns3::Time'])
register_Ns3TraceSourceAccessor_methods(root_module, root_module['ns3::TraceSourceAccessor'])
register_Ns3TriangularRandomVariable_methods(root_module, root_module['ns3::TriangularRandomVariable'])
register_Ns3UniformRandomVariable_methods(root_module, root_module['ns3::UniformRandomVariable'])
register_Ns3WallClockSynchronizer_methods(root_module, root_module['ns3::WallClockSynchronizer'])
register_Ns3WeibullRandomVariable_methods(root_module, root_module['ns3::WeibullRandomVariable'])
register_Ns3ZetaRandomVariable_methods(root_module, root_module['ns3::ZetaRandomVariable'])
register_Ns3ZipfRandomVariable_methods(root_module, root_module['ns3::ZipfRandomVariable'])
register_Ns3AttributeAccessor_methods(root_module, root_module['ns3::AttributeAccessor'])
register_Ns3AttributeChecker_methods(root_module, root_module['ns3::AttributeChecker'])
register_Ns3AttributeValue_methods(root_module, root_module['ns3::AttributeValue'])
register_Ns3BooleanChecker_methods(root_module, root_module['ns3::BooleanChecker'])
register_Ns3BooleanValue_methods(root_module, root_module['ns3::BooleanValue'])
register_Ns3CalendarScheduler_methods(root_module, root_module['ns3::CalendarScheduler'])
register_Ns3CallbackChecker_methods(root_module, root_module['ns3::CallbackChecker'])
register_Ns3CallbackImplBase_methods(root_module, root_module['ns3::CallbackImplBase'])
register_Ns3CallbackValue_methods(root_module, root_module['ns3::CallbackValue'])
register_Ns3ConstantRandomVariable_methods(root_module, root_module['ns3::ConstantRandomVariable'])
register_Ns3DefaultSimulatorImpl_methods(root_module, root_module['ns3::DefaultSimulatorImpl'])
register_Ns3DeterministicRandomVariable_methods(root_module, root_module['ns3::DeterministicRandomVariable'])
register_Ns3DoubleValue_methods(root_module, root_module['ns3::DoubleValue'])
register_Ns3EmpiricalRandomVariable_methods(root_module, root_module['ns3::EmpiricalRandomVariable'])
register_Ns3EmptyAttributeValue_methods(root_module, root_module['ns3::EmptyAttributeValue'])
register_Ns3EnumChecker_methods(root_module, root_module['ns3::EnumChecker'])
register_Ns3EnumValue_methods(root_module, root_module['ns3::EnumValue'])
register_Ns3ErlangRandomVariable_methods(root_module, root_module['ns3::ErlangRandomVariable'])
register_Ns3EventImpl_methods(root_module, root_module['ns3::EventImpl'])
register_Ns3ExponentialRandomVariable_methods(root_module, root_module['ns3::ExponentialRandomVariable'])
register_Ns3FdReader_methods(root_module, root_module['ns3::FdReader'])
register_Ns3GammaRandomVariable_methods(root_module, root_module['ns3::GammaRandomVariable'])
register_Ns3HeapScheduler_methods(root_module, root_module['ns3::HeapScheduler'])
register_Ns3IntegerValue_methods(root_module, root_module['ns3::IntegerValue'])
register_Ns3ListScheduler_methods(root_module, root_module['ns3::ListScheduler'])
register_Ns3LogNormalRandomVariable_methods(root_module, root_module['ns3::LogNormalRandomVariable'])
register_Ns3MapScheduler_methods(root_module, root_module['ns3::MapScheduler'])
register_Ns3NormalRandomVariable_methods(root_module, root_module['ns3::NormalRandomVariable'])
register_Ns3ObjectFactoryChecker_methods(root_module, root_module['ns3::ObjectFactoryChecker'])
register_Ns3ObjectFactoryValue_methods(root_module, root_module['ns3::ObjectFactoryValue'])
register_Ns3ObjectPtrContainerAccessor_methods(root_module, root_module['ns3::ObjectPtrContainerAccessor'])
register_Ns3ObjectPtrContainerChecker_methods(root_module, root_module['ns3::ObjectPtrContainerChecker'])
register_Ns3ObjectPtrContainerValue_methods(root_module, root_module['ns3::ObjectPtrContainerValue'])
register_Ns3ParetoRandomVariable_methods(root_module, root_module['ns3::ParetoRandomVariable'])
register_Ns3PointerChecker_methods(root_module, root_module['ns3::PointerChecker'])
register_Ns3PointerValue_methods(root_module, root_module['ns3::PointerValue'])
register_Ns3RealtimeSimulatorImpl_methods(root_module, root_module['ns3::RealtimeSimulatorImpl'])
register_Ns3RefCountBase_methods(root_module, root_module['ns3::RefCountBase'])
register_Ns3StringChecker_methods(root_module, root_module['ns3::StringChecker'])
register_Ns3StringValue_methods(root_module, root_module['ns3::StringValue'])
register_Ns3TimeValue_methods(root_module, root_module['ns3::TimeValue'])
register_Ns3TypeIdChecker_methods(root_module, root_module['ns3::TypeIdChecker'])
register_Ns3TypeIdValue_methods(root_module, root_module['ns3::TypeIdValue'])
register_Ns3UintegerValue_methods(root_module, root_module['ns3::UintegerValue'])
register_Ns3Vector2DChecker_methods(root_module, root_module['ns3::Vector2DChecker'])
register_Ns3Vector2DValue_methods(root_module, root_module['ns3::Vector2DValue'])
register_Ns3Vector3DChecker_methods(root_module, root_module['ns3::Vector3DChecker'])
register_Ns3Vector3DValue_methods(root_module, root_module['ns3::Vector3DValue'])
register_Ns3ConfigMatchContainer_methods(root_module, root_module['ns3::Config::MatchContainer'])
register_Ns3HashImplementation_methods(root_module, root_module['ns3::Hash::Implementation'])
register_Ns3HashFunctionFnv1a_methods(root_module, root_module['ns3::Hash::Function::Fnv1a'])
register_Ns3HashFunctionHash32_methods(root_module, root_module['ns3::Hash::Function::Hash32'])
register_Ns3HashFunctionHash64_methods(root_module, root_module['ns3::Hash::Function::Hash64'])
register_Ns3HashFunctionMurmur3_methods(root_module, root_module['ns3::Hash::Function::Murmur3'])
return
def register_Ns3AttributeConstructionList_methods(root_module, cls):
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList(ns3::AttributeConstructionList const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AttributeConstructionList const &', 'arg0')])
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList() [constructor]
cls.add_constructor([])
## attribute-construction-list.h (module 'core'): void ns3::AttributeConstructionList::Add(std::string name, ns3::Ptr<ns3::AttributeChecker const> checker, ns3::Ptr<ns3::AttributeValue> value) [member function]
cls.add_method('Add',
'void',
[param('std::string', 'name'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker'), param('ns3::Ptr< ns3::AttributeValue >', 'value')])
## attribute-construction-list.h (module 'core'): std::_List_const_iterator<ns3::AttributeConstructionList::Item> ns3::AttributeConstructionList::Begin() const [member function]
cls.add_method('Begin',
'std::_List_const_iterator< ns3::AttributeConstructionList::Item >',
[],
is_const=True)
## attribute-construction-list.h (module 'core'): std::_List_const_iterator<ns3::AttributeConstructionList::Item> ns3::AttributeConstructionList::End() const [member function]
cls.add_method('End',
'std::_List_const_iterator< ns3::AttributeConstructionList::Item >',
[],
is_const=True)
## attribute-construction-list.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeConstructionList::Find(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('Find',
'ns3::Ptr< ns3::AttributeValue >',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True)
return
def register_Ns3AttributeConstructionListItem_methods(root_module, cls):
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item() [constructor]
cls.add_constructor([])
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item(ns3::AttributeConstructionList::Item const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AttributeConstructionList::Item const &', 'arg0')])
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::checker [variable]
cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False)
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::name [variable]
cls.add_instance_attribute('name', 'std::string', is_const=False)
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::value [variable]
cls.add_instance_attribute('value', 'ns3::Ptr< ns3::AttributeValue >', is_const=False)
return
def register_Ns3CallbackBase_methods(root_module, cls):
## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::CallbackBase const & arg0) [copy constructor]
cls.add_constructor([param('ns3::CallbackBase const &', 'arg0')])
## callback.h (module 'core'): ns3::CallbackBase::CallbackBase() [constructor]
cls.add_constructor([])
## callback.h (module 'core'): ns3::Ptr<ns3::CallbackImplBase> ns3::CallbackBase::GetImpl() const [member function]
cls.add_method('GetImpl',
'ns3::Ptr< ns3::CallbackImplBase >',
[],
is_const=True)
## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::Ptr<ns3::CallbackImplBase> impl) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::CallbackImplBase >', 'impl')],
visibility='protected')
return
def register_Ns3CommandLine_methods(root_module, cls):
cls.add_output_stream_operator()
## command-line.h (module 'core'): ns3::CommandLine::CommandLine() [constructor]
cls.add_constructor([])
## command-line.h (module 'core'): ns3::CommandLine::CommandLine(ns3::CommandLine const & cmd) [copy constructor]
cls.add_constructor([param('ns3::CommandLine const &', 'cmd')])
## command-line.h (module 'core'): void ns3::CommandLine::AddValue(std::string const & name, std::string const & help, ns3::Callback<bool, std::string, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function]
cls.add_method('AddValue',
'void',
[param('std::string const &', 'name'), param('std::string const &', 'help'), param('ns3::Callback< bool, std::string, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')])
## command-line.h (module 'core'): void ns3::CommandLine::AddValue(std::string const & name, std::string const & attributePath) [member function]
cls.add_method('AddValue',
'void',
[param('std::string const &', 'name'), param('std::string const &', 'attributePath')])
## command-line.h (module 'core'): std::string ns3::CommandLine::GetName() const [member function]
cls.add_method('GetName',
'std::string',
[],
is_const=True)
## command-line.h (module 'core'): void ns3::CommandLine::Parse(int argc, char * * argv) [member function]
cls.add_method('Parse',
'void',
[param('int', 'argc'), param('char * *', 'argv')])
## command-line.h (module 'core'): void ns3::CommandLine::PrintHelp(std::ostream & os) const [member function]
cls.add_method('PrintHelp',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## command-line.h (module 'core'): void ns3::CommandLine::Usage(std::string const usage) [member function]
cls.add_method('Usage',
'void',
[param('std::string const', 'usage')])
return
def register_Ns3CriticalSection_methods(root_module, cls):
## system-mutex.h (module 'core'): ns3::CriticalSection::CriticalSection(ns3::CriticalSection const & arg0) [copy constructor]
cls.add_constructor([param('ns3::CriticalSection const &', 'arg0')])
## system-mutex.h (module 'core'): ns3::CriticalSection::CriticalSection(ns3::SystemMutex & mutex) [constructor]
cls.add_constructor([param('ns3::SystemMutex &', 'mutex')])
return
def register_Ns3EventGarbageCollector_methods(root_module, cls):
## event-garbage-collector.h (module 'core'): ns3::EventGarbageCollector::EventGarbageCollector(ns3::EventGarbageCollector const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EventGarbageCollector const &', 'arg0')])
## event-garbage-collector.h (module 'core'): ns3::EventGarbageCollector::EventGarbageCollector() [constructor]
cls.add_constructor([])
## event-garbage-collector.h (module 'core'): void ns3::EventGarbageCollector::Track(ns3::EventId event) [member function]
cls.add_method('Track',
'void',
[param('ns3::EventId', 'event')])
return
def register_Ns3EventId_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_binary_comparison_operator('==')
## event-id.h (module 'core'): ns3::EventId::EventId(ns3::EventId const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EventId const &', 'arg0')])
## event-id.h (module 'core'): ns3::EventId::EventId() [constructor]
cls.add_constructor([])
## event-id.h (module 'core'): ns3::EventId::EventId(ns3::Ptr<ns3::EventImpl> const & impl, uint64_t ts, uint32_t context, uint32_t uid) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::EventImpl > const &', 'impl'), param('uint64_t', 'ts'), param('uint32_t', 'context'), param('uint32_t', 'uid')])
## event-id.h (module 'core'): void ns3::EventId::Cancel() [member function]
cls.add_method('Cancel',
'void',
[])
## event-id.h (module 'core'): uint32_t ns3::EventId::GetContext() const [member function]
cls.add_method('GetContext',
'uint32_t',
[],
is_const=True)
## event-id.h (module 'core'): uint64_t ns3::EventId::GetTs() const [member function]
cls.add_method('GetTs',
'uint64_t',
[],
is_const=True)
## event-id.h (module 'core'): uint32_t ns3::EventId::GetUid() const [member function]
cls.add_method('GetUid',
'uint32_t',
[],
is_const=True)
## event-id.h (module 'core'): bool ns3::EventId::IsExpired() const [member function]
cls.add_method('IsExpired',
'bool',
[],
is_const=True)
## event-id.h (module 'core'): bool ns3::EventId::IsRunning() const [member function]
cls.add_method('IsRunning',
'bool',
[],
is_const=True)
## event-id.h (module 'core'): ns3::EventImpl * ns3::EventId::PeekEventImpl() const [member function]
cls.add_method('PeekEventImpl',
'ns3::EventImpl *',
[],
is_const=True)
return
def register_Ns3GlobalValue_methods(root_module, cls):
## global-value.h (module 'core'): ns3::GlobalValue::GlobalValue(ns3::GlobalValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::GlobalValue const &', 'arg0')])
## global-value.h (module 'core'): ns3::GlobalValue::GlobalValue(std::string name, std::string help, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeChecker const> checker) [constructor]
cls.add_constructor([param('std::string', 'name'), param('std::string', 'help'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')])
## global-value.h (module 'core'): static __gnu_cxx::__normal_iterator<ns3::GlobalValue* const*,std::vector<ns3::GlobalValue*, std::allocator<ns3::GlobalValue*> > > ns3::GlobalValue::Begin() [member function]
cls.add_method('Begin',
'__gnu_cxx::__normal_iterator< ns3::GlobalValue * const *, std::vector< ns3::GlobalValue * > >',
[],
is_static=True)
## global-value.h (module 'core'): static void ns3::GlobalValue::Bind(std::string name, ns3::AttributeValue const & value) [member function]
cls.add_method('Bind',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')],
is_static=True)
## global-value.h (module 'core'): static bool ns3::GlobalValue::BindFailSafe(std::string name, ns3::AttributeValue const & value) [member function]
cls.add_method('BindFailSafe',
'bool',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')],
is_static=True)
## global-value.h (module 'core'): static __gnu_cxx::__normal_iterator<ns3::GlobalValue* const*,std::vector<ns3::GlobalValue*, std::allocator<ns3::GlobalValue*> > > ns3::GlobalValue::End() [member function]
cls.add_method('End',
'__gnu_cxx::__normal_iterator< ns3::GlobalValue * const *, std::vector< ns3::GlobalValue * > >',
[],
is_static=True)
## global-value.h (module 'core'): ns3::Ptr<ns3::AttributeChecker const> ns3::GlobalValue::GetChecker() const [member function]
cls.add_method('GetChecker',
'ns3::Ptr< ns3::AttributeChecker const >',
[],
is_const=True)
## global-value.h (module 'core'): std::string ns3::GlobalValue::GetHelp() const [member function]
cls.add_method('GetHelp',
'std::string',
[],
is_const=True)
## global-value.h (module 'core'): std::string ns3::GlobalValue::GetName() const [member function]
cls.add_method('GetName',
'std::string',
[],
is_const=True)
## global-value.h (module 'core'): void ns3::GlobalValue::GetValue(ns3::AttributeValue & value) const [member function]
cls.add_method('GetValue',
'void',
[param('ns3::AttributeValue &', 'value')],
is_const=True)
## global-value.h (module 'core'): static void ns3::GlobalValue::GetValueByName(std::string name, ns3::AttributeValue & value) [member function]
cls.add_method('GetValueByName',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue &', 'value')],
is_static=True)
## global-value.h (module 'core'): static bool ns3::GlobalValue::GetValueByNameFailSafe(std::string name, ns3::AttributeValue & value) [member function]
cls.add_method('GetValueByNameFailSafe',
'bool',
[param('std::string', 'name'), param('ns3::AttributeValue &', 'value')],
is_static=True)
## global-value.h (module 'core'): void ns3::GlobalValue::ResetInitialValue() [member function]
cls.add_method('ResetInitialValue',
'void',
[])
## global-value.h (module 'core'): bool ns3::GlobalValue::SetValue(ns3::AttributeValue const & value) [member function]
cls.add_method('SetValue',
'bool',
[param('ns3::AttributeValue const &', 'value')])
return
def register_Ns3Hasher_methods(root_module, cls):
## hash.h (module 'core'): ns3::Hasher::Hasher(ns3::Hasher const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Hasher const &', 'arg0')])
## hash.h (module 'core'): ns3::Hasher::Hasher() [constructor]
cls.add_constructor([])
## hash.h (module 'core'): ns3::Hasher::Hasher(ns3::Ptr<ns3::Hash::Implementation> hp) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::Hash::Implementation >', 'hp')])
## hash.h (module 'core'): uint32_t ns3::Hasher::GetHash32(char const * buffer, size_t const size) [member function]
cls.add_method('GetHash32',
'uint32_t',
[param('char const *', 'buffer'), param('size_t const', 'size')])
## hash.h (module 'core'): uint32_t ns3::Hasher::GetHash32(std::string const s) [member function]
cls.add_method('GetHash32',
'uint32_t',
[param('std::string const', 's')])
## hash.h (module 'core'): uint64_t ns3::Hasher::GetHash64(char const * buffer, size_t const size) [member function]
cls.add_method('GetHash64',
'uint64_t',
[param('char const *', 'buffer'), param('size_t const', 'size')])
## hash.h (module 'core'): uint64_t ns3::Hasher::GetHash64(std::string const s) [member function]
cls.add_method('GetHash64',
'uint64_t',
[param('std::string const', 's')])
## hash.h (module 'core'): ns3::Hasher & ns3::Hasher::clear() [member function]
cls.add_method('clear',
'ns3::Hasher &',
[])
return
def register_Ns3IntToType__0_methods(root_module, cls):
## int-to-type.h (module 'core'): ns3::IntToType<0>::IntToType() [constructor]
cls.add_constructor([])
## int-to-type.h (module 'core'): ns3::IntToType<0>::IntToType(ns3::IntToType<0> const & arg0) [copy constructor]
cls.add_constructor([param('ns3::IntToType< 0 > const &', 'arg0')])
return
def register_Ns3IntToType__1_methods(root_module, cls):
## int-to-type.h (module 'core'): ns3::IntToType<1>::IntToType() [constructor]
cls.add_constructor([])
## int-to-type.h (module 'core'): ns3::IntToType<1>::IntToType(ns3::IntToType<1> const & arg0) [copy constructor]
cls.add_constructor([param('ns3::IntToType< 1 > const &', 'arg0')])
return
def register_Ns3IntToType__2_methods(root_module, cls):
## int-to-type.h (module 'core'): ns3::IntToType<2>::IntToType() [constructor]
cls.add_constructor([])
## int-to-type.h (module 'core'): ns3::IntToType<2>::IntToType(ns3::IntToType<2> const & arg0) [copy constructor]
cls.add_constructor([param('ns3::IntToType< 2 > const &', 'arg0')])
return
def register_Ns3IntToType__3_methods(root_module, cls):
## int-to-type.h (module 'core'): ns3::IntToType<3>::IntToType() [constructor]
cls.add_constructor([])
## int-to-type.h (module 'core'): ns3::IntToType<3>::IntToType(ns3::IntToType<3> const & arg0) [copy constructor]
cls.add_constructor([param('ns3::IntToType< 3 > const &', 'arg0')])
return
def register_Ns3IntToType__4_methods(root_module, cls):
## int-to-type.h (module 'core'): ns3::IntToType<4>::IntToType() [constructor]
cls.add_constructor([])
## int-to-type.h (module 'core'): ns3::IntToType<4>::IntToType(ns3::IntToType<4> const & arg0) [copy constructor]
cls.add_constructor([param('ns3::IntToType< 4 > const &', 'arg0')])
return
def register_Ns3IntToType__5_methods(root_module, cls):
## int-to-type.h (module 'core'): ns3::IntToType<5>::IntToType() [constructor]
cls.add_constructor([])
## int-to-type.h (module 'core'): ns3::IntToType<5>::IntToType(ns3::IntToType<5> const & arg0) [copy constructor]
cls.add_constructor([param('ns3::IntToType< 5 > const &', 'arg0')])
return
def register_Ns3IntToType__6_methods(root_module, cls):
## int-to-type.h (module 'core'): ns3::IntToType<6>::IntToType() [constructor]
cls.add_constructor([])
## int-to-type.h (module 'core'): ns3::IntToType<6>::IntToType(ns3::IntToType<6> const & arg0) [copy constructor]
cls.add_constructor([param('ns3::IntToType< 6 > const &', 'arg0')])
return
def register_Ns3LogComponent_methods(root_module, cls):
## log.h (module 'core'): ns3::LogComponent::LogComponent(ns3::LogComponent const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LogComponent const &', 'arg0')])
## log.h (module 'core'): ns3::LogComponent::LogComponent(std::string const & name, std::string const & file, ns3::LogLevel const mask=::ns3::LOG_NONE) [constructor]
cls.add_constructor([param('std::string const &', 'name'), param('std::string const &', 'file'), param('ns3::LogLevel const', 'mask', default_value='::ns3::LOG_NONE')])
## log.h (module 'core'): void ns3::LogComponent::Disable(ns3::LogLevel const level) [member function]
cls.add_method('Disable',
'void',
[param('ns3::LogLevel const', 'level')])
## log.h (module 'core'): void ns3::LogComponent::Enable(ns3::LogLevel const level) [member function]
cls.add_method('Enable',
'void',
[param('ns3::LogLevel const', 'level')])
## log.h (module 'core'): std::string ns3::LogComponent::File() const [member function]
cls.add_method('File',
'std::string',
[],
is_const=True)
## log.h (module 'core'): static std::map<std::basic_string<char, std::char_traits<char>, std::allocator<char> >,ns3::LogComponent*,std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >,std::allocator<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, ns3::LogComponent*> > > * ns3::LogComponent::GetComponentList() [member function]
cls.add_method('GetComponentList',
'std::map< std::string, ns3::LogComponent * > *',
[],
is_static=True)
## log.h (module 'core'): static std::string ns3::LogComponent::GetLevelLabel(ns3::LogLevel const level) [member function]
cls.add_method('GetLevelLabel',
'std::string',
[param('ns3::LogLevel const', 'level')],
is_static=True)
## log.h (module 'core'): bool ns3::LogComponent::IsEnabled(ns3::LogLevel const level) const [member function]
cls.add_method('IsEnabled',
'bool',
[param('ns3::LogLevel const', 'level')],
is_const=True)
## log.h (module 'core'): bool ns3::LogComponent::IsNoneEnabled() const [member function]
cls.add_method('IsNoneEnabled',
'bool',
[],
is_const=True)
## log.h (module 'core'): char const * ns3::LogComponent::Name() const [member function]
cls.add_method('Name',
'char const *',
[],
is_const=True)
## log.h (module 'core'): void ns3::LogComponent::SetMask(ns3::LogLevel const level) [member function]
cls.add_method('SetMask',
'void',
[param('ns3::LogLevel const', 'level')])
return
def register_Ns3Names_methods(root_module, cls):
## names.h (module 'core'): ns3::Names::Names() [constructor]
cls.add_constructor([])
## names.h (module 'core'): ns3::Names::Names(ns3::Names const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Names const &', 'arg0')])
## names.h (module 'core'): static void ns3::Names::Add(std::string name, ns3::Ptr<ns3::Object> object) [member function]
cls.add_method('Add',
'void',
[param('std::string', 'name'), param('ns3::Ptr< ns3::Object >', 'object')],
is_static=True)
## names.h (module 'core'): static void ns3::Names::Add(std::string path, std::string name, ns3::Ptr<ns3::Object> object) [member function]
cls.add_method('Add',
'void',
[param('std::string', 'path'), param('std::string', 'name'), param('ns3::Ptr< ns3::Object >', 'object')],
is_static=True)
## names.h (module 'core'): static void ns3::Names::Add(ns3::Ptr<ns3::Object> context, std::string name, ns3::Ptr<ns3::Object> object) [member function]
cls.add_method('Add',
'void',
[param('ns3::Ptr< ns3::Object >', 'context'), param('std::string', 'name'), param('ns3::Ptr< ns3::Object >', 'object')],
is_static=True)
## names.h (module 'core'): static void ns3::Names::Clear() [member function]
cls.add_method('Clear',
'void',
[],
is_static=True)
## names.h (module 'core'): static std::string ns3::Names::FindName(ns3::Ptr<ns3::Object> object) [member function]
cls.add_method('FindName',
'std::string',
[param('ns3::Ptr< ns3::Object >', 'object')],
is_static=True)
## names.h (module 'core'): static std::string ns3::Names::FindPath(ns3::Ptr<ns3::Object> object) [member function]
cls.add_method('FindPath',
'std::string',
[param('ns3::Ptr< ns3::Object >', 'object')],
is_static=True)
## names.h (module 'core'): static void ns3::Names::Rename(std::string oldpath, std::string newname) [member function]
cls.add_method('Rename',
'void',
[param('std::string', 'oldpath'), param('std::string', 'newname')],
is_static=True)
## names.h (module 'core'): static void ns3::Names::Rename(std::string path, std::string oldname, std::string newname) [member function]
cls.add_method('Rename',
'void',
[param('std::string', 'path'), param('std::string', 'oldname'), param('std::string', 'newname')],
is_static=True)
## names.h (module 'core'): static void ns3::Names::Rename(ns3::Ptr<ns3::Object> context, std::string oldname, std::string newname) [member function]
cls.add_method('Rename',
'void',
[param('ns3::Ptr< ns3::Object >', 'context'), param('std::string', 'oldname'), param('std::string', 'newname')],
is_static=True)
return
def register_Ns3NonCopyable_methods(root_module, cls):
## non-copyable.h (module 'core'): ns3::NonCopyable::NonCopyable() [constructor]
cls.add_constructor([],
visibility='protected')
return
def register_Ns3ObjectBase_methods(root_module, cls):
## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase() [constructor]
cls.add_constructor([])
## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase(ns3::ObjectBase const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ObjectBase const &', 'arg0')])
## object-base.h (module 'core'): void ns3::ObjectBase::GetAttribute(std::string name, ns3::AttributeValue & value) const [member function]
cls.add_method('GetAttribute',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue &', 'value')],
is_const=True)
## object-base.h (module 'core'): bool ns3::ObjectBase::GetAttributeFailSafe(std::string name, ns3::AttributeValue & value) const [member function]
cls.add_method('GetAttributeFailSafe',
'bool',
[param('std::string', 'name'), param('ns3::AttributeValue &', 'value')],
is_const=True)
## object-base.h (module 'core'): ns3::TypeId ns3::ObjectBase::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## object-base.h (module 'core'): static ns3::TypeId ns3::ObjectBase::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## object-base.h (module 'core'): void ns3::ObjectBase::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function]
cls.add_method('SetAttribute',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
## object-base.h (module 'core'): bool ns3::ObjectBase::SetAttributeFailSafe(std::string name, ns3::AttributeValue const & value) [member function]
cls.add_method('SetAttributeFailSafe',
'bool',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function]
cls.add_method('TraceConnect',
'bool',
[param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')])
## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function]
cls.add_method('TraceConnectWithoutContext',
'bool',
[param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')])
## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function]
cls.add_method('TraceDisconnect',
'bool',
[param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')])
## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function]
cls.add_method('TraceDisconnectWithoutContext',
'bool',
[param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')])
## object-base.h (module 'core'): void ns3::ObjectBase::ConstructSelf(ns3::AttributeConstructionList const & attributes) [member function]
cls.add_method('ConstructSelf',
'void',
[param('ns3::AttributeConstructionList const &', 'attributes')],
visibility='protected')
## object-base.h (module 'core'): void ns3::ObjectBase::NotifyConstructionCompleted() [member function]
cls.add_method('NotifyConstructionCompleted',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3ObjectDeleter_methods(root_module, cls):
## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter() [constructor]
cls.add_constructor([])
## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter(ns3::ObjectDeleter const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ObjectDeleter const &', 'arg0')])
## object.h (module 'core'): static void ns3::ObjectDeleter::Delete(ns3::Object * object) [member function]
cls.add_method('Delete',
'void',
[param('ns3::Object *', 'object')],
is_static=True)
return
def register_Ns3ObjectFactory_methods(root_module, cls):
cls.add_output_stream_operator()
## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(ns3::ObjectFactory const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ObjectFactory const &', 'arg0')])
## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory() [constructor]
cls.add_constructor([])
## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(std::string typeId) [constructor]
cls.add_constructor([param('std::string', 'typeId')])
## object-factory.h (module 'core'): ns3::Ptr<ns3::Object> ns3::ObjectFactory::Create() const [member function]
cls.add_method('Create',
'ns3::Ptr< ns3::Object >',
[],
is_const=True)
## object-factory.h (module 'core'): ns3::TypeId ns3::ObjectFactory::GetTypeId() const [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_const=True)
## object-factory.h (module 'core'): void ns3::ObjectFactory::Set(std::string name, ns3::AttributeValue const & value) [member function]
cls.add_method('Set',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(ns3::TypeId tid) [member function]
cls.add_method('SetTypeId',
'void',
[param('ns3::TypeId', 'tid')])
## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(char const * tid) [member function]
cls.add_method('SetTypeId',
'void',
[param('char const *', 'tid')])
## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(std::string tid) [member function]
cls.add_method('SetTypeId',
'void',
[param('std::string', 'tid')])
return
def register_Ns3ParameterLogger_methods(root_module, cls):
## log.h (module 'core'): ns3::ParameterLogger::ParameterLogger(ns3::ParameterLogger const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ParameterLogger const &', 'arg0')])
## log.h (module 'core'): ns3::ParameterLogger::ParameterLogger(std::ostream & os) [constructor]
cls.add_constructor([param('std::ostream &', 'os')])
return
def register_Ns3RandomVariableStreamHelper_methods(root_module, cls):
## random-variable-stream-helper.h (module 'core'): ns3::RandomVariableStreamHelper::RandomVariableStreamHelper() [constructor]
cls.add_constructor([])
## random-variable-stream-helper.h (module 'core'): ns3::RandomVariableStreamHelper::RandomVariableStreamHelper(ns3::RandomVariableStreamHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::RandomVariableStreamHelper const &', 'arg0')])
## random-variable-stream-helper.h (module 'core'): static int64_t ns3::RandomVariableStreamHelper::AssignStreams(std::string path, int64_t stream) [member function]
cls.add_method('AssignStreams',
'int64_t',
[param('std::string', 'path'), param('int64_t', 'stream')],
is_static=True)
return
def register_Ns3RngSeedManager_methods(root_module, cls):
## rng-seed-manager.h (module 'core'): ns3::RngSeedManager::RngSeedManager() [constructor]
cls.add_constructor([])
## rng-seed-manager.h (module 'core'): ns3::RngSeedManager::RngSeedManager(ns3::RngSeedManager const & arg0) [copy constructor]
cls.add_constructor([param('ns3::RngSeedManager const &', 'arg0')])
## rng-seed-manager.h (module 'core'): static uint64_t ns3::RngSeedManager::GetNextStreamIndex() [member function]
cls.add_method('GetNextStreamIndex',
'uint64_t',
[],
is_static=True)
## rng-seed-manager.h (module 'core'): static uint64_t ns3::RngSeedManager::GetRun() [member function]
cls.add_method('GetRun',
'uint64_t',
[],
is_static=True)
## rng-seed-manager.h (module 'core'): static uint32_t ns3::RngSeedManager::GetSeed() [member function]
cls.add_method('GetSeed',
'uint32_t',
[],
is_static=True)
## rng-seed-manager.h (module 'core'): static void ns3::RngSeedManager::SetRun(uint64_t run) [member function]
cls.add_method('SetRun',
'void',
[param('uint64_t', 'run')],
is_static=True)
## rng-seed-manager.h (module 'core'): static void ns3::RngSeedManager::SetSeed(uint32_t seed) [member function]
cls.add_method('SetSeed',
'void',
[param('uint32_t', 'seed')],
is_static=True)
return
def register_Ns3RngStream_methods(root_module, cls):
## rng-stream.h (module 'core'): ns3::RngStream::RngStream(uint32_t seed, uint64_t stream, uint64_t substream) [constructor]
cls.add_constructor([param('uint32_t', 'seed'), param('uint64_t', 'stream'), param('uint64_t', 'substream')])
## rng-stream.h (module 'core'): ns3::RngStream::RngStream(ns3::RngStream const & r) [copy constructor]
cls.add_constructor([param('ns3::RngStream const &', 'r')])
## rng-stream.h (module 'core'): double ns3::RngStream::RandU01() [member function]
cls.add_method('RandU01',
'double',
[])
return
def register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount(ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3Simulator_methods(root_module, cls):
## simulator.h (module 'core'): ns3::Simulator::Simulator(ns3::Simulator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Simulator const &', 'arg0')])
## simulator.h (module 'core'): static void ns3::Simulator::Cancel(ns3::EventId const & id) [member function]
cls.add_method('Cancel',
'void',
[param('ns3::EventId const &', 'id')],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::Destroy() [member function]
cls.add_method('Destroy',
'void',
[],
is_static=True)
## simulator.h (module 'core'): static uint32_t ns3::Simulator::GetContext() [member function]
cls.add_method('GetContext',
'uint32_t',
[],
is_static=True)
## simulator.h (module 'core'): static ns3::Time ns3::Simulator::GetDelayLeft(ns3::EventId const & id) [member function]
cls.add_method('GetDelayLeft',
'ns3::Time',
[param('ns3::EventId const &', 'id')],
is_static=True)
## simulator.h (module 'core'): static ns3::Ptr<ns3::SimulatorImpl> ns3::Simulator::GetImplementation() [member function]
cls.add_method('GetImplementation',
'ns3::Ptr< ns3::SimulatorImpl >',
[],
is_static=True)
## simulator.h (module 'core'): static ns3::Time ns3::Simulator::GetMaximumSimulationTime() [member function]
cls.add_method('GetMaximumSimulationTime',
'ns3::Time',
[],
is_static=True)
## simulator.h (module 'core'): static uint32_t ns3::Simulator::GetSystemId() [member function]
cls.add_method('GetSystemId',
'uint32_t',
[],
is_static=True)
## simulator.h (module 'core'): static bool ns3::Simulator::IsExpired(ns3::EventId const & id) [member function]
cls.add_method('IsExpired',
'bool',
[param('ns3::EventId const &', 'id')],
is_static=True)
## simulator.h (module 'core'): static bool ns3::Simulator::IsFinished() [member function]
cls.add_method('IsFinished',
'bool',
[],
is_static=True)
## simulator.h (module 'core'): static ns3::Time ns3::Simulator::Now() [member function]
cls.add_method('Now',
'ns3::Time',
[],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::Remove(ns3::EventId const & id) [member function]
cls.add_method('Remove',
'void',
[param('ns3::EventId const &', 'id')],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::SetImplementation(ns3::Ptr<ns3::SimulatorImpl> impl) [member function]
cls.add_method('SetImplementation',
'void',
[param('ns3::Ptr< ns3::SimulatorImpl >', 'impl')],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::SetScheduler(ns3::ObjectFactory schedulerFactory) [member function]
cls.add_method('SetScheduler',
'void',
[param('ns3::ObjectFactory', 'schedulerFactory')],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::Stop() [member function]
cls.add_method('Stop',
'void',
[],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::Stop(ns3::Time const & delay) [member function]
cls.add_method('Stop',
'void',
[param('ns3::Time const &', 'delay')],
is_static=True)
return
def register_Ns3SystemCondition_methods(root_module, cls):
## system-condition.h (module 'core'): ns3::SystemCondition::SystemCondition(ns3::SystemCondition const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SystemCondition const &', 'arg0')])
## system-condition.h (module 'core'): ns3::SystemCondition::SystemCondition() [constructor]
cls.add_constructor([])
## system-condition.h (module 'core'): void ns3::SystemCondition::Broadcast() [member function]
cls.add_method('Broadcast',
'void',
[])
## system-condition.h (module 'core'): bool ns3::SystemCondition::GetCondition() [member function]
cls.add_method('GetCondition',
'bool',
[])
## system-condition.h (module 'core'): void ns3::SystemCondition::SetCondition(bool condition) [member function]
cls.add_method('SetCondition',
'void',
[param('bool', 'condition')])
## system-condition.h (module 'core'): void ns3::SystemCondition::Signal() [member function]
cls.add_method('Signal',
'void',
[])
## system-condition.h (module 'core'): bool ns3::SystemCondition::TimedWait(uint64_t ns) [member function]
cls.add_method('TimedWait',
'bool',
[param('uint64_t', 'ns')])
## system-condition.h (module 'core'): void ns3::SystemCondition::Wait() [member function]
cls.add_method('Wait',
'void',
[])
return
def register_Ns3SystemMutex_methods(root_module, cls):
## system-mutex.h (module 'core'): ns3::SystemMutex::SystemMutex(ns3::SystemMutex const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SystemMutex const &', 'arg0')])
## system-mutex.h (module 'core'): ns3::SystemMutex::SystemMutex() [constructor]
cls.add_constructor([])
## system-mutex.h (module 'core'): void ns3::SystemMutex::Lock() [member function]
cls.add_method('Lock',
'void',
[])
## system-mutex.h (module 'core'): void ns3::SystemMutex::Unlock() [member function]
cls.add_method('Unlock',
'void',
[])
return
def register_Ns3SystemWallClockMs_methods(root_module, cls):
## system-wall-clock-ms.h (module 'core'): ns3::SystemWallClockMs::SystemWallClockMs(ns3::SystemWallClockMs const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SystemWallClockMs const &', 'arg0')])
## system-wall-clock-ms.h (module 'core'): ns3::SystemWallClockMs::SystemWallClockMs() [constructor]
cls.add_constructor([])
## system-wall-clock-ms.h (module 'core'): int64_t ns3::SystemWallClockMs::End() [member function]
cls.add_method('End',
'int64_t',
[])
## system-wall-clock-ms.h (module 'core'): int64_t ns3::SystemWallClockMs::GetElapsedReal() const [member function]
cls.add_method('GetElapsedReal',
'int64_t',
[],
is_const=True)
## system-wall-clock-ms.h (module 'core'): int64_t ns3::SystemWallClockMs::GetElapsedSystem() const [member function]
cls.add_method('GetElapsedSystem',
'int64_t',
[],
is_const=True)
## system-wall-clock-ms.h (module 'core'): int64_t ns3::SystemWallClockMs::GetElapsedUser() const [member function]
cls.add_method('GetElapsedUser',
'int64_t',
[],
is_const=True)
## system-wall-clock-ms.h (module 'core'): void ns3::SystemWallClockMs::Start() [member function]
cls.add_method('Start',
'void',
[])
return
def register_Ns3TimeWithUnit_methods(root_module, cls):
cls.add_output_stream_operator()
## nstime.h (module 'core'): ns3::TimeWithUnit::TimeWithUnit(ns3::TimeWithUnit const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TimeWithUnit const &', 'arg0')])
## nstime.h (module 'core'): ns3::TimeWithUnit::TimeWithUnit(ns3::Time const time, ns3::Time::Unit const unit) [constructor]
cls.add_constructor([param('ns3::Time const', 'time'), param('ns3::Time::Unit const', 'unit')])
return
def register_Ns3Timer_methods(root_module, cls):
## timer.h (module 'core'): ns3::Timer::Timer(ns3::Timer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Timer const &', 'arg0')])
## timer.h (module 'core'): ns3::Timer::Timer() [constructor]
cls.add_constructor([])
## timer.h (module 'core'): ns3::Timer::Timer(ns3::Timer::DestroyPolicy destroyPolicy) [constructor]
cls.add_constructor([param('ns3::Timer::DestroyPolicy', 'destroyPolicy')])
## timer.h (module 'core'): void ns3::Timer::Cancel() [member function]
cls.add_method('Cancel',
'void',
[])
## timer.h (module 'core'): ns3::Time ns3::Timer::GetDelay() const [member function]
cls.add_method('GetDelay',
'ns3::Time',
[],
is_const=True)
## timer.h (module 'core'): ns3::Time ns3::Timer::GetDelayLeft() const [member function]
cls.add_method('GetDelayLeft',
'ns3::Time',
[],
is_const=True)
## timer.h (module 'core'): ns3::Timer::State ns3::Timer::GetState() const [member function]
cls.add_method('GetState',
'ns3::Timer::State',
[],
is_const=True)
## timer.h (module 'core'): bool ns3::Timer::IsExpired() const [member function]
cls.add_method('IsExpired',
'bool',
[],
is_const=True)
## timer.h (module 'core'): bool ns3::Timer::IsRunning() const [member function]
cls.add_method('IsRunning',
'bool',
[],
is_const=True)
## timer.h (module 'core'): bool ns3::Timer::IsSuspended() const [member function]
cls.add_method('IsSuspended',
'bool',
[],
is_const=True)
## timer.h (module 'core'): void ns3::Timer::Remove() [member function]
cls.add_method('Remove',
'void',
[])
## timer.h (module 'core'): void ns3::Timer::Resume() [member function]
cls.add_method('Resume',
'void',
[])
## timer.h (module 'core'): void ns3::Timer::Schedule() [member function]
cls.add_method('Schedule',
'void',
[])
## timer.h (module 'core'): void ns3::Timer::Schedule(ns3::Time delay) [member function]
cls.add_method('Schedule',
'void',
[param('ns3::Time', 'delay')])
## timer.h (module 'core'): void ns3::Timer::SetDelay(ns3::Time const & delay) [member function]
cls.add_method('SetDelay',
'void',
[param('ns3::Time const &', 'delay')])
## timer.h (module 'core'): void ns3::Timer::Suspend() [member function]
cls.add_method('Suspend',
'void',
[])
return
def register_Ns3TimerImpl_methods(root_module, cls):
## timer-impl.h (module 'core'): ns3::TimerImpl::TimerImpl() [constructor]
cls.add_constructor([])
## timer-impl.h (module 'core'): ns3::TimerImpl::TimerImpl(ns3::TimerImpl const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TimerImpl const &', 'arg0')])
## timer-impl.h (module 'core'): void ns3::TimerImpl::Invoke() [member function]
cls.add_method('Invoke',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## timer-impl.h (module 'core'): ns3::EventId ns3::TimerImpl::Schedule(ns3::Time const & delay) [member function]
cls.add_method('Schedule',
'ns3::EventId',
[param('ns3::Time const &', 'delay')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3TypeId_methods(root_module, cls):
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('!=')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## type-id.h (module 'core'): ns3::TypeId::TypeId(char const * name) [constructor]
cls.add_constructor([param('char const *', 'name')])
## type-id.h (module 'core'): ns3::TypeId::TypeId() [constructor]
cls.add_constructor([])
## type-id.h (module 'core'): ns3::TypeId::TypeId(ns3::TypeId const & o) [copy constructor]
cls.add_constructor([param('ns3::TypeId const &', 'o')])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('AddAttribute',
'ns3::TypeId',
[param('std::string', 'name'), param('std::string', 'help'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, uint32_t flags, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('AddAttribute',
'ns3::TypeId',
[param('std::string', 'name'), param('std::string', 'help'), param('uint32_t', 'flags'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddTraceSource(std::string name, std::string help, ns3::Ptr<ns3::TraceSourceAccessor const> accessor) [member function]
cls.add_method('AddTraceSource',
'ns3::TypeId',
[param('std::string', 'name'), param('std::string', 'help'), param('ns3::Ptr< ns3::TraceSourceAccessor const >', 'accessor')],
deprecated=True)
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddTraceSource(std::string name, std::string help, ns3::Ptr<ns3::TraceSourceAccessor const> accessor, std::string callback) [member function]
cls.add_method('AddTraceSource',
'ns3::TypeId',
[param('std::string', 'name'), param('std::string', 'help'), param('ns3::Ptr< ns3::TraceSourceAccessor const >', 'accessor'), param('std::string', 'callback')])
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation ns3::TypeId::GetAttribute(uint32_t i) const [member function]
cls.add_method('GetAttribute',
'ns3::TypeId::AttributeInformation',
[param('uint32_t', 'i')],
is_const=True)
## type-id.h (module 'core'): std::string ns3::TypeId::GetAttributeFullName(uint32_t i) const [member function]
cls.add_method('GetAttributeFullName',
'std::string',
[param('uint32_t', 'i')],
is_const=True)
## type-id.h (module 'core'): uint32_t ns3::TypeId::GetAttributeN() const [member function]
cls.add_method('GetAttributeN',
'uint32_t',
[],
is_const=True)
## type-id.h (module 'core'): ns3::Callback<ns3::ObjectBase*,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ns3::TypeId::GetConstructor() const [member function]
cls.add_method('GetConstructor',
'ns3::Callback< ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >',
[],
is_const=True)
## type-id.h (module 'core'): std::string ns3::TypeId::GetGroupName() const [member function]
cls.add_method('GetGroupName',
'std::string',
[],
is_const=True)
## type-id.h (module 'core'): uint32_t ns3::TypeId::GetHash() const [member function]
cls.add_method('GetHash',
'uint32_t',
[],
is_const=True)
## type-id.h (module 'core'): std::string ns3::TypeId::GetName() const [member function]
cls.add_method('GetName',
'std::string',
[],
is_const=True)
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::GetParent() const [member function]
cls.add_method('GetParent',
'ns3::TypeId',
[],
is_const=True)
## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::GetRegistered(uint32_t i) [member function]
cls.add_method('GetRegistered',
'ns3::TypeId',
[param('uint32_t', 'i')],
is_static=True)
## type-id.h (module 'core'): static uint32_t ns3::TypeId::GetRegisteredN() [member function]
cls.add_method('GetRegisteredN',
'uint32_t',
[],
is_static=True)
## type-id.h (module 'core'): std::size_t ns3::TypeId::GetSize() const [member function]
cls.add_method('GetSize',
'std::size_t',
[],
is_const=True)
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation ns3::TypeId::GetTraceSource(uint32_t i) const [member function]
cls.add_method('GetTraceSource',
'ns3::TypeId::TraceSourceInformation',
[param('uint32_t', 'i')],
is_const=True)
## type-id.h (module 'core'): uint32_t ns3::TypeId::GetTraceSourceN() const [member function]
cls.add_method('GetTraceSourceN',
'uint32_t',
[],
is_const=True)
## type-id.h (module 'core'): uint16_t ns3::TypeId::GetUid() const [member function]
cls.add_method('GetUid',
'uint16_t',
[],
is_const=True)
## type-id.h (module 'core'): bool ns3::TypeId::HasConstructor() const [member function]
cls.add_method('HasConstructor',
'bool',
[],
is_const=True)
## type-id.h (module 'core'): bool ns3::TypeId::HasParent() const [member function]
cls.add_method('HasParent',
'bool',
[],
is_const=True)
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::HideFromDocumentation() [member function]
cls.add_method('HideFromDocumentation',
'ns3::TypeId',
[])
## type-id.h (module 'core'): bool ns3::TypeId::IsChildOf(ns3::TypeId other) const [member function]
cls.add_method('IsChildOf',
'bool',
[param('ns3::TypeId', 'other')],
is_const=True)
## type-id.h (module 'core'): bool ns3::TypeId::LookupAttributeByName(std::string name, ns3::TypeId::AttributeInformation * info) const [member function]
cls.add_method('LookupAttributeByName',
'bool',
[param('std::string', 'name'), param('ns3::TypeId::AttributeInformation *', 'info', transfer_ownership=False)],
is_const=True)
## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::LookupByHash(uint32_t hash) [member function]
cls.add_method('LookupByHash',
'ns3::TypeId',
[param('uint32_t', 'hash')],
is_static=True)
## type-id.h (module 'core'): static bool ns3::TypeId::LookupByHashFailSafe(uint32_t hash, ns3::TypeId * tid) [member function]
cls.add_method('LookupByHashFailSafe',
'bool',
[param('uint32_t', 'hash'), param('ns3::TypeId *', 'tid')],
is_static=True)
## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::LookupByName(std::string name) [member function]
cls.add_method('LookupByName',
'ns3::TypeId',
[param('std::string', 'name')],
is_static=True)
## type-id.h (module 'core'): ns3::Ptr<ns3::TraceSourceAccessor const> ns3::TypeId::LookupTraceSourceByName(std::string name) const [member function]
cls.add_method('LookupTraceSourceByName',
'ns3::Ptr< ns3::TraceSourceAccessor const >',
[param('std::string', 'name')],
is_const=True)
## type-id.h (module 'core'): bool ns3::TypeId::MustHideFromDocumentation() const [member function]
cls.add_method('MustHideFromDocumentation',
'bool',
[],
is_const=True)
## type-id.h (module 'core'): bool ns3::TypeId::SetAttributeInitialValue(uint32_t i, ns3::Ptr<ns3::AttributeValue const> initialValue) [member function]
cls.add_method('SetAttributeInitialValue',
'bool',
[param('uint32_t', 'i'), param('ns3::Ptr< ns3::AttributeValue const >', 'initialValue')])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetGroupName(std::string groupName) [member function]
cls.add_method('SetGroupName',
'ns3::TypeId',
[param('std::string', 'groupName')])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetParent(ns3::TypeId tid) [member function]
cls.add_method('SetParent',
'ns3::TypeId',
[param('ns3::TypeId', 'tid')])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetSize(std::size_t size) [member function]
cls.add_method('SetSize',
'ns3::TypeId',
[param('std::size_t', 'size')])
## type-id.h (module 'core'): void ns3::TypeId::SetUid(uint16_t tid) [member function]
cls.add_method('SetUid',
'void',
[param('uint16_t', 'tid')])
return
def register_Ns3TypeIdAttributeInformation_methods(root_module, cls):
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation() [constructor]
cls.add_constructor([])
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation(ns3::TypeId::AttributeInformation const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TypeId::AttributeInformation const &', 'arg0')])
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::accessor [variable]
cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::AttributeAccessor const >', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::checker [variable]
cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::flags [variable]
cls.add_instance_attribute('flags', 'uint32_t', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::help [variable]
cls.add_instance_attribute('help', 'std::string', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::initialValue [variable]
cls.add_instance_attribute('initialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::name [variable]
cls.add_instance_attribute('name', 'std::string', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::originalInitialValue [variable]
cls.add_instance_attribute('originalInitialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False)
return
def register_Ns3TypeIdTraceSourceInformation_methods(root_module, cls):
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation() [constructor]
cls.add_constructor([])
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation(ns3::TypeId::TraceSourceInformation const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TypeId::TraceSourceInformation const &', 'arg0')])
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::accessor [variable]
cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::TraceSourceAccessor const >', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::callback [variable]
cls.add_instance_attribute('callback', 'std::string', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::help [variable]
cls.add_instance_attribute('help', 'std::string', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::name [variable]
cls.add_instance_attribute('name', 'std::string', is_const=False)
return
def register_Ns3Vector2D_methods(root_module, cls):
cls.add_output_stream_operator()
## vector.h (module 'core'): ns3::Vector2D::Vector2D(ns3::Vector2D const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Vector2D const &', 'arg0')])
## vector.h (module 'core'): ns3::Vector2D::Vector2D(double _x, double _y) [constructor]
cls.add_constructor([param('double', '_x'), param('double', '_y')])
## vector.h (module 'core'): ns3::Vector2D::Vector2D() [constructor]
cls.add_constructor([])
## vector.h (module 'core'): ns3::Vector2D::x [variable]
cls.add_instance_attribute('x', 'double', is_const=False)
## vector.h (module 'core'): ns3::Vector2D::y [variable]
cls.add_instance_attribute('y', 'double', is_const=False)
return
def register_Ns3Vector3D_methods(root_module, cls):
cls.add_output_stream_operator()
## vector.h (module 'core'): ns3::Vector3D::Vector3D(ns3::Vector3D const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Vector3D const &', 'arg0')])
## vector.h (module 'core'): ns3::Vector3D::Vector3D(double _x, double _y, double _z) [constructor]
cls.add_constructor([param('double', '_x'), param('double', '_y'), param('double', '_z')])
## vector.h (module 'core'): ns3::Vector3D::Vector3D() [constructor]
cls.add_constructor([])
## vector.h (module 'core'): ns3::Vector3D::x [variable]
cls.add_instance_attribute('x', 'double', is_const=False)
## vector.h (module 'core'): ns3::Vector3D::y [variable]
cls.add_instance_attribute('y', 'double', is_const=False)
## vector.h (module 'core'): ns3::Vector3D::z [variable]
cls.add_instance_attribute('z', 'double', is_const=False)
return
def register_Ns3Watchdog_methods(root_module, cls):
## watchdog.h (module 'core'): ns3::Watchdog::Watchdog(ns3::Watchdog const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Watchdog const &', 'arg0')])
## watchdog.h (module 'core'): ns3::Watchdog::Watchdog() [constructor]
cls.add_constructor([])
## watchdog.h (module 'core'): void ns3::Watchdog::Ping(ns3::Time delay) [member function]
cls.add_method('Ping',
'void',
[param('ns3::Time', 'delay')])
return
def register_Ns3Empty_methods(root_module, cls):
## empty.h (module 'core'): ns3::empty::empty() [constructor]
cls.add_constructor([])
## empty.h (module 'core'): ns3::empty::empty(ns3::empty const & arg0) [copy constructor]
cls.add_constructor([param('ns3::empty const &', 'arg0')])
return
def register_Ns3Int64x64_t_methods(root_module, cls):
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right'))
cls.add_unary_numeric_operator('-')
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right'))
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('>')
cls.add_binary_comparison_operator('!=')
cls.add_inplace_numeric_operator('*=', param('ns3::int64x64_t const &', u'right'))
cls.add_inplace_numeric_operator('+=', param('ns3::int64x64_t const &', u'right'))
cls.add_inplace_numeric_operator('-=', param('ns3::int64x64_t const &', u'right'))
cls.add_inplace_numeric_operator('/=', param('ns3::int64x64_t const &', u'right'))
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('<=')
cls.add_binary_comparison_operator('==')
cls.add_binary_comparison_operator('>=')
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t() [constructor]
cls.add_constructor([])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(double v) [constructor]
cls.add_constructor([param('double', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long double v) [constructor]
cls.add_constructor([param('long double', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int v) [constructor]
cls.add_constructor([param('int', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long int v) [constructor]
cls.add_constructor([param('long int', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long int v) [constructor]
cls.add_constructor([param('long long int', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(unsigned int v) [constructor]
cls.add_constructor([param('unsigned int', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long unsigned int v) [constructor]
cls.add_constructor([param('long unsigned int', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long unsigned int v) [constructor]
cls.add_constructor([param('long long unsigned int', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int64_t hi, uint64_t lo) [constructor]
cls.add_constructor([param('int64_t', 'hi'), param('uint64_t', 'lo')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(ns3::int64x64_t const & o) [copy constructor]
cls.add_constructor([param('ns3::int64x64_t const &', 'o')])
## int64x64-double.h (module 'core'): double ns3::int64x64_t::GetDouble() const [member function]
cls.add_method('GetDouble',
'double',
[],
is_const=True)
## int64x64-double.h (module 'core'): int64_t ns3::int64x64_t::GetHigh() const [member function]
cls.add_method('GetHigh',
'int64_t',
[],
is_const=True)
## int64x64-double.h (module 'core'): uint64_t ns3::int64x64_t::GetLow() const [member function]
cls.add_method('GetLow',
'uint64_t',
[],
is_const=True)
## int64x64-double.h (module 'core'): static ns3::int64x64_t ns3::int64x64_t::Invert(uint64_t v) [member function]
cls.add_method('Invert',
'ns3::int64x64_t',
[param('uint64_t', 'v')],
is_static=True)
## int64x64-double.h (module 'core'): void ns3::int64x64_t::MulByInvert(ns3::int64x64_t const & o) [member function]
cls.add_method('MulByInvert',
'void',
[param('ns3::int64x64_t const &', 'o')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::implementation [variable]
cls.add_static_attribute('implementation', 'ns3::int64x64_t::impl_type const', is_const=True)
return
def register_Ns3Object_methods(root_module, cls):
## object.h (module 'core'): ns3::Object::Object() [constructor]
cls.add_constructor([])
## object.h (module 'core'): void ns3::Object::AggregateObject(ns3::Ptr<ns3::Object> other) [member function]
cls.add_method('AggregateObject',
'void',
[param('ns3::Ptr< ns3::Object >', 'other')])
## object.h (module 'core'): void ns3::Object::Dispose() [member function]
cls.add_method('Dispose',
'void',
[])
## object.h (module 'core'): ns3::Object::AggregateIterator ns3::Object::GetAggregateIterator() const [member function]
cls.add_method('GetAggregateIterator',
'ns3::Object::AggregateIterator',
[],
is_const=True)
## object.h (module 'core'): ns3::TypeId ns3::Object::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## object.h (module 'core'): ns3::Ptr<ns3::Object> ns3::Object::GetObject(ns3::TypeId tid) const [member function]
cls.add_method('GetObject',
'ns3::Ptr< ns3::Object >',
[param('ns3::TypeId', 'tid')],
is_const=True, template_parameters=['ns3::Object'], custom_template_method_name=u'GetObject')
## object.h (module 'core'): static ns3::TypeId ns3::Object::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## object.h (module 'core'): void ns3::Object::Initialize() [member function]
cls.add_method('Initialize',
'void',
[])
## object.h (module 'core'): ns3::Object::Object(ns3::Object const & o) [copy constructor]
cls.add_constructor([param('ns3::Object const &', 'o')],
visibility='protected')
## object.h (module 'core'): void ns3::Object::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## object.h (module 'core'): void ns3::Object::DoInitialize() [member function]
cls.add_method('DoInitialize',
'void',
[],
visibility='protected', is_virtual=True)
## object.h (module 'core'): void ns3::Object::NotifyNewAggregate() [member function]
cls.add_method('NotifyNewAggregate',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3ObjectAggregateIterator_methods(root_module, cls):
## object.h (module 'core'): ns3::Object::AggregateIterator::AggregateIterator(ns3::Object::AggregateIterator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Object::AggregateIterator const &', 'arg0')])
## object.h (module 'core'): ns3::Object::AggregateIterator::AggregateIterator() [constructor]
cls.add_constructor([])
## object.h (module 'core'): bool ns3::Object::AggregateIterator::HasNext() const [member function]
cls.add_method('HasNext',
'bool',
[],
is_const=True)
## object.h (module 'core'): ns3::Ptr<ns3::Object const> ns3::Object::AggregateIterator::Next() [member function]
cls.add_method('Next',
'ns3::Ptr< ns3::Object const >',
[])
return
def register_Ns3RandomVariableStream_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::RandomVariableStream::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::RandomVariableStream::RandomVariableStream() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): void ns3::RandomVariableStream::SetStream(int64_t stream) [member function]
cls.add_method('SetStream',
'void',
[param('int64_t', 'stream')])
## random-variable-stream.h (module 'core'): int64_t ns3::RandomVariableStream::GetStream() const [member function]
cls.add_method('GetStream',
'int64_t',
[],
is_const=True)
## random-variable-stream.h (module 'core'): void ns3::RandomVariableStream::SetAntithetic(bool isAntithetic) [member function]
cls.add_method('SetAntithetic',
'void',
[param('bool', 'isAntithetic')])
## random-variable-stream.h (module 'core'): bool ns3::RandomVariableStream::IsAntithetic() const [member function]
cls.add_method('IsAntithetic',
'bool',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::RandomVariableStream::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_pure_virtual=True, is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::RandomVariableStream::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_pure_virtual=True, is_virtual=True)
## random-variable-stream.h (module 'core'): ns3::RngStream * ns3::RandomVariableStream::Peek() const [member function]
cls.add_method('Peek',
'ns3::RngStream *',
[],
is_const=True, visibility='protected')
return
def register_Ns3Scheduler_methods(root_module, cls):
## scheduler.h (module 'core'): ns3::Scheduler::Scheduler() [constructor]
cls.add_constructor([])
## scheduler.h (module 'core'): ns3::Scheduler::Scheduler(ns3::Scheduler const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Scheduler const &', 'arg0')])
## scheduler.h (module 'core'): static ns3::TypeId ns3::Scheduler::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## scheduler.h (module 'core'): void ns3::Scheduler::Insert(ns3::Scheduler::Event const & ev) [member function]
cls.add_method('Insert',
'void',
[param('ns3::Scheduler::Event const &', 'ev')],
is_pure_virtual=True, is_virtual=True)
## scheduler.h (module 'core'): bool ns3::Scheduler::IsEmpty() const [member function]
cls.add_method('IsEmpty',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## scheduler.h (module 'core'): ns3::Scheduler::Event ns3::Scheduler::PeekNext() const [member function]
cls.add_method('PeekNext',
'ns3::Scheduler::Event',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## scheduler.h (module 'core'): void ns3::Scheduler::Remove(ns3::Scheduler::Event const & ev) [member function]
cls.add_method('Remove',
'void',
[param('ns3::Scheduler::Event const &', 'ev')],
is_pure_virtual=True, is_virtual=True)
## scheduler.h (module 'core'): ns3::Scheduler::Event ns3::Scheduler::RemoveNext() [member function]
cls.add_method('RemoveNext',
'ns3::Scheduler::Event',
[],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3SchedulerEvent_methods(root_module, cls):
cls.add_binary_comparison_operator('<')
## scheduler.h (module 'core'): ns3::Scheduler::Event::Event() [constructor]
cls.add_constructor([])
## scheduler.h (module 'core'): ns3::Scheduler::Event::Event(ns3::Scheduler::Event const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Scheduler::Event const &', 'arg0')])
## scheduler.h (module 'core'): ns3::Scheduler::Event::impl [variable]
cls.add_instance_attribute('impl', 'ns3::EventImpl *', is_const=False)
## scheduler.h (module 'core'): ns3::Scheduler::Event::key [variable]
cls.add_instance_attribute('key', 'ns3::Scheduler::EventKey', is_const=False)
return
def register_Ns3SchedulerEventKey_methods(root_module, cls):
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('>')
cls.add_binary_comparison_operator('!=')
## scheduler.h (module 'core'): ns3::Scheduler::EventKey::EventKey() [constructor]
cls.add_constructor([])
## scheduler.h (module 'core'): ns3::Scheduler::EventKey::EventKey(ns3::Scheduler::EventKey const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Scheduler::EventKey const &', 'arg0')])
## scheduler.h (module 'core'): ns3::Scheduler::EventKey::m_context [variable]
cls.add_instance_attribute('m_context', 'uint32_t', is_const=False)
## scheduler.h (module 'core'): ns3::Scheduler::EventKey::m_ts [variable]
cls.add_instance_attribute('m_ts', 'uint64_t', is_const=False)
## scheduler.h (module 'core'): ns3::Scheduler::EventKey::m_uid [variable]
cls.add_instance_attribute('m_uid', 'uint32_t', is_const=False)
return
def register_Ns3SequentialRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::SequentialRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::SequentialRandomVariable::SequentialRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::SequentialRandomVariable::GetMin() const [member function]
cls.add_method('GetMin',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::SequentialRandomVariable::GetMax() const [member function]
cls.add_method('GetMax',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): ns3::Ptr<ns3::RandomVariableStream> ns3::SequentialRandomVariable::GetIncrement() const [member function]
cls.add_method('GetIncrement',
'ns3::Ptr< ns3::RandomVariableStream >',
[],
is_const=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::SequentialRandomVariable::GetConsecutive() const [member function]
cls.add_method('GetConsecutive',
'uint32_t',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::SequentialRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::SequentialRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter< ns3::AttributeAccessor > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter< ns3::AttributeChecker > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter< ns3::AttributeValue > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::SimpleRefCount(ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter< ns3::CallbackImplBase > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::SimpleRefCount(ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter< ns3::EventImpl > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3FdReader_Ns3Empty_Ns3DefaultDeleter__lt__ns3FdReader__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::FdReader, ns3::empty, ns3::DefaultDeleter<ns3::FdReader> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::FdReader, ns3::empty, ns3::DefaultDeleter<ns3::FdReader> >::SimpleRefCount(ns3::SimpleRefCount<ns3::FdReader, ns3::empty, ns3::DefaultDeleter<ns3::FdReader> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::FdReader, ns3::empty, ns3::DefaultDeleter< ns3::FdReader > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::FdReader, ns3::empty, ns3::DefaultDeleter<ns3::FdReader> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3HashImplementation_Ns3Empty_Ns3DefaultDeleter__lt__ns3HashImplementation__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter< ns3::Hash::Implementation > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3RefCountBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3RefCountBase__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::RefCountBase, ns3::empty, ns3::DefaultDeleter<ns3::RefCountBase> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::RefCountBase, ns3::empty, ns3::DefaultDeleter<ns3::RefCountBase> >::SimpleRefCount(ns3::SimpleRefCount<ns3::RefCountBase, ns3::empty, ns3::DefaultDeleter<ns3::RefCountBase> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::RefCountBase, ns3::empty, ns3::DefaultDeleter< ns3::RefCountBase > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::RefCountBase, ns3::empty, ns3::DefaultDeleter<ns3::RefCountBase> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3SystemThread_Ns3Empty_Ns3DefaultDeleter__lt__ns3SystemThread__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::SystemThread, ns3::empty, ns3::DefaultDeleter<ns3::SystemThread> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::SystemThread, ns3::empty, ns3::DefaultDeleter<ns3::SystemThread> >::SimpleRefCount(ns3::SimpleRefCount<ns3::SystemThread, ns3::empty, ns3::DefaultDeleter<ns3::SystemThread> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::SystemThread, ns3::empty, ns3::DefaultDeleter< ns3::SystemThread > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::SystemThread, ns3::empty, ns3::DefaultDeleter<ns3::SystemThread> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::SimpleRefCount(ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter< ns3::TraceSourceAccessor > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimulatorImpl_methods(root_module, cls):
## simulator-impl.h (module 'core'): ns3::SimulatorImpl::SimulatorImpl() [constructor]
cls.add_constructor([])
## simulator-impl.h (module 'core'): ns3::SimulatorImpl::SimulatorImpl(ns3::SimulatorImpl const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SimulatorImpl const &', 'arg0')])
## simulator-impl.h (module 'core'): void ns3::SimulatorImpl::Cancel(ns3::EventId const & id) [member function]
cls.add_method('Cancel',
'void',
[param('ns3::EventId const &', 'id')],
is_pure_virtual=True, is_virtual=True)
## simulator-impl.h (module 'core'): void ns3::SimulatorImpl::Destroy() [member function]
cls.add_method('Destroy',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## simulator-impl.h (module 'core'): uint32_t ns3::SimulatorImpl::GetContext() const [member function]
cls.add_method('GetContext',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## simulator-impl.h (module 'core'): ns3::Time ns3::SimulatorImpl::GetDelayLeft(ns3::EventId const & id) const [member function]
cls.add_method('GetDelayLeft',
'ns3::Time',
[param('ns3::EventId const &', 'id')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## simulator-impl.h (module 'core'): ns3::Time ns3::SimulatorImpl::GetMaximumSimulationTime() const [member function]
cls.add_method('GetMaximumSimulationTime',
'ns3::Time',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## simulator-impl.h (module 'core'): uint32_t ns3::SimulatorImpl::GetSystemId() const [member function]
cls.add_method('GetSystemId',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## simulator-impl.h (module 'core'): static ns3::TypeId ns3::SimulatorImpl::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## simulator-impl.h (module 'core'): bool ns3::SimulatorImpl::IsExpired(ns3::EventId const & id) const [member function]
cls.add_method('IsExpired',
'bool',
[param('ns3::EventId const &', 'id')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## simulator-impl.h (module 'core'): bool ns3::SimulatorImpl::IsFinished() const [member function]
cls.add_method('IsFinished',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## simulator-impl.h (module 'core'): ns3::Time ns3::SimulatorImpl::Now() const [member function]
cls.add_method('Now',
'ns3::Time',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## simulator-impl.h (module 'core'): void ns3::SimulatorImpl::Remove(ns3::EventId const & id) [member function]
cls.add_method('Remove',
'void',
[param('ns3::EventId const &', 'id')],
is_pure_virtual=True, is_virtual=True)
## simulator-impl.h (module 'core'): void ns3::SimulatorImpl::Run() [member function]
cls.add_method('Run',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## simulator-impl.h (module 'core'): ns3::EventId ns3::SimulatorImpl::Schedule(ns3::Time const & delay, ns3::EventImpl * event) [member function]
cls.add_method('Schedule',
'ns3::EventId',
[param('ns3::Time const &', 'delay'), param('ns3::EventImpl *', 'event')],
is_pure_virtual=True, is_virtual=True)
## simulator-impl.h (module 'core'): ns3::EventId ns3::SimulatorImpl::ScheduleDestroy(ns3::EventImpl * event) [member function]
cls.add_method('ScheduleDestroy',
'ns3::EventId',
[param('ns3::EventImpl *', 'event')],
is_pure_virtual=True, is_virtual=True)
## simulator-impl.h (module 'core'): ns3::EventId ns3::SimulatorImpl::ScheduleNow(ns3::EventImpl * event) [member function]
cls.add_method('ScheduleNow',
'ns3::EventId',
[param('ns3::EventImpl *', 'event')],
is_pure_virtual=True, is_virtual=True)
## simulator-impl.h (module 'core'): void ns3::SimulatorImpl::ScheduleWithContext(uint32_t context, ns3::Time const & delay, ns3::EventImpl * event) [member function]
cls.add_method('ScheduleWithContext',
'void',
[param('uint32_t', 'context'), param('ns3::Time const &', 'delay'), param('ns3::EventImpl *', 'event')],
is_pure_virtual=True, is_virtual=True)
## simulator-impl.h (module 'core'): void ns3::SimulatorImpl::SetScheduler(ns3::ObjectFactory schedulerFactory) [member function]
cls.add_method('SetScheduler',
'void',
[param('ns3::ObjectFactory', 'schedulerFactory')],
is_pure_virtual=True, is_virtual=True)
## simulator-impl.h (module 'core'): void ns3::SimulatorImpl::Stop() [member function]
cls.add_method('Stop',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## simulator-impl.h (module 'core'): void ns3::SimulatorImpl::Stop(ns3::Time const & delay) [member function]
cls.add_method('Stop',
'void',
[param('ns3::Time const &', 'delay')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3Synchronizer_methods(root_module, cls):
## synchronizer.h (module 'core'): ns3::Synchronizer::Synchronizer(ns3::Synchronizer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Synchronizer const &', 'arg0')])
## synchronizer.h (module 'core'): ns3::Synchronizer::Synchronizer() [constructor]
cls.add_constructor([])
## synchronizer.h (module 'core'): uint64_t ns3::Synchronizer::EventEnd() [member function]
cls.add_method('EventEnd',
'uint64_t',
[])
## synchronizer.h (module 'core'): void ns3::Synchronizer::EventStart() [member function]
cls.add_method('EventStart',
'void',
[])
## synchronizer.h (module 'core'): uint64_t ns3::Synchronizer::GetCurrentRealtime() [member function]
cls.add_method('GetCurrentRealtime',
'uint64_t',
[])
## synchronizer.h (module 'core'): int64_t ns3::Synchronizer::GetDrift(uint64_t ts) [member function]
cls.add_method('GetDrift',
'int64_t',
[param('uint64_t', 'ts')])
## synchronizer.h (module 'core'): uint64_t ns3::Synchronizer::GetOrigin() [member function]
cls.add_method('GetOrigin',
'uint64_t',
[])
## synchronizer.h (module 'core'): static ns3::TypeId ns3::Synchronizer::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## synchronizer.h (module 'core'): bool ns3::Synchronizer::Realtime() [member function]
cls.add_method('Realtime',
'bool',
[])
## synchronizer.h (module 'core'): void ns3::Synchronizer::SetCondition(bool arg0) [member function]
cls.add_method('SetCondition',
'void',
[param('bool', 'arg0')])
## synchronizer.h (module 'core'): void ns3::Synchronizer::SetOrigin(uint64_t ts) [member function]
cls.add_method('SetOrigin',
'void',
[param('uint64_t', 'ts')])
## synchronizer.h (module 'core'): void ns3::Synchronizer::Signal() [member function]
cls.add_method('Signal',
'void',
[])
## synchronizer.h (module 'core'): bool ns3::Synchronizer::Synchronize(uint64_t tsCurrent, uint64_t tsDelay) [member function]
cls.add_method('Synchronize',
'bool',
[param('uint64_t', 'tsCurrent'), param('uint64_t', 'tsDelay')])
## synchronizer.h (module 'core'): uint64_t ns3::Synchronizer::DoEventEnd() [member function]
cls.add_method('DoEventEnd',
'uint64_t',
[],
is_pure_virtual=True, visibility='protected', is_virtual=True)
## synchronizer.h (module 'core'): void ns3::Synchronizer::DoEventStart() [member function]
cls.add_method('DoEventStart',
'void',
[],
is_pure_virtual=True, visibility='protected', is_virtual=True)
## synchronizer.h (module 'core'): uint64_t ns3::Synchronizer::DoGetCurrentRealtime() [member function]
cls.add_method('DoGetCurrentRealtime',
'uint64_t',
[],
is_pure_virtual=True, visibility='protected', is_virtual=True)
## synchronizer.h (module 'core'): int64_t ns3::Synchronizer::DoGetDrift(uint64_t ns) [member function]
cls.add_method('DoGetDrift',
'int64_t',
[param('uint64_t', 'ns')],
is_pure_virtual=True, visibility='protected', is_virtual=True)
## synchronizer.h (module 'core'): bool ns3::Synchronizer::DoRealtime() [member function]
cls.add_method('DoRealtime',
'bool',
[],
is_pure_virtual=True, visibility='protected', is_virtual=True)
## synchronizer.h (module 'core'): void ns3::Synchronizer::DoSetCondition(bool arg0) [member function]
cls.add_method('DoSetCondition',
'void',
[param('bool', 'arg0')],
is_pure_virtual=True, visibility='protected', is_virtual=True)
## synchronizer.h (module 'core'): void ns3::Synchronizer::DoSetOrigin(uint64_t ns) [member function]
cls.add_method('DoSetOrigin',
'void',
[param('uint64_t', 'ns')],
is_pure_virtual=True, visibility='protected', is_virtual=True)
## synchronizer.h (module 'core'): void ns3::Synchronizer::DoSignal() [member function]
cls.add_method('DoSignal',
'void',
[],
is_pure_virtual=True, visibility='protected', is_virtual=True)
## synchronizer.h (module 'core'): bool ns3::Synchronizer::DoSynchronize(uint64_t nsCurrent, uint64_t nsDelay) [member function]
cls.add_method('DoSynchronize',
'bool',
[param('uint64_t', 'nsCurrent'), param('uint64_t', 'nsDelay')],
is_pure_virtual=True, visibility='protected', is_virtual=True)
return
def register_Ns3SystemThread_methods(root_module, cls):
## system-thread.h (module 'core'): ns3::SystemThread::SystemThread(ns3::SystemThread const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SystemThread const &', 'arg0')])
## system-thread.h (module 'core'): ns3::SystemThread::SystemThread(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [constructor]
cls.add_constructor([param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')])
## system-thread.h (module 'core'): static bool ns3::SystemThread::Equals(pthread_t id) [member function]
cls.add_method('Equals',
'bool',
[param('pthread_t', 'id')],
is_static=True)
## system-thread.h (module 'core'): void ns3::SystemThread::Join() [member function]
cls.add_method('Join',
'void',
[])
## system-thread.h (module 'core'): static pthread_t ns3::SystemThread::Self() [member function]
cls.add_method('Self',
'pthread_t',
[],
is_static=True)
## system-thread.h (module 'core'): void ns3::SystemThread::Start() [member function]
cls.add_method('Start',
'void',
[])
return
def register_Ns3Time_methods(root_module, cls):
cls.add_binary_numeric_operator('*', root_module['ns3::Time'], root_module['ns3::Time'], param('int64_t const &', u'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', u'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', u'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::Time'], root_module['ns3::Time'], param('int64_t const &', u'right'))
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('>')
cls.add_binary_comparison_operator('!=')
cls.add_inplace_numeric_operator('+=', param('ns3::Time const &', u'right'))
cls.add_inplace_numeric_operator('-=', param('ns3::Time const &', u'right'))
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('<=')
cls.add_binary_comparison_operator('==')
cls.add_binary_comparison_operator('>=')
## nstime.h (module 'core'): ns3::Time::Time() [constructor]
cls.add_constructor([])
## nstime.h (module 'core'): ns3::Time::Time(ns3::Time const & o) [copy constructor]
cls.add_constructor([param('ns3::Time const &', 'o')])
## nstime.h (module 'core'): ns3::Time::Time(double v) [constructor]
cls.add_constructor([param('double', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(int v) [constructor]
cls.add_constructor([param('int', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(long int v) [constructor]
cls.add_constructor([param('long int', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(long long int v) [constructor]
cls.add_constructor([param('long long int', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(unsigned int v) [constructor]
cls.add_constructor([param('unsigned int', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(long unsigned int v) [constructor]
cls.add_constructor([param('long unsigned int', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(long long unsigned int v) [constructor]
cls.add_constructor([param('long long unsigned int', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(ns3::int64x64_t const & v) [constructor]
cls.add_constructor([param('ns3::int64x64_t const &', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(std::string const & s) [constructor]
cls.add_constructor([param('std::string const &', 's')])
## nstime.h (module 'core'): ns3::TimeWithUnit ns3::Time::As(ns3::Time::Unit const unit) const [member function]
cls.add_method('As',
'ns3::TimeWithUnit',
[param('ns3::Time::Unit const', 'unit')],
is_const=True)
## nstime.h (module 'core'): int ns3::Time::Compare(ns3::Time const & o) const [member function]
cls.add_method('Compare',
'int',
[param('ns3::Time const &', 'o')],
is_const=True)
## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & value) [member function]
cls.add_method('From',
'ns3::Time',
[param('ns3::int64x64_t const &', 'value')],
is_static=True)
## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & value, ns3::Time::Unit unit) [member function]
cls.add_method('From',
'ns3::Time',
[param('ns3::int64x64_t const &', 'value'), param('ns3::Time::Unit', 'unit')],
is_static=True)
## nstime.h (module 'core'): static ns3::Time ns3::Time::FromDouble(double value, ns3::Time::Unit unit) [member function]
cls.add_method('FromDouble',
'ns3::Time',
[param('double', 'value'), param('ns3::Time::Unit', 'unit')],
is_static=True)
## nstime.h (module 'core'): static ns3::Time ns3::Time::FromInteger(uint64_t value, ns3::Time::Unit unit) [member function]
cls.add_method('FromInteger',
'ns3::Time',
[param('uint64_t', 'value'), param('ns3::Time::Unit', 'unit')],
is_static=True)
## nstime.h (module 'core'): double ns3::Time::GetDays() const [member function]
cls.add_method('GetDays',
'double',
[],
is_const=True)
## nstime.h (module 'core'): double ns3::Time::GetDouble() const [member function]
cls.add_method('GetDouble',
'double',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetFemtoSeconds() const [member function]
cls.add_method('GetFemtoSeconds',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): double ns3::Time::GetHours() const [member function]
cls.add_method('GetHours',
'double',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetInteger() const [member function]
cls.add_method('GetInteger',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetMicroSeconds() const [member function]
cls.add_method('GetMicroSeconds',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetMilliSeconds() const [member function]
cls.add_method('GetMilliSeconds',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): double ns3::Time::GetMinutes() const [member function]
cls.add_method('GetMinutes',
'double',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetNanoSeconds() const [member function]
cls.add_method('GetNanoSeconds',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetPicoSeconds() const [member function]
cls.add_method('GetPicoSeconds',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): static ns3::Time::Unit ns3::Time::GetResolution() [member function]
cls.add_method('GetResolution',
'ns3::Time::Unit',
[],
is_static=True)
## nstime.h (module 'core'): double ns3::Time::GetSeconds() const [member function]
cls.add_method('GetSeconds',
'double',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetTimeStep() const [member function]
cls.add_method('GetTimeStep',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): double ns3::Time::GetYears() const [member function]
cls.add_method('GetYears',
'double',
[],
is_const=True)
## nstime.h (module 'core'): bool ns3::Time::IsNegative() const [member function]
cls.add_method('IsNegative',
'bool',
[],
is_const=True)
## nstime.h (module 'core'): bool ns3::Time::IsPositive() const [member function]
cls.add_method('IsPositive',
'bool',
[],
is_const=True)
## nstime.h (module 'core'): bool ns3::Time::IsStrictlyNegative() const [member function]
cls.add_method('IsStrictlyNegative',
'bool',
[],
is_const=True)
## nstime.h (module 'core'): bool ns3::Time::IsStrictlyPositive() const [member function]
cls.add_method('IsStrictlyPositive',
'bool',
[],
is_const=True)
## nstime.h (module 'core'): bool ns3::Time::IsZero() const [member function]
cls.add_method('IsZero',
'bool',
[],
is_const=True)
## nstime.h (module 'core'): static ns3::Time ns3::Time::Max() [member function]
cls.add_method('Max',
'ns3::Time',
[],
is_static=True)
## nstime.h (module 'core'): static ns3::Time ns3::Time::Min() [member function]
cls.add_method('Min',
'ns3::Time',
[],
is_static=True)
## nstime.h (module 'core'): static void ns3::Time::SetResolution(ns3::Time::Unit resolution) [member function]
cls.add_method('SetResolution',
'void',
[param('ns3::Time::Unit', 'resolution')],
is_static=True)
## nstime.h (module 'core'): static bool ns3::Time::StaticInit() [member function]
cls.add_method('StaticInit',
'bool',
[],
is_static=True)
## nstime.h (module 'core'): ns3::int64x64_t ns3::Time::To(ns3::Time::Unit unit) const [member function]
cls.add_method('To',
'ns3::int64x64_t',
[param('ns3::Time::Unit', 'unit')],
is_const=True)
## nstime.h (module 'core'): double ns3::Time::ToDouble(ns3::Time::Unit unit) const [member function]
cls.add_method('ToDouble',
'double',
[param('ns3::Time::Unit', 'unit')],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::ToInteger(ns3::Time::Unit unit) const [member function]
cls.add_method('ToInteger',
'int64_t',
[param('ns3::Time::Unit', 'unit')],
is_const=True)
return
def register_Ns3TraceSourceAccessor_methods(root_module, cls):
## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor(ns3::TraceSourceAccessor const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TraceSourceAccessor const &', 'arg0')])
## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor() [constructor]
cls.add_constructor([])
## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Connect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function]
cls.add_method('Connect',
'bool',
[param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::ConnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function]
cls.add_method('ConnectWithoutContext',
'bool',
[param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Disconnect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function]
cls.add_method('Disconnect',
'bool',
[param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::DisconnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function]
cls.add_method('DisconnectWithoutContext',
'bool',
[param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3TriangularRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::TriangularRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::TriangularRandomVariable::TriangularRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetMean() const [member function]
cls.add_method('GetMean',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetMin() const [member function]
cls.add_method('GetMin',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetMax() const [member function]
cls.add_method('GetMax',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetValue(double mean, double min, double max) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'mean'), param('double', 'min'), param('double', 'max')])
## random-variable-stream.h (module 'core'): uint32_t ns3::TriangularRandomVariable::GetInteger(uint32_t mean, uint32_t min, uint32_t max) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'mean'), param('uint32_t', 'min'), param('uint32_t', 'max')])
## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::TriangularRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3UniformRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::UniformRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::UniformRandomVariable::UniformRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetMin() const [member function]
cls.add_method('GetMin',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetMax() const [member function]
cls.add_method('GetMax',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetValue(double min, double max) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'min'), param('double', 'max')])
## random-variable-stream.h (module 'core'): uint32_t ns3::UniformRandomVariable::GetInteger(uint32_t min, uint32_t max) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'min'), param('uint32_t', 'max')])
## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::UniformRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3WallClockSynchronizer_methods(root_module, cls):
## wall-clock-synchronizer.h (module 'core'): ns3::WallClockSynchronizer::WallClockSynchronizer(ns3::WallClockSynchronizer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WallClockSynchronizer const &', 'arg0')])
## wall-clock-synchronizer.h (module 'core'): ns3::WallClockSynchronizer::WallClockSynchronizer() [constructor]
cls.add_constructor([])
## wall-clock-synchronizer.h (module 'core'): static ns3::TypeId ns3::WallClockSynchronizer::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## wall-clock-synchronizer.h (module 'core'): ns3::WallClockSynchronizer::NS_PER_SEC [variable]
cls.add_static_attribute('NS_PER_SEC', 'uint64_t const', is_const=True)
## wall-clock-synchronizer.h (module 'core'): ns3::WallClockSynchronizer::US_PER_NS [variable]
cls.add_static_attribute('US_PER_NS', 'uint64_t const', is_const=True)
## wall-clock-synchronizer.h (module 'core'): ns3::WallClockSynchronizer::US_PER_SEC [variable]
cls.add_static_attribute('US_PER_SEC', 'uint64_t const', is_const=True)
## wall-clock-synchronizer.h (module 'core'): uint64_t ns3::WallClockSynchronizer::DoEventEnd() [member function]
cls.add_method('DoEventEnd',
'uint64_t',
[],
visibility='protected', is_virtual=True)
## wall-clock-synchronizer.h (module 'core'): void ns3::WallClockSynchronizer::DoEventStart() [member function]
cls.add_method('DoEventStart',
'void',
[],
visibility='protected', is_virtual=True)
## wall-clock-synchronizer.h (module 'core'): uint64_t ns3::WallClockSynchronizer::DoGetCurrentRealtime() [member function]
cls.add_method('DoGetCurrentRealtime',
'uint64_t',
[],
visibility='protected', is_virtual=True)
## wall-clock-synchronizer.h (module 'core'): int64_t ns3::WallClockSynchronizer::DoGetDrift(uint64_t ns) [member function]
cls.add_method('DoGetDrift',
'int64_t',
[param('uint64_t', 'ns')],
visibility='protected', is_virtual=True)
## wall-clock-synchronizer.h (module 'core'): bool ns3::WallClockSynchronizer::DoRealtime() [member function]
cls.add_method('DoRealtime',
'bool',
[],
visibility='protected', is_virtual=True)
## wall-clock-synchronizer.h (module 'core'): void ns3::WallClockSynchronizer::DoSetCondition(bool cond) [member function]
cls.add_method('DoSetCondition',
'void',
[param('bool', 'cond')],
visibility='protected', is_virtual=True)
## wall-clock-synchronizer.h (module 'core'): void ns3::WallClockSynchronizer::DoSetOrigin(uint64_t ns) [member function]
cls.add_method('DoSetOrigin',
'void',
[param('uint64_t', 'ns')],
visibility='protected', is_virtual=True)
## wall-clock-synchronizer.h (module 'core'): void ns3::WallClockSynchronizer::DoSignal() [member function]
cls.add_method('DoSignal',
'void',
[],
visibility='protected', is_virtual=True)
## wall-clock-synchronizer.h (module 'core'): bool ns3::WallClockSynchronizer::DoSynchronize(uint64_t nsCurrent, uint64_t nsDelay) [member function]
cls.add_method('DoSynchronize',
'bool',
[param('uint64_t', 'nsCurrent'), param('uint64_t', 'nsDelay')],
visibility='protected', is_virtual=True)
## wall-clock-synchronizer.h (module 'core'): uint64_t ns3::WallClockSynchronizer::DriftCorrect(uint64_t nsNow, uint64_t nsDelay) [member function]
cls.add_method('DriftCorrect',
'uint64_t',
[param('uint64_t', 'nsNow'), param('uint64_t', 'nsDelay')],
visibility='protected')
## wall-clock-synchronizer.h (module 'core'): uint64_t ns3::WallClockSynchronizer::GetNormalizedRealtime() [member function]
cls.add_method('GetNormalizedRealtime',
'uint64_t',
[],
visibility='protected')
## wall-clock-synchronizer.h (module 'core'): uint64_t ns3::WallClockSynchronizer::GetRealtime() [member function]
cls.add_method('GetRealtime',
'uint64_t',
[],
visibility='protected')
## wall-clock-synchronizer.h (module 'core'): void ns3::WallClockSynchronizer::NsToTimeval(int64_t ns, timeval * tv) [member function]
cls.add_method('NsToTimeval',
'void',
[param('int64_t', 'ns'), param('timeval *', 'tv')],
visibility='protected')
## wall-clock-synchronizer.h (module 'core'): bool ns3::WallClockSynchronizer::SleepWait(uint64_t ns) [member function]
cls.add_method('SleepWait',
'bool',
[param('uint64_t', 'ns')],
visibility='protected')
## wall-clock-synchronizer.h (module 'core'): bool ns3::WallClockSynchronizer::SpinWait(uint64_t ns) [member function]
cls.add_method('SpinWait',
'bool',
[param('uint64_t', 'ns')],
visibility='protected')
## wall-clock-synchronizer.h (module 'core'): void ns3::WallClockSynchronizer::TimevalAdd(timeval * tv1, timeval * tv2, timeval * result) [member function]
cls.add_method('TimevalAdd',
'void',
[param('timeval *', 'tv1'), param('timeval *', 'tv2'), param('timeval *', 'result')],
visibility='protected')
## wall-clock-synchronizer.h (module 'core'): uint64_t ns3::WallClockSynchronizer::TimevalToNs(timeval * tv) [member function]
cls.add_method('TimevalToNs',
'uint64_t',
[param('timeval *', 'tv')],
visibility='protected')
return
def register_Ns3WeibullRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::WeibullRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::WeibullRandomVariable::WeibullRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetScale() const [member function]
cls.add_method('GetScale',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetShape() const [member function]
cls.add_method('GetShape',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetBound() const [member function]
cls.add_method('GetBound',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetValue(double scale, double shape, double bound) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'scale'), param('double', 'shape'), param('double', 'bound')])
## random-variable-stream.h (module 'core'): uint32_t ns3::WeibullRandomVariable::GetInteger(uint32_t scale, uint32_t shape, uint32_t bound) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'scale'), param('uint32_t', 'shape'), param('uint32_t', 'bound')])
## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::WeibullRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3ZetaRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ZetaRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::ZetaRandomVariable::ZetaRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::ZetaRandomVariable::GetAlpha() const [member function]
cls.add_method('GetAlpha',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ZetaRandomVariable::GetValue(double alpha) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'alpha')])
## random-variable-stream.h (module 'core'): uint32_t ns3::ZetaRandomVariable::GetInteger(uint32_t alpha) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'alpha')])
## random-variable-stream.h (module 'core'): double ns3::ZetaRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::ZetaRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3ZipfRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ZipfRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::ZipfRandomVariable::ZipfRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): uint32_t ns3::ZipfRandomVariable::GetN() const [member function]
cls.add_method('GetN',
'uint32_t',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ZipfRandomVariable::GetAlpha() const [member function]
cls.add_method('GetAlpha',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ZipfRandomVariable::GetValue(uint32_t n, double alpha) [member function]
cls.add_method('GetValue',
'double',
[param('uint32_t', 'n'), param('double', 'alpha')])
## random-variable-stream.h (module 'core'): uint32_t ns3::ZipfRandomVariable::GetInteger(uint32_t n, uint32_t alpha) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'n'), param('uint32_t', 'alpha')])
## random-variable-stream.h (module 'core'): double ns3::ZipfRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::ZipfRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3AttributeAccessor_methods(root_module, cls):
## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor(ns3::AttributeAccessor const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AttributeAccessor const &', 'arg0')])
## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor() [constructor]
cls.add_constructor([])
## attribute.h (module 'core'): bool ns3::AttributeAccessor::Get(ns3::ObjectBase const * object, ns3::AttributeValue & attribute) const [member function]
cls.add_method('Get',
'bool',
[param('ns3::ObjectBase const *', 'object'), param('ns3::AttributeValue &', 'attribute')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeAccessor::HasGetter() const [member function]
cls.add_method('HasGetter',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeAccessor::HasSetter() const [member function]
cls.add_method('HasSetter',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeAccessor::Set(ns3::ObjectBase * object, ns3::AttributeValue const & value) const [member function]
cls.add_method('Set',
'bool',
[param('ns3::ObjectBase *', 'object', transfer_ownership=False), param('ns3::AttributeValue const &', 'value')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3AttributeChecker_methods(root_module, cls):
## attribute.h (module 'core'): ns3::AttributeChecker::AttributeChecker(ns3::AttributeChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AttributeChecker const &', 'arg0')])
## attribute.h (module 'core'): ns3::AttributeChecker::AttributeChecker() [constructor]
cls.add_constructor([])
## attribute.h (module 'core'): bool ns3::AttributeChecker::Check(ns3::AttributeValue const & value) const [member function]
cls.add_method('Check',
'bool',
[param('ns3::AttributeValue const &', 'value')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeChecker::Copy(ns3::AttributeValue const & source, ns3::AttributeValue & destination) const [member function]
cls.add_method('Copy',
'bool',
[param('ns3::AttributeValue const &', 'source'), param('ns3::AttributeValue &', 'destination')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeChecker::Create() const [member function]
cls.add_method('Create',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeChecker::CreateValidValue(ns3::AttributeValue const & value) const [member function]
cls.add_method('CreateValidValue',
'ns3::Ptr< ns3::AttributeValue >',
[param('ns3::AttributeValue const &', 'value')],
is_const=True)
## attribute.h (module 'core'): std::string ns3::AttributeChecker::GetUnderlyingTypeInformation() const [member function]
cls.add_method('GetUnderlyingTypeInformation',
'std::string',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): std::string ns3::AttributeChecker::GetValueTypeName() const [member function]
cls.add_method('GetValueTypeName',
'std::string',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeChecker::HasUnderlyingTypeInformation() const [member function]
cls.add_method('HasUnderlyingTypeInformation',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3AttributeValue_methods(root_module, cls):
## attribute.h (module 'core'): ns3::AttributeValue::AttributeValue(ns3::AttributeValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AttributeValue const &', 'arg0')])
## attribute.h (module 'core'): ns3::AttributeValue::AttributeValue() [constructor]
cls.add_constructor([])
## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_pure_virtual=True, is_virtual=True)
## attribute.h (module 'core'): std::string ns3::AttributeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3BooleanChecker_methods(root_module, cls):
## boolean.h (module 'core'): ns3::BooleanChecker::BooleanChecker() [constructor]
cls.add_constructor([])
## boolean.h (module 'core'): ns3::BooleanChecker::BooleanChecker(ns3::BooleanChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::BooleanChecker const &', 'arg0')])
return
def register_Ns3BooleanValue_methods(root_module, cls):
cls.add_output_stream_operator()
## boolean.h (module 'core'): ns3::BooleanValue::BooleanValue(ns3::BooleanValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::BooleanValue const &', 'arg0')])
## boolean.h (module 'core'): ns3::BooleanValue::BooleanValue() [constructor]
cls.add_constructor([])
## boolean.h (module 'core'): ns3::BooleanValue::BooleanValue(bool value) [constructor]
cls.add_constructor([param('bool', 'value')])
## boolean.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::BooleanValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## boolean.h (module 'core'): bool ns3::BooleanValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## boolean.h (module 'core'): bool ns3::BooleanValue::Get() const [member function]
cls.add_method('Get',
'bool',
[],
is_const=True)
## boolean.h (module 'core'): std::string ns3::BooleanValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## boolean.h (module 'core'): void ns3::BooleanValue::Set(bool value) [member function]
cls.add_method('Set',
'void',
[param('bool', 'value')])
return
def register_Ns3CalendarScheduler_methods(root_module, cls):
## calendar-scheduler.h (module 'core'): ns3::CalendarScheduler::CalendarScheduler(ns3::CalendarScheduler const & arg0) [copy constructor]
cls.add_constructor([param('ns3::CalendarScheduler const &', 'arg0')])
## calendar-scheduler.h (module 'core'): ns3::CalendarScheduler::CalendarScheduler() [constructor]
cls.add_constructor([])
## calendar-scheduler.h (module 'core'): static ns3::TypeId ns3::CalendarScheduler::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## calendar-scheduler.h (module 'core'): void ns3::CalendarScheduler::Insert(ns3::Scheduler::Event const & ev) [member function]
cls.add_method('Insert',
'void',
[param('ns3::Scheduler::Event const &', 'ev')],
is_virtual=True)
## calendar-scheduler.h (module 'core'): bool ns3::CalendarScheduler::IsEmpty() const [member function]
cls.add_method('IsEmpty',
'bool',
[],
is_const=True, is_virtual=True)
## calendar-scheduler.h (module 'core'): ns3::Scheduler::Event ns3::CalendarScheduler::PeekNext() const [member function]
cls.add_method('PeekNext',
'ns3::Scheduler::Event',
[],
is_const=True, is_virtual=True)
## calendar-scheduler.h (module 'core'): void ns3::CalendarScheduler::Remove(ns3::Scheduler::Event const & ev) [member function]
cls.add_method('Remove',
'void',
[param('ns3::Scheduler::Event const &', 'ev')],
is_virtual=True)
## calendar-scheduler.h (module 'core'): ns3::Scheduler::Event ns3::CalendarScheduler::RemoveNext() [member function]
cls.add_method('RemoveNext',
'ns3::Scheduler::Event',
[],
is_virtual=True)
return
def register_Ns3CallbackChecker_methods(root_module, cls):
## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker() [constructor]
cls.add_constructor([])
## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker(ns3::CallbackChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::CallbackChecker const &', 'arg0')])
return
def register_Ns3CallbackImplBase_methods(root_module, cls):
## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase() [constructor]
cls.add_constructor([])
## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase(ns3::CallbackImplBase const & arg0) [copy constructor]
cls.add_constructor([param('ns3::CallbackImplBase const &', 'arg0')])
## callback.h (module 'core'): std::string ns3::CallbackImplBase::GetTypeid() const [member function]
cls.add_method('GetTypeid',
'std::string',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## callback.h (module 'core'): bool ns3::CallbackImplBase::IsEqual(ns3::Ptr<ns3::CallbackImplBase const> other) const [member function]
cls.add_method('IsEqual',
'bool',
[param('ns3::Ptr< ns3::CallbackImplBase const >', 'other')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## callback.h (module 'core'): static std::string ns3::CallbackImplBase::Demangle(std::string const & mangled) [member function]
cls.add_method('Demangle',
'std::string',
[param('std::string const &', 'mangled')],
is_static=True, visibility='protected')
return
def register_Ns3CallbackValue_methods(root_module, cls):
## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::CallbackValue const &', 'arg0')])
## callback.h (module 'core'): ns3::CallbackValue::CallbackValue() [constructor]
cls.add_constructor([])
## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackBase const & base) [constructor]
cls.add_constructor([param('ns3::CallbackBase const &', 'base')])
## callback.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::CallbackValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## callback.h (module 'core'): bool ns3::CallbackValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## callback.h (module 'core'): std::string ns3::CallbackValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## callback.h (module 'core'): void ns3::CallbackValue::Set(ns3::CallbackBase base) [member function]
cls.add_method('Set',
'void',
[param('ns3::CallbackBase', 'base')])
return
def register_Ns3ConstantRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ConstantRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::ConstantRandomVariable::ConstantRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::ConstantRandomVariable::GetConstant() const [member function]
cls.add_method('GetConstant',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ConstantRandomVariable::GetValue(double constant) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'constant')])
## random-variable-stream.h (module 'core'): uint32_t ns3::ConstantRandomVariable::GetInteger(uint32_t constant) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'constant')])
## random-variable-stream.h (module 'core'): double ns3::ConstantRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::ConstantRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3DefaultSimulatorImpl_methods(root_module, cls):
## default-simulator-impl.h (module 'core'): ns3::DefaultSimulatorImpl::DefaultSimulatorImpl(ns3::DefaultSimulatorImpl const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DefaultSimulatorImpl const &', 'arg0')])
## default-simulator-impl.h (module 'core'): ns3::DefaultSimulatorImpl::DefaultSimulatorImpl() [constructor]
cls.add_constructor([])
## default-simulator-impl.h (module 'core'): void ns3::DefaultSimulatorImpl::Cancel(ns3::EventId const & id) [member function]
cls.add_method('Cancel',
'void',
[param('ns3::EventId const &', 'id')],
is_virtual=True)
## default-simulator-impl.h (module 'core'): void ns3::DefaultSimulatorImpl::Destroy() [member function]
cls.add_method('Destroy',
'void',
[],
is_virtual=True)
## default-simulator-impl.h (module 'core'): uint32_t ns3::DefaultSimulatorImpl::GetContext() const [member function]
cls.add_method('GetContext',
'uint32_t',
[],
is_const=True, is_virtual=True)
## default-simulator-impl.h (module 'core'): ns3::Time ns3::DefaultSimulatorImpl::GetDelayLeft(ns3::EventId const & id) const [member function]
cls.add_method('GetDelayLeft',
'ns3::Time',
[param('ns3::EventId const &', 'id')],
is_const=True, is_virtual=True)
## default-simulator-impl.h (module 'core'): ns3::Time ns3::DefaultSimulatorImpl::GetMaximumSimulationTime() const [member function]
cls.add_method('GetMaximumSimulationTime',
'ns3::Time',
[],
is_const=True, is_virtual=True)
## default-simulator-impl.h (module 'core'): uint32_t ns3::DefaultSimulatorImpl::GetSystemId() const [member function]
cls.add_method('GetSystemId',
'uint32_t',
[],
is_const=True, is_virtual=True)
## default-simulator-impl.h (module 'core'): static ns3::TypeId ns3::DefaultSimulatorImpl::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## default-simulator-impl.h (module 'core'): bool ns3::DefaultSimulatorImpl::IsExpired(ns3::EventId const & id) const [member function]
cls.add_method('IsExpired',
'bool',
[param('ns3::EventId const &', 'id')],
is_const=True, is_virtual=True)
## default-simulator-impl.h (module 'core'): bool ns3::DefaultSimulatorImpl::IsFinished() const [member function]
cls.add_method('IsFinished',
'bool',
[],
is_const=True, is_virtual=True)
## default-simulator-impl.h (module 'core'): ns3::Time ns3::DefaultSimulatorImpl::Now() const [member function]
cls.add_method('Now',
'ns3::Time',
[],
is_const=True, is_virtual=True)
## default-simulator-impl.h (module 'core'): void ns3::DefaultSimulatorImpl::Remove(ns3::EventId const & id) [member function]
cls.add_method('Remove',
'void',
[param('ns3::EventId const &', 'id')],
is_virtual=True)
## default-simulator-impl.h (module 'core'): void ns3::DefaultSimulatorImpl::Run() [member function]
cls.add_method('Run',
'void',
[],
is_virtual=True)
## default-simulator-impl.h (module 'core'): ns3::EventId ns3::DefaultSimulatorImpl::Schedule(ns3::Time const & delay, ns3::EventImpl * event) [member function]
cls.add_method('Schedule',
'ns3::EventId',
[param('ns3::Time const &', 'delay'), param('ns3::EventImpl *', 'event')],
is_virtual=True)
## default-simulator-impl.h (module 'core'): ns3::EventId ns3::DefaultSimulatorImpl::ScheduleDestroy(ns3::EventImpl * event) [member function]
cls.add_method('ScheduleDestroy',
'ns3::EventId',
[param('ns3::EventImpl *', 'event')],
is_virtual=True)
## default-simulator-impl.h (module 'core'): ns3::EventId ns3::DefaultSimulatorImpl::ScheduleNow(ns3::EventImpl * event) [member function]
cls.add_method('ScheduleNow',
'ns3::EventId',
[param('ns3::EventImpl *', 'event')],
is_virtual=True)
## default-simulator-impl.h (module 'core'): void ns3::DefaultSimulatorImpl::ScheduleWithContext(uint32_t context, ns3::Time const & delay, ns3::EventImpl * event) [member function]
cls.add_method('ScheduleWithContext',
'void',
[param('uint32_t', 'context'), param('ns3::Time const &', 'delay'), param('ns3::EventImpl *', 'event')],
is_virtual=True)
## default-simulator-impl.h (module 'core'): void ns3::DefaultSimulatorImpl::SetScheduler(ns3::ObjectFactory schedulerFactory) [member function]
cls.add_method('SetScheduler',
'void',
[param('ns3::ObjectFactory', 'schedulerFactory')],
is_virtual=True)
## default-simulator-impl.h (module 'core'): void ns3::DefaultSimulatorImpl::Stop() [member function]
cls.add_method('Stop',
'void',
[],
is_virtual=True)
## default-simulator-impl.h (module 'core'): void ns3::DefaultSimulatorImpl::Stop(ns3::Time const & delay) [member function]
cls.add_method('Stop',
'void',
[param('ns3::Time const &', 'delay')],
is_virtual=True)
## default-simulator-impl.h (module 'core'): void ns3::DefaultSimulatorImpl::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3DeterministicRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::DeterministicRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::DeterministicRandomVariable::DeterministicRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): void ns3::DeterministicRandomVariable::SetValueArray(double * values, uint64_t length) [member function]
cls.add_method('SetValueArray',
'void',
[param('double *', 'values'), param('uint64_t', 'length')])
## random-variable-stream.h (module 'core'): double ns3::DeterministicRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::DeterministicRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3DoubleValue_methods(root_module, cls):
## double.h (module 'core'): ns3::DoubleValue::DoubleValue() [constructor]
cls.add_constructor([])
## double.h (module 'core'): ns3::DoubleValue::DoubleValue(ns3::DoubleValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DoubleValue const &', 'arg0')])
## double.h (module 'core'): ns3::DoubleValue::DoubleValue(double const & value) [constructor]
cls.add_constructor([param('double const &', 'value')])
## double.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::DoubleValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## double.h (module 'core'): bool ns3::DoubleValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## double.h (module 'core'): double ns3::DoubleValue::Get() const [member function]
cls.add_method('Get',
'double',
[],
is_const=True)
## double.h (module 'core'): std::string ns3::DoubleValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## double.h (module 'core'): void ns3::DoubleValue::Set(double const & value) [member function]
cls.add_method('Set',
'void',
[param('double const &', 'value')])
return
def register_Ns3EmpiricalRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): ns3::EmpiricalRandomVariable::EmpiricalRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): void ns3::EmpiricalRandomVariable::CDF(double v, double c) [member function]
cls.add_method('CDF',
'void',
[param('double', 'v'), param('double', 'c')])
## random-variable-stream.h (module 'core'): uint32_t ns3::EmpiricalRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::EmpiricalRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): double ns3::EmpiricalRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): double ns3::EmpiricalRandomVariable::Interpolate(double c1, double c2, double v1, double v2, double r) [member function]
cls.add_method('Interpolate',
'double',
[param('double', 'c1'), param('double', 'c2'), param('double', 'v1'), param('double', 'v2'), param('double', 'r')],
visibility='private', is_virtual=True)
## random-variable-stream.h (module 'core'): void ns3::EmpiricalRandomVariable::Validate() [member function]
cls.add_method('Validate',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3EmptyAttributeValue_methods(root_module, cls):
## attribute.h (module 'core'): ns3::EmptyAttributeValue::EmptyAttributeValue(ns3::EmptyAttributeValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EmptyAttributeValue const &', 'arg0')])
## attribute.h (module 'core'): ns3::EmptyAttributeValue::EmptyAttributeValue() [constructor]
cls.add_constructor([])
## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EmptyAttributeValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, visibility='private', is_virtual=True)
## attribute.h (module 'core'): bool ns3::EmptyAttributeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
visibility='private', is_virtual=True)
## attribute.h (module 'core'): std::string ns3::EmptyAttributeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3EnumChecker_methods(root_module, cls):
## enum.h (module 'core'): ns3::EnumChecker::EnumChecker(ns3::EnumChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EnumChecker const &', 'arg0')])
## enum.h (module 'core'): ns3::EnumChecker::EnumChecker() [constructor]
cls.add_constructor([])
## enum.h (module 'core'): void ns3::EnumChecker::Add(int value, std::string name) [member function]
cls.add_method('Add',
'void',
[param('int', 'value'), param('std::string', 'name')])
## enum.h (module 'core'): void ns3::EnumChecker::AddDefault(int value, std::string name) [member function]
cls.add_method('AddDefault',
'void',
[param('int', 'value'), param('std::string', 'name')])
## enum.h (module 'core'): bool ns3::EnumChecker::Check(ns3::AttributeValue const & value) const [member function]
cls.add_method('Check',
'bool',
[param('ns3::AttributeValue const &', 'value')],
is_const=True, is_virtual=True)
## enum.h (module 'core'): bool ns3::EnumChecker::Copy(ns3::AttributeValue const & src, ns3::AttributeValue & dst) const [member function]
cls.add_method('Copy',
'bool',
[param('ns3::AttributeValue const &', 'src'), param('ns3::AttributeValue &', 'dst')],
is_const=True, is_virtual=True)
## enum.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EnumChecker::Create() const [member function]
cls.add_method('Create',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## enum.h (module 'core'): std::string ns3::EnumChecker::GetUnderlyingTypeInformation() const [member function]
cls.add_method('GetUnderlyingTypeInformation',
'std::string',
[],
is_const=True, is_virtual=True)
## enum.h (module 'core'): std::string ns3::EnumChecker::GetValueTypeName() const [member function]
cls.add_method('GetValueTypeName',
'std::string',
[],
is_const=True, is_virtual=True)
## enum.h (module 'core'): bool ns3::EnumChecker::HasUnderlyingTypeInformation() const [member function]
cls.add_method('HasUnderlyingTypeInformation',
'bool',
[],
is_const=True, is_virtual=True)
return
def register_Ns3EnumValue_methods(root_module, cls):
## enum.h (module 'core'): ns3::EnumValue::EnumValue(ns3::EnumValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EnumValue const &', 'arg0')])
## enum.h (module 'core'): ns3::EnumValue::EnumValue() [constructor]
cls.add_constructor([])
## enum.h (module 'core'): ns3::EnumValue::EnumValue(int value) [constructor]
cls.add_constructor([param('int', 'value')])
## enum.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EnumValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## enum.h (module 'core'): bool ns3::EnumValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## enum.h (module 'core'): int ns3::EnumValue::Get() const [member function]
cls.add_method('Get',
'int',
[],
is_const=True)
## enum.h (module 'core'): std::string ns3::EnumValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## enum.h (module 'core'): void ns3::EnumValue::Set(int value) [member function]
cls.add_method('Set',
'void',
[param('int', 'value')])
return
def register_Ns3ErlangRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ErlangRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::ErlangRandomVariable::ErlangRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): uint32_t ns3::ErlangRandomVariable::GetK() const [member function]
cls.add_method('GetK',
'uint32_t',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ErlangRandomVariable::GetLambda() const [member function]
cls.add_method('GetLambda',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ErlangRandomVariable::GetValue(uint32_t k, double lambda) [member function]
cls.add_method('GetValue',
'double',
[param('uint32_t', 'k'), param('double', 'lambda')])
## random-variable-stream.h (module 'core'): uint32_t ns3::ErlangRandomVariable::GetInteger(uint32_t k, uint32_t lambda) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'k'), param('uint32_t', 'lambda')])
## random-variable-stream.h (module 'core'): double ns3::ErlangRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::ErlangRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3EventImpl_methods(root_module, cls):
## event-impl.h (module 'core'): ns3::EventImpl::EventImpl(ns3::EventImpl const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EventImpl const &', 'arg0')])
## event-impl.h (module 'core'): ns3::EventImpl::EventImpl() [constructor]
cls.add_constructor([])
## event-impl.h (module 'core'): void ns3::EventImpl::Cancel() [member function]
cls.add_method('Cancel',
'void',
[])
## event-impl.h (module 'core'): void ns3::EventImpl::Invoke() [member function]
cls.add_method('Invoke',
'void',
[])
## event-impl.h (module 'core'): bool ns3::EventImpl::IsCancelled() [member function]
cls.add_method('IsCancelled',
'bool',
[])
## event-impl.h (module 'core'): void ns3::EventImpl::Notify() [member function]
cls.add_method('Notify',
'void',
[],
is_pure_virtual=True, visibility='protected', is_virtual=True)
return
def register_Ns3ExponentialRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ExponentialRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::ExponentialRandomVariable::ExponentialRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetMean() const [member function]
cls.add_method('GetMean',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetBound() const [member function]
cls.add_method('GetBound',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetValue(double mean, double bound) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'mean'), param('double', 'bound')])
## random-variable-stream.h (module 'core'): uint32_t ns3::ExponentialRandomVariable::GetInteger(uint32_t mean, uint32_t bound) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'mean'), param('uint32_t', 'bound')])
## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::ExponentialRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3FdReader_methods(root_module, cls):
## unix-fd-reader.h (module 'core'): ns3::FdReader::FdReader(ns3::FdReader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::FdReader const &', 'arg0')])
## unix-fd-reader.h (module 'core'): ns3::FdReader::FdReader() [constructor]
cls.add_constructor([])
## unix-fd-reader.h (module 'core'): void ns3::FdReader::Start(int fd, ns3::Callback<void, unsigned char*, long, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> readCallback) [member function]
cls.add_method('Start',
'void',
[param('int', 'fd'), param('ns3::Callback< void, unsigned char *, long, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'readCallback')])
## unix-fd-reader.h (module 'core'): void ns3::FdReader::Stop() [member function]
cls.add_method('Stop',
'void',
[])
## unix-fd-reader.h (module 'core'): ns3::FdReader::Data ns3::FdReader::DoRead() [member function]
cls.add_method('DoRead',
'ns3::FdReader::Data',
[],
is_pure_virtual=True, visibility='protected', is_virtual=True)
return
def register_Ns3GammaRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::GammaRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::GammaRandomVariable::GammaRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetAlpha() const [member function]
cls.add_method('GetAlpha',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetBeta() const [member function]
cls.add_method('GetBeta',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetValue(double alpha, double beta) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'alpha'), param('double', 'beta')])
## random-variable-stream.h (module 'core'): uint32_t ns3::GammaRandomVariable::GetInteger(uint32_t alpha, uint32_t beta) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'alpha'), param('uint32_t', 'beta')])
## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::GammaRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3HeapScheduler_methods(root_module, cls):
## heap-scheduler.h (module 'core'): ns3::HeapScheduler::HeapScheduler(ns3::HeapScheduler const & arg0) [copy constructor]
cls.add_constructor([param('ns3::HeapScheduler const &', 'arg0')])
## heap-scheduler.h (module 'core'): ns3::HeapScheduler::HeapScheduler() [constructor]
cls.add_constructor([])
## heap-scheduler.h (module 'core'): static ns3::TypeId ns3::HeapScheduler::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## heap-scheduler.h (module 'core'): void ns3::HeapScheduler::Insert(ns3::Scheduler::Event const & ev) [member function]
cls.add_method('Insert',
'void',
[param('ns3::Scheduler::Event const &', 'ev')],
is_virtual=True)
## heap-scheduler.h (module 'core'): bool ns3::HeapScheduler::IsEmpty() const [member function]
cls.add_method('IsEmpty',
'bool',
[],
is_const=True, is_virtual=True)
## heap-scheduler.h (module 'core'): ns3::Scheduler::Event ns3::HeapScheduler::PeekNext() const [member function]
cls.add_method('PeekNext',
'ns3::Scheduler::Event',
[],
is_const=True, is_virtual=True)
## heap-scheduler.h (module 'core'): void ns3::HeapScheduler::Remove(ns3::Scheduler::Event const & ev) [member function]
cls.add_method('Remove',
'void',
[param('ns3::Scheduler::Event const &', 'ev')],
is_virtual=True)
## heap-scheduler.h (module 'core'): ns3::Scheduler::Event ns3::HeapScheduler::RemoveNext() [member function]
cls.add_method('RemoveNext',
'ns3::Scheduler::Event',
[],
is_virtual=True)
return
def register_Ns3IntegerValue_methods(root_module, cls):
## integer.h (module 'core'): ns3::IntegerValue::IntegerValue() [constructor]
cls.add_constructor([])
## integer.h (module 'core'): ns3::IntegerValue::IntegerValue(ns3::IntegerValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::IntegerValue const &', 'arg0')])
## integer.h (module 'core'): ns3::IntegerValue::IntegerValue(int64_t const & value) [constructor]
cls.add_constructor([param('int64_t const &', 'value')])
## integer.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::IntegerValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## integer.h (module 'core'): bool ns3::IntegerValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## integer.h (module 'core'): int64_t ns3::IntegerValue::Get() const [member function]
cls.add_method('Get',
'int64_t',
[],
is_const=True)
## integer.h (module 'core'): std::string ns3::IntegerValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## integer.h (module 'core'): void ns3::IntegerValue::Set(int64_t const & value) [member function]
cls.add_method('Set',
'void',
[param('int64_t const &', 'value')])
return
def register_Ns3ListScheduler_methods(root_module, cls):
## list-scheduler.h (module 'core'): ns3::ListScheduler::ListScheduler(ns3::ListScheduler const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ListScheduler const &', 'arg0')])
## list-scheduler.h (module 'core'): ns3::ListScheduler::ListScheduler() [constructor]
cls.add_constructor([])
## list-scheduler.h (module 'core'): static ns3::TypeId ns3::ListScheduler::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## list-scheduler.h (module 'core'): void ns3::ListScheduler::Insert(ns3::Scheduler::Event const & ev) [member function]
cls.add_method('Insert',
'void',
[param('ns3::Scheduler::Event const &', 'ev')],
is_virtual=True)
## list-scheduler.h (module 'core'): bool ns3::ListScheduler::IsEmpty() const [member function]
cls.add_method('IsEmpty',
'bool',
[],
is_const=True, is_virtual=True)
## list-scheduler.h (module 'core'): ns3::Scheduler::Event ns3::ListScheduler::PeekNext() const [member function]
cls.add_method('PeekNext',
'ns3::Scheduler::Event',
[],
is_const=True, is_virtual=True)
## list-scheduler.h (module 'core'): void ns3::ListScheduler::Remove(ns3::Scheduler::Event const & ev) [member function]
cls.add_method('Remove',
'void',
[param('ns3::Scheduler::Event const &', 'ev')],
is_virtual=True)
## list-scheduler.h (module 'core'): ns3::Scheduler::Event ns3::ListScheduler::RemoveNext() [member function]
cls.add_method('RemoveNext',
'ns3::Scheduler::Event',
[],
is_virtual=True)
return
def register_Ns3LogNormalRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::LogNormalRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::LogNormalRandomVariable::LogNormalRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::LogNormalRandomVariable::GetMu() const [member function]
cls.add_method('GetMu',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::LogNormalRandomVariable::GetSigma() const [member function]
cls.add_method('GetSigma',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::LogNormalRandomVariable::GetValue(double mu, double sigma) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'mu'), param('double', 'sigma')])
## random-variable-stream.h (module 'core'): uint32_t ns3::LogNormalRandomVariable::GetInteger(uint32_t mu, uint32_t sigma) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'mu'), param('uint32_t', 'sigma')])
## random-variable-stream.h (module 'core'): double ns3::LogNormalRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::LogNormalRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3MapScheduler_methods(root_module, cls):
## map-scheduler.h (module 'core'): ns3::MapScheduler::MapScheduler(ns3::MapScheduler const & arg0) [copy constructor]
cls.add_constructor([param('ns3::MapScheduler const &', 'arg0')])
## map-scheduler.h (module 'core'): ns3::MapScheduler::MapScheduler() [constructor]
cls.add_constructor([])
## map-scheduler.h (module 'core'): static ns3::TypeId ns3::MapScheduler::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## map-scheduler.h (module 'core'): void ns3::MapScheduler::Insert(ns3::Scheduler::Event const & ev) [member function]
cls.add_method('Insert',
'void',
[param('ns3::Scheduler::Event const &', 'ev')],
is_virtual=True)
## map-scheduler.h (module 'core'): bool ns3::MapScheduler::IsEmpty() const [member function]
cls.add_method('IsEmpty',
'bool',
[],
is_const=True, is_virtual=True)
## map-scheduler.h (module 'core'): ns3::Scheduler::Event ns3::MapScheduler::PeekNext() const [member function]
cls.add_method('PeekNext',
'ns3::Scheduler::Event',
[],
is_const=True, is_virtual=True)
## map-scheduler.h (module 'core'): void ns3::MapScheduler::Remove(ns3::Scheduler::Event const & ev) [member function]
cls.add_method('Remove',
'void',
[param('ns3::Scheduler::Event const &', 'ev')],
is_virtual=True)
## map-scheduler.h (module 'core'): ns3::Scheduler::Event ns3::MapScheduler::RemoveNext() [member function]
cls.add_method('RemoveNext',
'ns3::Scheduler::Event',
[],
is_virtual=True)
return
def register_Ns3NormalRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): ns3::NormalRandomVariable::INFINITE_VALUE [variable]
cls.add_static_attribute('INFINITE_VALUE', 'double const', is_const=True)
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::NormalRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::NormalRandomVariable::NormalRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetMean() const [member function]
cls.add_method('GetMean',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetVariance() const [member function]
cls.add_method('GetVariance',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetBound() const [member function]
cls.add_method('GetBound',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetValue(double mean, double variance, double bound=ns3::NormalRandomVariable::INFINITE_VALUE) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'mean'), param('double', 'variance'), param('double', 'bound', default_value='ns3::NormalRandomVariable::INFINITE_VALUE')])
## random-variable-stream.h (module 'core'): uint32_t ns3::NormalRandomVariable::GetInteger(uint32_t mean, uint32_t variance, uint32_t bound) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'mean'), param('uint32_t', 'variance'), param('uint32_t', 'bound')])
## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::NormalRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3ObjectFactoryChecker_methods(root_module, cls):
## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker() [constructor]
cls.add_constructor([])
## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker(ns3::ObjectFactoryChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ObjectFactoryChecker const &', 'arg0')])
return
def register_Ns3ObjectFactoryValue_methods(root_module, cls):
## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue() [constructor]
cls.add_constructor([])
## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactoryValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ObjectFactoryValue const &', 'arg0')])
## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactory const & value) [constructor]
cls.add_constructor([param('ns3::ObjectFactory const &', 'value')])
## object-factory.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::ObjectFactoryValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## object-factory.h (module 'core'): bool ns3::ObjectFactoryValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## object-factory.h (module 'core'): ns3::ObjectFactory ns3::ObjectFactoryValue::Get() const [member function]
cls.add_method('Get',
'ns3::ObjectFactory',
[],
is_const=True)
## object-factory.h (module 'core'): std::string ns3::ObjectFactoryValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## object-factory.h (module 'core'): void ns3::ObjectFactoryValue::Set(ns3::ObjectFactory const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::ObjectFactory const &', 'value')])
return
def register_Ns3ObjectPtrContainerAccessor_methods(root_module, cls):
## object-ptr-container.h (module 'core'): ns3::ObjectPtrContainerAccessor::ObjectPtrContainerAccessor() [constructor]
cls.add_constructor([])
## object-ptr-container.h (module 'core'): ns3::ObjectPtrContainerAccessor::ObjectPtrContainerAccessor(ns3::ObjectPtrContainerAccessor const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ObjectPtrContainerAccessor const &', 'arg0')])
## object-ptr-container.h (module 'core'): bool ns3::ObjectPtrContainerAccessor::Get(ns3::ObjectBase const * object, ns3::AttributeValue & value) const [member function]
cls.add_method('Get',
'bool',
[param('ns3::ObjectBase const *', 'object'), param('ns3::AttributeValue &', 'value')],
is_const=True, is_virtual=True)
## object-ptr-container.h (module 'core'): bool ns3::ObjectPtrContainerAccessor::HasGetter() const [member function]
cls.add_method('HasGetter',
'bool',
[],
is_const=True, is_virtual=True)
## object-ptr-container.h (module 'core'): bool ns3::ObjectPtrContainerAccessor::HasSetter() const [member function]
cls.add_method('HasSetter',
'bool',
[],
is_const=True, is_virtual=True)
## object-ptr-container.h (module 'core'): bool ns3::ObjectPtrContainerAccessor::Set(ns3::ObjectBase * object, ns3::AttributeValue const & value) const [member function]
cls.add_method('Set',
'bool',
[param('ns3::ObjectBase *', 'object'), param('ns3::AttributeValue const &', 'value')],
is_const=True, is_virtual=True)
## object-ptr-container.h (module 'core'): ns3::Ptr<ns3::Object> ns3::ObjectPtrContainerAccessor::DoGet(ns3::ObjectBase const * object, uint32_t i, uint32_t * index) const [member function]
cls.add_method('DoGet',
'ns3::Ptr< ns3::Object >',
[param('ns3::ObjectBase const *', 'object'), param('uint32_t', 'i'), param('uint32_t *', 'index')],
is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True)
## object-ptr-container.h (module 'core'): bool ns3::ObjectPtrContainerAccessor::DoGetN(ns3::ObjectBase const * object, uint32_t * n) const [member function]
cls.add_method('DoGetN',
'bool',
[param('ns3::ObjectBase const *', 'object'), param('uint32_t *', 'n')],
is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3ObjectPtrContainerChecker_methods(root_module, cls):
## object-ptr-container.h (module 'core'): ns3::ObjectPtrContainerChecker::ObjectPtrContainerChecker() [constructor]
cls.add_constructor([])
## object-ptr-container.h (module 'core'): ns3::ObjectPtrContainerChecker::ObjectPtrContainerChecker(ns3::ObjectPtrContainerChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ObjectPtrContainerChecker const &', 'arg0')])
## object-ptr-container.h (module 'core'): ns3::TypeId ns3::ObjectPtrContainerChecker::GetItemTypeId() const [member function]
cls.add_method('GetItemTypeId',
'ns3::TypeId',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3ObjectPtrContainerValue_methods(root_module, cls):
## object-ptr-container.h (module 'core'): ns3::ObjectPtrContainerValue::ObjectPtrContainerValue(ns3::ObjectPtrContainerValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ObjectPtrContainerValue const &', 'arg0')])
## object-ptr-container.h (module 'core'): ns3::ObjectPtrContainerValue::ObjectPtrContainerValue() [constructor]
cls.add_constructor([])
## object-ptr-container.h (module 'core'): std::_Rb_tree_const_iterator<std::pair<const unsigned int, ns3::Ptr<ns3::Object> > > ns3::ObjectPtrContainerValue::Begin() const [member function]
cls.add_method('Begin',
'std::_Rb_tree_const_iterator< std::pair< unsigned int const, ns3::Ptr< ns3::Object > > >',
[],
is_const=True)
## object-ptr-container.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::ObjectPtrContainerValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## object-ptr-container.h (module 'core'): bool ns3::ObjectPtrContainerValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## object-ptr-container.h (module 'core'): std::_Rb_tree_const_iterator<std::pair<const unsigned int, ns3::Ptr<ns3::Object> > > ns3::ObjectPtrContainerValue::End() const [member function]
cls.add_method('End',
'std::_Rb_tree_const_iterator< std::pair< unsigned int const, ns3::Ptr< ns3::Object > > >',
[],
is_const=True)
## object-ptr-container.h (module 'core'): ns3::Ptr<ns3::Object> ns3::ObjectPtrContainerValue::Get(uint32_t i) const [member function]
cls.add_method('Get',
'ns3::Ptr< ns3::Object >',
[param('uint32_t', 'i')],
is_const=True)
## object-ptr-container.h (module 'core'): uint32_t ns3::ObjectPtrContainerValue::GetN() const [member function]
cls.add_method('GetN',
'uint32_t',
[],
is_const=True)
## object-ptr-container.h (module 'core'): std::string ns3::ObjectPtrContainerValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
return
def register_Ns3ParetoRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ParetoRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::ParetoRandomVariable::ParetoRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetMean() const [member function]
cls.add_method('GetMean',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetShape() const [member function]
cls.add_method('GetShape',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetBound() const [member function]
cls.add_method('GetBound',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetValue(double mean, double shape, double bound) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'mean'), param('double', 'shape'), param('double', 'bound')])
## random-variable-stream.h (module 'core'): uint32_t ns3::ParetoRandomVariable::GetInteger(uint32_t mean, uint32_t shape, uint32_t bound) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'mean'), param('uint32_t', 'shape'), param('uint32_t', 'bound')])
## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::ParetoRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3PointerChecker_methods(root_module, cls):
## pointer.h (module 'core'): ns3::PointerChecker::PointerChecker() [constructor]
cls.add_constructor([])
## pointer.h (module 'core'): ns3::PointerChecker::PointerChecker(ns3::PointerChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PointerChecker const &', 'arg0')])
## pointer.h (module 'core'): ns3::TypeId ns3::PointerChecker::GetPointeeTypeId() const [member function]
cls.add_method('GetPointeeTypeId',
'ns3::TypeId',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3PointerValue_methods(root_module, cls):
## pointer.h (module 'core'): ns3::PointerValue::PointerValue(ns3::PointerValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PointerValue const &', 'arg0')])
## pointer.h (module 'core'): ns3::PointerValue::PointerValue() [constructor]
cls.add_constructor([])
## pointer.h (module 'core'): ns3::PointerValue::PointerValue(ns3::Ptr<ns3::Object> object) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::Object >', 'object')])
## pointer.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::PointerValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## pointer.h (module 'core'): bool ns3::PointerValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## pointer.h (module 'core'): ns3::Ptr<ns3::Object> ns3::PointerValue::GetObject() const [member function]
cls.add_method('GetObject',
'ns3::Ptr< ns3::Object >',
[],
is_const=True)
## pointer.h (module 'core'): std::string ns3::PointerValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## pointer.h (module 'core'): void ns3::PointerValue::SetObject(ns3::Ptr<ns3::Object> object) [member function]
cls.add_method('SetObject',
'void',
[param('ns3::Ptr< ns3::Object >', 'object')])
return
def register_Ns3RealtimeSimulatorImpl_methods(root_module, cls):
## realtime-simulator-impl.h (module 'core'): ns3::RealtimeSimulatorImpl::RealtimeSimulatorImpl(ns3::RealtimeSimulatorImpl const & arg0) [copy constructor]
cls.add_constructor([param('ns3::RealtimeSimulatorImpl const &', 'arg0')])
## realtime-simulator-impl.h (module 'core'): ns3::RealtimeSimulatorImpl::RealtimeSimulatorImpl() [constructor]
cls.add_constructor([])
## realtime-simulator-impl.h (module 'core'): void ns3::RealtimeSimulatorImpl::Cancel(ns3::EventId const & ev) [member function]
cls.add_method('Cancel',
'void',
[param('ns3::EventId const &', 'ev')],
is_virtual=True)
## realtime-simulator-impl.h (module 'core'): void ns3::RealtimeSimulatorImpl::Destroy() [member function]
cls.add_method('Destroy',
'void',
[],
is_virtual=True)
## realtime-simulator-impl.h (module 'core'): uint32_t ns3::RealtimeSimulatorImpl::GetContext() const [member function]
cls.add_method('GetContext',
'uint32_t',
[],
is_const=True, is_virtual=True)
## realtime-simulator-impl.h (module 'core'): ns3::Time ns3::RealtimeSimulatorImpl::GetDelayLeft(ns3::EventId const & id) const [member function]
cls.add_method('GetDelayLeft',
'ns3::Time',
[param('ns3::EventId const &', 'id')],
is_const=True, is_virtual=True)
## realtime-simulator-impl.h (module 'core'): ns3::Time ns3::RealtimeSimulatorImpl::GetHardLimit() const [member function]
cls.add_method('GetHardLimit',
'ns3::Time',
[],
is_const=True)
## realtime-simulator-impl.h (module 'core'): ns3::Time ns3::RealtimeSimulatorImpl::GetMaximumSimulationTime() const [member function]
cls.add_method('GetMaximumSimulationTime',
'ns3::Time',
[],
is_const=True, is_virtual=True)
## realtime-simulator-impl.h (module 'core'): ns3::RealtimeSimulatorImpl::SynchronizationMode ns3::RealtimeSimulatorImpl::GetSynchronizationMode() const [member function]
cls.add_method('GetSynchronizationMode',
'ns3::RealtimeSimulatorImpl::SynchronizationMode',
[],
is_const=True)
## realtime-simulator-impl.h (module 'core'): uint32_t ns3::RealtimeSimulatorImpl::GetSystemId() const [member function]
cls.add_method('GetSystemId',
'uint32_t',
[],
is_const=True, is_virtual=True)
## realtime-simulator-impl.h (module 'core'): static ns3::TypeId ns3::RealtimeSimulatorImpl::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## realtime-simulator-impl.h (module 'core'): bool ns3::RealtimeSimulatorImpl::IsExpired(ns3::EventId const & ev) const [member function]
cls.add_method('IsExpired',
'bool',
[param('ns3::EventId const &', 'ev')],
is_const=True, is_virtual=True)
## realtime-simulator-impl.h (module 'core'): bool ns3::RealtimeSimulatorImpl::IsFinished() const [member function]
cls.add_method('IsFinished',
'bool',
[],
is_const=True, is_virtual=True)
## realtime-simulator-impl.h (module 'core'): ns3::Time ns3::RealtimeSimulatorImpl::Now() const [member function]
cls.add_method('Now',
'ns3::Time',
[],
is_const=True, is_virtual=True)
## realtime-simulator-impl.h (module 'core'): ns3::Time ns3::RealtimeSimulatorImpl::RealtimeNow() const [member function]
cls.add_method('RealtimeNow',
'ns3::Time',
[],
is_const=True)
## realtime-simulator-impl.h (module 'core'): void ns3::RealtimeSimulatorImpl::Remove(ns3::EventId const & ev) [member function]
cls.add_method('Remove',
'void',
[param('ns3::EventId const &', 'ev')],
is_virtual=True)
## realtime-simulator-impl.h (module 'core'): void ns3::RealtimeSimulatorImpl::Run() [member function]
cls.add_method('Run',
'void',
[],
is_virtual=True)
## realtime-simulator-impl.h (module 'core'): ns3::EventId ns3::RealtimeSimulatorImpl::Schedule(ns3::Time const & delay, ns3::EventImpl * event) [member function]
cls.add_method('Schedule',
'ns3::EventId',
[param('ns3::Time const &', 'delay'), param('ns3::EventImpl *', 'event')],
is_virtual=True)
## realtime-simulator-impl.h (module 'core'): ns3::EventId ns3::RealtimeSimulatorImpl::ScheduleDestroy(ns3::EventImpl * event) [member function]
cls.add_method('ScheduleDestroy',
'ns3::EventId',
[param('ns3::EventImpl *', 'event')],
is_virtual=True)
## realtime-simulator-impl.h (module 'core'): ns3::EventId ns3::RealtimeSimulatorImpl::ScheduleNow(ns3::EventImpl * event) [member function]
cls.add_method('ScheduleNow',
'ns3::EventId',
[param('ns3::EventImpl *', 'event')],
is_virtual=True)
## realtime-simulator-impl.h (module 'core'): void ns3::RealtimeSimulatorImpl::ScheduleRealtime(ns3::Time const & delay, ns3::EventImpl * event) [member function]
cls.add_method('ScheduleRealtime',
'void',
[param('ns3::Time const &', 'delay'), param('ns3::EventImpl *', 'event')])
## realtime-simulator-impl.h (module 'core'): void ns3::RealtimeSimulatorImpl::ScheduleRealtimeNow(ns3::EventImpl * event) [member function]
cls.add_method('ScheduleRealtimeNow',
'void',
[param('ns3::EventImpl *', 'event')])
## realtime-simulator-impl.h (module 'core'): void ns3::RealtimeSimulatorImpl::ScheduleRealtimeNowWithContext(uint32_t context, ns3::EventImpl * event) [member function]
cls.add_method('ScheduleRealtimeNowWithContext',
'void',
[param('uint32_t', 'context'), param('ns3::EventImpl *', 'event')])
## realtime-simulator-impl.h (module 'core'): void ns3::RealtimeSimulatorImpl::ScheduleRealtimeWithContext(uint32_t context, ns3::Time const & delay, ns3::EventImpl * event) [member function]
cls.add_method('ScheduleRealtimeWithContext',
'void',
[param('uint32_t', 'context'), param('ns3::Time const &', 'delay'), param('ns3::EventImpl *', 'event')])
## realtime-simulator-impl.h (module 'core'): void ns3::RealtimeSimulatorImpl::ScheduleWithContext(uint32_t context, ns3::Time const & delay, ns3::EventImpl * event) [member function]
cls.add_method('ScheduleWithContext',
'void',
[param('uint32_t', 'context'), param('ns3::Time const &', 'delay'), param('ns3::EventImpl *', 'event')],
is_virtual=True)
## realtime-simulator-impl.h (module 'core'): void ns3::RealtimeSimulatorImpl::SetHardLimit(ns3::Time limit) [member function]
cls.add_method('SetHardLimit',
'void',
[param('ns3::Time', 'limit')])
## realtime-simulator-impl.h (module 'core'): void ns3::RealtimeSimulatorImpl::SetScheduler(ns3::ObjectFactory schedulerFactory) [member function]
cls.add_method('SetScheduler',
'void',
[param('ns3::ObjectFactory', 'schedulerFactory')],
is_virtual=True)
## realtime-simulator-impl.h (module 'core'): void ns3::RealtimeSimulatorImpl::SetSynchronizationMode(ns3::RealtimeSimulatorImpl::SynchronizationMode mode) [member function]
cls.add_method('SetSynchronizationMode',
'void',
[param('ns3::RealtimeSimulatorImpl::SynchronizationMode', 'mode')])
## realtime-simulator-impl.h (module 'core'): void ns3::RealtimeSimulatorImpl::Stop() [member function]
cls.add_method('Stop',
'void',
[],
is_virtual=True)
## realtime-simulator-impl.h (module 'core'): void ns3::RealtimeSimulatorImpl::Stop(ns3::Time const & delay) [member function]
cls.add_method('Stop',
'void',
[param('ns3::Time const &', 'delay')],
is_virtual=True)
## realtime-simulator-impl.h (module 'core'): void ns3::RealtimeSimulatorImpl::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3RefCountBase_methods(root_module, cls):
## ref-count-base.h (module 'core'): ns3::RefCountBase::RefCountBase() [constructor]
cls.add_constructor([])
## ref-count-base.h (module 'core'): ns3::RefCountBase::RefCountBase(ns3::RefCountBase const & arg0) [copy constructor]
cls.add_constructor([param('ns3::RefCountBase const &', 'arg0')])
return
def register_Ns3StringChecker_methods(root_module, cls):
## string.h (module 'core'): ns3::StringChecker::StringChecker() [constructor]
cls.add_constructor([])
## string.h (module 'core'): ns3::StringChecker::StringChecker(ns3::StringChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::StringChecker const &', 'arg0')])
return
def register_Ns3StringValue_methods(root_module, cls):
## string.h (module 'core'): ns3::StringValue::StringValue() [constructor]
cls.add_constructor([])
## string.h (module 'core'): ns3::StringValue::StringValue(ns3::StringValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::StringValue const &', 'arg0')])
## string.h (module 'core'): ns3::StringValue::StringValue(std::string const & value) [constructor]
cls.add_constructor([param('std::string const &', 'value')])
## string.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::StringValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## string.h (module 'core'): bool ns3::StringValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## string.h (module 'core'): std::string ns3::StringValue::Get() const [member function]
cls.add_method('Get',
'std::string',
[],
is_const=True)
## string.h (module 'core'): std::string ns3::StringValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## string.h (module 'core'): void ns3::StringValue::Set(std::string const & value) [member function]
cls.add_method('Set',
'void',
[param('std::string const &', 'value')])
return
def register_Ns3TimeValue_methods(root_module, cls):
## nstime.h (module 'core'): ns3::TimeValue::TimeValue() [constructor]
cls.add_constructor([])
## nstime.h (module 'core'): ns3::TimeValue::TimeValue(ns3::TimeValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TimeValue const &', 'arg0')])
## nstime.h (module 'core'): ns3::TimeValue::TimeValue(ns3::Time const & value) [constructor]
cls.add_constructor([param('ns3::Time const &', 'value')])
## nstime.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::TimeValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## nstime.h (module 'core'): bool ns3::TimeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## nstime.h (module 'core'): ns3::Time ns3::TimeValue::Get() const [member function]
cls.add_method('Get',
'ns3::Time',
[],
is_const=True)
## nstime.h (module 'core'): std::string ns3::TimeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## nstime.h (module 'core'): void ns3::TimeValue::Set(ns3::Time const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Time const &', 'value')])
return
def register_Ns3TypeIdChecker_methods(root_module, cls):
## type-id.h (module 'core'): ns3::TypeIdChecker::TypeIdChecker() [constructor]
cls.add_constructor([])
## type-id.h (module 'core'): ns3::TypeIdChecker::TypeIdChecker(ns3::TypeIdChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TypeIdChecker const &', 'arg0')])
return
def register_Ns3TypeIdValue_methods(root_module, cls):
## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue() [constructor]
cls.add_constructor([])
## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue(ns3::TypeIdValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TypeIdValue const &', 'arg0')])
## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue(ns3::TypeId const & value) [constructor]
cls.add_constructor([param('ns3::TypeId const &', 'value')])
## type-id.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::TypeIdValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## type-id.h (module 'core'): bool ns3::TypeIdValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## type-id.h (module 'core'): ns3::TypeId ns3::TypeIdValue::Get() const [member function]
cls.add_method('Get',
'ns3::TypeId',
[],
is_const=True)
## type-id.h (module 'core'): std::string ns3::TypeIdValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## type-id.h (module 'core'): void ns3::TypeIdValue::Set(ns3::TypeId const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::TypeId const &', 'value')])
return
def register_Ns3UintegerValue_methods(root_module, cls):
## uinteger.h (module 'core'): ns3::UintegerValue::UintegerValue() [constructor]
cls.add_constructor([])
## uinteger.h (module 'core'): ns3::UintegerValue::UintegerValue(ns3::UintegerValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UintegerValue const &', 'arg0')])
## uinteger.h (module 'core'): ns3::UintegerValue::UintegerValue(uint64_t const & value) [constructor]
cls.add_constructor([param('uint64_t const &', 'value')])
## uinteger.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::UintegerValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## uinteger.h (module 'core'): bool ns3::UintegerValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## uinteger.h (module 'core'): uint64_t ns3::UintegerValue::Get() const [member function]
cls.add_method('Get',
'uint64_t',
[],
is_const=True)
## uinteger.h (module 'core'): std::string ns3::UintegerValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## uinteger.h (module 'core'): void ns3::UintegerValue::Set(uint64_t const & value) [member function]
cls.add_method('Set',
'void',
[param('uint64_t const &', 'value')])
return
def register_Ns3Vector2DChecker_methods(root_module, cls):
## vector.h (module 'core'): ns3::Vector2DChecker::Vector2DChecker() [constructor]
cls.add_constructor([])
## vector.h (module 'core'): ns3::Vector2DChecker::Vector2DChecker(ns3::Vector2DChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Vector2DChecker const &', 'arg0')])
return
def register_Ns3Vector2DValue_methods(root_module, cls):
## vector.h (module 'core'): ns3::Vector2DValue::Vector2DValue() [constructor]
cls.add_constructor([])
## vector.h (module 'core'): ns3::Vector2DValue::Vector2DValue(ns3::Vector2DValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Vector2DValue const &', 'arg0')])
## vector.h (module 'core'): ns3::Vector2DValue::Vector2DValue(ns3::Vector2D const & value) [constructor]
cls.add_constructor([param('ns3::Vector2D const &', 'value')])
## vector.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::Vector2DValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## vector.h (module 'core'): bool ns3::Vector2DValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## vector.h (module 'core'): ns3::Vector2D ns3::Vector2DValue::Get() const [member function]
cls.add_method('Get',
'ns3::Vector2D',
[],
is_const=True)
## vector.h (module 'core'): std::string ns3::Vector2DValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## vector.h (module 'core'): void ns3::Vector2DValue::Set(ns3::Vector2D const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Vector2D const &', 'value')])
return
def register_Ns3Vector3DChecker_methods(root_module, cls):
## vector.h (module 'core'): ns3::Vector3DChecker::Vector3DChecker() [constructor]
cls.add_constructor([])
## vector.h (module 'core'): ns3::Vector3DChecker::Vector3DChecker(ns3::Vector3DChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Vector3DChecker const &', 'arg0')])
return
def register_Ns3Vector3DValue_methods(root_module, cls):
## vector.h (module 'core'): ns3::Vector3DValue::Vector3DValue() [constructor]
cls.add_constructor([])
## vector.h (module 'core'): ns3::Vector3DValue::Vector3DValue(ns3::Vector3DValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Vector3DValue const &', 'arg0')])
## vector.h (module 'core'): ns3::Vector3DValue::Vector3DValue(ns3::Vector3D const & value) [constructor]
cls.add_constructor([param('ns3::Vector3D const &', 'value')])
## vector.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::Vector3DValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## vector.h (module 'core'): bool ns3::Vector3DValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## vector.h (module 'core'): ns3::Vector3D ns3::Vector3DValue::Get() const [member function]
cls.add_method('Get',
'ns3::Vector3D',
[],
is_const=True)
## vector.h (module 'core'): std::string ns3::Vector3DValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## vector.h (module 'core'): void ns3::Vector3DValue::Set(ns3::Vector3D const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Vector3D const &', 'value')])
return
def register_Ns3ConfigMatchContainer_methods(root_module, cls):
## config.h (module 'core'): ns3::Config::MatchContainer::MatchContainer(ns3::Config::MatchContainer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Config::MatchContainer const &', 'arg0')])
## config.h (module 'core'): ns3::Config::MatchContainer::MatchContainer() [constructor]
cls.add_constructor([])
## config.h (module 'core'): ns3::Config::MatchContainer::MatchContainer(std::vector<ns3::Ptr<ns3::Object>, std::allocator<ns3::Ptr<ns3::Object> > > const & objects, std::vector<std::string, std::allocator<std::string> > const & contexts, std::string path) [constructor]
cls.add_constructor([param('std::vector< ns3::Ptr< ns3::Object > > const &', 'objects'), param('std::vector< std::string > const &', 'contexts'), param('std::string', 'path')])
## config.h (module 'core'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Object>*,std::vector<ns3::Ptr<ns3::Object>, std::allocator<ns3::Ptr<ns3::Object> > > > ns3::Config::MatchContainer::Begin() const [member function]
cls.add_method('Begin',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Object > const, std::vector< ns3::Ptr< ns3::Object > > >',
[],
is_const=True)
## config.h (module 'core'): void ns3::Config::MatchContainer::Connect(std::string name, ns3::CallbackBase const & cb) [member function]
cls.add_method('Connect',
'void',
[param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')])
## config.h (module 'core'): void ns3::Config::MatchContainer::ConnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function]
cls.add_method('ConnectWithoutContext',
'void',
[param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')])
## config.h (module 'core'): void ns3::Config::MatchContainer::Disconnect(std::string name, ns3::CallbackBase const & cb) [member function]
cls.add_method('Disconnect',
'void',
[param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')])
## config.h (module 'core'): void ns3::Config::MatchContainer::DisconnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function]
cls.add_method('DisconnectWithoutContext',
'void',
[param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')])
## config.h (module 'core'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Object>*,std::vector<ns3::Ptr<ns3::Object>, std::allocator<ns3::Ptr<ns3::Object> > > > ns3::Config::MatchContainer::End() const [member function]
cls.add_method('End',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Object > const, std::vector< ns3::Ptr< ns3::Object > > >',
[],
is_const=True)
## config.h (module 'core'): ns3::Ptr<ns3::Object> ns3::Config::MatchContainer::Get(uint32_t i) const [member function]
cls.add_method('Get',
'ns3::Ptr< ns3::Object >',
[param('uint32_t', 'i')],
is_const=True)
## config.h (module 'core'): std::string ns3::Config::MatchContainer::GetMatchedPath(uint32_t i) const [member function]
cls.add_method('GetMatchedPath',
'std::string',
[param('uint32_t', 'i')],
is_const=True)
## config.h (module 'core'): uint32_t ns3::Config::MatchContainer::GetN() const [member function]
cls.add_method('GetN',
'uint32_t',
[],
is_const=True)
## config.h (module 'core'): std::string ns3::Config::MatchContainer::GetPath() const [member function]
cls.add_method('GetPath',
'std::string',
[],
is_const=True)
## config.h (module 'core'): void ns3::Config::MatchContainer::Set(std::string name, ns3::AttributeValue const & value) [member function]
cls.add_method('Set',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
return
def register_Ns3HashImplementation_methods(root_module, cls):
## hash-function.h (module 'core'): ns3::Hash::Implementation::Implementation(ns3::Hash::Implementation const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Hash::Implementation const &', 'arg0')])
## hash-function.h (module 'core'): ns3::Hash::Implementation::Implementation() [constructor]
cls.add_constructor([])
## hash-function.h (module 'core'): uint32_t ns3::Hash::Implementation::GetHash32(char const * buffer, size_t const size) [member function]
cls.add_method('GetHash32',
'uint32_t',
[param('char const *', 'buffer'), param('size_t const', 'size')],
is_pure_virtual=True, is_virtual=True)
## hash-function.h (module 'core'): uint64_t ns3::Hash::Implementation::GetHash64(char const * buffer, size_t const size) [member function]
cls.add_method('GetHash64',
'uint64_t',
[param('char const *', 'buffer'), param('size_t const', 'size')],
is_virtual=True)
## hash-function.h (module 'core'): void ns3::Hash::Implementation::clear() [member function]
cls.add_method('clear',
'void',
[],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3HashFunctionFnv1a_methods(root_module, cls):
## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a::Fnv1a(ns3::Hash::Function::Fnv1a const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Hash::Function::Fnv1a const &', 'arg0')])
## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a::Fnv1a() [constructor]
cls.add_constructor([])
## hash-fnv.h (module 'core'): uint32_t ns3::Hash::Function::Fnv1a::GetHash32(char const * buffer, size_t const size) [member function]
cls.add_method('GetHash32',
'uint32_t',
[param('char const *', 'buffer'), param('size_t const', 'size')],
is_virtual=True)
## hash-fnv.h (module 'core'): uint64_t ns3::Hash::Function::Fnv1a::GetHash64(char const * buffer, size_t const size) [member function]
cls.add_method('GetHash64',
'uint64_t',
[param('char const *', 'buffer'), param('size_t const', 'size')],
is_virtual=True)
## hash-fnv.h (module 'core'): void ns3::Hash::Function::Fnv1a::clear() [member function]
cls.add_method('clear',
'void',
[],
is_virtual=True)
return
def register_Ns3HashFunctionHash32_methods(root_module, cls):
## hash-function.h (module 'core'): ns3::Hash::Function::Hash32::Hash32(ns3::Hash::Function::Hash32 const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Hash::Function::Hash32 const &', 'arg0')])
## hash-function.h (module 'core'): ns3::Hash::Function::Hash32::Hash32(ns3::Hash::Hash32Function_ptr hp) [constructor]
cls.add_constructor([param('ns3::Hash::Hash32Function_ptr', 'hp')])
## hash-function.h (module 'core'): uint32_t ns3::Hash::Function::Hash32::GetHash32(char const * buffer, size_t const size) [member function]
cls.add_method('GetHash32',
'uint32_t',
[param('char const *', 'buffer'), param('size_t const', 'size')],
is_virtual=True)
## hash-function.h (module 'core'): void ns3::Hash::Function::Hash32::clear() [member function]
cls.add_method('clear',
'void',
[],
is_virtual=True)
return
def register_Ns3HashFunctionHash64_methods(root_module, cls):
## hash-function.h (module 'core'): ns3::Hash::Function::Hash64::Hash64(ns3::Hash::Function::Hash64 const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Hash::Function::Hash64 const &', 'arg0')])
## hash-function.h (module 'core'): ns3::Hash::Function::Hash64::Hash64(ns3::Hash::Hash64Function_ptr hp) [constructor]
cls.add_constructor([param('ns3::Hash::Hash64Function_ptr', 'hp')])
## hash-function.h (module 'core'): uint32_t ns3::Hash::Function::Hash64::GetHash32(char const * buffer, size_t const size) [member function]
cls.add_method('GetHash32',
'uint32_t',
[param('char const *', 'buffer'), param('size_t const', 'size')],
is_virtual=True)
## hash-function.h (module 'core'): uint64_t ns3::Hash::Function::Hash64::GetHash64(char const * buffer, size_t const size) [member function]
cls.add_method('GetHash64',
'uint64_t',
[param('char const *', 'buffer'), param('size_t const', 'size')],
is_virtual=True)
## hash-function.h (module 'core'): void ns3::Hash::Function::Hash64::clear() [member function]
cls.add_method('clear',
'void',
[],
is_virtual=True)
return
def register_Ns3HashFunctionMurmur3_methods(root_module, cls):
## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3::Murmur3(ns3::Hash::Function::Murmur3 const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Hash::Function::Murmur3 const &', 'arg0')])
## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3::Murmur3() [constructor]
cls.add_constructor([])
## hash-murmur3.h (module 'core'): uint32_t ns3::Hash::Function::Murmur3::GetHash32(char const * buffer, size_t const size) [member function]
cls.add_method('GetHash32',
'uint32_t',
[param('char const *', 'buffer'), param('size_t const', 'size')],
is_virtual=True)
## hash-murmur3.h (module 'core'): uint64_t ns3::Hash::Function::Murmur3::GetHash64(char const * buffer, size_t const size) [member function]
cls.add_method('GetHash64',
'uint64_t',
[param('char const *', 'buffer'), param('size_t const', 'size')],
is_virtual=True)
## hash-murmur3.h (module 'core'): void ns3::Hash::Function::Murmur3::clear() [member function]
cls.add_method('clear',
'void',
[],
is_virtual=True)
return
def register_functions(root_module):
module = root_module
## nstime.h (module 'core'): ns3::Time ns3::Abs(ns3::Time const & time) [free function]
module.add_function('Abs',
'ns3::Time',
[param('ns3::Time const &', 'time')])
## int64x64.h (module 'core'): ns3::int64x64_t ns3::Abs(ns3::int64x64_t const & value) [free function]
module.add_function('Abs',
'ns3::int64x64_t',
[param('ns3::int64x64_t const &', 'value')])
## breakpoint.h (module 'core'): extern void ns3::BreakpointFallback() [free function]
module.add_function('BreakpointFallback',
'void',
[])
## vector.h (module 'core'): extern double ns3::CalculateDistance(ns3::Vector2D const & a, ns3::Vector2D const & b) [free function]
module.add_function('CalculateDistance',
'double',
[param('ns3::Vector2D const &', 'a'), param('ns3::Vector2D const &', 'b')])
## vector.h (module 'core'): extern double ns3::CalculateDistance(ns3::Vector3D const & a, ns3::Vector3D const & b) [free function]
module.add_function('CalculateDistance',
'double',
[param('ns3::Vector3D const &', 'a'), param('ns3::Vector3D const &', 'b')])
## ptr.h (module 'core'): extern ns3::Ptr<ns3::ObjectPtrContainerValue> ns3::Create() [free function]
module.add_function('Create',
'ns3::Ptr< ns3::ObjectPtrContainerValue >',
[],
template_parameters=['ns3::ObjectPtrContainerValue'])
## ptr.h (module 'core'): extern ns3::Ptr<ns3::PointerValue> ns3::Create() [free function]
module.add_function('Create',
'ns3::Ptr< ns3::PointerValue >',
[],
template_parameters=['ns3::PointerValue'])
## nstime.h (module 'core'): ns3::Time ns3::Days(ns3::int64x64_t value) [free function]
module.add_function('Days',
'ns3::Time',
[param('ns3::int64x64_t', 'value')])
## nstime.h (module 'core'): ns3::Time ns3::Days(double value) [free function]
module.add_function('Days',
'ns3::Time',
[param('double', 'value')])
## nstime.h (module 'core'): ns3::Time ns3::FemtoSeconds(ns3::int64x64_t value) [free function]
module.add_function('FemtoSeconds',
'ns3::Time',
[param('ns3::int64x64_t', 'value')])
## nstime.h (module 'core'): ns3::Time ns3::FemtoSeconds(uint64_t value) [free function]
module.add_function('FemtoSeconds',
'ns3::Time',
[param('uint64_t', 'value')])
## hash.h (module 'core'): uint32_t ns3::Hash32(std::string const s) [free function]
module.add_function('Hash32',
'uint32_t',
[param('std::string const', 's')])
## hash.h (module 'core'): uint32_t ns3::Hash32(char const * buffer, size_t const size) [free function]
module.add_function('Hash32',
'uint32_t',
[param('char const *', 'buffer'), param('size_t const', 'size')])
## hash.h (module 'core'): uint64_t ns3::Hash64(std::string const s) [free function]
module.add_function('Hash64',
'uint64_t',
[param('std::string const', 's')])
## hash.h (module 'core'): uint64_t ns3::Hash64(char const * buffer, size_t const size) [free function]
module.add_function('Hash64',
'uint64_t',
[param('char const *', 'buffer'), param('size_t const', 'size')])
## nstime.h (module 'core'): ns3::Time ns3::Hours(ns3::int64x64_t value) [free function]
module.add_function('Hours',
'ns3::Time',
[param('ns3::int64x64_t', 'value')])
## nstime.h (module 'core'): ns3::Time ns3::Hours(double value) [free function]
module.add_function('Hours',
'ns3::Time',
[param('double', 'value')])
## log.h (module 'core'): extern void ns3::LogComponentDisable(char const * name, ns3::LogLevel level) [free function]
module.add_function('LogComponentDisable',
'void',
[param('char const *', 'name'), param('ns3::LogLevel', 'level')])
## log.h (module 'core'): extern void ns3::LogComponentDisableAll(ns3::LogLevel level) [free function]
module.add_function('LogComponentDisableAll',
'void',
[param('ns3::LogLevel', 'level')])
## log.h (module 'core'): extern void ns3::LogComponentEnable(char const * name, ns3::LogLevel level) [free function]
module.add_function('LogComponentEnable',
'void',
[param('char const *', 'name'), param('ns3::LogLevel', 'level')])
## log.h (module 'core'): extern void ns3::LogComponentEnableAll(ns3::LogLevel level) [free function]
module.add_function('LogComponentEnableAll',
'void',
[param('ns3::LogLevel', 'level')])
## log.h (module 'core'): extern void ns3::LogComponentPrintList() [free function]
module.add_function('LogComponentPrintList',
'void',
[])
## log.h (module 'core'): extern ns3::LogNodePrinter ns3::LogGetNodePrinter() [free function]
module.add_function('LogGetNodePrinter',
'ns3::LogNodePrinter',
[])
## log.h (module 'core'): extern ns3::LogTimePrinter ns3::LogGetTimePrinter() [free function]
module.add_function('LogGetTimePrinter',
'ns3::LogTimePrinter',
[])
## log.h (module 'core'): extern void ns3::LogSetNodePrinter(ns3::LogNodePrinter np) [free function]
module.add_function('LogSetNodePrinter',
'void',
[param('ns3::LogNodePrinter', 'np')])
## log.h (module 'core'): extern void ns3::LogSetTimePrinter(ns3::LogTimePrinter lp) [free function]
module.add_function('LogSetTimePrinter',
'void',
[param('ns3::LogTimePrinter', 'lp')])
## boolean.h (module 'core'): extern ns3::Ptr<ns3::AttributeChecker const> ns3::MakeBooleanChecker() [free function]
module.add_function('MakeBooleanChecker',
'ns3::Ptr< ns3::AttributeChecker const >',
[])
## callback.h (module 'core'): extern ns3::Ptr<ns3::AttributeChecker const> ns3::MakeCallbackChecker() [free function]
module.add_function('MakeCallbackChecker',
'ns3::Ptr< ns3::AttributeChecker const >',
[])
## enum.h (module 'core'): extern ns3::Ptr<ns3::AttributeChecker const> ns3::MakeEnumChecker(int v1, std::string n1, int v2=0, std::string n2="", int v3=0, std::string n3="", int v4=0, std::string n4="", int v5=0, std::string n5="", int v6=0, std::string n6="", int v7=0, std::string n7="", int v8=0, std::string n8="", int v9=0, std::string n9="", int v10=0, std::string n10="", int v11=0, std::string n11="", int v12=0, std::string n12="", int v13=0, std::string n13="", int v14=0, std::string n14="", int v15=0, std::string n15="", int v16=0, std::string n16="", int v17=0, std::string n17="", int v18=0, std::string n18="", int v19=0, std::string n19="", int v20=0, std::string n20="", int v21=0, std::string n21="", int v22=0, std::string n22="") [free function]
module.add_function('MakeEnumChecker',
'ns3::Ptr< ns3::AttributeChecker const >',
[param('int', 'v1'), param('std::string', 'n1'), param('int', 'v2', default_value='0'), param('std::string', 'n2', default_value='""'), param('int', 'v3', default_value='0'), param('std::string', 'n3', default_value='""'), param('int', 'v4', default_value='0'), param('std::string', 'n4', default_value='""'), param('int', 'v5', default_value='0'), param('std::string', 'n5', default_value='""'), param('int', 'v6', default_value='0'), param('std::string', 'n6', default_value='""'), param('int', 'v7', default_value='0'), param('std::string', 'n7', default_value='""'), param('int', 'v8', default_value='0'), param('std::string', 'n8', default_value='""'), param('int', 'v9', default_value='0'), param('std::string', 'n9', default_value='""'), param('int', 'v10', default_value='0'), param('std::string', 'n10', default_value='""'), param('int', 'v11', default_value='0'), param('std::string', 'n11', default_value='""'), param('int', 'v12', default_value='0'), param('std::string', 'n12', default_value='""'), param('int', 'v13', default_value='0'), param('std::string', 'n13', default_value='""'), param('int', 'v14', default_value='0'), param('std::string', 'n14', default_value='""'), param('int', 'v15', default_value='0'), param('std::string', 'n15', default_value='""'), param('int', 'v16', default_value='0'), param('std::string', 'n16', default_value='""'), param('int', 'v17', default_value='0'), param('std::string', 'n17', default_value='""'), param('int', 'v18', default_value='0'), param('std::string', 'n18', default_value='""'), param('int', 'v19', default_value='0'), param('std::string', 'n19', default_value='""'), param('int', 'v20', default_value='0'), param('std::string', 'n20', default_value='""'), param('int', 'v21', default_value='0'), param('std::string', 'n21', default_value='""'), param('int', 'v22', default_value='0'), param('std::string', 'n22', default_value='""')])
## make-event.h (module 'core'): extern ns3::EventImpl * ns3::MakeEvent(void (*)( ) * f) [free function]
module.add_function('MakeEvent',
'ns3::EventImpl *',
[param('void ( * ) ( ) *', 'f')])
## object-factory.h (module 'core'): extern ns3::Ptr<ns3::AttributeChecker const> ns3::MakeObjectFactoryChecker() [free function]
module.add_function('MakeObjectFactoryChecker',
'ns3::Ptr< ns3::AttributeChecker const >',
[])
## string.h (module 'core'): extern ns3::Ptr<ns3::AttributeChecker const> ns3::MakeStringChecker() [free function]
module.add_function('MakeStringChecker',
'ns3::Ptr< ns3::AttributeChecker const >',
[])
## nstime.h (module 'core'): ns3::Ptr<ns3::AttributeChecker const> ns3::MakeTimeChecker() [free function]
module.add_function('MakeTimeChecker',
'ns3::Ptr< ns3::AttributeChecker const >',
[])
## nstime.h (module 'core'): ns3::Ptr<ns3::AttributeChecker const> ns3::MakeTimeChecker(ns3::Time const min) [free function]
module.add_function('MakeTimeChecker',
'ns3::Ptr< ns3::AttributeChecker const >',
[param('ns3::Time const', 'min')])
## nstime.h (module 'core'): extern ns3::Ptr<ns3::AttributeChecker const> ns3::MakeTimeChecker(ns3::Time const min, ns3::Time const max) [free function]
module.add_function('MakeTimeChecker',
'ns3::Ptr< ns3::AttributeChecker const >',
[param('ns3::Time const', 'min'), param('ns3::Time const', 'max')])
## type-id.h (module 'core'): extern ns3::Ptr<ns3::AttributeChecker const> ns3::MakeTypeIdChecker() [free function]
module.add_function('MakeTypeIdChecker',
'ns3::Ptr< ns3::AttributeChecker const >',
[])
## vector.h (module 'core'): extern ns3::Ptr<ns3::AttributeChecker const> ns3::MakeVector2DChecker() [free function]
module.add_function('MakeVector2DChecker',
'ns3::Ptr< ns3::AttributeChecker const >',
[])
## vector.h (module 'core'): extern ns3::Ptr<ns3::AttributeChecker const> ns3::MakeVector3DChecker() [free function]
module.add_function('MakeVector3DChecker',
'ns3::Ptr< ns3::AttributeChecker const >',
[])
## vector.h (module 'core'): extern ns3::Ptr<ns3::AttributeChecker const> ns3::MakeVectorChecker() [free function]
module.add_function('MakeVectorChecker',
'ns3::Ptr< ns3::AttributeChecker const >',
[])
## nstime.h (module 'core'): ns3::Time ns3::Max(ns3::Time const & ta, ns3::Time const & tb) [free function]
module.add_function('Max',
'ns3::Time',
[param('ns3::Time const &', 'ta'), param('ns3::Time const &', 'tb')])
## int64x64.h (module 'core'): ns3::int64x64_t ns3::Max(ns3::int64x64_t const & a, ns3::int64x64_t const & b) [free function]
module.add_function('Max',
'ns3::int64x64_t',
[param('ns3::int64x64_t const &', 'a'), param('ns3::int64x64_t const &', 'b')])
## nstime.h (module 'core'): ns3::Time ns3::MicroSeconds(ns3::int64x64_t value) [free function]
module.add_function('MicroSeconds',
'ns3::Time',
[param('ns3::int64x64_t', 'value')])
## nstime.h (module 'core'): ns3::Time ns3::MicroSeconds(uint64_t value) [free function]
module.add_function('MicroSeconds',
'ns3::Time',
[param('uint64_t', 'value')])
## nstime.h (module 'core'): ns3::Time ns3::MilliSeconds(ns3::int64x64_t value) [free function]
module.add_function('MilliSeconds',
'ns3::Time',
[param('ns3::int64x64_t', 'value')])
## nstime.h (module 'core'): ns3::Time ns3::MilliSeconds(uint64_t value) [free function]
module.add_function('MilliSeconds',
'ns3::Time',
[param('uint64_t', 'value')])
## nstime.h (module 'core'): ns3::Time ns3::Min(ns3::Time const & ta, ns3::Time const & tb) [free function]
module.add_function('Min',
'ns3::Time',
[param('ns3::Time const &', 'ta'), param('ns3::Time const &', 'tb')])
## int64x64.h (module 'core'): ns3::int64x64_t ns3::Min(ns3::int64x64_t const & a, ns3::int64x64_t const & b) [free function]
module.add_function('Min',
'ns3::int64x64_t',
[param('ns3::int64x64_t const &', 'a'), param('ns3::int64x64_t const &', 'b')])
## nstime.h (module 'core'): ns3::Time ns3::Minutes(ns3::int64x64_t value) [free function]
module.add_function('Minutes',
'ns3::Time',
[param('ns3::int64x64_t', 'value')])
## nstime.h (module 'core'): ns3::Time ns3::Minutes(double value) [free function]
module.add_function('Minutes',
'ns3::Time',
[param('double', 'value')])
## nstime.h (module 'core'): ns3::Time ns3::NanoSeconds(ns3::int64x64_t value) [free function]
module.add_function('NanoSeconds',
'ns3::Time',
[param('ns3::int64x64_t', 'value')])
## nstime.h (module 'core'): ns3::Time ns3::NanoSeconds(uint64_t value) [free function]
module.add_function('NanoSeconds',
'ns3::Time',
[param('uint64_t', 'value')])
## simulator.h (module 'core'): extern ns3::Time ns3::Now() [free function]
module.add_function('Now',
'ns3::Time',
[])
## nstime.h (module 'core'): ns3::Time ns3::PicoSeconds(ns3::int64x64_t value) [free function]
module.add_function('PicoSeconds',
'ns3::Time',
[param('ns3::int64x64_t', 'value')])
## nstime.h (module 'core'): ns3::Time ns3::PicoSeconds(uint64_t value) [free function]
module.add_function('PicoSeconds',
'ns3::Time',
[param('uint64_t', 'value')])
## nstime.h (module 'core'): ns3::Time ns3::Seconds(ns3::int64x64_t value) [free function]
module.add_function('Seconds',
'ns3::Time',
[param('ns3::int64x64_t', 'value')])
## nstime.h (module 'core'): ns3::Time ns3::Seconds(double value) [free function]
module.add_function('Seconds',
'ns3::Time',
[param('double', 'value')])
## test.h (module 'core'): extern bool ns3::TestDoubleIsEqual(double const a, double const b, double const epsilon=std::numeric_limits<double>::epsilon()) [free function]
module.add_function('TestDoubleIsEqual',
'bool',
[param('double const', 'a'), param('double const', 'b'), param('double const', 'epsilon', default_value='std::numeric_limits<double>::epsilon()')])
## nstime.h (module 'core'): ns3::Time ns3::TimeStep(uint64_t ts) [free function]
module.add_function('TimeStep',
'ns3::Time',
[param('uint64_t', 'ts')])
## type-name.h (module 'core'): extern std::string ns3::TypeNameGet() [free function]
module.add_function('TypeNameGet',
'std::string',
[],
template_parameters=['double'])
## type-name.h (module 'core'): extern std::string ns3::TypeNameGet() [free function]
module.add_function('TypeNameGet',
'std::string',
[],
template_parameters=['float'])
## type-name.h (module 'core'): extern std::string ns3::TypeNameGet() [free function]
module.add_function('TypeNameGet',
'std::string',
[],
template_parameters=['unsigned long'])
## type-name.h (module 'core'): extern std::string ns3::TypeNameGet() [free function]
module.add_function('TypeNameGet',
'std::string',
[],
template_parameters=['unsigned int'])
## type-name.h (module 'core'): extern std::string ns3::TypeNameGet() [free function]
module.add_function('TypeNameGet',
'std::string',
[],
template_parameters=['unsigned short'])
## type-name.h (module 'core'): extern std::string ns3::TypeNameGet() [free function]
module.add_function('TypeNameGet',
'std::string',
[],
template_parameters=['unsigned char'])
## type-name.h (module 'core'): extern std::string ns3::TypeNameGet() [free function]
module.add_function('TypeNameGet',
'std::string',
[],
template_parameters=['long'])
## type-name.h (module 'core'): extern std::string ns3::TypeNameGet() [free function]
module.add_function('TypeNameGet',
'std::string',
[],
template_parameters=['int'])
## type-name.h (module 'core'): extern std::string ns3::TypeNameGet() [free function]
module.add_function('TypeNameGet',
'std::string',
[],
template_parameters=['short'])
## type-name.h (module 'core'): extern std::string ns3::TypeNameGet() [free function]
module.add_function('TypeNameGet',
'std::string',
[],
template_parameters=['signed char'])
## nstime.h (module 'core'): ns3::Time ns3::Years(ns3::int64x64_t value) [free function]
module.add_function('Years',
'ns3::Time',
[param('ns3::int64x64_t', 'value')])
## nstime.h (module 'core'): ns3::Time ns3::Years(double value) [free function]
module.add_function('Years',
'ns3::Time',
[param('double', 'value')])
register_functions_ns3_CommandLineHelper(module.get_submodule('CommandLineHelper'), root_module)
register_functions_ns3_Config(module.get_submodule('Config'), root_module)
register_functions_ns3_FatalImpl(module.get_submodule('FatalImpl'), root_module)
register_functions_ns3_Hash(module.get_submodule('Hash'), root_module)
register_functions_ns3_SystemPath(module.get_submodule('SystemPath'), root_module)
register_functions_ns3_TracedValueCallback(module.get_submodule('TracedValueCallback'), root_module)
register_functions_ns3_internal(module.get_submodule('internal'), root_module)
return
def register_functions_ns3_CommandLineHelper(module, root_module):
## command-line.h (module 'core'): extern std::string ns3::CommandLineHelper::GetDefault(bool const & val) [free function]
module.add_function('GetDefault',
'std::string',
[param('bool const &', 'val')],
template_parameters=['bool'])
## command-line.h (module 'core'): extern bool ns3::CommandLineHelper::UserItemParse(std::string const value, bool & val) [free function]
module.add_function('UserItemParse',
'bool',
[param('std::string const', 'value'), param('bool &', 'val')],
template_parameters=['bool'])
return
def register_functions_ns3_Config(module, root_module):
## config.h (module 'core'): extern void ns3::Config::Connect(std::string path, ns3::CallbackBase const & cb) [free function]
module.add_function('Connect',
'void',
[param('std::string', 'path'), param('ns3::CallbackBase const &', 'cb')])
## config.h (module 'core'): extern void ns3::Config::ConnectWithoutContext(std::string path, ns3::CallbackBase const & cb) [free function]
module.add_function('ConnectWithoutContext',
'void',
[param('std::string', 'path'), param('ns3::CallbackBase const &', 'cb')])
## config.h (module 'core'): extern void ns3::Config::Disconnect(std::string path, ns3::CallbackBase const & cb) [free function]
module.add_function('Disconnect',
'void',
[param('std::string', 'path'), param('ns3::CallbackBase const &', 'cb')])
## config.h (module 'core'): extern void ns3::Config::DisconnectWithoutContext(std::string path, ns3::CallbackBase const & cb) [free function]
module.add_function('DisconnectWithoutContext',
'void',
[param('std::string', 'path'), param('ns3::CallbackBase const &', 'cb')])
## config.h (module 'core'): extern ns3::Ptr<ns3::Object> ns3::Config::GetRootNamespaceObject(uint32_t i) [free function]
module.add_function('GetRootNamespaceObject',
'ns3::Ptr< ns3::Object >',
[param('uint32_t', 'i')])
## config.h (module 'core'): extern uint32_t ns3::Config::GetRootNamespaceObjectN() [free function]
module.add_function('GetRootNamespaceObjectN',
'uint32_t',
[])
## config.h (module 'core'): extern ns3::Config::MatchContainer ns3::Config::LookupMatches(std::string path) [free function]
module.add_function('LookupMatches',
'ns3::Config::MatchContainer',
[param('std::string', 'path')])
## config.h (module 'core'): extern void ns3::Config::RegisterRootNamespaceObject(ns3::Ptr<ns3::Object> obj) [free function]
module.add_function('RegisterRootNamespaceObject',
'void',
[param('ns3::Ptr< ns3::Object >', 'obj')])
## config.h (module 'core'): extern void ns3::Config::Reset() [free function]
module.add_function('Reset',
'void',
[])
## config.h (module 'core'): extern void ns3::Config::Set(std::string path, ns3::AttributeValue const & value) [free function]
module.add_function('Set',
'void',
[param('std::string', 'path'), param('ns3::AttributeValue const &', 'value')])
## config.h (module 'core'): extern void ns3::Config::SetDefault(std::string name, ns3::AttributeValue const & value) [free function]
module.add_function('SetDefault',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
## config.h (module 'core'): extern bool ns3::Config::SetDefaultFailSafe(std::string name, ns3::AttributeValue const & value) [free function]
module.add_function('SetDefaultFailSafe',
'bool',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
## config.h (module 'core'): extern void ns3::Config::SetGlobal(std::string name, ns3::AttributeValue const & value) [free function]
module.add_function('SetGlobal',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
## config.h (module 'core'): extern bool ns3::Config::SetGlobalFailSafe(std::string name, ns3::AttributeValue const & value) [free function]
module.add_function('SetGlobalFailSafe',
'bool',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
## config.h (module 'core'): extern void ns3::Config::UnregisterRootNamespaceObject(ns3::Ptr<ns3::Object> obj) [free function]
module.add_function('UnregisterRootNamespaceObject',
'void',
[param('ns3::Ptr< ns3::Object >', 'obj')])
return
def register_functions_ns3_FatalImpl(module, root_module):
## fatal-impl.h (module 'core'): extern void ns3::FatalImpl::FlushStreams() [free function]
module.add_function('FlushStreams',
'void',
[])
## fatal-impl.h (module 'core'): extern void ns3::FatalImpl::RegisterStream(std::ostream * stream) [free function]
module.add_function('RegisterStream',
'void',
[param('std::ostream *', 'stream')])
## fatal-impl.h (module 'core'): extern void ns3::FatalImpl::UnregisterStream(std::ostream * stream) [free function]
module.add_function('UnregisterStream',
'void',
[param('std::ostream *', 'stream')])
return
def register_functions_ns3_Hash(module, root_module):
register_functions_ns3_Hash_Function(module.get_submodule('Function'), root_module)
return
def register_functions_ns3_Hash_Function(module, root_module):
return
def register_functions_ns3_SystemPath(module, root_module):
## system-path.h (module 'core'): extern std::string ns3::SystemPath::Append(std::string left, std::string right) [free function]
module.add_function('Append',
'std::string',
[param('std::string', 'left'), param('std::string', 'right')])
## system-path.h (module 'core'): extern std::string ns3::SystemPath::FindSelfDirectory() [free function]
module.add_function('FindSelfDirectory',
'std::string',
[])
## system-path.h (module 'core'): extern std::string ns3::SystemPath::Join(std::_List_const_iterator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > begin, std::_List_const_iterator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > end) [free function]
module.add_function('Join',
'std::string',
[param('std::_List_const_iterator< std::basic_string< char, std::char_traits< char >, std::allocator< char > > >', 'begin'), param('std::_List_const_iterator< std::basic_string< char, std::char_traits< char >, std::allocator< char > > >', 'end')])
## system-path.h (module 'core'): extern void ns3::SystemPath::MakeDirectories(std::string path) [free function]
module.add_function('MakeDirectories',
'void',
[param('std::string', 'path')])
## system-path.h (module 'core'): extern std::string ns3::SystemPath::MakeTemporaryDirectoryName() [free function]
module.add_function('MakeTemporaryDirectoryName',
'std::string',
[])
## system-path.h (module 'core'): extern std::list<std::string, std::allocator<std::string> > ns3::SystemPath::ReadFiles(std::string path) [free function]
module.add_function('ReadFiles',
'std::list< std::string >',
[param('std::string', 'path')])
## system-path.h (module 'core'): extern std::list<std::string, std::allocator<std::string> > ns3::SystemPath::Split(std::string path) [free function]
module.add_function('Split',
'std::list< std::string >',
[param('std::string', 'path')])
return
def register_functions_ns3_TracedValueCallback(module, root_module):
return
def register_functions_ns3_internal(module, root_module):
## double.h (module 'core'): extern ns3::Ptr<ns3::AttributeChecker const> ns3::internal::MakeDoubleChecker(double min, double max, std::string name) [free function]
module.add_function('MakeDoubleChecker',
'ns3::Ptr< ns3::AttributeChecker const >',
[param('double', 'min'), param('double', 'max'), param('std::string', 'name')])
## integer.h (module 'core'): extern ns3::Ptr<ns3::AttributeChecker const> ns3::internal::MakeIntegerChecker(int64_t min, int64_t max, std::string name) [free function]
module.add_function('MakeIntegerChecker',
'ns3::Ptr< ns3::AttributeChecker const >',
[param('int64_t', 'min'), param('int64_t', 'max'), param('std::string', 'name')])
## uinteger.h (module 'core'): extern ns3::Ptr<ns3::AttributeChecker const> ns3::internal::MakeUintegerChecker(uint64_t min, uint64_t max, std::string name) [free function]
module.add_function('MakeUintegerChecker',
'ns3::Ptr< ns3::AttributeChecker const >',
[param('uint64_t', 'min'), param('uint64_t', 'max'), param('std::string', 'name')])
return
def main():
out = FileCodeSink(sys.stdout)
root_module = module_init()
register_types(root_module)
register_methods(root_module)
register_functions(root_module)
root_module.generate(out)
if __name__ == '__main__':
main()
|
1tylermitchell/healthcheck-py | refs/heads/master | ping.py | 2 | #From https://raw.githubusercontent.com/duanev/ping-python/master/ping.py
#
# Ping - bounce ICMP identify packets off remote hosts
#
# The author of this code (a) does not expect anything from you, and
# (b) is not responsible for any problems you may have using this code.
#
# requires: python2 and root/administrator privs to use icmp port 22
# tested on: Arch Linux (as of feb 2014), Windows 8
#
# Linux:
#
# On Linux capabilities can be used to grant 'cap_net_raw+ep' to
# python scripts by copying the python *binary* to a separate
# directory and setting the copy's capabilities with setcap:
#
# $ cp /usr/bin/python2.7 python_net_raw
# # setcap cap_net_raw+ep python_net_raw
# $ ./python_net_raw ping.py ...
#
# Windows 8:
#
# Right click icon in lower left of screen, use Command Prompt (Admin)
__date__ = "2014/02/27"
__version__ = "v0.93"
import sys
import time
# -----------------------------------------------------------------------
# A thread based polling service with pause and kill.
# Since it polls the function passed in, the function
# needs to return as soon as possible.
import threading
ST_KILLED = 0
ST_PAUSED = 1
ST_RUNNING = 2
ST_names = { 0:"killed", 1:"paused", 2:"running" }
class Poll(threading.Thread):
def __init__(self, func, args=(), name=None, period=0.1):
# we need a tuple here
if type(args) != type((1,)):
args = (args,)
self._function = func
self._args = args
self.period = period
threading.Thread.__init__(self, target=func, name=name, args=())
self._uptime = time.time()
self._state = ST_RUNNING
self.start()
def run(self):
while self._state != ST_KILLED:
if self._state == ST_RUNNING:
self._function(self._args)
time.sleep(self.period)
# note: all threads must be killed before python will exit!
def kill(self):
self._state = ST_KILLED
def pause(self):
if self._state == ST_RUNNING:
self._state = ST_PAUSED
def resume(self):
if self._state == ST_PAUSED:
self._state = ST_RUNNING
def uptime(self):
return time.time() - self._uptime
def state(self):
return ST_names[self._state]
def __str__(self):
return self.getName()
@staticmethod
def thread_list():
return [x for x in threading.enumerate()
if x.getName() != "MainThread"]
@staticmethod
def tlist():
"""Human readable version of thread_list()"""
for t in Poll.thread_list():
if isinstance(t, Poll):
print "%-16s %-8s %4.3f" % (t, t.state(), t.uptime())
@staticmethod
def killall():
for t in Poll.thread_list():
t.kill()
# -----------------------------------------------------------------------
# ping from scratch
import os
import types
import struct
import socket
class PingService(object):
"""Send out icmp ping requests at 'delay' intervals and
watch for replies. The isup() method can be used by
other threads to check the status of the remote host.
@host - (string) ip of host to ping
@delay - (float) delay in seconds between pings
@its_dead_jim - (int) seconds to wait before running offline()
@verbose - (bool) print round trip stats for every reply
@persistent - (bool) thread continues to run even if no reply
usage: p = PingService('192.168.1.1')
p.start() - begin ping loop
p.isup() - True if host has replied recently
p.stop() - stop ping loop
online() and offline() methods can be overloaded:
def my_online(self):
self.log(self.host + " is up")
p.online = types.MethodType(my_online, p)
"""
# provide a class-wide thread-safe message queue
msgs = []
def __init__(self, host, delay=1.0, its_dead_jim=4,
verbose=True, persistent=False):
self.host = host
self.delay = delay
self.verbose = verbose
self.persistent = persistent
self.obituary_delay = its_dead_jim * delay
self.pad = "getoff my lawn" # should be 14 chars or more
socket.setdefaulttimeout(0.01)
self.started = 0
self.thread = None
self._isup = False
self.sock = socket.socket(socket.AF_INET, socket.SOCK_RAW,
socket.getprotobyname('icmp'))
try:
self.sock.connect((host, 22))
except socket.gaierror, ex:
self.log("ping socket cannot connect to %s: %s" % (host, ex[1]))
self.sock.close()
return
def log(self, msg):
if not self.verbose:
msg = time.strftime("%H:%M:%S ") + msg
self.msgs.append(msg)
def start(self):
self.seq = 0
self.pid = os.getpid()
self.last_heartbeat = 0
# send a ping right away
self.time_to_send = self.started = time.time()
self.thread = Poll(self._ping, (None), name=self.host)
#retry = int(round(self.obituary_delay / 0.2))
## retry, before letting caller deal with a down state
#while retry > 0 and not self._isup:
# time.sleep(0.2)
# retry -= 1
def stop(self):
if self.thread:
self.thread.kill()
self.thread = None
def _icmp_checksum(self, pkt):
n = len(pkt)
two_bytes = struct.unpack("!%sH" % (n/2), pkt)
chksum = sum(two_bytes)
if n & 1 == 1:
chksum += pkt[-1]
chksum = (chksum >> 16) + (chksum & 0xffff)
chksum += chksum >> 16
return ~chksum & 0xffff
def _icmp_create(self, data):
fmt = "!BBH"
args = [8, 0, 0]
if data and len(data) > 0:
fmt += "%ss" % len(data)
args.append(data)
args[2] = self._icmp_checksum(struct.pack(fmt, *args))
return struct.pack(fmt, *args)
def _icmp_parse(self, pkt):
"""Parse ICMP packet"""
string_len = len(pkt) - 4 # Ignore IP header
fmt = "!BBH"
if string_len:
fmt += "%ss" % string_len
unpacked_packet = struct.unpack(fmt, pkt)
typ, code, chksum = unpacked_packet[:3]
if self._icmp_checksum(pkt) != 0:
self.log("%s reply checksum is not zero" % self.host)
try:
data = unpacked_packet[3]
except IndexError:
data = None
return typ, code, data
def _ping(self, args):
pdatafmt = "!HHd%ds" % len(self.pad)
now = time.time()
if now >= self.time_to_send:
# send ping packet
self.seq += 1
self.seq &= 0xffff
pdata = struct.pack(pdatafmt, self.pid, self.seq, now, self.pad)
self.sock.send(self._icmp_create(pdata))
self.time_to_send = now + self.delay
if self._isup and now - self.last_heartbeat > self.obituary_delay:
self._isup = False
self.offline()
if self.last_heartbeat == 0 \
and not self.persistent \
and now - self.started > self.obituary_delay:
if self.verbose:
self.log("no response from " + self.host)
self.thread.kill()
self.thread = None
return
try:
rbuf = self.sock.recv(10000)
now = time.time() # refresh 'now' to make rtt more accurate
except socket.timeout:
return
if len(rbuf) <= 20:
self.log("%s truncated reply" % self.host)
return
# parse ICMP packet; ignore IP header
typ, code, rdata = self._icmp_parse(rbuf[20:])
if typ == 8:
self.log("%s is pinging us" % self.host)
self.last_heartbeat = now
if not self._isup:
self._isup = True
self.online()
return
if typ == 3:
self.log("%s dest unreachable (code=%d)" % (self.host, code));
return
if typ != 0:
self.log("%s packet not an echo reply (%d) " % (self.host, typ))
return
if not rdata:
self.log("%s packet contains no data" % (self.host))
return
if len(rdata) != 12 + len(self.pad):
# other ping programs can cause this
# self.log("%s not our ping (len=%d)" % (self.host, len(rdata)))
return
# parse ping data
(ident, seqno, timestamp, pad) = struct.unpack(pdatafmt, rdata)
if ident != self.pid:
# other instances of PingService can cause this
#self.log("%s not our ping (ident=%d)" % (self.host, ident))
return
if seqno != self.seq:
self.log("%s sequence out of order " % self.host +
"got(%d) expected(%d)" % (seqno, self.seq))
return
if rdata and len(rdata) >= 8:
self.last_heartbeat = now
if not self._isup:
self._isup = True
self.online()
if self.verbose:
str = "%d bytes from %s: seq=%u" % (
len(rbuf),
# inet_ntop not available on windows
'.'.join([('%d' % ord(c)) for c in list(rbuf[12:16])]),
self.seq)
# calculate rounttrip time
rtt = now - timestamp
rtt *= 1000
# note that some boxes that run python
# can't resolve milisecond time deltas ...
if rtt > 0:
str += ", rtt=%.1f ms" % rtt
self.log(str)
def online(self):
if not self.verbose:
self.log("%s is up" % self.host)
def offline(self):
if not self.verbose:
self.log("%s is down" % self.host)
def isup(self):
return self._isup
# ----------------------------------------------------------------------------
# demonstrate PingService
if __name__ == "__main__":
import traceback
import types
if len(sys.argv) < 2:
print "usage: python2 ping.py <ip>"
sys.exit(1)
ping_svc = PingService(sys.argv[1])
try:
ping_svc.start()
while len(Poll.thread_list()) > 0:
time.sleep(0.2)
# print log messages
while len(PingService.msgs) > 0:
print PingService.msgs.pop(0)
except KeyboardInterrupt:
pass
except:
t, v, tb = sys.exc_info()
traceback.print_exception(t, v, tb)
# note: all threads must be stopped before python will exit!
ping_svc.stop()
sys.exit(0)
|
HossainKhademian/YowsUP | refs/heads/master | yowsup/layers/axolotl/protocolentities/test_notification_encrypt.py | 67 | from yowsup.layers.protocol_notifications.protocolentities.test_notification import NotificationProtocolEntityTest
from yowsup.layers.axolotl.protocolentities import EncryptNotification
from yowsup.structs import ProtocolTreeNode
class TestEncryptNotification(NotificationProtocolEntityTest):
def setUp(self):
super(TestEncryptNotification, self).setUp()
self.ProtocolEntity = EncryptNotification
self.node.addChild(ProtocolTreeNode("count", {"value": "9"})) |
Eric-Zhong/odoo | refs/heads/8.0 | addons/website_sale/__openerp__.py | 299 | {
'name': 'eCommerce',
'category': 'Website',
'summary': 'Sell Your Products Online',
'website': 'https://www.odoo.com/page/e-commerce',
'version': '1.0',
'description': """
OpenERP E-Commerce
==================
""",
'author': 'OpenERP SA',
'depends': ['website', 'sale', 'payment'],
'data': [
'data/data.xml',
'views/views.xml',
'views/templates.xml',
'views/payment.xml',
'views/sale_order.xml',
'security/ir.model.access.csv',
'security/website_sale.xml',
],
'demo': [
'data/demo.xml',
],
'qweb': ['static/src/xml/*.xml'],
'installable': True,
'application': True,
}
|
mrniranjan/juno | refs/heads/master | PkiLib/pkicommonlib.py | 1 | #!/usr/bin/python
# -*- coding: utf-8 -*
from lxml import etree
def policy_attributes(Policy_definition, policy_attributes):
for idx,(name,syntax,constraint,description,defaultvalue) in enumerate(policy_attributes):
policy_attribute_name = etree.SubElement(Policy_definition, 'policyAttribute', name=name)
policy_attribute_descriptor = etree.SubElement(policy_attribute_name,'Descriptor')
policy_attribute_syntax = etree.SubElement(policy_attribute_descriptor, 'Syntax').text = syntax
if constraint != 'NULL':
policy_attribute_constraint = etree.SubElement(policy_attribute_descriptor, 'Constraint').text=constraint
policy_attribute_description = etree.SubElement(policy_attribute_descriptor, 'Description').text = description
if defaultvalue != 'NULL':
policy_attribute_defaultvalue = etree.SubElement(policy_attribute_descriptor, 'DefaultValue').text = defaultvalue
else:
policy_attribute_defaultvalue = etree.SubElement(policy_attribute_descriptor, 'DefaultValue')
def constraint_attributes(constraint_definition, constraint_attributes):
for idx,(constraintid, syntax, constraint, description, defaultvalue, value) in enumerate(constraint_attributes):
constraint_id = etree.SubElement(constraint_definition, 'constraint', id = constraintid)
constraint_id_descriptor = etree.SubElement(constraint_id, 'descriptor')
constraint_id_descriptor_syntax = etree.SubElement(constraint_id_descriptor, 'Syntax').text = syntax
if constraint != 'NULL':
constraint_id_descriptor_syntax = etree.SubElement(constraint_id_descriptor, 'Constraint').text = constraint
constraint_id_descriptor_description = etree.SubElement(constraint_id_descriptor, 'Description').text = description
if defaultvalue != 'NULL':
constraint_id_descriptor_defaultvalue = etree.SubElement(constraint_id_descriptor, 'DefaultValue').text = defaultvalue
if value != 'NULL':
constraint_value = etree.SubElement(constraint_id, 'value').text = value
else:
constraint_value = etree.SubElement(constraint_id, 'value')
def policy_parameters(Policy_definition, parameters):
for idx,(name, value) in enumerate(parameters):
policy_param_name = etree.SubElement(Policy_definition, 'params', name=name)
policy_param_value = etree.SubElement(policy_param_name, 'value').text=value
def policy_definition(Policy_Value,definition):
Policy_definition = etree.SubElement(Policy_Value, 'def', id=definition['id'], classId=definition['classid'])
Policy_description = etree.SubElement(Policy_definition, 'description').text = definition['description']
return Policy_definition
def constraint_definition(Policy_Value, definition):
constraint_definition = etree.SubElement(Policy_Value, 'constraint', id=definition['id'])
constraint_description = etree.SubElement(constraint_definition, 'description').text = definition['description']
constraint_classid = etree.SubElement(constraint_definition, 'classId').text = definition['classId']
return constraint_definition
def check_ext_key_usage(mylist, string):
s1 = 'true'
s2 = 'false'
if string in mylist:
return s1
else:
return s2
def get_policyId(root):
Policy_Value = root.findall('./PolicySets/PolicySet/value')
value = 0
for key in Policy_Value:
attributes = key.attrib
value = attributes["id"]
if value is 0:
pvalue = '1'
else:
pvalue = int(value) + 1
return str(pvalue)
|
albertrdixon/CouchPotatoServer | refs/heads/master | couchpotato/core/media/_base/searcher/base.py | 86 | from couchpotato.core.event import addEvent, fireEvent
from couchpotato.core.logger import CPLog
from couchpotato.core.plugins.base import Plugin
log = CPLog(__name__)
class SearcherBase(Plugin):
in_progress = False
def __init__(self):
super(SearcherBase, self).__init__()
addEvent('searcher.progress', self.getProgress)
addEvent('%s.searcher.progress' % self.getType(), self.getProgress)
self.initCron()
def initCron(self):
""" Set the searcher cronjob
Make sure to reset cronjob after setting has changed
"""
_type = self.getType()
def setCrons():
fireEvent('schedule.cron', '%s.searcher.all' % _type, self.searchAll,
day = self.conf('cron_day'), hour = self.conf('cron_hour'), minute = self.conf('cron_minute'))
addEvent('app.load', setCrons)
addEvent('setting.save.%s_searcher.cron_day.after' % _type, setCrons)
addEvent('setting.save.%s_searcher.cron_hour.after' % _type, setCrons)
addEvent('setting.save.%s_searcher.cron_minute.after' % _type, setCrons)
def getProgress(self, **kwargs):
""" Return progress of current searcher"""
progress = {
self.getType(): self.in_progress
}
return progress
|
Tatsh/youtube-dl | refs/heads/master | youtube_dl/extractor/cwtv.py | 16 | # coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..utils import (
ExtractorError,
int_or_none,
parse_age_limit,
parse_iso8601,
smuggle_url,
str_or_none,
)
class CWTVIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?cw(?:tv(?:pr)?|seed)\.com/(?:shows/)?(?:[^/]+/)+[^?]*\?.*\b(?:play|watch)=(?P<id>[a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12})'
_TESTS = [{
'url': 'http://cwtv.com/shows/arrow/legends-of-yesterday/?play=6b15e985-9345-4f60-baf8-56e96be57c63',
'info_dict': {
'id': '6b15e985-9345-4f60-baf8-56e96be57c63',
'ext': 'mp4',
'title': 'Legends of Yesterday',
'description': 'Oliver and Barry Allen take Kendra Saunders and Carter Hall to a remote location to keep them hidden from Vandal Savage while they figure out how to defeat him.',
'duration': 2665,
'series': 'Arrow',
'season_number': 4,
'season': '4',
'episode_number': 8,
'upload_date': '20151203',
'timestamp': 1449122100,
},
'params': {
# m3u8 download
'skip_download': True,
},
'skip': 'redirect to http://cwtv.com/shows/arrow/',
}, {
'url': 'http://www.cwseed.com/shows/whose-line-is-it-anyway/jeff-davis-4/?play=24282b12-ead2-42f2-95ad-26770c2c6088',
'info_dict': {
'id': '24282b12-ead2-42f2-95ad-26770c2c6088',
'ext': 'mp4',
'title': 'Jeff Davis 4',
'description': 'Jeff Davis is back to make you laugh.',
'duration': 1263,
'series': 'Whose Line Is It Anyway?',
'season_number': 11,
'episode_number': 20,
'upload_date': '20151006',
'timestamp': 1444107300,
'age_limit': 14,
'uploader': 'CWTV',
},
'params': {
# m3u8 download
'skip_download': True,
},
}, {
'url': 'http://cwtv.com/thecw/chroniclesofcisco/?play=8adebe35-f447-465f-ab52-e863506ff6d6',
'only_matching': True,
}, {
'url': 'http://cwtvpr.com/the-cw/video?watch=9eee3f60-ef4e-440b-b3b2-49428ac9c54e',
'only_matching': True,
}, {
'url': 'http://cwtv.com/shows/arrow/legends-of-yesterday/?watch=6b15e985-9345-4f60-baf8-56e96be57c63',
'only_matching': True,
}]
def _real_extract(self, url):
video_id = self._match_id(url)
data = self._download_json(
'http://images.cwtv.com/feed/mobileapp/video-meta/apiversion_8/guid_' + video_id,
video_id)
if data.get('result') != 'ok':
raise ExtractorError(data['msg'], expected=True)
video_data = data['video']
title = video_data['title']
mpx_url = video_data.get('mpx_url') or 'http://link.theplatform.com/s/cwtv/media/guid/2703454149/%s?formats=M3U' % video_id
season = str_or_none(video_data.get('season'))
episode = str_or_none(video_data.get('episode'))
if episode and season:
episode = episode[len(season):]
return {
'_type': 'url_transparent',
'id': video_id,
'title': title,
'url': smuggle_url(mpx_url, {'force_smil_url': True}),
'description': video_data.get('description_long'),
'duration': int_or_none(video_data.get('duration_secs')),
'series': video_data.get('series_name'),
'season_number': int_or_none(season),
'episode_number': int_or_none(episode),
'timestamp': parse_iso8601(video_data.get('start_time')),
'age_limit': parse_age_limit(video_data.get('rating')),
'ie_key': 'ThePlatform',
}
|
kamcpp/tensorflow | refs/heads/master | tensorflow/python/kernel_tests/spacetodepth_op_test.py | 21 | # 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.
# ==============================================================================
"""Functional tests for SpacetoDepth op."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
class SpaceToDepthTest(tf.test.TestCase):
def _testOne(self, inputs, block_size, outputs):
with self.test_session(use_gpu=True):
x_tf = tf.space_to_depth(tf.to_float(inputs), block_size)
self.assertAllEqual(x_tf.eval(), outputs)
def testBasic(self):
x_np = [[[[1], [2]],
[[3], [4]]]]
block_size = 2
x_out = [[[[1, 2, 3, 4]]]]
self._testOne(x_np, block_size, x_out)
# Tests for larger input dimensions. To make sure elements are
# correctly ordered spatially.
def testLargerInput2x2(self):
x_np = [[[[1], [2], [5], [6]],
[[3], [4], [7], [8]],
[[9], [10], [13], [14]],
[[11], [12], [15], [16]]]]
block_size = 2
x_out = [[[[1, 2, 3, 4],
[5, 6, 7, 8]],
[[9, 10, 11, 12],
[13, 14, 15, 16]]]]
self._testOne(x_np, block_size, x_out)
# Tests for larger input dimensions. To make sure elements are
# correctly ordered in depth. Here, larger block size.
def testLargerInput4x4(self):
x_np = [[[[1], [2], [5], [6]],
[[3], [4], [7], [8]],
[[9], [10], [13], [14]],
[[11], [12], [15], [16]]]]
block_size = 4
x_out = [[[[1, 2, 5, 6, 3, 4, 7, 8, 9, 10, 13, 14, 11, 12, 15, 16]]]]
self._testOne(x_np, block_size, x_out)
# Tests for larger input depths.
# To make sure elements are properly interleaved in depth.
def testDepthInterleaved(self):
x_np = [[[[1, 10], [2, 20]],
[[3, 30], [4, 40]]]]
block_size = 2
x_out = [[[[1, 10, 2, 20, 3, 30, 4, 40]]]]
self._testOne(x_np, block_size, x_out)
# Tests for larger input depths. Here an odd depth.
# To make sure elements are properly interleaved in depth.
def testDepthInterleavedDepth3(self):
x_np = [[[[1, 2, 3], [4, 5, 6]],
[[7, 8, 9], [10, 11, 12]]]]
block_size = 2
x_out = [[[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]]]]
self._testOne(x_np, block_size, x_out)
# Tests for larger input dimensions AND for larger input depths.
# To make sure elements are properly interleaved in depth and ordered
# spatially.
def testDepthInterleavedLarge(self):
x_np = [[[[1, 10], [2, 20], [5, 50], [6, 60]],
[[3, 30], [4, 40], [7, 70], [8, 80]],
[[9, 90], [10, 100], [13, 130], [14, 140]],
[[11, 110], [12, 120], [15, 150], [16, 160]]]]
block_size = 2
x_out = [[[[1, 10, 2, 20, 3, 30, 4, 40],
[5, 50, 6, 60, 7, 70, 8, 80]],
[[9, 90, 10, 100, 11, 110, 12, 120],
[13, 130, 14, 140, 15, 150, 16, 160]]]]
self._testOne(x_np, block_size, x_out)
def testBlockSize2Batch10(self):
block_size = 2
def batch_input_elt(i):
return [[[1 * i], [2 * i], [5 * i], [6 * i]],
[[3 * i], [4 * i], [7 * i], [8 * i]],
[[9 * i], [10 * i], [13 * i], [14 * i]],
[[11 * i], [12 * i], [15 * i], [16 * i]]]
def batch_output_elt(i):
return [[[1 * i, 2 * i, 3 * i, 4 * i],
[5 * i, 6 * i, 7 * i, 8 * i]],
[[9 * i, 10 * i, 11 * i, 12 * i],
[13 * i, 14 * i, 15 * i, 16 * i]]]
batch_size = 10
x_np = [batch_input_elt(i) for i in range(batch_size)]
x_out = [batch_output_elt(i) for i in range(batch_size)]
self._testOne(x_np, block_size, x_out)
# Tests for different width and height.
def testNonSquare(self):
x_np = [[[[1, 10], [2, 20]],
[[3, 30], [4, 40]],
[[5, 50], [6, 60]],
[[7, 70], [8, 80]],
[[9, 90], [10, 100]],
[[11, 110], [12, 120]]]]
block_size = 2
x_out = [[[[1, 10, 2, 20, 3, 30, 4, 40]],
[[5, 50, 6, 60, 7, 70, 8, 80]],
[[9, 90, 10, 100, 11, 110, 12, 120]]]]
self._testOne(x_np, block_size, x_out)
# Error handling:
def testInputWrongDimMissingDepth(self):
# The input is missing the last dimension ("depth")
x_np = [[[1, 2],
[3, 4]]]
block_size = 2
with self.assertRaises(ValueError):
out_tf = tf.space_to_depth(x_np, block_size)
out_tf.eval()
def testInputWrongDimMissingBatch(self):
# The input is missing the first dimension ("batch")
x_np = [[[1], [2]],
[[3], [4]]]
block_size = 2
with self.assertRaises(ValueError):
_ = tf.space_to_depth(x_np, block_size)
def testBlockSize0(self):
# The block size is 0.
x_np = [[[[1], [2]],
[[3], [4]]]]
block_size = 0
with self.assertRaises(ValueError):
out_tf = tf.space_to_depth(x_np, block_size)
out_tf.eval()
def testBlockSizeOne(self):
# The block size is 1. The block size needs to be > 1.
x_np = [[[[1], [2]],
[[3], [4]]]]
block_size = 1
with self.assertRaises(ValueError):
out_tf = tf.space_to_depth(x_np, block_size)
out_tf.eval()
def testBlockSizeLarger(self):
# The block size is too large for this input.
x_np = [[[[1], [2]],
[[3], [4]]]]
block_size = 10
with self.assertRaises(ValueError):
out_tf = tf.space_to_depth(x_np, block_size)
out_tf.eval()
def testBlockSizeNotDivisibleWidth(self):
# The block size divides width but not height.
x_np = [[[[1], [2], [3]],
[[3], [4], [7]]]]
block_size = 3
with self.assertRaises(ValueError):
_ = tf.space_to_depth(x_np, block_size)
def testBlockSizeNotDivisibleHeight(self):
# The block size divides height but not width.
x_np = [[[[1], [2]],
[[3], [4]],
[[5], [6]]]]
block_size = 3
with self.assertRaises(ValueError):
_ = tf.space_to_depth(x_np, block_size)
def testBlockSizeNotDivisibleBoth(self):
# The block size does not divide neither width or height.
x_np = [[[[1], [2]],
[[3], [4]]]]
block_size = 3
with self.assertRaises(ValueError):
_ = tf.space_to_depth(x_np, block_size)
def testUnknownShape(self):
t = tf.space_to_depth(tf.placeholder(tf.float32), block_size=4)
self.assertEqual(4, t.get_shape().ndims)
class SpaceToDepthGradientTest(tf.test.TestCase):
# Check the gradients.
def _checkGrad(self, x, block_size):
assert 4 == x.ndim
with self.test_session(use_gpu=True):
tf_x = tf.convert_to_tensor(x)
tf_y = tf.space_to_depth(tf_x, block_size)
epsilon = 1e-2
((x_jacob_t, x_jacob_n)) = tf.test.compute_gradient(
tf_x,
x.shape,
tf_y,
tf_y.get_shape().as_list(),
x_init_value=x,
delta=epsilon)
self.assertAllClose(x_jacob_t, x_jacob_n, rtol=1e-2, atol=epsilon)
# Tests a gradient for space_to_depth of x which is a four dimensional
# tensor of shape [b, h * block_size, w * block_size, d].
def _compare(self, b, h, w, d, block_size):
block_size_sq = block_size * block_size
x = np.random.normal(
0, 1, b * h * w * d * block_size_sq).astype(np.float32).reshape(
[b, h * block_size, w * block_size, d])
self._checkGrad(x, block_size)
# Don't use very large numbers as dimensions here as the result is tensor
# with cartesian product of the dimensions.
def testSmall(self):
block_size = 2
self._compare(1, 2, 3, 5, block_size)
def testSmall2(self):
block_size = 2
self._compare(2, 4, 3, 2, block_size)
if __name__ == "__main__":
tf.test.main()
|
TangXT/GreatCatMOOC | refs/heads/master | cms/djangoapps/contentstore/tests/tests.py | 6 | from django.test.utils import override_settings
from django.core.cache import cache
from django.core.urlresolvers import reverse
from contentstore.tests.utils import parse_json, user, registration, AjaxEnabledTestClient
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from contentstore.tests.test_course_settings import CourseTestCase
from xmodule.modulestore.tests.factories import CourseFactory
from contentstore.tests.modulestore_config import TEST_MODULESTORE
import datetime
from pytz import UTC
@override_settings(MODULESTORE=TEST_MODULESTORE)
class ContentStoreTestCase(ModuleStoreTestCase):
def _login(self, email, password):
"""
Login. View should always return 200. The success/fail is in the
returned json
"""
resp = self.client.post(
reverse('login_post'),
{'email': email, 'password': password}
)
self.assertEqual(resp.status_code, 200)
return resp
def login(self, email, password):
"""Login, check that it worked."""
resp = self._login(email, password)
data = parse_json(resp)
self.assertTrue(data['success'])
return resp
def _create_account(self, username, email, password):
"""Try to create an account. No error checking"""
resp = self.client.post('/create_account', {
'username': username,
'email': email,
'password': password,
'location': 'home',
'language': 'Franglish',
'name': 'Fred Weasley',
'terms_of_service': 'true',
'honor_code': 'true',
})
return resp
def create_account(self, username, email, password):
"""Create the account and check that it worked"""
resp = self._create_account(username, email, password)
self.assertEqual(resp.status_code, 200)
data = parse_json(resp)
self.assertEqual(data['success'], True)
# Check both that the user is created, and inactive
self.assertFalse(user(email).is_active)
return resp
def _activate_user(self, email):
"""Look up the activation key for the user, then hit the activate view.
No error checking"""
activation_key = registration(email).activation_key
# and now we try to activate
resp = self.client.get(reverse('activate', kwargs={'key': activation_key}))
return resp
def activate_user(self, email):
resp = self._activate_user(email)
self.assertEqual(resp.status_code, 200)
# Now make sure that the user is now actually activated
self.assertTrue(user(email).is_active)
class AuthTestCase(ContentStoreTestCase):
"""Check that various permissions-related things work"""
def setUp(self):
self.email = '[email protected]'
self.pw = 'xyz'
self.username = 'testuser'
self.client = AjaxEnabledTestClient()
# clear the cache so ratelimiting won't affect these tests
cache.clear()
def check_page_get(self, url, expected):
resp = self.client.get_html(url)
self.assertEqual(resp.status_code, expected)
return resp
def test_public_pages_load(self):
"""Make sure pages that don't require login load without error."""
pages = (
reverse('login'),
reverse('signup'),
)
for page in pages:
print("Checking '{0}'".format(page))
self.check_page_get(page, 200)
def test_create_account_errors(self):
# No post data -- should fail
resp = self.client.post('/create_account', {})
self.assertEqual(resp.status_code, 200)
data = parse_json(resp)
self.assertEqual(data['success'], False)
def test_create_account(self):
self.create_account(self.username, self.email, self.pw)
self.activate_user(self.email)
def test_login(self):
self.create_account(self.username, self.email, self.pw)
# Not activated yet. Login should fail.
resp = self._login(self.email, self.pw)
data = parse_json(resp)
self.assertFalse(data['success'])
self.activate_user(self.email)
# Now login should work
self.login(self.email, self.pw)
def test_login_ratelimited(self):
# try logging in 30 times, the default limit in the number of failed
# login attempts in one 5 minute period before the rate gets limited
for i in xrange(30):
resp = self._login(self.email, 'wrong_password{0}'.format(i))
self.assertEqual(resp.status_code, 200)
resp = self._login(self.email, 'wrong_password')
self.assertEqual(resp.status_code, 200)
data = parse_json(resp)
self.assertFalse(data['success'])
self.assertIn('Too many failed login attempts.', data['value'])
def test_login_link_on_activation_age(self):
self.create_account(self.username, self.email, self.pw)
# we want to test the rendering of the activation page when the user isn't logged in
self.client.logout()
resp = self._activate_user(self.email)
self.assertEqual(resp.status_code, 200)
# check the the HTML has links to the right login page. Note that this is merely a content
# check and thus could be fragile should the wording change on this page
expected = 'You can now <a href="' + reverse('login') + '">login</a>.'
self.assertIn(expected, resp.content)
def test_private_pages_auth(self):
"""Make sure pages that do require login work."""
auth_pages = (
'/course',
)
# These are pages that should just load when the user is logged in
# (no data needed)
simple_auth_pages = (
'/course',
)
# need an activated user
self.test_create_account()
# Create a new session
self.client = AjaxEnabledTestClient()
# Not logged in. Should redirect to login.
print('Not logged in')
for page in auth_pages:
print("Checking '{0}'".format(page))
self.check_page_get(page, expected=302)
# Logged in should work.
self.login(self.email, self.pw)
print('Logged in')
for page in simple_auth_pages:
print("Checking '{0}'".format(page))
self.check_page_get(page, expected=200)
def test_index_auth(self):
# not logged in. Should return a redirect.
resp = self.client.get_html('/course')
self.assertEqual(resp.status_code, 302)
# Logged in should work.
class ForumTestCase(CourseTestCase):
def setUp(self):
""" Creates the test course. """
super(ForumTestCase, self).setUp()
self.course = CourseFactory.create(org='testX', number='727', display_name='Forum Course')
def test_blackouts(self):
now = datetime.datetime.now(UTC)
times1 = [
(now - datetime.timedelta(days=14), now - datetime.timedelta(days=11)),
(now + datetime.timedelta(days=24), now + datetime.timedelta(days=30))
]
self.course.discussion_blackouts = [(t.isoformat(), t2.isoformat()) for t, t2 in times1]
self.assertTrue(self.course.forum_posts_allowed)
times2 = [
(now - datetime.timedelta(days=14), now + datetime.timedelta(days=2)),
(now + datetime.timedelta(days=24), now + datetime.timedelta(days=30))
]
self.course.discussion_blackouts = [(t.isoformat(), t2.isoformat()) for t, t2 in times2]
self.assertFalse(self.course.forum_posts_allowed)
|
Yukarumya/Yukarum-Redfoxes | refs/heads/master | testing/web-platform/tests/tools/pytest/testing/test_nose.py | 173 | import pytest
def setup_module(mod):
mod.nose = pytest.importorskip("nose")
def test_nose_setup(testdir):
p = testdir.makepyfile("""
l = []
from nose.tools import with_setup
@with_setup(lambda: l.append(1), lambda: l.append(2))
def test_hello():
assert l == [1]
def test_world():
assert l == [1,2]
test_hello.setup = lambda: l.append(1)
test_hello.teardown = lambda: l.append(2)
""")
result = testdir.runpytest(p, '-p', 'nose')
result.assert_outcomes(passed=2)
def test_setup_func_with_setup_decorator():
from _pytest.nose import call_optional
l = []
class A:
@pytest.fixture(autouse=True)
def f(self):
l.append(1)
call_optional(A(), "f")
assert not l
def test_setup_func_not_callable():
from _pytest.nose import call_optional
class A:
f = 1
call_optional(A(), "f")
def test_nose_setup_func(testdir):
p = testdir.makepyfile("""
from nose.tools import with_setup
l = []
def my_setup():
a = 1
l.append(a)
def my_teardown():
b = 2
l.append(b)
@with_setup(my_setup, my_teardown)
def test_hello():
print (l)
assert l == [1]
def test_world():
print (l)
assert l == [1,2]
""")
result = testdir.runpytest(p, '-p', 'nose')
result.assert_outcomes(passed=2)
def test_nose_setup_func_failure(testdir):
p = testdir.makepyfile("""
from nose.tools import with_setup
l = []
my_setup = lambda x: 1
my_teardown = lambda x: 2
@with_setup(my_setup, my_teardown)
def test_hello():
print (l)
assert l == [1]
def test_world():
print (l)
assert l == [1,2]
""")
result = testdir.runpytest(p, '-p', 'nose')
result.stdout.fnmatch_lines([
"*TypeError: <lambda>()*"
])
def test_nose_setup_func_failure_2(testdir):
testdir.makepyfile("""
l = []
my_setup = 1
my_teardown = 2
def test_hello():
assert l == []
test_hello.setup = my_setup
test_hello.teardown = my_teardown
""")
reprec = testdir.inline_run()
reprec.assertoutcome(passed=1)
def test_nose_setup_partial(testdir):
pytest.importorskip("functools")
p = testdir.makepyfile("""
from functools import partial
l = []
def my_setup(x):
a = x
l.append(a)
def my_teardown(x):
b = x
l.append(b)
my_setup_partial = partial(my_setup, 1)
my_teardown_partial = partial(my_teardown, 2)
def test_hello():
print (l)
assert l == [1]
def test_world():
print (l)
assert l == [1,2]
test_hello.setup = my_setup_partial
test_hello.teardown = my_teardown_partial
""")
result = testdir.runpytest(p, '-p', 'nose')
result.stdout.fnmatch_lines([
"*2 passed*"
])
def test_nose_test_generator_fixtures(testdir):
p = testdir.makepyfile("""
# taken from nose-0.11.1 unit_tests/test_generator_fixtures.py
from nose.tools import eq_
called = []
def outer_setup():
called.append('outer_setup')
def outer_teardown():
called.append('outer_teardown')
def inner_setup():
called.append('inner_setup')
def inner_teardown():
called.append('inner_teardown')
def test_gen():
called[:] = []
for i in range(0, 5):
yield check, i
def check(i):
expect = ['outer_setup']
for x in range(0, i):
expect.append('inner_setup')
expect.append('inner_teardown')
expect.append('inner_setup')
eq_(called, expect)
test_gen.setup = outer_setup
test_gen.teardown = outer_teardown
check.setup = inner_setup
check.teardown = inner_teardown
class TestClass(object):
def setup(self):
print ("setup called in %s" % self)
self.called = ['setup']
def teardown(self):
print ("teardown called in %s" % self)
eq_(self.called, ['setup'])
self.called.append('teardown')
def test(self):
print ("test called in %s" % self)
for i in range(0, 5):
yield self.check, i
def check(self, i):
print ("check called in %s" % self)
expect = ['setup']
#for x in range(0, i):
# expect.append('setup')
# expect.append('teardown')
#expect.append('setup')
eq_(self.called, expect)
""")
result = testdir.runpytest(p, '-p', 'nose')
result.stdout.fnmatch_lines([
"*10 passed*"
])
def test_module_level_setup(testdir):
testdir.makepyfile("""
from nose.tools import with_setup
items = {}
def setup():
items[1]=1
def teardown():
del items[1]
def setup2():
items[2] = 2
def teardown2():
del items[2]
def test_setup_module_setup():
assert items[1] == 1
@with_setup(setup2, teardown2)
def test_local_setup():
assert items[2] == 2
assert 1 not in items
""")
result = testdir.runpytest('-p', 'nose')
result.stdout.fnmatch_lines([
"*2 passed*",
])
def test_nose_style_setup_teardown(testdir):
testdir.makepyfile("""
l = []
def setup_module():
l.append(1)
def teardown_module():
del l[0]
def test_hello():
assert l == [1]
def test_world():
assert l == [1]
""")
result = testdir.runpytest('-p', 'nose')
result.stdout.fnmatch_lines([
"*2 passed*",
])
def test_nose_setup_ordering(testdir):
testdir.makepyfile("""
def setup_module(mod):
mod.visited = True
class TestClass:
def setup(self):
assert visited
def test_first(self):
pass
""")
result = testdir.runpytest()
result.stdout.fnmatch_lines([
"*1 passed*",
])
def test_apiwrapper_problem_issue260(testdir):
# this would end up trying a call a optional teardown on the class
# for plain unittests we dont want nose behaviour
testdir.makepyfile("""
import unittest
class TestCase(unittest.TestCase):
def setup(self):
#should not be called in unittest testcases
assert 0, 'setup'
def teardown(self):
#should not be called in unittest testcases
assert 0, 'teardown'
def setUp(self):
print('setup')
def tearDown(self):
print('teardown')
def test_fun(self):
pass
""")
result = testdir.runpytest()
result.assert_outcomes(passed=1)
def test_setup_teardown_linking_issue265(testdir):
# we accidentally didnt integrate nose setupstate with normal setupstate
# this test ensures that won't happen again
testdir.makepyfile('''
import pytest
class TestGeneric(object):
def test_nothing(self):
"""Tests the API of the implementation (for generic and specialized)."""
@pytest.mark.skipif("True", reason=
"Skip tests to check if teardown is skipped as well.")
class TestSkipTeardown(TestGeneric):
def setup(self):
"""Sets up my specialized implementation for $COOL_PLATFORM."""
raise Exception("should not call setup for skipped tests")
def teardown(self):
"""Undoes the setup."""
raise Exception("should not call teardown for skipped tests")
''')
reprec = testdir.runpytest()
reprec.assert_outcomes(passed=1, skipped=1)
def test_SkipTest_during_collection(testdir):
p = testdir.makepyfile("""
import nose
raise nose.SkipTest("during collection")
def test_failing():
assert False
""")
result = testdir.runpytest(p)
result.assert_outcomes(skipped=1)
def test_SkipTest_in_test(testdir):
testdir.makepyfile("""
import nose
def test_skipping():
raise nose.SkipTest("in test")
""")
reprec = testdir.inline_run()
reprec.assertoutcome(skipped=1)
def test_istest_function_decorator(testdir):
p = testdir.makepyfile("""
import nose.tools
@nose.tools.istest
def not_test_prefix():
pass
""")
result = testdir.runpytest(p)
result.assert_outcomes(passed=1)
def test_nottest_function_decorator(testdir):
testdir.makepyfile("""
import nose.tools
@nose.tools.nottest
def test_prefix():
pass
""")
reprec = testdir.inline_run()
assert not reprec.getfailedcollections()
calls = reprec.getreports("pytest_runtest_logreport")
assert not calls
def test_istest_class_decorator(testdir):
p = testdir.makepyfile("""
import nose.tools
@nose.tools.istest
class NotTestPrefix:
def test_method(self):
pass
""")
result = testdir.runpytest(p)
result.assert_outcomes(passed=1)
def test_nottest_class_decorator(testdir):
testdir.makepyfile("""
import nose.tools
@nose.tools.nottest
class TestPrefix:
def test_method(self):
pass
""")
reprec = testdir.inline_run()
assert not reprec.getfailedcollections()
calls = reprec.getreports("pytest_runtest_logreport")
assert not calls
|
moonlighting-apps/x264 | refs/heads/master | tools/digress/scm/dummy.py | 145 | """
Dummy SCM backend for Digress.
"""
from random import random
def checkout(revision):
"""
Checkout a revision.
"""
pass
def current_rev():
"""
Get the current revision
"""
return str(random())
def revisions(rev_a, rev_b):
"""
Get a list of revisions from one to another.
"""
pass
def stash():
"""
Stash the repository.
"""
pass
def unstash():
"""
Unstash the repository.
"""
pass
def bisect(command, revision):
"""
Perform a bisection.
"""
raise NotImplementedError("dummy SCM backend does not support bisection")
|
glwu/python-for-android | refs/heads/master | python3-alpha/python3-src/Tools/freeze/checkextensions.py | 100 | # Check for a module in a set of extension directories.
# An extension directory should contain a Setup file
# and one or more .o files or a lib.a file.
import os
import parsesetup
def checkextensions(unknown, extensions):
files = []
modules = []
edict = {}
for e in extensions:
setup = os.path.join(e, 'Setup')
liba = os.path.join(e, 'lib.a')
if not os.path.isfile(liba):
liba = None
edict[e] = parsesetup.getsetupinfo(setup), liba
for mod in unknown:
for e in extensions:
(mods, vars), liba = edict[e]
if mod not in mods:
continue
modules.append(mod)
if liba:
# If we find a lib.a, use it, ignore the
# .o files, and use *all* libraries for
# *all* modules in the Setup file
if liba in files:
break
files.append(liba)
for m in list(mods.keys()):
files = files + select(e, mods, vars,
m, 1)
break
files = files + select(e, mods, vars, mod, 0)
break
return files, modules
def select(e, mods, vars, mod, skipofiles):
files = []
for w in mods[mod]:
w = treatword(w)
if not w:
continue
w = expandvars(w, vars)
for w in w.split():
if skipofiles and w[-2:] == '.o':
continue
# Assume $var expands to absolute pathname
if w[0] not in ('-', '$') and w[-2:] in ('.o', '.a'):
w = os.path.join(e, w)
if w[:2] in ('-L', '-R') and w[2:3] != '$':
w = w[:2] + os.path.join(e, w[2:])
files.append(w)
return files
cc_flags = ['-I', '-D', '-U']
cc_exts = ['.c', '.C', '.cc', '.c++']
def treatword(w):
if w[:2] in cc_flags:
return None
if w[:1] == '-':
return w # Assume loader flag
head, tail = os.path.split(w)
base, ext = os.path.splitext(tail)
if ext in cc_exts:
tail = base + '.o'
w = os.path.join(head, tail)
return w
def expandvars(str, vars):
i = 0
while i < len(str):
i = k = str.find('$', i)
if i < 0:
break
i = i+1
var = str[i:i+1]
i = i+1
if var == '(':
j = str.find(')', i)
if j < 0:
break
var = str[i:j]
i = j+1
if var in vars:
str = str[:k] + vars[var] + str[i:]
i = k
return str
|
barma1309/Kalista | refs/heads/master | .virtualenvs/Kalista/lib/python3.4/site-packages/django/test/html.py | 220 | """
Comparing two html documents.
"""
from __future__ import unicode_literals
import re
from django.utils import six
from django.utils.encoding import force_text, python_2_unicode_compatible
from django.utils.html_parser import HTMLParseError, HTMLParser
WHITESPACE = re.compile('\s+')
def normalize_whitespace(string):
return WHITESPACE.sub(' ', string)
@python_2_unicode_compatible
class Element(object):
def __init__(self, name, attributes):
self.name = name
self.attributes = sorted(attributes)
self.children = []
def append(self, element):
if isinstance(element, six.string_types):
element = force_text(element)
element = normalize_whitespace(element)
if self.children:
if isinstance(self.children[-1], six.string_types):
self.children[-1] += element
self.children[-1] = normalize_whitespace(self.children[-1])
return
elif self.children:
# removing last children if it is only whitespace
# this can result in incorrect dom representations since
# whitespace between inline tags like <span> is significant
if isinstance(self.children[-1], six.string_types):
if self.children[-1].isspace():
self.children.pop()
if element:
self.children.append(element)
def finalize(self):
def rstrip_last_element(children):
if children:
if isinstance(children[-1], six.string_types):
children[-1] = children[-1].rstrip()
if not children[-1]:
children.pop()
children = rstrip_last_element(children)
return children
rstrip_last_element(self.children)
for i, child in enumerate(self.children):
if isinstance(child, six.string_types):
self.children[i] = child.strip()
elif hasattr(child, 'finalize'):
child.finalize()
def __eq__(self, element):
if not hasattr(element, 'name'):
return False
if hasattr(element, 'name') and self.name != element.name:
return False
if len(self.attributes) != len(element.attributes):
return False
if self.attributes != element.attributes:
# attributes without a value is same as attribute with value that
# equals the attributes name:
# <input checked> == <input checked="checked">
for i in range(len(self.attributes)):
attr, value = self.attributes[i]
other_attr, other_value = element.attributes[i]
if value is None:
value = attr
if other_value is None:
other_value = other_attr
if attr != other_attr or value != other_value:
return False
if self.children != element.children:
return False
return True
def __hash__(self):
return hash((self.name,) + tuple(a for a in self.attributes))
def __ne__(self, element):
return not self.__eq__(element)
def _count(self, element, count=True):
if not isinstance(element, six.string_types):
if self == element:
return 1
i = 0
for child in self.children:
# child is text content and element is also text content, then
# make a simple "text" in "text"
if isinstance(child, six.string_types):
if isinstance(element, six.string_types):
if count:
i += child.count(element)
elif element in child:
return 1
else:
i += child._count(element, count=count)
if not count and i:
return i
return i
def __contains__(self, element):
return self._count(element, count=False) > 0
def count(self, element):
return self._count(element, count=True)
def __getitem__(self, key):
return self.children[key]
def __str__(self):
output = '<%s' % self.name
for key, value in self.attributes:
if value:
output += ' %s="%s"' % (key, value)
else:
output += ' %s' % key
if self.children:
output += '>\n'
output += ''.join(six.text_type(c) for c in self.children)
output += '\n</%s>' % self.name
else:
output += ' />'
return output
def __repr__(self):
return six.text_type(self)
@python_2_unicode_compatible
class RootElement(Element):
def __init__(self):
super(RootElement, self).__init__(None, ())
def __str__(self):
return ''.join(six.text_type(c) for c in self.children)
class Parser(HTMLParser):
SELF_CLOSING_TAGS = ('br', 'hr', 'input', 'img', 'meta', 'spacer',
'link', 'frame', 'base', 'col')
def __init__(self):
HTMLParser.__init__(self)
self.root = RootElement()
self.open_tags = []
self.element_positions = {}
def error(self, msg):
raise HTMLParseError(msg, self.getpos())
def format_position(self, position=None, element=None):
if not position and element:
position = self.element_positions[element]
if position is None:
position = self.getpos()
if hasattr(position, 'lineno'):
position = position.lineno, position.offset
return 'Line %d, Column %d' % position
@property
def current(self):
if self.open_tags:
return self.open_tags[-1]
else:
return self.root
def handle_startendtag(self, tag, attrs):
self.handle_starttag(tag, attrs)
if tag not in self.SELF_CLOSING_TAGS:
self.handle_endtag(tag)
def handle_starttag(self, tag, attrs):
# Special case handling of 'class' attribute, so that comparisons of DOM
# instances are not sensitive to ordering of classes.
attrs = [
(name, " ".join(sorted(value.split(" "))))
if name == "class"
else (name, value)
for name, value in attrs
]
element = Element(tag, attrs)
self.current.append(element)
if tag not in self.SELF_CLOSING_TAGS:
self.open_tags.append(element)
self.element_positions[element] = self.getpos()
def handle_endtag(self, tag):
if not self.open_tags:
self.error("Unexpected end tag `%s` (%s)" % (
tag, self.format_position()))
element = self.open_tags.pop()
while element.name != tag:
if not self.open_tags:
self.error("Unexpected end tag `%s` (%s)" % (
tag, self.format_position()))
element = self.open_tags.pop()
def handle_data(self, data):
self.current.append(data)
def handle_charref(self, name):
self.current.append('&%s;' % name)
def handle_entityref(self, name):
self.current.append('&%s;' % name)
def parse_html(html):
"""
Takes a string that contains *valid* HTML and turns it into a Python object
structure that can be easily compared against other HTML on semantic
equivalence. Syntactical differences like which quotation is used on
arguments will be ignored.
"""
parser = Parser()
parser.feed(html)
parser.close()
document = parser.root
document.finalize()
# Removing ROOT element if it's not necessary
if len(document.children) == 1:
if not isinstance(document.children[0], six.string_types):
document = document.children[0]
return document
|
try-dash-now/dash-ia | refs/heads/master | tools/build/bdist.win32/winexe/temp/_hashlib.py | 29 |
def __load():
import imp, os, sys
try:
dirname = os.path.dirname(__loader__.archive)
except NameError:
dirname = sys.prefix
path = os.path.join(dirname, '_hashlib.pyd')
#print "py2exe extension module", __name__, "->", path
mod = imp.load_dynamic(__name__, path)
## mod.frozen = 1
__load()
del __load
|
djc/couchdb-python | refs/heads/master | couchdb/loader.py | 1 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Load design documents from the filesystem into a dict.
Subset of couchdbkit/couchapp functionality.
Description
-----------
Convert a target directory into an object (dict).
Each filename (without extension) or subdirectory name is a key in this object.
For files, the utf-8-decoded contents are the value, except for .json files
which are first decoded as json.
Subdirectories are converted into objects using the same procedure and then
added to the parent object.
Typically used for design documents. This directory tree::
.
├── filters
│ └── forms_only.js
├── _id
├── language
├── lib
│ └── validate.js
└── views
├── view_a
│ └── map.js
├── view_b
│ └── map.js
└── view_c
└── map.js
Becomes this object::
{
"views": {
"view_a": {
"map": "function(doc) { ... }"
},
"view_b": {
"map": "function(doc) { ... }"
},
"view_c": {
"map": "function(doc) { ... }"
}
},
"_id": "_design/name_of_design_document",
"filters": {
"forms_only": "function(doc, req) { ... }"
},
"language": "javascript",
"lib": {
"validate": "// A library for validations ..."
}
}
"""
from __future__ import unicode_literals, absolute_import
import os.path
import pprint
import codecs
import json
class DuplicateKeyError(ValueError):
pass
def load_design_doc(directory, strip=False, predicate=lambda x: True):
"""
Load a design document from the filesystem.
strip: remove leading and trailing whitespace from file contents,
like couchdbkit.
predicate: function that is passed the full path to each file or directory.
Each entry is only added to the document if predicate returns True.
Can be used to ignore backup files etc.
"""
objects = {}
if not os.path.isdir(directory):
raise OSError("No directory: '{0}'".format(directory))
for (dirpath, dirnames, filenames) in os.walk(directory, topdown=False):
key = os.path.split(dirpath)[-1]
ob = {}
objects[dirpath] = (key, ob)
for name in filenames:
fkey = os.path.splitext(name)[0]
fullname = os.path.join(dirpath, name)
if not predicate(fullname): continue
if fkey in ob:
raise DuplicateKeyError("file '{0}' clobbers key '{1}'"
.format(fullname, fkey))
with codecs.open(fullname, 'r', 'utf-8') as f:
contents = f.read()
if name.endswith('.json'):
contents = json.loads(contents)
elif strip:
contents = contents.strip()
ob[fkey] = contents
for name in dirnames:
if name == '_attachments':
raise NotImplementedError("_attachments are not supported")
fullpath = os.path.join(dirpath, name)
if not predicate(fullpath): continue
subkey, subthing = objects[fullpath]
if subkey in ob:
raise DuplicateKeyError("directory '{0}' clobbers key '{1}'"
.format(fullpath,subkey))
ob[subkey] = subthing
return ob
def main():
import sys
try:
directory = sys.argv[1]
except IndexError:
sys.stderr.write("Usage:\n\t{0} [directory]\n".format(sys.argv[0]))
sys.exit(1)
obj = load_design_doc(directory)
sys.stdout.write(json.dumps(obj, indent=2))
if __name__ == "__main__":
main()
|
CUCWD/edx-platform | refs/heads/master | lms/djangoapps/verify_student/models.py | 11 | # -*- coding: utf-8 -*-
"""
Models for Student Identity Verification
This is where we put any models relating to establishing the real-life identity
of a student over a period of time. Right now, the only models are the abstract
`PhotoVerification`, and its one concrete implementation
`SoftwareSecurePhotoVerification`. The hope is to keep as much of the
photo verification process as generic as possible.
"""
import functools
import json
import logging
import os.path
import uuid
from datetime import datetime, timedelta
from email.utils import formatdate
import pytz
import requests
import six
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.core.cache import cache
from django.core.files.base import ContentFile
from django.urls import reverse
from django.db import models
from django.dispatch import receiver
from django.utils.functional import cached_property
from django.utils.translation import ugettext_lazy
from model_utils import Choices
from model_utils.models import StatusModel, TimeStampedModel
from opaque_keys.edx.django.models import CourseKeyField
from openedx.core.djangolib.model_mixins import DeletableByUserValue
from lms.djangoapps.verify_student.ssencrypt import (
encrypt_and_encode,
generate_signed_message,
random_aes_key,
rsa_encrypt
)
from openedx.core.djangoapps.signals.signals import LEARNER_NOW_VERIFIED
from openedx.core.storage import get_storage
from .utils import earliest_allowed_verification_date
log = logging.getLogger(__name__)
def generateUUID(): # pylint: disable=invalid-name
""" Utility function; generates UUIDs """
return str(uuid.uuid4())
class VerificationException(Exception):
pass
def status_before_must_be(*valid_start_statuses):
"""
Helper decorator with arguments to make sure that an object with a `status`
attribute is in one of a list of acceptable status states before a method
is called. You could use it in a class definition like:
@status_before_must_be("submitted", "approved", "denied")
def refund_user(self, user_id):
# Do logic here...
If the object has a status that is not listed when the `refund_user` method
is invoked, it will throw a `VerificationException`. This is just to avoid
distracting boilerplate when looking at a Model that needs to go through a
workflow process.
"""
def decorator_func(func):
"""
Decorator function that gets returned
"""
@functools.wraps(func)
def with_status_check(obj, *args, **kwargs):
if obj.status not in valid_start_statuses:
exception_msg = (
u"Error calling {} {}: status is '{}', must be one of: {}"
).format(func, obj, obj.status, valid_start_statuses)
raise VerificationException(exception_msg)
return func(obj, *args, **kwargs)
return with_status_check
return decorator_func
class IDVerificationAttempt(StatusModel):
"""
Each IDVerificationAttempt represents a Student's attempt to establish
their identity through one of several methods that inherit from this Model,
including PhotoVerification and SSOVerification.
"""
STATUS = Choices('created', 'ready', 'submitted', 'must_retry', 'approved', 'denied')
user = models.ForeignKey(User, db_index=True, on_delete=models.CASCADE)
# They can change their name later on, so we want to copy the value here so
# we always preserve what it was at the time they requested. We only copy
# this value during the mark_ready() step. Prior to that, you should be
# displaying the user's name from their user.profile.name.
name = models.CharField(blank=True, max_length=255)
created_at = models.DateTimeField(auto_now_add=True, db_index=True)
updated_at = models.DateTimeField(auto_now=True, db_index=True)
class Meta(object):
app_label = "verify_student"
abstract = True
ordering = ['-created_at']
@property
def expiration_datetime(self):
"""Datetime that the verification will expire. """
days_good_for = settings.VERIFY_STUDENT["DAYS_GOOD_FOR"]
return self.created_at + timedelta(days=days_good_for)
def should_display_status_to_user(self):
"""Whether or not the status from this attempt should be displayed to the user."""
raise NotImplementedError
def active_at_datetime(self, deadline):
"""Check whether the verification was active at a particular datetime.
Arguments:
deadline (datetime): The date at which the verification was active
(created before and expiration datetime is after today).
Returns:
bool
"""
return (
self.created_at < deadline and
self.expiration_datetime > datetime.now(pytz.UTC)
)
class ManualVerification(IDVerificationAttempt):
"""
Each ManualVerification represents a user's verification that bypasses the need for
any other verification.
"""
reason = models.CharField(
max_length=255,
blank=True,
help_text=(
'Specifies the reason for manual verification of the user.'
)
)
class Meta(object):
app_label = 'verify_student'
def __unicode__(self):
return 'ManualIDVerification for {name}, status: {status}'.format(
name=self.name,
status=self.status,
)
def should_display_status_to_user(self):
"""
Whether or not the status should be displayed to the user.
"""
return False
class SSOVerification(IDVerificationAttempt):
"""
Each SSOVerification represents a Student's attempt to establish their identity
by signing in with SSO. ID verification through SSO bypasses the need for
photo verification.
"""
OAUTH2 = 'third_party_auth.models.OAuth2ProviderConfig'
SAML = 'third_party_auth.models.SAMLProviderConfig'
LTI = 'third_party_auth.models.LTIProviderConfig'
IDENTITY_PROVIDER_TYPE_CHOICES = (
(OAUTH2, 'OAuth2 Provider'),
(SAML, 'SAML Provider'),
(LTI, 'LTI Provider'),
)
identity_provider_type = models.CharField(
max_length=100,
blank=False,
choices=IDENTITY_PROVIDER_TYPE_CHOICES,
default=SAML,
help_text=(
'Specifies which type of Identity Provider this verification originated from.'
)
)
identity_provider_slug = models.SlugField(
max_length=30, db_index=True, default='default',
help_text=(
'The slug uniquely identifying the Identity Provider this verification originated from.'
))
class Meta(object):
app_label = "verify_student"
def __unicode__(self):
return 'SSOIDVerification for {name}, status: {status}'.format(
name=self.name,
status=self.status,
)
def should_display_status_to_user(self):
"""Whether or not the status from this attempt should be displayed to the user."""
return False
class PhotoVerification(IDVerificationAttempt):
"""
Each PhotoVerification represents a Student's attempt to establish
their identity by uploading a photo of themselves and a picture ID. An
attempt actually has a number of fields that need to be filled out at
different steps of the approval process. While it's useful as a Django Model
for the querying facilities, **you should only edit a `PhotoVerification`
object through the methods provided**. Initialize them with a user:
attempt = PhotoVerification(user=user)
We track this attempt through various states:
`created`
Initial creation and state we're in after uploading the images.
`ready`
The user has uploaded their images and checked that they can read the
images. There's a separate state here because it may be the case that we
don't actually submit this attempt for review until payment is made.
`submitted`
Submitted for review. The review may be done by a staff member or an
external service. The user cannot make changes once in this state.
`must_retry`
We submitted this, but there was an error on submission (i.e. we did not
get a 200 when we POSTed to Software Secure)
`approved`
An admin or an external service has confirmed that the user's photo and
photo ID match up, and that the photo ID's name matches the user's.
`denied`
The request has been denied. See `error_msg` for details on why. An
admin might later override this and change to `approved`, but the
student cannot re-open this attempt -- they have to create another
attempt and submit it instead.
Because this Model inherits from IDVerificationAttempt, which inherits
from StatusModel, we can also do things like:
attempt.status == PhotoVerification.STATUS.created
attempt.status == "created"
pending_requests = PhotoVerification.submitted.all()
"""
######################## Fields Set During Creation ########################
# See class docstring for description of status states
# Where we place the uploaded image files (e.g. S3 URLs)
face_image_url = models.URLField(blank=True, max_length=255)
photo_id_image_url = models.URLField(blank=True, max_length=255)
# Randomly generated UUID so that external services can post back the
# results of checking a user's photo submission without use exposing actual
# user IDs or something too easily guessable.
receipt_id = models.CharField(
db_index=True,
default=generateUUID,
max_length=255,
)
# Indicates whether or not a user wants to see the verification status
# displayed on their dash. Right now, only relevant for allowing students
# to "dismiss" a failed midcourse reverification message
# TODO: This field is deprecated.
display = models.BooleanField(db_index=True, default=True)
######################## Fields Set When Submitting ########################
submitted_at = models.DateTimeField(null=True, db_index=True)
#################### Fields Set During Approval/Denial #####################
# If the review was done by an internal staff member, mark who it was.
reviewing_user = models.ForeignKey(
User,
db_index=True,
default=None,
null=True,
related_name="photo_verifications_reviewed",
on_delete=models.CASCADE,
)
# Mark the name of the service used to evaluate this attempt (e.g
# Software Secure).
reviewing_service = models.CharField(blank=True, max_length=255)
# If status is "denied", this should contain text explaining why.
error_msg = models.TextField(blank=True)
# Non-required field. External services can add any arbitrary codes as time
# goes on. We don't try to define an exhuastive list -- this is just
# capturing it so that we can later query for the common problems.
error_code = models.CharField(blank=True, max_length=50)
class Meta(object):
app_label = "verify_student"
abstract = True
ordering = ['-created_at']
def parsed_error_msg(self):
"""
Sometimes, the error message we've received needs to be parsed into
something more human readable
The default behavior is to return the current error message as is.
"""
return self.error_msg
@status_before_must_be("created")
def upload_face_image(self, img):
raise NotImplementedError
@status_before_must_be("created")
def upload_photo_id_image(self, img):
raise NotImplementedError
@status_before_must_be("created")
def mark_ready(self):
"""
Mark that the user data in this attempt is correct. In order to
succeed, the user must have uploaded the necessary images
(`face_image_url`, `photo_id_image_url`). This method will also copy
their name from their user profile. Prior to marking it ready, we read
this value directly from their profile, since they're free to change it.
This often happens because people put in less formal versions of their
name on signup, but realize they want something different to go on a
formal document.
Valid attempt statuses when calling this method:
`created`
Status after method completes: `ready`
Other fields that will be set by this method:
`name`
State Transitions:
`created` → `ready`
This is what happens when the user confirms to us that the pictures
they uploaded are good. Note that we don't actually do a submission
anywhere yet.
"""
# At any point prior to this, they can change their names via their
# student dashboard. But at this point, we lock the value into the
# attempt.
self.name = self.user.profile.name
self.status = "ready"
self.save()
@status_before_must_be("must_retry", "submitted", "approved", "denied")
def approve(self, user_id=None, service=""):
"""
Approve this attempt. `user_id`
Valid attempt statuses when calling this method:
`submitted`, `approved`, `denied`
Status after method completes: `approved`
Other fields that will be set by this method:
`reviewed_by_user_id`, `reviewed_by_service`, `error_msg`
State Transitions:
`submitted` → `approved`
This is the usual flow, whether initiated by a staff user or an
external validation service.
`approved` → `approved`
No-op. First one to approve it wins.
`denied` → `approved`
This might happen if a staff member wants to override a decision
made by an external service or another staff member (say, in
response to a support request). In this case, the previous values
of `reviewed_by_user_id` and `reviewed_by_service` will be changed
to whoever is doing the approving, and `error_msg` will be reset.
The only record that this record was ever denied would be in our
logs. This should be a relatively rare occurence.
"""
# If someone approves an outdated version of this, the first one wins
if self.status == "approved":
return
log.info(u"Verification for user '{user_id}' approved by '{reviewer}'.".format(
user_id=self.user, reviewer=user_id
))
self.error_msg = "" # reset, in case this attempt was denied before
self.error_code = "" # reset, in case this attempt was denied before
self.reviewing_user = user_id
self.reviewing_service = service
self.status = "approved"
self.save()
# Emit signal to find and generate eligible certificates
LEARNER_NOW_VERIFIED.send_robust(
sender=PhotoVerification,
user=self.user
)
@status_before_must_be("must_retry", "submitted", "approved", "denied")
def deny(self,
error_msg,
error_code="",
reviewing_user=None,
reviewing_service=""):
"""
Deny this attempt.
Valid attempt statuses when calling this method:
`submitted`, `approved`, `denied`
Status after method completes: `denied`
Other fields that will be set by this method:
`reviewed_by_user_id`, `reviewed_by_service`, `error_msg`,
`error_code`
State Transitions:
`submitted` → `denied`
This is the usual flow, whether initiated by a staff user or an
external validation service.
`approved` → `denied`
This might happen if a staff member wants to override a decision
made by an external service or another staff member, or just correct
a mistake made during the approval process. In this case, the
previous values of `reviewed_by_user_id` and `reviewed_by_service`
will be changed to whoever is doing the denying. The only record
that this record was ever approved would be in our logs. This should
be a relatively rare occurence.
`denied` → `denied`
Update the error message and reviewing_user/reviewing_service. Just
lets you amend the error message in case there were additional
details to be made.
"""
log.info(u"Verification for user '{user_id}' denied by '{reviewer}'.".format(
user_id=self.user, reviewer=reviewing_user
))
self.error_msg = error_msg
self.error_code = error_code
self.reviewing_user = reviewing_user
self.reviewing_service = reviewing_service
self.status = "denied"
self.save()
@status_before_must_be("must_retry", "submitted", "approved", "denied")
def system_error(self,
error_msg,
error_code="",
reviewing_user=None,
reviewing_service=""):
"""
Mark that this attempt could not be completed because of a system error.
Status should be moved to `must_retry`. For example, if Software Secure
reported to us that they couldn't process our submission because they
couldn't decrypt the image we sent.
"""
if self.status in ["approved", "denied"]:
return # If we were already approved or denied, just leave it.
self.error_msg = error_msg
self.error_code = error_code
self.reviewing_user = reviewing_user
self.reviewing_service = reviewing_service
self.status = "must_retry"
self.save()
@classmethod
def retire_user(cls, user_id):
"""
Retire user as part of GDPR Phase I
Returns 'True' if records found
:param user_id: int
:return: bool
"""
try:
user_obj = User.objects.get(id=user_id)
except User.DoesNotExist:
return False
photo_objects = cls.objects.filter(
user=user_obj
).update(
name='',
face_image_url='',
photo_id_image_url='',
photo_id_key=''
)
return photo_objects > 0
class SoftwareSecurePhotoVerification(PhotoVerification):
"""
Model to verify identity using a service provided by Software Secure. Much
of the logic is inherited from `PhotoVerification`, but this class
encrypts the photos.
Software Secure (http://www.softwaresecure.com/) is a remote proctoring
service that also does identity verification. A student uses their webcam
to upload two images: one of their face, one of a photo ID. Due to the
sensitive nature of the data, the following security precautions are taken:
1. The snapshot of their face is encrypted using AES-256 in CBC mode. All
face photos are encypted with the same key, and this key is known to
both Software Secure and edx-platform.
2. The snapshot of a user's photo ID is also encrypted using AES-256, but
the key is randomly generated using os.urandom. Every verification
attempt has a new key. The AES key is then encrypted using a public key
provided by Software Secure. We store only the RSA-encryped AES key.
Since edx-platform does not have Software Secure's private RSA key, it
means that we can no longer even read photo ID.
3. The encrypted photos are base64 encoded and stored in an S3 bucket that
edx-platform does not have read access to.
Note: this model handles *inital* verifications (which you must perform
at the time you register for a verified cert).
"""
# This is a base64.urlsafe_encode(rsa_encrypt(photo_id_aes_key), ss_pub_key)
# So first we generate a random AES-256 key to encrypt our photo ID with.
# Then we RSA encrypt it with Software Secure's public key. Then we base64
# encode that. The result is saved here. Actual expected length is 344.
photo_id_key = models.TextField(max_length=1024)
IMAGE_LINK_DURATION = 5 * 60 * 60 * 24 # 5 days in seconds
copy_id_photo_from = models.ForeignKey("self", null=True, blank=True, on_delete=models.CASCADE)
@classmethod
def get_initial_verification(cls, user, earliest_allowed_date=None):
"""Get initial verification for a user with the 'photo_id_key'.
Arguments:
user(User): user object
earliest_allowed_date(datetime): override expiration date for initial verification
Return:
SoftwareSecurePhotoVerification (object) or None
"""
init_verification = cls.objects.filter(
user=user,
status__in=["submitted", "approved"],
created_at__gte=(
earliest_allowed_date or earliest_allowed_verification_date()
)
).exclude(photo_id_key='')
return init_verification.latest('created_at') if init_verification.exists() else None
@status_before_must_be("created")
def upload_face_image(self, img_data):
"""
Upload an image of the user's face. `img_data` should be a raw
bytestream of a PNG image. This method will take the data, encrypt it
using our FACE_IMAGE_AES_KEY, encode it with base64 and save it to the
storage backend.
Yes, encoding it to base64 adds compute and disk usage without much real
benefit, but that's what the other end of this API is expecting to get.
"""
# Skip this whole thing if we're running acceptance tests or if we're
# developing and aren't interested in working on student identity
# verification functionality. If you do want to work on it, you have to
# explicitly enable these in your private settings.
if settings.FEATURES.get('AUTOMATIC_VERIFY_STUDENT_IDENTITY_FOR_TESTING'):
return
aes_key_str = settings.VERIFY_STUDENT["SOFTWARE_SECURE"]["FACE_IMAGE_AES_KEY"]
aes_key = aes_key_str.decode("hex")
path = self._get_path("face")
buff = ContentFile(encrypt_and_encode(img_data, aes_key))
self._storage.save(path, buff)
@status_before_must_be("created")
def upload_photo_id_image(self, img_data):
"""
Upload an the user's photo ID image. `img_data` should be a raw
bytestream of a PNG image. This method will take the data, encrypt it
using a randomly generated AES key, encode it with base64 and save it
to the storage backend. The random key is also encrypted using Software
Secure's public RSA key and stored in our `photo_id_key` field.
Yes, encoding it to base64 adds compute and disk usage without much real
benefit, but that's what the other end of this API is expecting to get.
"""
# Skip this whole thing if we're running acceptance tests or if we're
# developing and aren't interested in working on student identity
# verification functionality. If you do want to work on it, you have to
# explicitly enable these in your private settings.
if settings.FEATURES.get('AUTOMATIC_VERIFY_STUDENT_IDENTITY_FOR_TESTING'):
# fake photo id key is set only for initial verification
self.photo_id_key = 'fake-photo-id-key'
self.save()
return
aes_key = random_aes_key()
rsa_key_str = settings.VERIFY_STUDENT["SOFTWARE_SECURE"]["RSA_PUBLIC_KEY"]
rsa_encrypted_aes_key = rsa_encrypt(aes_key, rsa_key_str)
# Save this to the storage backend
path = self._get_path("photo_id")
buff = ContentFile(encrypt_and_encode(img_data, aes_key))
self._storage.save(path, buff)
# Update our record fields
self.photo_id_key = rsa_encrypted_aes_key.encode('base64')
self.save()
@status_before_must_be("must_retry", "ready", "submitted")
def submit(self, copy_id_photo_from=None):
"""
Submit our verification attempt to Software Secure for validation. This
will set our status to "submitted" if the post is successful, and
"must_retry" if the post fails.
Keyword Arguments:
copy_id_photo_from (SoftwareSecurePhotoVerification): If provided, re-send the ID photo
data from this attempt. This is used for reverification, in which new face photos
are sent with previously-submitted ID photos.
"""
try:
response = self.send_request(copy_id_photo_from=copy_id_photo_from)
if response.ok:
self.submitted_at = datetime.now(pytz.UTC)
self.status = "submitted"
self.save()
else:
self.status = "must_retry"
self.error_msg = response.text
self.save()
except Exception: # pylint: disable=broad-except
log.exception(
'Software Secure submission failed for user %s, setting status to must_retry',
self.user.username
)
self.status = "must_retry"
self.save()
def parsed_error_msg(self):
"""
Parse the error messages we receive from SoftwareSecure
Error messages are written in the form:
`[{"photoIdReasons": ["Not provided"]}]`
Returns:
str[]: List of error messages.
"""
parsed_errors = []
error_map = {
'EdX name not provided': 'name_mismatch',
'Name mismatch': 'name_mismatch',
'Photo/ID Photo mismatch': 'photos_mismatched',
'ID name not provided': 'id_image_missing_name',
'Invalid Id': 'id_invalid',
'No text': 'id_invalid',
'Not provided': 'id_image_missing',
'Photo hidden/No photo': 'id_image_not_clear',
'Text not clear': 'id_image_not_clear',
'Face out of view': 'user_image_not_clear',
'Image not clear': 'user_image_not_clear',
'Photo not provided': 'user_image_missing',
}
try:
messages = set()
message_groups = json.loads(self.error_msg)
for message_group in message_groups:
messages = messages.union(set(*six.itervalues(message_group)))
for message in messages:
parsed_error = error_map.get(message)
if parsed_error:
parsed_errors.append(parsed_error)
else:
log.debug('Ignoring photo verification error message: %s', message)
except Exception: # pylint: disable=broad-except
log.exception('Failed to parse error message for SoftwareSecurePhotoVerification %d', self.pk)
return parsed_errors
def image_url(self, name, override_receipt_id=None):
"""
We dynamically generate this, since we want it the expiration clock to
start when the message is created, not when the record is created.
Arguments:
name (str): Name of the image (e.g. "photo_id" or "face")
Keyword Arguments:
override_receipt_id (str): If provided, use this receipt ID instead
of the ID for this attempt. This is useful for reverification
where we need to construct a URL to a previously-submitted
photo ID image.
Returns:
string: The expiring URL for the image.
"""
path = self._get_path(name, override_receipt_id=override_receipt_id)
return self._storage.url(path)
@cached_property
def _storage(self):
"""
Return the configured django storage backend.
"""
config = settings.VERIFY_STUDENT["SOFTWARE_SECURE"]
# Default to the S3 backend for backward compatibility
storage_class = config.get("STORAGE_CLASS", "storages.backends.s3boto.S3BotoStorage")
storage_kwargs = config.get("STORAGE_KWARGS", {})
# Map old settings to the parameters expected by the storage backend
if "AWS_ACCESS_KEY" in config:
storage_kwargs["access_key"] = config["AWS_ACCESS_KEY"]
if "AWS_SECRET_KEY" in config:
storage_kwargs["secret_key"] = config["AWS_SECRET_KEY"]
if "S3_BUCKET" in config:
storage_kwargs["bucket"] = config["S3_BUCKET"]
storage_kwargs["querystring_expire"] = self.IMAGE_LINK_DURATION
return get_storage(storage_class, **storage_kwargs)
def _get_path(self, prefix, override_receipt_id=None):
"""
Returns the path to a resource with this instance's `receipt_id`.
If `override_receipt_id` is given, the path to that resource will be
retrieved instead. This allows us to retrieve images submitted in
previous attempts (used for reverification, where we send a new face
photo with the same photo ID from a previous attempt).
"""
receipt_id = self.receipt_id if override_receipt_id is None else override_receipt_id
return os.path.join(prefix, receipt_id)
def _encrypted_user_photo_key_str(self):
"""
Software Secure needs to have both UserPhoto and PhotoID decrypted in
the same manner. So even though this is going to be the same for every
request, we're also using RSA encryption to encrypt the AES key for
faces.
"""
face_aes_key_str = settings.VERIFY_STUDENT["SOFTWARE_SECURE"]["FACE_IMAGE_AES_KEY"]
face_aes_key = face_aes_key_str.decode("hex")
rsa_key_str = settings.VERIFY_STUDENT["SOFTWARE_SECURE"]["RSA_PUBLIC_KEY"]
rsa_encrypted_face_aes_key = rsa_encrypt(face_aes_key, rsa_key_str)
return rsa_encrypted_face_aes_key.encode("base64")
def create_request(self, copy_id_photo_from=None):
"""
Construct the HTTP request to the photo verification service.
Keyword Arguments:
copy_id_photo_from (SoftwareSecurePhotoVerification): If provided, re-send the ID photo
data from this attempt. This is used for reverification, in which new face photos
are sent with previously-submitted ID photos.
Returns:
tuple of (header, body), where both `header` and `body` are dictionaries.
"""
access_key = settings.VERIFY_STUDENT["SOFTWARE_SECURE"]["API_ACCESS_KEY"]
secret_key = settings.VERIFY_STUDENT["SOFTWARE_SECURE"]["API_SECRET_KEY"]
scheme = "https" if settings.HTTPS == "on" else "http"
callback_url = "{}://{}{}".format(
scheme, settings.SITE_NAME, reverse('verify_student_results_callback')
)
# If we're copying the photo ID image from a previous verification attempt,
# then we need to send the old image data with the correct image key.
photo_id_url = (
self.image_url("photo_id")
if copy_id_photo_from is None
else self.image_url("photo_id", override_receipt_id=copy_id_photo_from.receipt_id)
)
photo_id_key = (
self.photo_id_key
if copy_id_photo_from is None else
copy_id_photo_from.photo_id_key
)
body = {
"EdX-ID": str(self.receipt_id),
"ExpectedName": self.name,
"PhotoID": photo_id_url,
"PhotoIDKey": photo_id_key,
"SendResponseTo": callback_url,
"UserPhoto": self.image_url("face"),
"UserPhotoKey": self._encrypted_user_photo_key_str(),
}
headers = {
"Content-Type": "application/json",
"Date": formatdate(timeval=None, localtime=False, usegmt=True)
}
_message, _sig, authorization = generate_signed_message(
"POST", headers, body, access_key, secret_key
)
headers['Authorization'] = authorization
return headers, body
def request_message_txt(self):
"""
This is the body of the request we send across. This is never actually
used in the code, but exists for debugging purposes -- you can call
`print attempt.request_message_txt()` on the console and get a readable
rendering of the request that would be sent across, without actually
sending anything.
"""
headers, body = self.create_request()
header_txt = "\n".join(
"{}: {}".format(h, v) for h, v in sorted(headers.items())
)
body_txt = json.dumps(body, indent=2, sort_keys=True, ensure_ascii=False).encode('utf-8')
return header_txt + "\n\n" + body_txt
def send_request(self, copy_id_photo_from=None):
"""
Assembles a submission to Software Secure and sends it via HTTPS.
Keyword Arguments:
copy_id_photo_from (SoftwareSecurePhotoVerification): If provided, re-send the ID photo
data from this attempt. This is used for reverification, in which new face photos
are sent with previously-submitted ID photos.
Returns:
request.Response
"""
# If AUTOMATIC_VERIFY_STUDENT_IDENTITY_FOR_TESTING is True, we want to
# skip posting anything to Software Secure. We actually don't even
# create the message because that would require encryption and message
# signing that rely on settings.VERIFY_STUDENT values that aren't set
# in dev. So we just pretend like we successfully posted
if settings.FEATURES.get('AUTOMATIC_VERIFY_STUDENT_IDENTITY_FOR_TESTING'):
fake_response = requests.Response()
fake_response.status_code = 200
return fake_response
headers, body = self.create_request(copy_id_photo_from=copy_id_photo_from)
response = requests.post(
settings.VERIFY_STUDENT["SOFTWARE_SECURE"]["API_URL"],
headers=headers,
data=json.dumps(body, indent=2, sort_keys=True, ensure_ascii=False).encode('utf-8'),
verify=False
)
log.info("Sent request to Software Secure for receipt ID %s.", self.receipt_id)
if copy_id_photo_from is not None:
log.info(
(
"Software Secure attempt with receipt ID %s used the same photo ID "
"data as the receipt with ID %s"
),
self.receipt_id, copy_id_photo_from.receipt_id
)
log.debug("Headers:\n{}\n\n".format(headers))
log.debug("Body:\n{}\n\n".format(body))
log.debug("Return code: {}".format(response.status_code))
log.debug("Return message:\n\n{}\n\n".format(response.text))
return response
def should_display_status_to_user(self):
"""Whether or not the status from this attempt should be displayed to the user."""
return True
class VerificationDeadline(TimeStampedModel):
"""
Represent a verification deadline for a particular course.
The verification deadline is the datetime after which
users are no longer allowed to submit photos for initial verification
in a course.
Note that this is NOT the same as the "upgrade" deadline, after
which a user is no longer allowed to upgrade to a verified enrollment.
If no verification deadline record exists for a course,
then that course does not have a deadline. This means that users
can submit photos at any time.
"""
class Meta(object):
app_label = "verify_student"
course_key = CourseKeyField(
max_length=255,
db_index=True,
unique=True,
help_text=ugettext_lazy(u"The course for which this deadline applies"),
)
deadline = models.DateTimeField(
help_text=ugettext_lazy(
u"The datetime after which users are no longer allowed "
u"to submit photos for verification."
)
)
# The system prefers to set this automatically based on default settings. But
# if the field is set manually we want a way to indicate that so we don't
# overwrite the manual setting of the field.
deadline_is_explicit = models.BooleanField(default=False)
ALL_DEADLINES_CACHE_KEY = "verify_student.all_verification_deadlines"
@classmethod
def set_deadline(cls, course_key, deadline, is_explicit=False):
"""
Configure the verification deadline for a course.
If `deadline` is `None`, then the course will have no verification
deadline. In this case, users will be able to verify for the course
at any time.
Arguments:
course_key (CourseKey): Identifier for the course.
deadline (datetime or None): The verification deadline.
"""
if deadline is None:
VerificationDeadline.objects.filter(course_key=course_key).delete()
else:
record, created = VerificationDeadline.objects.get_or_create(
course_key=course_key,
defaults={"deadline": deadline, "deadline_is_explicit": is_explicit}
)
if not created:
record.deadline = deadline
record.deadline_is_explicit = is_explicit
record.save()
@classmethod
def deadlines_for_courses(cls, course_keys):
"""
Retrieve verification deadlines for particular courses.
Arguments:
course_keys (list): List of `CourseKey`s.
Returns:
dict: Map of course keys to datetimes (verification deadlines)
"""
all_deadlines = cache.get(cls.ALL_DEADLINES_CACHE_KEY)
if all_deadlines is None:
all_deadlines = {
deadline.course_key: deadline.deadline
for deadline in VerificationDeadline.objects.all()
}
cache.set(cls.ALL_DEADLINES_CACHE_KEY, all_deadlines)
return {
course_key: all_deadlines[course_key]
for course_key in course_keys
if course_key in all_deadlines
}
@classmethod
def deadline_for_course(cls, course_key):
"""
Retrieve the verification deadline for a particular course.
Arguments:
course_key (CourseKey): The identifier for the course.
Returns:
datetime or None
"""
try:
deadline = cls.objects.get(course_key=course_key)
return deadline.deadline
except cls.DoesNotExist:
return None
@receiver(models.signals.post_save, sender=VerificationDeadline)
@receiver(models.signals.post_delete, sender=VerificationDeadline)
def invalidate_deadline_caches(sender, **kwargs): # pylint: disable=unused-argument
"""Invalidate the cached verification deadline information. """
cache.delete(VerificationDeadline.ALL_DEADLINES_CACHE_KEY)
|
UrsusPilot/mavlink | refs/heads/master | pymavlink/tools/mavlogdump.py | 2 | #!/usr/bin/env python
'''
example program that dumps a Mavlink log file. The log file is
assumed to be in the format that qgroundcontrol uses, which consists
of a series of MAVLink packets, each with a 64 bit timestamp
header. The timestamp is in microseconds since 1970 (unix epoch)
'''
import sys, time, os, struct
from optparse import OptionParser
parser = OptionParser("mavlogdump.py [options]")
parser.add_option("--no-timestamps",dest="notimestamps", action='store_true', help="Log doesn't have timestamps")
parser.add_option("--planner",dest="planner", action='store_true', help="use planner file format")
parser.add_option("--robust",dest="robust", action='store_true', help="Enable robust parsing (skip over bad data)")
parser.add_option("-f", "--follow",dest="follow", action='store_true', help="keep waiting for more data at end of file")
parser.add_option("--condition",dest="condition", default=None, help="select packets by condition")
parser.add_option("-q", "--quiet", dest="quiet", action='store_true', help="don't display packets")
parser.add_option("-o", "--output", default=None, help="output matching packets to give file")
parser.add_option("-p", "--parms", action='store_true', help="preserve parameters in output with -o")
parser.add_option("--types", default=None, help="types of messages (comma separated)")
parser.add_option("--dialect", default="ardupilotmega", help="MAVLink dialect")
parser.add_option("--zero-time-base", action='store_true', help="use Z time base for DF logs")
(opts, args) = parser.parse_args()
from pymavlink import mavutil
if len(args) < 1:
print("Usage: mavlogdump.py [options] <LOGFILE>")
sys.exit(1)
filename = args[0]
mlog = mavutil.mavlink_connection(filename, planner_format=opts.planner,
notimestamps=opts.notimestamps,
robust_parsing=opts.robust,
dialect=opts.dialect,
zero_time_base=opts.zero_time_base)
output = None
if opts.output:
output = open(opts.output, mode='wb')
types = opts.types
if types is not None:
types = types.split(',')
ext = os.path.splitext(filename)[1]
isbin = ext in ['.bin', '.BIN']
islog = ext in ['.log', '.LOG']
while True:
m = mlog.recv_match(blocking=opts.follow)
if m is None:
break
if output is not None:
if (isbin or islog) and m.get_type() == "FMT":
output.write(m.get_msgbuf())
continue
if (isbin or islog) and (m.get_type() == "PARM" and opts.parms):
output.write(m.get_msgbuf())
continue
if m.get_type() == 'PARAM_VALUE' and opts.parms:
timestamp = getattr(m, '_timestamp', None)
output.write(struct.pack('>Q', timestamp*1.0e6) + m.get_msgbuf())
continue
if not mavutil.evaluate_condition(opts.condition, mlog.messages):
continue
if types is not None and m.get_type() not in types:
continue
last_timestamp = 0
if output and m.get_type() != 'BAD_DATA':
timestamp = getattr(m, '_timestamp', None)
if not timestamp:
timestamp = last_timestamp
last_timestamp = timestamp
if not (isbin or islog):
output.write(struct.pack('>Q', timestamp*1.0e6))
output.write(m.get_msgbuf())
if opts.quiet:
continue
print("%s.%02u: %s" % (
time.strftime("%Y-%m-%d %H:%M:%S",
time.localtime(m._timestamp)),
int(m._timestamp*1000.0)%1000, m))
|
rfhk/awo-custom | refs/heads/8.0 | partner_statement_report/__openerp__.py | 1 | # -*- coding: utf-8 -*-
# Copyright 2017-2018 Quartile Limited
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
'name': 'Partner Statement Report',
'version': '8.0.2.1.0',
'author': 'Quartile Limited',
'website': 'https://www.quartile.co',
'category': 'Report',
'depends': [
'account_financial_report_webkit',
'account_financial_report_webkit_xls',
],
'description': """
""",
'data': [
'views/account_config_settings_views.xml',
'wizards/partner_statement_report_wizard_view.xml',
],
'post_init_hook': '_update_account_move_line',
'installable': True,
}
|
devs1991/test_edx_docmode | refs/heads/master | venv/lib/python2.7/site-packages/celery/app/builtins.py | 5 | # -*- coding: utf-8 -*-
"""
celery.app.builtins
~~~~~~~~~~~~~~~~~~~
Built-in tasks that are always available in all
app instances. E.g. chord, group and xmap.
"""
from __future__ import absolute_import
from collections import deque
from celery._state import get_current_worker_task, connect_on_app_finalize
from celery.utils import uuid
from celery.utils.log import get_logger
__all__ = []
logger = get_logger(__name__)
@connect_on_app_finalize
def add_backend_cleanup_task(app):
"""The backend cleanup task can be used to clean up the default result
backend.
If the configured backend requires periodic cleanup this task is also
automatically configured to run every day at midnight (requires
:program:`celery beat` to be running).
"""
@app.task(name='celery.backend_cleanup',
shared=False, _force_evaluate=True)
def backend_cleanup():
app.backend.cleanup()
return backend_cleanup
@connect_on_app_finalize
def add_unlock_chord_task(app):
"""This task is used by result backends without native chord support.
It joins chords by creating a task chain polling the header for completion.
"""
from celery.canvas import signature
from celery.exceptions import ChordError
from celery.result import allow_join_result, result_from_tuple
default_propagate = app.conf.CELERY_CHORD_PROPAGATES
@app.task(name='celery.chord_unlock', max_retries=None, shared=False,
default_retry_delay=1, ignore_result=True, _force_evaluate=True,
bind=True)
def unlock_chord(self, group_id, callback, interval=None, propagate=None,
max_retries=None, result=None,
Result=app.AsyncResult, GroupResult=app.GroupResult,
result_from_tuple=result_from_tuple):
# if propagate is disabled exceptions raised by chord tasks
# will be sent as part of the result list to the chord callback.
# Since 3.1 propagate will be enabled by default, and instead
# the chord callback changes state to FAILURE with the
# exception set to ChordError.
propagate = default_propagate if propagate is None else propagate
if interval is None:
interval = self.default_retry_delay
# check if the task group is ready, and if so apply the callback.
deps = GroupResult(
group_id,
[result_from_tuple(r, app=app) for r in result],
app=app,
)
j = deps.join_native if deps.supports_native_join else deps.join
try:
ready = deps.ready()
except Exception as exc:
raise self.retry(
exc=exc, countdown=interval, max_retries=max_retries,
)
else:
if not ready:
raise self.retry(countdown=interval, max_retries=max_retries)
callback = signature(callback, app=app)
try:
with allow_join_result():
ret = j(timeout=3.0, propagate=propagate)
except Exception as exc:
try:
culprit = next(deps._failed_join_report())
reason = 'Dependency {0.id} raised {1!r}'.format(
culprit, exc,
)
except StopIteration:
reason = repr(exc)
logger.error('Chord %r raised: %r', group_id, exc, exc_info=1)
app.backend.chord_error_from_stack(callback,
ChordError(reason))
else:
try:
callback.delay(ret)
except Exception as exc:
logger.error('Chord %r raised: %r', group_id, exc, exc_info=1)
app.backend.chord_error_from_stack(
callback,
exc=ChordError('Callback error: {0!r}'.format(exc)),
)
return unlock_chord
@connect_on_app_finalize
def add_map_task(app):
from celery.canvas import signature
@app.task(name='celery.map', shared=False, _force_evaluate=True)
def xmap(task, it):
task = signature(task, app=app).type
return [task(item) for item in it]
return xmap
@connect_on_app_finalize
def add_starmap_task(app):
from celery.canvas import signature
@app.task(name='celery.starmap', shared=False, _force_evaluate=True)
def xstarmap(task, it):
task = signature(task, app=app).type
return [task(*item) for item in it]
return xstarmap
@connect_on_app_finalize
def add_chunk_task(app):
from celery.canvas import chunks as _chunks
@app.task(name='celery.chunks', shared=False, _force_evaluate=True)
def chunks(task, it, n):
return _chunks.apply_chunks(task, it, n)
return chunks
@connect_on_app_finalize
def add_group_task(app):
_app = app
from celery.canvas import maybe_signature, signature
from celery.result import result_from_tuple
class Group(app.Task):
app = _app
name = 'celery.group'
accept_magic_kwargs = False
_decorated = True
def run(self, tasks, result, group_id, partial_args,
add_to_parent=True):
app = self.app
result = result_from_tuple(result, app)
# any partial args are added to all tasks in the group
taskit = (signature(task, app=app).clone(partial_args)
for i, task in enumerate(tasks))
if self.request.is_eager or app.conf.CELERY_ALWAYS_EAGER:
return app.GroupResult(
result.id,
[stask.apply(group_id=group_id) for stask in taskit],
)
with app.producer_or_acquire() as pub:
[stask.apply_async(group_id=group_id, producer=pub,
add_to_parent=False) for stask in taskit]
parent = get_current_worker_task()
if add_to_parent and parent:
parent.add_trail(result)
return result
def prepare(self, options, tasks, args, **kwargs):
options['group_id'] = group_id = (
options.setdefault('task_id', uuid()))
def prepare_member(task):
task = maybe_signature(task, app=self.app)
task.options['group_id'] = group_id
return task, task.freeze()
try:
tasks, res = list(zip(
*[prepare_member(task) for task in tasks]
))
except ValueError: # tasks empty
tasks, res = [], []
return (tasks, self.app.GroupResult(group_id, res), group_id, args)
def apply_async(self, partial_args=(), kwargs={}, **options):
if self.app.conf.CELERY_ALWAYS_EAGER:
return self.apply(partial_args, kwargs, **options)
tasks, result, gid, args = self.prepare(
options, args=partial_args, **kwargs
)
super(Group, self).apply_async((
list(tasks), result.as_tuple(), gid, args), **options
)
return result
def apply(self, args=(), kwargs={}, **options):
return super(Group, self).apply(
self.prepare(options, args=args, **kwargs),
**options).get()
return Group
@connect_on_app_finalize
def add_chain_task(app):
from celery.canvas import (
Signature, chain, chord, group, maybe_signature, maybe_unroll_group,
)
_app = app
class Chain(app.Task):
app = _app
name = 'celery.chain'
accept_magic_kwargs = False
_decorated = True
def prepare_steps(self, args, tasks):
app = self.app
steps = deque(tasks)
next_step = prev_task = prev_res = None
tasks, results = [], []
i = 0
while steps:
# First task get partial args from chain.
task = maybe_signature(steps.popleft(), app=app)
task = task.clone() if i else task.clone(args)
res = task.freeze()
i += 1
if isinstance(task, group):
task = maybe_unroll_group(task)
if isinstance(task, chain):
# splice the chain
steps.extendleft(reversed(task.tasks))
continue
elif isinstance(task, group) and steps and \
not isinstance(steps[0], group):
# automatically upgrade group(..) | s to chord(group, s)
try:
next_step = steps.popleft()
# for chords we freeze by pretending it's a normal
# task instead of a group.
res = Signature.freeze(next_step)
task = chord(task, body=next_step, task_id=res.task_id)
except IndexError:
pass # no callback, so keep as group
if prev_task:
# link previous task to this task.
prev_task.link(task)
# set the results parent attribute.
if not res.parent:
res.parent = prev_res
if not isinstance(prev_task, chord):
results.append(res)
tasks.append(task)
prev_task, prev_res = task, res
return tasks, results
def apply_async(self, args=(), kwargs={}, group_id=None, chord=None,
task_id=None, link=None, link_error=None, **options):
if self.app.conf.CELERY_ALWAYS_EAGER:
return self.apply(args, kwargs, **options)
options.pop('publisher', None)
tasks, results = self.prepare_steps(args, kwargs['tasks'])
result = results[-1]
if group_id:
tasks[-1].set(group_id=group_id)
if chord:
tasks[-1].set(chord=chord)
if task_id:
tasks[-1].set(task_id=task_id)
result = tasks[-1].type.AsyncResult(task_id)
# make sure we can do a link() and link_error() on a chain object.
if link:
tasks[-1].set(link=link)
# and if any task in the chain fails, call the errbacks
if link_error:
for task in tasks:
task.set(link_error=link_error)
tasks[0].apply_async(**options)
return result
def apply(self, args=(), kwargs={}, signature=maybe_signature,
**options):
app = self.app
last, fargs = None, args # fargs passed to first task only
for task in kwargs['tasks']:
res = signature(task, app=app).clone(fargs).apply(
last and (last.get(), ),
)
res.parent, last, fargs = last, res, None
return last
return Chain
@connect_on_app_finalize
def add_chord_task(app):
"""Every chord is executed in a dedicated task, so that the chord
can be used as a signature, and this generates the task
responsible for that."""
from celery import group
from celery.canvas import maybe_signature
_app = app
default_propagate = app.conf.CELERY_CHORD_PROPAGATES
class Chord(app.Task):
app = _app
name = 'celery.chord'
accept_magic_kwargs = False
ignore_result = False
_decorated = True
def run(self, header, body, partial_args=(), interval=None,
countdown=1, max_retries=None, propagate=None,
eager=False, **kwargs):
app = self.app
propagate = default_propagate if propagate is None else propagate
group_id = uuid()
# - convert back to group if serialized
tasks = header.tasks if isinstance(header, group) else header
header = group([
maybe_signature(s, app=app).clone() for s in tasks
], app=self.app)
# - eager applies the group inline
if eager:
return header.apply(args=partial_args, task_id=group_id)
body['chord_size'] = len(header.tasks)
results = header.freeze(group_id=group_id, chord=body).results
return self.backend.apply_chord(
header, partial_args, group_id,
body, interval=interval, countdown=countdown,
max_retries=max_retries, propagate=propagate, result=results,
)
def apply_async(self, args=(), kwargs={}, task_id=None,
group_id=None, chord=None, **options):
app = self.app
if app.conf.CELERY_ALWAYS_EAGER:
return self.apply(args, kwargs, **options)
header = kwargs.pop('header')
body = kwargs.pop('body')
header, body = (maybe_signature(header, app=app),
maybe_signature(body, app=app))
# forward certain options to body
if chord is not None:
body.options['chord'] = chord
if group_id is not None:
body.options['group_id'] = group_id
[body.link(s) for s in options.pop('link', [])]
[body.link_error(s) for s in options.pop('link_error', [])]
body_result = body.freeze(task_id)
parent = super(Chord, self).apply_async((header, body, args),
kwargs, **options)
body_result.parent = parent
return body_result
def apply(self, args=(), kwargs={}, propagate=True, **options):
body = kwargs['body']
res = super(Chord, self).apply(args, dict(kwargs, eager=True),
**options)
return maybe_signature(body, app=self.app).apply(
args=(res.get(propagate=propagate).get(), ))
return Chord
|
mlperf/training_results_v0.7 | refs/heads/master | Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/tvm/tests/python/unittest/test_lang_verify_compute.py | 2 | # 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 tvm
def test_verify_compute():
n = tvm.var("n")
m = tvm.var("m")
A = tvm.placeholder((n, m), name='A')
k = tvm.reduce_axis((0, m), "k")
k_ = tvm.reduce_axis((0, m-1), "k_")
f1 = lambda i: tvm.sum(A[i, k], axis=k)
f2 = lambda i: A[i,0] + 1
f3 = lambda i: tvm.sum(A[i, k], axis=k) + 1
f4 = lambda i: A[i,0] * (tvm.sum(A[i, k], axis=k) + 1)
f5 = lambda i: (tvm.sum(A[i, k], axis=k), A[i,0] + 1)
f6 = lambda i: (tvm.sum(A[i, k], axis=k), tvm.sum(A[i, k_], axis=k_))
#
# Valid compute
try:
B = tvm.compute((n,), f1, name="B")
except tvm._ffi.base.TVMError as ex:
assert False
#
# Valid compute
try:
B = tvm.compute((n,), f2, name="B")
except tvm._ffi.base.TVMError as ex:
assert False
#
# Invalid compute with non top level reduction
try:
B = tvm.compute((n,), f3, name="B")
assert False
except tvm._ffi.base.TVMError as ex:
pass
#
# Invalid compute with non top level reduction
try:
B = tvm.compute((n,), f4, name="B")
assert False
except tvm._ffi.base.TVMError as ex:
pass
#
# Invalid compute with reduction and non-reduction batch ops
try:
B0, B1 = tvm.compute((n,), f5, name="B")
assert False
except tvm._ffi.base.TVMError as ex:
pass
#
# Invalid compute with unequal batch reduction ops
try:
B0, B1 = tvm.compute((n,), f6, name="B")
assert False
except tvm._ffi.base.TVMError as ex:
pass
if __name__ == "__main__":
test_verify_compute()
|
goldenbull/grpc | refs/heads/master | src/python/grpcio/grpc_core_dependencies.py | 1 | # Copyright 2015, 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.
# AUTO-GENERATED FROM `$REPO_ROOT/templates/src/python/grpcio/grpc_core_dependencies.py.template`!!!
CORE_SOURCE_FILES = [
'src/core/lib/profiling/basic_timers.c',
'src/core/lib/profiling/stap_timers.c',
'src/core/lib/support/alloc.c',
'src/core/lib/support/avl.c',
'src/core/lib/support/backoff.c',
'src/core/lib/support/cmdline.c',
'src/core/lib/support/cpu_iphone.c',
'src/core/lib/support/cpu_linux.c',
'src/core/lib/support/cpu_posix.c',
'src/core/lib/support/cpu_windows.c',
'src/core/lib/support/env_linux.c',
'src/core/lib/support/env_posix.c',
'src/core/lib/support/env_win32.c',
'src/core/lib/support/histogram.c',
'src/core/lib/support/host_port.c',
'src/core/lib/support/load_file.c',
'src/core/lib/support/log.c',
'src/core/lib/support/log_android.c',
'src/core/lib/support/log_linux.c',
'src/core/lib/support/log_posix.c',
'src/core/lib/support/log_win32.c',
'src/core/lib/support/murmur_hash.c',
'src/core/lib/support/slice.c',
'src/core/lib/support/slice_buffer.c',
'src/core/lib/support/stack_lockfree.c',
'src/core/lib/support/string.c',
'src/core/lib/support/string_posix.c',
'src/core/lib/support/string_util_win32.c',
'src/core/lib/support/string_win32.c',
'src/core/lib/support/subprocess_posix.c',
'src/core/lib/support/subprocess_windows.c',
'src/core/lib/support/sync.c',
'src/core/lib/support/sync_posix.c',
'src/core/lib/support/sync_win32.c',
'src/core/lib/support/thd.c',
'src/core/lib/support/thd_posix.c',
'src/core/lib/support/thd_win32.c',
'src/core/lib/support/time.c',
'src/core/lib/support/time_posix.c',
'src/core/lib/support/time_precise.c',
'src/core/lib/support/time_win32.c',
'src/core/lib/support/tls_pthread.c',
'src/core/lib/support/tmpfile_msys.c',
'src/core/lib/support/tmpfile_posix.c',
'src/core/lib/support/tmpfile_win32.c',
'src/core/lib/support/wrap_memcpy.c',
'src/core/lib/surface/init.c',
'src/core/lib/channel/channel_args.c',
'src/core/lib/channel/channel_stack.c',
'src/core/lib/channel/channel_stack_builder.c',
'src/core/lib/channel/compress_filter.c',
'src/core/lib/channel/connected_channel.c',
'src/core/lib/channel/http_client_filter.c',
'src/core/lib/channel/http_server_filter.c',
'src/core/lib/compression/compression_algorithm.c',
'src/core/lib/compression/message_compress.c',
'src/core/lib/debug/trace.c',
'src/core/lib/http/format_request.c',
'src/core/lib/http/httpcli.c',
'src/core/lib/http/parser.c',
'src/core/lib/iomgr/closure.c',
'src/core/lib/iomgr/endpoint.c',
'src/core/lib/iomgr/endpoint_pair_posix.c',
'src/core/lib/iomgr/endpoint_pair_windows.c',
'src/core/lib/iomgr/ev_poll_and_epoll_posix.c',
'src/core/lib/iomgr/ev_posix.c',
'src/core/lib/iomgr/exec_ctx.c',
'src/core/lib/iomgr/executor.c',
'src/core/lib/iomgr/iocp_windows.c',
'src/core/lib/iomgr/iomgr.c',
'src/core/lib/iomgr/iomgr_posix.c',
'src/core/lib/iomgr/iomgr_windows.c',
'src/core/lib/iomgr/pollset_set_windows.c',
'src/core/lib/iomgr/pollset_windows.c',
'src/core/lib/iomgr/resolve_address_posix.c',
'src/core/lib/iomgr/resolve_address_windows.c',
'src/core/lib/iomgr/sockaddr_utils.c',
'src/core/lib/iomgr/socket_utils_common_posix.c',
'src/core/lib/iomgr/socket_utils_linux.c',
'src/core/lib/iomgr/socket_utils_posix.c',
'src/core/lib/iomgr/socket_windows.c',
'src/core/lib/iomgr/tcp_client_posix.c',
'src/core/lib/iomgr/tcp_client_windows.c',
'src/core/lib/iomgr/tcp_posix.c',
'src/core/lib/iomgr/tcp_server_posix.c',
'src/core/lib/iomgr/tcp_server_windows.c',
'src/core/lib/iomgr/tcp_windows.c',
'src/core/lib/iomgr/time_averaged_stats.c',
'src/core/lib/iomgr/timer.c',
'src/core/lib/iomgr/timer_heap.c',
'src/core/lib/iomgr/udp_server.c',
'src/core/lib/iomgr/unix_sockets_posix.c',
'src/core/lib/iomgr/unix_sockets_posix_noop.c',
'src/core/lib/iomgr/wakeup_fd_eventfd.c',
'src/core/lib/iomgr/wakeup_fd_nospecial.c',
'src/core/lib/iomgr/wakeup_fd_pipe.c',
'src/core/lib/iomgr/wakeup_fd_posix.c',
'src/core/lib/iomgr/workqueue_posix.c',
'src/core/lib/iomgr/workqueue_windows.c',
'src/core/lib/json/json.c',
'src/core/lib/json/json_reader.c',
'src/core/lib/json/json_string.c',
'src/core/lib/json/json_writer.c',
'src/core/lib/surface/alarm.c',
'src/core/lib/surface/api_trace.c',
'src/core/lib/surface/byte_buffer.c',
'src/core/lib/surface/byte_buffer_reader.c',
'src/core/lib/surface/call.c',
'src/core/lib/surface/call_details.c',
'src/core/lib/surface/call_log_batch.c',
'src/core/lib/surface/channel.c',
'src/core/lib/surface/channel_init.c',
'src/core/lib/surface/channel_ping.c',
'src/core/lib/surface/channel_stack_type.c',
'src/core/lib/surface/completion_queue.c',
'src/core/lib/surface/event_string.c',
'src/core/lib/surface/lame_client.c',
'src/core/lib/surface/metadata_array.c',
'src/core/lib/surface/server.c',
'src/core/lib/surface/validate_metadata.c',
'src/core/lib/surface/version.c',
'src/core/lib/transport/byte_stream.c',
'src/core/lib/transport/connectivity_state.c',
'src/core/lib/transport/metadata.c',
'src/core/lib/transport/metadata_batch.c',
'src/core/lib/transport/static_metadata.c',
'src/core/lib/transport/transport.c',
'src/core/lib/transport/transport_op_string.c',
'src/core/ext/transport/chttp2/server/secure/server_secure_chttp2.c',
'src/core/ext/transport/chttp2/transport/bin_encoder.c',
'src/core/ext/transport/chttp2/transport/chttp2_plugin.c',
'src/core/ext/transport/chttp2/transport/chttp2_transport.c',
'src/core/ext/transport/chttp2/transport/frame_data.c',
'src/core/ext/transport/chttp2/transport/frame_goaway.c',
'src/core/ext/transport/chttp2/transport/frame_ping.c',
'src/core/ext/transport/chttp2/transport/frame_rst_stream.c',
'src/core/ext/transport/chttp2/transport/frame_settings.c',
'src/core/ext/transport/chttp2/transport/frame_window_update.c',
'src/core/ext/transport/chttp2/transport/hpack_encoder.c',
'src/core/ext/transport/chttp2/transport/hpack_parser.c',
'src/core/ext/transport/chttp2/transport/hpack_table.c',
'src/core/ext/transport/chttp2/transport/huffsyms.c',
'src/core/ext/transport/chttp2/transport/incoming_metadata.c',
'src/core/ext/transport/chttp2/transport/parsing.c',
'src/core/ext/transport/chttp2/transport/status_conversion.c',
'src/core/ext/transport/chttp2/transport/stream_lists.c',
'src/core/ext/transport/chttp2/transport/stream_map.c',
'src/core/ext/transport/chttp2/transport/timeout_encoding.c',
'src/core/ext/transport/chttp2/transport/varint.c',
'src/core/ext/transport/chttp2/transport/writing.c',
'src/core/ext/transport/chttp2/alpn/alpn.c',
'src/core/lib/http/httpcli_security_connector.c',
'src/core/lib/security/b64.c',
'src/core/lib/security/client_auth_filter.c',
'src/core/lib/security/credentials.c',
'src/core/lib/security/credentials_metadata.c',
'src/core/lib/security/credentials_posix.c',
'src/core/lib/security/credentials_win32.c',
'src/core/lib/security/google_default_credentials.c',
'src/core/lib/security/handshake.c',
'src/core/lib/security/json_token.c',
'src/core/lib/security/jwt_verifier.c',
'src/core/lib/security/secure_endpoint.c',
'src/core/lib/security/security_connector.c',
'src/core/lib/security/security_context.c',
'src/core/lib/security/server_auth_filter.c',
'src/core/lib/surface/init_secure.c',
'src/core/lib/tsi/fake_transport_security.c',
'src/core/lib/tsi/ssl_transport_security.c',
'src/core/lib/tsi/transport_security.c',
'src/core/ext/transport/chttp2/client/secure/secure_channel_create.c',
'src/core/ext/client_config/channel_connectivity.c',
'src/core/ext/client_config/client_channel.c',
'src/core/ext/client_config/client_channel_factory.c',
'src/core/ext/client_config/client_config.c',
'src/core/ext/client_config/client_config_plugin.c',
'src/core/ext/client_config/connector.c',
'src/core/ext/client_config/default_initial_connect_string.c',
'src/core/ext/client_config/initial_connect_string.c',
'src/core/ext/client_config/lb_policy.c',
'src/core/ext/client_config/lb_policy_factory.c',
'src/core/ext/client_config/lb_policy_registry.c',
'src/core/ext/client_config/parse_address.c',
'src/core/ext/client_config/resolver.c',
'src/core/ext/client_config/resolver_factory.c',
'src/core/ext/client_config/resolver_registry.c',
'src/core/ext/client_config/subchannel.c',
'src/core/ext/client_config/subchannel_call_holder.c',
'src/core/ext/client_config/subchannel_index.c',
'src/core/ext/client_config/uri_parser.c',
'src/core/ext/transport/chttp2/server/insecure/server_chttp2.c',
'src/core/ext/transport/chttp2/client/insecure/channel_create.c',
'src/core/ext/lb_policy/grpclb/load_balancer_api.c',
'src/core/ext/lb_policy/grpclb/proto/grpc/lb/v1/load_balancer.pb.c',
'third_party/nanopb/pb_common.c',
'third_party/nanopb/pb_decode.c',
'third_party/nanopb/pb_encode.c',
'src/core/ext/lb_policy/pick_first/pick_first.c',
'src/core/ext/lb_policy/round_robin/round_robin.c',
'src/core/ext/resolver/dns/native/dns_resolver.c',
'src/core/ext/resolver/sockaddr/sockaddr_resolver.c',
'src/core/ext/census/context.c',
'src/core/ext/census/grpc_context.c',
'src/core/ext/census/grpc_filter.c',
'src/core/ext/census/grpc_plugin.c',
'src/core/ext/census/initialize.c',
'src/core/ext/census/mlog.c',
'src/core/ext/census/operation.c',
'src/core/ext/census/placeholders.c',
'src/core/ext/census/tracing.c',
'src/core/plugin_registry/grpc_plugin_registry.c',
'src/boringssl/err_data.c',
'third_party/boringssl/crypto/aes/aes.c',
'third_party/boringssl/crypto/aes/mode_wrappers.c',
'third_party/boringssl/crypto/asn1/a_bitstr.c',
'third_party/boringssl/crypto/asn1/a_bool.c',
'third_party/boringssl/crypto/asn1/a_bytes.c',
'third_party/boringssl/crypto/asn1/a_d2i_fp.c',
'third_party/boringssl/crypto/asn1/a_dup.c',
'third_party/boringssl/crypto/asn1/a_enum.c',
'third_party/boringssl/crypto/asn1/a_gentm.c',
'third_party/boringssl/crypto/asn1/a_i2d_fp.c',
'third_party/boringssl/crypto/asn1/a_int.c',
'third_party/boringssl/crypto/asn1/a_mbstr.c',
'third_party/boringssl/crypto/asn1/a_object.c',
'third_party/boringssl/crypto/asn1/a_octet.c',
'third_party/boringssl/crypto/asn1/a_print.c',
'third_party/boringssl/crypto/asn1/a_strnid.c',
'third_party/boringssl/crypto/asn1/a_time.c',
'third_party/boringssl/crypto/asn1/a_type.c',
'third_party/boringssl/crypto/asn1/a_utctm.c',
'third_party/boringssl/crypto/asn1/a_utf8.c',
'third_party/boringssl/crypto/asn1/asn1_lib.c',
'third_party/boringssl/crypto/asn1/asn1_par.c',
'third_party/boringssl/crypto/asn1/asn_pack.c',
'third_party/boringssl/crypto/asn1/bio_asn1.c',
'third_party/boringssl/crypto/asn1/bio_ndef.c',
'third_party/boringssl/crypto/asn1/f_enum.c',
'third_party/boringssl/crypto/asn1/f_int.c',
'third_party/boringssl/crypto/asn1/f_string.c',
'third_party/boringssl/crypto/asn1/t_bitst.c',
'third_party/boringssl/crypto/asn1/t_pkey.c',
'third_party/boringssl/crypto/asn1/tasn_dec.c',
'third_party/boringssl/crypto/asn1/tasn_enc.c',
'third_party/boringssl/crypto/asn1/tasn_fre.c',
'third_party/boringssl/crypto/asn1/tasn_new.c',
'third_party/boringssl/crypto/asn1/tasn_prn.c',
'third_party/boringssl/crypto/asn1/tasn_typ.c',
'third_party/boringssl/crypto/asn1/tasn_utl.c',
'third_party/boringssl/crypto/asn1/x_bignum.c',
'third_party/boringssl/crypto/asn1/x_long.c',
'third_party/boringssl/crypto/base64/base64.c',
'third_party/boringssl/crypto/bio/bio.c',
'third_party/boringssl/crypto/bio/bio_mem.c',
'third_party/boringssl/crypto/bio/buffer.c',
'third_party/boringssl/crypto/bio/connect.c',
'third_party/boringssl/crypto/bio/fd.c',
'third_party/boringssl/crypto/bio/file.c',
'third_party/boringssl/crypto/bio/hexdump.c',
'third_party/boringssl/crypto/bio/pair.c',
'third_party/boringssl/crypto/bio/printf.c',
'third_party/boringssl/crypto/bio/socket.c',
'third_party/boringssl/crypto/bio/socket_helper.c',
'third_party/boringssl/crypto/bn/add.c',
'third_party/boringssl/crypto/bn/asm/x86_64-gcc.c',
'third_party/boringssl/crypto/bn/bn.c',
'third_party/boringssl/crypto/bn/bn_asn1.c',
'third_party/boringssl/crypto/bn/cmp.c',
'third_party/boringssl/crypto/bn/convert.c',
'third_party/boringssl/crypto/bn/ctx.c',
'third_party/boringssl/crypto/bn/div.c',
'third_party/boringssl/crypto/bn/exponentiation.c',
'third_party/boringssl/crypto/bn/gcd.c',
'third_party/boringssl/crypto/bn/generic.c',
'third_party/boringssl/crypto/bn/kronecker.c',
'third_party/boringssl/crypto/bn/montgomery.c',
'third_party/boringssl/crypto/bn/mul.c',
'third_party/boringssl/crypto/bn/prime.c',
'third_party/boringssl/crypto/bn/random.c',
'third_party/boringssl/crypto/bn/rsaz_exp.c',
'third_party/boringssl/crypto/bn/shift.c',
'third_party/boringssl/crypto/bn/sqrt.c',
'third_party/boringssl/crypto/buf/buf.c',
'third_party/boringssl/crypto/bytestring/asn1_compat.c',
'third_party/boringssl/crypto/bytestring/ber.c',
'third_party/boringssl/crypto/bytestring/cbb.c',
'third_party/boringssl/crypto/bytestring/cbs.c',
'third_party/boringssl/crypto/chacha/chacha_generic.c',
'third_party/boringssl/crypto/chacha/chacha_vec.c',
'third_party/boringssl/crypto/cipher/aead.c',
'third_party/boringssl/crypto/cipher/cipher.c',
'third_party/boringssl/crypto/cipher/derive_key.c',
'third_party/boringssl/crypto/cipher/e_aes.c',
'third_party/boringssl/crypto/cipher/e_chacha20poly1305.c',
'third_party/boringssl/crypto/cipher/e_des.c',
'third_party/boringssl/crypto/cipher/e_null.c',
'third_party/boringssl/crypto/cipher/e_rc2.c',
'third_party/boringssl/crypto/cipher/e_rc4.c',
'third_party/boringssl/crypto/cipher/e_ssl3.c',
'third_party/boringssl/crypto/cipher/e_tls.c',
'third_party/boringssl/crypto/cipher/tls_cbc.c',
'third_party/boringssl/crypto/cmac/cmac.c',
'third_party/boringssl/crypto/conf/conf.c',
'third_party/boringssl/crypto/cpu-arm.c',
'third_party/boringssl/crypto/cpu-intel.c',
'third_party/boringssl/crypto/crypto.c',
'third_party/boringssl/crypto/curve25519/curve25519.c',
'third_party/boringssl/crypto/curve25519/x25519-x86_64.c',
'third_party/boringssl/crypto/des/des.c',
'third_party/boringssl/crypto/dh/check.c',
'third_party/boringssl/crypto/dh/dh.c',
'third_party/boringssl/crypto/dh/dh_asn1.c',
'third_party/boringssl/crypto/dh/params.c',
'third_party/boringssl/crypto/digest/digest.c',
'third_party/boringssl/crypto/digest/digests.c',
'third_party/boringssl/crypto/directory_posix.c',
'third_party/boringssl/crypto/directory_win.c',
'third_party/boringssl/crypto/dsa/dsa.c',
'third_party/boringssl/crypto/dsa/dsa_asn1.c',
'third_party/boringssl/crypto/ec/ec.c',
'third_party/boringssl/crypto/ec/ec_asn1.c',
'third_party/boringssl/crypto/ec/ec_key.c',
'third_party/boringssl/crypto/ec/ec_montgomery.c',
'third_party/boringssl/crypto/ec/oct.c',
'third_party/boringssl/crypto/ec/p224-64.c',
'third_party/boringssl/crypto/ec/p256-64.c',
'third_party/boringssl/crypto/ec/p256-x86_64.c',
'third_party/boringssl/crypto/ec/simple.c',
'third_party/boringssl/crypto/ec/util-64.c',
'third_party/boringssl/crypto/ec/wnaf.c',
'third_party/boringssl/crypto/ecdh/ecdh.c',
'third_party/boringssl/crypto/ecdsa/ecdsa.c',
'third_party/boringssl/crypto/ecdsa/ecdsa_asn1.c',
'third_party/boringssl/crypto/engine/engine.c',
'third_party/boringssl/crypto/err/err.c',
'third_party/boringssl/crypto/evp/algorithm.c',
'third_party/boringssl/crypto/evp/digestsign.c',
'third_party/boringssl/crypto/evp/evp.c',
'third_party/boringssl/crypto/evp/evp_asn1.c',
'third_party/boringssl/crypto/evp/evp_ctx.c',
'third_party/boringssl/crypto/evp/p_dsa_asn1.c',
'third_party/boringssl/crypto/evp/p_ec.c',
'third_party/boringssl/crypto/evp/p_ec_asn1.c',
'third_party/boringssl/crypto/evp/p_rsa.c',
'third_party/boringssl/crypto/evp/p_rsa_asn1.c',
'third_party/boringssl/crypto/evp/pbkdf.c',
'third_party/boringssl/crypto/evp/sign.c',
'third_party/boringssl/crypto/ex_data.c',
'third_party/boringssl/crypto/hkdf/hkdf.c',
'third_party/boringssl/crypto/hmac/hmac.c',
'third_party/boringssl/crypto/lhash/lhash.c',
'third_party/boringssl/crypto/md4/md4.c',
'third_party/boringssl/crypto/md5/md5.c',
'third_party/boringssl/crypto/mem.c',
'third_party/boringssl/crypto/modes/cbc.c',
'third_party/boringssl/crypto/modes/cfb.c',
'third_party/boringssl/crypto/modes/ctr.c',
'third_party/boringssl/crypto/modes/gcm.c',
'third_party/boringssl/crypto/modes/ofb.c',
'third_party/boringssl/crypto/obj/obj.c',
'third_party/boringssl/crypto/obj/obj_xref.c',
'third_party/boringssl/crypto/pem/pem_all.c',
'third_party/boringssl/crypto/pem/pem_info.c',
'third_party/boringssl/crypto/pem/pem_lib.c',
'third_party/boringssl/crypto/pem/pem_oth.c',
'third_party/boringssl/crypto/pem/pem_pk8.c',
'third_party/boringssl/crypto/pem/pem_pkey.c',
'third_party/boringssl/crypto/pem/pem_x509.c',
'third_party/boringssl/crypto/pem/pem_xaux.c',
'third_party/boringssl/crypto/pkcs8/p5_pbe.c',
'third_party/boringssl/crypto/pkcs8/p5_pbev2.c',
'third_party/boringssl/crypto/pkcs8/p8_pkey.c',
'third_party/boringssl/crypto/pkcs8/pkcs8.c',
'third_party/boringssl/crypto/poly1305/poly1305.c',
'third_party/boringssl/crypto/poly1305/poly1305_arm.c',
'third_party/boringssl/crypto/poly1305/poly1305_vec.c',
'third_party/boringssl/crypto/rand/rand.c',
'third_party/boringssl/crypto/rand/urandom.c',
'third_party/boringssl/crypto/rand/windows.c',
'third_party/boringssl/crypto/rc4/rc4.c',
'third_party/boringssl/crypto/refcount_c11.c',
'third_party/boringssl/crypto/refcount_lock.c',
'third_party/boringssl/crypto/rsa/blinding.c',
'third_party/boringssl/crypto/rsa/padding.c',
'third_party/boringssl/crypto/rsa/rsa.c',
'third_party/boringssl/crypto/rsa/rsa_asn1.c',
'third_party/boringssl/crypto/rsa/rsa_impl.c',
'third_party/boringssl/crypto/sha/sha1.c',
'third_party/boringssl/crypto/sha/sha256.c',
'third_party/boringssl/crypto/sha/sha512.c',
'third_party/boringssl/crypto/stack/stack.c',
'third_party/boringssl/crypto/thread.c',
'third_party/boringssl/crypto/thread_none.c',
'third_party/boringssl/crypto/thread_pthread.c',
'third_party/boringssl/crypto/thread_win.c',
'third_party/boringssl/crypto/time_support.c',
'third_party/boringssl/crypto/x509/a_digest.c',
'third_party/boringssl/crypto/x509/a_sign.c',
'third_party/boringssl/crypto/x509/a_strex.c',
'third_party/boringssl/crypto/x509/a_verify.c',
'third_party/boringssl/crypto/x509/asn1_gen.c',
'third_party/boringssl/crypto/x509/by_dir.c',
'third_party/boringssl/crypto/x509/by_file.c',
'third_party/boringssl/crypto/x509/i2d_pr.c',
'third_party/boringssl/crypto/x509/pkcs7.c',
'third_party/boringssl/crypto/x509/t_crl.c',
'third_party/boringssl/crypto/x509/t_req.c',
'third_party/boringssl/crypto/x509/t_x509.c',
'third_party/boringssl/crypto/x509/t_x509a.c',
'third_party/boringssl/crypto/x509/x509.c',
'third_party/boringssl/crypto/x509/x509_att.c',
'third_party/boringssl/crypto/x509/x509_cmp.c',
'third_party/boringssl/crypto/x509/x509_d2.c',
'third_party/boringssl/crypto/x509/x509_def.c',
'third_party/boringssl/crypto/x509/x509_ext.c',
'third_party/boringssl/crypto/x509/x509_lu.c',
'third_party/boringssl/crypto/x509/x509_obj.c',
'third_party/boringssl/crypto/x509/x509_r2x.c',
'third_party/boringssl/crypto/x509/x509_req.c',
'third_party/boringssl/crypto/x509/x509_set.c',
'third_party/boringssl/crypto/x509/x509_trs.c',
'third_party/boringssl/crypto/x509/x509_txt.c',
'third_party/boringssl/crypto/x509/x509_v3.c',
'third_party/boringssl/crypto/x509/x509_vfy.c',
'third_party/boringssl/crypto/x509/x509_vpm.c',
'third_party/boringssl/crypto/x509/x509cset.c',
'third_party/boringssl/crypto/x509/x509name.c',
'third_party/boringssl/crypto/x509/x509rset.c',
'third_party/boringssl/crypto/x509/x509spki.c',
'third_party/boringssl/crypto/x509/x509type.c',
'third_party/boringssl/crypto/x509/x_algor.c',
'third_party/boringssl/crypto/x509/x_all.c',
'third_party/boringssl/crypto/x509/x_attrib.c',
'third_party/boringssl/crypto/x509/x_crl.c',
'third_party/boringssl/crypto/x509/x_exten.c',
'third_party/boringssl/crypto/x509/x_info.c',
'third_party/boringssl/crypto/x509/x_name.c',
'third_party/boringssl/crypto/x509/x_pkey.c',
'third_party/boringssl/crypto/x509/x_pubkey.c',
'third_party/boringssl/crypto/x509/x_req.c',
'third_party/boringssl/crypto/x509/x_sig.c',
'third_party/boringssl/crypto/x509/x_spki.c',
'third_party/boringssl/crypto/x509/x_val.c',
'third_party/boringssl/crypto/x509/x_x509.c',
'third_party/boringssl/crypto/x509/x_x509a.c',
'third_party/boringssl/crypto/x509v3/pcy_cache.c',
'third_party/boringssl/crypto/x509v3/pcy_data.c',
'third_party/boringssl/crypto/x509v3/pcy_lib.c',
'third_party/boringssl/crypto/x509v3/pcy_map.c',
'third_party/boringssl/crypto/x509v3/pcy_node.c',
'third_party/boringssl/crypto/x509v3/pcy_tree.c',
'third_party/boringssl/crypto/x509v3/v3_akey.c',
'third_party/boringssl/crypto/x509v3/v3_akeya.c',
'third_party/boringssl/crypto/x509v3/v3_alt.c',
'third_party/boringssl/crypto/x509v3/v3_bcons.c',
'third_party/boringssl/crypto/x509v3/v3_bitst.c',
'third_party/boringssl/crypto/x509v3/v3_conf.c',
'third_party/boringssl/crypto/x509v3/v3_cpols.c',
'third_party/boringssl/crypto/x509v3/v3_crld.c',
'third_party/boringssl/crypto/x509v3/v3_enum.c',
'third_party/boringssl/crypto/x509v3/v3_extku.c',
'third_party/boringssl/crypto/x509v3/v3_genn.c',
'third_party/boringssl/crypto/x509v3/v3_ia5.c',
'third_party/boringssl/crypto/x509v3/v3_info.c',
'third_party/boringssl/crypto/x509v3/v3_int.c',
'third_party/boringssl/crypto/x509v3/v3_lib.c',
'third_party/boringssl/crypto/x509v3/v3_ncons.c',
'third_party/boringssl/crypto/x509v3/v3_pci.c',
'third_party/boringssl/crypto/x509v3/v3_pcia.c',
'third_party/boringssl/crypto/x509v3/v3_pcons.c',
'third_party/boringssl/crypto/x509v3/v3_pku.c',
'third_party/boringssl/crypto/x509v3/v3_pmaps.c',
'third_party/boringssl/crypto/x509v3/v3_prn.c',
'third_party/boringssl/crypto/x509v3/v3_purp.c',
'third_party/boringssl/crypto/x509v3/v3_skey.c',
'third_party/boringssl/crypto/x509v3/v3_sxnet.c',
'third_party/boringssl/crypto/x509v3/v3_utl.c',
'third_party/boringssl/ssl/custom_extensions.c',
'third_party/boringssl/ssl/d1_both.c',
'third_party/boringssl/ssl/d1_clnt.c',
'third_party/boringssl/ssl/d1_lib.c',
'third_party/boringssl/ssl/d1_meth.c',
'third_party/boringssl/ssl/d1_pkt.c',
'third_party/boringssl/ssl/d1_srtp.c',
'third_party/boringssl/ssl/d1_srvr.c',
'third_party/boringssl/ssl/dtls_record.c',
'third_party/boringssl/ssl/pqueue/pqueue.c',
'third_party/boringssl/ssl/s3_both.c',
'third_party/boringssl/ssl/s3_clnt.c',
'third_party/boringssl/ssl/s3_enc.c',
'third_party/boringssl/ssl/s3_lib.c',
'third_party/boringssl/ssl/s3_meth.c',
'third_party/boringssl/ssl/s3_pkt.c',
'third_party/boringssl/ssl/s3_srvr.c',
'third_party/boringssl/ssl/ssl_aead_ctx.c',
'third_party/boringssl/ssl/ssl_asn1.c',
'third_party/boringssl/ssl/ssl_buffer.c',
'third_party/boringssl/ssl/ssl_cert.c',
'third_party/boringssl/ssl/ssl_cipher.c',
'third_party/boringssl/ssl/ssl_ecdh.c',
'third_party/boringssl/ssl/ssl_file.c',
'third_party/boringssl/ssl/ssl_lib.c',
'third_party/boringssl/ssl/ssl_rsa.c',
'third_party/boringssl/ssl/ssl_session.c',
'third_party/boringssl/ssl/ssl_stat.c',
'third_party/boringssl/ssl/t1_enc.c',
'third_party/boringssl/ssl/t1_lib.c',
'third_party/boringssl/ssl/tls_record.c',
'third_party/zlib/adler32.c',
'third_party/zlib/compress.c',
'third_party/zlib/crc32.c',
'third_party/zlib/deflate.c',
'third_party/zlib/gzclose.c',
'third_party/zlib/gzlib.c',
'third_party/zlib/gzread.c',
'third_party/zlib/gzwrite.c',
'third_party/zlib/infback.c',
'third_party/zlib/inffast.c',
'third_party/zlib/inflate.c',
'third_party/zlib/inftrees.c',
'third_party/zlib/trees.c',
'third_party/zlib/uncompr.c',
'third_party/zlib/zutil.c',
]
|
marsleezm/riak_pb | refs/heads/develop | version.py | 3 | # This program is placed into the public domain.
"""
Gets the current version number.
If in a git repository, it is the current git tag.
Otherwise it is the one contained in the PKG-INFO file.
To use this script, simply import it in your setup.py file
and use the results of get_version() as your package version:
from version import *
setup(
...
version=get_version(),
...
)
"""
__all__ = ('get_version')
from os.path import dirname, isdir, join
import re
from subprocess import CalledProcessError, Popen, PIPE
try:
from subprocess import check_output
except ImportError:
def check_output(*popenargs, **kwargs):
r"""Run command with arguments and return its output as a byte string.
If the exit code was non-zero it raises a CalledProcessError. The
CalledProcessError object will have the return code in the returncode
attribute and output in the output attribute.
The arguments are the same as for the Popen constructor. Example:
>>> check_output(["ls", "-l", "/dev/null"])
'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
The stdout argument is not allowed as it is used internally.
To capture standard error in the result, use stderr=STDOUT.
>>> check_output(["/bin/sh", "-c",
... "ls -l non_existent_file ; exit 0"],
... stderr=STDOUT)
'ls: non_existent_file: No such file or directory\n'
"""
if 'stdout' in kwargs:
raise ValueError('stdout argument not allowed, it will be overridden.')
process = Popen(stdout=PIPE, *popenargs, **kwargs)
output, unused_err = process.communicate()
retcode = process.poll()
if retcode:
cmd = kwargs.get("args")
if cmd is None:
cmd = popenargs[0]
raise CalledProcessError(retcode, cmd, output=output)
return output
version_re = re.compile('^Version: (.+)$', re.M)
def get_version():
d = dirname(__file__)
if isdir(join(d, '.git')):
# Get the version using "git describe".
cmd = 'git describe --tags --match [0-9]*'.split()
try:
version = check_output(cmd).decode().strip()
except CalledProcessError:
print('Unable to get version number from git tags')
exit(1)
# PEP 386 compatibility
if '-' in version:
version = '.post'.join(version.split('-')[:2])
else:
# Extract the version from the PKG-INFO file.
with open(join(d, 'PKG-INFO')) as f:
version = version_re.search(f.read()).group(1)
return version
if __name__ == '__main__':
print(get_version())
|
ioannistsanaktsidis/invenio | refs/heads/prod | modules/bibformat/lib/elements/bfe_record_url.py | 11 | # -*- coding: utf-8 -*-
##
## This file is part of Invenio.
## Copyright (C) 2007, 2008, 2009, 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.
"""BibFormat element - Prints the record URL.
"""
__revision__ = "$Id$"
from invenio.config import \
CFG_SITE_URL, \
CFG_SITE_RECORD
def format_element(bfo, with_ln="yes"):
"""
Prints the record URL.
@param with_ln: if "yes" include "ln" attribute in the URL
"""
url = CFG_SITE_URL + "/" + CFG_SITE_RECORD + "/" + bfo.control_field('001')
if with_ln.lower() == "yes":
url += "?ln=" + bfo.lang
return url
|
carljm/django | refs/heads/master | tests/multiple_database/tests.py | 8 | from __future__ import unicode_literals
import datetime
import pickle
from operator import attrgetter
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.core import management
from django.db import DEFAULT_DB_ALIAS, connections, router, transaction
from django.db.models import signals
from django.db.utils import ConnectionRouter
from django.test import SimpleTestCase, TestCase, override_settings
from django.utils.six import StringIO
from .models import Book, Person, Pet, Review, UserProfile
from .routers import AuthRouter, TestRouter, WriteRouter
class QueryTestCase(TestCase):
multi_db = True
def test_db_selection(self):
"Check that querysets will use the default database by default"
self.assertEqual(Book.objects.db, DEFAULT_DB_ALIAS)
self.assertEqual(Book.objects.all().db, DEFAULT_DB_ALIAS)
self.assertEqual(Book.objects.using('other').db, 'other')
self.assertEqual(Book.objects.db_manager('other').db, 'other')
self.assertEqual(Book.objects.db_manager('other').all().db, 'other')
def test_default_creation(self):
"Objects created on the default database don't leak onto other databases"
# Create a book on the default database using create()
Book.objects.create(title="Pro Django", published=datetime.date(2008, 12, 16))
# Create a book on the default database using a save
dive = Book()
dive.title = "Dive into Python"
dive.published = datetime.date(2009, 5, 4)
dive.save()
# Check that book exists on the default database, but not on other database
try:
Book.objects.get(title="Pro Django")
Book.objects.using('default').get(title="Pro Django")
except Book.DoesNotExist:
self.fail('"Pro Django" should exist on default database')
with self.assertRaises(Book.DoesNotExist):
Book.objects.using('other').get(title="Pro Django")
try:
Book.objects.get(title="Dive into Python")
Book.objects.using('default').get(title="Dive into Python")
except Book.DoesNotExist:
self.fail('"Dive into Python" should exist on default database')
with self.assertRaises(Book.DoesNotExist):
Book.objects.using('other').get(title="Dive into Python")
def test_other_creation(self):
"Objects created on another database don't leak onto the default database"
# Create a book on the second database
Book.objects.using('other').create(title="Pro Django",
published=datetime.date(2008, 12, 16))
# Create a book on the default database using a save
dive = Book()
dive.title = "Dive into Python"
dive.published = datetime.date(2009, 5, 4)
dive.save(using='other')
# Check that book exists on the default database, but not on other database
try:
Book.objects.using('other').get(title="Pro Django")
except Book.DoesNotExist:
self.fail('"Pro Django" should exist on other database')
with self.assertRaises(Book.DoesNotExist):
Book.objects.get(title="Pro Django")
with self.assertRaises(Book.DoesNotExist):
Book.objects.using('default').get(title="Pro Django")
try:
Book.objects.using('other').get(title="Dive into Python")
except Book.DoesNotExist:
self.fail('"Dive into Python" should exist on other database')
with self.assertRaises(Book.DoesNotExist):
Book.objects.get(title="Dive into Python")
with self.assertRaises(Book.DoesNotExist):
Book.objects.using('default').get(title="Dive into Python")
def test_refresh(self):
dive = Book(title="Dive into Python", published=datetime.date(2009, 5, 4))
dive.save(using='other')
dive2 = Book.objects.using('other').get()
dive2.title = "Dive into Python (on default)"
dive2.save(using='default')
dive.refresh_from_db()
self.assertEqual(dive.title, "Dive into Python")
dive.refresh_from_db(using='default')
self.assertEqual(dive.title, "Dive into Python (on default)")
self.assertEqual(dive._state.db, "default")
def test_basic_queries(self):
"Queries are constrained to a single database"
dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4))
dive = Book.objects.using('other').get(published=datetime.date(2009, 5, 4))
self.assertEqual(dive.title, "Dive into Python")
with self.assertRaises(Book.DoesNotExist):
Book.objects.using('default').get(published=datetime.date(2009, 5, 4))
dive = Book.objects.using('other').get(title__icontains="dive")
self.assertEqual(dive.title, "Dive into Python")
with self.assertRaises(Book.DoesNotExist):
Book.objects.using('default').get(title__icontains="dive")
dive = Book.objects.using('other').get(title__iexact="dive INTO python")
self.assertEqual(dive.title, "Dive into Python")
with self.assertRaises(Book.DoesNotExist):
Book.objects.using('default').get(title__iexact="dive INTO python")
dive = Book.objects.using('other').get(published__year=2009)
self.assertEqual(dive.title, "Dive into Python")
self.assertEqual(dive.published, datetime.date(2009, 5, 4))
with self.assertRaises(Book.DoesNotExist):
Book.objects.using('default').get(published__year=2009)
years = Book.objects.using('other').dates('published', 'year')
self.assertEqual([o.year for o in years], [2009])
years = Book.objects.using('default').dates('published', 'year')
self.assertEqual([o.year for o in years], [])
months = Book.objects.using('other').dates('published', 'month')
self.assertEqual([o.month for o in months], [5])
months = Book.objects.using('default').dates('published', 'month')
self.assertEqual([o.month for o in months], [])
def test_m2m_separation(self):
"M2M fields are constrained to a single database"
# Create a book and author on the default database
pro = Book.objects.create(title="Pro Django",
published=datetime.date(2008, 12, 16))
marty = Person.objects.create(name="Marty Alchin")
# Create a book and author on the other database
dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4))
mark = Person.objects.using('other').create(name="Mark Pilgrim")
# Save the author relations
pro.authors.set([marty])
dive.authors.set([mark])
# Inspect the m2m tables directly.
# There should be 1 entry in each database
self.assertEqual(Book.authors.through.objects.using('default').count(), 1)
self.assertEqual(Book.authors.through.objects.using('other').count(), 1)
# Check that queries work across m2m joins
self.assertEqual(
list(Book.objects.using('default').filter(authors__name='Marty Alchin').values_list('title', flat=True)),
['Pro Django']
)
self.assertEqual(
list(Book.objects.using('other').filter(authors__name='Marty Alchin').values_list('title', flat=True)),
[]
)
self.assertEqual(
list(Book.objects.using('default').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)),
[]
)
self.assertEqual(
list(Book.objects.using('other').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)),
['Dive into Python']
)
# Reget the objects to clear caches
dive = Book.objects.using('other').get(title="Dive into Python")
mark = Person.objects.using('other').get(name="Mark Pilgrim")
# Retrieve related object by descriptor. Related objects should be database-bound
self.assertEqual(list(dive.authors.all().values_list('name', flat=True)), ['Mark Pilgrim'])
self.assertEqual(list(mark.book_set.all().values_list('title', flat=True)), ['Dive into Python'])
def test_m2m_forward_operations(self):
"M2M forward manipulations are all constrained to a single DB"
# Create a book and author on the other database
dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4))
mark = Person.objects.using('other').create(name="Mark Pilgrim")
# Save the author relations
dive.authors.set([mark])
# Add a second author
john = Person.objects.using('other').create(name="John Smith")
self.assertEqual(
list(Book.objects.using('other').filter(authors__name='John Smith').values_list('title', flat=True)),
[]
)
dive.authors.add(john)
self.assertEqual(
list(Book.objects.using('other').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)),
['Dive into Python']
)
self.assertEqual(
list(Book.objects.using('other').filter(authors__name='John Smith').values_list('title', flat=True)),
['Dive into Python']
)
# Remove the second author
dive.authors.remove(john)
self.assertEqual(
list(Book.objects.using('other').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)),
['Dive into Python']
)
self.assertEqual(
list(Book.objects.using('other').filter(authors__name='John Smith').values_list('title', flat=True)),
[]
)
# Clear all authors
dive.authors.clear()
self.assertEqual(
list(Book.objects.using('other').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)),
[]
)
self.assertEqual(
list(Book.objects.using('other').filter(authors__name='John Smith').values_list('title', flat=True)),
[]
)
# Create an author through the m2m interface
dive.authors.create(name='Jane Brown')
self.assertEqual(
list(Book.objects.using('other').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)),
[]
)
self.assertEqual(
list(Book.objects.using('other').filter(authors__name='Jane Brown').values_list('title', flat=True)),
['Dive into Python']
)
def test_m2m_reverse_operations(self):
"M2M reverse manipulations are all constrained to a single DB"
# Create a book and author on the other database
dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4))
mark = Person.objects.using('other').create(name="Mark Pilgrim")
# Save the author relations
dive.authors.set([mark])
# Create a second book on the other database
grease = Book.objects.using('other').create(title="Greasemonkey Hacks", published=datetime.date(2005, 11, 1))
# Add a books to the m2m
mark.book_set.add(grease)
self.assertEqual(
list(Person.objects.using('other').filter(book__title='Dive into Python').values_list('name', flat=True)),
['Mark Pilgrim']
)
self.assertEqual(
list(
Person.objects.using('other').filter(book__title='Greasemonkey Hacks').values_list('name', flat=True)
),
['Mark Pilgrim']
)
# Remove a book from the m2m
mark.book_set.remove(grease)
self.assertEqual(
list(Person.objects.using('other').filter(book__title='Dive into Python').values_list('name', flat=True)),
['Mark Pilgrim']
)
self.assertEqual(
list(
Person.objects.using('other').filter(book__title='Greasemonkey Hacks').values_list('name', flat=True)
),
[]
)
# Clear the books associated with mark
mark.book_set.clear()
self.assertEqual(
list(Person.objects.using('other').filter(book__title='Dive into Python').values_list('name', flat=True)),
[]
)
self.assertEqual(
list(
Person.objects.using('other').filter(book__title='Greasemonkey Hacks').values_list('name', flat=True)
),
[]
)
# Create a book through the m2m interface
mark.book_set.create(title="Dive into HTML5", published=datetime.date(2020, 1, 1))
self.assertEqual(
list(Person.objects.using('other').filter(book__title='Dive into Python').values_list('name', flat=True)),
[]
)
self.assertEqual(
list(Person.objects.using('other').filter(book__title='Dive into HTML5').values_list('name', flat=True)),
['Mark Pilgrim']
)
def test_m2m_cross_database_protection(self):
"Operations that involve sharing M2M objects across databases raise an error"
# Create a book and author on the default database
pro = Book.objects.create(title="Pro Django", published=datetime.date(2008, 12, 16))
marty = Person.objects.create(name="Marty Alchin")
# Create a book and author on the other database
dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4))
mark = Person.objects.using('other').create(name="Mark Pilgrim")
# Set a foreign key set with an object from a different database
with self.assertRaises(ValueError):
with transaction.atomic(using='default'):
marty.edited.set([pro, dive])
# Add to an m2m with an object from a different database
with self.assertRaises(ValueError):
with transaction.atomic(using='default'):
marty.book_set.add(dive)
# Set a m2m with an object from a different database
with self.assertRaises(ValueError):
with transaction.atomic(using='default'):
marty.book_set.set([pro, dive])
# Add to a reverse m2m with an object from a different database
with self.assertRaises(ValueError):
with transaction.atomic(using='other'):
dive.authors.add(marty)
# Set a reverse m2m with an object from a different database
with self.assertRaises(ValueError):
with transaction.atomic(using='other'):
dive.authors.set([mark, marty])
def test_m2m_deletion(self):
"Cascaded deletions of m2m relations issue queries on the right database"
# Create a book and author on the other database
dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4))
mark = Person.objects.using('other').create(name="Mark Pilgrim")
dive.authors.set([mark])
# Check the initial state
self.assertEqual(Person.objects.using('default').count(), 0)
self.assertEqual(Book.objects.using('default').count(), 0)
self.assertEqual(Book.authors.through.objects.using('default').count(), 0)
self.assertEqual(Person.objects.using('other').count(), 1)
self.assertEqual(Book.objects.using('other').count(), 1)
self.assertEqual(Book.authors.through.objects.using('other').count(), 1)
# Delete the object on the other database
dive.delete(using='other')
self.assertEqual(Person.objects.using('default').count(), 0)
self.assertEqual(Book.objects.using('default').count(), 0)
self.assertEqual(Book.authors.through.objects.using('default').count(), 0)
# The person still exists ...
self.assertEqual(Person.objects.using('other').count(), 1)
# ... but the book has been deleted
self.assertEqual(Book.objects.using('other').count(), 0)
# ... and the relationship object has also been deleted.
self.assertEqual(Book.authors.through.objects.using('other').count(), 0)
# Now try deletion in the reverse direction. Set up the relation again
dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4))
dive.authors.set([mark])
# Check the initial state
self.assertEqual(Person.objects.using('default').count(), 0)
self.assertEqual(Book.objects.using('default').count(), 0)
self.assertEqual(Book.authors.through.objects.using('default').count(), 0)
self.assertEqual(Person.objects.using('other').count(), 1)
self.assertEqual(Book.objects.using('other').count(), 1)
self.assertEqual(Book.authors.through.objects.using('other').count(), 1)
# Delete the object on the other database
mark.delete(using='other')
self.assertEqual(Person.objects.using('default').count(), 0)
self.assertEqual(Book.objects.using('default').count(), 0)
self.assertEqual(Book.authors.through.objects.using('default').count(), 0)
# The person has been deleted ...
self.assertEqual(Person.objects.using('other').count(), 0)
# ... but the book still exists
self.assertEqual(Book.objects.using('other').count(), 1)
# ... and the relationship object has been deleted.
self.assertEqual(Book.authors.through.objects.using('other').count(), 0)
def test_foreign_key_separation(self):
"FK fields are constrained to a single database"
# Create a book and author on the default database
pro = Book.objects.create(title="Pro Django", published=datetime.date(2008, 12, 16))
george = Person.objects.create(name="George Vilches")
# Create a book and author on the other database
dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4))
chris = Person.objects.using('other').create(name="Chris Mills")
# Save the author's favorite books
pro.editor = george
pro.save()
dive.editor = chris
dive.save()
pro = Book.objects.using('default').get(title="Pro Django")
self.assertEqual(pro.editor.name, "George Vilches")
dive = Book.objects.using('other').get(title="Dive into Python")
self.assertEqual(dive.editor.name, "Chris Mills")
# Check that queries work across foreign key joins
self.assertEqual(
list(Person.objects.using('default').filter(edited__title='Pro Django').values_list('name', flat=True)),
['George Vilches']
)
self.assertEqual(
list(Person.objects.using('other').filter(edited__title='Pro Django').values_list('name', flat=True)),
[]
)
self.assertEqual(
list(
Person.objects.using('default').filter(edited__title='Dive into Python').values_list('name', flat=True)
),
[]
)
self.assertEqual(
list(
Person.objects.using('other').filter(edited__title='Dive into Python').values_list('name', flat=True)
),
['Chris Mills']
)
# Reget the objects to clear caches
chris = Person.objects.using('other').get(name="Chris Mills")
dive = Book.objects.using('other').get(title="Dive into Python")
# Retrieve related object by descriptor. Related objects should be database-bound
self.assertEqual(list(chris.edited.values_list('title', flat=True)), ['Dive into Python'])
def test_foreign_key_reverse_operations(self):
"FK reverse manipulations are all constrained to a single DB"
dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4))
chris = Person.objects.using('other').create(name="Chris Mills")
# Save the author relations
dive.editor = chris
dive.save()
# Add a second book edited by chris
html5 = Book.objects.using('other').create(title="Dive into HTML5", published=datetime.date(2010, 3, 15))
self.assertEqual(
list(Person.objects.using('other').filter(edited__title='Dive into HTML5').values_list('name', flat=True)),
[]
)
chris.edited.add(html5)
self.assertEqual(
list(Person.objects.using('other').filter(edited__title='Dive into HTML5').values_list('name', flat=True)),
['Chris Mills']
)
self.assertEqual(
list(
Person.objects.using('other').filter(edited__title='Dive into Python').values_list('name', flat=True)
),
['Chris Mills']
)
# Remove the second editor
chris.edited.remove(html5)
self.assertEqual(
list(Person.objects.using('other').filter(edited__title='Dive into HTML5').values_list('name', flat=True)),
[]
)
self.assertEqual(
list(
Person.objects.using('other').filter(edited__title='Dive into Python').values_list('name', flat=True)
),
['Chris Mills']
)
# Clear all edited books
chris.edited.clear()
self.assertEqual(
list(Person.objects.using('other').filter(edited__title='Dive into HTML5').values_list('name', flat=True)),
[]
)
self.assertEqual(
list(
Person.objects.using('other').filter(edited__title='Dive into Python').values_list('name', flat=True)
),
[]
)
# Create an author through the m2m interface
chris.edited.create(title='Dive into Water', published=datetime.date(2010, 3, 15))
self.assertEqual(
list(Person.objects.using('other').filter(edited__title='Dive into HTML5').values_list('name', flat=True)),
[]
)
self.assertEqual(
list(Person.objects.using('other').filter(edited__title='Dive into Water').values_list('name', flat=True)),
['Chris Mills']
)
self.assertEqual(
list(
Person.objects.using('other').filter(edited__title='Dive into Python').values_list('name', flat=True)
),
[]
)
def test_foreign_key_cross_database_protection(self):
"Operations that involve sharing FK objects across databases raise an error"
# Create a book and author on the default database
pro = Book.objects.create(title="Pro Django", published=datetime.date(2008, 12, 16))
marty = Person.objects.create(name="Marty Alchin")
# Create a book and author on the other database
dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4))
# Set a foreign key with an object from a different database
with self.assertRaises(ValueError):
dive.editor = marty
# Set a foreign key set with an object from a different database
with self.assertRaises(ValueError):
with transaction.atomic(using='default'):
marty.edited.set([pro, dive])
# Add to a foreign key set with an object from a different database
with self.assertRaises(ValueError):
with transaction.atomic(using='default'):
marty.edited.add(dive)
def test_foreign_key_deletion(self):
"Cascaded deletions of Foreign Key relations issue queries on the right database"
mark = Person.objects.using('other').create(name="Mark Pilgrim")
Pet.objects.using('other').create(name="Fido", owner=mark)
# Check the initial state
self.assertEqual(Person.objects.using('default').count(), 0)
self.assertEqual(Pet.objects.using('default').count(), 0)
self.assertEqual(Person.objects.using('other').count(), 1)
self.assertEqual(Pet.objects.using('other').count(), 1)
# Delete the person object, which will cascade onto the pet
mark.delete(using='other')
self.assertEqual(Person.objects.using('default').count(), 0)
self.assertEqual(Pet.objects.using('default').count(), 0)
# Both the pet and the person have been deleted from the right database
self.assertEqual(Person.objects.using('other').count(), 0)
self.assertEqual(Pet.objects.using('other').count(), 0)
def test_foreign_key_validation(self):
"ForeignKey.validate() uses the correct database"
mickey = Person.objects.using('other').create(name="Mickey")
pluto = Pet.objects.using('other').create(name="Pluto", owner=mickey)
self.assertIsNone(pluto.full_clean())
# Any router that accesses `model` in db_for_read() works here.
@override_settings(DATABASE_ROUTERS=[AuthRouter()])
def test_foreign_key_validation_with_router(self):
"""
ForeignKey.validate() passes `model` to db_for_read() even if
model_instance=None.
"""
mickey = Person.objects.create(name="Mickey")
owner_field = Pet._meta.get_field('owner')
self.assertEqual(owner_field.clean(mickey.pk, None), mickey.pk)
def test_o2o_separation(self):
"OneToOne fields are constrained to a single database"
# Create a user and profile on the default database
alice = User.objects.db_manager('default').create_user('alice', '[email protected]')
alice_profile = UserProfile.objects.using('default').create(user=alice, flavor='chocolate')
# Create a user and profile on the other database
bob = User.objects.db_manager('other').create_user('bob', '[email protected]')
bob_profile = UserProfile.objects.using('other').create(user=bob, flavor='crunchy frog')
# Retrieve related objects; queries should be database constrained
alice = User.objects.using('default').get(username="alice")
self.assertEqual(alice.userprofile.flavor, "chocolate")
bob = User.objects.using('other').get(username="bob")
self.assertEqual(bob.userprofile.flavor, "crunchy frog")
# Check that queries work across joins
self.assertEqual(
list(
User.objects.using('default')
.filter(userprofile__flavor='chocolate').values_list('username', flat=True)
),
['alice']
)
self.assertEqual(
list(
User.objects.using('other')
.filter(userprofile__flavor='chocolate').values_list('username', flat=True)
),
[]
)
self.assertEqual(
list(
User.objects.using('default')
.filter(userprofile__flavor='crunchy frog').values_list('username', flat=True)
),
[]
)
self.assertEqual(
list(
User.objects.using('other')
.filter(userprofile__flavor='crunchy frog').values_list('username', flat=True)
),
['bob']
)
# Reget the objects to clear caches
alice_profile = UserProfile.objects.using('default').get(flavor='chocolate')
bob_profile = UserProfile.objects.using('other').get(flavor='crunchy frog')
# Retrieve related object by descriptor. Related objects should be database-bound
self.assertEqual(alice_profile.user.username, 'alice')
self.assertEqual(bob_profile.user.username, 'bob')
def test_o2o_cross_database_protection(self):
"Operations that involve sharing FK objects across databases raise an error"
# Create a user and profile on the default database
alice = User.objects.db_manager('default').create_user('alice', '[email protected]')
# Create a user and profile on the other database
bob = User.objects.db_manager('other').create_user('bob', '[email protected]')
# Set a one-to-one relation with an object from a different database
alice_profile = UserProfile.objects.using('default').create(user=alice, flavor='chocolate')
with self.assertRaises(ValueError):
bob.userprofile = alice_profile
# BUT! if you assign a FK object when the base object hasn't
# been saved yet, you implicitly assign the database for the
# base object.
bob_profile = UserProfile.objects.using('other').create(user=bob, flavor='crunchy frog')
new_bob_profile = UserProfile(flavor="spring surprise")
# assigning a profile requires an explicit pk as the object isn't saved
charlie = User(pk=51, username='charlie', email='[email protected]')
charlie.set_unusable_password()
# initially, no db assigned
self.assertIsNone(new_bob_profile._state.db)
self.assertIsNone(charlie._state.db)
# old object comes from 'other', so the new object is set to use 'other'...
new_bob_profile.user = bob
charlie.userprofile = bob_profile
self.assertEqual(new_bob_profile._state.db, 'other')
self.assertEqual(charlie._state.db, 'other')
# ... but it isn't saved yet
self.assertEqual(list(User.objects.using('other').values_list('username', flat=True)), ['bob'])
self.assertEqual(list(UserProfile.objects.using('other').values_list('flavor', flat=True)), ['crunchy frog'])
# When saved (no using required), new objects goes to 'other'
charlie.save()
bob_profile.save()
new_bob_profile.save()
self.assertEqual(list(User.objects.using('default').values_list('username', flat=True)), ['alice'])
self.assertEqual(list(User.objects.using('other').values_list('username', flat=True)), ['bob', 'charlie'])
self.assertEqual(list(UserProfile.objects.using('default').values_list('flavor', flat=True)), ['chocolate'])
self.assertEqual(
list(UserProfile.objects.using('other').values_list('flavor', flat=True)),
['crunchy frog', 'spring surprise']
)
# This also works if you assign the O2O relation in the constructor
denise = User.objects.db_manager('other').create_user('denise', '[email protected]')
denise_profile = UserProfile(flavor="tofu", user=denise)
self.assertEqual(denise_profile._state.db, 'other')
# ... but it isn't saved yet
self.assertEqual(list(UserProfile.objects.using('default').values_list('flavor', flat=True)), ['chocolate'])
self.assertEqual(
list(UserProfile.objects.using('other').values_list('flavor', flat=True)),
['crunchy frog', 'spring surprise']
)
# When saved, the new profile goes to 'other'
denise_profile.save()
self.assertEqual(list(UserProfile.objects.using('default').values_list('flavor', flat=True)), ['chocolate'])
self.assertEqual(
list(UserProfile.objects.using('other').values_list('flavor', flat=True)),
['crunchy frog', 'spring surprise', 'tofu']
)
def test_generic_key_separation(self):
"Generic fields are constrained to a single database"
# Create a book and author on the default database
pro = Book.objects.create(title="Pro Django", published=datetime.date(2008, 12, 16))
review1 = Review.objects.create(source="Python Monthly", content_object=pro)
# Create a book and author on the other database
dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4))
review2 = Review.objects.using('other').create(source="Python Weekly", content_object=dive)
review1 = Review.objects.using('default').get(source="Python Monthly")
self.assertEqual(review1.content_object.title, "Pro Django")
review2 = Review.objects.using('other').get(source="Python Weekly")
self.assertEqual(review2.content_object.title, "Dive into Python")
# Reget the objects to clear caches
dive = Book.objects.using('other').get(title="Dive into Python")
# Retrieve related object by descriptor. Related objects should be database-bound
self.assertEqual(list(dive.reviews.all().values_list('source', flat=True)), ['Python Weekly'])
def test_generic_key_reverse_operations(self):
"Generic reverse manipulations are all constrained to a single DB"
dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4))
temp = Book.objects.using('other').create(title="Temp", published=datetime.date(2009, 5, 4))
review1 = Review.objects.using('other').create(source="Python Weekly", content_object=dive)
review2 = Review.objects.using('other').create(source="Python Monthly", content_object=temp)
self.assertEqual(
list(Review.objects.using('default').filter(object_id=dive.pk).values_list('source', flat=True)),
[]
)
self.assertEqual(
list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)),
['Python Weekly']
)
# Add a second review
dive.reviews.add(review2)
self.assertEqual(
list(Review.objects.using('default').filter(object_id=dive.pk).values_list('source', flat=True)),
[]
)
self.assertEqual(
list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)),
['Python Monthly', 'Python Weekly']
)
# Remove the second author
dive.reviews.remove(review1)
self.assertEqual(
list(Review.objects.using('default').filter(object_id=dive.pk).values_list('source', flat=True)),
[]
)
self.assertEqual(
list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)),
['Python Monthly']
)
# Clear all reviews
dive.reviews.clear()
self.assertEqual(
list(Review.objects.using('default').filter(object_id=dive.pk).values_list('source', flat=True)),
[]
)
self.assertEqual(
list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)),
[]
)
# Create an author through the generic interface
dive.reviews.create(source='Python Daily')
self.assertEqual(
list(Review.objects.using('default').filter(object_id=dive.pk).values_list('source', flat=True)),
[]
)
self.assertEqual(
list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)),
['Python Daily']
)
def test_generic_key_cross_database_protection(self):
"Operations that involve sharing generic key objects across databases raise an error"
# Create a book and author on the default database
pro = Book.objects.create(title="Pro Django", published=datetime.date(2008, 12, 16))
review1 = Review.objects.create(source="Python Monthly", content_object=pro)
# Create a book and author on the other database
dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4))
Review.objects.using('other').create(source="Python Weekly", content_object=dive)
# Set a foreign key with an object from a different database
with self.assertRaises(ValueError):
review1.content_object = dive
# Add to a foreign key set with an object from a different database
with self.assertRaises(ValueError):
with transaction.atomic(using='other'):
dive.reviews.add(review1)
# BUT! if you assign a FK object when the base object hasn't
# been saved yet, you implicitly assign the database for the
# base object.
review3 = Review(source="Python Daily")
# initially, no db assigned
self.assertIsNone(review3._state.db)
# Dive comes from 'other', so review3 is set to use 'other'...
review3.content_object = dive
self.assertEqual(review3._state.db, 'other')
# ... but it isn't saved yet
self.assertEqual(
list(Review.objects.using('default').filter(object_id=pro.pk).values_list('source', flat=True)),
['Python Monthly']
)
self.assertEqual(
list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)),
['Python Weekly']
)
# When saved, John goes to 'other'
review3.save()
self.assertEqual(
list(Review.objects.using('default').filter(object_id=pro.pk).values_list('source', flat=True)),
['Python Monthly']
)
self.assertEqual(
list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)),
['Python Daily', 'Python Weekly']
)
def test_generic_key_deletion(self):
"Cascaded deletions of Generic Key relations issue queries on the right database"
dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4))
Review.objects.using('other').create(source="Python Weekly", content_object=dive)
# Check the initial state
self.assertEqual(Book.objects.using('default').count(), 0)
self.assertEqual(Review.objects.using('default').count(), 0)
self.assertEqual(Book.objects.using('other').count(), 1)
self.assertEqual(Review.objects.using('other').count(), 1)
# Delete the Book object, which will cascade onto the pet
dive.delete(using='other')
self.assertEqual(Book.objects.using('default').count(), 0)
self.assertEqual(Review.objects.using('default').count(), 0)
# Both the pet and the person have been deleted from the right database
self.assertEqual(Book.objects.using('other').count(), 0)
self.assertEqual(Review.objects.using('other').count(), 0)
def test_ordering(self):
"get_next_by_XXX commands stick to a single database"
Book.objects.create(title="Pro Django", published=datetime.date(2008, 12, 16))
dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4))
learn = Book.objects.using('other').create(title="Learning Python", published=datetime.date(2008, 7, 16))
self.assertEqual(learn.get_next_by_published().title, "Dive into Python")
self.assertEqual(dive.get_previous_by_published().title, "Learning Python")
def test_raw(self):
"test the raw() method across databases"
dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4))
val = Book.objects.db_manager("other").raw('SELECT id FROM multiple_database_book')
self.assertQuerysetEqual(val, [dive.pk], attrgetter("pk"))
val = Book.objects.raw('SELECT id FROM multiple_database_book').using('other')
self.assertQuerysetEqual(val, [dive.pk], attrgetter("pk"))
def test_select_related(self):
"Database assignment is retained if an object is retrieved with select_related()"
# Create a book and author on the other database
mark = Person.objects.using('other').create(name="Mark Pilgrim")
Book.objects.using('other').create(
title="Dive into Python",
published=datetime.date(2009, 5, 4),
editor=mark,
)
# Retrieve the Person using select_related()
book = Book.objects.using('other').select_related('editor').get(title="Dive into Python")
# The editor instance should have a db state
self.assertEqual(book.editor._state.db, 'other')
def test_subquery(self):
"""Make sure as_sql works with subqueries and primary/replica."""
sub = Person.objects.using('other').filter(name='fff')
qs = Book.objects.filter(editor__in=sub)
# When you call __str__ on the query object, it doesn't know about using
# so it falls back to the default. If the subquery explicitly uses a
# different database, an error should be raised.
with self.assertRaises(ValueError):
str(qs.query)
# Evaluating the query shouldn't work, either
with self.assertRaises(ValueError):
for obj in qs:
pass
def test_related_manager(self):
"Related managers return managers, not querysets"
mark = Person.objects.using('other').create(name="Mark Pilgrim")
# extra_arg is removed by the BookManager's implementation of
# create(); but the BookManager's implementation won't get called
# unless edited returns a Manager, not a queryset
mark.book_set.create(title="Dive into Python", published=datetime.date(2009, 5, 4), extra_arg=True)
mark.book_set.get_or_create(title="Dive into Python", published=datetime.date(2009, 5, 4), extra_arg=True)
mark.edited.create(title="Dive into Water", published=datetime.date(2009, 5, 4), extra_arg=True)
mark.edited.get_or_create(title="Dive into Water", published=datetime.date(2009, 5, 4), extra_arg=True)
class ConnectionRouterTestCase(SimpleTestCase):
@override_settings(DATABASE_ROUTERS=[
'multiple_database.tests.TestRouter',
'multiple_database.tests.WriteRouter'])
def test_router_init_default(self):
connection_router = ConnectionRouter()
self.assertListEqual([r.__class__.__name__ for r in connection_router.routers], ['TestRouter', 'WriteRouter'])
def test_router_init_arg(self):
connection_router = ConnectionRouter([
'multiple_database.tests.TestRouter',
'multiple_database.tests.WriteRouter'
])
self.assertListEqual([r.__class__.__name__ for r in connection_router.routers], ['TestRouter', 'WriteRouter'])
# Init with instances instead of strings
connection_router = ConnectionRouter([TestRouter(), WriteRouter()])
self.assertListEqual([r.__class__.__name__ for r in connection_router.routers], ['TestRouter', 'WriteRouter'])
# Make the 'other' database appear to be a replica of the 'default'
@override_settings(DATABASE_ROUTERS=[TestRouter()])
class RouterTestCase(TestCase):
multi_db = True
def test_db_selection(self):
"Check that querysets obey the router for db suggestions"
self.assertEqual(Book.objects.db, 'other')
self.assertEqual(Book.objects.all().db, 'other')
self.assertEqual(Book.objects.using('default').db, 'default')
self.assertEqual(Book.objects.db_manager('default').db, 'default')
self.assertEqual(Book.objects.db_manager('default').all().db, 'default')
def test_migrate_selection(self):
"Synchronization behavior is predictable"
self.assertTrue(router.allow_migrate_model('default', User))
self.assertTrue(router.allow_migrate_model('default', Book))
self.assertTrue(router.allow_migrate_model('other', User))
self.assertTrue(router.allow_migrate_model('other', Book))
with override_settings(DATABASE_ROUTERS=[TestRouter(), AuthRouter()]):
# Add the auth router to the chain. TestRouter is a universal
# synchronizer, so it should have no effect.
self.assertTrue(router.allow_migrate_model('default', User))
self.assertTrue(router.allow_migrate_model('default', Book))
self.assertTrue(router.allow_migrate_model('other', User))
self.assertTrue(router.allow_migrate_model('other', Book))
with override_settings(DATABASE_ROUTERS=[AuthRouter(), TestRouter()]):
# Now check what happens if the router order is reversed.
self.assertFalse(router.allow_migrate_model('default', User))
self.assertTrue(router.allow_migrate_model('default', Book))
self.assertTrue(router.allow_migrate_model('other', User))
self.assertTrue(router.allow_migrate_model('other', Book))
def test_partial_router(self):
"A router can choose to implement a subset of methods"
dive = Book.objects.using('other').create(title="Dive into Python",
published=datetime.date(2009, 5, 4))
# First check the baseline behavior.
self.assertEqual(router.db_for_read(User), 'other')
self.assertEqual(router.db_for_read(Book), 'other')
self.assertEqual(router.db_for_write(User), 'default')
self.assertEqual(router.db_for_write(Book), 'default')
self.assertTrue(router.allow_relation(dive, dive))
self.assertTrue(router.allow_migrate_model('default', User))
self.assertTrue(router.allow_migrate_model('default', Book))
with override_settings(DATABASE_ROUTERS=[WriteRouter(), AuthRouter(), TestRouter()]):
self.assertEqual(router.db_for_read(User), 'default')
self.assertEqual(router.db_for_read(Book), 'other')
self.assertEqual(router.db_for_write(User), 'writer')
self.assertEqual(router.db_for_write(Book), 'writer')
self.assertTrue(router.allow_relation(dive, dive))
self.assertFalse(router.allow_migrate_model('default', User))
self.assertTrue(router.allow_migrate_model('default', Book))
def test_database_routing(self):
marty = Person.objects.using('default').create(name="Marty Alchin")
pro = Book.objects.using('default').create(title="Pro Django",
published=datetime.date(2008, 12, 16),
editor=marty)
pro.authors.set([marty])
# Create a book and author on the other database
Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4))
# An update query will be routed to the default database
Book.objects.filter(title='Pro Django').update(pages=200)
with self.assertRaises(Book.DoesNotExist):
# By default, the get query will be directed to 'other'
Book.objects.get(title='Pro Django')
# But the same query issued explicitly at a database will work.
pro = Book.objects.using('default').get(title='Pro Django')
# Check that the update worked.
self.assertEqual(pro.pages, 200)
# An update query with an explicit using clause will be routed
# to the requested database.
Book.objects.using('other').filter(title='Dive into Python').update(pages=300)
self.assertEqual(Book.objects.get(title='Dive into Python').pages, 300)
# Related object queries stick to the same database
# as the original object, regardless of the router
self.assertEqual(list(pro.authors.values_list('name', flat=True)), ['Marty Alchin'])
self.assertEqual(pro.editor.name, 'Marty Alchin')
# get_or_create is a special case. The get needs to be targeted at
# the write database in order to avoid potential transaction
# consistency problems
book, created = Book.objects.get_or_create(title="Pro Django")
self.assertFalse(created)
book, created = Book.objects.get_or_create(title="Dive Into Python",
defaults={'published': datetime.date(2009, 5, 4)})
self.assertTrue(created)
# Check the head count of objects
self.assertEqual(Book.objects.using('default').count(), 2)
self.assertEqual(Book.objects.using('other').count(), 1)
# If a database isn't specified, the read database is used
self.assertEqual(Book.objects.count(), 1)
# A delete query will also be routed to the default database
Book.objects.filter(pages__gt=150).delete()
# The default database has lost the book.
self.assertEqual(Book.objects.using('default').count(), 1)
self.assertEqual(Book.objects.using('other').count(), 1)
def test_invalid_set_foreign_key_assignment(self):
marty = Person.objects.using('default').create(name="Marty Alchin")
dive = Book.objects.using('other').create(
title="Dive into Python",
published=datetime.date(2009, 5, 4),
)
# Set a foreign key set with an object from a different database
msg = "<Book: Dive into Python> instance isn't saved. Use bulk=False or save the object first."
with self.assertRaisesMessage(ValueError, msg):
marty.edited.set([dive])
def test_foreign_key_cross_database_protection(self):
"Foreign keys can cross databases if they two databases have a common source"
# Create a book and author on the default database
pro = Book.objects.using('default').create(title="Pro Django",
published=datetime.date(2008, 12, 16))
marty = Person.objects.using('default').create(name="Marty Alchin")
# Create a book and author on the other database
dive = Book.objects.using('other').create(title="Dive into Python",
published=datetime.date(2009, 5, 4))
mark = Person.objects.using('other').create(name="Mark Pilgrim")
# Set a foreign key with an object from a different database
dive.editor = marty
# Database assignments of original objects haven't changed...
self.assertEqual(marty._state.db, 'default')
self.assertEqual(pro._state.db, 'default')
self.assertEqual(dive._state.db, 'other')
self.assertEqual(mark._state.db, 'other')
# ... but they will when the affected object is saved.
dive.save()
self.assertEqual(dive._state.db, 'default')
# ...and the source database now has a copy of any object saved
Book.objects.using('default').get(title='Dive into Python').delete()
# This isn't a real primary/replica database, so restore the original from other
dive = Book.objects.using('other').get(title='Dive into Python')
self.assertEqual(dive._state.db, 'other')
# Set a foreign key set with an object from a different database
marty.edited.set([pro, dive], bulk=False)
# Assignment implies a save, so database assignments of original objects have changed...
self.assertEqual(marty._state.db, 'default')
self.assertEqual(pro._state.db, 'default')
self.assertEqual(dive._state.db, 'default')
self.assertEqual(mark._state.db, 'other')
# ...and the source database now has a copy of any object saved
Book.objects.using('default').get(title='Dive into Python').delete()
# This isn't a real primary/replica database, so restore the original from other
dive = Book.objects.using('other').get(title='Dive into Python')
self.assertEqual(dive._state.db, 'other')
# Add to a foreign key set with an object from a different database
marty.edited.add(dive, bulk=False)
# Add implies a save, so database assignments of original objects have changed...
self.assertEqual(marty._state.db, 'default')
self.assertEqual(pro._state.db, 'default')
self.assertEqual(dive._state.db, 'default')
self.assertEqual(mark._state.db, 'other')
# ...and the source database now has a copy of any object saved
Book.objects.using('default').get(title='Dive into Python').delete()
# This isn't a real primary/replica database, so restore the original from other
dive = Book.objects.using('other').get(title='Dive into Python')
# If you assign a FK object when the base object hasn't
# been saved yet, you implicitly assign the database for the
# base object.
chris = Person(name="Chris Mills")
html5 = Book(title="Dive into HTML5", published=datetime.date(2010, 3, 15))
# initially, no db assigned
self.assertIsNone(chris._state.db)
self.assertIsNone(html5._state.db)
# old object comes from 'other', so the new object is set to use the
# source of 'other'...
self.assertEqual(dive._state.db, 'other')
chris.save()
dive.editor = chris
html5.editor = mark
self.assertEqual(dive._state.db, 'other')
self.assertEqual(mark._state.db, 'other')
self.assertEqual(chris._state.db, 'default')
self.assertEqual(html5._state.db, 'default')
# This also works if you assign the FK in the constructor
water = Book(title="Dive into Water", published=datetime.date(2001, 1, 1), editor=mark)
self.assertEqual(water._state.db, 'default')
# For the remainder of this test, create a copy of 'mark' in the
# 'default' database to prevent integrity errors on backends that
# don't defer constraints checks until the end of the transaction
mark.save(using='default')
# This moved 'mark' in the 'default' database, move it back in 'other'
mark.save(using='other')
self.assertEqual(mark._state.db, 'other')
# If you create an object through a FK relation, it will be
# written to the write database, even if the original object
# was on the read database
cheesecake = mark.edited.create(title='Dive into Cheesecake', published=datetime.date(2010, 3, 15))
self.assertEqual(cheesecake._state.db, 'default')
# Same goes for get_or_create, regardless of whether getting or creating
cheesecake, created = mark.edited.get_or_create(
title='Dive into Cheesecake',
published=datetime.date(2010, 3, 15),
)
self.assertEqual(cheesecake._state.db, 'default')
puddles, created = mark.edited.get_or_create(title='Dive into Puddles', published=datetime.date(2010, 3, 15))
self.assertEqual(puddles._state.db, 'default')
def test_m2m_cross_database_protection(self):
"M2M relations can cross databases if the database share a source"
# Create books and authors on the inverse to the usual database
pro = Book.objects.using('other').create(pk=1, title="Pro Django",
published=datetime.date(2008, 12, 16))
marty = Person.objects.using('other').create(pk=1, name="Marty Alchin")
dive = Book.objects.using('default').create(pk=2, title="Dive into Python",
published=datetime.date(2009, 5, 4))
mark = Person.objects.using('default').create(pk=2, name="Mark Pilgrim")
# Now save back onto the usual database.
# This simulates primary/replica - the objects exist on both database,
# but the _state.db is as it is for all other tests.
pro.save(using='default')
marty.save(using='default')
dive.save(using='other')
mark.save(using='other')
# Check that we have 2 of both types of object on both databases
self.assertEqual(Book.objects.using('default').count(), 2)
self.assertEqual(Book.objects.using('other').count(), 2)
self.assertEqual(Person.objects.using('default').count(), 2)
self.assertEqual(Person.objects.using('other').count(), 2)
# Set a m2m set with an object from a different database
marty.book_set.set([pro, dive])
# Database assignments don't change
self.assertEqual(marty._state.db, 'default')
self.assertEqual(pro._state.db, 'default')
self.assertEqual(dive._state.db, 'other')
self.assertEqual(mark._state.db, 'other')
# All m2m relations should be saved on the default database
self.assertEqual(Book.authors.through.objects.using('default').count(), 2)
self.assertEqual(Book.authors.through.objects.using('other').count(), 0)
# Reset relations
Book.authors.through.objects.using('default').delete()
# Add to an m2m with an object from a different database
marty.book_set.add(dive)
# Database assignments don't change
self.assertEqual(marty._state.db, 'default')
self.assertEqual(pro._state.db, 'default')
self.assertEqual(dive._state.db, 'other')
self.assertEqual(mark._state.db, 'other')
# All m2m relations should be saved on the default database
self.assertEqual(Book.authors.through.objects.using('default').count(), 1)
self.assertEqual(Book.authors.through.objects.using('other').count(), 0)
# Reset relations
Book.authors.through.objects.using('default').delete()
# Set a reverse m2m with an object from a different database
dive.authors.set([mark, marty])
# Database assignments don't change
self.assertEqual(marty._state.db, 'default')
self.assertEqual(pro._state.db, 'default')
self.assertEqual(dive._state.db, 'other')
self.assertEqual(mark._state.db, 'other')
# All m2m relations should be saved on the default database
self.assertEqual(Book.authors.through.objects.using('default').count(), 2)
self.assertEqual(Book.authors.through.objects.using('other').count(), 0)
# Reset relations
Book.authors.through.objects.using('default').delete()
self.assertEqual(Book.authors.through.objects.using('default').count(), 0)
self.assertEqual(Book.authors.through.objects.using('other').count(), 0)
# Add to a reverse m2m with an object from a different database
dive.authors.add(marty)
# Database assignments don't change
self.assertEqual(marty._state.db, 'default')
self.assertEqual(pro._state.db, 'default')
self.assertEqual(dive._state.db, 'other')
self.assertEqual(mark._state.db, 'other')
# All m2m relations should be saved on the default database
self.assertEqual(Book.authors.through.objects.using('default').count(), 1)
self.assertEqual(Book.authors.through.objects.using('other').count(), 0)
# If you create an object through a M2M relation, it will be
# written to the write database, even if the original object
# was on the read database
alice = dive.authors.create(name='Alice')
self.assertEqual(alice._state.db, 'default')
# Same goes for get_or_create, regardless of whether getting or creating
alice, created = dive.authors.get_or_create(name='Alice')
self.assertEqual(alice._state.db, 'default')
bob, created = dive.authors.get_or_create(name='Bob')
self.assertEqual(bob._state.db, 'default')
def test_o2o_cross_database_protection(self):
"Operations that involve sharing FK objects across databases raise an error"
# Create a user and profile on the default database
alice = User.objects.db_manager('default').create_user('alice', '[email protected]')
# Create a user and profile on the other database
bob = User.objects.db_manager('other').create_user('bob', '[email protected]')
# Set a one-to-one relation with an object from a different database
alice_profile = UserProfile.objects.create(user=alice, flavor='chocolate')
bob.userprofile = alice_profile
# Database assignments of original objects haven't changed...
self.assertEqual(alice._state.db, 'default')
self.assertEqual(alice_profile._state.db, 'default')
self.assertEqual(bob._state.db, 'other')
# ... but they will when the affected object is saved.
bob.save()
self.assertEqual(bob._state.db, 'default')
def test_generic_key_cross_database_protection(self):
"Generic Key operations can span databases if they share a source"
# Create a book and author on the default database
pro = Book.objects.using(
'default').create(title="Pro Django", published=datetime.date(2008, 12, 16))
review1 = Review.objects.using(
'default').create(source="Python Monthly", content_object=pro)
# Create a book and author on the other database
dive = Book.objects.using(
'other').create(title="Dive into Python", published=datetime.date(2009, 5, 4))
review2 = Review.objects.using(
'other').create(source="Python Weekly", content_object=dive)
# Set a generic foreign key with an object from a different database
review1.content_object = dive
# Database assignments of original objects haven't changed...
self.assertEqual(pro._state.db, 'default')
self.assertEqual(review1._state.db, 'default')
self.assertEqual(dive._state.db, 'other')
self.assertEqual(review2._state.db, 'other')
# ... but they will when the affected object is saved.
dive.save()
self.assertEqual(review1._state.db, 'default')
self.assertEqual(dive._state.db, 'default')
# ...and the source database now has a copy of any object saved
Book.objects.using('default').get(title='Dive into Python').delete()
# This isn't a real primary/replica database, so restore the original from other
dive = Book.objects.using('other').get(title='Dive into Python')
self.assertEqual(dive._state.db, 'other')
# Add to a generic foreign key set with an object from a different database
dive.reviews.add(review1)
# Database assignments of original objects haven't changed...
self.assertEqual(pro._state.db, 'default')
self.assertEqual(review1._state.db, 'default')
self.assertEqual(dive._state.db, 'other')
self.assertEqual(review2._state.db, 'other')
# ... but they will when the affected object is saved.
dive.save()
self.assertEqual(dive._state.db, 'default')
# ...and the source database now has a copy of any object saved
Book.objects.using('default').get(title='Dive into Python').delete()
# BUT! if you assign a FK object when the base object hasn't
# been saved yet, you implicitly assign the database for the
# base object.
review3 = Review(source="Python Daily")
# initially, no db assigned
self.assertIsNone(review3._state.db)
# Dive comes from 'other', so review3 is set to use the source of 'other'...
review3.content_object = dive
self.assertEqual(review3._state.db, 'default')
# If you create an object through a M2M relation, it will be
# written to the write database, even if the original object
# was on the read database
dive = Book.objects.using('other').get(title='Dive into Python')
nyt = dive.reviews.create(source="New York Times", content_object=dive)
self.assertEqual(nyt._state.db, 'default')
def test_m2m_managers(self):
"M2M relations are represented by managers, and can be controlled like managers"
pro = Book.objects.using('other').create(pk=1, title="Pro Django",
published=datetime.date(2008, 12, 16))
marty = Person.objects.using('other').create(pk=1, name="Marty Alchin")
self.assertEqual(pro.authors.db, 'other')
self.assertEqual(pro.authors.db_manager('default').db, 'default')
self.assertEqual(pro.authors.db_manager('default').all().db, 'default')
self.assertEqual(marty.book_set.db, 'other')
self.assertEqual(marty.book_set.db_manager('default').db, 'default')
self.assertEqual(marty.book_set.db_manager('default').all().db, 'default')
def test_foreign_key_managers(self):
"FK reverse relations are represented by managers, and can be controlled like managers"
marty = Person.objects.using('other').create(pk=1, name="Marty Alchin")
Book.objects.using('other').create(pk=1, title="Pro Django",
published=datetime.date(2008, 12, 16),
editor=marty)
self.assertEqual(marty.edited.db, 'other')
self.assertEqual(marty.edited.db_manager('default').db, 'default')
self.assertEqual(marty.edited.db_manager('default').all().db, 'default')
def test_generic_key_managers(self):
"Generic key relations are represented by managers, and can be controlled like managers"
pro = Book.objects.using('other').create(title="Pro Django",
published=datetime.date(2008, 12, 16))
Review.objects.using('other').create(source="Python Monthly",
content_object=pro)
self.assertEqual(pro.reviews.db, 'other')
self.assertEqual(pro.reviews.db_manager('default').db, 'default')
self.assertEqual(pro.reviews.db_manager('default').all().db, 'default')
def test_subquery(self):
"""Make sure as_sql works with subqueries and primary/replica."""
# Create a book and author on the other database
mark = Person.objects.using('other').create(name="Mark Pilgrim")
Book.objects.using('other').create(title="Dive into Python",
published=datetime.date(2009, 5, 4),
editor=mark)
sub = Person.objects.filter(name='Mark Pilgrim')
qs = Book.objects.filter(editor__in=sub)
# When you call __str__ on the query object, it doesn't know about using
# so it falls back to the default. Don't let routing instructions
# force the subquery to an incompatible database.
str(qs.query)
# If you evaluate the query, it should work, running on 'other'
self.assertEqual(list(qs.values_list('title', flat=True)), ['Dive into Python'])
def test_deferred_models(self):
mark_def = Person.objects.using('default').create(name="Mark Pilgrim")
mark_other = Person.objects.using('other').create(name="Mark Pilgrim")
orig_b = Book.objects.using('other').create(title="Dive into Python",
published=datetime.date(2009, 5, 4),
editor=mark_other)
b = Book.objects.using('other').only('title').get(pk=orig_b.pk)
self.assertEqual(b.published, datetime.date(2009, 5, 4))
b = Book.objects.using('other').only('title').get(pk=orig_b.pk)
b.editor = mark_def
b.save(using='default')
self.assertEqual(Book.objects.using('default').get(pk=b.pk).published,
datetime.date(2009, 5, 4))
@override_settings(DATABASE_ROUTERS=[AuthRouter()])
class AuthTestCase(TestCase):
multi_db = True
def test_auth_manager(self):
"The methods on the auth manager obey database hints"
# Create one user using default allocation policy
User.objects.create_user('alice', '[email protected]')
# Create another user, explicitly specifying the database
User.objects.db_manager('default').create_user('bob', '[email protected]')
# The second user only exists on the other database
alice = User.objects.using('other').get(username='alice')
self.assertEqual(alice.username, 'alice')
self.assertEqual(alice._state.db, 'other')
with self.assertRaises(User.DoesNotExist):
User.objects.using('default').get(username='alice')
# The second user only exists on the default database
bob = User.objects.using('default').get(username='bob')
self.assertEqual(bob.username, 'bob')
self.assertEqual(bob._state.db, 'default')
with self.assertRaises(User.DoesNotExist):
User.objects.using('other').get(username='bob')
# That is... there is one user on each database
self.assertEqual(User.objects.using('default').count(), 1)
self.assertEqual(User.objects.using('other').count(), 1)
def test_dumpdata(self):
"Check that dumpdata honors allow_migrate restrictions on the router"
User.objects.create_user('alice', '[email protected]')
User.objects.db_manager('default').create_user('bob', '[email protected]')
# Check that dumping the default database doesn't try to include auth
# because allow_migrate prohibits auth on default
new_io = StringIO()
management.call_command('dumpdata', 'auth', format='json', database='default', stdout=new_io)
command_output = new_io.getvalue().strip()
self.assertEqual(command_output, '[]')
# Check that dumping the other database does include auth
new_io = StringIO()
management.call_command('dumpdata', 'auth', format='json', database='other', stdout=new_io)
command_output = new_io.getvalue().strip()
self.assertIn('"email": "[email protected]"', command_output)
class AntiPetRouter(object):
# A router that only expresses an opinion on migrate,
# passing pets to the 'other' database
def allow_migrate(self, db, app_label, model_name=None, **hints):
if db == 'other':
return model_name == 'pet'
else:
return model_name != 'pet'
class FixtureTestCase(TestCase):
multi_db = True
fixtures = ['multidb-common', 'multidb']
@override_settings(DATABASE_ROUTERS=[AntiPetRouter()])
def test_fixture_loading(self):
"Multi-db fixtures are loaded correctly"
# Check that "Pro Django" exists on the default database, but not on other database
Book.objects.get(title="Pro Django")
Book.objects.using('default').get(title="Pro Django")
with self.assertRaises(Book.DoesNotExist):
Book.objects.using('other').get(title="Pro Django")
# Check that "Dive into Python" exists on the default database, but not on other database
Book.objects.using('other').get(title="Dive into Python")
with self.assertRaises(Book.DoesNotExist):
Book.objects.get(title="Dive into Python")
with self.assertRaises(Book.DoesNotExist):
Book.objects.using('default').get(title="Dive into Python")
# Check that "Definitive Guide" exists on the both databases
Book.objects.get(title="The Definitive Guide to Django")
Book.objects.using('default').get(title="The Definitive Guide to Django")
Book.objects.using('other').get(title="The Definitive Guide to Django")
@override_settings(DATABASE_ROUTERS=[AntiPetRouter()])
def test_pseudo_empty_fixtures(self):
"""
A fixture can contain entries, but lead to nothing in the database;
this shouldn't raise an error (#14068).
"""
new_io = StringIO()
management.call_command('loaddata', 'pets', stdout=new_io, stderr=new_io)
command_output = new_io.getvalue().strip()
# No objects will actually be loaded
self.assertEqual(command_output, "Installed 0 object(s) (of 2) from 1 fixture(s)")
class PickleQuerySetTestCase(TestCase):
multi_db = True
def test_pickling(self):
for db in connections:
Book.objects.using(db).create(title='Dive into Python', published=datetime.date(2009, 5, 4))
qs = Book.objects.all()
self.assertEqual(qs.db, pickle.loads(pickle.dumps(qs)).db)
class DatabaseReceiver(object):
"""
Used in the tests for the database argument in signals (#13552)
"""
def __call__(self, signal, sender, **kwargs):
self._database = kwargs['using']
class WriteToOtherRouter(object):
"""
A router that sends all writes to the other database.
"""
def db_for_write(self, model, **hints):
return "other"
class SignalTests(TestCase):
multi_db = True
def override_router(self):
return override_settings(DATABASE_ROUTERS=[WriteToOtherRouter()])
def test_database_arg_save_and_delete(self):
"""
Tests that the pre/post_save signal contains the correct database.
(#13552)
"""
# Make some signal receivers
pre_save_receiver = DatabaseReceiver()
post_save_receiver = DatabaseReceiver()
pre_delete_receiver = DatabaseReceiver()
post_delete_receiver = DatabaseReceiver()
# Make model and connect receivers
signals.pre_save.connect(sender=Person, receiver=pre_save_receiver)
signals.post_save.connect(sender=Person, receiver=post_save_receiver)
signals.pre_delete.connect(sender=Person, receiver=pre_delete_receiver)
signals.post_delete.connect(sender=Person, receiver=post_delete_receiver)
p = Person.objects.create(name='Darth Vader')
# Save and test receivers got calls
p.save()
self.assertEqual(pre_save_receiver._database, DEFAULT_DB_ALIAS)
self.assertEqual(post_save_receiver._database, DEFAULT_DB_ALIAS)
# Delete, and test
p.delete()
self.assertEqual(pre_delete_receiver._database, DEFAULT_DB_ALIAS)
self.assertEqual(post_delete_receiver._database, DEFAULT_DB_ALIAS)
# Save again to a different database
p.save(using="other")
self.assertEqual(pre_save_receiver._database, "other")
self.assertEqual(post_save_receiver._database, "other")
# Delete, and test
p.delete(using="other")
self.assertEqual(pre_delete_receiver._database, "other")
self.assertEqual(post_delete_receiver._database, "other")
signals.pre_save.disconnect(sender=Person, receiver=pre_save_receiver)
signals.post_save.disconnect(sender=Person, receiver=post_save_receiver)
signals.pre_delete.disconnect(sender=Person, receiver=pre_delete_receiver)
signals.post_delete.disconnect(sender=Person, receiver=post_delete_receiver)
def test_database_arg_m2m(self):
"""
Test that the m2m_changed signal has a correct database arg (#13552)
"""
# Make a receiver
receiver = DatabaseReceiver()
# Connect it
signals.m2m_changed.connect(receiver=receiver)
# Create the models that will be used for the tests
b = Book.objects.create(title="Pro Django",
published=datetime.date(2008, 12, 16))
p = Person.objects.create(name="Marty Alchin")
# Create a copy of the models on the 'other' database to prevent
# integrity errors on backends that don't defer constraints checks
Book.objects.using('other').create(pk=b.pk, title=b.title,
published=b.published)
Person.objects.using('other').create(pk=p.pk, name=p.name)
# Test addition
b.authors.add(p)
self.assertEqual(receiver._database, DEFAULT_DB_ALIAS)
with self.override_router():
b.authors.add(p)
self.assertEqual(receiver._database, "other")
# Test removal
b.authors.remove(p)
self.assertEqual(receiver._database, DEFAULT_DB_ALIAS)
with self.override_router():
b.authors.remove(p)
self.assertEqual(receiver._database, "other")
# Test addition in reverse
p.book_set.add(b)
self.assertEqual(receiver._database, DEFAULT_DB_ALIAS)
with self.override_router():
p.book_set.add(b)
self.assertEqual(receiver._database, "other")
# Test clearing
b.authors.clear()
self.assertEqual(receiver._database, DEFAULT_DB_ALIAS)
with self.override_router():
b.authors.clear()
self.assertEqual(receiver._database, "other")
class AttributeErrorRouter(object):
"A router to test the exception handling of ConnectionRouter"
def db_for_read(self, model, **hints):
raise AttributeError
def db_for_write(self, model, **hints):
raise AttributeError
class RouterAttributeErrorTestCase(TestCase):
multi_db = True
def override_router(self):
return override_settings(DATABASE_ROUTERS=[AttributeErrorRouter()])
def test_attribute_error_read(self):
"Check that the AttributeError from AttributeErrorRouter bubbles up"
b = Book.objects.create(title="Pro Django",
published=datetime.date(2008, 12, 16))
with self.override_router():
with self.assertRaises(AttributeError):
Book.objects.get(pk=b.pk)
def test_attribute_error_save(self):
"Check that the AttributeError from AttributeErrorRouter bubbles up"
dive = Book()
dive.title = "Dive into Python"
dive.published = datetime.date(2009, 5, 4)
with self.override_router():
with self.assertRaises(AttributeError):
dive.save()
def test_attribute_error_delete(self):
"Check that the AttributeError from AttributeErrorRouter bubbles up"
b = Book.objects.create(title="Pro Django",
published=datetime.date(2008, 12, 16))
p = Person.objects.create(name="Marty Alchin")
b.authors.set([p])
b.editor = p
with self.override_router():
with self.assertRaises(AttributeError):
b.delete()
def test_attribute_error_m2m(self):
"Check that the AttributeError from AttributeErrorRouter bubbles up"
b = Book.objects.create(title="Pro Django",
published=datetime.date(2008, 12, 16))
p = Person.objects.create(name="Marty Alchin")
with self.override_router():
with self.assertRaises(AttributeError):
b.authors.set([p])
class ModelMetaRouter(object):
"A router to ensure model arguments are real model classes"
def db_for_write(self, model, **hints):
if not hasattr(model, '_meta'):
raise ValueError
@override_settings(DATABASE_ROUTERS=[ModelMetaRouter()])
class RouterModelArgumentTestCase(TestCase):
multi_db = True
def test_m2m_collection(self):
b = Book.objects.create(title="Pro Django",
published=datetime.date(2008, 12, 16))
p = Person.objects.create(name="Marty Alchin")
# test add
b.authors.add(p)
# test remove
b.authors.remove(p)
# test clear
b.authors.clear()
# test setattr
b.authors.set([p])
# test M2M collection
b.delete()
def test_foreignkey_collection(self):
person = Person.objects.create(name='Bob')
Pet.objects.create(owner=person, name='Wart')
# test related FK collection
person.delete()
class SyncOnlyDefaultDatabaseRouter(object):
def allow_migrate(self, db, app_label, **hints):
return db == DEFAULT_DB_ALIAS
class MigrateTestCase(TestCase):
available_apps = [
'multiple_database',
'django.contrib.auth',
'django.contrib.contenttypes'
]
multi_db = True
def test_migrate_to_other_database(self):
"""Regression test for #16039: migrate with --database option."""
cts = ContentType.objects.using('other').filter(app_label='multiple_database')
count = cts.count()
self.assertGreater(count, 0)
cts.delete()
management.call_command('migrate', verbosity=0, interactive=False, database='other')
self.assertEqual(cts.count(), count)
def test_migrate_to_other_database_with_router(self):
"""Regression test for #16039: migrate with --database option."""
cts = ContentType.objects.using('other').filter(app_label='multiple_database')
cts.delete()
with override_settings(DATABASE_ROUTERS=[SyncOnlyDefaultDatabaseRouter()]):
management.call_command('migrate', verbosity=0, interactive=False, database='other')
self.assertEqual(cts.count(), 0)
class RouterUsed(Exception):
WRITE = 'write'
def __init__(self, mode, model, hints):
self.mode = mode
self.model = model
self.hints = hints
class RouteForWriteTestCase(TestCase):
multi_db = True
class WriteCheckRouter(object):
def db_for_write(self, model, **hints):
raise RouterUsed(mode=RouterUsed.WRITE, model=model, hints=hints)
def override_router(self):
return override_settings(DATABASE_ROUTERS=[RouteForWriteTestCase.WriteCheckRouter()])
def test_fk_delete(self):
owner = Person.objects.create(name='Someone')
pet = Pet.objects.create(name='fido', owner=owner)
with self.assertRaises(RouterUsed) as cm:
with self.override_router():
pet.owner.delete()
e = cm.exception
self.assertEqual(e.mode, RouterUsed.WRITE)
self.assertEqual(e.model, Person)
self.assertEqual(e.hints, {'instance': owner})
def test_reverse_fk_delete(self):
owner = Person.objects.create(name='Someone')
to_del_qs = owner.pet_set.all()
with self.assertRaises(RouterUsed) as cm:
with self.override_router():
to_del_qs.delete()
e = cm.exception
self.assertEqual(e.mode, RouterUsed.WRITE)
self.assertEqual(e.model, Pet)
self.assertEqual(e.hints, {'instance': owner})
def test_reverse_fk_get_or_create(self):
owner = Person.objects.create(name='Someone')
with self.assertRaises(RouterUsed) as cm:
with self.override_router():
owner.pet_set.get_or_create(name='fido')
e = cm.exception
self.assertEqual(e.mode, RouterUsed.WRITE)
self.assertEqual(e.model, Pet)
self.assertEqual(e.hints, {'instance': owner})
def test_reverse_fk_update(self):
owner = Person.objects.create(name='Someone')
Pet.objects.create(name='fido', owner=owner)
with self.assertRaises(RouterUsed) as cm:
with self.override_router():
owner.pet_set.update(name='max')
e = cm.exception
self.assertEqual(e.mode, RouterUsed.WRITE)
self.assertEqual(e.model, Pet)
self.assertEqual(e.hints, {'instance': owner})
def test_m2m_add(self):
auth = Person.objects.create(name='Someone')
book = Book.objects.create(title="Pro Django",
published=datetime.date(2008, 12, 16))
with self.assertRaises(RouterUsed) as cm:
with self.override_router():
book.authors.add(auth)
e = cm.exception
self.assertEqual(e.mode, RouterUsed.WRITE)
self.assertEqual(e.model, Book.authors.through)
self.assertEqual(e.hints, {'instance': book})
def test_m2m_clear(self):
auth = Person.objects.create(name='Someone')
book = Book.objects.create(title="Pro Django",
published=datetime.date(2008, 12, 16))
book.authors.add(auth)
with self.assertRaises(RouterUsed) as cm:
with self.override_router():
book.authors.clear()
e = cm.exception
self.assertEqual(e.mode, RouterUsed.WRITE)
self.assertEqual(e.model, Book.authors.through)
self.assertEqual(e.hints, {'instance': book})
def test_m2m_delete(self):
auth = Person.objects.create(name='Someone')
book = Book.objects.create(title="Pro Django",
published=datetime.date(2008, 12, 16))
book.authors.add(auth)
with self.assertRaises(RouterUsed) as cm:
with self.override_router():
book.authors.all().delete()
e = cm.exception
self.assertEqual(e.mode, RouterUsed.WRITE)
self.assertEqual(e.model, Person)
self.assertEqual(e.hints, {'instance': book})
def test_m2m_get_or_create(self):
Person.objects.create(name='Someone')
book = Book.objects.create(title="Pro Django",
published=datetime.date(2008, 12, 16))
with self.assertRaises(RouterUsed) as cm:
with self.override_router():
book.authors.get_or_create(name='Someone else')
e = cm.exception
self.assertEqual(e.mode, RouterUsed.WRITE)
self.assertEqual(e.model, Book)
self.assertEqual(e.hints, {'instance': book})
def test_m2m_remove(self):
auth = Person.objects.create(name='Someone')
book = Book.objects.create(title="Pro Django",
published=datetime.date(2008, 12, 16))
book.authors.add(auth)
with self.assertRaises(RouterUsed) as cm:
with self.override_router():
book.authors.remove(auth)
e = cm.exception
self.assertEqual(e.mode, RouterUsed.WRITE)
self.assertEqual(e.model, Book.authors.through)
self.assertEqual(e.hints, {'instance': book})
def test_m2m_update(self):
auth = Person.objects.create(name='Someone')
book = Book.objects.create(title="Pro Django",
published=datetime.date(2008, 12, 16))
book.authors.add(auth)
with self.assertRaises(RouterUsed) as cm:
with self.override_router():
book.authors.all().update(name='Different')
e = cm.exception
self.assertEqual(e.mode, RouterUsed.WRITE)
self.assertEqual(e.model, Person)
self.assertEqual(e.hints, {'instance': book})
def test_reverse_m2m_add(self):
auth = Person.objects.create(name='Someone')
book = Book.objects.create(title="Pro Django",
published=datetime.date(2008, 12, 16))
with self.assertRaises(RouterUsed) as cm:
with self.override_router():
auth.book_set.add(book)
e = cm.exception
self.assertEqual(e.mode, RouterUsed.WRITE)
self.assertEqual(e.model, Book.authors.through)
self.assertEqual(e.hints, {'instance': auth})
def test_reverse_m2m_clear(self):
auth = Person.objects.create(name='Someone')
book = Book.objects.create(title="Pro Django",
published=datetime.date(2008, 12, 16))
book.authors.add(auth)
with self.assertRaises(RouterUsed) as cm:
with self.override_router():
auth.book_set.clear()
e = cm.exception
self.assertEqual(e.mode, RouterUsed.WRITE)
self.assertEqual(e.model, Book.authors.through)
self.assertEqual(e.hints, {'instance': auth})
def test_reverse_m2m_delete(self):
auth = Person.objects.create(name='Someone')
book = Book.objects.create(title="Pro Django",
published=datetime.date(2008, 12, 16))
book.authors.add(auth)
with self.assertRaises(RouterUsed) as cm:
with self.override_router():
auth.book_set.all().delete()
e = cm.exception
self.assertEqual(e.mode, RouterUsed.WRITE)
self.assertEqual(e.model, Book)
self.assertEqual(e.hints, {'instance': auth})
def test_reverse_m2m_get_or_create(self):
auth = Person.objects.create(name='Someone')
Book.objects.create(title="Pro Django",
published=datetime.date(2008, 12, 16))
with self.assertRaises(RouterUsed) as cm:
with self.override_router():
auth.book_set.get_or_create(title="New Book", published=datetime.datetime.now())
e = cm.exception
self.assertEqual(e.mode, RouterUsed.WRITE)
self.assertEqual(e.model, Person)
self.assertEqual(e.hints, {'instance': auth})
def test_reverse_m2m_remove(self):
auth = Person.objects.create(name='Someone')
book = Book.objects.create(title="Pro Django",
published=datetime.date(2008, 12, 16))
book.authors.add(auth)
with self.assertRaises(RouterUsed) as cm:
with self.override_router():
auth.book_set.remove(book)
e = cm.exception
self.assertEqual(e.mode, RouterUsed.WRITE)
self.assertEqual(e.model, Book.authors.through)
self.assertEqual(e.hints, {'instance': auth})
def test_reverse_m2m_update(self):
auth = Person.objects.create(name='Someone')
book = Book.objects.create(title="Pro Django",
published=datetime.date(2008, 12, 16))
book.authors.add(auth)
with self.assertRaises(RouterUsed) as cm:
with self.override_router():
auth.book_set.all().update(title='Different')
e = cm.exception
self.assertEqual(e.mode, RouterUsed.WRITE)
self.assertEqual(e.model, Book)
self.assertEqual(e.hints, {'instance': auth})
|
wubr2000/googleads-python-lib | refs/heads/master | examples/dfp/v201411/activity_group_service/get_active_activity_groups.py | 4 | #!/usr/bin/python
#
# Copyright 2014 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This code example gets all active activity groups.
To create activity groups, run create_activity_groups.py.
The LoadFromStorage method is pulling credentials and properties from a
"googleads.yaml" file. By default, it looks for this file in your home
directory. For more information, see the "Caching authentication information"
section of our README.
"""
# Import appropriate modules from the client library.
from googleads import dfp
def main(client):
# Initialize appropriate service.
activity_group_service = client.GetService('ActivityGroupService',
version='v201411')
# Create statement object to only select active activity groups.
values = [{
'key': 'status',
'value': {
'xsi_type': 'TextValue',
'value': 'ACTIVE'
}
}]
query = 'WHERE status = :status'
# Create a filter statement.
statement = dfp.FilterStatement(query, values)
# Get activity groups by statement.
while True:
response = activity_group_service.getActivityGroupsByStatement(
statement.ToStatement())
if 'results' in response:
# Display results.
for activity_group in response['results']:
print ('Activity group with ID \'%s\' and name \'%s\' was found.'
% (activity_group['id'], activity_group['name']))
statement.offset += dfp.SUGGESTED_PAGE_LIMIT
else:
break
print '\nNumber of results found: %s' % response['totalResultSetSize']
if __name__ == '__main__':
# Initialize client object.
dfp_client = dfp.DfpClient.LoadFromStorage()
main(dfp_client)
|
bbmt-bbmt/MagretUtilQT | refs/heads/master | logger.py | 1 | # -*- coding: utf-8 -*-
import logging
import logging.handlers
from threading import Thread
from PyQt5 import QtWidgets
from PyQt5.QtCore import *
from UILog import Ui_log_dialog
import re
# classe qui initialise le logger pour le process courant et
# qui lance un thread qui va permettre de logger les autres processus
# variable qui permet de fixer la queue utiliser par le logger
# utile pour le passer aux autre process
log_queue = None
class LogListenerThread(Thread):
def __init__(self, level, log_queue, ui_log):
super().__init__()
self.log_queue = log_queue
log_queue = log_queue
root = logging.getLogger()
h1 = logging.handlers.RotatingFileHandler('activity.log', 'a', 1000000, 1)
h1.setLevel(level)
h2 = QtHandler(ui_log)
h2.setLevel(level)
f = logging.Formatter('%(asctime)s :: %(name)s :: %(levelname)s :: %(message)s')
h1.setFormatter(f)
h2.setFormatter(f)
root.addHandler(h1)
root.addHandler(h2)
root.setLevel(level)
return
def run(self):
while True:
try:
record = self.log_queue.get()
if record is None:
break
logger = logging.getLogger(record.name)
logger.handle(record)
except Exception as e:
print("merde", e)
return
class QtHandler(logging.Handler):
"""Permet d'envoyer les log dans une fenetre dediée: ui_log_dialog"""
def __init__(self, ui_log):
super().__init__()
self.ui_log = ui_log
self.ui_log.log_text_edit.setReadOnly(True)
def emit(self, record):
msg = self.format(record)
self.ui_log.write_msg.emit(msg)
class ui_log_dialog(Ui_log_dialog, QtWidgets.QDialog):
"""fenetre qui va recevoir les log du logger"""
write_msg = pyqtSignal(str)
def __init__(self):
super().__init__()
self.setupUi(self)
self.text = []
self.stop_start_button.setText("Stop")
self.write_msg.connect(self.write_text)
self.regex_edit1.textChanged.connect(self.on_text_changed)
self.regex_edit2.textChanged.connect(self.on_text_changed)
self.stop_start_button.clicked.connect(self.on_stop_start_button_clicked)
return
def on_stop_start_button_clicked(self):
if self.stop_start_button.text() == "Stop":
self.write_msg.disconnect()
self.stop_start_button.setText("Start")
else:
self.write_msg.connect(self.write_text)
self.stop_start_button.setText("Stop")
return
def write_text(self, msg):
self.error_label1.setText("")
self.error_label2.setText("")
if msg != "":
self.text.append(msg)
expression1 = self.regex_edit1.text().strip()
expression2 = self.regex_edit2.text().strip()
max_line = self.max_line.value()
len_text = len(self.text)
if len_text >= max_line:
self.text = self.text[len_text - max_line+1:]
if expression1 != "":
try:
text = [line for line in self.text if re.search(expression1, line)]
except Exception:
text = ""
self.error_label1.setText('<span style=\" color:#ff0000;\">%s</span>' % "regex error")
if expression2 != "":
try:
text = [line for line in text if re.search(expression2, line)]
except Exception:
text = ""
self.error_label2.setText('<span style=\" color:#ff0000;\">%s</span>' % "regex error")
else:
text = self.text
self.log_text_edit.setPlainText("\n".join(text))
self.log_text_edit.verticalScrollBar().setValue(self.log_text_edit.verticalScrollBar().maximum())
return
def on_text_changed(self, txt):
self.write_text("")
return
|
ujdhesa/unisubs | refs/heads/staging | apps/comments/admin.py | 7 | # Amara, universalsubtitles.org
#
# Copyright (C) 2013 Participatory Culture Foundation
#
# 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/agpl-3.0.html.
from django.contrib import admin
from comments.models import Comment
class CommentAdmin(admin.ModelAdmin):
list_display = ('content_object', 'user', 'submit_date')
list_filter = ('content_type', 'submit_date')
raw_id_fields = ('user', 'reply_to')
admin.site.register(Comment, CommentAdmin)
|
olgabot/prettyplotlib | refs/heads/master | prettyplotlib/_fill_betweenx.py | 1 | __author__ = 'olga'
from prettyplotlib.utils import remove_chartjunk, maybe_get_ax, maybe_get_linewidth
from prettyplotlib.colors import almost_black, pretty
from itertools import cycle
import matplotlib as mpl
@pretty
def fill_betweenx(*args, **kwargs):
ax, args, kwargs = maybe_get_ax(*args, **kwargs)
lw = maybe_get_linewidth(**kwargs)
kwargs['linewidths'] = lw
if 'color' not in kwargs:
# if no color is specified, cycle over the ones in this axis
color_cycle = cycle(mpl.rcParams['axes.color_cycle'])
kwargs['color'] = next(color_cycle)
kwargs.setdefault('edgecolor', almost_black)
show_ticks = kwargs.pop('show_ticks', False)
lines = ax.fill_betweenx(*args, **kwargs)
remove_chartjunk(ax, ['top', 'right'], show_ticks=show_ticks)
return lines
|
emilio/servo | refs/heads/master | tests/wpt/web-platform-tests/tools/third_party/pytest/testing/test_pdb.py | 30 | from __future__ import absolute_import, division, print_function
import sys
import platform
import os
import _pytest._code
from _pytest.debugging import SUPPORTS_BREAKPOINT_BUILTIN
import pytest
_ENVIRON_PYTHONBREAKPOINT = os.environ.get("PYTHONBREAKPOINT", "")
def runpdb_and_get_report(testdir, source):
p = testdir.makepyfile(source)
result = testdir.runpytest_inprocess("--pdb", p)
reports = result.reprec.getreports("pytest_runtest_logreport")
assert len(reports) == 3, reports # setup/call/teardown
return reports[1]
@pytest.fixture
def custom_pdb_calls():
called = []
# install dummy debugger class and track which methods were called on it
class _CustomPdb(object):
def __init__(self, *args, **kwargs):
called.append("init")
def reset(self):
called.append("reset")
def interaction(self, *args):
called.append("interaction")
_pytest._CustomPdb = _CustomPdb
return called
@pytest.fixture
def custom_debugger_hook():
called = []
# install dummy debugger class and track which methods were called on it
class _CustomDebugger(object):
def __init__(self, *args, **kwargs):
called.append("init")
def reset(self):
called.append("reset")
def interaction(self, *args):
called.append("interaction")
def set_trace(self, frame):
print("**CustomDebugger**")
called.append("set_trace")
_pytest._CustomDebugger = _CustomDebugger
yield called
del _pytest._CustomDebugger
class TestPDB(object):
@pytest.fixture
def pdblist(self, request):
monkeypatch = request.getfixturevalue("monkeypatch")
pdblist = []
def mypdb(*args):
pdblist.append(args)
plugin = request.config.pluginmanager.getplugin("debugging")
monkeypatch.setattr(plugin, "post_mortem", mypdb)
return pdblist
def test_pdb_on_fail(self, testdir, pdblist):
rep = runpdb_and_get_report(
testdir,
"""
def test_func():
assert 0
""",
)
assert rep.failed
assert len(pdblist) == 1
tb = _pytest._code.Traceback(pdblist[0][0])
assert tb[-1].name == "test_func"
def test_pdb_on_xfail(self, testdir, pdblist):
rep = runpdb_and_get_report(
testdir,
"""
import pytest
@pytest.mark.xfail
def test_func():
assert 0
""",
)
assert "xfail" in rep.keywords
assert not pdblist
def test_pdb_on_skip(self, testdir, pdblist):
rep = runpdb_and_get_report(
testdir,
"""
import pytest
def test_func():
pytest.skip("hello")
""",
)
assert rep.skipped
assert len(pdblist) == 0
def test_pdb_on_BdbQuit(self, testdir, pdblist):
rep = runpdb_and_get_report(
testdir,
"""
import bdb
def test_func():
raise bdb.BdbQuit
""",
)
assert rep.failed
assert len(pdblist) == 0
def test_pdb_on_KeyboardInterrupt(self, testdir, pdblist):
rep = runpdb_and_get_report(
testdir,
"""
def test_func():
raise KeyboardInterrupt
""",
)
assert rep.failed
assert len(pdblist) == 1
def test_pdb_interaction(self, testdir):
p1 = testdir.makepyfile(
"""
def test_1():
i = 0
assert i == 1
"""
)
child = testdir.spawn_pytest("--pdb %s" % p1)
child.expect(".*def test_1")
child.expect(".*i = 0")
child.expect("(Pdb)")
child.sendeof()
rest = child.read().decode("utf8")
assert "1 failed" in rest
assert "def test_1" not in rest
self.flush(child)
@staticmethod
def flush(child):
if platform.system() == "Darwin":
return
if child.isalive():
child.wait()
def test_pdb_unittest_postmortem(self, testdir):
p1 = testdir.makepyfile(
"""
import unittest
class Blub(unittest.TestCase):
def tearDown(self):
self.filename = None
def test_false(self):
self.filename = 'debug' + '.me'
assert 0
"""
)
child = testdir.spawn_pytest("--pdb %s" % p1)
child.expect("(Pdb)")
child.sendline("p self.filename")
child.sendeof()
rest = child.read().decode("utf8")
assert "debug.me" in rest
self.flush(child)
def test_pdb_unittest_skip(self, testdir):
"""Test for issue #2137"""
p1 = testdir.makepyfile(
"""
import unittest
@unittest.skipIf(True, 'Skipping also with pdb active')
class MyTestCase(unittest.TestCase):
def test_one(self):
assert 0
"""
)
child = testdir.spawn_pytest("-rs --pdb %s" % p1)
child.expect("Skipping also with pdb active")
child.expect("1 skipped in")
child.sendeof()
self.flush(child)
def test_pdb_print_captured_stdout(self, testdir):
p1 = testdir.makepyfile(
"""
def test_1():
print("get\\x20rekt")
assert False
"""
)
child = testdir.spawn_pytest("--pdb %s" % p1)
child.expect("captured stdout")
child.expect("get rekt")
child.expect("(Pdb)")
child.sendeof()
rest = child.read().decode("utf8")
assert "1 failed" in rest
assert "get rekt" not in rest
self.flush(child)
def test_pdb_print_captured_stderr(self, testdir):
p1 = testdir.makepyfile(
"""
def test_1():
import sys
sys.stderr.write("get\\x20rekt")
assert False
"""
)
child = testdir.spawn_pytest("--pdb %s" % p1)
child.expect("captured stderr")
child.expect("get rekt")
child.expect("(Pdb)")
child.sendeof()
rest = child.read().decode("utf8")
assert "1 failed" in rest
assert "get rekt" not in rest
self.flush(child)
def test_pdb_dont_print_empty_captured_stdout_and_stderr(self, testdir):
p1 = testdir.makepyfile(
"""
def test_1():
assert False
"""
)
child = testdir.spawn_pytest("--pdb %s" % p1)
child.expect("(Pdb)")
output = child.before.decode("utf8")
child.sendeof()
assert "captured stdout" not in output
assert "captured stderr" not in output
self.flush(child)
@pytest.mark.parametrize("showcapture", ["all", "no", "log"])
def test_pdb_print_captured_logs(self, testdir, showcapture):
p1 = testdir.makepyfile(
"""
def test_1():
import logging
logging.warn("get " + "rekt")
assert False
"""
)
child = testdir.spawn_pytest("--show-capture=%s --pdb %s" % (showcapture, p1))
if showcapture in ("all", "log"):
child.expect("captured log")
child.expect("get rekt")
child.expect("(Pdb)")
child.sendeof()
rest = child.read().decode("utf8")
assert "1 failed" in rest
self.flush(child)
def test_pdb_print_captured_logs_nologging(self, testdir):
p1 = testdir.makepyfile(
"""
def test_1():
import logging
logging.warn("get " + "rekt")
assert False
"""
)
child = testdir.spawn_pytest(
"--show-capture=all --pdb " "-p no:logging %s" % p1
)
child.expect("get rekt")
output = child.before.decode("utf8")
assert "captured log" not in output
child.expect("(Pdb)")
child.sendeof()
rest = child.read().decode("utf8")
assert "1 failed" in rest
self.flush(child)
def test_pdb_interaction_exception(self, testdir):
p1 = testdir.makepyfile(
"""
import pytest
def globalfunc():
pass
def test_1():
pytest.raises(ValueError, globalfunc)
"""
)
child = testdir.spawn_pytest("--pdb %s" % p1)
child.expect(".*def test_1")
child.expect(".*pytest.raises.*globalfunc")
child.expect("(Pdb)")
child.sendline("globalfunc")
child.expect(".*function")
child.sendeof()
child.expect("1 failed")
self.flush(child)
def test_pdb_interaction_on_collection_issue181(self, testdir):
p1 = testdir.makepyfile(
"""
import pytest
xxx
"""
)
child = testdir.spawn_pytest("--pdb %s" % p1)
# child.expect(".*import pytest.*")
child.expect("(Pdb)")
child.sendeof()
child.expect("1 error")
self.flush(child)
def test_pdb_interaction_on_internal_error(self, testdir):
testdir.makeconftest(
"""
def pytest_runtest_protocol():
0/0
"""
)
p1 = testdir.makepyfile("def test_func(): pass")
child = testdir.spawn_pytest("--pdb %s" % p1)
# child.expect(".*import pytest.*")
child.expect("(Pdb)")
child.sendeof()
self.flush(child)
def test_pdb_interaction_capturing_simple(self, testdir):
p1 = testdir.makepyfile(
"""
import pytest
def test_1():
i = 0
print ("hello17")
pytest.set_trace()
x = 3
"""
)
child = testdir.spawn_pytest(str(p1))
child.expect("test_1")
child.expect("x = 3")
child.expect("(Pdb)")
child.sendeof()
rest = child.read().decode("utf-8")
assert "1 failed" in rest
assert "def test_1" in rest
assert "hello17" in rest # out is captured
self.flush(child)
def test_pdb_set_trace_interception(self, testdir):
p1 = testdir.makepyfile(
"""
import pdb
def test_1():
pdb.set_trace()
"""
)
child = testdir.spawn_pytest(str(p1))
child.expect("test_1")
child.expect("(Pdb)")
child.sendeof()
rest = child.read().decode("utf8")
assert "1 failed" in rest
assert "reading from stdin while output" not in rest
self.flush(child)
def test_pdb_and_capsys(self, testdir):
p1 = testdir.makepyfile(
"""
import pytest
def test_1(capsys):
print ("hello1")
pytest.set_trace()
"""
)
child = testdir.spawn_pytest(str(p1))
child.expect("test_1")
child.send("capsys.readouterr()\n")
child.expect("hello1")
child.sendeof()
child.read()
self.flush(child)
def test_set_trace_capturing_afterwards(self, testdir):
p1 = testdir.makepyfile(
"""
import pdb
def test_1():
pdb.set_trace()
def test_2():
print ("hello")
assert 0
"""
)
child = testdir.spawn_pytest(str(p1))
child.expect("test_1")
child.send("c\n")
child.expect("test_2")
child.expect("Captured")
child.expect("hello")
child.sendeof()
child.read()
self.flush(child)
def test_pdb_interaction_doctest(self, testdir):
p1 = testdir.makepyfile(
"""
import pytest
def function_1():
'''
>>> i = 0
>>> assert i == 1
'''
"""
)
child = testdir.spawn_pytest("--doctest-modules --pdb %s" % p1)
child.expect("(Pdb)")
child.sendline("i")
child.expect("0")
child.expect("(Pdb)")
child.sendeof()
rest = child.read().decode("utf8")
assert "1 failed" in rest
self.flush(child)
def test_pdb_interaction_capturing_twice(self, testdir):
p1 = testdir.makepyfile(
"""
import pytest
def test_1():
i = 0
print ("hello17")
pytest.set_trace()
x = 3
print ("hello18")
pytest.set_trace()
x = 4
"""
)
child = testdir.spawn_pytest(str(p1))
child.expect("test_1")
child.expect("x = 3")
child.expect("(Pdb)")
child.sendline("c")
child.expect("x = 4")
child.sendeof()
rest = child.read().decode("utf8")
assert "1 failed" in rest
assert "def test_1" in rest
assert "hello17" in rest # out is captured
assert "hello18" in rest # out is captured
self.flush(child)
def test_pdb_used_outside_test(self, testdir):
p1 = testdir.makepyfile(
"""
import pytest
pytest.set_trace()
x = 5
"""
)
child = testdir.spawn("%s %s" % (sys.executable, p1))
child.expect("x = 5")
child.sendeof()
self.flush(child)
def test_pdb_used_in_generate_tests(self, testdir):
p1 = testdir.makepyfile(
"""
import pytest
def pytest_generate_tests(metafunc):
pytest.set_trace()
x = 5
def test_foo(a):
pass
"""
)
child = testdir.spawn_pytest(str(p1))
child.expect("x = 5")
child.sendeof()
self.flush(child)
def test_pdb_collection_failure_is_shown(self, testdir):
p1 = testdir.makepyfile("xxx")
result = testdir.runpytest_subprocess("--pdb", p1)
result.stdout.fnmatch_lines(["*NameError*xxx*", "*1 error*"])
def test_enter_pdb_hook_is_called(self, testdir):
testdir.makeconftest(
"""
def pytest_enter_pdb(config):
assert config.testing_verification == 'configured'
print 'enter_pdb_hook'
def pytest_configure(config):
config.testing_verification = 'configured'
"""
)
p1 = testdir.makepyfile(
"""
import pytest
def test_foo():
pytest.set_trace()
"""
)
child = testdir.spawn_pytest(str(p1))
child.expect("enter_pdb_hook")
child.send("c\n")
child.sendeof()
self.flush(child)
def test_pdb_custom_cls(self, testdir, custom_pdb_calls):
p1 = testdir.makepyfile("""xxx """)
result = testdir.runpytest_inprocess("--pdb", "--pdbcls=_pytest:_CustomPdb", p1)
result.stdout.fnmatch_lines(["*NameError*xxx*", "*1 error*"])
assert custom_pdb_calls == ["init", "reset", "interaction"]
def test_pdb_custom_cls_without_pdb(self, testdir, custom_pdb_calls):
p1 = testdir.makepyfile("""xxx """)
result = testdir.runpytest_inprocess("--pdbcls=_pytest:_CustomPdb", p1)
result.stdout.fnmatch_lines(["*NameError*xxx*", "*1 error*"])
assert custom_pdb_calls == []
def test_pdb_custom_cls_with_settrace(self, testdir, monkeypatch):
testdir.makepyfile(
custom_pdb="""
class CustomPdb(object):
def set_trace(*args, **kwargs):
print 'custom set_trace>'
"""
)
p1 = testdir.makepyfile(
"""
import pytest
def test_foo():
pytest.set_trace()
"""
)
monkeypatch.setenv("PYTHONPATH", str(testdir.tmpdir))
child = testdir.spawn_pytest("--pdbcls=custom_pdb:CustomPdb %s" % str(p1))
child.expect("custom set_trace>")
self.flush(child)
class TestDebuggingBreakpoints(object):
def test_supports_breakpoint_module_global(self):
"""
Test that supports breakpoint global marks on Python 3.7+ and not on
CPython 3.5, 2.7
"""
if sys.version_info.major == 3 and sys.version_info.minor >= 7:
assert SUPPORTS_BREAKPOINT_BUILTIN is True
if sys.version_info.major == 3 and sys.version_info.minor == 5:
assert SUPPORTS_BREAKPOINT_BUILTIN is False
if sys.version_info.major == 2 and sys.version_info.minor == 7:
assert SUPPORTS_BREAKPOINT_BUILTIN is False
@pytest.mark.skipif(
not SUPPORTS_BREAKPOINT_BUILTIN, reason="Requires breakpoint() builtin"
)
@pytest.mark.parametrize("arg", ["--pdb", ""])
def test_sys_breakpointhook_configure_and_unconfigure(self, testdir, arg):
"""
Test that sys.breakpointhook is set to the custom Pdb class once configured, test that
hook is reset to system value once pytest has been unconfigured
"""
testdir.makeconftest(
"""
import sys
from pytest import hookimpl
from _pytest.debugging import pytestPDB
def pytest_configure(config):
config._cleanup.append(check_restored)
def check_restored():
assert sys.breakpointhook == sys.__breakpointhook__
def test_check():
assert sys.breakpointhook == pytestPDB.set_trace
"""
)
testdir.makepyfile(
"""
def test_nothing(): pass
"""
)
args = (arg,) if arg else ()
result = testdir.runpytest_subprocess(*args)
result.stdout.fnmatch_lines(["*1 passed in *"])
@pytest.mark.skipif(
not SUPPORTS_BREAKPOINT_BUILTIN, reason="Requires breakpoint() builtin"
)
def test_pdb_custom_cls(self, testdir, custom_debugger_hook):
p1 = testdir.makepyfile(
"""
def test_nothing():
breakpoint()
"""
)
result = testdir.runpytest_inprocess(
"--pdb", "--pdbcls=_pytest:_CustomDebugger", p1
)
result.stdout.fnmatch_lines(["*CustomDebugger*", "*1 passed*"])
assert custom_debugger_hook == ["init", "set_trace"]
@pytest.mark.parametrize("arg", ["--pdb", ""])
@pytest.mark.skipif(
not SUPPORTS_BREAKPOINT_BUILTIN, reason="Requires breakpoint() builtin"
)
def test_environ_custom_class(self, testdir, custom_debugger_hook, arg):
testdir.makeconftest(
"""
import os
import sys
os.environ['PYTHONBREAKPOINT'] = '_pytest._CustomDebugger.set_trace'
def pytest_configure(config):
config._cleanup.append(check_restored)
def check_restored():
assert sys.breakpointhook == sys.__breakpointhook__
def test_check():
import _pytest
assert sys.breakpointhook is _pytest._CustomDebugger.set_trace
"""
)
testdir.makepyfile(
"""
def test_nothing(): pass
"""
)
args = (arg,) if arg else ()
result = testdir.runpytest_subprocess(*args)
result.stdout.fnmatch_lines(["*1 passed in *"])
@pytest.mark.skipif(
not SUPPORTS_BREAKPOINT_BUILTIN, reason="Requires breakpoint() builtin"
)
@pytest.mark.skipif(
not _ENVIRON_PYTHONBREAKPOINT == "",
reason="Requires breakpoint() default value",
)
def test_sys_breakpoint_interception(self, testdir):
p1 = testdir.makepyfile(
"""
def test_1():
breakpoint()
"""
)
child = testdir.spawn_pytest(str(p1))
child.expect("test_1")
child.expect("(Pdb)")
child.sendeof()
rest = child.read().decode("utf8")
assert "1 failed" in rest
assert "reading from stdin while output" not in rest
TestPDB.flush(child)
@pytest.mark.skipif(
not SUPPORTS_BREAKPOINT_BUILTIN, reason="Requires breakpoint() builtin"
)
def test_pdb_not_altered(self, testdir):
p1 = testdir.makepyfile(
"""
import pdb
def test_1():
pdb.set_trace()
"""
)
child = testdir.spawn_pytest(str(p1))
child.expect("test_1")
child.expect("(Pdb)")
child.sendeof()
rest = child.read().decode("utf8")
assert "1 failed" in rest
assert "reading from stdin while output" not in rest
TestPDB.flush(child)
|
carlcarl/PyGithub | refs/heads/master | github/tests/IssueEvent.py | 39 | # -*- coding: utf-8 -*-
# ########################## Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <[email protected]> #
# Copyright 2012 Zearin <[email protected]> #
# Copyright 2013 Vincent Jacques <[email protected]> #
# #
# This file is part of PyGithub. http://jacquev6.github.com/PyGithub/ #
# #
# PyGithub 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. #
# #
# PyGithub 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 PyGithub. If not, see <http://www.gnu.org/licenses/>. #
# #
# ##############################################################################
import Framework
import datetime
class IssueEvent(Framework.TestCase):
def setUp(self):
Framework.TestCase.setUp(self)
self.event = self.g.get_user().get_repo("PyGithub").get_issues_event(16348656)
def testAttributes(self):
self.assertEqual(self.event.actor.login, "jacquev6")
self.assertEqual(self.event.commit_id, "ed866fc43833802ab553e5ff8581c81bb00dd433")
self.assertEqual(self.event.created_at, datetime.datetime(2012, 5, 27, 7, 29, 25))
self.assertEqual(self.event.event, "referenced")
self.assertEqual(self.event.id, 16348656)
self.assertEqual(self.event.issue.number, 30)
self.assertEqual(self.event.url, "https://api.github.com/repos/jacquev6/PyGithub/issues/events/16348656")
|
testmana2/test | refs/heads/master | Preferences/ConfigurationPages/ProjectBrowserPage.py | 2 | # -*- coding: utf-8 -*-
# Copyright (c) 2006 - 2015 Detlev Offenbach <[email protected]>
#
"""
Module implementing the Project Browser configuration page.
"""
from __future__ import unicode_literals
from PyQt5.QtCore import pyqtSlot
from E5Gui.E5Application import e5App
from .ConfigurationPageBase import ConfigurationPageBase
from .Ui_ProjectBrowserPage import Ui_ProjectBrowserPage
import Preferences
class ProjectBrowserPage(ConfigurationPageBase, Ui_ProjectBrowserPage):
"""
Class implementing the Project Browser configuration page.
"""
def __init__(self):
"""
Constructor
"""
super(ProjectBrowserPage, self).__init__()
self.setupUi(self)
self.setObjectName("ProjectBrowserPage")
self.__currentProjectTypeIndex = 0
# set initial values
self.projectTypeCombo.addItem('', '')
self.__projectBrowserFlags = {'': 0}
try:
projectTypes = e5App().getObject("Project").getProjectTypes()
for projectType in sorted(projectTypes.keys()):
self.projectTypeCombo.addItem(projectTypes[projectType],
projectType)
self.__projectBrowserFlags[projectType] = \
Preferences.getProjectBrowserFlags(projectType)
except KeyError:
self.pbGroup.setEnabled(False)
self.initColour(
"Highlighted", self.pbHighlightedButton,
Preferences.getProjectBrowserColour)
self.followEditorCheckBox.setChecked(
Preferences.getProject("FollowEditor"))
self.followCursorLineCheckBox.setChecked(
Preferences.getProject("FollowCursorLine"))
self.autoPopulateCheckBox.setChecked(
Preferences.getProject("AutoPopulateItems"))
self.hideGeneratedCheckBox.setChecked(
Preferences.getProject("HideGeneratedForms"))
def save(self):
"""
Public slot to save the Project Browser configuration.
"""
self.saveColours(Preferences.setProjectBrowserColour)
Preferences.setProject(
"FollowEditor",
self.followEditorCheckBox.isChecked())
Preferences.setProject(
"FollowCursorLine",
self.followCursorLineCheckBox.isChecked())
Preferences.setProject(
"AutoPopulateItems",
self.autoPopulateCheckBox.isChecked())
Preferences.setProject(
"HideGeneratedForms",
self.hideGeneratedCheckBox.isChecked())
if self.pbGroup.isEnabled():
self.__storeProjectBrowserFlags(
self.projectTypeCombo.itemData(self.__currentProjectTypeIndex))
for projectType, flags in list(self.__projectBrowserFlags.items()):
if projectType != '':
Preferences.setProjectBrowserFlags(projectType, flags)
def __storeProjectBrowserFlags(self, projectType):
"""
Private method to store the flags for the selected project type.
@param projectType type of the selected project (string)
"""
from Project.ProjectBrowserFlags import SourcesBrowserFlag, \
FormsBrowserFlag, ResourcesBrowserFlag, TranslationsBrowserFlag, \
InterfacesBrowserFlag, OthersBrowserFlag
flags = 0
if self.sourcesBrowserCheckBox.isChecked():
flags |= SourcesBrowserFlag
if self.formsBrowserCheckBox.isChecked():
flags |= FormsBrowserFlag
if self.resourcesBrowserCheckBox.isChecked():
flags |= ResourcesBrowserFlag
if self.translationsBrowserCheckBox.isChecked():
flags |= TranslationsBrowserFlag
if self.interfacesBrowserCheckBox.isChecked():
flags |= InterfacesBrowserFlag
if self.othersBrowserCheckBox.isChecked():
flags |= OthersBrowserFlag
self.__projectBrowserFlags[projectType] = flags
def __setProjectBrowsersCheckBoxes(self, projectType):
"""
Private method to set the checkboxes according to the selected project
type.
@param projectType type of the selected project (string)
"""
from Project.ProjectBrowserFlags import SourcesBrowserFlag, \
FormsBrowserFlag, ResourcesBrowserFlag, TranslationsBrowserFlag, \
InterfacesBrowserFlag, OthersBrowserFlag
flags = self.__projectBrowserFlags[projectType]
self.sourcesBrowserCheckBox.setChecked(flags & SourcesBrowserFlag)
self.formsBrowserCheckBox.setChecked(flags & FormsBrowserFlag)
self.resourcesBrowserCheckBox.setChecked(flags & ResourcesBrowserFlag)
self.translationsBrowserCheckBox.setChecked(
flags & TranslationsBrowserFlag)
self.interfacesBrowserCheckBox.setChecked(
flags & InterfacesBrowserFlag)
self.othersBrowserCheckBox.setChecked(flags & OthersBrowserFlag)
@pyqtSlot(int)
def on_projectTypeCombo_activated(self, index):
"""
Private slot to set the browser checkboxes according to the selected
project type.
@param index index of the selected project type (integer)
"""
if self.__currentProjectTypeIndex == index:
return
self.__storeProjectBrowserFlags(
self.projectTypeCombo.itemData(self.__currentProjectTypeIndex))
self.__setProjectBrowsersCheckBoxes(
self.projectTypeCombo.itemData(index))
self.__currentProjectTypeIndex = index
@pyqtSlot(bool)
def on_followEditorCheckBox_toggled(self, checked):
"""
Private slot to handle the change of the 'Follow Editor' checkbox.
@param checked flag indicating the state of the checkbox
"""
if not checked:
self.followCursorLineCheckBox.setChecked(False)
@pyqtSlot(bool)
def on_followCursorLineCheckBox_toggled(self, checked):
"""
Private slot to handle the change of the 'Follow Cursor Line' checkbox.
@param checked flag indicating the state of the checkbox
"""
if checked:
self.followEditorCheckBox.setChecked(True)
def create(dlg):
"""
Module function to create the configuration page.
@param dlg reference to the configuration dialog
@return reference to the instantiated page (ConfigurationPageBase)
"""
page = ProjectBrowserPage()
return page
|
CS2014/USM | refs/heads/master | usm/accounting/tests.py | 24123 | from django.test import TestCase
# Create your tests here.
|
jarshwah/django | refs/heads/master | tests/view_tests/generic_urls.py | 28 | # -*- coding:utf-8 -*-
from __future__ import unicode_literals
from django.conf.urls import url
from django.contrib.auth import views as auth_views
from django.views.generic import RedirectView
from . import views
from .models import Article, DateArticle
date_based_info_dict = {
'queryset': Article.objects.all(),
'date_field': 'date_created',
'month_format': '%m',
}
object_list_dict = {
'queryset': Article.objects.all(),
'paginate_by': 2,
}
object_list_no_paginate_by = {
'queryset': Article.objects.all(),
}
numeric_days_info_dict = dict(date_based_info_dict, day_format='%d')
date_based_datefield_info_dict = dict(date_based_info_dict, queryset=DateArticle.objects.all())
urlpatterns = [
url(r'^accounts/login/$', auth_views.LoginView.as_view(template_name='login.html')),
url(r'^accounts/logout/$', auth_views.LogoutView.as_view()),
# Special URLs for particular regression cases.
url('^中文/target/$', views.index_page),
]
# redirects, both temporary and permanent, with non-ASCII targets
urlpatterns += [
url('^nonascii_redirect/$', RedirectView.as_view(
url='/中文/target/', permanent=False)),
url('^permanent_nonascii_redirect/$', RedirectView.as_view(
url='/中文/target/', permanent=True)),
]
# json response
urlpatterns += [
url(r'^json/response/$', views.json_response_view),
]
|
swannapa/erpnext | refs/heads/develop | erpnext/healthcare/doctype/lab_test/lab_test.py | 5 | # -*- coding: utf-8 -*-
# Copyright (c) 2015, ESS and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
import json
from frappe.utils import getdate
from erpnext.healthcare.doctype.healthcare_settings.healthcare_settings import get_receivable_account
from frappe import _
class LabTest(Document):
def on_submit(self):
frappe.db.set_value(self.doctype,self.name,"submitted_date", getdate())
insert_lab_test_to_medical_record(self)
frappe.db.set_value("Lab Test", self.name, "status", "Completed")
def on_cancel(self):
delete_lab_test_from_medical_record(self)
frappe.db.set_value("Lab Test", self.name, "status", "Cancelled")
self.reload()
def on_update(self):
if(self.sensitivity_test_items):
sensitivity = sorted(self.sensitivity_test_items, key=lambda x: x.antibiotic_sensitivity)
for i, item in enumerate(sensitivity):
item.idx = i+1
self.sensitivity_test_items = sensitivity
def after_insert(self):
if(self.prescription):
frappe.db.set_value("Lab Prescription", self.prescription, "test_created", 1)
if not self.test_name and self.template:
self.load_test_from_template()
self.reload()
def load_test_from_template(self):
lab_test = self
create_test_from_template(lab_test)
self.reload()
def create_test_from_template(lab_test):
template = frappe.get_doc("Lab Test Template", lab_test.template)
patient = frappe.get_doc("Patient", lab_test.patient)
lab_test.test_name = template.test_name
lab_test.result_date = getdate()
lab_test.department = template.department
lab_test.test_group = template.test_group
lab_test = create_sample_collection(lab_test, template, patient, None)
lab_test = load_result_format(lab_test, template, None, None)
@frappe.whitelist()
def update_status(status, name):
frappe.db.sql("""update `tabLab Test` set status=%s, approved_date=%s where name = %s""", (status, getdate(), name))
@frappe.whitelist()
def update_lab_test_print_sms_email_status(print_sms_email, name):
frappe.db.set_value("Lab Test",name,print_sms_email,1)
def create_lab_test_doc(invoice, consultation, patient, template):
#create Test Result for template, copy vals from Invoice
lab_test = frappe.new_doc("Lab Test")
if(invoice):
lab_test.invoice = invoice
if(consultation):
lab_test.physician = consultation.physician
lab_test.patient = patient.name
lab_test.patient_age = patient.get_age()
lab_test.patient_sex = patient.sex
lab_test.email = patient.email
lab_test.mobile = patient.mobile
lab_test.department = template.department
lab_test.test_name = template.test_name
lab_test.template = template.name
lab_test.test_group = template.test_group
lab_test.result_date = getdate()
lab_test.report_preference = patient.report_preference
return lab_test
def create_normals(template, lab_test):
lab_test.normal_toggle = "1"
normal = lab_test.append("normal_test_items")
normal.test_name = template.test_name
normal.test_uom = template.test_uom
normal.normal_range = template.test_normal_range
normal.require_result_value = 1
normal.template = template.name
def create_compounds(template, lab_test, is_group):
lab_test.normal_toggle = "1"
for normal_test_template in template.normal_test_templates:
normal = lab_test.append("normal_test_items")
if is_group:
normal.test_event = normal_test_template.test_event
else:
normal.test_name = normal_test_template.test_event
normal.test_uom = normal_test_template.test_uom
normal.normal_range = normal_test_template.normal_range
normal.require_result_value = 1
normal.template = template.name
def create_specials(template, lab_test):
lab_test.special_toggle = "1"
if(template.sensitivity):
lab_test.sensitivity_toggle = "1"
for special_test_template in template.special_test_template:
special = lab_test.append("special_test_items")
special.test_particulars = special_test_template.particulars
special.require_result_value = 1
special.template = template.name
def create_sample_doc(template, patient, invoice):
if(template.sample):
sample_exist = frappe.db.exists({
"doctype": "Sample Collection",
"patient": patient.name,
"docstatus": 0,
"sample": template.sample})
if sample_exist :
#Update Sample Collection by adding quantity
sample_collection = frappe.get_doc("Sample Collection",sample_exist[0][0])
quantity = int(sample_collection.sample_quantity)+int(template.sample_quantity)
if(template.sample_collection_details):
sample_collection_details = sample_collection.sample_collection_details+"\n==============\n"+"Test :"+template.test_name+"\n"+"Collection Detials:\n\t"+template.sample_collection_details
frappe.db.set_value("Sample Collection", sample_collection.name, "sample_collection_details",sample_collection_details)
frappe.db.set_value("Sample Collection", sample_collection.name, "sample_quantity",quantity)
else:
#create Sample Collection for template, copy vals from Invoice
sample_collection = frappe.new_doc("Sample Collection")
if(invoice):
sample_collection.invoice = invoice
sample_collection.patient = patient.name
sample_collection.patient_age = patient.get_age()
sample_collection.patient_sex = patient.sex
sample_collection.sample = template.sample
sample_collection.sample_uom = template.sample_uom
sample_collection.sample_quantity = template.sample_quantity
if(template.sample_collection_details):
sample_collection.sample_collection_details = "Test :"+template.test_name+"\n"+"Collection Detials:\n\t"+template.sample_collection_details
sample_collection.save(ignore_permissions=True)
return sample_collection
@frappe.whitelist()
def create_lab_test_from_desk(patient, template, prescription, invoice=None):
lab_test_exist = frappe.db.exists({
"doctype": "Lab Test",
"prescription": prescription
})
if lab_test_exist:
return
template = frappe.get_doc("Lab Test Template", template)
#skip the loop if there is no test_template for Item
if not (template):
return
patient = frappe.get_doc("Patient", patient)
consultation_id = frappe.get_value("Lab Prescription", prescription, "parent")
consultation = frappe.get_doc("Consultation", consultation_id)
lab_test = create_lab_test(patient, template, prescription, consultation, invoice)
return lab_test.name
def create_sample_collection(lab_test, template, patient, invoice):
if(frappe.db.get_value("Healthcare Settings", None, "require_sample_collection") == "1"):
sample_collection = create_sample_doc(template, patient, invoice)
if(sample_collection):
lab_test.sample = sample_collection.name
return lab_test
def load_result_format(lab_test, template, prescription, invoice):
if(template.test_template_type == 'Single'):
create_normals(template, lab_test)
elif(template.test_template_type == 'Compound'):
create_compounds(template, lab_test, False)
elif(template.test_template_type == 'Descriptive'):
create_specials(template, lab_test)
elif(template.test_template_type == 'Grouped'):
#iterate for each template in the group and create one result for all.
for test_group in template.test_groups:
#template_in_group = None
if(test_group.test_template):
template_in_group = frappe.get_doc("Lab Test Template",
test_group.test_template)
if(template_in_group):
if(template_in_group.test_template_type == 'Single'):
create_normals(template_in_group, lab_test)
elif(template_in_group.test_template_type == 'Compound'):
normal_heading = lab_test.append("normal_test_items")
normal_heading.test_name = template_in_group.test_name
normal_heading.require_result_value = 0
normal_heading.template = template_in_group.name
create_compounds(template_in_group, lab_test, True)
elif(template_in_group.test_template_type == 'Descriptive'):
special_heading = lab_test.append("special_test_items")
special_heading.test_name = template_in_group.test_name
special_heading.require_result_value = 0
special_heading.template = template_in_group.name
create_specials(template_in_group, lab_test)
else:
normal = lab_test.append("normal_test_items")
normal.test_name = test_group.group_event
normal.test_uom = test_group.group_test_uom
normal.normal_range = test_group.group_test_normal_range
normal.require_result_value = 1
normal.template = template.name
if(template.test_template_type != 'No Result'):
if(prescription):
lab_test.prescription = prescription
if(invoice):
frappe.db.set_value("Lab Prescription", prescription, "invoice", invoice)
lab_test.save(ignore_permissions=True) # insert the result
return lab_test
def create_lab_test(patient, template, prescription, consultation, invoice):
lab_test = create_lab_test_doc(invoice, consultation, patient, template)
lab_test = create_sample_collection(lab_test, template, patient, invoice)
lab_test = load_result_format(lab_test, template, prescription, invoice)
return lab_test
@frappe.whitelist()
def get_employee_by_user_id(user_id):
emp_id = frappe.db.get_value("Employee",{"user_id":user_id})
employee = frappe.get_doc("Employee",emp_id)
return employee
def insert_lab_test_to_medical_record(doc):
subject = str(doc.test_name)
if(doc.test_comment):
subject += ", \n"+str(doc.test_comment)
medical_record = frappe.new_doc("Patient Medical Record")
medical_record.patient = doc.patient
medical_record.subject = subject
medical_record.status = "Open"
medical_record.communication_date = doc.result_date
medical_record.reference_doctype = "Lab Test"
medical_record.reference_name = doc.name
medical_record.reference_owner = doc.owner
medical_record.save(ignore_permissions=True)
def delete_lab_test_from_medical_record(self):
medical_record_id = frappe.db.sql("select name from `tabPatient Medical Record` where reference_name=%s",(self.name))
if(medical_record_id[0][0]):
frappe.delete_doc("Patient Medical Record", medical_record_id[0][0])
def create_item_line(test_code, sales_invoice):
if test_code:
item = frappe.get_doc("Item", test_code)
if item:
if not item.disabled:
sales_invoice_line = sales_invoice.append("items")
sales_invoice_line.item_code = item.item_code
sales_invoice_line.item_name = item.item_name
sales_invoice_line.qty = 1.0
sales_invoice_line.description = item.description
@frappe.whitelist()
def create_invoice(company, patient, lab_tests, prescriptions):
test_ids = json.loads(lab_tests)
line_ids = json.loads(prescriptions)
if not test_ids and not line_ids:
return
sales_invoice = frappe.new_doc("Sales Invoice")
sales_invoice.customer = frappe.get_value("Patient", patient, "customer")
sales_invoice.due_date = getdate()
sales_invoice.is_pos = '0'
sales_invoice.debit_to = get_receivable_account(company)
for line in line_ids:
test_code = frappe.get_value("Lab Prescription", line, "test_code")
create_item_line(test_code, sales_invoice)
for test in test_ids:
template = frappe.get_value("Lab Test", test, "template")
test_code = frappe.get_value("Lab Test Template", template, "item")
create_item_line(test_code, sales_invoice)
sales_invoice.set_missing_values()
sales_invoice.save()
#set invoice in lab test
for test in test_ids:
frappe.db.set_value("Lab Test", test, "invoice", sales_invoice.name)
prescription = frappe.db.get_value("Lab Test", test, "prescription")
if prescription:
frappe.db.set_value("Lab Prescription", prescription, "invoice", sales_invoice.name)
#set invoice in prescription
for line in line_ids:
frappe.db.set_value("Lab Prescription", line, "invoice", sales_invoice.name)
return sales_invoice.name
@frappe.whitelist()
def get_lab_test_prescribed(patient):
return frappe.db.sql(_("""select cp.name, cp.test_code, cp.parent, cp.invoice, ct.physician, ct.consultation_date from tabConsultation ct,
`tabLab Prescription` cp where ct.patient='{0}' and cp.parent=ct.name and cp.test_created=0""").format(patient))
|
rossp/django-helpdesk | refs/heads/master | helpdesk/migrations/0024_time_spent.py | 4 | # Generated by Django 2.0.5 on 2019-02-06 13:24
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('helpdesk', '0023_add_enable_notifications_on_email_events_to_ticket'),
]
operations = [
migrations.AddField(
model_name='followup',
name='time_spent',
field=models.DurationField(blank=True, help_text='Time spent on this follow up', null=True),
),
]
|
JaviMerino/trappy | refs/heads/master | trappy/plotter/EventPlot.py | 1 | # Copyright 2015-2016 ARM Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""
The EventPlot is used to represent Events with two characteristics:
- A name, which determines the colour on the plot
- A lane, which determines the lane in which the event occurred
In the case of a cpu residency plot, the term lane can be equated to
a CPU and the name attribute can be the PID of the task
"""
from trappy.plotter import AttrConf
import uuid
import json
import os
from trappy.plotter.AbstractDataPlotter import AbstractDataPlotter
from trappy.plotter import IPythonConf
if not IPythonConf.check_ipython():
raise ImportError("Ipython Environment not Found")
from IPython.display import display, HTML
# pylint: disable=R0201
# pylint: disable=R0921
class EventPlot(AbstractDataPlotter):
"""
Input Data should be of the format
::
{ "<name1>" : [
[event_start, event_end, lane],
.
.
[event_start, event_end, lane],
],
.
.
.
"<nameN>" : [
[event_start, event_end, lane],
.
.
[event_start, event_end, lane],
],
}
:param data: Input Data
:type data: dict
:param keys: List of unique names in the data dictionary
:type keys: list
:param domain: Domain of the event data
:type domain: tuple
:param lane_prefix: A string prefix to be used to name each lane
:type lane_prefix: str
:param num_lanes: Total number of expected lanes
:type num_lanes: int
:param summary: Show a mini plot below the main plot with an
overview of where your current view is with respect to the
whole trace
:type summary: bool
:param stride: Stride can be used if the trace is very large.
It results in sampled rendering
:type stride: bool
:param lanes: The sorted order of lanes
:type lanes: list
"""
def __init__(
self,
data,
keys,
domain,
lane_prefix="Lane: ",
num_lanes=0,
summary=True,
stride=False,
lanes=None):
self._html = []
self._fig_name = self._generate_fig_name()
# Function to get the average duration of each event
avgFunc = lambda x: sum([(evt[1] - evt[0]) for evt in x]) / float(len(x) + 1)
avg = {k: avgFunc(v) for k, v in data.iteritems()}
# Filter keys with zero average time
keys = filter(lambda x : avg[x] != 0, avg)
graph = {}
graph["data"] = data
graph["lanes"] = self._get_lanes(lanes, lane_prefix, num_lanes, data)
graph["xDomain"] = domain
graph["keys"] = sorted(keys, key=lambda x: avg[x], reverse=True)
graph["showSummary"] = summary
graph["stride"] = AttrConf.EVENT_PLOT_STRIDE
json_file = os.path.join(
IPythonConf.get_data_path(),
self._fig_name +
".json")
with open(json_file, "w") as json_fh:
json.dump(graph, json_fh)
# Initialize the HTML, CSS and JS Components
self._add_css()
self._init_html()
def view(self):
"""Views the Graph Object"""
# Defer installation of IPython components
# to the .view call to avoid any errors at
# when importing the module. This facilitates
# the importing of the module from outside
# an IPython notebook
IPythonConf.iplot_install("EventPlot")
display(HTML(self.html()))
def savefig(self, path):
"""Save the plot in the provided path
.. warning:: Not Implemented for :mod:`trappy.plotter.EventPlot`
"""
raise NotImplementedError(
"Save is not currently implemented for EventPlot")
def _get_lanes(self,
input_lanes,
lane_prefix,
num_lanes,
data):
"""Populate the lanes for the plot"""
# If the user has specified lanes explicitly
lanes = []
if input_lanes:
lane_map = {}
for idx, lane in enumerate(input_lanes):
lane_map[lane] = idx
for name in data:
for event in data[name]:
lane = event[2]
try:
event[2] = lane_map[lane]
except KeyError:
raise RuntimeError("Invalid Lane %s" % lane)
for idx, lane in enumerate(input_lanes):
lanes.append({"id": idx, "label": lane})
else:
if not num_lanes:
raise RuntimeError("Either lanes or num_lanes must be specified")
for idx in range(num_lanes):
lanes.append({"id": idx, "label": "{}{}".format(lane_prefix, idx)})
return lanes
def _generate_fig_name(self):
"""Generate a unqiue name for the figure"""
fig_name = "fig_" + uuid.uuid4().hex
return fig_name
def _init_html(self):
"""Initialize HTML for the plot"""
div_js = """
<script>
var req = require.config( {
paths: {
"EventPlot": '""" + IPythonConf.add_web_base("plotter_scripts/EventPlot/EventPlot") + """',
"d3-tip": '""" + IPythonConf.add_web_base("plotter_scripts/EventPlot/d3.tip.v0.6.3") + """',
"d3-plotter": '""" + IPythonConf.add_web_base("plotter_scripts/EventPlot/d3.min") + """'
},
shim: {
"d3-plotter" : {
"exports" : "d3"
},
"d3-tip": ["d3-plotter"],
"EventPlot": {
"deps": ["d3-tip", "d3-plotter" ],
"exports": "EventPlot"
}
}
});
req(["require", "EventPlot"], function() {
EventPlot.generate('""" + self._fig_name + """', '""" + IPythonConf.add_web_base("") + """');
});
</script>
"""
self._html.append(
'<div id="{}" class="eventplot">{}</div>'.format(self._fig_name,
div_js))
def _add_css(self):
"""Append the CSS to the HTML code generated"""
base_dir = os.path.dirname(os.path.realpath(__file__))
css_file = os.path.join(base_dir, "css/EventPlot.css")
css_fh = open(css_file, 'r')
self._html.append("<style>")
self._html += css_fh.readlines()
self._html.append("</style>")
css_fh.close()
def html(self):
"""Return a Raw HTML string for the plot"""
return "\n".join(self._html)
|
ivandevp/django | refs/heads/master | django/utils/dateformat.py | 365 | """
PHP date() style date formatting
See http://www.php.net/date for format strings
Usage:
>>> import datetime
>>> d = datetime.datetime.now()
>>> df = DateFormat(d)
>>> print(df.format('jS F Y H:i'))
7th October 2003 11:39
>>>
"""
from __future__ import unicode_literals
import calendar
import datetime
import re
import time
from django.utils import six
from django.utils.dates import (
MONTHS, MONTHS_3, MONTHS_ALT, MONTHS_AP, WEEKDAYS, WEEKDAYS_ABBR,
)
from django.utils.encoding import force_text
from django.utils.timezone import get_default_timezone, is_aware, is_naive
from django.utils.translation import ugettext as _
re_formatchars = re.compile(r'(?<!\\)([aAbBcdDeEfFgGhHiIjlLmMnNoOPrsStTUuwWyYzZ])')
re_escaped = re.compile(r'\\(.)')
class Formatter(object):
def format(self, formatstr):
pieces = []
for i, piece in enumerate(re_formatchars.split(force_text(formatstr))):
if i % 2:
pieces.append(force_text(getattr(self, piece)()))
elif piece:
pieces.append(re_escaped.sub(r'\1', piece))
return ''.join(pieces)
class TimeFormat(Formatter):
def __init__(self, obj):
self.data = obj
self.timezone = None
# We only support timezone when formatting datetime objects,
# not date objects (timezone information not appropriate),
# or time objects (against established django policy).
if isinstance(obj, datetime.datetime):
if is_naive(obj):
self.timezone = get_default_timezone()
else:
self.timezone = obj.tzinfo
def a(self):
"'a.m.' or 'p.m.'"
if self.data.hour > 11:
return _('p.m.')
return _('a.m.')
def A(self):
"'AM' or 'PM'"
if self.data.hour > 11:
return _('PM')
return _('AM')
def B(self):
"Swatch Internet time"
raise NotImplementedError('may be implemented in a future release')
def e(self):
"""
Timezone name.
If timezone information is not available, this method returns
an empty string.
"""
if not self.timezone:
return ""
try:
if hasattr(self.data, 'tzinfo') and self.data.tzinfo:
# Have to use tzinfo.tzname and not datetime.tzname
# because datatime.tzname does not expect Unicode
return self.data.tzinfo.tzname(self.data) or ""
except NotImplementedError:
pass
return ""
def f(self):
"""
Time, in 12-hour hours and minutes, with minutes left off if they're
zero.
Examples: '1', '1:30', '2:05', '2'
Proprietary extension.
"""
if self.data.minute == 0:
return self.g()
return '%s:%s' % (self.g(), self.i())
def g(self):
"Hour, 12-hour format without leading zeros; i.e. '1' to '12'"
if self.data.hour == 0:
return 12
if self.data.hour > 12:
return self.data.hour - 12
return self.data.hour
def G(self):
"Hour, 24-hour format without leading zeros; i.e. '0' to '23'"
return self.data.hour
def h(self):
"Hour, 12-hour format; i.e. '01' to '12'"
return '%02d' % self.g()
def H(self):
"Hour, 24-hour format; i.e. '00' to '23'"
return '%02d' % self.G()
def i(self):
"Minutes; i.e. '00' to '59'"
return '%02d' % self.data.minute
def O(self):
"""
Difference to Greenwich time in hours; e.g. '+0200', '-0430'.
If timezone information is not available, this method returns
an empty string.
"""
if not self.timezone:
return ""
seconds = self.Z()
sign = '-' if seconds < 0 else '+'
seconds = abs(seconds)
return "%s%02d%02d" % (sign, seconds // 3600, (seconds // 60) % 60)
def P(self):
"""
Time, in 12-hour hours, minutes and 'a.m.'/'p.m.', with minutes left off
if they're zero and the strings 'midnight' and 'noon' if appropriate.
Examples: '1 a.m.', '1:30 p.m.', 'midnight', 'noon', '12:30 p.m.'
Proprietary extension.
"""
if self.data.minute == 0 and self.data.hour == 0:
return _('midnight')
if self.data.minute == 0 and self.data.hour == 12:
return _('noon')
return '%s %s' % (self.f(), self.a())
def s(self):
"Seconds; i.e. '00' to '59'"
return '%02d' % self.data.second
def T(self):
"""
Time zone of this machine; e.g. 'EST' or 'MDT'.
If timezone information is not available, this method returns
an empty string.
"""
if not self.timezone:
return ""
name = self.timezone.tzname(self.data) if self.timezone else None
if name is None:
name = self.format('O')
return six.text_type(name)
def u(self):
"Microseconds; i.e. '000000' to '999999'"
return '%06d' % self.data.microsecond
def Z(self):
"""
Time zone offset in seconds (i.e. '-43200' to '43200'). The offset for
timezones west of UTC is always negative, and for those east of UTC is
always positive.
If timezone information is not available, this method returns
an empty string.
"""
if not self.timezone:
return ""
offset = self.timezone.utcoffset(self.data)
# `offset` is a datetime.timedelta. For negative values (to the west of
# UTC) only days can be negative (days=-1) and seconds are always
# positive. e.g. UTC-1 -> timedelta(days=-1, seconds=82800, microseconds=0)
# Positive offsets have days=0
return offset.days * 86400 + offset.seconds
class DateFormat(TimeFormat):
year_days = [None, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]
def b(self):
"Month, textual, 3 letters, lowercase; e.g. 'jan'"
return MONTHS_3[self.data.month]
def c(self):
"""
ISO 8601 Format
Example : '2008-01-02T10:30:00.000123'
"""
return self.data.isoformat()
def d(self):
"Day of the month, 2 digits with leading zeros; i.e. '01' to '31'"
return '%02d' % self.data.day
def D(self):
"Day of the week, textual, 3 letters; e.g. 'Fri'"
return WEEKDAYS_ABBR[self.data.weekday()]
def E(self):
"Alternative month names as required by some locales. Proprietary extension."
return MONTHS_ALT[self.data.month]
def F(self):
"Month, textual, long; e.g. 'January'"
return MONTHS[self.data.month]
def I(self):
"'1' if Daylight Savings Time, '0' otherwise."
if self.timezone and self.timezone.dst(self.data):
return '1'
else:
return '0'
def j(self):
"Day of the month without leading zeros; i.e. '1' to '31'"
return self.data.day
def l(self):
"Day of the week, textual, long; e.g. 'Friday'"
return WEEKDAYS[self.data.weekday()]
def L(self):
"Boolean for whether it is a leap year; i.e. True or False"
return calendar.isleap(self.data.year)
def m(self):
"Month; i.e. '01' to '12'"
return '%02d' % self.data.month
def M(self):
"Month, textual, 3 letters; e.g. 'Jan'"
return MONTHS_3[self.data.month].title()
def n(self):
"Month without leading zeros; i.e. '1' to '12'"
return self.data.month
def N(self):
"Month abbreviation in Associated Press style. Proprietary extension."
return MONTHS_AP[self.data.month]
def o(self):
"ISO 8601 year number matching the ISO week number (W)"
return self.data.isocalendar()[0]
def r(self):
"RFC 2822 formatted date; e.g. 'Thu, 21 Dec 2000 16:01:07 +0200'"
return self.format('D, j M Y H:i:s O')
def S(self):
"English ordinal suffix for the day of the month, 2 characters; i.e. 'st', 'nd', 'rd' or 'th'"
if self.data.day in (11, 12, 13): # Special case
return 'th'
last = self.data.day % 10
if last == 1:
return 'st'
if last == 2:
return 'nd'
if last == 3:
return 'rd'
return 'th'
def t(self):
"Number of days in the given month; i.e. '28' to '31'"
return '%02d' % calendar.monthrange(self.data.year, self.data.month)[1]
def U(self):
"Seconds since the Unix epoch (January 1 1970 00:00:00 GMT)"
if isinstance(self.data, datetime.datetime) and is_aware(self.data):
return int(calendar.timegm(self.data.utctimetuple()))
else:
return int(time.mktime(self.data.timetuple()))
def w(self):
"Day of the week, numeric, i.e. '0' (Sunday) to '6' (Saturday)"
return (self.data.weekday() + 1) % 7
def W(self):
"ISO-8601 week number of year, weeks starting on Monday"
# Algorithm from http://www.personal.ecu.edu/mccartyr/ISOwdALG.txt
week_number = None
jan1_weekday = self.data.replace(month=1, day=1).weekday() + 1
weekday = self.data.weekday() + 1
day_of_year = self.z()
if day_of_year <= (8 - jan1_weekday) and jan1_weekday > 4:
if jan1_weekday == 5 or (jan1_weekday == 6 and calendar.isleap(self.data.year - 1)):
week_number = 53
else:
week_number = 52
else:
if calendar.isleap(self.data.year):
i = 366
else:
i = 365
if (i - day_of_year) < (4 - weekday):
week_number = 1
else:
j = day_of_year + (7 - weekday) + (jan1_weekday - 1)
week_number = j // 7
if jan1_weekday > 4:
week_number -= 1
return week_number
def y(self):
"Year, 2 digits; e.g. '99'"
return six.text_type(self.data.year)[2:]
def Y(self):
"Year, 4 digits; e.g. '1999'"
return self.data.year
def z(self):
"Day of the year; i.e. '0' to '365'"
doy = self.year_days[self.data.month] + self.data.day
if self.L() and self.data.month > 2:
doy += 1
return doy
def format(value, format_string):
"Convenience function"
df = DateFormat(value)
return df.format(format_string)
def time_format(value, format_string):
"Convenience function"
tf = TimeFormat(value)
return tf.format(format_string)
|
switowski/PythonPerformancePresentation | refs/heads/gh-pages | test.py | 1 | def test():
"""Stupid test function"""
L = []
for i in range(100):
L.append(i)
def filter_list_slow(arr):
output = []
for element in arr:
if element % 2:
output.append(element)
return output
def filter_list_faster(arr):
return filter(lambda x: x % 2, arr)
def filter_list_comprehension(arr):
return [element for element in arr if element % 2]
def modify(x):
return x * x * x + 3 * x * x + 5 * x
>>> %timeit map(modify, ARR)
10 loops, best of 3: 184 ms per loop
>>> %timeit map(lambda x: x * x * x + 3 * x * x + 5 * x, ARR)
10 loops, best of 3: 186 ms per loop
>>> %timeit [x * x * x + 3 * x * x + 5 * x for x in ARR]
10 loops, best of 3: 135 ms per loop
def find_x(arr, min_val):
return [element for element in arr if element > min_val][0]
def find_x_loop(arr, min_val):
for element in arr:
if element > min_val:
return element
def find_x_gen(arr, min_val):
return next(element for element in arr if element > min_val) |
dotamin/migmig | refs/heads/master | migmig/utils.py | 1 | # Python utils for migmig project
import random
def parse_doc_arguments(arguments):
options, args, command = {}, {}, None
for key, value in arguments.items():
if key[0:2] == "--":
options[key[2:]] = value
elif key[0] == "<":
args[key] = value
else:
if value:
command = key
return command, args, options
def calc_bytes_range(start, end, threads_count):
"""
calculate "start byte" and "end byte" to give to each thread.
return a list including tuples: (start, end)
"""
bytes_range = []
chunk_size = end - start + 1
mini_chunk = chunk_size // threads_count
pos = start
for i in range(threads_count):
start_byte = pos
end_byte = start_byte + mini_chunk
if end_byte > end - 1:
end_byte = end
pos = end_byte + 1
bytes_range.append((start_byte, end_byte))
return bytes_range
def get_random_useragent():
"""
Returns a random popular user-agent.
Taken from `here <http://techblog.willshouse.com/2012/01/03/most-common-user-agents/>`_, last updated on 01/02/2014.
:returns: user-agent
:rtype: string
"""
l = [
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_1) AppleWebKit/537.73.11 (KHTML, like Gecko) Version/7.0.1 Safari/537.73.11',
'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:26.0) Gecko/20100101 Firefox/26.0',
'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36',
'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.76 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.77 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:26.0) Gecko/20100101 Firefox/26.0',
'Mozilla/5.0 (iPhone; CPU iPhone OS 7_0_4 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11B554a Safari/9537.53',
'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko',
'Mozilla/5.0 (Windows NT 5.1; rv:26.0) Gecko/20100101 Firefox/26.0',
]
return random.choice(l)
|
antoinecarme/pyaf | refs/heads/master | tests/artificial/transf_Logit/trend_Lag1Trend/cycle_12/ar_12/test_artificial_128_Logit_Lag1Trend_12_12_20.py | 1 | import pyaf.Bench.TS_datasets as tsds
import tests.artificial.process_artificial_dataset as art
art.process_dataset(N = 128 , FREQ = 'D', seed = 0, trendtype = "Lag1Trend", cycle_length = 12, transform = "Logit", sigma = 0.0, exog_count = 20, ar_order = 12); |
jeremiah-c-leary/vhdl-style-guide | refs/heads/master | vsg/tests/port/test_rule_011.py | 1 |
import os
import unittest
from vsg.rules import port
from vsg import vhdlFile
from vsg.tests import utils
sTestDir = os.path.dirname(__file__)
lFile, eError =vhdlFile.utils.read_vhdlfile(os.path.join(sTestDir,'rule_011_test_input.vhd'))
class test_port_rule(unittest.TestCase):
def setUp(self):
self.oFile = vhdlFile.vhdlFile(lFile)
self.assertIsNone(eError)
def test_rule_011(self):
oRule = port.rule_011()
self.assertTrue(oRule)
self.assertEqual(oRule.name, 'port')
self.assertEqual(oRule.identifier, '011')
lExpected = [14, 15, 16, 17]
oRule.analyze(self.oFile)
self.assertEqual(lExpected, utils.extract_violation_lines_from_violation_object(oRule.violations))
|
halbbob/dff | refs/heads/develop | modules/viewer/hexedit/hexeditor.py | 1 | # DFF -- An Open Source Digital Forensics Framework
# Copyright (C) 2009-2011 ArxSys
#
# This program is free software, distributed under the terms of
# the GNU General Public License Version 2. See the LICENSE file
# at the top of the source tree.
#
# See http://www.digital-forensic.org for more information about this
# project. Please do not directly contact any of the maintainers of
# DFF for assistance; the project provides a web site, mailing lists
# and IRC channels for your use.
#
# Author(s):
# Jeremy Mounier <[email protected]>
#
__dff_module_hexeditor_version__ = "1.0.0"
import sys
from api.module.script import Script
from api.module.module import Module
from api.types.libtypes import Argument, typeId
from PyQt4.QtCore import QSize, SIGNAL
from PyQt4.QtGui import QWidget, QVBoxLayout, QIcon, QMessageBox
from ui.gui.utils.utils import Utils
from Heditor import Heditor
try :
import nceditor
except ImportError:
pass
class ViewerHexa(QWidget, Script):
def __init__(self):
Script.__init__(self, "hexedit")
self.type = "hexedit"
# self.icon = ":hexedit.png"
def start(self, args) :
self.node = args["file"].value()
try:
self.preview = args["preview"].value()
except IndexError:
self.preview = False
def c_display(self):
try:
nceditor.start(self.node)
except NameError:
print "This functionality is not available on your operating system"
def g_display(self):
QWidget.__init__(self)
self.widget = Heditor(self)
self.name = "hexedit " + str(self.node.name())
if self.node.size() > 0:
self.widget.init(self.node, self.preview)
self.setLayout(self.widget.vlayout)
else:
msg = QMessageBox(QMessageBox.Critical, "Hexadecimal viewer", "Error: File is empty", QMessageBox.Ok)
msg.exec_()
def closeEvent(self, event):
self.widget.close()
def updateWidget(self):
pass
def initCallback(self):
pass
def refresh(self):
pass
class hexeditor(Module):
"""Hexadecimal view of a file content"""
def __init__(self):
Module.__init__(self, "hexadecimal", ViewerHexa)
self.conf.addArgument({"input": Argument.Required|Argument.Single|typeId.Node,
"name": "file",
"description": "File to display as hexadecimal"})
self.conf.addArgument({"name": "preview",
"description": "Preview mode",
"input": Argument.Empty})
self.tags = "Viewers"
self.icon = ":hexedit.png"
|
litebitcoins/litebitcoin | refs/heads/master | test/functional/test_runner.py | 1 | #!/usr/bin/env python3
# Copyright (c) 2014-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Run regression test suite.
This module calls down into individual test cases via subprocess. It will
forward all unrecognized arguments onto the individual test scripts.
Functional tests are disabled on Windows by default. Use --force to run them anyway.
For a description of arguments recognized by test scripts, see
`test/functional/test_framework/test_framework.py:BitcoinTestFramework.main`.
"""
import argparse
import configparser
import datetime
import os
import time
import shutil
import signal
import sys
import subprocess
import tempfile
import re
import logging
# Formatting. Default colors to empty strings.
BOLD, BLUE, RED, GREY = ("", ""), ("", ""), ("", ""), ("", "")
try:
# Make sure python thinks it can write unicode to its stdout
"\u2713".encode("utf_8").decode(sys.stdout.encoding)
TICK = "✓ "
CROSS = "✖ "
CIRCLE = "○ "
except UnicodeDecodeError:
TICK = "P "
CROSS = "x "
CIRCLE = "o "
if os.name == 'posix':
# primitive formatting on supported
# terminal via ANSI escape sequences:
BOLD = ('\033[0m', '\033[1m')
BLUE = ('\033[0m', '\033[0;34m')
RED = ('\033[0m', '\033[0;31m')
GREY = ('\033[0m', '\033[1;30m')
TEST_EXIT_PASSED = 0
TEST_EXIT_SKIPPED = 77
BASE_SCRIPTS= [
# Scripts that are run by the travis build process.
# Longest test should go first, to favor running tests in parallel
'wallet-hd.py',
'walletbackup.py',
# vv Tests less than 5m vv
'p2p-fullblocktest.py',
'fundrawtransaction.py',
'p2p-compactblocks.py',
'segwit.py',
# vv Tests less than 2m vv
'wallet.py',
'wallet-accounts.py',
'p2p-segwit.py',
'wallet-dump.py',
'listtransactions.py',
# vv Tests less than 60s vv
'sendheaders.py',
'zapwallettxes.py',
'importmulti.py',
'mempool_limit.py',
'merkle_blocks.py',
'receivedby.py',
'abandonconflict.py',
'bip68-112-113-p2p.py',
'rawtransactions.py',
'reindex.py',
# vv Tests less than 30s vv
'keypool-topup.py',
'zmq_test.py',
'bitcoin_cli.py',
'mempool_resurrect_test.py',
'txn_doublespend.py --mineblock',
'txn_clone.py',
'getchaintips.py',
'rest.py',
'mempool_spendcoinbase.py',
'mempool_reorg.py',
'mempool_persist.py',
'multiwallet.py',
'httpbasics.py',
'multi_rpc.py',
'proxy_test.py',
'signrawtransactions.py',
'disconnect_ban.py',
'decodescript.py',
'blockchain.py',
'disablewallet.py',
'net.py',
'keypool.py',
'p2p-mempool.py',
'prioritise_transaction.py',
'invalidblockrequest.py',
'invalidtxrequest.py',
'p2p-versionbits-warning.py',
'preciousblock.py',
'test_script_address2.py',
'importprunedfunds.py',
'signmessages.py',
'nulldummy.py',
'import-rescan.py',
'mining.py',
'bumpfee.py',
'rpcnamedargs.py',
'listsinceblock.py',
'p2p-leaktests.py',
'wallet-encryption.py',
'bipdersig-p2p.py',
'bip65-cltv-p2p.py',
'uptime.py',
'resendwallettransactions.py',
'minchainwork.py',
'p2p-acceptblock.py',
]
EXTENDED_SCRIPTS = [
# These tests are not run by the travis build process.
# Longest test should go first, to favor running tests in parallel
'pruning.py',
# vv Tests less than 20m vv
'smartfees.py',
# vv Tests less than 5m vv
'maxuploadtarget.py',
'mempool_packages.py',
'dbcrash.py',
# vv Tests less than 2m vv
'bip68-sequence.py',
'getblocktemplate_longpoll.py',
'p2p-timeouts.py',
# vv Tests less than 60s vv
'bip9-softforks.py',
'p2p-feefilter.py',
'rpcbind_test.py',
# vv Tests less than 30s vv
'assumevalid.py',
'example_test.py',
'txn_doublespend.py',
'txn_clone.py --mineblock',
'forknotify.py',
'invalidateblock.py',
'replace-by-fee.py',
]
# Place EXTENDED_SCRIPTS first since it has the 3 longest running tests
ALL_SCRIPTS = EXTENDED_SCRIPTS + BASE_SCRIPTS
NON_SCRIPTS = [
# These are python files that live in the functional tests directory, but are not test scripts.
"combine_logs.py",
"create_cache.py",
"test_runner.py",
]
def main():
# Parse arguments and pass through unrecognised args
parser = argparse.ArgumentParser(add_help=False,
usage='%(prog)s [test_runner.py options] [script options] [scripts]',
description=__doc__,
epilog='''
Help text and arguments for individual test script:''',
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('--coverage', action='store_true', help='generate a basic coverage report for the RPC interface')
parser.add_argument('--exclude', '-x', help='specify a comma-seperated-list of scripts to exclude.')
parser.add_argument('--extended', action='store_true', help='run the extended test suite in addition to the basic tests')
parser.add_argument('--force', '-f', action='store_true', help='run tests even on platforms where they are disabled by default (e.g. windows).')
parser.add_argument('--help', '-h', '-?', action='store_true', help='print help text and exit')
parser.add_argument('--jobs', '-j', type=int, default=4, help='how many test scripts to run in parallel. Default=4.')
parser.add_argument('--keepcache', '-k', action='store_true', help='the default behavior is to flush the cache directory on startup. --keepcache retains the cache from the previous testrun.')
parser.add_argument('--quiet', '-q', action='store_true', help='only print results summary and failure logs')
parser.add_argument('--tmpdirprefix', '-t', default=tempfile.gettempdir(), help="Root directory for datadirs")
args, unknown_args = parser.parse_known_args()
# args to be passed on always start with two dashes; tests are the remaining unknown args
tests = [arg for arg in unknown_args if arg[:2] != "--"]
passon_args = [arg for arg in unknown_args if arg[:2] == "--"]
# Read config generated by configure.
config = configparser.ConfigParser()
configfile = os.path.abspath(os.path.dirname(__file__)) + "/../config.ini"
config.read_file(open(configfile))
passon_args.append("--configfile=%s" % configfile)
# Set up logging
logging_level = logging.INFO if args.quiet else logging.DEBUG
logging.basicConfig(format='%(message)s', level=logging_level)
# Create base test directory
tmpdir = "%s/litebitcoin_test_runner_%s" % (args.tmpdirprefix, datetime.datetime.now().strftime("%Y%m%d_%H%M%S"))
os.makedirs(tmpdir)
logging.debug("Temporary test directory at %s" % tmpdir)
enable_wallet = config["components"].getboolean("ENABLE_WALLET")
enable_utils = config["components"].getboolean("ENABLE_UTILS")
enable_bitcoind = config["components"].getboolean("ENABLE_BITCOIND")
if config["environment"]["EXEEXT"] == ".exe" and not args.force:
# https://github.com/bitcoin/bitcoin/commit/d52802551752140cf41f0d9a225a43e84404d3e9
# https://github.com/bitcoin/bitcoin/pull/5677#issuecomment-136646964
print("Tests currently disabled on Windows by default. Use --force option to enable")
sys.exit(0)
if not (enable_wallet and enable_utils and enable_bitcoind):
print("No functional tests to run. Wallet, utils, and litebitcoind must all be enabled")
print("Rerun `configure` with -enable-wallet, -with-utils and -with-daemon and rerun make")
sys.exit(0)
# Build list of tests
if tests:
# Individual tests have been specified. Run specified tests that exist
# in the ALL_SCRIPTS list. Accept the name with or without .py extension.
tests = [re.sub("\.py$", "", t) + ".py" for t in tests]
test_list = []
for t in tests:
if t in ALL_SCRIPTS:
test_list.append(t)
else:
print("{}WARNING!{} Test '{}' not found in full test list.".format(BOLD[1], BOLD[0], t))
else:
# No individual tests have been specified.
# Run all base tests, and optionally run extended tests.
test_list = BASE_SCRIPTS
if args.extended:
# place the EXTENDED_SCRIPTS first since the three longest ones
# are there and the list is shorter
test_list = EXTENDED_SCRIPTS + test_list
# Remove the test cases that the user has explicitly asked to exclude.
if args.exclude:
tests_excl = [re.sub("\.py$", "", t) + ".py" for t in args.exclude.split(',')]
for exclude_test in tests_excl:
if exclude_test in test_list:
test_list.remove(exclude_test)
else:
print("{}WARNING!{} Test '{}' not found in current test list.".format(BOLD[1], BOLD[0], exclude_test))
if not test_list:
print("No valid test scripts specified. Check that your test is in one "
"of the test lists in test_runner.py, or run test_runner.py with no arguments to run all tests")
sys.exit(0)
if args.help:
# Print help for test_runner.py, then print help of the first script (with args removed) and exit.
parser.print_help()
subprocess.check_call([(config["environment"]["SRCDIR"] + '/test/functional/' + test_list[0].split()[0])] + ['-h'])
sys.exit(0)
check_script_list(config["environment"]["SRCDIR"])
if not args.keepcache:
shutil.rmtree("%s/test/cache" % config["environment"]["BUILDDIR"], ignore_errors=True)
run_tests(test_list, config["environment"]["SRCDIR"], config["environment"]["BUILDDIR"], config["environment"]["EXEEXT"], tmpdir, args.jobs, args.coverage, passon_args)
def run_tests(test_list, src_dir, build_dir, exeext, tmpdir, jobs=1, enable_coverage=False, args=[]):
# Warn if bitcoind is already running (unix only)
try:
if subprocess.check_output(["pidof", "litebitcoind"]) is not None:
print("%sWARNING!%s There is already a litebitcoind process running on this system. Tests may fail unexpectedly due to resource contention!" % (BOLD[1], BOLD[0]))
except (OSError, subprocess.SubprocessError):
pass
# Warn if there is a cache directory
cache_dir = "%s/test/cache" % build_dir
if os.path.isdir(cache_dir):
print("%sWARNING!%s There is a cache directory here: %s. If tests fail unexpectedly, try deleting the cache directory." % (BOLD[1], BOLD[0], cache_dir))
#Set env vars
if "LITEBITCOIND" not in os.environ:
os.environ["LITEBITCOIND"] = build_dir + '/src/litebitcoind' + exeext
os.environ["LITEBITCOINCLI"] = build_dir + '/src/litebitcoin-cli' + exeext
tests_dir = src_dir + '/test/functional/'
flags = ["--srcdir={}/src".format(build_dir)] + args
flags.append("--cachedir=%s" % cache_dir)
if enable_coverage:
coverage = RPCCoverage()
flags.append(coverage.flag)
logging.debug("Initializing coverage directory at %s" % coverage.dir)
else:
coverage = None
if len(test_list) > 1 and jobs > 1:
# Populate cache
subprocess.check_output([tests_dir + 'create_cache.py'] + flags + ["--tmpdir=%s/cache" % tmpdir])
#Run Tests
job_queue = TestHandler(jobs, tests_dir, tmpdir, test_list, flags)
time0 = time.time()
test_results = []
max_len_name = len(max(test_list, key=len))
for _ in range(len(test_list)):
test_result, stdout, stderr = job_queue.get_next()
test_results.append(test_result)
if test_result.status == "Passed":
logging.debug("\n%s%s%s passed, Duration: %s s" % (BOLD[1], test_result.name, BOLD[0], test_result.time))
elif test_result.status == "Skipped":
logging.debug("\n%s%s%s skipped" % (BOLD[1], test_result.name, BOLD[0]))
else:
print("\n%s%s%s failed, Duration: %s s\n" % (BOLD[1], test_result.name, BOLD[0], test_result.time))
print(BOLD[1] + 'stdout:\n' + BOLD[0] + stdout + '\n')
print(BOLD[1] + 'stderr:\n' + BOLD[0] + stderr + '\n')
print_results(test_results, max_len_name, (int(time.time() - time0)))
if coverage:
coverage.report_rpc_coverage()
logging.debug("Cleaning up coverage data")
coverage.cleanup()
# Clear up the temp directory if all subdirectories are gone
if not os.listdir(tmpdir):
os.rmdir(tmpdir)
all_passed = all(map(lambda test_result: test_result.was_successful, test_results))
sys.exit(not all_passed)
def print_results(test_results, max_len_name, runtime):
results = "\n" + BOLD[1] + "%s | %s | %s\n\n" % ("TEST".ljust(max_len_name), "STATUS ", "DURATION") + BOLD[0]
test_results.sort(key=lambda result: result.name.lower())
all_passed = True
time_sum = 0
for test_result in test_results:
all_passed = all_passed and test_result.was_successful
time_sum += test_result.time
test_result.padding = max_len_name
results += str(test_result)
status = TICK + "Passed" if all_passed else CROSS + "Failed"
results += BOLD[1] + "\n%s | %s | %s s (accumulated) \n" % ("ALL".ljust(max_len_name), status.ljust(9), time_sum) + BOLD[0]
results += "Runtime: %s s\n" % (runtime)
print(results)
class TestHandler:
"""
Trigger the testscrips passed in via the list.
"""
def __init__(self, num_tests_parallel, tests_dir, tmpdir, test_list=None, flags=None):
assert(num_tests_parallel >= 1)
self.num_jobs = num_tests_parallel
self.tests_dir = tests_dir
self.tmpdir = tmpdir
self.test_list = test_list
self.flags = flags
self.num_running = 0
# In case there is a graveyard of zombie bitcoinds, we can apply a
# pseudorandom offset to hopefully jump over them.
# (625 is PORT_RANGE/MAX_NODES)
self.portseed_offset = int(time.time() * 1000) % 625
self.jobs = []
def get_next(self):
while self.num_running < self.num_jobs and self.test_list:
# Add tests
self.num_running += 1
t = self.test_list.pop(0)
portseed = len(self.test_list) + self.portseed_offset
portseed_arg = ["--portseed={}".format(portseed)]
log_stdout = tempfile.SpooledTemporaryFile(max_size=2**16)
log_stderr = tempfile.SpooledTemporaryFile(max_size=2**16)
test_argv = t.split()
tmpdir = ["--tmpdir=%s/%s_%s" % (self.tmpdir, re.sub(".py$", "", test_argv[0]), portseed)]
self.jobs.append((t,
time.time(),
subprocess.Popen([self.tests_dir + test_argv[0]] + test_argv[1:] + self.flags + portseed_arg + tmpdir,
universal_newlines=True,
stdout=log_stdout,
stderr=log_stderr),
log_stdout,
log_stderr))
if not self.jobs:
raise IndexError('pop from empty list')
while True:
# Return first proc that finishes
time.sleep(.5)
for j in self.jobs:
(name, time0, proc, log_out, log_err) = j
if os.getenv('TRAVIS') == 'true' and int(time.time() - time0) > 20 * 60:
# In travis, timeout individual tests after 20 minutes (to stop tests hanging and not
# providing useful output.
proc.send_signal(signal.SIGINT)
if proc.poll() is not None:
log_out.seek(0), log_err.seek(0)
[stdout, stderr] = [l.read().decode('utf-8') for l in (log_out, log_err)]
log_out.close(), log_err.close()
if proc.returncode == TEST_EXIT_PASSED and stderr == "":
status = "Passed"
elif proc.returncode == TEST_EXIT_SKIPPED:
status = "Skipped"
else:
status = "Failed"
self.num_running -= 1
self.jobs.remove(j)
return TestResult(name, status, int(time.time() - time0)), stdout, stderr
print('.', end='', flush=True)
class TestResult():
def __init__(self, name, status, time):
self.name = name
self.status = status
self.time = time
self.padding = 0
def __repr__(self):
if self.status == "Passed":
color = BLUE
glyph = TICK
elif self.status == "Failed":
color = RED
glyph = CROSS
elif self.status == "Skipped":
color = GREY
glyph = CIRCLE
return color[1] + "%s | %s%s | %s s\n" % (self.name.ljust(self.padding), glyph, self.status.ljust(7), self.time) + color[0]
@property
def was_successful(self):
return self.status != "Failed"
def check_script_list(src_dir):
"""Check scripts directory.
Check that there are no scripts in the functional tests directory which are
not being run by pull-tester.py."""
script_dir = src_dir + '/test/functional/'
python_files = set([t for t in os.listdir(script_dir) if t[-3:] == ".py"])
missed_tests = list(python_files - set(map(lambda x: x.split()[0], ALL_SCRIPTS + NON_SCRIPTS)))
if len(missed_tests) != 0:
print("%sWARNING!%s The following scripts are not being run: %s. Check the test lists in test_runner.py." % (BOLD[1], BOLD[0], str(missed_tests)))
if os.getenv('TRAVIS') == 'true':
# On travis this warning is an error to prevent merging incomplete commits into master
sys.exit(1)
class RPCCoverage(object):
"""
Coverage reporting utilities for test_runner.
Coverage calculation works by having each test script subprocess write
coverage files into a particular directory. These files contain the RPC
commands invoked during testing, as well as a complete listing of RPC
commands per `litebitcoin-cli help` (`rpc_interface.txt`).
After all tests complete, the commands run are combined and diff'd against
the complete list to calculate uncovered RPC commands.
See also: test/functional/test_framework/coverage.py
"""
def __init__(self):
self.dir = tempfile.mkdtemp(prefix="coverage")
self.flag = '--coveragedir=%s' % self.dir
def report_rpc_coverage(self):
"""
Print out RPC commands that were unexercised by tests.
"""
uncovered = self._get_uncovered_rpc_commands()
if uncovered:
print("Uncovered RPC commands:")
print("".join((" - %s\n" % i) for i in sorted(uncovered)))
else:
print("All RPC commands covered.")
def cleanup(self):
return shutil.rmtree(self.dir)
def _get_uncovered_rpc_commands(self):
"""
Return a set of currently untested RPC commands.
"""
# This is shared from `test/functional/test-framework/coverage.py`
reference_filename = 'rpc_interface.txt'
coverage_file_prefix = 'coverage.'
coverage_ref_filename = os.path.join(self.dir, reference_filename)
coverage_filenames = set()
all_cmds = set()
covered_cmds = set()
if not os.path.isfile(coverage_ref_filename):
raise RuntimeError("No coverage reference found")
with open(coverage_ref_filename, 'r') as f:
all_cmds.update([i.strip() for i in f.readlines()])
for root, dirs, files in os.walk(self.dir):
for filename in files:
if filename.startswith(coverage_file_prefix):
coverage_filenames.add(os.path.join(root, filename))
for filename in coverage_filenames:
with open(filename, 'r') as f:
covered_cmds.update([i.strip() for i in f.readlines()])
return all_cmds - covered_cmds
if __name__ == '__main__':
main()
|
waseem18/bedrock | refs/heads/master | vendor-local/src/django-recaptcha/captcha/tests.py | 11 | import unittest
from captcha import fields, forms, models, widgets
class TestCase(unittest.TestCase):
def test_something(self):
raise NotImplementedError('Test not implemented. Bad developer!')
|
DrOctogon/Satchmo | refs/heads/master | satchmo/apps/satchmo_ext/productratings/utils.py | 12 | from django.conf import settings
from django.contrib.comments.models import Comment
from django.contrib.sites.models import Site
from django.db.models import Avg
from django.utils.translation import ugettext_lazy as _
from satchmo_ext.productratings.models import ProductRating
import logging
import operator
log = logging.getLogger('product.comments.utils')
def average(ratings):
""" Average a list of numbers, return None if it fails """
if ratings:
ratings = filter(lambda x: x is not None, ratings)
if ratings:
total = reduce(operator.add, ratings)
if total != None:
return float(total)/len(ratings)
return None
def get_product_rating(product, site=None):
"""Get the average product rating"""
if site is None:
site = Site.objects.get_current()
site = site.id
manager = Comment.objects
comment_pks = manager.filter(object_pk__exact=str(product.id),
content_type__app_label__exact='product',
content_type__model__exact='product',
site__id__exact=site,
is_public__exact=True).values_list('pk', flat=True)
rating = ProductRating.objects.filter(comment__in=comment_pks
).aggregate(average=Avg('rating'))['average']
log.debug("Rating: %s", rating)
return rating
def get_product_rating_string(product, site=None):
"""Get the average product rating as a string, for use in templates"""
rating = get_product_rating(product, site=site)
if rating is not None:
rating = "%0.1f" % rating
if rating.endswith('.0'):
rating = rating[0]
rating = rating + "/5"
else:
rating = _('Not Rated')
return rating
|
cclib/cclib | refs/heads/master | test/regression.py | 2 | # This file is part of cclib (http://cclib.github.io), a library for parsing
# and interpreting the results of computational chemistry packages.
#
# Copyright (C) 2020, the cclib development team
#
# The library is free software, distributed under the terms of
# the GNU Lesser General Public version 2.1 or later. You should have
# received a copy of the license along with cclib. You can also access
# the full license online at http://www.gnu.org/copyleft/lgpl.html.
"""A regression framework for parsing and testing logfiles.
The intention here is to make it easy to add new datafiles as bugs
are fixed and to write specific tests in the form of test functions.
In short, the file called regressionfiles.txt contains a list of regression
logfiles, which is compared to the files found on disk. All these files
should be parsed correctly, and if there is an appropriately named function
defined, that function will be used as a test.
There is also a mechanism for running unit tests on old logfiles, which
have been moved here from the cclib repository when newer versions
became available. We still want those logfiles to parse and test correctly,
although sometimes special modification will be needed.
To run the doctest, run `python -m test.regression` from the top level
directory in the cclib repository.
Running all regression can take anywhere from 10-20s to several minutes
depending in your hardware. To aid debugging, there are two ways to limit
which regressions to parse and test. You can limit the test to a specific
parse, for example:
python -m test.regression Gaussian
You can also limit a run to a single output file, using it's relative path
inside the data directory, like so:
python -m test.regression Gaussian/Gaussian03/borane-opt.log
"""
import glob
import logging
import os
import sys
import traceback
import unittest
import numpy
from packaging.version import parse as parse_version
from packaging.version import Version
from cclib.parser.utils import convertor
from cclib.parser import ccData
from cclib.parser import ADF
from cclib.parser import DALTON
from cclib.parser import FChk
from cclib.parser import GAMESS
from cclib.parser import GAMESSUK
from cclib.parser import Gaussian
from cclib.parser import Jaguar
from cclib.parser import Molcas
from cclib.parser import Molpro
from cclib.parser import MOPAC
from cclib.parser import NWChem
from cclib.parser import ORCA
from cclib.parser import Psi3
from cclib.parser import Psi4
from cclib.parser import QChem
from cclib.parser import Turbomole
from cclib.io import ccopen, ccread, moldenwriter
# This assume that the cclib-data repository is located at a specific location
# within the cclib repository. It would be better to figure out a more natural
# way to import the relevant tests from cclib here.
test_dir = os.path.realpath(os.path.dirname(__file__)) + "/../../test"
# This is safer than sys.path.append, and isn't sys.path.insert(0, ...) so
# virtualenvs work properly. See https://stackoverflow.com/q/10095037.
sys.path.insert(1, os.path.abspath(test_dir))
from .test_data import all_modules
from .test_data import all_parsers
from .test_data import module_names
from .test_data import parser_names
from .test_data import get_program_dir
# We need this to point to files relative to this script.
__filedir__ = os.path.abspath(os.path.dirname(__file__))
__regression_dir__ = os.path.join(__filedir__, "../data/regression/")
# The following regression test functions were manually written, because they
# contain custom checks that were determined on a per-file basis. Care needs to be taken
# that the function name corresponds to the path of the logfile, with some characters
# changed according to normalisefilename().
# ADF #
def testADF_ADF2004_01_Fe_ox3_final_out(logfile):
"""Make sure HOMOS are correct."""
assert logfile.data.homos[0] == 59 and logfile.data.homos[1] == 54
assert logfile.data.metadata["legacy_package_version"] == "2004.01"
assert logfile.data.metadata["package_version"] == "2004.01+200410211341"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
def testADF_ADF2013_01_dvb_gopt_b_unconverged_adfout(logfile):
"""An unconverged geometry optimization to test for empty optdone (see #103 for details)."""
assert hasattr(logfile.data, 'optdone') and not logfile.data.optdone
assert logfile.data.metadata["legacy_package_version"] == "2013.01"
assert logfile.data.metadata["package_version"] == "2013.01+201309012319"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
def testADF_ADF2013_01_stopiter_dvb_sp_adfout(logfile):
"""This logfile has not SCF test lines so we have no way to check what happens."""
# This is what we would have checked:
# len(logfile.data.scfvalues[0]) == 10
assert not hasattr(logfile.data, "scfvalues")
assert logfile.data.metadata["package_version"] == "2013.01+201309012319"
def testADF_ADF2013_01_stopiter_dvb_sp_b_adfout(logfile):
"""Check to ensure that an incomplete SCF is handled correctly."""
# Why is this not 3?
assert len(logfile.data.scfvalues[0]) == 2
assert logfile.data.metadata["package_version"] == "2013.01+201309012319"
def testADF_ADF2013_01_stopiter_dvb_sp_c_adfout(logfile):
"""This logfile has not SCF test lines so we have no way to check what happens."""
# This is what we would have checked:
# len(logfile.data.scfvalues[0]) == 6
assert not hasattr(logfile.data, "scfvalues")
assert logfile.data.metadata["package_version"] == "2013.01+201309012319"
def testADF_ADF2013_01_stopiter_dvb_sp_d_adfout(logfile):
"""This logfile has not SCF test lines so we have no way to check what happens."""
# This is what we would have checked:
# len(logfile.data.scfvalues[0]) == 7
assert not hasattr(logfile.data, "scfvalues")
assert logfile.data.metadata["package_version"] == "2013.01+201309012319"
def testADF_ADF2013_01_stopiter_dvb_un_sp_adfout(logfile):
"""This logfile has not SCF test lines so we have no way to check what happens."""
# This is what we would have checked:
# len(logfile.data.scfvalues[0]) == 7
assert not hasattr(logfile.data, "scfvalues")
assert logfile.data.metadata["package_version"] == "2013.01+201309012319"
def testADF_ADF2013_01_stopiter_dvb_un_sp_c_adfout(logfile):
"""This logfile has not SCF test lines so we have no way to check what happens."""
# This is what we would have checked:
# len(logfile.data.scfvalues[0]) == 10
assert not hasattr(logfile.data, "scfvalues")
assert logfile.data.metadata["package_version"] == "2013.01+201309012319"
def testADF_ADF2013_01_stopiter_MoOCl4_sp_adfout(logfile):
"""This logfile has not SCF test lines so we have no way to check what happens."""
# This is what we would have checked:
# len(logfile.data.scfvalues[0]) == 11
assert not hasattr(logfile.data, "scfvalues")
assert logfile.data.metadata["package_version"] == "2013.01+201309012319"
def testADF_ADF2014_01_DMO_ORD_orig_out(logfile):
"""In lieu of a unit test, make sure the polarizability (and
potentially later the optical rotation) is properly parsed.
"""
assert hasattr(logfile.data, 'polarizabilities')
assert len(logfile.data.polarizabilities) == 1
assert logfile.data.polarizabilities[0].shape == (3, 3)
# isotropic polarizability
isotropic_calc = numpy.average(numpy.diag(logfile.data.polarizabilities[0]))
isotropic_ref = 51.3359
assert abs(isotropic_calc - isotropic_ref) < 1.0e-4
assert logfile.data.metadata["legacy_package_version"] == "2014"
assert logfile.data.metadata["package_version"] == "2014dev42059"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
assert logfile.data.metadata["package_version_date"] == "2014-06-11"
assert logfile.data.metadata["package_version_description"] == "development version"
def testADF_ADF2016_166_tddft_0_31_new_out(logfile):
"""This file led to StopIteration (#430)."""
assert logfile.data.metadata["legacy_package_version"] == "2016"
assert logfile.data.metadata["package_version"] == "2016dev53619"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
assert logfile.data.metadata["package_version_date"] == "2016-07-21"
assert "package_version_description" not in logfile.data.metadata
def testADF_ADF2016_fa2_adf_out(logfile):
"""This logfile, without symmetry, should get atombasis parsed."""
assert hasattr(logfile.data, "atombasis")
assert [b for ab in logfile.data.atombasis for b in ab] == list(range(logfile.data.nbasis))
assert logfile.data.metadata["legacy_package_version"] == "2016"
assert logfile.data.metadata["package_version"] == "2016dev50467"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
assert logfile.data.metadata["package_version_date"] == "2016-02-17"
assert logfile.data.metadata["package_version_description"] == "branches/AndrewAtkins/ADF-Shar"
# DALTON #
def testDALTON_DALTON_2013_dvb_td_normalprint_out(logfile):
r"""This original unit test prints a DFT-specific version of the excitation
eigenvectors, which we do not parse.
Here is an example of the general output (requiring `**RESPONSE/.PRINT 4`
for older versions of DALTON), followed by "PBHT MO Overlap Diagnostic"
which only appears for DFT calculations. Note that the reason we cannot
parse this for etsyms is it doesn't contain the necessary
coefficient. "K_IA" and "(r s) operator", which is $\kappa_{rs}$, the
coefficient for excitation from the r -> s MO in the response vector, is
not what most programs print; it is "(r s) scaled", which is $\kappa_{rs}
* \sqrt{S_{rr} - S_{ss}}$. Because this isn't available from the PBHT
output, we cannot parse it.
Eigenvector for state no. 1
Response orbital operator symmetry = 1
(only scaled elements abs greater than 10.00 % of max abs value)
Index(r,s) r s (r s) operator (s r) operator (r s) scaled (s r) scaled
---------- ----- ----- -------------- -------------- -------------- --------------
154 27(2) 28(2) 0.5645327267 0.0077924161 0.7983698385 0.0110201405
311 58(4) 59(4) -0.4223079545 0.0137981027 -0.5972336367 0.0195134639
...
PBHT MO Overlap Diagnostic
--------------------------
I A K_IA K_AI <|I|*|A|> <I^2*A^2> Weight Contrib
27 28 0.564533 0.007792 0.790146 0.644560 0.309960 0.244913
58 59 -0.422308 0.013798 0.784974 0.651925 0.190188 0.149293
In the future, if `aooverlaps` and `mocoeffs` are available, it may be
possible to calculate the necessary scaled coefficients for `etsecs`.
"""
assert hasattr(logfile.data, "etenergies")
assert not hasattr(logfile.data, "etsecs")
assert hasattr(logfile.data, "etsyms")
assert hasattr(logfile.data, "etoscs")
assert logfile.data.metadata["legacy_package_version"] == "2013.4"
assert logfile.data.metadata["package_version"] == "2013.4+7abef2ada27562fe5e02849d6caeaa67c961732f"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
def testDALTON_DALTON_2015_dalton_atombasis_out(logfile):
"""This logfile didn't parse due to the absence of a line in the basis
set section.
"""
assert hasattr(logfile.data, "nbasis")
assert logfile.data.nbasis == 37
assert hasattr(logfile.data, "atombasis")
assert logfile.data.metadata["legacy_package_version"] == "2015.0"
assert logfile.data.metadata["package_version"] == "2015.0+d34efb170c481236ad60c789dea90a4c857c6bab"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
def testDALTON_DALTON_2015_dalton_intgrl_out(logfile):
"""This logfile didn't parse due to the absence of a line in the basis
set section.
"""
assert hasattr(logfile.data, "nbasis")
assert logfile.data.nbasis == 4
assert hasattr(logfile.data, "atombasis")
assert logfile.data.metadata["package_version"] == "2015.0+d34efb170c481236ad60c789dea90a4c857c6bab"
def testDALTON_DALTON_2015_dvb_td_normalprint_out(logfile):
"""This original unit test prints a DFT-specific version of the excitation
eigenvectors, which we do not parse.
"""
assert hasattr(logfile.data, "etenergies")
assert not hasattr(logfile.data, "etsecs")
assert hasattr(logfile.data, "etsyms")
assert hasattr(logfile.data, "etoscs")
assert logfile.data.metadata["package_version"] == "2015.0+d34efb170c481236ad60c789dea90a4c857c6bab"
def testDALTON_DALTON_2015_stopiter_dalton_dft_out(logfile):
"""Check to ensure that an incomplete SCF is handled correctly."""
assert len(logfile.data.scfvalues[0]) == 8
assert logfile.data.metadata["package_version"] == "2015.0+d34efb170c481236ad60c789dea90a4c857c6bab"
def testDALTON_DALTON_2015_stopiter_dalton_hf_out(logfile):
"""Check to ensure that an incomplete SCF is handled correctly."""
assert len(logfile.data.scfvalues[0]) == 5
assert logfile.data.metadata["package_version"] == "2015.0+d34efb170c481236ad60c789dea90a4c857c6bab"
def testDALTON_DALTON_2016_huge_neg_polar_freq_out(logfile):
"""This is an example of a multiple frequency-dependent polarizability
calculation.
"""
assert hasattr(logfile.data, "polarizabilities")
assert len(logfile.data.polarizabilities) == 3
assert abs(logfile.data.polarizabilities[2][0, 0] - 183.6308) < 1.0e-5
assert logfile.data.metadata["legacy_package_version"] == "2016.2"
assert logfile.data.metadata["package_version"] == "2016.2+7db4647eac203e51aae7da3cbc289f55146b30e9"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
def testDALTON_DALTON_2016_huge_neg_polar_stat_out(logfile):
"""This logfile didn't parse due to lack of spacing between
polarizability tensor elements.
"""
assert hasattr(logfile.data, "polarizabilities")
assert len(logfile.data.polarizabilities) == 1
assert abs(logfile.data.polarizabilities[0][1, 1] + 7220.150408) < 1.0e-7
assert logfile.data.metadata["package_version"] == "2016.2+7db4647eac203e51aae7da3cbc289f55146b30e9"
def testDALTON_DALTON_2016_Trp_polar_response_diplnx_out(logfile):
"""Check that only the xx component of polarizability is defined and
all others are NaN even after parsing a previous file with full tensor.
"""
full_tens_path = os.path.join(__regression_dir__, "DALTON/DALTON-2015/Trp_polar_response.out")
DALTON(full_tens_path, loglevel=logging.ERROR).parse()
assert hasattr(logfile.data, "polarizabilities")
assert abs(logfile.data.polarizabilities[0][0, 0] - 95.11540019) < 1.0e-8
assert numpy.count_nonzero(numpy.isnan(logfile.data.polarizabilities)) == 8
assert logfile.data.metadata["package_version"] == "2016.2+7db4647eac203e51aae7da3cbc289f55146b30e9"
def testDALTON_DALTON_2018_dft_properties_nosym_H2O_cc_pVDZ_out(logfile):
"""The "simple" version string in newer development versions of DALTON wasn't
being parsed properly.
This file is in DALTON-2018, rather than DALTON-2019, because 2018.0 was
just released.
"""
assert logfile.data.metadata["legacy_package_version"] == "2019.alpha"
assert logfile.data.metadata["package_version"] == "2019.alpha"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
def testDALTON_DALTON_2018_tdhf_2000_out(logfile):
"""Ensure etsecs are being parsed from a TDHF calculation without symmetry and
a big print level.
"""
assert hasattr(logfile.data, "etsecs")
for attr in ("etenergies", "etsecs", "etsyms", "etoscs"):
assert len(getattr(logfile.data, attr)) == 9
assert logfile.data.etsecs[0][0] == [(1, 0), (2, 0), -0.9733558768]
assert logfile.data.metadata["legacy_package_version"] == "2019.alpha"
assert logfile.data.metadata["package_version"] == "2019.alpha+25947a3d842ee2ebb42bff87a4dd64adbbd3ec5b"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
def testDALTON_DALTON_2018_tdhf_2000_sym_out(logfile):
"""Ensure etsecs are being parsed from a TDHF calculation with symmetry and a
big print level.
"""
assert hasattr(logfile.data, "etsecs")
for attr in ("etenergies", "etsecs", "etsyms", "etoscs"):
assert len(getattr(logfile.data, attr)) == 3
assert logfile.data.etsecs[0][0] == [(1, 0), (2, 0), 0.9733562358]
assert logfile.data.metadata["package_version"] == "2019.alpha+25947a3d842ee2ebb42bff87a4dd64adbbd3ec5b"
def testDALTON_DALTON_2018_tdhf_normal_out(logfile):
"""Ensure etsecs are being parsed from a TDHF calculation without symmetry and
a normal print level.
"""
assert hasattr(logfile.data, "etsecs")
for attr in ("etenergies", "etsecs", "etsyms", "etoscs"):
assert len(getattr(logfile.data, attr)) == 9
assert logfile.data.etsecs[0][0] == [(1, 0), (2, 0), -0.9733558768]
assert logfile.data.metadata["package_version"] == "2019.alpha+25947a3d842ee2ebb42bff87a4dd64adbbd3ec5b"
def testDALTON_DALTON_2018_tdhf_normal_sym_out(logfile):
"""Ensure etsecs are being parsed from a TDHF calculation with symmetry and a
normal print level.
"""
assert hasattr(logfile.data, "etsecs")
for attr in ("etenergies", "etsecs", "etsyms", "etoscs"):
assert len(getattr(logfile.data, attr)) == 3
assert logfile.data.etsecs[0][0] == [(1, 0), (2, 0), 0.9733562358]
assert logfile.data.metadata["package_version"] == "2019.alpha+25947a3d842ee2ebb42bff87a4dd64adbbd3ec5b"
def testDALTON_DALTON_2018_tdpbe_2000_out(logfile):
"""Ensure etsecs are being parsed from a TDDFT calculation without symmetry
and a big print level.
"""
assert hasattr(logfile.data, "etsecs")
for attr in ("etenergies", "etsecs", "etsyms", "etoscs"):
assert len(getattr(logfile.data, attr)) == 9
assert logfile.data.etsecs[0][0] == [(1, 0), (2, 0), 0.9992665559]
assert logfile.data.metadata["package_version"] == "2019.alpha+25947a3d842ee2ebb42bff87a4dd64adbbd3ec5b"
def testDALTON_DALTON_2018_tdpbe_2000_sym_out(logfile):
"""Ensure etsecs are being parsed from a TDDFT calculation with symmetry and a
big print level.
"""
assert hasattr(logfile.data, "etsecs")
for attr in ("etenergies", "etsecs", "etsyms", "etoscs"):
assert len(getattr(logfile.data, attr)) == 3
assert logfile.data.etsecs[0][0] == [(1, 0), (2, 0), 0.9992672154]
assert logfile.data.metadata["package_version"] == "2019.alpha+25947a3d842ee2ebb42bff87a4dd64adbbd3ec5b"
def testDALTON_DALTON_2018_tdpbe_normal_out(logfile):
"""Ensure etsecs are being parsed from a TDDFT calculation without symmetry
and a normal print level.
"""
assert hasattr(logfile.data, "etsecs")
for attr in ("etenergies", "etsecs", "etsyms", "etoscs"):
assert len(getattr(logfile.data, attr)) == 9
assert logfile.data.etsecs[0][0] == [(1, 0), (2, 0), 0.9992665559]
assert logfile.data.metadata["package_version"] == "2019.alpha+25947a3d842ee2ebb42bff87a4dd64adbbd3ec5b"
def testDALTON_DALTON_2018_tdpbe_normal_sym_out(logfile):
"""Ensure etsecs are being parsed from a TDDFT calculation with symmetry and a
normal print level.
"""
assert hasattr(logfile.data, "etsecs")
for attr in ("etenergies", "etsecs", "etsyms", "etoscs"):
assert len(getattr(logfile.data, attr)) == 3
assert logfile.data.etsecs[0][0] == [(1, 0), (2, 0), 0.9992672154]
assert logfile.data.metadata["package_version"] == "2019.alpha+25947a3d842ee2ebb42bff87a4dd64adbbd3ec5b"
# Firefly #
def testGAMESS_Firefly8_0_dvb_gopt_a_unconverged_out(logfile):
"""An unconverged geometry optimization to test for empty optdone (see #103 for details)."""
assert hasattr(logfile.data, 'optdone') and not logfile.data.optdone
assert logfile.data.metadata["legacy_package_version"] == "8.0.1"
assert logfile.data.metadata["package_version"] == "8.0.1+8540"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
def testGAMESS_Firefly8_0_h2o_log(logfile):
"""Check that molecular orbitals are parsed correctly (cclib/cclib#208)."""
assert logfile.data.mocoeffs[0][0][0] == -0.994216
assert logfile.data.metadata["legacy_package_version"] == "8.0.0"
assert logfile.data.metadata["package_version"] == "8.0.0+7651"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
def testGAMESS_Firefly8_0_stopiter_firefly_out(logfile):
"""Check to ensure that an incomplete SCF is handled correctly."""
assert len(logfile.data.scfvalues[0]) == 6
assert logfile.data.metadata["package_version"] == "8.0.1+8540"
def testGAMESS_Firefly8_1_benzene_am1_log(logfile):
"""Molecular orbitals were not parsed (cclib/cclib#228)."""
assert hasattr(logfile.data, 'mocoeffs')
assert logfile.data.metadata["legacy_package_version"] == "8.1.0"
assert logfile.data.metadata["package_version"] == "8.1.0+9035"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
def testGAMESS_Firefly8_1_naphtalene_t_0_out(logfile):
"""Molecular orbitals were not parsed (cclib/cclib#228)."""
assert hasattr(logfile.data, 'mocoeffs')
assert logfile.data.metadata["legacy_package_version"] == "8.1.1"
assert logfile.data.metadata["package_version"] == "8.1.1+9295"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
def testGAMESS_Firefly8_1_naphtalene_t_0_SP_out(logfile):
"""Molecular orbitals were not parsed (cclib/cclib#228)."""
assert hasattr(logfile.data, 'mocoeffs')
assert logfile.data.metadata["package_version"] == "8.1.1+9295"
# GAMESS #
def testGAMESS_GAMESS_US2008_N2_UMP2_out(logfile):
"""Check that the new format for GAMESS MP2 is parsed."""
assert hasattr(logfile.data, "mpenergies")
assert len(logfile.data.mpenergies) == 1
assert abs(logfile.data.mpenergies[0] + 2975.97) < 0.01
assert logfile.data.metadata["legacy_package_version"] == "2008R1"
assert logfile.data.metadata["package_version"] == "2008.r1"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
def testGAMESS_GAMESS_US2008_N2_ROMP2_out(logfile):
"""Check that the new format for GAMESS MP2 is parsed."""
assert hasattr(logfile.data, "mpenergies")
assert len(logfile.data.mpenergies) == 1
assert abs(logfile.data.mpenergies[0] + 2975.97) < 0.01
assert logfile.data.metadata["package_version"] == "2008.r1"
def testGAMESS_GAMESS_US2009_open_shell_ccsd_test_log(logfile):
"""Parse ccenergies from open shell CCSD calculations."""
assert hasattr(logfile.data, "ccenergies")
assert len(logfile.data.ccenergies) == 1
assert abs(logfile.data.ccenergies[0] + 3501.50) < 0.01
assert logfile.data.metadata["legacy_package_version"] == "2009R3"
assert logfile.data.metadata["package_version"] == "2009.r3"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
def testGAMESS_GAMESS_US2009_paulo_h2o_mp2_out(logfile):
"""Check that the new format for GAMESS MP2 is parsed."""
assert hasattr(logfile.data, "mpenergies")
assert len(logfile.data.mpenergies) == 1
assert abs(logfile.data.mpenergies[0] + 2072.13) < 0.01
assert logfile.data.metadata["package_version"] == "2009.r3"
def testGAMESS_GAMESS_US2012_dvb_gopt_a_unconverged_out(logfile):
"""An unconverged geometry optimization to test for empty optdone (see #103 for details)."""
assert hasattr(logfile.data, 'optdone') and not logfile.data.optdone
assert logfile.data.metadata["legacy_package_version"] == "2012R2"
assert logfile.data.metadata["package_version"] == "2012.r2"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
def testGAMESS_GAMESS_US2012_stopiter_gamess_out(logfile):
"""Check to ensure that an incomplete SCF is handled correctly."""
assert len(logfile.data.scfvalues[0]) == 10
assert logfile.data.metadata["package_version"] == "2012.r1"
def testGAMESS_GAMESS_US2013_N_UHF_out(logfile):
"""An UHF job that has an LZ value analysis between the alpha and beta orbitals."""
assert len(logfile.data.moenergies) == 2
assert logfile.data.metadata["legacy_package_version"] == "2013R1"
assert logfile.data.metadata["package_version"] == "2013.r1"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
def testGAMESS_GAMESS_US2014_CdtetraM1B3LYP_log(logfile):
"""This logfile had coefficients for only 80 molecular orbitals."""
assert len(logfile.data.mocoeffs) == 2
assert numpy.count_nonzero(logfile.data.mocoeffs[0][79-1:, :]) == 258
assert numpy.count_nonzero(logfile.data.mocoeffs[0][80-1: 0:]) == 0
assert logfile.data.mocoeffs[0].all() == logfile.data.mocoeffs[1].all()
assert logfile.data.metadata["legacy_package_version"] == "2014R1"
assert logfile.data.metadata["package_version"] == "2014.r1"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
def testGAMESS_GAMESS_US2018_exam45_log(logfile):
"""This logfile has EOM-CC electronic transitions (not currently supported)."""
assert not hasattr(logfile.data, 'etenergies')
assert logfile.data.metadata["legacy_package_version"] == "2018R2"
assert logfile.data.metadata["package_version"] == "2018.r2"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
def testGAMESS_GAMESS_US2018_exam46_log(logfile):
"""
This logfile has >100 scf iterations, which used to cause
a parsing error.
"""
assert len(logfile.data.scfvalues[0]) == 113
assert logfile.data.metadata["legacy_package_version"] == "2018R3"
assert logfile.data.metadata["package_version"] == "2018.r3"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
def testGAMESS_WinGAMESS_dvb_td_trplet_2007_03_24_r1_out(logfile):
"""Do some basic checks for this old unit test that was failing.
The unit tests are not run automatically on this old unit logfile,
because we know the output has etsecs whose sum is way off.
So, perform a subset of the basic assertions for GenericTDTesttrp.
"""
number = 5
assert len(logfile.data.etenergies) == number
idx_lambdamax = [i for i, x in enumerate(logfile.data.etoscs) if x == max(logfile.data.etoscs)][0]
assert abs(logfile.data.etenergies[idx_lambdamax] - 24500) < 100
assert len(logfile.data.etoscs) == number
assert abs(max(logfile.data.etoscs) - 0.0) < 0.01
assert len(logfile.data.etsecs) == number
assert logfile.data.metadata["legacy_package_version"] == "2007R1"
assert logfile.data.metadata["package_version"] == "2007.r1"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
def testnoparseGAMESS_WinGAMESS_H2O_def2SVPD_triplet_2019_06_30_R1_out(logfile):
"""Check if the molden writer can handle an unrestricted case
"""
data = ccread(os.path.join(__filedir__,logfile))
writer = moldenwriter.MOLDEN(data)
# Check size of Atoms section.
assert len(writer._mo_from_ccdata()) == (data.nbasis + 4) * (data.nmo * 2)
# check docc orbital
beta_idx = (data.nbasis + 4) * data.nmo
assert "Beta" in writer._mo_from_ccdata()[beta_idx + 2]
assert "Occup= 1.000000" in writer._mo_from_ccdata()[beta_idx + 3]
assert "0.989063" in writer._mo_from_ccdata()[beta_idx + 4]
# GAMESS-UK #
def testGAMESS_UK_GAMESS_UK8_0_dvb_gopt_hf_unconverged_out(logfile):
assert hasattr(logfile.data, 'optdone') and not logfile.data.optdone
assert logfile.data.metadata["legacy_package_version"] == "8.0"
assert logfile.data.metadata["package_version"] == "8.0+6248"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
def testGAMESS_UK_GAMESS_UK8_0_stopiter_gamessuk_dft_out(logfile):
"""Check to ensure that an incomplete SCF is handled correctly."""
assert len(logfile.data.scfvalues[0]) == 7
assert logfile.data.metadata["package_version"] == "8.0+6248"
def testGAMESS_UK_GAMESS_UK8_0_stopiter_gamessuk_hf_out(logfile):
"""Check to ensure that an incomplete SCF is handled correctly."""
assert len(logfile.data.scfvalues[0]) == 5
assert logfile.data.metadata["package_version"] == "8.0+6248"
# Gaussian #
def testGaussian_Gaussian98_C_bigmult_log(logfile):
"""
This file failed first becuase it had a double digit multiplicity.
Then it failed because it had no alpha virtual orbitals.
"""
assert logfile.data.charge == -3
assert logfile.data.mult == 10
assert logfile.data.homos[0] == 8
assert logfile.data.homos[1] == -1 # No occupied beta orbitals
assert logfile.data.metadata["legacy_package_version"] == "98revisionA.11.3"
assert logfile.data.metadata["package_version"] == "1998+A.11.3"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
def testGaussian_Gaussian98_NIST_CCCBDB_1himidaz_m21b0_out(logfile):
"""A G3 computation is a sequence of jobs."""
# All steps deal with the same molecule, so we extract the coordinates
# from all steps.
assert len(logfile.data.atomcoords) == 10
# Different G3 steps do perturbation to different orders, and so
# we expect only the last MP2 energy to be extracted.
assert len(logfile.data.mpenergies) == 1
assert logfile.data.metadata["legacy_package_version"] == "98revisionA.7"
assert logfile.data.metadata["package_version"] == "1998+A.7"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
def testGaussian_Gaussian98_NIST_CCCBDB_1himidaz_m23b6_out(logfile):
"""A job that was killed before it ended, should have several basic attributes parsed."""
assert hasattr(logfile.data, 'charge')
assert hasattr(logfile.data, 'metadata')
assert hasattr(logfile.data, 'mult')
assert logfile.data.metadata["package_version"] == "1998+A.7"
def testGaussian_Gaussian98_test_Cu2_log(logfile):
"""An example of the number of basis set function changing."""
assert logfile.data.nbasis == 38
assert logfile.data.metadata["legacy_package_version"] == "98revisionA.11.4"
assert logfile.data.metadata["package_version"] == "1998+A.11.4"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
def testGaussian_Gaussian98_test_H2_log(logfile):
"""
The atomic charges from a natural population analysis were
not parsed correctly, and they should be zero for dihydrogen.
"""
assert logfile.data.atomcharges['natural'][0] == 0.0
assert logfile.data.atomcharges['natural'][1] == 0.0
assert logfile.data.metadata["package_version"] == "1998+A.11.4"
def testGaussian_Gaussian98_water_zmatrix_nosym_log(logfile):
"""This file is missing natom.
This file had no atomcoords as it did not contain either an
"Input orientation" or "Standard orientation section".
As a result it failed to parse. Fixed in r400.
"""
assert len(logfile.data.atomcoords) == 1
assert logfile.data.natom == 3
assert logfile.data.metadata["package_version"] == "1998+A.11.3"
def testGaussian_Gaussian03_AM1_SP_out(logfile):
"""Previously, caused scfvalue parsing to fail."""
assert len(logfile.data.scfvalues[0]) == 13
assert logfile.data.metadata["legacy_package_version"] == "03revisionE.01"
assert logfile.data.metadata["package_version"] == "2003+E.01"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
def testGaussian_Gaussian03_anthracene_log(logfile):
"""This file exposed a bug in extracting the vibsyms."""
assert len(logfile.data.vibsyms) == len(logfile.data.vibfreqs)
assert logfile.data.metadata["legacy_package_version"] == "03revisionC.02"
assert logfile.data.metadata["package_version"] == "2003+C.02"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
def testGaussian_Gaussian03_borane_opt_log(logfile):
"""An example of changing molecular orbital count."""
assert logfile.data.optstatus[-1] == logfile.data.OPT_DONE
assert logfile.data.nmo == 609
assert logfile.data.metadata["package_version"] == "2003+E.01"
def testGaussian_Gaussian03_chn1_log(logfile):
"""
This file failed to parse, due to the use of 'pop=regular'.
We have decided that mocoeffs should not be defined for such calculations.
"""
assert not hasattr(logfile.data, "mocoeffs")
assert logfile.data.metadata["legacy_package_version"] == "03revisionB.04"
assert logfile.data.metadata["package_version"] == "2003+B.04"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
def testGaussian_Gaussian03_cyclopropenyl_rhf_g03_cut_log(logfile):
"""
Not using symmetry at all (option nosymm) means standard orientation
is not printed. In this case inputcoords are copied by the parser,
which up till now stored the last coordinates.
"""
assert len(logfile.data.atomcoords) == len(logfile.data.geovalues)
assert logfile.data.metadata["package_version"] == "2003+C.02"
def testGaussian_Gaussian03_DCV4T_C60_log(logfile):
"""This is a test for a very large Gaussian file with > 99 atoms.
The log file is too big, so we are just including the start.
Previously, parsing failed in the pseudopotential section.
"""
assert len(logfile.data.coreelectrons) == 102
assert logfile.data.coreelectrons[101] == 2
assert logfile.data.metadata["legacy_package_version"] == "03revisionD.02"
assert logfile.data.metadata["package_version"] == "2003+D.02"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
def testGaussian_Gaussian03_dvb_gopt_symmfollow_log(logfile):
"""Non-standard treatment of symmetry.
In this case the Standard orientation is also printed non-standard,
which caused only the first coordinates to be read previously.
"""
assert len(logfile.data.atomcoords) == len(logfile.data.geovalues)
assert logfile.data.metadata["legacy_package_version"] == "03revisionC.01"
assert logfile.data.metadata["package_version"] == "2003+C.01"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
def testGaussian_Gaussian03_mendes_out(logfile):
"""Previously, failed to extract coreelectrons."""
centers = [9, 10, 11, 27]
for i, x in enumerate(logfile.data.coreelectrons):
if i in centers:
assert x == 10
else:
assert x == 0
assert logfile.data.metadata["package_version"] == "2003+C.02"
def testGaussian_Gaussian03_Mo4OSibdt2_opt_log(logfile):
"""
This file had no atomcoords as it did not contain any
"Input orientation" sections, only "Standard orientation".
"""
assert logfile.data.optstatus[-1] == logfile.data.OPT_DONE
assert hasattr(logfile.data, "atomcoords")
assert logfile.data.metadata["package_version"] == "2003+C.02"
def testGaussian_Gaussian03_orbgs_log(logfile):
"""Check that the pseudopotential is being parsed correctly."""
assert hasattr(logfile.data, "coreelectrons"), "Missing coreelectrons"
assert logfile.data.coreelectrons[0] == 28
assert logfile.data.coreelectrons[15] == 10
assert logfile.data.coreelectrons[20] == 10
assert logfile.data.coreelectrons[23] == 10
assert logfile.data.metadata["package_version"] == "2003+C.02"
def testGaussian_Gaussian09_100_g09(logfile):
"""Check that the final system is the one parsed (cclib/cclib#243)."""
assert logfile.data.natom == 54
assert logfile.data.homos == [104]
assert logfile.data.metadata["legacy_package_version"] == "09revisionB.01"
assert logfile.data.metadata["package_version"] == "2009+B.01"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
def testGaussian_Gaussian09_25DMF_HRANH_log(logfile):
"""Check that the anharmonicities are being parsed correctly."""
assert hasattr(logfile.data, "vibanharms"), "Missing vibanharms"
anharms = logfile.data.vibanharms
N = len(logfile.data.vibfreqs)
assert 39 == N == anharms.shape[0] == anharms.shape[1]
assert abs(anharms[0][0] + 43.341) < 0.01
assert abs(anharms[N-1][N-1] + 36.481) < 0.01
assert logfile.data.metadata["package_version"] == "2009+B.01"
def testGaussian_Gaussian09_2D_PES_all_converged_log(logfile):
"""Check that optstatus has no UNCOVERGED values."""
assert ccData.OPT_UNCONVERGED not in logfile.data.optstatus
assert logfile.data.metadata["legacy_package_version"] == "09revisionD.01"
assert logfile.data.metadata["package_version"] == "2009+D.01"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
# The energies printed in the scan summary are misformated.
assert numpy.all(numpy.isnan(logfile.data.scanenergies))
def testGaussian_Gaussian09_2D_PES_one_unconverged_log(logfile):
"""Check that optstatus contains UNCOVERGED values."""
assert ccData.OPT_UNCONVERGED in logfile.data.optstatus
assert logfile.data.metadata["package_version"] == "2009+D.01"
def testGaussian_Gaussian09_534_out(logfile):
"""Previously, caused etenergies parsing to fail."""
assert logfile.data.etsyms[0] == "Singlet-?Sym"
assert abs(logfile.data.etenergies[0] - 20920.55328) < 1.0
assert logfile.data.metadata["legacy_package_version"] == "09revisionA.02"
assert logfile.data.metadata["package_version"] == "2009+A.02"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
def testGaussian_Gaussian09_BSL_opt_freq_DFT_out(logfile):
"""Failed for converting to CJSON when moments weren't parsed for
Gaussian.
"""
assert hasattr(logfile.data, 'moments')
# dipole Y
assert logfile.data.moments[1][1] == 0.5009
# hexadecapole ZZZZ
assert logfile.data.moments[4][-1] == -77.9600
assert logfile.data.metadata["package_version"] == "2009+D.01"
def testGaussian_Gaussian09_dvb_gopt_unconverged_log(logfile):
"""An unconverged geometry optimization to test for empty optdone (see #103 for details)."""
assert hasattr(logfile.data, 'optdone') and not logfile.data.optdone
assert logfile.data.optstatus[-1] == logfile.data.OPT_UNCONVERGED
assert logfile.data.metadata["package_version"] == "2009+D.01"
def testGaussian_Gaussian09_dvb_lowdin_log(logfile):
"""Check if both Mulliken and Lowdin charges are parsed."""
assert "mulliken" in logfile.data.atomcharges
assert "lowdin" in logfile.data.atomcharges
assert logfile.data.metadata["package_version"] == "2009+A.02"
def testGaussian_Gaussian09_Dahlgren_TS_log(logfile):
"""Failed to parse ccenergies for a variety of reasons"""
assert hasattr(logfile.data, "ccenergies")
assert abs(logfile.data.ccenergies[0] - (-11819.96506609)) < 0.001
assert logfile.data.metadata["package_version"] == "2009+A.02"
def testGaussian_Gaussian09_irc_point_log(logfile):
"""Failed to parse vibfreqs except for 10, 11"""
assert hasattr(logfile.data, "vibfreqs")
assert len(logfile.data.vibfreqs) == 11
assert logfile.data.metadata["package_version"] == "2009+D.01"
def testGaussian_Gaussian09_issue_460_log(logfile):
"""Lots of malformed lines when parsing for scfvalues:
RMSDP=3.79D-04 MaxDP=4.02D-02 OVMax= 4.31D-02
RMSDP=1.43D-06 MaxDP=5.44D-04 DE=-6.21D-07 OVMax= 5.76D-04
RMSDP=2.06D-05 MaxDP=3.84D-03 DE= 4.82D-04 O E= -2574.14897924075 Delta-E= 0.000439804468 Rises=F Damp=F
RMSDP=8.64D-09 MaxDP=2.65D-06 DE=-1.67D-10 OVMax= 3. E= -2574.14837678675 Delta-E= -0.000000179038 Rises=F Damp=F
RMSDP= E= -2574.14931865182 Delta-E= -0.000000019540 Rises=F Damp=F
RMSDP=9.34D- E= -2574.14837612206 Delta-E= -0.000000620705 Rises=F Damp=F
RMSDP=7.18D-05 Max E= -2574.14797761904 Delta-E= -0.000000000397 Rises=F Damp=F
RMSDP=1.85D-06 MaxD E= -2574.14770506975 Delta-E= -0.042173156160 Rises=F Damp=F
RMSDP=1.69D-06 MaxDP= E= -2574.14801776548 Delta-E= 0.000023521317 Rises=F Damp=F
RMSDP=3.80D-08 MaxDP=1 E= -2574.14856570920 Delta-E= -0.000002960194 Rises=F Damp=F
RMSDP=4.47D-09 MaxDP=1.40 E= -2574.14915435699 Delta-E= -0.000255709558 Rises=F Damp=F
RMSDP=5.54D-08 MaxDP=1.55D-05 DE=-2.55D-0 E= -2574.14854319757 Delta-E= -0.000929740010 Rises=F Damp=F
RMSDP=7.20D-09 MaxDP=1.75D-06 DE=- (Enter /QFsoft/applic/GAUSSIAN/g09d.01_pgi11.9-ISTANBUL/g09/l703.exe)
RMSDP=5.24D-09 MaxDP=1.47D-06 DE=-1.82D-11 OVMax= 2.15 (Enter /QFsoft/applic/GAUSSIAN/g09d.01_pgi11.9-ISTANBUL/g09/l703.exe)
RMSDP=1.71D-04 MaxDP=1.54D-02 Iteration 2 A^-1*A deviation from unit magnitude is 1.11D-15 for 266.
"""
assert hasattr(logfile.data, 'scfvalues')
assert logfile.data.scfvalues[0][0, 0] == 3.37e-03
assert numpy.isnan(logfile.data.scfvalues[0][0, 2])
assert logfile.data.metadata["package_version"] == "2009+D.01"
def testGaussian_Gaussian09_OPT_td_g09_out(logfile):
"""Couldn't find etrotats as G09 has different output than G03."""
assert len(logfile.data.etrotats) == 10
assert logfile.data.etrotats[0] == -0.4568
assert logfile.data.metadata["package_version"] == "2009+A.02"
def testGaussian_Gaussian09_OPT_td_out(logfile):
"""Working fine - adding to ensure that CD is parsed correctly."""
assert len(logfile.data.etrotats) == 10
assert logfile.data.etrotats[0] == -0.4568
assert logfile.data.metadata["package_version"] == "2003+B.05"
def testGaussian_Gaussian09_OPT_oniom_log(logfile):
"""AO basis extraction broke with ONIOM"""
assert logfile.data.metadata["package_version"] == "2009+D.01"
def testGaussian_Gaussian09_oniom_IR_intensity_log(logfile):
"""Problem parsing IR intensity from mode 192"""
assert hasattr(logfile.data, 'vibirs')
assert len(logfile.data.vibirs) == 216
assert logfile.data.metadata["package_version"] == "2009+C.01"
def testGaussian_Gaussian09_Ru2bpyen2_H2_freq3_log(logfile):
"""Here atomnos wans't added to the gaussian parser before."""
assert len(logfile.data.atomnos) == 69
assert logfile.data.metadata["package_version"] == "2009+A.02"
def testGaussian_Gaussian09_benzene_HPfreq_log(logfile):
"""Check that higher precision vib displacements obtained with freq=hpmodes) are parsed correctly."""
assert abs(logfile.data.vibdisps[0,0,2] - (-0.04497)) < 0.00001
assert logfile.data.metadata["package_version"] == "2009+C.01"
def testGaussian_Gaussian09_benzene_freq_log(logfile):
"""Check that default precision vib displacements are parsed correctly."""
assert abs(logfile.data.vibdisps[0,0,2] - (-0.04)) < 0.00001
assert logfile.data.metadata["package_version"] == "2009+C.01"
def testGaussian_Gaussian09_relaxed_PES_testH2_log(logfile):
"""Check that all optimizations converge in a single step."""
atomcoords = logfile.data.atomcoords
optstatus = logfile.data.optstatus
assert len(optstatus) == len(atomcoords)
assert all(s == ccData.OPT_DONE + ccData.OPT_NEW for s in optstatus)
assert logfile.data.metadata["package_version"] == "2009+D.01"
def testGaussian_Gaussian09_relaxed_PES_testCO2_log(logfile):
"""A relaxed PES scan with some uncoverged and some converged runs."""
atomcoords = logfile.data.atomcoords
optstatus = logfile.data.optstatus
assert len(optstatus) == len(atomcoords)
new_points = numpy.where(optstatus & ccData.OPT_NEW)[0]
# The first new point is just the beginning of the scan.
assert new_points[0] == 0
# The next two new points are at the end of unconverged runs.
assert optstatus[new_points[1]-1] == ccData.OPT_UNCONVERGED
assert all(optstatus[i] == ccData.OPT_UNKNOWN for i in range(new_points[0]+1, new_points[1]-1))
assert optstatus[new_points[2]-1] == ccData.OPT_UNCONVERGED
assert all(optstatus[i] == ccData.OPT_UNKNOWN for i in range(new_points[1]+1, new_points[2]-1))
# The next new point is after a convergence.
assert optstatus[new_points[3]-1] == ccData.OPT_DONE
assert all(optstatus[i] == ccData.OPT_UNKNOWN for i in range(new_points[2]+1, new_points[3]-1))
# All subsequent point are both new and converged, since they seem
# to have converged in a single step.
assert all(s == ccData.OPT_DONE + ccData.OPT_NEW for s in optstatus[new_points[3]:])
assert logfile.data.metadata["package_version"] == "2009+D.01"
def testGaussian_Gaussian09_stopiter_gaussian_out(logfile):
"""Check to ensure that an incomplete SCF is handled correctly."""
assert len(logfile.data.scfvalues[0]) == 4
assert logfile.data.metadata["package_version"] == "2009+D.01"
def testGaussian_Gaussian09_benzene_excited_states_optimization_issue889_log(logfile):
"""Check that only converged geometry excited states properties are reported."""
assert logfile.data.etdips.shape == (20,3)
assert len(logfile.data.etenergies) == 20
assert logfile.data.etmagdips.shape == (20,3)
assert len(logfile.data.etoscs) == 20
assert len(logfile.data.etrotats) == 20
assert len(logfile.data.etsecs) == 20
assert logfile.data.etveldips.shape == (20,3)
def testGaussian_Gaussian16_naturalspinorbitals_parsing_log(logfile):
"""A UHF calculation with natural spin orbitals."""
assert isinstance(logfile.data.nsocoeffs, list)
assert isinstance(logfile.data.nsocoeffs[0], numpy.ndarray)
assert isinstance(logfile.data.nsocoeffs[1], numpy.ndarray)
assert isinstance(logfile.data.nsooccnos, list)
assert isinstance(logfile.data.nsooccnos[0], list)
assert isinstance(logfile.data.nsooccnos[1], list)
assert isinstance(logfile.data.aonames,list)
assert isinstance(logfile.data.atombasis,list)
assert numpy.shape(logfile.data.nsocoeffs) == (2,logfile.data.nmo,logfile.data.nmo)
assert len(logfile.data.nsooccnos[0]) == logfile.data.nmo
assert len(logfile.data.nsooccnos[1]) == logfile.data.nmo
assert len(logfile.data.aonames) == logfile.data.nbasis
assert len(numpy.ravel(logfile.data.atombasis)) == logfile.data.nbasis
assert logfile.data.nsooccnos[0][14] == 0.00506
assert logfile.data.nsooccnos[1][14] == 0.00318
assert logfile.data.nsocoeffs[0][14,12] == 0.00618
assert logfile.data.nsocoeffs[1][14,9] == 0.79289
assert logfile.data.aonames[41] == 'O2_9D 0'
assert logfile.data.atombasis[1][0] == 23
assert logfile.data.metadata["legacy_package_version"] == "16revisionA.03"
assert logfile.data.metadata["package_version"] == "2016+A.03"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
def testGaussian_Gaussian16_issue851_log(logfile):
"""Surface scan from cclib/cclib#851 where attributes were not lists."""
assert isinstance(logfile.data.scannames, list)
assert isinstance(logfile.data.scanparm, list)
assert isinstance(logfile.data.scanenergies, list)
def testGaussian_Gaussian16_issue962_log(logfile):
"""For issue 962, this shouldn't have scftargets but should parse fully"""
assert not hasattr(logfile.data, "scftargets")
# Jaguar #
# It would be good to have an unconverged geometry optimization so that
# we can test that optdone is set properly.
#def testJaguarX.X_dvb_gopt_unconverged:
# assert hasattr(logfile.data, 'optdone') and not logfile.data.optdone
def testJaguar_Jaguar8_3_stopiter_jaguar_dft_out(logfile):
"""Check to ensure that an incomplete SCF is handled correctly."""
assert len(logfile.data.scfvalues[0]) == 4
assert logfile.data.metadata["legacy_package_version"] == "8.3"
assert logfile.data.metadata["package_version"] == "8.3+13"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
def testJaguar_Jaguar8_3_stopiter_jaguar_hf_out(logfile):
"""Check to ensure that an incomplete SCF is handled correctly."""
assert len(logfile.data.scfvalues[0]) == 3
assert logfile.data.metadata["package_version"] == "8.3+13"
# Molcas #
def testMolcas_Molcas18_test_standard_000_out(logfile):
"""Don't support parsing MOs for multiple symmetry species."""
assert not hasattr(logfile.data, "moenergies")
assert not hasattr(logfile.data, "mocoeffs")
assert logfile.data.metadata["legacy_package_version"] == "18.09"
assert logfile.data.metadata["package_version"] == "18.09+52-ge15dc38.81d3fb3dc6a5c5df6b3791ef1ef3790f"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
def testMolcas_Molcas18_test_standard_001_out(logfile):
"""This logfile has two calculations, and we currently only want to parse the first."""
assert logfile.data.natom == 8
# There are also four symmetry species, and orbital count should cover all of them.
assert logfile.data.nbasis == 30
assert logfile.data.nmo == 30
assert logfile.data.metadata["package_version"] == "18.09+52-ge15dc38.81d3fb3dc6a5c5df6b3791ef1ef3790f"
def testMolcas_Molcas18_test_standard_003_out(logfile):
"""This logfile has extra charged monopoles (not part of the molecule)."""
assert logfile.data.charge == 0
assert logfile.data.metadata["package_version"] == "18.09+52-ge15dc38.81d3fb3dc6a5c5df6b3791ef1ef3790f"
def testMolcas_Molcas18_test_standard_005_out(logfile):
"""Final geometry in optimization has fewer atoms due to symmetry, and so is ignored."""
assert len(logfile.data.atomcoords) == 2
assert logfile.data.metadata["package_version"] == "18.09+52-ge15dc38.81d3fb3dc6a5c5df6b3791ef1ef3790f"
def testMolcas_Molcas18_test_stevenv_001_out(logfile):
"""Don't support parsing MOs for RAS (active space)."""
assert not hasattr(logfile.data, "moenergies")
assert not hasattr(logfile.data, "mocoeffs")
assert logfile.data.metadata["package_version"] == "18.09+52-ge15dc38.81d3fb3dc6a5c5df6b3791ef1ef3790f"
def testMolcas_Molcas18_test_stevenv_desym_out(logfile):
"""This logfile has iterations interrupted by a Fermi aufbau procedure."""
assert len(logfile.data.scfvalues) == 1
assert len(logfile.data.scfvalues[0]) == 26
assert logfile.data.metadata["package_version"] == "18.09+52-ge15dc38.81d3fb3dc6a5c5df6b3791ef1ef3790f"
# Molpro #
def testMolpro_Molpro2008_ch2o_molpro_casscf_out(logfile):
"""A CASSCF job with symmetry and natural orbitals."""
# The last two atoms are equivalent, so the last ends up having no
# functions asigned. This is not obvious, because the functions are
# distributed between the last two atoms in the block where gbasis
# is parsed, but it seems all are assigned to the penultimate atom later.
assert logfile.data.atombasis[-1] == []
assert len(logfile.data.aonames) == logfile.data.nbasis
# The MO coefficients are printed in several block, each corresponding
# to one irrep, so make sure we have reconstructed the coefficients correctly.
assert len(logfile.data.moenergies) == 1
assert logfile.data.moenergies[0].shape == (logfile.data.nmo, )
assert len(logfile.data.mocoeffs) == 1
assert logfile.data.mocoeffs[0].shape == (logfile.data.nmo, logfile.data.nbasis)
# These coefficients should be zero due to symmetry.
assert logfile.data.mocoeffs[0][-2][0] == 0.0
assert logfile.data.mocoeffs[0][0][-2] == 0.0
assert isinstance(logfile.data.nocoeffs, numpy.ndarray)
assert isinstance(logfile.data.nooccnos, numpy.ndarray)
assert logfile.data.nocoeffs.shape == logfile.data.mocoeffs[0].shape
assert len(logfile.data.nooccnos) == logfile.data.nmo
assert logfile.data.nooccnos[27] == 1.95640
assert logfile.data.metadata["legacy_package_version"] == "2012.1"
assert logfile.data.metadata["package_version"] == "2012.1"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
def testMolpro_Molpro2012_CHONHSH_HF_STO_3G_out(logfile):
"""Formatting of the basis function is slightly different than expected."""
assert len(logfile.data.gbasis) == 7
assert len(logfile.data.gbasis[0]) == 3 # C
assert len(logfile.data.gbasis[1]) == 3 # N
assert len(logfile.data.gbasis[2]) == 3 # O
assert len(logfile.data.gbasis[3]) == 5 # S
assert len(logfile.data.gbasis[4]) == 1 # H
assert len(logfile.data.gbasis[5]) == 1 # H
assert len(logfile.data.gbasis[6]) == 1 # H
assert logfile.data.metadata["legacy_package_version"] == "2012.1"
assert logfile.data.metadata["package_version"] == "2012.1.23+f8cfea266908527a8826bdcd5983aaf62e47d3bf"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
def testMolpro_Molpro2012_dvb_gopt_unconverged_out(logfile):
"""An unconverged geometry optimization to test for empty optdone (see #103 for details)."""
assert hasattr(logfile.data, 'optdone') and not logfile.data.optdone
assert logfile.data.metadata["legacy_package_version"] == "2012.1"
assert logfile.data.metadata["package_version"] == "2012.1.12+e112a8ab93d81616c1987a1f1ef3707d874b6803"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
def testMolpro_Molpro2012_stopiter_molpro_dft_out(logfile):
"""Check to ensure that an incomplete SCF is handled correctly."""
assert len(logfile.data.scfvalues[0]) == 6
assert logfile.data.metadata["legacy_package_version"] == "2012.1"
assert logfile.data.metadata["package_version"] == "2012.1+c18f7d37f9f045f75d4f3096db241dde02ddca0a"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
def testMolpro_Molpro2012_stopiter_molpro_hf_out(logfile):
"""Check to ensure that an incomplete SCF is handled correctly."""
assert len(logfile.data.scfvalues[0]) == 6
assert logfile.data.metadata["package_version"] == "2012.1+c18f7d37f9f045f75d4f3096db241dde02ddca0a"
# MOPAC #
def testMOPAC_MOPAC2016_9S3_uuu_Cs_cation_freq_PM7_out(logfile):
"""There was a syntax error in the frequency parsing."""
assert hasattr(logfile.data, 'vibfreqs')
assert logfile.data.metadata["legacy_package_version"] == "2016"
assert logfile.data.metadata["package_version"] == "16.175"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
# NWChem #
def testNWChem_NWChem6_0_dvb_gopt_hf_unconverged_out(logfile):
"""An unconverged geometry optimization to test for empty optdone (see #103 for details)."""
assert hasattr(logfile.data, 'optdone') and not logfile.data.optdone
assert logfile.data.metadata["legacy_package_version"] == "6.0"
assert logfile.data.metadata["package_version"] == "6.0"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
def testNWChem_NWChem6_0_dvb_sp_hf_moments_only_quadrupole_out(logfile):
"""Quadrupole moments are printed/parsed, but not lower moments (no shape)."""
assert hasattr(logfile.data, 'moments') and len(logfile.data.moments) == 3
assert len(logfile.data.moments[0]) == 3
assert not logfile.data.moments[1].shape
assert len(logfile.data.moments[2]) == 6
assert logfile.data.metadata["package_version"] == "6.0"
def testNWChem_NWChem6_0_dvb_sp_hf_moments_only_octupole_out(logfile):
"""Quadrupole moments are printed/parsed, but not lower moments (no shape)."""
assert hasattr(logfile.data, 'moments') and len(logfile.data.moments) == 4
assert len(logfile.data.moments[0]) == 3
assert not logfile.data.moments[1].shape
assert not logfile.data.moments[2].shape
assert len(logfile.data.moments[3]) == 10
assert logfile.data.metadata["package_version"] == "6.0"
def testNWChem_NWChem6_0_hydrogen_atom_ROHF_cc_pVDZ_out(logfile):
"""A lone hydrogen atom is a common edge case; it has no beta
electrons.
"""
assert logfile.data.charge == 0
assert logfile.data.natom == 1
assert logfile.data.nbasis == 5
assert logfile.data.nmo == 5
assert len(logfile.data.moenergies) == 1
assert logfile.data.moenergies[0].shape == (5,)
assert logfile.data.homos.shape == (2,)
assert logfile.data.homos[0] == 0
assert logfile.data.homos[1] == -1
assert logfile.data.metadata["package_version"] == "6.0"
def testNWChem_NWChem6_0_hydrogen_atom_UHF_cc_pVDZ_out(logfile):
"""A lone hydrogen atom is a common edge case; it has no beta
electrons.
Additionally, this calculations has no title, which caused some
issues with skip_lines().
"""
assert logfile.data.charge == 0
assert logfile.data.natom == 1
assert logfile.data.nbasis == 5
assert logfile.data.nmo == 5
assert len(logfile.data.moenergies) == 2
assert logfile.data.moenergies[0].shape == (5,)
assert logfile.data.moenergies[1].shape == (5,)
assert logfile.data.homos.shape == (2,)
assert logfile.data.homos[0] == 0
assert logfile.data.homos[1] == -1
assert logfile.data.metadata["package_version"] == "6.0"
def testNWChem_NWChem6_5_stopiter_nwchem_dft_out(logfile):
"""Check to ensure that an incomplete SCF is handled correctly."""
assert len(logfile.data.scfvalues[0]) == 3
assert logfile.data.metadata["legacy_package_version"] == "6.5"
assert logfile.data.metadata["package_version"] == "6.5+26243"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
def testNWChem_NWChem6_5_stopiter_nwchem_hf_out(logfile):
"""Check to ensure that an incomplete SCF is handled correctly."""
assert len(logfile.data.scfvalues[0]) == 2
assert logfile.data.metadata["package_version"] == "6.5+26243"
def testNWChem_NWChem6_8_526_out(logfile):
"""If `print low` is present in the input, SCF iterations are not
printed.
"""
assert not hasattr(logfile.data, "scftargets")
assert not hasattr(logfile.data, "scfvalues")
assert logfile.data.metadata["legacy_package_version"] == "6.8.1"
assert logfile.data.metadata["package_version"] == "6.8.1+g08bf49b"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
# ORCA #
def testORCA_ORCA2_8_co_cosmo_out(logfile):
"""This is related to bug 3184890.
The scfenergies were not being parsed correctly for this geometry
optimization run, for two reasons.
First, the printing of SCF total energies is different inside
geometry optimization steps than for single point calculations,
which also affects unit tests.
However, this logfile uses a setting that causes an SCF run to
terminate prematurely when a set maximum number of cycles is reached.
In this case, the last energy reported should probably be used,
and the number of values in scfenergies preserved.
"""
assert hasattr(logfile.data, "scfenergies") and len(logfile.data.scfenergies) == 4
assert logfile.data.metadata["legacy_package_version"] == "2.8"
assert logfile.data.metadata["package_version"] == "2.8+2287"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
def testORCA_ORCA2_9_job_out(logfile):
"""First output file and request to parse atomic spin densities.
Make sure that the sum of such densities is one in this case (or reasonaby close),
but remember that this attribute is a dictionary, so we must iterate.
"""
assert all([abs(sum(v)-1.0) < 0.0001 for k, v in logfile.data.atomspins.items()])
assert logfile.data.metadata["legacy_package_version"] == "2.9.0"
assert logfile.data.metadata["package_version"] == "2.9.0"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
def testORCA_ORCA2_9_qmspeedtest_hf_out(logfile):
"""Check precision of SCF energies (cclib/cclib#210)."""
energy = logfile.data.scfenergies[-1]
expected = -17542.5188694
assert abs(energy - expected) < 10**-6
assert logfile.data.metadata["legacy_package_version"] == "2.9.1"
assert logfile.data.metadata["package_version"] == "2.9.1"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
def testORCA_ORCA3_0_chelpg_out(logfile):
"""ORCA file with chelpg charges"""
assert 'chelpg' in logfile.data.atomcharges
charges = logfile.data.atomcharges['chelpg']
assert len(charges) == 9
assert charges[0] == 0.363939
assert charges[1] == 0.025695
def testORCA_ORCA3_0_dvb_gopt_unconverged_out(logfile):
"""An unconverged geometry optimization to test for empty optdone (see #103 for details)."""
assert hasattr(logfile.data, 'optdone') and not logfile.data.optdone
assert logfile.data.metadata["legacy_package_version"] == "3.0.1"
assert logfile.data.metadata["package_version"] == "3.0.1"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
def testORCA_ORCA3_0_polar_rhf_cg_out(logfile):
"""Alternative CP-SCF solver for the polarizability wasn't being detected."""
assert hasattr(logfile.data, 'polarizabilities')
assert logfile.data.metadata["legacy_package_version"] == "3.0.3"
assert logfile.data.metadata["package_version"] == "3.0.3"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
def testORCA_ORCA3_0_polar_rhf_diis_out(logfile):
"""Alternative CP-SCF solver for the polarizability wasn't being detected."""
assert hasattr(logfile.data, 'polarizabilities')
assert logfile.data.metadata["package_version"] == "3.0.3"
def testORCA_ORCA3_0_stopiter_orca_scf_compact_out(logfile):
"""Check to ensure that an incomplete SCF is handled correctly."""
assert len(logfile.data.scfvalues[0]) == 1
assert logfile.data.metadata["package_version"] == "3.0.1"
def testORCA_ORCA3_0_stopiter_orca_scf_large_out(logfile):
"""Check to ensure that an incomplete SCF is handled correctly."""
assert len(logfile.data.scfvalues[0]) == 9
assert logfile.data.metadata["package_version"] == "2.9.1"
def testORCA_ORCA4_0_1_ttt_td_out(logfile):
"""RPA is slightly different from TDA, see #373."""
assert hasattr(logfile.data, 'etsyms')
assert len(logfile.data.etsecs) == 24
assert len(logfile.data.etsecs[0]) == 1
assert numpy.isnan(logfile.data.etsecs[0][0][2])
assert len(logfile.data.etrotats) == 24
assert logfile.data.etrotats[13] == -0.03974
assert logfile.data.metadata["legacy_package_version"] == "4.0.0"
assert logfile.data.metadata["package_version"] == "4.0.0"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
def testORCA_ORCA4_0_hydrogen_fluoride_numfreq_out(logfile):
"""Frequencies from linear molecules weren't parsed correctly (#426)."""
numpy.testing.assert_equal(logfile.data.vibfreqs, [4473.96])
def testORCA_ORCA4_0_hydrogen_fluoride_usesym_anfreq_out(logfile):
"""Frequencies from linear molecules weren't parsed correctly (#426)."""
numpy.testing.assert_equal(logfile.data.vibfreqs, [4473.89])
def testORCA_ORCA4_0_invalid_literal_for_float_out(logfile):
"""MO coefficients are glued together, see #629."""
assert hasattr(logfile.data, 'mocoeffs')
assert logfile.data.mocoeffs[0].shape == (logfile.data.nmo, logfile.data.nbasis)
# Test the coefficients from this line where things are glued together:
# 15C 6s -154.480939-111.069870-171.460819-79.052025241.536860-92.159399
assert logfile.data.mocoeffs[0][102][378] == -154.480939
assert logfile.data.mocoeffs[0][103][378] == -111.069870
assert logfile.data.mocoeffs[0][104][378] == -171.460819
assert logfile.data.mocoeffs[0][105][378] == -79.052025
assert logfile.data.mocoeffs[0][106][378] == 241.536860
assert logfile.data.mocoeffs[0][107][378] == -92.159399
assert logfile.data.metadata["legacy_package_version"] == "4.0.1.2"
assert logfile.data.metadata["package_version"] == "4.0.1.2"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
def testORCA_ORCA4_0_IrCl6_sp_out(logfile):
"""Tests ECP and weird SCF printing."""
assert hasattr(logfile.data, 'scfvalues')
assert len(logfile.data.scfvalues) == 1
vals_first = [0.000000000000, 28.31276975, 0.71923638]
vals_last = [0.000037800796, 0.00412549, 0.00014041]
numpy.testing.assert_almost_equal(logfile.data.scfvalues[0][0], vals_first)
numpy.testing.assert_almost_equal(logfile.data.scfvalues[0][-1], vals_last)
def testORCA_ORCA4_0_comment_or_blank_line_out(logfile):
"""Coordinates with blank lines or comments weren't parsed correctly (#747)."""
assert hasattr(logfile.data,"atomcoords")
assert logfile.data.atomcoords.shape == (1, 8, 3)
assert logfile.data.metadata["legacy_package_version"] == "4.0.1.2"
assert logfile.data.metadata["package_version"] == "4.0.1.2"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
def testORCA_ORCA4_1_725_out(logfile):
"""This file uses embedding potentials, which requires `>` after atom names in
the input file and that confuses different parts of the parser.
In #725 we decided to not include these potentials in the parsed results.
"""
assert logfile.data.natom == 7
numpy.testing.assert_equal(logfile.data.atomnos, numpy.array([20, 17, 17, 17, 17, 17, 17], dtype=int))
assert len(logfile.data.atomcharges["mulliken"]) == 7
assert len(logfile.data.atomcharges["lowdin"]) == 7
assert logfile.data.metadata["legacy_package_version"] == "4.1.x"
assert logfile.data.metadata["package_version"] == "4.1dev+13440"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
def testORCA_ORCA4_1_orca_from_issue_736_out(logfile):
"""ORCA file with no whitespace between SCF iteration columns."""
assert len(logfile.data.scfvalues) == 23
# The first iteration in the problematic block:
# ITER Energy Delta-E Max-DP RMS-DP [F,P] Damp
# *** Starting incremental Fock matrix formation ***
# 0 -257.0554667435 0.000000000000537.42184135 4.76025534 0.4401076 0.8500
assert abs(logfile.data.scfvalues[14][0][1] - 537) < 1.0, logfile.data.scfvalues[14][0]
def testORCA_ORCA4_1_porphine_out(logfile):
"""ORCA optimization with multiple TD-DFT gradients and absorption spectra."""
assert len(logfile.data.etenergies) == 1
def testORCA_ORCA4_1_single_atom_freq_out(logfile):
"""ORCA frequency with single atom."""
assert len(logfile.data.vibdisps) == 0
assert len(logfile.data.vibfreqs) == 0
assert len(logfile.data.vibirs) == 0
# These values are different from what ORCA prints as the total enthalpy,
# because for single atoms that includes a spurious correction. We build the
# enthalpy ourselves from electronic and translational energies (see #817 for details).
numpy.testing.assert_almost_equal(logfile.data.enthalpy, -460.14376, 5)
numpy.testing.assert_almost_equal(logfile.data.entropy, 6.056e-5, 8)
numpy.testing.assert_almost_equal(logfile.data.freeenergy, -460.16182, 6)
def testORCA_ORCA4_2_947_out(logfile):
"""A constrained geometry optimization which prints the extra line
WARNING: THERE ARE 5 CONSTRAINED CARTESIAN COORDINATES
just before the gradient.
"""
assert len(logfile.data.atomcoords) == 7
assert len(logfile.data.grads) == 6
def testORCA_ORCA4_2_MP2_gradient_out(logfile):
"""ORCA numerical frequency calculation with gradients."""
assert logfile.data.metadata["package_version"] == "4.2.0"
assert hasattr(logfile.data, 'grads')
assert logfile.data.grads.shape == (1, 3, 3)
# atom 2, y-coordinate.
idx = (0, 1, 1)
assert logfile.data.grads[idx] == -0.00040549
def testORCA_ORCA4_2_long_input_out(logfile):
"""Long ORCA input file (#804)."""
assert logfile.data.metadata["package_version"] == "4.2.0"
assert hasattr(logfile.data, 'atomcoords')
assert logfile.data.atomcoords.shape == (100, 12, 3)
def testORCA_ORCA4_2_water_dlpno_ccsd_out(logfile):
"""DLPNO-CCSD files have extra lines between E(0) and E(TOT) than normal CCSD
outputs:
----------------------
COUPLED CLUSTER ENERGY
----------------------
E(0) ... -74.963574242
E(CORR)(strong-pairs) ... -0.049905771
E(CORR)(weak-pairs) ... 0.000000000
E(CORR)(corrected) ... -0.049905771
E(TOT) ... -75.013480013
Singles Norm <S|S>**1/2 ... 0.013957180
T1 diagnostic ... 0.004934608
"""
assert hasattr(logfile.data, 'ccenergies')
def testORCA_ORCA4_2_longer_input_out(logfile):
"""Longer ORCA input file (#1034)."""
assert logfile.data.metadata['input_file_contents'][-47:-4] == 'H 1.066878310 1.542378768 -0.602599044'
def testORCA_ORCA4_2_casscf_out(logfile):
"""ORCA casscf input file (#1044)."""
assert numpy.isclose(logfile.data.etenergies[0], 28271.0)
# PSI 3 #
def testPsi3_Psi3_4_water_psi3_log(logfile):
"""An RHF for water with D orbitals and C2v symmetry.
Here we can check that the D orbitals are considered by checking atombasis and nbasis.
"""
assert logfile.data.nbasis == 25
assert [len(ab) for ab in logfile.data.atombasis] == [15, 5, 5]
assert logfile.data.metadata["legacy_package_version"] == "3.4"
assert logfile.data.metadata["package_version"] == "3.4alpha"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
# PSI 4 #
def testPsi4_Psi4_beta5_dvb_gopt_hf_unconverged_out(logfile):
"""An unconverged geometry optimization to test for empty optdone (see #103 for details)."""
assert logfile.data.metadata["legacy_package_version"] == "beta5"
assert logfile.data.metadata["package_version"] == "0!0.beta5"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
assert hasattr(logfile.data, 'optdone') and not logfile.data.optdone
def testPsi4_Psi4_beta5_sample_cc54_0_01_0_1_0_1_out(logfile):
"""TODO"""
assert logfile.data.metadata["legacy_package_version"] == "beta2+"
assert logfile.data.metadata["package_version"] == "0!0.beta2.dev+fa5960b375b8ca2a5e4000a48cb95e7f218c579a"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
def testPsi4_Psi4_beta5_stopiter_psi_dft_out(logfile):
"""Check to ensure that an incomplete SCF is handled correctly."""
assert logfile.data.metadata["package_version"] == "0!0.beta5"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
assert len(logfile.data.scfvalues[0]) == 7
def testPsi4_Psi4_beta5_stopiter_psi_hf_out(logfile):
"""Check to ensure that an incomplete SCF is handled correctly."""
assert logfile.data.metadata["package_version"] == "0!0.beta5"
assert len(logfile.data.scfvalues[0]) == 6
def testPsi4_Psi4_0_5_sample_scf5_out(logfile):
assert logfile.data.metadata["legacy_package_version"] == "0.5"
assert logfile.data.metadata["package_version"] == "1!0.5.dev+master-dbe9080"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
def testPsi4_Psi4_0_5_water_fdgrad_out(logfile):
"""Ensure that finite difference gradients are parsed."""
assert logfile.data.metadata["legacy_package_version"] == "1.2a1.dev429"
assert logfile.data.metadata["package_version"] == "1!1.2a1.dev429+fixsym-7838fc1-dirty"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
assert hasattr(logfile.data, 'grads')
assert logfile.data.grads.shape == (1, 3, 3)
assert abs(logfile.data.grads[0, 0, 2] - 0.05498126903657) < 1.0e-12
# In C2v symmetry, there are 5 unique displacements for the
# nuclear gradient, and this is at the MP2 level.
assert logfile.data.mpenergies.shape == (5, 1)
def testPsi4_Psi4_1_2_ch4_hf_opt_freq_out(logfile):
"""Ensure that molecular orbitals and normal modes are parsed in Psi4 1.2"""
assert logfile.data.metadata["legacy_package_version"] == "1.2.1"
assert logfile.data.metadata["package_version"] == "1!1.2.1.dev+HEAD-406f4de"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
assert hasattr(logfile.data, 'mocoeffs')
assert hasattr(logfile.data, 'vibdisps')
assert hasattr(logfile.data, 'vibfreqs')
# Q-Chem #
def testQChem_QChem4_2_CH3___Na__RS_out(logfile):
"""An unrestricted fragment job with BSSE correction.
Contains only the Roothaan step energies for the CP correction.
The fragment SCF sections are printed.
This is to ensure only the supersystem is parsed.
"""
assert logfile.data.metadata["legacy_package_version"] == "4.2.2"
assert logfile.data.metadata["package_version"] == "4.2.2"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
assert logfile.data.charge == 1
assert logfile.data.mult == 2
assert len(logfile.data.moenergies) == 2
assert len(logfile.data.atomcoords[0]) == 5
assert len(logfile.data.atomnos) == 5
# Fragments: A, B, RS_CP(A), RS_CP(B), Full
assert len(logfile.data.scfenergies) == 1
scfenergy = convertor(-201.9388745658, "hartree", "eV")
assert abs(logfile.data.scfenergies[0] - scfenergy) < 1.0e-10
assert logfile.data.nbasis == logfile.data.nmo == 40
assert len(logfile.data.moenergies[0]) == 40
assert len(logfile.data.moenergies[1]) == 40
assert type(logfile.data.moenergies) == type([])
assert type(logfile.data.moenergies[0]) == type(numpy.array([]))
assert type(logfile.data.moenergies[1]) == type(numpy.array([]))
def testQChem_QChem4_2_CH3___Na__RS_SCF_out(logfile):
"""An unrestricted fragment job with BSSE correction.
Contains both the Roothaan step and full SCF energies for the CP correction.
The fragment SCF sections are printed.
This is to ensure only the supersystem is printed.
"""
assert logfile.data.metadata["legacy_package_version"] == "4.1.0.1"
assert logfile.data.metadata["package_version"] == "4.1.0.1"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
assert logfile.data.charge == 1
assert logfile.data.mult == 2
assert len(logfile.data.moenergies) == 2
assert len(logfile.data.atomcoords[0]) == 5
assert len(logfile.data.atomnos) == 5
# Fragments: A, B, RS_CP(A), RS_CP(B), SCF_CP(A), SCF_CP(B), Full
assert len(logfile.data.scfenergies) == 1
scfenergy = convertor(-201.9396979324, "hartree", "eV")
assert abs(logfile.data.scfenergies[0] - scfenergy) < 1.0e-10
assert logfile.data.nbasis == logfile.data.nmo == 40
assert len(logfile.data.moenergies[0]) == 40
assert len(logfile.data.moenergies[1]) == 40
assert type(logfile.data.moenergies) == type([])
assert type(logfile.data.moenergies[0]) == type(numpy.array([]))
assert type(logfile.data.moenergies[1]) == type(numpy.array([]))
def testQChem_QChem4_2_CH4___Na__out(logfile):
"""A restricted fragment job with no BSSE correction.
The fragment SCF sections are printed.
This is to ensure only the supersystem is parsed.
"""
assert logfile.data.metadata["legacy_package_version"] == "4.2.0"
assert logfile.data.metadata["package_version"] == "4.2.0"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
assert logfile.data.charge == 1
assert logfile.data.mult == 1
assert len(logfile.data.moenergies) == 1
assert len(logfile.data.atomcoords[0]) == 6
assert len(logfile.data.atomnos) == 6
# Fragments: A, B, Full
assert len(logfile.data.scfenergies) == 1
scfenergy = convertor(-202.6119443654, "hartree", "eV")
assert abs(logfile.data.scfenergies[0] - scfenergy) < 1.0e-10
assert logfile.data.nbasis == logfile.data.nmo == 42
assert len(logfile.data.moenergies[0]) == 42
assert type(logfile.data.moenergies) == type([])
assert type(logfile.data.moenergies[0]) == type(numpy.array([]))
def testQChem_QChem4_2_CH3___Na__RS_SCF_noprint_out(logfile):
"""An unrestricted fragment job with BSSE correction.
Contains both the Roothaan step and full SCF energies for the CP correction.
The fragment SCF sections are not printed.
This is to ensure only the supersystem is parsed.
"""
assert logfile.data.metadata["legacy_package_version"] == "4.3.0"
assert logfile.data.metadata["package_version"] == "4.3.0"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
assert logfile.data.charge == 1
assert logfile.data.mult == 2
assert len(logfile.data.moenergies) == 2
assert len(logfile.data.atomcoords[0]) == 5
assert len(logfile.data.atomnos) == 5
assert len(logfile.data.scfenergies) == 1
scfenergy = convertor(-201.9396979324, "hartree", "eV")
assert abs(logfile.data.scfenergies[0] - scfenergy) < 1.0e-10
assert logfile.data.nbasis == logfile.data.nmo == 40
assert len(logfile.data.moenergies[0]) == 40
assert len(logfile.data.moenergies[1]) == 40
assert type(logfile.data.moenergies) == type([])
assert type(logfile.data.moenergies[0]) == type(numpy.array([]))
assert type(logfile.data.moenergies[1]) == type(numpy.array([]))
def testQChem_QChem4_2_CH3___Na__RS_noprint_out(logfile):
"""An unrestricted fragment job with BSSE correction.
Contains only the Roothaan step energies for the CP correction.
The fragment SCF sections are not printed.
This is to ensure only the supersystem is parsed.
"""
assert logfile.data.metadata["package_version"] == "4.3.0"
assert logfile.data.charge == 1
assert logfile.data.mult == 2
assert len(logfile.data.moenergies) == 2
assert len(logfile.data.atomcoords[0]) == 5
assert len(logfile.data.atomnos) == 5
assert len(logfile.data.scfenergies) == 1
scfenergy = convertor(-201.9388582085, "hartree", "eV")
assert abs(logfile.data.scfenergies[0] - scfenergy) < 1.0e-10
assert logfile.data.nbasis == logfile.data.nmo == 40
assert len(logfile.data.moenergies[0]) == 40
assert len(logfile.data.moenergies[1]) == 40
assert type(logfile.data.moenergies) == type([])
assert type(logfile.data.moenergies[0]) == type(numpy.array([]))
assert type(logfile.data.moenergies[1]) == type(numpy.array([]))
def testQChem_QChem4_2_CH4___Na__noprint_out(logfile):
"""A restricted fragment job with no BSSE correction.
The fragment SCF sections are not printed.
This is to ensure only the supersystem is parsed.
"""
assert logfile.data.metadata["package_version"] == "4.3.0"
assert logfile.data.charge == 1
assert logfile.data.mult == 1
assert len(logfile.data.moenergies) == 1
assert len(logfile.data.atomcoords[0]) == 6
assert len(logfile.data.atomnos) == 6
assert len(logfile.data.scfenergies) == 1
scfenergy = convertor(-202.6119443654, "hartree", "eV")
assert abs(logfile.data.scfenergies[0] - scfenergy) < 1.0e-10
assert logfile.data.nbasis == logfile.data.nmo == 42
assert len(logfile.data.moenergies[0]) == 42
assert type(logfile.data.moenergies) == type([])
assert type(logfile.data.moenergies[0]) == type(numpy.array([]))
def testQChem_QChem4_2_CO2_out(logfile):
"""A job containing a specific number of orbitals requested for
printing.
"""
assert logfile.data.metadata["package_version"] == "4.2.2"
nbasis = 45
nmo = 45
nalpha = 11
assert logfile.data.nbasis == nbasis
assert logfile.data.nmo == nmo
assert len(logfile.data.mocoeffs) == 1
assert logfile.data.mocoeffs[0].shape == (nmo, nbasis)
assert logfile.data.mocoeffs[0][0, 0] == -0.0001434
assert logfile.data.mocoeffs[0][nalpha + 5 - 1, nbasis - 1] == -0.0000661
assert len(logfile.data.moenergies) == 1
assert len(logfile.data.moenergies[0]) == nmo
def testQChem_QChem4_2_CO2_cation_UHF_out(logfile):
"""A job containing a specific number of orbitals requested for
printing."""
assert logfile.data.metadata["package_version"] == "4.2.2"
nbasis = 45
nmo = 45
nalpha = 11
nbeta = 10
assert logfile.data.nbasis == nbasis
assert logfile.data.nmo == nmo
assert len(logfile.data.mocoeffs) == 2
assert logfile.data.mocoeffs[0].shape == (nmo, nbasis)
assert logfile.data.mocoeffs[1].shape == (nmo, nbasis)
assert logfile.data.mocoeffs[0][0, 0] == -0.0001549
assert logfile.data.mocoeffs[0][nalpha + 5 - 1, nbasis - 1] == -0.0000985
assert logfile.data.mocoeffs[1][0, 0] == -0.0001612
assert logfile.data.mocoeffs[1][nbeta + 5 - 1, nbasis - 1] == -0.0027710
assert len(logfile.data.moenergies) == 2
assert len(logfile.data.moenergies[0]) == nmo
assert len(logfile.data.moenergies[1]) == nmo
def testQChem_QChem4_2_CO2_cation_ROHF_bigprint_allvirt_out(logfile):
"""A job containing a specific number of orbitals requested for
printing."""
assert logfile.data.metadata["package_version"] == "4.2.2"
nbasis = 45
nmo = 45
nalpha = 11
nbeta = 10
assert logfile.data.nbasis == nbasis
assert logfile.data.nmo == nmo
assert len(logfile.data.mocoeffs) == 2
assert logfile.data.mocoeffs[0].shape == (nmo, nbasis)
assert logfile.data.mocoeffs[1].shape == (nmo, nbasis)
assert logfile.data.mocoeffs[0][0, 0] == -0.0001543
assert logfile.data.mocoeffs[0][nalpha + 5 - 3, nbasis - 1] == -0.0132848
assert logfile.data.mocoeffs[1][2, 0] == 0.9927881
assert logfile.data.mocoeffs[1][nbeta + 5 - 1, nbasis - 1] == 0.0018019
assert len(logfile.data.moenergies) == 2
assert len(logfile.data.moenergies[0]) == nmo
assert len(logfile.data.moenergies[1]) == nmo
def testQChem_QChem4_2_CO2_linear_dependence_printall_out(logfile):
"""A job with linear dependency and all MOs printed."""
assert logfile.data.metadata["package_version"] == "4.2.2"
nbasis = 138
nmo = 106
assert logfile.data.nbasis == nbasis
assert logfile.data.nmo == nmo
assert len(logfile.data.mocoeffs) == 1
assert logfile.data.mocoeffs[0].shape == (nmo, nbasis)
assert logfile.data.mocoeffs[0].T[59, 15] == -0.28758
assert logfile.data.mocoeffs[0].T[59, 16] == -0.00000
def testQChem_QChem4_2_CO2_linear_dependence_printall_final_out(logfile):
"""A job with linear dependency and all MOs printed.
The increased precision is due to the presence of `scf_final_print
= 3` giving a separate block with more decimal places.
"""
assert logfile.data.metadata["package_version"] == "4.2.2"
nbasis = 138
nmo = 106
assert logfile.data.nbasis == nbasis
assert logfile.data.nmo == nmo
assert len(logfile.data.mocoeffs) == 1
assert logfile.data.mocoeffs[0].shape == (nmo, nbasis)
assert logfile.data.mocoeffs[0].T[59, 15] == -0.2875844
# Even though all MO coefficients are printed in the less precise
# block, they aren't parsed.
# assert logfile.data.mocoeffs[0].T[59, 16] == -0.00000
assert numpy.isnan(logfile.data.mocoeffs[0].T[59, 16])
def testQChem_QChem4_2_CO2_linear_dependence_printdefault_out(logfile):
"""A job with linear dependency and the default number of MOs printed
(all occupieds and 5 virtuals).
"""
assert logfile.data.metadata["package_version"] == "4.2.2"
nbasis = 138
nmo = 106
assert logfile.data.nbasis == nbasis
assert logfile.data.nmo == nmo
assert len(logfile.data.mocoeffs) == 1
assert logfile.data.mocoeffs[0].shape == (nmo, nbasis)
assert logfile.data.mocoeffs[0].T[59, 15] == -0.28758
assert numpy.isnan(logfile.data.mocoeffs[0].T[59, 16])
def testQChem_QChem4_2_dvb_gopt_unconverged_out(logfile):
"""An unconverged geometry optimization to test for empty optdone (see #103 for details)."""
assert logfile.data.metadata["package_version"] == "4.2.0"
assert hasattr(logfile.data, 'optdone') and not logfile.data.optdone
def testQChem_QChem4_2_dvb_sp_multipole_10_out(logfile):
"""Multipole moments up to the 10-th order.
Since this example has various formats for the moment ranks, we can test
the parser by making sure the first moment (pure X) is as expected.
"""
assert logfile.data.metadata["package_version"] == "4.2.0"
assert hasattr(logfile.data, 'moments') and len(logfile.data.moments) == 11
tol = 1.0e-6
assert logfile.data.moments[1][0] < tol
assert abs(logfile.data.moments[2][0] - -50.9647) < tol
assert abs(logfile.data.moments[3][0] - 0.0007) < tol
assert abs(logfile.data.moments[4][0] - -1811.1540) < tol
assert abs(logfile.data.moments[5][0] - 0.0159) < tol
assert abs(logfile.data.moments[6][0] - -57575.0744) < tol
assert abs(logfile.data.moments[7][0] - 0.3915) < tol
assert numpy.isnan(logfile.data.moments[8][0])
assert abs(logfile.data.moments[9][0] - 10.1638) < tol
assert numpy.isnan(logfile.data.moments[10][0])
def testQChem_QChem4_2_MoOCl4_sp_noprint_builtin_mixed_all_Cl_out(logfile):
"""ECP on all Cl atoms, but iprint is off, so coreelectrons must be
guessed.
"""
assert logfile.data.metadata["package_version"] == "4.2.0"
assert logfile.data.charge == -2
assert logfile.data.mult == 1
assert hasattr(logfile.data, 'coreelectrons')
coreelectrons = numpy.array([0, 0, 10, 10, 10, 10], dtype=int)
assert numpy.all(coreelectrons == logfile.data.coreelectrons)
def testQChem_QChem4_2_MoOCl4_sp_noprint_builtin_mixed_both_out(logfile):
"""ECP on Mo and all Cl atoms, but iprint is off, so coreelectrons
can't be guessed.
Uses `ecp = gen`.
"""
assert logfile.data.metadata["package_version"] == "4.2.0"
assert logfile.data.charge == -2
assert logfile.data.mult == 1
assert not hasattr(logfile.data, 'coreelectrons')
def testQChem_QChem4_2_MoOCl4_sp_noprint_builtin_mixed_single_Mo_out(logfile):
"""ECP on Mo, but iprint is off, so coreelectrons must be guessed."""
assert logfile.data.metadata["package_version"] == "4.2.0"
assert logfile.data.charge == -2
assert logfile.data.mult == 1
assert hasattr(logfile.data, 'coreelectrons')
coreelectrons = numpy.array([28, 0, 0, 0, 0, 0], dtype=int)
assert numpy.all(coreelectrons == logfile.data.coreelectrons)
def testQChem_QChem4_2_MoOCl4_sp_noprint_builtin_out(logfile):
"""ECP on Mo and all Cl atoms, but iprint is off, so coreelectrons
can't be guessed.
Uses `ecp = <builtin>`.
"""
assert logfile.data.metadata["package_version"] == "4.2.0"
assert logfile.data.charge == -2
assert logfile.data.mult == 1
assert not hasattr(logfile.data, 'coreelectrons')
def testQChem_QChem4_2_MoOCl4_sp_noprint_user_Mo_builtin_all_Cl_out(logfile):
"""ECP on Mo and all Cl atoms, but iprint is off; the coreelectrons
count is given for Mo, and Cl can be guessed.
"""
assert logfile.data.metadata["package_version"] == "4.2.0"
assert logfile.data.charge == -2
assert logfile.data.mult == 1
assert hasattr(logfile.data, 'coreelectrons')
coreelectrons = numpy.array([28, 0, 10, 10, 10, 10], dtype=int)
assert numpy.all(coreelectrons == logfile.data.coreelectrons)
def testQChem_QChem4_2_MoOCl4_sp_print_builtin_mixed_single_Mo_single_Cl_out(logfile):
"""ECP on Mo and all Cl atoms; iprint is on, so coreelectrons can be
calculated.
This was intended to only have an ECP on a single Cl, but Q-Chem
silently puts it on all.
"""
assert logfile.data.metadata["package_version"] == "4.2.0"
assert logfile.data.charge == -2
assert logfile.data.mult == 1
assert hasattr(logfile.data, 'coreelectrons')
coreelectrons = numpy.array([28, 0, 10, 10, 10, 10], dtype=int)
assert numpy.all(coreelectrons == logfile.data.coreelectrons)
def testQChem_QChem4_2_print_frgm_false_opt_out(logfile):
"""Fragment calculation: geometry optimization.
Fragment sections are not printed.
"""
assert logfile.data.metadata["package_version"] == "4.3.0"
assert logfile.data.charge == -1
assert logfile.data.mult == 1
assert len(logfile.data.scfenergies) == 11
assert len(logfile.data.grads) == 11
def testQChem_QChem4_2_print_frgm_true_opt_out(logfile):
"""Fragment calculation: geometry optimization.
Fragment sections are printed.
"""
assert logfile.data.metadata["package_version"] == "4.3.0"
assert logfile.data.charge == -1
assert logfile.data.mult == 1
assert len(logfile.data.scfenergies) == 11
assert len(logfile.data.grads) == 11
def testQChem_QChem4_2_print_frgm_false_sp_out(logfile):
"""Fragment calculation: single point energy.
Fragment sections are not printed.
"""
assert logfile.data.metadata["package_version"] == "4.3.0"
assert logfile.data.charge == -1
assert logfile.data.mult == 1
assert len(logfile.data.scfenergies) == 1
def testQChem_QChem4_2_print_frgm_true_sp_out(logfile):
"""Fragment calculation: single point energy.
Fragment sections are printed.
"""
assert logfile.data.metadata["package_version"] == "4.3.0"
assert logfile.data.charge == -1
assert logfile.data.mult == 1
assert len(logfile.data.scfenergies) == 1
def testQChem_QChem4_2_print_frgm_true_sp_ccsdt_out(logfile):
"""Fragment calculation: single point energy, CCSD(T).
Fragment sections are printed.
"""
assert logfile.data.metadata["package_version"] == "4.3.0"
assert len(logfile.data.mpenergies[0]) == 1
assert len(logfile.data.ccenergies) == 1
def testQChem_QChem4_2_qchem_tddft_rpa_out(logfile):
"""An RPA/TD-DFT job.
Here Q-Chem prints both the TDA and RPA results. These differ somewhat, since
TDA allows only X vectors (occupied-virtual transitions) whereas RPA also
allows Y vectors (virtual-occupied deexcitations), and the formatting in these
two cases is subtly different (see cclib/cclib#154 for details).
Currently cclib will store the second set of transitions (RPA), but this
could change in the future if we support multistep jobs.
"""
assert logfile.data.metadata["package_version"] == "4.2.0"
assert len(logfile.data.etsecs) == 10
assert len(logfile.data.etsecs[0]) == 13
# Check a few vectors manually, since we know the output. X vectors are transitions
# from occupied to virtual orbitals, whereas Y vectors the other way around, so cclib
# should be switching the indices. Here is the corresponding fragment in the logfile:
# Excited state 1: excitation energy (eV) = 3.1318
# Total energy for state 1: -382.185270280389
# Multiplicity: Triplet
# Trans. Mom.: 0.0000 X 0.0000 Y 0.0000 Z
# Strength : 0.0000
# X: D( 12) --> V( 13) amplitude = 0.0162
# X: D( 28) --> V( 5) amplitude = 0.1039
# Y: D( 28) --> V( 5) amplitude = 0.0605
assert logfile.data.etsecs[0][0] == [(11, 0), (47, 0), 0.0162]
assert logfile.data.etsecs[0][1] == [(27, 0), (39, 0), 0.1039]
assert logfile.data.etsecs[0][2] == [(39, 0), (27, 0), 0.0605]
def testQChem_QChem4_2_read_molecule_out(logfile):
"""A two-calculation output with the charge/multiplicity not specified
in the user section."""
assert logfile.data.metadata["package_version"] == "4.3.0"
# These correspond to the second calculation.
assert logfile.data.charge == 1
assert logfile.data.mult == 2
assert len(logfile.data.moenergies) == 2
# However, we currently take data from both, since they aren't
# exactly fragment calculations.
assert len(logfile.data.scfenergies) == 2
def testQChem_QChem4_2_stopiter_qchem_out(logfile):
"""Check to ensure that an incomplete SCF is handled correctly."""
assert logfile.data.metadata["legacy_package_version"] == "4.0.0.1"
assert logfile.data.metadata["package_version"] == "4.0.0.1"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
assert len(logfile.data.scfvalues[0]) == 7
def testQChem_QChem4_3_R_propylene_oxide_force_ccsd_out(logfile):
"""Check to see that the CCSD gradient (not the HF gradient) is being
parsed.
"""
assert logfile.data.metadata["package_version"] == "4.3.0"
assert hasattr(logfile.data, 'grads')
assert logfile.data.grads.shape == (1, logfile.data.natom, 3)
# atom 9, y-coordinate.
idx = (0, 8, 1)
assert logfile.data.grads[idx] == 0.00584973
def testQChem_QChem4_3_R_propylene_oxide_force_hf_numerical_energies_out(logfile):
"""Check to see that the HF numerical gradient (from energies) is
being parsed.
"""
assert logfile.data.metadata["package_version"] == "4.3.0"
# This isn't implemented yet.
assert not hasattr(logfile.data, "grads")
def testQChem_QChem4_3_R_propylene_oxide_force_mp2_out(logfile):
"""Check to see that the MP2 gradient (not the HF gradient) is
being parsed.
"""
assert logfile.data.metadata["package_version"] == "4.3.0"
assert hasattr(logfile.data, 'grads')
assert logfile.data.grads.shape == (1, logfile.data.natom, 3)
# atom 9, y-coordinate.
idx = (0, 8, 1)
assert logfile.data.grads[idx] == 0.00436177
def testQChem_QChem4_3_R_propylene_oxide_force_rimp2_out(logfile):
"""Check to see that the RI-MP2 gradient (not the HF gradient) is
being parsed.
"""
assert logfile.data.metadata["package_version"] == "4.3.0"
assert hasattr(logfile.data, 'grads')
assert logfile.data.grads.shape == (1, logfile.data.natom, 3)
# atom 9, y-coordinate.
idx = (0, 8, 1)
assert logfile.data.grads[idx] == 0.00436172
def testQChem_QChem4_3_R_propylene_oxide_freq_ccsd_out(logfile):
"""Check to see that the CCSD (numerical) Hessian is being parsed.
"""
assert logfile.data.metadata["package_version"] == "4.3.0"
# The gradient of the initial geometry in a Hessian calculated
# from finite difference of gradients should be the same as in a
# force calculation.
assert hasattr(logfile.data, 'grads')
ngrads = 1 + 6*logfile.data.natom
assert logfile.data.grads.shape == (ngrads, logfile.data.natom, 3)
# atom 9, y-coordinate.
idx = (0, 8, 1)
assert logfile.data.grads[idx] == 0.00584973
assert hasattr(logfile.data, 'hessian')
assert logfile.data.hessian.shape == (3*logfile.data.natom, 3*logfile.data.natom)
# atom 4, x-coordinate.
idx = (9, 9)
assert logfile.data.hessian[idx] == 0.3561243
def testQChem_QChem4_3_R_propylene_oxide_freq_hf_numerical_gradients_out(logfile):
"""Check to see that the HF Hessian (from gradients) is being parsed.
"""
assert logfile.data.metadata["package_version"] == "4.3.0"
# This isn't implemented yet.
assert not hasattr(logfile.data, "freq")
def testQChem_QChem4_3_R_propylene_oxide_freq_mp2_out(logfile):
"""Check to see that the MP2 (numerical) Hessian is being parsed.
"""
assert logfile.data.metadata["package_version"] == "4.3.0"
# The gradient of the initial geometry in a Hessian calculated
# from finite difference of gradients should be the same as in a
# force calculation.
assert hasattr(logfile.data, 'grads')
ngrads = 1 + 6*logfile.data.natom
assert logfile.data.grads.shape == (ngrads, logfile.data.natom, 3)
# atom 9, y-coordinate.
idx = (0, 8, 1)
assert logfile.data.grads[idx] == 0.00436177
assert hasattr(logfile.data, 'hessian')
assert logfile.data.hessian.shape == (3*logfile.data.natom, 3*logfile.data.natom)
# atom 4, x-coordinate.
idx = (9, 9)
assert logfile.data.hessian[idx] == 0.3520255
def testQChem_QChem4_3_R_propylene_oxide_freq_rimp2_out(logfile):
"""Check to see that the RI-MP2 (numerical) Hessian is being parsed.
"""
assert logfile.data.metadata["package_version"] == "4.3.0"
# The gradient of the initial geometry in a Hessian calculated
# from finite difference of gradients should be the same as in a
# force calculation.
assert hasattr(logfile.data, 'grads')
ngrads = 1 + 6*logfile.data.natom
assert logfile.data.grads.shape == (ngrads, logfile.data.natom, 3)
# atom 9, y-coordinate.
idx = (0, 8, 1)
# Well, not quite in this case...
assert logfile.data.grads[idx] == 0.00436167
assert hasattr(logfile.data, 'hessian')
assert logfile.data.hessian.shape == (3*logfile.data.natom, 3*logfile.data.natom)
# atom 4, x-coordinate.
idx = (9, 9)
assert logfile.data.hessian[idx] == 0.3520538
def testQChem_QChem4_4_full_2_out(logfile):
"""The polarizability section may not be parsed due to something
appearing just beforehand from a frequency-type calculation.
"""
assert logfile.data.metadata["legacy_package_version"] == "4.4.2"
assert logfile.data.metadata["package_version"] == "4.4.2"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
assert hasattr(logfile.data, 'polarizabilities')
def testQChem_QChem4_4_srtlg_out(logfile):
"""Some lines in the MO coefficients require fixed-width parsing. See
#349 and #381.
"""
assert logfile.data.metadata["legacy_package_version"] == "4.4.0"
assert logfile.data.metadata["package_version"] == "4.4.0"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
# There is a linear dependence problem.
nbasis, nmo = 1129, 1115
assert len(logfile.data.mocoeffs) == 2
assert logfile.data.mocoeffs[0].shape == (nmo, nbasis)
assert logfile.data.mocoeffs[1].shape == (nmo, nbasis)
index_ao = 151 - 1
indices_mo = [index_mo - 1 for index_mo in (493, 494, 495, 496, 497, 498)]
# line 306371:
# 151 C 7 s -54.24935 -36.37903-102.67529 32.37428-150.40380-103.24478
ref = numpy.asarray([-54.24935, -36.37903, -102.67529, 32.37428, -150.40380, -103.24478])
res = logfile.data.mocoeffs[1][indices_mo, index_ao]
numpy.testing.assert_allclose(ref, res, atol=1.0e-5, rtol=0.0)
def testQChem_QChem4_4_Trp_polar_ideriv0_out(logfile):
"""Ensure that the polarizability section is being parsed, but don't
compare to reference results as 2nd-order finite difference can have
large errors.
"""
assert logfile.data.metadata["package_version"] == "4.4.2"
assert hasattr(logfile.data, 'polarizabilities')
def testQChem_QChem4_4_top_out(logfile):
"""This job has fewer MOs (7) than would normally be printed (15)."""
assert logfile.data.metadata["package_version"] == "4.4.2"
nbasis = 7
nmo = 7
assert logfile.data.nbasis == nbasis
assert logfile.data.nmo == nmo
assert len(logfile.data.mocoeffs) == 1
assert logfile.data.mocoeffs[0].shape == (nmo, nbasis)
assert logfile.data.mocoeffs[0].T[6, 5] == 0.8115082
def testQChem_QChem5_0_438_out(logfile):
"""This job has an ECP on Pt, replacing 60 of 78 electrons, and was
showing the charge as 60.
"""
assert logfile.data.metadata["legacy_package_version"] == "5.0.0"
assert logfile.data.metadata["package_version"] == "5.0.0"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
assert logfile.data.charge == 0
assert logfile.data.coreelectrons[0] == 60
def testQChem_QChem5_0_argon_out(logfile):
"""This job has unit specifications at the end of 'Total energy for
state' lines.
"""
assert logfile.data.metadata["legacy_package_version"] == "5.0.1"
assert logfile.data.metadata["package_version"] == "5.0.1"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
nroots = 12
assert len(logfile.data.etenergies) == nroots
state_0_energy = -526.6323968555
state_1_energy = -526.14663738
assert logfile.data.scfenergies[0] == convertor(state_0_energy, 'hartree', 'eV')
assert abs(logfile.data.etenergies[0] - convertor(state_1_energy - state_0_energy, 'hartree', 'wavenumber')) < 1.0e-1
def testQChem_QChem5_0_Si_out(logfile):
"""
This job includes MOs as a test for this version. This fist MO coefficient is checked to ensure they were parsed.
"""
assert logfile.data.metadata["legacy_package_version"] == "5.0.2"
assert logfile.data.metadata["package_version"] == "5.0.2"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
assert logfile.data.mocoeffs[0][0,0] == 1.00042
def testQChem_QChem5_1_old_final_print_1_out(logfile):
"""This job has was run from a development version."""
assert logfile.data.metadata["legacy_package_version"] == "5.1.0"
assert logfile.data.metadata["package_version"] == "5.1.0dev+branches_libresponse-27553"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
def testQChem_QChem5_3_ccman2_soc_cisd_out(logfile):
"""This file has its atomcoords in bohr, which need to be converted."""
convfac = 0.5291772109
assert logfile.data.atomcoords[0, 0, 2] == -0.24685 * convfac
assert logfile.data.atomcoords[0, 1, 2] == 1.72795 * convfac
# Turbomole
def testTurbomole_Turbomole7_2_dvb_gopt_b3_lyp_Gaussian__(logfile):
assert logfile.data.metadata["legacy_package_version"] == "7.2"
assert logfile.data.metadata["package_version"] == "7.2.r21471"
assert isinstance(
parse_version(logfile.data.metadata["package_version"]), Version
)
assert logfile.data.natom == 20
# These regression tests are for logfiles that are not to be parsed
# for some reason, and the function should start with 'testnoparse'.
def testnoparseADF_ADF2004_01_mo_sp_adfout(filename):
"""This is an ADF file that has a different number of AO functions
and SFO functions. Currently nbasis parses the SFO count. This will
be discussed and resolved in the future (see issue #170), and can
this to get rid of the error in the meantime.
"""
pass
def testnoparseGaussian_Gaussian09_coeffs_log(filename):
"""This is a test for a Gaussian file with more than 999 basis functions.
The log file is too big, so we are just including a section. Before
parsing, we set some attributes of the parser so that it all goes smoothly.
"""
parser = Gaussian(os.path.join(__filedir__, filename), loglevel=logging.ERROR)
parser.nmo = 5
parser.nbasis = 1128
data = parser.parse()
assert data.mocoeffs[0].shape == (5, 1128)
assert data.aonames[-1] == "Ga71_19D-2"
assert data.aonames[0] == "Mn1_1S"
def flatten(seq):
"""Converts a list of lists [of lists] to a single flattened list.
Taken from the web.
"""
res = []
for item in seq:
if (isinstance(item, (tuple, list))):
res.extend(flatten(item))
else:
res.append(item)
return res
def normalisefilename(filename):
"""Replace all non-alphanumeric symbols by underscores.
>>> from . import regression
>>> for x in [ "Gaussian/Gaussian03/Mo4OSibdt2-opt.log" ]:
... print(regression.normalisefilename(x))
...
Gaussian_Gaussian03_Mo4OSibdt2_opt_log
"""
ans = []
for y in filename:
x = y.lower()
if (x >= 'a' and x <= 'z') or (x >= '0' and x <= '9'):
ans.append(y)
else:
ans.append("_")
return "".join(ans)
# When a unit test is removed or replaced by a newer version, we normally want
# the old logfile to become a regression, namely to run the unit test as part of
# the regression suite. To this end, add the logfile path to the dictionary
# below along with the appropriate unit test class to use, and the appropriate
# regression test function will be created automatically. If modifications
# are necessary due to developments in the unit test class, tweak it here
# and provide the modified version of the test class.
# Although there is probably a cleaner way to do this, making the unit class test names
# global makes reading the dictionary of old unit tests much easier, especially it
# will contain some classes defined here.
for m, module in all_modules.items():
for name in dir(module):
if name[-4:] == "Test":
globals()[name] = getattr(module, name)
class ADFGeoOptTest_noscfvalues(ADFGeoOptTest):
@unittest.skip('Cannot parse scfvalues from this file.')
def testgeovalues_scfvalues(self):
"""SCF cycles were not printed here."""
@unittest.skip('Cannot parse scfvalues from this file.')
def testscftargetdim(self):
"""SCF cycles were not printed here."""
@unittest.skip('Cannot parse scfvalues from this file.')
def testscfvaluetype(self):
"""SCF cycles were not printed here."""
class ADFSPTest_noscfvalues(ADFSPTest):
@unittest.skip('Cannot parse scfvalues from this file.')
def testscftargetdim(self):
"""SCF cycles were not printed here."""
@unittest.skip('Cannot parse scfvalues from this file.')
def testscfvaluetype(self):
"""SCF cycles were not printed here."""
@unittest.skip('Cannot parse aooverlaps from this file.')
def testaooverlaps(self):
"""AO overlaps were not printed here."""
class ADFSPTest_nosyms(ADFSPTest, GenericSPTest):
foverlap00 = 1.00000
foverlap11 = 0.99999
foverlap22 = 0.99999
@unittest.skip('Symmetry labels were not printed here')
def testsymlabels(self):
"""Symmetry labels were not printed here."""
class ADFSPTest_nosyms_noscfvalues(ADFSPTest_nosyms):
@unittest.skip('Cannot parse scfvalues from this file.')
def testscftargetdim(self):
"""SCF cycles were not printed here."""
@unittest.skip('Cannot parse scfvalues from this file.')
def testscfvaluetype(self):
"""SCF cycles were not printed here."""
@unittest.skip('Cannot parse aooverlaps from this file.')
def testaooverlaps(self):
"""AO overlaps were not printed here."""
class ADFSPTest_nosyms_valence(ADFSPTest_nosyms):
def testlengthmoenergies(self):
"""Only valence orbital energies were printed here."""
self.assertEqual(len(self.data.moenergies[0]), 45)
self.assertEqual(self.data.moenergies[0][0], 99999.0)
class ADFSPTest_nosyms_valence_noscfvalues(ADFSPTest_nosyms_valence):
@unittest.skip('Cannot parse scfvalues from this file.')
def testscftargetdim(self):
"""SCF cycles were not printed here."""
@unittest.skip('Cannot parse scfvalues from this file.')
def testscfvaluetype(self):
"""SCF cycles were not printed here."""
@unittest.skip('Cannot parse aooverlaps from this file.')
def testaooverlaps(self):
"""AO overlaps were not printed here."""
# DATLON #
class DALTONBigBasisTest_aug_cc_pCVQZ(GenericBigBasisTest):
contractions = { 6: 29 }
spherical = True
class DALTONSPTest_nosyms_nolabels(GenericSPTest):
@unittest.skip('?')
def testsymlabels(self):
"""Are all the symmetry labels either Ag/u or Bg/u?."""
class DALTONTDTest_noetsecs(DALTONTDTest):
@unittest.skip("etsecs cannot be parsed from this file")
def testsecs(self):
pass
@unittest.skip("etsecs cannot be parsed from this file")
def testsecs_transition(self):
pass
# GAMESS #
class GAMESSUSSPunTest_charge0(GenericSPunTest):
def testcharge_and_mult(self):
"""The charge in the input was wrong."""
self.assertEqual(self.data.charge, 0)
@unittest.skip('HOMOs were incorrect due to charge being wrong')
def testhomos(self):
"""HOMOs were incorrect due to charge being wrong."""
class GAMESSUSIRTest_ts(GenericIRimgTest):
@unittest.skip('This is a transition state with different intensities')
def testirintens(self):
"""This is a transition state with different intensities."""
class GAMESSUSCISTest_dets(GenericCISTest):
nstates = 10
@unittest.skip('This gives unexpected coeficcients, also for current unit tests.')
def testetsecsvalues(self):
"""This gives unexpected coeficcients, also for current unit tests."""
class GAMESSSPTest_noaooverlaps(GenericSPTest):
@unittest.skip('Cannot parse aooverlaps from this file.')
def testaooverlaps(self):
"""aooverlaps were not printed here."""
# Gaussian #
class GaussianSPunTest_nomosyms(GaussianSPunTest):
@unittest.skip('Cannot parse mosyms from this file.')
def testmosyms(self):
"""mosyms were not printed here."""
class GaussianSPunTest_nonaturalorbitals(GaussianCISTest):
@unittest.skip('Cannot parse natrual orbitals from this file.')
def testnocoeffs(self):
"""natural orbitals were not printed here."""
@unittest.skip('Cannot parse natrual orbital occupation numbers from this file.')
def testnooccnos(self):
"""natural orbital occupation numbers were not printed here."""
class GaussianPolarTest(ReferencePolarTest):
"""Customized static polarizability unittest, meant for calculations
with symmetry enabled.
"""
# Reference values are from Q-Chem 4.2/trithiolane_freq.out, since
# with symmetry enabled Q-Chem reorients molecules similarly to
# Gaussian.
isotropic = 66.0955766
principal_components = [46.71020322, 75.50778705, 76.06873953]
# Make the thresholds looser because these test jobs use symmetry,
# and the polarizability is orientation dependent.
isotropic_delta = 2.0
principal_components_delta = 0.7
# Jaguar #
class JaguarSPTest_6_31gss(JaguarSPTest):
"""AO counts and some values are different in 6-31G** compared to STO-3G."""
nbasisdict = {1: 5, 6: 15}
b3lyp_energy = -10530
overlap01 = 0.22
def testmetadata_basis_set(self):
"""This calculation did not use STO-3G for the basis set."""
self.assertEqual(self.data.metadata["basis_set"].lower(), "6-31g**")
class JaguarSPTest_6_31gss_nomosyms(JaguarSPTest_6_31gss):
@unittest.skip('Cannot parse mosyms from this file.')
def testsymlabels(self):
"""mosyms were not printed here."""
class JaguarSPunTest_nomosyms(JaguarSPunTest):
@unittest.skip('Cannot parse mosyms from this file.')
def testmosyms(self):
"""mosyms were not printed here."""
class JaguarSPunTest_nmo_all(JaguarSPunTest):
def testmoenergies(self):
"""Some tests printed all MO energies apparently."""
self.assertEqual(len(self.data.moenergies[0]), self.data.nmo)
class JaguarSPunTest_nmo_all_nomosyms(JaguarSPunTest_nmo_all):
@unittest.skip('Cannot parse mosyms from this file.')
def testmosyms(self):
"""mosyms were not printed here."""
class JaguarGeoOptTest_nmo45(GenericGeoOptTest):
def testlengthmoenergies(self):
"""Without special options, Jaguar only print Homo+10 orbital energies."""
self.assertEqual(len(self.data.moenergies[0]), 45)
class JaguarSPTest_nmo45(GenericSPTest):
def testlengthmoenergies(self):
"""Without special options, Jaguar only print Homo+10 orbital energies."""
self.assertEqual(len(self.data.moenergies[0]), 45)
@unittest.skip('Cannot parse mos from this file.')
def testfornoormo(self):
"""mos were not printed here."""
@unittest.skip('Cannot parse scftargets from this file.')
def testscftargets(self):
"""scftargets were not parsed correctly here."""
@unittest.skip('Cannot parse atomcharges from this file.')
def testatomcharges(self):
"""atomcharges were not parsed correctly here."""
@unittest.skip('Cannot parse atombasis from this file.')
def testatombasis(self):
"""atombasis was not parsed correctly here."""
class JaguarSPunTest_nmo45(GenericSPunTest):
def testlengthmoenergies(self):
"""Without special options, Jaguar only print Homo+10 orbital energies."""
self.assertEqual(len(self.data.moenergies[0]), 45)
class JaguarGeoOptTest_nmo45(GenericGeoOptTest):
def testlengthmoenergies(self):
"""Without special options, Jaguar only print Homo+10 orbital energies."""
self.assertEqual(len(self.data.moenergies[0]), 45)
class JaguarGeoOptTest_nmo45_nogeo(JaguarGeoOptTest_nmo45):
@unittest.skip('Cannot parse geotargets from this file.')
def testgeotargets(self):
"""geotargets were not printed here."""
@unittest.skip('Cannot parse geovalues from this file.')
def testgeovalues_atomcoords(self):
"""geovalues were not printed here."""
@unittest.skip('Cannot parse geovalues from this file.')
def testgeovalues_scfvalues(self):
"""geovalues were not printed here."""
@unittest.skip('Cannot parse optdone from this file.')
def testoptdone(self):
"""optdone does not exist for this file."""
class JaguarGeoOptTest_6_31gss(GenericGeoOptTest):
nbasisdict = {1: 5, 6: 15}
b3lyp_energy = -10530
class MolcasBigBasisTest_nogbasis(MolcasBigBasisTest):
@unittest.skip('gbasis was not printed in this output file')
def testgbasis(self):
"""gbasis was not parsed for this file"""
@unittest.skip('gbasis was not printed in this output file')
def testnames(self):
"""gbasis was not parsed for this file"""
@unittest.skip('gbasis was not printed in this output file')
def testprimitives(self):
"""gbasis was not parsed for this file"""
@unittest.skip('gbasis was not printed in this output file')
def testsizeofbasis(self):
"""gbasis was not parsed for this file"""
# Molpro #
class MolproBigBasisTest_cart(MolproBigBasisTest):
spherical = False
# ORCA #
class OrcaSPTest_3_21g(OrcaSPTest, GenericSPTest):
nbasisdict = {1: 2, 6: 9}
b3lyp_energy = -10460
overlap01 = 0.19
molecularmass = 130190
@unittest.skip('This calculation has no symmetry.')
def testsymlabels(self):
"""This calculation has no symmetry."""
class OrcaGeoOptTest_3_21g(OrcaGeoOptTest):
nbasisdict = {1: 2, 6: 9}
b3lyp_energy = -10460
class OrcaSPunTest_charge0(GenericSPunTest):
def testcharge_and_mult(self):
"""The charge in the input was wrong."""
self.assertEqual(self.data.charge, 0)
@unittest.skip('HOMOs were incorrect due to charge being wrong.')
def testhomos(self):
"""HOMOs were incorrect due to charge being wrong."""
def testorbitals(self):
"""Closed-shell calculation run as open-shell."""
self.assertTrue(self.data.closed_shell)
class OrcaTDDFTTest_error(OrcaTDDFTTest):
def testoscs(self):
"""These values used to be less accurate, probably due to wrong coordinates."""
self.assertEqual(len(self.data.etoscs), self.number)
self.assertAlmostEqual(max(self.data.etoscs), 1.0, delta=0.2)
class OrcaIRTest_old_coordsOK(OrcaIRTest):
zpve = 0.1986
enthalpy_places = -1
entropy_places = 2
freeenergy_places = -1
class OrcaIRTest_old(OrcaIRTest):
"""The frequency part of this calculation didn't finish, but went ahead and
printed incomplete and incorrect results anyway.
"""
zpve = 0.0200
enthalpy_places = -1
entropy_places = 2
freeenergy_places = -1
@unittest.skip('These values were wrong due to wrong input coordinates.')
def testfreqval(self):
"""These values were wrong due to wrong input coordinates."""
@unittest.skip('These values were wrong due to wrong input coordinates.')
def testirintens(self):
"""These values were wrong due to wrong input coordinates."""
# PSI3 #
class Psi3SPTest(GenericSPTest):
"""Customized restricted single point HF/KS unittest"""
# The final energy is also a bit higher here, I think due to the fact
# that a SALC calculation is done instead of a full LCAO.
b3lyp_energy = -10300
@unittest.skip('atommasses not implemented yet')
def testatommasses(self):
pass
@unittest.skip('Psi3 did not print partial atomic charges')
def testatomcharges(self):
pass
@unittest.skip('MO coefficients are printed separately for each SALC')
def testfornoormo(self):
pass
@unittest.skip('MO coefficients are printed separately for each SALC')
def testdimmocoeffs(self):
pass
# PSI4 #
class PsiSPTest_noatommasses(PsiSPTest):
@unittest.skip('atommasses were not printed in this file.')
def testatommasses(self):
"""These values are not present in this output file."""
old_unittests = {
"ADF/ADF2004.01/MoOCl4-sp.adfout": ADFCoreTest,
"ADF/ADF2004.01/dvb_gopt.adfout": ADFGeoOptTest_noscfvalues,
"ADF/ADF2004.01/dvb_gopt_b.adfout": ADFGeoOptTest,
"ADF/ADF2004.01/dvb_sp.adfout": ADFSPTest_noscfvalues,
"ADF/ADF2004.01/dvb_sp_b.adfout": ADFSPTest_noscfvalues,
"ADF/ADF2004.01/dvb_sp_c.adfout": ADFSPTest_nosyms_valence_noscfvalues,
"ADF/ADF2004.01/dvb_sp_d.adfout": ADFSPTest_nosyms_noscfvalues,
"ADF/ADF2004.01/dvb_un_sp.adfout": GenericSPunTest,
"ADF/ADF2004.01/dvb_un_sp_c.adfout": GenericSPunTest,
"ADF/ADF2004.01/dvb_ir.adfout": ADFIRTest,
"ADF/ADF2006.01/dvb_gopt.adfout": ADFGeoOptTest_noscfvalues,
"ADF/ADF2013.01/dvb_gopt_b_fullscf.adfout": ADFGeoOptTest,
"ADF/ADF2014.01/dvb_gopt_b_fullscf.out": ADFGeoOptTest,
"DALTON/DALTON-2013/C_bigbasis.aug-cc-pCVQZ.out": DALTONBigBasisTest_aug_cc_pCVQZ,
"DALTON/DALTON-2013/b3lyp_energy_dvb_sp_nosym.out": DALTONSPTest_nosyms_nolabels,
"DALTON/DALTON-2013/dvb_sp_hf_nosym.out": GenericSPTest,
"DALTON/DALTON-2013/dvb_td_normalprint.out": DALTONTDTest_noetsecs,
"DALTON/DALTON-2013/sp_b3lyp_dvb.out": GenericSPTest,
"DALTON/DALTON-2015/dvb_td_normalprint.out": DALTONTDTest_noetsecs,
"DALTON/DALTON-2015/trithiolane_polar_abalnr.out": GaussianPolarTest,
"DALTON/DALTON-2015/trithiolane_polar_response.out": GaussianPolarTest,
"DALTON/DALTON-2015/trithiolane_polar_static.out": GaussianPolarTest,
"DALTON/DALTON-2015/Trp_polar_response.out": ReferencePolarTest,
"DALTON/DALTON-2015/Trp_polar_static.out": ReferencePolarTest,
"GAMESS/GAMESS-US2005/water_ccd_2005.06.27.r3.out": GenericCCTest,
"GAMESS/GAMESS-US2005/water_ccsd_2005.06.27.r3.out": GenericCCTest,
"GAMESS/GAMESS-US2005/water_ccsd(t)_2005.06.27.r3.out": GenericCCTest,
"GAMESS/GAMESS-US2005/water_cis_dets_2005.06.27.r3.out": GAMESSUSCISTest_dets,
"GAMESS/GAMESS-US2005/water_cis_saps_2005.06.27.r3.out": GenericCISTest,
"GAMESS/GAMESS-US2005/MoOCl4-sp_2005.06.27.r3.out": GenericCoreTest,
"GAMESS/GAMESS-US2005/water_mp2_2005.06.27.r3.out": GenericMP2Test,
"GAMESS/GAMESS-US2006/C_bigbasis_2006.02.22.r3.out": GenericBigBasisTest,
"GAMESS/GAMESS-US2006/dvb_gopt_a_2006.02.22.r2.out": GenericGeoOptTest,
"GAMESS/GAMESS-US2006/dvb_sp_2006.02.22.r2.out": GenericSPTest,
"GAMESS/GAMESS-US2006/dvb_un_sp_2006.02.22.r2.out": GenericSPunTest,
"GAMESS/GAMESS-US2006/dvb_ir.2006.02.22.r2.out": GenericIRTest,
"GAMESS/GAMESS-US2006/nh3_ts_ir.2006.2.22.r2.out": GAMESSUSIRTest_ts,
"GAMESS/GAMESS-US2010/dvb_gopt.log": GenericGeoOptTest,
"GAMESS/GAMESS-US2010/dvb_sp.log": GAMESSSPTest_noaooverlaps,
"GAMESS/GAMESS-US2010/dvb_sp_un.log": GAMESSUSSPunTest_charge0,
"GAMESS/GAMESS-US2010/dvb_td.log": GAMESSUSTDDFTTest,
"GAMESS/GAMESS-US2010/dvb_ir.log": GenericIRTest,
"GAMESS/GAMESS-US2014/Trp_polar_freq.out": ReferencePolarTest,
"GAMESS/GAMESS-US2014/trithiolane_polar_freq.out": GaussianPolarTest,
"GAMESS/GAMESS-US2014/trithiolane_polar_tdhf.out": GenericPolarTest,
"GAMESS/GAMESS-US2014/C_bigbasis.out" : GenericBigBasisTest,
"GAMESS/GAMESS-US2014/dvb_gopt_a.out" : GenericGeoOptTest,
"GAMESS/GAMESS-US2014/dvb_ir.out" : GamessIRTest,
"GAMESS/GAMESS-US2014/dvb_sp.out" : GenericBasisTest,
"GAMESS/GAMESS-US2014/dvb_sp.out" : GenericSPTest,
"GAMESS/GAMESS-US2014/dvb_td.out" : GAMESSUSTDDFTTest,
"GAMESS/GAMESS-US2014/dvb_td_trplet.out" : GenericTDDFTtrpTest,
"GAMESS/GAMESS-US2014/dvb_un_sp.out" : GenericSPunTest,
"GAMESS/GAMESS-US2014/MoOCl4-sp.out" : GenericCoreTest,
"GAMESS/GAMESS-US2014/nh3_ts_ir.out" : GenericIRimgTest,
"GAMESS/GAMESS-US2014/water_ccd.out" : GenericCCTest,
"GAMESS/GAMESS-US2014/water_ccsd.out" : GenericCCTest,
"GAMESS/GAMESS-US2014/water_ccsd(t).out" : GenericCCTest,
"GAMESS/GAMESS-US2014/water_cis_saps.out" : GAMESSCISTest,
"GAMESS/GAMESS-US2014/water_mp2.out" : GenericMP2Test,
"GAMESS/PCGAMESS/C_bigbasis.out": GenericBigBasisTest,
"GAMESS/PCGAMESS/dvb_gopt_b.out": GenericGeoOptTest,
"GAMESS/PCGAMESS/dvb_ir.out": FireflyIRTest,
"GAMESS/PCGAMESS/dvb_raman.out": GenericRamanTest,
"GAMESS/PCGAMESS/dvb_sp.out": GenericSPTest,
"GAMESS/PCGAMESS/dvb_td.out": GenericTDTest,
"GAMESS/PCGAMESS/dvb_td_trplet.out": GenericTDDFTtrpTest,
"GAMESS/PCGAMESS/dvb_un_sp.out": GenericSPunTest,
"GAMESS/PCGAMESS/water_mp2.out": GenericMP2Test,
"GAMESS/PCGAMESS/water_mp3.out": GenericMP3Test,
"GAMESS/PCGAMESS/water_mp4.out": GenericMP4SDQTest,
"GAMESS/PCGAMESS/water_mp4_sdtq.out": GenericMP4SDTQTest,
"GAMESS/WinGAMESS/dvb_td_2007.03.24.r1.out": GAMESSUSTDDFTTest,
"Gaussian/Gaussian03/CO_TD_delta.log": GenericTDunTest,
"Gaussian/Gaussian03/C_bigbasis.out": GaussianBigBasisTest,
"Gaussian/Gaussian03/dvb_gopt.out": GenericGeoOptTest,
"Gaussian/Gaussian03/dvb_ir.out": GaussianIRTest,
"Gaussian/Gaussian03/dvb_raman.out": GaussianRamanTest,
"Gaussian/Gaussian03/dvb_sp.out": GaussianSPTest,
"Gaussian/Gaussian03/dvb_sp_basis.log": GenericBasisTest,
"Gaussian/Gaussian03/dvb_sp_basis_b.log": GenericBasisTest,
"Gaussian/Gaussian03/dvb_td.out": GaussianTDDFTTest,
"Gaussian/Gaussian03/dvb_un_sp.out": GaussianSPunTest_nomosyms,
"Gaussian/Gaussian03/dvb_un_sp_b.log": GaussianSPunTest,
"Gaussian/Gaussian03/Mo4OCl4-sp.log": GenericCoreTest,
"Gaussian/Gaussian03/water_ccd.log": GenericCCTest,
"Gaussian/Gaussian03/water_ccsd(t).log": GenericCCTest,
"Gaussian/Gaussian03/water_ccsd.log": GenericCCTest,
"Gaussian/Gaussian03/water_cis.log": GaussianSPunTest_nonaturalorbitals,
"Gaussian/Gaussian03/water_cisd.log": GaussianSPunTest_nonaturalorbitals,
"Gaussian/Gaussian03/water_mp2.log": GaussianMP2Test,
"Gaussian/Gaussian03/water_mp3.log": GaussianMP3Test,
"Gaussian/Gaussian03/water_mp4.log": GaussianMP4SDTQTest,
"Gaussian/Gaussian03/water_mp4sdq.log": GaussianMP4SDQTest,
"Gaussian/Gaussian03/water_mp5.log": GenericMP5Test,
"Gaussian/Gaussian09/dvb_gopt_revA.02.out": GenericGeoOptTest,
"Gaussian/Gaussian09/dvb_ir_revA.02.out": GaussianIRTest,
"Gaussian/Gaussian09/dvb_raman_revA.02.out": GaussianRamanTest,
"Gaussian/Gaussian09/dvb_scan_revA.02.log": GaussianRelaxedScanTest,
"Gaussian/Gaussian09/dvb_sp_basis_b_gfprint.log": GenericBasisTest,
"Gaussian/Gaussian09/dvb_sp_basis_gfinput.log": GenericBasisTest,
"Gaussian/Gaussian09/dvb_sp_revA.02.out": GaussianSPTest,
"Gaussian/Gaussian09/dvb_td_revA.02.out": GaussianTDDFTTest,
"Gaussian/Gaussian09/dvb_un_sp_revA.02.log": GaussianSPunTest_nomosyms,
"Gaussian/Gaussian09/dvb_un_sp_b_revA.02.log": GaussianSPunTest,
"Gaussian/Gaussian09/trithiolane_polar.log": GaussianPolarTest,
"Jaguar/Jaguar4.2/dvb_gopt.out": JaguarGeoOptTest_nmo45,
"Jaguar/Jaguar4.2/dvb_gopt_b.out": GenericGeoOptTest,
"Jaguar/Jaguar4.2/dvb_sp.out": JaguarSPTest_nmo45,
"Jaguar/Jaguar4.2/dvb_sp_b.out": JaguarSPTest_nmo45,
"Jaguar/Jaguar4.2/dvb_un_sp.out": JaguarSPunTest_nmo_all_nomosyms,
"Jaguar/Jaguar4.2/dvb_ir.out": JaguarIRTest,
"Jaguar/Jaguar6.0/dvb_gopt.out": JaguarGeoOptTest_6_31gss,
"Jaguar/Jaguar6.0/dvb_sp.out": JaguarSPTest_6_31gss_nomosyms,
"Jaguar/Jaguar6.0/dvb_un_sp.out" : JaguarSPunTest_nmo_all_nomosyms,
"Jaguar/Jaguar6.5/dvb_gopt.out": JaguarGeoOptTest_nmo45,
"Jaguar/Jaguar6.5/dvb_sp.out": JaguarSPTest_nmo45,
"Jaguar/Jaguar6.5/dvb_un_sp.out": JaguarSPunTest_nomosyms,
"Jaguar/Jaguar6.5/dvb_ir.out": JaguarIRTest,
"Molcas/Molcas8.0/dvb_sp.out": MolcasSPTest,
"Molcas/Molcas8.0/dvb_sp_un.out": GenericSPunTest,
"Molcas/Molcas8.0/C_bigbasis.out": MolcasBigBasisTest_nogbasis,
"Molpro/Molpro2006/C_bigbasis_cart.out": MolproBigBasisTest_cart,
"Molpro/Molpro2012/trithiolane_polar.out": GenericPolarTest,
"NWChem/NWChem6.6/trithiolane_polar.out": GaussianPolarTest,
"ORCA/ORCA2.6/dvb_gopt.out": OrcaGeoOptTest_3_21g,
"ORCA/ORCA2.6/dvb_sp.out": OrcaSPTest_3_21g,
"ORCA/ORCA2.6/dvb_td.out": OrcaTDDFTTest_error,
"ORCA/ORCA2.6/dvb_ir.out": OrcaIRTest_old_coordsOK,
"ORCA/ORCA2.8/dvb_gopt.out": OrcaGeoOptTest,
"ORCA/ORCA2.8/dvb_sp.out": GenericBasisTest,
"ORCA/ORCA2.8/dvb_sp.out": OrcaSPTest,
"ORCA/ORCA2.8/dvb_sp_un.out": OrcaSPunTest_charge0,
"ORCA/ORCA2.8/dvb_td.out": OrcaTDDFTTest,
"ORCA/ORCA2.8/dvb_ir.out": OrcaIRTest_old,
"ORCA/ORCA2.9/dvb_gopt.out": OrcaGeoOptTest,
"ORCA/ORCA2.9/dvb_ir.out": OrcaIRTest,
"ORCA/ORCA2.9/dvb_raman.out": GenericRamanTest,
"ORCA/ORCA2.9/dvb_scan.out": OrcaRelaxedScanTest,
"ORCA/ORCA2.9/dvb_sp.out": GenericBasisTest,
"ORCA/ORCA2.9/dvb_sp.out": OrcaSPTest,
"ORCA/ORCA2.9/dvb_sp_un.out": GenericSPunTest,
"ORCA/ORCA2.9/dvb_td.out": OrcaTDDFTTest,
"ORCA/ORCA3.0/dvb_bomd.out": GenericBOMDTest,
"ORCA/ORCA3.0/dvb_gopt.out": OrcaGeoOptTest,
"ORCA/ORCA3.0/dvb_ir.out": OrcaIRTest,
"ORCA/ORCA3.0/dvb_raman.out": GenericRamanTest,
"ORCA/ORCA3.0/dvb_scan.out": OrcaRelaxedScanTest,
"ORCA/ORCA3.0/dvb_sp_un.out": GenericSPunTest,
"ORCA/ORCA3.0/dvb_sp.out": GenericBasisTest,
"ORCA/ORCA3.0/dvb_sp.out": OrcaSPTest,
"ORCA/ORCA3.0/dvb_td.out": OrcaTDDFTTest,
"ORCA/ORCA3.0/Trp_polar.out": ReferencePolarTest,
"ORCA/ORCA3.0/trithiolane_polar.out": GaussianPolarTest,
"ORCA/ORCA4.0/dvb_sp.out": GenericBasisTest,
"ORCA/ORCA4.0/dvb_gopt.out": OrcaGeoOptTest,
"ORCA/ORCA4.0/Trp_polar.out": ReferencePolarTest,
"ORCA/ORCA4.0/dvb_sp.out": OrcaSPTest,
"ORCA/ORCA4.0/dvb_sp_un.out": GenericSPunTest,
"ORCA/ORCA4.0/dvb_td.out": OrcaTDDFTTest,
"ORCA/ORCA4.0/dvb_rocis.out": OrcaROCIS40Test,
"ORCA/ORCA4.0/dvb_ir.out": GenericIRTest,
"ORCA/ORCA4.0/dvb_raman.out": OrcaRamanTest,
"Psi3/Psi3.4/dvb_sp_hf.out": Psi3SPTest,
"Psi4/Psi4-1.0/C_bigbasis.out": Psi4BigBasisTest,
"Psi4/Psi4-1.0/dvb_gopt_rhf.out": Psi4GeoOptTest,
"Psi4/Psi4-1.0/dvb_gopt_rks.out": Psi4GeoOptTest,
"Psi4/Psi4-1.0/dvb_ir_rhf.out": Psi4IRTest,
"Psi4/Psi4-1.0/dvb_sp_rhf.out": PsiSPTest_noatommasses,
"Psi4/Psi4-1.0/dvb_sp_rks.out": PsiSPTest_noatommasses,
"Psi4/Psi4-1.0/dvb_sp_rohf.out": GenericROSPTest,
"Psi4/Psi4-1.0/dvb_sp_uhf.out": GenericSPunTest,
"Psi4/Psi4-1.0/dvb_sp_uks.out": GenericSPunTest,
"Psi4/Psi4-1.0/water_ccsd(t).out": GenericCCTest,
"Psi4/Psi4-1.0/water_ccsd.out": GenericCCTest,
"Psi4/Psi4-1.0/water_mp2.out": GenericMP2Test,
"Psi4/Psi4-beta5/C_bigbasis.out": GenericBigBasisTest,
"Psi4/Psi4-beta5/dvb_gopt_hf.out": Psi4GeoOptTest,
"Psi4/Psi4-beta5/dvb_sp_hf.out": GenericBasisTest,
"Psi4/Psi4-beta5/dvb_sp_hf.out": PsiSPTest_noatommasses,
"Psi4/Psi4-beta5/dvb_sp_ks.out": GenericBasisTest,
"Psi4/Psi4-beta5/dvb_sp_ks.out": PsiSPTest_noatommasses,
"Psi4/Psi4-beta5/water_ccsd.out": GenericCCTest,
"Psi4/Psi4-beta5/water_mp2.out": GenericMP2Test,
"QChem/QChem4.2/Trp_freq.out": ReferencePolarTest,
"QChem/QChem4.2/trithiolane_polar.out": GaussianPolarTest,
"QChem/QChem4.2/trithiolane_freq.out": GaussianPolarTest,
"QChem/QChem4.4/Trp_polar_ideriv1.out": ReferencePolarTest,
"QChem/QChem4.4/Trp_polar_response.out": ReferencePolarTest,
}
def make_regression_from_old_unittest(test_class):
"""Return a regression test function from an old unit test logfile."""
def old_unit_test(logfile):
test_class.logfile = logfile
test_class.data = logfile.data
devnull = open(os.devnull, 'w')
return unittest.TextTestRunner(stream=devnull).run(unittest.makeSuite(test_class))
return old_unit_test
def test_regressions(which=[], opt_traceback=True, regdir=__regression_dir__, loglevel=logging.ERROR):
# Build a list of regression files that can be found. If there is a directory
# on the third level, then treat all files within it as one job.
try:
filenames = {}
for p in parser_names:
filenames[p] = []
pdir = os.path.join(regdir, get_program_dir(p))
for version in os.scandir(pdir):
if version.is_file():
continue
for job in os.listdir(version.path):
path = os.path.join(version.path, job)
if os.path.isdir(path):
filenames[p].append(os.path.join(path, "*"))
else:
filenames[p].append(path)
except OSError as e:
print(e)
print("\nERROR: At least one program direcory is missing.")
print("Run 'git pull' or regression_download.sh in cclib to update.")
sys.exit(1)
# This file should contain the paths to all regresssion test files we have gathered
# over the years. It is not really necessary, since we can discover them on the disk,
# but we keep it as a legacy and a way to track the regression tests.
regfile = open(os.path.join(regdir, "regressionfiles.txt"), "r")
regfilenames = [os.sep.join(x.strip().split("/")) for x in regfile.readlines()]
regfile.close()
# We will want to print a warning if you haven't downloaded all of the regression
# test files, or when, vice versa, not all of the regression test files found on disk
# are included in filenames. However, gather that data here and print the warnings
# at the end so that we test all available files and the messages are displayed
# prominently at the end.
missing_on_disk = []
missing_in_list = []
for fn in regfilenames:
if not os.path.exists(os.path.join(regdir, fn)):
missing_on_disk.append(fn)
for fn in glob.glob(os.path.join(regdir, '*', '*', '*')):
fn = fn.replace(regdir, '').strip('/')
if fn not in regfilenames:
missing_in_list.append(fn)
# Create the regression test functions from logfiles that were old unittests.
for path, test_class in old_unittests.items():
funcname = "test" + normalisefilename(path)
func = make_regression_from_old_unittest(test_class)
globals()[funcname] = func
# Gather orphaned tests - functions starting with 'test' and not corresponding
# to any regression file name.
orphaned_tests = []
for pn in parser_names:
prefix = "test%s_%s" % (pn, pn)
tests = [fn for fn in globals() if fn[:len(prefix)] == prefix]
normalized = [normalisefilename(fn.replace(__regression_dir__, '')) for fn in filenames[pn]]
orphaned = [t for t in tests if t[4:] not in normalized]
orphaned_tests.extend(orphaned)
# Assume that if a string is not a parser name it'll be a relative
# path to a specific logfile.
# TODO: filter out things that are not parsers or files, and maybe
# raise an error in that case as well.
which_parsers = [w for w in which if w in parser_names]
which_filenames = [w for w in which if w not in which_parsers]
failures = errors = total = 0
for pn in parser_names:
parser_class = eval(pn)
# Continue to next iteration if we are limiting the regression and the current
# name was not explicitely chosen (that is, passed as an argument).
if which_parsers and pn not in which_parsers:
continue;
parser_total = 0
current_filenames = filenames[pn]
current_filenames.sort()
for fname in current_filenames:
relative_path = fname[len(regdir):]
if which_filenames and relative_path not in which_filenames:
continue;
parser_total += 1
if parser_total == 1:
print("Are the %s files ccopened and parsed correctly?" % pn)
total += 1
print(" %s ..." % fname, end=" ")
# Check if there is a test (needs to be an appropriately named function).
# If not, there can also be a test that does not assume the file is
# correctly parsed (for fragments, for example), and these test need
# to be additionaly prepended with 'testnoparse'.
test_this = test_noparse = False
fname_norm = normalisefilename(fname.replace(__regression_dir__, ''))
funcname = "test" + fname_norm
test_this = funcname in globals()
funcname_noparse = "testnoparse" + fname_norm
test_noparse = not test_this and funcname_noparse in globals()
if not test_noparse:
datatype = parser_class.datatype if hasattr(parser_class, 'datatype') else ccData
job_filenames = glob.glob(fname)
try:
if len(job_filenames) == 1:
logfile = ccopen(job_filenames[0], datatype=datatype, loglevel=loglevel)
else:
logfile = ccopen(job_filenames, datatype=datatype, loglevel=loglevel)
except Exception as e:
errors += 1
print("ccopen error: ", e)
if opt_traceback:
print(traceback.format_exc())
else:
if type(logfile) == parser_class:
try:
logfile.data = logfile.parse()
except KeyboardInterrupt:
sys.exit(1)
except Exception as e:
print("parse error:", e)
errors += 1
if opt_traceback:
print(traceback.format_exc())
else:
if test_this:
try:
res = eval(funcname)(logfile)
if res and len(res.failures) > 0:
failures += len(res.failures)
print("%i test(s) failed" % len(res.failures))
if opt_traceback:
for f in res.failures:
print("Failure for", f[0])
print(f[1])
continue
elif res and len(res.errors) > 0:
errors += len(res.errors)
print("{:d} test(s) had errors".format(len(res.errors)))
if opt_traceback:
for f in res.errors:
print("Error for", f[0])
print(f[1])
continue
except AssertionError:
print("test failed")
failures += 1
if opt_traceback:
print(traceback.format_exc())
else:
print("parsed and tested")
else:
print("parsed")
else:
print("ccopen failed")
failures += 1
else:
try:
eval(funcname_noparse)(fname)
except AssertionError:
print("test failed")
failures += 1
except:
print("parse error")
errors += 1
if opt_traceback:
print(traceback.format_exc())
else:
print("test passed")
if parser_total:
print()
print("Total: %d Failed: %d Errors: %d" % (total, failures, errors))
if not opt_traceback and failures + errors > 0:
print("\nFor more information on failures/errors, add --traceback as an argument.")
# Show these warnings at the end, so that they're easy to notice. Notice that the lists
# were populated at the beginning of this function.
if len(missing_on_disk) > 0:
print("\nWARNING: You are missing %d regression file(s)." % len(missing_on_disk))
print("Run regression_download.sh in the ../data directory to update.")
print("Missing files:")
print("\n".join(missing_on_disk))
if len(missing_in_list) > 0:
print("\nWARNING: The list in 'regressionfiles.txt' is missing %d file(s)." % len(missing_in_list))
print("Add these files paths to the list and commit the change.")
print("Missing files:")
print("\n".join(missing_in_list))
if len(orphaned_tests) > 0:
print("\nWARNING: There are %d orphaned regression test functions." % len(orphaned_tests))
print("Please make sure these function names correspond to regression files:")
print("\n".join(orphaned_tests))
if failures + errors > 0:
sys.exit(1)
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--traceback", action="store_true")
parser.add_argument("--debug", action="store_true")
parser.add_argument(
"parser_or_module",
nargs="*",
help="Limit the test to the packages/parsers passed as arguments. "
"No arguments implies all parsers."
)
args = parser.parse_args()
loglevel = logging.DEBUG if args.debug else logging.ERROR
test_regressions(args.parser_or_module, args.traceback, loglevel=loglevel)
|
hollerith/schoogle | refs/heads/master | gdata/geo/__init__.py | 249 | # -*-*- encoding: utf-8 -*-*-
#
# This is gdata.photos.geo, implementing geological positioning in gdata structures
#
# $Id: __init__.py 81 2007-10-03 14:41:42Z havard.gulldahl $
#
# Copyright 2007 Håvard Gulldahl
# Portions copyright 2007 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.
"""Picasa Web Albums uses the georss and gml namespaces for
elements defined in the GeoRSS and Geography Markup Language specifications.
Specifically, Picasa Web Albums uses the following elements:
georss:where
gml:Point
gml:pos
http://code.google.com/apis/picasaweb/reference.html#georss_reference
Picasa Web Albums also accepts geographic-location data in two other formats:
W3C format and plain-GeoRSS (without GML) format.
"""
#
#Over the wire, the Picasa Web Albums only accepts and sends the
#elements mentioned above, but this module will let you seamlessly convert
#between the different formats (TODO 2007-10-18 hg)
__author__ = u'[email protected]'# (Håvard Gulldahl)' #BUG: api chokes on non-ascii chars in __author__
__license__ = 'Apache License v2'
import atom
import gdata
GEO_NAMESPACE = 'http://www.w3.org/2003/01/geo/wgs84_pos#'
GML_NAMESPACE = 'http://www.opengis.net/gml'
GEORSS_NAMESPACE = 'http://www.georss.org/georss'
class GeoBaseElement(atom.AtomBase):
"""Base class for elements.
To add new elements, you only need to add the element tag name to self._tag
and the namespace to self._namespace
"""
_tag = ''
_namespace = GML_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def __init__(self, name=None, extension_elements=None,
extension_attributes=None, text=None):
self.name = name
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Pos(GeoBaseElement):
"""(string) Specifies a latitude and longitude, separated by a space,
e.g. `35.669998 139.770004'"""
_tag = 'pos'
def PosFromString(xml_string):
return atom.CreateClassFromXMLString(Pos, xml_string)
class Point(GeoBaseElement):
"""(container) Specifies a particular geographical point, by means of
a <gml:pos> element."""
_tag = 'Point'
_children = atom.AtomBase._children.copy()
_children['{%s}pos' % GML_NAMESPACE] = ('pos', Pos)
def __init__(self, pos=None, extension_elements=None, extension_attributes=None, text=None):
GeoBaseElement.__init__(self, extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
if pos is None:
pos = Pos()
self.pos=pos
def PointFromString(xml_string):
return atom.CreateClassFromXMLString(Point, xml_string)
class Where(GeoBaseElement):
"""(container) Specifies a geographical location or region.
A container element, containing a single <gml:Point> element.
(Not to be confused with <gd:where>.)
Note that the (only) child attribute, .Point, is title-cased.
This reflects the names of elements in the xml stream
(principle of least surprise).
As a convenience, you can get a tuple of (lat, lon) with Where.location(),
and set the same data with Where.setLocation( (lat, lon) ).
Similarly, there are methods to set and get only latitude and longitude.
"""
_tag = 'where'
_namespace = GEORSS_NAMESPACE
_children = atom.AtomBase._children.copy()
_children['{%s}Point' % GML_NAMESPACE] = ('Point', Point)
def __init__(self, point=None, extension_elements=None, extension_attributes=None, text=None):
GeoBaseElement.__init__(self, extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
if point is None:
point = Point()
self.Point=point
def location(self):
"(float, float) Return Where.Point.pos.text as a (lat,lon) tuple"
try:
return tuple([float(z) for z in self.Point.pos.text.split(' ')])
except AttributeError:
return tuple()
def set_location(self, latlon):
"""(bool) Set Where.Point.pos.text from a (lat,lon) tuple.
Arguments:
lat (float): The latitude in degrees, from -90.0 to 90.0
lon (float): The longitude in degrees, from -180.0 to 180.0
Returns True on success.
"""
assert(isinstance(latlon[0], float))
assert(isinstance(latlon[1], float))
try:
self.Point.pos.text = "%s %s" % (latlon[0], latlon[1])
return True
except AttributeError:
return False
def latitude(self):
"(float) Get the latitude value of the geo-tag. See also .location()"
lat, lon = self.location()
return lat
def longitude(self):
"(float) Get the longtitude value of the geo-tag. See also .location()"
lat, lon = self.location()
return lon
longtitude = longitude
def set_latitude(self, lat):
"""(bool) Set the latitude value of the geo-tag.
Args:
lat (float): The new latitude value
See also .set_location()
"""
_lat, lon = self.location()
return self.set_location(lat, lon)
def set_longitude(self, lon):
"""(bool) Set the longtitude value of the geo-tag.
Args:
lat (float): The new latitude value
See also .set_location()
"""
lat, _lon = self.location()
return self.set_location(lat, lon)
set_longtitude = set_longitude
def WhereFromString(xml_string):
return atom.CreateClassFromXMLString(Where, xml_string)
|
pwong-mapr/private-hue | refs/heads/HUE-1096-abe | desktop/core/ext-py/Django-1.4.5/django/contrib/staticfiles/utils.py | 322 | import os
import fnmatch
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
def matches_patterns(path, patterns=None):
"""
Return True or False depending on whether the ``path`` should be
ignored (if it matches any pattern in ``ignore_patterns``).
"""
if patterns is None:
patterns = []
for pattern in patterns:
if fnmatch.fnmatchcase(path, pattern):
return True
return False
def get_files(storage, ignore_patterns=None, location=''):
"""
Recursively walk the storage directories yielding the paths
of all files that should be copied.
"""
if ignore_patterns is None:
ignore_patterns = []
directories, files = storage.listdir(location)
for fn in files:
if matches_patterns(fn, ignore_patterns):
continue
if location:
fn = os.path.join(location, fn)
yield fn
for dir in directories:
if matches_patterns(dir, ignore_patterns):
continue
if location:
dir = os.path.join(location, dir)
for fn in get_files(storage, ignore_patterns, dir):
yield fn
def check_settings(base_url=None):
"""
Checks if the staticfiles settings have sane values.
"""
if base_url is None:
base_url = settings.STATIC_URL
if not base_url:
raise ImproperlyConfigured(
"You're using the staticfiles app "
"without having set the required STATIC_URL setting.")
if settings.MEDIA_URL == base_url:
raise ImproperlyConfigured("The MEDIA_URL and STATIC_URL "
"settings must have different values")
if ((settings.MEDIA_ROOT and settings.STATIC_ROOT) and
(settings.MEDIA_ROOT == settings.STATIC_ROOT)):
raise ImproperlyConfigured("The MEDIA_ROOT and STATIC_ROOT "
"settings must have different values")
|
2013Commons/HUE-SHARK | refs/heads/master | desktop/core/ext-py/lxml/src/lxml/html/defs.py | 36 | # FIXME: this should all be confirmed against what a DTD says
# (probably in a test; this may not match the DTD exactly, but we
# should document just how it differs).
# Data taken from http://www.w3.org/TR/html401/index/elements.html
try:
frozenset
except NameError:
from sets import Set as frozenset
empty_tags = frozenset([
'area', 'base', 'basefont', 'br', 'col', 'frame', 'hr',
'img', 'input', 'isindex', 'link', 'meta', 'param'])
deprecated_tags = frozenset([
'applet', 'basefont', 'center', 'dir', 'font', 'isindex',
'menu', 's', 'strike', 'u'])
# archive actually takes a space-separated list of URIs
link_attrs = frozenset([
'action', 'archive', 'background', 'cite', 'classid',
'codebase', 'data', 'href', 'longdesc', 'profile', 'src',
'usemap',
# Not standard:
'dynsrc', 'lowsrc',
])
# Not in the HTML 4 spec:
# onerror, onresize
event_attrs = frozenset([
'onblur', 'onchange', 'onclick', 'ondblclick', 'onerror',
'onfocus', 'onkeydown', 'onkeypress', 'onkeyup', 'onload',
'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover',
'onmouseup', 'onreset', 'onresize', 'onselect', 'onsubmit',
'onunload',
])
safe_attrs = frozenset([
'abbr', 'accept', 'accept-charset', 'accesskey', 'action', 'align',
'alt', 'axis', 'border', 'cellpadding', 'cellspacing', 'char', 'charoff',
'charset', 'checked', 'cite', 'class', 'clear', 'cols', 'colspan',
'color', 'compact', 'coords', 'datetime', 'dir', 'disabled', 'enctype',
'for', 'frame', 'headers', 'height', 'href', 'hreflang', 'hspace', 'id',
'ismap', 'label', 'lang', 'longdesc', 'maxlength', 'media', 'method',
'multiple', 'name', 'nohref', 'noshade', 'nowrap', 'prompt', 'readonly',
'rel', 'rev', 'rows', 'rowspan', 'rules', 'scope', 'selected', 'shape',
'size', 'span', 'src', 'start', 'summary', 'tabindex', 'target', 'title',
'type', 'usemap', 'valign', 'value', 'vspace', 'width'])
# From http://htmlhelp.com/reference/html40/olist.html
top_level_tags = frozenset([
'html', 'head', 'body', 'frameset',
])
head_tags = frozenset([
'base', 'isindex', 'link', 'meta', 'script', 'style', 'title',
])
general_block_tags = frozenset([
'address',
'blockquote',
'center',
'del',
'div',
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'hr',
'ins',
'isindex',
'noscript',
'p',
'pre',
])
list_tags = frozenset([
'dir', 'dl', 'dt', 'dd', 'li', 'menu', 'ol', 'ul',
])
table_tags = frozenset([
'table', 'caption', 'colgroup', 'col',
'thead', 'tfoot', 'tbody', 'tr', 'td', 'th',
])
# just this one from
# http://www.georgehernandez.com/h/XComputers/HTML/2BlockLevel.htm
block_tags = general_block_tags | list_tags | table_tags | frozenset([
# Partial form tags
'fieldset', 'form', 'legend', 'optgroup', 'option',
])
form_tags = frozenset([
'form', 'button', 'fieldset', 'legend', 'input', 'label',
'select', 'optgroup', 'option', 'textarea',
])
special_inline_tags = frozenset([
'a', 'applet', 'basefont', 'bdo', 'br', 'embed', 'font', 'iframe',
'img', 'map', 'area', 'object', 'param', 'q', 'script',
'span', 'sub', 'sup',
])
phrase_tags = frozenset([
'abbr', 'acronym', 'cite', 'code', 'del', 'dfn', 'em',
'ins', 'kbd', 'samp', 'strong', 'var',
])
font_style_tags = frozenset([
'b', 'big', 'i', 's', 'small', 'strike', 'tt', 'u',
])
frame_tags = frozenset([
'frameset', 'frame', 'noframes',
])
# These tags aren't standard
nonstandard_tags = frozenset(['blink', 'marque'])
tags = (top_level_tags | head_tags | general_block_tags | list_tags
| table_tags | form_tags | special_inline_tags | phrase_tags
| font_style_tags | nonstandard_tags)
|
MartynShaw/audacity | refs/heads/master | lib-src/lv2/lv2/plugins/eg-fifths.lv2/waflib/Tools/lua.py | 318 | #! /usr/bin/env python
# encoding: utf-8
# WARNING! Do not edit! http://waf.googlecode.com/git/docs/wafbook/single.html#_obtaining_the_waf_file
from waflib.TaskGen import extension
from waflib import Task,Utils
@extension('.lua')
def add_lua(self,node):
tsk=self.create_task('luac',node,node.change_ext('.luac'))
inst_to=getattr(self,'install_path',self.env.LUADIR and'${LUADIR}'or None)
if inst_to:
self.bld.install_files(inst_to,tsk.outputs)
return tsk
class luac(Task.Task):
run_str='${LUAC} -s -o ${TGT} ${SRC}'
color='PINK'
def configure(conf):
conf.find_program('luac',var='LUAC')
|
zafar-hussain/or-tools | refs/heads/master | examples/python/nontransitive_dice.py | 32 | # Copyright 2010 Hakan Kjellerstrand [email protected]
#
# 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.
"""
Nontransitive dice in Google CP Solver.
From
http://en.wikipedia.org/wiki/Nontransitive_dice
'''
A set of nontransitive dice is a set of dice for which the relation
'is more likely to roll a higher number' is not transitive. See also
intransitivity.
This situation is similar to that in the game Rock, Paper, Scissors,
in which each element has an advantage over one choice and a
disadvantage to the other.
'''
I start with the 3 dice version
'''
* die A has sides {2,2,4,4,9,9},
* die B has sides {1,1,6,6,8,8}, and
* die C has sides {3,3,5,5,7,7}.
'''
3 dice:
Maximum winning: 27
comp: [19, 27, 19]
dice:
[[0, 0, 3, 6, 6, 6],
[2, 5, 5, 5, 5, 5],
[1, 1, 4, 4, 4, 7]]
max_win: 27
Number of solutions: 1
Nodes: 1649873 Time: 25.94
getFailures: 1649853
getBacktracks: 1649873
getPropags: 98105090
Max winnings where they are the same: 21
comp: [21, 21, 21]
dice:
[[0, 0, 3, 3, 3, 6],
[2, 2, 2, 2, 2, 5],
[1, 1, 1, 4, 4, 4]]
max_win: 21
Compare with these models:
* MiniZinc: http://hakank.org/minizinc/nontransitive_dice.mzn
* Comet: http://hakank.org/comet/nontransitive_dice.co
This model was created by Hakan Kjellerstrand ([email protected])
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
import sys
import string
from ortools.constraint_solver import pywrapcp
def main(m=3, n=6, minimize_val=0):
# Create the solver.
solver = pywrapcp.Solver("Nontransitive dice")
#
# data
#
print "number of dice:", m
print "number of sides:", n
#
# declare variables
#
dice = {}
for i in range(m):
for j in range(n):
dice[(i, j)] = solver.IntVar(1, n * 2, "dice(%i,%i)" % (i, j))
dice_flat = [dice[(i, j)] for i in range(m) for j in range(n)]
comp = {}
for i in range(m):
for j in range(2):
comp[(i, j)] = solver.IntVar(0, n * n, "comp(%i,%i)" % (i, j))
comp_flat = [comp[(i, j)] for i in range(m) for j in range(2)]
# The following variables are for summaries or objectives
gap = [solver.IntVar(0, n * n, "gap(%i)" % i) for i in range(m)]
gap_sum = solver.IntVar(0, m * n * n, "gap_sum")
max_val = solver.IntVar(0, n * 2, "max_val")
max_win = solver.IntVar(0, n * n, "max_win")
# number of occurrences of each value of the dice
counts = [solver.IntVar(0, n * m, "counts(%i)" % i) for i in range(n * 2 + 1)]
#
# constraints
#
# number of occurrences for each number
solver.Add(solver.Distribute(dice_flat, range(n * 2 + 1), counts))
solver.Add(max_win == solver.Max(comp_flat))
solver.Add(max_val == solver.Max(dice_flat))
# order of the number of each die, lowest first
[solver.Add(dice[(i, j)] <= dice[(i, j + 1)])
for i in range(m) for j in range(n - 1)]
# nontransitivity
[comp[i, 0] > comp[i, 1] for i in range(m)],
# probability gap
[solver.Add(gap[i] == comp[i, 0] - comp[i, 1]) for i in range(m)]
[solver.Add(gap[i] > 0) for i in range(m)]
solver.Add(gap_sum == solver.Sum(gap))
# and now we roll...
# Number of wins for [A vs B, B vs A]
for d in range(m):
b1 = [solver.IsGreaterVar(dice[d % m, r1], dice[(d + 1) % m, r2])
for r1 in range(n) for r2 in range(n)]
solver.Add(comp[d % m, 0] == solver.Sum(b1))
b2 = [solver.IsGreaterVar(dice[(d + 1) % m, r1], dice[d % m, r2])
for r1 in range(n) for r2 in range(n)]
solver.Add(comp[d % m, 1] == solver.Sum(b2))
# objective
if minimize_val != 0:
print "Minimizing max_val"
objective = solver.Minimize(max_val, 1)
# other experiments
# objective = solver.Maximize(max_win, 1)
# objective = solver.Maximize(gap_sum, 1)
#
# solution and search
#
db = solver.Phase(dice_flat + comp_flat,
solver.INT_VAR_DEFAULT,
solver.ASSIGN_MIN_VALUE)
if minimize_val:
solver.NewSearch(db, [objective])
else:
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
print "gap_sum:", gap_sum.Value()
print "gap:", [gap[i].Value() for i in range(m)]
print "max_val:", max_val.Value()
print "max_win:", max_win.Value()
print "dice:"
for i in range(m):
for j in range(n):
print dice[(i, j)].Value(),
print
print "comp:"
for i in range(m):
for j in range(2):
print comp[(i, j)].Value(),
print
print "counts:", [counts[i].Value() for i in range(n * 2 + 1)]
print
num_solutions += 1
solver.EndSearch()
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
m = 3 # number of dice
n = 6 # number of sides of each die
minimize_val = 0 # Minimizing max value (0: no, 1: yes)
if __name__ == "__main__":
if len(sys.argv) > 1:
m = string.atoi(sys.argv[1])
if len(sys.argv) > 2:
n = string.atoi(sys.argv[2])
if len(sys.argv) > 3:
minimize_val = string.atoi(sys.argv[3])
main(m, n, minimize_val)
|
typemytype/Mechanic | refs/heads/master | src/lib/site-packages/requests/packages/urllib3/contrib/pyopenssl.py | 64 | """
SSL with SNI_-support for Python 2. Follow these instructions if you would
like to verify SSL certificates in Python 2. Note, the default libraries do
*not* do certificate checking; you need to do additional work to validate
certificates yourself.
This needs the following packages installed:
* pyOpenSSL (tested with 16.0.0)
* cryptography (minimum 1.3.4, from pyopenssl)
* idna (minimum 2.0, from cryptography)
However, pyopenssl depends on cryptography, which depends on idna, so while we
use all three directly here we end up having relatively few packages required.
You can install them with the following command:
pip install pyopenssl cryptography idna
To activate certificate checking, call
:func:`~urllib3.contrib.pyopenssl.inject_into_urllib3` from your Python code
before you begin making HTTP requests. This can be done in a ``sitecustomize``
module, or at any other time before your application begins using ``urllib3``,
like this::
try:
import urllib3.contrib.pyopenssl
urllib3.contrib.pyopenssl.inject_into_urllib3()
except ImportError:
pass
Now you can use :mod:`urllib3` as you normally would, and it will support SNI
when the required modules are installed.
Activating this module also has the positive side effect of disabling SSL/TLS
compression in Python 2 (see `CRIME attack`_).
If you want to configure the default list of supported cipher suites, you can
set the ``urllib3.contrib.pyopenssl.DEFAULT_SSL_CIPHER_LIST`` variable.
.. _sni: https://en.wikipedia.org/wiki/Server_Name_Indication
.. _crime attack: https://en.wikipedia.org/wiki/CRIME_(security_exploit)
"""
from __future__ import absolute_import
import idna
import OpenSSL.SSL
from cryptography import x509
from cryptography.hazmat.backends.openssl import backend as openssl_backend
from cryptography.hazmat.backends.openssl.x509 import _Certificate
from socket import timeout, error as SocketError
from io import BytesIO
try: # Platform-specific: Python 2
from socket import _fileobject
except ImportError: # Platform-specific: Python 3
_fileobject = None
from ..packages.backports.makefile import backport_makefile
import logging
import ssl
import select
import six
import sys
from .. import util
__all__ = ['inject_into_urllib3', 'extract_from_urllib3']
# SNI always works.
HAS_SNI = True
# Map from urllib3 to PyOpenSSL compatible parameter-values.
_openssl_versions = {
ssl.PROTOCOL_SSLv23: OpenSSL.SSL.SSLv23_METHOD,
ssl.PROTOCOL_TLSv1: OpenSSL.SSL.TLSv1_METHOD,
}
if hasattr(ssl, 'PROTOCOL_TLSv1_1') and hasattr(OpenSSL.SSL, 'TLSv1_1_METHOD'):
_openssl_versions[ssl.PROTOCOL_TLSv1_1] = OpenSSL.SSL.TLSv1_1_METHOD
if hasattr(ssl, 'PROTOCOL_TLSv1_2') and hasattr(OpenSSL.SSL, 'TLSv1_2_METHOD'):
_openssl_versions[ssl.PROTOCOL_TLSv1_2] = OpenSSL.SSL.TLSv1_2_METHOD
try:
_openssl_versions.update({ssl.PROTOCOL_SSLv3: OpenSSL.SSL.SSLv3_METHOD})
except AttributeError:
pass
_stdlib_to_openssl_verify = {
ssl.CERT_NONE: OpenSSL.SSL.VERIFY_NONE,
ssl.CERT_OPTIONAL: OpenSSL.SSL.VERIFY_PEER,
ssl.CERT_REQUIRED:
OpenSSL.SSL.VERIFY_PEER + OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT,
}
_openssl_to_stdlib_verify = dict(
(v, k) for k, v in _stdlib_to_openssl_verify.items()
)
# OpenSSL will only write 16K at a time
SSL_WRITE_BLOCKSIZE = 16384
orig_util_HAS_SNI = util.HAS_SNI
orig_util_SSLContext = util.ssl_.SSLContext
log = logging.getLogger(__name__)
def inject_into_urllib3():
'Monkey-patch urllib3 with PyOpenSSL-backed SSL-support.'
util.ssl_.SSLContext = PyOpenSSLContext
util.HAS_SNI = HAS_SNI
util.ssl_.HAS_SNI = HAS_SNI
util.IS_PYOPENSSL = True
util.ssl_.IS_PYOPENSSL = True
def extract_from_urllib3():
'Undo monkey-patching by :func:`inject_into_urllib3`.'
util.ssl_.SSLContext = orig_util_SSLContext
util.HAS_SNI = orig_util_HAS_SNI
util.ssl_.HAS_SNI = orig_util_HAS_SNI
util.IS_PYOPENSSL = False
util.ssl_.IS_PYOPENSSL = False
def _dnsname_to_stdlib(name):
"""
Converts a dNSName SubjectAlternativeName field to the form used by the
standard library on the given Python version.
Cryptography produces a dNSName as a unicode string that was idna-decoded
from ASCII bytes. We need to idna-encode that string to get it back, and
then on Python 3 we also need to convert to unicode via UTF-8 (the stdlib
uses PyUnicode_FromStringAndSize on it, which decodes via UTF-8).
"""
def idna_encode(name):
"""
Borrowed wholesale from the Python Cryptography Project. It turns out
that we can't just safely call `idna.encode`: it can explode for
wildcard names. This avoids that problem.
"""
for prefix in [u'*.', u'.']:
if name.startswith(prefix):
name = name[len(prefix):]
return prefix.encode('ascii') + idna.encode(name)
return idna.encode(name)
name = idna_encode(name)
if sys.version_info >= (3, 0):
name = name.decode('utf-8')
return name
def get_subj_alt_name(peer_cert):
"""
Given an PyOpenSSL certificate, provides all the subject alternative names.
"""
# Pass the cert to cryptography, which has much better APIs for this.
# This is technically using private APIs, but should work across all
# relevant versions until PyOpenSSL gets something proper for this.
cert = _Certificate(openssl_backend, peer_cert._x509)
# We want to find the SAN extension. Ask Cryptography to locate it (it's
# faster than looping in Python)
try:
ext = cert.extensions.get_extension_for_class(
x509.SubjectAlternativeName
).value
except x509.ExtensionNotFound:
# No such extension, return the empty list.
return []
except (x509.DuplicateExtension, x509.UnsupportedExtension,
x509.UnsupportedGeneralNameType, UnicodeError) as e:
# A problem has been found with the quality of the certificate. Assume
# no SAN field is present.
log.warning(
"A problem was encountered with the certificate that prevented "
"urllib3 from finding the SubjectAlternativeName field. This can "
"affect certificate validation. The error was %s",
e,
)
return []
# We want to return dNSName and iPAddress fields. We need to cast the IPs
# back to strings because the match_hostname function wants them as
# strings.
# Sadly the DNS names need to be idna encoded and then, on Python 3, UTF-8
# decoded. This is pretty frustrating, but that's what the standard library
# does with certificates, and so we need to attempt to do the same.
names = [
('DNS', _dnsname_to_stdlib(name))
for name in ext.get_values_for_type(x509.DNSName)
]
names.extend(
('IP Address', str(name))
for name in ext.get_values_for_type(x509.IPAddress)
)
return names
class WrappedSocket(object):
'''API-compatibility wrapper for Python OpenSSL's Connection-class.
Note: _makefile_refs, _drop() and _reuse() are needed for the garbage
collector of pypy.
'''
def __init__(self, connection, socket, suppress_ragged_eofs=True):
self.connection = connection
self.socket = socket
self.suppress_ragged_eofs = suppress_ragged_eofs
self._makefile_refs = 0
self._closed = False
def fileno(self):
return self.socket.fileno()
# Copy-pasted from Python 3.5 source code
def _decref_socketios(self):
if self._makefile_refs > 0:
self._makefile_refs -= 1
if self._closed:
self.close()
def recv(self, *args, **kwargs):
try:
data = self.connection.recv(*args, **kwargs)
except OpenSSL.SSL.SysCallError as e:
if self.suppress_ragged_eofs and e.args == (-1, 'Unexpected EOF'):
return b''
else:
raise SocketError(str(e))
except OpenSSL.SSL.ZeroReturnError as e:
if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN:
return b''
else:
raise
except OpenSSL.SSL.WantReadError:
rd, wd, ed = select.select(
[self.socket], [], [], self.socket.gettimeout())
if not rd:
raise timeout('The read operation timed out')
else:
return self.recv(*args, **kwargs)
else:
return data
def recv_into(self, *args, **kwargs):
try:
return self.connection.recv_into(*args, **kwargs)
except OpenSSL.SSL.SysCallError as e:
if self.suppress_ragged_eofs and e.args == (-1, 'Unexpected EOF'):
return 0
else:
raise SocketError(str(e))
except OpenSSL.SSL.ZeroReturnError as e:
if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN:
return 0
else:
raise
except OpenSSL.SSL.WantReadError:
rd, wd, ed = select.select(
[self.socket], [], [], self.socket.gettimeout())
if not rd:
raise timeout('The read operation timed out')
else:
return self.recv_into(*args, **kwargs)
def settimeout(self, timeout):
return self.socket.settimeout(timeout)
def _send_until_done(self, data):
while True:
try:
return self.connection.send(data)
except OpenSSL.SSL.WantWriteError:
_, wlist, _ = select.select([], [self.socket], [],
self.socket.gettimeout())
if not wlist:
raise timeout()
continue
def sendall(self, data):
total_sent = 0
while total_sent < len(data):
sent = self._send_until_done(data[total_sent:total_sent + SSL_WRITE_BLOCKSIZE])
total_sent += sent
def shutdown(self):
# FIXME rethrow compatible exceptions should we ever use this
self.connection.shutdown()
def close(self):
if self._makefile_refs < 1:
try:
self._closed = True
return self.connection.close()
except OpenSSL.SSL.Error:
return
else:
self._makefile_refs -= 1
def getpeercert(self, binary_form=False):
x509 = self.connection.get_peer_certificate()
if not x509:
return x509
if binary_form:
return OpenSSL.crypto.dump_certificate(
OpenSSL.crypto.FILETYPE_ASN1,
x509)
return {
'subject': (
(('commonName', x509.get_subject().CN),),
),
'subjectAltName': get_subj_alt_name(x509)
}
def _reuse(self):
self._makefile_refs += 1
def _drop(self):
if self._makefile_refs < 1:
self.close()
else:
self._makefile_refs -= 1
if _fileobject: # Platform-specific: Python 2
def makefile(self, mode, bufsize=-1):
self._makefile_refs += 1
return _fileobject(self, mode, bufsize, close=True)
else: # Platform-specific: Python 3
makefile = backport_makefile
WrappedSocket.makefile = makefile
class PyOpenSSLContext(object):
"""
I am a wrapper class for the PyOpenSSL ``Context`` object. I am responsible
for translating the interface of the standard library ``SSLContext`` object
to calls into PyOpenSSL.
"""
def __init__(self, protocol):
self.protocol = _openssl_versions[protocol]
self._ctx = OpenSSL.SSL.Context(self.protocol)
self._options = 0
self.check_hostname = False
@property
def options(self):
return self._options
@options.setter
def options(self, value):
self._options = value
self._ctx.set_options(value)
@property
def verify_mode(self):
return _openssl_to_stdlib_verify[self._ctx.get_verify_mode()]
@verify_mode.setter
def verify_mode(self, value):
self._ctx.set_verify(
_stdlib_to_openssl_verify[value],
_verify_callback
)
def set_default_verify_paths(self):
self._ctx.set_default_verify_paths()
def set_ciphers(self, ciphers):
if isinstance(ciphers, six.text_type):
ciphers = ciphers.encode('utf-8')
self._ctx.set_cipher_list(ciphers)
def load_verify_locations(self, cafile=None, capath=None, cadata=None):
if cafile is not None:
cafile = cafile.encode('utf-8')
if capath is not None:
capath = capath.encode('utf-8')
self._ctx.load_verify_locations(cafile, capath)
if cadata is not None:
self._ctx.load_verify_locations(BytesIO(cadata))
def load_cert_chain(self, certfile, keyfile=None, password=None):
self._ctx.use_certificate_file(certfile)
if password is not None:
self._ctx.set_passwd_cb(lambda max_length, prompt_twice, userdata: password)
self._ctx.use_privatekey_file(keyfile or certfile)
def wrap_socket(self, sock, server_side=False,
do_handshake_on_connect=True, suppress_ragged_eofs=True,
server_hostname=None):
cnx = OpenSSL.SSL.Connection(self._ctx, sock)
if isinstance(server_hostname, six.text_type): # Platform-specific: Python 3
server_hostname = server_hostname.encode('utf-8')
if server_hostname is not None:
cnx.set_tlsext_host_name(server_hostname)
cnx.set_connect_state()
while True:
try:
cnx.do_handshake()
except OpenSSL.SSL.WantReadError:
rd, _, _ = select.select([sock], [], [], sock.gettimeout())
if not rd:
raise timeout('select timed out')
continue
except OpenSSL.SSL.Error as e:
raise ssl.SSLError('bad handshake: %r' % e)
break
return WrappedSocket(cnx, sock)
def _verify_callback(cnx, x509, err_no, err_depth, return_code):
return err_no == 0
|
ESSS/err | refs/heads/master | errbot/core_plugins/flows.py | 1 | # -*- coding: utf-8 -*-
import io
import json
from errbot import BotPlugin, botcmd, arg_botcmd
from errbot.flow import FlowNode, FlowRoot, Flow, FLOW_END
class Flows(BotPlugin):
""" Management commands related to flows / conversations.
"""
def recurse_node(self, response: io.StringIO, stack, f: FlowNode, flow: Flow=None):
if f in stack:
response.write('%s↺<br>' % ('  ' * (len(stack))))
return
if isinstance(f, FlowRoot):
doc = f.description if flow else ''
response.write('Flow [' + f.name + '] ' + doc + ' <br>')
if flow and flow.current_step == f:
response.write('↪ Start (_%s_)<br>' % str(flow.requestor))
else:
cmd = 'END' if f is FLOW_END else self._bot.all_commands[f.command]
requestor = '(_%s_)' % str(flow.requestor) if flow and flow.current_step == f else ''
doc = cmd.__doc__ if flow and f is not FLOW_END else ''
response.write('%s↪ **%s** %s %s<br>' % ('  ' * len(stack),
f if f is not FLOW_END else 'END', doc if doc else '', requestor))
for _, sf in f.children:
self.recurse_node(response, stack + [f], sf, flow)
@botcmd(syntax='<name>')
def flows_show(self, _, args):
""" Shows the structure of a flow.
"""
if not args:
return "You need to specify a flow name."
with io.StringIO() as response:
flow_node = self._bot.flow_executor.flow_roots.get(args, None)
if flow_node is None:
return "Flow %s doesn't exist." % args
self.recurse_node(response, [], flow_node)
return response.getvalue()
# noinspection PyUnusedLocal
@botcmd
def flows_list(self, msg, args):
""" Displays the list of setup flows.
"""
with io.StringIO() as response:
for name, flow_node in self._bot.flow_executor.flow_roots.items():
response.write("- **" + name + "** " + flow_node.description + "\n")
return response.getvalue()
@botcmd(split_args_with=' ', syntax='<name> [initial_payload]')
def flows_start(self, msg, args):
""" Manually start a flow within the context of the calling user.
You can prefeed the flow data with a json payload.
Example:
!flows start poll_setup {"title":"yeah!","options":["foo","bar","baz"]}
"""
if not args:
return 'You need to specify a flow to manually start'
context = {}
flow_name = args[0]
if len(args) > 1:
json_payload = ' '.join(args[1:])
try:
context = json.loads(json_payload)
except Exception as e:
return 'Cannot parse json %s: %s' % (json_payload, e)
self._bot.flow_executor.start_flow(flow_name, msg.frm, context)
return 'Flow **%s** started ...' % flow_name
@botcmd(admin_only=True)
def flows_status(self, _, args):
""" Displays the list of started flows.
"""
with io.StringIO() as response:
if args:
for flow in self._bot.flow_executor.in_flight:
if flow.name == args:
self.recurse_node(response, [], flow.root, flow)
else:
if not self._bot.flow_executor.in_flight:
response.write('No Flow started.\n')
else:
for flow in self._bot.flow_executor.in_flight:
next_steps = ['\*{}\*'.format(str(step[1].command)) for step in flow._current_step.children if
step[1].command]
template = '\>>> {} is using flow \*{}\* on step \*{}\*\nNext Step(s): \n{}'
text = template.format(str(flow.requestor),
flow.name,
str(flow.current_step),
'\n'.join(next_steps))
response.write(text)
return response.getvalue()
@botcmd(syntax='[flow_name]')
def flows_stop(self, msg, args):
""" Stop flows you are in.
optionally, stop a specific flow you are in.
"""
if args:
flow = self._bot.flow_executor.stop_flow(args, msg.frm)
if flow:
yield flow.name + ' stopped.'
return
yield 'Flow not found.'
return
one_stopped = False
for flow in self._bot.flow_executor.in_flight:
if flow.requestor == msg.frm:
flow = self._bot.flow_executor.stop_flow(flow.name, msg.frm)
if flow:
one_stopped = True
yield flow.name + ' stopped.'
if not one_stopped:
yield 'No Flow found.'
@arg_botcmd('flow_name', type=str)
@arg_botcmd('user', type=str)
def flows_kill(self, _, user, flow_name):
""" Admin command to kill a specific flow."""
flow = self._bot.flow_executor.stop_flow(flow_name, self.build_identifier(user))
if flow:
return flow.name + ' killed.'
return 'Flow not found.'
|
ASMlover/study | refs/heads/master | python/imp-lang/imp_parser.py | 1 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
#
# Copyright (c) 2016 ASMlover. 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 ofconditions 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 materialsprovided with the
# distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
from functools import reduce
import const
import combinator as cb
import imp_ast as ast
def parse_keyword(kw):
return cb.Reserved(kw, const.RESERVED)
id = cb.Tag(const.ID)
num = cb.Tag(const.INT) ^ (lambda v: int(v))
def parse(tokens):
return do_parser()(tokens, 0)
def do_parser():
return cb.Phrase(stmt_list())
def stmt_list():
sep = parse_keyword(';') ^ (lambda x: lambda l, r: ast.CompoundStmtAST(l, r))
return cb.MulParser(stmt(), sep)
def stmt():
return assign_stmt() | if_stmt() | while_stmt()
def assign_stmt():
def process(parsed):
((name, _), expr) = parsed
return ast.AssignStmtAST(name, expr)
return id + parse_keyword('=') + a_expr() ^ process
def if_stmt():
def process(parsed):
(((((_, cond), _), true_stmt), else_parsed), _) = parsed
if else_parsed:
(_, else_stmt) = else_parsed
else:
else_stmt = None
return ast.IfStmtAST(cond, true_stmt, else_stmt)
return (parse_keyword('if') + b_expr() +
parse_keyword('then') + cb.Lazy(stmt_list) +
cb.Option(parse_keyword('else') + cb.Lazy(stmt_list)) +
parse_keyword('end') ^ process)
def while_stmt():
def process(parsed):
((((_, cond), _), body), _) = parsed
return ast.WhileStmtAST(cond, body)
return (parse_keyword('while') + b_expr() + parse_keyword('do') +
cb.Lazy(stmt_list) + parse_keyword('end') ^ process)
def b_expr():
return precedence(b_expr_term(),
b_expr_precedence_levels, process_logic)
def b_expr_term():
return b_expr_not() | b_expr_logic() | b_expr_group()
def b_expr_not():
return (parse_keyword('not') + cb.Lazy(b_expr_term) ^
(lambda parsed: ast.NotExprAST(parsed[1])))
def b_expr_logic():
ops = ['<', '<=', '>', '>=', '==', '!=']
return a_expr() + any_oper_in_list(ops) + a_expr() ^ process_logic_oper
def b_expr_group():
return (parse_keyword('(') + cb.Lazy(b_expr) +
parse_keyword(')') ^ process_group)
def a_expr():
return precedence(a_expr_term(),
a_expr_precedence_levels, process_binary_oper)
def a_expr_term():
return parse_expr_value() | a_expr_group()
def a_expr_group():
return (parse_keyword('(') + cb.Lazy(a_expr) +
parse_keyword(')') ^ process_group)
def parse_expr_value():
return ((num ^ (lambda x: ast.IntExprAST(x))) |
(id ^ (lambda x: ast.VariableExprAST(x))))
def precedence(val_parser, precedence_levels, combine):
def op_parser(precedence_level):
return any_oper_in_list(precedence_level) ^ combine
parser = val_parser * op_parser(precedence_levels[0])
for precedence_level in precedence_levels[1:]:
parser = parser * op_parser(precedence_level)
return parser
def process_binary_oper(op):
return lambda l, r: ast.BinaryOperExprAST(op, l, r)
def process_logic_oper(parsed):
((l, op), r) = parsed
return ast.LogicOperExprAST(op, l, r)
def process_logic(op):
if op == 'and':
return lambda l, r: ast.AndExprAST(l, r)
elif op == 'or':
return lambda l, r: ast.OrExprAST(l, r)
else:
raise RuntimeError('Unknown logic operator: %s' % op)
def process_group(parsed):
((_, p), _) = parsed
return p
def any_oper_in_list(ops):
op_parsers = [parse_keyword(op) for op in ops]
parser = reduce(lambda l, r: l | r, op_parsers)
return parser
a_expr_precedence_levels = [
('*', '/'),
('+', '-'),
]
b_expr_precedence_levels = [
('and'),
('or'),
]
|
ingenioustechie/zamboni | refs/heads/master | mkt/lookup/tests/test_serializers.py | 17 | from django.core.urlresolvers import reverse
from nose.tools import eq_
from mkt.lookup.serializers import WebsiteLookupSerializer
from mkt.site.tests import ESTestCase
from mkt.websites.indexers import WebsiteIndexer
from mkt.websites.utils import website_factory
class TestWebsiteLookupSerializer(ESTestCase):
def setUp(self):
self.website = website_factory()
self.refresh('website')
def serialize(self):
obj = WebsiteIndexer.search().filter(
'term', id=self.website.pk).execute().hits[0]
return WebsiteLookupSerializer(obj).data
def test_basic(self):
data = self.serialize()
eq_(data['id'], self.website.id)
eq_(data['name'], {'en-US': self.website.name})
eq_(data['url'],
reverse('lookup.website_summary', args=[self.website.id]))
|
SMTorg/smt | refs/heads/master | smt/utils/checks.py | 3 | """
Author: Dr. John T. Hwang <[email protected]>
This package is distributed under New BSD license.
"""
import numpy as np
def ensure_2d_array(array, name):
if not isinstance(array, np.ndarray):
raise ValueError("{} must be a NumPy array".format(name))
array = np.atleast_2d(array.T).T
if len(array.shape) != 2:
raise ValueError("{} must have a rank of 1 or 2".format(name))
return array
def check_support(sm, name, fail=False):
if not sm.supports[name] or fail:
class_name = sm.__class__.__name__
raise NotImplementedError("{} does not support {}".format(class_name, name))
def check_nx(nx, x):
if x.shape[1] != nx:
if nx == 1:
raise ValueError("x should have shape [:, 1] or [:]")
else:
raise ValueError(
"x should have shape [:, {}] and not {}".format(nx, x.shape)
)
|
sara-02/fabric8-analytics-stack-analysis | refs/heads/master | analytics_platform/kronos/__init__.py | 1 | """Kronos modules."""
|
baylabs/grpc | refs/heads/master | tools/run_tests/run_interop_tests.py | 2 | #!/usr/bin/env python
# Copyright 2015, 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.
"""Run interop (cross-language) tests in parallel."""
from __future__ import print_function
import argparse
import atexit
import itertools
import json
import multiprocessing
import os
import re
import subprocess
import sys
import tempfile
import time
import uuid
import six
import traceback
import python_utils.dockerjob as dockerjob
import python_utils.jobset as jobset
import python_utils.report_utils as report_utils
# Docker doesn't clean up after itself, so we do it on exit.
atexit.register(lambda: subprocess.call(['stty', 'echo']))
ROOT = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), '../..'))
os.chdir(ROOT)
_DEFAULT_SERVER_PORT=8080
_SKIP_CLIENT_COMPRESSION = ['client_compressed_unary',
'client_compressed_streaming']
_SKIP_SERVER_COMPRESSION = ['server_compressed_unary',
'server_compressed_streaming']
_SKIP_COMPRESSION = _SKIP_CLIENT_COMPRESSION + _SKIP_SERVER_COMPRESSION
_SKIP_ADVANCED = ['status_code_and_message',
'custom_metadata',
'unimplemented_method',
'unimplemented_service']
_TEST_TIMEOUT = 3*60
# disable this test on core-based languages,
# see https://github.com/grpc/grpc/issues/9779
_SKIP_DATA_FRAME_PADDING = ['data_frame_padding']
class CXXLanguage:
def __init__(self):
self.client_cwd = None
self.server_cwd = None
self.http2_cwd = None
self.safename = 'cxx'
def client_cmd(self, args):
return ['bins/opt/interop_client'] + args
def client_cmd_http2interop(self, args):
return ['bins/opt/http2_client'] + args
def cloud_to_prod_env(self):
return {}
def server_cmd(self, args):
return ['bins/opt/interop_server'] + args
def global_env(self):
return {}
def unimplemented_test_cases(self):
return _SKIP_DATA_FRAME_PADDING
def unimplemented_test_cases_server(self):
return []
def __str__(self):
return 'c++'
class CSharpLanguage:
def __init__(self):
self.client_cwd = 'src/csharp/Grpc.IntegrationTesting.Client/bin/Debug/net45'
self.server_cwd = 'src/csharp/Grpc.IntegrationTesting.Server/bin/Debug/net45'
self.safename = str(self)
def client_cmd(self, args):
return ['mono', 'Grpc.IntegrationTesting.Client.exe'] + args
def cloud_to_prod_env(self):
return {}
def server_cmd(self, args):
return ['mono', 'Grpc.IntegrationTesting.Server.exe'] + args
def global_env(self):
return {}
def unimplemented_test_cases(self):
return _SKIP_SERVER_COMPRESSION + _SKIP_DATA_FRAME_PADDING
def unimplemented_test_cases_server(self):
return _SKIP_COMPRESSION
def __str__(self):
return 'csharp'
class CSharpCoreCLRLanguage:
def __init__(self):
self.client_cwd = 'src/csharp/Grpc.IntegrationTesting.Client/bin/Debug/netcoreapp1.0'
self.server_cwd = 'src/csharp/Grpc.IntegrationTesting.Server/bin/Debug/netcoreapp1.0'
self.safename = str(self)
def client_cmd(self, args):
return ['dotnet', 'exec', 'Grpc.IntegrationTesting.Client.dll'] + args
def cloud_to_prod_env(self):
return {}
def server_cmd(self, args):
return ['dotnet', 'exec', 'Grpc.IntegrationTesting.Server.dll'] + args
def global_env(self):
return {}
def unimplemented_test_cases(self):
return _SKIP_SERVER_COMPRESSION + _SKIP_DATA_FRAME_PADDING
def unimplemented_test_cases_server(self):
return _SKIP_COMPRESSION
def __str__(self):
return 'csharpcoreclr'
class JavaLanguage:
def __init__(self):
self.client_cwd = '../grpc-java'
self.server_cwd = '../grpc-java'
self.http2_cwd = '../grpc-java'
self.safename = str(self)
def client_cmd(self, args):
return ['./run-test-client.sh'] + args
def client_cmd_http2interop(self, args):
return ['./interop-testing/build/install/grpc-interop-testing/bin/http2-client'] + args
def cloud_to_prod_env(self):
return {}
def server_cmd(self, args):
return ['./run-test-server.sh'] + args
def global_env(self):
return {}
def unimplemented_test_cases(self):
return _SKIP_COMPRESSION
def unimplemented_test_cases_server(self):
return _SKIP_COMPRESSION
def __str__(self):
return 'java'
class GoLanguage:
def __init__(self):
# TODO: this relies on running inside docker
self.client_cwd = '/go/src/google.golang.org/grpc/interop/client'
self.server_cwd = '/go/src/google.golang.org/grpc/interop/server'
self.http2_cwd = '/go/src/google.golang.org/grpc/interop/http2'
self.safename = str(self)
def client_cmd(self, args):
return ['go', 'run', 'client.go'] + args
def client_cmd_http2interop(self, args):
return ['go', 'run', 'negative_http2_client.go'] + args
def cloud_to_prod_env(self):
return {}
def server_cmd(self, args):
return ['go', 'run', 'server.go'] + args
def global_env(self):
return {}
def unimplemented_test_cases(self):
return _SKIP_COMPRESSION
def unimplemented_test_cases_server(self):
return _SKIP_COMPRESSION
def __str__(self):
return 'go'
class Http2Server:
"""Represents the HTTP/2 Interop Test server
This pretends to be a language in order to be built and run, but really it
isn't.
"""
def __init__(self):
self.server_cwd = None
self.safename = str(self)
def server_cmd(self, args):
return ['python test/http2_test/http2_test_server.py']
def cloud_to_prod_env(self):
return {}
def global_env(self):
return {}
def unimplemented_test_cases(self):
return _TEST_CASES + _SKIP_DATA_FRAME_PADDING
def unimplemented_test_cases_server(self):
return _TEST_CASES
def __str__(self):
return 'http2'
class Http2Client:
"""Represents the HTTP/2 Interop Test
This pretends to be a language in order to be built and run, but really it
isn't.
"""
def __init__(self):
self.client_cwd = None
self.safename = str(self)
def client_cmd(self, args):
return ['tools/http2_interop/http2_interop.test', '-test.v'] + args
def cloud_to_prod_env(self):
return {}
def global_env(self):
return {}
def unimplemented_test_cases(self):
return _TEST_CASES
def unimplemented_test_cases_server(self):
return _TEST_CASES
def __str__(self):
return 'http2'
class NodeLanguage:
def __init__(self):
self.client_cwd = None
self.server_cwd = None
self.safename = str(self)
def client_cmd(self, args):
return ['tools/run_tests/interop/with_nvm.sh',
'node', 'src/node/interop/interop_client.js'] + args
def cloud_to_prod_env(self):
return {}
def server_cmd(self, args):
return ['tools/run_tests/interop/with_nvm.sh',
'node', 'src/node/interop/interop_server.js'] + args
def global_env(self):
return {}
def unimplemented_test_cases(self):
return _SKIP_COMPRESSION + _SKIP_DATA_FRAME_PADDING
def unimplemented_test_cases_server(self):
return _SKIP_COMPRESSION
def __str__(self):
return 'node'
class PHPLanguage:
def __init__(self):
self.client_cwd = None
self.safename = str(self)
def client_cmd(self, args):
return ['src/php/bin/interop_client.sh'] + args
def cloud_to_prod_env(self):
return {}
def global_env(self):
return {}
def unimplemented_test_cases(self):
return _SKIP_COMPRESSION + _SKIP_DATA_FRAME_PADDING
def unimplemented_test_cases_server(self):
return []
def __str__(self):
return 'php'
class PHP7Language:
def __init__(self):
self.client_cwd = None
self.safename = str(self)
def client_cmd(self, args):
return ['src/php/bin/interop_client.sh'] + args
def cloud_to_prod_env(self):
return {}
def global_env(self):
return {}
def unimplemented_test_cases(self):
return _SKIP_COMPRESSION + _SKIP_DATA_FRAME_PADDING
def unimplemented_test_cases_server(self):
return []
def __str__(self):
return 'php7'
class ObjcLanguage:
def __init__(self):
self.client_cwd = 'src/objective-c/tests'
self.safename = str(self)
def client_cmd(self, args):
# from args, extract the server port and craft xcodebuild command out of it
for arg in args:
port = re.search('--server_port=(\d+)', arg)
if port:
portnum = port.group(1)
cmdline = 'pod install && xcodebuild -workspace Tests.xcworkspace -scheme InteropTestsLocalSSL -destination name="iPhone 6" HOST_PORT_LOCALSSL=localhost:%s test'%portnum
return [cmdline]
def cloud_to_prod_env(self):
return {}
def global_env(self):
return {}
def unimplemented_test_cases(self):
# ObjC test runs all cases with the same command. It ignores the testcase
# cmdline argument. Here we return all but one test cases as unimplemented,
# and depend upon ObjC test's behavior that it runs all cases even when
# we tell it to run just one.
return _TEST_CASES[1:] + _SKIP_COMPRESSION + _SKIP_DATA_FRAME_PADDING
def unimplemented_test_cases_server(self):
return _SKIP_COMPRESSION
def __str__(self):
return 'objc'
class RubyLanguage:
def __init__(self):
self.client_cwd = None
self.server_cwd = None
self.safename = str(self)
def client_cmd(self, args):
return ['tools/run_tests/interop/with_rvm.sh',
'ruby', 'src/ruby/pb/test/client.rb'] + args
def cloud_to_prod_env(self):
return {}
def server_cmd(self, args):
return ['tools/run_tests/interop/with_rvm.sh',
'ruby', 'src/ruby/pb/test/server.rb'] + args
def global_env(self):
return {}
def unimplemented_test_cases(self):
return _SKIP_SERVER_COMPRESSION + _SKIP_DATA_FRAME_PADDING
def unimplemented_test_cases_server(self):
return _SKIP_COMPRESSION
def __str__(self):
return 'ruby'
class PythonLanguage:
def __init__(self):
self.client_cwd = None
self.server_cwd = None
self.http2_cwd = None
self.safename = str(self)
def client_cmd(self, args):
return [
'py27/bin/python',
'src/python/grpcio_tests/setup.py',
'run_interop',
'--client',
'--args="{}"'.format(' '.join(args))
]
def client_cmd_http2interop(self, args):
return [ 'py27/bin/python',
'src/python/grpcio_tests/tests/http2/negative_http2_client.py',
] + args
def cloud_to_prod_env(self):
return {}
def server_cmd(self, args):
return [
'py27/bin/python',
'src/python/grpcio_tests/setup.py',
'run_interop',
'--server',
'--args="{}"'.format(' '.join(args))
]
def global_env(self):
return {'LD_LIBRARY_PATH': '{}/libs/opt'.format(DOCKER_WORKDIR_ROOT),
'PYTHONPATH': '{}/src/python/gens'.format(DOCKER_WORKDIR_ROOT)}
def unimplemented_test_cases(self):
return _SKIP_COMPRESSION + _SKIP_DATA_FRAME_PADDING
def unimplemented_test_cases_server(self):
return _SKIP_COMPRESSION
def __str__(self):
return 'python'
_LANGUAGES = {
'c++' : CXXLanguage(),
'csharp' : CSharpLanguage(),
'csharpcoreclr' : CSharpCoreCLRLanguage(),
'go' : GoLanguage(),
'java' : JavaLanguage(),
'node' : NodeLanguage(),
'php' : PHPLanguage(),
'php7' : PHP7Language(),
'objc' : ObjcLanguage(),
'ruby' : RubyLanguage(),
'python' : PythonLanguage(),
}
# languages supported as cloud_to_cloud servers
_SERVERS = ['c++', 'node', 'csharp', 'csharpcoreclr', 'java', 'go', 'ruby', 'python']
_TEST_CASES = ['large_unary', 'empty_unary', 'ping_pong',
'empty_stream', 'client_streaming', 'server_streaming',
'cancel_after_begin', 'cancel_after_first_response',
'timeout_on_sleeping_server', 'custom_metadata',
'status_code_and_message', 'unimplemented_method',
'client_compressed_unary', 'server_compressed_unary',
'client_compressed_streaming', 'server_compressed_streaming',
'unimplemented_service']
_AUTH_TEST_CASES = ['compute_engine_creds', 'jwt_token_creds',
'oauth2_auth_token', 'per_rpc_creds']
_HTTP2_TEST_CASES = ['tls', 'framing']
_HTTP2_SERVER_TEST_CASES = ['rst_after_header', 'rst_after_data', 'rst_during_data',
'goaway', 'ping', 'max_streams', 'data_frame_padding', 'no_df_padding_sanity_test']
_GRPC_CLIENT_TEST_CASES_FOR_HTTP2_SERVER_TEST_CASES = { 'data_frame_padding': 'large_unary', 'no_df_padding_sanity_test': 'large_unary' }
_HTTP2_SERVER_TEST_CASES_THAT_USE_GRPC_CLIENTS = _GRPC_CLIENT_TEST_CASES_FOR_HTTP2_SERVER_TEST_CASES.keys()
_LANGUAGES_WITH_HTTP2_CLIENTS_FOR_HTTP2_SERVER_TEST_CASES = ['java', 'go', 'python', 'c++']
DOCKER_WORKDIR_ROOT = '/var/local/git/grpc'
def docker_run_cmdline(cmdline, image, docker_args=[], cwd=None, environ=None):
"""Wraps given cmdline array to create 'docker run' cmdline from it."""
docker_cmdline = ['docker', 'run', '-i', '--rm=true']
# turn environ into -e docker args
if environ:
for k,v in environ.items():
docker_cmdline += ['-e', '%s=%s' % (k,v)]
# set working directory
workdir = DOCKER_WORKDIR_ROOT
if cwd:
workdir = os.path.join(workdir, cwd)
docker_cmdline += ['-w', workdir]
docker_cmdline += docker_args + [image] + cmdline
return docker_cmdline
def manual_cmdline(docker_cmdline):
"""Returns docker cmdline adjusted for manual invocation."""
print_cmdline = []
for item in docker_cmdline:
if item.startswith('--name='):
continue
# add quotes when necessary
if any(character.isspace() for character in item):
item = "\"%s\"" % item
print_cmdline.append(item)
return ' '.join(print_cmdline)
def write_cmdlog_maybe(cmdlog, filename):
"""Returns docker cmdline adjusted for manual invocation."""
if cmdlog:
with open(filename, 'w') as logfile:
logfile.write('#!/bin/bash\n')
logfile.writelines("%s\n" % line for line in cmdlog)
print('Command log written to file %s' % filename)
def bash_cmdline(cmdline):
"""Creates bash -c cmdline from args list."""
# Use login shell:
# * makes error messages clearer if executables are missing
return ['bash', '-c', ' '.join(cmdline)]
def auth_options(language, test_case):
"""Returns (cmdline, env) tuple with cloud_to_prod_auth test options."""
language = str(language)
cmdargs = []
env = {}
# TODO(jtattermusch): this file path only works inside docker
key_filepath = '/root/service_account/stubbyCloudTestingTest-ee3fce360ac5.json'
oauth_scope_arg = '--oauth_scope=https://www.googleapis.com/auth/xapi.zoo'
key_file_arg = '--service_account_key_file=%s' % key_filepath
default_account_arg = '--default_service_account=830293263384-compute@developer.gserviceaccount.com'
if test_case in ['jwt_token_creds', 'per_rpc_creds', 'oauth2_auth_token']:
if language in ['csharp', 'csharpcoreclr', 'node', 'php', 'php7', 'python', 'ruby']:
env['GOOGLE_APPLICATION_CREDENTIALS'] = key_filepath
else:
cmdargs += [key_file_arg]
if test_case in ['per_rpc_creds', 'oauth2_auth_token']:
cmdargs += [oauth_scope_arg]
if test_case == 'oauth2_auth_token' and language == 'c++':
# C++ oauth2 test uses GCE creds and thus needs to know the default account
cmdargs += [default_account_arg]
if test_case == 'compute_engine_creds':
cmdargs += [oauth_scope_arg, default_account_arg]
return (cmdargs, env)
def _job_kill_handler(job):
if job._spec.container_name:
dockerjob.docker_kill(job._spec.container_name)
# When the job times out and we decide to kill it,
# we need to wait a before restarting the job
# to prevent "container name already in use" error.
# TODO(jtattermusch): figure out a cleaner way to to this.
time.sleep(2)
def cloud_to_prod_jobspec(language, test_case, server_host_name,
server_host_detail, docker_image=None, auth=False,
manual_cmd_log=None):
"""Creates jobspec for cloud-to-prod interop test"""
container_name = None
cmdargs = [
'--server_host=%s' % server_host_detail[0],
'--server_host_override=%s' % server_host_detail[1],
'--server_port=443',
'--use_tls=true',
'--test_case=%s' % test_case]
environ = dict(language.cloud_to_prod_env(), **language.global_env())
if auth:
auth_cmdargs, auth_env = auth_options(language, test_case)
cmdargs += auth_cmdargs
environ.update(auth_env)
cmdline = bash_cmdline(language.client_cmd(cmdargs))
cwd = language.client_cwd
if docker_image:
container_name = dockerjob.random_name('interop_client_%s' %
language.safename)
cmdline = docker_run_cmdline(cmdline,
image=docker_image,
cwd=cwd,
environ=environ,
docker_args=['--net=host',
'--name=%s' % container_name])
if manual_cmd_log is not None:
manual_cmd_log.append(manual_cmdline(cmdline))
cwd = None
environ = None
suite_name='cloud_to_prod_auth' if auth else 'cloud_to_prod'
test_job = jobset.JobSpec(
cmdline=cmdline,
cwd=cwd,
environ=environ,
shortname='%s:%s:%s:%s' % (suite_name, server_host_name, language,
test_case),
timeout_seconds=_TEST_TIMEOUT,
flake_retries=5 if args.allow_flakes else 0,
timeout_retries=2 if args.allow_flakes else 0,
kill_handler=_job_kill_handler)
if docker_image:
test_job.container_name = container_name
return test_job
def cloud_to_cloud_jobspec(language, test_case, server_name, server_host,
server_port, docker_image=None, insecure=False,
manual_cmd_log=None):
"""Creates jobspec for cloud-to-cloud interop test"""
interop_only_options = [
'--server_host_override=foo.test.google.fr',
'--use_tls=%s' % ('false' if insecure else 'true'),
'--use_test_ca=true',
]
client_test_case = test_case
if test_case in _HTTP2_SERVER_TEST_CASES_THAT_USE_GRPC_CLIENTS:
client_test_case = _GRPC_CLIENT_TEST_CASES_FOR_HTTP2_SERVER_TEST_CASES[test_case]
if client_test_case in language.unimplemented_test_cases():
print('asking client %s to run unimplemented test case %s' % (repr(language), client_test_case))
sys.exit(1)
common_options = [
'--test_case=%s' % client_test_case,
'--server_host=%s' % server_host,
'--server_port=%s' % server_port,
]
if test_case in _HTTP2_SERVER_TEST_CASES:
if test_case in _HTTP2_SERVER_TEST_CASES_THAT_USE_GRPC_CLIENTS:
client_options = interop_only_options + common_options
cmdline = bash_cmdline(language.client_cmd(client_options))
cwd = language.client_cwd
else:
cmdline = bash_cmdline(language.client_cmd_http2interop(common_options))
cwd = language.http2_cwd
else:
cmdline = bash_cmdline(language.client_cmd(common_options+interop_only_options))
cwd = language.client_cwd
environ = language.global_env()
if docker_image and language.safename != 'objc':
# we can't run client in docker for objc.
container_name = dockerjob.random_name('interop_client_%s' % language.safename)
cmdline = docker_run_cmdline(cmdline,
image=docker_image,
environ=environ,
cwd=cwd,
docker_args=['--net=host',
'--name=%s' % container_name])
if manual_cmd_log is not None:
manual_cmd_log.append(manual_cmdline(cmdline))
cwd = None
test_job = jobset.JobSpec(
cmdline=cmdline,
cwd=cwd,
environ=environ,
shortname='cloud_to_cloud:%s:%s_server:%s' % (language, server_name,
test_case),
timeout_seconds=_TEST_TIMEOUT,
flake_retries=5 if args.allow_flakes else 0,
timeout_retries=2 if args.allow_flakes else 0,
kill_handler=_job_kill_handler)
if docker_image:
test_job.container_name = container_name
return test_job
def server_jobspec(language, docker_image, insecure=False, manual_cmd_log=None):
"""Create jobspec for running a server"""
container_name = dockerjob.random_name('interop_server_%s' % language.safename)
cmdline = bash_cmdline(
language.server_cmd(['--port=%s' % _DEFAULT_SERVER_PORT,
'--use_tls=%s' % ('false' if insecure else 'true')]))
environ = language.global_env()
docker_args = ['--name=%s' % container_name]
if language.safename == 'http2':
# we are running the http2 interop server. Open next N ports beginning
# with the server port. These ports are used for http2 interop test
# (one test case per port).
docker_args += list(
itertools.chain.from_iterable(('-p', str(_DEFAULT_SERVER_PORT + i))
for i in range(
len(_HTTP2_SERVER_TEST_CASES))))
# Enable docker's healthcheck mechanism.
# This runs a Python script inside the container every second. The script
# pings the http2 server to verify it is ready. The 'health-retries' flag
# specifies the number of consecutive failures before docker will report
# the container's status as 'unhealthy'. Prior to the first 'health_retries'
# failures or the first success, the status will be 'starting'. 'docker ps'
# or 'docker inspect' can be used to see the health of the container on the
# command line.
docker_args += [
'--health-cmd=python test/http2_test/http2_server_health_check.py '
'--server_host=%s --server_port=%d'
% ('localhost', _DEFAULT_SERVER_PORT),
'--health-interval=1s',
'--health-retries=5',
'--health-timeout=10s',
]
else:
docker_args += ['-p', str(_DEFAULT_SERVER_PORT)]
docker_cmdline = docker_run_cmdline(cmdline,
image=docker_image,
cwd=language.server_cwd,
environ=environ,
docker_args=docker_args)
if manual_cmd_log is not None:
manual_cmd_log.append(manual_cmdline(docker_cmdline))
server_job = jobset.JobSpec(
cmdline=docker_cmdline,
environ=environ,
shortname='interop_server_%s' % language,
timeout_seconds=30*60)
server_job.container_name = container_name
return server_job
def build_interop_image_jobspec(language, tag=None):
"""Creates jobspec for building interop docker image for a language"""
if not tag:
tag = 'grpc_interop_%s:%s' % (language.safename, uuid.uuid4())
env = {'INTEROP_IMAGE': tag,
'BASE_NAME': 'grpc_interop_%s' % language.safename}
if not args.travis:
env['TTY_FLAG'] = '-t'
# This env variable is used to get around the github rate limit
# error when running the PHP `composer install` command
host_file = '%s/.composer/auth.json' % os.environ['HOME']
if language.safename == 'php' and os.path.exists(host_file):
env['BUILD_INTEROP_DOCKER_EXTRA_ARGS'] = \
'-v %s:/root/.composer/auth.json:ro' % host_file
build_job = jobset.JobSpec(
cmdline=['tools/run_tests/dockerize/build_interop_image.sh'],
environ=env,
shortname='build_docker_%s' % (language),
timeout_seconds=30*60)
build_job.tag = tag
return build_job
def aggregate_http2_results(stdout):
match = re.search(r'\{"cases[^\]]*\]\}', stdout)
if not match:
return None
results = json.loads(match.group(0))
skipped = 0
passed = 0
failed = 0
failed_cases = []
for case in results['cases']:
if case.get('skipped', False):
skipped += 1
else:
if case.get('passed', False):
passed += 1
else:
failed += 1
failed_cases.append(case.get('name', "NONAME"))
return {
'passed': passed,
'failed': failed,
'skipped': skipped,
'failed_cases': ', '.join(failed_cases),
'percent': 1.0 * passed / (passed + failed)
}
# A dictionary of prod servers to test.
# Format: server_name: (server_host, server_host_override, errors_allowed)
# TODO(adelez): implement logic for errors_allowed where if the indicated tests
# fail, they don't impact the overall test result.
prod_servers = {
'default': ('216.239.32.254',
'grpc-test.sandbox.googleapis.com', False),
'gateway_v2': ('216.239.32.254',
'grpc-test2.sandbox.googleapis.com', True),
'cloud_gateway': ('216.239.32.255', 'grpc-test.sandbox.googleapis.com',
False),
'cloud_gateway_v2': ('216.239.32.255', 'grpc-test2.sandbox.googleapis.com',
True),
'gateway_v4': ('216.239.32.254',
'grpc-test4.sandbox.googleapis.com', True),
'cloud_gateway_v4': ('216.239.32.255', 'grpc-test4.sandbox.googleapis.com',
True),
}
argp = argparse.ArgumentParser(description='Run interop tests.')
argp.add_argument('-l', '--language',
choices=['all'] + sorted(_LANGUAGES),
nargs='+',
default=['all'],
help='Clients to run. Objc client can be only run on OSX.')
argp.add_argument('-j', '--jobs', default=multiprocessing.cpu_count(), type=int)
argp.add_argument('--cloud_to_prod',
default=False,
action='store_const',
const=True,
help='Run cloud_to_prod tests.')
argp.add_argument('--cloud_to_prod_auth',
default=False,
action='store_const',
const=True,
help='Run cloud_to_prod_auth tests.')
argp.add_argument('--prod_servers',
choices=prod_servers.keys(),
default=['default'],
nargs='+',
help=('The servers to run cloud_to_prod and '
'cloud_to_prod_auth tests against.'))
argp.add_argument('-s', '--server',
choices=['all'] + sorted(_SERVERS),
nargs='+',
help='Run cloud_to_cloud servers in a separate docker ' +
'image. Servers can only be started automatically if ' +
'--use_docker option is enabled.',
default=[])
argp.add_argument('--override_server',
action='append',
type=lambda kv: kv.split('='),
help='Use servername=HOST:PORT to explicitly specify a server. E.g. csharp=localhost:50000',
default=[])
argp.add_argument('-t', '--travis',
default=False,
action='store_const',
const=True)
argp.add_argument('-v', '--verbose',
default=False,
action='store_const',
const=True)
argp.add_argument('--use_docker',
default=False,
action='store_const',
const=True,
help='Run all the interop tests under docker. That provides ' +
'additional isolation and prevents the need to install ' +
'language specific prerequisites. Only available on Linux.')
argp.add_argument('--allow_flakes',
default=False,
action='store_const',
const=True,
help='Allow flaky tests to show as passing (re-runs failed tests up to five times)')
argp.add_argument('--manual_run',
default=False,
action='store_const',
const=True,
help='Prepare things for running interop tests manually. ' +
'Preserve docker images after building them and skip '
'actually running the tests. Only print commands to run by ' +
'hand.')
argp.add_argument('--http2_interop',
default=False,
action='store_const',
const=True,
help='Enable HTTP/2 client edge case testing. (Bad client, good server)')
argp.add_argument('--http2_server_interop',
default=False,
action='store_const',
const=True,
help='Enable HTTP/2 server edge case testing. (Includes positive and negative tests')
argp.add_argument('--insecure',
default=False,
action='store_const',
const=True,
help='Whether to use secure channel.')
args = argp.parse_args()
servers = set(s for s in itertools.chain.from_iterable(_SERVERS
if x == 'all' else [x]
for x in args.server))
if args.use_docker:
if not args.travis:
print('Seen --use_docker flag, will run interop tests under docker.')
print('')
print('IMPORTANT: The changes you are testing need to be locally committed')
print('because only the committed changes in the current branch will be')
print('copied to the docker environment.')
time.sleep(5)
if args.manual_run and not args.use_docker:
print('--manual_run is only supported with --use_docker option enabled.')
sys.exit(1)
if not args.use_docker and servers:
print('Running interop servers is only supported with --use_docker option enabled.')
sys.exit(1)
# we want to include everything but objc in 'all'
# because objc won't run on non-mac platforms
all_but_objc = set(six.iterkeys(_LANGUAGES)) - set(['objc'])
languages = set(_LANGUAGES[l]
for l in itertools.chain.from_iterable(
all_but_objc if x == 'all' else [x]
for x in args.language))
languages_http2_clients_for_http2_server_interop = set()
if args.http2_server_interop:
languages_http2_clients_for_http2_server_interop = set(
_LANGUAGES[l] for l in _LANGUAGES_WITH_HTTP2_CLIENTS_FOR_HTTP2_SERVER_TEST_CASES
if 'all' in args.language or l in args.language)
http2Interop = Http2Client() if args.http2_interop else None
http2InteropServer = Http2Server() if args.http2_server_interop else None
docker_images={}
if args.use_docker:
# languages for which to build docker images
languages_to_build = set(
_LANGUAGES[k] for k in set([str(l) for l in languages] + [s for s in servers]))
languages_to_build = languages_to_build | languages_http2_clients_for_http2_server_interop
if args.http2_interop:
languages_to_build.add(http2Interop)
if args.http2_server_interop:
languages_to_build.add(http2InteropServer)
build_jobs = []
for l in languages_to_build:
if str(l) == 'objc':
# we don't need to build a docker image for objc
continue
job = build_interop_image_jobspec(l)
docker_images[str(l)] = job.tag
build_jobs.append(job)
if build_jobs:
jobset.message('START', 'Building interop docker images.', do_newline=True)
if args.verbose:
print('Jobs to run: \n%s\n' % '\n'.join(str(j) for j in build_jobs))
num_failures, _ = jobset.run(
build_jobs, newline_on_success=True, maxjobs=args.jobs)
if num_failures == 0:
jobset.message('SUCCESS', 'All docker images built successfully.',
do_newline=True)
else:
jobset.message('FAILED', 'Failed to build interop docker images.',
do_newline=True)
for image in six.itervalues(docker_images):
dockerjob.remove_image(image, skip_nonexistent=True)
sys.exit(1)
server_manual_cmd_log = [] if args.manual_run else None
client_manual_cmd_log = [] if args.manual_run else None
# Start interop servers.
server_jobs = {}
server_addresses = {}
try:
for s in servers:
lang = str(s)
spec = server_jobspec(_LANGUAGES[lang], docker_images.get(lang),
args.insecure, manual_cmd_log=server_manual_cmd_log)
if not args.manual_run:
job = dockerjob.DockerJob(spec)
server_jobs[lang] = job
server_addresses[lang] = ('localhost', job.mapped_port(_DEFAULT_SERVER_PORT))
else:
# don't run the server, set server port to a placeholder value
server_addresses[lang] = ('localhost', '${SERVER_PORT}')
http2_server_job = None
if args.http2_server_interop:
# launch a HTTP2 server emulator that creates edge cases
lang = str(http2InteropServer)
spec = server_jobspec(http2InteropServer, docker_images.get(lang),
manual_cmd_log=server_manual_cmd_log)
if not args.manual_run:
http2_server_job = dockerjob.DockerJob(spec)
server_jobs[lang] = http2_server_job
else:
# don't run the server, set server port to a placeholder value
server_addresses[lang] = ('localhost', '${SERVER_PORT}')
jobs = []
if args.cloud_to_prod:
if args.insecure:
print('TLS is always enabled for cloud_to_prod scenarios.')
for server_host_name in args.prod_servers:
for language in languages:
for test_case in _TEST_CASES:
if not test_case in language.unimplemented_test_cases():
if not test_case in _SKIP_ADVANCED + _SKIP_COMPRESSION:
test_job = cloud_to_prod_jobspec(
language, test_case, server_host_name,
prod_servers[server_host_name],
docker_image=docker_images.get(str(language)),
manual_cmd_log=client_manual_cmd_log)
jobs.append(test_job)
if args.http2_interop:
for test_case in _HTTP2_TEST_CASES:
test_job = cloud_to_prod_jobspec(
http2Interop, test_case, server_host_name,
prod_servers[server_host_name],
docker_image=docker_images.get(str(http2Interop)),
manual_cmd_log=client_manual_cmd_log)
jobs.append(test_job)
if args.cloud_to_prod_auth:
if args.insecure:
print('TLS is always enabled for cloud_to_prod scenarios.')
for server_host_name in args.prod_servers:
for language in languages:
for test_case in _AUTH_TEST_CASES:
if not test_case in language.unimplemented_test_cases():
test_job = cloud_to_prod_jobspec(
language, test_case, server_host_name,
prod_servers[server_host_name],
docker_image=docker_images.get(str(language)), auth=True,
manual_cmd_log=client_manual_cmd_log)
jobs.append(test_job)
for server in args.override_server:
server_name = server[0]
(server_host, server_port) = server[1].split(':')
server_addresses[server_name] = (server_host, server_port)
for server_name, server_address in server_addresses.items():
(server_host, server_port) = server_address
server_language = _LANGUAGES.get(server_name, None)
skip_server = [] # test cases unimplemented by server
if server_language:
skip_server = server_language.unimplemented_test_cases_server()
for language in languages:
for test_case in _TEST_CASES:
if not test_case in language.unimplemented_test_cases():
if not test_case in skip_server:
test_job = cloud_to_cloud_jobspec(language,
test_case,
server_name,
server_host,
server_port,
docker_image=docker_images.get(str(language)),
insecure=args.insecure,
manual_cmd_log=client_manual_cmd_log)
jobs.append(test_job)
if args.http2_interop:
for test_case in _HTTP2_TEST_CASES:
if server_name == "go":
# TODO(carl-mastrangelo): Reenable after https://github.com/grpc/grpc-go/issues/434
continue
test_job = cloud_to_cloud_jobspec(http2Interop,
test_case,
server_name,
server_host,
server_port,
docker_image=docker_images.get(str(http2Interop)),
insecure=args.insecure,
manual_cmd_log=client_manual_cmd_log)
jobs.append(test_job)
if args.http2_server_interop:
if not args.manual_run:
http2_server_job.wait_for_healthy(timeout_seconds=600)
for language in languages_http2_clients_for_http2_server_interop:
for test_case in set(_HTTP2_SERVER_TEST_CASES) - set(_HTTP2_SERVER_TEST_CASES_THAT_USE_GRPC_CLIENTS):
offset = sorted(_HTTP2_SERVER_TEST_CASES).index(test_case)
server_port = _DEFAULT_SERVER_PORT+offset
if not args.manual_run:
server_port = http2_server_job.mapped_port(server_port)
test_job = cloud_to_cloud_jobspec(language,
test_case,
str(http2InteropServer),
'localhost',
server_port,
docker_image=docker_images.get(str(language)),
manual_cmd_log=client_manual_cmd_log)
jobs.append(test_job)
for language in languages:
# HTTP2_SERVER_TEST_CASES_THAT_USE_GRPC_CLIENTS is a subset of
# HTTP_SERVER_TEST_CASES, in which clients use their gRPC interop clients rather
# than specialized http2 clients, reusing existing test implementations.
# For example, in the "data_frame_padding" test, use language's gRPC
# interop clients and make them think that theyre running "large_unary"
# test case. This avoids implementing a new test case in each language.
for test_case in _HTTP2_SERVER_TEST_CASES_THAT_USE_GRPC_CLIENTS:
if test_case not in language.unimplemented_test_cases():
offset = sorted(_HTTP2_SERVER_TEST_CASES).index(test_case)
server_port = _DEFAULT_SERVER_PORT+offset
if not args.manual_run:
server_port = http2_server_job.mapped_port(server_port)
if not args.insecure:
print(('Creating grpc cient to http2 server test case with insecure connection, even though'
' args.insecure is False. Http2 test server only supports insecure connections.'))
test_job = cloud_to_cloud_jobspec(language,
test_case,
str(http2InteropServer),
'localhost',
server_port,
docker_image=docker_images.get(str(language)),
insecure=True,
manual_cmd_log=client_manual_cmd_log)
jobs.append(test_job)
if not jobs:
print('No jobs to run.')
for image in six.itervalues(docker_images):
dockerjob.remove_image(image, skip_nonexistent=True)
sys.exit(1)
if args.manual_run:
print('All tests will skipped --manual_run option is active.')
if args.verbose:
print('Jobs to run: \n%s\n' % '\n'.join(str(job) for job in jobs))
num_failures, resultset = jobset.run(jobs, newline_on_success=True,
maxjobs=args.jobs,
skip_jobs=args.manual_run)
if num_failures:
jobset.message('FAILED', 'Some tests failed', do_newline=True)
else:
jobset.message('SUCCESS', 'All tests passed', do_newline=True)
write_cmdlog_maybe(server_manual_cmd_log, 'interop_server_cmds.sh')
write_cmdlog_maybe(client_manual_cmd_log, 'interop_client_cmds.sh')
report_utils.render_junit_xml_report(resultset, 'report.xml')
for name, job in resultset.items():
if "http2" in name:
job[0].http2results = aggregate_http2_results(job[0].message)
http2_server_test_cases = (
_HTTP2_SERVER_TEST_CASES if args.http2_server_interop else [])
report_utils.render_interop_html_report(
set([str(l) for l in languages]), servers, _TEST_CASES, _AUTH_TEST_CASES,
_HTTP2_TEST_CASES, http2_server_test_cases, resultset, num_failures,
args.cloud_to_prod_auth or args.cloud_to_prod, args.prod_servers,
args.http2_interop)
except Exception as e:
print('exception occurred:')
traceback.print_exc(file=sys.stdout)
finally:
# Check if servers are still running.
for server, job in server_jobs.items():
if not job.is_running():
print('Server "%s" has exited prematurely.' % server)
dockerjob.finish_jobs([j for j in six.itervalues(server_jobs)])
for image in six.itervalues(docker_images):
if not args.manual_run:
print('Removing docker image %s' % image)
dockerjob.remove_image(image)
else:
print('Preserving docker image: %s' % image)
|
jnewland/home-assistant | refs/heads/ci | homeassistant/components/calendar/__init__.py | 5 | """Support for Google Calendar event device sensors."""
import logging
from datetime import timedelta
import re
from aiohttp import web
from homeassistant.components.google import (
CONF_OFFSET, CONF_DEVICE_ID, CONF_NAME)
from homeassistant.const import STATE_OFF, STATE_ON
from homeassistant.helpers.config_validation import ( # noqa
PLATFORM_SCHEMA, PLATFORM_SCHEMA_BASE)
from homeassistant.helpers.config_validation import time_period_str
from homeassistant.helpers.entity import Entity, generate_entity_id
from homeassistant.helpers.entity_component import EntityComponent
from homeassistant.helpers.template import DATE_STR_FORMAT
from homeassistant.util import dt
from homeassistant.components import http
_LOGGER = logging.getLogger(__name__)
DOMAIN = 'calendar'
ENTITY_ID_FORMAT = DOMAIN + '.{}'
SCAN_INTERVAL = timedelta(seconds=60)
async def async_setup(hass, config):
"""Track states and offer events for calendars."""
component = EntityComponent(
_LOGGER, DOMAIN, hass, SCAN_INTERVAL, DOMAIN)
hass.http.register_view(CalendarListView(component))
hass.http.register_view(CalendarEventView(component))
# Doesn't work in prod builds of the frontend: home-assistant-polymer#1289
# await hass.components.frontend.async_register_built_in_panel(
# 'calendar', 'calendar', 'hass:calendar')
await component.async_setup(config)
return True
DEFAULT_CONF_TRACK_NEW = True
DEFAULT_CONF_OFFSET = '!!'
def get_date(date):
"""Get the dateTime from date or dateTime as a local."""
if 'date' in date:
return dt.start_of_local_day(dt.dt.datetime.combine(
dt.parse_date(date['date']), dt.dt.time.min))
return dt.as_local(dt.parse_datetime(date['dateTime']))
class CalendarEventDevice(Entity):
"""A calendar event device."""
# Classes overloading this must set data to an object
# with an update() method
data = None
def __init__(self, hass, data):
"""Create the Calendar Event Device."""
self._name = data.get(CONF_NAME)
self.dev_id = data.get(CONF_DEVICE_ID)
self._offset = data.get(CONF_OFFSET, DEFAULT_CONF_OFFSET)
self.entity_id = generate_entity_id(
ENTITY_ID_FORMAT, self.dev_id, hass=hass)
self._cal_data = {
'all_day': False,
'offset_time': dt.dt.timedelta(),
'message': '',
'start': None,
'end': None,
'location': '',
'description': '',
}
self.update()
def offset_reached(self):
"""Have we reached the offset time specified in the event title."""
if self._cal_data['start'] is None or \
self._cal_data['offset_time'] == dt.dt.timedelta():
return False
return self._cal_data['start'] + self._cal_data['offset_time'] <= \
dt.now(self._cal_data['start'].tzinfo)
@property
def name(self):
"""Return the name of the entity."""
return self._name
@property
def device_state_attributes(self):
"""Return the device state attributes."""
start = self._cal_data.get('start', None)
end = self._cal_data.get('end', None)
start = start.strftime(DATE_STR_FORMAT) if start is not None else None
end = end.strftime(DATE_STR_FORMAT) if end is not None else None
return {
'message': self._cal_data.get('message', ''),
'all_day': self._cal_data.get('all_day', False),
'offset_reached': self.offset_reached(),
'start_time': start,
'end_time': end,
'location': self._cal_data.get('location', None),
'description': self._cal_data.get('description', None),
}
@property
def state(self):
"""Return the state of the calendar event."""
start = self._cal_data.get('start', None)
end = self._cal_data.get('end', None)
if start is None or end is None:
return STATE_OFF
now = dt.now()
if start <= now < end:
return STATE_ON
if now >= end:
self.cleanup()
return STATE_OFF
def cleanup(self):
"""Cleanup any start/end listeners that were setup."""
self._cal_data = {
'all_day': False,
'offset_time': 0,
'message': '',
'start': None,
'end': None,
'location': None,
'description': None
}
def update(self):
"""Search for the next event."""
if not self.data or not self.data.update():
# update cached, don't do anything
return
if not self.data.event:
# we have no event to work on, make sure we're clean
self.cleanup()
return
start = get_date(self.data.event['start'])
end = get_date(self.data.event['end'])
summary = self.data.event.get('summary', '')
# check if we have an offset tag in the message
# time is HH:MM or MM
reg = '{}([+-]?[0-9]{{0,2}}(:[0-9]{{0,2}})?)'.format(self._offset)
search = re.search(reg, summary)
if search and search.group(1):
time = search.group(1)
if ':' not in time:
if time[0] == '+' or time[0] == '-':
time = '{}0:{}'.format(time[0], time[1:])
else:
time = '0:{}'.format(time)
offset_time = time_period_str(time)
summary = (summary[:search.start()] + summary[search.end():]) \
.strip()
else:
offset_time = dt.dt.timedelta() # default it
# cleanup the string so we don't have a bunch of double+ spaces
self._cal_data['message'] = re.sub(' +', '', summary).strip()
self._cal_data['offset_time'] = offset_time
self._cal_data['location'] = self.data.event.get('location', '')
self._cal_data['description'] = self.data.event.get('description', '')
self._cal_data['start'] = start
self._cal_data['end'] = end
self._cal_data['all_day'] = 'date' in self.data.event['start']
class CalendarEventView(http.HomeAssistantView):
"""View to retrieve calendar content."""
url = '/api/calendars/{entity_id}'
name = 'api:calendars:calendar'
def __init__(self, component):
"""Initialize calendar view."""
self.component = component
async def get(self, request, entity_id):
"""Return calendar events."""
entity = self.component.get_entity(entity_id)
start = request.query.get('start')
end = request.query.get('end')
if None in (start, end, entity):
return web.Response(status=400)
try:
start_date = dt.parse_datetime(start)
end_date = dt.parse_datetime(end)
except (ValueError, AttributeError):
return web.Response(status=400)
event_list = await entity.async_get_events(
request.app['hass'], start_date, end_date)
return self.json(event_list)
class CalendarListView(http.HomeAssistantView):
"""View to retrieve calendar list."""
url = '/api/calendars'
name = "api:calendars"
def __init__(self, component):
"""Initialize calendar view."""
self.component = component
async def get(self, request):
"""Retrieve calendar list."""
get_state = request.app['hass'].states.get
calendar_list = []
for entity in self.component.entities:
state = get_state(entity.entity_id)
calendar_list.append({
"name": state.name,
"entity_id": entity.entity_id,
})
return self.json(sorted(calendar_list, key=lambda x: x['name']))
|
iver333/phantomjs | refs/heads/master | src/qt/qtwebkit/Tools/Scripts/webkitpy/tool/commands/queries_unittest.py | 121 | # Copyright (C) 2009 Google Inc. All rights reserved.
# Copyright (C) 2012 Intel Corporation. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import unittest2 as unittest
from webkitpy.common.system.outputcapture import OutputCapture
from webkitpy.common.net.bugzilla import Bugzilla
from webkitpy.common.system.outputcapture import OutputCapture
from webkitpy.thirdparty.mock import Mock
from webkitpy.port.test import TestPort
from webkitpy.tool.commands.commandtest import CommandsTest
from webkitpy.tool.commands.queries import *
from webkitpy.tool.mocktool import MockTool, MockOptions
class MockTestPort1(object):
def skips_layout_test(self, test_name):
return test_name in ["media/foo/bar.html", "foo"]
class MockTestPort2(object):
def skips_layout_test(self, test_name):
return test_name == "media/foo/bar.html"
class MockPortFactory(object):
def __init__(self):
self._all_ports = {
"test_port1": MockTestPort1(),
"test_port2": MockTestPort2(),
}
def all_port_names(self, options=None):
return self._all_ports.keys()
def get(self, port_name):
return self._all_ports.get(port_name)
class QueryCommandsTest(CommandsTest):
def test_bugs_to_commit(self):
expected_logs = "Warning, attachment 10001 on bug 50000 has invalid committer ([email protected])\n"
self.assert_execute_outputs(BugsToCommit(), None, "50000\n50003\n", expected_logs=expected_logs)
def test_patches_in_commit_queue(self):
expected_stdout = "http://example.com/10000\nhttp://example.com/10002\n"
expected_logs = "Warning, attachment 10001 on bug 50000 has invalid committer ([email protected])\nPatches in commit queue:\n"
self.assert_execute_outputs(PatchesInCommitQueue(), None, expected_stdout, expected_logs=expected_logs)
def test_patches_to_commit_queue(self):
expected_stdout = "http://example.com/10003&action=edit\n"
expected_logs = "10000 already has cq=+\n10001 already has cq=+\n10004 committer = \"Eric Seidel\" <[email protected]>\n"
options = Mock()
options.bugs = False
self.assert_execute_outputs(PatchesToCommitQueue(), None, expected_stdout, expected_logs=expected_logs, options=options)
expected_stdout = "http://example.com/50003\n"
options.bugs = True
self.assert_execute_outputs(PatchesToCommitQueue(), None, expected_stdout, expected_logs=expected_logs, options=options)
def test_patches_to_review(self):
options = Mock()
# When no cc_email is provided, we use the Bugzilla username by default.
# The MockBugzilla will fake the authentication using [email protected]
# as login and it should match the username at the report header.
options.cc_email = None
options.include_cq_denied = False
options.all = False
expected_stdout = \
"Bugs with attachments pending review that has [email protected] in the CC list:\n" \
"http://webkit.org/b/bugid Description (age in days)\n" \
"Total: 0\n"
expected_stderr = ""
self.assert_execute_outputs(PatchesToReview(), None, expected_stdout, expected_stderr, options=options)
options.cc_email = "[email protected]"
options.include_cq_denied = True
options.all = False
expected_stdout = \
"Bugs with attachments pending review that has [email protected] in the CC list:\n" \
"http://webkit.org/b/bugid Description (age in days)\n" \
"http://webkit.org/b/50001 Bug with a patch needing review. (0)\n" \
"Total: 1\n"
expected_stderr = ""
self.assert_execute_outputs(PatchesToReview(), None, expected_stdout, expected_stderr, options=options)
options.cc_email = None
options.include_cq_denied = True
options.all = True
expected_stdout = \
"Bugs with attachments pending review:\n" \
"http://webkit.org/b/bugid Description (age in days)\n" \
"http://webkit.org/b/50001 Bug with a patch needing review. (0)\n" \
"Total: 1\n"
self.assert_execute_outputs(PatchesToReview(), None, expected_stdout, expected_stderr, options=options)
options.cc_email = None
options.include_cq_denied = False
options.all = True
expected_stdout = \
"Bugs with attachments pending review:\n" \
"http://webkit.org/b/bugid Description (age in days)\n" \
"Total: 0\n"
self.assert_execute_outputs(PatchesToReview(), None, expected_stdout, expected_stderr, options=options)
options.cc_email = "[email protected]"
options.all = False
options.include_cq_denied = True
expected_stdout = \
"Bugs with attachments pending review that has [email protected] in the CC list:\n" \
"http://webkit.org/b/bugid Description (age in days)\n" \
"Total: 0\n"
self.assert_execute_outputs(PatchesToReview(), None, expected_stdout, expected_stderr, options=options)
def test_tree_status(self):
expected_stdout = "ok : Builder1\nok : Builder2\n"
self.assert_execute_outputs(TreeStatus(), None, expected_stdout)
class FailureReasonTest(unittest.TestCase):
def test_blame_line_for_revision(self):
tool = MockTool()
command = FailureReason()
command.bind_to_tool(tool)
# This is an artificial example, mostly to test the CommitInfo lookup failure case.
self.assertEqual(command._blame_line_for_revision(0), "FAILED to fetch CommitInfo for r0, likely missing ChangeLog")
def raising_mock(self):
raise Exception("MESSAGE")
tool.checkout().commit_info_for_revision = raising_mock
self.assertEqual(command._blame_line_for_revision(0), "FAILED to fetch CommitInfo for r0, exception: MESSAGE")
class PrintExpectationsTest(unittest.TestCase):
def run_test(self, tests, expected_stdout, platform='test-win-xp', **args):
options = MockOptions(all=False, csv=False, full=False, platform=platform,
include_keyword=[], exclude_keyword=[], paths=False).update(**args)
tool = MockTool()
tool.port_factory.all_port_names = lambda: TestPort.ALL_BASELINE_VARIANTS
command = PrintExpectations()
command.bind_to_tool(tool)
oc = OutputCapture()
try:
oc.capture_output()
command.execute(options, tests, tool)
finally:
stdout, _, _ = oc.restore_output()
self.assertMultiLineEqual(stdout, expected_stdout)
def test_basic(self):
self.run_test(['failures/expected/text.html', 'failures/expected/image.html'],
('// For test-win-xp\n'
'failures/expected/image.html [ ImageOnlyFailure ]\n'
'failures/expected/text.html [ Failure ]\n'))
def test_multiple(self):
self.run_test(['failures/expected/text.html', 'failures/expected/image.html'],
('// For test-win-vista\n'
'failures/expected/image.html [ ImageOnlyFailure ]\n'
'failures/expected/text.html [ Failure ]\n'
'\n'
'// For test-win-win7\n'
'failures/expected/image.html [ ImageOnlyFailure ]\n'
'failures/expected/text.html [ Failure ]\n'
'\n'
'// For test-win-xp\n'
'failures/expected/image.html [ ImageOnlyFailure ]\n'
'failures/expected/text.html [ Failure ]\n'),
platform='test-win-*')
def test_full(self):
self.run_test(['failures/expected/text.html', 'failures/expected/image.html'],
('// For test-win-xp\n'
'Bug(test) failures/expected/image.html [ ImageOnlyFailure ]\n'
'Bug(test) failures/expected/text.html [ Failure ]\n'),
full=True)
def test_exclude(self):
self.run_test(['failures/expected/text.html', 'failures/expected/image.html'],
('// For test-win-xp\n'
'failures/expected/text.html [ Failure ]\n'),
exclude_keyword=['image'])
def test_include(self):
self.run_test(['failures/expected/text.html', 'failures/expected/image.html'],
('// For test-win-xp\n'
'failures/expected/image.html\n'),
include_keyword=['image'])
def test_csv(self):
self.run_test(['failures/expected/text.html', 'failures/expected/image.html'],
('test-win-xp,failures/expected/image.html,BUGTEST,IMAGE\n'
'test-win-xp,failures/expected/text.html,BUGTEST,FAIL\n'),
csv=True)
def test_paths(self):
self.run_test([],
('LayoutTests/TestExpectations\n'
'LayoutTests/platform/test/TestExpectations\n'
'LayoutTests/platform/test-win-xp/TestExpectations\n'),
paths=True)
def test_platform(self):
self.run_test(['platform/test-mac-leopard/http/test.html'],
('// For test-mac-snowleopard\n'
'platform/test-mac-leopard [ Pass Skip WontFix ]\n' # Note that this is the expectation (from being skipped internally), not the test name
'\n'
'// For test-mac-leopard\n'
'platform/test-mac-leopard/http/test.html [ Pass ]\n'),
platform='test-mac-*')
class PrintBaselinesTest(unittest.TestCase):
def setUp(self):
self.oc = None
self.tool = MockTool()
self.test_port = self.tool.port_factory.get('test-win-xp')
self.tool.port_factory.get = lambda port_name=None: self.test_port
self.tool.port_factory.all_port_names = lambda: TestPort.ALL_BASELINE_VARIANTS
def tearDown(self):
if self.oc:
self.restore_output()
def capture_output(self):
self.oc = OutputCapture()
self.oc.capture_output()
def restore_output(self):
stdout, stderr, logs = self.oc.restore_output()
self.oc = None
return (stdout, stderr, logs)
def test_basic(self):
command = PrintBaselines()
command.bind_to_tool(self.tool)
self.capture_output()
command.execute(MockOptions(all=False, include_virtual_tests=False, csv=False, platform=None), ['passes/text.html'], self.tool)
stdout, _, _ = self.restore_output()
self.assertMultiLineEqual(stdout,
('// For test-win-xp\n'
'passes/text-expected.png\n'
'passes/text-expected.txt\n'))
def test_multiple(self):
command = PrintBaselines()
command.bind_to_tool(self.tool)
self.capture_output()
command.execute(MockOptions(all=False, include_virtual_tests=False, csv=False, platform='test-win-*'), ['passes/text.html'], self.tool)
stdout, _, _ = self.restore_output()
self.assertMultiLineEqual(stdout,
('// For test-win-vista\n'
'passes/text-expected.png\n'
'passes/text-expected.txt\n'
'\n'
'// For test-win-win7\n'
'passes/text-expected.png\n'
'passes/text-expected.txt\n'
'\n'
'// For test-win-xp\n'
'passes/text-expected.png\n'
'passes/text-expected.txt\n'))
def test_csv(self):
command = PrintBaselines()
command.bind_to_tool(self.tool)
self.capture_output()
command.execute(MockOptions(all=False, platform='*xp', csv=True, include_virtual_tests=False), ['passes/text.html'], self.tool)
stdout, _, _ = self.restore_output()
self.assertMultiLineEqual(stdout,
('test-win-xp,passes/text.html,None,png,passes/text-expected.png,None\n'
'test-win-xp,passes/text.html,None,txt,passes/text-expected.txt,None\n'))
|
alexmoratalla/yambo-py | refs/heads/master | yambopy/dbs/rtdb.py | 1 | # Copyright (c) 2016, Henrique Miranda
# All rights reserved.
#
# This file is part of the yambopy project
#
from yambopy import *
from yambopy.plot import *
ha2ev = 27.211396132
class YamboRTDB():
"""
Open the RT databases and store it in a RTDB class
"""
def __init__(self,folder='.',calc='.',save=None,referencedb='ndb.RT_reference_components',carriersdb='ndb.RT_carriers'):
self.path = '%s/%s/pulse'%(folder,calc)
if save==None:
self.save = '%s/SAVE'%folder
else:
self.save = save
self.referencedb = referencedb
self.carriersdb = carriersdb
#read save for symmetries
try:
filename = '%s/ns.db1'%self.save
database = Dataset(filename)
except:
raise ValueError( "Error reading %s database"%filename )
self.alat = database.variables['LATTICE_PARAMETER'][:].T
self.lat = database.variables['LATTICE_VECTORS'][:].T
self.sym_car = database.variables['SYMMETRY'][:]
dimensions = database.variables['DIMENSIONS'][:]
self.time_rev = dimensions[9]
database.close()
#read reference database
db = Dataset("%s/%s"%(self.path,referencedb))
self.nband_min, self.nband_max, self.nkpoints = db['RT_vars'][:].astype(int)
self.nbands = self.nband_max - self.nband_min + 1
db.close()
#get energies of bands
db = Dataset("%s/%s"%(self.path,carriersdb))
self.eigenvalues = db['RT_carriers_E_bare'][:].reshape([self.nkpoints,self.nbands])*ha2ev
#get kpoints coordinates
self.kpts_iku = db['RT_kpt'][:].T#.reshape([self.nkpoints,3])
db.close()
#get a list of symmetries with time reversal
nsym = len(self.sym_car)
#caclulate the reciprocal lattice
self.rlat = rec_lat(self.lat)
self.nsym = len(self.sym_car)
#convert form internal yambo units to cartesian lattice units
self.kpts_car = np.array([ k/self.alat for k in self.kpts_iku ])
#convert cartesian transformations to reduced transformations
inv = np.linalg.inv
self.sym_rlu = np.zeros([self.nsym,3,3])
for n,s in enumerate(self.sym_car):
a = np.dot(s.T,inv(self.rlat))
self.sym_rlu[n] = np.dot(inv(self.lat.T),a)
#convert cartesian transformations to reciprocal transformations
self.sym_rec = np.zeros([self.nsym,3,3])
for n,s in enumerate(self.sym_car):
self.sym_rec[n] = inv(s).T
#read the databases
self.readDB()
#integrate the occupations
self.integrate()
#status
self.expanded = False
def readDB(self):
"""
"""
#get how many rt databases exist
files = [ filename for filename in os.listdir(self.path) if 'ndb.RT_carriers_Time' in filename]
print "Number of RT carrier files:", len(files)
# sorting
units = {'as':1e-18,'fs':1e-15,'ps':1e-12}
s = []
for filename in files:
for unit in units.keys():
if unit in filename:
factor = units[unit]
s.append((float(re.findall("\d+\.\d+", filename)[0])*factor,filename))
ordered_files=sorted(s)
self.ntimes = len(ordered_files)
#read all of them
self.RT_carriers_delta_f = np.zeros([self.ntimes,self.nkpoints,self.nbands])
#self.RT_carriers_dE_Self_Energy = np.zeros([self.ntimes,self.nbands,self.nkpoints])
#self.RT_carriers_dE_V_xc = np.zeros([self.ntimes,self.nbands,self.nkpoints])
self.times = [ time for time,filename in ordered_files]
for n,(time,filename) in enumerate(ordered_files):
#open database for each k-point
db = Dataset("%s/%s"%(self.path,filename))
self.RT_carriers_delta_f[n] = db['RT_carriers_delta_f'][:].reshape([self.nkpoints,self.nbands])
#self.RT_carriers_dE_Self_Energy[n] = db['RT_carriers_dE_Self_Energy'][:].reshape([self.nkpoints,self.nbands])
#self.RT_carriers_dE_V_xc[n] = db['RT_carriers_dE_V_xc'][:].reshape([self.nbands,self.nkpoints])
#close database
db.close()
def integrate(self):
self.occupations = np.zeros([self.ntimes,self.nkpoints,self.nbands])
for t in xrange(0,self.ntimes):
#"delta_f" is df(t)-df(t0), so total occupation
self.occupations[t] = self.RT_carriers_delta_f[t]
def get_path(self,path,kpts=None):
""" Obtain a list of indexes and kpoints that belong to the regular mesh
"""
if kpts is None:
kpts, nks, nss = self.expand_kpts()
else:
nks = range(len(kpts))
#points in cartesian coordinates
path_car = red_car(path, self.rlat)
#find the points along the high symmetry lines
distance = 0
bands_kpoints = []
bands_indexes = []
#for all the paths
for k in range(len(path)-1):
# store here all the points in the path
# key: has the coordinates of the kpoint rounded to 4 decimal places
# value: index of the kpoint
# distance to the starting kpoint
# the kpoint cordinate
kpoints_in_path = {}
start_kpt = path_car[k] #start point of the path
end_kpt = path_car[k+1] #end point of the path
#generate repetitions of the brillouin zone
for x,y,z in product(range(-1,2),range(-1,2),range(1)):
#shift the brillouin zone
shift = red_car([np.array([x,y,z])],self.rlat)[0]
#iterate over all the kpoints
for index, kpt in zip(nks,kpts):
kpt_shift = kpt+shift #shift the kpoint
#if the point is collinear we add it
if isbetween(start_kpt,end_kpt,kpt_shift):
key = tuple([round(kpt,4) for kpt in kpt_shift])
value = [ index, np.linalg.norm(start_kpt-kpt_shift), kpt_shift ]
kpoints_in_path[key] = value
#sort the points acoording to distance to the start of the path
kpoints_in_path = sorted(kpoints_in_path.values(),key=lambda i: i[1])
#for all the kpoints in the path
for index, disp, kpt in kpoints_in_path:
bands_kpoints.append( kpt )
bands_indexes.append( index )
#print ("%12.8lf "*3)%tuple(kpt), index
self.bands_kpoints = bands_kpoints
self.bands_indexes = bands_indexes
self.bands_highsym_qpts = path_car
print 'Path generated using %d kpoints.'%len(bands_kpoints)
return bands_kpoints, bands_indexes, path_car
def expand_kpts(self):
""" Take a list of qpoints and symmetry operations and return the full brillouin zone
with the corresponding index in the irreducible brillouin zone
"""
#check if the kpoints were already exapnded
if self.expanded == True: return self.kpoints_full, self.kpoints_indexes, self.symmetry_indexes
kpoints_indexes = []
kpoints_full = []
symmetry_indexes = []
#kpoints in the full brillouin zone organized per index
kpoints_full_i = {}
#expand using symmetries
for nk,k in enumerate(self.kpts_car):
for ns,sym in enumerate(self.sym_car):
new_k = np.dot(sym,k)
#check if the point is inside the bounds
k_red = car_red([new_k],self.rlat)[0]
k_bz = (k_red+atol)%1
#if the index in not in the dicitonary add a list
if nk not in kpoints_full_i:
kpoints_full_i[nk] = []
#if the vector is not in the list of this index add it
if not vec_in_list(k_bz,kpoints_full_i[nk]):
kpoints_full_i[nk].append(k_bz)
kpoints_full.append(new_k)
kpoints_indexes.append(nk)
symmetry_indexes.append(ns)
#calculate the weights of each of the kpoints in the irreducible brillouin zone
self.full_nkpoints = len(kpoints_full)
weights = np.zeros([self.nkpoints])
for nk in kpoints_full_i:
weights[nk] = float(len(kpoints_full_i[nk]))/self.full_nkpoints
#set the variables
self.expanded = True
self.weights = np.array(weights)
self.kpoints_full = np.array(kpoints_full)
self.kpoints_indexes = np.array(kpoints_indexes)
self.symmetry_indexes = np.array(symmetry_indexes)
print "%d kpoints expanded to %d"%(len(self.kpts_car),len(kpoints_full))
return self.kpoints_full, self.kpoints_indexes, self.symmetry_indexes
def __str__(self):
s = ""
s += "nkpoints: %d\n"%self.nkpoints
s += "min_band: %d\n"%self.nband_min
s += "max_band: %d\n"%self.nband_max
return s
|
Subsets and Splits