Пример #1
0
 def test_curry_should_support_placeholders_to_curry_later_positional_arguments(
         self):
     expect(_(operator.add).curry(_, 'foo')('bar')._) == 'barfoo'
     expect(
         _(lambda x, y, z: x + y + z).curry(_, 'baz',
                                            _)('foo',
                                               'bar')._) == 'foobazbar'
Пример #2
0
class ILicense(model.Schema):

    image_caption = TextLine(
        title=_(u"Legende zum Vorschaubild"),
        description=_(u"Bitte Lizenzinformationen in folgender Form angeben"),
        required=False,
    )
Пример #3
0
 def test_curry_allows_reordering_arguments(self):
     expect(_(lambda x, y: x + y).curry(_._1, _._0)('foo',
                                                    'bar')._) == 'barfoo'
     expect(
         _(lambda x, y, z: x + y + z).curry(_._1, 'baz',
                                            _._0)('foo',
                                                  'bar')._) == 'barbazfoo'
Пример #4
0
def config_electrical_advanced():
    menu = [
        [_("Change ADC Offset"), set_adc_offset],
        [_("Enable ACS7xx Scaling Feature"), set_acs7xx_scaling],
        [_("Set ACS7xx Error Offset"), set_acs7xx_error],
    ]

    menu_map = {}
    menu_max = 0
    for item in menu:
        menu_max = menu_max + 1
        menu_map[menu_max] = item

    while True:
        print()
        print(_("Advanced Electrical Setup"))
        print()

        for index in menu_map:
            print("%d) %s" % (index, menu_map[index][0]))

        print()
        _input = input(
            _("Enter an option from 1-%d (enter q to quit): ") % (menu_max))
        if _input.isdigit() and int(_input) in range(1, menu_max + 1):
            ch = int(_input)
            if ch in menu_map:
                menu_map[ch][1](ch)
        elif _input.lower().startswith("q"):
            return False
        continue
Пример #5
0
    def test_zip(self):
        expect(_((1, 2)).izip((3, 4)).call(tuple)._) == ((1, 3), (2, 4))
        expect(_((1, 2)).izip((3, 4),
                              (5, 6)).call(tuple)._) == ((1, 3, 5), (2, 4, 6))

        expect(_((1, 2)).zip((3, 4))._) == ((1, 3), (2, 4))
        expect(_((1, 2)).zip((3, 4), (5, 6))._) == ((1, 3, 5), (2, 4, 6))
Пример #6
0
def set_units():
    menu = [
        [_("Imperial")],
        [_("Metric")],
    ]

    menu_map = {}
    menu_max = 0

    for item in menu:
        menu_max = menu_max + 1
        menu_map[menu_max] = item

    while True:
        print()
        print(_("Select measurment units (currently"), config_map['units'],
              ")")
        print()

        for index in menu_map:
            print("%d) %s" % (index, menu_map[index][0]))

        print()
        _input = input(
            _("Enter an option from 1-%d (enter q to quit): ") % (menu_max))
        if _input.isdigit() and int(_input) in range(1, menu_max + 1):
            ch = int(_input)
            if ch in menu_map:
                config_map['units'] = menu_map[ch][0]
                write_config()
                return True
        elif _input.lower().startswith("q"):
            return False
        continue
Пример #7
0
def config_electrical():
    menu = [
        [_("Motor Setup"), set_motor],
        [_("Battery Setup"), config_battery],
        [_("Advanced"), config_electrical_advanced],
    ]

    menu_map = {}
    menu_max = 0
    for item in menu:
        menu_max = menu_max + 1
        menu_map[menu_max] = item

    while True:
        print()
        print(_("Electrical"))
        print()

        for index in menu_map:
            print("%d) %s" % (index, menu_map[index][0]))

        print()
        _input = input(
            _("Enter an option from 1-%d (enter q to quit): ") % (menu_max))
        if _input.isdigit() and int(_input) in range(1, menu_max + 1):
            ch = int(_input)
            if ch in menu_map:
                menu_map[ch][1]()
        elif _input.lower().startswith("q"):
            return False
        continue
Пример #8
0
def config_battery():
    menu = [
        [_("New Battery Pack"), set_battery],
        [_("Edit Battery Pack"), set_battery],
    ]

    menu_map = {}
    menu_max = 0
    for item in menu:
        menu_max = menu_max + 1
        menu_map[menu_max] = item

    while True:
        print()
        print(_("Battery Setup"))
        print()

        for index in menu_map:
            print("%d) %s" % (index, menu_map[index][0]))

        print()
        _input = input(
            _("Enter an option from 1-%d (enter q to quit): ") % (menu_max))
        if _input.isdigit() and int(_input) in range(1, menu_max + 1):
            ch = int(_input)
            if ch in menu_map:
                menu_map[ch][1](ch)
        elif _input.lower().startswith("q"):
            return False
        continue
