INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Import customer s service module.
def import_modules(self): """Import customer's service module.""" modules = self.get_modules() log.info("import service modules: " + str(modules)) try: for module in modules: __import__(module) except ImportError as error: raise ImportModul...
This function takes a date string in various formats and converts it to a normalized and validated date range. A list with two elements is returned lower and upper date boundary.
def to_dates(param): """ This function takes a date string in various formats and converts it to a normalized and validated date range. A list with two elements is returned, lower and upper date boundary. Valid inputs are, for example: 2012 => Jan 1 20012 - Dec 31 2012 (whole year)...
Expands a ( possibly ) incomplete date string to either the lowest or highest possible contained date and returns datetime. datetime for that string.
def expand_date_param(param, lower_upper): """ Expands a (possibly) incomplete date string to either the lowest or highest possible contained date and returns datetime.datetime for that string. 0753 (lower) => 0753-01-01 2012 (upper) => 2012-12-31 2012 (lower) => 2012-01-01 201208 (uppe...
Take doc and create a new doc using only keys from the fields list. Supports referencing fields using dotted notation a. b. c so we can parse nested fields the way MongoDB does. The nested field class is a hack. It should be a sub - class of dict.
def select_fields(doc, field_list): ''' Take 'doc' and create a new doc using only keys from the 'fields' list. Supports referencing fields using dotted notation "a.b.c" so we can parse nested fields the way MongoDB does. The nested field class is a hack. It should be a sub-class...
For all the datetime fields in datemap find that key in doc and map the datetime object to a strftime string. This pprint and others will print out readable datetimes.
def date_map(doc, datemap_list, time_format=None): ''' For all the datetime fields in "datemap" find that key in doc and map the datetime object to a strftime string. This pprint and others will print out readable datetimes. ''' if datemap_list: for i in datemap_list:...
Output a cursor to a filename or stdout if filename is -. fmt defines whether we output CSV or JSON.
def printCursor(self, fieldnames=None, datemap=None, time_format=None): ''' Output a cursor to a filename or stdout if filename is "-". fmt defines whether we output CSV or JSON. ''' if self._format == 'csv': count = self.printCSVCursor(fieldnames, datemap, time_form...
Output all fields using the fieldNames list. for fields in the list datemap indicates the field must be date
def output(self, fieldNames=None, datemap=None, time_format=None): ''' Output all fields using the fieldNames list. for fields in the list datemap indicates the field must be date ''' count = self.printCursor(self._cursor, fieldNames, datemap, time_format)
Given a list of tasks to perform and a dependency graph return the tasks that must be performed in the correct order
def get_tasks(do_tasks, dep_graph): """Given a list of tasks to perform and a dependency graph, return the tasks that must be performed, in the correct order""" #XXX: Is it important that if a task has "foo" before "bar" as a dep, # that foo executes before bar? Why? ATM this may not happen. #...
Rotates a file. moves original file. ext to targetdir/ file - YYYY - MM - DD - THH: MM: SS. ext
def rotate(filename, targetdir, max_versions=None, archive_dir=None): """ Rotates a file. moves original file.ext to targetdir/file-YYYY-MM-DD-THH:MM:SS.ext deletes all older files matching the same pattern in targetdir that exceed the amount of max_versions. if versions = None, no...
View decorator that handles JSON based API requests and responses consistently.: param methods: A list of allowed methods: param require_token: Whether API token is checked automatically or not
def api_request(methods=None, require_token=True): """ View decorator that handles JSON based API requests and responses consistently. :param methods: A list of allowed methods :param require_token: Whether API token is checked automatically or not """ def decorator(view_func): @wraps(vi...
Add or create the default departments for the given project
def add_default_deps(project): """Add or create the default departments for the given project :param project: the project that needs default departments :type project: :class:`muke.models.Project` :returns: None :rtype: None :raises: None """ # create deps for project for name, shor...
Add or create the default assettypes for the given project
def add_default_atypes(project): """Add or create the default assettypes for the given project :param project: the project that needs default assettypes :type project: :class:`muke.models.Project` :returns: None :rtype: None :raises: None """ # create assettypes for project for name...
Add or create the default sequences for the given project
def add_default_sequences(project): """Add or create the default sequences for the given project :param project: the project that needs default sequences :type project: :class:`muke.models.Project` :returns: None :rtype: None :raises: None """ # create sequences for project seqs = [...
Add a rnd shot for every user in the project
def add_userrnd_shot(project): """Add a rnd shot for every user in the project :param project: the project that needs its rnd shots updated :type project: :class:`muke.models.Project` :returns: None :rtype: None :raises: None """ rndseq = project.sequence_set.get(name=RNDSEQ_NAME) u...
Post save receiver for when a Project is saved.
def prj_post_save_handler(sender, **kwargs): """ Post save receiver for when a Project is saved. Creates a rnd shot for every user. On creations does: 1. create all default departments 2. create all default assettypes 3. create all default sequences :param sender: the project cl...
Post save receiver for when a sequence is saved.
def seq_post_save_handler(sender, **kwargs): """ Post save receiver for when a sequence is saved. creates a global shot. :param sender: the sequence class :type sender: :class:`muke.models.Sequence` :returns: None :raises: None """ if not kwargs['created']: return seq = k...
Create all tasks for the element
def create_all_tasks(element): """Create all tasks for the element :param element: The shot or asset that needs tasks :type element: :class:`muke.models.Shot` | :class:`muke.models.Asset` :returns: None :rtype: None :raises: None """ prj = element.project if isinstance(element, Asse...
Return path
def path(self): """Return path :returns: path :rtype: str :raises: None """ p = os.path.normpath(self._path) if p.endswith(':'): p = p + os.path.sep return p
Set path
def path(self, value): """Set path :param value: The value for path :type value: str :raises: None """ prepval = value.replace('\\', '/') self._path = posixpath.normpath(prepval) if self._path.endswith(':'): self._path = self._path + posixpath...
Reimplemented from: class: models. Model. Check if startframe is before endframe
def clean(self, ): """Reimplemented from :class:`models.Model`. Check if startframe is before endframe :returns: None :rtype: None :raises: ValidationError """ if self.startframe > self.endframe: raise ValidationError("Shot starts before it ends: Framerange(%...
Set path
def path(self, value): """Set path :param value: The value for path :type value: str :raises: None """ prepval = value.replace('\\', '/') self._path = posixpath.normpath(prepval)
Registers a type name so that it may be used to send and receive packages.: param typename: Name of the packet type. A method with the same name and a on_ prefix should be added to handle incomming packets.: raises ValueError: If there is a hash code collision.
def register_type(self, typename): """ Registers a type name so that it may be used to send and receive packages. :param typename: Name of the packet type. A method with the same name and a "on_" prefix should be added to handle incomming packets. :raise...
Opens the port.: param packet_received: Callback which is invoked when we received a packet. Is passed the peer typename and data.
def open(self, packet_received): """ Opens the port. :param packet_received: Callback which is invoked when we received a packet. Is passed the peer, typename, and data. :returns: Deferred that callbacks when we are ready to receive. """ def port_open(...
Ensures that we have an open connection to the given peer. Returns the peer id. This should be equal to the given one but it might not if the given peer was say the IP and the peer actually identifies itself with a host name. The returned peer is the real one that should be used. This can be handy if we aren t 100% sur...
def pre_connect(self, peer): """ Ensures that we have an open connection to the given peer. Returns the peer id. This should be equal to the given one, but it might not if the given peer was, say, the IP and the peer actually identifies itself with a host name. The retur...
Sends a packet to a peer.
def send(self, peer, typename, data): """ Sends a packet to a peer. """ def attempt_to_send(_): if peer not in self._connections: d = self._connect(peer) d.addCallback(attempt_to_send) return d else: ...
Stop listing for new connections and close all open connections.: returns: Deferred that calls back once everything is closed.
def close(self): """ Stop listing for new connections and close all open connections. :returns: Deferred that calls back once everything is closed. """ def cancel_sends(_): logger.debug("Closed port. Cancelling all on-going send operations...") ...
Read customer s config value by section and key.
def get_config_value(self, section, key, return_type: type): """Read customer's config value by section and key. :param section: config file's section. i.e [default] :param key: config file's key under section. i.e packages_scan :param return_type: return value type, str | int | bool. ...
Nova annotation for adding function to process nova notification.
def nova(*arg): """ Nova annotation for adding function to process nova notification. if event_type include wildcard, will put {pattern: function} into process_wildcard dict else will put {event_type: function} into process dict :param arg: event_type of notification """ check_event_type(O...
Cinder annotation for adding function to process cinder notification.
def cinder(*arg): """ Cinder annotation for adding function to process cinder notification. if event_type include wildcard, will put {pattern: function} into process_wildcard dict else will put {event_type: function} into process dict :param arg: event_type of notification """ check_event_...
Neutron annotation for adding function to process neutron notification.
def neutron(*arg): """ Neutron annotation for adding function to process neutron notification. if event_type include wildcard, will put {pattern: function} into process_wildcard dict else will put {event_type: function} into process dict :param arg: event_type of notification """ check_eve...
Glance annotation for adding function to process glance notification.
def glance(*arg): """ Glance annotation for adding function to process glance notification. if event_type include wildcard, will put {pattern: function} into process_wildcard dict else will put {event_type: function} into process dict :param arg: event_type of notification """ check_event_...
Swift annotation for adding function to process swift notification.
def swift(*arg): """ Swift annotation for adding function to process swift notification. if event_type include wildcard, will put {pattern: function} into process_wildcard dict else will put {event_type: function} into process dict :param arg: event_type of notification """ check_event_typ...
Swift annotation for adding function to process keystone notification.
def keystone(*arg): """ Swift annotation for adding function to process keystone notification. if event_type include wildcard, will put {pattern: function} into process_wildcard dict else will put {event_type: function} into process dict :param arg: event_type of notification """ check_eve...
Heat annotation for adding function to process heat notification.
def heat(*arg): """ Heat annotation for adding function to process heat notification. if event_type include wildcard, will put {pattern: function} into process_wildcard dict else will put {event_type: function} into process dict :param arg: event_type of notification """ check_event_type(O...
Adds a factory.
def addFactory(self, identifier, factory): """Adds a factory. After calling this method, remote clients will be able to connect to it. This will call ``factory.doStart``. """ factory.doStart() self._factories[identifier] = factory
Removes a factory.
def removeFactory(self, identifier): """Removes a factory. After calling this method, remote clients will no longer be able to connect to it. This will call the factory's ``doStop`` method. """ factory = self._factories.pop(identifier) factory.doStop() ...
Attempts to connect using a given factory.
def connect(self, factory): """Attempts to connect using a given factory. This will find the requested factory and use it to build a protocol as if the AMP protocol's peer was making the connection. It will create a transport for the protocol and connect it immediately. It will ...
Receives some data for the given protocol.
def receiveData(self, connection, data): """ Receives some data for the given protocol. """ try: protocol = self._protocols[connection] except KeyError: raise NoSuchConnection() protocol.dataReceived(data) return {}
Disconnects the given protocol.
def disconnect(self, connection): """ Disconnects the given protocol. """ proto = self._protocols.pop(connection) proto.transport = None return {}
Shorthand for callRemote.
def _callRemote(self, command, **kwargs): """Shorthand for ``callRemote``. This uses the factory's connection to the AMP peer. """ return self.factory.remote.callRemote(command, **kwargs)
Create a multiplexed stream connection.
def connectionMade(self): """Create a multiplexed stream connection. Connect to the AMP server's multiplexed factory using the identifier (defined by this class' factory). When done, stores the connection reference and causes buffered data to be sent. """ log.msg("Creat...
Stores a reference to the connection registers this protocol on the factory as one related to a multiplexed AMP connection and sends currently buffered data. Gets rid of the buffer afterwards.
def _multiplexedConnectionMade(self, response): """Stores a reference to the connection, registers this protocol on the factory as one related to a multiplexed AMP connection, and sends currently buffered data. Gets rid of the buffer afterwards. """ self.connection = con...
Received some data from the local side.
def dataReceived(self, data): """Received some data from the local side. If we have set up the multiplexed connection, sends the data over the multiplexed connection. Otherwise, buffers. """ log.msg("{} bytes of data received locally".format(len(data))) if self.connecti...
Actually sends data over the wire.
def _sendData(self, data): """Actually sends data over the wire. """ d = self._callRemote(Transmit, connection=self.connection, data=data) d.addErrback(log.err)
If we already have an AMP connection registered on the factory get rid of it.
def connectionLost(self, reason): """If we already have an AMP connection registered on the factory, get rid of it. """ if self.connection is not None: del self.factory.protocols[self.connection]
Attempts to get a local protocol by connection identifier.
def getLocalProtocol(self, connectionIdentifier): """Attempts to get a local protocol by connection identifier. """ for factory in self.localFactories: try: return factory.protocols[connectionIdentifier] except KeyError: continue ...
Some data was received from the remote end. Find the matching protocol and replay it.
def remoteDataReceived(self, connection, data): """Some data was received from the remote end. Find the matching protocol and replay it. """ proto = self.getLocalProtocol(connection) proto.transport.write(data) return {}
The other side has asked us to disconnect.
def disconnect(self, connection): """The other side has asked us to disconnect. """ proto = self.getLocalProtocol(connection) proto.transport.loseConnection() return {}
Append s to the queue. Equivalent to:: queue + = s if queue where a regular string.
def enqueue(self, s): """ Append `s` to the queue. Equivalent to:: queue += s if `queue` where a regular string. """ self._parts.append(s) self._len += len(s)
Remove and return the first n characters from the queue. Throws an error if there are less than n characters in the queue. Equivalent to:: s = queue [: n ] queue = queue [ n: ] if queue where a regular string.
def dequeue(self, n): """ Remove and return the first `n` characters from the queue. Throws an error if there are less than `n` characters in the queue. Equivalent to:: s = queue[:n] queue = queue[n:] if `queue` where a regul...
Removes n bytes from the beginning of the queue. Throws an error if there are less than n characters in the queue. Equivalent to:: queue = queue [ n: ] if queue where a regular string.
def drop(self, n): """ Removes `n` bytes from the beginning of the queue. Throws an error if there are less than `n` characters in the queue. Equivalent to:: queue = queue[n:] if `queue` where a regular string. """ ...
Return the first n characters from the queue without removing them. Throws an error if there are less than n characters in the queue. Equivalent to:: s = queue [: n ] if queue where a regular string.
def peek(self, n): """ Return the first `n` characters from the queue without removing them. Throws an error if there are less than `n` characters in the queue. Equivalent to:: s = queue[:n] if `queue` where a regular string. ...
Takes a string centres it and pads it on both sides
def centered(mystring, linewidth=None, fill=" "): '''Takes a string, centres it, and pads it on both sides''' if linewidth is None: linewidth = get_terminal_size().columns - 1 sides = (linewidth - length_no_ansi(mystring))//2 extra = (linewidth - length_no_ansi(mystring)) % 2 fill = fill[:1]...
Takes a string and prints it with the time right aligned
def clock_on_right(mystring): '''Takes a string, and prints it with the time right aligned''' taken = length_no_ansi(mystring) padding = (get_terminal_size().columns - 1) - taken - 5 clock = time.strftime("%I:%M", time.localtime()) print(mystring + " "*padding + clock)
Ask a yes/ no question via raw_input () and return their answer.
def query_yes_no(question, default="yes"): '''Ask a yes/no question via raw_input() and return their answer. "question" is a string that is presented to the user. "default" is the presumed answer if the user just hits <Enter>. It must be "yes" (the default), "no" or None (meaning an answer ...
Ask a yes/ quit question via raw_input () and return their answer.
def query_yes_quit(question, default="quit"): '''Ask a yes/quit question via raw_input() and return their answer. "question" is a string that is presented to the user. "default" is the presumed answer if the user just hits <Enter>. It must be "yes" (the default), "quit" or None (meaning an ...
Prints a timer with the format 0: 00 to the console and then clears the line when the timer is done
def wait(sec): ''' Prints a timer with the format 0:00 to the console, and then clears the line when the timer is done ''' while sec > 0: sys.stdout.write('\r' + str(sec//60).zfill(1) + ":" + str(sec % 60).zfill(2) + ' ') sec -= 1 time.sleep(1) ...
Takes the parts of a semantic version number and returns a nicely formatted string.
def version_number_str(major, minor=0, patch=0, prerelease=None, build=None): """ Takes the parts of a semantic version number, and returns a nicely formatted string. """ version = str(major) + '.' + str(minor) + '.' + str(patch) if prerelease: if prerelease.startswith('-'): ...
Returns terminal dimensions: return: Returns ( width height ). If there s no terminal to be found we ll just return ( 80 24 ).
def get_terminal_size(): """Returns terminal dimensions :return: Returns ``(width, height)``. If there's no terminal to be found, we'll just return ``(80, 24)``. """ try: # shutil.get_terminal_size was added to the standard # library in Python 3.3 try: f...
Identify whether the user is requesting unit validation against astropy. units pint or quantities.
def identify_unit_framework(target_unit): """ Identify whether the user is requesting unit validation against astropy.units, pint, or quantities. """ if HAS_ASTROPY: from astropy.units import UnitBase if isinstance(target_unit, UnitBase): return ASTROPY if HAS_PI...
Check that a value has physical type consistent with user - specified units
def assert_unit_convertability(name, value, target_unit, unit_framework): """ Check that a value has physical type consistent with user-specified units Note that this does not convert the value, only check that the units have the right physical dimensionality. Parameters ---------- name : ...
Apply standard padding.
def pad(data_to_pad, block_size, style='pkcs7'): """Apply standard padding. :Parameters: data_to_pad : byte string The data that needs to be padded. block_size : integer The block boundary to use for padding. The output length is guaranteed to be a multiple of ``block_size``...
Remove standard padding.
def unpad(padded_data, block_size, style='pkcs7'): """Remove standard padding. :Parameters: padded_data : byte string A piece of data with padding that needs to be stripped. block_size : integer The block boundary to use for padding. The input length must be a multiple of ``...
Construct a: py: class: fedoidcmsg. entity. FederationEntity instance based on given configuration.
def make_federation_entity(config, eid='', httpcli=None, verify_ssl=True): """ Construct a :py:class:`fedoidcmsg.entity.FederationEntity` instance based on given configuration. :param config: Federation entity configuration :param eid: Entity ID :param httpcli: A http client instance to use whe...
Pick signed metadata statements based on ISS pattern matching: param pattern: A regular expression to match the iss against: return: list of tuples ( FO ID signed metadata statement )
def pick_signed_metadata_statements_regex(self, pattern, context): """ Pick signed metadata statements based on ISS pattern matching :param pattern: A regular expression to match the iss against :return: list of tuples (FO ID, signed metadata statement) """ comp_...
Pick signed metadata statements based on ISS pattern matching: param fo: Federation operators ID: param context: In connect with which operation ( one of the values in: py: data: fedoidc. CONTEXTS ).: return: list of tuples ( FO ID signed metadata statement )
def pick_signed_metadata_statements(self, fo, context): """ Pick signed metadata statements based on ISS pattern matching :param fo: Federation operators ID :param context: In connect with which operation (one of the values in :py:data:`fedoidc.CONTEXTS`). ...
Unpack and evaluate a compound metadata statement. Goes through the necessary three steps. * unpack the metadata statement * verify that the given statements are expected to be used in this context * evaluate the metadata statements ( = flatten )
def get_metadata_statement(self, input, cls=MetadataStatement, context=''): """ Unpack and evaluate a compound metadata statement. Goes through the necessary three steps. * unpack the metadata statement * verify that the given statements are expecte...
Sign the extended request.
def self_sign(self, req, receiver='', aud=None): """ Sign the extended request. :param req: Request, a :py:class:`fedoidcmsg.MetadataStatement' instance :param receiver: The intended user of this metadata statement :param aud: The audience, a list of receivers. :return: ...
Update a metadata statement by: * adding signed metadata statements or uris pointing to signed metadata statements. * adding the entities signing keys * create metadata statements one per signed metadata statement or uri sign these and add them to the metadata statement
def update_metadata_statement(self, metadata_statement, receiver='', federation=None, context=''): """ Update a metadata statement by: * adding signed metadata statements or uris pointing to signed metadata statements. * adding the entities ...
Update a request with signed metadata statements.: param req: The request: param federation: Federation Operator ID: param loes: List of: py: class: fedoidc. operator. LessOrEqual instances: param context:: return: The updated request
def add_sms_spec_to_request(self, req, federation='', loes=None, context=''): """ Update a request with signed metadata statements. :param req: The request :param federation: Federation Operator ID :param loes: List of :py:class:`fedoidc....
Only gathers metadata statements and returns them.
def gather_metadata_statements(self, fos=None, context=''): """ Only gathers metadata statements and returns them. :param fos: Signed metadata statements from these Federation Operators should be added. :param context: context of the metadata exchange :return: Dictio...
Add signed metadata statements to the request
def add_sms_spec_to_request(self, req, federation='', loes=None, context='', url=''): """ Add signed metadata statements to the request :param req: The request so far :param federation: If only signed metadata statements from a specific set of...
Add signed metadata statements to the request
def add_sms_spec_to_request(self, req, federation='', loes=None, context='', url=''): """ Add signed metadata statements to the request :param req: The request so far :param federation: If only signed metadata statements from a specific set of...
Prints the anagram results sorted by score to stdout.
def pretty_print(input_word, anagrams, by_length=False): """Prints the anagram results sorted by score to stdout. Args: input_word: the base word we searched on anagrams: generator of (word, score) from anagrams_in_word by_length: a boolean to declare printing by length instead of score...
Argparse logic command line options.
def argument_parser(args): """Argparse logic, command line options. Args: args: sys.argv[1:], everything passed to the program after its name Returns: A tuple of: a list of words/letters to search a boolean to declare if we want to use the sowpods words file ...
Main command line entry point.
def main(arguments=None): """Main command line entry point.""" if not arguments: arguments = sys.argv[1:] wordlist, sowpods, by_length, start, end = argument_parser(arguments) for word in wordlist: pretty_print( word, anagrams_in_word(word, sowpods, start, end),...
Registers a type name so that it may be used to send and receive packages.: param typename: Name of the packet type. A method with the same name and a on_ prefix should be added to handle incomming packets.: raises ValueError: If there is a hash code collision.
def register_type(self, typename): """ Registers a type name so that it may be used to send and receive packages. :param typename: Name of the packet type. A method with the same name and a "on_" prefix should be added to handle incomming packets. :raise...
Do not overwrite this method. Instead implement on_... methods for the registered typenames to handle incomming packets.
def dataReceived(self, data): """ Do not overwrite this method. Instead implement `on_...` methods for the registered typenames to handle incomming packets. """ self._unprocessed_data.enqueue(data) while True: if len(self._unprocesse...
Send a packet.: param typename: A previously registered typename.: param packet: String with the content of the packet.
def send_packet(self, typename, packet): """ Send a packet. :param typename: A previously registered typename. :param packet: String with the content of the packet. """ typekey = typehash(typename) if typename != self._type_register.get(typekey, ...
Invoked if a packet with an unregistered type was received. Default behaviour is to log and close the connection.
def on_unregistered_type(self, typekey, packet): """ Invoked if a packet with an unregistered type was received. Default behaviour is to log and close the connection. """ log.msg("Missing handler for typekey %s in %s. Closing connection." % (typekey, type(self).__name__)...
Creates a TCP based: class: RPCSystem.: param port_range: List of ports to try. If [ 0 ] an arbitrary free port will be used.
def create_tcp_rpc_system(hostname=None, port_range=(0,), ping_interval=1, ping_timeout=0.5): """ Creates a TCP based :class:`RPCSystem`. :param port_range: List of ports to try. If `[0]`, an arbitrary free port will be used. """ def ownid_factory(listeningport): port = lis...
Opens the port.: returns: Deferred that callbacks when we are ready to make and receive calls.
def open(self): """ Opens the port. :returns: Deferred that callbacks when we are ready to make and receive calls. """ logging.debug("Opening rpc system") d = self._connectionpool.open(self._packet_received) def opened(_): logging.deb...
Stop listing for new connections and close all open connections.: returns: Deferred that calls back once everything is closed.
def close(self): """ Stop listing for new connections and close all open connections. :returns: Deferred that calls back once everything is closed. """ assert self._opened, "RPC System is not opened" logger.debug("Closing rpc system. Stopping ping loop") ...
Registers the given callable in the system ( if it isn t already ) and returns the URL that can be used to invoke the given function from remote.
def get_function_url(self, function): """ Registers the given callable in the system (if it isn't already) and returns the URL that can be used to invoke the given function from remote. """ assert self._opened, "RPC System is not opened" logging.debug("get_function_url(%s...
Create a callable that will invoke the given remote function. The stub will return a deferred even if the remote function does not.
def create_function_stub(self, url): """ Create a callable that will invoke the given remote function. The stub will return a deferred even if the remote function does not. """ assert self._opened, "RPC System is not opened" logging.debug("create_function_stub(%s...
Called every ping_interval seconds. Invokes _ping () remotely for every ongoing call.
def _ping_loop_iteration(self): """ Called every `ping_interval` seconds. Invokes `_ping()` remotely for every ongoing call. """ deferredList = [] for peerid, callid in list(self._local_to_remote): if (peerid, callid) not in self...
Called from remote to ask if a call made to here is still in progress.
def _ping(self, peerid, callid): """ Called from remote to ask if a call made to here is still in progress. """ if not (peerid, callid) in self._remote_to_local: logger.warn("No remote call %s from %s. Might just be unfoutunate timing." % (callid, peerid))
Wraps a WSGI app and handles uncaught exceptions and defined exception and outputs a the exception in a structured format. Parameters: - wsgi_app is the app. wsgi_app of flask - app_name should in correct format e. g. APP_NAME_1 - app_logger is the logger object
def register_app_for_error_handling(wsgi_app, app_name, app_logger, custom_logging_service=None): """Wraps a WSGI app and handles uncaught exceptions and defined exception and outputs a the exception in a structured format. Parameters: - wsgi_app is the app.wsgi_app of flask, - app_name should in co...
Get command regex string and completer dict.
def _cmdRegex(self, cmd_grp=None): """Get command regex string and completer dict.""" cmd_grp = cmd_grp or "cmd" help_opts = ("-h", "--help") cmd = self.name() names = "|".join([re.escape(cmd)] + [re.escape(a) for a in self.aliases()]) opts = []...
Defers to amp. AmpList then gets the element from the list.
def fromStringProto(self, inString, proto): """ Defers to `amp.AmpList`, then gets the element from the list. """ value, = amp.AmpList.fromStringProto(self, inString, proto) return value
Wraps the object in a list and then defers to amp. AmpList.
def toStringProto(self, inObject, proto): """ Wraps the object in a list, and then defers to ``amp.AmpList``. """ return amp.AmpList.toStringProto(self, [inObject], proto)
Return the body of a signed JWT without verifying the signature.: param jwt: A signed JWT: return: The body of the JWT as a UTF - 8 string
def unfurl(jwt): """ Return the body of a signed JWT, without verifying the signature. :param jwt: A signed JWT :return: The body of the JWT as a 'UTF-8' string """ _rp_jwt = factory(jwt) return json.loads(_rp_jwt.jwt.part[1].decode('utf8'))
Builds a keyJar instance based on the information in the signing_keys claims in a list of metadata statements.: param iss: Owner of the signing keys: param msl: List of: py: class: MetadataStatement instances.: return: A: py: class: oidcmsg. key_jar. KeyJar instance
def keyjar_from_metadata_statements(iss, msl): """ Builds a keyJar instance based on the information in the 'signing_keys' claims in a list of metadata statements. :param iss: Owner of the signing keys :param msl: List of :py:class:`MetadataStatement` instances. :return: A :py:class:`oidcm...
Reads a file containing a JWKS and populates a: py: class: oidcmsg. key_jar. KeyJar from it.
def read_jwks_file(jwks_file): """ Reads a file containing a JWKS and populates a :py:class:`oidcmsg.key_jar.KeyJar` from it. :param jwks_file: file name of the JWKS file :return: A :py:class:`oidcmsg.key_jar.KeyJar` instance """ _jwks = open(jwks_file, 'r').read() _kj = KeyJar() _...
Verify that an item * a * is < = then an item * b *: param a: An item: param b: Another item: return: True or False
def is_lesser(a, b): """ Verify that an item *a* is <= then an item *b* :param a: An item :param b: Another item :return: True or False """ if type(a) != type(b): return False if isinstance(a, str) and isinstance(b, str): return a == b elif isinstance(a, bool) ...
Verifies that an instance of this class adheres to the given restrictions.
def verify(self, **kwargs): """ Verifies that an instance of this class adheres to the given restrictions. :param kwargs: A set of keyword arguments :return: True if it verifies OK otherwise False. """ super(MetadataStatement, self).verify(**kwargs) if "s...
Parse simple JWKS or signed JWKS from the HTTP response.
def _parse_remote_response(self, response): """ Parse simple JWKS or signed JWKS from the HTTP response. :param response: HTTP response from the 'jwks_uri' or 'signed_jwks_uri' endpoint :return: response parsed as JSON or None """ # Check if the content type ...
Performs a pg_dump backup.
def dump(filename, dbname, username=None, password=None, host=None, port=None, tempdir='/tmp', pg_dump_path='pg_dump', format='p'): """Performs a pg_dump backup. It runs with the current systemuser's privileges, unless you specify username and password. By default pg_dump connects to the value giv...
returns a connected cursor to the database - server.
def _connection(username=None, password=None, host=None, port=None, db=None): "returns a connected cursor to the database-server." c_opts = {} if username: c_opts['user'] = username if password: c_opts['password'] = password if host: c_opts['host'] = host if port: c_opts['port'] = port if ...
returns a list of all databases on this server
def db_list(username=None, password=None, host=None, port=None, maintain_db='postgres'): "returns a list of all databases on this server" conn = _connection(username=username, password=password, host=host, port=port, db=maintain_db) cur = conn.cursor() cur.execute('SELECT DATNAME from...