<commit_before># vim: tabstop=4 shiftwidth=4 softtabstop=4

# Copyright 2011 OpenStack LLC.
# All Rights Reserved.
#
#    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.

"""
While SQLAlchemy/sqlalchemy-migrate should abstract this correctly,
there are known issues with these libraries so SQLite and non-SQLite
migrations must be done separately.
"""

import migrate
import sqlalchemy

import glance.common.utils

meta = sqlalchemy.MetaData()
and_ = sqlalchemy.and_
or_ = sqlalchemy.or_

def upgrade(migrate_engine):
    """
    Call the correct dialect-specific upgrade.
    """
    meta.bind = migrate_engine

    t_images = _get_table('images', meta)
    t_image_members = _get_table('image_members', meta)
    t_image_properties = _get_table('image_properties', meta)

    if migrate_engine.url.get_dialect().name == "sqlite":
        _upgrade_sqlite(t_images, t_image_members, t_image_properties)
        _update_all_ids_to_uuids(t_images, t_image_members, t_image_properties)
    else:
        _upgrade_other(t_images, t_image_members, t_image_properties)

def downgrade(migrate_engine):
    """
    Call the correct dialect-specific downgrade.
    """
    meta.bind = migrate_engine

    t_images = _get_table('images', meta)
    t_image_members = _get_table('image_members', meta)
    t_image_properties = _get_table('image_properties', meta)

    if migrate_engine.url.get_dialect().name == "sqlite":
        _downgrade_sqlite(t_images, t_image_members, t_image_properties)
        _update_all_uuids_to_ids(t_images, t_image_members, t_image_properties)
    else:
        _downgrade_other(t_images, t_image_members, t_image_properties)

def _upgrade_sqlite(t_images, t_image_members, t_image_properties):
    """
    Upgrade 011 -> 012 with special SQLite-compatible logic.
    """
    t_images.c.id.alter(sqlalchemy.String(36), primary_key=True)

    sql_commands = [
        """CREATE TABLE image_members_backup (
            id INTEGER NOT NULL,
            image_id VARCHAR(36) NOT NULL,
            member VARCHAR(255) NOT NULL,
            can_share BOOLEAN NOT NULL,
            created_at DATETIME NOT NULL,
            updated_at DATETIME,
            deleted_at DATETIME,
            deleted BOOLEAN NOT NULL,
            PRIMARY KEY (id),
            UNIQUE (image_id, member),
            CHECK (can_share IN (0, 1)),
            CHECK (deleted IN (0, 1)),
            FOREIGN KEY(image_id) REFERENCES images (id)
        );""",
        """INSERT INTO image_members_backup
            SELECT * FROM image_members;""",
        """CREATE TABLE image_properties_backup (
            id INTEGER NOT NULL,
            image_id VARCHAR(36) NOT NULL,
            name VARCHAR(255) NOT NULL,
            value TEXT,
            created_at DATETIME NOT NULL,
            updated_at DATETIME,
            deleted_at DATETIME,
            deleted BOOLEAN NOT NULL,
            PRIMARY KEY (id),
            CHECK (deleted IN (0, 1)),
            UNIQUE (image_id, name),
            FOREIGN KEY(image_id) REFERENCES images (id)
        );""",
        """INSERT INTO image_properties_backup
            SELECT * FROM image_properties;""",
    ]

    for command in sql_commands:
        meta.bind.execute(command)

    _sqlite_table_swap(t_image_members, t_image_properties)

def _downgrade_sqlite(t_images, t_image_members, t_image_properties):
    """
    Downgrade 012 -> 011 with special SQLite-compatible logic.
    """
    t_images.c.id.alter(sqlalchemy.Integer(), primary_key=True)

    sql_commands = [
        """CREATE TABLE image_members_backup (
            id INTEGER NOT NULL,
            image_id INTEGER NOT NULL,
            member VARCHAR(255) NOT NULL,
            can_share BOOLEAN NOT NULL,
            created_at DATETIME NOT NULL,
            updated_at DATETIME,
            deleted_at DATETIME,
            deleted BOOLEAN NOT NULL,
            PRIMARY KEY (id),
            UNIQUE (image_id, member),
            CHECK (can_share IN (0, 1)),
            CHECK (deleted IN (0, 1)),
            FOREIGN KEY(image_id) REFERENCES images (id)
        );""",
        """INSERT INTO image_members_backup
            SELECT * FROM image_members;""",
        """CREATE TABLE image_properties_backup (
            id INTEGER NOT NULL,
            image_id INTEGER  NOT NULL,
            name VARCHAR(255) NOT NULL,
            value TEXT,
            created_at DATETIME NOT NULL,
            updated_at DATETIME,
            deleted_at DATETIME,
            deleted BOOLEAN NOT NULL,
            PRIMARY KEY (id),
            CHECK (deleted IN (0, 1)),
            UNIQUE (image_id, name),
            FOREIGN KEY(image_id) REFERENCES images (id)
        );""",
        """INSERT INTO image_properties_backup
            SELECT * FROM image_properties;""",
    ]

    for command in sql_commands:
        meta.bind.execute(command)

    _sqlite_table_swap(t_image_members, t_image_properties)

def _upgrade_other(t_images, t_image_members, t_image_properties):
    """
    Upgrade 011 -> 012 with logic for non-SQLite databases.
    """
    foreign_keys = _get_foreign_keys(t_images,
                                     t_image_members,
                                     t_image_properties)

    for fk in foreign_keys:
        fk.drop()

    t_images.c.id.alter(sqlalchemy.String(36), primary_key=True)
    t_image_members.c.image_id.alter(sqlalchemy.String(36))
    t_image_properties.c.image_id.alter(sqlalchemy.String(36))

    _update_all_ids_to_uuids(t_images, t_image_members, t_image_properties)

    for fk in foreign_keys:
        fk.create()

def _downgrade_other(t_images, t_image_members, t_image_properties):
    """
    Downgrade 012 -> 011 with logic for non-SQLite databases.
    """
    foreign_keys = _get_foreign_keys(t_images,
                                     t_image_members,
                                     t_image_properties)

    for fk in foreign_keys:
        fk.drop()

    t_images.c.id.alter(sqlalchemy.Integer(), primary_key=True)
    t_image_members.c.image_id.alter(sqlalchemy.Integer())
    t_image_properties.c.image_id.alter(sqlalchemy.Integer())

    _update_all_uuids_to_ids(t_images, t_image_members, t_image_properties)

    for fk in foreign_keys:
        fk.create()

def _sqlite_table_swap(t_image_members, t_image_properties):
    t_image_members.drop()
    t_image_properties.drop()

    meta.bind.execute("ALTER TABLE image_members_backup "
                      "RENAME TO image_members")
    meta.bind.execute("ALTER TABLE image_properties_backup "
                      "RENAME TO image_properties")

    for index in t_image_members.indexes.union(t_image_properties.indexes):
        index.create()

def _get_table(table_name, metadata):
    """Return a sqlalchemy Table definition with associated metadata."""
    return sqlalchemy.Table(table_name, metadata, autoload=True)

def _get_foreign_keys(t_images, t_image_members, t_image_properties):
    """Retrieve and return foreign keys for members/properties tables."""
    foreign_keys = []
    if t_image_members.foreign_keys:
        img_members_fk_name = list(t_image_members.foreign_keys)[0].name

        fk1 = migrate.ForeignKeyConstraint([t_image_members.c.image_id],
                                           [t_images.c.id],
                                           name=img_members_fk_name)
        foreign_keys.append(fk1)

    if t_image_properties.foreign_keys:
        img_properties_fk_name = list(t_image_properties.foreign_keys)[0].name

        fk2 = migrate.ForeignKeyConstraint([t_image_properties.c.image_id],
                                           [t_images.c.id],
                                           name=img_properties_fk_name)
        foreign_keys.append(fk2)

    return foreign_keys

def _update_all_ids_to_uuids(t_images, t_image_members, t_image_properties):
    """Transition from INTEGER id to VARCHAR(36) id."""
    images = list(t_images.select().execute())

    for image in images:
        old_id = image["id"]
        new_id = glance.common.utils.generate_uuid()

        t_images.update().\
            where(t_images.c.id == old_id).\
            values(id=new_id).execute()

        t_image_members.update().\
            where(t_image_members.c.image_id == old_id).\
            values(image_id=new_id).execute()

        t_image_properties.update().\
            where(t_image_properties.c.image_id == old_id).\
            values(image_id=new_id).execute()

        t_image_properties.update().\
            where(and_(or_(t_image_properties.c.name == 'kernel_id',
                           t_image_properties.c.name == 'ramdisk_id'),
                       t_image_properties.c.value == old_id)).\
            values(value=new_id).execute()

def _update_all_uuids_to_ids(t_images, t_image_members, t_image_properties):
    """Transition from VARCHAR(36) id to INTEGER id."""
    images = list(t_images.select().execute())

    for image in images:
        old_id = image["id"]
        new_id = 0

        t_images.update().\
            where(t_images.c.id == old_id).\
            values(id=new_id).execute()

        t_image_members.update().\
            where(t_image_members.c.image_id == old_id).\
            values(image_id=new_id).execute()

        t_image_properties.update().\
            where(t_image_properties.c.image_id == old_id).\
            values(image_id=new_id).execute()

        t_image_properties.update().\
            where(and_(or_(t_image_properties.c.name == 'kernel_id',
                           t_image_properties.c.name == 'ramdisk_id'),
                       t_image_properties.c.value == old_id)).\
            values(value=new_id).execute()

        new_id += 1