Пример #9
0
def config_date_time():
    menu = [
        [_("Set Date"), set_date],
        [_("Set Time"), set_time],
        [_("Configure Auto-set"), set_auto_dt],
    ]

    menu_map = {}
    menu_max = 0

    for item in menu:
        menu_max = menu_max + 1
        menu_map[menu_max] = item

    while True:
        print()
        print(_("Date / Time"))
        print()

        for index in menu_map:
            print("%d) %s" % (index, menu_map[index][0]))

        _input = input(
            _("Enter an option from 1-%d (enter q to quit): ") % (menu_max))
        if _input.isdigit() and int(_input) in range(1, menu_max + 1):
            ch = int(_input)
            if ch in menu_map:
                menu_map[ch][1]()
        elif _input.lower().startswith("q"):
            return False
        continue
Пример #10
0
def set_acs7xx_scaling():
    menu = [
        [_("Enable")],
        [_("Disable")],
    ]

    menu_map = {}
    menu_max = 0

    for item in menu:
        menu_max = menu_max + 1
        menu_map[menu_max] = item

    while True:
        print()
        print(_("ACS7xx Scaling (currently"), config_map['acs7xx_scaling'],
              ")")
        print()

        for index in menu_map:
            print("%d) %s" % (index, menu_map[index][0]))

        print()
        _input = input(
            _("Enter an option from 1-%d (enter q to quit): ") % (menu_max))
        if _input.isdigit() and int(_input) in range(1, menu_max + 1):
            ch = int(_input)
            if ch in menu_map:
                config_map['acs7xx_scaling'] = ch
                write_config()
                return True
        elif _input.lower().startswith("q"):
            return False
        continue
Пример #11
0
    def validate_integer(value, name, min_value=None, max_value=None):
        """Make sure that value is a valid integer, potentially within range.

        :param value: the value of the integer
        :param name: the name of the integer
        :param min_length: the min_length of the integer
        :param max_length: the max_length of the integer
        :returns: integer
        """
        try:
            value = int(value)
        except (TypeError, ValueError, UnicodeEncodeError):
            raise webob.exc.HTTPBadRequest(explanation=(
                _('%s must be an integer.') % name))

        if min_value is not None and value < min_value:
            raise webob.exc.HTTPBadRequest(
                explanation=(_('%(value_name)s must be >= %(min_value)d') %
                             {'value_name': name, 'min_value': min_value}))
        if max_value is not None and value > max_value:
            raise webob.exc.HTTPBadRequest(
                explanation=(_('%(value_name)s must be <= %(max_value)d') %
                             {'value_name': name, 'max_value': max_value}))

        return value
Пример #12
0
class CustomContent(Content):
    """ A custom content type. """

    id = Column(ForeignKey('contents.id'), primary_key=True)
    custom_attribute = Column(Unicode(1000))

    type_info = Content.type_info.copy(
        name=u'CustomContent',
        title=_(u'CustomContent'),
        add_view=u'add_custom_content',
        addable_to=[u'Document'],
        selectable_default_views=[
            ("alternative-view", _(u"Alternative view")),
        ],
    )

    def __init__(self, custom_attribute=None, **kwargs):
        """ Constructor

        :param custom_attribute: A very custom attribute
        :type custom_attribute: unicode

        :param **kwargs: Arguments that are passed to the base class(es)
        :type **kwargs: see :class:`kotti.resources.Content`
        """

        super(CustomContent, self).__init__(**kwargs)

        self.custom_attribute = custom_attribute
Пример #13
0
 def test_tee_breakout_a_function_with_side_effects_and_disregard_return_value(self):
     side_effect = {}
     def observer(a_list): side_effect['tee'] = a_list.join('-')._
     expect(_([1,2,3]).tee(observer)._) == [1,2,3]
     expect(side_effect['tee']) == '1-2-3'
     
     def fnording(ignored): return 'fnord'
     expect(_([1,2,3]).tee(fnording)._) == [1,2,3]
Пример #14
0
    def test_should_call_callable_with_double_star_splat_as_keyword_arguments(
            self):
        def foo(*, foo):
            return foo

        expect(_(dict(foo='bar')).star_call(foo)._) == 'bar'
        expect(_(dict(foo='baz')).star_call(foo, foo='bar')._) == 'baz'
        expect(_(dict()).star_call(foo, foo='bar')._) == 'bar'
Пример #15
0
    def test_flatten(self):
        expect(_([(1,2),[3,4],(5, [6,7])]).iflatten().call(list)._) == \
            [1,2,3,4,5,6,7]
        expect(_([(1,2),[3,4],(5, [6,7])]).flatten()._) == \
            (1,2,3,4,5,6,7)

        expect(_([(1,2),[3,4],(5, [6,7])]).flatten(level=1)._) == \
            (1,2,3,4,5,[6,7])
Пример #16
0
    def test_dir_vars(self):
        expect(_(object()).dir()._).contains('__class__', '__init__', '__eq__')

        class Foo(object):
            pass

        foo = Foo()
        foo.bar = 'baz'
        expect(_(foo).vars()._) == {'bar': 'baz'}
