<commit_before>from django.conf.urls import url

import views

urlpatterns = [
    url(r'^$', views.devices, name='devs'),
    url(r'^add$', views.dev, name='add'),
    url(r'^(?P<did>\d+)$', views.devview, name='view'),
    url(r'^(?P<did>\d+)/del$', views.devdel, name='del'),
    url(r'^(?P<devid>\d+)/edit$', views.dev, name='edit'),
]
<commit_msg>переключение порта<commit_after>from django.conf.urls import url

import views

urlpatterns = [
    url(r'^$', views.devices, name='devs'),
    url(r'^add$', views.dev, name='add'),
    url(r'^(?P<did>\d+)$', views.devview, name='view'),
    url(r'^(?P<did>\d+)/del$', views.devdel, name='del'),
    url(r'^(?P<devid>\d+)/edit$', views.dev, name='edit'),
    url(r'^(?P<did>\d+)/(?P<portid>\d+)_(?P<status>[0-1]{1})$', views.toggle_port, name='port_toggle')
]
<|endoftext|>


<commit_before>import random

total = 1000
current = 0
count = 0

while current < total:
    current += random.randrange(99)
    count += 1

print "Total obtenu : " + str(current)
print str(count) + " jets pour atteindre " + str(total)
<commit_msg>Ajout sauvegarde des jets et gestion des crits<commit_after>import random

total = 1000
current = 0
count = 0
rolls = []
crits = []

while current < total:
    roll = random.randrange(99)
    rolls.append(roll)
    if roll % 11 == 0:
        crits.append(roll)
        current += 2 * roll
    else:
        current += roll
    count += 1

print "Total obtenu : " + str(current)
print str(count) + " jets pour atteindre " + str(total)
print "Jets : " + str(rolls)
print "Critiques : " + str(crits)
<|endoftext|>


<commit_before>""" A simple python script that uses the leastsq function from SciPy to carry out a nonlinear
regression. Outputs a bunch of different measures to be used in judging the fit. Requires an input
file with x and y columns, no headings. Pass filename as an argument.

"""
import numpy, sys
from scipy.optimize import leastsq

# Define the function here, using p as an array of parameters. Functions must be able to take arrays
# as arguments (use numpy version of exp, for example).
def func(p, x):
    return (p[0] - p[1])*(1+(1-numpy.sqrt(8*p[2]*x+1))/(4*p[2]*x)) + p[1]

# Initial guesses for the parameters.
p0 = [10, 5, 600] # Pd Pm Ke

datafile = open(sys.argv[1])
x, y = numpy.array([]), numpy.array([])
for line in datafile:
    curline = line.replace("\n", "").split() # Splits at any whitespace.
    x = numpy.append(x, float(curline[0]))
    y = numpy.append(y, float(curline[1]))

# Defines the error function for leastsq. In for regression, it is just the residuals.
def func_res(p, x, y):
    return y - func(p, x)

dof = len(x) - len(p0) # Degrees of freedom

fit_parameters, covariance_matrix, info, msg, success \
    = leastsq(func_res, p0, args=(x,y), full_output=True)

sum_squares_residuals = sum(info["fvec"]*info["fvec"])
sum_squares_mean_dev = sum((y - numpy.mean(y))**2)

# The errors for each parameter are obtained by multiplying the covariance matrix by the residual
# variance (= sum_squares_residuals / dof).
errors = []
for i in range(len(covariance_matrix)):
    errors.append(numpy.sqrt(covariance_matrix[i,i]*sum_squares_residuals/dof))

print("**Regression results for file \"{}\"**".format(sys.argv[1]))
print()

print("Data (x, y, yfit)")
print("=================")
for n in range(len(x)):
    print("{}, {}, {}".format(x[n], y[n], y[n] + info["fvec"][n]))
print()

print("Optimized parameters")
print("====================")
for n in range(len(fit_parameters)):
    print("{} +/- {}".format(fit_parameters[n], errors[n]))
print()

print("Regression data")
print("===============")

# See leastsq documentation for descriptions of flags.
print("Flag: {}".format(success))

print("Std Deviation of residuals: {}".format(numpy.sqrt(sum_squares_residuals/dof)))
print("chi2 (sum square residuals): {}".format(sum_squares_residuals))

# Ideally, (reduced chi2)/(std dev of measurement) = 1.
print("Reduced chi2 (chi2/dof): {}".format(sum_squares_residuals/dof))
print("R2 = {}".format(1 - sum_squares_residuals/sum_squares_mean_dev))
print("Adjusted R2 = {}".format(1 - (sum_squares_residuals/dof)/(sum_squares_mean_dev/(len(x)-1))))
print("Covariance matrix:")
print(covariance_matrix*sum_squares_residuals/dof)
print("Residuals:")
print(info["fvec"])
<commit_msg>Fix calc of fit y data<commit_after>""" A simple python script that uses the leastsq function from SciPy to carry out a nonlinear
regression. Outputs a bunch of different measures to be used in judging the fit. Requires an input
file with x and y columns, no headings. Pass filename as an argument.

"""
import numpy, sys
from scipy.optimize import leastsq

# Define the function here, using p as an array of parameters. Functions must be able to take arrays
# as arguments (use numpy version of exp, for example).
def func(p, x):
    return (p[0] - p[1])*(1+(1-numpy.sqrt(8*p[2]*x+1))/(4*p[2]*x)) + p[1]

# Initial guesses for the parameters.
p0 = [10, 5, 600] # Pd Pm Ke

datafile = open(sys.argv[1])
x, y = numpy.array([]), numpy.array([])
for line in datafile:
    curline = line.replace("\n", "").split() # Splits at any whitespace.
    x = numpy.append(x, float(curline[0]))
    y = numpy.append(y, float(curline[1]))

# Defines the error function for leastsq. In for regression, it is just the residuals.
def func_res(p, x, y):
    return y - func(p, x)

dof = len(x) - len(p0) # Degrees of freedom

fit_parameters, covariance_matrix, info, msg, success \
    = leastsq(func_res, p0, args=(x,y), full_output=True)

sum_squares_residuals = sum(info["fvec"]*info["fvec"])
sum_squares_mean_dev = sum((y - numpy.mean(y))**2)

# The errors for each parameter are obtained by multiplying the covariance matrix by the residual
# variance (= sum_squares_residuals / dof).
errors = []
for i in range(len(covariance_matrix)):
    errors.append(numpy.sqrt(covariance_matrix[i,i]*sum_squares_residuals/dof))

print("**Regression results for file \"{}\"**".format(sys.argv[1]))
print()

print("Data (x, y, yfit)")
print("=================")
for n in range(len(x)):
    print("{}, {}, {}".format(x[n], y[n], y[n] - info["fvec"][n]))
print()

print("Optimized parameters")
print("====================")
for n in range(len(fit_parameters)):
    print("{} +/- {}".format(fit_parameters[n], errors[n]))
print()

print("Regression data")
print("===============")

# See leastsq documentation for descriptions of flags.
print("Flag: {}".format(success))

print("Std Deviation of residuals: {}".format(numpy.sqrt(sum_squares_residuals/dof)))
print("chi2 (sum square residuals): {}".format(sum_squares_residuals))

# Ideally, (reduced chi2)/(std dev of measurement) = 1.
print("Reduced chi2 (chi2/dof): {}".format(sum_squares_residuals/dof))
print("R2 = {}".format(1 - sum_squares_residuals/sum_squares_mean_dev))
print("Adjusted R2 = {}".format(1 - (sum_squares_residuals/dof)/(sum_squares_mean_dev/(len(x)-1))))
print("Covariance matrix:")
print(covariance_matrix*sum_squares_residuals/dof)
print("Residuals:")
print(info["fvec"])
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2008 JAILLET Simon - CrysaLEAD - www.crysalead.fr
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsability of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# garantees and support are strongly adviced to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
#
##############################################################################
{
    'name': 'France - Accounting',
    'version': '1.1',
    'author': 'OpenERP SA',
    'website': 'http://www.openerp.com',
    'category': 'Localization/Account Charts',
    'description': """
This is the module to manage the accounting chart for France in OpenERP.
========================================================================

This module applies to companies based in France mainland. It doesn't apply to
companies based in the DOM-TOMs (Guadeloupe, Martinique, Guyane, Réunion, Mayotte).

This localisation module creates the VAT taxes of type 'tax included' for purchases
(it is notably required when you use the module 'hr_expense'). Beware that these
'tax included' VAT taxes are not managed by the fiscal positions provided by this
module (because it is complex to manage both 'tax excluded' and 'tax included'
scenarios in fiscal positions).

This localisation module doesn't properly handle the scenario when a France-mainland
company sells services to a company based in the DOMs. We could manage it in the
fiscal positions, but it would require to differentiate between 'product' VAT taxes
and 'service' VAT taxes. We consider that it is too 'heavy' to have this by default
in l10n_fr; companies that sell services to DOM-based companies should update the
configuration of their taxes and fiscal positions manually.

**Credits:** Sistheo, Zeekom, CrysaLEAD, Akretion and Camptocamp.
""",
    'depends': ['base_iban', 'account', 'account_chart', 'base_vat', 'l10n_fr_rib'],
    'data': [
        'views/report_l10nfrbilan.xml',
        'views/report_l10nfrresultat.xml',
        'l10n_fr_reports.xml',
        'fr_report.xml',
        'plan_comptable_general.xml',
        'l10n_fr_view.xml',
        'l10n_fr_wizard.xml',
        'fr_pcg_taxes.xml',
        'fr_tax.xml',
        'fr_fiscal_templates.xml',
        'security/ir.model.access.csv',
        'wizard/fr_report_bilan_view.xml',
        'wizard/fr_report_compute_resultant_view.xml',
    ],
    'test': ['test/l10n_fr_report.yml'],
    'demo': [],
    'auto_install': False,
    'installable': True,
    'images': ['images/config_chart_l10n_fr.jpeg','images/l10n_fr_chart.jpeg'],
}

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
<commit_msg>[IMP] l10n_fr: remove dependency on l10n_fr_rib<commit_after># -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2008 JAILLET Simon - CrysaLEAD - www.crysalead.fr
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsability of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# garantees and support are strongly adviced to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
#
##############################################################################
{
    'name': 'France - Accounting',
    'version': '1.1',
    'author': 'OpenERP SA',
    'website': 'http://www.openerp.com',
    'category': 'Localization/Account Charts',
    'description': """
This is the module to manage the accounting chart for France in OpenERP.
========================================================================

This module applies to companies based in France mainland. It doesn't apply to
companies based in the DOM-TOMs (Guadeloupe, Martinique, Guyane, Réunion, Mayotte).

This localisation module creates the VAT taxes of type 'tax included' for purchases
(it is notably required when you use the module 'hr_expense'). Beware that these
'tax included' VAT taxes are not managed by the fiscal positions provided by this
module (because it is complex to manage both 'tax excluded' and 'tax included'
scenarios in fiscal positions).

This localisation module doesn't properly handle the scenario when a France-mainland
company sells services to a company based in the DOMs. We could manage it in the
fiscal positions, but it would require to differentiate between 'product' VAT taxes
and 'service' VAT taxes. We consider that it is too 'heavy' to have this by default
in l10n_fr; companies that sell services to DOM-based companies should update the
configuration of their taxes and fiscal positions manually.

**Credits:** Sistheo, Zeekom, CrysaLEAD, Akretion and Camptocamp.
""",
    'depends': ['base_iban', 'account', 'account_chart', 'base_vat'],
    'data': [
        'views/report_l10nfrbilan.xml',
        'views/report_l10nfrresultat.xml',
        'l10n_fr_reports.xml',
        'fr_report.xml',
        'plan_comptable_general.xml',
        'l10n_fr_view.xml',
        'l10n_fr_wizard.xml',
        'fr_pcg_taxes.xml',
        'fr_tax.xml',
        'fr_fiscal_templates.xml',
        'security/ir.model.access.csv',
        'wizard/fr_report_bilan_view.xml',
        'wizard/fr_report_compute_resultant_view.xml',
    ],
    'test': ['test/l10n_fr_report.yml'],
    'demo': [],
    'auto_install': False,
    'installable': True,
    'images': ['images/config_chart_l10n_fr.jpeg','images/l10n_fr_chart.jpeg'],
}

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
<|endoftext|>