<commit_msg>Fix issues with migration 012<commit_after># vim: tabstop=4 shiftwidth=4 softtabstop=4

# Copyright 2011 OpenStack LLC.
# All Rights Reserved.
#
#    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.

"""
While SQLAlchemy/sqlalchemy-migrate should abstract this correctly,
there are known issues with these libraries so SQLite and non-SQLite
migrations must be done separately.
"""

import migrate
import sqlalchemy

from glance.openstack.common import uuidutils

meta = sqlalchemy.MetaData()
and_ = sqlalchemy.and_
or_ = sqlalchemy.or_

def upgrade(migrate_engine):
    """
    Call the correct dialect-specific upgrade.
    """
    meta.bind = migrate_engine

    t_images = _get_table('images', meta)
    t_image_members = _get_table('image_members', meta)
    t_image_properties = _get_table('image_properties', meta)

    if migrate_engine.url.get_dialect().name == "sqlite":
        _upgrade_sqlite(t_images, t_image_members, t_image_properties)
        _update_all_ids_to_uuids(t_images, t_image_members, t_image_properties)
    else:
        _upgrade_other(t_images, t_image_members, t_image_properties)

def downgrade(migrate_engine):
    """
    Call the correct dialect-specific downgrade.
    """
    meta.bind = migrate_engine

    t_images = _get_table('images', meta)
    t_image_members = _get_table('image_members', meta)
    t_image_properties = _get_table('image_properties', meta)

    if migrate_engine.url.get_dialect().name == "sqlite":
        _update_all_uuids_to_ids(t_images, t_image_members, t_image_properties)
        _downgrade_sqlite(t_images, t_image_members, t_image_properties)
    else:
        _downgrade_other(t_images, t_image_members, t_image_properties)

def _upgrade_sqlite(t_images, t_image_members, t_image_properties):
    """
    Upgrade 011 -> 012 with special SQLite-compatible logic.
    """
    t_images.c.id.alter(sqlalchemy.String(36), primary_key=True)

    sql_commands = [
        """CREATE TABLE image_members_backup (
            id INTEGER NOT NULL,
            image_id VARCHAR(36) NOT NULL,
            member VARCHAR(255) NOT NULL,
            can_share BOOLEAN NOT NULL,
            created_at DATETIME NOT NULL,
            updated_at DATETIME,
            deleted_at DATETIME,
            deleted BOOLEAN NOT NULL,
            PRIMARY KEY (id),
            UNIQUE (image_id, member),
            CHECK (can_share IN (0, 1)),
            CHECK (deleted IN (0, 1)),
            FOREIGN KEY(image_id) REFERENCES images (id)
        );""",
        """INSERT INTO image_members_backup
            SELECT * FROM image_members;""",
        """CREATE TABLE image_properties_backup (
            id INTEGER NOT NULL,
            image_id VARCHAR(36) NOT NULL,
            name VARCHAR(255) NOT NULL,
            value TEXT,
            created_at DATETIME NOT NULL,
            updated_at DATETIME,
            deleted_at DATETIME,
            deleted BOOLEAN NOT NULL,
            PRIMARY KEY (id),
            CHECK (deleted IN (0, 1)),
            UNIQUE (image_id, name),
            FOREIGN KEY(image_id) REFERENCES images (id)
        );""",
        """INSERT INTO image_properties_backup
            SELECT * FROM image_properties;""",
    ]

    for command in sql_commands:
        meta.bind.execute(command)

    _sqlite_table_swap(t_image_members, t_image_properties)

def _downgrade_sqlite(t_images, t_image_members, t_image_properties):
    """
    Downgrade 012 -> 011 with special SQLite-compatible logic.
    """
    t_images.c.id.alter(sqlalchemy.Integer(), primary_key=True)

    sql_commands = [
        """CREATE TABLE image_members_backup (
            id INTEGER NOT NULL,
            image_id INTEGER NOT NULL,
            member VARCHAR(255) NOT NULL,
            can_share BOOLEAN NOT NULL,
            created_at DATETIME NOT NULL,
            updated_at DATETIME,
            deleted_at DATETIME,
            deleted BOOLEAN NOT NULL,
            PRIMARY KEY (id),
            UNIQUE (image_id, member),
            CHECK (can_share IN (0, 1)),
            CHECK (deleted IN (0, 1)),
            FOREIGN KEY(image_id) REFERENCES images (id)
        );""",
        """INSERT INTO image_members_backup
            SELECT * FROM image_members;""",
        """CREATE TABLE image_properties_backup (
            id INTEGER NOT NULL,
            image_id INTEGER  NOT NULL,
            name VARCHAR(255) NOT NULL,
            value TEXT,
            created_at DATETIME NOT NULL,
            updated_at DATETIME,
            deleted_at DATETIME,
            deleted BOOLEAN NOT NULL,
            PRIMARY KEY (id),
            CHECK (deleted IN (0, 1)),
            UNIQUE (image_id, name),
            FOREIGN KEY(image_id) REFERENCES images (id)
        );""",
        """INSERT INTO image_properties_backup
            SELECT * FROM image_properties;""",
    ]

    for command in sql_commands:
        meta.bind.execute(command)

    _sqlite_table_swap(t_image_members, t_image_properties)

def _upgrade_other(t_images, t_image_members, t_image_properties):
    """
    Upgrade 011 -> 012 with logic for non-SQLite databases.
    """
    foreign_keys = _get_foreign_keys(t_images,
                                     t_image_members,
                                     t_image_properties)

    for fk in foreign_keys:
        fk.drop()

    t_images.c.id.alter(sqlalchemy.String(36), primary_key=True)
    t_image_members.c.image_id.alter(sqlalchemy.String(36))
    t_image_properties.c.image_id.alter(sqlalchemy.String(36))

    _update_all_ids_to_uuids(t_images, t_image_members, t_image_properties)

    for fk in foreign_keys:
        fk.create()

def _downgrade_other(t_images, t_image_members, t_image_properties):
    """
    Downgrade 012 -> 011 with logic for non-SQLite databases.
    """
    foreign_keys = _get_foreign_keys(t_images,
                                     t_image_members,
                                     t_image_properties)

    for fk in foreign_keys:
        fk.drop()

    t_images.c.id.alter(sqlalchemy.Integer(), primary_key=True)
    t_image_members.c.image_id.alter(sqlalchemy.Integer())
    t_image_properties.c.image_id.alter(sqlalchemy.Integer())

    _update_all_uuids_to_ids(t_images, t_image_members, t_image_properties)

    for fk in foreign_keys:
        fk.create()

def _sqlite_table_swap(t_image_members, t_image_properties):
    t_image_members.drop()
    t_image_properties.drop()

    meta.bind.execute("ALTER TABLE image_members_backup "
                      "RENAME TO image_members")
    meta.bind.execute("ALTER TABLE image_properties_backup "
                      "RENAME TO image_properties")

    for index in t_image_members.indexes.union(t_image_properties.indexes):
        index.create()

def _get_table(table_name, metadata):
    """Return a sqlalchemy Table definition with associated metadata."""
    return sqlalchemy.Table(table_name, metadata, autoload=True)

def _get_foreign_keys(t_images, t_image_members, t_image_properties):
    """Retrieve and return foreign keys for members/properties tables."""
    foreign_keys = []
    if t_image_members.foreign_keys:
        img_members_fk_name = list(t_image_members.foreign_keys)[0].name

        fk1 = migrate.ForeignKeyConstraint([t_image_members.c.image_id],
                                           [t_images.c.id],
                                           name=img_members_fk_name)
        foreign_keys.append(fk1)

    if t_image_properties.foreign_keys:
        img_properties_fk_name = list(t_image_properties.foreign_keys)[0].name

        fk2 = migrate.ForeignKeyConstraint([t_image_properties.c.image_id],
                                           [t_images.c.id],
                                           name=img_properties_fk_name)
        foreign_keys.append(fk2)

    return foreign_keys

def _update_all_ids_to_uuids(t_images, t_image_members, t_image_properties):
    """Transition from INTEGER id to VARCHAR(36) id."""
    images = list(t_images.select().execute())

    for image in images:
        old_id = image["id"]
        new_id = uuidutils.generate_uuid()

        t_images.update().\
            where(t_images.c.id == old_id).\
            values(id=new_id).execute()

        t_image_members.update().\
            where(t_image_members.c.image_id == old_id).\
            values(image_id=new_id).execute()

        t_image_properties.update().\
            where(t_image_properties.c.image_id == old_id).\
            values(image_id=new_id).execute()

        t_image_properties.update().\
            where(and_(or_(t_image_properties.c.name == 'kernel_id',
                           t_image_properties.c.name == 'ramdisk_id'),
                       t_image_properties.c.value == old_id)).\
            values(value=new_id).execute()

def _update_all_uuids_to_ids(t_images, t_image_members, t_image_properties):
    """Transition from VARCHAR(36) id to INTEGER id."""
    images = list(t_images.select().execute())

    new_id = 1
    for image in images:
        old_id = image["id"]

        t_images.update().\
            where(t_images.c.id == old_id).\
            values(id=new_id).execute()

        t_image_members.update().\
            where(t_image_members.c.image_id == old_id).\
            values(image_id=new_id).execute()

        t_image_properties.update().\
            where(t_image_properties.c.image_id == old_id).\
            values(image_id=new_id).execute()

        t_image_properties.update().\
            where(and_(or_(t_image_properties.c.name == 'kernel_id',
                           t_image_properties.c.name == 'ramdisk_id'),
                       t_image_properties.c.value == old_id)).\
            values(value=new_id).execute()

        new_id += 1