Пример #17
0
    def test_curry_raises_if_number_of_arguments_missmatch(self):
        expect(lambda: _(lambda x, y: x + y).curry(_, _)('foo')).to_raise(
            AssertionError, 'Not enough arguments')
        expect(lambda: _(lambda x, y: x + y).curry(_._1)('foo')).to_raise(
            AssertionError, 'Not enough arguments')

        seen = set()
        expect(lambda: _(seen).add.curry(_._1)((True, 1))).to_raise(
            AssertionError, r'Not enough arguments.*Need at least 2, got 1')
Пример #18
0
    def test_should_wrap_callables(self):
        counter = [0]

        def foo():
            counter[0] += 1

        expect(_(foo)).is_instance(_.Wrapper)
        _(foo)()
        expect(counter[0]) == 1
Пример #19
0
    def test_use_getitem_to_bypass_overrides(self):
        class UnfortunateNames(object):
            def previous(self, *args):
                return args

        def producer(*args):
            return UnfortunateNames()

        expect(_(producer)().previous('foo')).is_instance(_.Wrapper)
        expect(_(UnfortunateNames()).proxy.previous('foo')._) == ('foo', )
Пример #20
0
    def test_help_method_outputs_correct_docstrings(self):
        with patch.object(sys, 'stdout', io.StringIO()):
            help(_)
            expect(sys.stdout.getvalue()).matches(
                'Help on function fluentpy.wrap')

        with patch.object(sys, 'stdout', io.StringIO()):
            _(list).help()
            expect(sys.stdout.getvalue()).matches(
                'Help on class list in module builtins')
Пример #21
0
    def test_reduce(self):
        # no iterator version of reduce as it's not a mapping
        expect(_((1, 2)).reduce(operator.add)._) == 3

        expect(
            _(((1, 2), (1, 4))).reduce(
                lambda acc, each: acc.setdefault(each[0], []).append(each[1])
                or acc, dict())._) == {
                    1: [2, 4]
                }
Пример #22
0
def set_battery_model():
    while True:
        print()
        print(_("Battery model (currently"), battery_map['model'], ")")
        print()
        model = input(_("Enter battery model or c to cancel: "))
        if model == "c":
            return False
        else:
            battery_map['model'] = model
            write_battery_config()
            return True
Пример #23
0
    def test_group_by(self):
        actual = {}
        for key, values in _((1, 1, 2, 2, 3, 3)).igroupby()._:
            actual[key] = tuple(values)

        expect(actual) == {1: (1, 1), 2: (2, 2), 3: (3, 3)}

        actual = {}
        for key, values in _((1, 1, 2, 2, 3, 3)).groupby()._:
            actual[key] = tuple(values)

        expect(actual) == {1: (1, 1), 2: (2, 2), 3: (3, 3)}
Пример #24
0
def set_battery_mfg():
    while True:
        print()
        print(_("Battery manufacturer (currently"), battery_map['mfg'], ")")
        print()
        mfg = input(_("Enter battery manufacturer or c to cancel: "))
        if mfg == "c":
            return False
        else:
            battery_map['mfg'] = mfg
            write_battery_config()
            return True
Пример #25
0
    def test_each_should_allow_to_call_functions_on_iterators_purely_for_their_side_effect(
            self):
        from unittest.mock import Mock
        call_counter = Mock()

        expect(next(iter(_(['a', 'b']).ieach(call_counter)))) == 'a'
        expect(call_counter.call_count) == 1

        expect(_(['a', 'b']).ieach(call_counter).to(tuple)) == ('a', 'b')
        expect(call_counter.call_count) == 3
        expect(_(['a', 'b']).each(call_counter)._) == ('a', 'b')
        expect(call_counter.call_count) == 5
Пример #26
0
def _get_offset_param(params):
    """Extract offset id from request's dictionary (defaults to 0) or fail."""
    try:
        offset = int(params.pop('offset', 0))
    except ValueError:
        msg = _('offset param must be an integer')
        raise webob.exc.HTTPBadRequest(explanation=msg)

    if offset < 0:
        msg = _('offset param must be positive')
        raise webob.exc.HTTPBadRequest(explanation=msg)

    return offset
Пример #27
0
    def test_flatten(self):
        expect(_([(1,2),[3,4],(5, [6,7])]).iflatten().call(list)._) == \
            [1,2,3,4,5,6,7]
        expect(_([(1,2),[3,4],(5, [6,7])]).flatten()._) == \
            (1,2,3,4,5,6,7)

        expect(_([(1,2),[3,4],(5, [6,7])]).flatten(level=1)._) == \
            (1,2,3,4,5,[6,7])

        # can flatten lists of strings
        expect(_([('D', 'L'), ('B', 'G')]).flatten()._) == ('D', 'L', 'B', 'G')
        expect(_([(b'D', b'L'),
                  (b'B', b'G')]).flatten()._) == (b'D', b'L', b'B', b'G')
