text:
"""Defines interface for DB access.

Functions in this module are imported into the cinder.db namespace. Call these
functions from cinder.db namespace, not the cinder.db.api namespace.

All functions in this module return objects that implement a dictionary-like
interface. Currently, many of these objects are sqlalchemy objects that
implement a dictionary interface. However, a future goal is to have all of
these objects be simple dictionaries.

**Related Flags**

:connection:  string specifying the sqlalchemy connection to use, like:
              `sqlite:///var/lib/cinder/cinder.sqlite`.

:enable_new_services:  when adding a new service to the database, is it in the
                       pool of available hardware (Default: True)

"""

from oslo_config import cfg
from oslo_db import concurrency as db_concurrency
from oslo_db import options as db_options

db_opts = [
    cfg.BoolOpt('enable_new_services',
                default=True,
                help='Services to be added to the available pool on create'),
    cfg.StrOpt('volume_name_template',
               default='volume-%s',
               help='Template string to be used to generate volume names'),
    cfg.StrOpt('snapshot_name_template',
               default='snapshot-%s',
               help='Template string to be used to generate snapshot names'),
    cfg.StrOpt('backup_name_template',
               default='backup-%s',
               help='Template string to be used to generate backup names'), ]

CONF = cfg.CONF
CONF.register_opts(db_opts)
db_options.set_defaults(CONF)
CONF.set_default('sqlite_db', 'cinder.sqlite', group='database')

_BACKEND_MAPPING = {'sqlalchemy': 'cinder.db.sqlalchemy.api'}

IMPL = db_concurrency.TpoolDbapiWrapper(CONF, _BACKEND_MAPPING)

###################

def service_destroy(context, service_id):
    """Destroy the service or raise if it does not exist."""
    return IMPL.service_destroy(context, service_id)

def service_get(context, service_id):
    """Get a service or raise if it does not exist."""
    return IMPL.service_get(context, service_id)

def service_get_by_host_and_topic(context, host, topic):
    """Get a service by host it's on and topic it listens to."""
    return IMPL.service_get_by_host_and_topic(context, host, topic)

def service_get_all(context, disabled=None):
    """Get all services."""
    return IMPL.service_get_all(context, disabled)

def service_get_all_by_topic(context, topic, disabled=None):
    """Get all services for a given topic."""
    return IMPL.service_get_all_by_topic(context, topic, disabled=disabled)

def service_get_by_args(context, host, binary):
    """Get the state of an service by node name and binary."""
    return IMPL.service_get_by_args(context, host, binary)

def service_create(context, values):
    """Create a service from the values dictionary."""
    return IMPL.service_create(context, values)

def service_update(context, service_id, values):
    """Set the given properties on an service and update it.

    Raises NotFound if service does not exist.

    """
    return IMPL.service_update(context, service_id, values)

###################

def iscsi_target_count_by_host(context, host):
    """Return count of export devices."""
    return IMPL.iscsi_target_count_by_host(context, host)

def iscsi_target_create_safe(context, values):
    """Create an iscsi_target from the values dictionary.

    The device is not returned. If the create violates the unique
    constraints because the iscsi_target and host already exist,
    no exception is raised.

    """
    return IMPL.iscsi_target_create_safe(context, values)

###############

def volume_attached(context, volume_id, instance_id, host_name, mountpoint):
    """Ensure that a volume is set as attached."""
    return IMPL.volume_attached(context, volume_id, instance_id, host_name,
                                mountpoint)

def volume_create(context, values):
    """Create a volume from the values dictionary."""
    return IMPL.volume_create(context, values)

def volume_data_get_for_host(context, host, count_only=False):
    """Get (volume_count, gigabytes) for project."""
    return IMPL.volume_data_get_for_host(context,
                                         host,
                                         count_only)

def volume_data_get_for_project(context, project_id):
    """Get (volume_count, gigabytes) for project."""
    return IMPL.volume_data_get_for_project(context, project_id)

def finish_volume_migration(context, src_vol_id, dest_vol_id):
    """Perform database updates upon completion of volume migration."""
    return IMPL.finish_volume_migration(context, src_vol_id, dest_vol_id)

def volume_destroy(context, volume_id):
    """Destroy the volume or raise if it does not exist."""
    return IMPL.volume_destroy(context, volume_id)

def volume_detached(context, volume_id):
    """Ensure that a volume is set as detached."""
    return IMPL.volume_detached(context, volume_id)

def volume_get(context, volume_id):
    """Get a volume or raise if it does not exist."""
    return IMPL.volume_get(context, volume_id)

def volume_get_all(context, marker, limit, sort_key, sort_dir,
                   filters=None):
    """Get all volumes."""
    return IMPL.volume_get_all(context, marker, limit, sort_key, sort_dir,
                               filters=filters)

def volume_get_all_by_host(context, host):
    """Get all volumes belonging to a host."""
    return IMPL.volume_get_all_by_host(context, host)

def volume_get_all_by_group(context, group_id):
    """Get all volumes belonging to a consistency group."""
    return IMPL.volume_get_all_by_group(context, group_id)

def volume_get_all_by_project(context, project_id, marker, limit, sort_key,
                              sort_dir, filters=None):
    """Get all volumes belonging to a project."""
    return IMPL.volume_get_all_by_project(context, project_id, marker, limit,
                                          sort_key, sort_dir, filters=filters)

def volume_get_iscsi_target_num(context, volume_id):
    """Get the target num (tid) allocated to the volume."""
    return IMPL.volume_get_iscsi_target_num(context, volume_id)

def volume_update(context, volume_id, values):
    """Set the given properties on an volume and update it.

    Raises NotFound if volume does not exist.

    """
    return IMPL.volume_update(context, volume_id, values)

####################

def snapshot_create(context, values):
    """Create a snapshot from the values dictionary."""
    return IMPL.snapshot_create(context, values)

def snapshot_destroy(context, snapshot_id):
    """Destroy the snapshot or raise if it does not exist."""
    return IMPL.snapshot_destroy(context, snapshot_id)

def snapshot_get(context, snapshot_id):
    """Get a snapshot or raise if it does not exist."""
    return IMPL.snapshot_get(context, snapshot_id)

def snapshot_get_all(context):
    """Get all snapshots."""
    return IMPL.snapshot_get_all(context)

def snapshot_get_all_by_project(context, project_id):
    """Get all snapshots belonging to a project."""
    return IMPL.snapshot_get_all_by_project(context, project_id)

def snapshot_get_all_for_cgsnapshot(context, project_id):
    """Get all snapshots belonging to a cgsnapshot."""
    return IMPL.snapshot_get_all_for_cgsnapshot(context, project_id)

def snapshot_get_all_for_volume(context, volume_id):
    """Get all snapshots for a volume."""
    return IMPL.snapshot_get_all_for_volume(context, volume_id)

def snapshot_update(context, snapshot_id, values):
    """Set the given properties on an snapshot and update it.

    Raises NotFound if snapshot does not exist.

    """
    return IMPL.snapshot_update(context, snapshot_id, values)

def snapshot_data_get_for_project(context, project_id, volume_type_id=None):
    """Get count and gigabytes used for snapshots for specified project."""
    return IMPL.snapshot_data_get_for_project(context,
                                              project_id,
                                              volume_type_id)

def snapshot_get_active_by_window(context, begin, end=None, project_id=None):
    """Get all the snapshots inside the window.

    Specifying a project_id will filter for a certain project.
    """
    return IMPL.snapshot_get_active_by_window(context, begin, end, project_id)

####################

def snapshot_metadata_get(context, snapshot_id):
    """Get all metadata for a snapshot."""
    return IMPL.snapshot_metadata_get(context, snapshot_id)

def snapshot_metadata_delete(context, snapshot_id, key):
    """Delete the given metadata item."""
    return IMPL.snapshot_metadata_delete(context, snapshot_id, key)

def snapshot_metadata_update(context, snapshot_id, metadata, delete):
    """Update metadata if it exists, otherwise create it."""
    return IMPL.snapshot_metadata_update(context, snapshot_id,
                                         metadata, delete)

####################

def volume_metadata_get(context, volume_id):
    """Get all metadata for a volume."""
    return IMPL.volume_metadata_get(context, volume_id)

def volume_metadata_delete(context, volume_id, key):
    """Delete the given metadata item."""
    return IMPL.volume_metadata_delete(context, volume_id, key)

def volume_metadata_update(context, volume_id, metadata, delete):
    """Update metadata if it exists, otherwise create it."""
    return IMPL.volume_metadata_update(context, volume_id, metadata, delete)

##################

def volume_admin_metadata_get(context, volume_id):
    """Get all administration metadata for a volume."""
    return IMPL.volume_admin_metadata_get(context, volume_id)

def volume_admin_metadata_delete(context, volume_id, key):
    """Delete the given metadata item."""
    return IMPL.volume_admin_metadata_delete(context, volume_id, key)

def volume_admin_metadata_update(context, volume_id, metadata, delete):
    """Update metadata if it exists, otherwise create it."""
    return IMPL.volume_admin_metadata_update(context, volume_id, metadata,
                                             delete)

##################

def volume_type_create(context, values, projects=None):
    """Create a new volume type."""
    return IMPL.volume_type_create(context, values, projects)

def volume_type_update(context, volume_type_id, values):
    return IMPL.volume_type_update(context, volume_type_id, values)

def volume_type_get_all(context, inactive=False, filters=None):
    """Get all volume types.

    :param context: context to query under
    :param inactive: Include inactive volume types to the result set
    :param filters: Filters for the query in the form of key/value.

        :is_public: Filter volume types based on visibility:

            * **True**: List public volume types only
            * **False**: List private volume types only
            * **None**: List both public and private volume types

    :returns: list of matching volume types
    """

    return IMPL.volume_type_get_all(context, inactive, filters)

def volume_type_get(context, id, inactive=False, expected_fields=None):
    """Get volume type by id.

    :param context: context to query under
    :param id: Volume type id to get.
    :param inactive: Consider inactive volume types when searching
    :param expected_fields: Return those additional fields.
                            Supported fields are: projects.
    :returns: volume type
    """
    return IMPL.volume_type_get(context, id, inactive, expected_fields)

def volume_type_get_by_name(context, name):
    """Get volume type by name."""
    return IMPL.volume_type_get_by_name(context, name)

def volume_types_get_by_name_or_id(context, volume_type_list):
    """Get volume types by name or id."""
    return IMPL.volume_types_get_by_name_or_id(context, volume_type_list)

def volume_type_qos_associations_get(context, qos_specs_id, inactive=False):
    """Get volume types that are associated with specific qos specs."""
    return IMPL.volume_type_qos_associations_get(context,
                                                 qos_specs_id,
                                                 inactive)

def volume_type_qos_associate(context, type_id, qos_specs_id):
    """Associate a volume type with specific qos specs."""
    return IMPL.volume_type_qos_associate(context, type_id, qos_specs_id)

def volume_type_qos_disassociate(context, qos_specs_id, type_id):
    """Disassociate a volume type from specific qos specs."""
    return IMPL.volume_type_qos_disassociate(context, qos_specs_id, type_id)

def volume_type_qos_disassociate_all(context, qos_specs_id):
    """Disassociate all volume types from specific qos specs."""
    return IMPL.volume_type_qos_disassociate_all(context,
                                                 qos_specs_id)

def volume_type_qos_specs_get(context, type_id):
    """Get all qos specs for given volume type."""
    return IMPL.volume_type_qos_specs_get(context, type_id)

def volume_type_destroy(context, id):
    """Delete a volume type."""
    return IMPL.volume_type_destroy(context, id)

