repo_name stringlengths 5 100 | path stringlengths 4 375 | copies stringclasses 991 values | size stringlengths 4 7 | content stringlengths 666 1M | license stringclasses 15 values |
|---|---|---|---|---|---|
objarni/splinter | splinter/driver/webdriver/firefox.py | 7 | 1689 | # -*- coding: utf-8 -*-
# Copyright 2012 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
from selenium.webdriver import Firefox
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
from splinter.driver.webdriver import (
BaseWebDriver, WebDriverElement as WebDriverElement)
from splinter.driver.webdriver.cookie_manager import CookieManager
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
class WebDriver(BaseWebDriver):
driver_name = "Firefox"
def __init__(self, profile=None, extensions=None, user_agent=None,
profile_preferences=None, fullscreen=False, wait_time=2):
firefox_profile = FirefoxProfile(profile)
firefox_profile.set_preference('extensions.logging.enabled', False)
firefox_profile.set_preference('network.dns.disableIPv6', False)
if user_agent is not None:
firefox_profile.set_preference(
'general.useragent.override', user_agent)
if profile_preferences:
for key, value in profile_preferences.items():
firefox_profile.set_preference(key, value)
if extensions:
for extension in extensions:
firefox_profile.add_extension(extension)
self.driver = Firefox(firefox_profile)
if fullscreen:
ActionChains(self.driver).send_keys(Keys.F11).perform()
self.element_class = WebDriverElement
self._cookie_manager = CookieManager(self.driver)
super(WebDriver, self).__init__(wait_time)
| bsd-3-clause |
kaiweifan/horizon | openstack_dashboard/openstack/common/rpc/impl_zmq.py | 19 | 27330 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 Cloudscaling Group, 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 os
import pprint
import re
import socket
import sys
import types
import uuid
import eventlet
import greenlet
from oslo.config import cfg
from openstack_dashboard.openstack.common import excutils
from openstack_dashboard.openstack.common.gettextutils import _
from openstack_dashboard.openstack.common import importutils
from openstack_dashboard.openstack.common import jsonutils
from openstack_dashboard.openstack.common.rpc import common as rpc_common
zmq = importutils.try_import('eventlet.green.zmq')
# for convenience, are not modified.
pformat = pprint.pformat
Timeout = eventlet.timeout.Timeout
LOG = rpc_common.LOG
RemoteError = rpc_common.RemoteError
RPCException = rpc_common.RPCException
zmq_opts = [
cfg.StrOpt('rpc_zmq_bind_address', default='*',
help='ZeroMQ bind address. Should be a wildcard (*), '
'an ethernet interface, or IP. '
'The "host" option should point or resolve to this '
'address.'),
# The module.Class to use for matchmaking.
cfg.StrOpt(
'rpc_zmq_matchmaker',
default=('openstack_dashboard.openstack.common.rpc.'
'matchmaker.MatchMakerLocalhost'),
help='MatchMaker driver',
),
# The following port is unassigned by IANA as of 2012-05-21
cfg.IntOpt('rpc_zmq_port', default=9501,
help='ZeroMQ receiver listening port'),
cfg.IntOpt('rpc_zmq_contexts', default=1,
help='Number of ZeroMQ contexts, defaults to 1'),
cfg.IntOpt('rpc_zmq_topic_backlog', default=None,
help='Maximum number of ingress messages to locally buffer '
'per topic. Default is unlimited.'),
cfg.StrOpt('rpc_zmq_ipc_dir', default='/var/run/openstack',
help='Directory for holding IPC sockets'),
cfg.StrOpt('rpc_zmq_host', default=socket.gethostname(),
help='Name of this node. Must be a valid hostname, FQDN, or '
'IP address. Must match "host" option, if running Nova.')
]
CONF = cfg.CONF
CONF.register_opts(zmq_opts)
ZMQ_CTX = None # ZeroMQ Context, must be global.
matchmaker = None # memoized matchmaker object
def _serialize(data):
"""
Serialization wrapper
We prefer using JSON, but it cannot encode all types.
Error if a developer passes us bad data.
"""
try:
return jsonutils.dumps(data, ensure_ascii=True)
except TypeError:
with excutils.save_and_reraise_exception():
LOG.error(_("JSON serialization failed."))
def _deserialize(data):
"""
Deserialization wrapper
"""
LOG.debug(_("Deserializing: %s"), data)
return jsonutils.loads(data)
class ZmqSocket(object):
"""
A tiny wrapper around ZeroMQ to simplify the send/recv protocol
and connection management.
Can be used as a Context (supports the 'with' statement).
"""
def __init__(self, addr, zmq_type, bind=True, subscribe=None):
self.sock = _get_ctxt().socket(zmq_type)
self.addr = addr
self.type = zmq_type
self.subscriptions = []
# Support failures on sending/receiving on wrong socket type.
self.can_recv = zmq_type in (zmq.PULL, zmq.SUB)
self.can_send = zmq_type in (zmq.PUSH, zmq.PUB)
self.can_sub = zmq_type in (zmq.SUB, )
# Support list, str, & None for subscribe arg (cast to list)
do_sub = {
list: subscribe,
str: [subscribe],
type(None): []
}[type(subscribe)]
for f in do_sub:
self.subscribe(f)
str_data = {'addr': addr, 'type': self.socket_s(),
'subscribe': subscribe, 'bind': bind}
LOG.debug(_("Connecting to %(addr)s with %(type)s"), str_data)
LOG.debug(_("-> Subscribed to %(subscribe)s"), str_data)
LOG.debug(_("-> bind: %(bind)s"), str_data)
try:
if bind:
self.sock.bind(addr)
else:
self.sock.connect(addr)
except Exception:
raise RPCException(_("Could not open socket."))
def socket_s(self):
"""Get socket type as string."""
t_enum = ('PUSH', 'PULL', 'PUB', 'SUB', 'REP', 'REQ', 'ROUTER',
'DEALER')
return dict(map(lambda t: (getattr(zmq, t), t), t_enum))[self.type]
def subscribe(self, msg_filter):
"""Subscribe."""
if not self.can_sub:
raise RPCException("Cannot subscribe on this socket.")
LOG.debug(_("Subscribing to %s"), msg_filter)
try:
self.sock.setsockopt(zmq.SUBSCRIBE, msg_filter)
except Exception:
return
self.subscriptions.append(msg_filter)
def unsubscribe(self, msg_filter):
"""Unsubscribe."""
if msg_filter not in self.subscriptions:
return
self.sock.setsockopt(zmq.UNSUBSCRIBE, msg_filter)
self.subscriptions.remove(msg_filter)
def close(self):
if self.sock is None or self.sock.closed:
return
# We must unsubscribe, or we'll leak descriptors.
if self.subscriptions:
for f in self.subscriptions:
try:
self.sock.setsockopt(zmq.UNSUBSCRIBE, f)
except Exception:
pass
self.subscriptions = []
try:
# Default is to linger
self.sock.close()
except Exception:
# While this is a bad thing to happen,
# it would be much worse if some of the code calling this
# were to fail. For now, lets log, and later evaluate
# if we can safely raise here.
LOG.error("ZeroMQ socket could not be closed.")
self.sock = None
def recv(self, **kwargs):
if not self.can_recv:
raise RPCException(_("You cannot recv on this socket."))
return self.sock.recv_multipart(**kwargs)
def send(self, data, **kwargs):
if not self.can_send:
raise RPCException(_("You cannot send on this socket."))
self.sock.send_multipart(data, **kwargs)
class ZmqClient(object):
"""Client for ZMQ sockets."""
def __init__(self, addr, socket_type=None, bind=False):
if socket_type is None:
socket_type = zmq.PUSH
self.outq = ZmqSocket(addr, socket_type, bind=bind)
def cast(self, msg_id, topic, data, envelope=False):
msg_id = msg_id or 0
if not envelope:
self.outq.send(map(bytes,
(msg_id, topic, 'cast', _serialize(data))))
return
rpc_envelope = rpc_common.serialize_msg(data[1], envelope)
zmq_msg = reduce(lambda x, y: x + y, rpc_envelope.items())
self.outq.send(map(bytes,
(msg_id, topic, 'impl_zmq_v2', data[0]) + zmq_msg))
def close(self):
self.outq.close()
class RpcContext(rpc_common.CommonRpcContext):
"""Context that supports replying to a rpc.call."""
def __init__(self, **kwargs):
self.replies = []
super(RpcContext, self).__init__(**kwargs)
def deepcopy(self):
values = self.to_dict()
values['replies'] = self.replies
return self.__class__(**values)
def reply(self, reply=None, failure=None, ending=False):
if ending:
return
self.replies.append(reply)
@classmethod
def marshal(self, ctx):
ctx_data = ctx.to_dict()
return _serialize(ctx_data)
@classmethod
def unmarshal(self, data):
return RpcContext.from_dict(_deserialize(data))
class InternalContext(object):
"""Used by ConsumerBase as a private context for - methods."""
def __init__(self, proxy):
self.proxy = proxy
self.msg_waiter = None
def _get_response(self, ctx, proxy, topic, data):
"""Process a curried message and cast the result to topic."""
LOG.debug(_("Running func with context: %s"), ctx.to_dict())
data.setdefault('version', None)
data.setdefault('args', {})
try:
result = proxy.dispatch(
ctx, data['version'], data['method'],
data.get('namespace'), **data['args'])
return ConsumerBase.normalize_reply(result, ctx.replies)
except greenlet.GreenletExit:
# ignore these since they are just from shutdowns
pass
except rpc_common.ClientException as e:
LOG.debug(_("Expected exception during message handling (%s)") %
e._exc_info[1])
return {'exc':
rpc_common.serialize_remote_exception(e._exc_info,
log_failure=False)}
except Exception:
LOG.error(_("Exception during message handling"))
return {'exc':
rpc_common.serialize_remote_exception(sys.exc_info())}
def reply(self, ctx, proxy,
msg_id=None, context=None, topic=None, msg=None):
"""Reply to a casted call."""
# NOTE(ewindisch): context kwarg exists for Grizzly compat.
# this may be able to be removed earlier than
# 'I' if ConsumerBase.process were refactored.
if type(msg) is list:
payload = msg[-1]
else:
payload = msg
response = ConsumerBase.normalize_reply(
self._get_response(ctx, proxy, topic, payload),
ctx.replies)
LOG.debug(_("Sending reply"))
_multi_send(_cast, ctx, topic, {
'method': '-process_reply',
'args': {
'msg_id': msg_id, # Include for Folsom compat.
'response': response
}
}, _msg_id=msg_id)
class ConsumerBase(object):
"""Base Consumer."""
def __init__(self):
self.private_ctx = InternalContext(None)
@classmethod
def normalize_reply(self, result, replies):
#TODO(ewindisch): re-evaluate and document this method.
if isinstance(result, types.GeneratorType):
return list(result)
elif replies:
return replies
else:
return [result]
def process(self, proxy, ctx, data):
data.setdefault('version', None)
data.setdefault('args', {})
# Method starting with - are
# processed internally. (non-valid method name)
method = data.get('method')
if not method:
LOG.error(_("RPC message did not include method."))
return
# Internal method
# uses internal context for safety.
if method == '-reply':
self.private_ctx.reply(ctx, proxy, **data['args'])
return
proxy.dispatch(ctx, data['version'],
data['method'], data.get('namespace'), **data['args'])
class ZmqBaseReactor(ConsumerBase):
"""
A consumer class implementing a
centralized casting broker (PULL-PUSH)
for RoundRobin requests.
"""
def __init__(self, conf):
super(ZmqBaseReactor, self).__init__()
self.mapping = {}
self.proxies = {}
self.threads = []
self.sockets = []
self.subscribe = {}
self.pool = eventlet.greenpool.GreenPool(conf.rpc_thread_pool_size)
def register(self, proxy, in_addr, zmq_type_in, out_addr=None,
zmq_type_out=None, in_bind=True, out_bind=True,
subscribe=None):
LOG.info(_("Registering reactor"))
if zmq_type_in not in (zmq.PULL, zmq.SUB):
raise RPCException("Bad input socktype")
# Items push in.
inq = ZmqSocket(in_addr, zmq_type_in, bind=in_bind,
subscribe=subscribe)
self.proxies[inq] = proxy
self.sockets.append(inq)
LOG.info(_("In reactor registered"))
if not out_addr:
return
if zmq_type_out not in (zmq.PUSH, zmq.PUB):
raise RPCException("Bad output socktype")
# Items push out.
outq = ZmqSocket(out_addr, zmq_type_out, bind=out_bind)
self.mapping[inq] = outq
self.mapping[outq] = inq
self.sockets.append(outq)
LOG.info(_("Out reactor registered"))
def consume_in_thread(self):
def _consume(sock):
LOG.info(_("Consuming socket"))
while True:
self.consume(sock)
for k in self.proxies.keys():
self.threads.append(
self.pool.spawn(_consume, k)
)
def wait(self):
for t in self.threads:
t.wait()
def close(self):
for s in self.sockets:
s.close()
for t in self.threads:
t.kill()
class ZmqProxy(ZmqBaseReactor):
"""
A consumer class implementing a
topic-based proxy, forwarding to
IPC sockets.
"""
def __init__(self, conf):
super(ZmqProxy, self).__init__(conf)
pathsep = set((os.path.sep or '', os.path.altsep or '', '/', '\\'))
self.badchars = re.compile(r'[%s]' % re.escape(''.join(pathsep)))
self.topic_proxy = {}
def consume(self, sock):
ipc_dir = CONF.rpc_zmq_ipc_dir
data = sock.recv(copy=False)
topic = data[1].bytes
if topic.startswith('fanout~'):
sock_type = zmq.PUB
topic = topic.split('.', 1)[0]
elif topic.startswith('zmq_replies'):
sock_type = zmq.PUB
else:
sock_type = zmq.PUSH
if topic not in self.topic_proxy:
def publisher(waiter):
LOG.info(_("Creating proxy for topic: %s"), topic)
try:
# The topic is received over the network,
# don't trust this input.
if self.badchars.search(topic) is not None:
emsg = _("Topic contained dangerous characters.")
LOG.warn(emsg)
raise RPCException(emsg)
out_sock = ZmqSocket("ipc://%s/zmq_topic_%s" %
(ipc_dir, topic),
sock_type, bind=True)
except RPCException:
waiter.send_exception(*sys.exc_info())
return
self.topic_proxy[topic] = eventlet.queue.LightQueue(
CONF.rpc_zmq_topic_backlog)
self.sockets.append(out_sock)
# It takes some time for a pub socket to open,
# before we can have any faith in doing a send() to it.
if sock_type == zmq.PUB:
eventlet.sleep(.5)
waiter.send(True)
while(True):
data = self.topic_proxy[topic].get()
out_sock.send(data, copy=False)
wait_sock_creation = eventlet.event.Event()
eventlet.spawn(publisher, wait_sock_creation)
try:
wait_sock_creation.wait()
except RPCException:
LOG.error(_("Topic socket file creation failed."))
return
try:
self.topic_proxy[topic].put_nowait(data)
except eventlet.queue.Full:
LOG.error(_("Local per-topic backlog buffer full for topic "
"%(topic)s. Dropping message.") % {'topic': topic})
def consume_in_thread(self):
"""Runs the ZmqProxy service."""
ipc_dir = CONF.rpc_zmq_ipc_dir
consume_in = "tcp://%s:%s" % \
(CONF.rpc_zmq_bind_address,
CONF.rpc_zmq_port)
consumption_proxy = InternalContext(None)
try:
os.makedirs(ipc_dir)
except os.error:
if not os.path.isdir(ipc_dir):
with excutils.save_and_reraise_exception():
LOG.error(_("Required IPC directory does not exist at"
" %s") % (ipc_dir, ))
try:
self.register(consumption_proxy,
consume_in,
zmq.PULL,
out_bind=True)
except zmq.ZMQError:
if os.access(ipc_dir, os.X_OK):
with excutils.save_and_reraise_exception():
LOG.error(_("Permission denied to IPC directory at"
" %s") % (ipc_dir, ))
with excutils.save_and_reraise_exception():
LOG.error(_("Could not create ZeroMQ receiver daemon. "
"Socket may already be in use."))
super(ZmqProxy, self).consume_in_thread()
def unflatten_envelope(packenv):
"""Unflattens the RPC envelope.
Takes a list and returns a dictionary.
i.e. [1,2,3,4] => {1: 2, 3: 4}
"""
i = iter(packenv)
h = {}
try:
while True:
k = i.next()
h[k] = i.next()
except StopIteration:
return h
class ZmqReactor(ZmqBaseReactor):
"""
A consumer class implementing a
consumer for messages. Can also be
used as a 1:1 proxy
"""
def __init__(self, conf):
super(ZmqReactor, self).__init__(conf)
def consume(self, sock):
#TODO(ewindisch): use zero-copy (i.e. references, not copying)
data = sock.recv()
LOG.debug(_("CONSUMER RECEIVED DATA: %s"), data)
if sock in self.mapping:
LOG.debug(_("ROUTER RELAY-OUT %(data)s") % {
'data': data})
self.mapping[sock].send(data)
return
proxy = self.proxies[sock]
if data[2] == 'cast': # Legacy protocol
packenv = data[3]
ctx, msg = _deserialize(packenv)
request = rpc_common.deserialize_msg(msg)
ctx = RpcContext.unmarshal(ctx)
elif data[2] == 'impl_zmq_v2':
packenv = data[4:]
msg = unflatten_envelope(packenv)
request = rpc_common.deserialize_msg(msg)
# Unmarshal only after verifying the message.
ctx = RpcContext.unmarshal(data[3])
else:
LOG.error(_("ZMQ Envelope version unsupported or unknown."))
return
self.pool.spawn_n(self.process, proxy, ctx, request)
class Connection(rpc_common.Connection):
"""Manages connections and threads."""
def __init__(self, conf):
self.topics = []
self.reactor = ZmqReactor(conf)
def create_consumer(self, topic, proxy, fanout=False):
# Register with matchmaker.
_get_matchmaker().register(topic, CONF.rpc_zmq_host)
# Subscription scenarios
if fanout:
sock_type = zmq.SUB
subscribe = ('', fanout)[type(fanout) == str]
topic = 'fanout~' + topic.split('.', 1)[0]
else:
sock_type = zmq.PULL
subscribe = None
topic = '.'.join((topic.split('.', 1)[0], CONF.rpc_zmq_host))
if topic in self.topics:
LOG.info(_("Skipping topic registration. Already registered."))
return
# Receive messages from (local) proxy
inaddr = "ipc://%s/zmq_topic_%s" % \
(CONF.rpc_zmq_ipc_dir, topic)
LOG.debug(_("Consumer is a zmq.%s"),
['PULL', 'SUB'][sock_type == zmq.SUB])
self.reactor.register(proxy, inaddr, sock_type,
subscribe=subscribe, in_bind=False)
self.topics.append(topic)
def close(self):
_get_matchmaker().stop_heartbeat()
for topic in self.topics:
_get_matchmaker().unregister(topic, CONF.rpc_zmq_host)
self.reactor.close()
self.topics = []
def wait(self):
self.reactor.wait()
def consume_in_thread(self):
_get_matchmaker().start_heartbeat()
self.reactor.consume_in_thread()
def _cast(addr, context, topic, msg, timeout=None, envelope=False,
_msg_id=None):
timeout_cast = timeout or CONF.rpc_cast_timeout
payload = [RpcContext.marshal(context), msg]
with Timeout(timeout_cast, exception=rpc_common.Timeout):
try:
conn = ZmqClient(addr)
# assumes cast can't return an exception
conn.cast(_msg_id, topic, payload, envelope)
except zmq.ZMQError:
raise RPCException("Cast failed. ZMQ Socket Exception")
finally:
if 'conn' in vars():
conn.close()
def _call(addr, context, topic, msg, timeout=None,
envelope=False):
# timeout_response is how long we wait for a response
timeout = timeout or CONF.rpc_response_timeout
# The msg_id is used to track replies.
msg_id = uuid.uuid4().hex
# Replies always come into the reply service.
reply_topic = "zmq_replies.%s" % CONF.rpc_zmq_host
LOG.debug(_("Creating payload"))
# Curry the original request into a reply method.
mcontext = RpcContext.marshal(context)
payload = {
'method': '-reply',
'args': {
'msg_id': msg_id,
'topic': reply_topic,
# TODO(ewindisch): safe to remove mcontext in I.
'msg': [mcontext, msg]
}
}
LOG.debug(_("Creating queue socket for reply waiter"))
# Messages arriving async.
# TODO(ewindisch): have reply consumer with dynamic subscription mgmt
with Timeout(timeout, exception=rpc_common.Timeout):
try:
msg_waiter = ZmqSocket(
"ipc://%s/zmq_topic_zmq_replies.%s" %
(CONF.rpc_zmq_ipc_dir,
CONF.rpc_zmq_host),
zmq.SUB, subscribe=msg_id, bind=False
)
LOG.debug(_("Sending cast"))
_cast(addr, context, topic, payload, envelope)
LOG.debug(_("Cast sent; Waiting reply"))
# Blocks until receives reply
msg = msg_waiter.recv()
LOG.debug(_("Received message: %s"), msg)
LOG.debug(_("Unpacking response"))
if msg[2] == 'cast': # Legacy version
raw_msg = _deserialize(msg[-1])[-1]
elif msg[2] == 'impl_zmq_v2':
rpc_envelope = unflatten_envelope(msg[4:])
raw_msg = rpc_common.deserialize_msg(rpc_envelope)
else:
raise rpc_common.UnsupportedRpcEnvelopeVersion(
_("Unsupported or unknown ZMQ envelope returned."))
responses = raw_msg['args']['response']
# ZMQError trumps the Timeout error.
except zmq.ZMQError:
raise RPCException("ZMQ Socket Error")
except (IndexError, KeyError):
raise RPCException(_("RPC Message Invalid."))
finally:
if 'msg_waiter' in vars():
msg_waiter.close()
# It seems we don't need to do all of the following,
# but perhaps it would be useful for multicall?
# One effect of this is that we're checking all
# responses for Exceptions.
for resp in responses:
if isinstance(resp, types.DictType) and 'exc' in resp:
raise rpc_common.deserialize_remote_exception(CONF, resp['exc'])
return responses[-1]
def _multi_send(method, context, topic, msg, timeout=None,
envelope=False, _msg_id=None):
"""
Wraps the sending of messages,
dispatches to the matchmaker and sends
message to all relevant hosts.
"""
conf = CONF
LOG.debug(_("%(msg)s") % {'msg': ' '.join(map(pformat, (topic, msg)))})
queues = _get_matchmaker().queues(topic)
LOG.debug(_("Sending message(s) to: %s"), queues)
# Don't stack if we have no matchmaker results
if not queues:
LOG.warn(_("No matchmaker results. Not casting."))
# While not strictly a timeout, callers know how to handle
# this exception and a timeout isn't too big a lie.
raise rpc_common.Timeout(_("No match from matchmaker."))
# This supports brokerless fanout (addresses > 1)
for queue in queues:
(_topic, ip_addr) = queue
_addr = "tcp://%s:%s" % (ip_addr, conf.rpc_zmq_port)
if method.__name__ == '_cast':
eventlet.spawn_n(method, _addr, context,
_topic, msg, timeout, envelope,
_msg_id)
return
return method(_addr, context, _topic, msg, timeout,
envelope)
def create_connection(conf, new=True):
return Connection(conf)
def multicall(conf, *args, **kwargs):
"""Multiple calls."""
return _multi_send(_call, *args, **kwargs)
def call(conf, *args, **kwargs):
"""Send a message, expect a response."""
data = _multi_send(_call, *args, **kwargs)
return data[-1]
def cast(conf, *args, **kwargs):
"""Send a message expecting no reply."""
_multi_send(_cast, *args, **kwargs)
def fanout_cast(conf, context, topic, msg, **kwargs):
"""Send a message to all listening and expect no reply."""
# NOTE(ewindisch): fanout~ is used because it avoid splitting on .
# and acts as a non-subtle hint to the matchmaker and ZmqProxy.
_multi_send(_cast, context, 'fanout~' + str(topic), msg, **kwargs)
def notify(conf, context, topic, msg, envelope):
"""
Send notification event.
Notifications are sent to topic-priority.
This differs from the AMQP drivers which send to topic.priority.
"""
# NOTE(ewindisch): dot-priority in rpc notifier does not
# work with our assumptions.
topic = topic.replace('.', '-')
cast(conf, context, topic, msg, envelope=envelope)
def cleanup():
"""Clean up resources in use by implementation."""
global ZMQ_CTX
if ZMQ_CTX:
ZMQ_CTX.term()
ZMQ_CTX = None
global matchmaker
matchmaker = None
def _get_ctxt():
if not zmq:
raise ImportError("Failed to import eventlet.green.zmq")
global ZMQ_CTX
if not ZMQ_CTX:
ZMQ_CTX = zmq.Context(CONF.rpc_zmq_contexts)
return ZMQ_CTX
def _get_matchmaker(*args, **kwargs):
global matchmaker
if not matchmaker:
mm = CONF.rpc_zmq_matchmaker
if mm.endswith('matchmaker.MatchMakerRing'):
mm.replace('matchmaker', 'matchmaker_ring')
LOG.warn(_('rpc_zmq_matchmaker = %(orig)s is deprecated; use'
' %(new)s instead') % dict(
orig=CONF.rpc_zmq_matchmaker, new=mm))
matchmaker = importutils.import_object(mm, *args, **kwargs)
return matchmaker
| apache-2.0 |
refnode/django-material | tests/urls.py | 10 | 2701 | from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.views import generic
from django.shortcuts import render
from formtools.wizard.views import SessionWizardView
from material.frontend import urls as frontend_urls
from . import forms
def index_view(request):
context = {
'login': forms.LoginForm(),
'registration': forms.RegistrationForm(),
'checkout': forms.CheckoutForm(),
'order': forms.OrderForm(),
'comment': forms.CommentForm(),
'bank': forms.BankForm()
}
return render(request, 'index.html', context)
class Wizard(SessionWizardView):
form_list = [forms.WizardForm1, forms.WizardForm2]
def done(self, form_list, **kwargs):
return render(self.request, 'formtools/wizard/wizard_done.html', {
'form_data': [form.cleaned_data for form in form_list],
})
urlpatterns = [
url(r'^$', index_view),
# demo
url(r'^demo/login/$', generic.FormView.as_view(
form_class=forms.LoginForm, success_url='/demo/login/', template_name="demo.html")),
url(r'^demo/registration/$', generic.FormView.as_view(
form_class=forms.RegistrationForm, success_url='/demo/registration/', template_name="demo.html")),
url(r'^demo/contact/$', generic.FormView.as_view(
form_class=forms.ContactForm, success_url='/demo/contact/', template_name="demo.html")),
url(r'^demo/order/$', generic.FormView.as_view(
form_class=forms.OrderForm, success_url='/demo/order/', template_name="demo.html")),
url(r'^demo/checkout/$', generic.FormView.as_view(
form_class=forms.CheckoutForm, success_url='/demo/checkout/', template_name="demo.html")),
url(r'^demo/comment/$', generic.FormView.as_view(
form_class=forms.CommentForm, success_url='/demo/comment/', template_name="demo.html")),
url(r'^demo/bank/$', generic.FormView.as_view(
form_class=forms.BankForm, success_url='/demo/bank/', template_name="demo.html")),
url(r'^demo/wizard/$', Wizard.as_view()),
url(r'^demo/hospital/$', generic.FormView.as_view(
form_class=forms.HospitalRegistrationForm, success_url='/demo/hospital/', template_name="demo.html")),
url(r'^foundation/basic/', generic.RedirectView.as_view(url='/?cache=no', permanent=False)),
# admin
url(r'^admin/', include(admin.site.urls)),
# frontend
url(r'^frontend/$', generic.RedirectView.as_view(url='/frontend/accounting/', permanent=False), name="index"),
url(r'', include(frontend_urls)),
]
if 'zinnia' in settings.INSTALLED_APPS:
urlpatterns += [url(r'^weblog/', include('zinnia.urls', namespace='zinnia'))]
| bsd-3-clause |
baloo/shinken | shinken/modules/nagios_retention_file_scheduler.py | 1 | 14015 | #!/usr/bin/python
#Copyright (C) 2009 Gabes Jean, naparuba@gmail.com
#
#This file is part of Shinken.
#
#Shinken is free software: you can redistribute it and/or modify
#it under the terms of the GNU Affero General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#
#Shinken is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU Affero General Public License for more details.
#
#You should have received a copy of the GNU Affero General Public License
#along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#This Class is an example of an Scheduler module
#Here for the configuration phase AND running one
import re
from shinken.objects import Timeperiod, Timeperiods
from shinken.objects import Service, Services
from shinken.objects import Host, Hosts
from shinken.objects import Contact, Contacts
from shinken.comment import Comment
from shinken.downtime import Downtime
from shinken.basemodule import BaseModule
from shinken.util import to_bool
from shinken.log import logger
properties = {
'daemons' : ['scheduler'],
'type' : 'nagios_retention_file',
'external' : False,
}
#called by the plugin manager to get a broker
def get_instance(plugin):
print "Get a Nagios3 retention scheduler module for plugin %s" % plugin.get_name()
path = plugin.path
instance = Nagios_retention_scheduler(plugin, path)
return instance
#Just print some stuff
class Nagios_retention_scheduler(BaseModule):
def __init__(self, mod_conf, path):
BaseModule.__init__(self, mod_conf)
self.path = path
# Ok, main function that is called in the retention creation pass
def hook_save_retention(self, daemon):
logger.log("[NagiosRetention] asking me to update the retention objects, but I won't do it.")
def _cut_line(self, line):
#punct = '"#$%&\'()*+/<=>?@[\\]^`{|}~'
tmp = re.split("=", line)
r = [elt for elt in tmp if elt != '']
return r
def read_retention_buf(self, buf):
params = []
objectscfg = {'void': [],
'timeperiod' : [],
'command' : [],
'contactgroup' : [],
'hostgroup' : [],
'contact' : [],
'notificationway' : [],
'host' : [],
'service' : [],
'servicegroup' : [],
'servicedependency' : [],
'hostdependency' : [],
'hostcomment' : [],
'hostdowntime' : [],
'servicecomment' : [],
'servicedowntime' : [],
}
tmp = []
tmp_type = 'void'
in_define = False
continuation_line = False
tmp_line = ''
lines = buf.split('\n')
for line in lines:
line = line.decode('utf8', 'ignore')
line = line.split(';')[0]
#A backslash means, there is more to come
if re.search("\\\s*$", line):
continuation_line = True
line = re.sub("\\\s*$", "", line)
line = re.sub("^\s+", " ", line)
tmp_line += line
continue
elif continuation_line:
#Now the continuation line is complete
line = re.sub("^\s+", "", line)
line = tmp_line + line
tmp_line = ''
continuation_line = False
if re.search("}", line):
in_define = False
if re.search("^\s*\t*#|^\s*$|^\s*}", line):
pass
#A define must be catch and the type save
#The old entry must be save before
elif re.search("{$", line):
in_define = True
if tmp_type not in objectscfg:
objectscfg[tmp_type] = []
objectscfg[tmp_type].append(tmp)
tmp = []
#Get new type
elts = re.split('\s', line)
tmp_type = elts[0]
# tmp_type = tmp_type.split('{')[0]
# print "TMP type", tmp_type
else:
if in_define:
tmp.append(line)
else:
params.append(line)
objectscfg[tmp_type].append(tmp)
objects = {}
# print "Loaded", objectscfg
for type in objectscfg:
objects[type] = []
for items in objectscfg[type]:
tmp = {}
for line in items:
elts = self._cut_line(line)
if elts != []:
prop = elts[0]
value = ' '.join(elts[1:])
tmp[prop] = value
if tmp != {}:
objects[type].append(tmp)
return objects
#We've got raw objects in string, now create real Instances
def create_objects(self, raw_objects, types_creations):
all_obj = {}
for t in types_creations:
all_obj[t] = self.create_objects_for_type(raw_objects, t, types_creations)
return all_obj
def pythonize_running(self, obj, obj_cfg):
cls = obj.__class__
running_properties = cls.running_properties
for prop, entry in running_properties.items():
if hasattr(obj, prop) and prop in obj_cfg:
# if 'pythonize' in entry:
f = entry.pythonize
if f is not None: # mean it's a string
#print "Apply", f, "to the property", prop, "for ", cls.my_type
val = getattr(obj, prop)
val = f(val)
setattr(obj, prop, val)
else: #no pythonize, int by default
# if cls.my_type != 'service':
# print "Intify", prop, getattr(obj, prop)
if prop != 'state_type':
val = int(getattr(obj, prop))
setattr(obj, prop, val)
else:#state type is a int, but should be set HARd or SOFT
val = int(getattr(obj, prop))
if val == 1:
setattr(obj, prop, 'HARD')
else:
setattr(obj, prop, 'SOFT')
def create_objects_for_type(self, raw_objects, type, types_creations):
t = type
#Ex: the above code do for timeperiods:
#timeperiods = []
#for timeperiodcfg in objects['timeperiod']:
# t = Timeperiod(timeperiodcfg)
# t.clean()
# timeperiods.append(t)
#self.timeperiods = Timeperiods(timeperiods)
(cls, clss, prop) = types_creations[t]
#List where we put objects
lst = []
for obj_cfg in raw_objects[t]:
#We create the object
#print "Create obj", obj_cfg
o = cls(obj_cfg)
o.clean()
if t in self.property_mapping:
entry = self.property_mapping[t]
for (old, new) in entry:
value = getattr(o, old)
setattr(o, new, value)
delattr(o, old)
obj_cfg[new] = obj_cfg[old]
del obj_cfg[old]
o.pythonize()
self.pythonize_running(o, obj_cfg)
lst.append(o)
#print "Got", lst
#we create the objects Class and we set it in prop
#setattr(self, prop, clss(lst))
#print "Object?", clss(lst)
return clss(lst)
def create_and_link_comments(self, raw_objects, all_obj):
#first service
for obj_cfg in raw_objects['servicecomment']:
#print "Managing", obj_cfg
host_name = obj_cfg['host_name']
service_description = obj_cfg['service_description']
srv = all_obj['service'].find_srv_by_name_and_hostname(host_name, service_description)
#print "Find my service", srv
if srv is not None:
cmd = Comment(srv, to_bool(obj_cfg['persistent']), obj_cfg['author'], obj_cfg['comment_data'], 1, int(obj_cfg['entry_type']), int(obj_cfg['source']), to_bool(obj_cfg['expires']), int(obj_cfg['expire_time']))
#print "Created cmd", cmd
srv.add_comment(cmd)
#then hosts
for obj_cfg in raw_objects['hostcomment']:
#print "Managing", obj_cfg
host_name = obj_cfg['host_name']
hst = all_obj['host'].find_by_name(host_name)
#print "Find my host", hst
if hst is not None:
cmd = Comment(hst, to_bool(obj_cfg['persistent']), obj_cfg['author'], obj_cfg['comment_data'], 1, int(obj_cfg['entry_type']), int(obj_cfg['source']), to_bool(obj_cfg['expires']), int(obj_cfg['expire_time']))
#print "Created cmd", cmd
hst.add_comment(cmd)
def create_and_link_downtimes(self, raw_objects, all_obj):
#first service
for obj_cfg in raw_objects['servicedowntime']:
print "Managing", obj_cfg
host_name = obj_cfg['host_name']
service_description = obj_cfg['service_description']
srv = all_obj['service'].find_srv_by_name_and_hostname(host_name, service_description)
print "Find my service", srv
if srv is not None:
dwn = Downtime(srv, int(obj_cfg['start_time']), int(obj_cfg['end_time']), to_bool(obj_cfg['fixed']), int(obj_cfg['triggered_by']), int(obj_cfg['duration']), obj_cfg['author'], obj_cfg['comment'])
print "Created dwn", dwn
srv.add_downtime(dwn)
#then hosts
for obj_cfg in raw_objects['hostdowntime']:
print "Managing", obj_cfg
host_name = obj_cfg['host_name']
hst = all_obj['host'].find_by_name(host_name)
print "Find my host", hst
if hst is not None:
dwn = Downtime(hst, int(obj_cfg['start_time']), int(obj_cfg['end_time']), to_bool(obj_cfg['fixed']), int(obj_cfg['triggered_by']), int(obj_cfg['duration']), obj_cfg['author'], obj_cfg['comment'])
print "Created dwn", dwn
hst.add_downtime(dwn)
# Should return if it succeed in the retention load or not
def hook_load_retention(self, sched):
log_mgr = logger
print "[NagiosRetention] asking me to load the retention file"
#Now the old flat file way :(
log_mgr.log("[NagiosRetention]Reading from retention_file %s" % self.path)
try:
f = open(self.path)
buf = f.read()
f.close()
except EOFError , exp:
print exp
return False
except ValueError , exp:
print exp
return False
except IOError , exp:
print exp
return False
except IndexError , exp:
s = "WARNING: Sorry, the ressource file is not compatible"
log_mgr.log(s)
return False
except TypeError , exp:
s = "WARNING: Sorry, the ressource file is not compatible"
log_mgr.log(s)
return False
print "Fin read config"
raw_objects = self.read_retention_buf(buf)
print "Fun raw"
types_creations = {'timeperiod' : (Timeperiod, Timeperiods, 'timeperiods'),
'service' : (Service, Services, 'services'),
'host' : (Host, Hosts, 'hosts'),
'contact' : (Contact, Contacts, 'contacts'),
}
self.property_mapping = {
'service' : [('current_attempt', 'attempt'), ('current_state','state_type_id'),
('plugin_output','output'), ('last_check','last_chk'),
('performance_data','perf_data'), ('next_check' , 'next_chk'),
('long_plugin_output', 'long_output'), ('check_execution_time', 'execution_time'),
('check_latency', 'latency')],
'host' : [('current_attempt', 'attempt'), ('current_state','state_type_id'),
('plugin_output','output'), ('last_check','last_chk'),
('performance_data','perf_data'), ('next_check' , 'next_chk'),
('long_plugin_output', 'long_output'), ('check_execution_time', 'execution_time'),
('check_latency', 'latency')],
}
all_obj = self.create_objects(raw_objects, types_creations)
print "Got all obj", all_obj
self.create_and_link_comments(raw_objects, all_obj)
self.create_and_link_downtimes(raw_objects, all_obj)
# Taken from the scheduler code... sorry
all_data = {'hosts' : {}, 'services' : {}}
for h in all_obj['host']:
d = {}
running_properties = h.__class__.running_properties
for prop, entry in running_properties.items():
if entry.retention:
d[prop] = getattr(h, prop)
all_data['hosts'][h.host_name] = d
#Now same for services
for s in all_obj['service']:
d = {}
running_properties = s.__class__.running_properties
for prop, entry in running_properties.items():
if entry.retention:
d[prop] = getattr(s, prop)
all_data['services'][(s.host_name, s.service_description)] = d
# all_data = {'hosts' : {}, 'services' : {}}
sched.restore_retention_data(all_data)
log_mgr.log("[NagiosRetention] OK we've load data from retention file")
return True
| agpl-3.0 |
hspencer77/calyptos | calyptos/plugins/validator/storage.py | 3 | 2489 | from calyptos.plugins.validator.validatorplugin import ValidatorPlugin
class Storage(ValidatorPlugin):
def validate(self):
self.topology = self.environment['default_attributes']['eucalyptus']['topology']
if 'system-properties' in self.environment['default_attributes']['eucalyptus']:
self.systemproperties = self.environment['default_attributes']['eucalyptus']['system-properties']
for name in self.topology['clusters'].keys():
if 'storage-backend' in self.topology['clusters'][name]:
storage_options = ['netapp', 'ceph-rbd', 'threepar']
netapp_properties = [name + '.storage.chapuser', name + '.storage.ncpaths', name + '.storage.scpaths',
name + '.storage.sanhost', name + '.storage.sanpassword', name +
'.storage.sanuser', name + '.storage.vservername']
ceph_properties = [name + '.storage.cephconfigfile', name + '.storage.cephkeyringfile',
name + '.storage.cephsnapshotpools', name + '.storage.cephuser',
name + '.storage.cephvolumepools']
threepar_properties = [name + '.storage.chapuser', name + '.storage.ncpaths', name + '.storage.sanhost',
name + '.storage.sanuser', name + '.storage.sanpassword', name +
'.storage.scpaths', name + '.storage.threeparwsport', name + '.storage.usercpg',
name + '.storage.copycpg']
for val1 in storage_options:
if val1 in self.topology['clusters'][name]['storage-backend']:
if val1 == "netapp":
storage_properties = netapp_properties
if val1 == "ceph-rbd":
storage_properties = ceph_properties
if val1 == "threepar":
storage_properties = threepar_properties
for val2 in storage_properties:
try:
assert val2 in self.systemproperties
self.success(val1 + ' system property ' + val2 + ' is present.')
except AssertionError, e:
self.failure(val1 + ' system property ' + val2 + ' is missing or invalid! ' + str(e))
| bsd-2-clause |
lantz/nox-tutorial | src/nox/netapps/data/datacache_impl.py | 10 | 1317 | #
# Copyright 2009 (C) Nicira, Inc.
#
import logging
from nox.lib.core import Component
from nox.netapps.data.pydatacache import PyData_cache, Principal_delete_event
lg = logging.getLogger('nox.netapps.data.datacache')
class DataCache(Component):
def __init__(self, ctxt):
Component.__init__(self, ctxt)
self.cache = PyData_cache(ctxt)
Principal_delete_event.register_event_converter(self.ctxt)
def getInterface(self):
return str(DataCache)
def configure(self, config):
self.cache.configure(config)
def get_authenticated_id(self, ptype):
return self.cache.get_authenticated_id(ptype)
def get_unauthenticated_id(self, ptype):
return self.cache.get_unauthenticated_id(ptype)
def get_unknown_id(self, ptype):
return self.cache.get_unknown_id(ptype)
def get_authenticated_name(self):
return self.cache.get_authenticated_name()
def get_unauthenticated_name(self):
return self.cache.get_unauthenticated_name()
def get_unknown_name(self):
return self.cache.get_unknown_name()
def get_name(self, ptype, id):
return self.cache.get_name(ptype, id)
def getFactory():
class Factory:
def instance(self, ctxt):
return DataCache(ctxt)
return Factory()
| gpl-3.0 |
pleaseproject/python-for-android | python-modules/zope/zope/interface/tests/test_verify.py | 50 | 4612 | ##############################################################################
#
# Copyright (c) 2001, 2002 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Interface Verify tests
$Id: test_verify.py 110536 2010-04-06 02:59:44Z tseaver $
"""
import doctest
import unittest
from zope.interface import Interface, implements, classImplements, Attribute
from zope.interface.verify import verifyClass, verifyObject
from zope.interface.exceptions import DoesNotImplement, BrokenImplementation
from zope.interface.exceptions import BrokenMethodImplementation
class Test(unittest.TestCase):
def testNotImplemented(self):
class C(object): pass
class I(Interface): pass
self.assertRaises(DoesNotImplement, verifyClass, I, C)
classImplements(C, I)
verifyClass(I, C)
def testMissingAttr(self):
class I(Interface):
def f(): pass
class C(object):
implements(I)
self.assertRaises(BrokenImplementation, verifyClass, I, C)
C.f=lambda self: None
verifyClass(I, C)
def testMissingAttr_with_Extended_Interface(self):
class II(Interface):
def f():
pass
class I(II):
pass
class C(object):
implements(I)
self.assertRaises(BrokenImplementation, verifyClass, I, C)
C.f=lambda self: None
verifyClass(I, C)
def testWrongArgs(self):
class I(Interface):
def f(a): pass
class C(object):
def f(self, b): pass
implements(I)
# We no longer require names to match.
#self.assertRaises(BrokenMethodImplementation, verifyClass, I, C)
C.f=lambda self, a: None
verifyClass(I, C)
C.f=lambda self, **kw: None
self.assertRaises(BrokenMethodImplementation, verifyClass, I, C)
C.f=lambda self, a, *args: None
verifyClass(I, C)
C.f=lambda self, a, *args, **kw: None
verifyClass(I, C)
C.f=lambda self, *args: None
verifyClass(I, C)
def testExtraArgs(self):
class I(Interface):
def f(a): pass
class C(object):
def f(self, a, b): pass
implements(I)
self.assertRaises(BrokenMethodImplementation, verifyClass, I, C)
C.f=lambda self, a: None
verifyClass(I, C)
C.f=lambda self, a, b=None: None
verifyClass(I, C)
def testNoVar(self):
class I(Interface):
def f(a, *args): pass
class C(object):
def f(self, a): pass
implements(I)
self.assertRaises(BrokenMethodImplementation, verifyClass, I, C)
C.f=lambda self, a, *foo: None
verifyClass(I, C)
def testNoKW(self):
class I(Interface):
def f(a, **args): pass
class C(object):
def f(self, a): pass
implements(I)
self.assertRaises(BrokenMethodImplementation, verifyClass, I, C)
C.f=lambda self, a, **foo: None
verifyClass(I, C)
def testModule(self):
from zope.interface.tests.ifoo import IFoo
from zope.interface.tests import dummy
verifyObject(IFoo, dummy)
def testMethodForAttr(self):
class IFoo(Interface):
foo = Attribute("The foo Attribute")
class Foo:
implements(IFoo)
def foo(self):
pass
verifyClass(IFoo, Foo)
def testNonMethodForMethod(self):
class IBar(Interface):
def foo():
pass
class Bar:
implements(IBar)
foo = 1
self.assertRaises(BrokenMethodImplementation, verifyClass, IBar, Bar)
def test_suite():
loader=unittest.TestLoader()
return unittest.TestSuite((
doctest.DocFileSuite(
'../verify.txt',
optionflags=doctest.NORMALIZE_WHITESPACE),
loader.loadTestsFromTestCase(Test),
))
if __name__=='__main__':
unittest.TextTestRunner().run(test_suite())
| apache-2.0 |
leighpauls/k2cro4 | v8/tools/testrunner/objects/context.py | 9 | 2331 | # Copyright 2012 the V8 project authors. 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.
class Context():
def __init__(self, arch, mode, shell_dir, mode_flags, verbose, timeout,
isolates, command_prefix, extra_flags):
self.arch = arch
self.mode = mode
self.shell_dir = shell_dir
self.mode_flags = mode_flags
self.verbose = verbose
self.timeout = timeout
self.isolates = isolates
self.command_prefix = command_prefix
self.extra_flags = extra_flags
def Pack(self):
return [self.arch, self.mode, self.mode_flags, self.timeout, self.isolates,
self.extra_flags]
@staticmethod
def Unpack(packed):
# For the order of the fields, refer to Pack() above.
return Context(packed[0], packed[1], None, packed[2], False,
packed[3], packed[4], "", packed[5])
| bsd-3-clause |
job/pdns | pdns/dnsdistdist/docs/conf.py | 4 | 5977 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# dnsdist documentation build configuration file, created by
# sphinx-quickstart on Thu Feb 9 00:08:08 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
# import os
# import sys
# sys.path.insert(0, os.path.abspath('.'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = ['redjack.sphinx.lua', 'sphinxcontrib.httpdomain', 'sphinxjsondomain',
'sphinxcontrib.fulltoc', 'changelog']
primary_domain = 'lua'
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The master toctree document.
master_doc = 'index_TOC'
# General information about the project.
project = 'dnsdist'
copyright = '2015-2017, PowerDNS.COM BV and its contributors'
author = 'PowerDNS.COM BV and its contributors'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '1.2'
# The full version, including alpha/beta/rc tags.
release = '1.2.0'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Changelog Options ----------------------------------------------------
changelog_render_ticket = "https://github.com/PowerDNS/pdns/issues/%s"
changelog_render_pullreq = "https://github.com/PowerDNS/pdns/pull/%s"
changelog_render_changeset = "https://github.com/PowerDNS/pdns/commit/%s"
changelog_sections = ['New Features', 'Improvements', 'Bug Fixes', "Removals"]
changelog_inner_tag_sort = ["Security", 'DNSCrypt', 'Protobuf', "Performance", 'Webserver']
changelog_render_tags = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme_path = ['_templates']
html_theme = 'pdns_html'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
html_theme_options = {}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
html_favicon = '_static/favicon.ico'
# -- Options for HTMLHelp output ------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'dnsdistdoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
'papersize': 'a4paper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'dnsdist.tex', 'dnsdist',
'PowerDNS.COM BV', 'manual'),
]
latex_logo = '_static/powerdns-logo-trans.png'
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('manpages/dnsdist.1', 'dnsdist', 'dnsdist',
[author], 1)
]
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'dnsdist', 'dnsdist',
author, 'dnsdist', 'One line description of project.',
'Miscellaneous'),
]
# -- Options for Epub output ----------------------------------------------
# Bibliographic Dublin Core info.
epub_title = project
epub_author = author
epub_publisher = author
epub_copyright = copyright
# The unique identifier of the text. This can be a ISBN number
# or the project homepage.
#
# epub_identifier = ''
# A unique identification for the text.
#
# epub_uid = ''
# A list of files that should not be packed into the epub file.
epub_exclude_files = ['search.html']
| gpl-2.0 |
GerritCodeReview/git-repo | subcmds/prune.py | 5 | 1970 | # -*- coding:utf-8 -*-
#
# Copyright (C) 2008 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import print_function
from color import Coloring
from command import PagedCommand
class Prune(PagedCommand):
common = True
helpSummary = "Prune (delete) already merged topics"
helpUsage = """
%prog [<project>...]
"""
def Execute(self, opt, args):
all_branches = []
for project in self.GetProjects(args):
all_branches.extend(project.PruneHeads())
if not all_branches:
return
class Report(Coloring):
def __init__(self, config):
Coloring.__init__(self, config, 'status')
self.project = self.printer('header', attr='bold')
out = Report(all_branches[0].project.config)
out.project('Pending Branches')
out.nl()
project = None
for branch in all_branches:
if project != branch.project:
project = branch.project
out.nl()
out.project('project %s/' % project.relpath)
out.nl()
print('%s %-33s ' % (
branch.name == project.CurrentBranch and '*' or ' ',
branch.name), end='')
if not branch.base_exists:
print('(ignoring: tracking branch is gone: %s)' % (branch.base,))
else:
commits = branch.commits
date = branch.date
print('(%2d commit%s, %s)' % (
len(commits),
len(commits) != 1 and 's' or ' ',
date))
| apache-2.0 |
petricm/DIRAC | FrameworkSystem/Client/UserProfileClient.py | 7 | 4566 |
import re
from DIRAC import S_OK, S_ERROR
from DIRAC.Core.DISET.RPCClient import RPCClient
from DIRAC.Core.Utilities import DEncode, Time
class UserProfileClient:
def __init__( self, profile, rpcClientFunctor = False ):
if rpcClientFunctor:
self.rpcClientFunctor = rpcClientFunctor
else:
self.rpcClientFunctor = RPCClient
self.profile = profile
def __getRPCClient( self ):
return self.rpcClientFunctor( "Framework/UserProfileManager" )
def __generateTypeDest( self, dataObj ):
if isinstance( dataObj, bool ):
return "b"
if dataObj is None:
return "o"
if isinstance( dataObj, ( int, long, float ) ):
return "n"
if isinstance( dataObj, basestring ):
return "s"
# Not even trying here...
if type( dataObj ) in Time._allTypes:
return "t"
if isinstance( dataObj, ( list, tuple ) ):
return "l%se" % "".join( [ self.__generateTypeDest( so ) for so in dataObj ] )
if isinstance( dataObj, dict ):
return "d%se" % "".join( [ "%s%s" % ( self.__generateTypeDest( k ),
self.__generateTypeDest( dataObj[k] ) ) for k in dataObj ] )
return ""
def checkTypeRe( self, dataObj, typeRE ):
if typeRE[0] != "^":
typeRE = "^%s" % typeRE
if typeRE[-1] != "$":
typeRE = "%s$" % typeRE
typeDesc = self.__generateTypeDest( dataObj )
if not re.match( typeRE, typeDesc ):
return S_ERROR( "Stored data does not match typeRE: %s vs %s" % ( typeDesc, typeRE ) )
return S_OK()
def storeVar( self, varName, data, perms = {} ):
try:
stub = DEncode.encode( data )
except Exception as e:
return S_ERROR( "Cannot encode data:%s" % str( e ) )
return self.__getRPCClient().storeProfileVar( self.profile, varName, stub, perms )
def __decodeVar( self, data, dataTypeRE ):
try:
dataObj, lenData = DEncode.decode( data )
except Exception as e:
return S_ERROR( "Cannot decode data: %s" % str( e ) )
if dataTypeRE:
result = self.checkTypeRe( dataObj, dataTypeRE )
if not result[ 'OK' ]:
return result
return S_OK( dataObj )
def retrieveVar( self, varName, dataTypeRE = False ):
rpcClient = self.__getRPCClient()
result = rpcClient.retrieveProfileVar( self.profile, varName )
if not result[ 'OK' ]:
return result
return self.__decodeVar( result[ 'Value' ], dataTypeRE )
def retrieveVarFromUser( self, ownerName, ownerGroup, varName, dataTypeRE = False ):
rpcClient = self.__getRPCClient()
result = rpcClient.retrieveProfileVarFromUser( ownerName, ownerGroup, self.profile, varName )
if not result[ 'OK' ]:
return result
return self.__decodeVar( result[ 'Value' ], dataTypeRE )
def retrieveAllVars( self ):
rpcClient = self.__getRPCClient()
result = rpcClient.retrieveProfileAllVars( self.profile )
if not result[ 'OK' ]:
return result
try:
encodedData = result[ 'Value' ]
dataObj = {}
for k in encodedData:
v, lenData = DEncode.decode( encodedData[k] )
dataObj[ k ] = v
except Exception as e:
return S_ERROR( "Cannot decode data: %s" % str( e ) )
return S_OK( dataObj )
def listAvailableVars( self, filterDict = {} ):
rpcClient = self.__getRPCClient()
return rpcClient.listAvailableProfileVars( self.profile, filterDict )
def getUserProfiles( self ):
rpcClient = self.__getRPCClient()
return rpcClient.getUserProfiles()
def setVarPermissions( self, varName, perms ):
rpcClient = self.__getRPCClient()
return rpcClient.setProfileVarPermissions( self.profile, varName, perms )
def getVarPermissions( self, varName ):
rpcClient = self.__getRPCClient()
return rpcClient.getProfileVarPermissions( self.profile, varName )
def deleteVar( self, varName ):
return self.__getRPCClient().deleteProfileVar( self.profile, varName )
def deleteProfiles( self, userList ):
return self.__getRPCClient().deleteProfiles( userList )
def storeHashTag( self, tagName ):
return self.__getRPCClient().storeHashTag( tagName )
def retrieveHashTag( self, hashTag ):
return self.__getRPCClient().retrieveHashTag( hashTag )
def retrieveAllHashTags( self ):
return self.__getRPCClient().retrieveAllHashTags()
def getUserProfileNames( self, permission = dict() ):
"""
it returns the available profile names by not taking account the permission: ReadAccess and PublishAccess
"""
return self.__getRPCClient().getUserProfileNames( permission )
| gpl-3.0 |
larrybradley/astropy | astropy/table/tests/test_row.py | 8 | 12241 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import sys
import pytest
import numpy as np
from astropy import table
from astropy.table import Row
from astropy import units as u
from .conftest import MaskedTable
def test_masked_row_with_object_col():
"""
Numpy < 1.8 has a bug in masked array that prevents access a row if there is
a column with object type.
"""
t = table.Table([[1]], dtype=['O'], masked=True)
t['col0'].mask = False
assert t[0]['col0'] == 1
t['col0'].mask = True
assert t[0]['col0'] is np.ma.masked
@pytest.mark.usefixtures('table_types')
class TestRow():
def _setup(self, table_types):
self._table_type = table_types.Table
self._column_type = table_types.Column
@property
def t(self):
# pytest wants to run this method once before table_types is run
# to set Table and Column. In this case just return None, which would
# cause any downstream test to fail if this happened in any other context.
if self._column_type is None:
return None
if not hasattr(self, '_t'):
a = self._column_type(name='a', data=[1, 2, 3], dtype='i8')
b = self._column_type(name='b', data=[4, 5, 6], dtype='i8')
self._t = self._table_type([a, b])
return self._t
def test_subclass(self, table_types):
"""Row is subclass of ndarray and Row"""
self._setup(table_types)
c = Row(self.t, 2)
assert isinstance(c, Row)
def test_values(self, table_types):
"""Row accurately reflects table values and attributes"""
self._setup(table_types)
table = self.t
row = table[1]
assert row['a'] == 2
assert row['b'] == 5
assert row[0] == 2
assert row[1] == 5
assert row.meta is table.meta
assert row.colnames == table.colnames
assert row.columns is table.columns
with pytest.raises(IndexError):
row[2]
if sys.byteorder == 'little':
assert str(row.dtype) == "[('a', '<i8'), ('b', '<i8')]"
else:
assert str(row.dtype) == "[('a', '>i8'), ('b', '>i8')]"
def test_ref(self, table_types):
"""Row is a reference into original table data"""
self._setup(table_types)
table = self.t
row = table[1]
row['a'] = 10
if table_types.Table is not MaskedTable:
assert table['a'][1] == 10
def test_left_equal(self, table_types):
"""Compare a table row to the corresponding structured array row"""
self._setup(table_types)
np_t = self.t.as_array()
if table_types.Table is MaskedTable:
with pytest.raises(ValueError):
self.t[0] == np_t[0]
else:
for row, np_row in zip(self.t, np_t):
assert np.all(row == np_row)
def test_left_not_equal(self, table_types):
"""Compare a table row to the corresponding structured array row"""
self._setup(table_types)
np_t = self.t.as_array()
np_t['a'] = [0, 0, 0]
if table_types.Table is MaskedTable:
with pytest.raises(ValueError):
self.t[0] == np_t[0]
else:
for row, np_row in zip(self.t, np_t):
assert np.all(row != np_row)
def test_right_equal(self, table_types):
"""Test right equal"""
self._setup(table_types)
np_t = self.t.as_array()
if table_types.Table is MaskedTable:
with pytest.raises(ValueError):
self.t[0] == np_t[0]
else:
for row, np_row in zip(self.t, np_t):
assert np.all(np_row == row)
def test_convert_numpy_array(self, table_types):
self._setup(table_types)
d = self.t[1]
np_data = np.array(d)
if table_types.Table is not MaskedTable:
assert np.all(np_data == d.as_void())
assert np_data is not d.as_void()
assert d.colnames == list(np_data.dtype.names)
np_data = np.array(d, copy=False)
if table_types.Table is not MaskedTable:
assert np.all(np_data == d.as_void())
assert np_data is not d.as_void()
assert d.colnames == list(np_data.dtype.names)
with pytest.raises(ValueError):
np_data = np.array(d, dtype=[('c', 'i8'), ('d', 'i8')])
def test_format_row(self, table_types):
"""Test formatting row"""
self._setup(table_types)
table = self.t
row = table[0]
assert repr(row).splitlines() == ['<{} {}{}>'
.format(row.__class__.__name__,
'index=0',
' masked=True' if table.masked else ''),
' a b ',
'int64 int64',
'----- -----',
' 1 4']
assert str(row).splitlines() == [' a b ',
'--- ---',
' 1 4']
assert row._repr_html_().splitlines() == [
'<i>{} {}{}</i>'
.format(row.__class__.__name__,
'index=0',
' masked=True' if table.masked else ''),
f'<table id="table{id(table)}">',
'<thead><tr><th>a</th><th>b</th></tr></thead>',
'<thead><tr><th>int64</th><th>int64</th></tr></thead>',
'<tr><td>1</td><td>4</td></tr>',
'</table>']
def test_as_void(self, table_types):
"""Test the as_void() method"""
self._setup(table_types)
table = self.t
row = table[0]
# If masked then with no masks, issue numpy/numpy#483 should come
# into play. Make sure as_void() code is working.
row_void = row.as_void()
if table.masked:
assert isinstance(row_void, np.ma.mvoid)
else:
assert isinstance(row_void, np.void)
assert row_void['a'] == 1
assert row_void['b'] == 4
# Confirm row is a view of table but row_void is not.
table['a'][0] = -100
assert row['a'] == -100
assert row_void['a'] == 1
# Make sure it works for a table that has masked elements
if table.masked:
table['a'].mask = True
# row_void is not a view, need to re-make
assert row_void['a'] == 1
row_void = row.as_void() # but row is a view
assert row['a'] is np.ma.masked
def test_row_and_as_void_with_objects(self, table_types):
"""Test the deprecated data property and as_void() method"""
t = table_types.Table([[{'a': 1}, {'b': 2}]], names=('a',))
assert t[0][0] == {'a': 1}
assert t[0]['a'] == {'a': 1}
assert t[0].as_void()[0] == {'a': 1}
assert t[0].as_void()['a'] == {'a': 1}
def test_bounds_checking(self, table_types):
"""Row gives index error upon creation for out-of-bounds index"""
self._setup(table_types)
for ibad in (-5, -4, 3, 4):
with pytest.raises(IndexError):
self.t[ibad]
def test_create_rows_from_list(self, table_types):
"""https://github.com/astropy/astropy/issues/8976"""
orig_tab = table_types.Table([[1, 2, 3], [4, 5, 6]], names=('a', 'b'))
new_tab = type(orig_tab)(rows=[row for row in orig_tab],
names=orig_tab.dtype.names)
assert np.all(orig_tab == new_tab)
def test_row_keys_values(self, table_types):
self._setup(table_types)
row = self.t[0]
for row_key, col_key in zip(row.keys(), self.t.columns.keys()):
assert row_key == col_key
for row_value, col in zip(row.values(), self.t.columns.values()):
assert row_value == col[0]
def test_row_as_mapping(self, table_types):
self._setup(table_types)
row = self.t[0]
row_dict = dict(row)
for key, value in row_dict.items():
assert row[key] == value
def f(**kwargs):
return kwargs
row_splatted = f(**row)
for key, value in row_splatted.items():
assert row[key] == value
def test_row_as_sequence(self, table_types):
self._setup(table_types)
row = self.t[0]
row_tuple = tuple(row)
keys = tuple(row.keys())
for key, value in zip(keys, row_tuple):
assert row[key] == value
def f(*args):
return args
row_splatted = f(*row)
for key, value in zip(keys, row_splatted):
assert row[key] == value
def test_row_tuple_column_slice():
"""
Test getting and setting a row using a tuple or list of column names
"""
t = table.QTable([[1, 2, 3] * u.m,
[10., 20., 30.],
[100., 200., 300.],
['x', 'y', 'z']], names=['a', 'b', 'c', 'd'])
# Get a row for index=1
r1 = t[1]
# Column slice with tuple of col names
r1_abc = r1['a', 'b', 'c'] # Row object for these cols
r1_abc_repr = ['<Row index=1>',
' a b c ',
' m ',
'float64 float64 float64',
'------- ------- -------',
' 2.0 20.0 200.0']
assert repr(r1_abc).splitlines() == r1_abc_repr
# Column slice with list of col names
r1_abc = r1[['a', 'b', 'c']]
assert repr(r1_abc).splitlines() == r1_abc_repr
# Make sure setting on a tuple or slice updates parent table and row
r1['c'] = 1000
r1['a', 'b'] = 1000 * u.cm, 100.
assert r1['a'] == 10 * u.m
assert r1['b'] == 100
assert t['a'][1] == 10 * u.m
assert t['b'][1] == 100.
assert t['c'][1] == 1000
# Same but using a list of column names instead of tuple
r1[['a', 'b']] = 2000 * u.cm, 200.
assert r1['a'] == 20 * u.m
assert r1['b'] == 200
assert t['a'][1] == 20 * u.m
assert t['b'][1] == 200.
# Set column slice of column slice
r1_abc['a', 'c'] = -1 * u.m, -10
assert t['a'][1] == -1 * u.m
assert t['b'][1] == 200.
assert t['c'][1] == -10.
# Bad column name
with pytest.raises(KeyError) as err:
t[1]['a', 'not_there']
assert "'not_there'" in str(err.value)
# Too many values
with pytest.raises(ValueError) as err:
t[1]['a', 'b'] = 1 * u.m, 2, 3
assert 'right hand side must be a sequence' in str(err.value)
# Something without a length
with pytest.raises(ValueError) as err:
t[1]['a', 'b'] = 1
assert 'right hand side must be a sequence' in str(err.value)
def test_row_tuple_column_slice_transaction():
"""
Test that setting a row that fails part way through does not
change the table at all.
"""
t = table.QTable([[10., 20., 30.],
[1, 2, 3] * u.m], names=['a', 'b'])
tc = t.copy()
# First one succeeds but second fails.
with pytest.raises(ValueError) as err:
t[1]['a', 'b'] = (-1, -1 * u.s) # Bad unit
assert "'s' (time) and 'm' (length) are not convertible" in str(err.value)
assert t[1] == tc[1]
def test_uint_indexing():
"""
Test that accessing a row with an unsigned integer
works as with a signed integer. Similarly tests
that printing such a row works.
This is non-trivial: adding a signed and unsigned
integer in numpy results in a float, which is an
invalid slice index.
Regression test for gh-7464.
"""
t = table.Table([[1., 2., 3.]], names='a')
assert t['a'][1] == 2.
assert t['a'][np.int_(1)] == 2.
assert t['a'][np.uint(1)] == 2.
assert t[np.uint(1)]['a'] == 2.
trepr = ['<Row index=1>',
' a ',
'float64',
'-------',
' 2.0']
assert repr(t[1]).splitlines() == trepr
assert repr(t[np.int_(1)]).splitlines() == trepr
assert repr(t[np.uint(1)]).splitlines() == trepr
| bsd-3-clause |
Mako-kun/mangaki | mangaki/irl/migrations/0004_event_attendees.py | 3 | 1151 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-01-24 18:50
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('irl', '0003_auto_20160124_1537'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Attendee',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('attending', models.BooleanField(default=False)),
('event', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='irl.Event')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.AddField(
model_name='event',
name='attendees',
field=models.ManyToManyField(blank=True, through='irl.Attendee', to=settings.AUTH_USER_MODEL),
),
]
| agpl-3.0 |
ruiaylin/percona-xtrabackup | storage/innobase/xtrabackup/test/kewpie/percona_tests/xtrabackup_disabled/ib_basic_test.py | 24 | 4748 | #! /usr/bin/env python
# -*- mode: python; indent-tabs-mode: nil; -*-
# vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
#
# Copyright (C) 2011 Patrick Crews
#
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
import os
import shutil
import unittest
from lib.util.mysqlBaseTestCase import mysqlBaseTestCase
server_requirements = [[]]
servers = []
server_manager = None
test_executor = None
# we explicitly use the --no-timestamp option
# here. We will be using a generic / vanilla backup dir
backup_path = None
class basicTest(mysqlBaseTestCase):
def setUp(self):
master_server = servers[0] # assumption that this is 'master'
backup_path = os.path.join(master_server.vardir, '_xtrabackup')
# remove backup path
if os.path.exists(backup_path):
shutil.rmtree(backup_path)
def test_basic1(self):
self.servers = servers
if servers[0].type not in ['mysql','percona']:
return
else:
innobackupex = test_executor.system_manager.innobackupex_path
xtrabackup = test_executor.system_manager.xtrabackup_path
master_server = servers[0] # assumption that this is 'master'
backup_path = os.path.join(master_server.vardir, '_xtrabackup')
output_path = os.path.join(master_server.vardir, 'innobackupex.out')
exec_path = os.path.dirname(innobackupex)
orig_dumpfile = os.path.join(master_server.vardir,'orig_dumpfile')
restored_dumpfile = os.path.join(master_server.vardir, 'restored_dumpfile')
# populate our server with a test bed
test_cmd = "./gentest.pl --gendata=conf/percona/percona.zz"
retcode, output = self.execute_randgen(test_cmd, test_executor, master_server)
# take a backup
cmd = ("%s --defaults-file=%s --user=root --port=%d"
" --host=127.0.0.1 --no-timestamp"
" --ibbackup=%s %s" %( innobackupex
, master_server.cnf_file
, master_server.master_port
, xtrabackup
, backup_path))
retcode, output = self.execute_cmd(cmd, output_path, exec_path, True)
self.assertTrue(retcode==0,output)
# take mysqldump of our current server state
self.take_mysqldump(master_server,databases=['test'],dump_path=orig_dumpfile)
# shutdown our server
master_server.stop()
# prepare our backup
cmd = ("%s --apply-log --no-timestamp --use-memory=500M "
"--ibbackup=%s %s" %( innobackupex
, xtrabackup
, backup_path))
retcode, output = self.execute_cmd(cmd, output_path, exec_path, True)
self.assertTrue(retcode==0,output)
# remove old datadir
shutil.rmtree(master_server.datadir)
os.mkdir(master_server.datadir)
# restore from backup
cmd = ("%s --defaults-file=%s --copy-back"
" --ibbackup=%s %s" %( innobackupex
, master_server.cnf_file
, xtrabackup
, backup_path))
retcode, output = self.execute_cmd(cmd, output_path, exec_path, True)
self.assertTrue(retcode==0, output)
# restart server (and ensure it doesn't crash)
master_server.start()
self.assertTrue(master_server.status==1, 'Server failed restart from restored datadir...')
# take mysqldump of current server state
self.take_mysqldump(master_server, databases=['test'],dump_path=restored_dumpfile)
# diff original vs. current server dump files
retcode, output = self.diff_dumpfiles(orig_dumpfile, restored_dumpfile)
self.assertTrue(retcode, output)
| gpl-2.0 |
charleszheng44/cctools | prune/examples/hep/hep.py | 4 | 2059 | #!/usr/bin/env cctools_python
# CCTOOLS_PYTHON_VERSION 2.7 2.6
# Copyright (c) 2010- The University of Notre Dame.
# This software is distributed under the GNU General Public License.
# See the file COPYING for details.
from prune import client
from os.path import expanduser
HOME = expanduser("~")
prune = client.Connect(base_dir = HOME+'/.prune') #Prune data is stored in base_dir
###### Create common HEP environment ######
E1 = prune.envi_add( engine='umbrella', spec='cms.umbrella',
sandbox_mode='parrot', log='umbrella.log',
cms_siteconf='SITECONF.tar.gz',
cvmfs_http_proxy='http://eddie.crc.nd.edu:3128',
http_proxy='http://eddie.crc.nd.edu:3128' )
event_count = 10
###### Simulation stage ######
D1 = prune.file_add( 'simulate.sh' )
D2, = prune.task_add( returns=['SinglePi0E10_cfi_GEN_SIM.root'],
env=E1, cmd='chmod 755 simulate.sh; ./simulate.sh %i ' % (event_count),
args=[D1], params=['simulate.sh'] )
###### Digitization stage ######
D3 = prune.file_add( 'digitize.sh' )
D4, = prune.task_add( returns=['SinglePi0E10_cfi_GEN_DIGI_L1_DIGI2RAW_HLT_RAW2DIGI_L1Reco.root'],
env=E1, cmd='chmod 755 digitize.sh; ./digitize.sh %i' % (event_count),
args=[D3,D2], params=['digitize.sh','SinglePi0E10_cfi_GEN_SIM.root'] )
###### Reconstruction stage ######
D5 = prune.file_add( 'reconstruct.sh' )
D6, D7, D8 = prune.task_add( returns=[
'SinglePi0E10_cfi_GEN_RAW2DIGI_L1Reco_RECO_VALIDATION_DQM.py',
'SinglePi0E10_cfi_GEN_RAW2DIGI_L1Reco_RECO_VALIDATION_DQM.root',
'SinglePi0E10_cfi_GEN_RAW2DIGI_L1Reco_RECO_VALIDATION_DQM_inDQM.root'],
env=E1, cmd='chmod 755 reconstruct.sh; ./reconstruct.sh %i' % (event_count),
args=[D5,D4], params=['reconstruct.sh','SinglePi0E10_cfi_GEN_DIGI2RAW.root'] )
###### Execute the workflow ######
prune.execute( worker_type='local', cores=8 )
###### Export final data ######
prune.export( D7, 'hep.result.root' )
###### Export publishable workflow ######
prune.export( D7, 'hep.prune', lineage=3 )
| gpl-2.0 |
meteorfox/PerfKitBenchmarker | tests/windows_packages/ntttcp_test.py | 7 | 2436 | # Copyright 2015 PerfKitBenchmarker Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for ntttcp_benchmark."""
import os
import unittest
from perfkitbenchmarker import sample
from perfkitbenchmarker import test_util
from perfkitbenchmarker.windows_packages import ntttcp
class NtttcpBenchmarkTestCase(unittest.TestCase, test_util.SamplesTestMixin):
def setUp(self):
self.maxDiff = None
# Load data
path = os.path.join(os.path.dirname(__file__),
'..', 'data',
'ntttcp_results.xml')
with open(path) as fp:
self.ntttcp_xml_results = fp.read()
def testNtttcpParsing(self):
extra_metadata = {}
samples = ntttcp.ParseNtttcpResults(self.ntttcp_xml_results,
extra_metadata)
expected_metadata = {
'async': 'False', 'bind_sender': 'False', 'cooldown_time': '15000',
'dash_n_timeout': '10800000', 'max_active_threads': '2',
'port': '5003', 'recv_socket_buff': '-1', 'run_time': '30000',
'send_socket_buff': '8192', 'sync_port': 'False', 'udp': 'False',
'use_ipv6': 'False', 'verbose': 'False', 'verify_data': 'False',
'wait_all': 'False', 'warmup_time': '15000', 'wsa': 'False'
}
expected_thread_0_metadata = expected_metadata.copy()
expected_thread_0_metadata['thread_index'] = '0'
expected_thread_1_metadata = expected_metadata.copy()
expected_thread_1_metadata['thread_index'] = '1'
expected_samples = [
sample.Sample('Total Throughput', 1990.541, 'Mbps',
expected_metadata),
sample.Sample('Thread Throughput', 975.871, 'Mbps',
expected_thread_0_metadata),
sample.Sample('Thread Throughput', 1014.669, 'Mbps',
expected_thread_1_metadata)]
self.assertSampleListsEqualUpToTimestamp(expected_samples, samples)
| apache-2.0 |
stephane-martin/salt-debian-packaging | salt-2016.3.3/salt/cloud/clouds/scaleway.py | 1 | 12629 | # -*- coding: utf-8 -*-
'''
Scaleway Cloud Module
=====================
.. versionadded:: 2015.8.0
The Scaleway cloud module is used to interact with your Scaleway BareMetal
Servers.
Use of this module only requires the ``api_key`` parameter to be set. Set up
the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/scaleway.conf``:
.. code-block:: yaml
scaleway-config:
# Scaleway organization and token
access_key: 0e604a2c-aea6-4081-acb2-e1d1258ef95c
token: be8fd96b-04eb-4d39-b6ba-a9edbcf17f12
driver: scaleway
:depends: requests
'''
# Import Python Libs
from __future__ import absolute_import
import json
import logging
import pprint
import time
# Import Salt Libs
from salt.ext.six.moves import range
import salt.utils.cloud
import salt.config as config
from salt.exceptions import (
SaltCloudNotFound,
SaltCloudSystemExit,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout
)
# Import Third Party Libs
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
log = logging.getLogger(__name__)
__virtualname__ = 'scaleway'
# Only load in this module if the Scaleway configurations are in place
def __virtual__():
'''
Check for Scaleway configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
''' Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('token',)
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'requests': HAS_REQUESTS}
)
def avail_images(call=None):
''' Return a list of the images that are on the provider.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
items = query(method='images')
ret = {}
for image in items['images']:
ret[image['id']] = {}
for item in image:
ret[image['id']][item] = str(image[item])
return ret
def list_nodes(call=None):
''' Return a list of the BareMetal servers that are on the provider.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
items = query(method='servers')
ret = {}
for node in items['servers']:
public_ips = []
private_ips = []
image_id = ''
if node.get('public_ip'):
public_ips = [node['public_ip']['address']]
if node.get('private_ip'):
private_ips = [node['private_ip']]
if node.get('image'):
image_id = node['image']['id']
ret[node['name']] = {
'id': node['id'],
'image_id': image_id,
'public_ips': public_ips,
'private_ips': private_ips,
'size': node['volumes']['0']['size'],
'state': node['state'],
}
return ret
def list_nodes_full(call=None):
''' Return a list of the BareMetal servers that are on the provider.
'''
if call == 'action':
raise SaltCloudSystemExit(
'list_nodes_full must be called with -f or --function'
)
items = query(method='servers')
# For each server, iterate on its parameters.
ret = {}
for node in items['servers']:
ret[node['name']] = {}
for item in node:
value = node[item]
ret[node['name']][item] = value
return ret
def list_nodes_select(call=None):
''' Return a list of the BareMetal servers that are on the provider, with
select fields.
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full('function'), __opts__['query.selection'], call,
)
def get_image(server_):
''' Return the image object to use.
'''
images = avail_images()
server_image = str(config.get_cloud_config_value(
'image', server_, __opts__, search_global=False
))
for image in images:
if server_image in (images[image]['name'], images[image]['id']):
return images[image]['id']
raise SaltCloudNotFound(
'The specified image, \'{0}\', could not be found.'.format(server_image)
)
def create_node(args):
''' Create a node.
'''
node = query(method='servers', args=args, http_method='post')
action = query(
method='servers',
server_id=node['server']['id'],
command='action',
args={'action': 'poweron'},
http_method='post'
)
return node
def create(server_):
'''
Create a single BareMetal server from a data dict.
'''
try:
# Check for required profile parameters before sending any API calls.
if server_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'scaleway',
server_['profile'],
vm_=server_) is False:
return False
except AttributeError:
pass
# Since using "provider: <provider-engine>" is deprecated, alias provider
# to use driver: "driver: <provider-engine>"
if 'provider' in server_:
server_['driver'] = server_.pop('provider')
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(server_['name']),
{
'name': server_['name'],
'profile': server_['profile'],
'provider': server_['driver'],
},
transport=__opts__['transport']
)
log.info('Creating a BareMetal server {0}'.format(server_['name']))
access_key = config.get_cloud_config_value(
'access_key', get_configured_provider(), __opts__, search_global=False
)
commercial_type = config.get_cloud_config_value(
'commercial_type', server_, __opts__, default='C1'
)
kwargs = {
'name': server_['name'],
'organization': access_key,
'image': get_image(server_),
'commercial_type': commercial_type,
}
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(server_['name']),
{'kwargs': kwargs},
transport=__opts__['transport']
)
try:
ret = create_node(kwargs)
except Exception as exc:
log.error(
'Error creating {0} on Scaleway\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: {1}'.format(
server_['name'],
str(exc)
),
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def __query_node_data(server_name):
''' Called to check if the server has a public IP address.
'''
data = show_instance(server_name, 'action')
if data and data.get('public_ip'):
return data
return False
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(server_['name'],),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', server_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', server_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(server_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(str(exc))
server_['ssh_host'] = data['public_ip']['address']
server_['ssh_password'] = config.get_cloud_config_value(
'ssh_password', server_, __opts__
)
ret = __utils__['cloud.bootstrap'](server_, __opts__)
ret.update(data)
log.info('Created BareMetal server \'{0[name]}\''.format(server_))
log.debug(
'\'{0[name]}\' BareMetal server creation details:\n{1}'.format(
server_, pprint.pformat(data)
)
)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(server_['name']),
{
'name': server_['name'],
'profile': server_['profile'],
'provider': server_['driver'],
},
transport=__opts__['transport']
)
return ret
def query(method='servers', server_id=None, command=None, args=None,
http_method='get'):
''' Make a call to the Scaleway API.
'''
base_path = str(config.get_cloud_config_value(
'api_root',
get_configured_provider(),
__opts__,
search_global=False,
default='https://api.cloud.online.net'
))
path = '{0}/{1}/'.format(base_path, method)
if server_id:
path += '{0}/'.format(server_id)
if command:
path += command
if not isinstance(args, dict):
args = {}
token = config.get_cloud_config_value(
'token', get_configured_provider(), __opts__, search_global=False
)
data = json.dumps(args)
requester = getattr(requests, http_method)
request = requester(
path, data=data,
headers={'X-Auth-Token': token, 'Content-Type': 'application/json'}
)
if request.status_code > 299:
raise SaltCloudSystemExit(
'An error occurred while querying Scaleway. HTTP Code: {0} '
'Error: \'{1}\''.format(
request.status_code,
request.text
)
)
log.debug(request.url)
# success without data
if request.status_code == 204:
return True
return request.json()
def script(server_):
''' Return the script deployment object.
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', server_, __opts__),
server_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, server_)
)
)
def show_instance(name, call=None):
''' Show the details from a Scaleway BareMetal server.
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
node = _get_node(name)
__utils__['cloud.cache_node'](node, __active_provider_name__, __opts__)
return node
def _get_node(name):
for attempt in reversed(list(range(10))):
try:
return list_nodes_full()[name]
except KeyError:
log.debug(
'Failed to get the data for node \'{0}\'. Remaining '
'attempts: {1}'.format(
name, attempt
)
)
# Just a little delay between attempts...
time.sleep(0.5)
return {}
def destroy(name, call=None):
''' Destroy a node. Will check termination protection and warn if enabled.
CLI Example:
.. code-block:: bash
salt-cloud --destroy mymachine
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
{'name': name},
transport=__opts__['transport']
)
data = show_instance(name, call='action')
node = query(
method='servers', server_id=data['id'], command='action',
args={'action': 'terminate'}, http_method='post'
)
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
{'name': name},
transport=__opts__['transport']
)
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](
name, __active_provider_name__.split(':')[0], __opts__
)
return node
| apache-2.0 |
savoirfairelinux/shinken | shinken/contactdowntime.py | 9 | 4255 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
# Gregory Starck, g.starck@gmail.com
# Hartmut Goebel, h.goebel@goebel-consult.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
import time
from shinken.log import logger
""" TODO: Add some comment about this class for the doc"""
class ContactDowntime:
id = 1
# Just to list the properties we will send as pickle
# so to others daemons, so all but NOT REF
properties = {
# 'activate_me': None,
# 'entry_time': None,
# 'fixed': None,
'start_time': None,
# 'duration': None,
# 'trigger_id': None,
'end_time': None,
# 'real_end_time': None,
'author': None,
'comment': None,
'is_in_effect': None,
# 'has_been_triggered': None,
'can_be_deleted': None,
}
# Schedule a contact downtime. It's far more easy than a host/service
# one because we got a beginning, and an end. That's all for running.
# got also an author and a comment for logging purpose.
def __init__(self, ref, start_time, end_time, author, comment):
self.id = self.__class__.id
self.__class__.id += 1
self.ref = ref # pointer to srv or host we are apply
self.start_time = start_time
self.end_time = end_time
self.author = author
self.comment = comment
self.is_in_effect = False
self.can_be_deleted = False
# self.add_automatic_comment()
# Check if we came into the activation of this downtime
def check_activation(self):
now = time.time()
was_is_in_effect = self.is_in_effect
self.is_in_effect = (self.start_time <= now <= self.end_time)
logger.debug("CHECK ACTIVATION:%s", self.is_in_effect)
# Raise a log entry when we get in the downtime
if not was_is_in_effect and self.is_in_effect:
self.enter()
# Same for exit purpose
if was_is_in_effect and not self.is_in_effect:
self.exit()
def in_scheduled_downtime(self):
return self.is_in_effect
# The referenced host/service object enters now a (or another) scheduled
# downtime. Write a log message only if it was not already in a downtime
def enter(self):
self.ref.raise_enter_downtime_log_entry()
# The end of the downtime was reached.
def exit(self):
self.ref.raise_exit_downtime_log_entry()
self.can_be_deleted = True
# A scheduled downtime was prematurely canceled
def cancel(self):
self.is_in_effect = False
self.ref.raise_cancel_downtime_log_entry()
self.can_be_deleted = True
# Call by pickle to dataify the comment
# because we DO NOT WANT REF in this pickleisation!
def __getstate__(self):
# print "Asking a getstate for a downtime on", self.ref.get_dbg_name()
cls = self.__class__
# id is not in *_properties
res = [self.id]
for prop in cls.properties:
res.append(getattr(self, prop))
# We reverse because we want to recreate
# By check at properties in the same order
res.reverse()
return res
# Inverted function of getstate
def __setstate__(self, state):
cls = self.__class__
self.id = state.pop()
for prop in cls.properties:
val = state.pop()
setattr(self, prop, val)
if self.id >= cls.id:
cls.id = self.id + 1
| agpl-3.0 |
rwanyoike/time2relax | tests/test_utils.py | 1 | 2826 | import pytest
from time2relax import exceptions, utils
def test_encode_uri_component():
assert utils.encode_uri_component('escaped%2F1') == 'escaped%252F1'
assert utils.encode_uri_component('a/b/c') == 'a%2Fb%2Fc'
assert utils.encode_uri_component('az09_$()+-') == 'az09_%24()%2B-'
def test_encode_attachment_id():
assert utils.encode_attachment_id('d/e/f.txt') == 'd/e/f.txt'
assert utils.encode_attachment_id('a0+$/9_()') == 'a0%2B%24/9_()'
def test_encode_document_id():
assert utils.encode_document_id('some+id') == 'some%2Bid'
assert utils.encode_document_id('_design/a/b/c') == '_design/a%2Fb%2Fc'
assert utils.encode_document_id('_local/az09_$()+-') == '_local/az09_%24()%2B-'
def test_get_database_host():
assert utils.get_database_host('https://foobar.com:5984/testdb') == 'https://foobar.com:5984'
assert utils.get_database_host('http://u:p@foo.com/a/b/index.html?hey=yo') == 'http://u:p@foo.com'
def test_get_database_name():
assert utils.get_database_name('http://foobar.com:5984/testdb') == 'testdb'
assert utils.get_database_name('https://u:p@foo.com/a/b/index.html?hey=yo') == 'index.html'
assert utils.get_database_name('http://foobar.com:5984/some%2Bid') == 'some%2Bid'
def test_query_method_kwargs():
assert utils.query_method_kwargs({}) == ('GET', {})
method, kwargs = utils.query_method_kwargs({'start_key': ['x'], 'endkey': 2})
assert method == 'GET'
assert kwargs == {'params': {'endkey': '2', 'start_key': '["x"]'}}
def test_query_method_kwargs_post_method():
keys = [2, '10', True, 'foo']
method, kwargs = utils.query_method_kwargs({'keys': keys})
assert method == 'POST'
assert kwargs == {'json': {'keys': keys}}
def test_raise_http_exception(mocker):
status_codes = {
400: exceptions.BadRequest,
401: exceptions.Unauthorized,
403: exceptions.Forbidden,
404: exceptions.ResourceNotFound,
405: exceptions.MethodNotAllowed,
# 406: time2relax.NotAcceptable,
409: exceptions.ResourceConflict,
412: exceptions.PreconditionFailed,
# 415: time2relax.BadContentType,
# 416: time2relax.RequestedRangeNotSatisfiable,
# 417: time2relax.ExpectationFailed,
500: exceptions.ServerError,
999: exceptions.HTTPError,
}
for code, ex in status_codes.items():
mock_response = mocker.Mock()
mock_response.status_code = code
mock_response.json.return_value = {
'error': 'error_{}'.format(code),
'reason': 'test',
}
with pytest.raises(ex) as ex_info:
utils.raise_http_exception(mock_response)
assert ex_info.value.args == (
mock_response.json.return_value,
mock_response,
)
| mit |
sabas/openaddresses | scripts/at/split.py | 38 | 1591 | # -*- coding: utf-8 -*-
import __future__
import csv, sys, json, copy, datetime, time
def main(address_filename, street_filename):
timestamp = datetime.datetime.now().strftime('%Y%m%d')
streets = {}
with open(street_filename) as f:
reader = csv.reader(f, delimiter=';')
next(reader)
for row in reader:
streets[row[0]] = row[1].strip()
writers = {}
pts = {}
with open(address_filename) as f:
reader = csv.reader(f, delimiter=';')
headers = next(reader) + ['STRASSE']
for row in reader:
srs = row[17].strip()
if not srs in writers:
writers[srs] = csv.writer(open('at-{}-{}.csv'.format(srs, timestamp), 'w'))
writers[srs].writerow(headers)
writers[srs].writerow(row + [streets.get(row[4].strip(), '')])
template = {}
with open('at_source.json', 'r') as f:
template = json.load(f)
for srs in writers:
source = copy.deepcopy(template)
source['data'] = 'http://data.openaddresses.io/cache/at-{}.zip'.format(timestamp)
source['conform']['srs'] = 'EPSG:{}'.format(srs)
source['conform']['file'] = 'at-{}-{}.csv'.format(srs, timestamp)
source['attribution'] = '© Austrian address register, date data from {}'.format(datetime.datetime.now().isoformat().split('T')[0])
with open('at-{}.json'.format(srs), 'w') as f:
json.dump(source, f, indent=4)
print(timestamp)
if __name__ == '__main__':
main(address_filename=sys.argv[1], street_filename=sys.argv[2]) | bsd-3-clause |
valkyriesavage/invenio | modules/webbasket/lib/webbasket_templates.py | 1 | 179905 | ## This file is part of Invenio.
## Copyright (C) 2005, 2006, 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.
""" Templating for webbasket module """
__revision__ = "$Id$"
import cgi
from invenio.messages import gettext_set_language
from invenio.webbasket_config import \
CFG_WEBBASKET_CATEGORIES, \
CFG_WEBBASKET_SHARE_LEVELS, \
CFG_WEBBASKET_DIRECTORY_BOX_NUMBER_OF_COLUMNS
from invenio.webmessage_mailutils import email_quoted_txt2html, \
email_quote_txt, \
escape_email_quoted_text
from invenio.htmlutils import get_html_text_editor
from invenio.config import \
CFG_SITE_URL, \
CFG_SITE_SECURE_URL, \
CFG_SITE_LANG, \
CFG_WEBBASKET_MAX_NUMBER_OF_DISPLAYED_BASKETS, \
CFG_WEBBASKET_USE_RICH_TEXT_EDITOR
from invenio.webuser import get_user_info
from invenio.dateutils import convert_datetext_to_dategui
class Template:
"""Templating class for webbasket module"""
######################## General interface ################################
def tmpl_create_directory_box(self,
category, topic,
(grpid, group_name),
bskid,
(personal_info, personal_baskets_info),
(group_info, group_baskets_info),
public_info,
ln):
"""Template for the directory-like menu.
@param category: the selected category
@param topic: the selected topic (optional)
@param (grpid, groupname): the id and name of the selected group (optional)
@param bskid: the id of the selected basket (optional)
@param (personal_info, personal_baskets_info): personal baskets data
@param (group_info, group_baskets_info): group baskets data
@param public_info: public baskets data
@param ln: language"""
_ = gettext_set_language(ln)
def __calculate_prettify_name_char_limit(nb_baskets, max_chars=45, nb_dots=3):
"""Private function. Calculates the char_limit to be fed to the
prettify_name function according to the max_chars limit and the nb_dots."""
# Let's do some initial calculations:
D = nb_dots
B = nb_baskets
M = max_chars
# some assisting abbreviations
Y = ( B > 3 and 2 or B - 1 )
Z = ( B > 3 and 5 or 0 )
# and the desired result
X = ( ( M - Z - ( ( 2 + D ) * Y ) - D ) / ( Y + 1 ) )
return X
if not personal_info and not group_info and not public_info:
return """
%(no_baskets_label)s
<br /><br />
%(create_basket_label)s""" % \
{'no_baskets_label': _('You have no personal or group baskets or are subscribed to any public baskets.'),
'create_basket_label': _('You may want to start by %(x_url_open)screating a new basket%(x_url_close)s.') % \
{'x_url_open': '<a href="%s/yourbaskets/create_basket?ln=%s">' % (CFG_SITE_URL, ln),
'x_url_close': '</a>'}}
## Firstly, create the tabs area.
if personal_info:
## If a specific topic is selected display the name of the topic
## and the options on it.
if personal_baskets_info:
personalbaskets_link = """<a href="%(url)s/yourbaskets/display?category=%(category)s&ln=%(ln)s">%(label)s</a>""" % \
{'url': CFG_SITE_URL,
'category': CFG_WEBBASKET_CATEGORIES['PRIVATE'],
'ln': ln,
'label': _('Personal baskets')}
topic_link = """<a href="%(url)s/yourbaskets/display?category=%(category)s&topic=%(topic)s&ln=%(ln)s">%(label)s</a>""" % \
{'url': CFG_SITE_URL,
'category': CFG_WEBBASKET_CATEGORIES['PRIVATE'],
'topic': topic,
'ln': ln,
'label': cgi.escape(topic, True)}
go_back_link = """<a href="%(url)s/yourbaskets/display?ln=%(ln)s"><img src="%(url)s/img/%(img)s" />%(label)s</a>""" % \
{'url': CFG_SITE_URL,
'ln': ln,
'img': 'wb-go-back.png',
'label': _('Back to Your Baskets')}
create_basket_link = """<a href="%(url)s/yourbaskets/create_basket?topic=%(topic)s&ln=%(ln)s"><img src="%(url)s/img/%(img)s" />%(label)s</a>""" % \
{'url': CFG_SITE_URL,
'topic': cgi.escape(topic, True),
'ln': ln,
'img': 'wb-create-basket.png',
'label': _('Create basket')}
edit_topic_link = """<a href="%(url)s/yourbaskets/edit_topic?topic=%(topic)s&ln=%(ln)s"><img src="%(url)s/img/%(img)s" />%(label)s</a>""" % \
{'url': CFG_SITE_URL,
'topic': cgi.escape(topic, True),
'ln': ln,
'img': 'wb-edit-topic.png',
'label': _('Edit topic')}
personal_tab = """
<td class="bsk_directory_box_nav_tab_content">
%(personalbaskets_link)s > %(topic_link)s
</td>
<td class="bsk_directory_box_nav_tab_options">
%(go_back)s
%(create_basket)s
%(edit_topic)s
</td>""" % {'topic_link': topic_link,
'personalbaskets_link': personalbaskets_link,
'go_back': go_back_link,
'create_basket': create_basket_link,
'edit_topic': edit_topic_link}
## If no specific topic is selected display the personal baskets tab.
else:
personal_tab = """
<td class="%(class)s">
<a href="%(url)s/yourbaskets/display?category=%(category)s&ln=%(ln)s">%(label)s</a>
</td>""" % {'class': category == CFG_WEBBASKET_CATEGORIES['PRIVATE'] \
and "bsk_directory_box_tab_content_selected" \
or "bsk_directory_box_tab_content",
'url': CFG_SITE_URL,
'category': CFG_WEBBASKET_CATEGORIES['PRIVATE'],
'ln': ln,
'label': _('Personal baskets')}
else:
personal_tab = """
<td class="%(class)s">
%(label)s
</td>""" % {'class': 'bsk_directory_box_tab_content_inactive',
'label': _('Personal baskets')}
if group_info:
## If a specific group is selected display the name of the group
## and the options on it.
if group_baskets_info:
groupbaskets_link = """<a href="%(url)s/yourbaskets/display?category=%(category)s&ln=%(ln)s">%(label)s</a>""" % \
{'url': CFG_SITE_URL,
'category': CFG_WEBBASKET_CATEGORIES['GROUP'],
'ln': ln,
'label': _('Group baskets')}
group_link = """<a href="%(url)s/yourbaskets/display?category=%(category)s&group=%(grpid)i&ln=%(ln)s">%(label)s</a>""" % \
{'url': CFG_SITE_URL,
'category': CFG_WEBBASKET_CATEGORIES['GROUP'],
'grpid': grpid,
'ln': ln,
'label': group_name}
go_back_link = """<a href="%(url)s/yourbaskets/display?ln=%(ln)s"><img src="%(url)s/img/%(img)s" />%(label)s</a>""" % \
{'url': CFG_SITE_URL,
'ln': ln,
'img': 'wb-go-back.png',
'label': _('Back to Your Baskets')}
group_tab = """
<td class="bsk_directory_box_nav_tab_content">
%(groupbaskets_link)s > %(group_link)s
</td>
<td class="bsk_directory_box_nav_tab_options">
%(go_back)s
</td>""" % {'groupbaskets_link': groupbaskets_link,
'group_link': group_link,
'go_back': go_back_link}
## If no specific group is selected display the group baskets tab.
else:
group_tab = """
<td class="%(class)s">
<a href="%(url)s/yourbaskets/display?category=%(category)s&ln=%(ln)s">%(label)s</a>
</td>""" % {'class': category == CFG_WEBBASKET_CATEGORIES['GROUP'] \
and "bsk_directory_box_tab_content_selected" \
or "bsk_directory_box_tab_content",
'url': CFG_SITE_URL,
'category': CFG_WEBBASKET_CATEGORIES['GROUP'],
'ln': ln,
'label': _('Group baskets')}
else:
group_tab = """
<td class="%(class)s">
%(label)s
</td>""" % {'class': 'bsk_directory_box_tab_content_inactive',
'label': _('Group baskets')}
if public_info:
## Display the public baskets tab.
public_tab = """
<td class="%(class)s">
<a href="%(url)s/yourbaskets/display?category=%(category)s&ln=%(ln)s">%(label)s</a>
</td>""" % {'class': category == CFG_WEBBASKET_CATEGORIES['EXTERNAL'] \
and "bsk_directory_box_tab_content_selected" \
or "bsk_directory_box_tab_content",
'url': CFG_SITE_URL,
'category': CFG_WEBBASKET_CATEGORIES['EXTERNAL'],
'ln': ln,
'label': _('Public baskets')}
else:
public_tab = """
<td class="%(class)s">
%(label)s
</td>""" % {'class': 'bsk_directory_box_tab_content_inactive',
'label': _('Public baskets')}
## If a specific topic is selected display the name of the topic
## and the options on it.
if personal_baskets_info:
tabs = """
<table cellspacing="0px" cellpadding="0px" class="bsk_directory_box_tabs">
<tr>%s
</tr>
</table>""" % (personal_tab,)
## If a specific group is selected display the name of the group
## and the options on it.
elif group_baskets_info:
tabs = """
<table cellspacing="0px" cellpadding="0px" class="bsk_directory_box_tabs">
<tr>
%s
</tr>
</table>""" % (group_tab,)
## If only a sepcific category is selected (or eveb none) display
## all the available tabs (selected, normal, inactive).
else:
tabs = """
<table cellspacing="0px" cellpadding="0px" class="bsk_directory_box_tabs">
<tr>
<td class="bsk_directory_box_tab_separator">
</td>
%(personal_tab)s
<td class="bsk_directory_box_tab_separator">
</td>
%(group_tab)s
<td class="bsk_directory_box_tab_separator">
</td>
%(public_tab)s
<td class="bsk_directory_box_tab_separator_end">
</td>
</tr>
</table>""" % {'personal_tab': personal_tab,
'group_tab': group_tab,
'public_tab': public_tab}
## Secondly, create the content.
if personal_info and category==CFG_WEBBASKET_CATEGORIES['PRIVATE']:
content_list = []
## If a specific topic is selected create a list of baskets for that topic.
if personal_baskets_info:
for basket in personal_baskets_info:
basket_id = basket[0]
basket_name = basket[1]
nb_items = basket[4]
basket_link = """%(opening_tag)s<a href="%(url)s/yourbaskets/display?category=%(category)s&topic=%(topic)s&bskid=%(bskid)i&ln=%(ln)s" title="%(title_name)s">%(basket_name)s</a>%(closing_tag)s <span class="bsk_directory_box_content_list_number_of">(%(nb_items)i)</span>""" % \
{'opening_tag': basket_id==bskid and "<em>" or "",
'closing_tag': basket_id==bskid and "</em>" or "",
'url': CFG_SITE_URL,
'category': category,
'topic': cgi.escape(topic, True),
'bskid': basket_id,
'ln': ln,
'title_name': cgi.escape(basket_name, True),
'basket_name': cgi.escape(prettify_name(basket_name, 27), True),
'nb_items': nb_items}
content_list_item = """
%(basket_link)s""" % {'basket_link': basket_link}
content_list.append(content_list_item)
## If no specific topic is selected create a list of topics with a preview of their baskets.
else:
for topic_and_baskets in personal_info:
topic_name = topic_and_baskets[0]
nb_baskets = topic_and_baskets[1]
topic_link = """<strong><a href="%(url)s/yourbaskets/display?category=%(category)s&topic=%(topic)s&ln=%(ln)s" title="%(title_name)s">%(topic_name)s</a></strong> <span class="bsk_directory_box_content_list_number_of">(%(nb_baskets)s)</span>""" % \
{'url': CFG_SITE_URL,
'category': category,
'topic': cgi.escape(topic_name, True),
'ln': ln,
'title_name': cgi.escape(topic_name, True),
'topic_name': cgi.escape(prettify_name(topic_name, 25), True),
'nb_baskets': nb_baskets}
baskets = eval(topic_and_baskets[2] + ',')
basket_links = ""
basket_links_list = []
for basket in baskets[:3]:
# TODO: adapt the prettify_name char_limit variable according to nb_baskets
basket_link = """<a href="%(url)s/yourbaskets/display?category=%(category)s&topic=%(topic)s&bskid=%(bskid)i&ln=%(ln)s" title="%(title_name)s">%(basket_name)s</a>""" % \
{'url': CFG_SITE_URL,
'category': category,
'topic': cgi.escape(topic_name, True),
'bskid': basket[0],
'ln': ln,
'title_name': cgi.escape(basket[1], True),
'basket_name': cgi.escape(prettify_name(basket[1], __calculate_prettify_name_char_limit(nb_baskets, 135/CFG_WEBBASKET_DIRECTORY_BOX_NUMBER_OF_COLUMNS)), True)}
basket_links_list.append(basket_link)
basket_links = ', '.join(basket_links_list)
if nb_baskets > 3:
basket_links += ", ..."
content_list_item = """
%(topic_link)s
<br />
<small>%(basket_links)s</small>""" % \
{'topic_link': topic_link,
'basket_links': basket_links}
content_list.append(content_list_item)
nb_cells = CFG_WEBBASKET_DIRECTORY_BOX_NUMBER_OF_COLUMNS
nb_items = len(content_list)
content_list.reverse()
content = """
<table cellspacing="0px" cellpadding="0px" align="center" width="100%">
<tr>"""
for i in range(nb_cells):
content += """
<td class="bsk_directory_box_content_list_cell" width="%s%%">""" % \
(100/nb_cells,)
nb_lines = (nb_items/nb_cells) + ((nb_items%nb_cells) > i and 1 or 0)
for j in range(nb_lines):
content += content_list.pop()
if j < (nb_lines-1):
content += personal_baskets_info and "<br />" or "<br /><br />"
content += """
</td>"""
content += """
</tr>
</table>"""
elif group_info and category==CFG_WEBBASKET_CATEGORIES['GROUP']:
content_list = []
## If a specific grpid is selected create a list of baskets for that group.
if group_baskets_info:
for basket in group_baskets_info:
basket_id = basket[0]
basket_name = basket[1]
nb_items = basket[4]
basket_link = """%(opening_tag)s<a href="%(url)s/yourbaskets/display?category=%(category)s&group=%(grpid)i&bskid=%(bskid)i&ln=%(ln)s" title="%(title_name)s">%(basket_name)s</a>%(closing_tag)s <span class="bsk_directory_box_content_list_number_of">(%(nb_items)i)</span>""" % \
{'opening_tag': basket_id==bskid and "<em>" or "",
'closing_tag': basket_id==bskid and "</em>" or "",
'url': CFG_SITE_URL,
'category': CFG_WEBBASKET_CATEGORIES['GROUP'],
'grpid': grpid,
'bskid': basket_id,
'ln': ln,
'title_name': cgi.escape(basket_name, True),
'basket_name': cgi.escape(prettify_name(basket_name, 27), True),
'nb_items': nb_items}
content_list_item = """
%(basket_link)s""" % {'basket_link': basket_link}
content_list.append(content_list_item)
## If no specific grpid is selected create a list of groups with a preview of their baskets.
else:
for group_and_baskets in group_info:
group_id = group_and_baskets[0]
group_name = group_and_baskets[1]
nb_baskets = group_and_baskets[2]
group_link = """<strong><a href="%(url)s/yourbaskets/display?category=%(category)s&group=%(group)i&ln=%(ln)s" title="%(title_name)s">%(group_name)s</a></strong> <span class="bsk_directory_box_content_list_number_of">(%(nb_baskets)s)</span>""" % \
{'url': CFG_SITE_URL,
'category': category,
'group': group_id,
'ln': ln,
'title_name': cgi.escape(group_name, True),
'group_name': cgi.escape(prettify_name(group_name, 25), True),
'nb_baskets': nb_baskets}
baskets = eval(group_and_baskets[3] + ',')
basket_links = ""
basket_links_list = []
for basket in baskets[:3]:
# TODO: adapt the prettify_name char_limit variable according to nb_baskets
basket_link = """<a href="%(url)s/yourbaskets/display?category=%(category)s&group=%(group)i&bskid=%(bskid)i&ln=%(ln)s" title="%(title_name)s">%(basket_name)s</a>""" % \
{'url': CFG_SITE_URL,
'category': category,
'group': group_id,
'bskid': basket[0],
'ln': ln,
'title_name': cgi.escape(basket[1], True),
'basket_name': cgi.escape(prettify_name(basket[1], __calculate_prettify_name_char_limit(nb_baskets, 135/CFG_WEBBASKET_DIRECTORY_BOX_NUMBER_OF_COLUMNS)), True)}
basket_links_list.append(basket_link)
basket_links = ', '.join(basket_links_list)
if nb_baskets > 3:
basket_links += ", ..."
content_list_item = """
%(group_link)s
<br />
<small>%(basket_links)s</small>""" % \
{'group_link': group_link,
'basket_links': basket_links}
content_list.append(content_list_item)
nb_cells = CFG_WEBBASKET_DIRECTORY_BOX_NUMBER_OF_COLUMNS
nb_items = len(content_list)
content_list.reverse()
content = """
<table cellspacing="0px" cellpadding="0px" align="center" width="100%">
<tr>"""
for i in range(nb_cells):
content += """
<td class="bsk_directory_box_content_list_cell" width="%s%%">""" % \
(100/nb_cells,)
nb_lines = (nb_items/nb_cells) + ((nb_items%nb_cells) > i and 1 or 0)
for j in range(nb_lines):
content += content_list.pop()
if j < (nb_lines-1):
#content += "<br /><br />"
content += group_baskets_info and "<br />" or "<br /><br />"
content += """
</td>"""
content += """
</tr>
</table>"""
elif public_info and category==CFG_WEBBASKET_CATEGORIES['EXTERNAL']:
content_list = []
for basket in public_info:
basket_id = basket[0]
basket_name = basket[1]
nb_items = basket[2]
basket_link = """<a href="%(url)s/yourbaskets/display?category=%(category)s&bskid=%(bskid)i&ln=%(ln)s" title="%(title_name)s">%(basket_name)s</a> <span class="bsk_directory_box_content_list_number_of">(%(nb_items)i)</span>""" % \
{'url': CFG_SITE_URL,
'category': category,
'bskid': basket_id,
'ln': ln,
'title_name': cgi.escape(basket_name, True),
'basket_name': cgi.escape(prettify_name(basket_name, 27), True),
'nb_items': nb_items}
content_list_item = """
%(basket_link)s""" % {'basket_link': basket_link}
content_list.append(content_list_item)
nb_cells = CFG_WEBBASKET_DIRECTORY_BOX_NUMBER_OF_COLUMNS
nb_items = len(content_list)
content_list.reverse()
content = """
<table cellspacing="0px" cellpadding="0px" align="center" width="100%">
<tr>"""
for i in range(nb_cells):
content += """
<td class="bsk_directory_box_content_list_cell" width="%s%%">""" % \
(100/nb_cells,)
nb_lines = (nb_items/nb_cells) + ((nb_items%nb_cells) > i and 1 or 0)
for j in range(nb_lines):
content += content_list.pop()
if j < (nb_lines-1):
content += "<br />"
content += """
</td>"""
content += """
</tr>
</table>"""
out = """
<table cellspacing="0px" cellpadding="0px" class="bsk_directory_box">
<tr>
<td width="100%%">
%(tabs)s
</td>
</tr>
<tr>
<td width="100%%">
<table cellspacing="0px" cellpadding="0px" class="bsk_directory_box_content">
<tr>
<td class="%(class)s">
%(content)s
</td>
</tr>
</table>
</td>
</tr>
</table>""" % {'class': ((category == CFG_WEBBASKET_CATEGORIES['PRIVATE'] and topic) or \
(category == CFG_WEBBASKET_CATEGORIES['GROUP'] and grpid)) and \
"bsk_directory_box_content_list_baskets" or \
"bsk_directory_box_content_list_topics_groups",
'tabs': tabs,
'content': content}
return out
def tmpl_create_search_box(self,
category="",
topic="",
grpid=0,
topic_list=(),
group_list=(),
number_of_public_baskets=0,
p="",
n=0,
ln=CFG_SITE_LANG):
"""EXPERIMENTAL UI"""
_ = gettext_set_language(ln)
action = """%s/yourbaskets/search""" % (CFG_SITE_URL,)
select_options = create_search_box_select_options(category,
topic,
grpid,
topic_list,
group_list,
number_of_public_baskets,
ln)
out = """
<table cellspacing="0px" cellpadding="5px" class="bsk_search_box">
<form name="search_baskets" action="%(action)s" method="get">
<thead>
<tr>
<td colspan="4">
<small><strong>%(search_for_label)s:</strong><small>
</td>
</tr>
</thead>
<tbody>
<tr>
<td>
<input name="p" value="%(p)s" type="text" />
</td>
<td>
<small><strong>in</strong><small>
</td>
<td>
<select name="b">%(select_options)s
</select>
</td>
<td>
<input class="formbutton" type="submit" value="Search" />
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="n" value="1"%(notes_checked)s />
<small>%(notes_label)s</small>
</td>
</tr>
</tbody>
<input type="hidden" name="ln" value="%(ln)s" />
</form>
</table>""" % {'action': action,
'search_for_label': _('Search baskets for'),
'notes_label': _('Search also in notes (where allowed)'),
'notes_checked': n and ' checked="checked"' or '',
'p': p,
'select_options': select_options,
'ln': cgi.escape(ln, True)}
return out
def tmpl_search_results(self,
personal_search_results={},
total_no_personal_search_results=0,
group_search_results={},
total_no_group_search_results=0,
public_search_results={},
total_no_public_search_results=0,
all_public_search_results={},
total_no_all_public_search_results=0,
ln=CFG_SITE_LANG):
"""Template for the search results."""
_ = gettext_set_language(ln)
out = """
<table cellspacing="0px" cellpadding="5px" class="bsk_search_box">"""
total_no_search_results = total_no_personal_search_results + \
total_no_group_search_results + \
total_no_public_search_results + \
total_no_all_public_search_results
if total_no_search_results:
# INFO: Results overview is disabled for now.
# Remove "if False:" when needed again.
if False:
out += """
<tr>
<td style="border-top: 1px #fc0 solid; border-bottom: 1px #fc0 dotted; background-color: #ffc">
<strong>%(results_overview_label)s:</strong> %(items_found_label)s
</td>
</tr>""" % {'results_overview_label': _('Results overview'),
'items_found_label': _('%i items found') % total_no_search_results}
if total_no_personal_search_results:
out += """
<tr>
<td>
<a href="#%(personal_baskets_name)s">%(personal_baskets_label)s</a>: %(items_found_label)s
</td>
</tr>""" % {'personal_baskets_label': _('Personal baskets'),
'personal_baskets_name': "P",
'items_found_label': _('%i items found') % total_no_personal_search_results}
if total_no_group_search_results:
out += """
<tr>
<td>
<a href="#%(group_baskets_name)s">%(group_baskets_label)s<a/>: %(items_found_label)s
</td>
</tr>""" % {'group_baskets_label': _('Group baskets'),
'group_baskets_name': "G",
'items_found_label': _('%i items found') % total_no_group_search_results}
if total_no_public_search_results:
out += """
<tr>
<td>
<a href="#%(public_baskets_name)s">%(public_baskets_label)s</a>: %(items_found_label)s
</td>
</tr>""" % {'public_baskets_label': _('Public baskets'),
'public_baskets_name': "E",
'items_found_label': _('%i items found') % total_no_public_search_results}
if total_no_all_public_search_results:
out += """
<tr>
<td>
<a href="#%(all_public_baskets_name)s">%(all_public_baskets_label)s</a>: %(items_found_label)s
</td>
</tr>""" % {'all_public_baskets_label': _('All public baskets'),
'all_public_baskets_name': "A",
'items_found_label': _('%i items found') % total_no_all_public_search_results}
out += """
<tr>
<td>
</td>
</tr>"""
else:
out += """
<tr>
<td>
%(no_items_found_label)s
</td>
</tr>""" % {'no_items_found_label': _('No items found.')}
if total_no_personal_search_results:
out += """
<tr>
<td style="border-top: 1px #fc0 solid; border-bottom: 1px #fc0 dotted; background-color: #ffc">
<a name="%(personal_baskets_name)s"></a><strong>%(personal_baskets_label)s:</strong> %(items_found_label)s
</td>
</tr>""" % {'personal_baskets_label': _('Personal baskets'),
'personal_baskets_name': "P",
'items_found_label': _('%i items found') % total_no_personal_search_results}
for personal_search_result in personal_search_results.iteritems():
basket_link = """<a href="%(url)s/yourbaskets/display?category=%(category)s&topic=%(topic)s&bskid=%(bskid)i&ln=%(ln)s" title="%(title_name)s">%(basket_name)s</a>""" % \
{'url': CFG_SITE_URL,
'category': CFG_WEBBASKET_CATEGORIES['PRIVATE'],
'topic': cgi.escape(personal_search_result[1][1], True),
'bskid': personal_search_result[0],
'ln': ln,
'title_name': cgi.escape(personal_search_result[1][0], True),
'basket_name': cgi.escape(personal_search_result[1][0], True)}
out += """
<tr>
<td>
%(in_basket_label)s: %(items_found)s
</td>
</tr>""" % {'in_basket_label': _('In %(x_linked_basket_name)s') % \
{'x_linked_basket_name': basket_link},
'items_found': _('%i items found') % personal_search_result[1][2]}
out += """
<tr>
<td>
</td>
</tr>"""
if total_no_group_search_results:
out += """
<tr>
<td style="border-top: 1px #fc0 solid; border-bottom: 1px #fc0 dotted; background-color: #ffc">
<a name="%(group_baskets_name)s"></a><strong>%(group_baskets_label)s:</strong> %(items_found_label)s
</td>
</tr>""" % {'group_baskets_label': _('Group baskets'),
'group_baskets_name': "G",
'items_found_label': _('%i items found') % total_no_group_search_results}
for group_search_result in group_search_results.iteritems():
basket_link = """<a href="%(url)s/yourbaskets/display?category=%(category)s&group=%(group)i&bskid=%(bskid)i&ln=%(ln)s" title="%(title_name)s">%(basket_name)s</a>""" % \
{'url': CFG_SITE_URL,
'category': CFG_WEBBASKET_CATEGORIES['GROUP'],
'group': group_search_result[1][1],
'bskid': group_search_result[0],
'ln': ln,
'title_name': cgi.escape(group_search_result[1][0], True),
'basket_name': cgi.escape(group_search_result[1][0], True)}
out += """
<tr>
<td>
%(in_basket_label)s: %(items_found)s
</td>
</tr>""" % {'in_basket_label': _('In %(x_linked_basket_name)s') % \
{'x_linked_basket_name': basket_link},
'items_found': _('%i items found') % group_search_result[1][3]}
out += """
<tr>
<td>
</td>
</tr>"""
if total_no_public_search_results:
out += """
<tr>
<td style="border-top: 1px #fc0 solid; border-bottom: 1px #fc0 dotted; background-color: #ffc">
<a name="%(public_baskets_name)s"></a><strong>%(public_baskets_label)s:</strong> %(items_found_label)s
</td>
</tr>""" % {'public_baskets_label': _('Public baskets'),
'public_baskets_name': "E",
'items_found_label': _('%i items found') % total_no_public_search_results}
for public_search_result in public_search_results.iteritems():
basket_link = """<a href="%(url)s/yourbaskets/display?category=%(category)s&bskid=%(bskid)i&ln=%(ln)s" title="%(title_name)s">%(basket_name)s</a>""" % \
{'url': CFG_SITE_URL,
'category': CFG_WEBBASKET_CATEGORIES['EXTERNAL'],
'bskid': public_search_result[0],
'ln': ln,
'title_name': cgi.escape(public_search_result[1][0], True),
'basket_name': cgi.escape(public_search_result[1][0], True)}
out += """
<tr>
<td>
%(in_basket_label)s: %(items_found)s
</td>
</tr>""" % {'in_basket_label': _('In %(x_linked_basket_name)s') % \
{'x_linked_basket_name': basket_link},
'items_found': _('%i items found') % public_search_result[1][1]}
out += """
<tr>
<td>
</td>
</tr>"""
if total_no_all_public_search_results:
out += """
<tr>
<td style="border-top: 1px #fc0 solid; border-bottom: 1px #fc0 dotted; background-color: #ffc">
<a name="%(all_public_baskets_name)s"></a><strong>%(all_public_baskets_label)s:</strong> %(items_found_label)s
</td>
</tr>""" % {'all_public_baskets_label': _('All public baskets'),
'all_public_baskets_name': "A",
'items_found_label': _('%i items found') % total_no_all_public_search_results}
for all_public_search_result in all_public_search_results.iteritems():
basket_link = """<a href="%(url)s/yourbaskets/display_public?bskid=%(bskid)i&ln=%(ln)s" title="%(title_name)s">%(basket_name)s</a>""" % \
{'url': CFG_SITE_URL,
'bskid': all_public_search_result[0],
'ln': ln,
'title_name': cgi.escape(all_public_search_result[1][0], True),
'basket_name': cgi.escape(all_public_search_result[1][0], True)}
out += """
<tr>
<td>
%(in_basket_label)s: %(items_found)s
</td>
</tr>""" % {'in_basket_label': _('In %(x_linked_basket_name)s') % \
{'x_linked_basket_name': basket_link},
'items_found': _('%i items found') % personal_search_result[1][2]}
out += """
<tr>
<td>
</td>
</tr>"""
out += """
</table>"""
return out
def tmpl_display(self,
directory='',
content='',
search_box='',
search_results=''):
"""Template for the generic display.
@param directory: the directory-like menu (optional)
@param content: content (of a basket) (optional)
@param search_box: the search form (optional)
@param search_results: the search results (optional)"""
display_items = []
if directory:
container_directory = """
<div id="bskcontainerdirectory">%s
</div>
""" % (directory,)
display_items.append(container_directory)
if content:
container_content = """
<div id="bskcontainercontent">%s
</div>
""" % (content,)
display_items.append(container_content)
if search_box:
container_search_box = """
<div id="bskcontainersearch">%s
</div>
""" % (search_box,)
display_items.append(container_search_box)
if search_results:
container_search_results = """
<div id="bskcontainersearch">%s
</div>
""" % (search_results,)
display_items.append(container_search_results)
display_separator= """
<div height="10px">
</div>
"""
display = display_separator.join(display_items)
out = """
<div id="bskcontainer">
%s
</div>""" % (display,)
return out
def tmpl_display_list_public_baskets(self,
all_public_baskets,
limit,
number_of_all_public_baskets,
sort,
asc,
nb_views_show_p=False,
ln=CFG_SITE_LANG):
"""Template for the list of public baskets.
@param all_public_baskets: tuple
(bskid, basket_name, owner_id, nickname, date_modification, nb_views, nb_items)
@param limit: display baskets from the incrementally numbered 'limit' and on
@param number_of_all_public_baskets: the number of all the public baskets
@param sort: 'name': sort by basket name
'views': sort by number of basket views
'nickname': sort by user nickname
'date': sort by basket modification date
'items': sort by number of basket items
@param asc: ascending sort or not
@param nb_views_show_p: show the views column or not
@param ln: language"""
_ = gettext_set_language(ln)
basket_name_label = _("Public basket")
owner_label = _("Owner")
date_modification_label = _("Last update")
nb_items_label = _("Items")
nb_views_label = _("Views")
if sort == "name":
if asc:
basket_name_sort_img = """<img src="%s/img/wb-sort-asc.gif" />""" % (CFG_SITE_URL,)
else:
basket_name_sort_img = """<img src="%s/img/wb-sort-desc.gif" />""" % (CFG_SITE_URL,)
else:
basket_name_sort_img = """<img src="%s/img/wb-sort-none.gif" />""" % (CFG_SITE_URL,)
if sort == "owner":
if asc:
owner_sort_img = """<img src="%s/img/wb-sort-asc.gif" />""" % (CFG_SITE_URL,)
else:
owner_sort_img = """<img src="%s/img/wb-sort-desc.gif" />""" % (CFG_SITE_URL,)
else:
owner_sort_img = """<img src="%s/img/wb-sort-none.gif" />""" % (CFG_SITE_URL,)
if sort == "date":
if asc:
date_modification_sort_img = """<img src="%s/img/wb-sort-asc.gif" />""" % (CFG_SITE_URL,)
else:
date_modification_sort_img = """<img src="%s/img/wb-sort-desc.gif" />""" % (CFG_SITE_URL,)
else:
date_modification_sort_img = """<img src="%s/img/wb-sort-none.gif" />""" % (CFG_SITE_URL,)
if sort == "items":
if asc:
nb_items_sort_img = """<img src="%s/img/wb-sort-asc.gif" />""" % (CFG_SITE_URL,)
else:
nb_items_sort_img = """<img src="%s/img/wb-sort-desc.gif" />""" % (CFG_SITE_URL,)
else:
nb_items_sort_img = """<img src="%s/img/wb-sort-none.gif" />""" % (CFG_SITE_URL,)
if sort == "views":
if asc:
nb_views_sort_img = """<img src="%s/img/wb-sort-asc.gif" />""" % (CFG_SITE_URL,)
else:
nb_views_sort_img = """<img src="%s/img/wb-sort-desc.gif" />""" % (CFG_SITE_URL,)
else:
nb_views_sort_img = """<img src="%s/img/wb-sort-none.gif" />""" % (CFG_SITE_URL,)
basket_name_sort = """<a href="%s/yourbaskets/list_public_baskets?limit=%i&sort=name&asc=%i&ln=%s">%s</a>""" % \
(CFG_SITE_URL, limit, not(asc), ln, basket_name_sort_img)
owner_sort = """<a href="%s/yourbaskets/list_public_baskets?limit=%i&sort=owner&asc=%i&ln=%s">%s</a>""" % \
(CFG_SITE_URL, limit, not(asc), ln, owner_sort_img)
date_modification_sort = """<a href="%s/yourbaskets/list_public_baskets?limit=%i&sort=date&asc=%i&ln=%s">%s</a>""" % \
(CFG_SITE_URL, limit, not(asc), ln, date_modification_sort_img)
nb_items_sort = """<a href="%s/yourbaskets/list_public_baskets?limit=%i&sort=items&asc=%i&ln=%s">%s</a>""" % \
(CFG_SITE_URL, limit, not(asc), ln, nb_items_sort_img)
nb_views_sort = """<a href="%s/yourbaskets/list_public_baskets?limit=%i&sort=views&asc=%i&ln=%s">%s</a>""" % \
(CFG_SITE_URL, limit, not(asc), ln, nb_views_sort_img)
baskets_html = ''
for (bskid, basket_name, owner_id, nickname, date_modification, nb_items, nb_views) in all_public_baskets:
if nickname:
display = nickname
else:
(owner_id, nickname, display) = get_user_info(owner_id)
webmessage_link = self.__create_webmessage_link(nickname, display, ln)
basket_link = """<a href="%s/yourbaskets/display_public?category=%s&bskid=%s&ln=%s">%s<a/>""" % \
(CFG_SITE_URL, CFG_WEBBASKET_CATEGORIES['EXTERNAL'], bskid, ln, cgi.escape(basket_name, True))
nb_views_td = """<td class="bsk_list_public_baskets_basket_right">%i</td>""" % (nb_views,)
baskets_html += """
<tr>
<td class="bsk_list_public_baskets_basket_left">%(basket_link)s</td>
<td class="bsk_list_public_baskets_basket_left">%(webmessage_link)s</td>
<td class="bsk_list_public_baskets_basket_left">%(date_modification)s</td>
<td class="bsk_list_public_baskets_basket_right">%(nb_items)i</td>
%(nb_views)s
</tr>""" % {'basket_link': basket_link,
'webmessage_link': webmessage_link,
'date_modification': date_modification,
'nb_items': nb_items,
'nb_views': nb_views_show_p and nb_views_td or ''}
if not all_public_baskets:
baskets_html = """
<tr>
<td colspan="%i">
%s
</td>
</tr>""" % (nb_views_show_p and 5 or 4,
_("There is currently no publicly accessible basket"))
footer = ''
if limit > CFG_WEBBASKET_MAX_NUMBER_OF_DISPLAYED_BASKETS:
limit_first = 1
page_first = """<a href="%s/yourbaskets/list_public_baskets?limit=%i&sort=%s&asc=%i&ln=%s"><img src="%s" /></a>""" % \
(CFG_SITE_URL, limit_first, sort, asc, ln, '/img/sb.gif')
footer += page_first
if limit > 0:
limit_previous = limit > CFG_WEBBASKET_MAX_NUMBER_OF_DISPLAYED_BASKETS \
and limit - CFG_WEBBASKET_MAX_NUMBER_OF_DISPLAYED_BASKETS + 1 \
or 1
page_previous = """<a href="%s/yourbaskets/list_public_baskets?limit=%i&sort=%s&asc=%i&ln=%s"><img src="%s" /></a>""" % \
(CFG_SITE_URL, limit_previous, sort, asc, ln, '/img/sp.gif')
footer += page_previous
display_from = limit + 1
display_to = limit + CFG_WEBBASKET_MAX_NUMBER_OF_DISPLAYED_BASKETS > number_of_all_public_baskets \
and number_of_all_public_baskets \
or limit + CFG_WEBBASKET_MAX_NUMBER_OF_DISPLAYED_BASKETS
footer += _('Displaying public baskets %(x_from)i - %(x_to)i out of %(x_total_public_basket)i public baskets in total.') % \
{'x_from': display_from, 'x_to': display_to, 'x_total_public_basket': number_of_all_public_baskets}
if limit < number_of_all_public_baskets - CFG_WEBBASKET_MAX_NUMBER_OF_DISPLAYED_BASKETS:
limit_next = limit + CFG_WEBBASKET_MAX_NUMBER_OF_DISPLAYED_BASKETS + 1
page_next = """<a href="%s/yourbaskets/list_public_baskets?limit=%i&sort=%s&asc=%i&ln=%s"><img src="%s" /></a>""" % \
(CFG_SITE_URL, limit_next, sort, asc, ln, '/img/sn.gif')
footer += page_next
if limit < number_of_all_public_baskets - ( 2 * CFG_WEBBASKET_MAX_NUMBER_OF_DISPLAYED_BASKETS ):
limit_last = number_of_all_public_baskets - CFG_WEBBASKET_MAX_NUMBER_OF_DISPLAYED_BASKETS + 1
page_last = """<a href="%s/yourbaskets/list_public_baskets?limit=%i&sort=%s&asc=%i&ln=%s"><img src="%s" /></a>""" % \
(CFG_SITE_URL, limit_last, sort, asc, ln, '/img/se.gif')
footer += page_last
if nb_views_show_p:
nb_views_label_td = """<td>%(nb_views_label)s %(nb_views_sort)s</td>""" % \
{'nb_views_label': nb_views_label,
'nb_views_sort': nb_views_sort}
out = """
<table class="bsk_list_public_baskets" cellpadding="5px">
<thead class="bsk_list_public_baskets_header">
<tr>
<td>%(basket_name_label)s %(basket_name_sort)s</td>
<td>%(owner_label)s %(owner_sort)s</td>
<td>%(date_modification_label)s %(date_modification_sort)s</td>
<td>%(nb_items_label)s %(nb_items_sort)s</td>
%(nb_views_label_td)s
</tr>
</thead>
<tfoot class="bsk_list_public_baskets_footer">
<tr>
<td colspan="%(colspan)s" style="text-align:center">%(footer)s</td>
</tr>
</tfoot>
<tbody>
%(baskets)s
</tbody>
</table>""" % {'basket_name_label': basket_name_label,
'basket_name_sort': basket_name_sort,
'owner_label': owner_label,
'owner_sort': owner_sort,
'date_modification_label': date_modification_label,
'date_modification_sort': date_modification_sort,
'nb_items_label': nb_items_label,
'nb_items_sort': nb_items_sort,
'nb_views_label_td': nb_views_show_p and nb_views_label_td or '',
'colspan': nb_views_show_p and 5 or 4,
'footer': footer,
'baskets': baskets_html}
return out
def tmpl_quote_comment_textual(self, title, uid, nickname, date, body, ln=CFG_SITE_LANG):
"""Return a comment in a quoted form (i.e. with '>' signs before each line)
@param title: title of comment to quote
@param uid: user id of user who posted comment to quote
@param nickname: nickname of user who posted comment to quote
@param date: date of post of comment to quote
@param body: body of comment to quote
@param ln: language"""
_ = gettext_set_language(ln)
if not(nickname):
nickname = get_user_info(uid)[2]
if title:
msg = _("%(x_title)s, by %(x_name)s on %(x_date)s:") % \
{'x_title': title, 'x_name': nickname, 'x_date': date}
else:
msg = _("%(x_name)s wrote on %(x_date)s:") % {'x_name': nickname, 'x_date': date}
msg += '\n\n'
msg += body
return email_quote_txt(msg)
def tmpl_quote_comment_html(self, title, uid, nickname, date, body, ln=CFG_SITE_LANG):
"""Return a comment in a quoted form (i.e. indented using HTML
table) for HTML output (i.e. in FCKeditor).
@param title: title of comment to quote
@param uid: user id of user who posted comment to quote
@param nickname: nickname of user who posted comment to quote
@param date: date of post of comment to quote
@param body: body of comment to quote
@param ln: language"""
_ = gettext_set_language(ln)
if not(nickname):
nickname = get_user_info(uid)[2]
if title:
msg = _("%(x_title)s, by %(x_name)s on %(x_date)s:") % \
{'x_title': title, 'x_name': nickname, 'x_date': date}
else:
msg = _("%(x_name)s wrote on %(x_date)s:") % {'x_name': nickname, 'x_date': date}
msg += '<br/><br/>'
msg += body
msg = email_quote_txt(text=msg)
msg = email_quoted_txt2html(text=msg)
return '<br/>' + msg + '<br/>'
def __tmpl_basket_box(self, img='', title=' ', subtitle=' ', body=''):
""" private function, display a basket/topic selection box """
out = """
<table class="bskbasket">
<thead class="bskbasketheader">
<tr>
<td class="bskactions">
<img src="%(logo)s" alt="%(label)s" />
</td>
<td class="bsktitle">
<b>%(label)s</b><br />
%(count)s
</td>
</tr>
</thead>
<tbody>
<tr>
<td colspan="2">
<table>%(basket_list)s
</table>
</td>
</tr>
</tbody>
</table>"""
out %= {'logo': img,
'label': title, 'count': subtitle,
'basket_list': body}
return out
def tmpl_create_box(self, new_basket_name='', new_topic_name='',
topics=[], selected_topic="",
ln=CFG_SITE_LANG):
"""Display a HTML box for creation of a new basket
@param new_basket_name: prefilled value (string)
@param new_topic_name: prefilled value (string)
@param topics: list of topics (list of strings)
@param selected_topic: preselected value for topic selection
@param ln: language"""
_ = gettext_set_language(ln)
topics_html = ''
#if selected_topic:
# try:
# selected_topic = topics.index(selected_topic)
# except:
# selected_topic = None
if topics:
topics = zip(topics, topics)
topics.insert(0, (-1, _("Select topic")))
topics_html = self.__create_select_menu('create_in_topic', topics, selected_topic)
create_html = """
<tr>
<td style="padding: 10 5 0 5;">%s</td>
<td style="padding: 10 5 0 0;">%s</td>
</tr>
<tr>
<td style="padding: 10 5 0 5;">%s</td>
<td style="padding: 10 5 0 0;"><input type="text" name="new_topic_name" value="%s"/></td>
</tr>
<tr>
<td style="padding: 10 5 0 5;">%s</td>
<td style="padding: 10 5 0 0;">
<input type="text" name="new_basket_name" value="%s"/>
</td>
</tr>""" % (topics_html != '' and _("Choose topic") or '', topics_html,
topics_html != '' and _("or create a new one") or _("Create new topic"), new_topic_name,
_("Basket name"), new_basket_name,)
return self.__tmpl_basket_box(img=CFG_SITE_URL + '/img/webbasket_create.png',
title=_("Create a new basket"),
body=create_html)
def tmpl_create_basket(self, new_basket_name='',
new_topic_name='', create_in_topic=None, topics=[],
ln=CFG_SITE_LANG):
"""Template for basket creation
@param new_basket_name: prefilled value (string)
@param new_topic_name: prefilled value (string)
@param topics: list of topics (list of strings)
@param create_in_topic: preselected value for topic selection
@param ln: language"""
_ = gettext_set_language(ln)
out = """
<form name="create_basket" action="%(action)s" method="post">
<input type="hidden" name="ln" value="%(ln)s" />
<div style="padding:10px;">
%(create_box)s
<input type="submit" value="%(label)s" class="formbutton"/>
</div>
</form>""" % {'action': CFG_SITE_URL + '/yourbaskets/create_basket',
'ln': ln,
'create_box': self.tmpl_create_box(new_basket_name=new_basket_name,
new_topic_name=new_topic_name,
topics=topics,
selected_topic=create_in_topic,
ln=ln),
'label': _("Create new basket")}
return out
############################ external sources ###########################
def tmpl_external_source_add_box(self,
title="",
desc="",
url="",
ln=CFG_SITE_LANG):
"""Template for adding external items."""
_ = gettext_set_language(ln)
# Instead of the rich editor we choose to use everytime a simple textarea
# because a rich text editor may already be used in the add to baskets
# page to anotate.
#desc_editor = get_html_text_editor(name="es_desc",
# content=desc,
# textual_content=desc,
# width="640px",
# height="100px",
# enabled=CFG_WEBBASKET_USE_RICH_TEXT_EDITOR,
# toolbar_set="WebComment")
desc_editor = """<textarea name="es_desc" style="width: 640px; height: 100px;">%(value)s</textarea>""" % \
{'value': desc}
out = """
<table class="bskbasket" width="100%%">
<thead>
<tr>
<td class="bskbasketheader">
<table>
<tr>
<td class="bskbasketheadertitle">
<strong>
%(header_label)s
</strong>
</td>
</table>
</td>
</tr>
</thead>
<tbody>
<tr>
<td style="padding: 10px;">
%(instructions_label)s:
</td>
</tr>
<tr>
<td style="padding: 10px;">
<p align="left">
<small>%(title_label)s:</small>
<br />
<input type="text" name="es_title" size="65" value="%(es_title)s" />
</p>
<p align="left">
<small>%(desc_label)s:</small>
<br />
%(desc_editor)s
</p>
<p align="left">
<small>%(url_label)s:</small>
<br />
<input type="text" name="es_url" size="65" value="%(es_url)s" />
<input type="hidden" name="colid" value="-1" />
</p>
</td>
</tr>
</tbody>
</table>""" % {'header_label': _('External item'),
'instructions_label': _('Provide a url for the external item you wish to add and fill in a title and description'),
'title_label': _('Title'),
'es_title': title,
'desc_label': _('Description'),
'desc_editor': desc_editor,
'url_label': _('URL'),
'es_url': url}
return out
########################## functions on baskets #########################
def tmpl_add(self,
recids=[],
category="",
bskid=0,
colid=0,
es_title="",
es_desc="",
es_url="",
note_body="",
personal_basket_list=(),
group_basket_list=(),
successful_add=False,
copy=False,
referer='',
ln=CFG_SITE_LANG):
"""Template for addding items to baskets."""
_ = gettext_set_language(ln)
if successful_add:
out = """
%(success_label)s.
<br /><br />
%(proceed_label)s""" % {'success_label': _('%i items have been successfully added to your basket') % (colid == -1 and 1 or len(recids)),
'proceed_label': _('Proceed to the %(x_url_open)sbasket%(x_url_close)s') % \
{'x_url_open': '<a href="%s/yourbaskets/display?category=%s&bskid=%i&ln=%s">' % (CFG_SITE_URL, category, bskid, ln),
'x_url_close': "</a>"}}
if referer:
if copy:
out += _(' or return to your %(x_url_open)sprevious basket%(x_url_close)s') % \
{'x_url_open': '<a href="%s">' % referer,
'x_url_close': '</a>'}
else:
out += _(' or return to your %(x_url_open)ssearch%(x_url_close)s') % \
{'x_url_open': '<a href="%s">' % referer,
'x_url_close': '</a>'}
else:
out += "."
return out
#If no recids were specified the page is asking which external item to add, so we remind to the user to use the search engine for internal items
out=""
if len(recids) == 0:
out += """
<table class="bskbasket">
<thead class="bskbasketheader">
<tr>
<td class="bskactions">
<img src="%(logo)s" alt="%(label)s" />
</td>
<td class="bsktitle">
<b>Adding items to your basket</b><br />
</td>
</tr>
</thead>
<tbody>
<tr>
<td colspan="2">
<table>
To add internal items to your basket please select them through the <a href="%(search_link)s">search page</a>
and use the "Add to basket" functionality. For any external resource please use the
"External item" form below.
</table>
</td>
</tr>
</tbody>
</table>"""
out %= {'logo': "%s/img/tick.gif"% (CFG_SITE_URL,),
'label':"tick",
'search_link':"%s"%(CFG_SITE_URL,) }
note_editor = get_html_text_editor(name="note_body",
content=note_body,
textual_content=note_body,
width="600px",
height="110px",
enabled=CFG_WEBBASKET_USE_RICH_TEXT_EDITOR,
toolbar_set="WebComment")
select_options = create_add_box_select_options(category,
bskid,
personal_basket_list,
group_basket_list,
ln)
hidden_recids = ""
for recid in recids:
hidden_recids += """
<input type="hidden" name="recid" value="%s" />""" % (recid,)
action = "%s/yourbaskets/add" % (CFG_SITE_URL,)
out += """
<form name="add_to_basket" action="%(action)s" method="post">""" % {'action': action}
if colid == -1:
out += self.tmpl_external_source_add_box(es_title, es_desc, es_url, ln)
out += """
<table class="bskbasket" width="100%%">
<thead>
<tr>
<td class="bskbasketheader">
<table>
<tr>
<td class="bskbasketheadertitle">
<strong>
%(header_label)s
</strong>
</td>
</table>
</td>
</tr>
</thead>
<tbody>
<tr>
<td style="padding: 10px;">
%(create_new_basket)s
<br />
</td>
</tr>
<tr>
<td style="padding: 10px;">
<p align="left">
<small>%(note_label)s:</small>
<br />
%(note_editor)s
</p>
</td>
</tr>
<tr>
<td style="padding: 10px;">
%(hidden_recids)s
<input type="hidden" name="colid" value="%(colid)s" />
<input type="hidden" name="copy" value="%(copy)i" />
<input type="hidden" name="referer" value="%(referer)s" />
<input type="submit" class="formbutton" value="%(add_label)s" />
<input type="button" class="nonsubmitbutton" value="%(cancel_label)s" onClick="window.location='/'" />
</td>
</tr>
</tbody>
</table>""" % {'header_label': _("Adding %i items to your baskets") % (colid == -1 and 1 or len(recids)),
'create_new_basket': _("Please choose a basket: %(x_basket_selection_box)s %(x_fmt_open)s(or %(x_url_open)screate a new one%(x_url_close)s first)%(x_fmt_close)s") % \
{'x_basket_selection_box': ' <select name="b">%s</select>' % select_options,
'x_url_open': '<a href="%s/yourbaskets/create_basket">' % CFG_SITE_URL,
'x_url_close': '</a>',
'x_fmt_open': '<br /><small>',
'x_fmt_close': '</small>'},
'note_label': len(recids) > 1 and _('Optionally, add a note to each one of these items') \
or _('Optionally, add a note to this item'),
'note_editor': note_editor,
'hidden_recids': hidden_recids,
'colid': colid,
'copy': copy and 1 or 0,
'referer': referer,
'add_label': _('Add items'),
'cancel_label': _('Cancel')}
out += """
</form>"""
return out
def tmpl_confirm_delete(self, bskid,
(nb_users, nb_groups, nb_alerts),
category=CFG_WEBBASKET_CATEGORIES['PRIVATE'],
selected_topic="", selected_group_id=0,
ln=CFG_SITE_LANG):
"""
display a confirm message
@param bskid: basket id
@param nb*: nb of users/groups/alerts linked to this basket
@param category: private, group or external baskets are selected
@param selected_topic: if private baskets, topic nb
@param selected_group_id: if group: group to display baskets of
@param ln: language
@return: html output
"""
_ = gettext_set_language(ln)
message = _("Are you sure you want to delete this basket?")
if nb_users:
message += '<p>' + _("%i users are subscribed to this basket.")% nb_users + '</p>'
if nb_groups:
message += '<p>' + _("%i user groups are subscribed to this basket.")% nb_groups + '</p>'
if nb_alerts:
message += '<p>' + _("You have set %i alerts on this basket.")% nb_alerts + '</p>'
out = """
<table class="confirmoperation">
<tr>
<td colspan="2" class="confirmmessage">
%(message)s
</td>
</tr>
<tr>
<td>
<form name="validate" action="%(url_ok)s" method="post">
<input type="hidden" name="confirmed" value="1" />
<input type="hidden" name="category" value="%(category)s" />
<input type="hidden" name="group" value="%(group)i" />
<input type="hidden" name="topic" value="%(topic)s" />
<input type="hidden" name="ln" value="%(ln)s" />
<input type="hidden" name="bskid" value="%(bskid)i" />
<input type="submit" value="%(yes_label)s" class="formbutton" />
</form>
</td>
<td>
<form name="cancel" action="%(url_cancel)s" method="get">
<input type="hidden" name="category" value="%(category)s" />
<input type="hidden" name="group" value="%(group)i" />
<input type="hidden" name="topic" value="%(topic)s" />
<input type="hidden" name="ln" value="%(ln)s" />
<input type="submit" value="%(no_label)s" class="formbutton" />
</form>
</td>
</tr>
</table>"""% {'message': message,
'bskid': bskid,
'url_ok': 'delete',
'url_cancel': 'display',
'category': category,
'topic': selected_topic,
'group': selected_group_id,
'ln':ln,
'yes_label': _("Yes"),
'no_label': _("Cancel")}
return out
def tmpl_edit(self, bskid, bsk_name, topic, topics, groups_rights, external_rights,
display_general=0, display_sharing=0, display_delete=0, ln=CFG_SITE_LANG):
"""Display interface for rights management over the given basket
@param group_rights: list of (group id, name, rights) tuples
@param external_rights: rights as defined in CFG_WEBBASKET_SHARE_LEVELS for public access.
@param display_general: display fields name and topic, used with personal baskets
@param display_sharing: display sharing possibilities
@param display_delete: display delete basket button
"""
_ = gettext_set_language(ln)
general_body = ''
if display_general:
general_body = """
<tr>
<td class="bskcontentcol">%s</td>
<td class="bskcontentcol"><input type="text" name="new_name" value="%s"/></td>
</tr>""" % (_("Basket name"), cgi.escape(bsk_name, 1))
#topics_selection = zip(range(len(topics)), topics)
topics_selection = zip(topics, topics)
topics_selection.insert(0, (-1, _("Choose topic")))
topics_body = """
<tr>
<td style="padding: 10 5 0 5;">%s</td>
<td style="padding: 10 5 0 0;">%s</td>
</tr>
<tr>
<td style="padding: 0 5 10 5;">%s</td>
<td style="padding: 0 5 10 0;"><input type="text" name="new_topic_name" />
</tr>""" % (_("Choose topic"),
self.__create_select_menu('new_topic', topics_selection, topic),
_("or create a new one"))
general_body += topics_body
general_box = self.__tmpl_basket_box(img=CFG_SITE_URL + '/img/webbasket_user.png',
title=_("General settings"),
body = general_body)
groups_body = ''
if display_sharing:
for (group_id, name, rights) in groups_rights:
groups_body += """
<tr>
<td>%s</td>
<td>%s</td>
</tr>""" % (name, self.__create_group_rights_selection_menu(group_id, rights, ln))
groups_body += """
<tr>
<td colspan="2">
<input type="submit" name="add_group" class="nonsubmitbutton" value="%s"/>
</td>
</tr>""" % _("Add group")
else:
groups_body = '<tr><td colspan="2">%s</td></tr>'
groups_body %= self.tmpl_create_guest_forbidden_box(ln)
groups_box = self.__tmpl_basket_box(img=CFG_SITE_URL + '/img/webbasket_usergroup.png',
title=_("Manage group rights"),
body=groups_body)
if display_sharing:
external_body = """
<tr>
<td>%s</td>
</tr>""" % self.__create_rights_selection_menu('external', external_rights, ln)
else:
external_body = '<tr><td colspan="2">%s</td></tr>'
external_body %= self.tmpl_create_guest_forbidden_box(ln)
external_box = self.__tmpl_basket_box(img=CFG_SITE_URL + '/img/webbasket_world.png',
title=_("Manage global sharing rights"),
body=external_body)
delete_button = ''
if display_delete:
delete_button = '<input type="submit" class="nonsubmitbutton" name="delete" value="%s" />'
delete_button %= _("Delete basket")
out = """
<form name="edit" action="%(action)s" method="post">
<p>%(label)s</p>
<input type="hidden" name="ln" value="%(ln)s" />
<input type="hidden" name="bskid" value="%(bskid)i" />
<input type="hidden" name="topic" value ="%(topic)s" />
<table>
<tr>
<td colspan="3">%(general)s</td>
</tr>
<tr>
<td colspan="3">%(groups)s</td>
</tr>
<tr>
<td colspan="3">%(external)s</td>
</tr>
<tr>
<td><input type="submit" class="formbutton" name="submit" value="%(submit_label)s" /></td>
<td><input type="submit" class="nonsubmitbutton" name="cancel" value="%(cancel_label)s" /></td>
<td>%(delete_button)s</td>
</tr>
</table>
</form>""" % {'label': _('Editing basket %(x_basket_name)s') % \
{'x_basket_name': cgi.escape(bsk_name)},
'action': CFG_SITE_URL + '/yourbaskets/edit',
'ln': ln,
'topic': topic,
'bskid': bskid,
'general': general_box,
'groups': groups_box,
'external': external_box,
'submit_label': _("Save changes"),
'cancel_label': _("Cancel"),
'delete_button': delete_button}
return out
def tmpl_edit_topic(self, topic, display_general=0, display_delete=0, ln=CFG_SITE_LANG):
"""Display interface for topic editing.
@param display_general: display topic name
@param display_delete: display delete topic button
"""
_ = gettext_set_language(ln)
general_body = ''
if not topic:
general_body = """<div class="important" style="padding: 10px;">%s</div>"""
general_body %= ("You must provide a valid topic name.",)
display_general = False
if display_general:
general_body = """
<tr>
<td>%s</td>
<td><input type="text" name="new_name" value="%s"/></td>
</tr>""" % (_("Topic name"), cgi.escape(topic, True))
#<td class="bskcontentcol">%s</td>
#<td class="bskcontentcol"><input type="text" name="new_name" value="%s"/></td>
general_box = self.__tmpl_basket_box(img=CFG_SITE_URL + '/img/webbasket_user.png',
title=_("General settings"),
body = general_body)
delete_button = ''
display_delete = False
if display_delete:
delete_button = '<input type="submit" class="nonsubmitbutton" name="delete" value="%s" />'
delete_button %= _("Delete basket")
out = """
<form name="edit" action="%(action)s" method="post">
<p>%(label)s</p>
<input type="hidden" name="ln" value="%(ln)s" />
<input type="hidden" name="topic" value ="%(topic)s" />
<table>
<tr>
<td colspan="3">%(general)s</td>
</tr>
<tr>
<td><input type="submit" class="formbutton" name="submit" value="%(submit_label)s" /></td>
<td><input type="submit" class="nonsubmitbutton" name="cancel" value="%(cancel_label)s" /></td>
<td>%(delete_button)s</td>
</tr>
</table>
</form>""" % {'label': _('Editing topic: %(x_topic_name)s') % {'x_topic_name': cgi.escape(topic, True)},
'action': CFG_SITE_URL + '/yourbaskets/edit_topic',
'ln': ln,
'topic': cgi.escape(topic, True),
'general': general_box,
'submit_label': _("Save changes"),
'cancel_label': _("Cancel"),
'delete_button': delete_button}
return out
def __create_rights_selection_menu(self, name, current_rights, ln=CFG_SITE_LANG):
"""Private function. create a drop down menu for selection of rights
@param name: name of menu (for HTML name attribute)
@param current_rights: rights as defined in CFG_WEBBASKET_SHARE_LEVELS
@param ln: language
"""
_ = gettext_set_language(ln)
elements = [('NO', _("No rights")),
(CFG_WEBBASKET_SHARE_LEVELS['READITM'],
_("View records")),
(CFG_WEBBASKET_SHARE_LEVELS['READCMT'],
'... ' + _("and") + ' ' + _("view comments")),
(CFG_WEBBASKET_SHARE_LEVELS['ADDCMT'],
'... ' + _("and") + ' ' + _("add comments"))]
return self.__create_select_menu(name, elements, current_rights)
def __create_group_rights_selection_menu(self, group_id, current_rights, ln=CFG_SITE_LANG):
"""Private function. create a drop down menu for selection of rights
@param current_rights: rights as defined in CFG_WEBBASKET_SHARE_LEVELS
@param ln: language
"""
_ = gettext_set_language(ln)
elements = [(str(group_id) + '_' + 'NO', _("No rights")),
(str(group_id) + '_' + CFG_WEBBASKET_SHARE_LEVELS['READITM'],
_("View records")),
(str(group_id) + '_' + CFG_WEBBASKET_SHARE_LEVELS['READCMT'],
'... ' + _("and") + ' ' + _("view notes")),
(str(group_id) + '_' + CFG_WEBBASKET_SHARE_LEVELS['ADDCMT'],
'... ' + _("and") + ' ' + _("add notes")),
(str(group_id) + '_' + CFG_WEBBASKET_SHARE_LEVELS['ADDITM'],
'... ' + _("and") + ' ' + _("add records")),
(str(group_id) + '_' + CFG_WEBBASKET_SHARE_LEVELS['DELCMT'],
'... ' + _("and") + ' ' + _("delete notes")),
(str(group_id) + '_' + CFG_WEBBASKET_SHARE_LEVELS['DELITM'],
'... ' + _("and") + ' ' + _("remove records")),
(str(group_id) + '_' + CFG_WEBBASKET_SHARE_LEVELS['MANAGE'],
'... ' + _("and") + ' ' + _("manage sharing rights"))
]
return self.__create_select_menu('groups', elements, str(group_id) + '_' + current_rights)
def tmpl_add_group(self, bskid, selected_topic, groups=[], ln=CFG_SITE_LANG):
"""
return form for selection of groups.
@param bskid: basket id (int)
@param selected_topic: topic currently displayed (int)
@param groups: list of tuples (group id, group name)
@param ln: language
"""
_ = gettext_set_language(ln)
if len(groups):
groups_body = """
<tr>
<td>%s</td>
</tr>""" % self.__create_select_menu('new_group', groups, selected_key=None)
else:
groups_body = """
<tr>
<td>%s</td>
</tr>""" % _("You are not a member of a group.")
groups_box = self.__tmpl_basket_box(img=CFG_SITE_URL + '/img/webbasket_usergroup.png',
title=_("Add group"),
body=groups_body)
out = """
<form name="add_group" action="%(action)s" method="post">
<p>%(label)s</p>
<input type="hidden" name="ln" value="%(ln)s" />
<input type="hidden" name="bskid" value="%(bskid)i" />
<input type="hidden" name="topic" value ="%(topic)s" />
<table style="width:100%%;">
<tr>
<td style="width:50%%;vertical-align:top;">%(groups)s</td>
<td style="width:50%%;vertical-align:top;"></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" class="formbutton" name="group_cancel" value="%(cancel_label)s" />
<input type="submit" class="formbutton" name="add_group" value="%(submit_label)s" />
</td>
</tr>
</table>
</form>""" % {'label': _('Sharing basket to a new group'),
'action': CFG_SITE_URL + '/yourbaskets/edit',
'ln': ln,
'topic': selected_topic,
'bskid': bskid,
'groups': groups_box,
'cancel_label': _("Cancel"),
'submit_label': _("Add group")}
return out
def tmpl_personal_baskets_selection_box(self,
baskets=[],
select_box_name='baskets',
selected_bskid=None,
ln=CFG_SITE_LANG):
"""return an HTML popupmenu
@param baskets: list of (bskid, bsk_name, bsk_topic) tuples
@param select_box_name: name that will be used for the control
@param selected_bskid: id of the selcte basket, use None for no selection
@param ln: language"""
_ = gettext_set_language(ln)
elements = [(0, '- ' + _("no basket") + ' -')]
for (bskid, bsk_name, bsk_topic) in baskets:
elements.append((bskid, bsk_topic + ' > ' + bsk_name))
return self.__create_select_menu(select_box_name, elements, selected_bskid)
def tmpl_create_guest_warning_box(self, ln=CFG_SITE_LANG):
"""return html warning box for non registered users"""
_ = gettext_set_language(ln)
message = _("You are logged in as a guest user, so your baskets will disappear at the end of the current session.") + ' '
message += _("If you wish you can %(x_url_open)slogin or register here%(x_url_close)s.") %\
{'x_url_open': '<a href="' + CFG_SITE_SECURE_URL + '/youraccount/login?ln=' + ln + '">',
'x_url_close': '</a>'}
out = """
<table class="errorbox">
<tr>
<th class="errorboxheader">%s</th>
</tr>
</table>"""
return out % message
def tmpl_create_guest_forbidden_box(self, ln=CFG_SITE_LANG):
"""return html warning box for non registered users"""
_ = gettext_set_language(ln)
message = _("This functionality is forbidden to guest users.") + ' '
message += _("If you wish you can %(x_url_open)slogin or register here%(x_url_close)s.") %\
{'x_url_open': '<a href="' + CFG_SITE_SECURE_URL + '/youraccount/login?ln=' + ln + '">',
'x_url_close': '</a>'}
out = """
<table class="errorbox">
<thead>
<tr>
<th class="errorboxheader">%s</th>
</tr>
</thead>
</table>"""
return out % message
############################ Utilities ###################################
def __create_select_menu(self, name, elements, selected_key=None):
""" private function, returns a popup menu
@param name: name of HTML control
@param elements: list of (key, value)
@param selected_key: item that should be selected (key of elements tuple)
"""
out = '<select name="%s">' % name
for (key, label) in elements:
selected = ''
if key == selected_key:
selected = ' selected="selected"'
out += '<option value="%s"%s>%s</option>'% (key, selected, cgi.escape(label))
out += '</select>'
return out
def tmpl_warnings(self, warnings=[], ln=CFG_SITE_LANG):
""" returns HTML for warnings """
from invenio.errorlib import get_msgs_for_code_list
out = ""
if type(warnings) is not list:
warnings = [warnings]
if warnings:
warnings_parsed = get_msgs_for_code_list(warnings, 'warning', ln)
for (dummy, warning_text) in warnings_parsed:
out += """
<p class="important">%s</p>
""" % warning_text
return out
def tmpl_back_link(self, link, ln=CFG_SITE_LANG):
""" returns HTML for a link whose label should be
'Back to search results'
"""
_ = gettext_set_language(ln)
label = _("Back to search results")
out = '<a href="%s">%s</a>' % (link, label)
return out
def __create_webmessage_link(self, to, display_name, ln=CFG_SITE_LANG):
"""prints a link to the messaging system"""
link = "%s/yourmessages/write?msg_to=%s&ln=%s" % (CFG_SITE_URL, to, ln)
if to:
return '<a href="%s" class="maillink">%s</a>' % (link, display_name)
else:
return display_name
def tmpl_xml_basket(self, items=[]):
"""Template for XML output of basket
@param items: XML version of each item (list)"""
items_xml = ''
for item in items:
items_xml += ' ' + item + '\n'
return """<?xml version="1.0" encoding="UTF-8"?>
<collection>
%s
</collection>
""" % items_xml
############################ Baskets ###################################
##################################
########### BASKET VIEW ##########
##################################
def tmpl_basket(self,
bskid,
name,
date_modification,
nb_items,
nb_subscribers,
(user_can_view_content,
user_can_edit_basket,
user_can_view_notes,
user_can_add_notes,
user_can_add_item,
user_can_delete_item),
nb_comments,
share_level,
selected_category=CFG_WEBBASKET_CATEGORIES['PRIVATE'],
selected_topic="",
selected_group=0,
items=[],
of='hb',
ln=CFG_SITE_LANG):
"""Template for basket display."""
if not of.startswith('x'):
out = """
<table class="bskbasket" width="100%">"""
else:
out = ""
if not of.startswith('x'):
out += self.tmpl_basket_header(bskid,
name,
nb_items,
nb_subscribers,
date_modification,
(user_can_view_content,
user_can_edit_basket,
user_can_view_notes),
selected_category,
nb_comments,
selected_topic,
share_level,
ln)
if not of.startswith('x'):
out += self.tmpl_basket_footer(bskid,
nb_items,
(user_can_view_content,
user_can_edit_basket),
selected_category,
selected_topic,
share_level,
ln)
out += self.tmpl_basket_content(bskid,
(user_can_view_content,
user_can_view_notes,
user_can_add_notes,
user_can_add_item,
user_can_delete_item),
selected_category,
selected_topic,
selected_group,
items,
of,
ln)
if not of.startswith('x'):
out += """
</table>"""
if not of.startswith('x'):
out += self.tmpl_create_export_as_list(selected_category,
selected_topic,
selected_group,
bskid,
None,
False)
return out
def tmpl_basket_header(self,
bskid,
name,
nb_items,
nb_subscribers,
date_modification,
(user_can_view_content,
user_can_edit_basket,
user_can_view_notes),
selected_category,
nb_comments,
selected_topic,
share_level,
ln=CFG_SITE_LANG):
"""Template for basket header display."""
_ = gettext_set_language(ln)
optional_colspan = nb_items and user_can_view_content and ' colspan="3"' or ''
records_field = '<br />' + _('%i items') % nb_items
comments_field = user_can_view_notes and (nb_comments and (', ' + _('%i notes') % nb_comments) or ', ' + _('no notes yet')) or ''
subscribers_field = selected_category == CFG_WEBBASKET_CATEGORIES['PRIVATE'] and \
share_level == 0 and \
', ' + (_('%i subscribers') % nb_subscribers) or \
''
last_update_field = '<br />' + _('last update') + ': ' + date_modification
if user_can_edit_basket:
add_ext_resource_url = """%s/yourbaskets/add?category=%s&bskid=%i""" % (CFG_SITE_URL,selected_category,bskid,)
add_ext_resource_logo = """<img src="%s/img/wb-create-basket.png" />""" % (CFG_SITE_URL,)
add_ext_resource = """<a href="%s">%s%s</a>""" % (add_ext_resource_url, add_ext_resource_logo, _("Add item"))
edit_basket_url = """%s/yourbaskets/edit?bskid=%i&topic=%s&ln=%s""" % (CFG_SITE_URL, bskid, cgi.escape(selected_topic, True), ln)
edit_basket_logo = """<img src="%s/img/wb-edit-basket.png" />""" % (CFG_SITE_URL,)
edit_basket = """<a href="%s">%s%s</a>""" % (edit_basket_url, edit_basket_logo, _("Edit basket"))
delete_basket_url = """%s/yourbaskets/edit?bskid=%i&topic=%s&delete=1&ln=%s""" % (CFG_SITE_URL, bskid, cgi.escape(selected_topic, True), ln)
delete_basket_logo = """<img src="%s/img/wb-delete-basket.png" />""" % (CFG_SITE_URL,)
delete_basket = """<a href="%s">%s%s</a>""" % (delete_basket_url, delete_basket_logo, _("Delete basket"))
else:
#edit_basket = """<small>%s</small>""" % (_("You cannot edit this basket"),)
#delete_basket = """<small>%s</small>""" % (_("You cannot delete this basket"),)
edit_basket = ""
delete_basket = ""
add_ext_resource = ""
if selected_category==CFG_WEBBASKET_CATEGORIES['EXTERNAL']:
unsubscribe_url = """%s/yourbaskets/unsubscribe?bskid=%i&ln=%s""" % (CFG_SITE_URL, bskid, ln)
unsubscribe_logo = """<img src="%s/img/wb-unsubscribe.png" />""" % (CFG_SITE_URL,)
unsubscribe = """ \n<a href="%s">%s%s</a>""" % (unsubscribe_url, unsubscribe_logo, _("Unsubscribe from basket"))
else:
unsubscribe = ""
out = """
<thead>
<tr>
<td class="bskbasketheader"%(optional_colspan)s>
<table>
<tr>
<td class="bskbasketheadertitle">
<strong>
%(name)s
</strong>
<small>
%(records_field)s%(comments_field)s%(subscribers_field)s
%(last_update_field)s
</small>
</td>
<td class="bskbasketheaderoptions">
%(add_ext_resource)s
%(edit_basket)s
%(delete_basket)s
%(unsubscribe)s
</td>
</table>
</td>
</tr>
</thead>"""
out %= {'optional_colspan': optional_colspan,
'name': cgi.escape(name, True),
'nb_items': nb_items,
'records_field': records_field,
'comments_field': comments_field,
'subscribers_field': subscribers_field,
'last_update_field': last_update_field,
'add_ext_resource': add_ext_resource,
'edit_basket': edit_basket,
'delete_basket': delete_basket,
'unsubscribe': unsubscribe,
}
return out
def tmpl_basket_footer(self,
bskid,
nb_items,
(user_can_view_content,
user_can_edit_basket),
selected_category,
selected_topic,
share_level=None,
ln=CFG_SITE_LANG):
"""Template for basket footer display."""
_ = gettext_set_language(ln)
optional_colspan = nb_items and user_can_view_content and ' colspan="3"' or ''
if user_can_edit_basket:
add_ext_resource_url = """%s/yourbaskets/add?category=%s&bskid=%i""" % (CFG_SITE_URL,selected_category,bskid,)
add_ext_resource_logo = """<img src="%s/img/wb-create-basket.png" />""" % (CFG_SITE_URL,)
add_ext_resource = """<a href="%s">%s%s</a>""" % (add_ext_resource_url, add_ext_resource_logo, _("Add item"))
edit_basket_url = """%s/yourbaskets/edit?bskid=%i&topic=%s&ln=%s""" % (CFG_SITE_URL, bskid, selected_topic, ln)
edit_basket_logo = """<img src="%s/img/wb-edit-basket.png" />""" % (CFG_SITE_URL,)
edit_basket = """<a href="%s">%s%s</a>""" % (edit_basket_url, edit_basket_logo, _("Edit basket"))
delete_basket_url = """%s/yourbaskets/edit?bskid=%i&topic=%s&delete=1&ln=%s""" % (CFG_SITE_URL, bskid, selected_topic, ln)
delete_basket_logo = """<img src="%s/img/wb-delete-basket.png" />""" % (CFG_SITE_URL,)
delete_basket = """<a href="%s">%s%s</a>""" % (delete_basket_url, delete_basket_logo, _("Delete basket"))
else:
edit_basket = ""
delete_basket = ""
add_ext_resource = ""
if selected_category==CFG_WEBBASKET_CATEGORIES['EXTERNAL']:
unsubscribe_url = """%s/yourbaskets/unsubscribe?bskid=%i&ln=%s""" % (CFG_SITE_URL, bskid, ln)
unsubscribe_logo = """<img src="%s/img/wb-unsubscribe.png" />""" % (CFG_SITE_URL,)
unsubscribe = """ \n<a href="%s">%s%s</a>""" % (unsubscribe_url, unsubscribe_logo, _("Unsubscribe from basket"))
else:
unsubscribe = ""
if share_level == 0:
display_public_url = """%s/yourbaskets/display_public?bskid=%i""" % (CFG_SITE_URL, bskid)
display_public_text = _("This basket is publicly accessible at the following address:")
display_public = """%s<br /><a href="%s">%s</a>""" % (display_public_text, display_public_url, display_public_url)
else:
display_public = ""
out = """
<tfoot>
<tr>
<td class="bskbasketfooter"%(optional_colspan)s>
<table>
<tr>
<td class="bskbasketfootertitle">
<small>
%(display_public)s
</small>
</td>
<td class="bskbasketfooteroptions">
%(add_ext_resource)s
%(edit_basket)s
%(delete_basket)s
%(unsubscribe)s
</td>
</tr>
</table>
</td>
</tr>
</tfoot>"""
out %= {'optional_colspan': optional_colspan,
'display_public': display_public,
'add_ext_resource': add_ext_resource,
'edit_basket': edit_basket,
'delete_basket': delete_basket,
'unsubscribe': unsubscribe}
return out
def tmpl_basket_content(self,
bskid,
(user_can_view_content,
user_can_view_notes,
user_can_add_notes,
user_can_add_item,
user_can_delete_item),
selected_category=CFG_WEBBASKET_CATEGORIES['PRIVATE'],
selected_topic="",
selected_group=0,
items=[],
of='hb',
ln=CFG_SITE_LANG):
"""Template for basket content display."""
if not of.startswith('x'):
_ = gettext_set_language(ln)
items_html = """
<tbody>"""
if user_can_view_content:
if not(items):
items_html += """
<tr>
<td style="text-align:center; height:100px">
%s
</td>
</tr>""" % _("Basket is empty")
else:
count = 0
for item in items:
count += 1
copy = 1
go_up = go_down = delete = 0
if user_can_add_item:
go_up = go_down = 1
if item == items[0]:
go_up = 0
if item == items[-1]:
go_down = 0
if user_can_delete_item:
delete = 1
items_html += self.__tmpl_basket_item(count=count,
bskid=bskid,
item=item,
uparrow=go_up,
downarrow=go_down,
copy_item=copy,
delete_item=delete,
view_notes=user_can_view_notes,
add_notes=user_can_add_notes,
selected_category=selected_category,
selected_topic=selected_topic,
selected_group=selected_group,
ln=ln)
else:
items_html += """
<tr>
<td style="text-align:center; height:100px">
%s
</td>
</tr>""" % _("You do not have sufficient rights to view this basket's content.")
items_html += """
</tbody>"""
return items_html
else:
items_xml = ""
for item in items:
items_xml += item[4] + "\n"
return items_xml
def __tmpl_basket_item(self,
count,
bskid,
item,
uparrow=0,
downarrow=0,
copy_item=0,
delete_item=0,
view_notes=0,
add_notes=0,
selected_category=CFG_WEBBASKET_CATEGORIES['PRIVATE'],
selected_topic="",
selected_group=0,
ln=CFG_SITE_LANG):
"""Template for basket item display within the basket content."""
_ = gettext_set_language(ln)
(recid, colid, nb_cmt, last_cmt, val, dummy) = item
if uparrow:
moveup_url = "%(siteurl)s/yourbaskets/modify?action=moveup&bskid=%(bskid)i&recid=%(recid)i"\
"&category=%(category)s&topic=%(topic)s&group_id=%(group)i&ln=%(ln)s" % \
{'siteurl': CFG_SITE_URL,
'bskid': bskid,
'recid': recid,
'category': selected_category,
'topic': selected_topic,
'group': selected_group,
'ln': ln}
moveup_img = "%s/img/wb-move-item-up.png" % (CFG_SITE_URL,)
moveup = """<a href="%s"><img src="%s" alt="%s" /></a>""" % \
(moveup_url, moveup_img, _("Move item up"))
else:
moveup_img = "%s/img/wb-move-item-up-disabled.png" % (CFG_SITE_URL,)
moveup = """<img src="%s" alt="%s" />""" % \
(moveup_img, _("You cannot move this item up"))
if downarrow:
movedown_url = "%(siteurl)s/yourbaskets/modify?action=movedown&bskid=%(bskid)i&recid=%(recid)i"\
"&category=%(category)s&topic=%(topic)s&group_id=%(group)i&ln=%(ln)s" % \
{'siteurl': CFG_SITE_URL,
'bskid': bskid,
'recid': recid,
'category': selected_category,
'topic': selected_topic,
'group': selected_group,
'ln': ln}
movedown_img = "%s/img/wb-move-item-down.png" % (CFG_SITE_URL,)
movedown = """<a href="%s"><img src="%s" alt="%s" /></a>""" % \
(movedown_url, movedown_img, _("Move item down"))
else:
movedown_img = "%s/img/wb-move-item-down-disabled.png" % (CFG_SITE_URL,)
movedown = """<img src="%s" alt="%s" />""" % \
(movedown_img, _("You cannot move this item down"))
if copy_item:
copy_url = "%(siteurl)s/yourbaskets/modify?action=copy&bskid=%(bskid)i&recid=%(recid)i"\
"&category=%(category)s&topic=%(topic)s&group_id=%(group)i&ln=%(ln)s" % \
{'siteurl': CFG_SITE_URL,
'bskid': bskid,
'recid': recid,
'category': selected_category,
'topic': selected_topic,
'group': selected_group,
'ln': ln}
copy_img = "%s/img/wb-copy-item.png" % (CFG_SITE_URL,)
copy = """<a href="%s"><img src="%s" alt="%s" />%s</a>""" % \
(copy_url, copy_img, _("Copy item"), _("Copy item"))
else:
copy = ""
if delete_item:
remove_url = "%(siteurl)s/yourbaskets/modify?action=delete&bskid=%(bskid)i&recid=%(recid)i"\
"&category=%(category)s&topic=%(topic)s&group=%(group)i&ln=%(ln)s" % \
{'siteurl': CFG_SITE_URL,
'bskid': bskid,
'recid': recid,
'category': selected_category,
'topic': selected_topic,
'group': selected_group,
'ln': ln}
remove_img = "%s/img/wb-delete-item.png" % (CFG_SITE_URL,)
remove = """<a href="%s"><img src="%s" alt="%s" />%s</a>""" % \
(remove_url, remove_img, _("Remove item"), _("Remove item"))
else:
remove = ""
if recid < 0:
external_item_img = '<img src="%s/img/wb-external-item.png" alt="%s" style="vertical-align: top;" /> ' % \
(CFG_SITE_URL, _("External item"))
else:
external_item_img = ''
out = """
<tr>
<td style="border-bottom: 1px solid #fc0;">
<table>
<tr>
<td class="bskcontentcount">
%(count)i.
</td>
<td class="bskcontentcol" colspan="2">
%(icon)s%(content)s
</td>
</tr>
<tr>
<td class="bskcontentoptions">
%(moveup)s%(movedown)s
</td>
<td>
<span class="moreinfo">"""
if item[0] > 0:
detailed_record = """<a class="moreinfo" href="%(siteurl)s/record/%(recid)s">%(detailed_record_label)s</a>"""
out += detailed_record + (view_notes and " - " or "")
external_url = ""
else:
## Uncomment the following lines if you want the Detailed record link to be
## displayed for external records but not for external sources (such as urls)
#external_colid_and_url = db.get_external_colid_and_url(item[0])
#if external_colid_and_url and external_colid_and_url[0][0] and external_colid_and_url[0][1]:
# detailed_record = '<a class="moreinfo" href="%(external_url)s">%(detailed_record_label)s</a>'
# out += detailed_record + (view_notes and " - " or "")
# external_url = external_colid_and_url[0][1]
#else:
# external_url = ""
## Currently no external items (records or sources) have a Detailed record link
external_url = ""
# TODO: If a user has the right to view the notes but not to add new ones,
# and there are no notes for some item an anchor to write notes will be
# created but with no text, hence invisible. Fix this so that no anchor
# is created whatsoever.
if view_notes:
notes = """\n<a class="moreinfo" href="%(siteurl)s/yourbaskets/%(add_and_view_notes_action)s?"""\
"""category=%(category)s&topic=%(topic)s&group=%(group)i&"""\
"""bskid=%(bskid)s&recid=%(recid)i&ln=%(ln)s%(add_and_view_notes_inline_anchor)s">%(add_and_view_notes_label)s</a>"""
out += notes
out += """
</span>
</td>
<td class="bskbasketheaderoptions">
%(copy)s
%(remove)s
</td>
</tr>
</table>
</td>
</tr>"""
out = out % {'moveup': moveup,
'movedown': movedown,
'count': count,
'icon': external_item_img,
'content': colid >= 0 and val or self.tmpl_create_pseudo_item(val),
'add_and_view_notes_action': nb_cmt and 'display' or 'write_note',
'add_and_view_notes_inline_anchor': not nb_cmt and '#note' or '',
'add_and_view_notes_label': nb_cmt and _('Notes') + ' (' + str(nb_cmt) + ')' or add_notes and _('Add a note...') or '',
'last_cmt': last_cmt,
'siteurl': CFG_SITE_URL,
'bskid': bskid,
'recid': recid,
'external_url': external_url,
'detailed_record_label': _("Detailed record"),
'category': selected_category,
'topic': selected_topic,
'group': selected_group,
'copy': copy,
'remove': remove,
'ln': ln}
return out
#############################################
########## BASKET SINGLE ITEM VIEW ##########
#############################################
def tmpl_basket_single_item(self,
bskid,
name,
nb_items,
(user_can_view_content,
user_can_view_notes,
user_can_add_notes,
user_can_delete_notes),
selected_category=CFG_WEBBASKET_CATEGORIES['PRIVATE'],
selected_topic="",
selected_group=0,
item=(),
comments=(),
previous_item_recid=0,
next_item_recid=0,
item_index=0,
optional_params={},
of='hb',
ln=CFG_SITE_LANG):
"""Template for basket's single item display."""
if of != 'xm':
out = """
<table class="bskbasket" width="100%">"""
else:
out = ""
if of != 'xm':
out += self.tmpl_basket_single_item_header(bskid,
name,
nb_items,
selected_category,
selected_topic,
selected_group,
previous_item_recid,
next_item_recid,
item_index,
ln)
if of != 'xm':
out += self.tmpl_basket_single_item_footer(bskid,
selected_category,
selected_topic,
selected_group,
previous_item_recid,
next_item_recid,
ln)
out += self.tmpl_basket_single_item_content(bskid,
(user_can_view_content,
user_can_view_notes,
user_can_add_notes,
user_can_delete_notes),
selected_category,
selected_topic,
selected_group,
item,
comments,
item_index,
optional_params,
of,
ln)
if of != 'xm':
out += """
</table>"""
if of != 'xm':
out += self.tmpl_create_export_as_list(selected_category,
selected_topic,
selected_group,
bskid,
item,
False)
return out
def tmpl_basket_single_item_header(self,
bskid,
name,
nb_items,
selected_category,
selected_topic,
selected_group,
previous_item_recid,
next_item_recid,
item_index,
ln=CFG_SITE_LANG):
"""Template for basket's single item header display."""
_ = gettext_set_language(ln)
records_field = '<br />' + _('Item %(x_item_index)i of %(x_item_total)i') % \
{'x_item_index': item_index, 'x_item_total': nb_items}
if previous_item_recid:
previous_item_url = """%s/yourbaskets/display?category=%s&topic=%s&group=%i&bskid=%i&recid=%s&ln=%s""" % \
(CFG_SITE_URL,
selected_category,
selected_topic,
selected_group,
bskid,
previous_item_recid,
ln)
previous_item_logo = """<img src="%s/img/wb-previous-item.png" />""" % (CFG_SITE_URL,)
previous_item = """<a href="%s">%s%s</a>""" % (previous_item_url, previous_item_logo, _("Previous item"))
else:
previous_item_logo = """<img src="%s/img/wb-previous-item-disabled.png" />""" % (CFG_SITE_URL,)
previous_item = """%s%s""" % (previous_item_logo, _("Previous item"))
if next_item_recid:
next_item_url = """%s/yourbaskets/display?category=%s&topic=%s&group=%i&bskid=%i&recid=%s&ln=%s""" % \
(CFG_SITE_URL,
selected_category,
selected_topic,
selected_group,
bskid,
next_item_recid,
ln)
next_item_logo = """<img src="%s/img/wb-next-item.png" />""" % (CFG_SITE_URL,)
next_item = """<a href="%s">%s%s</a>""" % (next_item_url, next_item_logo, _("Next item"))
else:
next_item_logo = """<img src="%s/img/wb-next-item-disabled.png" />""" % (CFG_SITE_URL,)
next_item = """%s%s""" % (next_item_logo, _("Next item"))
go_back_url = """%s/yourbaskets/display?category=%s&topic=%s&group=%i&bskid=%i&ln=%s""" % \
(CFG_SITE_URL,
selected_category,
selected_topic,
selected_group,
bskid,
ln)
go_back_logo = """<img src="%s/img/wb-go-back.png" />""" % (CFG_SITE_URL,)
go_back = """<a href="%s">%s%s</a>""" % (go_back_url, go_back_logo, _("Return to basket"))
out = """
<thead>
<tr>
<td class="bskbasketheader">
<table>
<tr>
<td class="bskbasketheadertitle">
<strong>
%(name)s
</strong>
<small>
%(records_field)s
</small>
</td>
<td class="bskbasketheaderoptions">
%(go_back)s
%(previous_item)s
%(next_item)s
</td>
</table>
</td>
</tr>
</thead>"""
out %= {'name': name,
'records_field': records_field,
'go_back': go_back,
'previous_item': previous_item,
'next_item': next_item,
}
return out
def tmpl_basket_single_item_footer(self,
bskid,
selected_category,
selected_topic,
selected_group,
previous_item_recid,
next_item_recid,
ln=CFG_SITE_LANG):
"""Template for basket's single item footer display."""
_ = gettext_set_language(ln)
if previous_item_recid:
previous_item_url = """%s/yourbaskets/display?category=%s&topic=%s&group=%i&bskid=%i&recid=%s&ln=%s""" % \
(CFG_SITE_URL,
selected_category,
selected_topic,
selected_group,
bskid,
previous_item_recid,
ln)
previous_item_logo = """<img src="%s/img/wb-previous-item.png" />""" % (CFG_SITE_URL,)
previous_item = """<a href="%s">%s%s</a>""" % (previous_item_url, previous_item_logo, _("Previous item"))
else:
previous_item_logo = """<img src="%s/img/wb-previous-item-disabled.png" />""" % (CFG_SITE_URL,)
previous_item = """%s%s""" % (previous_item_logo, _("Previous item"))
if next_item_recid:
next_item_url = """%s/yourbaskets/display?category=%s&topic=%s&group=%i&bskid=%i&recid=%s&ln=%s""" % \
(CFG_SITE_URL,
selected_category,
selected_topic,
selected_group,
bskid,
next_item_recid,
ln)
next_item_logo = """<img src="%s/img/wb-next-item.png" />""" % (CFG_SITE_URL,)
next_item = """<a href="%s">%s%s</a>""" % (next_item_url, next_item_logo, _("Next item"))
else:
next_item_logo = """<img src="%s/img/wb-next-item-disabled.png" />""" % (CFG_SITE_URL,)
next_item = """%s%s""" % (next_item_logo, _("Next item"))
go_back_url = """%s/yourbaskets/display?category=%s&topic=%s&group=%i&bskid=%i&ln=%s""" % \
(CFG_SITE_URL,
selected_category,
selected_topic,
selected_group,
bskid,
ln)
go_back_logo = """<img src="%s/img/wb-go-back.png" />""" % (CFG_SITE_URL,)
go_back = """<a href="%s">%s%s</a>""" % (go_back_url, go_back_logo, _("Return to basket"))
out = """
<tfoot>
<tr>
<td class="bskbasketfooter">
<table>
<tr>
<td class="bskbasketfootertitle">
</td>
<td class="bskbasketfooteroptions">
%(go_back)s
%(previous_item)s
%(next_item)s
</td>
</table>
</td>
</tr>
</tfoot>"""
out %= {'go_back': go_back,
'previous_item': previous_item,
'next_item': next_item,
}
return out
def tmpl_basket_single_item_content(self,
bskid,
(user_can_view_content,
user_can_view_notes,
user_can_add_notes,
user_can_delete_notes),
selected_category=CFG_WEBBASKET_CATEGORIES['PRIVATE'],
selected_topic="",
selected_group=0,
item=(),
notes=(),
index_item=0,
optional_params={},
of='hb',
ln=CFG_SITE_LANG):
"""Template for basket's single item content display."""
if of != 'xm':
_ = gettext_set_language(ln)
item_html = """
<tbody>"""
if user_can_view_content:
if not item:
item_html += """
<tr>
<td style="text-align: center; height: 100px">
%s
</td>
</tr>""" % _("The item you have selected does not exist.")
else:
(recid, colid, dummy, last_cmt, val, dummy) = item
if recid < 0:
external_item_img = '<img src="%s/img/wb-external-item.png" alt="%s" style="vertical-align: top;" /> ' % \
(CFG_SITE_URL, _("External item"))
else:
external_item_img = ''
if user_can_view_notes:
notes_html = self.__tmpl_display_notes(recid,
bskid,
(user_can_add_notes,
user_can_delete_notes),
selected_category,
selected_topic,
selected_group,
notes,
optional_params,
ln)
notes = """
<tr>
<td colspan="2" class="bskcontentnotes">%(notes_html)s
</td>
</tr>""" % {'notes_html': notes_html}
else:
notes_msg = _("You do not have sufficient rights to view this item's notes.")
notes = """
<tr>
<td colspan="2" style="text-align: center; height: 50px">
%(notes_msg)s
</td>
</tr>""" % {'notes_msg': notes_msg}
item_html += """
<tr>
<td style="border-bottom: 1px solid #fc0;">
<table>
<tr>
<td class="bskcontentcount">
%(count)i.
</td>
<td class="bskcontentcol">
%(icon)s%(content)s
</td>
</tr>%(notes)s
</table>
</td>
</tr>""" % {'count': index_item,
'icon': external_item_img,
'content': colid >=0 and val or self.tmpl_create_pseudo_item(val),
'last_cmt': last_cmt,
'siteurl': CFG_SITE_URL,
'bskid': bskid,
'recid': recid,
'category': selected_category,
'topic': selected_topic,
'group': selected_group,
'notes': notes,
'ln': ln}
else:
item_html += """
<tr>
<td style="text-align: center; height: 100px">
%s
</td>
</tr>""" % _("You do not have sufficient rights to view this item.")
item_html += """
</tbody>"""
return item_html
else:
item_xml = item[4]
return item_xml
def __tmpl_display_notes(self,
recid,
bskid,
(user_can_add_notes,
user_can_delete_notes),
selected_category,
selected_topic,
selected_group,
notes,
optional_params,
ln=CFG_SITE_LANG):
"""Template for basket's single item notes display."""
_ = gettext_set_language(ln)
warnings_html = ""
add_note_p = False
if user_can_add_notes and (optional_params.has_key("Add note") or optional_params.has_key("Incomplete note")):
add_note_p = True
if optional_params.has_key("Add note") and optional_params['Add note']:
replied_to_note = optional_params['Add note']
note_body_html = self.tmpl_quote_comment_html(replied_to_note[2],
replied_to_note[1],
replied_to_note[0],
replied_to_note[4],
replied_to_note[3],
ln)
note_body_textual = self.tmpl_quote_comment_textual(replied_to_note[2],
replied_to_note[1],
replied_to_note[0],
replied_to_note[4],
replied_to_note[3],
ln)
note_title = "Re: " + replied_to_note[2]
elif optional_params.has_key("Incomplete note") and optional_params['Incomplete note']:
incomplete_note = optional_params['Incomplete note']
note_body_html = incomplete_note[1]
# TODO: Do we need to format incomplete body correctly as textual
# and html as above?
note_body_textual = incomplete_note[1]
note_title = incomplete_note[0]
if optional_params.has_key("Warnings"):
warnings = optional_params["Warnings"]
warnings_html = self.tmpl_warnings(warnings, ln)
else:
note_body_html = ""
note_body_textual = ""
note_title = ""
if optional_params.has_key("Warnings"):
warnings = optional_params["Warnings"]
warnings_html = self.tmpl_warnings(warnings, ln)
# TODO: calculate the url
file_upload_url = ""
action = """%s/yourbaskets/save_note?category=%s&topic=%s&group=%i&bskid=%i&recid=%i&ln=%s%s""" % \
(CFG_SITE_URL, selected_category, selected_topic, selected_group, bskid, recid, ln, '#note')
cancel = """%s/yourbaskets/display?category=%s&topic=%s&group=%i&bskid=%i&recid=%i&ln=%s""" % \
(CFG_SITE_URL, selected_category, selected_topic, selected_group, bskid, recid, ln)
editor = get_html_text_editor(name="note_body",
content=note_body_html,
textual_content=note_body_textual,
width="99%",
height="160px",
enabled=CFG_WEBBASKET_USE_RICH_TEXT_EDITOR,
file_upload_url=file_upload_url,
toolbar_set="WebComment")
add_note_html = """
<table cellspacing="0" cellpadding="0" class="bsknotescontentaddnote">
<tr>
<td class="bsknotescontentaddform">
<form name="write_note" method="post" action="%(action)s">
<a name="note"></a><strong>%(add_a_note_label)s</strong>
%(warnings_html)s
<p align="left">
<small>Subject:</small>
<br />
<input type="text" name="note_title" size="65" value="%(note_title)s" />
</p>
<p align="left">
<small>Note:</small>
<br />
%(editor)s
</p>
<input type="hidden" name="reply_to" value="%(reply_to)s" />
<p align="left">
<input type="submit" class="formbutton" value="%(submit_label)s" />
<input type="button" class="nonsubmitbutton" value="%(cancel_label)s" onClick="window.location='%(cancel)s'" />
</p>
</form>
</td>
</tr>
</table>""" % {'action': action,
'warnings_html': warnings_html,
'cancel': cancel,
'cancel_label': _('Cancel'),
'note_title': note_title,
'editor': editor,
'add_a_note_label': _('Add a note'),
'submit_label': _('Add note'),
'reply_to': optional_params.get("Reply to")}
notes_icon = '<img src="%s/img/wb-notes.png" style="vertical-align: top;" /> ' % (CFG_SITE_URL,)
if user_can_add_notes and not add_note_p:
add_note_url = """%s/yourbaskets/write_note?category=%s&topic=%s&group=%i&bskid=%i&recid=%i&ln=%s%s""" % \
(CFG_SITE_URL, selected_category, selected_topic, selected_group, bskid, recid, ln, '#note')
add_note_logo = """<img src="%s/img/wb-add-note.png" />""" % (CFG_SITE_URL,)
add_note = """<a href="%s">%s%s</a>""" % (add_note_url, add_note_logo, _("Add a note"))
else:
add_note = ""
notes_html = """
<table>
<tr>
<td class="bsknotesheadertitle">
<br />
<strong>%(notes_icon)s%(notes_label)s</strong>
<br />
<small>%(nb_notes)i notes in total</small>
</td>
<td class="bsknotesheaderoptions">
%(add_note)s
</td>
</tr>""" % {'notes_label': _('Notes'),
'notes_icon': notes_icon,
'add_note': (notes and user_can_add_notes and not add_note_p) and add_note or " ",
'nb_notes': len(notes)}
if notes or add_note or add_note_p:
notes_html += """
<tr>
<td colspan="2" class="bsknotescontent">"""
thread_history = [0]
for (cmt_uid, cmt_nickname, cmt_title, cmt_body, cmt_date, dummy, cmtid, reply_to) in notes:
if reply_to not in thread_history:
# Going one level down in the thread
thread_history.append(reply_to)
depth = thread_history.index(reply_to)
else:
depth = thread_history.index(reply_to)
thread_history = thread_history[:depth + 1]
notes_html += '<div style="margin-left:%spx">' % (depth*20)
if user_can_add_notes:
reply_to_note = """<a href="%s/yourbaskets/write_note?category=%s&topic=%s&group=%i&bskid=%i&recid=%i&cmtid=%i&ln=%s%s">%s</a>""" % \
(CFG_SITE_URL, selected_category, cgi.escape(selected_topic, True), selected_group, bskid, recid, cmtid, ln, '#note', _('Reply'))
else:
reply_to_note = ""
if user_can_delete_notes:
delete_note = """ | <a href="%s/yourbaskets/delete_note?category=%s&topic=%s&group=%i&bskid=%i&recid=%i&cmtid=%i&ln=%s">%s</a>""" % \
(CFG_SITE_URL, selected_category, cgi.escape(selected_topic, True), selected_group, bskid, recid, cmtid, ln, _('Delete'))
else:
delete_note = ""
notes_html += """
<table cellspacing="0" cellpadding="0" class="bsknotescontentnote">
<tr>
<td class="bsknotescontenttitle">
%(inline_anchor)s<img src="%(CFG_SITE_URL)s/img/user-icon-1-24x24.gif" />%(authorship)s
</td>
</tr>
<tr>
<td class="bsknotescontentbody">
<blockquote>
%(body)s
</blockquote>
</td>
</tr>
<tr>
<td class="bsknotescontentoptions">
%(reply_to_note)s%(delete_note)s
</td>
</tr>
</table>
<br />""" % {'inline_anchor': (not add_note_p and notes[-1][-1]==cmtid) and '<a name="note"></a>' or '',
'CFG_SITE_URL': CFG_SITE_URL,
'authorship': _("%(x_title)s, by %(x_name)s on %(x_date)s") % \
{'x_title': '<strong>' + (cmt_title and cgi.escape(cmt_title, True) \
or _('Note')) + '</strong>',
'x_name': '<a href="%(CFG_SITE_URL)s/yourmessages/write?msg_to=%(user)s">%(user_display)s</a>' % \
{'CFG_SITE_URL': CFG_SITE_URL,
'user': cmt_nickname or cmt_uid,
'user_display': cmt_nickname or get_user_info(cmt_uid)[2]},
'x_date': '<em>' + convert_datetext_to_dategui(cmt_date) + '</em>'},
'body': email_quoted_txt2html(escape_email_quoted_text(cmt_body)),
'reply_to_note': reply_to_note,
'delete_note': delete_note}
notes_html += '</div>'
if add_note_p:
notes_html += add_note_html
notes_html += """
</td>
</tr>"""
notes_html += """
<tr>
<td class="bsknotesfootertitle">
</td>
<td class="bsknotesfooteroptions">
%(add_note)s
</td>
</tr>
</table>""" % {'add_note': (user_can_add_notes and not add_note_p) and add_note or ' '}
return notes_html
########################################
########## PUBLIC BASKET VIEW ##########
########################################
def tmpl_public_basket(self,
bskid,
basket_name,
date_modification,
nb_items,
(user_can_view_comments,),
nb_comments,
items=[],
id_owner=0,
subscription_status=0,
of='hb',
ln=CFG_SITE_LANG):
"""Template for public basket display."""
if of == 'hb':
out = """
<table class="bskbasket" width="100%">"""
else:
out = ""
if of == 'hb':
out += self.tmpl_public_basket_header(bskid,
basket_name,
nb_items,
date_modification,
(user_can_view_comments,),
nb_comments,
subscription_status,
ln)
if of == 'hb':
out += self.tmpl_public_basket_footer(bskid,
nb_items,
id_owner,
subscription_status,
ln)
out += self.tmpl_public_basket_content(bskid,
(user_can_view_comments,),
items,
of,
ln)
if of == 'hb':
out += """
</table>"""
if of == 'hb':
out += self.tmpl_create_export_as_list(bskid=bskid,
item=None,
public=True)
return out
def tmpl_public_basket_header(self,
bskid,
name,
nb_items,
date_modification,
(user_can_view_comments,),
nb_comments,
subscription_status,
ln=CFG_SITE_LANG):
"""Template for public basket header display."""
_ = gettext_set_language(ln)
optional_colspan = nb_items and ' colspan="3"' or ''
records_field = '<br />' + _('%i items') % nb_items
comments_field = user_can_view_comments and \
(nb_comments and ', ' + (_('%i notes') % nb_comments) or ', ' + _('no notes yet')) \
or ''
last_update_field = '<br />' + _('last update') + ': ' + date_modification
if subscription_status:
subscribe_url = """%s/yourbaskets/subscribe?bskid=%i&ln=%s""" % (CFG_SITE_URL, bskid, ln)
subscribe_logo = """<img src="%s/img/wb-subscribe.png" />""" % (CFG_SITE_URL,)
subscribe = """<a href="%s">%s%s</a>""" % (subscribe_url, subscribe_logo, _("Subscribe to basket"))
unsubscribe_url = """%s/yourbaskets/unsubscribe?bskid=%i&ln=%s""" % (CFG_SITE_URL, bskid, ln)
unsubscribe_logo = """<img src="%s/img/wb-unsubscribe.png" />""" % (CFG_SITE_URL,)
unsubscribe = """<a href="%s">%s%s</a>""" % (unsubscribe_url, unsubscribe_logo, _("Unsubscribe from basket"))
out = """
<thead>
<tr>
<td class="bskbasketheader"%(optional_colspan)s>
<table>
<tr>
<td class="bskbasketheadertitle">
<strong>
%(name)s
</strong>
<small>
%(records_field)s%(comments_field)s
%(last_update_field)s
</small>
</td>
<td class="bskbasketheaderoptions">
%(subscribe_unsubscribe_basket)s
</td>
</table>
</td>
</tr>
</thead>"""
out %= {'optional_colspan': optional_colspan,
'name': name,
'nb_items': nb_items,
'records_field': records_field,
'comments_field': comments_field,
'last_update_field': last_update_field,
'subscribe_unsubscribe_basket': subscription_status > 0 and unsubscribe or subscription_status < 0 and subscribe or not subscription_status and ' '}
return out
def tmpl_public_basket_footer(self,
bskid,
nb_items,
id_owner,
subscription_status,
ln=CFG_SITE_LANG):
"""Template for public basket footer display."""
_ = gettext_set_language(ln)
optional_colspan = nb_items and ' colspan="3"' or ''
if subscription_status:
subscribe_url = """%s/yourbaskets/subscribe?bskid=%i&ln=%s""" % (CFG_SITE_URL, bskid, ln)
subscribe_logo = """<img src="%s/img/wb-subscribe.png" />""" % (CFG_SITE_URL,)
subscribe = """<a href="%s">%s%s</a>""" % (subscribe_url, subscribe_logo, _("Subscribe to basket"))
unsubscribe_url = """%s/yourbaskets/unsubscribe?bskid=%i&ln=%s""" % (CFG_SITE_URL, bskid, ln)
unsubscribe_logo = """<img src="%s/img/wb-unsubscribe.png" />""" % (CFG_SITE_URL,)
unsubscribe = """<a href="%s">%s%s</a>""" % (unsubscribe_url, unsubscribe_logo, _("Unsubscribe from basket"))
(uid, nickname, display_name) = get_user_info(id_owner)
display_owner_url = """%s/yourmessages/write?msg_to=%s""" % (CFG_SITE_URL, nickname or str(uid))
display_owner_text = _("This public basket belongs to the user ")
display_owner = """%s<a href="%s">%s</a>.""" % (display_owner_text, display_owner_url, nickname or display_name)
out = """
<tfoot>
<tr>
<td class="bskbasketfooter"%(optional_colspan)s>
<table>
<tr>
<td class="bskbasketfootertitle">
<small>
%(display_owner)s
</small>
</td>
<td class="bskbasketfooteroptions">
%(subscribe_unsubscribe_basket)s
</td>
</tr>
</table>
</td>
</tr>
</tfoot>"""
out %= {'optional_colspan': optional_colspan,
'display_owner': subscription_status and display_owner or _('This public basket belongs to you.'),
'subscribe_unsubscribe_basket': subscription_status > 0 and unsubscribe or subscription_status < 0 and subscribe or not subscription_status and ' '}
return out
def tmpl_public_basket_content(self,
bskid,
(user_can_view_comments,),
items=[],
of='hb',
ln=CFG_SITE_LANG):
"""Template for public basket footer display."""
if of == 'hb':
_ = gettext_set_language(ln)
items_html = """
<tbody>"""
if not(items):
items_html += """
<tr>
<td style="text-align:center; height:100px">
%s
</td>
</tr>""" % _("Basket is empty")
else:
count = 0
for item in items:
count += 1
items_html += self.__tmpl_public_basket_item(count=count,
bskid=bskid,
item=item,
view_notes=user_can_view_comments,
ln=ln)
items_html += """
</tbody>"""
return items_html
elif of == 'xm':
items_xml = ""
for item in items:
items_xml += item[4] + "\n"
return items_xml
def __tmpl_public_basket_item(self,
count,
bskid,
item,
view_notes=0,
ln=CFG_SITE_LANG):
"""Template for basket item display within the basket content."""
_ = gettext_set_language(ln)
(recid, colid, nb_cmt, last_cmt, val, dummy) = item
copy_url = "%(siteurl)s/yourbaskets/modify?action=copy&bskid=%(bskid)i&recid=%(recid)i&ln=%(ln)s" % \
{'siteurl': CFG_SITE_URL,
'bskid': bskid,
'recid': recid,
'ln': ln}
copy_img = "%s/img/wb-copy-item.png" % (CFG_SITE_URL,)
copy = """<a href="%s"><img src="%s" alt="%s" />%s</a>""" % \
(copy_url, copy_img, _("Copy item"), _("Copy item"))
if recid < 0:
external_item_img = '<img src="%s/img/wb-external-item.png" alt="%s" style="vertical-align: top;" /> ' % \
(CFG_SITE_URL, _("External item"))
else:
external_item_img = ''
out = """
<tr>
<td style="border-bottom: 1px solid #fc0;">
<table>
<tr>
<td class="bskcontentcount">
%(count)i.
</td>
<td class="bskcontentcol" colspan="2">
%(icon)s%(content)s
</td>
</tr>
<tr>
<td class="bskcontentoptions">
</td>
<td>
<span class="moreinfo">"""
if item[0] > 0:
detailed_record = """<a class="moreinfo" href="%(siteurl)s/record/%(recid)s">%(detailed_record_label)s</a>"""
out += detailed_record + (view_notes and " - " or "")
external_url = ""
else:
## Uncomment the following lines if you want the Detailed record link to be
## displayed for external records but not for external sources (such as urls)
#external_colid_and_url = db.get_external_colid_and_url(item[0])
#if external_colid_and_url and external_colid_and_url[0][0] and external_colid_and_url[0][1]:
# detailed_record = '<a class="moreinfo" href="%(external_url)s">%(detailed_record_label)s</a>'
# out += detailed_record + (view_notes and " - " or "")
# external_url = external_colid_and_url[0][1]
#else:
# external_url = ""
## Currently no external items (records or sources) have a Detailed record link
external_url = ""
if view_notes:
notes = """\n<a class="moreinfo" href="%(siteurl)s/yourbaskets/%(add_and_view_notes_action)s?"""\
"""bskid=%(bskid)s&recid=%(recid)i&ln=%(ln)s%(add_and_view_notes_inline_anchor)s">%(add_and_view_notes_label)s</a>"""
out += notes
out += """
</span>
</td>
<td class="bskbasketheaderoptions">
%(copy)s
</td>
</tr>
</table>
</td>
</tr>"""
out = out % {'count': count,
'icon': external_item_img,
'content': colid >= 0 and val or self.tmpl_create_pseudo_item(val),
'add_and_view_notes_action': nb_cmt and 'display_public' or 'write_public_note',
'add_and_view_notes_inline_anchor': not nb_cmt and '#note' or '',
'add_and_view_notes_label': nb_cmt and _('Notes') + ' (' + str(nb_cmt) + ')' or _('Add a note...'),
'last_cmt': last_cmt,
'siteurl': CFG_SITE_URL,
'bskid': bskid,
'recid': recid,
'external_url': external_url,
'detailed_record_label': _("Detailed record"),
'copy': copy,
'ln': ln}
return out
####################################################
########## PUBLIC BASKET SINGLE ITEM VIEW ##########
####################################################
def tmpl_public_basket_single_item(self,
bskid,
name,
nb_items,
(user_can_view_notes,
user_can_add_notes),
item=(),
notes=(),
previous_item_recid=0,
next_item_recid=0,
item_index=0,
optional_params={},
of='hb',
ln=CFG_SITE_LANG):
"""Template for public basket's single item display."""
_ = gettext_set_language(ln)
if of == 'hb':
out = """
<table class="bskbasket" width="100%">"""
else:
out = ""
if of == 'hb':
out += self.tmpl_public_basket_single_item_header(bskid,
name,
nb_items,
previous_item_recid,
next_item_recid,
item_index,
ln=CFG_SITE_LANG)
if of == 'hb':
out += self.tmpl_public_basket_single_item_footer(bskid,
previous_item_recid,
next_item_recid,
ln=CFG_SITE_LANG)
out += self.tmpl_public_basket_single_item_content(bskid,
(user_can_view_notes,
user_can_add_notes),
item,
notes,
item_index,
optional_params,
of,
ln=CFG_SITE_LANG)
if of == 'hb':
out += """
</table>"""
if of == 'hb':
out += self.tmpl_create_export_as_list(bskid=bskid,
item=item,
public=True)
return out
def tmpl_public_basket_single_item_header(self,
bskid,
name,
nb_items,
previous_item_recid,
next_item_recid,
item_index,
ln=CFG_SITE_LANG):
"""Template for public basket's single item header display."""
_ = gettext_set_language(ln)
records_field = '<br />' + _('Item %(x_item_index)i of %(x_item_total)i') % \
{'x_item_index': item_index, 'x_item_total': nb_items}
if previous_item_recid:
previous_item_url = """%s/yourbaskets/display_public?bskid=%i&recid=%s&ln=%s""" % \
(CFG_SITE_URL,
bskid,
previous_item_recid,
ln)
previous_item_logo = """<img src="%s/img/wb-previous-item.png" />""" % (CFG_SITE_URL,)
previous_item = """<a href="%s">%s%s</a>""" % (previous_item_url, previous_item_logo, _("Previous item"))
else:
previous_item_logo = """<img src="%s/img/wb-previous-item-disabled.png" />""" % (CFG_SITE_URL,)
previous_item = """%s%s""" % (previous_item_logo, _("Previous item"))
if next_item_recid:
next_item_url = """%s/yourbaskets/display_public?bskid=%i&recid=%s&ln=%s""" % \
(CFG_SITE_URL,
bskid,
next_item_recid,
ln)
next_item_logo = """<img src="%s/img/wb-next-item.png" />""" % (CFG_SITE_URL,)
next_item = """<a href="%s">%s%s</a>""" % (next_item_url, next_item_logo, _("Next item"))
else:
next_item_logo = """<img src="%s/img/wb-next-item-disabled.png" />""" % (CFG_SITE_URL,)
next_item = """%s%s""" % (next_item_logo, _("Next item"))
go_back_url = """%s/yourbaskets/display_public?bskid=%i&ln=%s""" % \
(CFG_SITE_URL,
bskid,
ln)
go_back_logo = """<img src="%s/img/wb-go-back.png" />""" % (CFG_SITE_URL,)
go_back = """<a href="%s">%s%s</a>""" % (go_back_url, go_back_logo, _("Return to basket"))
out = """
<thead>
<tr>
<td class="bskbasketheader">
<table>
<tr>
<td class="bskbasketheadertitle">
<strong>
%(name)s
</strong>
<small>
%(records_field)s
</small>
</td>
<td class="bskbasketheaderoptions">
%(go_back)s
%(previous_item)s
%(next_item)s
</td>
</table>
</td>
</tr>
</thead>"""
out %= {'name': name,
'records_field': records_field,
'go_back': go_back,
'previous_item': previous_item,
'next_item': next_item,
}
return out
def tmpl_public_basket_single_item_footer(self,
bskid,
previous_item_recid,
next_item_recid,
ln=CFG_SITE_LANG):
"""Template for public basket's single item footer display."""
_ = gettext_set_language(ln)
if previous_item_recid:
previous_item_url = """%s/yourbaskets/display_public?bskid=%i&recid=%s&ln=%s""" % \
(CFG_SITE_URL,
bskid,
previous_item_recid,
ln)
previous_item_logo = """<img src="%s/img/wb-previous-item.png" />""" % (CFG_SITE_URL,)
previous_item = """<a href="%s">%s%s</a>""" % (previous_item_url, previous_item_logo, _("Previous item"))
else:
previous_item_logo = """<img src="%s/img/wb-previous-item-disabled.png" />""" % (CFG_SITE_URL,)
previous_item = """%s%s""" % (previous_item_logo, _("Previous item"))
if next_item_recid:
next_item_url = """%s/yourbaskets/display_public?bskid=%i&recid=%s&ln=%s""" % \
(CFG_SITE_URL,
bskid,
next_item_recid,
ln)
next_item_logo = """<img src="%s/img/wb-next-item.png" />""" % (CFG_SITE_URL,)
next_item = """<a href="%s">%s%s</a>""" % (next_item_url, next_item_logo, _("Next item"))
else:
next_item_logo = """<img src="%s/img/wb-next-item-disabled.png" />""" % (CFG_SITE_URL,)
next_item = """%s%s""" % (next_item_logo, _("Next item"))
go_back_url = """%s/yourbaskets/display_public?bskid=%i&ln=%s""" % \
(CFG_SITE_URL,
bskid,
ln)
go_back_logo = """<img src="%s/img/wb-go-back.png" />""" % (CFG_SITE_URL,)
go_back = """<a href="%s">%s%s</a>""" % (go_back_url, go_back_logo, _("Return to basket"))
out = """
<tfoot>
<tr>
<td class="bskbasketfooter">
<table>
<tr>
<td class="bskbasketfootertitle">
</td>
<td class="bskbasketfooteroptions">
%(go_back)s
%(previous_item)s
%(next_item)s
</td>
</table>
</td>
</tr>
</tfoot>"""
out %= {'go_back': go_back,
'previous_item': previous_item,
'next_item': next_item,
}
return out
def tmpl_public_basket_single_item_content(self,
bskid,
(user_can_view_notes,
user_can_add_notes),
item=(),
notes=(),
index_item=0,
optional_params={},
of='hb',
ln=CFG_SITE_LANG):
"""Template for public basket's single item content display."""
if of == 'hb':
_ = gettext_set_language(ln)
item_html = """
<tbody>"""
if not item:
item_html += """
<tr>
<td style="text-align: center; height: 100px">
%s
</td>
</tr>""" % _("The item you have selected does not exist.")
else:
(recid, colid, dummy, dummy, val, dummy) = item
if recid < 0:
external_item_img = '<img src="%s/img/wb-external-item.png" alt="%s" style="vertical-align: top;" /> ' % \
(CFG_SITE_URL, _("External item"))
else:
external_item_img = ''
if user_can_view_notes:
notes_html = self.__tmpl_display_public_notes(recid,
bskid,
(user_can_add_notes,),
notes,
optional_params,
ln)
notes = """
<tr>
<td colspan="2" class="bskcontentnotes">%(notes_html)s
</td>
</tr>""" % {'notes_html': notes_html}
else:
notes_msg = _("You do not have sufficient rights to view this item's notes.")
notes = """
<tr>
<td colspan="2" style="text-align: center; height: 50px">
%(notes_msg)s
</td>
</tr>""" % {'notes_msg': notes_msg}
item_html += """
<tr>
<td style="border-bottom: 1px solid #fc0;">
<table>
<tr>
<td class="bskcontentcount">
%(count)i.
</td>
<td class="bskcontentcol">
%(icon)s%(content)s
</td>
</tr>%(notes)s
</table>
</td>
</tr>""" % {'count': index_item,
'icon': external_item_img,
'content': colid >= 0 and val or self.tmpl_create_pseudo_item(val),
'notes': notes,
'ln': ln}
item_html += """
</tbody>"""
return item_html
elif of == 'xm':
item_xml = item[4]
return item_xml
def __tmpl_display_public_notes(self,
recid,
bskid,
(user_can_add_notes,),
notes,
optional_params,
ln=CFG_SITE_LANG):
"""Template for public basket's single item notes display."""
_ = gettext_set_language(ln)
warnings_html = ""
add_note_p = False
if user_can_add_notes and (optional_params.has_key("Add note") or optional_params.has_key("Incomplete note")):
add_note_p = True
if optional_params.has_key("Add note") and optional_params['Add note']:
replied_to_note = optional_params['Add note']
note_body_html = self.tmpl_quote_comment_html(replied_to_note[2],
replied_to_note[1],
replied_to_note[0],
replied_to_note[4],
replied_to_note[3],
ln)
note_body_textual = self.tmpl_quote_comment_textual(replied_to_note[2],
replied_to_note[1],
replied_to_note[0],
replied_to_note[4],
replied_to_note[3],
ln)
note_title = "Re: " + replied_to_note[2]
elif optional_params.has_key("Incomplete note") and optional_params['Incomplete note']:
incomplete_note = optional_params['Incomplete note']
note_body_html = incomplete_note[1]
# TODO: Do we need to format incomplete body correctly as textual
# and html as above?
note_body_textual = incomplete_note[1]
note_title = incomplete_note[0]
if optional_params.has_key("Warnings"):
warnings = optional_params["Warnings"]
warnings_html = self.tmpl_warnings(warnings, ln)
else:
note_body_html = ""
note_body_textual = ""
note_title = ""
if optional_params.has_key("Warnings"):
warnings = optional_params["Warnings"]
warnings_html = self.tmpl_warnings(warnings, ln)
# TODO: calculate the url
file_upload_url = ""
action = """%s/yourbaskets/save_public_note?bskid=%i&recid=%i&ln=%s%s""" % \
(CFG_SITE_URL, bskid, recid, ln, '#note')
cancel = """%s/yourbaskets/display_public?bskid=%i&recid=%i&ln=%s""" % \
(CFG_SITE_URL, bskid, recid, ln)
editor = get_html_text_editor(name="note_body",
content=note_body_html,
textual_content=note_body_textual,
width="100%",
height="200px",
enabled=CFG_WEBBASKET_USE_RICH_TEXT_EDITOR,
file_upload_url=file_upload_url,
toolbar_set="WebComment")
add_note_html = """
<table cellspacing="0" cellpadding="0" class="bsknotescontentaddnote">
<tr>
<td class="bsknotescontentaddform">
<form name="write_note" method="post" action="%(action)s">
<a name="note"></a><strong>%(add_a_note_label)s</strong>
%(warnings_html)s
<p align="left">
<small>Subject:</small>
<br />
<input type="text" name="note_title" size="65" value="%(note_title)s" />
</p>
<p align="left">
<small>Note:</small>
<br />
%(editor)s
</p>
<input type="hidden" name="reply_to" value="%(reply_to)s" />
<p align="right">
<input type="submit" class="formbutton" value="%(submit_label)s" />
<input type="button" class="nonsubmitbutton" value="%(cancel_label)s" onClick="window.location='%(cancel)s'" />
</p>
</form>
</td>
</tr>
</table>""" % {'action': action,
'warnings_html': warnings_html,
'cancel': cancel,
'cancel_label': _('Cancel'),
'note_title': note_title,
'editor': editor,
'add_a_note_label': _('Add a note'),
'submit_label': _('Add note'),
'reply_to': optional_params.get("Reply to")}
notes_icon = '<img src="%s/img/wb-notes.png" style="vertical-align: top;" /> ' % (CFG_SITE_URL,)
if user_can_add_notes and not add_note_p:
add_note_url = """%s/yourbaskets/write_public_note?bskid=%i&recid=%i&ln=%s%s""" % \
(CFG_SITE_URL, bskid, recid, ln, '#note')
add_note_logo = """<img src="%s/img/wb-add-note.png" />""" % (CFG_SITE_URL,)
add_note = """<a href="%s">%s%s</a>""" % (add_note_url, add_note_logo, _("Add a note"))
else:
add_note = ""
notes_html = """
<table>
<tr>
<td class="bsknotesheadertitle">
<br />
<strong>%(notes_icon)s%(notes_label)s</strong>
<br />
<small>%(nb_notes)i notes in total</small>
</td>
<td class="bsknotesheaderoptions">
%(add_note)s
</td>
</tr>""" % {'notes_label': _('Notes'),
'notes_icon': notes_icon,
'add_note': (notes and user_can_add_notes and not add_note_p) and add_note or " ",
'nb_notes': len(notes)}
if notes or add_note or add_note_p:
notes_html += """
<tr>
<td colspan="2" class="bsknotescontent">"""
thread_history = [0]
for (cmt_uid, cmt_nickname, cmt_title, cmt_body, cmt_date, dummy, cmtid, reply_to) in notes:
if reply_to not in thread_history:
# Going one level down in the thread
thread_history.append(reply_to)
depth = thread_history.index(reply_to)
else:
depth = thread_history.index(reply_to)
thread_history = thread_history[:depth + 1]
notes_html += '<div style="margin-left:%spx">' % (depth*20)
if user_can_add_notes:
reply_to_note = """<a href="%s/yourbaskets/write_public_note?bskid=%i&recid=%i&cmtid=%i&ln=%s%s">%s</a>""" % \
(CFG_SITE_URL, bskid, recid, cmtid, ln, '#note', _('Reply'))
else:
reply_to_note = ""
notes_html += """
<table cellspacing="0" cellpadding="0" class="bsknotescontentnote">
<tr>
<td class="bsknotescontenttitle">
%(inline_anchor)s<img src="%(CFG_SITE_URL)s/img/user-icon-1-24x24.gif" />%(authorship)s
</td>
</tr>
<tr>
<td class="bsknotescontentbody">
<blockquote>
%(body)s
</blockquote>
</td>
</tr>
<tr>
<td class="bsknotescontentoptions">
%(reply_to_note)s
</td>
</tr>
</table>
<br />""" % {'inline_anchor': (not add_note_p and notes[-1][-1]==cmtid) and '<a name="note"></a>' or '',
'CFG_SITE_URL': CFG_SITE_URL,
'authorship': _("%(x_title)s, by %(x_name)s on %(x_date)s") % \
{'x_title': '<strong>' + (cmt_title and cgi.escape(cmt_title, True) \
or _('Note')) + '</strong>',
'x_name': '<a href="%(CFG_SITE_URL)s/yourmessages/write?msg_to=%(user)s">%(user_display)s</a>' % \
{'CFG_SITE_URL': CFG_SITE_URL,
'user': cmt_nickname or cmt_uid,
'user_display': cmt_nickname or get_user_info(cmt_uid)[2]},
'x_date': '<em>' + convert_datetext_to_dategui(cmt_date) + '</em>'},
'body': email_quoted_txt2html(escape_email_quoted_text(cmt_body)),
'reply_to_note': reply_to_note}
notes_html += '</div>'
if add_note_p:
notes_html += add_note_html
notes_html += """
</td>
</tr>"""
notes_html += """
<tr>
<td class="bsknotesfootertitle">
</td>
<td class="bsknotesfooteroptions">
%(add_note)s
</td>
</tr>
</table>""" % {'add_note': (user_can_add_notes and not add_note_p) and add_note or ' '}
return notes_html
def tmpl_create_pseudo_item(self, item, of='hb'):
""""""
if of == 'hb':
(es_title, es_desc, es_url) = tuple(item.split('\n'))
es_title = cgi.escape(es_title, True)
es_desc = cgi.escape(es_desc.replace('<br />', '\n'), True).replace('\n', '<br />')
out = """<strong>%s</strong>
<br />
<small>%s
<br />
<strong>URL:</strong> <a class="note" target="_blank" href="%s">%s</a>
</small>
""" % (es_title, es_desc, es_url, prettify_url(es_url))
if of == 'xm':
# TODO: xml output...
out = ""
return out
def tmpl_export_xml(self, body):
"""Template for the xml represantation for the selected basket/items."""
out = """
<collection xmlns="http://www.loc.gov/MARC21/slim">
%s
</collection>""" % (body,)
return out
def tmpl_create_export_as_list(self,
selected_category=CFG_WEBBASKET_CATEGORIES['PRIVATE'],
selected_topic="",
selected_group=0,
bskid=0,
item=(),
public=False):
"""Tamplate that creates a bullet list of export as formats for a basket or an item."""
list_of_export_as_formats = [('BibTeX','hx'), ('DC','xd'), ('EndNote','xe'), ('MARCXML', 'xm'), ('NLM','xn'), ('RefWorks','xw')]
recid = item and "&recid=" + str(item[0]) or ""
if not public:
href = "%s/yourbaskets/display?category=%s&topic=%s&group=%i&bskid=%i%s" % \
(CFG_SITE_URL,
selected_category,
selected_topic,
selected_group,
bskid,
recid)
else:
href = "%s/yourbaskets/display_public?bskid=%i%s" % \
(CFG_SITE_URL,
bskid,
recid)
export_as_html = ""
for format in list_of_export_as_formats:
export_as_html += """<a style="text-decoration:underline;font-weight:normal" href="%s&of=%s">%s</a>, """ % \
(href, format[1], format[0])
if export_as_html:
export_as_html = export_as_html[:-2]
out = """
<div style="float:right; text-align:right;">
<ul class="bsk_export_as_list">
<li>Export as
%s
</li>
</ul>
</div>""" % (export_as_html,)
return out
#############################################
########## SUPPLEMENTARY FUNCTIONS ##########
#############################################
def prettify_name(name, char_limit=10, nb_dots=3):
"""If name has more characters than char_limit return a shortened version of it
keeping the beginning (up to char_limit) and replacing the rest with dots."""
name = unicode(name, 'utf-8')
if len(name) > char_limit:
while name[char_limit-1] == ' ':
char_limit -= 1
prettified_name = name[:char_limit] + '.'*nb_dots
return prettified_name.encode('utf-8')
else:
return name.encode('utf-8')
def prettify_url(url, char_limit=50, nb_dots=3):
"""If the url has more characters than char_limit return a shortened version of it
keeping the beginning and ending and replacing the rest with dots."""
if len(url) > char_limit:
# let's set a minimum character limit
if char_limit < 5:
char_limit = 5
# let's set a maximum number of dots in relation to the character limit
if nb_dots > char_limit/4:
nb_dots = char_limit/5
nb_char_url = char_limit - nb_dots
nb_char_end = nb_char_url/4
nb_char_beg = nb_char_url - nb_char_end
return url[:nb_char_beg] + '.'*nb_dots + url[-nb_char_end:]
else:
return url
def create_search_box_select_options(category,
topic,
grpid,
topic_list,
group_list,
number_of_public_baskets,
ln):
"""Returns an html list of options for the select form field of the search box."""
_ = gettext_set_language(ln)
out = ""
if category:
if topic:
b = CFG_WEBBASKET_CATEGORIES['PRIVATE'] + '_' + cgi.escape(topic, True)
elif grpid:
b = CFG_WEBBASKET_CATEGORIES['GROUP'] + '_' + str(grpid)
else:
b = category
else:
b = ""
options = []
if topic_list or group_list:
options.append((_("All your baskets"), "", True, False))
if topic_list:
options.append((_("Your personal baskets"), CFG_WEBBASKET_CATEGORIES['PRIVATE'], False, True))
for topic_name in topic_list:
topic_label = cgi.escape(topic_name[0], True)
topic_value = "P_%s" % (cgi.escape(topic_name[0], True),)
options.append((topic_label, topic_value, False, False))
if group_list:
options.append((_("Your group baskets"), CFG_WEBBASKET_CATEGORIES['GROUP'], False, True))
for group_id_and_name in group_list:
group_label = cgi.escape(group_id_and_name[1], True)
group_value = "G_%i" % (group_id_and_name[0],)
options.append((group_label, group_value, False, False))
if number_of_public_baskets:
options.append((_("Your public baskets"), CFG_WEBBASKET_CATEGORIES['EXTERNAL'], False, True))
options.append((_("All the public baskets"), CFG_WEBBASKET_CATEGORIES['ALLPUBLIC'], True, False))
for option in options:
out += """
<option style="%(style)s" value="%(value)s"%(selected)s>%(label)s</option>""" % \
{'value': option[1],
'label': option[0],
'selected': option[1] == b and ' selected="selected"' or '',
#'style': option[2] and \
#( ( not option[1] or option[1] == CFG_WEBBASKET_CATEGORIES['ALLPUBLIC'] ) and "font-weight: bold;" or \
#( option[1] and option[1] != CFG_WEBBASKET_CATEGORIES['ALLPUBLIC'] ) and "font-weight: bold; margin-left: 5px;" ) or \
#"font-weight: normal; margin-left: 10px;"}
'style': option[2] and "font-weight: bold;" or \
option[3] and "font-weight: bold; margin-left: 5px;" or \
"font-weight: normal; margin-left: 10px;"}
return out
def create_add_box_select_options(category,
bskid,
personal_basket_list,
group_basket_list,
ln):
"""Returns an html list of options for the select form field of the add box."""
_ = gettext_set_language(ln)
out = ""
options = []
if category and bskid:
if category == CFG_WEBBASKET_CATEGORIES['PRIVATE']:
b = CFG_WEBBASKET_CATEGORIES['PRIVATE'] + '_' + str(bskid)
elif category == CFG_WEBBASKET_CATEGORIES['GROUP']:
b = CFG_WEBBASKET_CATEGORIES['GROUP'] + '_' + str(bskid)
elif category == CFG_WEBBASKET_CATEGORIES['EXTERNAL']:
b = CFG_WEBBASKET_CATEGORIES['EXTERNAL'] + '_' + str(bskid)
else:
b = ""
else:
b = ""
#option list format: [ name, value, 1st level: True/False, 2nd level: True/False]
# name: the name of the option, it will be used as its label in the list.
# value: the value of the option that will be sent as a POST variable through
# the select form field
# 1st level: bold, no margin, used for categories
# 2nd level: bold, small margin, used for topics and groups
# * when both levels are False: normal font, big margin,
# used for actual options *
# Let's set the default "Choose a basket..." option first.
#options= [(_("Choose a basket..."), str(-1), False, False)]
out += """
<option style="%(style)s" value="%(value)i">%(label)s</option>""" % \
{'style': "font-weight: normal;",
'value': -1,
'label': _("*** basket name ***")}
# Then, we parse the personal and group basket lists and dynamically create
# the list of options
if personal_basket_list:
options.append((_("Your personal baskets"), None, True, False))
for personal_topic in personal_basket_list:
personal_topic_name = cgi.escape(personal_topic[0], True)
personal_baskets = eval(personal_topic[1] + ",")
options.append((personal_topic_name, None, False, True))
for personal_basket in personal_baskets:
personal_basket_name = cgi.escape(personal_basket[1], True)
personal_basket_value = CFG_WEBBASKET_CATEGORIES['PRIVATE'] + "_" + str(personal_basket[0])
options.append((personal_basket_name, personal_basket_value, False, False))
if group_basket_list:
options.append((_("Your group baskets"), None, True, False))
for group_group in group_basket_list:
group_group_name = cgi.escape(group_group[0], True)
group_baskets = eval(group_group[1] + ",")
options.append((group_group_name, None, False, True))
for group_basket in group_baskets:
group_basket_name = cgi.escape(group_basket[1], True)
group_basket_value = CFG_WEBBASKET_CATEGORIES['GROUP'] + "_" + str(group_basket[0])
options.append((group_basket_name, group_basket_value, False, False))
if len(options) == 3:
# In case we only have 1 option, pretend b has the value of that option
# so that it is selected by default.
b = options[2][1]
for option in options:
out += """
<option style="%(style)s"%(value)s%(selected)s%(disabled)s>%(label)s</option>""" % \
{'value': not ( option[2] or option[3] ) and ' value="' + option[1] + '"' or '',
'label': option[0],
'selected': option[1] == b and ' selected="selected"' or '',
'disabled': ( option[2] or option[3] ) and ' disabled="disabled"' or '',
'style': option[2] and "font-weight: bold;" or \
option[3] and "font-weight: bold; margin-left: 5px;" or \
"font-weight: normal; margin-left: 10px;"}
return out
| gpl-2.0 |
izakp/hokusai | hokusai/commands/push.py | 1 | 1727 | import os
from hokusai.lib.command import command
from hokusai.lib.config import config
from hokusai.services.ecr import ECR
from hokusai.lib.common import print_green, shout
from hokusai.lib.exceptions import HokusaiError
from hokusai.services.docker import Docker
@command()
def push(tag, local_tag, build, filename, force, overwrite, skip_latest=False):
if force is None and shout('git status --porcelain'):
raise HokusaiError("Working directory is not clean. Aborting.")
if force is None and shout('git status --porcelain --ignored'):
raise HokusaiError("Working directory contains ignored files and/or directories. Aborting.")
ecr = ECR()
if not ecr.project_repo_exists():
raise HokusaiError("ECR repo %s does not exist... did you run `hokusai setup` for this project?" % config.project_name)
shout(ecr.get_login(), mask=(r'^(docker login -u) .+ (-p) .+ (.+)$', r'\1 ****** \2 ***** \3'))
if tag is None:
tag = shout('git rev-parse HEAD').strip()
if overwrite is None and ecr.tag_exists(tag):
raise HokusaiError("Tag %s already exists in registry. Aborting." % tag)
if build:
Docker().build()
build_tag = "hokusai_%s:%s" % (config.project_name, local_tag)
shout("docker tag %s %s:%s" % (build_tag, ecr.project_repo, tag))
shout("docker push %s:%s" % (ecr.project_repo, tag), print_output=True)
print_green("Pushed %s to %s:%s" % (build_tag, ecr.project_repo, tag), newline_after=True)
if skip_latest: return
shout("docker tag %s %s:%s" % (build_tag, ecr.project_repo, 'latest'))
shout("docker push %s:%s" % (ecr.project_repo, 'latest'), print_output=True)
print_green("Pushed %s to %s:%s" % (build_tag, ecr.project_repo, 'latest'), newline_after=True)
| mit |
mburakergenc/Malware-Detection-using-Machine-Learning | cuckoo/modules/processing/suricata.py | 1 | 10407 | # Copyright (C) 2010-2013 Claudio Guarnieri.
# Copyright (C) 2014-2016 Cuckoo Foundation.
# This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org
# See the file 'docs/LICENSE' for copying permission.
import json
import logging
import os
import shutil
import subprocess
import time
from lib.cuckoo.common.abstracts import Processing
from lib.cuckoo.common.exceptions import CuckooProcessingError
from lib.cuckoo.common.utils import md5_file, sha1_file
try:
import suricatasc
HAVE_SURICATASC = True
except ImportError:
HAVE_SURICATASC = False
log = logging.getLogger(__name__)
class Suricata(Processing):
"""Suricata processing module."""
# List of Suricata Signatures IDs that should be ignored.
sid_blacklist = [
# SURICATA FRAG IPv6 Fragmentation overlap
2200074,
# ET INFO InetSim Response from External Source Possible SinkHole
2017363,
# SURICATA UDPv4 invalid checksum
2200075,
]
def process_pcap_socket(self):
"""Process a PCAP file with Suricata in socket mode."""
if not HAVE_SURICATASC:
raise CuckooProcessingError(
"Suricata has been configured to run in socket mode but "
"suricatasc has not been installed, please re-install "
"Suricata or SuricataSC"
)
if not os.path.exists(self.socket):
raise CuckooProcessingError(
"Suricata has been configured to run in socket mode "
"but the socket is unavailable"
)
suri = suricatasc.SuricataSC(self.socket)
try:
suri.connect()
except suricatasc.SuricataException as e:
raise CuckooProcessingError(
"Error connecting to Suricata in socket mode: %s" % e
)
# Submit the PCAP file.
ret = suri.send_command("pcap-file", {
"filename": self.pcap_path,
"output-dir": self.suricata_path,
})
if not ret or ret["return"] != "OK":
raise CuckooProcessingError(
"Error submitting PCAP file to Suricata in socket mode, "
"return value: %s" % ret
)
# TODO Should we add a timeout here? If we do so we should also add
# timeout logic to the binary mode.
while True:
ret = suri.send_command("pcap-current")
# When the pcap file has been processed the "current pcap" file
# will be none.
if ret and ret["message"] == "None":
break
time.sleep(1)
def process_pcap_binary(self):
"""Process a PCAP file with Suricata by running Suricata.
Using the socket mode is preferred as the plain binary mode requires
Suricata to load all its rules for every PCAP file and thus takes a
couple of performance heavy seconds to set itself up.
"""
if not os.path.isfile(self.suricata):
raise CuckooProcessingError("Unable to locate Suricata binary")
if not os.path.isfile(self.config_path):
raise CuckooProcessingError(
"Unable to locate Suricata configuration"
)
args = [
self.suricata,
"-c", self.config_path,
"-k", "none",
"-l", self.suricata_path,
"-r", self.pcap_path,
]
try:
subprocess.check_call(args)
except subprocess.CalledProcessError as e:
raise CuckooProcessingError(
"Suricata returned an error processing this pcap: %s" % e
)
def parse_eve_json(self):
"""Parse the eve.json file."""
eve_log = os.path.join(self.suricata_path, self.eve_log)
if not os.path.isfile(eve_log):
log.warning("Unable to find the eve.json log file")
return
for line in open(eve_log, "rb"):
event = json.loads(line)
if event["event_type"] == "alert":
alert = event["alert"]
if alert["signature_id"] in self.sid_blacklist:
log.debug(
"Ignoring alert with sid=%d, signature=%s",
alert["signature_id"], alert["signature"]
)
continue
if alert["signature"].startswith("SURICATA STREAM"):
log.debug(
"Ignoring alert starting with \"SURICATA STREAM\""
)
continue
self.results["alerts"].append({
"sid": alert["signature_id"],
"src_ip": event.get("src_ip"),
"src_port": event.get("src_port"),
"dst_ip": event["dest_ip"],
"dst_port": event.get("dest_port"),
"protocol": event.get("proto"),
"timestamp": event.get("timestamp"),
"category": alert.get("category") or "undefined",
"signature": alert["signature"],
})
elif event["event_type"] == "http":
http = event["http"]
referer = http.get("http_referer")
if referer == "<unknown>":
referer = None
user_agent = http.get("http_user_agent")
if user_agent == "<unknown>":
user_agent = None
self.results["http"].append({
"src_ip": event.get("src_ip"),
"src_port": event.get("src_port"),
"dst_ip": event.get("dest_ip"),
"dst_port": event.get("dest_port"),
"timestamp": event.get("timestamp"),
"method": http.get("http_method"),
"hostname": http.get("hostname"),
"url": http.get("url"),
"status": "%s" % http.get("status"),
"content_type": http.get("http_content_type"),
"user_agent": user_agent,
"referer": referer,
"length": http.get("length"),
})
elif event["event_type"] == "tls":
tls = event["tls"]
self.results["tls"].append({
"src_ip": event.get("src_ip"),
"src_port": event.get("src_port"),
"dst_ip": event.get("dest_ip"),
"dst_port": event.get("dest_port"),
"timestamp": event.get("timestamp"),
"fingerprint": tls.get("fingerprint"),
"issuer": tls.get("issuerdn"),
"version": tls.get("version"),
"subject": tls.get("subject"),
})
def parse_files(self):
"""Parse the files-json.log file and its associated files."""
files_log = os.path.join(self.suricata_path, self.files_log)
if not os.path.isfile(files_log):
log.warning("Unable to find the files-json.log log file")
return
files = {}
# Index all the available files.
files_dir = os.path.join(self.suricata_path, self.files_dir)
if not os.path.exists(files_dir):
log.warning("Suricata files dir is not available. Maybe you forgot to enable Suricata file-store ?")
return
for filename in os.listdir(files_dir):
filepath = os.path.join(files_dir, filename)
files[md5_file(filepath)] = filepath
for line in open(files_log, "rb"):
event = json.loads(line)
# Not entirely sure what's up, but some files are given just an
# ID, some files are given just an md5 hash (and maybe some get
# neither?) So take care of these situations.
if "id" in event:
filepath = os.path.join(files_dir, "file.%s" % event["id"])
elif "md5" in event:
filepath = files.get(event["md5"])
else:
filepath = None
if not filepath or not os.path.isfile(filepath):
log.warning(
"Suricata dropped file with id=%s and md5=%s not found, "
"skipping it..", event.get("id"), event.get("md5")
)
continue
referer = event.get("http_referer")
if referer == "<unknown>":
referer = None
self.results["files"].append({
"id": int(filepath.split(".", 1)[-1]),
"filesize": event["size"],
"filename": os.path.basename(event["filename"]),
"hostname": event.get("http_host"),
"uri": event.get("http_uri"),
"md5": md5_file(filepath),
"sha1": sha1_file(filepath),
"magic": event.get("magic"),
"referer": referer,
})
def run(self):
self.key = "suricata"
self.results = {
"alerts": [],
"tls": [],
"files": [],
"http": [],
}
self.suricata = self.options.get("suricata", "/usr/bin/suricata")
self.config_path = self.options.get("conf", "/etc/suricata/suricata.yaml")
self.eve_log = self.options.get("eve_log", "eve.json")
self.files_log = self.options.get("files_log", "files-json.log")
self.files_dir = self.options.get("files_dir", "files")
# Determines whether we're in socket more or binary mode.
self.socket = self.options.get("socket")
if not os.path.isfile(self.pcap_path):
log.warning("Unable to run Suricata as no pcap is available")
return self.results
# Remove any existing Suricata related log-files before we
# run Suricata again. I.e., prevent reprocessing an analysis from
# generating duplicate results.
if os.path.isdir(self.suricata_path):
shutil.rmtree(self.suricata_path)
os.mkdir(self.suricata_path)
if self.socket:
self.process_pcap_socket()
else:
self.process_pcap_binary()
self.parse_eve_json()
self.parse_files()
return self.results
| mit |
motmot/libcamiface | prosilica_help.py | 1 | 1097 | """check the installed Prosilica GigE SDK version number"""
import ctypes, sys
global _libprosilica
_libprosilica = None
ULong = ctypes.c_long # XXX should be unsigned long
def _load_libprosilica():
"""load the prosilica shared library"""
global _libprosilica
if _libprosilica is None:
if sys.platform.startswith('linux'):
_libprosilica = ctypes.cdll.LoadLibrary('libPvAPI.so')
elif sys.platform.startswith('win'):
_libprosilica = ctypes.CDLL('PvAPI.dll')
else:
raise NotImplementedError('unsupported platform')
argtype = ctypes.POINTER(ULong)
_libprosilica.PvVersion.argtypes = [argtype,argtype]
return _libprosilica
def get_prosilica_version():
"""get the version number of the prosilica shared library"""
libprosilica = _load_libprosilica()
major = ULong()
minor = ULong()
libprosilica.PvVersion(ctypes.byref(major), ctypes.byref(minor))
return major.value, minor.value
if __name__=='__main__':
print 'you have Prosilica SDK %s.%s installed'%get_prosilica_version()
| bsd-2-clause |
yanheven/horizon | openstack_dashboard/dashboards/admin/flavors/panel.py | 46 | 1059 | # Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from django.utils.translation import ugettext_lazy as _
import horizon
from openstack_dashboard.dashboards.admin import dashboard
class Flavors(horizon.Panel):
name = _("Flavors")
slug = 'flavors'
permissions = ('openstack.services.compute',)
dashboard.Admin.register(Flavors)
| apache-2.0 |
datenbetrieb/odoo | openerp/addons/test_impex/tests/test_import.py | 231 | 30712 | # -*- coding: utf-8 -*-
import openerp.modules.registry
import openerp
from openerp.tests import common
from openerp.tools.misc import mute_logger
def ok(n):
""" Successful import of ``n`` records
:param int n: number of records which should have been imported
"""
return n, 0, 0, 0
def error(row, message, record=None, **kwargs):
""" Failed import of the record ``record`` at line ``row``, with the error
message ``message``
:param str message:
:param dict record:
"""
return (
-1, dict(record or {}, **kwargs),
"Line %d : %s" % (row, message),
'')
def values(seq, field='value'):
return [item[field] for item in seq]
class ImporterCase(common.TransactionCase):
model_name = False
def __init__(self, *args, **kwargs):
super(ImporterCase, self).__init__(*args, **kwargs)
self.model = None
def setUp(self):
super(ImporterCase, self).setUp()
self.model = self.registry(self.model_name)
def import_(self, fields, rows, context=None):
return self.model.import_data(
self.cr, openerp.SUPERUSER_ID, fields, rows, context=context)
def read(self, fields=('value',), domain=(), context=None):
return self.model.read(
self.cr, openerp.SUPERUSER_ID,
self.model.search(self.cr, openerp.SUPERUSER_ID, domain, context=context),
fields=fields, context=context)
def browse(self, domain=(), context=None):
return self.model.browse(
self.cr, openerp.SUPERUSER_ID,
self.model.search(self.cr, openerp.SUPERUSER_ID, domain, context=context),
context=context)
def xid(self, record):
ModelData = self.registry('ir.model.data')
ids = ModelData.search(
self.cr, openerp.SUPERUSER_ID,
[('model', '=', record._name), ('res_id', '=', record.id)])
if ids:
d = ModelData.read(
self.cr, openerp.SUPERUSER_ID, ids, ['name', 'module'])[0]
if d['module']:
return '%s.%s' % (d['module'], d['name'])
return d['name']
name = record.name_get()[0][1]
# fix dotted name_get results, otherwise xid lookups blow up
name = name.replace('.', '-')
ModelData.create(self.cr, openerp.SUPERUSER_ID, {
'name': name,
'model': record._name,
'res_id': record.id,
'module': '__test__'
})
return '__test__.' + name
class test_ids_stuff(ImporterCase):
model_name = 'export.integer'
def test_create_with_id(self):
self.assertEqual(
self.import_(['.id', 'value'], [['42', '36']]),
error(1, u"Unknown database identifier '42'"))
def test_create_with_xid(self):
self.assertEqual(
self.import_(['id', 'value'], [['somexmlid', '42']]),
ok(1))
self.assertEqual(
'somexmlid',
self.xid(self.browse()[0]))
def test_update_with_id(self):
id = self.model.create(self.cr, openerp.SUPERUSER_ID, {'value': 36})
self.assertEqual(
36,
self.model.browse(self.cr, openerp.SUPERUSER_ID, id).value)
self.assertEqual(
self.import_(['.id', 'value'], [[str(id), '42']]),
ok(1))
self.assertEqual(
[42], # updated value to imported
values(self.read()))
def test_update_with_xid(self):
self.import_(['id', 'value'], [['somexmlid', '36']])
self.assertEqual([36], values(self.read()))
self.import_(['id', 'value'], [['somexmlid', '1234567']])
self.assertEqual([1234567], values(self.read()))
def test_wrong_format(self):
self.assertEqual(
self.import_(['value'], [['50%']]),
error(1, u"'50%' does not seem to be an integer for field 'unknown'"))
class test_boolean_field(ImporterCase):
model_name = 'export.boolean'
def test_empty(self):
self.assertEqual(
self.import_(['value'], []),
ok(0))
def test_exported(self):
self.assertEqual(
self.import_(['value'], [
['False'],
['True'],
]),
ok(2))
records = self.read()
self.assertEqual([
False,
True,
], values(records))
def test_falses(self):
self.assertEqual(
self.import_(['value'], [
[u'0'],
[u'no'],
[u'false'],
[u'FALSE'],
[u''],
]),
ok(5))
self.assertEqual([
False,
False,
False,
False,
False,
],
values(self.read()))
def test_trues(self):
self.assertEqual(
self.import_(['value'], [
['off'],
['None'],
['nil'],
['()'],
['f'],
['#f'],
# Problem: OpenOffice (and probably excel) output localized booleans
['VRAI'],
[u'OFF'],
[u'是的'],
['!&%#${}'],
['%(field)s'],
]),
ok(11))
self.assertEqual(
[True] * 11,
values(self.read()))
class test_integer_field(ImporterCase):
model_name = 'export.integer'
def test_none(self):
self.assertEqual(
self.import_(['value'], []),
ok(0))
def test_empty(self):
self.assertEqual(
self.import_(['value'], [['']]),
ok(1))
self.assertEqual(
[False],
values(self.read()))
def test_zero(self):
self.assertEqual(
self.import_(['value'], [['0']]),
ok(1))
self.assertEqual(
self.import_(['value'], [['-0']]),
ok(1))
self.assertEqual([False, False], values(self.read()))
def test_positives(self):
self.assertEqual(
self.import_(['value'], [
['1'],
['42'],
[str(2**31-1)],
['12345678']
]),
ok(4))
self.assertEqual([
1, 42, 2**31-1, 12345678
], values(self.read()))
def test_negatives(self):
self.assertEqual(
self.import_(['value'], [
['-1'],
['-42'],
[str(-(2**31 - 1))],
[str(-(2**31))],
['-12345678']
]),
ok(5))
self.assertEqual([
-1, -42, -(2**31 - 1), -(2**31), -12345678
], values(self.read()))
@mute_logger('openerp.sql_db')
def test_out_of_range(self):
self.assertEqual(
self.import_(['value'], [[str(2**31)]]),
error(1, "integer out of range\n"))
# auto-rollbacks if error is in process_liness, but not during
# ir.model.data write. Can differentiate because former ends lines
# error lines with "!"
self.cr.rollback()
self.assertEqual(
self.import_(['value'], [[str(-2**32)]]),
error(1, "integer out of range\n"))
def test_nonsense(self):
self.assertEqual(
self.import_(['value'], [['zorglub']]),
error(1, u"'zorglub' does not seem to be an integer for field 'unknown'"))
class test_float_field(ImporterCase):
model_name = 'export.float'
def test_none(self):
self.assertEqual(
self.import_(['value'], []),
ok(0))
def test_empty(self):
self.assertEqual(
self.import_(['value'], [['']]),
ok(1))
self.assertEqual(
[False],
values(self.read()))
def test_zero(self):
self.assertEqual(
self.import_(['value'], [['0']]),
ok(1))
self.assertEqual(
self.import_(['value'], [['-0']]),
ok(1))
self.assertEqual([False, False], values(self.read()))
def test_positives(self):
self.assertEqual(
self.import_(['value'], [
['1'],
['42'],
[str(2**31-1)],
['12345678'],
[str(2**33)],
['0.000001'],
]),
ok(6))
self.assertEqual([
1, 42, 2**31-1, 12345678, 2.0**33, .000001
], values(self.read()))
def test_negatives(self):
self.assertEqual(
self.import_(['value'], [
['-1'],
['-42'],
[str(-2**31 + 1)],
[str(-2**31)],
['-12345678'],
[str(-2**33)],
['-0.000001'],
]),
ok(7))
self.assertEqual([
-1, -42, -(2**31 - 1), -(2**31), -12345678, -2.0**33, -.000001
], values(self.read()))
def test_nonsense(self):
self.assertEqual(
self.import_(['value'], [['foobar']]),
error(1, u"'foobar' does not seem to be a number for field 'unknown'"))
class test_string_field(ImporterCase):
model_name = 'export.string.bounded'
def test_empty(self):
self.assertEqual(
self.import_(['value'], [['']]),
ok(1))
self.assertEqual([False], values(self.read()))
def test_imported(self):
self.assertEqual(
self.import_(['value'], [
[u'foobar'],
[u'foobarbaz'],
[u'Með suð í eyrum við spilum endalaust'],
[u"People 'get' types. They use them all the time. Telling "
u"someone he can't pound a nail with a banana doesn't much "
u"surprise him."]
]),
ok(4))
self.assertEqual([
u"foobar",
u"foobarbaz",
u"Með suð í eyrum ",
u"People 'get' typ",
], values(self.read()))
class test_unbound_string_field(ImporterCase):
model_name = 'export.string'
def test_imported(self):
self.assertEqual(
self.import_(['value'], [
[u'í dag viðrar vel til loftárása'],
# ackbar.jpg
[u"If they ask you about fun, you tell them – fun is a filthy"
u" parasite"]
]),
ok(2))
self.assertEqual([
u"í dag viðrar vel til loftárása",
u"If they ask you about fun, you tell them – fun is a filthy parasite"
], values(self.read()))
class test_text(ImporterCase):
model_name = 'export.text'
def test_empty(self):
self.assertEqual(
self.import_(['value'], [['']]),
ok(1))
self.assertEqual([False], values(self.read()))
def test_imported(self):
s = (u"Breiðskífa er notað um útgefna hljómplötu sem inniheldur "
u"stúdíóupptökur frá einum flytjanda. Breiðskífur eru oftast "
u"milli 25-80 mínútur og er lengd þeirra oft miðuð við 33⅓ "
u"snúninga 12 tommu vínylplötur (sem geta verið allt að 30 mín "
u"hvor hlið).\n\nBreiðskífur eru stundum tvöfaldar og eru þær þá"
u" gefnar út á tveimur geisladiskum eða tveimur vínylplötum.")
self.assertEqual(
self.import_(['value'], [[s]]),
ok(1))
self.assertEqual([s], values(self.read()))
class test_selection(ImporterCase):
model_name = 'export.selection'
translations_fr = [
("Qux", "toto"),
("Bar", "titi"),
("Foo", "tete"),
]
def test_imported(self):
self.assertEqual(
self.import_(['value'], [
['Qux'],
['Bar'],
['Foo'],
['2'],
]),
ok(4))
self.assertEqual([3, 2, 1, 2], values(self.read()))
def test_imported_translated(self):
self.registry('res.lang').create(self.cr, openerp.SUPERUSER_ID, {
'name': u'Français',
'code': 'fr_FR',
'translatable': True,
'date_format': '%d.%m.%Y',
'decimal_point': ',',
'thousands_sep': ' ',
})
Translations = self.registry('ir.translation')
for source, value in self.translations_fr:
Translations.create(self.cr, openerp.SUPERUSER_ID, {
'name': 'export.selection,value',
'lang': 'fr_FR',
'type': 'selection',
'src': source,
'value': value
})
self.assertEqual(
self.import_(['value'], [
['toto'],
['tete'],
['titi'],
], context={'lang': 'fr_FR'}),
ok(3))
self.assertEqual([3, 1, 2], values(self.read()))
self.assertEqual(
self.import_(['value'], [['Foo']], context={'lang': 'fr_FR'}),
ok(1))
def test_invalid(self):
self.assertEqual(
self.import_(['value'], [['Baz']]),
error(1, u"Value 'Baz' not found in selection field 'unknown'"))
self.cr.rollback()
self.assertEqual(
self.import_(['value'], [[42]]),
error(1, u"Value '42' not found in selection field 'unknown'"))
class test_selection_function(ImporterCase):
model_name = 'export.selection.function'
translations_fr = [
("Corge", "toto"),
("Grault", "titi"),
("Wheee", "tete"),
("Moog", "tutu"),
]
def test_imported(self):
""" import uses fields_get, so translates import label (may or may not
be good news) *and* serializes the selection function to reverse it:
import does not actually know that the selection field uses a function
"""
# NOTE: conflict between a value and a label => ?
self.assertEqual(
self.import_(['value'], [
['3'],
["Grault"],
]),
ok(2))
self.assertEqual(
[3, 1],
values(self.read()))
def test_translated(self):
""" Expects output of selection function returns translated labels
"""
self.registry('res.lang').create(self.cr, openerp.SUPERUSER_ID, {
'name': u'Français',
'code': 'fr_FR',
'translatable': True,
'date_format': '%d.%m.%Y',
'decimal_point': ',',
'thousands_sep': ' ',
})
Translations = self.registry('ir.translation')
for source, value in self.translations_fr:
Translations.create(self.cr, openerp.SUPERUSER_ID, {
'name': 'export.selection,value',
'lang': 'fr_FR',
'type': 'selection',
'src': source,
'value': value
})
self.assertEqual(
self.import_(['value'], [
['toto'],
['tete'],
], context={'lang': 'fr_FR'}),
ok(2))
self.assertEqual(
self.import_(['value'], [['Wheee']], context={'lang': 'fr_FR'}),
ok(1))
class test_m2o(ImporterCase):
model_name = 'export.many2one'
def test_by_name(self):
# create integer objects
integer_id1 = self.registry('export.integer').create(
self.cr, openerp.SUPERUSER_ID, {'value': 42})
integer_id2 = self.registry('export.integer').create(
self.cr, openerp.SUPERUSER_ID, {'value': 36})
# get its name
name1 = dict(self.registry('export.integer').name_get(
self.cr, openerp.SUPERUSER_ID,[integer_id1]))[integer_id1]
name2 = dict(self.registry('export.integer').name_get(
self.cr, openerp.SUPERUSER_ID,[integer_id2]))[integer_id2]
self.assertEqual(
self.import_(['value'], [
# import by name_get
[name1],
[name1],
[name2],
]),
ok(3))
# correct ids assigned to corresponding records
self.assertEqual([
(integer_id1, name1),
(integer_id1, name1),
(integer_id2, name2),],
values(self.read()))
def test_by_xid(self):
ExportInteger = self.registry('export.integer')
integer_id = ExportInteger.create(
self.cr, openerp.SUPERUSER_ID, {'value': 42})
xid = self.xid(ExportInteger.browse(
self.cr, openerp.SUPERUSER_ID, [integer_id])[0])
self.assertEqual(
self.import_(['value/id'], [[xid]]),
ok(1))
b = self.browse()
self.assertEqual(42, b[0].value.value)
def test_by_id(self):
integer_id = self.registry('export.integer').create(
self.cr, openerp.SUPERUSER_ID, {'value': 42})
self.assertEqual(
self.import_(['value/.id'], [[integer_id]]),
ok(1))
b = self.browse()
self.assertEqual(42, b[0].value.value)
def test_by_names(self):
integer_id1 = self.registry('export.integer').create(
self.cr, openerp.SUPERUSER_ID, {'value': 42})
integer_id2 = self.registry('export.integer').create(
self.cr, openerp.SUPERUSER_ID, {'value': 42})
name1 = dict(self.registry('export.integer').name_get(
self.cr, openerp.SUPERUSER_ID,[integer_id1]))[integer_id1]
name2 = dict(self.registry('export.integer').name_get(
self.cr, openerp.SUPERUSER_ID,[integer_id2]))[integer_id2]
# names should be the same
self.assertEqual(name1, name2)
self.assertEqual(
self.import_(['value'], [[name2]]),
ok(1))
self.assertEqual([
(integer_id1, name1)
], values(self.read()))
def test_fail_by_implicit_id(self):
""" Can't implicitly import records by id
"""
# create integer objects
integer_id1 = self.registry('export.integer').create(
self.cr, openerp.SUPERUSER_ID, {'value': 42})
integer_id2 = self.registry('export.integer').create(
self.cr, openerp.SUPERUSER_ID, {'value': 36})
self.assertEqual(
self.import_(['value'], [
# import by id, without specifying it
[integer_id1],
[integer_id2],
[integer_id1],
]),
error(1, u"No matching record found for name '%s' in field 'unknown'" % integer_id1))
def test_sub_field(self):
""" Does not implicitly create the record, does not warn that you can't
import m2o subfields (at all)...
"""
self.assertEqual(
self.import_(['value/value'], [['42']]),
error(1, u"Can not create Many-To-One records indirectly, import the field separately"))
def test_fail_noids(self):
self.assertEqual(
self.import_(['value'], [['nameisnoexist:3']]),
error(1, u"No matching record found for name 'nameisnoexist:3' in field 'unknown'"))
self.cr.rollback()
self.assertEqual(
self.import_(['value/id'], [['noxidhere']]),
error(1, u"No matching record found for external id 'noxidhere' in field 'unknown'"))
self.cr.rollback()
self.assertEqual(
self.import_(['value/.id'], [[66]]),
error(1, u"No matching record found for database id '66' in field 'unknown'"))
class test_m2m(ImporterCase):
model_name = 'export.many2many'
# apparently, one and only thing which works is a
# csv_internal_sep-separated list of ids, xids, or names (depending if
# m2m/.id, m2m/id or m2m[/anythingelse]
def test_ids(self):
id1 = self.registry('export.many2many.other').create(
self.cr, openerp.SUPERUSER_ID, {'value': 3, 'str': 'record0'})
id2 = self.registry('export.many2many.other').create(
self.cr, openerp.SUPERUSER_ID, {'value': 44, 'str': 'record1'})
id3 = self.registry('export.many2many.other').create(
self.cr, openerp.SUPERUSER_ID, {'value': 84, 'str': 'record2'})
id4 = self.registry('export.many2many.other').create(
self.cr, openerp.SUPERUSER_ID, {'value': 9, 'str': 'record3'})
id5 = self.registry('export.many2many.other').create(
self.cr, openerp.SUPERUSER_ID, {'value': 99, 'str': 'record4'})
self.assertEqual(
self.import_(['value/.id'], [
['%d,%d' % (id1, id2)],
['%d,%d,%d' % (id1, id3, id4)],
['%d,%d,%d' % (id1, id2, id3)],
['%d' % id5]
]),
ok(4))
ids = lambda records: [record.id for record in records]
b = self.browse()
self.assertEqual(ids(b[0].value), [id1, id2])
self.assertEqual(values(b[0].value), [3, 44])
self.assertEqual(ids(b[2].value), [id1, id2, id3])
self.assertEqual(values(b[2].value), [3, 44, 84])
def test_noids(self):
self.assertEqual(
self.import_(['value/.id'], [['42']]),
error(1, u"No matching record found for database id '42' in field 'unknown'"))
def test_xids(self):
M2O_o = self.registry('export.many2many.other')
id1 = M2O_o.create(self.cr, openerp.SUPERUSER_ID, {'value': 3, 'str': 'record0'})
id2 = M2O_o.create(self.cr, openerp.SUPERUSER_ID, {'value': 44, 'str': 'record1'})
id3 = M2O_o.create(self.cr, openerp.SUPERUSER_ID, {'value': 84, 'str': 'record2'})
id4 = M2O_o.create(self.cr, openerp.SUPERUSER_ID, {'value': 9, 'str': 'record3'})
records = M2O_o.browse(self.cr, openerp.SUPERUSER_ID, [id1, id2, id3, id4])
self.assertEqual(
self.import_(['value/id'], [
['%s,%s' % (self.xid(records[0]), self.xid(records[1]))],
['%s' % self.xid(records[3])],
['%s,%s' % (self.xid(records[2]), self.xid(records[1]))],
]),
ok(3))
b = self.browse()
self.assertEqual(values(b[0].value), [3, 44])
self.assertEqual(values(b[2].value), [44, 84])
def test_noxids(self):
self.assertEqual(
self.import_(['value/id'], [['noxidforthat']]),
error(1, u"No matching record found for external id 'noxidforthat' in field 'unknown'"))
def test_names(self):
M2O_o = self.registry('export.many2many.other')
id1 = M2O_o.create(self.cr, openerp.SUPERUSER_ID, {'value': 3, 'str': 'record0'})
id2 = M2O_o.create(self.cr, openerp.SUPERUSER_ID, {'value': 44, 'str': 'record1'})
id3 = M2O_o.create(self.cr, openerp.SUPERUSER_ID, {'value': 84, 'str': 'record2'})
id4 = M2O_o.create(self.cr, openerp.SUPERUSER_ID, {'value': 9, 'str': 'record3'})
records = M2O_o.browse(self.cr, openerp.SUPERUSER_ID, [id1, id2, id3, id4])
name = lambda record: record.name_get()[0][1]
self.assertEqual(
self.import_(['value'], [
['%s,%s' % (name(records[1]), name(records[2]))],
['%s,%s,%s' % (name(records[0]), name(records[1]), name(records[2]))],
['%s,%s' % (name(records[0]), name(records[3]))],
]),
ok(3))
b = self.browse()
self.assertEqual(values(b[1].value), [3, 44, 84])
self.assertEqual(values(b[2].value), [3, 9])
def test_nonames(self):
self.assertEqual(
self.import_(['value'], [['wherethem2mhavenonames']]),
error(1, u"No matching record found for name 'wherethem2mhavenonames' in field 'unknown'"))
def test_import_to_existing(self):
M2O_o = self.registry('export.many2many.other')
id1 = M2O_o.create(self.cr, openerp.SUPERUSER_ID, {'value': 3, 'str': 'record0'})
id2 = M2O_o.create(self.cr, openerp.SUPERUSER_ID, {'value': 44, 'str': 'record1'})
id3 = M2O_o.create(self.cr, openerp.SUPERUSER_ID, {'value': 84, 'str': 'record2'})
id4 = M2O_o.create(self.cr, openerp.SUPERUSER_ID, {'value': 9, 'str': 'record3'})
xid = 'myxid'
self.assertEqual(
self.import_(['id', 'value/.id'], [[xid, '%d,%d' % (id1, id2)]]),
ok(1))
self.assertEqual(
self.import_(['id', 'value/.id'], [[xid, '%d,%d' % (id3, id4)]]),
ok(1))
b = self.browse()
self.assertEqual(len(b), 1)
# TODO: replacement of existing m2m values is correct?
self.assertEqual(values(b[0].value), [84, 9])
class test_o2m(ImporterCase):
model_name = 'export.one2many'
def test_name_get(self):
s = u'Java is a DSL for taking large XML files and converting them to' \
u' stack traces'
self.assertEqual(
self.import_(
['const', 'value'],
[['5', s]]),
error(1, u"No matching record found for name '%s' in field 'unknown'" % s))
def test_single(self):
self.assertEqual(
self.import_(['const', 'value/value'], [
['5', '63']
]),
ok(1))
(b,) = self.browse()
self.assertEqual(b.const, 5)
self.assertEqual(values(b.value), [63])
def test_multicore(self):
self.assertEqual(
self.import_(['const', 'value/value'], [
['5', '63'],
['6', '64'],
]),
ok(2))
b1, b2 = self.browse()
self.assertEqual(b1.const, 5)
self.assertEqual(values(b1.value), [63])
self.assertEqual(b2.const, 6)
self.assertEqual(values(b2.value), [64])
def test_multisub(self):
self.assertEqual(
self.import_(['const', 'value/value'], [
['5', '63'],
['', '64'],
['', '65'],
['', '66'],
]),
ok(4))
(b,) = self.browse()
self.assertEqual(values(b.value), [63, 64, 65, 66])
def test_multi_subfields(self):
self.assertEqual(
self.import_(['value/str', 'const', 'value/value'], [
['this', '5', '63'],
['is', '', '64'],
['the', '', '65'],
['rhythm', '', '66'],
]),
ok(4))
(b,) = self.browse()
self.assertEqual(values(b.value), [63, 64, 65, 66])
self.assertEqual(
values(b.value, 'str'),
'this is the rhythm'.split())
def test_link_inline(self):
id1 = self.registry('export.one2many.child').create(self.cr, openerp.SUPERUSER_ID, {
'str': 'Bf', 'value': 109
})
id2 = self.registry('export.one2many.child').create(self.cr, openerp.SUPERUSER_ID, {
'str': 'Me', 'value': 262
})
try:
self.import_(['const', 'value/.id'], [
['42', '%d,%d' % (id1, id2)]
])
except ValueError, e:
# should be Exception(Database ID doesn't exist: export.one2many.child : $id1,$id2)
self.assertIs(type(e), ValueError)
self.assertEqual(
e.args[0],
"invalid literal for int() with base 10: '%d,%d'" % (id1, id2))
def test_link(self):
id1 = self.registry('export.one2many.child').create(self.cr, openerp.SUPERUSER_ID, {
'str': 'Bf', 'value': 109
})
id2 = self.registry('export.one2many.child').create(self.cr, openerp.SUPERUSER_ID, {
'str': 'Me', 'value': 262
})
self.assertEqual(
self.import_(['const', 'value/.id'], [
['42', str(id1)],
['', str(id2)],
]),
ok(2))
[b] = self.browse()
self.assertEqual(b.const, 42)
# automatically forces link between core record and o2ms
self.assertEqual(values(b.value), [109, 262])
self.assertEqual(values(b.value, field='parent_id'), [b, b])
def test_link_2(self):
O2M_c = self.registry('export.one2many.child')
id1 = O2M_c.create(self.cr, openerp.SUPERUSER_ID, {
'str': 'Bf', 'value': 109
})
id2 = O2M_c.create(self.cr, openerp.SUPERUSER_ID, {
'str': 'Me', 'value': 262
})
self.assertEqual(
self.import_(['const', 'value/.id', 'value/value'], [
['42', str(id1), '1'],
['', str(id2), '2'],
]),
ok(2))
[b] = self.browse()
self.assertEqual(b.const, 42)
self.assertEqual(values(b.value), [1, 2])
self.assertEqual(values(b.value, field='parent_id'), [b, b])
class test_o2m_multiple(ImporterCase):
model_name = 'export.one2many.multiple'
def test_multi_mixed(self):
self.assertEqual(
self.import_(['const', 'child1/value', 'child2/value'], [
['5', '11', '21'],
['', '12', '22'],
['', '13', '23'],
['', '14', ''],
]),
ok(4))
[b] = self.browse()
self.assertEqual(values(b.child1), [11, 12, 13, 14])
self.assertEqual(values(b.child2), [21, 22, 23])
def test_multi(self):
self.assertEqual(
self.import_(['const', 'child1/value', 'child2/value'], [
['5', '11', '21'],
['', '12', ''],
['', '13', ''],
['', '14', ''],
['', '', '22'],
['', '', '23'],
]),
ok(6))
[b] = self.browse()
self.assertEqual(values(b.child1), [11, 12, 13, 14])
self.assertEqual(values(b.child2), [21, 22, 23])
def test_multi_fullsplit(self):
self.assertEqual(
self.import_(['const', 'child1/value', 'child2/value'], [
['5', '11', ''],
['', '12', ''],
['', '13', ''],
['', '14', ''],
['', '', '21'],
['', '', '22'],
['', '', '23'],
]),
ok(7))
[b] = self.browse()
self.assertEqual(b.const, 5)
self.assertEqual(values(b.child1), [11, 12, 13, 14])
self.assertEqual(values(b.child2), [21, 22, 23])
# function, related, reference: written to db as-is...
# => function uses @type for value coercion/conversion
| agpl-3.0 |
openstack/cinder | tools/config/generate_cinder_opts.py | 2 | 10022 | #!/usr/bin/env python3
# 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 collections
import os
import subprocess
import textwrap
from cinder.volume import configuration
from cinder.compute import nova
OrderedDict = collections.OrderedDict
BASEDIR = os.path.split(os.path.realpath(__file__))[0] + "/../../"
if __name__ == "__main__":
os.chdir(BASEDIR)
opt_file = open("cinder/opts.py", 'w')
opt_dict = OrderedDict()
dir_trees_list = []
REGISTER_OPTS_STR = "CONF.register_opts("
REGISTER_OPT_STR = "CONF.register_opt("
license_str = textwrap.dedent(
"""
# 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.\n
""")
opt_file.write(license_str)
edit_header = textwrap.dedent(
"""
###################################################################
# WARNING!
#
# Do not edit this file directly. This file should be generated by
# running the command "tox -e genopts" any time a config option
# has been added, changed, or removed.
###################################################################\n
""")
opt_file.write(edit_header)
opt_file.write("import itertools\n\n")
opt_file.write("from keystoneauth1 import loading\n\n")
# NOTE(geguileo): We need to register all OVOs before importing any other
# cinder files, otherwise any decorator that uses cinder.objects.YYY will
# fail with exception AttributeError: 'module' object has no attribute
# 'YYY' when running tox -egenconfig
opt_file.write(
"from cinder import objects # noqa\nobjects.register_all()\n")
targetdir = 'cinder'
common_string = ('find ' + targetdir + ' -type f -name "*.py" ! '
'-path "*/tests/*" -exec grep -l "%s" {} '
'+ | sed -e "s|^' + BASEDIR +
'|/|g" | sort -u')
cmd_opts = common_string % REGISTER_OPTS_STR
output_opts = subprocess.check_output( # nosec : command is hardcoded
'{}'.format(cmd_opts), shell=True,
universal_newlines=True)
dir_trees_list = output_opts.split()
cmd_opt = common_string % REGISTER_OPT_STR
output_opt = subprocess.check_output( # nosec : command is hardcoded
'{}'.format(cmd_opt), shell=True,
universal_newlines=True)
temp_list = output_opt.split()
for item in temp_list:
dir_trees_list.append(item)
dir_trees_list.sort()
flag = False
def _check_import(aline):
if len(aline) > 79:
new_lines = aline.partition(' as ')
return new_lines
else:
return [aline]
for atree in dir_trees_list:
if atree in ["tools/config/generate_cinder_opts.py",
"cinder/tests/hacking/checks.py",
"cinder/volume/configuration.py",
"cinder/test.py",
"cinder/cmd/status.py"]:
continue
dirs_list = atree.split('/')
import_module = "from "
init_import_module = ""
import_name = ""
for dir in dirs_list:
if dir.find(".py") == -1:
import_module += dir + "."
init_import_module += dir + "."
import_name += dir + "_"
else:
if dir[:-3] != "__init__":
import_name += dir[:-3].replace("_", "")
import_module = (import_module[:-1] + " import " +
dir[:-3] + " as " + import_name)
lines = _check_import(import_module)
if len(lines) > 1:
opt_file.write(lines[0] + lines[1] + "\\\n")
opt_file.write(" " + lines[2] + "\n")
else:
opt_file.write(lines[0] + "\n")
else:
import_name = import_name[:-1].replace('/', '.')
init_import = atree[:-12].replace('/', '.')
opt_file.write("import " + init_import + "\n")
flag = True
if flag is False:
opt_dict[import_name] = atree
else:
opt_dict[init_import_module.strip(".")] = atree
flag = False
registered_opts_dict = OrderedDict([('DEFAULT', [])])
def _write_item(opts):
list_name = opts[-3:]
if list_name.lower() == "opt":
line_to_write = " [" + opts.strip("\n") + "],\n"
opt_line = _check_line_length(line_to_write)
if len(opt_line) > 1:
opt_file.write(opt_line[0] + opt_line[1] + "\n")
opt_file.write(" " + opt_line[2])
else:
opt_file.write(opt_line[0])
else:
line_to_write = " " + opts.strip("\n") + ",\n"
opt_line = _check_line_length(line_to_write)
if len(opt_line) > 1:
opt_file.write(opt_line[0] + opt_line[1] + "\n")
opt_file.write(" " + opt_line[2])
else:
opt_file.write(opt_line[0])
if opts.endswith('service_user_opts'):
su_dnt = " " * 16
su_plg = su_dnt + "loading.get_auth_plugin_conf_options"
opt_file.write(
su_plg + "('v3password'),\n"
+ su_dnt + "loading.get_session_conf_options(),\n")
def _retrieve_name(aline):
if REGISTER_OPT_STR in aline:
str_to_replace = REGISTER_OPT_STR
else:
str_to_replace = REGISTER_OPTS_STR
return aline.replace(str_to_replace, "")
def _check_line_length(aline):
if len(aline) > 79:
temp = aline.split(".")
lines_to_write = []
for section in temp:
lines_to_write.append(section)
lines_to_write.append('.')
return lines_to_write
else:
return [aline]
for key in opt_dict:
fd = os.open(opt_dict[key], os.O_RDONLY)
afile = os.fdopen(fd, "r")
for aline in afile:
exists = aline.find("CONF.register_opt")
if exists != -1:
# TODO(kjnelson) FIX THIS LATER. These are instances where
# CONF.register_opts is happening without actually registering
# real lists of opts
exists = aline.find('base_san_opts')
if (exists != -1) or (key == 'cinder_volume_configuration'):
continue
group_exists = aline.find(', group=')
formatted_opt = _retrieve_name(aline[: group_exists])
formatted_opt = formatted_opt.replace(')', '').strip()
if group_exists != -1:
group_name = aline[group_exists:-1].replace(
', group=\"\'', '').replace(
', group=', '').strip(
"\'\")").upper()
# NOTE(dulek): Hack to resolve constants manually.
if (group_name.endswith('SHARED_CONF_GROUP')
or group_name.lower() == 'backend_defaults'):
group_name = configuration.SHARED_CONF_GROUP
if (group_name == 'NOVA_GROUP'):
group_name = nova.NOVA_GROUP
if group_name in registered_opts_dict:
line = key + "." + formatted_opt
registered_opts_dict[group_name].append(line)
else:
line = key + "." + formatted_opt
registered_opts_dict[group_name] = [line]
else:
line = key + "." + formatted_opt
registered_opts_dict['DEFAULT'].append(line)
setup_str = ("\n\n"
"def list_opts():\n"
" return [\n")
opt_file.write(setup_str)
registered_opts_dict = OrderedDict(sorted(registered_opts_dict.items(),
key = lambda x: x[0]))
for key in registered_opts_dict:
# NOTE(jsbryant): We need to have 'DEFAULT' in uppercase but any
# other section using uppercase causes a Sphinx warning.
if (key == 'DEFAULT'):
section_start_str = (" ('" + key + "',\n"
" itertools.chain(\n")
else:
section_start_str = (" ('" + key.lower() + "',\n"
" itertools.chain(\n")
opt_file.write(section_start_str)
for item in registered_opts_dict[key]:
_write_item(item)
section_end_str = " )),\n"
opt_file.write(section_end_str)
closing_str = (" ]\n")
opt_file.write(closing_str)
opt_file.close()
| apache-2.0 |
odoo-turkiye/odoo | addons/mrp/report/__init__.py | 378 | 1122 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import price
import workcenter_load
import bom_structure
import mrp_report
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
lebedov/hide_my_python | ez_setup.py | 18 | 10476 | #!/usr/bin/env python
"""Bootstrap setuptools installation
To use setuptools in your package's setup.py, include this
file in the same directory and add this to the top of your setup.py::
from ez_setup import use_setuptools
use_setuptools()
To require a specific version of setuptools, set a download
mirror, or use an alternate download directory, simply supply
the appropriate options to ``use_setuptools()``.
This file can also be run as a script to install or upgrade setuptools.
"""
import os
import shutil
import sys
import tempfile
import zipfile
import optparse
import subprocess
import platform
import textwrap
import contextlib
from distutils import log
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
try:
from site import USER_SITE
except ImportError:
USER_SITE = None
DEFAULT_VERSION = "7.0"
DEFAULT_URL = "https://pypi.python.org/packages/source/s/setuptools/"
def _python_cmd(*args):
"""
Return True if the command succeeded.
"""
args = (sys.executable,) + args
return subprocess.call(args) == 0
def _install(archive_filename, install_args=()):
with archive_context(archive_filename):
# installing
log.warn('Installing Setuptools')
if not _python_cmd('setup.py', 'install', *install_args):
log.warn('Something went wrong during the installation.')
log.warn('See the error message above.')
# exitcode will be 2
return 2
def _build_egg(egg, archive_filename, to_dir):
with archive_context(archive_filename):
# building an egg
log.warn('Building a Setuptools egg in %s', to_dir)
_python_cmd('setup.py', '-q', 'bdist_egg', '--dist-dir', to_dir)
# returning the result
log.warn(egg)
if not os.path.exists(egg):
raise IOError('Could not build the egg.')
class ContextualZipFile(zipfile.ZipFile):
"""
Supplement ZipFile class to support context manager for Python 2.6
"""
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
self.close()
def __new__(cls, *args, **kwargs):
"""
Construct a ZipFile or ContextualZipFile as appropriate
"""
if hasattr(zipfile.ZipFile, '__exit__'):
return zipfile.ZipFile(*args, **kwargs)
return super(ContextualZipFile, cls).__new__(cls)
@contextlib.contextmanager
def archive_context(filename):
# extracting the archive
tmpdir = tempfile.mkdtemp()
log.warn('Extracting in %s', tmpdir)
old_wd = os.getcwd()
try:
os.chdir(tmpdir)
with ContextualZipFile(filename) as archive:
archive.extractall()
# going in the directory
subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0])
os.chdir(subdir)
log.warn('Now working in %s', subdir)
yield
finally:
os.chdir(old_wd)
shutil.rmtree(tmpdir)
def _do_download(version, download_base, to_dir, download_delay):
egg = os.path.join(to_dir, 'setuptools-%s-py%d.%d.egg'
% (version, sys.version_info[0], sys.version_info[1]))
if not os.path.exists(egg):
archive = download_setuptools(version, download_base,
to_dir, download_delay)
_build_egg(egg, archive, to_dir)
sys.path.insert(0, egg)
# Remove previously-imported pkg_resources if present (see
# https://bitbucket.org/pypa/setuptools/pull-request/7/ for details).
if 'pkg_resources' in sys.modules:
del sys.modules['pkg_resources']
import setuptools
setuptools.bootstrap_install_from = egg
def use_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL,
to_dir=os.curdir, download_delay=15):
to_dir = os.path.abspath(to_dir)
rep_modules = 'pkg_resources', 'setuptools'
imported = set(sys.modules).intersection(rep_modules)
try:
import pkg_resources
except ImportError:
return _do_download(version, download_base, to_dir, download_delay)
try:
pkg_resources.require("setuptools>=" + version)
return
except pkg_resources.DistributionNotFound:
return _do_download(version, download_base, to_dir, download_delay)
except pkg_resources.VersionConflict as VC_err:
if imported:
msg = textwrap.dedent("""
The required version of setuptools (>={version}) is not available,
and can't be installed while this script is running. Please
install a more recent version first, using
'easy_install -U setuptools'.
(Currently using {VC_err.args[0]!r})
""").format(VC_err=VC_err, version=version)
sys.stderr.write(msg)
sys.exit(2)
# otherwise, reload ok
del pkg_resources, sys.modules['pkg_resources']
return _do_download(version, download_base, to_dir, download_delay)
def _clean_check(cmd, target):
"""
Run the command to download target. If the command fails, clean up before
re-raising the error.
"""
try:
subprocess.check_call(cmd)
except subprocess.CalledProcessError:
if os.access(target, os.F_OK):
os.unlink(target)
raise
def download_file_powershell(url, target):
"""
Download the file at url to target using Powershell (which will validate
trust). Raise an exception if the command cannot complete.
"""
target = os.path.abspath(target)
ps_cmd = (
"[System.Net.WebRequest]::DefaultWebProxy.Credentials = "
"[System.Net.CredentialCache]::DefaultCredentials; "
"(new-object System.Net.WebClient).DownloadFile(%(url)r, %(target)r)"
% vars()
)
cmd = [
'powershell',
'-Command',
ps_cmd,
]
_clean_check(cmd, target)
def has_powershell():
if platform.system() != 'Windows':
return False
cmd = ['powershell', '-Command', 'echo test']
with open(os.path.devnull, 'wb') as devnull:
try:
subprocess.check_call(cmd, stdout=devnull, stderr=devnull)
except Exception:
return False
return True
download_file_powershell.viable = has_powershell
def download_file_curl(url, target):
cmd = ['curl', url, '--silent', '--output', target]
_clean_check(cmd, target)
def has_curl():
cmd = ['curl', '--version']
with open(os.path.devnull, 'wb') as devnull:
try:
subprocess.check_call(cmd, stdout=devnull, stderr=devnull)
except Exception:
return False
return True
download_file_curl.viable = has_curl
def download_file_wget(url, target):
cmd = ['wget', url, '--quiet', '--output-document', target]
_clean_check(cmd, target)
def has_wget():
cmd = ['wget', '--version']
with open(os.path.devnull, 'wb') as devnull:
try:
subprocess.check_call(cmd, stdout=devnull, stderr=devnull)
except Exception:
return False
return True
download_file_wget.viable = has_wget
def download_file_insecure(url, target):
"""
Use Python to download the file, even though it cannot authenticate the
connection.
"""
src = urlopen(url)
try:
# Read all the data in one block.
data = src.read()
finally:
src.close()
# Write all the data in one block to avoid creating a partial file.
with open(target, "wb") as dst:
dst.write(data)
download_file_insecure.viable = lambda: True
def get_best_downloader():
downloaders = (
download_file_powershell,
download_file_curl,
download_file_wget,
download_file_insecure,
)
viable_downloaders = (dl for dl in downloaders if dl.viable())
return next(viable_downloaders, None)
def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL,
to_dir=os.curdir, delay=15, downloader_factory=get_best_downloader):
"""
Download setuptools from a specified location and return its filename
`version` should be a valid setuptools version number that is available
as an sdist for download under the `download_base` URL (which should end
with a '/'). `to_dir` is the directory where the egg will be downloaded.
`delay` is the number of seconds to pause before an actual download
attempt.
``downloader_factory`` should be a function taking no arguments and
returning a function for downloading a URL to a target.
"""
# making sure we use the absolute path
to_dir = os.path.abspath(to_dir)
zip_name = "setuptools-%s.zip" % version
url = download_base + zip_name
saveto = os.path.join(to_dir, zip_name)
if not os.path.exists(saveto): # Avoid repeated downloads
log.warn("Downloading %s", url)
downloader = downloader_factory()
downloader(url, saveto)
return os.path.realpath(saveto)
def _build_install_args(options):
"""
Build the arguments to 'python setup.py install' on the setuptools package
"""
return ['--user'] if options.user_install else []
def _parse_args():
"""
Parse the command line for options
"""
parser = optparse.OptionParser()
parser.add_option(
'--user', dest='user_install', action='store_true', default=False,
help='install in user site package (requires Python 2.6 or later)')
parser.add_option(
'--download-base', dest='download_base', metavar="URL",
default=DEFAULT_URL,
help='alternative URL from where to download the setuptools package')
parser.add_option(
'--insecure', dest='downloader_factory', action='store_const',
const=lambda: download_file_insecure, default=get_best_downloader,
help='Use internal, non-validating downloader'
)
parser.add_option(
'--version', help="Specify which version to download",
default=DEFAULT_VERSION,
)
options, args = parser.parse_args()
# positional arguments are ignored
return options
def main():
"""Install or upgrade setuptools and EasyInstall"""
options = _parse_args()
archive = download_setuptools(
version=options.version,
download_base=options.download_base,
downloader_factory=options.downloader_factory,
)
return _install(archive, _build_install_args(options))
if __name__ == '__main__':
sys.exit(main())
| gpl-3.0 |
newerthcom/savagerebirth | libs/python-2.72/Lib/profile.py | 84 | 23466 | #! /usr/bin/env python
#
# Class for profiling python code. rev 1.0 6/2/94
#
# Based on prior profile module by Sjoerd Mullender...
# which was hacked somewhat by: Guido van Rossum
"""Class for profiling Python code."""
# Copyright 1994, by InfoSeek Corporation, all rights reserved.
# Written by James Roskind
#
# Permission to use, copy, modify, and distribute this Python software
# and its associated documentation for any purpose (subject to the
# restriction in the following sentence) without fee is hereby granted,
# provided that the above copyright notice appears in all copies, and
# that both that copyright notice and this permission notice appear in
# supporting documentation, and that the name of InfoSeek not be used in
# advertising or publicity pertaining to distribution of the software
# without specific, written prior permission. This permission is
# explicitly restricted to the copying and modification of the software
# to remain in Python, compiled Python, or other languages (such as C)
# wherein the modified or derived code is exclusively imported into a
# Python module.
#
# INFOSEEK CORPORATION DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
# SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
# FITNESS. IN NO EVENT SHALL INFOSEEK CORPORATION BE LIABLE FOR ANY
# SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
# RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
# CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
import sys
import os
import time
import marshal
from optparse import OptionParser
__all__ = ["run", "runctx", "help", "Profile"]
# Sample timer for use with
#i_count = 0
#def integer_timer():
# global i_count
# i_count = i_count + 1
# return i_count
#itimes = integer_timer # replace with C coded timer returning integers
#**************************************************************************
# The following are the static member functions for the profiler class
# Note that an instance of Profile() is *not* needed to call them.
#**************************************************************************
def run(statement, filename=None, sort=-1):
"""Run statement under profiler optionally saving results in filename
This function takes a single argument that can be passed to the
"exec" statement, and an optional file name. In all cases this
routine attempts to "exec" its first argument and gather profiling
statistics from the execution. If no file name is present, then this
function automatically prints a simple profiling report, sorted by the
standard name string (file/line/function-name) that is presented in
each line.
"""
prof = Profile()
try:
prof = prof.run(statement)
except SystemExit:
pass
if filename is not None:
prof.dump_stats(filename)
else:
return prof.print_stats(sort)
def runctx(statement, globals, locals, filename=None, sort=-1):
"""Run statement under profiler, supplying your own globals and locals,
optionally saving results in filename.
statement and filename have the same semantics as profile.run
"""
prof = Profile()
try:
prof = prof.runctx(statement, globals, locals)
except SystemExit:
pass
if filename is not None:
prof.dump_stats(filename)
else:
return prof.print_stats(sort)
# Backwards compatibility.
def help():
print "Documentation for the profile module can be found "
print "in the Python Library Reference, section 'The Python Profiler'."
if hasattr(os, "times"):
def _get_time_times(timer=os.times):
t = timer()
return t[0] + t[1]
# Using getrusage(3) is better than clock(3) if available:
# on some systems (e.g. FreeBSD), getrusage has a higher resolution
# Furthermore, on a POSIX system, returns microseconds, which
# wrap around after 36min.
_has_res = 0
try:
import resource
resgetrusage = lambda: resource.getrusage(resource.RUSAGE_SELF)
def _get_time_resource(timer=resgetrusage):
t = timer()
return t[0] + t[1]
_has_res = 1
except ImportError:
pass
class Profile:
"""Profiler class.
self.cur is always a tuple. Each such tuple corresponds to a stack
frame that is currently active (self.cur[-2]). The following are the
definitions of its members. We use this external "parallel stack" to
avoid contaminating the program that we are profiling. (old profiler
used to write into the frames local dictionary!!) Derived classes
can change the definition of some entries, as long as they leave
[-2:] intact (frame and previous tuple). In case an internal error is
detected, the -3 element is used as the function name.
[ 0] = Time that needs to be charged to the parent frame's function.
It is used so that a function call will not have to access the
timing data for the parent frame.
[ 1] = Total time spent in this frame's function, excluding time in
subfunctions (this latter is tallied in cur[2]).
[ 2] = Total time spent in subfunctions, excluding time executing the
frame's function (this latter is tallied in cur[1]).
[-3] = Name of the function that corresponds to this frame.
[-2] = Actual frame that we correspond to (used to sync exception handling).
[-1] = Our parent 6-tuple (corresponds to frame.f_back).
Timing data for each function is stored as a 5-tuple in the dictionary
self.timings[]. The index is always the name stored in self.cur[-3].
The following are the definitions of the members:
[0] = The number of times this function was called, not counting direct
or indirect recursion,
[1] = Number of times this function appears on the stack, minus one
[2] = Total time spent internal to this function
[3] = Cumulative time that this function was present on the stack. In
non-recursive functions, this is the total execution time from start
to finish of each invocation of a function, including time spent in
all subfunctions.
[4] = A dictionary indicating for each function name, the number of times
it was called by us.
"""
bias = 0 # calibration constant
def __init__(self, timer=None, bias=None):
self.timings = {}
self.cur = None
self.cmd = ""
self.c_func_name = ""
if bias is None:
bias = self.bias
self.bias = bias # Materialize in local dict for lookup speed.
if not timer:
if _has_res:
self.timer = resgetrusage
self.dispatcher = self.trace_dispatch
self.get_time = _get_time_resource
elif hasattr(time, 'clock'):
self.timer = self.get_time = time.clock
self.dispatcher = self.trace_dispatch_i
elif hasattr(os, 'times'):
self.timer = os.times
self.dispatcher = self.trace_dispatch
self.get_time = _get_time_times
else:
self.timer = self.get_time = time.time
self.dispatcher = self.trace_dispatch_i
else:
self.timer = timer
t = self.timer() # test out timer function
try:
length = len(t)
except TypeError:
self.get_time = timer
self.dispatcher = self.trace_dispatch_i
else:
if length == 2:
self.dispatcher = self.trace_dispatch
else:
self.dispatcher = self.trace_dispatch_l
# This get_time() implementation needs to be defined
# here to capture the passed-in timer in the parameter
# list (for performance). Note that we can't assume
# the timer() result contains two values in all
# cases.
def get_time_timer(timer=timer, sum=sum):
return sum(timer())
self.get_time = get_time_timer
self.t = self.get_time()
self.simulate_call('profiler')
# Heavily optimized dispatch routine for os.times() timer
def trace_dispatch(self, frame, event, arg):
timer = self.timer
t = timer()
t = t[0] + t[1] - self.t - self.bias
if event == "c_call":
self.c_func_name = arg.__name__
if self.dispatch[event](self, frame,t):
t = timer()
self.t = t[0] + t[1]
else:
r = timer()
self.t = r[0] + r[1] - t # put back unrecorded delta
# Dispatch routine for best timer program (return = scalar, fastest if
# an integer but float works too -- and time.clock() relies on that).
def trace_dispatch_i(self, frame, event, arg):
timer = self.timer
t = timer() - self.t - self.bias
if event == "c_call":
self.c_func_name = arg.__name__
if self.dispatch[event](self, frame, t):
self.t = timer()
else:
self.t = timer() - t # put back unrecorded delta
# Dispatch routine for macintosh (timer returns time in ticks of
# 1/60th second)
def trace_dispatch_mac(self, frame, event, arg):
timer = self.timer
t = timer()/60.0 - self.t - self.bias
if event == "c_call":
self.c_func_name = arg.__name__
if self.dispatch[event](self, frame, t):
self.t = timer()/60.0
else:
self.t = timer()/60.0 - t # put back unrecorded delta
# SLOW generic dispatch routine for timer returning lists of numbers
def trace_dispatch_l(self, frame, event, arg):
get_time = self.get_time
t = get_time() - self.t - self.bias
if event == "c_call":
self.c_func_name = arg.__name__
if self.dispatch[event](self, frame, t):
self.t = get_time()
else:
self.t = get_time() - t # put back unrecorded delta
# In the event handlers, the first 3 elements of self.cur are unpacked
# into vrbls w/ 3-letter names. The last two characters are meant to be
# mnemonic:
# _pt self.cur[0] "parent time" time to be charged to parent frame
# _it self.cur[1] "internal time" time spent directly in the function
# _et self.cur[2] "external time" time spent in subfunctions
def trace_dispatch_exception(self, frame, t):
rpt, rit, ret, rfn, rframe, rcur = self.cur
if (rframe is not frame) and rcur:
return self.trace_dispatch_return(rframe, t)
self.cur = rpt, rit+t, ret, rfn, rframe, rcur
return 1
def trace_dispatch_call(self, frame, t):
if self.cur and frame.f_back is not self.cur[-2]:
rpt, rit, ret, rfn, rframe, rcur = self.cur
if not isinstance(rframe, Profile.fake_frame):
assert rframe.f_back is frame.f_back, ("Bad call", rfn,
rframe, rframe.f_back,
frame, frame.f_back)
self.trace_dispatch_return(rframe, 0)
assert (self.cur is None or \
frame.f_back is self.cur[-2]), ("Bad call",
self.cur[-3])
fcode = frame.f_code
fn = (fcode.co_filename, fcode.co_firstlineno, fcode.co_name)
self.cur = (t, 0, 0, fn, frame, self.cur)
timings = self.timings
if fn in timings:
cc, ns, tt, ct, callers = timings[fn]
timings[fn] = cc, ns + 1, tt, ct, callers
else:
timings[fn] = 0, 0, 0, 0, {}
return 1
def trace_dispatch_c_call (self, frame, t):
fn = ("", 0, self.c_func_name)
self.cur = (t, 0, 0, fn, frame, self.cur)
timings = self.timings
if fn in timings:
cc, ns, tt, ct, callers = timings[fn]
timings[fn] = cc, ns+1, tt, ct, callers
else:
timings[fn] = 0, 0, 0, 0, {}
return 1
def trace_dispatch_return(self, frame, t):
if frame is not self.cur[-2]:
assert frame is self.cur[-2].f_back, ("Bad return", self.cur[-3])
self.trace_dispatch_return(self.cur[-2], 0)
# Prefix "r" means part of the Returning or exiting frame.
# Prefix "p" means part of the Previous or Parent or older frame.
rpt, rit, ret, rfn, frame, rcur = self.cur
rit = rit + t
frame_total = rit + ret
ppt, pit, pet, pfn, pframe, pcur = rcur
self.cur = ppt, pit + rpt, pet + frame_total, pfn, pframe, pcur
timings = self.timings
cc, ns, tt, ct, callers = timings[rfn]
if not ns:
# This is the only occurrence of the function on the stack.
# Else this is a (directly or indirectly) recursive call, and
# its cumulative time will get updated when the topmost call to
# it returns.
ct = ct + frame_total
cc = cc + 1
if pfn in callers:
callers[pfn] = callers[pfn] + 1 # hack: gather more
# stats such as the amount of time added to ct courtesy
# of this specific call, and the contribution to cc
# courtesy of this call.
else:
callers[pfn] = 1
timings[rfn] = cc, ns - 1, tt + rit, ct, callers
return 1
dispatch = {
"call": trace_dispatch_call,
"exception": trace_dispatch_exception,
"return": trace_dispatch_return,
"c_call": trace_dispatch_c_call,
"c_exception": trace_dispatch_return, # the C function returned
"c_return": trace_dispatch_return,
}
# The next few functions play with self.cmd. By carefully preloading
# our parallel stack, we can force the profiled result to include
# an arbitrary string as the name of the calling function.
# We use self.cmd as that string, and the resulting stats look
# very nice :-).
def set_cmd(self, cmd):
if self.cur[-1]: return # already set
self.cmd = cmd
self.simulate_call(cmd)
class fake_code:
def __init__(self, filename, line, name):
self.co_filename = filename
self.co_line = line
self.co_name = name
self.co_firstlineno = 0
def __repr__(self):
return repr((self.co_filename, self.co_line, self.co_name))
class fake_frame:
def __init__(self, code, prior):
self.f_code = code
self.f_back = prior
def simulate_call(self, name):
code = self.fake_code('profile', 0, name)
if self.cur:
pframe = self.cur[-2]
else:
pframe = None
frame = self.fake_frame(code, pframe)
self.dispatch['call'](self, frame, 0)
# collect stats from pending stack, including getting final
# timings for self.cmd frame.
def simulate_cmd_complete(self):
get_time = self.get_time
t = get_time() - self.t
while self.cur[-1]:
# We *can* cause assertion errors here if
# dispatch_trace_return checks for a frame match!
self.dispatch['return'](self, self.cur[-2], t)
t = 0
self.t = get_time() - t
def print_stats(self, sort=-1):
import pstats
pstats.Stats(self).strip_dirs().sort_stats(sort). \
print_stats()
def dump_stats(self, file):
f = open(file, 'wb')
self.create_stats()
marshal.dump(self.stats, f)
f.close()
def create_stats(self):
self.simulate_cmd_complete()
self.snapshot_stats()
def snapshot_stats(self):
self.stats = {}
for func, (cc, ns, tt, ct, callers) in self.timings.iteritems():
callers = callers.copy()
nc = 0
for callcnt in callers.itervalues():
nc += callcnt
self.stats[func] = cc, nc, tt, ct, callers
# The following two methods can be called by clients to use
# a profiler to profile a statement, given as a string.
def run(self, cmd):
import __main__
dict = __main__.__dict__
return self.runctx(cmd, dict, dict)
def runctx(self, cmd, globals, locals):
self.set_cmd(cmd)
sys.setprofile(self.dispatcher)
try:
exec cmd in globals, locals
finally:
sys.setprofile(None)
return self
# This method is more useful to profile a single function call.
def runcall(self, func, *args, **kw):
self.set_cmd(repr(func))
sys.setprofile(self.dispatcher)
try:
return func(*args, **kw)
finally:
sys.setprofile(None)
#******************************************************************
# The following calculates the overhead for using a profiler. The
# problem is that it takes a fair amount of time for the profiler
# to stop the stopwatch (from the time it receives an event).
# Similarly, there is a delay from the time that the profiler
# re-starts the stopwatch before the user's code really gets to
# continue. The following code tries to measure the difference on
# a per-event basis.
#
# Note that this difference is only significant if there are a lot of
# events, and relatively little user code per event. For example,
# code with small functions will typically benefit from having the
# profiler calibrated for the current platform. This *could* be
# done on the fly during init() time, but it is not worth the
# effort. Also note that if too large a value specified, then
# execution time on some functions will actually appear as a
# negative number. It is *normal* for some functions (with very
# low call counts) to have such negative stats, even if the
# calibration figure is "correct."
#
# One alternative to profile-time calibration adjustments (i.e.,
# adding in the magic little delta during each event) is to track
# more carefully the number of events (and cumulatively, the number
# of events during sub functions) that are seen. If this were
# done, then the arithmetic could be done after the fact (i.e., at
# display time). Currently, we track only call/return events.
# These values can be deduced by examining the callees and callers
# vectors for each functions. Hence we *can* almost correct the
# internal time figure at print time (note that we currently don't
# track exception event processing counts). Unfortunately, there
# is currently no similar information for cumulative sub-function
# time. It would not be hard to "get all this info" at profiler
# time. Specifically, we would have to extend the tuples to keep
# counts of this in each frame, and then extend the defs of timing
# tuples to include the significant two figures. I'm a bit fearful
# that this additional feature will slow the heavily optimized
# event/time ratio (i.e., the profiler would run slower, fur a very
# low "value added" feature.)
#**************************************************************
def calibrate(self, m, verbose=0):
if self.__class__ is not Profile:
raise TypeError("Subclasses must override .calibrate().")
saved_bias = self.bias
self.bias = 0
try:
return self._calibrate_inner(m, verbose)
finally:
self.bias = saved_bias
def _calibrate_inner(self, m, verbose):
get_time = self.get_time
# Set up a test case to be run with and without profiling. Include
# lots of calls, because we're trying to quantify stopwatch overhead.
# Do not raise any exceptions, though, because we want to know
# exactly how many profile events are generated (one call event, +
# one return event, per Python-level call).
def f1(n):
for i in range(n):
x = 1
def f(m, f1=f1):
for i in range(m):
f1(100)
f(m) # warm up the cache
# elapsed_noprofile <- time f(m) takes without profiling.
t0 = get_time()
f(m)
t1 = get_time()
elapsed_noprofile = t1 - t0
if verbose:
print "elapsed time without profiling =", elapsed_noprofile
# elapsed_profile <- time f(m) takes with profiling. The difference
# is profiling overhead, only some of which the profiler subtracts
# out on its own.
p = Profile()
t0 = get_time()
p.runctx('f(m)', globals(), locals())
t1 = get_time()
elapsed_profile = t1 - t0
if verbose:
print "elapsed time with profiling =", elapsed_profile
# reported_time <- "CPU seconds" the profiler charged to f and f1.
total_calls = 0.0
reported_time = 0.0
for (filename, line, funcname), (cc, ns, tt, ct, callers) in \
p.timings.items():
if funcname in ("f", "f1"):
total_calls += cc
reported_time += tt
if verbose:
print "'CPU seconds' profiler reported =", reported_time
print "total # calls =", total_calls
if total_calls != m + 1:
raise ValueError("internal error: total calls = %d" % total_calls)
# reported_time - elapsed_noprofile = overhead the profiler wasn't
# able to measure. Divide by twice the number of calls (since there
# are two profiler events per call in this test) to get the hidden
# overhead per event.
mean = (reported_time - elapsed_noprofile) / 2.0 / total_calls
if verbose:
print "mean stopwatch overhead per profile event =", mean
return mean
#****************************************************************************
def Stats(*args):
print 'Report generating functions are in the "pstats" module\a'
def main():
usage = "profile.py [-o output_file_path] [-s sort] scriptfile [arg] ..."
parser = OptionParser(usage=usage)
parser.allow_interspersed_args = False
parser.add_option('-o', '--outfile', dest="outfile",
help="Save stats to <outfile>", default=None)
parser.add_option('-s', '--sort', dest="sort",
help="Sort order when printing to stdout, based on pstats.Stats class",
default=-1)
if not sys.argv[1:]:
parser.print_usage()
sys.exit(2)
(options, args) = parser.parse_args()
sys.argv[:] = args
if len(args) > 0:
progname = args[0]
sys.path.insert(0, os.path.dirname(progname))
with open(progname, 'rb') as fp:
code = compile(fp.read(), progname, 'exec')
globs = {
'__file__': progname,
'__name__': '__main__',
'__package__': None,
}
runctx(code, globs, None, options.outfile, options.sort)
else:
parser.print_usage()
return parser
# When invoked as main program, invoke the profiler on a script
if __name__ == '__main__':
main()
| gpl-2.0 |
shownomercy/django | django/views/static.py | 190 | 5142 | """
Views and functions for serving static files. These are only to be used
during development, and SHOULD NOT be used in a production setting.
"""
from __future__ import unicode_literals
import mimetypes
import os
import posixpath
import re
import stat
from django.http import (
FileResponse, Http404, HttpResponse, HttpResponseNotModified,
HttpResponseRedirect,
)
from django.template import Context, Engine, TemplateDoesNotExist, loader
from django.utils.http import http_date, parse_http_date
from django.utils.six.moves.urllib.parse import unquote
from django.utils.translation import ugettext as _, ugettext_lazy
def serve(request, path, document_root=None, show_indexes=False):
"""
Serve static files below a given point in the directory structure.
To use, put a URL pattern such as::
from django.views.static import serve
url(r'^(?P<path>.*)$', serve, {'document_root': '/path/to/my/files/'})
in your URLconf. You must provide the ``document_root`` param. You may
also set ``show_indexes`` to ``True`` if you'd like to serve a basic index
of the directory. This index view will use the template hardcoded below,
but if you'd like to override it, you can create a template called
``static/directory_index.html``.
"""
path = posixpath.normpath(unquote(path))
path = path.lstrip('/')
newpath = ''
for part in path.split('/'):
if not part:
# Strip empty path components.
continue
drive, part = os.path.splitdrive(part)
head, part = os.path.split(part)
if part in (os.curdir, os.pardir):
# Strip '.' and '..' in path.
continue
newpath = os.path.join(newpath, part).replace('\\', '/')
if newpath and path != newpath:
return HttpResponseRedirect(newpath)
fullpath = os.path.join(document_root, newpath)
if os.path.isdir(fullpath):
if show_indexes:
return directory_index(newpath, fullpath)
raise Http404(_("Directory indexes are not allowed here."))
if not os.path.exists(fullpath):
raise Http404(_('"%(path)s" does not exist') % {'path': fullpath})
# Respect the If-Modified-Since header.
statobj = os.stat(fullpath)
if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'),
statobj.st_mtime, statobj.st_size):
return HttpResponseNotModified()
content_type, encoding = mimetypes.guess_type(fullpath)
content_type = content_type or 'application/octet-stream'
response = FileResponse(open(fullpath, 'rb'), content_type=content_type)
response["Last-Modified"] = http_date(statobj.st_mtime)
if stat.S_ISREG(statobj.st_mode):
response["Content-Length"] = statobj.st_size
if encoding:
response["Content-Encoding"] = encoding
return response
DEFAULT_DIRECTORY_INDEX_TEMPLATE = """
{% load i18n %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Language" content="en-us" />
<meta name="robots" content="NONE,NOARCHIVE" />
<title>{% blocktrans %}Index of {{ directory }}{% endblocktrans %}</title>
</head>
<body>
<h1>{% blocktrans %}Index of {{ directory }}{% endblocktrans %}</h1>
<ul>
{% ifnotequal directory "/" %}
<li><a href="../">../</a></li>
{% endifnotequal %}
{% for f in file_list %}
<li><a href="{{ f|urlencode }}">{{ f }}</a></li>
{% endfor %}
</ul>
</body>
</html>
"""
template_translatable = ugettext_lazy("Index of %(directory)s")
def directory_index(path, fullpath):
try:
t = loader.select_template([
'static/directory_index.html',
'static/directory_index',
])
except TemplateDoesNotExist:
t = Engine().from_string(DEFAULT_DIRECTORY_INDEX_TEMPLATE)
files = []
for f in os.listdir(fullpath):
if not f.startswith('.'):
if os.path.isdir(os.path.join(fullpath, f)):
f += '/'
files.append(f)
c = Context({
'directory': path + '/',
'file_list': files,
})
return HttpResponse(t.render(c))
def was_modified_since(header=None, mtime=0, size=0):
"""
Was something modified since the user last downloaded it?
header
This is the value of the If-Modified-Since header. If this is None,
I'll just return True.
mtime
This is the modification time of the item we're talking about.
size
This is the size of the item we're talking about.
"""
try:
if header is None:
raise ValueError
matches = re.match(r"^([^;]+)(; length=([0-9]+))?$", header,
re.IGNORECASE)
header_mtime = parse_http_date(matches.group(1))
header_len = matches.group(3)
if header_len and int(header_len) != size:
raise ValueError
if int(mtime) > header_mtime:
raise ValueError
except (AttributeError, ValueError, OverflowError):
return True
return False
| bsd-3-clause |
RaspberryPiFi/PiCode | lib/eyed3/plugins/statistics.py | 3 | 16127 | # -*- coding: utf-8 -*-
################################################################################
# Copyright (C) 2009 Travis Shirk <travis@pobox.com>
#
# 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
#
################################################################################
from __future__ import print_function
import sys, os, operator
from collections import Counter
from eyed3 import id3, mp3
from eyed3.core import AUDIO_MP3
from eyed3.utils import guessMimetype
from eyed3.utils.console import Fore, Style, printMsg
from eyed3.plugins import LoaderPlugin
from eyed3.id3.frames import ImageFrame
ID3_VERSIONS = [id3.ID3_V1_0, id3.ID3_V1_1,
id3.ID3_V2_2, id3.ID3_V2_3, id3.ID3_V2_4]
_OP_STRINGS = {operator.le: "<=",
operator.lt: "< ",
operator.ge: ">=",
operator.gt: "> ",
operator.eq: "= ",
operator.ne: "!=",
}
class Rule(object):
def test(self):
raise NotImplementedError()
PREFERRED_ID3_VERSIONS = [ id3.ID3_V2_3,
id3.ID3_V2_4,
]
class Id3TagRules(Rule):
def test(self, path, audio_file):
scores = []
if audio_file is None:
return None
if not audio_file.tag:
return [(-75, "Missing ID3 tag")];
tag = audio_file.tag
if tag.version not in PREFERRED_ID3_VERSIONS:
scores.append((-30, "ID3 version not in %s" %
PREFERRED_ID3_VERSIONS))
if not tag.title:
scores.append((-30, "Tag missing title"))
if not tag.artist:
scores.append((-28, "Tag missing artist"))
if not tag.album:
scores.append((-26, "Tag missing album"))
if not tag.track_num[0]:
scores.append((-24, "Tag missing track number"))
if not tag.track_num[1]:
scores.append((-22, "Tag missing total # of tracks"))
if not tag.getBestDate():
scores.append((-30, "Tag missing any useful dates"))
else:
if not tag.original_release_date:
# Original release date is so rarely used but is almost always
# what I mean or wanna know.
scores.append((-10, "No original release date"))
elif not tag.release_date:
scores.append((-5, "No release date"))
# TLEN, best gotten from audio_file.info.time_secs but having it in
# the tag is good, I guess.
if "TLEN" not in tag.frame_set:
scores.append((-5, "No TLEN frame"))
return scores
BITRATE_DEDUCTIONS = [(192, -20), (256, -10)]
class BitrateRule(Rule):
def test(self, path, audio_file):
scores = []
if not audio_file:
return None
if not audio_file.info:
# Detected as an audio file but not real audio data found.
return [(-90, "No audio data found")]
is_vbr, bitrate = audio_file.info.bit_rate
for threshold, score in BITRATE_DEDUCTIONS:
if bitrate < threshold:
scores.append((score, "Bit rate < %d" % threshold))
break
return scores
VALID_MIME_TYPES = mp3.MIME_TYPES + [ "image/png",
"image/gif",
"image/jpeg",
]
class FileRule(Rule):
def test(self, path, audio_file):
mt = guessMimetype(path)
for name in os.path.split(path):
if name.startswith('.'):
return [(-100, "Hidden file type")]
if mt not in VALID_MIME_TYPES:
return [(-100, "Unsupported file type: %s" % mt)]
return None
VALID_ARTWORK_NAMES = ("cover", "cover-front", "cover-back")
class ArtworkRule(Rule):
def test(self, path, audio_file):
mt = guessMimetype(path)
if mt and mt.startswith("image/"):
name, ext = os.path.splitext(os.path.basename(path))
if name not in VALID_ARTWORK_NAMES:
return [(-10, "Artwork file not in %s" %
str(VALID_ARTWORK_NAMES))]
return None
BAD_FRAMES = ["PRIV", "GEOB"]
class Id3FrameRules(Rule):
def test(self, path, audio_file):
scores = []
if not audio_file or not audio_file.tag:
return
tag = audio_file.tag
for fid in tag.frame_set:
if fid[0] == 'T' and fid != "TXXX" and len(tag.frame_set[fid]) > 1:
scores.append((-10, "Multiple %s frames" % fid))
elif fid in BAD_FRAMES:
scores.append((-13, "%s frames are bad, mmmkay?" % fid))
return scores
class Stat(Counter):
TOTAL = "total"
def __init__(self, *args, **kwargs):
super(Stat, self).__init__(*args, **kwargs)
self[self.TOTAL] = 0
self._key_names = {}
def compute(self, file, audio_file):
self[self.TOTAL] += 1
self._compute(file, audio_file)
def _compute(self, file, audio_file):
pass
def report(self):
self._report()
def _sortedKeys(self, most_common=False):
def keyDisplayName(k):
return self._key_names[k] if k in self._key_names else k
key_map = {}
for k in list(self.keys()):
key_map[keyDisplayName(k)] = k
if not most_common:
sorted_names = list(key_map.keys())
sorted_names.remove(self.TOTAL)
sorted_names.sort()
sorted_names.append(self.TOTAL)
else:
most_common = self.most_common()
sorted_names = []
remainder_names = []
for k, v in most_common:
if k != self.TOTAL and v > 0:
sorted_names.append(keyDisplayName(k))
elif k != self.TOTAL:
remainder_names.append(keyDisplayName(k))
remainder_names.sort()
sorted_names = sorted_names + remainder_names
sorted_names.append(self.TOTAL)
return [key_map[name] for name in sorted_names]
def _report(self, most_common=False):
keys = self._sortedKeys(most_common=most_common)
key_col_width = 0
val_col_width = 0
for key in keys:
key = self._key_names[key] if key in self._key_names else key
key_col_width = max(key_col_width, len(str(key)))
val_col_width = max(val_col_width, len(str(self[key])))
key_col_width += 1
val_col_width += 1
for k in keys:
key_name = self._key_names[k] if k in self._key_names else k
value = self[k]
percent = self.percent(k) if value and k != "total" else ""
print("%(padding)s%(key)s:%(value)s%(percent)s" %
{ "padding": ' ' * 4,
"key": str(key_name).ljust(key_col_width),
"value": str(value).rjust(val_col_width),
"percent": " ( %s%.2f%%%s )" %
(Fore.GREEN, percent, Fore.RESET) if percent
else "",
})
def percent(self, key):
return (float(self[key]) / float(self["total"])) * 100
class AudioStat(Stat):
def compute(self, audio_file):
assert(audio_file)
self["total"] += 1
self._compute(audio_file)
def _compute(self, audio_file):
pass
class FileCounterStat(Stat):
SUPPORTED_AUDIO = "audio"
UNSUPPORTED_AUDIO = "audio (unsupported)"
HIDDEN_FILES = "hidden"
OTHER_FILES = "other"
def __init__(self):
super(FileCounterStat, self).__init__()
for k in ("audio", "hidden", "audio (unsupported)"):
self[k] = 0
def _compute(self, file, audio_file):
mt = guessMimetype(file)
if audio_file:
self[self.SUPPORTED_AUDIO] += 1
elif mt and mt.startswith("audio/"):
self[self.UNSUPPORTED_AUDIO] += 1
elif os.path.basename(file).startswith('.'):
self[self.HIDDEN_FILES] += 1
else:
self[self.OTHER_FILES] += 1
def _report(self):
print(Style.BRIGHT + Fore.GREY + "Files:" + Style.RESET_ALL)
super(FileCounterStat, self)._report()
class MimeTypeStat(Stat):
def _compute(self, file, audio_file):
mt = guessMimetype(file)
self[mt] += 1
def _report(self):
print(Style.BRIGHT + Fore.GREY + "Mime-Types:" + Style.RESET_ALL)
super(MimeTypeStat, self)._report(most_common=True)
class Id3VersionCounter(AudioStat):
def __init__(self):
super(Id3VersionCounter, self).__init__()
for v in ID3_VERSIONS:
self[v] = 0
self._key_names[v] = id3.versionToString(v)
def _compute(self, audio_file):
if audio_file.tag:
self[audio_file.tag.version] += 1
else:
self[None] += 1
def _report(self):
print(Style.BRIGHT + Fore.GREY + "ID3 versions:" + Style.RESET_ALL)
super(Id3VersionCounter, self)._report()
class Id3FrameCounter(AudioStat):
def _compute(self, audio_file):
if audio_file.tag:
for frame_id in audio_file.tag.frame_set:
self[frame_id] += len(audio_file.tag.frame_set[frame_id])
def _report(self):
print(Style.BRIGHT + Fore.GREY + "ID3 frames:" + Style.RESET_ALL)
super(Id3FrameCounter, self)._report(most_common=True)
class BitrateCounter(AudioStat):
def __init__(self):
super(BitrateCounter, self).__init__()
self["cbr"] = 0
self["vbr"] = 0
self.bitrate_keys = [(operator.le, 96),
(operator.le, 112),
(operator.le, 128),
(operator.le, 160),
(operator.le, 192),
(operator.le, 256),
(operator.le, 320),
(operator.gt, 320),
]
for k in self.bitrate_keys:
self[k] = 0
op, bitrate = k
self._key_names[k] = "%s %d" % (_OP_STRINGS[op], bitrate)
def _compute(self, audio_file):
if audio_file.type != AUDIO_MP3 or audio_file.info is None:
self["total"] -=1
return
vbr, br = audio_file.info.bit_rate
if vbr:
self["vbr"] += 1
else:
self["cbr"] += 1
for key in self.bitrate_keys:
key_op, key_br = key
if key_op(br, key_br):
self[key] += 1
break
def _report(self):
print(Style.BRIGHT + Fore.GREY + "MP3 bitrates:" + Style.RESET_ALL)
super(BitrateCounter, self)._report(most_common=True)
def _sortedKeys(self, most_common=False):
keys = super(BitrateCounter, self)._sortedKeys(most_common=most_common)
keys.remove("cbr")
keys.remove("vbr")
keys.insert(0, "cbr")
keys.insert(1, "vbr")
return keys
class RuleViolationStat(Stat):
def _report(self):
print(Style.BRIGHT + Fore.GREY + "Rule Violations:" + Style.RESET_ALL)
super(RuleViolationStat, self)._report(most_common=True)
class Id3ImageTypeCounter(AudioStat):
def __init__(self):
super(Id3ImageTypeCounter, self).__init__()
self._key_names = {}
for attr in dir(ImageFrame):
val = getattr(ImageFrame, attr)
if isinstance(val, int) and not attr.endswith("_TYPE"):
self._key_names[val] = attr
for v in self._key_names:
self[v] = 0
def _compute(self, audio_file):
if audio_file.tag:
for img in audio_file.tag.images:
self[img.picture_type] += 1
def _report(self):
print(Style.BRIGHT + Fore.GREY + "APIC image types:" + Style.RESET_ALL)
super(Id3ImageTypeCounter, self)._report()
class StatisticsPlugin(LoaderPlugin):
NAMES = ['stats']
SUMMARY = u"Computes statistics for all audio files scanned."
def __init__(self, arg_parser):
super(StatisticsPlugin, self).__init__(arg_parser)
self.arg_group.add_argument(
"--verbose", action="store_true", default=False,
help="Show details for each file with rule violations.")
self._stats = []
self._rules_stat = RuleViolationStat()
self._stats.append(FileCounterStat())
self._stats.append(MimeTypeStat())
self._stats.append(Id3VersionCounter())
self._stats.append(Id3FrameCounter())
self._stats.append(Id3ImageTypeCounter())
self._stats.append(BitrateCounter())
self._score_sum = 0
self._score_count = 0
self._rules_log = {}
self._rules = [ Id3TagRules(),
FileRule(),
ArtworkRule(),
BitrateRule(),
Id3FrameRules(),
]
def handleFile(self, path):
super(StatisticsPlugin, self).handleFile(path)
if not self.args.quiet:
sys.stdout.write('.')
sys.stdout.flush()
for stat in self._stats:
if isinstance(stat, AudioStat):
if self.audio_file:
stat.compute(self.audio_file)
else:
stat.compute(path, self.audio_file)
self._score_count += 1
total_score = 100
for rule in self._rules:
scores = rule.test(path, self.audio_file) or []
if scores:
if path not in self._rules_log:
self._rules_log[path] = []
for score, text in scores:
self._rules_stat[text] += 1
self._rules_log[path].append((score, text))
# += because negative values are returned
total_score += score
if total_score != 100:
self._rules_stat[Stat.TOTAL] += 1
self._score_sum += total_score
def handleDone(self):
if self._num_loaded == 0:
super(StatisticsPlugin, self).handleDone()
return
print()
for stat in self._stats + [self._rules_stat]:
stat.report()
print()
# Detailed rule violations
if self.args.verbose:
for path in self._rules_log:
printMsg(path) # does the right thing for unicode
for score, text in self._rules_log[path]:
print("\t%s%s%s (%s)" % (Fore.RED, str(score).center(3),
Fore.RESET, text))
def prettyScore():
score = float(self._score_sum) / float(self._score_count)
if score > 80:
color = Fore.GREEN
elif score > 70:
color = Fore.YELLOW
else:
color = Fore.RED
return (score, color)
score, color = prettyScore()
print("%sScore%s = %s%d%%%s" % (Style.BRIGHT, Style.RESET_BRIGHT,
color, score, Fore.RESET))
if not self.args.verbose:
print("Run with --verbose to see files and their rule violations")
print()
| gpl-2.0 |
codrut3/tensorflow | tensorflow/contrib/tensor_forest/hybrid/python/models/nn.py | 190 | 1567 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""A simple baseline feed-forward neural network."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.tensor_forest.hybrid.python import hybrid_model
from tensorflow.contrib.tensor_forest.hybrid.python.layers import fully_connected
from tensorflow.python.training import adagrad
class NN(hybrid_model.HybridModel):
"""A simple baseline feed-forward neural network."""
def __init__(self,
params,
device_assigner=None,
optimizer_class=adagrad.AdagradOptimizer,
**kwargs):
super(NN, self).__init__(
params,
device_assigner=device_assigner,
optimizer_class=optimizer_class,
**kwargs)
self.layers = [fully_connected.FullyConnectedLayer(
params, 0, device_assigner=device_assigner)]
| apache-2.0 |
hiepthai/django-activity-stream | actstream/migrations/0002_auto__chg_field_action_timestamp.py | 8 | 5778 | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
from actstream.compat import user_model_label
class Migration(SchemaMigration):
def forwards(self, orm):
# Changing field 'Action.timestamp'
db.alter_column('actstream_action', 'timestamp', self.gf('django.db.models.fields.DateTimeField')())
def backwards(self, orm):
# Changing field 'Action.timestamp'
db.alter_column('actstream_action', 'timestamp', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True))
models = {
'actstream.action': {
'Meta': {'object_name': 'Action'},
'action_object_content_type': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'action_object'", 'null': 'True', 'to': "orm['contenttypes.ContentType']"}),
'action_object_object_id': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}),
'actor_content_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'actor'", 'to': "orm['contenttypes.ContentType']"}),
'actor_object_id': ('django.db.models.fields.PositiveIntegerField', [], {}),
'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'public': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'target_content_type': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'target'", 'null': 'True', 'to': "orm['contenttypes.ContentType']"}),
'target_object_id': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}),
'timestamp': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'verb': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
'actstream.follow': {
'Meta': {'unique_together': "(('user', 'content_type', 'object_id'),)", 'object_name': 'Follow'},
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'object_id': ('django.db.models.fields.PositiveIntegerField', [], {}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['%s']" % user_model_label})
},
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
user_model_label: {
'Meta': {'object_name': user_model_label.split('.')[-1]},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
}
}
complete_apps = ['actstream']
| bsd-3-clause |
80vs90/libsaas | libsaas/services/basecamp/calendars.py | 4 | 1639 | from libsaas import http, parsers
from libsaas.services import base
from .resource import BasecampResource
from .comments import Comments
from . import accesses as acc
class CalendarEventResource(BasecampResource):
path = 'calendar_events'
class CalendarEvents(CalendarEventResource):
@base.apimethod
def past(self):
url = '{0}/past'.format(self.get_url())
request = http.Request('GET', url, {})
return request, parsers.parse_json
class CalendarEvent(CalendarEventResource):
@base.resource(Comments)
def comments(self):
"""
Return the resource corresponding to all comments.
"""
return Comments(self)
class CalendarResource(BasecampResource):
path = 'calendars'
class Calendars(CalendarResource):
pass
class Calendar(CalendarResource):
@base.resource(acc.Accesses)
def accesses(self):
"""
Return the resource corresponding to all calendar accesses.
"""
return acc.Accesses(self)
@base.resource(acc.Access)
def access(self, access_id):
"""
Return the resource corresponding to a single access.
"""
return acc.Access(self, access_id)
@base.resource(CalendarEvents)
def calendar_events(self):
"""
Return the resource corresponding to all calendar events.
"""
return CalendarEvents(self)
@base.resource(CalendarEvent)
def calendar_event(self, calendar_event_id):
"""
Return the resource corresponding to a single calendar event.
"""
return CalendarEvent(self, calendar_event_id)
| mit |
akvo/akvo-sites-zz-template | code/wp-content/themes/akvo-sites/node_modules/node-gyp/gyp/pylib/gyp/flock_tool.py | 1835 | 1748 | #!/usr/bin/env python
# Copyright (c) 2011 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""These functions are executed via gyp-flock-tool when using the Makefile
generator. Used on systems that don't have a built-in flock."""
import fcntl
import os
import struct
import subprocess
import sys
def main(args):
executor = FlockTool()
executor.Dispatch(args)
class FlockTool(object):
"""This class emulates the 'flock' command."""
def Dispatch(self, args):
"""Dispatches a string command to a method."""
if len(args) < 1:
raise Exception("Not enough arguments")
method = "Exec%s" % self._CommandifyName(args[0])
getattr(self, method)(*args[1:])
def _CommandifyName(self, name_string):
"""Transforms a tool name like copy-info-plist to CopyInfoPlist"""
return name_string.title().replace('-', '')
def ExecFlock(self, lockfile, *cmd_list):
"""Emulates the most basic behavior of Linux's flock(1)."""
# Rely on exception handling to report errors.
# Note that the stock python on SunOS has a bug
# where fcntl.flock(fd, LOCK_EX) always fails
# with EBADF, that's why we use this F_SETLK
# hack instead.
fd = os.open(lockfile, os.O_WRONLY|os.O_NOCTTY|os.O_CREAT, 0666)
if sys.platform.startswith('aix'):
# Python on AIX is compiled with LARGEFILE support, which changes the
# struct size.
op = struct.pack('hhIllqq', fcntl.F_WRLCK, 0, 0, 0, 0, 0, 0)
else:
op = struct.pack('hhllhhl', fcntl.F_WRLCK, 0, 0, 0, 0, 0, 0)
fcntl.fcntl(fd, fcntl.F_SETLK, op)
return subprocess.call(cmd_list)
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
| agpl-3.0 |
rahul67/hue | desktop/core/ext-py/requests-2.6.0/setup.py | 40 | 2124 | #!/usr/bin/env python
import os
import re
import sys
from codecs import open
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit()
packages = [
'requests',
'requests.packages',
'requests.packages.chardet',
'requests.packages.urllib3',
'requests.packages.urllib3.packages',
'requests.packages.urllib3.contrib',
'requests.packages.urllib3.util',
'requests.packages.urllib3.packages.ssl_match_hostname',
]
requires = []
version = ''
with open('requests/__init__.py', 'r') as fd:
reg = re.compile(r'__version__\s*=\s*[\'"]([^\'"]*)[\'"]')
for line in fd:
m = reg.match(line)
if m:
version = m.group(1)
break
if not version:
raise RuntimeError('Cannot find version information')
with open('README.rst', 'r', 'utf-8') as f:
readme = f.read()
with open('HISTORY.rst', 'r', 'utf-8') as f:
history = f.read()
setup(
name='requests',
version=version,
description='Python HTTP for Humans.',
long_description=readme + '\n\n' + history,
author='Kenneth Reitz',
author_email='me@kennethreitz.com',
url='http://python-requests.org',
packages=packages,
package_data={'': ['LICENSE', 'NOTICE'], 'requests': ['*.pem']},
package_dir={'requests': 'requests'},
include_package_data=True,
install_requires=requires,
license='Apache 2.0',
zip_safe=False,
classifiers=(
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4'
),
extras_require={
'security': ['pyOpenSSL', 'ndg-httpsclient', 'pyasn1'],
},
)
| apache-2.0 |
Therp/odoo | addons/document/std_index.py | 430 | 7457 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from content_index import indexer, cntIndex
from subprocess import Popen, PIPE
import StringIO
import odt2txt
import sys, zipfile, xml.dom.minidom
import logging
_logger = logging.getLogger(__name__)
def _to_unicode(s):
try:
return s.decode('utf-8')
except UnicodeError:
try:
return s.decode('latin')
except UnicodeError:
try:
return s.encode('ascii')
except UnicodeError:
return s
def textToString(element):
buffer = u""
for node in element.childNodes :
if node.nodeType == xml.dom.Node.TEXT_NODE :
buffer += node.nodeValue
elif node.nodeType == xml.dom.Node.ELEMENT_NODE :
buffer += textToString(node)
return buffer
class TxtIndex(indexer):
def _getMimeTypes(self):
return ['text/plain','text/html','text/diff','text/xml', 'text/*',
'application/xml']
def _getExtensions(self):
return ['.txt', '.py']
def _doIndexContent(self, content):
return content
cntIndex.register(TxtIndex())
class PptxIndex(indexer):
def _getMimeTypes(self):
return [ 'application/vnd.openxmlformats-officedocument.presentationml.presentation']
def _getExtensions(self):
return ['.pptx']
def _doIndexFile(self, fname):
def toString () :
""" Converts the document to a string. """
buffer = u""
for val in ["a:t"]:
for paragraph in content.getElementsByTagName(val) :
buffer += textToString(paragraph) + "\n"
return buffer
data = []
zip = zipfile.ZipFile(fname)
files = filter(lambda x: x.startswith('ppt/slides/slide'), zip.namelist())
for i in range(1, len(files) + 1):
content = xml.dom.minidom.parseString(zip.read('ppt/slides/slide%s.xml' % str(i)))
res = toString().encode('ascii','replace')
data.append(res)
return _to_unicode('\n'.join(data))
cntIndex.register(PptxIndex())
class DocIndex(indexer):
def _getMimeTypes(self):
return [ 'application/ms-word']
def _getExtensions(self):
return ['.doc']
def _doIndexFile(self, fname):
try:
pop = Popen(['antiword', fname], shell=False, stdout=PIPE)
(data, _) = pop.communicate()
return _to_unicode(data)
except OSError:
_logger.warning("Failed attempt to execute antiword (MS Word reader). Antiword is necessary to index the file %s of MIME type %s. Detailed error available at DEBUG level.", fname, self._getMimeTypes()[0])
_logger.debug("Trace of the failed file indexing attempt.", exc_info=True)
return u''
cntIndex.register(DocIndex())
class DocxIndex(indexer):
def _getMimeTypes(self):
return [ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document']
def _getExtensions(self):
return ['.docx']
def _doIndexFile(self, fname):
zip = zipfile.ZipFile(fname)
content = xml.dom.minidom.parseString(zip.read("word/document.xml"))
def toString () :
""" Converts the document to a string. """
buffer = u""
for val in ["w:p", "w:h", "text:list"]:
for paragraph in content.getElementsByTagName(val) :
buffer += textToString(paragraph) + "\n"
return buffer
res = toString().encode('ascii','replace')
return _to_unicode(res)
cntIndex.register(DocxIndex())
class XlsxIndex(indexer):
def _getMimeTypes(self):
return [ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']
def _getExtensions(self):
return ['.xlsx']
def _doIndexFile(self, fname):
zip = zipfile.ZipFile(fname)
content = xml.dom.minidom.parseString(zip.read("xl/sharedStrings.xml"))
def toString () :
""" Converts the document to a string. """
buffer = u""
for val in ["t"]:
for paragraph in content.getElementsByTagName(val) :
buffer += textToString(paragraph) + "\n"
return buffer
res = toString().encode('ascii','replace')
return _to_unicode(res)
cntIndex.register(XlsxIndex())
class PdfIndex(indexer):
def _getMimeTypes(self):
return [ 'application/pdf']
def _getExtensions(self):
return ['.pdf']
def _doIndexFile(self, fname):
try:
pop = Popen(['pdftotext', '-enc', 'UTF-8', '-nopgbrk', fname, '-'], shell=False, stdout=PIPE)
(data, _) = pop.communicate()
return _to_unicode(data)
except OSError:
_logger.warning("Failed attempt to execute pdftotext. This program is necessary to index the file %s of MIME type %s. Detailed error available at DEBUG level.", fname, self._getMimeTypes()[0])
_logger.debug("Trace of the failed file indexing attempt.", exc_info=True)
return u''
cntIndex.register(PdfIndex())
class ImageNoIndex(indexer):
def _getMimeTypes(self):
return [ 'image/*']
def _getExtensions(self):
#better return no extension, and let 'file' do its magic
return []
#return ['.png','.jpg','.gif','.jpeg','.bmp','.tiff']
def _doIndexContent(self, content):
return 'image'
cntIndex.register(ImageNoIndex())
# other opendocument formats:
# chart-template chart database
# formula-template formula graphics-template graphics
# image
# presentation-template presentation spreadsheet-template spreadsheet
class OpenDoc(indexer):
""" Index OpenDocument files.
Q: is it really worth it to index spreadsheets, or do we only get a
meaningless list of numbers (cell contents) ?
"""
def _getMimeTypes(self):
otypes = [ 'text', 'text-web', 'text-template', 'text-master' ]
return map(lambda a: 'application/vnd.oasis.opendocument.'+a, otypes)
def _getExtensions(self):
return ['.odt', '.ott', ] # '.ods'
def _doIndexContent(self, content):
s = StringIO.StringIO(content)
o = odt2txt.OpenDocumentTextFile(s)
result = _to_unicode(o.toString())
s.close()
return result
cntIndex.register(OpenDoc())
#eof
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
joakim-hove/opm-common | python/pybind11/docs/conf.py | 9 | 10659 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# pybind11 documentation build configuration file, created by
# sphinx-quickstart on Sun Oct 11 19:23:48 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
import shlex
import subprocess
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = ['breathe']
breathe_projects = {'pybind11': '.build/doxygenxml/'}
breathe_default_project = 'pybind11'
breathe_domain_by_extension = {'h': 'cpp'}
# Add any paths that contain templates here, relative to this directory.
templates_path = ['.templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = 'pybind11'
copyright = '2017, Wenzel Jakob'
author = 'Wenzel Jakob'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '2.3'
# The full version, including alpha/beta/rc tags.
release = '2.3.0'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['.build', 'release.rst']
# The reST default role (used for this markup: `text`) to use for all
# documents.
default_role = 'any'
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
#pygments_style = 'monokai'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
if not on_rtd: # only import and set the theme if we're building docs locally
import sphinx_rtd_theme
html_theme = 'sphinx_rtd_theme'
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
html_context = {
'css_files': [
'_static/theme_overrides.css'
]
}
else:
html_context = {
'css_files': [
'//media.readthedocs.org/css/sphinx_rtd_theme.css',
'//media.readthedocs.org/css/readthedocs-doc-embed.css',
'_static/theme_overrides.css'
]
}
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Language to be used for generating the HTML full-text search index.
# Sphinx supports the following languages:
# 'da', 'de', 'en', 'es', 'fi', 'fr', 'h', 'it', 'ja'
# 'nl', 'no', 'pt', 'ro', 'r', 'sv', 'tr'
#html_search_language = 'en'
# A dictionary with options for the search language support, empty by default.
# Now only 'ja' uses this config value
#html_search_options = {'type': 'default'}
# The name of a javascript file (relative to the configuration directory) that
# implements a search results scorer. If empty, the default will be used.
#html_search_scorer = 'scorer.js'
# Output file base name for HTML help builder.
htmlhelp_basename = 'pybind11doc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
'preamble': '\DeclareUnicodeCharacter{00A0}{}',
# Latex figure (float) alignment
#'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'pybind11.tex', 'pybind11 Documentation',
'Wenzel Jakob', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
# latex_logo = 'pybind11-logo.png'
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'pybind11', 'pybind11 Documentation',
[author], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'pybind11', 'pybind11 Documentation',
author, 'pybind11', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
primary_domain = 'cpp'
highlight_language = 'cpp'
def generate_doxygen_xml(app):
build_dir = os.path.join(app.confdir, '.build')
if not os.path.exists(build_dir):
os.mkdir(build_dir)
try:
subprocess.call(['doxygen', '--version'])
retcode = subprocess.call(['doxygen'], cwd=app.confdir)
if retcode < 0:
sys.stderr.write("doxygen error code: {}\n".format(-retcode))
except OSError as e:
sys.stderr.write("doxygen execution failed: {}\n".format(e))
def setup(app):
"""Add hook for building doxygen xml when needed"""
app.connect("builder-inited", generate_doxygen_xml)
| gpl-3.0 |
mbaijal/incubator-mxnet | example/memcost/inception_memcost.py | 44 | 5758 | # 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.
# pylint: skip-file
import sys
sys.path.append('../../python/')
import mxnet as mx
import logging
def ConvFactory(data, num_filter, kernel, stride=(1,1), pad=(0, 0), name=None, suffix=''):
conv = mx.symbol.Convolution(data=data, num_filter=num_filter, kernel=kernel, stride=stride, pad=pad, name='conv_%s%s' %(name, suffix))
bn = mx.symbol.BatchNorm(data=conv, name='bn_%s%s' %(name, suffix))
act = mx.symbol.Activation(data=bn, act_type='relu', name='relu_%s%s' %(name, suffix))
return act
def InceptionFactoryA(data, num_1x1, num_3x3red, num_3x3, num_d3x3red, num_d3x3, pool, proj, name):
# 1x1
c1x1 = ConvFactory(data=data, num_filter=num_1x1, kernel=(1, 1), name=('%s_1x1' % name))
# 3x3 reduce + 3x3
c3x3r = ConvFactory(data=data, num_filter=num_3x3red, kernel=(1, 1), name=('%s_3x3' % name), suffix='_reduce')
c3x3 = ConvFactory(data=c3x3r, num_filter=num_3x3, kernel=(3, 3), pad=(1, 1), name=('%s_3x3' % name))
# double 3x3 reduce + double 3x3
cd3x3r = ConvFactory(data=data, num_filter=num_d3x3red, kernel=(1, 1), name=('%s_double_3x3' % name), suffix='_reduce')
cd3x3 = ConvFactory(data=cd3x3r, num_filter=num_d3x3, kernel=(3, 3), pad=(1, 1), name=('%s_double_3x3_0' % name))
cd3x3 = ConvFactory(data=cd3x3, num_filter=num_d3x3, kernel=(3, 3), pad=(1, 1), name=('%s_double_3x3_1' % name))
# pool + proj
pooling = mx.symbol.Pooling(data=data, kernel=(3, 3), stride=(1, 1), pad=(1, 1), pool_type=pool, name=('%s_pool_%s_pool' % (pool, name)))
cproj = ConvFactory(data=pooling, num_filter=proj, kernel=(1, 1), name=('%s_proj' % name))
# concat
concat = mx.symbol.Concat(*[c1x1, c3x3, cd3x3, cproj], name='ch_concat_%s_chconcat' % name)
return concat
def InceptionFactoryB(data, num_3x3red, num_3x3, num_d3x3red, num_d3x3, name):
# 3x3 reduce + 3x3
c3x3r = ConvFactory(data=data, num_filter=num_3x3red, kernel=(1, 1), name=('%s_3x3' % name), suffix='_reduce')
c3x3 = ConvFactory(data=c3x3r, num_filter=num_3x3, kernel=(3, 3), pad=(1, 1), stride=(2, 2), name=('%s_3x3' % name))
# double 3x3 reduce + double 3x3
cd3x3r = ConvFactory(data=data, num_filter=num_d3x3red, kernel=(1, 1), name=('%s_double_3x3' % name), suffix='_reduce')
cd3x3 = ConvFactory(data=cd3x3r, num_filter=num_d3x3, kernel=(3, 3), pad=(1, 1), stride=(1, 1), name=('%s_double_3x3_0' % name))
cd3x3 = ConvFactory(data=cd3x3, num_filter=num_d3x3, kernel=(3, 3), pad=(1, 1), stride=(2, 2), name=('%s_double_3x3_1' % name))
# pool + proj
pooling = mx.symbol.Pooling(data=data, kernel=(3, 3), stride=(2, 2), pad=(1, 1), pool_type="max", name=('max_pool_%s_pool' % name))
# concat
concat = mx.symbol.Concat(*[c3x3, cd3x3, pooling], name='ch_concat_%s_chconcat' % name)
return concat
def inception(nhidden, grad_scale):
# data
data = mx.symbol.Variable(name="data")
# stage 1
conv1 = ConvFactory(data=data, num_filter=64, kernel=(7, 7), stride=(2, 2), pad=(3, 3), name='conv1')
pool1 = mx.symbol.Pooling(data=conv1, kernel=(3, 3), stride=(2, 2), name='pool1', pool_type='max')
# stage 2
conv2red = ConvFactory(data=pool1, num_filter=64, kernel=(1, 1), stride=(1, 1), name='conv2red')
conv2 = ConvFactory(data=conv2red, num_filter=192, kernel=(3, 3), stride=(1, 1), pad=(1, 1), name='conv2')
pool2 = mx.symbol.Pooling(data=conv2, kernel=(3, 3), stride=(2, 2), name='pool2', pool_type='max')
# stage 2
in3a = InceptionFactoryA(pool2, 64, 64, 64, 64, 96, "avg", 32, '3a')
in3b = InceptionFactoryA(in3a, 64, 64, 96, 64, 96, "avg", 64, '3b')
in3c = InceptionFactoryB(in3b, 128, 160, 64, 96, '3c')
# stage 3
in4a = InceptionFactoryA(in3c, 224, 64, 96, 96, 128, "avg", 128, '4a')
in4b = InceptionFactoryA(in4a, 192, 96, 128, 96, 128, "avg", 128, '4b')
in4c = InceptionFactoryA(in4b, 160, 128, 160, 128, 160, "avg", 128, '4c')
in4d = InceptionFactoryA(in4c, 96, 128, 192, 160, 192, "avg", 128, '4d')
in4e = InceptionFactoryB(in4d, 128, 192, 192, 256, '4e')
# stage 4
in5a = InceptionFactoryA(in4e, 352, 192, 320, 160, 224, "avg", 128, '5a')
in5b = InceptionFactoryA(in5a, 352, 192, 320, 192, 224, "max", 128, '5b')
# global avg pooling
avg = mx.symbol.Pooling(data=in5b, kernel=(7, 7), stride=(1, 1), name="global_pool", pool_type='avg')
# linear classifier
flatten = mx.symbol.Flatten(data=avg, name='flatten')
fc1 = mx.symbol.FullyConnected(data=flatten, num_hidden=nhidden, name='fc1')
softmax = mx.symbol.SoftmaxOutput(data=fc1, name='softmax')
return softmax
softmax = inception(1000, 1.0)
batch_size = 32
softmax = inception(1000, 1.0)
if len(sys.argv) == 2:
grad_req = sys.argv[1]
else:
grad_req = 'write'
texec = softmax.simple_bind(ctx=mx.cpu(),
data=(batch_size, 3, 224, 224),
grad_req=grad_req)
# We extract the memory cost from the execution plan
print(texec.debug_str().split('\n')[-3])
| apache-2.0 |
Microsoft/Tocino | src/visualizer/bindings/modulegen__gcc_LP64.py | 82 | 361459 | 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.visualizer', cpp_namespace='::ns3')
return root_module
def register_types(module):
root_module = module.get_root()
## address.h (module 'network'): ns3::Address [class]
module.add_class('Address', import_from_module='ns.network')
## address.h (module 'network'): ns3::Address::MaxSize_e [enumeration]
module.add_enum('MaxSize_e', ['MAX_SIZE'], outer_class=root_module['ns3::Address'], import_from_module='ns.network')
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList [class]
module.add_class('AttributeConstructionList', import_from_module='ns.core')
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item [struct]
module.add_class('Item', import_from_module='ns.core', outer_class=root_module['ns3::AttributeConstructionList'])
## buffer.h (module 'network'): ns3::Buffer [class]
module.add_class('Buffer', import_from_module='ns.network')
## buffer.h (module 'network'): ns3::Buffer::Iterator [class]
module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::Buffer'])
## packet.h (module 'network'): ns3::ByteTagIterator [class]
module.add_class('ByteTagIterator', import_from_module='ns.network')
## packet.h (module 'network'): ns3::ByteTagIterator::Item [class]
module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagIterator'])
## byte-tag-list.h (module 'network'): ns3::ByteTagList [class]
module.add_class('ByteTagList', import_from_module='ns.network')
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator [class]
module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList'])
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item [struct]
module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList::Iterator'])
## callback.h (module 'core'): ns3::CallbackBase [class]
module.add_class('CallbackBase', import_from_module='ns.core')
## event-id.h (module 'core'): ns3::EventId [class]
module.add_class('EventId', import_from_module='ns.core')
## hash.h (module 'core'): ns3::Hasher [class]
module.add_class('Hasher', import_from_module='ns.core')
## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress [class]
module.add_class('Inet6SocketAddress', import_from_module='ns.network')
## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress [class]
root_module['ns3::Inet6SocketAddress'].implicitly_converts_to(root_module['ns3::Address'])
## inet-socket-address.h (module 'network'): ns3::InetSocketAddress [class]
module.add_class('InetSocketAddress', import_from_module='ns.network')
## inet-socket-address.h (module 'network'): ns3::InetSocketAddress [class]
root_module['ns3::InetSocketAddress'].implicitly_converts_to(root_module['ns3::Address'])
## ipv4-address.h (module 'network'): ns3::Ipv4Address [class]
module.add_class('Ipv4Address', import_from_module='ns.network')
## ipv4-address.h (module 'network'): ns3::Ipv4Address [class]
root_module['ns3::Ipv4Address'].implicitly_converts_to(root_module['ns3::Address'])
## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress [class]
module.add_class('Ipv4InterfaceAddress', import_from_module='ns.internet')
## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e [enumeration]
module.add_enum('InterfaceAddressScope_e', ['HOST', 'LINK', 'GLOBAL'], outer_class=root_module['ns3::Ipv4InterfaceAddress'], import_from_module='ns.internet')
## ipv4-address.h (module 'network'): ns3::Ipv4Mask [class]
module.add_class('Ipv4Mask', import_from_module='ns.network')
## ipv6-address.h (module 'network'): ns3::Ipv6Address [class]
module.add_class('Ipv6Address', import_from_module='ns.network')
## ipv6-address.h (module 'network'): ns3::Ipv6Address [class]
root_module['ns3::Ipv6Address'].implicitly_converts_to(root_module['ns3::Address'])
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix [class]
module.add_class('Ipv6Prefix', import_from_module='ns.network')
## mac48-address.h (module 'network'): ns3::Mac48Address [class]
module.add_class('Mac48Address', import_from_module='ns.network')
## mac48-address.h (module 'network'): ns3::Mac48Address [class]
root_module['ns3::Mac48Address'].implicitly_converts_to(root_module['ns3::Address'])
## object-base.h (module 'core'): ns3::ObjectBase [class]
module.add_class('ObjectBase', allow_subclassing=True, import_from_module='ns.core')
## object.h (module 'core'): ns3::ObjectDeleter [struct]
module.add_class('ObjectDeleter', import_from_module='ns.core')
## object-factory.h (module 'core'): ns3::ObjectFactory [class]
module.add_class('ObjectFactory', import_from_module='ns.core')
## packet-metadata.h (module 'network'): ns3::PacketMetadata [class]
module.add_class('PacketMetadata', import_from_module='ns.network')
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [struct]
module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata'])
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [enumeration]
module.add_enum('', ['PAYLOAD', 'HEADER', 'TRAILER'], outer_class=root_module['ns3::PacketMetadata::Item'], import_from_module='ns.network')
## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator [class]
module.add_class('ItemIterator', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata'])
## packet.h (module 'network'): ns3::PacketTagIterator [class]
module.add_class('PacketTagIterator', import_from_module='ns.network')
## packet.h (module 'network'): ns3::PacketTagIterator::Item [class]
module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagIterator'])
## packet-tag-list.h (module 'network'): ns3::PacketTagList [class]
module.add_class('PacketTagList', import_from_module='ns.network')
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData [struct]
module.add_class('TagData', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagList'])
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData_e [enumeration]
module.add_enum('TagData_e', ['MAX_SIZE'], outer_class=root_module['ns3::PacketTagList::TagData'], import_from_module='ns.network')
## pyviz.h (module 'visualizer'): ns3::PyViz [class]
module.add_class('PyViz')
## pyviz.h (module 'visualizer'): ns3::PyViz::PacketCaptureMode [enumeration]
module.add_enum('PacketCaptureMode', ['PACKET_CAPTURE_DISABLED', 'PACKET_CAPTURE_FILTER_HEADERS_OR', 'PACKET_CAPTURE_FILTER_HEADERS_AND'], outer_class=root_module['ns3::PyViz'])
## pyviz.h (module 'visualizer'): ns3::PyViz::LastPacketsSample [struct]
module.add_class('LastPacketsSample', outer_class=root_module['ns3::PyViz'])
## pyviz.h (module 'visualizer'): ns3::PyViz::NetDeviceStatistics [struct]
module.add_class('NetDeviceStatistics', outer_class=root_module['ns3::PyViz'])
## pyviz.h (module 'visualizer'): ns3::PyViz::NodeStatistics [struct]
module.add_class('NodeStatistics', outer_class=root_module['ns3::PyViz'])
## pyviz.h (module 'visualizer'): ns3::PyViz::PacketCaptureOptions [struct]
module.add_class('PacketCaptureOptions', outer_class=root_module['ns3::PyViz'])
## pyviz.h (module 'visualizer'): ns3::PyViz::PacketDropSample [struct]
module.add_class('PacketDropSample', outer_class=root_module['ns3::PyViz'])
## pyviz.h (module 'visualizer'): ns3::PyViz::PacketSample [struct]
module.add_class('PacketSample', outer_class=root_module['ns3::PyViz'])
## pyviz.h (module 'visualizer'): ns3::PyViz::RxPacketSample [struct]
module.add_class('RxPacketSample', parent=root_module['ns3::PyViz::PacketSample'], outer_class=root_module['ns3::PyViz'])
## pyviz.h (module 'visualizer'): ns3::PyViz::TransmissionSample [struct]
module.add_class('TransmissionSample', outer_class=root_module['ns3::PyViz'])
## pyviz.h (module 'visualizer'): ns3::PyViz::TxPacketSample [struct]
module.add_class('TxPacketSample', parent=root_module['ns3::PyViz::PacketSample'], outer_class=root_module['ns3::PyViz'])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', 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', import_from_module='ns.core')
## tag.h (module 'network'): ns3::Tag [class]
module.add_class('Tag', import_from_module='ns.network', parent=root_module['ns3::ObjectBase'])
## tag-buffer.h (module 'network'): ns3::TagBuffer [class]
module.add_class('TagBuffer', import_from_module='ns.network')
## type-id.h (module 'core'): ns3::TypeId [class]
module.add_class('TypeId', import_from_module='ns.core')
## 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'], import_from_module='ns.core')
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation [struct]
module.add_class('AttributeInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId'])
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation [struct]
module.add_class('TraceSourceInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId'])
## empty.h (module 'core'): ns3::empty [class]
module.add_class('empty', import_from_module='ns.core')
## int64x64-double.h (module 'core'): ns3::int64x64_t [class]
module.add_class('int64x64_t', import_from_module='ns.core')
## chunk.h (module 'network'): ns3::Chunk [class]
module.add_class('Chunk', import_from_module='ns.network', parent=root_module['ns3::ObjectBase'])
## header.h (module 'network'): ns3::Header [class]
module.add_class('Header', import_from_module='ns.network', parent=root_module['ns3::Chunk'])
## ipv4-header.h (module 'internet'): ns3::Ipv4Header [class]
module.add_class('Ipv4Header', import_from_module='ns.internet', parent=root_module['ns3::Header'])
## ipv4-header.h (module 'internet'): ns3::Ipv4Header::DscpType [enumeration]
module.add_enum('DscpType', ['DscpDefault', 'DSCP_CS1', 'DSCP_AF11', 'DSCP_AF12', 'DSCP_AF13', 'DSCP_CS2', 'DSCP_AF21', 'DSCP_AF22', 'DSCP_AF23', 'DSCP_CS3', 'DSCP_AF31', 'DSCP_AF32', 'DSCP_AF33', 'DSCP_CS4', 'DSCP_AF41', 'DSCP_AF42', 'DSCP_AF43', 'DSCP_CS5', 'DSCP_EF', 'DSCP_CS6', 'DSCP_CS7'], outer_class=root_module['ns3::Ipv4Header'], import_from_module='ns.internet')
## ipv4-header.h (module 'internet'): ns3::Ipv4Header::EcnType [enumeration]
module.add_enum('EcnType', ['ECN_NotECT', 'ECN_ECT1', 'ECN_ECT0', 'ECN_CE'], outer_class=root_module['ns3::Ipv4Header'], import_from_module='ns.internet')
## object.h (module 'core'): ns3::Object [class]
module.add_class('Object', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >'])
## object.h (module 'core'): ns3::Object::AggregateIterator [class]
module.add_class('AggregateIterator', import_from_module='ns.core', outer_class=root_module['ns3::Object'])
## 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, import_from_module='ns.core', 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, import_from_module='ns.core', 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, import_from_module='ns.core', 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, import_from_module='ns.core', 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, import_from_module='ns.core', 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::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', 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::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Ipv4MulticastRoute', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Ipv4MulticastRoute>'], 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::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Ipv4Route', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Ipv4Route>'], 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::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::NixVector', 'ns3::empty', 'ns3::DefaultDeleter<ns3::NixVector>'], 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::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::OutputStreamWrapper', 'ns3::empty', 'ns3::DefaultDeleter<ns3::OutputStreamWrapper>'], 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::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Packet', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Packet>'], 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, import_from_module='ns.core', 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'))
## socket.h (module 'network'): ns3::Socket [class]
module.add_class('Socket', import_from_module='ns.network', parent=root_module['ns3::Object'])
## socket.h (module 'network'): ns3::Socket::SocketErrno [enumeration]
module.add_enum('SocketErrno', ['ERROR_NOTERROR', 'ERROR_ISCONN', 'ERROR_NOTCONN', 'ERROR_MSGSIZE', 'ERROR_AGAIN', 'ERROR_SHUTDOWN', 'ERROR_OPNOTSUPP', 'ERROR_AFNOSUPPORT', 'ERROR_INVAL', 'ERROR_BADF', 'ERROR_NOROUTETOHOST', 'ERROR_NODEV', 'ERROR_ADDRNOTAVAIL', 'ERROR_ADDRINUSE', 'SOCKET_ERRNO_LAST'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network')
## socket.h (module 'network'): ns3::Socket::SocketType [enumeration]
module.add_enum('SocketType', ['NS3_SOCK_STREAM', 'NS3_SOCK_SEQPACKET', 'NS3_SOCK_DGRAM', 'NS3_SOCK_RAW'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network')
## socket.h (module 'network'): ns3::SocketAddressTag [class]
module.add_class('SocketAddressTag', import_from_module='ns.network', parent=root_module['ns3::Tag'])
## socket.h (module 'network'): ns3::SocketIpTosTag [class]
module.add_class('SocketIpTosTag', import_from_module='ns.network', parent=root_module['ns3::Tag'])
## socket.h (module 'network'): ns3::SocketIpTtlTag [class]
module.add_class('SocketIpTtlTag', import_from_module='ns.network', parent=root_module['ns3::Tag'])
## socket.h (module 'network'): ns3::SocketIpv6HopLimitTag [class]
module.add_class('SocketIpv6HopLimitTag', import_from_module='ns.network', parent=root_module['ns3::Tag'])
## socket.h (module 'network'): ns3::SocketIpv6TclassTag [class]
module.add_class('SocketIpv6TclassTag', import_from_module='ns.network', parent=root_module['ns3::Tag'])
## socket.h (module 'network'): ns3::SocketSetDontFragmentTag [class]
module.add_class('SocketSetDontFragmentTag', import_from_module='ns.network', parent=root_module['ns3::Tag'])
## nstime.h (module 'core'): ns3::Time [class]
module.add_class('Time', import_from_module='ns.core')
## 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'], import_from_module='ns.core')
## 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', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >'])
## trailer.h (module 'network'): ns3::Trailer [class]
module.add_class('Trailer', import_from_module='ns.network', parent=root_module['ns3::Chunk'])
## attribute.h (module 'core'): ns3::AttributeAccessor [class]
module.add_class('AttributeAccessor', import_from_module='ns.core', 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, import_from_module='ns.core', 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, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >'])
## callback.h (module 'core'): ns3::CallbackChecker [class]
module.add_class('CallbackChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## callback.h (module 'core'): ns3::CallbackImplBase [class]
module.add_class('CallbackImplBase', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >'])
## callback.h (module 'core'): ns3::CallbackValue [class]
module.add_class('CallbackValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## channel.h (module 'network'): ns3::Channel [class]
module.add_class('Channel', import_from_module='ns.network', parent=root_module['ns3::Object'])
## attribute.h (module 'core'): ns3::EmptyAttributeValue [class]
module.add_class('EmptyAttributeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## event-impl.h (module 'core'): ns3::EventImpl [class]
module.add_class('EventImpl', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >'])
## ipv4.h (module 'internet'): ns3::Ipv4 [class]
module.add_class('Ipv4', import_from_module='ns.internet', parent=root_module['ns3::Object'])
## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker [class]
module.add_class('Ipv4AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue [class]
module.add_class('Ipv4AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4L3Protocol [class]
module.add_class('Ipv4L3Protocol', import_from_module='ns.internet', parent=root_module['ns3::Ipv4'])
## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4L3Protocol::DropReason [enumeration]
module.add_enum('DropReason', ['DROP_TTL_EXPIRED', 'DROP_NO_ROUTE', 'DROP_BAD_CHECKSUM', 'DROP_INTERFACE_DOWN', 'DROP_ROUTE_ERROR', 'DROP_FRAGMENT_TIMEOUT'], outer_class=root_module['ns3::Ipv4L3Protocol'], import_from_module='ns.internet')
## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker [class]
module.add_class('Ipv4MaskChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue [class]
module.add_class('Ipv4MaskValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute [class]
module.add_class('Ipv4MulticastRoute', import_from_module='ns.internet', parent=root_module['ns3::SimpleRefCount< ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >'])
## ipv4-route.h (module 'internet'): ns3::Ipv4Route [class]
module.add_class('Ipv4Route', import_from_module='ns.internet', parent=root_module['ns3::SimpleRefCount< ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >'])
## ipv4-routing-protocol.h (module 'internet'): ns3::Ipv4RoutingProtocol [class]
module.add_class('Ipv4RoutingProtocol', import_from_module='ns.internet', parent=root_module['ns3::Object'])
## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker [class]
module.add_class('Ipv6AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue [class]
module.add_class('Ipv6AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker [class]
module.add_class('Ipv6PrefixChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue [class]
module.add_class('Ipv6PrefixValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
## mac48-address.h (module 'network'): ns3::Mac48AddressChecker [class]
module.add_class('Mac48AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
## mac48-address.h (module 'network'): ns3::Mac48AddressValue [class]
module.add_class('Mac48AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
## net-device.h (module 'network'): ns3::NetDevice [class]
module.add_class('NetDevice', import_from_module='ns.network', parent=root_module['ns3::Object'])
## net-device.h (module 'network'): ns3::NetDevice::PacketType [enumeration]
module.add_enum('PacketType', ['PACKET_HOST', 'NS3_PACKET_HOST', 'PACKET_BROADCAST', 'NS3_PACKET_BROADCAST', 'PACKET_MULTICAST', 'NS3_PACKET_MULTICAST', 'PACKET_OTHERHOST', 'NS3_PACKET_OTHERHOST'], outer_class=root_module['ns3::NetDevice'], import_from_module='ns.network')
## nix-vector.h (module 'network'): ns3::NixVector [class]
module.add_class('NixVector', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >'])
## node.h (module 'network'): ns3::Node [class]
module.add_class('Node', import_from_module='ns.network', parent=root_module['ns3::Object'])
## object-factory.h (module 'core'): ns3::ObjectFactoryChecker [class]
module.add_class('ObjectFactoryChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## object-factory.h (module 'core'): ns3::ObjectFactoryValue [class]
module.add_class('ObjectFactoryValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper [class]
module.add_class('OutputStreamWrapper', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >'])
## packet.h (module 'network'): ns3::Packet [class]
module.add_class('Packet', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >'])
## nstime.h (module 'core'): ns3::TimeValue [class]
module.add_class('TimeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## type-id.h (module 'core'): ns3::TypeIdChecker [class]
module.add_class('TypeIdChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## type-id.h (module 'core'): ns3::TypeIdValue [class]
module.add_class('TypeIdValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## address.h (module 'network'): ns3::AddressChecker [class]
module.add_class('AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
## address.h (module 'network'): ns3::AddressValue [class]
module.add_class('AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
module.add_container('std::vector< ns3::PyViz::RxPacketSample >', 'ns3::PyViz::RxPacketSample', container_type='vector')
module.add_container('std::vector< ns3::PyViz::TxPacketSample >', 'ns3::PyViz::TxPacketSample', container_type='vector')
module.add_container('std::vector< ns3::PyViz::PacketSample >', 'ns3::PyViz::PacketSample', container_type='vector')
module.add_container('std::set< ns3::TypeId >', 'ns3::TypeId', container_type='set')
module.add_container('std::vector< ns3::PyViz::TransmissionSample >', 'ns3::PyViz::TransmissionSample', container_type='vector')
module.add_container('std::vector< ns3::PyViz::PacketDropSample >', 'ns3::PyViz::PacketDropSample', container_type='vector')
module.add_container('std::vector< ns3::PyViz::NetDeviceStatistics >', 'ns3::PyViz::NetDeviceStatistics', container_type='vector')
module.add_container('std::vector< std::string >', 'std::string', container_type='vector')
module.add_container('std::set< unsigned int >', 'unsigned int', container_type='set')
module.add_container('std::vector< ns3::PyViz::NodeStatistics >', 'ns3::PyViz::NodeStatistics', container_type='vector')
module.add_container('std::map< unsigned int, unsigned int >', ('unsigned int', 'unsigned int'), container_type='map')
## 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)
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', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >'])
typehandlers.add_type_alias('uint32_t ( * ) ( char const *, size_t ) *', 'ns3::Hash::Hash32Function_ptr')
typehandlers.add_type_alias('uint32_t ( * ) ( char const *, size_t ) **', 'ns3::Hash::Hash32Function_ptr*')
typehandlers.add_type_alias('uint32_t ( * ) ( char const *, size_t ) *&', 'ns3::Hash::Hash32Function_ptr&')
typehandlers.add_type_alias('uint64_t ( * ) ( char const *, size_t ) *', 'ns3::Hash::Hash64Function_ptr')
typehandlers.add_type_alias('uint64_t ( * ) ( char const *, size_t ) **', 'ns3::Hash::Hash64Function_ptr*')
typehandlers.add_type_alias('uint64_t ( * ) ( char const *, size_t ) *&', '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', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation'])
## hash-function.h (module 'core'): ns3::Hash::Function::Hash32 [class]
module.add_class('Hash32', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation'])
## hash-function.h (module 'core'): ns3::Hash::Function::Hash64 [class]
module.add_class('Hash64', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation'])
## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3 [class]
module.add_class('Murmur3', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation'])
def register_methods(root_module):
register_Ns3Address_methods(root_module, root_module['ns3::Address'])
register_Ns3AttributeConstructionList_methods(root_module, root_module['ns3::AttributeConstructionList'])
register_Ns3AttributeConstructionListItem_methods(root_module, root_module['ns3::AttributeConstructionList::Item'])
register_Ns3Buffer_methods(root_module, root_module['ns3::Buffer'])
register_Ns3BufferIterator_methods(root_module, root_module['ns3::Buffer::Iterator'])
register_Ns3ByteTagIterator_methods(root_module, root_module['ns3::ByteTagIterator'])
register_Ns3ByteTagIteratorItem_methods(root_module, root_module['ns3::ByteTagIterator::Item'])
register_Ns3ByteTagList_methods(root_module, root_module['ns3::ByteTagList'])
register_Ns3ByteTagListIterator_methods(root_module, root_module['ns3::ByteTagList::Iterator'])
register_Ns3ByteTagListIteratorItem_methods(root_module, root_module['ns3::ByteTagList::Iterator::Item'])
register_Ns3CallbackBase_methods(root_module, root_module['ns3::CallbackBase'])
register_Ns3EventId_methods(root_module, root_module['ns3::EventId'])
register_Ns3Hasher_methods(root_module, root_module['ns3::Hasher'])
register_Ns3Inet6SocketAddress_methods(root_module, root_module['ns3::Inet6SocketAddress'])
register_Ns3InetSocketAddress_methods(root_module, root_module['ns3::InetSocketAddress'])
register_Ns3Ipv4Address_methods(root_module, root_module['ns3::Ipv4Address'])
register_Ns3Ipv4InterfaceAddress_methods(root_module, root_module['ns3::Ipv4InterfaceAddress'])
register_Ns3Ipv4Mask_methods(root_module, root_module['ns3::Ipv4Mask'])
register_Ns3Ipv6Address_methods(root_module, root_module['ns3::Ipv6Address'])
register_Ns3Ipv6Prefix_methods(root_module, root_module['ns3::Ipv6Prefix'])
register_Ns3Mac48Address_methods(root_module, root_module['ns3::Mac48Address'])
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_Ns3PacketMetadata_methods(root_module, root_module['ns3::PacketMetadata'])
register_Ns3PacketMetadataItem_methods(root_module, root_module['ns3::PacketMetadata::Item'])
register_Ns3PacketMetadataItemIterator_methods(root_module, root_module['ns3::PacketMetadata::ItemIterator'])
register_Ns3PacketTagIterator_methods(root_module, root_module['ns3::PacketTagIterator'])
register_Ns3PacketTagIteratorItem_methods(root_module, root_module['ns3::PacketTagIterator::Item'])
register_Ns3PacketTagList_methods(root_module, root_module['ns3::PacketTagList'])
register_Ns3PacketTagListTagData_methods(root_module, root_module['ns3::PacketTagList::TagData'])
register_Ns3PyViz_methods(root_module, root_module['ns3::PyViz'])
register_Ns3PyVizLastPacketsSample_methods(root_module, root_module['ns3::PyViz::LastPacketsSample'])
register_Ns3PyVizNetDeviceStatistics_methods(root_module, root_module['ns3::PyViz::NetDeviceStatistics'])
register_Ns3PyVizNodeStatistics_methods(root_module, root_module['ns3::PyViz::NodeStatistics'])
register_Ns3PyVizPacketCaptureOptions_methods(root_module, root_module['ns3::PyViz::PacketCaptureOptions'])
register_Ns3PyVizPacketDropSample_methods(root_module, root_module['ns3::PyViz::PacketDropSample'])
register_Ns3PyVizPacketSample_methods(root_module, root_module['ns3::PyViz::PacketSample'])
register_Ns3PyVizRxPacketSample_methods(root_module, root_module['ns3::PyViz::RxPacketSample'])
register_Ns3PyVizTransmissionSample_methods(root_module, root_module['ns3::PyViz::TransmissionSample'])
register_Ns3PyVizTxPacketSample_methods(root_module, root_module['ns3::PyViz::TxPacketSample'])
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_Ns3Tag_methods(root_module, root_module['ns3::Tag'])
register_Ns3TagBuffer_methods(root_module, root_module['ns3::TagBuffer'])
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_Ns3Empty_methods(root_module, root_module['ns3::empty'])
register_Ns3Int64x64_t_methods(root_module, root_module['ns3::int64x64_t'])
register_Ns3Chunk_methods(root_module, root_module['ns3::Chunk'])
register_Ns3Header_methods(root_module, root_module['ns3::Header'])
register_Ns3Ipv4Header_methods(root_module, root_module['ns3::Ipv4Header'])
register_Ns3Object_methods(root_module, root_module['ns3::Object'])
register_Ns3ObjectAggregateIterator_methods(root_module, root_module['ns3::Object::AggregateIterator'])
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__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__Ns3Ipv4MulticastRoute_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4MulticastRoute__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >'])
register_Ns3SimpleRefCount__Ns3Ipv4Route_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4Route__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >'])
register_Ns3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >'])
register_Ns3SimpleRefCount__Ns3OutputStreamWrapper_Ns3Empty_Ns3DefaultDeleter__lt__ns3OutputStreamWrapper__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >'])
register_Ns3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >'])
register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >'])
register_Ns3Socket_methods(root_module, root_module['ns3::Socket'])
register_Ns3SocketAddressTag_methods(root_module, root_module['ns3::SocketAddressTag'])
register_Ns3SocketIpTosTag_methods(root_module, root_module['ns3::SocketIpTosTag'])
register_Ns3SocketIpTtlTag_methods(root_module, root_module['ns3::SocketIpTtlTag'])
register_Ns3SocketIpv6HopLimitTag_methods(root_module, root_module['ns3::SocketIpv6HopLimitTag'])
register_Ns3SocketIpv6TclassTag_methods(root_module, root_module['ns3::SocketIpv6TclassTag'])
register_Ns3SocketSetDontFragmentTag_methods(root_module, root_module['ns3::SocketSetDontFragmentTag'])
register_Ns3Time_methods(root_module, root_module['ns3::Time'])
register_Ns3TraceSourceAccessor_methods(root_module, root_module['ns3::TraceSourceAccessor'])
register_Ns3Trailer_methods(root_module, root_module['ns3::Trailer'])
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_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_Ns3Channel_methods(root_module, root_module['ns3::Channel'])
register_Ns3EmptyAttributeValue_methods(root_module, root_module['ns3::EmptyAttributeValue'])
register_Ns3EventImpl_methods(root_module, root_module['ns3::EventImpl'])
register_Ns3Ipv4_methods(root_module, root_module['ns3::Ipv4'])
register_Ns3Ipv4AddressChecker_methods(root_module, root_module['ns3::Ipv4AddressChecker'])
register_Ns3Ipv4AddressValue_methods(root_module, root_module['ns3::Ipv4AddressValue'])
register_Ns3Ipv4L3Protocol_methods(root_module, root_module['ns3::Ipv4L3Protocol'])
register_Ns3Ipv4MaskChecker_methods(root_module, root_module['ns3::Ipv4MaskChecker'])
register_Ns3Ipv4MaskValue_methods(root_module, root_module['ns3::Ipv4MaskValue'])
register_Ns3Ipv4MulticastRoute_methods(root_module, root_module['ns3::Ipv4MulticastRoute'])
register_Ns3Ipv4Route_methods(root_module, root_module['ns3::Ipv4Route'])
register_Ns3Ipv4RoutingProtocol_methods(root_module, root_module['ns3::Ipv4RoutingProtocol'])
register_Ns3Ipv6AddressChecker_methods(root_module, root_module['ns3::Ipv6AddressChecker'])
register_Ns3Ipv6AddressValue_methods(root_module, root_module['ns3::Ipv6AddressValue'])
register_Ns3Ipv6PrefixChecker_methods(root_module, root_module['ns3::Ipv6PrefixChecker'])
register_Ns3Ipv6PrefixValue_methods(root_module, root_module['ns3::Ipv6PrefixValue'])
register_Ns3Mac48AddressChecker_methods(root_module, root_module['ns3::Mac48AddressChecker'])
register_Ns3Mac48AddressValue_methods(root_module, root_module['ns3::Mac48AddressValue'])
register_Ns3NetDevice_methods(root_module, root_module['ns3::NetDevice'])
register_Ns3NixVector_methods(root_module, root_module['ns3::NixVector'])
register_Ns3Node_methods(root_module, root_module['ns3::Node'])
register_Ns3ObjectFactoryChecker_methods(root_module, root_module['ns3::ObjectFactoryChecker'])
register_Ns3ObjectFactoryValue_methods(root_module, root_module['ns3::ObjectFactoryValue'])
register_Ns3OutputStreamWrapper_methods(root_module, root_module['ns3::OutputStreamWrapper'])
register_Ns3Packet_methods(root_module, root_module['ns3::Packet'])
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_Ns3AddressChecker_methods(root_module, root_module['ns3::AddressChecker'])
register_Ns3AddressValue_methods(root_module, root_module['ns3::AddressValue'])
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_Ns3Address_methods(root_module, cls):
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('!=')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## address.h (module 'network'): ns3::Address::Address() [constructor]
cls.add_constructor([])
## address.h (module 'network'): ns3::Address::Address(uint8_t type, uint8_t const * buffer, uint8_t len) [constructor]
cls.add_constructor([param('uint8_t', 'type'), param('uint8_t const *', 'buffer'), param('uint8_t', 'len')])
## address.h (module 'network'): ns3::Address::Address(ns3::Address const & address) [copy constructor]
cls.add_constructor([param('ns3::Address const &', 'address')])
## address.h (module 'network'): bool ns3::Address::CheckCompatible(uint8_t type, uint8_t len) const [member function]
cls.add_method('CheckCompatible',
'bool',
[param('uint8_t', 'type'), param('uint8_t', 'len')],
is_const=True)
## address.h (module 'network'): uint32_t ns3::Address::CopyAllFrom(uint8_t const * buffer, uint8_t len) [member function]
cls.add_method('CopyAllFrom',
'uint32_t',
[param('uint8_t const *', 'buffer'), param('uint8_t', 'len')])
## address.h (module 'network'): uint32_t ns3::Address::CopyAllTo(uint8_t * buffer, uint8_t len) const [member function]
cls.add_method('CopyAllTo',
'uint32_t',
[param('uint8_t *', 'buffer'), param('uint8_t', 'len')],
is_const=True)
## address.h (module 'network'): uint32_t ns3::Address::CopyFrom(uint8_t const * buffer, uint8_t len) [member function]
cls.add_method('CopyFrom',
'uint32_t',
[param('uint8_t const *', 'buffer'), param('uint8_t', 'len')])
## address.h (module 'network'): uint32_t ns3::Address::CopyTo(uint8_t * buffer) const [member function]
cls.add_method('CopyTo',
'uint32_t',
[param('uint8_t *', 'buffer')],
is_const=True)
## address.h (module 'network'): void ns3::Address::Deserialize(ns3::TagBuffer buffer) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'buffer')])
## address.h (module 'network'): uint8_t ns3::Address::GetLength() const [member function]
cls.add_method('GetLength',
'uint8_t',
[],
is_const=True)
## address.h (module 'network'): uint32_t ns3::Address::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## address.h (module 'network'): bool ns3::Address::IsInvalid() const [member function]
cls.add_method('IsInvalid',
'bool',
[],
is_const=True)
## address.h (module 'network'): bool ns3::Address::IsMatchingType(uint8_t type) const [member function]
cls.add_method('IsMatchingType',
'bool',
[param('uint8_t', 'type')],
is_const=True)
## address.h (module 'network'): static uint8_t ns3::Address::Register() [member function]
cls.add_method('Register',
'uint8_t',
[],
is_static=True)
## address.h (module 'network'): void ns3::Address::Serialize(ns3::TagBuffer buffer) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'buffer')],
is_const=True)
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_Ns3Buffer_methods(root_module, cls):
## buffer.h (module 'network'): ns3::Buffer::Buffer() [constructor]
cls.add_constructor([])
## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize) [constructor]
cls.add_constructor([param('uint32_t', 'dataSize')])
## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize, bool initialize) [constructor]
cls.add_constructor([param('uint32_t', 'dataSize'), param('bool', 'initialize')])
## buffer.h (module 'network'): ns3::Buffer::Buffer(ns3::Buffer const & o) [copy constructor]
cls.add_constructor([param('ns3::Buffer const &', 'o')])
## buffer.h (module 'network'): bool ns3::Buffer::AddAtEnd(uint32_t end) [member function]
cls.add_method('AddAtEnd',
'bool',
[param('uint32_t', 'end')])
## buffer.h (module 'network'): void ns3::Buffer::AddAtEnd(ns3::Buffer const & o) [member function]
cls.add_method('AddAtEnd',
'void',
[param('ns3::Buffer const &', 'o')])
## buffer.h (module 'network'): bool ns3::Buffer::AddAtStart(uint32_t start) [member function]
cls.add_method('AddAtStart',
'bool',
[param('uint32_t', 'start')])
## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::Begin() const [member function]
cls.add_method('Begin',
'ns3::Buffer::Iterator',
[],
is_const=True)
## buffer.h (module 'network'): void ns3::Buffer::CopyData(std::ostream * os, uint32_t size) const [member function]
cls.add_method('CopyData',
'void',
[param('std::ostream *', 'os'), param('uint32_t', 'size')],
is_const=True)
## buffer.h (module 'network'): uint32_t ns3::Buffer::CopyData(uint8_t * buffer, uint32_t size) const [member function]
cls.add_method('CopyData',
'uint32_t',
[param('uint8_t *', 'buffer'), param('uint32_t', 'size')],
is_const=True)
## buffer.h (module 'network'): ns3::Buffer ns3::Buffer::CreateFragment(uint32_t start, uint32_t length) const [member function]
cls.add_method('CreateFragment',
'ns3::Buffer',
[param('uint32_t', 'start'), param('uint32_t', 'length')],
is_const=True)
## buffer.h (module 'network'): ns3::Buffer ns3::Buffer::CreateFullCopy() const [member function]
cls.add_method('CreateFullCopy',
'ns3::Buffer',
[],
is_const=True)
## buffer.h (module 'network'): uint32_t ns3::Buffer::Deserialize(uint8_t const * buffer, uint32_t size) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('uint8_t const *', 'buffer'), param('uint32_t', 'size')])
## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::End() const [member function]
cls.add_method('End',
'ns3::Buffer::Iterator',
[],
is_const=True)
## buffer.h (module 'network'): int32_t ns3::Buffer::GetCurrentEndOffset() const [member function]
cls.add_method('GetCurrentEndOffset',
'int32_t',
[],
is_const=True)
## buffer.h (module 'network'): int32_t ns3::Buffer::GetCurrentStartOffset() const [member function]
cls.add_method('GetCurrentStartOffset',
'int32_t',
[],
is_const=True)
## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSize() const [member function]
cls.add_method('GetSize',
'uint32_t',
[],
is_const=True)
## buffer.h (module 'network'): uint8_t const * ns3::Buffer::PeekData() const [member function]
cls.add_method('PeekData',
'uint8_t const *',
[],
is_const=True)
## buffer.h (module 'network'): void ns3::Buffer::RemoveAtEnd(uint32_t end) [member function]
cls.add_method('RemoveAtEnd',
'void',
[param('uint32_t', 'end')])
## buffer.h (module 'network'): void ns3::Buffer::RemoveAtStart(uint32_t start) [member function]
cls.add_method('RemoveAtStart',
'void',
[param('uint32_t', 'start')])
## buffer.h (module 'network'): uint32_t ns3::Buffer::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function]
cls.add_method('Serialize',
'uint32_t',
[param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')],
is_const=True)
return
def register_Ns3BufferIterator_methods(root_module, cls):
## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator(ns3::Buffer::Iterator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Buffer::Iterator const &', 'arg0')])
## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator() [constructor]
cls.add_constructor([])
## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size) [member function]
cls.add_method('CalculateIpChecksum',
'uint16_t',
[param('uint16_t', 'size')])
## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size, uint32_t initialChecksum) [member function]
cls.add_method('CalculateIpChecksum',
'uint16_t',
[param('uint16_t', 'size'), param('uint32_t', 'initialChecksum')])
## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetDistanceFrom(ns3::Buffer::Iterator const & o) const [member function]
cls.add_method('GetDistanceFrom',
'uint32_t',
[param('ns3::Buffer::Iterator const &', 'o')],
is_const=True)
## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetSize() const [member function]
cls.add_method('GetSize',
'uint32_t',
[],
is_const=True)
## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsEnd() const [member function]
cls.add_method('IsEnd',
'bool',
[],
is_const=True)
## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsStart() const [member function]
cls.add_method('IsStart',
'bool',
[],
is_const=True)
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next() [member function]
cls.add_method('Next',
'void',
[])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next(uint32_t delta) [member function]
cls.add_method('Next',
'void',
[param('uint32_t', 'delta')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev() [member function]
cls.add_method('Prev',
'void',
[])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev(uint32_t delta) [member function]
cls.add_method('Prev',
'void',
[param('uint32_t', 'delta')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Read(uint8_t * buffer, uint32_t size) [member function]
cls.add_method('Read',
'void',
[param('uint8_t *', 'buffer'), param('uint32_t', 'size')])
## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadLsbtohU16() [member function]
cls.add_method('ReadLsbtohU16',
'uint16_t',
[])
## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadLsbtohU32() [member function]
cls.add_method('ReadLsbtohU32',
'uint32_t',
[])
## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadLsbtohU64() [member function]
cls.add_method('ReadLsbtohU64',
'uint64_t',
[])
## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadNtohU16() [member function]
cls.add_method('ReadNtohU16',
'uint16_t',
[])
## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadNtohU32() [member function]
cls.add_method('ReadNtohU32',
'uint32_t',
[])
## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadNtohU64() [member function]
cls.add_method('ReadNtohU64',
'uint64_t',
[])
## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadU16() [member function]
cls.add_method('ReadU16',
'uint16_t',
[])
## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadU32() [member function]
cls.add_method('ReadU32',
'uint32_t',
[])
## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadU64() [member function]
cls.add_method('ReadU64',
'uint64_t',
[])
## buffer.h (module 'network'): uint8_t ns3::Buffer::Iterator::ReadU8() [member function]
cls.add_method('ReadU8',
'uint8_t',
[])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(uint8_t const * buffer, uint32_t size) [member function]
cls.add_method('Write',
'void',
[param('uint8_t const *', 'buffer'), param('uint32_t', 'size')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(ns3::Buffer::Iterator start, ns3::Buffer::Iterator end) [member function]
cls.add_method('Write',
'void',
[param('ns3::Buffer::Iterator', 'start'), param('ns3::Buffer::Iterator', 'end')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU16(uint16_t data) [member function]
cls.add_method('WriteHtolsbU16',
'void',
[param('uint16_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU32(uint32_t data) [member function]
cls.add_method('WriteHtolsbU32',
'void',
[param('uint32_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU64(uint64_t data) [member function]
cls.add_method('WriteHtolsbU64',
'void',
[param('uint64_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU16(uint16_t data) [member function]
cls.add_method('WriteHtonU16',
'void',
[param('uint16_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU32(uint32_t data) [member function]
cls.add_method('WriteHtonU32',
'void',
[param('uint32_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU64(uint64_t data) [member function]
cls.add_method('WriteHtonU64',
'void',
[param('uint64_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU16(uint16_t data) [member function]
cls.add_method('WriteU16',
'void',
[param('uint16_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU32(uint32_t data) [member function]
cls.add_method('WriteU32',
'void',
[param('uint32_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU64(uint64_t data) [member function]
cls.add_method('WriteU64',
'void',
[param('uint64_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data) [member function]
cls.add_method('WriteU8',
'void',
[param('uint8_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data, uint32_t len) [member function]
cls.add_method('WriteU8',
'void',
[param('uint8_t', 'data'), param('uint32_t', 'len')])
return
def register_Ns3ByteTagIterator_methods(root_module, cls):
## packet.h (module 'network'): ns3::ByteTagIterator::ByteTagIterator(ns3::ByteTagIterator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ByteTagIterator const &', 'arg0')])
## packet.h (module 'network'): bool ns3::ByteTagIterator::HasNext() const [member function]
cls.add_method('HasNext',
'bool',
[],
is_const=True)
## packet.h (module 'network'): ns3::ByteTagIterator::Item ns3::ByteTagIterator::Next() [member function]
cls.add_method('Next',
'ns3::ByteTagIterator::Item',
[])
return
def register_Ns3ByteTagIteratorItem_methods(root_module, cls):
## packet.h (module 'network'): ns3::ByteTagIterator::Item::Item(ns3::ByteTagIterator::Item const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ByteTagIterator::Item const &', 'arg0')])
## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetEnd() const [member function]
cls.add_method('GetEnd',
'uint32_t',
[],
is_const=True)
## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetStart() const [member function]
cls.add_method('GetStart',
'uint32_t',
[],
is_const=True)
## packet.h (module 'network'): void ns3::ByteTagIterator::Item::GetTag(ns3::Tag & tag) const [member function]
cls.add_method('GetTag',
'void',
[param('ns3::Tag &', 'tag')],
is_const=True)
## packet.h (module 'network'): ns3::TypeId ns3::ByteTagIterator::Item::GetTypeId() const [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_const=True)
return
def register_Ns3ByteTagList_methods(root_module, cls):
## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList() [constructor]
cls.add_constructor([])
## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList(ns3::ByteTagList const & o) [copy constructor]
cls.add_constructor([param('ns3::ByteTagList const &', 'o')])
## byte-tag-list.h (module 'network'): ns3::TagBuffer ns3::ByteTagList::Add(ns3::TypeId tid, uint32_t bufferSize, int32_t start, int32_t end) [member function]
cls.add_method('Add',
'ns3::TagBuffer',
[param('ns3::TypeId', 'tid'), param('uint32_t', 'bufferSize'), param('int32_t', 'start'), param('int32_t', 'end')])
## byte-tag-list.h (module 'network'): void ns3::ByteTagList::Add(ns3::ByteTagList const & o) [member function]
cls.add_method('Add',
'void',
[param('ns3::ByteTagList const &', 'o')])
## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtEnd(int32_t adjustment, int32_t appendOffset) [member function]
cls.add_method('AddAtEnd',
'void',
[param('int32_t', 'adjustment'), param('int32_t', 'appendOffset')])
## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtStart(int32_t adjustment, int32_t prependOffset) [member function]
cls.add_method('AddAtStart',
'void',
[param('int32_t', 'adjustment'), param('int32_t', 'prependOffset')])
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator ns3::ByteTagList::Begin(int32_t offsetStart, int32_t offsetEnd) const [member function]
cls.add_method('Begin',
'ns3::ByteTagList::Iterator',
[param('int32_t', 'offsetStart'), param('int32_t', 'offsetEnd')],
is_const=True)
## byte-tag-list.h (module 'network'): void ns3::ByteTagList::RemoveAll() [member function]
cls.add_method('RemoveAll',
'void',
[])
return
def register_Ns3ByteTagListIterator_methods(root_module, cls):
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Iterator(ns3::ByteTagList::Iterator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ByteTagList::Iterator const &', 'arg0')])
## byte-tag-list.h (module 'network'): uint32_t ns3::ByteTagList::Iterator::GetOffsetStart() const [member function]
cls.add_method('GetOffsetStart',
'uint32_t',
[],
is_const=True)
## byte-tag-list.h (module 'network'): bool ns3::ByteTagList::Iterator::HasNext() const [member function]
cls.add_method('HasNext',
'bool',
[],
is_const=True)
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item ns3::ByteTagList::Iterator::Next() [member function]
cls.add_method('Next',
'ns3::ByteTagList::Iterator::Item',
[])
return
def register_Ns3ByteTagListIteratorItem_methods(root_module, cls):
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::ByteTagList::Iterator::Item const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ByteTagList::Iterator::Item const &', 'arg0')])
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::TagBuffer buf) [constructor]
cls.add_constructor([param('ns3::TagBuffer', 'buf')])
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::buf [variable]
cls.add_instance_attribute('buf', 'ns3::TagBuffer', is_const=False)
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::end [variable]
cls.add_instance_attribute('end', 'int32_t', is_const=False)
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::size [variable]
cls.add_instance_attribute('size', 'uint32_t', is_const=False)
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::start [variable]
cls.add_instance_attribute('start', 'int32_t', is_const=False)
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::tid [variable]
cls.add_instance_attribute('tid', 'ns3::TypeId', 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')
## callback.h (module 'core'): static std::string ns3::CallbackBase::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_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_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_Ns3Inet6SocketAddress_methods(root_module, cls):
## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(ns3::Inet6SocketAddress const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Inet6SocketAddress const &', 'arg0')])
## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(ns3::Ipv6Address ipv6, uint16_t port) [constructor]
cls.add_constructor([param('ns3::Ipv6Address', 'ipv6'), param('uint16_t', 'port')])
## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(ns3::Ipv6Address ipv6) [constructor]
cls.add_constructor([param('ns3::Ipv6Address', 'ipv6')])
## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(uint16_t port) [constructor]
cls.add_constructor([param('uint16_t', 'port')])
## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(char const * ipv6, uint16_t port) [constructor]
cls.add_constructor([param('char const *', 'ipv6'), param('uint16_t', 'port')])
## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(char const * ipv6) [constructor]
cls.add_constructor([param('char const *', 'ipv6')])
## inet6-socket-address.h (module 'network'): static ns3::Inet6SocketAddress ns3::Inet6SocketAddress::ConvertFrom(ns3::Address const & addr) [member function]
cls.add_method('ConvertFrom',
'ns3::Inet6SocketAddress',
[param('ns3::Address const &', 'addr')],
is_static=True)
## inet6-socket-address.h (module 'network'): ns3::Ipv6Address ns3::Inet6SocketAddress::GetIpv6() const [member function]
cls.add_method('GetIpv6',
'ns3::Ipv6Address',
[],
is_const=True)
## inet6-socket-address.h (module 'network'): uint16_t ns3::Inet6SocketAddress::GetPort() const [member function]
cls.add_method('GetPort',
'uint16_t',
[],
is_const=True)
## inet6-socket-address.h (module 'network'): static bool ns3::Inet6SocketAddress::IsMatchingType(ns3::Address const & addr) [member function]
cls.add_method('IsMatchingType',
'bool',
[param('ns3::Address const &', 'addr')],
is_static=True)
## inet6-socket-address.h (module 'network'): void ns3::Inet6SocketAddress::SetIpv6(ns3::Ipv6Address ipv6) [member function]
cls.add_method('SetIpv6',
'void',
[param('ns3::Ipv6Address', 'ipv6')])
## inet6-socket-address.h (module 'network'): void ns3::Inet6SocketAddress::SetPort(uint16_t port) [member function]
cls.add_method('SetPort',
'void',
[param('uint16_t', 'port')])
return
def register_Ns3InetSocketAddress_methods(root_module, cls):
## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(ns3::InetSocketAddress const & arg0) [copy constructor]
cls.add_constructor([param('ns3::InetSocketAddress const &', 'arg0')])
## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(ns3::Ipv4Address ipv4, uint16_t port) [constructor]
cls.add_constructor([param('ns3::Ipv4Address', 'ipv4'), param('uint16_t', 'port')])
## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(ns3::Ipv4Address ipv4) [constructor]
cls.add_constructor([param('ns3::Ipv4Address', 'ipv4')])
## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(uint16_t port) [constructor]
cls.add_constructor([param('uint16_t', 'port')])
## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(char const * ipv4, uint16_t port) [constructor]
cls.add_constructor([param('char const *', 'ipv4'), param('uint16_t', 'port')])
## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(char const * ipv4) [constructor]
cls.add_constructor([param('char const *', 'ipv4')])
## inet-socket-address.h (module 'network'): static ns3::InetSocketAddress ns3::InetSocketAddress::ConvertFrom(ns3::Address const & address) [member function]
cls.add_method('ConvertFrom',
'ns3::InetSocketAddress',
[param('ns3::Address const &', 'address')],
is_static=True)
## inet-socket-address.h (module 'network'): ns3::Ipv4Address ns3::InetSocketAddress::GetIpv4() const [member function]
cls.add_method('GetIpv4',
'ns3::Ipv4Address',
[],
is_const=True)
## inet-socket-address.h (module 'network'): uint16_t ns3::InetSocketAddress::GetPort() const [member function]
cls.add_method('GetPort',
'uint16_t',
[],
is_const=True)
## inet-socket-address.h (module 'network'): static bool ns3::InetSocketAddress::IsMatchingType(ns3::Address const & address) [member function]
cls.add_method('IsMatchingType',
'bool',
[param('ns3::Address const &', 'address')],
is_static=True)
## inet-socket-address.h (module 'network'): void ns3::InetSocketAddress::SetIpv4(ns3::Ipv4Address address) [member function]
cls.add_method('SetIpv4',
'void',
[param('ns3::Ipv4Address', 'address')])
## inet-socket-address.h (module 'network'): void ns3::InetSocketAddress::SetPort(uint16_t port) [member function]
cls.add_method('SetPort',
'void',
[param('uint16_t', 'port')])
return
def register_Ns3Ipv4Address_methods(root_module, cls):
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('!=')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(ns3::Ipv4Address const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4Address const &', 'arg0')])
## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address() [constructor]
cls.add_constructor([])
## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(uint32_t address) [constructor]
cls.add_constructor([param('uint32_t', 'address')])
## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(char const * address) [constructor]
cls.add_constructor([param('char const *', 'address')])
## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::CombineMask(ns3::Ipv4Mask const & mask) const [member function]
cls.add_method('CombineMask',
'ns3::Ipv4Address',
[param('ns3::Ipv4Mask const &', 'mask')],
is_const=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::ConvertFrom(ns3::Address const & address) [member function]
cls.add_method('ConvertFrom',
'ns3::Ipv4Address',
[param('ns3::Address const &', 'address')],
is_static=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::Deserialize(uint8_t const * buf) [member function]
cls.add_method('Deserialize',
'ns3::Ipv4Address',
[param('uint8_t const *', 'buf')],
is_static=True)
## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Address::Get() const [member function]
cls.add_method('Get',
'uint32_t',
[],
is_const=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetAny() [member function]
cls.add_method('GetAny',
'ns3::Ipv4Address',
[],
is_static=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetBroadcast() [member function]
cls.add_method('GetBroadcast',
'ns3::Ipv4Address',
[],
is_static=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetLoopback() [member function]
cls.add_method('GetLoopback',
'ns3::Ipv4Address',
[],
is_static=True)
## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::GetSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function]
cls.add_method('GetSubnetDirectedBroadcast',
'ns3::Ipv4Address',
[param('ns3::Ipv4Mask const &', 'mask')],
is_const=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetZero() [member function]
cls.add_method('GetZero',
'ns3::Ipv4Address',
[],
is_static=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsBroadcast() const [member function]
cls.add_method('IsBroadcast',
'bool',
[],
is_const=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsEqual(ns3::Ipv4Address const & other) const [member function]
cls.add_method('IsEqual',
'bool',
[param('ns3::Ipv4Address const &', 'other')],
is_const=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsLocalMulticast() const [member function]
cls.add_method('IsLocalMulticast',
'bool',
[],
is_const=True)
## ipv4-address.h (module 'network'): static bool ns3::Ipv4Address::IsMatchingType(ns3::Address const & address) [member function]
cls.add_method('IsMatchingType',
'bool',
[param('ns3::Address const &', 'address')],
is_static=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsMulticast() const [member function]
cls.add_method('IsMulticast',
'bool',
[],
is_const=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function]
cls.add_method('IsSubnetDirectedBroadcast',
'bool',
[param('ns3::Ipv4Mask const &', 'mask')],
is_const=True)
## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Serialize(uint8_t * buf) const [member function]
cls.add_method('Serialize',
'void',
[param('uint8_t *', 'buf')],
is_const=True)
## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(uint32_t address) [member function]
cls.add_method('Set',
'void',
[param('uint32_t', 'address')])
## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(char const * address) [member function]
cls.add_method('Set',
'void',
[param('char const *', 'address')])
return
def register_Ns3Ipv4InterfaceAddress_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::Ipv4InterfaceAddress() [constructor]
cls.add_constructor([])
## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::Ipv4InterfaceAddress(ns3::Ipv4Address local, ns3::Ipv4Mask mask) [constructor]
cls.add_constructor([param('ns3::Ipv4Address', 'local'), param('ns3::Ipv4Mask', 'mask')])
## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::Ipv4InterfaceAddress(ns3::Ipv4InterfaceAddress const & o) [copy constructor]
cls.add_constructor([param('ns3::Ipv4InterfaceAddress const &', 'o')])
## ipv4-interface-address.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4InterfaceAddress::GetBroadcast() const [member function]
cls.add_method('GetBroadcast',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv4-interface-address.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4InterfaceAddress::GetLocal() const [member function]
cls.add_method('GetLocal',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv4-interface-address.h (module 'internet'): ns3::Ipv4Mask ns3::Ipv4InterfaceAddress::GetMask() const [member function]
cls.add_method('GetMask',
'ns3::Ipv4Mask',
[],
is_const=True)
## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e ns3::Ipv4InterfaceAddress::GetScope() const [member function]
cls.add_method('GetScope',
'ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e',
[],
is_const=True)
## ipv4-interface-address.h (module 'internet'): bool ns3::Ipv4InterfaceAddress::IsSecondary() const [member function]
cls.add_method('IsSecondary',
'bool',
[],
is_const=True)
## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetBroadcast(ns3::Ipv4Address broadcast) [member function]
cls.add_method('SetBroadcast',
'void',
[param('ns3::Ipv4Address', 'broadcast')])
## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetLocal(ns3::Ipv4Address local) [member function]
cls.add_method('SetLocal',
'void',
[param('ns3::Ipv4Address', 'local')])
## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetMask(ns3::Ipv4Mask mask) [member function]
cls.add_method('SetMask',
'void',
[param('ns3::Ipv4Mask', 'mask')])
## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetPrimary() [member function]
cls.add_method('SetPrimary',
'void',
[])
## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetScope(ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e scope) [member function]
cls.add_method('SetScope',
'void',
[param('ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e', 'scope')])
## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetSecondary() [member function]
cls.add_method('SetSecondary',
'void',
[])
return
def register_Ns3Ipv4Mask_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(ns3::Ipv4Mask const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4Mask const &', 'arg0')])
## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask() [constructor]
cls.add_constructor([])
## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(uint32_t mask) [constructor]
cls.add_constructor([param('uint32_t', 'mask')])
## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(char const * mask) [constructor]
cls.add_constructor([param('char const *', 'mask')])
## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::Get() const [member function]
cls.add_method('Get',
'uint32_t',
[],
is_const=True)
## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::GetInverse() const [member function]
cls.add_method('GetInverse',
'uint32_t',
[],
is_const=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetLoopback() [member function]
cls.add_method('GetLoopback',
'ns3::Ipv4Mask',
[],
is_static=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetOnes() [member function]
cls.add_method('GetOnes',
'ns3::Ipv4Mask',
[],
is_static=True)
## ipv4-address.h (module 'network'): uint16_t ns3::Ipv4Mask::GetPrefixLength() const [member function]
cls.add_method('GetPrefixLength',
'uint16_t',
[],
is_const=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetZero() [member function]
cls.add_method('GetZero',
'ns3::Ipv4Mask',
[],
is_static=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsEqual(ns3::Ipv4Mask other) const [member function]
cls.add_method('IsEqual',
'bool',
[param('ns3::Ipv4Mask', 'other')],
is_const=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsMatch(ns3::Ipv4Address a, ns3::Ipv4Address b) const [member function]
cls.add_method('IsMatch',
'bool',
[param('ns3::Ipv4Address', 'a'), param('ns3::Ipv4Address', 'b')],
is_const=True)
## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Set(uint32_t mask) [member function]
cls.add_method('Set',
'void',
[param('uint32_t', 'mask')])
return
def register_Ns3Ipv6Address_methods(root_module, cls):
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('!=')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address() [constructor]
cls.add_constructor([])
## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(char const * address) [constructor]
cls.add_constructor([param('char const *', 'address')])
## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(uint8_t * address) [constructor]
cls.add_constructor([param('uint8_t *', 'address')])
## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const & addr) [copy constructor]
cls.add_constructor([param('ns3::Ipv6Address const &', 'addr')])
## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const * addr) [constructor]
cls.add_constructor([param('ns3::Ipv6Address const *', 'addr')])
## ipv6-address.h (module 'network'): ns3::Ipv6Address ns3::Ipv6Address::CombinePrefix(ns3::Ipv6Prefix const & prefix) [member function]
cls.add_method('CombinePrefix',
'ns3::Ipv6Address',
[param('ns3::Ipv6Prefix const &', 'prefix')])
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::ConvertFrom(ns3::Address const & address) [member function]
cls.add_method('ConvertFrom',
'ns3::Ipv6Address',
[param('ns3::Address const &', 'address')],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::Deserialize(uint8_t const * buf) [member function]
cls.add_method('Deserialize',
'ns3::Ipv6Address',
[param('uint8_t const *', 'buf')],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllHostsMulticast() [member function]
cls.add_method('GetAllHostsMulticast',
'ns3::Ipv6Address',
[],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllNodesMulticast() [member function]
cls.add_method('GetAllNodesMulticast',
'ns3::Ipv6Address',
[],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllRoutersMulticast() [member function]
cls.add_method('GetAllRoutersMulticast',
'ns3::Ipv6Address',
[],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAny() [member function]
cls.add_method('GetAny',
'ns3::Ipv6Address',
[],
is_static=True)
## ipv6-address.h (module 'network'): void ns3::Ipv6Address::GetBytes(uint8_t * buf) const [member function]
cls.add_method('GetBytes',
'void',
[param('uint8_t *', 'buf')],
is_const=True)
## ipv6-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv6Address::GetIpv4MappedAddress() const [member function]
cls.add_method('GetIpv4MappedAddress',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetLoopback() [member function]
cls.add_method('GetLoopback',
'ns3::Ipv6Address',
[],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetOnes() [member function]
cls.add_method('GetOnes',
'ns3::Ipv6Address',
[],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetZero() [member function]
cls.add_method('GetZero',
'ns3::Ipv6Address',
[],
is_static=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllHostsMulticast() const [member function]
cls.add_method('IsAllHostsMulticast',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllNodesMulticast() const [member function]
cls.add_method('IsAllNodesMulticast',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllRoutersMulticast() const [member function]
cls.add_method('IsAllRoutersMulticast',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAny() const [member function]
cls.add_method('IsAny',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsDocumentation() const [member function]
cls.add_method('IsDocumentation',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsEqual(ns3::Ipv6Address const & other) const [member function]
cls.add_method('IsEqual',
'bool',
[param('ns3::Ipv6Address const &', 'other')],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsIpv4MappedAddress() const [member function]
cls.add_method('IsIpv4MappedAddress',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLinkLocal() const [member function]
cls.add_method('IsLinkLocal',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLinkLocalMulticast() const [member function]
cls.add_method('IsLinkLocalMulticast',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLocalhost() const [member function]
cls.add_method('IsLocalhost',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): static bool ns3::Ipv6Address::IsMatchingType(ns3::Address const & address) [member function]
cls.add_method('IsMatchingType',
'bool',
[param('ns3::Address const &', 'address')],
is_static=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsMulticast() const [member function]
cls.add_method('IsMulticast',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsSolicitedMulticast() const [member function]
cls.add_method('IsSolicitedMulticast',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac16Address addr, ns3::Ipv6Address prefix) [member function]
cls.add_method('MakeAutoconfiguredAddress',
'ns3::Ipv6Address',
[param('ns3::Mac16Address', 'addr'), param('ns3::Ipv6Address', 'prefix')],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac48Address addr, ns3::Ipv6Address prefix) [member function]
cls.add_method('MakeAutoconfiguredAddress',
'ns3::Ipv6Address',
[param('ns3::Mac48Address', 'addr'), param('ns3::Ipv6Address', 'prefix')],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac64Address addr, ns3::Ipv6Address prefix) [member function]
cls.add_method('MakeAutoconfiguredAddress',
'ns3::Ipv6Address',
[param('ns3::Mac64Address', 'addr'), param('ns3::Ipv6Address', 'prefix')],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac16Address mac) [member function]
cls.add_method('MakeAutoconfiguredLinkLocalAddress',
'ns3::Ipv6Address',
[param('ns3::Mac16Address', 'mac')],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac48Address mac) [member function]
cls.add_method('MakeAutoconfiguredLinkLocalAddress',
'ns3::Ipv6Address',
[param('ns3::Mac48Address', 'mac')],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac64Address mac) [member function]
cls.add_method('MakeAutoconfiguredLinkLocalAddress',
'ns3::Ipv6Address',
[param('ns3::Mac64Address', 'mac')],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeIpv4MappedAddress(ns3::Ipv4Address addr) [member function]
cls.add_method('MakeIpv4MappedAddress',
'ns3::Ipv6Address',
[param('ns3::Ipv4Address', 'addr')],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeSolicitedAddress(ns3::Ipv6Address addr) [member function]
cls.add_method('MakeSolicitedAddress',
'ns3::Ipv6Address',
[param('ns3::Ipv6Address', 'addr')],
is_static=True)
## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Serialize(uint8_t * buf) const [member function]
cls.add_method('Serialize',
'void',
[param('uint8_t *', 'buf')],
is_const=True)
## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(char const * address) [member function]
cls.add_method('Set',
'void',
[param('char const *', 'address')])
## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(uint8_t * address) [member function]
cls.add_method('Set',
'void',
[param('uint8_t *', 'address')])
return
def register_Ns3Ipv6Prefix_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix() [constructor]
cls.add_constructor([])
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t * prefix) [constructor]
cls.add_constructor([param('uint8_t *', 'prefix')])
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(char const * prefix) [constructor]
cls.add_constructor([param('char const *', 'prefix')])
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t prefix) [constructor]
cls.add_constructor([param('uint8_t', 'prefix')])
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const & prefix) [copy constructor]
cls.add_constructor([param('ns3::Ipv6Prefix const &', 'prefix')])
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const * prefix) [constructor]
cls.add_constructor([param('ns3::Ipv6Prefix const *', 'prefix')])
## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::GetBytes(uint8_t * buf) const [member function]
cls.add_method('GetBytes',
'void',
[param('uint8_t *', 'buf')],
is_const=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetLoopback() [member function]
cls.add_method('GetLoopback',
'ns3::Ipv6Prefix',
[],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetOnes() [member function]
cls.add_method('GetOnes',
'ns3::Ipv6Prefix',
[],
is_static=True)
## ipv6-address.h (module 'network'): uint8_t ns3::Ipv6Prefix::GetPrefixLength() const [member function]
cls.add_method('GetPrefixLength',
'uint8_t',
[],
is_const=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetZero() [member function]
cls.add_method('GetZero',
'ns3::Ipv6Prefix',
[],
is_static=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsEqual(ns3::Ipv6Prefix const & other) const [member function]
cls.add_method('IsEqual',
'bool',
[param('ns3::Ipv6Prefix const &', 'other')],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsMatch(ns3::Ipv6Address a, ns3::Ipv6Address b) const [member function]
cls.add_method('IsMatch',
'bool',
[param('ns3::Ipv6Address', 'a'), param('ns3::Ipv6Address', 'b')],
is_const=True)
## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
return
def register_Ns3Mac48Address_methods(root_module, cls):
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('!=')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address(ns3::Mac48Address const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Mac48Address const &', 'arg0')])
## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address() [constructor]
cls.add_constructor([])
## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address(char const * str) [constructor]
cls.add_constructor([param('char const *', 'str')])
## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::Allocate() [member function]
cls.add_method('Allocate',
'ns3::Mac48Address',
[],
is_static=True)
## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::ConvertFrom(ns3::Address const & address) [member function]
cls.add_method('ConvertFrom',
'ns3::Mac48Address',
[param('ns3::Address const &', 'address')],
is_static=True)
## mac48-address.h (module 'network'): void ns3::Mac48Address::CopyFrom(uint8_t const * buffer) [member function]
cls.add_method('CopyFrom',
'void',
[param('uint8_t const *', 'buffer')])
## mac48-address.h (module 'network'): void ns3::Mac48Address::CopyTo(uint8_t * buffer) const [member function]
cls.add_method('CopyTo',
'void',
[param('uint8_t *', 'buffer')],
is_const=True)
## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetBroadcast() [member function]
cls.add_method('GetBroadcast',
'ns3::Mac48Address',
[],
is_static=True)
## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast(ns3::Ipv4Address address) [member function]
cls.add_method('GetMulticast',
'ns3::Mac48Address',
[param('ns3::Ipv4Address', 'address')],
is_static=True)
## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast(ns3::Ipv6Address address) [member function]
cls.add_method('GetMulticast',
'ns3::Mac48Address',
[param('ns3::Ipv6Address', 'address')],
is_static=True)
## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast6Prefix() [member function]
cls.add_method('GetMulticast6Prefix',
'ns3::Mac48Address',
[],
is_static=True)
## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticastPrefix() [member function]
cls.add_method('GetMulticastPrefix',
'ns3::Mac48Address',
[],
is_static=True)
## mac48-address.h (module 'network'): bool ns3::Mac48Address::IsBroadcast() const [member function]
cls.add_method('IsBroadcast',
'bool',
[],
is_const=True)
## mac48-address.h (module 'network'): bool ns3::Mac48Address::IsGroup() const [member function]
cls.add_method('IsGroup',
'bool',
[],
is_const=True)
## mac48-address.h (module 'network'): static bool ns3::Mac48Address::IsMatchingType(ns3::Address const & address) [member function]
cls.add_method('IsMatchingType',
'bool',
[param('ns3::Address const &', 'address')],
is_static=True)
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 & attribute) const [member function]
cls.add_method('GetAttributeFailSafe',
'bool',
[param('std::string', 'name'), param('ns3::AttributeValue &', 'attribute')],
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_Ns3PacketMetadata_methods(root_module, cls):
## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(uint64_t uid, uint32_t size) [constructor]
cls.add_constructor([param('uint64_t', 'uid'), param('uint32_t', 'size')])
## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(ns3::PacketMetadata const & o) [copy constructor]
cls.add_constructor([param('ns3::PacketMetadata const &', 'o')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddAtEnd(ns3::PacketMetadata const & o) [member function]
cls.add_method('AddAtEnd',
'void',
[param('ns3::PacketMetadata const &', 'o')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddHeader(ns3::Header const & header, uint32_t size) [member function]
cls.add_method('AddHeader',
'void',
[param('ns3::Header const &', 'header'), param('uint32_t', 'size')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddPaddingAtEnd(uint32_t end) [member function]
cls.add_method('AddPaddingAtEnd',
'void',
[param('uint32_t', 'end')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddTrailer(ns3::Trailer const & trailer, uint32_t size) [member function]
cls.add_method('AddTrailer',
'void',
[param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')])
## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::PacketMetadata::BeginItem(ns3::Buffer buffer) const [member function]
cls.add_method('BeginItem',
'ns3::PacketMetadata::ItemIterator',
[param('ns3::Buffer', 'buffer')],
is_const=True)
## packet-metadata.h (module 'network'): ns3::PacketMetadata ns3::PacketMetadata::CreateFragment(uint32_t start, uint32_t end) const [member function]
cls.add_method('CreateFragment',
'ns3::PacketMetadata',
[param('uint32_t', 'start'), param('uint32_t', 'end')],
is_const=True)
## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Deserialize(uint8_t const * buffer, uint32_t size) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('uint8_t const *', 'buffer'), param('uint32_t', 'size')])
## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::Enable() [member function]
cls.add_method('Enable',
'void',
[],
is_static=True)
## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::EnableChecking() [member function]
cls.add_method('EnableChecking',
'void',
[],
is_static=True)
## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## packet-metadata.h (module 'network'): uint64_t ns3::PacketMetadata::GetUid() const [member function]
cls.add_method('GetUid',
'uint64_t',
[],
is_const=True)
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtEnd(uint32_t end) [member function]
cls.add_method('RemoveAtEnd',
'void',
[param('uint32_t', 'end')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtStart(uint32_t start) [member function]
cls.add_method('RemoveAtStart',
'void',
[param('uint32_t', 'start')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveHeader(ns3::Header const & header, uint32_t size) [member function]
cls.add_method('RemoveHeader',
'void',
[param('ns3::Header const &', 'header'), param('uint32_t', 'size')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveTrailer(ns3::Trailer const & trailer, uint32_t size) [member function]
cls.add_method('RemoveTrailer',
'void',
[param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')])
## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function]
cls.add_method('Serialize',
'uint32_t',
[param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')],
is_const=True)
return
def register_Ns3PacketMetadataItem_methods(root_module, cls):
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item() [constructor]
cls.add_constructor([])
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item(ns3::PacketMetadata::Item const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketMetadata::Item const &', 'arg0')])
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::current [variable]
cls.add_instance_attribute('current', 'ns3::Buffer::Iterator', is_const=False)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentSize [variable]
cls.add_instance_attribute('currentSize', 'uint32_t', is_const=False)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromEnd [variable]
cls.add_instance_attribute('currentTrimedFromEnd', 'uint32_t', is_const=False)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromStart [variable]
cls.add_instance_attribute('currentTrimedFromStart', 'uint32_t', is_const=False)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::isFragment [variable]
cls.add_instance_attribute('isFragment', 'bool', is_const=False)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::tid [variable]
cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False)
return
def register_Ns3PacketMetadataItemIterator_methods(root_module, cls):
## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata::ItemIterator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketMetadata::ItemIterator const &', 'arg0')])
## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata const * metadata, ns3::Buffer buffer) [constructor]
cls.add_constructor([param('ns3::PacketMetadata const *', 'metadata'), param('ns3::Buffer', 'buffer')])
## packet-metadata.h (module 'network'): bool ns3::PacketMetadata::ItemIterator::HasNext() const [member function]
cls.add_method('HasNext',
'bool',
[],
is_const=True)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item ns3::PacketMetadata::ItemIterator::Next() [member function]
cls.add_method('Next',
'ns3::PacketMetadata::Item',
[])
return
def register_Ns3PacketTagIterator_methods(root_module, cls):
## packet.h (module 'network'): ns3::PacketTagIterator::PacketTagIterator(ns3::PacketTagIterator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketTagIterator const &', 'arg0')])
## packet.h (module 'network'): bool ns3::PacketTagIterator::HasNext() const [member function]
cls.add_method('HasNext',
'bool',
[],
is_const=True)
## packet.h (module 'network'): ns3::PacketTagIterator::Item ns3::PacketTagIterator::Next() [member function]
cls.add_method('Next',
'ns3::PacketTagIterator::Item',
[])
return
def register_Ns3PacketTagIteratorItem_methods(root_module, cls):
## packet.h (module 'network'): ns3::PacketTagIterator::Item::Item(ns3::PacketTagIterator::Item const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketTagIterator::Item const &', 'arg0')])
## packet.h (module 'network'): void ns3::PacketTagIterator::Item::GetTag(ns3::Tag & tag) const [member function]
cls.add_method('GetTag',
'void',
[param('ns3::Tag &', 'tag')],
is_const=True)
## packet.h (module 'network'): ns3::TypeId ns3::PacketTagIterator::Item::GetTypeId() const [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_const=True)
return
def register_Ns3PacketTagList_methods(root_module, cls):
## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList() [constructor]
cls.add_constructor([])
## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList(ns3::PacketTagList const & o) [copy constructor]
cls.add_constructor([param('ns3::PacketTagList const &', 'o')])
## packet-tag-list.h (module 'network'): void ns3::PacketTagList::Add(ns3::Tag const & tag) const [member function]
cls.add_method('Add',
'void',
[param('ns3::Tag const &', 'tag')],
is_const=True)
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData const * ns3::PacketTagList::Head() const [member function]
cls.add_method('Head',
'ns3::PacketTagList::TagData const *',
[],
is_const=True)
## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Peek(ns3::Tag & tag) const [member function]
cls.add_method('Peek',
'bool',
[param('ns3::Tag &', 'tag')],
is_const=True)
## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Remove(ns3::Tag & tag) [member function]
cls.add_method('Remove',
'bool',
[param('ns3::Tag &', 'tag')])
## packet-tag-list.h (module 'network'): void ns3::PacketTagList::RemoveAll() [member function]
cls.add_method('RemoveAll',
'void',
[])
## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Replace(ns3::Tag & tag) [member function]
cls.add_method('Replace',
'bool',
[param('ns3::Tag &', 'tag')])
return
def register_Ns3PacketTagListTagData_methods(root_module, cls):
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData() [constructor]
cls.add_constructor([])
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData(ns3::PacketTagList::TagData const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketTagList::TagData const &', 'arg0')])
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::count [variable]
cls.add_instance_attribute('count', 'uint32_t', is_const=False)
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::data [variable]
cls.add_instance_attribute('data', 'uint8_t [ 20 ]', is_const=False)
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::next [variable]
cls.add_instance_attribute('next', 'ns3::PacketTagList::TagData *', is_const=False)
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::tid [variable]
cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False)
return
def register_Ns3PyViz_methods(root_module, cls):
## pyviz.h (module 'visualizer'): ns3::PyViz::PyViz(ns3::PyViz const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PyViz const &', 'arg0')])
## pyviz.h (module 'visualizer'): ns3::PyViz::PyViz() [constructor]
cls.add_constructor([])
## pyviz.h (module 'visualizer'): ns3::PyViz::LastPacketsSample ns3::PyViz::GetLastPackets(uint32_t nodeId) const [member function]
cls.add_method('GetLastPackets',
'ns3::PyViz::LastPacketsSample',
[param('uint32_t', 'nodeId')],
is_const=True)
## pyviz.h (module 'visualizer'): std::vector<ns3::PyViz::NodeStatistics,std::allocator<ns3::PyViz::NodeStatistics> > ns3::PyViz::GetNodesStatistics() const [member function]
cls.add_method('GetNodesStatistics',
'std::vector< ns3::PyViz::NodeStatistics >',
[],
is_const=True)
## pyviz.h (module 'visualizer'): std::vector<ns3::PyViz::PacketDropSample,std::allocator<ns3::PyViz::PacketDropSample> > ns3::PyViz::GetPacketDropSamples() const [member function]
cls.add_method('GetPacketDropSamples',
'std::vector< ns3::PyViz::PacketDropSample >',
[],
is_const=True)
## pyviz.h (module 'visualizer'): std::vector<std::string, std::allocator<std::string> > ns3::PyViz::GetPauseMessages() const [member function]
cls.add_method('GetPauseMessages',
'std::vector< std::string >',
[],
is_const=True)
## pyviz.h (module 'visualizer'): std::vector<ns3::PyViz::TransmissionSample,std::allocator<ns3::PyViz::TransmissionSample> > ns3::PyViz::GetTransmissionSamples() const [member function]
cls.add_method('GetTransmissionSamples',
'std::vector< ns3::PyViz::TransmissionSample >',
[],
is_const=True)
## pyviz.h (module 'visualizer'): static void ns3::PyViz::LineClipping(double boundsX1, double boundsY1, double boundsX2, double boundsY2, double & lineX1, double & lineY1, double & lineX2, double & lineY2) [member function]
cls.add_method('LineClipping',
'void',
[param('double', 'boundsX1'), param('double', 'boundsY1'), param('double', 'boundsX2'), param('double', 'boundsY2'), param('double &', 'lineX1', direction=3), param('double &', 'lineY1', direction=3), param('double &', 'lineX2', direction=3), param('double &', 'lineY2', direction=3)],
is_static=True)
## pyviz.h (module 'visualizer'): static void ns3::PyViz::Pause(std::string const & message) [member function]
cls.add_method('Pause',
'void',
[param('std::string const &', 'message')],
is_static=True)
## pyviz.h (module 'visualizer'): void ns3::PyViz::RegisterCsmaLikeDevice(std::string const & deviceTypeName) [member function]
cls.add_method('RegisterCsmaLikeDevice',
'void',
[param('std::string const &', 'deviceTypeName')])
## pyviz.h (module 'visualizer'): void ns3::PyViz::RegisterDropTracePath(std::string const & tracePath) [member function]
cls.add_method('RegisterDropTracePath',
'void',
[param('std::string const &', 'tracePath')])
## pyviz.h (module 'visualizer'): void ns3::PyViz::RegisterPointToPointLikeDevice(std::string const & deviceTypeName) [member function]
cls.add_method('RegisterPointToPointLikeDevice',
'void',
[param('std::string const &', 'deviceTypeName')])
## pyviz.h (module 'visualizer'): void ns3::PyViz::RegisterWifiLikeDevice(std::string const & deviceTypeName) [member function]
cls.add_method('RegisterWifiLikeDevice',
'void',
[param('std::string const &', 'deviceTypeName')])
## pyviz.h (module 'visualizer'): void ns3::PyViz::SetNodesOfInterest(std::set<unsigned int, std::less<unsigned int>, std::allocator<unsigned int> > nodes) [member function]
cls.add_method('SetNodesOfInterest',
'void',
[param('std::set< unsigned int >', 'nodes')])
## pyviz.h (module 'visualizer'): void ns3::PyViz::SetPacketCaptureOptions(uint32_t nodeId, ns3::PyViz::PacketCaptureOptions options) [member function]
cls.add_method('SetPacketCaptureOptions',
'void',
[param('uint32_t', 'nodeId'), param('ns3::PyViz::PacketCaptureOptions', 'options')])
## pyviz.h (module 'visualizer'): void ns3::PyViz::SimulatorRunUntil(ns3::Time time) [member function]
cls.add_method('SimulatorRunUntil',
'void',
[param('ns3::Time', 'time')])
return
def register_Ns3PyVizLastPacketsSample_methods(root_module, cls):
## pyviz.h (module 'visualizer'): ns3::PyViz::LastPacketsSample::LastPacketsSample() [constructor]
cls.add_constructor([])
## pyviz.h (module 'visualizer'): ns3::PyViz::LastPacketsSample::LastPacketsSample(ns3::PyViz::LastPacketsSample const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PyViz::LastPacketsSample const &', 'arg0')])
## pyviz.h (module 'visualizer'): ns3::PyViz::LastPacketsSample::lastDroppedPackets [variable]
cls.add_instance_attribute('lastDroppedPackets', 'std::vector< ns3::PyViz::PacketSample >', is_const=False)
## pyviz.h (module 'visualizer'): ns3::PyViz::LastPacketsSample::lastReceivedPackets [variable]
cls.add_instance_attribute('lastReceivedPackets', 'std::vector< ns3::PyViz::RxPacketSample >', is_const=False)
## pyviz.h (module 'visualizer'): ns3::PyViz::LastPacketsSample::lastTransmittedPackets [variable]
cls.add_instance_attribute('lastTransmittedPackets', 'std::vector< ns3::PyViz::TxPacketSample >', is_const=False)
return
def register_Ns3PyVizNetDeviceStatistics_methods(root_module, cls):
## pyviz.h (module 'visualizer'): ns3::PyViz::NetDeviceStatistics::NetDeviceStatistics(ns3::PyViz::NetDeviceStatistics const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PyViz::NetDeviceStatistics const &', 'arg0')])
## pyviz.h (module 'visualizer'): ns3::PyViz::NetDeviceStatistics::NetDeviceStatistics() [constructor]
cls.add_constructor([])
## pyviz.h (module 'visualizer'): ns3::PyViz::NetDeviceStatistics::receivedBytes [variable]
cls.add_instance_attribute('receivedBytes', 'uint64_t', is_const=False)
## pyviz.h (module 'visualizer'): ns3::PyViz::NetDeviceStatistics::receivedPackets [variable]
cls.add_instance_attribute('receivedPackets', 'uint32_t', is_const=False)
## pyviz.h (module 'visualizer'): ns3::PyViz::NetDeviceStatistics::transmittedBytes [variable]
cls.add_instance_attribute('transmittedBytes', 'uint64_t', is_const=False)
## pyviz.h (module 'visualizer'): ns3::PyViz::NetDeviceStatistics::transmittedPackets [variable]
cls.add_instance_attribute('transmittedPackets', 'uint32_t', is_const=False)
return
def register_Ns3PyVizNodeStatistics_methods(root_module, cls):
## pyviz.h (module 'visualizer'): ns3::PyViz::NodeStatistics::NodeStatistics() [constructor]
cls.add_constructor([])
## pyviz.h (module 'visualizer'): ns3::PyViz::NodeStatistics::NodeStatistics(ns3::PyViz::NodeStatistics const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PyViz::NodeStatistics const &', 'arg0')])
## pyviz.h (module 'visualizer'): ns3::PyViz::NodeStatistics::nodeId [variable]
cls.add_instance_attribute('nodeId', 'uint32_t', is_const=False)
## pyviz.h (module 'visualizer'): ns3::PyViz::NodeStatistics::statistics [variable]
cls.add_instance_attribute('statistics', 'std::vector< ns3::PyViz::NetDeviceStatistics >', is_const=False)
return
def register_Ns3PyVizPacketCaptureOptions_methods(root_module, cls):
## pyviz.h (module 'visualizer'): ns3::PyViz::PacketCaptureOptions::PacketCaptureOptions() [constructor]
cls.add_constructor([])
## pyviz.h (module 'visualizer'): ns3::PyViz::PacketCaptureOptions::PacketCaptureOptions(ns3::PyViz::PacketCaptureOptions const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PyViz::PacketCaptureOptions const &', 'arg0')])
## pyviz.h (module 'visualizer'): ns3::PyViz::PacketCaptureOptions::headers [variable]
cls.add_instance_attribute('headers', 'std::set< ns3::TypeId >', is_const=False)
## pyviz.h (module 'visualizer'): ns3::PyViz::PacketCaptureOptions::mode [variable]
cls.add_instance_attribute('mode', 'ns3::PyViz::PacketCaptureMode', is_const=False)
## pyviz.h (module 'visualizer'): ns3::PyViz::PacketCaptureOptions::numLastPackets [variable]
cls.add_instance_attribute('numLastPackets', 'uint32_t', is_const=False)
return
def register_Ns3PyVizPacketDropSample_methods(root_module, cls):
## pyviz.h (module 'visualizer'): ns3::PyViz::PacketDropSample::PacketDropSample() [constructor]
cls.add_constructor([])
## pyviz.h (module 'visualizer'): ns3::PyViz::PacketDropSample::PacketDropSample(ns3::PyViz::PacketDropSample const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PyViz::PacketDropSample const &', 'arg0')])
## pyviz.h (module 'visualizer'): ns3::PyViz::PacketDropSample::bytes [variable]
cls.add_instance_attribute('bytes', 'uint32_t', is_const=False)
## pyviz.h (module 'visualizer'): ns3::PyViz::PacketDropSample::transmitter [variable]
cls.add_instance_attribute('transmitter', 'ns3::Ptr< ns3::Node >', is_const=False)
return
def register_Ns3PyVizPacketSample_methods(root_module, cls):
## pyviz.h (module 'visualizer'): ns3::PyViz::PacketSample::PacketSample() [constructor]
cls.add_constructor([])
## pyviz.h (module 'visualizer'): ns3::PyViz::PacketSample::PacketSample(ns3::PyViz::PacketSample const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PyViz::PacketSample const &', 'arg0')])
## pyviz.h (module 'visualizer'): ns3::PyViz::PacketSample::device [variable]
cls.add_instance_attribute('device', 'ns3::Ptr< ns3::NetDevice >', is_const=False)
## pyviz.h (module 'visualizer'): ns3::PyViz::PacketSample::packet [variable]
cls.add_instance_attribute('packet', 'ns3::Ptr< ns3::Packet >', is_const=False)
## pyviz.h (module 'visualizer'): ns3::PyViz::PacketSample::time [variable]
cls.add_instance_attribute('time', 'ns3::Time', is_const=False)
return
def register_Ns3PyVizRxPacketSample_methods(root_module, cls):
## pyviz.h (module 'visualizer'): ns3::PyViz::RxPacketSample::RxPacketSample() [constructor]
cls.add_constructor([])
## pyviz.h (module 'visualizer'): ns3::PyViz::RxPacketSample::RxPacketSample(ns3::PyViz::RxPacketSample const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PyViz::RxPacketSample const &', 'arg0')])
## pyviz.h (module 'visualizer'): ns3::PyViz::RxPacketSample::from [variable]
cls.add_instance_attribute('from', 'ns3::Mac48Address', is_const=False)
return
def register_Ns3PyVizTransmissionSample_methods(root_module, cls):
## pyviz.h (module 'visualizer'): ns3::PyViz::TransmissionSample::TransmissionSample() [constructor]
cls.add_constructor([])
## pyviz.h (module 'visualizer'): ns3::PyViz::TransmissionSample::TransmissionSample(ns3::PyViz::TransmissionSample const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PyViz::TransmissionSample const &', 'arg0')])
## pyviz.h (module 'visualizer'): ns3::PyViz::TransmissionSample::bytes [variable]
cls.add_instance_attribute('bytes', 'uint32_t', is_const=False)
## pyviz.h (module 'visualizer'): ns3::PyViz::TransmissionSample::channel [variable]
cls.add_instance_attribute('channel', 'ns3::Ptr< ns3::Channel >', is_const=False)
## pyviz.h (module 'visualizer'): ns3::PyViz::TransmissionSample::receiver [variable]
cls.add_instance_attribute('receiver', 'ns3::Ptr< ns3::Node >', is_const=False)
## pyviz.h (module 'visualizer'): ns3::PyViz::TransmissionSample::transmitter [variable]
cls.add_instance_attribute('transmitter', 'ns3::Ptr< ns3::Node >', is_const=False)
return
def register_Ns3PyVizTxPacketSample_methods(root_module, cls):
## pyviz.h (module 'visualizer'): ns3::PyViz::TxPacketSample::TxPacketSample() [constructor]
cls.add_constructor([])
## pyviz.h (module 'visualizer'): ns3::PyViz::TxPacketSample::TxPacketSample(ns3::PyViz::TxPacketSample const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PyViz::TxPacketSample const &', 'arg0')])
## pyviz.h (module 'visualizer'): ns3::PyViz::TxPacketSample::to [variable]
cls.add_instance_attribute('to', 'ns3::Mac48Address', is_const=False)
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 & time) [member function]
cls.add_method('Stop',
'void',
[param('ns3::Time const &', 'time')],
is_static=True)
return
def register_Ns3Tag_methods(root_module, cls):
## tag.h (module 'network'): ns3::Tag::Tag() [constructor]
cls.add_constructor([])
## tag.h (module 'network'): ns3::Tag::Tag(ns3::Tag const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Tag const &', 'arg0')])
## tag.h (module 'network'): void ns3::Tag::Deserialize(ns3::TagBuffer i) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_pure_virtual=True, is_virtual=True)
## tag.h (module 'network'): uint32_t ns3::Tag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## tag.h (module 'network'): static ns3::TypeId ns3::Tag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## tag.h (module 'network'): void ns3::Tag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## tag.h (module 'network'): void ns3::Tag::Serialize(ns3::TagBuffer i) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3TagBuffer_methods(root_module, cls):
## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(ns3::TagBuffer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TagBuffer const &', 'arg0')])
## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(uint8_t * start, uint8_t * end) [constructor]
cls.add_constructor([param('uint8_t *', 'start'), param('uint8_t *', 'end')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::CopyFrom(ns3::TagBuffer o) [member function]
cls.add_method('CopyFrom',
'void',
[param('ns3::TagBuffer', 'o')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::Read(uint8_t * buffer, uint32_t size) [member function]
cls.add_method('Read',
'void',
[param('uint8_t *', 'buffer'), param('uint32_t', 'size')])
## tag-buffer.h (module 'network'): double ns3::TagBuffer::ReadDouble() [member function]
cls.add_method('ReadDouble',
'double',
[])
## tag-buffer.h (module 'network'): uint16_t ns3::TagBuffer::ReadU16() [member function]
cls.add_method('ReadU16',
'uint16_t',
[])
## tag-buffer.h (module 'network'): uint32_t ns3::TagBuffer::ReadU32() [member function]
cls.add_method('ReadU32',
'uint32_t',
[])
## tag-buffer.h (module 'network'): uint64_t ns3::TagBuffer::ReadU64() [member function]
cls.add_method('ReadU64',
'uint64_t',
[])
## tag-buffer.h (module 'network'): uint8_t ns3::TagBuffer::ReadU8() [member function]
cls.add_method('ReadU8',
'uint8_t',
[])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::TrimAtEnd(uint32_t trim) [member function]
cls.add_method('TrimAtEnd',
'void',
[param('uint32_t', 'trim')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::Write(uint8_t const * buffer, uint32_t size) [member function]
cls.add_method('Write',
'void',
[param('uint8_t const *', 'buffer'), param('uint32_t', 'size')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteDouble(double v) [member function]
cls.add_method('WriteDouble',
'void',
[param('double', 'v')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU16(uint16_t data) [member function]
cls.add_method('WriteU16',
'void',
[param('uint16_t', 'data')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU32(uint32_t data) [member function]
cls.add_method('WriteU32',
'void',
[param('uint32_t', 'data')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU64(uint64_t v) [member function]
cls.add_method('WriteU64',
'void',
[param('uint64_t', 'v')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU8(uint8_t v) [member function]
cls.add_method('WriteU8',
'void',
[param('uint8_t', 'v')])
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')])
## 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'): 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'): 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::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_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('long long unsigned int const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', '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 &', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', '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 &', 'right'))
cls.add_inplace_numeric_operator('+=', param('ns3::int64x64_t const &', 'right'))
cls.add_inplace_numeric_operator('-=', param('ns3::int64x64_t const &', 'right'))
cls.add_inplace_numeric_operator('/=', param('ns3::int64x64_t const &', '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(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')])
return
def register_Ns3Chunk_methods(root_module, cls):
## chunk.h (module 'network'): ns3::Chunk::Chunk() [constructor]
cls.add_constructor([])
## chunk.h (module 'network'): ns3::Chunk::Chunk(ns3::Chunk const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Chunk const &', 'arg0')])
## chunk.h (module 'network'): uint32_t ns3::Chunk::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_pure_virtual=True, is_virtual=True)
## chunk.h (module 'network'): static ns3::TypeId ns3::Chunk::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## chunk.h (module 'network'): void ns3::Chunk::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3Header_methods(root_module, cls):
cls.add_output_stream_operator()
## header.h (module 'network'): ns3::Header::Header() [constructor]
cls.add_constructor([])
## header.h (module 'network'): ns3::Header::Header(ns3::Header const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Header const &', 'arg0')])
## header.h (module 'network'): uint32_t ns3::Header::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_pure_virtual=True, is_virtual=True)
## header.h (module 'network'): uint32_t ns3::Header::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## header.h (module 'network'): static ns3::TypeId ns3::Header::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## header.h (module 'network'): void ns3::Header::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## header.h (module 'network'): void ns3::Header::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3Ipv4Header_methods(root_module, cls):
## ipv4-header.h (module 'internet'): ns3::Ipv4Header::Ipv4Header(ns3::Ipv4Header const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4Header const &', 'arg0')])
## ipv4-header.h (module 'internet'): ns3::Ipv4Header::Ipv4Header() [constructor]
cls.add_constructor([])
## ipv4-header.h (module 'internet'): uint32_t ns3::Ipv4Header::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## ipv4-header.h (module 'internet'): std::string ns3::Ipv4Header::DscpTypeToString(ns3::Ipv4Header::DscpType dscp) const [member function]
cls.add_method('DscpTypeToString',
'std::string',
[param('ns3::Ipv4Header::DscpType', 'dscp')],
is_const=True)
## ipv4-header.h (module 'internet'): std::string ns3::Ipv4Header::EcnTypeToString(ns3::Ipv4Header::EcnType ecn) const [member function]
cls.add_method('EcnTypeToString',
'std::string',
[param('ns3::Ipv4Header::EcnType', 'ecn')],
is_const=True)
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::EnableChecksum() [member function]
cls.add_method('EnableChecksum',
'void',
[])
## ipv4-header.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Header::GetDestination() const [member function]
cls.add_method('GetDestination',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv4-header.h (module 'internet'): ns3::Ipv4Header::DscpType ns3::Ipv4Header::GetDscp() const [member function]
cls.add_method('GetDscp',
'ns3::Ipv4Header::DscpType',
[],
is_const=True)
## ipv4-header.h (module 'internet'): ns3::Ipv4Header::EcnType ns3::Ipv4Header::GetEcn() const [member function]
cls.add_method('GetEcn',
'ns3::Ipv4Header::EcnType',
[],
is_const=True)
## ipv4-header.h (module 'internet'): uint16_t ns3::Ipv4Header::GetFragmentOffset() const [member function]
cls.add_method('GetFragmentOffset',
'uint16_t',
[],
is_const=True)
## ipv4-header.h (module 'internet'): uint16_t ns3::Ipv4Header::GetIdentification() const [member function]
cls.add_method('GetIdentification',
'uint16_t',
[],
is_const=True)
## ipv4-header.h (module 'internet'): ns3::TypeId ns3::Ipv4Header::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## ipv4-header.h (module 'internet'): uint16_t ns3::Ipv4Header::GetPayloadSize() const [member function]
cls.add_method('GetPayloadSize',
'uint16_t',
[],
is_const=True)
## ipv4-header.h (module 'internet'): uint8_t ns3::Ipv4Header::GetProtocol() const [member function]
cls.add_method('GetProtocol',
'uint8_t',
[],
is_const=True)
## ipv4-header.h (module 'internet'): uint32_t ns3::Ipv4Header::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## ipv4-header.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Header::GetSource() const [member function]
cls.add_method('GetSource',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv4-header.h (module 'internet'): uint8_t ns3::Ipv4Header::GetTos() const [member function]
cls.add_method('GetTos',
'uint8_t',
[],
is_const=True)
## ipv4-header.h (module 'internet'): uint8_t ns3::Ipv4Header::GetTtl() const [member function]
cls.add_method('GetTtl',
'uint8_t',
[],
is_const=True)
## ipv4-header.h (module 'internet'): static ns3::TypeId ns3::Ipv4Header::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## ipv4-header.h (module 'internet'): bool ns3::Ipv4Header::IsChecksumOk() const [member function]
cls.add_method('IsChecksumOk',
'bool',
[],
is_const=True)
## ipv4-header.h (module 'internet'): bool ns3::Ipv4Header::IsDontFragment() const [member function]
cls.add_method('IsDontFragment',
'bool',
[],
is_const=True)
## ipv4-header.h (module 'internet'): bool ns3::Ipv4Header::IsLastFragment() const [member function]
cls.add_method('IsLastFragment',
'bool',
[],
is_const=True)
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetDestination(ns3::Ipv4Address destination) [member function]
cls.add_method('SetDestination',
'void',
[param('ns3::Ipv4Address', 'destination')])
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetDontFragment() [member function]
cls.add_method('SetDontFragment',
'void',
[])
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetDscp(ns3::Ipv4Header::DscpType dscp) [member function]
cls.add_method('SetDscp',
'void',
[param('ns3::Ipv4Header::DscpType', 'dscp')])
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetEcn(ns3::Ipv4Header::EcnType ecn) [member function]
cls.add_method('SetEcn',
'void',
[param('ns3::Ipv4Header::EcnType', 'ecn')])
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetFragmentOffset(uint16_t offsetBytes) [member function]
cls.add_method('SetFragmentOffset',
'void',
[param('uint16_t', 'offsetBytes')])
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetIdentification(uint16_t identification) [member function]
cls.add_method('SetIdentification',
'void',
[param('uint16_t', 'identification')])
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetLastFragment() [member function]
cls.add_method('SetLastFragment',
'void',
[])
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetMayFragment() [member function]
cls.add_method('SetMayFragment',
'void',
[])
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetMoreFragments() [member function]
cls.add_method('SetMoreFragments',
'void',
[])
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetPayloadSize(uint16_t size) [member function]
cls.add_method('SetPayloadSize',
'void',
[param('uint16_t', 'size')])
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetProtocol(uint8_t num) [member function]
cls.add_method('SetProtocol',
'void',
[param('uint8_t', 'num')])
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetSource(ns3::Ipv4Address source) [member function]
cls.add_method('SetSource',
'void',
[param('ns3::Ipv4Address', 'source')])
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetTos(uint8_t tos) [member function]
cls.add_method('SetTos',
'void',
[param('uint8_t', 'tos')])
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetTtl(uint8_t ttl) [member function]
cls.add_method('SetTtl',
'void',
[param('uint8_t', 'ttl')])
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'): 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_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__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__Ns3Ipv4MulticastRoute_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4MulticastRoute__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter< ns3::Ipv4MulticastRoute > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3Ipv4Route_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4Route__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter< ns3::Ipv4Route > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::SimpleRefCount(ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter< ns3::NixVector > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3OutputStreamWrapper_Ns3Empty_Ns3DefaultDeleter__lt__ns3OutputStreamWrapper__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >::SimpleRefCount(ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter< ns3::OutputStreamWrapper > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter< ns3::Packet > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::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_Ns3Socket_methods(root_module, cls):
## socket.h (module 'network'): ns3::Socket::Socket(ns3::Socket const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Socket const &', 'arg0')])
## socket.h (module 'network'): ns3::Socket::Socket() [constructor]
cls.add_constructor([])
## socket.h (module 'network'): int ns3::Socket::Bind(ns3::Address const & address) [member function]
cls.add_method('Bind',
'int',
[param('ns3::Address const &', 'address')],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): int ns3::Socket::Bind() [member function]
cls.add_method('Bind',
'int',
[],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): int ns3::Socket::Bind6() [member function]
cls.add_method('Bind6',
'int',
[],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): void ns3::Socket::BindToNetDevice(ns3::Ptr<ns3::NetDevice> netdevice) [member function]
cls.add_method('BindToNetDevice',
'void',
[param('ns3::Ptr< ns3::NetDevice >', 'netdevice')],
is_virtual=True)
## socket.h (module 'network'): int ns3::Socket::Close() [member function]
cls.add_method('Close',
'int',
[],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): int ns3::Socket::Connect(ns3::Address const & address) [member function]
cls.add_method('Connect',
'int',
[param('ns3::Address const &', 'address')],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): static ns3::Ptr<ns3::Socket> ns3::Socket::CreateSocket(ns3::Ptr<ns3::Node> node, ns3::TypeId tid) [member function]
cls.add_method('CreateSocket',
'ns3::Ptr< ns3::Socket >',
[param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::TypeId', 'tid')],
is_static=True)
## socket.h (module 'network'): bool ns3::Socket::GetAllowBroadcast() const [member function]
cls.add_method('GetAllowBroadcast',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## socket.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Socket::GetBoundNetDevice() [member function]
cls.add_method('GetBoundNetDevice',
'ns3::Ptr< ns3::NetDevice >',
[])
## socket.h (module 'network'): ns3::Socket::SocketErrno ns3::Socket::GetErrno() const [member function]
cls.add_method('GetErrno',
'ns3::Socket::SocketErrno',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## socket.h (module 'network'): uint8_t ns3::Socket::GetIpTos() const [member function]
cls.add_method('GetIpTos',
'uint8_t',
[],
is_const=True)
## socket.h (module 'network'): uint8_t ns3::Socket::GetIpTtl() const [member function]
cls.add_method('GetIpTtl',
'uint8_t',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): uint8_t ns3::Socket::GetIpv6HopLimit() const [member function]
cls.add_method('GetIpv6HopLimit',
'uint8_t',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): uint8_t ns3::Socket::GetIpv6Tclass() const [member function]
cls.add_method('GetIpv6Tclass',
'uint8_t',
[],
is_const=True)
## socket.h (module 'network'): ns3::Ptr<ns3::Node> ns3::Socket::GetNode() const [member function]
cls.add_method('GetNode',
'ns3::Ptr< ns3::Node >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## socket.h (module 'network'): uint32_t ns3::Socket::GetRxAvailable() const [member function]
cls.add_method('GetRxAvailable',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## socket.h (module 'network'): int ns3::Socket::GetSockName(ns3::Address & address) const [member function]
cls.add_method('GetSockName',
'int',
[param('ns3::Address &', 'address')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## socket.h (module 'network'): ns3::Socket::SocketType ns3::Socket::GetSocketType() const [member function]
cls.add_method('GetSocketType',
'ns3::Socket::SocketType',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## socket.h (module 'network'): uint32_t ns3::Socket::GetTxAvailable() const [member function]
cls.add_method('GetTxAvailable',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## socket.h (module 'network'): static ns3::TypeId ns3::Socket::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## socket.h (module 'network'): bool ns3::Socket::IsIpRecvTos() const [member function]
cls.add_method('IsIpRecvTos',
'bool',
[],
is_const=True)
## socket.h (module 'network'): bool ns3::Socket::IsIpRecvTtl() const [member function]
cls.add_method('IsIpRecvTtl',
'bool',
[],
is_const=True)
## socket.h (module 'network'): bool ns3::Socket::IsIpv6RecvHopLimit() const [member function]
cls.add_method('IsIpv6RecvHopLimit',
'bool',
[],
is_const=True)
## socket.h (module 'network'): bool ns3::Socket::IsIpv6RecvTclass() const [member function]
cls.add_method('IsIpv6RecvTclass',
'bool',
[],
is_const=True)
## socket.h (module 'network'): bool ns3::Socket::IsRecvPktInfo() const [member function]
cls.add_method('IsRecvPktInfo',
'bool',
[],
is_const=True)
## socket.h (module 'network'): int ns3::Socket::Listen() [member function]
cls.add_method('Listen',
'int',
[],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::Recv(uint32_t maxSize, uint32_t flags) [member function]
cls.add_method('Recv',
'ns3::Ptr< ns3::Packet >',
[param('uint32_t', 'maxSize'), param('uint32_t', 'flags')],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::Recv() [member function]
cls.add_method('Recv',
'ns3::Ptr< ns3::Packet >',
[])
## socket.h (module 'network'): int ns3::Socket::Recv(uint8_t * buf, uint32_t size, uint32_t flags) [member function]
cls.add_method('Recv',
'int',
[param('uint8_t *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags')])
## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::RecvFrom(uint32_t maxSize, uint32_t flags, ns3::Address & fromAddress) [member function]
cls.add_method('RecvFrom',
'ns3::Ptr< ns3::Packet >',
[param('uint32_t', 'maxSize'), param('uint32_t', 'flags'), param('ns3::Address &', 'fromAddress')],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::RecvFrom(ns3::Address & fromAddress) [member function]
cls.add_method('RecvFrom',
'ns3::Ptr< ns3::Packet >',
[param('ns3::Address &', 'fromAddress')])
## socket.h (module 'network'): int ns3::Socket::RecvFrom(uint8_t * buf, uint32_t size, uint32_t flags, ns3::Address & fromAddress) [member function]
cls.add_method('RecvFrom',
'int',
[param('uint8_t *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags'), param('ns3::Address &', 'fromAddress')])
## socket.h (module 'network'): int ns3::Socket::Send(ns3::Ptr<ns3::Packet> p, uint32_t flags) [member function]
cls.add_method('Send',
'int',
[param('ns3::Ptr< ns3::Packet >', 'p'), param('uint32_t', 'flags')],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): int ns3::Socket::Send(ns3::Ptr<ns3::Packet> p) [member function]
cls.add_method('Send',
'int',
[param('ns3::Ptr< ns3::Packet >', 'p')])
## socket.h (module 'network'): int ns3::Socket::Send(uint8_t const * buf, uint32_t size, uint32_t flags) [member function]
cls.add_method('Send',
'int',
[param('uint8_t const *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags')])
## socket.h (module 'network'): int ns3::Socket::SendTo(ns3::Ptr<ns3::Packet> p, uint32_t flags, ns3::Address const & toAddress) [member function]
cls.add_method('SendTo',
'int',
[param('ns3::Ptr< ns3::Packet >', 'p'), param('uint32_t', 'flags'), param('ns3::Address const &', 'toAddress')],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): int ns3::Socket::SendTo(uint8_t const * buf, uint32_t size, uint32_t flags, ns3::Address const & address) [member function]
cls.add_method('SendTo',
'int',
[param('uint8_t const *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags'), param('ns3::Address const &', 'address')])
## socket.h (module 'network'): void ns3::Socket::SetAcceptCallback(ns3::Callback<bool, ns3::Ptr<ns3::Socket>, ns3::Address const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> connectionRequest, ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::Address const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> newConnectionCreated) [member function]
cls.add_method('SetAcceptCallback',
'void',
[param('ns3::Callback< bool, ns3::Ptr< ns3::Socket >, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'connectionRequest'), param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'newConnectionCreated')])
## socket.h (module 'network'): bool ns3::Socket::SetAllowBroadcast(bool allowBroadcast) [member function]
cls.add_method('SetAllowBroadcast',
'bool',
[param('bool', 'allowBroadcast')],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): void ns3::Socket::SetCloseCallbacks(ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> normalClose, ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> errorClose) [member function]
cls.add_method('SetCloseCallbacks',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'normalClose'), param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'errorClose')])
## socket.h (module 'network'): void ns3::Socket::SetConnectCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> connectionSucceeded, ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> connectionFailed) [member function]
cls.add_method('SetConnectCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'connectionSucceeded'), param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'connectionFailed')])
## socket.h (module 'network'): void ns3::Socket::SetDataSentCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> dataSent) [member function]
cls.add_method('SetDataSentCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'dataSent')])
## socket.h (module 'network'): void ns3::Socket::SetIpRecvTos(bool ipv4RecvTos) [member function]
cls.add_method('SetIpRecvTos',
'void',
[param('bool', 'ipv4RecvTos')])
## socket.h (module 'network'): void ns3::Socket::SetIpRecvTtl(bool ipv4RecvTtl) [member function]
cls.add_method('SetIpRecvTtl',
'void',
[param('bool', 'ipv4RecvTtl')])
## socket.h (module 'network'): void ns3::Socket::SetIpTos(uint8_t ipTos) [member function]
cls.add_method('SetIpTos',
'void',
[param('uint8_t', 'ipTos')])
## socket.h (module 'network'): void ns3::Socket::SetIpTtl(uint8_t ipTtl) [member function]
cls.add_method('SetIpTtl',
'void',
[param('uint8_t', 'ipTtl')],
is_virtual=True)
## socket.h (module 'network'): void ns3::Socket::SetIpv6HopLimit(uint8_t ipHopLimit) [member function]
cls.add_method('SetIpv6HopLimit',
'void',
[param('uint8_t', 'ipHopLimit')],
is_virtual=True)
## socket.h (module 'network'): void ns3::Socket::SetIpv6RecvHopLimit(bool ipv6RecvHopLimit) [member function]
cls.add_method('SetIpv6RecvHopLimit',
'void',
[param('bool', 'ipv6RecvHopLimit')])
## socket.h (module 'network'): void ns3::Socket::SetIpv6RecvTclass(bool ipv6RecvTclass) [member function]
cls.add_method('SetIpv6RecvTclass',
'void',
[param('bool', 'ipv6RecvTclass')])
## socket.h (module 'network'): void ns3::Socket::SetIpv6Tclass(int ipTclass) [member function]
cls.add_method('SetIpv6Tclass',
'void',
[param('int', 'ipTclass')])
## socket.h (module 'network'): void ns3::Socket::SetRecvCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> arg0) [member function]
cls.add_method('SetRecvCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'arg0')])
## socket.h (module 'network'): void ns3::Socket::SetRecvPktInfo(bool flag) [member function]
cls.add_method('SetRecvPktInfo',
'void',
[param('bool', 'flag')])
## socket.h (module 'network'): void ns3::Socket::SetSendCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> sendCb) [member function]
cls.add_method('SetSendCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'sendCb')])
## socket.h (module 'network'): int ns3::Socket::ShutdownRecv() [member function]
cls.add_method('ShutdownRecv',
'int',
[],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): int ns3::Socket::ShutdownSend() [member function]
cls.add_method('ShutdownSend',
'int',
[],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): void ns3::Socket::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## socket.h (module 'network'): bool ns3::Socket::IsManualIpTos() const [member function]
cls.add_method('IsManualIpTos',
'bool',
[],
is_const=True, visibility='protected')
## socket.h (module 'network'): bool ns3::Socket::IsManualIpTtl() const [member function]
cls.add_method('IsManualIpTtl',
'bool',
[],
is_const=True, visibility='protected')
## socket.h (module 'network'): bool ns3::Socket::IsManualIpv6HopLimit() const [member function]
cls.add_method('IsManualIpv6HopLimit',
'bool',
[],
is_const=True, visibility='protected')
## socket.h (module 'network'): bool ns3::Socket::IsManualIpv6Tclass() const [member function]
cls.add_method('IsManualIpv6Tclass',
'bool',
[],
is_const=True, visibility='protected')
## socket.h (module 'network'): void ns3::Socket::NotifyConnectionFailed() [member function]
cls.add_method('NotifyConnectionFailed',
'void',
[],
visibility='protected')
## socket.h (module 'network'): bool ns3::Socket::NotifyConnectionRequest(ns3::Address const & from) [member function]
cls.add_method('NotifyConnectionRequest',
'bool',
[param('ns3::Address const &', 'from')],
visibility='protected')
## socket.h (module 'network'): void ns3::Socket::NotifyConnectionSucceeded() [member function]
cls.add_method('NotifyConnectionSucceeded',
'void',
[],
visibility='protected')
## socket.h (module 'network'): void ns3::Socket::NotifyDataRecv() [member function]
cls.add_method('NotifyDataRecv',
'void',
[],
visibility='protected')
## socket.h (module 'network'): void ns3::Socket::NotifyDataSent(uint32_t size) [member function]
cls.add_method('NotifyDataSent',
'void',
[param('uint32_t', 'size')],
visibility='protected')
## socket.h (module 'network'): void ns3::Socket::NotifyErrorClose() [member function]
cls.add_method('NotifyErrorClose',
'void',
[],
visibility='protected')
## socket.h (module 'network'): void ns3::Socket::NotifyNewConnectionCreated(ns3::Ptr<ns3::Socket> socket, ns3::Address const & from) [member function]
cls.add_method('NotifyNewConnectionCreated',
'void',
[param('ns3::Ptr< ns3::Socket >', 'socket'), param('ns3::Address const &', 'from')],
visibility='protected')
## socket.h (module 'network'): void ns3::Socket::NotifyNormalClose() [member function]
cls.add_method('NotifyNormalClose',
'void',
[],
visibility='protected')
## socket.h (module 'network'): void ns3::Socket::NotifySend(uint32_t spaceAvailable) [member function]
cls.add_method('NotifySend',
'void',
[param('uint32_t', 'spaceAvailable')],
visibility='protected')
return
def register_Ns3SocketAddressTag_methods(root_module, cls):
## socket.h (module 'network'): ns3::SocketAddressTag::SocketAddressTag(ns3::SocketAddressTag const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SocketAddressTag const &', 'arg0')])
## socket.h (module 'network'): ns3::SocketAddressTag::SocketAddressTag() [constructor]
cls.add_constructor([])
## socket.h (module 'network'): void ns3::SocketAddressTag::Deserialize(ns3::TagBuffer i) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_virtual=True)
## socket.h (module 'network'): ns3::Address ns3::SocketAddressTag::GetAddress() const [member function]
cls.add_method('GetAddress',
'ns3::Address',
[],
is_const=True)
## socket.h (module 'network'): ns3::TypeId ns3::SocketAddressTag::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): uint32_t ns3::SocketAddressTag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): static ns3::TypeId ns3::SocketAddressTag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## socket.h (module 'network'): void ns3::SocketAddressTag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## socket.h (module 'network'): void ns3::SocketAddressTag::Serialize(ns3::TagBuffer i) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_const=True, is_virtual=True)
## socket.h (module 'network'): void ns3::SocketAddressTag::SetAddress(ns3::Address addr) [member function]
cls.add_method('SetAddress',
'void',
[param('ns3::Address', 'addr')])
return
def register_Ns3SocketIpTosTag_methods(root_module, cls):
## socket.h (module 'network'): ns3::SocketIpTosTag::SocketIpTosTag(ns3::SocketIpTosTag const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SocketIpTosTag const &', 'arg0')])
## socket.h (module 'network'): ns3::SocketIpTosTag::SocketIpTosTag() [constructor]
cls.add_constructor([])
## socket.h (module 'network'): void ns3::SocketIpTosTag::Deserialize(ns3::TagBuffer i) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_virtual=True)
## socket.h (module 'network'): ns3::TypeId ns3::SocketIpTosTag::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): uint32_t ns3::SocketIpTosTag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): uint8_t ns3::SocketIpTosTag::GetTos() const [member function]
cls.add_method('GetTos',
'uint8_t',
[],
is_const=True)
## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpTosTag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## socket.h (module 'network'): void ns3::SocketIpTosTag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## socket.h (module 'network'): void ns3::SocketIpTosTag::Serialize(ns3::TagBuffer i) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_const=True, is_virtual=True)
## socket.h (module 'network'): void ns3::SocketIpTosTag::SetTos(uint8_t tos) [member function]
cls.add_method('SetTos',
'void',
[param('uint8_t', 'tos')])
return
def register_Ns3SocketIpTtlTag_methods(root_module, cls):
## socket.h (module 'network'): ns3::SocketIpTtlTag::SocketIpTtlTag(ns3::SocketIpTtlTag const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SocketIpTtlTag const &', 'arg0')])
## socket.h (module 'network'): ns3::SocketIpTtlTag::SocketIpTtlTag() [constructor]
cls.add_constructor([])
## socket.h (module 'network'): void ns3::SocketIpTtlTag::Deserialize(ns3::TagBuffer i) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_virtual=True)
## socket.h (module 'network'): ns3::TypeId ns3::SocketIpTtlTag::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): uint32_t ns3::SocketIpTtlTag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): uint8_t ns3::SocketIpTtlTag::GetTtl() const [member function]
cls.add_method('GetTtl',
'uint8_t',
[],
is_const=True)
## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpTtlTag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## socket.h (module 'network'): void ns3::SocketIpTtlTag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## socket.h (module 'network'): void ns3::SocketIpTtlTag::Serialize(ns3::TagBuffer i) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_const=True, is_virtual=True)
## socket.h (module 'network'): void ns3::SocketIpTtlTag::SetTtl(uint8_t ttl) [member function]
cls.add_method('SetTtl',
'void',
[param('uint8_t', 'ttl')])
return
def register_Ns3SocketIpv6HopLimitTag_methods(root_module, cls):
## socket.h (module 'network'): ns3::SocketIpv6HopLimitTag::SocketIpv6HopLimitTag(ns3::SocketIpv6HopLimitTag const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SocketIpv6HopLimitTag const &', 'arg0')])
## socket.h (module 'network'): ns3::SocketIpv6HopLimitTag::SocketIpv6HopLimitTag() [constructor]
cls.add_constructor([])
## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::Deserialize(ns3::TagBuffer i) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_virtual=True)
## socket.h (module 'network'): uint8_t ns3::SocketIpv6HopLimitTag::GetHopLimit() const [member function]
cls.add_method('GetHopLimit',
'uint8_t',
[],
is_const=True)
## socket.h (module 'network'): ns3::TypeId ns3::SocketIpv6HopLimitTag::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): uint32_t ns3::SocketIpv6HopLimitTag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpv6HopLimitTag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::Serialize(ns3::TagBuffer i) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_const=True, is_virtual=True)
## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::SetHopLimit(uint8_t hopLimit) [member function]
cls.add_method('SetHopLimit',
'void',
[param('uint8_t', 'hopLimit')])
return
def register_Ns3SocketIpv6TclassTag_methods(root_module, cls):
## socket.h (module 'network'): ns3::SocketIpv6TclassTag::SocketIpv6TclassTag(ns3::SocketIpv6TclassTag const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SocketIpv6TclassTag const &', 'arg0')])
## socket.h (module 'network'): ns3::SocketIpv6TclassTag::SocketIpv6TclassTag() [constructor]
cls.add_constructor([])
## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::Deserialize(ns3::TagBuffer i) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_virtual=True)
## socket.h (module 'network'): ns3::TypeId ns3::SocketIpv6TclassTag::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): uint32_t ns3::SocketIpv6TclassTag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): uint8_t ns3::SocketIpv6TclassTag::GetTclass() const [member function]
cls.add_method('GetTclass',
'uint8_t',
[],
is_const=True)
## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpv6TclassTag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::Serialize(ns3::TagBuffer i) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_const=True, is_virtual=True)
## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::SetTclass(uint8_t tclass) [member function]
cls.add_method('SetTclass',
'void',
[param('uint8_t', 'tclass')])
return
def register_Ns3SocketSetDontFragmentTag_methods(root_module, cls):
## socket.h (module 'network'): ns3::SocketSetDontFragmentTag::SocketSetDontFragmentTag(ns3::SocketSetDontFragmentTag const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SocketSetDontFragmentTag const &', 'arg0')])
## socket.h (module 'network'): ns3::SocketSetDontFragmentTag::SocketSetDontFragmentTag() [constructor]
cls.add_constructor([])
## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Deserialize(ns3::TagBuffer i) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_virtual=True)
## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Disable() [member function]
cls.add_method('Disable',
'void',
[])
## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Enable() [member function]
cls.add_method('Enable',
'void',
[])
## socket.h (module 'network'): ns3::TypeId ns3::SocketSetDontFragmentTag::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): uint32_t ns3::SocketSetDontFragmentTag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): static ns3::TypeId ns3::SocketSetDontFragmentTag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## socket.h (module 'network'): bool ns3::SocketSetDontFragmentTag::IsEnabled() const [member function]
cls.add_method('IsEnabled',
'bool',
[],
is_const=True)
## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Serialize(ns3::TagBuffer i) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_const=True, is_virtual=True)
return
def register_Ns3Time_methods(root_module, cls):
cls.add_binary_numeric_operator('+', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', '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 &', 'right'))
cls.add_inplace_numeric_operator('-=', param('ns3::Time const &', '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(std::string const & s) [constructor]
cls.add_constructor([param('std::string const &', 's')])
## nstime.h (module 'core'): ns3::Time::Time(ns3::int64x64_t const & value) [constructor]
cls.add_constructor([param('ns3::int64x64_t const &', 'value')])
## 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 & from, ns3::Time::Unit timeUnit) [member function]
cls.add_method('From',
'ns3::Time',
[param('ns3::int64x64_t const &', 'from'), param('ns3::Time::Unit', 'timeUnit')],
is_static=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::FromDouble(double value, ns3::Time::Unit timeUnit) [member function]
cls.add_method('FromDouble',
'ns3::Time',
[param('double', 'value'), param('ns3::Time::Unit', 'timeUnit')],
is_static=True)
## nstime.h (module 'core'): static ns3::Time ns3::Time::FromInteger(uint64_t value, ns3::Time::Unit timeUnit) [member function]
cls.add_method('FromInteger',
'ns3::Time',
[param('uint64_t', 'value'), param('ns3::Time::Unit', 'timeUnit')],
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 timeUnit) const [member function]
cls.add_method('To',
'ns3::int64x64_t',
[param('ns3::Time::Unit', 'timeUnit')],
is_const=True)
## nstime.h (module 'core'): double ns3::Time::ToDouble(ns3::Time::Unit timeUnit) const [member function]
cls.add_method('ToDouble',
'double',
[param('ns3::Time::Unit', 'timeUnit')],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::ToInteger(ns3::Time::Unit timeUnit) const [member function]
cls.add_method('ToInteger',
'int64_t',
[param('ns3::Time::Unit', 'timeUnit')],
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_Ns3Trailer_methods(root_module, cls):
cls.add_output_stream_operator()
## trailer.h (module 'network'): ns3::Trailer::Trailer() [constructor]
cls.add_constructor([])
## trailer.h (module 'network'): ns3::Trailer::Trailer(ns3::Trailer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Trailer const &', 'arg0')])
## trailer.h (module 'network'): uint32_t ns3::Trailer::Deserialize(ns3::Buffer::Iterator end) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'end')],
is_pure_virtual=True, is_virtual=True)
## trailer.h (module 'network'): uint32_t ns3::Trailer::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## trailer.h (module 'network'): static ns3::TypeId ns3::Trailer::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## trailer.h (module 'network'): void ns3::Trailer::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## trailer.h (module 'network'): void ns3::Trailer::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_pure_virtual=True, is_const=True, 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_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'): 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)
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_Ns3Channel_methods(root_module, cls):
## channel.h (module 'network'): ns3::Channel::Channel(ns3::Channel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Channel const &', 'arg0')])
## channel.h (module 'network'): ns3::Channel::Channel() [constructor]
cls.add_constructor([])
## channel.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Channel::GetDevice(uint32_t i) const [member function]
cls.add_method('GetDevice',
'ns3::Ptr< ns3::NetDevice >',
[param('uint32_t', 'i')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## channel.h (module 'network'): uint32_t ns3::Channel::GetId() const [member function]
cls.add_method('GetId',
'uint32_t',
[],
is_const=True)
## channel.h (module 'network'): uint32_t ns3::Channel::GetNDevices() const [member function]
cls.add_method('GetNDevices',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## channel.h (module 'network'): static ns3::TypeId ns3::Channel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=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_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_Ns3Ipv4_methods(root_module, cls):
## ipv4.h (module 'internet'): ns3::Ipv4::Ipv4(ns3::Ipv4 const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4 const &', 'arg0')])
## ipv4.h (module 'internet'): ns3::Ipv4::Ipv4() [constructor]
cls.add_constructor([])
## ipv4.h (module 'internet'): bool ns3::Ipv4::AddAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function]
cls.add_method('AddAddress',
'bool',
[param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): uint32_t ns3::Ipv4::AddInterface(ns3::Ptr<ns3::NetDevice> device) [member function]
cls.add_method('AddInterface',
'uint32_t',
[param('ns3::Ptr< ns3::NetDevice >', 'device')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): ns3::Ptr<ns3::Socket> ns3::Ipv4::CreateRawSocket() [member function]
cls.add_method('CreateRawSocket',
'ns3::Ptr< ns3::Socket >',
[],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): void ns3::Ipv4::DeleteRawSocket(ns3::Ptr<ns3::Socket> socket) [member function]
cls.add_method('DeleteRawSocket',
'void',
[param('ns3::Ptr< ns3::Socket >', 'socket')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): ns3::Ipv4InterfaceAddress ns3::Ipv4::GetAddress(uint32_t interface, uint32_t addressIndex) const [member function]
cls.add_method('GetAddress',
'ns3::Ipv4InterfaceAddress',
[param('uint32_t', 'interface'), param('uint32_t', 'addressIndex')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4.h (module 'internet'): int32_t ns3::Ipv4::GetInterfaceForAddress(ns3::Ipv4Address address) const [member function]
cls.add_method('GetInterfaceForAddress',
'int32_t',
[param('ns3::Ipv4Address', 'address')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4.h (module 'internet'): int32_t ns3::Ipv4::GetInterfaceForDevice(ns3::Ptr<const ns3::NetDevice> device) const [member function]
cls.add_method('GetInterfaceForDevice',
'int32_t',
[param('ns3::Ptr< ns3::NetDevice const >', 'device')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4.h (module 'internet'): int32_t ns3::Ipv4::GetInterfaceForPrefix(ns3::Ipv4Address address, ns3::Ipv4Mask mask) const [member function]
cls.add_method('GetInterfaceForPrefix',
'int32_t',
[param('ns3::Ipv4Address', 'address'), param('ns3::Ipv4Mask', 'mask')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4.h (module 'internet'): uint16_t ns3::Ipv4::GetMetric(uint32_t interface) const [member function]
cls.add_method('GetMetric',
'uint16_t',
[param('uint32_t', 'interface')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4.h (module 'internet'): uint16_t ns3::Ipv4::GetMtu(uint32_t interface) const [member function]
cls.add_method('GetMtu',
'uint16_t',
[param('uint32_t', 'interface')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4.h (module 'internet'): uint32_t ns3::Ipv4::GetNAddresses(uint32_t interface) const [member function]
cls.add_method('GetNAddresses',
'uint32_t',
[param('uint32_t', 'interface')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4.h (module 'internet'): uint32_t ns3::Ipv4::GetNInterfaces() const [member function]
cls.add_method('GetNInterfaces',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv4::GetNetDevice(uint32_t interface) [member function]
cls.add_method('GetNetDevice',
'ns3::Ptr< ns3::NetDevice >',
[param('uint32_t', 'interface')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): ns3::Ptr<ns3::IpL4Protocol> ns3::Ipv4::GetProtocol(int protocolNumber) const [member function]
cls.add_method('GetProtocol',
'ns3::Ptr< ns3::IpL4Protocol >',
[param('int', 'protocolNumber')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4.h (module 'internet'): ns3::Ptr<ns3::Ipv4RoutingProtocol> ns3::Ipv4::GetRoutingProtocol() const [member function]
cls.add_method('GetRoutingProtocol',
'ns3::Ptr< ns3::Ipv4RoutingProtocol >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4.h (module 'internet'): static ns3::TypeId ns3::Ipv4::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## ipv4.h (module 'internet'): void ns3::Ipv4::Insert(ns3::Ptr<ns3::IpL4Protocol> protocol) [member function]
cls.add_method('Insert',
'void',
[param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): bool ns3::Ipv4::IsDestinationAddress(ns3::Ipv4Address address, uint32_t iif) const [member function]
cls.add_method('IsDestinationAddress',
'bool',
[param('ns3::Ipv4Address', 'address'), param('uint32_t', 'iif')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4.h (module 'internet'): bool ns3::Ipv4::IsForwarding(uint32_t interface) const [member function]
cls.add_method('IsForwarding',
'bool',
[param('uint32_t', 'interface')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4.h (module 'internet'): bool ns3::Ipv4::IsUp(uint32_t interface) const [member function]
cls.add_method('IsUp',
'bool',
[param('uint32_t', 'interface')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4.h (module 'internet'): bool ns3::Ipv4::RemoveAddress(uint32_t interface, uint32_t addressIndex) [member function]
cls.add_method('RemoveAddress',
'bool',
[param('uint32_t', 'interface'), param('uint32_t', 'addressIndex')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): bool ns3::Ipv4::RemoveAddress(uint32_t interface, ns3::Ipv4Address address) [member function]
cls.add_method('RemoveAddress',
'bool',
[param('uint32_t', 'interface'), param('ns3::Ipv4Address', 'address')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4::SelectSourceAddress(ns3::Ptr<const ns3::NetDevice> device, ns3::Ipv4Address dst, ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e scope) [member function]
cls.add_method('SelectSourceAddress',
'ns3::Ipv4Address',
[param('ns3::Ptr< ns3::NetDevice const >', 'device'), param('ns3::Ipv4Address', 'dst'), param('ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e', 'scope')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): void ns3::Ipv4::Send(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Address source, ns3::Ipv4Address destination, uint8_t protocol, ns3::Ptr<ns3::Ipv4Route> route) [member function]
cls.add_method('Send',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Address', 'source'), param('ns3::Ipv4Address', 'destination'), param('uint8_t', 'protocol'), param('ns3::Ptr< ns3::Ipv4Route >', 'route')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): void ns3::Ipv4::SendWithHeader(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Header ipHeader, ns3::Ptr<ns3::Ipv4Route> route) [member function]
cls.add_method('SendWithHeader',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Header', 'ipHeader'), param('ns3::Ptr< ns3::Ipv4Route >', 'route')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): void ns3::Ipv4::SetDown(uint32_t interface) [member function]
cls.add_method('SetDown',
'void',
[param('uint32_t', 'interface')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): void ns3::Ipv4::SetForwarding(uint32_t interface, bool val) [member function]
cls.add_method('SetForwarding',
'void',
[param('uint32_t', 'interface'), param('bool', 'val')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): void ns3::Ipv4::SetMetric(uint32_t interface, uint16_t metric) [member function]
cls.add_method('SetMetric',
'void',
[param('uint32_t', 'interface'), param('uint16_t', 'metric')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): void ns3::Ipv4::SetRoutingProtocol(ns3::Ptr<ns3::Ipv4RoutingProtocol> routingProtocol) [member function]
cls.add_method('SetRoutingProtocol',
'void',
[param('ns3::Ptr< ns3::Ipv4RoutingProtocol >', 'routingProtocol')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): void ns3::Ipv4::SetUp(uint32_t interface) [member function]
cls.add_method('SetUp',
'void',
[param('uint32_t', 'interface')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): ns3::Ipv4::IF_ANY [variable]
cls.add_static_attribute('IF_ANY', 'uint32_t const', is_const=True)
## ipv4.h (module 'internet'): bool ns3::Ipv4::GetIpForward() const [member function]
cls.add_method('GetIpForward',
'bool',
[],
is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True)
## ipv4.h (module 'internet'): bool ns3::Ipv4::GetWeakEsModel() const [member function]
cls.add_method('GetWeakEsModel',
'bool',
[],
is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True)
## ipv4.h (module 'internet'): void ns3::Ipv4::SetIpForward(bool forward) [member function]
cls.add_method('SetIpForward',
'void',
[param('bool', 'forward')],
is_pure_virtual=True, visibility='private', is_virtual=True)
## ipv4.h (module 'internet'): void ns3::Ipv4::SetWeakEsModel(bool model) [member function]
cls.add_method('SetWeakEsModel',
'void',
[param('bool', 'model')],
is_pure_virtual=True, visibility='private', is_virtual=True)
return
def register_Ns3Ipv4AddressChecker_methods(root_module, cls):
## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker::Ipv4AddressChecker() [constructor]
cls.add_constructor([])
## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker::Ipv4AddressChecker(ns3::Ipv4AddressChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4AddressChecker const &', 'arg0')])
return
def register_Ns3Ipv4AddressValue_methods(root_module, cls):
## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue() [constructor]
cls.add_constructor([])
## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue(ns3::Ipv4AddressValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4AddressValue const &', 'arg0')])
## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue(ns3::Ipv4Address const & value) [constructor]
cls.add_constructor([param('ns3::Ipv4Address const &', 'value')])
## ipv4-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv4AddressValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4AddressValue::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)
## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4AddressValue::Get() const [member function]
cls.add_method('Get',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv4-address.h (module 'network'): std::string ns3::Ipv4AddressValue::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)
## ipv4-address.h (module 'network'): void ns3::Ipv4AddressValue::Set(ns3::Ipv4Address const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Ipv4Address const &', 'value')])
return
def register_Ns3Ipv4L3Protocol_methods(root_module, cls):
## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4L3Protocol::Ipv4L3Protocol() [constructor]
cls.add_constructor([])
## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::AddAddress(uint32_t i, ns3::Ipv4InterfaceAddress address) [member function]
cls.add_method('AddAddress',
'bool',
[param('uint32_t', 'i'), param('ns3::Ipv4InterfaceAddress', 'address')],
is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): uint32_t ns3::Ipv4L3Protocol::AddInterface(ns3::Ptr<ns3::NetDevice> device) [member function]
cls.add_method('AddInterface',
'uint32_t',
[param('ns3::Ptr< ns3::NetDevice >', 'device')],
is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::Socket> ns3::Ipv4L3Protocol::CreateRawSocket() [member function]
cls.add_method('CreateRawSocket',
'ns3::Ptr< ns3::Socket >',
[],
is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::DeleteRawSocket(ns3::Ptr<ns3::Socket> socket) [member function]
cls.add_method('DeleteRawSocket',
'void',
[param('ns3::Ptr< ns3::Socket >', 'socket')],
is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4InterfaceAddress ns3::Ipv4L3Protocol::GetAddress(uint32_t interfaceIndex, uint32_t addressIndex) const [member function]
cls.add_method('GetAddress',
'ns3::Ipv4InterfaceAddress',
[param('uint32_t', 'interfaceIndex'), param('uint32_t', 'addressIndex')],
is_const=True, is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::Ipv4Interface> ns3::Ipv4L3Protocol::GetInterface(uint32_t i) const [member function]
cls.add_method('GetInterface',
'ns3::Ptr< ns3::Ipv4Interface >',
[param('uint32_t', 'i')],
is_const=True)
## ipv4-l3-protocol.h (module 'internet'): int32_t ns3::Ipv4L3Protocol::GetInterfaceForAddress(ns3::Ipv4Address addr) const [member function]
cls.add_method('GetInterfaceForAddress',
'int32_t',
[param('ns3::Ipv4Address', 'addr')],
is_const=True, is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): int32_t ns3::Ipv4L3Protocol::GetInterfaceForDevice(ns3::Ptr<const ns3::NetDevice> device) const [member function]
cls.add_method('GetInterfaceForDevice',
'int32_t',
[param('ns3::Ptr< ns3::NetDevice const >', 'device')],
is_const=True, is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): int32_t ns3::Ipv4L3Protocol::GetInterfaceForPrefix(ns3::Ipv4Address addr, ns3::Ipv4Mask mask) const [member function]
cls.add_method('GetInterfaceForPrefix',
'int32_t',
[param('ns3::Ipv4Address', 'addr'), param('ns3::Ipv4Mask', 'mask')],
is_const=True, is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): uint16_t ns3::Ipv4L3Protocol::GetMetric(uint32_t i) const [member function]
cls.add_method('GetMetric',
'uint16_t',
[param('uint32_t', 'i')],
is_const=True, is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): uint16_t ns3::Ipv4L3Protocol::GetMtu(uint32_t i) const [member function]
cls.add_method('GetMtu',
'uint16_t',
[param('uint32_t', 'i')],
is_const=True, is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): uint32_t ns3::Ipv4L3Protocol::GetNAddresses(uint32_t interface) const [member function]
cls.add_method('GetNAddresses',
'uint32_t',
[param('uint32_t', 'interface')],
is_const=True, is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): uint32_t ns3::Ipv4L3Protocol::GetNInterfaces() const [member function]
cls.add_method('GetNInterfaces',
'uint32_t',
[],
is_const=True, is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv4L3Protocol::GetNetDevice(uint32_t i) [member function]
cls.add_method('GetNetDevice',
'ns3::Ptr< ns3::NetDevice >',
[param('uint32_t', 'i')],
is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::IpL4Protocol> ns3::Ipv4L3Protocol::GetProtocol(int protocolNumber) const [member function]
cls.add_method('GetProtocol',
'ns3::Ptr< ns3::IpL4Protocol >',
[param('int', 'protocolNumber')],
is_const=True, is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::Ipv4RoutingProtocol> ns3::Ipv4L3Protocol::GetRoutingProtocol() const [member function]
cls.add_method('GetRoutingProtocol',
'ns3::Ptr< ns3::Ipv4RoutingProtocol >',
[],
is_const=True, is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): static ns3::TypeId ns3::Ipv4L3Protocol::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::Insert(ns3::Ptr<ns3::IpL4Protocol> protocol) [member function]
cls.add_method('Insert',
'void',
[param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol')],
is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::IsDestinationAddress(ns3::Ipv4Address address, uint32_t iif) const [member function]
cls.add_method('IsDestinationAddress',
'bool',
[param('ns3::Ipv4Address', 'address'), param('uint32_t', 'iif')],
is_const=True, is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::IsForwarding(uint32_t i) const [member function]
cls.add_method('IsForwarding',
'bool',
[param('uint32_t', 'i')],
is_const=True, is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::IsUp(uint32_t i) const [member function]
cls.add_method('IsUp',
'bool',
[param('uint32_t', 'i')],
is_const=True, is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::Receive(ns3::Ptr<ns3::NetDevice> device, ns3::Ptr<const ns3::Packet> p, uint16_t protocol, ns3::Address const & from, ns3::Address const & to, ns3::NetDevice::PacketType packetType) [member function]
cls.add_method('Receive',
'void',
[param('ns3::Ptr< ns3::NetDevice >', 'device'), param('ns3::Ptr< ns3::Packet const >', 'p'), param('uint16_t', 'protocol'), param('ns3::Address const &', 'from'), param('ns3::Address const &', 'to'), param('ns3::NetDevice::PacketType', 'packetType')])
## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::Remove(ns3::Ptr<ns3::IpL4Protocol> protocol) [member function]
cls.add_method('Remove',
'void',
[param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol')])
## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::RemoveAddress(uint32_t interfaceIndex, uint32_t addressIndex) [member function]
cls.add_method('RemoveAddress',
'bool',
[param('uint32_t', 'interfaceIndex'), param('uint32_t', 'addressIndex')],
is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::RemoveAddress(uint32_t interface, ns3::Ipv4Address address) [member function]
cls.add_method('RemoveAddress',
'bool',
[param('uint32_t', 'interface'), param('ns3::Ipv4Address', 'address')],
is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4L3Protocol::SelectSourceAddress(ns3::Ptr<const ns3::NetDevice> device, ns3::Ipv4Address dst, ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e scope) [member function]
cls.add_method('SelectSourceAddress',
'ns3::Ipv4Address',
[param('ns3::Ptr< ns3::NetDevice const >', 'device'), param('ns3::Ipv4Address', 'dst'), param('ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e', 'scope')],
is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::Send(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Address source, ns3::Ipv4Address destination, uint8_t protocol, ns3::Ptr<ns3::Ipv4Route> route) [member function]
cls.add_method('Send',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Address', 'source'), param('ns3::Ipv4Address', 'destination'), param('uint8_t', 'protocol'), param('ns3::Ptr< ns3::Ipv4Route >', 'route')],
is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SendWithHeader(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Header ipHeader, ns3::Ptr<ns3::Ipv4Route> route) [member function]
cls.add_method('SendWithHeader',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Header', 'ipHeader'), param('ns3::Ptr< ns3::Ipv4Route >', 'route')],
is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetDefaultTtl(uint8_t ttl) [member function]
cls.add_method('SetDefaultTtl',
'void',
[param('uint8_t', 'ttl')])
## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetDown(uint32_t i) [member function]
cls.add_method('SetDown',
'void',
[param('uint32_t', 'i')],
is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetForwarding(uint32_t i, bool val) [member function]
cls.add_method('SetForwarding',
'void',
[param('uint32_t', 'i'), param('bool', 'val')],
is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetMetric(uint32_t i, uint16_t metric) [member function]
cls.add_method('SetMetric',
'void',
[param('uint32_t', 'i'), param('uint16_t', 'metric')],
is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetNode(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('SetNode',
'void',
[param('ns3::Ptr< ns3::Node >', 'node')])
## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetRoutingProtocol(ns3::Ptr<ns3::Ipv4RoutingProtocol> routingProtocol) [member function]
cls.add_method('SetRoutingProtocol',
'void',
[param('ns3::Ptr< ns3::Ipv4RoutingProtocol >', 'routingProtocol')],
is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetUp(uint32_t i) [member function]
cls.add_method('SetUp',
'void',
[param('uint32_t', 'i')],
is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4L3Protocol::PROT_NUMBER [variable]
cls.add_static_attribute('PROT_NUMBER', 'uint16_t const', is_const=True)
## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::NotifyNewAggregate() [member function]
cls.add_method('NotifyNewAggregate',
'void',
[],
visibility='protected', is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::GetIpForward() const [member function]
cls.add_method('GetIpForward',
'bool',
[],
is_const=True, visibility='private', is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::GetWeakEsModel() const [member function]
cls.add_method('GetWeakEsModel',
'bool',
[],
is_const=True, visibility='private', is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetIpForward(bool forward) [member function]
cls.add_method('SetIpForward',
'void',
[param('bool', 'forward')],
visibility='private', is_virtual=True)
## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetWeakEsModel(bool model) [member function]
cls.add_method('SetWeakEsModel',
'void',
[param('bool', 'model')],
visibility='private', is_virtual=True)
return
def register_Ns3Ipv4MaskChecker_methods(root_module, cls):
## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker::Ipv4MaskChecker() [constructor]
cls.add_constructor([])
## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker::Ipv4MaskChecker(ns3::Ipv4MaskChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4MaskChecker const &', 'arg0')])
return
def register_Ns3Ipv4MaskValue_methods(root_module, cls):
## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue() [constructor]
cls.add_constructor([])
## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue(ns3::Ipv4MaskValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4MaskValue const &', 'arg0')])
## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue(ns3::Ipv4Mask const & value) [constructor]
cls.add_constructor([param('ns3::Ipv4Mask const &', 'value')])
## ipv4-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv4MaskValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4MaskValue::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)
## ipv4-address.h (module 'network'): ns3::Ipv4Mask ns3::Ipv4MaskValue::Get() const [member function]
cls.add_method('Get',
'ns3::Ipv4Mask',
[],
is_const=True)
## ipv4-address.h (module 'network'): std::string ns3::Ipv4MaskValue::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)
## ipv4-address.h (module 'network'): void ns3::Ipv4MaskValue::Set(ns3::Ipv4Mask const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Ipv4Mask const &', 'value')])
return
def register_Ns3Ipv4MulticastRoute_methods(root_module, cls):
## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::Ipv4MulticastRoute(ns3::Ipv4MulticastRoute const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4MulticastRoute const &', 'arg0')])
## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::Ipv4MulticastRoute() [constructor]
cls.add_constructor([])
## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4MulticastRoute::GetGroup() const [member function]
cls.add_method('GetGroup',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4MulticastRoute::GetOrigin() const [member function]
cls.add_method('GetOrigin',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv4-route.h (module 'internet'): uint32_t ns3::Ipv4MulticastRoute::GetOutputTtl(uint32_t oif) [member function]
cls.add_method('GetOutputTtl',
'uint32_t',
[param('uint32_t', 'oif')],
deprecated=True)
## ipv4-route.h (module 'internet'): std::map<unsigned int, unsigned int, std::less<unsigned int>, std::allocator<std::pair<unsigned int const, unsigned int> > > ns3::Ipv4MulticastRoute::GetOutputTtlMap() const [member function]
cls.add_method('GetOutputTtlMap',
'std::map< unsigned int, unsigned int >',
[],
is_const=True)
## ipv4-route.h (module 'internet'): uint32_t ns3::Ipv4MulticastRoute::GetParent() const [member function]
cls.add_method('GetParent',
'uint32_t',
[],
is_const=True)
## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetGroup(ns3::Ipv4Address const group) [member function]
cls.add_method('SetGroup',
'void',
[param('ns3::Ipv4Address const', 'group')])
## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetOrigin(ns3::Ipv4Address const origin) [member function]
cls.add_method('SetOrigin',
'void',
[param('ns3::Ipv4Address const', 'origin')])
## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetOutputTtl(uint32_t oif, uint32_t ttl) [member function]
cls.add_method('SetOutputTtl',
'void',
[param('uint32_t', 'oif'), param('uint32_t', 'ttl')])
## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetParent(uint32_t iif) [member function]
cls.add_method('SetParent',
'void',
[param('uint32_t', 'iif')])
## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::MAX_INTERFACES [variable]
cls.add_static_attribute('MAX_INTERFACES', 'uint32_t const', is_const=True)
## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::MAX_TTL [variable]
cls.add_static_attribute('MAX_TTL', 'uint32_t const', is_const=True)
return
def register_Ns3Ipv4Route_methods(root_module, cls):
cls.add_output_stream_operator()
## ipv4-route.h (module 'internet'): ns3::Ipv4Route::Ipv4Route(ns3::Ipv4Route const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4Route const &', 'arg0')])
## ipv4-route.h (module 'internet'): ns3::Ipv4Route::Ipv4Route() [constructor]
cls.add_constructor([])
## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Route::GetDestination() const [member function]
cls.add_method('GetDestination',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Route::GetGateway() const [member function]
cls.add_method('GetGateway',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv4-route.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv4Route::GetOutputDevice() const [member function]
cls.add_method('GetOutputDevice',
'ns3::Ptr< ns3::NetDevice >',
[],
is_const=True)
## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Route::GetSource() const [member function]
cls.add_method('GetSource',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetDestination(ns3::Ipv4Address dest) [member function]
cls.add_method('SetDestination',
'void',
[param('ns3::Ipv4Address', 'dest')])
## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetGateway(ns3::Ipv4Address gw) [member function]
cls.add_method('SetGateway',
'void',
[param('ns3::Ipv4Address', 'gw')])
## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetOutputDevice(ns3::Ptr<ns3::NetDevice> outputDevice) [member function]
cls.add_method('SetOutputDevice',
'void',
[param('ns3::Ptr< ns3::NetDevice >', 'outputDevice')])
## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetSource(ns3::Ipv4Address src) [member function]
cls.add_method('SetSource',
'void',
[param('ns3::Ipv4Address', 'src')])
return
def register_Ns3Ipv4RoutingProtocol_methods(root_module, cls):
## ipv4-routing-protocol.h (module 'internet'): ns3::Ipv4RoutingProtocol::Ipv4RoutingProtocol() [constructor]
cls.add_constructor([])
## ipv4-routing-protocol.h (module 'internet'): ns3::Ipv4RoutingProtocol::Ipv4RoutingProtocol(ns3::Ipv4RoutingProtocol const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4RoutingProtocol const &', 'arg0')])
## ipv4-routing-protocol.h (module 'internet'): static ns3::TypeId ns3::Ipv4RoutingProtocol::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::NotifyAddAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function]
cls.add_method('NotifyAddAddress',
'void',
[param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')],
is_pure_virtual=True, is_virtual=True)
## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::NotifyInterfaceDown(uint32_t interface) [member function]
cls.add_method('NotifyInterfaceDown',
'void',
[param('uint32_t', 'interface')],
is_pure_virtual=True, is_virtual=True)
## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::NotifyInterfaceUp(uint32_t interface) [member function]
cls.add_method('NotifyInterfaceUp',
'void',
[param('uint32_t', 'interface')],
is_pure_virtual=True, is_virtual=True)
## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::NotifyRemoveAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function]
cls.add_method('NotifyRemoveAddress',
'void',
[param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')],
is_pure_virtual=True, is_virtual=True)
## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::PrintRoutingTable(ns3::Ptr<ns3::OutputStreamWrapper> stream) const [member function]
cls.add_method('PrintRoutingTable',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4-routing-protocol.h (module 'internet'): bool ns3::Ipv4RoutingProtocol::RouteInput(ns3::Ptr<const ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<const ns3::NetDevice> idev, ns3::Callback<void,ns3::Ptr<ns3::Ipv4Route>,ns3::Ptr<const ns3::Packet>,const ns3::Ipv4Header&,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ucb, ns3::Callback<void,ns3::Ptr<ns3::Ipv4MulticastRoute>,ns3::Ptr<const ns3::Packet>,const ns3::Ipv4Header&,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> mcb, ns3::Callback<void,ns3::Ptr<const ns3::Packet>,const ns3::Ipv4Header&,unsigned int,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> lcb, ns3::Callback<void,ns3::Ptr<const ns3::Packet>,const ns3::Ipv4Header&,ns3::Socket::SocketErrno,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ecb) [member function]
cls.add_method('RouteInput',
'bool',
[param('ns3::Ptr< ns3::Packet const >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice const >', 'idev'), param('ns3::Callback< void, ns3::Ptr< ns3::Ipv4Route >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ucb'), param('ns3::Callback< void, ns3::Ptr< ns3::Ipv4MulticastRoute >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'mcb'), param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'lcb'), param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ecb')],
is_pure_virtual=True, is_virtual=True)
## ipv4-routing-protocol.h (module 'internet'): ns3::Ptr<ns3::Ipv4Route> ns3::Ipv4RoutingProtocol::RouteOutput(ns3::Ptr<ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<ns3::NetDevice> oif, ns3::Socket::SocketErrno & sockerr) [member function]
cls.add_method('RouteOutput',
'ns3::Ptr< ns3::Ipv4Route >',
[param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice >', 'oif'), param('ns3::Socket::SocketErrno &', 'sockerr')],
is_pure_virtual=True, is_virtual=True)
## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::SetIpv4(ns3::Ptr<ns3::Ipv4> ipv4) [member function]
cls.add_method('SetIpv4',
'void',
[param('ns3::Ptr< ns3::Ipv4 >', 'ipv4')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3Ipv6AddressChecker_methods(root_module, cls):
## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker::Ipv6AddressChecker() [constructor]
cls.add_constructor([])
## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker::Ipv6AddressChecker(ns3::Ipv6AddressChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv6AddressChecker const &', 'arg0')])
return
def register_Ns3Ipv6AddressValue_methods(root_module, cls):
## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue() [constructor]
cls.add_constructor([])
## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue(ns3::Ipv6AddressValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv6AddressValue const &', 'arg0')])
## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue(ns3::Ipv6Address const & value) [constructor]
cls.add_constructor([param('ns3::Ipv6Address const &', 'value')])
## ipv6-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv6AddressValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6AddressValue::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)
## ipv6-address.h (module 'network'): ns3::Ipv6Address ns3::Ipv6AddressValue::Get() const [member function]
cls.add_method('Get',
'ns3::Ipv6Address',
[],
is_const=True)
## ipv6-address.h (module 'network'): std::string ns3::Ipv6AddressValue::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)
## ipv6-address.h (module 'network'): void ns3::Ipv6AddressValue::Set(ns3::Ipv6Address const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Ipv6Address const &', 'value')])
return
def register_Ns3Ipv6PrefixChecker_methods(root_module, cls):
## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker::Ipv6PrefixChecker() [constructor]
cls.add_constructor([])
## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker::Ipv6PrefixChecker(ns3::Ipv6PrefixChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv6PrefixChecker const &', 'arg0')])
return
def register_Ns3Ipv6PrefixValue_methods(root_module, cls):
## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue() [constructor]
cls.add_constructor([])
## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue(ns3::Ipv6PrefixValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv6PrefixValue const &', 'arg0')])
## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue(ns3::Ipv6Prefix const & value) [constructor]
cls.add_constructor([param('ns3::Ipv6Prefix const &', 'value')])
## ipv6-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv6PrefixValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6PrefixValue::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)
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix ns3::Ipv6PrefixValue::Get() const [member function]
cls.add_method('Get',
'ns3::Ipv6Prefix',
[],
is_const=True)
## ipv6-address.h (module 'network'): std::string ns3::Ipv6PrefixValue::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)
## ipv6-address.h (module 'network'): void ns3::Ipv6PrefixValue::Set(ns3::Ipv6Prefix const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Ipv6Prefix const &', 'value')])
return
def register_Ns3Mac48AddressChecker_methods(root_module, cls):
## mac48-address.h (module 'network'): ns3::Mac48AddressChecker::Mac48AddressChecker() [constructor]
cls.add_constructor([])
## mac48-address.h (module 'network'): ns3::Mac48AddressChecker::Mac48AddressChecker(ns3::Mac48AddressChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Mac48AddressChecker const &', 'arg0')])
return
def register_Ns3Mac48AddressValue_methods(root_module, cls):
## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue() [constructor]
cls.add_constructor([])
## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue(ns3::Mac48AddressValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Mac48AddressValue const &', 'arg0')])
## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue(ns3::Mac48Address const & value) [constructor]
cls.add_constructor([param('ns3::Mac48Address const &', 'value')])
## mac48-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Mac48AddressValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## mac48-address.h (module 'network'): bool ns3::Mac48AddressValue::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)
## mac48-address.h (module 'network'): ns3::Mac48Address ns3::Mac48AddressValue::Get() const [member function]
cls.add_method('Get',
'ns3::Mac48Address',
[],
is_const=True)
## mac48-address.h (module 'network'): std::string ns3::Mac48AddressValue::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)
## mac48-address.h (module 'network'): void ns3::Mac48AddressValue::Set(ns3::Mac48Address const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Mac48Address const &', 'value')])
return
def register_Ns3NetDevice_methods(root_module, cls):
## net-device.h (module 'network'): ns3::NetDevice::NetDevice() [constructor]
cls.add_constructor([])
## net-device.h (module 'network'): ns3::NetDevice::NetDevice(ns3::NetDevice const & arg0) [copy constructor]
cls.add_constructor([param('ns3::NetDevice const &', 'arg0')])
## net-device.h (module 'network'): void ns3::NetDevice::AddLinkChangeCallback(ns3::Callback<void,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> callback) [member function]
cls.add_method('AddLinkChangeCallback',
'void',
[param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetAddress() const [member function]
cls.add_method('GetAddress',
'ns3::Address',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetBroadcast() const [member function]
cls.add_method('GetBroadcast',
'ns3::Address',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): ns3::Ptr<ns3::Channel> ns3::NetDevice::GetChannel() const [member function]
cls.add_method('GetChannel',
'ns3::Ptr< ns3::Channel >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): uint32_t ns3::NetDevice::GetIfIndex() const [member function]
cls.add_method('GetIfIndex',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): uint16_t ns3::NetDevice::GetMtu() const [member function]
cls.add_method('GetMtu',
'uint16_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetMulticast(ns3::Ipv4Address multicastGroup) const [member function]
cls.add_method('GetMulticast',
'ns3::Address',
[param('ns3::Ipv4Address', 'multicastGroup')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetMulticast(ns3::Ipv6Address addr) const [member function]
cls.add_method('GetMulticast',
'ns3::Address',
[param('ns3::Ipv6Address', 'addr')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): ns3::Ptr<ns3::Node> ns3::NetDevice::GetNode() const [member function]
cls.add_method('GetNode',
'ns3::Ptr< ns3::Node >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): static ns3::TypeId ns3::NetDevice::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## net-device.h (module 'network'): bool ns3::NetDevice::IsBridge() const [member function]
cls.add_method('IsBridge',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::IsBroadcast() const [member function]
cls.add_method('IsBroadcast',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::IsLinkUp() const [member function]
cls.add_method('IsLinkUp',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::IsMulticast() const [member function]
cls.add_method('IsMulticast',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::IsPointToPoint() const [member function]
cls.add_method('IsPointToPoint',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::NeedsArp() const [member function]
cls.add_method('NeedsArp',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::Send(ns3::Ptr<ns3::Packet> packet, ns3::Address const & dest, uint16_t protocolNumber) [member function]
cls.add_method('Send',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::SendFrom(ns3::Ptr<ns3::Packet> packet, ns3::Address const & source, ns3::Address const & dest, uint16_t protocolNumber) [member function]
cls.add_method('SendFrom',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'source'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): void ns3::NetDevice::SetAddress(ns3::Address address) [member function]
cls.add_method('SetAddress',
'void',
[param('ns3::Address', 'address')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): void ns3::NetDevice::SetIfIndex(uint32_t const index) [member function]
cls.add_method('SetIfIndex',
'void',
[param('uint32_t const', 'index')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::SetMtu(uint16_t const mtu) [member function]
cls.add_method('SetMtu',
'bool',
[param('uint16_t const', 'mtu')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): void ns3::NetDevice::SetNode(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('SetNode',
'void',
[param('ns3::Ptr< ns3::Node >', 'node')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): void ns3::NetDevice::SetPromiscReceiveCallback(ns3::Callback<bool,ns3::Ptr<ns3::NetDevice>,ns3::Ptr<const ns3::Packet>,short unsigned int,const ns3::Address&,const ns3::Address&,ns3::NetDevice::PacketType,ns3::empty,ns3::empty,ns3::empty> cb) [member function]
cls.add_method('SetPromiscReceiveCallback',
'void',
[param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, short unsigned int, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): void ns3::NetDevice::SetReceiveCallback(ns3::Callback<bool,ns3::Ptr<ns3::NetDevice>,ns3::Ptr<const ns3::Packet>,short unsigned int,const ns3::Address&,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> cb) [member function]
cls.add_method('SetReceiveCallback',
'void',
[param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, short unsigned int, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::SupportsSendFrom() const [member function]
cls.add_method('SupportsSendFrom',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3NixVector_methods(root_module, cls):
cls.add_output_stream_operator()
## nix-vector.h (module 'network'): ns3::NixVector::NixVector() [constructor]
cls.add_constructor([])
## nix-vector.h (module 'network'): ns3::NixVector::NixVector(ns3::NixVector const & o) [copy constructor]
cls.add_constructor([param('ns3::NixVector const &', 'o')])
## nix-vector.h (module 'network'): void ns3::NixVector::AddNeighborIndex(uint32_t newBits, uint32_t numberOfBits) [member function]
cls.add_method('AddNeighborIndex',
'void',
[param('uint32_t', 'newBits'), param('uint32_t', 'numberOfBits')])
## nix-vector.h (module 'network'): uint32_t ns3::NixVector::BitCount(uint32_t numberOfNeighbors) const [member function]
cls.add_method('BitCount',
'uint32_t',
[param('uint32_t', 'numberOfNeighbors')],
is_const=True)
## nix-vector.h (module 'network'): ns3::Ptr<ns3::NixVector> ns3::NixVector::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::NixVector >',
[],
is_const=True)
## nix-vector.h (module 'network'): uint32_t ns3::NixVector::Deserialize(uint32_t const * buffer, uint32_t size) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('uint32_t const *', 'buffer'), param('uint32_t', 'size')])
## nix-vector.h (module 'network'): uint32_t ns3::NixVector::ExtractNeighborIndex(uint32_t numberOfBits) [member function]
cls.add_method('ExtractNeighborIndex',
'uint32_t',
[param('uint32_t', 'numberOfBits')])
## nix-vector.h (module 'network'): uint32_t ns3::NixVector::GetRemainingBits() [member function]
cls.add_method('GetRemainingBits',
'uint32_t',
[])
## nix-vector.h (module 'network'): uint32_t ns3::NixVector::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## nix-vector.h (module 'network'): uint32_t ns3::NixVector::Serialize(uint32_t * buffer, uint32_t maxSize) const [member function]
cls.add_method('Serialize',
'uint32_t',
[param('uint32_t *', 'buffer'), param('uint32_t', 'maxSize')],
is_const=True)
return
def register_Ns3Node_methods(root_module, cls):
## node.h (module 'network'): ns3::Node::Node(ns3::Node const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Node const &', 'arg0')])
## node.h (module 'network'): ns3::Node::Node() [constructor]
cls.add_constructor([])
## node.h (module 'network'): ns3::Node::Node(uint32_t systemId) [constructor]
cls.add_constructor([param('uint32_t', 'systemId')])
## node.h (module 'network'): uint32_t ns3::Node::AddApplication(ns3::Ptr<ns3::Application> application) [member function]
cls.add_method('AddApplication',
'uint32_t',
[param('ns3::Ptr< ns3::Application >', 'application')])
## node.h (module 'network'): uint32_t ns3::Node::AddDevice(ns3::Ptr<ns3::NetDevice> device) [member function]
cls.add_method('AddDevice',
'uint32_t',
[param('ns3::Ptr< ns3::NetDevice >', 'device')])
## node.h (module 'network'): static bool ns3::Node::ChecksumEnabled() [member function]
cls.add_method('ChecksumEnabled',
'bool',
[],
is_static=True)
## node.h (module 'network'): ns3::Ptr<ns3::Application> ns3::Node::GetApplication(uint32_t index) const [member function]
cls.add_method('GetApplication',
'ns3::Ptr< ns3::Application >',
[param('uint32_t', 'index')],
is_const=True)
## node.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Node::GetDevice(uint32_t index) const [member function]
cls.add_method('GetDevice',
'ns3::Ptr< ns3::NetDevice >',
[param('uint32_t', 'index')],
is_const=True)
## node.h (module 'network'): uint32_t ns3::Node::GetId() const [member function]
cls.add_method('GetId',
'uint32_t',
[],
is_const=True)
## node.h (module 'network'): uint32_t ns3::Node::GetNApplications() const [member function]
cls.add_method('GetNApplications',
'uint32_t',
[],
is_const=True)
## node.h (module 'network'): uint32_t ns3::Node::GetNDevices() const [member function]
cls.add_method('GetNDevices',
'uint32_t',
[],
is_const=True)
## node.h (module 'network'): uint32_t ns3::Node::GetSystemId() const [member function]
cls.add_method('GetSystemId',
'uint32_t',
[],
is_const=True)
## node.h (module 'network'): static ns3::TypeId ns3::Node::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## node.h (module 'network'): void ns3::Node::RegisterDeviceAdditionListener(ns3::Callback<void,ns3::Ptr<ns3::NetDevice>,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> listener) [member function]
cls.add_method('RegisterDeviceAdditionListener',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'listener')])
## node.h (module 'network'): void ns3::Node::RegisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler, uint16_t protocolType, ns3::Ptr<ns3::NetDevice> device, bool promiscuous=false) [member function]
cls.add_method('RegisterProtocolHandler',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler'), param('uint16_t', 'protocolType'), param('ns3::Ptr< ns3::NetDevice >', 'device'), param('bool', 'promiscuous', default_value='false')])
## node.h (module 'network'): void ns3::Node::UnregisterDeviceAdditionListener(ns3::Callback<void,ns3::Ptr<ns3::NetDevice>,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> listener) [member function]
cls.add_method('UnregisterDeviceAdditionListener',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'listener')])
## node.h (module 'network'): void ns3::Node::UnregisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler) [member function]
cls.add_method('UnregisterProtocolHandler',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler')])
## node.h (module 'network'): void ns3::Node::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## node.h (module 'network'): void ns3::Node::DoInitialize() [member function]
cls.add_method('DoInitialize',
'void',
[],
visibility='protected', 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_Ns3OutputStreamWrapper_methods(root_module, cls):
## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(ns3::OutputStreamWrapper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::OutputStreamWrapper const &', 'arg0')])
## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(std::string filename, std::_Ios_Openmode filemode) [constructor]
cls.add_constructor([param('std::string', 'filename'), param('std::_Ios_Openmode', 'filemode')])
## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(std::ostream * os) [constructor]
cls.add_constructor([param('std::ostream *', 'os')])
## output-stream-wrapper.h (module 'network'): std::ostream * ns3::OutputStreamWrapper::GetStream() [member function]
cls.add_method('GetStream',
'std::ostream *',
[])
return
def register_Ns3Packet_methods(root_module, cls):
cls.add_output_stream_operator()
## packet.h (module 'network'): ns3::Packet::Packet() [constructor]
cls.add_constructor([])
## packet.h (module 'network'): ns3::Packet::Packet(ns3::Packet const & o) [copy constructor]
cls.add_constructor([param('ns3::Packet const &', 'o')])
## packet.h (module 'network'): ns3::Packet::Packet(uint32_t size) [constructor]
cls.add_constructor([param('uint32_t', 'size')])
## packet.h (module 'network'): ns3::Packet::Packet(uint8_t const * buffer, uint32_t size, bool magic) [constructor]
cls.add_constructor([param('uint8_t const *', 'buffer'), param('uint32_t', 'size'), param('bool', 'magic')])
## packet.h (module 'network'): ns3::Packet::Packet(uint8_t const * buffer, uint32_t size) [constructor]
cls.add_constructor([param('uint8_t const *', 'buffer'), param('uint32_t', 'size')])
## packet.h (module 'network'): void ns3::Packet::AddAtEnd(ns3::Ptr<const ns3::Packet> packet) [member function]
cls.add_method('AddAtEnd',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
## packet.h (module 'network'): void ns3::Packet::AddByteTag(ns3::Tag const & tag) const [member function]
cls.add_method('AddByteTag',
'void',
[param('ns3::Tag const &', 'tag')],
is_const=True)
## packet.h (module 'network'): void ns3::Packet::AddHeader(ns3::Header const & header) [member function]
cls.add_method('AddHeader',
'void',
[param('ns3::Header const &', 'header')])
## packet.h (module 'network'): void ns3::Packet::AddPacketTag(ns3::Tag const & tag) const [member function]
cls.add_method('AddPacketTag',
'void',
[param('ns3::Tag const &', 'tag')],
is_const=True)
## packet.h (module 'network'): void ns3::Packet::AddPaddingAtEnd(uint32_t size) [member function]
cls.add_method('AddPaddingAtEnd',
'void',
[param('uint32_t', 'size')])
## packet.h (module 'network'): void ns3::Packet::AddTrailer(ns3::Trailer const & trailer) [member function]
cls.add_method('AddTrailer',
'void',
[param('ns3::Trailer const &', 'trailer')])
## packet.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::Packet::BeginItem() const [member function]
cls.add_method('BeginItem',
'ns3::PacketMetadata::ItemIterator',
[],
is_const=True)
## packet.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Packet::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::Packet >',
[],
is_const=True)
## packet.h (module 'network'): uint32_t ns3::Packet::CopyData(uint8_t * buffer, uint32_t size) const [member function]
cls.add_method('CopyData',
'uint32_t',
[param('uint8_t *', 'buffer'), param('uint32_t', 'size')],
is_const=True)
## packet.h (module 'network'): void ns3::Packet::CopyData(std::ostream * os, uint32_t size) const [member function]
cls.add_method('CopyData',
'void',
[param('std::ostream *', 'os'), param('uint32_t', 'size')],
is_const=True)
## packet.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Packet::CreateFragment(uint32_t start, uint32_t length) const [member function]
cls.add_method('CreateFragment',
'ns3::Ptr< ns3::Packet >',
[param('uint32_t', 'start'), param('uint32_t', 'length')],
is_const=True)
## packet.h (module 'network'): static void ns3::Packet::EnableChecking() [member function]
cls.add_method('EnableChecking',
'void',
[],
is_static=True)
## packet.h (module 'network'): static void ns3::Packet::EnablePrinting() [member function]
cls.add_method('EnablePrinting',
'void',
[],
is_static=True)
## packet.h (module 'network'): bool ns3::Packet::FindFirstMatchingByteTag(ns3::Tag & tag) const [member function]
cls.add_method('FindFirstMatchingByteTag',
'bool',
[param('ns3::Tag &', 'tag')],
is_const=True)
## packet.h (module 'network'): ns3::ByteTagIterator ns3::Packet::GetByteTagIterator() const [member function]
cls.add_method('GetByteTagIterator',
'ns3::ByteTagIterator',
[],
is_const=True)
## packet.h (module 'network'): ns3::Ptr<ns3::NixVector> ns3::Packet::GetNixVector() const [member function]
cls.add_method('GetNixVector',
'ns3::Ptr< ns3::NixVector >',
[],
is_const=True)
## packet.h (module 'network'): ns3::PacketTagIterator ns3::Packet::GetPacketTagIterator() const [member function]
cls.add_method('GetPacketTagIterator',
'ns3::PacketTagIterator',
[],
is_const=True)
## packet.h (module 'network'): uint32_t ns3::Packet::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## packet.h (module 'network'): uint32_t ns3::Packet::GetSize() const [member function]
cls.add_method('GetSize',
'uint32_t',
[],
is_const=True)
## packet.h (module 'network'): uint64_t ns3::Packet::GetUid() const [member function]
cls.add_method('GetUid',
'uint64_t',
[],
is_const=True)
## packet.h (module 'network'): uint8_t const * ns3::Packet::PeekData() const [member function]
cls.add_method('PeekData',
'uint8_t const *',
[],
deprecated=True, is_const=True)
## packet.h (module 'network'): uint32_t ns3::Packet::PeekHeader(ns3::Header & header) const [member function]
cls.add_method('PeekHeader',
'uint32_t',
[param('ns3::Header &', 'header')],
is_const=True)
## packet.h (module 'network'): bool ns3::Packet::PeekPacketTag(ns3::Tag & tag) const [member function]
cls.add_method('PeekPacketTag',
'bool',
[param('ns3::Tag &', 'tag')],
is_const=True)
## packet.h (module 'network'): uint32_t ns3::Packet::PeekTrailer(ns3::Trailer & trailer) [member function]
cls.add_method('PeekTrailer',
'uint32_t',
[param('ns3::Trailer &', 'trailer')])
## packet.h (module 'network'): void ns3::Packet::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## packet.h (module 'network'): void ns3::Packet::PrintByteTags(std::ostream & os) const [member function]
cls.add_method('PrintByteTags',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## packet.h (module 'network'): void ns3::Packet::PrintPacketTags(std::ostream & os) const [member function]
cls.add_method('PrintPacketTags',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## packet.h (module 'network'): void ns3::Packet::RemoveAllByteTags() [member function]
cls.add_method('RemoveAllByteTags',
'void',
[])
## packet.h (module 'network'): void ns3::Packet::RemoveAllPacketTags() [member function]
cls.add_method('RemoveAllPacketTags',
'void',
[])
## packet.h (module 'network'): void ns3::Packet::RemoveAtEnd(uint32_t size) [member function]
cls.add_method('RemoveAtEnd',
'void',
[param('uint32_t', 'size')])
## packet.h (module 'network'): void ns3::Packet::RemoveAtStart(uint32_t size) [member function]
cls.add_method('RemoveAtStart',
'void',
[param('uint32_t', 'size')])
## packet.h (module 'network'): uint32_t ns3::Packet::RemoveHeader(ns3::Header & header) [member function]
cls.add_method('RemoveHeader',
'uint32_t',
[param('ns3::Header &', 'header')])
## packet.h (module 'network'): bool ns3::Packet::RemovePacketTag(ns3::Tag & tag) [member function]
cls.add_method('RemovePacketTag',
'bool',
[param('ns3::Tag &', 'tag')])
## packet.h (module 'network'): uint32_t ns3::Packet::RemoveTrailer(ns3::Trailer & trailer) [member function]
cls.add_method('RemoveTrailer',
'uint32_t',
[param('ns3::Trailer &', 'trailer')])
## packet.h (module 'network'): bool ns3::Packet::ReplacePacketTag(ns3::Tag & tag) [member function]
cls.add_method('ReplacePacketTag',
'bool',
[param('ns3::Tag &', 'tag')])
## packet.h (module 'network'): uint32_t ns3::Packet::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function]
cls.add_method('Serialize',
'uint32_t',
[param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')],
is_const=True)
## packet.h (module 'network'): void ns3::Packet::SetNixVector(ns3::Ptr<ns3::NixVector> arg0) [member function]
cls.add_method('SetNixVector',
'void',
[param('ns3::Ptr< ns3::NixVector >', 'arg0')])
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_Ns3AddressChecker_methods(root_module, cls):
## address.h (module 'network'): ns3::AddressChecker::AddressChecker() [constructor]
cls.add_constructor([])
## address.h (module 'network'): ns3::AddressChecker::AddressChecker(ns3::AddressChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AddressChecker const &', 'arg0')])
return
def register_Ns3AddressValue_methods(root_module, cls):
## address.h (module 'network'): ns3::AddressValue::AddressValue() [constructor]
cls.add_constructor([])
## address.h (module 'network'): ns3::AddressValue::AddressValue(ns3::AddressValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AddressValue const &', 'arg0')])
## address.h (module 'network'): ns3::AddressValue::AddressValue(ns3::Address const & value) [constructor]
cls.add_constructor([param('ns3::Address const &', 'value')])
## address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::AddressValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## address.h (module 'network'): bool ns3::AddressValue::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)
## address.h (module 'network'): ns3::Address ns3::AddressValue::Get() const [member function]
cls.add_method('Get',
'ns3::Address',
[],
is_const=True)
## address.h (module 'network'): std::string ns3::AddressValue::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)
## address.h (module 'network'): void ns3::AddressValue::Set(ns3::Address const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Address 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
register_functions_ns3_FatalImpl(module.get_submodule('FatalImpl'), root_module)
register_functions_ns3_Hash(module.get_submodule('Hash'), root_module)
return
def register_functions_ns3_FatalImpl(module, root_module):
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 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()
| gpl-2.0 |
thomazs/geraldo | site/newsite/django_1_0/django/db/backends/__init__.py | 9 | 9142 | try:
# Only exists in Python 2.4+
from threading import local
except ImportError:
# Import copy of _thread_local.py from Python 2.4
from django.utils._threading_local import local
class BaseDatabaseWrapper(local):
"""
Represents a database connection.
"""
ops = None
def __init__(self, **kwargs):
self.connection = None
self.queries = []
self.options = kwargs
def _commit(self):
if self.connection is not None:
return self.connection.commit()
def _rollback(self):
if self.connection is not None:
return self.connection.rollback()
def close(self):
if self.connection is not None:
self.connection.close()
self.connection = None
def cursor(self):
from django.conf import settings
cursor = self._cursor(settings)
if settings.DEBUG:
return self.make_debug_cursor(cursor)
return cursor
def make_debug_cursor(self, cursor):
from django.db.backends import util
return util.CursorDebugWrapper(cursor, self)
class BaseDatabaseFeatures(object):
allows_group_by_ordinal = True
inline_fk_references = True
needs_datetime_string_cast = True
supports_constraints = True
supports_tablespaces = False
uses_case_insensitive_names = False
uses_custom_query_class = False
empty_fetchmany_value = []
update_can_self_select = True
supports_usecs = True
time_field_needs_date = False
interprets_empty_strings_as_nulls = False
date_field_supports_time_value = True
can_use_chunked_reads = True
class BaseDatabaseOperations(object):
"""
This class encapsulates all backend-specific differences, such as the way
a backend performs ordering or calculates the ID of a recently-inserted
row.
"""
def autoinc_sql(self, table, column):
"""
Returns any SQL needed to support auto-incrementing primary keys, or
None if no SQL is necessary.
This SQL is executed when a table is created.
"""
return None
def date_extract_sql(self, lookup_type, field_name):
"""
Given a lookup_type of 'year', 'month' or 'day', returns the SQL that
extracts a value from the given date field field_name.
"""
raise NotImplementedError()
def date_trunc_sql(self, lookup_type, field_name):
"""
Given a lookup_type of 'year', 'month' or 'day', returns the SQL that
truncates the given date field field_name to a DATE object with only
the given specificity.
"""
raise NotImplementedError()
def datetime_cast_sql(self):
"""
Returns the SQL necessary to cast a datetime value so that it will be
retrieved as a Python datetime object instead of a string.
This SQL should include a '%s' in place of the field's name.
"""
return "%s"
def deferrable_sql(self):
"""
Returns the SQL necessary to make a constraint "initially deferred"
during a CREATE TABLE statement.
"""
return ''
def drop_foreignkey_sql(self):
"""
Returns the SQL command that drops a foreign key.
"""
return "DROP CONSTRAINT"
def drop_sequence_sql(self, table):
"""
Returns any SQL necessary to drop the sequence for the given table.
Returns None if no SQL is necessary.
"""
return None
def field_cast_sql(self, db_type):
"""
Given a column type (e.g. 'BLOB', 'VARCHAR'), returns the SQL necessary
to cast it before using it in a WHERE statement. Note that the
resulting string should contain a '%s' placeholder for the column being
searched against.
"""
return '%s'
def fulltext_search_sql(self, field_name):
"""
Returns the SQL WHERE clause to use in order to perform a full-text
search of the given field_name. Note that the resulting string should
contain a '%s' placeholder for the value being searched against.
"""
raise NotImplementedError('Full-text search is not implemented for this database backend')
def last_executed_query(self, cursor, sql, params):
"""
Returns a string of the query last executed by the given cursor, with
placeholders replaced with actual values.
`sql` is the raw query containing placeholders, and `params` is the
sequence of parameters. These are used by default, but this method
exists for database backends to provide a better implementation
according to their own quoting schemes.
"""
from django.utils.encoding import smart_unicode, force_unicode
# Convert params to contain Unicode values.
to_unicode = lambda s: force_unicode(s, strings_only=True)
if isinstance(params, (list, tuple)):
u_params = tuple([to_unicode(val) for val in params])
else:
u_params = dict([(to_unicode(k), to_unicode(v)) for k, v in params.items()])
return smart_unicode(sql) % u_params
def last_insert_id(self, cursor, table_name, pk_name):
"""
Given a cursor object that has just performed an INSERT statement into
a table that has an auto-incrementing ID, returns the newly created ID.
This method also receives the table name and the name of the primary-key
column.
"""
return cursor.lastrowid
def lookup_cast(self, lookup_type):
"""
Returns the string to use in a query when performing lookups
("contains", "like", etc). The resulting string should contain a '%s'
placeholder for the column being searched against.
"""
return "%s"
def max_name_length(self):
"""
Returns the maximum length of table and column names, or None if there
is no limit.
"""
return None
def no_limit_value(self):
"""
Returns the value to use for the LIMIT when we are wanting "LIMIT
infinity". Returns None if the limit clause can be omitted in this case.
"""
# FIXME: API may need to change once Oracle backend is repaired.
raise NotImplementedError()
def pk_default_value(self):
"""
Returns the value to use during an INSERT statement to specify that
the field should use its default value.
"""
return 'DEFAULT'
def query_class(self, DefaultQueryClass):
"""
Given the default Query class, returns a custom Query class
to use for this backend. Returns None if a custom Query isn't used.
See also BaseDatabaseFeatures.uses_custom_query_class, which regulates
whether this method is called at all.
"""
return None
def quote_name(self, name):
"""
Returns a quoted version of the given table, index or column name. Does
not quote the given name if it's already been quoted.
"""
raise NotImplementedError()
def random_function_sql(self):
"""
Returns a SQL expression that returns a random value.
"""
return 'RANDOM()'
def regex_lookup(self, lookup_type):
"""
Returns the string to use in a query when performing regular expression
lookups (using "regex" or "iregex"). The resulting string should
contain a '%s' placeholder for the column being searched against.
If the feature is not supported (or part of it is not supported), a
NotImplementedError exception can be raised.
"""
raise NotImplementedError
def sql_flush(self, style, tables, sequences):
"""
Returns a list of SQL statements required to remove all data from
the given database tables (without actually removing the tables
themselves).
The `style` argument is a Style object as returned by either
color_style() or no_style() in django.core.management.color.
"""
raise NotImplementedError()
def sequence_reset_sql(self, style, model_list):
"""
Returns a list of the SQL statements required to reset sequences for
the given models.
The `style` argument is a Style object as returned by either
color_style() or no_style() in django.core.management.color.
"""
return [] # No sequence reset required by default.
def start_transaction_sql(self):
"""
Returns the SQL statement required to start a transaction.
"""
return "BEGIN;"
def tablespace_sql(self, tablespace, inline=False):
"""
Returns the tablespace SQL, or None if the backend doesn't use
tablespaces.
"""
return None
def prep_for_like_query(self, x):
"""Prepares a value for use in a LIKE query."""
from django.utils.encoding import smart_unicode
return smart_unicode(x).replace("\\", "\\\\").replace("%", "\%").replace("_", "\_")
| lgpl-3.0 |
joxer/Baka-No-Voltron | tmp/android.dist/private/renpy/dump.py | 1 | 6422 | # Copyright 2004-2015 Tom Rothamel <pytom@bishoujo.us>
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# This file contains code to write the reflect.json file. This file contains
# information about the game that's used to reflect on the contents,
# including how to navigate around the game.
import inspect
import json
import sys
import os
import renpy
# A list of (name, filename, linenumber) tuples, for various types of
# name. These are added to as the definitions occur.
definitions = [ ]
transforms = [ ]
screens = [ ]
# Does a file exist? We cache the result here.
file_exists_cache = { }
def file_exists(fn):
rv = file_exists_cache.get(fn, None)
if rv is None:
fullfn = renpy.parser.unelide_filename(fn)
rv = os.path.exists(fullfn)
file_exists_cache[fn] = rv
return rv
# Did we do a dump?
completed_dump = False
def dump(error):
"""
Causes a JSON dump file to be written, if the user has requested it.
`error`
An error flag that is added to the written file.
"""
global completed_dump
args = renpy.game.args
if completed_dump:
return
completed_dump = True
if not args.json_dump:
return
def filter(name, filename): #@ReservedAssignment
"""
Returns true if the name is included by the filter, or false if it is excluded.
"""
filename = filename.replace("\\", "/")
if name.startswith("_") and not args.json_dump_private:
if name.startswith("__") and name.endswith("__"):
pass
else:
return False
if not file_exists(filename):
return False
if filename.startswith("common/") or filename.startswith("renpy/common/"):
return args.json_dump_common
if not filename.startswith("game/"):
return False
return True
result = { }
# Error flag.
result["error"] = error
# The JSON object we return.
location = { }
result["location"] = location
# Labels.
label = location["label"] = { }
for name, n in renpy.game.script.namemap.iteritems():
filename = n.filename
line = n.linenumber
if not isinstance(name, basestring):
continue
if not filter(name, filename):
continue
label[name] = [ filename, line ]
# Definitions.
define = location["define"] = { }
for name, filename, line in definitions:
if not filter(name, filename):
continue
define[name] = [ filename, line ]
# Screens.
screen = location["screen"] = { }
for name, filename, line in screens:
if not filter(name, filename):
continue
screen[name] = [ filename, line ]
# Transforms.
transform = location["transform"] = { }
for name, filename, line in transforms:
if not filter(name, filename):
continue
transform[name] = [ filename, line ]
# Code.
def get_line(o):
"""
Returns the filename and the first line number of the class or function o. Returns
None, None if unknown.
For a class, this doesn't return the first line number of the class, but rather
the line number of the first method in the class - hopefully.
"""
if inspect.isfunction(o):
return inspect.getfile(o), o.func_code.co_firstlineno
if inspect.ismethod(o):
return get_line(o.im_func)
return None, None
code = location["callable"] = { }
for modname, mod in sys.modules.items():
if mod is None:
continue
if modname == "store":
prefix = ""
elif modname.startswith("store."):
prefix = modname[6:] + "."
else:
continue
for name, o in mod.__dict__.items():
if inspect.isfunction(o):
try:
if inspect.getmodule(o) != mod:
continue
filename, line = get_line(o)
if filename is None:
continue
if not filter(name, filename):
continue
code[prefix + name] = [ filename, line ]
except:
continue
if inspect.isclass(o):
for methname, method in o.__dict__.iteritems():
try:
if inspect.getmodule(method) != mod:
continue
filename, line = get_line(method)
if filename is None:
continue
if not filter(name, filename):
continue
if not filter(methname, filename):
continue
code[prefix + name + "." + methname] = [ filename, line ]
except:
continue
# Add the build info from 00build.rpy, if it's available.
try:
result["build"] = renpy.store.build.dump() #@UndefinedVariable
except:
pass
if args.json_dump != "-":
with file(args.json_dump, "w") as f:
json.dump(result, f)
else:
json.dump(result, sys.stdout, indent=2)
| gpl-2.0 |
h4ck3rm1k3/MapNickAutotools | scons/scons-local-1.2.0/SCons/Tool/rpm.py | 12 | 4426 | """SCons.Tool.rpm
Tool-specific initialization for rpm.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
The rpm tool calls the rpmbuild command. The first and only argument should a
tar.gz consisting of the source file and a specfile.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/rpm.py 3842 2008/12/20 22:59:52 scons"
import os
import re
import shutil
import subprocess
import SCons.Builder
import SCons.Node.FS
import SCons.Util
import SCons.Action
import SCons.Defaults
def get_cmd(source, env):
tar_file_with_included_specfile = source
if SCons.Util.is_List(source):
tar_file_with_included_specfile = source[0]
return "%s %s %s"%(env['RPM'], env['RPMFLAGS'],
tar_file_with_included_specfile.abspath )
def build_rpm(target, source, env):
# create a temporary rpm build root.
tmpdir = os.path.join( os.path.dirname( target[0].abspath ), 'rpmtemp' )
if os.path.exists(tmpdir):
shutil.rmtree(tmpdir)
# now create the mandatory rpm directory structure.
for d in ['RPMS', 'SRPMS', 'SPECS', 'BUILD']:
os.makedirs( os.path.join( tmpdir, d ) )
# set the topdir as an rpmflag.
env.Prepend( RPMFLAGS = '--define \'_topdir %s\'' % tmpdir )
# now call rpmbuild to create the rpm package.
handle = subprocess.Popen(get_cmd(source, env),
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
shell=True)
output = handle.stdout.read()
status = handle.wait()
if status:
raise SCons.Errors.BuildError( node=target[0],
errstr=output,
filename=str(target[0]) )
else:
# XXX: assume that LC_ALL=c is set while running rpmbuild
output_files = re.compile( 'Wrote: (.*)' ).findall( output )
for output, input in zip( output_files, target ):
rpm_output = os.path.basename(output)
expected = os.path.basename(input.get_path())
assert expected == rpm_output, "got %s but expected %s" % (rpm_output, expected)
shutil.copy( output, input.abspath )
# cleanup before leaving.
shutil.rmtree(tmpdir)
return status
def string_rpm(target, source, env):
try:
return env['RPMCOMSTR']
except KeyError:
return get_cmd(source, env)
rpmAction = SCons.Action.Action(build_rpm, string_rpm)
RpmBuilder = SCons.Builder.Builder(action = SCons.Action.Action('$RPMCOM', '$RPMCOMSTR'),
source_scanner = SCons.Defaults.DirScanner,
suffix = '$RPMSUFFIX')
def generate(env):
"""Add Builders and construction variables for rpm to an Environment."""
try:
bld = env['BUILDERS']['Rpm']
except KeyError:
bld = RpmBuilder
env['BUILDERS']['Rpm'] = bld
env.SetDefault(RPM = 'LC_ALL=c rpmbuild')
env.SetDefault(RPMFLAGS = SCons.Util.CLVar('-ta'))
env.SetDefault(RPMCOM = rpmAction)
env.SetDefault(RPMSUFFIX = '.rpm')
def exists(env):
return env.Detect('rpmbuild')
| lgpl-2.1 |
ram8647/gcb-mobilecsp | modules/analytics/page_event_aggregator.py | 1 | 14112 | # 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.
"""Student aggregate collection of page enter/exit events."""
__author__ = ['Michael Gainer (mgainer@google.com)']
import collections
import datetime
import urlparse
from common import schema_fields
from models import courses
from models import transforms
from modules.analytics import student_aggregate
from tools import verify
UNIX_EPOCH = datetime.datetime(year=1970, month=1, day=1)
class AbstractPageEventMatcher(object):
def get_name(self):
"""Return a short string identifying this matcher."""
raise NotImplementedError()
def get_path_match(self):
"""Provide the exact portion of a location URL to match.
E.g., "/unit", "/course", etc.
"""
raise NotImplementedError()
def match(self, static_params, query_params):
"""Perform matching on the given query parameters.
This function is only called if the URL matches on the path
component. Return a 2-tuple of name and item_id (as described
above in PageEvent) if the given params match, or None if they
do not.
Args:
static_params: the value returned from build_static_params(), or None.
query_params: a dict of URL parameters.
Returns:
A 2-tuple of name, item_id or None.
"""
raise NotImplementedError()
@classmethod
def build_static_params(cls, unused_app_context):
"""Build any expensive-to-calculate items at course level.
If this class needs to pre-calculate any facts that would be expensive
to regenerate on each call to process_event(), those facts can be
returned as a single object from this method. If no such facts are
required, return None. This function is called once when each
map/reduce job starts. Any type of object may be returned.
Args:
unused_app_context: A standard CB application context object.
Returns:
Any.
"""
return None
class PathOnlyMatcher(AbstractPageEventMatcher):
def __init__(self, name, path_match):
self._name = name
self._path_match = path_match
def get_name(self):
return self._path_match
def get_path_match(self):
return self._path_match
def match(self, static_params, query_params):
return (self._name, None)
class AssessmentMatcher(AbstractPageEventMatcher):
@classmethod
def get_name(cls):
return 'assessment'
@classmethod
def get_path_match(cls):
return '/assessment'
@classmethod
def match(cls, static_params, query_params):
if 'name' in query_params:
return ('assessment', query_params['name'][0])
return None
class UnitMatcher(AbstractPageEventMatcher):
@classmethod
def get_name(cls):
return 'unit'
@classmethod
def get_path_match(cls):
return '/unit'
@classmethod
def match(cls, static_params, query_params):
if 'lesson' in query_params:
return 'lesson', query_params['lesson'][0]
if 'assessment' in query_params:
# Occurs for pre/post assessment in unit.
return 'assessment', query_params['assessment'][0]
# OK, now we get ambiguous. If we have a unit ID, then either we are
# going to be returning a lesson or asssessment, depending on what's
# first in the unit, or just the unit if the unit is marked as
# show-all-lessons. Here, we start to realize that the whole reliance
# on URLs is silly, and we wish that we were actually recording what
# was shown as part of the event. Particularly note that we are only
# best-guessing about what actually showed if we don't have full data,
# since we are looking at the course now and just believing that the
# arrangement hasn't changed since the event was emitted. This is
# reasonable, but not _necessarily_ true.
if 'unit' in query_params:
unit_id = query_params['unit'][0]
else:
unit_id = static_params['first_unit_id']
if unit_id in static_params:
return static_params[unit_id]
@classmethod
def build_static_params(cls, app_context):
"""Provide map of unit ID to result to report for partial unit URLs.
The result returned by this function is passed in to the map/reduce
job aggregating event data on a per-Student basis. It is retrieved
just above via "units_info = params['unit_page_disambiguation']".
When a URL referencing a unit is not fully specified, the first
item in the unit is shown. This function pre-computes the
result that get_mapper_result() should return when it has only
the unit ID provided.
Args:
app_context: Standard CB application context object.
Returns:
A map from Unit ID to a 2-tuple of page-type name and ID.
"""
ret = {}
course = courses.Course(None, app_context=app_context)
for unit in course.get_units_of_type(verify.UNIT_TYPE_UNIT):
if 'first_unit_id' not in ret:
ret['first_unit_id'] = str(unit.unit_id)
lessons = course.get_lessons(unit.unit_id)
if unit.show_contents_on_one_page:
ret[unit.unit_id] = ('unit', str(unit.unit_id))
elif unit.pre_assessment:
ret[unit.unit_id] = ('assessment', str(unit.pre_assessment))
elif lessons:
ret[unit.unit_id] = ('lesson', str(lessons[0].lesson_id))
elif unit.post_assessment:
ret[unit.unit_id] = ('assessment', str(unit.post_assessment))
else:
ret[unit.unit_id] = ('unit', str(unit.unit_id))
return ret
class PageEventAggregator(
student_aggregate.AbstractStudentAggregationComponent):
_matchers_by_name = {}
_matchers_by_path = collections.defaultdict(list)
@classmethod
def get_name(cls):
return 'page_event'
@classmethod
def get_event_sources_wanted(cls):
return ['enter-page', 'exit-page', 'tag-youtube-event']
@classmethod
def build_static_params(cls, app_context):
ret = {}
slug = app_context.get_slug()
if not slug or slug == '/':
slug = ''
ret['slug'] = slug
for name, matcher in cls._matchers_by_name.iteritems():
value = matcher.build_static_params(app_context)
if value:
ret[name] = value
return ret
@classmethod
def process_event(cls, event, static_params):
ret = []
data = transforms.loads(event.data)
url_parts = urlparse.urlparse(data.get('location', ''))
query_params = urlparse.parse_qs(url_parts.query)
path = url_parts.path.replace(static_params['slug'], '')
for matcher in cls._matchers_by_path.get(path, []):
matcher_params = static_params.get(matcher.get_name())
value = matcher.match(matcher_params, query_params)
if value:
name, item_id = value
timestamp = int(
(event.recorded_on - UNIX_EPOCH).total_seconds())
ret.append([name, item_id, timestamp, event.source])
return ret
@classmethod
def produce_aggregate(cls, course, student, static_value, event_items):
# separate events by location.
location_events = collections.defaultdict(list)
for sub_list in event_items:
for name, item_id, timestamp, source in sub_list:
location_events[(name, item_id)].append((timestamp, source))
# Sort events in each location by timestamp.
for events_list in location_events.itervalues():
events_list.sort()
# Cluster events into groups delimited by enter-page and exit-page
current_view = None
page_views = []
for location, events in location_events.iteritems():
name, item_id = location
for timestamp, source in events:
activity = {
'action': source,
'timestamp': timestamp,
}
if not current_view or source == 'enter-page':
current_view = {
'name': name,
'item_id': item_id,
'start': timestamp,
'activities': [activity]
}
page_views.append(current_view)
else:
current_view['activities'].append(activity)
if source == 'exit-page':
current_view['end'] = timestamp
current_view = None
page_views.sort(key=lambda v: v['start'])
return {'page_views': page_views}
@classmethod
def get_schema(cls):
activity = schema_fields.FieldRegistry('activity')
activity.add_property(schema_fields.SchemaField(
'action', 'Action', 'string',
description='A short string indicating the nature of the event, '
'such as "enter", "exit", "submit_assessment", "check_answer"'))
activity.add_property(schema_fields.SchemaField(
'timestamp', 'Timestamp', 'timestamp',
description='Timestamp when the event occurred'))
page_view = schema_fields.FieldRegistry('page_view')
page_view.add_property(schema_fields.SchemaField(
'name', 'Name', 'string',
description='Name of the kind of page being shown. This is a '
'short string, such as "unit", "lesson", "enroll", "unenroll", '
'etc. The full list of these can be found in '
'coursebuilder/modules/analytics/student_events.py.'))
page_view.add_property(schema_fields.SchemaField(
'item_id', 'Item ID', 'string', optional=True,
description='Identity of the kind of page in question, if '
'the page may have more than one instance. E.g., units and '
'lessons have IDs; the forum, enroll and unenroll pages do not.'))
page_view.add_property(schema_fields.SchemaField(
'start', 'Start', 'timestamp',
description='Timestamp when the page was entered.'))
page_view.add_property(schema_fields.SchemaField(
'end', 'End', 'timestamp', optional=True,
description='Timestamp when the page was exited. '
'Note that this field may be blank if we are missing '
'the exit event. Also note that this field may be '
'extremely misleading - users may leave the page open while '
'doing other things. You should arrange to clip this value '
'at some reasonable maximum, and impute either the average '
'or the median value when this field is blank.'))
page_view.add_property(schema_fields.FieldArray(
'activities', 'Activities', item_type=activity))
page_views = schema_fields.FieldArray(
'page_views', 'Page Views', item_type=page_view,
description='User activity events for this student, grouped by '
'page enter/exit.')
return page_views
@classmethod
def register_matcher(cls, matcher):
name = matcher.get_name()
if name in cls._matchers_by_name:
raise ValueError(
'Page event matcher named "%s" already registered.' % name)
cls._matchers_by_name[name] = matcher
cls._matchers_by_path[matcher.get_path_match()].append(matcher)
@classmethod
def unregister_matcher(cls, matcher):
name = matcher.get_name()
if name in cls._matchers_by_name:
matcher = cls._matchers_by_name[name]
del cls._matchers_by_name[name]
for matcher_list in cls._matcher_by_path.itervalues():
matcher_list.remove(matcher)
def register_base_course_matchers():
PageEventAggregator.register_matcher(UnitMatcher)
PageEventAggregator.register_matcher(AssessmentMatcher)
PageEventAggregator.register_matcher(
PathOnlyMatcher('course', '/course'))
PageEventAggregator.register_matcher(
PathOnlyMatcher('enroll', '/register_matcher'))
PageEventAggregator.register_matcher(
PathOnlyMatcher('announcements', '/announcements'))
PageEventAggregator.register_matcher(
PathOnlyMatcher('forum', '/forum'))
PageEventAggregator.register_matcher(
PathOnlyMatcher('answer', '/answer'))
PageEventAggregator.register_matcher(
PathOnlyMatcher('unenroll', '/student/unenroll'))
def unregister_base_course_matchers():
PageEventAggregator.unregister_matcher(UnitMatcher)
PageEventAggregator.unregister_matcher(AssessmentMatcher)
PageEventAggregator.unregister_matcher(
PathOnlyMatcher('course', '/course'))
PageEventAggregator.unregister_matcher(
PathOnlyMatcher('enroll', '/register_matcher'))
PageEventAggregator.unregister_matcher(
PathOnlyMatcher('announcements', '/announcements'))
PageEventAggregator.unregister_matcher(
PathOnlyMatcher('forum', '/forum'))
PageEventAggregator.unregister_matcher(
PathOnlyMatcher('answer', '/answer'))
PageEventAggregator.unregister_matcher(
PathOnlyMatcher('unenroll', '/student/unenroll'))
| apache-2.0 |
flyher/pymo | symbian/PythonForS60/module-repo/standard-modules/xml/sax/xmlreader.py | 28 | 12656 | """An XML Reader is the SAX 2 name for an XML parser. XML Parsers
should be based on this code. """
import handler
from _exceptions import SAXNotSupportedException, SAXNotRecognizedException
# ===== XMLREADER =====
class XMLReader:
"""Interface for reading an XML document using callbacks.
XMLReader is the interface that an XML parser's SAX2 driver must
implement. This interface allows an application to set and query
features and properties in the parser, to register event handlers
for document processing, and to initiate a document parse.
All SAX interfaces are assumed to be synchronous: the parse
methods must not return until parsing is complete, and readers
must wait for an event-handler callback to return before reporting
the next event."""
def __init__(self):
self._cont_handler = handler.ContentHandler()
self._dtd_handler = handler.DTDHandler()
self._ent_handler = handler.EntityResolver()
self._err_handler = handler.ErrorHandler()
def parse(self, source):
"Parse an XML document from a system identifier or an InputSource."
raise NotImplementedError("This method must be implemented!")
def getContentHandler(self):
"Returns the current ContentHandler."
return self._cont_handler
def setContentHandler(self, handler):
"Registers a new object to receive document content events."
self._cont_handler = handler
def getDTDHandler(self):
"Returns the current DTD handler."
return self._dtd_handler
def setDTDHandler(self, handler):
"Register an object to receive basic DTD-related events."
self._dtd_handler = handler
def getEntityResolver(self):
"Returns the current EntityResolver."
return self._ent_handler
def setEntityResolver(self, resolver):
"Register an object to resolve external entities."
self._ent_handler = resolver
def getErrorHandler(self):
"Returns the current ErrorHandler."
return self._err_handler
def setErrorHandler(self, handler):
"Register an object to receive error-message events."
self._err_handler = handler
def setLocale(self, locale):
"""Allow an application to set the locale for errors and warnings.
SAX parsers are not required to provide localization for errors
and warnings; if they cannot support the requested locale,
however, they must throw a SAX exception. Applications may
request a locale change in the middle of a parse."""
raise SAXNotSupportedException("Locale support not implemented")
def getFeature(self, name):
"Looks up and returns the state of a SAX2 feature."
raise SAXNotRecognizedException("Feature '%s' not recognized" % name)
def setFeature(self, name, state):
"Sets the state of a SAX2 feature."
raise SAXNotRecognizedException("Feature '%s' not recognized" % name)
def getProperty(self, name):
"Looks up and returns the value of a SAX2 property."
raise SAXNotRecognizedException("Property '%s' not recognized" % name)
def setProperty(self, name, value):
"Sets the value of a SAX2 property."
raise SAXNotRecognizedException("Property '%s' not recognized" % name)
class IncrementalParser(XMLReader):
"""This interface adds three extra methods to the XMLReader
interface that allow XML parsers to support incremental
parsing. Support for this interface is optional, since not all
underlying XML parsers support this functionality.
When the parser is instantiated it is ready to begin accepting
data from the feed method immediately. After parsing has been
finished with a call to close the reset method must be called to
make the parser ready to accept new data, either from feed or
using the parse method.
Note that these methods must _not_ be called during parsing, that
is, after parse has been called and before it returns.
By default, the class also implements the parse method of the XMLReader
interface using the feed, close and reset methods of the
IncrementalParser interface as a convenience to SAX 2.0 driver
writers."""
def __init__(self, bufsize=2**16):
self._bufsize = bufsize
XMLReader.__init__(self)
def parse(self, source):
import saxutils
source = saxutils.prepare_input_source(source)
self.prepareParser(source)
file = source.getByteStream()
buffer = file.read(self._bufsize)
while buffer != "":
self.feed(buffer)
buffer = file.read(self._bufsize)
self.close()
def feed(self, data):
"""This method gives the raw XML data in the data parameter to
the parser and makes it parse the data, emitting the
corresponding events. It is allowed for XML constructs to be
split across several calls to feed.
feed may raise SAXException."""
raise NotImplementedError("This method must be implemented!")
def prepareParser(self, source):
"""This method is called by the parse implementation to allow
the SAX 2.0 driver to prepare itself for parsing."""
raise NotImplementedError("prepareParser must be overridden!")
def close(self):
"""This method is called when the entire XML document has been
passed to the parser through the feed method, to notify the
parser that there are no more data. This allows the parser to
do the final checks on the document and empty the internal
data buffer.
The parser will not be ready to parse another document until
the reset method has been called.
close may raise SAXException."""
raise NotImplementedError("This method must be implemented!")
def reset(self):
"""This method is called after close has been called to reset
the parser so that it is ready to parse new documents. The
results of calling parse or feed after close without calling
reset are undefined."""
raise NotImplementedError("This method must be implemented!")
# ===== LOCATOR =====
class Locator:
"""Interface for associating a SAX event with a document
location. A locator object will return valid results only during
calls to DocumentHandler methods; at any other time, the
results are unpredictable."""
def getColumnNumber(self):
"Return the column number where the current event ends."
return -1
def getLineNumber(self):
"Return the line number where the current event ends."
return -1
def getPublicId(self):
"Return the public identifier for the current event."
return None
def getSystemId(self):
"Return the system identifier for the current event."
return None
# ===== INPUTSOURCE =====
class InputSource:
"""Encapsulation of the information needed by the XMLReader to
read entities.
This class may include information about the public identifier,
system identifier, byte stream (possibly with character encoding
information) and/or the character stream of an entity.
Applications will create objects of this class for use in the
XMLReader.parse method and for returning from
EntityResolver.resolveEntity.
An InputSource belongs to the application, the XMLReader is not
allowed to modify InputSource objects passed to it from the
application, although it may make copies and modify those."""
def __init__(self, system_id = None):
self.__system_id = system_id
self.__public_id = None
self.__encoding = None
self.__bytefile = None
self.__charfile = None
def setPublicId(self, public_id):
"Sets the public identifier of this InputSource."
self.__public_id = public_id
def getPublicId(self):
"Returns the public identifier of this InputSource."
return self.__public_id
def setSystemId(self, system_id):
"Sets the system identifier of this InputSource."
self.__system_id = system_id
def getSystemId(self):
"Returns the system identifier of this InputSource."
return self.__system_id
def setEncoding(self, encoding):
"""Sets the character encoding of this InputSource.
The encoding must be a string acceptable for an XML encoding
declaration (see section 4.3.3 of the XML recommendation).
The encoding attribute of the InputSource is ignored if the
InputSource also contains a character stream."""
self.__encoding = encoding
def getEncoding(self):
"Get the character encoding of this InputSource."
return self.__encoding
def setByteStream(self, bytefile):
"""Set the byte stream (a Python file-like object which does
not perform byte-to-character conversion) for this input
source.
The SAX parser will ignore this if there is also a character
stream specified, but it will use a byte stream in preference
to opening a URI connection itself.
If the application knows the character encoding of the byte
stream, it should set it with the setEncoding method."""
self.__bytefile = bytefile
def getByteStream(self):
"""Get the byte stream for this input source.
The getEncoding method will return the character encoding for
this byte stream, or None if unknown."""
return self.__bytefile
def setCharacterStream(self, charfile):
"""Set the character stream for this input source. (The stream
must be a Python 2.0 Unicode-wrapped file-like that performs
conversion to Unicode strings.)
If there is a character stream specified, the SAX parser will
ignore any byte stream and will not attempt to open a URI
connection to the system identifier."""
self.__charfile = charfile
def getCharacterStream(self):
"Get the character stream for this input source."
return self.__charfile
# ===== ATTRIBUTESIMPL =====
class AttributesImpl:
def __init__(self, attrs):
"""Non-NS-aware implementation.
attrs should be of the form {name : value}."""
self._attrs = attrs
def getLength(self):
return len(self._attrs)
def getType(self, name):
return "CDATA"
def getValue(self, name):
return self._attrs[name]
def getValueByQName(self, name):
return self._attrs[name]
def getNameByQName(self, name):
if not self._attrs.has_key(name):
raise KeyError, name
return name
def getQNameByName(self, name):
if not self._attrs.has_key(name):
raise KeyError, name
return name
def getNames(self):
return self._attrs.keys()
def getQNames(self):
return self._attrs.keys()
def __len__(self):
return len(self._attrs)
def __getitem__(self, name):
return self._attrs[name]
def keys(self):
return self._attrs.keys()
def has_key(self, name):
return self._attrs.has_key(name)
def __contains__(self, name):
return self._attrs.has_key(name)
def get(self, name, alternative=None):
return self._attrs.get(name, alternative)
def copy(self):
return self.__class__(self._attrs)
def items(self):
return self._attrs.items()
def values(self):
return self._attrs.values()
# ===== ATTRIBUTESNSIMPL =====
class AttributesNSImpl(AttributesImpl):
def __init__(self, attrs, qnames):
"""NS-aware implementation.
attrs should be of the form {(ns_uri, lname): value, ...}.
qnames of the form {(ns_uri, lname): qname, ...}."""
self._attrs = attrs
self._qnames = qnames
def getValueByQName(self, name):
for (nsname, qname) in self._qnames.items():
if qname == name:
return self._attrs[nsname]
raise KeyError, name
def getNameByQName(self, name):
for (nsname, qname) in self._qnames.items():
if qname == name:
return nsname
raise KeyError, name
def getQNameByName(self, name):
return self._qnames[name]
def getQNames(self):
return self._qnames.values()
def copy(self):
return self.__class__(self._attrs, self._qnames)
def _test():
XMLReader()
IncrementalParser()
Locator()
if __name__ == "__main__":
_test()
| mit |
diefenbach/django-lfs | lfs/manage/discounts/views.py | 1 | 11722 | import json
# django imports
from django.contrib.auth.decorators import permission_required
from django.core.exceptions import ObjectDoesNotExist
from django.core.paginator import Paginator, EmptyPage
from django.urls import reverse
from django.db.models import Q
from django.http import HttpResponseRedirect
from django.http import HttpResponse
from django.shortcuts import render
from django.template.loader import render_to_string
from django.utils.translation import ugettext_lazy as _
from django.views.decorators.http import require_POST
# lfs imports
from lfs.catalog.models import Category, Product
import lfs.core.utils
import lfs.criteria.utils
from lfs.caching.utils import lfs_get_object_or_404
from lfs.core.utils import LazyEncoder
from lfs.discounts.models import Discount
from lfs.manage.discounts.forms import DiscountForm
from lfs.manufacturer.models import Manufacturer
@permission_required("core.manage_shop")
def manage_discounts(request):
"""Dispatches to the first discount or to the add discount method
form if there is no discount yet.
"""
try:
discount = Discount.objects.all()[0]
except IndexError:
url = reverse("lfs_manage_no_discounts")
else:
url = reverse("lfs_manage_discount", kwargs={"id": discount.id})
return HttpResponseRedirect(url)
@permission_required("core.manage_shop")
def manage_discount(request, id, template_name="manage/discounts/discount.html"):
"""The main view to manage the discount with given id.
This view collects the various parts of the discount form (data, criteria,
and displays them.
"""
try:
discount = Discount.objects.get(pk=id)
except Discount.DoesNotExist:
return HttpResponseRedirect(reverse("lfs_manage_discounts"))
return render(request, template_name, {
"discount": discount,
"navigation": navigation(request),
"data": discount_data(request, id),
"products": products_tab(request, id),
"criteria": discount_criteria(request, id),
})
@permission_required("core.manage_shop")
def no_discounts(request, template_name="manage/discounts/no_discounts.html"):
"""Displays no discounts view
"""
return render(request, template_name, {})
# Parts of the manage discount view.
@permission_required("core.manage_shop")
def navigation(request, template_name="manage/discounts/navigation.html"):
"""Returns the navigation for the discount view.
"""
try:
current_id = int(request.path.split("/")[-1])
except ValueError:
current_id = ""
return render_to_string(template_name, request=request, context={
"current_id": current_id,
"discounts": Discount.objects.all(),
})
@permission_required("core.manage_shop")
def discount_data(request, id, template_name="manage/discounts/data.html"):
"""Returns the discount data as html.
This view is used as a part within the manage discount view.
"""
discount = Discount.objects.get(pk=id)
return render_to_string(template_name, request=request, context={
"form": DiscountForm(instance=discount),
"discount": discount,
})
@permission_required("core.manage_shop")
def discount_criteria(request, id, template_name="manage/discounts/criteria.html"):
"""Returns the criteria of the discount with passed id as HTML.
This view is used as a part within the manage discount view.
"""
discount = Discount.objects.get(pk=id)
criteria = []
position = 0
for criterion_object in discount.get_criteria():
position += 10
criterion_html = criterion_object.get_content_object().render(request, position)
criteria.append(criterion_html)
return render_to_string(template_name, request=request, context={
"discount": discount,
"criteria": criteria,
})
# Actions
@permission_required("core.manage_shop")
def add_discount(request, template_name="manage/discounts/add_discount.html"):
"""Provides an add form and saves a new discount method.
"""
if request.method == "POST":
form = DiscountForm(data=request.POST, files=request.FILES)
if form.is_valid():
new_discount = form.save()
return lfs.core.utils.set_message_cookie(
url=reverse("lfs_manage_discount", kwargs={"id": new_discount.id}),
msg=_(u"Discount method has been added."),
)
else:
form = DiscountForm()
return render(request, template_name, {
"navigation": navigation(request),
"form": form,
"came_from": (request.POST if request.method == 'POST' else request.GET).get("came_from", reverse("lfs_manage_discounts")),
})
@permission_required("core.manage_shop")
def save_discount_criteria(request, id):
"""Saves the criteria for the discount with given id. The criteria
are passed via request body.
"""
discount = lfs_get_object_or_404(Discount, pk=id)
discount.save_criteria(request)
html = [["#criteria", discount_criteria(request, id)]]
result = json.dumps({
"html": html,
"message": _("Changes have been saved."),
}, cls=LazyEncoder)
return HttpResponse(result, content_type='application/json')
@permission_required("core.manage_shop")
def save_discount_data(request, id):
"""Saves discount data (via request body) to the discount with passed
id.
This is called via an AJAX request and returns JSON encoded data.
"""
discount = Discount.objects.get(pk=id)
discount_form = DiscountForm(instance=discount, data=request.POST)
if discount_form.is_valid():
discount_form.save()
return lfs.core.utils.set_message_cookie(
url=reverse("lfs_manage_discount", kwargs={"id": id}),
msg=_(u"Discount data has been saved."),
)
@permission_required("core.manage_shop")
@require_POST
def delete_discount(request, id):
"""Deletes discount with passed id.
"""
try:
discount = Discount.objects.get(pk=id)
except ObjectDoesNotExist:
pass
else:
discount.delete()
return lfs.core.utils.set_message_cookie(
url=reverse("lfs_manage_discounts"),
msg=_(u"Discount has been deleted."),
)
@permission_required("core.manage_shop")
def assign_products(request, discount_id):
"""Assign products to given property group with given property_group_id.
"""
discount = lfs_get_object_or_404(Discount, pk=discount_id)
for temp_id in request.POST.keys():
if temp_id.startswith("product"):
temp_id = temp_id.split("-")[1]
product = Product.objects.get(pk=temp_id)
discount.products.add(product)
html = [["#products-inline", products_inline(request, discount_id, as_string=True)]]
result = json.dumps({
"html": html,
"message": _(u"Products have been assigned.")
}, cls=LazyEncoder)
return HttpResponse(result, content_type='application/json')
@permission_required("core.manage_shop")
def remove_products(request, discount_id):
"""Remove products from given property group with given property_group_id.
"""
discount = lfs_get_object_or_404(Discount, pk=discount_id)
for temp_id in request.POST.keys():
if temp_id.startswith("product"):
temp_id = temp_id.split("-")[1]
product = Product.objects.get(pk=temp_id)
discount.products.remove(product)
html = [["#products-inline", products_inline(request, discount_id, as_string=True)]]
result = json.dumps({
"html": html,
"message": _(u"Products have been removed.")
}, cls=LazyEncoder)
return HttpResponse(result, content_type='application/json')
@permission_required("core.manage_shop")
def products_tab(request, discount_id, template_name="manage/discounts/products.html"):
"""Renders the products tab of the property groups management views.
"""
discount = Discount.objects.get(pk=discount_id)
inline = products_inline(request, discount_id, as_string=True)
return render_to_string(template_name, request=request, context={
"discount": discount,
"products_inline": inline,
})
@permission_required("core.manage_shop")
def products_inline(request, discount_id, as_string=False,
template_name="manage/discounts/products_inline.html"):
"""Renders the products tab of the property groups management views.
"""
discount = Discount.objects.get(pk=discount_id)
discount_products = discount.products.all().select_related('parent')
r = request.POST if request.method == 'POST' else request.GET
s = request.session
# If we get the parameter ``keep-filters`` or ``page`` we take the
# filters out of the request resp. session. The request takes precedence.
# The page parameter is given if the user clicks on the next/previous page
# links. The ``keep-filters`` parameters is given is the users adds/removes
# products. In this way we keeps the current filters when we needed to. If
# the whole page is reloaded there is no ``keep-filters`` or ``page`` and
# all filters are reset as they should.
if r.get("keep-filters") or r.get("page"):
page = r.get("page", s.get("discount_page", 1))
filter_ = r.get("filter", s.get("filter"))
category_filter = r.get("products_category_filter",
s.get("products_category_filter"))
manufacturer_filter = r.get("products_manufacturer_filter",
s.get("products_manufacturer_filter"))
else:
page = r.get("page", 1)
filter_ = r.get("filter")
category_filter = r.get("products_category_filter")
manufacturer_filter = r.get("products_manufacturer_filter")
# The current filters are saved in any case for later use.
s["discount_page"] = page
s["filter"] = filter_
s["products_category_filter"] = category_filter
s["products_manufacturer_filter"] = manufacturer_filter
filters = Q()
if filter_:
filters &= Q(name__icontains=filter_)
if category_filter:
if category_filter == "None":
filters &= Q(categories=None)
elif category_filter == "All":
pass
else:
# First we collect all sub categories and using the `in` operator
category = lfs_get_object_or_404(Category, pk=category_filter)
categories = [category]
categories.extend(category.get_all_children())
filters &= Q(categories__in=categories)
if manufacturer_filter:
if manufacturer_filter == "None":
filters &= Q(manufacturer=None)
elif manufacturer_filter == "All":
pass
else:
# First we collect all sub categories and using the `in` operator
manufacturer = lfs_get_object_or_404(Manufacturer, pk=manufacturer_filter)
filters &= Q(manufacturer=manufacturer)
products = Product.objects.select_related('parent').filter(filters)
paginator = Paginator(products.exclude(pk__in=discount_products), 25)
try:
page = paginator.page(page)
except EmptyPage:
page = 0
result = render_to_string(template_name, request=request, context={
"discount": discount,
"discount_products": discount_products,
"page": page,
"paginator": paginator,
"filter": filter_
})
if as_string:
return result
else:
return HttpResponse(
json.dumps({
"html": [["#products-inline", result]],
}), content_type='application/json')
| bsd-3-clause |
SnappleCap/oh-mainline | mysite/profile/migrations/0032_put_the_last_polled_field_back_into_person.py | 17 | 5659 | # This file is part of OpenHatch.
# Copyright (C) 2009 OpenHatch, Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from south.db import db
from django.db import models
from mysite.profile.models import *
class Migration:
def forwards(self, orm):
# Adding field 'Person.last_polled'
db.add_column('profile_person', 'last_polled', models.DateTimeField(default=datetime.datetime(1970, 1, 1, 0, 0)))
def backwards(self, orm):
# Deleting field 'Person.last_polled'
db.delete_column('profile_person', 'last_polled')
models = {
'profile.person': {
'gotten_name_from_ohloh': ('models.BooleanField', [], {'default': 'False'}),
'id': ('models.AutoField', [], {'primary_key': 'True'}),
'interested_in_working_on': ('models.CharField', [], {'default': "''", 'max_length': '1024'}),
'last_polled': ('models.DateTimeField', [], {'default': 'datetime.datetime(1970, 1, 1, 0, 0)'}),
'ohloh_grab_completed': ('models.BooleanField', [], {'default': 'False'}),
'poll_on_next_web_view': ('models.BooleanField', [], {'default': 'True'}),
'user': ('models.ForeignKey', ["orm['auth.User']"], {'unique': 'True'})
},
'profile.link_person_tag': {
'id': ('models.AutoField', [], {'primary_key': 'True'}),
'person': ('models.ForeignKey', ["orm['profile.Person']"], {}),
'source': ('models.CharField', [], {'max_length': '200'}),
'tag': ('models.ForeignKey', ["orm['profile.Tag']"], {})
},
'profile.tag': {
'id': ('models.AutoField', [], {'primary_key': 'True'}),
'tag_type': ('models.ForeignKey', ["orm['profile.TagType']"], {}),
'text': ('models.CharField', [], {'max_length': '50'})
},
'profile.link_projectexp_tag': {
'Meta': {'unique_together': "[('tag','project_exp','source'),]"},
'favorite': ('models.BooleanField', [], {'default': 'False'}),
'id': ('models.AutoField', [], {'primary_key': 'True'}),
'project_exp': ('models.ForeignKey', ["orm['profile.ProjectExp']"], {}),
'source': ('models.CharField', [], {'max_length': '200'}),
'tag': ('models.ForeignKey', ["orm['profile.Tag']"], {})
},
'profile.sourceforgeperson': {
'id': ('models.AutoField', [], {'primary_key': 'True'}),
'username': ('models.CharField', [], {'max_length': '200'})
},
'profile.link_project_tag': {
'id': ('models.AutoField', [], {'primary_key': 'True'}),
'project': ('models.ForeignKey', ["orm['search.Project']"], {}),
'source': ('models.CharField', [], {'max_length': '200'}),
'tag': ('models.ForeignKey', ["orm['profile.Tag']"], {})
},
'profile.sourceforgeproject': {
'id': ('models.AutoField', [], {'primary_key': 'True'}),
'unixname': ('models.CharField', [], {'max_length': '200'})
},
'search.project': {
'_stub': True,
'id': ('models.AutoField', [], {'primary_key': 'True'})
},
'auth.user': {
'_stub': True,
'id': ('models.AutoField', [], {'primary_key': 'True'})
},
'profile.link_sf_proj_dude_fm': {
'Meta': {'unique_together': "[('person','project'),]"},
'date_collected': ('models.DateTimeField', [], {}),
'id': ('models.AutoField', [], {'primary_key': 'True'}),
'is_admin': ('models.BooleanField', [], {'default': 'False'}),
'person': ('models.ForeignKey', ["orm['profile.SourceForgePerson']"], {}),
'position': ('models.CharField', [], {'max_length': '200'}),
'project': ('models.ForeignKey', ["orm['profile.SourceForgeProject']"], {})
},
'profile.tagtype': {
'id': ('models.AutoField', [], {'primary_key': 'True'}),
'name': ('models.CharField', [], {'max_length': '100'}),
'prefix': ('models.CharField', [], {'max_length': '20'})
},
'profile.projectexp': {
'description': ('models.TextField', [], {}),
'favorite': ('models.BooleanField', [], {'default': '0'}),
'id': ('models.AutoField', [], {'primary_key': 'True'}),
'man_months': ('models.PositiveIntegerField', [], {'null': 'True'}),
'person': ('models.ForeignKey', ["orm['profile.Person']"], {}),
'person_role': ('models.CharField', [], {'max_length': '200'}),
'primary_language': ('models.CharField', [], {'max_length': '200', 'null': 'True'}),
'project': ('models.ForeignKey', ["orm['search.Project']"], {}),
'source': ('models.CharField', [], {'max_length': '100', 'null': 'True'}),
'url': ('models.URLField', [], {'max_length': '200', 'null': 'True'})
}
}
complete_apps = ['profile']
| agpl-3.0 |
Intel-Corporation/tensorflow | tensorflow/python/keras/optimizer_v2/adamax.py | 8 | 7131 | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Adamax for TensorFlow."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import ops
from tensorflow.python.keras import backend_config
from tensorflow.python.keras.optimizer_v2 import optimizer_v2
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.training import training_ops
from tensorflow.python.util.tf_export import keras_export
@keras_export('keras.optimizers.Adamax')
class Adamax(optimizer_v2.OptimizerV2):
"""Optimizer that implements the Adamax algorithm.
It is a variant of Adam based on the infinity norm.
Default parameters follow those provided in the paper.
Adamax is sometimes superior to adam, specially in models with embeddings.
References
see Section 7 of [Kingma et al., 2014](http://arxiv.org/abs/1412.6980)
([pdf](http://arxiv.org/pdf/1412.6980.pdf)).
"""
def __init__(self,
learning_rate=0.001,
beta_1=0.9,
beta_2=0.999,
epsilon=1e-7,
name='Adamax',
**kwargs):
"""Construct a new Adamax optimizer.
Initialization:
```
m_0 <- 0 (Initialize initial 1st moment vector)
v_0 <- 0 (Initialize the exponentially weighted infinity norm)
t <- 0 (Initialize timestep)
```
The update rule for `variable` with gradient `g` uses an optimization
described at the end of section 7.1 of the paper:
```
t <- t + 1
m_t <- beta1 * m_{t-1} + (1 - beta1) * g
v_t <- max(beta2 * v_{t-1}, abs(g))
variable <- variable - learning_rate / (1 - beta1^t) * m_t / (v_t + epsilon)
```
Similar to AdamOptimizer, the epsilon is added for numerical stability
(especially to get rid of division by zero when v_t = 0).
Contrast to AdamOptimizer, the sparse implementation of this algorithm
(used when the gradient is an IndexedSlices object, typically because of
`tf.gather` or an embedding lookup in the forward pass) only updates
variable slices and corresponding `m_t`, `v_t` terms when that part of
the variable was used in the forward pass. This means that the sparse
behavior is contrast to the dense behavior (similar to some momentum
implementations which ignore momentum unless a variable slice was actually
used).
Args:
learning_rate: A Tensor or a floating point value. The learning rate.
beta_1: A float value or a constant float tensor. The exponential decay
rate for the 1st moment estimates.
beta_2: A float value or a constant float tensor. The exponential decay
rate for the exponentially weighted infinity norm.
epsilon: A small constant for numerical stability.
name: Optional name for the operations created when applying gradients.
Defaults to "Adamax".
**kwargs: keyword arguments. Allowed to be {`clipnorm`, `clipvalue`, `lr`,
`decay`}. `clipnorm` is clip gradients by norm; `clipvalue` is clip
gradients by value, `decay` is included for backward compatibility to
allow time inverse decay of learning rate. `lr` is included for backward
compatibility, recommended to use `learning_rate` instead.
"""
if epsilon is None:
epsilon = backend_config.epsilon()
super(Adamax, self).__init__(name, **kwargs)
self._set_hyper('learning_rate', kwargs.get('lr', learning_rate))
self._set_hyper('decay', self._initial_decay)
self._set_hyper('beta_1', beta_1)
self._set_hyper('beta_2', beta_2)
self._set_hyper('epsilon', epsilon)
def _create_slots(self, var_list):
# Separate for-loops to respect the ordering of slot variables from v1.
for var in var_list:
self.add_slot(var, 'm') # Create slots for the first moments.
for var in var_list:
self.add_slot(var, 'v') # Create slots for the second moments.
def _resource_apply_dense(self, grad, var):
var_dtype = var.dtype.base_dtype
lr_t = self._decayed_lr(var_dtype)
m = self.get_slot(var, 'm')
v = self.get_slot(var, 'v')
beta_1_t = self._get_hyper('beta_1', var_dtype)
beta_2_t = self._get_hyper('beta_2', var_dtype)
local_step = math_ops.cast(self.iterations + 1, var_dtype)
beta_1_power = math_ops.pow(beta_1_t, local_step)
return training_ops.resource_apply_ada_max(
var.handle,
m.handle,
v.handle,
beta_1_power,
lr_t,
beta_1_t,
beta_2_t,
self._get_hyper('epsilon', var_dtype),
grad,
use_locking=self._use_locking)
def _resource_apply_sparse(self, grad, var, indices):
var_dtype = var.dtype.base_dtype
lr_t = self._decayed_lr(var_dtype)
beta_1_t = self._get_hyper('beta_1', var_dtype)
beta_2_t = self._get_hyper('beta_2', var_dtype)
local_step = math_ops.cast(self.iterations + 1, var_dtype)
beta_1_power = math_ops.pow(beta_1_t, local_step)
epsilon_t = self._get_hyper('epsilon', var_dtype)
# m_t = beta1 * m + (1 - beta1) * g_t
m = self.get_slot(var, 'm')
m_slice = array_ops.gather(m, indices)
m_t_slice = m_slice * beta_1_t + grad * (1 - beta_1_t)
with ops.control_dependencies([m_t_slice]):
m_t = self._resource_scatter_update(m, indices, m_t_slice)
# u_t = max(beta2 * u, abs(g_t))
v = self.get_slot(var, 'v')
v_slice = array_ops.gather(v, indices)
v_t_slice = math_ops.maximum(v_slice * beta_2_t, math_ops.abs(grad))
with ops.control_dependencies([v_t_slice]):
v_t = self._resource_scatter_update(v, indices, v_t_slice)
# theta_t = theta - lr / (1 - beta1^t) * m_t / u_t
var_slice = -lr_t / (1 - beta_1_power) * (
m_t_slice / (v_t_slice + epsilon_t))
with ops.control_dependencies([var_slice]):
var_update = self._resource_scatter_add(var, indices, var_slice)
return control_flow_ops.group(*[var_update, m_t, v_t])
def get_config(self):
config = super(Adamax, self).get_config()
config.update({
'learning_rate': self._serialize_hyperparameter('learning_rate'),
'decay': self._serialize_hyperparameter('decay'),
'beta_1': self._serialize_hyperparameter('beta_1'),
'beta_2': self._serialize_hyperparameter('beta_2'),
'epsilon': self._serialize_hyperparameter('epsilon'),
})
return config
| apache-2.0 |
TridentSDK/TridentSDK | scripts/ids/items.py | 1 | 1853 | #!/usr/bin/env python3
import bs4
import json
import urllib.request
from collections import OrderedDict
url = '''
http://minecraft.gamepedia.com/api.php?action=parse&format=json&prop=text&title=Data_values&text=%7B%7B%3AData+values%2FItem+IDs%7D%7D
'''.strip()
def get_items_data():
req = urllib.request.Request(url)
req.headers['User-Agent'] = 'Trident/ItemID Getter'
with urllib.request.urlopen(req) as u:
content = u.read()
json_content = json.loads(content)
table_content = json_content['parse']['text']['*']
soup = bs4.BeautifulSoup(table_content, 'html.parser')
items = []
known_sups = {
'D': "Use the item's Damage field to define its durability.",
'B': "Requires additional data in the item's Damage field to fully define the inventory item."
}
for table in soup.find_all('table'):
for table_row in table.find_all('tr')[1:]:
tds = table_row.find_all('td')
id = int(tds[1].get_text())
string_id = tds[3].get_text()
a_tag = tds[4].find('a')
if a_tag is None:
continue
name = a_tag.get_text()
sup_data = []
for span_tag in tds[4].select('sup a span'):
sup_code = span_tag.get_text()
if sup_code not in known_sups:
sup_description = span_tag['title']
known_sups[sup_code] = sup_description
sup_data.append(sup_code)
items.append({
'id': id,
'string_id': string_id,
'name': name,
'sup': sup_data
})
return OrderedDict([
('items', items),
('sup_codes', known_sups),
])
if __name__ == '__main__':
print(json.dumps(get_items_data()))
| apache-2.0 |
NathanAtSamraksh/dart-linux | Documentation/networking/cxacru-cf.py | 14668 | 1626 | #!/usr/bin/env python
# Copyright 2009 Simon Arlott
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2 of the License, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
# more details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 59
# Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
# Usage: cxacru-cf.py < cxacru-cf.bin
# Output: values string suitable for the sysfs adsl_config attribute
#
# Warning: cxacru-cf.bin with MD5 hash cdbac2689969d5ed5d4850f117702110
# contains mis-aligned values which will stop the modem from being able
# to make a connection. If the first and last two bytes are removed then
# the values become valid, but the modulation will be forced to ANSI
# T1.413 only which may not be appropriate.
#
# The original binary format is a packed list of le32 values.
import sys
import struct
i = 0
while True:
buf = sys.stdin.read(4)
if len(buf) == 0:
break
elif len(buf) != 4:
sys.stdout.write("\n")
sys.stderr.write("Error: read {0} not 4 bytes\n".format(len(buf)))
sys.exit(1)
if i > 0:
sys.stdout.write(" ")
sys.stdout.write("{0:x}={1}".format(i, struct.unpack("<I", buf)[0]))
i += 1
sys.stdout.write("\n")
| gpl-2.0 |
caisq/tensorflow | tensorflow/python/ops/collective_ops.py | 25 | 5901 | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""TensorFlow collective Ops."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import device
from tensorflow.python.ops import gen_collective_ops
def all_reduce(t, group_size, group_key, instance_key, merge_op, final_op,
subdiv_offsets=(0,)):
"""Reduces tensors collectively, across devices.
Args:
t: the tensor to be reduced.
group_size: the total number of tensors to be collectively reduced.
Each must reside on a different device.
group_key: an integer identifying the group of devices.
instance_key: an integer identifying the participating group of Ops.
merge_op: string naming the binary Op to be applied to compute each
partial reduction.
final_op: string naming the unary Op to be applied to each fully
reduced value. Can be 'Id' for no operation.
subdiv_offsets: a list of integer offsets into the tensor at which each
independent subdivision should begin. Use [0] if no subdivision should
be done.
Returns:
An Op implementing the distributed reduction.
Raises:
ValueError: if any of the input parameter constraints are not met.
"""
if not device.canonical_name(t.device):
raise ValueError('Device assignment required for collective ops')
if group_size <= 1:
raise ValueError('Parameter group_size to add_reduce must be at least 2.')
return gen_collective_ops.collective_reduce(t,
group_size=group_size,
group_key=group_key,
instance_key=instance_key,
merge_op=merge_op,
final_op=final_op,
subdiv_offsets=subdiv_offsets)
def broadcast_send(t, shape, dtype, group_size, group_key, instance_key):
"""Broadcasts one tensor to a group of others, across devices.
Args:
t: the tensor to be sent.
shape: the shape of the tensor being sent, which must agree with t.
dtype: the type of the tensor being sent, which must agree with t.
group_size: one plus the number of receiving tensors, i.e. the total
number of devices participating. Each tensor must reside on a
different device.
group_key: an integer identifying the group of devices.
instance_key: an integer identifying the participating group of Ops.
Returns:
An Op implementing the distributed broadcast send.
Raises:
ValueError: if any of the input parameter constraints are not met.
Note that the shape and dtype arguments appear redundant since they
should be obtainable from t. The are two reasons for including
them. First, the shape and type of tensors passed via broadcast must
be known ahead of time in their most specific form so that the receive
side can allocate memory for the operation and shape/type inference can
carry forward from there. Including the same declarations on the
send side clarifies a commitment already made. Secondly, having nearly
identical use syntax for send and receive sides may simplify tool-driven
generation of broadcast.
"""
if not device.canonical_name(t.device):
raise ValueError('Device assignment required for collective ops')
if group_size <= 1:
raise ValueError(
'Parameter group_size to broadcast_send must be at least 2.')
if t.shape != shape:
raise ValueError(
'Shape of broadcast_send tensor not equal to delcared shape')
if t.dtype != dtype:
raise ValueError(
'Type of broadcast_send tensor not equal to declared type')
return gen_collective_ops.collective_bcast_send(t,
shape=shape,
group_size=group_size,
group_key=group_key,
instance_key=instance_key)
def broadcast_recv(shape, dtype, group_size, group_key, instance_key):
"""Receives a broadcasts tensor, across devices.
Args:
shape: Shape of the tensor to be received.
dtype: Type of the tensor to be received.
group_size: one plus the number of receiving tensors, i.e. the total
number of devices participating. Each tensor must reside on a
different device.
group_key: an integer identifying the group of devices.
instance_key: an integer identifying the participating group of Ops.
Returns:
An Op implementing the broadcast receive.
Raises:
ValueError: if any of the input parameter constraints are not met.
"""
if group_size <= 1:
raise ValueError(
'Parameter group_size to broadcast_send must be at least 2.')
return gen_collective_ops.collective_bcast_recv(shape=shape,
T=dtype,
group_size=group_size,
group_key=group_key,
instance_key=instance_key)
| apache-2.0 |
cgstudiomap/cgstudiomap | main/eggs/Shapely-1.5.13-py2.7.egg/shapely/geometry/proxy.py | 17 | 1341 | """Proxy for coordinates stored outside Shapely geometries
"""
from shapely.geometry.base import deserialize_wkb, EMPTY
from shapely.geos import lgeos
class CachingGeometryProxy(object):
context = None
factory = None
__geom__ = EMPTY
_gtag = None
def __init__(self, context):
self.context = context
@property
def _is_empty(self):
return self.__geom__ in [EMPTY, None]
def empty(self, val=EMPTY):
if not self._is_empty and self.__geom__:
lgeos.GEOSGeom_destroy(self.__geom__)
self.__geom__ = val
@property
def _geom(self):
"""Keeps the GEOS geometry in synch with the context."""
gtag = self.gtag()
if gtag != self._gtag or self._is_empty:
self.empty()
self.__geom__, n = self.factory(self.context)
self._gtag = gtag
return self.__geom__
def gtag(self):
return hash(repr(self.context))
class PolygonProxy(CachingGeometryProxy):
@property
def _geom(self):
"""Keeps the GEOS geometry in synch with the context."""
gtag = self.gtag()
if gtag != self._gtag or self._is_empty:
self.empty()
self.__geom__, n = self.factory(self.context[0], self.context[1])
self._gtag = gtag
return self.__geom__
| agpl-3.0 |
fritsvanveen/QGIS | python/plugins/processing/algs/lidar/lastools/las2demPro.py | 5 | 4084 | # -*- coding: utf-8 -*-
"""
***************************************************************************
las2demPro.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
---------------------
Date : September 2013
Copyright : (C) 2013 by Martin Isenburg
Email : martin near rapidlasso point com
***************************************************************************
* *
* 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. *
* *
***************************************************************************
"""
from future import standard_library
standard_library.install_aliases()
__author__ = 'Victor Olaya'
__date__ = 'August 2012'
__copyright__ = '(C) 2012, Victor Olaya'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
import os
from .LAStoolsUtils import LAStoolsUtils
from .LAStoolsAlgorithm import LAStoolsAlgorithm
from processing.core.parameters import ParameterSelection
from processing.core.parameters import ParameterBoolean
class las2demPro(LAStoolsAlgorithm):
ATTRIBUTE = "ATTRIBUTE"
PRODUCT = "PRODUCT"
ATTRIBUTES = ["elevation", "slope", "intensity", "rgb", "edge_longest", "edge_shortest"]
PRODUCTS = ["actual values", "hillshade", "gray", "false"]
USE_TILE_BB = "USE_TILE_BB"
def defineCharacteristics(self):
self.name, self.i18n_name = self.trAlgorithm('las2demPro')
self.group, self.i18n_group = self.trAlgorithm('LAStools Production')
self.addParametersPointInputFolderGUI()
self.addParametersFilter1ReturnClassFlagsGUI()
self.addParametersStepGUI()
self.addParameter(ParameterSelection(las2demPro.ATTRIBUTE,
self.tr("attribute (what to interpolate)"), las2demPro.ATTRIBUTES, 0))
self.addParameter(ParameterSelection(las2demPro.PRODUCT,
self.tr("product (how to output per pixel)"), las2demPro.PRODUCTS, 0))
self.addParameter(ParameterBoolean(las2demPro.USE_TILE_BB,
self.tr("use tile bounding box (after tiling with buffer)"), False))
self.addParametersOutputDirectoryGUI()
self.addParametersOutputAppendixGUI()
self.addParametersRasterOutputFormatGUI()
self.addParametersAdditionalGUI()
self.addParametersCoresGUI()
self.addParametersVerboseGUI()
def processAlgorithm(self, progress):
commands = [os.path.join(LAStoolsUtils.LAStoolsPath(), "bin", "las2dem")]
self.addParametersVerboseCommands(commands)
self.addParametersPointInputFolderCommands(commands)
self.addParametersFilter1ReturnClassFlagsCommands(commands)
self.addParametersStepCommands(commands)
attribute = self.getParameterValue(las2demPro.ATTRIBUTE)
if attribute != 0:
commands.append("-" + las2demPro.ATTRIBUTES[attribute])
product = self.getParameterValue(las2demPro.PRODUCT)
if product != 0:
commands.append("-" + las2demPro.PRODUCTS[product])
if (self.getParameterValue(las2demPro.USE_TILE_BB)):
commands.append("-use_tile_bb")
self.addParametersOutputDirectoryCommands(commands)
self.addParametersOutputAppendixCommands(commands)
self.addParametersRasterOutputFormatCommands(commands)
self.addParametersAdditionalCommands(commands)
self.addParametersCoresCommands(commands)
LAStoolsUtils.runLAStools(commands, progress)
| gpl-2.0 |
lmazuel/azure-sdk-for-python | azure-mgmt-compute/azure/mgmt/compute/v2016_03_30/models/boot_diagnostics_py3.py | 5 | 1526 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Model
class BootDiagnostics(Model):
"""Boot Diagnostics is a debugging feature which allows you to view Console
Output and Screenshot to diagnose VM status. <br><br> For Linux Virtual
Machines, you can easily view the output of your console log. <br><br> For
both Windows and Linux virtual machines, Azure also enables you to see a
screenshot of the VM from the hypervisor.
:param enabled: Whether boot diagnostics should be enabled on the Virtual
Machine.
:type enabled: bool
:param storage_uri: Uri of the storage account to use for placing the
console output and screenshot.
:type storage_uri: str
"""
_attribute_map = {
'enabled': {'key': 'enabled', 'type': 'bool'},
'storage_uri': {'key': 'storageUri', 'type': 'str'},
}
def __init__(self, *, enabled: bool=None, storage_uri: str=None, **kwargs) -> None:
super(BootDiagnostics, self).__init__(**kwargs)
self.enabled = enabled
self.storage_uri = storage_uri
| mit |
J-CPelletier/webcomix | webcomix/tests/test_search.py | 2 | 4068 | from webcomix.comic import Comic
from webcomix.search import discovery
from webcomix.tests.fake_websites.fixture import (
one_webpage_searchable_uri,
three_webpages_uri,
three_webpages_classes_uri,
)
def test_search_searchable_website(mocker, three_webpages_classes_uri):
expected = Comic(
"Blindsprings",
three_webpages_classes_uri,
"//*[contains(translate(@class, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz'), 'comic')]//@src",
"//*[contains(translate(@class, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz'), 'next')]//@href",
)
mocker.patch("webcomix.search.possible_image_xpath", ["comic"])
mocker.patch("webcomix.search.possible_next_page_xpath", ["next"])
mocker.patch("webcomix.search.possible_tags_image", ["*"])
mocker.patch("webcomix.search.possible_tags_next", ["*"])
mocker.patch("webcomix.search.possible_attributes_image", ["@class"])
mocker.patch("webcomix.search.possible_attributes_next", ["@class"])
mocker.patch("webcomix.util.check_first_pages")
comic, result = discovery("Blindsprings", three_webpages_classes_uri)
three_webpages_classes_folder = three_webpages_classes_uri.strip("1.html")
assert result == [
{
"page": 1,
"url": three_webpages_classes_uri,
"image_urls": [three_webpages_classes_folder + "1.jpeg"],
"alt_text": None,
},
{
"page": 2,
"url": three_webpages_classes_folder + "2.html",
"image_urls": [three_webpages_classes_folder + "2.jpeg"],
"alt_text": None,
},
{
"page": 3,
"url": three_webpages_classes_folder + "3.html",
"image_urls": [three_webpages_classes_folder + "3.jpeg"],
"alt_text": None,
},
]
assert comic.start_url == expected.start_url
assert comic.next_page_selector == expected.next_page_selector
assert comic.comic_image_selector == expected.comic_image_selector
def test_search_unsearchable_website(mocker, three_webpages_uri):
mocker.patch("webcomix.search.possible_image_xpath", ["comic"])
mocker.patch("webcomix.search.possible_next_page_xpath", ["next"])
mocker.patch("webcomix.search.possible_tags_image", ["*"])
mocker.patch("webcomix.search.possible_tags_next", ["*"])
mocker.patch("webcomix.search.possible_attributes_image", ["@class"])
mocker.patch("webcomix.search.possible_attributes_next", ["@class"])
assert discovery("test", three_webpages_uri) == (None, None)
def test_can_stop_searching(mocker, three_webpages_classes_uri):
mocker.patch("webcomix.search.possible_image_xpath", ["comic"])
mocker.patch("webcomix.search.possible_next_page_xpath", ["next"])
mocker.patch("webcomix.search.possible_tags_image", ["div"])
mocker.patch("webcomix.search.possible_tags_next", ["div"])
mocker.patch("webcomix.search.possible_attributes_image", ["@rel"])
mocker.patch("webcomix.search.possible_attributes_next", ["@class"])
exit_called = mocker.patch("sys.exit")
mocker.patch("webcomix.comic.Comic.verify_xpath", side_effect=KeyboardInterrupt)
result = discovery("test", three_webpages_classes_uri)
assert exit_called.call_count == 1
assert result == (None, None)
def test_can_find_single_page_correctly_while_searching(
mocker, one_webpage_searchable_uri
):
mocker.patch("webcomix.search.possible_image_xpath", ["image"])
mocker.patch("webcomix.search.possible_next_page_xpath", ["next"])
mocker.patch("webcomix.search.possible_tags_image", ["*"])
mocker.patch("webcomix.search.possible_tags_next", ["*"])
mocker.patch("webcomix.search.possible_attributes_image", ["@class"])
mocker.patch("webcomix.search.possible_attributes_next", ["."])
comic, result = discovery("test", one_webpage_searchable_uri, single_page=True)
validation = comic.verify_xpath()
assert len(result) == 1
assert result == validation
assert len(result[0]["image_urls"]) == 2
| mit |
j0nathan33/CouchPotatoServer | couchpotato/core/media/movie/providers/trailer/youtube_dl/extractor/normalboots.py | 19 | 2263 | # encoding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
unified_strdate,
)
class NormalbootsIE(InfoExtractor):
_VALID_URL = r'http://(?:www\.)?normalboots\.com/video/(?P<videoid>[0-9a-z-]*)/?$'
_TEST = {
'url': 'http://normalboots.com/video/home-alone-games-jontron/',
'md5': '8bf6de238915dd501105b44ef5f1e0f6',
'info_dict': {
'id': 'home-alone-games-jontron',
'ext': 'mp4',
'title': 'Home Alone Games - JonTron - NormalBoots',
'description': 'Jon is late for Christmas. Typical. Thanks to: Paul Ritchey for Co-Writing/Filming: http://www.youtube.com/user/ContinueShow Michael Azzi for Christmas Intro Animation: http://michafrar.tumblr.com/ Jerrod Waters for Christmas Intro Music: http://www.youtube.com/user/xXJerryTerryXx Casey Ormond for ‘Tense Battle Theme’:\xa0http://www.youtube.com/Kiamet/',
'uploader': 'JonTron',
'upload_date': '20140125',
}
}
def _real_extract(self, url):
mobj = re.match(self._VALID_URL, url)
video_id = mobj.group('videoid')
webpage = self._download_webpage(url, video_id)
video_uploader = self._html_search_regex(r'Posted\sby\s<a\shref="[A-Za-z0-9/]*">(?P<uploader>[A-Za-z]*)\s</a>',
webpage, 'uploader')
raw_upload_date = self._html_search_regex('<span style="text-transform:uppercase; font-size:inherit;">[A-Za-z]+, (?P<date>.*)</span>',
webpage, 'date')
video_upload_date = unified_strdate(raw_upload_date)
player_url = self._html_search_regex(r'<iframe\swidth="[0-9]+"\sheight="[0-9]+"\ssrc="(?P<url>[\S]+)"', webpage, 'url')
player_page = self._download_webpage(player_url, video_id)
video_url = self._html_search_regex(r"file:\s'(?P<file>[^']+\.mp4)'", player_page, 'file')
return {
'id': video_id,
'url': video_url,
'title': self._og_search_title(webpage),
'description': self._og_search_description(webpage),
'thumbnail': self._og_search_thumbnail(webpage),
'uploader': video_uploader,
'upload_date': video_upload_date,
}
| gpl-3.0 |
browseinfo/odoo_saas3_nicolas | openerp/addons/base/res/ir_property.py | 9 | 7527 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import time
from openerp.osv import osv, fields
from openerp.osv.orm import browse_record, browse_null
from openerp.tools.misc import attrgetter
# -------------------------------------------------------------------------
# Properties
# -------------------------------------------------------------------------
class ir_property(osv.osv):
_name = 'ir.property'
_columns = {
'name': fields.char('Name', size=128, select=1),
'res_id': fields.char('Resource', size=128, help="If not set, acts as a default value for new resources", select=1),
'company_id': fields.many2one('res.company', 'Company', select=1),
'fields_id': fields.many2one('ir.model.fields', 'Field', ondelete='cascade', required=True, select=1),
'value_float' : fields.float('Value'),
'value_integer' : fields.integer('Value'),
'value_text' : fields.text('Value'), # will contain (char, text)
'value_binary' : fields.binary('Value'),
'value_reference': fields.char('Value', size=128),
'value_datetime' : fields.datetime('Value'),
'type' : fields.selection([('char', 'Char'),
('float', 'Float'),
('boolean', 'Boolean'),
('integer', 'Integer'),
('text', 'Text'),
('binary', 'Binary'),
('many2one', 'Many2One'),
('date', 'Date'),
('datetime', 'DateTime'),
('selection', 'Selection'),
],
'Type',
required=True,
select=1),
}
_defaults = {
'type': 'many2one',
}
def _update_values(self, cr, uid, ids, values):
value = values.pop('value', None)
if not value:
return values
prop = None
type_ = values.get('type')
if not type_:
if ids:
prop = self.browse(cr, uid, ids[0])
type_ = prop.type
else:
type_ = self._defaults['type']
type2field = {
'char': 'value_text',
'float': 'value_float',
'boolean' : 'value_integer',
'integer': 'value_integer',
'text': 'value_text',
'binary': 'value_binary',
'many2one': 'value_reference',
'date' : 'value_datetime',
'datetime' : 'value_datetime',
'selection': 'value_text',
}
field = type2field.get(type_)
if not field:
raise osv.except_osv('Error', 'Invalid type')
if field == 'value_reference':
if isinstance(value, browse_record):
value = '%s,%d' % (value._name, value.id)
elif isinstance(value, (int, long)):
field_id = values.get('fields_id')
if not field_id:
if not prop:
raise ValueError()
field_id = prop.fields_id
else:
field_id = self.pool.get('ir.model.fields').browse(cr, uid, field_id)
value = '%s,%d' % (field_id.relation, value)
values[field] = value
return values
def write(self, cr, uid, ids, values, context=None):
return super(ir_property, self).write(cr, uid, ids, self._update_values(cr, uid, ids, values), context=context)
def create(self, cr, uid, values, context=None):
return super(ir_property, self).create(cr, uid, self._update_values(cr, uid, None, values), context=context)
def get_by_record(self, cr, uid, record, context=None):
if record.type in ('char', 'text', 'selection'):
return record.value_text
elif record.type == 'float':
return record.value_float
elif record.type == 'boolean':
return bool(record.value_integer)
elif record.type == 'integer':
return record.value_integer
elif record.type == 'binary':
return record.value_binary
elif record.type == 'many2one':
if not record.value_reference:
return browse_null()
model, resource_id = record.value_reference.split(',')
return self.pool.get(model).browse(cr, uid, int(resource_id), context=context)
elif record.type == 'datetime':
return record.value_datetime
elif record.type == 'date':
if not record.value_datetime:
return False
return time.strftime('%Y-%m-%d', time.strptime(record.value_datetime, '%Y-%m-%d %H:%M:%S'))
return False
def get(self, cr, uid, name, model, res_id=False, context=None):
domain = self._get_domain(cr, uid, name, model, context=context)
if domain is not None:
domain = [('res_id', '=', res_id)] + domain
#make the search with company_id asc to make sure that properties specific to a company are given first
nid = self.search(cr, uid, domain, limit=1, order='company_id asc', context=context)
if not nid: return False
record = self.browse(cr, uid, nid[0], context=context)
return self.get_by_record(cr, uid, record, context=context)
return False
def _get_domain_default(self, cr, uid, prop_name, model, context=None):
domain = self._get_domain(cr, uid, prop_name, model, context=context)
if domain is None:
return None
return ['&', ('res_id', '=', False)] + domain
def _get_domain(self, cr, uid, prop_name, model, context=None):
context = context or {}
cr.execute('select id from ir_model_fields where name=%s and model=%s', (prop_name, model))
res = cr.fetchone()
if not res:
return None
if 'force_company' in context and context['force_company']:
cid = context['force_company']
else:
company = self.pool.get('res.company')
cid = company._company_default_get(cr, uid, model, res[0], context=context)
domain = ['&', ('fields_id', '=', res[0]),
'|', ('company_id', '=', cid), ('company_id', '=', False)]
return domain
ir_property()
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
arhote/exchange | exchange/fileservice/helpers.py | 1 | 1043 | from django.conf import settings
import os
def get_streaming_supported():
"""
example settings file
FILESERVICE_CONFIG = {
'streaming_supported': True
}
"""
conf = getattr(settings, 'FILESERVICE_CONFIG', {})
return conf.get('streaming_supported', False)
def get_fileservice_dir():
"""
example settings file
FILESERVICE_CONFIG = {
'store_dir': '/var/lib/geoserver_data/fileservice_store'
}
"""
conf = getattr(settings, 'FILESERVICE_CONFIG', {})
dir = conf.get(
'store_dir', os.path.join(settings.MEDIA_ROOT, 'fileservice'))
return os.path.normpath(dir) + os.sep
def get_fileservice_whitelist():
conf = getattr(settings, 'FILESERVICE_CONFIG', {})
return [x.lower() for x in conf.get('types_allowed', [])]
def u_to_str(string):
return string.encode('ascii', 'ignore')
def get_fileservice_files():
return os.listdir(get_fileservice_dir())
def get_filename_absolute(filename):
return '{}/{}'.format(get_fileservice_dir(), filename)
| gpl-3.0 |
alaski/nova | nova/api/openstack/compute/evacuate.py | 4 | 5688 | # Copyright 2013 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_utils import strutils
from webob import exc
from nova.api.openstack import api_version_request
from nova.api.openstack import common
from nova.api.openstack.compute.schemas import evacuate
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova.api import validation
from nova import compute
import nova.conf
from nova import exception
from nova.i18n import _
from nova.policies import evacuate as evac_policies
from nova import utils
CONF = nova.conf.CONF
ALIAS = "os-evacuate"
class EvacuateController(wsgi.Controller):
def __init__(self, *args, **kwargs):
super(EvacuateController, self).__init__(*args, **kwargs)
self.compute_api = compute.API()
self.host_api = compute.HostAPI()
def _get_on_shared_storage(self, req, evacuate_body):
if api_version_request.is_supported(req, min_version='2.14'):
return None
else:
return strutils.bool_from_string(evacuate_body["onSharedStorage"])
def _get_password(self, req, evacuate_body, on_shared_storage):
password = None
if 'adminPass' in evacuate_body:
# check that if requested to evacuate server on shared storage
# password not specified
if on_shared_storage:
msg = _("admin password can't be changed on existing disk")
raise exc.HTTPBadRequest(explanation=msg)
password = evacuate_body['adminPass']
elif not on_shared_storage:
password = utils.generate_password()
return password
def _get_password_v214(self, req, evacuate_body):
if 'adminPass' in evacuate_body:
password = evacuate_body['adminPass']
else:
password = utils.generate_password()
return password
# TODO(eliqiao): Should be responding here with 202 Accept
# because evacuate is an async call, but keep to 200 for
# backwards compatibility reasons.
@extensions.expected_errors((400, 404, 409))
@wsgi.action('evacuate')
@validation.schema(evacuate.evacuate, "2.1", "2.12")
@validation.schema(evacuate.evacuate_v214, "2.14", "2.28")
@validation.schema(evacuate.evacuate_v2_29, "2.29")
def _evacuate(self, req, id, body):
"""Permit admins to evacuate a server from a failed host
to a new one.
"""
context = req.environ["nova.context"]
instance = common.get_instance(self.compute_api, context, id)
context.can(evac_policies.BASE_POLICY_NAME,
target={'user_id': instance.user_id,
'project_id': instance.project_id})
evacuate_body = body["evacuate"]
host = evacuate_body.get("host")
force = None
on_shared_storage = self._get_on_shared_storage(req, evacuate_body)
if api_version_request.is_supported(req, min_version='2.29'):
force = body["evacuate"].get("force", False)
force = strutils.bool_from_string(force, strict=True)
if force is True and not host:
message = _("Can't force to a non-provided destination")
raise exc.HTTPBadRequest(explanation=message)
if api_version_request.is_supported(req, min_version='2.14'):
password = self._get_password_v214(req, evacuate_body)
else:
password = self._get_password(req, evacuate_body,
on_shared_storage)
if host is not None:
try:
self.host_api.service_get_by_compute_host(context, host)
except exception.ComputeHostNotFound:
msg = _("Compute host %s not found.") % host
raise exc.HTTPNotFound(explanation=msg)
if instance.host == host:
msg = _("The target host can't be the same one.")
raise exc.HTTPBadRequest(explanation=msg)
try:
self.compute_api.evacuate(context, instance, host,
on_shared_storage, password, force)
except exception.InstanceUnknownCell as e:
raise exc.HTTPNotFound(explanation=e.format_message())
except exception.InstanceInvalidState as state_error:
common.raise_http_conflict_for_instance_invalid_state(state_error,
'evacuate', id)
except exception.ComputeServiceInUse as e:
raise exc.HTTPBadRequest(explanation=e.format_message())
if (not api_version_request.is_supported(req, min_version='2.14') and
CONF.enable_instance_password):
return {'adminPass': password}
else:
return None
class Evacuate(extensions.V21APIExtensionBase):
"""Enables server evacuation."""
name = "Evacuate"
alias = ALIAS
version = 1
def get_resources(self):
return []
def get_controller_extensions(self):
controller = EvacuateController()
extension = extensions.ControllerExtension(self, 'servers', controller)
return [extension]
| apache-2.0 |
awslabs/s2n | tests/integration/common/s2n_test_reporting.py | 3 | 1976 | ##
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License.
# A copy of the License is located at
#
# http://aws.amazon.com/apache2.0
#
# or in the "license" file accompanying this file. This file is distributed
# on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
# express or implied. See the License for the specific language governing
# permissions and limitations under the License.
#
"""
Common functions used to report the results of tests.
"""
import sys
from enum import Enum
class Color(Enum):
RED = 31
GREEN = 32
class Status(Enum):
"""
Enum to represent success/failure. The values are the
color codes used to print the status.
"""
PASSED = Color.GREEN
FAILED = Color.RED
def __str__(self):
return with_color(self.name, self.value)
class Result:
"""
A class to standardize how test results are reported.
"""
def __init__(self, error_msg=None):
self.error_msg = error_msg
self.client_error = None
self.server_error = None
self.status = Status.PASSED if error_msg is None else Status.FAILED
def is_success(self):
return self.status is not Status.FAILED
def __str__(self):
result = str(self.status)
if self.error_msg:
result += "\n\t" + with_color(self.error_msg, Color.RED)
if self.client_error:
result += with_color("\n\tClient: ", Color.RED)
result += self.client_error.rstrip()
if self.server_error:
result += with_color("\n\tServer: ", Color.RED)
result += self.server_error.rstrip()
return result
def with_color(msg, color):
if sys.stdout.isatty():
return "\033[%d;1m%s\033[0m" % (color.value, msg)
else:
return msg
| apache-2.0 |
SickGear/SickGear | lib/hachoir_py2/parser/video/amf.py | 2 | 3239 | """
AMF metadata (inside Flash video, FLV file) parser.
Documentation:
- flashticle: Python project to read Flash (formats SWF, FLV and AMF)
http://undefined.org/python/#flashticle
Author: Victor Stinner
Creation date: 4 november 2006
"""
from hachoir_py2.field import (FieldSet, ParserError,
UInt8, UInt16, UInt32, PascalString16, Float64)
from hachoir_py2.core.tools import timestampUNIX
def parseUTF8(parent):
yield PascalString16(parent, "value", charset="UTF-8")
def parseDouble(parent):
yield Float64(parent, "value")
def parseBool(parent):
yield UInt8(parent, "value")
def parseArray(parent):
yield UInt32(parent, "count")
for index in xrange(parent["count"].value):
yield AMFObject(parent, "item[]")
def parseObjectAttributes(parent):
while True:
item = Attribute(parent, "attr[]")
yield item
if item["key"].value == "":
break
def parseMixedArray(parent):
yield UInt32(parent, "count")
for index in xrange(parent["count"].value + 1):
item = Attribute(parent, "item[]")
yield item
if not item['key'].value:
break
def parseDate(parent):
yield Float64(parent, "timestamp_microsec")
yield UInt16(parent, "timestamp_sec")
def parseNothing(parent):
# Python hack to make sure that the function is a generator
if 0:
yield
class AMFObject(FieldSet):
CODE_DATE = 11
tag_info = {
# http://osflash.org/amf/astypes
0: (parseDouble, "Double"),
1: (parseBool, "Boolean"),
2: (parseUTF8, "UTF-8 string"),
3: (parseObjectAttributes, "Object attributes"),
# MOVIECLIP = '\x04',
# NULL = '\x05',
# UNDEFINED = '\x06',
# REFERENCE = '\x07',
8: (parseMixedArray, "Mixed array"),
9: (parseNothing, "End of object"),
10: (parseArray, "Array"),
CODE_DATE: (parseDate, "Date"),
# LONGUTF8 = '\x0c',
# UNSUPPORTED = '\x0d',
## Server-to-client only
# RECORDSET = '\x0e',
# XML = '\x0f',
# TYPEDOBJECT = '\x10',
}
def __init__(self, *args, **kw):
FieldSet.__init__(self, *args, **kw)
code = self["type"].value
try:
self.parser, desc = self.tag_info[code]
if code == self.CODE_DATE:
self.createValue = self.createValueDate
except KeyError:
raise ParserError("AMF: Unable to parse type %s" % code)
def createFields(self):
yield UInt8(self, "type")
for field in self.parser(self):
yield field
def createValueDate(self):
value = (self["timestamp_microsec"].value * 0.001) \
- (self["timestamp_sec"].value * 60)
return timestampUNIX(value)
class Attribute(AMFObject):
def __init__(self, *args):
AMFObject.__init__(self, *args)
self._description = None
def createFields(self):
yield PascalString16(self, "key", charset="UTF-8")
yield UInt8(self, "type")
for field in self.parser(self):
yield field
def createDescription(self):
return 'Attribute "%s"' % self["key"].value
| gpl-3.0 |
schleichdi2/OpenNfr_E2_Gui-6.0 | lib/python/Screens/Ci.py | 5 | 27345 | from Screen import Screen
from Screens.MessageBox import MessageBox
from Components.ConfigList import ConfigListScreen
from Components.ActionMap import ActionMap
from Components.ActionMap import NumberActionMap
from Components.Label import Label
from Components.Pixmap import Pixmap
from Components.Console import Console
from Components.Sources.StaticText import StaticText
from Components.Sources.Boolean import Boolean
from Components.config import config, ConfigSubsection, ConfigSelection, ConfigSubList, getConfigListEntry, KEY_LEFT, KEY_RIGHT, KEY_0, ConfigNothing, ConfigPIN, ConfigText, ConfigYesNo, NoSave
from Components.ConfigList import ConfigList
from Components.SystemInfo import SystemInfo
from Tools.Directories import fileExists
from os import path as os_path, remove, unlink, rename, chmod, access, X_OK
from enigma import eTimer, eDVBCI_UI, eDVBCIInterfaces
from Tools.BoundFunction import boundFunction
from boxbranding import getBrandOEM, getBoxType
import time
MAX_NUM_CI = 4
def setCIBitrate(configElement):
if configElement.value == "no":
eDVBCI_UI.getInstance().setClockRate(configElement.slotid, eDVBCI_UI.rateNormal)
else:
eDVBCI_UI.getInstance().setClockRate(configElement.slotid, eDVBCI_UI.rateHigh)
def setdvbCiDelay(configElement):
f = open("/proc/stb/tsmux/rmx_delay", "w")
f.write(configElement.value)
f.close()
def InitCiConfig():
config.ci = ConfigSubList()
config.cimisc = ConfigSubsection()
for slot in range(MAX_NUM_CI):
config.ci.append(ConfigSubsection())
config.ci[slot].canDescrambleMultipleServices = ConfigSelection(choices = [("auto", _("Auto")), ("no", _("No")), ("yes", _("Yes"))], default = "auto")
config.ci[slot].use_static_pin = ConfigYesNo(default = True)
config.ci[slot].static_pin = ConfigPIN(default = 0)
config.ci[slot].show_ci_messages = ConfigYesNo(default = True)
if SystemInfo["CommonInterfaceSupportsHighBitrates"]:
if getBrandOEM() in ('dags', 'blackbox'):
config.ci[slot].canHandleHighBitrates = ConfigSelection(choices = [("no", _("No")), ("yes", _("Yes"))], default = "yes")
else:
config.ci[slot].canHandleHighBitrates = ConfigSelection(choices = [("no", _("No")), ("yes", _("Yes"))], default = "no")
config.ci[slot].canHandleHighBitrates.slotid = slot
config.ci[slot].canHandleHighBitrates.addNotifier(setCIBitrate)
if SystemInfo["CommonInterfaceCIDelay"]:
config.cimisc.dvbCiDelay = ConfigSelection(default = "256", choices = [ ("16", _("16")), ("32", _("32")), ("64", _("64")), ("128", _("128")), ("256", _("256"))] )
config.cimisc.dvbCiDelay.addNotifier(setdvbCiDelay)
if getBrandOEM() in ('entwopia', 'tripledot', 'dreambox'):
if SystemInfo["HaveCISSL"]:
config.cimisc.civersion = ConfigSelection(default = "ciplus1", choices = [("auto", _("Auto")), ("ciplus1", _("CI Plus 1.2")), ("ciplus2", _("CI Plus 1.3")), ("legacy", _("CI Legacy"))])
else:
config.cimisc.civersion = ConfigSelection(default = "legacy", choices = [("legacy", _("CI Legacy"))])
else:
config.cimisc.civersion = ConfigSelection(default = "auto", choices = [("auto", _("Auto")), ("ciplus1", _("CI Plus 1.2")), ("ciplus2", _("CI Plus 1.3")), ("legacy", _("CI Legacy"))])
class CISetup(Screen, ConfigListScreen):
def __init__(self, session):
Screen.__init__(self, session)
self.skinName = ["Setup" ]
self.setup_title = _("CI settings")
self["HelpWindow"] = Pixmap()
self["HelpWindow"].hide()
self["VKeyIcon"] = Boolean(False)
self['footnote'] = Label()
self.onChangedEntry = [ ]
self.list = [ ]
ConfigListScreen.__init__(self, self.list, session = session, on_change = self.changedEntry)
from Components.ActionMap import ActionMap
self["actions"] = ActionMap(["SetupActions", "MenuActions", "ColorActions"],
{
"cancel": self.keyCancel,
"save": self.apply,
"menu": self.closeRecursive,
}, -2)
self["key_red"] = StaticText(_("Cancel"))
self["key_green"] = StaticText(_("OK"))
self["description"] = Label("")
self.createSetup()
self.onLayoutFinish.append(self.layoutFinished)
def layoutFinished(self):
self.setTitle(self.setup_title)
def createSetup(self):
level = config.usage.setup_level.index
self.list = [ ]
if level >= 1:
if SystemInfo["CommonInterfaceCIDelay"]:
self.list.append(getConfigListEntry(_("DVB CI Delay"), config.cimisc.dvbCiDelay, _("Choose dvb wait delay for ci response.")))
if SystemInfo["HaveCISSL"]:
self.list.append(getConfigListEntry(_("CI Operation Mode"), config.cimisc.civersion, _("Choose the CI protocol operation mode for standard ci or ciplus.")))
else:
self.list.append(getConfigListEntry(_("CI Operation Mode"), config.cimisc.civersion, _("Your Hardware can detect ci mode self or work only in legacy mode.")))
self["config"].list = self.list
self["config"].l.setList(self.list)
if config.usage.sort_settings.value:
self["config"].list.sort()
def keyRight(self):
ConfigListScreen.keyRight(self)
self.createSetup()
def confirm(self, confirmed):
self.keySave()
def apply(self):
self.keySave()
# for summary:
def changedEntry(self):
for x in self.onChangedEntry:
x()
def getCurrentEntry(self):
return self["config"].getCurrent()[0]
def getCurrentValue(self):
return str(self["config"].getCurrent()[1].getText())
def getCurrentDescription(self):
return self["config"].getCurrent() and len(self["config"].getCurrent()) > 2 and self["config"].getCurrent()[2] or ""
def createSummary(self):
from Screens.Setup import SetupSummary
return SetupSummary
class MMIDialog(Screen):
def __init__(self, session, slotid, action, handler = eDVBCI_UI.getInstance(), wait_text = "wait for ci...", screen_data = None ):
Screen.__init__(self, session)
print "MMIDialog with action" + str(action)
self.mmiclosed = False
self.tag = None
self.slotid = slotid
self.timer = eTimer()
self.timer.callback.append(self.keyCancel)
#else the skins fails
self["title"] = Label("")
self["subtitle"] = Label("")
self["bottom"] = Label("")
self["entries"] = ConfigList([ ])
self["actions"] = NumberActionMap(["SetupActions"],
{
"ok": self.okbuttonClick,
"cancel": self.keyCancel,
#for PIN
"left": self.keyLeft,
"right": self.keyRight,
"1": self.keyNumberGlobal,
"2": self.keyNumberGlobal,
"3": self.keyNumberGlobal,
"4": self.keyNumberGlobal,
"5": self.keyNumberGlobal,
"6": self.keyNumberGlobal,
"7": self.keyNumberGlobal,
"8": self.keyNumberGlobal,
"9": self.keyNumberGlobal,
"0": self.keyNumberGlobal
}, -1)
self.action = action
self.handler = handler
self.wait_text = _(wait_text)
self.screen_data = screen_data
self.is_pin_list = -1
if action == 2: #start MMI
handler.startMMI(self.slotid)
self.showWait()
elif action == 3: #mmi already there (called from infobar)
self.showScreen()
def addEntry(self, list, entry):
if entry[0] == "TEXT": #handle every item (text / pin only?)
list.append( (entry[1], ConfigNothing(), entry[2]) )
if entry[0] == "PIN":
pinlength = entry[1]
if entry[3] == 1:
# masked pins:
x = ConfigPIN(0, len = pinlength, censor = "*")
else:
# unmasked pins:
x = ConfigPIN(0, len = pinlength)
self["subtitle"].setText(entry[2])
list.append( getConfigListEntry("", x) )
self["bottom"].setText(_("please press OK when ready"))
def okbuttonClick(self):
self.timer.stop()
if not self.tag:
return
if self.tag == "WAIT":
print "do nothing - wait"
elif self.tag == "MENU":
print "answer MENU"
cur = self["entries"].getCurrent()
if cur:
self.handler.answerMenu(self.slotid, cur[2])
else:
self.handler.answerMenu(self.slotid, 0)
self.showWait()
elif self.tag == "LIST":
print "answer LIST"
self.handler.answerMenu(self.slotid, 0)
self.showWait()
elif self.tag == "ENQ":
cur = self["entries"].getCurrent()
answer = str(cur[1].value)
length = len(answer)
while length < cur[1].getLength():
answer = '0'+answer
length+=1
self.answer = answer
if config.ci[self.slotid].use_static_pin.value:
self.session.openWithCallback(self.save_PIN_CB, MessageBox, _("Would you save the entered PIN %s persistent?") % self.answer, MessageBox.TYPE_YESNO)
else:
self.save_PIN_CB(False)
def save_PIN_CB(self, ret = None):
if ret:
config.ci[self.slotid].static_pin.value = self.answer
config.ci[self.slotid].static_pin.save()
self.handler.answerEnq(self.slotid, self.answer)
self.showWait()
def closeMmi(self):
self.timer.stop()
self.close(self.slotid)
def keyCancel(self):
self.timer.stop()
if not self.tag or self.mmiclosed:
self.closeMmi()
elif self.tag == "WAIT":
self.handler.stopMMI(self.slotid)
self.closeMmi()
elif self.tag in ( "MENU", "LIST" ):
print "cancel list"
self.handler.answerMenu(self.slotid, 0)
self.showWait()
elif self.tag == "ENQ":
print "cancel enq"
self.handler.cancelEnq(self.slotid)
self.showWait()
else:
print "give cancel action to ci"
def keyConfigEntry(self, key):
self.timer.stop()
try:
self["entries"].handleKey(key)
if self.is_pin_list == 4:
self.okbuttonClick()
except:
pass
def keyNumberGlobal(self, number):
self.timer.stop()
if self.is_pin_list > -1:
self.is_pin_list += 1
self.keyConfigEntry(KEY_0 + number)
def keyLeft(self):
self.timer.stop()
if self.is_pin_list > 0:
self.is_pin_list += -1
self.keyConfigEntry(KEY_LEFT)
def keyRight(self):
self.timer.stop()
if self.is_pin_list > -1 and self.is_pin_list < 4:
self.is_pin_list += 1
self.keyConfigEntry(KEY_RIGHT)
def updateList(self, list):
List = self["entries"]
try:
List.instance.moveSelectionTo(0)
except:
pass
List.l.setList(list)
def showWait(self):
self.tag = "WAIT"
self["title"].setText("")
self["subtitle"].setText("")
self["bottom"].setText("")
list = [ ]
list.append( (self.wait_text, ConfigNothing()) )
self.updateList(list)
def showScreen(self):
if self.screen_data is not None:
screen = self.screen_data
self.screen_data = None
else:
screen = self.handler.getMMIScreen(self.slotid)
list = [ ]
self.timer.stop()
if len(screen) > 0 and screen[0][0] == "CLOSE":
timeout = screen[0][1]
self.mmiclosed = True
if timeout > 0:
self.timer.start(timeout*1000, True)
else:
self.keyCancel()
else:
self.mmiclosed = False
self.tag = screen[0][0]
for entry in screen:
if entry[0] == "PIN":
if config.ci[self.slotid].use_static_pin.value and str(config.ci[self.slotid].static_pin.value) != "0":
answer = str(config.ci[self.slotid].static_pin.value)
length = len(answer)
while length < config.ci[self.slotid].static_pin.getLength():
answer = '0' + answer
length+=1
self.handler.answerEnq(self.slotid, answer)
self.showWait()
break
else:
self.is_pin_list = 0
self.addEntry(list, entry)
else:
if entry[0] == "TITLE":
self["title"].setText(entry[1])
elif entry[0] == "SUBTITLE":
self["subtitle"].setText(entry[1])
elif entry[0] == "BOTTOM":
self["bottom"].setText(entry[1])
elif entry[0] == "TEXT":
self.addEntry(list, entry)
self.updateList(list)
def ciStateChanged(self):
do_close = False
if self.action == 0: #reset
do_close = True
if self.action == 1: #init
do_close = True
#module still there ?
if self.handler.getState(self.slotid) != 2:
do_close = True
#mmi session still active ?
if self.handler.getMMIState(self.slotid) != 1:
do_close = True
if do_close:
self.closeMmi()
elif self.action > 1 and self.handler.availableMMI(self.slotid) == 1:
self.showScreen()
#FIXME: check for mmi-session closed
class CiMessageHandler:
def __init__(self):
self.session = None
self.ci = { }
self.dlgs = { }
self.auto_close = False
eDVBCI_UI.getInstance().ciStateChanged.get().append(self.ciStateChanged)
if getBoxType() in ('vuzero'):
SystemInfo["CommonInterface"] = False
else:
SystemInfo["CommonInterface"] = eDVBCIInterfaces.getInstance().getNumOfSlots() > 0
try:
file = open("/proc/stb/tsmux/ci0_tsclk", "r")
file.close()
SystemInfo["CommonInterfaceSupportsHighBitrates"] = True
except:
SystemInfo["CommonInterfaceSupportsHighBitrates"] = False
try:
file = open("/proc/stb/tsmux/rmx_delay", "r")
file.close()
SystemInfo["CommonInterfaceCIDelay"] = True
except:
SystemInfo["CommonInterfaceCIDelay"] = False
def setSession(self, session):
self.session = session
def ciStateChanged(self, slot):
if slot in self.ci:
self.ci[slot](slot)
else:
handler = eDVBCI_UI.getInstance()
if slot in self.dlgs:
self.dlgs[slot].ciStateChanged()
elif handler.availableMMI(slot) == 1:
if self.session:
show_ui = False
if config.ci[slot].show_ci_messages.value:
show_ui = True
screen_data = handler.getMMIScreen(slot)
if config.ci[slot].use_static_pin.value:
if screen_data is not None and len(screen_data):
ci_tag = screen_data[0][0]
if ci_tag == 'ENQ' and len(screen_data) >= 2 and screen_data[1][0] == 'PIN':
if str(config.ci[slot].static_pin.value) == "0":
show_ui = True
else:
answer = str(config.ci[slot].static_pin.value)
length = len(answer)
while length < config.ci[slot].static_pin.getLength():
answer = '0' + answer
length+=1
handler.answerEnq(slot, answer)
show_ui = False
self.auto_close = True
elif ci_tag == 'CLOSE' and self.auto_close:
show_ui = False
self.auto_close = False
if show_ui:
self.dlgs[slot] = self.session.openWithCallback(self.dlgClosed, MMIDialog, slot, 3, screen_data = screen_data)
def dlgClosed(self, slot):
if slot in self.dlgs:
del self.dlgs[slot]
def registerCIMessageHandler(self, slot, func):
self.unregisterCIMessageHandler(slot)
self.ci[slot] = func
def unregisterCIMessageHandler(self, slot):
if slot in self.ci:
del self.ci[slot]
CiHandler = CiMessageHandler()
class CiSelection(Screen):
def __init__(self, session):
Screen.__init__(self, session)
self.setTitle(_("Common Interface"))
self["actions"] = ActionMap(["OkCancelActions", "CiSelectionActions"],
{
"left": self.keyLeft,
"right": self.keyLeft,
"ok": self.okbuttonClick,
"cancel": self.cancel
},-1)
self.dlg = None
self.state = { }
self.list = [ ]
for slot in range(MAX_NUM_CI):
state = eDVBCI_UI.getInstance().getState(slot)
if state != -1:
self.appendEntries(slot, state)
CiHandler.registerCIMessageHandler(slot, self.ciStateChanged)
menuList = ConfigList(self.list)
menuList.list = self.list
menuList.l.setList(self.list)
self["entries"] = menuList
self["entries"].onSelectionChanged.append(self.selectionChanged)
self["text"] = Label(_("Slot %d")%(1))
def selectionChanged(self):
cur_idx = self["entries"].getCurrentIndex()
self["text"].setText(_("Slot %d")%((cur_idx / 9)+1))
def keyConfigEntry(self, key):
try:
self["entries"].handleKey(key)
self["entries"].getCurrent()[1].save()
except:
pass
def keyLeft(self):
self.keyConfigEntry(KEY_LEFT)
def keyRight(self):
self.keyConfigEntry(KEY_RIGHT)
def appendEntries(self, slot, state):
self.state[slot] = state
self.list.append( (_("Reset"), ConfigNothing(), 0, slot) )
self.list.append( (_("Init"), ConfigNothing(), 1, slot) )
if self.state[slot] == 0: #no module
self.list.append( (_("no module found"), ConfigNothing(), 2, slot) )
elif self.state[slot] == 1: #module in init
self.list.append( (_("init module"), ConfigNothing(), 2, slot) )
elif self.state[slot] == 2: #module ready
#get appname
appname = eDVBCI_UI.getInstance().getAppName(slot)
self.list.append( (appname, ConfigNothing(), 2, slot) )
self.list.append(getConfigListEntry(_("Set pin code persistent"), config.ci[slot].use_static_pin))
self.list.append( ( _("Enter persistent PIN code"), ConfigNothing(), 5, slot) )
self.list.append( ( _("Reset persistent PIN code"), ConfigNothing(), 6, slot) )
self.list.append(getConfigListEntry(_("Show CI messages"), config.ci[slot].show_ci_messages))
self.list.append(getConfigListEntry(_("Multiple service support"), config.ci[slot].canDescrambleMultipleServices))
if SystemInfo["CommonInterfaceSupportsHighBitrates"]:
self.list.append(getConfigListEntry(_("High bitrate support"), config.ci[slot].canHandleHighBitrates))
def updateState(self, slot):
state = eDVBCI_UI.getInstance().getState(slot)
self.state[slot] = state
slotidx=0
while len(self.list[slotidx]) < 3 or self.list[slotidx][3] != slot:
slotidx += 1
slotidx += 1 # do not change Reset
slotidx += 1 # do not change Init
if state == 0: #no module
self.list[slotidx] = (_("no module found"), ConfigNothing(), 2, slot)
elif state == 1: #module in init
self.list[slotidx] = (_("init module"), ConfigNothing(), 2, slot)
elif state == 2: #module ready
#get appname
appname = eDVBCI_UI.getInstance().getAppName(slot)
self.list[slotidx] = (appname, ConfigNothing(), 2, slot)
lst = self["entries"]
lst.list = self.list
lst.l.setList(self.list)
def ciStateChanged(self, slot):
if self.dlg:
self.dlg.ciStateChanged()
else:
state = eDVBCI_UI.getInstance().getState(slot)
if self.state[slot] != state:
#print "something happens"
self.state[slot] = state
self.updateState(slot)
def dlgClosed(self, slot):
self.dlg = None
def okbuttonClick(self):
cur = self["entries"].getCurrent()
if cur and len(cur) > 2:
action = cur[2]
slot = cur[3]
if action == 0: #reset
eDVBCI_UI.getInstance().setReset(slot)
elif action == 1: #init
eDVBCI_UI.getInstance().setInit(slot)
elif action == 5:
self.session.openWithCallback(self.cancelCB, PermanentPinEntry, config.ci[slot].static_pin, _("Smartcard PIN"))
elif action == 6:
config.ci[slot].static_pin.value = 0
config.ci[slot].static_pin.save()
self.session.openWithCallback(self.cancelCB, MessageBox, _("The saved PIN was cleared."), MessageBox.TYPE_INFO)
elif self.state[slot] == 2:
self.dlg = self.session.openWithCallback(self.dlgClosed, MMIDialog, slot, action)
def cancelCB(self,value):
pass
def cancel(self):
for slot in range(MAX_NUM_CI):
state = eDVBCI_UI.getInstance().getState(slot)
if state != -1:
CiHandler.unregisterCIMessageHandler(slot)
self.close()
class PermanentPinEntry(Screen, ConfigListScreen):
def __init__(self, session, pin, pin_slot):
Screen.__init__(self, session)
self.skinName = ["ParentalControlChangePin", "Setup" ]
self.setup_title = _("Enter pin code")
self.onChangedEntry = [ ]
self.slot = pin_slot
self.pin = pin
self.list = []
self.pin1 = ConfigPIN(default = 0, censor = "*")
self.pin2 = ConfigPIN(default = 0, censor = "*")
self.pin1.addEndNotifier(boundFunction(self.valueChanged, 1))
self.pin2.addEndNotifier(boundFunction(self.valueChanged, 2))
self.list.append(getConfigListEntry(_("Enter PIN"), NoSave(self.pin1)))
self.list.append(getConfigListEntry(_("Reenter PIN"), NoSave(self.pin2)))
ConfigListScreen.__init__(self, self.list)
self["actions"] = NumberActionMap(["DirectionActions", "ColorActions", "OkCancelActions"],
{
"cancel": self.cancel,
"red": self.cancel,
"save": self.keyOK,
}, -1)
self["key_red"] = StaticText(_("Cancel"))
self["key_green"] = StaticText(_("OK"))
self.onLayoutFinish.append(self.layoutFinished)
def layoutFinished(self):
self.setTitle(self.setup_title)
def valueChanged(self, pin, value):
if pin == 1:
self["config"].setCurrentIndex(1)
elif pin == 2:
self.keyOK()
def keyOK(self):
if self.pin1.value == self.pin2.value:
self.pin.value = self.pin1.value
self.pin.save()
self.session.openWithCallback(self.close, MessageBox, _("The PIN code has been saved successfully."), MessageBox.TYPE_INFO)
else:
self.session.open(MessageBox, _("The PIN codes you entered are different."), MessageBox.TYPE_ERROR)
def cancel(self):
self.close(None)
def keyNumberGlobal(self, number):
ConfigListScreen.keyNumberGlobal(self, number)
# for summary:
def changedEntry(self):
for x in self.onChangedEntry:
x()
def getCurrentEntry(self):
return self["config"].getCurrent()[0]
def getCurrentValue(self):
return str(self["config"].getCurrent()[1].getText())
def createSummary(self):
from Screens.Setup import SetupSummary
return SetupSummary
class CIHelper(Screen):
def __init__(self, session):
Screen.__init__(self, session)
Screen.setTitle(self, _("CIHelper Setup"))
self.skinName = "CIHelper"
self.onChangedEntry = [ ]
self['ci0'] = Label(_("CIHelper for SLOT CI0"))
self['ci0active'] = Pixmap()
self['ci0inactive'] = Pixmap()
self['ci1'] = Label(_("CIHelper for SLOT CI1"))
self['ci1active'] = Pixmap()
self['ci1inactive'] = Pixmap()
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['key_red'] = Label()
self['key_green'] = Label(_("Start"))
self['key_yellow'] = Label(_("Autostart"))
self['key_blue'] = Label()
self.Console = Console()
self.my_cihelper_active = False
self.my_cihelper_run = False
self['actions'] = ActionMap(['WizardActions', 'ColorActions', 'SetupActions'], {'ok': self.setupcihelper, 'back': self.close, 'menu': self.setupcihelper, 'green': self.CIHelperStartStop, 'yellow': self.CIHelperset})
self.onLayoutFinish.append(self.updateService)
def CIHelperStartStop(self):
if not self.my_cihelper_run:
self.Console.ePopen('/etc/init.d/cihelper.sh start', self.StartStopCallback)
elif self.my_cihelper_run:
self.Console.ePopen('/etc/init.d/cihelper.sh stop', self.StartStopCallback)
def StartStopCallback(self, result = None, retval = None, extra_args = None):
time.sleep(5)
self.updateService()
def CIHelperset(self):
if fileExists('/etc/rcS.d/S50cihelper.sh') or fileExists('/etc/rc4.d/S50cihelper.sh'):
self.Console.ePopen('update-rc.d -f cihelper.sh remove', self.StartStopCallback)
else:
self.Console.ePopen('update-rc.d -f -s cihelper.sh start 50 S .', self.StartStopCallback)
def updateService(self):
import process
p = process.ProcessList()
cihelper_process = str(p.named('cihelper')).strip('[]')
self['labrun'].hide()
self['labstop'].hide()
self['labactive'].hide()
self['labdisabled'].hide()
self.my_cihelper_active = False
self.my_cihelper_run = False
if fileExists('/etc/rcS.d/S50cihelper.sh') or fileExists('/etc/rc4.d/S50cihelper.sh'):
self['labdisabled'].hide()
self['labactive'].show()
self.my_cihelper_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 cihelper_process:
self.my_cihelper_run = True
if self.my_cihelper_run:
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/cihelper.conf'):
f = open('/etc/cihelper.conf', 'r')
for line in f.readlines():
line = line.strip()
if line.startswith('ENABLE_CI0='):
if line[11:] == 'no':
self['ci0active'].hide()
self['ci0inactive'].show()
else:
self['ci0active'].show()
self['ci0inactive'].hide()
elif fileExists('/dev/ci1'):
if line.startswith('ENABLE_CI1='):
if line[11:] == 'no':
self['ci1active'].hide()
self['ci1inactive'].show()
else:
self['ci1active'].show()
self['ci1inactive'].hide()
else:
self['ci1active'].hide()
self['ci1inactive'].hide()
self['ci1'].hide()
f.close()
title = _("CIHelper Setup")
for cb in self.onChangedEntry:
cb(title, status_summary, autostartstatus_summary)
def setupcihelper(self):
self.session.openWithCallback(self.updateService, CIHelperSetup)
class CIHelperSetup(Screen, ConfigListScreen):
def __init__(self, session):
Screen.__init__(self, session)
Screen.setTitle(self, _("CIHelper Setup"))
self.onChangedEntry = [ ]
self.list = []
ConfigListScreen.__init__(self, self.list, session = self.session, on_change = self.selectionChanged)
Screen.setTitle(self, _("CIHelper Setup"))
self['key_red'] = Label(_("Save"))
self['actions'] = ActionMap(['WizardActions', 'ColorActions'], {'red': self.saveCIHelper, 'back': self.close})
self.updateList()
if not self.selectionChanged in self["config"].onSelectionChanged:
self["config"].onSelectionChanged.append(self.selectionChanged)
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.cihelper_ci0 = NoSave(ConfigYesNo(default='True'))
if fileExists('/dev/ci1'):
self.cihelper_ci1 = NoSave(ConfigYesNo(default='True'))
else:
self.cihelper_ci1 = ConfigNothing()
if fileExists('/etc/cihelper.conf'):
f = open('/etc/cihelper.conf', 'r')
for line in f.readlines():
line = line.strip()
if line.startswith('ENABLE_CI0='):
if line[11:] == 'no':
self.cihelper_ci0.value = False
else:
self.cihelper_ci0.value = True
cihelper_ci0x = getConfigListEntry(_("Enable CIHelper for SLOT CI0") + ":", self.cihelper_ci0)
self.list.append(cihelper_ci0x)
elif line.startswith('ENABLE_CI1='):
if line[11:] == 'no':
self.cihelper_ci1.value = False
else:
self.cihelper_ci1.value = True
if fileExists('/dev/ci1'):
cihelper_ci1x = getConfigListEntry(_("Enable CIHelper for SLOT CI1") + ":", self.cihelper_ci1)
self.list.append(cihelper_ci1x)
f.close()
self['config'].list = self.list
self['config'].l.setList(self.list)
def saveCIHelper(self):
if fileExists('/etc/cihelper.conf'):
inme = open('/etc/cihelper.conf', 'r')
out = open('/etc/cihelper.conf.tmp', 'w')
for line in inme.readlines():
line = line.replace('\n', '')
if line.startswith('ENABLE_CI0='):
if not self.cihelper_ci0.value:
line = 'ENABLE_CI0=no'
else:
line = 'ENABLE_CI0=yes'
elif line.startswith('ENABLE_CI1='):
if not self.cihelper_ci1.value:
line = 'ENABLE_CI1=no'
else:
line = 'ENABLE_CI1=yes'
out.write((line + '\n'))
out.close()
inme.close()
else:
open('/tmp/CIHelper.log', "a").write(_("Sorry CIHelper Config is Missing") + '\n')
self.session.open(MessageBox, _("Sorry CIHelper Config is Missing"), MessageBox.TYPE_INFO)
self.close()
if fileExists('/etc/cihelper.conf.tmp'):
rename('/etc/cihelper.conf.tmp', '/etc/cihelper.conf')
self.myStop()
def myStop(self):
self.close()
| gpl-2.0 |
DavidPurcell/murano_temp | murano/tests/unit/api/v1/test_sessions.py | 1 | 16337 | # Copyright (c) 2015 Mirantis 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 mock
from oslo_config import fixture as config_fixture
from oslo_serialization import jsonutils
from murano.api.v1 import environments
from murano.api.v1 import sessions
from murano.db import models
from murano.db import session as db_session
from murano.services import states
import murano.tests.unit.api.base as tb
from webob import exc
class TestSessionsApi(tb.ControllerTest, tb.MuranoApiTestCase):
def setUp(self):
super(TestSessionsApi, self).setUp()
self.environments_controller = environments.Controller()
self.sessions_controller = sessions.Controller()
self.fixture = self.useFixture(config_fixture.Config())
self.fixture.conf(args=[])
def test_deploy_session(self):
CREDENTIALS = {'tenant': 'test_tenant_1', 'user': 'test_user_1'}
self._set_policy_rules(
{'create_environment': '@'}
)
self.expect_policy_check('create_environment')
request = self._post(
'/environments',
jsonutils.dump_as_bytes({'name': 'test_environment_1'}),
**CREDENTIALS
)
response_body = jsonutils.loads(request.get_response(self.api).body)
ENVIRONMENT_ID = response_body['id']
request = self._post(
'/environments/{environment_id}/configure'
.format(environment_id=ENVIRONMENT_ID),
b'',
**CREDENTIALS
)
response_body = jsonutils.loads(request.get_response(self.api).body)
SESSION_ID = response_body['id']
request = self._post(
'/environments/{environment_id}/sessions/'
'{session_id}/deploy'.format(environment_id=ENVIRONMENT_ID,
session_id=SESSION_ID),
b'',
**CREDENTIALS
)
response = request.get_response(self.api)
self.assertEqual(response.status_code, 200)
request = self._get(
'/environments/{environment_id}/sessions/{session_id}'
.format(environment_id=ENVIRONMENT_ID, session_id=SESSION_ID),
b'',
**CREDENTIALS
)
response_body = jsonutils.loads(request.get_response(self.api).body)
self.assertIn(response_body['state'], [states.SessionState.DEPLOYED,
states.SessionState.DEPLOYING])
def test_cant_deploy_from_another_tenant(self):
"""Test to prevent deployment under another tenant user's creds
If user from one tenant uses session id and environment id
of user from another tenant - he is not able to deploy
the environment.
Bug: #1382026
"""
CREDENTIALS_1 = {'tenant': 'test_tenant_1', 'user': 'test_user_1'}
CREDENTIALS_2 = {'tenant': 'test_tenant_2', 'user': 'test_user_2'}
self._set_policy_rules(
{'create_environment': '@'}
)
self.expect_policy_check('create_environment')
# Create environment for user #1
request = self._post(
'/environments',
jsonutils.dump_as_bytes({'name': 'test_environment_1'}),
**CREDENTIALS_1
)
response_body = jsonutils.loads(request.get_response(self.api).body)
self.assertEqual(CREDENTIALS_1['tenant'],
response_body['tenant_id'])
ENVIRONMENT_ID = response_body['id']
# Create session of user #1
request = self._post(
'/environments/{environment_id}/configure'
.format(environment_id=ENVIRONMENT_ID),
b'',
**CREDENTIALS_1
)
response_body = jsonutils.loads(request.get_response(self.api).body)
SESSION_ID = response_body['id']
# Deploy the environment using environment id and session id of user #1
# by user #2
request = self._post(
'/environments/{environment_id}/sessions/'
'{session_id}/deploy'
.format(environment_id=ENVIRONMENT_ID, session_id=SESSION_ID),
b'',
**CREDENTIALS_2
)
response = request.get_response(self.api)
# Should be forbidden!
self.assertEqual(403, response.status_code)
def test_session_show(self):
CREDENTIALS_1 = {'tenant': 'test_tenant_1', 'user': 'test_user_1'}
CREDENTIALS_2 = {'tenant': 'test_tenant_2', 'user': 'test_user_2'}
self._set_policy_rules(
{'create_environment': '@'}
)
self.expect_policy_check('create_environment')
# Create environment for user #1
request = self._post(
'/environments',
jsonutils.dump_as_bytes({'name': 'test_environment_1'}),
**CREDENTIALS_1
)
response_body = jsonutils.loads(request.get_response(self.api).body)
self.assertEqual(CREDENTIALS_1['tenant'],
response_body['tenant_id'])
ENVIRONMENT_ID = response_body['id']
# Create session of user #1
request = self._post(
'/environments/{environment_id}/configure'
.format(environment_id=ENVIRONMENT_ID),
b'',
**CREDENTIALS_1
)
response_body = jsonutils.loads(request.get_response(self.api).body)
SESSION_ID = response_body['id']
# Show environment with correct credentials
request = self._get(
'/environments/{environment_id}/sessions/{session_id}'
.format(environment_id=ENVIRONMENT_ID, session_id=SESSION_ID),
b'',
**CREDENTIALS_1
)
response_body = jsonutils.loads(request.get_response(self.api).body)
self.assertEqual(SESSION_ID, response_body['id'])
# Show environment with incorrect credentials
request = self._get(
'/environments/{environment_id}/sessions/{session_id}'
.format(environment_id=ENVIRONMENT_ID, session_id=SESSION_ID),
b'',
**CREDENTIALS_2
)
response = request.get_response(self.api)
self.assertEqual(403, response.status_code)
def test_session_delete(self):
CREDENTIALS = {'tenant': 'test_tenant_1', 'user': 'test_user_1'}
self._set_policy_rules(
{'create_environment': '@'}
)
self.expect_policy_check('create_environment')
# Create environment
request = self._post(
'/environments',
jsonutils.dump_as_bytes({'name': 'test_environment_1'}),
**CREDENTIALS
)
response_body = jsonutils.loads(request.get_response(self.api).body)
self.assertEqual(CREDENTIALS['tenant'],
response_body['tenant_id'])
ENVIRONMENT_ID = response_body['id']
# Create session
request = self._post(
'/environments/{environment_id}/configure'
.format(environment_id=ENVIRONMENT_ID),
b'',
**CREDENTIALS
)
response_body = jsonutils.loads(request.get_response(self.api).body)
SESSION_ID = response_body['id']
# Delete session
request = self._delete(
'/environments/{environment_id}/delete/{session_id}'
.format(environment_id=ENVIRONMENT_ID, session_id=SESSION_ID),
b'',
**CREDENTIALS
)
response = self.sessions_controller.delete(
request, ENVIRONMENT_ID, SESSION_ID)
# Make sure the session was deleted
request = self._get(
'/environments/{environment_id}/sessions/{session_id}'
.format(environment_id=ENVIRONMENT_ID, session_id=SESSION_ID),
b'',
**CREDENTIALS
)
response = request.get_response(self.api)
self.assertEqual(404, response.status_code)
unit = db_session.get_session()
session = unit.query(models.Session).get(SESSION_ID)
self.assertIsNone(session)
@mock.patch('murano.db.services.environments.EnvironmentServices.'
'get_status')
def test_configure_handle_exc(self, mock_function):
"""Test whether env status in DEPLOYING, DELETING throws exception."""
CREDENTIALS = {'tenant': 'test_tenant_1', 'user': 'test_user_1'}
self._set_policy_rules(
{'create_environment': '@'}
)
self.expect_policy_check('create_environment')
request = self._post(
'/environments',
jsonutils.dump_as_bytes({'name': 'test_environment_1'}),
**CREDENTIALS
)
response_body = jsonutils.loads(request.get_response(self.api).body)
ENVIRONMENT_ID = response_body['id']
env_statuses = [states.EnvironmentStatus.DEPLOYING,
states.EnvironmentStatus.DELETING]
for env_status in env_statuses:
mock_function.return_value = env_status
request = self._post(
'/environments/{environment_id}/configure'
.format(environment_id=ENVIRONMENT_ID),
b'',
**CREDENTIALS
)
response = request.get_response(self.api)
self.assertEqual(response.status_code, 403)
self.assertEqual(mock_function.call_count, len(env_statuses))
def test_show_handle_exc(self):
"""Test whether invalid user/invalid session throws exception."""
CREDENTIALS = {'tenant': 'test_tenant_1', 'user': 'test_user_1'}
self._set_policy_rules(
{'create_environment': '@'}
)
self.expect_policy_check('create_environment')
request = self._post(
'/environments',
jsonutils.dump_as_bytes({'name': 'test_environment_1'}),
**CREDENTIALS
)
response_body = jsonutils.loads(request.get_response(self.api).body)
ENVIRONMENT_ID = response_body['id']
request = self._post(
'/environments/{environment_id}/configure'
.format(environment_id=ENVIRONMENT_ID),
b'',
**CREDENTIALS
)
response_body = jsonutils.loads(request.get_response(self.api).body)
SESSION_ID = response_body['id']
unit = db_session.get_session()
environment = unit.query(models.Environment).get(ENVIRONMENT_ID)
mock_context = mock.MagicMock(user_id=None,
tenant=environment.tenant_id)
mock_request = mock.MagicMock(context=mock_context)
self.assertRaises(exc.HTTPUnauthorized,
self.sessions_controller.show,
mock_request,
ENVIRONMENT_ID,
SESSION_ID)
with mock.patch('murano.db.services.sessions.SessionServices.'
'validate') as mock_validate:
mock_validate.return_value = False
request = self._get(
'/environments/{environment_id}/sessions/{session_id}'
.format(environment_id=ENVIRONMENT_ID, session_id=SESSION_ID),
b'',
**CREDENTIALS
)
response = request.get_response(self.api)
self.assertEqual(response.status_code, 403)
def test_delete_handle_exc(self):
"""Test whether invalid user/invalid session throws exception."""
CREDENTIALS = {'tenant': 'test_tenant_1', 'user': 'test_user_1'}
self._set_policy_rules(
{'create_environment': '@'}
)
self.expect_policy_check('create_environment')
request = self._post(
'/environments',
jsonutils.dump_as_bytes({'name': 'test_environment_1'}),
**CREDENTIALS
)
response_body = jsonutils.loads(request.get_response(self.api).body)
ENVIRONMENT_ID = response_body['id']
request = self._post(
'/environments/{environment_id}/configure'
.format(environment_id=ENVIRONMENT_ID),
b'',
**CREDENTIALS
)
response_body = jsonutils.loads(request.get_response(self.api).body)
SESSION_ID = response_body['id']
unit = db_session.get_session()
environment = unit.query(models.Environment).get(ENVIRONMENT_ID)
mock_context = mock.MagicMock(user_id=None,
tenant=environment.tenant_id)
mock_request = mock.MagicMock(context=mock_context)
self.assertRaises(exc.HTTPUnauthorized,
self.sessions_controller.delete, mock_request,
ENVIRONMENT_ID, SESSION_ID)
with mock.patch('murano.services.states.SessionState') as mock_state:
unit = db_session.get_session()
session = unit.query(models.Session).get(SESSION_ID)
mock_state.DEPLOYING = session.state
request = self._delete(
'/environments/{environment_id}/delete/{session_id}'
.format(environment_id=ENVIRONMENT_ID, session_id=SESSION_ID),
b'',
**CREDENTIALS
)
self.assertRaises(exc.HTTPForbidden,
self.sessions_controller.delete, request,
ENVIRONMENT_ID, SESSION_ID)
def test_deploy_handle_exc(self):
"""Test whether invalid user/invalid session throws exception."""
CREDENTIALS = {'tenant': 'test_tenant_1', 'user': 'test_user_1'}
self._set_policy_rules(
{'create_environment': '@'}
)
self.expect_policy_check('create_environment')
request = self._post(
'/environments',
jsonutils.dump_as_bytes({'name': 'test_environment_1'}),
**CREDENTIALS
)
response_body = jsonutils.loads(request.get_response(self.api).body)
ENVIRONMENT_ID = response_body['id']
request = self._post(
'/environments/{environment_id}/configure'
.format(environment_id=ENVIRONMENT_ID),
b'',
**CREDENTIALS
)
response_body = jsonutils.loads(request.get_response(self.api).body)
SESSION_ID = response_body['id']
with mock.patch('murano.db.services.sessions.SessionServices.'
'validate') as mock_validate:
mock_validate.return_value = False
request = self._post(
'/environments/{environment_id}/sessions/'
'{session_id}/deploy'.format(environment_id=ENVIRONMENT_ID,
session_id=SESSION_ID),
b'',
**CREDENTIALS
)
self.assertRaises(exc.HTTPForbidden,
self.sessions_controller.deploy, request,
ENVIRONMENT_ID, SESSION_ID)
with mock.patch('murano.db.services.sessions.SessionServices.'
'validate') as mock_validate:
with mock.patch('murano.services.states.SessionState')\
as mock_state:
mock_validate.return_value = True
mock_state.OPENED = 'NOT OPENED STATE'
request = self._post(
'/environments/{environment_id}/deploy/{session_id}'
.format(environment_id=ENVIRONMENT_ID,
session_id=SESSION_ID),
b'',
**CREDENTIALS
)
self.assertRaises(exc.HTTPForbidden,
self.sessions_controller.deploy, request,
ENVIRONMENT_ID, SESSION_ID)
| apache-2.0 |
newswangerd/ansible | lib/ansible/template/native_helpers.py | 31 | 3191 | # Copyright: (c) 2018, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ast import literal_eval
from itertools import islice, chain
import types
from jinja2.runtime import StrictUndefined
from ansible.module_utils._text import to_text
from ansible.module_utils.common.collections import is_sequence, Mapping
from ansible.module_utils.common.text.converters import container_to_text
from ansible.module_utils.six import PY2, text_type
from ansible.parsing.yaml.objects import AnsibleVaultEncryptedUnicode
from ansible.utils.native_jinja import NativeJinjaText
def _fail_on_undefined(data):
"""Recursively find an undefined value in a nested data structure
and properly raise the undefined exception.
"""
if isinstance(data, Mapping):
for value in data.values():
_fail_on_undefined(value)
elif is_sequence(data):
for item in data:
_fail_on_undefined(item)
else:
if isinstance(data, StrictUndefined):
# To actually raise the undefined exception we need to
# access the undefined object otherwise the exception would
# be raised on the next access which might not be properly
# handled.
# See https://github.com/ansible/ansible/issues/52158
# and StrictUndefined implementation in upstream Jinja2.
str(data)
return data
def ansible_native_concat(nodes):
"""Return a native Python type from the list of compiled nodes. If the
result is a single node, its value is returned. Otherwise, the nodes are
concatenated as strings. If the result can be parsed with
:func:`ast.literal_eval`, the parsed value is returned. Otherwise, the
string is returned.
https://github.com/pallets/jinja/blob/master/src/jinja2/nativetypes.py
"""
head = list(islice(nodes, 2))
if not head:
return None
if len(head) == 1:
out = _fail_on_undefined(head[0])
# TODO send unvaulted data to literal_eval?
if isinstance(out, AnsibleVaultEncryptedUnicode):
return out.data
if isinstance(out, NativeJinjaText):
# Sometimes (e.g. ``| string``) we need to mark variables
# in a special way so that they remain strings and are not
# passed into literal_eval.
# See:
# https://github.com/ansible/ansible/issues/70831
# https://github.com/pallets/jinja/issues/1200
# https://github.com/ansible/ansible/issues/70831#issuecomment-664190894
return out
else:
if isinstance(nodes, types.GeneratorType):
nodes = chain(head, nodes)
out = u''.join([to_text(_fail_on_undefined(v)) for v in nodes])
try:
out = literal_eval(out)
if PY2:
# ensure bytes are not returned back into Ansible from templating
out = container_to_text(out)
return out
except (ValueError, SyntaxError, MemoryError):
return out
| gpl-3.0 |
rohitranjan1991/home-assistant | homeassistant/components/notify/instapush.py | 2 | 3638 | """
homeassistant.components.notify.instapush
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Instapush notification service.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/notify.instapush.html
"""
import logging
import json
from homeassistant.helpers import validate_config
from homeassistant.components.notify import (
DOMAIN, ATTR_TITLE, BaseNotificationService)
from homeassistant.const import CONF_API_KEY
_LOGGER = logging.getLogger(__name__)
_RESOURCE = 'https://api.instapush.im/v1/'
def get_service(hass, config):
""" Get the instapush notification service. """
if not validate_config(config,
{DOMAIN: [CONF_API_KEY,
'app_secret',
'event',
'tracker']},
_LOGGER):
return None
try:
import requests
except ImportError:
_LOGGER.exception(
"Unable to import requests. "
"Did you maybe not install the 'Requests' package?")
return None
# pylint: disable=unused-variable
try:
response = requests.get(_RESOURCE)
except requests.ConnectionError:
_LOGGER.error(
"Connection error "
"Please check if https://instapush.im is available.")
return None
instapush = requests.Session()
headers = {'x-instapush-appid': config[DOMAIN][CONF_API_KEY],
'x-instapush-appsecret': config[DOMAIN]['app_secret']}
response = instapush.get(_RESOURCE + 'events/list',
headers=headers)
try:
if response.json()['error']:
_LOGGER.error(response.json()['msg'])
# pylint: disable=bare-except
except:
try:
next(events for events in response.json()
if events['title'] == config[DOMAIN]['event'])
except StopIteration:
_LOGGER.error(
"No event match your given value. "
"Please create an event at https://instapush.im")
else:
return InstapushNotificationService(
config[DOMAIN].get(CONF_API_KEY),
config[DOMAIN]['app_secret'],
config[DOMAIN]['event'],
config[DOMAIN]['tracker']
)
# pylint: disable=too-few-public-methods
class InstapushNotificationService(BaseNotificationService):
""" Implements notification service for Instapush. """
def __init__(self, api_key, app_secret, event, tracker):
# pylint: disable=no-name-in-module, unused-variable
from requests import Session
self._api_key = api_key
self._app_secret = app_secret
self._event = event
self._tracker = tracker
self._headers = {
'x-instapush-appid': self._api_key,
'x-instapush-appsecret': self._app_secret,
'Content-Type': 'application/json'}
self.instapush = Session()
def send_message(self, message="", **kwargs):
""" Send a message to a user. """
title = kwargs.get(ATTR_TITLE)
data = {"event": self._event,
"trackers": {self._tracker: title + " : " + message}}
response = self.instapush.post(
_RESOURCE + 'post',
data=json.dumps(data),
headers=self._headers)
if response.json()['status'] == 401:
_LOGGER.error(
response.json()['msg'],
"Please check your details at https://instapush.im/")
| mit |
amghost/myblog | node_modules/pygmentize-bundled/vendor/pygments/build-2.7/pygments/lexers/__init__.py | 194 | 7698 | # -*- coding: utf-8 -*-
"""
pygments.lexers
~~~~~~~~~~~~~~~
Pygments lexers.
:copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import sys
import types
import fnmatch
from os.path import basename
from pygments.lexers._mapping import LEXERS
from pygments.modeline import get_filetype_from_buffer
from pygments.plugin import find_plugin_lexers
from pygments.util import ClassNotFound, bytes
__all__ = ['get_lexer_by_name', 'get_lexer_for_filename', 'find_lexer_class',
'guess_lexer'] + LEXERS.keys()
_lexer_cache = {}
def _load_lexers(module_name):
"""
Load a lexer (and all others in the module too).
"""
mod = __import__(module_name, None, None, ['__all__'])
for lexer_name in mod.__all__:
cls = getattr(mod, lexer_name)
_lexer_cache[cls.name] = cls
def get_all_lexers():
"""
Return a generator of tuples in the form ``(name, aliases,
filenames, mimetypes)`` of all know lexers.
"""
for item in LEXERS.itervalues():
yield item[1:]
for lexer in find_plugin_lexers():
yield lexer.name, lexer.aliases, lexer.filenames, lexer.mimetypes
def find_lexer_class(name):
"""
Lookup a lexer class by name. Return None if not found.
"""
if name in _lexer_cache:
return _lexer_cache[name]
# lookup builtin lexers
for module_name, lname, aliases, _, _ in LEXERS.itervalues():
if name == lname:
_load_lexers(module_name)
return _lexer_cache[name]
# continue with lexers from setuptools entrypoints
for cls in find_plugin_lexers():
if cls.name == name:
return cls
def get_lexer_by_name(_alias, **options):
"""
Get a lexer by an alias.
"""
# lookup builtin lexers
for module_name, name, aliases, _, _ in LEXERS.itervalues():
if _alias in aliases:
if name not in _lexer_cache:
_load_lexers(module_name)
return _lexer_cache[name](**options)
# continue with lexers from setuptools entrypoints
for cls in find_plugin_lexers():
if _alias in cls.aliases:
return cls(**options)
raise ClassNotFound('no lexer for alias %r found' % _alias)
def get_lexer_for_filename(_fn, code=None, **options):
"""
Get a lexer for a filename. If multiple lexers match the filename
pattern, use ``analyze_text()`` to figure out which one is more
appropriate.
"""
matches = []
fn = basename(_fn)
for modname, name, _, filenames, _ in LEXERS.itervalues():
for filename in filenames:
if fnmatch.fnmatch(fn, filename):
if name not in _lexer_cache:
_load_lexers(modname)
matches.append((_lexer_cache[name], filename))
for cls in find_plugin_lexers():
for filename in cls.filenames:
if fnmatch.fnmatch(fn, filename):
matches.append((cls, filename))
if sys.version_info > (3,) and isinstance(code, bytes):
# decode it, since all analyse_text functions expect unicode
code = code.decode('latin1')
def get_rating(info):
cls, filename = info
# explicit patterns get a bonus
bonus = '*' not in filename and 0.5 or 0
# The class _always_ defines analyse_text because it's included in
# the Lexer class. The default implementation returns None which
# gets turned into 0.0. Run scripts/detect_missing_analyse_text.py
# to find lexers which need it overridden.
if code:
return cls.analyse_text(code) + bonus
return cls.priority + bonus
if matches:
matches.sort(key=get_rating)
#print "Possible lexers, after sort:", matches
return matches[-1][0](**options)
raise ClassNotFound('no lexer for filename %r found' % _fn)
def get_lexer_for_mimetype(_mime, **options):
"""
Get a lexer for a mimetype.
"""
for modname, name, _, _, mimetypes in LEXERS.itervalues():
if _mime in mimetypes:
if name not in _lexer_cache:
_load_lexers(modname)
return _lexer_cache[name](**options)
for cls in find_plugin_lexers():
if _mime in cls.mimetypes:
return cls(**options)
raise ClassNotFound('no lexer for mimetype %r found' % _mime)
def _iter_lexerclasses():
"""
Return an iterator over all lexer classes.
"""
for key in sorted(LEXERS):
module_name, name = LEXERS[key][:2]
if name not in _lexer_cache:
_load_lexers(module_name)
yield _lexer_cache[name]
for lexer in find_plugin_lexers():
yield lexer
def guess_lexer_for_filename(_fn, _text, **options):
"""
Lookup all lexers that handle those filenames primary (``filenames``)
or secondary (``alias_filenames``). Then run a text analysis for those
lexers and choose the best result.
usage::
>>> from pygments.lexers import guess_lexer_for_filename
>>> guess_lexer_for_filename('hello.html', '<%= @foo %>')
<pygments.lexers.templates.RhtmlLexer object at 0xb7d2f32c>
>>> guess_lexer_for_filename('hello.html', '<h1>{{ title|e }}</h1>')
<pygments.lexers.templates.HtmlDjangoLexer object at 0xb7d2f2ac>
>>> guess_lexer_for_filename('style.css', 'a { color: <?= $link ?> }')
<pygments.lexers.templates.CssPhpLexer object at 0xb7ba518c>
"""
fn = basename(_fn)
primary = None
matching_lexers = set()
for lexer in _iter_lexerclasses():
for filename in lexer.filenames:
if fnmatch.fnmatch(fn, filename):
matching_lexers.add(lexer)
primary = lexer
for filename in lexer.alias_filenames:
if fnmatch.fnmatch(fn, filename):
matching_lexers.add(lexer)
if not matching_lexers:
raise ClassNotFound('no lexer for filename %r found' % fn)
if len(matching_lexers) == 1:
return matching_lexers.pop()(**options)
result = []
for lexer in matching_lexers:
rv = lexer.analyse_text(_text)
if rv == 1.0:
return lexer(**options)
result.append((rv, lexer))
result.sort()
if not result[-1][0] and primary is not None:
return primary(**options)
return result[-1][1](**options)
def guess_lexer(_text, **options):
"""
Guess a lexer by strong distinctions in the text (eg, shebang).
"""
# try to get a vim modeline first
ft = get_filetype_from_buffer(_text)
if ft is not None:
try:
return get_lexer_by_name(ft, **options)
except ClassNotFound:
pass
best_lexer = [0.0, None]
for lexer in _iter_lexerclasses():
rv = lexer.analyse_text(_text)
if rv == 1.0:
return lexer(**options)
if rv > best_lexer[0]:
best_lexer[:] = (rv, lexer)
if not best_lexer[0] or best_lexer[1] is None:
raise ClassNotFound('no lexer matching the text found')
return best_lexer[1](**options)
class _automodule(types.ModuleType):
"""Automatically import lexers."""
def __getattr__(self, name):
info = LEXERS.get(name)
if info:
_load_lexers(info[0])
cls = _lexer_cache[info[1]]
setattr(self, name, cls)
return cls
raise AttributeError(name)
oldmod = sys.modules['pygments.lexers']
newmod = _automodule('pygments.lexers')
newmod.__dict__.update(oldmod.__dict__)
sys.modules['pygments.lexers'] = newmod
del newmod.newmod, newmod.oldmod, newmod.sys, newmod.types
| mit |
graik/biskit | biskit/amberResidueLibrary.py | 1 | 8496 | ##
## Biskit, a toolkit for the manipulation of macromolecular structures
## Copyright (C) 2004-2018 Raik Gruenberg
##
## This program is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 3 of the
## License, or 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 find a copy of the GNU General Public License in the file
## license.txt along with this program; if not, write to the Free
## Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
"""
Collect and index AmberResidueType instances from amber topology files.
"""
from biskit import PDBModel, AmberPrepParser, StdLog
import biskit.tools as T
class AmberResidueLibraryError( Exception ):
pass
class AmberResidueLibrary:
"""
A collection of reference residue types taken from Amber topology files.
By default, the collection is initialized from the four all-atom
library or "off files" in Biskit/data/amber/residues.
The idea here is that the residues of some PDB structure can be matched
against this library in order to assign charges or other properties.
Matching residue types are indentified by their 'atom key', which is simply
the concatenation of a residue's atom names in alphabetical order. This
means residues are matched by atom content, not by residue name. That's
important for modified residues, for example, a C-terminal ALA (with an
additional oxygen) will be matched to the AmberResidueType CALA rather than
to ALA.
The default all-atom topologies include hydrogen atoms. Structures without
hydrogens will *not* match. You can add hydrogens with the Reduce class
(biskit.reduce).
Atom names need to conform to Amber conventions --
this can be ensured with `PDBModel.xplor2amber()`.
Use
===
>>> model = PDBModel('mystructure.pdb')
>>> residue = model.resModels()[0] ## fetch first residue
>>>
>>> lib = AmberResidueLibrary()
>>> refres = lib[ residue ] ## look up matching AmberResidueType
>>>
>>> ## or alternatively:
>>> refres = lib['all_amino03', 'ALA']
"""
## list of Amber topology files in decending priority
F_RESTYPES = ['all_amino03.in',
'all_aminoct03.in',
'all_aminont03.in',
'all_nuc02.in' ]
def __init__(self, topofiles=F_RESTYPES, log=None, verbose=False):
"""
:param topofiles: list of topology file names \
(default `all_*in` in `Biskit/data/amber/residues`)
:type topofiles: [ str ]
:param log: optional LogFile instance (default STDOUT)
:type log: biskit.LogFile
:param verbose: add messages to log (default False)
:type verbose: bool
"""
self.aindex = {} ## residue types indexed by atom key
self.topoindex = {} ## residue types indexed by topo and resname
self.log = log or StdLog()
self.verbose = verbose
for f in topofiles:
self.addTopology( f )
def addTopology(self, topofile, override=False):
"""
Include an additional topology (off) library in the collection.
:param topofile: file name of topology, either full path or
simple file name which will then be looked for in
biskit/data/amber/residues.
:type topofile: str
:param override: override topologies or residue entries with same name
(default False)
:type override: False
:return: dictionary of all residue types parsed from topofile indexed
by three-letter residue name
:rtype : {str : AmberResidueType}
:raise: AmberResidueLibraryError if override==False and a topology or
a residue with identical atom content have already been
registered.
"""
fbase = T.stripFilename( topofile )
if fbase in self.topoindex and not override:
raise AmberResidueLibraryError('duplicate topology '+fbase)
if self.verbose:
self.log.add('parsing %s...' % topofile )
resdic = AmberPrepParser( topofile ).residueDict()
if self.verbose:
self.log.add( 'Read %i residue definitions.\n' % len(resdic) )
self.topoindex[ fbase ] = resdic
for resname, restype in resdic.items():
akey = restype.atomkey(compress=False)
if akey in self.aindex and not override:
raise AmberResidueLibraryError('duplicate residue entry: %s -> %s' %\
(resname, self.aindex[akey].code))
self.aindex[ akey ] = restype
return self.topoindex[ fbase ]
def atomkey( self, residue ):
"""
Create a string key encoding the atom content of residue.
:param residue: model or AmberResidue
:type residue: PDBModel or AmberResidue
:return: key formed from alphabetically sorted atom content of residue
:rtype: str
"""
return residue.atomkey(compress=False)
def byAtoms(self, akey, default=None ):
"""
Identify a matching reference residue by atom content.
:param akey: atomkey or PDBModel with a single residue
:type akey: str or PDBModel
:return: matching reference residue OR None
:rtype: AmberResidueType
"""
if isinstance( akey, PDBModel ):
akey = akey.atomkey(compress=False)
return self.aindex.get(akey, default)
def byName(self, rescode, topo=None ):
"""
Identify matching reference residue by residue name. Note: residue
names are not guaranteed to be unique if several topology files have
been read in (the default set of Amber topologies uses unique names
though). The optional topo parameter can be used to specify in
which topology the residue is looked up.
Note: residue 3 letter names are all UPPERCASE.
:param rescode: three-letter name of residue to look up
:type rescode: str
:param topo: optional (file) name of topology (see also: `topokeys()` )
:type topo: str
:return: matching reference residue
:rtype: AmberResidueType
:raise: KeyError if the topology or residue name are not found
"""
if topo:
fbase = T.stripFilename( topo )
return self.topoindex[ fbase ][ rescode ]
for topo, residues in self.topoindex.items():
if rescode in residues:
return residues[rescode]
raise KeyError('No residue type found for name '+str(rescode))
def __len__( self ):
return len(self.aindex)
def __getitem__( self, key ):
"""
Examples:
- `reslib[ PDBModel ]` -> `ResidueType` for matching residue
- `reslib[ str(atomkey) ]` -> `ResidueType` with same atom key
"""
if type(key) is str:
return self.aindex[key]
if isinstance(key, PDBModel):
return self.aindex[ key.atomkey(compress=False) ]
def topokeys( self ):
return list(self.topoindex.keys())
def keys( self ):
return list(self.aindex.keys())
def values( self ):
return list(self.aindex.values())
#############
## TESTING
#############
import biskit.test as BT
class Test(BT.BiskitTest):
"""Test class"""
def test_amberResidueLibrary( self ):
"""AmberResidueLibrary test"""
self.lib = AmberResidueLibrary(verbose=self.local)
ala = self.lib.byName('ALA', 'all_amino03')
r = self.lib[ ala ]
self.assertEqual( r, ala )
r = self.lib.byName( 'ALA' )
self.assertEqual( r, ala )
self.assertEqual( len( self.lib ), 114 )
if __name__ == '__main__':
BT.localTest(debug=False)
| gpl-3.0 |
Kraxi/YTplaylist | venv/Lib/site-packages/wheel/pep425tags.py | 220 | 2861 | """Generate and work with PEP 425 Compatibility Tags."""
import sys
try:
import sysconfig
except ImportError: # pragma nocover
# Python < 2.7
import distutils.sysconfig as sysconfig
import distutils.util
def get_abbr_impl():
"""Return abbreviated implementation name."""
if hasattr(sys, 'pypy_version_info'):
pyimpl = 'pp'
elif sys.platform.startswith('java'):
pyimpl = 'jy'
elif sys.platform == 'cli':
pyimpl = 'ip'
else:
pyimpl = 'cp'
return pyimpl
def get_impl_ver():
"""Return implementation version."""
impl_ver = sysconfig.get_config_var("py_version_nodot")
if not impl_ver:
impl_ver = ''.join(map(str, sys.version_info[:2]))
return impl_ver
def get_platform():
"""Return our platform name 'win32', 'linux_x86_64'"""
# XXX remove distutils dependency
return distutils.util.get_platform().replace('.', '_').replace('-', '_')
def get_supported(versions=None):
"""Return a list of supported tags for each version specified in
`versions`.
:param versions: a list of string versions, of the form ["33", "32"],
or None. The first version will be assumed to support our ABI.
"""
supported = []
# Versions must be given with respect to the preference
if versions is None:
versions = []
major = sys.version_info[0]
# Support all previous minor Python versions.
for minor in range(sys.version_info[1], -1, -1):
versions.append(''.join(map(str, (major, minor))))
impl = get_abbr_impl()
abis = []
soabi = sysconfig.get_config_var('SOABI')
if soabi and soabi.startswith('cpython-'):
abis[0:0] = ['cp' + soabi.split('-', 1)[-1]]
abi3s = set()
import imp
for suffix in imp.get_suffixes():
if suffix[0].startswith('.abi'):
abi3s.add(suffix[0].split('.', 2)[1])
abis.extend(sorted(list(abi3s)))
abis.append('none')
arch = get_platform()
# Current version, current API (built specifically for our Python):
for abi in abis:
supported.append(('%s%s' % (impl, versions[0]), abi, arch))
# No abi / arch, but requires our implementation:
for i, version in enumerate(versions):
supported.append(('%s%s' % (impl, version), 'none', 'any'))
if i == 0:
# Tagged specifically as being cross-version compatible
# (with just the major version specified)
supported.append(('%s%s' % (impl, versions[0][0]), 'none', 'any'))
# No abi / arch, generic Python
for i, version in enumerate(versions):
supported.append(('py%s' % (version,), 'none', 'any'))
if i == 0:
supported.append(('py%s' % (version[0]), 'none', 'any'))
return supported
| gpl-2.0 |
ninotoshi/tensorflow | tensorflow/python/training/saver_test.py | 3 | 49397 | # Copyright 2015 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.
# ==============================================================================
"""Tests for tensorflow.python.training.saver.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import os.path
import time
import contextlib
import shutil
import tempfile
import tensorflow as tf
import numpy as np
import six
from google.protobuf.any_pb2 import Any
from tensorflow.core.framework import graph_pb2
from tensorflow.core.protobuf import meta_graph_pb2
from tensorflow.core.protobuf import queue_runner_pb2
from tensorflow.python.framework import errors
from tensorflow.python.framework import function
from tensorflow.python.platform import gfile
from tensorflow.python.training import saver as saver_module
from tensorflow.python.util import compat
def _TestDir(test_name):
test_dir = os.path.join(tf.test.get_temp_dir(), test_name)
if os.path.exists(test_dir):
shutil.rmtree(test_dir)
gfile.MakeDirs(test_dir)
return test_dir
class SaverTest(tf.test.TestCase):
def testBasics(self):
save_path = os.path.join(self.get_temp_dir(), "basics")
# Build a graph with 2 parameter nodes, and Save and
# Restore nodes for them.
v0 = tf.Variable(10.0, name="v0")
v1 = tf.Variable(20.0, name="v1")
save = tf.train.Saver({"v0": v0, "v1": v1}, restore_sequentially=True)
init_all_op = tf.initialize_all_variables()
with self.test_session() as sess:
# Initialize all variables
sess.run(init_all_op)
# Check that the parameter nodes have been initialized.
self.assertEqual(10.0, v0.eval())
self.assertEqual(20.0, v1.eval())
# Save the initialized values in the file at "save_path"
val = save.save(sess, save_path)
self.assertTrue(isinstance(val, six.string_types))
self.assertEqual(save_path, val)
# Start a second session. In that session the parameter nodes
# have not been initialized either.
with self.test_session() as sess:
v0 = tf.Variable(-1.0, name="v0")
v1 = tf.Variable(-1.0, name="v1")
save = tf.train.Saver({"v0": v0, "v1": v1})
with self.assertRaisesWithPredicateMatch(
tf.OpError, lambda e: "uninitialized value v0" in e.message):
sess.run(v0)
with self.assertRaisesWithPredicateMatch(
tf.OpError, lambda e: "uninitialized value v1" in e.message):
sess.run(v1)
# Restore the saved values in the parameter nodes.
save.restore(sess, save_path)
# Check that the parameter nodes have been restored.
self.assertEqual(10.0, v0.eval())
self.assertEqual(20.0, v1.eval())
# Build another graph with 2 nodes, initialized
# differently, and a Restore node for them.
with self.test_session() as sess:
v0_2 = tf.Variable(1000.0, name="v0")
v1_2 = tf.Variable(2000.0, name="v1")
save2 = tf.train.Saver({"v0": v0_2, "v1": v1_2})
tf.initialize_all_variables().run()
# Check that the parameter nodes have been initialized.
self.assertEqual(1000.0, v0_2.eval())
self.assertEqual(2000.0, v1_2.eval())
# Restore the values saved earlier in the parameter nodes.
save2.restore(sess, save_path)
# Check that the parameter nodes have been restored.
self.assertEqual(10.0, v0_2.eval())
self.assertEqual(20.0, v1_2.eval())
def testInt64(self):
save_path = os.path.join(self.get_temp_dir(), "int64")
with self.test_session() as sess:
# Build a graph with 1 node, and save and restore for them.
v = tf.Variable(np.int64(15), name="v")
save = tf.train.Saver({"v": v}, restore_sequentially=True)
tf.initialize_all_variables().run()
# Save the initialized values in the file at "save_path"
val = save.save(sess, save_path)
self.assertTrue(isinstance(val, six.string_types))
self.assertEqual(save_path, val)
with self.test_session() as sess:
v = tf.Variable(np.int64(-1), name="v")
save = tf.train.Saver({"v": v})
with self.assertRaisesWithPredicateMatch(
tf.OpError, lambda e: "uninitialized value v" in e.message):
sess.run(v)
# Restore the saved values in the parameter nodes.
save.restore(sess, save_path)
# Check that the parameter nodes have been restored.
self.assertEqual(np.int64(15), v.eval())
def testSomeErrors(self):
with tf.Graph().as_default():
v0 = tf.Variable([10.0], name="v0")
v1 = tf.Variable([20.0], name="v1")
v2 = tf.Variable([20.0], name="v2")
v2._set_save_slice_info(tf.Variable.SaveSliceInfo("v1", [1], [0], [1]))
# By default the name used for "v2" will be "v1" and raise an error.
with self.assertRaisesRegexp(ValueError, "same name: v1"):
tf.train.Saver([v0, v1, v2])
# The names are different and will work.
tf.train.Saver({"vee1": v1, "other": [v2]})
def testBasicsWithListOfVariables(self):
save_path = os.path.join(self.get_temp_dir(), "basics_with_list")
with self.test_session(graph=tf.Graph()) as sess:
# Build a graph with 2 parameter nodes, and Save and
# Restore nodes for them.
v0 = tf.Variable(10.0, name="v0")
v1 = tf.Variable(20.0, name="v1")
save = tf.train.Saver([v0, v1])
tf.initialize_all_variables().run()
# Check that the parameter nodes have been initialized.
self.assertEqual(10.0, v0.eval())
self.assertEqual(20.0, v1.eval())
# Save the initialized values in the file at "save_path"
val = save.save(sess, save_path)
self.assertTrue(isinstance(val, six.string_types))
self.assertEqual(save_path, val)
# Start a second session. In that session the variables
# have not been initialized either.
with self.test_session(graph=tf.Graph()) as sess:
v0 = tf.Variable(-1.0, name="v0")
v1 = tf.Variable(-1.0, name="v1")
save = tf.train.Saver([v0, v1])
with self.assertRaisesWithPredicateMatch(
tf.OpError, lambda e: "uninitialized value v0" in e.message):
sess.run(v0)
with self.assertRaisesWithPredicateMatch(
tf.OpError, lambda e: "uninitialized value v1" in e.message):
sess.run(v1)
# Restore the saved values in the parameter nodes.
save.restore(sess, save_path)
# Check that the parameter nodes have been restored.
self.assertEqual(10.0, v0.eval())
self.assertEqual(20.0, v1.eval())
# Build another graph with 2 nodes, initialized
# differently, and a Restore node for them.
with self.test_session(graph=tf.Graph()) as sess:
v0_2 = tf.Variable(1000.0, name="v0")
v1_2 = tf.Variable(2000.0, name="v1")
save2 = tf.train.Saver([v0_2, v1_2])
tf.initialize_all_variables().run()
# Check that the parameter nodes have been initialized.
self.assertEqual(1000.0, v0_2.eval())
self.assertEqual(2000.0, v1_2.eval())
# Restore the values saved earlier in the parameter nodes.
save2.restore(sess, save_path)
# Check that the parameter nodes have been restored.
self.assertEqual(10.0, v0_2.eval())
self.assertEqual(20.0, v1_2.eval())
def _SaveAndLoad(self, var_name, var_value, other_value, save_path):
with self.test_session() as sess:
var = tf.Variable(var_value, name=var_name)
save = tf.train.Saver({var_name: var})
var.initializer.run()
val = save.save(sess, save_path)
self.assertEqual(save_path, val)
with self.test_session() as sess:
var = tf.Variable(other_value, name=var_name)
save = tf.train.Saver({var_name: var})
save.restore(sess, save_path)
self.assertAllClose(var_value, var.eval())
def testCacheRereadsFile(self):
save_path = os.path.join(self.get_temp_dir(), "cache_rereads")
# Save and reload one Variable named "var0".
self._SaveAndLoad("var0", 0.0, 1.0, save_path)
# Save and reload one Variable named "var1" in the same file.
# The cached readers should know to re-read the file.
self._SaveAndLoad("var1", 1.1, 2.2, save_path)
def testGPU(self):
if not tf.test.is_built_with_cuda():
return
save_path = os.path.join(self.get_temp_dir(), "gpu")
with tf.Session("", graph=tf.Graph()) as sess:
with sess.graph.device("/gpu:0"):
v0_1 = tf.Variable(123.45)
save = tf.train.Saver({"v0": v0_1})
tf.initialize_all_variables().run()
save.save(sess, save_path)
with tf.Session("", graph=tf.Graph()) as sess:
with sess.graph.device("/gpu:0"):
v0_2 = tf.Variable(543.21)
save = tf.train.Saver({"v0": v0_2})
tf.initialize_all_variables().run()
self.assertAllClose(543.21, v0_2.eval())
save.restore(sess, save_path)
self.assertAllClose(123.45, v0_2.eval())
def testVariables(self):
save_path = os.path.join(self.get_temp_dir(), "variables")
with tf.Session("", graph=tf.Graph()) as sess:
one = tf.Variable(1.0)
twos = tf.Variable([2.0, 2.0, 2.0])
init = tf.initialize_all_variables()
save = tf.train.Saver(tf.all_variables())
init.run()
save.save(sess, save_path)
with tf.Session("", graph=tf.Graph()) as sess:
one = tf.Variable(0.0)
twos = tf.Variable([0.0, 0.0, 0.0])
# Saver with no arg, defaults to 'all variables'.
save = tf.train.Saver()
save.restore(sess, save_path)
self.assertAllClose(1.0, one.eval())
self.assertAllClose([2.0, 2.0, 2.0], twos.eval())
def testSaveWithGlobalStep(self):
save_path = os.path.join(self.get_temp_dir(), "ckpt_with_global_step")
global_step_int = 5
# Save and reload one Variable named "var0".
self._SaveAndLoad("var0", 0.0, 1.0, save_path)
for use_tensor in [True, False]:
with self.test_session() as sess:
var = tf.Variable(1.0, name="var0")
save = tf.train.Saver({var.op.name: var})
var.initializer.run()
if use_tensor:
global_step = tf.constant(global_step_int)
val = save.save(sess, save_path, global_step=global_step)
else:
val = save.save(sess, save_path, global_step=global_step_int)
expected_save_path = "%s-%d" % (save_path, global_step_int)
self.assertEqual(expected_save_path, val)
class SaveRestoreShardedTest(tf.test.TestCase):
def testBasics(self):
save_path = os.path.join(self.get_temp_dir(), "sharded")
# Build a graph with 2 parameter nodes on different devices.
with tf.Session(
target="",
config=tf.ConfigProto(device_count={"CPU": 2})) as sess:
with sess.graph.device("/cpu:0"):
v0 = tf.Variable(10, name="v0")
with sess.graph.device("/cpu:1"):
v1 = tf.Variable(20, name="v1")
save = tf.train.Saver({"v0": v0, "v1": v1}, sharded=True)
tf.initialize_all_variables().run()
val = save.save(sess, save_path)
self.assertEqual(save_path + "-?????-of-00002", val)
meta_graph_filename = save._MetaGraphFilename(val)
self.assertEqual(save_path + ".meta", meta_graph_filename)
# Restore a different "v0" from shard 0 of the saved files.
with tf.Session(
target="",
config=tf.ConfigProto(device_count={"CPU": 2})) as sess:
with sess.graph.device("/cpu:0"):
v0 = tf.Variable(111, name="v0")
save = tf.train.Saver({"v0": v0}, sharded=True)
tf.initialize_all_variables().run()
self.assertEqual(111, v0.eval())
save.restore(sess, save_path + "-00000-of-00002")
self.assertEqual(10, v0.eval())
# Restore a different "v1" from shard 1 of the saved files.
with tf.Session(
target="",
config=tf.ConfigProto(device_count={"CPU": 2})) as sess:
with sess.graph.device("/cpu:0"):
v1 = tf.Variable(222)
save = tf.train.Saver({"v1": v1}, sharded=True)
tf.initialize_all_variables().run()
self.assertEqual(222, v1.eval())
save.restore(sess, save_path + "-00001-of-00002")
self.assertEqual(20, v1.eval())
# Now try a restore with the sharded filename.
with tf.Session(
target="",
config=tf.ConfigProto(device_count={"CPU": 2})) as sess:
with sess.graph.device("/cpu:0"):
v0 = tf.Variable(111, name="v0")
with sess.graph.device("/cpu:1"):
v1 = tf.Variable(222, name="v1")
save = tf.train.Saver({"v0": v0, "v1": v1}, sharded=True)
tf.initialize_all_variables().run()
self.assertEqual(111, v0.eval())
self.assertEqual(222, v1.eval())
save_path = os.path.join(self.get_temp_dir(), "sharded")
save.restore(sess, save_path + "-?????-of-?????")
self.assertEqual(10, v0.eval())
self.assertEqual(20, v1.eval())
self.assertEqual(
tf.train.latest_checkpoint(self.get_temp_dir()),
os.path.join(self.get_temp_dir(), "sharded-?????-of-00002"))
def testSaverDef(self):
with self.test_session():
v0 = tf.Variable(123, name="v0")
save = tf.train.Saver({"v0": v0}, sharded=True)
sd = save.as_saver_def()
self.assertTrue(sd.sharded)
class MaxToKeepTest(tf.test.TestCase):
def testNonSharded(self):
save_dir = _TestDir("max_to_keep_non_sharded")
with self.test_session() as sess:
v = tf.Variable(10.0, name="v")
save = tf.train.Saver({"v": v}, max_to_keep=2)
tf.initialize_all_variables().run()
self.assertEqual([], save.last_checkpoints)
s1 = save.save(sess, os.path.join(save_dir, "s1"))
self.assertEqual([s1], save.last_checkpoints)
self.assertTrue(gfile.Exists(s1))
s2 = save.save(sess, os.path.join(save_dir, "s2"))
self.assertEqual([s1, s2], save.last_checkpoints)
self.assertTrue(gfile.Exists(s1))
self.assertTrue(gfile.Exists(s2))
s3 = save.save(sess, os.path.join(save_dir, "s3"))
self.assertEqual([s2, s3], save.last_checkpoints)
self.assertFalse(gfile.Exists(s1))
self.assertTrue(gfile.Exists(s2))
self.assertTrue(gfile.Exists(s3))
# Create a second helper, identical to the first.
save2 = tf.train.Saver(saver_def=save.as_saver_def())
save2.set_last_checkpoints(save.last_checkpoints)
# Create a third helper, with the same configuration but no knowledge of
# previous checkpoints.
save3 = tf.train.Saver(saver_def=save.as_saver_def())
# Exercise the first helper.
# Adding s2 again (old s2 is removed first, then new s2 appended)
s2 = save.save(sess, os.path.join(save_dir, "s2"))
self.assertEqual([s3, s2], save.last_checkpoints)
self.assertFalse(gfile.Exists(s1))
self.assertFalse(gfile.Exists(save._MetaGraphFilename(s1)))
self.assertTrue(gfile.Exists(s3))
self.assertTrue(gfile.Exists(save._MetaGraphFilename(s3)))
self.assertTrue(gfile.Exists(s2))
self.assertTrue(gfile.Exists(save._MetaGraphFilename(s2)))
# Adding s1 (s3 should now be deleted as oldest in list)
s1 = save.save(sess, os.path.join(save_dir, "s1"))
self.assertEqual([s2, s1], save.last_checkpoints)
self.assertFalse(gfile.Exists(s3))
self.assertFalse(gfile.Exists(save._MetaGraphFilename(s3)))
self.assertTrue(gfile.Exists(s2))
self.assertTrue(gfile.Exists(save._MetaGraphFilename(s2)))
self.assertTrue(gfile.Exists(s1))
self.assertTrue(gfile.Exists(save._MetaGraphFilename(s1)))
# Exercise the second helper.
# Adding s2 again (old s2 is removed first, then new s2 appended)
s2 = save2.save(sess, os.path.join(save_dir, "s2"))
self.assertEqual([s3, s2], save2.last_checkpoints)
# Created by the first helper.
self.assertTrue(gfile.Exists(s1))
self.assertTrue(gfile.Exists(save._MetaGraphFilename(s1)))
# Deleted by the first helper.
self.assertFalse(gfile.Exists(s3))
self.assertFalse(gfile.Exists(save._MetaGraphFilename(s3)))
self.assertTrue(gfile.Exists(s2))
self.assertTrue(gfile.Exists(save._MetaGraphFilename(s2)))
# Adding s1 (s3 should now be deleted as oldest in list)
s1 = save2.save(sess, os.path.join(save_dir, "s1"))
self.assertEqual([s2, s1], save2.last_checkpoints)
self.assertFalse(gfile.Exists(s3))
self.assertFalse(gfile.Exists(save._MetaGraphFilename(s3)))
self.assertTrue(gfile.Exists(s2))
self.assertTrue(gfile.Exists(save._MetaGraphFilename(s2)))
self.assertTrue(gfile.Exists(s1))
self.assertTrue(gfile.Exists(save._MetaGraphFilename(s1)))
# Exercise the third helper.
# Adding s2 again (but helper is unaware of previous s2)
s2 = save3.save(sess, os.path.join(save_dir, "s2"))
self.assertEqual([s2], save3.last_checkpoints)
# Created by the first helper.
self.assertTrue(gfile.Exists(s1))
self.assertTrue(gfile.Exists(save._MetaGraphFilename(s1)))
# Deleted by the first helper.
self.assertFalse(gfile.Exists(s3))
self.assertFalse(gfile.Exists(save._MetaGraphFilename(s3)))
self.assertTrue(gfile.Exists(s2))
self.assertTrue(gfile.Exists(save._MetaGraphFilename(s2)))
# Adding s1 (s3 should not be deleted because helper is unaware of it)
s1 = save3.save(sess, os.path.join(save_dir, "s1"))
self.assertEqual([s2, s1], save3.last_checkpoints)
self.assertFalse(gfile.Exists(s3))
self.assertFalse(gfile.Exists(save._MetaGraphFilename(s3)))
self.assertTrue(gfile.Exists(s2))
self.assertTrue(gfile.Exists(save._MetaGraphFilename(s2)))
self.assertTrue(gfile.Exists(s1))
self.assertTrue(gfile.Exists(save._MetaGraphFilename(s1)))
def testSharded(self):
save_dir = _TestDir("max_to_keep_sharded")
with tf.Session(
target="",
config=tf.ConfigProto(device_count={"CPU": 2})) as sess:
with sess.graph.device("/cpu:0"):
v0 = tf.Variable(111, name="v0")
with sess.graph.device("/cpu:1"):
v1 = tf.Variable(222, name="v1")
save = tf.train.Saver({"v0": v0, "v1": v1}, sharded=True, max_to_keep=2)
tf.initialize_all_variables().run()
self.assertEqual([], save.last_checkpoints)
s1 = save.save(sess, os.path.join(save_dir, "s1"))
self.assertEqual([s1], save.last_checkpoints)
self.assertEqual(2, len(gfile.Glob(s1)))
self.assertTrue(gfile.Exists(save._MetaGraphFilename(s1)))
s2 = save.save(sess, os.path.join(save_dir, "s2"))
self.assertEqual([s1, s2], save.last_checkpoints)
self.assertEqual(2, len(gfile.Glob(s1)))
self.assertTrue(gfile.Exists(save._MetaGraphFilename(s1)))
self.assertEqual(2, len(gfile.Glob(s2)))
self.assertTrue(gfile.Exists(save._MetaGraphFilename(s2)))
s3 = save.save(sess, os.path.join(save_dir, "s3"))
self.assertEqual([s2, s3], save.last_checkpoints)
self.assertEqual(0, len(gfile.Glob(s1)))
self.assertFalse(gfile.Exists(save._MetaGraphFilename(s1)))
self.assertEqual(2, len(gfile.Glob(s2)))
self.assertTrue(gfile.Exists(save._MetaGraphFilename(s2)))
self.assertEqual(2, len(gfile.Glob(s3)))
self.assertTrue(gfile.Exists(save._MetaGraphFilename(s3)))
def testNoMaxToKeep(self):
save_dir = _TestDir("no_max_to_keep")
save_dir2 = _TestDir("max_to_keep_0")
with self.test_session() as sess:
v = tf.Variable(10.0, name="v")
tf.initialize_all_variables().run()
# Test max_to_keep being None.
save = tf.train.Saver({"v": v}, max_to_keep=None)
self.assertEqual([], save.last_checkpoints)
s1 = save.save(sess, os.path.join(save_dir, "s1"))
self.assertEqual([], save.last_checkpoints)
self.assertTrue(gfile.Exists(s1))
s2 = save.save(sess, os.path.join(save_dir, "s2"))
self.assertEqual([], save.last_checkpoints)
self.assertTrue(gfile.Exists(s2))
# Test max_to_keep being 0.
save2 = tf.train.Saver({"v": v}, max_to_keep=0)
self.assertEqual([], save2.last_checkpoints)
s1 = save2.save(sess, os.path.join(save_dir2, "s1"))
self.assertEqual([], save2.last_checkpoints)
self.assertTrue(gfile.Exists(s1))
s2 = save2.save(sess, os.path.join(save_dir2, "s2"))
self.assertEqual([], save2.last_checkpoints)
self.assertTrue(gfile.Exists(s2))
def testNoMetaGrap(self):
save_dir = _TestDir("no_meta_graph")
with self.test_session() as sess:
v = tf.Variable(10.0, name="v")
save = tf.train.Saver({"v": v})
tf.initialize_all_variables().run()
s1 = save.save(sess, os.path.join(save_dir, "s1"),
write_meta_graph=False)
self.assertTrue(gfile.Exists(s1))
self.assertFalse(gfile.Exists(save._MetaGraphFilename(s1)))
class KeepCheckpointEveryNHoursTest(tf.test.TestCase):
def testNonSharded(self):
save_dir = _TestDir("keep_checkpoint_every_n_hours")
with self.test_session() as sess:
v = tf.Variable([10.0], name="v")
# Run the initializer NOW to avoid the 0.5s overhead of the first Run()
# call, which throws the test timing off in fastbuild mode.
tf.initialize_all_variables().run()
# Create a saver that will keep the last 2 checkpoints plus one every 0.7
# seconds.
start_time = time.time()
save = tf.train.Saver({"v": v}, max_to_keep=2,
keep_checkpoint_every_n_hours=0.7 / 3600)
self.assertEqual([], save.last_checkpoints)
# Wait till 0.7 second have elapsed so s1 will be old enough to keep.
time.sleep((time.time() + 0.7) - start_time)
s1 = save.save(sess, os.path.join(save_dir, "s1"))
self.assertEqual([s1], save.last_checkpoints)
s2 = save.save(sess, os.path.join(save_dir, "s2"))
self.assertEqual([s1, s2], save.last_checkpoints)
# We now have 2 'last_checkpoints': [s1, s2]. The next call to Save(),
# would normally delete s1, because max_to_keep is 2. However, s1 is
# older than 0.7s so we must keep it.
s3 = save.save(sess, os.path.join(save_dir, "s3"))
self.assertEqual([s2, s3], save.last_checkpoints)
# s1 should still be here, we are Not checking now to reduce time
# variance in the test.
# We now have 2 'last_checkpoints': [s2, s3], and s1 on disk. The next
# call to Save(), will delete s2, because max_to_keep is 2, and because
# we already kept the old s1. s2 is very close in time to s1 so it gets
# deleted.
s4 = save.save(sess, os.path.join(save_dir, "s4"))
self.assertEqual([s3, s4], save.last_checkpoints)
# Check that s1 is still here, but s2 is gone.
self.assertTrue(gfile.Exists(s1))
self.assertFalse(gfile.Exists(s2))
self.assertTrue(gfile.Exists(s3))
self.assertTrue(gfile.Exists(s4))
class SaveRestoreWithVariableNameMap(tf.test.TestCase):
def testNonReshape(self):
save_path = os.path.join(self.get_temp_dir(), "basics")
with self.test_session() as sess:
# Build a graph with 2 parameter nodes, and Save and
# Restore nodes for them.
v0 = tf.Variable(10.0, name="v0")
v1 = tf.Variable(20.0, name="v1")
save = tf.train.Saver({"save_prefix/v0": v0, "save_prefix/v1": v1})
tf.initialize_all_variables().run()
# Check that the parameter nodes have been initialized.
self.assertEqual(10.0, v0.eval())
self.assertEqual(20.0, v1.eval())
# Save the initialized values in the file at "save_path"
# Use a variable name map to set the saved tensor names
val = save.save(sess, save_path)
self.assertTrue(isinstance(val, six.string_types))
self.assertEqual(save_path, val)
# Verify that the original names are not in the Saved file
save = tf.train.Saver({"v0": v0, "v1": v1})
with self.assertRaisesOpError("not found in checkpoint"):
save.restore(sess, save_path)
# Verify that the mapped names are present in the Saved file and can be
# Restored using remapped names.
with self.test_session() as sess:
v0 = tf.Variable(-1.0, name="v0")
v1 = tf.Variable(-1.0, name="v1")
with self.assertRaisesOpError("uninitialized value v0"):
sess.run(v0)
with self.assertRaisesOpError("uninitialized value v1"):
sess.run(v1)
save = tf.train.Saver({"save_prefix/v0": v0, "save_prefix/v1": v1})
save.restore(sess, save_path)
# Check that the parameter nodes have been restored.
self.assertEqual(10.0, v0.eval())
self.assertEqual(20.0, v1.eval())
# Add a prefix to the node names in the current graph and Restore using
# remapped names.
with self.test_session() as sess:
v0 = tf.Variable(-1.0, name="restore_prefix/v0")
v1 = tf.Variable(-1.0, name="restore_prefix/v1")
with self.assertRaisesOpError("uninitialized value restore_prefix/v0"):
sess.run(v0)
with self.assertRaisesOpError("uninitialized value restore_prefix/v1"):
sess.run(v1)
# Restore the saved values in the parameter nodes.
save = tf.train.Saver({"save_prefix/v0": v0, "save_prefix/v1": v1})
save.restore(sess, save_path)
# Check that the parameter nodes have been restored.
self.assertEqual(10.0, v0.eval())
self.assertEqual(20.0, v1.eval())
class LatestCheckpointWithRelativePaths(tf.test.TestCase):
@staticmethod
@contextlib.contextmanager
def tempWorkingDir(temppath):
cwd = os.getcwd()
os.chdir(temppath)
try:
yield
finally:
os.chdir(cwd)
@staticmethod
@contextlib.contextmanager
def tempDir():
tempdir = tempfile.mkdtemp()
try:
yield tempdir
finally:
shutil.rmtree(tempdir)
def testRelativePath(self):
# Make sure we have a clean directory to work in.
with self.tempDir() as tempdir:
# Jump to that directory until this test is done.
with self.tempWorkingDir(tempdir):
# Save training snapshots to a relative path.
traindir = "train/"
os.mkdir(traindir)
filename = "snapshot"
filepath = os.path.join(traindir, filename)
with self.test_session() as sess:
# Build a simple graph.
v0 = tf.Variable(0.0)
inc = v0.assign_add(1.0)
save = tf.train.Saver({"v0": v0})
# Record a short training history.
tf.initialize_all_variables().run()
save.save(sess, filepath, global_step=0)
inc.eval()
save.save(sess, filepath, global_step=1)
inc.eval()
save.save(sess, filepath, global_step=2)
with self.test_session() as sess:
# Build a new graph with different initialization.
v0 = tf.Variable(-1.0)
# Create a new saver.
save = tf.train.Saver({"v0": v0})
tf.initialize_all_variables().run()
# Get the most recent checkpoint name from the training history file.
name = tf.train.latest_checkpoint(traindir)
self.assertIsNotNone(name)
# Restore "v0" from that checkpoint.
save.restore(sess, name)
self.assertEqual(v0.eval(), 2.0)
class CheckpointStateTest(tf.test.TestCase):
def testAbsPath(self):
save_dir = _TestDir("abs_paths")
abs_path = os.path.join(save_dir, "model-0")
ckpt = tf.train.generate_checkpoint_state_proto(save_dir, abs_path)
self.assertEqual(ckpt.model_checkpoint_path, abs_path)
self.assertTrue(os.path.isabs(ckpt.model_checkpoint_path))
self.assertEqual(len(ckpt.all_model_checkpoint_paths), 1)
self.assertEqual(ckpt.all_model_checkpoint_paths[-1], abs_path)
def testRelPath(self):
train_dir = "train"
model = os.path.join(train_dir, "model-0")
# model_checkpoint_path should have no "train" directory part.
new_rel_path = "model-0"
ckpt = tf.train.generate_checkpoint_state_proto(train_dir, model)
self.assertEqual(ckpt.model_checkpoint_path, new_rel_path)
self.assertEqual(len(ckpt.all_model_checkpoint_paths), 1)
self.assertEqual(ckpt.all_model_checkpoint_paths[-1], new_rel_path)
def testAllModelCheckpointPaths(self):
save_dir = _TestDir("all_models_test")
abs_path = os.path.join(save_dir, "model-0")
for paths in [None, [], ["model-2"]]:
ckpt = tf.train.generate_checkpoint_state_proto(
save_dir,
abs_path,
all_model_checkpoint_paths=paths)
self.assertEqual(ckpt.model_checkpoint_path, abs_path)
self.assertTrue(os.path.isabs(ckpt.model_checkpoint_path))
self.assertEqual(
len(ckpt.all_model_checkpoint_paths), len(paths) if paths else 1)
self.assertEqual(ckpt.all_model_checkpoint_paths[-1], abs_path)
def testUpdateCheckpointState(self):
save_dir = _TestDir("update_checkpoint_state")
os.chdir(save_dir)
# Make a temporary train directory.
train_dir = "train"
os.mkdir(train_dir)
abs_path = os.path.join(save_dir, "model-0")
rel_path = "train/model-2"
tf.train.update_checkpoint_state(
train_dir,
rel_path,
all_model_checkpoint_paths=[abs_path, rel_path])
ckpt = tf.train.get_checkpoint_state(train_dir)
self.assertEqual(ckpt.model_checkpoint_path, rel_path)
self.assertEqual(len(ckpt.all_model_checkpoint_paths), 2)
self.assertEqual(ckpt.all_model_checkpoint_paths[-1], rel_path)
self.assertEqual(ckpt.all_model_checkpoint_paths[0], abs_path)
class MetaGraphTest(tf.test.TestCase):
def testNoVariables(self):
test_dir = _TestDir("no_variables")
filename = os.path.join(test_dir, "metafile")
input_feed_value = -10 # Arbitrary input value for feed_dict.
orig_graph = tf.Graph()
with self.test_session(graph=orig_graph) as sess:
# Create a minimal graph with zero variables.
input_tensor = tf.placeholder(tf.float32, shape=[], name="input")
offset = tf.constant(42, dtype=tf.float32, name="offset")
output_tensor = tf.add(input_tensor, offset, name="add_offset")
# Add input and output tensors to graph collections.
tf.add_to_collection("input_tensor", input_tensor)
tf.add_to_collection("output_tensor", output_tensor)
output_value = sess.run(output_tensor, {input_tensor: input_feed_value})
self.assertEqual(output_value, 32)
# Generates MetaGraphDef.
#
# Note that this is calling the saver *module-level* export_meta_graph and
# not the Saver.export_meta_graph instance-level method.
meta_graph_def = saver_module.export_meta_graph(
filename=filename,
graph_def=tf.get_default_graph().as_graph_def(add_shapes=True),
collection_list=["input_tensor", "output_tensor"],
saver_def=None,
)
# Create a clean graph and import the MetaGraphDef nodes.
new_graph = tf.Graph()
with self.test_session(graph=new_graph) as sess:
# Import the previously export meta graph.
saver_instance = saver_module.import_meta_graph(filename)
# The saver instance should be None since there are no graph variables
# to be restored in this case.
self.assertIsNone(saver_instance)
# Re-exports the current graph state for comparison to the original.
new_meta_graph_def = saver_module.export_meta_graph(filename + "_new")
self.assertProtoEquals(meta_graph_def, new_meta_graph_def)
# Ensures that we can still get a reference to our graph collections.
new_input_tensor = tf.get_collection("input_tensor")[0]
new_output_tensor = tf.get_collection("output_tensor")[0]
# Verifies that the new graph computes the same result as the original.
new_output_value = sess.run(
new_output_tensor, {new_input_tensor: input_feed_value})
self.assertEqual(new_output_value, output_value)
def testAddCollectionDef(self):
test_dir = _TestDir("good_collection")
filename = os.path.join(test_dir, "metafile")
with self.test_session():
# Creates a graph.
v0 = tf.Variable(10.0, name="v0")
var = tf.Variable(tf.constant(0, dtype=tf.int64))
count_up_to = var.count_up_to(3)
input_queue = tf.FIFOQueue(30, tf.float32, shared_name="collection_queue")
qr = tf.train.QueueRunner(input_queue, [count_up_to])
tf.initialize_all_variables()
# Creates a saver.
save = tf.train.Saver({"v0": v0})
# Adds a set of collections.
tf.add_to_collection("int_collection", 3)
tf.add_to_collection("float_collection", 3.5)
tf.add_to_collection("string_collection", "hello")
tf.add_to_collection("variable_collection", v0)
# Add QueueRunners.
tf.train.add_queue_runner(qr)
# Adds user_defined proto in three formats: string, bytes and Any.
queue_runner = queue_runner_pb2.QueueRunnerDef(queue_name="test_queue")
tf.add_to_collection("user_defined_string_collection", str(queue_runner))
tf.add_to_collection("user_defined_bytes_collection",
queue_runner.SerializeToString())
any_buf = Any()
any_buf.Pack(queue_runner)
tf.add_to_collection("user_defined_any_collection", any_buf)
# Generates MetaGraphDef.
meta_graph_def = save.export_meta_graph(filename)
self.assertTrue(meta_graph_def.HasField("saver_def"))
self.assertTrue(meta_graph_def.HasField("graph_def"))
collection_def = meta_graph_def.collection_def
self.assertEqual(len(collection_def), 10)
with tf.Graph().as_default():
# Restores from MetaGraphDef.
new_saver = tf.train.import_meta_graph(filename)
# Generates a new MetaGraphDef.
new_meta_graph_def = new_saver.export_meta_graph()
# It should be the same as the original.
self.assertProtoEquals(meta_graph_def, new_meta_graph_def)
def testAddCollectionDefFails(self):
with self.test_session():
# Creates a graph.
v0 = tf.Variable(10.0, name="v0")
# Creates a saver.
save = tf.train.Saver({"v0": v0})
# Generates MetaGraphDef.
meta_graph_def = meta_graph_pb2.MetaGraphDef()
# Verifies that collection with unsupported key will not be added.
tf.add_to_collection(save, 3)
save._add_collection_def(meta_graph_def, save)
self.assertEqual(len(meta_graph_def.collection_def), 0)
# Verifies that collection where item type does not match expected
# type will not be added.
tf.add_to_collection("int_collection", 3)
tf.add_to_collection("int_collection", 3.5)
save._add_collection_def(meta_graph_def, "int_collection")
self.assertEqual(len(meta_graph_def.collection_def), 0)
def _testMultiSaverCollectionSave(self):
test_dir = _TestDir("saver_collection")
filename = os.path.join(test_dir, "metafile")
saver0_ckpt = os.path.join(test_dir, "saver0.ckpt")
saver1_ckpt = os.path.join(test_dir, "saver1.ckpt")
with self.test_session(graph=tf.Graph()) as sess:
# Creates a graph.
v0 = tf.Variable([[1.0, 2.0],
[3.0, 4.0],
[5.0, 6.0]], name="v0")
v1 = tf.Variable(11.0, name="v1")
# Creates 2 savers.
saver0 = tf.train.Saver({"v0": v0}, name="saver0")
saver1 = tf.train.Saver({"v1": v1}, name="saver1")
tf.add_to_collection("savers", saver0)
tf.add_to_collection("savers", saver1)
tf.initialize_all_variables().run()
# Saves to different checkpoints.
saver0.save(sess, saver0_ckpt)
saver1.save(sess, saver1_ckpt)
# Generates MetaGraphDef.
meta_graph_def = tf.train.export_meta_graph(filename)
meta_graph_def0 = saver0.export_meta_graph()
meta_graph_def1 = saver1.export_meta_graph()
# Verifies that there is no saver_def in meta_graph_def.
self.assertFalse(meta_graph_def.HasField("saver_def"))
# Verifies that there is saver_def in meta_graph_def0 and 1.
self.assertTrue(meta_graph_def0.HasField("saver_def"))
self.assertTrue(meta_graph_def1.HasField("saver_def"))
# Verifies SAVERS is saved as bytes_list for meta_graph_def.
collection_def = meta_graph_def.collection_def["savers"]
kind = collection_def.WhichOneof("kind")
self.assertEqual(kind, "bytes_list")
# Verifies that there are 2 entries in SAVERS collection.
savers = getattr(collection_def, kind)
self.assertEqual(2, len(savers.value))
# Verifies SAVERS collection is saved as bytes_list for meta_graph_def0.
collection_def = meta_graph_def0.collection_def["savers"]
kind = collection_def.WhichOneof("kind")
self.assertEqual(kind, "bytes_list")
# Verifies that there are 3 entries in SAVERS collection.
savers = getattr(collection_def, kind)
self.assertEqual(2, len(savers.value))
def _testMultiSaverCollectionRestore(self):
test_dir = os.path.join(self.get_temp_dir(), "saver_collection")
filename = os.path.join(test_dir, "metafile")
saver0_ckpt = os.path.join(test_dir, "saver0.ckpt")
saver1_ckpt = os.path.join(test_dir, "saver1.ckpt")
with self.test_session(graph=tf.Graph()) as sess:
# Imports from meta_graph.
tf.train.import_meta_graph(filename)
# Retrieves SAVERS collection. Verifies there are 2 entries.
savers = tf.get_collection("savers")
self.assertEqual(2, len(savers))
# Retrieves saver0. Verifies that new_saver0 can restore v0, but not v1.
new_saver0 = savers[0]
new_saver0.restore(sess, saver0_ckpt)
v0 = sess.graph.get_tensor_by_name("v0:0")
v1 = sess.graph.get_tensor_by_name("v1:0")
self.assertAllEqual([[1.0, 2.0],
[3.0, 4.0],
[5.0, 6.0]], v0.eval())
self.assertEqual([3, 2], v0.get_shape())
self.assertEqual([], v1.get_shape())
with self.assertRaisesWithPredicateMatch(
tf.OpError, lambda e: "uninitialized value v1" in e.message):
sess.run(v1)
# Retrieves saver1. Verifies that new_saver1 can restore v1.
new_saver1 = savers[1]
new_saver1.restore(sess, saver1_ckpt)
v1 = sess.graph.get_tensor_by_name("v1:0")
self.assertEqual(11.0, v1.eval())
def testMultiSaverCollection(self):
self._testMultiSaverCollectionSave()
self._testMultiSaverCollectionRestore()
def testBinaryAndTextFormat(self):
test_dir = _TestDir("binary_and_text")
filename = os.path.join(test_dir, "metafile")
with self.test_session(graph=tf.Graph()):
# Creates a graph.
tf.Variable(10.0, name="v0")
# Exports the graph as binary format.
tf.train.export_meta_graph(filename, as_text=False)
with self.test_session(graph=tf.Graph()):
# Imports the binary format graph.
saver = tf.train.import_meta_graph(filename)
self.assertIsNotNone(saver)
# Exports the graph as text format.
saver.export_meta_graph(filename, as_text=True)
with self.test_session(graph=tf.Graph()):
# Imports the text format graph.
tf.train.import_meta_graph(filename)
# Writes wrong contents to the file.
tf.train.write_graph(saver.as_saver_def(), os.path.dirname(filename),
os.path.basename(filename))
with self.test_session(graph=tf.Graph()):
# Import should fail.
with self.assertRaisesWithPredicateMatch(
IOError, lambda e: "Cannot parse file"):
tf.train.import_meta_graph(filename)
# Deletes the file
gfile.Remove(filename)
with self.assertRaisesWithPredicateMatch(
IOError, lambda e: "does not exist"):
tf.train.import_meta_graph(filename)
def testSliceVariable(self):
test_dir = _TestDir("slice_saver")
filename = os.path.join(test_dir, "metafile")
with self.test_session():
v1 = tf.Variable([20.0], name="v1")
v2 = tf.Variable([20.0], name="v2")
v2._set_save_slice_info(tf.Variable.SaveSliceInfo("v1", [1], [0], [1]))
# The names are different and will work.
slice_saver = tf.train.Saver({"first": v1, "second": v2})
tf.initialize_all_variables().run()
# Exports to meta_graph
meta_graph_def = slice_saver.export_meta_graph(filename)
with tf.Graph().as_default():
# Restores from MetaGraphDef.
new_saver = tf.train.import_meta_graph(filename)
self.assertIsNotNone(new_saver)
# Generates a new MetaGraphDef.
new_meta_graph_def = new_saver.export_meta_graph()
# It should be the same as the original.
self.assertProtoEquals(meta_graph_def, new_meta_graph_def)
def _testGraphExtensionSave(self):
test_dir = _TestDir("graph_extension")
filename = os.path.join(test_dir, "metafile")
saver0_ckpt = os.path.join(test_dir, "saver0.ckpt")
# Creates an inference graph.
# Hidden 1
images = tf.constant(1.2, tf.float32, shape=[100, 28])
with tf.name_scope("hidden1"):
weights = tf.Variable(
tf.truncated_normal([28, 128],
stddev=1.0 / math.sqrt(float(28))),
name="weights")
biases = tf.Variable(tf.zeros([128]),
name="biases")
hidden1 = tf.nn.relu(tf.matmul(images, weights) + biases)
# Hidden 2
with tf.name_scope("hidden2"):
weights = tf.Variable(
tf.truncated_normal([128, 32],
stddev=1.0 / math.sqrt(float(128))),
name="weights")
biases = tf.Variable(tf.zeros([32]),
name="biases")
hidden2 = tf.nn.relu(tf.matmul(hidden1, weights) + biases)
# Linear
with tf.name_scope("softmax_linear"):
weights = tf.Variable(
tf.truncated_normal([32, 10],
stddev=1.0 / math.sqrt(float(32))),
name="weights")
biases = tf.Variable(tf.zeros([10]),
name="biases")
logits = tf.matmul(hidden2, weights) + biases
tf.add_to_collection("logits", logits)
init_all_op = tf.initialize_all_variables()
with self.test_session() as sess:
# Initializes all the variables.
sess.run(init_all_op)
# Runs to logit.
sess.run(logits)
# Creates a saver.
saver0 = tf.train.Saver()
saver0.save(sess, saver0_ckpt)
# Generates MetaGraphDef.
saver0.export_meta_graph(filename)
def _testGraphExtensionRestore(self):
test_dir = os.path.join(self.get_temp_dir(), "graph_extension")
filename = os.path.join(test_dir, "metafile")
saver0_ckpt = os.path.join(test_dir, "saver0.ckpt")
with self.test_session(graph=tf.Graph()) as sess:
# Restores from MetaGraphDef.
new_saver = tf.train.import_meta_graph(filename)
# Generates a new MetaGraphDef.
new_saver.export_meta_graph()
# Restores from checkpoint.
new_saver.restore(sess, saver0_ckpt)
# Addes loss and train.
labels = tf.constant(0, tf.int32, shape=[100], name="labels")
batch_size = tf.size(labels)
labels = tf.expand_dims(labels, 1)
indices = tf.expand_dims(tf.range(0, batch_size), 1)
concated = tf.concat(1, [indices, labels])
onehot_labels = tf.sparse_to_dense(
concated, tf.pack([batch_size, 10]), 1.0, 0.0)
logits = tf.get_collection("logits")[0]
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits,
onehot_labels,
name="xentropy")
loss = tf.reduce_mean(cross_entropy, name="xentropy_mean")
tf.scalar_summary(loss.op.name, loss)
# Creates the gradient descent optimizer with the given learning rate.
optimizer = tf.train.GradientDescentOptimizer(0.01)
# Runs train_op.
train_op = optimizer.minimize(loss)
sess.run(train_op)
def testGraphExtension(self):
self._testGraphExtensionSave()
self._testGraphExtensionRestore()
def testStrippedOpListDef(self):
with self.test_session():
# Creates a graph.
v0 = tf.Variable(0.0)
var = tf.Variable(10.0)
tf.add(v0, var)
@function.Defun(x=tf.float32)
def minus_one(x):
return x - 1
minus_one(tf.identity(v0))
save = tf.train.Saver({"v0": v0})
tf.initialize_all_variables()
# Generates MetaGraphDef.
meta_graph_def = save.export_meta_graph()
ops = [o.name for o in meta_graph_def.meta_info_def.stripped_op_list.op]
self.assertEqual(ops, ["Add", "Assign", "Const", "Identity", "NoOp",
"RestoreSlice", "SaveSlices", "Sub", "Variable"])
# Test calling stripped_op_list_for_graph directly
op_list = tf.contrib.util.stripped_op_list_for_graph(
meta_graph_def.graph_def)
self.assertEqual(ops, [o.name for o in op_list.op])
for o in op_list.op:
self.assertEqual(o.summary, "")
self.assertEqual(o.description, "")
def testStrippedOpListNestedFunctions(self):
with self.test_session():
# Square two levels deep
def f0(x):
return tf.square(x)
f0 = function.define_function(f0, {"x": tf.int32})
def f1(x):
return function.call_function(f0, x)
f1 = function.define_function(f1, {"x": tf.int32})
# At this point we've defined two functions but haven't called them, so
# there should be no used ops.
op_list = tf.contrib.util.stripped_op_list_for_graph(
tf.get_default_graph().as_graph_def())
self.assertEquals(len(op_list.op), 0)
# If we call the function on a constant, there should be two ops
function.call_function(f1, tf.constant(7))
op_list = tf.contrib.util.stripped_op_list_for_graph(
tf.get_default_graph().as_graph_def())
self.assertEquals(["Const", "Square"], [op.name for op in op_list.op])
def testStrippedOpListRecursiveFunctions(self):
# The function module doesn't support recursive functions, so we build a
# recursive function situation by ourselves: A calls B calls A and Const.
graph = graph_pb2.GraphDef()
a = graph.library.function.add()
b = graph.library.function.add()
a.signature.name = "A"
b.signature.name = "B"
a.node.add().op = "B"
b.node.add().op = "Const"
b.node.add().op = "A"
# Use A in the graph
graph.node.add().op = "A"
# The stripped op list should contain just Const.
op_list = tf.contrib.util.stripped_op_list_for_graph(graph)
self.assertEquals(["Const"], [op.name for op in op_list.op])
class CheckpointReaderTest(tf.test.TestCase):
def testDebugString(self):
# Builds a graph.
v0 = tf.Variable([[1, 2, 3], [4, 5, 6]], dtype=tf.float32, name="v0")
v1 = tf.Variable([[[1], [2]], [[3], [4]], [[5], [6]]], dtype=tf.float32,
name="v1")
init_all_op = tf.initialize_all_variables()
save = tf.train.Saver({"v0": v0, "v1": v1})
save_path = os.path.join(self.get_temp_dir(), "ckpt_for_debug_string")
with self.test_session() as sess:
sess.run(init_all_op)
# Saves a checkpoint.
save.save(sess, save_path)
# Creates a reader.
reader = tf.train.NewCheckpointReader(save_path)
# Verifies that the tensors exist.
self.assertTrue(reader.has_tensor("v0"))
self.assertTrue(reader.has_tensor("v1"))
debug_string = reader.debug_string()
# Verifies that debug string contains the right strings.
self.assertTrue(compat.as_bytes("v0 (DT_FLOAT) [2,3]") in debug_string)
self.assertTrue(compat.as_bytes("v1 (DT_FLOAT) [3,2,1]") in debug_string)
# Verifies get_variable_to_shape_map() returns the correct information.
var_map = reader.get_variable_to_shape_map()
self.assertEquals([2, 3], var_map["v0"])
self.assertEquals([3, 2, 1], var_map["v1"])
# Verifies get_tensor() returns the tensor value.
v0_tensor = reader.get_tensor("v0")
v1_tensor = reader.get_tensor("v1")
self.assertAllEqual(v0.eval(), v0_tensor)
self.assertAllEqual(v1.eval(), v1_tensor)
# Verifies get_tensor() fails for non-existent tensors.
with self.assertRaisesRegexp(errors.NotFoundError,
"v3 not found in checkpoint file"):
reader.get_tensor("v3")
def testNonexistentPath(self):
with self.assertRaisesRegexp(errors.NotFoundError,
"Unsuccessful TensorSliceReader"):
tf.train.NewCheckpointReader("non-existent")
class WriteGraphTest(tf.test.TestCase):
def testRecursiveCreate(self):
test_dir = _TestDir("deep_dir")
tf.Variable([[1, 2, 3], [4, 5, 6]], dtype=tf.float32, name="v0")
tf.train.write_graph(tf.get_default_graph().as_graph_def(),
"/".join([test_dir, "l1/l2/l3"]), "graph.pbtxt")
if __name__ == "__main__":
tf.test.main()
| apache-2.0 |
sestrella/ansible | lib/ansible/modules/network/cloudengine/ce_ip_interface.py | 5 | 24258 | #!/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': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: ce_ip_interface
version_added: "2.4"
short_description: Manages L3 attributes for IPv4 and IPv6 interfaces on HUAWEI CloudEngine switches.
description:
- Manages Layer 3 attributes for IPv4 and IPv6 interfaces on HUAWEI CloudEngine switches.
author: QijunPan (@QijunPan)
notes:
- Interface must already be a L3 port when using this module.
- Logical interfaces (loopback, vlanif) must be created first.
- C(mask) must be inserted in decimal format (i.e. 24) for
both IPv6 and IPv4.
- A single interface can have multiple IPv6 configured.
- This module requires the netconf system service be enabled on the remote device being managed.
- Recommended connection is C(netconf).
- This module also works with C(local) connections for legacy playbooks.
options:
interface:
description:
- Full name of interface, i.e. 40GE1/0/22, vlanif10.
required: true
addr:
description:
- IPv4 or IPv6 Address.
mask:
description:
- Subnet mask for IPv4 or IPv6 Address in decimal format.
version:
description:
- IP address version.
default: v4
choices: ['v4','v6']
ipv4_type:
description:
- Specifies an address type.
The value is an enumerated type.
main, primary IP address.
sub, secondary IP address.
default: main
choices: ['main','sub']
state:
description:
- Specify desired state of the resource.
default: present
choices: ['present','absent']
'''
EXAMPLES = '''
- name: ip_interface module test
hosts: cloudengine
connection: local
gather_facts: no
vars:
cli:
host: "{{ inventory_hostname }}"
port: "{{ ansible_ssh_port }}"
username: "{{ username }}"
password: "{{ password }}"
transport: cli
tasks:
- name: Ensure ipv4 address is configured on 10GE1/0/22
ce_ip_interface:
interface: 10GE1/0/22
version: v4
state: present
addr: 20.20.20.20
mask: 24
provider: '{{ cli }}'
- name: Ensure ipv4 secondary address is configured on 10GE1/0/22
ce_ip_interface:
interface: 10GE1/0/22
version: v4
state: present
addr: 30.30.30.30
mask: 24
ipv4_type: sub
provider: '{{ cli }}'
- name: Ensure ipv6 is enabled on 10GE1/0/22
ce_ip_interface:
interface: 10GE1/0/22
version: v6
state: present
provider: '{{ cli }}'
- name: Ensure ipv6 address is configured on 10GE1/0/22
ce_ip_interface:
interface: 10GE1/0/22
version: v6
state: present
addr: 2001::db8:800:200c:cccb
mask: 64
provider: '{{ cli }}'
'''
RETURN = '''
proposed:
description: k/v pairs of parameters passed into module
returned: always
type: dict
sample: {"addr": "20.20.20.20", "interface": "10GE1/0/22", "mask": "24"}
existing:
description: k/v pairs of existing IP attributes on the interface
returned: always
type: dict
sample: {"ipv4": [{"ifIpAddr": "11.11.11.11", "subnetMask": "255.255.0.0", "addrType": "main"}],
"interface": "10GE1/0/22"}
end_state:
description: k/v pairs of IP attributes after module execution
returned: always
type: dict
sample: {"ipv4": [{"ifIpAddr": "20.20.20.20", "subnetMask": "255.255.255.0", "addrType": "main"}],
"interface": "10GE1/0/22"}
updates:
description: commands sent to the device
returned: always
type: list
sample: ["interface 10GE1/0/22", "ip address 20.20.20.20 24"]
changed:
description: check to see if a change was made on the device
returned: always
type: bool
sample: true
'''
import re
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.network.cloudengine.ce import get_nc_config, set_nc_config, ce_argument_spec
CE_NC_GET_INTF = """
<filter type="subtree">
<ifm xmlns="http://www.huawei.com/netconf/vrp" content-version="1.0" format-version="1.0">
<interfaces>
<interface>
<ifName>%s</ifName>
<isL2SwitchPort></isL2SwitchPort>
<ifmAm4>
</ifmAm4>
<ifmAm6>
</ifmAm6>
</interface>
</interfaces>
</ifm>
</filter>
"""
CE_NC_ADD_IPV4 = """
<config>
<ifm xmlns="http://www.huawei.com/netconf/vrp" content-version="1.0" format-version="1.0">
<interfaces>
<interface>
<ifName>%s</ifName>
<ifmAm4>
<am4CfgAddrs>
<am4CfgAddr operation="merge">
<ifIpAddr>%s</ifIpAddr>
<subnetMask>%s</subnetMask>
<addrType>%s</addrType>
</am4CfgAddr>
</am4CfgAddrs>
</ifmAm4>
</interface>
</interfaces>
</ifm>
</config>
"""
CE_NC_MERGE_IPV4 = """
<config>
<ifm xmlns="http://www.huawei.com/netconf/vrp" content-version="1.0" format-version="1.0">
<interfaces>
<interface>
<ifName>%s</ifName>
<ifmAm4>
<am4CfgAddrs>
<am4CfgAddr operation="delete">
<ifIpAddr>%s</ifIpAddr>
<subnetMask>%s</subnetMask>
<addrType>main</addrType>
</am4CfgAddr>
<am4CfgAddr operation="merge">
<ifIpAddr>%s</ifIpAddr>
<subnetMask>%s</subnetMask>
<addrType>main</addrType>
</am4CfgAddr>
</am4CfgAddrs>
</ifmAm4>
</interface>
</interfaces>
</ifm>
</config>
"""
CE_NC_DEL_IPV4 = """
<config>
<ifm xmlns="http://www.huawei.com/netconf/vrp" content-version="1.0" format-version="1.0">
<interfaces>
<interface>
<ifName>%s</ifName>
<ifmAm4>
<am4CfgAddrs>
<am4CfgAddr operation="delete">
<ifIpAddr>%s</ifIpAddr>
<subnetMask>%s</subnetMask>
<addrType>%s</addrType>
</am4CfgAddr>
</am4CfgAddrs>
</ifmAm4>
</interface>
</interfaces>
</ifm>
</config>
"""
CE_NC_ADD_IPV6 = """
<config>
<ifm xmlns="http://www.huawei.com/netconf/vrp" content-version="1.0" format-version="1.0">
<interfaces>
<interface>
<ifName>%s</ifName>
<ifmAm6>
<am6CfgAddrs>
<am6CfgAddr operation="merge">
<ifIp6Addr>%s</ifIp6Addr>
<addrPrefixLen>%s</addrPrefixLen>
<addrType6>global</addrType6>
</am6CfgAddr>
</am6CfgAddrs>
</ifmAm6>
</interface>
</interfaces>
</ifm>
</config>
"""
CE_NC_DEL_IPV6 = """
<config>
<ifm xmlns="http://www.huawei.com/netconf/vrp" content-version="1.0" format-version="1.0">
<interfaces>
<interface>
<ifName>%s</ifName>
<ifmAm6>
<am6CfgAddrs>
<am6CfgAddr operation="delete">
<ifIp6Addr>%s</ifIp6Addr>
<addrPrefixLen>%s</addrPrefixLen>
<addrType6>global</addrType6>
</am6CfgAddr>
</am6CfgAddrs>
</ifmAm6>
</interface>
</interfaces>
</ifm>
</config>
"""
CE_NC_MERGE_IPV6_ENABLE = """
<config>
<ifm xmlns="http://www.huawei.com/netconf/vrp" content-version="1.0" format-version="1.0">
<interfaces>
<interface>
<ifName>%s</ifName>
<ifmAm6 operation="merge">
<enableFlag>%s</enableFlag>
</ifmAm6>
</interface>
</interfaces>
</ifm>
</config>
"""
def get_interface_type(interface):
"""Gets the type of interface, such as 10GE, ETH-TRUNK, VLANIF..."""
if interface is None:
return None
iftype = None
if interface.upper().startswith('GE'):
iftype = 'ge'
elif interface.upper().startswith('10GE'):
iftype = '10ge'
elif interface.upper().startswith('25GE'):
iftype = '25ge'
elif interface.upper().startswith('4X10GE'):
iftype = '4x10ge'
elif interface.upper().startswith('40GE'):
iftype = '40ge'
elif interface.upper().startswith('100GE'):
iftype = '100ge'
elif interface.upper().startswith('VLANIF'):
iftype = 'vlanif'
elif interface.upper().startswith('LOOPBACK'):
iftype = 'loopback'
elif interface.upper().startswith('METH'):
iftype = 'meth'
elif interface.upper().startswith('ETH-TRUNK'):
iftype = 'eth-trunk'
elif interface.upper().startswith('VBDIF'):
iftype = 'vbdif'
elif interface.upper().startswith('NVE'):
iftype = 'nve'
elif interface.upper().startswith('TUNNEL'):
iftype = 'tunnel'
elif interface.upper().startswith('ETHERNET'):
iftype = 'ethernet'
elif interface.upper().startswith('FCOE-PORT'):
iftype = 'fcoe-port'
elif interface.upper().startswith('FABRIC-PORT'):
iftype = 'fabric-port'
elif interface.upper().startswith('STACK-PORT'):
iftype = 'stack-port'
elif interface.upper().startswith('NULL'):
iftype = 'null'
else:
return None
return iftype.lower()
def is_valid_v4addr(addr):
"""check is ipv4 addr is valid"""
if not addr:
return False
if addr.find('.') != -1:
addr_list = addr.split('.')
if len(addr_list) != 4:
return False
for each_num in addr_list:
if not each_num.isdigit():
return False
if int(each_num) > 255:
return False
return True
return False
class IpInterface(object):
"""
Manages L3 attributes for IPv4 and IPv6 interfaces.
"""
def __init__(self, argument_spec):
self.spec = argument_spec
self.module = None
self.__init_module__()
# module input info]
self.interface = self.module.params['interface']
self.addr = self.module.params['addr']
self.mask = self.module.params['mask']
self.version = self.module.params['version']
self.ipv4_type = self.module.params['ipv4_type']
self.state = self.module.params['state']
# state
self.changed = False
self.updates_cmd = list()
self.results = dict()
self.proposed = dict()
self.existing = dict()
self.end_state = dict()
# interface info
self.intf_info = dict()
self.intf_type = None
def __init_module__(self):
""" init module """
required_if = [("version", "v4", ("addr", "mask"))]
required_together = [("addr", "mask")]
self.module = AnsibleModule(
argument_spec=self.spec,
required_if=required_if,
required_together=required_together,
supports_check_mode=True
)
def netconf_set_config(self, xml_str, xml_name):
""" netconf set config """
rcv_xml = set_nc_config(self.module, xml_str)
if "<ok/>" not in rcv_xml:
self.module.fail_json(msg='Error: %s failed.' % xml_name)
def get_interface_dict(self, ifname):
""" get one interface attributes dict."""
intf_info = dict()
conf_str = CE_NC_GET_INTF % ifname
rcv_xml = get_nc_config(self.module, conf_str)
if "<data/>" in rcv_xml:
return intf_info
# get interface base info
intf = re.findall(
r'.*<ifName>(.*)</ifName>.*\s*'
r'<isL2SwitchPort>(.*)</isL2SwitchPort>.*', rcv_xml)
if intf:
intf_info = dict(ifName=intf[0][0],
isL2SwitchPort=intf[0][1])
# get interface ipv4 address info
ipv4_info = re.findall(
r'.*<ifIpAddr>(.*)</ifIpAddr>.*\s*<subnetMask>(.*)'
r'</subnetMask>.*\s*<addrType>(.*)</addrType>.*', rcv_xml)
intf_info["am4CfgAddr"] = list()
for info in ipv4_info:
intf_info["am4CfgAddr"].append(
dict(ifIpAddr=info[0], subnetMask=info[1], addrType=info[2]))
# get interface ipv6 address info
ipv6_info = re.findall(
r'.*<ifmAm6>.*\s*<enableFlag>(.*)</enableFlag>.*', rcv_xml)
if not ipv6_info:
self.module.fail_json(msg='Error: Fail to get interface %s IPv6 state.' % self.interface)
else:
intf_info["enableFlag"] = ipv6_info[0]
# get interface ipv6 enable info
ipv6_info = re.findall(
r'.*<ifIp6Addr>(.*)</ifIp6Addr>.*\s*<addrPrefixLen>(.*)'
r'</addrPrefixLen>.*\s*<addrType6>(.*)</addrType6>.*', rcv_xml)
intf_info["am6CfgAddr"] = list()
for info in ipv6_info:
intf_info["am6CfgAddr"].append(
dict(ifIp6Addr=info[0], addrPrefixLen=info[1], addrType6=info[2]))
return intf_info
def convert_len_to_mask(self, masklen):
"""convert mask length to ip address mask, i.e. 24 to 255.255.255.0"""
mask_int = ["0"] * 4
length = int(masklen)
if length > 32:
self.module.fail_json(msg='Error: IPv4 ipaddress mask length is invalid.')
if length < 8:
mask_int[0] = str(int((0xFF << (8 - length % 8)) & 0xFF))
if length >= 8:
mask_int[0] = '255'
mask_int[1] = str(int((0xFF << (16 - (length % 16))) & 0xFF))
if length >= 16:
mask_int[1] = '255'
mask_int[2] = str(int((0xFF << (24 - (length % 24))) & 0xFF))
if length >= 24:
mask_int[2] = '255'
mask_int[3] = str(int((0xFF << (32 - (length % 32))) & 0xFF))
if length == 32:
mask_int[3] = '255'
return '.'.join(mask_int)
def is_ipv4_exist(self, addr, maskstr, ipv4_type):
""""Check IPv4 address exist"""
addrs = self.intf_info["am4CfgAddr"]
if not addrs:
return False
for address in addrs:
if address["ifIpAddr"] == addr:
return address["subnetMask"] == maskstr and address["addrType"] == ipv4_type
return False
def get_ipv4_main_addr(self):
"""get IPv4 main address"""
addrs = self.intf_info["am4CfgAddr"]
if not addrs:
return None
for address in addrs:
if address["addrType"] == "main":
return address
return None
def is_ipv6_exist(self, addr, masklen):
"""Check IPv6 address exist"""
addrs = self.intf_info["am6CfgAddr"]
if not addrs:
return False
for address in addrs:
if address["ifIp6Addr"] == addr.upper():
if address["addrPrefixLen"] == masklen and address["addrType6"] == "global":
return True
else:
self.module.fail_json(
msg="Error: Input IPv6 address or mask is invalid.")
return False
def set_ipv4_addr(self, ifname, addr, mask, ipv4_type):
"""Set interface IPv4 address"""
if not addr or not mask or not type:
return
maskstr = self.convert_len_to_mask(mask)
if self.state == "present":
if not self.is_ipv4_exist(addr, maskstr, ipv4_type):
# primary IP address
if ipv4_type == "main":
main_addr = self.get_ipv4_main_addr()
if not main_addr:
# no ipv4 main address in this interface
xml_str = CE_NC_ADD_IPV4 % (ifname, addr, maskstr, ipv4_type)
self.netconf_set_config(xml_str, "ADD_IPV4_ADDR")
else:
# remove old address and set new
xml_str = CE_NC_MERGE_IPV4 % (ifname, main_addr["ifIpAddr"],
main_addr["subnetMask"],
addr, maskstr)
self.netconf_set_config(xml_str, "MERGE_IPV4_ADDR")
# secondary IP address
else:
xml_str = CE_NC_ADD_IPV4 % (ifname, addr, maskstr, ipv4_type)
self.netconf_set_config(xml_str, "ADD_IPV4_ADDR")
self.updates_cmd.append("interface %s" % ifname)
if ipv4_type == "main":
self.updates_cmd.append("ip address %s %s" % (addr, maskstr))
else:
self.updates_cmd.append("ip address %s %s sub" % (addr, maskstr))
self.changed = True
else:
if self.is_ipv4_exist(addr, maskstr, ipv4_type):
xml_str = CE_NC_DEL_IPV4 % (ifname, addr, maskstr, ipv4_type)
self.netconf_set_config(xml_str, "DEL_IPV4_ADDR")
self.updates_cmd.append("interface %s" % ifname)
if ipv4_type == "main":
self.updates_cmd.append("undo ip address %s %s" % (addr, maskstr))
else:
self.updates_cmd.append("undo ip address %s %s sub" % (addr, maskstr))
self.changed = True
def set_ipv6_addr(self, ifname, addr, mask):
"""Set interface IPv6 address"""
if not addr or not mask:
return
if self.state == "present":
self.updates_cmd.append("interface %s" % ifname)
if self.intf_info["enableFlag"] == "false":
xml_str = CE_NC_MERGE_IPV6_ENABLE % (ifname, "true")
self.netconf_set_config(xml_str, "SET_IPV6_ENABLE")
self.updates_cmd.append("ipv6 enable")
self.changed = True
if not self.is_ipv6_exist(addr, mask):
xml_str = CE_NC_ADD_IPV6 % (ifname, addr, mask)
self.netconf_set_config(xml_str, "ADD_IPV6_ADDR")
self.updates_cmd.append("ipv6 address %s %s" % (addr, mask))
self.changed = True
if not self.changed:
self.updates_cmd.pop()
else:
if self.is_ipv6_exist(addr, mask):
xml_str = CE_NC_DEL_IPV6 % (ifname, addr, mask)
self.netconf_set_config(xml_str, "DEL_IPV6_ADDR")
self.updates_cmd.append("interface %s" % ifname)
self.updates_cmd.append(
"undo ipv6 address %s %s" % (addr, mask))
self.changed = True
def set_ipv6_enable(self, ifname):
"""Set interface IPv6 enable"""
if self.state == "present":
if self.intf_info["enableFlag"] == "false":
xml_str = CE_NC_MERGE_IPV6_ENABLE % (ifname, "true")
self.netconf_set_config(xml_str, "SET_IPV6_ENABLE")
self.updates_cmd.append("interface %s" % ifname)
self.updates_cmd.append("ipv6 enable")
self.changed = True
else:
if self.intf_info["enableFlag"] == "true":
xml_str = CE_NC_MERGE_IPV6_ENABLE % (ifname, "false")
self.netconf_set_config(xml_str, "SET_IPV6_DISABLE")
self.updates_cmd.append("interface %s" % ifname)
self.updates_cmd.append("undo ipv6 enable")
self.changed = True
def check_params(self):
"""Check all input params"""
# check interface type
if self.interface:
self.intf_type = get_interface_type(self.interface)
if not self.intf_type:
self.module.fail_json(
msg='Error: Interface name of %s '
'is error.' % self.interface)
# ipv4 addr and mask check
if self.version == "v4":
if not is_valid_v4addr(self.addr):
self.module.fail_json(
msg='Error: The %s is not a valid address.' % self.addr)
if not self.mask.isdigit():
self.module.fail_json(msg='Error: mask is invalid.')
if int(self.mask) > 32 or int(self.mask) < 1:
self.module.fail_json(
msg='Error: mask must be an integer between 1 and 32.')
# ipv6 mask check
if self.version == "v6":
if self.addr:
if not self.mask.isdigit():
self.module.fail_json(msg='Error: mask is invalid.')
if int(self.mask) > 128 or int(self.mask) < 1:
self.module.fail_json(
msg='Error: mask must be an integer between 1 and 128.')
# interface and layer3 check
self.intf_info = self.get_interface_dict(self.interface)
if not self.intf_info:
self.module.fail_json(msg='Error: interface %s does not exist.' % self.interface)
if self.intf_info["isL2SwitchPort"] == "true":
self.module.fail_json(msg='Error: interface %s is layer2.' % self.interface)
def get_proposed(self):
"""get proposed info"""
self.proposed["state"] = self.state
self.proposed["addr"] = self.addr
self.proposed["mask"] = self.mask
self.proposed["ipv4_type"] = self.ipv4_type
self.proposed["version"] = self.version
self.proposed["interface"] = self.interface
def get_existing(self):
"""get existing info"""
self.existing["interface"] = self.interface
self.existing["ipv4addr"] = self.intf_info["am4CfgAddr"]
self.existing["ipv6addr"] = self.intf_info["am6CfgAddr"]
self.existing["ipv6enalbe"] = self.intf_info["enableFlag"]
def get_end_state(self):
"""get end state info"""
intf_info = self.get_interface_dict(self.interface)
self.end_state["interface"] = self.interface
self.end_state["ipv4addr"] = intf_info["am4CfgAddr"]
self.end_state["ipv6addr"] = intf_info["am6CfgAddr"]
self.end_state["ipv6enalbe"] = intf_info["enableFlag"]
def work(self):
"""worker"""
self.check_params()
self.get_existing()
self.get_proposed()
# deal present or absent
if self.version == "v4":
self.set_ipv4_addr(self.interface, self.addr, self.mask, self.ipv4_type)
else:
if not self.addr and not self.mask:
self.set_ipv6_enable(self.interface)
else:
self.set_ipv6_addr(self.interface, self.addr, self.mask)
self.get_end_state()
self.results['changed'] = self.changed
self.results['proposed'] = self.proposed
self.results['existing'] = self.existing
self.results['end_state'] = self.end_state
if self.changed:
self.results['updates'] = self.updates_cmd
else:
self.results['updates'] = list()
self.module.exit_json(**self.results)
def main():
"""Module main"""
argument_spec = dict(
interface=dict(required=True),
addr=dict(required=False),
version=dict(required=False, choices=['v4', 'v6'],
default='v4'),
mask=dict(type='str', required=False),
ipv4_type=dict(required=False, choices=['main', 'sub'], default='main'),
state=dict(required=False, default='present',
choices=['present', 'absent'])
)
argument_spec.update(ce_argument_spec)
module = IpInterface(argument_spec)
module.work()
if __name__ == '__main__':
main()
| gpl-3.0 |
ivansib/sentinel | bin/dbtest.py | 1 | 1930 | # -*- coding: utf-8 -*-
import pdb
from pprint import pprint
import re
import sys
import os
sys.path.append(os.path.normpath(os.path.join(os.path.dirname(__file__), '../lib')))
import config
from models import Superblock, Proposal, GovernanceObject, Setting, Signal, Vote, Outcome
from models import VoteSignals, VoteOutcomes
from peewee import PeeweeException # , OperationalError, IntegrityError
#from dashd import DashDaemon
from sibcoind import SibcoinDaemon
import dashlib
from decimal import Decimal
#dashd = DashDaemon.from_dash_conf(config.dash_conf)
sibcoind = SibcoinDaemon.from_sibcoin_conf(config.sibcoin_conf)
import misc
# ==============================================================================
# do stuff here
pr = Proposal(
name='proposal7',
url='https://dashcentral.com/proposal7',
payment_address='yTC62huR4YQEPn9AJHjnQxxreHSbgAoatV',
payment_amount=39.23,
start_epoch=1483250400,
end_epoch=1491022800,
)
# sb = Superblock(
# event_block_height = 62500,
# payment_addresses = "yYe8KwyaUu5YswSYmB3q3ryx8XTUu9y7Ui|yTC62huR4YQEPn9AJHjnQxxreHSbgAoatV",
# payment_amounts = "5|3"
# )
# TODO: make this a test, mock 'dashd' and tie a test block height to a
# timestamp, ensure only unit testing a within_window method
#
# also, create the `within_window` or similar method & use that.
#
bh = 131112
bh_epoch = sibcoind.block_height_to_epoch(bh)
fudge = 72000
window_start = 1483689082 - fudge
window_end = 1483753726 + fudge
print("Window start: %s" % misc.epoch2str(window_start))
print("Window end: %s" % misc.epoch2str(window_end))
print("\nbh_epoch: %s" % misc.epoch2str(bh_epoch))
if (bh_epoch < window_start or bh_epoch > window_end):
print("outside of window!")
else:
print("Within window, we're good!")
# pdb.set_trace()
# dashd.get_object_list()
# ==============================================================================
# pdb.set_trace()
1
| mit |
robertaabreu/FatecJS | projetoTeckton/backend/appengine/routes/courses/rest.py | 28 | 1086 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from gaebusiness.business import CommandExecutionException
from tekton.gae.middleware.json_middleware import JsonResponse
from course_app import facade
def index():
cmd = facade.list_courses_cmd()
course_list = cmd()
short_form=facade.course_short_form()
course_short = [short_form.fill_with_model(m) for m in course_list]
return JsonResponse(course_short)
def save(**course_properties):
cmd = facade.save_course_cmd(**course_properties)
return _save_or_update_json_response(cmd)
def update(course_id, **course_properties):
cmd = facade.update_course_cmd(course_id, **course_properties)
return _save_or_update_json_response(cmd)
def delete(course_id):
facade.delete_course_cmd(course_id)()
def _save_or_update_json_response(cmd):
try:
course = cmd()
except CommandExecutionException:
return JsonResponse({'errors': cmd.errors})
short_form=facade.course_short_form()
return JsonResponse(short_form.fill_with_model(course))
| mit |
jendap/tensorflow | tensorflow/python/keras/utils/tf_utils.py | 1 | 10787 | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""TensorFlow-related utilities."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import six
from tensorflow.python.eager import context
from tensorflow.python.framework import ops
from tensorflow.python.framework import smart_cond as smart_module
from tensorflow.python.framework import sparse_tensor
from tensorflow.python.framework import tensor_shape
from tensorflow.python.framework import tensor_util
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import variables
from tensorflow.python.util import nest
def smart_cond(pred, true_fn=None, false_fn=None, name=None):
"""Return either `true_fn()` if predicate `pred` is true else `false_fn()`.
If `pred` is a bool or has a constant value, we return either `true_fn()`
or `false_fn()`, otherwise we use `tf.cond` to dynamically route to both.
Arguments:
pred: A scalar determining whether to return the result of `true_fn` or
`false_fn`.
true_fn: The callable to be performed if pred is true.
false_fn: The callable to be performed if pred is false.
name: Optional name prefix when using `tf.cond`.
Returns:
Tensors returned by the call to either `true_fn` or `false_fn`.
Raises:
TypeError: If `true_fn` or `false_fn` is not callable.
"""
if isinstance(pred, variables.Variable):
return control_flow_ops.cond(
pred, true_fn=true_fn, false_fn=false_fn, name=name)
return smart_module.smart_cond(
pred, true_fn=true_fn, false_fn=false_fn, name=name)
def constant_value(pred):
"""Return the bool value for `pred`, or None if `pred` had a dynamic value.
Arguments:
pred: A scalar, either a Python bool or a TensorFlow boolean variable
or tensor, or the Python integer 1 or 0.
Returns:
True or False if `pred` has a constant boolean value, None otherwise.
Raises:
TypeError: If `pred` is not a Variable, Tensor or bool, or Python
integer 1 or 0.
"""
# Allow integer booleans.
if isinstance(pred, int):
if pred == 1:
pred = True
elif pred == 0:
pred = False
if isinstance(pred, variables.Variable):
return None
return smart_module.smart_constant_value(pred)
def is_tensor_or_tensor_list(v):
v = nest.flatten(v)
if v and isinstance(v[0], ops.Tensor):
return True
else:
return False
def get_reachable_from_inputs(inputs, targets=None):
"""Returns the set of tensors/ops reachable from `inputs`.
Stops if all targets have been found (target is optional).
Only valid in Symbolic mode, not Eager mode.
Args:
inputs: List of tensors.
targets: List of tensors.
Returns:
A set of tensors reachable from the inputs (includes the inputs themselves).
"""
inputs = nest.flatten(inputs)
reachable = set(inputs)
if targets:
targets = set(targets)
queue = inputs[:]
while queue:
x = queue.pop()
if isinstance(x, ops.Operation):
outputs = x.outputs[:] or []
outputs += x._control_outputs # pylint: disable=protected-access
elif isinstance(x, variables.Variable):
outputs = [x.op]
elif tensor_util.is_tensor(x):
outputs = x.consumers()
else:
raise TypeError('Expected Operation, Variable, or Tensor, got ' + str(x))
for y in outputs:
if y not in reachable:
reachable.add(y)
queue.insert(0, y)
if targets and targets.issubset(reachable):
return reachable
return reachable
# This function needs access to private functions of `nest`.
# pylint: disable=protected-access
def map_structure_with_atomic(is_atomic_fn, map_fn, nested):
"""Maps the atomic elements of a nested structure.
Arguments:
is_atomic_fn: A function that determines if an element of `nested` is
atomic.
map_fn: The function to apply to atomic elements of `nested`.
nested: A nested structure.
Returns:
The nested structure, with atomic elements mapped according to `map_fn`.
Raises:
ValueError: If an element that is neither atomic nor a sequence is
encountered.
"""
if is_atomic_fn(nested):
return map_fn(nested)
# Recursively convert.
if not nest.is_sequence(nested):
raise ValueError(
'Received non-atomic and non-sequence element: {}'.format(nested))
if nest._is_mapping(nested):
values = [nested[k] for k in nest._sorted(nested)]
else:
values = nested
mapped_values = [
map_structure_with_atomic(is_atomic_fn, map_fn, ele) for ele in values
]
return nest._sequence_like(nested, mapped_values)
# pylint: enable=protected-access
def convert_shapes(input_shape, to_tuples=True):
"""Converts nested shape representations to desired format.
Performs:
TensorShapes -> tuples if `to_tuples=True`.
tuples of int or None -> TensorShapes if `to_tuples=False`.
Valid objects to be converted are:
- TensorShapes
- tuples with elements of type int or None.
- ints
- None
Arguments:
input_shape: A nested structure of objects to be converted to TensorShapes.
to_tuples: If `True`, converts all TensorShape to tuples. Otherwise converts
all tuples representing shapes to TensorShapes.
Returns:
Nested structure of shapes in desired format.
"""
def _is_shape_component(element):
value = tensor_shape.as_dimension(element).value
return value is None or isinstance(value, int)
def _is_atomic_shape(input_shape):
# Ex: TensorShape or (None, 10, 32) or 5 or `None`
if input_shape is None or isinstance(input_shape, int):
return True
if isinstance(input_shape, tensor_shape.TensorShape):
return True
if (isinstance(input_shape, tuple) and
all(_is_shape_component(ele) for ele in input_shape)):
return True
return False
def _convert_shape(input_shape):
input_shape = tensor_shape.TensorShape(input_shape)
if to_tuples:
input_shape = tuple(input_shape.as_list())
return input_shape
return map_structure_with_atomic(_is_atomic_shape, _convert_shape,
input_shape)
class ListWrapper(object):
"""A wrapper for lists to be treated as elements for `nest`."""
def __init__(self, list_to_wrap):
self._list = list_to_wrap
def as_list(self):
return self._list
def convert_inner_node_data(nested, wrap=False):
"""Either wraps or unwraps innermost node data lists in `ListWrapper` objects.
Arguments:
nested: A nested data structure.
wrap: If `True`, wrap innermost lists in `ListWrapper` objects. If `False`,
unwraps `ListWrapper` objects into lists.
Returns:
Strucutre of same type as nested, with lists wrapped/unwrapped.
"""
def _is_atomic_nested(nested):
"""Returns `True` if `nested` is a list representing node data."""
if isinstance(nested, ListWrapper):
return True
# Node data can be of form `[layer_name, node_id, tensor_id]` or
# `[layer_name, node_id, tensor_id, kwargs]`.
if (isinstance(nested, list) and (len(nested) in [3, 4]) and
isinstance(nested[0], six.string_types)):
return True
return False
def _convert_object_or_list(nested):
"""Convert b/t `ListWrapper` object and list representations."""
if wrap:
if isinstance(nested, ListWrapper):
return nested
return ListWrapper(nested)
else:
if isinstance(nested, ListWrapper):
return nested.as_list()
return nested
return map_structure_with_atomic(_is_atomic_nested, _convert_object_or_list,
nested)
def shape_type_conversion(fn):
"""Decorator that handles tuple/TensorShape conversion.
Used in `compute_output_shape` and `build`.
Arguments:
fn: function to wrap.
Returns:
Wrapped function.
"""
def wrapper(instance, input_shape):
# Pass shapes as tuples to `fn`
# This preserves compatibility with external Keras.
if input_shape is not None:
input_shape = convert_shapes(input_shape, to_tuples=True)
output_shape = fn(instance, input_shape)
# Return shapes from `fn` as TensorShapes.
if output_shape is not None:
output_shape = convert_shapes(output_shape, to_tuples=False)
return output_shape
return wrapper
def are_all_symbolic_tensors(tensors):
return all(is_symbolic_tensor(tensor) for tensor in tensors)
_user_convertible_tensor_types = set()
def is_symbolic_tensor(tensor):
"""Returns whether a tensor is symbolic (from a TF graph) or an eager tensor.
A Variable can be seen as either: it is considered symbolic
when we are in a graph scope, and eager when we are in an eager scope.
Arguments:
tensor: A tensor instance to test.
Returns:
True for symbolic tensors, False for eager tensors.
"""
if isinstance(tensor, variables.Variable):
return not context.executing_eagerly()
if isinstance(tensor, (ops.Tensor, sparse_tensor.SparseTensor)):
return hasattr(tensor, 'graph')
if isinstance(tensor, tuple(_user_convertible_tensor_types)):
return hasattr(ops.convert_to_tensor(tensor), 'graph')
return False
def register_symbolic_tensor_type(cls):
"""Allows users to specify types regarded as symbolic `Tensor`s.
Used in conjunction with `tf.register_tensor_conversion_function`, calling
`tf.keras.utils.register_symbolic_tensor_type(cls)` allows non-`Tensor`
objects to be plumbed through Keras layers.
Example:
```python
# One-time setup.
class Foo(object):
def __init__(self, input_):
self._input = input_
def value(self):
return tf.constant(42.)
tf.register_tensor_conversion_function(
Foo, lambda x, *args, **kwargs: x.value())
tf.keras.utils.register_symbolic_tensor_type(Foo)
# User-land.
layer = tf.keras.layers.Lambda(lambda input_: Foo(input_))
```
Arguments:
cls: A `class` type which shall be regarded as a symbolic `Tensor`.
"""
global _user_convertible_tensor_types
_user_convertible_tensor_types.add(cls)
def is_tensor_or_variable(x):
return tensor_util.is_tensor(x) or isinstance(x, variables.Variable)
| apache-2.0 |
saumishr/django | tests/urls.py | 91 | 1189 | from django.conf.urls import patterns, include
urlpatterns = patterns('',
# test_client modeltest urls
(r'^test_client/', include('modeltests.test_client.urls')),
(r'^test_client_regress/', include('regressiontests.test_client_regress.urls')),
# File upload test views
(r'^file_uploads/', include('regressiontests.file_uploads.urls')),
# Always provide the auth system login and logout views
(r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'login.html'}),
(r'^accounts/logout/$', 'django.contrib.auth.views.logout'),
# test urlconf for {% url %} template tag
(r'^url_tag/', include('regressiontests.templates.urls')),
# django built-in views
(r'^views/', include('regressiontests.views.urls')),
# test urlconf for middleware tests
(r'^middleware/', include('regressiontests.middleware.urls')),
# admin widget tests
(r'widget_admin/', include('regressiontests.admin_widgets.urls')),
# admin custom URL tests
(r'^custom_urls/', include('regressiontests.admin_custom_urls.urls')),
# admin scripts tests
(r'^admin_scripts/', include('regressiontests.admin_scripts.urls')),
)
| bsd-3-clause |
3dfxsoftware/cbss-addons | gamification/__openerp__.py | 62 | 2433 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2013 OpenERP SA (<http://openerp.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name': 'Gamification',
'version': '1.0',
'author': 'OpenERP SA',
'category': 'Human Ressources',
'depends': ['mail', 'email_template', 'web_kanban_gauge'],
'description': """
Gamification process
====================
The Gamification module provides ways to evaluate and motivate the users of OpenERP.
The users can be evaluated using goals and numerical objectives to reach.
**Goals** are assigned through **challenges** to evaluate and compare members of a team with each others and through time.
For non-numerical achievements, **badges** can be granted to users. From a simple "thank you" to an exceptional achievement, a badge is an easy way to exprimate gratitude to a user for their good work.
Both goals and badges are flexibles and can be adapted to a large range of modules and actions. When installed, this module creates easy goals to help new users to discover OpenERP and configure their user profile.
""",
'data': [
'wizard/update_goal.xml',
'wizard/grant_badge.xml',
'views/badge.xml',
'views/challenge.xml',
'views/goal.xml',
'data/cron.xml',
'security/gamification_security.xml',
'security/ir.model.access.csv',
'data/goal_base.xml',
'data/badge.xml',
'views/gamification.xml',
],
'installable': True,
'application': True,
'auto_install': False,
'qweb': ['static/src/xml/gamification.xml'],
}
| gpl-2.0 |
lantianlz/zx | www/misc/oauth2/sina.py | 1 | 2675 | # -*- coding: utf-8 -*-
'''
@author: lizheng
@date: 2014-01-01
'''
import requests
import urllib
import re
import json
from pprint import pprint
from django.conf import settings
CLIENT_ID = '266639437'
CLIENT_SECRET = 'b10ce4a1500d819a2c5437b7d6d1ea79'
API_URL = 'https://api.weibo.com'
REDIRECT_URI = '%s/account/oauth/sina' % settings.MAIN_DOMAIN
class Consumer(object):
def __init__(self, response_type='code'):
self.client_id = CLIENT_ID
self.client_secret = CLIENT_SECRET
self.api_url = API_URL
self.response_type = response_type
self.redirect_uri = REDIRECT_URI # urllib.quote_plus(REDIRECT_URI)
self.grant_type = 'authorization_code'
self.dict_format = dict(client_id=self.client_id, client_secret=self.client_secret,
response_type=self.response_type, api_url=self.api_url, grant_type=self.grant_type,
redirect_uri=self.redirect_uri)
def authorize(self):
return ('%(api_url)s/oauth2/authorize?response_type=%(response_type)s&client_id=%(client_id)s'
'&redirect_uri=%(redirect_uri)s') % self.dict_format
def token(self, code):
self.dict_format.update(dict(code=code))
access_token_url = ('%(api_url)s/oauth2/access_token') % self.dict_format
data = dict(grant_type=self.dict_format['grant_type'],
client_id=self.dict_format['client_id'],
client_secret=self.dict_format['client_secret'],
code=self.dict_format['code'],
redirect_uri=self.dict_format['redirect_uri'],
)
rep = requests.post(access_token_url, data=data, timeout=30)
content = rep.text
dict_result = json.loads(content)
return dict(access_token=dict_result['access_token'], expires_in=dict_result['expires_in'],
uid=dict_result['uid'], refresh_token='')
def refresh_token(self, refresh_token):
pass
def request_api(self, access_token, method_name, data={}, method='GET'):
request_url = '%(api_url)s%(method_name)s' % dict(api_url=self.api_url, method_name=method_name)
data.update(oauth_consumer_key=self.client_id)
if method == 'GET':
request_url = '%s?%s' % (request_url, urllib.urlencode(data))
rep = requests.get(request_url, timeout=30)
else:
rep = requests.post(request_url, data=data, timeout=30)
content = rep.content
# print request_url
# print content
try:
return json.loads(content)
except:
return content
| gpl-2.0 |
moyaproject/moya | moya/tests/test_urlmapper.py | 1 | 3878 | import unittest
from moya import urlmapper
from moya.urlmapper import RouteMatch
class TestURLMapper(unittest.TestCase):
def setUp(self):
self.mapper = urlmapper.URLMapper()
self.mapper.map("/", "front")
self.mapper.map("/page/", "page", defaults={"page": "front"})
self.mapper.map("/page/{page}/", "page")
self.mapper.map("/page/{page}/edit/", "edit", methods=["GET"])
self.mapper.map("/page/{page}/edit/", "editform", methods=["POST"])
self.mapper.map("/blog/", "blog")
self.mapper.map("/blog/{year}/{month}/{day}/", "post")
self.submapper = urlmapper.URLMapper()
self.submapper.map("/", "wikifront")
self.submapper.map("/page/{slug}/", "wikipage")
self.mapper.mount("/wiki/", self.submapper)
def testSimple(self):
"""Test simple top-level URL mapping"""
self.assertEqual(self.mapper.get_route("/"), RouteMatch({}, "front", None))
self.assertEqual(
self.mapper.get_route("/page/"), RouteMatch({"page": "front"}, "page", None)
)
self.assertEqual(
self.mapper.get_route("/page/welcome/"),
RouteMatch({"page": "welcome"}, "page", None),
)
self.assertEqual(self.mapper.get_route("/blog/"), RouteMatch({}, "blog", None))
self.assertEqual(
self.mapper.get_route("/blog/2011/7/5/"),
RouteMatch(dict(year="2011", month="7", day="5"), "post", None),
)
self.assertEqual(self.mapper.get_route("/nothere/"), None)
# Test again to confirm caching is working
self.assertEqual(self.mapper.get_route("/"), RouteMatch({}, "front", None))
self.assertEqual(
self.mapper.get_route("/page/"), RouteMatch({"page": "front"}, "page", None)
)
self.assertEqual(
self.mapper.get_route("/page/welcome/"),
RouteMatch({"page": "welcome"}, "page", None),
)
self.assertEqual(self.mapper.get_route("/blog/"), RouteMatch({}, "blog", None))
self.assertEqual(
self.mapper.get_route("/blog/2011/7/5/"),
RouteMatch(dict(year="2011", month="7", day="5"), "post", None),
)
self.assertEqual(self.mapper.get_route("/nothere/"), None)
def testSubMapper(self):
"""Test URL sub-mapper"""
self.assertEqual(
self.mapper.get_route("/wiki/"), RouteMatch({}, "wikifront", None)
)
self.assertEqual(
self.mapper.get_route("/wiki/page/moya/"),
RouteMatch({"slug": "moya"}, "wikipage", None),
)
self.assertEqual(
self.mapper.get_route("/wiki/"), RouteMatch({}, "wikifront", None)
)
self.assertEqual(
self.mapper.get_route("/wiki/page/moya/"),
RouteMatch({"slug": "moya"}, "wikipage", None),
)
def testMethodMap(self):
"""Test URL mapping by method"""
self.assertEqual(
self.mapper.get_route("/page/moya/edit/"),
RouteMatch(dict(page="moya"), "edit", None),
)
self.assertEqual(
self.mapper.get_route("/page/moya/edit/", "GET"),
RouteMatch(dict(page="moya"), "edit", None),
)
self.assertEqual(
self.mapper.get_route("/page/moya/edit/", "POST"),
RouteMatch(dict(page="moya"), "editform", None),
)
self.assertEqual(
self.mapper.get_route("/page/moya/edit/"),
RouteMatch(dict(page="moya"), "edit", None),
)
self.assertEqual(
self.mapper.get_route("/page/moya/edit/", "GET"),
RouteMatch(dict(page="moya"), "edit", None),
)
self.assertEqual(
self.mapper.get_route("/page/moya/edit/", "POST"),
RouteMatch(dict(page="moya"), "editform", None),
)
| mit |
rdio/translate-toolkit | convert/po2ical.py | 3 | 2540 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2002-2006 Zuza Software Foundation
#
# This file is part of translate.
#
# translate 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.
#
# translate 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 translate; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
"""convert Gettext PO localization files to iCal files"""
from translate.storage import factory
from translate.storage import ical
class reical:
def __init__(self, templatefile, inputstore):
self.templatefile = templatefile
self.templatestore = ical.icalfile(templatefile)
self.inputstore = inputstore
def convertstore(self, includefuzzy=False):
self.includefuzzy = includefuzzy
self.inputstore.makeindex()
for unit in self.templatestore.units:
for location in unit.getlocations():
if location in self.inputstore.locationindex:
inputunit = self.inputstore.locationindex[location]
if inputunit.isfuzzy() and not self.includefuzzy:
unit.target = unit.source
else:
unit.target = inputunit.target
else:
unit.target = unit.source
return str(self.templatestore)
def convertical(inputfile, outputfile, templatefile, includefuzzy=False):
inputstore = factory.getobject(inputfile)
if templatefile is None:
raise ValueError("must have template file for iCal files")
else:
convertor = reical(templatefile, inputstore)
outputstring = convertor.convertstore(includefuzzy)
outputfile.write(outputstring)
return 1
def main(argv=None):
# handle command line options
from translate.convert import convert
formats = {("po", "ics"): ("ics", convertical)}
parser = convert.ConvertOptionParser(formats, usetemplates=True, description=__doc__)
parser.add_fuzzy_option()
parser.run(argv)
if __name__ == '__main__':
main()
| gpl-2.0 |
v1bri/gnuradio | gr-zeromq/python/zeromq/rpc_manager.py | 25 | 3805 | #
# Copyright 2013 Free Software Foundation, Inc.
#
# This file is part of GNU Radio.
#
# 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, or (at your option)
# any later version.
#
# This software is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this software; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
import zmq
import pmt
import threading
class rpc_manager():
def __init__(self):
self.zmq_context = zmq.Context()
self.poller_rep = zmq.Poller()
self.poller_req_out = zmq.Poller()
self.poller_req_in = zmq.Poller()
self.interfaces = dict()
def __del__(self):
self.stop_watcher()
self.watcher_thread.join()
def set_reply_socket(self, address):
self.rep_socket = self.zmq_context.socket(zmq.REP)
self.rep_socket.bind(address)
print "[RPC] reply socket bound to: ", address
self.poller_rep.register(self.rep_socket, zmq.POLLIN)
def set_request_socket(self, address):
self.req_socket = self.zmq_context.socket(zmq.REQ)
self.req_socket.connect(address)
print "[RPC] request socket connected to: ", address
self.poller_req_out.register(self.req_socket, zmq.POLLOUT)
self.poller_req_in.register(self.req_socket, zmq.POLLIN)
def add_interface(self, id_str, callback_func):
if not self.interfaces.has_key(id_str):
self.interfaces[id_str] = callback_func
print "[RPC] added reply interface:", id_str
else:
print "[RPC] ERROR: duplicate id_str:", id_str
def watcher(self):
self.keep_running = True
while self.keep_running:
# poll for calls
socks = dict(self.poller_rep.poll(10))
if socks.get(self.rep_socket) == zmq.POLLIN:
# receive call
msg = self.rep_socket.recv()
(id_str, args) = pmt.to_python(pmt.deserialize_str(msg))
print "[RPC] request:", id_str, ", args:", args
reply = self.callback(id_str, args)
self.rep_socket.send(pmt.serialize_str(pmt.to_pmt(reply)))
def start_watcher(self):
self.watcher_thread = threading.Thread(target=self.watcher,args=())
self.watcher_thread.daemon = True
self.watcher_thread.start()
def stop_watcher(self):
self.keep_running = False
self.watcher_thread.join()
def request(self, id_str, args=None):
socks = dict(self.poller_req_out.poll(10))
if socks.get(self.req_socket) == zmq.POLLOUT:
self.req_socket.send(pmt.serialize_str(pmt.to_pmt((id_str,args))))
socks = dict(self.poller_req_in.poll(10))
if socks.get(self.req_socket) == zmq.POLLIN:
reply = pmt.to_python(pmt.deserialize_str(self.req_socket.recv()))
print "[RPC] reply:", reply
return reply
def callback(self, id_str, args):
if self.interfaces.has_key(id_str):
callback_func = self.interfaces.get(id_str)
if not args == None:
# use unpacking or splat operator * to unpack argument list
return(callback_func(*args))
else:
return(callback_func())
else:
print "[RPC] ERROR: id_str not found:", id_str
return None
| gpl-3.0 |
mxOBS/deb-pkg_trusty_chromium-browser | third_party/webpagereplay/httpclient_test.py | 4 | 7389 | #!/usr/bin/env python
# Copyright 2012 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.
import unittest
import httpclient
import platformsettings
class RealHttpFetchTest(unittest.TestCase):
# Initialize test data
CONTENT_TYPE = 'content-type: image/x-icon'
COOKIE_1 = ('Set-Cookie: GMAIL_IMP=EXPIRED; '
'Expires=Thu, 12-Jul-2012 22:41:22 GMT; '
'Path=/mail; Secure')
COOKIE_2 = ('Set-Cookie: GMAIL_STAT_205a=EXPIRED; '
'Expires=Thu, 12-Jul-2012 22:42:24 GMT; '
'Path=/mail; Secure')
FIRST_LINE = 'fake-header: first line'
SECOND_LINE = ' second line'
THIRD_LINE = '\tthird line'
BAD_HEADER = 'this is a bad header'
def test__GetHeaderNameValueBasic(self):
"""Test _GetHeaderNameValue with normal header."""
real_http_fetch = httpclient.RealHttpFetch
name_value = real_http_fetch._GetHeaderNameValue(self.CONTENT_TYPE)
self.assertEqual(name_value, ('content-type', 'image/x-icon'))
def test__GetHeaderNameValueLowercasesName(self):
"""_GetHeaderNameValue lowercases header name."""
real_http_fetch = httpclient.RealHttpFetch
header = 'X-Google-Gfe-Backend-Request-Info: eid=1KMAUMeiK4eMiAL52YyMBg'
expected = ('x-google-gfe-backend-request-info',
'eid=1KMAUMeiK4eMiAL52YyMBg')
name_value = real_http_fetch._GetHeaderNameValue(header)
self.assertEqual(name_value, expected)
def test__GetHeaderNameValueBadLineGivesNone(self):
"""_GetHeaderNameValue returns None for a header in wrong format."""
real_http_fetch = httpclient.RealHttpFetch
name_value = real_http_fetch._GetHeaderNameValue(self.BAD_HEADER)
self.assertIsNone(name_value)
def test__ToTuplesBasic(self):
"""Test _ToTuples with normal input."""
real_http_fetch = httpclient.RealHttpFetch
headers = [self.CONTENT_TYPE, self.COOKIE_1, self.FIRST_LINE]
result = real_http_fetch._ToTuples(headers)
expected = [('content-type', 'image/x-icon'),
('set-cookie', self.COOKIE_1[12:]),
('fake-header', 'first line')]
self.assertEqual(result, expected)
def test__ToTuplesMultipleHeadersWithSameName(self):
"""Test mulitple headers with the same name."""
real_http_fetch = httpclient.RealHttpFetch
headers = [self.CONTENT_TYPE, self.COOKIE_1, self.COOKIE_2, self.FIRST_LINE]
result = real_http_fetch._ToTuples(headers)
expected = [('content-type', 'image/x-icon'),
('set-cookie', self.COOKIE_1[12:]),
('set-cookie', self.COOKIE_2[12:]),
('fake-header', 'first line')]
self.assertEqual(result, expected)
def test__ToTuplesAppendsContinuationLine(self):
"""Test continuation line is handled."""
real_http_fetch = httpclient.RealHttpFetch
headers = [self.CONTENT_TYPE, self.COOKIE_1, self.FIRST_LINE,
self.SECOND_LINE, self.THIRD_LINE]
result = real_http_fetch._ToTuples(headers)
expected = [('content-type', 'image/x-icon'),
('set-cookie', self.COOKIE_1[12:]),
('fake-header', 'first line\n second line\n third line')]
self.assertEqual(result, expected)
def test__ToTuplesIgnoresBadHeader(self):
"""Test bad header is ignored."""
real_http_fetch = httpclient.RealHttpFetch
bad_headers = [self.CONTENT_TYPE, self.BAD_HEADER, self.COOKIE_1]
expected = [('content-type', 'image/x-icon'),
('set-cookie', self.COOKIE_1[12:])]
result = real_http_fetch._ToTuples(bad_headers)
self.assertEqual(result, expected)
def test__ToTuplesIgnoresMisplacedContinuationLine(self):
"""Test misplaced continuation line is ignored."""
real_http_fetch = httpclient.RealHttpFetch
misplaced_headers = [self.THIRD_LINE, self.CONTENT_TYPE,
self.COOKIE_1, self.FIRST_LINE, self.SECOND_LINE]
result = real_http_fetch._ToTuples(misplaced_headers)
expected = [('content-type', 'image/x-icon'),
('set-cookie', self.COOKIE_1[12:]),
('fake-header', 'first line\n second line')]
self.assertEqual(result, expected)
class RealHttpFetchGetConnectionTest(unittest.TestCase):
"""Test that a connection is made with request IP/port or proxy IP/port."""
def setUp(self):
def real_dns_lookup(host):
return {
'example.com': '127.127.127.127',
'proxy.com': '2.2.2.2',
}[host]
self.fetch = httpclient.RealHttpFetch(real_dns_lookup)
self.https_proxy = None
self.http_proxy = None
def get_proxy(is_ssl):
return self.https_proxy if is_ssl else self.http_proxy
self.fetch._get_system_proxy = get_proxy
def set_http_proxy(self, host, port):
self.http_proxy = platformsettings.SystemProxy(host, port)
def set_https_proxy(self, host, port):
self.https_proxy = platformsettings.SystemProxy(host, port)
def test_get_connection_without_proxy_connects_to_host_ip(self):
"""HTTP connection with no proxy connects to host IP."""
self.set_http_proxy(host=None, port=None)
connection = self.fetch._get_connection('example.com', None, is_ssl=False)
self.assertEqual('127.127.127.127', connection.host)
self.assertEqual(80, connection.port) # default HTTP port
def test_get_connection_without_proxy_uses_nondefault_request_port(self):
"""HTTP connection with no proxy connects with request port."""
self.set_https_proxy(host=None, port=None)
connection = self.fetch._get_connection('example.com', 8888, is_ssl=False)
self.assertEqual('127.127.127.127', connection.host)
self.assertEqual(8888, connection.port) # request HTTP port
def test_get_connection_with_proxy_uses_proxy_port(self):
"""HTTP connection with proxy connects used proxy port."""
self.set_http_proxy(host='proxy.com', port=None)
connection = self.fetch._get_connection('example.com', 8888, is_ssl=False)
self.assertEqual('2.2.2.2', connection.host) # proxy IP
self.assertEqual(80, connection.port) # proxy port (default HTTP)
def test_ssl_get_connection_without_proxy_connects_to_host_ip(self):
"""HTTPS (SSL) connection with no proxy connects to host IP."""
self.set_https_proxy(host=None, port=None)
connection = self.fetch._get_connection('example.com', None, is_ssl=True)
self.assertEqual('127.127.127.127', connection.host)
self.assertEqual(443, connection.port) # default SSL port
def test_ssl_get_connection_with_proxy_connects_to_proxy_ip(self):
"""HTTPS (SSL) connection with proxy connects to proxy IP."""
self.set_https_proxy(host='proxy.com', port=8443)
connection = self.fetch._get_connection('example.com', None, is_ssl=True)
self.assertEqual('2.2.2.2', connection.host) # proxy IP
self.assertEqual(8443, connection.port) # SSL proxy port
if __name__ == '__main__':
unittest.main()
| bsd-3-clause |
TeamTwisted/external_chromium_org | tools/cr/cr/commands/run.py | 45 | 1663 | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""A module for the run command."""
import cr
class RunCommand(cr.Command):
"""The implementation of the run command.
This first uses Builder to bring the target up to date.
It then uses Installer to install the target (if needed), and
finally it uses Runner to run the target.
You can use skip version to not perform any of these steps.
"""
def __init__(self):
super(RunCommand, self).__init__()
self.help = 'Invoke a target'
def AddArguments(self, subparsers):
parser = super(RunCommand, self).AddArguments(subparsers)
cr.Builder.AddArguments(self, parser)
cr.Installer.AddArguments(self, parser)
cr.Runner.AddArguments(self, parser)
cr.Target.AddArguments(self, parser, allow_multiple=True)
self.ConsumeArgs(parser, 'the binary')
return parser
def Run(self):
targets = cr.Target.GetTargets()
test_targets = [target for target in targets if target.is_test]
run_targets = [target for target in targets if not target.is_test]
if cr.Installer.Skipping():
# No installer, only build test targets
build_targets = test_targets
else:
build_targets = targets
if build_targets:
cr.Builder.Build(build_targets, [])
# See if we can use restart when not installing
if cr.Installer.Skipping():
cr.Runner.Restart(targets, cr.context.remains)
else:
cr.Runner.Kill(run_targets, [])
cr.Installer.Reinstall(run_targets, [])
cr.Runner.Invoke(targets, cr.context.remains)
| bsd-3-clause |
chotchki/servo | python/mach/mach/test/test_conditions.py | 28 | 2848 | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from __future__ import unicode_literals
import os
from mach.base import MachError
from mach.main import Mach
from mach.test.common import TestBase
from mozunit import main
def _populate_context(context, key=None):
if key is None:
return
if key == 'foo':
return True
if key == 'bar':
return False
raise AttributeError(key)
class TestConditions(TestBase):
"""Tests for conditionally filtering commands."""
def _run_mach(self, args, context_handler=None):
return TestBase._run_mach(self, args, 'conditions.py',
context_handler=context_handler)
def test_conditions_pass(self):
"""Test that a command which passes its conditions is runnable."""
self.assertEquals((0, '', ''), self._run_mach(['cmd_foo']))
self.assertEquals((0, '', ''), self._run_mach(['cmd_foo_ctx'], _populate_context))
def test_invalid_context_message(self):
"""Test that commands which do not pass all their conditions
print the proper failure message."""
def is_bar():
"""Bar must be true"""
fail_conditions = [is_bar]
for name in ('cmd_bar', 'cmd_foobar'):
result, stdout, stderr = self._run_mach([name])
self.assertEquals(1, result)
fail_msg = Mach._condition_failed_message(name, fail_conditions)
self.assertEquals(fail_msg.rstrip(), stdout.rstrip())
for name in ('cmd_bar_ctx', 'cmd_foobar_ctx'):
result, stdout, stderr = self._run_mach([name], _populate_context)
self.assertEquals(1, result)
fail_msg = Mach._condition_failed_message(name, fail_conditions)
self.assertEquals(fail_msg.rstrip(), stdout.rstrip())
def test_invalid_type(self):
"""Test that a condition which is not callable raises an exception."""
m = Mach(os.getcwd())
m.define_category('testing', 'Mach unittest', 'Testing for mach core', 10)
self.assertRaises(MachError, m.load_commands_from_file,
os.path.join(self.provider_dir, 'conditions_invalid.py'))
def test_help_message(self):
"""Test that commands that are not runnable do not show up in help."""
result, stdout, stderr = self._run_mach(['help'], _populate_context)
self.assertIn('cmd_foo', stdout)
self.assertNotIn('cmd_bar', stdout)
self.assertNotIn('cmd_foobar', stdout)
self.assertIn('cmd_foo_ctx', stdout)
self.assertNotIn('cmd_bar_ctx', stdout)
self.assertNotIn('cmd_foobar_ctx', stdout)
if __name__ == '__main__':
main()
| mpl-2.0 |
paulmadore/Eric-IDE | 6-6.0.9/eric/Graphics/AssociationItem.py | 2 | 19298 | # -*- coding: utf-8 -*-
# Copyright (c) 2004 - 2015 Detlev Offenbach <detlev@die-offenbachs.de>
#
"""
Module implementing a graphics item for an association between two items.
"""
from __future__ import unicode_literals
from PyQt5.QtCore import QPointF, QRectF, QLineF
from PyQt5.QtWidgets import QGraphicsItem
from E5Graphics.E5ArrowItem import E5ArrowItem, NormalArrow, WideArrow
import Utilities
Normal = 0
Generalisation = 1
Imports = 2
NoRegion = 0
West = 1
North = 2
East = 3
South = 4
NorthWest = 5
NorthEast = 6
SouthEast = 7
SouthWest = 8
Center = 9
class AssociationItem(E5ArrowItem):
"""
Class implementing a graphics item for an association between two items.
The association is drawn as an arrow starting at the first items and
ending at the second.
"""
def __init__(self, itemA, itemB, type=Normal, topToBottom=False,
parent=None):
"""
Constructor
@param itemA first widget of the association
@param itemB second widget of the association
@param type type of the association. This must be one of
<ul>
<li>Normal (default)</li>
<li>Generalisation</li>
<li>Imports</li>
</ul>
@keyparam topToBottom flag indicating to draw the association
from item A top to item B bottom (boolean)
@keyparam parent reference to the parent object (QGraphicsItem)
"""
if type == Normal:
arrowType = NormalArrow
arrowFilled = True
elif type == Imports:
arrowType = NormalArrow
arrowFilled = True
elif type == Generalisation:
arrowType = WideArrow
arrowFilled = False
E5ArrowItem.__init__(self, QPointF(0, 0), QPointF(100, 100),
arrowFilled, arrowType, parent)
self.setFlag(QGraphicsItem.ItemIsMovable, False)
self.setFlag(QGraphicsItem.ItemIsSelectable, False)
if topToBottom:
self.calculateEndingPoints = \
self.__calculateEndingPoints_topToBottom
else:
## self.calculateEndingPoints = self.__calculateEndingPoints_center
self.calculateEndingPoints = self.__calculateEndingPoints_rectangle
self.itemA = itemA
self.itemB = itemB
self.assocType = type
self.topToBottom = topToBottom
self.regionA = NoRegion
self.regionB = NoRegion
self.calculateEndingPoints()
self.itemA.addAssociation(self)
self.itemB.addAssociation(self)
def __mapRectFromItem(self, item):
"""
Private method to map item's rectangle to this item's coordinate
system.
@param item reference to the item to be mapped (QGraphicsRectItem)
@return item's rectangle in local coordinates (QRectF)
"""
rect = item.rect()
tl = self.mapFromItem(item, rect.topLeft())
return QRectF(tl.x(), tl.y(), rect.width(), rect.height())
def __calculateEndingPoints_topToBottom(self):
"""
Private method to calculate the ending points of the association item.
The ending points are calculated from the top center of the lower item
to the bottom center of the upper item.
"""
if self.itemA is None or self.itemB is None:
return
self.prepareGeometryChange()
rectA = self.__mapRectFromItem(self.itemA)
rectB = self.__mapRectFromItem(self.itemB)
midA = QPointF(rectA.x() + rectA.width() / 2.0,
rectA.y() + rectA.height() / 2.0)
midB = QPointF(rectB.x() + rectB.width() / 2.0,
rectB.y() + rectB.height() / 2.0)
if midA.y() > midB.y():
startP = QPointF(rectA.x() + rectA.width() / 2.0, rectA.y())
endP = QPointF(rectB.x() + rectB.width() / 2.0,
rectB.y() + rectB.height())
else:
startP = QPointF(rectA.x() + rectA.width() / 2.0,
rectA.y() + rectA.height())
endP = QPointF(rectB.x() + rectB.width() / 2.0, rectB.y())
self.setPoints(startP.x(), startP.y(), endP.x(), endP.y())
def __calculateEndingPoints_center(self):
"""
Private method to calculate the ending points of the association item.
The ending points are calculated from the centers of the
two associated items.
"""
if self.itemA is None or self.itemB is None:
return
self.prepareGeometryChange()
rectA = self.__mapRectFromItem(self.itemA)
rectB = self.__mapRectFromItem(self.itemB)
midA = QPointF(rectA.x() + rectA.width() / 2.0,
rectA.y() + rectA.height() / 2.0)
midB = QPointF(rectB.x() + rectB.width() / 2.0,
rectB.y() + rectB.height() / 2.0)
startP = self.__findRectIntersectionPoint(self.itemA, midA, midB)
endP = self.__findRectIntersectionPoint(self.itemB, midB, midA)
if startP.x() != -1 and startP.y() != -1 and \
endP.x() != -1 and endP.y() != -1:
self.setPoints(startP.x(), startP.y(), endP.x(), endP.y())
def __calculateEndingPoints_rectangle(self):
r"""
Private method to calculate the ending points of the association item.
The ending points are calculated by the following method.
For each item the diagram is divided in four Regions by its diagonals
as indicated below
<pre>
\ Region 2 /
\ /
|--------|
| \ / |
| \ / |
| \/ |
Region 1 | /\ | Region 3
| / \ |
| / \ |
|--------|
/ \
/ Region 4 \
</pre>
Each diagonal is defined by two corners of the bounding rectangle
To calculate the start point we have to find out in which
region (defined by itemA's diagonals) is itemB's TopLeft corner
(lets call it region M). After that the start point will be
the middle point of rectangle's side contained in region M.
To calculate the end point we repeat the above but in the opposite
direction (from itemB to itemA)
"""
if self.itemA is None or self.itemB is None:
return
self.prepareGeometryChange()
rectA = self.__mapRectFromItem(self.itemA)
rectB = self.__mapRectFromItem(self.itemB)
xA = rectA.x() + rectA.width() / 2.0
yA = rectA.y() + rectA.height() / 2.0
xB = rectB.x() + rectB.width() / 2.0
yB = rectB.y() + rectB.height() / 2.0
# find itemA region
rc = QRectF(xA, yA, rectA.width(), rectA.height())
self.regionA = self.__findPointRegion(rc, xB, yB)
# move some regions to the standard ones
if self.regionA == NorthWest:
self.regionA = North
elif self.regionA == NorthEast:
self.regionA = East
elif self.regionA == SouthEast:
self.regionA = South
elif self.regionA == SouthWest:
self.regionA = West
elif self.regionA == Center:
self.regionA = West
self.__updateEndPoint(self.regionA, True)
# now do the same for itemB
rc = QRectF(xB, yB, rectB.width(), rectB.height())
self.regionB = self.__findPointRegion(rc, xA, yA)
# move some regions to the standard ones
if self.regionB == NorthWest:
self.regionB = North
elif self.regionB == NorthEast:
self.regionB = East
elif self.regionB == SouthEast:
self.regionB = South
elif self.regionB == SouthWest:
self.regionB = West
elif self.regionB == Center:
self.regionB = West
self.__updateEndPoint(self.regionB, False)
def __findPointRegion(self, rect, posX, posY):
"""
Private method to find out, which region of rectangle rect contains
the point (PosX, PosY) and returns the region number.
@param rect rectangle to calculate the region for (QRectF)
@param posX x position of point (float)
@param posY y position of point (float)
@return the calculated region number<br />
West = Region 1<br />
North = Region 2<br />
East = Region 3<br />
South = Region 4<br />
NorthWest = On diagonal 2 between Region 1 and 2<br />
NorthEast = On diagonal 1 between Region 2 and 3<br />
SouthEast = On diagonal 2 between Region 3 and 4<br />
SouthWest = On diagonal 1 between Region4 and 1<br />
Center = On diagonal 1 and On diagonal 2 (the center)<br />
"""
w = rect.width()
h = rect.height()
x = rect.x()
y = rect.y()
slope2 = w / h
slope1 = -slope2
b1 = x + w / 2.0 - y * slope1
b2 = x + w / 2.0 - y * slope2
eval1 = slope1 * posY + b1
eval2 = slope2 * posY + b2
result = NoRegion
# inside region 1
if eval1 > posX and eval2 > posX:
result = West
#inside region 2
elif eval1 > posX and eval2 < posX:
result = North
# inside region 3
elif eval1 < posX and eval2 < posX:
result = East
# inside region 4
elif eval1 < posX and eval2 > posX:
result = South
# inside region 5
elif eval1 == posX and eval2 < posX:
result = NorthWest
# inside region 6
elif eval1 < posX and eval2 == posX:
result = NorthEast
# inside region 7
elif eval1 == posX and eval2 > posX:
result = SouthEast
# inside region 8
elif eval1 > posX and eval2 == posX:
result = SouthWest
# inside region 9
elif eval1 == posX and eval2 == posX:
result = Center
return result
def __updateEndPoint(self, region, isWidgetA):
"""
Private method to update an endpoint.
@param region the region for the endpoint (integer)
@param isWidgetA flag indicating update for itemA is done (boolean)
"""
if region == NoRegion:
return
if isWidgetA:
rect = self.__mapRectFromItem(self.itemA)
else:
rect = self.__mapRectFromItem(self.itemB)
x = rect.x()
y = rect.y()
ww = rect.width()
wh = rect.height()
ch = wh / 2.0
cw = ww / 2.0
if region == West:
px = x
py = y + ch
elif region == North:
px = x + cw
py = y
elif region == East:
px = x + ww
py = y + ch
elif region == South:
px = x + cw
py = y + wh
elif region == Center:
px = x + cw
py = y + wh
if isWidgetA:
self.setStartPoint(px, py)
else:
self.setEndPoint(px, py)
def __findRectIntersectionPoint(self, item, p1, p2):
"""
Private method to find the intersetion point of a line with a
rectangle.
@param item item to check against
@param p1 first point of the line (QPointF)
@param p2 second point of the line (QPointF)
@return the intersection point (QPointF)
"""
rect = self.__mapRectFromItem(item)
lines = [
QLineF(rect.topLeft(), rect.topRight()),
QLineF(rect.topLeft(), rect.bottomLeft()),
QLineF(rect.bottomRight(), rect.bottomLeft()),
QLineF(rect.bottomRight(), rect.topRight())
]
intersectLine = QLineF(p1, p2)
intersectPoint = QPointF(0, 0)
for line in lines:
if intersectLine.intersect(line, intersectPoint) == \
QLineF.BoundedIntersection:
return intersectPoint
return QPointF(-1.0, -1.0)
def __findIntersection(self, p1, p2, p3, p4):
"""
Private method to calculate the intersection point of two lines.
The first line is determined by the points p1 and p2, the second
line by p3 and p4. If the intersection point is not contained in
the segment p1p2, then it returns (-1.0, -1.0).
For the function's internal calculations remember:<br />
QT coordinates start with the point (0,0) as the topleft corner
and x-values increase from left to right and y-values increase
from top to bottom; it means the visible area is quadrant I in
the regular XY coordinate system
<pre>
Quadrant II | Quadrant I
-----------------|-----------------
Quadrant III | Quadrant IV
</pre>
In order for the linear function calculations to work in this method
we must switch x and y values (x values become y values and viceversa)
@param p1 first point of first line (QPointF)
@param p2 second point of first line (QPointF)
@param p3 first point of second line (QPointF)
@param p4 second point of second line (QPointF)
@return the intersection point (QPointF)
"""
x1 = p1.y()
y1 = p1.x()
x2 = p2.y()
y2 = p2.x()
x3 = p3.y()
y3 = p3.x()
x4 = p4.y()
y4 = p4.x()
# line 1 is the line between (x1, y1) and (x2, y2)
# line 2 is the line between (x3, y3) and (x4, y4)
no_line1 = True # it is false, if line 1 is a linear function
no_line2 = True # it is false, if line 2 is a linear function
slope1 = 0.0
slope2 = 0.0
b1 = 0.0
b2 = 0.0
if x2 != x1:
slope1 = (y2 - y1) / (x2 - x1)
b1 = y1 - slope1 * x1
no_line1 = False
if x4 != x3:
slope2 = (y4 - y3) / (x4 - x3)
b2 = y3 - slope2 * x3
no_line2 = False
pt = QPointF()
# if either line is not a function
if no_line1 and no_line2:
# if the lines are not the same one
if x1 != x3:
return QPointF(-1.0, -1.0)
# if the lines are the same ones
if y3 <= y4:
if y3 <= y1 and y1 <= y4:
return QPointF(y1, x1)
else:
return QPointF(y2, x2)
else:
if y4 <= y1 and y1 <= y3:
return QPointF(y1, x1)
else:
return QPointF(y2, x2)
elif no_line1:
pt.setX(slope2 * x1 + b2)
pt.setY(x1)
if y1 >= y2:
if not (y2 <= pt.x() and pt.x() <= y1):
pt.setX(-1.0)
pt.setY(-1.0)
else:
if not (y1 <= pt.x() and pt.x() <= y2):
pt.setX(-1.0)
pt.setY(-1.0)
return pt
elif no_line2:
pt.setX(slope1 * x3 + b1)
pt.setY(x3)
if y3 >= y4:
if not (y4 <= pt.x() and pt.x() <= y3):
pt.setX(-1.0)
pt.setY(-1.0)
else:
if not (y3 <= pt.x() and pt.x() <= y4):
pt.setX(-1.0)
pt.setY(-1.0)
return pt
if slope1 == slope2:
pt.setX(-1.0)
pt.setY(-1.0)
return pt
pt.setY((b2 - b1) / (slope1 - slope2))
pt.setX(slope1 * pt.y() + b1)
# the intersection point must be inside the segment (x1, y1) (x2, y2)
if x2 >= x1 and y2 >= y1:
if not ((x1 <= pt.y() and pt.y() <= x2) and
(y1 <= pt.x() and pt.x() <= y2)):
pt.setX(-1.0)
pt.setY(-1.0)
elif x2 < x1 and y2 >= y1:
if not ((x2 <= pt.y() and pt.y() <= x1) and
(y1 <= pt.x() and pt.x() <= y2)):
pt.setX(-1.0)
pt.setY(-1.0)
elif x2 >= x1 and y2 < y1:
if not ((x1 <= pt.y() and pt.y() <= x2) and
(y2 <= pt.x() and pt.x() <= y1)):
pt.setX(-1.0)
pt.setY(-1.0)
else:
if not ((x2 <= pt.y() and pt.y() <= x1) and
(y2 <= pt.x() and pt.x() <= y1)):
pt.setX(-1.0)
pt.setY(-1.0)
return pt
def widgetMoved(self):
"""
Public method to recalculate the association after a widget was moved.
"""
self.calculateEndingPoints()
def unassociate(self):
"""
Public method to unassociate from the widgets.
"""
self.itemA.removeAssociation(self)
self.itemB.removeAssociation(self)
def buildAssociationItemDataString(self):
"""
Public method to build a string to persist the specific item data.
This string should be built like "attribute=value" with pairs separated
by ", ". value must not contain ", " or newlines.
@return persistence data (string)
"""
entries = [
"src={0}".format(self.itemA.getId()),
"dst={0}".format(self.itemB.getId()),
"type={0}".format(self.assocType),
"topToBottom={0}".format(self.topToBottom)
]
return ", ".join(entries)
@classmethod
def parseAssociationItemDataString(cls, data):
"""
Class method to parse the given persistence data.
@param data persisted data to be parsed (string)
@return tuple with the IDs of the source and destination items,
the association type and a flag indicating to associate from top
to bottom (integer, integer, integer, boolean)
"""
src = -1
dst = -1
assocType = Normal
topToBottom = False
for entry in data.split(", "):
if "=" in entry:
key, value = entry.split("=", 1)
if key == "src":
src = int(value)
elif key == "dst":
dst = int(value)
elif key == "type":
assocType = int(value)
elif key == "topToBottom":
topToBottom = Utilities.toBool(value)
return src, dst, assocType, topToBottom
| gpl-3.0 |
kelvin13/shifty-octocat | pygments/lexers/d.py | 47 | 9530 | # -*- coding: utf-8 -*-
"""
pygments.lexers.d
~~~~~~~~~~~~~~~~~
Lexers for D languages.
:copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.lexer import RegexLexer, include, words
from pygments.token import Text, Comment, Keyword, Name, String, \
Number, Punctuation
__all__ = ['DLexer', 'CrocLexer', 'MiniDLexer']
class DLexer(RegexLexer):
"""
For D source.
.. versionadded:: 1.2
"""
name = 'D'
filenames = ['*.d', '*.di']
aliases = ['d']
mimetypes = ['text/x-dsrc']
tokens = {
'root': [
(r'\n', Text),
(r'\s+', Text),
# (r'\\\n', Text), # line continuations
# Comments
(r'//(.*?)\n', Comment.Single),
(r'/(\\\n)?[*](.|\n)*?[*](\\\n)?/', Comment.Multiline),
(r'/\+', Comment.Multiline, 'nested_comment'),
# Keywords
(words((
'abstract', 'alias', 'align', 'asm', 'assert', 'auto', 'body',
'break', 'case', 'cast', 'catch', 'class', 'const', 'continue',
'debug', 'default', 'delegate', 'delete', 'deprecated', 'do', 'else',
'enum', 'export', 'extern', 'finally', 'final', 'foreach_reverse',
'foreach', 'for', 'function', 'goto', 'if', 'immutable', 'import',
'interface', 'invariant', 'inout', 'in', 'is', 'lazy', 'mixin',
'module', 'new', 'nothrow', 'out', 'override', 'package', 'pragma',
'private', 'protected', 'public', 'pure', 'ref', 'return', 'scope',
'shared', 'static', 'struct', 'super', 'switch', 'synchronized',
'template', 'this', 'throw', 'try', 'typedef', 'typeid', 'typeof',
'union', 'unittest', 'version', 'volatile', 'while', 'with',
'__gshared', '__traits', '__vector', '__parameters'),
suffix=r'\b'),
Keyword),
(words((
'bool', 'byte', 'cdouble', 'cent', 'cfloat', 'char', 'creal',
'dchar', 'double', 'float', 'idouble', 'ifloat', 'int', 'ireal',
'long', 'real', 'short', 'ubyte', 'ucent', 'uint', 'ulong',
'ushort', 'void', 'wchar'), suffix=r'\b'),
Keyword.Type),
(r'(false|true|null)\b', Keyword.Constant),
(words((
'__FILE__', '__MODULE__', '__LINE__', '__FUNCTION__', '__PRETTY_FUNCTION__'
'', '__DATE__', '__EOF__', '__TIME__', '__TIMESTAMP__', '__VENDOR__',
'__VERSION__'), suffix=r'\b'),
Keyword.Pseudo),
(r'macro\b', Keyword.Reserved),
(r'(string|wstring|dstring|size_t|ptrdiff_t)\b', Name.Builtin),
# FloatLiteral
# -- HexFloat
(r'0[xX]([0-9a-fA-F_]*\.[0-9a-fA-F_]+|[0-9a-fA-F_]+)'
r'[pP][+\-]?[0-9_]+[fFL]?[i]?', Number.Float),
# -- DecimalFloat
(r'[0-9_]+(\.[0-9_]+[eE][+\-]?[0-9_]+|'
r'\.[0-9_]*|[eE][+\-]?[0-9_]+)[fFL]?[i]?', Number.Float),
(r'\.(0|[1-9][0-9_]*)([eE][+\-]?[0-9_]+)?[fFL]?[i]?', Number.Float),
# IntegerLiteral
# -- Binary
(r'0[Bb][01_]+', Number.Bin),
# -- Octal
(r'0[0-7_]+', Number.Oct),
# -- Hexadecimal
(r'0[xX][0-9a-fA-F_]+', Number.Hex),
# -- Decimal
(r'(0|[1-9][0-9_]*)([LUu]|Lu|LU|uL|UL)?', Number.Integer),
# CharacterLiteral
(r"""'(\\['"?\\abfnrtv]|\\x[0-9a-fA-F]{2}|\\[0-7]{1,3}"""
r"""|\\u[0-9a-fA-F]{4}|\\U[0-9a-fA-F]{8}|\\&\w+;|.)'""",
String.Char),
# StringLiteral
# -- WysiwygString
(r'r"[^"]*"[cwd]?', String),
# -- AlternateWysiwygString
(r'`[^`]*`[cwd]?', String),
# -- DoubleQuotedString
(r'"(\\\\|\\"|[^"])*"[cwd]?', String),
# -- EscapeSequence
(r"\\(['\"?\\abfnrtv]|x[0-9a-fA-F]{2}|[0-7]{1,3}"
r"|u[0-9a-fA-F]{4}|U[0-9a-fA-F]{8}|&\w+;)",
String),
# -- HexString
(r'x"[0-9a-fA-F_\s]*"[cwd]?', String),
# -- DelimitedString
(r'q"\[', String, 'delimited_bracket'),
(r'q"\(', String, 'delimited_parenthesis'),
(r'q"<', String, 'delimited_angle'),
(r'q"\{', String, 'delimited_curly'),
(r'q"([a-zA-Z_]\w*)\n.*?\n\1"', String),
(r'q"(.).*?\1"', String),
# -- TokenString
(r'q\{', String, 'token_string'),
# Attributes
(r'@([a-zA-Z_]\w*)?', Name.Decorator),
# Tokens
(r'(~=|\^=|%=|\*=|==|!>=|!<=|!<>=|!<>|!<|!>|!=|>>>=|>>>|>>=|>>|>='
r'|<>=|<>|<<=|<<|<=|\+\+|\+=|--|-=|\|\||\|=|&&|&=|\.\.\.|\.\.|/=)'
r'|[/.&|\-+<>!()\[\]{}?,;:$=*%^~]', Punctuation),
# Identifier
(r'[a-zA-Z_]\w*', Name),
# Line
(r'#line\s.*\n', Comment.Special),
],
'nested_comment': [
(r'[^+/]+', Comment.Multiline),
(r'/\+', Comment.Multiline, '#push'),
(r'\+/', Comment.Multiline, '#pop'),
(r'[+/]', Comment.Multiline),
],
'token_string': [
(r'\{', Punctuation, 'token_string_nest'),
(r'\}', String, '#pop'),
include('root'),
],
'token_string_nest': [
(r'\{', Punctuation, '#push'),
(r'\}', Punctuation, '#pop'),
include('root'),
],
'delimited_bracket': [
(r'[^\[\]]+', String),
(r'\[', String, 'delimited_inside_bracket'),
(r'\]"', String, '#pop'),
],
'delimited_inside_bracket': [
(r'[^\[\]]+', String),
(r'\[', String, '#push'),
(r'\]', String, '#pop'),
],
'delimited_parenthesis': [
(r'[^()]+', String),
(r'\(', String, 'delimited_inside_parenthesis'),
(r'\)"', String, '#pop'),
],
'delimited_inside_parenthesis': [
(r'[^()]+', String),
(r'\(', String, '#push'),
(r'\)', String, '#pop'),
],
'delimited_angle': [
(r'[^<>]+', String),
(r'<', String, 'delimited_inside_angle'),
(r'>"', String, '#pop'),
],
'delimited_inside_angle': [
(r'[^<>]+', String),
(r'<', String, '#push'),
(r'>', String, '#pop'),
],
'delimited_curly': [
(r'[^{}]+', String),
(r'\{', String, 'delimited_inside_curly'),
(r'\}"', String, '#pop'),
],
'delimited_inside_curly': [
(r'[^{}]+', String),
(r'\{', String, '#push'),
(r'\}', String, '#pop'),
],
}
class CrocLexer(RegexLexer):
"""
For `Croc <http://jfbillingsley.com/croc>`_ source.
"""
name = 'Croc'
filenames = ['*.croc']
aliases = ['croc']
mimetypes = ['text/x-crocsrc']
tokens = {
'root': [
(r'\n', Text),
(r'\s+', Text),
# Comments
(r'//(.*?)\n', Comment.Single),
(r'/\*', Comment.Multiline, 'nestedcomment'),
# Keywords
(words((
'as', 'assert', 'break', 'case', 'catch', 'class', 'continue',
'default', 'do', 'else', 'finally', 'for', 'foreach', 'function',
'global', 'namespace', 'if', 'import', 'in', 'is', 'local',
'module', 'return', 'scope', 'super', 'switch', 'this', 'throw',
'try', 'vararg', 'while', 'with', 'yield'), suffix=r'\b'),
Keyword),
(r'(false|true|null)\b', Keyword.Constant),
# FloatLiteral
(r'([0-9][0-9_]*)(?=[.eE])(\.[0-9][0-9_]*)?([eE][+\-]?[0-9_]+)?',
Number.Float),
# IntegerLiteral
# -- Binary
(r'0[bB][01][01_]*', Number.Bin),
# -- Hexadecimal
(r'0[xX][0-9a-fA-F][0-9a-fA-F_]*', Number.Hex),
# -- Decimal
(r'([0-9][0-9_]*)(?![.eE])', Number.Integer),
# CharacterLiteral
(r"""'(\\['"\\nrt]|\\x[0-9a-fA-F]{2}|\\[0-9]{1,3}"""
r"""|\\u[0-9a-fA-F]{4}|\\U[0-9a-fA-F]{8}|.)'""",
String.Char),
# StringLiteral
# -- WysiwygString
(r'@"(""|[^"])*"', String),
(r'@`(``|[^`])*`', String),
(r"@'(''|[^'])*'", String),
# -- DoubleQuotedString
(r'"(\\\\|\\"|[^"])*"', String),
# Tokens
(r'(~=|\^=|%=|\*=|==|!=|>>>=|>>>|>>=|>>|>=|<=>|\?=|-\>'
r'|<<=|<<|<=|\+\+|\+=|--|-=|\|\||\|=|&&|&=|\.\.|/=)'
r'|[-/.&$@|\+<>!()\[\]{}?,;:=*%^~#\\]', Punctuation),
# Identifier
(r'[a-zA-Z_]\w*', Name),
],
'nestedcomment': [
(r'[^*/]+', Comment.Multiline),
(r'/\*', Comment.Multiline, '#push'),
(r'\*/', Comment.Multiline, '#pop'),
(r'[*/]', Comment.Multiline),
],
}
class MiniDLexer(CrocLexer):
"""
For MiniD source. MiniD is now known as Croc.
"""
name = 'MiniD'
filenames = [] # don't lex .md as MiniD, reserve for Markdown
aliases = ['minid']
mimetypes = ['text/x-minidsrc']
| gpl-3.0 |
makaimc/mms-picture-roulette | roulette/views.py | 1 | 1859 | import json
import random
import requests
from flask import request
from twilio.rest import TwilioRestClient
from . import app
from config import FLICKR_API_KEY
client = TwilioRestClient()
@app.route('/', methods=['GET', 'POST'])
def send_image():
if request.method == 'GET':
return 'The deployment worked! Now copy your browser URL into the' + \
' Twilio message text box for your phone number.'
sender_number = request.form.get('From', '')
twilio_number = request.form.get('To', '')
tag = request.form.get('Body', '')
image_url, msg = _get_flickr_image(tag)
_send_mms_twiml(image_url, msg, sender_number, twilio_number)
return 'ok'
def _get_flickr_image(tag):
flickr_api_call = "https://api.flickr.com/services/rest/" + \
"?method=flickr.photos.search&api_key=%s&tags=%s&per_page=25&" + \
"format=json&nojsoncallback=1"
try:
response = requests.get(flickr_api_call % (FLICKR_API_KEY, tag))
json_response = json.loads(response.content)
random_photo_number = random.randint(0, 25)
photo_json = json_response['photos']['photo'][random_photo_number]
msg = "Here's a picture of %s. Maybe." % tag
image_url = "https://farm" + str(photo_json['farm']) + \
".staticflickr.com/" + str(photo_json['server']) + "/" + \
str(photo_json['id']) + "_" + photo_json['secret'] + ".jpg"
except:
msg = "Sorry, we couldn't pull an image for that word, " + \
"here's a dinosaur instead!"
image_url = "https://farm1.staticflickr.com/46/" + \
"154877897_a299d80baa_b_d.jpg"
return image_url, msg
def _send_mms_twiml(image_url, msg, sender_number, twilio_number):
client.messages.create(to=sender_number, from_=twilio_number,
body=msg, media_url=image_url)
| bsd-3-clause |
StefanRijnhart/odoo | addons/sale_mrp/tests/test_move_explode.py | 149 | 3045 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Business Applications
# Copyright (c) 2012-TODAY OpenERP S.A. <http://openerp.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.tests import common
class TestMoveExplode(common.TransactionCase):
def setUp(self):
super(TestMoveExplode, self).setUp()
cr, uid = self.cr, self.uid
# Usefull models
self.ir_model_data = self.registry('ir.model.data')
self.sale_order_line = self.registry('sale.order.line')
self.sale_order = self.registry('sale.order')
self.mrp_bom = self.registry('mrp.bom')
#product that has a phantom bom
self.product_bom_id = self.ir_model_data.get_object_reference(cr, uid, 'product', 'product_product_3')[1]
#bom with that product
self.bom_id = self.ir_model_data.get_object_reference(cr, uid, 'mrp', 'mrp_bom_9')[1]
#partner agrolait
self.partner_id = self.ir_model_data.get_object_reference(cr, uid, 'base', 'res_partner_1')[1]
def test_00_sale_move_explode(self):
"""check that when creating a sale order with a product that has a phantom BoM, move explode into content of the
BoM"""
cr, uid, context = self.cr, self.uid, {}
#create sale order with one sale order line containing product with a phantom bom
so_id = self.sale_order.create(cr, uid, vals={'partner_id': self.partner_id}, context=context)
self.sale_order_line.create(cr, uid, values={'order_id': so_id, 'product_id': self.product_bom_id, 'product_uom_qty': 1}, context=context)
#confirm sale order
self.sale_order.action_button_confirm(cr, uid, [so_id], context=context)
#get all move associated to that sale_order
browse_move_ids = self.sale_order.browse(cr, uid, so_id, context=context).picking_ids[0].move_lines
move_ids = [x.id for x in browse_move_ids]
#we should have same amount of move as the component in the phatom bom
bom = self.mrp_bom.browse(cr, uid, self.bom_id, context=context)
bom_component_length = self.mrp_bom._bom_explode(cr, uid, bom, self.product_bom_id, 1, [])
self.assertEqual(len(move_ids), len(bom_component_length[0]))
| agpl-3.0 |
manipopopo/tensorflow | tensorflow/contrib/boosted_trees/python/ops/boosted_trees_ops_loader.py | 79 | 1283 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Loads the _boosted_trees_ops.so when the binary is not statically linked."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.util import loader
from tensorflow.python.framework import errors
from tensorflow.python.platform import resource_loader
# Conditionally load ops, they might already be statically linked in.
try:
loader.load_op_library(
resource_loader.get_path_to_datafile('_boosted_trees_ops.so'))
except (errors.NotFoundError, IOError):
print('Error loading _boosted_trees_ops.so')
| apache-2.0 |
FearNGreed/unbroken | contrib/spendfrom/spendfrom.py | 2 | 10053 | #!/usr/bin/env python
#
# Use the raw transactions API to spend bitcoins received on particular addresses,
# and send any change back to that same address.
#
# Example usage:
# spendfrom.py # Lists available funds
# spendfrom.py --from=ADDRESS --to=ADDRESS --amount=11.00
#
# Assumes it will talk to a bitcoind or Bitcoin-Qt running
# on localhost.
#
# Depends on jsonrpc
#
from decimal import *
import getpass
import math
import os
import os.path
import platform
import sys
import time
from jsonrpc import ServiceProxy, json
BASE_FEE=Decimal("0.001")
def check_json_precision():
"""Make sure json library being used does not lose precision converting BTC values"""
n = Decimal("20000000.00000003")
satoshis = int(json.loads(json.dumps(float(n)))*1.0e8)
if satoshis != 2000000000000003:
raise RuntimeError("JSON encode/decode loses precision")
def determine_db_dir():
"""Return the default location of the bitcoin data directory"""
if platform.system() == "Darwin":
return os.path.expanduser("~/Library/Application Support/Bitcoin/")
elif platform.system() == "Windows":
return os.path.join(os.environ['APPDATA'], "Bitcoin")
return os.path.expanduser("~/.bitcoin")
def read_bitcoin_config(dbdir):
"""Read the bitcoin.conf file from dbdir, returns dictionary of settings"""
from ConfigParser import SafeConfigParser
class FakeSecHead(object):
def __init__(self, fp):
self.fp = fp
self.sechead = '[all]\n'
def readline(self):
if self.sechead:
try: return self.sechead
finally: self.sechead = None
else:
s = self.fp.readline()
if s.find('#') != -1:
s = s[0:s.find('#')].strip() +"\n"
return s
config_parser = SafeConfigParser()
config_parser.readfp(FakeSecHead(open(os.path.join(dbdir, "bitcoin.conf"))))
return dict(config_parser.items("all"))
def connect_JSON(config):
"""Connect to a bitcoin JSON-RPC server"""
testnet = config.get('testnet', '0')
testnet = (int(testnet) > 0) # 0/1 in config file, convert to True/False
if not 'rpcport' in config:
config['rpcport'] = 19546 if testnet else 9546
connect = "http://%s:%s@127.0.0.1:%s"%(config['rpcuser'], config['rpcpassword'], config['rpcport'])
try:
result = ServiceProxy(connect)
# ServiceProxy is lazy-connect, so send an RPC command mostly to catch connection errors,
# but also make sure the bitcoind we're talking to is/isn't testnet:
if result.getmininginfo()['testnet'] != testnet:
sys.stderr.write("RPC server at "+connect+" testnet setting mismatch\n")
sys.exit(1)
return result
except:
sys.stderr.write("Error connecting to RPC server at "+connect+"\n")
sys.exit(1)
def unlock_wallet(bitcoind):
info = bitcoind.getinfo()
if 'unlocked_until' not in info:
return True # wallet is not encrypted
t = int(info['unlocked_until'])
if t <= time.time():
try:
passphrase = getpass.getpass("Wallet is locked; enter passphrase: ")
bitcoind.walletpassphrase(passphrase, 5)
except:
sys.stderr.write("Wrong passphrase\n")
info = bitcoind.getinfo()
return int(info['unlocked_until']) > time.time()
def list_available(bitcoind):
address_summary = dict()
address_to_account = dict()
for info in bitcoind.listreceivedbyaddress(0):
address_to_account[info["address"]] = info["account"]
unspent = bitcoind.listunspent(0)
for output in unspent:
# listunspent doesn't give addresses, so:
rawtx = bitcoind.getrawtransaction(output['txid'], 1)
vout = rawtx["vout"][output['vout']]
pk = vout["scriptPubKey"]
# This code only deals with ordinary pay-to-bitcoin-address
# or pay-to-script-hash outputs right now; anything exotic is ignored.
if pk["type"] != "pubkeyhash" and pk["type"] != "scripthash":
continue
address = pk["addresses"][0]
if address in address_summary:
address_summary[address]["total"] += vout["value"]
address_summary[address]["outputs"].append(output)
else:
address_summary[address] = {
"total" : vout["value"],
"outputs" : [output],
"account" : address_to_account.get(address, "")
}
return address_summary
def select_coins(needed, inputs):
# Feel free to improve this, this is good enough for my simple needs:
outputs = []
have = Decimal("0.0")
n = 0
while have < needed and n < len(inputs):
outputs.append({ "txid":inputs[n]["txid"], "vout":inputs[n]["vout"]})
have += inputs[n]["amount"]
n += 1
return (outputs, have-needed)
def create_tx(bitcoind, fromaddresses, toaddress, amount, fee):
all_coins = list_available(bitcoind)
total_available = Decimal("0.0")
needed = amount+fee
potential_inputs = []
for addr in fromaddresses:
if addr not in all_coins:
continue
potential_inputs.extend(all_coins[addr]["outputs"])
total_available += all_coins[addr]["total"]
if total_available < needed:
sys.stderr.write("Error, only %f BTC available, need %f\n"%(total_available, needed));
sys.exit(1)
#
# Note:
# Python's json/jsonrpc modules have inconsistent support for Decimal numbers.
# Instead of wrestling with getting json.dumps() (used by jsonrpc) to encode
# Decimals, I'm casting amounts to float before sending them to bitcoind.
#
outputs = { toaddress : float(amount) }
(inputs, change_amount) = select_coins(needed, potential_inputs)
if change_amount > BASE_FEE: # don't bother with zero or tiny change
change_address = fromaddresses[-1]
if change_address in outputs:
outputs[change_address] += float(change_amount)
else:
outputs[change_address] = float(change_amount)
rawtx = bitcoind.createrawtransaction(inputs, outputs)
signed_rawtx = bitcoind.signrawtransaction(rawtx)
if not signed_rawtx["complete"]:
sys.stderr.write("signrawtransaction failed\n")
sys.exit(1)
txdata = signed_rawtx["hex"]
return txdata
def compute_amount_in(bitcoind, txinfo):
result = Decimal("0.0")
for vin in txinfo['vin']:
in_info = bitcoind.getrawtransaction(vin['txid'], 1)
vout = in_info['vout'][vin['vout']]
result = result + vout['value']
return result
def compute_amount_out(txinfo):
result = Decimal("0.0")
for vout in txinfo['vout']:
result = result + vout['value']
return result
def sanity_test_fee(bitcoind, txdata_hex, max_fee):
class FeeError(RuntimeError):
pass
try:
txinfo = bitcoind.decoderawtransaction(txdata_hex)
total_in = compute_amount_in(bitcoind, txinfo)
total_out = compute_amount_out(txinfo)
if total_in-total_out > max_fee:
raise FeeError("Rejecting transaction, unreasonable fee of "+str(total_in-total_out))
tx_size = len(txdata_hex)/2
kb = tx_size/1000 # integer division rounds down
if kb > 1 and fee < BASE_FEE:
raise FeeError("Rejecting no-fee transaction, larger than 1000 bytes")
if total_in < 0.01 and fee < BASE_FEE:
raise FeeError("Rejecting no-fee, tiny-amount transaction")
# Exercise for the reader: compute transaction priority, and
# warn if this is a very-low-priority transaction
except FeeError as err:
sys.stderr.write((str(err)+"\n"))
sys.exit(1)
def main():
import optparse
parser = optparse.OptionParser(usage="%prog [options]")
parser.add_option("--from", dest="fromaddresses", default=None,
help="addresses to get bitcoins from")
parser.add_option("--to", dest="to", default=None,
help="address to get send bitcoins to")
parser.add_option("--amount", dest="amount", default=None,
help="amount to send")
parser.add_option("--fee", dest="fee", default="0.0",
help="fee to include")
parser.add_option("--datadir", dest="datadir", default=determine_db_dir(),
help="location of bitcoin.conf file with RPC username/password (default: %default)")
parser.add_option("--testnet", dest="testnet", default=False, action="store_true",
help="Use the test network")
parser.add_option("--dry_run", dest="dry_run", default=False, action="store_true",
help="Don't broadcast the transaction, just create and print the transaction data")
(options, args) = parser.parse_args()
check_json_precision()
config = read_bitcoin_config(options.datadir)
if options.testnet: config['testnet'] = True
bitcoind = connect_JSON(config)
if options.amount is None:
address_summary = list_available(bitcoind)
for address,info in address_summary.iteritems():
n_transactions = len(info['outputs'])
if n_transactions > 1:
print("%s %.8f %s (%d transactions)"%(address, info['total'], info['account'], n_transactions))
else:
print("%s %.8f %s"%(address, info['total'], info['account']))
else:
fee = Decimal(options.fee)
amount = Decimal(options.amount)
while unlock_wallet(bitcoind) == False:
pass # Keep asking for passphrase until they get it right
txdata = create_tx(bitcoind, options.fromaddresses.split(","), options.to, amount, fee)
sanity_test_fee(bitcoind, txdata, amount*Decimal("0.01"))
if options.dry_run:
print(txdata)
else:
txid = bitcoind.sendrawtransaction(txdata)
print(txid)
if __name__ == '__main__':
main()
| mit |
Azure/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2020_06_01/operations/_private_dns_zone_groups_operations.py | 1 | 22889 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpRequest, HttpResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.arm_polling import ARMPolling
from .. import models as _models
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
class PrivateDnsZoneGroupsOperations(object):
"""PrivateDnsZoneGroupsOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.network.v2020_06_01.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
def _delete_initial(
self,
resource_group_name, # type: str
private_endpoint_name, # type: str
private_dns_zone_group_name, # type: str
**kwargs # type: Any
):
# type: (...) -> None
cls = kwargs.pop('cls', None) # type: ClsType[None]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-06-01"
accept = "application/json"
# Construct URL
url = self._delete_initial.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'privateEndpointName': self._serialize.url("private_endpoint_name", private_endpoint_name, 'str'),
'privateDnsZoneGroupName': self._serialize.url("private_dns_zone_group_name", private_dns_zone_group_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.delete(url, query_parameters, header_parameters)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateEndpoints/{privateEndpointName}/privateDnsZoneGroups/{privateDnsZoneGroupName}'} # type: ignore
def begin_delete(
self,
resource_group_name, # type: str
private_endpoint_name, # type: str
private_dns_zone_group_name, # type: str
**kwargs # type: Any
):
# type: (...) -> LROPoller[None]
"""Deletes the specified private dns zone group.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param private_endpoint_name: The name of the private endpoint.
:type private_endpoint_name: str
:param private_dns_zone_group_name: The name of the private dns zone group.
:type private_dns_zone_group_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: Pass in True if you'd like the ARMPolling polling method,
False for no polling, or your own initialized polling object for a personal polling strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType[None]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = self._delete_initial(
resource_group_name=resource_group_name,
private_endpoint_name=private_endpoint_name,
private_dns_zone_group_name=private_dns_zone_group_name,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
if cls:
return cls(pipeline_response, None, {})
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'privateEndpointName': self._serialize.url("private_endpoint_name", private_endpoint_name, 'str'),
'privateDnsZoneGroupName': self._serialize.url("private_dns_zone_group_name", private_dns_zone_group_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = NoPolling()
else: polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateEndpoints/{privateEndpointName}/privateDnsZoneGroups/{privateDnsZoneGroupName}'} # type: ignore
def get(
self,
resource_group_name, # type: str
private_endpoint_name, # type: str
private_dns_zone_group_name, # type: str
**kwargs # type: Any
):
# type: (...) -> "_models.PrivateDnsZoneGroup"
"""Gets the private dns zone group resource by specified private dns zone group name.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param private_endpoint_name: The name of the private endpoint.
:type private_endpoint_name: str
:param private_dns_zone_group_name: The name of the private dns zone group.
:type private_dns_zone_group_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: PrivateDnsZoneGroup, or the result of cls(response)
:rtype: ~azure.mgmt.network.v2020_06_01.models.PrivateDnsZoneGroup
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateDnsZoneGroup"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-06-01"
accept = "application/json"
# Construct URL
url = self.get.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'privateEndpointName': self._serialize.url("private_endpoint_name", private_endpoint_name, 'str'),
'privateDnsZoneGroupName': self._serialize.url("private_dns_zone_group_name", private_dns_zone_group_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.get(url, query_parameters, header_parameters)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize('PrivateDnsZoneGroup', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateEndpoints/{privateEndpointName}/privateDnsZoneGroups/{privateDnsZoneGroupName}'} # type: ignore
def _create_or_update_initial(
self,
resource_group_name, # type: str
private_endpoint_name, # type: str
private_dns_zone_group_name, # type: str
parameters, # type: "_models.PrivateDnsZoneGroup"
**kwargs # type: Any
):
# type: (...) -> "_models.PrivateDnsZoneGroup"
cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateDnsZoneGroup"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-06-01"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
# Construct URL
url = self._create_or_update_initial.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'privateEndpointName': self._serialize.url("private_endpoint_name", private_endpoint_name, 'str'),
'privateDnsZoneGroupName': self._serialize.url("private_dns_zone_group_name", private_dns_zone_group_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
body_content = self._serialize.body(parameters, 'PrivateDnsZoneGroup')
body_content_kwargs['content'] = body_content
request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize('PrivateDnsZoneGroup', pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize('PrivateDnsZoneGroup', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateEndpoints/{privateEndpointName}/privateDnsZoneGroups/{privateDnsZoneGroupName}'} # type: ignore
def begin_create_or_update(
self,
resource_group_name, # type: str
private_endpoint_name, # type: str
private_dns_zone_group_name, # type: str
parameters, # type: "_models.PrivateDnsZoneGroup"
**kwargs # type: Any
):
# type: (...) -> LROPoller["_models.PrivateDnsZoneGroup"]
"""Creates or updates a private dns zone group in the specified private endpoint.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param private_endpoint_name: The name of the private endpoint.
:type private_endpoint_name: str
:param private_dns_zone_group_name: The name of the private dns zone group.
:type private_dns_zone_group_name: str
:param parameters: Parameters supplied to the create or update private dns zone group
operation.
:type parameters: ~azure.mgmt.network.v2020_06_01.models.PrivateDnsZoneGroup
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: Pass in True if you'd like the ARMPolling polling method,
False for no polling, or your own initialized polling object for a personal polling strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of LROPoller that returns either PrivateDnsZoneGroup or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.network.v2020_06_01.models.PrivateDnsZoneGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateDnsZoneGroup"]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = self._create_or_update_initial(
resource_group_name=resource_group_name,
private_endpoint_name=private_endpoint_name,
private_dns_zone_group_name=private_dns_zone_group_name,
parameters=parameters,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize('PrivateDnsZoneGroup', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'privateEndpointName': self._serialize.url("private_endpoint_name", private_endpoint_name, 'str'),
'privateDnsZoneGroupName': self._serialize.url("private_dns_zone_group_name", private_dns_zone_group_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = NoPolling()
else: polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateEndpoints/{privateEndpointName}/privateDnsZoneGroups/{privateDnsZoneGroupName}'} # type: ignore
def list(
self,
private_endpoint_name, # type: str
resource_group_name, # type: str
**kwargs # type: Any
):
# type: (...) -> Iterable["_models.PrivateDnsZoneGroupListResult"]
"""Gets all private dns zone groups in a private endpoint.
:param private_endpoint_name: The name of the private endpoint.
:type private_endpoint_name: str
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either PrivateDnsZoneGroupListResult or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.network.v2020_06_01.models.PrivateDnsZoneGroupListResult]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateDnsZoneGroupListResult"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-06-01"
accept = "application/json"
def prepare_request(next_link=None):
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.list.metadata['url'] # type: ignore
path_format_arguments = {
'privateEndpointName': self._serialize.url("private_endpoint_name", private_endpoint_name, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {} # type: Dict[str, Any]
request = self._client.get(url, query_parameters, header_parameters)
return request
def extract_data(pipeline_response):
deserialized = self._deserialize('PrivateDnsZoneGroupListResult', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
error = self._deserialize.failsafe_deserialize(_models.Error, response)
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(
get_next, extract_data
)
list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateEndpoints/{privateEndpointName}/privateDnsZoneGroups'} # type: ignore
| mit |
rokuz/omim | 3party/osrm/osrm-backend/cmake/cmake_options_script.py | 80 | 1514 | # Based on @berenm's pull request https://github.com/quarnster/SublimeClang/pull/135
# Create the database with cmake with for example: cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=ON ..
# or you could have set(CMAKE_EXPORT_COMPILE_COMMANDS ON) in your CMakeLists.txt
# Usage within SublimeClang:
# "sublimeclang_options_script": "python ${home}/code/cmake_options_script.py ${project_path:build}/compile_commands.json",
import re
import os
import os.path
import pickle
import sys
import json
compilation_database_pattern = re.compile('(?<=\s)-[DIOUWfgs][^=\s]+(?:=\\"[^"]+\\"|=[^"]\S+)?')
def load_db(filename):
compilation_database = {}
with open(filename) as compilation_database_file:
compilation_database_entries = json.load(compilation_database_file)
total = len(compilation_database_entries)
entry = 0
for compilation_entry in compilation_database_entries:
entry = entry + 1
compilation_database[compilation_entry["file"]] = [ p.strip() for p in compilation_database_pattern.findall(compilation_entry["command"]) ]
return compilation_database
scriptpath = os.path.dirname(os.path.abspath(sys.argv[1]))
cache_file = "%s/cached_options.txt" % (scriptpath)
db = None
if os.access(cache_file, os.R_OK) == 0:
db = load_db(sys.argv[1])
f = open(cache_file, "wb")
pickle.dump(db, f)
f.close()
else:
f = open(cache_file)
db = pickle.load(f)
f.close()
if db and sys.argv[2] in db:
for option in db[sys.argv[2]]:
print option
| apache-2.0 |
jeremiahmarks/sl4a | python/src/Demo/curses/life.py | 43 | 7349 | #!/usr/bin/env python
# life.py -- A curses-based version of Conway's Game of Life.
# Contributed by AMK
#
# An empty board will be displayed, and the following commands are available:
# E : Erase the board
# R : Fill the board randomly
# S : Step for a single generation
# C : Update continuously until a key is struck
# Q : Quit
# Cursor keys : Move the cursor around the board
# Space or Enter : Toggle the contents of the cursor's position
#
# TODO :
# Support the mouse
# Use colour if available
# Make board updates faster
#
import random, string, traceback
import curses
class LifeBoard:
"""Encapsulates a Life board
Attributes:
X,Y : horizontal and vertical size of the board
state : dictionary mapping (x,y) to 0 or 1
Methods:
display(update_board) -- If update_board is true, compute the
next generation. Then display the state
of the board and refresh the screen.
erase() -- clear the entire board
makeRandom() -- fill the board randomly
set(y,x) -- set the given cell to Live; doesn't refresh the screen
toggle(y,x) -- change the given cell from live to dead, or vice
versa, and refresh the screen display
"""
def __init__(self, scr, char=ord('*')):
"""Create a new LifeBoard instance.
scr -- curses screen object to use for display
char -- character used to render live cells (default: '*')
"""
self.state = {}
self.scr = scr
Y, X = self.scr.getmaxyx()
self.X, self.Y = X-2, Y-2-1
self.char = char
self.scr.clear()
# Draw a border around the board
border_line = '+'+(self.X*'-')+'+'
self.scr.addstr(0, 0, border_line)
self.scr.addstr(self.Y+1,0, border_line)
for y in range(0, self.Y):
self.scr.addstr(1+y, 0, '|')
self.scr.addstr(1+y, self.X+1, '|')
self.scr.refresh()
def set(self, y, x):
"""Set a cell to the live state"""
if x<0 or self.X<=x or y<0 or self.Y<=y:
raise ValueError, "Coordinates out of range %i,%i"% (y,x)
self.state[x,y] = 1
def toggle(self, y, x):
"""Toggle a cell's state between live and dead"""
if x<0 or self.X<=x or y<0 or self.Y<=y:
raise ValueError, "Coordinates out of range %i,%i"% (y,x)
if self.state.has_key( (x,y) ):
del self.state[x,y]
self.scr.addch(y+1, x+1, ' ')
else:
self.state[x,y] = 1
self.scr.addch(y+1, x+1, self.char)
self.scr.refresh()
def erase(self):
"""Clear the entire board and update the board display"""
self.state = {}
self.display(update_board=False)
def display(self, update_board=True):
"""Display the whole board, optionally computing one generation"""
M,N = self.X, self.Y
if not update_board:
for i in range(0, M):
for j in range(0, N):
if self.state.has_key( (i,j) ):
self.scr.addch(j+1, i+1, self.char)
else:
self.scr.addch(j+1, i+1, ' ')
self.scr.refresh()
return
d = {}
self.boring = 1
for i in range(0, M):
L = range( max(0, i-1), min(M, i+2) )
for j in range(0, N):
s = 0
live = self.state.has_key( (i,j) )
for k in range( max(0, j-1), min(N, j+2) ):
for l in L:
if self.state.has_key( (l,k) ):
s += 1
s -= live
if s == 3:
# Birth
d[i,j] = 1
self.scr.addch(j+1, i+1, self.char)
if not live: self.boring = 0
elif s == 2 and live: d[i,j] = 1 # Survival
elif live:
# Death
self.scr.addch(j+1, i+1, ' ')
self.boring = 0
self.state = d
self.scr.refresh()
def makeRandom(self):
"Fill the board with a random pattern"
self.state = {}
for i in range(0, self.X):
for j in range(0, self.Y):
if random.random() > 0.5:
self.set(j,i)
def erase_menu(stdscr, menu_y):
"Clear the space where the menu resides"
stdscr.move(menu_y, 0)
stdscr.clrtoeol()
stdscr.move(menu_y+1, 0)
stdscr.clrtoeol()
def display_menu(stdscr, menu_y):
"Display the menu of possible keystroke commands"
erase_menu(stdscr, menu_y)
stdscr.addstr(menu_y, 4,
'Use the cursor keys to move, and space or Enter to toggle a cell.')
stdscr.addstr(menu_y+1, 4,
'E)rase the board, R)andom fill, S)tep once or C)ontinuously, Q)uit')
def keyloop(stdscr):
# Clear the screen and display the menu of keys
stdscr.clear()
stdscr_y, stdscr_x = stdscr.getmaxyx()
menu_y = (stdscr_y-3)-1
display_menu(stdscr, menu_y)
# Allocate a subwindow for the Life board and create the board object
subwin = stdscr.subwin(stdscr_y-3, stdscr_x, 0, 0)
board = LifeBoard(subwin, char=ord('*'))
board.display(update_board=False)
# xpos, ypos are the cursor's position
xpos, ypos = board.X//2, board.Y//2
# Main loop:
while (1):
stdscr.move(1+ypos, 1+xpos) # Move the cursor
c = stdscr.getch() # Get a keystroke
if 0<c<256:
c = chr(c)
if c in ' \n':
board.toggle(ypos, xpos)
elif c in 'Cc':
erase_menu(stdscr, menu_y)
stdscr.addstr(menu_y, 6, ' Hit any key to stop continuously '
'updating the screen.')
stdscr.refresh()
# Activate nodelay mode; getch() will return -1
# if no keystroke is available, instead of waiting.
stdscr.nodelay(1)
while (1):
c = stdscr.getch()
if c != -1:
break
stdscr.addstr(0,0, '/')
stdscr.refresh()
board.display()
stdscr.addstr(0,0, '+')
stdscr.refresh()
stdscr.nodelay(0) # Disable nodelay mode
display_menu(stdscr, menu_y)
elif c in 'Ee':
board.erase()
elif c in 'Qq':
break
elif c in 'Rr':
board.makeRandom()
board.display(update_board=False)
elif c in 'Ss':
board.display()
else: pass # Ignore incorrect keys
elif c == curses.KEY_UP and ypos>0: ypos -= 1
elif c == curses.KEY_DOWN and ypos<board.Y-1: ypos += 1
elif c == curses.KEY_LEFT and xpos>0: xpos -= 1
elif c == curses.KEY_RIGHT and xpos<board.X-1: xpos += 1
else:
# Ignore incorrect keys
pass
def main(stdscr):
keyloop(stdscr) # Enter the main loop
if __name__ == '__main__':
curses.wrapper(main)
| apache-2.0 |
1200wd/1200wd_addons | account_margin_actual_cost/report/account_invoice_report.py | 1 | 2292 | # -*- coding: utf-8 -*-
#
# Account Invoice - Actual Costs and Margins
# © 1200 WebDevelopment <http://1200wd.com/>
# 2016 November
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from openerp import models, fields, api
class AccountInvoiceReport(models.Model):
_inherit = "account.invoice.report"
actual_cost_total = fields.Float(string="Total Actual Cost", readonly=True,
help="Total Actual Costs of invoices")
margin_avg = fields.Float(string="Margin % Average", readonly=True, digits=(16, 1),
help="Average margin on invoices", group_operator="avg")
def _select(self):
select_str = super(AccountInvoiceReport, self)._select()
select_str += """,
sub.actual_cost_total as actual_cost_total,
sub.margin_avg as margin_avg
"""
return select_str
def _sub_select(self):
select_str = super(AccountInvoiceReport, self)._sub_select()
select_str += """,
SUM(CASE
WHEN ai.type::text = ANY (ARRAY['out_refund'::character varying::text, 'in_invoice'::character varying::text])
THEN - ail.actual_cost
ELSE ail.actual_cost
END) AS actual_cost_total,
avg(ai.margin_perc) as margin_avg
"""
return select_str
def _group_by(self):
group_by_str = super(AccountInvoiceReport, self)._group_by()
group_by_str += """,
ai.margin_perc
"""
return group_by_str | agpl-3.0 |
DarthMaulware/EquationGroupLeaks | Leak #5 - Lost In Translation/windows/Resources/Dsz/PyScripts/DataHandlers/Mcl_Cmd_DomainController_DataHandler.py | 1 | 4370 | # uncompyle6 version 2.9.10
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10)
# [GCC 6.2.0 20161005]
# Embedded file name: Mcl_Cmd_DomainController_DataHandler.py
def DataHandlerMain(namespace, InputFilename, OutputFilename):
import mcl.imports
import mcl.data.Input
import mcl.data.Output
import mcl.status
import mcl.target
import mcl.object.Message
mcl.imports.ImportNamesWithNamespace(namespace, 'mca.survey.cmd.domaincontroller', globals())
input = mcl.data.Input.GetInput(InputFilename)
output = mcl.data.Output.StartOutput(OutputFilename, input)
output.Start('DomainController', 'domaincontroller', [])
msg = mcl.object.Message.DemarshalMessage(input.GetData())
if input.GetStatus() != mcl.status.MCL_SUCCESS:
errorMsg = msg.FindMessage(mcl.object.Message.MSG_KEY_RESULT_ERROR)
moduleError = errorMsg.FindU32(mcl.object.Message.MSG_KEY_RESULT_ERROR_MODULE)
osError = errorMsg.FindU32(mcl.object.Message.MSG_KEY_RESULT_ERROR_OS)
output.RecordModuleError(moduleError, osError, errorStrings)
output.EndWithStatus(input.GetStatus())
return True
rtn = mcl.target.CALL_SUCCEEDED
while msg.GetNumRetrieved() < msg.GetCount():
if mcl.CheckForStop():
output.EndWithStatus(mcl.target.CALL_FAILED)
return False
statusResults = ResultStatus()
statusResults.Demarshal(msg)
from mcl.object.XmlOutput import XmlOutput
xml = XmlOutput()
xml.Start('DomainController')
xml.AddSubElementWithText('DCName', statusResults.dc)
properties = xml.AddSubElement('Properties')
if statusResults.typeServ & RESULT_FLAG_TYPE_DOMAIN_CTRL:
properties.AddSubElement('Primary')
if statusResults.typeServ & RESULT_FLAG_TYPE_DOMAIN_BAKCTRL:
properties.AddSubElement('Backup')
if statusResults.extraInfoRtn != 0:
sub = xml.AddSubElement('ExtendedErrorInfo')
errorStr = output.TranslateOsError(statusResults.extraInfoRtn)
sub.AddSubElementWithText('QueryError', errorStr)
else:
results = ResultDomainController()
results.Demarshal(msg)
xml.AddSubElementWithText('DCFullName', results.dcName)
sub = xml.AddSubElement('DCAddress')
sub.SetText(results.dcAddress)
if results.addressType == RESULT_ADDRTYPE_INET:
sub.AddAttribute('addrType', 'IPAddress')
elif results.addressType == RESULT_ADDRTYPE_NETBIOS:
sub.AddAttribute('addrType', 'NetBIOS')
else:
sub.AddAttribute('addrType', 'Unknown')
xml.AddSubElementWithText('DomainGuid', results.domainGuid)
xml.AddSubElementWithText('DomainName', results.domainName)
xml.AddSubElementWithText('DnsForestName', results.dnsForestName)
xml.AddSubElementWithText('DCSiteName', results.dcSiteName)
xml.AddSubElementWithText('ClientSiteName', results.clientSiteName)
if results.flags & RESULT_FLAG_DC_KDC:
properties.AddSubElement('KerberosKeyDistCenter')
if results.flags & RESULT_FLAG_DC_GC:
properties.AddSubElement('GlobalCatalog')
if results.flags & RESULT_FLAG_DC_DS:
properties.AddSubElement('DirectoryService')
if results.flags & RESULT_FLAG_DC_TIMESERV:
properties.AddSubElement('TimeService')
if results.flags & RESULT_FLAG_DC_WRITABLE:
properties.AddSubElement('SAM')
if statusResults.dcEnumStatus == 1:
sub = xml.AddSubElement('AddlInformation')
sub.AddSubElementWithText('EnumQueryError', 'Although all domain controllers (dcs) were requested, only primary dc obtained as enumeration of dcs failed')
rtn = mcl.target.CALL_FAILED
output.RecordXml(xml)
output.EndWithStatus(rtn)
return True
if __name__ == '__main__':
import sys
try:
namespace, InputFilename, OutputFilename = sys.argv[1:]
except:
print '%s <namespace> <input filename> <output filename>' % sys.argv[0]
sys.exit(1)
if DataHandlerMain(namespace, InputFilename, OutputFilename) != True:
sys.exit(-1) | unlicense |
openego/eDisGo | edisgo/flex_opt/storage_integration.py | 1 | 4762 | from math import sqrt
from edisgo.grid.components import Storage, Line, LVStation
from edisgo.grid.grids import MVGrid
from edisgo.grid.tools import select_cable
def storage_at_hvmv_substation(mv_grid, parameters, mode=None):
"""
Place storage at HV/MV substation bus bar.
Parameters
----------
mv_grid : :class:`~.grid.grids.MVGrid`
MV grid instance
parameters : :obj:`dict`
Dictionary with storage parameters. Must at least contain
'nominal_power'. See :class:`~.grid.network.StorageControl` for more
information.
mode : :obj:`str`, optional
Operational mode. See :class:`~.grid.network.StorageControl` for
possible options and more information. Default: None.
Returns
-------
:class:`~.grid.components.Storage`, :class:`~.grid.components.Line`
Created storage instance and newly added line to connect storage.
"""
storage = set_up_storage(node=mv_grid.station, parameters=parameters,
operational_mode=mode)
line = connect_storage(storage, mv_grid.station)
return storage, line
def set_up_storage(node, parameters,
voltage_level=None, operational_mode=None):
"""
Sets up a storage instance.
Parameters
----------
node : :class:`~.grid.components.Station` or :class:`~.grid.components.BranchTee`
Node the storage will be connected to.
parameters : :obj:`dict`, optional
Dictionary with storage parameters. Must at least contain
'nominal_power'. See :class:`~.grid.network.StorageControl` for more
information.
voltage_level : :obj:`str`, optional
This parameter only needs to be provided if `node` is of type
:class:`~.grid.components.LVStation`. In that case `voltage_level`
defines which side of the LV station the storage is connected to. Valid
options are 'lv' and 'mv'. Default: None.
operational_mode : :obj:`str`, optional
Operational mode. See :class:`~.grid.network.StorageControl` for
possible options and more information. Default: None.
"""
# if node the storage is connected to is an LVStation voltage_level
# defines which side the storage is connected to
if isinstance(node, LVStation):
if voltage_level == 'lv':
grid = node.grid
elif voltage_level == 'mv':
grid = node.mv_grid
else:
raise ValueError(
"{} is not a valid option for voltage_level.".format(
voltage_level))
else:
grid = node.grid
return Storage(operation=operational_mode,
id='{}_storage_{}'.format(grid,
len(grid.graph.nodes_by_attribute(
'storage')) + 1),
grid=grid,
geom=node.geom,
**parameters)
def connect_storage(storage, node):
"""
Connects storage to the given node.
The storage is connected by a cable
The cable the storage is connected with is selected to be able to carry
the storages nominal power and equal amount of reactive power.
No load factor is considered.
Parameters
----------
storage : :class:`~.grid.components.Storage`
Storage instance to be integrated into the grid.
node : :class:`~.grid.components.Station` or :class:`~.grid.components.BranchTee`
Node the storage will be connected to.
Returns
-------
:class:`~.grid.components.Line`
Newly added line to connect storage.
"""
# add storage itself to graph
storage.grid.graph.add_node(storage, type='storage')
# add 1m connecting line to node the storage is connected to
if isinstance(storage.grid, MVGrid):
voltage_level = 'mv'
else:
voltage_level = 'lv'
# necessary apparent power the line must be able to carry is set to be
# the storages nominal power and equal amount of reactive power devided by
# the minimum load factor
lf_dict = storage.grid.network.config['grid_expansion_load_factors']
lf = min(lf_dict['{}_feedin_case_line'.format(voltage_level)],
lf_dict['{}_load_case_line'.format(voltage_level)])
apparent_power_line = sqrt(2) * storage.nominal_power / lf
line_type, line_count = select_cable(storage.grid.network, voltage_level,
apparent_power_line)
line = Line(
id=storage.id,
type=line_type,
kind='cable',
length=1e-3,
grid=storage.grid,
quantity=line_count)
storage.grid.graph.add_edge(node, storage, line=line, type='line')
return line
| agpl-3.0 |
luotao1/Paddle | python/paddle/fluid/tests/unittests/test_print_op.py | 2 | 5661 | # Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import print_function
import unittest
import numpy as np
from op_test import OpTest
import paddle
import paddle.fluid as fluid
import paddle.fluid.layers as layers
from paddle.fluid import core
from paddle.fluid.framework import switch_main_program
from simple_nets import simple_fc_net, init_data
from paddle.static import Program, program_guard
paddle.enable_static()
class TestPrintOpCPU(unittest.TestCase):
def setUp(self):
self.place = paddle.CPUPlace()
self.x_tensor = fluid.core.LoDTensor()
tensor_np = np.random.random(size=(2, 3)).astype('float32')
self.x_tensor.set(tensor_np, self.place)
self.x_tensor.set_recursive_sequence_lengths([[1, 1]])
def build_network(self, only_forward, **kargs):
x = layers.data('x', shape=[3], dtype='float32', lod_level=1)
x.stop_gradient = False
paddle.static.Print(input=x, **kargs)
loss = paddle.mean(x)
paddle.static.append_backward(loss=loss)
return loss
def test_forward(self):
switch_main_program(Program())
printed = self.build_network(True, print_phase='forward')
exe = paddle.static.Executor(self.place)
outs = exe.run(feed={'x': self.x_tensor},
fetch_list=[printed],
return_numpy=False)
def test_backward(self):
switch_main_program(Program())
loss = self.build_network(False, print_phase='backward')
exe = paddle.static.Executor(self.place)
outs = exe.run(feed={'x': self.x_tensor},
fetch_list=[loss],
return_numpy=False)
def test_all_parameters(self):
x = layers.data('x', shape=[3], dtype='float32', lod_level=1)
x.stop_gradient = False
for print_tensor_name in [True, False]:
for print_tensor_type in [True, False]:
for print_tensor_shape in [True, False]:
for print_tensor_lod in [True, False]:
paddle.static.Print(
input=x,
print_tensor_name=print_tensor_name,
print_tensor_type=print_tensor_type,
print_tensor_shape=print_tensor_shape,
print_tensor_lod=print_tensor_lod, )
loss = paddle.mean(x)
paddle.static.append_backward(loss=loss)
exe = paddle.static.Executor(self.place)
outs = exe.run(feed={'x': self.x_tensor},
fetch_list=[loss],
return_numpy=False)
def test_no_summarize(self):
switch_main_program(Program())
printed = self.build_network(True, summarize=-1, print_phase='forward')
exe = paddle.static.Executor(self.place)
outs = exe.run(feed={'x': self.x_tensor},
fetch_list=[printed],
return_numpy=False)
class TestPrintOpError(unittest.TestCase):
def test_errors(self):
with program_guard(Program(), Program()):
# The input type of Print_op must be Variable.
x1 = fluid.create_lod_tensor(
np.array([[-1]]), [[1]], paddle.CPUPlace())
self.assertRaises(TypeError, paddle.static.Print, x1)
# The input dtype of Print_op must be float32, float64, int32_t, int64_t or bool.
x2 = paddle.static.data(name='x2', shape=[4], dtype="float16")
self.assertRaises(TypeError, paddle.static.Print, x2)
@unittest.skipIf(not core.is_compiled_with_cuda(),
"core is not compiled with CUDA")
class TestPrintOpGPU(TestPrintOpCPU):
def setUp(self):
self.place = paddle.CUDAPlace(0)
self.x_tensor = fluid.core.LoDTensor()
tensor_np = np.random.random(size=(2, 3)).astype('float32')
self.x_tensor.set(tensor_np, self.place)
self.x_tensor.set_recursive_sequence_lengths([[1, 1]])
class TestPrintOpBackward(unittest.TestCase):
def check_backward(self, use_cuda):
main = paddle.static.Program()
startup = paddle.static.Program()
with program_guard(main, startup):
loss = simple_fc_net()
loss = paddle.static.Print(loss)
paddle.optimizer.Adam().minimize(loss)
print_ops = [op for op in main.blocks[0].ops if op.type == u'print']
assert len(print_ops) == 2, "The number of print op should be 2"
place = paddle.CUDAPlace(0) if use_cuda else paddle.CPUPlace()
exe = paddle.static.Executor(place)
exe.run(startup)
binary = paddle.static.CompiledProgram(main).with_data_parallel(
loss_name=loss.name)
img, label = init_data()
feed_dict = {"image": img, "label": label}
exe.run(binary, feed_dict)
def test_fw_bw(self):
if paddle.is_compiled_with_cuda():
self.check_backward(use_cuda=True)
self.check_backward(use_cuda=False)
if __name__ == '__main__':
unittest.main()
| apache-2.0 |
procangroup/edx-platform | openedx/core/djangoapps/content/block_structure/exceptions.py | 25 | 1044 | """
Application-specific exceptions raised by the block structure framework.
"""
class BlockStructureException(Exception):
"""
Base class for all Block Structure framework exceptions.
"""
pass
class TransformerException(BlockStructureException):
"""
Exception class for Transformer related errors.
"""
pass
class UsageKeyNotInBlockStructure(BlockStructureException):
"""
Exception for when a usage key is not found within a block structure.
"""
pass
class TransformerDataIncompatible(BlockStructureException):
"""
Exception for when the version of a Transformer's data is not
compatible with the current version of the Transformer.
"""
pass
class BlockStructureNotFound(BlockStructureException):
"""
Exception for when a Block Structure is not found.
"""
def __init__(self, root_block_usage_key):
super(BlockStructureNotFound, self).__init__(
'Block structure not found; data_usage_key: {}'.format(root_block_usage_key)
)
| agpl-3.0 |
krishnazure/Flask | Work/TriviaMVA/TriviaMVA/env/Lib/site-packages/setuptools/tests/test_test.py | 286 | 3710 | # -*- coding: UTF-8 -*-
"""develop tests
"""
import sys
import os, shutil, tempfile, unittest
import tempfile
import site
from distutils.errors import DistutilsError
from setuptools.compat import StringIO
from setuptools.command.test import test
from setuptools.command import easy_install as easy_install_pkg
from setuptools.dist import Distribution
SETUP_PY = """\
from setuptools import setup
setup(name='foo',
packages=['name', 'name.space', 'name.space.tests'],
namespace_packages=['name'],
test_suite='name.space.tests.test_suite',
)
"""
NS_INIT = """# -*- coding: Latin-1 -*-
# Söme Arbiträry Ünicode to test Issüé 310
try:
__import__('pkg_resources').declare_namespace(__name__)
except ImportError:
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
"""
# Make sure this is Latin-1 binary, before writing:
if sys.version_info < (3,):
NS_INIT = NS_INIT.decode('UTF-8')
NS_INIT = NS_INIT.encode('Latin-1')
TEST_PY = """import unittest
class TestTest(unittest.TestCase):
def test_test(self):
print "Foo" # Should fail under Python 3 unless 2to3 is used
test_suite = unittest.makeSuite(TestTest)
"""
class TestTestTest(unittest.TestCase):
def setUp(self):
if sys.version < "2.6" or hasattr(sys, 'real_prefix'):
return
# Directory structure
self.dir = tempfile.mkdtemp()
os.mkdir(os.path.join(self.dir, 'name'))
os.mkdir(os.path.join(self.dir, 'name', 'space'))
os.mkdir(os.path.join(self.dir, 'name', 'space', 'tests'))
# setup.py
setup = os.path.join(self.dir, 'setup.py')
f = open(setup, 'wt')
f.write(SETUP_PY)
f.close()
self.old_cwd = os.getcwd()
# name/__init__.py
init = os.path.join(self.dir, 'name', '__init__.py')
f = open(init, 'wb')
f.write(NS_INIT)
f.close()
# name/space/__init__.py
init = os.path.join(self.dir, 'name', 'space', '__init__.py')
f = open(init, 'wt')
f.write('#empty\n')
f.close()
# name/space/tests/__init__.py
init = os.path.join(self.dir, 'name', 'space', 'tests', '__init__.py')
f = open(init, 'wt')
f.write(TEST_PY)
f.close()
os.chdir(self.dir)
self.old_base = site.USER_BASE
site.USER_BASE = tempfile.mkdtemp()
self.old_site = site.USER_SITE
site.USER_SITE = tempfile.mkdtemp()
def tearDown(self):
if sys.version < "2.6" or hasattr(sys, 'real_prefix'):
return
os.chdir(self.old_cwd)
shutil.rmtree(self.dir)
shutil.rmtree(site.USER_BASE)
shutil.rmtree(site.USER_SITE)
site.USER_BASE = self.old_base
site.USER_SITE = self.old_site
def test_test(self):
if sys.version < "2.6" or hasattr(sys, 'real_prefix'):
return
dist = Distribution(dict(
name='foo',
packages=['name', 'name.space', 'name.space.tests'],
namespace_packages=['name'],
test_suite='name.space.tests.test_suite',
use_2to3=True,
))
dist.script_name = 'setup.py'
cmd = test(dist)
cmd.user = 1
cmd.ensure_finalized()
cmd.install_dir = site.USER_SITE
cmd.user = 1
old_stdout = sys.stdout
sys.stdout = StringIO()
try:
try: # try/except/finally doesn't work in Python 2.4, so we need nested try-statements.
cmd.run()
except SystemExit: # The test runner calls sys.exit, stop that making an error.
pass
finally:
sys.stdout = old_stdout
| apache-2.0 |
almir-sne/backup | Inteligência artificial/EP1/ep1ai_almir/robot.py | 1 | 5657 | # -*- coding: latin-1 -*-
from state import *
from copy import copy
# A classe robot representa um robo
# state_map representa o mapa interno do robo, que é construido conforme ele anda
# start é a posição inicial
# position é a posição atual do robo
# goal é o objetivo
# open_list guarda os estados que estão com t = OPEN
class robot():
# Na inicialização, a classe recebe o ponto de partida e o ponto de chegada e
# cria a configuração inicial dos backpointers
def __init__ (self, px, py, gx, gy):
self.goal = point (gx, gy)
self.start = point (px, py)
self.position = point (px, py)
self.state_map = self.state_matrix ()
self.open_list = state_list ()
self.open_list.insert(self.state_map[gx][gy], 0)
while self.state_map[px][py].t != CLOSED and self.process_state() != -1:
pass
print "Robot says: YOU CAN'T ESCAPE HUMANOID!"
# Recebe o mapa do ambiente e imprime a trajetória do robo na saída padrão
def print_map (self, map):
print " y"
print " v 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 <- x"
for j in range(0, 18):
print str(j).rjust(2),
for i in range(0, 18):
if map[i][j] == EMPTY:
if point (i, j) == self.goal:
print 'G',
elif point (i, j) == self.start:
print 'S',
elif self.state_map[i][j].path == 1:
print 'R',
else:
print ' ',
else:
print 'O',
print ('\n'),
print " ^ 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 <- x"
print " y"
print "Legenda:\n G -> objetivo\n S -> ponto de partida\n O -> obstaculo\n R -> local por onde o robo passou"
# Recebe o mapa do ambiente e move o robo em 1 posição
# Se houver uma discrepancia entre o mapa do robo e o ambiente,
# atualiza o mapa e os backpointers
# Devolve 1 se o robo chegou no objetivo e 0 caso contrario
def move (self, map):
if self.position == self.goal:
return 1
p = point (self.position.x, self.position.y)
x = self.state_map[p.x][p.y]
if map[x.backpointer.x][x.backpointer.y] == OBSTACLE:
h = x.h
self.modify_cost (x.backpointer, OBSTACLE)
kmin = -2
while kmin < h and kmin != -1:
kmin = self.process_state()
else:
self.state_map[p.x][p.y].path = 1
self.position.x = x.backpointer.x
self.position.y = x.backpointer.y
return 0
# Recebe um estado y e seu novo custo cval
# Atualiza o custo de y e o insere na lista de estados abertos
# Devolve o estado da lista com menor k
def modify_cost (self, y, cval):
y.c = cval
if y.t == CLOSED:
self.open_list.insert (y, y.h)
return self.open_list.get_kmin ()
# Recebe dois inteiros i e j, ambos entre 0 e 17
# Devolve uma lista contendo todos os estados vizinhos de state_map[i][j]
def get_neighbors(self, i, j):
neighbors = []
if i > 0 and j < 17:
neighbors += [self.state_map[i - 1][j + 1]]
if i < 17 and j > 0:
neighbors += [self.state_map[i + 1][j - 1]]
if i < 17 and j < 17:
neighbors += [self.state_map[i + 1][j + 1]]
if i > 0 and j > 0:
neighbors += [self.state_map[i - 1][j - 1]]
if i > 0:
neighbors += [self.state_map[i - 1][j]]
if i < 17:
neighbors += [self.state_map[i + 1][j]]
if j > 0:
neighbors += [self.state_map[i][j - 1]]
if j < 17:
neighbors += [self.state_map[i][j + 1]]
return neighbors
# Atualiza os backpointers dos estados
# Devolve o menor valor de k da lista de estados abertos
def process_state (self):
x = self.open_list.delete()
if x == None:
return -1
kold = x.k
neighbors = self.get_neighbors(x.x, x.y)
if kold < x.h:
for y in neighbors:
if y.h != None and y.h <= kold and x.h > y.h + y.c:
x.backpointer = y
x.h = y.h + y.c
if kold == x.h:
for y in neighbors:
if (y.t == NEW or ((y.backpointer is x) and (y.h != x.h + x.c)) or
(y.backpointer is not x and y.h > x.h + x.c)):
y.backpointer = x
self.open_list.insert(y, x.h + x.c)
else:
for y in neighbors:
if y.t == NEW or (y.backpointer is x and y.h != x.h + x.c):
y.backpointer = x
self.open_list.insert(y, x.h + x.c)
elif y.backpointer is not x and y.h > x.h + x.c:
self.open_list.insert(x, x.h)
elif (y.backpointer is not x and x.h > y.h + y.c and y.t == CLOSED
and y.h > kold):
self.open_list.insert(y, y.h)
return self.open_list.get_kmin()
# Usando as tecnicas mais avancadas de POG, cria uma matriz de estados
# As bordas da matriz já são inicializadas como obstaculos
# Devolve a matriz criada
def state_matrix (self):
mat = []
for i in range(0, 18):
x = []
for j in range(0, 18):
x += [state(i, j)]
mat += [x]
for i in range(0, 18):
mat[0][i].c = mat[i][0].c = mat[17][i].c = mat[i][17].c = OBSTACLE
return mat
| mit |
dasch/avro | lang/py3/avro/tests/av_bench.py | 21 | 3194 | #!/usr/bin/env python3
# -*- mode: python -*-
# -*- coding: utf-8 -*-
# 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 logging
import random
import string
import sys
import time
import avro.datafile
import avro.io
import avro.schema
TYPES = ('A', 'CNAME',)
FILENAME = 'datafile.avr'
def GenerateRandomName():
return ''.join(random.sample(string.ascii_lowercase, 15))
def GenerateRandomIP():
return '%s.%s.%s.%s' % (
random.randint(0, 255),
random.randint(0, 255),
random.randint(0, 255),
random.randint(0, 255),
)
def Write(nrecords):
"""Writes a data file with the specified number of random records.
Args:
nrecords: Number of records to write.
"""
schema_s = """
{
"type": "record",
"name": "Query",
"fields" : [
{"name": "query", "type": "string"},
{"name": "response", "type": "string"},
{"name": "type", "type": "string", "default": "A"}
]
}
"""
schema = avro.schema.Parse(schema_s)
writer = avro.io.DatumWriter(schema)
with open(FILENAME, 'wb') as out:
with avro.datafile.DataFileWriter(
out, writer, schema,
# codec='deflate'
) as data_writer:
for _ in range(nrecords):
response = GenerateRandomIP()
query = GenerateRandomName()
type = random.choice(TYPES)
data_writer.append({
'query': query,
'response': response,
'type': type,
})
def Read(expect_nrecords):
"""Reads the data file generated by Write()."""
with open(FILENAME, 'rb') as f:
reader = avro.io.DatumReader()
with avro.datafile.DataFileReader(f, reader) as file_reader:
nrecords = 0
for record in file_reader:
nrecords += 1
assert (nrecords == expect_nrecords), (
'Expecting %d records, got %d.' % (expected_nrecords, nrecords))
def Timing(f, *args):
s = time.time()
f(*args)
e = time.time()
return e - s
def Main(args):
nrecords = int(args[1])
print('Write %0.4f' % Timing(Write, nrecords))
print('Read %0.4f' % Timing(Read, nrecords))
if __name__ == '__main__':
log_formatter = logging.Formatter(
'%(asctime)s %(levelname)s %(filename)s:%(lineno)s : %(message)s')
logging.root.setLevel(logging.DEBUG)
console_handler = logging.StreamHandler()
console_handler.setFormatter(log_formatter)
console_handler.setLevel(logging.DEBUG)
logging.root.addHandler(console_handler)
Main(sys.argv)
| apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.