text:
#include "state.h"

#include "parse.h"
#include "debug.h"

#include <fstream>

using namespace std;

void State::readFile(const string &fil) {
  ifstream ifs(fil.c_str());
  kvData kvd;
  while(getkvDataInline(ifs, kvd)) {
    if(kvd.category == "file") {
      string itemname = kvd.consume("name");
      vector<int> depend = sti(tokenize(kvd.consume("dependencies"), " "));
      CHECK(!items.count(itemname));
      items[itemname] = Item::MakeOriginal(atoll(kvd.consume("size").c_str()), atoll(kvd.consume("timestamp").c_str()), atochecksum(kvd.consume("checksum").c_str()), set<int>(depend.begin(), depend.end()));
    } else {
      CHECK(0);
    }
  }
  CHECK(kvd.isDone());
}

const map<string, Item> &State::getItemDb() const {
  return items;
}

const Item *State::findItem(const string &name) const {
  if(items.count(name))
    return &items.find(name)->second;
  return NULL;
}

void State::process(const Instruction &in, int tversion) {
  if(in.type == TYPE_CREATE) {
    CHECK(0);
  } else if(in.type == TYPE_ROTATE) {
    vector<Item> srcs;
    for(int i = 0; i < in.rotate_paths.size(); i++) {
      CHECK(items.count(in.rotate_paths[i].first));
      srcs.push_back(Item::MakeOriginal(items[in.rotate_paths[i].first].size(), in.rotate_paths[i].second, items[in.rotate_paths[i].first].checksum(), items[in.rotate_paths[i].first].getVersions()));
      srcs.back().addVersion(tversion);
      //printf("%lld %s\n", srcs.back().metadata.timestamp, srcs.back().checksum().toString().c_str());
    }
    for(int i = 0; i < in.rotate_paths.size(); i++)
      items[in.rotate_paths[(i + 1) % in.rotate_paths.size()].first] = srcs[i];
    for(int i = 0; i < in.rotate_paths.size(); i++)
      items[in.rotate_paths[i].first].addVersion(tversion);
  } else if(in.type == TYPE_DELETE) {
    CHECK(items.count(in.delete_path));
    items.erase(items.find(in.delete_path));
  } else if(in.type == TYPE_COPY) {
    //dprintf("Copying from %s\n", in.copy_source.c_str());
    //dprintf("%d\n", items.count(in.copy_source));
    CHECK(items.count(in.copy_source));
    items[in.copy_dest] = Item::MakeOriginal(items[in.copy_source].size(), in.copy_dest_meta, items[in.copy_source].checksum(), items[in.copy_source].getVersions());
    items[in.copy_dest].addVersion(tversion);
  } else if(in.type == TYPE_APPEND) {
    CHECK(items.count(in.append_path));
    items[in.append_path] = Item::MakeOriginal(in.append_size, in.append_meta, in.append_checksum, items[in.append_path].getVersions());
    items[in.append_path].addVersion(tversion);
  } else if(in.type == TYPE_STORE) {
    if(items.count(in.store_path))
      items.erase(items.find(in.store_path));
    items[in.store_path] = Item::MakeOriginal(in.store_size, in.store_meta, in.store_source->checksumPart(in.store_size), set<int>());
    items[in.store_path].addVersion(tversion);
  } else if(in.type == TYPE_TOUCH) {
    CHECK(items.count(in.touch_path));
    items[in.touch_path] = Item::MakeOriginal(items[in.touch_path].size(), in.touch_meta, items[in.touch_path].checksum(), items[in.touch_path].getVersions());
    // We're not going to add a version entry because the client can pull that data straight out of the information file
  } else {
    CHECK(0);
  }
}

void State::writeOut(const string &fn) const {
  ofstream ofs(fn.c_str());
  for(map<string, Item>::const_iterator itr = items.begin(); itr != items.end(); itr++) {
    //dprintf("Processing %s\n", itr->first.c_str());
    kvData kvd;
    kvd.category = "file";
    kvd.kv["name"] = itr->first;
    kvd.kv["size"] = StringPrintf("%lld", itr->second.size());
    kvd.kv["timestamp"] = StringPrintf("%lld", itr->second.metadata().timestamp);
    kvd.kv["checksum"] = itr->second.checksum().toString();
    {
      const set<int> &vers = itr->second.getVersions();
      string vs;
      for(set<int>::const_iterator itr = vers.begin(); itr != vers.end(); itr++) {
        if(itr != vers.begin())
          vs += " ";
        vs += StringPrintf("%d", *itr);
      }
      kvd.kv["dependencies"] = vs;
    }
    putkvDataInline(ofs, kvd, "name");
  }
}

void dumpa(string *str, const string &txt, const vector<pair<bool, string> > &vek) {
  *str += "  " + txt + "\n";
  for(int i = 0; i < vek.size(); i++)
    *str += StringPrintf("    %d:%s\n", vek[i].first, vek[i].second.c_str());
}

string Instruction::textout() const {
  string rvx;
  CHECK(type >= 0 && type < TYPE_END);
  rvx = type_strs[type] + "\n";
  dumpa(&rvx, "Depends:", depends);
  dumpa(&rvx, "Removes:", removes);
  dumpa(&rvx, "Creates:", creates);
  return rvx;
}

string Instruction::processString() const {
  kvData kvd;
  if(type == TYPE_CREATE) {
    CHECK(0);
  } else if(type == TYPE_ROTATE) {
    kvd.category = "rotate";
    for(int i = 0; i < rotate_paths.size(); i++) {
      kvd.kv[StringPrintf("src%02ddst%02d", i, (i + rotate_paths.size() - 1) % rotate_paths.size())] = rotate_paths[i].first;
      kvd.kv[StringPrintf("meta%02d", i)] = rotate_paths[i].second.toKvd();
    }
  } else if(type == TYPE_DELETE) {
    kvd.category = "delete";
    kvd.kv["path"] = delete_path;
  } else if(type == TYPE_COPY) {
    kvd.category = "copy";
    kvd.kv["source"] = copy_source;
    kvd.kv["dest"] = copy_dest;
    kvd.kv["dest_meta"] = copy_dest_meta.toKvd();
  } else if(type == TYPE_APPEND) {
    kvd.category = "touch";
    kvd.kv["path"] = append_path;
    kvd.kv["meta"] = append_meta.toKvd();
    // TODO: Checksum?
  } else if(type == TYPE_STORE) {
    kvd.category = "touch";
    kvd.kv["path"] = store_path;
    kvd.kv["meta"] = store_meta.toKvd();
    // TODO: Checksum?
  } else if(type == TYPE_TOUCH) {
    kvd.category = "touch";
    kvd.kv["path"] = touch_path;
    kvd.kv["meta"] = touch_meta.toKvd();
  } else {
    CHECK(0);
  }
  return putkvDataInlineString(kvd);
}

long long Instruction::size() const {
  if(type == TYPE_STORE) {
    return usedperitem + store_size;
  } else if(type == TYPE_APPEND) {
    return usedperitem + append_size - append_begin;
  } else {
    return usedperitem;
  }
}

int getsize(const vector<pair<bool, string> > &dt) {
  int ts  = 0;
  for(int i = 0; i < dt.size(); i++)
    ts += dt[i].second.size() + sizeof(dt[0]);
  return ts;
}

int getsize(const vector<pair<string, Metadata> > &dt) {
  int ts  = 0;
  for(int i = 0; i < dt.size(); i++)
    ts += dt[i].first.size() + sizeof(dt[0]);
  return ts;
}

int Instruction::bytesused() const {
  return getsize(depends) + getsize(removes) + getsize(creates) + getsize(rotate_paths) + create_path.size() + delete_path.size() + copy_source.size() + copy_dest.size() + append_path.size() + store_path.size() + touch_path.size() + sizeof(*this);
}


text:
require 'svnx/propset/options'
require 'svnx/base/command'

module Svnx::Propset
  class Command < Svnx::Base::Command
    noncaching
    nonxml
  end
end

redpajama_set_name: RedPajamaGithub


text:
/**
 * Module dependencies.
 */

var path = require('path'),
    fs = require('fs'),
    dirname = path.dirname,
    basename = path.basename,
    extname = path.extname,
    exists = fs.existsSync || path.existsSync,
    join = path.join;

/**
 * Cross-platform function that checks, whether the path is absolute, copied from express/lib/utils
 * @param {String} path
 * @returns {boolean}
 * @api private
 */

var isAbsolute = function(path) {
    if ('/' == path[0])
        return true;
    if (':' == path[1] && '\\' == path[2])
        return true;
};

/**
 * Expose `View`.
 */

module.exports = View;

/**
 * Initialize a new `View` with the given `name`.
 *
 * Options:
 *
 * - `defaultEngine` the default template engine name
 * - `engines` template engine require() cache
 * - `root` roots { prefix: dir } Object for view lookup
 *
 * @param {String} name
 * @param {Object} options
 * @api private
 */

function View(name, options) {
    options = options || {};
    this.name = name;
    this.roots = options.root;
    var engines = options.engines;
    this.defaultEngine = options.defaultEngine;
    var ext = this.ext = extname(name);
    if (!ext)
        name += (ext = this.ext = ('.' != this.defaultEngine[0] ? '.' : '') + this.defaultEngine);
    this.engine = engines[ext] || (engines[ext] = require(ext.slice(1)).__express);
    this.path = this.lookup(name);
}

/**
 * Lookup view by the given `path`
 *
 * @param {String} path
 * @return {String}
 * @api private
 */

View.prototype.lookup = function(path) {
    var root = G.app.get('views_base'); //this.roots[''];
    var lookedUp;
    if (root) {
        // if base root exists, check it first
        lookedUp = this.lookupOne(root, path);
        if (lookedUp) {
            return lookedUp;
        }
    }
    var slashIndex = path.indexOf('/');
    if (slashIndex == -1) {
        slashIndex = path.indexOf('\\');
    }
    if (slashIndex > 0) {
        // if contains prefix
        var prefix = path.substring(0, slashIndex);
        root = this.roots[prefix];
        if (root) {
            // if prefixed root exists, check it
            lookedUp = this.lookupOne(root, path.substring(slashIndex + 1));
            if (lookedUp) {
                return lookedUp;
            }
        }
    }
};

/**
 * Lookup view by the given `path`
 *
 * @param {String} root
 * @param {String} path
 * @return {String}
 * @api private
 */

View.prototype.lookupOne = function(root, path) {
    var ext = this.ext;
    // <path>.<engine>
    if (!isAbsolute(path))
        path = join(root, path);

    if (exists(path)) {
        return path;
    }

    // <path>/index.<engine>
    path = join(dirname(path), basename(path, ext), 'index' + ext);
    if (exists(path)) {
        return path;
    }
};

/**
 * Render with the given `options` and callback `fn(err, str)`.
 *
 * @param {Object} options
 * @param {Function} fn
 * @api private
 */

View.prototype.render = function(options, fn) {
    this.engine(this.path, options, fn);
};


text:
//
//  Generated by the J2ObjC translator.  DO NOT EDIT!
//  source: ./core/src/java/org/apache/lucene/search/similarities/LambdaDF.java
//

#include "J2ObjC_header.h"

#pragma push_macro("INCLUDE_ALL_OrgApacheLuceneSearchSimilaritiesLambdaDF")
#ifdef RESTRICT_OrgApacheLuceneSearchSimilaritiesLambdaDF
#define INCLUDE_ALL_OrgApacheLuceneSearchSimilaritiesLambdaDF 0
#else
#define INCLUDE_ALL_OrgApacheLuceneSearchSimilaritiesLambdaDF 1
#endif
#undef RESTRICT_OrgApacheLuceneSearchSimilaritiesLambdaDF

#if __has_feature(nullability)
#pragma clang diagnostic push
#pragma GCC diagnostic ignored "-Wnullability"
#pragma GCC diagnostic ignored "-Wnullability-completeness"
#endif

#if !defined (OrgApacheLuceneSearchSimilaritiesLambdaDF_) && (INCLUDE_ALL_OrgApacheLuceneSearchSimilaritiesLambdaDF || defined(INCLUDE_OrgApacheLuceneSearchSimilaritiesLambdaDF))
#define OrgApacheLuceneSearchSimilaritiesLambdaDF_