def volume_get_active_by_window(context, begin, end=None, project_id=None):
    """Get all the volumes inside the window.

    Specifying a project_id will filter for a certain project.
    """
    return IMPL.volume_get_active_by_window(context, begin, end, project_id)

def volume_type_access_get_all(context, type_id):
    """Get all volume type access of a volume type."""
    return IMPL.volume_type_access_get_all(context, type_id)

def volume_type_access_add(context, type_id, project_id):
    """Add volume type access for project."""
    return IMPL.volume_type_access_add(context, type_id, project_id)

def volume_type_access_remove(context, type_id, project_id):
    """Remove volume type access for project."""
    return IMPL.volume_type_access_remove(context, type_id, project_id)

####################

def volume_type_extra_specs_get(context, volume_type_id):
    """Get all extra specs for a volume type."""
    return IMPL.volume_type_extra_specs_get(context, volume_type_id)

def volume_type_extra_specs_delete(context, volume_type_id, key):
    """Delete the given extra specs item."""
    return IMPL.volume_type_extra_specs_delete(context, volume_type_id, key)

def volume_type_extra_specs_update_or_create(context,
                                             volume_type_id,
                                             extra_specs):
    """Create or update volume type extra specs. This adds or modifies the
    key/value pairs specified in the extra specs dict argument
    """
    return IMPL.volume_type_extra_specs_update_or_create(context,
                                                         volume_type_id,
                                                         extra_specs)

###################

def volume_type_encryption_get(context, volume_type_id, session=None):
    return IMPL.volume_type_encryption_get(context, volume_type_id, session)

def volume_type_encryption_delete(context, volume_type_id):
    return IMPL.volume_type_encryption_delete(context, volume_type_id)

def volume_type_encryption_create(context, volume_type_id, encryption_specs):
    return IMPL.volume_type_encryption_create(context, volume_type_id,
                                              encryption_specs)

def volume_type_encryption_update(context, volume_type_id, encryption_specs):
    return IMPL.volume_type_encryption_update(context, volume_type_id,
                                              encryption_specs)

def volume_type_encryption_volume_get(context, volume_type_id, session=None):
    return IMPL.volume_type_encryption_volume_get(context, volume_type_id,
                                                  session)

def volume_encryption_metadata_get(context, volume_id, session=None):
    return IMPL.volume_encryption_metadata_get(context, volume_id, session)

###################

def qos_specs_create(context, values):
    """Create a qos_specs."""
    return IMPL.qos_specs_create(context, values)

def qos_specs_get(context, qos_specs_id):
    """Get all specification for a given qos_specs."""
    return IMPL.qos_specs_get(context, qos_specs_id)

def qos_specs_get_all(context, inactive=False, filters=None):
    """Get all qos_specs."""
    return IMPL.qos_specs_get_all(context, inactive, filters)

def qos_specs_get_by_name(context, name):
    """Get all specification for a given qos_specs."""
    return IMPL.qos_specs_get_by_name(context, name)

def qos_specs_associations_get(context, qos_specs_id):
    """Get all associated volume types for a given qos_specs."""
    return IMPL.qos_specs_associations_get(context, qos_specs_id)

def qos_specs_associate(context, qos_specs_id, type_id):
    """Associate qos_specs from volume type."""
    return IMPL.qos_specs_associate(context, qos_specs_id, type_id)

def qos_specs_disassociate(context, qos_specs_id, type_id):
    """Disassociate qos_specs from volume type."""
    return IMPL.qos_specs_disassociate(context, qos_specs_id, type_id)

def qos_specs_disassociate_all(context, qos_specs_id):
    """Disassociate qos_specs from all entities."""
    return IMPL.qos_specs_disassociate_all(context, qos_specs_id)

def qos_specs_delete(context, qos_specs_id):
    """Delete the qos_specs."""
    return IMPL.qos_specs_delete(context, qos_specs_id)

def qos_specs_item_delete(context, qos_specs_id, key):
    """Delete specified key in the qos_specs."""
    return IMPL.qos_specs_item_delete(context, qos_specs_id, key)

def qos_specs_update(context, qos_specs_id, specs):
    """Update qos specs.

    This adds or modifies the key/value pairs specified in the
    specs dict argument for a given qos_specs.
    """
    return IMPL.qos_specs_update(context, qos_specs_id, specs)

###################

def volume_glance_metadata_create(context, volume_id, key, value):
    """Update the Glance metadata for the specified volume."""
    return IMPL.volume_glance_metadata_create(context,
                                              volume_id,
                                              key,
                                              value)

def volume_glance_metadata_get_all(context):
    """Return the glance metadata for all volumes."""
    return IMPL.volume_glance_metadata_get_all(context)

def volume_glance_metadata_get(context, volume_id):
    """Return the glance metadata for a volume."""
    return IMPL.volume_glance_metadata_get(context, volume_id)

def volume_snapshot_glance_metadata_get(context, snapshot_id):
    """Return the Glance metadata for the specified snapshot."""
    return IMPL.volume_snapshot_glance_metadata_get(context, snapshot_id)

def volume_glance_metadata_copy_to_snapshot(context, snapshot_id, volume_id):
    """Update the Glance metadata for a snapshot.

    This will copy all of the key:value pairs from the originating volume,
    to ensure that a volume created from the snapshot will retain the
    original metadata.
    """
    return IMPL.volume_glance_metadata_copy_to_snapshot(context, snapshot_id,
                                                        volume_id)

def volume_glance_metadata_copy_to_volume(context, volume_id, snapshot_id):
    """Update the Glance metadata from a volume (created from a snapshot).

    This will copy all of the key:value pairs from the originating snapshot,
    to ensure that the Glance metadata from the original volume is retained.
    """
    return IMPL.volume_glance_metadata_copy_to_volume(context, volume_id,
                                                      snapshot_id)

def volume_glance_metadata_delete_by_volume(context, volume_id):
    """Delete the glance metadata for a volume."""
    return IMPL.volume_glance_metadata_delete_by_volume(context, volume_id)

def volume_glance_metadata_delete_by_snapshot(context, snapshot_id):
    """Delete the glance metadata for a snapshot."""
    return IMPL.volume_glance_metadata_delete_by_snapshot(context, snapshot_id)

def volume_glance_metadata_copy_from_volume_to_volume(context,
                                                      src_volume_id,
                                                      volume_id):
    """Update the Glance metadata for a volume by copying all of the key:value
    pairs from the originating volume.

    This is so that a volume created from the volume (clone) will retain the
    original metadata.
    """
    return IMPL.volume_glance_metadata_copy_from_volume_to_volume(
        context,
        src_volume_id,
        volume_id)

###################

def quota_create(context, project_id, resource, limit):
    """Create a quota for the given project and resource."""
    return IMPL.quota_create(context, project_id, resource, limit)

def quota_get(context, project_id, resource):
    """Retrieve a quota or raise if it does not exist."""
    return IMPL.quota_get(context, project_id, resource)

def quota_get_all_by_project(context, project_id):
    """Retrieve all quotas associated with a given project."""
    return IMPL.quota_get_all_by_project(context, project_id)

def quota_update(context, project_id, resource, limit):
    """Update a quota or raise if it does not exist."""
    return IMPL.quota_update(context, project_id, resource, limit)

def quota_destroy(context, project_id, resource):
    """Destroy the quota or raise if it does not exist."""
    return IMPL.quota_destroy(context, project_id, resource)

###################

def quota_class_create(context, class_name, resource, limit):
    """Create a quota class for the given name and resource."""
    return IMPL.quota_class_create(context, class_name, resource, limit)

def quota_class_get(context, class_name, resource):
    """Retrieve a quota class or raise if it does not exist."""
    return IMPL.quota_class_get(context, class_name, resource)

def quota_class_get_default(context):
    """Retrieve all default quotas."""
    return IMPL.quota_class_get_default(context)

def quota_class_get_all_by_name(context, class_name):
    """Retrieve all quotas associated with a given quota class."""
    return IMPL.quota_class_get_all_by_name(context, class_name)

def quota_class_update(context, class_name, resource, limit):
    """Update a quota class or raise if it does not exist."""
    return IMPL.quota_class_update(context, class_name, resource, limit)

def quota_class_destroy(context, class_name, resource):
    """Destroy the quota class or raise if it does not exist."""
    return IMPL.quota_class_destroy(context, class_name, resource)

def quota_class_destroy_all_by_name(context, class_name):
    """Destroy all quotas associated with a given quota class."""
    return IMPL.quota_class_destroy_all_by_name(context, class_name)

###################

def quota_usage_get(context, project_id, resource):
    """Retrieve a quota usage or raise if it does not exist."""
    return IMPL.quota_usage_get(context, project_id, resource)

def quota_usage_get_all_by_project(context, project_id):
    """Retrieve all usage associated with a given resource."""
    return IMPL.quota_usage_get_all_by_project(context, project_id)

###################

def quota_reserve(context, resources, quotas, deltas, expire,
                  until_refresh, max_age, project_id=None):
    """Check quotas and create appropriate reservations."""
    return IMPL.quota_reserve(context, resources, quotas, deltas, expire,
                              until_refresh, max_age, project_id=project_id)

def reservation_commit(context, reservations, project_id=None):
    """Commit quota reservations."""
    return IMPL.reservation_commit(context, reservations,
                                   project_id=project_id)

def reservation_rollback(context, reservations, project_id=None):
    """Roll back quota reservations."""
    return IMPL.reservation_rollback(context, reservations,
                                     project_id=project_id)

def quota_destroy_all_by_project(context, project_id):
    """Destroy all quotas associated with a given project."""
    return IMPL.quota_destroy_all_by_project(context, project_id)

def reservation_expire(context):
    """Roll back any expired reservations."""
    return IMPL.reservation_expire(context)

###################

def backup_get(context, backup_id):
    """Get a backup or raise if it does not exist."""
    return IMPL.backup_get(context, backup_id)

def backup_get_all(context, filters=None):
    """Get all backups."""
    return IMPL.backup_get_all(context, filters=filters)

def backup_get_all_by_host(context, host):
    """Get all backups belonging to a host."""
    return IMPL.backup_get_all_by_host(context, host)

def backup_create(context, values):
    """Create a backup from the values dictionary."""
    return IMPL.backup_create(context, values)

def backup_get_all_by_project(context, project_id, filters=None):
    """Get all backups belonging to a project."""
    return IMPL.backup_get_all_by_project(context, project_id,
                                          filters=filters)

def backup_update(context, backup_id, values):
    """Set the given properties on a backup and update it.

    Raises NotFound if backup does not exist.
    """
    return IMPL.backup_update(context, backup_id, values)

def backup_destroy(context, backup_id):
    """Destroy the backup or raise if it does not exist."""
    return IMPL.backup_destroy(context, backup_id)

###################

def transfer_get(context, transfer_id):
    """Get a volume transfer record or raise if it does not exist."""
    return IMPL.transfer_get(context, transfer_id)

def transfer_get_all(context):
    """Get all volume transfer records."""
    return IMPL.transfer_get_all(context)

def transfer_get_all_by_project(context, project_id):
    """Get all volume transfer records for specified project."""
    return IMPL.transfer_get_all_by_project(context, project_id)

def transfer_create(context, values):
    """Create an entry in the transfers table."""
    return IMPL.transfer_create(context, values)

def transfer_destroy(context, transfer_id):
    """Destroy a record in the volume transfer table."""
    return IMPL.transfer_destroy(context, transfer_id)

def transfer_accept(context, transfer_id, user_id, project_id):
    """Accept a volume transfer."""
    return IMPL.transfer_accept(context, transfer_id, user_id, project_id)

###################

def consistencygroup_get(context, consistencygroup_id):
    """Get a consistencygroup or raise if it does not exist."""
    return IMPL.consistencygroup_get(context, consistencygroup_id)

