text:
package org.caleydo.core.data.collection.table;

import java.util.Map;
import java.util.concurrent.ForkJoinPool;

import javax.naming.OperationNotSupportedException;

import org.caleydo.core.data.collection.EDataClass;
import org.caleydo.core.data.collection.column.AColumn;
import org.caleydo.core.data.collection.column.NumericalColumn;
import org.caleydo.core.data.collection.column.container.IntContainer;
import org.caleydo.core.data.datadomain.ATableBasedDataDomain;
import org.caleydo.core.io.DataSetDescription;
import org.caleydo.core.io.KNNImputeDescription;
import org.caleydo.core.io.NumericalProperties;
import org.caleydo.core.util.color.mapping.ColorMapper;
import org.caleydo.core.util.color.mapping.ColorMarkerPoint;
import org.caleydo.core.util.function.DoubleStatistics;
import org.caleydo.core.util.function.ExpressionFunctions.EMonoOperator;
import org.caleydo.core.util.impute.KNNImpute;
import org.caleydo.core.util.impute.KNNImpute.Gene;
import org.caleydo.core.util.logging.Logger;
import org.caleydo.core.util.math.MathHelper;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;

import com.google.common.base.Stopwatch;
import com.google.common.collect.ImmutableList;

/**
 * Extension of {@link Table} to add functionality specific to homogeneous numerical tables, such as a joint
 * normalization, a joint maximum, etc.
 *
 * @author Alexander Lex
 */
public class NumericalTable extends Table {

	public class Transformation extends Table.Transformation {
		public static final String LOG2 = "Log2";
		public static final String LOG10 = "Log10";
	}

	private boolean artificialMin = false;
	private double min = Double.POSITIVE_INFINITY;

	private boolean artificialMax = false;
	private double max = Double.NEGATIVE_INFINITY;

	/** same as {@link DataSetDescription#getDataCenter()} */
	private Double dataCenter = null;

	private final NumericalProperties numericalProperties;

	private DoubleStatistics datasetStatistics;

	/**
	 * @param dataDomain
	 */
	public NumericalTable(ATableBasedDataDomain dataDomain) {
		super(dataDomain);
		numericalProperties = dataSetDescription.getDataDescription().getNumericalProperties();
	}

	/**
	 * Calculates a raw value based on min and max from a normalized value.
	 *
	 * @param normalized
	 *            a value between 0 and 1
	 * @return a value between min and max
	 */
	public double getRawForNormalized(String dataTransformation, double normalized) {

		if (dataTransformation.equals(Table.Transformation.LINEAR)) {
			return getMin() + normalized * (getMax() - getMin());
		} else if (dataTransformation.equals(Transformation.LOG2)) {
			// FIXME why is the transformation for log2 and log10 different except the base?
			double logMin = MathHelper.log(getMin(), 2);
			double logMax = MathHelper.log(getMax(), 2);
			double spread = logMax - logMin;

			double logRaw = logMin + normalized * spread;
			double raw = Math.pow(2, logRaw);
			return raw;
			// normalized = Math.pow(2, normalized);
		} else if (dataTransformation.equals(Transformation.LOG10)) {
			return EMonoOperator.LOG10.unapply(normalized);
		} else {
			throw new IllegalStateException("Unknown transformation" + dataTransformation);
		}

	}

	/**
	 * Calculates a normalized value based on min and max.
	 *
	 * @param raw
	 *            the raw value
	 * @return a value between 0 and 1
	 */
	public double getNormalizedForRaw(String dataTransformation, double raw) {
		double result;

		switch (dataTransformation) {
		case org.caleydo.core.data.collection.table.Table.Transformation.LINEAR:
			result = raw;
			break;
		case Transformation.LOG2:
			result = Math.log(raw) / Math.log(2);
			break;
		case Transformation.LOG10:
			result = Math.log10(raw);
			break;
		default:
			throw new IllegalStateException("Conversion raw to normalized not implemented for data rep"
					+ dataTransformation);
		}

		result = (result - getMin()) / (getMax() - getMin());

		return result;
	}

	/**
	 * @param dataCenter
	 *            setter, see {@link #dataCenter}
	 */
	public void setDataCenter(Double dataCenter) {
		this.dataCenter = dataCenter;
	}

	/**
	 * @return the dataCenter, see {@link #dataCenter}
	 */
	public Double getDataCenter() {
		return dataCenter;
	}

	/**
	 * Get the minimum value in the table.
	 *
	 * @throws OperationNotSupportedException
	 *             when executed on nominal data
	 * @return the absolute minimum value in the set
	 */
	public double getMin() {
		if (min == Double.POSITIVE_INFINITY) {
			calculateGlobalExtrema();
		}
		return min;
	}

	/**
	 * Get the maximum value in the table.
	 *
	 * @throws OperationNotSupportedException
	 *             when executed on nominal data
	 * @return the absolute minimum value in the set
	 */
	public double getMax() {
		if (max == Double.NEGATIVE_INFINITY) {
			calculateGlobalExtrema();
		}
		return max;
	}

	/**
	 * Set an artificial minimum for the datatable. All elements smaller than that are clipped to this value in the
	 * representation. This only affects the normalization, does not alter the raw data
	 */
	void setMin(double dMin) {
		artificialMin = true;
		this.min = dMin;
	}

	/**
	 * Set an artificial maximum for the Table. All elements smaller than that are clipped to this value in the
	 * representation. This only affects the normalization, does not alter the raw data
	 */
	void setMax(double dMax) {
		artificialMax = true;
		this.max = dMax;
	}

	private void calculateGlobalExtrema() {
		double temp = 1.0;

		if (!(columns.get(0) instanceof NumericalColumn<?, ?>)) {
			throw new UnsupportedOperationException("Minimum or maximum can be calculated only on numeric data");
		}

		for (AColumn<?, ?> column : columns) {
			NumericalColumn<?, ?> nColumn = (NumericalColumn<?, ?>) column;
			temp = new Double(nColumn.getMin());
			if (!artificialMin && temp < min) {
				min = temp;
			}
			temp = nColumn.getMax();
			if (!artificialMax && temp > max) {
				max = temp;
			}
		}
		if (dataCenter == null) {
			// in case we have data with both, positive and negative values
			// we assume it to be centered.
			if (min < 0 && max > 0)
				dataCenter = 0d;
		}
		if (dataCenter != null) {
			if (min > dataCenter || max < dataCenter) {
				dataCenter = null;

				Logger.log(new Status(
						IStatus.WARNING,
						this.toString(),
						"DataCentered was set to "
								+ dataCenter
								+ ", but min ("
								+ min
								+ ") is larger or max ("
								+ max
								+ ") is smaller than data center. This means that the dataCenter was inccoretly set. Setting dataCenter to null!"));
				return;
			}

			double lowerDelta = Math.abs(min - dataCenter);
			double upperDelta = Math.abs(max - dataCenter);
			double maxDelta;
			maxDelta = (lowerDelta > upperDelta) ? lowerDelta : upperDelta;
			max = dataCenter + maxDelta;
			min = dataCenter - maxDelta;

		}

	}

	// /**
	// * Calculates log10 on all dimensions in the table. Take care that the set contains only numerical dimensions,
	// since
	// * nominal dimensions will cause a runtime exception. If you have mixed data you have to call log10 on all the
	// * dimensions that support it manually.
	// */
	// void log10() {
	// for (AColumn<?, ?> dimension : columns) {
	// if (dimension instanceof NumericalColumn) {
	// NumericalColumn<?, ?> nDimension = (NumericalColumn<?, ?>) dimension;
	// nDimension.log10();
	// } else
	// throw new UnsupportedOperationException(
	// "Tried to calcualte log values on a set wich contains nominal dimensions. This is not possible!");
	// }
	// }
	//
	// /**
	// * Calculates log2 on all dimensions in the table. Take care that the set contains only numerical dimensions,
	// since
	// * nominal dimensions will cause a runtime exception. If you have mixed data you have to call log2 on all the
	// * dimensions that support it manually.
	// */
	// void log2() {
	// for (AColumn<?, ?> dimension : columns) {
	// if (dimension instanceof NumericalColumn) {
	// NumericalColumn<?, ?> nDimension = (NumericalColumn<?, ?>) dimension;
	// nDimension.log2();
	// } else
	// throw new UnsupportedOperationException("Tried to calcualte log values on a set wich has"
	// + "contains nominal dimensions. This is not possible!");
	// }
	// }

	/**
	 * Normalize all columns in the tablet, based on values of all dimensions. For a numerical dimension, this would
	 * mean, that global minima and maxima are retrieved instead of local ones (as is done with normalize()) Operates
	 * with the raw data as basis by default, however when a logarithmized representation is in the dimension this is
	 * used. Make sure that all dimensions are logarithmized.
	 */
	@Override
	protected void normalize() {
		if (numericalProperties != null && numericalProperties.getImputeDescription() != null)
			performImputation(numericalProperties.getImputeDescription());

		if (numericalProperties != null
				&& NumericalProperties.ZSCORE_ROWS.equals(numericalProperties.getzScoreNormalization())) {
			DoubleStatistics.Builder postStats = DoubleStatistics.builder();
			for (int rowCount = 0; rowCount < getNrRows(); rowCount++) {
				DoubleStatistics stats = computeRowStats(rowCount);
				for (AColumn<?, ?> column : columns) {
					@SuppressWarnings("unchecked")
					NumericalColumn<?, Float> nColumn = (NumericalColumn<?, Float>) column;
					double zScore = ((nColumn.getRaw(rowCount)) - stats.getMean()) / stats.getSd();

					nColumn.setRaw(rowCount, (float) zScore);
					postStats.add(zScore);
				}
			}
			datasetStatistics = postStats.build();
		} else if (numericalProperties != null
				&& NumericalProperties.ZSCORE_COLUMNS.equals(numericalProperties.getzScoreNormalization())) {
			DoubleStatistics.Builder postStats = DoubleStatistics.builder();
			for (AColumn<?, ?> column : columns) {
				@SuppressWarnings("unchecked")
				NumericalColumn<?, Float> nColumn = (NumericalColumn<?, Float>) column;
				DoubleStatistics stats = computeColumnStats(nColumn);

				for (int rowCount = 0; rowCount < getNrRows(); rowCount++) {
					double zScore = ((nColumn.getRaw(rowCount)) - stats.getMean()) / stats.getSd();
					nColumn.setRaw(rowCount, (float) zScore);
					postStats.add(zScore);
				}
			}
			datasetStatistics = postStats.build();
		} else {
			datasetStatistics = computeTableStats();
		}

		if (numericalProperties != null && numericalProperties.getClipToStdDevFactor() != null) {
			float nrDevs = numericalProperties.getClipToStdDevFactor();
			setMax(datasetStatistics.getMean() + nrDevs * datasetStatistics.getSd());
			setMin(datasetStatistics.getMean() - nrDevs * datasetStatistics.getSd());
			if (dataCenter == null) {
				// in case we have data with both, positive and negative values
				// we assume it to be centered.
				if (min < 0 && max > 0)
					dataCenter = 0d;
			}
		}

		for (AColumn<?, ?> column : columns) {
			NumericalColumn<?, ?> nColumn = (NumericalColumn<?, ?>) column;
			nColumn.setExternalMin(getMin());
			nColumn.setExternalMax(getMax());
			nColumn.normalize();
			// FIXME - need to re-think this
			nColumn.log2();
			nColumn.log10();

		}

		// setting the color marker points to 3 std devs
		ColorMapper mapper = getColorMapper();
		ColorMarkerPoint point = mapper.getMarkerPoints().get(0);
		double raw = datasetStatistics.getMean() - 3 * datasetStatistics.getSd();
		float normalized = (float) getNormalizedForRaw(defaultDataTransformation, raw);
		if (normalized < 0)
			normalized = 0;
		point.setRightSpread(normalized);

		point = mapper.getMarkerPoints().get(mapper.getMarkerPoints().size() - 1);
		raw = datasetStatistics.getMean() + 3 * datasetStatistics.getSd();
		normalized = (float) getNormalizedForRaw(defaultDataTransformation, raw);
		float distance = 1 - normalized;
		if (distance < 0)
			distance = 0;
		point.setLeftSpread(distance);
		mapper.update();
		// mapper.update();
	}

