<commit_before># -*- coding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in module root
# directory
##############################################################################
from openerp import api, fields, models, _
from openerp.exceptions import Warning
from openerp import tools
from lxml import etree
from ast import literal_eval
from openerp.osv.orm import setup_modifiers
import logging
_logger = logging.getLogger(__name__)

class ResCompanyProperty(models.Model):
    """
    We dont use res.company because most user dont' have access rights to edit
    it
    """
    _name = "res.company.property"
    _description = "Company Property"
    _auto = False
    _rec_name = 'display_name'
    _depends = {
        'res.company': [
            'id',
        ],
    }

    company_id = fields.Many2one('res.company', 'Company', required=True,)

    def init(self, cr):
        tools.drop_view_if_exists(cr, self._table)
        query = """
            SELECT
                c.id as id,
                c.id as company_id
            FROM
                res_company c
        """
        cr.execute("""CREATE or REPLACE VIEW %s as (%s
        )""" % (self._table, query))

    property_field = fields.Char(
        compute='_get_property_field'
    )
    property_account_id = fields.Many2one(
        'account.account',
        string='Account',
        compute='_get_property_account',
        inverse='_set_property_account',
    )
    property_term_id = fields.Many2one(
        'account.payment.term',
        string='Payment Term',
        compute='_get_property_term',
        inverse='_set_property_term',
    )
    property_position_id = fields.Many2one(
        'account.fiscal.position',
        string='Fiscal Position',
        compute='_get_property_position',
        inverse='_set_property_position',
    )
    property_pricelist_id = fields.Many2one(
        'product.pricelist',
        string='Pricelist',
        compute='_get_property_pricelist',
        inverse='_set_property_pricelist',
    )
    display_name = fields.Char(
        compute='_get_display_name'
    )

    @api.model
    def _get_companies(self):
        domain = []
        comodel = self._get_property_comodel()
        if comodel not in [
                'account.payment.term', 'product.pricelist',
                'account.fiscal.position']:
            domain = [('company_id.consolidation_company', '=', False)]
        return self.search(domain)

    @api.model
    def action_company_properties(self):
        property_field = self._context.get('property_field', False)
        if not property_field:
            return True

        company_properties = self._get_companies()
        action = self.env.ref(
            'account_multicompany_usability.action_res_company_property')

        if not action:
            return False
        action_read = action.read()[0]
        action_read['context'] = self._context
        action_read['domain'] = [('id', 'in', company_properties.ids)]
        return action_read

    @api.model
    def _get_property_comodel(self):
        property_field = self._context.get('property_field')
        record = self._get_record()
        if record:
            field = self._get_record()._fields.get(property_field)
            return field and field.comodel_name or False

    @api.model
    def _get_record(self):
        context = self._context
        active_model = context.get('active_model')
        active_id = context.get('active_id')
        property_field = context.get('property_field')
        if not property_field or not active_id or not active_model:
            _logger.warn(
                'Could not get property record from context %s' % context)
            return False
        return self.with_context(
            force_company=self.id).env[active_model].browse(
            active_id)

    @api.model
    def fields_view_get(
            self, view_id=None, view_type=False, toolbar=False, submenu=False):
        """
        Con esta funcion hacemos dos cosas:
        1. Mostrar solo la columna que corresponda segun el modelo
        2. Agregar dominio segun el dominio original de la porperty mas de cia
        """
        res = super(ResCompanyProperty, self).fields_view_get(
            view_id=view_id, view_type=view_type, toolbar=toolbar,
            submenu=submenu)
        doc = etree.XML(res['arch'])
        property_field = self._context.get('property_field')
        domain = self._context.get('property_domain')
        record = self._get_record()
        print 'record', record
        if record:
            field = self._get_record()._fields.get(property_field)
            # si no viene definido un property_domain buscamos uno para
            # definido ene l campo de la property
            if not domain:
                try:
                    domain = literal_eval(field.domain)
                except:
                    domain = []
            domain_elements = [str(x) for x in domain]

            # add company domain if comodel has company
            comodel = self._get_property_comodel()
            if comodel:
                if self.env[comodel]._fields.get('company_id'):
                    domain_elements += [
                        "'|'",
                        "('company_id', '=', False)",
                        "('company_id', '=', company_id)"]
            str_domain = '[%s]' % ','.join(domain_elements)

            company_property_field = self._get_company_property_field()
            xpath = "//field[@name='%s']" % company_property_field
            for node in doc.xpath(xpath):
                node.set('domain', str(str_domain))
                node.set('invisible', '0')
                # modifiers make still invisible = 1
                setup_modifiers(node, res['fields'][company_property_field])
        res['arch'] = etree.tostring(doc)
        return res

    @api.model
    def _get_company_property_field(self):
        comodel = self._get_property_comodel()
        if comodel == 'account.account':
            company_property_field = 'property_account_id'
        elif comodel == 'account.fiscal.position':
            company_property_field = 'property_position_id'
        elif comodel == 'account.payment.term':
            company_property_field = 'property_term_id'
        elif comodel == 'product.pricelist':
            company_property_field = 'property_pricelist_id'
        else:
            raise Warning(
                _('Property for model %s not implemented yet' % comodel))
        return company_property_field

    @api.one
    def _get_display_name(self):
        """
        No llamamos a super porque tendriamos que igualmente hacer un read
        para obtener la compania y no queremos disminuir la performance
        """
        company_field = getattr(
            self.with_context(no_company_sufix=True),
            self._get_company_property_field())
        display_name = '%s%s' % (
            company_field.display_name or _('None'),
            self.company_id.get_company_sufix())
        self.display_name = display_name

    @api.one
    def _get_property_field(self):
        self.property_field = self._context.get('property_field')

    @api.multi
    def _get_property_value(self):
        self.ensure_one()
        property_field = self.property_field
        record = self._get_record()
        if not record or not property_field:
            return False
        return getattr(
            record,
            property_field)

    @api.one
    def _get_property_account(self):
        if self._get_property_comodel() == 'account.account':
            self.property_account_id = self._get_property_value()

    @api.one
    def _get_property_position(self):
        if self._get_property_comodel() == 'account.fiscal.position':
            self.property_position_id = self._get_property_value()

    @api.one
    def _get_property_term(self):
        if self._get_property_comodel() == 'account.payment.term':
            self.property_term_id = self._get_property_value()

    @api.one
    def _get_property_pricelist(self):
        if self._get_property_comodel() == 'product.pricelist':
            self.property_pricelist_id = self._get_property_value()

    @api.one
    def _set_property_value(self, value):
        record = self._get_record()
        property_field = self.property_field
        if not record or not property_field:
            return True
        setattr(
            record,
            property_field,
            value)

    @api.one
    def _set_property_account(self):
        self._set_property_value(self.property_account_id.id)

    @api.one
    def _set_property_position(self):
        self._set_property_value(self.property_position_id.id)

    @api.one
    def _set_property_term(self):
        self._set_property_value(self.property_term_id.id)

    @api.one
    def _set_property_pricelist(self):
        self._set_property_value(self.property_pricelist_id.id)
<commit_msg>FIX view_type='form',<commit_after># -*- coding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in module root
# directory
##############################################################################
from openerp import api, fields, models, _
from openerp.exceptions import Warning
from openerp import tools
from lxml import etree
from ast import literal_eval
from openerp.osv.orm import setup_modifiers
import logging
_logger = logging.getLogger(__name__)

