text:
"""Import legacy data from TIM (basic version).

Usage:

- :attr:`legacy_data_path <lino.core.site.Site.legacy_data_path>` must
  point to the TIM data path, e.g.::

      legacy_data_path = '~/vbshared2/drives/L/backup/data/privat'

- Add ``'tim2lino'`` to your
  :attr:`demo_fixtures <lino.core.site.Site.demo_fixtures>`.

- Run :manage:`prep`.

"""
from __future__ import unicode_literals

GET_THEM_ALL = True

START_YEAR = 2002
"""
Don't import vouchers before 2002. TODO: make this
configurable
"""

import datetime
from decimal import Decimal
# from lino.utils.quantities import Duration

from dateutil import parser as dateparser

from django.conf import settings
from django.core.exceptions import ValidationError
from django.utils.timezone import make_aware

from lino.utils import dblogger
from lino.utils import dpy
from lino.mixins import Created

from lino_xl.lib.accounts.choicelists import AccountTypes
from lino_xl.lib.accounts.utils import ZERO

from lino.core.utils import obj2str
from lino.core.utils import is_valid_email

from lino_xl.lib.ledger.utils import myround
from lino_xl.lib.tim2lino.utils import TimLoader

from lino.api import dd, rt

# Activity = dd.resolve_model('pcsw.Activity')
Country = dd.resolve_model('countries.Country')
Place = dd.resolve_model('countries.Place')
Person = dd.resolve_model("contacts.Person")
Company = dd.resolve_model("contacts.Company")
# Account = dd.resolve_model('accounts.Account')
Account = rt.models.accounts.Account
Group = dd.resolve_model('accounts.Group')
Journal = dd.resolve_model('ledger.Journal')
Movement = dd.resolve_model('ledger.Movement')
# potentially UnresolvedModel:
Household = dd.resolve_model('households.Household')
List = dd.resolve_model('lists.List')

if True:
    users = dd.resolve_app('users')
    households = dd.resolve_app('households')
    vat = dd.resolve_app('vat')
    sales = dd.resolve_app('sales')
    ledger = dd.resolve_app('ledger')
    accounts = dd.resolve_app('accounts')
    products = dd.resolve_app('products')
    contacts = dd.resolve_app('contacts')
    finan = dd.resolve_app('finan')
    sepa = dd.resolve_app('sepa')
    lists = dd.resolve_app('lists')

# if dd.is_installed('vat'):
#     VatRule = rt.models.vat.VatRule

# def convert_username(name):
    # return name.lower()

from lino_xl.lib.vat.choicelists import VatClasses, VatRegimes

def tax2vat(idtax):
    idtax = idtax.strip()
    if idtax == 'D20':
        return VatClasses.normal
    elif idtax == 'D18':
        return VatClasses.normal
    elif idtax == '0':
        return VatClasses.exempt
    elif idtax == 'IS':
        return VatClasses.normal
    elif idtax == 'XS':
        return VatClasses.normal
    else:
        return VatClasses.normal
    raise Exception("Unknown VNl->IdTax %r" % idtax)

def vat_regime(idreg):
    if idreg == 'A':
        return VatRegimes.subject
    elif idreg == 'P':
        return VatRegimes.private
    elif idreg == 'C':
        return VatRegimes.cocontractor
    elif idreg == 'I':
        return VatRegimes.intracom
    elif idreg == 'S':
        return VatRegimes.intracom
    elif idreg == 'X':
        return VatRegimes.outside
    elif idreg == '0':
        return VatRegimes.exempt
    elif idreg == 'D':
        return VatRegimes.de
    elif idreg == 'L':
        return VatRegimes.lu

def pcmn2type(idgen):
    if idgen[0] == '6':
        return AccountTypes.expenses
    if idgen[0] == '7':
        return AccountTypes.incomes
    if idgen[0] == '4':
        return AccountTypes.liabilities
    return AccountTypes.assets

def tim2bool(x):
    if not x.strip():
        return False
    return True

def convert_gender(v):
    if v in ('W', 'F'):
        return 'F'
    if v == 'M':
        return 'M'
    return None

def mton(s, default=None):  # PriceField
    s = s.strip()
    if not s:
        return default
    if s != "GRATIS":
        # TIM accepted an (erroneous) amount '36535..23' as 36535
        # (omitting the part after the duplicated ".")
        i = s.find('..')
        if i != -1:
            s = s[:i]
        return myround(Decimal(s))
    return Decimal()

def qton(s):  # QuantityField
    return s.strip()
    # s = s.strip()
    # if s:
        # if ':' in s: return Duration(s)
        # if s.endswith('%'):
            # return Decimal(s[:-1]) / 100
        # return Decimal(s)
    # return None

def isolang(x):
    if x == 'K':
        return 'et'
    if x == 'E':
        return 'en'
    if x == 'D':
        return 'de'
    if x == 'F':
        return 'fr'
    # if x == 'N' : return 'nl'

def store_date(row, obj, rowattr, objattr):
    v = row[rowattr]
    if v:
        if isinstance(v, basestring):
            v = dateparser.parse(v)
        setattr(obj, objattr, v)

def year_num(iddoc):
    # TODO: handle data before A.D. 2000
    year = ledger.FiscalYears.from_int(2000 + int(iddoc[:2]))
    num = int(iddoc[2:])
    return (year, num)

def row2jnl(row):
    try:
        jnl = Journal.objects.get(ref=row.idjnl.strip())
    except Journal.DoesNotExist:
        return None, None, None
    year, num = year_num(row.iddoc)
    # if year < 2002:
    #     # Don't import vouchers before 2002. TODO: make this
    #     # configurable
    #     return None, None, None
    return jnl, year, num

# def country2kw(row,kw):

def try_full_clean(i):
    while True:
        try:
            i.full_clean()
        except ValidationError as e:
            if not hasattr(e, 'message_dict'):
                raise
            for k in e.message_dict.keys():
                fld = i._meta.get_field(k)
                v = getattr(i, k)
                setattr(i, k, fld.default)
                dblogger.warning(
                    "%s : ignoring value %r for %s : %s",
                    obj2str(i), v, k, e)
        return

