text:
package liquibase.changelog;

import liquibase.*;
import liquibase.changelog.filter.ContextChangeSetFilter;
import liquibase.changelog.filter.DbmsChangeSetFilter;
import liquibase.changelog.filter.LabelChangeSetFilter;
import liquibase.changelog.visitor.ValidatingVisitor;
import liquibase.database.Database;
import liquibase.database.DatabaseList;
import liquibase.database.ObjectQuotingStrategy;
import liquibase.exception.*;
import liquibase.logging.Logger;
import liquibase.parser.ChangeLogParser;
import liquibase.parser.ChangeLogParserFactory;
import liquibase.parser.core.ParsedNode;
import liquibase.parser.core.ParsedNodeException;
import liquibase.precondition.Conditional;
import liquibase.precondition.Precondition;
import liquibase.precondition.core.PreconditionContainer;
import liquibase.resource.Resource;
import liquibase.resource.ResourceAccessor;
import liquibase.servicelocator.LiquibaseService;
import liquibase.util.StringUtil;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Paths;
import java.util.*;
import java.util.regex.Pattern;

/**
 * Encapsulates the information stored in the change log XML file.
 */
public class DatabaseChangeLog implements Comparable<DatabaseChangeLog>, Conditional {
    private static final ThreadLocal<DatabaseChangeLog> ROOT_CHANGE_LOG = new ThreadLocal<>();
    private static final ThreadLocal<DatabaseChangeLog> PARENT_CHANGE_LOG = new ThreadLocal<>();
    private static final Logger LOG = Scope.getCurrentScope().getLog(DatabaseChangeLog.class);
    private static final Pattern SLASH_PATTERN = Pattern.compile("^/");
    private static final Pattern NON_CLASSPATH_PATTERN = Pattern.compile("^classpath:");
    private static final Pattern DOUBLE_BACK_SLASH_PATTERN = Pattern.compile("\\\\");
    private static final Pattern DOUBLE_SLASH_PATTERN = Pattern.compile("//+");
    private static final Pattern SLASH_DOT_SLASH_PATTERN = Pattern.compile("/\\./");
    private static final Pattern NO_LETTER_PATTERN = Pattern.compile("^[a-zA-Z]:");
    private static final Pattern DOT_SLASH_PATTERN = Pattern.compile("^\\.?/");

    private PreconditionContainer preconditionContainer = new GlobalPreconditionContainer();
    private String physicalFilePath;
    private String logicalFilePath;
    private String changeLogId;
    private ObjectQuotingStrategy objectQuotingStrategy;

    private List<ChangeSet> changeSets = new ArrayList<>();
    private ChangeLogParameters changeLogParameters;

    private RuntimeEnvironment runtimeEnvironment;

    private DatabaseChangeLog rootChangeLog = ROOT_CHANGE_LOG.get();

    private DatabaseChangeLog parentChangeLog = PARENT_CHANGE_LOG.get();

    private ContextExpression contextFilter;

    private ContextExpression includeContextFilter;

    private Labels includeLabels;
    private boolean includeIgnore;

    public DatabaseChangeLog() {
    }

    public DatabaseChangeLog(String physicalFilePath) {
        this.physicalFilePath = physicalFilePath;
    }

    public void setRootChangeLog(DatabaseChangeLog rootChangeLog) {
        this.rootChangeLog = rootChangeLog;
    }

    public DatabaseChangeLog getRootChangeLog() {
        return (rootChangeLog != null) ? rootChangeLog : this;
    }

    public void setParentChangeLog(DatabaseChangeLog parentChangeLog) {
        this.parentChangeLog = parentChangeLog;
    }

    public DatabaseChangeLog getParentChangeLog() {
        return parentChangeLog;
    }

    public RuntimeEnvironment getRuntimeEnvironment() {
        return runtimeEnvironment;
    }

    public void setRuntimeEnvironment(RuntimeEnvironment runtimeEnvironment) {
        this.runtimeEnvironment = runtimeEnvironment;
    }

    @Override
    public PreconditionContainer getPreconditions() {
        return preconditionContainer;
    }

    @Override
    public void setPreconditions(PreconditionContainer precond) {
        this.preconditionContainer.addNestedPrecondition(precond);
    }

    public ChangeLogParameters getChangeLogParameters() {
        return changeLogParameters;
    }

    public void setChangeLogParameters(ChangeLogParameters changeLogParameters) {
        this.changeLogParameters = changeLogParameters;
    }

    public String getPhysicalFilePath() {
        return physicalFilePath;
    }

    public void setPhysicalFilePath(String physicalFilePath) {
        this.physicalFilePath = physicalFilePath;
    }

    public String getChangeLogId() {
        return changeLogId;
    }

    public void setChangeLogId(String changeLogId) {
        this.changeLogId = changeLogId;
    }

    public String getLogicalFilePath() {
        String returnPath = logicalFilePath;
        if (logicalFilePath == null) {
            returnPath = physicalFilePath;
        }
        if (returnPath == null) {
            return null;
        }
        String path = DOUBLE_BACK_SLASH_PATTERN.matcher(returnPath).replaceAll("/");
        return SLASH_PATTERN.matcher(path).replaceFirst("");
    }

    public void setLogicalFilePath(String logicalFilePath) {
        this.logicalFilePath = logicalFilePath;
    }

    public String getFilePath() {
        if (logicalFilePath == null) {
            return physicalFilePath;
        } else {
            return getLogicalFilePath();
        }
    }

    public ObjectQuotingStrategy getObjectQuotingStrategy() {
        return objectQuotingStrategy;
    }

    public void setObjectQuotingStrategy(ObjectQuotingStrategy objectQuotingStrategy) {
        this.objectQuotingStrategy = objectQuotingStrategy;
    }

    /**
     * @deprecated use {@link #getContextFilter()}
     */
    public ContextExpression getContexts() {
        return getContextFilter();
    }

    /**
     * @deprecated use {@link #setContextFilter(ContextExpression)}
     */
    public void setContexts(ContextExpression contexts) {
        setContextFilter(contexts);
    }

    public ContextExpression getContextFilter() {
        return contextFilter;
    }

    public void setContextFilter(ContextExpression contextFilter) {
        this.contextFilter = contextFilter;
    }

    public ContextExpression getIncludeContextFilter() {
        return includeContextFilter;
    }

    /**
     * @deprecated Correct version is {@link #setIncludeLabels(Labels)}. Kept for backwards compatibility.
     */
    public void setIncludeLabels(LabelExpression labels) {
        this.includeLabels = new Labels(labels.toString());
    }

    public void setIncludeLabels(Labels labels) {
        this.includeLabels = labels;
    }

    public Labels getIncludeLabels() {
        return includeLabels;
    }

    public void setIncludeIgnore(boolean ignore) {
        this.includeIgnore = ignore;
    }

    public boolean isIncludeIgnore() {
        return this.includeIgnore;
    }

    /**
     * @deprecated use {@link #setIncludeContextFilter(ContextExpression)}
     */
    public void setIncludeContexts(ContextExpression includeContexts) {
        setIncludeContextFilter(includeContexts);
    }

    public void setIncludeContextFilter(ContextExpression includeContextFilter) {
        this.includeContextFilter = includeContextFilter;
    }

    @Override
    public String toString() {
        return getFilePath();
    }

    @Override
    public int compareTo(DatabaseChangeLog o) {
        return getFilePath().compareTo(o.getFilePath());
    }

    public ChangeSet getChangeSet(String path, String author, String id) {
	    final List<ChangeSet> possibleChangeSets = getChangeSets(path, author, id);
	    if (possibleChangeSets.isEmpty()){
	    	return null;
	    }
	    return possibleChangeSets.get(0);
    }

    public List<ChangeSet> getChangeSets(String path, String author, String id) {
	    final ArrayList<ChangeSet> changeSetsToReturn = new ArrayList<>();
	    for (ChangeSet changeSet : this.changeSets) {
            final String normalizedPath = normalizePath(changeSet.getFilePath());
            if (normalizedPath != null &&
                    normalizedPath.equalsIgnoreCase(normalizePath(path)) &&
                    changeSet.getAuthor().equalsIgnoreCase(author) &&
                    changeSet.getId().equalsIgnoreCase(id) &&
                    isDbmsMatch(changeSet.getDbmsSet())) {
                changeSetsToReturn.add(changeSet);
            }
        }
        return changeSetsToReturn;
    }

    public List<ChangeSet> getChangeSets() {
        return changeSets;
    }

    public void addChangeSet(ChangeSet changeSet) {
        if (changeSet.getRunOrder() == null) {
            ListIterator<ChangeSet> it = this.changeSets.listIterator(this.changeSets.size());
            boolean added = false;
            while (it.hasPrevious() && !added) {
                if (!"last".equals(it.previous().getRunOrder())) {
                    it.next();
                    it.add(changeSet);
                    added = true;
                }
            }
            if (!added) {
                it.add(changeSet);
            }

        } else if ("first".equals(changeSet.getRunOrder())) {
            ListIterator<ChangeSet> it = this.changeSets.listIterator();
            boolean added = false;
            while (it.hasNext() && !added) {
                if (!"first".equals(it.next().getRunOrder())) {
                    it.previous();
                    it.add(changeSet);
                    added = true;
                }
            }
            if (!added) {
                this.changeSets.add(changeSet);
            }
        } else if ("last".equals(changeSet.getRunOrder())) {
            this.changeSets.add(changeSet);
        } else {
            throw new UnexpectedLiquibaseException("Unknown runOrder: " + changeSet.getRunOrder());
        }
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if ((o == null) || (getClass() != o.getClass())) {
            return false;
        }

        DatabaseChangeLog that = (DatabaseChangeLog) o;

        return getFilePath().equals(that.getFilePath());

    }