class ResCompanyProperty(models.Model):
    """
    We dont use res.company because most user dont' have access rights to edit
    it
    """
    _name = "res.company.property"
    _description = "Company Property"
    _auto = False
    _rec_name = 'display_name'
    _depends = {
        'res.company': [
            'id',
        ],
    }

    company_id = fields.Many2one('res.company', 'Company', required=True,)

    def init(self, cr):
        tools.drop_view_if_exists(cr, self._table)
        query = """
            SELECT
                c.id as id,
                c.id as company_id
            FROM
                res_company c
        """
        cr.execute("""CREATE or REPLACE VIEW %s as (%s
        )""" % (self._table, query))

    property_field = fields.Char(
        compute='_get_property_field'
    )
    property_account_id = fields.Many2one(
        'account.account',
        string='Account',
        compute='_get_property_account',
        inverse='_set_property_account',
    )
    property_term_id = fields.Many2one(
        'account.payment.term',
        string='Payment Term',
        compute='_get_property_term',
        inverse='_set_property_term',
    )
    property_position_id = fields.Many2one(
        'account.fiscal.position',
        string='Fiscal Position',
        compute='_get_property_position',
        inverse='_set_property_position',
    )
    property_pricelist_id = fields.Many2one(
        'product.pricelist',
        string='Pricelist',
        compute='_get_property_pricelist',
        inverse='_set_property_pricelist',
    )
    display_name = fields.Char(
        compute='_get_display_name'
    )

    @api.model
    def _get_companies(self):
        domain = []
        comodel = self._get_property_comodel()
        if comodel not in [
                'account.payment.term', 'product.pricelist',
                'account.fiscal.position']:
            domain = [('company_id.consolidation_company', '=', False)]
        return self.search(domain)

    @api.model
    def action_company_properties(self):
        property_field = self._context.get('property_field', False)
        if not property_field:
            return True

        company_properties = self._get_companies()
        action = self.env.ref(
            'account_multicompany_usability.action_res_company_property')

        if not action:
            return False
        action_read = action.read()[0]
        action_read['context'] = self._context
        action_read['domain'] = [('id', 'in', company_properties.ids)]
        return action_read

    @api.model
    def _get_property_comodel(self):
        property_field = self._context.get('property_field')
        record = self._get_record()
        if record:
            field = self._get_record()._fields.get(property_field)
            return field and field.comodel_name or False

    @api.model
    def _get_record(self):
        context = self._context
        active_model = context.get('active_model')
        active_id = context.get('active_id')
        property_field = context.get('property_field')
        if not property_field or not active_id or not active_model:
            _logger.warn(
                'Could not get property record from context %s' % context)
            return False
        return self.with_context(
            force_company=self.id).env[active_model].browse(
            active_id)

    @api.model
    def fields_view_get(
            self, view_id=None, view_type='form', toolbar=False,
            submenu=False):
        """
        Con esta funcion hacemos dos cosas:
        1. Mostrar solo la columna que corresponda segun el modelo
        2. Agregar dominio segun el dominio original de la porperty mas de cia
        """
        res = super(ResCompanyProperty, self).fields_view_get(
            view_id=view_id, view_type=view_type, toolbar=toolbar,
            submenu=submenu)
        doc = etree.XML(res['arch'])
        property_field = self._context.get('property_field')
        domain = self._context.get('property_domain')
        record = self._get_record()
        print 'record', record
        if record:
            field = self._get_record()._fields.get(property_field)
            # si no viene definido un property_domain buscamos uno para
            # definido ene l campo de la property
            if not domain:
                try:
                    domain = literal_eval(field.domain)
                except:
                    domain = []
            domain_elements = [str(x) for x in domain]

            # add company domain if comodel has company
            comodel = self._get_property_comodel()
            if comodel:
                if self.env[comodel]._fields.get('company_id'):
                    domain_elements += [
                        "'|'",
                        "('company_id', '=', False)",
                        "('company_id', '=', company_id)"]
            str_domain = '[%s]' % ','.join(domain_elements)

            company_property_field = self._get_company_property_field()
            xpath = "//field[@name='%s']" % company_property_field
            for node in doc.xpath(xpath):
                node.set('domain', str(str_domain))
                node.set('invisible', '0')
                # modifiers make still invisible = 1
                setup_modifiers(node, res['fields'][company_property_field])
        res['arch'] = etree.tostring(doc)
        return res

    @api.model
    def _get_company_property_field(self):
        comodel = self._get_property_comodel()
        if comodel == 'account.account':
            company_property_field = 'property_account_id'
        elif comodel == 'account.fiscal.position':
            company_property_field = 'property_position_id'
        elif comodel == 'account.payment.term':
            company_property_field = 'property_term_id'
        elif comodel == 'product.pricelist':
            company_property_field = 'property_pricelist_id'
        else:
            raise Warning(
                _('Property for model %s not implemented yet' % comodel))
        return company_property_field

    @api.one
    def _get_display_name(self):
        """
        No llamamos a super porque tendriamos que igualmente hacer un read
        para obtener la compania y no queremos disminuir la performance
        """
        company_field = getattr(
            self.with_context(no_company_sufix=True),
            self._get_company_property_field())
        display_name = '%s%s' % (
            company_field.display_name or _('None'),
            self.company_id.get_company_sufix())
        self.display_name = display_name

    @api.one
    def _get_property_field(self):
        self.property_field = self._context.get('property_field')

    @api.multi
    def _get_property_value(self):
        self.ensure_one()
        property_field = self.property_field
        record = self._get_record()
        if not record or not property_field:
            return False
        return getattr(
            record,
            property_field)

    @api.one
    def _get_property_account(self):
        if self._get_property_comodel() == 'account.account':
            self.property_account_id = self._get_property_value()

    @api.one
    def _get_property_position(self):
        if self._get_property_comodel() == 'account.fiscal.position':
            self.property_position_id = self._get_property_value()

    @api.one
    def _get_property_term(self):
        if self._get_property_comodel() == 'account.payment.term':
            self.property_term_id = self._get_property_value()

    @api.one
    def _get_property_pricelist(self):
        if self._get_property_comodel() == 'product.pricelist':
            self.property_pricelist_id = self._get_property_value()

    @api.one
    def _set_property_value(self, value):
        record = self._get_record()
        property_field = self.property_field
        if not record or not property_field:
            return True
        setattr(
            record,
            property_field,
            value)

    @api.one
    def _set_property_account(self):
        self._set_property_value(self.property_account_id.id)

    @api.one
    def _set_property_position(self):
        self._set_property_value(self.property_position_id.id)

    @api.one
    def _set_property_term(self):
        self._set_property_value(self.property_term_id.id)

    @api.one
    def _set_property_pricelist(self):
        self._set_property_value(self.property_pricelist_id.id)
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-

# Copyright © 2012-2018 Roberto Alsina and others.

# Permission is hereby granted, free of charge, to any
# person obtaining a copy of this software and associated
# documentation files (the "Software"), to deal in the
# Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the
# Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice
# shall be included in all copies or substantial portions of
# the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
# PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
# OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""Chart directive for reSTructuredText."""

from ast import literal_eval

try:
    import pygal
except ImportError:
    pygal = None  # NOQA

from nikola.plugin_categories import ShortcodePlugin
from nikola.utils import req_missing

_site = None

class Plugin(ShortcodePlugin):
    """Plugin for chart shortcode."""

    name = "chart"

    def handler(self, chart_type, **_options):
        if pygal is None:
            msg = req_missing(
                ['pygal'], 'use the Chart directive', optional=True)
            return '
{0}
'.format(msg)
        options = {}
        data = _options.pop('data')
        _options.pop('post', None)
        _options.pop('site')
        if 'style' in _options:
            style_name = _options.pop('style')
        else:
            style_name = 'BlueStyle'
        if '(' in style_name:  # Parametric style
            style = eval('pygal.style.' + style_name)
        else:
            style = getattr(pygal.style, style_name)
        for k, v in _options.items():
            try:
                options[k] = literal_eval(v)
            except Exception:
                options[k] = v
        chart = pygal
        for o in chart_type.split('.'):
            chart = getattr(chart, o)
        chart = chart(style=style)
        if _site and _site.invariant:
            chart.no_prefix = True
        chart.config(**options)
        for line in data.splitlines():
            line = line.strip()
            if line:
                label, series = literal_eval('({0})'.format(line))
                chart.add(label, series)
        return chart.render().decode('utf8')
<commit_msg>added missing docstring<commit_after># -*- coding: utf-8 -*-

# Copyright © 2012-2018 Roberto Alsina and others.

# Permission is hereby granted, free of charge, to any
# person obtaining a copy of this software and associated
# documentation files (the "Software"), to deal in the
# Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the
# Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice
# shall be included in all copies or substantial portions of
# the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
# PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
# OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""Chart directive for reSTructuredText."""

from ast import literal_eval

try:
    import pygal
except ImportError:
    pygal = None  # NOQA

from nikola.plugin_categories import ShortcodePlugin
from nikola.utils import req_missing

_site = None

class Plugin(ShortcodePlugin):
    """Plugin for chart shortcode."""

    name = "chart"

    def handler(self, chart_type, **_options):
        """Generate chart using Pygal."""
        if pygal is None:
            msg = req_missing(
                ['pygal'], 'use the Chart directive', optional=True)
            return '
{0}
'.format(msg)
        options = {}
        data = _options.pop('data')
        _options.pop('post', None)
        _options.pop('site')
        if 'style' in _options:
            style_name = _options.pop('style')
        else:
            style_name = 'BlueStyle'
        if '(' in style_name:  # Parametric style
            style = eval('pygal.style.' + style_name)
        else:
            style = getattr(pygal.style, style_name)
        for k, v in _options.items():
            try:
                options[k] = literal_eval(v)
            except Exception:
                options[k] = v
        chart = pygal
        for o in chart_type.split('.'):
            chart = getattr(chart, o)
        chart = chart(style=style)
        if _site and _site.invariant:
            chart.no_prefix = True
        chart.config(**options)
        for line in data.splitlines():
            line = line.strip()
            if line:
                label, series = literal_eval('({0})'.format(line))
                chart.add(label, series)
        return chart.render().decode('utf8')
