<commit_before>from dynamic_stack_decider.abstract_decision_element import AbstractDecisionElement
from tf.transformations import euler_from_quaternion
import math

class AlignedToGoal(AbstractDecisionElement):
    def __init__(self, blackboard, dsd, parameters=None):
        super(AlignedToGoal, self).__init__(blackboard, dsd, parameters)
        self.orientation_threshold = self.blackboard.config['goal_alignment_orientation_threshold']  # [deg]

    def perform(self, reevaluate=False):
        """
        It is determined if the robot is correctly aligned to the orientation of the move_base goal within a
        determined threshold by comparing the current orientation angle of the robot in the map with the one from the
        move_base goal.
        """
        current_pose = self.blackboard.pathfinding.get_current_pose()
        if current_pose is None:
            # When move_base did not received a goal yet, no current position on the map is known.
            # In this case it is not know if the robot is aligned correctly to, e.g., the goal and therefore the robot
            # should not be allowed to kick the ball.
            return 'NO'
        current_orientation = current_pose.pose.orientation
        current_orientation = euler_from_quaternion([current_orientation.x, current_orientation.y,
                                                     current_orientation.z, current_orientation.w])
        goal_orientation = current_pose.pose.orientation
        goal_orientation = euler_from_quaternion([goal_orientation.x, goal_orientation.y, goal_orientation.z,
                                                  goal_orientation.w])
        if math.degrees(abs(current_orientation[2] - goal_orientation[2])) < self.orientation_threshold:
            return 'YES'
        else:
            return 'NO'

    def get_reevaluate(self):
        return True
<commit_msg>fix error in AlignedToGoal<commit_after>from dynamic_stack_decider.abstract_decision_element import AbstractDecisionElement
from tf.transformations import euler_from_quaternion
import math

class AlignedToGoal(AbstractDecisionElement):
    def __init__(self, blackboard, dsd, parameters=None):
        super(AlignedToGoal, self).__init__(blackboard, dsd, parameters)
        self.orientation_threshold = self.blackboard.config['goal_alignment_orientation_threshold']  # [deg]

    def perform(self, reevaluate=False):
        """
        It is determined if the robot is correctly aligned to the orientation of the move_base goal within a
        determined threshold by comparing the current orientation angle of the robot in the map with the one from the
        move_base goal.
        """
        current_pose = self.blackboard.pathfinding.get_current_pose()
        current_goal = self.blackboard.pathfinding.get_goal()
        if current_pose is None or current_pose is None:
            # When move_base did not received a goal yet, no current position on the map is known.
            # In this case it is not know if the robot is aligned correctly to, e.g., the goal and therefore the robot
            # should not be allowed to kick the ball.
            return 'NO'
        current_orientation = current_pose.pose.orientation
        current_orientation = euler_from_quaternion([current_orientation.x, current_orientation.y,
                                                     current_orientation.z, current_orientation.w])
        goal_orientation = current_goal.pose.orientation
        goal_orientation = euler_from_quaternion([goal_orientation.x, goal_orientation.y, goal_orientation.z,
                                                  goal_orientation.w])
        if math.degrees(abs(current_orientation[2] - goal_orientation[2])) < self.orientation_threshold:
            return 'YES'
        else:
            return 'NO'

    def get_reevaluate(self):
        return True
<|endoftext|>


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

# OpenFisca -- A versatile microsimulation software
# By: OpenFisca Team <contact@openfisca.fr>
#
# Copyright (C) 2011, 2012, 2013, 2014 OpenFisca Team
# https://github.com/openfisca
#
# This file is part of OpenFisca.
#
# OpenFisca 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.
#
# OpenFisca 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 pandas import DataFrame
import matplotlib.pyplot as plt

import openfisca_france_indirect_taxation
from openfisca_survey_manager.survey_collections import SurveyCollection

from openfisca_france_data import default_config_files_directory as config_files_directory
from openfisca_france_indirect_taxation.surveys import SurveyScenario

def get_input_data_frame(year):
    openfisca_survey_collection = SurveyCollection.load(
        collection = "openfisca_indirect_taxation", config_files_directory = config_files_directory)
    openfisca_survey = openfisca_survey_collection.get_survey("openfisca_indirect_taxation_data_{}".format(year))
    input_data_frame = openfisca_survey.get_values(table = "input")
    input_data_frame.reset_index(inplace = True)
    return input_data_frame

def simulate_df(var_to_be_simulated, year = 2005):
    '''
    Construction de la DataFrame à partir de laquelle sera faite l'analyse des données
    '''
    input_data_frame = get_input_data_frame(year)
    TaxBenefitSystem = openfisca_france_indirect_taxation.init_country()

    tax_benefit_system = TaxBenefitSystem()
    survey_scenario = SurveyScenario().init_from_data_frame(
        input_data_frame = input_data_frame,
        tax_benefit_system = tax_benefit_system,
        year = year,
        )
    simulation = survey_scenario.new_simulation()
    return DataFrame(
        dict([
            (name, simulation.calculate(name)) for name in var_to_be_simulated

            ])
        )

def wavg(groupe, var):
    '''
    Fonction qui calcule la moyenne pondérée par groupe d'une variable
    '''
    d = groupe[var]
    w = groupe['pondmen']
    return (d * w).sum() / w.sum()

def collapse(dataframe, groupe, var):
    '''
    Pour une variable, fonction qui calcule la moyenne pondérée au sein de chaque groupe.
    '''
    grouped = dataframe.groupby([groupe])
    var_weighted_grouped = grouped.apply(lambda x: wavg(groupe = x, var = var))
    return var_weighted_grouped

def df_weighted_average_grouped(dataframe, groupe, varlist):
    '''
    Agrège les résultats de weighted_average_grouped() en une unique dataframe pour la liste de variable 'varlist'.
    '''
    return DataFrame(
        dict([
            (var, collapse(dataframe, groupe, var)) for var in varlist
            ])
        )

if __name__ == '__main__':
    import logging
    log = logging.getLogger(__name__)
    import sys
    logging.basicConfig(level = logging.INFO, stream = sys.stdout)

# Exemple: graphe par décile de revenu par uc de la ventilation de la consommation selon les postes agrégés de la CN
    # Lite des coicop agrégées en 12 postes
    list_coicop12 = []
    for coicop12_index in range(1, 13):
        list_coicop12.append('coicop12_{}'.format(coicop12_index))
    # Liste des variables que l'on veut simuler
    var_to_be_simulated = [
        'ident_men',
        'pondmen',
        'decuc',
        'age',
        'decile',
        'revtot',
        'consommation_totale',
        'ocde10',
        'niveau_de_vie',
        ]
    # Merge des deux listes
    var_to_be_simulated += list_coicop12

    # Constition d'une base de données agrégée par décile (= collapse en stata)
    df = simulate_df(var_to_be_simulated = var_to_be_simulated)
    var_to_concat = list_coicop12 + ['consommation_totale']
    Wconcat = df_weighted_average_grouped(dataframe = df, groupe = 'decile', varlist = var_to_concat)

    # Construction des parts
    list_part_coicop12 = []
    for i in range(1, 13):
        Wconcat['part_coicop12_{}'.format(i)] = Wconcat['coicop12_{}'.format(i)] / Wconcat['consommation_totale']
        'list_part_coicop12_{}'.format(i)
        list_part_coicop12.append('part_coicop12_{}'.format(i))

    df_to_graph = Wconcat[list_part_coicop12]

    df_to_graph.plot(kind = 'bar', stacked = True)
    plt.axhline(0, color = 'k')
    #TODO: analyser, changer les déciles de revenus en déciles de consommation
    # faire un truc plus joli, mettres labels...
<commit_msg>little modifications plot consumption<commit_after># -*- coding: utf-8 -*-

# OpenFisca -- A versatile microsimulation software
# By: OpenFisca Team <contact@openfisca.fr>
#
# Copyright (C) 2011, 2012, 2013, 2014 OpenFisca Team
# https://github.com/openfisca
#
# This file is part of OpenFisca.
#
# OpenFisca 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.
#
# OpenFisca 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 __future__ import division
from pandas import DataFrame
import matplotlib.pyplot as plt

import openfisca_france_indirect_taxation
from openfisca_survey_manager.survey_collections import SurveyCollection

from openfisca_france_data import default_config_files_directory as config_files_directory
from openfisca_france_indirect_taxation.surveys import SurveyScenario

def get_input_data_frame(year):
    openfisca_survey_collection = SurveyCollection.load(
        collection = "openfisca_indirect_taxation", config_files_directory = config_files_directory)
    openfisca_survey = openfisca_survey_collection.get_survey("openfisca_indirect_taxation_data_{}".format(year))
    input_data_frame = openfisca_survey.get_values(table = "input")
    input_data_frame.reset_index(inplace = True)
    return input_data_frame