Пример #28
0
    def test_should_behave_consistently_in_face_of_methods_returning_none_intermittently(
            self):
        # The problem with the implicit 'self' behaviour, the code changed behaviour
        # if a method returned 'zero' depending on the input

        class SometimesNone(object):
            def maybe_none(self, should_return_none):
                if should_return_none:
                    return None
                return 'fnord'

        expect(_(
            SometimesNone()).maybe_none(True).self._).isinstance(SometimesNone)
        expect(_(SometimesNone()).maybe_none(False).self._).isinstance(
            SometimesNone)
Пример #29
0
    def test_curry_raises_if_handed_too_many_arguments(self):
        curried = _(lambda x: x).curry(
            3)._  # this should now be a funnction that takes _no_ arguments!
        expect(lambda: curried(2)).to_raise(
            TypeError,
            r'<lambda>\(\) takes 1 positional argument but 2 were given')
        expect(lambda: curried(x=2)).to_raise(
            TypeError, r"<lambda>\(\) got multiple values for argument 'x'")

        # a function of 3 arguments of which the first two are ignored
        curried = _(lambda x: x).curry(_._2)._
        expect(curried(1, 2, 3)) == 3
        expect(lambda: curried(1, 2, 3, 4)).to_raise(
            TypeError,
            r'<lambda>\(\) takes 1 positional argument but 2 were given')
Пример #30
0
    def test_islice(self):
        expect(_([1, 2, 1]).slice(1)._) == (1, )
        expect(_([1, 2, 1]).slice(1, 2)._) == (2, )
        expect(_([1, 2, 1]).slice(None, None, 2)._) == (1, 1)

        expect(_([1, 2, 1]).islice(1).to(tuple)) == (1, )
        expect(_([1, 2, 1]).islice(1, 2).to(tuple)) == (2, )
        expect(_([1, 2, 1]).islice(None, None, 2).to(tuple)) == (1, 1)

        expect(_([1, 2, 1]).icycle().slice(1)._) == (1, )
        expect(_([1, 2, 1]).icycle().slice(1, 2)._) == (2, )
        expect(_([1, 2]).icycle().slice(None, 8, 2)._) == (1, 1, 1, 1)
 def load(self):
     if self.object_id is not None:
         raw = self.manager.o.find_one(self.object_id)
         if not raw:
             raise DocumentValidationError(_('Failed to load document, unknown document_id=%s' % self.object_id))
         self.inflate(raw)
     else:
         self._injected_object_id = ObjectId()
         self.object_id = self._injected_object_id
Пример #32
0
def send_invitation_email(meeting):
	meeting = frappe.get_doc("Meeting Brk", meeting)
	meeting.check_permission("email")


	if meeting.status == "Planned":
		frappe.sendmail(
			recipients = [d.attendee for d in meeting.attendees],
			sender = frappe.session.user,
			subject = meeting.title,
			message = meeting.invitation_message,
			reference_doctype = meeting.doctype,
			reference_name = meeting.name
		)

		meeting.status = "Invitation Sent"
		meeting.save()
		frappe.msgprint(_("Invitation Sent"))

	else:
		frappe.msgprint(_("Meeting status must be 'planned'"))
 def assert_permission(self, user, action, *args):
     if self.manager.collection_name is None:
         raise DeveloperFault(_("Unable to check permission against non-modeled document"))
     user.can("%s+%s" % (self.manager.collection_name, action), args[0] if len(args) > 0 else None, True)
Пример #34
0
from django.db import modelsfrom django.utils.translation import ugettext_lazy as _
from .compat import Userfrom . import settings

class Campaign(models.Model):    name = models.CharField(_("Name"), max_length=255, unique=True)    description = models.TextField(_("Description"), blank=True, null=True)    pattern = models.CharField(_("Referrer pattern"), blank=True, max_length=255, help_text="All auto created referrers containing this pattern will be associated with this campaign")
 class Meta:        ordering = ['name']        verbose_name = _("Campaign")        verbose_name_plural = _("Campaigns")
 def __unicode__(self): return self.name
 def __str__(self): return self.__unicode__()
 def count_users(self):        count = 0 for referrer in self.referrers.all():            count += referrer.count_users() return count    count_users.short_description = _("User count")

class Referrer(models.Model):    name = models.CharField(_("Name"), max_length=255, unique=True)    description = models.TextField(_("Description"), blank=True, null=True)    creation_date = models.DateTimeField(_("Creation date"), auto_now_add=True)    campaign = models.ForeignKey(Campaign, verbose_name=_("Campaign"), related_name='referrers', blank=True, null=True)
 class Meta:        ordering = ['name']        verbose_name = _("Referrer")        verbose_name_plural = _("Referrers")
 def __unicode__(self): return self.name
 def __str__(self): return self.__unicode__()
 def count_users(self): return self.users.count()    count_users.short_description = _("User count")
 def match_campaign(self): for campaign in Campaign.objects.exclude(pattern=""): if campaign.pattern in self.name: self.campaign = campaign self.save() break

