text:
package org.apache.ignite.internal.processors.query.h2.opt.join;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import javax.cache.CacheException;

import org.apache.ignite.internal.processors.query.h2.opt.GridH2Table;
import org.apache.ignite.internal.processors.query.h2.sql.GridSqlQueryParser;
import org.apache.ignite.internal.processors.query.h2.sql.SplitterContext;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.internal.util.typedef.internal.SB;
import org.h2.command.dml.Query;
import org.h2.command.dml.Select;
import org.h2.command.dml.SelectUnion;
import org.h2.engine.Session;
import org.h2.expression.Comparison;
import org.h2.expression.Expression;
import org.h2.expression.ExpressionColumn;
import org.h2.index.IndexCondition;
import org.h2.index.ViewIndex;
import org.h2.table.Column;
import org.h2.table.IndexColumn;
import org.h2.table.SubQueryInfo;
import org.h2.table.Table;
import org.h2.table.TableFilter;
import org.h2.table.TableView;

/**
 * Collocation model for a query.
 */
public final class CollocationModel {
    /** Empty filter array. */
    private static final TableFilter[] EMPTY_FILTERS = new TableFilter[0];

    /** */
    private final CollocationModel upper;

    /** */
    private final int filter;

    /** */
    private final boolean view;

    /** */
    private CollocationModelMultiplier multiplier;

    /** */
    private CollocationModelType type;

    /** */
    private CollocationModel[] children;

    /** */
    private TableFilter[] childFilters;

    /** */
    private List<CollocationModel> unions;

    /** */
    private Select select;

    /** */
    private final boolean validate;

    /**
     * @param upper Upper.
     * @param filter Filter.
     * @param view This model will be a subquery (or top level query) and must contain child filters.
     * @param validate Query validation flag.
     */
    private CollocationModel(CollocationModel upper, int filter, boolean view, boolean validate) {
        this.upper = upper;
        this.filter = filter;
        this.view = view;
        this.validate = validate;
    }

    /**
     * @return Table filter for this collocation model.
     */
    private TableFilter filter() {
        return upper == null ? null : upper.childFilters[filter];
    }

    /** {@inheritDoc} */
    @Override public String toString() {
        calculate();

        SB b = new SB();

        for (int lvl = 0; lvl < 20; lvl++) {
            if (!toString(b, lvl))
                break;

            b.a('\n');
        }

        return b.toString();
    }

    /**
     * @param b String builder.
     * @param lvl Depth level.
     */
    private boolean toString(SB b, int lvl) {
        boolean res = false;

        if (lvl == 0) {
            TableFilter f = filter();
            String tblAlias = f == null ? "^" : f.getTableAlias();

            b.a("[tbl=").a(tblAlias).a(", type=").a(type).a(", mul=").a(multiplier).a("]");

            res = true;
        }
        else if (childFilters != null) {
            assert lvl > 0;

            lvl--;

            for (int i = 0; i < childFilters.length; i++) {
                if (lvl == 0)
                    b.a(" | ");

                res |= child(i, true).toString(b, lvl);
            }

            if (lvl == 0)
                b.a(" | ");
        }

        return res;
    }

    /**
     * @param upper Upper.
     * @param filter Filter.
     * @param unions Unions.
     * @param view This model will be a subquery (or top level query) and must contain child filters.
     * @param validate Query validation flag.
     * @return Created child collocation model.
     */
    private static CollocationModel createChildModel(CollocationModel upper,
        int filter,
        List<CollocationModel> unions,
        boolean view,
        boolean validate) {
        CollocationModel child = new CollocationModel(upper, filter, view, validate);

        if (unions != null) {
            // Bind created child to unions.
            assert upper == null || upper.child(filter, false) != null || unions.isEmpty();

            if (upper != null && unions.isEmpty()) {
                assert upper.child(filter, false) == null;

                upper.children[filter] = child;
            }

            unions.add(child);

            child.unions = unions;
        }
        else if (upper != null) {
            // Bind created child to upper model.
            assert upper.child(filter, false) == null;

            upper.children[filter] = child;
        }

        return child;
    }

    /**
     * @param childFilters New child filters.
     * @return {@code true} If child filters were updated.
     */
    private boolean childFilters(TableFilter[] childFilters) {
        assert childFilters != null;
        assert view;

        Select select = childFilters[0].getSelect();

        assert this.select == null || this.select == select;

        if (this.select == null) {
            this.select = select;

            assert this.childFilters == null;
        }
        else if (Arrays.equals(this.childFilters, childFilters))
            return false;

        if (this.childFilters == null || this.childFilters.length != childFilters.length) {
            // We have to clone because H2 reuses array and reorders elements.
            this.childFilters = childFilters.clone();

            children = new CollocationModel[childFilters.length];
        }
        else {
            // We have to copy because H2 reuses array and reorders elements.
            System.arraycopy(childFilters, 0, this.childFilters, 0, childFilters.length);

            Arrays.fill(children, null);
        }

        // Reset results.
        type = null;
        multiplier = null;

        return true;
    }

    /**
     * Do the needed calculations.
     */
    @SuppressWarnings("ConstantConditions")
    private void calculate() {
        if (type != null)
            return;

        if (view) { // We are at (sub-)query model.
            assert childFilters != null;

            boolean collocated = true;
            boolean partitioned = false;
            CollocationModelMultiplier maxMultiplier = CollocationModelMultiplier.COLLOCATED;

            for (int i = 0; i < childFilters.length; i++) {
                CollocationModel child = child(i, true);

                CollocationModelType t = child.type(true);

                if (child.multiplier == CollocationModelMultiplier.REPLICATED_NOT_LAST)
                    maxMultiplier = child.multiplier;

                if (t.isPartitioned()) {
                    partitioned = true;

                    if (!t.isCollocated()) {
                        collocated = false;

                        CollocationModelMultiplier m = child.multiplier(true);

                        if (m.multiplier() > maxMultiplier.multiplier()) {
                            maxMultiplier = m;

                            if (maxMultiplier == CollocationModelMultiplier.REPLICATED_NOT_LAST)
                                break;
                        }
                    }
                }
            }

            type = CollocationModelType.of(partitioned, collocated);
            multiplier = maxMultiplier;
        }
        else {
            assert upper != null;
            assert childFilters == null;

            // We are at table instance.
            Table tbl = filter().getTable();

            // Only partitioned tables will do distributed joins.
            if (!(tbl instanceof GridH2Table) || !((GridH2Table)tbl).isPartitioned()) {
                type = CollocationModelType.REPLICATED;
                multiplier = CollocationModelMultiplier.COLLOCATED;

                return;
            }

            // If we are the first partitioned table in a join, then we are "base" for all the rest partitioned tables
            // which will need to get remote result (if there is no affinity condition). Since this query is broadcasted
            // to all the affinity nodes the "base" does not need to get remote results.
            if (!upper.isPartitionedTableBeforeExists(filter)) {
                type = CollocationModelType.PARTITIONED_COLLOCATED;
                multiplier = CollocationModelMultiplier.COLLOCATED;
            }
            else {
                // It is enough to make sure that our previous join by affinity key is collocated, then we are
                // collocated. If we at least have affinity key condition, then we do unicast which is cheaper.
                switch (upper.joinedWithCollocated(filter)) {
                    case COLLOCATED_JOIN:
                        type = CollocationModelType.PARTITIONED_COLLOCATED;
                        multiplier = CollocationModelMultiplier.COLLOCATED;

                        break;

                    case HAS_AFFINITY_CONDITION:
                        type = CollocationModelType.PARTITIONED_NOT_COLLOCATED;
                        multiplier = CollocationModelMultiplier.UNICAST;

                        break;

                    case NONE:
                        type = CollocationModelType.PARTITIONED_NOT_COLLOCATED;
                        multiplier = CollocationModelMultiplier.BROADCAST;

                        break;

                    default:
                        throw new IllegalStateException();
                }
            }

            if (upper.isPreviousTableReplicated(filter))
                multiplier = CollocationModelMultiplier.REPLICATED_NOT_LAST;
        }
    }

    /**
     * Check whether at least one PARTITIONED table is located before current table.
     *
     * @param filterIdx Current filter index.
     * @return {@code true} If PARTITIONED table exists.
     */
    private boolean isPartitionedTableBeforeExists(int filterIdx) {
        for (int idx = 0; idx < filterIdx; idx++) {
            CollocationModel child = child(idx, true);

            // The c can be null if it is not a GridH2Table and not a sub-query,
            // it is a some kind of function table or anything else that considered replicated.
            if (child != null && child.type(true).isPartitioned())
                return true;
        }

        // We have to search globally in upper queries as well.
        return upper != null && upper.isPartitionedTableBeforeExists(filter);
    }

    /**
     * Check if previous table in the sequence is REPLICATED.
     *
     * @param filterIdx Current filter index.
     * @return {@code true} If previous table is REPLICATED.
     */
    private boolean isPreviousTableReplicated(int filterIdx) {
        // We are at the first table, nothing exists before it
        if (filterIdx == 0)
            return false;

        CollocationModel child = child(filterIdx - 1, true);

        if (child != null && child.type(true) == CollocationModelType.REPLICATED)
            return true;

        return upper != null && upper.isPreviousTableReplicated(filter);
    }

    /**
     * @param f Filter.
     * @return Affinity join type.
     */
    @SuppressWarnings("ForLoopReplaceableByForEach")
    private CollocationModelAffinity joinedWithCollocated(int f) {
        TableFilter tf = childFilters[f];

        GridH2Table tbl = (GridH2Table)tf.getTable();

        if (validate) {
            if (tbl.isCustomAffinityMapper())
                throw customAffinityError(tbl.cacheName());

            if (F.isEmpty(tf.getIndexConditions())) {
                throw new CacheException("Failed to prepare distributed join query: " +
                    "join condition does not use index [joinedCache=" + tbl.cacheName() +
                    ", plan=" + tf.getSelect().getPlanSQL() + ']');
            }
        }

        IndexColumn affCol = tbl.getAffinityKeyColumn();

        boolean affKeyCondFound = false;

        if (affCol != null) {
            ArrayList<IndexCondition> idxConditions = tf.getIndexConditions();

            int affColId = affCol.column.getColumnId();

            for (int i = 0; i < idxConditions.size(); i++) {
                IndexCondition c = idxConditions.get(i);
                int colId = c.getColumn().getColumnId();
                int cmpType = c.getCompareType();

                if ((cmpType == Comparison.EQUAL || cmpType == Comparison.EQUAL_NULL_SAFE) &&
                    (colId == affColId || tbl.rowDescriptor().isKeyColumn(colId)) && c.isEvaluatable()) {
                    affKeyCondFound = true;

                    Expression exp = c.getExpression();
                    exp = exp.getNonAliasExpression();

                    if (exp instanceof ExpressionColumn) {
                        ExpressionColumn expCol = (ExpressionColumn)exp;

                        // This is one of our previous joins.
                        TableFilter prevJoin = expCol.getTableFilter();

                        if (prevJoin != null) {
                            CollocationModel cm = child(indexOf(prevJoin), true);

                            // If the previous joined model is a subquery (view), we can not be sure that
                            // the found affinity column is the needed one, since we can select multiple
                            // different affinity columns from different tables.
                            if (cm != null && !cm.view) {
                                CollocationModelType t = cm.type(true);

                                if (t.isPartitioned() && t.isCollocated() && isAffinityColumn(prevJoin, expCol, validate))
                                    return CollocationModelAffinity.COLLOCATED_JOIN;
                            }
                        }
                    }
                }
            }
        }

        return affKeyCondFound ? CollocationModelAffinity.HAS_AFFINITY_CONDITION : CollocationModelAffinity.NONE;
    }