<|endoftext|>


<commit_before>from django.core.management import color
from django.db import connection, models

from common import BaseEvolutionOperations

TEMP_TABLE_NAME = 'TEMP_TABLE'

class EvolutionOperations(BaseEvolutionOperations):
    def delete_column(self, model, f):
        qn = connection.ops.quote_name
        output = []

        field_list = [field for field in model._meta.local_fields
                        if f.name != field.name # Remove the field to be deleted
                        and field.db_type() is not None] # and any Generic fields
        table_name = model._meta.db_table

        output.extend(self.create_temp_table(field_list))
        output.extend(self.copy_to_temp_table(table_name, field_list))
        output.extend(self.delete_table(table_name))
        output.extend(self.create_table(table_name, field_list))
        output.extend(self.copy_from_temp_table(table_name, field_list))
        output.extend(self.delete_table(TEMP_TABLE_NAME))

        return output

    def create_mock_model(self, model, fields):
        field_sig_dict = {}
        for f in fields:
            field_sig_dict[f.name] = create_field_sig(field)

        proj_sig = create_project_sig()
        model_sig = create_model_sig(model)
        model_sig['fields'] = field_sig_dict
        mock_model = MockModel(proj_sig, model.app_name, model.model_name, model_sig, stub=False)

    def copy_to_temp_table(self, source_table_name, field_list):
        qn = connection.ops.quote_name
        output = [self.create_temp_table(field_list)]
        columns = []
        for field in field_list:
            if not models.ManyToManyField == field.__class__:
                columns.append(qn(field.column))
        column_names = ', '.join(columns)
        return ['INSERT INTO %s SELECT %s FROM %s;' % (qn(TEMP_TABLE_NAME), column_names, qn(source_table_name))]

    def copy_from_temp_table(self, dest_table_name, field_list):
        qn = connection.ops.quote_name
        columns = []
        for field in field_list:
            if not models.ManyToManyField == field.__class__:
                columns.append(qn(field.column))
        column_names = ', '.join(columns)
        params = {
            'dest_table_name': qn(dest_table_name),
            'temp_table': qn(TEMP_TABLE_NAME),
            'column_names': column_names,
        }

        return ['INSERT INTO %(dest_table_name)s (%(column_names)s) SELECT %(column_names)s FROM %(temp_table)s;' % params]

    def insert_to_temp_table(self, field, initial):
        qn = connection.ops.quote_name

        # At this point, initial can only be None if null=True, otherwise it is
        # a user callable or the default AddFieldInitialCallback which will shortly raise an exception.
        if initial is None:
            return []

        params = {
            'table_name': qn(TEMP_TABLE_NAME),
            'column_name': qn(field.column),
        }

        if callable(initial):
            params['value'] = initial()
            return ["UPDATE %(table_name)s SET %(column_name)s = %(value)s;" % params]
        else:
            return [("UPDATE %(table_name)s SET %(column_name)s = %%s;" % params, (initial,))]

    def create_temp_table(self, field_list):
        return self.create_table(TEMP_TABLE_NAME, field_list, True, False)

    def create_indexes_for_table(self, table_name, field_list):
        class FakeMeta(object):
            def __init__(self, table_name, field_list):
                self.db_table = table_name
                self.local_fields = field_list
                self.fields = field_list # Required for Pre QS-RF support
                self.db_tablespace = None
                self.managed = True

        class FakeModel(object):
            def __init__(self, table_name, field_list):
                self._meta = FakeMeta(table_name, field_list)

        style = color.no_style()
        return connection.creation.sql_indexes_for_model(FakeModel(table_name, field_list), style)

    def create_table(self, table_name, field_list, temporary=False, create_index=True):
        qn = connection.ops.quote_name
        output = []

        create = ['CREATE']
        if temporary:
            create.append('TEMPORARY')
        create.append('TABLE %s' % qn(table_name))
        output = [' '.join(create)]
        output.append('(')
        columns = []
        for field in field_list:
            if not models.ManyToManyField == field.__class__:
                column_name = qn(field.column)
                column_type = field.db_type()
                params = [column_name, column_type]
                if field.null:
                    params.append('NULL')
                else:
                    params.append('NOT NULL')
                if field.unique:
                    params.append('UNIQUE')
                if field.primary_key:
                    params.append('PRIMARY KEY')
                columns.append(' '.join(params))

        output.append(', '.join(columns))
        output.append(');')
        output = [''.join(output)]

        if create_index:
            output.extend(self.create_indexes_for_table(table_name, field_list))

        return output

    def rename_column(self, opts, old_field, new_field):
        if old_field.column == new_field.column:
            # No Operation
            return []

        original_fields = opts.local_fields
        new_fields = []
        for f in original_fields:
            if f.db_type() is not None: # Ignore Generic Fields
                if f.name == old_field.name:
                    new_fields.append(new_field)
                else:
                    new_fields.append(f)

        table_name = opts.db_table
        output = []
        output.extend(self.create_temp_table(new_fields))
        output.extend(self.copy_to_temp_table(table_name, original_fields))
        output.extend(self.delete_table(table_name))
        output.extend(self.create_table(table_name, new_fields))
        output.extend(self.copy_from_temp_table(table_name, new_fields))
        output.extend(self.delete_table(TEMP_TABLE_NAME))

        return output

    def add_column(self, model, f, initial):
        output = []
        table_name = model._meta.db_table
        original_fields = [field for field in model._meta.local_fields if field.db_type() is not None]
        new_fields = original_fields
        new_fields.append(f)

        output.extend(self.create_temp_table(new_fields))
        output.extend(self.copy_to_temp_table(table_name, original_fields))
        output.extend(self.insert_to_temp_table(f, initial))
        output.extend(self.delete_table(table_name))
        output.extend(self.create_table(table_name, new_fields, create_index=False))
        output.extend(self.copy_from_temp_table(table_name, new_fields))
        output.extend(self.delete_table(TEMP_TABLE_NAME))
        return output

    def change_null(self, model, field_name, new_null_attr, initial=None):
        return self.change_attribute(model, field_name, 'null', new_null_attr, initial)

    def change_max_length(self, model, field_name, new_max_length, initial=None):
        return self.change_attribute(model, field_name, 'max_length', new_max_length, initial)

    def change_unique(self, model, field_name, new_unique_value, initial=None):
        return self.change_attribute(model, field_name, '_unique', new_unique_value, initial)

    def change_attribute(self, model, field_name, attr_name, new_attr_value, initial=None):
        output = []
        opts = model._meta
        table_name = opts.db_table
        setattr(opts.get_field(field_name), attr_name, new_attr_value)
        fields = [f for f in opts.local_fields if f.db_type() is not None]

        output.extend(self.create_temp_table(fields))
        output.extend(self.copy_to_temp_table(table_name, fields))
        output.extend(self.insert_to_temp_table(opts.get_field(field_name), initial))
        output.extend(self.delete_table(table_name))
        output.extend(self.create_table(table_name, fields, create_index=False))
        output.extend(self.copy_from_temp_table(table_name, fields))
        output.extend(self.delete_table(TEMP_TABLE_NAME))
        return output
<commit_msg>Added fix for v1.1 support under SQLite3.<commit_after>from django.core.management import color
from django.db import connection, models

from common import BaseEvolutionOperations

TEMP_TABLE_NAME = 'TEMP_TABLE'