<|endoftext|>


<commit_before>#
#    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.

from heat.common.i18n import _
from heat.engine import properties
from heat.engine import resource
from heat.engine import support

class CinderVolumeType(resource.Resource):
    """
    A resource for creating cinder volume types.

    Note that default cinder security policy usage of this resource
    is limited to being used by administrators only.

    Here is an example cinder volume_type and cinder volume resources::

        heat_template_version: 2013-05-23
        description:  Heat Cinder creation with volume_type example
        resources:
          my_volume_type:
            type: OS::Cinder::VolumeType
            properties:
              name: volumeBackend
              metadata: {volume_backend_name: lvmdriver}
          my_volume:
            type: OS::Cinder::Volume
            properties:
              size: 1
              volume_type: {get_resource: my_volume_type}
    """

    support_status = support.SupportStatus(version='2015.1')

    default_client_name = 'cinder'

    entity = 'volume_types'

    PROPERTIES = (
        NAME, METADATA, IS_PUBLIC, DESCRIPTION,
    ) = (
        'name', 'metadata', 'is_public', 'description',
    )

    properties_schema = {
        NAME: properties.Schema(
            properties.Schema.STRING,
            _('Name of the volume type.'),
            required=True,
            update_allowed=True,
        ),
        METADATA: properties.Schema(
            properties.Schema.MAP,
            _('The extra specs key and value pairs of the volume type.'),
            update_allowed=True
        ),
        IS_PUBLIC: properties.Schema(
            properties.Schema.BOOLEAN,
            _('Whether the volume type is accessible to the public.'),
            default=True,
            support_status=support.SupportStatus(version='5.0.0'),
        ),
        DESCRIPTION: properties.Schema(
            properties.Schema.STRING,
            _('Description of the volume type.'),
            update_allowed=True,
            support_status=support.SupportStatus(version='5.0.0'),
        ),
    }

    def handle_create(self):
        args = {
            'name': self.properties[self.NAME],
            'is_public': self.properties[self.IS_PUBLIC],
            'description': self.properties[self.DESCRIPTION]
        }

        volume_type = self.client().volume_types.create(**args)
        self.resource_id_set(volume_type.id)
        vtype_metadata = self.properties[self.METADATA]
        if vtype_metadata:
            volume_type.set_keys(vtype_metadata)

    def handle_update(self, json_snippet, tmpl_diff, prop_diff):
        """Update the name, description and metadata for volume type."""

        update_args = {}
        # Update the name, description of cinder volume type
        if self.DESCRIPTION in prop_diff:
            update_args['description'] = prop_diff.get(self.DESCRIPTION)
        if self.NAME in prop_diff:
            update_args['name'] = prop_diff.get(self.NAME)
        if update_args:
            self.client().volume_types.update(self.resource_id, **update_args)
        # Update the key-value pairs of cinder volume type.
        if self.METADATA in prop_diff:
            volume_type = self.client().volume_types.get(self.resource_id)
            old_keys = volume_type.get_keys()
            volume_type.unset_keys(old_keys)
            new_keys = prop_diff.get(self.METADATA)
            if new_keys is not None:
                volume_type.set_keys(new_keys)

    def handle_delete(self):
        if self.resource_id is None:
            return

        try:
            self.client().volume_types.delete(self.resource_id)
        except Exception as e:
            self.client_plugin().ignore_not_found(e)

    # TODO(huangtianhua): remove this method when bug #1479641 is fixed.
    def _show_resource(self):
        vtype = self.client().volume_types.get(self.resource_id)
        return vtype._info

def resource_mapping():
    return {
        'OS::Cinder::VolumeType': CinderVolumeType
    }
<commit_msg>OS::Cinder::VolumeType help doc string contains redundant info<commit_after>#
#    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.

from heat.common.i18n import _
from heat.engine import properties
from heat.engine import resource
from heat.engine import support

class CinderVolumeType(resource.Resource):
    """
    A resource for creating cinder volume types.

    Note that default cinder security policy usage of this resource
    is limited to being used by administrators only.
    """

    support_status = support.SupportStatus(version='2015.1')

    default_client_name = 'cinder'

    entity = 'volume_types'

    PROPERTIES = (
        NAME, METADATA, IS_PUBLIC, DESCRIPTION,
    ) = (
        'name', 'metadata', 'is_public', 'description',
    )

    properties_schema = {
        NAME: properties.Schema(
            properties.Schema.STRING,
            _('Name of the volume type.'),
            required=True,
            update_allowed=True,
        ),
        METADATA: properties.Schema(
            properties.Schema.MAP,
            _('The extra specs key and value pairs of the volume type.'),
            update_allowed=True
        ),
        IS_PUBLIC: properties.Schema(
            properties.Schema.BOOLEAN,
            _('Whether the volume type is accessible to the public.'),
            default=True,
            support_status=support.SupportStatus(version='5.0.0'),
        ),
        DESCRIPTION: properties.Schema(
            properties.Schema.STRING,
            _('Description of the volume type.'),
            update_allowed=True,
            support_status=support.SupportStatus(version='5.0.0'),
        ),
    }

    def handle_create(self):
        args = {
            'name': self.properties[self.NAME],
            'is_public': self.properties[self.IS_PUBLIC],
            'description': self.properties[self.DESCRIPTION]
        }

        volume_type = self.client().volume_types.create(**args)
        self.resource_id_set(volume_type.id)
        vtype_metadata = self.properties[self.METADATA]
        if vtype_metadata:
            volume_type.set_keys(vtype_metadata)

    def handle_update(self, json_snippet, tmpl_diff, prop_diff):
        """Update the name, description and metadata for volume type."""

        update_args = {}
        # Update the name, description of cinder volume type
        if self.DESCRIPTION in prop_diff:
            update_args['description'] = prop_diff.get(self.DESCRIPTION)
        if self.NAME in prop_diff:
            update_args['name'] = prop_diff.get(self.NAME)
        if update_args:
            self.client().volume_types.update(self.resource_id, **update_args)
        # Update the key-value pairs of cinder volume type.
        if self.METADATA in prop_diff:
            volume_type = self.client().volume_types.get(self.resource_id)
            old_keys = volume_type.get_keys()
            volume_type.unset_keys(old_keys)
            new_keys = prop_diff.get(self.METADATA)
            if new_keys is not None:
                volume_type.set_keys(new_keys)

    def handle_delete(self):
        if self.resource_id is None:
            return

        try:
            self.client().volume_types.delete(self.resource_id)
        except Exception as e:
            self.client_plugin().ignore_not_found(e)

    # TODO(huangtianhua): remove this method when bug #1479641 is fixed.
    def _show_resource(self):
        vtype = self.client().volume_types.get(self.resource_id)
        return vtype._info

def resource_mapping():
    return {
        'OS::Cinder::VolumeType': CinderVolumeType
    }
<|endoftext|>


<commit_before># vim: tabstop=4 shiftwidth=4 softtabstop=4
#
#    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
#

import util
import verify
import nose
from nose.plugins.attrib import attr
import unittest
import os

@attr(speed='slow')
@attr(tag=['func', 'wordpress', 'WordPress_Single_Instance.template', 'boto'])
class WordPressBotoFunctionalTest(unittest.TestCase):
    def setUp(self):
        template = 'WordPress_Single_Instance.template'

        stack_paramstr = ';'.join(['InstanceType=m1.xlarge',
            'DBUsername=dbuser',
            'DBPassword=' + os.environ['OS_PASSWORD']])

        self.stack = util.StackBoto(template, 'F17', 'x86_64', 'cfntools',
            stack_paramstr)
        self.WikiDatabase = util.Instance('WikiDatabase')

    def tearDown(self):
        self.stack.cleanup()

    def test_instance(self):
        self.stack.create()

        self.WikiDatabase.wait_for_boot()
        self.WikiDatabase.check_cfntools()
        self.WikiDatabase.wait_for_provisioning()

        # ensure wordpress was installed by checking for expected
        # configuration file over ssh
        self.assertTrue(self.WikiDatabase.file_present
                        ('/etc/wordpress/wp-config.php'))
        print "Wordpress installation detected"

        # Verify the output URL parses as expected, ie check that
        # the wordpress installation is operational
        stack_url = self.stack.get_stack_output("WebsiteURL")
        print "Got stack output WebsiteURL=%s, verifying" % stack_url
        ver = verify.VerifyStack()
        self.assertTrue(ver.verify_wordpress(stack_url))

        self.stack.cleanup()
<commit_msg>heat tests : remove duplicate cleanup Wordpress_Boto<commit_after># vim: tabstop=4 shiftwidth=4 softtabstop=4
#
#    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
#

import util
import verify
import nose
from nose.plugins.attrib import attr
import unittest
import os

