text:
"""Tests for the experimental input pipeline ops."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import threading

import numpy as np

from tensorflow.python.client import session
from tensorflow.python.data.ops import dataset_ops
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors
from tensorflow.python.ops import script_ops
from tensorflow.python.platform import test

class DatasetConstructorTest(test.TestCase):

  def _testFromGenerator(self, generator, elem_sequence, num_repeats,
                         output_types=None):
    if output_types is None:
      output_types = dtypes.int64
    iterator = (
        dataset_ops.Dataset.from_generator(generator, output_types=output_types)
        .repeat(num_repeats)
        .prefetch(5)
        .make_initializable_iterator())
    init_op = iterator.initializer
    get_next = iterator.get_next()

    with self.test_session() as sess:
      for _ in range(2):  # Run twice to test reinitialization.
        sess.run(init_op)
        for _ in range(num_repeats):
          for elem in elem_sequence:
            self.assertAllEqual(elem, sess.run(get_next))
        with self.assertRaises(errors.OutOfRangeError):
          sess.run(get_next)

  def _testFromGeneratorOneShot(self, generator, elem_sequence, num_repeats):
    iterator = (
        dataset_ops.Dataset.from_generator(generator, output_types=dtypes.int64)
        .repeat(num_repeats)
        .prefetch(5)
        .make_one_shot_iterator())
    get_next = iterator.get_next()

    with self.test_session() as sess:
      for _ in range(num_repeats):
        for elem in elem_sequence:
          self.assertAllEqual(elem, sess.run(get_next))
      with self.assertRaises(errors.OutOfRangeError):
        sess.run(get_next)

  def testFromGeneratorUsingFunction(self):
    def generator():
      for i in range(1, 100):
        yield [i] * i
    elem_sequence = list(generator())
    self._testFromGenerator(generator, elem_sequence, 1)
    self._testFromGenerator(generator, elem_sequence, 5)
    self._testFromGeneratorOneShot(generator, elem_sequence, 1)
    self._testFromGeneratorOneShot(generator, elem_sequence, 5)

  def testFromGeneratorUsingList(self):
    generator = lambda: [[i] * i for i in range(1, 100)]
    elem_sequence = list(generator())
    self._testFromGenerator(generator, elem_sequence, 1)
    self._testFromGenerator(generator, elem_sequence, 5)

  def testFromGeneratorUsingNdarray(self):
    generator = lambda: np.arange(100, dtype=np.int64)
    elem_sequence = list(generator())
    self._testFromGenerator(generator, elem_sequence, 1, output_types=np.int64)
    self._testFromGenerator(generator, elem_sequence, 5, output_types=np.int64)

  def testFromGeneratorUsingGeneratorExpression(self):
    # NOTE(mrry): Generator *expressions* are not repeatable (or in
    # general reusable), because they eagerly evaluate the `for`
    # expression as `iter(range(1, 100))` and discard the means of
    # reconstructing `range(1, 100)`. Wrapping the generator
    # expression in a `lambda` makes it repeatable.
    generator = lambda: ([i] * i for i in range(1, 100))
    elem_sequence = list(generator())
    self._testFromGenerator(generator, elem_sequence, 1)
    self._testFromGenerator(generator, elem_sequence, 5)

  def testFromMultipleConcurrentGenerators(self):
    num_inner_repeats = 5
    num_outer_repeats = 100

    def generator():
      for i in range(1, 10):
        yield ([i] * i, [i, i ** 2, i ** 3])
    input_list = list(generator())

    # The interleave transformation is essentially a flat map that
    # draws from multiple input datasets concurrently (in a cyclic
    # fashion). By placing `Datsaet.from_generator()` inside an
    # interleave, we test its behavior when multiple iterators are
    # active at the same time; by additionally prefetching inside the
    # interleave, we create the possibility of parallel (modulo GIL)
    # invocations to several iterators created by the same dataset.
    def interleave_fn(_):
      return (dataset_ops.Dataset.from_generator(
          generator, output_types=(dtypes.int64, dtypes.int64),
          output_shapes=([None], [3]))
              .repeat(num_inner_repeats).prefetch(5))

    iterator = (
        dataset_ops.Dataset.range(num_outer_repeats)
        .interleave(interleave_fn, cycle_length=10,
                    block_length=len(input_list))
        .make_initializable_iterator())
    init_op = iterator.initializer
    get_next = iterator.get_next()

    with self.test_session() as sess:
      sess.run(init_op)
      for _ in range(num_inner_repeats * num_outer_repeats):
        for elem in input_list:
          val0, val1 = sess.run(get_next)
          self.assertAllEqual(elem[0], val0)
          self.assertAllEqual(elem[1], val1)
      with self.assertRaises(errors.OutOfRangeError):
        sess.run(get_next)

  # TODO(b/67868766): Reenable this when the source of flakiness is discovered.
  def _testFromGeneratorsRunningInParallel(self):
    num_parallel_iterators = 3

    # Define shared state that multiple iterator instances will access to
    # demonstrate their concurrent activity.
    lock = threading.Lock()
    condition = threading.Condition(lock)
    next_ticket = [0]  # GUARDED_BY(lock)

    def generator():
      # NOTE(mrry): We yield one element before the barrier, because
      # the current implementation of `Dataset.interleave()` must
      # fetch one element from each incoming dataset to start the
      # prefetching.
      yield 0

      # Define a barrier that `num_parallel_iterators` iterators must enter
      # before any can proceed. Demonstrates that multiple iterators may be
      # active at the same time.
      condition.acquire()
      ticket = next_ticket[0]
      next_ticket[0] += 1
      if ticket == num_parallel_iterators - 1:
        # The last iterator to join the barrier notifies the others.
        condition.notify_all()
      else:
        # Wait until the last iterator enters the barrier.
        while next_ticket[0] < num_parallel_iterators:
          condition.wait()
      condition.release()

      yield 1

    # As in `testFromMultipleConcurrentGenerators()`, we use a combination of
    # `Dataset.interleave()` and `Dataset.prefetch()` to cause multiple
    # iterators to be active concurrently.
    def interleave_fn(_):
      return dataset_ops.Dataset.from_generator(
          generator, output_types=dtypes.int64, output_shapes=[]).prefetch(2)

    iterator = (
        dataset_ops.Dataset.range(num_parallel_iterators)
        .interleave(
            interleave_fn, cycle_length=num_parallel_iterators, block_length=1)
        .make_initializable_iterator())
    init_op = iterator.initializer
    get_next = iterator.get_next()

    with self.test_session() as sess:
      sess.run(init_op)
      for elem in [0, 1]:
        for _ in range(num_parallel_iterators):
          self.assertAllEqual(elem, sess.run(get_next))
      with self.assertRaises(errors.OutOfRangeError):
        sess.run(get_next)

  def testFromGeneratorImplicitConversion(self):
    def generator():
      yield [1]
      yield [2]
      yield [3]

    for dtype in [dtypes.int8, dtypes.int32, dtypes.int64]:
      iterator = (dataset_ops.Dataset.from_generator(
          generator, output_types=dtype, output_shapes=[1])
                  .make_initializable_iterator())
      init_op = iterator.initializer
      get_next = iterator.get_next()

      self.assertEqual(dtype, get_next.dtype)

      with self.test_session() as sess:
        sess.run(init_op)
        for expected in [[1], [2], [3]]:
          next_val = sess.run(get_next)
          self.assertEqual(dtype.as_numpy_dtype, next_val.dtype)
          self.assertAllEqual(expected, next_val)
        with self.assertRaises(errors.OutOfRangeError):
          sess.run(get_next)

  def testFromGeneratorString(self):
    def generator():
      yield "foo"
      yield b"bar"
      yield u"baz"

    iterator = (dataset_ops.Dataset.from_generator(
        generator, output_types=dtypes.string, output_shapes=[])
                .make_initializable_iterator())
    init_op = iterator.initializer
    get_next = iterator.get_next()

    with self.test_session() as sess:
      sess.run(init_op)
      for expected in [b"foo", b"bar", b"baz"]:
        next_val = sess.run(get_next)
        self.assertAllEqual(expected, next_val)
      with self.assertRaises(errors.OutOfRangeError):
        sess.run(get_next)

  def testFromGeneratorTypeError(self):
    def generator():
      yield np.array([1, 2, 3], dtype=np.int64)
      yield np.array([4, 5, 6], dtype=np.int64)
      yield "ERROR"
      yield np.array([7, 8, 9], dtype=np.int64)

    iterator = (dataset_ops.Dataset.from_generator(
        generator, output_types=dtypes.int64, output_shapes=[3])
                .make_initializable_iterator())
    init_op = iterator.initializer
    get_next = iterator.get_next()

    with self.test_session() as sess:
      sess.run(init_op)
      self.assertAllEqual([1, 2, 3], sess.run(get_next))
      self.assertAllEqual([4, 5, 6], sess.run(get_next))
      # NOTE(mrry): Type name in message differs between Python 2 (`long`) and
      # 3 (`int`).
      with self.assertRaisesOpError(r"invalid literal for"):
        sess.run(get_next)
      self.assertAllEqual([7, 8, 9], sess.run(get_next))
      with self.assertRaises(errors.OutOfRangeError):
        sess.run(get_next)

  def testFromGeneratorShapeError(self):
    def generator():
      yield np.array([1, 2, 3], dtype=np.int64)
      yield np.array([4, 5, 6], dtype=np.int64)
      yield np.array([7, 8, 9, 10], dtype=np.int64)
      yield np.array([11, 12, 13], dtype=np.int64)

    iterator = (dataset_ops.Dataset.from_generator(
        generator, output_types=dtypes.int64, output_shapes=[3])
                .make_initializable_iterator())
    init_op = iterator.initializer
    get_next = iterator.get_next()

    with self.test_session() as sess:
      sess.run(init_op)
      self.assertAllEqual([1, 2, 3], sess.run(get_next))
      self.assertAllEqual([4, 5, 6], sess.run(get_next))
      with self.assertRaisesOpError(r"element of shape \(3,\) was expected"):
        sess.run(get_next)
      self.assertAllEqual([11, 12, 13], sess.run(get_next))
      with self.assertRaises(errors.OutOfRangeError):
        sess.run(get_next)

  def testFromGeneratorHeterogeneous(self):
    def generator():
      yield 1
      yield [2, 3]

    iterator = (
        dataset_ops.Dataset.from_generator(
            generator, output_types=dtypes.int64).make_initializable_iterator())
    init_op = iterator.initializer
    get_next = iterator.get_next()

    with self.test_session() as sess:
      sess.run(init_op)
      self.assertAllEqual(1, sess.run(get_next))
      self.assertAllEqual([2, 3], sess.run(get_next))
      with self.assertRaises(errors.OutOfRangeError):
        sess.run(get_next)

  def testFromGeneratorStopShort(self):

    def generator():
      yield 0
      yield 1
      yield 2

    iterator = (
        dataset_ops.Dataset.from_generator(
            generator, output_types=dtypes.int64).make_initializable_iterator())
    init_op = iterator.initializer
    get_next = iterator.get_next()

    with self.test_session() as sess:
      sess.run(init_op)
      self.assertAllEqual(0, sess.run(get_next))
      self.assertAllEqual(1, sess.run(get_next))

  def testFromGeneratorDestructorCalled(self):
    # Use an `Event` to signal that the generator has been deleted.
    event = threading.Event()

    class GeneratorWrapper(object):

      def __iter__(self):
        return self

      def next(self):
        return self.__next__()

      def __next__(self):
        return 42

      def __del__(self):
        event.set()

    iterator = dataset_ops.Dataset.from_generator(
        GeneratorWrapper,
        output_types=dtypes.int64).take(2).make_initializable_iterator()
    init_op = iterator.initializer
    get_next = iterator.get_next()

    with session.Session() as sess:
      sess.run(init_op)
      self.assertAllEqual(42, sess.run(get_next))
      self.assertAllEqual(42, sess.run(get_next))
      with self.assertRaises(errors.OutOfRangeError):
        sess.run(get_next)
      # Test that `GeneratorWrapper` object is destroyed when the
      # iterator terminates (and the generator iterator is deleted).
      self.assertTrue(event.is_set())

  def testFromGeneratorWithArgs(self):

    def flat_map_fn(elem):

      def generator_with_arg(n):
        for _ in range(n):
          yield np.array(n, dtype=np.int64)

      return dataset_ops.Dataset.from_generator(
          generator_with_arg, output_types=dtypes.int64, output_shapes=(),
          args=(elem,))

    iterator = (dataset_ops.Dataset
                .range(5)
                .flat_map(flat_map_fn)
                .make_initializable_iterator())
    init_op = iterator.initializer
    get_next = iterator.get_next()

    with self.test_session() as sess:
      sess.run(init_op)
      expected = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
      for x in expected:
        self.assertEqual(x, sess.run(get_next))
      with self.assertRaises(errors.OutOfRangeError):
        sess.run(get_next)

  def testFromGeneratorWithTwoArgs(self):

    def flat_map_fn(elem, message):

      def generator_with_arg(n, msg):
        for i in range(n):
          yield i, msg

      return dataset_ops.Dataset.from_generator(
          generator_with_arg, output_types=(dtypes.int64, dtypes.string),
          output_shapes=((), ()), args=(elem, message))

    iterator = (
        dataset_ops.Dataset.zip(
            (dataset_ops.Dataset.range(5),
             dataset_ops.Dataset.from_tensors("Hi!").repeat(None)))
        .flat_map(flat_map_fn)
        .make_initializable_iterator())
    init_op = iterator.initializer
    get_next = iterator.get_next()

    with self.test_session() as sess:
      sess.run(init_op)
      expected = [(0, b"Hi!"),
                  (0, b"Hi!"), (1, b"Hi!"),
                  (0, b"Hi!"), (1, b"Hi!"), (2, b"Hi!"),
                  (0, b"Hi!"), (1, b"Hi!"), (2, b"Hi!"), (3, b"Hi!")]
      for x in expected:
        self.assertEqual(x, sess.run(get_next))
      with self.assertRaises(errors.OutOfRangeError):
        sess.run(get_next)

  def testGeneratorDatasetFinalizeFunctionCalled(self):
    # NOTE(mrry): This test tests the internal `_GeneratorDataset`,
    # which affords more control over what the finalize function can do than
    # the `Dataset.from_generator()` wrapper.

    # Use an `Event` to signal that the generator has been deleted.
    event = threading.Event()

    def finalize_fn(_):
      def finalize_py_func():
        event.set()
        return 0
      return script_ops.py_func(finalize_py_func, [], [dtypes.int64],
                                stateful=True)

    dummy = constant_op.constant(37)
    iterator = (dataset_ops._GeneratorDataset(dummy, lambda x: x,
                                              lambda x: x, finalize_fn)
                .take(2)
                .make_initializable_iterator())
    init_op = iterator.initializer
    get_next = iterator.get_next()

    with self.test_session() as sess:
      sess.run(init_op)
      self.assertAllEqual(37, sess.run(get_next))
      self.assertAllEqual(37, sess.run(get_next))
      with self.assertRaises(errors.OutOfRangeError):
        sess.run(get_next)
        self.assertTrue(event.is_set())

if __name__ == "__main__":
  test.main()


text:
package net.tomp2p.replication;

import net.tomp2p.p2p.Peer;
import net.tomp2p.peers.*;

import java.util.ArrayList;
import java.util.HashSet;

/**
 * AutomaticReplication class observes the local network conditions and predicts
 * the next departure count based on previous and current peer churn behaviors.
 * This predicted value and given reliability are used to calculate the
 * replication factor
 *
 * @author Maxat Pernebayev
 * @author Thomas Bocek
 *
 */
public class AutoReplication implements PeerMapChangeListener, ReplicationFactor {
	private final HashSet<Number160> removedPeers = new HashSet<Number160>();
	private final ArrayList<Integer> observations = new ArrayList<Integer>();
	private final ArrayList<Double> emas = new ArrayList<Double>();
	private final PeerMap peerMap;

	private double reliability;
	private int minReplicationFactor = 2;
	private int maxReplicationFactor = 100;
	private int observationLength = 10;

	/**
	 * Constructor.
	 *
	 * @param reliability
	 *            The reliability
	 * @param peerMap
	 *            The map of my neighbors
	 */
	public AutoReplication(Peer peer) {
		this.emas.add(0.0);
		this.peerMap = peer.peerBean().peerMap();

	}

	public AutoReplication start() {
		peerMap.addPeerMapChangeListener(this);
		return this;
	}

	public AutoReplication shutdown() {
		peerMap.removePeerMapChangeListener(this);
		return this;
	}

	@Override
	public void peerInserted(PeerAddress peerAddress, boolean verified) {}

	@Override
	public void peerUpdated(PeerAddress peerAddress, PeerStatistic storedPeerAddress) {}

	@Override
	public void peerRemoved(PeerAddress peerAddress, PeerStatistic storedPeerAddress) {
		synchronized (removedPeers) {
			removedPeers.add(peerAddress.peerId());
		}
	}

	public AutoReplication reliability(double reliability) {
		this.reliability = reliability;
		return this;
	}

	public double reliability() {
		return reliability;
	}

	public AutoReplication minReplicationFactor(int minReplicationFactor) {
		this.minReplicationFactor = minReplicationFactor;
		return this;
	}

	public int minReplicationFactor() {
		return minReplicationFactor;
	}

	public AutoReplication maxReplicationFactor(int maxReplicationFactor) {
		this.maxReplicationFactor = maxReplicationFactor;
		return this;
	}

	public int maxReplicationFactor() {
		return maxReplicationFactor;
	}

	public AutoReplication observationLength(int observationLength) {
		this.observationLength = observationLength;
		return this;
	}

	public int observationLength() {
		return observationLength;
	}

	/**
	 *
	 * @return The number of neighbor peers.
	 */
	public int peerMapSize() {
		return peerMap.size();
	}

	/**
	 * @return The replication factor.
	 */
	public int replicationFactor() {
		final int removedPeerSize;
		synchronized (removedPeers) {
			removedPeerSize = removedPeers.size();
			removedPeers.clear();
		}

		observations.add(removedPeerSize);
		double average = ema(observations, emas);
		emas.add(average);
		int predictedValue = predictedValue(observations, average);

		int replicationFactor = replicationFactor2(predictedValue, peerMapSize(), reliability, minReplicationFactor,
		        maxReplicationFactor);

		if (observations.size() >= observationLength) {
			observations.remove(0);
			emas.remove(0);
		}
		return replicationFactor;
	}

	/**
	 * Calculate the replication factor given the reliability within a churn
	 * interval and the (predicted) number of peers that left the system.
	 *
	 * @param m
	 *            (predicted) number of peers that left the system
	 * @param n
	 *            number of all peers
	 * @param r
	 *            reliability
	 * @param minReplicationFactor
	 *            the minimal replication factor, not considering the
	 *            reliability
	 * @param maxReplicationFactor
	 *            the maximal replication factor, not considering the
	 *            reliability
	 *
	 * @return the replication factor for the desired reliability rate
	 */

	public static int replicationFactor(int m, int n, double r, int minReplicationFactor, int maxReplicationFactor) {
		// f = replication factor
		for (int f = minReplicationFactor; f < maxReplicationFactor; f++) {
			// probability that we hit exactly all the f peers where we have our
			// replicas.
			// p1 = 1/(n choose f)
			//
			// probability that we hit exactly all the f peers that went offline
			// p2 = 1/(m choose f)
			//
			// probability that we hit all replicas with the peers that went
			// offline / probability of f peers being part of the departing m
			// peers
			// p = p1/p2
			double p = choose(m, f) / choose(n, f);
			// 1 − p gives the probability of f peers not being within predicted
			// departing m peers. As automatic replication mechanism is supposed
			// to provide at least reliability r,
			// 1 − p should be more than or equal to r
			//
			// 1-p >= r
			if (1 - p >= r) {
				return f;
			}
		}
		return maxReplicationFactor;
	}

	/**
	 * nCR (ohne Zurücklegen, ohne Beachtung der Reihenfolge)
	 *
	 * http://stackoverflow.com/questions/1678690/what-is-a-good-way-to-
	 * implement-choose-notation-in-java
	 *
	 * @param n
	 * @param k
	 * @return
	 */
	public static double choose(int n, int k) {
		if (k < 0 || k > n)
			return 0;
		if (k > n / 2) {
			// choose(n,k) == choose(n,n-k),
			// so this could save a little effort
			k = n - k;
		}

		double answer = 1.0;
		for (int i = 1; i <= k; i++) {
			answer *= (n + 1 - i);
			answer /= i;
		}
		return answer;
	}

	/**
	 * Calculate the replication factor given the reliability within a churn
	 * interval and the (predicted) number of peers that left the system.
	 *
	 * Faster than replicationFactor as we only use one for loop.
	 *
	 * @param m
	 *            (predicted) number of peers that left the system
	 * @param n
	 *            number of all peers
	 * @param r
	 *            reliability
	 * @param minReplicationFactor
	 *            the minimal replication factor, not considering the
	 *            reliability
	 * @param maxReplicationFactor
	 *            the maximal replication factor, not considering the
	 *            reliability
	 * @return the replication factor for the desired reliability rate
	 */
	public static int replicationFactor2(int m, int n, double r, int minReplicationFactor, int maxReplicationFactor) {
		// f = replication factor
		for (int f = minReplicationFactor; f < maxReplicationFactor; f++) {
			double p = 1.0;
			for (int i = 0; i < f; i++) {
				p = p * (m - i) / (n - i);
			}
			// 1 − p gives the probability of f peers not being within predicted
			// departing m peers. As automatic replication mechanism is supposed
			// to provide at least reliability r,
			// 1 − p should be more than or equal to r
			//
			// 1-p >= r
			if (1 - p >= r) {
				return f;
			}
		}
		return maxReplicationFactor;
	}

	/**
	 * The interval length which results in maximum value of R squared is
	 * considered to be the best solution for the smoothing factor.
	 *
	 * @param x
	 *            The array of independent values, i.e. observations
	 * @param y
	 *            The array of dependent values, i.e. averages
	 * @return Smoothing factor alpha, which is based on the interval length
	 *         which results in maximum value of R squared.
	 */
	public static double bestSmoothingFactor(ArrayList<Integer> x, ArrayList<Double> y) {
		final int size = x.size();
		double max = 0;
		int interval = size;
		//make sure we have more than 2 points, otherwise we will have a perfect linear regression
		for (int i = size; i >= 3; i--) {
			double r2 = linearRegression(x, y, i);
			if (r2 >= max) {
				max = r2;
				interval = i;
			}
		}
		return 2.0 / (interval + 1);
	}

	/**
	 * LinearRegression, adapted from:
	 * http://introcs.cs.princeton.edu/java/97data/LinearRegression.java.html
	 *
	 * @param x
	 *            The array of independent values, i.e. observations
	 * @param y
	 *            The array of dependent values, i.e. averages
	 * @param interval
	 *            How much values should be considered
	 * @return R squared - defines how much percent of dependent values can be
	 *         explained by independent values. The closer R squared is to 1,
	 *         the better relationship between dependent and independent values.
	 */
	public static double linearRegression(final ArrayList<Integer> x, final ArrayList<Double> y, final int n) {
		// first pass: read in data, compute xbar and ybar
		double sumx = 0.0, sumy = 0.0;
		for (int i = n - 1; i >= 0; i--) {
			sumx += x.get(i);
			sumy += y.get(i);
		}
		double xbar = sumx / n;
		double ybar = sumy / n;

		// second pass: compute summary statistics
		double xxbar = 0.0, yybar = 0.0, xybar = 0.0;
		for (int i = n - 1; i >= 0; i--) {
			xxbar += (x.get(i) - xbar) * (x.get(i) - xbar);
			yybar += (y.get(i) - ybar) * (y.get(i) - ybar);
			xybar += (x.get(i) - xbar) * (y.get(i) - ybar);
		}
		double beta1 = xybar / xxbar;
		double beta0 = ybar - beta1 * xbar;

		// analyze results
		double ssr = 0.0; // regression sum of squares
		for (int i = n - 1; i >= 0; i--) {
			double fit = beta1 * x.get(i) + beta0;
			ssr += (fit - ybar) * (fit - ybar);
		}
		double r2 = ssr / yybar;
		return r2;
	}

	/**
	 * Exponential Moving Average with Dynamic Smoothing Factor
	 *
	 * @param observations
	 *            Array that contains peer departures numbers.
	 * @param emas
	 *            Array that contains values of exponential moving averages
	 * @param interval
	 *            The length of interval that is used to calculate smoothing
	 *            factor
	 * @return The exponential moving average for given observations of peer
	 *         departures.
	 */
	public static double ema(ArrayList<Integer> observations, ArrayList<Double> emas) {
		double alpha = bestSmoothingFactor(observations, emas);
		final int lastObservation = observations.get(observations.size() - 1);
		final double lastEMA = emas.get(emas.size() - 1);
		// EMA today = EMA_yesterday + alpha * (value_today - EMA_yesterday)
		return lastEMA + (alpha * (lastObservation - lastEMA));
	}

	/**
	 * Calculation of sample standard deviation for a set of values. Inspired
	 * by: http://introcs.cs.princeton.edu/java/stdlib/StdStats.java.html
	 *
	 * @param range
	 *            A set of values
	 * @param currentAverage
	 *            Average value for the set
	 * @return The standard deviation
	 */
	public static double standardDeviation(ArrayList<Integer> range, double average) {
		if (range.size() <= 1) {
			return 0.0;
		}
		double sd = 0;
		final int size = range.size();
		for (int i = 0; i < size; i++) {
			sd = sd + Math.pow(range.get(i) - average, 2);
		}
		sd = sd / (size - 1);
		return Math.sqrt(sd);
	}

	/**
	 * Exponential Moving Average with Dynamic Smoothing Factor plus Deviation
	 *
	 * @param observations
	 *            Array that contains recent peer departures numbers.
	 * @param currentAverage
	 *            Current exponential moving average
	 * @param interval
	 *            The length of interval that is used to calculate deviation
	 * @return The exponential moving average plus deviation for a given
	 *         observation of peer departures. This value is regarded as a
	 *         prediction value for the next second.
	 */
	public static int predictedValue(ArrayList<Integer> observations, double currentAverage) {
		double deviation = standardDeviation(observations, currentAverage);
		//round up, as we defined a minimum reliability
		return (int) Math.floor(currentAverage + deviation);
	}

}

redpajama_set_name: RedPajamaGithub


text:
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import {Pagina2Page} from '../pagina-2/pagina-2';

/*
  Generated class for the Pagina1Page page.

  See http://ionicframework.com/docs/v2/components/#navigation for more info on
  Ionic pages and navigation.
*/
@Component({
  templateUrl: 'build/pages/pagina-1/pagina-1.html',
})
export class Pagina1Page {

  constructor(private nav: NavController) {

  }
  irPagina2(){
    //push another page onto the history stack
    //causing the nav controller to animate the new page in
    this.nav.push(Pagina2Page);
  }
}


text:
// ExpectedAndFound.java, created on Apr 19, 2012
package eu.fabiostrozzi.ceppo.terms;

/**
 * Expected and found details.
 *
 * @author fabio
 */
public class ExpectedAndFound implements Term {
	private Object[] found;
	private Object[] expected;

	/**
	 * @return the found
	 */
	public Object[] getFound() {
		return found;
	}

	/**
	 * @param found
	 *            the found to set
	 */
	public void setFound(Object[] foundWhat) {
		this.found = foundWhat;
	}

	/**
	 * @return the expected
	 */
	public Object[] getExpected() {
		return expected;
	}

	/**
	 * @param expected
	 *            the expected to set
	 */
	public void setExpected(Object[] expectedWhat) {
		this.expected = expectedWhat;
	}
}


text:
using System;
using System.Runtime.Serialization;
using System.Threading.Tasks;
using Orleans;
using Orleans.Providers;
using Orleans.Runtime;
using Microsoft.Extensions.Logging;
using Orleans.Serialization;

namespace UnitTests.StorageTests
{
    [Serializable]
    public enum ErrorInjectionPoint
    {
        Unknown = 0,
        None = 1,
        BeforeRead = 2,
        AfterRead = 3,
        BeforeWrite = 4,
        AfterWrite = 5
    }

    [Serializable]
    [GenerateSerializer]
    public struct ErrorInjectionBehavior
    {
        public static readonly ErrorInjectionBehavior None = new ErrorInjectionBehavior { ErrorInjectionPoint = ErrorInjectionPoint.None };

        [Id(0)]
        public Type ExceptionType { get; set; }
        [Id(1)]
        public ErrorInjectionPoint ErrorInjectionPoint { get; set; }
    }

    [Serializable]
    [GenerateSerializer]
    public class StorageProviderInjectedError : OrleansException
    {
        [Id(0)]
        private readonly ErrorInjectionPoint errorInjectionPoint;

        public StorageProviderInjectedError(ErrorInjectionPoint errorPoint)
        {
            errorInjectionPoint = errorPoint;
        }

        public StorageProviderInjectedError()
        {
            errorInjectionPoint = ErrorInjectionPoint.Unknown;
        }

        public override string Message
        {
            get
            {
                return "ErrorInjectionPoint=" + Enum.GetName(typeof(ErrorInjectionPoint), errorInjectionPoint);
            }
        }

        protected StorageProviderInjectedError(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
        }

        protected StorageProviderInjectedError(string message) : base(message)
        {
        }

        protected StorageProviderInjectedError(string message, Exception innerException) : base(message, innerException)
        {
        }
    }

    public class ErrorInjectionStorageProvider : MockStorageProvider, IControllable
    {
        private ILogger logger;

        public ErrorInjectionStorageProvider(
            ILogger<ErrorInjectionStorageProvider> logger,
            ILoggerFactory loggerFactory,
            DeepCopier copier) : base(loggerFactory, copier)
        {
            this.logger = logger;
            SetErrorInjection(ErrorInjectionBehavior.None);
        }

        public static async Task SetErrorInjection(string providerName, ErrorInjectionBehavior errorInjectionBehavior, IGrainFactory grainFactory)
        {
            IManagementGrain mgmtGrain = grainFactory.GetGrain<IManagementGrain>(0);
            await mgmtGrain.SendControlCommandToProvider(
                typeof(ErrorInjectionStorageProvider).FullName,
                providerName,
                (int)Commands.SetErrorInjection,
                errorInjectionBehavior);
        }

        public ErrorInjectionBehavior ErrorInjection { get; private set; }

        internal static bool DoInjectErrors = true;

        public void SetErrorInjection(ErrorInjectionBehavior errorInject)
        {
            ErrorInjection = errorInject;
            logger.LogInformation("Set ErrorInjection to {ErrorInjection}", ErrorInjection);
        }

        public async override Task Close()
        {
            logger.LogInformation("Close ErrorInjection={ErrorInjection}", ErrorInjection);
            try
            {
                SetErrorInjection(ErrorInjectionBehavior.None);
                await base.Close();
            }
            catch (Exception exc)
            {
                logger.LogError(exc, "Unexpected error during Close");
                throw;
            }
        }

        public async override Task ReadStateAsync<T>(string grainType, GrainReference grainReference, IGrainState<T> grainState)
        {
            logger.LogInformation( "ReadStateAsync for {GrainType} {GrainId} ErrorInjection={ErrorInjection}", grainType, grainReference?.GrainId, ErrorInjection);
            try
            {
                ThrowIfMatches(ErrorInjectionPoint.BeforeRead);
                await base.ReadStateAsync(grainType, grainReference, grainState);
                ThrowIfMatches(ErrorInjectionPoint.AfterRead);
            }
            catch (Exception exc)
            {
                logger.LogWarning(exc, "Injected error during ReadStateAsync for {GrainType} {GrainId}", grainType, grainReference?.GrainId);
                throw;
            }
        }

        public async override Task WriteStateAsync<T>(string grainType, GrainReference grainReference, IGrainState<T> grainState)
        {
            logger.LogInformation("WriteStateAsync for {GrainType} {GrainReference} ErrorInjection={ErrorInjection}", grainType, grainReference, ErrorInjection);
            try
            {
                ThrowIfMatches(ErrorInjectionPoint.BeforeWrite);
                await base.WriteStateAsync(grainType, grainReference, grainState);
                ThrowIfMatches(ErrorInjectionPoint.AfterWrite);
            }
            catch (Exception exc)
            {
                logger.LogWarning(exc, "Injected error during WriteStateAsync for {GrainType} {GrainId}", grainType, grainReference?.GrainId);
                throw;
            }
        }

        private void ThrowIfMatches(ErrorInjectionPoint executingPoint)
        {
            if (DoInjectErrors && ErrorInjection.ErrorInjectionPoint == executingPoint)
            {
                if (ErrorInjection.ExceptionType == null || ErrorInjection.ExceptionType == typeof(StorageProviderInjectedError))
                {
                    throw new StorageProviderInjectedError(ErrorInjection.ErrorInjectionPoint);
                }
                else
                {
                    throw ((Exception)Activator.CreateInstance(ErrorInjection.ExceptionType));
                }
            }
        }

        /// <summary>
        /// A function to execute a control command.
        /// </summary>
        /// <param name="command">A serial number of the command.</param>
        /// <param name="arg">An opaque command argument</param>
        public override Task<object> ExecuteCommand(int command, object arg)
        {
            switch ((Commands)command)
            {
                case Commands.SetErrorInjection:
                    SetErrorInjection((ErrorInjectionBehavior)arg);
                    return Task.FromResult<object>(true);
                default:
                    return base.ExecuteCommand(command, arg);
            }
        }
    }
}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
Willdenowia 12:45. 1982

#### Original name
Linum mauritanicum Pomel

### Remarks
null


text:
package uk.co.quidos.gdsap.evaluation.calculate.output;

import java.io.FileInputStream;

import org.dom4j.Document;
import org.dom4j.io.SAXReader;

import com.google.gson.Gson;

public class OATrunk {

	private String RdSAPXml;
	private String OAXml;
	private String GDIPXml;
	private String country;
    private Integer version;

    public OATrunk(String RdSAPXml, String OAXml, String GDIPXml, String country, Integer version)
    {
    	this.RdSAPXml = RdSAPXml;
    	this.OAXml = OAXml;
    	this.GDIPXml = GDIPXml;
    	this.country = country;
    	this.version = version;
    }

    public String toJosn()
    {
    	String json = null;
    	Gson gson = new Gson();
    	json = gson.toJson(this);
    	return json;
    }

    public OATrunk toOATrunk(String json)
    {
    	Gson gson = new Gson();
    	OATrunk oa = (OATrunk) gson.fromJson(json, OATrunk.class);
    	return oa;
    }

    public static void main(String[] args) {
    	Document calDocument = getDocumentByURI("D:\\VS2012\\OA_LIG17_output\\OA-1_CAL.xml");
    	OATrunk oa = new OATrunk(null,calDocument.asXML(),null,"EAW",992);
    	System.out.println(oa.toJosn());

    	OATrunk oa2 = oa.toOATrunk(oa.toJosn());
    	System.out.println(oa2.getOAXml());
	}

    public static Document getDocumentByURI(String path){
		SAXReader reader = new SAXReader();
        Document document = null;
		try {
			document = reader.read(new FileInputStream(path));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return document;
	}

	public String getRdSAPXml() {
		return RdSAPXml;
	}
	public void setRdSAPXml(String rdSAPXml) {
		RdSAPXml = rdSAPXml;
	}
	public String getOAXml() {
		return OAXml;
	}
	public void setOAXml(String oAXml) {
		OAXml = oAXml;
	}
	public String getGDIPXml() {
		return GDIPXml;
	}
	public void setGDIPXml(String gDIPXml) {
		GDIPXml = gDIPXml;
	}
	public String getCountry() {
		return country;
	}
	public void setCountry(String country) {
		this.country = country;
	}
	public Integer getVersion() {
		return version;
	}
	public void setVersion(Integer version) {
		this.version = version;
	}
}


text:
cd ~
easy_install mercurial

mkdir ~/webapps
mkdir ~/webapps/myshop

# go to your app directory and set some variables and aliases to
# make the intallation a bit easier
cd ~/webapps/myshop
export APPBIN=`pwd`/bin
export APPLIB=`pwd`/lib/python2.5
export PYTHONPATH=$APPLIB:$PYTHONPATH
alias easy_install="easy_install-2.5 -s $APPBIN -d $APPLIB"

# fetch dependencies
mkdir src
svn checkout http://django-app-plugins.googlecode.com/svn/trunk/ src/django-app-plugins-read-only
hg clone https://sorl-thumbnail.googlecode.com/hg/ src/sorl-thumbnail
hg clone http://bitbucket.org/bkroeze/django-signals-ahoy/ src/django-signals-ahoy
hg clone http://bitbucket.org/chris1610/satchmo/ src/satchmo

# install dependencies
easy_install pycrypto
easy_install http://code.enthought.com/enstaller/eggs/rhel/3/Reportlab-2.1.0001-py2.5.egg
easy_install http://www.satchmoproject.com/snapshots/trml2pdf-1.2.tar.gz
easy_install django-registration
easy_install PyYAML
easy_install http://bitbucket.org/bkroeze/django-threaded-multihost/downloads/django_threaded_multihost-1.3_2-py2.5.egg
easy_install src/django-app-plugins-read-only
easy_install src/sorl-thumbnail
easy_install src/django-signals-ahoy
easy_install src/satchmo

# copy satchmo local settings
cp src/satchmo/satchmo/projects/base/local_settings.py myproject/


text:
  * [FIX] : Fixes auto focus on the editor when opening the dialog.
  * [FIX] : Fixes space character encoding
  * [FEATURE] : Added property to choose the ACE Editor sources

## v1.2.2 (4.0.x - 4.4.x)

  * [FIX] : Fixes ckeditor style overriden by pbckcode plugin

## v1.2.1 (4.0.x - 4.3.x)

  * [FIX] : problem with minification for CKEditor Builder
  * [FIX] : multiples script loads when you instanciate several CKEditor on the same page

From the v1.2.1, ACE Editor is now loaded from the [jsDelivr CDN](http://www.jsdelivr.com/). The loading will be faster and the plugin size will be smaller.

## v1.2.0 (4.0.x - 4.3.x)

  * [FIX] : fix problem of external files loading
  * [IMPROVEMENT] : load external files only once
  * [FEATURE] : tab size settings
  * [FIX] : added CKEditor ACF to parse already saved code

## v1.1.0 (4.0.x - 4.1.x)

  * [FEATURE] : added several syntax highlighters (Prism.js, Highlight.js, SyntaxHighlighter.js)


text:
/*
 * IEEE754 floating point
 * double precision internal header file
 */
/*
 * MIPS floating point support
 * Copyright (C) 1994-2000 Algorithmics Ltd.
 *
 *  This program is free software; you can distribute it and/or modify it
 *  under the terms of the GNU General Public License (Version 2) as
 *  published by the Free Software Foundation.
 *
 *  This program is distributed in the hope it will be useful, but WITHOUT
 *  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 *  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 *  for more details.
 *
 *  You should have received a copy of the GNU General Public License along
 *  with this program; if not, write to the Free Software Foundation, Inc.,
 *  51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA.
 */

#include <linux/compiler.h>

#include "ieee754int.h"

#define assert(expr) ((void)0)

#define DP_EBIAS	1023
#define DP_EMIN		(-1022)
#define DP_EMAX		1023
#define DP_FBITS	52
#define DP_MBITS	52

#define DP_MBIT(x)	((u64)1 << (x))
#define DP_HIDDEN_BIT	DP_MBIT(DP_FBITS)
#define DP_SIGN_BIT	DP_MBIT(63)

#define DPSIGN(dp)	(dp.sign)
#define DPBEXP(dp)	(dp.bexp)
#define DPMANT(dp)	(dp.mant)

static inline int ieee754dp_finite(union ieee754dp x)
{
	return DPBEXP(x) != DP_EMAX + 1 + DP_EBIAS;
}

/* 3bit extended double precision sticky right shift */
#define XDPSRS(v,rs)	\
	((rs > (DP_FBITS+3))?1:((v) >> (rs)) | ((v) << (64-(rs)) != 0))

#define XDPSRSX1() \
	(xe++, (xm = (xm >> 1) | (xm & 1)))

#define XDPSRS1(v)	\
	(((v) >> 1) | ((v) & 1))

/* convert denormal to normalized with extended exponent */
#define DPDNORMx(m,e) \
	while ((m >> DP_FBITS) == 0) { m <<= 1; e--; }
#define DPDNORMX	DPDNORMx(xm, xe)
#define DPDNORMY	DPDNORMx(ym, ye)

static inline union ieee754dp builddp(int s, int bx, u64 m)
{
	union ieee754dp r;

	assert((s) == 0 || (s) == 1);
	assert((bx) >= DP_EMIN - 1 + DP_EBIAS
	       && (bx) <= DP_EMAX + 1 + DP_EBIAS);
	assert(((m) >> DP_FBITS) == 0);

	r.sign = s;
	r.bexp = bx;
	r.mant = m;

	return r;
}

extern union ieee754dp __cold ieee754dp_nanxcpt(union ieee754dp);
extern union ieee754dp ieee754dp_format(int, int, u64);


text:
using System;
using AutoFixture.Kernel;

namespace AutoFixture.AutoFakeItEasy2
{
    /// <summary>
    /// Provides pre- and post-condition checks for requests for fake instances.
    /// </summary>
    /// <seealso cref="Create(object, ISpecimenContext)" />
    [Obsolete("The AutoFakeItEasy2 package has been retired; use the AutoFakeItEasy (without the trailing \"2\") package instead. Details: it's turned out that it's possible to enable AutoFakeItEasy to also work with FakeItEasy 2. From version 3.49.1, you should be able to use AutoFakeItEasy with FakeItEasy 2 by adding an assembly binding redirect. This enables us, the maintainers of AutoFixture, to maintain only one code base for FakeItEasy, instead of two. If this causes problems, please create an issue at https://github.com/AutoFixture/AutoFixture/issues. We apologise for any inconvenience this may cause.", true)]
    public class FakeItEasyBuilder : ISpecimenBuilder
    {
        private readonly ISpecimenBuilder builder;

        /// <summary>
        /// Initializes a new instance of the <see cref="FakeItEasyBuilder"/> class with an
        /// <see cref="ISpecimenBuilder" /> to decorate.
        /// </summary>
        /// <param name="builder">The builder which must build mock instances.</param>
        /// <remarks>
        /// <para>
        /// <paramref name="builder" /> is subsequently available through the <see cref="Builder"/>
        /// property.
        /// </para>
        /// </remarks>
        /// <seealso cref="Builder" />
        public FakeItEasyBuilder(ISpecimenBuilder builder)
        {
            this.builder = builder ?? throw new ArgumentNullException(nameof(builder));
        }

        /// <summary>
        /// Gets the decorated builder supplied through the constructor.
        /// </summary>
        /// <seealso cref="FakeItEasyBuilder(ISpecimenBuilder)" />
        public ISpecimenBuilder Builder
        {
            get { return this.builder; }
        }

        /// <summary>
        /// Creates a new specimen based on a request.
        /// </summary>
        /// <param name="request">The request that describes what to create.</param>
        /// <param name="context">A context that can be used to create other specimens.</param>
        /// <returns>
        /// A mock instance created by FakeItEasy if appropriate; otherwise a
        /// <see cref="NoSpecimen"/> instance.
        /// </returns>
        /// <remarks>
        /// <para>
        /// The Create method checks whether a request is for an interface or abstract class. If so
        /// it delegates the call to the decorated <see cref="Builder"/>. When the specimen is
        /// returned from the decorated <see cref="ISpecimenBuilder"/> the method checks whether
        /// the returned instance is a FakeItEasy Fake instance of the correct type.
        /// </para>
        /// <para>
        /// If all pre- and post-conditions are satisfied, the mock instance is returned; otherwise
        /// a <see cref="NoSpecimen" /> instance.
        /// </para>
        /// </remarks>
        public object Create(object request, ISpecimenContext context)
        {
            var type = request as Type;
            if (type == null || !type.IsFake())
            {
                return new NoSpecimen();
            }

            var fake = this.builder.Create(request, context);
            if (!type.IsInstanceOfType(fake))
            {
                return new NoSpecimen();
            }

            return fake;
        }
    }
}


text:
package org.orekit.files.ccsds.ndm.cdm;

/** Maneuvrable possibilities used in CCSDS Conjunction Data Messages.
 * @author Melina Vanel
 * @since 11.2
 */
public enum Maneuvrable {

    /** Maneuvrable. */
    YES("YES"),

    /** Non Maneuvrable. */
    NO("NO"),

    /** Don't know or not applicable. */
    N_A("N/A");

    /** Value of the enum .*/
    private String value;

    Maneuvrable(final String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }

    @Override
    public String toString() {
        return this.getValue();
    }

    public static Maneuvrable getEnum(final String keyValue) {
        for (Maneuvrable v : values()) {
            if (v.getValue().equalsIgnoreCase(keyValue)) {
                return v;
            }
        }
        throw new IllegalArgumentException();
    }

}


text:
using System;
using System.Runtime.InteropServices;

namespace CppSharp
{
    public static class SymbolResolver
    {
        static readonly string[] formats;
        static readonly Func<string, IntPtr> loadImage;
        static readonly Func<IntPtr, string, IntPtr> resolveSymbol;

        static SymbolResolver ()
        {
            switch (Environment.OSVersion.Platform)
            {
            case PlatformID.Unix:
            case PlatformID.MacOSX:
                loadImage = dlopen;
                resolveSymbol = dlsym;
                formats = new[] {
                    "{0}",
                    "{0}.so",
                    "{0}.dylib",
                    "lib{0}.so",
                    "lib{0}.dylib",
                    "{0}.bundle"
                };
                break;
            default:
                loadImage = LoadLibrary;
                resolveSymbol = GetProcAddress;
                formats = new[] { "{0}", "{0}.dll" };
                break;
            }
        }

        public static IntPtr LoadImage (ref string name)
        {
            foreach (var format in formats)
            {
                var attempted = string.Format (format, name);
                var ptr = loadImage (attempted);

                if (ptr == IntPtr.Zero)
                    continue;

                name = attempted;
                return ptr;
            }

            return IntPtr.Zero;
        }

        public static IntPtr ResolveSymbol (string name, string symbol)
        {
            var image = LoadImage(ref name);
            return ResolveSymbol(image, symbol);
        }

        public static IntPtr ResolveSymbol (IntPtr image, string symbol)
        {
            if (image != IntPtr.Zero)
                return resolveSymbol (image, symbol);

            return IntPtr.Zero;
        }

        #region POSIX

        static IntPtr dlopen (string path)
        {
            return dlopen (path, 0x0);
        }

        [DllImport ("dl", CharSet=CharSet.Ansi)]
        static extern IntPtr dlopen (string path, int flags);

        [DllImport ("dl", CharSet=CharSet.Ansi)]
        static extern IntPtr dlsym (IntPtr handle, string symbol);

        #endregion

        #region Win32

        [DllImport("kernel32", SetLastError=true)]
        static extern IntPtr LoadLibrary (string lpFileName);

        [DllImport("kernel32", CharSet=CharSet.Ansi, ExactSpelling=true, SetLastError=true)]
        static extern IntPtr GetProcAddress (IntPtr hModule, string procName);

        #endregion

    }
}


text:
import unittest
from prime import prime_numbers

class PrimeTest(unittest.TestCase):
    def test_returns_prime_numbers(self):
        self.assertListEqual(prime_numbers(6), [2,3,5], msg="Range of 0-6 should return [2,3,5] as the prime numbers")

    def test_input_is_a_number(self):
        with self.assertRaises(TypeError, msg="Should raise type error if a string is passed as argument"):
            prime_numbers("String")

    def test_return_value_is_list(self):
        self.assertTrue(isinstance(prime_numbers(10), list), msg="The function should return a list")

    def test_returns_None_for_negative_input(self):
        self.assertEqual(prime_numbers(-30),"No prime numbers within that range! All prime numbers are positive",msg="There are no negative primes")

    def test_does_not_return_negative_primes(self):
        self.assertGreater(min(prime_numbers(50)),0)

    def test_does_not_include_non_primes(self):
        self.assertNotIn([0,1,4,6],prime_numbers(6))

if __name__=='__main__':
    unittest.main()


text:
require "vagrant"

module VagrantPlugins
  module GuestSUSE
    class Plugin < Vagrant.plugin("2")
      name "SUSE guest"
      description "SUSE guest support."

      guest("suse", "linux") do
        require File.expand_path("../guest", __FILE__)
        Guest
      end

      guest_capability("suse", "change_host_name") do
        require_relative "cap/change_host_name"
        Cap::ChangeHostName
      end

      guest_capability("suse", "configure_networks") do
        require_relative "cap/configure_networks"
        Cap::ConfigureNetworks
      end

      guest_capability("suse", "halt") do
        require_relative "cap/halt"
        Cap::Halt
      end

      guest_capability("suse", "network_scripts_dir") do
        require_relative "cap/network_scripts_dir"
        Cap::NetworkScriptsDir
      end

      guest_capability("suse", "nfs_client_install") do
        require_relative "cap/nfs_client"
        Cap::NFSClient
      end

      guest_capability("suse", "rsync_install") do
        require_relative "cap/rsync"
        Cap::RSync
      end

      guest_capability("suse", "rsync_installed") do
        require_relative "cap/rsync"
        Cap::RSync
      end
    end
  end
end


text:
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ash/system/network/auto_connect_notifier.h"

#include "ash/public/cpp/network_icon_image_source.h"
#include "ash/public/cpp/notification_utils.h"
#include "ash/strings/grit/ash_strings.h"
#include "base/bind_helpers.h"
#include "base/logging.h"
#include "base/strings/string16.h"
#include "base/time/time.h"
#include "base/timer/timer.h"
#include "chromeos/network/network_connection_handler.h"
#include "chromeos/network/network_event_log.h"
#include "chromeos/network/network_state.h"
#include "chromeos/network/network_state_handler.h"
#include "chromeos/network/network_type_pattern.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/image/canvas_image_source.h"
#include "ui/gfx/image/image.h"
#include "ui/message_center/message_center.h"
#include "ui/message_center/public/cpp/message_center_constants.h"
#include "ui/message_center/public/cpp/notification.h"
#include "ui/message_center/public/cpp/notification_types.h"
#include "ui/message_center/public/cpp/notifier_id.h"
#include "url/gurl.h"

using chromeos::NetworkHandler;

namespace ash {

namespace {

// Timeout used for connecting to a managed network. When an auto-connection is
// initiated, we expect the connection to occur within this amount of time. If
// a timeout occurs, we assume that no auto-connection occurred and do not show
// a notification.
constexpr const base::TimeDelta kNetworkConnectionTimeout =
    base::TimeDelta::FromSeconds(3);

const char kNotifierAutoConnect[] = "ash.auto-connect";

}  // namespace

// static
const char AutoConnectNotifier::kAutoConnectNotificationId[] =
    "cros_auto_connect_notifier_ids.connected_to_network";

AutoConnectNotifier::AutoConnectNotifier()
    : timer_(std::make_unique<base::OneShotTimer>()) {
  // NetworkHandler may not be initialized in tests.
  if (NetworkHandler::IsInitialized()) {
    auto* network_handler = NetworkHandler::Get();
    network_handler->network_connection_handler()->AddObserver(this);
    network_handler->network_state_handler()->AddObserver(this, FROM_HERE);
    // AutoConnectHandler may not be initialized in tests with NetworkHandler.
    if (network_handler->auto_connect_handler())
      network_handler->auto_connect_handler()->AddObserver(this);
  }
}

AutoConnectNotifier::~AutoConnectNotifier() {
  // NetworkHandler may not be initialized in tests.
  if (NetworkHandler::IsInitialized()) {
    auto* network_handler = NetworkHandler::Get();
    // AutoConnectHandler may not be initialized in tests with NetworkHandler.
    if (network_handler->auto_connect_handler())
      network_handler->auto_connect_handler()->RemoveObserver(this);
    network_handler->network_state_handler()->RemoveObserver(this, FROM_HERE);
    network_handler->network_connection_handler()->RemoveObserver(this);
  }
}

void AutoConnectNotifier::ConnectToNetworkRequested(
    const std::string& /* service_path */) {
  has_user_explicitly_requested_connection_ = true;
}

void AutoConnectNotifier::NetworkConnectionStateChanged(
    const chromeos::NetworkState* network) {
  // Ignore non WiFi networks completely.
  if (!network->Matches(chromeos::NetworkTypePattern::WiFi()))
    return;

  // The notification is only shown when a connection has succeeded; if
  // |network| is not connected, there is nothing to do.
  if (!network->IsConnectedState()) {
    // Clear the tracked network if it is no longer connected or connecting.
    if (!network->IsConnectingState() &&
        network->guid() == connected_network_guid_) {
      connected_network_guid_.clear();
    }
    return;
  }

  // No notification should be shown unless an auto-connection is underway.
  if (!timer_->IsRunning()) {
    // Track the currently connected network.
    connected_network_guid_ = network->guid();
    return;
  }

  // Ignore NetworkConnectionStateChanged for a previously connected network.
  if (network->guid() == connected_network_guid_)
    return;

  // An auto-connected network has connected successfully. Display a
  // notification alerting the user that this has occurred.
  DisplayNotification(network);
  has_user_explicitly_requested_connection_ = false;
}

void AutoConnectNotifier::OnAutoConnectedInitiated(int auto_connect_reasons) {
  // If the user has not explicitly requested a connection to another network,
  // the notification does not need to be shown.
  if (!has_user_explicitly_requested_connection_)
    return;

  // The notification should only be shown if a network is joined due to a
  // policy or certificate. Other reasons (e.g., joining a network due to login)
  // do not require that a notification be shown.
  const int kManagedNetworkReasonsBitmask =
      chromeos::AutoConnectHandler::AUTO_CONNECT_REASON_POLICY_APPLIED |
      chromeos::AutoConnectHandler::AUTO_CONNECT_REASON_CERTIFICATE_RESOLVED;
  if (!(auto_connect_reasons & kManagedNetworkReasonsBitmask))
    return;

  // If a potential connection is already underway, reset the timeout and
  // continue waiting.
  if (timer_->IsRunning()) {
    timer_->Reset();
    return;
  }

  // Auto-connection has been requested, so start a timer. If a network connects
  // successfully before the timer expires, auto-connection has succeeded, so a
  // notification should be shown. If no connection occurs before the timer
  // fires, we assume that auto-connect attempted to search for networks to
  // join but did not succeed in joining one (in that case, no notification
  // should be shown).
  timer_->Start(FROM_HERE, kNetworkConnectionTimeout, base::DoNothing());
}

void AutoConnectNotifier::DisplayNotification(
    const chromeos::NetworkState* network) {
  NET_LOG(EVENT) << "Show AutoConnect Notification for: " << NetworkId(network);
  auto notification = CreateSystemNotification(
      message_center::NotificationType::NOTIFICATION_TYPE_SIMPLE,
      kAutoConnectNotificationId,
      l10n_util::GetStringUTF16(IDS_ASH_NETWORK_AUTOCONNECT_NOTIFICATION_TITLE),
      l10n_util::GetStringUTF16(
          IDS_ASH_NETWORK_AUTOCONNECT_NOTIFICATION_MESSAGE),
      base::string16() /* display_source */, GURL() /* origin_url */,
      message_center::NotifierId(message_center::NotifierType::SYSTEM_COMPONENT,
                                 kNotifierAutoConnect),
      {} /* optional_fields */,
      base::MakeRefCounted<message_center::NotificationDelegate>(),
      gfx::VectorIcon() /* small_image */,
      message_center::SystemNotificationWarningLevel::NORMAL);

  notification->set_small_image(gfx::Image(network_icon::GetImageForWifiNetwork(
      notification->accent_color(),
      gfx::Size(message_center::kSmallImageSizeMD,
                message_center::kSmallImageSizeMD))));

  message_center::MessageCenter* message_center =
      message_center::MessageCenter::Get();
  if (message_center->FindVisibleNotificationById(kAutoConnectNotificationId))
    message_center->RemoveNotification(kAutoConnectNotificationId, false);
  message_center->AddNotification(std::move(notification));
}

}  // namespace ash


text:
<?php

namespace CondensedQuery\Parser;

abstract class Procedure extends Element
{
	const FUNC_DATE = 'date';
	const FUNC_ID	= 'id';

	/**
	 * @var Element
	 */
	protected $_function = null;

	/**
	 * Test if in buffer is function
	 *
	 * @return Element|Boolean
	 */
	protected function getFunction()
	{
		switch($this->_buffer){
			case self::FUNC_DATE:	$this->_function = new Date();	break;
			case self::FUNC_ID:		$this->_function = new Id();	break;
			default:
				throw new Exception('Invalid function name', $this);
		}

		$this->_state = parent::STATE_SUB;
		return true;
	}
}


text:
@echo off
rem: Note %~dp0 get path of this batch file
rem: Need to change drive if My Documents is on a drive other than C:
set driverLetter=%~dp0
set driverLetter=%driverLetter:~0,2%
%driverLetter%
cd %~dp0
rem: the two line below are needed to fix path issues with incorrect slashes before the bin file name
set str=%4
set str=%str:/=\%

rem: ------------- use STLINK CLI
stlink\ST-LINK_CLI.exe -c SWD -P %str% 0x8000000 -Rst -Run

rem: Using the open source texane-stlink instead of the proprietary STM stlink exe
rem:texane-stlink\st-flash.exe write %str% 0x8000000


text:
package symexpr

import (
	"fmt"
	"math"
)

type ExprType int

const (
	NULL ExprType = iota

	STARTLEAF
	CONSTANT  // indexed constant, useful for non-linear regression tasks
	CONSTANTF // floating point constant
	TIME      // useful when looking at time series and RK4 integration
	SYSTEM    // i use this like a variable that changes between experiments, but not with time (mass,size,etc.)
	VAR       // a canonical variable
	LASTLEAF

	STARTFUNC
	NEG
	ABS
	SQRT
	SIN
	COS
	TAN
	EXP
	LOG
	LASTFUNC

	POWI // Expr^Integer
	POWF // Expr^Float
	POWE // Expr^Expr
	DIV  // Expr/Expr

	ADD // these can have more than two child nodes
	MUL // this eases sorting and simplification

	EXPR_MAX
	STARTVAR // for serialization reduction of variables
)

// Expr is the interface to all node types for the AST of mathematical expression
//
type Expr interface {

	// types.go (this file)
	ExprType() ExprType
	Clone() Expr

	// stats.go
	Size() int
	Depth() int
	Height() int
	NumChildren() int
	CalcExprStats()
	calcExprStatsR(depth int, pos *int)

	// compare.go
	AmILess(rhs Expr) bool
	AmIEqual(rhs Expr) bool
	AmISame(rhs Expr) bool       // equality without coefficient values/index
	AmIAlmostSame(rhs Expr) bool // adds flexibility to mul comparison to AmISame
	Sort()

	// has.go
	HasVar() bool
	HasVarI(i int) bool
	NumVar() int

	// DFS for a floating point valued ConstantF
	HasConst() bool
	// DFS for a indexed valued Constant
	HasConstI(i int) bool
	// Counts the number of indexed Constant nodes
	NumConstants() int

	// convert.go

	// Converts indexed Constant nodes to ConstantF nodes
	// using the input slice as the values for replacement
	ConvertToConstantFs(cs []float64) Expr
	// DFS converting float valued constants to indexed constants
	// the input should be an empty slice
	// the output is an appended slice the size = |ConstantF| in the tree
	ConvertToConstants(cs []float64) ([]float64, Expr)
	//   IndexConstants( ci int ) int

	// getset.go
	// DFS retrieval of a node by index
	GetExpr(pos *int) Expr
	// DFS replacement of a node and it's subtree
	// replaced is used to discontinue the DFS after replacement
	// replace_me gets triggered when pos == 0 and informs the parent node to replace the respective child node
	SetExpr(pos *int, e Expr) (replace_me, replaced bool)

	// print.go

	// prints the AST
	String() string

	// creates an integer representation of the AST in ~prefix notation
	// The input is an empty slice, output is the representation.
	// The output is generally the ExprType integer value
	// Associative operators (+ & *) also include the number of children.
	// The terminal nodes include the index when appropriate.
	Serial([]int) []int
	StackSerial([]int) []int

	// Pretty print acts like String, but replaces the internal indexed
	// formatting with user specified strings and values
	PrettyPrint(dnames, snames []string, cvals []float64) string
	// 	WriteString( buf *bytes.Buffer )

	// Similar to PrettyPrint, but in latex format
	Latex(dnames, snames []string, cvals []float64) string
	Javascript(dnames, snames []string, cvals []float64) string

	// eval.go
	// Evaluates an expression at one point
	// t is a time value
	// x are the input Var values
	// c are the indexed Constant values
	// s are the indexed System values
	// the output is the result of DFS evaluation
	Eval(t float64, x, c, s []float64) float64

	// simp.go
	Simplify(rules SimpRules) Expr

	// deriv.go
	// Calculate the derivative w.r.t. Var_i
	DerivVar(i int) Expr
	// Calculate the derivative w.r.t. Constant_i
	DerivConst(i int) Expr
}

type ExprArray []Expr

func (p ExprArray) Len() int      { return len(p) }
func (p ExprArray) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
func (p ExprArray) Less(i, j int) bool {
	if p[i] == nil && p[j] == nil {
		return false
	}
	if p[i] == nil {
		return false
	}
	if p[j] == nil {
		return true
	}
	return p[i].AmILess(p[j])
}

// Null Leaf  (shouldn't really appear)
// This is a sample for the other node types
type Null struct {
	ExprStats
}

func NewNull() *Null               { return new(Null) }
func (n *Null) ExprType() ExprType { return NULL }
func (n *Null) Clone() Expr        { return NewNull() }

func (n *Null) CalcExprStats() {
	n.depth = 1
	n.height = 1
	n.size = 1
	n.pos = 0
	n.numchld = 0
}
func (n *Null) calcExprStatsR(depth int, pos *int) {
	n.depth = depth + 1
	n.height = 1
	n.size = 1
	n.pos = *pos
	(*pos)++
	n.numchld = 0
}

func (n *Null) AmILess(r Expr) bool       { return NULL < r.ExprType() }
func (n *Null) AmIEqual(r Expr) bool      { return r.ExprType() == NULL }
func (n *Null) AmISame(r Expr) bool       { return r.ExprType() == NULL }
func (n *Null) AmIAlmostSame(r Expr) bool { return r.ExprType() == NULL }
func (n *Null) Sort()                     { return }

func (n *Null) HasVar() bool         { return false }
func (n *Null) HasVarI(i int) bool   { return false }
func (n *Null) NumVar() int          { return 0 }
func (n *Null) HasConst() bool       { return false }
func (n *Null) HasConstI(i int) bool { return false }
func (n *Null) NumConstants() int    { return 0 }

func (n *Null) ConvertToConstantFs(cs []float64) Expr             { return n }
func (n *Null) ConvertToConstants(cs []float64) ([]float64, Expr) { return cs, n }

func (n *Null) GetExpr(pos *int) Expr {
	if (*pos) == 0 {
		return n
	}
	(*pos)--
	return nil
}
func (n *Null) SetExpr(pos *int, e Expr) (replace_me, replaced bool) {
	if (*pos) == 0 {
		return true, false
	}
	(*pos)--
	return false, false
}

func (n *Null) String() string                                              { return "NULL" }
func (n *Null) Serial(sofar []int) []int                                    { return append(sofar, int(NULL)) }
func (n *Null) StackSerial(sofar []int) []int                               { return append(sofar, int(NULL)) }
func (n *Null) PrettyPrint(dnames, snames []string, cvals []float64) string { return "NULL" }
func (n *Null) Latex(dnames, snames []string, cvals []float64) string       { return "NULL" }
func (n *Null) Javascript(dnames, snames []string, cvals []float64) string  { return "null" }

func (n *Null) Eval(t float64, x, c, s []float64) float64 { return math.NaN() }

func (n *Null) Simplify(rules SimpRules) Expr { return n }

func (n *Null) DerivConst(i int) Expr { return &ConstantF{F: 0} }
func (n *Null) DerivVar(i int) Expr   { return &ConstantF{F: 0} }

func DumpExprTypes() {
	fmt.Printf("ExprTypes:\n")
	fmt.Printf("---------------\n")

	fmt.Printf("NULL:      %d\n", int(NULL))

	fmt.Printf("STARTLEAF: %d\n", int(STARTLEAF))
	fmt.Printf("CONSTANT:  %d\n", int(CONSTANT))
	fmt.Printf("TIME:      %d\n", int(TIME))
	fmt.Printf("SYSTEM:    %d\n", int(SYSTEM))
	fmt.Printf("VAR:       %d\n", int(VAR))
	fmt.Printf("LASTLEAF:  %d\n", int(LASTLEAF))

	fmt.Printf("STARTFUNC: %d\n", int(STARTFUNC))
	fmt.Printf("NEG:       %d\n", int(NEG))
	fmt.Printf("ABS:       %d\n", int(ABS))
	fmt.Printf("SQRT:      %d\n", int(SQRT))
	fmt.Printf("SIN:       %d\n", int(SIN))
	fmt.Printf("COS:       %d\n", int(COS))
	fmt.Printf("TAN:       %d\n", int(TAN))
	fmt.Printf("EXP:       %d\n", int(EXP))
	fmt.Printf("LOG:       %d\n", int(LOG))
	fmt.Printf("LASTFUNC:  %d\n", int(LASTFUNC))

	fmt.Printf("POWI:      %d\n", int(POWI))
	fmt.Printf("POWF:      %d\n", int(POWF))
	fmt.Printf("POWE:      %d\n", int(POWE))
	fmt.Printf("DIV:       %d\n", int(DIV))

	fmt.Printf("ADD:       %d\n", int(ADD))
	fmt.Printf("MUL:       %d\n", int(MUL))

	fmt.Printf("EXPR_MAX:  %d\n", int(EXPR_MAX))
	fmt.Printf("STARTVAR:  %d\n", int(STARTVAR))

}

func (e ExprType) String() string {
	switch e {
	case NULL:
		return "NULL"
	case STARTLEAF:
		return "STARTLEAF"
	case CONSTANT:
		return "CONSTANT"
	case CONSTANTF:
		return "CONSTANTF"
	case TIME:
		return "TIME"
	case SYSTEM:
		return "SYSTEM"
	case VAR:
		return "VAR"
	case LASTLEAF:
		return "LASTLEAF"
	case STARTFUNC:
		return "STARTFUNC"
	case NEG:
		return "NEG"
	case ABS:
		return "ABS"
	case SQRT:
		return "SQRT"
	case SIN:
		return "SIN"
	case COS:
		return "COS"
	case TAN:
		return "TAN"
	case EXP:
		return "EXP"
	case LOG:
		return "LOG"
	case LASTFUNC:
		return "LASTFUNC"
	case POWI:
		return "POWI"
	case POWF:
		return "POWF"
	case POWE:
		return "POWE"
	case DIV:
		return "DIV"
	case ADD:
		return "ADD"
	case MUL:
		return "MUL"
	case EXPR_MAX:
		return "EXPR_MAX"
	case STARTVAR:
		return "STARTVAR"
	default:
		return "Unknown ExprType"
	}
	return "Unknown ExprType"
}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright company="Chocolatey" file="PackageService.cs">
//   Copyright 2014 - Present Rob Reynolds, the maintainers of Chocolatey, and RealDimensions Software, LLC
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace ChocolateyGui.Services
{
    using System;
    using System.IO;
    using System.Threading.Tasks;
    using ChocolateyGui.Models;
    using ChocolateyGui.Services.PackageServices;
    using ChocolateyGui.ViewModels.Items;

    public class PackageService : IPackageService
    {
        private readonly IProgressService _progressService;
        private readonly ISourceService _sourceService;
        private readonly Func<IPackageViewModel> _packageFactory;
        private readonly ILogService _logService;

        public PackageService(
            IProgressService progressService,
            ISourceService sourceService,
            Func<IPackageViewModel> packageFactory,
            Func<Type, ILogService> logFunc)
        {
            if (logFunc == null)
            {
                throw new ArgumentNullException("logFunc");
            }

            this._progressService = progressService;
            this._sourceService = sourceService;
            this._packageFactory = packageFactory;
            this._logService = logFunc(typeof(PackageService));
        }

        public async Task<PackageSearchResults> Search(string query, Uri source = null)
        {
            return await this.Search(query, new PackageSearchOptions(), source);
        }

        public async Task<PackageSearchResults> Search(string query, PackageSearchOptions options, Uri source = null)
        {
            await this._progressService.StartLoading("Search");
            if (string.IsNullOrWhiteSpace(query))
            {
                this._progressService.WriteMessage("Loading data...");
            }
            else
            {
                this._progressService.WriteMessage(string.Format("Searching for {0}", query));
            }

            if (source == null)
            {
                source = new Uri(this._sourceService.GetDefaultSource().Url);
            }

            if (source.Scheme == "http" || source.Scheme == "https")
            {
                var results = await ODataPackageService.Search(query, this._packageFactory, options, source);
                await this._progressService.StopLoading();
                return results;
            }

            if (source.IsFile || source.IsUnc)
            {
                await this._progressService.StopLoading();
                return null;
            }

            throw new InvalidDataException("Invalid Source Uri. Double check that you current source is a valid endpoint.");
        }

        public async Task<IPackageViewModel> GetLatest(string id, bool includePrerelease = false, Uri source = null)
        {
            this._progressService.WriteMessage(string.Format("Getting latest version of {0}...", id));
            if (source == null)
            {
                var defaultSource = new Uri(this._sourceService.GetDefaultSource().Url);

                if (defaultSource.Scheme == "http" || defaultSource.Scheme == "https")
                {
                    var result = await ODataPackageService.GetLatest(id, this._packageFactory, defaultSource, includePrerelease);
                    if (result != null)
                    {
                        result.Source = defaultSource;
                        return result;
                    }
                }

                foreach (var sourceViewModel in this._sourceService.GetSources())
                {
                    var currentSource = new Uri(sourceViewModel.Url);
                    if (currentSource.Scheme == "http" || currentSource.Scheme == "https")
                    {
                        var result = await ODataPackageService.GetLatest(id, this._packageFactory, currentSource, includePrerelease);
                        if (result == null)
                        {
                            continue;
                        }

                        result.Source = currentSource;
                        await this._progressService.StopLoading();
                        return result;
                    }
                }
            }
            else
            {
                if (source.Scheme == "http" || source.Scheme == "https")
                {
                    var result = await ODataPackageService.GetLatest(id, this._packageFactory, source, includePrerelease);
                    if (result != null)
                    {
                        result.Source = source;
                    }

                    return result;
                }

                if (source.IsFile || source.IsUnc)
                {
                    return null;
                }
            }

            return null;
        }

        public async Task<IPackageViewModel> EnsureIsLoaded(IPackageViewModel viewModel, Uri source = null)
        {
            await this._progressService.StartLoading("Loading Package Information");
            this._progressService.WriteMessage("Loading remote package information...");

            // If we don't have a source, iterate through our source until we find one that matches.
            if (source == null)
            {
                var defaultSourceVm = this._sourceService.GetDefaultSource();
                var defaultSource = new Uri(defaultSourceVm.Url);
                if (defaultSource.Scheme == "http" || defaultSource.Scheme == "https")
                {
                    var result = await ODataPackageService.EnsureIsLoaded(viewModel, defaultSource);
                    if (result != null)
                    {
                        await this._progressService.StopLoading();
                        result.Source = defaultSource;
                        return result;
                    }
                }

                foreach (var sourceViewModel in this._sourceService.GetSources())
                {
                    var currentSource = new Uri(sourceViewModel.Url);
                    if (currentSource.Scheme == "http" || currentSource.Scheme == "https")
                    {
                        var result = await ODataPackageService.EnsureIsLoaded(viewModel, currentSource);
                        if (result == null)
                        {
                            continue;
                        }

                        await this._progressService.StopLoading();
                        result.Source = currentSource;
                        return result;
                    }
                }
            }
            else
            {
                if (source.Scheme == "http" || source.Scheme == "https")
                {
                    var result = await ODataPackageService.EnsureIsLoaded(viewModel, source);
                    await this._progressService.StopLoading();
                    if (result != null)
                    {
                        result.Source = source;
                    }

                    return result;
                }

                if (source.IsFile || source.IsUnc)
                {
                    await this._progressService.StopLoading();
                    return null;
                }
            }

            await this._progressService.StopLoading();
            return null;
        }

        public async Task<bool> TestSourceUrl(Uri source)
        {
            if (source.Scheme == "http" || source.Scheme == "https")
            {
                var exception = await ODataPackageService.TestPath(source);
                if (exception == null)
                {
                    return true;
                }

                this._logService.Debug("TestSourceUrl failed.", exception);
                return false;
            }

            if (source.IsFile || source.IsUnc)
            {
                return false;
            }

            return false;
        }
    }
}


text:
class BaseArticle < ActiveRecord::Base
has_many :base_article_authors
has_many :authors , :through=>:base_article_authors
has_many :image_properties, :as => :entity

# searchable do
#   integer :id
#   text :title, :stored => true
#   text :content, :stored => true
#   text :description
#   integer :author_ids, :multiple => true
# end

def article_id
  BaseArticle.all.collect(&:id) if !BaseArticle.all.blank?
end

def article_authors
 Author.all.collect(&:id)  if !BaseArticle.all.blank?
end

 def self.article_search(query,page=1,per_page=10)
 @results= results = BaseArticle.search do
    fulltext query do
      boost_fields :title => 3.0
      highlight :content
    end
    facet(:author_ids)
    paginate :page => page, :per_page => per_page
  end
  return @results
 end

 def base_article_image=(profle_image)
  self.image_properties.delete_all if !self.image_properties.blank?
  if !profle_image.blank?
  image=BaseImage.find(profle_image)
  image_path = image.resize_image(100,100)
  image_property = self.image_properties.new(:image_id=>profle_image,:entity_type=>"BaseArticle",:image_path=>image_path)
  end
 end
# after_create do |article|
#   article.index!
# end

# after_update do |article|
#   article.index!
# end
end


text:
package org.jitsi.impl.neomedia.device;

import java.util.*;

/**
 * Represents a listener which is to be notified before and after an associated
 * <tt>DeviceSystem</tt>'s function to update the list of available devices is
 * invoked.
 *
 * @author Lyubomir Marinov
 */
public interface UpdateAvailableDeviceListListener
    extends EventListener
{
    /**
     * Notifies this listener that the associated <tt>DeviceSystem</tt>'s
     * function to update the list of available devices was invoked.
     *
     * @throws Exception if this implementation encounters an error. Any
     * <tt>Throwable</tt> apart from <tt>ThreadDeath</tt> will be ignored
     * after it is logged for debugging purposes.
     */
    void didUpdateAvailableDeviceList()
        throws Exception;

    /**
     * Notifies this listener that the associated <tt>DeviceSystem</tt>'s
     * function to update the list of available devices will be invoked.
     *
     * @throws Exception if this implementation encounters an error. Any
     * <tt>Throwable</tt> apart from <tt>ThreadDeath</tt> will be ignored
     * after it is logged for debugging purposes.
     */
    void willUpdateAvailableDeviceList()
        throws Exception;
}


text:
class CreateJobs < ActiveRecord::Migration
  def change
    enable_extension 'uuid-ossp'
    create_table :jobs, id: :uuid do |t|
      t.integer :status, null: false, default: 0
      t.string :redirect_to
      t.json :error
    end
  end
end


text:
for iOS and Android, by [Eddy Verbruggen](http://www.x-services.nl)
- This repo is for PhoneGap 3.0.0 and up
- For PhoneGap 2.9.0 and lower, [switch to the phonegap-2.9.0-and-lower branch](https://github.com/EddyVerbruggen/LaunchMyApp-PhoneGap-Plugin/tree/phonegap-2.9.0-and-lower)

1. [Description](https://github.com/EddyVerbruggen/LaunchMyApp-PhoneGap-Plugin#1-description)
2. [Installation](https://github.com/EddyVerbruggen/LaunchMyApp-PhoneGap-Plugin#2-installation)
	2. [Automatically (CLI / Plugman)](https://github.com/EddyVerbruggen/LaunchMyApp-PhoneGap-Plugin#automatically-cli--plugman)
	2. [Manually](https://github.com/EddyVerbruggen/LaunchMyApp-PhoneGap-Plugin#manually)
	2. [PhoneGap Build](https://github.com/EddyVerbruggen/LaunchMyApp-PhoneGap-Plugin#phonegap-build)
3. [Usage](https://github.com/EddyVerbruggen/LaunchMyApp-PhoneGap-Plugin#3-usage)
4. [URL Scheme hints](https://github.com/EddyVerbruggen/LaunchMyApp-PhoneGap-Plugin#4-url-scheme-hints)
5. [License](https://github.com/EddyVerbruggen/LaunchMyApp-PhoneGap-Plugin#5-license)

## 1. Description

This plugin allows you to start your app by calling it with a URL like `mycoolapp://path?foo=bar`

* Compatible with [Cordova Plugman](https://github.com/apache/cordova-plugman)
* Submitted and waiting for approval at PhoneGap Build ([more information](https://build.phonegap.com/plugins))

### iOS specifics
* Forget about [using config.xml to define a URL scheme](https://build.phonegap.com/docs/config-xml#url_schemes). This plugin adds 2 essential enhancements:
  - Uniform URL scheme with Android (for which there is no option to define a URL scheme via PhoneGap configuration at all).
  - You still need to wire up the Javascript to handle incoming events. This plugin assists you with that.
* Tested on iOS 5.1, 6 and 7.

### Android specifics
* Unlike iOS, there is no way to use config.xml to define a scheme for your app. Now there is.
* Tested on Android 4.3, will most likely work with 2.2 and up.

## 2. Installation

### Automatically (CLI / Plugman)
LaunchMyApp is compatible with [Cordova Plugman](https://github.com/apache/cordova-plugman).
Replace `mycoolapp` by a nice scheme you want to have your app listen to:

```
$ cordova plugin add https://github.com/EddyVerbruggen/LaunchMyApp-PhoneGap-Plugin.git --variable URL_SCHEME=mycoolapp
```
(note that the phonegap cli doesn't accept variables, so please use the cordova cli as shown above)

The LaunchMyApp.js file is brought in automatically.

Note for iOS: there was a bug in CLI which caused an error in your `*-Info.plist`.
Please manually remove the blank line and whitespace (if any) from `NSMainNibFile` and `NSMainNibFile~ipad` (or your app won't start at all).

### Manually

#### iOS
1\. `Copy www/ios/LaunchMyApp.js` to `www/js/plugins/LaunchMyApp.js` and reference it in your `index.html`:
```html
<script type="text/javascript" src="js/plugins/LaunchMyApp.js"></script>
```

2\. Add this to your `*-Info.plist` (replace `URL_SCHEME` by a nice scheme you want to have your app listen to, like `mycoolapp`):
```xml
<key>CFBundleURLTypes</key>
<array>
  <dict>
    <key>CFBundleURLSchemes</key>
    <array>
      <string>URL_SCHEME</string>
    </array>
  </dict>
</array>
```

#### Android
1\. Copy www/android/LaunchMyApp.js to www/js/plugins/LaunchMyApp.js and reference it in your `index.html`:
```html
<script type="text/javascript" src="js/plugins/LaunchMyApp.js"></script>
```

2\. Add the following xml to your `config.xml` to always use the latest version of this plugin:
```xml
<plugin name="LaunchMyApp" value="nl.xservices.plugins.LaunchMyApp"/>
```

3\. Copy `LaunchMyApp.java` to `platforms/android/src/nl/xservices/plugins` (create the folders)

4\. Add the following to your `AndroidManifest.xml` inside the `/manifest/application/activity` node (replace `URL_SCHEME` by a nice scheme you want to have your app listen to, like `mycoolapp`):
```xml
<intent-filter>
  <data android:scheme="URL_SCHEME"/>
  <action android:name="android.intent.action.VIEW" />
  <category android:name="android.intent.category.DEFAULT" />
  <category android:name="android.intent.category.BROWSABLE" />
</intent-filter>
```

### PhoneGap Build

Using LaunchMyApp with PhoneGap Build requires you to add the following xml to your `config.xml` to use the latest version of this plugin (replace `mycoolapp` by a nice scheme you want to have your app listen to):
```xml
<gap:plugin name="nl.x-services.plugins.launchmyapp">
  <param name="URL_SCHEME" value="mycoolapp" />
</gap:plugin>
```

The LaunchMyApp.js file is brought in automatically.

## 3. Usage

1a\. Your app can be launced by linking to it like this from a website or an email for example (all of these will work):
```html
<a href="mycoolapp://">Open my app</a>
<a href="mycoolapp://somepath">Open my app</a>
<a href="mycoolapp://somepath?foo=bar">Open my app</a>
<a href="mycoolapp://?foo=bar">Open my app</a>
```

`mycoolapp` is the value of URL_SCHEME you used while installing this plugin.

1b\. If you're trying to open your app from another PhoneGap app, use the InAppBrowser plugin and launch the receiving app like this, to avoid a 'protocol not supported' error:
```html
<button onclick="window.open('mycoolapp://', '_system')">Open the other app</button>
```

2\. When your app is launched by a URL, you probably want to do something based on the path and parameters in the URL. For that, you could implement the (optional) `handleOpenURL(url)` method, which receives the URL that was used to launch your app.
```javascript
function handleOpenURL(url) {
  console.log("received url: " + url);
}
```

If you want to alert the URL for testing the plugin, at least on iOS you need to wrap it in a timeout like this:
```javascript
function handleOpenURL(url) {
  setTimeout(function() {
    alert("received url: " + url);
  }, 0);
}
```
A more useful implementation would mean parsing the URL, saving any params to sessionStorage and redirecting the app to the correct page inside your app.
All this happens before the first page is loaded.

### Android Quirck
When the launchMode of your activity in AndroidManifest.xml is 'singleTask', your app does start via the URL scheme, but it will not receive any parameters. To work around this, change the launchMode (duh), or add this anywhere in your app:
```javascript
document.addEventListener("pause", function(){navigator.app.exitApp()}, false);
```

## 4. URL Scheme hints
Please choose a URL_SCHEME which which complies to these restrictions:
- Don't use an already registered scheme (like `fb`, `twitter`, `comgooglemaps`, etc).
- Use only lowercase characters.
- Don't use a dash `-` because on Android it will become underscore `_`.
- Use only 1 word (no spaces).

TIP: test your scheme by installing the app on a device or simulator and typing yourscheme:// in the browser URL bar, or create a test HTML page with a link to your app to impress your buddies.

## 5. License

[The MIT License (MIT)](http://www.opensource.org/licenses/mit-license.html)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.


text:
package edu.rhhs.frc.commands;

import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.command.Command;

/**
 * @author rhhs
 */
public abstract class ExtraThreeTimeoutCommandBase extends CommandBase {

    protected double m_extraTimeout1 = -1;
    private double m_startExtraTime1;
    protected double m_extraTimeout2 = -1;
    private double m_startExtraTime2;
    protected double m_extraTimeout3 = -1;
    private double m_startExtraTime3;

    public ExtraThreeTimeoutCommandBase() {
    }

    /**
     * Sets the timeout of this command.
     *
     * @param seconds the timeout (in seconds)
     * @throws IllegalArgumentException if seconds is negative
     * @see Command#isTimedOut() isTimedOut()
     */
    protected synchronized final void startExtraTimeout1(double seconds) {
        if (seconds < 0) {
            throw new IllegalArgumentException("Seconds must be positive.  Given:" + seconds);
        }
        m_startExtraTime1 = Timer.getFPGATimestamp();
        m_extraTimeout1 = seconds;
    }

    protected synchronized final void startExtraTimeout2(double seconds) {
        if (seconds < 0) {
            throw new IllegalArgumentException("Seconds must be positive.  Given:" + seconds);
        }
        m_startExtraTime2 = Timer.getFPGATimestamp();
        m_extraTimeout2 = seconds;
    }

    protected synchronized final void startExtraTimeout3(double seconds) {
        if (seconds < 0) {
            throw new IllegalArgumentException("Seconds must be positive.  Given:" + seconds);
        }
        m_startExtraTime3 = Timer.getFPGATimestamp();
        m_extraTimeout3 = seconds;
    }

    /**
     * Returns the time since this command was initialized (in seconds).
     * This function will work even if there is no specified timeout.
     * @return the time since this command was initialized (in seconds).
     */
    public synchronized final double timeSinceExtraInitialized1() {
        return m_startExtraTime1 < 0 ? 0 : Timer.getFPGATimestamp() - m_startExtraTime1;
    }

    public synchronized final double timeSinceExtraInitialized2() {
        return m_startExtraTime2 < 0 ? 0 : Timer.getFPGATimestamp() - m_startExtraTime2;
    }

    public synchronized final double timeSinceExtraInitialized3() {
        return m_startExtraTime3 < 0 ? 0 : Timer.getFPGATimestamp() - m_startExtraTime3;
    }

     /**
     * Returns whether or not the {@link Command#timeSinceInitialized() timeSinceInitialized()}
     * method returns a number which is greater than or equal to the timeout for the command.
     * If there is no timeout, this will always return false.
     * @return whether the time has expired
     */
    protected synchronized boolean isExtraTimedOut1() {
        return m_extraTimeout1 != -1 && timeSinceExtraInitialized1() >= m_extraTimeout1;
    }

    protected synchronized boolean isExtraTimedOut2() {
        return m_extraTimeout2 != -1 && timeSinceExtraInitialized2() >= m_extraTimeout2;
    }

    protected synchronized boolean isExtraTimedOut3() {
        return m_extraTimeout3 != -1 && timeSinceExtraInitialized3() >= m_extraTimeout3;
    }

    protected void resetTimer1() {
        m_extraTimeout1 = -1;
    }

    protected void resetTimer2() {
        m_extraTimeout2 = -1;
    }

    protected void resetTimer3() {
        m_extraTimeout3 = -1;
    }
}