Search is not available for this dataset
text
stringlengths
75
104k
def unregisterAPI(self, name): """ Remove an API from this handler """ if name.startswith('public/'): target = 'public' name = name[len('public/'):] else: target = self.servicename name = name removes = [m for m in self.hand...
def discover(self, details = False): 'Discover API definitions. Set details=true to show details' if details and not (isinstance(details, str) and details.lower() == 'false'): return copy.deepcopy(self.discoverinfo) else: return dict((k,v.get('description', '')) for k,v i...
async def loadmodule(self, module): ''' Load a module class ''' self._logger.debug('Try to load module %r', module) if hasattr(module, '_instance'): self._logger.debug('Module is already initialized, module state is: %r', module._instance.state) if module....
async def unloadmodule(self, module, ignoreDependencies = False): ''' Unload a module class ''' self._logger.debug('Try to unload module %r', module) if hasattr(module, '_instance'): self._logger.debug('Module %r is loaded, module state is %r', module, module._instanc...
async def load_by_path(self, path): """ Load a module by full path. If there are dependencies, they are also loaded. """ try: p, module = findModule(path, True) except KeyError as exc: raise ModuleLoadException('Cannot load module ' + repr(path) + ': ' + s...
async def unload_by_path(self, path): """ Unload a module by full path. Dependencies are automatically unloaded if they are marked to be services. """ p, module = findModule(path, False) if module is None: raise ModuleLoadException('Cannot find module: ' + rep...
async def reload_modules(self, pathlist): """ Reload modules with a full path in the pathlist """ loadedModules = [] failures = [] for path in pathlist: p, module = findModule(path, False) if module is not None and hasattr(module, '_instance') and ...
def get_module_by_name(self, targetname): """ Return the module instance for a target name. """ if targetname == 'public': target = None elif not targetname not in self.activeModules: raise KeyError('Module %r not exists or is not loaded' % (targetname,)) ...
def configbase(key): """ Decorator to set this class to configuration base class. A configuration base class uses `<parentbase>.key.` for its configuration base, and uses `<parentbase>.key.default` for configuration mapping. """ def decorator(cls): parent = cls.getConfigurableParent() ...
def config(key): """ Decorator to map this class directly to a configuration node. It uses `<parentbase>.key` for configuration base and configuration mapping. """ def decorator(cls): parent = cls.getConfigurableParent() if parent is None: parentbase = None else: ...
def defaultconfig(cls): """ Generate a default configuration mapping bases on the class name. If this class does not have a parent with `configbase` defined, it is set to a configuration base with `configbase=<lowercase-name>` and `configkey=<lowercase-name>.default`; otherwise it inherits `configba...
def config_keys(self, sortkey = False): """ Return all configuration keys in this node, including configurations on children nodes. """ if sortkey: items = sorted(self.items()) else: items = self.items() for k,v in items: if isinstance(...
def config_items(self, sortkey = False): """ Return all `(key, value)` tuples for configurations in this node, including configurations on children nodes. """ if sortkey: items = sorted(self.items()) else: items = self.items() for k,v in items: ...
def config_value_keys(self, sortkey = False): """ Return configuration keys directly stored in this node. Configurations in child nodes are not included. """ if sortkey: items = sorted(self.items()) else: items = self.items() return (k for k,v in i...
def loadconfig(self, keysuffix, obj): """ Copy all configurations from this node into obj """ subtree = self.get(keysuffix) if subtree is not None and isinstance(subtree, ConfigTree): for k,v in subtree.items(): if isinstance(v, ConfigTree): ...
def withconfig(self, keysuffix): """ Load configurations with this decorator """ def decorator(cls): return self.loadconfig(keysuffix, cls) return decorator
def gettree(self, key, create = False): """ Get a subtree node from the key (path relative to this node) """ tree, _ = self._getsubitem(key + '.tmp', create) return tree
def get(self, key, defaultvalue = None): """ Support dict-like get (return a default value if not found) """ (t, k) = self._getsubitem(key, False) if t is None: return defaultvalue else: return t.__dict__.get(k, defaultvalue)
def setdefault(self, key, defaultvalue = None): """ Support dict-like setdefault (create if not existed) """ (t, k) = self._getsubitem(key, True) return t.__dict__.setdefault(k, defaultvalue)
def todict(self): """ Convert this node to a dictionary tree. """ dict_entry = [] for k,v in self.items(): if isinstance(v, ConfigTree): dict_entry.append((k, v.todict())) else: dict_entry.append((k, v)) return dict(...
def loadfromfile(self, filelike): """ Read configurations from a file-like object, or a sequence of strings. Old values are not cleared, if you want to reload the configurations completely, you should call `clear()` before using `load*` methods. """ line_format = re.compi...
def save(self, sortkey = True): """ Save configurations to a list of strings """ return [k + '=' + repr(v) for k,v in self.config_items(sortkey)]
def savetostr(self, sortkey = True): """ Save configurations to a single string """ return ''.join(k + '=' + repr(v) + '\n' for k,v in self.config_items(sortkey))
def savetofile(self, filelike, sortkey = True): """ Save configurations to a file-like object which supports `writelines` """ filelike.writelines(k + '=' + repr(v) + '\n' for k,v in self.config_items(sortkey))
def saveto(self, path, sortkey = True): """ Save configurations to path """ with open(path, 'w') as f: self.savetofile(f, sortkey)
def getConfigurableParent(cls): """ Return the parent from which this class inherits configurations """ for p in cls.__bases__: if isinstance(p, Configurable) and p is not Configurable: return p return None
def getConfigRoot(cls, create = False): """ Return the mapped configuration root node """ try: return manager.gettree(getattr(cls, 'configkey'), create) except AttributeError: return None
def config_value_keys(self, sortkey = False): """ Return all mapped configuration keys for this object """ ret = set() cls = type(self) while True: root = cls.getConfigRoot() if root: ret = ret.union(set(root.config_value_keys())) ...
def config_value_items(self, sortkey = False): """ Return `(key, value)` tuples for all mapped configurations for this object """ return ((k, getattr(self, k)) for k in self.config_value_keys(sortkey))
def main(configpath = None, startup = None, daemon = False, pidfile = None, fork = None): """ The most simple way to start the VLCP framework :param configpath: path of a configuration file to be loaded :param startup: startup modules list. If None, `server.startup` in the configuration files ...
async def wait_for_group(self, container, networkid, timeout = 120): """ Wait for a VXLAN group to be created """ if networkid in self._current_groups: return self._current_groups[networkid] else: if not self._connection.connected: raise Co...
async def read(self, container = None, size = None): """ Coroutine method to read from the stream and return the data. Raises EOFError when the stream end has been reached; raises IOError if there are other errors. :param container: A routine container :param si...
def readonce(self, size = None): """ Read from current buffer. If current buffer is empty, returns an empty string. You can use `prepareRead` to read the next chunk of data. This is not a coroutine method. """ if self.eof: raise EOFError if se...
async def readline(self, container = None, size = None): """ Coroutine method which reads the next line or until EOF or size exceeds """ ret = [] retsize = 0 if self.eof: raise EOFError if self.errored: raise IOError('Stream is broken befor...
async def copy_to(self, dest, container, buffering = True): """ Coroutine method to copy content from this stream to another stream. """ if self.eof: await dest.write(u'' if self.isunicode else b'', True) elif self.errored: await dest.error(container) ...
async def write(self, data, container, eof = False, ignoreexception = False, buffering = True, split = True): """ Coroutine method to write data to this stream. :param data: data to write :param container: the routine container :param eof: if True, this...
def subtree(self, matcher, create = False): ''' Find a subtree from a matcher :param matcher: the matcher to locate the subtree. If None, return the root of the tree. :param create: if True, the subtree is created if not exists; otherwise return None if not exists ...
def insert(self, matcher, obj): ''' Insert a new matcher :param matcher: an EventMatcher :param obj: object to return ''' current = self.subtree(matcher, True) #current.matchers[(obj, matcher)] = None if current._use_dict: cur...
def remove(self, matcher, obj): ''' Remove the matcher :param matcher: an EventMatcher :param obj: the object to remove ''' current = self.subtree(matcher, False) if current is None: return # Assume that this pair only appears...
def matchesWithMatchers(self, event): ''' Return all matches for this event. The first matcher is also returned for each matched object. :param event: an input event ''' ret = [] self._matches(event, set(), ret) return tuple(ret)
def matches(self, event): ''' Return all matches for this event. The first matcher is also returned for each matched object. :param event: an input event ''' ret = [] self._matches(event, set(), ret) return tuple(r[0] for r in ret)
def matchfirst(self, event): ''' Return first match for this event :param event: an input event ''' # 1. matches(self.index[ind], event) # 2. matches(self.any, event) # 3. self.matches if self.depth < len(event.indices): ind = event.in...
def subtree(self, event, create = False): ''' Find a subtree from an event ''' current = self for i in range(self.depth, len(event.indices)): if not hasattr(current, 'index'): return current ind = event.indices[i] if create: ...
def lognet_vxlan_walker(prepush = True): """ Return a walker function to retrieve necessary information from ObjectDB """ def _walk_lognet(key, value, walk, save): save(key) if value is None: return try: phynet = walk(value.physicalnetwork.getkey()) ...
async def update_vxlaninfo(container, network_ip_dict, created_ports, removed_ports, ovsdb_vhost, system_id, bridge, allowedmigrationtime, refreshinterval): ''' Do an ObjectDB transact to update all VXLAN informations :param container: Routine container :param n...
def get_broadcast_ips(vxlan_endpointset, local_ip, ovsdb_vhost, system_id, bridge): ''' Get all IP addresses that are not local :param vxlan_endpointset: a VXLANEndpointSet object :param local_ips: list of local IP address to exclude with :param ovsdb_vhost: identifier, vhost ...
def result(self): ''' :return: None if the result is not ready, the result from set_result, or raise the exception from set_exception. If the result can be None, it is not possible to tell if the result is available; use done() to determine that. ''' try...
async def wait(self, container = None): ''' :param container: DEPRECATED container of current routine :return: The result, or raise the exception from set_exception. ''' if hasattr(self, '_result'): if hasattr(self, '_exception'): raise self._...
def set_result(self, result): ''' Set the result to Future object, wake up all the waiters :param result: result to set ''' if hasattr(self, '_result'): raise ValueError('Cannot set the result twice') self._result = result self._scheduler.emer...
def set_exception(self, exception): ''' Set an exception to Future object, wake up all the waiters :param exception: exception to set ''' if hasattr(self, '_result'): raise ValueError('Cannot set the result twice') self._result = None self._ex...
def ensure_result(self, supress_exception = False, defaultresult = None): ''' Context manager to ensure returning the result ''' try: yield self except Exception as exc: if not self.done(): self.set_exception(exc) if not supress...
def freeze(result, format='csv', filename='freeze.csv', fileobj=None, prefix='.', mode='list', **kw): """ Perform a data export of a given result set. This is a very flexible exporter, allowing for various output formats, metadata assignment, and file name templating to dump each record (or a...
def decode_cert(cert): """Convert an X509 certificate into a Python dictionary This function converts the given X509 certificate into a Python dictionary in the manner established by the Python standard library's ssl module. """ ret_dict = {} subject_xname = X509_get_subject_name(cert.value) ...
def _get_server_certificate(addr, ssl_version=PROTOCOL_SSLv23, ca_certs=None): """Retrieve a server certificate Retrieve the certificate from the server at the specified address, and return it as a PEM-encoded string. If 'ca_certs' is specified, validate the server cert against it. If 'ssl_version'...
def set_curves(self, curves): u''' Set supported curves by name, nid or nist. :param str | tuple(int) curves: Example "secp384r1:secp256k1", (715, 714), "P-384", "K-409:B-409:K-571", ... :return: 1 for success and 0 for failure ''' retVal = None if isinstance(curves, str...
def set_ecdh_curve(self, curve_name=None): u''' Select a curve to use for ECDH(E) key exchange or set it to auto mode Used for server only! s.a. openssl.exe ecparam -list_curves :param None | str curve_name: None = Auto-mode, "secp256k1", "secp384r1", ... :return: 1 for succes...
def build_cert_chain(self, flags=SSL_BUILD_CHAIN_FLAG_NONE): u''' Used for server side only! :param flags: :return: 1 for success and 0 for failure ''' retVal = SSL_CTX_build_cert_chain(self._ctx, flags) return retVal
def set_ssl_logging(self, enable=False, func=_ssl_logging_cb): u''' Enable or disable SSL logging :param True | False enable: Enable or disable SSL logging :param func: Callback function for logging ''' if enable: SSL_CTX_set_info_callback(self._ctx, func) el...
def get_socket(self, inbound): """Retrieve a socket used by this connection When inbound is True, then the socket from which this connection reads data is retrieved. Otherwise the socket to which this connection writes data is retrieved. Read and write sockets differ depending ...
def listen(self): """Server-side cookie exchange This method reads datagrams from the socket and initiates cookie exchange, upon whose successful conclusion one can then proceed to the accept method. Alternatively, accept can be called directly, in which case it will call this m...
def accept(self): """Server-side UDP connection establishment This method returns a server-side SSLConnection object, connected to that peer most recently returned from the listen method and not yet connected. If there is no such peer, then the listen method is invoked. Return ...
def connect(self, peer_address): """Client-side UDP connection establishment This method connects this object's underlying socket. It subsequently performs a handshake if do_handshake_on_connect was set during initialization. Arguments: peer_address - address tuple of s...
def do_handshake(self): """Perform a handshake with the peer This method forces an explicit handshake to be performed with either the client or server peer. """ _logger.debug("Initiating handshake...") try: self._wrap_socket_library_call( lam...
def read(self, len=1024, buffer=None): """Read data from connection Read up to len bytes and return them. Arguments: len -- maximum number of bytes to read Return value: string containing read bytes """ try: return self._wrap_socket_library_...
def write(self, data): """Write data to connection Write data as string of bytes. Arguments: data -- buffer containing data to be written Return value: number of bytes actually transmitted """ try: ret = self._wrap_socket_library_call( ...
def shutdown(self): """Shut down the DTLS connection This method attemps to complete a bidirectional shutdown between peers. For non-blocking sockets, it should be called repeatedly until it no longer raises continuation request exceptions. """ if hasattr(self, "_listen...
def getpeercert(self, binary_form=False): """Retrieve the peer's certificate When binary form is requested, the peer's DER-encoded certficate is returned if it was transmitted during the handshake. When binary form is not requested, and the peer's certificate has been validated...
def cipher(self): """Retrieve information about the current cipher Return a triple consisting of cipher name, SSL protocol version defining its use, and the number of secret bits. Return None if handshaking has not been completed. """ if not self._handshake_done: ...
def _prep_bins(): """ Support for running straight out of a cloned source directory instead of an installed distribution """ from os import path from sys import platform, maxsize from shutil import copy bit_suffix = "-x86_64" if maxsize > 2**32 else "-x86" package_root = path.abspat...
def get_connection(self, address): """Create or retrieve a muxed connection Arguments: address -- a peer endpoint in IPv4/v6 address format; None refers to the connection for unknown peers Return: a bound, connected datagram socket instance, or the root socke...
def SSL_CTX_set_info_callback(ctx, app_info_cb): """ Set the info callback :param callback: The Python callback to use :return: None """ def py_info_callback(ssl, where, ret): try: app_info_cb(SSL(ssl), where, ret) except: pass return global ...
def raise_ssl_error(code, nested=None): """Raise an SSL error with the given error code""" err_string = str(code) + ": " + _ssl_errors[code] if nested: raise SSLError(code, err_string + str(nested)) raise SSLError(code, err_string)
def get_connection(self, address): """Create or retrieve a muxed connection Arguments: address -- a peer endpoint in IPv4/v6 address format; None refers to the connection for unknown peers Return: a bound, connected datagram socket instance """ ...
def service(self): """Service the root socket Read from the root socket and forward one datagram to a connection. The call will return without forwarding data if any of the following occurs: * An error is encountered while reading from the root socket * Reading from...
def forward(self): """Forward a stored datagram When the service method returns the address of a new peer, it holds the datagram from that peer in this instance. In this case, this method will perform the forwarding step. The target connection is the one associated with address ...
def emojificate_filter(content, autoescape=True): "Convert any emoji in a string into accessible content." # return mark_safe(emojificate(content)) if autoescape: esc = conditional_escape else: esc = lambda x: x return mark_safe(emojificate(esc(content)))
def updateorders(self): """ Update the orders """ log.info("Replacing orders") # Canceling orders self.cancelall() # Target target = self.bot.get("target", {}) price = self.getprice() # prices buy_price = price * (1 - target["offsets"]["...
def getprice(self): """ Here we obtain the price for the quote and make sure it has a feed price """ target = self.bot.get("target", {}) if target.get("reference") == "feed": assert self.market == self.market.core_quote_market(), "Wrong market for 'feed' reference...
def tick(self, d): """ ticks come in on every block """ if self.test_blocks: if not (self.counter["blocks"] or 0) % self.test_blocks: self.test() self.counter["blocks"] += 1
def orders(self): """ Return the bot's open accounts in the current market """ self.account.refresh() return [o for o in self.account.openorders if self.bot["market"] == o.market and self.account.openorders]
def _callbackPlaceFillOrders(self, d): """ This method distringuishes notifications caused by Matched orders from those caused by placed orders """ if isinstance(d, FilledOrder): self.onOrderMatched(d) elif isinstance(d, Order): self.onOrderPlaced(d) ...
def execute(self): """ Execute a bundle of operations """ self.bitshares.blocking = "head" r = self.bitshares.txbuffer.broadcast() self.bitshares.blocking = False return r
def cancelall(self): """ Cancel all orders of this bot """ if self.orders: return self.bitshares.cancel( [o["id"] for o in self.orders], account=self.account )
def raw_xml(self) -> _RawXML: """Bytes representation of the XML content. (`learn more <http://www.diveintopython3.net/strings.html>`_). """ if self._xml: return self._xml else: return etree.tostring(self.element, encoding='unicode').strip().encode(self.en...
def xml(self) -> _BaseXML: """Unicode representation of the XML content (`learn more <http://www.diveintopython3.net/strings.html>`_). """ if self._xml: return self.raw_xml.decode(self.encoding) else: return etree.tostring(self.element, encoding='unicode')...
def pq(self) -> PyQuery: """`PyQuery <https://pythonhosted.org/pyquery/>`_ representation of the :class:`Element <Element>` or :class:`HTML <HTML>`. """ if self._pq is None: self._pq = PyQuery(self.raw_xml) return self._pq
def lxml(self) -> _LXML: """`lxml <http://lxml.de>`_ representation of the :class:`Element <Element>` or :class:`XML <XML>`. """ if self._lxml is None: self._lxml = etree.fromstring(self.raw_xml) return self._lxml
def links(self) -> _Links: """All found links on page, in as–is form. Only works for Atom feeds.""" return list(set(x.text for x in self.xpath('//link')))
def encoding(self) -> _Encoding: """The encoding string to be used, extracted from the XML and :class:`XMLResponse <XMLResponse>` header. """ if self._encoding: return self._encoding # Scan meta tags for charset. if self._xml: self._encoding = htm...
def json(self, conversion: _Text = 'badgerfish') -> Mapping: """A JSON Representation of the XML. Default is badgerfish. :param conversion: Which conversion method to use. (`learn more <https://github.com/sanand0/xmljson#conventions>`_) """ if not self._json: if conversion ...
def xpath(self, selector: str, *, first: bool = False, _encoding: str = None) -> _XPath: """Given an XPath selector, returns a list of :class:`Element <Element>` objects or a single one. :param selector: XPath Selector to use. :param first: Whether or not to return just the first result...
def search(self, template: str, first: bool = False) -> _Result: """Search the :class:`Element <Element>` for the given parse template. :param template: The Parse template to use. """ elements = [r for r in findall(template, self.xml)] return _get_first_or_list(elements...
def find(self, selector: str = '*', containing: _Containing = None, first: bool = False, _encoding: str = None) -> _Find: """Given a simple element name, returns a list of :class:`Element <Element>` objects or a single one. :param selector: Element name to find. :param c...
def _handle_response(response, **kwargs) -> XMLResponse: """Requests HTTP Response handler. Attaches .html property to class:`requests.Response <requests.Response>` objects. """ if not response.encoding: response.encoding = DEFAULT_ENCODING return response
def request(self, *args, **kwargs) -> XMLResponse: """Makes an HTTP Request, with mocked User–Agent headers. Returns a class:`HTTPResponse <HTTPResponse>`. """ # Convert Request object into HTTPRequest object. r = super(XMLSession, self).request(*args, **kwargs) return X...
def response_hook(response, **kwargs) -> XMLResponse: """ Change response enconding and replace it by a HTMLResponse. """ response.encoding = DEFAULT_ENCODING return XMLResponse._from_response(response)
def start(self): """Start the background process.""" self._lc = LoopingCall(self._download) # Run immediately, and then every 30 seconds: self._lc.start(30, now=True)
def _download(self): """Download the page.""" print("Downloading!") def parse(result): print("Got %r back from Yahoo." % (result,)) values = result.strip().split(",") self._value = float(values[1]) d = getPage( "http://download.finance.yaho...
def register(self, result): """ Register an EventualResult. May be called in any thread. """ if self._stopped: raise ReactorStopped() self._results.add(result)
def stop(self): """ Indicate no more results will get pushed into EventualResults, since the reactor has stopped. This should be called in the reactor thread. """ self._stopped = True for result in self._results: result._set_result(Failure(ReactorStop...