<commit_before>from django.conf import settings
from django.contrib.sites import models as site_models
from django.core.mail.message import EmailMultiAlternatives
from django.template import Context
from django.template.loader import select_template
from django.utils import translation

from . import mixins

class EmailBase:
    site_id = 1
    object = None
    template_name = None
    fallback_language = 'en'
    for_moderator = False

    def get_site(self):
        return site_models.Site.objects.get(pk=self.site_id)

    def get_host(self):
        site = self.get_site()
        ssl_enabled = True
        if site.domain.startswith('localhost:'):
            ssl_enabled = False

        url = 'http{ssl_flag}://{domain}'.format(
            ssl_flag='s' if ssl_enabled else '',
            domain=site.domain,
        )
        return url

    def get_context(self):
        object_context_key = self.object.__class__.__name__.lower()
        return Context({
            'email': self,
            'site': self.get_site(),
            object_context_key: self.object
        })

    def get_receivers(self):
        return []

    def get_attachments(self):
        return []

    def get_languages(self, receiver):
        return [translation.get_language(), self.fallback_language]

    @classmethod
    def send(cls, object, *args, **kwargs):
        return cls().dispatch(object, *args, **kwargs)

    def render(self, template_name, context):
        languages = self.get_languages(context['receiver'])
        template = select_template([
            '{}.{}.email'.format(template_name, lang)
            for lang in languages
        ])

        # Get the actually chosen language from the template name
        language = template.template.name.split('.', 2)[-2]

        with translation.override(language):
            parts = []
            for part_type in ('subject', 'txt', 'html'):
                context.update({'part_type': part_type})
                parts.append(template.render(context))
                context.pop()

        return tuple(parts)

    def dispatch(self, object, *args, **kwargs):
        self.object = object
        self.kwargs = kwargs
        receivers = self.get_receivers()
        context = self.get_context()
        context.update(kwargs)
        attachments = self.get_attachments()
        template = self.template_name

        mails = []
        for receiver in receivers:
            context.update({'receiver': receiver})
            (subject, text, html) = self.render(template, context)
            context.pop()

            if hasattr(receiver, 'email'):
                to_address = receiver.email
            else:
                to_address = receiver

            mail = EmailMultiAlternatives(
                subject=subject.strip(),
                body=text,
                from_email=settings.DEFAULT_FROM_EMAIL,
                to=[to_address],
            )

            if len(attachments) > 0:
                mail.mixed_subtype = 'related'

                for attachment in attachments:
                    mail.attach(attachment)

            mail.attach_alternative(html, 'text/html')
            mail.send()
            mails.append(mail)
        return mails

class Email(mixins.PlatformEmailMixin, EmailBase):
    pass

class ExternalNotification(Email):
    email_attr_name = 'email'

    def get_receivers(self):
        return [getattr(self.object, self.email_attr_name)]

class UserNotification(Email):
    user_attr_name = 'creator'

    def get_receivers(self):
        return [getattr(self.object, self.user_attr_name)]

class ModeratorNotification(Email):
    def get_receivers(self):
        return self.object.project.moderators.all()

class InitiatorNotification(Email):
    def get_receivers(self):
        return self.object.organisation.initiators.all()
<commit_msg>Add reply_to<commit_after>from django.conf import settings
from django.contrib.sites import models as site_models
from django.core.mail.message import EmailMultiAlternatives
from django.template import Context
from django.template.loader import select_template
from django.utils import translation

from . import mixins

class EmailBase:
    site_id = 1
    object = None
    template_name = None
    fallback_language = 'en'
    for_moderator = False

    def get_reply_to(self):
        return []

    def get_site(self):
        return site_models.Site.objects.get(pk=self.site_id)

    def get_host(self):
        site = self.get_site()
        ssl_enabled = True
        if site.domain.startswith('localhost:'):
            ssl_enabled = False

        url = 'http{ssl_flag}://{domain}'.format(
            ssl_flag='s' if ssl_enabled else '',
            domain=site.domain,
        )
        return url

    def get_context(self):
        object_context_key = self.object.__class__.__name__.lower()
        return Context({
            'email': self,
            'site': self.get_site(),
            object_context_key: self.object
        })

    def get_receivers(self):
        return []

    def get_attachments(self):
        return []

    def get_languages(self, receiver):
        return [translation.get_language(), self.fallback_language]

    @classmethod
    def send(cls, object, *args, **kwargs):
        return cls().dispatch(object, *args, **kwargs)

    def render(self, template_name, context):
        languages = self.get_languages(context['receiver'])
        template = select_template([
            '{}.{}.email'.format(template_name, lang)
            for lang in languages
        ])

        # Get the actually chosen language from the template name
        language = template.template.name.split('.', 2)[-2]

        with translation.override(language):
            parts = []
            for part_type in ('subject', 'txt', 'html'):
                context.update({'part_type': part_type})
                parts.append(template.render(context))
                context.pop()

        return tuple(parts)

    def dispatch(self, object, *args, **kwargs):
        self.object = object
        self.kwargs = kwargs
        receivers = self.get_receivers()
        context = self.get_context()
        context.update(kwargs)
        attachments = self.get_attachments()
        template = self.template_name

        mails = []
        for receiver in receivers:
            context.update({'receiver': receiver})
            (subject, text, html) = self.render(template, context)
            context.pop()

            if hasattr(receiver, 'email'):
                to_address = receiver.email
            else:
                to_address = receiver

            mail = EmailMultiAlternatives(
                subject=subject.strip(),
                body=text,
                from_email=settings.DEFAULT_FROM_EMAIL,
                to=[to_address],
                reply_to=self.get_reply_to()
            )

            if len(attachments) > 0:
                mail.mixed_subtype = 'related'

                for attachment in attachments:
                    mail.attach(attachment)

            mail.attach_alternative(html, 'text/html')
            mail.send()
            mails.append(mail)
        return mails

class Email(mixins.PlatformEmailMixin, EmailBase):
    pass

class ExternalNotification(Email):
    email_attr_name = 'email'

    def get_receivers(self):
        return [getattr(self.object, self.email_attr_name)]

class UserNotification(Email):
    user_attr_name = 'creator'

    def get_receivers(self):
        return [getattr(self.object, self.user_attr_name)]

class ModeratorNotification(Email):
    def get_receivers(self):
        return self.object.project.moderators.all()

class InitiatorNotification(Email):
    def get_receivers(self):
        return self.object.organisation.initiators.all()
<|endoftext|>


<commit_before>from django import template

register = template.Library()

def addressblock(address):
    """Output an address as a HTML formatted text block"""
    return {"address" : address}

register.inclusion_tag('contact/_addressblock.html')(addressblock)

def contact_for_user(user):
    if user.contact_set.count() > 0:
        return user.contact_set.all()[0]
    else:
        return None

register.filter('contact_for_user')(contact_for_user)
<commit_msg>fixing an edge case for contact_for_user tag<commit_after>from django import template

register = template.Library()

def addressblock(address):
    """Output an address as a HTML formatted text block"""
    return {"address" : address}

register.inclusion_tag('contact/_addressblock.html')(addressblock)

def contact_for_user(user):
    if not user.is_anonymous() and user.contact_set.count() > 0:
        return user.contact_set.all()[0]
    return None

register.filter('contact_for_user')(contact_for_user)
<|endoftext|>


<commit_before># Generated by Django 2.0 on 2018-01-09 05:03

from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ("schedule", "0008_gfk_index"),
    ]

    operations = []
<commit_msg>fix black code style<commit_after># Generated by Django 2.0 on 2018-01-09 05:03

from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [("schedule", "0008_gfk_index")]

    operations = []
<|endoftext|>


<commit_before>import unittest
from scrapy.utils.serialization import serialize, unserialize, serialize_funcs

class SerializationTest(unittest.TestCase):
    def test_string_serialization(self):
        """Test simple string serialization"""

        s = "string to serialize"
        for format in serialize_funcs.iterkeys():
            self.assertEqual(s, unserialize(serialize(s)))

    def test_dict_serialization(self):
        """Test dict serialization"""

        # using only string keys/values since it's the only data type that
        # works with all serializers
        d = {'one': 'item one', 'two': 'item two'}
        for format in serialize_funcs.iterkeys():
            self.assertEqual(d, unserialize(serialize(d)))