    /**
     * @param f Table filter.
     * @return Index.
     */
    private int indexOf(TableFilter f) {
        for (int i = 0; i < childFilters.length; i++) {
            if (childFilters[i] == f)
                return i;
        }

        throw new IllegalStateException();
    }

    /**
     * @param f Table filter.
     * @param expCol Expression column.
     * @param validate Query validation flag.
     * @return {@code true} It it is an affinity column.
     */
    @SuppressWarnings("IfMayBeConditional")
    private static boolean isAffinityColumn(TableFilter f, ExpressionColumn expCol, boolean validate) {
        Column col = expCol.getColumn();

        if (col == null)
            return false;

        Table t = col.getTable();

        if (t.isView()) {
            Query qry;

            if (f.getIndex() != null)
                qry = getSubQuery(f);
            else
                qry = GridSqlQueryParser.VIEW_QUERY.get((TableView)t);

            return isAffinityColumn(qry, expCol, validate);
        }

        if (t instanceof GridH2Table) {
            GridH2Table t0 = (GridH2Table)t;

            if (validate && t0.isCustomAffinityMapper())
                throw customAffinityError((t0).cacheName());

            IndexColumn affCol = t0.getAffinityKeyColumn();

            return affCol != null && col.getColumnId() == affCol.column.getColumnId();
        }

        return false;
    }

    /**
     * @param qry Query.
     * @param expCol Expression column.
     * @param validate Query validation flag.
     * @return {@code true} It it is an affinity column.
     */
    private static boolean isAffinityColumn(Query qry, ExpressionColumn expCol, boolean validate) {
        if (qry.isUnion()) {
            SelectUnion union = (SelectUnion)qry;

            return isAffinityColumn(union.getLeft(), expCol, validate) && isAffinityColumn(union.getRight(), expCol, validate);
        }

        Expression exp = qry.getExpressions().get(expCol.getColumn().getColumnId()).getNonAliasExpression();

        if (exp instanceof ExpressionColumn) {
            expCol = (ExpressionColumn)exp;

            return isAffinityColumn(expCol.getTableFilter(), expCol, validate);
        }

        return false;
    }

    /**
     * @param withUnion With respect to union.
     * @return Multiplier.
     */
    @SuppressWarnings("ForLoopReplaceableByForEach")
    private CollocationModelMultiplier multiplier(boolean withUnion) {
        calculate();

        assert multiplier != null;

        if (withUnion && unions != null) {
            CollocationModelMultiplier maxMultiplier = null;

            for (int i = 0; i < unions.size(); i++) {
                CollocationModelMultiplier m = unions.get(i).multiplier(false);

                if (maxMultiplier == null || m.multiplier() > maxMultiplier.multiplier())
                    maxMultiplier = m;
            }

            assert maxMultiplier != null;

            return maxMultiplier;
        }

        return multiplier;
    }

    /**
     * @param withUnion With respect to union.
     * @return Type.
     */
    private CollocationModelType type(boolean withUnion) {
        calculate();

        assert type != null;

        if (withUnion && unions != null) {
            CollocationModelType left = unions.get(0).type(false);

            for (int i = 1; i < unions.size(); i++) {
                CollocationModelType right = unions.get(i).type(false);

                if (!left.isCollocated() || !right.isCollocated()) {
                    left = CollocationModelType.PARTITIONED_NOT_COLLOCATED;

                    break;
                }
                else if (!left.isPartitioned() && !right.isPartitioned())
                    left = CollocationModelType.REPLICATED;
                else
                    left = CollocationModelType.PARTITIONED_COLLOCATED;
            }

            return left;
        }

        return type;
    }

    /**
     * @param i Index.
     * @param create Create child if needed.
     * @return Child collocation.
     */
    @SuppressWarnings("IfMayBeConditional")
    private CollocationModel child(int i, boolean create) {
        CollocationModel child = children[i];

        if (child == null && create) {
            TableFilter f = childFilters[i];

            if (f.getTable().isView()) {
                if (f.getIndex() == null) {
                    // If we don't have view index yet, then we just creating empty model and it must be filled later.
                    child = createChildModel(this, i, null, true, validate);
                }
                else
                    child = buildCollocationModel(this, i, getSubQuery(f), null, validate);
            }
            else
                child = createChildModel(this, i, null, false, validate);

            assert child != null;
            assert children[i] == child;
        }

        return child;
    }

    /**
     * @param f Table filter.
     * @return Sub-query.
     */
    private static Query getSubQuery(TableFilter f) {
        return ((ViewIndex)f.getIndex()).getQuery();
    }

    /**
     * @return Unions list.
     */
    private List<CollocationModel> getOrCreateUnions() {
        if (unions == null) {
            unions = new ArrayList<>(4);

            unions.add(this);
        }

        return unions;
    }

    /**
     * Get distributed multiplier for the given sequence of tables.
     *
     * @param ses Session.
     * @param filters Filters.
     * @param filter Filter index.
     * @return Multiplier.
     */
    public static CollocationModelMultiplier distributedMultiplier(Session ses, TableFilter[] filters, int filter) {
        // Notice that we check for isJoinBatchEnabled, because we can do multiple different
        // optimization passes on PREPARE stage.
        // Query expressions can not be distributed as well.
        SplitterContext ctx = SplitterContext.get();

        if (!ctx.distributedJoins() || !ses.isJoinBatchEnabled() || ses.isPreparingQueryExpression())
            return CollocationModelMultiplier.COLLOCATED;

        assert filters != null;

        clearViewIndexCache(ses);

        CollocationModel model = buildCollocationModel(ctx, ses.getSubQueryInfo(), filters, filter, false);

        return model.multiplier(false);
    }

    /**
     * @param ctx Splitter context.
     * @param info Sub-query info.
     * @param filters Filters.
     * @param filter Filter.
     * @param validate Query validation flag.
     * @return Collocation.
     */
    private static CollocationModel buildCollocationModel(
        SplitterContext ctx,
        SubQueryInfo info,
        TableFilter[] filters,
        int filter,
        boolean validate
    ) {
        CollocationModel cm;

        if (info != null) {
            // Go up until we reach the root query.
            cm = buildCollocationModel(ctx, info.getUpper(), info.getFilters(), info.getFilter(), validate);
        }
        else {
            // We are at the root query.
            cm = ctx.collocationModel();

            if (cm == null) {
                cm = createChildModel(null, -1, null, true, validate);

                ctx.collocationModel(cm);
            }
        }

        if (filters == null)
            return cm;

        assert cm.view;

        Select select = filters[0].getSelect();

        // Handle union. We have to rely on fact that select will be the same on uppermost select.
        // For sub-queries we will drop collocation models, so that they will be recalculated anyways.
        if (cm.select != null && cm.select != select) {
            List<CollocationModel> unions = cm.getOrCreateUnions();

            // Try to find this select in existing unions.
            // Start with 1 because at 0 it always will be c.
            for (int i = 1; i < unions.size(); i++) {
                CollocationModel u = unions.get(i);

                if (u.select == select) {
                    cm = u;

                    break;
                }
            }

            // Nothing was found, need to create new child in union.
            if (cm.select != select)
                cm = createChildModel(cm.upper, cm.filter, unions, true, validate);
        }

        cm.childFilters(filters);

        return cm.child(filter, true);
    }

    /**
     * @param qry Query.
     * @return {@code true} If the query is collocated.
     */
    public static boolean isCollocated(Query qry) {
        CollocationModel mdl = buildCollocationModel(null, -1, qry, null, true);

        CollocationModelType type = mdl.type(true);

        if (!type.isCollocated() && mdl.multiplier == CollocationModelMultiplier.REPLICATED_NOT_LAST)
            throw new CacheException("Failed to execute query: for distributed join " +
                "all REPLICATED caches must be at the end of the joined tables list.");

        return type.isCollocated();
    }

    /**
     * @param upper Upper.
     * @param filter Filter.
     * @param qry Query.
     * @param unions Unions.
     * @param validate Query validation flag.
     * @return Built model.
     */
    private static CollocationModel buildCollocationModel(
        CollocationModel upper,
        int filter,
        Query qry,
        List<CollocationModel> unions,
        boolean validate
    ) {
        if (qry.isUnion()) {
            if (unions == null)
                unions = new ArrayList<>();

            SelectUnion union = (SelectUnion)qry;

            CollocationModel left = buildCollocationModel(upper, filter, union.getLeft(), unions, validate);
            CollocationModel right = buildCollocationModel(upper, filter, union.getRight(), unions, validate);

            assert left != null;
            assert right != null;

            return upper != null ? upper : left;
        }

        Select select = (Select)qry;

        List<TableFilter> list = new ArrayList<>();

        for (TableFilter f = select.getTopTableFilter(); f != null; f = f.getJoin())
            list.add(f);

        TableFilter[] filters = list.toArray(EMPTY_FILTERS);

        CollocationModel cm = createChildModel(upper, filter, unions, true, validate);

        cm.childFilters(filters);

        for (int i = 0; i < filters.length; i++) {
            TableFilter f = filters[i];

            if (f.getTable().isView())
                buildCollocationModel(cm, i, getSubQuery(f), null, validate);
            else if (f.getTable() instanceof GridH2Table)
                createChildModel(cm, i, null, false, validate);
        }

        return upper != null ? upper : cm;
    }

    /**
     * @param cacheName Cache name.
     * @return Error.
     */
    private static CacheException customAffinityError(String cacheName) {
        return new CacheException("Failed to prepare distributed join query: can not use distributed joins for cache " +
            "with custom AffinityKeyMapper configured. " +
            "Please use AffinityKeyMapped annotation instead [cache=" + cacheName + ']');
    }