@attr(speed='slow')
@attr(tag=['func', 'wordpress', 'WordPress_Single_Instance.template', 'boto'])
class WordPressBotoFunctionalTest(unittest.TestCase):
    def setUp(self):
        template = 'WordPress_Single_Instance.template'

        stack_paramstr = ';'.join(['InstanceType=m1.xlarge',
            'DBUsername=dbuser',
            'DBPassword=' + os.environ['OS_PASSWORD']])

        self.stack = util.StackBoto(template, 'F17', 'x86_64', 'cfntools',
            stack_paramstr)
        self.WikiDatabase = util.Instance('WikiDatabase')

    def tearDown(self):
        self.stack.cleanup()

    def test_instance(self):
        self.stack.create()

        self.WikiDatabase.wait_for_boot()
        self.WikiDatabase.check_cfntools()
        self.WikiDatabase.wait_for_provisioning()

        # ensure wordpress was installed by checking for expected
        # configuration file over ssh
        self.assertTrue(self.WikiDatabase.file_present
                        ('/etc/wordpress/wp-config.php'))
        print "Wordpress installation detected"

        # Verify the output URL parses as expected, ie check that
        # the wordpress installation is operational
        stack_url = self.stack.get_stack_output("WebsiteURL")
        print "Got stack output WebsiteURL=%s, verifying" % stack_url
        ver = verify.VerifyStack()
        self.assertTrue(ver.verify_wordpress(stack_url))
<|endoftext|>


<commit_before>#!/usr/bin/python
"""
Jutda Helpdesk - A Django powered ticket tracker for small enterprise.

(c) Copyright 2008 Jutda. All Rights Reserved. See LICENSE for details.

scripts/create_escalation_exclusion.py - Easy way to routinely add particular
                                         days to the list of days on which no
                                         escalation should take place.
"""

from datetime import timedelta, date
import getopt
from optparse import make_option
import sys

from django.core.management.base import BaseCommand, CommandError
from django.db.models import Q

from helpdesk.models import EscalationExclusion, Queue

class Command(BaseCommand):
    def __init__(self):
        BaseCommand.__init__(self)

        self.option_list += (
            make_option(
                '--days', '-d',
                help='Days of week (monday, tuesday, etc)'),
            make_option(
                '--occurrences', '-o',
                type='int',
                default=1,
                help='Occurrences: How many weeks ahead to exclude this day'),
            make_option(
                '--queues', '-q',
                help='Queues to include (default: all). Use queue slugs'),
            make_option(
                '--escalate-verbosely', '-x',
                action='store_true',
                default=False,
                help='Display a list of dates excluded'),
            )

    def handle(self, *args, **options):
        days = options['days']
        occurrences = options['occurrences']
        verbose = False
        queue_slugs = options['queues']
        queues = []

        if options['escalate-verbosely']:
            verbose = True

        # this should already be handled by optparse
        if not occurrences: occurrences = 1
        if not (days and occurrences):
            raise CommandError('One or more occurrences must be specified.')

        if queue_slugs is not None:
            queue_set = queue_slugs.split(',')
            for queue in queue_set:
                try:
                    q = Queue.objects.get(slug__exact=queue)
                except Queue.DoesNotExist:
                    raise CommandError("Queue %s does not exist." % queue)
                queues.append(q)

        create_exclusions(days=days, occurrences=occurrences, verbose=verbose, queues=queues)

day_names = {
    'monday': 0,
    'tuesday': 1,
    'wednesday': 2,
    'thursday': 3,
    'friday': 4,
    'saturday': 5,
    'sunday': 6,
}

def create_exclusions(days, occurrences, verbose, queues):
    days = days.split(',')
    for day in days:
        day_name = day
        day = day_names[day]
        workdate = date.today()
        i = 0
        while i < occurrences:
            if day == workdate.weekday():
                if EscalationExclusion.objects.filter(date=workdate).count() == 0:
                    esc = EscalationExclusion(name='Auto Exclusion for %s' % day_name, date=workdate)
                    esc.save()

                    if verbose:
                        print "Created exclusion for %s %s" % (day_name, workdate)

                    for q in queues:
                        esc.queues.add(q)
                        if verbose:
                            print "  - for queue %s" % q

                i += 1
            workdate += timedelta(days=1)

def usage():
    print "Options:"
    print " --days, -d: Days of week (monday, tuesday, etc)"
    print " --occurrences, -o: Occurrences: How many weeks ahead to exclude this day"
    print " --queues, -q: Queues to include (default: all). Use queue slugs"
    print " --verbose, -v: Display a list of dates excluded"

if __name__ == '__main__':
    # This script can be run from the command-line or via Django's manage.py.
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'd:o:q:v', ['days=', 'occurrences=', 'verbose', 'queues='])
    except getopt.GetoptError:
        usage()
        sys.exit(2)

    days = None
    occurrences = None
    verbose = False
    queue_slugs = None
    queues = []

    for o, a in opts:
        if o in ('-x', '--escalate-verbosely'):
            verbose = True
        if o in ('-d', '--days'):
            days = a
        if o in ('-q', '--queues'):
            queue_slugs = a
        if o in ('-o', '--occurrences'):
            occurrences = int(a)

    if not occurrences: occurrences = 1
    if not (days and occurrences):
        usage()
        sys.exit(2)

    if queue_slugs is not None:
        queue_set = queue_slugs.split(',')
        for queue in queue_set:
            try:
                q = Queue.objects.get(slug__exact=queue)
            except Queue.DoesNotExist:
                print "Queue %s does not exist." % queue
                sys.exit(2)
            queues.append(q)

    create_exclusions(days=days, occurrences=occurrences, verbose=verbose, queues=queues)
<commit_msg>Modify make_option with dest variable 'escalate-verbosely'<commit_after>#!/usr/bin/python
"""
Jutda Helpdesk - A Django powered ticket tracker for small enterprise.

(c) Copyright 2008 Jutda. All Rights Reserved. See LICENSE for details.

scripts/create_escalation_exclusion.py - Easy way to routinely add particular
                                         days to the list of days on which no
                                         escalation should take place.
"""

from datetime import timedelta, date
import getopt
from optparse import make_option
import sys

from django.core.management.base import BaseCommand, CommandError
from django.db.models import Q

from helpdesk.models import EscalationExclusion, Queue

class Command(BaseCommand):
    def __init__(self):
        BaseCommand.__init__(self)

        self.option_list += (
            make_option(
                '--days', '-d',
                help='Days of week (monday, tuesday, etc)'),
            make_option(
                '--occurrences', '-o',
                type='int',
                default=1,
                help='Occurrences: How many weeks ahead to exclude this day'),
            make_option(
                '--queues', '-q',
                help='Queues to include (default: all). Use queue slugs'),
            make_option(
                '--escalate-verbosely', '-x',
                action='store_true',
                default=False,
                dest='escalate-verbosely',
                help='Display a list of dates excluded'),
            )

    def handle(self, *args, **options):
        days = options['days']
        occurrences = options['occurrences']
        verbose = False
        queue_slugs = options['queues']
        queues = []

        if options['escalate-verbosely']:
            verbose = True

        # this should already be handled by optparse
        if not occurrences: occurrences = 1
        if not (days and occurrences):
            raise CommandError('One or more occurrences must be specified.')

        if queue_slugs is not None:
            queue_set = queue_slugs.split(',')
            for queue in queue_set:
                try:
                    q = Queue.objects.get(slug__exact=queue)
                except Queue.DoesNotExist:
                    raise CommandError("Queue %s does not exist." % queue)
                queues.append(q)

        create_exclusions(days=days, occurrences=occurrences, verbose=verbose, queues=queues)

day_names = {
    'monday': 0,
    'tuesday': 1,
    'wednesday': 2,
    'thursday': 3,
    'friday': 4,
    'saturday': 5,
    'sunday': 6,
}

def create_exclusions(days, occurrences, verbose, queues):
    days = days.split(',')
    for day in days:
        day_name = day
        day = day_names[day]
        workdate = date.today()
        i = 0
        while i < occurrences:
            if day == workdate.weekday():
                if EscalationExclusion.objects.filter(date=workdate).count() == 0:
                    esc = EscalationExclusion(name='Auto Exclusion for %s' % day_name, date=workdate)
                    esc.save()

                    if verbose:
                        print "Created exclusion for %s %s" % (day_name, workdate)

                    for q in queues:
                        esc.queues.add(q)
                        if verbose:
                            print "  - for queue %s" % q

                i += 1
            workdate += timedelta(days=1)

def usage():
    print "Options:"
    print " --days, -d: Days of week (monday, tuesday, etc)"
    print " --occurrences, -o: Occurrences: How many weeks ahead to exclude this day"
    print " --queues, -q: Queues to include (default: all). Use queue slugs"
    print " --verbose, -v: Display a list of dates excluded"

if __name__ == '__main__':
    # This script can be run from the command-line or via Django's manage.py.
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'd:o:q:v', ['days=', 'occurrences=', 'verbose', 'queues='])
    except getopt.GetoptError:
        usage()
        sys.exit(2)

    days = None
    occurrences = None
    verbose = False
    queue_slugs = None
    queues = []

    for o, a in opts:
        if o in ('-x', '--escalate-verbosely'):
            verbose = True
        if o in ('-d', '--days'):
            days = a
        if o in ('-q', '--queues'):
            queue_slugs = a
        if o in ('-o', '--occurrences'):
            occurrences = int(a)

    if not occurrences: occurrences = 1
    if not (days and occurrences):
        usage()
        sys.exit(2)

    if queue_slugs is not None:
        queue_set = queue_slugs.split(',')
        for queue in queue_set:
            try:
                q = Queue.objects.get(slug__exact=queue)
            except Queue.DoesNotExist:
                print "Queue %s does not exist." % queue
                sys.exit(2)
            queues.append(q)

    create_exclusions(days=days, occurrences=occurrences, verbose=verbose, queues=queues)
