id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
8,100
suds-community/suds
suds/xsd/sxbasic.py
Import.open
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} """ 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 schema (%s) not-found", self.ns[1]) else: url = self.location if "://" not in url: url = urljoin(self.schema.baseurl, url) result = (loaded_schemata.get(url) or self.__download(url, loaded_schemata, options)) log.debug("imported:\n%s", result) return result
python
def open(self, options, loaded_schemata): 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 schema (%s) not-found", self.ns[1]) else: url = self.location if "://" not in url: url = urljoin(self.schema.baseurl, url) result = (loaded_schemata.get(url) or self.__download(url, loaded_schemata, options)) log.debug("imported:\n%s", result) return result
[ "def", "open", "(", "self", ",", "options", ",", "loaded_schemata", ")", ":", "if", "self", ".", "opened", ":", "return", "self", ".", "opened", "=", "True", "log", ".", "debug", "(", "\"%s, importing ns='%s', location='%s'\"", ",", "self", ".", "id", ",",...
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}
[ "Open", "and", "import", "the", "referenced", "schema", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/xsd/sxbasic.py#L552-L580
8,101
suds-community/suds
suds/xsd/sxbasic.py
Import.__locate
def __locate(self): """Find the schema locally.""" if self.ns[1] != self.schema.tns[1]: return self.schema.locate(self.ns)
python
def __locate(self): if self.ns[1] != self.schema.tns[1]: return self.schema.locate(self.ns)
[ "def", "__locate", "(", "self", ")", ":", "if", "self", ".", "ns", "[", "1", "]", "!=", "self", ".", "schema", ".", "tns", "[", "1", "]", ":", "return", "self", ".", "schema", ".", "locate", "(", "self", ".", "ns", ")" ]
Find the schema locally.
[ "Find", "the", "schema", "locally", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/xsd/sxbasic.py#L582-L585
8,102
suds-community/suds
suds/xsd/sxbasic.py
Import.__download
def __download(self, url, loaded_schemata, options): """Download the schema.""" 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), failed" % (self.ns[1], url) log.error("%s, %s", self.id, msg, exc_info=True) raise Exception(msg)
python
def __download(self, url, loaded_schemata, options): 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), failed" % (self.ns[1], url) log.error("%s, %s", self.id, msg, exc_info=True) raise Exception(msg)
[ "def", "__download", "(", "self", ",", "url", ",", "loaded_schemata", ",", "options", ")", ":", "try", ":", "reader", "=", "DocumentReader", "(", "options", ")", "d", "=", "reader", ".", "open", "(", "url", ")", "root", "=", "d", ".", "root", "(", ...
Download the schema.
[ "Download", "the", "schema", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/xsd/sxbasic.py#L587-L598
8,103
suds-community/suds
suds/xsd/sxbasic.py
Include.__applytns
def __applytns(self, root): """Make sure included schema has the same target namespace.""" 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
python
def __applytns(self, root): 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", ")", ":", "TNS", "=", "\"targetNamespace\"", "tns", "=", "root", ".", "get", "(", "TNS", ")", "if", "tns", "is", "None", ":", "tns", "=", "self", ".", "schema", ".", "tns", "[", "1", "]", "root", "."...
Make sure included schema has the same target namespace.
[ "Make", "sure", "included", "schema", "has", "the", "same", "target", "namespace", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/xsd/sxbasic.py#L662-L671
8,104
suds-community/suds
suds/wsdl.py
Definitions.add_methods
def add_methods(self, service): """Build method view for service.""" 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() for name in (op.name for op in operations): m = Facade("Method") m.name = name m.location = p.location m.binding = Facade("binding") op = binding.operation(name) m.soap = op.soap key = "/".join((op.soap.style, op.soap.input.body.use)) m.binding.input = bindings.get(key) key = "/".join((op.soap.style, op.soap.output.body.use)) m.binding.output = bindings.get(key) p.methods[name] = m
python
def add_methods(self, service): 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() for name in (op.name for op in operations): m = Facade("Method") m.name = name m.location = p.location m.binding = Facade("binding") op = binding.operation(name) m.soap = op.soap key = "/".join((op.soap.style, op.soap.input.body.use)) m.binding.input = bindings.get(key) key = "/".join((op.soap.style, op.soap.output.body.use)) m.binding.output = bindings.get(key) p.methods[name] = m
[ "def", "add_methods", "(", "self", ",", "service", ")", ":", "bindings", "=", "{", "\"document/literal\"", ":", "Document", "(", "self", ")", ",", "\"rpc/literal\"", ":", "RPC", "(", "self", ")", ",", "\"rpc/encoded\"", ":", "Encoded", "(", "self", ")", ...
Build method view for service.
[ "Build", "method", "view", "for", "service", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/wsdl.py#L261-L282
8,105
suds-community/suds
suds/wsdl.py
PortType.operation
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. """ try: return self.operations[name] except Exception, e: raise MethodNotFound(name)
python
def operation(self, name): try: return self.operations[name] except Exception, e: raise MethodNotFound(name)
[ "def", "operation", "(", "self", ",", "name", ")", ":", "try", ":", "return", "self", ".", "operations", "[", "name", "]", "except", "Exception", ",", "e", ":", "raise", "MethodNotFound", "(", "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.
[ "Shortcut", "used", "to", "get", "a", "contained", "operation", "by", "name", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/wsdl.py#L555-L569
8,106
suds-community/suds
suds/wsdl.py
Service.port
def port(self, name): """ Locate a port by name. @param name: A port name. @type name: str @return: The port object. @rtype: L{Port} """ for p in self.ports: if p.name == name: return p
python
def port(self, name): for p in self.ports: if p.name == name: return p
[ "def", "port", "(", "self", ",", "name", ")", ":", "for", "p", "in", "self", ".", "ports", ":", "if", "p", ".", "name", "==", "name", ":", "return", "p" ]
Locate a port by name. @param name: A port name. @type name: str @return: The port object. @rtype: L{Port}
[ "Locate", "a", "port", "by", "name", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/wsdl.py#L910-L922
8,107
suds-community/suds
suds/wsdl.py
Service.do_resolve
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} """ 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: log.debug("binding '%s' - not a SOAP binding, discarded", binding.name) continue # After we have been resolved, our caller will expect that the # binding we are referencing has been fully constructed, i.e. # resolved, as well. The only scenario where the operations binding # might possibly not have already resolved its references, and # where this explicit resolve() call is required, is if we are # dealing with a recursive WSDL import chain. binding.resolve(definitions) p.binding = binding filtered.append(p) self.ports = filtered
python
def do_resolve(self, definitions): 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: log.debug("binding '%s' - not a SOAP binding, discarded", binding.name) continue # After we have been resolved, our caller will expect that the # binding we are referencing has been fully constructed, i.e. # resolved, as well. The only scenario where the operations binding # might possibly not have already resolved its references, and # where this explicit resolve() call is required, is if we are # dealing with a recursive WSDL import chain. binding.resolve(definitions) p.binding = binding filtered.append(p) self.ports = filtered
[ "def", "do_resolve", "(", "self", ",", "definitions", ")", ":", "filtered", "=", "[", "]", "for", "p", "in", "self", ".", "ports", ":", "ref", "=", "qualify", "(", "p", ".", "binding", ",", "self", ".", "root", ",", "definitions", ".", "tns", ")", ...
Resolve named references to other WSDL objects. Ports without SOAP bindings are discarded. @param definitions: A definitions object. @type definitions: L{Definitions}
[ "Resolve", "named", "references", "to", "other", "WSDL", "objects", ".", "Ports", "without", "SOAP", "bindings", "are", "discarded", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/wsdl.py#L939-L967
8,108
suds-community/suds
suds/cache.py
FileCache._getf
def _getf(self, id): """Open a cached file with the given id for reading.""" try: filename = self.__filename(id) self.__remove_if_expired(filename) return self.__open(filename, "rb") except Exception: pass
python
def _getf(self, id): try: filename = self.__filename(id) self.__remove_if_expired(filename) return self.__open(filename, "rb") except Exception: pass
[ "def", "_getf", "(", "self", ",", "id", ")", ":", "try", ":", "filename", "=", "self", ".", "__filename", "(", "id", ")", "self", ".", "__remove_if_expired", "(", "filename", ")", "return", "self", ".", "__open", "(", "filename", ",", "\"rb\"", ")", ...
Open a cached file with the given id for reading.
[ "Open", "a", "cached", "file", "with", "the", "given", "id", "for", "reading", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/cache.py#L182-L189
8,109
suds-community/suds
suds/cache.py
FileCache.__filename
def __filename(self, id): """Return the cache file name for an entry with a given id.""" suffix = self.fnsuffix() filename = "%s-%s.%s" % (self.fnprefix, id, suffix) return os.path.join(self.location, filename)
python
def __filename(self, id): suffix = self.fnsuffix() filename = "%s-%s.%s" % (self.fnprefix, id, suffix) return os.path.join(self.location, filename)
[ "def", "__filename", "(", "self", ",", "id", ")", ":", "suffix", "=", "self", ".", "fnsuffix", "(", ")", "filename", "=", "\"%s-%s.%s\"", "%", "(", "self", ".", "fnprefix", ",", "id", ",", "suffix", ")", "return", "os", ".", "path", ".", "join", "(...
Return the cache file name for an entry with a given id.
[ "Return", "the", "cache", "file", "name", "for", "an", "entry", "with", "a", "given", "id", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/cache.py#L209-L213
8,110
suds-community/suds
suds/cache.py
FileCache.__get_default_location
def __get_default_location(): """ Returns the current process's default cache location folder. The folder is determined lazily on first call. """ 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
python
def __get_default_location(): 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", "(", ")", ":", "if", "not", "FileCache", ".", "__default_location", ":", "tmp", "=", "tempfile", ".", "mkdtemp", "(", "\"suds-default-cache\"", ")", "FileCache", ".", "__default_location", "=", "tmp", "import", "atexit", "atexit", ...
Returns the current process's default cache location folder. The folder is determined lazily on first call.
[ "Returns", "the", "current", "process", "s", "default", "cache", "location", "folder", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/cache.py#L216-L228
8,111
suds-community/suds
suds/cache.py
FileCache.__remove_if_expired
def __remove_if_expired(self, filename): """ Remove a cached file entry if it expired. @param filename: The file name. @type filename: str """ 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)
python
def __remove_if_expired(self, filename): 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", ")", ":", "if", "not", "self", ".", "duration", ":", "return", "created", "=", "datetime", ".", "datetime", ".", "fromtimestamp", "(", "os", ".", "path", ".", "getctime", "(", "filename", ")", "...
Remove a cached file entry if it expired. @param filename: The file name. @type filename: str
[ "Remove", "a", "cached", "file", "entry", "if", "it", "expired", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/cache.py#L261-L275
8,112
suds-community/suds
tools/suds_devel/utility.py
any_contains_any
def any_contains_any(strings, candidates): """Whether any of the strings contains any of the candidates.""" for string in strings: for c in candidates: if c in string: return True
python
def any_contains_any(strings, candidates): for string in strings: for c in candidates: if c in string: return True
[ "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.
[ "Whether", "any", "of", "the", "strings", "contains", "any", "of", "the", "candidates", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/tools/suds_devel/utility.py#L32-L37
8,113
suds-community/suds
tools/suds_devel/utility.py
path_to_URL
def path_to_URL(path, escape=True): """Convert a local file path to a absolute path file protocol URL.""" # 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 on others) # - urllib implementation prior to Python 2.5 used to quote ':' characters # as '|' which would confuse pip on Windows. url = os.path.abspath(path) for sep in (os.sep, os.altsep): if sep and sep != "/": url = url.replace(sep, "/") if escape: # Must not escape ':' or '/' or Python will not recognize those URLs # correctly. Detected on Windows 7 SP1 x64 with Python 3.4.0, but doing # this always does not hurt since both are valid ASCII characters. no_protocol_URL = url_quote(url, safe=":/") else: no_protocol_URL = url return "file:///%s" % (no_protocol_URL,)
python
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 on others) # - urllib implementation prior to Python 2.5 used to quote ':' characters # as '|' which would confuse pip on Windows. url = os.path.abspath(path) for sep in (os.sep, os.altsep): if sep and sep != "/": url = url.replace(sep, "/") if escape: # Must not escape ':' or '/' or Python will not recognize those URLs # correctly. Detected on Windows 7 SP1 x64 with Python 3.4.0, but doing # this always does not hurt since both are valid ASCII characters. no_protocol_URL = url_quote(url, safe=":/") else: no_protocol_URL = url return "file:///%s" % (no_protocol_URL,)
[ "def", "path_to_URL", "(", "path", ",", "escape", "=", "True", ")", ":", "# We do not use urllib's builtin pathname2url() function since:\r", "# - it has been commented with 'not recommended for general use'\r", "# - it does not seem to work the same on Windows and non-Windows platforms\r"...
Convert a local file path to a absolute path file protocol URL.
[ "Convert", "a", "local", "file", "path", "to", "a", "absolute", "path", "file", "protocol", "URL", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/tools/suds_devel/utility.py#L67-L86
8,114
suds-community/suds
tools/suds_devel/utility.py
requirement_spec
def requirement_spec(package_name, *args): """Identifier used when specifying a requirement to pip or setuptools.""" 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(version_spec, str) operator = "==" version = version_spec version_specs.append("%s%s" % (operator, version)) return "%s%s" % (package_name, ",".join(version_specs))
python
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(version_spec, str) operator = "==" version = version_spec version_specs.append("%s%s" % (operator, version)) return "%s%s" % (package_name, ",".join(version_specs))
[ "def", "requirement_spec", "(", "package_name", ",", "*", "args", ")", ":", "if", "not", "args", "or", "args", "==", "(", "None", ",", ")", ":", "return", "package_name", "version_specs", "=", "[", "]", "for", "version_spec", "in", "args", ":", "if", "...
Identifier used when specifying a requirement to pip or setuptools.
[ "Identifier", "used", "when", "specifying", "a", "requirement", "to", "pip", "or", "setuptools", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/tools/suds_devel/utility.py#L93-L106
8,115
suds-community/suds
tools/suds_devel/utility.py
path_iter
def path_iter(path): """Returns an iterator over all the file & folder names in a path.""" parts = [] while path: path, item = os.path.split(path) if item: parts.append(item) return reversed(parts)
python
def path_iter(path): parts = [] while path: path, item = os.path.split(path) if item: parts.append(item) return reversed(parts)
[ "def", "path_iter", "(", "path", ")", ":", "parts", "=", "[", "]", "while", "path", ":", "path", ",", "item", "=", "os", ".", "path", ".", "split", "(", "path", ")", "if", "item", ":", "parts", ".", "append", "(", "item", ")", "return", "reversed...
Returns an iterator over all the file & folder names in a path.
[ "Returns", "an", "iterator", "over", "all", "the", "file", "&", "folder", "names", "in", "a", "path", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/tools/suds_devel/utility.py#L147-L154
8,116
suds-community/suds
suds/bindings/document.py
Document.mkparam
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. """ if isinstance(object, (list, tuple)): return [self.mkparam(method, pdef, item) for item in object] return super(Document, self).mkparam(method, pdef, object)
python
def mkparam(self, method, pdef, object): 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", ")", ":", "if", "isinstance", "(", "object", ",", "(", "list", ",", "tuple", ")", ")", ":", "return", "[", "self", ".", "mkparam", "(", "method", ",", "pdef", ",", "item", ...
Expand list parameters into individual parameters each with the type information. This is because in document arrays are simply multi-occurrence elements.
[ "Expand", "list", "parameters", "into", "individual", "parameters", "each", "with", "the", "type", "information", ".", "This", "is", "because", "in", "document", "arrays", "are", "simply", "multi", "-", "occurrence", "elements", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/bindings/document.py#L120-L129
8,117
suds-community/suds
suds/bindings/document.py
Document.param_defs
def param_defs(self, method): """Get parameter definitions for document literal.""" 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()]
python
def param_defs(self, method): 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", ")", ":", "pts", "=", "self", ".", "bodypart_types", "(", "method", ")", "if", "not", "method", ".", "soap", ".", "input", ".", "body", ".", "wrapped", ":", "return", "pts", "pt", "=", "pts", "[", "0...
Get parameter definitions for document literal.
[ "Get", "parameter", "definitions", "for", "document", "literal", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/bindings/document.py#L131-L137
8,118
suds-community/suds
suds/__init__.py
byte_str
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. """ 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
python
def byte_str(s="", encoding="utf-8", input_encoding="utf-8", errors="strict"): 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\"", ")", ":", "assert", "isinstance", "(", "s", ",", "basestring", ")", "if", "isinstance", "(", "s", ",",...
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.
[ "Returns", "a", "byte", "string", "version", "of", "s", "encoded", "as", "specified", "in", "encoding", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/__init__.py#L144-L157
8,119
suds-community/suds
suds/sax/date.py
_date_from_match
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} """ year = int(match_object.group("year")) month = int(match_object.group("month")) day = int(match_object.group("day")) return datetime.date(year, month, day)
python
def _date_from_match(match_object): 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", ")", ":", "year", "=", "int", "(", "match_object", ".", "group", "(", "\"year\"", ")", ")", "month", "=", "int", "(", "match_object", ".", "group", "(", "\"month\"", ")", ")", "day", "=", "int", "(", "mat...
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}
[ "Create", "a", "date", "object", "from", "a", "regular", "expression", "match", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/sax/date.py#L373-L389
8,120
suds-community/suds
suds/client.py
_parse
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} """ if string: return suds.sax.parser.Parser().parse(string=string)
python
def _parse(string): if string: return suds.sax.parser.Parser().parse(string=string)
[ "def", "_parse", "(", "string", ")", ":", "if", "string", ":", "return", "suds", ".", "sax", ".", "parser", ".", "Parser", "(", ")", ".", "parse", "(", "string", "=", "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}
[ "Parses", "given", "XML", "document", "content", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/client.py#L933-L947
8,121
suds-community/suds
suds/client.py
Factory.create
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} """ 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.name, e.name) else: try: result = self.builder.build(type) except Exception, e: log.error("create '%s' failed", name, exc_info=True) raise BuildError(name, e) timer.stop() metrics.log.debug("%s created: %s", name, timer) return result
python
def create(self, name): 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.name, e.name) else: try: result = self.builder.build(type) except Exception, e: log.error("create '%s' failed", name, exc_info=True) raise BuildError(name, e) timer.stop() metrics.log.debug("%s created: %s", name, timer) return result
[ "def", "create", "(", "self", ",", "name", ")", ":", "timer", "=", "metrics", ".", "Timer", "(", ")", "timer", ".", "start", "(", ")", "type", "=", "self", ".", "resolver", ".", "find", "(", "name", ")", "if", "type", "is", "None", ":", "raise", ...
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}
[ "Create", "a", "WSDL", "type", "by", "name", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/client.py#L220-L247
8,122
suds-community/suds
suds/client.py
RequestContext.process_reply
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 status: The HTTP status code. @type status: int @param description: Additional status description. @type description: I{bytes} @return: The invoked web service operation return value. @rtype: I{builtin}|I{subclass of} L{Object}|I{bytes}|I{None} """ return self.__process_reply(reply, status, description)
python
def process_reply(self, reply, status=None, description=None): return self.__process_reply(reply, status, description)
[ "def", "process_reply", "(", "self", ",", "reply", ",", "status", "=", "None", ",", "description", "=", "None", ")", ":", "return", "self", ".", "__process_reply", "(", "reply", ",", "status", ",", "description", ")" ]
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 status: The HTTP status code. @type status: int @param description: Additional status description. @type description: I{bytes} @return: The invoked web service operation return value. @rtype: I{builtin}|I{subclass of} L{Object}|I{bytes}|I{None}
[ "Re", "-", "entry", "for", "processing", "a", "successful", "reply", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/client.py#L607-L625
8,123
suds-community/suds
suds/client.py
_SoapClient.send
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. * Invoke the web service operation, process its results and return the Python object representing the returned value. @param soapenv: A SOAP envelope to send. @type soapenv: L{Document} @return: SOAP request, SOAP reply or a web service return value. @rtype: L{RequestContext}|I{builtin}|I{subclass of} L{Object}|I{bytes}| I{None} """ 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: soapenv = soapenv.plain() soapenv = soapenv.encode("utf-8") ctx = plugins.message.sending(envelope=soapenv) soapenv = ctx.envelope if self.options.nosend: return RequestContext(self.process_reply, soapenv) request = suds.transport.Request(location, soapenv) request.headers = self.__headers() try: timer = metrics.Timer() timer.start() reply = self.options.transport.send(request) timer.stop() metrics.log.debug("waited %s on server reply", timer) except suds.transport.TransportError, e: content = e.fp and e.fp.read() or "" return self.process_reply(content, e.httpcode, tostr(e)) return self.process_reply(reply.message, None, None)
python
def send(self, soapenv): 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: soapenv = soapenv.plain() soapenv = soapenv.encode("utf-8") ctx = plugins.message.sending(envelope=soapenv) soapenv = ctx.envelope if self.options.nosend: return RequestContext(self.process_reply, soapenv) request = suds.transport.Request(location, soapenv) request.headers = self.__headers() try: timer = metrics.Timer() timer.start() reply = self.options.transport.send(request) timer.stop() metrics.log.debug("waited %s on server reply", timer) except suds.transport.TransportError, e: content = e.fp and e.fp.read() or "" return self.process_reply(content, e.httpcode, tostr(e)) return self.process_reply(reply.message, None, None)
[ "def", "send", "(", "self", ",", "soapenv", ")", ":", "location", "=", "self", ".", "__location", "(", ")", "log", ".", "debug", "(", "\"sending to (%s)\\nmessage:\\n%s\"", ",", "location", ",", "soapenv", ")", "plugins", "=", "PluginContainer", "(", "self",...
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. * Invoke the web service operation, process its results and return the Python object representing the returned value. @param soapenv: A SOAP envelope to send. @type soapenv: L{Document} @return: SOAP request, SOAP reply or a web service return value. @rtype: L{RequestContext}|I{builtin}|I{subclass of} L{Object}|I{bytes}| I{None}
[ "Send", "SOAP", "message", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/client.py#L710-L753
8,124
suds-community/suds
suds/client.py
_SoapClient.process_reply
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 status: The HTTP status code (None indicates httplib.OK). @type status: int|I{None} @param description: Additional status description. @type description: str @return: The invoked web service operation return value. @rtype: I{builtin}|I{subclass of} L{Object}|I{bytes}|I{None} """ 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, # httplib.ACCEPTED & httplib.NO_CONTENT replies as well as successful # ones. if status == httplib.OK: log.debug("%s\n%s", debug_message, reply) else: log.debug("%s - %s\n%s", debug_message, description, reply) plugins = PluginContainer(self.options.plugins) ctx = plugins.message.received(reply=reply) reply = ctx.reply # SOAP standard states that SOAP errors must be accompanied by HTTP # status code 500 - internal server error: # # From SOAP 1.1 specification: # In case of a SOAP error while processing the request, the SOAP HTTP # server MUST issue an HTTP 500 "Internal Server Error" response and # include a SOAP message in the response containing a SOAP Fault # element (see section 4.4) indicating the SOAP processing error. # # From WS-I Basic profile: # An INSTANCE MUST use a "500 Internal Server Error" HTTP status code # if the response message is a SOAP Fault. replyroot = None if status in (httplib.OK, httplib.INTERNAL_SERVER_ERROR): replyroot = _parse(reply) plugins.message.parsed(reply=replyroot) fault = self.__get_fault(replyroot) if fault: if status != httplib.INTERNAL_SERVER_ERROR: log.warn("Web service reported a SOAP processing fault " "using an unexpected HTTP status code %d. Reporting " "as an internal server error.", status) if self.options.faults: raise WebFault(fault, replyroot) return httplib.INTERNAL_SERVER_ERROR, fault if status != httplib.OK: if self.options.faults: #TODO: Use a more specific exception class here. raise Exception((status, description)) return status, description if self.options.retxml: return reply result = replyroot and self.method.binding.output.get_reply( self.method, replyroot) ctx = plugins.message.unmarshalled(reply=result) result = ctx.reply if self.options.faults: return result return httplib.OK, result
python
def process_reply(self, reply, status, description): 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, # httplib.ACCEPTED & httplib.NO_CONTENT replies as well as successful # ones. if status == httplib.OK: log.debug("%s\n%s", debug_message, reply) else: log.debug("%s - %s\n%s", debug_message, description, reply) plugins = PluginContainer(self.options.plugins) ctx = plugins.message.received(reply=reply) reply = ctx.reply # SOAP standard states that SOAP errors must be accompanied by HTTP # status code 500 - internal server error: # # From SOAP 1.1 specification: # In case of a SOAP error while processing the request, the SOAP HTTP # server MUST issue an HTTP 500 "Internal Server Error" response and # include a SOAP message in the response containing a SOAP Fault # element (see section 4.4) indicating the SOAP processing error. # # From WS-I Basic profile: # An INSTANCE MUST use a "500 Internal Server Error" HTTP status code # if the response message is a SOAP Fault. replyroot = None if status in (httplib.OK, httplib.INTERNAL_SERVER_ERROR): replyroot = _parse(reply) plugins.message.parsed(reply=replyroot) fault = self.__get_fault(replyroot) if fault: if status != httplib.INTERNAL_SERVER_ERROR: log.warn("Web service reported a SOAP processing fault " "using an unexpected HTTP status code %d. Reporting " "as an internal server error.", status) if self.options.faults: raise WebFault(fault, replyroot) return httplib.INTERNAL_SERVER_ERROR, fault if status != httplib.OK: if self.options.faults: #TODO: Use a more specific exception class here. raise Exception((status, description)) return status, description if self.options.retxml: return reply result = replyroot and self.method.binding.output.get_reply( self.method, replyroot) ctx = plugins.message.unmarshalled(reply=result) result = ctx.reply if self.options.faults: return result return httplib.OK, result
[ "def", "process_reply", "(", "self", ",", "reply", ",", "status", ",", "description", ")", ":", "if", "status", "is", "None", ":", "status", "=", "httplib", ".", "OK", "debug_message", "=", "\"Reply HTTP status - %d\"", "%", "(", "status", ",", ")", "if", ...
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 status: The HTTP status code (None indicates httplib.OK). @type status: int|I{None} @param description: Additional status description. @type description: str @return: The invoked web service operation return value. @rtype: I{builtin}|I{subclass of} L{Object}|I{bytes}|I{None}
[ "Process", "a", "web", "service", "operation", "SOAP", "reply", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/client.py#L755-L831
8,125
suds-community/suds
suds/client.py
_SoapClient.__get_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: A fault object. @rtype: L{Object} """ 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)
python
def __get_fault(self, replyroot): 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", ")", ":", "envns", "=", "suds", ".", "bindings", ".", "binding", ".", "envns", "soapenv", "=", "replyroot", "and", "replyroot", ".", "getChild", "(", "\"Envelope\"", ",", "envns", ")", "soapbody", "=", ...
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: A fault object. @rtype: L{Object}
[ "Extract", "fault", "information", "from", "a", "SOAP", "reply", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/client.py#L833-L850
8,126
suds-community/suds
suds/client.py
_SimClient.invoke
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 without sending it to the web service. * Invoke the web service operation and return its SOAP reply XML. * Invoke the web service operation, process its results and return the Python object representing the returned value. @param args: Positional arguments for the method invoked. @type args: list|tuple @param kwargs: Keyword arguments for the method invoked. @type kwargs: dict @return: SOAP request, SOAP reply or a web service return value. @rtype: L{RequestContext}|I{builtin}|I{subclass of} L{Object}|I{bytes}| I{None} """ 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("inject (simulated) send message:\n%s", msg) reply = simulation.get("reply") if reply is not None: assert reply.__class__ is suds.byte_str_class status = simulation.get("status") description = simulation.get("description") if description is None: description = "injected reply" return self.process_reply(reply, status, description) raise Exception("reply or msg injection parameter expected")
python
def invoke(self, args, kwargs): 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("inject (simulated) send message:\n%s", msg) reply = simulation.get("reply") if reply is not None: assert reply.__class__ is suds.byte_str_class status = simulation.get("status") description = simulation.get("description") if description is None: description = "injected reply" return self.process_reply(reply, status, description) raise Exception("reply or msg injection parameter expected")
[ "def", "invoke", "(", "self", ",", "args", ",", "kwargs", ")", ":", "simulation", "=", "kwargs", ".", "pop", "(", "self", ".", "__injkey", ")", "msg", "=", "simulation", ".", "get", "(", "\"msg\"", ")", "if", "msg", "is", "not", "None", ":", "asser...
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 without sending it to the web service. * Invoke the web service operation and return its SOAP reply XML. * Invoke the web service operation, process its results and return the Python object representing the returned value. @param args: Positional arguments for the method invoked. @type args: list|tuple @param kwargs: Keyword arguments for the method invoked. @type kwargs: dict @return: SOAP request, SOAP reply or a web service return value. @rtype: L{RequestContext}|I{builtin}|I{subclass of} L{Object}|I{bytes}| I{None}
[ "Invoke", "a", "specified", "web", "service", "method", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/client.py#L891-L930
8,127
suds-community/suds
suds/transport/__init__.py
Request.__set_URL
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. """ 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")
python
def __set_URL(self, url): 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", ")", ":", "if", "isinstance", "(", "url", ",", "str", ")", ":", "url", ".", "encode", "(", "\"ascii\"", ")", "# Check for non-ASCII characters.", "self", ".", "url", "=", "url", "elif", "sys", ".", "version_in...
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.
[ "URL", "is", "stored", "as", "a", "str", "internally", "and", "must", "not", "contain", "ASCII", "chars", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/transport/__init__.py#L75-L90
8,128
suds-community/suds
suds/resolver.py
PathResolver.root
def root(self, parts): """ Find the path root. @param parts: A list of path parts. @type parts: [str,..] @return: The root. @rtype: L{xsd.sxbase.SchemaObject} """ result = None name = parts[0] log.debug('searching schema for (%s)', name) qref = self.qualify(parts[0]) query = BlindQuery(qref) result = query.execute(self.schema) if result is None: log.error('(%s) not-found', name) raise PathResolver.BadPath(name) log.debug('found (%s) as (%s)', name, Repr(result)) return result
python
def root(self, parts): result = None name = parts[0] log.debug('searching schema for (%s)', name) qref = self.qualify(parts[0]) query = BlindQuery(qref) result = query.execute(self.schema) if result is None: log.error('(%s) not-found', name) raise PathResolver.BadPath(name) log.debug('found (%s) as (%s)', name, Repr(result)) return result
[ "def", "root", "(", "self", ",", "parts", ")", ":", "result", "=", "None", "name", "=", "parts", "[", "0", "]", "log", ".", "debug", "(", "'searching schema for (%s)'", ",", "name", ")", "qref", "=", "self", ".", "qualify", "(", "parts", "[", "0", ...
Find the path root. @param parts: A list of path parts. @type parts: [str,..] @return: The root. @rtype: L{xsd.sxbase.SchemaObject}
[ "Find", "the", "path", "root", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/resolver.py#L119-L137
8,129
suds-community/suds
suds/resolver.py
PathResolver.branch
def branch(self, root, parts): """ Traverse the path until a leaf is reached. @param parts: A list of path parts. @type parts: [str,..] @param root: The root. @type root: L{xsd.sxbase.SchemaObject} @return: The end of the branch. @rtype: L{xsd.sxbase.SchemaObject} """ result = root for part in parts[1:-1]: name = splitPrefix(part)[1] log.debug('searching parent (%s) for (%s)', Repr(result), name) result, ancestry = result.get_child(name) if result is None: log.error('(%s) not-found', name) raise PathResolver.BadPath(name) result = result.resolve(nobuiltin=True) log.debug('found (%s) as (%s)', name, Repr(result)) return result
python
def branch(self, root, parts): result = root for part in parts[1:-1]: name = splitPrefix(part)[1] log.debug('searching parent (%s) for (%s)', Repr(result), name) result, ancestry = result.get_child(name) if result is None: log.error('(%s) not-found', name) raise PathResolver.BadPath(name) result = result.resolve(nobuiltin=True) log.debug('found (%s) as (%s)', name, Repr(result)) return result
[ "def", "branch", "(", "self", ",", "root", ",", "parts", ")", ":", "result", "=", "root", "for", "part", "in", "parts", "[", "1", ":", "-", "1", "]", ":", "name", "=", "splitPrefix", "(", "part", ")", "[", "1", "]", "log", ".", "debug", "(", ...
Traverse the path until a leaf is reached. @param parts: A list of path parts. @type parts: [str,..] @param root: The root. @type root: L{xsd.sxbase.SchemaObject} @return: The end of the branch. @rtype: L{xsd.sxbase.SchemaObject}
[ "Traverse", "the", "path", "until", "a", "leaf", "is", "reached", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/resolver.py#L139-L159
8,130
suds-community/suds
suds/resolver.py
TreeResolver.getchild
def getchild(self, name, parent): """Get a child by name.""" log.debug('searching parent (%s) for (%s)', Repr(parent), name) if name.startswith('@'): return parent.get_attribute(name[1:]) return parent.get_child(name)
python
def getchild(self, name, parent): log.debug('searching parent (%s) for (%s)', Repr(parent), name) if name.startswith('@'): return parent.get_attribute(name[1:]) return parent.get_child(name)
[ "def", "getchild", "(", "self", ",", "name", ",", "parent", ")", ":", "log", ".", "debug", "(", "'searching parent (%s) for (%s)'", ",", "Repr", "(", "parent", ")", ",", "name", ")", "if", "name", ".", "startswith", "(", "'@'", ")", ":", "return", "par...
Get a child by name.
[ "Get", "a", "child", "by", "name", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/resolver.py#L292-L297
8,131
suds-community/suds
tools/suds_devel/zip.py
_Archiver.__path_prefix
def __path_prefix(self, folder): """ Path prefix to be used when archiving any items from the given folder. Expects the folder to be located under the base folder path and the returned path prefix does not include the base folder information. This makes sure we include just the base folder's content in the archive, and not the base folder itself. """ path_parts = path_iter(folder) _skip_expected(path_parts, self.__base_folder_parts) result = "/".join(path_parts) if result: result += "/" return result
python
def __path_prefix(self, folder): path_parts = path_iter(folder) _skip_expected(path_parts, self.__base_folder_parts) result = "/".join(path_parts) if result: result += "/" return result
[ "def", "__path_prefix", "(", "self", ",", "folder", ")", ":", "path_parts", "=", "path_iter", "(", "folder", ")", "_skip_expected", "(", "path_parts", ",", "self", ".", "__base_folder_parts", ")", "result", "=", "\"/\"", ".", "join", "(", "path_parts", ")", ...
Path prefix to be used when archiving any items from the given folder. Expects the folder to be located under the base folder path and the returned path prefix does not include the base folder information. This makes sure we include just the base folder's content in the archive, and not the base folder itself.
[ "Path", "prefix", "to", "be", "used", "when", "archiving", "any", "items", "from", "the", "given", "folder", ".", "Expects", "the", "folder", "to", "be", "located", "under", "the", "base", "folder", "path", "and", "the", "returned", "path", "prefix", "does...
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/tools/suds_devel/zip.py#L67-L82
8,132
suds-community/suds
suds/xsd/sxbuiltin.py
XDecimal._decimal_to_xsd_format
def _decimal_to_xsd_format(value): """ Converts a decimal.Decimal value to its XSD decimal type value. Result is a string containing the XSD decimal type's lexical value representation. The conversion is done without any precision loss. Note that Python's native decimal.Decimal string representation will not do here as the lexical representation desired here does not allow representing decimal values using float-like `<mantissa>E<exponent>' format, e.g. 12E+30 or 0.10006E-12. """ value = XDecimal._decimal_canonical(value) negative, digits, exponent = value.as_tuple() # The following implementation assumes the following tuple decimal # encoding (part of the canonical decimal value encoding): # - digits must contain at least one element # - no leading integral 0 digits except a single one in 0 (if a non-0 # decimal value has leading integral 0 digits they must be encoded # in its 'exponent' value and not included explicitly in its # 'digits' tuple) assert digits assert digits[0] != 0 or len(digits) == 1 result = [] if negative: result.append("-") # No fractional digits. if exponent >= 0: result.extend(str(x) for x in digits) result.extend("0" * exponent) return "".join(result) digit_count = len(digits) # Decimal point offset from the given digit start. point_offset = digit_count + exponent # Trim trailing fractional 0 digits. fractional_digit_count = min(digit_count, -exponent) while fractional_digit_count and digits[digit_count - 1] == 0: digit_count -= 1 fractional_digit_count -= 1 # No trailing fractional 0 digits and a decimal point coming not after # the given digits, meaning there is no need to add additional trailing # integral 0 digits. if point_offset <= 0: # No integral digits. result.append("0") if digit_count > 0: result.append(".") result.append("0" * -point_offset) result.extend(str(x) for x in digits[:digit_count]) else: # Have integral and possibly some fractional digits. result.extend(str(x) for x in digits[:point_offset]) if point_offset < digit_count: result.append(".") result.extend(str(x) for x in digits[point_offset:digit_count]) return "".join(result)
python
def _decimal_to_xsd_format(value): value = XDecimal._decimal_canonical(value) negative, digits, exponent = value.as_tuple() # The following implementation assumes the following tuple decimal # encoding (part of the canonical decimal value encoding): # - digits must contain at least one element # - no leading integral 0 digits except a single one in 0 (if a non-0 # decimal value has leading integral 0 digits they must be encoded # in its 'exponent' value and not included explicitly in its # 'digits' tuple) assert digits assert digits[0] != 0 or len(digits) == 1 result = [] if negative: result.append("-") # No fractional digits. if exponent >= 0: result.extend(str(x) for x in digits) result.extend("0" * exponent) return "".join(result) digit_count = len(digits) # Decimal point offset from the given digit start. point_offset = digit_count + exponent # Trim trailing fractional 0 digits. fractional_digit_count = min(digit_count, -exponent) while fractional_digit_count and digits[digit_count - 1] == 0: digit_count -= 1 fractional_digit_count -= 1 # No trailing fractional 0 digits and a decimal point coming not after # the given digits, meaning there is no need to add additional trailing # integral 0 digits. if point_offset <= 0: # No integral digits. result.append("0") if digit_count > 0: result.append(".") result.append("0" * -point_offset) result.extend(str(x) for x in digits[:digit_count]) else: # Have integral and possibly some fractional digits. result.extend(str(x) for x in digits[:point_offset]) if point_offset < digit_count: result.append(".") result.extend(str(x) for x in digits[point_offset:digit_count]) return "".join(result)
[ "def", "_decimal_to_xsd_format", "(", "value", ")", ":", "value", "=", "XDecimal", ".", "_decimal_canonical", "(", "value", ")", "negative", ",", "digits", ",", "exponent", "=", "value", ".", "as_tuple", "(", ")", "# The following implementation assumes the followin...
Converts a decimal.Decimal value to its XSD decimal type value. Result is a string containing the XSD decimal type's lexical value representation. The conversion is done without any precision loss. Note that Python's native decimal.Decimal string representation will not do here as the lexical representation desired here does not allow representing decimal values using float-like `<mantissa>E<exponent>' format, e.g. 12E+30 or 0.10006E-12.
[ "Converts", "a", "decimal", ".", "Decimal", "value", "to", "its", "XSD", "decimal", "type", "value", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/xsd/sxbuiltin.py#L129-L192
8,133
suds-community/suds
tools/setup_base_environments.py
_reuse_pre_installed_setuptools
def _reuse_pre_installed_setuptools(env, installer): """ Return whether a pre-installed setuptools distribution should be reused. """ if not env.setuptools_version: return # no prior setuptools ==> no reuse reuse_old = config.reuse_old_setuptools reuse_best = config.reuse_best_setuptools reuse_future = config.reuse_future_setuptools reuse_comment = None if reuse_old or reuse_best or reuse_future: pv_old = parse_version(env.setuptools_version) pv_new = parse_version(installer.setuptools_version()) if pv_old < pv_new: if reuse_old: reuse_comment = "%s+ recommended" % ( installer.setuptools_version(),) elif pv_old > pv_new: if reuse_future: reuse_comment = "%s+ required" % ( installer.setuptools_version(),) elif reuse_best: reuse_comment = "" if reuse_comment is None: return # reuse not allowed by configuration if reuse_comment: reuse_comment = " (%s)" % (reuse_comment,) print("Reusing pre-installed setuptools %s distribution%s." % ( env.setuptools_version, reuse_comment)) return True
python
def _reuse_pre_installed_setuptools(env, installer): if not env.setuptools_version: return # no prior setuptools ==> no reuse reuse_old = config.reuse_old_setuptools reuse_best = config.reuse_best_setuptools reuse_future = config.reuse_future_setuptools reuse_comment = None if reuse_old or reuse_best or reuse_future: pv_old = parse_version(env.setuptools_version) pv_new = parse_version(installer.setuptools_version()) if pv_old < pv_new: if reuse_old: reuse_comment = "%s+ recommended" % ( installer.setuptools_version(),) elif pv_old > pv_new: if reuse_future: reuse_comment = "%s+ required" % ( installer.setuptools_version(),) elif reuse_best: reuse_comment = "" if reuse_comment is None: return # reuse not allowed by configuration if reuse_comment: reuse_comment = " (%s)" % (reuse_comment,) print("Reusing pre-installed setuptools %s distribution%s." % ( env.setuptools_version, reuse_comment)) return True
[ "def", "_reuse_pre_installed_setuptools", "(", "env", ",", "installer", ")", ":", "if", "not", "env", ".", "setuptools_version", ":", "return", "# no prior setuptools ==> no reuse\r", "reuse_old", "=", "config", ".", "reuse_old_setuptools", "reuse_best", "=", "config", ...
Return whether a pre-installed setuptools distribution should be reused.
[ "Return", "whether", "a", "pre", "-", "installed", "setuptools", "distribution", "should", "be", "reused", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/tools/setup_base_environments.py#L534-L564
8,134
suds-community/suds
tools/setup_base_environments.py
download_pip
def download_pip(env, requirements): """Download pip and its requirements using setuptools.""" if config.installation_cache_folder() is None: raise EnvironmentSetupError("Local installation cache folder not " "defined but required for downloading a pip installation.") # Installation cache folder needs to be explicitly created for setuptools # to be able to copy its downloaded installation files into it. Seen using # Python 2.4.4 & setuptools 1.4. _create_installation_cache_folder_if_needed() try: env.execute(["-m", "easy_install", "--zip-ok", "--multi-version", "--always-copy", "--exclude-scripts", "--install-dir", config.installation_cache_folder()] + requirements) zip_eggs_in_folder(config.installation_cache_folder()) except (KeyboardInterrupt, SystemExit): raise except Exception: raise EnvironmentSetupError("pip download failed.")
python
def download_pip(env, requirements): if config.installation_cache_folder() is None: raise EnvironmentSetupError("Local installation cache folder not " "defined but required for downloading a pip installation.") # Installation cache folder needs to be explicitly created for setuptools # to be able to copy its downloaded installation files into it. Seen using # Python 2.4.4 & setuptools 1.4. _create_installation_cache_folder_if_needed() try: env.execute(["-m", "easy_install", "--zip-ok", "--multi-version", "--always-copy", "--exclude-scripts", "--install-dir", config.installation_cache_folder()] + requirements) zip_eggs_in_folder(config.installation_cache_folder()) except (KeyboardInterrupt, SystemExit): raise except Exception: raise EnvironmentSetupError("pip download failed.")
[ "def", "download_pip", "(", "env", ",", "requirements", ")", ":", "if", "config", ".", "installation_cache_folder", "(", ")", "is", "None", ":", "raise", "EnvironmentSetupError", "(", "\"Local installation cache folder not \"", "\"defined but required for downloading a pip ...
Download pip and its requirements using setuptools.
[ "Download", "pip", "and", "its", "requirements", "using", "setuptools", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/tools/setup_base_environments.py#L596-L613
8,135
suds-community/suds
tools/setup_base_environments.py
setuptools_install_options
def setuptools_install_options(local_storage_folder): """ Return options to make setuptools use installations from the given folder. No other installation source is allowed. """ if local_storage_folder is None: return [] # setuptools expects its find-links parameter to contain a list of link # sources (either local paths, file: URLs pointing to folders or URLs # pointing to a file containing HTML links) separated by spaces. That means # that, when specifying such items, whether local paths or URLs, they must # not contain spaces. The problem can be worked around by using a local # file URL, since URLs can contain space characters encoded as '%20' (for # more detailed information see below). # # Any URL referencing a folder needs to be specified with a trailing '/' # character in order for setuptools to correctly recognize it as a folder. # # All this has been tested using Python 2.4.3/2.4.4 & setuptools 1.4/1.4.2 # as well as Python 3.4 & setuptools 3.3. # # Supporting paths with spaces - method 1: # ---------------------------------------- # One way would be to prepare a link file and pass an URL referring to that # link file. The link file needs to contain a list of HTML link tags # (<a href="..."/>), one for every item stored inside the local storage # folder. If a link file references a folder whose name matches the desired # requirement name, it will be searched recursively (as described in method # 2 below). # # Note that in order for setuptools to recognize a local link file URL # correctly, the file needs to be named with the '.html' extension. That # will cause the underlying urllib2.open() operation to return the link # file's content type as 'text/html' which is required for setuptools to # recognize a valid link file. # # Supporting paths with spaces - method 2: # ---------------------------------------- # Another possible way is to use an URL referring to the local storage # folder directly. This will cause setuptools to prepare and use a link # file internally - with its content read from a 'index.html' file located # in the given local storage folder, if it exists, or constructed so it # contains HTML links to all top-level local storage folder items, as # described for method 1 above. if " " in local_storage_folder: find_links_param = utility.path_to_URL(local_storage_folder) if find_links_param[-1] != "/": find_links_param += "/" else: find_links_param = local_storage_folder return ["-f", find_links_param, "--allow-hosts=None"]
python
def setuptools_install_options(local_storage_folder): if local_storage_folder is None: return [] # setuptools expects its find-links parameter to contain a list of link # sources (either local paths, file: URLs pointing to folders or URLs # pointing to a file containing HTML links) separated by spaces. That means # that, when specifying such items, whether local paths or URLs, they must # not contain spaces. The problem can be worked around by using a local # file URL, since URLs can contain space characters encoded as '%20' (for # more detailed information see below). # # Any URL referencing a folder needs to be specified with a trailing '/' # character in order for setuptools to correctly recognize it as a folder. # # All this has been tested using Python 2.4.3/2.4.4 & setuptools 1.4/1.4.2 # as well as Python 3.4 & setuptools 3.3. # # Supporting paths with spaces - method 1: # ---------------------------------------- # One way would be to prepare a link file and pass an URL referring to that # link file. The link file needs to contain a list of HTML link tags # (<a href="..."/>), one for every item stored inside the local storage # folder. If a link file references a folder whose name matches the desired # requirement name, it will be searched recursively (as described in method # 2 below). # # Note that in order for setuptools to recognize a local link file URL # correctly, the file needs to be named with the '.html' extension. That # will cause the underlying urllib2.open() operation to return the link # file's content type as 'text/html' which is required for setuptools to # recognize a valid link file. # # Supporting paths with spaces - method 2: # ---------------------------------------- # Another possible way is to use an URL referring to the local storage # folder directly. This will cause setuptools to prepare and use a link # file internally - with its content read from a 'index.html' file located # in the given local storage folder, if it exists, or constructed so it # contains HTML links to all top-level local storage folder items, as # described for method 1 above. if " " in local_storage_folder: find_links_param = utility.path_to_URL(local_storage_folder) if find_links_param[-1] != "/": find_links_param += "/" else: find_links_param = local_storage_folder return ["-f", find_links_param, "--allow-hosts=None"]
[ "def", "setuptools_install_options", "(", "local_storage_folder", ")", ":", "if", "local_storage_folder", "is", "None", ":", "return", "[", "]", "# setuptools expects its find-links parameter to contain a list of link\r", "# sources (either local paths, file: URLs pointing to folders o...
Return options to make setuptools use installations from the given folder. No other installation source is allowed.
[ "Return", "options", "to", "make", "setuptools", "use", "installations", "from", "the", "given", "folder", ".", "No", "other", "installation", "source", "is", "allowed", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/tools/setup_base_environments.py#L616-L668
8,136
suds-community/suds
tools/setup_base_environments.py
install_pip
def install_pip(env, requirements): """Install pip and its requirements using setuptools.""" try: installation_source_folder = config.installation_cache_folder() options = setuptools_install_options(installation_source_folder) if installation_source_folder is not None: zip_eggs_in_folder(installation_source_folder) env.execute(["-m", "easy_install"] + options + requirements) except (KeyboardInterrupt, SystemExit): raise except Exception: raise EnvironmentSetupError("pip installation failed.")
python
def install_pip(env, requirements): try: installation_source_folder = config.installation_cache_folder() options = setuptools_install_options(installation_source_folder) if installation_source_folder is not None: zip_eggs_in_folder(installation_source_folder) env.execute(["-m", "easy_install"] + options + requirements) except (KeyboardInterrupt, SystemExit): raise except Exception: raise EnvironmentSetupError("pip installation failed.")
[ "def", "install_pip", "(", "env", ",", "requirements", ")", ":", "try", ":", "installation_source_folder", "=", "config", ".", "installation_cache_folder", "(", ")", "options", "=", "setuptools_install_options", "(", "installation_source_folder", ")", "if", "installat...
Install pip and its requirements using setuptools.
[ "Install", "pip", "and", "its", "requirements", "using", "setuptools", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/tools/setup_base_environments.py#L671-L682
8,137
suds-community/suds
tools/setup_base_environments.py
download_pip_based_installations
def download_pip_based_installations(env, pip_invocation, requirements, download_cache_folder): """Download requirements for pip based installation.""" if config.installation_cache_folder() is None: raise EnvironmentSetupError("Local installation cache folder not " "defined but required for downloading pip based installations.") # Installation cache folder needs to be explicitly created for pip to be # able to copy its downloaded installation files into it. The same does not # hold for pip's download cache folder which gets created by pip on-demand. # Seen using Python 3.4.0 & pip 1.5.4. _create_installation_cache_folder_if_needed() try: pip_options = ["install", "-d", config.installation_cache_folder(), "--exists-action=i"] pip_options.extend(pip_download_cache_options(download_cache_folder)) # Running pip based installations on Python 2.5. # * Python 2.5 does not come with SSL support enabled by default and # so pip can not use SSL certified downloads from PyPI. # * To work around this either install the # https://pypi.python.org/pypi/ssl package or run pip using the # '--insecure' command-line options. # * Installing the ssl package seems ridden with problems on # Python 2.5 so this workaround has not been tested. if (2, 5) <= env.sys_version_info < (2, 6): # There are some potential cases where we do not need to use # "--insecure", e.g. if the target Python environment already has # the 'ssl' module installed. However, detecting whether this is so # does not seem to be worth the effort. The only way to detect # whether secure download is supported would be to scan the target # environment for this information, e.g. setuptools has this # information in its pip.backwardcompat.ssl variable - if it is # None, the necessary SSL support is not available. But then we # would have to be careful: # - not to run the scan if we already know this information from # some previous scan # - to track all actions that could have invalidated our previous # scan results, etc. # It just does not seem to be worth the hassle so for now - YAGNI. pip_options.append("--insecure") env.execute(pip_invocation + pip_options + requirements) except (KeyboardInterrupt, SystemExit): raise except Exception: raise EnvironmentSetupError("pip based download failed.")
python
def download_pip_based_installations(env, pip_invocation, requirements, download_cache_folder): if config.installation_cache_folder() is None: raise EnvironmentSetupError("Local installation cache folder not " "defined but required for downloading pip based installations.") # Installation cache folder needs to be explicitly created for pip to be # able to copy its downloaded installation files into it. The same does not # hold for pip's download cache folder which gets created by pip on-demand. # Seen using Python 3.4.0 & pip 1.5.4. _create_installation_cache_folder_if_needed() try: pip_options = ["install", "-d", config.installation_cache_folder(), "--exists-action=i"] pip_options.extend(pip_download_cache_options(download_cache_folder)) # Running pip based installations on Python 2.5. # * Python 2.5 does not come with SSL support enabled by default and # so pip can not use SSL certified downloads from PyPI. # * To work around this either install the # https://pypi.python.org/pypi/ssl package or run pip using the # '--insecure' command-line options. # * Installing the ssl package seems ridden with problems on # Python 2.5 so this workaround has not been tested. if (2, 5) <= env.sys_version_info < (2, 6): # There are some potential cases where we do not need to use # "--insecure", e.g. if the target Python environment already has # the 'ssl' module installed. However, detecting whether this is so # does not seem to be worth the effort. The only way to detect # whether secure download is supported would be to scan the target # environment for this information, e.g. setuptools has this # information in its pip.backwardcompat.ssl variable - if it is # None, the necessary SSL support is not available. But then we # would have to be careful: # - not to run the scan if we already know this information from # some previous scan # - to track all actions that could have invalidated our previous # scan results, etc. # It just does not seem to be worth the hassle so for now - YAGNI. pip_options.append("--insecure") env.execute(pip_invocation + pip_options + requirements) except (KeyboardInterrupt, SystemExit): raise except Exception: raise EnvironmentSetupError("pip based download failed.")
[ "def", "download_pip_based_installations", "(", "env", ",", "pip_invocation", ",", "requirements", ",", "download_cache_folder", ")", ":", "if", "config", ".", "installation_cache_folder", "(", ")", "is", "None", ":", "raise", "EnvironmentSetupError", "(", "\"Local in...
Download requirements for pip based installation.
[ "Download", "requirements", "for", "pip", "based", "installation", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/tools/setup_base_environments.py#L778-L821
8,138
suds-community/suds
tools/setup_base_environments.py
enabled_actions_for_env
def enabled_actions_for_env(env): """Returns actions to perform when processing the given environment.""" def enabled(config_value, required): if config_value is Config.TriBool.No: return False if config_value is Config.TriBool.Yes: return True assert config_value is Config.TriBool.IfNeeded return bool(required) # Some old Python versions do not support HTTPS downloads and therefore can # not download installation packages from PyPI. To run setuptools or pip # based installations on such Python versions, all the required # installation packages need to be downloaded locally first using a # compatible Python version (e.g. Python 2.4.4 for Python 2.4.3) and then # installed locally. download_supported = not ((2, 4, 3) <= env.sys_version_info < (2, 4, 4)) local_install = config.installation_cache_folder() is not None actions = set() pip_required = False run_pip_based_installations = enabled(config.install_environments, True) if run_pip_based_installations: actions.add("run pip based installations") pip_required = True if download_supported and enabled(config.download_installations, local_install and run_pip_based_installations): actions.add("download pip based installations") pip_required = True setuptools_required = False run_pip_installation = enabled(config.install_environments, pip_required) if run_pip_installation: actions.add("run pip installation") setuptools_required = True if download_supported and enabled(config.download_installations, local_install and run_pip_installation): actions.add("download pip installation") setuptools_required = True if enabled(config.setup_setuptools, setuptools_required): actions.add("setup setuptools") return actions
python
def enabled_actions_for_env(env): def enabled(config_value, required): if config_value is Config.TriBool.No: return False if config_value is Config.TriBool.Yes: return True assert config_value is Config.TriBool.IfNeeded return bool(required) # Some old Python versions do not support HTTPS downloads and therefore can # not download installation packages from PyPI. To run setuptools or pip # based installations on such Python versions, all the required # installation packages need to be downloaded locally first using a # compatible Python version (e.g. Python 2.4.4 for Python 2.4.3) and then # installed locally. download_supported = not ((2, 4, 3) <= env.sys_version_info < (2, 4, 4)) local_install = config.installation_cache_folder() is not None actions = set() pip_required = False run_pip_based_installations = enabled(config.install_environments, True) if run_pip_based_installations: actions.add("run pip based installations") pip_required = True if download_supported and enabled(config.download_installations, local_install and run_pip_based_installations): actions.add("download pip based installations") pip_required = True setuptools_required = False run_pip_installation = enabled(config.install_environments, pip_required) if run_pip_installation: actions.add("run pip installation") setuptools_required = True if download_supported and enabled(config.download_installations, local_install and run_pip_installation): actions.add("download pip installation") setuptools_required = True if enabled(config.setup_setuptools, setuptools_required): actions.add("setup setuptools") return actions
[ "def", "enabled_actions_for_env", "(", "env", ")", ":", "def", "enabled", "(", "config_value", ",", "required", ")", ":", "if", "config_value", "is", "Config", ".", "TriBool", ".", "No", ":", "return", "False", "if", "config_value", "is", "Config", ".", "T...
Returns actions to perform when processing the given environment.
[ "Returns", "actions", "to", "perform", "when", "processing", "the", "given", "environment", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/tools/setup_base_environments.py#L891-L936
8,139
suds-community/suds
tools/setup_base_environments.py
_ez_setup_script.__setuptools_version
def __setuptools_version(self): """Read setuptools version from the underlying ez_setup script.""" # Read the script directly as a file instead of importing it as a # Python module and reading the value from the loaded module's global # DEFAULT_VERSION variable. Not all ez_setup scripts are compatible # with all Python environments and so importing them would require # doing so using a separate process run in the target Python # environment instead of the current one. f = open(self.script_path(), "r") try: matcher = re.compile(r'\s*DEFAULT_VERSION\s*=\s*"([^"]*)"\s*$') for i, line in enumerate(f): if i > 50: break match = matcher.match(line) if match: return match.group(1) finally: f.close() self.__error("error parsing setuptools installation script '%s'" % ( self.script_path(),))
python
def __setuptools_version(self): # Read the script directly as a file instead of importing it as a # Python module and reading the value from the loaded module's global # DEFAULT_VERSION variable. Not all ez_setup scripts are compatible # with all Python environments and so importing them would require # doing so using a separate process run in the target Python # environment instead of the current one. f = open(self.script_path(), "r") try: matcher = re.compile(r'\s*DEFAULT_VERSION\s*=\s*"([^"]*)"\s*$') for i, line in enumerate(f): if i > 50: break match = matcher.match(line) if match: return match.group(1) finally: f.close() self.__error("error parsing setuptools installation script '%s'" % ( self.script_path(),))
[ "def", "__setuptools_version", "(", "self", ")", ":", "# Read the script directly as a file instead of importing it as a\r", "# Python module and reading the value from the loaded module's global\r", "# DEFAULT_VERSION variable. Not all ez_setup scripts are compatible\r", "# with all Python enviro...
Read setuptools version from the underlying ez_setup script.
[ "Read", "setuptools", "version", "from", "the", "underlying", "ez_setup", "script", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/tools/setup_base_environments.py#L471-L491
8,140
suds-community/suds
suds/sax/element.py
Element.rename
def rename(self, name): """ Rename the element. @param name: A new name for the element. @type name: basestring """ if name is None: raise Exception("name (%s) not-valid" % (name,)) self.prefix, self.name = splitPrefix(name)
python
def rename(self, name): if name is None: raise Exception("name (%s) not-valid" % (name,)) self.prefix, self.name = splitPrefix(name)
[ "def", "rename", "(", "self", ",", "name", ")", ":", "if", "name", "is", "None", ":", "raise", "Exception", "(", "\"name (%s) not-valid\"", "%", "(", "name", ",", ")", ")", "self", ".", "prefix", ",", "self", ".", "name", "=", "splitPrefix", "(", "na...
Rename the element. @param name: A new name for the element. @type name: basestring
[ "Rename", "the", "element", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/sax/element.py#L104-L114
8,141
suds-community/suds
suds/sax/element.py
Element.clone
def clone(self, parent=None): """ Deep clone of this element and children. @param parent: An optional parent for the copied fragment. @type parent: I{Element} @return: A deep copy parented by I{parent} @rtype: I{Element} """ root = Element(self.qname(), parent, self.namespace()) for a in self.attributes: root.append(a.clone(self)) for c in self.children: root.append(c.clone(self)) for ns in self.nsprefixes.items(): root.addPrefix(ns[0], ns[1]) return root
python
def clone(self, parent=None): root = Element(self.qname(), parent, self.namespace()) for a in self.attributes: root.append(a.clone(self)) for c in self.children: root.append(c.clone(self)) for ns in self.nsprefixes.items(): root.addPrefix(ns[0], ns[1]) return root
[ "def", "clone", "(", "self", ",", "parent", "=", "None", ")", ":", "root", "=", "Element", "(", "self", ".", "qname", "(", ")", ",", "parent", ",", "self", ".", "namespace", "(", ")", ")", "for", "a", "in", "self", ".", "attributes", ":", "root",...
Deep clone of this element and children. @param parent: An optional parent for the copied fragment. @type parent: I{Element} @return: A deep copy parented by I{parent} @rtype: I{Element}
[ "Deep", "clone", "of", "this", "element", "and", "children", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/sax/element.py#L158-L175
8,142
suds-community/suds
suds/sax/element.py
Element.get
def get(self, name, ns=None, default=None): """ Get the value of an attribute by name. @param name: The name of the attribute. @type name: basestring @param ns: The optional attribute's namespace. @type ns: (I{prefix}, I{name}) @param default: An optional value to be returned when either the attribute does not exist or has no value. @type default: basestring @return: The attribute's value or I{default}. @rtype: basestring @see: __getitem__() """ attr = self.getAttribute(name, ns) if attr is None or attr.value is None: return default return attr.getValue()
python
def get(self, name, ns=None, default=None): attr = self.getAttribute(name, ns) if attr is None or attr.value is None: return default return attr.getValue()
[ "def", "get", "(", "self", ",", "name", ",", "ns", "=", "None", ",", "default", "=", "None", ")", ":", "attr", "=", "self", ".", "getAttribute", "(", "name", ",", "ns", ")", "if", "attr", "is", "None", "or", "attr", ".", "value", "is", "None", ...
Get the value of an attribute by name. @param name: The name of the attribute. @type name: basestring @param ns: The optional attribute's namespace. @type ns: (I{prefix}, I{name}) @param default: An optional value to be returned when either the attribute does not exist or has no value. @type default: basestring @return: The attribute's value or I{default}. @rtype: basestring @see: __getitem__()
[ "Get", "the", "value", "of", "an", "attribute", "by", "name", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/sax/element.py#L227-L246
8,143
suds-community/suds
suds/sax/element.py
Element.namespace
def namespace(self): """ Get the element's namespace. @return: The element's namespace by resolving the prefix, the explicit namespace or the inherited namespace. @rtype: (I{prefix}, I{name}) """ if self.prefix is None: return self.defaultNamespace() return self.resolvePrefix(self.prefix)
python
def namespace(self): if self.prefix is None: return self.defaultNamespace() return self.resolvePrefix(self.prefix)
[ "def", "namespace", "(", "self", ")", ":", "if", "self", ".", "prefix", "is", "None", ":", "return", "self", ".", "defaultNamespace", "(", ")", "return", "self", ".", "resolvePrefix", "(", "self", ".", "prefix", ")" ]
Get the element's namespace. @return: The element's namespace by resolving the prefix, the explicit namespace or the inherited namespace. @rtype: (I{prefix}, I{name})
[ "Get", "the", "element", "s", "namespace", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/sax/element.py#L299-L310
8,144
suds-community/suds
suds/sax/element.py
Element.append
def append(self, objects): """ Append the specified child based on whether it is an element or an attribute. @param objects: A (single|collection) of attribute(s) or element(s) to be added as children. @type objects: (L{Element}|L{Attribute}) @return: self @rtype: L{Element} """ if not isinstance(objects, (list, tuple)): objects = (objects,) for child in objects: if isinstance(child, Element): self.children.append(child) child.parent = self continue if isinstance(child, Attribute): self.attributes.append(child) child.parent = self continue raise Exception("append %s not-valid" % (child.__class__.__name__,)) return self
python
def append(self, objects): if not isinstance(objects, (list, tuple)): objects = (objects,) for child in objects: if isinstance(child, Element): self.children.append(child) child.parent = self continue if isinstance(child, Attribute): self.attributes.append(child) child.parent = self continue raise Exception("append %s not-valid" % (child.__class__.__name__,)) return self
[ "def", "append", "(", "self", ",", "objects", ")", ":", "if", "not", "isinstance", "(", "objects", ",", "(", "list", ",", "tuple", ")", ")", ":", "objects", "=", "(", "objects", ",", ")", "for", "child", "in", "objects", ":", "if", "isinstance", "(...
Append the specified child based on whether it is an element or an attribute. @param objects: A (single|collection) of attribute(s) or element(s) to be added as children. @type objects: (L{Element}|L{Attribute}) @return: self @rtype: L{Element}
[ "Append", "the", "specified", "child", "based", "on", "whether", "it", "is", "an", "element", "or", "an", "attribute", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/sax/element.py#L330-L355
8,145
suds-community/suds
suds/sax/element.py
Element.promotePrefixes
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} """ for c in self.children: c.promotePrefixes() if self.parent is None: return for p, u in self.nsprefixes.items(): if p in self.parent.nsprefixes: pu = self.parent.nsprefixes[p] if pu == u: del self.nsprefixes[p] continue if p != self.parent.prefix: self.parent.nsprefixes[p] = u del self.nsprefixes[p] return self
python
def promotePrefixes(self): for c in self.children: c.promotePrefixes() if self.parent is None: return for p, u in self.nsprefixes.items(): if p in self.parent.nsprefixes: pu = self.parent.nsprefixes[p] if pu == u: del self.nsprefixes[p] continue if p != self.parent.prefix: self.parent.nsprefixes[p] = u del self.nsprefixes[p] return self
[ "def", "promotePrefixes", "(", "self", ")", ":", "for", "c", "in", "self", ".", "children", ":", "c", ".", "promotePrefixes", "(", ")", "if", "self", ".", "parent", "is", "None", ":", "return", "for", "p", ",", "u", "in", "self", ".", "nsprefixes", ...
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}
[ "Push", "prefix", "declarations", "up", "the", "tree", "as", "far", "as", "possible", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/sax/element.py#L662-L687
8,146
suds-community/suds
suds/sax/element.py
Element.isempty
def isempty(self, content=True): """ Get whether the element has no children. @param content: Test content (children & text) only. @type content: boolean @return: True when element has not children. @rtype: boolean """ nochildren = not self.children notext = self.text is None nocontent = nochildren and notext if content: return nocontent noattrs = not len(self.attributes) return nocontent and noattrs
python
def isempty(self, content=True): nochildren = not self.children notext = self.text is None nocontent = nochildren and notext if content: return nocontent noattrs = not len(self.attributes) return nocontent and noattrs
[ "def", "isempty", "(", "self", ",", "content", "=", "True", ")", ":", "nochildren", "=", "not", "self", ".", "children", "notext", "=", "self", ".", "text", "is", "None", "nocontent", "=", "nochildren", "and", "notext", "if", "content", ":", "return", ...
Get whether the element has no children. @param content: Test content (children & text) only. @type content: boolean @return: True when element has not children. @rtype: boolean
[ "Get", "whether", "the", "element", "has", "no", "children", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/sax/element.py#L723-L739
8,147
suds-community/suds
suds/sax/element.py
Element.applyns
def applyns(self, ns): """ Apply the namespace to this node. If the prefix is I{None} then this element's explicit namespace I{expns} is set to the URI defined by I{ns}. Otherwise, the I{ns} is simply mapped. @param ns: A namespace. @type ns: (I{prefix}, I{URI}) """ if ns is None: return if not isinstance(ns, (list, tuple)): raise Exception("namespace must be a list or a tuple") if ns[0] is None: self.expns = ns[1] else: self.prefix = ns[0] self.nsprefixes[ns[0]] = ns[1]
python
def applyns(self, ns): if ns is None: return if not isinstance(ns, (list, tuple)): raise Exception("namespace must be a list or a tuple") if ns[0] is None: self.expns = ns[1] else: self.prefix = ns[0] self.nsprefixes[ns[0]] = ns[1]
[ "def", "applyns", "(", "self", ",", "ns", ")", ":", "if", "ns", "is", "None", ":", "return", "if", "not", "isinstance", "(", "ns", ",", "(", "list", ",", "tuple", ")", ")", ":", "raise", "Exception", "(", "\"namespace must be a list or a tuple\"", ")", ...
Apply the namespace to this node. If the prefix is I{None} then this element's explicit namespace I{expns} is set to the URI defined by I{ns}. Otherwise, the I{ns} is simply mapped. @param ns: A namespace. @type ns: (I{prefix}, I{URI})
[ "Apply", "the", "namespace", "to", "this", "node", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/sax/element.py#L772-L792
8,148
suds-community/suds
suds/reader.py
DocumentReader.__fetch
def __fetch(self, url): """ Fetch document content from an external source. The document content will first be looked up in the registered document store, and if not found there, downloaded using the registered transport system. Before being returned, the fetched document content first gets processed by all the registered 'loaded' plugins. @param url: A document URL. @type url: str. @return: A file pointer to the fetched document content. @rtype: file-like """ content = None store = self.options.documentStore if store is not None: content = store.open(url) if content is None: request = suds.transport.Request(url) fp = self.options.transport.open(request) try: content = fp.read() finally: fp.close() ctx = self.plugins.document.loaded(url=url, document=content) content = ctx.document sax = suds.sax.parser.Parser() return sax.parse(string=content)
python
def __fetch(self, url): content = None store = self.options.documentStore if store is not None: content = store.open(url) if content is None: request = suds.transport.Request(url) fp = self.options.transport.open(request) try: content = fp.read() finally: fp.close() ctx = self.plugins.document.loaded(url=url, document=content) content = ctx.document sax = suds.sax.parser.Parser() return sax.parse(string=content)
[ "def", "__fetch", "(", "self", ",", "url", ")", ":", "content", "=", "None", "store", "=", "self", ".", "options", ".", "documentStore", "if", "store", "is", "not", "None", ":", "content", "=", "store", ".", "open", "(", "url", ")", "if", "content", ...
Fetch document content from an external source. The document content will first be looked up in the registered document store, and if not found there, downloaded using the registered transport system. Before being returned, the fetched document content first gets processed by all the registered 'loaded' plugins. @param url: A document URL. @type url: str. @return: A file pointer to the fetched document content. @rtype: file-like
[ "Fetch", "document", "content", "from", "an", "external", "source", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/reader.py#L165-L196
8,149
suds-community/suds
tools/suds_devel/environment.py
Environment.__construct_python_version
def __construct_python_version(self): """ Construct a setuptools compatible Python version string. Constructed based on the environment's reported sys.version_info. """ major, minor, micro, release_level, serial = self.sys_version_info assert release_level in ("alfa", "beta", "candidate", "final") assert release_level != "final" or serial == 0 parts = [str(major), ".", str(minor), ".", str(micro)] if release_level != "final": parts.append(release_level[0]) parts.append(str(serial)) self.python_version = "".join(parts)
python
def __construct_python_version(self): major, minor, micro, release_level, serial = self.sys_version_info assert release_level in ("alfa", "beta", "candidate", "final") assert release_level != "final" or serial == 0 parts = [str(major), ".", str(minor), ".", str(micro)] if release_level != "final": parts.append(release_level[0]) parts.append(str(serial)) self.python_version = "".join(parts)
[ "def", "__construct_python_version", "(", "self", ")", ":", "major", ",", "minor", ",", "micro", ",", "release_level", ",", "serial", "=", "self", ".", "sys_version_info", "assert", "release_level", "in", "(", "\"alfa\"", ",", "\"beta\"", ",", "\"candidate\"", ...
Construct a setuptools compatible Python version string. Constructed based on the environment's reported sys.version_info.
[ "Construct", "a", "setuptools", "compatible", "Python", "version", "string", ".", "Constructed", "based", "on", "the", "environment", "s", "reported", "sys", ".", "version_info", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/tools/suds_devel/environment.py#L164-L178
8,150
suds-community/suds
tools/suds_devel/environment.py
Environment.__parse_scanned_version_info
def __parse_scanned_version_info(self): """Parses the environment's formatted version info string.""" string = self.sys_version_info_formatted try: major, minor, micro, release_level, serial = string.split(",") if (release_level in ("alfa", "beta", "candidate", "final") and (release_level != "final" or serial == "0") and major.isdigit() and # --- --- --- --- --- --- --- --- --- minor.isdigit() and # Explicit isdigit() checks to detect micro.isdigit() and # leading/trailing whitespace. serial.isdigit()): # --- --- --- --- --- --- --- --- --- self.sys_version_info = (int(major), int(minor), int(micro), release_level, int(serial)) self.__construct_python_version() return except (KeyboardInterrupt, SystemExit): raise except Exception: pass raise BadEnvironment("Unsupported Python version (%s)" % (string,))
python
def __parse_scanned_version_info(self): string = self.sys_version_info_formatted try: major, minor, micro, release_level, serial = string.split(",") if (release_level in ("alfa", "beta", "candidate", "final") and (release_level != "final" or serial == "0") and major.isdigit() and # --- --- --- --- --- --- --- --- --- minor.isdigit() and # Explicit isdigit() checks to detect micro.isdigit() and # leading/trailing whitespace. serial.isdigit()): # --- --- --- --- --- --- --- --- --- self.sys_version_info = (int(major), int(minor), int(micro), release_level, int(serial)) self.__construct_python_version() return except (KeyboardInterrupt, SystemExit): raise except Exception: pass raise BadEnvironment("Unsupported Python version (%s)" % (string,))
[ "def", "__parse_scanned_version_info", "(", "self", ")", ":", "string", "=", "self", ".", "sys_version_info_formatted", "try", ":", "major", ",", "minor", ",", "micro", ",", "release_level", ",", "serial", "=", "string", ".", "split", "(", "\",\"", ")", "if"...
Parses the environment's formatted version info string.
[ "Parses", "the", "environment", "s", "formatted", "version", "info", "string", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/tools/suds_devel/environment.py#L233-L252
8,151
suds-community/suds
suds/mx/literal.py
Typed.node
def node(self, content): """ Create an XML node. The XML node is namespace qualified as defined by the corresponding schema element. """ ns = content.type.namespace() if content.type.form_qualified: node = Element(content.tag, ns=ns) if ns[0]: node.addPrefix(ns[0], ns[1]) else: node = Element(content.tag) self.encode(node, content) log.debug("created - node:\n%s", node) return node
python
def node(self, content): ns = content.type.namespace() if content.type.form_qualified: node = Element(content.tag, ns=ns) if ns[0]: node.addPrefix(ns[0], ns[1]) else: node = Element(content.tag) self.encode(node, content) log.debug("created - node:\n%s", node) return node
[ "def", "node", "(", "self", ",", "content", ")", ":", "ns", "=", "content", ".", "type", ".", "namespace", "(", ")", "if", "content", ".", "type", ".", "form_qualified", ":", "node", "=", "Element", "(", "content", ".", "tag", ",", "ns", "=", "ns",...
Create an XML node. The XML node is namespace qualified as defined by the corresponding schema element.
[ "Create", "an", "XML", "node", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/mx/literal.py#L143-L160
8,152
suds-community/suds
tools/suds_devel/egg.py
_detect_eggs_in_folder
def _detect_eggs_in_folder(folder): """ Detect egg distributions located in the given folder. Only direct folder content is considered and subfolders are not searched recursively. """ eggs = {} for x in os.listdir(folder): zip = x.endswith(_zip_ext) if zip: root = x[:-len(_zip_ext)] egg = _Egg.NONE elif x.endswith(_egg_ext): root = x[:-len(_egg_ext)] if os.path.isdir(os.path.join(folder, x)): egg = _Egg.FOLDER else: egg = _Egg.FILE else: continue try: info = eggs[root] except KeyError: eggs[root] = _Egg(os.path.join(folder, root), egg, zip) else: if egg is not _Egg.NONE: info.set_egg(egg) if zip: info.set_zip() return eggs.values()
python
def _detect_eggs_in_folder(folder): eggs = {} for x in os.listdir(folder): zip = x.endswith(_zip_ext) if zip: root = x[:-len(_zip_ext)] egg = _Egg.NONE elif x.endswith(_egg_ext): root = x[:-len(_egg_ext)] if os.path.isdir(os.path.join(folder, x)): egg = _Egg.FOLDER else: egg = _Egg.FILE else: continue try: info = eggs[root] except KeyError: eggs[root] = _Egg(os.path.join(folder, root), egg, zip) else: if egg is not _Egg.NONE: info.set_egg(egg) if zip: info.set_zip() return eggs.values()
[ "def", "_detect_eggs_in_folder", "(", "folder", ")", ":", "eggs", "=", "{", "}", "for", "x", "in", "os", ".", "listdir", "(", "folder", ")", ":", "zip", "=", "x", ".", "endswith", "(", "_zip_ext", ")", "if", "zip", ":", "root", "=", "x", "[", ":"...
Detect egg distributions located in the given folder. Only direct folder content is considered and subfolders are not searched recursively.
[ "Detect", "egg", "distributions", "located", "in", "the", "given", "folder", ".", "Only", "direct", "folder", "content", "is", "considered", "and", "subfolders", "are", "not", "searched", "recursively", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/tools/suds_devel/egg.py#L144-L175
8,153
suds-community/suds
tools/suds_devel/egg.py
_Egg.normalize
def normalize(self): """ Makes sure this egg distribution is stored only as an egg file. The egg file will be created from another existing distribution format if needed. """ if self.has_egg_file(): if self.has_zip(): self.__remove_zip() else: if self.has_egg_folder(): if not self.has_zip(): self.__zip_egg_folder() self.__remove_egg_folder() self.__rename_zip_to_egg()
python
def normalize(self): if self.has_egg_file(): if self.has_zip(): self.__remove_zip() else: if self.has_egg_folder(): if not self.has_zip(): self.__zip_egg_folder() self.__remove_egg_folder() self.__rename_zip_to_egg()
[ "def", "normalize", "(", "self", ")", ":", "if", "self", ".", "has_egg_file", "(", ")", ":", "if", "self", ".", "has_zip", "(", ")", ":", "self", ".", "__remove_zip", "(", ")", "else", ":", "if", "self", ".", "has_egg_folder", "(", ")", ":", "if", ...
Makes sure this egg distribution is stored only as an egg file. The egg file will be created from another existing distribution format if needed.
[ "Makes", "sure", "this", "egg", "distribution", "is", "stored", "only", "as", "an", "egg", "file", ".", "The", "egg", "file", "will", "be", "created", "from", "another", "existing", "distribution", "format", "if", "needed", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/tools/suds_devel/egg.py#L85-L101
8,154
suds-community/suds
suds/argparser.py
parse_args
def parse_args(method_name, param_defs, args, kwargs, external_param_processor, extra_parameter_errors): """ Parse arguments for suds web service operation invocation functions. Suds prepares Python function objects for invoking web service operations. This function implements generic binding agnostic part of processing the arguments passed when calling those function objects. Argument parsing rules: * Each input parameter element should be represented by single regular Python function argument. * At most one input parameter belonging to a single choice parameter structure may have its value specified as something other than None. * Positional arguments are mapped to choice group input parameters the same as is done for a simple all/sequence group - each in turn. Expects to be passed the web service operation's parameter definitions (parameter name, type & optional ancestry information) in order and, based on that, extracts the values for those parameter from the arguments provided in the web service operation invocation call. Ancestry information describes parameters constructed based on suds library's automatic input parameter structure unwrapping. It is expected to include the parameter's XSD schema 'ancestry' context, i.e. a list of all the parent XSD schema tags containing the parameter's <element> tag. Such ancestry context provides detailed information about how the parameter's value is expected to be used, especially in relation to other input parameters, e.g. at most one parameter value may be specified for parameters directly belonging to the same choice input group. Rules on acceptable ancestry items: * Ancestry item's choice() method must return whether the item represents a <choice> XSD schema tag. * Passed ancestry items are used 'by address' internally and the same XSD schema tag is expected to be identified by the exact same ancestry item object during the whole argument processing. During processing, each parameter's definition and value, together with any additional pertinent information collected from the encountered parameter definition structure, is passed on to the provided external parameter processor function. There that information is expected to be used to construct the actual binding specific web service operation invocation request. Raises a TypeError exception in case any argument related errors are detected. The exceptions raised have been constructed to make them as similar as possible to their respective exceptions raised during regular Python function argument checking. Does not support multiple same-named input parameters. """ arg_parser = _ArgParser(method_name, param_defs, external_param_processor) return arg_parser(args, kwargs, extra_parameter_errors)
python
def parse_args(method_name, param_defs, args, kwargs, external_param_processor, extra_parameter_errors): arg_parser = _ArgParser(method_name, param_defs, external_param_processor) return arg_parser(args, kwargs, extra_parameter_errors)
[ "def", "parse_args", "(", "method_name", ",", "param_defs", ",", "args", ",", "kwargs", ",", "external_param_processor", ",", "extra_parameter_errors", ")", ":", "arg_parser", "=", "_ArgParser", "(", "method_name", ",", "param_defs", ",", "external_param_processor", ...
Parse arguments for suds web service operation invocation functions. Suds prepares Python function objects for invoking web service operations. This function implements generic binding agnostic part of processing the arguments passed when calling those function objects. Argument parsing rules: * Each input parameter element should be represented by single regular Python function argument. * At most one input parameter belonging to a single choice parameter structure may have its value specified as something other than None. * Positional arguments are mapped to choice group input parameters the same as is done for a simple all/sequence group - each in turn. Expects to be passed the web service operation's parameter definitions (parameter name, type & optional ancestry information) in order and, based on that, extracts the values for those parameter from the arguments provided in the web service operation invocation call. Ancestry information describes parameters constructed based on suds library's automatic input parameter structure unwrapping. It is expected to include the parameter's XSD schema 'ancestry' context, i.e. a list of all the parent XSD schema tags containing the parameter's <element> tag. Such ancestry context provides detailed information about how the parameter's value is expected to be used, especially in relation to other input parameters, e.g. at most one parameter value may be specified for parameters directly belonging to the same choice input group. Rules on acceptable ancestry items: * Ancestry item's choice() method must return whether the item represents a <choice> XSD schema tag. * Passed ancestry items are used 'by address' internally and the same XSD schema tag is expected to be identified by the exact same ancestry item object during the whole argument processing. During processing, each parameter's definition and value, together with any additional pertinent information collected from the encountered parameter definition structure, is passed on to the provided external parameter processor function. There that information is expected to be used to construct the actual binding specific web service operation invocation request. Raises a TypeError exception in case any argument related errors are detected. The exceptions raised have been constructed to make them as similar as possible to their respective exceptions raised during regular Python function argument checking. Does not support multiple same-named input parameters.
[ "Parse", "arguments", "for", "suds", "web", "service", "operation", "invocation", "functions", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/argparser.py#L29-L83
8,155
suds-community/suds
suds/argparser.py
_ArgParser.__all_parameters_processed
def __all_parameters_processed(self): """ Finish the argument processing. Should be called after all the web service operation's parameters have been successfully processed and, afterwards, no further parameter processing is allowed. Returns a 2-tuple containing the number of required & allowed arguments. See the _ArgParser class description for more detailed information. """ assert self.active() sentinel_frame = self.__stack[0] self.__pop_frames_above(sentinel_frame) assert len(self.__stack) == 1 self.__pop_top_frame() assert not self.active() args_required = sentinel_frame.args_required() args_allowed = sentinel_frame.args_allowed() self.__check_for_extra_arguments(args_required, args_allowed) return args_required, args_allowed
python
def __all_parameters_processed(self): assert self.active() sentinel_frame = self.__stack[0] self.__pop_frames_above(sentinel_frame) assert len(self.__stack) == 1 self.__pop_top_frame() assert not self.active() args_required = sentinel_frame.args_required() args_allowed = sentinel_frame.args_allowed() self.__check_for_extra_arguments(args_required, args_allowed) return args_required, args_allowed
[ "def", "__all_parameters_processed", "(", "self", ")", ":", "assert", "self", ".", "active", "(", ")", "sentinel_frame", "=", "self", ".", "__stack", "[", "0", "]", "self", ".", "__pop_frames_above", "(", "sentinel_frame", ")", "assert", "len", "(", "self", ...
Finish the argument processing. Should be called after all the web service operation's parameters have been successfully processed and, afterwards, no further parameter processing is allowed. Returns a 2-tuple containing the number of required & allowed arguments. See the _ArgParser class description for more detailed information.
[ "Finish", "the", "argument", "processing", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/argparser.py#L124-L147
8,156
suds-community/suds
suds/argparser.py
_ArgParser.__check_for_extra_arguments
def __check_for_extra_arguments(self, args_required, args_allowed): """ Report an error in case any extra arguments are detected. Does nothing if reporting extra arguments as exceptions has not been enabled. May only be called after the argument processing has been completed. """ assert not self.active() if not self.__extra_parameter_errors: return if self.__kwargs: param_name = self.__kwargs.keys()[0] if param_name in self.__params_with_arguments: msg = "got multiple values for parameter '%s'" else: msg = "got an unexpected keyword argument '%s'" self.__error(msg % (param_name,)) if self.__args: def plural_suffix(count): if count == 1: return "" return "s" def plural_was_were(count): if count == 1: return "was" return "were" expected = args_required if args_required != args_allowed: expected = "%d to %d" % (args_required, args_allowed) given = self.__args_count msg_parts = ["takes %s positional argument" % (expected,), plural_suffix(expected), " but %d " % (given,), plural_was_were(given), " given"] self.__error("".join(msg_parts))
python
def __check_for_extra_arguments(self, args_required, args_allowed): assert not self.active() if not self.__extra_parameter_errors: return if self.__kwargs: param_name = self.__kwargs.keys()[0] if param_name in self.__params_with_arguments: msg = "got multiple values for parameter '%s'" else: msg = "got an unexpected keyword argument '%s'" self.__error(msg % (param_name,)) if self.__args: def plural_suffix(count): if count == 1: return "" return "s" def plural_was_were(count): if count == 1: return "was" return "were" expected = args_required if args_required != args_allowed: expected = "%d to %d" % (args_required, args_allowed) given = self.__args_count msg_parts = ["takes %s positional argument" % (expected,), plural_suffix(expected), " but %d " % (given,), plural_was_were(given), " given"] self.__error("".join(msg_parts))
[ "def", "__check_for_extra_arguments", "(", "self", ",", "args_required", ",", "args_allowed", ")", ":", "assert", "not", "self", ".", "active", "(", ")", "if", "not", "self", ".", "__extra_parameter_errors", ":", "return", "if", "self", ".", "__kwargs", ":", ...
Report an error in case any extra arguments are detected. Does nothing if reporting extra arguments as exceptions has not been enabled. May only be called after the argument processing has been completed.
[ "Report", "an", "error", "in", "case", "any", "extra", "arguments", "are", "detected", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/argparser.py#L149-L187
8,157
suds-community/suds
suds/argparser.py
_ArgParser.__frame_factory
def __frame_factory(self, ancestry_item): """Construct a new frame representing the given ancestry item.""" frame_class = Frame if ancestry_item is not None and ancestry_item.choice(): frame_class = ChoiceFrame return frame_class(ancestry_item, self.__error, self.__extra_parameter_errors)
python
def __frame_factory(self, ancestry_item): frame_class = Frame if ancestry_item is not None and ancestry_item.choice(): frame_class = ChoiceFrame return frame_class(ancestry_item, self.__error, self.__extra_parameter_errors)
[ "def", "__frame_factory", "(", "self", ",", "ancestry_item", ")", ":", "frame_class", "=", "Frame", "if", "ancestry_item", "is", "not", "None", "and", "ancestry_item", ".", "choice", "(", ")", ":", "frame_class", "=", "ChoiceFrame", "return", "frame_class", "(...
Construct a new frame representing the given ancestry item.
[ "Construct", "a", "new", "frame", "representing", "the", "given", "ancestry", "item", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/argparser.py#L198-L204
8,158
suds-community/suds
suds/argparser.py
_ArgParser.__get_param_value
def __get_param_value(self, name): """ Extract a parameter value from the remaining given arguments. Returns a 2-tuple consisting of the following: * Boolean indicating whether an argument has been specified for the requested input parameter. * Parameter value. """ if self.__args: return True, self.__args.pop(0) try: value = self.__kwargs.pop(name) except KeyError: return False, None return True, value
python
def __get_param_value(self, name): if self.__args: return True, self.__args.pop(0) try: value = self.__kwargs.pop(name) except KeyError: return False, None return True, value
[ "def", "__get_param_value", "(", "self", ",", "name", ")", ":", "if", "self", ".", "__args", ":", "return", "True", ",", "self", ".", "__args", ".", "pop", "(", "0", ")", "try", ":", "value", "=", "self", ".", "__kwargs", ".", "pop", "(", "name", ...
Extract a parameter value from the remaining given arguments. Returns a 2-tuple consisting of the following: * Boolean indicating whether an argument has been specified for the requested input parameter. * Parameter value.
[ "Extract", "a", "parameter", "value", "from", "the", "remaining", "given", "arguments", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/argparser.py#L206-L222
8,159
suds-community/suds
suds/argparser.py
_ArgParser.__in_choice_context
def __in_choice_context(self): """ Whether we are currently processing a choice parameter group. This includes processing a parameter defined directly or indirectly within such a group. May only be called during parameter processing or the result will be calculated based on the context left behind by the previous parameter processing if any. """ for x in self.__stack: if x.__class__ is ChoiceFrame: return True return False
python
def __in_choice_context(self): for x in self.__stack: if x.__class__ is ChoiceFrame: return True return False
[ "def", "__in_choice_context", "(", "self", ")", ":", "for", "x", "in", "self", ".", "__stack", ":", "if", "x", ".", "__class__", "is", "ChoiceFrame", ":", "return", "True", "return", "False" ]
Whether we are currently processing a choice parameter group. This includes processing a parameter defined directly or indirectly within such a group. May only be called during parameter processing or the result will be calculated based on the context left behind by the previous parameter processing if any.
[ "Whether", "we", "are", "currently", "processing", "a", "choice", "parameter", "group", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/argparser.py#L224-L239
8,160
suds-community/suds
suds/argparser.py
_ArgParser.__init_run
def __init_run(self, args, kwargs, extra_parameter_errors): """Initializes data for a new argument parsing run.""" assert not self.active() self.__args = list(args) self.__kwargs = dict(kwargs) self.__extra_parameter_errors = extra_parameter_errors self.__args_count = len(args) + len(kwargs) self.__params_with_arguments = set() self.__stack = [] self.__push_frame(None)
python
def __init_run(self, args, kwargs, extra_parameter_errors): assert not self.active() self.__args = list(args) self.__kwargs = dict(kwargs) self.__extra_parameter_errors = extra_parameter_errors self.__args_count = len(args) + len(kwargs) self.__params_with_arguments = set() self.__stack = [] self.__push_frame(None)
[ "def", "__init_run", "(", "self", ",", "args", ",", "kwargs", ",", "extra_parameter_errors", ")", ":", "assert", "not", "self", ".", "active", "(", ")", "self", ".", "__args", "=", "list", "(", "args", ")", "self", ".", "__kwargs", "=", "dict", "(", ...
Initializes data for a new argument parsing run.
[ "Initializes", "data", "for", "a", "new", "argument", "parsing", "run", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/argparser.py#L241-L250
8,161
suds-community/suds
suds/argparser.py
_ArgParser.__match_ancestry
def __match_ancestry(self, ancestry): """ Find frames matching the given ancestry. Returns a tuple containing the following: * Topmost frame matching the given ancestry or the bottom-most sentry frame if no frame matches. * Unmatched ancestry part. """ stack = self.__stack if len(stack) == 1: return stack[0], ancestry previous = stack[0] for frame, n in zip(stack[1:], xrange(len(ancestry))): if frame.id() is not ancestry[n]: return previous, ancestry[n:] previous = frame return frame, ancestry[n + 1:]
python
def __match_ancestry(self, ancestry): stack = self.__stack if len(stack) == 1: return stack[0], ancestry previous = stack[0] for frame, n in zip(stack[1:], xrange(len(ancestry))): if frame.id() is not ancestry[n]: return previous, ancestry[n:] previous = frame return frame, ancestry[n + 1:]
[ "def", "__match_ancestry", "(", "self", ",", "ancestry", ")", ":", "stack", "=", "self", ".", "__stack", "if", "len", "(", "stack", ")", "==", "1", ":", "return", "stack", "[", "0", "]", ",", "ancestry", "previous", "=", "stack", "[", "0", "]", "fo...
Find frames matching the given ancestry. Returns a tuple containing the following: * Topmost frame matching the given ancestry or the bottom-most sentry frame if no frame matches. * Unmatched ancestry part.
[ "Find", "frames", "matching", "the", "given", "ancestry", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/argparser.py#L252-L270
8,162
suds-community/suds
suds/argparser.py
_ArgParser.__pop_frames_above
def __pop_frames_above(self, frame): """Pops all the frames above, but not including the given frame.""" while self.__stack[-1] is not frame: self.__pop_top_frame() assert self.__stack
python
def __pop_frames_above(self, frame): while self.__stack[-1] is not frame: self.__pop_top_frame() assert self.__stack
[ "def", "__pop_frames_above", "(", "self", ",", "frame", ")", ":", "while", "self", ".", "__stack", "[", "-", "1", "]", "is", "not", "frame", ":", "self", ".", "__pop_top_frame", "(", ")", "assert", "self", ".", "__stack" ]
Pops all the frames above, but not including the given frame.
[ "Pops", "all", "the", "frames", "above", "but", "not", "including", "the", "given", "frame", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/argparser.py#L272-L276
8,163
suds-community/suds
suds/argparser.py
_ArgParser.__pop_top_frame
def __pop_top_frame(self): """Pops the top frame off the frame stack.""" popped = self.__stack.pop() if self.__stack: self.__stack[-1].process_subframe(popped)
python
def __pop_top_frame(self): popped = self.__stack.pop() if self.__stack: self.__stack[-1].process_subframe(popped)
[ "def", "__pop_top_frame", "(", "self", ")", ":", "popped", "=", "self", ".", "__stack", ".", "pop", "(", ")", "if", "self", ".", "__stack", ":", "self", ".", "__stack", "[", "-", "1", "]", ".", "process_subframe", "(", "popped", ")" ]
Pops the top frame off the frame stack.
[ "Pops", "the", "top", "frame", "off", "the", "frame", "stack", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/argparser.py#L278-L282
8,164
suds-community/suds
suds/argparser.py
_ArgParser.__process_parameter
def __process_parameter(self, param_name, param_type, ancestry=None): """Collect values for a given web service operation input parameter.""" assert self.active() param_optional = param_type.optional() has_argument, value = self.__get_param_value(param_name) if has_argument: self.__params_with_arguments.add(param_name) self.__update_context(ancestry) self.__stack[-1].process_parameter(param_optional, value is not None) self.__external_param_processor(param_name, param_type, self.__in_choice_context(), value)
python
def __process_parameter(self, param_name, param_type, ancestry=None): assert self.active() param_optional = param_type.optional() has_argument, value = self.__get_param_value(param_name) if has_argument: self.__params_with_arguments.add(param_name) self.__update_context(ancestry) self.__stack[-1].process_parameter(param_optional, value is not None) self.__external_param_processor(param_name, param_type, self.__in_choice_context(), value)
[ "def", "__process_parameter", "(", "self", ",", "param_name", ",", "param_type", ",", "ancestry", "=", "None", ")", ":", "assert", "self", ".", "active", "(", ")", "param_optional", "=", "param_type", ".", "optional", "(", ")", "has_argument", ",", "value", ...
Collect values for a given web service operation input parameter.
[ "Collect", "values", "for", "a", "given", "web", "service", "operation", "input", "parameter", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/argparser.py#L284-L294
8,165
suds-community/suds
suds/argparser.py
_ArgParser.__push_frame
def __push_frame(self, ancestry_item): """Push a new frame on top of the frame stack.""" frame = self.__frame_factory(ancestry_item) self.__stack.append(frame)
python
def __push_frame(self, ancestry_item): frame = self.__frame_factory(ancestry_item) self.__stack.append(frame)
[ "def", "__push_frame", "(", "self", ",", "ancestry_item", ")", ":", "frame", "=", "self", ".", "__frame_factory", "(", "ancestry_item", ")", "self", ".", "__stack", ".", "append", "(", "frame", ")" ]
Push a new frame on top of the frame stack.
[ "Push", "a", "new", "frame", "on", "top", "of", "the", "frame", "stack", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/argparser.py#L301-L304
8,166
suds-community/suds
suds/store.py
DocumentStore.open
def open(self, url): """ Open a document at the specified URL. The document URL's needs not contain a protocol identifier, and if it does, that protocol identifier is ignored when looking up the store content. Missing documents referenced using the internal 'suds' protocol are reported by raising an exception. For other protocols, None is returned instead. @param url: A document URL. @type url: str @return: Document content or None if not found. @rtype: bytes """ protocol, location = self.__split(url) content = self.__find(location) if protocol == 'suds' and content is None: raise Exception, 'location "%s" not in document store' % location return content
python
def open(self, url): protocol, location = self.__split(url) content = self.__find(location) if protocol == 'suds' and content is None: raise Exception, 'location "%s" not in document store' % location return content
[ "def", "open", "(", "self", ",", "url", ")", ":", "protocol", ",", "location", "=", "self", ".", "__split", "(", "url", ")", "content", "=", "self", ".", "__find", "(", "location", ")", "if", "protocol", "==", "'suds'", "and", "content", "is", "None"...
Open a document at the specified URL. The document URL's needs not contain a protocol identifier, and if it does, that protocol identifier is ignored when looking up the store content. Missing documents referenced using the internal 'suds' protocol are reported by raising an exception. For other protocols, None is returned instead. @param url: A document URL. @type url: str @return: Document content or None if not found. @rtype: bytes
[ "Open", "a", "document", "at", "the", "specified", "URL", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/store.py#L548-L570
8,167
suds-community/suds
setup.py
read_python_code
def read_python_code(filename): "Returns the given Python source file's compiled content." file = open(filename, "rt") try: source = file.read() finally: file.close() # Python 2.6 and below did not support passing strings to exec() & # compile() functions containing line separators other than '\n'. To # support them we need to manually make sure such line endings get # converted even on platforms where this is not handled by native text file # read operations. source = source.replace("\r\n", "\n").replace("\r", "\n") return compile(source, filename, "exec")
python
def read_python_code(filename): "Returns the given Python source file's compiled content." file = open(filename, "rt") try: source = file.read() finally: file.close() # Python 2.6 and below did not support passing strings to exec() & # compile() functions containing line separators other than '\n'. To # support them we need to manually make sure such line endings get # converted even on platforms where this is not handled by native text file # read operations. source = source.replace("\r\n", "\n").replace("\r", "\n") return compile(source, filename, "exec")
[ "def", "read_python_code", "(", "filename", ")", ":", "file", "=", "open", "(", "filename", ",", "\"rt\"", ")", "try", ":", "source", "=", "file", ".", "read", "(", ")", "finally", ":", "file", ".", "close", "(", ")", "# Python 2.6 and below did not suppor...
Returns the given Python source file's compiled content.
[ "Returns", "the", "given", "Python", "source", "file", "s", "compiled", "content", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/setup.py#L309-L322
8,168
suds-community/suds
setup.py
recursive_package_list
def recursive_package_list(*packages): """ Returns a list of all the given packages and all their subpackages. Given packages are expected to be found relative to this script's location. Subpackages are detected by scanning the given packages' subfolder hierarchy for any folders containing the '__init__.py' module. As a consequence, namespace packages are not supported. This is our own specialized setuptools.find_packages() replacement so we can avoid the setuptools dependency. """ result = set() todo = [] for package in packages: folder = os.path.join(script_folder, *package.split(".")) if not os.path.isdir(folder): raise Exception("Folder not found for package '%s'." % (package,)) todo.append((package, folder)) while todo: package, folder = todo.pop() if package in result: continue result.add(package) for subitem in os.listdir(folder): subpackage = ".".join((package, subitem)) subfolder = os.path.join(folder, subitem) if not os.path.isfile(os.path.join(subfolder, "__init__.py")): continue todo.append((subpackage, subfolder)) return list(result)
python
def recursive_package_list(*packages): result = set() todo = [] for package in packages: folder = os.path.join(script_folder, *package.split(".")) if not os.path.isdir(folder): raise Exception("Folder not found for package '%s'." % (package,)) todo.append((package, folder)) while todo: package, folder = todo.pop() if package in result: continue result.add(package) for subitem in os.listdir(folder): subpackage = ".".join((package, subitem)) subfolder = os.path.join(folder, subitem) if not os.path.isfile(os.path.join(subfolder, "__init__.py")): continue todo.append((subpackage, subfolder)) return list(result)
[ "def", "recursive_package_list", "(", "*", "packages", ")", ":", "result", "=", "set", "(", ")", "todo", "=", "[", "]", "for", "package", "in", "packages", ":", "folder", "=", "os", ".", "path", ".", "join", "(", "script_folder", ",", "*", "package", ...
Returns a list of all the given packages and all their subpackages. Given packages are expected to be found relative to this script's location. Subpackages are detected by scanning the given packages' subfolder hierarchy for any folders containing the '__init__.py' module. As a consequence, namespace packages are not supported. This is our own specialized setuptools.find_packages() replacement so we can avoid the setuptools dependency.
[ "Returns", "a", "list", "of", "all", "the", "given", "packages", "and", "all", "their", "subpackages", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/setup.py#L324-L356
8,169
suds-community/suds
suds/xsd/sxbase.py
SchemaObject.find
def find(self, qref, classes=[], ignore=None): """ Find a referenced type in self or children. Return None if not found. Qualified references for all schema objects checked in this search will be added to the set of ignored qualified references to avoid the find operation going into an infinite loop in case of recursively defined structures. @param qref: A qualified reference. @type qref: qref @param classes: A collection of classes used to qualify the match. @type classes: Collection(I{class},...), e.g. [I(class),...] @param ignore: A set of qualified references to ignore in this search. @type ignore: {qref,...} @return: The referenced type. @rtype: L{SchemaObject} @see: L{qualify()} """ if not len(classes): classes = (self.__class__,) if ignore is None: ignore = set() if self.qname in ignore: return ignore.add(self.qname) if self.qname == qref and self.__class__ in classes: return self for c in self.rawchildren: p = c.find(qref, classes, ignore=ignore) if p is not None: return p
python
def find(self, qref, classes=[], ignore=None): if not len(classes): classes = (self.__class__,) if ignore is None: ignore = set() if self.qname in ignore: return ignore.add(self.qname) if self.qname == qref and self.__class__ in classes: return self for c in self.rawchildren: p = c.find(qref, classes, ignore=ignore) if p is not None: return p
[ "def", "find", "(", "self", ",", "qref", ",", "classes", "=", "[", "]", ",", "ignore", "=", "None", ")", ":", "if", "not", "len", "(", "classes", ")", ":", "classes", "=", "(", "self", ".", "__class__", ",", ")", "if", "ignore", "is", "None", "...
Find a referenced type in self or children. Return None if not found. Qualified references for all schema objects checked in this search will be added to the set of ignored qualified references to avoid the find operation going into an infinite loop in case of recursively defined structures. @param qref: A qualified reference. @type qref: qref @param classes: A collection of classes used to qualify the match. @type classes: Collection(I{class},...), e.g. [I(class),...] @param ignore: A set of qualified references to ignore in this search. @type ignore: {qref,...} @return: The referenced type. @rtype: L{SchemaObject} @see: L{qualify()}
[ "Find", "a", "referenced", "type", "in", "self", "or", "children", ".", "Return", "None", "if", "not", "found", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/xsd/sxbase.py#L342-L374
8,170
suds-community/suds
suds/xsd/sxbase.py
Iter.next
def next(self): """ Get the next item. @return: A tuple: the next (child, ancestry). @rtype: (L{SchemaObject}, [L{SchemaObject},..]) @raise StopIteration: A the end. """ frame = self.top() while True: result = frame.next() if result is None: self.pop() return self.next() if isinstance(result, Content): ancestry = [f.sx for f in self.stack] return result, ancestry self.push(result) return self.next()
python
def next(self): frame = self.top() while True: result = frame.next() if result is None: self.pop() return self.next() if isinstance(result, Content): ancestry = [f.sx for f in self.stack] return result, ancestry self.push(result) return self.next()
[ "def", "next", "(", "self", ")", ":", "frame", "=", "self", ".", "top", "(", ")", "while", "True", ":", "result", "=", "frame", ".", "next", "(", ")", "if", "result", "is", "None", ":", "self", ".", "pop", "(", ")", "return", "self", ".", "next...
Get the next item. @return: A tuple: the next (child, ancestry). @rtype: (L{SchemaObject}, [L{SchemaObject},..]) @raise StopIteration: A the end.
[ "Get", "the", "next", "item", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/xsd/sxbase.py#L657-L676
8,171
suds-community/suds
suds/servicedefinition.py
ServiceDefinition.getprefixes
def getprefixes(self): """Add prefixes for each namespace referenced by parameter types.""" namespaces = [] for l in (self.params, self.types): for t,r in l: ns = r.namespace() if ns[1] is None: continue if ns[1] in namespaces: continue if Namespace.xs(ns) or Namespace.xsd(ns): continue namespaces.append(ns[1]) if t == r: continue ns = t.namespace() if ns[1] is None: continue if ns[1] in namespaces: continue namespaces.append(ns[1]) i = 0 namespaces.sort() for u in namespaces: p = self.nextprefix() ns = (p, u) self.prefixes.append(ns)
python
def getprefixes(self): namespaces = [] for l in (self.params, self.types): for t,r in l: ns = r.namespace() if ns[1] is None: continue if ns[1] in namespaces: continue if Namespace.xs(ns) or Namespace.xsd(ns): continue namespaces.append(ns[1]) if t == r: continue ns = t.namespace() if ns[1] is None: continue if ns[1] in namespaces: continue namespaces.append(ns[1]) i = 0 namespaces.sort() for u in namespaces: p = self.nextprefix() ns = (p, u) self.prefixes.append(ns)
[ "def", "getprefixes", "(", "self", ")", ":", "namespaces", "=", "[", "]", "for", "l", "in", "(", "self", ".", "params", ",", "self", ".", "types", ")", ":", "for", "t", ",", "r", "in", "l", ":", "ns", "=", "r", ".", "namespace", "(", ")", "if...
Add prefixes for each namespace referenced by parameter types.
[ "Add", "prefixes", "for", "each", "namespace", "referenced", "by", "parameter", "types", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/servicedefinition.py#L107-L128
8,172
suds-community/suds
suds/servicedefinition.py
ServiceDefinition.description
def description(self): """ Get a textual description of the service for which this object represents. @return: A textual description. @rtype: str """ s = [] indent = (lambda n : '\n%*s'%(n*3,' ')) s.append('Service ( %s ) tns="%s"' % (self.service.name, self.wsdl.tns[1])) s.append(indent(1)) s.append('Prefixes (%d)' % len(self.prefixes)) for p in self.prefixes: s.append(indent(2)) s.append('%s = "%s"' % p) s.append(indent(1)) s.append('Ports (%d):' % len(self.ports)) for p in self.ports: s.append(indent(2)) s.append('(%s)' % p[0].name) s.append(indent(3)) s.append('Methods (%d):' % len(p[1])) for m in p[1]: sig = [] s.append(indent(4)) sig.append(m[0]) sig.append('(') sig.append(', '.join("%s %s" % (self.xlate(p[1]), p[0]) for p in m[1])) sig.append(')') try: s.append(''.join(sig)) except Exception: pass s.append(indent(3)) s.append('Types (%d):' % len(self.types)) for t in self.types: s.append(indent(4)) s.append(self.xlate(t[0])) s.append('\n\n') return ''.join(s)
python
def description(self): s = [] indent = (lambda n : '\n%*s'%(n*3,' ')) s.append('Service ( %s ) tns="%s"' % (self.service.name, self.wsdl.tns[1])) s.append(indent(1)) s.append('Prefixes (%d)' % len(self.prefixes)) for p in self.prefixes: s.append(indent(2)) s.append('%s = "%s"' % p) s.append(indent(1)) s.append('Ports (%d):' % len(self.ports)) for p in self.ports: s.append(indent(2)) s.append('(%s)' % p[0].name) s.append(indent(3)) s.append('Methods (%d):' % len(p[1])) for m in p[1]: sig = [] s.append(indent(4)) sig.append(m[0]) sig.append('(') sig.append(', '.join("%s %s" % (self.xlate(p[1]), p[0]) for p in m[1])) sig.append(')') try: s.append(''.join(sig)) except Exception: pass s.append(indent(3)) s.append('Types (%d):' % len(self.types)) for t in self.types: s.append(indent(4)) s.append(self.xlate(t[0])) s.append('\n\n') return ''.join(s)
[ "def", "description", "(", "self", ")", ":", "s", "=", "[", "]", "indent", "=", "(", "lambda", "n", ":", "'\\n%*s'", "%", "(", "n", "*", "3", ",", "' '", ")", ")", "s", ".", "append", "(", "'Service ( %s ) tns=\"%s\"'", "%", "(", "self", ".", "se...
Get a textual description of the service for which this object represents. @return: A textual description. @rtype: str
[ "Get", "a", "textual", "description", "of", "the", "service", "for", "which", "this", "object", "represents", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/servicedefinition.py#L194-L233
8,173
suds-community/suds
suds/sax/document.py
Document.plain
def plain(self): """ Get a string representation of this XML document. @return: A I{plain} string. @rtype: basestring """ s = [] s.append(self.DECL) root = self.root() if root is not None: s.append(root.plain()) return ''.join(s)
python
def plain(self): s = [] s.append(self.DECL) root = self.root() if root is not None: s.append(root.plain()) return ''.join(s)
[ "def", "plain", "(", "self", ")", ":", "s", "=", "[", "]", "s", ".", "append", "(", "self", ".", "DECL", ")", "root", "=", "self", ".", "root", "(", ")", "if", "root", "is", "not", "None", ":", "s", ".", "append", "(", "root", ".", "plain", ...
Get a string representation of this XML document. @return: A I{plain} string. @rtype: basestring
[ "Get", "a", "string", "representation", "of", "this", "XML", "document", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/sax/document.py#L162-L173
8,174
suds-community/suds
suds/xsd/schema.py
SchemaCollection.merge
def merge(self): """ Merge contained schemas into one. @return: The merged schema. @rtype: L{Schema} """ if self.children: schema = self.children[0] for s in self.children[1:]: schema.merge(s) return schema
python
def merge(self): if self.children: schema = self.children[0] for s in self.children[1:]: schema.merge(s) return schema
[ "def", "merge", "(", "self", ")", ":", "if", "self", ".", "children", ":", "schema", "=", "self", ".", "children", "[", "0", "]", "for", "s", "in", "self", ".", "children", "[", "1", ":", "]", ":", "schema", ".", "merge", "(", "s", ")", "return...
Merge contained schemas into one. @return: The merged schema. @rtype: L{Schema}
[ "Merge", "contained", "schemas", "into", "one", "." ]
6fb0a829337b5037a66c20aae6f89b41acd77e40
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/xsd/schema.py#L146-L158
8,175
remind101/stacker_blueprints
stacker_blueprints/sns.py
Topics.create_sqs_policy
def create_sqs_policy(self, topic_name, topic_arn, topic_subs): """ This method creates the SQS policy needed for an SNS subscription. It also takes the ARN of the SQS queue and converts it to the URL needed for the subscription, as that takes a URL rather than the ARN. """ t = self.template arn_endpoints = [] url_endpoints = [] for sub in topic_subs: arn_endpoints.append(sub["Endpoint"]) split_endpoint = sub["Endpoint"].split(":") queue_url = "https://%s.%s.amazonaws.com/%s/%s" % ( split_endpoint[2], # literally "sqs" split_endpoint[3], # AWS region split_endpoint[4], # AWS ID split_endpoint[5], # Queue name ) url_endpoints.append(queue_url) policy_doc = queue_policy(topic_arn, arn_endpoints) t.add_resource( sqs.QueuePolicy( topic_name + "SubPolicy", PolicyDocument=policy_doc, Queues=url_endpoints, ) )
python
def create_sqs_policy(self, topic_name, topic_arn, topic_subs): t = self.template arn_endpoints = [] url_endpoints = [] for sub in topic_subs: arn_endpoints.append(sub["Endpoint"]) split_endpoint = sub["Endpoint"].split(":") queue_url = "https://%s.%s.amazonaws.com/%s/%s" % ( split_endpoint[2], # literally "sqs" split_endpoint[3], # AWS region split_endpoint[4], # AWS ID split_endpoint[5], # Queue name ) url_endpoints.append(queue_url) policy_doc = queue_policy(topic_arn, arn_endpoints) t.add_resource( sqs.QueuePolicy( topic_name + "SubPolicy", PolicyDocument=policy_doc, Queues=url_endpoints, ) )
[ "def", "create_sqs_policy", "(", "self", ",", "topic_name", ",", "topic_arn", ",", "topic_subs", ")", ":", "t", "=", "self", ".", "template", "arn_endpoints", "=", "[", "]", "url_endpoints", "=", "[", "]", "for", "sub", "in", "topic_subs", ":", "arn_endpoi...
This method creates the SQS policy needed for an SNS subscription. It also takes the ARN of the SQS queue and converts it to the URL needed for the subscription, as that takes a URL rather than the ARN.
[ "This", "method", "creates", "the", "SQS", "policy", "needed", "for", "an", "SNS", "subscription", ".", "It", "also", "takes", "the", "ARN", "of", "the", "SQS", "queue", "and", "converts", "it", "to", "the", "URL", "needed", "for", "the", "subscription", ...
71624f6e1bd4ea794dc98fb621a04235e1931cae
https://github.com/remind101/stacker_blueprints/blob/71624f6e1bd4ea794dc98fb621a04235e1931cae/stacker_blueprints/sns.py#L81-L110
8,176
remind101/stacker_blueprints
stacker_blueprints/sns.py
Topics.create_topic
def create_topic(self, topic_name, topic_config): """ Creates the SNS topic, along with any subscriptions requested. """ topic_subs = [] t = self.template if "Subscription" in topic_config: topic_subs = topic_config["Subscription"] t.add_resource( sns.Topic.from_dict( topic_name, topic_config ) ) topic_arn = Ref(topic_name) t.add_output( Output(topic_name + "Name", Value=GetAtt(topic_name, "TopicName")) ) t.add_output(Output(topic_name + "Arn", Value=topic_arn)) sqs_subs = [sub for sub in topic_subs if sub["Protocol"] == "sqs"] if sqs_subs: self.create_sqs_policy(topic_name, topic_arn, sqs_subs)
python
def create_topic(self, topic_name, topic_config): topic_subs = [] t = self.template if "Subscription" in topic_config: topic_subs = topic_config["Subscription"] t.add_resource( sns.Topic.from_dict( topic_name, topic_config ) ) topic_arn = Ref(topic_name) t.add_output( Output(topic_name + "Name", Value=GetAtt(topic_name, "TopicName")) ) t.add_output(Output(topic_name + "Arn", Value=topic_arn)) sqs_subs = [sub for sub in topic_subs if sub["Protocol"] == "sqs"] if sqs_subs: self.create_sqs_policy(topic_name, topic_arn, sqs_subs)
[ "def", "create_topic", "(", "self", ",", "topic_name", ",", "topic_config", ")", ":", "topic_subs", "=", "[", "]", "t", "=", "self", ".", "template", "if", "\"Subscription\"", "in", "topic_config", ":", "topic_subs", "=", "topic_config", "[", "\"Subscription\"...
Creates the SNS topic, along with any subscriptions requested.
[ "Creates", "the", "SNS", "topic", "along", "with", "any", "subscriptions", "requested", "." ]
71624f6e1bd4ea794dc98fb621a04235e1931cae
https://github.com/remind101/stacker_blueprints/blob/71624f6e1bd4ea794dc98fb621a04235e1931cae/stacker_blueprints/sns.py#L112-L138
8,177
remind101/stacker_blueprints
stacker_blueprints/aws_lambda.py
get_stream_action_type
def get_stream_action_type(stream_arn): """Returns the awacs Action for a stream type given an arn Args: stream_arn (str): The Arn of the stream. Returns: :class:`awacs.aws.Action`: The appropriate stream type awacs Action class Raises: ValueError: If the stream type doesn't match kinesis or dynamodb. """ stream_type_map = { "kinesis": awacs.kinesis.Action, "dynamodb": awacs.dynamodb.Action, } stream_type = stream_arn.split(":")[2] try: return stream_type_map[stream_type] except KeyError: raise ValueError( "Invalid stream type '%s' in arn '%s'" % (stream_type, stream_arn) )
python
def get_stream_action_type(stream_arn): stream_type_map = { "kinesis": awacs.kinesis.Action, "dynamodb": awacs.dynamodb.Action, } stream_type = stream_arn.split(":")[2] try: return stream_type_map[stream_type] except KeyError: raise ValueError( "Invalid stream type '%s' in arn '%s'" % (stream_type, stream_arn) )
[ "def", "get_stream_action_type", "(", "stream_arn", ")", ":", "stream_type_map", "=", "{", "\"kinesis\"", ":", "awacs", ".", "kinesis", ".", "Action", ",", "\"dynamodb\"", ":", "awacs", ".", "dynamodb", ".", "Action", ",", "}", "stream_type", "=", "stream_arn"...
Returns the awacs Action for a stream type given an arn Args: stream_arn (str): The Arn of the stream. Returns: :class:`awacs.aws.Action`: The appropriate stream type awacs Action class Raises: ValueError: If the stream type doesn't match kinesis or dynamodb.
[ "Returns", "the", "awacs", "Action", "for", "a", "stream", "type", "given", "an", "arn" ]
71624f6e1bd4ea794dc98fb621a04235e1931cae
https://github.com/remind101/stacker_blueprints/blob/71624f6e1bd4ea794dc98fb621a04235e1931cae/stacker_blueprints/aws_lambda.py#L37-L62
8,178
remind101/stacker_blueprints
stacker_blueprints/aws_lambda.py
stream_reader_statements
def stream_reader_statements(stream_arn): """Returns statements to allow Lambda to read from a stream. Handles both DynamoDB & Kinesis streams. Automatically figures out the type of stream, and provides the correct actions from the supplied Arn. Arg: stream_arn (str): A kinesis or dynamodb stream arn. Returns: list: A list of statements. """ action_type = get_stream_action_type(stream_arn) arn_parts = stream_arn.split("/") # Cut off the last bit and replace it with a wildcard wildcard_arn_parts = arn_parts[:-1] wildcard_arn_parts.append("*") wildcard_arn = "/".join(wildcard_arn_parts) return [ Statement( Effect=Allow, Resource=[stream_arn], Action=[ action_type("DescribeStream"), action_type("GetRecords"), action_type("GetShardIterator"), ] ), Statement( Effect=Allow, Resource=[wildcard_arn], Action=[action_type("ListStreams")] ) ]
python
def stream_reader_statements(stream_arn): action_type = get_stream_action_type(stream_arn) arn_parts = stream_arn.split("/") # Cut off the last bit and replace it with a wildcard wildcard_arn_parts = arn_parts[:-1] wildcard_arn_parts.append("*") wildcard_arn = "/".join(wildcard_arn_parts) return [ Statement( Effect=Allow, Resource=[stream_arn], Action=[ action_type("DescribeStream"), action_type("GetRecords"), action_type("GetShardIterator"), ] ), Statement( Effect=Allow, Resource=[wildcard_arn], Action=[action_type("ListStreams")] ) ]
[ "def", "stream_reader_statements", "(", "stream_arn", ")", ":", "action_type", "=", "get_stream_action_type", "(", "stream_arn", ")", "arn_parts", "=", "stream_arn", ".", "split", "(", "\"/\"", ")", "# Cut off the last bit and replace it with a wildcard", "wildcard_arn_part...
Returns statements to allow Lambda to read from a stream. Handles both DynamoDB & Kinesis streams. Automatically figures out the type of stream, and provides the correct actions from the supplied Arn. Arg: stream_arn (str): A kinesis or dynamodb stream arn. Returns: list: A list of statements.
[ "Returns", "statements", "to", "allow", "Lambda", "to", "read", "from", "a", "stream", "." ]
71624f6e1bd4ea794dc98fb621a04235e1931cae
https://github.com/remind101/stacker_blueprints/blob/71624f6e1bd4ea794dc98fb621a04235e1931cae/stacker_blueprints/aws_lambda.py#L65-L99
8,179
remind101/stacker_blueprints
stacker_blueprints/aws_lambda.py
Function.add_policy_statements
def add_policy_statements(self, statements): """Adds statements to the policy. Args: statements (:class:`awacs.aws.Statement` or list): Either a single Statment, or a list of statements. """ if isinstance(statements, Statement): statements = [statements] self._policy_statements.extend(statements)
python
def add_policy_statements(self, statements): if isinstance(statements, Statement): statements = [statements] self._policy_statements.extend(statements)
[ "def", "add_policy_statements", "(", "self", ",", "statements", ")", ":", "if", "isinstance", "(", "statements", ",", "Statement", ")", ":", "statements", "=", "[", "statements", "]", "self", ".", "_policy_statements", ".", "extend", "(", "statements", ")" ]
Adds statements to the policy. Args: statements (:class:`awacs.aws.Statement` or list): Either a single Statment, or a list of statements.
[ "Adds", "statements", "to", "the", "policy", "." ]
71624f6e1bd4ea794dc98fb621a04235e1931cae
https://github.com/remind101/stacker_blueprints/blob/71624f6e1bd4ea794dc98fb621a04235e1931cae/stacker_blueprints/aws_lambda.py#L221-L230
8,180
remind101/stacker_blueprints
stacker_blueprints/aws_lambda.py
Function.generate_policy_statements
def generate_policy_statements(self): """Generates the policy statements for the role used by the function. To add additional statements you can either override the `extended_policy_statements` method to return a list of Statements to be added to the policy, or override this method itself if you need more control. Returns: list: A list of :class:`awacs.aws.Statement` objects. """ statements = self._policy_statements statements.extend( lambda_basic_execution_statements( self.function.Ref() ) ) extended_statements = self.extended_policy_statements() if extended_statements: statements.extend(extended_statements) return statements
python
def generate_policy_statements(self): statements = self._policy_statements statements.extend( lambda_basic_execution_statements( self.function.Ref() ) ) extended_statements = self.extended_policy_statements() if extended_statements: statements.extend(extended_statements) return statements
[ "def", "generate_policy_statements", "(", "self", ")", ":", "statements", "=", "self", ".", "_policy_statements", "statements", ".", "extend", "(", "lambda_basic_execution_statements", "(", "self", ".", "function", ".", "Ref", "(", ")", ")", ")", "extended_stateme...
Generates the policy statements for the role used by the function. To add additional statements you can either override the `extended_policy_statements` method to return a list of Statements to be added to the policy, or override this method itself if you need more control. Returns: list: A list of :class:`awacs.aws.Statement` objects.
[ "Generates", "the", "policy", "statements", "for", "the", "role", "used", "by", "the", "function", "." ]
71624f6e1bd4ea794dc98fb621a04235e1931cae
https://github.com/remind101/stacker_blueprints/blob/71624f6e1bd4ea794dc98fb621a04235e1931cae/stacker_blueprints/aws_lambda.py#L240-L260
8,181
remind101/stacker_blueprints
stacker_blueprints/generic.py
GenericResourceCreator.setup_resource
def setup_resource(self): """ Setting Up Resource """ template = self.template variables = self.get_variables() tclass = variables['Class'] tprops = variables['Properties'] output = variables['Output'] klass = load_object_from_string('troposphere.' + tclass) instance = klass.from_dict('ResourceRefName', tprops) template.add_resource(instance) template.add_output(Output( output, Description="A reference to the object created in this blueprint", Value=Ref(instance) ))
python
def setup_resource(self): template = self.template variables = self.get_variables() tclass = variables['Class'] tprops = variables['Properties'] output = variables['Output'] klass = load_object_from_string('troposphere.' + tclass) instance = klass.from_dict('ResourceRefName', tprops) template.add_resource(instance) template.add_output(Output( output, Description="A reference to the object created in this blueprint", Value=Ref(instance) ))
[ "def", "setup_resource", "(", "self", ")", ":", "template", "=", "self", ".", "template", "variables", "=", "self", ".", "get_variables", "(", ")", "tclass", "=", "variables", "[", "'Class'", "]", "tprops", "=", "variables", "[", "'Properties'", "]", "outp...
Setting Up Resource
[ "Setting", "Up", "Resource" ]
71624f6e1bd4ea794dc98fb621a04235e1931cae
https://github.com/remind101/stacker_blueprints/blob/71624f6e1bd4ea794dc98fb621a04235e1931cae/stacker_blueprints/generic.py#L57-L75
8,182
remind101/stacker_blueprints
stacker_blueprints/kms.py
kms_key_policy
def kms_key_policy(): """ Creates a key policy for use of a KMS Key. """ statements = [] statements.extend(kms_key_root_statements()) return Policy( Version="2012-10-17", Id="root-account-access", Statement=statements )
python
def kms_key_policy(): statements = [] statements.extend(kms_key_root_statements()) return Policy( Version="2012-10-17", Id="root-account-access", Statement=statements )
[ "def", "kms_key_policy", "(", ")", ":", "statements", "=", "[", "]", "statements", ".", "extend", "(", "kms_key_root_statements", "(", ")", ")", "return", "Policy", "(", "Version", "=", "\"2012-10-17\"", ",", "Id", "=", "\"root-account-access\"", ",", "Stateme...
Creates a key policy for use of a KMS Key.
[ "Creates", "a", "key", "policy", "for", "use", "of", "a", "KMS", "Key", "." ]
71624f6e1bd4ea794dc98fb621a04235e1931cae
https://github.com/remind101/stacker_blueprints/blob/71624f6e1bd4ea794dc98fb621a04235e1931cae/stacker_blueprints/kms.py#L40-L50
8,183
remind101/stacker_blueprints
stacker_blueprints/empire/policies.py
logstream_policy
def logstream_policy(): """Policy needed for logspout -> kinesis log streaming.""" p = Policy( Statement=[ Statement( Effect=Allow, Resource=["*"], Action=[ kinesis.CreateStream, kinesis.DescribeStream, Action(kinesis.prefix, "AddTagsToStream"), Action(kinesis.prefix, "PutRecords") ])]) return p
python
def logstream_policy(): p = Policy( Statement=[ Statement( Effect=Allow, Resource=["*"], Action=[ kinesis.CreateStream, kinesis.DescribeStream, Action(kinesis.prefix, "AddTagsToStream"), Action(kinesis.prefix, "PutRecords") ])]) return p
[ "def", "logstream_policy", "(", ")", ":", "p", "=", "Policy", "(", "Statement", "=", "[", "Statement", "(", "Effect", "=", "Allow", ",", "Resource", "=", "[", "\"*\"", "]", ",", "Action", "=", "[", "kinesis", ".", "CreateStream", ",", "kinesis", ".", ...
Policy needed for logspout -> kinesis log streaming.
[ "Policy", "needed", "for", "logspout", "-", ">", "kinesis", "log", "streaming", "." ]
71624f6e1bd4ea794dc98fb621a04235e1931cae
https://github.com/remind101/stacker_blueprints/blob/71624f6e1bd4ea794dc98fb621a04235e1931cae/stacker_blueprints/empire/policies.py#L245-L257
8,184
remind101/stacker_blueprints
stacker_blueprints/empire/policies.py
runlogs_policy
def runlogs_policy(log_group_ref): """Policy needed for Empire -> Cloudwatch logs to record run output.""" p = Policy( Statement=[ Statement( Effect=Allow, Resource=[ Join('', [ 'arn:aws:logs:*:*:log-group:', log_group_ref, ':log-stream:*'])], Action=[ logs.CreateLogStream, logs.PutLogEvents, ])]) return p
python
def runlogs_policy(log_group_ref): p = Policy( Statement=[ Statement( Effect=Allow, Resource=[ Join('', [ 'arn:aws:logs:*:*:log-group:', log_group_ref, ':log-stream:*'])], Action=[ logs.CreateLogStream, logs.PutLogEvents, ])]) return p
[ "def", "runlogs_policy", "(", "log_group_ref", ")", ":", "p", "=", "Policy", "(", "Statement", "=", "[", "Statement", "(", "Effect", "=", "Allow", ",", "Resource", "=", "[", "Join", "(", "''", ",", "[", "'arn:aws:logs:*:*:log-group:'", ",", "log_group_ref", ...
Policy needed for Empire -> Cloudwatch logs to record run output.
[ "Policy", "needed", "for", "Empire", "-", ">", "Cloudwatch", "logs", "to", "record", "run", "output", "." ]
71624f6e1bd4ea794dc98fb621a04235e1931cae
https://github.com/remind101/stacker_blueprints/blob/71624f6e1bd4ea794dc98fb621a04235e1931cae/stacker_blueprints/empire/policies.py#L260-L275
8,185
remind101/stacker_blueprints
stacker_blueprints/util.py
check_properties
def check_properties(properties, allowed_properties, resource): """Checks the list of properties in the properties variable against the property list provided by the allowed_properties variable. If any property does not match the properties in allowed_properties, a ValueError is raised to prevent unexpected behavior when creating resources. properties: The config (as dict) provided by the configuration file allowed_properties: A list of strings representing the available params for a resource. resource: A string naming the resource in question for the error message. """ for key in properties.keys(): if key not in allowed_properties: raise ValueError( "%s is not a valid property of %s" % (key, resource) )
python
def check_properties(properties, allowed_properties, resource): for key in properties.keys(): if key not in allowed_properties: raise ValueError( "%s is not a valid property of %s" % (key, resource) )
[ "def", "check_properties", "(", "properties", ",", "allowed_properties", ",", "resource", ")", ":", "for", "key", "in", "properties", ".", "keys", "(", ")", ":", "if", "key", "not", "in", "allowed_properties", ":", "raise", "ValueError", "(", "\"%s is not a va...
Checks the list of properties in the properties variable against the property list provided by the allowed_properties variable. If any property does not match the properties in allowed_properties, a ValueError is raised to prevent unexpected behavior when creating resources. properties: The config (as dict) provided by the configuration file allowed_properties: A list of strings representing the available params for a resource. resource: A string naming the resource in question for the error message.
[ "Checks", "the", "list", "of", "properties", "in", "the", "properties", "variable", "against", "the", "property", "list", "provided", "by", "the", "allowed_properties", "variable", ".", "If", "any", "property", "does", "not", "match", "the", "properties", "in", ...
71624f6e1bd4ea794dc98fb621a04235e1931cae
https://github.com/remind101/stacker_blueprints/blob/71624f6e1bd4ea794dc98fb621a04235e1931cae/stacker_blueprints/util.py#L6-L22
8,186
remind101/stacker_blueprints
stacker_blueprints/util.py
merge_tags
def merge_tags(left, right, factory=Tags): """ Merge two sets of tags into a new troposphere object Args: left (Union[dict, troposphere.Tags]): dictionary or Tags object to be merged with lower priority right (Union[dict, troposphere.Tags]): dictionary or Tags object to be merged with higher priority factory (type): Type of object to create. Defaults to the troposphere Tags class. """ if isinstance(left, Mapping): tags = dict(left) elif hasattr(left, 'tags'): tags = _tags_to_dict(left.tags) else: tags = _tags_to_dict(left) if isinstance(right, Mapping): tags.update(right) elif hasattr(left, 'tags'): tags.update(_tags_to_dict(right.tags)) else: tags.update(_tags_to_dict(right)) return factory(**tags)
python
def merge_tags(left, right, factory=Tags): if isinstance(left, Mapping): tags = dict(left) elif hasattr(left, 'tags'): tags = _tags_to_dict(left.tags) else: tags = _tags_to_dict(left) if isinstance(right, Mapping): tags.update(right) elif hasattr(left, 'tags'): tags.update(_tags_to_dict(right.tags)) else: tags.update(_tags_to_dict(right)) return factory(**tags)
[ "def", "merge_tags", "(", "left", ",", "right", ",", "factory", "=", "Tags", ")", ":", "if", "isinstance", "(", "left", ",", "Mapping", ")", ":", "tags", "=", "dict", "(", "left", ")", "elif", "hasattr", "(", "left", ",", "'tags'", ")", ":", "tags"...
Merge two sets of tags into a new troposphere object Args: left (Union[dict, troposphere.Tags]): dictionary or Tags object to be merged with lower priority right (Union[dict, troposphere.Tags]): dictionary or Tags object to be merged with higher priority factory (type): Type of object to create. Defaults to the troposphere Tags class.
[ "Merge", "two", "sets", "of", "tags", "into", "a", "new", "troposphere", "object" ]
71624f6e1bd4ea794dc98fb621a04235e1931cae
https://github.com/remind101/stacker_blueprints/blob/71624f6e1bd4ea794dc98fb621a04235e1931cae/stacker_blueprints/util.py#L29-L56
8,187
remind101/stacker_blueprints
stacker_blueprints/route53.py
get_record_set_md5
def get_record_set_md5(rs_name, rs_type): """Accept record_set Name and Type. Return MD5 sum of these values.""" rs_name = rs_name.lower() rs_type = rs_type.upper() # Make A and CNAME records hash to same sum to support updates. rs_type = "ACNAME" if rs_type in ["A", "CNAME"] else rs_type return md5(rs_name + rs_type).hexdigest()
python
def get_record_set_md5(rs_name, rs_type): rs_name = rs_name.lower() rs_type = rs_type.upper() # Make A and CNAME records hash to same sum to support updates. rs_type = "ACNAME" if rs_type in ["A", "CNAME"] else rs_type return md5(rs_name + rs_type).hexdigest()
[ "def", "get_record_set_md5", "(", "rs_name", ",", "rs_type", ")", ":", "rs_name", "=", "rs_name", ".", "lower", "(", ")", "rs_type", "=", "rs_type", ".", "upper", "(", ")", "# Make A and CNAME records hash to same sum to support updates.", "rs_type", "=", "\"ACNAME\...
Accept record_set Name and Type. Return MD5 sum of these values.
[ "Accept", "record_set", "Name", "and", "Type", ".", "Return", "MD5", "sum", "of", "these", "values", "." ]
71624f6e1bd4ea794dc98fb621a04235e1931cae
https://github.com/remind101/stacker_blueprints/blob/71624f6e1bd4ea794dc98fb621a04235e1931cae/stacker_blueprints/route53.py#L66-L72
8,188
remind101/stacker_blueprints
stacker_blueprints/route53.py
DNSRecords.add_hosted_zone_id_for_alias_target_if_missing
def add_hosted_zone_id_for_alias_target_if_missing(self, rs): """Add proper hosted zone id to record set alias target if missing.""" alias_target = getattr(rs, "AliasTarget", None) if alias_target: hosted_zone_id = getattr(alias_target, "HostedZoneId", None) if not hosted_zone_id: dns_name = alias_target.DNSName if dns_name.endswith(CF_DOMAIN): alias_target.HostedZoneId = CLOUDFRONT_ZONE_ID elif dns_name.endswith(ELB_DOMAIN): region = dns_name.split('.')[-5] alias_target.HostedZoneId = ELB_ZONE_IDS[region] elif dns_name in S3_WEBSITE_ZONE_IDS: alias_target.HostedZoneId = S3_WEBSITE_ZONE_IDS[dns_name] else: alias_target.HostedZoneId = self.hosted_zone_id return rs
python
def add_hosted_zone_id_for_alias_target_if_missing(self, rs): alias_target = getattr(rs, "AliasTarget", None) if alias_target: hosted_zone_id = getattr(alias_target, "HostedZoneId", None) if not hosted_zone_id: dns_name = alias_target.DNSName if dns_name.endswith(CF_DOMAIN): alias_target.HostedZoneId = CLOUDFRONT_ZONE_ID elif dns_name.endswith(ELB_DOMAIN): region = dns_name.split('.')[-5] alias_target.HostedZoneId = ELB_ZONE_IDS[region] elif dns_name in S3_WEBSITE_ZONE_IDS: alias_target.HostedZoneId = S3_WEBSITE_ZONE_IDS[dns_name] else: alias_target.HostedZoneId = self.hosted_zone_id return rs
[ "def", "add_hosted_zone_id_for_alias_target_if_missing", "(", "self", ",", "rs", ")", ":", "alias_target", "=", "getattr", "(", "rs", ",", "\"AliasTarget\"", ",", "None", ")", "if", "alias_target", ":", "hosted_zone_id", "=", "getattr", "(", "alias_target", ",", ...
Add proper hosted zone id to record set alias target if missing.
[ "Add", "proper", "hosted", "zone", "id", "to", "record", "set", "alias", "target", "if", "missing", "." ]
71624f6e1bd4ea794dc98fb621a04235e1931cae
https://github.com/remind101/stacker_blueprints/blob/71624f6e1bd4ea794dc98fb621a04235e1931cae/stacker_blueprints/route53.py#L123-L139
8,189
remind101/stacker_blueprints
stacker_blueprints/route53.py
DNSRecords.create_record_sets
def create_record_sets(self, record_set_dicts): """Accept list of record_set dicts. Return list of record_set objects.""" record_set_objects = [] for record_set_dict in record_set_dicts: # pop removes the 'Enabled' key and tests if True. if record_set_dict.pop('Enabled', True): record_set_objects.append( self.create_record_set(record_set_dict) ) return record_set_objects
python
def create_record_sets(self, record_set_dicts): record_set_objects = [] for record_set_dict in record_set_dicts: # pop removes the 'Enabled' key and tests if True. if record_set_dict.pop('Enabled', True): record_set_objects.append( self.create_record_set(record_set_dict) ) return record_set_objects
[ "def", "create_record_sets", "(", "self", ",", "record_set_dicts", ")", ":", "record_set_objects", "=", "[", "]", "for", "record_set_dict", "in", "record_set_dicts", ":", "# pop removes the 'Enabled' key and tests if True.", "if", "record_set_dict", ".", "pop", "(", "'E...
Accept list of record_set dicts. Return list of record_set objects.
[ "Accept", "list", "of", "record_set", "dicts", ".", "Return", "list", "of", "record_set", "objects", "." ]
71624f6e1bd4ea794dc98fb621a04235e1931cae
https://github.com/remind101/stacker_blueprints/blob/71624f6e1bd4ea794dc98fb621a04235e1931cae/stacker_blueprints/route53.py#L156-L166
8,190
remind101/stacker_blueprints
stacker_blueprints/route53.py
DNSRecords.create_record_set_groups
def create_record_set_groups(self, record_set_group_dicts): """Accept list of record_set_group dicts. Return list of record_set_group objects.""" record_set_groups = [] for name, group in record_set_group_dicts.iteritems(): # pop removes the 'Enabled' key and tests if True. if group.pop('Enabled', True): record_set_groups.append( self.create_record_set_group(name, group) ) return record_set_groups
python
def create_record_set_groups(self, record_set_group_dicts): record_set_groups = [] for name, group in record_set_group_dicts.iteritems(): # pop removes the 'Enabled' key and tests if True. if group.pop('Enabled', True): record_set_groups.append( self.create_record_set_group(name, group) ) return record_set_groups
[ "def", "create_record_set_groups", "(", "self", ",", "record_set_group_dicts", ")", ":", "record_set_groups", "=", "[", "]", "for", "name", ",", "group", "in", "record_set_group_dicts", ".", "iteritems", "(", ")", ":", "# pop removes the 'Enabled' key and tests if True....
Accept list of record_set_group dicts. Return list of record_set_group objects.
[ "Accept", "list", "of", "record_set_group", "dicts", ".", "Return", "list", "of", "record_set_group", "objects", "." ]
71624f6e1bd4ea794dc98fb621a04235e1931cae
https://github.com/remind101/stacker_blueprints/blob/71624f6e1bd4ea794dc98fb621a04235e1931cae/stacker_blueprints/route53.py#L168-L178
8,191
remind101/stacker_blueprints
stacker_blueprints/policies.py
read_only_s3_bucket_policy_statements
def read_only_s3_bucket_policy_statements(buckets, folder="*"): """ Read only policy an s3 bucket. """ list_buckets = [s3_arn(b) for b in buckets] object_buckets = [s3_objects_arn(b, folder) for b in buckets] bucket_resources = list_buckets + object_buckets return [ Statement( Effect=Allow, Resource=[s3_arn("*")], Action=[s3.ListAllMyBuckets] ), Statement( Effect=Allow, Resource=bucket_resources, Action=[Action('s3', 'Get*'), Action('s3', 'List*')] ) ]
python
def read_only_s3_bucket_policy_statements(buckets, folder="*"): list_buckets = [s3_arn(b) for b in buckets] object_buckets = [s3_objects_arn(b, folder) for b in buckets] bucket_resources = list_buckets + object_buckets return [ Statement( Effect=Allow, Resource=[s3_arn("*")], Action=[s3.ListAllMyBuckets] ), Statement( Effect=Allow, Resource=bucket_resources, Action=[Action('s3', 'Get*'), Action('s3', 'List*')] ) ]
[ "def", "read_only_s3_bucket_policy_statements", "(", "buckets", ",", "folder", "=", "\"*\"", ")", ":", "list_buckets", "=", "[", "s3_arn", "(", "b", ")", "for", "b", "in", "buckets", "]", "object_buckets", "=", "[", "s3_objects_arn", "(", "b", ",", "folder",...
Read only policy an s3 bucket.
[ "Read", "only", "policy", "an", "s3", "bucket", "." ]
71624f6e1bd4ea794dc98fb621a04235e1931cae
https://github.com/remind101/stacker_blueprints/blob/71624f6e1bd4ea794dc98fb621a04235e1931cae/stacker_blueprints/policies.py#L62-L80
8,192
remind101/stacker_blueprints
stacker_blueprints/policies.py
lambda_vpc_execution_statements
def lambda_vpc_execution_statements(): """Allow Lambda to manipuate EC2 ENIs for VPC support.""" return [ Statement( Effect=Allow, Resource=['*'], Action=[ ec2.CreateNetworkInterface, ec2.DescribeNetworkInterfaces, ec2.DeleteNetworkInterface, ] ) ]
python
def lambda_vpc_execution_statements(): return [ Statement( Effect=Allow, Resource=['*'], Action=[ ec2.CreateNetworkInterface, ec2.DescribeNetworkInterfaces, ec2.DeleteNetworkInterface, ] ) ]
[ "def", "lambda_vpc_execution_statements", "(", ")", ":", "return", "[", "Statement", "(", "Effect", "=", "Allow", ",", "Resource", "=", "[", "'*'", "]", ",", "Action", "=", "[", "ec2", ".", "CreateNetworkInterface", ",", "ec2", ".", "DescribeNetworkInterfaces"...
Allow Lambda to manipuate EC2 ENIs for VPC support.
[ "Allow", "Lambda", "to", "manipuate", "EC2", "ENIs", "for", "VPC", "support", "." ]
71624f6e1bd4ea794dc98fb621a04235e1931cae
https://github.com/remind101/stacker_blueprints/blob/71624f6e1bd4ea794dc98fb621a04235e1931cae/stacker_blueprints/policies.py#L202-L214
8,193
remind101/stacker_blueprints
stacker_blueprints/policies.py
dynamodb_autoscaling_policy
def dynamodb_autoscaling_policy(tables): """Policy to allow AutoScaling a list of DynamoDB tables.""" return Policy( Statement=[ Statement( Effect=Allow, Resource=dynamodb_arns(tables), Action=[ dynamodb.DescribeTable, dynamodb.UpdateTable, ] ), Statement( Effect=Allow, Resource=['*'], Action=[ cloudwatch.PutMetricAlarm, cloudwatch.DescribeAlarms, cloudwatch.GetMetricStatistics, cloudwatch.SetAlarmState, cloudwatch.DeleteAlarms, ] ), ] )
python
def dynamodb_autoscaling_policy(tables): return Policy( Statement=[ Statement( Effect=Allow, Resource=dynamodb_arns(tables), Action=[ dynamodb.DescribeTable, dynamodb.UpdateTable, ] ), Statement( Effect=Allow, Resource=['*'], Action=[ cloudwatch.PutMetricAlarm, cloudwatch.DescribeAlarms, cloudwatch.GetMetricStatistics, cloudwatch.SetAlarmState, cloudwatch.DeleteAlarms, ] ), ] )
[ "def", "dynamodb_autoscaling_policy", "(", "tables", ")", ":", "return", "Policy", "(", "Statement", "=", "[", "Statement", "(", "Effect", "=", "Allow", ",", "Resource", "=", "dynamodb_arns", "(", "tables", ")", ",", "Action", "=", "[", "dynamodb", ".", "D...
Policy to allow AutoScaling a list of DynamoDB tables.
[ "Policy", "to", "allow", "AutoScaling", "a", "list", "of", "DynamoDB", "tables", "." ]
71624f6e1bd4ea794dc98fb621a04235e1931cae
https://github.com/remind101/stacker_blueprints/blob/71624f6e1bd4ea794dc98fb621a04235e1931cae/stacker_blueprints/policies.py#L222-L246
8,194
astropy/astropy-healpix
astropy_healpix/high_level.py
HEALPix.interpolate_bilinear_skycoord
def interpolate_bilinear_skycoord(self, skycoord, values): """ Interpolate values at specific celestial coordinates using bilinear interpolation. If a position does not have four neighbours, this currently returns NaN. Note that this method requires that a celestial frame was specified when initializing HEALPix. If you don't know or need the celestial frame, you can instead use :meth:`~astropy_healpix.HEALPix.interpolate_bilinear_lonlat`. Parameters ---------- skycoord : :class:`~astropy.coordinates.SkyCoord` The celestial coordinates at which to interpolate values : `~numpy.ndarray` 1-D array with the values in each HEALPix pixel. This must have a length of the form 12 * nside ** 2 (and nside is determined automatically from this). Returns ------- result : `~numpy.ndarray` 1-D array of interpolated values """ if self.frame is None: raise NoFrameError("interpolate_bilinear_skycoord") skycoord = skycoord.transform_to(self.frame) representation = skycoord.represent_as(UnitSphericalRepresentation) lon, lat = representation.lon, representation.lat return self.interpolate_bilinear_lonlat(lon, lat, values)
python
def interpolate_bilinear_skycoord(self, skycoord, values): if self.frame is None: raise NoFrameError("interpolate_bilinear_skycoord") skycoord = skycoord.transform_to(self.frame) representation = skycoord.represent_as(UnitSphericalRepresentation) lon, lat = representation.lon, representation.lat return self.interpolate_bilinear_lonlat(lon, lat, values)
[ "def", "interpolate_bilinear_skycoord", "(", "self", ",", "skycoord", ",", "values", ")", ":", "if", "self", ".", "frame", "is", "None", ":", "raise", "NoFrameError", "(", "\"interpolate_bilinear_skycoord\"", ")", "skycoord", "=", "skycoord", ".", "transform_to", ...
Interpolate values at specific celestial coordinates using bilinear interpolation. If a position does not have four neighbours, this currently returns NaN. Note that this method requires that a celestial frame was specified when initializing HEALPix. If you don't know or need the celestial frame, you can instead use :meth:`~astropy_healpix.HEALPix.interpolate_bilinear_lonlat`. Parameters ---------- skycoord : :class:`~astropy.coordinates.SkyCoord` The celestial coordinates at which to interpolate values : `~numpy.ndarray` 1-D array with the values in each HEALPix pixel. This must have a length of the form 12 * nside ** 2 (and nside is determined automatically from this). Returns ------- result : `~numpy.ndarray` 1-D array of interpolated values
[ "Interpolate", "values", "at", "specific", "celestial", "coordinates", "using", "bilinear", "interpolation", "." ]
c7fbe36305aadda9946dd37969d5dcb9ff6b1440
https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/high_level.py#L333-L362
8,195
astropy/astropy-healpix
astropy_healpix/high_level.py
HEALPix.cone_search_skycoord
def cone_search_skycoord(self, skycoord, radius): """ Find all the HEALPix pixels within a given radius of a celestial position. Note that this returns all pixels that overlap, including partially, with the search cone. This function can only be used for a single celestial position at a time, since different calls to the function may result in a different number of matches. This method requires that a celestial frame was specified when initializing HEALPix. If you don't know or need the celestial frame, you can instead use :meth:`~astropy_healpix.HEALPix.cone_search_lonlat`. Parameters ---------- skycoord : :class:`~astropy.coordinates.SkyCoord` The celestial coordinates to use for the cone search radius : :class:`~astropy.units.Quantity` The search radius Returns ------- healpix_index : `~numpy.ndarray` 1-D array with all the matching HEALPix pixel indices. """ if self.frame is None: raise NoFrameError("cone_search_skycoord") skycoord = skycoord.transform_to(self.frame) representation = skycoord.represent_as(UnitSphericalRepresentation) lon, lat = representation.lon, representation.lat return self.cone_search_lonlat(lon, lat, radius)
python
def cone_search_skycoord(self, skycoord, radius): if self.frame is None: raise NoFrameError("cone_search_skycoord") skycoord = skycoord.transform_to(self.frame) representation = skycoord.represent_as(UnitSphericalRepresentation) lon, lat = representation.lon, representation.lat return self.cone_search_lonlat(lon, lat, radius)
[ "def", "cone_search_skycoord", "(", "self", ",", "skycoord", ",", "radius", ")", ":", "if", "self", ".", "frame", "is", "None", ":", "raise", "NoFrameError", "(", "\"cone_search_skycoord\"", ")", "skycoord", "=", "skycoord", ".", "transform_to", "(", "self", ...
Find all the HEALPix pixels within a given radius of a celestial position. Note that this returns all pixels that overlap, including partially, with the search cone. This function can only be used for a single celestial position at a time, since different calls to the function may result in a different number of matches. This method requires that a celestial frame was specified when initializing HEALPix. If you don't know or need the celestial frame, you can instead use :meth:`~astropy_healpix.HEALPix.cone_search_lonlat`. Parameters ---------- skycoord : :class:`~astropy.coordinates.SkyCoord` The celestial coordinates to use for the cone search radius : :class:`~astropy.units.Quantity` The search radius Returns ------- healpix_index : `~numpy.ndarray` 1-D array with all the matching HEALPix pixel indices.
[ "Find", "all", "the", "HEALPix", "pixels", "within", "a", "given", "radius", "of", "a", "celestial", "position", "." ]
c7fbe36305aadda9946dd37969d5dcb9ff6b1440
https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/high_level.py#L364-L394
8,196
astropy/astropy-healpix
astropy_healpix/high_level.py
HEALPix.boundaries_skycoord
def boundaries_skycoord(self, healpix_index, step): """ Return the celestial coordinates of the edges of HEALPix pixels This returns the celestial coordinates of points along the edge of each HEALPIX pixel. The number of points returned for each pixel is ``4 * step``, so setting ``step`` to 1 returns just the corners. This method requires that a celestial frame was specified when initializing HEALPix. If you don't know or need the celestial frame, you can instead use :meth:`~astropy_healpix.HEALPix.boundaries_lonlat`. Parameters ---------- healpix_index : `~numpy.ndarray` 1-D array of HEALPix pixels step : int The number of steps to take along each edge. Returns ------- skycoord : :class:`~astropy.coordinates.SkyCoord` The celestial coordinates of the HEALPix pixel boundaries """ if self.frame is None: raise NoFrameError("boundaries_skycoord") lon, lat = self.boundaries_lonlat(healpix_index, step) representation = UnitSphericalRepresentation(lon, lat, copy=False) return SkyCoord(self.frame.realize_frame(representation))
python
def boundaries_skycoord(self, healpix_index, step): if self.frame is None: raise NoFrameError("boundaries_skycoord") lon, lat = self.boundaries_lonlat(healpix_index, step) representation = UnitSphericalRepresentation(lon, lat, copy=False) return SkyCoord(self.frame.realize_frame(representation))
[ "def", "boundaries_skycoord", "(", "self", ",", "healpix_index", ",", "step", ")", ":", "if", "self", ".", "frame", "is", "None", ":", "raise", "NoFrameError", "(", "\"boundaries_skycoord\"", ")", "lon", ",", "lat", "=", "self", ".", "boundaries_lonlat", "("...
Return the celestial coordinates of the edges of HEALPix pixels This returns the celestial coordinates of points along the edge of each HEALPIX pixel. The number of points returned for each pixel is ``4 * step``, so setting ``step`` to 1 returns just the corners. This method requires that a celestial frame was specified when initializing HEALPix. If you don't know or need the celestial frame, you can instead use :meth:`~astropy_healpix.HEALPix.boundaries_lonlat`. Parameters ---------- healpix_index : `~numpy.ndarray` 1-D array of HEALPix pixels step : int The number of steps to take along each edge. Returns ------- skycoord : :class:`~astropy.coordinates.SkyCoord` The celestial coordinates of the HEALPix pixel boundaries
[ "Return", "the", "celestial", "coordinates", "of", "the", "edges", "of", "HEALPix", "pixels" ]
c7fbe36305aadda9946dd37969d5dcb9ff6b1440
https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/high_level.py#L396-L424
8,197
astropy/astropy-healpix
astropy_healpix/core.py
level_to_nside
def level_to_nside(level): """ Find the pixel dimensions of the top-level HEALPix tiles. This is given by ``nside = 2**level``. Parameters ---------- level : int The resolution level Returns ------- nside : int The number of pixels on the side of one of the 12 'top-level' HEALPix tiles. """ level = np.asarray(level, dtype=np.int64) _validate_level(level) return 2 ** level
python
def level_to_nside(level): level = np.asarray(level, dtype=np.int64) _validate_level(level) return 2 ** level
[ "def", "level_to_nside", "(", "level", ")", ":", "level", "=", "np", ".", "asarray", "(", "level", ",", "dtype", "=", "np", ".", "int64", ")", "_validate_level", "(", "level", ")", "return", "2", "**", "level" ]
Find the pixel dimensions of the top-level HEALPix tiles. This is given by ``nside = 2**level``. Parameters ---------- level : int The resolution level Returns ------- nside : int The number of pixels on the side of one of the 12 'top-level' HEALPix tiles.
[ "Find", "the", "pixel", "dimensions", "of", "the", "top", "-", "level", "HEALPix", "tiles", "." ]
c7fbe36305aadda9946dd37969d5dcb9ff6b1440
https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/core.py#L86-L105
8,198
astropy/astropy-healpix
astropy_healpix/core.py
nside_to_level
def nside_to_level(nside): """ Find the HEALPix level for a given nside. This is given by ``level = log2(nside)``. This function is the inverse of `level_to_nside`. Parameters ---------- nside : int The number of pixels on the side of one of the 12 'top-level' HEALPix tiles. Must be a power of two. Returns ------- level : int The level of the HEALPix cells """ nside = np.asarray(nside, dtype=np.int64) _validate_nside(nside) return np.log2(nside).astype(np.int64)
python
def nside_to_level(nside): nside = np.asarray(nside, dtype=np.int64) _validate_nside(nside) return np.log2(nside).astype(np.int64)
[ "def", "nside_to_level", "(", "nside", ")", ":", "nside", "=", "np", ".", "asarray", "(", "nside", ",", "dtype", "=", "np", ".", "int64", ")", "_validate_nside", "(", "nside", ")", "return", "np", ".", "log2", "(", "nside", ")", ".", "astype", "(", ...
Find the HEALPix level for a given nside. This is given by ``level = log2(nside)``. This function is the inverse of `level_to_nside`. Parameters ---------- nside : int The number of pixels on the side of one of the 12 'top-level' HEALPix tiles. Must be a power of two. Returns ------- level : int The level of the HEALPix cells
[ "Find", "the", "HEALPix", "level", "for", "a", "given", "nside", "." ]
c7fbe36305aadda9946dd37969d5dcb9ff6b1440
https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/core.py#L108-L130
8,199
astropy/astropy-healpix
astropy_healpix/core.py
level_ipix_to_uniq
def level_ipix_to_uniq(level, ipix): """ Convert a level and HEALPix index into a uniq number representing the cell. This function is the inverse of `uniq_to_level_ipix`. Parameters ---------- level : int The level of the HEALPix cell ipix : int The index of the HEALPix cell Returns ------- uniq : int The uniq number representing the HEALPix cell. """ level = np.asarray(level, dtype=np.int64) ipix = np.asarray(ipix, dtype=np.int64) _validate_level(level) _validate_npix(level, ipix) return ipix + (1 << 2*(level + 1))
python
def level_ipix_to_uniq(level, ipix): level = np.asarray(level, dtype=np.int64) ipix = np.asarray(ipix, dtype=np.int64) _validate_level(level) _validate_npix(level, ipix) return ipix + (1 << 2*(level + 1))
[ "def", "level_ipix_to_uniq", "(", "level", ",", "ipix", ")", ":", "level", "=", "np", ".", "asarray", "(", "level", ",", "dtype", "=", "np", ".", "int64", ")", "ipix", "=", "np", ".", "asarray", "(", "ipix", ",", "dtype", "=", "np", ".", "int64", ...
Convert a level and HEALPix index into a uniq number representing the cell. This function is the inverse of `uniq_to_level_ipix`. Parameters ---------- level : int The level of the HEALPix cell ipix : int The index of the HEALPix cell Returns ------- uniq : int The uniq number representing the HEALPix cell.
[ "Convert", "a", "level", "and", "HEALPix", "index", "into", "a", "uniq", "number", "representing", "the", "cell", "." ]
c7fbe36305aadda9946dd37969d5dcb9ff6b1440
https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/core.py#L163-L187