class TimLoader(TimLoader):

    sales_gen2art = dict()
    """A dict which maps a `GEN->IdGen` to a product instance or id.

    """

    def get_customer(self, pk):
        pk = pk.strip()
        if not pk:
            return None
        pk = self.par_pk(pk)
        try:
            return contacts.Partner.objects.get(pk=pk)
        except contacts.Partner.DoesNotExist:
            return None

    def par_pk(self, pk):
        if pk.startswith('T'):
            return 3000 + int(pk[1:]) - 256
        else:
            return int(pk)

    def store(self, kw, **d):
        for k, v in d.items():
            if v is not None:
                if isinstance(v, basestring):
                    v = self.decode_string(v).strip()
            # if v:
                kw[k] = v

    def short2iso(self, s):
        if s == 'B':
            return 'BE'
        if s == 'D':
            return 'DE'
        if s == 'F':
            return 'FR'
        if s == 'L':
            return 'LU'
        if s == 'E':
            return 'ES'
        if s == 'H':
            return 'HU'
        if s == 'I':
            return 'IT'
        if s == 'USA':
            return 'US'
        if s == 'A':
            return 'AT'
        if s == 'AUS':
            return 'AU'
        if s == 'BEN':
            return 'BJ'
        if s == 'ANG':
            return 'AO'
        if s == 'TUN':
            return 'TN'
        if s == 'EST':
            return 'EE'
        if s == 'SLO':
            return 'SK'
        if s == 'S':
            return 'SE'
        if s == 'D-':
            return 'DE'
        if s == 'COL':
            return 'CO'
        if s == 'CAM':
            return 'CM'
        if s == 'SF':
            return 'FI'
        if s == 'VIE':
            return ''
        if s == 'BRA':
            return 'BR'
        return s
        # if s == 'AU': return 'AU'
        # if s == 'NL': return 'NL'
        # raise Exception("Unknown short country code %r" % s)

    def load_gen2group(self, row, **kw):
        idgen = row.idgen.strip()
        if not idgen:
            return
        if len(idgen) < self.LEN_IDGEN:
            # dclsel = row.dclsel.strip()
            kw.update(ref=idgen)
            kw.update(account_type=pcmn2type(idgen))
            self.babel2kw('libell', 'name', row, kw)
            # def names2kw(kw,*names):
                # names = [n.strip() for n in names]
                # kw.update(name=names[0])
            # names2kw(kw,row.libell1,row.libell2,row.libell3,row.libell4)
            """TIM accepts empty GEN->Libell fields. In that
            case we take the ref as name.
            """
            kw.setdefault('name', idgen)
            ag = accounts.Group(**kw)
            self.GROUPS[idgen] = ag
            yield ag

    def load_gen2account(self, row, **kw):
        idgen = row.idgen.strip()
        if not idgen:
            return
        if len(idgen) == self.LEN_IDGEN:
            ag = None
            for length in range(len(idgen), 0, -1):
                # print idgen[:length]
                ag = self.GROUPS.get(idgen[:length])
                if ag is not None:
                    break
            # dclsel = row.dclsel.strip()
            kw.update(ref=idgen)
            kw.update(group=ag)
            kw.update(type=pcmn2type(idgen))
            self.babel2kw('libell', 'name', row, kw)
            kw.update(purchases_allowed=True)
            kw.update(sales_allowed=True)
            # def names2kw(kw,*names):
                # names = [n.strip() for n in names]
                # kw.update(name=names[0])
            # names2kw(kw,row.libell1,row.libell2,row.libell3,row.libell4)
            obj = Account(**kw)
            # if idgen == "612410":
                # raise Exception(20131116)
            # dblogger.info("20131116 %s",dd.obj2str(obj))
            # dblogger.info("20131116 ACCOUNT %s ",obj)
            yield obj

    def get_account(self, idgen):
        idgen = idgen.strip()
        if not idgen:
            return None
        try:
            return accounts.Account.objects.get(ref=idgen)
        except accounts.Account.DoesNotExist:
            return None

    def load_fin(self, row, **kw):
        jnl, year, number = row2jnl(row)
        if jnl is None:
            dblogger.info("No journal %s (%s)", row.idjnl, row)
            return
        if year < START_YEAR:
            return
        kw.update(year=year)
        kw.update(number=number)
        # kw.update(id=pk)
        kw.update(entry_date=row.date)
        kw.update(voucher_date=row.date)
        kw.update(user=self.get_user())
        kw.update(balance1=mton(row.mont1, ZERO))
        kw.update(balance2=mton(row.mont2, ZERO))
        doc = jnl.create_voucher(**kw)
        self.FINDICT[(jnl, year, number)] = doc
        # print row.etat
        if row.etat == self.etat_registered:
            self.must_register.append(doc)
        return doc

    def load_fnl(self, row, **kw):
        jnl, year, number = row2jnl(row)
        if jnl is None:
            dblogger.info("No journal %s (%s)", row.idjnl, row)
            return
        if year < START_YEAR:
            return
        doc = self.FINDICT.get((jnl, year, number))
        if doc is None:
            raise Exception("FNL %r without document" %
                            list(jnl, year, number))
        try:
            kw.update(seqno=int(row.line.strip()))
        except ValueError:
            pass  # some lines contain "***"
        if row.date:
            kw.update(date=row.date)
        try:
            if row.idctr == ('V'):
                kw.update(partner_id=self.par_pk(row.idcpt.strip()))
                kw.update(
                    account=vat.TradeTypes.sales.get_main_account())
            elif row.idctr == ('E'):
                kw.update(partner_id=self.par_pk(row.idcpt.strip()))
                kw.update(
                    account=vat.TradeTypes.purchases.get_main_account())
            elif row.idctr == ('G'):
                kw.update(partner_id=self.par_pk(row.idcpt.strip()))
                kw.update(
                    account=vat.TradeTypes.wages.get_main_account())
            elif row.idctr == ('S'):
                kw.update(partner_id=self.par_pk(row.idcpt.strip()))
                kw.update(
                    account=vat.TradeTypes.clearings.get_main_account())
            else:
                a = Account.objects.get(ref=row.idcpt.strip())
                kw.update(account=a)
            kw.update(amount=mton(row.mont, ZERO))
            kw.update(dc=self.dc2lino(row.dc))
        except Exception as e:
            dblogger.warning(
                "Failed to load FNL line %s from %s : %s", row, kw, e)
            raise
        try:
            kw.update(match=row.match.strip())
            item = doc.add_voucher_item(**kw)
            # match = row.match.strip()
            # if match:
            #     lst = self.must_match.setdefault(match, [])
            #     lst.append((doc, item))
            #     # self.must_match.append((doc, item, match))
            return item
        except Exception as e:
            dblogger.warning(
                "Failed to load FNL line %s from %s : %s", row, kw, e)

    def load_ven(self, row, **kw):
        jnl, year, number = row2jnl(row)
        if jnl is None:
            dblogger.info("No journal %s (%s)", row.idjnl, row)
            return
        if year < START_YEAR:
            return
        kw.update(year=year)
        kw.update(number=number)
        kw.update(vat_regime=vat_regime(row.idreg.strip()))
        # kw.update(id=pk)
        partner = self.get_customer(row.idpar)
        if partner is None:
            raise Exception("No partner id {0} in {1}".format(row.idpar, row))
        else:
            kw.update(partner=partner)
        if jnl.trade_type.name == 'sales':
            # kw.update(imode=self.DIM)
            if row.idprj.strip():
                kw.update(project_id=int(row.idprj.strip()))
            kw.update(discount=mton(row.remise))
        elif jnl.trade_type.name == 'purchases':
            pass
            # kw.update(partner=contacts.Partner.objects.get(
            #     pk=self.par_pk(row.idpar)))
            # partner=contacts.Partner.objects.get(pk=self.par_pk(row.idpar))
        else:
            raise Exception("Unknown TradeType %r" % jnl.trade_type)
        kw.update(entry_date=row.date)
        kw.update(voucher_date=row.date)
        kw.update(user=self.get_user(row.auteur))
        kw.update(total_excl=mton(row.montr))
        kw.update(total_vat=mton(row.montt))
        kw.update(match=row.match.strip())
        doc = jnl.create_voucher(**kw)
        # doc.partner = partner
        # doc.full_clean()
        # doc.save()
        self.VENDICT[(jnl, year, number)] = doc
        if row.etat == self.etat_registered:
            self.must_register.append(doc)
        # match = row.match.strip()
        # if match:
        #     lst = self.must_match.setdefault(match, [])
        #     lst.append((doc, doc))
        #     # self.must_match.append((doc, doc, match))
        return doc

    def load_vnl(self, row, **kw):
        jnl, year, number = row2jnl(row)
        if jnl is None:
            return
        if year < START_YEAR:
            return
        doc = self.VENDICT.get((jnl, year, number))
        if doc is None:
            msg = "VNL {0} without document".format(
                [jnl.ref, year, number])
            dblogger.warning(msg)
            return
            # raise Exception(msg)
        # dblogger.info("20131116 %s %s",row.idjnl,row.iddoc)
        # doc = jnl.get_document(year,number)
        # try:
            # doc = jnl.get_document(year,number)
        # except Exception,e:
            # dblogger.warning(str(e))
            # return
        # kw.update(document=doc)
        kw.update(seqno=int(row.line.strip()))
        idart = row.idart.strip()
        if isinstance(doc, sales.VatProductInvoice):
            if row.code in ('A', 'F'):
                kw.update(product=products.Product.get_by_ref(idart))
            elif row.code == 'G':
                a = self.vnlg2product(row)
                if a is not None:
                    kw.update(product=a)
            kw.update(unit_price=mton(row.prixu))
            kw.update(qty=qton(row.qte))
        elif isinstance(doc, vat.VatAccountInvoice):
            if row.code == 'G':
                kw.update(account=idart)
        kw.update(title=row.desig.strip())
        vc = tax2vat(row.idtax)
        kw.update(vat_class=vc)
        mb = mton(row.cmont)
        mv = mton(row.montt)
        kw.update(total_base=mb)
        kw.update(total_vat=mv)
        if mb is not None and mv is not None:
            kw.update(total_incl=mb+mv)
        # kw.update(qty=row.idtax.strip())
        # kw.update(qty=row.montt.strip())
        # kw.update(qty=row.attrib.strip())
        # kw.update(date=row.date)

        # check whether we need a vat rule
        # if mv and mb:
        #     vatrule = dict(vat_class=vc, vat_regime=doc.vat_regime)
        #     vatrule.update(
        #         country=doc.partner.country or
        #         dd.plugins.countries.get_my_country())
        #     try:
        #         VatRule.objects.get(**vatrule)
        #     except VatRule.DoesNotExist:
        #         vatrule.update(rate=myround(mv / mb))
        #         yield VatRule(**vatrule)
        try:
            yield doc.add_voucher_item(**kw)
        except Exception as e:
            dblogger.warning("Failed to load VNL line %s from %s : %s",
                             row, kw, e)

    def vnlg2product(self, row):
        a = row.idart.strip()
        return self.sales_gen2art.get(a)

    # Countries already exist after initial_data, but their short_code is
    # needed as lookup field for Places.
    def load_nat(self, row):
        if not row['isocode'].strip():
            return
        try:
            country = Country.objects.get(
                isocode=row['isocode'].strip())
        except Country.DoesNotExist:
            country = Country(isocode=row['isocode'].strip())
            country.name = row['name'].strip()
        if row['idnat'].strip():
            country.short_code = row['idnat'].strip()
        return country

    def load_plz(self, row):
        pk = row.pays.strip()
        if not pk:
            return
        name = row.nom.strip() or row.cp.strip()
        if not name:
            return

        if False:  # severe
            country = Country.objects.get(isocode=self.short2iso(pk))
            # country = Country.objects.get(short_code=pk)
        else:
            try:
                country = Country.objects.get(isocode=self.short2iso(pk))
                # country = Country.objects.get(short_code=pk)
            except Country.DoesNotExist:
                dblogger.warning(
                    "Ignored PLZ %s (with invalid country %s)", row, pk)
                return
        zip_code = row['cp'].strip()
        if Place.objects.filter(zip_code=zip_code, country=country).exists():
            dblogger.warning(
                "Ignored PLZ %s (duplicate zip code %s-%s)",
                row, country.isocode, zip_code)
            return

        kw = dict(
            zip_code=zip_code,
            name=name,
            country=country,
        )
        return Place(**kw)

    def load_par(self, row):
        kw = {}
        # kw.update(
        #     street2kw(join_words(
        #         row['RUE'],
        #         row['RUENUM'],
        #         row['RUEBTE'])))

        # the following code needs the top-level (possibly abstract)
        # models:
        from lino_xl.lib.contacts.models import Person, Company
        from lino_xl.lib.households.models import Household

        self.store(kw, id=self.par_pk(row.idpar))

        cl = self.par_class(row)

        if cl is None:
            dblogger.warning(
                "Ignored PAR record %s (IdPrt %r)" % (
                    row.idpar, row.idprt))
            return

        if issubclass(cl, (Company, Person, Household)):
            email = row.email.strip()
            if email and is_valid_email(email):
                self.store(kw, email=email)

        if 'idreg' in row:
            self.store(kw, vat_regime=vat_regime(row.idreg.strip()))

        if 'idgen' in row:
            self.store(kw, purchase_account=self.get_account(row.idgen))

        if issubclass(cl, Company):
            # cl = Company
            self.store(
                kw,
                prefix=row['allo'].strip(),
                name=row.firme.strip() + ' ' + row.vorname,
            )
            if dd.is_installed('vat'):
                self.store(
                    kw, vat_id=row['notva'].strip())

        if issubclass(cl, Person):
            # self.store(kw, prefix=row.allo)
            # kw.update(**name2kw(self.decode_string(row.firme)))
            last_name = row.firme.strip()
            if row.name2.strip():
                last_name += '-' + row.name2.strip()
            self.store(
                kw,
                first_name=row['vorname'].strip(),
                last_name=last_name,
                # birth_date=row['gebdat'],
                title=row['allo'].strip(),
            )
            assert kw['first_name'] or kw['last_name']
            # depends on which dbf module is being used:
            # if 'sex' in row:
            if hasattr(row, 'sex'):
                # sex = row.get('sex', None)
                sex = row.sex
                self.store(
                    kw, gender=convert_gender(sex))
        if issubclass(cl, Household):
            self.store(
                kw,
                name=row.firme.strip() + ' ' + row.vorname.strip(),
            )
        if dd.is_installed('lists') and issubclass(cl, List):
            self.store(kw, designation=row.firme)

        if issubclass(cl, Created):
            if 'datcrea' in row:
                created = row.get('datcrea', None)
                if created:
                    created = datetime.datetime.combine(
                        created, datetime.time(0, 0, 0))
                    if settings.USE_TZ:
                        created = make_aware(created)
                    kw.update(created=created)

        # if cl is not List:
        if issubclass(cl, rt.models.contacts.Partner):
            language = isolang(row['langue'])

            if settings.SITE.get_language_info(language):
                self.store(kw, language=language)

            if 'memo' in row:
                self.store(
                    kw, remarks=self.dbfmemo(row.get('memo') or ''))

            isocode = self.short2iso(row.pays.strip())
            if isocode:
                try:
                    country = Country.objects.get(
                        isocode=isocode)
                except Country.DoesNotExist:
                    country = Country(isocode=isocode,
                                      name=isocode)
                    country.save()
                kw.update(country=country)

                zip_code = row['cp'].strip()
                if zip_code:
                    kw.update(zip_code=zip_code)
                    qs = Place.objects.filter(
                        country=country,
                        zip_code__exact=zip_code,
                    )
                    if qs.count() == 0:
                        city = Place(zip_code=zip_code,
                                     name=zip_code,
                                     country=country)
                        city.save()
                        kw.update(city=city)
                    else:
                        kw.update(city=qs[0])
                        s = self.duplicate_zip_codes.get(country, set([]))
                        s.add(zip_code)

            self.store(
                kw,
                phone=row['tel'].strip(),
                fax=row['fax'].strip(),
                street=row['rue'].strip(),
                street_no=row['ruenum'],
                street_box=row['ruebte'].strip(),
            )

            # kw.update(street2kw(join_words(row['RUE'],
            # row['RUENUM'],row['RUEBTE'])))

        try:
            obj = cl(**kw)
        except Exception:
            dblogger.warning("Failed to instantiate %s from %s",
                             cl, kw)
            raise
        yield obj

        def compte2iban(s, **kw):
            a = s.split(':')
            if len(a) == 1:
                kw.update(iban=s)
            elif len(a) == 2:
                kw.update(bic=a[0])
                kw.update(iban=a[1])
            else:
                kw.update(iban=s)
            return kw

        if not dd.is_installed('sepa'):
            return

        compte1 = row['compte1'].strip()
        if compte1:
            obj.full_clean()
            obj.save()
            kw = compte2iban(compte1, partner=obj, primary=True)
            if kw['iban']:
                obj = sepa.Account(**kw)
                try:
                    obj.full_clean()
                    yield obj
                except ValidationError:
                    dblogger.warning(
                        "Ignored invalid PAR->Compte1 %r", compte1)

    def load_prj(self, row, **kw):
        pk = int(row.idprj.strip())
        kw.update(id=pk)
        if row.parent.strip():
            kw.update(parent_id=int(row.parent))
        kw.update(name=row.name1.strip())
        # if row.idpar.strip():
        #     kw.update(partner_id=self.par_pk(row.idpar.strip()))

        kw.update(ref=row.seq.strip())
        # kw.update(user=self.get_user(None))
        desc = self.dbfmemo(row.abstract).strip() + '\n\n' + self.dbfmemo(row.body)
        # kw.update(summary=self.dbfmemo(row.abstract))
        kw.update(description=desc)
        return tickets.Project(**kw)

    def load_pin(self, row, **kw):
        pk = int(row.idpin)
        kw.update(id=pk)
        if row.idprj.strip():
            kw.update(project_id=int(row.idprj))
            # kw.update(partner_id=PRJPAR.get(int(row.idprj),None))
        kw.update(summary=row.short.strip())
        kw.update(description=self.dbfmemo(row.memo))
        kw.update(state=ticket_state(row.idpns))
        kw.update(closed=row.closed)
        kw.update(created=row['date'])
        kw.update(modified=datetime.datetime.now())
        kw.update(reporter=self.get_user(row.idusr))
        return tickets.Ticket(**kw)
        # if row.idpar.strip():
        #     kw = dict(project=obj)
        #     kw.update(partner_id=self.par_pk(row.idpar))
        #     yield tickets.Sponsorship(**kw)

    def load_art(self, row, **kw):
        # try:
        #     pk = int(row.idart)
        # except ValueError as e:
        #     dblogger.warning("Ignored %s: %s", row, e)
        #     # return
        idart = row.idart.strip()
        if not idart:
            dblogger.warning("Ignored %s: ART->IdArt is empty", row)
            return
        kw.update(ref=idart)
        # if pk == 0:
        #     pk = 1000  # mysql doesn't accept value 0
        # kw.update(id=pk)
        self.babel2kw('name', 'name', row, kw)
        # dblogger.info("20140823 product %s", kw)
        kw.setdefault('name', idart)
        return products.Product(**kw)

    def create_users(self):

        self.ROOT = users.User(
            username='tim', first_name='tim',
            id=1,
            user_type=users.UserTypes.admin)
        self.ROOT.set_password("1234")
        # if isinstance(self.ROOT, rt.models.contacts.Partner):
        #     self.ROOT.name = "tim"
        yield self.ROOT

    def get_user(self, idusr=None):
        return self.ROOT

    def objects(tim):

        self = tim

        yield self.create_users()

        # settings.SITE.loading_from_dump = True

        if False:
            self.DIM = sales.InvoicingMode(name='Default')
            yield self.DIM

        # yield sales.Invoice.create_journal('sales',
        #    chart=self.CHART,name="Verkaufsrechnungen",ref="VKR")
        # yield ledger.AccountInvoice.create_journal('purchases',
        #    chart=self.CHART,name="Einkaufsrechnungen",ref="EKR")
        # from lino.modlib.users import models as users
        # ROOT = users.User.objects.get(username='root')
        # DIM = sales.InvoicingMode.objects.get(name='Default')
        yield tim.load_dbf('GEN', self.load_gen2group)
        yield tim.load_dbf('GEN', self.load_gen2account)

        yield dpy.FlushDeferredObjects

        self.after_gen_load()

        yield tim.load_dbf('ART')
        yield tim.load_dbf('JNL')

        yield dpy.FlushDeferredObjects

        # yield tim.load_dbf('NAT')
        yield tim.load_dbf('PLZ')
        yield tim.load_dbf('PAR')

        # from lino_xl.lib.vat.fixtures import euvatrates
        # yield euvatrates.objects()

        if False:
            settings.SITE.loading_from_dump = True
            yield tim.load_dbf('PRJ')
            yield dpy.FlushDeferredObjects
            settings.SITE.loading_from_dump = False

        """
        We need a FlushDeferredObjects here because most Project
        objects don't get saved at the first attempt
        """

        if False:  # GET_THEM_ALL:

            yield tim.load_dbf('VEN')
            yield tim.load_dbf('VNL')

            yield tim.load_dbf('FIN')
            yield tim.load_dbf('FNL')