def simulate_df(var_to_be_simulated, year = 2005):
    '''
    Construction de la DataFrame à partir de laquelle sera faite l'analyse des données
    '''
    input_data_frame = get_input_data_frame(year)
    TaxBenefitSystem = openfisca_france_indirect_taxation.init_country()

    tax_benefit_system = TaxBenefitSystem()
    survey_scenario = SurveyScenario().init_from_data_frame(
        input_data_frame = input_data_frame,
        tax_benefit_system = tax_benefit_system,
        year = year,
        )
    simulation = survey_scenario.new_simulation()
    return DataFrame(
        dict([
            (name, simulation.calculate(name)) for name in var_to_be_simulated

            ])
        )

def wavg(groupe, var):
    '''
    Fonction qui calcule la moyenne pondérée par groupe d'une variable
    '''
    d = groupe[var]
    w = groupe['pondmen']
    return (d * w).sum() / w.sum()

def collapse(dataframe, groupe, var):
    '''
    Pour une variable, fonction qui calcule la moyenne pondérée au sein de chaque groupe.
    '''
    grouped = dataframe.groupby([groupe])
    var_weighted_grouped = grouped.apply(lambda x: wavg(groupe = x, var = var))
    return var_weighted_grouped

    df_grouped = collapse(df, 'decile', ['montant_tva_taux_plein'])

def df_weighted_average_grouped(dataframe, groupe, varlist):
    '''
    Agrège les résultats de weighted_average_grouped() en une unique dataframe pour la liste de variable 'varlist'.
    '''
    return DataFrame(
        dict([
            (var, collapse(dataframe, groupe, var)) for var in varlist
            ])
        )

if __name__ == '__main__':
    import logging
    log = logging.getLogger(__name__)
    import sys
    logging.basicConfig(level = logging.INFO, stream = sys.stdout)

# Exemple: graphe par décile de revenu par uc de la ventilation de la consommation selon les postes agrégés de la CN
    # Lite des coicop agrégées en 12 postes
    list_coicop12 = []
    for coicop12_index in range(1, 13):
        list_coicop12.append('coicop12_{}'.format(coicop12_index))
    # Liste des variables que l'on veut simuler
    var_to_be_simulated = [
        'ident_men',
        'pondmen',
        'decuc',
        'age',
        'decile',
        'revtot',
        'consommation_totale',
        'ocde10',
        'niveau_de_vie',
        ]
    # Merge des deux listes
    var_to_be_simulated += list_coicop12

    # Constition d'une base de données agrégée par décile (= collapse en stata)
    df = simulate_df(var_to_be_simulated = var_to_be_simulated)
    var_to_concat = list_coicop12 + ['consommation_totale']
    Wconcat = df_weighted_average_grouped(dataframe = df, groupe = 'decile', varlist = var_to_concat)

    # Construction des parts
    list_part_coicop12 = []
    for i in range(1, 13):
        Wconcat['part_coicop12_{}'.format(i)] = Wconcat['coicop12_{}'.format(i)] / Wconcat['consommation_totale']
        'list_part_coicop12_{}'.format(i)
        list_part_coicop12.append('part_coicop12_{}'.format(i))

    df_to_graph = Wconcat[list_part_coicop12]

    df_to_graph.plot(kind = 'bar', stacked = True)
    plt.axhline(0, color = 'k')
    #TODO: analyser, changer les déciles de revenus en déciles de consommation
    # faire un truc plus joli, mettres labels...
<|endoftext|>


<commit_before>import numpy as np
import pandas as pd
from cardpay_reward_programs.config import default_payment_list
from cardpay_reward_programs.rule import Rule

class MinSpend(Rule):
    def __init__(self, core_parameters, user_defined_parameters):
        super(MinSpend, self).__init__(core_parameters, user_defined_parameters)

    def set_user_defined_parameters(
        self, min_spend, base_reward, token, subgraph_config_location, duration
    ):
        self.min_spend = min_spend
        self.base_reward = base_reward
        self.token = token
        self.subgraph_config_location = subgraph_config_location
        self.duration = duration

    def sql(self, table_query):
        return f"""
        select
        prepaid_card_owner as payee,
        sum(spend_amount_uint64) as total_spent

        from {table_query}
        where block_number_uint64 > ?::integer and block_number_uint64 <= ?::integer

        group by prepaid_card_owner
        having(total_spent) >= ?::integer
        """

    def df_to_payment_list(self, df, reward_program_id="0x"):
        if df.empty:
            return default_payment_list
        new_df = df.copy()
        new_df["rewardProgramID"] = reward_program_id
        new_df["validFrom"] = self.end_block
        new_df["validTo"] = self.end_block + self.duration
        new_df["token"] = self.token
        new_df["amount"] = np.where(new_df["total_spent"] > self.min_spend, self.base_reward, 0)
        new_df = new_df.drop(["total_spent"], axis=1)
        return new_df[new_df["amount"] > 0].reset_index()

    def run(self, start_block: int, end_block: int):
        vars = [start_block, end_block, self.min_spend]
        table_query = self._get_table_query("prepaid_card_payment", start_block, end_block)
        if table_query == "parquet_scan[]":
            return pd.DataFrame(columns=["payee", "total_spent"])
        else:
            return self.run_query(table_query, vars)

    def aggregate(self, cached_df=[]):
        if len(cached_df) == 0:
            return pd.DataFrame(columns=["payee", "total_spent"])
        else:
            return pd.concat(cached_df).groupby("payee").sum().reset_index()
<commit_msg>fix empty parquet file again<commit_after>import numpy as np
import pandas as pd
from cardpay_reward_programs.config import default_payment_list
from cardpay_reward_programs.rule import Rule

class MinSpend(Rule):
    def __init__(self, core_parameters, user_defined_parameters):
        super(MinSpend, self).__init__(core_parameters, user_defined_parameters)

    def set_user_defined_parameters(
        self, min_spend, base_reward, token, subgraph_config_location, duration
    ):
        self.min_spend = min_spend
        self.base_reward = base_reward
        self.token = token
        self.subgraph_config_location = subgraph_config_location
        self.duration = duration

    def sql(self, table_query):
        return f"""
        select
        prepaid_card_owner as payee,
        sum(spend_amount_uint64) as total_spent

        from {table_query}
        where block_number_uint64 > ?::integer and block_number_uint64 <= ?::integer

        group by prepaid_card_owner
        having(total_spent) >= ?::integer
        """

    def df_to_payment_list(self, df, reward_program_id="0x"):
        if df.empty:
            return default_payment_list.copy()
        new_df = df.copy()
        new_df["rewardProgramID"] = reward_program_id
        new_df["validFrom"] = self.end_block
        new_df["validTo"] = self.end_block + self.duration
        new_df["token"] = self.token
        new_df["amount"] = np.where(new_df["total_spent"] > self.min_spend, self.base_reward, 0)
        new_df = new_df.drop(["total_spent"], axis=1)
        return new_df[new_df["amount"] > 0].reset_index()

    def run(self, start_block: int, end_block: int):
        vars = [start_block, end_block, self.min_spend]
        table_query = self._get_table_query("prepaid_card_payment", start_block, end_block)
        if table_query == "parquet_scan([])":
            return pd.DataFrame(columns=["payee", "total_spent"])
        else:
            return self.run_query(table_query, vars)

    def aggregate(self, cached_df=[]):
        if len(cached_df) == 0:
            return pd.DataFrame(columns=["payee", "total_spent"])
        else:
            return pd.concat(cached_df).groupby("payee").sum().reset_index()
<|endoftext|>


<commit_before>from django.contrib.contenttypes.models import ContentType
from django.conf import settings
from django.core.urlresolvers import reverse
from django.core.exceptions import ValidationError
from django.utils.safestring import mark_safe
from django.utils import timezone
from django.db import models
from django.db.models import Avg, Min, Max, Count, Sum
from django.db.models.signals import post_save
from report_builder.unique_slugify import unique_slugify
from dateutil import parser

AUTH_USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User')