if __name__ == "__main__":
    unittest.main()
<commit_msg>skip serialization tests if simplejson module is not available<commit_after>from twisted.trial import unittest

class SerializationTest(unittest.TestCase):

    def setUp(self):
        try:
            import simplejson
        except ImportError, e:
            raise unittest.SkipTest(e)

    def test_string_serialization(self):
        """Test simple string serialization"""
        from scrapy.utils.serialization import serialize, unserialize, serialize_funcs

        s = "string to serialize"
        for format in serialize_funcs.iterkeys():
            self.assertEqual(s, unserialize(serialize(s)))

    def test_dict_serialization(self):
        """Test dict serialization"""
        from scrapy.utils.serialization import serialize, unserialize, serialize_funcs

        # using only string keys/values since it's the only data type that
        # works with all serializers
        d = {'one': 'item one', 'two': 'item two'}
        for format in serialize_funcs.iterkeys():
            self.assertEqual(d, unserialize(serialize(d)))

if __name__ == "__main__":
    unittest.main()
<|endoftext|>


<commit_before><commit_msg>corect top level package export<commit_after><|endoftext|>


<commit_before># -*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from osv import fields, osv
from tools.translate import _
import tools

class account_move_journal(osv.osv_memory):
    _name = "account.move.journal"
    _description = "Move journal"

    def _get_period(self, cr, uid, context={}):
        """
        Return  default account period value
        """
        ids = self.pool.get('account.period').find(cr, uid, context=context)
        period_id = False
        if len(ids):
            period_id = ids[0]
        return period_id

    def _get_journal(self, cr, uid, context={}):
        """
        Return journal based on the journal type
        """

        journal_id = False

        journal_pool = self.pool.get('account.journal')
        if context.get('journal_type', False):
            jids = journal_pool.search(cr, uid, [('type','=', context.get('journal_type'))])
            journal_id = jids[0]

        return journal_id

    def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
        """
        Returns views and fields for current model where view will depend on {view_type}.
        @param cr: A database cursor
        @param user: ID of the user currently logged in
        @param view_id: list of fields, which required to read signatures
        @param view_type: defines a view type. it can be one of (form, tree, graph, calender, gantt, search, mdx)
        @param context: context arguments, like lang, time zone
        @param toolbar: contains a list of reports, wizards, and links related to current model

        @return: Returns a dict that contains definition for fields, views, and toolbars
        """

        res = super(account_move_journal, self).fields_view_get(cr, uid, view_id, view_type, context, toolbar, submenu)

        if not view_id:
            return res

        period_pool = self.pool.get('account.period')
        journal_pool = self.pool.get('account.journal')

        journal_id = self._get_journal(cr, uid, context)
        period_id = self._get_period(cr, uid, context)

        journal = False
        if journal_id:
            journal = journal_pool.read(cr, uid, [journal_id], ['name'])[0]['name']
        else:
            journal = "All"

        period = False
        if period_id:
            period = period_pool.browse(cr, uid, [period_id], ['name'])[0]['name']

        view = """<?xml version="1.0" encoding="utf-8"?>
        <form string="Standard entries">
            <separator string="Open Journal Items !" colspan="4"/>
            <group colspan="4" >
                <label width="300" string="Journal : %s"/>
                <newline/>
                <label width="300" string="Period :  %s"/>
            </group>
            <group colspan="4" col="4">
                <label string ="" colspan="2"/>
                <button icon="terp-gtk-go-back-rtl" string="Ok" name="action_open_window" type="object"/>
            </group>
        </form>""" % (str(journal), str(period))

        res.update({
            'arch':view
        })
        return res

    def action_open_window(self, cr, uid, ids, context=None):
        """
        This function Open action move line window on given period and  Journal/Payment Mode
        @param cr: the current row, from the database cursor,
        @param uid: the current user’s ID for security checks,
        @param ids: account move journal’s ID or list of IDs
        @return: dictionary of Open action move line window on given period and  Journal/Payment Mode
        """

        period_pool = self.pool.get('account.journal.period')
        data_pool = self.pool.get('ir.model.data')
        journal_pool = self.pool.get('account.journal')

        if context is None:
            context = {}

        journal_id = self._get_journal(cr, uid, context)
        period_id = self._get_period(cr, uid, context)

        name = _("Journal Items")
        if journal_id:
            ids = period_pool.search(cr, uid, [('journal_id', '=', journal_id), ('period_id', '=', period_id)], context=context)

            if not len(ids):
                journal = journal_pool.browse(cr, uid, journal_id)
                period = self.pool.get('account.period').browse(cr, uid, period_id)

                name = journal.name
                state = period.state

                if state == 'done':
                    raise osv.except_osv(_('UserError'), _('This period is already closed !'))

                company = period.company_id.id
                res = {
                    'name': name,
                    'period_id': period_id,
                    'journal_id': journal_id,
                    'company_id': company
                }
                period_pool.create(cr, uid, res,context=context)

            ids = period_pool.search(cr, uid, [('journal_id', '=', journal_id), ('period_id', '=', period_id)],context=context)
            period = period_pool.browse(cr, uid, ids[0], context=context)
            name = (period.journal_id.code or '') + ':' + (period.period_id.code or '')

        result = data_pool._get_id(cr, uid, 'account', 'view_account_move_line_filter')
        res_id = data_pool.browse(cr, uid, result, context=context).res_id

        return {
#            'domain': str([('journal_id', '=', journal_id), ('period_id', '=', period_id)]),
            'name': name,
            'view_type': 'form',
            'view_mode': 'tree,graph,form',
            'res_model': 'account.move.line',
            'view_id': False,
            'context': "{'visible_id':%s, 'journal_id': %d, 'search_default_journal_id':%d, 'search_default_period_id':%d}" % (journal_id, journal_id, journal_id, period_id),
            'type': 'ir.actions.act_window',
            'search_view_id': res_id
        }

account_move_journal()

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
<commit_msg>[FIX] account: the encoding entries by line wasn't working if there was no journal of the type passed in context<commit_after># -*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from osv import fields, osv
from tools.translate import _
import tools

class account_move_journal(osv.osv_memory):
    _name = "account.move.journal"
    _description = "Move journal"

    def _get_period(self, cr, uid, context={}):
        """
        Return  default account period value
        """
        ids = self.pool.get('account.period').find(cr, uid, context=context)
        period_id = False
        if len(ids):
            period_id = ids[0]
        return period_id

    def _get_journal(self, cr, uid, context={}):
        """
        Return journal based on the journal type
        """

        journal_id = False

        journal_pool = self.pool.get('account.journal')
        if context.get('journal_type', False):
            jids = journal_pool.search(cr, uid, [('type','=', context.get('journal_type'))])
            if not jids:
                raise osv.except_osv(_('Configuration Error !'), _('Can\'t find any account journal of %s type for this company.\n\nYou can create one in the menu: \nConfiguration\Financial Accounting\Accounts\Journals.' % (context.get('journal_type'))))
            journal_id = jids[0]

        return journal_id

    def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
        """
        Returns views and fields for current model where view will depend on {view_type}.
        @param cr: A database cursor
        @param user: ID of the user currently logged in
        @param view_id: list of fields, which required to read signatures
        @param view_type: defines a view type. it can be one of (form, tree, graph, calender, gantt, search, mdx)
        @param context: context arguments, like lang, time zone
        @param toolbar: contains a list of reports, wizards, and links related to current model

        @return: Returns a dict that contains definition for fields, views, and toolbars
        """

        res = super(account_move_journal, self).fields_view_get(cr, uid, view_id, view_type, context, toolbar, submenu)

        if not view_id:
            return res

        period_pool = self.pool.get('account.period')
        journal_pool = self.pool.get('account.journal')

        journal_id = self._get_journal(cr, uid, context)
        period_id = self._get_period(cr, uid, context)

        journal = False
        if journal_id:
            journal = journal_pool.read(cr, uid, [journal_id], ['name'])[0]['name']
        else:
            journal = "All"

        period = False
        if period_id:
            period = period_pool.browse(cr, uid, [period_id], ['name'])[0]['name']

        view = """<?xml version="1.0" encoding="utf-8"?>
        <form string="Standard entries">
            <separator string="Open Journal Items !" colspan="4"/>
            <group colspan="4" >
                <label width="300" string="Journal : %s"/>
                <newline/>
                <label width="300" string="Period :  %s"/>
            </group>
            <group colspan="4" col="4">
                <label string ="" colspan="2"/>
                <button icon="terp-gtk-go-back-rtl" string="Ok" name="action_open_window" type="object"/>
            </group>
        </form>""" % (str(journal), str(period))

        res.update({
            'arch':view
        })
        return res

    def action_open_window(self, cr, uid, ids, context=None):
        """
        This function Open action move line window on given period and  Journal/Payment Mode
        @param cr: the current row, from the database cursor,
        @param uid: the current user’s ID for security checks,
        @param ids: account move journal’s ID or list of IDs
        @return: dictionary of Open action move line window on given period and  Journal/Payment Mode
        """

        period_pool = self.pool.get('account.journal.period')
        data_pool = self.pool.get('ir.model.data')
        journal_pool = self.pool.get('account.journal')

        if context is None:
            context = {}

        journal_id = self._get_journal(cr, uid, context)
        period_id = self._get_period(cr, uid, context)

        name = _("Journal Items")
        if journal_id:
            ids = period_pool.search(cr, uid, [('journal_id', '=', journal_id), ('period_id', '=', period_id)], context=context)

            if not len(ids):
                journal = journal_pool.browse(cr, uid, journal_id)
                period = self.pool.get('account.period').browse(cr, uid, period_id)

                name = journal.name
                state = period.state

                if state == 'done':
                    raise osv.except_osv(_('UserError'), _('This period is already closed !'))

                company = period.company_id.id
                res = {
                    'name': name,
                    'period_id': period_id,
                    'journal_id': journal_id,
                    'company_id': company
                }
                period_pool.create(cr, uid, res,context=context)

            ids = period_pool.search(cr, uid, [('journal_id', '=', journal_id), ('period_id', '=', period_id)],context=context)
            period = period_pool.browse(cr, uid, ids[0], context=context)
            name = (period.journal_id.code or '') + ':' + (period.period_id.code or '')

        result = data_pool._get_id(cr, uid, 'account', 'view_account_move_line_filter')
        res_id = data_pool.browse(cr, uid, result, context=context).res_id

        return {
#            'domain': str([('journal_id', '=', journal_id), ('period_id', '=', period_id)]),
            'name': name,
            'view_type': 'form',
            'view_mode': 'tree,graph,form',
            'res_model': 'account.move.line',
            'view_id': False,
            'context': "{'visible_id':%s, 'journal_id': %d, 'search_default_journal_id':%d, 'search_default_period_id':%d}" % (journal_id, journal_id, journal_id, period_id),
            'type': 'ir.actions.act_window',
            'search_view_id': res_id
        }

