desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Stop this server.
This is not a very nice action, as currently the method by which a
server is stopped is by killing its eventlet.
:returns: None'
| def stop(self):
| LOG.info(_('Stopping WSGI server.'))
self._server.kill()
|
'Block, until the server has stopped.
Waits on the server\'s eventlet to finish, then returns.
:returns: None'
| def wait(self):
| try:
self._server.wait()
except greenlet.GreenletExit:
LOG.info(_('WSGI server has stopped.'))
|
'Used for paste app factories in paste.deploy config files.
Any local configuration (that is, values under the [app:APPNAME]
section of the paste config) will be passed into the `__init__` method
as kwargs.
A hypothetical configuration would look like:
[app:wadl]
latest_version = 1.3
paste.app_factory = monitor.api.fan... | @classmethod
def factory(cls, global_config, **local_config):
| return cls(**local_config)
|
'Subclasses will probably want to implement __call__ like this:
@webob.dec.wsgify(RequestClass=Request)
def __call__(self, req):
# Any of the following objects work as responses:
# Option 1: simple string
res = \'message\n\'
# Option 2: a nicely formatted HTTP exception page
res = exc.HTTPForbidden(detail=\'Nice try\')... | def __call__(self, environ, start_response):
| raise NotImplementedError(_('You must implement __call__'))
|
'Used for paste app factories in paste.deploy config files.
Any local configuration (that is, values under the [filter:APPNAME]
section of the paste config) will be passed into the `__init__` method
as kwargs.
A hypothetical configuration would look like:
[filter:analytics]
redis_host = 127.0.0.1
paste.filter_factory =... | @classmethod
def factory(cls, global_config, **local_config):
| def _factory(app):
return cls(app, **local_config)
return _factory
|
'Called on each request.
If this returns None, the next application down the stack will be
executed. If it returns a response then that response will be returned
and execution will stop here.'
| def process_request(self, req):
| return None
|
'Do whatever you\'d like to the response.'
| def process_response(self, response):
| return response
|
'Iterator that prints the contents of a wrapper string.'
| @staticmethod
def print_generator(app_iter):
| print (('*' * 40) + ' BODY')
for part in app_iter:
sys.stdout.write(part)
sys.stdout.flush()
(yield part)
print
|
'Create a router for the given routes.Mapper.
Each route in `mapper` must specify a \'controller\', which is a
WSGI app to call. You\'ll probably want to specify an \'action\' as
well and have your controller be an object that can route
the request to the action-specific method.
Examples:
mapper = routes.Mapper()
sc =... | def __init__(self, mapper):
| self.map = mapper
self._router = routes.middleware.RoutesMiddleware(self._dispatch, self.map)
|
'Route the incoming request to a controller based on self.map.
If no match, return a 404.'
| @webob.dec.wsgify(RequestClass=Request)
def __call__(self, req):
| return self._router
|
'Dispatch the request to the appropriate controller.
Called by self._router after matching the incoming request to a route
and putting the information into req.environ. Either returns 404
or the routed WSGI app\'s response.'
| @staticmethod
@webob.dec.wsgify(RequestClass=Request)
def _dispatch(req):
| match = req.environ['wsgiorg.routing_args'][1]
if (not match):
return webob.exc.HTTPNotFound()
app = match['controller']
return app
|
'Initialize the loader, and attempt to find the config.
:param config_path: Full or relative path to the paste config.
:returns: None'
| def __init__(self, config_path=None):
| config_path = (config_path or FLAGS.api_paste_config)
self.config_path = utils.find_config(config_path)
|
'Return the paste URLMap wrapped WSGI application.
:param name: Name of the application to load.
:returns: Paste URLMap object wrapping the requested application.
:raises: `monitor.exception.PasteAppNotFound`'
| def load_app(self, name):
| try:
return deploy.loadapp(('config:%s' % self.config_path), name=name)
except LookupError as err:
LOG.error(err)
raise exception.PasteAppNotFound(name=name, path=self.config_path)
|
':param read_deleted: \'no\' indicates deleted records are hidden, \'yes\'
indicates deleted records are visible, \'only\' indicates that
*only* deleted records are visible.
:param overwrite: Set to False to ensure that the greenthread local
copy of the index is not overwritten.
:param kwargs: Extra arguments that migh... | def __init__(self, user_id, project_id, is_admin=None, read_deleted='no', roles=None, remote_address=None, timestamp=None, request_id=None, auth_token=None, overwrite=True, quota_class=None, **kwargs):
| if kwargs:
LOG.warn((_('Arguments dropped when creating context: %s') % str(kwargs)))
self.user_id = user_id
self.project_id = project_id
self.roles = (roles or [])
self.is_admin = is_admin
if (self.is_admin is None):
self.is_admin = policy.check_is_admin(self.role... |
'Return a version of this context with admin flag set.'
| def elevated(self, read_deleted=None, overwrite=False):
| context = copy.copy(self)
context.is_admin = True
if ('admin' not in context.roles):
context.roles.append('admin')
if (read_deleted is not None):
context.read_deleted = read_deleted
return context
|
'Initialize the model used for style transfer.
:param str model_name:
Model to use.
:param bool use_pbar:
Use progressbar flag.'
| def __init__(self, model_name, use_pbar=True):
| style_path = os.path.abspath(os.path.split(__file__)[0])
base_path = os.path.join(style_path, 'models', model_name)
if (model_name == 'vgg19'):
model_file = os.path.join(base_path, 'VGG_ILSVRC_19_layers_deploy.prototxt')
pretrained_file = os.path.join(base_path, 'VGG_ILSVRC_19_layers.caffemo... |
'Loads specified model from caffe install (see caffe docs).
:param str model_file:
Path to model protobuf.
:param str pretrained_file:
Path to pretrained caffe model.
:param str mean_file:
Path to mean file.'
| def load_model(self, model_file, pretrained_file, mean_file):
| null_fds = os.open(os.devnull, os.O_RDWR)
out_orig = os.dup(2)
os.dup2(null_fds, 2)
net = caffe.Net(str(model_file), str(pretrained_file), caffe.TEST)
os.dup2(out_orig, 2)
os.close(null_fds)
transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape})
transformer.set_mean('... |
'Saves the generated image (net input, after optimization).
:param str path:
Output path.'
| def get_generated(self):
| data = self.net.blobs['data'].data
img_out = self.transformer.deprocess('data', data)
return img_out
|
'Rescales the network to fit a particular image.'
| def _rescale_net(self, img):
| new_dims = ((1, img.shape[2]) + img.shape[:2])
self.net.blobs['data'].reshape(*new_dims)
self.transformer.inputs['data'] = new_dims
|
'Creates an initial input (generated) image.'
| def _make_noise_input(self, init):
| dims = (tuple(self.net.blobs['data'].data.shape[2:]) + (self.net.blobs['data'].data.shape[1],))
grid = np.mgrid[0:dims[0], 0:dims[1]]
Sf = (((grid[0] - ((dims[0] - 1) / 2.0)) ** 2) + ((grid[1] - ((dims[1] - 1) / 2.0)) ** 2))
Sf[np.where((Sf == 0))] = 1
Sf = np.sqrt(Sf)
Sf = np.dstack((((Sf ** in... |
'Creates a progress bar.'
| def _create_pbar(self, max_iter):
| self.grad_iter = 0
self.pbar = pb.ProgressBar()
self.pbar.widgets = ['Optimizing: ', pb.Percentage(), ' ', pb.Bar(marker=pb.AnimatedMarker()), ' ', pb.ETA()]
self.pbar.maxval = max_iter
|
'Transfers the style of the artwork to the input image.
:param numpy.ndarray img_style:
A style image with the desired target style.
:param numpy.ndarray img_content:
A content image in floating point, RGB format.
:param function callback:
A callback function, which takes images at iterations.'
| def transfer_style(self, img_style, img_content, length=512, ratio=100000.0, n_iter=512, init='-1', verbose=False, callback=None):
| orig_dim = min(self.net.blobs['data'].shape[2:])
scale = max((length / float(max(img_style.shape[:2]))), (orig_dim / float(min(img_style.shape[:2]))))
img_style = rescale(img_style, (STYLE_SCALE * scale))
scale = max((length / float(max(img_content.shape[:2]))), (orig_dim / float(min(img_content.shape[:... |
'domReader -- class must implement DOMAdapterInterface
base_url -- base url string'
| def __init__(self, domReader=None, base_url=None):
| self.__base_url = base_url
self.__readerClass = domReader
if (not self.__readerClass):
self.__readerClass = DOMAdapter
self._includes = {}
self._imports = {}
|
'Add dictionary of imports to schema instance.
schema -- XMLSchema instance'
| def __setImports(self, schema):
| for (ns, val) in schema.imports.items():
if self._imports.has_key(ns):
schema.addImportSchema(self._imports[ns])
|
'Add dictionary of includes to schema instance.
schema -- XMLSchema instance'
| def __setIncludes(self, schema):
| for (schemaLocation, val) in schema.includes.items():
if self._includes.has_key(schemaLocation):
schema.addIncludeSchema(schemaLocation, self._imports[schemaLocation])
|
'provide reader with schema document for a location.'
| def addSchemaByLocation(self, location, schema):
| self._includes[location] = schema
|
'provide reader with schema document for a targetNamespace.'
| def addSchemaByNamespace(self, schema):
| self._imports[schema.targetNamespace] = schema
|
'element -- DOM node or document
parent -- WSDLAdapter instance'
| def loadFromNode(self, parent, element):
| reader = self.__readerClass(element)
schema = XMLSchema(parent)
schema.wsdl = parent
schema.setBaseUrl(self.__base_url)
schema.load(reader)
return schema
|
'Return an XMLSchema instance loaded from a file object.
file -- file object
url -- base location for resolving imports/includes.'
| def loadFromStream(self, file, url=None):
| reader = self.__readerClass()
reader.loadDocument(file)
schema = XMLSchema()
if (url is not None):
schema.setBaseUrl(url)
schema.load(reader)
self.__setIncludes(schema)
self.__setImports(schema)
return schema
|
'Return an XMLSchema instance loaded from an XML string.
data -- XML string'
| def loadFromString(self, data):
| return self.loadFromStream(StringIO(data))
|
'Return an XMLSchema instance loaded from the given url.
url -- URL to dereference
schema -- Optional XMLSchema instance.'
| def loadFromURL(self, url, schema=None):
| reader = self.__readerClass()
if self.__base_url:
url = basejoin(self.__base_url, url)
reader.loadFromURL(url)
schema = (schema or XMLSchema())
schema.setBaseUrl(url)
schema.load(reader)
self.__setIncludes(schema)
self.__setImports(schema)
return schema
|
'Return an XMLSchema instance loaded from the given file.
filename -- name of file to open'
| def loadFromFile(self, filename):
| if self.__base_url:
filename = basejoin(self.__base_url, filename)
file = open(filename, 'rb')
try:
schema = self.loadFromStream(file, filename)
finally:
file.close()
return schema
|
'return true if node has attribute
attr -- attribute to check for
ns -- namespace of attribute, by default None'
| def hasattr(self, attr, ns=None):
| raise NotImplementedError, 'adapter method not implemented'
|
'returns an ordered list of child nodes
*contents -- list of node names to return'
| def getContentList(self, *contents):
| raise NotImplementedError, 'adapter method not implemented'
|
'set attribute dictionary'
| def setAttributeDictionary(self, attributes):
| raise NotImplementedError, 'adapter method not implemented'
|
'returns a dict of node\'s attributes'
| def getAttributeDictionary(self):
| raise NotImplementedError, 'adapter method not implemented'
|
'returns namespace referenced by prefix.'
| def getNamespace(self, prefix):
| raise NotImplementedError, 'adapter method not implemented'
|
'returns tagName of node'
| def getTagName(self):
| raise NotImplementedError, 'adapter method not implemented'
|
'returns parent element in DOMAdapter or None'
| def getParentNode(self):
| raise NotImplementedError, 'adapter method not implemented'
|
'load a Document from a file object
file --'
| def loadDocument(self, file):
| raise NotImplementedError, 'adapter method not implemented'
|
'load a Document from an url
url -- URL to dereference'
| def loadFromURL(self, url):
| raise NotImplementedError, 'adapter method not implemented'
|
'Reset all instance variables.
element -- DOM document, node, or None'
| def __init__(self, node=None):
| if hasattr(node, 'documentElement'):
self.__node = node.documentElement
else:
self.__node = node
self.__attributes = None
|
'attr -- attribute
ns -- optional namespace, None means unprefixed attribute.'
| def hasattr(self, attr, ns=None):
| if (not self.__attributes):
self.setAttributeDictionary()
if ns:
return self.__attributes.get(ns, {}).has_key(attr)
return self.__attributes.has_key(attr)
|
'prefix -- deference namespace prefix in node\'s context.
Ascends parent nodes until found.'
| def getNamespace(self, prefix):
| namespace = None
if (prefix == 'xmlns'):
namespace = DOM.findDefaultNS(prefix, self.__node)
else:
try:
namespace = DOM.findNamespaceURI(prefix, self.__node)
except DOMException as ex:
if (prefix != 'xml'):
raise SchemaError, ('%s namespace ... |
'parent -- parent instance
instance variables:
attributes -- dictionary of node\'s attributes'
| def __init__(self, parent=None):
| self.attributes = None
self._parent = parent
if self._parent:
self._parent = weakref.ref(parent)
if ((not (self.__class__ == XMLSchemaComponent)) and (not ((type(self.__class__.required) == type(XMLSchemaComponent.required)) and (type(self.__class__.attributes) == type(XMLSchemaComponent.attribu... |
'Returns a node trace up to the <schema> item.'
| def getItemTrace(self):
| (item, path, name, ref) = (self, [], 'name', 'ref')
while ((not isinstance(item, XMLSchema)) and (not isinstance(item, WSDLToolsAdapter))):
attr = item.getAttribute(name)
if (not attr):
attr = item.getAttribute(ref)
if (not attr):
path.append(('<%s>' % ite... |
'return targetNamespace'
| def getTargetNamespace(self):
| parent = self
targetNamespace = 'targetNamespace'
tns = self.attributes.get(targetNamespace)
while ((not tns) and parent and (parent._parent is not None)):
parent = parent._parent()
tns = parent.attributes.get(targetNamespace)
return (tns or '')
|
'attribute -- attribute with a QName value (eg. type).
collection -- check types collection in parent Schema instance'
| def getAttributeDeclaration(self, attribute):
| return self.getQNameAttribute(ATTRIBUTES, attribute)
|
'attribute -- attribute with a QName value (eg. type).
collection -- check types collection in parent Schema instance'
| def getAttributeGroup(self, attribute):
| return self.getQNameAttribute(ATTRIBUTE_GROUPS, attribute)
|
'attribute -- attribute with a QName value (eg. type).
collection -- check types collection in parent Schema instance'
| def getTypeDefinition(self, attribute):
| return self.getQNameAttribute(TYPES, attribute)
|
'attribute -- attribute with a QName value (eg. element).
collection -- check elements collection in parent Schema instance.'
| def getElementDeclaration(self, attribute):
| return self.getQNameAttribute(ELEMENTS, attribute)
|
'attribute -- attribute with a QName value (eg. ref).
collection -- check model_group collection in parent Schema instance.'
| def getModelGroup(self, attribute):
| return self.getQNameAttribute(MODEL_GROUPS, attribute)
|
'returns object instance representing QName --> (namespace,name),
or if does not exist return None.
attribute -- an information item attribute, with a QName value.
collection -- collection in parent Schema instance to search.'
| def getQNameAttribute(self, collection, attribute):
| tdc = self.getAttributeQName(attribute)
if (not tdc):
return
obj = self.getSchemaItem(collection, tdc.getTargetNamespace(), tdc.getName())
if obj:
return obj
return
|
'returns object instance representing namespace, name,
or if does not exist return None if built-in, else
raise SchemaError.
namespace -- namespace item defined in.
name -- name of item.
collection -- collection in parent Schema instance to search.'
| def getSchemaItem(self, collection, namespace, name):
| parent = GetSchema(self)
if (parent.targetNamespace == namespace):
try:
obj = getattr(parent, collection)[name]
except KeyError as ex:
raise KeyError, ('targetNamespace(%s) collection(%s) has no item(%s)' % (namespace, collection, name))
return obj
... |
'deference prefix or by default xmlns, returns namespace.'
| def getXMLNS(self, prefix=None):
| if (prefix == XMLSchemaComponent.xml):
return XMLNS.XML
parent = self
ns = self.attributes[XMLSchemaComponent.xmlns].get((prefix or XMLSchemaComponent.xmlns_key))
while (not ns):
parent = parent._parent()
ns = parent.attributes[XMLSchemaComponent.xmlns].get((prefix or XMLSchemaCo... |
'return requested attribute value or None'
| def getAttribute(self, attribute):
| if (type(attribute) in (list, tuple)):
if (len(attribute) != 2):
raise LookupError, 'To access attributes must use name or (namespace,name)'
ns_dict = self.attributes.get(attribute[0])
if (ns_dict is None):
return None
return ns_dict.get(a... |
'return requested attribute value as (namespace,name) or None'
| def getAttributeQName(self, attribute):
| qname = self.getAttribute(attribute)
if (isinstance(qname, TypeDescriptionComponent) is True):
return qname
if (qname is None):
return None
(prefix, ncname) = SplitQName(qname)
namespace = self.getXMLNS(prefix)
return TypeDescriptionComponent((namespace, ncname))
|
'return attribute name or None'
| def getAttributeName(self):
| return self.getAttribute('name')
|
'Sets up attribute dictionary, checks for required attributes and
sets default attribute values. attr is for default attribute values
determined at runtime.
structure of attributes dictionary
[\'xmlns\'][xmlns_key] -- xmlns namespace
[\'xmlns\'][prefix] -- declared namespace prefix
[namespace][prefix] -- attributes d... | def setAttributes(self, node):
| self.attributes = {XMLSchemaComponent.xmlns: {}}
for (k, v) in node.getAttributeDictionary().items():
(prefix, value) = SplitQName(k)
if (value == XMLSchemaComponent.xmlns):
self.attributes[value][(prefix or XMLSchemaComponent.xmlns_key)] = v
elif prefix:
ns = nod... |
'retrieve xsd contents'
| def getContents(self, node):
| return node.getContentList(*self.__class__.contents['xsd'])
|
'Looks for default values for unset attributes. If
class variable representing attribute is None, then
it must be defined as an instance variable.'
| def __setAttributeDefaults(self):
| for (k, v) in self.__class__.attributes.items():
if ((v is not None) and (self.attributes.has_key(k) is False)):
if isinstance(v, types.FunctionType):
self.attributes[k] = v(self)
else:
self.attributes[k] = v
|
'Checks that required attributes have been defined,
attributes w/default cannot be required. Checks
all defined attributes are legal, attribute
references are not subject to this test.'
| def __checkAttributes(self):
| for a in self.__class__.required:
if (not self.attributes.has_key(a)):
raise SchemaError, ('class instance %s, missing required attribute %s' % (self.__class__, a))
for (a, v) in self.attributes.items():
if (type(v) is dict):
continue
if (a in (X... |
'returns WSDLTools.WSDL types Collection'
| def getImportSchemas(self):
| return self._parent().types
|
'parent --
instance variables:
targetNamespace -- schema\'s declared targetNamespace, or empty string.
_imported_schemas -- namespace keyed dict of schema dependencies, if
a schema is provided instance will not resolve import statement.
_included_schemas -- schemaLocation keyed dict of component schemas,
if schema is p... | def __init__(self, parent=None):
| self.__node = None
self.targetNamespace = None
XMLSchemaComponent.__init__(self, parent)
f = (lambda k: k.attributes['name'])
ns = (lambda k: k.attributes['namespace'])
sl = (lambda k: k.attributes['schemaLocation'])
self.includes = Collection(self, key=sl)
self.imports = Collection(self... |
'Interacting with the underlying DOM tree.'
| def getNode(self):
| return self.__node
|
'for resolving import statements in Schema instance
schema -- schema instance
_imported_schemas'
| def addImportSchema(self, schema):
| if (not isinstance(schema, XMLSchema)):
raise TypeError, 'expecting a Schema instance'
if (schema.targetNamespace != self.targetNamespace):
self._imported_schemas[schema.targetNamespace] = schema
else:
raise SchemaError, 'import schema bad targetNamespace'
|
'for resolving include statements in Schema instance
schemaLocation -- schema location
schema -- schema instance
_included_schemas'
| def addIncludeSchema(self, schemaLocation, schema):
| if (not isinstance(schema, XMLSchema)):
raise TypeError, 'expecting a Schema instance'
if ((not schema.targetNamespace) or (schema.targetNamespace == self.targetNamespace)):
self._included_schemas[schemaLocation] = schema
else:
raise SchemaError, 'include schema bad ... |
'set the import schema dictionary, which is used to
reference depedent schemas.'
| def setImportSchemas(self, schema_dict):
| self._imported_schemas = schema_dict
|
'get the import schema dictionary, which is used to
reference depedent schemas.'
| def getImportSchemas(self):
| return self._imported_schemas
|
'returns tuple of namespaces the schema instance has declared
itself to be depedent upon.'
| def getSchemaNamespacesToImport(self):
| return tuple(self.includes.keys())
|
'set the include schema dictionary, which is keyed with
schemaLocation (uri).
This is a means of providing
schemas to the current schema for content inclusion.'
| def setIncludeSchemas(self, schema_dict):
| self._included_schemas = schema_dict
|
'get the include schema dictionary, which is keyed with
schemaLocation (uri).'
| def getIncludeSchemas(self):
| return self._included_schemas
|
'get base url, used for normalizing all relative uri\'s'
| def getBaseUrl(self):
| return self._base_url
|
'set base url, used for normalizing all relative uri\'s'
| def setBaseUrl(self, url):
| self._base_url = url
|
'return elementFormDefault attribute'
| def getElementFormDefault(self):
| return self.attributes.get('elementFormDefault')
|
'return attributeFormDefault attribute'
| def getAttributeFormDefault(self):
| return self.attributes.get('attributeFormDefault')
|
'return blockDefault attribute'
| def getBlockDefault(self):
| return self.attributes.get('blockDefault')
|
'return finalDefault attribute'
| def getFinalDefault(self):
| return self.attributes.get('finalDefault')
|
'if schema is not defined, first look for a Schema class instance
in parent Schema. Else if not defined resolve schemaLocation
and create a new Schema class instance, and keep a hard reference.'
| def getSchema(self):
| if (not self._schema):
ns = self.attributes['namespace']
schema = self._parent().getImportSchemas().get(ns)
if ((not schema) and self._parent()._parent):
schema = self._parent()._parent().getImportSchemas().get(ns)
if (not schema):
url = self.attributes.get('s... |
''
| def loadSchema(self, schema):
| base_url = self._parent().getBaseUrl()
reader = SchemaReader(base_url=base_url)
reader._imports = self._parent().getImportSchemas()
reader._includes = self._parent().getIncludeSchemas()
self._schema = schema
if (not self.attributes.has_key('schemaLocation')):
raise NoSchemaLocationWarnin... |
'if schema is not defined, first look for a Schema class instance
in parent Schema. Else if not defined resolve schemaLocation
and create a new Schema class instance.'
| def getSchema(self):
| if (not self._schema):
schema = self._parent()
self._schema = schema.getIncludeSchemas().get(self.attributes['schemaLocation'])
if (not self._schema):
url = self.attributes['schemaLocation']
reader = SchemaReader(base_url=schema.getBaseUrl())
reader._impor... |
'No list or union support'
| def fromDom(self, node):
| self.setAttributes(node)
contents = self.getContents(node)
for i in contents:
component = SplitQName(i.getTagName())[1]
if ((component == 'annotation') and (not self.annotation)):
self.annotation = Annotation(self)
self.annotation.fromDom(i)
elif (component ==... |
'attribute -- attribute with a QName value (eg. type).
collection -- check types collection in parent Schema instance'
| def getAttributeGroup(self, attribute='ref'):
| return XMLSchemaComponent.getAttributeGroup(self, attribute)
|
'Global elements are always qualified.'
| def isQualified(self):
| return True
|
'return attribute.
If attribute is type and it\'s None, and no simple or complex content,
return the default type "xsd:anyType"'
| def getAttribute(self, attribute):
| value = XMLSchemaComponent.getAttribute(self, attribute)
if ((attribute != 'type') or (value is not None)):
return value
if (self.content is not None):
return None
parent = self
while 1:
nsdict = parent.attributes[XMLSchemaComponent.xmlns]
for (k, v) in nsdict.items()... |
'If attribute is None, "type" is assumed, return the corresponding
representation of the global type definition (TypeDefinition),
or the local definition if don\'t find "type". To maintain backwards
compat, if attribute is provided call base class method.'
| def getTypeDefinition(self, attribute=None):
| if attribute:
return XMLSchemaComponent.getTypeDefinition(self, attribute)
gt = XMLSchemaComponent.getTypeDefinition(self, 'type')
if gt:
return gt
return self.content
|
'Local elements can be qualified or unqualifed according
to the attribute form, or the elementFormDefault. By default
local elements are unqualified.'
| def isQualified(self):
| form = self.getAttribute('form')
if (form == 'qualified'):
return True
if (form == 'unqualified'):
return False
raise SchemaError, ('Bad form (%s) for element: %s' % (form, self.getItemTrace()))
|
'If attribute is None, "ref" is assumed, return the corresponding
representation of the global element declaration (ElementDeclaration),
To maintain backwards compat, if attribute is provided call base class method.'
| def getElementDeclaration(self, attribute=None):
| if attribute:
return XMLSchemaComponent.getElementDeclaration(self, attribute)
return XMLSchemaComponent.getElementDeclaration(self, 'ref')
|
'Global elements are always qualified, but if processContents
are not strict could have dynamically generated local elements.'
| def isQualified(self):
| return GetSchema(self).isElementFormDefaultQualified()
|
'return attribute.'
| def getAttribute(self, attribute):
| return XMLSchemaComponent.getAttribute(self, attribute)
|
'return the type refered to by itemType attribute or
the simpleType content. If returns None, then the
type refered to by itemType is primitive.'
| def getTypeDefinition(self, attribute='itemType'):
| tp = XMLSchemaComponent.getTypeDefinition(self, attribute)
return (tp or self.content)
|
'args -- (namespace, name)
Remove the name\'s prefix, irrelevant.'
| def __init__(self, args):
| if (len(args) != 2):
raise TypeError, ('expecting tuple (namespace, name), got %s' % args)
elif (args[1].find(':') >= 0):
args = (args[0], SplitQName(args[1])[1])
tuple.__init__(self, args)
return
|
'Write convenience function; writes strings.'
| def write(self, *args):
| for s in args:
self.out.write(s)
event = ''.join(*args)
|
''
| def __str__(self):
| from cStringIO import StringIO
s = StringIO()
n = ' '
reserved = self.reserved
omitname = self.omitname
levels = self.levels
for k in (list(filter((lambda i: self.has_key(i)), reserved)) + list(filter((lambda i: (i not in reserved)), self.keys()))):
v = self[k]
if (k in om... |
'args -- datetime (year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])'
| def __new__(self, args=None):
| import datetime
args = (args or datetime.datetime.utcnow())
l = (args.year, args.month, args.day, args.hour, args.minute, args.second, args.microsecond, (args.tzinfo or 'Z'))
return str.__new__(self, ('%04d-%02d-%02dT%02d:%02d:%02d.%06d%s' % l))
|
'Create and run the implementation.'
| def __init__(self, node, write, **kw):
| self.write = write
self.subset = kw.get('subset')
self.comments = kw.get('comments', 0)
self.unsuppressedPrefixes = kw.get('unsuppressedPrefixes')
nsdict = kw.get('nsdict', {'xml': XMLNS.XML, 'xmlns': XMLNS.BASE})
self.state = (nsdict, {'xml': ''}, {}, {})
if (node.nodeType == Node.DOCUMENT_... |
'_inherit_context(self, node) -> list
Scan ancestors of attribute and namespace context. Used only
for single element node canonicalization, not for subset
canonicalization.'
| def _inherit_context(self, node):
| xmlattrs = filter(_IN_XML_NS, _attrs(node))
(inherited, parent) = ([], node.parentNode)
while (parent and (parent.nodeType == Node.ELEMENT_NODE)):
for a in filter(_IN_XML_NS, _attrs(parent)):
n = a.localName
if (n not in xmlattrs):
xmlattrs.append(n)
... |
'_do_document(self, node) -> None
Process a document node. documentOrder holds whether the document
element has been encountered such that PIs/comments can be written
as specified.'
| def _do_document(self, node):
| self.documentOrder = _LesserElement
for child in node.childNodes:
if (child.nodeType == Node.ELEMENT_NODE):
self.documentOrder = _Element
self._do_element(child)
self.documentOrder = _GreaterElement
elif (child.nodeType == Node.PROCESSING_INSTRUCTION_NODE):
... |
'_do_text(self, node) -> None
Process a text or CDATA node. Render various special characters
as their C14N entity representations.'
| def _do_text(self, node):
| if (not _in_subset(self.subset, node)):
return
s = string.replace(node.data, '&', '&')
s = string.replace(s, '<', '<')
s = string.replace(s, '>', '>')
s = string.replace(s, '\r', '
')
if s:
self.write(s)
|
'_do_pi(self, node) -> None
Process a PI node. Render a leading or trailing #xA if the
document order of the PI is greater or lesser (respectively)
than the document element.'
| def _do_pi(self, node):
| if (not _in_subset(self.subset, node)):
return
W = self.write
if (self.documentOrder == _GreaterElement):
W('\n')
W('<?')
W(node.nodeName)
s = node.data
if s:
W(' ')
W(s)
W('?>')
if (self.documentOrder == _LesserElement):
W('\n')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.