    @Override
    public int hashCode() {
        return getFilePath().hashCode();
    }

    public void validate(Database database, String... contexts) throws LiquibaseException {
        this.validate(database, new Contexts(contexts), new LabelExpression());
    }

    public void validate(Database database, Contexts contexts, LabelExpression labelExpression)
            throws LiquibaseException {

        database.setObjectQuotingStrategy(objectQuotingStrategy);

        ChangeLogIterator logIterator = new ChangeLogIterator(
                this,
                new DbmsChangeSetFilter(database),
                new ContextChangeSetFilter(contexts),
                new LabelChangeSetFilter(labelExpression)
        );

        ValidatingVisitor validatingVisitor = new ValidatingVisitor(database.getRanChangeSetList());
        validatingVisitor.validate(database, this);
        logIterator.run(validatingVisitor, new RuntimeEnvironment(database, contexts, labelExpression));

        final Logger log = Scope.getCurrentScope().getLog(getClass());
        for (String message : validatingVisitor.getWarnings().getMessages()) {
            log.warning(message);
        }

        if (!validatingVisitor.validationPassed()) {
            throw new ValidationFailedException(validatingVisitor);
        }
    }

    public ChangeSet getChangeSet(RanChangeSet ranChangeSet) {
        final ChangeSet changeSet = getChangeSet(ranChangeSet.getChangeLog(), ranChangeSet.getAuthor(), ranChangeSet.getId());
        if (changeSet != null) {
            changeSet.setStoredFilePath(ranChangeSet.getStoredChangeLog());
        }
        return changeSet;
    }

    public List<ChangeSet> getChangeSets(RanChangeSet ranChangeSet) {
        return getChangeSets(ranChangeSet.getChangeLog(), ranChangeSet.getAuthor(), ranChangeSet.getId());
    }

    public void load(ParsedNode parsedNode, ResourceAccessor resourceAccessor) throws ParsedNodeException, SetupException {
        setChangeLogId(parsedNode.getChildValue(null, "changeLogId", String.class));
        setLogicalFilePath(parsedNode.getChildValue(null, "logicalFilePath", String.class));

        String context = parsedNode.getChildValue(null, "contextFilter", String.class);
        if (context == null) {
            context = parsedNode.getChildValue(null, "context", String.class);
        }

        setContextFilter(new ContextExpression(context));
        String nodeObjectQuotingStrategy = parsedNode.getChildValue(null, "objectQuotingStrategy", String.class);
        if (nodeObjectQuotingStrategy != null) {
            setObjectQuotingStrategy(ObjectQuotingStrategy.valueOf(nodeObjectQuotingStrategy));
        }
        for (ParsedNode childNode : parsedNode.getChildren()) {
            handleChildNode(childNode, resourceAccessor, new HashMap<>());
        }
    }

    protected void expandExpressions(ParsedNode parsedNode) throws UnknownChangeLogParameterException {
        if (changeLogParameters == null) {
            return;
        }
        try {
            Object value = parsedNode.getValue();
            if ((value != null) && (value instanceof String)) {
                parsedNode.setValue(changeLogParameters.expandExpressions(parsedNode.getValue(String.class), this));
            }

            List<ParsedNode> children = parsedNode.getChildren();
            if (children != null) {
                for (ParsedNode child : children) {
                    expandExpressions(child);
                }
            }
        } catch (ParsedNodeException e) {
            throw new UnexpectedLiquibaseException(e);
        }
    }

    protected void handleChildNode(ParsedNode node, ResourceAccessor resourceAccessor)
            throws ParsedNodeException, SetupException {
        handleChildNode(node, resourceAccessor, new HashMap<>());
    }

    protected void handleChildNode(ParsedNode node, ResourceAccessor resourceAccessor, Map<String, Object> nodeScratch)
            throws ParsedNodeException, SetupException {
        expandExpressions(node);
        String nodeName = node.getName();
        switch (nodeName) {
            case "changeSet":
                if (isDbmsMatch(node.getChildValue(null, "dbms", String.class))) {
                    this.addChangeSet(createChangeSet(node, resourceAccessor));
                }
                break;
            case "modifyChangeSets":
                ModifyChangeSets modifyChangeSets = new ModifyChangeSets((String)node.getChildValue(null, "runWith"));
                nodeScratch = new HashMap<>();
                nodeScratch.put("modifyChangeSets", modifyChangeSets);
                for (ParsedNode modifyChildNode : node.getChildren()) {
                    handleChildNode(modifyChildNode, resourceAccessor, nodeScratch);
                }
                nodeScratch.remove("modifyChangeSets");
                break;
            case "include": {
                String path = node.getChildValue(null, "file", String.class);
                if (path == null) {
                    throw new UnexpectedLiquibaseException("No 'file' attribute on 'include'");
                }
                path = path.replace('\\', '/');
                ContextExpression includeContextFilter = new ContextExpression(node.getChildValue(null, "contextFilter", String.class));
                if (includeContextFilter.isEmpty()) {
                    includeContextFilter = new ContextExpression(node.getChildValue(null, "context", String.class));
                }
                Labels labels = new Labels(node.getChildValue(null, "labels", String.class));
                Boolean ignore = node.getChildValue(null, "ignore", Boolean.class);
                try {
                    include(path,
                            node.getChildValue(null, "relativeToChangelogFile", false),
                            resourceAccessor,
                            includeContextFilter,
                            labels,
                            ignore,
                            OnUnknownFileFormat.FAIL,
                            (ModifyChangeSets)nodeScratch.get("modifyChangeSets"));
                } catch (LiquibaseException e) {
                    throw new SetupException(e);
                }
                break;
            }
            case "includeAll": {
                String path = node.getChildValue(null, "path", String.class);
                String resourceFilterDef = node.getChildValue(null, "filter", String.class);
                if (resourceFilterDef == null) {
                    resourceFilterDef = node.getChildValue(null, "resourceFilter", String.class);
                }
                IncludeAllFilter resourceFilter = null;
                if (resourceFilterDef != null) {
                    try {
                        resourceFilter = (IncludeAllFilter) Class.forName(resourceFilterDef).getConstructor().newInstance();
                    } catch (ReflectiveOperationException e) {
                        throw new SetupException(e);
                    }
                }

                String resourceComparatorDef = node.getChildValue(null, "resourceComparator", String.class);
                Comparator<String> resourceComparator = null;
                if (resourceComparatorDef == null) {
                    resourceComparator = getStandardChangeLogComparator();
                } else {
                    try {
                        resourceComparator = (Comparator<String>) Class.forName(resourceComparatorDef).getConstructor().newInstance();
                    } catch (ReflectiveOperationException e) {
                        //take default comparator
                        Scope.getCurrentScope().getLog(getClass()).info("no resourceComparator defined - taking default " +
                                "implementation");
                        resourceComparator = getStandardChangeLogComparator();
                    }
                }

                ContextExpression includeContextFilter = new ContextExpression(node.getChildValue(null, "contextFilter", String.class));
                if (includeContextFilter.isEmpty()) {
                    includeContextFilter = new ContextExpression(node.getChildValue(null, "context", String.class));
                }
                Labels labels = new Labels(node.getChildValue(null, "labels", String.class));
                Boolean ignore = node.getChildValue(null, "ignore", Boolean.class);
                if (ignore == null) {
                    ignore = false;
                }
                includeAll(path, node.getChildValue(null, "relativeToChangelogFile", false), resourceFilter,
                        node.getChildValue(null, "errorIfMissingOrEmpty", true),
                        resourceComparator,
                        resourceAccessor,
                        includeContextFilter,
                        labels,
                        ignore,
                        (ModifyChangeSets)nodeScratch.get("modifyChangeSets"));
                break;
            }
            case "preConditions": {
                PreconditionContainer parsedContainer = new PreconditionContainer();
                parsedContainer.load(node, resourceAccessor);
                this.preconditionContainer.addNestedPrecondition(parsedContainer);

                break;
            }
            case "property": {
                try {
                    String contextFilter = node.getChildValue(null, "contextFilter", String.class);
                    if (StringUtil.isEmpty(contextFilter)) {
                        contextFilter = node.getChildValue(null, "context", String.class);
                    }
                    String dbms = node.getChildValue(null, "dbms", String.class);
                    String labels = node.getChildValue(null, "labels", String.class);
                    Boolean global = node.getChildValue(null, "global", Boolean.class);
                    if (global == null) {
                        // okay behave like liquibase < 3.4 and set global == true
                        global = true;
                    }

                    String file = node.getChildValue(null, "file", String.class);

                    if (file == null) {
                        // direct referenced property, no file
                        String name = node.getChildValue(null, "name", String.class);
                        String value = node.getChildValue(null, "value", String.class);

                        this.changeLogParameters.set(name, value, contextFilter, labels, dbms, global, this);
                    } else {
                        // read properties from the file
                        Properties props = new Properties();
                        Resource resource = resourceAccessor.get(file);
                        if (resource == null) {
                            Scope.getCurrentScope().getLog(getClass()).info("Could not open properties file " + file);
                        } else {
                            try (InputStream propertiesStream = resource.openInputStream()) {
                                props.load(propertiesStream);

                                for (Map.Entry<Object, Object> entry : props.entrySet()) {
                                    this.changeLogParameters.set(
                                            entry.getKey().toString(),
                                            entry.getValue().toString(),
                                            contextFilter,
                                            labels,
                                            dbms,
                                            global,
                                            this
                                    );
                                }
                            }
                        }
                    }
                } catch (IOException e) {
                    throw new ParsedNodeException(e);
                }

                break;
            }
            default:
                // we want to exclude child nodes that are not changesets or the other things
                // and avoid failing when encountering "child" nodes of the databaseChangeLog which are just
                // XML node attributes (like schemaLocation). If you don't understand, remove the if and run the tests
                // and look at the error output or review the "node" object here with a debugger.
                if (node.getChildren() != null && !node.getChildren().isEmpty()) {
                    throw new ParsedNodeException("Unexpected node found under databaseChangeLog: " + nodeName);
                }
        }
    }