account_move_journal()

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
<|endoftext|>


<commit_before># -*- encoding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
#    $Id$
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    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 General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

import wizard
import pooler

class wizard_account_chart(wizard.interface):
    _account_chart_arch = '''<?xml version="1.0"?>
    <form string="Account charts">
        <field name="fiscalyear"/>
        <label align="0.7" colspan="6" string="(If you do not select Fiscal year it will take all open fiscal years)"/>
        <field name="target_move"/>
    </form>'''

    _account_chart_fields = {
            'fiscalyear': {
                'string': 'Fiscal year',
                'type': 'many2one',
                'relation': 'account.fiscalyear',
                'help': 'Keep empty for all open fiscal year',
        },
            'target_move': {
                'string': 'Target Moves',
                'type': 'selection',
                'selection': [('all','All Entries'),('posted_only','All Posted Entries')],
                'required': True,
                'default': lambda *a:"all",
        },
    }

    def _get_defaults(self, cr, uid, data, context):
        fiscalyear_obj = pooler.get_pool(cr.dbname).get('account.fiscalyear')
        data['form']['fiscalyear'] = fiscalyear_obj.find(cr, uid)
        return data['form']

    def _account_chart_open_window(self, cr, uid, data, context):
        mod_obj = pooler.get_pool(cr.dbname).get('ir.model.data')
        act_obj = pooler.get_pool(cr.dbname).get('ir.actions.act_window')

        result = mod_obj._get_id(cr, uid, 'account', 'action_account_tree')
        id = mod_obj.read(cr, uid, [result], ['res_id'])[0]['res_id']
        result = act_obj.read(cr, uid, [id], context=context)[0]
        result['context'] = str({'fiscalyear': data['form']['fiscalyear'],'target_move':data['form']['target_move']})
        if data['form']['fiscalyear']:
            result['name']+=':'+pooler.get_pool(cr.dbname).get('account.fiscalyear').read(cr,uid,[data['form']['fiscalyear']])[0]['code']
        return result

    states = {
        'init': {
            'actions': [_get_defaults],
            'result': {'type': 'form', 'arch':_account_chart_arch, 'fields':_account_chart_fields, 'state': [('end', 'Cancel'), ('open', 'Open Charts')]}
        },
        'open': {
            'actions': [],
            'result': {'type': 'action', 'action':_account_chart_open_window, 'state':'end'}
        }
    }
wizard_account_chart('account.chart')

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:

<commit_msg>[FIX] Account : Charts of accounts - target move options corrected<commit_after># -*- encoding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
#    $Id$
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    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 General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

import wizard
import pooler

class wizard_account_chart(wizard.interface):
    _account_chart_arch = '''<?xml version="1.0"?>
    <form string="Account charts">
        <field name="fiscalyear"/>
        <label align="0.7" colspan="6" string="(If you do not select Fiscal year it will take all open fiscal years)"/>
        <field name="target_move"/>
    </form>'''

    _account_chart_fields = {
            'fiscalyear': {
                'string': 'Fiscal year',
                'type': 'many2one',
                'relation': 'account.fiscalyear',
                'help': 'Keep empty for all open fiscal year',
        },
            'target_move': {
                'string': 'Target Moves',
                'type': 'selection',
                'selection': [('all','All Entries'),('posted','All Posted Entries')],
                'required': True,
                'default': lambda *a:"all",
        },
    }

    def _get_defaults(self, cr, uid, data, context):
        fiscalyear_obj = pooler.get_pool(cr.dbname).get('account.fiscalyear')
        data['form']['fiscalyear'] = fiscalyear_obj.find(cr, uid)
        return data['form']

    def _account_chart_open_window(self, cr, uid, data, context):
        mod_obj = pooler.get_pool(cr.dbname).get('ir.model.data')
        act_obj = pooler.get_pool(cr.dbname).get('ir.actions.act_window')

        result = mod_obj._get_id(cr, uid, 'account', 'action_account_tree')
        id = mod_obj.read(cr, uid, [result], ['res_id'])[0]['res_id']
        result = act_obj.read(cr, uid, [id], context=context)[0]
        result['context'] = str({'fiscalyear': data['form']['fiscalyear'],'state':data['form']['target_move']})
        if data['form']['fiscalyear']:
            result['name']+=':'+pooler.get_pool(cr.dbname).get('account.fiscalyear').read(cr,uid,[data['form']['fiscalyear']])[0]['code']
        return result

    states = {
        'init': {
            'actions': [_get_defaults],
            'result': {'type': 'form', 'arch':_account_chart_arch, 'fields':_account_chart_fields, 'state': [('end', 'Cancel'), ('open', 'Open Charts')]}
        },
        'open': {
            'actions': [],
            'result': {'type': 'action', 'action':_account_chart_open_window, 'state':'end'}
        }
    }
wizard_account_chart('account.chart')

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:

<|endoftext|>


<commit_before>import operator
import re
from pprint import pprint

from systextil.queries.base import SMountQuery

from utils.functions.queries import debug_cursor_execute

def query_endereco(tipo):
    where_tipo = []
    if tipo == 'ES':
        where_tipo = [
            f"REGEXP_LIKE(e.COD_ENDERECO, '^1[ABCDEFGH][0123456789]{{4}}$')",
        ]
    elif tipo == 'NE':
        where_tipo = [
            "e.COD_ENDERECO LIKE '1%'",
            f"NOT REGEXP_LIKE(e.COD_ENDERECO, '^1[ABCDEFGH][0123456789]{{4}}$')",
        ]
    elif tipo == 'IN':
        where_tipo = [
            "e.COD_ENDERECO LIKE '1%'",
        ]
    elif tipo == 'EX':
        where_tipo = [
            "e.COD_ENDERECO NOT LIKE '1%'",
        ]
    elif tipo != 'TO':
        where_tipo = [
            f"REGEXP_LIKE(e.COD_ENDERECO, '^1{tipo}[0123456789]{{4}}$')",
        ]
    data = SMountQuery(
        fields=[
          "e.COD_ENDERECO end",
          "e.ROTA",
        ],
        table="ENDR_013 e",
        where=where_tipo,
        order=[
          f"e.COD_ENDERECO",
        ],
    ).oquery.debug_execute()

    for row in data:
        try:
            rua = re.search('^[0-9]([A-Z]+)[0-9]+', row['end']).group(1)
        except AttributeError:
            rua = '#'
        if rua in ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']:
            row['order'] = 1
            row['area'] = 'Estantes'
        elif rua.startswith('Q'):
            row['order'] = 2
            row['area'] = 'Quarto andar'
        elif (
                rua.startswith('S') or
                rua.startswith('Y')
              ):
            row['order'] = 3
            row['area'] = 'Externo'
        else:
            row['order'] = 4
            row['area'] = 'Indefinido'

    data.sort(key=operator.itemgetter('order', 'end'))

    return data

def endereco_split(endereco):
    """Split endereço em espaco, bloco, andar e ap"""
    try:
        busca = re.search('^([0-9])([A-Z]+)([0-9]{2})([0-9]{2})$', endereco)
    except AttributeError:
        return None, None, None
    return busca.group(1), busca.group(2), busca.group(3), busca.group(4)

def calc_rota(endereco):
    ruas = {
        'A': 'AB',
        'B': 'AB',
        'C': 'CD',
        'D': 'CD',
        'E': 'EF',
        'F': 'EF',
        'G': 'GH',
        'H': 'GH',
    }
    espaco, bloco, andar, ap = endereco_split(endereco)
    if bloco in ruas.keys():
        iap = int(ap)
        irota = iap//2
        rua = ruas[bloco]
        rota = f'{espaco}{rua}{irota:02}'
    else:
        rota = f'{espaco}{bloco}'
    return rota

def add_endereco(cursor, endereco):
    """Cria endereco no banco de dados
    Recebe: cursor e endereco a ser criado
    Retorna: Se sucesso, None, senão, mensagem de erro
    """
    rota = calc_rota(endereco)
    sql = f"""
        INSERT INTO SYSTEXTIL.ENDR_013
        (RUA, BOX, ALTURA, COD_ENDERECO, EMPRESA, PROCESSO, SITUACAO, TIPO_ENDERECO, ROTA)
        VALUES(NULL, NULL, NULL, '{endereco}', 1, 1, '1', '1', '{rota}')
    """
    try:
        debug_cursor_execute(cursor, sql)
    except Exception as e:
        return repr(e)
<commit_msg>função endereco_split refeita<commit_after>import operator
import re
from pprint import pprint

from systextil.queries.base import SMountQuery

from utils.functions.queries import debug_cursor_execute