#define RESTRICT_OrgApacheLuceneSearchSimilaritiesLambda 1
#define INCLUDE_OrgApacheLuceneSearchSimilaritiesLambda 1
#include "org/apache/lucene/search/similarities/Lambda.h"

@class OrgApacheLuceneSearchExplanation;
@class OrgApacheLuceneSearchSimilaritiesBasicStats;

/*!
 @brief Computes lambda as docFreq+1 / numberOfDocuments+1.
 */
@interface OrgApacheLuceneSearchSimilaritiesLambdaDF : OrgApacheLuceneSearchSimilaritiesLambda

#pragma mark Public

/*!
 @brief Sole constructor: parameter-free
 */
- (instancetype __nonnull)init;

- (OrgApacheLuceneSearchExplanation *)explainWithOrgApacheLuceneSearchSimilaritiesBasicStats:(OrgApacheLuceneSearchSimilaritiesBasicStats *)stats;

- (jfloat)lambdaWithOrgApacheLuceneSearchSimilaritiesBasicStats:(OrgApacheLuceneSearchSimilaritiesBasicStats *)stats;

- (NSString *)description;

@end

J2OBJC_EMPTY_STATIC_INIT(OrgApacheLuceneSearchSimilaritiesLambdaDF)

FOUNDATION_EXPORT void OrgApacheLuceneSearchSimilaritiesLambdaDF_init(OrgApacheLuceneSearchSimilaritiesLambdaDF *self);

FOUNDATION_EXPORT OrgApacheLuceneSearchSimilaritiesLambdaDF *new_OrgApacheLuceneSearchSimilaritiesLambdaDF_init(void) NS_RETURNS_RETAINED;

FOUNDATION_EXPORT OrgApacheLuceneSearchSimilaritiesLambdaDF *create_OrgApacheLuceneSearchSimilaritiesLambdaDF_init(void);

J2OBJC_TYPE_LITERAL_HEADER(OrgApacheLuceneSearchSimilaritiesLambdaDF)

#endif

#if __has_feature(nullability)
#pragma clang diagnostic pop
#endif
#pragma pop_macro("INCLUDE_ALL_OrgApacheLuceneSearchSimilaritiesLambdaDF")


text:
package org.ovirt.engine.core.bll.storage;

import static org.ovirt.engine.core.bll.hostedengine.HostedEngineHelper.isHostedEngineDomain;

import java.io.Serializable;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;

import javax.inject.Inject;

import org.apache.commons.lang.StringUtils;
import org.ovirt.engine.core.bll.context.CommandContext;
import org.ovirt.engine.core.bll.context.CompensationContext;
import org.ovirt.engine.core.bll.profiles.DiskProfileHelper;
import org.ovirt.engine.core.bll.utils.PermissionSubject;
import org.ovirt.engine.core.common.VdcObjectType;
import org.ovirt.engine.core.common.action.DiskProfileParameters;
import org.ovirt.engine.core.common.action.StorageDomainParametersBase;
import org.ovirt.engine.core.common.action.VdcActionType;
import org.ovirt.engine.core.common.businessentities.StorageDomain;
import org.ovirt.engine.core.common.businessentities.StorageDomainStatus;
import org.ovirt.engine.core.common.businessentities.StorageDomainType;
import org.ovirt.engine.core.common.businessentities.StoragePoolIsoMap;
import org.ovirt.engine.core.common.businessentities.StoragePoolIsoMapId;
import org.ovirt.engine.core.common.businessentities.StorageServerConnections;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.businessentities.profiles.DiskProfile;
import org.ovirt.engine.core.common.businessentities.storage.LUNStorageServerConnectionMap;
import org.ovirt.engine.core.common.businessentities.storage.LUNStorageServerConnectionMapId;
import org.ovirt.engine.core.common.businessentities.storage.LUNs;
import org.ovirt.engine.core.common.businessentities.storage.StorageType;
import org.ovirt.engine.core.common.config.Config;
import org.ovirt.engine.core.common.config.ConfigValues;
import org.ovirt.engine.core.common.errors.EngineMessage;
import org.ovirt.engine.core.common.eventqueue.Event;
import org.ovirt.engine.core.common.eventqueue.EventQueue;
import org.ovirt.engine.core.common.eventqueue.EventResult;
import org.ovirt.engine.core.common.eventqueue.EventType;
import org.ovirt.engine.core.common.utils.Pair;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;
import org.ovirt.engine.core.dao.BaseDiskDao;
import org.ovirt.engine.core.dao.CommandEntityDao;
import org.ovirt.engine.core.dao.DiskImageDynamicDao;
import org.ovirt.engine.core.dao.ImageDao;
import org.ovirt.engine.core.dao.ImageStorageDomainMapDao;
import org.ovirt.engine.core.dao.LunDao;
import org.ovirt.engine.core.dao.StorageServerConnectionDao;
import org.ovirt.engine.core.utils.linq.LinqUtils;
import org.ovirt.engine.core.utils.linq.Predicate;
import org.ovirt.engine.core.utils.threadpool.ThreadPoolUtil;
import org.ovirt.engine.core.utils.transaction.TransactionMethod;
import org.ovirt.engine.core.utils.transaction.TransactionSupport;

