text:
from conary.server import schema
from conary.repository import errors
from conary.repository.netrepos import instances, versionops
from conary.lib.tracelog import logMe

# - Entries in the RoleTroves table are processed and flattened
#   into the RoleAllTroves table
# - Entries in the Permissions table are processed and flattened into
#   the RoleAllPermissions table
# - Then, RoleAllTroves and RoleAllPermissions are summarized
#   in the RoleInstancesCache table

# base class for handling RAP and GAT
class RoleTable:
    def __init__(self, db):
        self.db = db

    def getWhereArgs(self, cond = "where", **kw):
        where = []
        args = []
        for key, val in kw.items():
            if val is None:
                continue
            where.append("%s = ?" % (key,))
            args.append(val)
        if len(where):
            where = cond + " " + " and ".join(where)
        else:
            where = ""
        return (where, args)

# class and methods for handling RoleTroves operations
class RoleTroves(RoleTable):
    # given a list of (n,v,f) tuples, convert them to instanceIds in
    # the tmpInstanceId table
    def _findInstanceIds(self, troveList, checkMissing=True):
        cu = self.db.cursor()
        schema.resetTable(cu, "tmpNVF")
        schema.resetTable(cu, "tmpInstanceId")
        for (n,v,f) in troveList:
            cu.execute("insert into tmpNVF (name, version, flavor) "
                       "values (?,?,?)", (n,v,f), start_transaction=False)
        self.db.analyze("tmpNVF")
        cu.execute("""
        insert into tmpInstanceId (idx, instanceId)
        select tmpNVF.idx, Instances.instanceId
        from tmpNVF
        join Items on tmpNVF.name = Items.item
        join Versions on tmpNVF.version = Versions.version
        join Flavors on tmpNVF.flavor = Flavors.flavor
        join Instances on
            Instances.itemId = Items.itemId and
            Instances.versionId = Versions.versionId and
            Instances.flavorId = Flavors.flavorId
        where
            Instances.isPresent in (%d,%d)
        """ % (instances.INSTANCE_PRESENT_NORMAL,
               instances.INSTANCE_PRESENT_HIDDEN),
                   start_transaction=False)
        self.db.analyze("tmpInstances")
        # check if any troves specified are missing
        cu.execute("""
        select tmpNVF.idx, name, version, flavor
        from tmpNVF
        left join tmpInstanceId using(idx)
        where tmpInstanceId.instanceId is NULL
        """)
        if checkMissing:
            # granting permissions to a !present trove has a fuzzy meaning
            for i, n, v, f in cu.fetchall():
                raise errors.TroveMissing(n,v)
        return True

    # update the RoleAllTroves table
    def rebuild(self, cu = None, rtId = None, roleId = None):
        where = []
        args = {}
        if rtId is not None:
            where.append("ugtId = :rtId")
            args["rtId"] = rtId
        if roleId is not None:
            where.append("userGroupId = :roleId")
            args["roleId"] = roleId
        whereCond = ""
        andCond = ""
        if where:
            whereCond = "where " + " and ".join(where)
            andCond   = "and "   + " and ".join(where)
        if cu is None:
            cu = self.db.cursor()
        # update the UserGroupAllTroves table
        cu.execute("delete from UserGroupAllTroves %s" % (whereCond,), args)
        cu.execute("""
        insert into UserGroupAllTroves (ugtId, userGroupId, instanceId)
        select ugtId, userGroupId, instanceId from UserGroupTroves %s
        union
        select ugtId, userGroupId, TroveTroves.includedId
        from UserGroupTroves join TroveTroves using (instanceId)
        where UserGroupTroves.recursive = 1 %s
        """ %(whereCond, andCond), args)
        if rtId is None and roleId is None:
            # this was a full rebuild
            self.db.analyze("UserGroupAllTroves")
        return True

    # grant access on a troveList to role
    def add(self, roleId, troveList, recursive=True):
        """
        grant access on a troveList to a Role. If recursive = True,
        then access is also granted to all the children of the troves
        passed
        """
        self._findInstanceIds(troveList)
        recursive = int(bool(recursive))
        # we have now the list of instanceIds in the tmpInstanceId table.
        # avoid inserting duplicates
        cu = self.db.cursor()
        cu.execute("""
        select distinct tmpInstanceId.instanceId, ugt.userGroupId, ugt.ugtId, ugt.recursive
        from tmpInstanceId
        left join UserGroupTroves as ugt using(instanceId)
        """)
        # record the new permissions
        ugtList = []
        results = cu.fetchall()
        instanceIds = set([ x[0] for x in results ])
        for instanceId in instanceIds:
            # if there's more than one result here, a DB constraint has been broken
            permissions = [ x[2:] for x in results if x[0] == instanceId and x[1] == roleId ]
            if len(permissions) == 0:
                # This is a new role for this instanceId
                cu.execute("insert into UserGroupTroves(userGroupId, instanceId, recursive) "
                           "values (?,?,?)", (roleId, instanceId, recursive))
                ugtId = cu.lastrowid
            else:
                ugtId, recflag = permissions[0]
                if recursive and not recflag:
                    # granting recursive access to something that wasn't recursive before
                    cu.execute("update UserGroupTroves set recursive = ? where ugtId = ?",
                           (recursive, ugtId))
                else:
                    ugtId = None
            if ugtId:
                self.rebuild(cu, ugtId, roleId)
                ugtList.append(ugtId)
        return ugtList

    # remove trove access grants
    def delete(self, roleId, troveList):
        """remove group access to troves passed in the (n,v,f) troveList"""
        self._findInstanceIds(troveList, checkMissing=False)
        cu = self.db.cursor()
        schema.resetTable(cu, "tmpId")
        cu.execute("""
        insert into tmpId(id)
        select ugtId from UserGroupTroves
        where userGroupId = ?
        and instanceId in (select instanceId from tmpInstanceId)
        """, roleId, start_transaction=False)
        self.db.analyze("tmpId")
        # save what instanceIds will be affected by this delete
        schema.resetTable(cu, "tmpInstances")
        cu.execute("""
        insert into tmpInstances(instanceId)
        select distinct ugat.instanceId
        from UserGroupAllTroves as ugat
        where ugat.userGroupId = ?
          and ugat.ugtId in (select id from tmpId)
        """, roleId, start_transaction = False)
        cu.execute("delete from UserGroupAllTroves where ugtId in (select id from tmpId)")
        cu.execute("delete from UserGroupTroves where ugtId in (select id from tmpId)")
        # filter out the ones that are still allowed based on other permissions
        cu.execute("""
        delete from tmpInstances
        where exists (
            select 1 from UserGroupAllTroves as ugat
            where userGroupId = ?
              and ugat.instanceId = tmpInstances.instanceId )
        """, roleId, start_transaction=False)
        return True

    # list what we have in the repository for a roleId
    def list(self, roleId):
        """return a list of the troves this usergroup is granted special access"""
        cu = self.db.cursor()
        cu.execute("""
        select Items.item, Versions.version, Flavors.flavor, ugt.recursive
        from UserGroupTroves as ugt
        join Instances using(instanceId)
        join Items on Instances.itemId = Items.itemId
        join Versions on Instances.versionId = Versions.versionId
        join Flavors on Instances.flavorId = Flavors.flavorId
        where ugt.userGroupId = ? """, roleId)
        return [ ((n,v,f),r) for n,v,f,r in cu.fetchall()]

# class and methods for handling RoleAllPermissions operations
class RolePermissions(RoleTable):
    # adds into the RoleAllPermissions table new entries
    # triggered by one or more recordIds
    def addId(self, cu = None, permissionId = None, roleId = None, instanceId = None):
        where = []
        args = []
        if permissionId is not None:
            where.append("Permissions.permissionId = ?")
            args.append(permissionId)
        if instanceId is not None:
            where.append("Instances.instanceId = ?")
            args.append(instanceId)
        if roleId is not None:
            where.append("Permissions.userGroupId = ?")
            args.append(roleId)
        whereStr = ""
        if len(where):
            whereStr = "where %s" % (' and '.join(where),)
        if cu is None:
            cu = self.db.cursor()
        cu.execute("""
        insert into UserGroupAllPermissions
            (permissionId, userGroupId, instanceId, canWrite)
        select
            Permissions.permissionId as permissionId,
            Permissions.userGroupId as userGroupId,
            Instances.instanceId as instanceId,
            Permissions.canWrite as canWrite
        from Instances
        join Nodes using(itemId, versionId)
        join LabelMap using(itemId, branchId)
        join Permissions on
            Permissions.labelId = 0 or
            Permissions.labelId = LabelMap.labelId
        join CheckTroveCache on
            Permissions.itemId = CheckTroveCache.patternId and
            Instances.itemId = CheckTroveCache.itemId
        %s """ % (whereStr,), args)
        return True

    def addInstanceSet(self, cu, table, column):
        cu.execute("""
        insert into UserGroupAllPermissions
            (permissionId, userGroupId, instanceId, canWrite)
        select
            Permissions.permissionId as permissionId,
            Permissions.userGroupId as userGroupId,
            Instances.instanceId as instanceId,
            Permissions.canWrite as canWrite
        from %s
        join Instances using(%s)
        join Nodes on
            Instances.itemId = Nodes.itemId and
            Instances.versionId = Nodes.versionId
        join LabelMap on
            Nodes.itemId = LabelMap.itemId and
            Nodes.branchId = LabelMap.branchId
        join Permissions on
            Permissions.labelId = 0 or
            Permissions.labelId = LabelMap.labelId
        join CheckTroveCache on
            Permissions.itemId = CheckTroveCache.patternId and
            Instances.itemId = CheckTroveCache.itemId
        """ % (table, column))

    def deleteId(self, cu = None, permissionId = None, roleId = None,
                 instanceId = None):
        where, args = self.getWhereArgs("where", permissionId=permissionId,
            userGroupId=roleId, instanceId=instanceId)
        if cu is None:
            cu = self.db.cursor()
        cu.execute("delete from UserGroupAllPermissions %s" % (where,), args)
        return True

    def rebuild(self, cu = None, permissionId = None, roleId = None,
                instanceId = None):
        if cu is None:
            cu = self.db.cursor()
        self.deleteId(cu, permissionId, roleId, instanceId)
        self.addId(cu, permissionId, roleId, instanceId)
        if permissionId is None and roleId is None and instanceId is None:
            # this was a full rebuild
            self.db.analyze("UserGroupAllPermissions")
        return True