text:
using System.Collections.Generic;
using MyVote.BusinessObjects.Contracts;

namespace MyVote.BusinessObjects
{
	public sealed class ActivatorCallContext
		: ICallContext
	{
		// Note: If any of the BOs ever do any async operations,
		// this will probably fail.
		private readonly IDictionary<string, object> values =
			new Dictionary<string, object>();

		public void FreeNamedDataSlot(string name)
		{
			this.values.Remove(name);
		}

		public T GetData<T>(string name)
			where T: class
		{
			return this.values.ContainsKey(name) ?
				this.values[name] as T : null as T;
		}

		public void SetData<T>(string name, T value)
			where T: class
		{
			this.values.Add(name, value);
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
<?php

/* $Platon$ */

/* Modeline for ViM {{{
 * vim: set ts=4:
 * vim600: fdm=marker fdl=0 fdc=0:
 * }}} */

// This script will make DROP queries for getting rid of tables that have the same prefix
// (i.e. tables logs_*). This makes it easier to clean up old data.
//

$basePath = dirname( __FILE__ );
include_once "$basePath/../html/includes/common_funcs.php";
include_once "$basePath/../html/config/config.php";

if (!mysql_connect(DBHOST, DBADMIN, DBADMINPW)) {
	print 'Could not connect to mysql';
	exit;
}

$result = mysql_list_tables(DBNAME);

if (!$result) {
	print "DB Error, could not list tables\n";
	print 'MySQL Error: ' . mysql_error();
	exit;
}

if ($_GET['prefix'] == null) {
	print "TABLE LIST:
";

	while ($row = mysql_fetch_row($result)) {
		print "Table: $row[0]
";
	}
	print "
Syntax to make a DROP TABLE is 'drop_tables.php?prefix=\"prefix that the tables have\"'.";
} else {

	echo "DROP TABLE QUERY FOR TABLES WITH PREFIX '".$_GET['prefix']."'
Copy this query into your MySQL program and execute to remove these tables.

";

	while ($row = mysql_fetch_row($result)) {
		if (substr($row[0], 0, strlen($_GET['prefix'])) == $_GET['prefix']) {
			print "DROP TABLE $row[0];
";
		}
	}
}

mysql_free_result($result);
?>


text:
/* signal_functions.h

   Header file for signal_functions.c.
*/
#ifndef SIGNAL_FUNCTIONS_H
#define SIGNAL_FUNCTIONS_H

#include <signal.h>
#include "tlpi_hdr.h"

int printSigMask(FILE *of, const char *msg);

int printPendingSigs(FILE *of, const char *msg);

void printSigset(FILE *of, const char *ldr, const sigset_t *mask);

#endif


text:
<?php

namespace OGIS\IndexBundle\EventListener;

use FOS\UserBundle\FOSUserEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Acl\Domain\ObjectIdentity;
use Symfony\Component\Security\Acl\Domain\UserSecurityIdentity;
use Symfony\Component\Security\Acl\Permission\MaskBuilder;
use FOS\UserBundle\Event\UserEvent;
use FOS\UserBundle\Model\UserInterface;
use OGIS\IndexBundle\Entity\User;
use OGIS\IndexBundle\Entity\Role;
use OGIS\IndexBundle\Entity\Catalog;

class UserExtraFieldAssignmentListener implements EventSubscriberInterface {

		protected $entityManager;
		protected $aclProvider;
		protected $tokenStorage;

		public function __construct($entityManager, $aclProvider, $tokenStorage){
				$this->entityManager = $entityManager;
				$this->aclProvider = $aclProvider;
				$this->tokenStorage = $tokenStorage;
		}

		public static function getSubscribedEvents(){
				return array( FOSUserEvents::REGISTRATION_COMPLETED => 'onRegistrationSuccessful' );
		}

		public function onRegistrationSuccessful(UserEvent $event){
				$user = $event->getUser();

				// set user display name using username as default value
				$user->setDisplayName($user->getUsername());
				// update user role to 'proper' value and add limits to user
				$user->setRoles(array('ROLE_USER'));
				$limits = $this->entityManager->getRepository('OGIS\IndexBundle\Entity\Role')->findOneBy(array('role' => 'ROLE_USER'));
				$user->setLimits($limits);

				// create catalogs for the user
				$catalog = new Catalog();
				$catalog->addOwner($user);
				$catalog->setTitle($user->getDisplayName() . '\'s resources');
				$this->entityManager->persist($catalog);
				$this->entityManager->flush();

				// bind catalog to user
				$user->addCatalog($catalog);

				// ACL
				$objectIdentity = ObjectIdentity::fromDomainObject($catalog);
				try{
						$acl = $this->aclProvider->findAcl($objectIdentity);
				}catch (\Symfony\Component\Security\Acl\Exception\AclNotFoundException $e) {
						$acl = $this->aclProvider->createAcl($objectIdentity);
				}
				$securityIdentity = UserSecurityIdentity::fromAccount($user);
				$acl->insertObjectAce($securityIdentity, MaskBuilder::MASK_OWNER);
				$this->aclProvider->updateAcl($acl);
		}
}


text:
import client_intf
import string
import re
import types
from sys import stderr

# control verbosity of error output
verbose = 1

secLevelMap = { 'noAuthNoPriv':1, 'authNoPriv':2, 'authPriv':3 }

def _parse_session_args(kargs):
    sessArgs = {
        'Version':3,
        'DestHost':'localhost',
        'Community':'public',
        'Timeout':1000000,
        'Retries':3,
        'RemotePort':161,
        'LocalPort':0,
        'SecLevel':'noAuthNoPriv',
        'SecName':'initial',
        'PrivProto':'DEFAULT',
        'PrivPass':'',
        'AuthProto':'DEFAULT',
        'AuthPass':'',
        'ContextEngineId':'',
        'SecEngineId':'',
        'Context':'',
        'Engineboots':0,
        'Enginetime':0,
        'UseNumeric':0,
        }
    keys = kargs.keys()
    for key in keys:
        if sessArgs.has_key(key):
            sessArgs[key] = kargs[key]
        else:
            print >>stderr, "ERROR: unknown key", key
    return sessArgs

def STR(obj):
    if obj != None:
        obj = str(obj)
    return obj

class Varbind(object):
    def __init__(self, tag=None, iid=None, val=None, type=None):
        self.tag = STR(tag)
        self.iid = STR(iid)
        self.val = STR(val)
        self.type = STR(type)
        # parse iid out of tag if needed
        if iid == None and tag != None:
            regex = re.compile(r'^((?:\.\d+)+|(?:\w+(?:[-:]*\w+)+))\.?(.*)$')
            match = regex.match(tag)
            if match:
                (self.tag, self.iid) = match.group(1,2)

    def __setattr__(self, name, val):
        self.__dict__[name] = STR(val)

    def print_str(self):
        return self.tag, self.iid, self.val, self.type

class VarList(object):
    def __init__(self, *vs):
        self.varbinds = []

        for var in vs:
            if isinstance(var, netsnmp.client.Varbind):
                self.varbinds.append(var)
            else:
                self.varbinds.append(Varbind(var))

    def __len__(self):
        return len(self.varbinds)

    def __getitem__(self, index):
        return self.varbinds[index]

    def __setitem__(self, index, val):
        if isinstance(val, netsnmp.client.Varbind):
            self.varbinds[index] = val
        else:
            raise TypeError

    def __iter__(self):
        return iter(self.varbinds)

    def __delitem__(self, index):
        del self.varbinds[index]

    def __repr__(self):
        return repr(self.varbinds)

    def __getslice__(self, i, j):
        return self.varbinds[i:j]

    def append(self, *vars):
         for var in vars:
            if isinstance(var, netsnmp.client.Varbind):
                self.varbinds.append(var)
            else:
                raise TypeError

class Session(object):
    def __init__(self, **args):
        self.sess_ptr = None
        self.UseLongNames = 0
        self.UseNumeric = 0
        self.UseSprintValue = 0
        self.UseEnums = 0
        self.BestGuess = 0
        self.RetryNoSuch = 0
        self.ErrorStr = ''
        self.ErrorNum = 0
        self.ErrorInd = 0

        sess_args = _parse_session_args(args)

        for k,v in sess_args.items():
            self.__dict__[k] = v

        if sess_args['Version'] == 3:
            self.sess_ptr = client_intf.session_v3(
                sess_args['Version'],
                sess_args['DestHost'],
                sess_args['LocalPort'],
                sess_args['Retries'],
                sess_args['Timeout'],
                sess_args['SecName'],
                secLevelMap[sess_args['SecLevel']],
                sess_args['SecEngineId'],
                sess_args['ContextEngineId'],
                sess_args['Context'],
                sess_args['AuthProto'],
                sess_args['AuthPass'],
                sess_args['PrivProto'],
                sess_args['PrivPass'],
                sess_args['Engineboots'],
                sess_args['Enginetime'])
        else:
            self.sess_ptr = client_intf.session(
                sess_args['Version'],
                sess_args['Community'],
                sess_args['DestHost'],
                sess_args['LocalPort'],
                sess_args['Retries'],
                sess_args['Timeout'])

    def get(self, varlist):
        res = client_intf.get(self, varlist)
        return res

    def set(self, varlist):
        res = client_intf.set(self, varlist)
        return res

    def getnext(self, varlist):
        res = client_intf.getnext(self, varlist)
        return res

    def getbulk(self, nonrepeaters, maxrepetitions, varlist):
        if self.Version == 1:
            return None
        res = client_intf.getbulk(self, nonrepeaters, maxrepetitions, varlist)
        return res

    def walk(self, varlist):
        res = client_intf.walk(self, varlist)
        return res

    def __del__(self):
        res = client_intf.delete_session(self)
        return res

import netsnmp

def snmpget(*args, **kargs):
    sess = Session(**kargs)
    var_list = VarList()
    for arg in args:
        if isinstance(arg, netsnmp.client.Varbind):
            var_list.append(arg)
        else:
            var_list.append(Varbind(arg))
    res = sess.get(var_list)
    return res

def snmpset(*args, **kargs):
    sess = Session(**kargs)
    var_list = VarList()
    for arg in args:
        if isinstance(arg, netsnmp.client.Varbind):
            var_list.append(arg)
        else:
            var_list.append(Varbind(arg))
    res = sess.set(var_list)
    return res

def snmpgetnext(*args, **kargs):
    sess = Session(**kargs)
    var_list = VarList()
    for arg in args:
        if isinstance(arg, netsnmp.client.Varbind):
            var_list.append(arg)
        else:
            var_list.append(Varbind(arg))
    res = sess.getnext(var_list)
    return res

def snmpgetbulk(nonrepeaters, maxrepetitions,*args, **kargs):
    sess = Session(**kargs)
    var_list = VarList()
    for arg in args:
        if isinstance(arg, netsnmp.client.Varbind):
            var_list.append(arg)
        else:
            var_list.append(Varbind(arg))
    res = sess.getbulk(nonrepeaters, maxrepetitions, var_list)
    return res

def snmpwalk(*args, **kargs):
    sess = Session(**kargs)
    if isinstance(args[0], netsnmp.client.VarList):
        var_list = args[0]
    else:
        var_list = VarList()
        for arg in args:
            if isinstance(arg, netsnmp.client.Varbind):
                var_list.append(arg)
            else:
                var_list.append(Varbind(arg))
    res = sess.walk(var_list)
    return res


text:
crawler
=======

Async crawler in python 3


text:
<?php namespace Vdbf\Components\Twinfield\Entity;

use Vdbf\Components\Twinfield\Entity;

class GeneralLedger extends Entity
{

}


text:
using System;
using System.Collections.Generic;

namespace Flurl.Http
{
	/// <summary>
	/// URL builder extension methods on FlurlRequest
	/// </summary>
	public static class UrlBuilderExtensions
	{
		/// <summary>
		/// Appends a segment to the URL path, ensuring there is one and only one '/' character as a seperator.
		/// </summary>
		/// <param name="request">The IFlurlRequest associated with the URL</param>
		/// <param name="segment">The segment to append</param>
		/// <param name="fullyEncode">If true, URL-encodes reserved characters such as '/', '+', and '%'. Otherwise, only encodes strictly illegal characters (including '%' but only when not followed by 2 hex characters).</param>
		/// <returns>This IFlurlRequest</returns>
		/// <exception cref="ArgumentNullException"><paramref name="segment"/> is <see langword="null" />.</exception>
		public static IFlurlRequest AppendPathSegment(this IFlurlRequest request, object segment, bool fullyEncode = false) {
			request.Url.AppendPathSegment(segment, fullyEncode);
			return request;
		}

		/// <summary>
		/// Appends multiple segments to the URL path, ensuring there is one and only one '/' character as a seperator.
		/// </summary>
		/// <param name="request">The IFlurlRequest associated with the URL</param>
		/// <param name="segments">The segments to append</param>
		/// <returns>This IFlurlRequest</returns>
		public static IFlurlRequest AppendPathSegments(this IFlurlRequest request, params object[] segments) {
			request.Url.AppendPathSegments(segments);
			return request;
		}

		/// <summary>
		/// Appends multiple segments to the URL path, ensuring there is one and only one '/' character as a seperator.
		/// </summary>
		/// <param name="request">The IFlurlRequest associated with the URL</param>
		/// <param name="segments">The segments to append</param>
		/// <returns>This IFlurlRequest</returns>
		public static IFlurlRequest AppendPathSegments(this IFlurlRequest request, IEnumerable<object> segments) {
			request.Url.AppendPathSegments(segments);
			return request;
		}

		/// <summary>
		/// Adds a parameter to the URL query, overwriting the value if name exists.
		/// </summary>
		/// <param name="request">The IFlurlRequest associated with the URL</param>
		/// <param name="name">Name of query parameter</param>
		/// <param name="value">Value of query parameter</param>
		/// <param name="nullValueHandling">Indicates how to handle null values. Defaults to Remove (any existing)</param>
		/// <returns>This IFlurlRequest</returns>
		public static IFlurlRequest SetQueryParam(this IFlurlRequest request, string name, object value, NullValueHandling nullValueHandling = NullValueHandling.Remove) {
			request.Url.SetQueryParam(name, value, nullValueHandling);
			return request;
		}

		/// <summary>
		/// Adds a parameter to the URL query, overwriting the value if name exists.
		/// </summary>
		/// <param name="request">The IFlurlRequest associated with the URL</param>
		/// <param name="name">Name of query parameter</param>
		/// <param name="value">Value of query parameter</param>
		/// <param name="isEncoded">Set to true to indicate the value is already URL-encoded</param>
		/// <param name="nullValueHandling">Indicates how to handle null values. Defaults to Remove (any existing)</param>
		/// <returns>This IFlurlRequest</returns>
		/// <exception cref="ArgumentNullException"><paramref name="name"/> is <see langword="null" />.</exception>
		public static IFlurlRequest SetQueryParam(this IFlurlRequest request, string name, string value, bool isEncoded = false, NullValueHandling nullValueHandling = NullValueHandling.Remove) {
			request.Url.SetQueryParam(name, value, isEncoded, nullValueHandling);
			return request;
		}

		/// <summary>
		/// Adds a parameter without a value to the URL query, removing any existing value.
		/// </summary>
		/// <param name="request">The IFlurlRequest associated with the URL</param>
		/// <param name="name">Name of query parameter</param>
		/// <returns>This IFlurlRequest</returns>
		public static IFlurlRequest SetQueryParam(this IFlurlRequest request, string name) {
			request.Url.SetQueryParam(name);
			return request;
		}

		/// <summary>
		/// Parses values (usually an anonymous object or dictionary) into name/value pairs and adds them to the URL query, overwriting any that already exist.
		/// </summary>
		/// <param name="request">The IFlurlRequest associated with the URL</param>
		/// <param name="values">Typically an anonymous object, ie: new { x = 1, y = 2 }</param>
		/// <param name="nullValueHandling">Indicates how to handle null values. Defaults to Remove (any existing)</param>
		/// <returns>This IFlurlRequest</returns>
		public static IFlurlRequest SetQueryParams(this IFlurlRequest request, object values, NullValueHandling nullValueHandling = NullValueHandling.Remove) {
			request.Url.SetQueryParams(values, nullValueHandling);
			return request;
		}

		/// <summary>
		/// Adds multiple parameters without values to the URL query.
		/// </summary>
		/// <param name="request">The IFlurlRequest associated with the URL</param>
		/// <param name="names">Names of query parameters.</param>
		/// <returns>This IFlurlRequest</returns>
		public static IFlurlRequest SetQueryParams(this IFlurlRequest request, IEnumerable<string> names) {
			request.Url.SetQueryParams(names);
			return request;
		}

		/// <summary>
		/// Adds multiple parameters without values to the URL query.
		/// </summary>
		/// <param name="request">The IFlurlRequest associated with the URL</param>
		/// <param name="names">Names of query parameters</param>
		/// <returns>This IFlurlRequest</returns>
		public static IFlurlRequest SetQueryParams(this IFlurlRequest request, params string[] names) {
			request.Url.SetQueryParams(names as IEnumerable<string>);
			return request;
		}

		/// <summary>
		/// Removes a name/value pair from the URL query by name.
		/// </summary>
		/// <param name="request">The IFlurlRequest associated with the URL</param>
		/// <param name="name">Query string parameter name to remove</param>
		/// <returns>This IFlurlRequest</returns>
		public static IFlurlRequest RemoveQueryParam(this IFlurlRequest request, string name) {
			request.Url.RemoveQueryParam(name);
			return request;
		}

		/// <summary>
		/// Removes multiple name/value pairs from the URL query by name.
		/// </summary>
		/// <param name="request">The IFlurlRequest associated with the URL</param>
		/// <param name="names">Query string parameter names to remove</param>
		/// <returns>This IFlurlRequest</returns>
		public static IFlurlRequest RemoveQueryParams(this IFlurlRequest request, params string[] names) {
			request.Url.RemoveQueryParams(names);
			return request;
		}

		/// <summary>
		/// Removes multiple name/value pairs from the URL query by name.
		/// </summary>
		/// <param name="request">The IFlurlRequest associated with the URL</param>
		/// <param name="names">Query string parameter names to remove</param>
		/// <returns>This IFlurlRequest</returns>
		public static IFlurlRequest RemoveQueryParams(this IFlurlRequest request, IEnumerable<string> names) {
			request.Url.RemoveQueryParams(names);
			return request;
		}

		/// <summary>
		/// Set the URL fragment fluently.
		/// </summary>
		/// <param name="request">The IFlurlRequest associated with the URL</param>
		/// <param name="fragment">The part of the URL afer #</param>
		/// <returns>This IFlurlRequest</returns>
		public static IFlurlRequest SetFragment(this IFlurlRequest request, string fragment) {
			request.Url.SetFragment(fragment);
			return request;
		}

		/// <summary>
		/// Removes the URL fragment including the #.
		/// </summary>
		/// <param name="request">The IFlurlRequest associated with the URL</param>
		/// <returns>This IFlurlRequest</returns>
		public static IFlurlRequest RemoveFragment(this IFlurlRequest request) {
			request.Url.RemoveFragment();
			return request;
		}
	}
}


text:
/*jslint node: true */

'use strict';

if (process.argv[2] == null) {
  console.log("Filename as argument must be provided.");
  process.exit(1);
}

var fs = require('fs');
var needle = require('needle');
var q = require('q');

var apiUrl = {
  global: 'https://twitchemotes.com/api_cache/v2/global.json',
  subscriber: 'https://twitchemotes.com/api_cache/v2/subscriber.json',
  betterttv: 'https://api.betterttv.net/2/emotes'
};

function download(url, callback) {
  var deferred = q.defer();
  needle.get(url, function (error, response) {
    if (!error && response.statusCode === 200) {
      deferred.resolve(response);
    } else {
      deferred.reject(error);
    }
  });
  return deferred.promise;
}

function parseGlobal(obj) {
  var newObj = {};
  Object.keys(obj.emotes).forEach(function (key) {
    newObj[key] = obj.emotes[key].image_id;
  });
  return newObj;
}

function parseSubscriber(obj) {
  var newObj = {};
  for (var i in obj.channels) {
    newObj[i] = {};
    for (var j in obj.channels[i].emotes) {
        var key = obj.channels[i].emotes[j].code;
        var value = obj.channels[i].emotes[j].image_id;
        newObj[i][key] = value;
    }
  }
  return newObj;
}

function parseBetterttv(obj) {
  var newObj = {}, i, key = '', value = '';
  if (obj.hasOwnProperty('emotes')) {
    obj.emotes.forEach(function (emote) {
      newObj[emote.code] = emote.id;
    });
  }
  return newObj;
}

function save(filename, data) {
  var deferred = q.defer();
  fs.writeFile(filename, data, function (err) {
    if (err) {
      deferred.reject(err);
    } else {
      deferred.resolve(true);
    }
  });
  return deferred.promise;
}

var emotesGlobal = {};
var emotesSubscriber = {};
var emotesBetterttv = {};

q.all([
  download(apiUrl.global),
  download(apiUrl.subscriber),
  download(apiUrl.betterttv)
]).spread(function (resGlobal, resSubscriber, resBetterttv) {
  emotesGlobal = parseGlobal(resGlobal.body);
  emotesSubscriber = parseSubscriber(resSubscriber.body);
  emotesBetterttv = parseBetterttv(resBetterttv.body);
}).then(function () {
  return save(process.argv[2], JSON.stringify({
    global: emotesGlobal,
    subscriber: emotesSubscriber,
    betterttv: emotesBetterttv
  }));
}).then(function () {
  console.log('Emotes saved.');
}).fail(function (err) {
  console.log('Error:', err);
});


text:
package org.sparkcommerce.openadmin.dto;

import java.util.Map;

/**
 * The current state of an entity
 *
 * @author Jeff Fischer
 */
public interface StateDescriptor {

    Property[] getProperties();

    Property findProperty(String name);

    Map<String, Property> getPMap();

}


text:
ITEM.Name = "Shadow Daggers" .. " | " .. "Gamma Doppler"
ITEM.Price = 20000
ITEM.Model = "models/weapons/w_csgo_push.mdl"
ITEM.Skin = 19
ITEM.WeaponClass = "csgo_daggers_gamma_doppler"

function ITEM:OnEquip(ply)
	ply:Give(self.WeaponClass)
end

function ITEM:OnBuy(ply)
	ply:Give(self.WeaponClass)
	ply:SelectWeapon(self.WeaponClass)
end

function ITEM:OnSell(ply)
	ply:StripWeapon(self.WeaponClass)
end

function ITEM:OnHolster(ply)
	ply:StripWeapon(self.WeaponClass)
end


text:
**To delete an API within the specified region**

Command::

  aws apigateway delete-rest-api --rest-api-id 1234123412 --region us-west-2


text:
import { IterableDiffers } from './differs/iterable_differs';
import { DefaultIterableDifferFactory } from './differs/default_iterable_differ';
import { KeyValueDiffers } from './differs/keyvalue_differs';
import { DefaultKeyValueDifferFactory } from './differs/default_keyvalue_differ';
import { CONST_EXPR } from 'angular2/src/facade/lang';
export { DefaultKeyValueDifferFactory, KeyValueChangeRecord } from './differs/default_keyvalue_differ';
export { DefaultIterableDifferFactory, CollectionChangeRecord } from './differs/default_iterable_differ';
export { ChangeDetectionStrategy, CHANGE_DETECTION_STRATEGY_VALUES, ChangeDetectorState, CHANGE_DETECTOR_STATE_VALUES, isDefaultChangeDetectionStrategy } from './constants';
export { ChangeDetectorRef } from './change_detector_ref';
export { IterableDiffers } from './differs/iterable_differs';
export { KeyValueDiffers } from './differs/keyvalue_differs';
export { WrappedValue, ValueUnwrapper, SimpleChange, devModeEqual, looseIdentical, uninitialized } from './change_detection_util';
/**
 * Structural diffing for `Object`s and `Map`s.
 */
export const keyValDiff = CONST_EXPR([CONST_EXPR(new DefaultKeyValueDifferFactory())]);
/**
 * Structural diffing for `Iterable` types such as `Array`s.
 */
export const iterableDiff = CONST_EXPR([CONST_EXPR(new DefaultIterableDifferFactory())]);
export const defaultIterableDiffers = CONST_EXPR(new IterableDiffers(iterableDiff));
export const defaultKeyValueDiffers = CONST_EXPR(new KeyValueDiffers(keyValDiff));


text:
/* jshint node: true */

module.exports = function(environment) {
  var backendUrl = 'http://localhost:6500';

  if (environment === 'development-loc') {
    // Use `ember s -e development-loc` command for local backend usage.
    backendUrl = 'http://localhost:6170';
  }

  var ENV = {
    modulePrefix: 'dummy',
    environment: environment,
    baseURL: '/',
    locationType: 'hash',
    EmberENV: {
      FEATURES: {
        // Here you can enable experimental features on an ember canary build
        // e.g. 'with-controller': true
      }
    },

    APP: {
      // Application name
      name: 'dummy',

      // Here you can pass flags/options to your application instance
      // when it is created
      backendUrl: backendUrl,

      // It's a custom property, used to prevent duplicate backend urls in sources.
      backendUrls: {
        root: backendUrl,
        api: backendUrl + '/odata'
      },

      // Log service settings.
      log: {
        // Flag: indicates whether log service is enabled or not.
        enabled: false,

        // Flag: indicates whether to store error messages or not.
        storeErrorMessages: true
      },

      // Flag: indicates whether to use user settings service or not.
      useUserSettingsService: true,

      resolveWithoutDeviceTypeDetection: [
        'component:flexberry-objectlistview',
        'component:flexberry-groupedit',
        'component:object-list-view',
        'component:object-list-view-row',
        'template:components/object-list-view',
        'template:components/object-list-view-row',
      ],

      // Custom property with components settings.
      components: {
        // Settings for flexberry-file component.
        flexberryFile: {
          // URL of file upload controller.
          uploadUrl: backendUrl + '/api/File',

          // Max file size in bytes for uploading files.
          maxUploadFileSize: null,

          // Flag: indicates whether to upload file on controllers modelPreSave event.
          uploadOnModelPreSave: true,

          // Flag: indicates whether to show upload button or not.
          showUploadButton: true,

          // Flag: indicates whether to show modal dialog on upload errors or not.
          showModalDialogOnUploadError: true,

          // Flag: indicates whether to show modal dialog on download errors or not.
          showModalDialogOnDownloadError: true,
        }
      }
    }
  };

  // Read more about CSP:
  // http://www.ember-cli.com/#content-security-policy
  // https://github.com/rwjblue/ember-cli-content-security-policy
  // http://content-security-policy.com
  ENV.contentSecurityPolicy = {
    'style-src': "'self' 'unsafe-inline' https://fonts.googleapis.com",
    'font-src': "'self' data: https://fonts.gstatic.com",
    'connect-src': "'self' " + ENV.APP.backendUrls.root
  };

  // Read more about ember-i18n: https://github.com/jamesarosen/ember-i18n.
  ENV.i18n = {
    // Should be defined to avoid ember-i18n deprecations.
    // Locale will be changed then to navigator current locale (in instance initializer).
    defaultLocale: 'en'
  };

  // Read more about ember-moment: https://github.com/stefanpenner/ember-moment.
  // Locale will be changed then to same as ember-i18n locale (and will be changed every time when i18n locale changes).
  ENV.moment = {
    outputFormat: 'L'
  };

  if (environment === 'development') {
    // ENV.APP.LOG_RESOLVER = true;
    // ENV.APP.LOG_ACTIVE_GENERATION = true;
    // ENV.APP.LOG_TRANSITIONS = true;
    // ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
    // ENV.APP.LOG_VIEW_LOOKUPS = true;
  }

  if (environment === 'test') {
    // Testem prefers this...
    ENV.baseURL = '/';
    ENV.locationType = 'none';

    // keep test console output quieter
    ENV.APP.LOG_ACTIVE_GENERATION = false;
    ENV.APP.LOG_VIEW_LOOKUPS = false;

    ENV.APP.rootElement = '#ember-testing';
  }

  if (environment === 'production') {

  }

  return ENV;
};


text:
package com.ettrema.json;

import com.bradmcevoy.http.Auth;
import com.bradmcevoy.http.GetableResource;
import com.bradmcevoy.http.HttpManager;
import com.bradmcevoy.http.PropFindableResource;
import com.bradmcevoy.http.Range;
import com.bradmcevoy.http.Request;
import com.bradmcevoy.http.Request.Method;
import com.bradmcevoy.http.exceptions.BadRequestException;
import com.bradmcevoy.http.exceptions.NotAuthorizedException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PropFindJsonResource extends JsonResource implements GetableResource {

    private static final Logger log = LoggerFactory.getLogger( PropFindJsonResource.class );

    private final PropFindableResource wrappedResource;
    private final JsonPropFindHandler jsonPropFindHandler;
    private final String encodedUrl;

    public PropFindJsonResource(PropFindableResource wrappedResource, JsonPropFindHandler jsonPropFindHandler, String encodedUrl, Long maxAgeSecs) {
        super(wrappedResource, Request.Method.PROPFIND.code, maxAgeSecs);
        this.wrappedResource = wrappedResource;
        this.encodedUrl = encodedUrl;
        this.jsonPropFindHandler = jsonPropFindHandler;
    }

	@Override
    public void sendContent(OutputStream out, Range range, Map<String, String> params, String contentType) throws IOException, NotAuthorizedException, BadRequestException {
        //jsonPropFindHandler.sendContent( wrappedResource, encodedUrl, out, range, params, contentType );
        jsonPropFindHandler.sendContent(wrappedResource, encodedUrl, out, range, params, contentType);
    }

    @Override
    public Method applicableMethod() {
        return Method.PROPFIND;
    }

    /**
     * Overridden to allow clients to specifiy the max age as a request parameter
     *
     * This is to allow efficient browser caching of results in cases that need it,
     * while also permitting non-cached access
     *
     * @param auth
     * @return
     */
    @Override
    public Long getMaxAgeSeconds(Auth auth) {
        Request req = HttpManager.request();
        if (req != null) {
            String sMaxAge = req.getParams().get("maxAgeSecs");
            if (sMaxAge != null && sMaxAge.length() > 0) {
                try {
                    log.trace("using max age from parameter");
                    Long maxAge = Long.parseLong(sMaxAge);
                    return maxAge;
                } catch (NumberFormatException e) {
                    log.debug("Couldnt parse max age parameter: " + sMaxAge);
                }
            }
        }
        return super.getMaxAgeSeconds(auth);
    }

}


text:
require 'rails/generators'
module PolymorphicAttachments
  module Generators
    class InstallGenerator < Rails::Generators::Base

      desc "install basic files"
      source_root File.expand_path("../templates", __FILE__)

      def add_initializer
        path = "#{Rails.root}/config/initializers/polymorphic_attachments.rb"
        if File.exists?(path)
          puts "Skipping config/initializers/polymorphic_attachments.rb creation, as file already exists!"
        else
          puts "Adding polymorphic_attachments initializer (config/initializers/polymorphic_attachments.rb)..."
          template "config/initializers/polymorphic_attachments.rb", path
        end
      end

      def add_routes
        route 'mount PolymorphicAttachments::Engine, at: "/polymorphic_attachments"'
      end

      def add_migrations
        migration_num = Time.now.strftime("%Y%m%d%H%M%S")
        template "attachments_migration.rb", File.join('db/migrate', '', "#{migration_num}_create_polymorphic_attachments.rb")

      end

    end

  end

end


text:
package org.apache.logging.log4j.flume.appender;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.apache.flume.Event;
import org.apache.flume.EventDeliveryException;
import org.apache.flume.agent.embedded.EmbeddedAgent;
import org.apache.logging.log4j.LoggingException;
import org.apache.logging.log4j.core.appender.ManagerFactory;
import org.apache.logging.log4j.core.config.ConfigurationException;
import org.apache.logging.log4j.core.config.Property;
import org.apache.logging.log4j.core.util.NameUtil;
import org.apache.logging.log4j.util.PropertiesUtil;
import org.apache.logging.log4j.util.Strings;

/**
 *
 */
public class FlumeEmbeddedManager extends AbstractFlumeManager {

    private static final String FILE_SEP = PropertiesUtil.getProperties().getStringProperty("file.separator");

    private static final String IN_MEMORY = "InMemory";

    private static FlumeManagerFactory factory = new FlumeManagerFactory();

    private final EmbeddedAgent agent;

    private final String shortName;

    /**
     * Constructor
     * @param name The unique name of this manager.
     * @param shortName The short version of the agent name.
     * @param agent The embedded agent.
     */
    protected FlumeEmbeddedManager(final String name, final String shortName, final EmbeddedAgent agent) {
        super(name);
        this.agent = agent;
        this.shortName = shortName;
    }

    /**
     * Returns a FlumeEmbeddedManager.
     * @param name The name of the manager.
     * @param agents The agents to use.
     * @param properties Properties for the embedded manager.
     * @param batchSize The number of events to include in a batch.
     * @param dataDir The directory where the Flume FileChannel should write to.
     * @return A FlumeAvroManager.
     */
    public static FlumeEmbeddedManager getManager(final String name, final Agent[] agents, final Property[] properties,
                                                  int batchSize, final String dataDir) {

        if (batchSize <= 0) {
            batchSize = 1;
        }

        if ((agents == null || agents.length == 0) && (properties == null || properties.length == 0)) {
            throw new IllegalArgumentException("Either an Agent or properties are required");
        } else if (agents != null && agents.length > 0 && properties != null && properties.length > 0) {
            throw new IllegalArgumentException("Cannot configure both Agents and Properties.");
        }

        final StringBuilder sb = new StringBuilder();
        boolean first = true;

        if (agents != null && agents.length > 0) {
            sb.append(name).append('[');
            for (final Agent agent : agents) {
                if (!first) {
                    sb.append('_');
                }
                sb.append(agent.getHost()).append('-').append(agent.getPort());
                first = false;
            }
            sb.append(']');
        } else {
            String sep = Strings.EMPTY;
            sb.append(name).append('-');
            final StringBuilder props = new StringBuilder();
            for (final Property prop : properties) {
                props.append(sep);
                props.append(prop.getName()).append('=').append(prop.getValue());
                sep = "_";
            }
            sb.append(NameUtil.md5(props.toString()));
        }
        return getManager(sb.toString(), factory,
                new FactoryData(name, agents, properties, batchSize, dataDir));
    }

    @Override
    public void send(final Event event) {
        try {
            agent.put(event);
        } catch (final EventDeliveryException ex) {
            throw new LoggingException("Unable to deliver event to Flume Appender " + shortName, ex);
        }
    }

    @Override
    protected boolean releaseSub(final long timeout, final TimeUnit timeUnit) {
        agent.stop();
        return true;
    }

    /**
     * Factory data.
     */
    private static class FactoryData {
        private final Agent[] agents;
        private final Property[] properties;
        private final int batchSize;
        private final String dataDir;
        private final String name;

        /**
         * Constructor.
         * @param name The name of the Appender.
         * @param agents The agents.
         * @param properties The Flume configuration properties.
         * @param batchSize The number of events to include in a batch.
         * @param dataDir The directory where Flume should write to.
         */
        public FactoryData(final String name, final Agent[] agents, final Property[] properties, final int batchSize,
                           final String dataDir) {
            this.name = name;
            this.agents = agents;
            this.batchSize = batchSize;
            this.properties = properties;
            this.dataDir = dataDir;
        }
    }

    /**
     * Avro Manager Factory.
     */
    private static class FlumeManagerFactory implements ManagerFactory<FlumeEmbeddedManager, FactoryData> {

        /**
         * Create the FlumeAvroManager.
         * @param name The name of the entity to manage.
         * @param data The data required to create the entity.
         * @return The FlumeAvroManager.
         */
        @Override
        public FlumeEmbeddedManager createManager(final String name, final FactoryData data) {
            try {
                final Map<String, String> props = createProperties(data.name, data.agents, data.properties,
                    data.batchSize, data.dataDir);
                final EmbeddedAgent agent = new EmbeddedAgent(name);
                agent.configure(props);
                agent.start();
                LOGGER.debug("Created Agent " + name);
                return new FlumeEmbeddedManager(name, data.name, agent);
            } catch (final Exception ex) {
                LOGGER.error("Could not create FlumeEmbeddedManager", ex);
            }
            return null;
        }

        private Map<String, String> createProperties(final String name, final Agent[] agents,
                                                     final Property[] properties, final int batchSize, String dataDir) {
            final Map<String, String> props = new HashMap<>();

            if ((agents == null || agents.length == 0) && (properties == null || properties.length == 0)) {
                LOGGER.error("No Flume configuration provided");
                throw new ConfigurationException("No Flume configuration provided");
            }

            if (agents != null && agents.length > 0 && properties != null && properties.length > 0) {
                LOGGER.error("Agents and Flume configuration cannot both be specified");
                throw new ConfigurationException("Agents and Flume configuration cannot both be specified");
            }

            if (agents != null && agents.length > 0) {

                if (Strings.isNotEmpty(dataDir)) {
                    if (dataDir.equals(IN_MEMORY)) {
                        props.put("channel.type", "memory");
                    } else {
                        props.put("channel.type", "file");

                        if (!dataDir.endsWith(FILE_SEP)) {
                            dataDir = dataDir + FILE_SEP;
                        }

                        props.put("channel.checkpointDir", dataDir + "checkpoint");
                        props.put("channel.dataDirs", dataDir + "data");
                    }

                } else {
                    props.put("channel.type", "file");
                }

                final StringBuilder sb = new StringBuilder();
                String leading = Strings.EMPTY;
                final int priority = agents.length;
                for (int i = 0; i < priority; ++i) {
                    sb.append(leading).append("agent").append(i);
                    leading = " ";
                    final String prefix = "agent" + i;
                    props.put(prefix + ".type", "avro");
                    props.put(prefix + ".hostname", agents[i].getHost());
                    props.put(prefix + ".port", Integer.toString(agents[i].getPort()));
                    props.put(prefix + ".batch-size", Integer.toString(batchSize));
                    props.put("processor.priority." + prefix, Integer.toString(agents.length - i));
                }
                props.put("sinks", sb.toString());
                props.put("processor.type", "failover");
            } else {
                String[] sinks = null;

                for (final Property property : properties) {
                    final String key = property.getName();

                    if (Strings.isEmpty(key)) {
                        final String msg = "A property name must be provided";
                        LOGGER.error(msg);
                        throw new ConfigurationException(msg);
                    }

                    final String upperKey = key.toUpperCase(Locale.ENGLISH);

                    if (upperKey.startsWith(name.toUpperCase(Locale.ENGLISH))) {
                        final String msg =
                            "Specification of the agent name is not allowed in Flume Appender configuration: " + key;
                        LOGGER.error(msg);
                        throw new ConfigurationException(msg);
                    }

                    final String value = property.getValue();
                    if (Strings.isEmpty(value)) {
                        final String msg = "A value for property " + key + " must be provided";
                        LOGGER.error(msg);
                        throw new ConfigurationException(msg);
                    }

                    if (upperKey.equals("SINKS")) {
                        sinks = value.trim().split(" ");
                    }

                    props.put(key, value);
                }

                if (sinks == null || sinks.length == 0) {
                    final String msg = "At least one Sink must be specified";
                    LOGGER.error(msg);
                    throw new ConfigurationException(msg);
                }
            }
            return props;
        }

    }

}


text:
run_command() {
  for table in $(psql -h ${PGHOST} -p ${PGPORT} -d ${PGDB} -U ${PGUSER} \
    -c "select tablename from pg_tables where schemaname = '${PGSCHEMA}';" | \
    tail -n +3 | head -n -2); do
      psql -h ${PGHOST} -p ${PGPORT} -d ${PGDB} -U ${PGUSER} \
           -c "VACUUM (ANALYZE) ${PGSCHEMA}.${table};";
  done
}

display_help() {
    echo "Usage: $0 -s schemaname" >&2
    echo
    echo "   -s schema           The schema to be analyzed."
    echo
    echo " The script assumes that you have a ~/.pgpass file that contains your password"
    echo " information.  The file is described in detail on the Postgres documentation:"
    echo " https://www.postgresql.org/docs/current/libpq-pgpass.html"
    echo
    exit 1
}

while getopts "hw:s:" optionName; do
  case "$optionName" in
    h)
      display_help
      exit 0
      ;;
    s)
      PGSCHEMA="$OPTARG";;
    [?])
      display_help
      exit 0
      ;;
  esac