    public boolean isDbmsMatch(String dbmsList) {
        return isDbmsMatch(DatabaseList.toDbmsSet(dbmsList));
    }

    public boolean isDbmsMatch(Set<String> dbmsSet) {
        return dbmsSet == null
                || changeLogParameters == null
                || changeLogParameters.getValue("database.typeName", this) == null
                || DatabaseList.definitionMatches(dbmsSet, changeLogParameters.getValue("database.typeName", this).toString(), true);
    }

    /**
     * @deprecated Incorrect LabelExpression parameter. Kept for backwards compatibility
     */
    @Deprecated
    public void includeAll(String pathName,
                           boolean isRelativeToChangelogFile,
                           IncludeAllFilter resourceFilter,
                           boolean errorIfMissingOrEmpty,
                           Comparator<String> resourceComparator,
                           ResourceAccessor resourceAccessor,
                           ContextExpression includeContextFilter,
                           LabelExpression labelExpression,
                           boolean ignore)
            throws SetupException {
        Labels labels = null;
        if (labelExpression != null && !labelExpression.isEmpty()) {
            labels = new Labels(labelExpression.toString());
        }
        includeAll(pathName,
                isRelativeToChangelogFile,
                resourceFilter,
                errorIfMissingOrEmpty,
                resourceComparator,
                resourceAccessor,
                includeContextFilter,
                labels,
                ignore);
    }
    public void includeAll(String pathName,
                           boolean isRelativeToChangelogFile,
                           IncludeAllFilter resourceFilter,
                           boolean errorIfMissingOrEmpty,
                           Comparator<String> resourceComparator,
                           ResourceAccessor resourceAccessor,
                           ContextExpression includeContextFilter,
                           Labels labels,
                           boolean ignore)
            throws SetupException {
        includeAll(pathName, isRelativeToChangelogFile, resourceFilter, errorIfMissingOrEmpty, resourceComparator,
                   resourceAccessor, includeContextFilter, labels, ignore, new ModifyChangeSets(null));
    }

    public void includeAll(String pathName,
                           boolean isRelativeToChangelogFile,
                           IncludeAllFilter resourceFilter,
                           boolean errorIfMissingOrEmpty,
                           Comparator<String> resourceComparator,
                           ResourceAccessor resourceAccessor,
                           ContextExpression includeContextFilter,
                           Labels labels,
                           boolean ignore,
                           ModifyChangeSets modifyChangeSets)
            throws SetupException {
        try {
            if (pathName == null) {
                throw new SetupException("No path attribute for includeAll");
            }
            pathName = pathName.replace('\\', '/');

            if (StringUtil.isNotEmpty(pathName) && !(pathName.endsWith("/"))) {
                pathName = pathName + '/';
            }
            String relativeTo = null;
            if (isRelativeToChangelogFile) {
                relativeTo = this.getPhysicalFilePath();
            }

            List<Resource> unsortedResources = null;
            try {
                String path;
                if (relativeTo == null) {
                    path = pathName;
                } else {
                    path = resourceAccessor.get(relativeTo).resolveSibling(pathName).getPath();
                    path = Paths.get(path).normalize().toString()
                            .replace("\\", "/");
                }

                path = path.replace("\\", "/");
                LOG.fine("includeAll for " + pathName);
                LOG.fine("Using file opener for includeAll: " + resourceAccessor.toString());

                unsortedResources = resourceAccessor.search(path, true);
            } catch (IOException e) {
                if (errorIfMissingOrEmpty) {
                    throw e;
                }
            }
            SortedSet<Resource> resources = new TreeSet<>((o1, o2) -> resourceComparator.compare(o1.getPath(), o2.getPath()));
            if (unsortedResources != null) {
                for (Resource resourcePath : unsortedResources) {
                    if ((resourceFilter == null) || resourceFilter.include(resourcePath.getPath())) {
                        resources.add(resourcePath);
                    }
                }
            }

            if (resources.isEmpty() && errorIfMissingOrEmpty) {
                throw new SetupException(
                        "Could not find directory or directory was empty for includeAll '" + pathName + "'");
            }

            for (Resource resource : resources) {
                Scope.getCurrentScope().getLog(getClass()).info("Reading resource: " + resource);
                include(resource.getPath(), false, resourceAccessor, includeContextFilter,
                        labels, ignore, OnUnknownFileFormat.WARN, modifyChangeSets);
            }
        } catch (Exception e) {
            throw new SetupException(e);
        }
    }

    /**
     * @deprecated Incorrect LabelExpression parameter. Kept for backwards compatibility
     */
    @Deprecated
    public boolean include(String fileName,
                           boolean isRelativePath,
                           ResourceAccessor resourceAccessor,
                           ContextExpression includeContextFilter,
                           LabelExpression labelExpression,
                           Boolean ignore,
                           boolean logEveryUnknownFileFormat)
            throws LiquibaseException {
        Labels labels = null;
        if (labelExpression != null && !labelExpression.isEmpty()) {
            labels = new Labels(labelExpression.getLabels());
        }

        return include(fileName,
                isRelativePath,
                resourceAccessor,
                includeContextFilter,
                labels,
                ignore,
                logEveryUnknownFileFormat);
    }

    /**
     * @deprecated
     */
    public boolean include(String fileName,
                           boolean isRelativePath,
                           ResourceAccessor resourceAccessor,
                           ContextExpression includeContextFilter,
                           Labels labels,
                           Boolean ignore,
                           boolean logEveryUnknownFileFormat)
            throws LiquibaseException {
        return include(fileName, isRelativePath, resourceAccessor, includeContextFilter, labels, ignore, logEveryUnknownFileFormat ? OnUnknownFileFormat.WARN : OnUnknownFileFormat.SKIP);
    }

    public boolean include(String fileName,
                           boolean isRelativePath,
                           ResourceAccessor resourceAccessor,
                           ContextExpression includeContextFilter,
                           Labels labels,
                           Boolean ignore,
                           OnUnknownFileFormat onUnknownFileFormat)
            throws LiquibaseException {
        return include(fileName, isRelativePath, resourceAccessor, includeContextFilter, labels, ignore, onUnknownFileFormat, new ModifyChangeSets(null));
    }

    public boolean include(String fileName,
                           boolean isRelativePath,
                           ResourceAccessor resourceAccessor,
                           ContextExpression includeContextFilter,
                           Labels labels,
                           Boolean ignore,
                           OnUnknownFileFormat onUnknownFileFormat,
                           ModifyChangeSets modifyChangeSets)
            throws LiquibaseException {
        if (".svn".equalsIgnoreCase(fileName) || "cvs".equalsIgnoreCase(fileName)) {
            return false;
        }

        if (isRelativePath) {
            try {
                fileName = resourceAccessor.get(this.getPhysicalFilePath()).resolveSibling(fileName).getPath();
                fileName = Paths.get(fileName).normalize().toString()
                        .replace("\\", "/");
            } catch (IOException e) {
                throw new UnexpectedLiquibaseException(e);
            }
        }
        DatabaseChangeLog changeLog;
        try {
            DatabaseChangeLog rootChangeLog = ROOT_CHANGE_LOG.get();
            if (rootChangeLog == null) {
                ROOT_CHANGE_LOG.set(this);
            }
            DatabaseChangeLog parentChangeLog = PARENT_CHANGE_LOG.get();
            PARENT_CHANGE_LOG.set(this);
            try {
                ChangeLogParser parser = ChangeLogParserFactory.getInstance().getParser(fileName, resourceAccessor);
                changeLog = parser.parse(fileName, changeLogParameters, resourceAccessor);
                changeLog.setIncludeContextFilter(includeContextFilter);
                changeLog.setIncludeLabels(labels);
                changeLog.setIncludeIgnore(ignore != null ? ignore.booleanValue() : false);
            } finally {
                if (rootChangeLog == null) {
                    ROOT_CHANGE_LOG.remove();
                }
                if (parentChangeLog == null) {
                    PARENT_CHANGE_LOG.remove();
                } else {
                    PARENT_CHANGE_LOG.set(parentChangeLog);
                }
            }
        } catch (UnknownChangelogFormatException e) {
            if (onUnknownFileFormat == OnUnknownFileFormat.FAIL) {
                throw e;
            }
            // This matches only an extension, but filename can be a full path, too. Is it right?
            boolean matchesFileExtension = StringUtil.trimToEmpty(fileName).matches("\\.\\w+$");
            if (matchesFileExtension || onUnknownFileFormat == OnUnknownFileFormat.WARN) {
                Scope.getCurrentScope().getLog(getClass()).warning(
                        "included file " + fileName + "/" + fileName + " is not a recognized file type"
                );
            }
            return false;
        }
        PreconditionContainer preconditions = changeLog.getPreconditions();
        if (preconditions != null) {
            if (null == this.getPreconditions()) {
                this.setPreconditions(new PreconditionContainer());
            }
            this.getPreconditions().addNestedPrecondition(preconditions);
        }
        for (ChangeSet changeSet : changeLog.getChangeSets()) {
            if (changeSet.getRunWith() == null) {
                changeSet.setRunWith(modifyChangeSets != null ? modifyChangeSets.getRunWith() : null);
            }
            addChangeSet(changeSet);
        }

        return true;
    }