# this class takes care of the RoleInstancesCache table, which is
# a summary of rows present in RoleAllTroves and RoleAllPermissions tables
class RoleInstances(RoleTable):
    def __init__(self, db):
        RoleTable.__init__(self, db)
        self.rt = RoleTroves(db)
        self.rp = RolePermissions(db)
        self.latest = versionops.LatestTable(db)

    def _getRoleId(self, role):
        cu = self.db.cursor()
        cu.execute("SELECT userGroupId FROM UserGroups WHERE userGroup=?",
                   role)
        ret = cu.fetchall()
        if len(ret):
            return ret[0][0]
        raise errors.RoleNotFound

    def addTroveAccess(self, role, troveList, recursive=True):
        roleId = self._getRoleId(role)
        rtList = self.rt.add(roleId, troveList, recursive)
        # we now know the ids of the new acls added. They're useful in
        # updating the UGIC table
        cu = self.db.cursor()
        # grab the list of instanceIds we are adding to the UGIC table;
        # we need those for a faster recomputation of the LatestCache table
        schema.resetTable(cu, "tmpInstances")
        cu.execute("""
        insert into tmpInstances(instanceId)
        select distinct ugat.instanceId
        from UserGroupAllTroves as ugat
        where ugat.ugtId in (%s)
          and ugat.userGroupId = ?
          and not exists (
              select 1 from UserGroupInstancesCache as ugi
              where ugi.userGroupId = ?
                and ugi.instanceId = ugat.instanceId )
        """ % (",".join("%d" % x for x in rtList),),
                   (roleId, roleId), start_transaction=False)
        # insert into UGIC and recompute the latest table
        cu.execute("""
        insert into UserGroupInstancesCache (userGroupId, instanceId)
        select %d, instanceId from tmpInstances """ %(roleId,))
        # tmpInstances has instanceIds for which Latest needs to be recomputed
        self.db.analyze("tmpInstances")
        self.latest.updateRoleId(cu, roleId, tmpInstances=True)

    def deleteTroveAccess(self, role, troveList):
        roleId = self._getRoleId(role)
        # remove the RoleTrove access
        cu = self.db.cursor()
        self.rt.delete(roleId, troveList)
        # instanceIds that were removed from RAT are in tmpInstances now
        # RAP might still grant permissions to some, so we filter those out
        cu.execute("""
        delete from tmpInstances
        where exists (
            select 1 from UserGroupAllPermissions as ugap
            where ugap.userGroupId = ?
              and ugap.instanceId = tmpInstances.instanceId )
        """, roleId, start_transaction = False)
        self.db.analyze("tmpInstances")
        # now we should have in tmpInstances the instanceIds of the
        # troves this user can no longer access.
        cu.execute("""
        delete from UserGroupInstancesCache
        where userGroupId = ?
          and instanceId in (select instanceId from tmpInstances)
        """, roleId)
        # tmpInstances has instanceIds for which Latest needs to be recomputed
        self.latest.updateRoleId(cu, roleId, tmpInstances=True)

    def listTroveAccess(self, role):
        roleId = self._getRoleId(role)
        return self.rt.list(roleId)

    # changes in the Permissions table
    def addPermissionId(self, permissionId, roleId):
        cu = self.db.cursor()
        self.rp.addId(cu, permissionId = permissionId)
        # figure out newly accessible troves. We keep track separately
        # to speed up the Latest update
        schema.resetTable(cu, "tmpInstances")
        cu.execute("""
        insert into tmpInstances(instanceId)
        select instanceId from UserGroupAllPermissions as ugap
        where permissionId = ?
          and not exists (
              select instanceId from UserGroupInstancesCache as ugi
              where ugi.userGroupId = ?
              and ugi.instanceId = ugap.instanceId ) """,
                   (permissionId, roleId),
                   start_transaction = False)
        # update UsergroupInstancesCache
        cu.execute("""
        insert into UserGroupInstancesCache (userGroupId, instanceId, canWrite)
        select userGroupId, instanceId,
               case when sum(canWrite) = 0 then 0 else 1 end as canWrite
        from UserGroupAllPermissions
        where permissionId = ?
          and instanceId in (select instanceId from tmpInstances)
        group by userGroupId, instanceId
        """, permissionId)
        # update Latest
        self.latest.updateRoleId(cu, roleId, tmpInstances=True)

    def updatePermissionId(self, permissionId, roleId):
        cu = self.db.cursor()
        schema.resetTable(cu, "tmpInstances")
        # figure out how the access is changing
        cu.execute("""
        insert into tmpInstances(instanceId)
        select instanceId from UserGroupAllPermissions
        where permissionId = ? """, permissionId, start_transaction=False)
        # re-add
        self.rp.deleteId(cu, permissionId = permissionId)
        self.rp.addId(cu, permissionId = permissionId)
        # remove from consideration troves for which we still have access
        cu.execute("""
        delete from tmpInstances
        where exists (
            select 1 from UserGroupAllPermissions as ugap
            where ugap.userGroupId = :roleId
              and ugap.instanceId = tmpInstances.instanceId )
        or exists (
            select 1 from UserGroupAllTroves as ugat
            where ugat.userGroupId = :roleId
              and ugat.instanceId = tmpInstances.instanceId )
        """, roleId=roleId, start_transaction=False)
        self.db.analyze("tmpInstances")
        # remove trove access from troves that are left
        cu.execute("""
        delete from UserGroupInstancesCache
        where userGroupId = :roleId
          and instanceId in (select instanceId from tmpInstances)
          and not exists (
              select 1 from UserGroupAllTroves as ugat
              where ugat.userGroupId = :roleId
                and ugat.instanceId = UserGroupInstancesCache.instanceId )
        """, roleId=roleId)
        # add the new troves now
        cu.execute("""
        insert into UserGroupInstancesCache(userGroupId, instanceId, canWrite)
        select userGroupId, instanceId,
               case when sum(canWrite) = 0 then 0 else 1 end as canWrite
        from UserGroupAllPermissions as ugap
        where ugap.permissionId = ?
          and not exists (
              select 1 from UserGroupInstancesCache as ugi
              where ugi.instanceId = ugap.instanceId
                and ugi.userGroupId = ugap.userGroupId )
        group by userGroupId, instanceId
        """, permissionId)
        self.latest.updateRoleId(cu, roleId)
        return True

    # updates the canWrite flag for an acl change
    def updateCanWrite(self, permissionId, roleId):
        cu = self.db.cursor()
        # update the flattened table first
        cu.execute("""
        update UserGroupAllPermissions set canWrite = (
            select canWrite from Permissions where permissionId = ? )
        where permissionId = ? """, (permissionId, permissionId))
        # update the UserGroupInstancesCache now. hopefully we won't
        # do too many of these...
        cu.execute("""
        update UserGroupInstancesCache set canWrite = (
            select case when sum(canWrite) = 0 then 0 else 1 end
            from UserGroupAllPermissions as ugap
            where ugap.userGroupId = UserGroupInstancesCache.userGroupId
              and ugap.instanceId = UserGroupInstancesCache.instanceId )
        where userGroupId = ? and instanceId in (
            select instanceId from UserGroupAllPermissions as ugap2
            where ugap2.permissionId = ? )
        """, (roleId, permissionId))
        return True

    def deletePermissionId(self, permissionId, roleId):
        cu = self.db.cursor()
        # compute the list of troves for which no other RAP/RAT access exists
        schema.resetTable(cu, "tmpInstances")
        cu.execute("""
        insert into tmpInstances(instanceId)
        select ugi.instanceId from UserGroupInstancesCache as ugi
        where ugi.userGroupId = ?
          and not exists (
              select 1 from UserGroupAllPermissions as ugap
              where ugap.userGroupId = ?
                and ugap.instanceId = ugi.instanceId
                and ugap.permissionId != ? )
          and not exists (
              select 1 from UserGroupAllTroves as ugat
              where ugat.instanceId = ugi.instanceId
                and ugat.userGroupId = ? )""",
                   (roleId, roleId, permissionId, roleId),
                   start_transaction = False)
        # clean up the flattened table
        cu.execute("delete from UserGroupAllPermissions where permissionId = ?",
                   permissionId)
        # now we have only the troves which need to be erased out of UGIC
        self.db.analyze("tmpInstances")
        cu.execute("""
        delete from UserGroupInstancesCache
        where userGroupId = ?
        and instanceId in (select instanceId from tmpInstances)""", roleId)
        # update Latest
        self.latest.updateRoleId(cu, roleId, tmpInstances=True)

    # a new trove has been comitted to the system
    def addInstanceId(self, instanceId):
        cu = self.db.cursor()
        self.rp.addId(cu, instanceId = instanceId)
        cu.execute("""
        insert into UserGroupInstancesCache(userGroupId, instanceId, canWrite)
        select userGroupId, instanceId,
            case when sum(canWrite) = 0 then 0 else 1 end as canWrite
        from UserGroupAllPermissions as ugap
        where ugap.instanceId = ?
          and not exists (
              select 1 from UserGroupInstancesCache as ugi
              where ugi.instanceId = ugap.instanceId
                and ugi.userGroupId = ugap.userGroupId )
        group by userGroupId, instanceId
        """, instanceId)
        self.latest.updateInstanceId(cu, instanceId)

    def addInstanceIdSet(self, table, column):
        cu = self.db.cursor()
        self.rp.addInstanceSet(cu, table, column)
        cu.execute("""
        insert into UserGroupInstancesCache(userGroupId, instanceId, canWrite)
        select userGroupId, instanceId,
            case when sum(canWrite) = 0 then 0 else 1 end as canWrite
        from %s join
        UserGroupAllPermissions as ugap using (%s)
        where not exists (
              select 1 from UserGroupInstancesCache as ugi
              where ugi.instanceId = ugap.instanceId
                and ugi.userGroupId = ugap.userGroupId )
        group by userGroupId, instanceId
        """ % (table, column))

    def _updateLatest(self, table, column):
        cu = self.db.cursor()
        cu.execute("select %s from %s" % (column, table))
        for instanceId in [ x[0] for x in cu ]:
            self.latest.updateInstanceId(cu, instanceId)

    # these used used primarily by the markRemoved code
    def deleteInstanceId(self, instanceId):
        cu = self.db.cursor()
        for t in [ "UserGroupInstancesCache", "UserGroupAllTroves",
                   "UserGroupAllPermissions", "UserGroupTroves"]:
            cu.execute("delete from %s where instanceId = ?" % (t,),
                       instanceId)
        self.latest.updateInstanceId(cu, instanceId)

    def deleteInstanceIds(self, idTableName):
        cu = self.db.cursor()
        for t in [ "UserGroupInstancesCache", "UserGroupAllTroves",
                   "UserGroupAllPermissions", "UserGroupTroves" ]:
            cu.execute("delete from %s where instanceId in (select instanceId from %s)"%(
                t, idTableName))
        # this case usually does not require recomputing the
        # LatestCache since we only remove !present troves in bulk
        return True

    # rebuild the UGIC table entries
    def rebuild(self, roleId = None, cu = None):
        if cu is None:
            cu = self.db.cursor()
        where, args = self.getWhereArgs("where", userGroupId = roleId)
        cu.execute("delete from UserGroupInstancesCache %s" % (where,), args)
        # first, rebuild the flattened tables
        logMe(3, "rebuilding UserGroupAllTroves", "roleId=%s" % roleId)
        self.rt.rebuild(cu, roleId = roleId)
        logMe(3, "rebuilding UserGroupAllPermissions", "roleId=%s" % roleId)
        self.rp.rebuild(cu, roleId = roleId)
        # and now sum it up
        logMe(3, "updating UserGroupInstancesCache from UserGroupAllPermissions")
        cu.execute("""
        insert into UserGroupInstancesCache(userGroupId, instanceId, canWrite)
        select userGroupId, instanceId, case when sum(canWrite) = 0 then 0 else 1 end
        from UserGroupAllPermissions %s
        group by userGroupId, instanceId
        """ % (where,), args)
        cond, args = self.getWhereArgs("and", userGroupId = roleId)
        logMe(3, "updating UserGroupInstancesCache from UserGroupAllTroves")
        cu.execute("""
        insert into UserGroupInstancesCache(userGroupId, instanceId, canWrite)
        select distinct userGroupId, instanceId, 0 as canWrite
        from UserGroupAllTroves as ugat
        where not exists (
            select 1 from UserGroupInstancesCache as ugi
            where ugat.instanceId = ugi.instanceId
              and ugat.userGroupId = ugi.userGroupId )
        %s """ % (cond,), args)
        self.db.analyze("UserGroupInstancesCache")
        # need to rebuild the latest as well
        logMe(3, "rebuilding the LatestCache rows", "roleId=%s"%roleId)
        if roleId is not None:
            self.latest.updateRoleId(cu, roleId)
        else: # this is a full rebuild
            self.latest.rebuild()
        return True