done
run_command


text:
<?php

if (!defined('ABSPATH')) die('No direct access allowed');

class WP_Optimize_Database_Information {

	const UNKNOWN_DB = 'unknown';
	const MARIA_DB = 'MariaDB';
	const PERCONA_DB = 'Percona';
	// for some reason coding standard parser give error here WordPress.DB.RestrictedFunctions.mysql_mysql_db
	// @codingStandardsIgnoreLine
	const MYSQL_DB = 'MysqlDB';

	const MYISAM_ENGINE = 'MyISAM';
	const MEMORY_ENGINE = 'Memory';
	const INNODB_ENGINE = 'InnoDB';
	const ARCHIVE_ENGINE = 'ARCHIVE';
	const CSV_ENGINE = 'CSV';
	const NDB_ENGINE = 'NDB';
	const ARIA_ENGINE = 'Aria'; // MariaDB
	const VIEW = 'VIEW';

	/**
	 * Returns server type MySQL or MariaDB if mysql database or Unknown if not mysql.
	 *
	 * @return string
	 */
	public function get_server_type() {
		global $wpdb;
		static $server_type = null;

		if (!$wpdb->is_mysql) return self::UNKNOWN_DB;

		if (null !== $server_type) return $server_type;

		$server_type = self::MYSQL_DB;

		$variables = $wpdb->get_results('SHOW SESSION VARIABLES LIKE "version%"');

		if (!empty($variables)) {
			foreach ($variables as $variable) {
				if (preg_match('/mariadb/i', $variable->Value)) {
					$server_type = self::MARIA_DB;
				}
				if (preg_match('/percona/i', $variable->Value)) {
					$server_type = self::PERCONA_DB;
				}
			}
		}

		return $server_type;
	}