<|endoftext|>


<commit_before>

def poker(hands):
    """Return the best hand: poker([hand,...]) => hand"""
    return max(hands, key=hand_rank)

def hand_rank(hand):
    """define a rank for a specific hand"""
    ranks = card_ranks(hand)
    if straight(ranks) and flush(hand):            # straight flush
        return (8, max(ranks))
    elif kind(4, ranks):                           # 4 of a kind
        return (7, kind(4, ranks), kind(1, ranks))
    elif kind(3, ranks) and kind(2, ranks):        # full house
        return (6, kind(3, ranks), kind(2, ranks))
    elif flush(hand):                              # flush
        return (5, ranks)
    elif straight(ranks):                          # straight
        return (4, max(ranks))
    elif kind(3, ranks):                           # 3 of a kind
        return (3, kind(3, ranks), ranks)
    elif two_pair(ranks):                          # 2 pair
        return (2, two_pair(ranks), ranks)
    elif kind(2, ranks):                           # kind
        return (1, kind(2, ranks), ranks)
    else:                                          # high card
        return (0, ranks)

def card_ranks(cards):
    """ Return a list of the ranks, sorted with higher first"""
    ranks = ["--23456789TJQKA".index(r) for r, s in cards]
    ranks.sort(reverse=True)
    return [5, 4, 3, 2, 1] if ranks == [14, 5, 4, 3, 2] else ranks

def straight(ranks):
    """ Return True if the ordered ranks from a 5 card straight"""
    return (max(ranks) - min(ranks) == 4) and len(set(ranks)) == 5

def flush(hand):
    """ Return True if all cards have the same suit"""
    suits = [s for r, s in hand]
    return len(set(suits)) == 1

def kind(n, ranks):
    """ Return the first rank that this hand has exactly n
        and return None otherwise"""
    for r in ranks:
        if ranks.count(r) == n:
            return r
    return None

def two_pair(ranks):
    """If there are two pair, return the two ranks as a
       tuple: (highest, lowest); otherwise return None."""
    pair_highest = kind(2, ranks)
    pair_lowest = kind(2, list(reversed(ranks)))
    if pair_highest and pair_highest != pair_lowest:
        return (pair_highest, pair_lowest)
    return None
<commit_msg>deal with tie hands<commit_after>

def poker(hands):
    """Return a list of winning hands: poker([hand,...]) => [hand,...]"""
    return allmax(hands, key=hand_rank)

def allmax(iterable, key=None):
    """Return a list of all items equal to the max of the iterable"""
    return None

def hand_rank(hand):
    """define a rank for a specific hand"""
    ranks = card_ranks(hand)
    if straight(ranks) and flush(hand):            # straight flush
        return (8, max(ranks))
    elif kind(4, ranks):                           # 4 of a kind
        return (7, kind(4, ranks), kind(1, ranks))
    elif kind(3, ranks) and kind(2, ranks):        # full house
        return (6, kind(3, ranks), kind(2, ranks))
    elif flush(hand):                              # flush
        return (5, ranks)
    elif straight(ranks):                          # straight
        return (4, max(ranks))
    elif kind(3, ranks):                           # 3 of a kind
        return (3, kind(3, ranks), ranks)
    elif two_pair(ranks):                          # 2 pair
        return (2, two_pair(ranks), ranks)
    elif kind(2, ranks):                           # kind
        return (1, kind(2, ranks), ranks)
    else:                                          # high card
        return (0, ranks)

def card_ranks(cards):
    """ Return a list of the ranks, sorted with higher first"""
    ranks = ["--23456789TJQKA".index(r) for r, s in cards]
    ranks.sort(reverse=True)
    return [5, 4, 3, 2, 1] if ranks == [14, 5, 4, 3, 2] else ranks

def straight(ranks):
    """ Return True if the ordered ranks from a 5 card straight"""
    return (max(ranks) - min(ranks) == 4) and len(set(ranks)) == 5

def flush(hand):
    """ Return True if all cards have the same suit"""
    suits = [s for r, s in hand]
    return len(set(suits)) == 1

def kind(n, ranks):
    """ Return the first rank that this hand has exactly n
        and return None otherwise"""
    for r in ranks:
        if ranks.count(r) == n:
            return r
    return None

def two_pair(ranks):
    """If there are two pair, return the two ranks as a
       tuple: (highest, lowest); otherwise return None."""
    pair_highest = kind(2, ranks)
    pair_lowest = kind(2, list(reversed(ranks)))
    if pair_highest and pair_highest != pair_lowest:
        return (pair_highest, pair_lowest)
    return None
<|endoftext|>


<commit_before>from django.db import models

class AbstractApplicationKeyValue(models.Model):
    """ Abstract model for application+Key/value pair. """
    application = models.CharField(max_length=300, db_index=True)
    key = models.CharField(max_length=300, db_index=True)
    value = models.TextField(null=True, blank=True)

    class Meta:
        abstract = True # This model will then not be used to create any database table. Instead, when it is used as a base class for other models, its fields will be added to those of the child class.

    def __unicode__(self):
        return '{0}.{1}={2}'.format(self.application, self.key, self.value)
<commit_msg>apps.core.models.abstract_applicationkeyvalue: Added index to value field.<commit_after>from django.db import models

class AbstractApplicationKeyValue(models.Model):
    """ Abstract model for application+Key/value pair. """
    application = models.CharField(max_length=300, db_index=True)
    key = models.CharField(max_length=300, db_index=True)
    value = models.TextField(null=True, blank=True, db_index=True)

    class Meta:
        abstract = True # This model will then not be used to create any database table. Instead, when it is used as a base class for other models, its fields will be added to those of the child class.

    def __unicode__(self):
        return '{0}.{1}={2}'.format(self.application, self.key, self.value)
<|endoftext|>


<commit_before>from django import template
import os.path

from django.utils.translation import ugettext_lazy

from devilry.devilry_markup import parse_markdown
import tomd

register = template.Library()

@register.filter("devilry_truncatefileextension")
def devilry_truncatefileextension(value, max_length):
    """
    Args:
        value: filename.
        max_length: number of characters the truncated
            string consists of including the extension

    Returns:
        str: truncated filename.

    Example:
        If max_length is 10, the string "Delivery.pdf" will be
        truncated to "Deli...pdf"
    """
    if len(value) == 0:
        return 'NO_NAME'
    else:
        offset = 3              # show at least three letters from filename
        min_value_length = 8    # entire value name is same length or less than ex. Del.html

        if len(value) <= min_value_length:
            return value
        elif len(value) > max_length:
            splitted = os.path.splitext(value)
            value_extension = splitted[1].strip('.')   # get extension

            if (max_length - len(value_extension) - 3) < offset:
                # show at least three letters from valuename
                # to ensure no files are called "...<fileextension>"
                truncated_value = value[:offset] + '...' + value_extension
            else:
                truncated_value = value[:max_length - len(value_extension) - 3] + '...' + value_extension
            return truncated_value

    return value

@register.filter("devilry_verbosenumber")
def devilry_verbosenumber(value, number):
    """
    Numbers from 1 to 10 is given as verbose(first, second, third, ...)
    and all numbers above 10 has the number and the corresponding ending(11th, 23rd, 32nd, 41st, ...)

    Args:
        value: The value passed(empty in this case).
        number: To get the verbose version of.

    Returns:
        str: Verbose version of number.
    """
    numbers = {
        1: ugettext_lazy('first'),
        2: ugettext_lazy('second'),
        3: ugettext_lazy('third'),
        4: ugettext_lazy('fourth'),
        5: ugettext_lazy('fifth'),
        6: ugettext_lazy('sixth'),
        7: ugettext_lazy('seventh'),
        8: ugettext_lazy('eighth'),
        9: ugettext_lazy('ninth'),
        10: ugettext_lazy('tenth')
    }

    if number <= 10:
        # use numbers dictionary
        # to get verbose result
        return numbers[number]
    return '{}.'.format(number)

@register.filter("devilry_group_comment_published")
def devilry_group_comment_published(comment):
    """
    Get the published datetime of a :class:`~devilry_group.GroupComment`

    Args:
        comment: A :obj:`~devilry_group.GroupComment` object.

    Returns:
        DateTime: published datetime of the comment.

    """
    return comment.get_published_datetime()

@register.filter("devilry_group_markdown")
def devilry_group_markdown(value):
    return parse_markdown.markdown_full(value)

@register.filter("devilry_group_html_to_markdown")
def devilry_group_html_to_markdown(value):
    print tomd.convert(value)
    return tomd.convert(value)

@register.inclusion_tag("devilry_group/template_tags/devilry_group_comment_user_is_none.django.html")
def devilry_group_comment_user_is_none():
    return {}
<commit_msg>devilry_group: Removed unused import of tomd and method using import #1037<commit_after>from django import template
import os.path

from django.utils.translation import ugettext_lazy

from devilry.devilry_markup import parse_markdown

register = template.Library()

@register.filter("devilry_truncatefileextension")
def devilry_truncatefileextension(value, max_length):
    """
    Args:
        value: filename.
        max_length: number of characters the truncated
            string consists of including the extension

    Returns:
        str: truncated filename.

    Example:
        If max_length is 10, the string "Delivery.pdf" will be
        truncated to "Deli...pdf"
    """
    if len(value) == 0:
        return 'NO_NAME'
    else:
        offset = 3              # show at least three letters from filename
        min_value_length = 8    # entire value name is same length or less than ex. Del.html

        if len(value) <= min_value_length:
            return value
        elif len(value) > max_length:
            splitted = os.path.splitext(value)
            value_extension = splitted[1].strip('.')   # get extension

            if (max_length - len(value_extension) - 3) < offset:
                # show at least three letters from valuename
                # to ensure no files are called "...<fileextension>"
                truncated_value = value[:offset] + '...' + value_extension
            else:
                truncated_value = value[:max_length - len(value_extension) - 3] + '...' + value_extension
            return truncated_value

    return value