class Report(models.Model):
    """ A saved report with queryset and descriptive fields
    """
    def _get_allowed_models():
        models = ContentType.objects.all()
        if getattr(settings, 'REPORT_BUILDER_INCLUDE', False):
            models = models.filter(name__in=settings.REPORT_BUILDER_INCLUDE)
        if getattr(settings, 'REPORT_BUILDER_EXCLUDE', False):
            models = models.exclude(name__in=settings.REPORT_BUILDER_EXCLUDE)
        return models

    name = models.CharField(max_length=255)
    slug = models.SlugField(verbose_name="Short Name")
    description = models.TextField(blank=True)
    root_model = models.ForeignKey(ContentType, limit_choices_to={'pk__in':_get_allowed_models})
    created = models.DateField(auto_now_add=True)
    modified = models.DateField(auto_now=True)
    user_created = models.ForeignKey(AUTH_USER_MODEL, editable=False, blank=True, null=True)
    user_modified = models.ForeignKey(AUTH_USER_MODEL, editable=False, blank=True, null=True, related_name="report_modified_set")
    distinct = models.BooleanField()
    starred = models.ManyToManyField(AUTH_USER_MODEL, blank=True,
                                     help_text="These users have starred this report for easy reference.",
                                     related_name="report_starred_set")

    def save(self, *args, **kwargs):
        if not self.id:
            unique_slugify(self, self.name)
        super(Report, self).save(*args, **kwargs)

    def add_aggregates(self, queryset):
        for display_field in self.displayfield_set.filter(aggregate__isnull=False):
            if display_field.aggregate == "Avg":
                queryset = queryset.annotate(Avg(display_field.path + display_field.field))
            elif display_field.aggregate == "Max":
                queryset = queryset.annotate(Max(display_field.path + display_field.field))
            elif display_field.aggregate == "Min":
                queryset = queryset.annotate(Min(display_field.path + display_field.field))
            elif display_field.aggregate == "Count":
                queryset = queryset.annotate(Count(display_field.path + display_field.field))
            elif display_field.aggregate == "Sum":
                queryset = queryset.annotate(Sum(display_field.path + display_field.field))
        return queryset

    def get_query(self):
        report = self
        model_class = report.root_model.model_class()
        message= ""
        objects = model_class.objects.all()

        # Filters
        # NOTE: group all the filters together into one in order to avoid
        # unnecessary joins
        filters = {}
        excludes = {}
        for filter_field in report.filterfield_set.all():
            try:
                # exclude properties from standard ORM filtering
                if '[property]' in filter_field.field_verbose:
                    continue
                if '[custom' in filter_field.field_verbose:
                    continue

                filter_string = str(filter_field.path + filter_field.field)

                if filter_field.filter_type:
                    filter_string += '__' + filter_field.filter_type

                # Check for special types such as isnull
                if filter_field.filter_type == "isnull" and filter_field.filter_value == "0":
                    filter_ = {filter_string: False}
                elif filter_field.filter_type == "in":
                    filter_ = {filter_string: filter_field.filter_value.split(',')}
                else:
                    # All filter values are stored as strings, but may need to be converted
                    if '[Date' in filter_field.field_verbose:
                        filter_value = parser.parse(filter_field.filter_value)
                        if settings.USE_TZ:
                            filter_value = timezone.make_aware(
                                filter_value,
                                timezone.get_current_timezone()
                            )
                        if filter_field.filter_type == 'range':
                            filter_value = [filter_value, parser.parse(filter_field.filter_value2)]
                            if settings.USE_TZ:
                                filter_value[1] = timezone.make_aware(
                                    filter_value[1],
                                    timezone.get_current_timezone()
                                )
                    else:
                        filter_value = filter_field.filter_value
                        if filter_field.filter_type == 'range':
                            filter_value = [filter_value, filter_field.filter_value2]
                    filter_ = {filter_string: filter_value}

                if not filter_field.exclude:
                    filters.update(filter_)
                else:
                    excludes.update(filter_)

            except Exception, e:
                message += "Filter Error on %s. If you are using the report builder then " % filter_field.field_verbose
                message += "you found a bug! "
                message += "If you made this in admin, then you probably did something wrong."

        if filters:
            objects = objects.filter(**filters)
        if excludes:
            objects = objects.exclude(**excludes)

        # Aggregates
        objects = self.add_aggregates(objects)

        # Distinct
        if report.distinct:
            objects = objects.distinct()

        return objects

    @models.permalink
    def get_absolute_url(self):
        return ("report_update_view", [str(self.id)])

    def edit(self):
        return mark_safe(''.format(
            self.get_absolute_url(),
            getattr(settings, 'STATIC_URL', '/static/')
        ))
    edit.allow_tags = True

    def download_xlsx(self):
        return mark_safe(''.format(
            reverse('report_builder.views.download_xlsx', args=[self.id]),
            getattr(settings, 'STATIC_URL', '/static/'),
        ))
    download_xlsx.short_description = "Download"
    download_xlsx.allow_tags = True

    def copy_report(self):
        return ''.format(
            reverse('report_builder.views.create_copy', args=[self.id]),
            getattr(settings, 'STATIC_URL', '/static/'),
        )
    copy_report.short_description = "Copy"
    copy_report.allow_tags = True

    def check_report_display_field_positions(self):
        """ After report is saved, make sure positions are sane
        """
        for i, display_field in enumerate(self.displayfield_set.all()):
            if display_field.position != i+1:
                display_field.position = i+1
                display_field.save()

class Format(models.Model):
    """ A specifies a Python string format for e.g. `DisplayField`s.
    """
    name = models.CharField(max_length=50, blank=True, default='')
    string = models.CharField(max_length=300, blank=True, default='', help_text='Python string format. Ex ${} would place a $ in front of the result.')

    def __unicode__(self):
        return self.name

class DisplayField(models.Model):
    """ A display field to show in a report. Always belongs to a Report
    """
    report = models.ForeignKey(Report)
    path = models.CharField(max_length=2000, blank=True)
    path_verbose = models.CharField(max_length=2000, blank=True)
    field = models.CharField(max_length=2000)
    field_verbose = models.CharField(max_length=2000)
    name = models.CharField(max_length=2000)
    sort = models.IntegerField(blank=True, null=True)
    sort_reverse = models.BooleanField(verbose_name="Reverse")
    width = models.IntegerField(default=15)
    aggregate = models.CharField(
        max_length=5,
        choices = (
            ('Sum','Sum'),
            ('Count','Count'),
            ('Avg','Avg'),
            ('Max','Max'),
            ('Min','Min'),
        ),
        blank = True
    )
    position = models.PositiveSmallIntegerField(blank = True, null = True)
    total = models.BooleanField(default=False)
    group = models.BooleanField(default=False)
    display_format = models.ForeignKey(Format, blank=True, null=True)

    class Meta:
        ordering = ['position']

    def get_choices(self, path, field_name):
        model_name = path.split(':')[-1]
        model = ContentType.objects.get(model=model_name).model_class()
        try:
            model_field = model._meta.get_field_by_name(field_name)[0]
        except:
            model_field = None
        if model_field and model_field.choices:
            return model_field.choices

    @property
    def choices_dict(self):
        choices = self.choices
        choices_dict = {}
        if choices:
            for choice in choices:
                choices_dict.update({choice[0]: choice[1]})
        return choices_dict

    @property
    def choices(self):
        if self.pk:
            path = self.path_verbose or self.report.root_model.model
            return self.get_choices(path, self.field)

    def __unicode__(self):
        return self.name

class FilterField(models.Model):
    """ A display field to show in a report. Always belongs to a Report
    """
    report = models.ForeignKey(Report)
    path = models.CharField(max_length=2000, blank=True)
    path_verbose = models.CharField(max_length=2000, blank=True)
    field = models.CharField(max_length=2000)
    field_verbose = models.CharField(max_length=2000)
    filter_type = models.CharField(
        max_length=20,
        choices = (
            ('exact','Equals'),
            ('iexact','Equals (case-insensitive)'),
            ('contains','Contains'),
            ('icontains','Contains (case-insensitive)'),
            ('in','in (comma seperated 1,2,3)'),
            ('gt','Greater than'),
            ('gte','Greater than equals'),
            ('lt','Less than'),
            ('lte','Less than equals'),
            ('startswith','Starts with'),
            ('istartswith','Starts with (case-insensitive)'),
            ('endswith','Ends with'),
            ('iendswith','Ends with  (case-insensitive)'),
            ('range','range'),
            ('week_day','Week day'),
            ('isnull','Is null'),
            ('regex','Regular Expression'),
            ('iregex','Reg. Exp. (case-insensitive)'),
        ),
        blank=True,
        default = 'icontains',
    )
    filter_value = models.CharField(max_length=2000)
    filter_value2 = models.CharField(max_length=2000, blank=True)
    exclude = models.BooleanField()
    position = models.PositiveSmallIntegerField(blank = True, null = True)

    class Meta:
        ordering = ['position']

    def clean(self):
        if self.filter_type == "range":
            if self.filter_value2 in [None, ""]:
                raise ValidationError('Range filters must have two values')
        return super(FilterField, self).clean()

    def get_choices(self, path, field_name):
        model_name = path.split(':')[-1]
        model = ContentType.objects.get(model=model_name).model_class()
        try:
            model_field = model._meta.get_field_by_name(field_name)[0]
        except:
            model_field = None
        if model_field and model_field.choices:
            return model_field.choices

    @property
    def choices(self):
        if self.pk:
            path = self.path_verbose or self.report.root_model.model
            return self.get_choices(path, self.field)

    def __unicode__(self):
        return self.field