    /**
     * @param ses Session.
     */
    private static void clearViewIndexCache(Session ses) {
        // We have to clear this cache because normally sub-query plan cost does not depend on anything
        // other than index condition masks and sort order, but in our case it can depend on order
        // of previous table filters.
        Map<Object,ViewIndex> viewIdxCache = ses.getViewIndexCache(true);

        if (!viewIdxCache.isEmpty())
            viewIdxCache.clear();
    }
}


text:
<?php
namespace Importer;

class WrongHeaderException extends \LogicException
{

}

redpajama_set_name: RedPajamaGithub


text:
package ca.corefacility.bioinformatics.irida.pipeline.upload.galaxy;

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

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import java.util.Optional;

import ca.corefacility.bioinformatics.irida.exceptions.WorkflowException;
import ca.corefacility.bioinformatics.irida.exceptions.galaxy.DeleteGalaxyObjectFailedException;
import ca.corefacility.bioinformatics.irida.exceptions.galaxy.WorkflowUploadException;
import ca.corefacility.bioinformatics.irida.model.workflow.execution.galaxy.WorkflowInputsGalaxy;

import com.github.jmchilton.blend4j.galaxy.WorkflowsClient;
import com.github.jmchilton.blend4j.galaxy.beans.Workflow;
import com.github.jmchilton.blend4j.galaxy.beans.WorkflowDetails;
import com.github.jmchilton.blend4j.galaxy.beans.WorkflowInputDefinition;
import com.github.jmchilton.blend4j.galaxy.beans.WorkflowInvocationOutputs;
import com.sun.jersey.api.client.ClientResponse;

/**
 * Handles operating with workflows in Galaxy.
 *
 */
public class GalaxyWorkflowService {
	private WorkflowsClient workflowsClient;

	private final Charset workflowCharset;

	/**
	 * Constructs a new GalaxyWorkflowSubmitter with the given information.
	 * @param workflowsClient  The WorkflowsClient used to connect to Galaxy workflows.
	 * @param workflowCharset  The {@link Charset} to use for reading in workflows from files.
	 */
	public GalaxyWorkflowService(
			WorkflowsClient workflowsClient, Charset workflowCharset) {
		checkNotNull(workflowsClient, "workflowsClient is null");
		checkNotNull(workflowCharset, "workflowCharset is null");

		this.workflowsClient = workflowsClient;
		this.workflowCharset = workflowCharset;
	}

	/**
	 * Uploads a workflow definined in the given file to Galaxy.
	 * @param workflowFile  The file to upload.
	 * @return  The id of the workflow in Galaxy.
	 * @throws IOException If there was an issue reading the file.
	 * @throws WorkflowUploadException If there was an issue uploading the workflow to Galaxy.
	 */
	public String uploadGalaxyWorkflow(Path workflowFile) throws IOException, WorkflowUploadException {
		checkNotNull(workflowFile, "workflowFile is null");

		byte[] fileBytes = Files.readAllBytes(workflowFile);
		String workflowString = new String(fileBytes, workflowCharset);

		try {
			Workflow workflow = workflowsClient.importWorkflow(workflowString, false);
			return workflow.getId();
		} catch (RuntimeException e) {
			throw new WorkflowUploadException("Could not upload workflow from " + workflowFile,e);
		}
	}

	/**
	 * Given a WorkflowDetails an a workflowInputLabel find the corresponding id for this input.
	 * @param workflowDetails  The WorkflowDetails describing the workflow.
	 * @param workflowInputLabel  The label defining the input to search for.
	 * @return  The id of the input corresponding to the passed label.
	 * @throws WorkflowException  If no such input id could be found.
	 */
	public String getWorkflowInputId(WorkflowDetails workflowDetails, String workflowInputLabel) throws WorkflowException {
		checkNotNull(workflowDetails, "workflowDetails is null");
		checkNotNull(workflowInputLabel, "workflowInputLabel is null");

		Map<String, WorkflowInputDefinition> workflowInputMap = workflowDetails.getInputs();

		Optional<Map.Entry<String, WorkflowInputDefinition>> e =
				workflowInputMap.entrySet().stream().filter((entry) ->
				workflowInputLabel.equals(entry.getValue().getLabel())).findFirst();

		if (e.isPresent()) {
			return e.get().getKey();
		} else {
			throw new WorkflowException("Cannot find workflowInputId for input label " + workflowInputLabel);
		}
	}

	/**
	 * Gets details about a given workflow.
	 *
	 * @param workflowId
	 *            The id of the workflow.
	 * @return A details object for this workflow.
	 * @throws WorkflowException
	 *             If there was an issue getting the details of the workflow.
	 */
	public WorkflowDetails getWorkflowDetails(String workflowId) throws WorkflowException {
		checkNotNull(workflowId, "workflowId is null");

		try {
			return workflowsClient.showWorkflow(workflowId);
		} catch (RuntimeException e) {
			throw new WorkflowException(e);
		}
	}

	/**
	 * Attempts to run the workflow definined by the given WorkflowInputs object.
	 * @param inputs  The inputs to the workflow.
	 * @return  A WorkflowOutputs object with information on output files in the workflow.
	 * @throws WorkflowException  If there was an issue running the workflow.
	 */
	public WorkflowInvocationOutputs runWorkflow(WorkflowInputsGalaxy inputs) throws WorkflowException {
		checkNotNull(inputs, "inputs is null");

		try {
			return workflowsClient.invokeWorkflow(inputs.getInputsObject());
		} catch (RuntimeException e) {
			throw new WorkflowException(e);
		}
	}

	/**
	 * Deletes a workflow with the given id.
	 *
	 * @param workflowId
	 *            The id of the workflow to delete.
	 * @throws DeleteGalaxyObjectFailedException
	 *             If there was an error while deleting the workflow.
	 */
	public void deleteWorkflow(String workflowId) throws DeleteGalaxyObjectFailedException {
		try {
			ClientResponse response = workflowsClient.deleteWorkflowRequest(workflowId);
			if (ClientResponse.Status.OK.getStatusCode() != response.getStatusInfo().getStatusCode()) {
				throw new DeleteGalaxyObjectFailedException("Could not workflow with id " + workflowId + ", status="
						+ response.getStatusInfo() + ", content=" + response.getEntity(String.class));
			}
		} catch (RuntimeException e) {
			throw new DeleteGalaxyObjectFailedException("Error while deleting workflow with id " + workflowId, e);
		}
	}
}


text:
        x

        {{ msg.txt | translate }}

            {{ msg.link.txt }}


text:
from vector import Vector
from span import Span


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

    <group android:checkableBehavior="single">
        <item
            android:id="@+id/nav_current_packet"
            android:icon="@drawable/ic_menu_current_packet"
            android:title="Текущий пакет" />
        <item
            android:id="@+id/nav_cabinet"
            android:icon="@drawable/ic_menu_cabinet"
            android:title="Кабинет"/>
        <item
            android:id="@+id/nav_messages"
            android:icon="@drawable/ic_menu_send"
            android:title="Сообщения" />
        <!--<item-->
            <!--android:id="@+id/nav_history"-->
            <!--android:icon="@drawable/ic_menu_gallery"-->
            <!--android:title="История" />-->
    </group>

    <item android:title="">
        <menu>
            <item
                android:id="@+id/nav_settings"
                android:icon="@drawable/ic_menu_manage"
                android:title="Настройки" />
            <item
                android:id="@+id/nav_info"
                android:icon="@drawable/info_contacts"
                android:title="Контакты" />
        </menu>
    </item>

    <item android:title="">
        <menu>
            <item
                android:id="@+id/nav_quit"
                android:icon="@drawable/nav_quit"
                android:title="Выйти"
                />
        </menu>
    </item>

</menu>


text:
package com.github.slidekb.front;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Properties;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JCheckBox;
import javax.swing.JButton;
import javax.swing.JLayeredPane;
import javax.swing.JList;
import javax.swing.JScrollPane;

import org.aeonbits.owner.Accessible;
import org.aeonbits.owner.Mutable;
import org.aeonbits.owner.Config;
import org.aeonbits.owner.ConfigFactory;

import com.github.slidekb.api.SlideBarPlugin;
import com.github.slidekb.back.MainBack;

import javax.swing.JComboBox;

public class UI {

    private static JFrame frame;
    private static JLabel lblConnected;
    private static ThisConfig cfg;

    @Config.Sources({ "classpath:Program/Main.properties" })
    private static interface ThisConfig extends Accessible, Mutable {
        @DefaultValue("default")
        String SliderDefault1();

        @DefaultValue("default2")
        String SliderDefault2();

        @DefaultValue("default3")
        String SliderDefault3();

        @DefaultValue("default4")
        String SliderDefault4();

        @DefaultValue("false")
        boolean SliderDefault1Reversed();

        @DefaultValue("false")
        boolean SliderDefault2Reversed();

        @DefaultValue("false")
        boolean SliderDefault3Reversed();

        @DefaultValue("false")
        boolean SliderDefault4Reversed();

        @DefaultValue("false")
        boolean RunOnStartUp();

        @DefaultValue("false")
        Boolean CheckForUpdates();
    }

    private static String SliderDefault1;
    private static String SliderDefault2;
    private static String SliderDefault3;
    private static String SliderDefault4;
    private static boolean slider1Reversed;
    private static boolean slider2Reversed;
    private static boolean slider3Reversed;
    private static boolean slider4Reversed;

    public static void readFromConfig() throws IOException {
        FileInputStream in = new FileInputStream("classpath:Program/Main.properties");
        cfg.load(in);
        in.close();
        SliderDefault1 = cfg.SliderDefault1();
        SliderDefault2 = cfg.SliderDefault2();
        SliderDefault3 = cfg.SliderDefault3();
        SliderDefault4 = cfg.SliderDefault4();
        slider1Reversed = cfg.SliderDefault1Reversed();
        slider2Reversed = cfg.SliderDefault2Reversed();
        slider3Reversed = cfg.SliderDefault3Reversed();
        slider4Reversed = cfg.SliderDefault4Reversed();
        System.out.println("reload complete");
    }