text:
import EditRoute from 'appkit/routes/wh/content/type/edit';

export default EditRoute.extend({
  templateName: 'wh/content/type/edit'
});

redpajama_set_name: RedPajamaGithub


text:
var open = false;

var showHideElement = document.getElementById('show-hide');

function changeClass(element, className) {
  element.className = className;
}

function toggleModule() {

  if (open) {

    changeClass(showHideElement, 'hide');
    open = false;

  } else {

    changeClass(showHideElement, 'show');
    open = true;

  }
}


text:
@class NSImageCell;

@interface DVTPathComponentCell : NSPathComponentCell
{
    NSImageCell *_imageCell;
    BOOL _isLastItem;
    BOOL _isFirstItem;
    int _gradientStyle;
    long long _textAlignment;
}

- (void).cxx_destruct;
@property long long textAlignment; // @synthesize textAlignment=_textAlignment;
@property BOOL isFirstItem; // @synthesize isFirstItem=_isFirstItem;
@property BOOL isLastItem; // @synthesize isLastItem=_isLastItem;
@property int gradientStyle; // @synthesize gradientStyle=_gradientStyle;
- (BOOL)_delegateRespondsToAndIsDeemphasizedInView:(id)arg1;
- (void)drawInteriorWithFrame:(struct CGRect)arg1 inView:(id)arg2;
- (void)drawWithFrame:(struct CGRect)arg1 inView:(id)arg2;
- (BOOL)iconHitTest:(struct CGPoint)arg1 inFrame:(struct CGRect)arg2;
- (double)_textOffsetForIcon:(id)arg1 inFrame:(struct CGRect)arg2 doDraw:(BOOL)arg3 isActive:(BOOL)arg4;
- (void)_drawDividerForFrame:(struct CGRect)arg1 inControlView:(id)arg2;
- (struct CGSize)cellSizeForBounds:(struct CGRect)arg1;
- (double)_rightDividerWidth;
- (double)_leftDividerWidth;
- (void)_useChevronForLeftEdge:(char *)arg1 rightEdge:(char *)arg2;
- (id)textColor;
- (void)_commonInit;
- (id)initTextCell:(id)arg1;
- (id)initWithCoder:(id)arg1;

@end


text:
OC.L10N.register(
    "files",
    {
    "Storage not available" : "Хранилище недоступно",
    "Storage invalid" : "Хранилище неисправно",
    "Unknown error" : "Неизвестная ошибка",
    "Could not move %s - File with this name already exists" : "Невозможно переместить %s - файл с таким именем уже существует",
    "Could not move %s" : "Невозможно переместить %s",
    "Permission denied" : "В доступе отказано",
    "File name cannot be empty." : "Имя файла не может быть пустым.",
    "\"%s\" is an invalid file name." : "\"%s\" недопустимое имя файла.",
    "Invalid name, '\\', '/', '<', '>', ':', '\"', '|', '?' and '*' are not allowed." : "Неправильное имя, символы '\\', '/', '<', '>', ':', '\"', '|', '?' и '*' недопустимы.",
    "The target folder has been moved or deleted." : "Целевой каталог был перемещен или удален.",
    "The name %s is already used in the folder %s. Please choose a different name." : "Имя %s уже используется для каталога %s. Укажите другое имя.",
    "Not a valid source" : "Неправильный источник",
    "Server is not allowed to open URLs, please check the server configuration" : "Сервер не позволяет открывать URL-адреса, проверьте настройки сервера",
    "The file exceeds your quota by %s" : "Размер файла превышает квоту на %s",
    "Error while downloading %s to %s" : "Ошибка при скачивании %s в %s",
    "Error when creating the file" : "Ошибка при создании файла",
    "Folder name cannot be empty." : "Имя каталога не может быть пустым.",
    "Error when creating the folder" : "Ошибка создания каталога",
    "Unable to set upload directory." : "Невозможно установить каталог загрузки.",
    "Invalid Token" : "Недопустимый маркер",
    "No file was uploaded. Unknown error" : "Файл не был загружен. Неизвестная ошибка",
    "There is no error, the file uploaded with success" : "Файл загружен успешно. Ошибок нет.",
    "The uploaded file exceeds the upload_max_filesize directive in php.ini: " : "Размер загруженного файла превышает установленный предел upload_max_filesize в php.ini:",
    "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form" : "Размер загруженного файла превышает установленный предел MAX_FILE_SIZE в HTML-форме",
    "The uploaded file was only partially uploaded" : "Файл загружен лишь частично",
    "No file was uploaded" : "Не было загружено ни одного файла",
    "Missing a temporary folder" : "Отсутствует временный каталог",
    "Failed to write to disk" : "Ошибка записи на диск",
    "Not enough storage available" : "Недостаточно доступного места в хранилище",
    "Upload failed. Could not find uploaded file" : "Загрузка не удалась. Невозможно найти загружаемый файл",
    "Upload failed. Could not get file info." : "Загрузка не удалась. Невозможно получить информацию о файле",
    "Invalid directory." : "Неверный каталог.",
    "Files" : "Файлы",
    "All files" : "Все файлы",
    "Favorites" : "Избранное",
    "Home" : "Главная",
    "Unable to upload {filename} as it is a directory or has 0 bytes" : "Невозможно загрузить {filename}, так как это либо каталог, либо файл нулевого размера",
    "Total file size {size1} exceeds upload limit {size2}" : "Полный размер файла {size1} превышает лимит по загрузке {size2}",
    "Not enough free space, you are uploading {size1} but only {size2} is left" : "Недостаточно свободного места, Вы загружаете {size1}, но осталось только {size2}",
    "Upload cancelled." : "Загрузка отменена.",
    "Could not get result from server." : "Не удалось получить ответ от сервера.",
    "File upload is in progress. Leaving the page now will cancel the upload." : "Идёт загрузка файла. Покинув страницу, вы прервёте загрузку.",
    "URL cannot be empty" : "Ссылка не может быть пустой.",
    "{new_name} already exists" : "{new_name} уже существует",
    "Could not create file" : "Не удалось создать файл",
    "Could not create folder" : "Не удалось создать каталог",
    "Error fetching URL" : "Ошибка получения URL",
    "Rename" : "Переименовать",
    "Delete" : "Удалить",
    "Disconnect storage" : "Отсоединить хранилище",
    "Unshare" : "Закрыть доступ",
    "Download" : "Скачать",
    "Select" : "Выбрать",
    "Pending" : "Ожидание",
    "Unable to determine date" : "Невозможно определить дату",
    "Error moving file." : "Ошибка при перемещении файла.",
    "Error moving file" : "Ошибка при перемещении файла",
    "Error" : "Ошибка",
    "Could not rename file" : "Не удалось переименовать файл",
    "Error deleting file." : "Ошибка при удалении файла.",
    "No entries in this folder match '{filter}'" : "В данном каталоге нет элементов соответствующих '{filter}'",
    "Name" : "Имя",
    "Size" : "Размер",
    "Modified" : "Изменён",
    "_%n folder_::_%n folders_" : ["%n каталог","%n каталога","%n каталогов"],
    "_%n file_::_%n files_" : ["%n файл","%n файла","%n файлов"],
    "You don't have permission to upload or create files here" : "У вас нет прав для загрузки или создания файлов здесь.",
    "_Uploading %n file_::_Uploading %n files_" : ["Закачка %n файла","Закачка %n файлов","Закачка %n файлов"],
    "\"{name}\" is an invalid file name." : "\"{name}\" это неправильное имя файла.",
    "Your storage is full, files can not be updated or synced anymore!" : "Ваше хранилище заполнено, произведите очистку перед загрузкой новых файлов.",
    "Your storage is almost full ({usedSpacePercent}%)" : "Ваше хранилище почти заполнено ({usedSpacePercent}%)",
    "Encryption App is enabled but your keys are not initialized, please log-out and log-in again" : "Приложение для шифрования активно, но ваши ключи не инициализированы, выйдите из системы и войдите заново",
    "Invalid private key for Encryption App. Please update your private key password in your personal settings to recover access to your encrypted files." : "Закрытый ключ приложения шифрования недействителен. Обновите закрытый ключ в личных настройках, чтобы восстановить доступ к зашифрованным файлам.",
    "Encryption was disabled but your files are still encrypted. Please go to your personal settings to decrypt your files." : "Шифрование было отключено, но ваши файлы остались зашифрованными. Зайдите на страницу личных настроек для того, чтобы расшифровать их.",
    "_matches '{filter}'_::_match '{filter}'_" : ["соответствует '{filter}'","соответствуют '{filter}'","соответствуют '{filter}'"],
    "{dirs} and {files}" : "{dirs} и {files}",
    "Favorited" : "Избранное",
    "Favorite" : "Избранное",
    "%s could not be renamed as it has been deleted" : "Невозможно переименовать %s, поскольку объект удалён.",
    "%s could not be renamed" : "%s не может быть переименован",
    "Upload (max. %s)" : "Загрузка (максимум %s)",
    "File handling" : "Управление файлами",
    "Maximum upload size" : "Максимальный размер загружаемого файла",
    "max. possible: " : "макс. возможно: ",
    "Save" : "Сохранить",
    "Settings" : "Настройки",
    "WebDAV" : "WebDAV",
    "Use this address to access your Files via WebDAV" : "Используйте этот адрес для доступа файлам через WebDAV",
    "New" : "Новый",
    "New text file" : "Новый текстовый файл",
    "Text file" : "Текстовый файл",
    "New folder" : "Новый каталог",
    "Folder" : "Каталог",
    "From link" : "Объект по ссылке",
    "Upload" : "Загрузить",
    "Cancel upload" : "Отменить загрузку",
    "No files yet" : "Пока ещё нет файлов",
    "Upload some content or sync with your devices!" : "Загрузите что-нибудь или синхронизируйте со своими устройствами!",
    "No entries found in this folder" : "Ничего не найдено",
    "Select all" : "Выбрать все",
    "Upload too large" : "Файл слишком велик",
    "The files you are trying to upload exceed the maximum size for file uploads on this server." : "Файлы, которые вы пытаетесь загрузить, превышают лимит максимального размера на этом сервере.",
    "Files are being scanned, please wait." : "Идет сканирование файлов. Пожалуйста подождите.",
    "Currently scanning" : "В настоящее время сканируется",
    "No favorites" : "Нет избранного",
    "Files and folders you mark as favorite will show up here" : "Здесь появятся файлы и каталоги, отмеченные как избранные"
},
"nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);");


text:
package matlabcontrol.link;

import static matlabcontrol.link.ArrayUtils.*;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import matlabcontrol.MatlabInvocationException;
import matlabcontrol.MatlabOperations;
import matlabcontrol.link.MatlabType.MatlabTypeGetter;

/**
 *
 * @since 4.2.0
 * @author Joshua Kaplan
 */
@SuppressWarnings("rawtypes")
class ArrayMultidimensionalizer {
	static class PrimitiveArrayGetter implements MatlabTypeGetter<Object> {
		private static final long serialVersionUID = -3228683201238234004L;
		private int[] _lengths;
		private Object _array;

		private boolean _retreived = false;

		private final boolean _getRealPart;
		private final boolean _keepLinear;