	/**
	 * Returns database server version
	 *
	 * @return string|bool
	 */
	public function get_version() {
		$version = $this->get_option_value('version');

		if (!empty($version)) {
			if (preg_match('/^(\d+)(\.\d+)+/', $version, $match)) {
				return $match[0];
			}
		}

		return false;
	}

	/**
	 * Return table type by $table_name.
	 *
	 * @param String $table_name Database table name.
	 * @return String|Boolean - returns false upon failure
	 */
	public function get_table_type($table_name) {
		$table_info = $this->get_table_status($table_name);

		if ($table_info) {
			if (!$table_info->Engine && $this->is_view($table_name)) return self::VIEW;

			return $table_info->Engine;
		}

		return false;
	}

	/**
	 * Returns information about database table.
	 *
	 * @param string $table_name
	 * @param bool   $update     if true, then force request to database and don't use cached values.
	 * @return bool|mixed
	 */
	public function get_table_status($table_name, $update = false) {

		$tables_info = $this->get_show_table_status($update);

		foreach ($tables_info as $table_info) {
			if ($table_name == $table_info->Name) return $table_info;
		}

		return false;
	}

	/**
	 * Returns result for query SHOW TABLE STATUS.
	 *
	 * @param bool $update refresh or no cached data
	 * @return array
	 */
	public function get_show_table_status($update = false) {
		global $wpdb;
		static $tables_info = array();

		if ($update || empty($tables_info) || !is_array($tables_info)) {
			$tables_info = $wpdb->get_results('SHOW TABLE STATUS');
		}

		// If option innodb_file_per_table is disabled then Data_free column will have summary overhead value for all table.
		if (!empty($tables_info)) {
			foreach ($tables_info as $i => $table) {
				if (self::INNODB_ENGINE == $table->Engine && false == $this->is_option_enabled('innodb_file_per_table')) {
					$tables_info[$i]->Data_free = 0;
				}
			}
		}

		return $tables_info;
	}

