code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
---|---|---|---|---|---|
return (
isinstance(object, tuple) and
len(object) == 2 and
isinstance(object[0], basestring) and
isinstance(object[1], basestring))
|
def isqref(object)
|
Get whether the object is a I{qualified reference}.
@param object: An object to be tested.
@type object: I{any}
@rtype: boolean
@see: L{qualify}
| 2.360921 | 2.901451 | 0.813704 |
key = schema.tns[1]
existing = self.namespaces.get(key)
if existing is None:
self.children.append(schema)
self.namespaces[key] = schema
else:
existing.root.children += schema.root.children
existing.root.nsprefixes.update(schema.root.nsprefixes)
|
def add(self, schema)
|
Add a schema node to the collection. Schema(s) within the same target
namespace are consolidated.
@param schema: A schema object.
@type schema: (L{Schema})
| 3.354226 | 3.48698 | 0.961928 |
if options.autoblend:
self.autoblend()
for child in self.children:
child.build()
for child in self.children:
child.open_imports(options)
for child in self.children:
child.dereference()
log.debug('loaded:\n%s', self)
merged = self.merge()
log.debug('MERGED:\n%s', merged)
return merged
|
def load(self, options)
|
Load the schema objects for the root nodes.
- de-references schemas
- merge schemas
@param options: An options dictionary.
@type options: L{options.Options}
@return: The merged schema.
@rtype: L{Schema}
| 4.719463 | 4.373377 | 1.079135 |
namespaces = self.namespaces.keys()
for s in self.children:
for ns in namespaces:
tns = s.root.get('targetNamespace')
if tns == ns:
continue
for imp in s.root.getChildren('import'):
if imp.get('namespace') == ns:
continue
imp = Element('import', ns=Namespace.xsdns)
imp.set('namespace', ns)
s.root.append(imp)
return self
|
def autoblend(self)
|
Ensure that all schemas within the collection
import each other which has a blending effect.
@return: self
@rtype: L{SchemaCollection}
| 4.866531 | 4.341719 | 1.120877 |
tns = [None, self.root.get('targetNamespace')]
if tns[1] is not None:
tns[0] = self.root.findPrefix(tns[1])
return tuple(tns)
|
def mktns(self)
|
Make the schema's target namespace.
@return: The namespace representation of the schema's
targetNamespace value.
@rtype: (prefix, uri)
| 4.851052 | 4.430238 | 1.094987 |
self.children = BasicFactory.build(self.root, self)
collated = BasicFactory.collate(self.children)
self.children = collated[0]
self.attributes = collated[2]
self.imports = collated[1]
self.elements = collated[3]
self.types = collated[4]
self.groups = collated[5]
self.agrps = collated[6]
|
def build(self)
|
Build the schema (object graph) using the root node
using the factory.
- Build the graph.
- Collate the children.
| 4.418993 | 3.331284 | 1.326514 |
for item in schema.attributes.items():
if item[0] in self.attributes:
continue
self.all.append(item[1])
self.attributes[item[0]] = item[1]
for item in schema.elements.items():
if item[0] in self.elements:
continue
self.all.append(item[1])
self.elements[item[0]] = item[1]
for item in schema.types.items():
if item[0] in self.types:
continue
self.all.append(item[1])
self.types[item[0]] = item[1]
for item in schema.groups.items():
if item[0] in self.groups:
continue
self.all.append(item[1])
self.groups[item[0]] = item[1]
for item in schema.agrps.items():
if item[0] in self.agrps:
continue
self.all.append(item[1])
self.agrps[item[0]] = item[1]
schema.merged = True
return self
|
def merge(self, schema)
|
Merge the contents from the schema. Only objects not already contained
in this schema's collections are merged. This is to provide for
bidirectional import which produce cyclic includes.
@returns: self
@rtype: L{Schema}
| 1.541191 | 1.514772 | 1.017441 |
all = []
indexes = {}
for child in self.children:
child.content(all)
deplist = DepList()
for x in all:
x.qualify()
midx, deps = x.dependencies()
item = (x, tuple(deps))
deplist.add(item)
indexes[x] = midx
for x, deps in deplist.sort():
midx = indexes.get(x)
if midx is None:
continue
d = deps[midx]
log.debug('(%s) merging %s <== %s', self.tns[1], Repr(x), Repr(d))
x.merge(d)
|
def dereference(self)
|
Instruct all children to perform dereferencing.
| 6.148859 | 6.008932 | 1.023286 |
if ref is None:
return True
else:
return not self.builtin(ref, context)
|
def custom(self, ref, context=None)
|
Get whether the specified reference is B{not} an (xs) builtin.
@param ref: A str or qref.
@type ref: (str|qref)
@return: True if B{not} a builtin, else False.
@rtype: bool
| 7.246388 | 4.4715 | 1.620572 |
w3 = 'http://www.w3.org'
try:
if isqref(ref):
ns = ref[1]
return ref[0] in Factory.tags and ns.startswith(w3)
if context is None:
context = self.root
prefix = splitPrefix(ref)[0]
prefixes = context.findPrefixes(w3, 'startswith')
return prefix in prefixes and ref[0] in Factory.tags
except:
return False
|
def builtin(self, ref, context=None)
|
Get whether the specified reference is an (xs) builtin.
@param ref: A str or qref.
@type ref: (str|qref)
@return: True if builtin, else False.
@rtype: bool
| 7.221863 | 6.29383 | 1.147451 |
self.nodes = []
self.catalog = {}
self.build_catalog(body)
self.update(body)
body.children = self.nodes
return body
|
def process(self, body)
|
Process the specified soap envelope body and replace I{multiref} node
references with the contents of the referenced node.
@param body: A soap envelope body node.
@type body: L{Element}
@return: The processed I{body}
@rtype: L{Element}
| 6.587058 | 6.681854 | 0.985813 |
self.replace_references(node)
for c in node.children:
self.update(c)
return node
|
def update(self, node)
|
Update the specified I{node} by replacing the I{multiref} references
with the contents of the referenced nodes and remove the I{href}
attribute.
@param node: A node to update.
@type node: L{Element}
@return: The updated node
@rtype: L{Element}
| 5.289202 | 5.495322 | 0.962492 |
href = node.getAttribute('href')
if href is None:
return
id = href.getValue()
ref = self.catalog.get(id)
if ref is None:
log.error('soap multiref: %s, not-resolved', id)
return
node.append(ref.children)
node.setText(ref.getText())
for a in ref.attributes:
if a.name != 'id':
node.append(a)
node.remove(href)
|
def replace_references(self, node)
|
Replacing the I{multiref} references with the contents of the
referenced nodes and remove the I{href} attribute. Warning: since
the I{ref} is not cloned,
@param node: A node to update.
@type node: L{Element}
| 5.312006 | 5.255349 | 1.010781 |
for child in body.children:
if self.soaproot(child):
self.nodes.append(child)
id = child.get('id')
if id is None:
continue
key = '#%s' % id
self.catalog[key] = child
|
def build_catalog(self, body)
|
Create the I{catalog} of multiref nodes by id and the list of
non-multiref nodes.
@param body: A soap envelope body node.
@type body: L{Element}
| 5.273501 | 5.520004 | 0.955344 |
root = node.getAttribute('root', ns=soapenc)
if root is None:
return True
else:
return root.value == '1'
|
def soaproot(self, node)
|
Get whether the specified I{node} is a soap encoded root.
This is determined by examining @soapenc:root='1'.
The node is considered to be a root when the attribute
is not specified.
@param node: A node to evaluate.
@type node: L{Element}
@return: True if a soap encoded root.
@rtype: bool
| 7.809624 | 5.490646 | 1.422351 |
result = None
parts = self.split(path)
try:
result = self.root(parts)
if len(parts) > 1:
result = result.resolve(nobuiltin=True)
result = self.branch(result, parts)
result = self.leaf(result, parts)
if resolved:
result = result.resolve(nobuiltin=True)
except PathResolver.BadPath:
log.error('path: "%s", not-found' % path)
return result
|
def find(self, path, resolved=True)
|
Get the definition object for the schema type located at the specified
path.
The path may contain (.) dot notation to specify nested types.
Actually, the path separator is usually a (.) but can be redefined
during contruction.
@param path: A (.) separated path to a schema type.
@type path: basestring
@param resolved: A flag indicating that the fully resolved type
should be returned.
@type resolved: boolean
@return: The found schema I{type}
@rtype: L{xsd.sxbase.SchemaObject}
| 4.684278 | 4.815283 | 0.972794 |
name = splitPrefix(parts[-1])[1]
if name.startswith('@'):
result, path = parent.get_attribute(name[1:])
else:
result, ancestry = parent.get_child(name)
if result is None:
raise PathResolver.BadPath(name)
return result
|
def leaf(self, parent, parts)
|
Find the leaf.
@param parts: A list of path parts.
@type parts: [str,..]
@param parent: The leaf's parent.
@type parent: L{xsd.sxbase.SchemaObject}
@return: The leaf.
@rtype: L{xsd.sxbase.SchemaObject}
| 6.103199 | 6.450682 | 0.946132 |
m = self.altp.match(name)
if m is None:
return qualify(name, self.wsdl.root, self.wsdl.tns)
else:
return (m.group(4), m.group(2))
|
def qualify(self, name)
|
Qualify the name as either:
- plain name
- ns prefixed name (eg: ns0:Person)
- fully ns qualified name (eg: {http://myns-uri}Person)
@param name: The name of an object in the schema.
@type name: str
@return: A qualifed name.
@rtype: qname
| 5.969181 | 7.129961 | 0.837197 |
parts = []
b = 0
while 1:
m = self.splitp.match(s, b)
if m is None:
break
b, e = m.span()
parts.append(s[b:e])
b = e + 1
return parts
|
def split(self, s)
|
Split the string on (.) while preserving any (.) inside the
'{}' alternalte syntax for full ns qualification.
@param s: A plain or qualifed name.
@type s: str
@return: A list of the name's parts.
@rtype: [str,..]
| 2.791638 | 3.089162 | 0.903688 |
if isinstance(x, Frame):
frame = x
else:
frame = Frame(x)
self.stack.append(frame)
log.debug('push: (%s)\n%s', Repr(frame), Repr(self.stack))
return frame
|
def push(self, x)
|
Push an I{object} onto the stack.
@param x: An object to push.
@type x: L{Frame}
@return: The pushed frame.
@rtype: L{Frame}
| 4.08593 | 3.727556 | 1.096142 |
if len(self.stack):
popped = self.stack.pop()
log.debug('pop: (%s)\n%s', Repr(popped), Repr(self.stack))
return popped
else:
log.debug('stack empty, not-popped')
return None
|
def pop(self)
|
Pop the frame at the top of the stack.
@return: The popped frame, else None.
@rtype: L{Frame}
| 4.526266 | 4.593721 | 0.985316 |
name = '@%s' % name
parent = self.top().resolved
if parent is None:
result, ancestry = self.query(name, node)
else:
result, ancestry = self.getchild(name, parent)
if result is None:
return result
if resolved:
result = result.resolve()
return result
|
def findattr(self, name, resolved=True)
|
Find an attribute type definition.
@param name: An attribute name.
@type name: basestring
@param resolved: A flag indicating that the fully resolved type should
be returned.
@type resolved: boolean
@return: The found schema I{type}
@rtype: L{xsd.sxbase.SchemaObject}
| 5.163695 | 5.804049 | 0.889671 |
ref = node.get('type', Namespace.xsins)
if ref is None:
return None
qref = qualify(ref, node, node.namespace())
query = BlindQuery(qref)
return query.execute(self.schema)
|
def known(self, node)
|
resolve type referenced by @xsi:type
| 12.462919 | 9.246509 | 1.347851 |
try:
md = object.__metadata__
known = md.sxtype
return known
except:
pass
|
def known(self, object)
|
get the type specified in the object's metadata
| 16.421556 | 11.649363 | 1.409653 |
if isinstance(s, str):
for c in self.special:
if c in s:
return True
return False
|
def needsEncoding(self, s)
|
Get whether string I{s} contains special characters.
@param s: A string to check.
@type s: str
@return: True if needs encoding.
@rtype: boolean
| 3.793367 | 3.892684 | 0.974486 |
if isinstance(s, str) and self.needsEncoding(s):
for x in self.encodings:
s = re.sub(x[0], x[1], s)
return s
|
def encode(self, s)
|
Encode special characters found in string I{s}.
@param s: A string to encode.
@type s: str
@return: The encoded string.
@rtype: str
| 3.644688 | 3.679051 | 0.99066 |
if isinstance(s, str) and '&' in s:
for x in self.decodings:
s = s.replace(x[0], x[1])
return s
|
def decode(self, s)
|
Decode special characters encodings found in string I{s}.
@param s: A string to decode.
@type s: str
@return: The decoded string.
@rtype: str
| 3.75986 | 4.077389 | 0.922124 |
for ns in self.prefixes:
self.wsdl.root.addPrefix(ns[0], ns[1])
|
def pushprefixes(self)
|
Add our prefixes to the wsdl so that when users invoke methods
and reference the prefixes, the will resolve properly.
| 7.340863 | 4.267928 | 1.720006 |
timer = metrics.Timer()
timer.start()
for port in self.service.ports:
p = self.findport(port)
for op in port.binding.operations.values():
m = p[0].method(op.name)
binding = m.binding.input
method = (m.name, binding.param_defs(m))
p[1].append(method)
metrics.log.debug("method '%s' created: %s", m.name, timer)
p[1].sort()
timer.stop()
|
def addports(self)
|
Look through the list of service ports and construct a list of tuples
where each tuple is used to describe a port and it's list of methods
as: (port, [method]). Each method is tuple: (name, [pdef,..] where
each pdef is a tuple: (param-name, type).
| 6.611104 | 5.332383 | 1.239803 |
for p in self.ports:
if p[0] == p:
return p
p = (port, [])
self.ports.append(p)
return p
|
def findport(self, port)
|
Find and return a port tuple for the specified port.
Created and added when not found.
@param port: A port.
@type port: I{service.Port}
@return: A port tuple.
@rtype: (port, [method])
| 3.835087 | 3.51124 | 1.092231 |
for m in [p[1] for p in self.ports]:
for p in [p[1] for p in m]:
for pd in p:
if pd[1] in self.params:
continue
item = (pd[1], pd[1].resolve())
self.params.append(item)
|
def paramtypes(self)
|
get all parameter types
| 4.85606 | 4.551769 | 1.066851 |
for t in self.wsdl.schema.types.values():
if t in self.params:
continue
if t in self.types:
continue
item = (t, t)
self.types.append(item)
self.types.sort(key=lambda x: x[0].name)
|
def publictypes(self)
|
get all public types
| 4.13242 | 4.00843 | 1.030932 |
used = [ns[0] for ns in self.prefixes]
used += [ns[0] for ns in self.wsdl.root.nsprefixes.items()]
for n in range(0, 1024):
p = 'ns%d' % n
if p not in used:
return p
raise Exception('prefixes exhausted')
|
def nextprefix(self)
|
Get the next available prefix. This means a prefix starting with 'ns'
with a number appended as (ns0, ns1, ..) that is not already defined
on the wsdl document.
| 4.627544 | 4.124074 | 1.122081 |
for ns in Namespace.all:
if u == ns[1]:
return ns[0]
for ns in self.prefixes:
if u == ns[1]:
return ns[0]
raise Exception('ns (%s) not mapped' % u)
|
def getprefix(self, u)
|
Get the prefix for the specified namespace (uri)
@param u: A namespace uri.
@type u: str
@return: The namspace.
@rtype: (prefix, uri).
| 4.588731 | 4.011996 | 1.143753 |
tm = self.options.timeout
url = self.u2opener()
if self.u2ver() < 2.6:
socket.setdefaulttimeout(tm)
return url.open(u2request)
else:
return url.open(u2request, timeout=tm)
|
def u2open(self, u2request)
|
Open a connection.
@param u2request: A urllib2 request.
@type u2request: urllib2.Requet.
@return: The opened file-like urllib2 object.
@rtype: fp
| 4.907978 | 4.806062 | 1.021206 |
if self.urlopener is None:
return u2.build_opener(*self.u2handlers())
else:
return self.urlopener
|
def u2opener(self)
|
Create a urllib opener.
@return: An opener.
@rtype: I{OpenerDirector}
| 6.415697 | 5.845942 | 1.097462 |
handlers = []
handlers.append(u2.ProxyHandler(self.proxy))
return handlers
|
def u2handlers(self)
|
Get a collection of urllib handlers.
@return: A list of handlers to be installed in the opener.
@rtype: [Handler,...]
| 9.965821 | 9.505236 | 1.048456 |
try:
part = u2.__version__.split('.', 1)
n = float('.'.join(part))
return n
except Exception as e:
log.exception(e)
return 0
|
def u2ver(self)
|
Get the major/minor version of the urllib2 lib.
@return: The urllib2 version.
@rtype: float
| 6.077149 | 5.200283 | 1.168619 |
for tag in path.split('/'):
child = parent.getChild(tag)
if child is None:
child = Element(tag, parent)
parent = child
return child
|
def buildPath(self, parent, path)
|
Build the specifed pat as a/b/c where missing intermediate nodes are
built automatically.
@param parent: A parent element on which the path is built.
@type parent: I{Element}
@param path: A simple path separated by (/).
@type path: basestring
@return: The leaf node of I{path}.
@rtype: L{Element}
| 3.307373 | 3.252989 | 1.016718 |
self.prefix = p
if p is not None and u is not None:
self.addPrefix(p, u)
return self
|
def setPrefix(self, p, u=None)
|
Set the element namespace prefix.
@param p: A new prefix for the element.
@type p: basestring
@param u: A namespace URI to be mapped to the prefix.
@type u: basestring
@return: self
@rtype: L{Element}
| 3.338073 | 3.517703 | 0.948936 |
if self.prefix is None:
return self.name
else:
return '%s:%s' % (self.prefix, self.name)
|
def qname(self)
|
Get the B{fully} qualified name of this element
@return: The fully qualified name.
@rtype: basestring
| 2.5588 | 2.490866 | 1.027273 |
if self.parent is not None:
if self in self.parent.children:
self.parent.children.remove(self)
self.parent = None
return self
|
def detach(self)
|
Detach from parent.
@return: This element removed from its parent's
child list and I{parent}=I{None}
@rtype: L{Element}
| 2.552555 | 2.43074 | 1.050114 |
attr = self.getAttribute(name)
if attr is None:
attr = Attribute(name, value)
self.append(attr)
else:
attr.setValue(value)
|
def set(self, name, value)
|
Set an attribute's value.
@param name: The name of the attribute.
@type name: basestring
@param value: The attribute value.
@type value: basestring
@see: __setitem__()
| 2.777073 | 3.023437 | 0.918515 |
if isinstance(value, Text):
self.text = value
else:
self.text = Text(value)
return self
|
def setText(self, value)
|
Set the element's L{Text} content.
@param value: The element's text value.
@type value: basestring
@return: self
@rtype: I{Element}
| 3.261705 | 3.965197 | 0.822583 |
if self.hasText():
self.text = self.text.trim()
return self
|
def trim(self)
|
Trim leading and trailing whitespace.
@return: self
@rtype: L{Element}
| 7.719241 | 5.761312 | 1.339841 |
if isinstance(child, Element):
return child.detach()
if isinstance(child, Attribute):
self.attributes.remove(child)
return None
|
def remove(self, child)
|
Remove the specified child element or attribute.
@param child: A child to remove.
@type child: L{Element}|L{Attribute}
@return: The detached I{child} when I{child} is an element, else None.
@rtype: L{Element}|None
| 4.497772 | 3.097818 | 1.451916 |
if child not in self.children:
raise Exception('child not-found')
index = self.children.index(child)
self.remove(child)
if not isinstance(content, (list, tuple)):
content = (content,)
for node in content:
self.children.insert(index, node.detach())
node.parent = self
index += 1
|
def replaceChild(self, child, content)
|
Replace I{child} with the specified I{content}.
@param child: A child element.
@type child: L{Element}
@param content: An element or collection of elements.
@type content: L{Element} or [L{Element},]
| 3.120188 | 3.172109 | 0.983632 |
if ns is None:
prefix, name = splitPrefix(name)
if prefix is None:
ns = None
else:
ns = self.resolvePrefix(prefix)
for a in self.attributes:
if a.match(name, ns):
return a
return default
|
def getAttribute(self, name, ns=None, default=None)
|
Get an attribute by name and (optional) namespace
@param name: The name of a contained attribute (may contain prefix).
@type name: basestring
@param ns: An optional namespace
@type ns: (I{prefix}, I{name})
@param default: Returned when attribute not-found.
@type default: L{Attribute}
@return: The requested attribute object.
@rtype: L{Attribute}
| 3.145639 | 3.118712 | 1.008634 |
detached = self.children
self.children = []
for child in detached:
child.parent = None
return detached
|
def detachChildren(self)
|
Detach and return this element's children.
@return: The element's children (detached).
@rtype: [L{Element},...]
| 3.41182 | 4.426147 | 0.770833 |
n = self
while n is not None:
if prefix in n.nsprefixes:
return (prefix, n.nsprefixes[prefix])
if prefix in self.specialprefixes:
return (prefix, self.specialprefixes[prefix])
n = n.parent
return default
|
def resolvePrefix(self, prefix, default=Namespace.default)
|
Resolve the specified prefix to a namespace. The I{nsprefixes} is
searched. If not found, it walks up the tree until either resolved or
the top of the tree is reached. Searching up the tree provides for
inherited mappings.
@param prefix: A namespace prefix to resolve.
@type prefix: basestring
@param default: An optional value to be returned when the prefix
cannot be resolved.
@type default: (I{prefix},I{URI})
@return: The namespace that is mapped to I{prefix} in this context.
@rtype: (I{prefix},I{URI})
| 3.084157 | 2.835301 | 1.087771 |
if p in self.nsprefixes:
self.nsprefixes[p] = u
for c in self.children:
c.updatePrefix(p, u)
return self
|
def updatePrefix(self, p, u)
|
Update (redefine) a prefix mapping for the branch.
@param p: A prefix.
@type p: basestring
@param u: A namespace URI.
@type u: basestring
@return: self
@rtype: L{Element}
@note: This method traverses down the entire branch!
| 3.143898 | 2.763601 | 1.137609 |
if prefix in self.nsprefixes:
del self.nsprefixes[prefix]
return self
|
def clearPrefix(self, prefix)
|
Clear the specified prefix from the prefix mappings.
@param prefix: A prefix to clear.
@type prefix: basestring
@return: self
@rtype: L{Element}
| 4.32652 | 4.978148 | 0.869102 |
for item in self.nsprefixes.items():
if item[1] == uri:
prefix = item[0]
return prefix
for item in self.specialprefixes.items():
if item[1] == uri:
prefix = item[0]
return prefix
if self.parent is not None:
return self.parent.findPrefix(uri, default)
else:
return default
|
def findPrefix(self, uri, default=None)
|
Find the first prefix that has been mapped to a namespace URI.
The local mapping is searched, then it walks up the tree until
it reaches the top or finds a match.
@param uri: A namespace URI.
@type uri: basestring
@param default: A default prefix when not found.
@type default: basestring
@return: A mapped prefix.
@rtype: basestring
| 2.392384 | 2.372427 | 1.008412 |
result = []
for item in self.nsprefixes.items():
if self.matcher[match](item[1], uri):
prefix = item[0]
result.append(prefix)
for item in self.specialprefixes.items():
if self.matcher[match](item[1], uri):
prefix = item[0]
result.append(prefix)
if self.parent is not None:
result += self.parent.findPrefixes(uri, match)
return result
|
def findPrefixes(self, uri, match='eq')
|
Find all prefixes that has been mapped to a namespace URI.
The local mapping is searched, then it walks up the tree until
it reaches the top collecting all matches.
@param uri: A namespace URI.
@type uri: basestring
@param match: A matching function L{Element.matcher}.
@type match: basestring
@return: A list of mapped prefixes.
@rtype: [basestring,...]
| 2.41041 | 2.370715 | 1.016744 |
for c in self.children:
c.promotePrefixes()
if self.parent is None:
return
_pref = []
for p, u in self.nsprefixes.items():
if p in self.parent.nsprefixes:
pu = self.parent.nsprefixes[p]
if pu == u:
_pref.append(p)
continue
if p != self.parent.prefix:
self.parent.nsprefixes[p] = u
_pref.append(p)
for x in _pref:
del self.nsprefixes[x]
return self
|
def promotePrefixes(self)
|
Push prefix declarations up the tree as far as possible. Prefix
mapping are pushed to its parent unless the parent has the
prefix mapped to another URI or the parent has the prefix.
This is propagated up the tree until the top is reached.
@return: self
@rtype: L{Element}
| 2.853345 | 2.701656 | 1.056147 |
for c in self.children:
c.refitPrefixes()
if self.prefix is not None:
ns = self.resolvePrefix(self.prefix)
if ns[1] is not None:
self.expns = ns[1]
self.prefix = None
self.nsprefixes = {}
return self
|
def refitPrefixes(self)
|
Refit namespace qualification by replacing prefixes
with explicit namespaces. Also purges prefix mapping table.
@return: self
@rtype: L{Element}
| 4.006483 | 3.676564 | 1.089736 |
branch = [self]
for c in self.children:
branch += c.branch()
return branch
|
def branch(self)
|
Get a flattened representation of the branch.
@return: A flat list of nodes.
@rtype: [L{Element},..]
| 5.191658 | 4.39988 | 1.179954 |
ancestors = []
p = self.parent
while p is not None:
ancestors.append(p)
p = p.parent
return ancestors
|
def ancestors(self)
|
Get a list of ancestors.
@return: A list of ancestors.
@rtype: [L{Element},..]
| 2.407977 | 2.563777 | 0.93923 |
visitor(self)
for c in self.children:
c.walk(visitor)
return self
|
def walk(self, visitor)
|
Walk the branch and call the visitor function
on each node.
@param visitor: A function.
@return: self
@rtype: L{Element}
| 3.588794 | 5.829897 | 0.615585 |
pruned = []
for c in self.children:
c.prune()
if c.isempty(False):
pruned.append(c)
for p in pruned:
self.children.remove(p)
|
def prune(self)
|
Prune the branch of empty nodes.
| 3.106666 | 2.791937 | 1.112728 |
try:
child = self.children[self.pos]
self.pos += 1
return child
except:
raise StopIteration()
|
def next(self)
|
Get the next child.
@return: The next child.
@rtype: L{Element}
@raise StopIterator: At the end.
| 3.734624 | 3.618582 | 1.032068 |
s = set()
for n in self.branch + self.node.ancestors():
if self.permit(n.expns):
s.add(n.expns)
s = s.union(self.pset(n))
return s
|
def getNamespaces(self)
|
Get the I{unique} set of namespaces referenced in the branch.
@return: A set of namespaces.
@rtype: set
| 9.897741 | 9.242819 | 1.070857 |
s = set()
for ns in n.nsprefixes.items():
if self.permit(ns):
s.add(ns[1])
return s
|
def pset(self, n)
|
Convert the nodes nsprefixes into a set.
@param n: A node.
@type n: L{Element}
@return: A set of namespaces.
@rtype: set
| 7.054482 | 5.152127 | 1.369237 |
prefixes = {}
n = 0
for u in self.namespaces:
p = 'ns%d' % n
prefixes[u] = p
n += 1
return prefixes
|
def genPrefixes(self)
|
Generate a I{reverse} mapping of unique prefixes for all namespaces.
@return: A referse dict of prefixes.
@rtype: {u, p}
| 3.913136 | 3.482441 | 1.123676 |
for n in self.branch:
if n.prefix is not None:
ns = n.namespace()
if self.permit(ns):
n.prefix = self.prefixes[ns[1]]
self.refitAttrs(n)
|
def refitNodes(self)
|
Refit (normalize) all of the nodes in the branch.
| 8.728458 | 7.711959 | 1.131808 |
if a.prefix is not None:
ns = a.namespace()
if self.permit(ns):
a.prefix = self.prefixes[ns[1]]
self.refitValue(a)
|
def refitAddr(self, a)
|
Refit (normalize) the attribute.
@param a: An attribute.
@type a: L{Attribute}
| 8.650057 | 9.177567 | 0.942522 |
p, name = splitPrefix(a.getValue())
if p is None:
return
ns = a.resolvePrefix(p)
if self.permit(ns):
u = ns[1]
p = self.prefixes[u]
a.setValue(':'.join((p, name)))
|
def refitValue(self, a)
|
Refit (normalize) the attribute's value.
@param a: An attribute.
@type a: L{Attribute}
| 9.336295 | 9.173231 | 1.017776 |
for n in self.branch:
n.nsprefixes = {}
n = self.node
for u, p in self.prefixes.items():
n.addPrefix(p, u)
|
def refitMappings(self)
|
Refit (normalize) all of the nsprefix mappings.
| 10.063798 | 7.357026 | 1.367917 |
return ns in (None, Namespace.default, Namespace.xsdns, Namespace.xsins, Namespace.xmlns)
|
def skip(self, ns)
|
Get whether the I{ns} is to B{not} be normalized.
@param ns: A namespace.
@type ns: (p,u)
@return: True if to be skipped.
@rtype: boolean
| 19.637136 | 19.44072 | 1.010103 |
if isinstance(name, str) and ':' in name:
return tuple(name.split(':', 1))
else:
return (None, name)
|
def splitPrefix(name)
|
Split the name into a tuple (I{prefix}, I{name}). The first element in
the tuple is I{None} when the name does't have a prefix.
@param name: A node name containing an optional prefix.
@type name: basestring
@return: A tuple containing the (2) parts of I{name}
@rtype: (I{prefix}, I{name})
| 3.07469 | 3.672004 | 0.837333 |
hour = int(match_object.group('hour'))
minute = int(match_object.group('minute'))
second = int(match_object.group('second'))
subsecond = match_object.group('subsecond')
microsecond = 0
if subsecond is not None:
subsecond_denominator = 10.0 ** len(subsecond)
subsecond = int(subsecond)
microsecond = subsecond * (1000000 / subsecond_denominator)
microsecond = int(round(microsecond))
return datetime.time(hour, minute, second, microsecond)
|
def time_from_match(match_object)
|
Create a time object from a regular expression match.
The regular expression match is expected to be from RE_TIME or RE_DATETIME.
@param match_object: The regular expression match.
@type value: B{re}.I{MatchObject}
@return: A date object.
@rtype: B{datetime}.I{time}
| 1.962845 | 2.119386 | 0.926139 |
tz_utc = match_object.group('tz_utc')
tz_sign = match_object.group('tz_sign')
tz_hour = int(match_object.group('tz_hour') or 0)
tz_minute = int(match_object.group('tz_minute') or 0)
tz_second = int(match_object.group('tz_second') or 0)
tzinfo = None
if tz_utc is not None:
tzinfo = UtcTimezone()
elif tz_sign is not None:
tz_delta = datetime.timedelta(hours=tz_hour,
minutes=tz_minute,
seconds=tz_second)
if tz_delta == datetime.timedelta():
tzinfo = UtcTimezone()
else:
tz_multiplier = int('%s1' % (tz_sign, ))
tz_delta = tz_multiplier * tz_delta
tzinfo = FixedOffsetTimezone(tz_delta)
return tzinfo
|
def tzinfo_from_match(match_object)
|
Create a timezone information object from a regular expression match.
The regular expression match is expected to be from RE_DATE, RE_TIME or
RE_DATETIME.
@param match_object: The regular expression match.
@type value: B{re}.I{MatchObject}
@return: A timezone information object.
@rtype: B{datetime}.I{tzinfo}
| 1.998757 | 2.138054 | 0.934849 |
match_result = RE_DATE.match(value)
if match_result is None:
raise ValueError('date data has invalid format "%s"' % value)
value = date_from_match(match_result)
return value
|
def parse(value)
|
Parse the string date.
This supports the subset of ISO8601 used by xsd:date, but is lenient
with what is accepted, handling most reasonable syntax.
Any timezone is parsed but ignored because a) it's meaningless without
a time and b) B{datetime}.I{date} does not support a tzinfo property.
@param value: A date string.
@type value: str
@return: A date object.
@rtype: B{datetime}.I{date}
| 5.328262 | 5.837793 | 0.912719 |
match_result = RE_TIME.match(value)
if match_result is None:
raise ValueError('date data has invalid format "%s"' % (value, ))
date = time_from_match(match_result)
tzinfo = tzinfo_from_match(match_result)
value = date.replace(tzinfo=tzinfo)
return value
|
def parse(value)
|
Parse the string date.
This supports the subset of ISO8601 used by xsd:time, but is lenient
with what is accepted, handling most reasonable syntax.
@param value: A time string.
@type value: str
@return: A time object.
@rtype: B{datetime}.I{time}
| 4.378245 | 4.513976 | 0.969931 |
match_result = RE_DATETIME.match(value)
if match_result is None:
raise ValueError('date data has invalid format "%s"' % (value, ))
date = date_from_match(match_result)
time = time_from_match(match_result)
tzinfo = tzinfo_from_match(match_result)
value = datetime.datetime.combine(date, time)
value = value.replace(tzinfo=tzinfo)
return value
|
def parse(value)
|
Parse the string datetime.
This supports the subset of ISO8601 used by xsd:dateTime, but is
lenient with what is accepted, handling most reasonable syntax.
@param value: A datetime string.
@type value: str
@return: A datetime object.
@rtype: B{datetime}.I{datetime}
| 2.922866 | 2.981765 | 0.980247 |
sign = '+'
if self.__offset < datetime.timedelta():
sign = '-'
# total_seconds was introduced in Python 2.7
if hasattr(self.__offset, 'total_seconds'):
total_seconds = self.__offset.total_seconds()
else:
total_seconds = (self.__offset.days * 24 * 60 * 60) + \
(self.__offset.seconds) + \
(self.__offset.microseconds / 1000000.0)
hours = total_seconds // (60 * 60)
total_seconds -= hours * 60 * 60
minutes = total_seconds // 60
total_seconds -= minutes * 60
seconds = total_seconds // 1
total_seconds -= seconds
if seconds:
return '%s%02d:%02d:%02d' % (sign, hours, minutes, seconds)
else:
return '%s%02d:%02d' % (sign, hours, minutes)
|
def tzname(self, dt)
|
http://docs.python.org/library/datetime.html#datetime.tzinfo.tzname
| 1.772768 | 1.711417 | 1.035848 |
if self.__is_daylight_time(dt):
return self.__dst_offset
else:
return self.__offset
|
def utcoffset(self, dt)
|
http://docs.python.org/library/datetime.html#datetime.tzinfo.utcoffset
| 5.701178 | 4.236423 | 1.345753 |
if self.__is_daylight_time(dt):
return self.__dst_offset - self.__offset
else:
return datetime.timedelta(0)
|
def dst(self, dt)
|
http://docs.python.org/library/datetime.html#datetime.tzinfo.dst
| 5.952972 | 4.82044 | 1.234944 |
if self.__is_daylight_time(dt):
return time.tzname[1]
else:
return time.tzname[0]
|
def tzname(self, dt)
|
http://docs.python.org/library/datetime.html#datetime.tzinfo.tzname
| 3.58078 | 3.058743 | 1.170671 |
for item in a:
setattr(b, item[0], item[1])
b.__metadata__ = b.__metadata__
return b
|
def merge(a, b)
|
Merge all attributes and metadata from I{a} to I{b}.
@param a: A I{source} object
@type a: L{Object}
@param b: A I{destination} object
@type b: L{Object}
| 7.818018 | 6.70823 | 1.165437 |
n = 0
for a in sobject.__keylist__:
v = getattr(sobject, a)
if v is None:
continue
if isinstance(v, Object):
n += footprint(v)
continue
if hasattr(v, '__len__'):
if len(v):
n += 1
continue
n += 1
return n
|
def footprint(sobject)
|
Get the I{virtual footprint} of the object.
This is really a count of the attributes in the branch with a significant
value.
@param sobject: A suds object.
@type sobject: L{Object}
@return: The branch footprint.
@rtype: int
| 2.814983 | 2.727205 | 1.032186 |
history = []
return self.process(object, history, indent)
|
def tostr(self, object, indent=-2)
|
get s string representation of object
| 13.384903 | 11.728909 | 1.141189 |
if object is None:
return 'None'
if isinstance(object, Object):
if len(object) == 0:
return '<empty>'
else:
return self.print_object(object, h, n+2, nl)
if isinstance(object, dict):
if len(object) == 0:
return '<empty>'
else:
return self.print_dictionary(object, h, n+2, nl)
if isinstance(object, (list, tuple)):
if len(object) == 0:
return '<empty>'
else:
return self.print_collection(object, h, n+2)
if isinstance(object, basestring):
return '"%s"' % tostr(object)
return '%s' % tostr(object)
|
def process(self, object, h, n=0, nl=False)
|
print object using the specified indent (n) and newline (nl).
| 2.014606 | 1.923453 | 1.04739 |
s = []
cls = d.__class__
md = d.__metadata__
if d in h:
s.append('(')
s.append(cls.__name__)
s.append(')')
s.append('...')
return ''.join(s)
h.append(d)
if nl:
s.append('\n')
s.append(self.indent(n))
if cls != Object:
s.append('(')
if isinstance(d, Facade):
s.append(md.facade)
else:
s.append(cls.__name__)
s.append(')')
s.append('{')
for item in d:
if self.exclude(d, item):
continue
item = self.unwrap(d, item)
s.append('\n')
s.append(self.indent(n+1))
if isinstance(item[1], (list, tuple)):
s.append(item[0])
s.append('[]')
else:
s.append(item[0])
s.append(' = ')
s.append(self.process(item[1], h, n, True))
s.append('\n')
s.append(self.indent(n))
s.append('}')
h.pop()
return ''.join(s)
|
def print_object(self, d, h, n, nl=False)
|
print complex using the specified indent (n) and newline (nl).
| 2.389156 | 2.3538 | 1.015021 |
i = 0
for x in s:
if x in filter:
d.insert(i, x)
i += 1
|
def prepend(cls, d, s, filter=Filter())
|
Prepend schema object's from B{s}ource list to
the B{d}estination list while applying the filter.
@param d: The destination list.
@type d: list
@param s: The source list.
@type s: list
@param filter: A filter that allows items to be prepended.
@type filter: L{Filter}
| 3.898466 | 4.131884 | 0.943508 |
for item in s:
if item in filter:
d.append(item)
|
def append(cls, d, s, filter=Filter())
|
Append schema object's from B{s}ource list to
the B{d}estination list while applying the filter.
@param d: The destination list.
@type d: list
@param s: The source list.
@type s: list
@param filter: A filter that allows items to be appended.
@type filter: L{Filter}
| 5.482504 | 4.847366 | 1.131027 |
result = []
for child, ancestry in self:
if child.isattr() and child in filter:
result.append((child, ancestry))
return result
|
def attributes(self, filter=Filter())
|
Get only the attribute content.
@param filter: A filter to constrain the result.
@type filter: L{Filter}
@return: A list of tuples (attr, ancestry)
@rtype: [(L{SchemaObject}, [L{SchemaObject},..]),..]
| 5.759252 | 4.116547 | 1.399049 |
for child, ancestry in self.attributes():
if child.name == name:
return (child, ancestry)
return (None, [])
|
def get_attribute(self, name)
|
Get (find) a I{non-attribute} attribute by name.
@param name: A attribute name.
@type name: str
@return: A tuple: the requested (attribute, ancestry).
@rtype: (L{SchemaObject}, [L{SchemaObject},..])
| 5.014562 | 3.642627 | 1.376633 |
for child, ancestry in self.children():
if child.any() or child.name == name:
return (child, ancestry)
return (None, [])
|
def get_child(self, name)
|
Get (find) a I{non-attribute} child by name.
@param name: A child name.
@type name: str
@return: A tuple: the requested (child, ancestry).
@rtype: (L{SchemaObject}, [L{SchemaObject},..])
| 6.017028 | 4.816213 | 1.249328 |
ns = self.schema.tns
if ns[0] is None:
ns = (prefix, ns[1])
return ns
|
def namespace(self, prefix=None)
|
Get this properties namespace
@param prefix: The default prefix.
@type prefix: str
@return: The schema's target namespace
@rtype: (I{prefix},I{URI})
| 8.32955 | 6.778011 | 1.228908 |
max = self.max
if max is None:
max = '1'
if max.isdigit():
return (int(max) > 1)
else:
return max == 'unbounded'
|
def unbounded(self)
|
Get whether this node is unbounded I{(a collection)}
@return: True if unbounded, else False.
@rtype: boolean
| 4.534019 | 4.121925 | 1.099976 |
if not len(classes):
classes = (self.__class__,)
if self.qname == qref and self.__class__ in classes:
return self
for c in self.rawchildren:
p = c.find(qref, classes)
if p is not None:
return p
return None
|
def find(self, qref, classes=())
|
Find a referenced type in self or children.
@param qref: A qualified reference.
@type qref: qref
@param classes: A list of classes used to qualify the match.
@type classes: [I{class},...]
@return: The referenced type.
@rtype: L{SchemaObject}
@see: L{qualify()}
| 2.966839 | 3.146916 | 0.942777 |
defns = self.root.defaultNamespace()
if Namespace.none(defns):
defns = self.schema.tns
for a in self.autoqualified():
ref = getattr(self, a)
if ref is None:
continue
if isqref(ref):
continue
qref = qualify(ref, self.root, defns)
log.debug('%s, convert %s="%s" to %s', self.id, a, ref, qref)
setattr(self, a, qref)
|
def qualify(self)
|
Convert attribute values, that are references to other
objects, into I{qref}. Qualfied using default document namespace.
Since many wsdls are written improperly: when the document does
not define a default namespace, the schema target namespace is used
to qualify references.
| 6.718792 | 4.70319 | 1.428561 |
other.qualify()
for n in ('name',
'qname',
'min',
'max',
'default',
'type',
'nillable',
'form_qualified',):
if getattr(self, n) is not None:
continue
v = getattr(other, n)
if v is None:
continue
setattr(self, n, v)
|
def merge(self, other)
|
Merge another object as needed.
| 4.282117 | 4.067611 | 1.052735 |
if collection is None:
collection = []
if history is None:
history = []
if self in history:
return collection
history.append(self)
if self in filter:
collection.append(self)
for c in self.rawchildren:
c.content(collection, filter, history[:])
return collection
|
def content(self, collection=None, filter=Filter(), history=None)
|
Get a I{flattened} list of this nodes contents.
@param collection: A list to fill.
@type collection: list
@param filter: A filter used to constrain the result.
@type filter: L{Filter}
@param history: The history list used to prevent cyclic dependency.
@type history: list
@return: The filled list.
@rtype: list
| 3.221038 | 2.86431 | 1.124542 |
if history is None:
history = []
if self in history:
return '%s ...' % Repr(self)
history.append(self)
tab = '%*s' % (indent * 3, '')
result = []
result.append('%s<%s' % (tab, self.id))
for n in self.description():
if not hasattr(self, n):
continue
v = getattr(self, n)
if v is None:
continue
result.append(' %s="%s"' % (n, v))
if len(self):
result.append('>')
for c in self.rawchildren:
result.append('\n')
result.append(c.str(indent+1, history[:]))
if c.isattr():
result.append('@')
result.append('\n%s' % tab)
result.append('</%s>' % self.__class__.__name__)
else:
result.append(' />')
return ''.join(result)
|
def str(self, indent=0, history=None)
|
Get a string representation of this object.
@param indent: The indent.
@type indent: int
@return: A string.
@rtype: str
| 2.66838 | 2.680767 | 0.995379 |
if self.matcher.match(node):
list.append(node)
self.limit -= 1
if self.limit == 0:
return
for c in node.rawchildren:
self.find(c, list)
return self
|
def find(self, node, list)
|
Traverse the tree looking for matches.
@param node: A node to match on.
@type node: L{SchemaObject}
@param list: A list to fill.
@type list: list
| 4.163347 | 4.405737 | 0.944983 |
if len(duration) == 1:
arg = [x[0] for x in duration.items()]
if not arg[0] in self.units:
raise Exception('must be: %s' % str(self.units))
self.duration = arg
return self
|
def setduration(self, **duration)
|
Set the caching duration which defines how long the
file will be cached.
@param duration: The cached file duration which defines how
long the file will be cached. A duration=0 means forever.
The duration may be: (months|weeks|days|hours|minutes|seconds).
@type duration: {unit:value}
| 4.468772 | 4.78948 | 0.933039 |
try:
if not os.path.isdir(self.location):
os.makedirs(self.location)
except:
log.debug(self.location, exc_info=1)
return self
|
def mktmp(self)
|
Make the I{location} directory if it doesn't already exits.
| 3.420873 | 2.700191 | 1.266901 |
if self.duration[1] < 1:
return
created = dt.fromtimestamp(os.path.getctime(fn))
d = {self.duration[0]: self.duration[1]}
expired = created+timedelta(**d)
if expired < dt.now():
log.debug('%s expired, deleted', fn)
os.remove(fn)
|
def validate(self, fn)
|
Validate that the file has not expired based on the I{duration}.
@param fn: The file name.
@type fn: str
| 4.639059 | 4.028209 | 1.151643 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.