		public PrimitiveArrayGetter(boolean realPart, boolean keepLinear) {
			_getRealPart = realPart;
			_keepLinear = keepLinear;
		}

		public boolean isRealPart() {
			return _getRealPart;
		}

		public int[] getLengths() {
			return _lengths;
		}

		/**
		 * May be null if this represents the imaginary part and the array has no imaginary values or the array was
		 * empty.
		 *
		 * @return
		 */
		@Override
		public Object retrieve() {
			//Validate
			if (!_retreived) {
				throw new IllegalStateException("array has not yet been retrieved");
			}

			if (_array != null && !_keepLinear) {
				return multidimensionalize(_array, _lengths);
			} else {
				return _array;
			}
		}

		@Override
		public void getInMatlab(MatlabOperations ops, String variableName) throws MatlabInvocationException {
			//Retrieve lengths of array
			double[] size = (double[]) ops.returningEval("size(" + variableName + ");", 1)[0];
			_lengths = new int[size.length];
			for (int i = 0; i < size.length; i++) {
				_lengths[i] = (int) size[i];
			}

			//Retrieve array
			String name = (String) ops.returningEval("genvarname('" + variableName + "_getter', who);", 1)[0];
			ops.setVariable(name, this);
			try {
				if (_getRealPart) {
					ops.eval(name + ".setArray(reshape(" + variableName + ", 1, []));");
				} else {
					//If the array has an imaginary part, retrieve it
					boolean isReal = ((boolean[]) ops.returningEval("isreal(" + variableName + ");", 1)[0])[0];
					if (!isReal) {
						ops.eval(name + ".setArray(imag(reshape(" + variableName + ", 1, [])));");
					}
				}
			} finally {
				ops.eval("clear " + name);
			}

			_retreived = true;
		}

		//The following methods are to be called only from MATLAB to pass in the array

		public void setArray(byte[] array) {
			_array = array;
		}

		public void setArray(short[] array) {
			_array = array;
		}

		public void setArray(int[] array) {
			_array = array;
		}

		public void setArray(long[] array) {
			_array = array;
		}

		public void setArray(float[] array) {
			_array = array;
		}

		public void setArray(double[] array) {
			_array = array;
		}

		public void setArray(char[] array) {
			_array = array;
		}

		public void setArray(boolean[] array) {
			_array = array;
		}
	}

	/**
	 * Creates a rectangular multidimensional array from {@code linearArray} with the length of each dimension specified
	 * by {@code lengths}. The length of the array must equal the total size specified by {@code lengths}.
	 *
	 * @param <T>
	 * @param linearArray a primitive linear array
	 * @param lengths length of each dimension
	 * @return multidimensional array
	 */
	static Object multidimensionalize(Object linearArray, int[] lengths) {
		//Validate primitive single dimension array
		if (linearArray == null || !linearArray.getClass().isArray() &&
				!linearArray.getClass().getComponentType().isPrimitive()) {
			throw new RuntimeException("linear array must be a single dimension primitive array");
		}

		//Validate lengths
		if (getNumberOfElements(lengths) != Array.getLength(linearArray)) {
			throw new RuntimeException("linear array's length does not match the total size of the provided " +
					"multidimensional lengths\n" +
					"Linear Array Length: " + Array.getLength(linearArray) + "\n" +
					"Multidimensional Lengths: " + Arrays.toString(lengths) + "\n" +
					"Multidimensional Total Size: " + getNumberOfElements(lengths));
		}

		Class componentType = linearArray.getClass().getComponentType();
		Class outputArrayType = getArrayClass(componentType, lengths.length);
		ArrayFillOperation fillOperation = FILL_OPERATIONS.get(componentType);

		return multidimensionalize_internal(linearArray, outputArrayType, fillOperation, lengths, 0, new int[lengths.length]);
	}