public abstract class StorageDomainCommandBase<T extends StorageDomainParametersBase> extends
        StorageHandlingCommandBase<T> {

    @Inject
    protected EventQueue eventQueue;

    protected StorageDomainCommandBase(T parameters) {
        this(parameters, null);
    }

    protected StorageDomainCommandBase(T parameters, CommandContext cmdContext) {
        super(parameters, cmdContext);
    }

    /**
     * Constructor for command creation when compensation is applied on startup
     *
     * @param commandId
     */
    protected StorageDomainCommandBase(Guid commandId) {
        super(commandId);
    }

    @Override
    public Guid getStorageDomainId() {
        return getParameters() != null ? !Guid.Empty.equals(getParameters().getStorageDomainId()) ? getParameters()
                .getStorageDomainId() : super.getStorageDomainId() : super.getStorageDomainId();
    }

    protected boolean canDetachDomain(boolean isDestroyStoragePool, boolean isRemoveLast, boolean isInternal) {
        return checkStoragePool()
                && checkStorageDomain()
                && checkStorageDomainStatus(StorageDomainStatus.Inactive, StorageDomainStatus.Maintenance)
                && (isMaster() || isDestroyStoragePool || checkMasterDomainIsUp())
                && isNotLocalData(isInternal)
                && isDetachAllowed(isRemoveLast)
                && isCinderStorageHasNoDisks();
    }

    protected boolean isDetachAllowed(final boolean isRemoveLast) {
        boolean returnValue = true;
        if (getStoragePoolIsoMap() == null) {
            returnValue = false;
            addCanDoActionMessage(EngineMessage.STORAGE_DOMAIN_NOT_ATTACHED_TO_STORAGE_POOL);
        } else if (!isRemoveLast
                && isMaster()) {

            StorageDomain storage_domains =
                    LinqUtils.firstOrNull(getStorageDomainDao().getAllForStoragePool
                            (getStorageDomain().getStoragePoolId()),
                            new Predicate<StorageDomain>() {
                                @Override
                                public boolean eval(StorageDomain a) {
                                    return a.getId().equals(getStorageDomain().getId())
                                            && a.getStatus() == StorageDomainStatus.Active;
                                }
                            });
            if (storage_domains == null) {
                returnValue = false;
                addCanDoActionMessage(EngineMessage.ERROR_CANNOT_DETACH_LAST_STORAGE_DOMAIN);
            }
        }
        return returnValue;
    }

    protected boolean isNotLocalData(final boolean isInternal) {
        boolean returnValue = true;
        if (this.getStoragePool().isLocal()
                && getStorageDomain().getStorageDomainType() == StorageDomainType.Data
                && !isInternal) {
            returnValue = false;
            addCanDoActionMessage(EngineMessage.VDS_GROUP_CANNOT_DETACH_DATA_DOMAIN_FROM_LOCAL_STORAGE);
        }
        return returnValue;
    }

    private StoragePoolIsoMap getStoragePoolIsoMap() {
        return getStoragePoolIsoMapDao()
                .get(new StoragePoolIsoMapId(getStorageDomain().getId(),
                        getStoragePoolId()));
    }

    protected boolean isCinderStorageHasNoDisks() {
        if (getStorageDomain().getStorageType() == StorageType.CINDER) {
            return validate(CINDERStorageHelper.isCinderHasNoImages(getStorageDomainId()));
        }
        return true;
    }

    private boolean isMaster() {
        return getStorageDomain().getStorageDomainType() == StorageDomainType.Master;
    }

    @Override
    protected void setActionMessageParameters() {
        addCanDoActionMessage(EngineMessage.VAR__TYPE__STORAGE__DOMAIN);
    }

    protected boolean checkStorageDomainNameLengthValid() {
        boolean result = true;
        if (StringUtils.isNotEmpty(getStorageDomain().getStorageName()) &&
                getStorageDomain().getStorageName().length() > Config
                .<Integer> getValue(ConfigValues.StorageDomainNameSizeLimit)) {
            addCanDoActionMessage(EngineMessage.ACTION_TYPE_FAILED_NAME_LENGTH_IS_TOO_LONG);
            result = false;
        }
        return result;
    }

    protected boolean checkStorageDomain() {
        return isStorageDomainNotNull(getStorageDomain());
    }

    protected boolean checkStorageDomainStatus(final StorageDomainStatus... statuses) {
        boolean valid = false;
        StorageDomainStatus status = getStorageDomainStatus();
        if (status != null) {
            valid = Arrays.asList(statuses).contains(status);
        }
        if (!valid) {
            if (status.isStorageDomainInProcess()) {
                return failCanDoAction(EngineMessage.ACTION_TYPE_FAILED_OBJECT_LOCKED);
            }
            addStorageDomainStatusIllegalMessage();
        }
        return valid;
    }

    protected boolean checkStorageDomainStatusNotEqual(StorageDomainStatus status) {
        boolean returnValue = false;
        if (getStorageDomainStatus() != null) {
            returnValue = (getStorageDomainStatus() != status);
            if (!returnValue) {
                addStorageDomainStatusIllegalMessage();
            }
        }
        return returnValue;
    }

    protected boolean checkMasterDomainIsUp() {
        boolean returnValue = true;
        List<StorageDomain> storageDomains = getStorageDomainDao().getAllForStoragePool(getStoragePool().getId());
        storageDomains = LinqUtils.filter(storageDomains, new Predicate<StorageDomain>() {
            @Override
            public boolean eval(StorageDomain a) {
                return a.getStorageDomainType() == StorageDomainType.Master
                        && a.getStatus() == StorageDomainStatus.Active;
            }
        });
        if (storageDomains.isEmpty()) {
            addCanDoActionMessage(EngineMessage.ACTION_TYPE_FAILED_MASTER_STORAGE_DOMAIN_NOT_ACTIVE);
            returnValue = false;
        }
        return returnValue;
    }

    protected void setStorageDomainStatus(StorageDomainStatus status, CompensationContext context) {
        if (getStorageDomain() != null && getStorageDomain().getStoragePoolId() != null) {
            StoragePoolIsoMap map = getStorageDomain().getStoragePoolIsoMapData();
            if(context != null) {
                context.snapshotEntityStatus(map);
            }
            getStorageDomain().setStatus(status);
            getStoragePoolIsoMapDao().updateStatus(map.getId(), status);
        }
    }

    protected boolean isLunsAlreadyInUse(List<String> lunIds) {
        // Get LUNs from DB
        List<LUNs> lunsFromDb = getLunDao().getAll();
        Set<LUNs> lunsUsedBySDs = new HashSet<>();
        Set<LUNs> lunsUsedByDisks = new HashSet<>();

        for (LUNs lun : lunsFromDb) {
            if (lunIds.contains(lun.getLUN_id())) {
                if (lun.getStorageDomainId() != null) {
                    // LUN is already part of a storage domain
                    lunsUsedBySDs.add(lun);
                }
                if (lun.getDiskId() != null) {
                    // LUN is already used by a disk
                    lunsUsedByDisks.add(lun);
                }
            }
        }

        if (!lunsUsedBySDs.isEmpty()) {
            addCanDoActionMessage(EngineMessage.ACTION_TYPE_FAILED_LUNS_ALREADY_PART_OF_STORAGE_DOMAINS);
            Set<String> formattedIds = new HashSet<>();
            for (LUNs lun : lunsUsedBySDs) {
                formattedIds.add(getFormattedLunId(lun, lun.getStorageDomainName()));
            }
            addCanDoActionMessageVariable("lunIds", StringUtils.join(formattedIds, ", "));
        }

        if (!lunsUsedByDisks.isEmpty()) {
            addCanDoActionMessage(EngineMessage.ACTION_TYPE_FAILED_LUNS_ALREADY_USED_BY_DISKS);
            Set<String> formattedIds = new HashSet<>();
            for (LUNs lun : lunsUsedByDisks) {
                formattedIds.add(getFormattedLunId(lun, lun.getDiskAlias()));
            }
            addCanDoActionMessageVariable("lunIds", StringUtils.join(formattedIds, ", "));
        }

       return !lunsUsedBySDs.isEmpty() || !lunsUsedByDisks.isEmpty();
    }

    protected String getFormattedLunId(LUNs lun, String usedByEntityName) {
        return String.format("%1$s (%2$s)", lun.getLUN_id(), usedByEntityName);
    }

    public static void proceedLUNInDb(final LUNs lun, StorageType storageType) {
        proceedLUNInDb(lun, storageType, "");
    }

    protected LunDao getLunDao() {
        return DbFacade.getInstance().getLunDao();
    }

    public static void proceedLUNInDb(final LUNs lun, StorageType storageType, String volumeGroupId) {
        lun.setvolume_group_id(volumeGroupId);
        if (DbFacade.getInstance().getLunDao().get(lun.getLUN_id()) == null) {
            DbFacade.getInstance().getLunDao().save(lun);
        } else if (!volumeGroupId.isEmpty()) {
            DbFacade.getInstance().getLunDao().update(lun);
        }

        if (storageType == StorageType.FCP) {
            // No need to handle connections (FCP storage doesn't utilize connections).
            return;
        }

        for (StorageServerConnections connection : lun.getLunConnections()) {
            StorageServerConnections dbConnection = ISCSIStorageHelper.findConnectionWithSameDetails(connection);
            if (dbConnection == null) {
                connection.setId(Guid.newGuid().toString());
                connection.setstorage_type(storageType);
                DbFacade.getInstance().getStorageServerConnectionDao().save(connection);

            } else {
                connection.setId(dbConnection.getId());
            }
            if (DbFacade.getInstance()
                    .getStorageServerConnectionLunMapDao()
                    .get(new LUNStorageServerConnectionMapId(lun.getLUN_id(),
                            connection.getId())) == null) {
                DbFacade.getInstance().getStorageServerConnectionLunMapDao().save(
                        new LUNStorageServerConnectionMap(lun.getLUN_id(), connection.getId()));
            }
        }
    }

    protected List<Pair<Guid, Boolean>> connectHostsInUpToDomainStorageServer() {
        List<VDS> hostsInStatusUp = getAllRunningVdssInPool();
        List<Callable<Pair<Guid, Boolean>>> callables = new LinkedList<>();
        for (final VDS vds : hostsInStatusUp) {
            callables.add(new Callable<Pair<Guid, Boolean>>() {
                @Override
                public Pair<Guid, Boolean> call() throws Exception {
                    Pair<Guid, Boolean> toReturn = new Pair<>(vds.getId(), Boolean.FALSE);
                    try {
                        boolean connectResult = StorageHelperDirector.getInstance().getItem(getStorageDomain().getStorageType())
                                .connectStorageToDomainByVdsId(getStorageDomain(), vds.getId());
                        toReturn.setSecond(connectResult);
                    } catch (RuntimeException e) {
                        log.error("Failed to connect host '{}' to storage domain (name '{}', id '{}'): {}",
                                vds.getName(),
                                getStorageDomain().getName(),
                                getStorageDomain().getId(),
                                e.getMessage());
                        log.debug("Exception", e);
                    }
                    return toReturn;
                }
            });
        }

        return ThreadPoolUtil.invokeAll(callables);
    }

    protected List<Pair<Guid, Boolean>> disconnectHostsInUpToDomainStorageServer() {
        List<VDS> hostsInStatusUp = getAllRunningVdssInPool();
        List<Callable<Pair<Guid, Boolean>>> callables = new LinkedList<>();
        for (final VDS vds : hostsInStatusUp) {
            callables.add(new Callable<Pair<Guid, Boolean>>() {
                @Override
                public Pair<Guid, Boolean> call() throws Exception {
                    Pair<Guid, Boolean> toReturn = new Pair<>(vds.getId(), Boolean.FALSE);
                    try {
                        boolean connectResult = StorageHelperDirector.getInstance().getItem(getStorageDomain().getStorageType())
                                .disconnectStorageFromDomainByVdsId(getStorageDomain(), vds.getId());
                        toReturn.setSecond(connectResult);
                    } catch (RuntimeException e) {
                        log.error("Failed to disconnect host '{}' to storage domain (name '{}', id '{}'): {}",
                                vds.getName(),
                                getStorageDomain().getName(),
                                getStorageDomain().getId(),
                                e.getMessage());
                        log.debug("Exception", e);
                    }
                    return toReturn;
                }
            });
        }

        return ThreadPoolUtil.invokeAll(callables);
    }

    protected void disconnectAllHostsInPool() {
        getEventQueue().submitEventSync(
                new Event(getParameters().getStoragePoolId(),
                        getParameters().getStorageDomainId(),
                        null,
                        EventType.POOLREFRESH,
                        ""),
                new Callable<EventResult>() {
                    @Override
                    public EventResult call() {
                        runSynchronizeOperation(new RefreshStoragePoolAndDisconnectAsyncOperationFactory());
                        return null;
                    }
                });
    }

    /**
     *  The new master is a data domain which is preferred to be in Active/Unknown status, if selectInactiveWhenNoActiveUnknownDomains
     * is set to True, an Inactive domain will be returned in case that no domain in Active/Unknown status was found.
     * @return an elected master domain or null
     */
    protected StorageDomain electNewMaster(boolean duringReconstruct, boolean selectInactiveWhenNoActiveUnknownDomains, boolean canChooseCurrentMasterAsNewMaster) {
        if (getStoragePool() == null) {
            log.warn("Cannot elect new master: storage pool not found");
            return null;
        }

        List<StorageDomain> storageDomains = getStorageDomainDao().getAllForStoragePool(getStoragePool().getId());

        if (storageDomains.isEmpty()) {
            log.warn("Cannot elect new master, no storage domains found for pool {}", getStoragePool().getName());
            return null;
        }

        Collections.sort(storageDomains, LastTimeUsedAsMasterComp.instance);

        StorageDomain newMaster = null;
        StorageDomain storageDomain = getStorageDomain();

        for (StorageDomain dbStorageDomain : storageDomains) {
            if (isHostedEngineDomain(dbStorageDomain)) {
                continue;
            }
            if ((storageDomain == null || (duringReconstruct || !dbStorageDomain.getId()
                    .equals(storageDomain.getId())))
                    && ((dbStorageDomain.getStorageDomainType() == StorageDomainType.Data)
                    ||
                    (canChooseCurrentMasterAsNewMaster && dbStorageDomain.getStorageDomainType() == StorageDomainType.Master))) {
                if (dbStorageDomain.getStatus() == StorageDomainStatus.Active
                        || dbStorageDomain.getStatus() == StorageDomainStatus.Unknown) {
                    newMaster = dbStorageDomain;
                    break;
                } else if (selectInactiveWhenNoActiveUnknownDomains && newMaster == null
                        && dbStorageDomain.getStatus() == StorageDomainStatus.Inactive) {
                    // if the found domain is inactive, we don't break to continue and look for
                    // active/unknown domain.
                    newMaster = dbStorageDomain;
                }
            }
        }

        return newMaster;
    }

    /**
     * returns new master domain which is in Active/Unknown status
     * @return an elected master domain or null
     */
    protected StorageDomain electNewMaster() {
        return electNewMaster(false, false, false);
    }

    @Override
    public List<PermissionSubject> getPermissionCheckSubjects() {
        return Collections.singletonList(new PermissionSubject(getParameters().getStorageDomainId(),
                VdcObjectType.Storage,
                getActionType().getActionGroup()));
    }

    protected void changeStorageDomainStatusInTransaction(final StoragePoolIsoMap map,
                                                          final StorageDomainStatus status) {
        changeStorageDomainStatusInTransaction(map, status, getCompensationContext());
    }

    protected void changeStorageDomainStatusInTransaction(final StoragePoolIsoMap map,
            final StorageDomainStatus status, final CompensationContext context) {
        executeInNewTransaction(new TransactionMethod<StoragePoolIsoMap>() {
            @SuppressWarnings("synthetic-access")
            @Override
            public StoragePoolIsoMap runInTransaction() {
                context.snapshotEntityStatus(map);
                map.setStatus(status);
                getStoragePoolIsoMapDao().updateStatus(map.getId(), map.getStatus());
                context.stateChanged();
                return null;
            }
        });
    }

    protected void changeDomainStatusWithCompensation(StoragePoolIsoMap map, StorageDomainStatus compensateStatus,
                                                      StorageDomainStatus newStatus, CompensationContext context) {
        map.setStatus(compensateStatus);
        changeStorageDomainStatusInTransaction(map, newStatus, context);
    }

    private StorageDomainStatus getStorageDomainStatus() {
        StorageDomainStatus status = null;
        if (getStorageDomain() != null) {
            status = getStorageDomain().getStatus();
        }
        return status;
    }

    protected void addStorageDomainStatusIllegalMessage() {
        addCanDoActionMessage(EngineMessage.ACTION_TYPE_FAILED_STORAGE_DOMAIN_STATUS_ILLEGAL2);
        addCanDoActionMessageVariable("status", getStorageDomainStatus());
    }

    protected BaseDiskDao getBaseDiskDao() {
        return getDbFacade().getBaseDiskDao();
    }

    protected ImageDao getImageDao() {
        return getDbFacade().getImageDao();
    }

    protected DiskImageDynamicDao getDiskImageDynamicDao() {
        return getDbFacade().getDiskImageDynamicDao();
    }

    protected ImageStorageDomainMapDao getImageStorageDomainMapDao() {
        return getDbFacade().getImageStorageDomainMapDao();
    }

    protected StorageServerConnectionDao getStorageServerConnectionDao() {
        return getDbFacade().getStorageServerConnectionDao();
    }

    protected IStorageHelper getStorageHelper(StorageDomain storageDomain) {
        return StorageHelperDirector.getInstance().getItem(storageDomain.getStorageType());
    }

    protected void executeInNewTransaction(TransactionMethod<?> method) {
        TransactionSupport.executeInNewTransaction(method);
    }

    private static final class LastTimeUsedAsMasterComp implements Comparator<StorageDomain>, Serializable {
        private static final long serialVersionUID = -7736904426129973519L;
        public static final LastTimeUsedAsMasterComp instance = new LastTimeUsedAsMasterComp();

        @Override
        public int compare(StorageDomain o1, StorageDomain o2) {
            return Long.compare(o1.getLastTimeUsedAsMaster(), o2.getLastTimeUsedAsMaster());
        }
    }

    protected CommandEntityDao getCommandEntityDao() {
        return getDbFacade().getCommandEntityDao();
    }

    protected boolean isCinderStorageDomain() {
        return getStorageDomain().getStorageType().isCinderDomain();
    }

    protected EventQueue getEventQueue() {
        return eventQueue;
    }

    /**
     * Creates default disk profile for existing storage domain.
     */
    protected void createDefaultDiskProfile() {
        executeInNewTransaction(new TransactionMethod<Object>() {
            @Override
            public Object runInTransaction() {
                final DiskProfile diskProfile =
                        DiskProfileHelper.createDiskProfile(getStorageDomain().getId(), getStorageDomainName());
                DiskProfileParameters diskProfileParameters = new DiskProfileParameters(diskProfile, true);
                runInternalAction(VdcActionType.AddDiskProfile, diskProfileParameters);
                getCompensationContext().snapshotNewEntity(diskProfile);
                getCompensationContext().stateChanged();
                return null;
            }
        });
    }
}


