text
stringlengths
81
112k
Compute the MAP estimate of a network choice model's parameters. This function computes the maximum-a-posteriori (MAP) estimate of model parameters given a network structure and node-level traffic data (see :ref:`data-network`), using the ChoiceRank algorithm [MG17]_, [KTVV15]_. The nodes are assumed ...
Decorate a function so the function call is checked whenever a call is made. The calls that do not need any checks are skipped. The `function` argument is the function to be decorated. The return value will be either * the function itself, if there is nothing to validate, or *...
Remove validator decoration from a function. The `function` argument is the function to be cleaned from the validator decorator. def undecorate(cls, function): ''' Remove validator decoration from a function. The `function` argument is the function to be cleaned from t...
Validate the arguments passed to a function. If an error occurred, the function will throw a TypesafetyError. The `locals_dict` argument should be the local value dictionary of the function. An example call would be like: def validate_arguments(self, locals_dict): ''' Validate ...
Validate the return value of a function call. If an error occurred, the function will throw a TypesafetyError. The `retval` should contain the return value of the function call. def validate_return_value(self, retval): ''' Validate the return value of a function call. If an error occur...
Uninstall the module finder. If not installed, this will do nothing. After uninstallation, none of the newly loaded modules will be decorated (that is, everything will be back to normal). def uninstall(self): ''' Uninstall the module finder. If not installed, this will do nothing. ...
Find the module. Required for the Python meta-loading mechanism. This will do nothing, since we use the system to locate a module. def find_module(self, fullname, path=None): ''' Find the module. Required for the Python meta-loading mechanism. This will do nothing, since we use the sy...
Load the module. Required for the Python meta-loading mechanism. def load_module(self, loader): ''' Load the module. Required for the Python meta-loading mechanism. ''' modfile, pathname, description = loader.info module = imp.load_module( loader.fullname, ...
:param cls: DB class def _register_event_listeners(self, cls): """ :param cls: DB class """ event.listen(cls, 'after_insert', self._new_listener) event.listen(cls, 'after_update', self._update_listener) event.listen(cls, 'after_delete', self._delete_listener)
Processing the changes. All new or changed items are now indexed. All deleted items are now removed from the index. def after_commit_listener(self, session): """ Processing the changes. All new or changed items are now indexed. All deleted items are now removed from the index. "...
creates a new job on the queue :param redis: redis :param delegate: method to be executed by the queue. Use fully qualified method name as String. :param args: arguments of the method :return: job_id def _queue_job(redis, queue_name, delegate, *args): """ ...
Rollback of the transaction, undo the indexes. If our transaction is terminated, we will reset the indexing assignments. def after_rollback_listener(self, session): """ Rollback of the transaction, undo the indexes. If our transaction is terminated, we will reset the ind...
:param sqlalchemy.session.Session session: Database session to remove def remove_session(self, session): """ :param sqlalchemy.session.Session session: Database session to remove """ try: del session.redis except AttributeError: pass try: ...
Parse a sort string for use with elasticsearch :param: sort: the sort string def parse_sort_string(sort): """ Parse a sort string for use with elasticsearch :param: sort: the sort string """ if sort is None: return ['_score'] l = sort.rsplit(',') sortlist = [] for se in l:...
Parse query_params to a filter params dict. Merge multiple values for one key to a list. Filter out keys that aren't filterable. :param query_params: query params :param filterable: list of filterable keys :return: dict of filter values def parse_filter_params(query_params, filterable): """ Pa...
Adding previous or next links to the given feed self._link_to_sibling(feed, 'previous', atom_feed) self._link_to_sibling(feed, 'next', atom_feed) :param feed: a feed object :param sibling_type: 'previous' or 'next' :param atom_feed: an atom feed like `feedgen.feed.FeedGenerator`...
Initializing an atom feed `feedgen.feed.FeedGenerator` given a feed object :param feed: a feed object :return: an atom feed `feedgen.feed.FeedGenerator` def init_atom_feed(self, feed): """ Initializing an atom feed `feedgen.feed.FeedGenerator` given a feed object :param feed: ...
A function returning a feed like `feedgen.feed.FeedGenerator`. The function can be overwritten when used in other applications. :param feed: a feed object :return: an atom feed `feedgen.feed.FeedGenerator` def _generate_atom_feed(self, feed): """ A function returning a feed lik...
Create a client for a service account. Create a client with an account name and a private key. Args: account_name: str, the account identifier (probably the account email). private_key: str, the private key as a string. private_key_path: str, path to a file with the private key in. st...
Create a client for a web or installed application. Create a client with a client secrets file. Args: client_secrets: str, path to the client secrets file (downloadable from Google API Console) storage: oauth2client.client.Storage, a Storage implementation to store ...
Create a client for a web or installed application. Create a client with a credentials stored in stagecraft db. Args: client_secrets: dict, client secrets (downloadable from Google API Console) storage: stagecraft.apps.collectors.libs.ga.CredentialStorage, ...
Build the client object. def _build(credentials, api_version, http_client=None): """Build the client object.""" if not http_client: http_client = httplib2.Http() authorised_client = credentials.authorize(http_client) return build("analytics", api_version, http=authorised_client)
Prefix a string with 'ga:' if it is not already Sort values may be prefixed with '-' to indicate negative sort. >>> _prefix_ga('foo') 'ga:foo' >>> _prefix_ga('ga:foo') 'ga:foo' >>> _prefix_ga('-foo') '-ga:foo' >>> _prefix_ga('-ga:foo') '-ga:foo' def _prefix_ga(value): """Prefi...
Approximates the limiting distribution to about 5 decimal digits. def ad_unif_inf(statistic): """ Approximates the limiting distribution to about 5 decimal digits. """ z = statistic if z < 2: return (exp(-1.2337141 / z) / sqrt(z) * (2.00012 + (.247105 - (.064...
Corrects the limiting distribution for a finite sample size. def ad_unif_fix(samples, pinf): """ Corrects the limiting distribution for a finite sample size. """ n = samples c = .01265 + .1757 / n if pinf < c: return (((.0037 / n + .00078) / n + .00006) / n) * g1(pinf / c) elif pinf...
Ensure all required meta-data are supplied. Specifically: name, version, URL, author or maintainer Warns if any are missing. If enforce-email option is true, author and/or maintainer must specify an email. def check_metadata(self): """Ensure all required meta-data are supplied...
Construct a PostgresConfig from a URL. def from_url(cls, url): """ Construct a PostgresConfig from a URL. """ parsed = urlparse(url) return cls( username=parsed.username, password=parsed.password, hostname=parsed.hostname, port=par...
Allows using `@vectorize` as well as `@vectorize()`. def vectorize(*args, **kwargs): """ Allows using `@vectorize` as well as `@vectorize()`. """ if args and callable(args[0]): # Guessing the argument is the method. return _vectorize(args[0]) else: # Wait for the second call...
Vectorized `arange()` taking a sequence of starts and a count of elements. For example:: >>> varange(1, 5) array([1, 2, 3, 4, 5]) >>> varange((1, 3), 5) array([[1, 2, 3, 4, 5], [3, 4, 5, 6, 7]]) def varange(starts, count): """ Vectorized `arange()` taking a...
Tween that adds ETag headers and tells Pyramid to enable conditional responses where appropriate. def conditional_http_tween_factory(handler, registry): """ Tween that adds ETag headers and tells Pyramid to enable conditional responses where appropriate. """ settings = registry.settings if ha...
Get the last modified date of a given file :param filename: string: pathname of a file :return: Date def get_last_modified_date(filename): """ Get the last modified date of a given file :param filename: string: pathname of a file :return: Date """ if os.path.isfile(filename): ...
Get the file size of a given file :param filename: string: pathname of a file :return: human readable filesize def get_file_size(filename): """ Get the file size of a given file :param filename: string: pathname of a file :return: human readable filesize """ if os.path.isfile(filename...
Transform bytesize to a human readable filesize :param size_bytes: bytesize :return: human readable filesize def convert_size(size_bytes): """ Transform bytesize to a human readable filesize :param size_bytes: bytesize :return: human readable filesize """ if size_bytes == 0: r...
Force validation of all traits. Useful for circumstances where an attribute won't be accessed until well after construction, but we want to fail eagerly if that attribute is passed incorrectly. Consider using ``StrictSerializable`` for classes where you always want this called ...
Generate an example instance of a Serializable subclass. If traits have been tagged with an `example` value, then we use that value. Otherwise we fall back the default_value for the instance. Traits with names in ``skip`` will not have example values set. def example_instance(cls, skip=()): ...
Generate an example yaml string for a Serializable subclass. If traits have been tagged with an `example` value, then we use that value. Otherwise we fall back the default_value for the instance. def example_yaml(cls, skip=()): """ Generate an example yaml string for a Serializable su...
Write a file containing an example yaml string for a Serializable subclass. def write_example_yaml(cls, dest, skip=()): """ Write a file containing an example yaml string for a Serializable subclass. """ # Make sure we can make an instance before we open a file. ...
Construct from base64-encoded JSON. def to_base64(self, skip=()): """ Construct from base64-encoded JSON. """ return base64.b64encode( ensure_bytes( self.to_json(skip=skip), encoding='utf-8', ) )
Serialize and write self to environ[self._envvar]. Parameters ---------- environ : dict-like Dict-like object (e.g. os.environ) into which to write ``self``. def to_environ(self, environ, skip=()): """ Serialize and write self to environ[self._envvar]. Para...
Retrieve an object by its object_id :param object_id: the objects id. :return: the requested object :raises: :class: NoResultFound when the object could not be found def get_one(self, object_id): """ Retrieve an object by its object_id :param object_id: the objects id....
Retrieve an object by its object_id Does a select for update on the row, results in row level lock for the duration of the transaction :param object_id: the objects id. :return: the requested object :raises: :class: NoResultFound when the object could not be found def get_one_for_updat...
Retrieve an object by its object_id :param: object_id: the objects id. :param: cls: the objects class, if None use the default class from the datamanager :return: the requested object or None if not found def get(self, object_id, cls=None): """ Retrieve an object by its object_...
Retrieve an object by its object_id Does a select for update on the row, results in row level lock for the duration of the transaction :param: object_id: the objects id. :param: cls: the objects class, if None use the default class from the datamanager :return: the requested object or N...
Delete an object by its id :param object_id: the objects id. :return: the deleted object :raises: :class: NoResultFound when the object could not be found def delete(self, object_id): """ Delete an object by its id :param object_id: the objects id. :return: the...
save an object :param obj: the object :return: the saved object def save(self, obj): """ save an object :param obj: the object :return: the saved object """ if obj not in self.session: self.session.add(obj) else: obj = se...
get a previous/next sibling from a feed :param feed_id: id of the feed :param sibling_type: sibling type ('previous', 'next') :return: the sibling def get_sibling(self, feed_id, sibling_type): """ get a previous/next sibling from a feed :param feed_id: id of the feed ...
Save an object to the db :param obj: the object to save :return: the saved object def save_object(self, obj): """ Save an object to the db :param obj: the object to save :return: the saved object """ self.session.add(obj) self.session.flush() ...
Retrieves feed that was persisted as .xml file by its id (= filename) Note: No check on feed validity. file content is assumed correct :param feed_id: :return: the atom feed as string def get_from_archive(self, feed_id): """ Retrieves feed that was persisted as .xml file by its ...
Get a specific feed entry :param id: id of the feed entry to retrieve :return: the feed entry def get_atom_feed_entry(self, feedentry_id): """ Get a specific feed entry :param id: id of the feed entry to retrieve :return: the feed entry """ return self.se...
Archive a feed :param feed_id: the feed id of the feed to archive :param feed: the feed to archive def archive_feed(self, feed_id, feed): """ Archive a feed :param feed_id: the feed id of the feed to archive :param feed: the feed to archive """ with open(...
Adds named concept filters :param named_filter_concepts: dict with named filter concepts which will be mapped as the key as query param and the value as search string def add_named_concept_filters(self, named_filter_concepts): """ Adds named concept filters :param named_filter_concept...
Add a concept filter :param concept: concept which will be used as lowercase string in a search term :param concept_name: name of the place where there will be searched for def add_concept_filter(self, concept, concept_name=None): """ Add a concept filter :param concept: conce...
Builds the query string, which can be used for a search query :return: the query string def build(self): """ Builds the query string, which can be used for a search query :return: the query string """ if self.es_version == '1': if len(self.filters) > 0: ...
Parse the range headers into a range object. When there are no range headers, check for a page 'pagina' parameter, otherwise use the defaults defaults :param request: a request object :param default_start: default start for paging (optional, default is 0) :param default_end: default en...
Set the correct range headers on the response :param request: a request object :param total_count: the total number of results def set_response_headers(self, request, total_count): ''' Set the correct range headers on the response :param request: a request object :para...
Sets Link headers on the response. When the Range header is present in the request no Link headers will be added. 4 links will be added: first, prev, next, last. If the current page is already the first page, the prev link will not be present. If the current page is alre...
Colander validator that checks whether a given value is a valid Belgian national ID number . :raises colander.Invalid: If the value is no valid Belgian national ID number. def validator(node, rrn): ''' Colander validator that checks whether a given value is a valid Belgian natio...
Edit a value to a value that can be validated as a kbo number. def preparer(value): ''' Edit a value to a value that can be validated as a kbo number. ''' if value is None or value == colander.null: return colander.null return value.strip().replace('....
Colander validator that checks whether a given value is a valid is company number. For our purposes , we expect a firm number that is composed of nine or ten characters like 2028445291. Sometimes a company number is formatted with separation marks like 0.400.378.485. Therefore, t...
Edit a phone value to a value that can be validated as a phone number. This takes the incoming value and : Removes all whitespace ( space, tab , newline , ... ) characters Removes the following characters: " / - . " If no + is present at frond, add the country code ...
A valid international phone number looks like this: + . It is up to 15 digits long . The country code consists of 1 to 4 digits. The actual number may even 15 - cells ( country code) figures cover . We're going to keep the phone numbers including a + to indicate the international call prefix. A ...
Calculates the limiting distribution of the Cramer-von Mises statistic. After the second line of equation 1.3 from the Csorgo and Faraway paper. def cvm_unif_inf(statistic): """ Calculates the limiting distribution of the Cramer-von Mises statistic. After the second line of equation 1.3 from the Csor...
Approximates the first-term of the small sample count Gotze expansion. After equation 1.10 (with coefficients pulled out as csa / csb). def cvm_unif_fix1(statistic): """ Approximates the first-term of the small sample count Gotze expansion. After equation 1.10 (with coefficients pulled out as csa / c...
Merge together a sequence if dictionaries. Later entries overwrite values from earlier entries. >>> merge({'a': 'b', 'c': 'd'}, {'a': 'z', 'e': 'f'}) {'a': 'z', 'c': 'd', 'e': 'f'} def merge(*ds): """ Merge together a sequence if dictionaries. Later entries overwrite values from earlier entr...
Validate a sqlalchemy object or identifier. Function checks if value is an instance of sqlalchemy model or an id of one. :param node: A colander SchemaNode. :param value: The value to be validated. Is the key of the SQLAlchemy model. :param model: A SQLAlchemy model. :param session: A SQ...
Calculates the Kolmogorov-Smirnov statistic for sorted values from U(0, 1). def ks_stat(data): """ Calculates the Kolmogorov-Smirnov statistic for sorted values from U(0, 1). """ samples = len(data) uniform = arange(0, samples + 1) / samples d_plus = (uniform[1:] - data).max() d_minus = (da...
Calculates the Cramer-von Mises statistic for sorted values from U(0, 1). def cvm_stat(data): """ Calculates the Cramer-von Mises statistic for sorted values from U(0, 1). """ samples2 = 2 * len(data) minuends = arange(1, samples2, 2) / samples2 return 1 / (6 * samples2) + ((minuends - data) **...
Calculates the Anderson-Darling statistic for sorted values from U(0, 1). The statistic is not defined if any of the values is exactly 0 or 1. You will get infinity as a result and a divide-by-zero warning for such values. The warning can be silenced or raised using numpy.errstate(divide=...). def ad_stat...
Calculates the probability that the statistic is less than the given value, using a fairly accurate implementation of the Durbin's matrix formula. Not an exact transliteration of the Marsaglia code, but using the same ideas. Assumes samples > 0. See: doi:10.18637/jss.v008.i18. def ks_unif_durbin_matrix(sa...
Calculates the probability that the statistic is less than the given value, using Durbin's recurrence and employing the standard fractions module. This is a (hopefully) exact reference implementation, likely too slow for practical usage. The statistic should be given as a Fraction instance and the resu...
Approximates the statistic distribution by a transformed Li-Chien formula. This ought to be a bit more accurate than using the Kolmogorov limit, but should only be used with large squared sample count times statistic. See: doi:10.18637/jss.v039.i11 and http://www.jstor.org/stable/2985019. def ks_unif_pelz...
Activate the type safety checker. After the call all functions that need to be checked will be. def activate(self, *, filter_func=None): ''' Activate the type safety checker. After the call all functions that need to be checked will be. ''' if self.active: r...
use this decorator to audit an operation def audit(**kwargs): """ use this decorator to audit an operation """ def wrap(fn): @functools.wraps(fn) def advice(parent_object, *args, **kw): request = parent_object.request wijziging = request.audit_manager.create_re...
use this decorator to audit an operation with a request as input variable def audit_with_request(**kwargs): """ use this decorator to audit an operation with a request as input variable """ def wrap(fn): @audit(**kwargs) def operation(parent_object, *args, **kw): return fn(p...
A contextmanager for holding Traited object's cross-validators. This should be used in circumstances where you want to call _validate, but don't want to fire cross-validators. def cross_validation_lock(obj): """ A contextmanager for holding Traited object's cross-validators. This should be used i...
If we're an instance of a Serializable, fall back to its `example_instance()` method. def example_value(self): """ If we're an instance of a Serializable, fall back to its `example_instance()` method. """ from .serializable import Serializable inst = self._static...
Copy a file and replace some placeholders with new values. def copy_and_replace(file_in, file_out, mapping, **kwargs): ''' Copy a file and replace some placeholders with new values. ''' separator = '@@' if 'separator' in kwargs: separator = kwargs['separator'] file_in = open(file_in, 'r...
Convert plain list to MutableList. def coerce(cls, key, value): """ Convert plain list to MutableList. """ if not isinstance(value, MutableList): if isinstance(value, list): return MutableList(value) # this call will raise ValueError r...
Register a new Worker, under the given descriptive name. Trying to register multiple workers under the same name will raise an Exception. Parameters ---------- name: string Name to register the given worker under. worker: multiprocessing.Process, or a subclass Process object to register. def register...
Retrieve the Worker registered under the given name. If the given name does not exists in the Worker list, an Exception is raised. Parameters ---------- name: string Name of the Worker to retrieve def getWorker(self, name): """ Retrieve the Worker registered under the given name. If the given name ...
Unregister the Worker registered under the given name. Make sure that the given Worker is properly stopped, or that a reference is kept in another place. Once unregistered, this class will not keep any other references to the Worker. Parameters ---------- name: string Name of the Worker to unregister ...
Start all registered Workers. def startAll(self): """ Start all registered Workers. """ self.logger.info("Starting all workers...") for worker in self.getWorkers(): process = self.getWorker(worker) self.logger.debug("Starting {0}".format(process.name)) process.start() self.logger.info("Started a...
Stop all registered Workers. This is method assumes that the Worker has already received a stop message somehow, and simply joins the Process until it dies, as follows: 1. The Worker is retrieved. 2. The Worker is joined, and will wait until the Worker exits. 3. The Worker is unregistered. 4. If $stop = T...
get cached data for a url if stored in the cache and not outdated Args: url: URL for the Ensembl REST service Returns: data if data in cache, else None def get_cached_data(self, url): """ get cached data for a url if stored in the cache and not outdated...
cache the data retrieved from ensembl Args: url: URL for the Ensembl REST service data: response data from Ensembl def cache_url_data(self, url, data, attempt=0): """ cache the data retrieved from ensembl Args: url: URL for the Ensembl REST ...
parses the url into a list of folder locations We take a URL like: http://rest.ensembl.org/sequence/id/ENST00000538324?type=genomic;expand_3prime=10;expand_5prime=10 and turn it into 'sequence.id.ENST00000538324.genomic' Args: url: URL for the Ensembl RE...
Cast a datetime filter value. :param value: string representation of a value that needs to be casted to a `datetime` object. def cast_datetime_filter(value): """Cast a datetime filter value. :param value: string representation of a value that needs to be casted to a `datetime` object. ...
Cast and validate filter args. :param filter_dict: Filter kwargs :param accepted_filter_keys: List of keys that are acceptable to use. def filter_args_to_dict(filter_dict, accepted_filter_keys=[]): """Cast and validate filter args. :param filter_dict: Filter kwargs :param accepted_filter_keys: Li...
Bencodes obj and returns it as a string def bencode(obj): """Bencodes obj and returns it as a string""" if isinstance(obj, int): return "i" + str(obj) + "e" if isinstance(obj, str): if not obj: return None return str(len(obj)) + ":" + obj if isinstance(obj, list): ...
Decodes a bencoded bytearray and returns it as a python object def bdecode(text): """Decodes a bencoded bytearray and returns it as a python object""" text = text.decode('utf-8') def bdecode_next(start): """bdecode helper function""" if text[start] == 'i': end = text.find('e', ...
Changes the standard password from neo4j to testing to be able to run the test suite. def change_password(): """ Changes the standard password from neo4j to testing to be able to run the test suite. """ basic_auth = '%s:%s' % (DEFAULT_USERNAME, DEFAULT_PASSWORD) try: # Python 2 auth = base...
Create an ArgumentParser which listens for the following common options: - --config - --help - --quiet - --verbose - --version Arguments --------- suppress_help: list of strings Defines what options to suppress from being added to the ArgumentParser. Provide the name of the options to suppress, without "--...
Parse command line arguments, and try to find common options. Internally this method uses the ArgumentParser returned by get_config_argparse(). All variables are stored as True if set, --config will contain a string. Returns a tuple containing parsed variables and unknown variables, just like ArgumentParser.parse...
Turn an ArgumentParser into a ConfigObj compatible configuration file. This method will take the given argparser, and loop over all options contained. The configuration file is formatted as follows: # <option help info> <option destination variable>=<option default value> Arguments --------- argparser: Argume...
Binds queues to exchanges. Parameters ---------- binds: list of dicts a list of dicts with the following keys: queue: string - name of the queue to bind exchange: string - name of the exchange to bind routing_key: string - routing key to use for this bind def _perform_binds(self, binds): """ ...
Unbinds queues from exchanges. Parameters ---------- binds: list of dicts A list of dicts with the following keys: queue: string - name of the queue to bind exchange: string - name of the exchange to bind routing_key: string - routing key to use for this bind def _perform_unbinds(self, binds): ...
Closes the internal connection. def close(self): """ Closes the internal connection. """ self.cancel() self.logger.debug("Closing AMQP connection") try: self.connection.close() except Exception, eee: self.logger.warning("Received an error while trying to close AMQP connection: " + str(eee))
Cancels the current consuming action by using the stored consumer_tag. If a consumer_tag is given, that one is used instead. Parameters ---------- consumer_tag: string Tag of consumer to cancel def cancel(self, consumer_tag=None): """ Cancels the current consuming action by using the stored consumer_tag....
Initialize consuming of messages from an AMQP queue. Messages will be consumed after start_consuming() is called. Calling this method multiple times with exclusive active will result in a pika.exceptions.ChannelClosed Error. Parameters ---------- consumer_callback: callback Function to call when a message ...
Retrieves the key from a parsed_json dictionary, or raises an exception if the key is not present def json_get(parsed_json, key): """ Retrieves the key from a parsed_json dictionary, or raises an exception if the key is not present """ if key not in parsed_json: raise ValueError("JSON d...