	/**
	 * The real logic of the multidimensionalize. This method recurs on itself, hence the need for the extra parameters.
	 * This method does not store state in any external variables.
	 *
	 * @param linearArray
	 * @param outputArrayType
	 * @param fillOperation operation used to fill in single dimension pieces of the array
	 * @param lengths
	 * @param depth should be {@code 0} initially
	 * @param indices must be the length of {@code lengths}
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private static Object multidimensionalize_internal(Object linearArray, Class<?> outputArrayType,
			ArrayFillOperation fillOperation, int[] lengths, int depth, int[] indices) {
		Class<?> componentType = outputArrayType.getComponentType();
		int arrayLength = lengths[depth];
		Object array = Array.newInstance(componentType, arrayLength);

		//If what was created holds an array, then fill it
		if (componentType.isArray()) {
			//If the array that was created holds the primitive array: double[], int[], boolean[] etc.
			if (componentType.getComponentType().isPrimitive()) {
				//Iterate over the created array, placing a primitive array in each index
				for (int i = 0; i < arrayLength; i++) {
					indices[indices.length - 2] = i;

					//Create the primitive array
					Object primitiveArray = Array.newInstance(componentType.getComponentType(), lengths[lengths.length - 1]);

					//Fill the primitive array with values from the linear array
					fillOperation.fill(primitiveArray, linearArray, indices, lengths);

					//Place primitive array into the enclosing array
					Array.set(array, i, primitiveArray);
				}
			} else {
				//Iterate over the created array, placing an array in each index (using recursion)
				for (int i = 0; i < arrayLength; i++) {
					indices[depth] = i;

					Object innerArray = multidimensionalize_internal(linearArray, componentType,
							fillOperation, lengths, depth + 1, indices);
					Array.set(array, i, innerArray);
				}
			}
		}
		//If the componentType is not an array, then the original request was to create a one dimensional array
		else {
			System.arraycopy(linearArray, 0, array, 0, arrayLength);
		}

		return array;
	}

	private static final Map<Class<?>, ArrayFillOperation<?>> FILL_OPERATIONS;

	static {
		Map<Class<?>, ArrayFillOperation<?>> map = new HashMap<Class<?>, ArrayFillOperation<?>>();

		map.put(byte.class, new ByteArrayFillOperation());
		map.put(short.class, new ShortArrayFillOperation());
		map.put(int.class, new IntArrayFillOperation());
		map.put(long.class, new LongArrayFillOperation());
		map.put(float.class, new FloatArrayFillOperation());
		map.put(double.class, new DoubleArrayFillOperation());
		map.put(boolean.class, new BooleanArrayFillOperation());
		map.put(char.class, new CharArrayFillOperation());

		FILL_OPERATIONS = Collections.unmodifiableMap(map);
	}

	private static interface ArrayFillOperation<T> {
		public void fill(T dst, T src, int[] indices, int[] lengths);
	}

	private static class ByteArrayFillOperation implements ArrayFillOperation<byte[]> {
		@Override
		public void fill(byte[] dst, byte[] src, int[] indices, int[] lengths) {
			for (int i = 0; i < dst.length; i++) {
				indices[indices.length - 1] = i;
				int linearIndex = multidimensionalIndicesToLinearIndex(lengths, indices);
				dst[i] = src[linearIndex];
			}
		}
	}

	private static class ShortArrayFillOperation implements ArrayFillOperation<short[]> {
		@Override
		public void fill(short[] dst, short[] src, int[] indices, int[] lengths) {
			for (int i = 0; i < dst.length; i++) {
				indices[indices.length - 1] = i;
				int linearIndex = multidimensionalIndicesToLinearIndex(lengths, indices);
				dst[i] = src[linearIndex];
			}
		}
	}

	private static class IntArrayFillOperation implements ArrayFillOperation<int[]> {
		@Override
		public void fill(int[] dst, int[] src, int[] indices, int[] lengths) {
			for (int i = 0; i < dst.length; i++) {
				indices[indices.length - 1] = i;
				int linearIndex = multidimensionalIndicesToLinearIndex(lengths, indices);
				dst[i] = src[linearIndex];
			}
		}
	}

	private static class LongArrayFillOperation implements ArrayFillOperation<long[]> {
		@Override
		public void fill(long[] dst, long[] src, int[] indices, int[] lengths) {
			for (int i = 0; i < dst.length; i++) {
				indices[indices.length - 1] = i;
				int linearIndex = multidimensionalIndicesToLinearIndex(lengths, indices);
				dst[i] = src[linearIndex];
			}
		}
	}

	private static class FloatArrayFillOperation implements ArrayFillOperation<float[]> {
		@Override
		public void fill(float[] dst, float[] src, int[] indices, int[] lengths) {
			for (int i = 0; i < dst.length; i++) {
				indices[indices.length - 1] = i;
				int linearIndex = multidimensionalIndicesToLinearIndex(lengths, indices);
				dst[i] = src[linearIndex];
			}
		}
	}

	private static class DoubleArrayFillOperation implements ArrayFillOperation<double[]> {
		@Override
		public void fill(double[] dst, double[] src, int[] indices, int[] lengths) {
			for (int i = 0; i < dst.length; i++) {
				indices[indices.length - 1] = i;
				int linearIndex = multidimensionalIndicesToLinearIndex(lengths, indices);
				dst[i] = src[linearIndex];
			}
		}
	}

	private static class BooleanArrayFillOperation implements ArrayFillOperation<boolean[]> {
		@Override
		public void fill(boolean[] dst, boolean[] src, int[] indices, int[] lengths) {
			for (int i = 0; i < dst.length; i++) {
				indices[indices.length - 1] = i;
				int linearIndex = multidimensionalIndicesToLinearIndex(lengths, indices);
				dst[i] = src[linearIndex];
			}
		}
	}

	private static class CharArrayFillOperation implements ArrayFillOperation<char[]> {
		@Override
		public void fill(char[] dst, char[] src, int[] indices, int[] lengths) {
			for (int i = 0; i < dst.length; i++) {
				indices[indices.length - 1] = i;
				int linearIndex = multidimensionalIndicesToLinearIndex(lengths, indices);
				dst[i] = src[linearIndex];
			}
		}
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="match_parent"
	android:layout_height="match_parent">

	<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
				  android:layout_width="match_parent"
				  android:layout_height="wrap_content"
				  android:layout_margin="8dp"
				  android:orientation="vertical">

		<TextView
			style="@style/Text.Sample"
			android:text="TODO"/>

	</LinearLayout>

</ScrollView>


text:
from model import model

import numpy as np
import tensorflow as tf

import os
import sys
import time

TRAIN = 'train.csv'

tf.app.flags.DEFINE_string('data_directory', './data/', 'directory containing the data sets')
tf.app.flags.DEFINE_float('validation_fraction', 0.2, 'fraction of training data set aside for validation')
tf.app.flags.DEFINE_integer('batch_size', 1000, 'batch size for training')
tf.app.flags.DEFINE_integer('num_epochs', 10, 'number of epochs trained')
tf.app.flags.DEFINE_float('learning_rate', 0.0001, 'learning rate in training')
tf.app.flags.DEFINE_string('model_name', 'mnist', 'name of the saved model')
tf.app.flags.DEFINE_string('models_directory', './models/', 'directory to save the tensorflow model')
tf.app.flags.DEFINE_string('logs_directory', './logs/', 'directory to save logs')
tf.app.flags.DEFINE_integer('run_id', 1, 'id of this run, affects logs')

FLAGS = tf.app.flags.FLAGS

def train(train_images, train_labels, validation_images=None, validation_labels=None):
    assert train_images.shape[1] == train_images.shape[2]
    train_size, image_size, _ = train_images.shape

    images_ph = tf.placeholder(tf.float32, shape=(None, image_size, image_size))
    labels_ph = tf.placeholder(tf.int64, shape=(None,))
    keep_prob = tf.placeholder(tf.float32)

    logits = model(images_ph, keep_prob, reuse=None)
    loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits, labels_ph))
    accuracy = tf.contrib.metrics.accuracy(tf.argmax(logits, 1), labels_ph)
    optimizer = tf.train.AdamOptimizer(learning_rate=FLAGS.learning_rate)

    train_op = optimizer.minimize(loss)
    init_op = tf.global_variables_initializer()

    merged_summary = tf.merge_summary([
        tf.scalar_summary('loss', loss),
        tf.scalar_summary('accuracy', accuracy)
    ])
    params_summary = tf.merge_summary([
        tf.scalar_summary('hyper-parameters/learning_rate', FLAGS.learning_rate),
        tf.scalar_summary('hyper-parameters/num_epochs', FLAGS.num_epochs),
        tf.scalar_summary('hyper-parameters/batch_size', FLAGS.batch_size)
    ])

    logs_path = os.path.join(FLAGS.logs_directory, 'run%d' % FLAGS.run_id)
    if not os.path.exists(logs_path):
        os.mkdir(logs_path)
    summary_writer = tf.train.SummaryWriter(logs_path)
    with tf.Session() as session:
        session.run(init_op)
        t0 = time.time()
        summary_writer.add_summary(session.run(params_summary))
        for e in range(FLAGS.num_epochs):
            for i in range(0, train_size, FLAGS.batch_size):
                batch_images = train_images[i:i + FLAGS.batch_size, :, :]
                batch_labels = train_labels[i:i + FLAGS.batch_size]

                step_loss, step_accuracy, _ = session.run([loss, accuracy, train_op], feed_dict={
                    images_ph: batch_images,
                    labels_ph: batch_labels,
                    keep_prob: 0.5
                })

                progress = ((e + (min(i + FLAGS.batch_size, train_size) / train_size)) / FLAGS.num_epochs)
                eta = (time.time() - t0) * (1 / progress - 1)

                sys.stdout.write('\r')
                sys.stdout.write('\033[K')
                sys.stdout.write('progress: %.2f%%, loss: %.3f, accuracy: %.3f, eta: %.3f' %
                                 (progress * 100, step_loss, 100 * step_accuracy, eta))
                sys.stdout.flush()

            if validation_images is not None:
                step_merged_summary = session.run(merged_summary, feed_dict={
                    images_ph: validation_images,
                    labels_ph: validation_labels,
                    keep_prob: 1.0
                })
                summary_writer.add_summary(step_merged_summary, e)

        sys.stdout.write('\n')
        saver = tf.train.Saver(write_version=tf.train.SaverDef.V2)
        save_path = os.path.join(FLAGS.models_directory, FLAGS.model_name + '.ckpt')
        saver.save(sess=session, save_path=save_path)
        print('saved tensorflow model at %s' % save_path, flush=True)

def main(_):
    train_path = os.path.join(FLAGS.data_directory, TRAIN)
    print('reading data from %s ...' % train_path, end='', flush=True)
    train_data = np.genfromtxt(train_path, dtype=np.uint8, delimiter=',', skip_header=1)
    print(' done', flush=True)

    labels = train_data[:, 0].astype(np.int64)

    image_size = int(np.sqrt(train_data.shape[1] - 1))
    images = train_data[:, 1:].reshape((-1, image_size, image_size)).astype(np.float32)
    images = np.array(images * 2.0 / 255 - 1, copy=False)

    train_size = int(np.round(images.shape[0] * (1 - FLAGS.validation_fraction)))
    train_images = images[:train_size, :, :]
    train_labels = labels[:train_size]

    train_images = np.concatenate((train_images, np.fliplr(train_images)))
    train_labels = np.concatenate((train_labels, train_labels))

    validation_images = images[train_size:, :, :] if train_size != images.shape[0] else None
    validation_labels = labels[train_size:] if train_size != images.shape[0] else None

    print('beginning training...', flush=True)
    train(train_images, train_labels, validation_images, validation_labels)
    print('training done', flush=True)

if __name__ == '__main__':
    tf.app.run()


text:
A curated list of awesome PostgreSQL tools, scripts, slides, and short examples. inspired by the other [awesome lists](https://github.com/bayandin/awesome-awesomeness).

- [awesome-postgresql](https://github.com/devton/awesome-postgresql#awesome-postgresql)
  - [Extensions / Tools](#extensions-and-tools)
  - [Utilities](#utilities)
    - [Useful Scripts] (#useful-scripts)
    - [Useful Examples] (#useful-examples)
    - [Useful Slides](#useful-slides)

### Extensions and Tools
- [Citus](https://github.com/citusdata/citus) - Citus horizontally scales PostgreSQL across commodity servers using sharding and replication. Its query engine parallelizes incoming SQL queries across these servers to enable real-time responses on large datasets.
- [ldap2pg](https://github.com/dalibo/ldap2pg) - manage roles and ACL.
- [PL/V8](http://pgxn.org/dist/plv8/doc/plv8.html) - Content for starting and do quick consults about PL/V8.
- [PGBouncer](https://pgbouncer.github.io/) - Lightweight connection pooler for PostgreSQL.
- [pgpool-II](http://pgpool.net) - Connection pooler, load balancer, replicator, also implementing parallel query.
- [PGStrom (GPU Process)
](https://wiki.postgresql.org/wiki/PGStrom) - Designed to off-load several CPU intensive workloads to GPU devices.
- [PostgREST](http://postgrest.com/) - Standalone web server that tuns your database directly into a RESTful API.
- [pgloader](http://pgloader.io/) - Load data into PostgreSQL. Any Data.
- [pgbundle](https://github.com/adjust/pgbundle) - Manage your PostgreSQL extensions with Pgbundle.
- [pgcli](http://pgcli.com/) - Postgres CLI with autocompletion and syntax highlighting.
- [Barman](http://www.pgbarman.org) - Backup and recovery manager.
- [psql2csv](https://github.com/fphilipe/psql2csv) - Run a query in psql and output the result as CSV.
- [pome](https://github.com/rach/pome) - A Postgres Metrics Dashboard which can be deployed as a binary.
- [pg_bulkload](http://ossc-db.github.io/pg_bulkload/index.html) - It's a high speed data loading utility for PostgreSQL.

#### SQL plan visualizers
- [Depesz](http://explain.depesz.com/)
- [Tatiyants](http://tatiyants.com/pev/)

### Utilities

##### Useful scripts

- [Views dependency handle](http://pretius.com/postgresql-stop-worrying-about-table-and-view-dependencies/) - Script to handle with tabe and view dependencies easy.

##### Useful Examples

- [Listen / Notify in Node.js](http://bjorngylling.com/2011-04-13/postgres-listen-notify-with-node-js.html) - Tiny how to use about listen / notify
- [JSON Queries](http://webrobots.io/postgresql-json-queries/) - Real examples of using lateral joins and recursive queries on JSON structures
- [Using postgresql](http://www.postgresguide.com) - Real examples about using postgresql with awesome examples

##### Useful slides

- [Full text search (PT_BR)](http://pt.slideshare.net/spjuliano/fts-26392077) -  Deep intro on full text search on postgresql
- [PostgREST + Mihtril.js](http://slideshare.net/tonnysk823/using-mithriljs-postgrest-to-build-and-consume-apis) - Real example of postREST using

### Blogs
- [2ndQuadrant](http://blog.2ndquadrant.com/)
- [PostgreSQL-Consulting](http://blog.postgresql-consulting.com/)
- [Depesz](http://www.depesz.com/)

### Screencasts
- [PG Casts](https://www.pgcasts.com/)


text:
from pyflink.common import Time, WatermarkStrategy, Duration
from pyflink.common.typeinfo import Types
from pyflink.common.watermark_strategy import TimestampAssigner
from pyflink.datastream import StreamExecutionEnvironment
from pyflink.datastream.functions import KeyedProcessFunction, RuntimeContext
from pyflink.datastream.state import ValueStateDescriptor, StateTtlConfig

class Sum(KeyedProcessFunction):

    def __init__(self):
        self.state = None

    def open(self, runtime_context: RuntimeContext):
        state_descriptor = ValueStateDescriptor("state", Types.FLOAT())
        state_ttl_config = StateTtlConfig \
            .new_builder(Time.seconds(1)) \
            .set_update_type(StateTtlConfig.UpdateType.OnReadAndWrite) \
            .disable_cleanup_in_background() \
            .build()
        state_descriptor.enable_time_to_live(state_ttl_config)
        self.state = runtime_context.get_state(state_descriptor)

    def process_element(self, value, ctx: 'KeyedProcessFunction.Context'):
        # retrieve the current count
        current = self.state.value()
        if current is None:
            current = 0

        # update the state's count
        current += value[2]
        self.state.update(current)

        # register an event time timer 2 seconds later
        ctx.timer_service().register_event_time_timer(ctx.timestamp() + 2000)

    def on_timer(self, timestamp: int, ctx: 'KeyedProcessFunction.OnTimerContext'):
        yield ctx.get_current_key(), self.state.value()

class MyTimestampAssigner(TimestampAssigner):

    def extract_timestamp(self, value, record_timestamp: int) -> int:
        return int(value[0])

def event_timer_timer_demo():
    env = StreamExecutionEnvironment.get_execution_environment()

    ds = env.from_collection(
        collection=[
            (1000, 'Alice', 110.1),
            (4000, 'Bob', 30.2),
            (3000, 'Alice', 20.0),
            (2000, 'Bob', 53.1),
            (5000, 'Alice', 13.1),
            (3000, 'Bob', 3.1),
            (7000, 'Bob', 16.1),
            (10000, 'Alice', 20.1)
        ],
        type_info=Types.TUPLE([Types.LONG(), Types.STRING(), Types.FLOAT()]))

    ds = ds.assign_timestamps_and_watermarks(
        WatermarkStrategy.for_bounded_out_of_orderness(Duration.of_seconds(2))
                         .with_timestamp_assigner(MyTimestampAssigner()))

    # apply the process function onto a keyed stream
    ds.key_by(lambda value: value[1]) \
      .process(Sum()) \
      .print()

    # submit for execution
    env.execute()

if __name__ == '__main__':
    event_timer_timer_demo()


text:
package tech.tablesaw.api;

import static com.google.common.base.Preconditions.checkArgument;

import com.google.common.base.Preconditions;
import it.unimi.dsi.fastutil.longs.*;
import java.nio.ByteBuffer;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.stream.LongStream;
import tech.tablesaw.columns.AbstractColumnParser;
import tech.tablesaw.columns.Column;
import tech.tablesaw.columns.numbers.DoubleColumnType;
import tech.tablesaw.columns.numbers.LongColumnType;
import tech.tablesaw.columns.numbers.NumberColumnFormatter;
import tech.tablesaw.selection.BitmapBackedSelection;
import tech.tablesaw.selection.Selection;

/** A column that contains long values */
public class LongColumn extends NumberColumn<LongColumn, Long> implements CategoricalColumn<Long> {

  protected final LongArrayList data;

  private LongColumn(String name, LongArrayList data) {
    super(LongColumnType.instance(), name, LongColumnType.DEFAULT_PARSER);
    setPrintFormatter(NumberColumnFormatter.ints());
    this.data = data;
  }

  /** {@inheritDoc} */
  @Override
  public int valueHash(int rowNumber) {
    return Long.hashCode(getLong(rowNumber));
  }

  /** {@inheritDoc} */
  @Override
  public boolean equals(int rowNumber1, int rowNumber2) {
    return getLong(rowNumber1) == getLong(rowNumber2);
  }