def query_endereco(tipo):
    where_tipo = []
    if tipo == 'ES':
        where_tipo = [
            f"REGEXP_LIKE(e.COD_ENDERECO, '^1[ABCDEFGH][0123456789]{{4}}$')",
        ]
    elif tipo == 'NE':
        where_tipo = [
            "e.COD_ENDERECO LIKE '1%'",
            f"NOT REGEXP_LIKE(e.COD_ENDERECO, '^1[ABCDEFGH][0123456789]{{4}}$')",
        ]
    elif tipo == 'IN':
        where_tipo = [
            "e.COD_ENDERECO LIKE '1%'",
        ]
    elif tipo == 'EX':
        where_tipo = [
            "e.COD_ENDERECO NOT LIKE '1%'",
        ]
    elif tipo != 'TO':
        where_tipo = [
            f"REGEXP_LIKE(e.COD_ENDERECO, '^1{tipo}[0123456789]{{4}}$')",
        ]
    data = SMountQuery(
        fields=[
          "e.COD_ENDERECO end",
          "e.ROTA",
        ],
        table="ENDR_013 e",
        where=where_tipo,
        order=[
          f"e.COD_ENDERECO",
        ],
    ).oquery.debug_execute()

    for row in data:
        try:
            rua = re.search('^[0-9]([A-Z]+)[0-9]+', row['end']).group(1)
        except AttributeError:
            rua = '#'
        if rua in ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']:
            row['order'] = 1
            row['area'] = 'Estantes'
        elif rua.startswith('Q'):
            row['order'] = 2
            row['area'] = 'Quarto andar'
        elif (
                rua.startswith('S') or
                rua.startswith('Y')
              ):
            row['order'] = 3
            row['area'] = 'Externo'
        else:
            row['order'] = 4
            row['area'] = 'Indefinido'

    data.sort(key=operator.itemgetter('order', 'end'))

    return data

def endereco_split(endereco):
    """Split endereço em espaco, bloco e apartamento; e este último em andar e coluna"""
    parts = {
        'espaco' : None,
        'bloco' : None,
        'apartamento' : None,
        'andar' : None,
        'coluna' : None,
    }
    try:
        end_parts = re.search('^([0-9])(.+)([0-9]+)$', endereco)
    except Exception:
        end_parts = None
    if end_parts:
        try:
            parts['espaco'] = end_parts.group(1)
            parts['bloco'] = end_parts.group(2)
            parts['apartamento'] = end_parts.group(3)
        except AttributeError:
            end_parts = None
    if end_parts:
        if parts['apartamento'] and len(parts['apartamento']) >= 4:
            try:
                ap_parts = re.search('^([0-9]+)([0-9]{2})$', parts['apartamento'])
                parts['andar'] = ap_parts.group(1)
                parts['coluna'] = ap_parts.group(2)
            except Exception:
                pass
    return parts

def calc_rota(endereco):
    ruas = {
        'A': 'AB',
        'B': 'AB',
        'C': 'CD',
        'D': 'CD',
        'E': 'EF',
        'F': 'EF',
        'G': 'GH',
        'H': 'GH',
    }
    parts = endereco_split(endereco)
    if parts['bloco']:
        icoluna = int(parts['coluna'])
        irota = icoluna//2
        rua = ruas[parts['bloco']]
        rota = f"{parts['espaco']}{rua}{irota:02}"
    else:
        rota = f"{parts['espaco']}{parts['bloco']}"
    return rota

def add_endereco(cursor, endereco):
    """Cria endereco no banco de dados
    Recebe: cursor e endereco a ser criado
    Retorna: Se sucesso, None, senão, mensagem de erro
    """
    rota = calc_rota(endereco)
    sql = f"""
        INSERT INTO SYSTEXTIL.ENDR_013
        (RUA, BOX, ALTURA, COD_ENDERECO, EMPRESA, PROCESSO, SITUACAO, TIPO_ENDERECO, ROTA)
        VALUES(NULL, NULL, NULL, '{endereco}', 1, 1, '1', '1', '{rota}')
    """
    try:
        debug_cursor_execute(cursor, sql)
    except Exception as e:
        return repr(e)
<|endoftext|>


<commit_before># Copyright 2021 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Keras-based TransformerEncoder block layer."""

import tensorflow as tf

