code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
log.info('Removing indexing orders.') try: session.index_new[self.cls_name].clear() session.index_dirty[self.cls_name].clear() session.index_deleted[self.cls_name].clear() except (AttributeError, KeyError): log.warning('Trying to remove in...
def after_rollback_listener(self, session)
Rollback of the transaction, undo the indexes. If our transaction is terminated, we will reset the indexing assignments.
5.741309
5.079799
1.130224
try: del session.redis except AttributeError: pass try: del session.index_new[self.cls_name] del session.index_dirty[self.cls_name] del session.index_deleted[self.cls_name] except (AttributeError, KeyError): ...
def remove_session(self, session)
:param sqlalchemy.session.Session session: Database session to remove
4.623857
4.853123
0.952759
if sort is None: return ['_score'] l = sort.rsplit(',') sortlist = [] for se in l: se = se.strip() order = 'desc' if se[0:1] == '-' else 'asc' field = se[1:] if se[0:1] in ['-', '+'] else se field = field.strip() sortlist.append({field: {"order": orde...
def parse_sort_string(sort)
Parse a sort string for use with elasticsearch :param: sort: the sort string
2.870541
2.992836
0.959137
if query_params is not None: filter_params = {} for fq in query_params.mixed(): if fq in filterable: filter_params[fq] = query_params.mixed().get(fq) return filter_params else: return {}
def parse_filter_params(query_params, filterable)
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
3.113946
3.673283
0.847728
sibling = self.atom_feed_manager.get_sibling(feed.id, sibling_type) if sibling: rel = "prev-archive" if sibling_type == "previous" else "next-archive" atom_feed.link(href=self.request.route_url(self.get_atom_feed_url, id=sibling.id), rel=rel)
def link_to_sibling(self, feed, sibling_type, atom_feed)
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`
3.770951
3.989132
0.945306
atom_feed = FeedGenerator() atom_feed.id(id=self.request.route_url(self.get_atom_feed_url, id=feed.id)) atom_feed.link(href=self.request.route_url(self.get_atom_feed_url, id=feed.id), rel='self') atom_feed.language('nl-BE') self.link_to_sibling(feed, 'previous', atom_fee...
def init_atom_feed(self, feed)
Initializing an atom feed `feedgen.feed.FeedGenerator` given a feed object :param feed: a feed object :return: an atom feed `feedgen.feed.FeedGenerator`
2.544118
2.749291
0.925372
atom_feed = self.init_atom_feed(feed) atom_feed.title("Feed") return atom_feed
def _generate_atom_feed(self, 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`
6.594009
7.395452
0.89163
if not private_key: if not private_key_path: raise GapyError( "Must provide either a private_key or a private_key_file") if isinstance(private_key_path, basestring): private_key_path = open(private_key_path) private_key = private_key_path.read() ...
def from_private_key(account_name, private_key=None, private_key_path=None, storage=None, storage_path=None, api_version="v3", readonly=False, http_client=None, ga_hook=None)
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...
2.747089
2.901047
0.94693
scope = GOOGLE_API_SCOPE_READONLY if readonly else GOOGLE_API_SCOPE flow = flow_from_clientsecrets(client_secrets, scope=scope) storage = _get_storage(storage, storage_path) credentials = storage.get() if credentials is None or credentials.invalid: cre...
def from_secrets_file(client_secrets, storage=None, flags=None, storage_path=None, api_version="v3", readonly=False, http_client=None, ga_hook=None)
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 ...
2.767882
3.162226
0.875296
credentials = storage.get() return Client(_build(credentials, api_version, http_client), ga_hook)
def from_credentials_db(client_secrets, storage, api_version="v3", readonly=False, http_client=None, ga_hook=None)
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, ...
6.584402
14.844278
0.443565
if not http_client: http_client = httplib2.Http() authorised_client = credentials.authorize(http_client) return build("analytics", api_version, http=authorised_client)
def _build(credentials, api_version, http_client=None)
Build the client object.
3.840541
3.299313
1.164043
prefix = '' if value[0] == '-': value = value[1:] prefix = '-' if not value.startswith('ga:'): prefix += 'ga:' return prefix + value
def _prefix_ga(value)
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'
3.171892
4.186478
0.757652
z = statistic if z < 2: return (exp(-1.2337141 / z) / sqrt(z) * (2.00012 + (.247105 - (.0649821 - (.0347962 - (.011672 - .00168691 * z) * z) * z) * z) * z)) else: return exp(-exp(1.0776 - (2.30695 - (.43424 - (.082433 - ...
def ad_unif_inf(statistic)
Approximates the limiting distribution to about 5 decimal digits.
6.506016
6.488157
1.002753
n = samples c = .01265 + .1757 / n if pinf < c: return (((.0037 / n + .00078) / n + .00006) / n) * g1(pinf / c) elif pinf < .8: return ((.01365 / n + .04213) / n) * g2((pinf - c) / (.8 - c)) else: return g3(pinf) / n
def ad_unif_fix(samples, pinf)
Corrects the limiting distribution for a finite sample size.
4.872634
4.8894
0.996571
metadata = self.distribution.metadata missing = [] for attr in ("name", "version", "url"): if not (hasattr(metadata, attr) and getattr(metadata, attr)): missing.append(attr) # https://www.python.org/dev/peps/pep-0345/ # author or maintainer ...
def check_metadata(self)
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.
2.530119
2.3257
1.087896
parsed = urlparse(url) return cls( username=parsed.username, password=parsed.password, hostname=parsed.hostname, port=parsed.port, database=parsed.path.lstrip('/'), # Like parse_qs, but produces a scalar per key, instead of...
def from_url(cls, url)
Construct a PostgresConfig from a URL.
3.49983
3.359103
1.041894
if args and callable(args[0]): # Guessing the argument is the method. return _vectorize(args[0]) else: # Wait for the second call. return lambda m: _vectorize(m, *args, **kwargs)
def vectorize(*args, **kwargs)
Allows using `@vectorize` as well as `@vectorize()`.
5.648413
5.281832
1.069404
try: return stack(arange(s, s + count) for s in starts) except TypeError: return arange(starts, starts + count)
def varange(starts, count)
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]])
4.258035
5.15479
0.826035
settings = registry.settings if hasattr(registry, 'settings') else {} not_cacheble_list = [] if 'not.cachable.list' in settings: not_cacheble_list = settings.get('not.cachable.list').split() def conditional_http_tween(request): response = handler(request) if request.path n...
def conditional_http_tween_factory(handler, registry)
Tween that adds ETag headers and tells Pyramid to enable conditional responses where appropriate.
4.090772
3.856851
1.060651
if os.path.isfile(filename): t = os.path.getmtime(filename) return datetime.date.fromtimestamp(t).strftime('%d/%m/%Y') return None
def get_last_modified_date(filename)
Get the last modified date of a given file :param filename: string: pathname of a file :return: Date
2.420544
3.043233
0.795386
if os.path.isfile(filename): return convert_size(os.path.getsize(filename)) return None
def get_file_size(filename)
Get the file size of a given file :param filename: string: pathname of a file :return: human readable filesize
2.848833
3.423269
0.832197
if size_bytes == 0: return "0B" size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB") i = int(math.floor(math.log(size_bytes, 1024))) p = math.pow(1024, i) s = round(size_bytes / p, 2) return "%s %s" % (s, size_name[i])
def convert_size(size_bytes)
Transform bytesize to a human readable filesize :param size_bytes: bytesize :return: human readable filesize
1.173551
1.252585
0.936903
errors = {} for name in self.trait_names(): try: getattr(self, name) except TraitError as e: errors[name] = e if errors: raise MultipleTraitErrors(errors)
def validate_all_attributes(self)
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 ...
3.79622
3.877717
0.978983
kwargs = {} for name, trait in iteritems(cls.class_traits()): if name in skip: continue value = trait.example_value if value is Undefined: continue kwargs[name] = value return cls(**kwargs)
def example_instance(cls, skip=())
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.
3.60301
2.908134
1.238942
return cls.example_instance(skip=skip).to_yaml(skip=skip)
def example_yaml(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.
10.070773
7.381396
1.364345
# Make sure we can make an instance before we open a file. inst = cls.example_instance(skip=skip) with open(dest, 'w') as f: inst.to_yaml(stream=f, skip=skip)
def write_example_yaml(cls, dest, skip=())
Write a file containing an example yaml string for a Serializable subclass.
5.281007
5.134607
1.028512
return base64.b64encode( ensure_bytes( self.to_json(skip=skip), encoding='utf-8', ) )
def to_base64(self, skip=())
Construct from base64-encoded JSON.
3.740217
3.148577
1.187907
environ[ensure_unicode(type(self).__name__)] = ( ensure_unicode(self.to_base64(skip=skip)) )
def to_environ(self, environ, skip=())
Serialize and write self to environ[self._envvar]. Parameters ---------- environ : dict-like Dict-like object (e.g. os.environ) into which to write ``self``.
7.451053
9.308857
0.800426
return self.session.query(self.cls).filter_by(id=object_id).one()
def get_one(self, object_id)
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
3.344427
4.356463
0.767693
return self.session.query(self.cls).with_for_update().filter_by(id=object_id).one()
def get_one_for_update(self, object_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
3.317829
3.786883
0.876137
cls = self.cls if cls is None else cls return self.session.query(cls).get(object_id)
def get(self, object_id, cls=None)
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
3.765516
4.534389
0.830435
cls = self.cls if cls is None else cls return self.session.query(cls).with_for_update().get(object_id)
def get_for_update(self, object_id, cls=None)
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...
3.309175
3.511389
0.942412
obj = self.session.query(self.cls).filter_by(id=object_id).one() self.session.delete(obj) return obj
def delete(self, object_id)
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
2.632103
3.085231
0.85313
if obj not in self.session: self.session.add(obj) else: obj = self.session.merge(obj) self.session.flush() self.session.refresh(obj) return obj
def save(self, obj)
save an object :param obj: the object :return: the saved object
2.453403
2.680969
0.915118
if sibling_type == 'previous': query = self.session.query(self.feed_model).filter(self.feed_model.id < feed_id) order_clause = desc(self.feed_model.id) elif sibling_type == 'next': query = self.session.query(self.feed_model).filter(self.feed_model.id > feed_i...
def get_sibling(self, feed_id, sibling_type)
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
2.195005
2.152442
1.019774
self.session.add(obj) self.session.flush() return obj
def save_object(self, obj)
Save an object to the db :param obj: the object to save :return: the saved object
3.847226
4.248203
0.905613
file_path = self.feed_repository + '/' + str(feed_id) + '.xml' if not os.path.isfile(file_path): raise FeedArchiveNotFound() with open(file_path, 'r') as rec_file: return rec_file.read()
def get_from_archive(self, feed_id)
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
3.458055
3.227156
1.071549
return self.session.query(self.feedentry_model).filter( self.feedentry_model.id == feedentry_id ).one()
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
3.025465
3.988018
0.758639
with open(self.feed_repository + '/' + str(feed_id) + '.xml', 'w') as rec_file: rec_file.write(feed.atom_str(pretty=True)) if feed_id == self.current_feed.id: self._current_feed = None
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
4.143354
4.488084
0.92319
for concept_key, concept_name in named_filter_concepts.items(): self.add_concept_filter(concept_key, concept_name=concept_name)
def add_named_concept_filters(self, named_filter_concepts)
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
2.748652
3.33061
0.82527
if concept in self.query_params.keys(): if not concept_name: concept_name = concept if isinstance(self.query_params[concept], list): if self.es_version == '1': es_filter = {'or': []} for or_filter in self.qu...
def add_concept_filter(self, concept, concept_name=None)
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
1.930866
2.157114
0.895115
if self.es_version == '1': if len(self.filters) > 0: return { 'filtered': { 'query': self.query, 'filter': { 'and': self.filters } } ...
def build(self)
Builds the query string, which can be used for a search query :return: the query string
2.393203
2.154067
1.111016
''' 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 def...
def parse(cls, request, default_start=0, default_end=9, max_end=50)
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...
2.731379
1.709332
1.597921
''' Set the correct range headers on the response :param request: a request object :param total_count: the total number of results ''' response = request.response response.headerlist.append(('Access-Control-Expose-Headers', 'Content-Range, X-Content-Range')) ...
def set_response_headers(self, request, total_count)
Set the correct range headers on the response :param request: a request object :param total_count: the total number of results
4.229672
3.317824
1.274833
response = request.response if request.headers.get('Range'): # Don't set the Link headers when custom ranges were used. return settings = request.registry.settings page_param = settings.get('oe.paging.page.queryparam', 'pagina') per_page_param = ...
def set_link_headers(self, request, total_count)
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...
2.945355
3.062181
0.961849
''' 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 _valid(_rrn): x = 97 - (int(_rrn[:-2]) - (int(_rrn[:-2]) // 97) * 97) ...
def validator(node, rrn)
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.
3.619807
2.624437
1.37927
''' 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('.', '')
def preparer(value)
Edit a value to a value that can be validated as a kbo number.
12.958536
3.624367
3.575392
''' 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. ...
def validator(node, value)
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...
16.742615
1.648159
10.158371
''' 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...
def preparer(telefoon)
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 ...
4.341762
1.791837
2.423079
''' 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...
def validator(node, telefoon)
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 ...
7.289632
2.13237
3.418558
args = inf_args / statistic return (inf_cs * exp(-args) * kv(.25, args)).sum() / statistic ** .5
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 Csorgo and Faraway paper.
23.633413
31.423695
0.752089
args = fix1_args / statistic kvs = kv((.25, .75, 1.25), args[:, :, newaxis]) gs, hs = exp(-args) * tensordot(((1, 1, 0), (2, 3, -1)), kvs, axes=(1, 2)) a = dot((7, 16, 7), fix1_csa * gs).sum() / statistic ** 1.5 b = dot((1, 0, 24), fix1_csb * hs).sum() / statistic ** 2.5 return cvm_unif_inf...
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 / csb).
7.039523
7.039217
1.000043
if not ds: raise ValueError("Must provide at least one dict to merge().") out = {} for d in ds: out.update(d) return out
def merge(*ds)
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'}
3.778896
6.251339
0.604494
m = session.query(model).get(value) if not m: raise colander.Invalid( node, msg % value ) return m
def sqlalchemy_validator(node, value, model, session=None, msg='%s is ongeldig')
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...
3.779833
3.945017
0.958128
samples = len(data) uniform = arange(0, samples + 1) / samples d_plus = (uniform[1:] - data).max() d_minus = (data - uniform[:-1]).max() return max(d_plus, d_minus)
def ks_stat(data)
Calculates the Kolmogorov-Smirnov statistic for sorted values from U(0, 1).
4.403922
3.89937
1.129393
samples2 = 2 * len(data) minuends = arange(1, samples2, 2) / samples2 return 1 / (6 * samples2) + ((minuends - data) ** 2).sum()
def cvm_stat(data)
Calculates the Cramer-von Mises statistic for sorted values from U(0, 1).
8.298124
8.632166
0.961303
samples = len(data) factors = arange(1, 2 * samples, 2) return -samples - (factors * log(data * (1 - data[::-1]))).sum() / samples
def ad_stat(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=...).
9.595121
8.533024
1.124469
# Construct the Durbin matrix. h, k = modf(samples * statistic) k = int(k) h = 1 - h m = 2 * k + 1 A = tri(m, k=1) hs = h ** arange(1, m + 1) A[:, 0] -= hs A[-1] -= hs[::-1] if h > .5: A[-1, 0] += (2 * h - 1) ** m A /= fromfunction(lambda i, j: gamma(fmax(1, i - ...
def ks_unif_durbin_matrix(samples, statistic)
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.
4.920313
4.777691
1.029852
t = statistic * samples # Python 3: int()s can be skipped. ft1 = int(floor(t)) + 1 fmt1 = int(floor(-t)) + 1 fdt1 = int(floor(2 * t)) + 1 qs = [Fraction(i ** i, factorial(i)) for i in range(ft1)] qs.extend(Fraction(i ** i, factorial(i)) - 2 * t * sum((t + j) ** (j - ...
def ks_unif_durbin_recurrence_rational(samples, statistic)
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...
4.481969
4.480777
1.000266
x = 1 / statistic r2 = 1 / samples rx = sqrt(r2) * x r2x = r2 * x r2x2 = r2x * x r4x = r2x * r2 r4x2 = r2x2 * r2 r4x3 = r2x2 * r2x r5x3 = r4x2 * rx r5x4 = r4x3 * rx r6x3 = r4x2 * r2x r7x5 = r5x4 * r2x r9x6 = r7x5 * r2x r11x8 = r9x6 * r2x2 a1 = rx * (-r6x3...
def ks_unif_pelz_good(samples, statistic)
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.
3.284686
3.24983
1.010726
''' Activate the type safety checker. After the call all functions that need to be checked will be. ''' if self.active: raise RuntimeError("Type safety check already active") self.__module_finder = ModuleFinder(Validator.decorate) if filter_func is n...
def activate(self, *, filter_func=None)
Activate the type safety checker. After the call all functions that need to be checked will be.
8.139754
4.092168
1.989106
def wrap(fn): @functools.wraps(fn) def advice(parent_object, *args, **kw): request = parent_object.request wijziging = request.audit_manager.create_revision() result = fn(parent_object, *args, **kw) if hasattr(request, 'user') and request.user...
def audit(**kwargs)
use this decorator to audit an operation
3.334156
3.309043
1.007589
def wrap(fn): @audit(**kwargs) def operation(parent_object, *args, **kw): return fn(parent_object.request, *args, **kw) @functools.wraps(fn) def advice_with_request(the_request, *args, **kw): class ParentObject: request = the_request ...
def audit_with_request(**kwargs)
use this decorator to audit an operation with a request as input variable
3.962459
3.591185
1.103385
# TODO: Replace this with usage of public API when # https://github.com/ipython/traitlets/pull/166 lands upstream. orig = getattr(obj, '_cross_validation_lock', False) try: obj._cross_validation_lock = True yield finally: obj._cross_validation_lock = orig
def cross_validation_lock(obj)
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.
4.122989
3.95744
1.041832
from .serializable import Serializable inst = self._static_example_value() if inst is tr.Undefined and issubclass(self.klass, Serializable): return self.klass.example_instance() return inst
def example_value(self)
If we're an instance of a Serializable, fall back to its `example_instance()` method.
11.20506
6.644137
1.686458
''' Copy a file and replace some placeholders with new values. ''' separator = '@@' if 'separator' in kwargs: separator = kwargs['separator'] file_in = open(file_in, 'r') file_out = open(file_out, 'w') s = file_in.read() for find, replace in mapping: find = separator ...
def copy_and_replace(file_in, file_out, mapping, **kwargs)
Copy a file and replace some placeholders with new values.
2.524867
2.339956
1.079023
if not isinstance(value, MutableList): if isinstance(value, list): return MutableList(value) # this call will raise ValueError return Mutable.coerce(key, value) else: return value
def coerce(cls, key, value)
Convert plain list to MutableList.
5.14481
3.272021
1.572365
if not isinstance(worker, multiprocessing.Process): self.logger.error("Process {0} is not actually a Process!".format(name)) raise Exception("Process {0} is not actually a Process!".format(name)) if name in self.worker_list: self.logger.error("Process {0} already registered!".format(name)) raise Exc...
def registerWorker(self, name, worker)
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.
1.971951
2.138619
0.922067
if not name in self.worker_list: self.logger.error("Worker {0} is not registered!".format(name)) raise Exception("Worker {0} is not registered!".format(name)) return self.worker_list[name]
def getWorker(self, name)
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
2.178163
2.496291
0.87256
if not name in self.worker_list: self.logger.error("Worker {0} is not registered!".format(name)) raise Exception("Worker {0} is not registered!".format(name)) del self.worker_list[name] self.logger.debug("Unregistered worker {0}".format(name))
def unregisterWorker(self, 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
1.988678
2.448282
0.812275
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 all workers")
def startAll(self)
Start all registered Workers.
2.908048
2.710967
1.072698
self.logger.info("Stopping all workers...") for worker in self.getWorkers(): process = self.getWorker(worker) self.logger.debug("Stopping {0}".format(process.name)) if process.is_alive(): process.join(timeout) if process.is_alive(): self.logger.warning("Failed to stop {0}, terminating".for...
def stopAll(self, timeout=10, stop=False)
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...
2.731176
2.560826
1.066522
key = self.get_key_from_url(url) with self.conn as conn: cursor = conn.cursor() cursor.execute("SELECT * FROM ensembl WHERE key=? AND genome_build=?", (key, self.genome_build)) row = cursor.fetchone() # if the da...
def get_cached_data(self, url)
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
3.581029
3.419174
1.047337
if attempt > 5: raise ValueError('too many attempts at writing to the cache') key = self.get_key_from_url(url) # don't cache the ensembl version check if key == "info.rest": return current_date = datetime.strfti...
def cache_url_data(self, url, data, attempt=0)
cache the data retrieved from ensembl Args: url: URL for the Ensembl REST service data: response data from Ensembl
5.001806
4.87782
1.025418
key = url.split("/")[3:] # fix the final bit of the url, none of which uniquely define the data suffix = key.pop() suffix = suffix.split(";")[0] # convert "LONG_ID?feature=transcript" to ['LONG_ID', "transcript"] etc id = suffix.split("...
def get_key_from_url(self, url)
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...
7.675257
7.211849
1.064256
if isinstance(value, str): dtime = parse_datetime(value) elif isinstance(value, datetime): dtime = value else: raise ValueError('Received value of type {0}'.format(type(value))) return dtime.isoformat()
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.
3.235669
3.648612
0.886822
out_dict = {} for k, v in filter_dict.items(): # make sure that the filter k is acceptable # and that there is a value associated with the key if k not in accepted_filter_keys or v is None: logger.debug( 'Filter was not in accepted_filter_keys or value is...
def filter_args_to_dict(filter_dict, accepted_filter_keys=[])
Cast and validate filter args. :param filter_dict: Filter kwargs :param accepted_filter_keys: List of keys that are acceptable to use.
3.611014
3.634628
0.993503
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): res = "l" for elem in obj: elem = bencode(elem) if elem: ...
def bencode(obj)
Bencodes obj and returns it as a string
2.153378
2.131379
1.010322
text = text.decode('utf-8') def bdecode_next(start): if text[start] == 'i': end = text.find('e', start) return int(text[start+1:end], 10), end + 1 if text[start] == 'l': res = [] start += 1 while text[start] != 'e': ...
def bdecode(text)
Decodes a bencoded bytearray and returns it as a python object
1.811881
1.764148
1.027058
basic_auth = '%s:%s' % (DEFAULT_USERNAME, DEFAULT_PASSWORD) try: # Python 2 auth = base64.encodestring(basic_auth) except TypeError: # Python 3 auth = base64.encodestring(bytes(basic_auth, 'utf-8')).decode() headers = { "Content-Type": "application/json", "Accept"...
def change_password()
Changes the standard password from neo4j to testing to be able to run the test suite.
2.57216
2.473473
1.039898
if suppress is None: suppress = [] config_parser = ArgumentParser(description="Looking for config", add_help=(not "help" in suppress)) if not "config" in suppress: config_parser.add_argument("--config", metavar="CFG", type=str, help="Config file to load") if "help" in suppress: config_parser.add_argume...
def get_config_argparse(suppress=None)
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 "--...
2.146687
2.065651
1.03923
logger = logging.getLogger(__name__) logger.debug("Parsing configuration arguments") return get_config_argparse(suppress=["help"]).parse_known_args()
def get_config_arguments()
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...
7.638469
5.572841
1.37066
if not suppress: suppress = [] if not default_override: default_override = {} lines = [] seen_arguments = [] for arg in argparser._actions: if arg.dest in suppress: continue if arg.dest in seen_arguments: continue default = arg.default if arg.dest in default_override.keys(): default = defau...
def get_default_config_file(argparser, suppress=None, default_override=None)
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...
1.998222
2.006117
0.996065
for bind in binds: self.logger.debug("Binding queue {0} to exchange {1} with key {2}".format(bind['queue'], bind['exchange'], bind['routing_key'])) self.channel.queue_bind(**bind)
def _perform_binds(self, binds)
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
2.741521
2.418501
1.133562
for bind in binds: self.logger.debug("Unbinding queue {0} from exchange {1} with key {2}".format(bind['queue'], bind['exchange'], bind['routing_key'])) self.channel.queue_unbind(**bind)
def _perform_unbinds(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
2.593518
2.359976
1.09896
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))
def close(self)
Closes the internal connection.
3.878213
3.788592
1.023655
if not consumer_tag: if not hasattr(self, "consumer_tag"): return consumer_tag = self.consumer_tag self.channel.basic_cancel(consumer_tag)
def cancel(self, consumer_tag=None)
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
2.342537
2.950596
0.79392
if recover: self.logger.info("Asking server to requeue all unacknowledged messages") self.channel.basic_recover(requeue=True) self.consumer_tag = self.channel.basic_consume(consumer_callback=consumer_callback, queue=self.queue_name, exclusive=exclusive) return self.consumer_tag
def consume(self, consumer_callback, exclusive=False, recover=False)
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 ...
2.858314
2.505186
1.140959
if key not in parsed_json: raise ValueError("JSON does not contain a {} field".format(key)) return parsed_json[key]
def json_get(parsed_json, key)
Retrieves the key from a parsed_json dictionary, or raises an exception if the key is not present
3.130045
3.286421
0.952418
md = open(os.path.join(os.path.dirname(__file__), fname)).read() output = md try: import pypandoc output = pypandoc.convert(md, 'rst', format='md') except ImportError: pass return output
def readme(fname)
Reads a markdown file and returns the contents formatted as rst
2.320534
2.436026
0.95259
logger = logging.getLogger(__name__) logger.debug("Expanding variables") home = os.path.expanduser("~") loc = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) logger.debug("Create empty config") config = ConfigObj() # Merge in config file in program dir if os.path.isfile(os.path.j...
def get_config(config_base, custom_file=None, configspec=None)
Loads a configuration file from multiple locations, and merge the results into one. This function will load configuration files from a number of locations in sequence, and will overwrite values in the previous level if they are redefined in the current. The levels are in sequence: 1. Distribution level configura...
1.859974
1.801748
1.032317
logger = logging.getLogger(__name__) logger.debug("Loading all files matching {0} in {1}".format(pattern, path)) files = Globber(path, include=[pattern], recursive=False).glob() files = sorted(files) config = ConfigObj() for filename in files: logger.debug("- Loading config for {0}".format(filename)) tr...
def get_config_dir(path, pattern="*.config", configspec=None, allow_errors=False)
Load an entire directory of configuration files, merging them into one. This function will load multiple configuration files matching the given pattern, in the given path, and merge them. The found files are first sorted alphabetically, and then loaded and merged. A good practice is to use ConfigObj sections, for e...
3.007114
2.958855
1.01631
self._cached = (pargs, kwargs) self._try_then()
def resolve(self, *pargs, **kwargs)
Resolve the promise.
22.429804
15.04547
1.490801
if self._cached is not None and self._callback is not None: self._callback(*self._cached[0], **self._cached[1])
def _try_then(self)
Check to see if self has been resolved yet, if so invoke then.
5.134582
4.091336
1.254989
results = [None] results_called = [False] def results_callback(val): results[0] = val results_called[0] = True self.then(results_callback) start = time.time() while not results_called[0]: if time.time() - start > timeout / 1...
def wait_for(self, timeout=3000)
Hault execution until self resolves.
3.383987
3.009711
1.124356
is_url = re.compile( r'^(?:http|ftp)s?://' # http:// or https:// r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain... r'localhost|' # localhost... r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip r'(?::\d+)?' # optional p...
def open(path_or_url)
Wrapper for opening an IO object to a local file or URL :param path_or_url: :return:
1.290406
1.309313
0.985559
primitive = (int, str, bool, float) return isinstance(thing, primitive)
def _is_primitive(thing)
Determine if the value is a primitive
7.097583
6.240308
1.137377
if isinstance(val, bool): return "choice" elif isinstance(val, int): return "number" elif isinstance(val, float): return "number" elif isinstance(val, str): return "text" elif hasattr(val, 'read'): return "file"...
def _guess_type(val)
Guess the input type of the parameter based off the default value, if unknown use text
2.157009
1.914015
1.126955
params = [] for p in sig.parameters: param = sig.parameters[p] optional = param.default != inspect.Signature.empty default = UIBuilder._safe_default(param.default) if param.default != inspect.Signature.empty else '' annotation = param.annotation i...
def _params(sig)
Read params, values and annotations from the signature
3.291379
3.206225
1.026559
func_name = func.__name__ # from foo.bar import func // func() # WARNING: May be broken in IPython, in which case the widget will use a fallback if func_name in globals(): return func_name # import foo.bar // foo.bar.func() module_name = func.__modu...
def _import(func)
Return the namespace path to the function
3.718865
3.654829
1.017521