  public static LongColumn create(final String name) {
    return new LongColumn(name, new LongArrayList());
  }

  public static LongColumn create(String name, long... arr) {
    return new LongColumn(name, new LongArrayList(arr));
  }

  public static LongColumn create(String name, int initialSize) {
    LongColumn column = new LongColumn(name, new LongArrayList(initialSize));
    for (int i = 0; i < initialSize; i++) {
      column.appendMissing();
    }
    return column;
  }

  public static LongColumn create(String name, LongStream stream) {
    LongArrayList list = new LongArrayList();
    stream.forEach(list::add);
    return new LongColumn(name, list);
  }

  /** {@inheritDoc} */
  @Override
  public LongColumn createCol(String name, int initialSize) {
    return create(name, initialSize);
  }

  /** {@inheritDoc} */
  @Override
  public LongColumn createCol(String name) {
    return create(name);
  }

  /**
   * Returns a new numeric column initialized with the given name and size. The values in the column
   * are integers beginning at startsWith and continuing through size (exclusive), monotonically
   * increasing by 1 TODO consider a generic fill function including steps or random samples from
   * various distributions
   */
  public static LongColumn indexColumn(
      final String columnName, final int size, final int startsWith) {
    final LongColumn indexColumn = LongColumn.create(columnName, size);
    for (long i = 0; i < size; i++) {
      indexColumn.append(i + startsWith);
    }
    return indexColumn;
  }

  /** {@inheritDoc} */
  @Override
  public String getString(final int row) {
    final long value = getLong(row);
    return getPrintFormatter().format(value);
  }

  public static boolean valueIsMissing(long value) {
    return LongColumnType.valueIsMissing(value);
  }

  /** {@inheritDoc} */
  @Override
  public int size() {
    return data.size();
  }

  /** {@inheritDoc} */
  @Override
  public void clear() {
    data.clear();
  }

  /** {@inheritDoc} */
  @Override
  public Long get(int index) {
    long result = getLong(index);
    return isMissingValue(result) ? null : result;
  }

  /** {@inheritDoc} */
  @Override
  public LongColumn subset(final int[] rows) {
    final LongColumn c = this.emptyCopy();
    for (final int row : rows) {
      c.append(getLong(row));
    }
    return c;
  }

  public Selection isIn(final long... numbers) {
    final Selection results = new BitmapBackedSelection();
    final LongRBTreeSet intSet = new LongRBTreeSet(numbers);
    for (int i = 0; i < size(); i++) {
      if (intSet.contains(getLong(i))) {
        results.add(i);
      }
    }
    return results;
  }

  public Selection isNotIn(final long... numbers) {
    final Selection results = new BitmapBackedSelection();
    results.addRange(0, size());
    results.andNot(isIn(numbers));
    return results;
  }

  /** {@inheritDoc} */
  @Override
  public LongColumn unique() {
    final LongSet values = new LongOpenHashSet();
    for (int i = 0; i < size(); i++) {
      values.add(getLong(i));
    }
    final LongColumn column = LongColumn.create(name() + " Unique values");
    for (long value : values) {
      column.append(value);
    }
    return column;
  }

  /** {@inheritDoc} */
  @Override
  public LongColumn top(int n) {
    final LongArrayList top = new LongArrayList();
    final long[] values = data.toLongArray();
    LongArrays.parallelQuickSort(values, LongComparators.OPPOSITE_COMPARATOR);
    for (int i = 0; i < n && i < values.length; i++) {
      top.add(values[i]);
    }
    return new LongColumn(name() + "[Top " + n + "]", top);
  }

  /** {@inheritDoc} */
  @Override
  public LongColumn bottom(final int n) {
    final LongArrayList bottom = new LongArrayList();
    final long[] values = data.toLongArray();
    LongArrays.parallelQuickSort(values);
    for (int i = 0; i < n && i < values.length; i++) {
      bottom.add(values[i]);
    }
    return new LongColumn(name() + "[Bottoms " + n + "]", bottom);
  }

  /** {@inheritDoc} */
  @Override
  public LongColumn lag(int n) {
    final int srcPos = n >= 0 ? 0 : -n;
    final long[] dest = new long[size()];
    final int destPos = Math.max(n, 0);
    final int length = n >= 0 ? size() - n : size() + n;

    for (int i = 0; i < size(); i++) {
      dest[i] = LongColumnType.missingValueIndicator();
    }

    long[] array = data.toLongArray();

    System.arraycopy(array, srcPos, dest, destPos, length);
    return new LongColumn(name() + " lag(" + n + ")", new LongArrayList(dest));
  }

  /** {@inheritDoc} */
  @Override
  public LongColumn removeMissing() {
    LongColumn result = copy();
    result.clear();
    LongListIterator iterator = data.iterator();
    while (iterator.hasNext()) {
      final long v = iterator.nextLong();
      if (!isMissingValue(v)) {
        result.append(v);
      }
    }
    return result;
  }

  public LongColumn append(long i) {
    data.add(i);
    return this;
  }

  /** {@inheritDoc} */
  @Override
  public LongColumn append(Long val) {
    if (val == null) {
      appendMissing();
    } else {
      append(val.longValue());
    }
    return this;
  }

  /** {@inheritDoc} */
  @Override
  public LongColumn copy() {
    LongColumn copy = new LongColumn(name(), data.clone());
    copy.setPrintFormatter(getPrintFormatter());
    copy.locale = locale;
    return copy;
  }

  public long[] asLongArray() {
    // TODO: Need to figure out how to handle NaN -> Maybe just use a list with nulls?
    final long[] result = new long[size()];
    for (int i = 0; i < size(); i++) {
      result[i] = getLong(i);
    }
    return result;
  }

  /**
   * Returns a DateTimeColumn where each value is the LocalDateTime represented by the values in
   * this column
   *
   *
The values in this column must be longs that represent the time in milliseconds from the
   * epoch as in standard Java date/time calculations
   *
   * @param offset The ZoneOffset to use in the calculation
   * @return A column of LocalDateTime values
   */
  public DateTimeColumn asDateTimes(ZoneOffset offset) {
    DateTimeColumn column = DateTimeColumn.create(name() + ": date time");
    for (int i = 0; i < size(); i++) {
      column.append(Instant.ofEpochMilli(getLong(i)).atZone(offset).toLocalDateTime());
    }
    return column;
  }

  /** {@inheritDoc} */
  @Override
  public Iterator<Long> iterator() {
    return data.iterator();
  }

  public LongIterator longIterator() {
    return data.iterator();
  }

  /** {@inheritDoc} */
  @Override
  public Long[] asObjectArray() {
    final Long[] output = new Long[size()];
    for (int i = 0; i < size(); i++) {
      if (!isMissing(i)) {
        output[i] = getLong(i);
      } else {
        output[i] = null;
      }
    }
    return output;
  }

  /** {@inheritDoc} */
  @Override
  public int compare(Long o1, Long o2) {
    return Long.compare(o1, o2);
  }

  /** {@inheritDoc} */
  @Override
  public LongColumn set(int i, Long val) {
    return val == null ? setMissing(i) : set(i, (long) val);
  }

  public LongColumn set(int i, long val) {
    data.set(i, val);
    return this;
  }

  /** {@inheritDoc} */
  @Override
  public Column<Long> set(int row, String stringValue, AbstractColumnParser<?> parser) {
    return set(row, parser.parseLong(stringValue));
  }

  /** {@inheritDoc} */
  @Override
  public LongColumn append(final Column<Long> column) {
    Preconditions.checkArgument(
        column.type() == this.type(),
        "Column '%s' has type %s, but column '%s' has type %s.",
        name(),
        type(),
        column.name(),
        column.type());
    final LongColumn numberColumn = (LongColumn) column;
    final int size = numberColumn.size();
    for (int i = 0; i < size; i++) {
      append(numberColumn.getLong(i));
    }
    return this;
  }

  /** {@inheritDoc} */
  @Override
  public LongColumn append(Column<Long> column, int row) {
    checkArgument(
        column.type() == this.type(),
        "Column '%s' has type %s, but column '%s' has type %s.",
        name(),
        type(),
        column.name(),
        column.type());
    return append(((LongColumn) column).getLong(row));
  }

  /** {@inheritDoc} */
  @Override
  public LongColumn set(int row, Column<Long> column, int sourceRow) {
    checkArgument(
        column.type() == this.type(),
        "Column '%s' has type %s, but column '%s' has type %s.",
        name(),
        type(),
        column.name(),
        column.type());
    return set(row, ((LongColumn) column).getLong(sourceRow));
  }

  /** {@inheritDoc} */
  @Override
  public LongColumn appendMissing() {
    return append(LongColumnType.missingValueIndicator());
  }

  /** {@inheritDoc} */
  @Override
  public byte[] asBytes(int rowNumber) {
    return ByteBuffer.allocate(LongColumnType.instance().byteSize())
        .putLong(getLong(rowNumber))
        .array();
  }

  /** {@inheritDoc} */
  @Override
  public Set<Long> asSet() {
    return new HashSet<>(unique().asList());
  }

  /** {@inheritDoc} */
  @Override
  public int countUnique() {
    LongSet uniqueElements = new LongOpenHashSet();
    for (int i = 0; i < size(); i++) {
      uniqueElements.add(getLong(i));
    }
    return uniqueElements.size();
  }

  /**
   * Returns the value at the given index. The actual value is returned if the ColumnType is
   * INTEGER. Otherwise the value is rounded as described below.
   *
   *
Returns the closest {@code int} to the argument, with ties rounding to positive infinity.
   *
   *
Special cases:
   *
   *
Special cases:
   *
   *

   *
If the argument is NaN, the result is 0.
   *
If the argument is positive infinity or any value greater than or equal to the value of
   *       {@code Integer.MAX_VALUE}, an error will be thrown
   *

   *
   * @param row the index of the value to be rounded to an integer.
   * @return the value of the argument rounded to the nearest {@code int} value.
   * @throws ClassCastException if the absolute value of the value to be rounded is too large to be
   *     cast to an int
   */
  public long getLong(int row) {
    return data.getLong(row);
  }

  /** {@inheritDoc} */
  @Override
  public double getDouble(int row) {
    long value = data.getLong(row);
    if (isMissingValue(value)) {
      return DoubleColumnType.missingValueIndicator();
    }
    return value;
  }

  public boolean isMissingValue(long value) {
    return LongColumnType.valueIsMissing(value);
  }

  /** {@inheritDoc} */
  @Override
  public boolean isMissing(int rowNumber) {
    return isMissingValue(getLong(rowNumber));
  }

  /** {@inheritDoc} */
  @Override
  public LongColumn setMissing(int i) {
    return set(i, LongColumnType.missingValueIndicator());
  }

  /** {@inheritDoc} */
  @Override
  public void sortAscending() {
    data.sort(LongComparators.NATURAL_COMPARATOR);
  }

  /** {@inheritDoc} */
  @Override
  public void sortDescending() {
    data.sort(LongComparators.OPPOSITE_COMPARATOR);
  }

  /** {@inheritDoc} */
  @Override
  public LongColumn appendObj(Object obj) {
    if (obj == null) {
      return appendMissing();
    }
    if (obj instanceof Long) {
      return append((long) obj);
    }
    throw new IllegalArgumentException("Could not append " + obj.getClass());
  }

  /** {@inheritDoc} */
  @Override
  public LongColumn appendCell(final String value) {
    try {
      return append(parser().parseLong(value));
    } catch (final NumberFormatException e) {
      throw new NumberFormatException(
          "Error adding value to column " + name() + ": " + e.getMessage());
    }
  }