    protected ChangeSet createChangeSet(ParsedNode node, ResourceAccessor resourceAccessor) throws ParsedNodeException {
        ChangeSet changeSet = new ChangeSet(this);
        changeSet.setChangeLogParameters(this.getChangeLogParameters());
        changeSet.load(node, resourceAccessor);
        return changeSet;
    }

    protected Comparator<String> getStandardChangeLogComparator() {
        return new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                //by ignoring WEB-INF/classes in path all changelog Files independent
                //whehther they are in a WAR or in a JAR are order following the same rule
                return o1.replace("WEB-INF/classes/", "").compareTo(o2.replace("WEB-INF/classes/", ""));
            }
        };
    }

    public static String normalizePath(String filePath) {
        if (filePath == null) {
            return null;
        }
        String noClassPathReplaced = NON_CLASSPATH_PATTERN.matcher(filePath).replaceFirst("");
        String doubleBackSlashReplaced = DOUBLE_BACK_SLASH_PATTERN.matcher(noClassPathReplaced).replaceAll("/");
        String doubleSlashReplaced = DOUBLE_SLASH_PATTERN.matcher(doubleBackSlashReplaced).replaceAll("/");
        String slashDotSlashReplaced = SLASH_DOT_SLASH_PATTERN.matcher(doubleSlashReplaced).replaceAll("/");
        String noLetterReplaced = NO_LETTER_PATTERN.matcher(slashDotSlashReplaced).replaceFirst("");
        return DOT_SLASH_PATTERN.matcher(noLetterReplaced).replaceFirst("");
    }

    public void clearCheckSums() {
        for (ChangeSet changeSet : getChangeSets()) {
            changeSet.clearCheckSum();
        }
    }

    /**
     *
     * Container class to handle the modifyChangeSets tag.
     * Other attributes may be added later
     *
     */
    private static class ModifyChangeSets {
        private final String runWith;

        /**
         *
         * @param  runWith                The native executor to execute all included change sets with. Can be null
         *
         */
        public ModifyChangeSets(String runWith) {
            this.runWith = runWith;
        }

        public String getRunWith() {
            return runWith;
        }
    }

    /**
     * Holder for the PreconditionContainer for this changelog, plus any nested changelogs.
     */
    @LiquibaseService(skip = true)
    private static class GlobalPreconditionContainer extends PreconditionContainer {

        /**
         * This container should always be TEST because it may contain a mix of containers which may or may not get tested during update-sql
         */
        @Override
        public OnSqlOutputOption getOnSqlOutput() {
            return OnSqlOutputOption.TEST;
        }

        @Override
        public void addNestedPrecondition(Precondition precondition) {
            super.addNestedPrecondition(precondition);
        }
    }

    /**
     * Controls what to do when including a file with a format that isn't recognized by a changelog parser.
     */
    public enum OnUnknownFileFormat {

        /**
         * Silently skip unknown files.
         */
        SKIP,

        /**
         * Log a warning about the file not being in a recognized format, but continue on
         */
        WARN,

        /**
         * Fail parsing with an error
         */
        FAIL
    }

}


text:
const fs = require('fs')
const EventEmitter = require('events')
const event = require('p-event')
const ms = require('ms')
const getRandom = require('random-item')
const debug = require('debug')('WikiBattle:pages')

/**
 * Possible starting and goal wikipedia articles manager.
 */