text:
namespace System.Runtime.InteropServices
{
    [AttributeUsage(AttributeTargets.Class, Inherited = true)]
    public sealed class ComSourceInterfacesAttribute : Attribute
    {
        public ComSourceInterfacesAttribute(string sourceInterfaces)
        {
            Value = sourceInterfaces;
        }

        public ComSourceInterfacesAttribute(Type sourceInterface)
        {
            Value = sourceInterface.FullName!;
        }

        public ComSourceInterfacesAttribute(Type sourceInterface1, Type sourceInterface2)
        {
            Value = sourceInterface1.FullName + "\0" + sourceInterface2.FullName;
        }

        public ComSourceInterfacesAttribute(Type sourceInterface1, Type sourceInterface2, Type sourceInterface3)
        {
            Value = sourceInterface1.FullName + "\0" + sourceInterface2.FullName + "\0" + sourceInterface3.FullName;
        }

        public ComSourceInterfacesAttribute(Type sourceInterface1, Type sourceInterface2, Type sourceInterface3, Type sourceInterface4)
        {
            Value = sourceInterface1.FullName + "\0" + sourceInterface2.FullName + "\0" + sourceInterface3.FullName + "\0" + sourceInterface4.FullName;
        }

        public string Value { get; }
    }
}


text:
using System;
using System.Runtime.Caching.Resources;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using System.Diagnostics;

namespace System.Runtime.Caching
{
    internal sealed class MemoryCacheEntryChangeMonitor : CacheEntryChangeMonitor
    {
        // use UTC minimum DateTime for error free conversions to DateTimeOffset
        private static readonly DateTime s_DATETIME_MINVALUE_UTC = new DateTime(0, DateTimeKind.Utc);
        private const int MAX_CHAR_COUNT_OF_LONG_CONVERTED_TO_HEXADECIMAL_STRING = 16;
        private ReadOnlyCollection<string> _keys;
        private string _regionName;
        private string _uniqueId;
        private DateTimeOffset _lastModified;
        private List<MemoryCacheEntry> _dependencies;

        private MemoryCacheEntryChangeMonitor() { } // hide default .ctor

        private void InitDisposableMembers(MemoryCache cache)
        {
            bool dispose = true;
            try
            {
                bool hasChanged = false;
                string uniqueId = null;
                _dependencies = new List<MemoryCacheEntry>(_keys.Count);
                if (_keys.Count == 1)
                {
                    string k = _keys[0];
                    MemoryCacheEntry entry = cache.GetEntry(k);
                    DateTime utcCreated = s_DATETIME_MINVALUE_UTC;
                    StartMonitoring(cache, entry, ref hasChanged, ref utcCreated);
                    uniqueId = k + utcCreated.Ticks.ToString("X", CultureInfo.InvariantCulture);
                    _lastModified = utcCreated;
                }
                else
                {
                    int capacity = 0;
                    foreach (string key in _keys)
                    {
                        capacity += key.Length + MAX_CHAR_COUNT_OF_LONG_CONVERTED_TO_HEXADECIMAL_STRING;
                    }
                    StringBuilder sb = new StringBuilder(capacity);
                    foreach (string key in _keys)
                    {
                        MemoryCacheEntry entry = cache.GetEntry(key);
                        DateTime utcCreated = s_DATETIME_MINVALUE_UTC;
                        StartMonitoring(cache, entry, ref hasChanged, ref utcCreated);
                        sb.Append(key);
                        sb.Append(utcCreated.Ticks.ToString("X", CultureInfo.InvariantCulture));
                        if (utcCreated > _lastModified)
                        {
                            _lastModified = utcCreated;
                        }
                    }
                    uniqueId = sb.ToString();
                }
                _uniqueId = uniqueId;
                if (hasChanged)
                {
                    OnChanged(null);
                }
                dispose = false;
            }
            finally
            {
                InitializationComplete();
                if (dispose)
                {
                    Dispose();
                }
            }
        }

        private void StartMonitoring(MemoryCache cache, MemoryCacheEntry entry, ref bool hasChanged, ref DateTime utcCreated)
        {
            if (entry != null)
            {
                // pass reference to self so the dependency can notify us when it changes
                entry.AddDependent(cache, this);
                // add dependency to collection so we can dispose it later
                _dependencies.Add(entry);
                // has the entry already changed?
                if (entry.State != EntryState.AddedToCache)
                {
                    hasChanged = true;
                }
                utcCreated = entry.UtcCreated;
            }
            else
            {
                // the entry does not exist--set hasChanged to true so the user is notified
                hasChanged = true;
            }
        }