	/**
	 * Returns result for query SHOW FULL TABLES as associative array [table_name] => table_type.
	 *
	 * @return array
	 */
	public function get_show_full_tables() {
		global $wpdb;

		static $tables_info = array();

		if (empty($tables_info) || !is_array($tables_info)) {
			$_tables_info = $wpdb->get_results('SHOW FULL TABLES', ARRAY_N);

			if (!empty($_tables_info)) {
				foreach ($_tables_info as $row) {
					$tables_info[$row[0]] = $row[1];
				}
			}
		}

		return $tables_info;
	}

	/**
	 * Checks if table is a VIEW.
	 *
	 * @param  string $table_name
	 * @return bool
	 */
	public function is_view($table_name) {
		$tables_info = $this->get_show_full_tables();

		if (!array_key_exists($table_name, $tables_info)) return false;

		return ('VIEW' == $tables_info[$table_name]);
	}

	/**
	 * Returns true if DDL supported.
	 *
	 * @return bool
	 */
	public function has_online_ddl() {
		if (self::MYSQL_DB == $this->get_server_type()) {
			if (version_compare($this->get_version(), '5.7', '>=')) {
				return true;
			} else {
				return false;
			}
		} elseif (self::MARIA_DB == $this->get_server_type()) {
			if (version_compare($this->get_version(), '10.0.0', '>=')) {
				return true;
			} else {
				return false;
			}
		}

		return false;
	}