@tf.keras.utils.register_keras_serializable(package="keras_nlp")
class TransformerEncoderBlock(tf.keras.layers.Layer):
  """TransformerEncoderBlock layer.

  This layer implements the Transformer Encoder from
  "Attention Is All You Need". (https://arxiv.org/abs/1706.03762),
  which combines a `tf.keras.layers.MultiHeadAttention` layer with a
  two-layer feedforward network.

  References:
    [Attention Is All You Need](https://arxiv.org/abs/1706.03762)
    [BERT: Pre-training of Deep Bidirectional Transformers for Language
     Understanding](https://arxiv.org/abs/1810.04805)
  """

  def __init__(self,
               num_attention_heads,
               inner_dim,
               inner_activation,
               output_range=None,
               kernel_initializer="glorot_uniform",
               bias_initializer="zeros",
               kernel_regularizer=None,
               bias_regularizer=None,
               activity_regularizer=None,
               kernel_constraint=None,
               bias_constraint=None,
               use_bias=True,
               norm_first=False,
               norm_epsilon=1e-12,
               output_dropout=0.0,
               attention_dropout=0.0,
               inner_dropout=0.0,
               attention_initializer=None,
               attention_axes=None,
               **kwargs):
    """Initializes `TransformerEncoderBlock`.

    Args:
      num_attention_heads: Number of attention heads.
      inner_dim: The output dimension of the first Dense layer in a two-layer
        feedforward network.
      inner_activation: The activation for the first Dense layer in a two-layer
        feedforward network.
      output_range: the sequence output range, [0, output_range) for slicing the
        target sequence. `None` means the target sequence is not sliced.
      kernel_initializer: Initializer for dense layer kernels.
      bias_initializer: Initializer for dense layer biases.
      kernel_regularizer: Regularizer for dense layer kernels.
      bias_regularizer: Regularizer for dense layer biases.
      activity_regularizer: Regularizer for dense layer activity.
      kernel_constraint: Constraint for dense layer kernels.
      bias_constraint: Constraint for dense layer kernels.
      use_bias: Whether to enable use_bias in attention layer. If set False,
        use_bias in attention layer is disabled.
      norm_first: Whether to normalize inputs to attention and intermediate
        dense layers. If set False, output of attention and intermediate dense
        layers is normalized.
      norm_epsilon: Epsilon value to initialize normalization layers.
      output_dropout: Dropout probability for the post-attention and output
        dropout.
      attention_dropout: Dropout probability for within the attention layer.
      inner_dropout: Dropout probability for the first Dense layer in a
        two-layer feedforward network.
      attention_initializer: Initializer for kernels of attention layers. If set
        `None`, attention layers use kernel_initializer as initializer for
        kernel.
      attention_axes: axes over which the attention is applied. `None` means
        attention over all axes, but batch, heads, and features.
      **kwargs: keyword arguments/
    """
    super().__init__(**kwargs)

    self._num_heads = num_attention_heads
    self._inner_dim = inner_dim
    self._inner_activation = inner_activation
    self._attention_dropout = attention_dropout
    self._attention_dropout_rate = attention_dropout
    self._output_dropout = output_dropout
    self._output_dropout_rate = output_dropout
    self._output_range = output_range
    self._kernel_initializer = tf.keras.initializers.get(kernel_initializer)
    self._bias_initializer = tf.keras.initializers.get(bias_initializer)
    self._kernel_regularizer = tf.keras.regularizers.get(kernel_regularizer)
    self._bias_regularizer = tf.keras.regularizers.get(bias_regularizer)
    self._activity_regularizer = tf.keras.regularizers.get(activity_regularizer)
    self._kernel_constraint = tf.keras.constraints.get(kernel_constraint)
    self._bias_constraint = tf.keras.constraints.get(bias_constraint)
    self._use_bias = use_bias
    self._norm_first = norm_first
    self._norm_epsilon = norm_epsilon
    self._inner_dropout = inner_dropout
    if attention_initializer:
      self._attention_initializer = tf.keras.initializers.get(
          attention_initializer)
    else:
      self._attention_initializer = self._kernel_initializer
    self._attention_axes = attention_axes

  def build(self, input_shape):
    if isinstance(input_shape, tf.TensorShape):
      input_tensor_shape = input_shape
    elif isinstance(input_shape, (list, tuple)):
      input_tensor_shape = tf.TensorShape(input_shape[0])
    else:
      raise ValueError(
          "The type of input shape argument is not supported, got: %s" %
          type(input_shape))
    einsum_equation = "abc,cd->abd"
    if len(input_tensor_shape.as_list()) > 3:
      einsum_equation = "...bc,cd->...bd"
    hidden_size = input_tensor_shape[-1]
    if hidden_size % self._num_heads != 0:
      raise ValueError(
          "The input size (%d) is not a multiple of the number of attention "
          "heads (%d)" % (hidden_size, self._num_heads))
    self._attention_head_size = int(hidden_size // self._num_heads)
    common_kwargs = dict(
        bias_initializer=self._bias_initializer,
        kernel_regularizer=self._kernel_regularizer,
        bias_regularizer=self._bias_regularizer,
        activity_regularizer=self._activity_regularizer,
        kernel_constraint=self._kernel_constraint,
        bias_constraint=self._bias_constraint)
    self._attention_layer = tf.keras.layers.MultiHeadAttention(
        num_heads=self._num_heads,
        key_dim=self._attention_head_size,
        dropout=self._attention_dropout,
        use_bias=self._use_bias,
        kernel_initializer=self._attention_initializer,
        attention_axes=self._attention_axes,
        name="self_attention",
        **common_kwargs)
    self._attention_dropout = tf.keras.layers.Dropout(rate=self._output_dropout)
    # Use float32 in layernorm for numeric stability.
    # It is probably safe in mixed_float16, but we haven't validated this yet.
    self._attention_layer_norm = (
        tf.keras.layers.LayerNormalization(
            name="self_attention_layer_norm",
            axis=-1,
            epsilon=self._norm_epsilon,
            dtype=tf.float32))
    self._intermediate_dense = tf.keras.layers.experimental.EinsumDense(
        einsum_equation,
        output_shape=(None, self._inner_dim),
        bias_axes="d",
        kernel_initializer=self._kernel_initializer,
        name="intermediate",
        **common_kwargs)
    policy = tf.keras.mixed_precision.global_policy()
    if policy.name == "mixed_bfloat16":
      # bfloat16 causes BERT with the LAMB optimizer to not converge
      # as well, so we use float32.
      # TODO(b/154538392): Investigate this.
      policy = tf.float32
    self._intermediate_activation_layer = tf.keras.layers.Activation(
        self._inner_activation, dtype=policy)
    self._inner_dropout_layer = tf.keras.layers.Dropout(
        rate=self._inner_dropout)
    self._output_dense = tf.keras.layers.experimental.EinsumDense(
        einsum_equation,
        output_shape=(None, hidden_size),
        bias_axes="d",
        name="output",
        kernel_initializer=self._kernel_initializer,
        **common_kwargs)
    self._output_dropout = tf.keras.layers.Dropout(rate=self._output_dropout)
    # Use float32 in layernorm for numeric stability.
    self._output_layer_norm = tf.keras.layers.LayerNormalization(
        name="output_layer_norm",
        axis=-1,
        epsilon=self._norm_epsilon,
        dtype=tf.float32)

    super(TransformerEncoderBlock, self).build(input_shape)

  def get_config(self):
    config = {
        "num_attention_heads":
            self._num_heads,
        "inner_dim":
            self._inner_dim,
        "inner_activation":
            self._inner_activation,
        "output_dropout":
            self._output_dropout_rate,
        "attention_dropout":
            self._attention_dropout_rate,
        "output_range":
            self._output_range,
        "kernel_initializer":
            tf.keras.initializers.serialize(self._kernel_initializer),
        "bias_initializer":
            tf.keras.initializers.serialize(self._bias_initializer),
        "kernel_regularizer":
            tf.keras.regularizers.serialize(self._kernel_regularizer),
        "bias_regularizer":
            tf.keras.regularizers.serialize(self._bias_regularizer),
        "activity_regularizer":
            tf.keras.regularizers.serialize(self._activity_regularizer),
        "kernel_constraint":
            tf.keras.constraints.serialize(self._kernel_constraint),
        "bias_constraint":
            tf.keras.constraints.serialize(self._bias_constraint),
        "use_bias":
            self._use_bias,
        "norm_first":
            self._norm_first,
        "norm_epsilon":
            self._norm_epsilon,
        "inner_dropout":
            self._inner_dropout,
        "attention_initializer":
            tf.keras.initializers.serialize(self._attention_initializer),
        "attention_axes": self._attention_axes,
    }
    base_config = super(TransformerEncoderBlock, self).get_config()
    return dict(list(base_config.items()) + list(config.items()))

  def call(self, inputs):
    """Transformer self-attention encoder block call.

    Args:
      inputs: a single tensor or a list of tensors.
        `input tensor` as the single sequence of embeddings.
        [`input tensor`, `attention mask`] to have the additional attention
          mask.
        [`query tensor`, `key value tensor`, `attention mask`] to have separate
          input streams for the query, and key/value to the multi-head
          attention.

    Returns:
      An ouput tensor with the same dimensions as input/query tensor.
    """
    if isinstance(inputs, (list, tuple)):
      if len(inputs) == 2:
        input_tensor, attention_mask = inputs
        key_value = None
      elif len(inputs) == 3:
        input_tensor, key_value, attention_mask = inputs
      else:
        raise ValueError("Unexpected inputs to %s with length at %d" %
                         (self.__class__, len(inputs)))
    else:
      input_tensor, key_value, attention_mask = (inputs, None, None)

    if self._output_range:
      if self._norm_first:
        source_tensor = input_tensor[:, 0:self._output_range, :]
        input_tensor = self._attention_layer_norm(input_tensor)
        if key_value is not None:
          key_value = self._attention_layer_norm(key_value)
      target_tensor = input_tensor[:, 0:self._output_range, :]
      if attention_mask is not None:
        attention_mask = attention_mask[:, 0:self._output_range, :]
    else:
      if self._norm_first:
        source_tensor = input_tensor
        input_tensor = self._attention_layer_norm(input_tensor)
        if key_value is not None:
          key_value = self._attention_layer_norm(key_value)
      target_tensor = input_tensor

    if key_value is None:
      key_value = input_tensor
    attention_output = self._attention_layer(
        query=target_tensor, value=key_value, attention_mask=attention_mask)
    attention_output = self._attention_dropout(attention_output)
    if self._norm_first:
      attention_output = source_tensor + attention_output
    else:
      attention_output = self._attention_layer_norm(target_tensor +
                                                    attention_output)
    if self._norm_first:
      source_attention_output = attention_output
      attention_output = self._output_layer_norm(attention_output)
    inner_output = self._intermediate_dense(attention_output)
    inner_output = self._intermediate_activation_layer(inner_output)
    inner_output = self._inner_dropout_layer(inner_output)
    layer_output = self._output_dense(inner_output)
    layer_output = self._output_dropout(layer_output)

    if self._norm_first:
      return source_attention_output + layer_output

    # During mixed precision training, layer norm output is always fp32 for now.
    # Casts fp32 for the subsequent add.
    layer_output = tf.cast(layer_output, tf.float32)
    return self._output_layer_norm(layer_output + attention_output)
<commit_msg>Fix typo in TransformerEncoderBlock docstring<commit_after># Copyright 2021 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Keras-based TransformerEncoder block layer."""

import tensorflow as tf

@tf.keras.utils.register_keras_serializable(package="keras_nlp")
class TransformerEncoderBlock(tf.keras.layers.Layer):
  """TransformerEncoderBlock layer.

  This layer implements the Transformer Encoder from
  "Attention Is All You Need". (https://arxiv.org/abs/1706.03762),
  which combines a `tf.keras.layers.MultiHeadAttention` layer with a
  two-layer feedforward network.

  References:
    [Attention Is All You Need](https://arxiv.org/abs/1706.03762)
    [BERT: Pre-training of Deep Bidirectional Transformers for Language
     Understanding](https://arxiv.org/abs/1810.04805)
  """

  def __init__(self,
               num_attention_heads,
               inner_dim,
               inner_activation,
               output_range=None,
               kernel_initializer="glorot_uniform",
               bias_initializer="zeros",
               kernel_regularizer=None,
               bias_regularizer=None,
               activity_regularizer=None,
               kernel_constraint=None,
               bias_constraint=None,
               use_bias=True,
               norm_first=False,
               norm_epsilon=1e-12,
               output_dropout=0.0,
               attention_dropout=0.0,
               inner_dropout=0.0,
               attention_initializer=None,
               attention_axes=None,
               **kwargs):
    """Initializes `TransformerEncoderBlock`.

    Args:
      num_attention_heads: Number of attention heads.
      inner_dim: The output dimension of the first Dense layer in a two-layer
        feedforward network.
      inner_activation: The activation for the first Dense layer in a two-layer
        feedforward network.
      output_range: the sequence output range, [0, output_range) for slicing the
        target sequence. `None` means the target sequence is not sliced.
      kernel_initializer: Initializer for dense layer kernels.
      bias_initializer: Initializer for dense layer biases.
      kernel_regularizer: Regularizer for dense layer kernels.
      bias_regularizer: Regularizer for dense layer biases.
      activity_regularizer: Regularizer for dense layer activity.
      kernel_constraint: Constraint for dense layer kernels.
      bias_constraint: Constraint for dense layer kernels.
      use_bias: Whether to enable use_bias in attention layer. If set False,
        use_bias in attention layer is disabled.
      norm_first: Whether to normalize inputs to attention and intermediate
        dense layers. If set False, output of attention and intermediate dense
        layers is normalized.
      norm_epsilon: Epsilon value to initialize normalization layers.
      output_dropout: Dropout probability for the post-attention and output
        dropout.
      attention_dropout: Dropout probability for within the attention layer.
      inner_dropout: Dropout probability for the first Dense layer in a
        two-layer feedforward network.
      attention_initializer: Initializer for kernels of attention layers. If set
        `None`, attention layers use kernel_initializer as initializer for
        kernel.
      attention_axes: axes over which the attention is applied. `None` means
        attention over all axes, but batch, heads, and features.
      **kwargs: keyword arguments/
    """
    super().__init__(**kwargs)

    self._num_heads = num_attention_heads
    self._inner_dim = inner_dim
    self._inner_activation = inner_activation
    self._attention_dropout = attention_dropout
    self._attention_dropout_rate = attention_dropout
    self._output_dropout = output_dropout
    self._output_dropout_rate = output_dropout
    self._output_range = output_range
    self._kernel_initializer = tf.keras.initializers.get(kernel_initializer)
    self._bias_initializer = tf.keras.initializers.get(bias_initializer)
    self._kernel_regularizer = tf.keras.regularizers.get(kernel_regularizer)
    self._bias_regularizer = tf.keras.regularizers.get(bias_regularizer)
    self._activity_regularizer = tf.keras.regularizers.get(activity_regularizer)
    self._kernel_constraint = tf.keras.constraints.get(kernel_constraint)
    self._bias_constraint = tf.keras.constraints.get(bias_constraint)
    self._use_bias = use_bias
    self._norm_first = norm_first
    self._norm_epsilon = norm_epsilon
    self._inner_dropout = inner_dropout
    if attention_initializer:
      self._attention_initializer = tf.keras.initializers.get(
          attention_initializer)
    else:
      self._attention_initializer = self._kernel_initializer
    self._attention_axes = attention_axes

  def build(self, input_shape):
    if isinstance(input_shape, tf.TensorShape):
      input_tensor_shape = input_shape
    elif isinstance(input_shape, (list, tuple)):
      input_tensor_shape = tf.TensorShape(input_shape[0])
    else:
      raise ValueError(
          "The type of input shape argument is not supported, got: %s" %
          type(input_shape))
    einsum_equation = "abc,cd->abd"
    if len(input_tensor_shape.as_list()) > 3:
      einsum_equation = "...bc,cd->...bd"
    hidden_size = input_tensor_shape[-1]
    if hidden_size % self._num_heads != 0:
      raise ValueError(
          "The input size (%d) is not a multiple of the number of attention "
          "heads (%d)" % (hidden_size, self._num_heads))
    self._attention_head_size = int(hidden_size // self._num_heads)
    common_kwargs = dict(
        bias_initializer=self._bias_initializer,
        kernel_regularizer=self._kernel_regularizer,
        bias_regularizer=self._bias_regularizer,
        activity_regularizer=self._activity_regularizer,
        kernel_constraint=self._kernel_constraint,
        bias_constraint=self._bias_constraint)
    self._attention_layer = tf.keras.layers.MultiHeadAttention(
        num_heads=self._num_heads,
        key_dim=self._attention_head_size,
        dropout=self._attention_dropout,
        use_bias=self._use_bias,
        kernel_initializer=self._attention_initializer,
        attention_axes=self._attention_axes,
        name="self_attention",
        **common_kwargs)
    self._attention_dropout = tf.keras.layers.Dropout(rate=self._output_dropout)
    # Use float32 in layernorm for numeric stability.
    # It is probably safe in mixed_float16, but we haven't validated this yet.
    self._attention_layer_norm = (
        tf.keras.layers.LayerNormalization(
            name="self_attention_layer_norm",
            axis=-1,
            epsilon=self._norm_epsilon,
            dtype=tf.float32))
    self._intermediate_dense = tf.keras.layers.experimental.EinsumDense(
        einsum_equation,
        output_shape=(None, self._inner_dim),
        bias_axes="d",
        kernel_initializer=self._kernel_initializer,
        name="intermediate",
        **common_kwargs)
    policy = tf.keras.mixed_precision.global_policy()
    if policy.name == "mixed_bfloat16":
      # bfloat16 causes BERT with the LAMB optimizer to not converge
      # as well, so we use float32.
      # TODO(b/154538392): Investigate this.
      policy = tf.float32
    self._intermediate_activation_layer = tf.keras.layers.Activation(
        self._inner_activation, dtype=policy)
    self._inner_dropout_layer = tf.keras.layers.Dropout(
        rate=self._inner_dropout)
    self._output_dense = tf.keras.layers.experimental.EinsumDense(
        einsum_equation,
        output_shape=(None, hidden_size),
        bias_axes="d",
        name="output",
        kernel_initializer=self._kernel_initializer,
        **common_kwargs)
    self._output_dropout = tf.keras.layers.Dropout(rate=self._output_dropout)
    # Use float32 in layernorm for numeric stability.
    self._output_layer_norm = tf.keras.layers.LayerNormalization(
        name="output_layer_norm",
        axis=-1,
        epsilon=self._norm_epsilon,
        dtype=tf.float32)

    super(TransformerEncoderBlock, self).build(input_shape)

  def get_config(self):
    config = {
        "num_attention_heads":
            self._num_heads,
        "inner_dim":
            self._inner_dim,
        "inner_activation":
            self._inner_activation,
        "output_dropout":
            self._output_dropout_rate,
        "attention_dropout":
            self._attention_dropout_rate,
        "output_range":
            self._output_range,
        "kernel_initializer":
            tf.keras.initializers.serialize(self._kernel_initializer),
        "bias_initializer":
            tf.keras.initializers.serialize(self._bias_initializer),
        "kernel_regularizer":
            tf.keras.regularizers.serialize(self._kernel_regularizer),
        "bias_regularizer":
            tf.keras.regularizers.serialize(self._bias_regularizer),
        "activity_regularizer":
            tf.keras.regularizers.serialize(self._activity_regularizer),
        "kernel_constraint":
            tf.keras.constraints.serialize(self._kernel_constraint),
        "bias_constraint":
            tf.keras.constraints.serialize(self._bias_constraint),
        "use_bias":
            self._use_bias,
        "norm_first":
            self._norm_first,
        "norm_epsilon":
            self._norm_epsilon,
        "inner_dropout":
            self._inner_dropout,
        "attention_initializer":
            tf.keras.initializers.serialize(self._attention_initializer),
        "attention_axes": self._attention_axes,
    }
    base_config = super(TransformerEncoderBlock, self).get_config()
    return dict(list(base_config.items()) + list(config.items()))

  def call(self, inputs):
    """Transformer self-attention encoder block call.

    Args:
      inputs: a single tensor or a list of tensors.
        `input tensor` as the single sequence of embeddings.
        [`input tensor`, `attention mask`] to have the additional attention
          mask.
        [`query tensor`, `key value tensor`, `attention mask`] to have separate
          input streams for the query, and key/value to the multi-head
          attention.

    Returns:
      An output tensor with the same dimensions as input/query tensor.
    """
    if isinstance(inputs, (list, tuple)):
      if len(inputs) == 2:
        input_tensor, attention_mask = inputs
        key_value = None
      elif len(inputs) == 3:
        input_tensor, key_value, attention_mask = inputs
      else:
        raise ValueError("Unexpected inputs to %s with length at %d" %
                         (self.__class__, len(inputs)))
    else:
      input_tensor, key_value, attention_mask = (inputs, None, None)

    if self._output_range:
      if self._norm_first:
        source_tensor = input_tensor[:, 0:self._output_range, :]
        input_tensor = self._attention_layer_norm(input_tensor)
        if key_value is not None:
          key_value = self._attention_layer_norm(key_value)
      target_tensor = input_tensor[:, 0:self._output_range, :]
      if attention_mask is not None:
        attention_mask = attention_mask[:, 0:self._output_range, :]
    else:
      if self._norm_first:
        source_tensor = input_tensor
        input_tensor = self._attention_layer_norm(input_tensor)
        if key_value is not None:
          key_value = self._attention_layer_norm(key_value)
      target_tensor = input_tensor

    if key_value is None:
      key_value = input_tensor
    attention_output = self._attention_layer(
        query=target_tensor, value=key_value, attention_mask=attention_mask)
    attention_output = self._attention_dropout(attention_output)
    if self._norm_first:
      attention_output = source_tensor + attention_output
    else:
      attention_output = self._attention_layer_norm(target_tensor +
                                                    attention_output)
    if self._norm_first:
      source_attention_output = attention_output
      attention_output = self._output_layer_norm(attention_output)
    inner_output = self._intermediate_dense(attention_output)
    inner_output = self._intermediate_activation_layer(inner_output)
    inner_output = self._inner_dropout_layer(inner_output)
    layer_output = self._output_dense(inner_output)
    layer_output = self._output_dropout(layer_output)

    if self._norm_first:
      return source_attention_output + layer_output

    # During mixed precision training, layer norm output is always fp32 for now.
    # Casts fp32 for the subsequent add.
    layer_output = tf.cast(layer_output, tf.float32)
    return self._output_layer_norm(layer_output + attention_output)
<|endoftext|>


<commit_before># Copyright 2017 Francesco Apruzzese <f.apruzzese@apuliasoftware.it>,
# Copyright 2019 Alessandro Camilli <alessandrocamilli@openforce.it>,
# Link IT <info@linkgroup.it>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).

{
    'name': 'ITA - Dichiarazione di intento',
    'summary': 'Gestione dichiarazioni di intento',
    'version': '12.0.0.1.4',
    'license': 'AGPL-3',
    'author': 'Francesco Apruzzese, Odoo Community Association (OCA), '
              'Sergio Corato, Glauco Prina, Lara Baggio',
    'website': 'https://github.com/OCA/l10n-italy/tree/'
               '12.0/l10n_it_dichiarazione_intento',
    'depends': [
        'account',
        'sale',
        ],
    'data': [
        'wizard/manually_declarations_view.xml',
        'views/account_view.xml',
        'views/dichiarazione_intento_view.xml',
        'views/company_view.xml',
        'views/account_invoice_view.xml',
        'data/sequence.xml',
        'security/ir.model.access.csv',
        ],
    'installable': True,
    'auto_install': False,
}
<commit_msg>l10n_it_dichiarazione_intento 12.0.0.1.5<commit_after># Copyright 2017 Francesco Apruzzese <f.apruzzese@apuliasoftware.it>,
# Copyright 2019 Alessandro Camilli <alessandrocamilli@openforce.it>,
# Link IT <info@linkgroup.it>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).

{
    'name': 'ITA - Dichiarazione di intento',
    'summary': 'Gestione dichiarazioni di intento',
    'version': '12.0.0.1.5',
    'license': 'AGPL-3',
    'author': 'Francesco Apruzzese, Odoo Community Association (OCA), '
              'Sergio Corato, Glauco Prina, Lara Baggio',
    'website': 'https://github.com/OCA/l10n-italy/tree/'
               '12.0/l10n_it_dichiarazione_intento',
    'depends': [
        'account',
        'sale',
        ],
    'data': [
        'wizard/manually_declarations_view.xml',
        'views/account_view.xml',
        'views/dichiarazione_intento_view.xml',
        'views/company_view.xml',
        'views/account_invoice_view.xml',
        'data/sequence.xml',
        'security/ir.model.access.csv',
        ],
    'installable': True,
    'auto_install': False,
}
<|endoftext|>


<commit_before># Copyright (C) 2021 Open Source Integrators
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).

{
    "name": "Portugal InvoiceXpress Integration",
    "summary": "Legal invoices with InvoiceXpress",
    "version": "14.0.2.0.0",
    "author": "Open Source Integrators, Odoo Community Association (OCA)",
    "license": "AGPL-3",
    "website": "https://github.com/OCA/l10n-portugal",
    "category": "Accounting/Localizations/EDI",
    "maintainers": ["dreispt"],
    "development_status": "Production/Stable",
    "depends": ["l10n_pt_vat", "account"],
    "data": [
        "views/res_config_settings.xml",
        "views/account_tax_view.xml",
        "views/account_move_view.xml",
        "data/mail_template.xml",
        "data/res.country.csv",
    ],
    "application": True,
    "installable": True,
}
<commit_msg>l10n_pt_account_invoicexpress 14.0.2.0.1<commit_after># Copyright (C) 2021 Open Source Integrators
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).