<commit_msg>made exception python2/3 compatible<commit_after>from django.contrib.contenttypes.models import ContentType
from django.conf import settings
from django.core.urlresolvers import reverse
from django.core.exceptions import ValidationError
from django.utils.safestring import mark_safe
from django.utils import timezone
from django.db import models
from django.db.models import Avg, Min, Max, Count, Sum
from django.db.models.signals import post_save
from report_builder.unique_slugify import unique_slugify
from dateutil import parser

AUTH_USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User')

class Report(models.Model):
    """ A saved report with queryset and descriptive fields
    """
    def _get_allowed_models():
        models = ContentType.objects.all()
        if getattr(settings, 'REPORT_BUILDER_INCLUDE', False):
            models = models.filter(name__in=settings.REPORT_BUILDER_INCLUDE)
        if getattr(settings, 'REPORT_BUILDER_EXCLUDE', False):
            models = models.exclude(name__in=settings.REPORT_BUILDER_EXCLUDE)
        return models

    name = models.CharField(max_length=255)
    slug = models.SlugField(verbose_name="Short Name")
    description = models.TextField(blank=True)
    root_model = models.ForeignKey(ContentType, limit_choices_to={'pk__in':_get_allowed_models})
    created = models.DateField(auto_now_add=True)
    modified = models.DateField(auto_now=True)
    user_created = models.ForeignKey(AUTH_USER_MODEL, editable=False, blank=True, null=True)
    user_modified = models.ForeignKey(AUTH_USER_MODEL, editable=False, blank=True, null=True, related_name="report_modified_set")
    distinct = models.BooleanField()
    starred = models.ManyToManyField(AUTH_USER_MODEL, blank=True,
                                     help_text="These users have starred this report for easy reference.",
                                     related_name="report_starred_set")

    def save(self, *args, **kwargs):
        if not self.id:
            unique_slugify(self, self.name)
        super(Report, self).save(*args, **kwargs)

    def add_aggregates(self, queryset):
        for display_field in self.displayfield_set.filter(aggregate__isnull=False):
            if display_field.aggregate == "Avg":
                queryset = queryset.annotate(Avg(display_field.path + display_field.field))
            elif display_field.aggregate == "Max":
                queryset = queryset.annotate(Max(display_field.path + display_field.field))
            elif display_field.aggregate == "Min":
                queryset = queryset.annotate(Min(display_field.path + display_field.field))
            elif display_field.aggregate == "Count":
                queryset = queryset.annotate(Count(display_field.path + display_field.field))
            elif display_field.aggregate == "Sum":
                queryset = queryset.annotate(Sum(display_field.path + display_field.field))
        return queryset

    def get_query(self):
        report = self
        model_class = report.root_model.model_class()
        message= ""
        objects = model_class.objects.all()

        # Filters
        # NOTE: group all the filters together into one in order to avoid
        # unnecessary joins
        filters = {}
        excludes = {}
        for filter_field in report.filterfield_set.all():
            try:
                # exclude properties from standard ORM filtering
                if '[property]' in filter_field.field_verbose:
                    continue
                if '[custom' in filter_field.field_verbose:
                    continue

                filter_string = str(filter_field.path + filter_field.field)

                if filter_field.filter_type:
                    filter_string += '__' + filter_field.filter_type

                # Check for special types such as isnull
                if filter_field.filter_type == "isnull" and filter_field.filter_value == "0":
                    filter_ = {filter_string: False}
                elif filter_field.filter_type == "in":
                    filter_ = {filter_string: filter_field.filter_value.split(',')}
                else:
                    # All filter values are stored as strings, but may need to be converted
                    if '[Date' in filter_field.field_verbose:
                        filter_value = parser.parse(filter_field.filter_value)
                        if settings.USE_TZ:
                            filter_value = timezone.make_aware(
                                filter_value,
                                timezone.get_current_timezone()
                            )
                        if filter_field.filter_type == 'range':
                            filter_value = [filter_value, parser.parse(filter_field.filter_value2)]
                            if settings.USE_TZ:
                                filter_value[1] = timezone.make_aware(
                                    filter_value[1],
                                    timezone.get_current_timezone()
                                )
                    else:
                        filter_value = filter_field.filter_value
                        if filter_field.filter_type == 'range':
                            filter_value = [filter_value, filter_field.filter_value2]
                    filter_ = {filter_string: filter_value}

                if not filter_field.exclude:
                    filters.update(filter_)
                else:
                    excludes.update(filter_)

            except Exception:
                import sys
                e = sys.exc_info()[1]
                message += "Filter Error on %s. If you are using the report builder then " % filter_field.field_verbose
                message += "you found a bug! "
                message += "If you made this in admin, then you probably did something wrong."

        if filters:
            objects = objects.filter(**filters)
        if excludes:
            objects = objects.exclude(**excludes)

        # Aggregates
        objects = self.add_aggregates(objects)

        # Distinct
        if report.distinct:
            objects = objects.distinct()

        return objects

    @models.permalink
    def get_absolute_url(self):
        return ("report_update_view", [str(self.id)])

    def edit(self):
        return mark_safe(''.format(
            self.get_absolute_url(),
            getattr(settings, 'STATIC_URL', '/static/')
        ))
    edit.allow_tags = True

    def download_xlsx(self):
        return mark_safe(''.format(
            reverse('report_builder.views.download_xlsx', args=[self.id]),
            getattr(settings, 'STATIC_URL', '/static/'),
        ))
    download_xlsx.short_description = "Download"
    download_xlsx.allow_tags = True

    def copy_report(self):
        return ''.format(
            reverse('report_builder.views.create_copy', args=[self.id]),
            getattr(settings, 'STATIC_URL', '/static/'),
        )
    copy_report.short_description = "Copy"
    copy_report.allow_tags = True

    def check_report_display_field_positions(self):
        """ After report is saved, make sure positions are sane
        """
        for i, display_field in enumerate(self.displayfield_set.all()):
            if display_field.position != i+1:
                display_field.position = i+1
                display_field.save()

class Format(models.Model):
    """ A specifies a Python string format for e.g. `DisplayField`s.
    """
    name = models.CharField(max_length=50, blank=True, default='')
    string = models.CharField(max_length=300, blank=True, default='', help_text='Python string format. Ex ${} would place a $ in front of the result.')

    def __unicode__(self):
        return self.name

class DisplayField(models.Model):
    """ A display field to show in a report. Always belongs to a Report
    """
    report = models.ForeignKey(Report)
    path = models.CharField(max_length=2000, blank=True)
    path_verbose = models.CharField(max_length=2000, blank=True)
    field = models.CharField(max_length=2000)
    field_verbose = models.CharField(max_length=2000)
    name = models.CharField(max_length=2000)
    sort = models.IntegerField(blank=True, null=True)
    sort_reverse = models.BooleanField(verbose_name="Reverse")
    width = models.IntegerField(default=15)
    aggregate = models.CharField(
        max_length=5,
        choices = (
            ('Sum','Sum'),
            ('Count','Count'),
            ('Avg','Avg'),
            ('Max','Max'),
            ('Min','Min'),
        ),
        blank = True
    )
    position = models.PositiveSmallIntegerField(blank = True, null = True)
    total = models.BooleanField(default=False)
    group = models.BooleanField(default=False)
    display_format = models.ForeignKey(Format, blank=True, null=True)

    class Meta:
        ordering = ['position']

    def get_choices(self, path, field_name):
        model_name = path.split(':')[-1]
        model = ContentType.objects.get(model=model_name).model_class()
        try:
            model_field = model._meta.get_field_by_name(field_name)[0]
        except:
            model_field = None
        if model_field and model_field.choices:
            return model_field.choices

    @property
    def choices_dict(self):
        choices = self.choices
        choices_dict = {}
        if choices:
            for choice in choices:
                choices_dict.update({choice[0]: choice[1]})
        return choices_dict

    @property
    def choices(self):
        if self.pk:
            path = self.path_verbose or self.report.root_model.model
            return self.get_choices(path, self.field)

    def __unicode__(self):
        return self.name

