text:
import datetime
from lxml import etree
import math
import pytz
import threading
import urlparse

import openerp
from openerp import tools, api
from openerp.osv import osv, fields
from openerp.osv.expression import get_unaccent_wrapper
from openerp.tools.translate import _
from openerp.exceptions import UserError

ADDRESS_FORMAT_CLASSES = {
    '%(city)s %(state_code)s\n%(zip)s': 'o_city_state',
    '%(zip)s %(city)s': 'o_zip_city'
}

class format_address(object):
    @api.model
    def fields_view_get_address(self, arch):
        address_format = self.env.user.company_id.country_id.address_format or ''
        for format_pattern, format_class in ADDRESS_FORMAT_CLASSES.iteritems():
            if format_pattern in address_format:
                doc = etree.fromstring(arch)
                for address_node in doc.xpath("//div[@class='o_address_format']"):
                    # add address format class to address block
                    address_node.attrib['class'] += ' ' + format_class
                    if format_class.startswith('o_zip'):
                        zip_fields = address_node.xpath("//field[@name='zip']")
                        city_fields = address_node.xpath("//field[@name='city']")
                        if zip_fields and city_fields:
                            # move zip field before city field
                            city_fields[0].addprevious(zip_fields[0])
                arch = etree.tostring(doc)
                break
        return arch

@api.model
def _tz_get(self):
    # put POSIX 'Etc/*' entries at the end to avoid confusing users - see bug 1086728
    return [(tz,tz) for tz in sorted(pytz.all_timezones, key=lambda tz: tz if not tz.startswith('Etc/') else '_')]

class res_partner_category(osv.Model):

    def name_get(self, cr, uid, ids, context=None):
        """ Return the categories' display name, including their direct
            parent by default.

            If ``context['partner_category_display']`` is ``'short'``, the short
            version of the category name (without the direct parent) is used.
            The default is the long version.
        """
        if not isinstance(ids, list):
            ids = [ids]
        if context is None:
            context = {}

        if context.get('partner_category_display') == 'short':
            return super(res_partner_category, self).name_get(cr, uid, ids, context=context)

        res = []
        for category in self.browse(cr, uid, ids, context=context):
            names = []
            current = category
            while current:
                names.append(current.name)
                current = current.parent_id
            res.append((category.id, ' / '.join(reversed(names))))
        return res

    @api.model
    def name_search(self, name, args=None, operator='ilike', limit=100):
        args = args or []
        if name:
            # Be sure name_search is symetric to name_get
            name = name.split(' / ')[-1]
            args = [('name', operator, name)] + args
        categories = self.search(args, limit=limit)
        return categories.name_get()

    @api.multi
    def _name_get_fnc(self, field_name, arg):
        return dict(self.name_get())

    _description = 'Partner Tags'
    _name = 'res.partner.category'
    _columns = {
        'name': fields.char('Category Name', required=True, translate=True),
        'color': fields.integer('Color Index'),
        'parent_id': fields.many2one('res.partner.category', 'Parent Tag', select=True, ondelete='cascade'),
        'complete_name': fields.function(_name_get_fnc, type="char", string='Full Name'),
        'child_ids': fields.one2many('res.partner.category', 'parent_id', 'Child Tag'),
        'active': fields.boolean('Active', help="The active field allows you to hide the category without removing it."),
        'parent_left': fields.integer('Left parent', select=True),
        'parent_right': fields.integer('Right parent', select=True),
        'partner_ids': fields.many2many('res.partner', id1='category_id', id2='partner_id', string='Partners'),
    }
    _constraints = [
        (osv.osv._check_recursion, 'Error ! You can not create recursive tags.', ['parent_id'])
    ]
    _defaults = {
        'active': 1,
    }
    _parent_store = True
    _parent_order = 'name'
    _order = 'parent_left, name'

class res_partner_title(osv.osv):
    _name = 'res.partner.title'
    _order = 'name'
    _columns = {
        'name': fields.char('Title', required=True, translate=True),
        'shortcut': fields.char('Abbreviation', translate=True),
    }

@api.model
def _lang_get(self):
    languages = self.env['res.lang'].search([])
    return [(language.code, language.name) for language in languages]

ADDRESS_FIELDS = ('street', 'street2', 'zip', 'city', 'state_id', 'country_id')