class EvolutionOperations(BaseEvolutionOperations):
    def delete_column(self, model, f):
        qn = connection.ops.quote_name
        output = []

        field_list = [field for field in model._meta.local_fields
                        if f.name != field.name # Remove the field to be deleted
                        and field.db_type() is not None] # and any Generic fields
        table_name = model._meta.db_table

        output.extend(self.create_temp_table(field_list))
        output.extend(self.copy_to_temp_table(table_name, field_list))
        output.extend(self.delete_table(table_name))
        output.extend(self.create_table(table_name, field_list))
        output.extend(self.copy_from_temp_table(table_name, field_list))
        output.extend(self.delete_table(TEMP_TABLE_NAME))

        return output

    def create_mock_model(self, model, fields):
        field_sig_dict = {}
        for f in fields:
            field_sig_dict[f.name] = create_field_sig(field)

        proj_sig = create_project_sig()
        model_sig = create_model_sig(model)
        model_sig['fields'] = field_sig_dict
        mock_model = MockModel(proj_sig, model.app_name, model.model_name, model_sig, stub=False)

    def copy_to_temp_table(self, source_table_name, field_list):
        qn = connection.ops.quote_name
        output = [self.create_temp_table(field_list)]
        columns = []
        for field in field_list:
            if not models.ManyToManyField == field.__class__:
                columns.append(qn(field.column))
        column_names = ', '.join(columns)
        return ['INSERT INTO %s SELECT %s FROM %s;' % (qn(TEMP_TABLE_NAME), column_names, qn(source_table_name))]

    def copy_from_temp_table(self, dest_table_name, field_list):
        qn = connection.ops.quote_name
        columns = []
        for field in field_list:
            if not models.ManyToManyField == field.__class__:
                columns.append(qn(field.column))
        column_names = ', '.join(columns)
        params = {
            'dest_table_name': qn(dest_table_name),
            'temp_table': qn(TEMP_TABLE_NAME),
            'column_names': column_names,
        }

        return ['INSERT INTO %(dest_table_name)s (%(column_names)s) SELECT %(column_names)s FROM %(temp_table)s;' % params]

    def insert_to_temp_table(self, field, initial):
        qn = connection.ops.quote_name

        # At this point, initial can only be None if null=True, otherwise it is
        # a user callable or the default AddFieldInitialCallback which will shortly raise an exception.
        if initial is None:
            return []

        params = {
            'table_name': qn(TEMP_TABLE_NAME),
            'column_name': qn(field.column),
        }

        if callable(initial):
            params['value'] = initial()
            return ["UPDATE %(table_name)s SET %(column_name)s = %(value)s;" % params]
        else:
            return [("UPDATE %(table_name)s SET %(column_name)s = %%s;" % params, (initial,))]

    def create_temp_table(self, field_list):
        return self.create_table(TEMP_TABLE_NAME, field_list, True, False)

    def create_indexes_for_table(self, table_name, field_list):
        class FakeMeta(object):
            def __init__(self, table_name, field_list):
                self.db_table = table_name
                self.local_fields = field_list
                self.fields = field_list # Required for Pre QS-RF support
                self.db_tablespace = None
                self.managed = True
                self.proxy = False

        class FakeModel(object):
            def __init__(self, table_name, field_list):
                self._meta = FakeMeta(table_name, field_list)

        style = color.no_style()
        return connection.creation.sql_indexes_for_model(FakeModel(table_name, field_list), style)

    def create_table(self, table_name, field_list, temporary=False, create_index=True):
        qn = connection.ops.quote_name
        output = []

        create = ['CREATE']
        if temporary:
            create.append('TEMPORARY')
        create.append('TABLE %s' % qn(table_name))
        output = [' '.join(create)]
        output.append('(')
        columns = []
        for field in field_list:
            if not models.ManyToManyField == field.__class__:
                column_name = qn(field.column)
                column_type = field.db_type()
                params = [column_name, column_type]
                if field.null:
                    params.append('NULL')
                else:
                    params.append('NOT NULL')
                if field.unique:
                    params.append('UNIQUE')
                if field.primary_key:
                    params.append('PRIMARY KEY')
                columns.append(' '.join(params))

        output.append(', '.join(columns))
        output.append(');')
        output = [''.join(output)]

        if create_index:
            output.extend(self.create_indexes_for_table(table_name, field_list))

        return output

    def rename_column(self, opts, old_field, new_field):
        if old_field.column == new_field.column:
            # No Operation
            return []

        original_fields = opts.local_fields
        new_fields = []
        for f in original_fields:
            if f.db_type() is not None: # Ignore Generic Fields
                if f.name == old_field.name:
                    new_fields.append(new_field)
                else:
                    new_fields.append(f)

        table_name = opts.db_table
        output = []
        output.extend(self.create_temp_table(new_fields))
        output.extend(self.copy_to_temp_table(table_name, original_fields))
        output.extend(self.delete_table(table_name))
        output.extend(self.create_table(table_name, new_fields))
        output.extend(self.copy_from_temp_table(table_name, new_fields))
        output.extend(self.delete_table(TEMP_TABLE_NAME))

        return output

    def add_column(self, model, f, initial):
        output = []
        table_name = model._meta.db_table
        original_fields = [field for field in model._meta.local_fields if field.db_type() is not None]
        new_fields = original_fields
        new_fields.append(f)

        output.extend(self.create_temp_table(new_fields))
        output.extend(self.copy_to_temp_table(table_name, original_fields))
        output.extend(self.insert_to_temp_table(f, initial))
        output.extend(self.delete_table(table_name))
        output.extend(self.create_table(table_name, new_fields, create_index=False))
        output.extend(self.copy_from_temp_table(table_name, new_fields))
        output.extend(self.delete_table(TEMP_TABLE_NAME))
        return output

    def change_null(self, model, field_name, new_null_attr, initial=None):
        return self.change_attribute(model, field_name, 'null', new_null_attr, initial)

    def change_max_length(self, model, field_name, new_max_length, initial=None):
        return self.change_attribute(model, field_name, 'max_length', new_max_length, initial)

    def change_unique(self, model, field_name, new_unique_value, initial=None):
        return self.change_attribute(model, field_name, '_unique', new_unique_value, initial)

    def change_attribute(self, model, field_name, attr_name, new_attr_value, initial=None):
        output = []
        opts = model._meta
        table_name = opts.db_table
        setattr(opts.get_field(field_name), attr_name, new_attr_value)
        fields = [f for f in opts.local_fields if f.db_type() is not None]

        output.extend(self.create_temp_table(fields))
        output.extend(self.copy_to_temp_table(table_name, fields))
        output.extend(self.insert_to_temp_table(opts.get_field(field_name), initial))
        output.extend(self.delete_table(table_name))
        output.extend(self.create_table(table_name, fields, create_index=False))
        output.extend(self.copy_from_temp_table(table_name, fields))
        output.extend(self.delete_table(TEMP_TABLE_NAME))
        return output
<|endoftext|>


<commit_before># emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Nibabel-based interfaces."""
from pathlib import Path
import numpy as np
import nibabel as nb
from nipype import logging
from nipype.utils.filemanip import fname_presuffix
from nipype.interfaces.base import (
    traits,
    TraitedSpec,
    BaseInterfaceInputSpec,
    File,
    SimpleInterface,
    OutputMultiObject,
    InputMultiObject,
)

IFLOGGER = logging.getLogger("nipype.interface")

class _ApplyMaskInputSpec(BaseInterfaceInputSpec):
    in_file = File(exists=True, mandatory=True, desc="an image")
    in_mask = File(exists=True, mandatory=True, desc="a mask")
    threshold = traits.Float(
        0.5, usedefault=True, desc="a threshold to the mask, if it is nonbinary"
    )

class _ApplyMaskOutputSpec(TraitedSpec):
    out_file = File(exists=True, desc="masked file")

class ApplyMask(SimpleInterface):
    """Mask the input given a mask."""

    input_spec = _ApplyMaskInputSpec
    output_spec = _ApplyMaskOutputSpec

    def _run_interface(self, runtime):
        img = nb.load(self.inputs.in_file)
        msknii = nb.load(self.inputs.in_mask)
        msk = msknii.get_fdata() > self.inputs.threshold

        self._results["out_file"] = fname_presuffix(
            self.inputs.in_file, suffix="_masked", newpath=runtime.cwd
        )

        if img.dataobj.shape[:3] != msk.shape:
            raise ValueError("Image and mask sizes do not match.")

        if not np.allclose(img.affine, msknii.affine):
            raise ValueError("Image and mask affines are not similar enough.")

        if img.dataobj.ndim == msk.ndim + 1:
            msk = msk[..., np.newaxis]

        masked = img.__class__(img.dataobj * msk, None, img.header)
        masked.to_filename(self._results["out_file"])
        return runtime

class _BinarizeInputSpec(BaseInterfaceInputSpec):
    in_file = File(exists=True, mandatory=True, desc="input image")
    thresh_low = traits.Float(mandatory=True, desc="non-inclusive lower threshold")

class _BinarizeOutputSpec(TraitedSpec):
    out_file = File(exists=True, desc="masked file")
    out_mask = File(exists=True, desc="output mask")

class Binarize(SimpleInterface):
    """Binarizes the input image applying the given thresholds."""

    input_spec = _BinarizeInputSpec
    output_spec = _BinarizeOutputSpec

    def _run_interface(self, runtime):
        img = nb.load(self.inputs.in_file)

        self._results["out_file"] = fname_presuffix(
            self.inputs.in_file, suffix="_masked", newpath=runtime.cwd
        )
        self._results["out_mask"] = fname_presuffix(
            self.inputs.in_file, suffix="_mask", newpath=runtime.cwd
        )

        data = img.get_fdata()
        mask = data > self.inputs.thresh_low
        data[~mask] = 0.0
        masked = img.__class__(data, img.affine, img.header)
        masked.to_filename(self._results["out_file"])

        img.header.set_data_dtype("uint8")
        maskimg = img.__class__(mask.astype("uint8"), img.affine, img.header)
        maskimg.to_filename(self._results["out_mask"])

        return runtime