class FilterField(models.Model):
    """ A display field to show in a report. Always belongs to a Report
    """
    report = models.ForeignKey(Report)
    path = models.CharField(max_length=2000, blank=True)
    path_verbose = models.CharField(max_length=2000, blank=True)
    field = models.CharField(max_length=2000)
    field_verbose = models.CharField(max_length=2000)
    filter_type = models.CharField(
        max_length=20,
        choices = (
            ('exact','Equals'),
            ('iexact','Equals (case-insensitive)'),
            ('contains','Contains'),
            ('icontains','Contains (case-insensitive)'),
            ('in','in (comma seperated 1,2,3)'),
            ('gt','Greater than'),
            ('gte','Greater than equals'),
            ('lt','Less than'),
            ('lte','Less than equals'),
            ('startswith','Starts with'),
            ('istartswith','Starts with (case-insensitive)'),
            ('endswith','Ends with'),
            ('iendswith','Ends with  (case-insensitive)'),
            ('range','range'),
            ('week_day','Week day'),
            ('isnull','Is null'),
            ('regex','Regular Expression'),
            ('iregex','Reg. Exp. (case-insensitive)'),
        ),
        blank=True,
        default = 'icontains',
    )
    filter_value = models.CharField(max_length=2000)
    filter_value2 = models.CharField(max_length=2000, blank=True)
    exclude = models.BooleanField()
    position = models.PositiveSmallIntegerField(blank = True, null = True)

    class Meta:
        ordering = ['position']

    def clean(self):
        if self.filter_type == "range":
            if self.filter_value2 in [None, ""]:
                raise ValidationError('Range filters must have two values')
        return super(FilterField, self).clean()

    def get_choices(self, path, field_name):
        model_name = path.split(':')[-1]
        model = ContentType.objects.get(model=model_name).model_class()
        try:
            model_field = model._meta.get_field_by_name(field_name)[0]
        except:
            model_field = None
        if model_field and model_field.choices:
            return model_field.choices

    @property
    def choices(self):
        if self.pk:
            path = self.path_verbose or self.report.root_model.model
            return self.get_choices(path, self.field)

    def __unicode__(self):
        return self.field

<|endoftext|>


<commit_before># Copyright (c) 2014-2015, GEM Foundation.
#
# OpenQuake 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.
#
# OpenQuake 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 Affero General Public License
# along with OpenQuake.  If not, see <http://www.gnu.org/licenses/>.

"""
Core functionality for the classical tilint PSHA hazard calculator.
"""
import math
from openquake.baselib.general import split_in_blocks
from openquake.commonlib import readinput
from openquake.hazardlib.site import SiteCollection

from openquake.engine.calculators import calculators
from openquake.engine.calculators.hazard.general import BaseHazardCalculator
from openquake.engine.logs import LOG

@calculators.add('classical_tiling')
class ClassicalTilingHazardCalculator(BaseHazardCalculator):
    """
    Classical tiling PSHA hazard calculator.
    """

    def run_tile(self, i, tile):
        """
        :param i: ordinal number of the tile being processed (from 1)
        :param tile: list of sites being processed
        """
        classical = calculators['classical'](self.job)
        classical.tilepath = ('tile%d' % i,)
        classical.site_collection = SiteCollection(tile)
        classical.initialize_sources()
        classical.init_zeros_ones()
        classical.execute()
        classical.post_execute()
        classical.post_process()

    def pre_execute(self):
        """
        Read the full source model and sites and build the needed tiles
        """
        self.oqparam = self.job.get_oqparam()
        source_model_lt = readinput.get_source_model_lt(self.oqparam)
        source_models = list(readinput.get_source_models(
            self.oqparam, source_model_lt))
        self.parse_risk_model()
        self.initialize_site_collection()
        info = readinput.get_job_info(
            self.oqparam, source_models, self.site_collection)
        self.imtls = self.oqparam.intensity_measure_types_and_levels
        weight = info['n_sites'] * info['n_levels'] * info['max_realizations']
        nblocks = math.ceil(weight / self.oqparam.maximum_tile_weight)
        self.tiles = list(split_in_blocks(self.site_collection, nblocks))
        self.num_tiles = len(self.tiles)

    def execute(self):
        """
        Executing all tiles sequentially
        """
        for i, tile in enumerate(self.tiles, 1):
            LOG.progress('Running tile %d of %d, %s sites',
                         i, self.num_tiles, len(tile))
            self.run_tile(i, tile)

    def post_execute(self):
        """Do nothing"""

    def post_process(self):
        """Do nothing"""
<commit_msg>Fixed a parameter changed in another branch<commit_after># Copyright (c) 2014-2015, GEM Foundation.
#
# OpenQuake 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.
#
# OpenQuake 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 Affero General Public License
# along with OpenQuake.  If not, see <http://www.gnu.org/licenses/>.

"""
Core functionality for the classical tilint PSHA hazard calculator.
"""
import math
from openquake.baselib.general import split_in_blocks
from openquake.commonlib import readinput
from openquake.hazardlib.site import SiteCollection

from openquake.engine.calculators import calculators
from openquake.engine.calculators.hazard.general import BaseHazardCalculator
from openquake.engine.logs import LOG

@calculators.add('classical_tiling')
class ClassicalTilingHazardCalculator(BaseHazardCalculator):
    """
    Classical tiling PSHA hazard calculator.
    """

    def run_tile(self, i, tile):
        """
        :param i: ordinal number of the tile being processed (from 1)
        :param tile: list of sites being processed
        """
        classical = calculators['classical'](self.job)
        classical.tilepath = ('tile%d' % i,)
        classical.site_collection = SiteCollection(tile)
        classical.initialize_sources()
        classical.init_zeros_ones()
        classical.execute()
        classical.post_execute()
        classical.post_process()

    def pre_execute(self):
        """
        Read the full source model and sites and build the needed tiles
        """
        self.oqparam = self.job.get_oqparam()
        source_model_lt = readinput.get_source_model_lt(self.oqparam)
        source_models = list(readinput.get_source_models(
            self.oqparam, source_model_lt))
        self.parse_risk_model()
        self.initialize_site_collection()
        info = readinput.get_job_info(
            self.oqparam, source_models, self.site_collection)
        self.imtls = self.oqparam.imtls
        weight = info['n_sites'] * info['n_levels'] * info['max_realizations']
        nblocks = math.ceil(weight / self.oqparam.maximum_tile_weight)
        self.tiles = list(split_in_blocks(self.site_collection, nblocks))
        self.num_tiles = len(self.tiles)

    def execute(self):
        """
        Executing all tiles sequentially
        """
        for i, tile in enumerate(self.tiles, 1):
            LOG.progress('Running tile %d of %d, %s sites',
                         i, self.num_tiles, len(tile))
            self.run_tile(i, tile)

    def post_execute(self):
        """Do nothing"""

    def post_process(self):
        """Do nothing"""
<|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 selenium.webdriver.common import by

from openstack_dashboard.test.integration_tests.pages import navigation
from openstack_dashboard.test.integration_tests.pages import pageobject
from openstack_dashboard.test.integration_tests.regions import bars
from openstack_dashboard.test.integration_tests.regions import menus
from openstack_dashboard.test.integration_tests.regions import messages

class BasePage(pageobject.PageObject):
    """Base class for all dashboard page objects."""

    _heading_locator = (by.By.CSS_SELECTOR, 'div.page-header > h2')

    @property
    def heading(self):
        return self._get_element(*self._heading_locator)

    @property
    def topbar(self):
        return bars.TopBarRegion(self.driver, self.conf)

    @property
    def is_logged_in(self):
        return self.topbar.is_logged_in

    @property
    def navaccordion(self):
        return menus.NavigationAccordionRegion(self.driver, self.conf)

    def go_to_login_page(self):
        self.driver.get(self.login_url)

    def go_to_home_page(self):
        self.topbar.brand.click()

    def log_out(self):
        self.topbar.user_dropdown_menu.click_on_logout()
        return self.go_to_login_page()

    def go_to_help_page(self):
        self.topbar.user_dropdown_menu.click_on_help()

    def find_message_and_dismiss(self, message_level=messages.SUCCESS):
        message = messages.MessageRegion(self.driver, self.conf, message_level)
        is_message_present = message.exists()
        if is_message_present:
            message.close()
        return is_message_present

    def change_project(self, name):
        self.topbar.user_dropdown_project.click_on_project(name)

class BaseNavigationPage(BasePage, navigation.Navigation):
    pass
<commit_msg>Remove redundant line to open login page<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 selenium.webdriver.common import by

from openstack_dashboard.test.integration_tests.pages import navigation
from openstack_dashboard.test.integration_tests.pages import pageobject
from openstack_dashboard.test.integration_tests.regions import bars
from openstack_dashboard.test.integration_tests.regions import menus
from openstack_dashboard.test.integration_tests.regions import messages

class BasePage(pageobject.PageObject):
    """Base class for all dashboard page objects."""

    _heading_locator = (by.By.CSS_SELECTOR, 'div.page-header > h2')

    @property
    def heading(self):
        return self._get_element(*self._heading_locator)

    @property
    def topbar(self):
        return bars.TopBarRegion(self.driver, self.conf)

    @property
    def is_logged_in(self):
        return self.topbar.is_logged_in

    @property
    def navaccordion(self):
        return menus.NavigationAccordionRegion(self.driver, self.conf)

    def go_to_login_page(self):
        self.driver.get(self.login_url)

    def go_to_home_page(self):
        self.topbar.brand.click()

    def log_out(self):
        self.topbar.user_dropdown_menu.click_on_logout()

    def go_to_help_page(self):
        self.topbar.user_dropdown_menu.click_on_help()

    def find_message_and_dismiss(self, message_level=messages.SUCCESS):
        message = messages.MessageRegion(self.driver, self.conf, message_level)
        is_message_present = message.exists()
        if is_message_present:
            message.close()
        return is_message_present

    def change_project(self, name):
        self.topbar.user_dropdown_project.click_on_project(name)