module.exports = class WikiPages extends EventEmitter {
  constructor (filename) {
    super()

    this.pages = null
    this.filename = filename

    try { this.load() } catch (err) {
      const fd = fs.openSync(this.filename, 'a')
      fs.closeSync(fd)
    }
    this.startWatching()
  }

  /**
   * Load article titles from the pages file.
   */

  load () {
    debug('Loading pages')
    const json = fs.readFileSync(this.filename, 'utf8')
    this.pages = JSON.parse(json)
    this.emit('loaded')
  }

  /**
   * Begin watching the pages file, and reload when it changes.
   */

  startWatching () {
    fs.watch(this.filename, () => {
      setTimeout(() => {
        debug('Reloading pages')
        this.load()
      }, ms('2 seconds'))
    })
  }

  /**
   * Get a random article name.
   */

  random () {
    return getRandom(this.pages)
  }

  /**
   * Get a pair of random article names, guaranteed to be two different pages.
   */

  randomPair () {
    const one = this.random()

    let two = this.random()
    while (one === two) {
      two = this.random()
    }

    return [one, two]
  }

  /**
   * Wait for the pages list to be available.
   */

  async ready () {
    if (!Array.isArray(this.pages)) {
      await event(this, 'loaded')
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
@interface RunTrace : UIView

@end


text:
module Redis

  #WARN Time complexity may not match C version in this module yet.
  #TODO Should add and delete manipulate @keys instead of clearing?

  module ZSets

    class ZSet
      include Enumerable

      def initialize
        @hash = Hash.new
  	    @keys = nil
  	    @keys_reverse = nil
  	  end

  	  def add(o, s = 0.0)
        @hash[o] = s
  	    @keys = nil
  	    @keys_reverse = nil
        self
      end

  	  def delete(o)
  	    @keys = nil
  	    @keys_reverse = nil
  	    @hash.delete(o)
  	    self
  	  end

  	  def include?(o)
        @hash.include?(o)
      end

  	  def score(o)
  	    @hash[o]
      end

      def size
        @hash.size
      end

      def empty?
        @hash.empty?
      end

  	  def each
  	    block_given? or return enum_for(__method__)
  	    to_a.each { |o| yield(o) }
  	    self
  	  end

  	  def to_a
  	    unless @keys
    	    (@keys = @hash.to_a).sort! do |a, b|
    	      a.reverse <=> b.reverse
  	      end
  	    end
  	    @keys
  	  end

  	  def to_a_reverse
  	    unless @keys_reverse
  	      @keys_reverse = to_a.reverse
        end
  	    @keys_reverse
      end

      def range reverse, start ,stop, conversions, withscores = false
        start = conversions.redis_i start
        stop = conversions.redis_i stop
        array = reverse ? to_a_reverse : to_a
        start = 0 if start < -size
        return array[start..stop].flatten(1) if withscores
        (array[start..stop]||[]).collect{|i|i.first}
      end

      def range_by_score reverse, min, max, conversions, *args
        withscores = offset = count = nil
        until args.empty?
          case args.shift.upcase
          when 'LIMIT'
            offset = args.shift.to_i
            count = args.shift.to_i
          when 'WITHSCORES'
            withscores = true
          else
            raise 'bad arguments'
          end
        end
        result = []
        min_exclusive = false
        if min[0..0] == '('
          min_exclusive = true
          min = min[1..-1]
        end
        min = conversions.redis_f min
        max_exclusive = false
        if max[0..0] == '('
          max_exclusive = true
          max = max[1..-1]
        end
        max = conversions.redis_f max
        if reverse
          x = min; min = max; max = x
        end
        (reverse ? to_a_reverse : to_a).each do |member, score|
          next if min > score or (min_exclusive and min >= score)
          next if max < score or (max_exclusive and max <= score)
          if offset
            offset -= 1
            next unless offset < 0
            offset = nil
          end
          result << member
          result << score if withscores
          if count
            count -= 1
            break if count == 0
          end
        end
        result
      end

      def self.aggregate database, is_and, destination, numkeys, conversions, *args
        numkeys = numkeys.to_i
        aggregate = 'SUM'
        keys = []
        keys << args.shift while (numkeys -= 1) >= 0
        weights = Array.new keys.size, 1
        until args.empty?
          case args.shift.upcase
          when 'WEIGHTS'
            weights = []
            keys.size.times {weights << conversions.redis_f(args.shift, 'weight value is not a double')}
          when 'AGGREGATE'
            aggregate = args.shift.upcase
          else
            raise 'bad arguments'
          end
        end
        results = []
        keys.zip(weights) do |key, weight|
          inner_result = ZSet.new
          record = database[key] || ZSet.new
          record.each do |member, score|
            inner_result.add member, (score||1) * weight
          end
          results << inner_result
        end
        result = results.reduce do |memo, result|
          n = is_and ? new : memo
          result.each do |member, score|
            next if is_and and !memo.include?(member)
            test = [score, memo.score(member)].compact
            text << 0 if test.empty?
            case aggregate
            when 'SUM'
              score = test.reduce :+
            when 'MIN'
              score = test.min
            when 'MAX'
              score = test.max
            else
              raise 'bad arguments'
            end
            n.add member, score
          end
          n
        end
        database[destination] = result unless result.empty?
        result.size
      end

    end

    def redis_ZADD key, score, member
      record = (@database[key] ||= ZSet.new)
      result = !record.include?(member)
      record.add member, redis_f(score)
      result
    end

    def redis_ZINCRBY key, increment, member
      record = (@database[key] ||= ZSet.new)
      increment = redis_f increment
      if record.include?(member)
        score = record.score(member) + increment
      else
        score = increment
      end
      raise 'NaN' if score.nan?
      record.add member, score
      score
    end

    def redis_ZRANK key, member
      record = (@database[key] || ZSet.new).to_a
      record.index {|i| i[0]==member}
    end

    def redis_ZREM key, member
      record = @database[key] || []
      return false unless record.include? member
      record.delete member
      @database.delete key if record.empty?
      return true
    end

    def redis_ZSCORE key, member
      (@database[key] || ZSet.new).score member
    end

    def redis_ZREVRANK key, member
      record = (@database[key] || ZSet.new).to_a_reverse
      record.index {|i| i[0]==member}
    end

    def redis_ZCARD key
      (@database[key] || []).size
    end

    def redis_ZREMRANGEBYSCORE key, min, max
      record = @database[key] || ZSet.new
      range = record.range_by_score(false, min, max, self)
      range.each do |member, score|
        record.delete member
      end
      range.size
    end

    def redis_ZCOUNT key, min, max
      record = @database[key] || ZSet.new
      record.range_by_score(false, min, max, self).size
    end

    def redis_ZREVRANGEBYSCORE key, min, max, *args
      record = @database[key] || ZSet.new
      record.range_by_score true, min, max, self, *args
    end

    def redis_ZRANGEBYSCORE key, min, max, *args
      record = @database[key] || ZSet.new
      record.range_by_score false, min, max, self, *args
    end

    def redis_ZRANGE key, start ,stop, withscores = false
      record = @database[key] || ZSet.new
      start = redis_i start
      stop = redis_i stop
      record.range false, start, stop, self, withscores
    end

    def redis_ZREVRANGE key, start ,stop, withscores = false
      record = @database[key] || ZSet.new
      start = redis_i start
      stop = redis_i stop
      record.range true, start, stop, self, withscores
    end

    def redis_ZREMRANGEBYRANK key, start, stop
      record = @database[key] || ZSet.new
      range = record.range false, start, stop, self
      range.each do |member, score|
        record.delete member
      end
      range.size
    end

    def redis_ZUNIONSTORE destination, numkeys, *args
      ZSet.aggregate @database, false, destination, numkeys, self, *args
    end

    def redis_ZINTERSTORE destination, numkeys, *args
      ZSet.aggregate @database, true, destination, numkeys, self, *args
    end

  end
end


text:
Super Lite Android Library to select files/directories from Device Storage.

### Developed by
[Angad Singh](https://www.github.com/angads25) ([@angads25](https://www.twitter.com/angads25))

### Benchmark:
[![API](https://img.shields.io/badge/API-9%2B-brightgreen.svg?style=flat)](https://android-arsenal.com/api?level=9)

### Where to Find:
[ ![Download](https://api.bintray.com/packages/angads25/maven/filepicker/images/download.svg) ](https://bintray.com/angads25/maven/filepicker/_latestVersion) [![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.github.angads25/filepicker/badge.svg)](https://maven-badges.herokuapp.com/maven-central/com.github.angads25/filepicker) [![Android Arsenal](https://img.shields.io/badge/Android%20Arsenal-FilePicker-blue.svg?style=flat)](http://android-arsenal.com/details/1/3950)

### Read all about internal classes and functions in the [wiki](https://github.com/Angads25/android-filepicker/wiki).

### Features

* Easy to Implement.
* No permissions required.
* Files, Directory Selection.
* Single or Multiple File selection.

### Installation

* Library is also Available in MavenCentral, So just put this in your app dependencies to use it:
```gradle
    compile 'com.github.angads25:filepicker:1.1.1'
```

### Usage
## FilePickerDialog
1. Start by creating an instance of `DialogProperties`.

    ```java
        DialogProperties properties = new DialogProperties();
    ```

    Now 'DialogProperties' has certain parameters.

2. Assign values to each Dialog Property using `DialogConfig` class.

    ```java
        properties.selection_mode = DialogConfigs.SINGLE_MODE;
        properties.selection_type = DialogConfigs.FILE_SELECT;
        properties.root = new File(DialogConfigs.DEFAULT_DIR);
        properties.error_dir = new File(DialogConfigs.DEFAULT_DIR);
        properties.offset = new File(DialogConfigs.DEFAULT_DIR);
        properties.extensions = null;
    ```

3. Next create an instance of `FilePickerDialog`, and pass `Context` and `DialogProperties` references as parameters. Optional: You can change the title of dialog. Default is current directory name. Set the positive button string. Default is Select. Set the negative button string. Defalut is Cancel.

    ```java
        FilePickerDialog dialog = new FilePickerDialog(MainActivity.this,properties);
        dialog.setTitle("Select a File");
    ```

4.  Next, Attach `DialogSelectionListener` to `FilePickerDialog` as below,
    ```java
        dialog.setDialogSelectionListener(new DialogSelectionListener() {
            @Override
            public void onSelectedFilePaths(String[] files) {
                //files is the array of the paths of files selected by the Application User.
            }
        });
    ```
    An array of paths is returned whenever user press the `select` button`.

5. Use ```dialog.show()``` method to show dialog.

### NOTE:
Marshmallow and above requests for the permission on runtime. You should override `onRequestPermissionsResult` in Activity/AppCompatActivity class and show the dialog only if permissions have been granted.

```java
        //Add this method to show Dialog when the required permission has been granted to the app.
        @Override
        public void onRequestPermissionsResult(int requestCode,@NonNull String permissions[],@NonNull int[] grantResults) {
            switch (requestCode) {
                case FilePickerDialog.EXTERNAL_READ_PERMISSION_GRANT: {
                    if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        if(dialog!=null)
                        {   //Show dialog if the read permission has been granted.
                            dialog.show();
                        }
                    }
                    else {
                        //Permission has not been granted. Notify the user.
                        Toast.makeText(MainActivity.this,"Permission is Required for getting list of files",Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }
```

    That's It. You are good to proceed further.

### FilePickerPreference

1. Start by declaring [FilePickerPreference](https://github.com/angads25/android-filepicker/wiki/filepicker-preference) in your settings xml file as:

    ```xml
       <com.github.angads25.filepicker.view.FilePickerPreference
           xmlns:app="http://schemas.android.com/apk/res-auto"
           android:key="your_preference_key"
           android:title="Pick a Directory"
           android:summary="Just a Summary"
           android:defaultValue="/sdcard:/mnt"
           app:titleText="Select Directories"
           app:error_dir="/mnt"
           app:root_dir="/sdcard"
           app:selection_mode="multi_mode"
           app:selection_type="dir_select"
           app:extensions="txt:pdf:"/>
    ```

2. Implement [Preference.OnPreferenceChangeListener](https://developer.android.com/reference/android/preference/Preference.OnPreferenceChangeListener.html) to class requiring selected values and `Override` `onPreferenceChange(Preference, Object)` method. Check for preference key using [Preference](https://developer.android.com/reference/android/preference/Preference.html) reference.

    ```java
        @Override
        public boolean onPreferenceChange(Preference preference, Object o)
        {   if(preference.getKey().equals("your_preference_key"))
            {   ...
            }
            return false;
        }
    ```
3. Typecast `Object o` into `String` Object and use `split(String)` function in `String` class to get array of selected files.

    ```java
        @Override
        public boolean onPreferenceChange(Preference preference, Object o)
        {   if(preference.getKey().equals("your_preference_key"))
            {   String value=(String)o;
                String arr[]=value.split(":");
                ...
                ...
            }
            return false;
        }
    ```

    That's It. You are good to move further.

### Important:
* `defaultValue`, `error_dir`, `root_dir`, `offset_dir` must have valid directory/file paths.
* `defaultValue` paths should end with ':'.
* `defaultValue` can have multiple paths, there should be a ':' between two paths.
* `extensions` must not have '.'.
* `extensions` should end with ':' , also have ':' between two extensions.
eg. /sdcard:/mnt:

### Note:
[FilePickerPreference](https://github.com/angads25/android-filepicker/wiki/filepicker-preference) stores selected directories/files as a `String`. It delimits multiple files/directories using ':' `char`.

## Read more on implementation [here](https://github.com/Angads25/android-filepicker/wiki/Implementation).

### Screenshot

#### Theme.Black

![Screenshot 1](https://raw.githubusercontent.com/Angads25/android-filepicker/master/screenshots/theme_black.png)

#### Theme.Holo

![Screenshot 2](https://raw.githubusercontent.com/Angads25/android-filepicker/master/screenshots/theme_holo.png)

#### Theme.Holo.Light

![Screenshot 3](https://raw.githubusercontent.com/Angads25/android-filepicker/master/screenshots/theme_holo_light.png)

#### Theme.Material

![Screenshot 4](https://raw.githubusercontent.com/Angads25/android-filepicker/master/screenshots/theme_material.png)

#### Theme.DeviceDefault

![Screenshot 5](https://raw.githubusercontent.com/Angads25/android-filepicker/master/screenshots/theme_device_default.png)

### Performance

#### GPU Overdraw

![Performance 1](https://raw.githubusercontent.com/Angads25/android-filepicker/master/screenshots/performance_overdraw.png)

#### GPU Rendering

![Performance 2](https://raw.githubusercontent.com/Angads25/android-filepicker/master/screenshots/profile_gpu_rendering.png)

### License
    Copyright (C) 2016 Angad Singh

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.


text:
"""Modoboa related tasks."""

import json
import os
import pwd
import shutil
import stat
import sys

from .. import compatibility_matrix
from .. import package
from .. import python
from .. import system
from .. import utils

from . import base

class Modoboa(base.Installer):
    """Modoboa installation."""

    appname = "modoboa"
    no_daemon = True
    packages = {
        "deb": [
            "build-essential", "python3-dev", "libxml2-dev", "libxslt-dev",
            "libjpeg-dev", "librrd-dev", "rrdtool", "libffi-dev", "cron",
            "libssl-dev", "redis-server", "supervisor"
        ],
        "rpm": [
            "gcc", "gcc-c++", "python3-devel", "libxml2-devel", "libxslt-devel",
            "libjpeg-turbo-devel", "rrdtool-devel", "rrdtool", "libffi-devel",
            "supervisor", "redis"
        ]
    }
    config_files = [
        "crontab=/etc/cron.d/modoboa",
        "sudoers=/etc/sudoers.d/modoboa",
    ]
    with_db = True
    with_user = True

    def __init__(self, *args, **kwargs):
        """Get configuration."""
        super(Modoboa, self).__init__(*args, **kwargs)
        self.venv_path = self.config.get("modoboa", "venv_path")
        self.instance_path = self.config.get("modoboa", "instance_path")
        self.extensions = self.config.get("modoboa", "extensions").split()
        self.devmode = self.config.getboolean("modoboa", "devmode")
        # Sanity check for amavis
        self.amavis_enabled = False
        if "modoboa-amavis" in self.extensions:
            if self.config.getboolean("amavis", "enabled"):
                self.amavis_enabled = True
            else:
                self.extensions.remove("modoboa-amavis")
        if "modoboa-radicale" in self.extensions:
            if not self.config.getboolean("radicale", "enabled"):
                self.extensions.remove("modoboa-radicale")
        self.dovecot_enabled = self.config.getboolean("dovecot", "enabled")
        self.opendkim_enabled = self.config.getboolean("opendkim", "enabled")

    def is_extension_ok_for_version(self, extension, version):
        """Check if extension can be installed with this modo version."""
        if extension not in compatibility_matrix.EXTENSIONS_AVAILABILITY:
            return True
        version = utils.convert_version_to_int(version)
        min_version = compatibility_matrix.EXTENSIONS_AVAILABILITY[extension]
        min_version = utils.convert_version_to_int(min_version)
        return version >= min_version

    def _setup_venv(self):
        """Prepare a dedicated virtualenv."""
        python.setup_virtualenv(
            self.venv_path, sudo_user=self.user, python_version=3)
        packages = ["rrdtool"]
        version = self.config.get("modoboa", "version")
        if version == "latest":
            packages += ["modoboa"] + self.extensions
        else:
            matrix = compatibility_matrix.COMPATIBILITY_MATRIX[version]
            packages.append("modoboa=={}".format(version))
            for extension in list(self.extensions):
                if not self.is_extension_ok_for_version(extension, version):
                    self.extensions.remove(extension)
                    continue
                if extension in matrix:
                    req_version = matrix[extension]
                    req_version = req_version.replace("<", "\<")
                    req_version = req_version.replace(">", "\>")
                    packages.append("{}{}".format(extension, req_version))
                else:
                    packages.append(extension)
        # Temp fix for django-braces
        python.install_package(
            "django-braces", self.venv_path, upgrade=self.upgrade,
            sudo_user=self.user
        )
        if self.dbengine == "postgres":
            packages.append("psycopg2-binary\<2.9")
        else:
            packages.append("mysqlclient")
        if sys.version_info.major == 2 and sys.version_info.micro < 9:
            # Add extra packages to fix the SNI issue
            packages += ["pyOpenSSL"]
        # Temp fix for https://github.com/modoboa/modoboa/issues/2247
        packages.append("django-webpack-loader==0.7.0")
        python.install_packages(
            packages, self.venv_path,
            upgrade=self.upgrade,
            sudo_user=self.user,
            beta=self.config.getboolean("modoboa", "install_beta")
        )
        if self.devmode:
            # FIXME: use dev-requirements instead
            python.install_packages(
                ["django-bower", "django-debug-toolbar"], self.venv_path,
                upgrade=self.upgrade, sudo_user=self.user)

    def _deploy_instance(self):
        """Deploy Modoboa."""
        target = os.path.join(self.home_dir, "instance")
        if os.path.exists(target):
            condition = (
                not self.upgrade and
                not self.config.getboolean("general", "force")
            )
            if condition:
                utils.printcolor(
                    "Target directory for Modoboa deployment ({}) already "
                    "exists. If you choose to continue, it will be removed."
                    .format(target),
                    utils.YELLOW
                )
                answer = utils.user_input("Do you confirm? (Y/n) ")
                if answer.lower().startswith("n"):
                    return
            shutil.rmtree(target)

        prefix = ". {}; ".format(
            os.path.join(self.venv_path, "bin", "activate"))
        args = [
            "--collectstatic",
            "--timezone", self.config.get("modoboa", "timezone"),
            "--domain", self.config.get("general", "hostname"),
            "--extensions", " ".join(self.extensions),
            "--dont-install-extensions",
            "--dburl", "'default:{}://{}:{}@{}:{}/{}'".format(
                self.config.get("database", "engine"),
                self.dbuser, self.dbpasswd, self.dbhost, self.dbport,
                self.dbname
            )
        ]
        if self.devmode:
            args = ["--devel"] + args
        if self.amavis_enabled:
            args += [
                "'amavis:{}://{}:{}@{}:{}/{}'".format(
                    self.config.get("database", "engine"),
                    self.config.get("amavis", "dbuser"),
                    self.config.get("amavis", "dbpassword"),
                    self.dbhost,
                    self.dbport,
                    self.config.get("amavis", "dbname")
                )
            ]
        if self.upgrade and self.opendkim_enabled and self.dbengine == "postgres":
            # Drop dkim view to prevent an error during migration (2.0)
            self.backend._exec_query("DROP VIEW IF EXISTS dkim")
        code, output = utils.exec_cmd(
            "bash -c '{} modoboa-admin.py deploy instance {}'".format(
                prefix, " ".join(args)),
            sudo_user=self.user, cwd=self.home_dir)
        if code:
            raise utils.FatalError(output)
        if self.upgrade and self.opendkim_enabled and self.dbengine == "postgres":
            # Restore view previously deleted
            self.backend.load_sql_file(
                self.dbname, self.dbuser, self.dbpassword,
                self.get_file_path("dkim_view_{}.sql".format(self.dbengine))
            )
            self.backend.grant_right_on_table(
                self.dbname, "dkim", self.config.get("opendkim", "dbuser"),
                "SELECT"
            )

    def setup_database(self):
        """Additional config."""
        super(Modoboa, self).setup_database()
        if not self.amavis_enabled:
            return
        self.backend.grant_access(
            self.config.get("amavis", "dbname"), self.dbuser)

    def get_packages(self):
        """Include extra packages if needed."""
        packages = super(Modoboa, self).get_packages()
        condition = (
            package.backend.FORMAT == "rpm" and
            sys.version_info.major == 2 and
            sys.version_info.micro < 9)
        if condition:
            # Add extra packages to fix the SNI issue
            packages += ["openssl-devel"]
        return packages

    def get_config_files(self):
        """Return appropriate path."""
        config_files = super().get_config_files()
        if package.backend.FORMAT == "deb":
            path = "supervisor=/etc/supervisor/conf.d/policyd.conf"
        else:
            path = "supervisor=/etc/supervisord.d/policyd.ini"
        config_files.append(path)
        return config_files

    def get_template_context(self):
        """Additional variables."""
        context = super(Modoboa, self).get_template_context()
        extensions = self.config.get("modoboa", "extensions")
        extensions = extensions.split()
        context.update({
            "sudo_user": (
                "uwsgi" if package.backend.FORMAT == "rpm" else context["user"]
            ),
            "dovecot_mailboxes_owner": (
                self.config.get("dovecot", "mailboxes_owner")),
            "radicale_enabled": (
                "" if "modoboa-radicale" in extensions else "#"),
            "opendkim_user": self.config.get("opendkim", "user"),
        })
        return context

    def apply_settings(self):
        """Configure modoboa."""
        rrd_root_dir = os.path.join(self.home_dir, "rrdfiles")
        pdf_storage_dir = os.path.join(self.home_dir, "pdfcredentials")
        webmail_media_dir = os.path.join(
            self.instance_path, "media", "webmail")
        pw = pwd.getpwnam(self.user)
        for d in [rrd_root_dir, pdf_storage_dir, webmail_media_dir]:
            utils.mkdir(d, stat.S_IRWXU | stat.S_IRWXG, pw[2], pw[3])
        settings = {
            "admin": {
                "handle_mailboxes": True,
                "account_auto_removal": True
            },
            "modoboa_amavis": {
                "am_pdp_mode": "inet",
            },
            "maillog": {
                "rrd_rootdir": rrd_root_dir,
            },
            "modoboa_pdfcredentials": {
                "storage_dir": pdf_storage_dir
            },
            "modoboa_radicale": {
                "server_location": "https://{}/radicale/".format(
                    self.config.get("general", "hostname")),
                "rights_file_path": "{}/rights".format(
                    self.config.get("radicale", "config_dir"))
            }
        }
        for path in ["/var/log/maillog", "/var/log/mail.log"]:
            if os.path.exists(path):
                settings["maillog"]["logfile"] = path
        if self.config.getboolean("opendkim", "enabled"):
            settings["admin"]["dkim_keys_storage_dir"] = (
                self.config.get("opendkim", "keys_storage_dir"))
        settings = json.dumps(settings)
        query = (
            "UPDATE core_localconfig SET _parameters='{}'"
            .format(settings)
        )
        self.backend._exec_query(
            query, self.dbname, self.dbuser, self.dbpasswd)

    def post_run(self):
        """Additional tasks."""
        self._setup_venv()
        self._deploy_instance()
        if not self.upgrade:
            self.apply_settings()

        if 'centos' in utils.dist_name():
            supervisor = "supervisord"
            system.enable_and_start_service("redis")
        else:
            supervisor = "supervisor"
            system.enable_and_start_service("redis-server")
        # Restart supervisor
        system.enable_service(supervisor)
        utils.exec_cmd("service {} stop".format(supervisor))
        utils.exec_cmd("service {} start".format(supervisor))


text:
package com.fsck.k9.preferences;

import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.preference.DialogPreference;
import android.util.AttributeSet;

public class CheckBoxListPreference extends DialogPreference {

    private CharSequence[] mItems;

    private boolean[] mCheckedItems;

    /**
     * checkboxes state when the dialog is displayed
     */
    private boolean[] mPendingItems;

    /**
     * @param context
     * @param attrs
     * @param defStyle
     */
    public CheckBoxListPreference(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    /**
     * @param context
     * @param attrs
     */
    public CheckBoxListPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onPrepareDialogBuilder(final Builder builder) {
        mPendingItems = new boolean[mItems.length];

        System.arraycopy(mCheckedItems, 0, mPendingItems, 0, mCheckedItems.length);

        builder.setMultiChoiceItems(mItems, mPendingItems,
        new DialogInterface.OnMultiChoiceClickListener() {
            @Override
            public void onClick(final DialogInterface dialog, final int which,
            final boolean isChecked) {
                mPendingItems[which] = isChecked;
            }
        });
    }

    @Override
    protected void onDialogClosed(boolean positiveResult) {
        if (positiveResult) {
            System.arraycopy(mPendingItems, 0, mCheckedItems, 0, mPendingItems.length);
        }
        mPendingItems = null;
    }

    public void setItems(final CharSequence[] items) {
        mItems = items;
    }

    public void setCheckedItems(final boolean[] items) {
        mCheckedItems = items;
    }

    public boolean[] getCheckedItems() {
        return mCheckedItems;
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<!--
 | Licensed to the Apache Software Foundation (ASF) under one
 | or more contributor license agreements.  See the NOTICE file
 | distributed with this work for additional information
 | regarding copyright ownership.  The ASF licenses this file
 | to you under the Apache License, Version 2.0 (the
 | "License"); you may not use this file except in compliance
 | with the License.  You may obtain a copy of the License at
 |
 |   http://www.apache.org/licenses/LICENSE-2.0
 |
 | Unless required by applicable law or agreed to in writing,
 | software distributed under the License is distributed on an
 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 | KIND, either express or implied.  See the License for the
 | specific language governing permissions and limitations
 | under the License.
-->
<properties version="1.0">
  <entry key="com.ibaguice.memcached.keyprefix">test_</entry>
  <entry key="com.ibaguice.memcached.compression">true</entry>
</properties>


text:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateTableLogs extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('logs', function (Blueprint $table)
        {
            $table->increments('id');
            $table->integer('site_id')->default(1);
            $table->integer('cms_user_id');
            $table->string('logged_session_id')->nullable();
            $table->integer('level')->default(1);
            $table->string('action')->nullable();
            $table->string('controller')->nullable();
            $table->text('request_data')->nullable();

            $table->timestamps();

            $table->index(['site_id'], 'site_id');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('logs');
    }
}


text:
layout: post
title:  "Java图片处理"
date:   2017-04-21 9:45
categories: java
tags: imgage
author: Max
mathjax: true
---
* content
{:toc}

### java图片处理

#### java.awt.image.BufferedImage 类
提供一个供访问的图片缓冲区
##### 方法:
isAlphaPremultiplied()
```
isAlphaPremultiplied()
Returns whether or not the alpha has been premultiplied.
```
延伸阅读:[premultiplied alpha][premultiplied alpha]
返回图像是否进行过通道混合处理。

##### 属性:
TRANSLUCENT:透明度。 <br/>
TYPE_INT_RGB:'the color data must be adjusted to a non-premultiplied form and the alpha discarded'
整数像素,必须没有进行通道混合和加透明度
```java
//获取图片类型后再处理
final int imageType = srcImage.isAlphaPremultiplied() ? BufferedImage.TRANSLUCENT : BufferedImage.TYPE_INT_RGB;
```

#### javax.imageio.imageio 类
1、`public static BufferedImage read(InputStream input) throws IOException`
```java
public static BufferedImage read(InputStream input)
                          throws IOException
Returns a BufferedImage as the result of decoding a supplied InputStream with an ImageReader chosen automatically from among those currently registered. The InputStream is wrapped in an ImageInputStream. If no registered ImageReader claims to be able to read the resulting stream, null is returned.
The current cache settings from getUseCacheand getCacheDirectory will be used to control caching in the ImageInputStream that is created.

This method does not attempt to locate ImageReaders that can read directly from an InputStream; that may be accomplished using IIORegistry and ImageReaderSpi.

This method does not close the provided InputStream after the read operation has completed; it is the responsibility of the caller to close the stream, if desired.
```
从InputStream流中读取图片信息到BufferedImage,方法不会自己关闭输入流,需要调用者自己关闭

#### drawImage绘制图片
```java
//drawImage
public abstract boolean drawImage(Image img,
                                  int x,
                                  int y,
                                  int width,
                                  int height,
                                  Color bgcolor,
                                  ImageObserver observer)
```
绘制指定图像中已缩放到适合指定矩形内部的图像。
图像绘制在此图形上下文坐标空间的指定矩形内部,如果需要,则进行缩放。以指定的背景色绘制透明像素。此操作等同于用给定颜色填充指定图像宽度和高度的矩形,然后在其上绘制图像,但此操作效率更高。

#### javax.imageio 类
```java
public class IIOImage
extends Object
//注解
A simple container class to aggregate an image, a set of thumbnail (preview) images, and an object representing metadata associated with the image.
The image data may take the form of either a RenderedImage, or a Raster. Reader methods that return an IIOImage will always return a BufferedImage using the RenderedImage reference. Writer methods that accept an IIOImage will always accept a RenderedImage, and may optionally accept a Raster.

Exactly one of getRenderedImage and getRaster will return a non-null value. Subclasses are responsible for ensuring this behavior.
```
IIOImage对象,一个聚合图像的容器,一组缩略图或者图片的元素局表现。```new IIOImage(bufferedImage, null, null)```构建一个包含bufferedImage的IIOImage对象。

```java
public abstract class ImageWriter
extends Object
implements ImageTranscoder
//注解
An abstract superclass for encoding and writing images. This class must be subclassed by classes that write out images in the context of the Java Image I/O framework.
ImageWriter objects are normally instantiated by the service provider class for the specific format. Service provider classes are registered with the IIORegistry, which uses them for format recognition and presentation of available format readers and writers.
```
写图片的超类。通常实例为特定格式。

方法:
```java
public ImageWriteParam getDefaultWriteParam();
//返回默认的ImageWriteParam对象,用来规范ImageWriter的格式

public void setOutput(Object output);
//设置并写入对象(目的地),并且直到end不会关闭。

public abstract void write(IIOMetadata streamMetadata,
         IIOImage image,
         ImageWriteParam param)
                    throws IOException
//注解
Appends a complete image stream containing a single image and associated stream and image metadata and thumbnails to the output. Any necessary header information is included. If the output is an ImageOutputStream, its existing contents prior to the current seek position are not affected, and need not be readable or writable.
The output must have been set beforehand using the setOutput method.

Stream metadata may optionally be supplied; if it is null, default stream metadata will be used.

If canWriteRasters returns true, the IIOImage may contain a Raster source. Otherwise, it must contain a RenderedImage source.

The supplied thumbnails will be resized if needed, and any thumbnails in excess of the supported number will be ignored. If the format requires additional thumbnails that are not provided, the writer should generate them internally.

An ImageWriteParam may optionally be supplied to control the writing process. If param is null, a default write param will be used.

If the supplied ImageWriteParam contains optional setting values not supported by this writer (e.g. progressive encoding or any format-specific settings), they will be ignored.

Parameters:
streamMetadata - an IIOMetadata object representing stream metadata, or null to use default values.
image - an IIOImage object containing an image, thumbnails, and metadata to be written.
param - an ImageWriteParam, or null to use a default ImageWriteParam.
```
write方法:必须先调用setOutput方法,附加图像数据IIOImage到output流。ImageWriteParam是图像的压缩信息详细。

#### MemoryCacheImageOutputStream类
```java
public class MemoryCacheImageOutputStream
extends ImageOutputStreamImpl
//注解
An implementation of ImageOutputStream that writes its output to a regular OutputStream. A memory buffer is used to cache at least the data between the discard position and the current write position. The only constructor takes an OutputStream, so this class may not be used for read/modify/write operations. Reading can occur only on parts of the stream that have already been written to the cache and not yet flushed.
```
是ImageOutputStream的一个实现,用于写入一个普通的OutputStream。会至少缓存在写图像信息。写完后需要`ImageOutputStream.flush()`或者`ImageOutputStream.close()`。

[premultiplied alpha]:http://blog.csdn.net/mydreamremindme/article/details/50817294


text:
namespace net
{

log4cxx::LoggerPtr ConnectionListener::logger(log4cxx::Logger::getLogger("net.ConnectionListener"));

ConnectionListener::ConnectionListener(ConnectionManager *manager, const std::string &host, int port):
    Thread(std::string("CLSN_") + aqlib::Value(Application::getInstance().getNextId())),
    mManager(manager),
    mInstanceName("Clsn." + host + "." + aqlib::Value(port)),
    mStopRequested(false),
    mHost(host),
    mPort(port)
{
}

void ConnectionListener::requestStop()
{
    LOG4CXX_INFO(logger, mInstanceName << " requesting stop");
    aqlib::Lock lock(mLock);
    mStopRequested = true;
    mLock.notify();

    // Wake up processor thread blocked in I/O operation
    try
    {
        mSocket.shutdown();
    }
    catch (std::exception &ex)
    {
        LOG4CXX_WARN(logger, mInstanceName << ": " << ex.what());
    }
}

void ConnectionListener::run()
{
    LOG4CXX_INFO(logger, mInstanceName << " running");

    while (!isStopRequested())
    {
        try
        {
            process();
        }
        catch (std::exception &ex)
        {
            if (!isStopRequested())
            {
                LOG4CXX_ERROR(logger, mInstanceName << ": " << ex.what());
                break;
            }
        }
    }

    LOG4CXX_INFO(logger, mInstanceName << " stopped");
}

bool ConnectionListener::isStopRequested()
{
    aqlib::Lock lock(mLock);
    return mStopRequested;
}

void ConnectionListener::process()
{
    LOG4CXX_INFO(logger, mInstanceName << " listening");
    SocketPtr socket = mSocket.accept();
    LOG4CXX_INFO(logger, mInstanceName << " accepted: " + aqlib::Value(socket->getHandle()));

    ConnectionPtr connection;
    try
    {
        // If moving the connection stuff to a library,
        // the Session should be created by the application
        // and hold the objects necessary for communicating with the client.
        connection = ConnectionPtr(new Session(mManager, socket));
    }
    catch (std::exception &ex)
    {
        LOG4CXX_ERROR(logger, mInstanceName << " failed creating session for: " << aqlib::Value(socket->getHandle()));
        return;
    }

    mManager->add(connection);
}

void ConnectionListener::init()
{
    mSocket.listen(mHost, mPort);
    start();
}

void ConnectionListener::cleanup()
{
    requestStop();
    join();
}

} // namespace net


text:
package com.tale.androidcore.compat;

/**
 * Created by TALE on 12/17/2014.
 */
public class Platform {
    public static boolean SUPPORTS_GINGERBREAD = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD;
    public static boolean SUPPORTS_HONEYCOMB = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB;
    public static boolean SUPPORTS_FROYO = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.FROYO;
    public static boolean SUPPORTS_ECLAIR = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.ECLAIR;
}


text:
export declare class Tree<T> {
    constructor(root: TreeNode<T>);
    readonly root: T;
    parent(t: T): T;
    children(t: T): T[];
    firstChild(t: T): T;
    siblings(t: T): T[];
    pathFromRoot(t: T): T[];
    contains(tree: Tree<T>): boolean;
}
export declare class TreeNode<T> {
    value: T;
    children: TreeNode<T>[];
    constructor(value: T, children: TreeNode<T>[]);
    toString(): string;
}


text:
<!DOCTYPE animal [
<!ELEMENT animal ANY>
<?ϗ an illegal char #x3d7
 in PITarget ?>
]>
<animal/>


text:
[Back To Navigation Tree](https://wesleywh.github.io/GameDevRepo/docs/navigation.html)
# RagdollHelper

## Description:
File has no description.

## Variables:
List of variables that you can modify in the inspector.

|Access|Name|Type|Default Value|Description|
|---|---|---|---|---|
|public|that can be set to toggle between ragdolled and animated character|property|no default|No description.|
|public|ragdolled|bool|no default|No description.|
|public|ragdollToMecanimBlendTime|float|0.5f|No description.|
|public|transform|Transform|no default|No description.|
|public|storedPosition|Vector3|no default|No description.|
|public|storedRotation|Quaternion|no default|No description.|


text:
require 'rubygems' # This line not needed for ruby > 1.8
require 'twilio-ruby'

# Get your Account Sid and Auth Token from twilio.com/user/account
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Twilio::REST::Client.new account_sid, auth_token

numbers = client.account
                .available_phone_numbers.get('US')
                .toll_free.list(contains: 'STORM')

# Purchase the number
number = numbers[0].phone_number
client.account.incoming_phone_numbers.create(phone_number: number)


text:
Bootstrap

Bootstrap es un framework HTML, CSS, Javascript para crear aplicaciones web. Incluye widgets reutilizables, buenas prácticas y está orientado a responsive web design.


text:
<!DOCTYPE html>

    Placeholder image size set. When replacement happends, there is no jump in the page.
    The placeholder image has a transparent background to let the background image spinner show.

    Placeholder image size set. When replacement happends, there is no jump in the page.

    Placeholder image size set. Retina image available. When replacement happends, there is no jump in the page.

    Placeholder image size set. When replacement happends, there is no jump in the page.

    No size set. The image takes the size of the place holder. Not recommended,
    as when the final image is loaded, there will be a reflow of the content.

    No src in img tag. This is invalid HTML. Should not be used.
    An empty src (src='') means "url of the current page" and has
    inconsistent behaviour between browsers.

    Using an animated spinner to as placeholder.

    Using an animated spinner with a set size.


text:
import React = require('react')
import { EditorPluginBuilder, InAddtionAccepts } from '../interface.plugin'
import { EditorState, ContentBlock, ContentState } from 'draft-js'
import Prism = require('prismjs')
import PrismDecorator = require('draft-js-prism')
import './style.less'
import './laguage'

interface PluginConfig { }
interface Method { }
export type codeHighLightPlugin = InAddtionAccepts & Method

const WS = /\s+/g
const BACK_SLASH = /\//g
const mapFileExtensionToLanguage = (name: string) => FILE_EXTENSION_MAP[name] ? FILE_EXTENSION_MAP[name] : name
export const FILE_EXTENSION_MAP = {
  js: 'javascript',
  'c++': 'cpp',
  ts: 'typescript',
  py: 'python',
  rb: 'ruby'
}

export const codeHighLightPlugin: EditorPluginBuilder<PluginConfig, Method> = (...args) => {

  let currentSyntax

  // "//${type}"           it'sworkring
  // "//   ${type}   "     it'sworkring
  // "/*${type}*/"         not working
  // support file extension name. ie: js=>javascript , ts=>typescript
  function getSyntax(block: ContentBlock) {
    const text = block.getText().replace(WS, '')

    if (!text || !text.startsWith('//')) {
      return currentSyntax
    }

    let languageType = text.replace(BACK_SLASH, '')
    languageType = mapFileExtensionToLanguage(languageType)
    const syntaxDefinition = Prism.languages[languageType]

    if (typeof syntaxDefinition === 'object') {
      currentSyntax = languageType
    }

    if (__DEV__) {
      /* tslint:disable */
      console.log(text, languageType, syntaxDefinition, currentSyntax)
      /* tslint:enable */
    }
    return currentSyntax
  }

  function render({ type, children }) {
    return (
      <span className={ `prism-token token ${type}` }>{ children }
    )
  }

  return {
    decorators: [new PrismDecorator({ prism: Prism, getSyntax, render })],
  }
}

export default codeHighLightPlugin


text:
var MaxSimple = natives.ImportNow("MaxSimple");
var MinSimple = natives.ImportNow("MinSimple");

function checkEvaluations(target) {
  var evaluations = 0;
  var observedNumber = {
    valueOf: function() {
      evaluations++;
      return 0;
    }
  };
  target(observedNumber, observedNumber);
  return evaluations;
}

assertEquals(1, MaxSimple(-1, 1));
assertEquals(2, checkEvaluations(MaxSimple));

assertEquals(-1, MinSimple(-1, 1));
assertEquals(2, checkEvaluations(MinSimple));


text:
import React from 'react'
import { IndexLink, Link } from 'react-router'
import PropTypes from 'prop-types'
import { Row, Col } from 'react-bootstrap'
import FontAwesome from 'react-fontawesome'
import './Header.scss'

import MainNav from '../NavLayout/MainNav'
import HeaderNav from '../NavLayout/HeaderNav'

export const Header = ({ children }) => (

    <Row>
      <Col xs={4} md={4} id='col-1'>

(888) 0-MARIO

      </Col>
      <Col xs={4} md={4} id='col-2' />
      <Col xs={4} md={4} id='col-3'>
        <FontAwesome
          className='fa fa-lock' />
        <FontAwesome
          className='fa fa-facebook' />
        <FontAwesome
          className='fa fa-instagram' />
        <FontAwesome
          className='fa fa-twitter' />
      </Col>
    </Row>
    <Row id='nav-row'>
      <MainNav />
      {/*<HeaderNav /> */}
    </Row>

)

Header.propTypes = {
  children: PropTypes.node,
}

export default Header