def consistencygroup_get_all(context):
    """Get all consistencygroups."""
    return IMPL.consistencygroup_get_all(context)

def consistencygroup_create(context, values):
    """Create a consistencygroup from the values dictionary."""
    return IMPL.consistencygroup_create(context, values)

def consistencygroup_get_all_by_project(context, project_id):
    """Get all consistencygroups belonging to a project."""
    return IMPL.consistencygroup_get_all_by_project(context, project_id)

def consistencygroup_update(context, consistencygroup_id, values):
    """Set the given properties on a consistencygroup and update it.

    Raises NotFound if consistencygroup does not exist.
    """
    return IMPL.consistencygroup_update(context, consistencygroup_id, values)

def consistencygroup_destroy(context, consistencygroup_id):
    """Destroy the consistencygroup or raise if it does not exist."""
    return IMPL.consistencygroup_destroy(context, consistencygroup_id)

###################

def cgsnapshot_get(context, cgsnapshot_id):
    """Get a cgsnapshot or raise if it does not exist."""
    return IMPL.cgsnapshot_get(context, cgsnapshot_id)

def cgsnapshot_get_all(context):
    """Get all cgsnapshots."""
    return IMPL.cgsnapshot_get_all(context)

def cgsnapshot_create(context, values):
    """Create a cgsnapshot from the values dictionary."""
    return IMPL.cgsnapshot_create(context, values)

def cgsnapshot_get_all_by_group(context, group_id):
    """Get all cgsnapshots belonging to a consistency group."""
    return IMPL.cgsnapshot_get_all_by_group(context, group_id)

def cgsnapshot_get_all_by_project(context, project_id):
    """Get all cgsnapshots belonging to a project."""
    return IMPL.cgsnapshot_get_all_by_project(context, project_id)

def cgsnapshot_update(context, cgsnapshot_id, values):
    """Set the given properties on a cgsnapshot and update it.

    Raises NotFound if cgsnapshot does not exist.
    """
    return IMPL.cgsnapshot_update(context, cgsnapshot_id, values)

def cgsnapshot_destroy(context, cgsnapshot_id):
    """Destroy the cgsnapshot or raise if it does not exist."""
    return IMPL.cgsnapshot_destroy(context, cgsnapshot_id)

def purge_deleted_rows(context, age_in_days):
    """Purge deleted rows older than given age from cinder tables

    Raises InvalidParameterValue if age_in_days is incorrect.
    :returns: number of deleted rows
    """
    return IMPL.purge_deleted_rows(context, age_in_days=age_in_days)


text:
"""
General numerical functions and methods.

"""
import functools
import itertools

import numpy as np
import scipy as sp
import scipy.linalg as linalg
import scipy.special as special
import scipy.optimize as optimize
import scipy.sparse as sparse

import tempfile as tmp

import unittest
from numpy import testing

def composite_function(function_list):
    """
    Construct a function composition from a list of functions.

    Given a list of functions [f,g,h], constructs a function :math:`h \circ g
    \circ f`.  That is, returns a function :math:`z`, for which :math:`z(x) =
    h(g(f(x)))`.
    """
    def composite(X):
        for function in function_list:
            X = function(X)
        return X
    return composite