class UserReferrerManager(models.Manager): def apply_referrer(self, user, request): try:            referrer = Referrer.objects.get(pk=request.session.pop(settings.SESSION_KEY)) except KeyError: pass else:            user_referrer = UserReferrer(user=user, referrer=referrer)            user_referrer.save()

class UserReferrer(models.Model):    user = models.OneToOneField(User, verbose_name=_("User"), related_name='user_referrer')    referrer = models.ForeignKey(Referrer, verbose_name=_("Referrer"), related_name='users')
    objects = UserReferrerManager()
 class Meta:        ordering = ['referrer__name']        verbose_name = _("User Referrer")        verbose_name_plural = _("User Referrers")
 def __unicode__(self): return "%s -> %s" % (self.user.username, self.referrer.name)
 def __str__(self): return self.__unicode__()
Пример #35
0
# -*- coding: utf-8 -*-################################################################################    fiscal_printer#    Copyright (C) 2014 No author.#    No email##    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/>.###############################################################################
import refrom openerp import netsvcfrom openerp.osv import osv, fieldsfrom openerp.tools.translate import _
from controllers.main import do_eventfrom datetime import datetime
from openerp.addons.fpoc.controllers.main import DenialService
class fiscal_printer_disconnected(osv.TransientModel): """    Disconnected but published printers. """    _name = 'fpoc.disconnected'    _description = 'Printers not connected to the server.'
    _columns = { 'name': fields.char(string='Name'), 'protocol': fields.char(string='Protocol'), 'model': fields.char(string='Model'), 'serialNumber': fields.char(string='Serial Number'), 'session_id': fields.char(string='Session'), 'user_id': fields.many2one('res.users', string='Responsable'),    }
 def _update_(self, cr, uid, force=True, context=None):        cr.execute('SELECT COUNT(*) FROM %s' % self._table)        count = cr.fetchone()[0] if not force and count > 0: return  if count > 0:            cr.execute('DELETE FROM %s' % self._table)        t_fp_obj = self.pool.get('fpoc.fiscal_printer') R = do_event('list_printers', control=True)        w_wfp_ids = []        i = 0 for resp in R: if not resp: continue for p in resp['printers']: if t_fp_obj.search(cr, uid, [("name", "=", p['name'])]): pass else:                    values = { 'name': p['name'], 'protocol': p['protocol'], 'model': p['model'], 'serialNumber': p['serialNumber'], 'session_id': p['sid'], 'user_id': p['uid'],                    }                    pid = self.create(cr, uid, values)
 def search(self, cr, uid, args, offset=0, limit=None, order=None, context=None, count=False): self._update_(cr, uid, force=True) return super(fiscal_printer_disconnected, self).search(cr, uid, args, offset=offset, limit=limit, order=order, context=context, count=count)
 def read(self, cr, uid, ids, fields=None, context=None, load='_classic_read'): self._update_(cr, uid, force=False) return super(fiscal_printer_disconnected, self).read(cr, uid, ids, fields=fields, context=context, load=load)
 def create_fiscal_printer(self, cr, uid, ids, context=None): """        Create fiscal printers from this temporal printers """        fp_obj = self.pool.get('fpoc.fiscal_printer') for pri in self.browse(cr, uid, ids):            values = { 'name': pri.name, 'protocol': pri.protocol, 'model': pri.model, 'serialNumber': pri.serialNumber,            }            fp_obj.create(cr, uid, values) return { 'name': _('Fiscal Printers'), 'domain': [], 'res_model': 'fpoc.fiscal_printer', 'type': 'ir.actions.act_window', 'view_id': False, 'view_mode': 'tree,form', 'view_type': 'form', 'context': context,        }
