code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
data = {'amount': amount, 'address': address, 'currency': currency}
response = self._post("ripple_withdrawal/", data=data,
return_json=True)
return self._expect_true(response) | def ripple_withdrawal(self, amount, address, currency) | Returns true if successful. | 4.035717 | 3.751539 | 1.07575 |
data = {'amount': amount, 'address': address}
if destination_tag:
data['destination_tag'] = destination_tag
return self._post("xrp_withdrawal/", data=data, return_json=True,
version=2)["id"] | def xrp_withdrawal(self, amount, address, destination_tag=None) | Sends xrps to another xrp wallet specified by address. Returns withdrawal id. | 3.654756 | 3.318579 | 1.101301 |
data = {'amount': amount,
'currency': currency,}
if subaccount is not None:
data['subAccount'] = subaccount
return self._post("transfer-to-main/", data=data, return_json=True,
version=2) | def transfer_to_main(self, amount, currency, subaccount=None) | Returns dictionary with status.
subaccount has to be the numerical id of the subaccount, not the name | 3.546571 | 3.331179 | 1.064659 |
y_hat = librosa.core.resample(self.y, self.sr, target_sr)
return Sound(y_hat, target_sr) | def resample(self, target_sr) | Returns a new sound with a samplerate of target_sr. | 3.360728 | 2.93383 | 1.145509 |
from IPython.display import Audio
return Audio(data=self.y, rate=self.sr) | def as_ipywidget(self) | Provides an IPywidgets player that can be used in a notebook. | 6.684381 | 5.147866 | 1.298476 |
y, sr = librosa.load(filename, sr=sr)
return cls(y, sr) | def from_file(cls, filename, sr=22050) | Loads an audiofile, uses sr=22050 by default. | 2.380264 | 2.269118 | 1.048982 |
if not hasattr(self, '_it'):
class ChunkIterator(object):
def __iter__(iter):
return iter
def __next__(iter):
try:
chunk = self._next_chunk()
except StopIteration:
... | def chunks(self) | Returns a chunk iterator over the sound. | 3.989844 | 3.522602 | 1.132641 |
freq = numpy.fft.rfft(chunk)
N = len(freq)
shifted_freq = numpy.zeros(N, freq.dtype)
S = numpy.round(shift if shift > 0 else N + shift, 0)
s = N - S
shifted_freq[:S] = freq[s:]
shifted_freq[S:] = freq[:s]
shifted_chunk = numpy.fft.irfft(shifte... | def pitch_shifter(self, chunk, shift) | Pitch-Shift the given chunk by shift semi-tones. | 2.904742 | 2.914004 | 0.996821 |
start = self._i2
end = min(self._i2 + self._N, len(self._sy) - (self._N + self._H))
if start >= end:
raise StopIteration
# The not so clean code below basically implements a phase vocoder
out = numpy.zeros(self._N, dtype=numpy.complex)
while self._... | def _time_stretcher(self, stretch_factor) | Real time time-scale without pitch modification.
:param int i: index of the beginning of the chunk to stretch
:param float stretch_factor: audio scale factor (if > 1 speed up the sound else slow it down)
.. warning:: This method needs to store the phase computed from the previous c... | 3.181824 | 3.134835 | 1.014989 |
(MID, END, CONT, LAST, ROOT) = (u'|-- ', u'`-- ', u'| ', u' ', u'')
def rec(x, indent, sym):
line = indent + sym + show(x)
xs = kids(x)
if len(xs) == 0:
return line
else:
if sym == MID:
next_indent = indent + CONT
eli... | def pretty_tree(x, kids, show) | (a, (a -> list(a)), (a -> str)) -> str
Returns a pseudographic tree representation of x similar to the tree command
in Unix. | 3.076451 | 3.42443 | 0.898383 |
def compile_spec(spec):
name, args = spec
return name, re.compile(*args)
compiled = [compile_spec(s) for s in specs]
def match_specs(specs, str, i, position):
line, pos = position
for type, regexp in specs:
m = regexp.match(str, i)
if m is not ... | def make_tokenizer(specs) | [(str, (str, int?))] -> (str -> Iterable(Token)) | 2.858832 | 2.802692 | 1.02003 |
if s.pos >= len(tokens):
return None, s
else:
raise NoParseError(u'should have reached <EOF>', s) | def finished(tokens, s) | Parser(a, None)
Throws an exception if any tokens are left in the input unparsed. | 11.552857 | 10.272532 | 1.124636 |
@Parser
def _many(tokens, s):
res = []
try:
while True:
(v, s) = p.run(tokens, s)
res.append(v)
except NoParseError, e:
return res, State(s.pos, e.state.max)
_many.name = u'{ %s }' % p.name
return _many | def many(p) | Parser(a, b) -> Parser(a, [b])
Returns a parser that infinitely applies the parser p to the input sequence
of tokens while it successfully parsers them. The resulting parser returns a
list of parsed values. | 6.395013 | 6.190862 | 1.032976 |
@Parser
def _some(tokens, s):
if s.pos >= len(tokens):
raise NoParseError(u'no tokens left in the stream', s)
else:
t = tokens[s.pos]
if pred(t):
pos = s.pos + 1
s2 = State(pos, max(pos, s.max))
if debug:
... | def some(pred) | (a -> bool) -> Parser(a, a)
Returns a parser that parses a token if it satisfies a predicate pred. | 3.9609 | 3.963637 | 0.99931 |
name = getattr(value, 'name', value)
return some(lambda t: t == value).named(u'(a "%s")' % (name,)) | def a(value) | Eq(a) -> Parser(a, a)
Returns a parser that parses a token that is equal to the value value. | 11.969766 | 11.581596 | 1.033516 |
@Parser
def _oneplus(tokens, s):
(v1, s2) = p.run(tokens, s)
(v2, s3) = many(p).run(tokens, s2)
return [v1] + v2, s3
_oneplus.name = u'(%s , { %s })' % (p.name, p.name)
return _oneplus | def oneplus(p) | Parser(a, b) -> Parser(a, [b])
Returns a parser that applies the parser p one or more times. | 4.822523 | 4.430807 | 1.088407 |
@Parser
def f(tokens, s):
return suspension().run(tokens, s)
return f | def with_forward_decls(suspension) | (None -> Parser(a, b)) -> Parser(a, b)
Returns a parser that computes itself lazily as a result of the suspension
provided. It is needed when some parsers contain forward references to
parsers defined later and such references are cyclic. See examples for more
details. | 17.382368 | 15.889873 | 1.093927 |
f = getattr(p, 'run', p)
if debug:
setattr(self, '_run', f)
else:
setattr(self, 'run', f)
self.named(getattr(p, 'name', p.__doc__)) | def define(self, p) | Defines a parser wrapped into this object. | 5.794494 | 4.914608 | 1.179035 |
if debug:
log.debug(u'trying %s' % self.name)
return self._run(tokens, s) | def run(self, tokens, s) | Sequence(a), State -> (b, State)
Runs a parser wrapped into this object. | 7.918938 | 7.833138 | 1.010953 |
try:
(tree, _) = self.run(tokens, State())
return tree
except NoParseError, e:
max = e.state.max
if len(tokens) > max:
tok = tokens[max]
else:
tok = u'<EOF>'
raise NoParseError(u'%s: %s' % (e... | def parse(self, tokens) | Sequence(a) -> b
Applies the parser to a sequence of tokens producing a parsing result.
It provides a way to invoke a parser hiding details related to the
parser state. Also it makes error messages more readable by specifying
the position of the rightmost token that has been reached. | 4.432936 | 4.377189 | 1.012736 |
@Parser
def _bind(tokens, s):
(v, s2) = self.run(tokens, s)
return f(v).run(tokens, s2)
_bind.name = u'(%s >>=)' % (self.name,)
return _bind | def bind(self, f) | Parser(a, b), (b -> Parser(a, c)) -> Parser(a, c)
NOTE: A monadic bind function. It is used internally to implement other
combinators. Functions bind and pure make the Parser a Monad. | 8.778764 | 7.257623 | 1.209592 |
self.is_done.clear() # hold is_done until the sound is played
if self.sr != sound.sr:
raise ValueError('You can only play sound with a samplerate of {} (here {}). Use the Sound.resample method for instance.', self.sr, sound.sr)
if sound in self.sounds:
self.rem... | def play(self, sound) | Adds and plays a new Sound to the Sampler.
:param sound: sound to play
.. note:: If the sound is already playing, it will restart from the beginning. | 6.671897 | 7.163206 | 0.931412 |
with self.chunk_available:
sound.playing = False
self.sounds.remove(sound) | def remove(self, sound) | Remove a currently played sound. | 11.864701 | 10.582732 | 1.121138 |
with self.chunk_available:
while True:
playing_sounds = [s for s in self.sounds if s.playing]
chunks = []
for s in playing_sounds:
try:
chunks.append(next(s.chunks))
except StopI... | def next_chunks(self) | Gets a new chunk from all played sound and mix them together. | 4.84423 | 4.047424 | 1.196867 |
self.running = True
def chunks_producer():
while self.running:
self.chunks.put(self.next_chunks())
t = Thread(target=chunks_producer)
t.start()
with self.BackendStream(samplerate=self.sr, channels=1) as stream:
while self.runnin... | def run(self) | Play loop, i.e. send all sound chunk by chunk to the soundcard. | 5.161837 | 4.283437 | 1.205069 |
root = Element('UsernameToken', ns=wssens)
u = Element('Username', ns=wssens)
u.setText(self.username)
root.append(u)
p = Element('Password', ns=wssens)
p.setText(self.password)
if self.password_digest:
p.set("Type", wsdigest)
p.se... | def xml(self) | Get xml representation of the object.
@return: The root node.
@rtype: L{Element} | 2.803912 | 2.810373 | 0.997701 |
ns = attr.namespace()
skip = (
Namespace.xmlns[1],
'http://schemas.xmlsoap.org/soap/encoding/',
'http://schemas.xmlsoap.org/soap/envelope/',
'http://www.w3.org/2003/05/soap-envelope',
)
return ( Namespace.xs(ns) or ns[1] in skip ) | def skip(self, attr) | Get whether to skip (filter-out) the specified attribute.
@param attr: An attribute.
@type attr: I{Attribute}
@return: True if should be skipped.
@rtype: bool | 4.126132 | 4.11469 | 1.002781 |
sorted = []
processed = set()
for key, deps in dependency_tree.iteritems():
_sort_r(sorted, processed, key, deps, dependency_tree)
return sorted | def dependency_sort(dependency_tree) | Sorts items 'dependencies first' in a given dependency tree.
A dependency tree is a dictionary mapping an object to a collection its
dependency objects.
Result is a properly sorted list of items, where each item is a 2-tuple
containing an object and its dependency list, as given in the input
depen... | 4.934414 | 6.803833 | 0.72524 |
if key in processed:
return
processed.add(key)
for dep_key in deps:
dep_deps = dependency_tree.get(dep_key)
if dep_deps is None:
log.debug('"%s" not found, skipped', Repr(dep_key))
continue
_sort_r(sorted, processed, dep_key, dep_deps, dependency_... | def _sort_r(sorted, processed, key, deps, dependency_tree) | Recursive topological sort implementation. | 2.586328 | 2.665635 | 0.970248 |
cached = self.resolved_cache.get(nobuiltin)
if cached is not None:
return cached
resolved = self.__resolve_type(nobuiltin)
self.resolved_cache[nobuiltin] = resolved
return resolved | def resolve(self, nobuiltin=False) | Resolve the node's type reference and return the referenced type node.
Returns self if the type is defined locally, e.g. as a <complexType>
subnode. Otherwise returns the referenced external node.
@param nobuiltin: Flag indicating whether resolving to XSD built-in
types should not ... | 3.098911 | 3.505009 | 0.884138 |
# There is no need for a recursive implementation here since a node can
# reference an external type node but XSD specification explicitly
# states that that external node must not be a reference to yet another
# node.
qref = self.qref()
if qref is None:
... | def __resolve_type(self, nobuiltin=False) | Private resolve() worker without any result caching.
@param nobuiltin: Flag indicating whether resolving to XSD built-in
types should not be allowed.
@return: The resolved (true) type.
@rtype: L{SchemaObject} | 8.439309 | 8.527486 | 0.98966 |
if self.type is None and self.ref is None and self.root.isempty():
self.type = self.anytype() | def implany(self) | Set the type to <xsd:any/> when implicit.
An element has an implicit <xsd:any/> type when it has no body and no
explicitly defined type.
@return: self
@rtype: L{Element} | 10.817488 | 9.495407 | 1.139234 |
e = self.__deref()
if e is not None:
return e.namespace(prefix)
return super(Element, self).namespace() | def namespace(self, prefix=None) | Get this schema element's target namespace.
In case of reference elements, the target namespace is defined by the
referenced and not the referencing element node.
@param prefix: The default prefix.
@type prefix: str
@return: The schema element's target namespace
@rtype:... | 6.246705 | 8.787756 | 0.710842 |
if self.opened:
return
self.opened = True
log.debug("%s, importing ns='%s', location='%s'", self.id, self.ns[1],
self.location)
result = self.__locate()
if result is None:
if self.location is None:
log.debug("imported s... | def open(self, options, loaded_schemata) | Open and import the referenced schema.
@param options: An options dictionary.
@type options: L{options.Options}
@param loaded_schemata: Already loaded schemata cache (URL --> Schema).
@type loaded_schemata: dict
@return: The referenced schema.
@rtype: L{Schema} | 4.754375 | 4.544425 | 1.046199 |
if self.ns[1] != self.schema.tns[1]:
return self.schema.locate(self.ns) | def __locate(self) | Find the schema locally. | 11.414183 | 7.76327 | 1.47028 |
try:
reader = DocumentReader(options)
d = reader.open(url)
root = d.root()
root.set("url", url)
return self.schema.instance(root, url, loaded_schemata, options)
except TransportError:
msg = "import schema (%s) at (%s), fail... | def __download(self, url, loaded_schemata, options) | Download the schema. | 5.702151 | 5.624776 | 1.013756 |
TNS = "targetNamespace"
tns = root.get(TNS)
if tns is None:
tns = self.schema.tns[1]
root.set(TNS, tns)
else:
if self.schema.tns[1] != tns:
raise Exception, "%s mismatch" % TNS | def __applytns(self, root) | Make sure included schema has the same target namespace. | 3.733698 | 3.007693 | 1.241383 |
if not self.__resolved:
self.do_resolve(definitions)
self.__resolved = True | def resolve(self, definitions) | Resolve named references to other WSDL objects.
Can be safely called multiple times.
@param definitions: A definitions object.
@type definitions: L{Definitions} | 5.200476 | 6.909801 | 0.752623 |
tns = root.get("targetNamespace")
prefix = root.findPrefix(tns)
if prefix is None:
log.debug("warning: tns (%s), not mapped to prefix", tns)
prefix = "tns"
return (prefix, tns) | def mktns(self, root) | Get/create the target namespace. | 5.475588 | 5.018282 | 1.091128 |
for imp in self.imports:
imp.load(self, imported_definitions) | def open_imports(self, imported_definitions) | Import the I{imported} WSDLs. | 6.759464 | 5.659167 | 1.194427 |
bindings = {
"document/literal": Document(self),
"rpc/literal": RPC(self),
"rpc/encoded": Encoded(self)}
for p in service.ports:
binding = p.binding
ptype = p.binding.type
operations = p.binding.type.operations.values()
... | def add_methods(self, service) | Build method view for service. | 4.337395 | 4.350185 | 0.99706 |
definitions.types += d.types
definitions.messages.update(d.messages)
definitions.port_types.update(d.port_types)
definitions.bindings.update(d.bindings)
self.imported = d
log.debug("imported (WSDL):\n%s", d) | def import_definitions(self, definitions, d) | Import/merge WSDL definitions. | 4.99566 | 3.516247 | 1.420736 |
if not definitions.types:
root = Element("types", ns=wsdlns)
definitions.root.insert(root)
types = Types(root, definitions)
definitions.types.append(types)
else:
types = definitions.types[-1]
types.root.append(d.root)
l... | def import_schema(self, definitions, d) | Import schema as <types/> content. | 5.533428 | 5.277761 | 1.048442 |
try:
return self.operations[name]
except Exception, e:
raise MethodNotFound(name) | def operation(self, name) | Shortcut used to get a contained operation by name.
@param name: An operation name.
@type name: str
@return: The named operation.
@rtype: Operation
@raise L{MethodNotFound}: When not found. | 4.73238 | 4.664006 | 1.01466 |
for ns in (soapns, soap12ns):
sr = self.root.getChild("binding", ns=ns)
if sr is not None:
return sr | def soaproot(self) | Get the soap:binding. | 6.89195 | 5.425249 | 1.270347 |
self.__resolveport(definitions)
for op in self.operations.values():
self.__resolvesoapbody(definitions, op)
self.__resolveheaders(definitions, op)
self.__resolvefaults(definitions, op) | def do_resolve(self, definitions) | Resolve named references to other WSDL objects. This includes
cross-linking information (from) the portType (to) the I{SOAP} protocol
information on the binding for each operation.
@param definitions: A definitions object.
@type definitions: L{Definitions} | 5.603264 | 4.512428 | 1.24174 |
ref = qualify(self.type, self.root, definitions.tns)
port_type = definitions.port_types.get(ref)
if port_type is None:
raise Exception("portType '%s', not-found" % (self.type,))
# Later on we will require access to the message data referenced by
# this port_t... | def __resolveport(self, definitions) | Resolve port_type reference.
@param definitions: A definitions object.
@type definitions: L{Definitions} | 10.890443 | 11.039663 | 0.986483 |
for p in self.ports:
if p.name == name:
return p | def port(self, name) | Locate a port by name.
@param name: A port name.
@type name: str
@return: The port object.
@rtype: L{Port} | 3.341351 | 5.068485 | 0.659241 |
filtered = []
for p in self.ports:
ref = qualify(p.binding, self.root, definitions.tns)
binding = definitions.bindings.get(ref)
if binding is None:
raise Exception("binding '%s', not-found" % (p.binding,))
if binding.soap is None:
... | def do_resolve(self, definitions) | Resolve named references to other WSDL objects. Ports without SOAP
bindings are discarded.
@param definitions: A definitions object.
@type definitions: L{Definitions} | 8.976488 | 7.706214 | 1.164838 |
fn = cls.tags.get(root.name)
if fn is not None:
return fn(root, definitions) | def create(cls, root, definitions) | Create an object based on the root tag name.
@param root: An XML root element.
@type root: L{Element}
@param definitions: A definitions object.
@type definitions: L{Definitions}
@return: The created object.
@rtype: L{WObject} | 5.340991 | 5.502786 | 0.970598 |
soapenv = replyroot.getChild("Envelope", envns)
soapenv.promotePrefixes()
soapbody = soapenv.getChild("Body", envns)
soapbody = self.multiref.process(soapbody)
nodes = self.replycontent(method, soapbody)
rtypes = self.returned_types(method)
if len(rtypes)... | def get_reply(self, method, replyroot) | Process the I{reply} for the specified I{method} by unmarshalling it
into into Python object(s).
@param method: The name of the invoked method.
@type method: str
@param replyroot: The reply XML root node received after invoking the
specified method.
@type replyroot: ... | 5.411273 | 5.614103 | 0.963871 |
resolved = rt.resolve(nobuiltin=True)
unmarshaller = self.unmarshaller()
return [unmarshaller.process(node, resolved) for node in nodes] | def replylist(self, rt, nodes) | Construct a I{list} reply.
Called for replies with possible multiple occurrences.
@param rt: The return I{type}.
@type rt: L{suds.xsd.sxbase.SchemaObject}
@param nodes: A collection of XML nodes.
@type nodes: [L{Element},...]
@return: A list of I{unmarshalled} objects.
... | 11.212152 | 10.053699 | 1.115226 |
marshaller = self.marshaller()
if isinstance(object, (list, tuple)):
return [self.mkheader(method, hdef, item) for item in object]
content = Content(tag=hdef[0], value=object, type=hdef[1])
return marshaller.process(content) | def mkheader(self, method, hdef, object) | Builds a soapheader for the specified I{method} using the header
definition (hdef) and the specified value (object).
@param method: A method name.
@type method: str
@param hdef: A header definition.
@type hdef: tuple: (I{name}, L{xsd.sxbase.SchemaObject})
@param object: ... | 4.825099 | 4.485503 | 1.07571 |
env = Element("Envelope", ns=envns)
env.addPrefix(Namespace.xsins[0], Namespace.xsins[1])
env.append(header)
env.append(body)
return env | def envelope(self, header, body) | Build the B{<Envelope/>} for a SOAP outbound message.
@param header: The SOAP message B{header}.
@type header: L{Element}
@param body: The SOAP message B{body}.
@type body: L{Element}
@return: The SOAP envelope containing the body and header.
@rtype: L{Element} | 7.429801 | 8.806832 | 0.843641 |
header = Element("Header", ns=envns)
header.append(content)
return header | def header(self, content) | Build the B{<Body/>} for a SOAP outbound message.
@param content: The header content.
@type content: L{Element}
@return: The SOAP body fragment.
@rtype: L{Element} | 9.335575 | 10.739603 | 0.869266 |
content = []
wsse = self.options().wsse
if wsse is not None:
content.append(wsse.xml())
headers = self.options().soapheaders
if not isinstance(headers, (tuple, list, dict)):
headers = (headers,)
elif not headers:
return content... | def headercontent(self, method) | Get the content for the SOAP I{Header} node.
@param method: A service method.
@type method: I{service.Method}
@return: The XML content for the <body/>.
@rtype: [L{Element},...] | 2.878938 | 2.803956 | 1.026741 |
if input:
parts = method.soap.input.body.parts
else:
parts = method.soap.output.body.parts
return [self.__part_type(p, input) for p in parts] | def bodypart_types(self, method, input=True) | Get a list of I{parameter definitions} (pdefs) defined for the
specified method.
An input I{pdef} is a (I{name}, L{xsd.sxbase.SchemaObject}) tuple,
while an output I{pdef} is a L{xsd.sxbase.SchemaObject}.
@param method: A service method.
@type method: I{service.Method}
... | 3.824984 | 4.262036 | 0.897454 |
if input:
headers = method.soap.input.headers
else:
headers = method.soap.output.headers
return [self.__part_type(h.part, input) for h in headers] | def headpart_types(self, method, input=True) | Get a list of header I{parameter definitions} (pdefs) defined for the
specified method.
An input I{pdef} is a (I{name}, L{xsd.sxbase.SchemaObject}) tuple,
while an output I{pdef} is a L{xsd.sxbase.SchemaObject}.
@param method: A service method.
@type method: I{service.Method}
... | 4.933511 | 4.93157 | 1.000394 |
if part.element is None:
query = TypeQuery(part.type)
else:
query = ElementQuery(part.element)
part_type = query.execute(self.schema())
if part_type is None:
raise TypeNotFound(query.ref)
if part.type is not None:
part_type... | def __part_type(self, part, input) | Get a I{parameter definition} (pdef) defined for a given body or header
message part.
An input I{pdef} is a (I{name}, L{xsd.sxbase.SchemaObject}) tuple,
while an output I{pdef} is a L{xsd.sxbase.SchemaObject}.
@param part: A service method input or output part.
@type part: I{su... | 3.706626 | 3.730729 | 0.993539 |
if value is None:
value = node.getText()
if isinstance(value, Object):
known = cls.known(value)
if known.name is None:
return node
tm = known.name, known.namespace()
else:
tm = cls.types.get(value.__class__, cls... | def auto(cls, node, value=None) | Automatically set the node's xsi:type attribute based on either
I{value}'s or the node text's class. When I{value} is an unmapped
class, the default type (xs:any) is set.
@param node: XML node.
@type node: L{sax.element.Element}
@param value: Object that is or would be the node'... | 5.674137 | 5.709319 | 0.993838 |
xta = ":".join((Namespace.xsins[0], "type"))
node.addPrefix(Namespace.xsins[0], Namespace.xsins[1])
if ns is None:
node.set(xta, tval)
else:
ns = cls.genprefix(node, ns)
qname = ":".join((ns[0], tval))
node.set(xta, qname)
... | def manual(cls, node, tval, ns=None) | Set the node's xsi:type attribute based on either I{value}'s or the
node text's class. Then adds the referenced prefix(s) to the node's
prefix mapping.
@param node: XML node.
@type node: L{sax.element.Element}
@param tval: XSD schema type name.
@type tval: str
@p... | 4.325462 | 4.169951 | 1.037293 |
for i in range(1, 1024):
prefix = "ns%d" % (i,)
uri = node.resolvePrefix(prefix, default=None)
if uri in (None, ns[1]):
return prefix, ns[1]
raise Exception("auto prefix, exhausted") | def genprefix(cls, node, ns) | Generate a prefix.
@param node: XML node on which the prefix will be used.
@type node: L{sax.element.Element}
@param ns: Namespace needing a unique prefix.
@type ns: (prefix, URI)
@return: I{ns} with a new prefix.
@rtype: (prefix, URI) | 6.047262 | 5.051609 | 1.197096 |
try:
filename = self.__filename(id)
self.__remove_if_expired(filename)
return self.__open(filename, "rb")
except Exception:
pass | def _getf(self, id) | Open a cached file with the given id for reading. | 6.183314 | 5.416666 | 1.141535 |
suffix = self.fnsuffix()
filename = "%s-%s.%s" % (self.fnprefix, id, suffix)
return os.path.join(self.location, filename) | def __filename(self, id) | Return the cache file name for an entry with a given id. | 5.165777 | 5.156257 | 1.001846 |
if not FileCache.__default_location:
tmp = tempfile.mkdtemp("suds-default-cache")
FileCache.__default_location = tmp
import atexit
atexit.register(FileCache.__remove_default_location)
return FileCache.__default_location | def __get_default_location() | Returns the current process's default cache location folder.
The folder is determined lazily on first call. | 4.286535 | 4.139744 | 1.035459 |
try:
if not os.path.isdir(self.location):
os.makedirs(self.location)
except Exception:
log.debug(self.location, exc_info=1)
return self | def __mktmp(self) | Create the I{location} folder if it does not already exist. | 3.462076 | 2.72021 | 1.272724 |
if not self.duration:
return
created = datetime.datetime.fromtimestamp(os.path.getctime(filename))
expired = created + self.duration
if expired < datetime.datetime.now():
os.remove(filename)
log.debug("%s expired, deleted", filename) | def __remove_if_expired(self, filename) | Remove a cached file entry if it expired.
@param filename: The file name.
@type filename: str | 2.899867 | 3.190895 | 0.908794 |
tns = root.get('targetNamespace')
if len(self.tns):
matched = ( tns in self.tns )
else:
matched = 1
itself = ( ns == tns )
return ( matched and not itself ) | def match(self, root, ns) | Match by I{targetNamespace} excluding those that
are equal to the specified namespace to prevent
adding an import to itself.
@param root: A schema root.
@type root: L{Element} | 6.836073 | 6.565776 | 1.041167 |
if self.urlopener is None:
return urllib2.build_opener(*self.u2handlers())
return self.urlopener | def u2opener(self) | Create a urllib opener.
@return: An opener.
@rtype: I{OpenerDirector} | 4.567792 | 4.821627 | 0.947355 |
try:
part = urllib2.__version__.split('.', 1)
return float('.'.join(part))
except Exception, 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.416796 | 4.23201 | 1.516253 |
def any_contains_any(strings, candidates):
for string in strings:
for c in candidates:
if c in string:
return True | Whether any of the strings contains any of the candidates. | null | null | null | |
def path_to_URL(path, escape=True):
# We do not use urllib's builtin pathname2url() function since:
# - it has been commented with 'not recommended for general use'
# - it does not seem to work the same on Windows and non-Windows platforms
# (result starts with /// on Windows but does not... | Convert a local file path to a absolute path file protocol URL. | null | null | null | |
def requirement_spec(package_name, *args):
if not args or args == (None,):
return package_name
version_specs = []
for version_spec in args:
if isinstance(version_spec, (list, tuple)):
operator, version = version_spec
else:
assert isinstance(versi... | Identifier used when specifying a requirement to pip or setuptools. | null | null | null | |
def script_folder(script_path):
# There exist modules whose __file__ attribute does not correspond directly
# to a disk file, e.g. modules imported from inside zip archives.
if os.path.isfile(script_path):
return _rel_path(os.path.dirname(script_path)) or "." | Return the given script's folder or None if it can not be determined.
Script is identified by its __file__ attribute. If the given __file__
attribute value contains no path information, it is expected to identify an
existing file in the current working folder.
Returned folder may be specified re... | null | null | null | |
def path_iter(path):
parts = []
while path:
path, item = os.path.split(path)
if item:
parts.append(item)
return reversed(parts) | Returns an iterator over all the file & folder names in a path. | null | null | null | |
tag = wrapper[1].name
ns = wrapper[1].namespace("ns0")
return Element(tag, ns=ns) | def document(self, wrapper) | Get the document root. For I{document/literal}, this is the name of the
wrapper element qualified by the schema's target namespace.
@param wrapper: The method name.
@type wrapper: L{xsd.sxbase.SchemaObject}
@return: A root element.
@rtype: L{Element} | 13.726094 | 12.262532 | 1.119352 |
if isinstance(object, (list, tuple)):
return [self.mkparam(method, pdef, item) for item in object]
return super(Document, self).mkparam(method, pdef, object) | def mkparam(self, method, pdef, object) | Expand list parameters into individual parameters each with the type
information. This is because in document arrays are simply
multi-occurrence elements. | 2.648542 | 2.430124 | 1.089879 |
pts = self.bodypart_types(method)
if not method.soap.input.body.wrapped:
return pts
pt = pts[0][1].resolve()
return [(c.name, c, a) for c, a in pt if not c.isattr()] | def param_defs(self, method) | Get parameter definitions for document literal. | 16.635231 | 11.886828 | 1.399468 |
assert isinstance(s, basestring)
if isinstance(s, unicode):
return s.encode(encoding, errors)
if s and encoding != input_encoding:
return s.decode(input_encoding, errors).encode(encoding, errors)
return s | def byte_str(s="", encoding="utf-8", input_encoding="utf-8", errors="strict") | Returns a byte string version of 's', encoded as specified in 'encoding'.
Accepts str & unicode objects, interpreting non-unicode strings as byte
strings encoded using the given input encoding. | 2.245214 | 2.395551 | 0.937243 |
dt = datetime.datetime(2000, 1, 1, time.hour, time.minute,
time.second, time.microsecond)
dt += datetime.timedelta(microseconds=1)
return dt.time() | def _bump_up_time_by_microsecond(time) | Helper function bumping up the given datetime.time by a microsecond,
cycling around silently to 00:00:00.0 in case of an overflow.
@param time: Time object.
@type time: B{datetime}.I{time}
@return: Time object.
@rtype: B{datetime}.I{time} | 2.29833 | 2.905539 | 0.791017 |
year = int(match_object.group("year"))
month = int(match_object.group("month"))
day = int(match_object.group("day"))
return datetime.date(year, month, day) | def _date_from_match(match_object) | Create a date object from a regular expression match.
The regular expression match is expected to be from _RE_DATE or
_RE_DATETIME.
@param match_object: The regular expression match.
@type match_object: B{re}.I{MatchObject}
@return: A date object.
@rtype: B{datetime}.I{date} | 1.699156 | 2.129108 | 0.79806 |
hour = int(match_object.group('hour'))
minute = int(match_object.group('minute'))
second = int(match_object.group('second'))
subsecond = match_object.group('subsecond')
round_up = False
microsecond = 0
if subsecond:
round_up = len(subsecond) > 6 and int(subsecond[6]) >= 5
... | def _time_from_match(match_object) | Create a time object from a regular expression match.
Returns the time object and information whether the resulting time should
be bumped up by one microsecond due to microsecond rounding.
Subsecond information is rounded to microseconds due to a restriction in
the python datetime.datetime/time implem... | 2.161818 | 2.251372 | 0.960223 |
tz_utc = match_object.group("tz_utc")
if tz_utc:
return UtcTimezone()
tz_sign = match_object.group("tz_sign")
if not tz_sign:
return
h = int(match_object.group("tz_hour") or 0)
m = int(match_object.group("tz_minute") or 0)
if h == 0 and m == 0:
return UtcTimezo... | 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_DATETIME
or _RE_TIME.
@param match_object: The regular expression match.
@type match_object: B{re}.I{MatchObject}
@return: A timezone information object.
@rty... | 3.6019 | 3.877202 | 0.928995 |
match_result = _RE_DATE.match(value)
if match_result is None:
raise ValueError("date data has invalid format '%s'" % (value,))
return _date_from_match(match_result) | def __parse(value) | Parse the string date.
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 is meaningless without
a time and b) B{datetime}.I{date} does not support timezone
inf... | 4.865919 | 5.093557 | 0.955309 |
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, round_up = _time_from_match(match_result)
tzinfo = _tzinfo_from_match(match_result)
... | def __parse(value) | Parse the string datetime.
Supports the subset of ISO8601 used by xsd:dateTime, but is lenient
with what is accepted, handling most reasonable syntax.
Subsecond information is rounded to microseconds due to a restriction
in the python datetime.datetime/time implementation.
@pa... | 3.028232 | 2.902644 | 1.043267 |
match_result = _RE_TIME.match(value)
if match_result is None:
raise ValueError("date data has invalid format '%s'" % (value,))
time, round_up = _time_from_match(match_result)
tzinfo = _tzinfo_from_match(match_result)
if round_up:
time = _bump_up_t... | def __parse(value) | Parse the string date.
Supports the subset of ISO8601 used by xsd:time, but is lenient with
what is accepted, handling most reasonable syntax.
Subsecond information is rounded to microseconds due to a restriction
in the python datetime.time implementation.
@param value: A time... | 4.384603 | 4.004408 | 1.094944 |
# 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)
hours... | def tzname(self, dt) | http://docs.python.org/library/datetime.html#datetime.tzinfo.tzname | 1.929656 | 1.861196 | 1.036783 |
node = content.node
if len(node.children) and node.hasText():
return node
attributes = AttrList(node.attributes)
if attributes.rlen() and \
not len(node.children) and \
node.hasText():
p = Factory.property(node.name, node.getTe... | def postprocess(self, content) | Perform final processing of the resulting data structure as follows:
- Mixed values (children and text) will have a result of the I{content.node}.
- Simi-simple values (attributes, no-children and text) will have a result of a
property object.
- Simple values (no-attributes, n... | 5.276029 | 4.626072 | 1.140499 |
for child in content.node:
cont = Content(child)
cval = self.append(cont)
key = reserved.get(child.name, child.name)
if key in content.data:
v = getattr(content.data, key)
if isinstance(v, list):
v.appen... | def append_children(self, content) | Append child nodes into L{Content.data}
@param content: The current content being unmarshalled.
@type content: L{Content} | 3.025117 | 2.982719 | 1.014214 |
if string:
return suds.sax.parser.Parser().parse(string=string) | def _parse(string) | Parses given XML document content.
Returns the resulting root XML element node or None if the given XML
content is empty.
@param string: XML document content to parse.
@type string: I{bytes}
@return: Resulting root XML element node or None.
@rtype: L{Element}|I{None} | 11.147562 | 15.951349 | 0.698848 |
timer = metrics.Timer()
timer.start()
type = self.resolver.find(name)
if type is None:
raise TypeNotFound(name)
if type.enum():
result = sudsobject.Factory.object(name)
for e, a in type.children():
setattr(result, e.nam... | def create(self, name) | Create a WSDL type by name.
@param name: The name of a type defined in the WSDL.
@type name: str
@return: The requested object.
@rtype: L{Object} | 4.68838 | 4.53044 | 1.034862 |
service = None
if not self.__services:
raise Exception, "No services defined"
if isinstance(name, int):
try:
service = self.__services[name]
name = service.name
except IndexError:
raise ServiceNotFound, ... | def __find(self, name) | Find a I{service} by name (string) or index (integer).
@param name: The name (or index) of a service.
@type name: int|str
@return: A L{PortSelector} for the found service.
@rtype: L{PortSelector}. | 3.616242 | 3.10391 | 1.16506 |
ds = self.__client.options.service
if ds is not None:
return self.__find(ds) | def __ds(self) | Get the I{default} service if defined in the I{options}.
@return: A L{PortSelector} for the I{default} service.
@rtype: L{PortSelector}. | 14.566179 | 11.867446 | 1.227406 |
return self.__process_reply(reply, status, description) | def process_reply(self, reply, status=None, description=None) | Re-entry for processing a successful reply.
Depending on how the ``retxml`` option is set, may return the SOAP
reply XML or process it and return the Python object representing the
returned value.
@param reply: The SOAP reply envelope.
@type reply: I{bytes}
@param statu... | 6.440422 | 10.266122 | 0.627347 |
location = self.__location()
log.debug("sending to (%s)\nmessage:\n%s", location, soapenv)
plugins = PluginContainer(self.options.plugins)
plugins.message.marshalled(envelope=soapenv.root())
if self.options.prettyxml:
soapenv = soapenv.str()
else:
... | def send(self, soapenv) | Send SOAP message.
Depending on how the ``nosend`` & ``retxml`` options are set, may do
one of the following:
* Return a constructed web service operation request without sending
it to the web service.
* Invoke the web service operation and return its SOAP reply XML.
... | 4.754745 | 4.639486 | 1.024843 |
if status is None:
status = httplib.OK
debug_message = "Reply HTTP status - %d" % (status,)
if status in (httplib.ACCEPTED, httplib.NO_CONTENT):
log.debug(debug_message)
return
#TODO: Consider whether and how to allow plugins to handle error,
... | def process_reply(self, reply, status, description) | Process a web service operation SOAP reply.
Depending on how the ``retxml`` option is set, may return the SOAP
reply XML or process it and return the Python object representing the
returned value.
@param reply: The SOAP reply envelope.
@type reply: I{bytes}
@param statu... | 4.813208 | 4.633045 | 1.038886 |
envns = suds.bindings.binding.envns
soapenv = replyroot and replyroot.getChild("Envelope", envns)
soapbody = soapenv and soapenv.getChild("Body", envns)
fault = soapbody and soapbody.getChild("Fault", envns)
return fault is not None and UmxBasic().process(fault) | def __get_fault(self, replyroot) | Extract fault information from a SOAP reply.
Returns an I{unmarshalled} fault L{Object} or None in case the given
XML document does not contain a SOAP <Fault> element.
@param replyroot: A SOAP reply message root XML element or None.
@type replyroot: L{Element}|I{None}
@return: ... | 5.432428 | 5.842453 | 0.92982 |
action = self.method.soap.action
if isinstance(action, unicode):
action = action.encode("utf-8")
result = {
"Content-Type": "text/xml; charset=utf-8",
"SOAPAction": action}
result.update(**self.options.headers)
log.debug("headers = %s"... | def __headers(self) | Get HTTP headers for a HTTP/HTTPS SOAP request.
@return: A dictionary of header/values.
@rtype: dict | 4.241982 | 4.099296 | 1.034808 |
simulation = kwargs.pop(self.__injkey)
msg = simulation.get("msg")
if msg is not None:
assert msg.__class__ is suds.byte_str_class
return self.send(_parse(msg))
msg = self.method.binding.input.get_message(self.method, args, kwargs)
log.debug("inje... | def invoke(self, args, kwargs) | Invoke a specified web service method.
Uses an injected SOAP request/response instead of a regularly
constructed/received one.
Depending on how the ``nosend`` & ``retxml`` options are set, may do
one of the following:
* Return a constructed web service operation request witho... | 5.958014 | 5.676333 | 1.049624 |
if isinstance(url, str):
url.encode("ascii") # Check for non-ASCII characters.
self.url = url
elif sys.version_info < (3, 0):
self.url = url.encode("ascii")
else:
self.url = url.decode("ascii") | def __set_URL(self, url) | URL is stored as a str internally and must not contain ASCII chars.
Raised exception in case of detected non-ASCII URL characters may be
either UnicodeEncodeError or UnicodeDecodeError, depending on the used
Python version's str type and the exact value passed as URL input data. | 2.976037 | 3.021469 | 0.984963 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.