class _SplitSeriesInputSpec(BaseInterfaceInputSpec):
    in_file = File(exists=True, mandatory=True, desc="input 4d image")

class _SplitSeriesOutputSpec(TraitedSpec):
    out_files = OutputMultiObject(File(exists=True), desc="output list of 3d images")

class SplitSeries(SimpleInterface):
    """Split a 4D dataset along the last dimension into a series of 3D volumes."""

    input_spec = _SplitSeriesInputSpec
    output_spec = _SplitSeriesOutputSpec

    def _run_interface(self, runtime):
        in_file = self.inputs.in_file
        img = nb.load(in_file)
        extra_dims = tuple(dim for dim in img.shape[3:] if dim > 1) or (1,)
        if len(extra_dims) != 1:
            raise ValueError(f"Invalid shape {'x'.join(str(s) for s in img.shape)}")
        img = img.__class__(img.dataobj.reshape(img.shape[:3] + extra_dims),
                            img.affine, img.header)

        self._results["out_files"] = []
        for i, img_3d in enumerate(nb.four_to_three(img)):
            out_file = str(
                Path(fname_presuffix(in_file, suffix=f"_idx-{i:03}",
                                     newpath=runtime.cwd)).absolute()
            )
            img_3d.to_filename(out_file)
            self._results["out_files"].append(out_file)

        return runtime

class _MergeSeriesInputSpec(BaseInterfaceInputSpec):
    in_files = InputMultiObject(
        File(exists=True, mandatory=True, desc="input list of 3d images")
    )
    allow_4D = traits.Bool(
        True, usedefault=True, desc="whether 4D images are allowed to be concatenated"
    )

class _MergeSeriesOutputSpec(TraitedSpec):
    out_file = File(exists=True, desc="output 4d image")

class MergeSeries(SimpleInterface):
    """Merge a series of 3D volumes along the last dimension into a single 4D image."""

    input_spec = _MergeSeriesInputSpec
    output_spec = _MergeSeriesOutputSpec

    def _run_interface(self, runtime):
        nii_list = []
        for f in self.inputs.in_files:
            filenii = nb.squeeze_image(nb.load(f))
            ndim = filenii.dataobj.ndim
            if ndim == 3:
                nii_list.append(filenii)
                continue
            elif self.inputs.allow_4D and ndim == 4:
                nii_list += nb.four_to_three(filenii)
                continue
            else:
                raise ValueError(
                    "Input image has an incorrect number of dimensions" f" ({ndim})."
                )

        img_4d = nb.concat_images(nii_list)
        out_file = fname_presuffix(self.inputs.in_files[0], suffix="_merged",
                                   newpath=runtime.cwd)
        img_4d.to_filename(out_file)

        self._results["out_file"] = out_file
        return runtime
<commit_msg>enh: address review comment by @mgxd<commit_after># emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Nibabel-based interfaces."""
import numpy as np
import nibabel as nb
from nipype import logging
from nipype.utils.filemanip import fname_presuffix
from nipype.interfaces.base import (
    traits,
    TraitedSpec,
    BaseInterfaceInputSpec,
    File,
    SimpleInterface,
    OutputMultiObject,
    InputMultiObject,
)

IFLOGGER = logging.getLogger("nipype.interface")

class _ApplyMaskInputSpec(BaseInterfaceInputSpec):
    in_file = File(exists=True, mandatory=True, desc="an image")
    in_mask = File(exists=True, mandatory=True, desc="a mask")
    threshold = traits.Float(
        0.5, usedefault=True, desc="a threshold to the mask, if it is nonbinary"
    )

class _ApplyMaskOutputSpec(TraitedSpec):
    out_file = File(exists=True, desc="masked file")

class ApplyMask(SimpleInterface):
    """Mask the input given a mask."""

    input_spec = _ApplyMaskInputSpec
    output_spec = _ApplyMaskOutputSpec

    def _run_interface(self, runtime):
        img = nb.load(self.inputs.in_file)
        msknii = nb.load(self.inputs.in_mask)
        msk = msknii.get_fdata() > self.inputs.threshold

        self._results["out_file"] = fname_presuffix(
            self.inputs.in_file, suffix="_masked", newpath=runtime.cwd
        )

        if img.dataobj.shape[:3] != msk.shape:
            raise ValueError("Image and mask sizes do not match.")

        if not np.allclose(img.affine, msknii.affine):
            raise ValueError("Image and mask affines are not similar enough.")

        if img.dataobj.ndim == msk.ndim + 1:
            msk = msk[..., np.newaxis]

        masked = img.__class__(img.dataobj * msk, None, img.header)
        masked.to_filename(self._results["out_file"])
        return runtime

class _BinarizeInputSpec(BaseInterfaceInputSpec):
    in_file = File(exists=True, mandatory=True, desc="input image")
    thresh_low = traits.Float(mandatory=True, desc="non-inclusive lower threshold")

class _BinarizeOutputSpec(TraitedSpec):
    out_file = File(exists=True, desc="masked file")
    out_mask = File(exists=True, desc="output mask")

class Binarize(SimpleInterface):
    """Binarizes the input image applying the given thresholds."""

    input_spec = _BinarizeInputSpec
    output_spec = _BinarizeOutputSpec

    def _run_interface(self, runtime):
        img = nb.load(self.inputs.in_file)

        self._results["out_file"] = fname_presuffix(
            self.inputs.in_file, suffix="_masked", newpath=runtime.cwd
        )
        self._results["out_mask"] = fname_presuffix(
            self.inputs.in_file, suffix="_mask", newpath=runtime.cwd
        )

        data = img.get_fdata()
        mask = data > self.inputs.thresh_low
        data[~mask] = 0.0
        masked = img.__class__(data, img.affine, img.header)
        masked.to_filename(self._results["out_file"])

        img.header.set_data_dtype("uint8")
        maskimg = img.__class__(mask.astype("uint8"), img.affine, img.header)
        maskimg.to_filename(self._results["out_mask"])

        return runtime

class _SplitSeriesInputSpec(BaseInterfaceInputSpec):
    in_file = File(exists=True, mandatory=True, desc="input 4d image")

class _SplitSeriesOutputSpec(TraitedSpec):
    out_files = OutputMultiObject(File(exists=True), desc="output list of 3d images")

class SplitSeries(SimpleInterface):
    """Split a 4D dataset along the last dimension into a series of 3D volumes."""

    input_spec = _SplitSeriesInputSpec
    output_spec = _SplitSeriesOutputSpec

    def _run_interface(self, runtime):
        in_file = self.inputs.in_file
        img = nb.load(in_file)
        extra_dims = tuple(dim for dim in img.shape[3:] if dim > 1) or (1,)
        if len(extra_dims) != 1:
            raise ValueError(f"Invalid shape {'x'.join(str(s) for s in img.shape)}")
        img = img.__class__(img.dataobj.reshape(img.shape[:3] + extra_dims),
                            img.affine, img.header)

        self._results["out_files"] = []
        for i, img_3d in enumerate(nb.four_to_three(img)):
            out_file = fname_presuffix(in_file, suffix=f"_idx-{i:03}",
                                       newpath=runtime.cwd)
            img_3d.to_filename(out_file)
            self._results["out_files"].append(out_file)

        return runtime

class _MergeSeriesInputSpec(BaseInterfaceInputSpec):
    in_files = InputMultiObject(
        File(exists=True, mandatory=True, desc="input list of 3d images")
    )
    allow_4D = traits.Bool(
        True, usedefault=True, desc="whether 4D images are allowed to be concatenated"
    )

class _MergeSeriesOutputSpec(TraitedSpec):
    out_file = File(exists=True, desc="output 4d image")

class MergeSeries(SimpleInterface):
    """Merge a series of 3D volumes along the last dimension into a single 4D image."""

    input_spec = _MergeSeriesInputSpec
    output_spec = _MergeSeriesOutputSpec

    def _run_interface(self, runtime):
        nii_list = []
        for f in self.inputs.in_files:
            filenii = nb.squeeze_image(nb.load(f))
            ndim = filenii.dataobj.ndim
            if ndim == 3:
                nii_list.append(filenii)
                continue
            elif self.inputs.allow_4D and ndim == 4:
                nii_list += nb.four_to_three(filenii)
                continue
            else:
                raise ValueError(
                    "Input image has an incorrect number of dimensions" f" ({ndim})."
                )

        img_4d = nb.concat_images(nii_list)
        out_file = fname_presuffix(self.inputs.in_files[0], suffix="_merged",
                                   newpath=runtime.cwd)
        img_4d.to_filename(out_file)

        self._results["out_file"] = out_file
        return runtime