fiscal_printer_disconnected()
class fiscal_printer(osv.osv): """    The fiscal printer entity. """
 def _get_status(self, cr, uid, ids, field_name, arg, context=None):        s = self.get_state(cr, uid, ids, context) 
        r = {} for p_id in ids: if s[p_id]:                dt = datetime.strptime(s[p_id]['clock'], "%Y-%m-%d %H:%M:%S")                r[p_id] = { 'clock': dt.strftime("%Y-%m-%d %H:%M:%S"), 'printerStatus': s[p_id].get('strPrinterStatus', 'Unknown'), 'fiscalStatus': s[p_id].get('strFiscalStatus', 'Unknown'),                } else:                r[p_id]= { 'clock':False, 'printerStatus':'Offline', 'fiscalStatus': 'Offline',                } return r
    _name = 'fpoc.fiscal_printer'    _description = 'fiscal_printer'
    _columns = { 'name': fields.char(string='Name', required=True), 'protocol': fields.char(string='Protocol'), 'model': fields.char(string='Model'), 'serialNumber': fields.char(string='Serial Number (S/N)'), 'lastUpdate': fields.datetime(string='Last Update'), 'printerStatus': fields.function(_get_status, type="char", method=True, readonly="True", multi="state", string='Printer status'), 'fiscalStatus':  fields.function(_get_status, type="char", method=True, readonly="True", multi="state", string='Fiscal status'), 'clock':         fields.function(_get_status, type="datetime", method=True, readonly="True", multi="state", string='Clock'), 'session_id': fields.char(string='session_id'),    }
    _defaults = {    }
    _constraints = [    ]
    _sql_constraints = [ ('model_serialNumber_unique', 'unique("model", "serialNumber")', 'this printer with this model and serial number yet exists') ]
 def update_printers(self, cr, uid, ids, context=None):        r = do_event('info', {}) return True
 def short_test(self, cr, uid, ids, context=None): for fp in self.browse(cr, uid, ids):            do_event('short_test', {'name': fp.name}, session_id=fp.session_id, printer_id=fp.name) return True
 def large_test(self, cr, uid, ids, context=None): for fp in self.browse(cr, uid, ids):            do_event('large_test', {'name': fp.name}, session_id=fp.session_id, printer_id=fp.name) return True
 def advance_paper(self, cr, uid, ids, context=None): for fp in self.browse(cr, uid, ids):            do_event('advance_paper', {'name': fp.name}, session_id=fp.session_id, printer_id=fp.name) return True  def cut_paper(self, cr, uid, ids, context=None): for fp in self.browse(cr, uid, ids):            do_event('cut_paper', {'name': fp.name}, session_id=fp.session_id, printer_id=fp.name) return True  def open_fiscal_journal(self, cr, uid, ids, context=None): for fp in self.browse(cr, uid, ids):            do_event('open_fiscal_journal', {'name': fp.name}, session_id=fp.session_id, printer_id=fp.name) return True
 def cancel_fiscal_ticket(self, cr, uid, ids, context=None): for fp in self.browse(cr, uid, ids):            do_event('cancel_fiscal_ticket', {'name': fp.name}, session_id=fp.session_id, printer_id=fp.name) return True
 def close_fiscal_journal(self, cr, uid, ids, context=None): for fp in self.browse(cr, uid, ids):            do_event('close_fiscal_journal', {'name': fp.name}, session_id=fp.session_id, printer_id=fp.name) return True
 def shift_change(self, cr, uid, ids, context=None): for fp in self.browse(cr, uid, ids):            do_event('shift_change', {'name': fp.name}, session_id=fp.session_id, printer_id=fp.name) return True
 def get_state(self, cr, uid, ids, context=None):        r = {} for fp in self.browse(cr, uid, ids): try:                event_result = do_event('get_status', {'name': fp.name}, session_id=fp.session_id, printer_id=fp.name) except DenialService, m: raise osv.except_osv(_('Connectivity Error'), m)            r[fp.id] = event_result.pop() if event_result else False return r
 def get_counters(self, cr, uid, ids, context=None):        r = {} for fp in self.browse(cr, uid, ids):            event_result = do_event('get_counters', {'name': fp.name}, session_id=fp.session_id, printer_id=fp.name)            r[fp.id] = event_result.pop() if event_result else False return r
 def make_fiscal_ticket(self, cr, uid, ids, options={}, ticket={}, context=None):        fparms = {}        r = {} for fp in self.browse(cr, uid, ids):            fparms['name'] = fp.name            fparms['options'] = options            fparms['ticket'] = ticket            event_result = do_event('make_fiscal_ticket', fparms, session_id=fp.session_id, printer_id=fp.name)            r[fp.id] = event_result.pop() if event_result else False return r
 def cancel_fiscal_ticket(self, cr, uid, ids, context=None):        fparms = {}         r = {} for fp in self.browse(cr, uid, ids):            fparms['name'] = fp.name            event_result = do_event('cancel_fiscal_ticket', fparms, session_id=fp.session_id, printer_id=fp.name)            r[fp.id] = event_result.pop() if event_result else False return r fiscal_printer()
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
Пример #36
0
		timestamp('date',from_time) as start,
		timestamp('date',to_time ) as end,
		name,
		title,
		status,
		0 as all_day	
	from 'tabMeeting Brk'
	where 'date' between %(start)s and %(end)s""",{
		"start": start,
		"end": end
	}, as_dict=True)
		
def make_orientation_meeting(doc, method):
	#create an Orientation meeting when a new user is added
	meeting = frappe.get_doc({
		"doctype": "Meeting Brk",
		"title": "Orientation for {0}".format(doc.first_name),
		"date": add_days(nowdate(), 1),
		"from_time": "09:00",
		"to_time": "09:30",
		"status": "Planned",
		"attendees": [{
			"attendee": doc.name
		}]

	})
	#the System Manager might not have permission to create a Meeting 
	meeting.flags.ignore_permission = True
	meeting.insert()
	frappe.msgprint(_("Orientation meeting created"))
Пример #37
0
        """The main database has been opened."""

        database = zope.interface.Attribute("The main database.")

    class DatabaseOpened(object):
        zope.interface.implements(IDatabaseOpenedEvent)

        def __init__(self, database):
            self.database = database

# TODO: these interfaces are not particularly complete.  The other
# documentation is more accurate at the moment.

KEY = 'zc.async'

NEW = _('new-status', 'New')
PENDING = _('pending-status', 'Pending')
ASSIGNED = _('assigned-status', 'Assigned')
ACTIVE = _('active-status', 'Active')
CALLBACKS = _('callback-status', 'Performing Callbacks')
COMPLETED = _('completed-status', 'Completed')

class IReactor(zope.interface.Interface):
    """This describes what the dispatcher expects of the reactor.

    The reactor does not need to actually provide this interface."""

    def callFromThread(callable, *args, **kw):
        """have callable run in reactor's thread, by reactor, ASAP.

        Intended to be called from a thread other than the reactor's main