    public static void writeToConfig() throws IOException {
        FileInputStream in = new FileInputStream(ClassLoader.getSystemClassLoader().getResource(".").getPath() + "Program/Main.properties");
        Properties props = new Properties();
        props.load(in);
        in.close();

        FileOutputStream out = new FileOutputStream(ClassLoader.getSystemClassLoader().getResource(".").getPath() + "Program/Main.properties");
        System.out.println(ClassLoader.getSystemClassLoader().getResource(".").getPath() + "Program/Main.properties");
        props.setProperty("SliderDefault1", "testing");
        props.setProperty("SliderDefault2", SliderDefault2);
        props.setProperty("SliderDefault3", SliderDefault3);
        props.setProperty("SliderDefault4", SliderDefault4);
        props.setProperty("slider1Reversed", slider1Reversed + "");
        props.setProperty("slider2Reversed", slider2Reversed + "");
        props.setProperty("slider3Reversed", slider3Reversed + "");
        props.setProperty("slider4Reversed", slider4Reversed + "");
        props.store(out, null);
        out.close();
        System.out.println("Saved");
    }

    public static void main(String[] args) throws InterruptedException {
        Thread back = new Thread(new MainBack());
        back.start();
        MainBack.pluginMan.waitUntilProcessesLoaded();
        cfg = ConfigFactory.create(ThisConfig.class);
        try {
            readFromConfig();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        createAndShowGUI();
        setupTray();
    }

    private static void setupTray() {
        try {
            // Check the SystemTray is supported
            if (!SystemTray.isSupported()) {
                System.out.println("SystemTray is not supported");
                return;
            }
            final TrayIcon trayIcon = new TrayIcon(Toolkit.getDefaultToolkit().getImage(new URL("http://home.comcast.net/~supportcd/Icons/Java_Required.jpg")), "Library Drop");
            final SystemTray tray = SystemTray.getSystemTray();

            // Create a pop-up menu components
            final PopupMenu popup = createPopupMenu();
            trayIcon.setPopupMenu(popup);
            trayIcon.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    if (e.getButton() == MouseEvent.BUTTON1) {
                        createAndShowGUI();
                    }
                }
            });

            tray.add(trayIcon);
        } catch (AWTException e) {
            System.out.println("TrayIcon could not be added.");
        } catch (MalformedURLException e) {
            System.out.println("Malformed Exception");
        }
    }

    /**
     * Initialize the contents of the frame.
     *
     * @wbp.parser.entryPoint
     */
    private static void createAndShowGUI() {
        // if (frame == null) {
        frame = new JFrame();
        frame.getContentPane().setLayout(null);
        frame.setBounds(100, 100, 989, 1008);
        frame.setPreferredSize(new Dimension(989, 1008));
        frame.setMinimumSize(new Dimension(989, 1008));
        frame.setMaximumSize(new Dimension(989, 1008));
        JLayeredPane layeredPane = new JLayeredPane();
        layeredPane.setBounds(15, 61, 177, 203);
        frame.getContentPane().add(layeredPane);

        if (MainBack.getSliderManager().getDefaultSlider() != null && MainBack.getSliderManager().getDefaultSlider().getID() != null) {
            JLabel lblSlider = new JLabel("Default Slider 1");
            lblSlider.setBounds(15, 16, 147, 20);
            layeredPane.add(lblSlider);
            lblSlider.setFont(new Font("Tahoma", Font.PLAIN, 20));

            JCheckBox chckbxReversed = new JCheckBox("Reversed");
            chckbxReversed.addItemListener(new ItemListener() {
                @Override
                public void itemStateChanged(ItemEvent e) {
                    if (e.getStateChange() == ItemEvent.SELECTED) {
                        MainBack.getSliderManager().getDefaultSlider().setReversed(true);
                        System.out.println(cfg.SliderDefault1Reversed());
                        System.out.println("[UI] setting default slider 1 to reverse direction");

                    } else {
                        MainBack.getSliderManager().getDefaultSlider().setReversed(false);

                        System.out.println("[UI] setting default slider 1 to standard direction");
                    }
                    ;
                }
            });
            chckbxReversed.setBounds(11, 156, 139, 29);
            chckbxReversed.setSelected(cfg.SliderDefault1Reversed());
            layeredPane.add(chckbxReversed);

            JLabel lblId = new JLabel("ID: " + MainBack.getSliderManager().getDefaultSlider().getID());
            lblId.setBounds(15, 52, 69, 20);
            layeredPane.add(lblId);

            JLabel lblSize = new JLabel("Size:");
            lblSize.setBounds(15, 88, 69, 20);
            layeredPane.add(lblSize);

            JLabel lblPort = new JLabel("Port: ");
            lblPort.setBounds(15, 124, 69, 20);
            layeredPane.add(lblPort);
        }

        if (MainBack.getSliderManager().getDefaultSlider2() != null && MainBack.getSliderManager().getDefaultSlider2().getID() != null) {
            JButton btnNewButton = new JButton(">");
            btnNewButton.setBounds(206, 127, 45, 29);
            frame.getContentPane().add(btnNewButton);

            JButton button = new JButton("<");
            button.setBounds(206, 172, 45, 29);
            frame.getContentPane().add(button);

            JLayeredPane layeredPane_1 = new JLayeredPane();
            layeredPane_1.setBounds(266, 61, 177, 203);
            frame.getContentPane().add(layeredPane_1);

            JCheckBox checkBox = new JCheckBox("Reversed");
            checkBox.setBounds(11, 156, 139, 29);
            layeredPane_1.add(checkBox);

            JLabel label_1 = new JLabel("ID: ");
            label_1.setBounds(15, 52, 69, 20);
            layeredPane_1.add(label_1);

            JLabel label_2 = new JLabel("Size:");
            label_2.setBounds(15, 88, 69, 20);
            layeredPane_1.add(label_2);

            JLabel label_3 = new JLabel("Port: ");
            label_3.setBounds(15, 124, 69, 20);
            layeredPane_1.add(label_3);

            JLabel lblDefaultSlider = new JLabel("Default Slider 2");
            lblDefaultSlider.setFont(new Font("Tahoma", Font.PLAIN, 20));
            lblDefaultSlider.setBounds(15, 16, 147, 20);
            layeredPane_1.add(lblDefaultSlider);

        }

        if (MainBack.getSliderManager().getDefaultSlider3() != null && MainBack.getSliderManager().getDefaultSlider3().getID() != null) {
            JButton button_1 = new JButton(">");
            button_1.setBounds(458, 127, 45, 29);
            frame.getContentPane().add(button_1);

            JButton button_2 = new JButton("<");
            button_2.setBounds(458, 172, 45, 29);
            frame.getContentPane().add(button_2);

            JLayeredPane layeredPane_2 = new JLayeredPane();
            layeredPane_2.setBounds(518, 61, 177, 203);
            frame.getContentPane().add(layeredPane_2);

            JCheckBox checkBox_1 = new JCheckBox("Reversed");
            checkBox_1.setBounds(11, 156, 139, 29);
            layeredPane_2.add(checkBox_1);

            JLabel label_5 = new JLabel("ID: ");
            label_5.setBounds(15, 52, 69, 20);
            layeredPane_2.add(label_5);

            JLabel label_6 = new JLabel("Size:");
            label_6.setBounds(15, 88, 69, 20);
            layeredPane_2.add(label_6);

            JLabel label_7 = new JLabel("Port: ");
            label_7.setBounds(15, 124, 69, 20);
            layeredPane_2.add(label_7);

            JLabel lblDefaultSlider_1 = new JLabel("Default Slider 3");
            lblDefaultSlider_1.setFont(new Font("Tahoma", Font.PLAIN, 20));
            lblDefaultSlider_1.setBounds(15, 16, 147, 20);
            layeredPane_2.add(lblDefaultSlider_1);
        }
        if (MainBack.getSliderManager().getDefaultSlider4() != null && MainBack.getSliderManager().getDefaultSlider4().getID() != null) {
            JButton button_3 = new JButton(">");
            button_3.setBounds(710, 127, 45, 29);
            frame.getContentPane().add(button_3);

            JButton button_4 = new JButton("<");
            button_4.setBounds(710, 172, 45, 29);
            frame.getContentPane().add(button_4);

            JLayeredPane layeredPane_3 = new JLayeredPane();
            layeredPane_3.setBounds(770, 61, 177, 203);
            frame.getContentPane().add(layeredPane_3);

            JCheckBox checkBox_2 = new JCheckBox("Reversed");
            checkBox_2.setBounds(11, 156, 139, 29);
            layeredPane_3.add(checkBox_2);

            JLabel label_9 = new JLabel("ID: ");
            label_9.setBounds(15, 52, 69, 20);
            layeredPane_3.add(label_9);

            JLabel label_10 = new JLabel("Size:");
            label_10.setBounds(15, 88, 69, 20);
            layeredPane_3.add(label_10);

            JLabel label_11 = new JLabel("Port: ");
            label_11.setBounds(15, 124, 69, 20);
            layeredPane_3.add(label_11);

            JLabel lblDefaultSlider_2 = new JLabel("Default Slider 4");
            lblDefaultSlider_2.setFont(new Font("Tahoma", Font.PLAIN, 20));
            lblDefaultSlider_2.setBounds(15, 16, 147, 20);
            layeredPane_3.add(lblDefaultSlider_2);

        }

        JLabel lblSlidersConnected = new JLabel("Sliders Connected");
        lblSlidersConnected.setFont(new Font("Tahoma", Font.PLAIN, 36));
        lblSlidersConnected.setBounds(15, 16, 434, 29);
        frame.getContentPane().add(lblSlidersConnected);

        JLabel lblProgramSettings = new JLabel("Program Settings");
        lblProgramSettings.setFont(new Font("Tahoma", Font.PLAIN, 36));
        lblProgramSettings.setBounds(15, 275, 339, 44);
        frame.getContentPane().add(lblProgramSettings);

        JCheckBox chckbxRunOnStartup = new JCheckBox("Run on startup");
        chckbxRunOnStartup.setBounds(15, 331, 139, 29);
        frame.getContentPane().add(chckbxRunOnStartup);

        JCheckBox chckbxCheckForUpdates = new JCheckBox("Check for updates");
        chckbxCheckForUpdates.setBounds(15, 368, 177, 29);
        frame.getContentPane().add(chckbxCheckForUpdates);

        JLabel lblPluginSettings = new JLabel("Plugin Settings");
        lblPluginSettings.setFont(new Font("Tahoma", Font.PLAIN, 36));
        lblPluginSettings.setBounds(15, 409, 339, 44);
        frame.getContentPane().add(lblPluginSettings);

        JButton btnTestSliders = new JButton("Test \r\nSliders");
        btnTestSliders.setFont(new Font("Tahoma", Font.PLAIN, 20));
        btnTestSliders.setBounds(601, 331, 139, 66);
        frame.getContentPane().add(btnTestSliders);

        JButton btnReconnect = new JButton("Reconnect");
        btnReconnect.setFont(new Font("Tahoma", Font.PLAIN, 20));
        btnReconnect.setBounds(447, 331, 139, 66);
        btnReconnect.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                lblConnected.setText("Reconnecting");
                if (MainBack.reconnect()) {
                    lblConnected.setText("Connected");
                } else {
                    lblConnected.setText("Not Connected");
                }
            }
        });
        frame.getContentPane().add(btnReconnect);

        // JList list = new JList();
        // list.setBounds(15, 469, 468, 467);
        // frame.getContentPane().add(list);

        ArrayList<String> arrayProcess = new ArrayList<String>();
        for (SlideBarPlugin p : MainBack.pluginMan.getProci()) {
            arrayProcess.add(p.getLabelName());
            System.out.println("adding to list: " + p.getLabelName());
        }
        String proci[] = arrayProcess.toArray(new String[arrayProcess.size()]);
        JList<String> processList = new JList<String>(proci);
        // JList<String> processList = new JList<String>();
        JScrollPane pane = new JScrollPane(processList);
        pane.setBounds(15, 469, 468, 467);
        frame.getContentPane().add(pane);

        JLayeredPane layeredPane_4 = new JLayeredPane();
        layeredPane_4.setBounds(498, 715, 449, 221);
        frame.getContentPane().add(layeredPane_4);

        JLabel lblSlider_1 = new JLabel("Slider 1");
        lblSlider_1.setBounds(15, 65, 69, 20);
        layeredPane_4.add(lblSlider_1);

        JComboBox comboBox = new JComboBox();
        comboBox.setBounds(83, 65, 148, 26);
        layeredPane_4.add(comboBox);

        JLabel lblPluginSliderAssignment = new JLabel("Plugin Slider Assignment");
        lblPluginSliderAssignment.setFont(new Font("Tahoma", Font.PLAIN, 20));
        lblPluginSliderAssignment.setBounds(15, 16, 303, 33);
        layeredPane_4.add(lblPluginSliderAssignment);

        JLabel lblSlider_2 = new JLabel("Slider 2");
        lblSlider_2.setBounds(15, 101, 69, 20);
        layeredPane_4.add(lblSlider_2);

        JComboBox comboBox_1 = new JComboBox();
        comboBox_1.setBounds(83, 101, 148, 26);
        layeredPane_4.add(comboBox_1);

        JLabel lblSlider_3 = new JLabel("Slider 3");
        lblSlider_3.setBounds(15, 137, 69, 20);
        layeredPane_4.add(lblSlider_3);

        JComboBox comboBox_2 = new JComboBox();
        comboBox_2.setBounds(83, 137, 148, 26);
        layeredPane_4.add(comboBox_2);

        JLabel lblSlider_4 = new JLabel("Slider 4");
        lblSlider_4.setBounds(15, 173, 69, 20);
        layeredPane_4.add(lblSlider_4);

        JComboBox comboBox_3 = new JComboBox();
        comboBox_3.setBounds(83, 173, 148, 26);
        layeredPane_4.add(comboBox_3);

        JButton btnInfo = new JButton("Details");
        btnInfo.setBounds(350, 62, 84, 29);
        layeredPane_4.add(btnInfo);

        JButton button_5 = new JButton("Details");
        button_5.setBounds(350, 98, 84, 29);
        layeredPane_4.add(button_5);

        JButton button_6 = new JButton("Details");
        button_6.setBounds(350, 134, 84, 29);
        layeredPane_4.add(button_6);

        JButton button_7 = new JButton("Details");
        button_7.setBounds(350, 173, 84, 29);
        layeredPane_4.add(button_7);

        JCheckBox checkBox_3 = new JCheckBox("Reversed");
        checkBox_3.setBounds(242, 65, 97, 29);
        layeredPane_4.add(checkBox_3);

        JCheckBox checkBox_4 = new JCheckBox("Reversed");
        checkBox_4.setBounds(242, 101, 97, 29);
        layeredPane_4.add(checkBox_4);

        JCheckBox checkBox_5 = new JCheckBox("Reversed");
        checkBox_5.setBounds(242, 137, 97, 29);
        layeredPane_4.add(checkBox_5);

        JCheckBox checkBox_6 = new JCheckBox("Reversed");
        checkBox_6.setBounds(242, 173, 97, 29);
        layeredPane_4.add(checkBox_6);

        JLabel lblSliderSettings = new JLabel("LabelName");
        lblSliderSettings.setFont(new Font("Tahoma", Font.PLAIN, 36));
        lblSliderSettings.setBounds(498, 470, 197, 47);
        frame.getContentPane().add(lblSliderSettings);

        JLabel lblRunsWithBased = new JLabel("Runs based on active program");
        lblRunsWithBased.setBounds(498, 533, 255, 20);
        frame.getContentPane().add(lblRunsWithBased);

        JButton btnConfigureList = new JButton("Edit Program List");
        btnConfigureList.setBounds(780, 529, 172, 29);
        frame.getContentPane().add(btnConfigureList);

        JCheckBox chckbxEnabled = new JCheckBox("Enabled");
        chckbxEnabled.setBounds(492, 565, 139, 29);
        frame.getContentPane().add(chckbxEnabled);

        JButton btnOpenConfigFile = new JButton("Open Config File");
        btnOpenConfigFile.setBounds(498, 670, 157, 29);
        frame.getContentPane().add(btnOpenConfigFile);

        JButton btnSaveAndReload = new JButton("Save and Reload");
        btnSaveAndReload.setBounds(790, 670, 157, 29);
        frame.getContentPane().add(btnSaveAndReload);

        JButton btnSave = new JButton("Save");
        btnSave.setBounds(670, 670, 105, 29);
        frame.getContentPane().add(btnSave);

        JButton btnReloadAllPlugins = new JButton("Reload Plugins");
        btnReloadAllPlugins.setFont(new Font("Tahoma", Font.PLAIN, 20));
        btnReloadAllPlugins.setBounds(755, 331, 192, 66);
        frame.getContentPane().add(btnReloadAllPlugins);

        JLabel lblStatus = new JLabel("Running: ");
        lblStatus.setBounds(223, 335, 69, 20);
        frame.getContentPane().add(lblStatus);

        lblConnected = new JLabel(MainBack.isStarted() + "");
        lblConnected.setBounds(286, 335, 90, 20);
        frame.getContentPane().add(lblConnected);
        // }
        frame.pack();
        bringToFront();
    }

    /**
     * Popup Menu
     *
     * @return
     */
    protected static PopupMenu createPopupMenu() {
        final PopupMenu popup = new PopupMenu();
        MenuItem aboutItem = new MenuItem("Open Configuration");
        aboutItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                createAndShowGUI();
            }
        });
        MenuItem about = new MenuItem("About");
        MenuItem website = new MenuItem("Website");
        MenuItem reload = new MenuItem("Reload");
        MenuItem exitItem = new MenuItem("Exit");
        exitItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
        // Add components to pop-up menu
        popup.add(aboutItem);
        popup.addSeparator();
        popup.add(about);
        popup.add(website);
        popup.add(reload);
        popup.addSeparator();
        popup.add(exitItem);
        return popup;
    }

    private static void bringToFront() {
        try {
            readFromConfig();
        } catch (IOException e) {
            System.out.println("[UI] failed to read from config");
        }
        getInstance().setVisible(true);
        getInstance().setExtendedState(JFrame.NORMAL);
        getInstance().toFront();
        getInstance().repaint();
    }

    private static JFrame getInstance() {
        return frame;
    }
}