	/**
	 *
	 */
	private void performImputation(KNNImputeDescription desc) {

		Stopwatch w = new Stopwatch().start();
		ImmutableList.Builder<Gene> b = ImmutableList.builder();
		final int rows = getNrRows();
		final int cols = columns.size();

		// create data
		if (desc.getDimension().isRecord()) {
			for (int i = 0; i < rows; ++i) {
				float[] data = new float[cols];
				int nans = 0;
				int j = 0;
				for (AColumn<?, ?> column : columns) {
					@SuppressWarnings("unchecked")
					NumericalColumn<?, Float> nColumn = (NumericalColumn<?, Float>) column;
					Float raw = nColumn.getRaw(i);
					if (raw == null || raw.isNaN())
						nans++;
					data[j++] = raw == null ? Float.NaN : raw.floatValue();
				}
				b.add(new Gene(i, nans, data));
			}
		} else {
			int i = 0;
			for (AColumn<?, ?> column : columns) {
				float[] data = new float[rows];
				int nans = 0;
				@SuppressWarnings("unchecked")
				NumericalColumn<?, Float> nColumn = (NumericalColumn<?, Float>) column;

				for (int j = 0; j < rows; j++) {
					Float raw = nColumn.getRaw(i);
					if (raw == null || raw.isNaN())
						nans++;
					data[j++] = raw == null ? Float.NaN : raw.floatValue();
				}
				b.add(new Gene(i++, nans, data));
			}
		}

		System.out.println("NumericalTable.performImputation() data creation:\t" + w);
		w.reset().start();
		KNNImpute task = new KNNImpute(desc, b.build());
		ForkJoinPool pool = new ForkJoinPool();
		com.google.common.collect.Table<Integer, Integer, Float> impute = pool.invoke(task);
		pool.shutdown();
		System.out.println("NumericalTable.performImputation() computation:\t" + w);
		w.reset().start();

		// update data
		final boolean isColumnFirstDimension = desc.getDimension().isDimension();
		// in either case iterate over the columns first and update a columns at once
		for (Map.Entry<Integer, Map<Integer, Float>> entry : (isColumnFirstDimension ? impute.rowMap() : impute
				.columnMap()).entrySet()) {
			AColumn<?, ?> aColumn = columns.get(entry.getKey().intValue());
			@SuppressWarnings("unchecked")
			NumericalColumn<?, Float> nColumn = (NumericalColumn<?, Float>) aColumn;
			// apply updates
			for (Map.Entry<Integer, Float> entry2 : entry.getValue().entrySet()) {
				nColumn.setRaw(entry2.getKey(), entry2.getValue());
			}
		}
		System.out.println("NumericalTable.performImputation() update:\t" + w);
	}

	/**
	 * @return the datasetStatistics, see {@link #datasetStatistics}
	 */
	public DoubleStatistics getDatasetStatistics() {
		return datasetStatistics;
	}

	private DoubleStatistics computeColumnStats(NumericalColumn<?, Float> nColumn) {
		DoubleStatistics.Builder stats = DoubleStatistics.builder();
		for (int rowCount = 0; rowCount < getNrRows(); rowCount++) {
			stats.add(nColumn.getRaw(rowCount));
		}
		return stats.build();
	}

	private DoubleStatistics computeTableStats() {
		DoubleStatistics.Builder stats = DoubleStatistics.builder();
		for (AColumn<?, ?> column : columns) {
			NumericalColumn<?, ?> nColumn = (NumericalColumn<?, ?>) column;
			for (int rowCount = 0; rowCount < getNrRows(); rowCount++) {
				Number n = nColumn.getRaw(rowCount);
				if (nColumn.getDataClass() == EDataClass.NATURAL_NUMBER && n.intValue() == IntContainer.UNKNOWN_VALUE)
					n = Double.NaN;
				stats.add(n.doubleValue());
			}
		}
		return stats.build();
	}

	private DoubleStatistics computeRowStats(int row) {
		DoubleStatistics.Builder stats = DoubleStatistics.builder();
		for (AColumn<?, ?> column : columns) {
			NumericalColumn<?, ?> nColumn = (NumericalColumn<?, ?>) column;
			Number n = nColumn.getRaw(row);
			if (nColumn.getDataClass() == EDataClass.NATURAL_NUMBER && n.intValue() == IntContainer.UNKNOWN_VALUE)
				n = Double.NaN;
			stats.add(n.doubleValue());
		}
		return stats.build();
	}

	// /**
	// * Switch the representation of the data. When this is called the data in normalized is replaced with data
	// * calculated from the mode specified.
	// *
	// * @param dataTransformation
	// * Determines how the data is visualized. For options see {@link EDataTransformation}.
	// */
	// void setDataTransformation(EDataTransformation dataTransformation) {
	// if (dataTransformation == this.dataTransformation)
	// return;
	//
	// this.dataTransformation = dataTransformation;
	//
	// for (AColumn<?, ?> dimension : columns) {
	// if (dimension instanceof NumericalColumn) {
	// ((NumericalColumn<?, ?>) dimension).setDataTransformation(dataTransformation);
	// }
	// }
	//
	// switch (dataTransformation) {
	// case NONE:
	// break;
	// case LOG10:
	// log10();
	// break;
	// case LOG2:
	// log2();
	// break;
	// }
	// }

	@Override
	public boolean isDataHomogeneous() {
		return true;
	}

}