class res_partner(osv.Model, format_address):
    _description = 'Partner'
    _name = "res.partner"

    def _address_display(self, cr, uid, ids, name, args, context=None):
        res = {}
        for partner in self.browse(cr, uid, ids, context=context):
            res[partner.id] = self._display_address(cr, uid, partner, context=context)
        return res

    @api.multi
    def _get_tz_offset(self, name, args):
        return dict(
            (p.id, datetime.datetime.now(pytz.timezone(p.tz or 'GMT')).strftime('%z'))
            for p in self)

    def _commercial_partner_compute(self, cr, uid, ids, name, args, context=None):
        """ Returns the partner that is considered the commercial
        entity of this partner. The commercial entity holds the master data
        for all commercial fields (see :py:meth:`~_commercial_fields`) """
        result = dict.fromkeys(ids, False)
        for partner in self.browse(cr, uid, ids, context=context):
            current_partner = partner
            while not current_partner.is_company and current_partner.parent_id:
                current_partner = current_partner.parent_id
            result[partner.id] = current_partner.id
        return result

    def _display_name_compute(self, cr, uid, ids, name, args, context=None):
        context = dict(context or {})
        context.pop('show_address', None)
        context.pop('show_address_only', None)
        context.pop('show_email', None)
        return dict(self.name_get(cr, uid, ids, context=context))

    # indirections to avoid passing a copy of the overridable method when declaring the function field
    _commercial_partner_id = lambda self, *args, **kwargs: self._commercial_partner_compute(*args, **kwargs)
    _display_name = lambda self, *args, **kwargs: self._display_name_compute(*args, **kwargs)

    _commercial_partner_store_triggers = {
        'res.partner': (lambda self,cr,uid,ids,context=None: self.search(cr, uid, [('id','child_of',ids)], context=dict(active_test=False)),
                        ['parent_id', 'is_company'], 10)
    }
    _display_name_store_triggers = {
        'res.partner': (lambda self,cr,uid,ids,context=None: self.search(cr, uid, [('id','child_of',ids)], context=dict(active_test=False)),
                        ['parent_id', 'is_company', 'name'], 10)
    }

    _order = "display_name"
    _columns = {
        'name': fields.char('Name', select=True),
        'display_name': fields.function(_display_name, type='char', string='Name', store=_display_name_store_triggers, select=True),
        'date': fields.date('Date', select=1),
        'title': fields.many2one('res.partner.title', 'Title'),
        'parent_id': fields.many2one('res.partner', 'Related Company', select=True),
        'parent_name': fields.related('parent_id', 'name', type='char', readonly=True, string='Parent name'),
        'child_ids': fields.one2many('res.partner', 'parent_id', 'Contacts', domain=[('active','=',True)]), # force "active_test" domain to bypass _search() override
        'ref': fields.char('Internal Reference', select=1),
        'lang': fields.selection(_lang_get, 'Language',
            help="If the selected language is loaded in the system, all documents related to this contact will be printed in this language. If not, it will be English."),
        'tz': fields.selection(_tz_get,  'Timezone', size=64,
            help="The partner's timezone, used to output proper date and time values inside printed reports. "
                 "It is important to set a value for this field. You should use the same timezone "
                 "that is otherwise used to pick and render date and time values: your computer's timezone."),
        'tz_offset': fields.function(_get_tz_offset, type='char', size=5, string='Timezone offset', invisible=True),
        'user_id': fields.many2one('res.users', 'Salesperson', help='The internal user that is in charge of communicating with this contact if any.'),
        'vat': fields.char('TIN', help="Tax Identification Number. Fill it if the company is subjected to taxes. Used by the some of the legal statements."),
        'bank_ids': fields.one2many('res.partner.bank', 'partner_id', 'Banks'),
        'website': fields.char('Website', help="Website of Partner or Company"),
        'comment': fields.text('Notes'),
        'category_id': fields.many2many('res.partner.category', id1='partner_id', id2='category_id', string='Tags'),
        'credit_limit': fields.float(string='Credit Limit'),
        'barcode': fields.char('Barcode', oldname='ean13'),
        'active': fields.boolean('Active'),
        'customer': fields.boolean('Is a Customer', help="Check this box if this contact is a customer."),
        'supplier': fields.boolean('Is a Vendor', help="Check this box if this contact is a vendor. If it's not checked, purchase people will not see it when encoding a purchase order."),
        'employee': fields.boolean('Employee', help="Check this box if this contact is an Employee."),
        'function': fields.char('Job Position'),
        'type': fields.selection(
            [('contact', 'Contact'),
             ('invoice', 'Invoice address'),
             ('delivery', 'Shipping address'),
             ('other', 'Other address')], 'Address Type',
            help="Used to select automatically the right address according to the context in sales and purchases documents."),
        'street': fields.char('Street'),
        'street2': fields.char('Street2'),
        'zip': fields.char('Zip', size=24, change_default=True),
        'city': fields.char('City'),
        'state_id': fields.many2one("res.country.state", 'State', ondelete='restrict'),
        'country_id': fields.many2one('res.country', 'Country', ondelete='restrict'),
        'email': fields.char('Email'),
        'phone': fields.char('Phone'),
        'fax': fields.char('Fax'),
        'mobile': fields.char('Mobile'),
        'birthdate': fields.char('Birthdate'),
        'is_company': fields.boolean(
            'Is a Company',
            help="Check if the contact is a company, otherwise it is a person"),
        'company_type': fields.selection(
            selection=[('person', 'Individual'),
                       ('company', 'Company')],
            string='Company Type',
            help='Technical field, used only to display a boolean using a radio '
                 'button. As for Odoo v9 RadioButton cannot be used on boolean '
                 'fields, this one serves as interface. Due to the old API '
                 'limitations with interface function field, we implement it '
                 'by hand instead of a true function field. When migrating to '
                 'the new API the code should be simplified. Changing the'
                 'company_type of a company contact into a company will not display'
                 'this contact as a company contact but as a standalone company.'),
        'use_parent_address': fields.boolean('Use Company Address', help="Select this if you want to set company's address information  for this contact"),
        'company_id': fields.many2one('res.company', 'Company', select=1),
        'color': fields.integer('Color Index'),
        'user_ids': fields.one2many('res.users', 'partner_id', 'Users', auto_join=True),
        'contact_address': fields.function(_address_display,  type='char', string='Complete Address'),

        # technical field used for managing commercial fields
        'commercial_partner_id': fields.function(_commercial_partner_id, type='many2one', relation='res.partner', string='Commercial Entity', store=_commercial_partner_store_triggers)
    }

    # image: all image fields are base64 encoded and PIL-supported
    image = openerp.fields.Binary("Image", attachment=True,
        help="This field holds the image used as avatar for this contact, limited to 1024x1024px",
        default=lambda self: self._get_default_image(False, True))
    image_medium = openerp.fields.Binary("Medium-sized image", attachment=True,
        help="Medium-sized image of this contact. It is automatically "\
             "resized as a 128x128px image, with aspect ratio preserved. "\
             "Use this field in form views or some kanban views.")
    image_small = openerp.fields.Binary("Small-sized image", attachment=True,
        help="Small-sized image of this contact. It is automatically "\
             "resized as a 64x64px image, with aspect ratio preserved. "\
             "Use this field anywhere a small image is required.")

    @api.model
    def _default_category(self):
        category_id = self.env.context.get('category_id', False)
        return [category_id] if category_id else False

    @api.model
    def _get_default_image(self, is_company, colorize=False):
        if getattr(threading.currentThread(), 'testing', False) or self.env.context.get('install_mode'):
            return False

        if self.env.context.get('partner_type') == 'delivery':
            img_path = openerp.modules.get_module_resource('base', 'static/src/img', 'truck.png')
        elif self.env.context.get('partner_type') == 'invoice':
            img_path = openerp.modules.get_module_resource('base', 'static/src/img', 'money.png')
        else:
            img_path = openerp.modules.get_module_resource(
                'base', 'static/src/img', 'company_image.png' if is_company else 'avatar.png')
        with open(img_path, 'rb') as f:
            image = f.read()

        # colorize user avatars
        if not is_company and colorize:
            image = tools.image_colorize(image)

        return tools.image_resize_image_big(image.encode('base64'))

    def fields_view_get(self, cr, user, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
        if (not view_id) and (view_type=='form') and context and context.get('force_email', False):
            view_id = self.pool['ir.model.data'].get_object_reference(cr, user, 'base', 'view_partner_simple_form')[1]
        res = super(res_partner,self).fields_view_get(cr, user, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar, submenu=submenu)
        if view_type == 'form':
            res['arch'] = self.fields_view_get_address(cr, user, res['arch'], context=context)
        return res

    @api.model
    def _default_company(self):
        return self.env['res.company']._company_default_get('res.partner')

    _defaults = {
        'active': True,
        'lang': api.model(lambda self: self.env.lang),
        'tz': api.model(lambda self: self.env.context.get('tz', False)),
        'customer': True,
        'category_id': _default_category,
        'company_id': _default_company,
        'color': 0,
        'is_company': False,
        'company_type': 'person',
        'type': 'contact',
        'image': False,
    }

    _constraints = [
        (osv.osv._check_recursion, 'You cannot create recursive Partner hierarchies.', ['parent_id']),
    ]

    _sql_constraints = [
        ('check_name', "CHECK( (type='contact' AND name IS NOT NULL) or (type!='contact') )", 'Contacts require a name.'),
    ]

    @api.one
    def copy(self, default=None):
        default = dict(default or {})
        default['name'] = _('%s (copy)') % self.name
        return super(res_partner, self).copy(default)

    def onchange_parent_id(self, cr, uid, ids, parent_id, context=None):
        def value_or_id(val):
            """ return val or val.id if val is a browse record """
            return val if isinstance(val, (bool, int, long, float, basestring)) else val.id
        if not parent_id or not ids:
            return {'value': {}}
        if parent_id:
            result = {}
            partner = self.browse(cr, uid, ids[0], context=context)
            if partner.parent_id and partner.parent_id.id != parent_id:
                result['warning'] = {
                    'title': _('Warning'),
                    'message': _('Changing the company of a contact should only be done if it '
                                 'was never correctly set. If an existing contact starts working for a new '
                                 'company then a new contact should be created under that new '
                                 'company. You can use the "Discard" button to abandon this change.')}
            # for contacts: copy the parent address, if set (aka, at least
            # one value is set in the address: otherwise, keep the one from
            # the contact)
            if partner.type == 'contact':
                parent = self.browse(cr, uid, parent_id, context=context)
                address_fields = self._address_fields(cr, uid, context=context)
                if any(parent[key] for key in address_fields):
                    result['value'] = dict((key, value_or_id(parent[key])) for key in address_fields)
        return result

    @api.multi
    def onchange_state(self, state_id):
        if state_id:
            state = self.env['res.country.state'].browse(state_id)
            return {'value': {'country_id': state.country_id.id}}
        return {'value': {}}

    @api.multi
    def on_change_company_type(self, company_type):
        return {'value': {'is_company': company_type == 'company'}}

    def _update_fields_values(self, cr, uid, partner, fields, context=None):
        """ Returns dict of write() values for synchronizing ``fields`` """
        values = {}
        for fname in fields:
            field = self._fields[fname]
            if field.type == 'one2many':
                raise AssertionError('One2Many fields cannot be synchronized as part of `commercial_fields` or `address fields`')
            if field.type == 'many2one':
                values[fname] = partner[fname].id if partner[fname] else False
            elif field.type == 'many2many':
                values[fname] = [(6,0,[r.id for r in partner[fname] or []])]
            else:
                values[fname] = partner[fname]
        return values

    def _address_fields(self, cr, uid, context=None):
        """ Returns the list of address fields that are synced from the parent
        when the `use_parent_address` flag is set. """
        return list(ADDRESS_FIELDS)

    def update_address(self, cr, uid, ids, vals, context=None):
        address_fields = self._address_fields(cr, uid, context=context)
        addr_vals = dict((key, vals[key]) for key in address_fields if key in vals)
        if addr_vals:
            return super(res_partner, self).write(cr, uid, ids, addr_vals, context)

    def _commercial_fields(self, cr, uid, context=None):
        """ Returns the list of fields that are managed by the commercial entity
        to which a partner belongs. These fields are meant to be hidden on
        partners that aren't `commercial entities` themselves, and will be
        delegated to the parent `commercial entity`. The list is meant to be
        extended by inheriting classes. """
        return ['vat', 'credit_limit']

    def _commercial_sync_from_company(self, cr, uid, partner, context=None):
        """ Handle sync of commercial fields when a new parent commercial entity is set,
        as if they were related fields """
        commercial_partner = partner.commercial_partner_id
        if not commercial_partner:
            # On child partner creation of a parent partner,
            # the commercial_partner_id is not yet computed
            commercial_partner_id = self._commercial_partner_compute(
                cr, uid, [partner.id], 'commercial_partner_id', [], context=context)[partner.id]
            commercial_partner = self.browse(cr, uid, commercial_partner_id, context=context)
        if commercial_partner != partner:
            commercial_fields = self._commercial_fields(cr, uid, context=context)
            sync_vals = self._update_fields_values(cr, uid, commercial_partner,
                                                   commercial_fields, context=context)
            partner.write(sync_vals)

    def _commercial_sync_to_children(self, cr, uid, partner, context=None):
        """ Handle sync of commercial fields to descendants """
        commercial_fields = self._commercial_fields(cr, uid, context=context)
        commercial_partner = partner.commercial_partner_id
        if not commercial_partner:
            # On child partner creation of a parent partner,
            # the commercial_partner_id is not yet computed
            commercial_partner_id = self._commercial_partner_compute(
                cr, uid, [partner.id], 'commercial_partner_id', [], context=context)[partner.id]
            commercial_partner = self.browse(cr, uid, commercial_partner_id, context=context)
        sync_vals = self._update_fields_values(cr, uid, commercial_partner,
                                               commercial_fields, context=context)
        sync_children = [c for c in partner.child_ids if not c.is_company]
        for child in sync_children:
            self._commercial_sync_to_children(cr, uid, child, context=context)
        return self.write(cr, uid, [c.id for c in sync_children], sync_vals, context=context)

    def _fields_sync(self, cr, uid, partner, update_values, context=None):
        """ Sync commercial fields and address fields from company and to children after create/update,
        just as if those were all modeled as fields.related to the parent """
        # 1. From UPSTREAM: sync from parent
        if update_values.get('parent_id') or update_values.get('type', 'contact'):  # TDE/ fp change to check, get default value not sure
            # 1a. Commercial fields: sync if parent changed
            if update_values.get('parent_id'):
                self._commercial_sync_from_company(cr, uid, partner, context=context)
            # 1b. Address fields: sync if parent or use_parent changed *and* both are now set
            if partner.parent_id and partner.type == 'contact':
                onchange_vals = self.onchange_parent_id(cr, uid, [partner.id],
                                                        parent_id=partner.parent_id.id,
                                                        context=context).get('value', {})
                partner.update_address(onchange_vals)

        # 2. To DOWNSTREAM: sync children
        if partner.child_ids:
            # 2a. Commercial Fields: sync if commercial entity
            if partner.commercial_partner_id == partner:
                commercial_fields = self._commercial_fields(cr, uid,
                                                            context=context)
                if any(field in update_values for field in commercial_fields):
                    self._commercial_sync_to_children(cr, uid, partner,
                                                      context=context)
            # 2b. Address fields: sync if address changed
            address_fields = self._address_fields(cr, uid, context=context)
            if any(field in update_values for field in address_fields):
                domain_children = [('parent_id', '=', partner.id), ('type', '=', 'contact')]
                update_ids = self.search(cr, uid, domain_children, context=context)
                self.update_address(cr, uid, update_ids, update_values, context=context)

    def _handle_first_contact_creation(self, cr, uid, partner, context=None):
        """ On creation of first contact for a company (or root) that has no address, assume contact address
        was meant to be company address """
        parent = partner.parent_id
        address_fields = self._address_fields(cr, uid, context=context)
        if parent and (parent.is_company or not parent.parent_id) and len(parent.child_ids) == 1 and \
            any(partner[f] for f in address_fields) and not any(parent[f] for f in address_fields):
            addr_vals = self._update_fields_values(cr, uid, partner, address_fields, context=context)
            parent.update_address(addr_vals)

    def _clean_website(self, website):
        (scheme, netloc, path, params, query, fragment) = urlparse.urlparse(website)
        if not scheme:
            if not netloc:
                netloc, path = path, ''
            website = urlparse.urlunparse(('http', netloc, path, params, query, fragment))
        return website

    @api.multi
    def write(self, vals):
        # res.partner must only allow to set the company_id of a partner if it
        # is the same as the company of all users that inherit from this partner
        # (this is to allow the code from res_users to write to the partner!) or
        # if setting the company_id to False (this is compatible with any user
        # company)
        if vals.get('website'):
            vals['website'] = self._clean_website(vals['website'])
        if vals.get('company_id'):
            company = self.env['res.company'].browse(vals['company_id'])
            for partner in self:
                if partner.user_ids:
                    companies = set(user.company_id for user in partner.user_ids)
                    if len(companies) > 1 or company not in companies:
                        raise UserError(_("You can not change the company as the partner/user has multiple user linked with different companies."))
        # function field implemented by hand -> remove my when migrating
        c_type = vals.get('company_type')
        is_company = vals.get('is_company')
        if c_type:
            vals['is_company'] = c_type == 'company'
        elif 'is_company' in vals:
            vals['company_type'] = is_company and 'company' or 'person'
        tools.image_resize_images(vals)

        result = super(res_partner, self).write(vals)
        for partner in self:
            if any(u.has_group('base.group_user') for u in partner.user_ids if u != self.env.user):
                self.env['res.users'].check_access_rights('write')
            self._fields_sync(partner, vals)
        return result

    @api.model
    def create(self, vals):
        if vals.get('type') in ['delivery', 'invoice'] and not vals.get('image'):
            # force no colorize for images with no transparency
            vals['image'] = self.with_context(partner_type=vals['type'])._get_default_image(False, False)
        if vals.get('website'):
            vals['website'] = self._clean_website(vals['website'])
        # function field not correctly triggered at create -> remove me when
        # migrating to the new API
        c_type = vals.get('company_type', self._context.get('default_company_type'))
        is_company = vals.get('is_company', self._context.get('default_is_company'))
        if c_type:
            vals['is_company'] = c_type == 'company'
        else:
            vals['company_type'] = is_company and 'company' or 'person'
        tools.image_resize_images(vals)
        partner = super(res_partner, self).create(vals)
        self._fields_sync(partner, vals)
        self._handle_first_contact_creation(partner)
        return partner

    def open_commercial_entity(self, cr, uid, ids, context=None):
        """ Utility method used to add an "Open Company" button in partner views """
        partner = self.browse(cr, uid, ids[0], context=context)
        return {'type': 'ir.actions.act_window',
                'res_model': 'res.partner',
                'view_mode': 'form',
                'res_id': partner.commercial_partner_id.id,
                'target': 'current',
                'flags': {'form': {'action_buttons': True}}}

    def open_parent(self, cr, uid, ids, context=None):
        """ Utility method used to add an "Open Parent" button in partner views """
        partner = self.browse(cr, uid, ids[0], context=context)
        address_form_id = self.pool['ir.model.data'].xmlid_to_res_id(cr, uid, 'base.view_partner_address_form')
        return {'type': 'ir.actions.act_window',
                'res_model': 'res.partner',
                'view_mode': 'form',
                'views': [(address_form_id, 'form')],
                'res_id': partner.parent_id.id,
                'target': 'new',
                'flags': {'form': {'action_buttons': True}}}

    def name_get(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        if isinstance(ids, (int, long)):
            ids = [ids]
        res = []
        for record in self.browse(cr, uid, ids, context=context):
            name = record.name or ''
            if record.parent_id and not record.is_company:
                if not name and record.type in ['invoice', 'delivery', 'other']:
                    name = dict(self.fields_get(cr, uid, ['type'], context=context)['type']['selection'])[record.type]
                name = "%s, %s" % (record.parent_name, name)
            if context.get('show_address_only'):
                name = self._display_address(cr, uid, record, without_company=True, context=context)
            if context.get('show_address'):
                name = name + "\n" + self._display_address(cr, uid, record, without_company=True, context=context)
            name = name.replace('\n\n','\n')
            name = name.replace('\n\n','\n')
            if context.get('show_email') and record.email:
                name = "%s <%s>" % (name, record.email)
            if context.get('html_format'):
                name = name.replace('\n', '<br/>')
            res.append((record.id, name))
        return res

    def _parse_partner_name(self, text, context=None):
        """ Supported syntax:
            - 'Raoul <raoul@grosbedon.fr>': will find name and email address
            - otherwise: default, everything is set as the name """
        emails = tools.email_split(text.replace(' ',','))
        if emails:
            email = emails[0]
            name = text[:text.index(email)].replace('"', '').replace('<', '').strip()
        else:
            name, email = text, ''
        return name, email

    def name_create(self, cr, uid, name, context=None):
        """ Override of orm's name_create method for partners. The purpose is
            to handle some basic formats to create partners using the
            name_create.
            If only an email address is received and that the regex cannot find
            a name, the name will have the email value.
            If 'force_email' key in context: must find the email address. """
        if context is None:
            context = {}
        name, email = self._parse_partner_name(name, context=context)
        if context.get('force_email') and not email:
            raise UserError(_("Couldn't create contact without email address!"))
        if not name and email:
            name = email
        rec_id = self.create(cr, uid, {self._rec_name: name or email, 'email': email or False}, context=context)
        return self.name_get(cr, uid, [rec_id], context)[0]

    def _search(self, cr, user, args, offset=0, limit=None, order=None, context=None, count=False, access_rights_uid=None):
        """ Override search() to always show inactive children when searching via ``child_of`` operator. The ORM will
        always call search() with a simple domain of the form [('parent_id', 'in', [ids])]. """
        # a special ``domain`` is set on the ``child_ids`` o2m to bypass this logic, as it uses similar domain expressions
        if len(args) == 1 and len(args[0]) == 3 and args[0][:2] == ('parent_id','in') \
                and args[0][2] != [False]:
            context = dict(context or {}, active_test=False)
        return super(res_partner, self)._search(cr, user, args, offset=offset, limit=limit, order=order, context=context,
                                                count=count, access_rights_uid=access_rights_uid)

    def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100):
        if not args:
            args = []
        if name and operator in ('=', 'ilike', '=ilike', 'like', '=like'):

            self.check_access_rights(cr, uid, 'read')
            where_query = self._where_calc(cr, uid, args, context=context)
            self._apply_ir_rules(cr, uid, where_query, 'read', context=context)
            from_clause, where_clause, where_clause_params = where_query.get_sql()
            where_str = where_clause and (" WHERE %s AND " % where_clause) or ' WHERE '

            # search on the name of the contacts and of its company
            search_name = name
            if operator in ('ilike', 'like'):
                search_name = '%%%s%%' % name
            if operator in ('=ilike', '=like'):
                operator = operator[1:]

            unaccent = get_unaccent_wrapper(cr)

            query = """SELECT id
                         FROM res_partner
                      {where} ({email} {operator} {percent}
                           OR {display_name} {operator} {percent}
                           OR {reference} {operator} {percent})
                           -- don't panic, trust postgres bitmap
                     ORDER BY {display_name} {operator} {percent} desc,
                              {display_name}
                    """.format(where=where_str,
                               operator=operator,
                               email=unaccent('email'),
                               display_name=unaccent('display_name'),
                               reference=unaccent('ref'),
                               percent=unaccent('%s'))

            where_clause_params += [search_name]*4
            if limit:
                query += ' limit %s'
                where_clause_params.append(limit)
            cr.execute(query, where_clause_params)
            ids = map(lambda x: x[0], cr.fetchall())

            if ids:
                return self.name_get(cr, uid, ids, context)
            else:
                return []
        return super(res_partner,self).name_search(cr, uid, name, args, operator=operator, context=context, limit=limit)

    def find_or_create(self, cr, uid, email, context=None):
        """ Find a partner with the given ``email`` or use :py:method:`~.name_create`
            to create one

            :param str email: email-like string, which should contain at least one email,
                e.g. ``"Raoul Grosbedon <r.g@grosbedon.fr>"``"""
        assert email, 'an email is required for find_or_create to work'
        emails = tools.email_split(email)
        if emails:
            email = emails[0]
        ids = self.search(cr, uid, [('email','=ilike',email)], context=context)
        if not ids:
            return self.name_create(cr, uid, email, context=context)[0]
        return ids[0]

    def _email_send(self, cr, uid, ids, email_from, subject, body, on_error=None):
        partners = self.browse(cr, uid, ids)
        for partner in partners:
            if partner.email:
                tools.email_send(email_from, [partner.email], subject, body, on_error)
        return True

    def email_send(self, cr, uid, ids, email_from, subject, body, on_error=''):
        while len(ids):
            self.pool['ir.cron'].create(cr, uid, {
                'name': 'Send Partner Emails',
                'user_id': uid,
                'model': 'res.partner',
                'function': '_email_send',
                'args': repr([ids[:16], email_from, subject, body, on_error])
            })
            ids = ids[16:]
        return True

    def address_get(self, cr, uid, ids, adr_pref=None, context=None):
        """ Find contacts/addresses of the right type(s) by doing a depth-first-search
        through descendants within company boundaries (stop at entities flagged ``is_company``)
        then continuing the search at the ancestors that are within the same company boundaries.
        Defaults to partners of type ``'default'`` when the exact type is not found, or to the
        provided partner itself if no type ``'default'`` is found either. """
        adr_pref = set(adr_pref or [])
        if 'contact' not in adr_pref:
            adr_pref.add('contact')
        result = {}
        visited = set()
        if isinstance(ids, (int, long)):
            ids = [ids]
        for partner in self.browse(cr, uid, filter(None, ids), context=context):
            current_partner = partner
            while current_partner:
                to_scan = [current_partner]
                # Scan descendants, DFS
                while to_scan:
                    record = to_scan.pop(0)
                    visited.add(record)
                    if record.type in adr_pref and not result.get(record.type):
                        result[record.type] = record.id
                    if len(result) == len(adr_pref):
                        return result
                    to_scan = [c for c in record.child_ids
                                 if c not in visited
                                 if not c.is_company] + to_scan

                # Continue scanning at ancestor if current_partner is not a commercial entity
                if current_partner.is_company or not current_partner.parent_id:
                    break
                current_partner = current_partner.parent_id

        # default to type 'contact' or the partner itself
        default = result.get('contact', ids and ids[0] or False)
        for adr_type in adr_pref:
            result[adr_type] = result.get(adr_type) or default
        return result

    def view_header_get(self, cr, uid, view_id, view_type, context):
        res = super(res_partner, self).view_header_get(cr, uid, view_id, view_type, context)
        if res: return res
        if not context.get('category_id', False):
            return False
        return _('Partners: ')+self.pool['res.partner.category'].browse(cr, uid, context['category_id'], context).name

    @api.model
    @api.returns('self')
    def main_partner(self):
        ''' Return the main partner '''
        return self.env.ref('base.main_partner')

    def _display_address(self, cr, uid, address, without_company=False, context=None):

        '''
        The purpose of this function is to build and return an address formatted accordingly to the
        standards of the country where it belongs.

        :param address: browse record of the res.partner to format
        :returns: the address formatted in a display that fit its country habits (or the default ones
            if not country is specified)
        :rtype: string
        '''

        # get the information that will be injected into the display format
        # get the address format
        address_format = address.country_id.address_format or \
              "%(street)s\n%(street2)s\n%(city)s %(state_code)s %(zip)s\n%(country_name)s"
        args = {
            'state_code': address.state_id.code or '',
            'state_name': address.state_id.name or '',
            'country_code': address.country_id.code or '',
            'country_name': address.country_id.name or '',
            'company_name': address.parent_name or '',
        }
        for field in self._address_fields(cr, uid, context=context):
            args[field] = getattr(address, field) or ''
        if without_company:
            args['company_name'] = ''
        elif address.parent_id:
            address_format = '%(company_name)s\n' + address_format
        return address_format % args


text:
'use strict';

import { AlignedQuoteBy } from '@twreporter/react-article-components/dist/components/article/index';
import AtomicBlockRendererMixin from '../mixins/atomic-block-renderer-mixin';
import BlockQuoteEditingBlock from './block-quote-editing-block';
import React from 'react';
import get from 'lodash/get';

const _ = {
  get,
}

export default class BlockQuoteBlock extends AtomicBlockRendererMixin(React.Component) {
	constructor (props) {
		super(props);
	}

	render () {
		if (!this.state.data) {
			return null;
		}

		let blockContent = _.get(this.state.data, ['content', 0], {});
		let quote = blockContent.quote;
		let quoteBy = blockContent.quoteBy;

		const EditBlock = (
			<BlockQuoteEditingBlock
				label="blockquote"
				isModalOpen={this.state.editMode}
				onToggle={this.handleEditingBlockChange}
				quote={quote}
				quoteBy={quoteBy}
				toggleModal={this.toggleEditMode}
			/>
		);

		return (
			<div
				contentEditable={false}
				onClick={this.toggleEditMode}
				style={{ cursor: 'pointer' }}
			>
				<AlignedQuoteBy
					{...this.state.data}
					device={this.props.device}
				>
				{this.props.children}
				</AlignedQuoteBy>
				{EditBlock}
			</div>
		);
	}
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.hadoop.hdfs.server.namenode;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;

import org.apache.hadoop.HadoopIllegalArgumentException;
import org.apache.hadoop.fs.XAttr;
import org.apache.hadoop.fs.XAttrSetFlag;
import org.apache.hadoop.fs.permission.FsAction;
import org.apache.hadoop.hdfs.XAttrHelper;
import org.apache.hadoop.hdfs.protocol.ErasureCodingPolicy;
import org.apache.hadoop.hdfs.protocol.HdfsFileStatus;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.WritableUtils;

import static org.apache.hadoop.hdfs.server.common.HdfsServerConstants.XATTR_ERASURECODING_POLICY;

/**
 * Helper class to perform erasure coding related operations.
 */
final class FSDirErasureCodingOp {

  /**
   * Private constructor for preventing FSDirErasureCodingOp object
   * creation. Static-only class.
   */
  private FSDirErasureCodingOp() {}

  /**
   * Set an erasure coding policy on the given path.
   *
   * @param fsn The namespace
   * @param srcArg The path of the target directory.
   * @param ecPolicy The erasure coding policy to set on the target directory.
   * @param logRetryCache whether to record RPC ids in editlog for retry
   *          cache rebuilding
   * @return {@link HdfsFileStatus}
   * @throws IOException
   */
  static HdfsFileStatus setErasureCodingPolicy(final FSNamesystem fsn,
      final String srcArg, final ErasureCodingPolicy ecPolicy,
      final boolean logRetryCache) throws IOException {
    assert fsn.hasWriteLock();

    String src = srcArg;
    FSPermissionChecker pc = null;
    byte[][] pathComponents = null;
    pathComponents = FSDirectory.getPathComponentsForReservedPath(src);
    pc = fsn.getPermissionChecker();
    FSDirectory fsd = fsn.getFSDirectory();
    src = fsd.resolvePath(pc, src, pathComponents);
    final INodesInPath iip;
    List<XAttr> xAttrs;
    fsd.writeLock();
    try {
      iip = fsd.getINodesInPath4Write(src, false);
      xAttrs = createErasureCodingPolicyXAttr(fsn, iip, ecPolicy);
    } finally {
      fsd.writeUnlock();
    }
    fsn.getEditLog().logSetXAttrs(src, xAttrs, logRetryCache);
    return fsd.getAuditFileInfo(iip);
  }

  static List<XAttr> createErasureCodingPolicyXAttr(final FSNamesystem fsn,
      final INodesInPath srcIIP, ErasureCodingPolicy ecPolicy) throws IOException {
    FSDirectory fsd = fsn.getFSDirectory();
    assert fsd.hasWriteLock();
    Preconditions.checkNotNull(srcIIP, "INodes cannot be null");
    String src = srcIIP.getPath();
    if (srcIIP.getLastINode() != null &&
        !srcIIP.getLastINode().isDirectory()) {
      throw new IOException("Attempt to set an erasure coding policy " +
          "for a file " + src);
    }
    if (getErasureCodingPolicyForPath(fsn, srcIIP) != null) {
      throw new IOException("Directory " + src + " already has an " +
          "erasure coding policy.");
    }

    // System default erasure coding policy will be used since no specified.
    if (ecPolicy == null) {
      ecPolicy = ErasureCodingPolicyManager.getSystemDefaultPolicy();
    } else {
      // If ecPolicy is specified check if it is one among active policies.
      boolean validPolicy = false;
      ErasureCodingPolicy[] activePolicies =
          FSDirErasureCodingOp.getErasureCodingPolicies(fsd.getFSNamesystem());
      for (ErasureCodingPolicy activePolicy : activePolicies) {
        if (activePolicy.equals(ecPolicy)) {
          validPolicy = true;
          break;
        }
      }
      if (!validPolicy) {
        List<String> ecPolicyNames = new ArrayList<String>();
        for (ErasureCodingPolicy activePolicy : activePolicies) {
          ecPolicyNames.add(activePolicy.getName());
        }
        throw new HadoopIllegalArgumentException("Policy [ " +
            ecPolicy.getName()+ " ] does not match any of the " +
            "supported policies. Please select any one of " + ecPolicyNames);
      }
    }

    final XAttr ecXAttr;
    DataOutputStream dOut = null;
    try {
      ByteArrayOutputStream bOut = new ByteArrayOutputStream();
      dOut = new DataOutputStream(bOut);
      WritableUtils.writeString(dOut, ecPolicy.getName());
      ecXAttr = XAttrHelper.buildXAttr(XATTR_ERASURECODING_POLICY,
          bOut.toByteArray());
    } finally {
      IOUtils.closeStream(dOut);
    }
    final List<XAttr> xattrs = Lists.newArrayListWithCapacity(1);
    xattrs.add(ecXAttr);
    FSDirXAttrOp.unprotectedSetXAttrs(fsd, src, xattrs,
        EnumSet.of(XAttrSetFlag.CREATE));
    return xattrs;
  }

  /**
   * Get the erasure coding policy information for specified path.
   *
   * @param fsn namespace
   * @param src path
   * @return {@link ErasureCodingPolicy}
   * @throws IOException
   * @throws FileNotFoundException if the path does not exist.
   */
  static ErasureCodingPolicy getErasureCodingPolicy(final FSNamesystem fsn,
      final String src) throws IOException {
    assert fsn.hasReadLock();

    final INodesInPath iip = getINodesInPath(fsn, src);
    if (iip.getLastINode() == null) {
      throw new FileNotFoundException("Path not found: " + iip.getPath());
    }
    return getErasureCodingPolicyForPath(fsn, iip);
  }

  /**
   * Check if the file or directory has an erasure coding policy.
   *
   * @param fsn namespace
   * @param srcArg path
   * @return Whether the file or directory has an erasure coding policy.
   * @throws IOException
   */
  static boolean hasErasureCodingPolicy(final FSNamesystem fsn,
      final String srcArg) throws IOException {
    return hasErasureCodingPolicy(fsn, getINodesInPath(fsn, srcArg));
  }

  /**
   * Check if the file or directory has an erasure coding policy.
   *
   * @param fsn namespace
   * @param iip inodes in the path containing the file
   * @return Whether the file or directory has an erasure coding policy.
   * @throws IOException
   */
  static boolean hasErasureCodingPolicy(final FSNamesystem fsn,
      final INodesInPath iip) throws IOException {
    return getErasureCodingPolicy(fsn, iip) != null;
  }

  /**
   * Get the erasure coding policy.
   *
   * @param fsn namespace
   * @param iip inodes in the path containing the file
   * @return {@link ErasureCodingPolicy}
   * @throws IOException
   */
  static ErasureCodingPolicy getErasureCodingPolicy(final FSNamesystem fsn,
      final INodesInPath iip) throws IOException {
    assert fsn.hasReadLock();

    return getErasureCodingPolicyForPath(fsn, iip);
  }

  /**
   * Get available erasure coding polices.
   *
   * @param fsn namespace
   * @return {@link ErasureCodingPolicy} array
   */
  static ErasureCodingPolicy[] getErasureCodingPolicies(final FSNamesystem fsn)
      throws IOException {
    assert fsn.hasReadLock();

    return fsn.getErasureCodingPolicyManager().getPolicies();
  }

  private static INodesInPath getINodesInPath(final FSNamesystem fsn,
      final String srcArg) throws IOException {
    String src = srcArg;
    final byte[][] pathComponents = FSDirectory
        .getPathComponentsForReservedPath(src);
    final FSDirectory fsd = fsn.getFSDirectory();
    final FSPermissionChecker pc = fsn.getPermissionChecker();
    src = fsd.resolvePath(pc, src, pathComponents);
    INodesInPath iip = fsd.getINodesInPath(src, true);
    if (fsn.isPermissionEnabled()) {
      fsn.getFSDirectory().checkPathAccess(pc, iip, FsAction.READ);
    }
    return iip;
  }

  private static ErasureCodingPolicy getErasureCodingPolicyForPath(FSNamesystem fsn,
      INodesInPath iip) throws IOException {
    Preconditions.checkNotNull(iip, "INodes cannot be null");
    FSDirectory fsd = fsn.getFSDirectory();
    fsd.readLock();
    try {
      List<INode> inodes = iip.getReadOnlyINodes();
      for (int i = inodes.size() - 1; i >= 0; i--) {
        final INode inode = inodes.get(i);
        if (inode == null) {
          continue;
        }
        /**
         * TODO: lookup {@link ErasureCodingPolicyManager#getSystemPolices()}
         */
        if (inode.isFile()) {
          return inode.asFile().getErasureCodingPolicyID() == 0 ?
              null : ErasureCodingPolicyManager.getSystemDefaultPolicy();
        }
        // We don't allow setting EC policies on paths with a symlink. Thus
        // if a symlink is encountered, the dir shouldn't have EC policy.
        // TODO: properly support symlinks
        if (inode.isSymlink()) {
          return null;
        }
        final XAttrFeature xaf = inode.getXAttrFeature();
        if (xaf != null) {
          XAttr xattr = xaf.getXAttr(XATTR_ERASURECODING_POLICY);
          if (xattr != null) {
            ByteArrayInputStream bIn = new ByteArrayInputStream(xattr.getValue());
            DataInputStream dIn = new DataInputStream(bIn);
            String ecPolicyName = WritableUtils.readString(dIn);
            return fsd.getFSNamesystem().getErasureCodingPolicyManager().
                getPolicy(ecPolicyName);
          }
        }
      }
    } finally {
      fsd.readUnlock();
    }
    return null;
  }
}


text:
class Todolist

	attr_reader :tasks

	def initialize user
		@tasks = []
		@user = user
	end

	def add task
		@tasks.push(task)
	end

	def delete_task id
		@tasks.delete_if{|task| task.id == id}
	end

	def find_task_by_id id
		@tasks.select{|task| task.id == id}
	end

	def sort_by_created
		@tasks.sort {|task1, task2| task1.created_at <=> task2.created_at}
	end

	def save
		@todo_store.transaction do
			@todo_store[@user] = @tasks
		end
	end

	def load_tasks

	end
end


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Operator ==</title>
<link rel="stylesheet" href="../../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="../../../index.html" title="Chapter 1. Fusion 2.2">
<link rel="up" href="../operator.html" title="Operator">
<link rel="prev" href="operator_unary_star.html" title="Operator *">
<link rel="next" href="operator_inequality.html" title="Operator !=">

Home
Libraries
People
FAQ
More

Operator
        ==

          Description

          Compares 2 iterators for equality.

          Synopsis

template<
    typename I,
    typename J
    >
unspecified operator==(I const& i, J const& i);

Table 1.10. Parameters

<colgroup>
<col>
<col>
<col>
</colgroup>

                    Parameter

                    Requirement

                    Description

                    i, j

                    Any fusion iterators

                    Operation's arguments

          Expression
          Semantics

i == j

          Return type: Convertible to bool.

          Semantics: Equivalent to result_of::equal_to<I,J>::value
          where I and J are the types of i
          and j respectively.

          Header

#include <boost/fusion/iterator/equal_to.hpp>
#include <boost/fusion/include/equal_to.hpp>

Copyright © 2001-2006, 2011, 2012 Joel de Guzman,
      Dan Marsden, Tobias Schwinger

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Composition;
using System.Threading;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;

namespace Microsoft.CodeAnalysis.CSharp.Classification
{
    [ExportLanguageService(typeof(IClassificationService), LanguageNames.CSharp), Shared]
    internal class CSharpEditorClassificationService : AbstractClassificationService
    {
        [ImportingConstructor]
        [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
        public CSharpEditorClassificationService()
        {
        }

        public override void AddLexicalClassifications(SourceText text, TextSpan textSpan, ArrayBuilder<ClassifiedSpan> result, CancellationToken cancellationToken)
            => ClassificationHelpers.AddLexicalClassifications(text, textSpan, result, cancellationToken);

        public override ClassifiedSpan AdjustStaleClassification(SourceText text, ClassifiedSpan classifiedSpan)
            => ClassificationHelpers.AdjustStaleClassification(text, classifiedSpan);
    }
}


text:
package org.openuap.cms.survey.model;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 *

 * 问卷答案实体.
 *

 *
 *

 * $Id: SurveyAnswer.java 4017 2011-03-13 13:55:50Z orangeforjava $
 *

 *
 * @author Joseph
 * @version 1.0
 */
public class SurveyAnswer implements java.io.Serializable {

	/**
	 *
	 */
	private static final long serialVersionUID = -4481308125153434505L;

	private Long surveyId;

	private Map questionAnswers;

	private Map questionItemAnswers;

	private Long answerDate;

	private Voter voter;

	/**
	 *
	 */
	public SurveyAnswer() {
		//
		questionAnswers = Collections.synchronizedMap(new HashMap());
		questionItemAnswers = Collections.synchronizedMap(new HashMap());
	}

	public Long getSurveyId() {
		return surveyId;
	}

	public Map getQuestionItemAnswers() {
		return questionItemAnswers;
	}

	public Map getQuestionAnswers() {
		return questionAnswers;
	}

	public Long getAnswerDate() {
		return answerDate;
	}

	public Voter getVoter() {
		return voter;
	}

	public void setSurveyId(Long surveyId) {
		this.surveyId = surveyId;
	}

	public void setAnswerDate(Long answerDate) {
		this.answerDate = answerDate;
	}

	public void setVoter(Voter voter) {
		this.voter = voter;
	}

	public void setQuestionItemAnswers(Map questionItemAnswers) {
		this.questionItemAnswers = questionItemAnswers;
	}

	public void setQuestionAnswers(Map questionAnswers) {
		this.questionAnswers = questionAnswers;
	}
}


text:
<?php

/**
 * A container for return values from the {@link CampaignService#mutateLabel} call.
 * @package    Google_Api_Ads_AdWords_v201605
 * @subpackage v201605
 */
class CampaignLabelReturnValue extends ListReturnValue
{

    const WSDL_NAMESPACE = "https://adwords.google.com/api/adwords/cm/v201605";
    const XSI_TYPE = "CampaignLabelReturnValue";

    /**
     * @access public
     * @var CampaignLabel[]
     */
    public $value;

    /**
     * @access public
     * @var ApiError[]
     */
    public $partialFailureErrors;

    /**
     * Gets the namesapce of this class
     * @return string the namespace of this class
     */
    public function getNamespace()
    {
        return self::WSDL_NAMESPACE;
    }

    /**
     * Gets the xsi:type name of this class
     * @return string the xsi:type name of this class
     */
    public function getXsiTypeName()
    {
        return self::XSI_TYPE;
    }

    public function __construct($value = null, $partialFailureErrors = null, $ListReturnValueType = null)
    {
        parent::__construct();
        $this->value = $value;
        $this->partialFailureErrors = $partialFailureErrors;
        $this->ListReturnValueType = $ListReturnValueType;
    }

}


text:
package com.feedzai.fos.impl.r.rserve;

import com.feedzai.fos.api.FOSException;

import java.util.List;

/**
 * FOS interface to interface with RServe
 *
 * @author rafael.marmelo
 * @author miguel.duarte
 */
public interface FosRServeAPI {

    /**
     * Loads a R script to the backing R process
     * @param script path to the R script to be loaded s
     * @throws FOSException if the file load failed
     */
    public void load(String script) throws FOSException;

    /**
     * Evals a R command and returns the returned value as the expected Java type
     * @param command R command to execute
     * @param <T> Expected return type
     * @return returned value
     * @throws FOSException  Thrown if R eval fails
     */
    public <T> T eval(String command) throws FOSException;

    /**
     * Remove all variable definitions from all R namespaces
     * @throws FOSException if unable to remove
     */
    public void reset() throws FOSException;

    /**
     * Close the connection with the backing RServe process
     * @throws FOSException if unable to disconnect
     */
    public void close() throws FOSException;

    /**
     * Shutdown the backing R process. No new connections will be allowed afterwards
     * @throws FOSException
     */
    public void shutdown() throws FOSException;

    /**
     * Convenience method to assign a string list inside a given R environment
     * @param varname variable to be assigned
     * @param rEnvironment environment where the variable should be created
     * @param values values to be assigned
     * @throws FOSException if failed to assign variable
     */
    void assignStringList(String varname, String rEnvironment, List<String> values) throws FOSException;

    /**
     * Convenience method to assign a int list inside a given R environment
     * @param varname variable to be assigned
     * @param rEnvironment environment where the variable should be created
     * @param values values to be assigned
     * @throws FOSException if failed to assign variable
     */
    void assignIntList(String varname, String rEnvironment, List<Integer> values) throws FOSException;
}


text:
// ==========================================================================
//  Squidex Headless CMS
// ==========================================================================
//  Copyright (c) Squidex UG (haftungsbeschraenkt)
//  All rights reserved. Licensed under the MIT license.
// ==========================================================================

using NodaTime;
using Squidex.Areas.Api.Controllers.Rules.Models.Converters;
using Squidex.Domain.Apps.Core.Rules;
using Squidex.Domain.Apps.Entities.Rules;
using Squidex.Domain.Apps.Entities.Rules.Runner;
using Squidex.Infrastructure;
using Squidex.Infrastructure.Reflection;
using Squidex.Infrastructure.Validation;
using Squidex.Web;

namespace Squidex.Areas.Api.Controllers.Rules.Models;

public sealed class RuleDto : Resource
{
    /// <summary>
    /// The ID of the rule.
    /// </summary>
    public DomainId Id { get; set; }

    /// <summary>
    /// The user that has created the rule.
    /// </summary>
    [LocalizedRequired]
    public RefToken CreatedBy { get; set; }

    /// <summary>
    /// The user that has updated the rule.
    /// </summary>
    [LocalizedRequired]
    public RefToken LastModifiedBy { get; set; }

    /// <summary>
    /// The date and time when the rule has been created.
    /// </summary>
    public Instant Created { get; set; }

    /// <summary>
    /// The date and time when the rule has been modified last.
    /// </summary>
    public Instant LastModified { get; set; }

    /// <summary>
    /// The version of the rule.
    /// </summary>
    public long Version { get; set; }

    /// <summary>
    /// Determines if the rule is enabled.
    /// </summary>
    public bool IsEnabled { get; set; }

    /// <summary>
    /// Optional rule name.
    /// </summary>
    public string? Name { get; set; }

    /// <summary>
    /// The trigger properties.
    /// </summary>
    [LocalizedRequired]
    public RuleTriggerDto Trigger { get; set; }

    /// <summary>
    /// The action properties.
    /// </summary>
    [LocalizedRequired]
    public RuleAction Action { get; set; }

    /// <summary>
    /// The number of completed executions.
    /// </summary>
    public int NumSucceeded { get; set; }

    /// <summary>
    /// The number of failed executions.
    /// </summary>
    public int NumFailed { get; set; }

    /// <summary>
    /// The date and time when the rule was executed the last time.
    /// </summary>
    public Instant? LastExecuted { get; set; }

    public static RuleDto FromDomain(IEnrichedRuleEntity rule, bool canRun, IRuleRunnerService ruleRunnerService, Resources resources)
    {
        var result = new RuleDto();

        SimpleMapper.Map(rule, result);
        SimpleMapper.Map(rule.RuleDef, result);

        if (rule.RuleDef.Trigger != null)
        {
            result.Trigger = RuleTriggerDtoFactory.Create(rule.RuleDef.Trigger);
        }

        return result.CreateLinks(resources, rule, canRun, ruleRunnerService);
    }

    private RuleDto CreateLinks(Resources resources, IEnrichedRuleEntity rule, bool canRun, IRuleRunnerService ruleRunnerService)
    {
        var values = new { app = resources.App, id = Id };

        if (resources.CanDisableRule)
        {
            if (IsEnabled)
            {
                AddPutLink("disable",
                    resources.Url<RulesController>(x => nameof(x.DisableRule), values));
            }
            else
            {
                AddPutLink("enable",
                    resources.Url<RulesController>(x => nameof(x.EnableRule), values));
            }
        }

        if (resources.CanUpdateRule)
        {
            AddPutLink("update",
                resources.Url<RulesController>(x => nameof(x.PutRule), values));
        }

        if (resources.CanRunRuleEvents)
        {
            AddPutLink("trigger",
                resources.Url<RulesController>(x => nameof(x.TriggerRule), values));

            if (canRun && ruleRunnerService.CanRunRule(rule))
            {
                AddPutLink("run",
                    resources.Url<RulesController>(x => nameof(x.PutRuleRun), values));
            }

            if (canRun && ruleRunnerService.CanRunFromSnapshots(rule))
            {
                var snaphshotValues = new { values.app, values.id, fromSnapshots = true };

                AddPutLink("run/snapshots",
                    resources.Url<RulesController>(x => nameof(x.PutRuleRun), snaphshotValues));
            }
        }

        if (resources.CanReadRuleEvents)
        {
            AddGetLink("logs",
                resources.Url<RulesController>(x => nameof(x.GetEvents), values));
        }

        if (resources.CanDeleteRule)
        {
            AddDeleteLink("delete",
                resources.Url<RulesController>(x => nameof(x.DeleteRule), values));
        }

        return this;
    }
}


text:
// Copyright (C) 2014 André Bargull. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
info: Compound Assignment Operator calls PutValue(lref, v)
es5id: S11.13.2_A6.4_T1
description: >
    Evaluating LeftHandSideExpression lref returns Reference type; Reference
    base value is an environment record and environment record kind is
    declarative environment record. PutValue(lref, v) uses the initially
    created Reference even if a more local binding is available.
    Check operator is "x += y".
flags: [noStrict]
---*/

function testCompoundAssignment() {
  var x = 3;
  var innerX = (function() {
    x += (eval("var x = 2;"), 1);
    return x;
  })();

  if (innerX !== 2) {
    $ERROR('#1: innerX === 2. Actual: ' + (innerX));
  }
  if (x !== 4) {
    $ERROR('#2: x === 4. Actual: ' + (x));
  }
}
testCompoundAssignment();


text:
* **Ensure the bug was not already reported** by searching on GitHub under [Issues](https://github.com/go-zookeper/zk/issues).

* If you're unable to find an open issue addressing the problem, open a new one.
  * Be sure to include a title and clear description.
  * Be sure to include the actual behavior vs the expected.
  * As much relevant information as possible, a code sample or an executable test case demonstrating the expected vs actual behavior.

## Did you write a patch that fixes a bug

* Ensure that all bugs are first reported as an issue. This will help others in finding fixes through issues first.

* Open a PR referencing the issue for the bug.

## Pull Requests

We are open to all Pull Requests, its best to accompany the requests with an issue.

* The PR requires the github actions to pass.

* Requires at least one maintainer to approve the PR to merge to master.

While the above must be satisfied prior to having your pull request reviewed, the reviewer(s) may ask you to complete additional design work, tests, or other changes before your pull request can be ultimately accepted.

## Versioned Releases

Since this library is a core client for interacting with Zookeeper, we do [SemVer](https://semver.org/) releases to ensure predictable changes for users.

Zookeeper itself maintains a compatibility check on the main codebase as well as maintaining backwards compatibility through all Major releases, this core library will try to uphold similar standards of releases.

* Code that is merged into master should be ready for release at any given time.
  * This is to say, that code should not be merged into master if it is not complete and ready for production use.

* If a fix needs to be released ahead of normal operations, file an issue explaining the urgency and impact of the bug.

## Coding guidelines

Some good external resources for style:

1. [Effective Go](https://golang.org/doc/effective_go.html)
2. [The Go common mistakes guide](https://github.com/golang/go/wiki/CodeReviewComments)

All code should be error-free when run through `golint` and `go vet`. We
recommend setting up your editor to:

* Run `goimports` on save
* Run `golint` and `go vet` to check for errors

You can find information in editor support for Go tools here:
<https://github.com/golang/go/wiki/IDEsAndTextEditorPlugins>

## Addition information

* We have zero external dependencies, and would like to maintain this. Use of any external go library should be limited to tests.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace NLP_Assignment2
{
	class DataManager
	{
		// TODO_LOW: global variables should be instantiated through a constructor (or in another way)?
		internal Dictionary<string, int> grammarRules = new Dictionary<string, int>();
		internal Dictionary<string, int> lexiconRules = new Dictionary<string, int>();
		internal List<string> formattedGrammarRules;
		internal List<string> formattedLexiconRules;
		internal int grammarRulesCounter, lexiconRulesCounter;

		internal string LoadFile(string path)
		{
			FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read);
			StreamReader reader = new StreamReader(file);
			string res = reader.ReadToEnd();
			reader.Close();
			file.Close();

			return res;
		}

		// NOTE: When printUniqueRules is set to true, the number of unique grammar/lexicon rules will be written in the output file
		//		 this should only be used for debug reasons as BitPar will crash when parsing these lines.
		internal void SaveFile(string path, List<string> content, ExtractMode extractmode, bool printUniqueRules)
		{
			FileStream file = new FileStream(path, FileMode.Create, FileAccess.Write);
			StreamWriter writer = new StreamWriter(file);

			foreach (string entry in content)
			{
				writer.WriteLine(entry);
			}

			if (printUniqueRules)
			{
				writer.WriteLine("============================================================================");
				if (extractmode.Equals(ExtractMode.GRAMMAR))
				{
					writer.WriteLine("Number of unique grammar rules: " + grammarRulesCounter);
				}
				else if (extractmode.Equals(ExtractMode.LEXICON))
				{
					writer.WriteLine("Number of unique lexicon rules: " + lexiconRulesCounter);
				}
				else
					throw new ArgumentException("Illegal ExtractMode enumerator was passed");
			}

			writer.Close();
			file.Close();
		}

	}
}


text:
<?php

namespace Illuminate\Tests\Integration\Database;

use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Schema;

class DatabaseEloquentModelAttributeCastingTest extends DatabaseTestCase
{
    protected function defineDatabaseMigrationsAfterDatabaseRefreshed()
    {
        Schema::create('test_eloquent_model_with_custom_casts', function (Blueprint $table) {
            $table->increments('id');
            $table->timestamps();
        });
    }

    public function testBasicCustomCasting()
    {
        $model = new TestEloquentModelWithAttributeCast;
        $model->uppercase = 'taylor';

        $this->assertSame('TAYLOR', $model->uppercase);
        $this->assertSame('TAYLOR', $model->getAttributes()['uppercase']);
        $this->assertSame('TAYLOR', $model->toArray()['uppercase']);

        $unserializedModel = unserialize(serialize($model));

        $this->assertSame('TAYLOR', $unserializedModel->uppercase);
        $this->assertSame('TAYLOR', $unserializedModel->getAttributes()['uppercase']);
        $this->assertSame('TAYLOR', $unserializedModel->toArray()['uppercase']);

        $model->syncOriginal();
        $model->uppercase = 'dries';
        $this->assertSame('TAYLOR', $model->getOriginal('uppercase'));

        $model = new TestEloquentModelWithAttributeCast;
        $model->uppercase = 'taylor';
        $model->syncOriginal();
        $model->uppercase = 'dries';
        $model->getOriginal();

        $this->assertSame('DRIES', $model->uppercase);

        $model = new TestEloquentModelWithAttributeCast;

        $model->address = $address = new AttributeCastAddress('110 Kingsbrook St.', 'My Childhood House');
        $address->lineOne = '117 Spencer St.';
        $this->assertSame('117 Spencer St.', $model->getAttributes()['address_line_one']);

        $model = new TestEloquentModelWithAttributeCast;

        $model->setRawAttributes([
            'address_line_one' => '110 Kingsbrook St.',
            'address_line_two' => 'My Childhood House',
        ]);

        $this->assertSame('110 Kingsbrook St.', $model->address->lineOne);
        $this->assertSame('My Childhood House', $model->address->lineTwo);

        $this->assertSame('110 Kingsbrook St.', $model->toArray()['address_line_one']);
        $this->assertSame('My Childhood House', $model->toArray()['address_line_two']);

        $model->address->lineOne = '117 Spencer St.';

        $this->assertFalse(isset($model->toArray()['address']));
        $this->assertSame('117 Spencer St.', $model->toArray()['address_line_one']);
        $this->assertSame('My Childhood House', $model->toArray()['address_line_two']);

        $this->assertSame('117 Spencer St.', json_decode($model->toJson(), true)['address_line_one']);
        $this->assertSame('My Childhood House', json_decode($model->toJson(), true)['address_line_two']);

        $model->address = null;

        $this->assertNull($model->toArray()['address_line_one']);
        $this->assertNull($model->toArray()['address_line_two']);

        $model->options = ['foo' => 'bar'];
        $this->assertEquals(['foo' => 'bar'], $model->options);
        $this->assertEquals(['foo' => 'bar'], $model->options);
        $model->options = ['foo' => 'bar'];
        $model->options = ['foo' => 'bar'];
        $this->assertEquals(['foo' => 'bar'], $model->options);
        $this->assertEquals(['foo' => 'bar'], $model->options);

        $this->assertSame(json_encode(['foo' => 'bar']), $model->getAttributes()['options']);

        $model = new TestEloquentModelWithAttributeCast(['options' => []]);
        $model->syncOriginal();
        $model->options = ['foo' => 'bar'];
        $this->assertTrue($model->isDirty('options'));

        $model = new TestEloquentModelWithAttributeCast;
        $model->birthday_at = now();
        $this->assertIsString($model->toArray()['birthday_at']);
    }

    public function testGetOriginalWithCastValueObjects()
    {
        $model = new TestEloquentModelWithAttributeCast([
            'address' => new AttributeCastAddress('110 Kingsbrook St.', 'My Childhood House'),
        ]);

        $model->syncOriginal();

        $model->address = new AttributeCastAddress('117 Spencer St.', 'Another house.');

        $this->assertSame('117 Spencer St.', $model->address->lineOne);
        $this->assertSame('110 Kingsbrook St.', $model->getOriginal('address')->lineOne);
        $this->assertSame('117 Spencer St.', $model->address->lineOne);

        $model = new TestEloquentModelWithAttributeCast([
            'address' => new AttributeCastAddress('110 Kingsbrook St.', 'My Childhood House'),
        ]);

        $model->syncOriginal();

        $model->address = new AttributeCastAddress('117 Spencer St.', 'Another house.');

        $this->assertSame('117 Spencer St.', $model->address->lineOne);
        $this->assertSame('110 Kingsbrook St.', $model->getOriginal()['address_line_one']);
        $this->assertSame('117 Spencer St.', $model->address->lineOne);
        $this->assertSame('110 Kingsbrook St.', $model->getOriginal()['address_line_one']);

        $model = new TestEloquentModelWithAttributeCast([
            'address' => new AttributeCastAddress('110 Kingsbrook St.', 'My Childhood House'),
        ]);

        $model->syncOriginal();

        $model->address = null;

        $this->assertNull($model->address);
        $this->assertInstanceOf(AttributeCastAddress::class, $model->getOriginal('address'));
        $this->assertNull($model->address);
    }

    public function testOneWayCasting()
    {
        $model = new TestEloquentModelWithAttributeCast;

        $model->password = 'secret';

        $this->assertEquals(hash('sha256', 'secret'), $model->password);
        $this->assertEquals(hash('sha256', 'secret'), $model->getAttributes()['password']);
        $this->assertEquals(hash('sha256', 'secret'), $model->getAttributes()['password']);
        $this->assertEquals(hash('sha256', 'secret'), $model->password);

        $model->password = 'secret2';

        $this->assertEquals(hash('sha256', 'secret2'), $model->password);
        $this->assertEquals(hash('sha256', 'secret2'), $model->getAttributes()['password']);
        $this->assertEquals(hash('sha256', 'secret2'), $model->getAttributes()['password']);
        $this->assertEquals(hash('sha256', 'secret2'), $model->password);
    }

    public function testSettingRawAttributesClearsTheCastCache()
    {
        $model = new TestEloquentModelWithAttributeCast;

        $model->setRawAttributes([
            'address_line_one' => '110 Kingsbrook St.',
            'address_line_two' => 'My Childhood House',
        ]);

        $this->assertSame('110 Kingsbrook St.', $model->address->lineOne);

        $model->setRawAttributes([
            'address_line_one' => '117 Spencer St.',
            'address_line_two' => 'My Childhood House',
        ]);

        $this->assertSame('117 Spencer St.', $model->address->lineOne);
    }
}

class TestEloquentModelWithAttributeCast extends Model
{
    /**
     * The attributes that aren't mass assignable.
     *
     * @var string[]
     */
    protected $guarded = [];

    public function uppercase(): Attribute
    {
        return new Attribute(
            function ($value) {
                return strtoupper($value);
            },
            function ($value) {
                return strtoupper($value);
            }
        );
    }

    public function address(): Attribute
    {
        return new Attribute(
            function ($value, $attributes) {
                if (is_null($attributes['address_line_one'])) {
                    return;
                }

                return new AttributeCastAddress($attributes['address_line_one'], $attributes['address_line_two']);
            },
            function ($value) {
                if (is_null($value)) {
                    return [
                        'address_line_one' => null,
                        'address_line_two' => null,
                    ];
                }

                return ['address_line_one' => $value->lineOne, 'address_line_two' => $value->lineTwo];
            }
        );
    }

    public function options(): Attribute
    {
        return new Attribute(
            function ($value) {
                return json_decode($value, true);
            },
            function ($value) {
                return json_encode($value);
            }
        );
    }

    public function birthdayAt(): Attribute
    {
        return new Attribute(
            function ($value) {
                return Carbon::parse($value);
            },
            function ($value) {
                return $value->format('Y-m-d');
            }
        );
    }

    public function password(): Attribute
    {
        return new Attribute(null, function ($value) {
            return hash('sha256', $value);
        });
    }
}

class AttributeCastAddress
{
    public $lineOne;
    public $lineTwo;

    public function __construct($lineOne, $lineTwo)
    {
        $this->lineOne = $lineOne;
        $this->lineTwo = $lineTwo;
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Sphaerulina inquinans Rehm

### Remarks
null


text:
CC=gcc
CFLAGS=-c -Wall
LDFLAGS=
RM=rm -f

OVERSEER_SOURCES=iface_lcd.c iface_uart.c iface_w1_gpio.c overseer.c
OVERSEER_OBJECTS=$(OVERSEER_SOURCES:.c=.o)
SET_BACKLIGHT_SOURCES=iface_lcd.c iface_uart.c set_backlight.c
SET_BACKLIGHT_OBJECTS=$(SET_BACKLIGHT_SOURCES:.c=.o)

all: overseer set_backlight

overseer: $(OVERSEER_OBJECTS)
	$(CC) $(LDFLAGS) $(OVERSEER_OBJECTS) -o $@

set_backlight: $(SET_BACKLIGHT_OBJECTS)
	$(CC) $(LDFLAGS) $(SET_BACKLIGHT_OBJECTS) -o $@

.c.o:
	$(CC) $(CFLAGS) $< -o $@

clean: clean_test clean_overseer clean_set_backlight

clean_overseer:
	$(RM) $(OVERSEER_OBJECTS) overseer

clean_set_backlight:
	$(RM) $(SET_BACKLIGHT_OBJECTS) set_backlight

test: test_w1_gpio clean_test
clean_test: clean_test_w1_gpio

test_w1_gpio: iface_w1_gpio.o test_iface_w1_gpio.o
	$(CC) $(LDFLAGS) iface_w1_gpio.o test_iface_w1_gpio.o -o test_iface_w1_gpio
	./test_iface_w1_gpio

clean_test_w1_gpio:
	$(RM) test_iface_w1_gpio test_iface_w1_gpio.o


text:
Aviso Legal

Cookies

Contacto


text:
using Lykke.Service.EthereumCore.Core;
using Lykke.Service.EthereumCore.Core.Repositories;
using Lykke.Service.EthereumCore.Core.Settings;
using Nethereum.Web3;
using Lykke.Service.EthereumCore.Services.New.Models;
using System;
using System.Collections.Generic;
using System.Numerics;
using System.Threading.Tasks;
using Autofac.Features.AttributeFilters;
using AzureStorage.Queue;
using EthereumSamuraiApiCaller;
using EthereumSamuraiApiCaller.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Lykke.Service.EthereumCore.Services.Coins.Models;
using Lykke.Service.EthereumCore.Services.PrivateWallet;

namespace Lykke.Service.EthereumCore.Services.New
{
    public interface ITransactionEventsService
    {
        Task IndexCashinEventsForAdapter(string coinAdapterAddress, string deployedTransactionHash);
        Task IndexCashinEventsForErc20Deposits();
        Task MonitorNewEvents(string coinAdapterAddress);
        Task<ICashinEvent> GetCashinEvent(string transactionHash);
        Task IndexEventsForTransaction(string coinAdapterAddress, string trHash);
        Task<BigInteger?> IndexCashinEventsForErc20TransactionHashAsync(string transactionHash);
    }

    public class TransactionEventsService : ITransactionEventsService
    {
        private const string Erc20HotWalletMarker = "ERC20_HOTWALLET";

        private readonly Web3 _web3;
        private readonly IBaseSettings _baseSettings;
        private readonly IQueueFactory _queueFactory;
        private readonly IQueueExt _cashinQueue;
        private readonly IQueueExt _cointTransactionQueue;
        private readonly IEthereumIndexerService _ethereumIndexerService;
        private readonly ICoinRepository _coinRepository;
        private readonly ICashinEventRepository _cashinEventRepository;
        private readonly IBlockSyncedRepository _blockSyncedRepository;
        private readonly AppSettings _settingsWrapper;
        private readonly IEthereumSamuraiAPI _indexerApi;
        private readonly IErc20DepositContractService _depositContractService;

        public TransactionEventsService(Web3 web3,
            IBaseSettings baseSettings,
            ICoinRepository coinRepository,
            ICashinEventRepository cashinEventRepository,
            IBlockSyncedRepository blockSyncedRepository,
            IQueueFactory queueFactory,
            AppSettings settingsWrapper,
            IEthereumSamuraiAPI indexerApi,
            [KeyFilter(Constants.DefaultKey)]IErc20DepositContractService depositContractService,
            IEthereumIndexerService ethereumIndexerService)
        {
            _cashinEventRepository = cashinEventRepository;
            _coinRepository = coinRepository;
            _web3 = web3;
            _blockSyncedRepository = blockSyncedRepository;
            _baseSettings = baseSettings;
            _queueFactory = queueFactory;
            _settingsWrapper = settingsWrapper;
            _indexerApi = indexerApi;
            _depositContractService = depositContractService;
            _cashinQueue = _queueFactory.Build(Constants.CashinCompletedEventsQueue);
            _cointTransactionQueue = _queueFactory.Build(Constants.HotWalletTransactionMonitoringQueue);
            _ethereumIndexerService = ethereumIndexerService;
        }

        public async Task IndexCashinEventsForAdapter(string coinAdapterAddress, string deployedTransactionHash)
        {
            var lastBlock = await _web3.Eth.Blocks.GetBlockNumber.SendRequestAsync();
            var contract = _web3.Eth.GetContract(_baseSettings.CoinAbi, coinAdapterAddress);
            var coinCashInEvent = contract.GetEvent("CoinCashIn");
            BigInteger lastSynced = await GetLastSyncedBlockNumber(coinAdapterAddress);
            var tranaction = await _web3.Eth.Transactions.GetTransactionByHash.SendRequestAsync(deployedTransactionHash);
            BigInteger contractDeployBlockNumber = tranaction.BlockNumber;
            BigInteger indexStartBlock = lastSynced > contractDeployBlockNumber ? lastSynced : contractDeployBlockNumber;
            int scanRange = 1000;

            for (BigInteger from = indexStartBlock; from < lastBlock; from += scanRange + 1)
            {
                BigInteger to = from + scanRange;
                to = to < lastBlock ? to : lastBlock;
                await IndexEventsInRange(coinAdapterAddress, coinCashInEvent, from, to);
            }
        }

        public async Task<BigInteger?> IndexCashinEventsForErc20TransactionHashAsync(string transactionHash)
        {
            BigInteger result = 0;
            var transaction = await _ethereumIndexerService.GetTransactionAsync(transactionHash);

            if (transaction == null)
                return null;

            if (transaction.ErcTransfer != null)
            {
                //only one transfer could appear in deposit transaction
                foreach (var item in transaction.ErcTransfer)
                {
                    if (item.To?.ToLower() != _settingsWrapper.Ethereum.HotwalletAddress?.ToLower())
                        continue;

                    await _cashinEventRepository.InsertAsync(new CashinEvent
                    {
                        CoinAdapterAddress = Erc20HotWalletMarker,
                        Amount = item.Value,
                        TransactionHash = item.TransactionHash,
                        UserAddress = item.From,
                        ContractAddress = item.ContractAddress
                    });

                    BigInteger.TryParse(item.Value, out result);
                }
            }

            return result;
        }

        public async Task IndexCashinEventsForErc20Deposits()
        {
            var indexerStatusResponse = await _indexerApi.ApiIsAliveGetWithHttpMessagesAsync();
            if (indexerStatusResponse.Response.IsSuccessStatusCode)
            {
                var responseContent = await indexerStatusResponse.Response.Content.ReadAsStringAsync();
                var indexerStatus = JObject.Parse(responseContent);
                var lastIndexedBlock = BigInteger.Parse(indexerStatus["blockchainTip"].Value<string>());
                var lastSyncedBlock = await GetLastSyncedBlockNumber(Erc20HotWalletMarker);

                while (++lastSyncedBlock <= lastIndexedBlock - _baseSettings.Level2TransactionConfirmation)
                {
                    var transfersResponse = await _indexerApi.ApiErc20TransferHistoryGetErc20TransfersPostAsync
                    (
                        new GetErc20TransferHistoryRequest
                        {
                            AssetHolder = _settingsWrapper.Ethereum.HotwalletAddress?.ToLower(),
                            BlockNumber = (long)lastSyncedBlock,
                        }
                    );

                    switch (transfersResponse)
                    {
                        case IEnumerable<Erc20TransferHistoryResponse> transfers:

                            foreach (var transfer in transfers)
                            {
                                // Ignore transfers from not deposit contract addresses
                                if (!await _depositContractService.ContainsAsync(transfer.FromProperty))
                                {
                                    continue;
                                }

                                var coinTransactionMessage = new CoinTransactionMessage
                                {
                                    TransactionHash = transfer.TransactionHash
                                };

                                await _cashinEventRepository.InsertAsync(new CashinEvent
                                {
                                    CoinAdapterAddress = Erc20HotWalletMarker,
                                    Amount = transfer.TransferAmount,
                                    TransactionHash = transfer.TransactionHash,
                                    UserAddress = transfer.FromProperty,
                                    ContractAddress = transfer.Contract
                                });

                                await _cointTransactionQueue.PutRawMessageAsync(JsonConvert.SerializeObject(coinTransactionMessage));
                            }

                            break;
                        case ApiException exception:
                            throw new Exception($"Ethereum indexer responded with error: {exception.Error.Message}");
                        default:
                            throw new Exception($"Ethereum indexer returned unexpected response");
                    }

                    await _blockSyncedRepository.InsertAsync(new BlockSynced
                    {
                        BlockNumber = lastSyncedBlock.ToString(),
                        CoinAdapterAddress = Erc20HotWalletMarker
                    });
                }
            }
            else
            {
                throw new Exception("Can not obtain ethereum indexer status.");
            }
        }

        public async Task MonitorNewEvents(string coinAdapterAddress)
        {
            var contract = _web3.Eth.GetContract(_baseSettings.CoinAbi, coinAdapterAddress);
            var coinCashInEvent = contract.GetEvent("CoinCashIn");
            var lastBlock = await GetLastSyncedBlockNumber(coinAdapterAddress);
            var lastRpcBlock = await _web3.Eth.Blocks.GetBlockNumber.SendRequestAsync();

            if (lastRpcBlock.Value == lastBlock)
            {
                return;
            }

            await IndexEventsInRange(coinAdapterAddress, coinCashInEvent, lastBlock, lastRpcBlock.Value);
        }

        public async Task<ICashinEvent> GetCashinEvent(string transactionHash)
        {
            ICashinEvent @event = await _cashinEventRepository.GetAsync(transactionHash);

            return @event;
        }

        public async Task IndexEventsForTransaction(string coinAdapterAddress, string trHash)
        {
            var contract = _web3.Eth.GetContract(_baseSettings.CoinAbi, coinAdapterAddress);
            var coinCashInEvent = contract.GetEvent("CoinCashIn");
            var transaction = await _web3.Eth.Transactions.GetTransactionByHash.SendRequestAsync(trHash);
            var fromBlock = new Nethereum.RPC.Eth.DTOs.BlockParameter(new Nethereum.Hex.HexTypes.HexBigInteger(transaction.BlockNumber));
            var toBlock = new Nethereum.RPC.Eth.DTOs.BlockParameter(new Nethereum.Hex.HexTypes.HexBigInteger(transaction.BlockNumber.Value + 1));
            var filter = await coinCashInEvent.CreateFilterBlockRangeAsync(fromBlock, toBlock);
            var filterByCaller = await coinCashInEvent.GetAllChanges<CoinCashinEvent>(filter);

            filterByCaller.ForEach(async @event =>
            {
                string transactionHash = @event.Log.TransactionHash;
                CoinEventCashinCompletedMessage cashinTransactionMessage = new CoinEventCashinCompletedMessage()
                {
                    TransactionHash = transactionHash
                };

                await _cashinEventRepository.InsertAsync(new CashinEvent()
                {
                    CoinAdapterAddress = coinAdapterAddress,
                    Amount = @event.Event.Amount.ToString(),
                    TransactionHash = transactionHash,
                    UserAddress = @event.Event.Caller
                });
            });
        }

        private async Task<BigInteger> GetLastSyncedBlockNumber(string coinAdapterAddress)
        {
            string lastSyncedBlockNumber = (await _blockSyncedRepository.GetLastSyncedAsync(coinAdapterAddress))?.BlockNumber;
            BigInteger lastSynced;
            BigInteger.TryParse(lastSyncedBlockNumber, out lastSynced);

            return lastSynced;
        }

        private async Task IndexEventsInRange(string coinAdapterAddress, Nethereum.Contracts.Event coinCashInEvent, BigInteger from, BigInteger to)
        {
            var fromBlock = new Nethereum.RPC.Eth.DTOs.BlockParameter(new Nethereum.Hex.HexTypes.HexBigInteger(from));
            var toBlock = new Nethereum.RPC.Eth.DTOs.BlockParameter(new Nethereum.Hex.HexTypes.HexBigInteger(to));
            var filter = await coinCashInEvent.CreateFilterBlockRangeAsync(fromBlock, toBlock);
            var filterByCaller = await coinCashInEvent.GetAllChanges<CoinCashinEvent>(filter);

            filterByCaller.ForEach(async @event =>
            {
                string transactionHash = @event.Log.TransactionHash;
                CoinEventCashinCompletedMessage cashinTransactionMessage = new CoinEventCashinCompletedMessage()
                {
                    TransactionHash = transactionHash
                };

                await _cashinEventRepository.InsertAsync(new CashinEvent()
                {
                    CoinAdapterAddress = coinAdapterAddress,
                    Amount = @event.Event.Amount.ToString(),
                    TransactionHash = transactionHash,
                    UserAddress = @event.Event.Caller
                });

                await _cashinQueue.PutRawMessageAsync(Newtonsoft.Json.JsonConvert.SerializeObject(cashinTransactionMessage));
            });

            await _blockSyncedRepository.InsertAsync(new BlockSynced() { BlockNumber = to.ToString(), CoinAdapterAddress = coinAdapterAddress });
        }
    }
}


text:
<?php
/**
 * Athene2 - Advanced Learning Resources Manager
 *
 * @author      Aeneas Rekkas (aeneas.rekkas@serlo.org)
 * @license     MIT License
 * @license     http://opensource.org/licenses/MIT The MIT License (MIT)
 * @link        https://github.com/serlo-org/athene2 for the canonical source repository
 */
namespace Versioning;

interface RepositoryManagerAwareInterface
{

    /**
     * Set repository manager
     *
     * @param RepositoryManagerInterface $repositoryManager
     */
    public function setRepositoryManager(RepositoryManagerInterface $repositoryManager);

    /**
     * Returns the RepositoryManager
     *
     * @return RepositoryManagerInterface
     */
    public function getRepositoryManager();
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sandeshvahak.parser;

import java.util.Date;

/**
 *
 * @author Vijay
 */
public class GroupSetting {
    public String Jid;
        public boolean Enabled;
        public Date MuteExpiry;
}


text:
name: Mali
permalink: "/categories/mali/"
layout: category
---