def ceildiv(a, b):
    """
    Compute a divided by b and rounded up.
    """
    return -(-a // b)

def rmse(y1, y2, axis=None):
    return np.sqrt(np.mean((y1-y2)**2, axis=axis))

def is_callable(f):
    return hasattr(f, '__call__')

def atleast_nd(X, d):
    if np.ndim(X) < d:
        sh = (d-np.ndim(X))*(1,) + np.shape(X)
        X = np.reshape(X, sh)
    return X

def T(X):
    """
    Transpose the matrix.
    """
    return np.swapaxes(X, -1, -2)

class TestCase(unittest.TestCase):
    """
    Simple base class for unit testing.

    Adds NumPy's features to Python's unittest.
    """

    def assertAllClose(self, A, B,
                       msg="Arrays not almost equal",
                       rtol=1e-4,
                       atol=0):

        self.assertEqual(np.shape(A), np.shape(B), msg=msg)
        testing.assert_allclose(A, B, err_msg=msg, rtol=rtol, atol=atol)
        pass

    def assertArrayEqual(self, A, B, msg="Arrays not equal"):
        self.assertEqual(np.shape(A), np.shape(B), msg=msg)
        testing.assert_array_equal(A, B, err_msg=msg)
        pass

    def assertMessage(self, M1, M2):

        if len(M1) != len(M2):
            self.fail("Message lists have different lengths")

        for (m1, m2) in zip(M1, M2):
            self.assertAllClose(m1, m2)

        pass

    def assertMessageToChild(self, X, u):
        self.assertMessage(X._message_to_child(), u)
        pass

def symm(X):
    """
    Make X symmetric.
    """
    return 0.5 * (X + np.swapaxes(X, -1, -2))

def unique(l):
    """
    Remove duplicate items from a list while preserving order.
    """
    seen = set()
    seen_add = seen.add
    return [ x for x in l if x not in seen and not seen_add(x)]

def tempfile(prefix='', suffix=''):
    return tmp.NamedTemporaryFile(prefix=prefix, suffix=suffix).name

def write_to_hdf5(group, data, name):
    """
    Writes the given array into the HDF5 file.
    """
    try:
        # Try using compression. It doesn't work for scalars.
        group.create_dataset(name,
                             data=data,
                             compression='gzip')
    except TypeError:
        group.create_dataset(name,
                             data=data)
    except ValueError:
        raise ValueError('Could not write %s' % data)

def nans(size=()):
    return np.tile(np.nan, size)

def trues(shape):
    return np.ones(shape, dtype=np.bool)

def identity(*shape):
    return np.reshape(np.identity(np.prod(shape)), shape+shape)

def array_to_scalar(x):
    # This transforms an N-dimensional array to a scalar. It's most
    # useful when you know that the array has only one element and you
    # want it out as a scalar.
    return np.ravel(x)[0]

#def diag(x):

def grid(x1, x2):
    """ Returns meshgrid as a (M*N,2)-shape array. """
    (X1, X2) = np.meshgrid(x1, x2)
    return np.hstack((X1.reshape((-1,1)),X2.reshape((-1,1))))

class CholeskyDense():

    def __init__(self, K):
        self.U = linalg.cho_factor(K)

    def solve(self, b):
        if sparse.issparse(b):
            b = b.toarray()
        return linalg.cho_solve(self.U, b)

    def logdet(self):
        return 2*np.sum(np.log(np.diag(self.U[0])))

    def trace_solve_gradient(self, dK):
        return np.trace(self.solve(dK))

class CholeskySparse():

    def __init__(self, K):
        self.LD = cholmod.cholesky(K)

    def solve(self, b):
        if sparse.issparse(b):
            b = b.toarray()
        return self.LD.solve_A(b)

    def logdet(self):
        return self.LD.logdet()
        #np.sum(np.log(LD.D()))

    def trace_solve_gradient(self, dK):
        # WTF?! numpy.multiply doesn't work for two sparse
        # matrices.. It returns a result but it is incorrect!

        # Use the identity trace(K\dK)=sum(inv(K).*dK) by computing
        # the sparse inverse (lower triangular part)
        iK = self.LD.spinv(form='lower')
        return (2*iK.multiply(dK).sum()
                - iK.diagonal().dot(dK.diagonal()))
        # Multiply by two because of symmetry (remove diagonal once
        # because it was taken into account twice)
        #return np.multiply(self.LD.inv().todense(),dK.todense()).sum()
        #return self.LD.inv().multiply(dK).sum() # THIS WORKS
        #return np.multiply(self.LD.inv(),dK).sum() # THIS NOT WORK!! WTF??
        iK = self.LD.spinv()
        return iK.multiply(dK).sum()
        #return (2*iK.multiply(dK).sum()
        #        - iK.diagonal().dot(dK.diagonal()))
        #return (2*np.multiply(iK, dK).sum()
        #        - iK.diagonal().dot(dK.diagonal())) # THIS NOT WORK!!
        #return np.trace(self.solve(dK))

def cholesky(K):
    if isinstance(K, np.ndarray):
        return CholeskyDense(K)
    elif sparse.issparse(K):
        return CholeskySparse(K)
    else:
        raise Exception("Unsupported covariance matrix type")

def vb_optimize(x0, set_values, lowerbound, gradient=None):
    # Function for computing the lower bound
    def func(x):
        # Set the value of the nodes
        set_values(x)
        # Compute lower bound (and gradient terms)
        return -lowerbound()
        #return f

    # Function for computing the gradient of the lower bound
    def funcprime(x):
        # Collect the gradients from the nodes
        set_values(x)
        # Compute lower bound (and gradient terms)
        #lowerbound()
        return -gradient()
        #return df

    # Optimize
    if gradient != None:
        check_gradient(x0, func, funcprime, 1e-6)

        xopt = optimize.fmin_bfgs(func, x0, fprime=funcprime, maxiter=100)
        #xopt = optimize.fmin_ncg(func, x0, fprime=funcprime, maxiter=50)
    else:
        xopt = optimize.fmin_bfgs(func, x0, maxiter=100)
        #xopt = optimize.fmin_ncg(func, x0, maxiter=50)

    # Set optimal values to the nodes
    set_values(xopt)

# Optimizes the parameters of the given nodes.
def vb_optimize_nodes(*nodes):

    # Get cost functions
    lbs = set()
    for node in nodes:
        # Add node's cost function
        lbs |= node.get_all_vb_terms()
        #.lower_bound_contribution)
        # Add child nodes' cost functions
        #for lb in node.get_children_vb_bound():
            #lbs.add(lb)

    # Uniqify nodes?
    nodes = set(nodes)

    # Get initial value and transformation/update function
    ind = 0
    ind_all = list()
    transform_all = list()
    gradient_all = list()
    x0_all = np.array([])
    for node in nodes:
        (x0, transform, gradient) = node.start_optimization()
        # Vector of initial values
        x0 = np.atleast_1d(x0)
        x0_all = np.concatenate((x0_all, x0))
        # Indices of the vector elements that correspond to this node
        sz = np.size(x0)
        ind_all.append((ind, ind+sz))
        ind += sz
        # Function for setting the value of this node
        transform_all.append(transform)
        # Gradients
        gradient_all.append(gradient)

    # Function for changing the values of the nodes
    def set_value(x):
        for (ind, transform) in zip(ind_all, transform_all):
            # Transform/update variable
            transform(x[ind[0]:ind[1]])

    # Compute the lower bound (and the gradient)
    def lowerbound():
        l = 0
        # TODO: Put gradients to zero!
        for lb in lbs:
            l += lb(gradient=False)
        return l

    # Compute (or get) the gradient
    def gradient():
        for lb in lbs:
            lb(gradient=True)
        dl = np.zeros(np.shape(x0_all))
        for (ind, gradient) in zip(ind_all, gradient_all):
            dl[ind[0]:ind[1]] = gradient()

        return dl

    #vb_optimize(x0_all, set_value, lowerbound)
    vb_optimize(x0_all, set_value, lowerbound, gradient=gradient)

    for node in nodes:
        node.stop_optimization()

# Computes log probability density function of the Gaussian
# distribution
def gaussian_logpdf(y_invcov_y,
                    y_invcov_mu,
                    mu_invcov_mu,
                    logdetcov,
                    D):

    return (-0.5*D*np.log(2*np.pi)
            -0.5*logdetcov
            -0.5*y_invcov_y
            +y_invcov_mu
            -0.5*mu_invcov_mu)

def check_gradient(x0, f, df, eps):
    #f0 = f(x0)
    grad = np.zeros(np.shape(x0))

    for ind in range(len(x0)):
        xmin = x0.copy()
        xmax = x0.copy()
        xmin[ind] -= eps
        xmax[ind] += eps

        fmin = f(xmin)
        fmax = f(xmax)

        grad[ind] = (fmax-fmin) / (2*eps)

    print('x: ' + str(x0))
    print('Numerical gradient: ' + str(grad))
    print('Exact gradient: ' + str(df(x0)))

def zipper_merge(*lists):
    """
    Combines lists by alternating elements from them.

    Combining lists [1,2,3], ['a','b','c'] and [42,666,99] results in
    [1,'a',42,2,'b',666,3,'c',99]

    The lists should have equal length or they are assumed to have the length of
    the shortest list.

    This is known as alternating merge or zipper merge.
    """

    return list(sum(zip(*lists), ()))

def remove_whitespace(s):
    return ''.join(s.split())

def is_numeric(a):
    return (np.isscalar(a) or
            isinstance(a, list) or
            isinstance(a, np.ndarray))

def isinteger(x):
    t = np.asanyarray(x).dtype.type
    return ( issubclass(t, np.integer) or issubclass(t, np.bool_) )

def is_string(s):
    return isinstance(s, str)

def multiply_shapes(*shapes):
    """
    Compute element-wise product of lists/tuples.

    Shorter lists are concatenated with leading 1s in order to get lists with
    the same length.
    """

    # Make the shapes equal length
    shapes = make_equal_length(*shapes)

    # Compute element-wise product
    f = lambda X,Y: (x*y for (x,y) in zip(X,Y))
    shape = functools.reduce(f, shapes)

    return tuple(shape)

def make_equal_length(*shapes):
    """
    Make tuples equal length.

    Add leading 1s to shorter tuples.
    """

    # Get maximum length
    max_len = max((len(shape) for shape in shapes))

    # Make the shapes equal length
    shapes = ((1,)*(max_len-len(shape)) + tuple(shape) for shape in shapes)

    return shapes

def make_equal_ndim(*arrays):
    """
    Add trailing unit axes so that arrays have equal ndim
    """
    shapes = [np.shape(array) for array in arrays]
    shapes = make_equal_length(*shapes)
    arrays = [np.reshape(array, shape)
              for (array, shape) in zip(arrays, shapes)]
    return arrays

def sum_to_dim(A, dim):
    """
    Sum leading axes of A such that A has dim dimensions.
    """
    dimdiff = np.ndim(A) - dim
    if dimdiff > 0:
        axes = np.arange(dimdiff)
        A = np.sum(A, axis=axes)
    return A

def broadcasting_multiplier(plates, *args):
    """
    Compute the plate multiplier for given shapes.

    The first shape is compared to all other shapes (using NumPy
    broadcasting rules). All the elements which are non-unit in the first
    shape but 1 in all other shapes are multiplied together.

    This method is used, for instance, for computing a correction factor for
    messages to parents: If this node has non-unit plates that are unit
    plates in the parent, those plates are summed. However, if the message
    has unit axis for that plate, it should be first broadcasted to the
    plates of this node and then summed to the plates of the parent. In
    order to avoid this broadcasting and summing, it is more efficient to
    just multiply by the correct factor. This method computes that
    factor. The first argument is the full plate shape of this node (with
    respect to the parent). The other arguments are the shape of the message
    array and the plates of the parent (with respect to this node).
    """

    # Check broadcasting of the shapes
    for arg in args:
        broadcasted_shape(plates, arg)

    # Check that each arg-plates are a subset of plates?
    for arg in args:
        if not is_shape_subset(arg, plates):
            print("Plates:", plates)
            print("Args:", args)
            raise ValueError("The shapes in args are not a sub-shape of "
                             "plates")

    r = 1
    for j in range(-len(plates),0):
        mult = True
        for arg in args:
            # if -j <= len(arg) and arg[j] != 1:
            if not (-j > len(arg) or arg[j] == 1):
                mult = False
        if mult:
            r *= plates[j]
    return r

def sum_multiply_to_plates(*arrays, to_plates=(), from_plates=None, ndim=0):
    """
    Compute the product of the arguments and sum to the target shape.
    """
    arrays = list(arrays)
    def get_plates(x):
        if ndim == 0:
            return x
        else:
            return x[:-ndim]

    plates_arrays = [get_plates(np.shape(array)) for array in arrays]
    product_plates = broadcasted_shape(*plates_arrays)

    if from_plates is None:
        from_plates = product_plates
        r = 1
    else:
        r = broadcasting_multiplier(from_plates, product_plates, to_plates)

    for ind in range(len(arrays)):
        plates_others = plates_arrays[:ind] + plates_arrays[(ind+1):]
        plates_without = broadcasted_shape(to_plates, *plates_others)
        ax = axes_to_collapse(plates_arrays[ind], #get_plates(np.shape(arrays[ind])),
                              plates_without)
        if ax:
            ax = tuple([a-ndim for a in ax])
            arrays[ind] = np.sum(arrays[ind], axis=ax, keepdims=True)

    plates_arrays = [get_plates(np.shape(array)) for array in arrays]
    product_plates = broadcasted_shape(*plates_arrays)

    ax = axes_to_collapse(product_plates, to_plates)
    if ax:
        ax = tuple([a-ndim for a in ax])
        y = sum_multiply(*arrays, axis=ax, keepdims=True)
    else:
        y = functools.reduce(np.multiply, arrays)
    y = squeeze_to_dim(y, len(to_plates) + ndim)
    return r * y

def sum_multiply(*args, axis=None, sumaxis=True, keepdims=False):

    # Computes sum(arg[0]*arg[1]*arg[2]*..., axis=axes_to_sum) without
    # explicitly computing the intermediate product

    if len(args) == 0:
        raise ValueError("You must give at least one input array")

    # Dimensionality of the result
    max_dim = 0
    for k in range(len(args)):
        max_dim = max(max_dim, np.ndim(args[k]))

    if sumaxis:
        if axis is None:
            # Sum all axes
            axes = []
        else:
            if np.isscalar(axis):
                axis = [axis]
            axes = [i
                    for i in range(max_dim)
                    if i not in axis and (-max_dim+i) not in axis]
    else:
        if axis is None:
            # Keep all axes
            axes = range(max_dim)
        else:
            # Find axes that are kept
            if np.isscalar(axis):
                axes = [axis]
            axes = [i if i >= 0
                    else i+max_dim
                    for i in axis]
            axes = sorted(axes)

    if len(axes) > 0 and (min(axes) < 0 or max(axes) >= max_dim):
        raise ValueError("Axis index out of bounds")

    # Form a list of pairs: the array in the product and its axes
    pairs = list()
    for i in range(len(args)):
        a = args[i]
        a_dim = np.ndim(a)
        pairs.append(a)
        pairs.append(range(max_dim-a_dim, max_dim))

    # Output axes are those which are not summed
    pairs.append(axes)

    # Compute the sum-product
    try:
        y = np.einsum(*pairs)
    except ValueError as err:
        if str(err) == ("If 'op_axes' or 'itershape' is not NULL in "
                        "theiterator constructor, 'oa_ndim' must be greater "
                        "than zero"):
            # TODO/FIXME: Handle a bug in NumPy. If all arguments to einsum are
            # scalars, it raises an error. For scalars we can just use multiply
            # and forget about summing. Hopefully, in the future, einsum handles
            # scalars properly and this try-except becomes unnecessary.
            y = functools.reduce(np.multiply, args)
        else:
            raise err

    # Restore summed axes as singleton axes
    if keepdims:
        d = 0
        s = ()
        for k in range(max_dim):
            if k in axes:
                # Axis not summed
                s = s + (np.shape(y)[d],)
                d += 1
            else:
                # Axis was summed
                s = s + (1,)
        y = np.reshape(y, s)

    return y

def sum_product(*args, axes_to_keep=None, axes_to_sum=None, keepdims=False):
    if axes_to_keep is not None:
        return sum_multiply(*args,
                            axis=axes_to_keep,
                            sumaxis=False,
                            keepdims=keepdims)
    else:
        return sum_multiply(*args,
                            axis=axes_to_sum,
                            sumaxis=True,
                            keepdims=keepdims)

def moveaxis(A, axis_from, axis_to):
    """
    Move the axis `axis_from` to position `axis_to`.
    """
    if ((axis_from < 0 and abs(axis_from) > np.ndim(A)) or
        (axis_from >= 0 and axis_from >= np.ndim(A)) or
        (axis_to < 0 and abs(axis_to) > np.ndim(A)) or
        (axis_to >= 0  and axis_to >= np.ndim(A))):

        raise ValueError("Can't move axis %d to position %d. Axis index out of "
                         "bounds for array with shape %s"
                         % (axis_from,
                            axis_to,
                            np.shape(A)))

    axes = np.arange(np.ndim(A))
    axes[axis_from:axis_to] += 1
    axes[axis_from:axis_to:-1] -= 1
    axes[axis_to] = axis_from
    return np.transpose(A, axes=axes)

def safe_indices(inds, shape):
    """
    Makes sure that indices are valid for given shape.

    The shorter shape determines the length.

    For instance,

    .. testsetup::

       from bayespy.utils.misc import safe_indices

    >>> safe_indices( (3, 4, 5), (1, 6) )
    (0, 5)
    """
    m = min(len(inds), len(shape))

    if m == 0:
        return ()

    inds = inds[-m:]
    maxinds = np.array(shape[-m:]) - 1

    return tuple(np.fmin(inds, maxinds))

def broadcasted_shape(*shapes):
    """
    Computes the resulting broadcasted shape for a given set of shapes.

    Uses the broadcasting rules of NumPy.  Raises an exception if the shapes do
    not broadcast.
    """
    dim = 0
    for a in shapes:
        dim = max(dim, len(a))
    S = ()
    for i in range(-dim,0):
        s = 1
        for a in shapes:
            if -i <= len(a):
                if s == 1:
                    s = a[i]
                elif a[i] != 1 and a[i] != s:
                    raise ValueError("Shapes %s do not broadcast" % (shapes,))
        S = S + (s,)
    return S

def broadcasted_shape_from_arrays(*arrays):
    """
    Computes the resulting broadcasted shape for a given set of arrays.

    Raises an exception if the shapes do not broadcast.
    """

    shapes = [np.shape(array) for array in arrays]
    return broadcasted_shape(*shapes)

def is_shape_subset(sub_shape, full_shape):
    """
    """
    if len(sub_shape) > len(full_shape):
        return False
    for i in range(len(sub_shape)):
        ind = -1 - i
        if sub_shape[ind] != 1 and sub_shape[ind] != full_shape[ind]:
            return False
    return True

def add_axes(X, num=1, axis=0):
    for i in range(num):
        X = np.expand_dims(X, axis=axis)
    return X
    shape = np.shape(X)[:axis] + num*(1,) + np.shape(X)[axis:]
    return np.reshape(X, shape)

def add_leading_axes(x, n):
    return add_axes(x, axis=0, num=n)

def add_trailing_axes(x, n):
    return add_axes(x, axis=-1, num=n)

## def add_axes(x, lead, trail):
##     shape = (1,)*lead + np.shape(x) + (1,)*trail
##     return np.reshape(x, shape)

def nested_iterator(max_inds):
    s = [range(i) for i in max_inds]
    return itertools.product(*s)

def first(L):
    """
    """
    for (n,l) in enumerate(L):
        if l:
            return n
    return None

def squeeze(X):
    """
    Remove leading axes that have unit length.

    For instance, a shape (1,1,4,1,3) will be reshaped to (4,1,3).
    """
    shape = np.array(np.shape(X))
    inds = np.nonzero(shape != 1)[0]
    if len(inds) == 0:
        shape = ()
    else:
        shape = shape[inds[0]:]
    return np.reshape(X, shape)

def squeeze_to_dim(X, dim):
    s = tuple(range(np.ndim(X)-dim))
    return np.squeeze(X, axis=s)

def axes_to_collapse(shape_x, shape_to):
    # Solves which axes of shape shape_x need to be collapsed in order
    # to get the shape shape_to
    s = ()
    for j in range(-len(shape_x), 0):
        if shape_x[j] != 1:
            if -j > len(shape_to) or shape_to[j] == 1:
                s += (j,)
            elif shape_to[j] != shape_x[j]:
                print('Shape from: ' + str(shape_x))
                print('Shape to: ' + str(shape_to))
                raise Exception('Incompatible shape to squeeze')
    return tuple(s)

def sum_to_shape(X, s):
    """
    Sum axes of the array such that the resulting shape is as given.

    Thus, the shape of the result will be s or an error is raised.
    """
    # First, sum and remove axes that are not in s
    if np.ndim(X) > len(s):
        axes = tuple(range(-np.ndim(X), -len(s)))
    else:
        axes = ()
    Y = np.sum(X, axis=axes)

    # Second, sum axes that are 1 in s but keep the axes
    axes = ()
    for i in range(-np.ndim(Y), 0):
        if s[i] == 1:
            if np.shape(Y)[i] > 1:
                axes = axes + (i,)
        else:
            if np.shape(Y)[i] != s[i]:
                raise ValueError("Shape %s can't be summed to shape %s" %
                                 (np.shape(X), s))
    Y = np.sum(Y, axis=axes, keepdims=True)

    return Y

def repeat_to_shape(A, s):
    # Current shape
    t = np.shape(A)
    if len(t) > len(s):
        raise Exception("Can't repeat to a smaller shape")
    # Add extra axis
    t = tuple([1]*(len(s)-len(t))) + t
    A = np.reshape(A,t)
    # Repeat
    for i in reversed(range(len(s))):
        if s[i] != t[i]:
            if t[i] != 1:
                raise Exception("Can't repeat non-singular dimensions")
            else:
                A = np.repeat(A, s[i], axis=i)
    return A

#def spinv_chol(L):

def chol(C):
    if sparse.issparse(C):
        # Sparse Cholesky decomposition (returns a Factor object)
        return cholmod.cholesky(C)
    else:
        # Dense Cholesky decomposition
        return linalg.cho_factor(C)[0]

def chol_solve(U, b):
    if isinstance(U, np.ndarray):
        if sparse.issparse(b):
            b = b.toarray()
        return linalg.cho_solve((U, False), b)
    elif isinstance(U, cholmod.Factor):
        if sparse.issparse(b):
            b = b.toarray()
        return U.solve_A(b)
    else:
        raise ValueError("Unknown type of Cholesky factor")

def chol_inv(U):
    if isinstance(U, np.ndarray):
        I = np.identity(np.shape(U)[-1])
        return linalg.cho_solve((U, False), I)
    elif isinstance(U, cholmod.Factor):
        raise NotImplementedError
        ## if sparse.issparse(b):
        ##     b = b.toarray()
        ## return U.solve_A(b)
    else:
        raise ValueError("Unknown type of Cholesky factor")

def chol_logdet(U):
    if isinstance(U, np.ndarray):
        return 2*np.sum(np.log(np.diag(U)))
    elif isinstance(U, cholmod.Factor):
        return np.sum(np.log(U.D()))
    else:
        raise ValueError("Unknown type of Cholesky factor")

def logdet_chol(U):
    if isinstance(U, np.ndarray):
        return 2*np.sum(np.log(np.diag(U)))
    elif isinstance(U, cholmod.Factor):
        return np.sum(np.log(U.D()))

def m_solve_triangular(U, B, **kwargs):
    # Allocate memory
    U = np.atleast_2d(U)
    B = np.atleast_1d(B)
    sh_u = U.shape[:-2]
    sh_b = B.shape[:-1]
    l_u = len(sh_u)
    l_b = len(sh_b)

    # Check which axis are iterated over with B along with U
    ind_b = [Ellipsis] * l_b
    l_min = min(l_u, l_b)
    jnd_b = tuple(i for i in range(-l_min,0) if sh_b[i]==sh_u[i])

    # Shape of the result (broadcasting rules)
    sh = broadcasted_shape(sh_u, sh_b)
    #out = np.zeros(np.shape(B))
    out = np.zeros(sh + B.shape[-1:])
    ## if out == None:
    ##     # Shape of the result (broadcasting rules)
    ##     sh = broadcasted_shape(sh_u, sh_b)
    ##     #out = np.zeros(np.shape(B))
    ##     out = np.zeros(sh + B.shape[-1:])
    for i in nested_iterator(np.shape(U)[:-2]):

        # The goal is to run triangular solver once for all vectors of
        # B for which the matrices of U are the same (according to the
        # broadcasting rules). Thus, we collect all the axes of B for
        # which U is singleton and form them as a 2-D matrix and then
        # run the solver once.

        # Select those axes of B for which U and B are not singleton
        for j in jnd_b:
            ind_b[j] = i[j]

        # Collect all the axes for which U is singleton
        b = B[tuple(ind_b) + (Ellipsis,)]

        # Reshape it to a 2-D (or 1-D) array
        orig_shape = b.shape
        if b.ndim > 1:
            b = b.reshape((-1, b.shape[-1]))

        # Ellipsis to all preceeding axes and ellipsis for the last
        # axis:
        if len(ind_b) < len(sh):
            ind_out = (Ellipsis,) + tuple(ind_b) + (Ellipsis,)
        else:
            ind_out = tuple(ind_b) + (Ellipsis,)

        #print('utils.m_solve_triangular', np.shape(U[i]), np.shape(b))
        out[ind_out] = linalg.solve_triangular(U[i],
                                               b.T,
                                               **kwargs).T.reshape(orig_shape)
        #out[ind_out] = out[ind_out].T.reshape(orig_shape)

    return out

def multidigamma(a, d):
    """
    Returns the derivative of the log of multivariate gamma.
    """
    return np.sum(special.digamma(a[...,None] - 0.5*np.arange(d)),
                  axis=-1)

m_digamma = multidigamma

def m_outer(A,B):
    # Computes outer product over the last axes of A and B. The other
    # axes are broadcasted. Thus, if A has shape (..., N) and B has
    # shape (..., M), then the result has shape (..., N, M)
    A = np.asanyarray(A)
    B = np.asanyarray(B)
    return A[...,np.newaxis]*B[...,np.newaxis,:]

def diagonal(A):
    return np.diagonal(A, axis1=-2, axis2=-1)

def get_diag(X, ndim=1):
    """
    Get the diagonal of an array.

    If ndim>1, take the diagonal of the last 2*ndim axes.
    """
    if ndim == 0:
        return X

    if ndim < 0:
        raise ValueError("Parameter ndim must be non-negative integer")

    if np.ndim(X) < 2*ndim:
        raise ValueError("The array does not have enough axes")

    if np.shape(X)[-ndim:] != np.shape(X)[-2*ndim:-ndim]:
        raise ValueError("The array X is not square")

    axes_out = tuple(range(np.ndim(X)-ndim, 0, -1))
    axes_dim = tuple(range(ndim, 0, -1))
    return np.einsum(X, axes_out+axes_dim, axes_out)

def diag(X, ndim=1):
    """
    Create a diagonal array given the diagonal elements.

    The diagonal array can be multi-dimensional. By default, the last axis is
    transformed to two axes (diagonal matrix) but this can be changed using ndim
    keyword. For instance, an array with shape (K,L,M,N) can be transformed to a
    set of diagonal 4-D tensors with shape (K,L,M,N,M,N) by giving ndim=2. If
    ndim=3, the result has shape (K,L,M,N,L,M,N), and so on.

    Diagonality means that for the resulting array Y holds:
    Y[...,i_1,i_2,..,i_ndim,j_1,j_2,..,j_ndim] is zero if i_n!=j_n for any n.
    """
    X = atleast_nd(X, ndim)
    if ndim > 0:
        I = identity(*(np.shape(X)[-ndim:]))
        X = add_axes(X, axis=np.ndim(X), num=ndim)
        X = I * X
    return X

def m_dot(A,b):
    # Compute matrix-vector product over the last two axes of A and
    # the last axes of b.  Other axes are broadcasted. If A has shape
    # (..., M, N) and b has shape (..., N), then the result has shape
    # (..., M)

    #b = reshape(b, shape(b)[:-1] + (1,) + shape(b)[-1:])
    #return np.dot(A, b)
    return np.einsum('...ik,...k->...i', A, b)
    # TODO: Use einsum!!
    #return np.sum(A*b[...,np.newaxis,:], axis=(-1,))

def block_banded(D, B):
    """
    Construct a symmetric block-banded matrix.

    `D` contains square diagonal blocks.
    `B` contains super-diagonal blocks.

    The resulting matrix is:

    D[0],   B[0],   0,    0,    ..., 0,        0,        0
    B[0].T, D[1],   B[1], 0,    ..., 0,        0,        0
    0,      B[1].T, D[2], B[2], ..., ...,      ...,      ...
    ...     ...     ...   ...   ..., B[N-2].T, D[N-1],   B[N-1]
    0,      0,      0,    0,    ..., 0,        B[N-1].T, D[N]

    """

    D = [np.atleast_2d(d) for d in D]
    B = [np.atleast_2d(b) for b in B]

    # Number of diagonal blocks
    N = len(D)

    if len(B) != N-1:
        raise ValueError("The number of super-diagonal blocks must contain "
                         "exactly one block less than the number of diagonal "
                         "blocks")

    # Compute the size of the full matrix
    M = 0
    for i in range(N):
        if np.ndim(D[i]) != 2:
            raise ValueError("Blocks must be 2 dimensional arrays")
        d = np.shape(D[i])
        if d[0] != d[1]:
            raise ValueError("Diagonal blocks must be square")
        M += d[0]

    for i in range(N-1):
        if np.ndim(B[i]) != 2:
            raise ValueError("Blocks must be 2 dimensional arrays")
        b = np.shape(B[i])
        if b[0] != np.shape(D[i])[1] or b[1] != np.shape(D[i+1])[0]:
            raise ValueError("Shapes of the super-diagonal blocks do not match "
                             "the shapes of the diagonal blocks")

    A = np.zeros((M,M))
    k = 0

    for i in range(N-1):
        (d0, d1) = np.shape(B[i])
        # Diagonal block
        A[k:k+d0, k:k+d0] = D[i]
        # Super-diagonal block
        A[k:k+d0, k+d0:k+d0+d1] = B[i]
        # Sub-diagonal block
        A[k+d0:k+d0+d1, k:k+d0] = B[i].T

        k += d0
    A[k:,k:] = D[-1]

    return A

def kalman_filter(y, U, A, V, mu0, Cov0, out=None):
    """
    Perform Kalman filtering to obtain filtered mean and covariance.

    The parameters of the process may vary in time, thus they are
    given as iterators instead of fixed values.

    Parameters
    ----------
    y : (N,D) array
        "Normalized" noisy observations of the states, that is, the
        observations multiplied by the precision matrix U (and possibly
        other transformation matrices).
    U : (N,D,D) array or N-list of (D,D) arrays
        Precision matrix (i.e., inverse covariance matrix) of the observation
        noise for each time instance.
    A : (N-1,D,D) array or (N-1)-list of (D,D) arrays
        Dynamic matrix for each time instance.
    V : (N-1,D,D) array or (N-1)-list of (D,D) arrays
        Covariance matrix of the innovation noise for each time instance.

    Returns
    -------
    mu : array
        Filtered mean of the states.
    Cov : array
        Filtered covariance of the states.

    See also
    --------
    rts_smoother
    """
    mu = mu0
    Cov = Cov0

    # Allocate memory for the results
    (N,D) = np.shape(y)
    X = np.empty((N,D))
    CovX = np.empty((N,D,D))

    # Update step for t=0
    M = np.dot(np.dot(Cov, U[0]), Cov) + Cov
    L = chol(M)
    mu = np.dot(Cov, chol_solve(L, np.dot(Cov,y[0]) + mu))
    Cov = np.dot(Cov, chol_solve(L, Cov))
    X[0,:] = mu
    CovX[0,:,:] = Cov

    #for (yn, Un, An, Vn) in zip(y, U, A, V):
    for n in range(len(y)-1): #(yn, Un, An, Vn) in zip(y, U, A, V):
        # Prediction step
        mu = np.dot(A[n], mu)
        Cov = np.dot(np.dot(A[n], Cov), A[n].T) + V[n]
        # Update step
        M = np.dot(np.dot(Cov, U[n+1]), Cov) + Cov
        L = chol(M)
        mu = np.dot(Cov, chol_solve(L, np.dot(Cov,y[n+1]) + mu))
        Cov = np.dot(Cov, chol_solve(L, Cov))

        # Force symmetric covariance (for numeric inaccuracy)
        Cov = 0.5*Cov + 0.5*Cov.T

        # Store results
        X[n+1,:] = mu
        CovX[n+1,:,:] = Cov

    return (X, CovX)

def rts_smoother(mu, Cov, A, V, removethis=None):
    """
    Perform Rauch-Tung-Striebel smoothing to obtain the posterior.

    The function returns the posterior mean and covariance of each
    state. The parameters of the process may vary in time, thus they
    are given as iterators instead of fixed values.

    Parameters
    ----------
    mu : (N,D) array
        Mean of the states from Kalman filter.
    Cov : (N,D,D) array
        Covariance of the states from Kalman filter.
    A : (N-1,D,D) array or (N-1)-list of (D,D) arrays
        Dynamic matrix for each time instance.
    V : (N-1,D,D) array or (N-1)-list of (D,D) arrays
        Covariance matrix of the innovation noise for each time instance.

    Returns
    -------
    mu : array
        Posterior mean of the states.
    Cov : array
        Posterior covariance of the states.

    See also
    --------
    kalman_filter
    """

    N = len(mu)
    #n = N-1

    # Start from the last time instance and smoothen backwards
    x = mu[-1,:]
    Covx = Cov[-1,:,:]

    for n in reversed(range(N-1)):#(An, Vn) in zip(reversed(A), reversed(V)):

        #n = n - 1
        #if n <= 0:
        #    break

        # The predicted value of n
        x_p = np.dot(A[n], mu[n,:])
        Cov_p = np.dot(np.dot(A[n], Cov[n,:,:]), A[n].T) + V[n]

        # Temporary variable
        S = np.linalg.solve(Cov_p, np.dot(A[n], Cov[n,:,:]))

        # Smoothed value of n
        x = mu[n,:] + np.dot(S.T, x-x_p)
        Covx = Cov[n,:,:] + np.dot(np.dot(S.T, Covx-Cov_p), S)

        # Force symmetric covariance (for numeric inaccuracy)
        Covx = 0.5*Covx + 0.5*Covx.T

        # Store results
        mu[n,:] = x
        Cov[n,:] = Covx

    return (mu, Cov)

def dist_haversine(c1, c2, radius=6372795):

    # Convert coordinates to radians
    lat1 = np.atleast_1d(c1[0])[...,:,None] * np.pi / 180
    lon1 = np.atleast_1d(c1[1])[...,:,None] * np.pi / 180
    lat2 = np.atleast_1d(c2[0])[...,None,:] * np.pi / 180
    lon2 = np.atleast_1d(c2[1])[...,None,:] * np.pi / 180

    dlat = lat2 - lat1
    dlon = lon2 - lon1

    A = np.sin(dlat/2)**2 + np.cos(lat1)*np.cos(lat2)*(np.sin(dlon/2)**2)
    C = 2 * np.arctan2(np.sqrt(A), np.sqrt(1-A))

    return radius * C

def logsumexp(X, axis=None, keepdims=False):
    """
    Compute log(sum(exp(X)) in a numerically stable way
    """

    X = np.asanyarray(X)

    maxX = np.amax(X, axis=axis, keepdims=True)

    if np.ndim(maxX) > 0:
        maxX[~np.isfinite(maxX)] = 0
    elif not np.isfinite(maxX):
        maxX = 0

    X = X - maxX

    if not keepdims:
        maxX = np.squeeze(maxX, axis=axis)

    return np.log(np.sum(np.exp(X), axis=axis, keepdims=keepdims)) + maxX

def invpsi(x):
    r"""
    Inverse digamma (psi) function.

    The digamma function is the derivative of the log gamma function.
    This calculates the value Y > 0 for a value X such that digamma(Y) = X.

    See: http://www4.ncsu.edu/~pfackler/
    """
    L = 1.0
    y = np.exp(x)
    while (L > 1e-10):
        y += L*np.sign(x-special.psi(y))
        L /= 2
    # Ad hoc by Jaakko
    y[x<-10] = -1/x[x<-10]
    return y

def invgamma(x):
    r"""
    Inverse gamma function.

    See: http://mathoverflow.net/a/28977
    """
    k = 1.461632
    c = 0.036534
    L = np.log((x+c)/np.sqrt(2*np.pi))
    W = special.lambertw(L/np.exp(1))
    return L/W + 0.5

def mean(X, axis=None, keepdims=False):
    """
    Compute the mean, ignoring NaNs.
    """
    if np.ndim(X) == 0:
        if axis is not None:
            raise ValueError("Axis out of bounds")
        return X
    X = np.asanyarray(X)
    nans = np.isnan(X)
    X = X.copy()
    X[nans] = 0
    m = (np.sum(X, axis=axis, keepdims=keepdims) /
         np.sum(~nans, axis=axis, keepdims=keepdims))
    return m

redpajama_set_name: RedPajamaGithub


text:
<#
  Copyright 2014 ASOS.com Limited

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
#>

function Get-RoleAttributes {

  <#

  .SYNOPSIS
    Using the role list get the attributes

  .DESCRIPTION
    Function to reverse the order of the roles so that the attributes are resolved in such
    a way that the last role wins.

  #>

  # If in debug mode, show the function currently in
  Write-Log -IfDebug -Message $("***** {0} *****" -f $MyInvocation.MyCommand)

  # Get the list of roles from the session and reverse it
  $roles = $script:session.roles
  [array]::Reverse($roles)

  # Remove duplicates in the roles array
  $roles = $roles | Select -Unique

  # Iterate around the roles
  foreach ($role in $roles) {

    if ($role -match "(.*)?\[(.*)\]") {

      # get the run list type and the name of the item
      $role_name = $matches[2]

      # Call the function to get the named role
      $role = Get-Role -name $role_name

      # if the role is false do not merge
      if ($role -ne $false) {

        # The attributes for the role need to be merged with the ones already retrieved
        # these are currently in the session object
        # Attributes of the same name in different roles will be overridden
        # The last role to have the same setting will win
        $merged = Merge-Hashtables -primary $role.default_attributes -secondary $script:session.attributes.roles
        $script:session.attributes.roles = $merged
      }
    }
  }

  # Set the list of roles in the session
  $script:session.roles = $roles

}


text:
# 0.5.0 (2016-08-30)

### Note
Not all packages used in ng2-admin support RC5 at the moment, so we suggest waiting until ng2-admin@0.5.1 version for a complete support of RC5.

### Features

* Angular rc.5 (ngModule)
* Webpack 2
* Dependencies updated

### Bug Fixes

### Breaking changes

Things to consider:

* We introduced NgaModule - wrapper for all ng2-admin features. At the moment it includes everything (directives, services, configs, etc). But, the important thing is that we are planning to refactor it and divide into smaller modules, so that if you don't need a whole list of features somewhere in your code - you can simply import a smaller part. [Here are some more details](https://github.com/akveo/ng2-admin/issues/179).
* Each page section now is a module (Feature Module as per angular documents) wrapped in pages.module.
* Routes configuration (again :( ) moved from one complete file to modules (page sections) configurations. Thus we just left menu configuration as it was before (in one file), just renamed it into app.menu.ts.
* We are planning to continue code refactoring and planning to change component names to follow angular recommendations. Thus we strongly recommend to not import Ba* directives directly and use NgaModule which will encapsulate the changes we are going to make. [Here are some more details](https://github.com/akveo/ng2-admin/issues/179).

### How to update

* Read Angluar RC4 -> RC5 [migration guide](https://angular.io/docs/ts/latest/cookbook/rc4-to-rc5.html)
* Pull sources from git, merge accordingly
* remove `node_modules`
* run `npm install`
* Wrap all your pages into modules, register them in the PagesModule
* Create separate routing files per module
* Remove all direct imports of Ba* components, directives, pipes, etc, instead change your modules the way to import NgaModule
* Enjoy!

# 0.4.4 (2016-08-29)

### Features

* Missed new component [ng2-smart-table](https://akveo.github.io/ng2-smart-table/) - [demo](http://akveo.com/ng2-admin/#/pages/tables/smarttables)

### How to update

* Pull sources from git
* run `npm install`

# 0.4.3 (2016-08-23)

### Bug Fixes

* Fix leaflet maps styles
* Fix license
* Remove tracing of typings (thanks to @GRoguelon)
* Update baContentTop to work with routerLink (thanks to @Kaizeras)
* Fix Chartist to handle data update dynamically (thanks to @bnayalivne)

### Features

* Finally get rid of bower (thanks to @GRoguelon)
* New component [ng2-smart-table](https://akveo.github.io/ng2-smart-table/) - [demo](http://akveo.com/ng2-admin/#/pages/tables/smarttables)

### How to update

* Pull sources from git
* run `npm install`

# 0.4.2 (2016-07-28)

### Bug Fixes

* Fix menu and router configuration
* Fix broken dependencies

### Features

* Dependencies updated
* Use @types instead of typings

### BREAKING CHANGES

* Typings were removed, now we use @types instead, more details [here](https://github.com/AngularClass/angular2-webpack-starter#types)

### How to update

* Remove node_modules folder
* Remove typings folder and move all custom typings to package.json
* run `npm install`

# 0.4.0 (2016-07-12)

### Bug Fixes

* Make source files generated correctly (thanks to @AlbertXingZhang)
* Fix docker configuration (thanks to @gavinzhou)

### Features

* Angular updated to rc.4
* Dependencies updated accordingly
* Angular Component Router instead or Router Deprecated (thanks to @RonnyRoos)
* New Angular Forms
* Sidebar rewritten, menu merged with routes configuration
* New CKEditor component
* New Image Uploader component
* New Tree view component
* New Rating component
* New Checkbox and multi-checkbox component

### BREAKING CHANGES

* Router is updated to Angular Router Component. Old beta router is removed.
That means that all the routes are moved to the `src/app/app.routes.ts` file. `src/app/app.menu.ts` is also merged into the routes configuration.
More details on how to configure a new route you can find [here](https://akveo.github.io/ng2-admin/articles/015-sidebar/).

* Forms are updated as well. Thus you need to reconfigure all your forms to use new Angular Forms. Checkout the `src/app/pages/login/login.component.ts`component for more details and example.

### How to update

* run `npm install`

# 0.3.0 (2016-06-29)

### Bug Fixes

* Sidebar menu angle fixed
* Sidebar menu selected item fixed

### Features

* Angular updated to rc.3
* Dependencies updated accordingly

### How to update

* Remove `node_modules` and `typings` folders
* run `npm install`

# 0.2.1 (2016-06-21)

### Bug Fixes

* Multiple bugfixes

### Features

* Angular updated to rc.2
* Dependencies updated accordingly
* Login page component [Demo](http://akveo.com/ng2-admin/#/login)
* Sign up page component [Demo](http://akveo.com/ng2-admin/#/register)

### BREAKING CHANGES
* `$` renamed to `jQuery` because of name resolution conflicts

### How to update

* Remove `node_modules` and `typings` folders
* run `npm install`


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright (c) 2001 World Wide Web Consortium,
(Massachusetts Institute of Technology, Institut National de
Recherche en Informatique et en Automatique, Keio University). All
Rights Reserved. This program is distributed under the W3C's Software
Intellectual Property License. This program is distributed in the
hope that it will be useful, but WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.
See W3C License http://www.w3.org/Consortium/Legal/ for more details.
--><!DOCTYPE test SYSTEM "dom1.dtd">

<test xmlns="http://www.w3.org/2001/DOM-Test-Suite/Level-1" name="hc_nodedocumentnodetype">
<metadata>
<title>hc_nodeDocumentNodeType</title>
<creator>Curt Arnold</creator>
<description>
The "getNodeType()" method for a Document Node
returns the constant value 9.

Retrieve the document and invoke the "getNodeType()"
method.   The method should return 9.
</description>

<date qualifier="created">2002-06-09</date>
<!-- Document interface -->
<subject resource="http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core#i-Document"/>
<subject resource="http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core#ID-111237558"/>
</metadata>
<var name="doc" type="Document"/>
<var name="nodeType" type="int"/>
<load var="doc" href="hc_staff" willBeModified="false"/>
<nodeType obj="doc" var="nodeType"/>
<assertEquals actual="nodeType" expected="9" id="nodeDocumentNodeTypeAssert1" ignoreCase="false"/>
</test>


text:
from lib.action import PagerDutyAction

class ResolveIncident(PagerDutyAction):
    def run(self, event_keys):
        """
        Resolve an incident, You can provide comma(,) separated keys for resolving more events at
        once.
        """
        for arg in event_keys:
            self.pager.resolve_incident(self.config['service_api'], arg)

        return event_keys


text:
#ifndef PC_TEST_FRAMEGENERATORCAPTURERVIDEOTRACKSOURCE_H_
#define PC_TEST_FRAMEGENERATORCAPTURERVIDEOTRACKSOURCE_H_

#include <memory>

#include BOSS_WEBRTC_U_pc__videotracksource_h //original-code:"pc/videotracksource.h"
#include "test/frame_generator_capturer.h"

namespace webrtc {

// Implements a VideoTrackSourceInterface to be used for creating VideoTracks.
// The video source is generated using a FrameGeneratorCapturer, specifically
// a SquareGenerator that generates frames with randomly sized and colored
// squares.
class FrameGeneratorCapturerVideoTrackSource : public VideoTrackSource {
 public:
  static const int kDefaultFramesPerSecond = 30;
  static const int kDefaultWidth = 640;
  static const int kDefaultHeight = 480;
  static const int kNumSquaresGenerated = 50;

  struct Config {
    int frames_per_second = kDefaultFramesPerSecond;
    int width = kDefaultWidth;
    int height = kDefaultHeight;
    int num_squares_generated = 50;
  };

  explicit FrameGeneratorCapturerVideoTrackSource(Clock* clock)
      : FrameGeneratorCapturerVideoTrackSource(Config(), clock) {}

  FrameGeneratorCapturerVideoTrackSource(Config config, Clock* clock)
      : VideoTrackSource(false /* remote */) {
    video_capturer_.reset(test::FrameGeneratorCapturer::Create(
        config.width, config.height, absl::nullopt,
        config.num_squares_generated, config.frames_per_second, clock));
  }

  ~FrameGeneratorCapturerVideoTrackSource() = default;

  void Start() {
    video_capturer_->Start();
    SetState(kLive);
  }

  void Stop() {
    video_capturer_->Stop();
    SetState(kMuted);
  }

 protected:
  rtc::VideoSourceInterface<VideoFrame>* source() override {
    return video_capturer_.get();
  }

 private:
  std::unique_ptr<test::FrameGeneratorCapturer> video_capturer_;
};

}  // namespace webrtc

#endif  // PC_TEST_FRAMEGENERATORCAPTURERVIDEOTRACKSOURCE_H_


text:
typedef uint16_t zeevoId_t;
typedef uint16_t userId_t;
typedef uint8_t magicNum_t ;

typedef struct{
  userId_t ID;
  uint16_t size;
}FileInfo;

#define FS_DEBUG

#ifdef FS_DEBUG
//#define WRITE_CRASH_ID 666 //(this is for testing boot crash)
//#define MAX_ZEEVO_IDS 4 // this is for testing failure of zeevo
                        //id distribution

#endif


text:
package dms_enterprise

//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

// DatabaseInfo is a nested struct in dms_enterprise response
type DatabaseInfo struct {
	DbId           int64    `json:"DbId" xml:"DbId"`
	Logic          bool     `json:"Logic" xml:"Logic"`
	DbType         string   `json:"DbType" xml:"DbType"`
	SearchName     string   `json:"SearchName" xml:"SearchName"`
	EnvType        string   `json:"EnvType" xml:"EnvType"`
	OwnerIds       []int64  `json:"OwnerIds" xml:"OwnerIds"`
	OwnerNickNames []string `json:"OwnerNickNames" xml:"OwnerNickNames"`
}


text:
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    ×
                </button>

Change Password

                <form id="changePasswordForm" role="form">

                        Old Password
                        <input type="password" class="form-control" id="inputOldPassword" required>

                        New Password
                        <input type="password" class="form-control" id="inputNewPassword" required>

                        Confirm New Password
                        <input type="password" class="form-control" id="inputConfirmNewPassword" required>

                    <button type="submit" class="hidden" id="theSubmit"></button>
                </form>

                <button type="button" id="cancelButton" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" id="submitButton" class="btn btn-primary">Submit</button>


text:
title: Web-basierte Anwendungen 1 - WWW Technologien
modulverantwortlich: Herr Prof. Christian Noss
modulniveau:
kuezel: WBA1
untertitel:
studiensemester: 3
kategorie:
sprache: deutsch
zuordnung-zum-curriculum: Medieninformatik Bachelor
kreditpunkte: 5
voraussetzungen-nach-pruefungsordnung: Abgeschlossenes Grundstudium
empfohlene-voraussetzungen: Für das Praktikum sollte sicher mit OS X umgegangen werden können. Ein eigener Account auf der advm1 sollte vorhanden sein.
published: true
---

## Lehrform/SWS:
Vorlesung, Praktikum

## Arbeitsaufwand:

## Angestrebte Lernergebnisse:
Die Studierenden sollen die technischen Grundlagen des WWW sowie die wesentlichen Meilensteine bei der Entstehung desselben kennen. Netzbasierte Anwendungen sollen beurteilt sowie deren Vor- und Nachteile im Vergleich mit anderen Medien argumentiert werden können. Grundlegende Konzepte und Technologien des WWW sollen verstanden und angewendet werden können. Eigene Projekte sollen unter Einsatz von (X)HTML, XML, CSS und Javascript konzipiert und realisiert werden können.

## Inhalt:
technische Grundlagen

Geschichte

Anwendungsgebiete für NBAs

(X)HTML, CSS und Javascript

XML, DTD und XSL

Web 2.0, Ajax und Co.

Information, Navigation, Transaktion

Barrierefreiheit

Suchmaschinenoptimierung

## Studien-/Prüfungsleistungen:
Klausur mit Teilnahmeschein für das Praktikum als Prüfungsvorleistung. Alle Inhalte aus Vorlesung und Praktikum sind prüfungsrelevant.

## Medienformen:

## Literatur:
Cederholm, Dan: Bulletproof Webdesign, München: Addison-Wesley, 2006

Stefan Münz und andere: SelfHTML.. URL [http://de.selfhtml.org] Stand 04.2009

Michael Jendryschik: Einführung in XHTML, CSS und Webdesign. URL [http://jendryschik.de/wsdev/einfuehrung/] Stand 06.2008

Wendy Chisholm, Gregg Vanderheiden, Ian Jacobs: Zugänglichkeitsrichtlinien des W3C, URL[http://www.w3c.de/Trans/WAI/webinhalt.html] Stand 02.2002


text:
namespace Cronofy.Test.CronofyEnterpriseConnectAccountClientTests
{
    using System;
    using System.Collections.Generic;
    using NUnit.Framework;

    internal sealed class AuthorizeUser : Base
    {
        [Test]
        public void CanAuthorizeUser()
        {
            const string email = "test@cronofy.com";
            const string callbackUrl = "https://cronofy.com/test-callback";
            const string scopes = "read_account list_calendars read_events create_event delete_event read_free_busy";

            this.Http.Stub(
                HttpPost
                .Url("https://api.cronofy.com/v1/service_account_authorizations")
                .RequestHeader("Authorization", "Bearer " + AccessToken)
                .RequestHeader("Content-Type", "application/json; charset=utf-8")
                .RequestBodyFormat(
                    "{{\"email\":\"{0}\"," +
                    "\"callback_url\":\"{1}\"," +
                    "\"scope\":\"{2}\"" +
                    "}}",
                    email,
                    callbackUrl,
                    scopes)
                .ResponseCode(202));

            this.Client.AuthorizeUser(email, callbackUrl, scopes);
        }

        [Test]
        public void CanAuthorizeMultipleUsers()
        {
            const string email = "test@cronofy.com";
            const string callbackUrl = "https://cronofy.com/test-callback";
            const string scope = "read_account list_calendars read_events create_event delete_event read_free_busy";
            const string state = "nggyu";

            this.Http.Stub(
                HttpPost
                .Url("https://api.cronofy.com/v1/service_account_authorizations")
                .RequestHeader("Authorization", "Bearer " + AccessToken)
                .RequestHeader("Content-Type", "application/json; charset=utf-8")
                .RequestBodyFormat(
                    "{{\"service_account_authorizations\":[" +
                    "{{\"email\":\"{0}\"," +
                    "\"callback_url\":\"{1}\"," +
                    "\"scope\":\"{2}\"," +
                    "\"state\":\"{3}\"" +
                    "}}" +
                    "]}}",
                    email,
                    callbackUrl,
                    scope,
                    state)
                .ResponseCode(202));

            var options = new List<EnterpriseConnectAuthorizeUserOptions>
            {
                new EnterpriseConnectAuthorizeUserOptions
                {
                    Email = email,
                    CallbackUrl = callbackUrl,
                    Scope = scope,
                    State = state,
                },
            };

            this.Client.AuthorizeUsers(options);
        }

        [Test]
        public void CanAuthorizeUserWithState()
        {
            const string email = "test@cronofy.com";
            const string callbackUrl = "https://cronofy.com/test-callback";
            const string scopes = "read_account list_calendars read_events create_event delete_event read_free_busy";
            const string state = "customers-state-value";

            this.Http.Stub(
                HttpPost
                .Url("https://api.cronofy.com/v1/service_account_authorizations")
                .RequestHeader("Authorization", "Bearer " + AccessToken)
                .RequestHeader("Content-Type", "application/json; charset=utf-8")
                .RequestBodyFormat(
                    "{{\"email\":\"{0}\"," +
                    "\"callback_url\":\"{1}\"," +
                    "\"scope\":\"{2}\"," +
                    "\"state\":\"{3}\"" +
                    "}}",
                    email,
                    callbackUrl,
                    scopes,
                    state)
                .ResponseCode(202));

            this.Client.AuthorizeUser(email, callbackUrl, scopes, state);
        }

        [Test]
        public void CanAuthorizeUserForSpecificDataCenter()
        {
            this.Client = new CronofyEnterpriseConnectAccountClient(AccessToken, "de");
            this.Client.HttpClient = this.Http;

            const string email = "test@cronofy.com";
            const string callbackUrl = "https://cronofy.com/test-callback";
            const string scopes = "read_account list_calendars read_events create_event delete_event read_free_busy";

            this.Http.Stub(
                HttpPost
                .Url("https://api-de.cronofy.com/v1/service_account_authorizations")
                .RequestHeader("Authorization", "Bearer " + AccessToken)
                .RequestHeader("Content-Type", "application/json; charset=utf-8")
                .RequestBodyFormat(
                    "{{\"email\":\"{0}\"," +
                    "\"callback_url\":\"{1}\"," +
                    "\"scope\":\"{2}\"" +
                    "}}",
                    email,
                    callbackUrl,
                    scopes)
                .ResponseCode(202));

            this.Client.AuthorizeUser(email, callbackUrl, scopes);
        }

        [Test]
        public void CanAuthorizeUserWithEnumerableScopes()
        {
            const string email = "test@test.com";
            const string callbackUrl = "https://test.com/test-callback";
            string[] scopes = { "read_account", "list_calendars", "read_events", "create_event", "delete_event", "read_free_busy" };

            this.Http.Stub(
                HttpPost
                .Url("https://api.cronofy.com/v1/service_account_authorizations")
                .RequestHeader("Authorization", "Bearer " + AccessToken)
                .RequestHeader("Content-Type", "application/json; charset=utf-8")
                .RequestBodyFormat(
                    "{{\"email\":\"{0}\"," +
                    "\"callback_url\":\"{1}\"," +
                    "\"scope\":\"{2}\"" +
                    "}}",
                    email,
                    callbackUrl,
                    string.Join(" ", scopes))
                .ResponseCode(202));

            this.Client.AuthorizeUser(email, callbackUrl, scopes);
        }
    }
}


text:
Minimalistic auto-scaling for Unicorn.

## Installation

Add this line to your application's Gemfile:

    gem 'unicorn-autoscaling', require: false

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install unicorn-autoscaling

## Usage

Add the following `require` to your unicorn configuration file:

    require 'unicorn/autoscaling'

And enable autoscaling by adding:

    autoscaling true

## Configuration options

    autoscaling true

    autoscale_idle_time_decrement 30

    autoscale_idle_time_increment 10

    autoscale_idle_time_samples 20

    autoscale_check_interval 10

    autoscale_min_workers 4

    autoscale_max_workers 16

## Contributing

1. Fork it ( https://github.com/ydkn/unicorn-autoscaling/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request


text:
[![Build Status][ico-build]][link-build]
[![Coverage Status][ico-coverage]][link-coverage]

The bundle extends LDAP authentication of the Symfony LDAP component with the ability to automatically create / fetch users from eg. a database. This enables you to (easily) add LDAP authentication to existing authentication bundles.

## Installation using Composer
Run the following command to add the package to the composer.json of your project:

``` bash
$ composer require connectholland/ldap-bundle
```

### Enable the bundle
Enable the bundle in the kernel:

``` php
// app/AppKernel.php

public function registerBundles()
{
    $bundles = array(
        // ...
        new ConnectHolland\LdapBundle\ConnectHollandLdapBundle(),
        // ...
    );
}
```

## Configuring the bundle
The bundle requires the following configuration to function in your `security.yml` file:

``` yaml
# app/config/security.yml
security:
    # ...

    providers:
        my_ldap:
            connect_holland_ldap: # Configuration part of this bundle.
                connection:
                    host: ldap.example.com
                user_factory:
                    type: doctrine # Currently 2 types available (doctrine and sulu). Custom user factories can be defined through a 'service' key with the id of the service.
                    user_class: 'AppBundle\Entity\User'
                    username_column: username
                    user_property_map: # Mapping of LDAP attributes (keys) to user properties (values).
                        uid: username
                        givenname: firstname
                        sn: lastname
                        mail: email
                base_dn: ou=users,dc=example,dc=com
                search_dn: ~
                search_password: ~
                default_roles:
                    - ROLE_ADMIN
                uid_key: uid

    firewalls:
        somename:
            # ...
            form_login_ldap:
                provider: my_ldap
                service: security.user.provider.concrete.my_ldap.client # Service created by the bundle.
                dn_string: 'uid={username},ou=users,dc=example,dc=com'
```

For more information and a detailed description of the various options, see [Authenticating against an LDAP server](https://symfony.com/doc/2.8/security/ldap.html) within the Symfony documentation.

### Configuring the bundle for Sulu CMS
To add LDAP authentication to Sulu CMS add the following configuration to `app/config/admin/security.yml`:
``` yaml
# app/config/admin/security.yml

security:
    # ...

    ldap:
        connect_holland_ldap: # Configuration part of this bundle.
            connection:
                host: ldap.example.com
            user_factory:
                type: sulu
                user_property_map: # Mapping of LDAP attributes (keys) to user properties (values).
                    uid: username
                    givenname: contact.first_name
                    sn: contact.last_name
                    mail: email
            base_dn: ou=users,dc=example,dc=com
            search_dn: ~
            search_password: ~
            default_roles:
                - User # The name of the role within your Sulu CMS.
            uid_key: uid

    firewalls:
        admin:
            # ...

            form_login_ldap:
                login_path: sulu_admin.login
                check_path: sulu_admin.login_check
                success_handler: sulu_security.authentication_handler
                failure_handler: sulu_security.authentication_handler
                csrf_provider: security.csrf.token_manager
                provider: ldap
                service: security.user.provider.concrete.ldap.client
                dn_string: 'uid={username},ou=users,dc=example,dc=com'
```

Adjust the settings within `connect_holland_ldap` according to your LDAP configuration.

## Configuration reference
``` yaml
connect_holland_ldap:
    connection:
        host: ldap.example.com
        port: 389
        encryption: ssl # tls or ssl
        options:
            protocol_version: 3
            referrals: false
    user_factory:
        type: sulu # doctrine or sulu
        service: ~ # Reference to your own user factory service.
        user_class: ~ # Fully qualified class name of your user entity. Only used for doctrine user factory type.
        username_column: ~ # Name of the username column. Only used for doctrine user factory type.
        user_property_map: # Mapping of LDAP attributes (keys) to user properties (values).
            uid: username
            givenname: firstname
            sn: lastname
            mail: email
    base_dn: ~
    search_dn: ~
    search_password: ~
    default_roles:
        - ~
    uid_key: sAMAccountName
    filter: '({uid_key}={username})'
```

[ico-build]: https://travis-ci.org/ConnectHolland/ldap-bundle.svg
[ico-coverage]: https://coveralls.io/repos/github/ConnectHolland/ldap-bundle/badge.svg

[link-build]: https://travis-ci.org/ConnectHolland/ldap-bundle
[link-coverage]: https://coveralls.io/github/ConnectHolland/ldap-bundle


text:
<!doctype html>
<html>
    <head>
        <title>Shooting astronaut</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <style type="text/css">
            html {
                background: #1e1f21;
            }
            canvas {
                margin: 0 auto;
                display: block;
                background: #252729;
            }
        </style>
        <script type="text/javascript" src="bower_components/easeljs/lib/easeljs-0.8.1.min.js"></script>
        <script type="text/javascript" src="bower_components/createjs-tweenjs/lib/tweenjs-0.6.1.min.js"></script>
        <script type="text/javascript" src="bower_components/createjs-preloadjs/lib/preloadjs-0.6.1.min.js"></script>

        <script type="text/javascript" src="app.js" ></script>
    </head>
    <body onload="init();">
        <canvas id="demoCanvas" width="960" height="950" ></canvas>

    </body>
</html>


text:
alter table TAB_INDEX drop constraint ID_NUMMER_PK_PK;
alter table TAB_INDEX drop constraint ID_NUMMER_MOD_UK_UK;
alter table TAB_INDEX drop constraint ID_NUMMER_MOD_UK_UK_DEF;
alter table TAB_INDEX add ID_NUMMER_INT NUMBER(15) not null;
alter table TAB_INDEX add ID_NUMMER_EXT NUMBER(15) not null;
alter table TAB_INDEX add ID_NUMMER_UK NUMBER(15) not null;
alter table TAB_INDEX add constraint ID_NUMMER_PK_PK primary key (ID_NUMMER_PK) using index tablespace TABLESPACE1;
create index ID_NUMMER_INT_IX on TAB_INDEX ( ID_NUMMER_INT ) tablespace TABLESPACE1 parallel;
alter index ID_NUMMER_INT_IX noparallel;
alter index MOD_TABSPACE_IX rebuild tablespace TABLESPACE2;
alter index MOD_TABSPACE_REVERSE_IX rebuild tablespace TABLESPACE1;
alter index MOD_TABSPACE_DEF_IX rebuild tablespace TABLESPACE1;
alter index MOD_TABSPACE_REVERSE_DEF_IX rebuild tablespace null;
create index ID_NUMMER_EXT_IX on TAB_INDEX ( ID_NUMMER_EXT ) tablespace TABLESPACE1 parallel;
alter index ID_NUMMER_EXT_IX noparallel;
alter table TAB_INDEX add constraint ID_NUMMER_MOD_UK_UK unique (ID_NUMMER_MOD_UK) using index tablespace TABLESPACE2;
alter table TAB_INDEX add constraint ID_NUMMER_UK_UK unique (ID_NUMMER_UK) using index tablespace TABLESPACE1;
alter table TAB_INDEX add constraint ID_NUMMER_MOD_UK_UK_DEF unique (ID_NUMMER_MOD_UK_DEF);


text:
<?xml version="1.0" encoding="UTF-8"?>
<TestPlan>
   <Test>11733/submit</Test>
   <Rule>R.a Accept register one document</Rule>
    <TestStep id="submit">
        <ExpectedStatus>Success</ExpectedStatus>
        <RegisterTransaction>
            <XDSa/>
            <MetadataFile>single_doc.xml</MetadataFile>
        </RegisterTransaction>
    </TestStep>
    <TestStep id="submit_split_uri">
        <ExpectedStatus>Success</ExpectedStatus>
        <RegisterTransaction>
            <XDSa/>
            <MetadataFile>single_doc_split_uri.xml</MetadataFile>
        </RegisterTransaction>
    </TestStep>
</TestPlan>


text:
A nice WordPress theme presenting Eat Your Coffee project.
Visit the [website](#)

## Authors

[![forthebadge](http://forthebadge.com/images/badges/built-with-love.svg)](#)

This project was lead by :
- [Lisa Fises](https://github.com/lisafises)

It was designed thanks to :
- [Johanna Nguyen](https://dribbble.com/JohanakinSkywalker)
- Charlotte Sieess
- [David Salobir](https://dribbble.com/davidsalobir)

It was developed thanks to :
- [Lisa Fises](https://github.com/lisafises)
- [Thanh-Thao Hoang](https://github.com/thanhthaohoang)

## Theme installation

Before using the theme, make sure you've installed [Gulp](https://gulpjs.com) and [Node.js](https://nodejs.org/) on your machine.
After that, you can follow the next instructions :

```
#Clone the repository
git clone https://github.com/lisafises/H3G2_P2020_EatYourCoffee.git

#Go to the theme folder
cd your-folder-name/wp-content/themes/eatyourcoffee

#Install dependencies
npm install
```

### Disclaimer
This a school project carried by students.

### License
This project is licensed under the MIT License

#### And don't forget : Enjoy your EatYourCoffee Bar !

![Time for coffee](https://media.giphy.com/media/KRcn1ilIBjWQ8/giphy.gif)