class BaseNavigationPage(BasePage, navigation.Navigation):
    pass
<|endoftext|>


<commit_before># © 2019 Comunitea
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import models
from datetime import datetime

class ComputeRappelInvoice(models.TransientModel):

    _inherit = 'rappel.invoice.wzd'

    def action_invoice(self):
        res = super().action_invoice()
        compute_rappel_obj = self.env["rappel.calculated"]
        for rappel in compute_rappel_obj.browse(self.env.context["active_ids"]):
            if rappel.quantity <= 0:
                continue
            if rappel.invoice_id:
                invoice_rappel = rappel.invoice_id
                # Update description invoice lines
                for line in invoice_rappel.invoice_line_ids:
                    ctx = dict(rappel.rappel_id._context or {})
                    ctx['lang'] = rappel.partner_id.lang
                    line.write(
                        {'name': '{} ({} - {})'.format(
                            rappel.rappel_id.with_context(ctx).description,
                            datetime.strptime(rappel.date_start, "%Y-%m-%d").strftime('%d/%m/%Y'),
                            datetime.strptime(rappel.date_end, "%Y-%m-%d").strftime('%d/%m/%Y'))})
                # Update account data
                if not invoice_rappel.payment_mode_id \
                        or not invoice_rappel.partner_bank_id \
                        or not invoice_rappel.team_id:
                    partner_bank_id = False
                    for banks in rappel.partner_id.bank_ids:
                        for mandate in banks.mandate_ids:
                            if mandate.state == 'valid':
                                partner_bank_id = banks.id
                                break
                            else:
                                partner_bank_id = False
                    invoice_rappel.write(
                        {'payment_mode_id':
                         rappel.partner_id.customer_payment_mode_id.id,
                         'partner_bank_id': partner_bank_id,
                         'team_id': rappel.partner_id.team_id.id})
        return res
<commit_msg>[FIX] rappel_custom: Calcular tasas al crear factura rectificativa desde el asistente de rappels calculados y arrastrar mandato del cliente<commit_after># © 2019 Comunitea
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import models
from datetime import datetime

class ComputeRappelInvoice(models.TransientModel):

    _inherit = 'rappel.invoice.wzd'

    def action_invoice(self):
        res = super().action_invoice()
        compute_rappel_obj = self.env["rappel.calculated"]
        for rappel in compute_rappel_obj.browse(self.env.context["active_ids"]):
            if rappel.quantity <= 0:
                continue
            if rappel.invoice_id:
                invoice_rappel = rappel.invoice_id
                invoice_rappel.compute_taxes()
                partner = rappel.partner_id
                # Update description invoice lines
                for line in invoice_rappel.invoice_line_ids:
                    ctx = dict(rappel.rappel_id._context or {})
                    ctx['lang'] = partner.lang
                    line.write(
                        {'name': '{} ({} - {})'.format(
                            rappel.rappel_id.with_context(ctx).description,
                            datetime.strptime(rappel.date_start, "%Y-%m-%d").strftime('%d/%m/%Y'),
                            datetime.strptime(rappel.date_end, "%Y-%m-%d").strftime('%d/%m/%Y'))})
                # Update account data
                if not invoice_rappel.payment_mode_id \
                        or not invoice_rappel.mandate_id \
                        or not invoice_rappel.team_id:
                    invoice_rappel.write(
                        {'payment_mode_id':
                         partner.customer_payment_mode_id.id,
                         'mandate_id': partner.valid_mandate_id.id,
                         'team_id': partner.team_id.id})
        return res
<|endoftext|>


<commit_before>#  Numenta Platform for Intelligent Computing (NuPIC)
#  Copyright (C) 2021, Numenta, Inc.  Unless you have an agreement
#  with Numenta, Inc., for a separate license for this software code, the
#  following terms and conditions apply:
#
#  This program is free software you can redistribute it and/or modify
#  it under the terms of the GNU Affero Public License version 3 as
#  published by the Free Software Foundation.
#
#  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 Public License for more details.
#
#  You should have received a copy of the GNU Affero Public License
#  along with this program.  If not, see htt"://www.gnu.org/licenses.
#
#  http://numenta.org/licenses/
#

"""
Experiment file that runs dendritic networks where (a) the context vector is inferred
during inference via prototyping, and (b) Synaptic Intelligence (SI) is applied to the
feed-forward parameters.
"""

import os
from copy import deepcopy

import numpy as np
import ray.tune as tune
import torch
import torch.nn.functional as F

from nupic.research.frameworks.dendrites import DendriticMLP
from nupic.research.frameworks.dendrites.dendrite_cl_experiment import (
    DendriteContinualLearningExperiment,
)
from nupic.research.frameworks.pytorch.datasets import PermutedMNIST
from nupic.research.frameworks.vernon import mixins

class SIPrototypeExperiment(mixins.SynapticIntelligence,
                            mixins.RezeroWeights,
                            mixins.PrototypeContext,
                            mixins.PermutedMNISTTaskIndices,
                            DendriteContinualLearningExperiment):
    pass

# Synaptic Intelligence + Dendrites on 10 permutedMNIST tasks
SI_PROTOTYPE_10 = dict(
    experiment_class=SIPrototypeExperiment,
    num_samples=8,

    # Results path
    local_dir=os.path.expanduser("~/nta/results/experiments/dendrites"),

    dataset_class=PermutedMNIST,
    dataset_args=dict(
        num_tasks=10,
        root=os.path.expanduser("~/nta/results/data/"),
        download=False,  # Change to True if running for the first time
        seed=42,
    ),

    model_class=DendriticMLP,
    model_args=dict(
        input_size=784,
        output_size=10,
        hidden_sizes=[2000, 2000],  # Note we use 2000 hidden units instead of 2048 for
                                    # a better comparison with SI and XdG
        num_segments=10,
        dim_context=784,
        kw=True,
        kw_percent_on=0.05,
        dendrite_weight_sparsity=0.0,
        weight_sparsity=0.5,
        context_percent_on=0.1,
    ),

    si_args=dict(
        c=0.1,
        damping=0.1,
    ),

    batch_size=256,
    val_batch_size=512,
    epochs=20,  # Note that SI only works well with ~20 epochs of training per task
    tasks_to_validate=[0, 1, 2, 3, 4, 9, 24, 49, 74, 99],
    num_tasks=10,
    num_classes=10 * 10,
    distributed=False,
    seed=tune.sample_from(lambda spec: np.random.randint(2, 10000)),

    loss_function=F.cross_entropy,
    optimizer_class=torch.optim.Adam,  # On permutedMNIST, Adam works better than
                                       # SGD with default hyperparameter settings
    optimizer_args=dict(lr=5e-4),
    reset_optimizer_after_task=False,  # The SI paper reports not resetting the Adam
                                       # optimizer between tasks, and this
                                       # works well with dendrites too
)

# Synaptic Intelligence + Dendrites on 50 permutedMNIST tasks
SI_PROTOTYPE_50 = deepcopy(SI_PROTOTYPE_10)
SI_PROTOTYPE_50["dataset_args"].update(num_tasks=50)
SI_PROTOTYPE_50["model_args"].update(num_segments=50)
SI_PROTOTYPE_50.update(
    num_tasks=50,
    num_classes=10 * 50,
)

SI_PROTOTYPE_100 = deepcopy(SI_PROTOTYPE_50)
SI_PROTOTYPE_100["dataset_args"].update(num_tasks=100)
SI_PROTOTYPE_100["model_args"].update(num_segments=100)
SI_PROTOTYPE_100.update(
    num_tasks=100,
    num_classes=10 * 100,
    optimizer_args=dict(lr=5e-4),
)

# -------------------------- HYPERPARAMETER SEARCH CONFIGS -------------------------- #

# HP search on dendrites for 10 tasks with SI FF + SI Dendrites.
SI_PROTOTYPE_HP_10 = deepcopy(SI_PROTOTYPE_10)
SI_PROTOTYPE_HP_10["model_args"].update(
    kw_percent_on=0.1,
    weight_sparsity=0.5,
    num_segments=tune.grid_search([2, 3, 5, 7, 10, 14, 20, 30, 50, 100])
)
SI_PROTOTYPE_HP_10.update(
    tasks_to_validate=[9],

    si_args=dict(
        c=0.1,
        damping=0.1,
        apply_to_dendrites=True
    )
)