<|endoftext|>


<commit_before>"""
Django settings for django_get_started project.
"""

from os import path
PROJECT_ROOT = path.dirname(path.abspath(path.dirname(__file__)))

DEBUG = True
TEMPLATE_DEBUG = DEBUG

ALLOWED_HOSTS = (
    'localhost',
    'palliassist-dev-us.azurewebsites.net',
    '127.0.0.1',
)

ADMINS = (
    # ('Your Name', 'your_email@example.com'),
)

MANAGERS = ADMINS

AUTHENTICATION_BACKENDS = ('app.backends.SqlBackend',)

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': path.join(PROJECT_ROOT, 'db.sqlite3'),
        'USER': '',
        'PASSWORD': '',
        'HOST': '',
        'PORT': '',
    }
}

LOGIN_URL = '/login'
LOGIN_REDIRECT_URL = 'home'

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Chicago'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True

# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = ''

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = ''

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = path.join(PROJECT_ROOT, 'static').replace('\\', '/')

# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'

# Additional locations of static files
STATICFILES_DIRS = (
    # Put strings here, like "/home/html/static" or "C:/www/django/static".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    "/home/cwang/palliassist_web/palliassist_webportal/app/static",
)

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#    'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

# Make this unique, and don't share it with anybody.
SECRET_KEY = 'n(bd1f1c%e8=_xad02x5qtfn%wgwpi492e$8_erx+d)!tpeoim'

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
#     'django.template.loaders.eggs.Loader',
)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    # Uncomment the next line for simple clickjacking protection:
    # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'django_get_started.urls'

# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'django_get_started.wsgi.application'

TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [
        path.join(path.dirname(__file__), 'templates'),
    ],
    'APP_DIRS': True,
    'OPTIONS': {
        'context_processors': [
        'django.template.context_processors.debug',
        'django.template.context_processors.request',
        'django.contrib.auth.context_processors.auth',
        'django.contrib.messages.context_processors.messages',
        ],
    },
},
]

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app',
    # Uncomment the next line to enable the admin:
    # 'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
)

# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}

# Specify the default test runner.
TEST_RUNNER = 'django.test.runner.DiscoverRunner'

<commit_msg>changed staticfiles_dir away from local path<commit_after>"""
Django settings for django_get_started project.
"""

from os import path
PROJECT_ROOT = path.dirname(path.abspath(path.dirname(__file__)))

DEBUG = True
TEMPLATE_DEBUG = DEBUG

ALLOWED_HOSTS = (
    'localhost',
    'palliassist-dev-us.azurewebsites.net',
    '127.0.0.1',
)

ADMINS = (
    # ('Your Name', 'your_email@example.com'),
)

MANAGERS = ADMINS

AUTHENTICATION_BACKENDS = ('app.backends.SqlBackend',)

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': path.join(PROJECT_ROOT, 'db.sqlite3'),
        'USER': '',
        'PASSWORD': '',
        'HOST': '',
        'PORT': '',
    }
}

LOGIN_URL = '/login'
LOGIN_REDIRECT_URL = 'home'

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Chicago'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True

# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = ''

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = ''

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = path.join(PROJECT_ROOT, 'static').replace('\\', '/')

# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'

# Additional locations of static files
STATICFILES_DIRS = (
    # Put strings here, like "/home/html/static" or "C:/www/django/static".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    path.join(path.dirname(__file__), 'templates'),
)

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#    'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

# Make this unique, and don't share it with anybody.
SECRET_KEY = 'n(bd1f1c%e8=_xad02x5qtfn%wgwpi492e$8_erx+d)!tpeoim'

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
#     'django.template.loaders.eggs.Loader',
)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    # Uncomment the next line for simple clickjacking protection:
    # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'django_get_started.urls'

# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'django_get_started.wsgi.application'

TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [
        path.join(path.dirname(__file__), 'templates'),
    ],
    'APP_DIRS': True,
    'OPTIONS': {
        'context_processors': [
        'django.template.context_processors.debug',
        'django.template.context_processors.request',
        'django.contrib.auth.context_processors.auth',
        'django.contrib.messages.context_processors.messages',
        ],
    },
},
]

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app',
    # Uncomment the next line to enable the admin:
    # 'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
)

# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}

# Specify the default test runner.
TEST_RUNNER = 'django.test.runner.DiscoverRunner'

<|endoftext|>


<commit_before># emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Nibabel-based interfaces."""
from pathlib import Path
import numpy as np
import nibabel as nb
from nipype import logging
from nipype.utils.filemanip import fname_presuffix
from nipype.interfaces.base import (
    traits,
    TraitedSpec,
    BaseInterfaceInputSpec,
    File,
    SimpleInterface,
    OutputMultiObject,
    InputMultiObject,
)

IFLOGGER = logging.getLogger("nipype.interface")

class _ApplyMaskInputSpec(BaseInterfaceInputSpec):
    in_file = File(exists=True, mandatory=True, desc="an image")
    in_mask = File(exists=True, mandatory=True, desc="a mask")
    threshold = traits.Float(
        0.5, usedefault=True, desc="a threshold to the mask, if it is nonbinary"
    )

class _ApplyMaskOutputSpec(TraitedSpec):
    out_file = File(exists=True, desc="masked file")

class ApplyMask(SimpleInterface):
    """Mask the input given a mask."""

    input_spec = _ApplyMaskInputSpec
    output_spec = _ApplyMaskOutputSpec

    def _run_interface(self, runtime):
        img = nb.load(self.inputs.in_file)
        msknii = nb.load(self.inputs.in_mask)
        msk = msknii.get_fdata() > self.inputs.threshold

        self._results["out_file"] = fname_presuffix(
            self.inputs.in_file, suffix="_masked", newpath=runtime.cwd
        )

        if img.dataobj.shape[:3] != msk.shape:
            raise ValueError("Image and mask sizes do not match.")

        if not np.allclose(img.affine, msknii.affine):
            raise ValueError("Image and mask affines are not similar enough.")

        if img.dataobj.ndim == msk.ndim + 1:
            msk = msk[..., np.newaxis]

        masked = img.__class__(img.dataobj * msk, None, img.header)
        masked.to_filename(self._results["out_file"])
        return runtime

class _BinarizeInputSpec(BaseInterfaceInputSpec):
    in_file = File(exists=True, mandatory=True, desc="input image")
    thresh_low = traits.Float(mandatory=True, desc="non-inclusive lower threshold")

class _BinarizeOutputSpec(TraitedSpec):
    out_file = File(exists=True, desc="masked file")
    out_mask = File(exists=True, desc="output mask")

class Binarize(SimpleInterface):
    """Binarizes the input image applying the given thresholds."""

    input_spec = _BinarizeInputSpec
    output_spec = _BinarizeOutputSpec

    def _run_interface(self, runtime):
        img = nb.load(self.inputs.in_file)

        self._results["out_file"] = fname_presuffix(
            self.inputs.in_file, suffix="_masked", newpath=runtime.cwd
        )
        self._results["out_mask"] = fname_presuffix(
            self.inputs.in_file, suffix="_mask", newpath=runtime.cwd
        )

        data = img.get_fdata()
        mask = data > self.inputs.thresh_low
        data[~mask] = 0.0
        masked = img.__class__(data, img.affine, img.header)
        masked.to_filename(self._results["out_file"])

        img.header.set_data_dtype("uint8")
        maskimg = img.__class__(mask.astype("uint8"), img.affine, img.header)
        maskimg.to_filename(self._results["out_mask"])

        return runtime

class _SplitSeriesInputSpec(BaseInterfaceInputSpec):
    in_file = File(exists=True, mandatory=True, desc="input 4d image")

class _SplitSeriesOutputSpec(TraitedSpec):
    out_files = OutputMultiObject(File(exists=True), desc="output list of 3d images")

class SplitSeries(SimpleInterface):
    """Split a 4D dataset along the last dimension into a series of 3D volumes."""

    input_spec = _SplitSeriesInputSpec
    output_spec = _SplitSeriesOutputSpec

    def _run_interface(self, runtime):
        in_file = self.inputs.in_file
        img = nb.load(in_file)
        extra_dims = tuple(dim for dim in img.shape[3:] if dim > 1) or (1,)
        if len(extra_dims) != 1:
            raise ValueError(f"Invalid shape {'x'.join(str(s) for s in img.shape)}")
        img = img.__class__(img.dataobj.reshape(img.shape[:3] + extra_dims),
                            img.affine, img.header)

        self._results["out_files"] = []
        for i, img_3d in enumerate(nb.four_to_three(img)):
            out_file = str(
                Path(fname_presuffix(in_file, suffix=f"_idx-{i:03}")).absolute()
            )
            img_3d.to_filename(out_file)
            self._results["out_files"].append(out_file)

        return runtime