	/**
	 * Returns database option variable
	 *
	 * @param string $option_name Name of database option.
	 * @return mixed|null
	 */
	public function get_option_value($option_name) {
		global $wpdb;
		static $options = array();

		if (array_key_exists($option_name, $options)) return $options[$option_name];

		$option = $wpdb->get_row(
			$wpdb->prepare('SHOW SESSION VARIABLES LIKE %s', $option_name)
		);

		if (!empty($option)) {
			$options[$option_name] = $option->Value;
			return $option->Value;
		}

		return null;
	}

	/**
	 * Returns true if database option $option_name
	 *
	 * @param string $option_name Name of database option name.
	 * @return bool
	 */
	public function is_option_enabled($option_name) {
		$option_value = $this->get_option_value($option_name);

		if ('ON' == strtoupper($option_value)) return true;
		return false;
	}

	/**
	 * Returns true if table $table_name is optimizable
	 *
	 * @param string $table_name Name of database table
	 * @return bool
	 */
	public function is_table_optimizable($table_name) {
		$server_type = $this->get_server_type();
		$server_version = $this->get_version();
		$table_type = $this->get_table_type($table_name);

		// return true if table is MyISAM.
		if (self::MYISAM_ENGINE == $table_type) return true;

		// return true if table is Archive or Aria.
		if (self::ARCHIVE_ENGINE == $table_type || self::ARIA_ENGINE == $table_type) return true;

		// if InnoDB then check if we can optimize.
		if (self::INNODB_ENGINE == $table_type) {
			// check for MysqlDB.
			if (self::MYSQL_DB == $server_type && $this->has_online_ddl()) {
				return true;
			}

			// check for MariaDB.
			if (self::MARIA_DB == $server_type) {
				// if innodb_file_per_table enabled or version not older than 10.1.1 and innodb_defragment enabled.
				if ($this->is_option_enabled('innodb_file_per_table') || (version_compare($server_version, '10.1.1', '>=') && $this->is_option_enabled('innodb_defragment'))) {
					return true;
				}
			}
		}

		// otherwise return false.
		return false;
	}

	/**
	 * Returns true if table type is supported for optimization.
	 *
	 * @param string $table_name Name of database table
	 * @return bool
	 */
	public function is_table_type_optimize_supported($table_name) {
		$table_type = $this->get_table_type($table_name);

		$supported_table_types = array(
			self::MYISAM_ENGINE,
			self::INNODB_ENGINE,
			self::ARCHIVE_ENGINE,
			self::ARIA_ENGINE,
		);

		return in_array($table_type, $supported_table_types);
	}

	/**
	 * Returns true if table type is supported for repair.
	 *
	 * @param string $table_name
	 * @return bool
	 */
	public function is_table_type_repair_supported($table_name) {
		$table_type = $this->get_table_type($table_name);

		$supported_table_types = array(
			self::MYISAM_ENGINE,
			self::ARCHIVE_ENGINE,
			self::CSV_ENGINE,
		);

		return in_array($table_type, $supported_table_types);
	}

	/**
	 * Run CHECK TABLE query and returns statuses for single or list of tables.
	 *
	 * @param array|string $table
	 */
	public function check_table($table) {
		global $wpdb;

		if (is_array($table)) {
			$table = join('`,`', $table);
		}

		$result = array();

		if (empty($table)) return $result;

		$query_result = $wpdb->get_results('CHECK TABLE `'.$table.'`;');

		if (empty($query_result)) return $result;

		foreach ($query_result as $row) {
			$table_name_parts = explode('.', rtrim($row->Table, ' .'));
			$table_name = array_pop($table_name_parts);

			if (!array_key_exists($table_name, $result)) {
				$result[$table_name] = array(
					'status' => '',
					'corrupted' => false,
				);
			}

			if ('error' == $row->Msg_type) {
				$result[$table_name]['status'] = $row->Msg_type;

				if (preg_match('/corrupt/i', $row->Msg_text)) {
					$result[$table_name]['corrupted'] = true;
				} else {
					$result[$table_name]['message'] = $row->Msg_text;
				}
			}

			if ('status' == $row->Msg_type) {
				$result[$table_name]['status'] = $row->Msg_text;
			}
		}

		return $result;
	}

	/**
	 * Check all supported for repair tables and return statuses for them.
	 *
	 * @return array
	 */
	public function check_all_tables() {
		static $result = null;

		if (null !== $result) return $result;

		$tables = $this->get_show_table_status();
		$supported_tables = array();

		foreach ($tables as $table) {
			if ('' == $table->Engine || $this->is_table_type_repair_supported($table->Name)) {
				$supported_tables[] = $table->Name;
			}
		}

		$result = $this->check_table($supported_tables);

		return $result;
	}

	/**
	 * Returns true if table needing repair.
	 *
	 * @param string $table_name Database table name.
	 */
	public function is_table_needing_repair($table_name) {
		$table_statuses = $this->check_all_tables();

		if (is_array($table_statuses) && array_key_exists($table_name, $table_statuses) && $table_statuses[$table_name]['corrupted']) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * Check if $table using by any of installed plugins.
	 *
	 * @param string $table
	 * @return bool
	 */
	public function is_table_using_by_plugin($table) {
		$plugin_names = $this->get_table_plugin($table);

		// if we can't determine which plugin use $table then return true.
		if (false == $plugin_names) {
			return true;
		}

		// is WordPress core table or using by any of installed plugins then return true.
		foreach ($plugin_names as $plugin_name) {
			if (__('WordPress core', 'wp-optimize') == $plugin_name || in_array($plugin_name, $this->get_all_installed_plugins())) {
				return true;
			}
		}

		return false;
	}

	/**
	 * Get information about relations between tables and plugins. [ 'table' => ['plugin1', 'plugin2', ...], ... ].
	 *
	 * @return array
	 */
	private function get_all_plugin_tables_relationship() {
		static $plugin_tables;

		$wp_core_tables = array(
			'blogs',
			'blog_versions',
			'commentmeta',
			'comments',
			'links',
			'options',
			'postmeta',
			'posts',
			'registration_log',
			'signups',
			'term_relationships',
			'term_taxonomy',
			'termmeta',
			'terms',
			'usermeta',
			'users',
			'site',
			'sitemeta',
		);

		if (is_array($plugin_tables)) return $plugin_tables;

		$plugin_tables_json_file = WPO_PLUGIN_MAIN_PATH.'/plugin.json';
		$plugin_tables = array();

		if (is_file($plugin_tables_json_file) && is_readable($plugin_tables_json_file)) {
			// get data from plugin.json file.
			$plugin_tables = json_decode(file_get_contents($plugin_tables_json_file), true);
		}

		foreach ($wp_core_tables as $table) {
			$plugin_tables[$table][] = __('WordPress core', 'wp-optimize');
		}

		// add WP-Optimize tables.
		$plugin_tables['tm_taskmeta'][] = 'wp-optimize';
		$plugin_tables['tm_tasks'][] = 'wp-optimize';

		return $plugin_tables;
	}

	/**
	 * Try to get plugin name by table name and return it or return false if plugin is not defined.
	 *
	 * @param string $table
	 * @return array|bool - array with plugin slugs or false.
	 */
	public function get_table_plugin($table) {
		global $wpdb;

		// delete table prefix.
		$table = preg_replace('/^'.$wpdb->prefix.'([0-9]+_)?/', '', $table);
		$plugins_tables = $this->get_all_plugin_tables_relationship();

		if (array_key_exists($table, $plugins_tables)) {
			return $plugins_tables[$table];
		}

		return false;
	}

	/**
	 * Get all installed plugin slugs.
	 *
	 * @return array
	 */
	public function get_all_installed_plugins() {
		static $installed_plugins;

		if (is_array($installed_plugins)) return $installed_plugins;

		$installed_plugins = array();

		if (!function_exists('get_plugins')) include_once(ABSPATH.'wp-admin/includes/plugin.php');

		$plugins = get_plugins();

		foreach ($plugins as $plugin_file => $plugin_data) {
			if ('' != $plugin_data['TextDomain']) {
				$installed_plugins[] = $plugin_data['TextDomain'];
			} else {
				$plugin_file_parts = explode('/', $plugin_file);
				$installed_plugins[]= $plugin_file_parts[0];
			}
		}

		return $installed_plugins;
	}

	/**
	 * Check current plugin status installed/not installed and active/inactive.
	 *
	 * @param string $plugin
	 * @return array - ['installed' => true|false, 'active' => true|false]
	 */
	public function get_plugin_status($plugin) {

		if (!function_exists('get_plugins')) include_once(ABSPATH.'wp-admin/includes/plugin.php');
		$plugins = get_plugins();

		// return true for wp-optimize without checking.
		if ('wp-optimize' == $plugin) {
			return array(
				'installed' => true,
				'active' => true,
			);
		}

		$installed = false;
		$active = false;

		foreach ($plugins as $plugin_file => $plugin_data) {
			$plugin_file_parts = explode('/', $plugin_file);
			$plugin_slug = $plugin_file_parts[0];

			if ($plugin == $plugin_slug) {
				$installed = true;
				$active = is_plugin_active($plugin_file);
			}
		}

		return array(
			'installed' => $installed,
			'active' => $active,
		);
	}
}


text:
#.rst:
# CMakeVerifyManifest
# -------------------
#
#
#
# CMakeVerifyManifest.cmake
#
# This script is used to verify that embedded manifests and side by side
# manifests for a project match.  To run this script, cd to a directory
# and run the script with cmake -P.  On the command line you can pass in
# versions that are OK even if not found in the .manifest files.  For
# example, cmake -Dallow_versions=8.0.50608.0
# -PCmakeVerifyManifest.cmake could be used to allow an embedded manifest
# of 8.0.50608.0 to be used in a project even if that version was not
# found in the .manifest file.

# This script first recursively globs *.manifest files from
# the current directory.  Then globs *.exe and *.dll.  Each
# .exe and .dll is scanned for embedded manifests and the versions
# of CRT are compared to those found in the .manifest files
# from the first glob.

# crt_version:
# function to extract the CRT version from a file
# this can be passed a .exe, .dll, or a .manifest file
# it will put the list of versions found into the variable
# specified by list_var
function(crt_version file list_var)
  file(STRINGS "${file}" strings REGEX "Microsoft.VC...CRT" NEWLINE_CONSUME)
  foreach(s ${strings})
    set(has_match 1)
    string(REGEX
      REPLACE ".*<assembly.*\"Microsoft.VC...CRT\".*version=\"([^\"]*)\".*</assembly>.*$" "\\1"
      version "${s}")
    if(NOT "${version}" STREQUAL "")
      list(APPEND version_list ${version})
    else()
      message(FATAL_ERROR "Parse error could not find version in [${s}]")
    endif()
  endforeach()
  if(NOT DEFINED has_match)
    message("Information: no embedded manifest in: ${file}")
    return()
  endif()
  list(APPEND version_list ${${list_var}})
  list(REMOVE_DUPLICATES version_list)
  if(version_list)
    set(${list_var} ${version_list} PARENT_SCOPE)
  endif()
endfunction()
set(fatal_error FALSE)

# check_version:
#
# test a file against the shipped manifest versions
# for a directory
function(check_version file manifest_versions)
  set(manifest_versions ${manifest_versions} ${allow_versions})
  # collect versions for a given file
  crt_version(${file} file_versions)
  # see if the versions
  foreach(ver ${file_versions})
    list(FIND manifest_versions "${ver}" found_version)
    if("${found_version}" EQUAL -1)
      message("ERROR: ${file} uses ${ver} not found in shipped manifests:[${manifest_versions}].")
      set(fatal_error TRUE PARENT_SCOPE)
    endif()
  endforeach()
  list(LENGTH file_versions len)
  if(${len} GREATER 1)
    message("WARNING: found more than one version of MICROSOFT.VC80.CRT referenced in ${file}: [${file_versions}]")
  endif()
endfunction()

# collect up the versions of CRT that are shipped
# in .manifest files
set(manifest_version_list )
file(GLOB_RECURSE manifest_files "*.manifest")
foreach(f ${manifest_files})
  crt_version("${f}" manifest_version_list)
endforeach()
list(LENGTH manifest_version_list LEN)
if(LEN EQUAL 0)
  message(FATAL_ERROR "No .manifest files found, no version check can be done.")
endif()
message("Versions found in ${manifest_files}: ${manifest_version_list}")
if(DEFINED allow_versions)
  message("Extra versions allowed: ${allow_versions}")
endif()

# now find all .exe and .dll files
# and call check_version on each of them
file(GLOB_RECURSE exe_files "*.exe")
file(GLOB_RECURSE dll_files "*.dll")
set(exe_files ${exe_files} ${dll_files})
foreach(f ${exe_files})
  check_version(${f} "${manifest_version_list}")
endforeach()

# report a fatal error if there were any so that cmake will return
# a non zero value
if(fatal_error)
  message(FATAL_ERROR "This distribution embeds dll "
    " versions that it does not ship, and may not work on other machines.")
endif()


text:
///<reference path='../../typings/todomvc/todomvc.d.ts'/>

import React = require('react/addons');
import ReactComponent = require('../react/ReactComponent');
import ReactJSX = require('../react/ReactJSX');
import TodoActions = require('../flux/actions/TodoActions');

var ReactPropTypes: React.ReactPropTypes = React.PropTypes;

interface FooterProps {
  allTodos: MapStringTo<TodoData>;
}

interface FooterElement {
  id: string;
}

interface ClearCompletedButton {
  id: string;
  onClick: () => void;
}

class Footer extends ReactComponent<FooterProps,any> {