# HP search on dendrites for 10 tasks with SI FF.
SI_PROTOTYPE_HP_10_CONTROL = deepcopy(SI_PROTOTYPE_HP_10)
SI_PROTOTYPE_HP_10_CONTROL["model_args"].update(
    kw_percent_on=0.1,
    weight_sparsity=0.5,
    num_segments=tune.grid_search([2, 3, 5, 7, 10, 14, 20, 30, 50, 100])
)
SI_PROTOTYPE_HP_10_CONTROL.update(
    tasks_to_validate=[10],

    si_args=dict(
        c=0.1,
        damping=0.1,
        apply_to_dendrites=False
    )
)

# Test on 50 tasks with SI FF + SI Dendrites.
SI_PROTOTYPE_50_TEST_WITH_SI = deepcopy(SI_PROTOTYPE_50)
SI_PROTOTYPE_50_TEST_WITH_SI["model_args"].update(
    kw_percent_on=0.1,
    weight_sparsity=0.5,
    num_segments=50
)
SI_PROTOTYPE_50_TEST_WITH_SI.update(
    num_samples=8,
    tasks_to_validate=[49],

    si_args=dict(
        c=0.1,
        damping=0.1,
        apply_to_dendrites=True
    )
)

# Export configurations in this file
CONFIGS = dict(
    si__10=SI_PROTOTYPE_10,
    si_prototype_50=SI_PROTOTYPE_50,
    si_prototype_100=SI_PROTOTYPE_100,
    si_prototype_hp_10=SI_PROTOTYPE_HP_10,
    si_prototype_hp_10_control=SI_PROTOTYPE_HP_10_CONTROL,
    si_prototype_50_test_with_si=SI_PROTOTYPE_50_TEST_WITH_SI
)
<commit_msg>Fix typo<commit_after>#  Numenta Platform for Intelligent Computing (NuPIC)
#  Copyright (C) 2021, Numenta, Inc.  Unless you have an agreement
#  with Numenta, Inc., for a separate license for this software code, the
#  following terms and conditions apply:
#
#  This program is free software you can redistribute it and/or modify
#  it under the terms of the GNU Affero Public License version 3 as
#  published by the Free Software Foundation.
#
#  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 Public License for more details.
#
#  You should have received a copy of the GNU Affero Public License
#  along with this program.  If not, see htt"://www.gnu.org/licenses.
#
#  http://numenta.org/licenses/
#

"""
Experiment file that runs dendritic networks where (a) the context vector is inferred
during inference via prototyping, and (b) Synaptic Intelligence (SI) is applied to the
feed-forward parameters.
"""

import os
from copy import deepcopy

import numpy as np
import ray.tune as tune
import torch
import torch.nn.functional as F

from nupic.research.frameworks.dendrites import DendriticMLP
from nupic.research.frameworks.dendrites.dendrite_cl_experiment import (
    DendriteContinualLearningExperiment,
)
from nupic.research.frameworks.pytorch.datasets import PermutedMNIST
from nupic.research.frameworks.vernon import mixins

class SIPrototypeExperiment(mixins.SynapticIntelligence,
                            mixins.RezeroWeights,
                            mixins.PrototypeContext,
                            mixins.PermutedMNISTTaskIndices,
                            DendriteContinualLearningExperiment):
    pass

# Synaptic Intelligence + Dendrites on 10 permutedMNIST tasks
SI_PROTOTYPE_10 = dict(
    experiment_class=SIPrototypeExperiment,
    num_samples=8,

    # Results path
    local_dir=os.path.expanduser("~/nta/results/experiments/dendrites"),

    dataset_class=PermutedMNIST,
    dataset_args=dict(
        num_tasks=10,
        root=os.path.expanduser("~/nta/results/data/"),
        download=False,  # Change to True if running for the first time
        seed=42,
    ),

    model_class=DendriticMLP,
    model_args=dict(
        input_size=784,
        output_size=10,
        hidden_sizes=[2000, 2000],  # Note we use 2000 hidden units instead of 2048 for
                                    # a better comparison with SI and XdG
        num_segments=10,
        dim_context=784,
        kw=True,
        kw_percent_on=0.05,
        dendrite_weight_sparsity=0.0,
        weight_sparsity=0.5,
        context_percent_on=0.1,
    ),

    si_args=dict(
        c=0.1,
        damping=0.1,
    ),

    batch_size=256,
    val_batch_size=512,
    epochs=20,  # Note that SI only works well with ~20 epochs of training per task
    tasks_to_validate=[0, 1, 2, 3, 4, 9, 24, 49, 74, 99],
    num_tasks=10,
    num_classes=10 * 10,
    distributed=False,
    seed=tune.sample_from(lambda spec: np.random.randint(2, 10000)),

    loss_function=F.cross_entropy,
    optimizer_class=torch.optim.Adam,  # On permutedMNIST, Adam works better than
                                       # SGD with default hyperparameter settings
    optimizer_args=dict(lr=5e-4),
    reset_optimizer_after_task=False,  # The SI paper reports not resetting the Adam
                                       # optimizer between tasks, and this
                                       # works well with dendrites too
)

# Synaptic Intelligence + Dendrites on 50 permutedMNIST tasks
SI_PROTOTYPE_50 = deepcopy(SI_PROTOTYPE_10)
SI_PROTOTYPE_50["dataset_args"].update(num_tasks=50)
SI_PROTOTYPE_50["model_args"].update(num_segments=50)
SI_PROTOTYPE_50.update(
    num_tasks=50,
    num_classes=10 * 50,
)

SI_PROTOTYPE_100 = deepcopy(SI_PROTOTYPE_50)
SI_PROTOTYPE_100["dataset_args"].update(num_tasks=100)
SI_PROTOTYPE_100["model_args"].update(num_segments=100)
SI_PROTOTYPE_100.update(
    num_tasks=100,
    num_classes=10 * 100,
    optimizer_args=dict(lr=5e-4),
)

# -------------------------- HYPERPARAMETER SEARCH CONFIGS -------------------------- #

# HP search on dendrites for 10 tasks with SI FF + SI Dendrites.
SI_PROTOTYPE_HP_10 = deepcopy(SI_PROTOTYPE_10)
SI_PROTOTYPE_HP_10["model_args"].update(
    kw_percent_on=0.1,
    weight_sparsity=0.5,
    num_segments=tune.grid_search([2, 3, 5, 7, 10, 14, 20, 30, 50, 100])
)
SI_PROTOTYPE_HP_10.update(
    tasks_to_validate=[9],

    si_args=dict(
        c=0.1,
        damping=0.1,
        apply_to_dendrites=True
    )
)

# HP search on dendrites for 10 tasks with SI FF.
SI_PROTOTYPE_HP_10_CONTROL = deepcopy(SI_PROTOTYPE_HP_10)
SI_PROTOTYPE_HP_10_CONTROL["model_args"].update(
    kw_percent_on=0.1,
    weight_sparsity=0.5,
    num_segments=tune.grid_search([2, 3, 5, 7, 10, 14, 20, 30, 50, 100])
)
SI_PROTOTYPE_HP_10_CONTROL.update(
    tasks_to_validate=[10],

    si_args=dict(
        c=0.1,
        damping=0.1,
        apply_to_dendrites=False
    )
)

# Test on 50 tasks with SI FF + SI Dendrites.
SI_PROTOTYPE_50_TEST_WITH_SI = deepcopy(SI_PROTOTYPE_50)
SI_PROTOTYPE_50_TEST_WITH_SI["model_args"].update(
    kw_percent_on=0.1,
    weight_sparsity=0.5,
    num_segments=50
)
SI_PROTOTYPE_50_TEST_WITH_SI.update(
    num_samples=8,
    tasks_to_validate=[49],

    si_args=dict(
        c=0.1,
        damping=0.1,
        apply_to_dendrites=True
    )
)

# Export configurations in this file
CONFIGS = dict(
    si_prototype_10=SI_PROTOTYPE_10,
    si_prototype_50=SI_PROTOTYPE_50,
    si_prototype_100=SI_PROTOTYPE_100,
    si_prototype_hp_10=SI_PROTOTYPE_HP_10,
    si_prototype_hp_10_control=SI_PROTOTYPE_HP_10_CONTROL,
    si_prototype_50_test_with_si=SI_PROTOTYPE_50_TEST_WITH_SI
)
<|endoftext|>


<commit_before>
"""
Region spatial relations
------------------------
Group of functions to compute region-region spatial relations.

"""

import numpy as np

