Search is not available for this dataset
text
stringlengths
75
104k
def bisect(seq, func=bool): """ Split a sequence into two sequences: the first is elements that return False for func(element) and the second for True for func(element). By default, func is ``bool``, so uses the truth value of the object. >>> is_odd = lambda n: n%2 >>> even, odd = bisect(range(5), is_odd) >>>...
def grouper_nofill_str(n, iterable): """ Take a sequence and break it up into chunks of the specified size. The last chunk may be smaller than size. This works very similar to grouper_nofill, except it works with strings as well. >>> tuple(grouper_nofill_str(3, 'foobarbaz')) ('foo', 'bar', 'baz') You can sti...
def flatten(subject, test=None): """ *Deprecated*: Use more_itertools.collapse instead. """ warnings.warn( "Use more_itertools.collapse instead", DeprecationWarning, stacklevel=2) return list(more_itertools.collapse(subject, base_type=(bytes,)))
def every_other(iterable): """ Yield every other item from the iterable >>> ' '.join(every_other('abcdefg')) 'a c e g' """ items = iter(iterable) while True: try: yield next(items) next(items) except StopIteration: return
def remove_duplicates(iterable, key=None): """ Given an iterable with items that may come in as sequential duplicates, remove those duplicates. Unlike unique_justseen, this function does not remove triplicates. >>> ' '.join(remove_duplicates('abcaabbccaaabbbcccbcbc')) 'a b c a b c a a b b c c b c b c' >>> ' '....
def peek(iterable): """ Get the next value from an iterable, but also return an iterable that will subsequently return that value and the rest of the original iterable. >>> l = iter([1,2,3]) >>> val, l = peek(l) >>> val 1 >>> list(l) [1, 2, 3] """ peeker, original = itertools.tee(iterable) return next(pee...
def takewhile_peek(predicate, iterable): """ Like takewhile, but takes a peekable iterable and doesn't consume the non-matching item. >>> items = Peekable(range(10)) >>> is_small = lambda n: n < 4 >>> small_items = takewhile_peek(is_small, items) >>> list(small_items) [0, 1, 2, 3] >>> list(items) [4, 5, 6...
def nwise(iter, n): """ Like pairwise, except returns n-tuples of adjacent items. s -> (s0,s1,...,sn), (s1,s2,...,s(n+1)), ... """ iterset = [iter] while len(iterset) < n: iterset[-1:] = itertools.tee(iterset[-1]) next(iterset[-1], None) return six.moves.zip(*iterset)
def window(iter, pre_size=1, post_size=1): """ Given an iterable, return a new iterable which yields triples of (pre, item, post), where pre and post are the items preceeding and following the item (or None if no such item is appropriate). pre and post will always be pre_size and post_size in length. >>> example...
def partition_items(count, bin_size): """ Given the total number of items, determine the number of items that can be added to each bin with a limit on the bin size. So if you want to partition 11 items into groups of 3, you'll want three of three and one of two. >>> partition_items(11, 3) [3, 3, 3, 2] But if...
def balanced_rows(n, iterable, fillvalue=None): """ Like grouper, but balance the rows to minimize fill per row. balanced_rows(3, 'ABCDEFG', 'x') --> ABC DEx FGx" """ iterable, iterable_copy = itertools.tee(iterable) count = len(tuple(iterable_copy)) for allocation in partition_items(count, n): row = itertools...
def always_iterable(item): """ Given an object, always return an iterable. If the item is not already iterable, return a tuple containing only the item. If item is None, an empty iterable is returned. >>> always_iterable([1,2,3]) <list_iterator...> >>> always_iterable('foo') <tuple_iterator...> >>> always_ite...
def suppress_exceptions(callables, *exceptions): """ Call each callable in callables, suppressing any exceptions supplied. If no exception classes are supplied, all Exceptions will be suppressed. >>> import functools >>> c1 = functools.partial(int, 'a') >>> c2 = functools.partial(int, '10') >>> list(suppress_ex...
def duplicates(*iterables, **kwargs): """ Yield duplicate items from any number of sorted iterables of items >>> items_a = [1, 2, 3] >>> items_b = [0, 3, 4, 5, 6] >>> list(duplicates(items_a, items_b)) [(3, 3)] It won't behave as you expect if the iterables aren't ordered >>> items_b.append(1) >>> list(dupl...
def assert_ordered(iterable, key=lambda x: x, comp=operator.le): """ Assert that for all items in the iterable, they're in order based on comp >>> list(assert_ordered(range(5))) [0, 1, 2, 3, 4] >>> list(assert_ordered(range(5), comp=operator.ge)) Traceback (most recent call last): ... AssertionError: 0 < 1 >>...
def collate_revs(old, new, key=lambda x: x, merge=lambda old, new: new): """ Given revision sets old and new, each containing a series of revisions of some set of objects, collate them based on these rules: - all items from each set are yielded in stable order - items in old are yielded first - items in new are...
def _mutable_iter(dict): """ Iterate over items in the dict, yielding the first one, but allowing it to be mutated during the process. >>> d = dict(a=1) >>> it = _mutable_iter(d) >>> next(it) ('a', 1) >>> d {} >>> d.update(b=2) >>> list(it) [('b', 2)] """ while dict: prev_key = next(iter(dict)) yield ...
def _swap_on_miss(partition_result): """ Given a partition_dict result, if the partition missed, swap the before and after. """ before, item, after = partition_result return (before, item, after) if item else (after, item, before)
def partition_dict(items, key): """ Given an ordered dictionary of items and a key in that dict, return an ordered dict of items before, the keyed item, and an ordered dict of items after. >>> od = collections.OrderedDict(zip(range(5), 'abcde')) >>> before, item, after = partition_dict(od, 3) >>> before Ordere...
def get_first_n_queues(self, n): """ Run through the sequence until n queues are created and return them. If fewer are created, return those plus empty iterables to compensate. """ try: while len(self.queues) < n: self.__fetch__() except StopIteration: pass values = list(self.queues.values()) ...
def reset(self): """ Resets the iterator to the start. Any remaining values in the current iteration are discarded. """ self.__iterator, self.__saved = itertools.tee(self.__saved)
def parse_as_var(parser, token): """ Parse the remainder of the token, to find a "as varname" statement. :param parser: The "parser" object that ``@register.tag`` provides. :type parser: :class:`~django.template.Parser` :param token: The "token" object that ``@register.tag`` provides. :type tok...
def parse_token_kwargs(parser, token, allowed_kwargs=None, compile_args=True, compile_kwargs=True): """ Allow the template tag arguments to be like a normal Python function, with *args and **kwargs. :param parser: The "parser" object that ``@register.tag`` provides. :type parser: :class:`~django.templa...
def template_tag(library, name): """ Decorator to register class tags :param library: The template tag library, typically instantiated as ``register = Library()``. :type library: :class:`~django.template.Library` :param name: The name of the template tag :type name: str Example: .. co...
def descendant(self, chain_path): """ A descendant is a child many steps down. """ public_child = self.hdkeychain chain_step_bytes = 4 max_bits_per_step = 2**31 chain_steps = [ int(chain_path[i:i+chain_step_bytes*2], 16) % max_bits_per_step for i i...
def bip32_serialize(rawtuple): """ Derived from code from pybitcointools (https://github.com/vbuterin/pybitcointools) by Vitalik Buterin """ vbytes, depth, fingerprint, i, chaincode, key = rawtuple i = encode(i, 256, 4) chaincode = encode(hash_to_int(chaincode), 256, 32) keydata = b'\x00...
def bip32_deserialize(data): """ Derived from code from pybitcointools (https://github.com/vbuterin/pybitcointools) by Vitalik Buterin """ dbin = changebase(data, 58, 256) if bin_dbl_sha256(dbin[:-4])[:4] != dbin[-4:]: raise Exception("Invalid checksum") vbytes = dbin[0:4] depth ...
def fetch_table_names(self, include_system_table=False): """ :return: List of table names in the database. :rtype: list """ result = self.__cur.execute("SELECT name FROM sqlite_master WHERE TYPE='table'") if result is None: return [] table_names = [r...
def fetch_sqlite_master(self): """ Get sqlite_master table information as a list of dictionaries. :return: sqlite_master table information. :rtype: list :Sample Code: .. code:: python from sqliteschema import SQLiteSchemaExtractor p...
def object_iter(obj, parent=None, parent_key=None, idx=None, siblings=None): """Yields each node of object graph in postorder.""" obj_node = Node(value=obj, parent=parent, parent_key=parent_key, siblings=siblings, idx=idx) if isinstance(obj, list): _siblings = len(o...
def select(selector, obj): """Appy selector to obj and return matching nodes. If only one node is found, return it, otherwise return a list of matches. Returns False on syntax error. None if no results found. """ parser = Parser(obj) try: return parser.parse(selector) except Select...
def parse(self, selector): """Accept a list of tokens. Returns matched nodes of self.obj.""" log.debug(self.obj) tokens = lex(selector) if self.peek(tokens, 'operator') == '*': self.match(tokens, 'operator') results = list(object_iter(self.obj)) else: ...
def selector_production(self, tokens): """Production for a full selector.""" validators = [] # the following productions should return predicate functions. if self.peek(tokens, 'type'): type_ = self.match(tokens, 'type') validators.append(self.type_production(ty...
def parents(self, lhs, rhs): """Find nodes in rhs which have parents in lhs.""" return [node for node in rhs if node.parent in lhs]
def ancestors(self, lhs, rhs): """Return nodes from rhs which have ancestors in lhs.""" def _search(node): if node in lhs: return True if not node.parent: return False return _search(node.parent) return [node for node in rhs i...
def siblings(self, lhs, rhs): """Find nodes in rhs having common parents in lhs.""" parents = [node.parent for node in lhs] return [node for node in rhs if node.parent in parents]
def nth_child_production(self, lexeme, tokens): """Parse args and pass them to pclass_func_validator.""" args = self.match(tokens, 'expr') pat = self.nth_child_pat.match(args) if pat.group(5): a = 2 b = 1 if pat.group(5) == 'odd' else 0 elif pat.group(6...
def _match_nodes(self, validators, obj): """Apply each validator in validators to each node in obj. Return each node in obj which matches all validators. """ results = [] for node in object_iter(obj): if all([validate(node) for validate in validators]): ...
def ping(dst, count, inter=0.2, maxwait=1000, size=64): """Sends ICMP echo requests to destination `dst` `count` times. Returns a deferred which fires when responses are finished. """ def _then(result, p): p.stopListening() return result d = defer.Deferred() p = ICMPPort(0, ICMP...
def getBody(self, url, method='GET', headers={}, data=None, socket=None): """Make an HTTP request and return the body """ if not 'User-Agent' in headers: headers['User-Agent'] = ['Tensor HTTP checker'] return self.request(url, method, headers, data, socket)
def expire(self, age): """Expire any items in the cache older than `age` seconds""" now = time.time() cache = self._acquire_cache() expired = [k for k, v in cache.items() if (now - v[0]) > age] for k in expired: if k in cache: del cache[k] ...
def set(self, k, v): """Set a key `k` to value `v`""" self.store[k] = (time.time(), v) self._persist()
def get(self, k): """Returns key contents, and modify time""" if self._changed(): self._read() if k in self.store: return tuple(self.store[k]) else: return None
def contains(self, k): """Return True if key `k` exists""" if self._changed(): self._read() return k in self.store.keys()
def chain_check(cls, timestamp: int) -> bool: """ Given a record timestamp, verify the chain integrity. :param timestamp: UNIX time / POSIX time / Epoch time :return: 'True' if the timestamp fits the chain. 'False' otherwise. """ # Creation is messy. # You want ...
def get_first_record( cls, download: bool=True ) -> NistBeaconValue: """ Get the first (oldest) record available. Since the first record IS a known value in the system we can load it from constants. :param download: 'True' will always reach out to NIST to get...
def from_json(cls, input_json: str) -> 'NistBeaconValue': """ Convert a string of JSON which represents a NIST randomness beacon value into a 'NistBeaconValue' object. :param input_json: JSON to build a 'Nist RandomnessBeaconValue' from :return: A 'NistBeaconValue' object, 'None...
def from_xml(cls, input_xml: str) -> 'NistBeaconValue': """ Convert a string of XML which represents a NIST Randomness Beacon value into a 'NistBeaconValue' object. :param input_xml: XML to build a 'NistBeaconValue' from :return: A 'NistBeaconValue' object, 'None' otherwise ...
def rendered_content(self): """Returns a 'minified' version of the javascript content""" template = self.resolve_template(self.template_name) if django.VERSION[1] < 8: if template.name.endswith('.min'): return super(MinifiedJsTemplateResponse, self).rendered_content ...
def get_fn(self, fn, max_lines=None): """Passes each parsed log line to `fn` This is a better idea than storing a giant log file in memory """ stat = os.stat(self.logfile) if (stat.st_ino == self.lastInode) and (stat.st_size == self.lastSize): # Nothing new ...
def get(self, max_lines=None): """Returns a big list of all log lines since the last run """ rows = [] self.get_fn(lambda row: rows.append(row), max_lines=max_lines) return rows
def create_token(self, obj_id, extra_data): """Create a token referencing the object id with extra data. Note random data is added to ensure that no two tokens are identical. """ return self.dumps( dict( id=obj_id, data=extra_data, ...
def validate_token(self, token, expected_data=None): """Validate secret link token. :param token: Token value. :param expected_data: A dictionary of key/values that must be present in the data part of the token (i.e. included via ``extra_data`` in ``create_token``). ...
def load_token(self, token, force=False): """Load data in a token. :param token: Token to load. :param force: Load token data even if signature expired. Default: False. """ try: data = self.loads(token) except SignatureExpired as e: ...
def engine(self): """Get cryptographic engine.""" if not hasattr(self, '_engine'): from cryptography.fernet import Fernet from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes digest = hashes.Hash(hashe...
def create_token(self, obj_id, extra_data): """Create a token referencing the object id with extra data.""" return self.engine.encrypt( super(EncryptedTokenMixIn, self).create_token(obj_id, extra_data) )
def load_token(self, token, force=False): """Load data in a token. :param token: Token to load. :param force: Load token data even if signature expired. Default: False. """ return super(EncryptedTokenMixIn, self).load_token( self.engine.decrypt(...
def compat_validate_token(cls, *args, **kwargs): """Multiple algorithm-compatible token validation.""" data = None for algorithm in SUPPORTED_DIGEST_ALGORITHMS: data = cls(algorithm_name=algorithm).validate_token( *args, **kwargs) if not data: # move to n...
def create_token(cls, obj_id, data, expires_at=None): """Create the secret link token.""" if expires_at: s = TimedSecretLinkSerializer(expires_at=expires_at) else: s = SecretLinkSerializer() return s.create_token(obj_id, data)
def validate_token(cls, token, expected_data=None): """Validate a secret link token (non-expiring + expiring).""" for algorithm in SUPPORTED_DIGEST_ALGORITHMS: s = SecretLinkSerializer(algorithm_name=algorithm) st = TimedSecretLinkSerializer(algorithm_name=algorithm) ...
def load_token(cls, token, force=False): """Validate a secret link token (non-expiring + expiring).""" for algorithm in SUPPORTED_DIGEST_ALGORITHMS: s = SecretLinkSerializer(algorithm_name=algorithm) st = TimedSecretLinkSerializer(algorithm_name=algorithm) for seriali...
def Counter32(a, b, delta): """32bit counter aggregator with wrapping """ if b < a: c = 4294967295 - a return (c + b) / float(delta) return (b - a) / float(delta)
def Counter64(a, b, delta): """64bit counter aggregator with wrapping """ if b < a: c = 18446744073709551615 - a return (c + b) / float(delta) return (b - a) / float(delta)
def Counter(a, b, delta): """Counter derivative """ if b < a: return None return (b - a) / float(delta)
def average_duration(total_duration, visits): """ Method to calculate and format an average duration safely """ if not visits: seconds = 0 else: seconds = int(round(total_duration / Decimal(visits))) duration = timedelta(seconds=seconds) return str(duration)
def setupOutputs(self, config): """Setup output processors""" if self.proto == 'tcp': defaultOutput = { 'output': 'tensor.outputs.riemann.RiemannTCP', 'server': self.server, 'port': self.port } else: defaultOutp...
def setupSources(self, config): """Sets up source objects from the given config""" sources = config.get('sources', []) for source in sources: src = self.createSource(source) self.setupTriggers(source, src) self.sources.append(src)
def sendEvent(self, source, events): """Callback that all event sources call when they have a new event or list of events """ if isinstance(events, list): self.eventCounter += len(events) else: self.eventCounter += 1 events = [events] ...
def sourceWatchdog(self): """Watchdog timer function. Recreates sources which have not generated events in 10*interval if they have watchdog set to true in their configuration """ for i, source in enumerate(self.sources): if not source.config.get('watchdog', False):...
def _parse_format(self, format): """ Converts the input format to a regular expression, as well as extracting fields Raises an exception if it couldn't compile the generated regex. """ format = format.strip() format = re.sub('[ \t]+',' ',format) ...
def parse(self, line): """ Parses a single line from the log file and returns a dictionary of it's contents. Raises and exception if it couldn't parse the line """ line = line.strip() match = self._regex.match(line) if match: data = {...
def validate_expires_at(form, field): """Validate that date is in the future.""" if form.accept.data: if not field.data or datetime.utcnow().date() >= field.data: raise validators.StopValidation(_( "Please provide a future date." )) if not field.data or \ ...
def validate_accept(form, field): """Validate that accept have not been set.""" if field.data and form.reject.data: raise validators.ValidationError( _("Both reject and accept cannot be set at the same time.") )
def validate_reject(form, field): """Validate that accept have not been set.""" if field.data and form.accept.data: raise validators.ValidationError( _("Both reject and accept cannot be set at the same time.") )
def validate_message(form, field): """Validate message.""" if form.reject.data and not field.data.strip(): raise validators.ValidationError( _("You are required to provide message to the requester when" " you reject a request.") )
def verify_token(): """Verify token and save in session if it's valid.""" try: from .models import SecretLink token = request.args['token'] # if the token is valid if token and SecretLink.validate_token(token, {}): # then save in session the token session[...
def init_app(self, app): """Flask application initialization.""" app.before_request(verify_token) self.init_config(app) state = _AppState(app=app) app.extensions['zenodo-accessrequests'] = state
def name(self): """ Return a basic meaningful name based on device type """ if ( self.device_type and self.device_type.code in (DeviceType.MOBILE, DeviceType.TABLET) ): return self.device else: return self.browser
def _warn_node(self, msg, *args, **kwargs): """Do not warn on external images.""" if not msg.startswith('nonlocal image URI found:'): _warn_node_old(self, msg, *args, **kwargs)
def connect_receivers(): """Connect receivers to signals.""" request_created.connect(send_email_validation) request_confirmed.connect(send_confirmed_notifications) request_rejected.connect(send_reject_notification) # Order is important: request_accepted.connect(create_secret_link) request_ac...
def create_secret_link(request, message=None, expires_at=None): """Receiver for request-accepted signal.""" pid, record = get_record(request.recid) if not record: raise RecordNotFound(request.recid) description = render_template( "zenodo_accessrequests/link_description.tpl", req...
def send_accept_notification(request, message=None, expires_at=None): """Receiver for request-accepted signal to send email notification.""" pid, record = get_record(request.recid) _send_notification( request.sender_email, _("Access request accepted"), "zenodo_accessrequests/emails/a...
def send_confirmed_notifications(request): """Receiver for request-confirmed signal to send email notification.""" pid, record = get_record(request.recid) if record is None: current_app.logger.error("Cannot retrieve record %s. Emails not sent" % request.recid) ...
def send_email_validation(request): """Receiver for request-created signal to send email notification.""" token = EmailConfirmationSerializer().create_token( request.id, dict(email=request.sender_email) ) pid, record = get_record(request.recid) _send_notification( request.sender_ema...
def send_reject_notification(request, message=None): """Receiver for request-rejected signal to send email notification.""" pid, record = get_record(request.recid) _send_notification( request.sender_email, _("Access request rejected"), "zenodo_accessrequests/emails/rejected.tpl", ...
def _send_notification(to, subject, template, **ctx): """Render a template and send as email.""" msg = Message( subject, sender=current_app.config.get('SUPPORT_EMAIL'), recipients=[to] ) msg.body = render_template(template, **ctx) send_email.delay(msg.__dict__)
def create(cls, title, owner, extra_data, description="", expires_at=None): """Create a new secret link.""" if isinstance(expires_at, date): expires_at = datetime.combine(expires_at, datetime.min.time()) with db.session.begin_nested(): obj = cls( owner=ow...
def validate_token(cls, token, expected_data): """Validate a secret link token. Only queries the database if token is valid to determine that the token has not been revoked. """ data = SecretLinkFactory.validate_token( token, expected_data=expected_data ) ...
def extra_data(self): """Load token data stored in token (ignores expiry date of tokens).""" if self.token: return SecretLinkFactory.load_token(self.token, force=True)["data"] return None
def get_absolute_url(self, endpoint): """Get absolute for secret link (using https scheme). The endpoint is passed to ``url_for`` with ``token`` and ``extra_data`` as keyword arguments. E.g.:: >>> link.extra_data dict(recid=1) >>> link.get_absolute_url('reco...
def revoke(self): """Revoken a secret link.""" if self.revoked_at is None: with db.session.begin_nested(): self.revoked_at = datetime.utcnow() link_revoked.send(self) return True return False
def create(cls, recid=None, receiver=None, sender_full_name=None, sender_email=None, justification=None, sender=None): """Create a new access request. :param recid: Record id (required). :param receiver: User object of receiver (required). :param sender_full_name: Full na...
def get_by_receiver(cls, request_id, user): """Get access request for a specific receiver.""" return cls.query.filter_by( id=request_id, receiver_user_id=user.id ).first()
def confirm_email(self): """Confirm that senders email is valid.""" with db.session.begin_nested(): if self.status != RequestStatus.EMAIL_VALIDATION: raise InvalidRequestStateError(RequestStatus.EMAIL_VALIDATION) self.status = RequestStatus.PENDING reques...
def accept(self, message=None, expires_at=None): """Accept request.""" with db.session.begin_nested(): if self.status != RequestStatus.PENDING: raise InvalidRequestStateError(RequestStatus.PENDING) self.status = RequestStatus.ACCEPTED request_accepted.send...
def reject(self, message=None): """Reject request.""" with db.session.begin_nested(): if self.status != RequestStatus.PENDING: raise InvalidRequestStateError(RequestStatus.PENDING) self.status = RequestStatus.REJECTED request_rejected.send(self, message=me...
def create_secret_link(self, title, description=None, expires_at=None): """Create a secret link from request.""" self.link = SecretLink.create( title, self.receiver, extra_data=dict(recid=self.recid), description=description, expires_at=expires...
def get_hash( cls, version: str, frequency: int, timestamp: int, seed_value: str, prev_output: str, status_code: str, ) -> SHA512Hash: """ Given required properties from a NistBeaconValue, compute the SHA512H...
def verify( cls, timestamp: int, message_hash: SHA512Hash, signature: bytes, ) -> bool: """ Verify a given NIST message hash and signature for a beacon value. :param timestamp: The timestamp of the record being verified. :param message...
def is_embargoed(record): """Template filter to check if a record is embargoed.""" return record.get('access_right') == 'embargoed' and \ record.get('embargo_date') and \ record.get('embargo_date') > datetime.utcnow().date()