Пример #38
0
# -*- coding: utf-8 -*-################################################################################    fiscal_printer#    Copyright (C) 2014 No author.#    No email##    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/>.###############################################################################
import refrom openerp import netsvcfrom openerp.osv import osv, fieldsfrom openerp.tools.translate import _
from controllers.main import do_eventfrom datetime import datetimeimport logging
_logger = logging.getLogger(__name__)_schema = logging.getLogger(__name__ + '.schema')
_header_lines = ['headerLine 1', 'headerLine 2', 'headerLine 3', 'headerLine 4', 'headerLine 5', 'headerLine 6', 'headerLine 7']_footer_lines = ['footerLine 1', 'footerLine 2', 'footerLine 3', 'footerLine 4', 'footerLine 5', 'footerLine 6', 'footerLine 7']
class epson_ar_fiscal_printer(osv.osv): """    The fiscal printer entity. """
    _inherit = 'fpoc.fiscal_printer'
 def _get_field(self, cr, uid, ids, field_name, args, context):        r = {} for fp in self.browse(cr, uid, ids):            r[fp.id] = { fn: False for fn in field_name }            event_result = do_event('read_attributes', {'name': fp.name}, session_id=fp.session_id, printer_id=fp.name)            event_result = event_result.pop() if event_result else {} if event_result and 'attributes' in event_result:                attrs = event_result['attributes']                r[fp.id]['header'] = '\n'.join([ attrs[k] for k in _header_lines if k in attrs and attrs[k] ])                r[fp.id]['footer'] = '\n'.join([ attrs[k] for k in _footer_lines if k in attrs and attrs[k] ]) for fn in field_name: if fn in attrs: if fn in ['tasaIVA', 'maxMonto']:                            r[fp.id][fn] = float(attrs[fn])/100. elif fn in ['fechaFiscalizacion']:                            line = attrs[fn]                            r[fp.id][fn] = "20{2}-{1}-{0}".format(*[line[i:i+2] for i in range(0, len(line), 2)]) else:                            r[fp.id][fn] = attrs[fn] return r
 def _put_field(self, cr, uid, ids, field_name, field_value, arg, context):        fp = self.browse(cr, uid, ids)        data = { 'name': fp.name, 'attributes': {} } if (field_name == 'header'):            lines = field_value.split('\n')[:len(_header_lines)] if field_value else []            lines = lines + (len(_header_lines) - len(lines)) * ['']            data['attributes'].update(dict(zip(_header_lines, lines))) if (field_name == 'footer'):            lines = field_value.split('\n')[:len(_footer_lines)] if field_value else []            lines = lines + (len(_footer_lines) - len(lines)) * ['']            data['attributes'].update(dict(zip(_footer_lines, lines)))        event_result = do_event('write_attributes', data, session_id=fp.session_id, printer_id=fp.name) return True
    _columns = { 'header': fields.function(_get_field, fnct_inv=_put_field, type="text", method=True, multi='epson_text', store=False, string='Header'), 'footer': fields.function(_get_field, fnct_inv=_put_field, type="text", method=True, multi='epson_text', store=False, string='Footer'),
 'razonSocial': fields.function(_get_field, type="char", method=True, multi='epson_info', store=False, string='Razon Social'), 'cuit': fields.function(_get_field, type="char", method=True, multi='epson_info', store=False, string='CUIT'), 'caja': fields.function(_get_field, type="char", method=True, multi='epson_info', store=False, string='Caja/Punto de Venta'), 'ivaResponsabilidad': fields.function(_get_field, type="char", method=True, multi='epson_info', store=False, string='Resp. IVA'), 'calle': fields.function(_get_field, type="char", method=True, multi='epson_info', store=False, string='Calle'), 'numero': fields.function(_get_field, type="char", method=True, multi='epson_info', store=False, string='Numero'), 'piso': fields.function(_get_field, type="char", method=True, multi='epson_info', store=False, string='Piso'), 'depto': fields.function(_get_field, type="char", method=True, multi='epson_info', store=False, string='Depto'), 'localidad': fields.function(_get_field, type="char", method=True, multi='epson_info', store=False, string='Localidad'), 'cpa': fields.function(_get_field, type="char", method=True, multi='epson_info', store=False, string='Cod.Pos.'), 'provincia': fields.function(_get_field, type="char", method=True, multi='epson_info', store=False, string='Provincia'), 'tasaIVA': fields.function(_get_field, type="float", method=True, multi='epson_info', store=False, string='Tasa IVA'), 'maxMonto': fields.function(_get_field, type="float", method=True, multi='epson_info', store=False, string='Monto Maximo'), 'fechaFiscalizacion': fields.function(_get_field, type="date", method=True, multi='epson_info', store=False, string='Fecha Fiscalizacion'),    }