text:
<?php

/* @var $installer Mage_Customer_Model_Entity_Setup */
$installer = $this;

$installer->startSetup();
$installer->run("
CREATE TABLE `{$installer->getTable('customer/eav_attribute_website')}` (
  `attribute_id` smallint(5) unsigned NOT NULL,
  `website_id` smallint(5) unsigned NOT NULL,
  `is_visible` tinyint(1) unsigned DEFAULT NULL,
  `is_required` tinyint(1) unsigned DEFAULT NULL,
  `default_value` text,
  `multiline_count` tinyint(3) unsigned DEFAULT NULL,
  PRIMARY KEY (`attribute_id`, `website_id`),
  KEY `IDX_WEBSITE` (`website_id`),
  CONSTRAINT `FK_CUSTOMER_EAV_ATTRIBUTE_WEBSITE_ATTRIBUTE_EAV_ATTRIBUTE` FOREIGN KEY (`attribute_id`)
    REFERENCES `{$installer->getTable('eav/attribute')}` (`attribute_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `FK_CUSTOMER_EAV_ATTRIBUTE_WEBSITE_WEBSITE_CORE_WEBSITE` FOREIGN KEY (`website_id`)
    REFERENCES `{$installer->getTable('core/website')}` (`website_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
");
$installer->endSetup();


text:
using NQuery.Syntax;

namespace NQuery.Authoring.Selection.Providers
{
    internal sealed class SelectClauseSelectionSpanProvider : SeparatedSyntaxListSelectionSpanProvider<SelectClauseSyntax, SelectColumnSyntax>
    {
        protected override SeparatedSyntaxList<SelectColumnSyntax> GetList(SelectClauseSyntax node)
        {
            return node.Columns;
        }
    }
}


text:
using System;
using System.Linq;

using Ninject;
using Ninject.Parameters;

namespace RedisRepo.Tests.ServiceLocator
{
	public class NinjectServiceLocator : IAppServiceLocator
	{
		private readonly IKernel _kernel;
		public NinjectServiceLocator (IKernel kernel) {
			_kernel = kernel;
		}

		public T GetInstance<T>(params object[] argumentParameters) where T : class
		{
			return argumentParameters.Length > 0
				? _kernel.Get<T>(argumentParameters.OfType<ConstructorArgument>().Cast<IParameter>().ToArray()) : _kernel.Get<T>();
		}

		public T GetNamedInstance<T>(string instanceName) { return _kernel.Get<T>(instanceName); }

		public object GetInstance(Type type) { return _kernel.Get(type); }
	}
}


text:
package com.navercorp.pinpoint.web.service;

import com.navercorp.pinpoint.common.bo.SpanBo;
import com.navercorp.pinpoint.common.bo.SpanEventBo;
import com.navercorp.pinpoint.common.service.ServiceTypeRegistryService;
import com.navercorp.pinpoint.common.trace.HistogramSchema;
import com.navercorp.pinpoint.common.trace.HistogramSlot;
import com.navercorp.pinpoint.common.trace.ServiceType;
import com.navercorp.pinpoint.web.applicationmap.ApplicationMap;
import com.navercorp.pinpoint.web.applicationmap.ApplicationMapBuilder;
import com.navercorp.pinpoint.web.applicationmap.rawdata.LinkDataDuplexMap;
import com.navercorp.pinpoint.web.applicationmap.rawdata.LinkDataMap;
import com.navercorp.pinpoint.web.dao.ApplicationTraceIndexDao;
import com.navercorp.pinpoint.web.dao.TraceDao;
import com.navercorp.pinpoint.web.filter.Filter;
import com.navercorp.pinpoint.web.util.TimeWindow;
import com.navercorp.pinpoint.web.util.TimeWindowDownSampler;
import com.navercorp.pinpoint.web.vo.*;
import com.navercorp.pinpoint.web.vo.scatter.ApplicationScatterScanResult;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StopWatch;

import java.util.*;

/**
 * @author netspider
 * @author emeroad
 * @author minwoo.jung
 */
@Service
public class FilteredMapServiceImpl implements FilteredMapService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private TraceDao traceDao;

    @Autowired
    private ApplicationTraceIndexDao applicationTraceIndexDao;

    @Autowired
    private AgentInfoService agentInfoService;

    @Autowired
    private ServiceTypeRegistryService registry;

    @Autowired
    private ApplicationFactory applicationFactory;

    private static final Object V = new Object();

    @Override
    public LimitedScanResult<List<TransactionId>> selectTraceIdsFromApplicationTraceIndex(String applicationName, Range range, int limit) {
        if (applicationName == null) {
            throw new NullPointerException("applicationName must not be null");
        }
        if (range == null) {
            throw new NullPointerException("range must not be null");
        }
        if (logger.isTraceEnabled()) {
            logger.trace("scan(selectTraceIdsFromApplicationTraceIndex) {}, {}", applicationName, range);
        }

        return this.applicationTraceIndexDao.scanTraceIndex(applicationName, range, limit);
    }

    @Override
    public LimitedScanResult<List<TransactionId>> selectTraceIdsFromApplicationTraceIndex(String applicationName, SelectedScatterArea area, int limit) {
        if (applicationName == null) {
            throw new NullPointerException("applicationName must not be null");
        }
        if (area == null) {
            throw new NullPointerException("area must not be null");
        }
        if (logger.isTraceEnabled()) {
            logger.trace("scan(selectTraceIdsFromApplicationTraceIndex) {}, {}", applicationName, area);
        }

        return this.applicationTraceIndexDao.scanTraceIndex(applicationName, area, limit);
    }

    @Override
    @Deprecated
    public LoadFactor linkStatistics(Range range, List<TransactionId> traceIdSet, Application sourceApplication, Application destinationApplication, Filter filter) {
        if (sourceApplication == null) {
            throw new NullPointerException("sourceApplication must not be null");
        }
        if (destinationApplication == null) {
            throw new NullPointerException("destApplicationName must not be null");
        }
        if (filter == null) {
            throw new NullPointerException("filter must not be null");
        }

        StopWatch watch = new StopWatch();
        watch.start();

        List<List<SpanBo>> originalList = this.traceDao.selectAllSpans(traceIdSet);
        List<SpanBo> filteredTransactionList = filterList(originalList, filter);

        LoadFactor statistics = new LoadFactor(range);

        // TODO need to handle these separately by node type (like fromToFilter)

        // scan transaction list
        for (SpanBo span : filteredTransactionList) {
            if (sourceApplication.equals(span.getApplicationId(), registry.findServiceType(span.getApplicationServiceType()))) {
                List<SpanEventBo> spanEventBoList = span.getSpanEventBoList();
                if (spanEventBoList == null) {
                    continue;
                }

                // find dest elapsed time
                for (SpanEventBo spanEventBo : spanEventBoList) {
                    if (destinationApplication.equals(spanEventBo.getDestinationId(), registry.findServiceType(spanEventBo.getServiceType()))) {
                        // find exception
                        boolean hasException = spanEventBo.hasException();
                        // add sample
                        // TODO : need timeslot value instead of the actual value
                        statistics.addSample(span.getStartTime() + spanEventBo.getStartElapsed(), spanEventBo.getEndElapsed(), 1, hasException);
                        break;
                    }
                }
            }
        }

        watch.stop();
        logger.info("Fetch link statistics elapsed. {}ms", watch.getLastTaskTimeMillis());

        return statistics;
    }

    private List<SpanBo> filterList(List<List<SpanBo>> transactionList, Filter filter) {
        final List<SpanBo> filteredResult = new ArrayList<>();
        for (List<SpanBo> transaction : transactionList) {
            if (filter.include(transaction)) {
                filteredResult.addAll(transaction);
            }
        }
        return filteredResult;
    }

    private List<List<SpanBo>> filterList2(List<List<SpanBo>> transactionList, Filter filter) {
        final List<List<SpanBo>> filteredResult = new ArrayList<>();
        for (List<SpanBo> transaction : transactionList) {
            if (filter.include(transaction)) {
                filteredResult.add(transaction);
            }
        }
        return filteredResult;
    }

    @Override
    public ApplicationMap selectApplicationMap(TransactionId transactionId) {
        if (transactionId == null) {
            throw new NullPointerException("transactionId must not be null");
        }
        List<TransactionId> transactionIdList = new ArrayList<>();
        transactionIdList.add(transactionId);
        // FIXME from,to -1
        Range range = new Range(-1, -1);
        return selectApplicationMap(transactionIdList, range, range, Filter.NONE);
    }

    /**
     * filtered application map
     */
    @Override
    public ApplicationMap selectApplicationMap(List<TransactionId> transactionIdList, Range originalRange, Range scanRange, Filter filter) {
        if (transactionIdList == null) {
            throw new NullPointerException("transactionIdList must not be null");
        }
        if (filter == null) {
            throw new NullPointerException("filter must not be null");
        }

        StopWatch watch = new StopWatch();
        watch.start();

        final List<List<SpanBo>> filterList = selectFilteredSpan(transactionIdList, filter);

        ApplicationMap map = createMap(originalRange, scanRange, filterList);

        watch.stop();
        logger.debug("Select filtered application map elapsed. {}ms", watch.getTotalTimeMillis());

        return map;
    }

    private List<List<SpanBo>> selectFilteredSpan(List<TransactionId> transactionIdList, Filter filter) {
        // filters out recursive calls by looking at each objects
        // do not filter here if we change to a tree-based collision check in the future.
        final Collection<TransactionId> recursiveFilterList = recursiveCallFilter(transactionIdList);

        // FIXME might be better to simply traverse the List<Span> and create a process chain for execution
        final List<List<SpanBo>> originalList = this.traceDao.selectAllSpans(recursiveFilterList);

        return filterList2(originalList, filter);
    }

    private ApplicationMap createMap(Range range, Range scanRange, List<List<SpanBo>> filterList) {

        // TODO inject TimeWindow from elsewhere
        final TimeWindow window = new TimeWindow(range, TimeWindowDownSampler.SAMPLER);

        final LinkDataDuplexMap linkDataDuplexMap = new LinkDataDuplexMap();

        final DotExtractor dotExtractor = new DotExtractor(scanRange, applicationFactory);
        final ResponseHistogramBuilder mapHistogramSummary = new ResponseHistogramBuilder(range);
        /**
         * Convert to statistical data
         */
        for (List<SpanBo> transaction : filterList) {
            final Map<Long, SpanBo> transactionSpanMap = checkDuplicatedSpanId(transaction);

            for (SpanBo span : transaction) {
                final Application parentApplication = createParentApplication(span, transactionSpanMap);
                final Application spanApplication = this.applicationFactory.createApplication(span.getApplicationId(), span.getApplicationServiceType());

                // records the Span's response time statistics
                recordSpanResponseTime(spanApplication, span, mapHistogramSummary, span.getCollectorAcceptTime());

                if (!spanApplication.getServiceType().isRecordStatistics() || spanApplication.getServiceType().isRpcClient()) {
                    // span's serviceType is probably not set correctly
                    logger.warn("invalid span application:{}", spanApplication);
                    continue;
                }

                final short slotTime = getHistogramSlotTime(span, spanApplication.getServiceType());
                // might need to reconsider using collector's accept time for link statistics.
                // we need to convert to time window's timestamp. If not, it may lead to OOM due to mismatch in timeslots.
                long timestamp = window.refineTimestamp(span.getCollectorAcceptTime());

                if (parentApplication.getServiceType() == ServiceType.USER) {
                    // Outbound data
                    if (logger.isTraceEnabled()) {
                        logger.trace("span user:{} {} -> span:{} {}", parentApplication, span.getAgentId(), spanApplication, span.getAgentId());
                    }
                    final LinkDataMap sourceLinkData = linkDataDuplexMap.getSourceLinkDataMap();
                    sourceLinkData.addLinkData(parentApplication, span.getAgentId(), spanApplication,  span.getAgentId(), timestamp, slotTime, 1);

                    if (logger.isTraceEnabled()) {
                        logger.trace("span target user:{} {} -> span:{} {}", parentApplication, span.getAgentId(), spanApplication, span.getAgentId());
                    }
                    // Inbound data
                    final LinkDataMap targetLinkDataMap = linkDataDuplexMap.getTargetLinkDataMap();
                    targetLinkDataMap.addLinkData(parentApplication, span.getAgentId(), spanApplication, span.getAgentId(), timestamp, slotTime, 1);
                } else {
                    // Inbound data
                    if (logger.isTraceEnabled()) {
                        logger.trace("span target parent:{} {} -> span:{} {}", parentApplication, span.getAgentId(), spanApplication, span.getAgentId());
                    }
                    final LinkDataMap targetLinkDataMap = linkDataDuplexMap.getTargetLinkDataMap();
                    targetLinkDataMap.addLinkData(parentApplication, span.getAgentId(), spanApplication, span.getAgentId(), timestamp, slotTime, 1);
                }

                addNodeFromSpanEvent(span, window, linkDataDuplexMap, transactionSpanMap);
                dotExtractor.addDot(span);
            }
        }
        List<ApplicationScatterScanResult> applicationScatterScanResult = dotExtractor.getApplicationScatterScanResult();

        ApplicationMapBuilder applicationMapBuilder = new ApplicationMapBuilder(range);
        mapHistogramSummary.build();
        ApplicationMap map = applicationMapBuilder.build(linkDataDuplexMap, agentInfoService, mapHistogramSummary);

        map.setApplicationScatterScanResult(applicationScatterScanResult);

        return map;
    }

    private Map<Long, SpanBo> checkDuplicatedSpanId(List<SpanBo> transaction) {
        final Map<Long, SpanBo> transactionSpanMap = new HashMap<>();
        for (SpanBo span : transaction) {
            final SpanBo old = transactionSpanMap.put(span.getSpanId(), span);
            if (old != null) {
                logger.warn("duplicated span found:{}", old);
            }
        }
        return transactionSpanMap;
    }

    private void recordSpanResponseTime(Application application, SpanBo span, ResponseHistogramBuilder responseHistogramBuilder, long timeStamp) {
        responseHistogramBuilder.addHistogram(application, span, timeStamp);
    }

    private void addNodeFromSpanEvent(SpanBo span, TimeWindow window, LinkDataDuplexMap linkDataDuplexMap, Map<Long, SpanBo> transactionSpanMap) {
        /**
         * add span event statistics
         */
        final List<SpanEventBo> spanEventBoList = span.getSpanEventBoList();
        if (CollectionUtils.isEmpty(spanEventBoList)) {
            return;
        }
        final Application srcApplication = applicationFactory.createApplication(span.getApplicationId(), span.getApplicationServiceType());

        LinkDataMap sourceLinkDataMap = linkDataDuplexMap.getSourceLinkDataMap();
        for (SpanEventBo spanEvent : spanEventBoList) {

            ServiceType destServiceType = registry.findServiceType(spanEvent.getServiceType());
            if (!destServiceType.isRecordStatistics()) {
                // internal method
                continue;
            }
            // convert to Unknown if destServiceType is a rpc client and there is no acceptor.
            // acceptor exists if there is a span with spanId identical to the current spanEvent's next spanId.
            // logic for checking acceptor
            if (destServiceType.isRpcClient()) {
                if (!transactionSpanMap.containsKey(spanEvent.getNextSpanId())) {
                    destServiceType = ServiceType.UNKNOWN;
                }
            }

            String dest = spanEvent.getDestinationId();
            if (dest == null) {
                dest = "Unknown";
            }

            final Application destApplication = this.applicationFactory.createApplication(dest, destServiceType);

            final short slotTime = getHistogramSlotTime(spanEvent, destServiceType);

            // FIXME
            final long spanEventTimeStamp = window.refineTimestamp(span.getStartTime() + spanEvent.getStartElapsed());
            if (logger.isTraceEnabled()) {
                logger.trace("spanEvent  src:{} {} -> dest:{} {}", srcApplication, span.getAgentId(), destApplication, spanEvent.getEndPoint());
            }
            // endPoint may be null
            final String destinationAgentId = StringUtils.defaultString(spanEvent.getEndPoint());
            sourceLinkDataMap.addLinkData(srcApplication, span.getAgentId(), destApplication, destinationAgentId, spanEventTimeStamp, slotTime, 1);
        }
    }

    private Application createParentApplication(SpanBo span, Map<Long, SpanBo> transactionSpanMap) {
        final SpanBo parentSpan = transactionSpanMap.get(span.getParentSpanId());
        if (span.isRoot() || parentSpan == null) {
            String applicationName = span.getApplicationId();
            ServiceType serviceType = ServiceType.USER;
            return this.applicationFactory.createApplication(applicationName, serviceType);
        } else {
            String parentApplicationName = parentSpan.getApplicationId();
            short parentServiceType = parentSpan.getApplicationServiceType();
            return this.applicationFactory.createApplication(parentApplicationName, parentServiceType);
        }
    }

    private short getHistogramSlotTime(SpanEventBo spanEvent, ServiceType serviceType) {
        return getHistogramSlotTime(spanEvent.hasException(), spanEvent.getEndElapsed(), serviceType);
    }

    private short getHistogramSlotTime(SpanBo span, ServiceType serviceType) {
        boolean allException = span.getErrCode() != 0;
        return getHistogramSlotTime(allException, span.getElapsed(), serviceType);
    }

    private short getHistogramSlotTime(boolean hasException, int elapsedTime, ServiceType serviceType) {
        final HistogramSchema schema = serviceType.getHistogramSchema();
        final HistogramSlot histogramSlot = schema.findHistogramSlot(elapsedTime, hasException);
        return histogramSlot.getSlotTime();
    }

    private Collection<TransactionId> recursiveCallFilter(List<TransactionId> transactionIdList) {
        if (transactionIdList == null) {
            throw new NullPointerException("transactionIdList must not be null");
        }

        List<TransactionId> crashKey = new ArrayList<>();
        Map<TransactionId, Object> filterMap = new LinkedHashMap<>(transactionIdList.size());
        for (TransactionId transactionId : transactionIdList) {
            Object old = filterMap.put(transactionId, V);
            if (old != null) {
                crashKey.add(transactionId);
            }
        }
        if (crashKey.size() != 0) {
            Set<TransactionId> filteredTransactionId = filterMap.keySet();
            logger.info("transactionId crash found. original:{} filter:{} crashKey:{}", transactionIdList.size(), filteredTransactionId.size(), crashKey);
            return filteredTransactionId;
        }
        return transactionIdList;
    }

}


text:
#region Copyright
//=======================================================================================
// Microsoft Azure Customer Advisory Team
//
// This sample is supplemental to the technical guidance published on my personal
// blog at http://blogs.msdn.com/b/paolos/.
//
// Author: Paolo Salvatori
//=======================================================================================
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// LICENSED UNDER THE APACHE LICENSE, VERSION 2.0 (THE "LICENSE"); YOU MAY NOT USE THESE
// FILES 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.
//=======================================================================================
#endregion

#region Using Directives

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Threading.Tasks;
using Microsoft.ServiceBus.Messaging;

#endregion

namespace ServiceBusExplorer.Helpers
{
    public class CustomMessageSessionAsyncHandler : IMessageSessionAsyncHandler
    {
        #region Private Constants
        //***************************
        // Formats
        //***************************
        private const string ExceptionFormat = "Exception: {0}";
        private const string InnerExceptionFormat = "InnerException: {0}";

        //***************************
        // Texts
        //***************************
        private const string NullValue = "NULL";

        //***************************
        // Messages
        //***************************
        private const string MessageSuccessfullyReceived = "Message received. MessageId=[{0}] SessionId=[{1}] Label=[{2}] Size=[{3}]";
        private const string SessionClosed = "Session[{0}] closed. Message Count=[{1}]";
        #endregion

        #region Private Fields
        private readonly CustomMessageSessionAsyncHandlerConfiguration configuration;
        #endregion

        #region Public Static Fields
        public static readonly Dictionary<string, int> SessionDictionary = new Dictionary<string, int>();
        #endregion

        #region Public Constructors
        public CustomMessageSessionAsyncHandler(CustomMessageSessionAsyncHandlerConfiguration configuration)
        {
            this.configuration = configuration;
        }
        #endregion

        #region IMessageSessionAsyncHandler Methods
        public async Task OnMessageAsync(MessageSession session, BrokeredMessage message)
        {
            try
            {
                if (message == null)
                {
                    return;
                }
                if (session == null)
                {
                    return;
                }
                if (configuration == null)
                {
                    return;
                }
                if (configuration.MessageInspector != null)
                {
                    message = configuration.MessageInspector.AfterReceiveMessage(message);
                }
                if (configuration.Logging)
                {
                    var builder = new StringBuilder(string.Format(MessageSuccessfullyReceived,
                                                    string.IsNullOrWhiteSpace(message.MessageId)
                                                        ? NullValue
                                                        : message.MessageId,
                                                    string.IsNullOrWhiteSpace(message.SessionId)
                                                        ? NullValue
                                                        : message.SessionId,
                                                    string.IsNullOrWhiteSpace(message.Label)
                                                        ? NullValue
                                                        : message.Label,
                                                    message.Size));
                    if (configuration.Verbose)
                    {
                        configuration.ServiceBusHelper.GetMessageAndProperties(builder, message, configuration.MessageEncoder);
                    }
                    configuration.WriteToLog(builder.ToString(), false);
                }
                if (configuration.Tracking)
                {
                    configuration.TrackMessage(message.Clone());
                }
                configuration.UpdateStatistics(1, configuration.GetElapsedTime(), message.Size);
                if (configuration.ReceiveMode == ReceiveMode.PeekLock && !configuration.AutoComplete)
                {
                    await message.CompleteAsync();
                }
                if (!SessionDictionary.ContainsKey(message.SessionId))
                {
                    SessionDictionary.Add(message.SessionId, 1);
                }
                else
                {
                    SessionDictionary[message.SessionId]++;
                }
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }

        public Task OnCloseSessionAsync(MessageSession session)
        {
            if (session == null)
            {
                return Task.FromResult(0);
            }
            if (configuration == null)
            {
                return Task.FromResult(0);
            }
            configuration.WriteToLog(string.Format(SessionClosed, session.SessionId, SessionDictionary[session.SessionId]));
            return Task.FromResult(0);
        }

        public Task OnSessionLostAsync(Exception exception)
        {
            if (exception == null)
            {
                return Task.FromResult(0);
            }
            HandleException(exception);
            return Task.FromResult(0);
        }
        #endregion

        #region Private Methods
        private void HandleException(Exception ex)
        {
            if (ex == null || string.IsNullOrWhiteSpace(ex.Message))
            {
                return;
            }
            if (configuration == null)
            {
                return;
            }
            configuration.WriteToLog(string.Format(CultureInfo.CurrentCulture, ExceptionFormat, ex.Message));
            if (ex.InnerException != null && !string.IsNullOrWhiteSpace(ex.InnerException.Message))
            {
                configuration.WriteToLog(string.Format(CultureInfo.CurrentCulture, InnerExceptionFormat, ex.InnerException.Message));
            }
        }
        #endregion
    }
}


text:
//-----------------------------------------------------------------------
// <summary>Defines the SyncFolderHierarchyResponse class.</summary>
//-----------------------------------------------------------------------

namespace Microsoft.Exchange.WebServices.Data
{
    using System;
    using System.Collections.Generic;
    using System.Text;

    /// <summary>
    /// Represents the response to a folder synchronization operation.
    /// </summary>
    public sealed class SyncFolderHierarchyResponse : SyncResponse<Folder, FolderChange>
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="SyncFolderHierarchyResponse"/> class.
        /// </summary>
        /// <param name="propertySet">Property set.</param>
        internal SyncFolderHierarchyResponse(PropertySet propertySet)
            : base(propertySet)
        {
        }

        /// <summary>
        /// Gets the name of the includes last in range XML element.
        /// </summary>
        /// <returns>XML element name.</returns>
        internal override string GetIncludesLastInRangeXmlElementName()
        {
            return XmlElementNames.IncludesLastFolderInRange;
        }

        /// <summary>
        /// Creates a folder change instance.
        /// </summary>
        /// <returns>FolderChange instance</returns>
        internal override FolderChange CreateChangeInstance()
        {
            return new FolderChange();
        }

        /// <summary>
        /// Gets the name of the change element.
        /// </summary>
        /// <returns>Change element name.</returns>
        internal override string GetChangeElementName()
        {
            return XmlElementNames.Folder;
        }

        /// <summary>
        /// Gets the name of the change id element.
        /// </summary>
        /// <returns>Change id element name.</returns>
        internal override string GetChangeIdElementName()
        {
            return XmlElementNames.FolderId;
        }

        /// <summary>
        /// Gets a value indicating whether this request returns full or summary properties.
        /// </summary>
        /// <value>
        /// <c>true</c> if summary properties only; otherwise, <c>false</c>.
        /// </value>
        internal override bool SummaryPropertiesOnly
        {
            get { return false; }
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using umbraco.cms.businesslogic.macro;
using umbraco.cms.businesslogic.web;
using WebBlocks.BusinessLogic.Helpers;
using WebBlocks.BusinessLogic.Model;

namespace WebBlocks.usercontrols.webblocks.datatypes
{
    public partial class UserControlPropertySetter : UserControl, umbraco.editorControls.userControlGrapper.IUsercontrolDataEditor
    {
        protected List<UserControlProperty> userControlProperties = new List<UserControlProperty>();
        protected Macro currentMacro;
        public object value {
            get { return userControlProperties.ToJson(); }
            set
            {
                string json = (string) value;
                if (json != null && json != "")
                {
                    userControlProperties = json.FromJson<List<UserControlProperty>>();
                }
            }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            int id = Convert.ToInt32(Request.QueryString["id"]);
            Document doc = new Document(id);
            string alias = doc.ContentType.Alias;

            currentMacro = GetUserControlMacro(alias);

            if (currentMacro != null)
            {
                UserControl userControl = (UserControl)this.LoadControl("~/" + currentMacro.Type);
                Type userControlType = userControl.GetType().UnderlyingSystemType;

                foreach (var property in currentMacro.Properties)
                {
                    plcParameters.Controls.Add(CreateEditorForField(property, userControlType));
                }
            }
            else
            {
                plcParameters.Controls.Add(new Label() {
                    ID = "lblError",
                    Text = string.Format("A macro doesn't exist with the alias '{0}'", alias)
                });
            }

        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //for the first load only set the values
                SetEditorValues();
            }
            else
            {
                //build up the usercontrol properties to save for this block
                BuildUserControlProperties();
            }
        }

        /// <summary>
        /// Gets usercontrol macro based on alias
        /// </summary>
        /// <returns>A usercontrol macro if the macro is found and is a usercontrol macro</returns>
        protected Macro GetUserControlMacro(string alias)
        {
            IEnumerable<Macro> macros = Macro.GetAll();

            return macros.FirstOrDefault(m => !string.IsNullOrEmpty(m.Type) && m.Alias == alias);
        }

        /// <summary>
        /// Creates a textbox to allow editing
        /// </summary>
        /// <returns>A control to add to the container</returns>
        protected Control CreateEditorForField(MacroProperty property, Type userControlType)
        {
            HtmlGenericControl div = new HtmlGenericControl("div");
            div.Attributes.Add("class", "wbPropertyRow");
            Label label = new Label();
            WebControl editorControl = GetCorrectControl(property.Alias, userControlType);

            label.ID = string.Format("lbl{0}", property.Alias);
            label.Text = string.Format("{0}: ", property.Name);

            editorControl.ID = string.Format("txt{0}", property.Alias);
            editorControl.Attributes.Add("propertytype", property.Type.Alias);

            div.Controls.Add(label);
            div.Controls.Add(editorControl);

            return div;
        }

        /// <summary>
        /// Set the text box values from what is saved
        /// </summary>
        protected void SetEditorValues()
        {
            foreach (MacroProperty property in currentMacro.Properties)
            {
                WebControl control = (WebControl)plcParameters.FindControl(string.Format("txt{0}", property.Alias));

                UserControlProperty storedProperty = userControlProperties.FirstOrDefault(p => p.Name == property.Alias);
                if (storedProperty != null)
                {
                    SetControlValue(storedProperty.Value, control);
                }
            }
        }

        /// <summary>
        /// Builds a list of UserControlProperty with the settings that match the data entered for each property
        /// </summary>
        /// <returns></returns>
        protected void BuildUserControlProperties()
        {
            userControlProperties.Clear();
            foreach (MacroProperty property in currentMacro.Properties)
            {
                WebControl control = (WebControl)plcParameters.FindControl(string.Format("txt{0}", property.Alias));

                userControlProperties.Add(new UserControlProperty()
                {
                    Name = property.Alias,
                    Type = property.Type.Alias,
                    Value = GetControlValue(control)
                });
            }
        }

        #region Get and Set Control Values (based on control types in the GetCorrectControl method)
        protected string GetControlValue(WebControl control)
        {
            //dictionary to get the correct type
            Dictionary<Type, Func<WebControl, string>> relatedControls = new Dictionary<Type, Func<WebControl, string>>()
                {
                    //the type          will use calendar control
                    { typeof(Calendar), (c) => ((Calendar)c).SelectedDate.ToString() },
                    { typeof(TextBox), (c) => ((TextBox)c).Text },
                    { typeof(CheckBox), (c) => ((CheckBox)c).Checked.ToString() },
                    //e.g. { typeof(YourCustomControl), (type) => new YourCustomControl() } }
                };
            Type controlType = control.GetType();
            return relatedControls[controlType](control);
        }

        protected void SetControlValue(string value, WebControl control)
        {
            //dictionary to set the correct type value
            Dictionary<Type, Action<string, WebControl>> relatedControls = new Dictionary<Type, Action<string, WebControl>>()
                {
                    //the type          set the control
                    { typeof(Calendar), (v, c) => ((Calendar)c).SelectedDate = DateTime.Parse(v) },
                    { typeof(TextBox), (v, c) => ((TextBox)c).Text = value },
                    { typeof(CheckBox), (v, c) =>
                        {
                            //in case the property wasn't a bool on previous load, parse it
                            bool defaultBool = false;
                            if (!bool.TryParse(v, out defaultBool))
                                defaultBool = false;
                            ((CheckBox)c).Checked = defaultBool;
                        } },
                    //e.g. { typeof(YourCustomControl), (type) => new YourCustomControl() } }
                };

            //set the value
            relatedControls[control.GetType().UnderlyingSystemType](value, control);
        }
        #endregion

        /// <summary>
        /// Gets the correct control to display and edit the property
        /// </summary>
        /// <param name="propertyName">The alias of the property</param>
        /// <param name="userControlType">the type of usercontrol</param>
        /// <returns>A web control to allow editing of the property</returns>
        protected WebControl GetCorrectControl(string propertyName, Type userControlType)
        {
            WebControl control = null;
            Type propertyType = GetPropertyType(propertyName, userControlType);
            //to use specific controls, add to this function
            //also update GetControlValue to get the value if you use that control
            Dictionary<Type, Func<WebControl>> relatedControls = new Dictionary<Type, Func<WebControl>>()
                {
                    //the type          will use calendar control
                    { typeof(DateTime), () => new Calendar() },
                    { typeof(TimeSpan), () => new TextBox() },
                    { typeof(bool), () => new CheckBox() }
                    //e.g. { typeof(YourCustomControl), (type) => new YourCustomControl() } }
                };

            Func<WebControl> relatedControlFunc = null;

            if (relatedControls.ContainsKey(propertyType))
                relatedControlFunc = relatedControls[propertyType];

            //if a related function is found
            if (relatedControlFunc != null)
            {
                //call the function to get the related control
                control = relatedControlFunc();
            }
            else
            {
                //otherwise as a fallback use a textbox
                control = new TextBox();
            }

            return control;
        }

        /// <summary>
        /// Gets the property type from a given property name and given the type of usercontrol
        /// </summary>
        /// <param name="propertyName">The name of the property</param>
        /// <param name="userControlType">the type of usercontrol</param>
        /// <returns>The type of the property (string etc)</returns>
        protected Type GetPropertyType(string propertyName, Type userControlType)
        {
            Type propertyType = null;
            PropertyInfo propertyInfo = userControlType.GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance);
            if (propertyInfo != null)
            {
                propertyType = propertyInfo.PropertyType;
            }
            return propertyType ?? typeof(string);
        }

    }
}


text:
logging
=======

A small, flexible logging framework for C libraries and applications.

Designed for use in large applications down to embedded systems.

Installing
----------

    $ git clone https://github.com/kanemathers/logging.git
    $ cd logging
    $ make
    $ sudo make install

Usage
-----

Include the header:

    #include <logging.h>

### Programmable

First thing you'll want to do is create your logger:

    logger_t *logger = logger_new();

Then create your handlers:

    handler_t *console = hconsole_new();
    handler_t *file    = hfile_new("/tmp/output.log");
    handler_t *syslog  = hsyslog_new("ident", LOG_LOCAL0);

Need to add those handlers to the logger. Specify a priority to filter the
output to that handler:

    logger_add_handler(logger, console, LOG_DEBUG);
    logger_add_handler(logger, file, LOG_DEBUG);
    logger_add_handler(logger, syslog, LOG_ERR);

And now you can start firing off log messages:

    logger_emit(logger, LOG_DEBUG, "syslog won't see this");
    logger_emit(logger, LOG_ERR, "all handlers will %s", "see this");

When you're done, cleanup:

    logger_free(logger);

### Config

You can also generate a logger instance from a config file:

    logger_t *logger = logger_from_config("./config.ini");

### Full Example

    #include <stdlib.h>
    #include <logging.h>

    int main()
    {
        logger_t *logger = logger_from_config("./config.ini");

        if (!logger)
            return EXIT_FAILURE;

        logger_emit(logger, LOG_DEBUG, "works!\n");

        logger_free(logger);

        return EXIT_SUCCESS;
    }


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Padrao extends MY_Controller {
    public $dados;

    public function __construct() {
        parent::__construct();
    }

    public function index() {
        $dados['teste'] = 'teste';

        $this->load->view('padrao', $dados);
    }
}


text:
import {
	Line
} from '../../../src/Three';

import { LineSegmentsGeometry } from './LineSegmentsGeometry';

export class LineGeometry extends LineSegmentsGeometry {

	constructor();
	isLineGeometry: boolean;

	fromLine( line: Line ): this;

}


text:
<?php
/**
 * Created by PhpStorm.
 * User: zsgy
 * Date: 2017/8/14
 * Time: 15:04
 */

namespace App\Repositories;

use App\Models\User;

/**
 * Class UserRepository
 * @package App\Repositories
 */
class UserRepository
{

    public function byId($id)
    {
        return User::find($id);
    }

    public function create(array $attribute)
    {
        return User::create($attribute);
    }

    public function getUserInfoBy($name)
    {
        return User::where('name', $name)->first();
    }

}