@register.filter("devilry_verbosenumber")
def devilry_verbosenumber(value, number):
    """
    Numbers from 1 to 10 is given as verbose(first, second, third, ...)
    and all numbers above 10 has the number and the corresponding ending(11th, 23rd, 32nd, 41st, ...)

    Args:
        value: The value passed(empty in this case).
        number: To get the verbose version of.

    Returns:
        str: Verbose version of number.
    """
    numbers = {
        1: ugettext_lazy('first'),
        2: ugettext_lazy('second'),
        3: ugettext_lazy('third'),
        4: ugettext_lazy('fourth'),
        5: ugettext_lazy('fifth'),
        6: ugettext_lazy('sixth'),
        7: ugettext_lazy('seventh'),
        8: ugettext_lazy('eighth'),
        9: ugettext_lazy('ninth'),
        10: ugettext_lazy('tenth')
    }

    if number <= 10:
        # use numbers dictionary
        # to get verbose result
        return numbers[number]
    return '{}.'.format(number)

@register.filter("devilry_group_comment_published")
def devilry_group_comment_published(comment):
    """
    Get the published datetime of a :class:`~devilry_group.GroupComment`

    Args:
        comment: A :obj:`~devilry_group.GroupComment` object.

    Returns:
        DateTime: published datetime of the comment.

    """
    return comment.get_published_datetime()

@register.filter("devilry_group_markdown")
def devilry_group_markdown(value):
    return parse_markdown.markdown_full(value)

@register.inclusion_tag("devilry_group/template_tags/devilry_group_comment_user_is_none.django.html")
def devilry_group_comment_user_is_none():
    return {}
<|endoftext|>


<commit_before>import pickle
import pysixtrack
import numpy as np
import NAFFlib
import helpers as hp
import footprint
import matplotlib.pyplot as plt

track_with = 'PySixtrack'
# track_with = 'Sixtrack'
track_with = 'sixtracklib'
device_opencl = '0.0'
device_opencl = None

n_turns = 100

with open('line.pkl', 'rb') as fid:
    line = pickle.load(fid)

with open('particle_on_CO.pkl', 'rb') as fid:
    partCO = pickle.load(fid)

with open('DpxDpy_for_footprint.pkl', 'rb') as fid:
    temp_data = pickle.load(fid)

xy_norm = temp_data['xy_norm']
DpxDpy_wrt_CO = temp_data['DpxDpy_wrt_CO']

if track_with == 'PySixtrack':

    part = pysixtrack.Particles(**partCO)

    x_tbt, px_tbt, y_tbt, py_tbt, sigma_tbt, delta_tbt = hp.track_particle_pysixtrack(
        line, part=part, Dx_wrt_CO_m=0., Dpx_wrt_CO_rad=DpxDpy_wrt_CO[:, :, 0].flatten(),
        Dy_wrt_CO_m=0, Dpy_wrt_CO_rad=DpxDpy_wrt_CO[:, :, 1].flatten(),
        Dsigma_wrt_CO_m=0., Ddelta_wrt_CO=0., n_turns=n_turns, verbose=True)

elif track_with == 'Sixtrack':
    x_tbt, px_tbt, y_tbt, py_tbt, sigma_tbt, delta_tbt = hp.track_particle_sixtrack(
        partCO=partCO, Dx_wrt_CO_m=0., Dpx_wrt_CO_rad=DpxDpy_wrt_CO[:, :, 0].flatten(),
        Dy_wrt_CO_m=0, Dpy_wrt_CO_rad=DpxDpy_wrt_CO[:, :, 1].flatten(),
        Dsigma_wrt_CO_m=0., Ddelta_wrt_CO=0., n_turns=n_turns)

elif track_with == 'sixtracklib':
    x_tbt, px_tbt, y_tbt, py_tbt, sigma_tbt, delta_tbt = hp.track_particle_sixtracklib(
        line=line, partCO=partCO, Dx_wrt_CO_m=0., Dpx_wrt_CO_rad=DpxDpy_wrt_CO[:, :, 0].flatten(),
        Dy_wrt_CO_m=0., Dpy_wrt_CO_rad=DpxDpy_wrt_CO[:, :, 1].flatten(),
        Dsigma_wrt_CO_m=0., Ddelta_wrt_CO=0., n_turns=n_turns, device_opencl=device_opencl)
else:
    raise ValueError('What?!')

n_part = x_tbt.shape[1]
Qx = np.zeros(n_part)
Qy = np.zeros(n_part)

for i_part in range(n_part):
    Qx[i_part] = NAFFlib.get_tune(x_tbt[:, i_part])
    Qy[i_part] = NAFFlib.get_tune(y_tbt[:, i_part])

Qxy_fp = np.zeros_like(xy_norm)

Qxy_fp[:, :, 0] = np.reshape(Qx, Qxy_fp[:, :, 0].shape)
Qxy_fp[:, :, 1] = np.reshape(Qy, Qxy_fp[:, :, 1].shape)

plt.close('all')

fig3 = plt.figure(3)
axcoord = fig3.add_subplot(1, 1, 1)
footprint.draw_footprint(xy_norm, axis_object=axcoord, linewidth = 1)
axcoord.set_xlim(right=np.max(xy_norm[:, :, 0]))
axcoord.set_ylim(top=np.max(xy_norm[:, :, 1]))

fig4 = plt.figure(4)
axFP = fig4.add_subplot(1, 1, 1)
footprint.draw_footprint(Qxy_fp, axis_object=axFP, linewidth = 1)
# axFP.set_xlim(right=np.max(Qxy_fp[:, :, 0]))
# axFP.set_ylim(top=np.max(Qxy_fp[:, :, 1]))
fig4.suptitle(track_with)
plt.show()
<commit_msg>A title<commit_after>import pickle
import pysixtrack
import numpy as np
import NAFFlib
import helpers as hp
import footprint
import matplotlib.pyplot as plt

track_with = 'PySixtrack'
# track_with = 'Sixtrack'
track_with = 'Sixtracklib'
device_opencl = '0.0'
device_opencl = None

n_turns = 100

with open('line.pkl', 'rb') as fid:
    line = pickle.load(fid)

with open('particle_on_CO.pkl', 'rb') as fid:
    partCO = pickle.load(fid)

with open('DpxDpy_for_footprint.pkl', 'rb') as fid:
    temp_data = pickle.load(fid)

xy_norm = temp_data['xy_norm']
DpxDpy_wrt_CO = temp_data['DpxDpy_wrt_CO']

if track_with == 'PySixtrack':

    part = pysixtrack.Particles(**partCO)

    x_tbt, px_tbt, y_tbt, py_tbt, sigma_tbt, delta_tbt = hp.track_particle_pysixtrack(
        line, part=part, Dx_wrt_CO_m=0., Dpx_wrt_CO_rad=DpxDpy_wrt_CO[:, :, 0].flatten(),
        Dy_wrt_CO_m=0, Dpy_wrt_CO_rad=DpxDpy_wrt_CO[:, :, 1].flatten(),
        Dsigma_wrt_CO_m=0., Ddelta_wrt_CO=0., n_turns=n_turns, verbose=True)

    info = track_with

elif track_with == 'Sixtrack':
    x_tbt, px_tbt, y_tbt, py_tbt, sigma_tbt, delta_tbt = hp.track_particle_sixtrack(
        partCO=partCO, Dx_wrt_CO_m=0., Dpx_wrt_CO_rad=DpxDpy_wrt_CO[:, :, 0].flatten(),
        Dy_wrt_CO_m=0, Dpy_wrt_CO_rad=DpxDpy_wrt_CO[:, :, 1].flatten(),
        Dsigma_wrt_CO_m=0., Ddelta_wrt_CO=0., n_turns=n_turns)
    info = track_with

elif track_with == 'Sixtracklib':
    x_tbt, px_tbt, y_tbt, py_tbt, sigma_tbt, delta_tbt = hp.track_particle_sixtracklib(
        line=line, partCO=partCO, Dx_wrt_CO_m=0., Dpx_wrt_CO_rad=DpxDpy_wrt_CO[:, :, 0].flatten(),
        Dy_wrt_CO_m=0., Dpy_wrt_CO_rad=DpxDpy_wrt_CO[:, :, 1].flatten(),
        Dsigma_wrt_CO_m=0., Ddelta_wrt_CO=0., n_turns=n_turns, device_opencl=device_opencl)
    info = track_with
    if device_opencl is None:
    	info += ' (CPU)'
    else:
    	info += ' (GPU %s)'%device_opencl
else:
    raise ValueError('What?!')

n_part = x_tbt.shape[1]
Qx = np.zeros(n_part)
Qy = np.zeros(n_part)

for i_part in range(n_part):
    Qx[i_part] = NAFFlib.get_tune(x_tbt[:, i_part])
    Qy[i_part] = NAFFlib.get_tune(y_tbt[:, i_part])

Qxy_fp = np.zeros_like(xy_norm)