text:
VerdictDB is a thin Java library placed between the user (or an application) and the backend database. Its Python library, i.e., `pyverdict`, also relies on the Java library. The user can make a connection to VerdictDB either using the standard JDBC or the public API provided by VerdictDB. VerdictDB communicates with the backend database also using JDBC except for special cases (e.g., Apache Spark's SparkSession).

<!-- <img width="400px" class="img-responsive center" style="margin: 0 auto;" src="http://verdictdb.org/image/verdict-architecture.png" /> -->

![archi](http://verdictdb.org/image/verdict-architecture.png){: .center width="400px"}

## Internal Architecture

VerdictDB has the following hierarchical structure. In the list below, an item that comes earlier in the following list depends (only) on the item that comes after the item. For example, JDBC Wrapper relies on VerdictContext. However, JDBC Wrapper does not directly rely on ExecutionContext.

1. JDBC Wrapper (public interface)
1. VerdictContext (public interface)
1. ExecutionContext
1. QueryCoordinator
1. ExecutionPlan
1. ExecutionNode

### Connection (VerdictContext)

When the user makes a connection to VerdictDB using VerdictContext. VerdictDB's JDBC interface is simply a wrapper over VerdictContext. VerdictContext contains the information sufficient to connect to the backend database. If the user wishes VerdictDB to connect to the backend database using the JDBC interface, it is recommended to pass a connection string; then, VerdictDB creates multiple (10 by default) connections for concurrent query executions. The concurrent query executions make it possible to interleave short, light-weight queries (e.g., metadata retrieval) among long, data-intensive queries (e.g., aggregations).

### Execution (ExecutionContext)

When the user issues a query, VerdictDB lets VerdictContext create a new instance of ExecutionContext. The instance of ExecutionContext is responsible for the execution of the single query. After the query execution is finished, the ExecutionContext instance is removed from VerdictContext's ExecutionContext list. JVM then may garbage-collect it. For the query execution, ExecutionContext creates a different type of QueryCoordinator instance, as describe below.

### Actual Query Processing (QueryCoordinator)

Depending on the query type, a different type of QueryCoordinator is created. An important type (or class) is SelectQueryCoordinator. SelectQueryCoordinator parses and converts a given select query into a Java object. The Java object represents relational operations in a platform-independent way (since different DBMS have different SQL syntaxes). Then, SelectQueryCoordinator plans how to execute the Java object. Finally, the plan is executed. See below for more details about the plan.

### Plan and Nodes (ExecutionPlan and ExecutionNode)

VerdictDB's most internal query executions are based on ExecutionPlan and ExecutionNode. A few exceptions are simple metadata updates. Here, we describe the general concepts about plans and nodes. How the plans and nodes are created, given a select query, is described on [this page](/how_it_works/query_processing).

An ExecutionPlan instance is a [directed acyclic graph](https://en.wikipedia.org/wiki/Directed_acyclic_graph) that consists of one or more ExecutionNode instances. An ExecutionNode instance corresponds to a single select query without any subqueries (either projection or aggregation). The directed edge between two ExecutionNode instances indicates the dependency: the parent node depends on some information returned by the child node. Each node runs on a separate Java thread for maximum concurrency.

redpajama_set_name: RedPajamaGithub


text:
#import "RCTDisplayWeakRefreshable.h"

@implementation RCTDisplayWeakRefreshable

+ (CADisplayLink *)displayLinkWithWeakRefreshable:(id<RCTDisplayRefreshable>)refreshable {
  RCTDisplayWeakRefreshable *target = [[RCTDisplayWeakRefreshable alloc] initWithRefreshable:refreshable];
  return [CADisplayLink displayLinkWithTarget:target selector:@selector(displayDidRefresh:)];
}

- (instancetype)initWithRefreshable:(id<RCTDisplayRefreshable>)refreshable
{
  if (self = [super init]) {
    _refreshable = refreshable;
  }
  return self;
}

- (void)displayDidRefresh:(CADisplayLink *)displayLink {
  [_refreshable displayDidRefresh:displayLink];
}

@end


text:
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Text;

namespace Gallio.Common.Collections
{
    /// <summary>
    /// Encapsulates various strategies for counting the number of elements in a collection, an array, or
    /// a simple enumerable type.
    /// </summary>
    public class EnumerableCounter
    {
        private readonly IEnumerable values;

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="values">The collection, the array, or the simple enumerable object to count elements.</param>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="values"/> is null.</exception>
        public EnumerableCounter(IEnumerable values)
        {
            if (values == null)
                throw new ArgumentNullException("values");

            this.values = values;
        }

        /// <summary>
        /// Counts the number of elements in a collection, an array, or any other enumerable type, by
        /// using the most appropriate strategies.
        /// </summary>
        /// <returns>An enumeration of counting strategies applicable to the specified enumerable values.</returns>
        public IEnumerable<ICountingStrategy> Count()
        {
            var methods = new Func<IEnumerable<ICountingStrategy>>[]
            {
                ForArray,
                ForGenericCollection,
                ForNonGenericCollection,
                ForSimpleEnumerable,
            };

            foreach (var method in methods)
            {
                bool found = false;

                foreach (var strategy in method())
                {
                    found = true;
                    yield return strategy;
                }

                if (found)
                    break;
            }
        }

        private IEnumerable<ICountingStrategy> ForArray()
        {
            if (values is Array)
            {
                yield return CountingStrategy.ByLengthGetter((Array)values);
            }
        }

        private IEnumerable<ICountingStrategy> ForGenericCollection()
        {
            var collection = values as ICollection;

            if (!ReferenceEquals(null, collection))
            {
                yield return CountingStrategy.ByCountGetter(() => collection.Count);
                yield return CountingStrategy.ByEnumeratingElements(values);
            }
        }

        private IEnumerable<ICountingStrategy> ForNonGenericCollection()
        {
            foreach (Type type in values.GetType().GetInterfaces())
            {
                if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(ICollection<>))
                {
                    yield return CountingStrategy.ByCountGetter(() => (int)type.GetProperty("Count").GetValue(values, null));
                    yield return CountingStrategy.ByEnumeratingElements(values);
                }
            }
        }

        private IEnumerable<ICountingStrategy> ForSimpleEnumerable()
        {
            var type = values.GetType();
            var property = type.GetProperty("Count", BindingFlags.Instance | BindingFlags.Public, null, typeof(int), EmptyArray<Type>.Instance, null);

            if (property != null)
                yield return CountingStrategy.ByReflectedCountGetter(() => (int)property.GetValue(values, null));

            yield return CountingStrategy.ByEnumeratingElements(values);
        }
    }

    /// <summary>
    /// Represents a strategy for counting the number of elements in a collection, an array, or a simple enumerable type.
    /// </summary>
    public interface ICountingStrategy
    {
        /// <summary>
        /// Gets the name of the counting strategy.
        /// </summary>
        CountingStrategyName Name
        {
            get;
        }

        /// <summary>
        /// Gets a displayable description of the counting strategy.
        /// </summary>
        string Description
        {
            get;
        }

        /// <summary>
        /// Returns the number of elements found by applying the current counting strategy.
        /// </summary>
        /// <returns>The number of elements found.</returns>
        int Count
        {
            get;
        }
    }

    /// <summary>
    /// Name of the existing counting strategies.
    /// </summary>
    public enum CountingStrategyName
    {
        /// <summary>
        /// Counts by getting the value returned by the <see cref="Array.Length"/> property getter.
        /// </summary>
        ByLengthGetter,

        /// <summary>
        /// Counts by getting the value returned by the <see cref="ICollection.Count"/> or <see cref="ICollection{T}.Count"/> property getter.
        /// </summary>
        ByCountGetter,

        /// <summary>
        /// Counts by enumerating the elements returned by <see cref="IEnumerable.GetEnumerator"/>.
        /// </summary>
        ByEnumeratingElements,

        /// <summary>
        /// Counts by getting the value returned by an existing public "Count" property getter.
        /// </summary>
        ByReflectedCountGetter,
    }

    internal class CountingStrategy : ICountingStrategy
    {
        private readonly string description;
        private readonly CountingStrategyName name;
        private readonly Lazy<int> lazyCount;

        private CountingStrategy(CountingStrategyName name, string description, Func<int> counting)
        {
            this.name = name;
            this.description = description;
            lazyCount = new Lazy<int>(counting);
        }

        public CountingStrategyName Name
        {
            get
            {
                return name;
            }
        }

        public int Count
        {
            get
            {
                return lazyCount.Value;
            }
        }

        public string Description
        {
            get
            {
                return description;
            }
        }

        public static ICountingStrategy ByLengthGetter(Array array)
        {
            return new CountingStrategy(CountingStrategyName.ByLengthGetter, "By Length Property", () => array.Length);
        }

        public static ICountingStrategy ByCountGetter(Func<int> countReader)
        {
            return new CountingStrategy(CountingStrategyName.ByCountGetter, "By Count Property", countReader);
        }

        public static ICountingStrategy ByEnumeratingElements(IEnumerable values)
        {
            return new CountingStrategy(CountingStrategyName.ByEnumeratingElements, "By Enumerating Elements", () =>
            {
                int count = 0;
                var enumerator = values.GetEnumerator();

                while (enumerator.MoveNext())
                    count++;

                return count;
            });
        }

        public static ICountingStrategy ByReflectedCountGetter(Func<int> countReader)
        {
            return new CountingStrategy(CountingStrategyName.ByReflectedCountGetter, "By Reflected Count Property", countReader);
        }
    }
}


text:
--TEST--
XMLWriter: libxml2 XML Writer, Elements & Attributes
--SKIPIF--
<?php
if (!extension_loaded("xmlwriter")) die("skip");
if (LIBXML_VERSION < 20629) die("skip: libxml2 2.6.29+ required");
?>
--FILE--
<?php
/* $Id$ */

$xw = xmlwriter_open_memory();
xmlwriter_set_indent($xw, TRUE);
xmlwriter_set_indent_string($xw, '   ');
xmlwriter_start_document($xw, '1.0', "UTF-8");
xmlwriter_start_element($xw, 'root');
xmlwriter_start_element_ns($xw, 'ns1', 'child1', 'urn:ns1');
xmlwriter_start_attribute_ns($xw, 'ns1', 'att1', 'urn:ns1');
xmlwriter_text($xw, 'a&b');
xmlwriter_end_attribute($xw);
xmlwriter_write_attribute($xw, 'att2', "double\" single'");
xmlwriter_start_attribute_ns($xw, 'ns1', 'att2', 'urn:ns1');
xmlwriter_text($xw, "<>\"'&");
xmlwriter_end_attribute($xw);
xmlwriter_write_element($xw, 'chars', "special characters: <>\"'&");
xmlwriter_end_element($xw);
xmlwriter_end_document($xw);
// Force to write and empty the buffer
$output = xmlwriter_flush($xw, true);
print $output;
?>
--EXPECT--
<?xml version="1.0" encoding="UTF-8"?>
<root>
   <ns1:child1 ns1:att1="a&b" att2="double" single'" ns1:att2="<>"'&" xmlns:ns1="urn:ns1">
      <chars>special characters: <>"'&</chars>
   </ns1:child1>
</root>


text:
pyramid_decoy
=============

.. image:: https://img.shields.io/pypi/v/pyramid_decoy.svg
    :target: https://pypi.python.org/pypi/pyramid_decoy/
    :alt: Latest PyPI version

.. image:: https://readthedocs.or/projects/pyramid_decoy/badge/?version=v0.2.0
    :target: http://pyramid_decoy.readthedocs.io/en/v0.2.0/
    :alt: Documentation Status

.. image:: https://img.shields.io/pypi/wheel/pyramid_decoy.svg
    :target: https://pypi.python.org/pypi/pyramid_decoy/
    :alt: Wheel Status

.. image:: https://img.shields.io/pypi/pyversions/pyramid_decoy.svg
    :target: https://pypi.python.org/pypi/pyramid_decoy/
    :alt: Supported Python Versions

.. image:: https://img.shields.io/pypi/l/pyramid_decoy.svg
    :target: https://pypi.python.org/pypi/pyramid_decoy/
    :alt: License

pyramid_decoy, a simple pyramid app, which solely purpose is to redirect traffic away
to configured location, with hooks (in the future) to be able to plug in a tracking code.

Package resources
-----------------

* Bug tracker: https://github.com/fizyk/pyramid_decoy/issues
* Documentation: http://pyramid_decoy.readthedocs.org/

Travis-ci
---------

After creating package on github, move to tracis-ci.org, and turn on ci builds for given package.


text:
Sagas are stateful event-based message consumers -- they retain state. Therefore, saving state between
events is important. Without persistent state, a saga would consider each event a new event, and orchestration
of subsequent events would be meaningless.

- [Specifying saga persistence](#specifying-saga-persistence)
- [Identity](#identity)
- [Publishing and Sending From Sagas](#publishing-and-sending-from-sagas)
- [Storage Engines](#storage-engines)
    - [Entity Framework](#entity-framework)
    - [MongoDB](#mongodb)
    - [NHibernate](#nhibernate)
    - [Redis](#redis)
    - [Marten](#marten)
    - [Azure Service Bus](#azure-service-bus)

## Specifying saga persistence

In order to store the saga state, you need to use one form of saga persistence. There are several
types of storage that MassTransit supports, all of those, which are included to the main distribution,
are listed below. There is also a in-memory unreliable storage, which allows to temporarily store
your saga state. It is useful to try things out since it does not require any infrastructure.

Simple initialization of a state machine saga with persistence looks like this:

```csharp
var sagaStateMachine = new ShoppingCartStateMachine();
var repository = new InMemorySagaRepository<ShoppingCart>();
var busControl = Bus.Factory.CreateUsingRabbitMq(x =>
{
    var host = x.Host(new Uri("rabbitmq://localhost"), h =>
    {
        h.Username("guest");
        h.Password("guest");
    });

    x.ReceiveEndpoint(host, "shopping_cart_state", e =>
    {
        e.StateMachineSaga(sagaStateMachine, repository);
    });
});
```

It is important to notice that the saga repository object is a singleton. It does not hold any state
inside the class instance and only performs operations on the saga state objects that are send to it
to persist and retrieve.

There are two types of saga repository:
* Query repository
* Identity-only repository

Depending on the persistence mechanism, repository implementation can be either identity-only or
identity plus query.

When using identity-only repository, such as Azure Service Bus message session or Redis, you can
only use correlation by identity. This means that all events that the saga receives, must hold
the saga correlation id, and the correlation for each event can only use `CorrelateById` method
to define the correlation.

Query repository by definition support identity correlation too, but in addition support other
properties of events being received and saga state properties. Such correlations are defined using
`CorrelateBy` method and you can use any logical expression that involve the event data and
saga state data to establish such correlation. Repository implementation such as Entity Framework,
NHibernate and Marten support correlation by query. Of course, in-memory repository supports it as well.

## Identity

Saga instances are identified by a unique identifier (`Guid`), represented by the `CorrelationId` on the saga instance.
Events are correlated to the saga instance using either the unique identifier, or alternatively using an expression
that correlates properties on the saga instance to each event. If the `CorrelationId` is used, it's always a
one-to-one match, either the saga already exists, or it's a new saga instance. With a correlation expression,
the expression might match to more than one saga instance, so care should be used -- because the event would be
delivered to all matching instances.

> Seriously, don't sent an event to all instances -- unless you want to watch your messages consumers lock
> your entire saga storage engine.

It is strongly advised to have `CorrelationId` as your table/document key. This will enable better
concurrency handling and will make the saga state consistent.

## Publishing and Sending From Sagas

Sagas are completely message-driven and therefore not only consume but also publish events and send commands.
However, if your saga received a lot of messages coming roughly at the same time and the endpoint is set to
process multiple messages in parallel - this can lead to a conflict between message processing and saga persistence.

This means that there could be more than one saga state updates that are being persisted at the same time.
Depending on the saga repository type, this might fail for different reasons - versioning issue, row or table
lock or eTag mismatch. All those problems are basically saying that you are having a concurrency issue.

It is normal for the saga repository to throw an exception in such case but if your saga is publishing messages,
they were already published but the saga state has not been updated. MassTransit will eventually use retry policy
on the endpoint and more messages will be send, potentially leading to mess. Or, if there are no retry policies
configured, messages might be sent indicating that the process needs to continue but saga instance will be in the
old state and will not accept any further messages because they will come in a wrong state.

This issue is common and can be solved by postponing the message publish and send operations until all
persistence work is done. All messages that should be published, are collected in a buffer, which is
called *Outbox*. MassTransit implements this feature and it can be configured by adding these lines to your
endpoint configuration:

```csharp
c.ReceiveEndpoint("queue", e =>
{
    e.UseInMemoryOutbox();
    // other endpoint configuration here
}
```

## Storage Engines

MassTransit supports several storage engines, including NHibernate, Entity Framework, MongoDB and Redis.
Each of these are setup in a similar way, but examples are shown below for each engine.

* [Entity Framework](#entity-framework)
* [NHibernate](#nhibernate)
* [MondoDB](#mongodb)
* [Redis](#redis)
* [Marten](#marten)
* [Azure Service Bus](#azure-service-bus)

### Optimistic vs pessimistic concurrency

Most persistence mechanisms for sagas supported by MassTransit need some way to guarantee ACID when processing sagas.
Because there can be multiple threads _consuming_ multiple bus events meant for the same saga instance,
they could end up overwriting each other (race condition).

Relational databases can easily handle this by setting the transaction type to *serializable* or (page/row) locking.
This would be considered as _pessimistic concurrency_.

Another way to handle concurrency is to have some attribute like version or timestamp, which updates
every time a saga is persisted. By doing that we can instruct the database only to update the
record if this attribute matches between what we are trying to persist and what is stored in the
database record we are trying to update.

This is type of concurrency is called an _optimistic concurrency_.
It doesn't guarantee your unit of work with the database will succeed (must retry after these exceptions),
but it also doesn't block anybody else from working within the same database page (not locking the table/page).

#### So, which one should I use?

For almost every scenario, it is recommended using the optimistic concurrency, because most state machine
logic should be fairly quick.

If the chosen persistence method supports optimistic concurrency, race conditions can be handled rather
easily by specifying a retry policy for concurrency exceptions or using generic retry policy.

### Entity Framework

Entity Framework seems to be the most common ORM for class-SQL mappings, and SQL is still widely used
for storing data. So it's a win to have it supported out of the box by MassTransit.

#### Concurrency handling
Fortunately, Entity Framework is a repository pattern itself, and has a column type `[Timestamp]`
(a.k.a. `IsRowVersion` with fluent mapping), which will check the value of the column when it starts it's
"unit of work" and if that value is the same when updating that row in the database - everybody is happy!
But, if that column value is different, then it has been updated elsewhere.
So, the Entity Framework will throw a `DbUpdateConcurrencyException`, which can be handled by a retry policy
to fix the concurrency violation.

#### Configuration and usage
The code-first mapping example below shows the basics of getting started. The lines have been commented
where the additional optimistic concurrency column is needed.

```csharp
public class SagaInstance : SagaStateMachineInstance
{
    public SagaInstance(Guid correlationId)
    {
        CorrelationId = correlationId;
    }

    protected SagaInstance()
    {
    }

    public string CurrentState { get; set; }
    public string ServiceName { get; set; }
    public Guid CorrelationId { get; set; }
    public byte[] RowVersion { get; set; } // For Optimistic Concurrency
}

public class SagaInstanceMap : SagaClassMapping<SagaInstance>
{
    public SagaInstanceMap()
    {
        Property(x => x.CurrentState);
        Property(x => x.ServiceName, x => x.Length(40));
        Property(x => x.RowVersion).IsRowVersion(); // For Optimistic Concurrency
    }
}
```

> Important:
> The `SagaClassMapping` has default mapping for the `CorrelationId` as a database generated primary key.
> If you use your own mapping, you must follow the same convention, otherwise there is a big chance to
> get deadlock exceptions in case of high throughput.

The repository is then created on the context factory:
```csharp
SagaDbContextFactory contextFactory = () =>
    new SagaDbContext<SagaInstance, SagaInstanceMap>(_connectionString);

var repository = new EntityFrameworkSagaRepository<SagaInstance>(
    contextFactory, optimistic: true); // true For Optimistic Concurrency, false is default for pessimistic
```

Lastly, the snippet below is _only needed for optimistic concurrency_, because the saga
should retry processing if failure occurred when writing to the database.
This snippet is adding [retry policies](../../usage/retries.md) middleware to the
saga receive endpoint from the [first section](#specifying-saga-persistence).

```csharp
x.ReceiveEndpoint(host, "shopping_cart_state", e =>
{
    e.UseRetry(x =>
        {
            x.Handle<DbUpdateConcurrencyException>();
            x.Interval(5, TimeSpan.FromMilliseconds(100)));
        }); // Add the retry middleware for optimistic concurrency
    e.StateMachineSaga(sagaStateMachine, repository);
});
```

Hence, that if you have retry policy without an exception filter, it will also handle
the concurrency exception, so explicit configuration is not required in this case.

### MongoDB

MongoDB is an easy to use saga repository, because setup is easy. There is no need for class mapping,
the saga instances can be persisted easily using a MongoDB collection.

#### Concurrency

MongoDb saga persistence requires that saga instance classes implement `IVersionedSaga` interface.
This interface has a `Version` property, which allows the saga persistence to handle optimistic
concurrency.

#### Configuration and usage

```csharp
public class SagaInstance : SagaStateMachineInstance, IVersionedSaga
{
    public SagaInstance(Guid correlationId)
    {
        CorrelationId = correlationId;
    }

    protected SagaInstance() { }

    public string CurrentState { get; set; }
    public string ServiceName { get; set; }
    public Guid CorrelationId { get; set; }
    public int Version { get; set; }
}
```

The saga repository is created using the simple syntax:

```csharp
var database = new MongoClient("mongodb://127.0.0.1").GetDatabase("sagas");
var repository = new MongoDbSagaRepository<SagaInstance>(database);
```

Each saga instance will be placed in a collection specific to the instance type.

### NHibernate

NHibernate is a widely used ORM and it is supported by MassTransit for saga storage.
The example below shows the code-first approach to using NHibernate for saga persistence.

#### Concurrency

NHibernate natively supports multiple concurrency handling mechanisms.
The easiest is probably adding a `Version` property of type `int` to the saga instance class
and map it to the column with the same name. NHibernate will use it by default.

#### Configuration and usage

```csharp
public class SagaInstance : SagaStateMachineInstance
{
    public SagaInstance(Guid correlationId)
    {
        CorrelationId = correlationId;
    }

    protected SagaInstance() { }

    public string CurrentState { get; set; }
    public string ServiceName { get; set; }
    public Guid CorrelationId { get; set; }
    public int Version { get; set; } // for optimistic concurrency
}

public class SagaInstanceMap : SagaClassMapping<SagaInstance>
{
    public SagaInstanceMap()
    {
        Property(x => x.CurrentState);
        Property(x => x.ServiceName, x => x.Length(40));
        Property(x => x.Version); // for optimistic concurrency
    }
}
```

The `SagaClassMapping` base class maps the `CorrelationId` of the saga, and handles some of the basic
bootstrapping of the class map. All other properties, including the property for the `CurrentState`
(if you're using state machine sagas), must be mapped by the developer. Once mapped, the `ISessionFactory`
can be created using NHibernate directly. From the session factory, the saga repository can be created.

> Important:
> The `SagaClassMapping` has default mapping for the `CorrelationId` as a database generated primary key.
> If you use your own mapping, you must follow the same convention, otherwise there is a big chance to
> get deadlock exceptions in case of high throughput.

```csharp
ISessionFactory sessionFactory = CreateSessionFactory();
var repository = new NHibernateSagaRepository<SagaInstance>(sessionFactory);
```

### Redis

Redis is a very popular key-value store, which is known for being very fast.

Redis does not support queries, therefore Redis saga persistence only supports correlation by id.
If you try to use correlation by expressions, you will get a "not implemented" exception.

Saga persistence for Redis uses `ServiceStack.Redis` library and it support both BSD-licensed v3.9.71
and the latest commercial versions as well.

Saga instance class must implement `IHasGuid` interface and the `Id` property, that must return the
value of the `CorrelationId` property:

```csharp
public class SagaInstance :
    SagaStateMachineInstance, IHasGuidId
{
    public Guid CorrelationId { get; set; }
    public Guid Id => CorrelationId;
    public string CurrentState { get; set; }

    public string CustomData { get; set; }
}
```

#### Concurrency

Redis saga persistence does not acquire locking on the database record when writing it so potentially
you can have write conflict in case the saga is updating its state frequently (hundreds of times per second).
To resolve this, the saga instance can implement the `IVersionedSaga` interface and include the Version property:

```csharp
public int Version { get; set; }
```

When the version of the instance that is being updated is lower than the expected version,
the saga repository will trow an exception and force the message to be retried, potentially resolving the issue.

#### Redis client initialization

The Redis saga repository requires `ServiceStack.Redis.IRedisClientsManager` as constructor parameter.
For containerless initialization the code would look like:

```csharp
var redisConnectionString = "redis://localhost:6379";
var repository = new RedisSagaRepository<SagaInstance>(
    new RedisManagerPool(redisConnectionString));
```

If you use a container, you can use the code like this (example for Autofac):

```csharp
var redisConnectionString = "redis://localhost:6379";
builder.Register<IRedisClientsManager>(c =>
    new RedisManagerPool(redisConnectionString)).SingleInstance();
builder.RegisterGeneric(typeof(RedisSagaRepository<>))
    .As(typeof(ISagaRepository<>)).SingleInstance();
```

### Marten

[Marten][2] is an open-source library that provides an API to the PostgreSQL [JSONB storage][1], influenced by
RavenDb client API. It allows to use PostgreSQL as schema-less NoSQL document storage. Unlike typical document
databases, PostgreSQL JSONB storage provides you the ACID-compliant transactional store with full consistency.

To use Marten and PostgreSQL as saga persistence, you need to install `MassTransit.Marten` NuGet package and
add some code.

First, your saga state class needs to mark the correlationId property with the `[Identity]` attribute. By this
you inform Marten that correlationId will be used as the primary key.

```csharp
public class SampleSaga : ISaga
{
    [Identity]
    public Guid CorrelationId { get; set; }
    public string State { get; set; }
    public string SomeProperty { get; set; }
}
```

Then you need to initialize the document store and the repository. Repository needs the store as its constructor
parameter.

```csharp
var connectionString =
    "server=localhost;port=5432;database=test;user id=test;password=test;";
var store = DocumentStore.For(connectionString);
var repository = new MartenSagaRepository<SampleSaga>(store);
```

If you use a container, you can use the code like this (example for Autofac):

```csharp
var connectionString =
    "server=localhost;port=5432;database=test;user id=test;password=test;";
builder.Register<IDocumentStore>(c => DocumentStore.For(connectionString);
builder.RegisterGeneric(typeof(MartenSagaRepository<>))
    .As(typeof(ISagaRepository<>)).SingleInstance();
```

Marten will create the necessary tables for you. This type of saga repository
supports correlation by id and custom expressions.

#### Concurrency

Marten supports optimistic concurrency by using an eTag-like version field in the metadata.
This means that the saga instance class does not need any additional fields for version.

There are two ways to use this feature:

1) Apply `[UseOptimisticConcurrency]` attribute to the saga instance class

```csharp
[UseOptimisticConcurrency]
public class SampleSaga : ISaga
{
    [Identity]
    public Guid CorrelationId { get; set; }
    ...
}
```

2. Configure the store to use optimistic concurrency for your saga instance class

 ```csharp
 var store = DocumentStore.For(_ =>
 {
     // Adds optimistic concurrency checking to Issue
     _.Schema.For<SampleSaga>().UseOptimisticConcurrency(true);
 });
 ```

### Azure Service Bus

Azure Service Bus provides a feature called *message sessions*, to process multiple messages at once and
to store some state on a temporary basis, which can be retrieved by some key.

The latter give us an ability to use this feature as saga state storage. Using message sessions
as saga persistence, you can only use Azure Service Bus for both messaging and saga persistence purposes,
without needing any additional infrastructure.

There is a limitation for using message sessions - this feature is not supported for AMQP transport.

You have to explicitly enable message sessions when configuring the endpoint, and use parameterless
constructor to instantiate the saga repository.

Here is the basic sample of how to use the Azure Service Bus message session as saga repository:

```csharp
var sagaStateMachine = new MySagaStateMachine();
var repository = new MessageSessionSagaRepository<MySaga>();
sbc.ReceiveEndpoint(host, "test_queue", ep =>
{
    ep.RequiresSession = true;
    ep.StateMachineSaga(sagaStateMachine, repository);
});
```

As mentioned before, the message session allows storing and retrieving any state by some unique key.
This means that this type of saga persistence only support correlation by id. So, similar to Redis
saga persistence, you cannot use `CorrelateBy` to specify how to find the saga instance, but only
`CorrelateById`.

[1]: https://www.postgresql.org/docs/9.5/static/functions-json.html
[2]: http://jasperfx.github.io/marten/


text:
import random

from marrow.mailer.exc import TransportFailedException, TransportExhaustedException

from marrow.util.bunch import Bunch

__all__ = ['MockTransport']

log = __import__('logging').getLogger(__name__)

class MockTransport(object):
    """A no-op dummy transport.

    Accepts two configuration directives:

     * success - probability of successful delivery
     * failure - probability of failure
     * exhaustion - probability of exhaustion

    All are represented as percentages between 0.0 and 1.0, inclusive.
    (Setting failure or exhaustion to 1.0 means every delivery will fail
    badly; do not do this except under controlled, unit testing scenarios!)
    """

    __slots__ = ('ephemeral', 'config')

    def __init__(self, config):
        base = {'success': 1.0, 'failure': 0.0, 'exhaustion': 0.0}
        base.update(dict(config))
        self.config = Bunch(base)

    def startup(self):
        pass

    def deliver(self, message):
        """Concrete message delivery."""

        config = self.config
        success = config.success
        failure = config.failure
        exhaustion = config.exhaustion

        if getattr(message, 'die', False):
            1/0

        if failure:
            chance = random.randint(0,100001) / 100000.0
            if chance < failure:
                raise TransportFailedException("Mock failure.")

        if exhaustion:
            chance = random.randint(0,100001) / 100000.0
            if chance < exhaustion:
                raise TransportExhaustedException("Mock exhaustion.")

        if success == 1.0:
            return True

        chance = random.randint(0,100001) / 100000.0
        if chance <= success:
            return True

        return False

    def shutdown(self):
        pass


text:
layout: null
---

<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">

 <title>What about Angela & Silvester?</title>
 <link href="{{ site.url }}/atom.xml" rel="self"/>
 <link href="{{ site.url }}/"/>
 <updated>{{ site.time | date_to_xmlschema }}</updated>
 <id>{{ site.url }}</id>
 <author>
   <name>Angela & Silvester</name>
   <email>{{ site.author.email }}</email>
 </author>

 {% for post in site.posts %}
 <entry>
   <title>{{ post.title }}</title>
   <link href="{{ site.url }}{{ post.url }}"/>
   <updated>{{ post.date | date_to_xmlschema }}</updated>
   <id>{{ site.url }}{{ post.id }}</id>
   <content type="html">{{ post.content | xml_escape }}</content>
 </entry>
 {% endfor %}

</feed>


text:
<Type Name="X509Stores" FullName="Mono.Security.X509.X509Stores">
  <TypeSignature Language="C#" Value="public class X509Stores" Maintainer="auto" />
  <AssemblyInfo>
    <AssemblyName>Mono.Security</AssemblyName>
    <AssemblyPublicKey>[00 24 00 00 04 80 00 00 94 00 00 00 06 02 00 00 00 24 00 00 52 53 41 31 00 04 00 00 01 00 01 00 79 15 99 77 D2 D0 3A 8E 6B EA 7A 2E 74 E8 D1 AF CC 93 E8 85 19 74 95 2B B4 80 A1 2C 91 34 47 4D 04 06 24 47 C3 7E 0E 68 C0 80 53 6F CF 3C 3F BE 2F F9 C9 79 CE 99 84 75 E5 06 E8 CE 82 DD 5B 0F 35 0D C1 0E 93 BF 2E EE CF 87 4B 24 77 0C 50 81 DB EA 74 47 FD DA FA 27 7B 22 DE 47 D6 FF EA 44 96 74 A4 F9 FC CF 84 D1 50 69 08 93 80 28 4D BD D3 5F 46 CD FF 12 A1 BD 78 E4 EF 00 65 D0 16 DF]</AssemblyPublicKey>
    <AssemblyVersion>1.0.5000.0</AssemblyVersion>
    <AssemblyVersion>2.0.0.0</AssemblyVersion>
  </AssemblyInfo>
  <ThreadSafetyStatement>Gtk# is thread aware, but not thread safe; See the <link location="node:gtk-sharp/programming/threads">Gtk# Thread Programming</link> for details.</ThreadSafetyStatement>
  <Base>
    <BaseTypeName>System.Object</BaseTypeName>
  </Base>
  <Interfaces />
  <Docs>
    To be added
    <remarks>To be added</remarks>
  </Docs>
  <Members>
    <Member MemberName="Clear">
      <MemberSignature Language="C#" Value="public void Clear ();" />
      <MemberType>Method</MemberType>
      <ReturnValue>
        <ReturnType>System.Void</ReturnType>
      </ReturnValue>
      <Parameters />
      <Docs>
        To be added
        <remarks>To be added</remarks>
      </Docs>
      <AssemblyInfo>
        <AssemblyVersion>1.0.5000.0</AssemblyVersion>
        <AssemblyVersion>2.0.0.0</AssemblyVersion>
      </AssemblyInfo>
    </Member>
    <Member MemberName="IntermediateCA">
      <MemberSignature Language="C#" Value="public Mono.Security.X509.X509Store IntermediateCA { get; }" />
      <MemberType>Property</MemberType>
      <ReturnValue>
        <ReturnType>Mono.Security.X509.X509Store</ReturnType>
      </ReturnValue>
      <Parameters />
      <Docs>
        To be added
        <value>a <see cref="T:Mono.Security.X509.X509Store" /></value>
        <remarks>To be added</remarks>
      </Docs>
      <AssemblyInfo>
        <AssemblyVersion>1.0.5000.0</AssemblyVersion>
        <AssemblyVersion>2.0.0.0</AssemblyVersion>
      </AssemblyInfo>
    </Member>
    <Member MemberName="Open">
      <MemberSignature Language="C#" Value="public Mono.Security.X509.X509Store Open (string storeName, bool create);" />
      <MemberType>Method</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>1.0.5000.0</AssemblyVersion>
        <AssemblyVersion>2.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>Mono.Security.X509.X509Store</ReturnType>
      </ReturnValue>
      <Parameters>
        <Parameter Name="storeName" Type="System.String" />
        <Parameter Name="create" Type="System.Boolean" />
      </Parameters>
      <Docs>
        <param name="storeName">To be added.</param>
        <param name="create">To be added.</param>
        To be added.
        <returns>To be added.</returns>
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="OtherPeople">
      <MemberSignature Language="C#" Value="public Mono.Security.X509.X509Store OtherPeople { get; }" />
      <MemberType>Property</MemberType>
      <ReturnValue>
        <ReturnType>Mono.Security.X509.X509Store</ReturnType>
      </ReturnValue>
      <Parameters />
      <Docs>
        To be added
        <value>a <see cref="T:Mono.Security.X509.X509Store" /></value>
        <remarks>To be added</remarks>
      </Docs>
      <AssemblyInfo>
        <AssemblyVersion>1.0.5000.0</AssemblyVersion>
        <AssemblyVersion>2.0.0.0</AssemblyVersion>
      </AssemblyInfo>
    </Member>
    <Member MemberName="Personal">
      <MemberSignature Language="C#" Value="public Mono.Security.X509.X509Store Personal { get; }" />
      <MemberType>Property</MemberType>
      <ReturnValue>
        <ReturnType>Mono.Security.X509.X509Store</ReturnType>
      </ReturnValue>
      <Parameters />
      <Docs>
        To be added
        <value>a <see cref="T:Mono.Security.X509.X509Store" /></value>
        <remarks>To be added</remarks>
      </Docs>
      <AssemblyInfo>
        <AssemblyVersion>1.0.5000.0</AssemblyVersion>
        <AssemblyVersion>2.0.0.0</AssemblyVersion>
      </AssemblyInfo>
    </Member>
    <Member MemberName="TrustedRoot">
      <MemberSignature Language="C#" Value="public Mono.Security.X509.X509Store TrustedRoot { get; }" />
      <MemberType>Property</MemberType>
      <ReturnValue>
        <ReturnType>Mono.Security.X509.X509Store</ReturnType>
      </ReturnValue>
      <Parameters />
      <Docs>
        To be added
        <value>a <see cref="T:Mono.Security.X509.X509Store" /></value>
        <remarks>To be added</remarks>
      </Docs>
      <AssemblyInfo>
        <AssemblyVersion>1.0.5000.0</AssemblyVersion>
        <AssemblyVersion>2.0.0.0</AssemblyVersion>
      </AssemblyInfo>
    </Member>
    <Member MemberName="Untrusted">
      <MemberSignature Language="C#" Value="public Mono.Security.X509.X509Store Untrusted { get; }" />
      <MemberType>Property</MemberType>
      <ReturnValue>
        <ReturnType>Mono.Security.X509.X509Store</ReturnType>
      </ReturnValue>
      <Parameters />
      <Docs>
        To be added
        <value>a <see cref="T:Mono.Security.X509.X509Store" /></value>
        <remarks>To be added</remarks>
      </Docs>
      <AssemblyInfo>
        <AssemblyVersion>1.0.5000.0</AssemblyVersion>
        <AssemblyVersion>2.0.0.0</AssemblyVersion>
      </AssemblyInfo>
    </Member>
  </Members>
</Type>


text:
deconstruction-engine
=====================

An experiment in networked multiplayer game engine design. written primarily in
Java (server-side) and JavaScript (client).

This is currently in pre-alpha state: basic networking is complete, but APIs and
the overall engine design are still being decided on. Don't expect anything
playable yet.

Building
--------

### Client
Building the client-side code requires Node and Gulp to be installed. Then:

```bash
npm install
gulp build
```

The file `build.js` should be written to `src/main/webapp/build/build.js`, and
will be included in subsequent server builds.

### Server
With Maven installed, run:
```
mvn war:war
```

A package will be written to `target/deconstruction-engine-x.y.war`, suitable for upload to a compatible webapp container (such as Tomcat). Make sure the client has been built as described above first.

FAQ
---

### What is this?

It's an experiment to see how far some basic abstractions can be taken, and to
see if some or all implicit restrictions of traditional game engines can be
alleviated through design.

The essentials of the design:
 * `Entity`: some object in the game world, made up of:
  * Many `Controllers`: implement some behavior
  * Many `Views`: provide rendering instructions for an entity in a zone
 * `Zone`: a collection of `Entities`
 * `World`: a collection of `Zones`
 * `Player`: controls an `Entity`

The definitions above are more or less literal: a zone exists to do the best
possible job of containing entities, and nothing more; an entity exists to
provide behaviors and views. Specializations of these base classes exist, but
are still composed primarily of these base concepts.

### Why?

For fun, mostly.


text:
FROM nicolasbonnet/debian:latest

#MAINTAINER
MAINTAINER Nicolas Bonnet <nicolas.bonnet@maisondeco.com>

LABEL version="1.0"
LABEL description="front web based on debian jessie"

RUN echo 'alias ll="ls -aslh"' >> ~/.bashrc

#install dev tools
RUN apt-get update && apt-get install -y vim wget

#add some sources
RUN echo "deb http://packages.dotdeb.org jessie all" >> /etc/apt/sources.list && \
    echo "deb-src http://packages.dotdeb.org jessie all" >> /etc/apt/sources.list && \
    wget https://www.dotdeb.org/dotdeb.gpg && \
    apt-key add dotdeb.gpg

RUN apt-get update && apt-get -y install apache2 && apt-get clean && rm -rf /var/lib/apt/lists/* && apt-get -qy autoremove

# Remove default VirtualHost
RUN rm -rf /etc/apache2/sites-enabled/* /etc/apache2/sites-available/* /var/www/html

#copy special conf
COPY ./conf.d/httpd.conf /etc/apache2/conf.d/httpd.conf
#copy vhost for prestashop
COPY ./sites-enabled/presta_test.conf /etc/apache2/sites-enabled/
COPY ./sites-available/000-default.conf /etc/apache2/sites-available/
COPY ./sites-available/default-ssl.conf /etc/apache2/sites-available/

#enable ssl
RUN /usr/sbin/a2ensite default-ssl
RUN /usr/sbin/a2enmod ssl
# Enable rewrite module
RUN a2enmod rewrite&& \
 	a2enmod proxy && \
 	a2enmod proxy_fcgi

RUN a2enmod actions alias

# Configure Apache2
ENV APACHE_RUN_USER     www-data
ENV APACHE_RUN_GROUP    www-data
ENV APACHE_LOG_DIR      /var/log/apache2

COPY ./index.html /var/www/
WORKDIR /var/www

# Expose ourselves
EXPOSE 80
EXPOSE 443

# Run!
CMD ["/usr/sbin/apache2ctl", "-D", "FOREGROUND"]


text:
var express = require('express'),
	app = module.exports = express(),
	m = require('measurejs');

app.get('/:amount/:dimension/:from/:to', function (req, res) {
	// TODO
	res.status(501).send({ error: 'This endpoint has not been implemented'});
});

app.get('/:amount/:from/:to', function (req, res) {
	// TODO
	res.status(501).send({ error: 'This endpoint has not been implemented'});
});

app.get('/:from/:to', function (req, res) {
	// TODO - Assume amount = 1
	res.status(501).send({ error: 'This endpoint has not been implemented'});
});


text:
<?php

namespace backend\models\search;

use common\models\AuditRecord;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;

class AuditRecordSearch extends AuditRecord {

    /**
     * @inheritdoc
     */
    public function rules2()
    {
        return [
            [['application', 'category', 'event', 'created_at'], 'safe'],
        ];
    }

    public function rules() {
        return [
            [['event', 'connected_type', 'created_at', 'user_id', 'connected_id'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }
    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = AuditRecord::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        if (!($this->load($params) && $this->validate())) {
            return $dataProvider;
        }

        $query->andFilterWhere([
            'id' => $this->id,
            'created_at' => $this->created_at,
        ]);

        $query->andFilterWhere(['like', 'connected_type', $this->connected_type]);
        $query->andFilterWhere(['like', 'user_id', $this->user_id]);
        $query->andFilterWhere(['like', 'event', $this->event]);

        return $dataProvider;
    }
}


text:
from nose.tools import raises

from railgun import SimObject, relpath

def check_cstructname_and_cfuncprefix(cstructname, cfuncprefix):
    class ClassNameIsNotVectCalc(SimObject):
        _clibname_ = 'vectclac.so'
        _clibdir_ = relpath('ext/build', __file__)

        _cmembers_ = [
            'num_i',
            'int v1[i]',
            'int v2[i]',
            'int v3[i]',
            'int ans',
            ]

        _cfuncs_ = [
            "vec_{op | plus, minus, times, divide}()",
            "subvec_{op | plus, minus, times, divide}(i i1=0, i< i2=num_i)",
            "fill_{vec | v1, v2, v3}(int s)",
            "ans subvec_dot(i i1=0, i< i2=num_i)",
            ]

        if cstructname is not None:
            _cstructname_ = cstructname
        if cfuncprefix is not None:
            _cfuncprefix_ = cfuncprefix

def test_cstructname_and_cfuncprefix():
    raises_nothing = check_cstructname_and_cfuncprefix
    raises_AttributeError = raises(AttributeError)(raises_nothing)
    yield (raises_nothing, 'VectCalc', None)
    yield (raises_AttributeError, None, None)
    yield (raises_AttributeError, 'WrongClassName', None)
    yield (raises_AttributeError, 'VectCalc', 'WrongPrefix_')
    yield (raises_nothing, None, 'VectCalc_')

def check_empty_cfuncprefix(cfuncprefix):
    class ClassNameIsNotVectCalc(SimObject):
        _clibname_ = 'vectclac.so'
        _clibdir_ = relpath('ext/build', __file__)

        _cmembers_ = [
            'num_i',
            'int v1[i]',
            'int v2[i]',
            'int v3[i]',
            'int ans',
            ]

        _cfuncs_ = ['VectCalc_' + f for f in [
            "vec_{op | plus, minus, times, divide}()",
            "subvec_{op | plus, minus, times, divide}(i i1=0, i< i2=num_i)",
            "fill_{vec | v1, v2, v3}(int s)",
            "subvec_dot(i i1=0, i< i2=num_i)",
            ]]

        if cfuncprefix is not None:
            _cfuncprefix_ = cfuncprefix

def test_empty_cfuncprefix():
    raises_nothing = check_empty_cfuncprefix
    raises_AttributeError = raises(AttributeError)(raises_nothing)
    yield (raises_nothing, '')
    yield (raises_AttributeError, None)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _02_Reverse_an_Array_of_Integers
{
    class Program
    {
        static void Main(string[] args)
        {
            int n = int.Parse(Console.ReadLine());

            int[] arrayOfNumbers = new int[n];
            for (int i = 0; i < n; i++)
            {
                arrayOfNumbers[i] = int.Parse(Console.ReadLine());
            }

            for (int i = arrayOfNumbers.Length - 1; i >= 0 ; i--)
            {
                Console.Write(arrayOfNumbers[i]);
                if (i != 0)
                {
                    Console.Write(" ");
                }
            }
        }
    }
}


text:
import { Inject, Component, OnInit } from '@angular/core';
import { HttpService, HttpPaths } from '../http.service';
import { SuperComponent } from '../super.component';
import { WindowRefService } from '../window-ref.service';
import { FlagService } from '../flag.service';

@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.css']
})
export class SearchComponent extends SuperComponent implements OnInit {

  searchInput;
  searchResult;
  searchSize = 10;

  constructor(
    private _httpService: HttpService,
    private _windowRefService: WindowRefService,
    private _flagService: FlagService
  ) {
    super();
  }

  ngOnInit() {
  }

  refresh() {
  }

  search() {
    this._httpService.getESResource(HttpPaths.SEARCH + '?q=' + this.searchInput + '&size=' + this.searchSize).subscribe(
      searchResult => {
        this.searchResult = searchResult;
        /*this._flagService.showFlag('Search Stats',
          '
Shards total: ' + searchResult._shards.total + '
'
            + '
Shards successful: ' + searchResult._shards.successful + '
'
              + '
Shards failed: ' + searchResult._shards.failed + '
'
                + '
Timed out: ' + searchResult.timed_out + '
'
                  + '
Total hits: ' + searchResult.hits.total + '
'
                    + '
Max score: ' + searchResult.hits.max_score + '
')*/
      }
    );
  }

  showJson(_id) {
    this._windowRefService.nativeWindow.AJS.dialog2(' #dialog-json-' + _id).show();
  }
}


text:
package com.cloudera.oryx.app.als;

import java.util.List;

/**
 *
Implementations of this interface provide, optionally, objects that can be used to
 * modify and influence the results of endpoints like {@code Recommend}, {@code Similarity},
 * etc. It is a means to inject business logic into the results of the ALS application
 * endpoints.

 *
 *
Implementations of this class are factories. An implementation creates and configures
 * a {@link Rescorer} rescoring object and returns it for use in the context of one
 * of the endpoints' operation. For example, the result of
 * {@link #getRecommendRescorer(List, List)} is used with {@code Recommend}.
 * The {@link Rescorer} filters the candidates recommendations by item ID
 * ({@link Rescorer#isFiltered(String)}) or modifies the scores of item candidates that
 * are not filtered ({@link Rescorer#rescore(String, double)}) based on the item ID and
 * original score.

 *
 *
The factory methods take several optional {@code String} arguments. These are passed
 * from the REST API, as several {@code String}s, from URL parameter {@code rescorerParams}.
 * The implementation may need this information to initialize its rescoring logic for the request.
 * For example, the argument may be the user's current location, used to filter
 * results by location.

 *
 *
For example, a request containing {@code ...?rescorerParams=xxx,yyy,zzz} will result in an
 * {@code args} parameter with one elements, {@code xxx,yyy,zzz}. A request containing
 * {@code ...?rescorerParams=xxx&...rescorerParams=yyy&...rescorerParams=zzz...} will result in an
 * {@code args} parameter with 3 elements, {@code xxx}, {@code yyy}, {@code zzz}.

 */
public interface RescorerProvider {

  /**
   * @param userIDs user(s) for which recommendations are being made, which may be needed
   *  in the rescoring logic.
   * @param args arguments, if any, that should be used when making the {@link Rescorer}.
   *  This is additional information from the request that may be necessary to its logic,
   *  like current location. What it means is up to the implementation.
   * @return {@link Rescorer} to use or {@code null} if none should be used.
   *  The resulting {@link Rescorer} will be passed each candidate item ID to
   *  {@link Rescorer#isFiltered(String)}, and each non-filtered candidate with its original score
   *  to {@link Rescorer#rescore(String, double)}
   */
  Rescorer getRecommendRescorer(List<String> userIDs, List<String> args);

  /**
   * @param itemIDs items that the anonymous user is associated to
   * @param args arguments, if any, that should be used when making the {@link Rescorer}.
   *  This is additional information from the request that may be necessary to its logic,
   *  like current location. What it means is up to the implementation.
   * @return {@link Rescorer} to use or {@code null} if none should be used.
   *  The resulting {@link Rescorer} will be passed each candidate item ID to
   *  {@link Rescorer#isFiltered(String)}, and each non-filtered candidate with its original score
   *  to {@link Rescorer#rescore(String, double)}
   */
  Rescorer getRecommendToAnonymousRescorer(List<String> itemIDs, List<String> args);

  /**
   * @param args arguments, if any, that should be used when making the {@link Rescorer}.
   *  This is additional information from the request that may be necessary to its logic,
   *  like current location. What it means is up to the implementation.
   * @return {@link Rescorer} to use or {@code null} if none should be used. Note that
   *  only its {@link Rescorer#isFiltered(String)} method has effect.
   */
  Rescorer getMostPopularItemsRescorer(List<String> args);

  /**
   * @param args arguments, if any, that should be used when making the {@link Rescorer}.
   *  This is additional information from the request that may be necessary to its logic,
   *  like current location. What it means is up to the implementation.
   * @return {@link Rescorer} to use or {@code null} if none should be used. Note that
   *  only its {@link Rescorer#isFiltered(String)} method has effect.
   */
  Rescorer getMostActiveUsersRescorer(List<String> args);

  /**
   * @param args arguments, if any, that should be used when making the {@link Rescorer}.
   *  This is additional information from the request that may be necessary to its logic,
   *  like current location. What it means is up to the implementation.
   * @return {@link Rescorer} to use or {@code null} if none should be used.
   *  The {@link Rescorer} will be passed, to its {@link Rescorer#isFiltered(String)}
   *  method, the candidate item ID passed in the user query as its second element.
   *  Each non-filtered pair is passed with its original score to
   *  {@link Rescorer#rescore(String, double)}
   */
  Rescorer getMostSimilarItemsRescorer(List<String> args);

}


text:
<!DOCTYPE html>

{% include head.html %}

    {% include header.html %}

        {{ content }}

  {% include footer.html %}


text:
package com.koch.ambeth.merge;

public interface IMergeProcessContent extends IMergeProcessStarted {
	/**
	 * Executes the previously configured merge process instance on the stack
	 */
	void finish();

	@Override
	IMergeProcessContent onLocalDiff(ProceedWithMergeHook hook);

	@Override
	IMergeProcessContent onDataChange(DataChangeReceivedCallback callback);

	@Override
	IMergeProcessContent onSuccess(MergeFinishedCallback callback);

	@Override
	IMergeProcessContent suppressNewEntitiesAddedToCache();

	@Override
	IMergeProcessContent shallow();
}


text:
@interface TwitterAPI()
@property (nonatomic) NSString *sSearchQuery;
@property (nonatomic) NSString *sBearerToken;
@property (nonatomic) NSInteger iLimitResults;
@end

@implementation TwitterAPI

- (void) searchWithQueryString:(NSString *) sQuery limit:(NSInteger) iLimit completionHandler:(void(^)(NSArray *tweets, NSError *error))completionHandler
{
    self.sSearchQuery = sQuery;
    self.iLimitResults = iLimit;

    if (self.sBearerToken == nil || [self.sBearerToken isEqualToString:@""]) {
        [self requestBearerToken:completionHandler];
    }
    else {
        [self performSearchQuery:completionHandler];
    }

}

- (void) requestBearerToken:(void(^)(NSArray *tweets, NSError *error))completionHandler {
    NSMutableURLRequest *sRequestURL = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:kOAuthBaseUrl]];
    // from Twitter API 1.1 onwards, the search API requires OAuth per Twitter Account or App-only authentication with consumer key and consumer secret
    NSString *secretKeys = [self base64encoded:@"Ds1qgCXtNwE8eSKQOOfGepyjy:HjOqYvccp9f4GIe2NV8dbogp6uV3l4mOlU93Jj8HEA2nuJ9ATD"];

    [sRequestURL setHTTPMethod:@"POST"];
    [sRequestURL setValue:@"gzip" forHTTPHeaderField:@"Accept-encoding"];
    [sRequestURL setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [sRequestURL setValue:[NSString stringWithFormat:@"Basic %@", secretKeys] forHTTPHeaderField:@"Authorization"];

    NSString *dataToSend = @"grant_type=client_credentials";
    [sRequestURL setHTTPBody:[dataToSend dataUsingEncoding:NSUTF8StringEncoding]];

    NSURLSessionDataTask *firstTask = [[NSURLSession sharedSession] dataTaskWithRequest:sRequestURL completionHandler:^(NSData *data, NSURLResponse *reponse, NSError *error) {
        if (error)
        {
            completionHandler(nil, error);
            return;
        }
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*) reponse;
        NSInteger code = [httpResponse statusCode];
        if ((code >= 200 && code < 300))
        {
            NSDictionary *tokenDiction = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            self.sBearerToken = [tokenDiction valueForKey:@"access_token"];
            [self performSearchQuery:completionHandler];
        }
        else
            return;
    }];

    [firstTask resume];
}

- (void) performSearchQuery:(void(^)(NSArray *tweets, NSError *error))completionHandler {

    NSString *sSearchRequest = [NSString stringWithFormat:@"%@?count=%ld&q=%@", kSearchBaseUrl, (long)self.iLimitResults, [self encodeQuery:self.sSearchQuery]];

    NSMutableURLRequest *sSearchRequestURL = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:sSearchRequest]];
    [sSearchRequestURL setHTTPMethod:@"GET"];
    [sSearchRequestURL setValue:@"gzip" forHTTPHeaderField:@"Accept-encoding"];
    [sSearchRequestURL setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [sSearchRequestURL setValue:[NSString stringWithFormat:@"Bearer %@", self.sBearerToken] forHTTPHeaderField:@"Authorization"];

    NSURLSessionDataTask *secondTask = [[NSURLSession sharedSession] dataTaskWithRequest:sSearchRequestURL completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (error)
        {
            completionHandler(nil, error);
            return;
        }
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*) response;
        NSInteger code = [httpResponse statusCode];
        if ((code >= 200 && code < 300))
        {
            NSArray *aTweets = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            completionHandler(aTweets, nil);
        }
        else
            return;
    }];
    [secondTask resume];
}

- (NSString *) base64encoded:(NSString *) passedString
{
    NSData *oData = [passedString dataUsingEncoding:NSUTF8StringEncoding];
    NSString *sResult = [oData base64EncodedStringWithOptions:0];

    return sResult;
}

- (NSString *) encodeQuery:(NSString *) passedQuery
{
    return [passedQuery stringByAddingPercentEncodingWithAllowedCharacters: [NSCharacterSet URLHostAllowedCharacterSet]];
}

@end


text:
<?xml version="1.0"?>
<Document>

	<Sentence>
		<value>It is OK to wash the site with soap and water daily to keep the area clean and prevent infection.</value>
		<pattern_crowdsource> It is OK to wash the site with soap and [[water|C0043047]] daily to keep the area clean and prevent [[infection|C0009450]].		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>site</surface-form>
				<RDF-ID>C0205145</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>soap</surface-form>
				<RDF-ID>C0037392</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>water</surface-form>
				<RDF-ID>C0043047</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>daily</surface-form>
				<RDF-ID>C0332173</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>area</surface-form>
				<RDF-ID>C0205146</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>infection</surface-form>
				<RDF-ID>C0009450</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0043047 PREVENTS C0009450</triple>
		</triples>
	</Sentence>

</Document>


text:
package network

import (
	"errors"
	"fmt"
	"io"

	"github.com/spf13/cobra"

	kcmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
	kerrors "k8s.io/kubernetes/pkg/util/errors"

	"github.com/openshift/origin/pkg/cmd/util/clientcmd"
)

const (
	JoinProjectsNetworkCommandName = "join-projects"

	joinProjectsNetworkLong = `
Join project network

Allows projects to join existing project network when using the %[1]s network plugin.`

	joinProjectsNetworkExample = `	# Allow project p2 to use project p1 network
	$ %[1]s --to=<p1> <p2>

	# Allow all projects with label name=top-secret to use project p1 network
	$ %[1]s --to=<p1> --selector='name=top-secret'`
)

type JoinOptions struct {
	Options *ProjectOptions

	joinProjectName string
}

func NewCmdJoinProjectsNetwork(commandName, fullName string, f *clientcmd.Factory, out io.Writer) *cobra.Command {
	opts := &ProjectOptions{}
	joinOp := &JoinOptions{Options: opts}

	cmd := &cobra.Command{
		Use:     commandName,
		Short:   "Join project network",
		Long:    fmt.Sprintf(joinProjectsNetworkLong, ovsPluginName),
		Example: fmt.Sprintf(joinProjectsNetworkExample, fullName),
		Run: func(c *cobra.Command, args []string) {
			if err := opts.Complete(f, c, args, out); err != nil {
				kcmdutil.CheckErr(err)
			}
			opts.CheckSelector = c.Flag("selector").Changed
			if err := joinOp.Validate(); err != nil {
				kcmdutil.CheckErr(kcmdutil.UsageError(c, err.Error()))
			}

			err := joinOp.Run()
			kcmdutil.CheckErr(err)
		},
	}
	flags := cmd.Flags()

	// Supported operations
	flags.StringVar(&joinOp.joinProjectName, "to", "", "Join network of the given project name")

	// Common optional params
	flags.StringVar(&opts.Selector, "selector", "", "Label selector to filter projects. Either pass one/more projects as arguments or use this project selector")

	return cmd
}

func (j *JoinOptions) Validate() error {
	errList := []error{}
	if err := j.Options.Validate(); err != nil {
		errList = append(errList, err)
	}
	if len(j.joinProjectName) == 0 {
		errList = append(errList, errors.New("must provide --to=<project_name>"))
	}
	return kerrors.NewAggregate(errList)
}

func (j *JoinOptions) Run() error {
	netID, err := j.Options.GetNetID(j.joinProjectName)
	if err != nil {
		return err
	}
	projects, err := j.Options.GetProjects()
	if err != nil {
		return err
	}

	errList := []error{}
	for _, project := range projects {
		err = j.Options.CreateOrUpdateNetNamespace(project.ObjectMeta.Name, netID)
		if err != nil {
			errList = append(errList, fmt.Errorf("Project '%s' failed to join '%s', error: %v", project.ObjectMeta.Name, j.joinProjectName, err))
		}
	}
	return kerrors.NewAggregate(errList)
}


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

class Leaveapproval extends MY_Controller
{
    /**
     * Class constructor
     *
     * @return	void
     */
    public function __construct()
    {
        parent::__construct();
    }

    // --------------------------------------------------------------------

    /**
     * Index
     */
    public function index()
    {
        $this->load->library(array('leave'));

        $this->load->helper(array('my_datetime_helper', 'my_variable_helper'));

        if ($this->input->post('btnfilter'))
        {
            $data['startdate'] = $this->input->post('startdate');
            $data['enddate'] = $this->input->post('enddate');

            // Use this for live
            $data['forapproval'] = $this->leave->leaves_for_approval(trim($this->session->userdata('employeenumber')),$data['startdate'],$data['enddate']);
			# var_dump($data['forapproval']);
            // Use this for test
            // $data['leaveforapproval'] = $this->leave->leaves_for_approval('051039',$data['startdate'],$data['enddate']);
        }
        else
        {
            // Use this for live
            $data['forapproval'] = $this->leave->leaves_for_approval(trim($this->session->userdata('employeenumber')));

            // Use this for test
            // $data['leaveforapproval'] = $this->leave->leaves_for_approval('051039');
        }

        $this->page_title('Leaves Approval - TREC Webforms');
        $this->add_css(array('datepicker.min', 'dataTables.bootstrap.min'));
        $this->add_js_footer(array('bootstrap-datepicker.min',
            'input-datepicker',
            'jquery.dataTables.min',
            'dataTables.bootstrap.min',
            'initdttable',
            'bootbox.min',
            'leaveapproval'));

        $this->display_master('index', $data);
    }

    // --------------------------------------------------------------------

    /**
     * View leave for approval
     */
    public function view()
    {
        $this->load->model(array('employeeleavesfiled',
            'leavetype',
            'employeemedcert'));

        $this->load->helper(array('my_datetime_helper', 'my_leavestatus_helper'));

        $this->employeeleavesfiled->load($this->uri->segment(3));
        $data['leave'] = $this->employeeleavesfiled;
        $data['leavetypes'] = $this->leavetype->get_leave_types();
        $data['leavedescription'] = $this->config->item('leavedescription');
        $data['leavepaylabels'] = $this->config->item('leavepaylabels');

        $this->load->view('leaveapproval/view', $data);
    }

    // --------------------------------------------------------------------

    /**
     * Approve/ decline leave.
     */
    public function update()
    {
        $this->load->model(array('employeeleavesfiled','employeeleaves',
                'leavetype'));
        $this->load->library('leave');
        $this->load->helper(array('my_datetime_helper'));

        $this->leavetype->Remarks = $this->db->escape($this->input->post('leavetype'));
        $type = $this->leavetype->get();

        $this->employeeleavesfiled->EmployeeNumber = $this->input->post('employeenumber');
        $this->employeeleavesfiled->LeaveFrom = convert_date($this->input->post('leavefrom'), 'Y-m-d H:i:s');
        $this->employeeleavesfiled->LeaveTo = convert_date($this->input->post('leaveto'), 'Y-m-d H:i:s');
        $this->employeeleavesfiled->LeaveCount = $this->input->post('count');
        $this->employeeleavesfiled->Type = $type[0]->LeaveType;
        $this->employeeleavesfiled->Reason = $this->input->post('leavereason');
        $this->employeeleavesfiled->Deleted = $this->input->post('status');
        $this->employeeleavesfiled->WithPay = $this->input->post('withpay');
        $this->employeeleavesfiled->AuditUser = '123456';
        $this->employeeleavesfiled->AuditDate = date('Y-m-d H:i:s');
        $this->employeeleavesfiled->update($this->input->post('leaveid'));

        // Update leave credits
        // Leave is approved
        if ($this->input->post('status') == 0)
        {
            // Leave is with pay.
            if ($this->input->post('withpay') == 1)
            {
				$this->employees->load($this->input->post('employeenumber'));

                // Employees hired after May 31, 2013 have no sick leave credits.
                // They only earn vacation leave credits which can be used in place
                // of the sick leave.
                if (strtotime($this->employees->DateHired) > strtotime('May 31, 2013') && $this->input->post('leavetype') == 'Sick Leave')
                {
                    $leavetype = 'Vacation Leave';
                }
                else
                {
                    $leavetype = $this->input->post('leavetype');
                }

                $this->leave->updatecredits($this->input->post('employeenumber'),
                        $leavetype,
                        $this->input->post('leavefrom'),
                        $this->input->post('leaveto'));

				// Update employee logs.
				$this->leave->leavedetails($this->input->post('leaveid'));
            }

        }

    }

    // --------------------------------------------------------------------

    /**
     * Check leave credits
     */
    public function credits()
    {
        $this->load->model('employeeleaves');
        if ($this->input->get('emp'))
        {
            $this->employeeleaves->load($this->input->get('emp'));
            $credits[] = array('sick' => $this->employeeleaves->Sick,
                'vacation' => $this->employeeleaves->Vacation,
                'emergency' => $this->employeeleaves->Emergency,
                'maternity' => $this->employeeleaves->Maternity,
                'paternity' => $this->employeeleaves->Paternity,
                'auditdate' => $this->employeeleaves->AuditDate,);

            echo json_encode($credits);
        }
    }

    // --------------------------------------------------------------------

    /**
     * Check date hired
     */
    public function datehired()
    {
        $this->load->model('employees');
        if ($this->input->get('emp'))
        {
            $this->employees->load($this->input->get('emp'));
            $employee[] = array('datehired' => strtotime($this->employees->DateHired));

            $this->output->set_content_type('application/json', 'utf-8')
                         ->set_output(json_encode($employee));
        }
    }
}


text:
package org.apache.synapse.util.streaming_xpath.custom;

import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.impl.builder.StAXOMBuilder;
import org.apache.synapse.util.streaming_xpath.custom.components.*;

import javax.xml.stream.XMLStreamException;
import java.io.InputStream;

public class StreamingParser {

    ParserComponent firstComp;
    ParserComponent currentComp;

    public ParserComponent getCurrentComp() {
        return currentComp;
    }

    public void setCurrentComp(ParserComponent currentComp) {
        this.currentComp = currentComp;
    }

    public String process(InputStream xmlIn) throws XMLStreamException {
        StAXOMBuilder builder = new StAXOMBuilder(xmlIn);
        OMElement documentElement = builder.getDocumentElement();
        return firstComp.process(documentElement);
    }

    public String process(OMElement documentElement) throws XMLStreamException {
        return firstComp.process(documentElement);
    }

    public StreamingParser GetChild_GetCurrent() {
        ParserComponent newComp = new GetCurrentParserComponent();
        if (firstComp == null) {
            firstComp = newComp;
            currentComp = newComp;

        } else {
            currentComp.setNext(newComp);
            currentComp = newComp;
        }
        return this;
    }

    public StreamingParser GetChild_GetCurrentMatch(String localName, String nameSpace) {
        ParserComponent newComp = new GetCurrentMatchParserComponent(localName, nameSpace);
        if (firstComp == null) {
            firstComp = newComp;
            currentComp = newComp;

        } else {
            currentComp.setNext(newComp);
            currentComp = newComp;
        }
        return this;
    }

    public StreamingParser GetChild_FirstChild() {
        ParserComponent newComp = new GetFirstChildParserComponent();
        if (firstComp == null) {
            firstComp = newComp;
            currentComp = newComp;

        } else {
            currentComp.setNext(newComp);
            currentComp = newComp;
        }
        return this;
    }

    public StreamingParser GetChild_GetChildrenByName(String localName, String nameSpace) {
        ParserComponent newComp = new GetChildrenByNameParserComponent(localName, nameSpace);
        if (firstComp == null) {
            firstComp = newComp;
            currentComp = newComp;

        } else {
            currentComp.setNext(newComp);
            currentComp = newComp;
        }
        return this;
    }

    public StreamingParser GetChild_GetChildrenByNameRelative(String localName, String nameSpace) {
        ParserComponent newComp = new GetChildrenByNameRelativeParserComponent(localName, nameSpace);
        if (firstComp == null) {
            firstComp = newComp;
            currentComp = newComp;

        } else {
            currentComp.setNext(newComp);
            currentComp = newComp;
        }
        return this;
    }

    public StreamingParser GetChild_GetChildrenWithChild(String localName, String nameSpace) {
        ParserComponent newComp = new GetChildrenWithChildParserComponent(localName, nameSpace);
        if (firstComp == null) {
            firstComp = newComp;
            currentComp = newComp;

        } else {
            currentComp.setNext(newComp);
        }
        return this;
    }

    public StreamingParser GetChild_GetChildrenWithChildValue(String localName, String nameSpace, String value) {
        ParserComponent newComp = new GetChildrenWithChildValueParserComponent(localName, nameSpace, value);
        if (firstComp == null) {
            firstComp = newComp;
            currentComp = newComp;

        } else {
            currentComp.setNext(newComp);
        }
        return this;
    }

    public StreamingParser GetChild_GetChildrenWithAttribute(String localName, String nameSpace) {
        ParserComponent newComp = new GetChildrenWithAttributeParserComponent(localName, nameSpace);
        if (firstComp == null) {
            firstComp = newComp;
            currentComp = newComp;

        } else {
            currentComp.setNext(newComp);
        }
        return this;
    }

    public StreamingParser GetChild_GetChildrenWithAttributeValue(String localName, String nameSpace, String value) {
        ParserComponent newComp = new GetChildrenWithAttributeValueParserComponent(localName, nameSpace, value);
        if (firstComp == null) {
            firstComp = newComp;
            currentComp = newComp;

        } else {
            currentComp.setNext(newComp);
        }
        return this;
    }

    public StreamingParser GetChild_GetAttribute(String localName, String nameSpace) {
        ParserComponent newComp = new GetAttributeParserComponent(localName, nameSpace);
        if (firstComp == null) {
            firstComp = newComp;
            currentComp = newComp;

        } else {
            currentComp.setNext(newComp);
        }
        return this;
    }

    public ParserComponent getFirstComp() {
        return firstComp;
    }

    public void processOM(OMElement om) {
        firstComp.process(om);
    }
}


text:
// ----------------------------------------------------------
// 系统名称:EasySoft PssS
// 项目名称:领域实体类库
// 创 建 人:刘年超
// 创建时间:2017-01-14
// ----------------------------------------------------------
// 修改记录:
//
//
// ----------------------------------------------------------
// 版权所有:易则科技工作室
// ----------------------------------------------------------
namespace EasySoft.PssS.Domain.Entity
{
    using EasySoft.Core.Persistence;
    using EasySoft.Core.Util;
    using EasySoft.PssS.Domain.ValueObject;
    using System;
    using System.Collections.Generic;
    using System.Data;

    /// <summary>
    /// 销售领域实体类
    /// </summary>
    [Table("dbo.Sale")]
    public class Sale : EntityWithOperatorBase
    {
        #region 属性

        /// <summary>
        /// 获取或设置分类
        /// </summary>
        [Column("DeliveryId", DbType.String, Size = Constant.STRING_LENGTH_32)]
        public string DeliveryId { get; private set; }

        /// <summary>
        /// 获取或设置项
        /// </summary>
        [Column("Item", DbType.String, Size = Constant.STRING_LENGTH_10)]
        public string Item { get; private set; }

        /// <summary>
        /// 获取或设置数量
        /// </summary>
        [Column("Quantity", DbType.Decimal, Size = Constant.STRING_LENGTH_18)]
        public decimal Quantity { get; private set; }

        /// <summary>
        /// 获取或设置单位
        /// </summary>
        [Column("Unit", DbType.String, Size = Constant.STRING_LENGTH_2)]
        public string Unit { get; private set; }

        /// <summary>
        /// 获取或设置余量
        /// </summary>
        [Column("Inventory", DbType.Decimal, Size = Constant.STRING_LENGTH_18)]
        public decimal Inventory { get; private set; }

        /// <summary>
        /// 获取或设置益损
        /// </summary>
        [Column("ProfitLoss", DbType.Decimal, Size = Constant.STRING_LENGTH_18)]
        public decimal ProfitLoss { get; private set; }

        /// <summary>
        /// 获取或设置采购单状态
        /// </summary>
        [Column("Status", DbType.String, Size = Constant.STRING_LENGTH_1)]
        public string Status { get; private set; }

        #endregion

        #region 构造函数

        /// <summary>
        /// 构造函数
        /// </summary>
        public Sale()
        {

        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="id">ID</param>
        /// <param name="deliveryId">采购单ID</param>
        /// <param name="item">项</param>
        /// <param name="quantity">数量</param>
        /// <param name="unit">单位</param>
        /// <param name="inventory">余量</param>
        /// <param name="profitLoss">益损</param>
        /// <param name="status">状态</param>
        /// <param name="creator">创建人</param>
        /// <param name="createTime">创建时间</param>
        /// <param name="mender">修改人</param>
        /// <param name="modifyTime">修改时间</param>
        public Sale(string id, string deliveryId, string item, decimal quantity, string unit, decimal inventory, decimal profitLoss, string status, string creator, DateTime createTime, string mender, DateTime modifyTime)
            : base(id, creator, createTime, mender, modifyTime)
        {
            this.DeliveryId = deliveryId;
            this.Item = item;
            this.Quantity = quantity;
            this.Unit = unit;
            this.Inventory = inventory;
            this.ProfitLoss = profitLoss;
            this.Status = status;
        }

        #endregion

        #region 方法

        /// <summary>
        /// 采购出库到销售
        /// </summary>
        /// <param name="date">日期</param>
        /// <param name="category">分类</param>
        /// <param name="item">项</param>
        /// <param name="quantity">数量</param>
        /// <param name="unit">单位</param>
        /// <param name="supplier">供应方</param>
        /// <param name="remark">备注</param>
        /// <param name="costs">成本</param>
        /// <param name="creator">创建人</param>
        public void Create(string deliveryId, string item, decimal quantity, string unit, string creator)
        {
            base.Create(creator);
            this.DeliveryId = deliveryId;
            this.Item = item;
            this.Quantity = quantity;
            this.Unit = unit;
            this.Inventory = quantity;
            this.Status = SaleStatus.Sent;
        }

        /// <summary>
        /// 增加数量
        /// </summary>
        /// <param name="quantity"></param>
        public void AddQuantity(decimal quantity)
        {
            this.Quantity += quantity;
        }

        /// <summary>
        /// 增加益损数据
        /// </summary>
        /// <param name="category">益损类型</param>
        /// <param name="quantity">数量</param>
        public void AddProfitLoss(string category, decimal quantity)
        {
            if (this.Status != SaleStatus.Received)
            {
                throw new EasySoftException("当前状态不能进行益损操作。");
            }

            decimal profitLoss = Entity.ProfitLoss.Calculate(category, quantity);

            this.Inventory += profitLoss;
            this.ProfitLoss += profitLoss;

            if (this.Inventory == Constant.DECIMAL_ZERO)
            {
                this.Status = SaleStatus.Finished;
            }
        }

        #endregion
    }
}


text:
package com.hxz.example.controller;

import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * @author hxz
 * @since 2016/10/05 12:34
 */
@Component
public class ComputeClientHystrix implements ComputeClient{

    @Override
    public Integer add(@RequestParam(value = "a") Integer a, @RequestParam(value = "b") Integer b) {
        return -9999;
    }
}