{
    "name": "Portugal InvoiceXpress Integration",
    "summary": "Legal invoices with InvoiceXpress",
    "version": "14.0.2.0.1",
    "author": "Open Source Integrators, Odoo Community Association (OCA)",
    "license": "AGPL-3",
    "website": "https://github.com/OCA/l10n-portugal",
    "category": "Accounting/Localizations/EDI",
    "maintainers": ["dreispt"],
    "development_status": "Production/Stable",
    "depends": ["l10n_pt_vat", "account"],
    "data": [
        "views/res_config_settings.xml",
        "views/account_tax_view.xml",
        "views/account_move_view.xml",
        "data/mail_template.xml",
        "data/res.country.csv",
    ],
    "application": True,
    "installable": True,
}
<|endoftext|>


<commit_before>import pytz
from pytz.exceptions import UnknownTimeZoneError
from sqlalchemy.inspection import inspect
from sqlalchemy.orm.exc import DetachedInstanceError
from sqlalchemy.sql.expression import select
from sqlalchemy.sql.functions import func
from zope.sqlalchemy.datamanager import mark_changed

from gengine.metadata import DBSession
from gengine.base.cache import cache_general

class ABaseMeta(type):
    def __init__(cls, name, bases, nmspc):
        super(ABaseMeta, cls).__init__(name, bases, nmspc)

        # monkey patch __unicode__
        # this is required to give show the SQL error to the user in flask admin if constraints are violated
        if hasattr(cls,"__unicode__"):
            old_unicode = cls.__unicode__
            def patched(self):
                try:
                    return old_unicode(self)
                except DetachedInstanceError:
                    return "(DetachedInstance)"
            cls.__unicode__ = patched

    def __getattr__(cls, item):
        if item == "__table__":
            return inspect(cls).local_table
        raise AttributeError(item)