Qxy_fp[:, :, 0] = np.reshape(Qx, Qxy_fp[:, :, 0].shape)
Qxy_fp[:, :, 1] = np.reshape(Qy, Qxy_fp[:, :, 1].shape)

plt.close('all')

fig3 = plt.figure(3)
axcoord = fig3.add_subplot(1, 1, 1)
footprint.draw_footprint(xy_norm, axis_object=axcoord, linewidth = 1)
axcoord.set_xlim(right=np.max(xy_norm[:, :, 0]))
axcoord.set_ylim(top=np.max(xy_norm[:, :, 1]))

fig4 = plt.figure(4)
axFP = fig4.add_subplot(1, 1, 1)
footprint.draw_footprint(Qxy_fp, axis_object=axFP, linewidth = 1)
# axFP.set_xlim(right=np.max(Qxy_fp[:, :, 0]))
# axFP.set_ylim(top=np.max(Qxy_fp[:, :, 1]))
fig4.suptitle(info)
plt.show()
<|endoftext|>


<commit_before># Copyright 2014-2016 The ODL development group
#
# This file is part of ODL.
#
# ODL is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ODL 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 the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ODL.  If not, see <http://www.gnu.org/licenses/>.

"""L1-regularized denoising using the proximal gradient solvers.

Solves the optimization problem

    min_x  lam || T(W.inverse(x)) - g ||_2^2 + lam * || x ||_1

Where ``W`` is a wavelet operator, ``T`` is a parallel beam ray transform and
 ``g`` is given noisy data.

The proximal gradient solvers are also known as ISTA and FISTA.
"""

import odl
import numpy as np

# --- Set up problem definition --- #

# Discrete reconstruction space: discretized functions on the rectangle
# [-20, 20]^2 with 256 samples per dimension.
space = odl.uniform_discr(
    min_pt=[-20, -20], max_pt=[20, 20], shape=[256, 256], dtype='float32')

# Make a parallel beam geometry with flat detector
# Angles: uniformly spaced, n = 300, min = 0, max = pi
angle_partition = odl.uniform_partition(0, np.pi, 300)
# Detector: uniformly sampled, n = 300, min = -30, max = 30
detector_partition = odl.uniform_partition(-30, 30, 300)
geometry = odl.tomo.Parallel2dGeometry(angle_partition, detector_partition)

# The implementation of the ray transform to use, options:
# 'scikit'                    Requires scikit-image (can be installed by
#                             running ``pip install scikit-image``).
# 'astra_cpu', 'astra_cuda'   Requires astra tomography to be installed.
#                             Astra is much faster than scikit. Webpage:
#                             https://github.com/astra-toolbox/astra-toolbox
impl = 'astra_cuda'

# Create the forward operator, and also the vectorial forward operator.
ray_trafo = odl.tomo.RayTransform(space, geometry, impl=impl)

# --- Generate artificial data --- #

# Create phantom
discr_phantom = odl.phantom.shepp_logan(space, modified=True)

# Create sinogram of forward projected phantom with noise
data = ray_trafo(discr_phantom)
data += odl.phantom.white_noise(ray_trafo.range) * np.mean(data) * 0.1

# --- Set up the inverse problem --- #

# Create wavelet operator
W = odl.trafos.WaveletTransform(space, wavelet='haar', nlevels=5)

# The wavelets bases are normalized to constant norm regardless of scale.
# since we want to penalize "small" wavelets more than "large" ones, we need
# to weight by the scale of the wavelets.
# The "area" of the wavelets scales as 2 ^ scale, but we use a slightly smaller
# number in order to allow some high frequencies.
scales = W.scales()
Wtrafoinv = W.inverse * (1 / (np.power(1.7, scales)))

# Create regularizer as l1 norm
regularizer = 0.0002 * odl.solvers.L1Norm(W.range)

# l2-squared norm of residual
l2_norm_sq = odl.solvers.L2NormSquared(ray_trafo.range).translated(data)

# Compose from the right with ray transform and wavelet transform
data_discrepancy = l2_norm_sq * ray_trafo * Wtrafoinv

# --- Select solver parameters and solve using proximal gradient --- #

# Select step-size that guarantees convergence.
gamma = 0.05

# Optionally pass callback to the solver to display intermediate results
callback = (odl.solvers.CallbackPrintIteration() &
            odl.solvers.CallbackShow())

def callb(x):
    """Callback that displays the inverse wavelet transform of current iter."""
    callback(Wtrafoinv(x))

# Run the algorithm (FISTA)
x = data_discrepancy.domain.zero()
odl.solvers.accelerated_proximal_gradient(
    x, f=regularizer, g=data_discrepancy, niter=200, gamma=gamma,
    callback=callb)

# Display images
data.show(title='Data')
x.show(title='Wavelet coefficients')
Wtrafoinv(x).show('Wavelet regularized reconstruction')
<commit_msg>MAINT: Improve parameters of wavelet tomo example<commit_after># Copyright 2014-2016 The ODL development group
#
# This file is part of ODL.
#
# ODL is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ODL 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 the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ODL.  If not, see <http://www.gnu.org/licenses/>.

"""L1-regularized denoising using the proximal gradient solvers.

Solves the optimization problem

    min_x  lam || T(W.inverse(x)) - g ||_2^2 + lam * || x ||_1

Where ``W`` is a wavelet operator, ``T`` is a parallel beam ray transform and
 ``g`` is given noisy data.

The proximal gradient solvers are also known as ISTA and FISTA.
"""

import odl
import numpy as np

# --- Set up problem definition --- #

# Discrete reconstruction space: discretized functions on the rectangle
# [-20, 20]^2 with 256 samples per dimension.
space = odl.uniform_discr(
    min_pt=[-20, -20], max_pt=[20, 20], shape=[256, 256], dtype='float32')

# Make a parallel beam geometry with flat detector
# Angles: uniformly spaced, n = 300, min = 0, max = pi
angle_partition = odl.uniform_partition(0, np.pi, 300)
# Detector: uniformly sampled, n = 300, min = -30, max = 30
detector_partition = odl.uniform_partition(-30, 30, 300)
geometry = odl.tomo.Parallel2dGeometry(angle_partition, detector_partition)

# The implementation of the ray transform to use, options:
# 'scikit'                    Requires scikit-image (can be installed by
#                             running ``pip install scikit-image``).
# 'astra_cpu', 'astra_cuda'   Requires astra tomography to be installed.
#                             Astra is much faster than scikit. Webpage:
#                             https://github.com/astra-toolbox/astra-toolbox
impl = 'astra_cuda'

# Create the forward operator, and also the vectorial forward operator.
ray_trafo = odl.tomo.RayTransform(space, geometry, impl=impl)

# --- Generate artificial data --- #

# Create phantom
discr_phantom = odl.phantom.shepp_logan(space, modified=True)

# Create sinogram of forward projected phantom with noise
data = ray_trafo(discr_phantom)
data += odl.phantom.white_noise(ray_trafo.range) * np.mean(data) * 0.1

# --- Set up the inverse problem --- #

# Create wavelet operator
W = odl.trafos.WaveletTransform(space, wavelet='haar', nlevels=5)

# The wavelets bases are normalized to constant norm regardless of scale.
# since we want to penalize "small" wavelets more than "large" ones, we need
# to weight by the scale of the wavelets.
# The "area" of the wavelets scales as 2 ^ scale, but we use a slightly smaller
# number in order to allow some high frequencies.
scales = W.scales()
Wtrafoinv = W.inverse * (1 / (np.power(1.7, scales)))

# Create regularizer as l1 norm
regularizer = 0.0005 * odl.solvers.L1Norm(W.range)

# l2-squared norm of residual
l2_norm_sq = odl.solvers.L2NormSquared(ray_trafo.range).translated(data)

# Compose from the right with ray transform and wavelet transform
data_discrepancy = l2_norm_sq * ray_trafo * Wtrafoinv

# --- Select solver parameters and solve using proximal gradient --- #

# Select step-size that gives convergence.
gamma = 0.2

# Optionally pass callback to the solver to display intermediate results
callback = (odl.solvers.CallbackPrintIteration() &
            odl.solvers.CallbackShow(display_step=5))

def callb(x):
    """Callback that displays the inverse wavelet transform of current iter."""
    callback(Wtrafoinv(x))

# Run the algorithm (FISTA)
x = data_discrepancy.domain.zero()
odl.solvers.accelerated_proximal_gradient(
    x, f=regularizer, g=data_discrepancy, niter=400, gamma=gamma,
    callback=callb)

# Display images
data.show(title='Data')
x.show(title='Wavelet coefficients')
Wtrafoinv(x).show('Wavelet regularized reconstruction')
<|endoftext|>


<commit_before>import datetime
import os
import time