        //
        // protected members
        //

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (_dependencies != null)
                {
                    foreach (MemoryCacheEntry entry in _dependencies)
                    {
                        if (entry != null)
                        {
                            entry.RemoveDependent(this);
                        }
                    }
                }
            }
        }

        //
        // public and internal members
        //

        public override ReadOnlyCollection<string> CacheKeys { get { return new ReadOnlyCollection<string>(_keys); } }
        public override string RegionName { get { return _regionName; } }
        public override string UniqueId { get { return _uniqueId; } }
        public override DateTimeOffset LastModified { get { return _lastModified; } }
        internal List<MemoryCacheEntry> Dependencies { get { return _dependencies; } }

        internal MemoryCacheEntryChangeMonitor(ReadOnlyCollection<string> keys, string regionName, MemoryCache cache)
        {
            Debug.Assert(keys != null && keys.Count > 0, "keys != null && keys.Count > 0");
            _keys = keys;
            _regionName = regionName;
            InitDisposableMembers(cache);
        }

        // invoked by a cache entry dependency when it is released from the cache
        internal void OnCacheEntryReleased()
        {
            OnChanged(null);
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<Export generator="Cache" version="25">
<Class name="MR.Sample.AgeAverage.Person">
<StorageStrategy/>
<Super>%Persistent,%Populate</Super>
<TimeCreated>63702,1551.341127</TimeCreated>

<Property name="Name">
<Type>%String</Type>
</Property>

<Property name="Age">
<Type>%Integer</Type>
<Parameter name="MAXVAL" value="100"/>
<Parameter name="MINVAL" value="1"/>
</Property>

<Property name="Contacts">
<Type>%Integer</Type>
<Parameter name="MAXVAL" value="40"/>
<Parameter name="MINVAL" value="0"/>
</Property>

<Storage name="Default">
<Type>%Library.CacheStorage</Type>
<DataLocation>^MR.Sample.AgeAverage.PersonD</DataLocation>
<DefaultData>PersonDefaultData</DefaultData>
<IdLocation>^MR.Sample.AgeAverage.PersonD</IdLocation>
<IndexLocation>^MR.Sample.AgeAverage.PersonI</IndexLocation>
<StreamLocation>^MR.Sample.AgeAverage.PersonS</StreamLocation>
<ExtentSize>10000</ExtentSize>
<Data name="PersonDefaultData">
<Structure>listnode</Structure>
<Subscript/>
<Value name="1">
<Value>%%CLASSNAME</Value>
</Value>
<Value name="2">
<Value>Name</Value>
</Value>
<Value name="3">
<Value>Age</Value>
</Value>
<Value name="4">
<Value>Contacts</Value>
</Value>
</Data>
<Property name="%%CLASSNAME">
<Selectivity>0.0233%</Selectivity>
<OutlierSelectivity>.997667:</OutlierSelectivity>
<AverageFieldSize>1</AverageFieldSize>
</Property>
<Property name="%%ID">
<Selectivity>1</Selectivity>
<AverageFieldSize>3.84</AverageFieldSize>
</Property>
<Property name="Age">
<Selectivity>0.9414%</Selectivity>
<AverageFieldSize>1.92</AverageFieldSize>
</Property>
<Property name="Contacts">
<Selectivity>2.4987%</Selectivity>
<AverageFieldSize>1.78</AverageFieldSize>
</Property>
<Property name="Name">
<Selectivity>0.0100%</Selectivity>
<AverageFieldSize>15.95</AverageFieldSize>
</Property>
<SQLMap name="IDKEY">
<BlockCount>-180</BlockCount>
</SQLMap>
</Storage>
</Class>
</Export>


text:
module['exports'] = function transformStream (req, res, next) {
  // If the hook is not currently streaming,
  // the req has already been fully buffered,
  // and can no longer be streamed!
  if (!req.streaming) {
    return hook.res.end('No streaming request detected. \n\nTo test streaming data to this Hook try running this Curl command: \n\n     echo "foo" | curl --header "content-type: application/octet-stream"  --data-binary @- https://hook.io/examples/javascript-stream-transform');
  }
  req.on('end', function(){
    console.log('called end event')
    res.end();
  });
  req.on('data', function(chunk){
    res.write('hello world');
  });
};


text:
package com.facebook.imagepipeline.animated.base;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;

import com.facebook.common.references.CloseableReference;
import com.facebook.common.references.ResourceReleaser;
import com.facebook.common.testing.FakeClock;
import org.robolectric.RobolectricTestRunner;
import com.facebook.imagepipeline.animated.testing.MyShadowBitmap;
import com.facebook.imagepipeline.animated.testing.MyShadowCanvas;
import com.facebook.imagepipeline.animated.testing.TestAnimatedDrawableBackend;
import com.facebook.imagepipeline.animated.impl.AnimatedDrawableDiagnosticsNoop;
import com.facebook.imagepipeline.animated.testing.TestScheduledExecutorService;

import com.nineoldandroids.animation.ValueAnimator;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.annotation.Config;

import static com.facebook.imagepipeline.animated.testing.TestAnimatedDrawableBackend.pixelValue;
import static org.junit.Assert.*;

/**
 * Tests for {@link AnimatedDrawable}.
 */
@RunWith(RobolectricTestRunner.class)
@Config(shadows = {MyShadowCanvas.class, MyShadowBitmap.class})
public class AnimatedDrawableTest {

  private static final int WIDTH = 200;
  private static final int HEIGHT = 100;
  private static final int[] FRAME_DURATIONS = new int[]{ 60, 30, 15, 30, 60 };
  private static final int[] FRAME_DURATIONS_LONG = new int[]{ 10000, 10000 };

  private FakeClock mFakeClock;
  private TestScheduledExecutorService mTestScheduledExecutorService;
  private TestAnimatedDrawableBackend mBackend;
  private TestAnimatedDrawableCachingBackend mCachingBackend;
  private MyCallback mCallback;
  private AnimatedDrawable mDrawable;

  @Before
  public void setup() {
    mFakeClock = new FakeClock();
    mTestScheduledExecutorService = new TestScheduledExecutorService(mFakeClock);
    mBackend = new TestAnimatedDrawableBackend(WIDTH, HEIGHT, FRAME_DURATIONS);
    mCachingBackend = new TestAnimatedDrawableCachingBackend(mBackend);
    mCallback = new MyCallback(mFakeClock);
    mDrawable = new AnimatedDrawable(
        mTestScheduledExecutorService,
        mCachingBackend,
        AnimatedDrawableDiagnosticsNoop.getInstance(),
        mFakeClock);
    mDrawable.setCallback(mCallback);
  }

  @Test
  public void testIntrinsicDimensions() {
    assertEquals(WIDTH, mDrawable.getIntrinsicWidth());
    assertEquals(HEIGHT, mDrawable.getIntrinsicHeight());
  }

  @Test
  public void testValueAnimator() {
    ValueAnimator valueAnimator = mDrawable.createValueAnimator();
    assertEquals(mBackend.getDurationMs(), valueAnimator.getDuration());
    assertEquals(ValueAnimator.INFINITE, valueAnimator.getRepeatCount());
  }

  @Test
  public void testScheduling() {
    Bitmap bitmap = Bitmap.createBitmap(WIDTH, HEIGHT, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    prepareDrawable();

    // Spot check a pixel. Should be frame 0.
    mDrawable.draw(canvas);
    assertEquals(pixelValue(0, 10, 20), bitmap.getPixel(10, 20));

    // Advance just before next frame.
    mFakeClock.incrementBy(FRAME_DURATIONS[0] - 1);
    mDrawable.draw(canvas);
    assertEquals(pixelValue(0, 10, 20), bitmap.getPixel(10, 20));

    // Advance just to second frame.
    mFakeClock.incrementBy(1);
    mDrawable.draw(canvas);
    assertEquals(pixelValue(1, 10, 20), bitmap.getPixel(10, 20));

    // Advance to the last millisecond of the last frame.
    mFakeClock.incrementBy(FRAME_DURATIONS[1]);
    mFakeClock.incrementBy(FRAME_DURATIONS[2]);
    mFakeClock.incrementBy(FRAME_DURATIONS[3]);
    mFakeClock.incrementBy(FRAME_DURATIONS[4] - 1);
    mDrawable.draw(canvas);
    assertEquals(pixelValue(4, 10, 20), bitmap.getPixel(10, 20));

    // Make sure wrapping works.
    mFakeClock.incrementBy(1);
    mDrawable.draw(canvas);
    assertEquals(pixelValue(0, 10, 20), bitmap.getPixel(10, 20));
    assertEquals(1, mBackend.getDropCachesCallCount());
  }

  @Test
  public void testDropCachesAfterDrawTimeout() {
    Bitmap bitmap = Bitmap.createBitmap(WIDTH, HEIGHT, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    prepareDrawable();

    // Draw and advance to next frame.
    mDrawable.draw(canvas);

    // Make sure caches are dropped after couple seconds without a draw call.
    assertFalse(mDrawable.isWaitingForDraw());
    mFakeClock.incrementBy(60);
    assertTrue(mDrawable.isWaitingForDraw());
    mFakeClock.incrementBy(1940);
    assertEquals(2, mBackend.getDropCachesCallCount());
  }

  @Test
  public void testDropCachesAfterNextFrameTimeout() {
    Bitmap bitmap = Bitmap.createBitmap(WIDTH, HEIGHT, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    prepareDrawable();

    // Draw and advance to next frame.
    mDrawable.draw(canvas);

    // Make sure caches are dropped after couple seconds.
    assertFalse(mDrawable.isWaitingForDraw());
    assertTrue(mDrawable.isWaitingForNextFrame());
    mCallback.setDropCallbacks(true);
    mFakeClock.incrementBy(2000);
    assertEquals(2, mBackend.getDropCachesCallCount());
  }

  @Test
  public void testDoNotDropCacheIfFramesAreLongDurationSpecialCase() {
    mBackend = new TestAnimatedDrawableBackend(WIDTH, HEIGHT, FRAME_DURATIONS_LONG);
    mCachingBackend = new TestAnimatedDrawableCachingBackend(mBackend);
    mCallback = new MyCallback(mFakeClock);
    mDrawable = new AnimatedDrawable(
        mTestScheduledExecutorService,
        mCachingBackend,
        AnimatedDrawableDiagnosticsNoop.getInstance(),
        mFakeClock);
    mDrawable.setCallback(mCallback);

    Bitmap bitmap = Bitmap.createBitmap(WIDTH, HEIGHT, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    prepareDrawable();

    // Draw and advance to next frame.
    mDrawable.draw(canvas);

    // After 10 seconds, it should move to the next frame. It shouldn't drop the caches though
    // until it's 2 seconds after the invalidate.
    assertFalse(mDrawable.isWaitingForDraw());
    assertTrue(mDrawable.isWaitingForNextFrame());
    assertEquals(0, mDrawable.getScheduledFrameNumber());
    mFakeClock.incrementBy(10000);
    assertTrue(mDrawable.isWaitingForDraw());
    assertFalse(mDrawable.isWaitingForNextFrame());
    assertEquals(1, mDrawable.getScheduledFrameNumber());
    assertEquals(1, mBackend.getDropCachesCallCount());
    mFakeClock.incrementBy(1000);
    assertEquals(1, mBackend.getDropCachesCallCount());
    mFakeClock.incrementBy(2000);
    assertEquals(2, mBackend.getDropCachesCallCount());
  }

  private void prepareDrawable() {
    mDrawable.start();
    mFakeClock.incrementBy(0); // Just to trigger the callbacks to run.
    mDrawable.setBounds(0, 0, 200, 100);
    assertEquals(1, mBackend.getDropCachesCallCount());
  }

  private static class ScheduledRunnable {

    final Runnable runnable;
    final long when;

    private ScheduledRunnable(Runnable runnable, long when) {
      this.runnable = runnable;
      this.when = when;
    }
  }

  private static class TestAnimatedDrawableCachingBackend extends DelegatingAnimatedDrawableBackend
      implements AnimatedDrawableCachingBackend {

    public TestAnimatedDrawableCachingBackend(AnimatedDrawableBackend animatedDrawableBackend) {
      super(animatedDrawableBackend);
    }

    @Override
    public CloseableReference<Bitmap> getBitmapForFrame(int frameNumber) {
      Bitmap bitmap = Bitmap.createBitmap(WIDTH, HEIGHT, Bitmap.Config.ARGB_8888);
      getDelegate().renderFrame(frameNumber, new Canvas(bitmap));
      return CloseableReference.of(
          bitmap,
          new ResourceReleaser<Bitmap>() {
            @Override
            public void release(Bitmap value) {

            }
          });
    }

    @Override
    public CloseableReference<Bitmap> getPreviewBitmap() {
      return null;
    }

    @Override
    public CloseableReference<Bitmap> getPreDecodedFrame(int frameNumber) {
      return null;
    }

    @Override
    public void appendDebugOptionString(StringBuilder sb) {
    }

    @Override
    public AnimatedDrawableCachingBackend forNewBounds(Rect bounds) {
      return this;
    }
  }

  private static class MyCallback implements Drawable.Callback {

    private final FakeClock mFakeClock;
    private final List<ScheduledRunnable> mScheduledRunnables = new ArrayList<>();
    private boolean mDropCallbacks;

    MyCallback(FakeClock fakeClock) {
      mFakeClock = fakeClock;
      mFakeClock.addListener(
          new FakeClock.OnTickListener() {
            @Override
            public void onTick() {
              runReadyTasks();
            }
          });
    }

    @Override
    public void invalidateDrawable(Drawable who) {

    }

    @Override
    public void scheduleDrawable(Drawable who, Runnable what, long when) {
      mScheduledRunnables.add(new ScheduledRunnable(what, when));
    }

    @Override
    public void unscheduleDrawable(Drawable who, Runnable what) {
      Iterator<ScheduledRunnable> iterator = mScheduledRunnables.iterator();
      while (iterator.hasNext()) {
        ScheduledRunnable next = iterator.next();
        if (next.runnable == what) {
          iterator.remove();
        }
      }
    }

    void runReadyTasks() {
      List<Runnable> toRun = new ArrayList<>();
      long now = mFakeClock.now();
      Iterator<ScheduledRunnable> iterator = mScheduledRunnables.iterator();
      while (iterator.hasNext()) {
        ScheduledRunnable next = iterator.next();
        if (next.when <= now) {
          iterator.remove();
          toRun.add(next.runnable);
        }
      }
      if (!mDropCallbacks) {
        for (Runnable runnable : toRun) {
          runnable.run();
        }
      }
    }

    void setDropCallbacks(boolean dropCallbacks) {
      mDropCallbacks = dropCallbacks;
    }
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/decelerate_interpolator"
    android:shareInterpolator="false">
    <alpha
        android:duration="500"
        android:fromAlpha="0.0"
        android:toAlpha="1.0" />
    <translate
        android:duration="200"
        android:fromXDelta="0%"
        android:toXDelta="0%"
        android:fromYDelta="200%"
        android:toYDelta="0%" />
    <!--
    <translate
        android:duration="500"
        android:fromXDelta="-200%"
        android:toXDelta="0%"
        android:fromYDelta="0%"
        android:toYDelta="0%" /> -->
</set>


text:
<ion-view title="Home" ng-init="setInits()">
    <ion-list>
        <ion-item ng-click="setItem(item)" ng-repeat="item in items">

            <ion-delete-button class="ion-minus-circled"></ion-delete-button>
            Hello, {{item}}!

        </ion-item>
    </ion-list>
</ion-view>

<script id="item.html" type="text/ng-template">
    < ion - modal - view >
        < ion - header - bar >
        < h1 class = "title" > Item < /h1>
      <button class="button button-clear button-positive" ng-click="closeItem()">Cancel</button >

    < /ion-header-bar>
    <ion-content>
      Hello!
    </ion - content >
        < /ion-modal-view>
</script>


text:
namespace SIL.XForge.WebApi.Server.Models
{
    public class AccessTokenInfo
    {
        public string IdToken { get; set; }
        public string AccessToken { get; set; }
        public string RefreshToken { get; set; }
    }
}


text:
package me.snowdrop.data.hibernatesearch.core.query;

/**
 * @author Ales Justin
 */
public class OrCriteria<Q> extends Criteria<Q> {
    private Criteria<Q> left;
    private Criteria<Q> right;

    public OrCriteria(Criteria<Q> left, Criteria<Q> right) {
        this.left = left;
        this.right = right;
    }

    @Override
    public Q apply(OpsCriteriaConverter<Q> converter) {
        return converter.or(this);
    }

    public Criteria<Q> getLeft() {
        return left;
    }

    public Criteria<Q> getRight() {
        return right;
    }
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Chaetophoma alliicola Tassi, 1897

### Remarks
null


text:
package api

import (
	"crypto/rand"
	"encoding/hex"
	"fmt"
	"net/http"

	"github.com/rancher/norman/httperror"
	"github.com/rancher/norman/parse"
	"github.com/rancher/norman/types"
)

const (
	csrfCookie = "CSRF"
	csrfHeader = "X-API-CSRF"
)

func ValidateAction(request *types.APIContext) (*types.Action, error) {
	if request.Action == "" || request.Method != http.MethodPost {
		return nil, nil
	}

	actions := request.Schema.CollectionActions
	if request.ID != "" {
		actions = request.Schema.ResourceActions
	}

	action, ok := actions[request.Action]
	if !ok {
		return nil, httperror.NewAPIError(httperror.INVALID_ACTION, fmt.Sprintf("Invalid action: %s", request.Action))
	}

	if request.ID != "" {
		resource := request.ReferenceValidator.Lookup(request.Type, request.ID)
		if resource == nil {
			return nil, httperror.NewAPIError(httperror.NOT_FOUND, fmt.Sprintf("Failed to find type: %s id: %s", request.Type, request.ID))
		}

		if _, ok := resource.Actions[request.Action]; !ok {
			return nil, httperror.NewAPIError(httperror.INVALID_ACTION, fmt.Sprintf("Invalid action: %s", request.Action))
		}
	}

	return &action, nil
}

func CheckCSRF(rw http.ResponseWriter, req *http.Request) error {
	if !parse.IsBrowser(req, false) {
		return nil
	}

	cookie, err := req.Cookie(csrfCookie)
	if err == http.ErrNoCookie {
		bytes := make([]byte, 5)
		_, err := rand.Read(bytes)
		if err != nil {
			return httperror.WrapAPIError(err, httperror.SERVER_ERROR, "Failed in CSRF processing")
		}

		cookie = &http.Cookie{
			Name:  csrfCookie,
			Value: hex.EncodeToString(bytes),
		}
	} else if err != nil {
		return httperror.NewAPIError(httperror.INVALID_CSRF_TOKEN, "Failed to parse cookies")
	} else if req.Method != http.MethodGet {
		/*
		 * Very important to use request.getMethod() and not httpRequest.getMethod(). The client can override the HTTP method with _method
		 */
		if cookie.Value == req.Header.Get(csrfHeader) {
			// Good
		} else if cookie.Value == req.URL.Query().Get(csrfCookie) {
			// Good
		} else {
			return httperror.NewAPIError(httperror.INVALID_CSRF_TOKEN, "Invalid CSRF token")
		}
	}

	cookie.Path = "/"
	http.SetCookie(rw, cookie)
	return nil
}


text:
package org.apache.hyracks.control.nc;

import java.nio.ByteBuffer;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Logger;

import org.apache.hyracks.api.application.INCServiceContext;
import org.apache.hyracks.api.comm.IPartitionCollector;
import org.apache.hyracks.api.comm.PartitionChannel;
import org.apache.hyracks.api.context.IHyracksJobletContext;
import org.apache.hyracks.api.dataflow.TaskAttemptId;
import org.apache.hyracks.api.dataflow.state.IStateObject;
import org.apache.hyracks.api.deployment.DeploymentId;
import org.apache.hyracks.api.exceptions.HyracksDataException;
import org.apache.hyracks.api.exceptions.HyracksException;
import org.apache.hyracks.api.io.FileReference;
import org.apache.hyracks.api.io.IIOManager;
import org.apache.hyracks.api.io.IWorkspaceFileFactory;
import org.apache.hyracks.api.job.ActivityClusterGraph;
import org.apache.hyracks.api.job.IGlobalJobDataFactory;
import org.apache.hyracks.api.job.IJobletEventListener;
import org.apache.hyracks.api.job.IJobletEventListenerFactory;
import org.apache.hyracks.api.job.IOperatorEnvironment;
import org.apache.hyracks.api.job.JobId;
import org.apache.hyracks.api.job.JobStatus;
import org.apache.hyracks.api.job.profiling.counters.ICounter;
import org.apache.hyracks.api.job.profiling.counters.ICounterContext;
import org.apache.hyracks.api.partitions.PartitionId;
import org.apache.hyracks.api.resources.IDeallocatable;
import org.apache.hyracks.control.common.deployment.DeploymentUtils;
import org.apache.hyracks.control.common.job.PartitionRequest;
import org.apache.hyracks.control.common.job.PartitionState;
import org.apache.hyracks.control.common.job.profiling.StatsCollector;
import org.apache.hyracks.control.common.job.profiling.counters.Counter;
import org.apache.hyracks.control.common.job.profiling.om.JobletProfile;
import org.apache.hyracks.control.common.job.profiling.om.TaskProfile;
import org.apache.hyracks.control.nc.io.WorkspaceFileFactory;
import org.apache.hyracks.control.nc.resources.DefaultDeallocatableRegistry;
import org.apache.hyracks.control.nc.resources.memory.FrameManager;

public class Joblet implements IHyracksJobletContext, ICounterContext {
    private static final Logger LOGGER = Logger.getLogger(Joblet.class.getName());

    private final NodeControllerService nodeController;

    private final INCServiceContext serviceCtx;

    private final DeploymentId deploymentId;

    private final JobId jobId;

    private final ActivityClusterGraph acg;

    private final Map<PartitionId, IPartitionCollector> partitionRequestMap;

    private final IOperatorEnvironment env;

    private final Map<Object, IStateObject> stateObjectMap;

    private final Map<TaskAttemptId, Task> taskMap;

    private final Map<String, Counter> counterMap;

    private final DefaultDeallocatableRegistry deallocatableRegistry;

    private final IWorkspaceFileFactory fileFactory;

    private final Object globalJobData;

    private final IJobletEventListener jobletEventListener;

    private final FrameManager frameManager;

    private final AtomicLong memoryAllocation;

    private JobStatus cleanupStatus;

    private boolean cleanupPending;

    private final IJobletEventListenerFactory jobletEventListenerFactory;

    public Joblet(NodeControllerService nodeController, DeploymentId deploymentId, JobId jobId,
            INCServiceContext serviceCtx, ActivityClusterGraph acg,
            IJobletEventListenerFactory jobletEventListenerFactory) {
        this.nodeController = nodeController;
        this.serviceCtx = serviceCtx;
        this.deploymentId = deploymentId;
        this.jobId = jobId;
        this.frameManager = new FrameManager(acg.getFrameSize());
        memoryAllocation = new AtomicLong();
        this.acg = acg;
        partitionRequestMap = new HashMap<>();
        env = new OperatorEnvironmentImpl(nodeController.getId());
        stateObjectMap = new HashMap<>();
        taskMap = new HashMap<>();
        counterMap = new HashMap<>();
        deallocatableRegistry = new DefaultDeallocatableRegistry();
        fileFactory = new WorkspaceFileFactory(this, serviceCtx.getIoManager());
        cleanupPending = false;
        this.jobletEventListenerFactory = jobletEventListenerFactory;
        if (jobletEventListenerFactory != null) {
            IJobletEventListener listener = jobletEventListenerFactory.createListener(this);
            this.jobletEventListener = listener;
            listener.jobletStart();
        } else {
            jobletEventListener = null;
        }
        IGlobalJobDataFactory gjdf = acg.getGlobalJobDataFactory();
        globalJobData = gjdf != null ? gjdf.createGlobalJobData(this) : null;
    }

    @Override
    public JobId getJobId() {
        return jobId;
    }

    @Override
    public IJobletEventListenerFactory getJobletEventListenerFactory() {
        return jobletEventListenerFactory;
    }

    public ActivityClusterGraph getActivityClusterGraph() {
        return acg;
    }

    public IOperatorEnvironment getEnvironment() {
        return env;
    }

    public void addTask(Task task) {
        taskMap.put(task.getTaskAttemptId(), task);
    }

    public void removeTask(Task task) {
        taskMap.remove(task.getTaskAttemptId());
        if (cleanupPending && taskMap.isEmpty()) {
            performCleanup();
        }
    }

    public Map<TaskAttemptId, Task> getTaskMap() {
        return taskMap;
    }

    private final class OperatorEnvironmentImpl implements IOperatorEnvironment {
        private final String nodeId;

        public OperatorEnvironmentImpl(String nodeId) {
            this.nodeId = nodeId;
        }

        @Override
        public String toString() {
            return super.toString() + "@" + nodeId;
        }

        @Override
        public synchronized void setStateObject(IStateObject taskState) {
            stateObjectMap.put(taskState.getId(), taskState);
        }

        @Override
        public synchronized IStateObject getStateObject(Object id) {
            return stateObjectMap.get(id);
        }
    }

    public NodeControllerService getNodeController() {
        return nodeController;
    }

    public void dumpProfile(JobletProfile jProfile) {
        Map<String, Long> counters = jProfile.getCounters();
        counterMap.forEach((key, value) -> counters.put(key, value.get()));
        for (Task task : taskMap.values()) {
            TaskProfile taskProfile = new TaskProfile(task.getTaskAttemptId(),
                    new Hashtable<>(task.getPartitionSendProfile()), new StatsCollector());
            task.dumpProfile(taskProfile);
            jProfile.getTaskProfiles().put(task.getTaskAttemptId(), taskProfile);
        }
    }

    @Override
    public INCServiceContext getServiceContext() {
        return serviceCtx;
    }

    @Override
    public ICounterContext getCounterContext() {
        return this;
    }

    @Override
    public void registerDeallocatable(IDeallocatable deallocatable) {
        deallocatableRegistry.registerDeallocatable(deallocatable);
    }

    public void close() {
        long stillAllocated = memoryAllocation.get();
        if (stillAllocated > 0) {
            LOGGER.warning("Freeing leaked " + stillAllocated + " bytes");
            serviceCtx.getMemoryManager().deallocate(stillAllocated);
        }
        nodeController.getExecutor().execute(new Runnable() {
            @Override
            public void run() {
                deallocatableRegistry.close();
            }
        });
    }

    ByteBuffer allocateFrame() throws HyracksDataException {
        return frameManager.allocateFrame();
    }

    ByteBuffer allocateFrame(int bytes) throws HyracksDataException {
        if (serviceCtx.getMemoryManager().allocate(bytes)) {
            memoryAllocation.addAndGet(bytes);
            return frameManager.allocateFrame(bytes);
        }
        throw new HyracksDataException("Unable to allocate frame: Not enough memory");
    }

    ByteBuffer reallocateFrame(ByteBuffer usedBuffer, int newFrameSizeInBytes, boolean copyOldData)
            throws HyracksDataException {
        return frameManager.reallocateFrame(usedBuffer, newFrameSizeInBytes, copyOldData);
    }

    void deallocateFrames(int bytes) {
        memoryAllocation.addAndGet(bytes);
        serviceCtx.getMemoryManager().deallocate(bytes);
        frameManager.deallocateFrames(bytes);
    }

    public final int getFrameSize() {
        return frameManager.getInitialFrameSize();
    }

    public IIOManager getIOManager() {
        return serviceCtx.getIoManager();
    }

    @Override
    public FileReference createManagedWorkspaceFile(String prefix) throws HyracksDataException {
        return fileFactory.createManagedWorkspaceFile(prefix);
    }

    @Override
    public FileReference createUnmanagedWorkspaceFile(String prefix) throws HyracksDataException {
        return fileFactory.createUnmanagedWorkspaceFile(prefix);
    }

    @Override
    public synchronized ICounter getCounter(String name, boolean create) {
        Counter counter = counterMap.get(name);
        if (counter == null && create) {
            counter = new Counter(name);
            counterMap.put(name, counter);
        }
        return counter;
    }

    @Override
    public Object getGlobalJobData() {
        return globalJobData;
    }

    public IJobletEventListener getJobletEventListener() {
        return jobletEventListener;
    }

    public synchronized void advertisePartitionRequest(TaskAttemptId taId, Collection<PartitionId> pids,
            IPartitionCollector collector, PartitionState minState) throws Exception {
        for (PartitionId pid : pids) {
            partitionRequestMap.put(pid, collector);
            PartitionRequest req = new PartitionRequest(pid, nodeController.getId(), taId, minState);
            nodeController.getClusterController().registerPartitionRequest(req);
        }
    }

    public synchronized void reportPartitionAvailability(PartitionChannel channel) throws HyracksException {
        IPartitionCollector collector = partitionRequestMap.get(channel.getPartitionId());
        if (collector != null) {
            collector.addPartitions(Collections.singleton(channel));
        }
    }

    public void cleanup(JobStatus status) {
        cleanupStatus = status;
        cleanupPending = true;
        if (taskMap.isEmpty()) {
            performCleanup();
        }
    }

    private void performCleanup() {
        nodeController.getJobletMap().remove(jobId);
        IJobletEventListener listener = getJobletEventListener();
        if (listener != null) {
            listener.jobletFinish(cleanupStatus);
        }
        close();
        cleanupPending = false;
        try {
            nodeController.getClusterController().notifyJobletCleanup(jobId, nodeController.getId());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Class<?> loadClass(String className) throws HyracksException {
        return DeploymentUtils.loadClass(className, deploymentId, serviceCtx);
    }

    @Override
    public ClassLoader getClassLoader() throws HyracksException {
        return DeploymentUtils.getClassLoader(deploymentId, serviceCtx);
    }
}


text:
package com.intellij.ide;

import com.intellij.openapi.extensions.PluginAware;
import com.intellij.openapi.extensions.PluginDescriptor;
import com.intellij.openapi.extensions.RequiredElement;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.util.NullableLazyValue;
import com.intellij.util.xmlb.annotations.Attribute;
import com.intellij.util.xmlb.annotations.Transient;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;

final class TypeIconEP implements PluginAware {
  @Transient
  private PluginDescriptor pluginDescriptor;

  @Attribute("className")
  @RequiredElement
  public String className;

  @Attribute("icon")
  @RequiredElement
  public String icon;

  @Transient final NullableLazyValue<Icon> lazyIcon = NullableLazyValue.createValue(() -> {
    return IconLoader.findIcon(icon, pluginDescriptor == null ? getClass().getClassLoader() : pluginDescriptor.getPluginClassLoader());
  });

  @Override
  public final void setPluginDescriptor(@NotNull PluginDescriptor pluginDescriptor) {
    this.pluginDescriptor = pluginDescriptor;
  }
}


text:
def shortest_string(list_of_words)
  if list_of_words == []
    return nil
  elsif list_of_words == ['']
    return ''
  elsif list_of_words.length == 1
    return list_of_words[0]
  else
    array = list_of_words.sort_by { |x| x.length }
    return array[0]
  end
end

shortest_string(['cat'])


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

namespace Kalendar.Zero.Utility.Common
{
    public class BrowerResponse
    {
        public HttpStatusCode StatusCode { get; set; }

        public string Content { get; set; }

        public Dictionary<string,string> Headers { get; set; }
    }
}


text:
@interface IASKSpecifierValuesViewController()

@property (nonatomic, strong, readonly) IASKMultipleValueSelection *selection;
@property (nonatomic) BOOL didFirstLayout;
@end

@implementation IASKSpecifierValuesViewController

@synthesize currentSpecifier=_currentSpecifier;
@synthesize settingsReader = _settingsReader;
@synthesize settingsStore = _settingsStore;

- (void)setSettingsStore:(id <IASKSettingsStore>)settingsStore {
	_selection = [IASKMultipleValueSelection new];
    _settingsStore = settingsStore;
    _selection.settingsStore = settingsStore;
	_selection.specifier = _currentSpecifier;
}

- (void)viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];

    if (_currentSpecifier) {
		self.title = _currentSpecifier.title;
		IASK_IF_IOS11_OR_GREATER(self.navigationItem.largeTitleDisplayMode = self.title.length ? UINavigationItemLargeTitleDisplayModeAutomatic : UINavigationItemLargeTitleDisplayModeNever;);
    }

    if (self.tableView) {
		_selection.tableView = self.tableView;
		[self.tableView reloadData];

		// Make sure the currently checked item is visible
		[self.tableView scrollToRowAtIndexPath:_selection.checkedItem
							  atScrollPosition:UITableViewScrollPositionMiddle animated:NO];
	}
	self.didFirstLayout = NO;
}

- (void)viewDidDisappear:(BOOL)animated {
	[super viewDidDisappear:animated];
    _selection.tableView = nil;
}

- (void)viewWillLayoutSubviews {
	[super viewWillLayoutSubviews];

	if (!self.didFirstLayout) {
		self.didFirstLayout = YES;
		[self.tableView scrollToRowAtIndexPath:_selection.checkedItem
							  atScrollPosition:UITableViewScrollPositionMiddle animated:NO];
		[self.tableView flashScrollIndicators];
	}
}

#pragma mark -
#pragma mark UITableView delegates

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [_currentSpecifier multipleValuesCount];
}

- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
    return [_currentSpecifier footerText];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell   = [tableView dequeueReusableCellWithIdentifier:kCellValue];
    NSArray *titles         = [_currentSpecifier multipleTitles];

    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCellValue];
    }

    [_selection updateSelectionInCell:cell indexPath:indexPath];

    @try {
		[[cell textLabel] setText:[self.settingsReader titleForId:[titles objectAtIndex:indexPath.row]]];
	}
	@catch (NSException * e) {}
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [_selection selectRowAtIndexPath:indexPath];
}

- (CGSize)preferredContentSize {
    return [[self view] sizeThatFits:CGSizeMake(320, 2000)];
}

@end


text:
      <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navigation" aria-controls="navigation-index" aria-expanded="false" aria-label="Toggle navigation">

      </button>

        Pizza PaaS

          Catalogue

          Cart

          About

          Contact

          Have an issue?

Twitter

Facebook

Github


text:
/**
 * Print navto items for a symbol in a file
 */

import { connect, end, failure, navTo, success } from './lib/client';
import { parseArgs } from './lib/opts';

const { args, flags, port } = parseArgs({
	args: [ 'file', 'searchValue' ],
	flags: { 'search-project': 's' }
});

const searchProject = flags['search-project'];

const navToArgs: protocol.NavtoRequestArgs = {
	file: args[0],
	searchValue: args[1],
	currentFileOnly: !searchProject
};

connect(port).then(() => navTo(navToArgs))
	.then(success)
	.catch(failure)
	.then(end);


text:
"""Pagination support.

"""

from flask import abort, request, url_for

class Page(object):
    def __init__(self, docs, pagenum, hpp=20):
        if pagenum < 1:
            abort(404)
        self.docs = docs[hpp * (pagenum - 1): hpp * pagenum].check_at_least(-1)
        self.pagenum = pagenum
        self.pages = (self.docs.matches_lower_bound + hpp - 1) / hpp
        if pagenum > 1 and len(self.docs) == 0:
            abort(404)

    @property
    def pagenums(self):
        return range(1, self.pages + 1)

def url_for_page(page):
    args = request.view_args.copy()
    args['page'] = page
    return url_for(request.endpoint, **args)

def register(app):
    app.jinja_env.globals['url_for_page'] = url_for_page


text:
<?php
declare(strict_types=1);

namespace BugReportTest\Dependencies;

use BugReport\Dependencies\Installed;
use PHPUnit\Framework\TestCase;

class InstalledTest extends TestCase
{
    /**
     * @test
     */
    public function it_gets_all_projects_of_git_type_from_composer_packages()
    {
        $lockfile = __DIR__ . '/../fixtures/composer.lock';
        $lockfile = json_decode(file_get_contents($lockfile), true);
        $packages = array_merge($lockfile['packages'], $lockfile['packages-dev']);

        $installedDependencies = Installed::fromComposerPackages($packages);

        $expected = [
            "clue/php-stream-filter",
            "guzzle/guzzle",
            "guzzle/promises",
            "guzzle/psr7",
            "KnpLabs/php-github-api",
            "php-http/cache-plugin",
            "php-http/client-common",
            "php-http/discovery",
            "php-http/guzzle6-adapter",
            "php-http/httplug",
            "php-http/message",
            "php-http/message-factory",
            "php-http/promise",
            "php-fig/cache",
            "php-fig/http-message",
            "php-fig/log",
            "symfony/console",
            "symfony/debug",
            "symfony/options-resolver",
            "symfony/polyfill-mbstring",
            "webmozart/assert",
            "doctrine/instantiator",
            "hamcrest/hamcrest-php",
            "mockery/mockery",
            "myclabs/DeepCopy",
            "phar-io/manifest",
            "phar-io/version",
            "phpDocumentor/ReflectionCommon",
            "phpDocumentor/ReflectionDocBlock",
            "phpDocumentor/TypeResolver",
            "phpspec/prophecy",
            "sebastianbergmann/php-code-coverage",
            "sebastianbergmann/php-file-iterator",
            "sebastianbergmann/php-text-template",
            "sebastianbergmann/php-timer",
            "sebastianbergmann/php-token-stream",
            "sebastianbergmann/phpunit",
            "sebastianbergmann/phpunit-mock-objects",
            "sebastianbergmann/code-unit-reverse-lookup",
            "sebastianbergmann/comparator",
            "sebastianbergmann/diff",
            "sebastianbergmann/environment",
            "sebastianbergmann/exporter",
            "sebastianbergmann/global-state",
            "sebastianbergmann/object-enumerator",
            "sebastianbergmann/object-reflector",
            "sebastianbergmann/recursion-context",
            "sebastianbergmann/resource-operations",
            "sebastianbergmann/version",
            "theseer/tokenizer",
        ];

        $this->assertSame($expected, $installedDependencies->all());
        $this->assertSame(50, $installedDependencies->total());
    }

    /**
     * @test
     * @expectedException InvalidArgumentException
     */
    public function it_cannot_get_installed_dependencies_from_no_packages()
    {
        Installed::fromComposerPackages([]);
    }
}


text:
module Gitlab
  module Git
    class Commit
      include Gitlab::EncodingHelper
      extend Gitlab::Git::WrapsGitalyErrors

      attr_accessor :raw_commit, :head

      MAX_COMMIT_MESSAGE_DISPLAY_SIZE = 10.megabytes
      MIN_SHA_LENGTH = 7
      SERIALIZE_KEYS = [
        :id, :message, :parent_ids,
        :authored_date, :author_name, :author_email,
        :committed_date, :committer_name, :committer_email
      ].freeze

      attr_accessor *SERIALIZE_KEYS # rubocop:disable Lint/AmbiguousOperator

      def ==(other)
        return false unless other.is_a?(Gitlab::Git::Commit)

        id && id == other.id
      end

      class << self
        # Get commits collection
        #
        # Ex.
        #   Commit.where(
        #     repo: repo,
        #     ref: 'master',
        #     path: 'app/models',
        #     limit: 10,
        #     offset: 5,
        #   )
        #
        def where(options)
          repo = options.delete(:repo)
          raise 'Gitlab::Git::Repository is required' unless repo.respond_to?(:log)

          repo.log(options)
        end

        # Get single commit
        #
        # Ex.
        #   Commit.find(repo, '29eda46b')
        #
        #   Commit.find(repo, 'master')
        #
        # Gitaly migration: https://gitlab.com/gitlab-org/gitaly/issues/321
        def find(repo, commit_id = "HEAD")
          # Already a commit?
          return commit_id if commit_id.is_a?(Gitlab::Git::Commit)

          # Some weird thing?
          return nil unless commit_id.is_a?(String)

          # This saves us an RPC round trip.
          return nil if commit_id.include?(':')

          commit = wrapped_gitaly_errors do
            repo.gitaly_commit_client.find_commit(commit_id)
          end

          decorate(repo, commit) if commit
        rescue Gitlab::Git::CommandError, Gitlab::Git::Repository::NoRepository, ArgumentError
          nil
        end

        # Get last commit for HEAD
        #
        # Ex.
        #   Commit.last(repo)
        #
        def last(repo)
          find(repo)
        end

        # Get last commit for specified path and ref
        #
        # Ex.
        #   Commit.last_for_path(repo, '29eda46b', 'app/models')
        #
        #   Commit.last_for_path(repo, 'master', 'Gemfile')
        #
        def last_for_path(repo, ref, path = nil)
          where(
            repo: repo,
            ref: ref,
            path: path,
            limit: 1
          ).first
        end

        # Get commits between two revspecs
        # See also #repository.commits_between
        #
        # Ex.
        #   Commit.between(repo, '29eda46b', 'master')
        #
        def between(repo, base, head)
          wrapped_gitaly_errors do
            repo.gitaly_commit_client.between(base, head)
          end
        end

        # Returns commits collection
        #
        # Ex.
        #   Commit.find_all(
        #     repo,
        #     ref: 'master',
        #     max_count: 10,
        #     skip: 5,
        #     order: :date
        #   )
        #
        #   +options+ is a Hash of optional arguments to git
        #     :ref is the ref from which to begin (SHA1 or name)
        #     :max_count is the maximum number of commits to fetch
        #     :skip is the number of commits to skip
        #     :order is the commits order and allowed value is :none (default), :date,
        #        :topo, or any combination of them (in an array). Commit ordering types
        #        are documented here:
        #        http://www.rubydoc.info/github/libgit2/rugged/Rugged#SORT_NONE-constant)
        def find_all(repo, options = {})
          wrapped_gitaly_errors do
            Gitlab::GitalyClient::CommitService.new(repo).find_all_commits(options)
          end
        end

        def decorate(repository, commit, ref = nil)
          Gitlab::Git::Commit.new(repository, commit, ref)
        end

        def shas_with_signatures(repository, shas)
          Gitlab::GitalyClient::CommitService.new(repository).filter_shas_with_signatures(shas)
        end

        # Only to be used when the object ids will not necessarily have a
        # relation to each other. The last 10 commits for a branch for example,
        # should go through .where
        def batch_by_oid(repo, oids)
          wrapped_gitaly_errors do
            repo.gitaly_commit_client.list_commits_by_oid(oids)
          end
        end

        def extract_signature(repository, commit_id)
          repository.gitaly_commit_client.extract_signature(commit_id)
        end

        def extract_signature_lazily(repository, commit_id)
          BatchLoader.for(commit_id).batch(key: repository) do |commit_ids, loader, args|
            batch_signature_extraction(args[:key], commit_ids).each do |commit_id, signature_data|
              loader.call(commit_id, signature_data)
            end
          end
        end

        def batch_signature_extraction(repository, commit_ids)
          repository.gitaly_commit_client.get_commit_signatures(commit_ids)
        end

        def get_message(repository, commit_id)
          BatchLoader.for(commit_id).batch(key: repository) do |commit_ids, loader, args|
            get_messages(args[:key], commit_ids).each do |commit_id, message|
              loader.call(commit_id, message)
            end
          end
        end

        def get_messages(repository, commit_ids)
          repository.gitaly_commit_client.get_commit_messages(commit_ids)
        end
      end

      def initialize(repository, raw_commit, head = nil)
        raise "Nil as raw commit passed" unless raw_commit

        @repository = repository
        @head = head

        case raw_commit
        when Hash
          init_from_hash(raw_commit)
        when Gitaly::GitCommit
          init_from_gitaly(raw_commit)
        else
          raise "Invalid raw commit type: #{raw_commit.class}"
        end
      end

      def sha
        id
      end

      def short_id(length = 10)
        id.to_s[0..length]
      end

      def safe_message
        @safe_message ||= message
      end

      def created_at
        committed_date
      end

      # Was this commit committed by a different person than the original author?
      def different_committer?
        author_name != committer_name || author_email != committer_email
      end

      def parent_id
        parent_ids.first
      end

      # Returns a diff object for the changes from this commit's first parent.
      # If there is no parent, then the diff is between this commit and an
      # empty repo. See Repository#diff for keys allowed in the +options+
      # hash.
      def diff_from_parent(options = {})
        @repository.gitaly_commit_client.diff_from_parent(self, options)
      end

      def deltas
        @deltas ||= begin
          deltas = @repository.gitaly_commit_client.commit_deltas(self)
          deltas.map { |delta| Gitlab::Git::Diff.new(delta) }
        end
      end

      def has_zero_stats?
        stats.total.zero?
      rescue
        true
      end

      def no_commit_message
        "--no commit message"
      end

      def to_hash
        serialize_keys.map.with_object({}) do |key, hash|
          hash[key] = send(key) # rubocop:disable GitlabSecurity/PublicSend
        end
      end

      def date
        committed_date
      end

      def diffs(options = {})
        Gitlab::Git::DiffCollection.new(diff_from_parent(options), options)
      end

      def parents
        parent_ids.map { |oid| self.class.find(@repository, oid) }.compact
      end

      def stats
        Gitlab::Git::CommitStats.new(@repository, self)
      end

      # Get ref names collection
      #
      # Ex.
      #   commit.ref_names(repo)
      #
      def ref_names(repo)
        refs(repo).map do |ref|
          ref.sub(%r{^refs/(heads|remotes|tags)/}, "")
        end
      end

      def message
        encode! @message
      end

      def author_name
        encode! @author_name
      end

      def author_email
        encode! @author_email
      end

      def committer_name
        encode! @committer_name
      end

      def committer_email
        encode! @committer_email
      end

      def merge_commit?
        parent_ids.size > 1
      end

      def tree_entry(path)
        return unless path.present?

        # We're only interested in metadata, so limit actual data to 1 byte
        # since Gitaly doesn't support "send no data" option.
        entry = @repository.gitaly_commit_client.tree_entry(id, path, 1)
        return unless entry

        entry = entry.to_h
        entry.delete(:data)
        entry[:name] = File.basename(path)
        entry[:type] = entry[:type].downcase

        entry
      end

      def to_gitaly_commit
        return raw_commit if raw_commit.is_a?(Gitaly::GitCommit)

        message_split = raw_commit.message.split("\n", 2)
        Gitaly::GitCommit.new(
          id: raw_commit.oid,
          subject: message_split[0] ? message_split[0].chomp.b : "",
          body: raw_commit.message.b,
          parent_ids: raw_commit.parent_ids,
          author: gitaly_commit_author_from_raw(raw_commit.author),
          committer: gitaly_commit_author_from_raw(raw_commit.committer)
        )
      end

      private

      def init_from_hash(hash)
        raw_commit = hash.symbolize_keys

        serialize_keys.each do |key|
          send("#{key}=", raw_commit[key]) # rubocop:disable GitlabSecurity/PublicSend
        end
      end

      def init_from_gitaly(commit)
        @raw_commit = commit
        @id = commit.id
        # TODO: Once gitaly "takes over" Rugged consider separating the
        # subject from the message to make it clearer when there's one
        # available but not the other.
        @message = message_from_gitaly_body
        @authored_date = Time.at(commit.author.date.seconds).utc
        @author_name = commit.author.name.dup
        @author_email = commit.author.email.dup
        @committed_date = Time.at(commit.committer.date.seconds).utc
        @committer_name = commit.committer.name.dup
        @committer_email = commit.committer.email.dup
        @parent_ids = Array(commit.parent_ids)
      end

      def serialize_keys
        SERIALIZE_KEYS
      end

      def gitaly_commit_author_from_raw(author_or_committer)
        Gitaly::CommitAuthor.new(
          name: author_or_committer[:name].b,
          email: author_or_committer[:email].b,
          date: Google::Protobuf::Timestamp.new(seconds: author_or_committer[:time].to_i)
        )
      end

      # Get a collection of Gitlab::Git::Ref objects for this commit.
      #
      # Ex.
      #   commit.ref(repo)
      #
      def refs(repo)
        repo.refs_hash[id]
      end

      def message_from_gitaly_body
        return @raw_commit.subject.dup if @raw_commit.body_size.zero?
        return @raw_commit.body.dup if full_body_fetched_from_gitaly?

        if @raw_commit.body_size > MAX_COMMIT_MESSAGE_DISPLAY_SIZE
          "#{@raw_commit.subject}\n\n--commit message is too big".strip
        else
          fetch_body_from_gitaly
        end
      end

      def full_body_fetched_from_gitaly?
        @raw_commit.body.bytesize == @raw_commit.body_size
      end

      def fetch_body_from_gitaly
        self.class.get_message(@repository, id)
      end
    end
  end
end


text:
Begin by declaring a type that defines the information
that you need to collect from the command line.
Decorate each stored property with one of `ArgumentParser`'s property wrappers,
and then declare conformance to `ParsableCommand` and add the `@main` attribute.
Finally, implement your command's logic in the `run()` method.

```swift
import ArgumentParser

@main
struct Repeat: ParsableCommand {
    @Flag(help: "Include a counter with each repetition.")
    var includeCounter = false

    @Option(name: .shortAndLong, help: "The number of times to repeat 'phrase'.")
    var count: Int? = nil

    @Argument(help: "The phrase to repeat.")
    var phrase: String

    mutating func run() throws {
        let repeatCount = count ?? 2

        for i in 1...repeatCount {
            if includeCounter {
                print("\(i): \(phrase)")
            } else {
                print(phrase)
            }
        }
    }
}
```

The `ArgumentParser` library parses the command-line arguments,
instantiates your command type, and then either executes your `run()` method
or exits with a useful message.

`ArgumentParser` uses your properties' names and type information,
along with the details you provide using property wrappers,
to supply useful error messages and detailed help:

```
$ repeat hello --count 3
hello
hello
hello
$ repeat --count 3
Error: Missing expected argument 'phrase'.
Help:  <phrase>  The phrase to repeat.
Usage: repeat [--count <count>] [--include-counter] <phrase>
  See 'repeat --help' for more information.
$ repeat --help
USAGE: repeat [--count <count>] [--include-counter] <phrase>

ARGUMENTS:
  <phrase>                The phrase to repeat.

OPTIONS:
  --include-counter       Include a counter with each repetition.
  -c, --count <count>     The number of times to repeat 'phrase'.
  -h, --help              Show help for this command.
```

## Documentation

For guides, articles, and API documentation see the
[library's documentation on the Web][docs] or in Xcode.

- [ArgumentParser documentation][docs]
- [Getting Started with ArgumentParser](https://apple.github.io/swift-argument-parser/documentation/argumentparser/gettingstarted)
- [`ParsableCommand` documentation](https://apple.github.io/swift-argument-parser/documentation/argumentparser/parsablecommand)

[docs]: https://apple.github.io/swift-argument-parser/documentation/argumentparser/

#### Examples

This repository includes a few examples of using the library:

- [`repeat`](Examples/repeat/Repeat.swift) is the example shown above.
- [`roll`](Examples/roll/main.swift) is a simple utility implemented as a straight-line script.
- [`math`](Examples/math/Math.swift) is an annotated example of using nested commands and subcommands.
- [`count-lines`](Examples/count-lines/CountLines.swift) uses `async`/`await` code in its implementation.

You can also see examples of `ArgumentParser` adoption among Swift project tools:

- [`swift-format`](https://github.com/apple/swift-format/) uses some advanced features, like custom option values and hidden flags.
- [`swift-package-manager`](https://github.com/apple/swift-package-manager/) includes a deep command hierarchy and extensive use of option groups.

## Project Status

The Swift Argument Parser package is source stable;
version numbers follow semantic versioning.
Source breaking changes to public API can only land in a new major version.

The public API of version 1.0.0 of the `swift-argument-parser` package
consists of non-underscored declarations that are marked public in the `ArgumentParser` module.
Interfaces that aren't part of the public API may continue to change in any release,
including the exact wording and formatting of the autogenerated help and error messages,
as well as the package's examples, tests, utilities, and documentation.

Future minor versions of the package may introduce changes to these rules as needed.

We'd like this package to quickly embrace Swift language and toolchain improvements that are relevant to its mandate.
Accordingly, from time to time,
we expect that new versions of this package will require clients to upgrade to a more recent Swift toolchain release.
Requiring a new Swift release will only require a minor version bump.

## Adding `ArgumentParser` as a Dependency

To use the `ArgumentParser` library in a SwiftPM project,
add it to the dependencies for your package and your command-line executable target:

```swift
let package = Package(
    // name, platforms, products, etc.
    dependencies: [
        // other dependencies
        .package(url: "https://github.com/apple/swift-argument-parser", from: "1.2.0"),
    ],
    targets: [
        .executableTarget(name: "<command-line-tool>", dependencies: [
            // other dependencies
            .product(name: "ArgumentParser", package: "swift-argument-parser"),
        ]),
        // other targets
    ]
)
```

### Supported Versions

The most recent versions of swift-argument-parser support Swift 5.5 and newer. The minimum Swift version supported by swift-argument-parser releases are detailed below:

swift-argument-parser | Minimum Swift Version
----------------------|----------------------
`0.0.1 ..< 0.2.0`     | 5.1
`0.2.0 ..< 1.1.0`     | 5.2
`1.1.0 ...`           | 5.5


text:
<?php

namespace Drupal\Driver\Cores;

/**
 * Drupal core interface.
 */
interface CoreInterface {
  /**
   * Instantiate the core interface.
   *
   * @param string $drupalRoot
   *
   * @param string $uri
   *   URI that is accessing Drupal. Defaults to 'default'.
   */
  public function __construct($drupalRoot, $uri = 'default');

  /**
   * Bootstrap Drupal.
   */
  public function bootstrap();

  /**
   * Clear caches.
   */
  public function clearCache();

  /**
   * Run cron.
   *
   * @return boolean
   *   True if cron runs, otherwise false.
   */
  public function runCron();

  /**
   * Create a node.
   */
  public function nodeCreate($node);

  /**
   * Delete a node.
   */
  public function nodeDelete($node);

  /**
   * Create a user.
   */
  public function userCreate(\stdClass $user);

  /**
   * Delete a user.
   */
  public function userDelete(\stdClass $user);

  /**
   * Add a role to a user.
   */
  public function userAddRole(\stdClass $user, $role_name);

  /**
   * Validate, and prepare environment for Drupal bootstrap.
   *
   * @throws BootstrapException
   *
   * @see _drush_bootstrap_drupal_site_validate()
   */
  public function validateDrupalSite();

  /**
   * Create a taxonomy term.
   */
  public function termCreate(\stdClass $term);

  /**
   * Delete a taxonomy term,
   */
  public function termDelete(\stdClass $term);

  /**
   * Create a role
   *
   * @param array $permissions
   *   An array of permissions to create the role with.
   *
   * @return string
   *   Role ID of newly created role, or FALSE if role creation failed.
   */
  public function roleCreate(array $permissions);

  /**
   * Delete a role
   *
   * @param $rid
   *   A role name to delete.
   */
  public function roleDelete($rid);

}