sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
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...
Remove an API from this handler
entailment
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...
Discover API definitions. Set details=true to show details
entailment
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....
Load a module class
entailment
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...
Unload a module class
entailment
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...
Load a module by full path. If there are dependencies, they are also loaded.
entailment
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...
Unload a module by full path. Dependencies are automatically unloaded if they are marked to be services.
entailment
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 ...
Reload modules with a full path in the pathlist
entailment
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,)) ...
Return the module instance for a target name.
entailment
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() ...
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.
entailment
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: ...
Decorator to map this class directly to a configuration node. It uses `<parentbase>.key` for configuration base and configuration mapping.
entailment
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...
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 `configbase` of its parent and set `configkey...
entailment
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(...
Return all configuration keys in this node, including configurations on children nodes.
entailment
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: ...
Return all `(key, value)` tuples for configurations in this node, including configurations on children nodes.
entailment
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...
Return configuration keys directly stored in this node. Configurations in child nodes are not included.
entailment
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): ...
Copy all configurations from this node into obj
entailment
def withconfig(self, keysuffix): """ Load configurations with this decorator """ def decorator(cls): return self.loadconfig(keysuffix, cls) return decorator
Load configurations with this decorator
entailment
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
Get a subtree node from the key (path relative to this node)
entailment
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)
Support dict-like get (return a default value if not found)
entailment
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)
Support dict-like setdefault (create if not existed)
entailment
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(...
Convert this node to a dictionary tree.
entailment
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...
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.
entailment
def save(self, sortkey = True): """ Save configurations to a list of strings """ return [k + '=' + repr(v) for k,v in self.config_items(sortkey)]
Save configurations to a list of strings
entailment
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))
Save configurations to a single string
entailment
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))
Save configurations to a file-like object which supports `writelines`
entailment
def saveto(self, path, sortkey = True): """ Save configurations to path """ with open(path, 'w') as f: self.savetofile(f, sortkey)
Save configurations to path
entailment
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
Return the parent from which this class inherits configurations
entailment
def getConfigRoot(cls, create = False): """ Return the mapped configuration root node """ try: return manager.gettree(getattr(cls, 'configkey'), create) except AttributeError: return None
Return the mapped configuration root node
entailment
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())) ...
Return all mapped configuration keys for this object
entailment
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))
Return `(key, value)` tuples for all mapped configurations for this object
entailment
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 ...
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 is used; if `server.startup` is not configured, any module defined or imported ...
entailment
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...
Wait for a VXLAN group to be created
entailment
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...
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 size: maximum read size, or unlimited if is None
entailment
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...
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.
entailment
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...
Coroutine method which reads the next line or until EOF or size exceeds
entailment
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) ...
Coroutine method to copy content from this stream to another stream.
entailment
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...
Coroutine method to write data to this stream. :param data: data to write :param container: the routine container :param eof: if True, this is the last chunk of this stream. The other end will receive an EOF after reading this chunk. ...
entailment
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 ...
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
entailment
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...
Insert a new matcher :param matcher: an EventMatcher :param obj: object to return
entailment
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...
Remove the matcher :param matcher: an EventMatcher :param obj: the object to remove
entailment
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)
Return all matches for this event. The first matcher is also returned for each matched object. :param event: an input event
entailment
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)
Return all matches for this event. The first matcher is also returned for each matched object. :param event: an input event
entailment
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...
Return first match for this event :param event: an input event
entailment
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: ...
Find a subtree from an event
entailment
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()) ...
Return a walker function to retrieve necessary information from ObjectDB
entailment
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...
Do an ObjectDB transact to update all VXLAN informations :param container: Routine container :param network_ip_dict: a {logicalnetwork_id: tunnel_ip} dictionary :param created_ports: logical ports to be added, a {logicalport_id: tunnel_ip} dictionary :param removed_ports: logical por...
entailment
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 ...
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 :param system_id: identifier, system-id :param bridge: identifier, bridge name ...
entailment
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...
: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.
entailment
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._...
:param container: DEPRECATED container of current routine :return: The result, or raise the exception from set_exception.
entailment
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...
Set the result to Future object, wake up all the waiters :param result: result to set
entailment
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...
Set an exception to Future object, wake up all the waiters :param exception: exception to set
entailment
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...
Context manager to ensure returning the result
entailment
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...
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 set of records) into individual files. :: result = db['person'].all() dataset.freeze(result, forma...
entailment
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) ...
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.
entailment
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'...
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' is specified, use it in the connection attempt.
entailment
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...
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
entailment
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...
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 success and 0 for failure
entailment
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
u''' Used for server side only! :param flags: :return: 1 for success and 0 for failure
entailment
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...
u''' Enable or disable SSL logging :param True | False enable: Enable or disable SSL logging :param func: Callback function for logging
entailment
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 ...
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 on whether this is a server- or a ...
entailment
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...
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 method. In order to prevent de...
entailment
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 ...
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 value: SSLConnection connecte...
entailment
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...
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 server peer
entailment
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...
Perform a handshake with the peer This method forces an explicit handshake to be performed with either the client or server peer.
entailment
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_...
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
entailment
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( ...
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
entailment
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...
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.
entailment
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...
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, then a certificate dictionary is returned. If the c...
entailment
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: ...
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.
entailment
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...
Support for running straight out of a cloned source directory instead of an installed distribution
entailment
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...
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 socket in case address was None
entailment
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 ...
Set the info callback :param callback: The Python callback to use :return: None
entailment
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)
Raise an SSL error with the given error code
entailment
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 """ ...
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
entailment
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...
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 the root socket times out ...
entailment
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 ...
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 None if get_connection has not...
entailment
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)))
Convert any emoji in a string into accessible content.
entailment
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"]["...
Update the orders
entailment
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...
Here we obtain the price for the quote and make sure it has a feed price
entailment
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
ticks come in on every block
entailment
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]
Return the bot's open accounts in the current market
entailment
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) ...
This method distringuishes notifications caused by Matched orders from those caused by placed orders
entailment
def execute(self): """ Execute a bundle of operations """ self.bitshares.blocking = "head" r = self.bitshares.txbuffer.broadcast() self.bitshares.blocking = False return r
Execute a bundle of operations
entailment
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 )
Cancel all orders of this bot
entailment
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...
Bytes representation of the XML content. (`learn more <http://www.diveintopython3.net/strings.html>`_).
entailment
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')...
Unicode representation of the XML content (`learn more <http://www.diveintopython3.net/strings.html>`_).
entailment
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
`PyQuery <https://pythonhosted.org/pyquery/>`_ representation of the :class:`Element <Element>` or :class:`HTML <HTML>`.
entailment
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
`lxml <http://lxml.de>`_ representation of the :class:`Element <Element>` or :class:`XML <XML>`.
entailment
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')))
All found links on page, in as–is form. Only works for Atom feeds.
entailment
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...
The encoding string to be used, extracted from the XML and :class:`XMLResponse <XMLResponse>` header.
entailment
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 ...
A JSON Representation of the XML. Default is badgerfish. :param conversion: Which conversion method to use. (`learn more <https://github.com/sanand0/xmljson#conventions>`_)
entailment
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...
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. :param _encoding: The encoding format. If a sub-selector is specified (e.g. ``//a...
entailment
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...
Search the :class:`Element <Element>` for the given parse template. :param template: The Parse template to use.
entailment
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...
Given a simple element name, returns a list of :class:`Element <Element>` objects or a single one. :param selector: Element name to find. :param containing: If specified, only return elements that contain the provided text. :param first: Whether or not to return just the...
entailment
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
Requests HTTP Response handler. Attaches .html property to class:`requests.Response <requests.Response>` objects.
entailment
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...
Makes an HTTP Request, with mocked User–Agent headers. Returns a class:`HTTPResponse <HTTPResponse>`.
entailment
def response_hook(response, **kwargs) -> XMLResponse: """ Change response enconding and replace it by a HTMLResponse. """ response.encoding = DEFAULT_ENCODING return XMLResponse._from_response(response)
Change response enconding and replace it by a HTMLResponse.
entailment
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)
Start the background process.
entailment
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...
Download the page.
entailment
def register(self, result): """ Register an EventualResult. May be called in any thread. """ if self._stopped: raise ReactorStopped() self._results.add(result)
Register an EventualResult. May be called in any thread.
entailment
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...
Indicate no more results will get pushed into EventualResults, since the reactor has stopped. This should be called in the reactor thread.
entailment