def regions_relation_points(locs, regions, retriever, info_ret):
    """Function which computes the spatial relations between regions
    considering the shared neighbourhoods of their points.
    """
    n_reg = np.unique(regions).shape[0]
    coincidence = np.zeros((n_reg, n_reg))
    for i in xrange(locs.shape[0]):
        neighs = retriever.retrieve_neighs(locs[i, :], info_ret[i], False)
        print type(neighs)
        for j in range(len(neighs)):
            coincidence[regions[i], regions[neighs[j]]] += 1
    return coincidence
<commit_msg>Module for computing regions relations.<commit_after>
"""
Region spatial relations
------------------------
Group of functions to compute region-region spatial relations.

"""

import numpy as np

def regions_relation_points(locs, regions, retriever, info_ret):
    """Function which computes the spatial relations between regions
    considering the shared neighbourhoods of their points.

    TODO
    ----
    - Normalization coincidence
    """
    n_reg = np.unique(regions).shape[0]
    regs = np.unique(regions)
    map_reg = dict(zip(regs, range(regs.shape[0])))
    coincidence = np.zeros((n_reg, n_reg))
    for i in xrange(locs.shape[0]):
        neighs = retriever.retrieve_neighs(locs[i, :], info_ret[i], False)[0]
        for j in range(len(neighs)):
            coincidence[map_reg[regions[i]], map_reg[regions[neighs[j]]]] += 1
    return coincidence
<|endoftext|>


<commit_before>from MiniBotFramework.Sensing.Sensor import Sensor
from MiniBotFramework.Lib.TCS34725 import TCS34725 as CSensor
import smbus
import math

def distance(p1, p2):
    """ Returns distance between two 3-tuples.
    Used for evaluating color """
    return math.sqrt((p1[0]-p2[0])**2 + (p1[1]-p2[1])**2 + (p1[2]-p2[2])**2)

class ColorSensor(Sensor):
    """ Pre-determined set of colors and corresponding RGB 3-tuples
    that are the basis of color inputs. Sensor inputs will be compared
    with values in this dict to see what "color" it is closest to. """

    def __init__(self, bot, name, pin_number):
        Sensor.__init__(self, bot, name)
        self.pin_number = pin_number
        self.color_sensor = CSensor()
        self.bus = smbus.SMBus(1)
        self.bus.write_byte(0x29,0x80|0x12)
        ver = self.bus.read_byte(0x29)

        self.colors = {
            # "RED":(7885,2631,3034),
            # "GREEN":(4794,10432,8395),
            # "BLUE":(14162,7582,4268),
            # "ORANGE":(14162,7582,4268),
            # "VIOLET":(8263,7538,9303),
            # "YELLOW":(13772,12879,5783),
            # "PINK":(11483,7839,8267)
            "RED":(151,49,58),
            "GREEN":(160,357,286),
            "BLUE":(76,158,198),
            "ORANGE":(250,134,76),
            "VIOLET":(137,128,156),
            "YELLOW":(245,229,103),
            "PINK":(236,165,172)
        }

    def read(self):
        """ Returns a 3-tuple of RGB value """
        data = self.bus.read_i2c_block_data(0x29, 0)
        # clear = clear = data[1] << 8 | data[0]
        red = data[3] << 8 | data[2]
        green = data[5] << 8 | data[4]
        blue = data[7] << 8 | data[6]

        rgb = (red, green, blue)
        return rgb

    def read_color(self):
        """ Returns string of color """
        color_guess = ("", 99999999999999999999999999) #tuple of color, distance from color to input
        color_actual = self.read()
        for c in self.colors:
            dist = distance(self.colors[c],color_actual)
            print "    " + c+ " dist: " + str(dist)
            if(dist < color_guess[1]):
                color_guess = (c, dist)
                print "    new guess is " + color_guess[0]
        return color_guess[0]

<commit_msg>color sensor BEEP<commit_after>from MiniBotFramework.Sensing.Sensor import Sensor
from MiniBotFramework.Lib.TCS34725 import TCS34725 as CSensor
import smbus
import math

def distance(p1, p2):
    """ Returns distance between two 3-tuples.
    Used for evaluating color """
    return math.sqrt((p1[0]-p2[0])**2 + (p1[1]-p2[1])**2 + (p1[2]-p2[2])**2)

class ColorSensor(Sensor):
    """ Pre-determined set of colors and corresponding RGB 3-tuples
    that are the basis of color inputs. Sensor inputs will be compared
    with values in this dict to see what "color" it is closest to. """

    def __init__(self, bot, name, pin_number):
        Sensor.__init__(self, bot, name)
        self.pin_number = pin_number
        self.color_sensor = CSensor()
        self.bus = smbus.SMBus(1)
        self.bus.write_byte(0x29,0x80|0x12)
        ver = self.bus.read_byte(0x29)
        self.bus.write_byte(0x29, 0x80|0x00) # 0x00 = ENABLE register
        self.bus.write_byte(0x29, 0x01|0x02) # 0x01 = Power on, 0x02 RGB sensors enabled
        self.bus.write_byte(0x29, 0x80|0x14) # Reading results start register 14, LSB then MSB

        self.colors = {
            # "RED":(7885,2631,3034),
            # "GREEN":(4794,10432,8395),
            # "BLUE":(14162,7582,4268),
            # "ORANGE":(14162,7582,4268),
            # "VIOLET":(8263,7538,9303),
            # "YELLOW":(13772,12879,5783),
            # "PINK":(11483,7839,8267)
            "RED":(151,49,58),
            "GREEN":(160,357,286),
            "BLUE":(76,158,198),
            "ORANGE":(250,134,76),
            "VIOLET":(137,128,156),j
            "YELLOW":(245,229,103),
            "PINK":(236,165,172)
        }

    def read(self):
        """ Returns a 3-tuple of RGB value """
        data = self.bus.read_i2c_block_data(0x29, 0)
        # clear = clear = data[1] << 8 | data[0]
        red = data[3] << 8 | data[2]
        green = data[5] << 8 | data[4]
        blue = data[7] << 8 | data[6]

        rgb = (red, green, blue)
        return rgb

    def read_color(self):
        """ Returns string of color """
        color_guess = ("", 99999999999999999999999999) #tuple of color, distance from color to input
        color_actual = self.read()
        for c in self.colors:
            dist = distance(self.colors[c],color_actual)
            print "    " + c+ " dist: " + str(dist)
            if(dist < color_guess[1]):
                color_guess = (c, dist)
                print "    new guess is " + color_guess[0]
        return color_guess[0]

<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Adding model 'UserPrivacy'
        db.create_table(u'profile_userprivacy', (
            (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.User'])),
            ('public_profile', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('public_name', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('public_age', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('public_sex', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('public_email', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('public_phonenumber', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('public_town', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('public_contact', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('public_websites', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('public_join_date', self.gf('django.db.models.fields.BooleanField')(default=False)),
        ))
        db.send_create_signal(u'profile', ['UserPrivacy'])

    def backwards(self, orm):
        # Deleting model 'UserPrivacy'
        db.delete_table(u'profile_userprivacy')

    models = {
        u'auth.group': {
            'Meta': {'object_name': 'Group'},
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
            'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
        },
        u'auth.permission': {
            'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
            'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
        },
        u'auth.user': {
            'Meta': {'object_name': 'User'},
            'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
            'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
        },
        u'contenttypes.contenttype': {
            'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
        },
        u'profile.userprivacy': {
            'Meta': {'object_name': 'UserPrivacy'},
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'public_age': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'public_contact': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'public_email': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'public_join_date': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'public_name': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'public_phonenumber': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'public_profile': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'public_sex': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'public_town': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'public_websites': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"})
        }
    }

    complete_apps = ['profile']<commit_msg>Fix wrong app label<commit_after># -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Adding model 'UserPrivacy'
        db.create_table(u'profile_userprivacy', (
            (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.User'])),
            ('public_profile', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('public_name', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('public_age', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('public_sex', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('public_email', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('public_phonenumber', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('public_town', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('public_contact', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('public_websites', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('public_join_date', self.gf('django.db.models.fields.BooleanField')(default=False)),
        ))
        db.send_create_signal(u'userportal', ['UserPrivacy'])

    def backwards(self, orm):
        # Deleting model 'UserPrivacy'
        db.delete_table(u'profile_userprivacy')

    models = {
        u'auth.group': {
            'Meta': {'object_name': 'Group'},
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
            'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
        },
        u'auth.permission': {
            'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
            'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
        },
        u'auth.user': {
            'Meta': {'object_name': 'User'},
            'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
            'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
        },
        u'contenttypes.contenttype': {
            'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
        },
        u'userportal.userprivacy': {
            'Meta': {'object_name': 'UserPrivacy'},
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'public_age': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'public_contact': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'public_email': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'public_join_date': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'public_name': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'public_phonenumber': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'public_profile': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'public_sex': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'public_town': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'public_websites': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"})
        }
    }

    complete_apps = ['userportal']<|endoftext|>