  static propTypes: React.ValidationMap<FooterProps> =	{
    allTodos: ReactPropTypes.object.isRequired
  };

  /**
   * Event handler to delete all completed TODOs
   */
  private _onClearCompletedClick: () => void =
    (): void => {
      TodoActions.destroyCompleted();
    };

  /**
   * @return {object}
   */
  public render(): React.ReactElement<FooterElement> {

    var allTodos: MapStringTo<TodoData> = this.props.allTodos;
    var total: number = Object.keys(allTodos).length;
    var completed: number = 0;
    var key: string;
    var itemsLeft: number;
    var itemsLeftPhrase: string;
    var clearCompletedButton:  React.ReactElement<ClearCompletedButton>;

    if (total === 0) {
      return null;
    }

    for (key in allTodos) {
      if (allTodos[key].complete) {
	     completed++;
      }
    }

    itemsLeft = total - completed;
    itemsLeftPhrase = itemsLeft === 1 ? ' item ' : ' items ';
    itemsLeftPhrase += 'left';

    // Undefined and thus not rendered if no completed items are left.
    if (completed) {
      clearCompletedButton =
	     ReactJSX<ClearCompletedButton>(`
				<button
	       id='clear-completed'
	       onClick={this._onClearCompletedClick}>
	       Clear completed
				</button>`,
				this,
				{
					completed: completed
				});
    }

    return ReactJSX<FooterElement>(`

	       {itemsLeft}

	       {itemsLeftPhrase}

	     {clearCompletedButton}
      `,
      this,
      {
	      'itemsLeft': itemsLeft,
	      'itemsLeftPhrase': itemsLeftPhrase,
	      'clearCompletedButton': clearCompletedButton
      }
    );
  }
}

export = Footer;


text:
package com.facebook.react.modules.systeminfo;

import android.os.Build;

public class AndroidInfoHelpers {

    public static String EMULATOR_LOCALHOST = "10.0.2.2:8081";

    public static String GENYMOTION_LOCALHOST = "10.0.3.2:8081";

    public static String DEVICE_LOCALHOST = "localhost:8081";

    private static boolean isRunningOnGenymotion() {
        return Build.FINGERPRINT.contains("vbox");
    }

    private static boolean isRunningOnStockEmulator() {
        return Build.FINGERPRINT.contains("generic");
    }

    public static String getServerHost() {
        if (isRunningOnGenymotion()) {
            return GENYMOTION_LOCALHOST;
        }
        if (isRunningOnStockEmulator()) {
            return EMULATOR_LOCALHOST;
        }
        return DEVICE_LOCALHOST;
    }
}


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/menu_settings"
        android:orderInCategory="100"
        android:showAsAction="never"
        android:title="Settings"/>

    <item
        android:id="@+id/menu_about"
        android:orderInCategory="100"
        android:showAsAction="never"
        android:title="About"/>

    <item
        android:id="@+id/menu_logout"
        android:orderInCategory="100"
        android:showAsAction="never"
        android:title="Log Out"/>

</menu>


text:
include_recipe 'dyn'

# "i-17734b7c.example.com" => ec2.public_hostname
dyn_rr node["ec2"]["instance_id"] do
  record_type "CNAME"
  fqdn "#{node["ec2"]["instance_id"]}.#{node["dyn"]["domain"]}"
  rdata({ "cname" => "#{node["ec2"]["public_hostname"]}." })
  customer node["dyn"]["customer"]
  username node["dyn"]["username"]
  password node["dyn"]["password"]
  zone     node["dyn"]["zone"]
  action :update
end

new_hostname = "#{node["dyn"]["ec2"]["type"]}-#{node["dyn"]["ec2"]["env"]}-#{node["ec2"]["instance_id"]}"
new_fqdn = "#{new_hostname}.#{node["dyn"]["domain"]}"

dyn_rr new_hostname do
  record_type "CNAME"
  fqdn new_fqdn
  rdata({ "cname" => "#{node["ec2"]["public_hostname"]}." })
  customer node["dyn"]["customer"]
  username node["dyn"]["username"]
  password node["dyn"]["password"]
  zone     node["dyn"]["zone"]
  action :update
end

ruby_block "edit resolv conf" do
  block do
    rc = Chef::Util::FileEdit.new("/etc/resolv.conf")
    rc.search_file_replace_line(/^search/, "search #{node["dyn"]["domain"]} compute-1.internal")
    rc.search_file_replace_line(/^domain/, "domain #{node["dyn"]["domain"]}")
    rc.write_file
  end
end

ruby_block "edit etc hosts" do
  block do
    rc = Chef::Util::FileEdit.new("/etc/hosts")
    new_hosts_entry = "#{node["ec2"]["local_ipv4"]} #{new_fqdn} #{new_hostname}"
    rc.insert_line_if_no_match(new_hosts_entry, new_hosts_entry)
    rc.write_file
  end
end

execute "hostname --file /etc/hostname" do
  action :nothing
end

file "/etc/hostname" do
  content new_hostname
  notifies :run, "execute[hostname --file /etc/hostname]", :immediately
end

node.automatic_attrs["hostname"] = new_hostname
node.automatic_attrs["fqdn"] = new_fqdn


text:
var Alloy = require('/alloy'),
    Backbone = Alloy.Backbone,
    _ = Alloy._;

function __processArg(obj, key) {
	var arg = null;
	if (obj) {
		arg = obj[key] || null;
		delete obj[key];
	}
	return arg;
}

function Controller() {

	require('/alloy/controllers/' + 'BaseController').apply(this, Array.prototype.slice.call(arguments));
	this.__controllerPath = 'index';
	this.args = arguments[0] || {};

	if (arguments[0]) {
		var __parentSymbol = __processArg(arguments[0], '__parentSymbol');
		var $model = __processArg(arguments[0], '$model');
		var __itemTemplate = __processArg(arguments[0], '__itemTemplate');
	}
	var $ = this;
	var exports = {};
	var __defers = {};

	$.__views.index = Ti.UI.createWindow({ backgroundColor: "#fff", fullscreen: false, exitOnClose: true, id: "index" });
	$.__views.index && $.addTopLevelView($.__views.index);
	function __alloyId1() {
		$.__views.index.removeEventListener('open', __alloyId1);
		if ($.__views.index.activity) {
			$.__views.index.activity.actionBar.displayHomeAsUp = true;$.__views.index.activity.actionBar.onHomeIconItemSelected = doHomeIcon;
		} else {
			Ti.API.warn('You attempted to access an Activity on a lightweight Window or other');
			Ti.API.warn('UI component which does not have an Android activity. Android Activities');
			Ti.API.warn('are valid with only windows in TabGroups or heavyweight Windows.');
		}
	}
	$.__views.index.addEventListener('open', __alloyId1);
	$.__views.drawer = Ti.UI.Android.createDrawerLayout({ id: "drawer" });
	$.__views.index.add($.__views.drawer);
	if (true) {
		$.__views.__alloyId3 = Ti.UI.createView({ backgroundColor: "red", id: "__alloyId3" });
		$.__views.drawer.leftView = $.__views.__alloyId3;
	}
	$.__views.__alloyId5 = Ti.UI.createView({ backgroundColor: "yellow", id: "__alloyId5" });
	$.__views.__alloyId6 = Ti.UI.createButton({ title: 'RIGHT', id: "__alloyId6" });
	$.__views.__alloyId5.add($.__views.__alloyId6);
	doButtonClick ? $.addListener($.__views.__alloyId6, 'click', doButtonClick) : __defers['$.__views.__alloyId6!click!doButtonClick'] = true;$.__views.drawer.centerView = $.__views.__alloyId5;$.__views.__alloyId8 = Ti.UI.createView({ backgroundColor: "orange", id: "__alloyId8" });
	$.__views.drawer.rightView = $.__views.__alloyId8;exports.destroy = function () {};

	_.extend($, $.__views);

	function doButtonClick(e) {
		$.drawer.toggleRight();
	}

	function doHomeIcon(e) {
		$.drawer.toggleLeft();
	}

	$.index.open();

	__defers['$.__views.__alloyId6!click!doButtonClick'] && $.addListener($.__views.__alloyId6, 'click', doButtonClick);

	_.extend($, exports);
}

module.exports = Controller;


text:
namespace CroquetAustralia.Domain.Specifications.TestHelpers
{
    public abstract class StepsBase
    {
        protected readonly Actual Actual;
        protected readonly Given Given;

        protected StepsBase(Given given, Actual actual)
        {
            Given = given;
            Actual = actual;
        }
    }
}


text:
local draft = param.get("draft", "table")
local initiative = draft.initiative
local issue = initiative.issue

ui.title(function()
  ui.link{
    content = issue.area.name,
    module = "area",
    view = "show",
    id = issue.area.id
  }
  slot.put(" · ")
  ui.link{
    content = _("Issue ##{id}", { id = issue.id }),
    module = "issue",
    view = "show",
    id = issue.id
  }
  slot.put(" · ")
  ui.link{
    content = _("Initiative: ")..initiative.name,
    module = "initiative",
    view = "show",
    id = initiative.id
  }
end)


text:
//=============================================================================
/**
 *  @file    gatewayd.cpp
 *
 *  Driver for the gateway daemon (gatewayd).  Note that this is
 *  completely generic code due to the Service Configurator
 *  framework!
 *
 *  @author Douglas C. Schmidt
 */
//=============================================================================

#include "ace/OS_NS_unistd.h"
#include "ace/Service_Config.h"
#include "ace/Service_Object.h"
#include "ace/Log_Msg.h"
#include "ace/Reactor.h"
#include "Gateway.h"

int
ACE_TMAIN (int argc, ACE_TCHAR *argv[])
{
  if (ACE_OS::access (ACE_DEFAULT_SVC_CONF, F_OK) != 0)
    {
      // Use static linking.
      ACE_Service_Object_Ptr sp = ACE_SVC_INVOKE (Gateway);

      if (sp->init (argc - 1, argv + 1) == -1)
        ACE_ERROR_RETURN ((LM_ERROR,
                           ACE_TEXT ("%p\n"),
                           ACE_TEXT ("init")),
                          1);

      // Run forever, performing the configured services until we
      // are shut down by a SIGINT/SIGQUIT signal.

      ACE_Reactor::instance ()->run_reactor_event_loop ();

      // Destructor of <ACE_Service_Object_Ptr> automagically call
      // <fini>.
    }
  else
    {
      if (ACE_Service_Config::open (argc, argv) == -1)
        ACE_ERROR_RETURN ((LM_ERROR,
                           ACE_TEXT ("%p\n"),
                           ACE_TEXT ("open")),
                          1);
      else // Use dynamic linking.

        // Run forever, performing the configured services until we are
        // shut down by a signal (e.g., SIGINT or SIGQUIT).

        ACE_Reactor::instance ()->run_reactor_event_loop ();
    }
  return 0;
}