class _MergeSeriesInputSpec(BaseInterfaceInputSpec):
    in_files = InputMultiObject(
        File(exists=True, mandatory=True, desc="input list of 3d images")
    )
    allow_4D = traits.Bool(
        True, usedefault=True, desc="whether 4D images are allowed to be concatenated"
    )

class _MergeSeriesOutputSpec(TraitedSpec):
    out_file = File(exists=True, desc="output 4d image")

class MergeSeries(SimpleInterface):
    """Merge a series of 3D volumes along the last dimension into a single 4D image."""

    input_spec = _MergeSeriesInputSpec
    output_spec = _MergeSeriesOutputSpec

    def _run_interface(self, runtime):
        nii_list = []
        for f in self.inputs.in_files:
            filenii = nb.squeeze_image(nb.load(f))
            ndim = filenii.dataobj.ndim
            if ndim == 3:
                nii_list.append(filenii)
                continue
            elif self.inputs.allow_4D and ndim == 4:
                nii_list += nb.four_to_three(filenii)
                continue
            else:
                raise ValueError(
                    "Input image has an incorrect number of dimensions" f" ({ndim})."
                )

        img_4d = nb.concat_images(nii_list)
        out_file = fname_presuffix(self.inputs.in_files[0], suffix="_merged")
        img_4d.to_filename(out_file)

        self._results["out_file"] = out_file
        return runtime
<commit_msg>FIX: Merge/SplitSeries write to path of input image, instead of cwd<commit_after># emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Nibabel-based interfaces."""
from pathlib import Path
import numpy as np
import nibabel as nb
from nipype import logging
from nipype.utils.filemanip import fname_presuffix
from nipype.interfaces.base import (
    traits,
    TraitedSpec,
    BaseInterfaceInputSpec,
    File,
    SimpleInterface,
    OutputMultiObject,
    InputMultiObject,
)

IFLOGGER = logging.getLogger("nipype.interface")

class _ApplyMaskInputSpec(BaseInterfaceInputSpec):
    in_file = File(exists=True, mandatory=True, desc="an image")
    in_mask = File(exists=True, mandatory=True, desc="a mask")
    threshold = traits.Float(
        0.5, usedefault=True, desc="a threshold to the mask, if it is nonbinary"
    )

class _ApplyMaskOutputSpec(TraitedSpec):
    out_file = File(exists=True, desc="masked file")

class ApplyMask(SimpleInterface):
    """Mask the input given a mask."""

    input_spec = _ApplyMaskInputSpec
    output_spec = _ApplyMaskOutputSpec

    def _run_interface(self, runtime):
        img = nb.load(self.inputs.in_file)
        msknii = nb.load(self.inputs.in_mask)
        msk = msknii.get_fdata() > self.inputs.threshold

        self._results["out_file"] = fname_presuffix(
            self.inputs.in_file, suffix="_masked", newpath=runtime.cwd
        )

        if img.dataobj.shape[:3] != msk.shape:
            raise ValueError("Image and mask sizes do not match.")

        if not np.allclose(img.affine, msknii.affine):
            raise ValueError("Image and mask affines are not similar enough.")

        if img.dataobj.ndim == msk.ndim + 1:
            msk = msk[..., np.newaxis]

        masked = img.__class__(img.dataobj * msk, None, img.header)
        masked.to_filename(self._results["out_file"])
        return runtime

class _BinarizeInputSpec(BaseInterfaceInputSpec):
    in_file = File(exists=True, mandatory=True, desc="input image")
    thresh_low = traits.Float(mandatory=True, desc="non-inclusive lower threshold")

class _BinarizeOutputSpec(TraitedSpec):
    out_file = File(exists=True, desc="masked file")
    out_mask = File(exists=True, desc="output mask")

class Binarize(SimpleInterface):
    """Binarizes the input image applying the given thresholds."""

    input_spec = _BinarizeInputSpec
    output_spec = _BinarizeOutputSpec

    def _run_interface(self, runtime):
        img = nb.load(self.inputs.in_file)

        self._results["out_file"] = fname_presuffix(
            self.inputs.in_file, suffix="_masked", newpath=runtime.cwd
        )
        self._results["out_mask"] = fname_presuffix(
            self.inputs.in_file, suffix="_mask", newpath=runtime.cwd
        )

        data = img.get_fdata()
        mask = data > self.inputs.thresh_low
        data[~mask] = 0.0
        masked = img.__class__(data, img.affine, img.header)
        masked.to_filename(self._results["out_file"])

        img.header.set_data_dtype("uint8")
        maskimg = img.__class__(mask.astype("uint8"), img.affine, img.header)
        maskimg.to_filename(self._results["out_mask"])

        return runtime

class _SplitSeriesInputSpec(BaseInterfaceInputSpec):
    in_file = File(exists=True, mandatory=True, desc="input 4d image")

class _SplitSeriesOutputSpec(TraitedSpec):
    out_files = OutputMultiObject(File(exists=True), desc="output list of 3d images")

class SplitSeries(SimpleInterface):
    """Split a 4D dataset along the last dimension into a series of 3D volumes."""

    input_spec = _SplitSeriesInputSpec
    output_spec = _SplitSeriesOutputSpec

    def _run_interface(self, runtime):
        in_file = self.inputs.in_file
        img = nb.load(in_file)
        extra_dims = tuple(dim for dim in img.shape[3:] if dim > 1) or (1,)
        if len(extra_dims) != 1:
            raise ValueError(f"Invalid shape {'x'.join(str(s) for s in img.shape)}")
        img = img.__class__(img.dataobj.reshape(img.shape[:3] + extra_dims),
                            img.affine, img.header)

        self._results["out_files"] = []
        for i, img_3d in enumerate(nb.four_to_three(img)):
            out_file = str(
                Path(fname_presuffix(in_file, suffix=f"_idx-{i:03}",
                                     newpath=runtime.cwd)).absolute()
            )
            img_3d.to_filename(out_file)
            self._results["out_files"].append(out_file)

        return runtime

class _MergeSeriesInputSpec(BaseInterfaceInputSpec):
    in_files = InputMultiObject(
        File(exists=True, mandatory=True, desc="input list of 3d images")
    )
    allow_4D = traits.Bool(
        True, usedefault=True, desc="whether 4D images are allowed to be concatenated"
    )

class _MergeSeriesOutputSpec(TraitedSpec):
    out_file = File(exists=True, desc="output 4d image")

class MergeSeries(SimpleInterface):
    """Merge a series of 3D volumes along the last dimension into a single 4D image."""

    input_spec = _MergeSeriesInputSpec
    output_spec = _MergeSeriesOutputSpec

    def _run_interface(self, runtime):
        nii_list = []
        for f in self.inputs.in_files:
            filenii = nb.squeeze_image(nb.load(f))
            ndim = filenii.dataobj.ndim
            if ndim == 3:
                nii_list.append(filenii)
                continue
            elif self.inputs.allow_4D and ndim == 4:
                nii_list += nb.four_to_three(filenii)
                continue
            else:
                raise ValueError(
                    "Input image has an incorrect number of dimensions" f" ({ndim})."
                )

        img_4d = nb.concat_images(nii_list)
        out_file = fname_presuffix(self.inputs.in_files[0], suffix="_merged",
                                   newpath=runtime.cwd)
        img_4d.to_filename(out_file)

        self._results["out_file"] = out_file
        return runtime
<|endoftext|>


<commit_before>VERSION = '0.2.0'<commit_msg>bumped version<commit_after>VERSION = '0.2.1'<|endoftext|>


<commit_before>from django.db.models.expressions import Expression, F
from django.db.models import fields

class ResolvedOuterRef(F):
    """
    An object that contains a reference to an outer query.

    In this case, the reference to the outer query has been resolved because
    the inner query has been used as a subquery.
    """
    def as_sql(self, *args, **kwargs):
        raise ValueError(
            'This queryset contains a reference to an outer query and may '
            'only be used in a subquery.'
        )

    def _prepare(self, output_field=None):
        return self

class OuterRef(F):
    def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):
        if isinstance(self.name, self.__class__):
            return self.name
        return ResolvedOuterRef(self.name)

    def _prepare(self, output_field=None):
        return self