  /** {@inheritDoc} */
  @Override
  public LongColumn appendCell(final String value, AbstractColumnParser<?> parser) {
    try {
      return append(parser.parseLong(value));
    } catch (final NumberFormatException e) {
      throw new NumberFormatException(
          "Error adding value to column " + name() + ": " + e.getMessage());
    }
  }

  /** {@inheritDoc} */
  @Override
  public String getUnformattedString(final int row) {
    final long value = getLong(row);
    if (LongColumnType.valueIsMissing(value)) {
      return "";
    }
    return String.valueOf(value);
  }

  /** {@inheritDoc} */
  @Override
  public Table countByCategory() {
    return null;
  }

  /**
   * Returns a new IntColumn containing a value for each value in this column
   *
   *
A narrowing conversion of a signed integer to an integral type T simply discards all but the
   * n lowest order bits, where n is the number of bits used to represent type T. In addition to a
   * possible loss of information about the magnitude of the numeric value, this may cause the sign
   * of the resulting value to differ from the sign of the input value.
   *
   *
In other words, if the element being converted is larger (or smaller) than Integer.MAX_VALUE
   * (or Integer.MIN_VALUE) you will not get a conventionally good conversion.
   *
   *
Despite the fact that overflow, underflow, or other loss of information may occur, a
   * narrowing primitive conversion never results in a run-time exception.
   *
   *
A missing value in the receiver is converted to a missing value in the result
   */
  @Override
  public IntColumn asIntColumn() {
    IntColumn result = IntColumn.create(name());
    for (long d : data) {
      if (LongColumnType.valueIsMissing(d)) {
        result.appendMissing();
      } else {
        result.append((int) d);
      }
    }
    return result;
  }

  /**
   * Returns a new ShortColumn containing a value for each value in this column
   *
   *
A narrowing conversion of a signed long to an integral type T simply discards all but the n
   * lowest order bits, where n is the number of bits used to represent type T. In addition to a
   * possible loss of information about the magnitude of the numeric value, this may cause the sign
   * of the resulting value to differ from the sign of the input value.
   *
   *
In other words, if the element being converted is larger (or smaller) than Short.MAX_VALUE
   * (or Short.MIN_VALUE) you will not get a conventionally good conversion.
   *
   *
Despite the fact that overflow, underflow, or other loss of information may occur, a
   * narrowing primitive conversion never results in a run-time exception.
   *
   *
A missing value in the receiver is converted to a missing value in the result
   */
  @Override
  public ShortColumn asShortColumn() {
    ShortColumn result = ShortColumn.create(name());
    for (long d : data) {
      if (LongColumnType.valueIsMissing(d)) {
        result.appendMissing();
      } else {
        result.append((short) d);
      }
    }
    return result;
  }

  /**
   * Returns a new FloatColumn containing a value for each value in this column
   *
   *
A widening primitive conversion from a long to a float does not lose information about the
   * overall magnitude of a numeric value. It may, however, result in loss of precision - that is,
   * the result may lose some of the least significant bits of the value. In this case, the
   * resulting floating-point value will be a correctly rounded version of the integer value, using
   * IEEE 754 round-to-nearest mode.
   *
   *
Despite the fact that a loss of precision may occur, a widening primitive conversion never
   * results in a run-time exception.
   *
   *
A missing value in the receiver is converted to a missing value in the result
   */
  @Override
  public FloatColumn asFloatColumn() {
    FloatColumn result = FloatColumn.create(name());
    for (long d : data) {
      if (LongColumnType.valueIsMissing(d)) {
        result.appendMissing();
      } else {
        result.append(d);
      }
    }
    return result;
  }

  /**
   * Returns a new DoubleColumn containing a value for each value in this column
   *
   *
A widening primitive conversion from a long to a double does not lose information about the
   * overall magnitude of a numeric value. It may, however, result in loss of precision - that is,
   * the result may lose some of the least significant bits of the value. In this case, the
   * resulting floating-point value will be a correctly rounded version of the integer value, using
   * IEEE 754 round-to-nearest mode.
   *
   *
Despite the fact that a loss of precision may occur, a widening primitive conversion never
   * results in a run-time exception.
   *
   *
A missing value in the receiver is converted to a missing value in the result
   */
  @Override
  public DoubleColumn asDoubleColumn() {
    DoubleColumn result = DoubleColumn.create(name());
    for (long d : data) {
      if (LongColumnType.valueIsMissing(d)) {
        result.appendMissing();
      } else {
        result.append(d);
      }
    }
    return result;
  }
}


text:
/*
 * Rule: Include all compatible vendor prefixes to reach a wider
 * range of users.
 */

CSSLint.addRule({

    //rule information
    id: "compatible-vendor-prefixes",
    name: "Require compatible vendor prefixes",
    desc: "Include all compatible vendor prefixes to reach a wider range of users.",
    browsers: "All",

    //initialization
    init: function (parser, reporter) {
        "use strict";
        var rule = this,
            compatiblePrefixes,
            properties,
            prop,
            variations,
            prefixed,
            i,
            len,
            inKeyFrame = false,
            arrayPush = Array.prototype.push,
            applyTo = [];

        // See http://peter.sh/experiments/vendor-prefixed-css-property-overview/ for details
        compatiblePrefixes = {
            "animation"                  : "webkit moz",
            "animation-delay"            : "webkit moz",
            "animation-direction"        : "webkit moz",
            "animation-duration"         : "webkit moz",
            "animation-fill-mode"        : "webkit moz",
            "animation-iteration-count"  : "webkit moz",
            "animation-name"             : "webkit moz",
            "animation-play-state"       : "webkit moz",
            "animation-timing-function"  : "webkit moz",
            "appearance"                 : "webkit moz",
            "border-end"                 : "webkit moz",
            "border-end-color"           : "webkit moz",
            "border-end-style"           : "webkit moz",
            "border-end-width"           : "webkit moz",
            "border-image"               : "webkit moz o",
            "border-radius"              : "webkit",
            "border-start"               : "webkit moz",
            "border-start-color"         : "webkit moz",
            "border-start-style"         : "webkit moz",
            "border-start-width"         : "webkit moz",
            "box-align"                  : "webkit moz ms",
            "box-direction"              : "webkit moz ms",
            "box-flex"                   : "webkit moz ms",
            "box-lines"                  : "webkit ms",
            "box-ordinal-group"          : "webkit moz ms",
            "box-orient"                 : "webkit moz ms",
            "box-pack"                   : "webkit moz ms",
            "box-sizing"                 : "webkit moz",
            "box-shadow"                 : "webkit moz",
            "column-count"               : "webkit moz ms",
            "column-gap"                 : "webkit moz ms",
            "column-rule"                : "webkit moz ms",
            "column-rule-color"          : "webkit moz ms",
            "column-rule-style"          : "webkit moz ms",
            "column-rule-width"          : "webkit moz ms",
            "column-width"               : "webkit moz ms",
            "hyphens"                    : "epub moz",
            "line-break"                 : "webkit ms",
            "margin-end"                 : "webkit moz",
            "margin-start"               : "webkit moz",
            "marquee-speed"              : "webkit wap",
            "marquee-style"              : "webkit wap",
            "padding-end"                : "webkit moz",
            "padding-start"              : "webkit moz",
            "tab-size"                   : "moz o",
            "text-size-adjust"           : "webkit ms",
            "transform"                  : "webkit moz ms o",
            "transform-origin"           : "webkit moz ms o",
            "transition"                 : "webkit moz o",
            "transition-delay"           : "webkit moz o",
            "transition-duration"        : "webkit moz o",
            "transition-property"        : "webkit moz o",
            "transition-timing-function" : "webkit moz o",
            "user-modify"                : "webkit moz",
            "user-select"                : "webkit moz ms",
            "word-break"                 : "epub ms",
            "writing-mode"               : "epub ms"
        };

        for (prop in compatiblePrefixes) {
            if (compatiblePrefixes.hasOwnProperty(prop)) {
                variations = [];
                prefixed = compatiblePrefixes[prop].split(" ");
                for (i = 0, len = prefixed.length; i < len; i++) {
                    variations.push("-" + prefixed[i] + "-" + prop);
                }
                compatiblePrefixes[prop] = variations;
                arrayPush.apply(applyTo, variations);
            }
        }

        parser.addListener("startrule", function () {
            properties = [];
        });

        parser.addListener("startkeyframes", function (event) {
            inKeyFrame = event.prefix || true;
        });

        parser.addListener("endkeyframes", function () {
            inKeyFrame = false;
        });

        parser.addListener("property", function (event) {
            var name = event.property;
            if (CSSLint.Util.indexOf(applyTo, name.text) > -1) {

                // e.g., -moz-transform is okay to be alone in @-moz-keyframes
                if (!inKeyFrame || typeof inKeyFrame !== "string" ||
                        name.text.indexOf("-" + inKeyFrame + "-") !== 0) {
                    properties.push(name);
                }
            }
        });

        parser.addListener("endrule", function () {
            if (!properties.length) {
                return;
            }

            var propertyGroups = {},
                i,
                len,
                name,
                prop,
                variations,
                value,
                full,
                actual,
                item,
                propertiesSpecified;

            for (i = 0, len = properties.length; i < len; i++) {
                name = properties[i];

                for (prop in compatiblePrefixes) {
                    if (compatiblePrefixes.hasOwnProperty(prop)) {
                        variations = compatiblePrefixes[prop];
                        if (CSSLint.Util.indexOf(variations, name.text) > -1) {
                            if (!propertyGroups[prop]) {
                                propertyGroups[prop] = {
                                    full : variations.slice(0),
                                    actual : [],
                                    actualNodes: []
                                };
                            }
                            if (CSSLint.Util.indexOf(propertyGroups[prop].actual, name.text) === -1) {
                                propertyGroups[prop].actual.push(name.text);
                                propertyGroups[prop].actualNodes.push(name);
                            }
                        }
                    }
                }
            }

            for (prop in propertyGroups) {
                if (propertyGroups.hasOwnProperty(prop)) {
                    value = propertyGroups[prop];
                    full = value.full;
                    actual = value.actual;

                    if (full.length > actual.length) {
                        for (i = 0, len = full.length; i < len; i++) {
                            item = full[i];
                            if (CSSLint.Util.indexOf(actual, item) === -1) {
                                propertiesSpecified = (actual.length === 1) ? actual[0] : (actual.length === 2) ? actual.join(" and ") : actual.join(", ");
                                reporter.report("The property " + item + " is compatible with " + propertiesSpecified + " and should be included as well.", value.actualNodes[0].line, value.actualNodes[0].col, rule);
                            }
                        }

                    }
                }
            }
        });
    }
});


text:
// Copyright 2016 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.packages;

import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet;
import com.google.devtools.build.lib.concurrent.ThreadSafety.Immutable;
import com.google.devtools.build.lib.util.Fingerprint;
import java.util.ArrayList;
import java.util.Objects;

/**
 * Captures the set of providers rules and aspects can advertise. It is either of:
 *
 *

 *
a set of builtin and Starlark providers
 *
"can have any provider" set that alias rules have.
 *

 *
 *
Built-in providers should in theory only contain subclasses of {@link
 * com.google.devtools.build.lib.analysis.TransitiveInfoProvider}, but our current dependency
 * structure does not allow a reference to that class here.
 */
@Immutable
public final class AdvertisedProviderSet {
  private final boolean canHaveAnyProvider;
  private final ImmutableSet<Class<?>> builtinProviders;
  private final ImmutableSet<StarlarkProviderIdentifier> starlarkProviders;