class CallbackModule(object):
    """
    A plugin for timing tasks
    """
    def __init__(self):
        self.stats = {}
        self.current = None

    def playbook_on_task_start(self, name, is_conditional):
        """
        Logs the start of each task
        """

        if os.getenv("ANSIBLE_PROFILE_DISABLE") is not None:
            return

        if self.current is not None:
            # Record the running time of the last executed task
            self.stats[self.current] = time.time() - self.stats[self.current]

        # Record the start time of the current task
        self.current = name
        self.stats[self.current] = time.time()

    def playbook_on_stats(self, stats):
        """
        Prints the timings
        """

        if os.getenv("ANSIBLE_PROFILE_DISABLE") is not None:
            return

        # Record the timing of the very last task
        if self.current is not None:
            self.stats[self.current] = time.time() - self.stats[self.current]

        # Sort the tasks by their running time
        results = sorted(
            self.stats.items(),
            key=lambda value: value[1],
            reverse=True,
        )

        # Just keep the top 10
        results = results[:10]

        # Print the timings
        for name, elapsed in results:
            print(
                "{0:-<70}{1:->9}".format(
                    '{0} '.format(name),
                    ' {0:.02f}s'.format(elapsed),
                )
            )

        total_seconds = sum([x[1] for x in self.stats.items()])
        print("\nPlaybook finished: {0}, {1} total tasks.  {2} elapsed. \n".format(
                time.asctime(),
                len(self.stats.items()),
                datetime.timedelta(seconds=(int(total_seconds)))
                )
          )
<commit_msg>Adds LICENSE information and source URL for profile_tasks plugin<commit_after># Source: https://github.com/jlafon/ansible-profile
# License: MIT
# More info: http://jlafon.io/ansible-profiling.html
# The profiling functionality will be provided by Ansible v2,
# since this callback_plugin has been merged into core,
# but we're including here to support older versions of Ansible.
import datetime
import os
import time

class CallbackModule(object):
    """
    A plugin for timing tasks
    """
    def __init__(self):
        self.stats = {}
        self.current = None

    def playbook_on_task_start(self, name, is_conditional):
        """
        Logs the start of each task
        """

        if os.getenv("ANSIBLE_PROFILE_DISABLE") is not None:
            return

        if self.current is not None:
            # Record the running time of the last executed task
            self.stats[self.current] = time.time() - self.stats[self.current]

        # Record the start time of the current task
        self.current = name
        self.stats[self.current] = time.time()

    def playbook_on_stats(self, stats):
        """
        Prints the timings
        """

        if os.getenv("ANSIBLE_PROFILE_DISABLE") is not None:
            return

        # Record the timing of the very last task
        if self.current is not None:
            self.stats[self.current] = time.time() - self.stats[self.current]

        # Sort the tasks by their running time
        results = sorted(
            self.stats.items(),
            key=lambda value: value[1],
            reverse=True,
        )

        # Just keep the top 10
        results = results[:10]

        # Print the timings
        for name, elapsed in results:
            print(
                "{0:-<70}{1:->9}".format(
                    '{0} '.format(name),
                    ' {0:.02f}s'.format(elapsed),
                )
            )

        total_seconds = sum([x[1] for x in self.stats.items()])
        print("\nPlaybook finished: {0}, {1} total tasks.  {2} elapsed. \n".format(
                time.asctime(),
                len(self.stats.items()),
                datetime.timedelta(seconds=(int(total_seconds)))
                )
          )
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
##############################################################################
#
#    KMEE, KM Enterprising Engineering
#    Copyright (C) 2014 - Michell Stuttgart Faria (<http://www.kmee.com.br>).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    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 the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from openerp import models

class SaleAdvancePaymentInvoice(models.Model):
    _inherit = 'sale.advance.payment.inv'

    def _get_line_qty(self, cr, uid, line, context=None):
        if (line.order_id.invoice_quantity == 'order'):
            if line.product_uos:
                return line.product_uos_qty or 0.0
        return line.product_uom_qty

    def _get_line_uom(self, cr, uid, line, context=None):
        if (line.order_id.invoice_quantity == 'order'):
            if line.product_uos:
                return line.product_uos.id
        return line.product_uom.id

    def _prepare_advance_invoice_vals(self, cr, uid, ids, context=None):

        # Lista de campos
        result = super(
            SaleAdvancePaymentInvoice, self)._prepare_advance_invoice_vals(
                cr, uid, ids, context)

        if context is None:
            context = {}

        sale_obj = self.pool['sale.order']
        wizard = self.browse(cr, uid, ids[0], context)
        # get invoice type
        payment_type = wizard.advance_payment_method

        for res in result:
            for sale in sale_obj.browse(cr, uid, [res[0]], context=context):

                # Verificamos o tipo de fatura
                if payment_type == 'percentage':
                    percent = wizard.amount / 100.0
                else:
                    percent = wizard.amount / sale.amount_gross

                # Aux list of invoice
                list_invoice = []

                # Invoice dict in res
                invoice_dict = res[1]['invoice_line'][0][2]

                for order_line in sale.order_line:

                    # Objeto sale.order.line
                    order_line_obj = self.pool.get('sale.order.line')

                    res_aux = {}
                    res_aux = (order_line_obj.
                               l10n_br_sale_prepare_order_line_invoice_line(
                                   cr, uid, order_line, res_aux, context))

                    res_aux = order_line_obj.\
                        l10n_br_sale_product_prepare_order_line_invoice_line(
                            cr, uid, order_line, res_aux, context)

                    tax_list_id = []

                    uosqty = self._get_line_qty(
                        cr, uid, order_line, context=context)
                    uos_id = self._get_line_uom(
                        cr, uid, order_line, context=context)

                    # Add the ID of tax of order line
                    for tax in order_line.tax_id:
                        tax_list_id.append(tax.id)

                    # create the invoice
                    inv_line_values = {
                        'name': order_line.name,
                        'origin': invoice_dict['origin'],
                        'account_id': invoice_dict['account_id'],
                        'price_unit': order_line.price_unit,
                        'quantity': (percent * uosqty) or 1.0,
                        'discount': invoice_dict['discount'],
                        'uos_id': uos_id,
                        'product_id': order_line.product_id.id,
                        'invoice_line_tax_id': [(6, 0, tax_list_id)],
                        'account_analytic_id': invoice_dict.get(
                            'account_analytic_id'),
                        'fiscal_category_id': res_aux.get(
                            'fiscal_category_id'),
                        'fiscal_position': res_aux.get('fiscal_position'),
                        'cfop_id': res_aux.get('cfop_id'),
                    }

                    list_invoice.append((0, 0, inv_line_values))

                res[1]['invoice_line'] = list_invoice
                res[1]['comment'] = invoice_dict['name']
        return result
<commit_msg>FIX: AccessError (Modelo de documento: sale.advance.payment.inv)<commit_after># -*- coding: utf-8 -*-
##############################################################################
#
#    KMEE, KM Enterprising Engineering
#    Copyright (C) 2014 - Michell Stuttgart Faria (<http://www.kmee.com.br>).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    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 the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from openerp import models

class SaleAdvancePaymentInvoice(models.TransientModel):
    _inherit = 'sale.advance.payment.inv'

    def _get_line_qty(self, cr, uid, line, context=None):
        if (line.order_id.invoice_quantity == 'order'):
            if line.product_uos:
                return line.product_uos_qty or 0.0
        return line.product_uom_qty

    def _get_line_uom(self, cr, uid, line, context=None):
        if (line.order_id.invoice_quantity == 'order'):
            if line.product_uos:
                return line.product_uos.id
        return line.product_uom.id

    def _prepare_advance_invoice_vals(self, cr, uid, ids, context=None):

        # Lista de campos
        result = super(
            SaleAdvancePaymentInvoice, self)._prepare_advance_invoice_vals(
                cr, uid, ids, context)

        if context is None:
            context = {}

        sale_obj = self.pool['sale.order']
        wizard = self.browse(cr, uid, ids[0], context)
        # get invoice type
        payment_type = wizard.advance_payment_method

        for res in result:
            for sale in sale_obj.browse(cr, uid, [res[0]], context=context):

                # Verificamos o tipo de fatura
                if payment_type == 'percentage':
                    percent = wizard.amount / 100.0
                else:
                    percent = wizard.amount / sale.amount_gross

                # Aux list of invoice
                list_invoice = []

                # Invoice dict in res
                invoice_dict = res[1]['invoice_line'][0][2]

                for order_line in sale.order_line:

                    # Objeto sale.order.line
                    order_line_obj = self.pool.get('sale.order.line')

                    res_aux = {}
                    res_aux = (order_line_obj.
                               l10n_br_sale_prepare_order_line_invoice_line(
                                   cr, uid, order_line, res_aux, context))

                    res_aux = order_line_obj.\
                        l10n_br_sale_product_prepare_order_line_invoice_line(
                            cr, uid, order_line, res_aux, context)

                    tax_list_id = []

                    uosqty = self._get_line_qty(
                        cr, uid, order_line, context=context)
                    uos_id = self._get_line_uom(
                        cr, uid, order_line, context=context)

                    # Add the ID of tax of order line
                    for tax in order_line.tax_id:
                        tax_list_id.append(tax.id)

                    # create the invoice
                    inv_line_values = {
                        'name': order_line.name,
                        'origin': invoice_dict['origin'],
                        'account_id': invoice_dict['account_id'],
                        'price_unit': order_line.price_unit,
                        'quantity': (percent * uosqty) or 1.0,
                        'discount': invoice_dict['discount'],
                        'uos_id': uos_id,
                        'product_id': order_line.product_id.id,
                        'invoice_line_tax_id': [(6, 0, tax_list_id)],
                        'account_analytic_id': invoice_dict.get(
                            'account_analytic_id'),
                        'fiscal_category_id': res_aux.get(
                            'fiscal_category_id'),
                        'fiscal_position': res_aux.get('fiscal_position'),
                        'cfop_id': res_aux.get('cfop_id'),
                    }

                    list_invoice.append((0, 0, inv_line_values))

                res[1]['invoice_line'] = list_invoice
                res[1]['comment'] = invoice_dict['name']
        return result
<|endoftext|>