class Subquery(Expression):
    """
    An explicit subquery. It may contain OuterRef() references to the outer
    query which will be resolved when it is applied to that query.
    """
    template = '(%(subquery)s)'

    def __init__(self, queryset, output_field=None, **extra):
        self.queryset = queryset
        self.extra = extra
        if output_field is None and len(self.queryset.query.select) == 1:
            output_field = self.queryset.query.select[0].field
        super(Subquery, self).__init__(output_field)

    def copy(self):
        clone = super(Subquery, self).copy()
        clone.queryset = clone.queryset.all()
        return clone

    def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):
        clone = self.copy()
        clone.is_summary = summarize
        clone.queryset.query.bump_prefix(query)

        # Need to recursively resolve these.
        def resolve_all(child):
            if hasattr(child, 'children'):
                [resolve_all(_child) for _child in child.children]
            if hasattr(child, 'rhs'):
                child.rhs = resolve(child.rhs)

        def resolve(child):
            if hasattr(child, 'resolve_expression'):
                resolved = child.resolve_expression(
                    query=query, allow_joins=allow_joins, reuse=reuse,
                    summarize=summarize, for_save=for_save,
                )
                if hasattr(resolved, 'alias') and resolved.alias != resolved.target.model._meta.db_table:
                    clone.queryset.query.external_aliases.add(resolved.alias)
                return resolved
            return child

        resolve_all(clone.queryset.query.where)

        for key, value in clone.queryset.query.annotations.items():
            if isinstance(value, Subquery):
                clone.queryset.query.annotations[key] = resolve(value)

        return clone

    def get_source_expressions(self):
        return [
            x for x in [
                getattr(expr, 'lhs', None)
                for expr in self.queryset.query.where.children
            ] if x
        ]

    def relabeled_clone(self, change_map):
        clone = self.copy()
        clone.queryset.query = clone.queryset.query.relabeled_clone(change_map)
        clone.queryset.query.external_aliases.update(
            alias for alias in change_map.values()
            if alias not in clone.queryset.query.tables
        )
        return clone

    def as_sql(self, compiler, connection, template=None, **extra_context):
        connection.ops.check_expression_support(self)
        template_params = self.extra.copy()
        template_params.update(extra_context)
        template_params['subquery'], sql_params = self.queryset.query.get_compiler(connection=connection).as_sql()

        template = template or template_params.get('template', self.template)
        sql = template % template_params
        sql = connection.ops.unification_cast_sql(self.output_field) % sql
        return sql, sql_params

    def _prepare(self, output_field=None):
        # This method will only be called if this instance is the "rhs" in an
        # expression: the wrapping () must be removed (as the expression that
        # contains this will provide them). SQLite evaluates ((subquery))
        # differently than the other databases.
        if self.template == '(%(subquery)s)':
            clone = self.copy()
            clone.template = '%(subquery)s'
            return clone
        return self

class Exists(Subquery):
    template = 'EXISTS(%(subquery)s)'

    def __init__(self, *args, **kwargs):
        self.negated = kwargs.pop('negated', False)
        super(Exists, self).__init__(*args, **kwargs)

    def __invert__(self):
        return type(self)(self.queryset, self.output_field, negated=(not self.negated), **self.extra)

    @property
    def output_field(self):
        return fields.BooleanField()

    def resolve_expression(self, query=None, **kwargs):
        # As a performance optimization, remove ordering since EXISTS doesn't
        # care about it, just whether or not a row matches.
        self.queryset = self.queryset.order_by()
        return super(Exists, self).resolve_expression(query, **kwargs)

    def as_sql(self, compiler, connection, template=None, **extra_context):
        sql, params = super(Exists, self).as_sql(compiler, connection, template, **extra_context)
        if self.negated:
            sql = 'NOT {}'.format(sql)
        return sql, params

    def as_oracle(self, compiler, connection, template=None, **extra_context):
        # Oracle doesn't allow EXISTS() in the SELECT list, so we must wrap it
        # with a CASE WHEN expression. Since Django's When expression requires
        # a left hand side (column) to compare against, we must change the
        # template ourselves.
        sql, params = self.as_sql(compiler, connection, template, **extra_context)
        sql = 'CASE WHEN {} THEN 1 ELSE 0 END'.format(sql)
        return sql, params
<commit_msg>Backport https://code.djangoproject.com/ticket/28199.<commit_after>from django.db.models.expressions import Expression, F
from django.db.models import fields

class ResolvedOuterRef(F):
    """
    An object that contains a reference to an outer query.

    In this case, the reference to the outer query has been resolved because
    the inner query has been used as a subquery.
    """
    def as_sql(self, *args, **kwargs):
        raise ValueError(
            'This queryset contains a reference to an outer query and may '
            'only be used in a subquery.'
        )

    def _prepare(self, output_field=None):
        return self

class OuterRef(F):
    def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):
        if isinstance(self.name, self.__class__):
            return self.name
        return ResolvedOuterRef(self.name)

    def _prepare(self, output_field=None):
        return self

class Subquery(Expression):
    """
    An explicit subquery. It may contain OuterRef() references to the outer
    query which will be resolved when it is applied to that query.
    """
    template = '(%(subquery)s)'

    def __init__(self, queryset, output_field=None, **extra):
        self.queryset = queryset
        self.extra = extra
        if output_field is None and len(self.queryset.query.select) == 1:
            output_field = self.queryset.query.select[0].field
        super(Subquery, self).__init__(output_field)

    def copy(self):
        clone = super(Subquery, self).copy()
        clone.queryset = clone.queryset.all()
        return clone

    def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):
        clone = self.copy()
        clone.is_summary = summarize
        clone.queryset.query.bump_prefix(query)

        # Need to recursively resolve these.
        def resolve_all(child):
            if hasattr(child, 'children'):
                [resolve_all(_child) for _child in child.children]
            if hasattr(child, 'rhs'):
                child.rhs = resolve(child.rhs)

        def resolve(child):
            if hasattr(child, 'resolve_expression'):
                resolved = child.resolve_expression(
                    query=query, allow_joins=allow_joins, reuse=reuse,
                    summarize=summarize, for_save=for_save,
                )
                if hasattr(resolved, 'alias') and resolved.alias != resolved.target.model._meta.db_table:
                    clone.queryset.query.external_aliases.add(resolved.alias)
                return resolved
            return child

        resolve_all(clone.queryset.query.where)

        for key, value in clone.queryset.query.annotations.items():
            if isinstance(value, Subquery):
                clone.queryset.query.annotations[key] = resolve(value)

        return clone

    def get_source_expressions(self):
        return [
            x for x in [
                getattr(expr, 'lhs', None)
                for expr in self.queryset.query.where.children
            ] if x
        ]

    def relabeled_clone(self, change_map):
        clone = self.copy()
        clone.queryset.query = clone.queryset.query.relabeled_clone(change_map)
        clone.queryset.query.external_aliases.update(
            alias for alias in change_map.values()
            if alias not in clone.queryset.query.tables
        )
        return clone

    def as_sql(self, compiler, connection, template=None, **extra_context):
        connection.ops.check_expression_support(self)
        template_params = self.extra.copy()
        template_params.update(extra_context)
        template_params['subquery'], sql_params = self.queryset.query.get_compiler(connection=connection).as_sql()

        template = template or template_params.get('template', self.template)
        sql = template % template_params
        return sql, sql_params

    def _prepare(self, output_field=None):
        # This method will only be called if this instance is the "rhs" in an
        # expression: the wrapping () must be removed (as the expression that
        # contains this will provide them). SQLite evaluates ((subquery))
        # differently than the other databases.
        if self.template == '(%(subquery)s)':
            clone = self.copy()
            clone.template = '%(subquery)s'
            return clone
        return self

class Exists(Subquery):
    template = 'EXISTS(%(subquery)s)'

    def __init__(self, *args, **kwargs):
        self.negated = kwargs.pop('negated', False)
        super(Exists, self).__init__(*args, **kwargs)

    def __invert__(self):
        return type(self)(self.queryset, self.output_field, negated=(not self.negated), **self.extra)

    @property
    def output_field(self):
        return fields.BooleanField()

    def resolve_expression(self, query=None, **kwargs):
        # As a performance optimization, remove ordering since EXISTS doesn't
        # care about it, just whether or not a row matches.
        self.queryset = self.queryset.order_by()
        return super(Exists, self).resolve_expression(query, **kwargs)

    def as_sql(self, compiler, connection, template=None, **extra_context):
        sql, params = super(Exists, self).as_sql(compiler, connection, template, **extra_context)
        if self.negated:
            sql = 'NOT {}'.format(sql)
        return sql, params

    def as_oracle(self, compiler, connection, template=None, **extra_context):
        # Oracle doesn't allow EXISTS() in the SELECT list, so we must wrap it
        # with a CASE WHEN expression. Since Django's When expression requires
        # a left hand side (column) to compare against, we must change the
        # template ourselves.
        sql, params = self.as_sql(compiler, connection, template, **extra_context)
        sql = 'CASE WHEN {} THEN 1 ELSE 0 END'.format(sql)
        return sql, params
<|endoftext|>