class ABase(object, metaclass=ABaseMeta):
    """abstract base class which introduces a nice constructor for the model classes."""

    def __init__(self, *args, **kw):
        """ create a model object.

        pass attributes by using named parameters, e.g. name="foo", value=123
        """

        for k, v in kw.items():
            setattr(self, k, v)

    def __str__(self):
        if hasattr(self, "__unicode__"):
            return self.__unicode__()

def calc_distance(latlong1, latlong2):
    """generates a sqlalchemy expression for distance query in km

       :param latlong1: the location from which we look for rows, as tuple (lat,lng)

       :param latlong2: the columns containing the latitude and longitude, as tuple (lat,lng)
    """

    # explain: http://geokoder.com/distances

    # return func.sqrt(func.pow(69.1 * (latlong1[0] - latlong2[0]),2)
    #               + func.pow(53.0 * (latlong1[1] - latlong2[1]),2))

    return func.sqrt(func.pow(111.2 * (latlong1[0] - latlong2[0]), 2)
                     + func.pow(111.2 * (latlong1[1] - latlong2[1]) * func.cos(latlong2[0]), 2))

def coords(row):
    return (row["lat"], row["lng"])

def combine_updated_at(list_of_dates):
    return max(list_of_dates)

def get_insert_id_by_result(r):
    return r.last_inserted_ids()[0]

def get_insert_ids_by_result(r):
    return r.last_inserted_ids()

def exists_by_expr(t, expr):
    # TODO: use exists instead of count
    q = select([func.count("*").label("c")], from_obj=t).where(expr)
    r = DBSession.execute(q).fetchone()
    if r.c > 0:
        return True
    else:
        return False

@cache_general.cache_on_arguments()
def datetime_trunc(field, timezone):
    return "date_trunc('%(field)s', CAST(to_char(NOW() AT TIME ZONE %(timezone)s, 'YYYY-MM-DD HH24:MI:SS') AS TIMESTAMP)) AT TIME ZONE %(timezone)s" % {
        "field": field,
        "timezone": timezone
    }

@cache_general.cache_on_arguments()
def valid_timezone(timezone):
    try:
        pytz.timezone(timezone)
    except UnknownTimeZoneError:
        return False
    return True

def update_connection():
    session = DBSession()
    mark_changed(session)
    return session
<commit_msg>make orm objects dict-like<commit_after>import pytz
from pytz.exceptions import UnknownTimeZoneError
from sqlalchemy.inspection import inspect
from sqlalchemy.orm.exc import DetachedInstanceError
from sqlalchemy.sql.expression import select
from sqlalchemy.sql.functions import func
from zope.sqlalchemy.datamanager import mark_changed

from gengine.metadata import DBSession
from gengine.base.cache import cache_general

class ABaseMeta(type):
    def __init__(cls, name, bases, nmspc):
        super(ABaseMeta, cls).__init__(name, bases, nmspc)

        # monkey patch __unicode__
        # this is required to give show the SQL error to the user in flask admin if constraints are violated
        if hasattr(cls,"__unicode__"):
            old_unicode = cls.__unicode__
            def patched(self):
                try:
                    return old_unicode(self)
                except DetachedInstanceError:
                    return "(DetachedInstance)"
            cls.__unicode__ = patched

    def __getattr__(cls, item):
        if item == "__table__":
            return inspect(cls).local_table
        raise AttributeError(item)

class ABase(object, metaclass=ABaseMeta):
    """abstract base class which introduces a nice constructor for the model classes."""

    def __init__(self, *args, **kw):
        """ create a model object.

        pass attributes by using named parameters, e.g. name="foo", value=123
        """

        for k, v in kw.items():
            setattr(self, k, v)

    def __str__(self):
        if hasattr(self, "__unicode__"):
            return self.__unicode__()

    def __getitem__(self, key):
        return getattr(self,key)

    def __setitem__(self, key, item):
        return setattr(self,key,item)

def calc_distance(latlong1, latlong2):
    """generates a sqlalchemy expression for distance query in km

       :param latlong1: the location from which we look for rows, as tuple (lat,lng)

       :param latlong2: the columns containing the latitude and longitude, as tuple (lat,lng)
    """

    # explain: http://geokoder.com/distances

    # return func.sqrt(func.pow(69.1 * (latlong1[0] - latlong2[0]),2)
    #               + func.pow(53.0 * (latlong1[1] - latlong2[1]),2))

    return func.sqrt(func.pow(111.2 * (latlong1[0] - latlong2[0]), 2)
                     + func.pow(111.2 * (latlong1[1] - latlong2[1]) * func.cos(latlong2[0]), 2))

def coords(row):
    return (row["lat"], row["lng"])

def combine_updated_at(list_of_dates):
    return max(list_of_dates)

def get_insert_id_by_result(r):
    return r.last_inserted_ids()[0]

def get_insert_ids_by_result(r):
    return r.last_inserted_ids()

def exists_by_expr(t, expr):
    # TODO: use exists instead of count
    q = select([func.count("*").label("c")], from_obj=t).where(expr)
    r = DBSession.execute(q).fetchone()
    if r.c > 0:
        return True
    else:
        return False

@cache_general.cache_on_arguments()
def datetime_trunc(field, timezone):
    return "date_trunc('%(field)s', CAST(to_char(NOW() AT TIME ZONE %(timezone)s, 'YYYY-MM-DD HH24:MI:SS') AS TIMESTAMP)) AT TIME ZONE %(timezone)s" % {
        "field": field,
        "timezone": timezone
    }

@cache_general.cache_on_arguments()
def valid_timezone(timezone):
    try:
        pytz.timezone(timezone)
    except UnknownTimeZoneError:
        return False
    return True

def update_connection():
    session = DBSession()
    mark_changed(session)
    return session
<|endoftext|>


<commit_before>from __future__ import print_function
import os, sys
from twisted.internet.defer import maybeDeferred
from twisted.internet.task import react
from ..timing import DebugTiming
from .cli_args import parser

def dispatch(args): # returns Deferred
    if args.func == "send/send":
        from . import cmd_send
        return cmd_send.send_twisted(args)
    if args.func == "receive/receive":
        _start = args.timing.add_event("import c_r_t")
        from . import cmd_receive
        args.timing.finish_event(_start)
        return cmd_receive.receive_twisted(args)

    raise ValueError("unknown args.func %s" % args.func)

def run(reactor, argv, cwd, stdout, stderr, executable=None):
    """This is invoked by entry() below, and can also be invoked directly by
    tests.
    """

    args = parser.parse_args(argv)
    if not getattr(args, "func", None):
        # So far this only works on py3. py2 exits with a really terse
        # "error: too few arguments" during parse_args().
        parser.print_help()
        sys.exit(0)
    args.cwd = cwd
    args.stdout = stdout
    args.stderr = stderr
    args.timing = timing = DebugTiming()

    timing.add_event("command dispatch")
    d = maybeDeferred(dispatch, args)
    def _maybe_dump_timing(res):
        timing.add_event("exit")
        if args.dump_timing:
            timing.write(args.dump_timing, stderr)
        return res
    d.addBoth(_maybe_dump_timing)
    def _rc(rc):
        raise SystemExit(rc)
    d.addCallback(_rc)
    return d

def entry():
    """This is used by a setuptools entry_point. When invoked this way,
    setuptools has already put the installed package on sys.path ."""
    react(run, (sys.argv[1:], os.getcwd(), sys.stdout, sys.stderr,
                sys.argv[0]))

if __name__ == "__main__":
    args = parser.parse_args()
    print(args)
<commit_msg>runner: display TransferErrors better<commit_after>from __future__ import print_function
import os, sys
from twisted.internet.defer import maybeDeferred
from twisted.internet.task import react
from ..errors import TransferError
from ..timing import DebugTiming
from .cli_args import parser

def dispatch(args): # returns Deferred
    if args.func == "send/send":
        from . import cmd_send
        return cmd_send.send_twisted(args)
    if args.func == "receive/receive":
        _start = args.timing.add_event("import c_r_t")
        from . import cmd_receive
        args.timing.finish_event(_start)
        return cmd_receive.receive_twisted(args)

    raise ValueError("unknown args.func %s" % args.func)

def run(reactor, argv, cwd, stdout, stderr, executable=None):
    """This is invoked by entry() below, and can also be invoked directly by
    tests.
    """

    args = parser.parse_args(argv)
    if not getattr(args, "func", None):
        # So far this only works on py3. py2 exits with a really terse
        # "error: too few arguments" during parse_args().
        parser.print_help()
        sys.exit(0)
    args.cwd = cwd
    args.stdout = stdout
    args.stderr = stderr
    args.timing = timing = DebugTiming()

    timing.add_event("command dispatch")
    d = maybeDeferred(dispatch, args)
    def _maybe_dump_timing(res):
        timing.add_event("exit")
        if args.dump_timing:
            timing.write(args.dump_timing, stderr)
        return res
    d.addBoth(_maybe_dump_timing)
    def _explain_error(f):
        f.trap(TransferError)
        print("ERROR:", f.value, file=stderr)
        raise SystemExit(1)
    d.addErrback(_explain_error)
    def _rc(rc):
        raise SystemExit(rc)
    d.addCallback(_rc)
    return d

def entry():
    """This is used by a setuptools entry_point. When invoked this way,
    setuptools has already put the installed package on sys.path ."""
    react(run, (sys.argv[1:], os.getcwd(), sys.stdout, sys.stderr,
                sys.argv[0]))

if __name__ == "__main__":
    args = parser.parse_args()
    print(args)
<|endoftext|>