  private AdvertisedProviderSet(
      boolean canHaveAnyProvider,
      ImmutableSet<Class<?>> builtinProviders,
      ImmutableSet<StarlarkProviderIdentifier> starlarkProviders) {
    this.canHaveAnyProvider = canHaveAnyProvider;
    this.builtinProviders = builtinProviders;
    this.starlarkProviders = starlarkProviders;
  }

  public static final AdvertisedProviderSet ANY =
      new AdvertisedProviderSet(
          true, ImmutableSet.<Class<?>>of(), ImmutableSet.<StarlarkProviderIdentifier>of());
  public static final AdvertisedProviderSet EMPTY =
      new AdvertisedProviderSet(
          false, ImmutableSet.<Class<?>>of(), ImmutableSet.<StarlarkProviderIdentifier>of());

  public static AdvertisedProviderSet create(
      ImmutableSet<Class<?>> builtinProviders,
      ImmutableSet<StarlarkProviderIdentifier> starlarkProviders) {
    if (builtinProviders.isEmpty() && starlarkProviders.isEmpty()) {
      return EMPTY;
    }
    return new AdvertisedProviderSet(false, builtinProviders, starlarkProviders);
  }

  @Override
  public int hashCode() {
    return Objects.hash(canHaveAnyProvider, builtinProviders, starlarkProviders);
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj) {
      return true;
    }

    if (!(obj instanceof AdvertisedProviderSet)) {
      return false;
    }

    AdvertisedProviderSet that = (AdvertisedProviderSet) obj;
    return Objects.equals(this.canHaveAnyProvider, that.canHaveAnyProvider)
        && Objects.equals(this.builtinProviders, that.builtinProviders)
        && Objects.equals(this.starlarkProviders, that.starlarkProviders);
  }

  @Override
  public String toString() {
    if (canHaveAnyProvider()) {
      return "Any Provider";
    }
    return String.format(
        "allowed built-in providers=%s, allowed Starlark providers=%s",
        getBuiltinProviders(), getStarlarkProviders());
  }

  /** Checks whether the rule can have any provider.
   *
   *  Used for alias rules.
   */
  public boolean canHaveAnyProvider() {
    return canHaveAnyProvider;
  }

  /** Get all advertised built-in providers. */
  public ImmutableSet<Class<?>> getBuiltinProviders() {
    return builtinProviders;
  }

  /** Get all advertised Starlark providers. */
  public ImmutableSet<StarlarkProviderIdentifier> getStarlarkProviders() {
    return starlarkProviders;
  }

  /**
   * Adds the fingerprints of this {@link AdvertisedProviderSet} into {@code fp}.
   *
   *
Fingerprints of {@link AdvertisedProviderSet} must have the following properties:
   *
   *

   *
If {@code aps1.equals(aps2)} then {@code aps1} and {@code aps2} have the same
   *       fingerprint.
   *
If {@code !aps1.equals(aps2)} then {@code aps1} and {@code aps2} don't have the same
   *       fingerprint (except for unintentional digest collisions).
   *

   *
   *
In other words, {@link #fingerprint} is a proxy for {@link #equals}. These properties *do
   * not* need to be maintained across Blaze versions (e.g. there's no need to worry about
   * historical serialized fingerprints).
   */
  public void fingerprint(Fingerprint fp) {
    fp.addBoolean(canHaveAnyProvider);
    // #builtinProviders and #starlarkProviders are ordered according to the calls to the builder
    // methods, and that order is assumed to be deterministic.
    builtinProviders.forEach(clazz -> fp.addString(clazz.getCanonicalName()));
    starlarkProviders.forEach(starlarkProvider -> starlarkProvider.fingerprint(fp));
  }

  public static Builder builder() {
    return new Builder();
  }

  /**
   * Returns {@code true} if this provider set can have any provider, or if it advertises the
   * specific built-in provider requested.
   */
  public boolean advertises(Class<?> builtinProviderClass) {
    if (canHaveAnyProvider()) {
      return true;
    }
    return builtinProviders.contains(builtinProviderClass);
  }

  /**
   * Returns {@code true} if this provider set can have any provider, or if it advertises the
   * specific Starlark provider requested.
   */
  public boolean advertises(StarlarkProviderIdentifier starlarkProvider) {
    if (canHaveAnyProvider()) {
      return true;
    }
    return starlarkProviders.contains(starlarkProvider);
  }

  /** Builder for {@link AdvertisedProviderSet} */
  public static class Builder {
    private boolean canHaveAnyProvider;
    private final ArrayList<Class<?>> builtinProviders;
    private final ArrayList<StarlarkProviderIdentifier> starlarkProviders;

    private Builder() {
      builtinProviders = new ArrayList<>();
      starlarkProviders = new ArrayList<>();
    }

    /**
     * Advertise all providers inherited from a parent rule.
     */
    public Builder addParent(AdvertisedProviderSet parentSet) {
      Preconditions.checkState(!canHaveAnyProvider, "Alias rules inherit from no other rules");
      Preconditions.checkState(!parentSet.canHaveAnyProvider(),
          "Cannot inherit from alias rules");
      builtinProviders.addAll(parentSet.getBuiltinProviders());
      starlarkProviders.addAll(parentSet.getStarlarkProviders());
      return this;
    }

    public Builder addBuiltin(Class<?> builtinProvider) {
      this.builtinProviders.add(builtinProvider);
      return this;
    }

    public void canHaveAnyProvider() {
      Preconditions.checkState(builtinProviders.isEmpty() && starlarkProviders.isEmpty());
      this.canHaveAnyProvider = true;
    }

    public AdvertisedProviderSet build() {
      if (canHaveAnyProvider) {
        Preconditions.checkState(builtinProviders.isEmpty() && starlarkProviders.isEmpty());
        return ANY;
      }
      return AdvertisedProviderSet.create(
          ImmutableSet.copyOf(builtinProviders), ImmutableSet.copyOf(starlarkProviders));
    }

    public Builder addStarlark(String providerName) {
      starlarkProviders.add(StarlarkProviderIdentifier.forLegacy(providerName));
      return this;
    }

    public Builder addStarlark(StarlarkProviderIdentifier id) {
      starlarkProviders.add(id);
      return this;
    }

    public Builder addStarlark(Provider.Key id) {
      starlarkProviders.add(StarlarkProviderIdentifier.forKey(id));
      return this;
    }
  }
}


text:
using System;
using System.Collections.Generic;
using Autofac;
using Autofac.Core;
using VSTOContrib.Core;
using VSTOContrib.Core.RibbonFactory.Interfaces;

namespace VSTOContrib.Autofac
{
    /// <summary>
    /// Autofac View Model Factory
    /// </summary>
    public class AutofacViewModelFactory : IViewModelFactory, IDisposable
    {
        readonly IContainer autofacContainer;

        readonly Dictionary<IRibbonViewModel, ILifetimeScope> lifetimeScopeLookups =
            new Dictionary<IRibbonViewModel, ILifetimeScope>();

        readonly bool shouldDisposeContainer;

        /// <summary>
        /// Creates new instance of AutofacViewModelFactory using an Autofac Module
        ///
        /// This will cause the container to be disposed when the AutofacViewModelFactory is disposed
        /// </summary>
        public AutofacViewModelFactory(IModule moduleToRegister)
        {
            var containerBuilder = new ContainerBuilder();
            containerBuilder.RegisterModule(moduleToRegister);
            autofacContainer = containerBuilder.Build();
            shouldDisposeContainer = true;
        }

        /// <summary>
        /// Creates new instance of AutofacViewModelFactory using an Autofac Container
        ///
        /// This will cause the container NOT to be disposed when the AutofacViewModelFactory is disposed
        /// </summary>
        /// <param name="autofacContainer"></param>
        public AutofacViewModelFactory(IContainer autofacContainer)
        {
            this.autofacContainer = autofacContainer;
        }

        /// <summary>
        /// Builds the requested viewmodel type
        /// </summary>
        /// <returns></returns>
        public IRibbonViewModel Resolve(Type viewModelType)
        {
            var lifetime = autofacContainer.BeginLifetimeScope();
            var viewModel = (IRibbonViewModel)lifetime.Resolve(viewModelType);
            lifetimeScopeLookups.Add(viewModel, lifetime);

            return viewModel;
        }

        /// <summary>
        /// Releases the viewmodel instance and gives the factory the chance to clean up any related services
        /// </summary>
        /// <param name="viewModelInstance"></param>
        public void Release(IRibbonViewModel viewModelInstance)
        {
            var lifetimeScope = lifetimeScopeLookups[viewModelInstance];
            lifetimeScopeLookups.Remove(viewModelInstance);
            lifetimeScope.Dispose();
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            if (shouldDisposeContainer)
                autofacContainer.Dispose();
        }
    }
}


text:
package br.com.swconsultoria.cte;

import br.com.swconsultoria.cte.dom.ConfiguracoesCte;
import br.com.swconsultoria.cte.dom.enuns.ServicosEnum;
import br.com.swconsultoria.cte.exception.CteException;
import br.com.swconsultoria.cte.schema_300.evPrestDesacordo.TEvento;
import br.com.swconsultoria.cte.schema_300.evPrestDesacordo.TRetEvento;
import br.com.swconsultoria.cte.util.XmlCteUtil;

import javax.xml.bind.JAXBException;

/**
 * @author Samuel Oliveira - samuel@swconsultoria.com.br
 * Data: 28/09/2017 - 11:11
 */
class PrestacaoDesacordo {

    static TRetEvento eventoPrestacaoDesacordo(ConfiguracoesCte config, TEvento enviEvento, boolean valida) throws CteException {

        try {

            String xml = XmlCteUtil.objectToXml(enviEvento);
            xml = xml.replaceAll(" xmlns:ns2=\"http://www.w3.org/2000/09/xmldsig#\"", "");
            xml = xml.replaceAll("<evento v", "<evento xmlns=\"http://www.portalfiscal.inf.br/cte\" v");

            xml = Eventos.enviarEvento(config, xml, ServicosEnum.PRESTACAO_DESACORDO, valida);

            return XmlCteUtil.xmlToObject(xml, TRetEvento.class);

        } catch (JAXBException e) {
            throw new CteException(e.getMessage());
        }

    }

}


text:
/**
 * Constructors.
 */

exports.PubEmitterSocket = require('./sockets/pub-emitter');
exports.SubEmitterSocket = require('./sockets/sub-emitter');
exports.PushSocket = require('./sockets/push');
exports.PullSocket = require('./sockets/pull');
exports.PubSocket = require('./sockets/pub');
exports.SubSocket = require('./sockets/sub');
exports.ReqSocket = require('./sockets/req');
exports.RepSocket = require('./sockets/rep');
exports.Socket = require('./sockets/sock');

/**
 * Socket types.
 */

exports.types = {
  'pub-emitter': exports.PubEmitterSocket,
  'sub-emitter': exports.SubEmitterSocket,
  'push': exports.PushSocket,
  'pull': exports.PullSocket,
  'pub': exports.PubSocket,
  'sub': exports.SubSocket,
  'req': exports.ReqSocket,
  'rep': exports.RepSocket
};

/**
 * Return a new socket of the given `type`.
 *
 * @param {String} type
 * @param {Object} options
 * @return {Socket}
 * @api public
 */

exports.socket = function(type, options){
  var fn = exports.types[type];
  if (!fn) throw new Error('invalid socket type "' + type + '"');
  return new fn(options);
};