Search is not available for this dataset
text
stringlengths
75
104k
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(...
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...
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: ...
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...") ...
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. ...
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...
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_...
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...
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_...
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...
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...
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...
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
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() ...
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 ...
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 {}
def disconnect(self, connection): """ Disconnects the given protocol. """ proto = self._protocols.pop(connection) proto.transport = None return {}
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)
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...
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...
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...
def _sendData(self, data): """Actually sends data over the wire. """ d = self._callRemote(Transmit, connection=self.connection, data=data) d.addErrback(log.err)
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]
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 ...
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 {}
def disconnect(self, connection): """The other side has asked us to disconnect. """ proto = self.getLocalProtocol(connection) proto.transport.loseConnection() return {}
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)
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...
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. """ ...
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. ...
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]...
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)
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 ...
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 ...
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) ...
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('-'): ...
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...
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...
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 : ...
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``...
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 ``...
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...
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_...
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`). ...
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...
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: ...
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 ...
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....
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...
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...
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...
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...
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 ...
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),...
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...
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...
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, ...
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__)...
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...
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...
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") ...
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...
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...
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...
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))
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...
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 = []...
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
def toStringProto(self, inObject, proto): """ Wraps the object in a list, and then defers to ``amp.AmpList``. """ return amp.AmpList.toStringProto(self, [inObject], proto)
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'))
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...
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() _...
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) ...
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...
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 ...
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...
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 ...
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...
def _get_local_files(self, path): """Returns a dictionary of all the files under a path.""" if not path: raise ValueError("No path specified") files = defaultdict(lambda: None) path_len = len(path) + 1 for root, dirs, filenames in os.walk(path): for name i...
def sync_folder(self, path, bucket): """Syncs a local directory with an S3 bucket. Currently does not delete files from S3 that are not in the local directory. path: The path to the directory to sync to S3 bucket: The name of the bucket on S3 """ bucket = self.conn...
def sync(self, folders): """Syncs a list of folders to their assicated buckets. folders: A list of 2-tuples in the form (folder, bucket) """ if not folders: raise ValueError("No folders to sync given") for folder in folders: self.sync_folder(*fold...
def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None): """ Decorator for views that checks that the user is logged in, redirecting to the log-in page if necessary. """ actual_decorator = request_passes_test( lambda r: r.session.get('use...
def permission_required(function=None, permission=None, object_id=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None): """ Decorator for views that checks that the user is logged in, redirecting to the log-in page if necessary. """ actual_de...
def tokens_required(service_list): """ Ensure the user has the necessary tokens for the specified services """ def decorator(func): @wraps(func) def inner(request, *args, **kwargs): for service in service_list: if service not in request.session["user_tokens"]:...
def login(request, template_name='ci/login.html', redirect_field_name=REDIRECT_FIELD_NAME, authentication_form=AuthenticationForm): """ Displays the login form and handles the login action. """ redirect_to = request.POST.get(redirect_field_name, req...
def build(cli, path, package): """Build CLI dynamically based on the package structure. """ for _, name, ispkg in iter_modules(path): module = import_module(f'.{name}', package) if ispkg: build(cli.group(name)(module.group), module.__path__, mo...
def readonly(cls, *args, **kwargs): """ Return an already closed read-only instance of Fridge. Arguments are the same as for the constructor. """ fridge = cls(*args, **kwargs) fridge.close() return fridge
def load(self): """ Force reloading the data from the file. All data in the in-memory dictionary is discarded. This method is called automatically by the constructor, normally you don't need to call it. """ self._check_open() try: data = json.l...
def save(self): """ Force saving the dictionary to the file. All data in the file is discarded. This method is called automatically by :meth:`close`. """ self._check_open() self.file.truncate(0) self.file.seek(0) json.dump(self, self.file, **self.d...
def close(self): """ Close the fridge. Calls :meth:`save` and closes the underlying file object unless an already open file was passed to the constructor. This method has no effect if the object is already closed. After the fridge is closed :meth:`save` and :meth:`load` ...
def self_sign_jwks(keyjar, iss, kid='', lifetime=3600): """ Create a signed JWT containing a JWKS. The JWT is signed by one of the keys in the JWKS. :param keyjar: A KeyJar instance with at least one private signing key :param iss: issuer of the JWT, should be the owner of the keys :param kid: ...
def verify_self_signed_jwks(sjwt): """ Verify the signature of a signed JWT containing a JWKS. The JWT is signed by one of the keys in the JWKS. In the JWT the JWKS is stored using this format :: 'jwks': { 'keys': [ ] } :param sjwt: Signed Jason Web Token :retu...
def request_signed_by_signing_keys(keyjar, msreq, iss, lifetime, kid=''): """ A metadata statement signing request with 'signing_keys' signed by one of the keys in 'signing_keys'. :param keyjar: A KeyJar instance with the private signing key :param msreq: Metadata statement signing request. A Metad...
def verify_request_signed_by_signing_keys(smsreq): """ Verify that a JWT is signed with a key that is inside the JWT. :param smsreq: Signed Metadata Statement signing request :return: Dictionary containing 'ms' (the signed request) and 'iss' (the issuer of the JWT). """ _jws = fact...
def card(func): """ A decorator for providing a unittesting function/method with every card in a librarian card library database when it is called. """ @wraps(func) def wrapped(*args, **kwargs): """Transparent wrapper.""" return func(*args, **kwargs) TESTS.append(wrapped) ...
def library(func): """ A decorator for providing a unittest with a library and have it called only once. """ @wraps(func) def wrapped(*args, **kwargs): """Transparent wrapper.""" return func(*args, **kwargs) SINGLES.append(wrapped) return wrapped
def descovery(testdir): """Descover and load greencard tests.""" from os.path import join, exists, isdir, splitext, basename, sep if not testdir or not exists(testdir) or not isdir(testdir): return None from os import walk import fnmatch import imp for root, _, filenames in walk(te...
def main(clargs=None): """Command line entry point.""" from argparse import ArgumentParser from librarian.library import Library import sys parser = ArgumentParser( description="A test runner for each card in a librarian library.") parser.add_argument("library", help="Library database")...
def letter_score(letter): """Returns the Scrabble score of a letter. Args: letter: a single character string Raises: TypeError if a non-Scrabble character is supplied """ score_map = { 1: ["a", "e", "i", "o", "u", "l", "n", "r", "s", "t"], 2: ["d", "g"], 3:...
def word_score(word, input_letters, questions=0): """Checks the Scrabble score of a single word. Args: word: a string to check the Scrabble score of input_letters: the letters in our rack questions: integer of the tiles already on the board to build on Returns: an integer S...