epson_ar_fiscal_printer()
class epson_ar_fiscal_tf_printer_configuration(osv.osv): """    Configuracion necesaria para documentos fiscales Ticket-Facturas/Nota de Debito """
    _inherit = 'fpoc.configuration'    _description = 'Configuracion de TF/TND para Epson Argentina'
    epson_type_paper_status = { 'epson_ar_receipt': ( 'receiptState', { 0: 'ok', 1: 'low', 2: 'none', 3: 'unknown',        }), 'epson_ar_journal': ( 'journalState', { 0: 'ok', 1: 'low', 2: 'none', 3: 'unknown',        }), 'epson_ar_slip': ( 'slipHasPaper', { 0: 'ok', 1: 'low', 2: 'none', 3: 'unknown',        }),    }
 def solve_status(self, cr, uid, ids, status, context=None):        r = super(epson_ar_fiscal_tf_printer_configuration, self).solve_status(cr, uid, ids, status, context=context) for conf in self.browse(cr, uid, ids): if conf.type not in ['epson_ar_receipt', 'epson_ar_journal', 'epson_ar_slip']: continue for stat in r.values():                _logger.debug(stat) if not stat: continue if 'paper_state' not in stat:                    key, rule = self.epson_type_paper_status.get(conf.type, (False, False))                    stat['paper_state'] = rule.get(stat.get(key, 'unknown'),'unknown') if 'fiscal_state' not in stat:                    stat['fiscal_state'] = 'open' if stat['inFiscalJournal'] else 'close' if 'printer_state' not in stat:                    stat['printer_state'] = [ v for v in ['deviceopen' if stat['isPrinterOpen']      else False, 'onerror' if stat['inError']            else False, 'offline' if stat['isOffline']          else False, 'nomemory' if stat['memStatus']          else False, 'nopaper' if stat['slipHasPaper']       else False, 'printing' if stat['documentInProgress'] else False, 'ready'] if v ][0] return r
 def _get_type(self, cr, uid, context=None):        r = super(epson_ar_fiscal_tf_printer_configuration, self)._get_type(cr, uid, context=context) return r + [            ('epson_ar_receipt', _('Receipt Epson Arg.')),            ('epson_ar_journal', _('Journal Epson Arg.')),            ('epson_ar_slip',    _('Slip station Epson Arg.')),        ]
    _columns = { 'type': fields.selection(_get_type, 'Type'), 'triplicated': fields.boolean('Imprimir en triplicado'), 'store_description': fields.boolean('Almacenar descripciones de items'), 'keep_description_attributes': fields.boolean('Conservar atributos de impresion de las descripciones'), 'store_extra_description': fields.boolean('Almacenar solo primer descripcion extra'), 'cut_paper': fields.boolean('Cortar papel'), 'electronic_answer':fields.boolean('Devuelve respuesta electronica'), 'print_return_attribute':fields.boolean('Imprime "Su Vuelto" con atributos'), 'current_account_automatic_pay':fields.boolean('Utiliza pago automatico como cuenta corriente'), 'print_quantities':fields.boolean('Imprimir Cantidad de unidades'), 'tail': fields.text('Modificaciones en el pie del ticket'),    }
 def onchange_type(self, cr, uid, ids, type, context=None):        r = super(epson_ar_fiscal_tf_printer_configuration, self).onchange_type(cr, uid, ids, type, context=context) if (type == "epson_ar_tf"):            r['value']['protocol'] = 'epson_ar' return r
 def toDict(self, cr, uid, ids, context=None):        r = super(epson_ar_fiscal_tf_printer_configuration, self).toDict(cr, uid, ids, context=context)        fields = self._columns.keys()        fields.remove('user_ids') for conf in self.read(cr, uid, ids, fields, context=context): if (conf['type'] == "epson_ar_tf"):                conf_id = conf['id'] del conf['type'] del conf['name'] del conf['protocol'] del conf['id'] del conf['tail'] # Proceso especial.                r[conf_id] = conf return r

epson_ar_fiscal_tf_printer_configuration()
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: