Search is not available for this dataset
text
stringlengths
75
104k
def delete_roles_request(request): """Submission to remove a role acceptance request.""" uuid_ = request.matchdict['uuid'] posted_roles = request.json with db_connect() as db_conn: with db_conn.cursor() as cursor: remove_role_requests(cursor, uuid_, posted_roles) resp = request...
def get_acl(request): """Returns the ACL for the given content identified by ``uuid``.""" uuid_ = request.matchdict['uuid'] with db_connect() as db_conn: with db_conn.cursor() as cursor: cursor.execute("""\ SELECT TRUE FROM document_controls WHERE uuid = %s""", (uuid_,)) try...
def post_acl_request(request): """Submission to create an ACL.""" uuid_ = request.matchdict['uuid'] posted = request.json permissions = [(x['uid'], x['permission'],) for x in posted] with db_connect() as db_conn: with db_conn.cursor() as cursor: cursor.execute("""\ SELECT TRUE F...
def delete_acl_request(request): """Submission to remove an ACL.""" uuid_ = request.matchdict['uuid'] posted = request.json permissions = [(x['uid'], x['permission'],) for x in posted] with db_connect() as db_conn: with db_conn.cursor() as cursor: remove_acl(cursor, uuid_, permi...
def processor(): # pragma: no cover """Churns over PostgreSQL notifications on configured channels. This requires the application be setup and the registry be available. This function uses the database connection string and a list of pre configured channels. """ registry = get_current_registry...
def lookup_api_key_info(): """Given a dbapi cursor, lookup all the api keys and their information.""" info = {} with db_connect() as conn: with conn.cursor() as cursor: cursor.execute(ALL_KEY_INFO_SQL_STMT) for row in cursor.fetchall(): id, key, name, groups =...
def includeme(config): """Configuration include fuction for this module""" api_key_authn_policy = APIKeyAuthenticationPolicy() config.include('openstax_accounts') openstax_authn_policy = config.registry.getUtility( IOpenstaxAccountsAuthenticationPolicy) # Set up api & user authentication po...
def expandvars_dict(settings): """Expands all environment variables in a settings dictionary.""" return dict( (key, os.path.expandvars(value)) for key, value in settings.iteritems() )
def initialize_sentry_integration(): # pragma: no cover """\ Used to optionally initialize the Sentry service with this app. See https://docs.sentry.io/platforms/python/pyramid/ """ # This function is not under coverage because it is boilerplate # from the Sentry documentation. try: ...
def task(**kwargs): """A function task decorator used in place of ``@celery_app.task``.""" def wrapper(wrapped): def callback(scanner, name, obj): celery_app = scanner.config.registry.celery_app celery_app.task(**kwargs)(obj) venusian.attach(wrapped, callback) ...
def _make_celery_app(config): """This exposes the celery app. The app is actually created as part of the configuration. However, this does make the celery app functional as a stand-alone celery application. This puts the pyramid configuration object on the celery app to be used for making the regis...
def post_publication_processing(event, cursor): """Process post-publication events coming out of the database.""" module_ident, ident_hash = event.module_ident, event.ident_hash celery_app = get_current_registry().celery_app # Check baking is not already queued. cursor.execute('SELECT result_id::t...
def parse_archive_uri(uri): """Given an archive URI, parse to a split ident-hash.""" parsed = urlparse(uri) path = parsed.path.rstrip('/').split('/') ident_hash = path[-1] ident_hash = unquote(ident_hash) return ident_hash
def declare_api_routes(config): """Declaration of routing""" add_route = config.add_route add_route('get-content', '/contents/{ident_hash}') add_route('get-resource', '/resources/{hash}') # User actions API add_route('license-request', '/contents/{uuid}/licensors') add_route('roles-request'...
def declare_browsable_routes(config): """Declaration of routes that can be browsed by users.""" # This makes our routes slashed, which is good browser behavior. config.add_notfound_view(default_exceptionresponse_view, append_slash=True) add_route = config.add_route add_...
def includeme(config): """Declare all routes.""" config.include('pyramid_jinja2') config.add_jinja2_renderer('.html') config.add_jinja2_renderer('.rss') config.add_static_view(name='/a/static', path="cnxpublishing:static/") # Commit the configuration otherwise the jija2_env won't have # a `...
def _formatter_callback_factory(): # pragma: no cover """Returns a list of includes to be given to `cnxepub.collation.collate`. """ includes = [] exercise_url_template = '{baseUrl}/api/exercises?q={field}:"{{itemCode}}"' settings = get_current_registry().settings exercise_base_url = settings.g...
def bake(binder, recipe_id, publisher, message, cursor): """Given a `Binder` as `binder`, bake the contents and persist those changes alongside the published content. """ recipe = _get_recipe(recipe_id, cursor) includes = _formatter_callback_factory() binder = collate_models(binder, ruleset=rec...
def volcano(differential_dfs, title='Axial Volcano Plot', scripts_mode="CDN", data_mode="directory", organism="human", q_value_column_name="q", log2FC_column_name="logFC", output_dir=".", filename="volcano.html", version=this_version): """ Arguments: differential_dfs (dict or pan...
def heatmap(genes_by_samples_matrix, sample_attributes, title='Axial Heatmap', scripts_mode="CDN", data_mode="directory", organism="human", separate_zscore_by=["system"], output_dir=".", filename="heatmap.html", version=this_version): """ Arguments: genes_by_samples_matrix (panda...
def graph(networkx_graph, title='Axial Graph Visualization', scripts_mode="CDN", data_mode="directory", output_dir=".", filename="graph.html", version=this_version): """ Arguments: networkx_graph (networkx.Graph): any instance of networkx.Graph title (str): The title of the plot (to be...
def db_connect(connection_string=None, **kwargs): """Function to supply a database connection object.""" if connection_string is None: connection_string = get_current_registry().settings[CONNECTION_STRING] db_conn = psycopg2.connect(connection_string, **kwargs) try: with db_conn: ...
def with_db_cursor(func): """Decorator that supplies a cursor to the function. This passes in a psycopg2 Cursor as the argument 'cursor'. It also accepts a cursor if one is given. """ @functools.wraps(func) def wrapped(*args, **kwargs): if 'cursor' in kwargs or func.func_code.co_argcoun...
def _role_type_to_db_type(type_): """Translates a role type (a value found in ``cnxepub.ATTRIBUTED_ROLE_KEYS``) to a database compatible value for ``role_types``. """ with db_connect() as db_conn: with db_conn.cursor() as cursor: cursor.execute("""\ WITH unnested_role_types AS ( ...
def _dissect_roles(metadata): """Given a model's ``metadata``, iterate over the roles. Return values are the role identifier and role type as a tuple. """ for role_key in cnxepub.ATTRIBUTED_ROLE_KEYS: for user in metadata.get(role_key, []): if user['type'] != 'cnx-id': ...
def upsert_pending_licensors(cursor, document_id): """Update or insert records for pending license acceptors.""" cursor.execute("""\ SELECT "uuid", "metadata" FROM pending_documents WHERE id = %s""", (document_id,)) uuid_, metadata = cursor.fetchone() acceptors = set([uid for uid, type_ in _dissect_role...
def upsert_pending_roles(cursor, document_id): """Update or insert records for pending document role acceptance.""" cursor.execute("""\ SELECT "uuid", "metadata" FROM pending_documents WHERE id = %s""", (document_id,)) uuid_, metadata = cursor.fetchone() acceptors = set([(uid, _role_type_to_db_type(typ...
def obtain_licenses(): """Obtain the licenses in a dictionary form, keyed by url.""" with db_connect() as db_conn: with db_conn.cursor() as cursor: cursor.execute("""\ SELECT combined_row.url, row_to_json(combined_row) FROM ( SELECT "code", "version", "name", "url", "is_valid_for_publicati...
def _validate_license(model): """Given the model, check the license is one valid for publication.""" license_mapping = obtain_licenses() try: license_url = model.metadata['license_url'] except KeyError: raise exceptions.MissingRequiredMetadata('license_url') try: license = li...
def _validate_roles(model): """Given the model, check that all the metadata role values have valid information in them and any required metadata fields contain values. """ required_roles = (ATTRIBUTED_ROLE_KEYS[0], ATTRIBUTED_ROLE_KEYS[4],) for role_key in ATTRIBUTED_ROLE_KEYS: try: ...
def _validate_derived_from(cursor, model): """Given a database cursor and model, check the derived-from value accurately points to content in the archive. The value can be nothing or must point to existing content. """ derived_from_uri = model.metadata.get('derived_from_uri') if derived_from_uri...
def _validate_subjects(cursor, model): """Give a database cursor and model, check the subjects against the subject vocabulary. """ subject_vocab = [term[0] for term in acquire_subject_vocabulary(cursor)] subjects = model.metadata.get('subjects', []) invalid_subjects = [s for s in subjects if s n...
def validate_model(cursor, model): """Validates the model using a series of checks on bits of the data.""" # Check the license is one valid for publication. _validate_license(model) _validate_roles(model) # Other required metadata includes: title, summary required_metadata = ('title', 'summary'...
def is_publication_permissible(cursor, publication_id, uuid_): """Check the given publisher of this publication given by ``publication_id`` is allowed to publish the content given by ``uuid``. """ # Check the publishing user has permission to publish cursor.execute("""\ SELECT 't'::boolean FROM ...
def add_pending_model(cursor, publication_id, model): """Adds a model (binder or document) that is awaiting publication to the database. """ # FIXME Too much happening here... assert isinstance(model, (cnxepub.Document, cnxepub.Binder,)), type(model) uri = model.get_uri('cnx-archive') if ur...
def lookup_document_pointer(ident_hash, cursor): """Lookup a document by id and version.""" id, version = split_ident_hash(ident_hash, split_version=True) stmt = "SELECT name FROM modules WHERE uuid = %s" args = [id] if version and version[0] is not None: operator = version[1] is None and 'i...
def add_pending_model_content(cursor, publication_id, model): """Updates the pending model's content. This is a secondary step not in ``add_pending_model, because content reference resolution requires the identifiers as they will appear in the end publication. """ cursor.execute("""\ SEL...
def set_publication_failure(cursor, exc): """Given a publication exception, set the publication as failed and append the failure message to the publication record. """ publication_id = exc.publication_id if publication_id is None: raise ValueError("Exception must have a ``publication_id`` va...
def add_publication(cursor, epub, epub_file, is_pre_publication=False): """Adds a publication entry and makes each item a pending document. """ publisher = epub[0].metadata['publisher'] publish_message = epub[0].metadata['publication_message'] epub_binary = psycopg2.Binary(epub_file.read()) ...
def _check_pending_document_license_state(cursor, document_id): """Check the aggregate state on the pending document.""" cursor.execute("""\ SELECT BOOL_AND(accepted IS TRUE) FROM pending_documents AS pd, license_acceptances AS la WHERE pd.id = %s AND pd.uuid = la.uuid""", (document...
def _check_pending_document_role_state(cursor, document_id): """Check the aggregate state on the pending document.""" cursor.execute("""\ SELECT BOOL_AND(accepted IS TRUE) FROM role_acceptances AS ra, pending_documents as pd WHERE pd.id = %s AND pd.uuid = ra.uuid""", (document_id,))...
def _update_pending_document_state(cursor, document_id, is_license_accepted, are_roles_accepted): """Update the state of the document's state values.""" args = (bool(is_license_accepted), bool(are_roles_accepted), document_id,) cursor.execute("""\ UPDATE pendin...
def is_revision_publication(publication_id, cursor): """Checks to see if the publication contains any revised models. Revised in this context means that it is a new version of an existing piece of content. """ cursor.execute("""\ SELECT 't'::boolean FROM modules WHERE uuid IN (SELECT uuid ...
def poke_publication_state(publication_id, cursor): """Invoked to poke at the publication to update and acquire its current state. This is used to persist the publication to archive. """ cursor.execute("""\ SELECT "state", "state_messages", "is_pre_publication", "publisher" FROM publications WHERE id = ...
def check_publication_state(publication_id): """Check the publication's current state.""" with db_connect() as db_conn: with db_conn.cursor() as cursor: cursor.execute("""\ SELECT "state", "state_messages" FROM publications WHERE id = %s""", (publication_id,)) publication_state, ...
def _node_to_model(tree_or_item, metadata=None, parent=None, lucent_id=cnxepub.TRANSLUCENT_BINDER_ID): """Given a tree, parse to a set of models""" if 'contents' in tree_or_item: # It is a binder. tree = tree_or_item binder = cnxepub.TranslucentBinder(metadata=tree) ...
def _reassemble_binder(id, tree, metadata): """Reassemble a Binder object coming out of the database.""" binder = cnxepub.Binder(id, metadata=metadata) for item in tree['contents']: node = _node_to_model(item, parent=binder) if node.metadata['title'] != item['title']: binder.set_...
def publish_pending(cursor, publication_id): """Given a publication id as ``publication_id``, write the documents to the *Connexions Archive*. """ cursor.execute("""\ WITH state_update AS ( UPDATE publications SET state = 'Publishing' WHERE id = %s ) SELECT publisher, publication_message FROM publicat...
def accept_publication_license(cursor, publication_id, user_id, document_ids, is_accepted=False): """Accept or deny the document license for the publication (``publication_id``) and user (at ``user_id``) for the documents (listed by id as ``document_ids``). """ cursor...
def accept_publication_role(cursor, publication_id, user_id, document_ids, is_accepted=False): """Accept or deny the document role attribution for the publication (``publication_id``) and user (at ``user_id``) for the documents (listed by id as ``document_ids``). """ cur...
def upsert_license_requests(cursor, uuid_, roles): """Given a ``uuid`` and list of ``roles`` (user identifiers) create a license acceptance entry. If ``has_accepted`` is supplied, it will be used to assign an acceptance value to all listed ``uids``. """ if not isinstance(roles, (list, set, tuple,)):...
def remove_license_requests(cursor, uuid_, uids): """Given a ``uuid`` and list of ``uids`` (user identifiers) remove the identified users' license acceptance entries. """ if not isinstance(uids, (list, set, tuple,)): raise TypeError("``uids`` is an invalid type: {}".format(type(uids))) acce...
def upsert_role_requests(cursor, uuid_, roles): """Given a ``uuid`` and list of dicts containing the ``uid`` and ``role`` for creating a role acceptance entry. The ``roles`` dict can optionally contain a ``has_accepted`` value, which will default to true. """ if not isinstance(roles, (list, set,...
def remove_role_requests(cursor, uuid_, roles): """Given a ``uuid`` and list of dicts containing the ``uid`` (user identifiers) and ``role`` for removal of the identified users' role acceptance entries. """ if not isinstance(roles, (list, set, tuple,)): raise TypeError("``roles`` is an inval...
def upsert_acl(cursor, uuid_, permissions): """Given a ``uuid`` and a set of permissions given as a tuple of ``uid`` and ``permission``, upsert them into the database. """ if not isinstance(permissions, (list, set, tuple,)): raise TypeError("``permissions`` is an invalid type: {}" ...
def remove_acl(cursor, uuid_, permissions): """Given a ``uuid`` and a set of permissions given as a tuple of ``uid`` and ``permission``, remove these entries from the database. """ if not isinstance(permissions, (list, set, tuple,)): raise TypeError("``permissions`` is an invalid type: {}" ...
def _upsert_persons(cursor, person_ids, lookup_func): """Upsert's user info into the database. The model contains the user info as part of the role values. """ person_ids = list(set(person_ids)) # cleanse data # Check for existing records to update. cursor.execute("SELECT personid from persons...
def _upsert_users(cursor, user_ids, lookup_func): """Upsert's user info into the database. The model contains the user info as part of the role values. """ user_ids = list(set(user_ids)) # cleanse data # Check for existing records to update. cursor.execute("SELECT username from users where use...
def upsert_users(cursor, user_ids): """Given a set of user identifiers (``user_ids``), upsert them into the database after checking accounts for the latest information. """ accounts = get_current_registry().getUtility(IOpenstaxAccounts) def lookup_profile(username): profile = accounts.g...
def notify_users(cursor, document_id): """Notify all users about their role and/or license acceptance for a piece of content associated with the given ``document_id``. """ return registry = get_current_registry() accounts = registry.getUtility(IOpenstaxAccounts) cursor.execute("""\ SELECT l...
def set_post_publications_state(cursor, module_ident, state_name, state_message=''): # pragma: no cover """This sets the post-publication state in the database.""" cursor.execute("""\ INSERT INTO post_publications (module_ident, state, state_message) VALUES (%s, %s, %s)""", ...
def update_module_state(cursor, module_ident, state_name, recipe): # pragma: no cover """This updates the module's state in the database.""" cursor.execute("""\ UPDATE modules SET stateid = ( SELECT stateid FROM modulestates WHERE statename = %s ), recipe = %s, baked = now() WHERE m...
def get_moderation(request): """Return the list of publications that need moderation.""" with db_connect() as db_conn: with db_conn.cursor() as cursor: cursor.execute("""\ SELECT row_to_json(combined_rows) FROM ( SELECT id, created, publisher, publication_message, (select array_ag...
def includeme(config): """Configures the session manager""" settings = config.registry.settings session_factory = SignedCookieSessionFactory(settings['session_key']) config.set_session_factory(session_factory)
def admin_print_styles(request): """ Returns a dictionary of all unique print_styles, and their latest tag, revision, and recipe_type. """ styles = [] # This fetches all recipes that have been used to successfully bake a # current book plus all default recipes that have not yet been used ...
def admin_print_styles_single(request): """ Returns all books with any version of the given print style. Returns the print_style, recipe type, num books using the print_style, along with a dictionary of the book, author, revision date, recipe, tag of the print_style, and a link to the content. """ ...
def get_api_keys(request): """Return the list of API keys.""" with db_connect() as db_conn: with db_conn.cursor() as cursor: cursor.execute("""\ SELECT row_to_json(combined_rows) FROM ( SELECT id, key, name, groups FROM api_keys ) AS combined_rows""") api_keys = [x[0] for x in ...
def get_baking_statuses_sql(get_request): """ Creates SQL to get info on baking books filtered from GET request. All books that have ever attempted to bake will be retured if they pass the filters in the GET request. If a single book has been requested to bake multiple times there will be a row for...
def admin_content_status(request): """ Returns a dictionary with the states and info of baking books, and the filters from the GET request to pre-populate the form. """ statement, sql_args = get_baking_statuses_sql(request.GET) states = [] status_filters = request.params.getall('status_filt...
def admin_content_status_single(request): """ Returns a dictionary with all the past baking statuses of a single book. """ uuid = request.matchdict['uuid'] try: UUID(uuid) except ValueError: raise httpexceptions.HTTPBadRequest( '{} is not a valid uuid'.format(uuid)) ...
def admin_content_status_single_POST(request): """ Retriggers baking for a given book. """ args = admin_content_status_single(request) title = args['title'] if args['current_state'] == 'SUCCESS': args['response'] = title + ' is not stale, no need to bake' return args with db_connect...
def _insert_optional_roles(cursor, model, ident): """Inserts the optional roles if values for the optional roles exist. """ optional_roles = [ # (<metadata-attr>, <db-role-id>,), ('translators', 4,), ('editors', 5,), ] for attr, role_id in optional_roles: roles = ...
def _insert_metadata(cursor, model, publisher, message): """Insert a module with the given ``metadata``.""" params = model.metadata.copy() params['publisher'] = publisher params['publication_message'] = message params['_portal_type'] = _model_to_portaltype(model) params['summary'] = str(cnxepub...
def _get_file_sha1(file): """Return the SHA1 hash of the given a file-like object as ``file``. This will seek the file back to 0 when it's finished. """ bits = file.read() file.seek(0) h = hashlib.new('sha1', bits).hexdigest() return h
def _insert_file(cursor, file, media_type): """Upsert the ``file`` and ``media_type`` into the files table. Returns the ``fileid`` and ``sha1`` of the upserted file. """ resource_hash = _get_file_sha1(file) cursor.execute("SELECT fileid FROM files WHERE sha1 = %s", (resource_hash...
def _insert_resource_file(cursor, module_ident, resource): """Insert a resource into the modules_files table. This will create a new file entry or associates an existing one. """ with resource.open() as file: fileid, _ = _insert_file(cursor, file, resource.media_type) # Is this file legitim...
def _insert_tree(cursor, tree, parent_id=None, index=0, is_collated=False): """Inserts a binder tree into the archive.""" if isinstance(tree, dict): if tree['id'] == 'subcol': document_id = None title = tree['title'] else: cursor.execute("""\ SELEC...
def publish_model(cursor, model, publisher, message): """Publishes the ``model`` and return its ident_hash.""" publishers = publisher if isinstance(publishers, list) and len(publishers) > 1: raise ValueError("Only one publisher is allowed. '{}' " "were given: {}" ...
def publish_composite_model(cursor, model, parent_model, publisher, message): """Publishes the ``model`` and return its ident_hash.""" if not (isinstance(model, CompositeDocument) or (isinstance(model, Binder) and model.metadata.get('type') == 'composite-chapter')): raise Val...
def publish_collated_document(cursor, model, parent_model): """Publish a given `module`'s collated content in the context of the `parent_model`. Note, the model's content is expected to already have the collated content. This will just persist that content to the archive. """ html = bytes(cnxep...
def publish_collated_tree(cursor, tree): """Publish a given collated `tree` (containing newly added `CompositeDocument` objects and number inforation) alongside the original tree. """ tree = _insert_tree(cursor, tree, is_collated=True) return tree
def republish_binders(cursor, models): """Republish the Binders that share Documents in the publication context. This needs to be given all the models in the publication context.""" documents = set([]) binders = set([]) history_mapping = {} # <previous-ident-hash>: <current-ident-hash> if not i...
def get_previous_publication(cursor, ident_hash): """Get the previous publication of the given publication as an ident-hash. """ cursor.execute("""\ WITH contextual_module AS ( SELECT uuid, module_ident FROM modules WHERE ident_hash(uuid, major_version, minor_version) = %s) SELECT ident_hash(m.uui...
def bump_version(cursor, uuid, is_minor_bump=False): """Bump to the next version of the given content identified by ``uuid``. Returns the next available version as a version tuple, containing major and minor version. If ``is_minor_bump`` is ``True`` the version will minor bump. That is 1.2 becomes 1...
def republish_collection(cursor, ident_hash, version): """Republish the collection identified as ``ident_hash`` with the given ``version``. """ if not isinstance(version, (list, tuple,)): split_version = version.split('.') if len(split_version) == 1: split_version.append(None...
def rebuild_collection_tree(cursor, ident_hash, history_map): """Create a new tree for the collection based on the old tree but with new document ids """ collection_tree_sql = """\ WITH RECURSIVE t(nodeid, parent_id, documentid, title, childorder, latest, ident_hash, path) AS ( SELECT...
def publish(request): """Accept a publication request at form value 'epub'""" if 'epub' not in request.POST: raise httpexceptions.HTTPBadRequest("Missing EPUB in POST body.") is_pre_publication = asbool(request.POST.get('pre-publication')) epub_upload = request.POST['epub'].file try: ...
def get_publication(request): """Lookup publication state""" publication_id = request.matchdict['id'] state, messages = check_publication_state(publication_id) response_data = { 'publication': publication_id, 'state': state, 'messages': messages, } return response_data
def get_accept_license(request): """This produces JSON data for a user (at ``uid``) to view the license(s) they have accepted or will need to accept for a publication (at ``id``). """ publication_id = request.matchdict['id'] user_id = request.matchdict['uid'] # FIXME Is this an active publicati...
def post_accept_license(request): """Allows the user (at ``uid``) to accept the license(s) for a publication (at ``id``). """ publication_id = request.matchdict['id'] uid = request.matchdict['uid'] # TODO Verify the accepting user is the one making the request. # They could be authenti...
def bake_content(request): """Invoke the baking process - trigger post-publication""" ident_hash = request.matchdict['ident_hash'] try: id, version = split_ident_hash(ident_hash) except IdentHashError: raise httpexceptions.HTTPNotFound() if not version: raise httpexceptions....
def includeme(config): """Configures the caching manager""" global cache_manager settings = config.registry.settings cache_manager = CacheManager(**parse_cache_config_options(settings))
def create_pg_notify_event(notif): """A factory for creating a Postgres Notification Event (an object inheriting from `cnxpublishing.events.PGNotifyEvent`) given `notif`, a `psycopg2.extensions.Notify` object. """ # TODO Lookup registered events via getAllUtilitiesRegisteredFor # for class...
def create_map(self, type_from, type_to, mapping=None): """Method for adding mapping definitions :param type_from: source type :param type_to: target type :param mapping: dictionary of mapping definitions in a form {'target_property_name', lambda function f...
def map(self, from_obj, to_type, ignore_case=False, allow_none=False, excluded=None): """Method for creating target object instance :param from_obj: source object to be mapped from :param to_type: target type :param ignore_case: if set to true, ignores attribute case when performin...
def get(self, key, default=_sentinel): """ Gets the value from the key. If the key doesn't exist, the default value is returned, otherwise None. :param key: The key :param default: The default value :return: The value """ tup = self._data.get(key.lower())...
def pop(self, key, default=_sentinel): """ Removes the specified key and returns the corresponding value. If key is not found, the default is returned if given, otherwise KeyError is raised. :param key: The key :param default: The default value :return: The value ...
def reversals(series, left=False, right=False): """Iterate reversal points in the series. A reversal point is a point in the series at which the first derivative changes sign. Reversal is undefined at the first (last) point because the derivative before (after) this point is undefined. The first and th...
def _sort_lows_and_highs(func): "Decorator for extract_cycles" @functools.wraps(func) def wrapper(*args, **kwargs): for low, high, mult in func(*args, **kwargs): if low < high: yield low, high, mult else: yield high, low, mult return wrappe...
def extract_cycles(series, left=False, right=False): """Iterate cycles in the series. Parameters ---------- series : iterable sequence of numbers left: bool, optional If True, treat the first point in the series as a reversal. right: bool, optional If True, treat the last point ...