text:
package org.apache.hadoop.hbase.replication.regionserver;

import static org.apache.hadoop.hbase.HConstants.HBASE_MASTER_LOGCLEANER_PLUGINS;
import static org.apache.hadoop.hbase.HConstants.REPLICATION_ENABLE_KEY;
import static org.apache.hadoop.hbase.HConstants.REPLICATION_SCOPE_LOCAL;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.NavigableMap;
import java.util.TreeMap;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hbase.classification.InterfaceAudience;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellScanner;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.Server;
import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.WALEntry;
import org.apache.hadoop.hbase.regionserver.ReplicationSinkService;
import org.apache.hadoop.hbase.regionserver.ReplicationSourceService;
import org.apache.hadoop.hbase.wal.WALKey;
import org.apache.hadoop.hbase.regionserver.wal.WALActionsListener;
import org.apache.hadoop.hbase.regionserver.wal.WALEdit;
import org.apache.hadoop.hbase.replication.ReplicationException;
import org.apache.hadoop.hbase.replication.ReplicationFactory;
import org.apache.hadoop.hbase.replication.ReplicationPeers;
import org.apache.hadoop.hbase.replication.ReplicationQueues;
import org.apache.hadoop.hbase.replication.ReplicationTracker;
import org.apache.hadoop.hbase.replication.master.ReplicationLogCleaner;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.zookeeper.ZKClusterId;
import org.apache.zookeeper.KeeperException;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

/**
 * Gateway to Replication.  Used by {@link org.apache.hadoop.hbase.regionserver.HRegionServer}.
 */
@InterfaceAudience.Private
public class Replication extends WALActionsListener.Base implements
  ReplicationSourceService, ReplicationSinkService {
  private static final Log LOG =
      LogFactory.getLog(Replication.class);
  private boolean replication;
  private ReplicationSourceManager replicationManager;
  private ReplicationQueues replicationQueues;
  private ReplicationPeers replicationPeers;
  private ReplicationTracker replicationTracker;
  private Configuration conf;
  private ReplicationSink replicationSink;
  // Hosting server
  private Server server;
  /** Statistics thread schedule pool */
  private ScheduledExecutorService scheduleThreadPool;
  private int statsThreadPeriod;
  // ReplicationLoad to access replication metrics
  private ReplicationLoad replicationLoad;

  /**
   * Instantiate the replication management (if rep is enabled).
   * @param server Hosting server
   * @param fs handle to the filesystem
   * @param logDir
   * @param oldLogDir directory where logs are archived
   * @throws IOException
   */
  public Replication(final Server server, final FileSystem fs,
      final Path logDir, final Path oldLogDir) throws IOException{
    initialize(server, fs, logDir, oldLogDir);
  }

  /**
   * Empty constructor
   */
  public Replication() {
  }

  public void initialize(final Server server, final FileSystem fs,
      final Path logDir, final Path oldLogDir) throws IOException {
    this.server = server;
    this.conf = this.server.getConfiguration();
    this.replication = isReplication(this.conf);
    this.scheduleThreadPool = Executors.newScheduledThreadPool(1,
      new ThreadFactoryBuilder()
        .setNameFormat(server.getServerName().toShortString() + "Replication Statistics #%d")
        .setDaemon(true)
        .build());
    if (replication) {
      try {
        this.replicationQueues =
            ReplicationFactory.getReplicationQueues(server.getZooKeeper(), this.conf, this.server);
        this.replicationQueues.init(this.server.getServerName().toString());
        this.replicationPeers =
            ReplicationFactory.getReplicationPeers(server.getZooKeeper(), this.conf, this.server);
        this.replicationPeers.init();
        this.replicationTracker =
            ReplicationFactory.getReplicationTracker(server.getZooKeeper(), this.replicationPeers,
              this.conf, this.server, this.server);
      } catch (ReplicationException e) {
        throw new IOException("Failed replication handler create", e);
      }
      UUID clusterId = null;
      try {
        clusterId = ZKClusterId.getUUIDForCluster(this.server.getZooKeeper());
      } catch (KeeperException ke) {
        throw new IOException("Could not read cluster id", ke);
      }
      this.replicationManager =
          new ReplicationSourceManager(replicationQueues, replicationPeers, replicationTracker,
              conf, this.server, fs, logDir, oldLogDir, clusterId);
      this.statsThreadPeriod =
          this.conf.getInt("replication.stats.thread.period.seconds", 5 * 60);
      LOG.debug("ReplicationStatisticsThread " + this.statsThreadPeriod);
      this.replicationLoad = new ReplicationLoad();
    } else {
      this.replicationManager = null;
      this.replicationQueues = null;
      this.replicationPeers = null;
      this.replicationTracker = null;
      this.replicationLoad = null;
    }
  }

   /**
    * @param c Configuration to look at
    * @return True if replication is enabled.
    */
  public static boolean isReplication(final Configuration c) {
    return c.getBoolean(REPLICATION_ENABLE_KEY, HConstants.REPLICATION_ENABLE_DEFAULT);
  }

   /*
    * Returns an object to listen to new wal changes
    **/
  public WALActionsListener getWALActionsListener() {
    return this;
  }
  /**
   * Stops replication service.
   */
  public void stopReplicationService() {
    join();
  }

  /**
   * Join with the replication threads
   */
  public void join() {
    if (this.replication) {
      this.replicationManager.join();
      if (this.replicationSink != null) {
        this.replicationSink.stopReplicationSinkServices();
      }
    }
    scheduleThreadPool.shutdown();
  }

  /**
   * Carry on the list of log entries down to the sink
   * @param entries list of entries to replicate
   * @param cells The data -- the cells -- that entries describes (the entries
   * do not contain the Cells we are replicating; they are passed here on the side in this
   * CellScanner).
   * @throws IOException
   */
  public void replicateLogEntries(List<WALEntry> entries, CellScanner cells) throws IOException {
    if (this.replication) {
      this.replicationSink.replicateEntries(entries, cells);
    }
  }

  /**
   * If replication is enabled and this cluster is a master,
   * it starts
   * @throws IOException
   */
  public void startReplicationService() throws IOException {
    if (this.replication) {
      try {
        this.replicationManager.init();
      } catch (ReplicationException e) {
        throw new IOException(e);
      }
      this.replicationSink = new ReplicationSink(this.conf, this.server);
      this.scheduleThreadPool.scheduleAtFixedRate(
        new ReplicationStatisticsThread(this.replicationSink, this.replicationManager),
        statsThreadPeriod, statsThreadPeriod, TimeUnit.SECONDS);
    }
  }

  /**
   * Get the replication sources manager
   * @return the manager if replication is enabled, else returns false
   */
  public ReplicationSourceManager getReplicationManager() {
    return this.replicationManager;
  }

  @Override
  public void visitLogEntryBeforeWrite(HTableDescriptor htd, WALKey logKey,
                                       WALEdit logEdit) {
    scopeWALEdits(htd, logKey, logEdit);
  }

  /**
   * Utility method used to set the correct scopes on each log key. Doesn't set a scope on keys
   * from compaction WAL edits and if the scope is local.
   * @param htd Descriptor used to find the scope to use
   * @param logKey Key that may get scoped according to its edits
   * @param logEdit Edits used to lookup the scopes
   */
  public static void scopeWALEdits(HTableDescriptor htd, WALKey logKey,
                                   WALEdit logEdit) {
    NavigableMap<byte[], Integer> scopes =
        new TreeMap<byte[], Integer>(Bytes.BYTES_COMPARATOR);
    byte[] family;
    for (Cell cell : logEdit.getCells()) {
      family = cell.getFamily();
      // This is expected and the KV should not be replicated
      if (CellUtil.matchingFamily(cell, WALEdit.METAFAMILY)) continue;
      // Unexpected, has a tendency to happen in unit tests
      assert htd.getFamily(family) != null;

      int scope = htd.getFamily(family).getScope();
      if (scope != REPLICATION_SCOPE_LOCAL &&
          !scopes.containsKey(family)) {
        scopes.put(family, scope);
      }
    }
    if (!scopes.isEmpty()) {
      logKey.setScopes(scopes);
    }
  }

  @Override
  public void preLogRoll(Path oldPath, Path newPath) throws IOException {
    getReplicationManager().preLogRoll(newPath);
  }

  @Override
  public void postLogRoll(Path oldPath, Path newPath) throws IOException {
    getReplicationManager().postLogRoll(newPath);
  }

  /**
   * This method modifies the master's configuration in order to inject
   * replication-related features
   * @param conf
   */
  public static void decorateMasterConfiguration(Configuration conf) {
    if (!isReplication(conf)) {
      return;
    }
    String plugins = conf.get(HBASE_MASTER_LOGCLEANER_PLUGINS);
    String cleanerClass = ReplicationLogCleaner.class.getCanonicalName();
    if (!plugins.contains(cleanerClass)) {
      conf.set(HBASE_MASTER_LOGCLEANER_PLUGINS, plugins + "," + cleanerClass);
    }
  }

  /*
   * Statistics thread. Periodically prints the cache statistics to the log.
   */
  static class ReplicationStatisticsThread extends Thread {

    private final ReplicationSink replicationSink;
    private final ReplicationSourceManager replicationManager;

    public ReplicationStatisticsThread(final ReplicationSink replicationSink,
                            final ReplicationSourceManager replicationManager) {
      super("ReplicationStatisticsThread");
      this.replicationManager = replicationManager;
      this.replicationSink = replicationSink;
    }

    @Override
    public void run() {
      printStats(this.replicationManager.getStats());
      printStats(this.replicationSink.getStats());
    }

    private void printStats(String stats) {
      if (!stats.isEmpty()) {
        LOG.info(stats);
      }
    }
  }

  @Override
  public ReplicationLoad refreshAndGetReplicationLoad() {
    if (this.replicationLoad == null) {
      return null;
    }
    // always build for latest data
    buildReplicationLoad();
    return this.replicationLoad;
  }

  private void buildReplicationLoad() {
    // get source
    List<ReplicationSourceInterface> sources = this.replicationManager.getSources();
    List<MetricsSource> sourceMetricsList = new ArrayList<MetricsSource>();

    for (ReplicationSourceInterface source : sources) {
      if (source instanceof ReplicationSource) {
        sourceMetricsList.add(((ReplicationSource) source).getSourceMetrics());
      }
    }
    // get sink
    MetricsSink sinkMetrics = this.replicationSink.getSinkMetrics();
    this.replicationLoad.buildReplicationLoad(sourceMetricsList, sinkMetrics);
  }
}


text:
var getTypeStr = require ('./GetTypeStr');
var getBSONType = require ('./GetBSONType');
var matchLeaves = require ('./MatchQuery').matchLeaves;
var Sorting = require ('./Sorting');
var leafSorter = Sorting.getLeafsort (1);
var Set = require ('./Set');
var FauxmongoError = require ('./FauxmongoError');

function evaluate (expression, context) {
    var type = getTypeStr (expression);
    if (type == 'string') {
        if (expression[0] == '$')
            if (expression[1] == '$') {
                // variable
                var varname = expression.slice (2);
                if (Object.hasOwnProperty.call (context, varname))
                    return context[varname];
                throw new FauxmongoError ('INVALID', 'variable '+expression+' not found');
            } else {
                // path
                var pointer = context.CURRENT;
                var frags = expression.slice(1).split ('.');
                for (var i in frags) {
                    var frag = frags[i];
                    if (!Object.hasOwnProperty.call (pointer, frag))
                        return undefined;
                    pointer = pointer[frag];
                }
                return pointer;
            }
        return expression;
    }

    if (type == 'object') {
        var key = Object.keys (expression)[0];
        if (key[0] != '$') {
            var newDoc = {};
            for (var key in expression)
                newDoc[key] = evaluate (expression[key], context);
            return newDoc;
        }

        if (key == '$literal')
            return expression.$literal;

        if (key == '$let') {
            var backup = {};
            var spec = expression.$let;

            // prime context
            for (var tempVar in spec.vars) {
                if (Object.hasOwnProperty.call (context, tempVar))
                    backup[tempVar] = context[tempVar];
                context[tempVar] = evaluate (spec.vars[tempVar], context);
            }

            // evaluate with primed context
            var retval = evaluate (spec.in, context);

            // restore context
            for (var tempVar in spec.vars) {
                if (Object.hasOwnProperty.call (backup, tempVar))
                    context[tempVar] = backup[tempVar];
                else
                    delete context[tempVar];
            }

            return retval;
        }

        if (key == '$map') {
            var spec = expression.$map;
            var backup = Object.hasOwnProperty.call (context, spec.as) ?
                context[spec.as]
              : undefined
              ;

            var docs = evaluate (spec.input, context);
            if (!(docs instanceof Array))
                throw new Error ('$map requires an Array input');

            var results = [];
            for (var i in docs) {
                context[spec.as] = docs[i];
                results.push (evaluate (spec.in, context));
            }

            if (backup !== undefined)
                context[spec.as] = backup;
            else
                delete context[spec.as];
            return results;
        }

        if (!Object.hasOwnProperty.call (AggregationOperators, key))
            throw new Error ('unknown aggregation operator '+key);
        return AggregationOperators[key] (expression[key], context);
    }

    return expression;
}

var AggregationOperators = {
    '$and':             function (expression, context) {
        for (var i in expression)
            if (!evaluate (expression[i], context))
                return false;
        return true;
    },
    '$or':              function (expression, context) {
        for (var i in expression)
            if (!evaluate (expression[i], context))
                return true;
        return false;
    },
    '$not':             function (expression, context) {
        return ! Boolean (evaluate (expression[0], context));
    },
    '$allElementsTrue': function (expression, context) {
        expression = expression[0];
        var set = evaluate (expression, context);
        if (!(set instanceof Array))
            throw new Error ('$allElementsTrue requires an Array');
        for (var i in set)
            if (!set[i])
                return false;
        return true;
    },
    '$anyElementTrue':  function (expression, context) {
        expression = expression[0];
        var set = evaluate (expression, context);
        if (!(set instanceof Array))
            throw new Error ('$anyElementTrue requires an Array');
        for (var i in set)
            if (set[i])
                return true;
        return false;
    },
    '$setDifference':   function (expression, context) {
        var able = new Set (evaluate (expression[0], context));
        var baker = new Set (evaluate (expression[1], context));
        able.difference (baker);
        return able.export();
    },
    '$setEquals':       function (expression, context) {
        var sets = [];
        for (var i in expression) {
            var val = evaluate (expression[i], context);
            if (!(val instanceof Array))
                throw new Error ('$setEquals only accepts Arrays');
            sets.push (new Set (val));
        }

        if (sets.length < 2)
            throw new Error ('$setEquals requires at least 2 sets');

        var first = sets[1];
        for (var i=1,j=sets.length; i<j; i++)
            if (!first.equals (sets[i]))
                return false;

        return true;
    },
    '$setIntersection': function (expression, context) {
        var sets = [];
        for (var i in expression) {
            var val = evaluate (expression[i], context);
            if (!(val instanceof Array))
                throw new Error ('$setIntersection only accepts Arrays');
            sets.push (new Set (val));
        }

        if (sets.length < 2)
            throw new Error ('$setIntersection requires at least 2 sets');

        var walker = sets[0];
        for (var i=1,j=sets.length; i<j; i++)
            walker = walker.intersect (sets[i]);

        return walker.export();
    },
    '$setIsSubset':     function (expression, context) {
        var able = evaluate (expression[0], context);
        var baker = evaluate (expression[1], context);
        if (!(able instanceof Array) || !(baker instanceof Array))
            throw new FauxmongoError ('FORMAT', '$setIsSubset only accepts Arrays');
        able = new Set (able);
        baker = new Set (baker);
        return baker.contains (able);
    },
    '$setUnion':        function (expression, context) {
        var sets = [];
        for (var i in expression)
            sets.push (new Set (evaluate (expression[i], context)));

        if (sets.length < 2)
            throw new Error ('$setIntersection requires at least 2 sets');

        var first = sets[0];
        for (var i=1,j=sets.length; i<j; i++)
            first.union (sets[i]);

        return first.export();
    },
    '$cmp':             function (expression, context) {
        var able = evaluate (expression[0], context);
        var baker = evaluate (expression[1], context);
        return leafSorter (able, baker);
    },
    '$eq':              function (expression, context) {
        var able = evaluate (expression[0], context);
        var baker = evaluate (expression[1], context);
        return matchLeaves (able, baker);
    },
    '$gt':              function (expression, context) {
        var able = evaluate (expression[0], context);
        var baker = evaluate (expression[1], context);
        return leafSorter (able, baker) > 0 ? true : false;
    },
    '$gte':             function (expression, context) {
        var able = evaluate (expression[0], context);
        var baker = evaluate (expression[1], context);
        return leafSorter (able, baker) >= 0 ? true : false;
    },
    '$lt':              function (expression, context) {
        var able = evaluate (expression[0], context);
        var baker = evaluate (expression[1], context);
        return leafSorter (able, baker) < 0 ? true : false;
    },
    '$lte':             function (expression, context) {
        var able = evaluate (expression[0], context);
        var baker = evaluate (expression[1], context);
        return leafSorter (able, baker) <= 0 ? true : false;
    },
    '$ne':              function (expression, context) {
        var able = evaluate (expression[0], context);
        var baker = evaluate (expression[1], context);
        return !matchLeaves (able, baker);
    },
    '$add':             function (expression, context) {
        var vals = [];
        var datestamp = false;
        for (var i in expression) {
            var val = evaluate (expression[i], context);
            var type = typeof val;
            if (type == 'date')
                if (datestamp)
                    throw new Error ('$add accepts at most 1 Date');
                else datestamp = val;
            else if (type != 'number')
                throw new Error ('$add only accepts Numbers and Dates');
            else
                vals.push (val);
        }

        if (datestamp) {
            var tms = datestamp.getTime();
            for (var i in vals)
                tms += vals[i];
            datestamp.setTime (tms);
            return datestamp;
        }

        var total = 0;
        for (var i in vals)
            total += vals[i];
        return total;
    },
    '$divide':          function (expression, context) {
        var able = evaluate (expression[0], context);
        var baker = evaluate (expression[1], context);
        if (typeof able != 'number' || typeof baker != 'number')
            throw new Error ('$divide only accepts Numbers');

        return able / baker;
    },
    '$mod':             function (expression, context) {
        var able = evaluate (expression[0], context);
        var baker = evaluate (expression[1], context);
        if (typeof able != 'number' || typeof baker != 'number')
            throw new Error ('$divide only accepts Numbers');

        return able % baker;
    },
    '$multiply':        function (expression, context) {
        var vals = [];
        for (var i in expression) {
            var val = evaluate (expression[i], context);
            if (typeof val != 'number')
                throw new Error ('$multiply only accepts Numbers');
            vals.push (val);
        }

        var accumulator = 1;
        for (var i in vals)
            accumulator *= vals[i];
        return accumulator;
    },
    '$subtract':        function (expression, context) {
        var able = evaluate (expression[0], context);
        var baker = evaluate (expression[1], context);
        if (typeof able != 'number' || typeof baker != 'number')
            throw new Error ('$divide only accepts Numbers');

        return able - baker;
    },
    '$concat':          function (expression, context) {
        var vals = [];
        for (var i in expression) {
            var val = evaluate (expression[i], context);
            if (typeof val != 'string')
                if (val === null || val === undefined)
                    return null;
                else
                    throw new Error ('$multiply only accepts Numbers');
            vals.push (val);
        }

        if (vals.length < 2)
            throw new Error ('$concat requires at least 2 arguments');

        return String.prototype.concat.apply ('', vals);
    },
    '$strcasecmp':      function (expression, context) {
        var able = evaluate (expression[0], context);
        var baker = evaluate (expression[1], context);
        if (typeof able != 'string' || typeof baker != 'string')
            throw new Error ('$strcasecmp only accepts Strings');

        able = able.toUpperCase();
        baker = baker.toUpperCase();
        if (able == baker)
            return 0;
        if (able < baker)
            return -1;
        return 1;
    },
    '$substr':          function (expression, context) {
        var str = evaluate (expression[0], context);
        var start = evaluate (expression[1], context);
        var length = evaluate (expression[2], context);

        if (typeof str != 'string' || typeof start != 'number' || typeof length != 'number')
            throw new Error ('invalid arguments to $substr');

        if (start < 0)
            return '';
        if (length < 0)
            return str.slice (start);
        return str.slice (start, start + length);
    },
    '$toLower':         function (expression, context) {
        var str = evaluate (expression, context);
        if (str === null)
            return '';
        if (typeof str != 'string')
            throw new Error ('$toLower only accepts Strings');
        return str.toLowerCase();
    },
    '$toUpper':         function (expression, context) {
        var str = evaluate (expression, context);
        if (str === null)
            return '';
        if (typeof str != 'string')
            throw new Error ('$toUpper only accepts Strings');
        return str.toUpperCase();
    },
    '$meta':            function (expression, context) {
        throw new Error ('$meta not supported');
    },
    '$size':            function (expression, context) {
        var arr = evaluate (expression, context);
        if (!(arr instanceof Array))
            throw new Error ('$size only accepts Arrays');
        return arr.length;
    },
    '$dayOfMonth':      function (expression, context) {
        expression = evaluate (expression, context);
        if (!(expression instanceof Date))
            throw new Error ('$dayOfMonth only accepts Dates');
        return expression.getDate();
    },
    '$dayOfWeek':       function (expression, context) {
        expression = evaluate (expression, context);
        if (!(expression instanceof Date))
            throw new Error ('$dayOfWeek only accepts Dates');
        return (expression.getDay() % 7) + 1;
    },
    '$dayOfYear':       function (expression, context) {
        expression = evaluate (expression, context);
        if (!(expression instanceof Date))
            throw new Error ('$dayOfYear only accepts Dates');

        // all the oldest javascript apis are puketastic
        var start = new Date(expression.getFullYear(), 0, 0);
        var diff = expression - start;
        return Math.floor (diff / ( 1000 * 60 * 60 * 24 ));
    },
    '$hour':            function (expression, context) {
        expression = evaluate (expression, context);
        if (!(expression instanceof Date))
            throw new Error ('$hour only accepts Dates');
        return expression.getHours();
    },
    '$millisecond':     function (expression, context) {
        expression = evaluate (expression, context);
        if (!(expression instanceof Date))
            throw new Error ('$millisecond only accepts Dates');
        return expression.getMilliseconds();
    },
    '$minute':          function (expression, context) {
        expression = evaluate (expression, context);
        if (!(expression instanceof Date))
            throw new Error ('$minute only accepts Dates');
        return expression.getMinutes();
    },
    '$month':           function (expression, context) {
        expression = evaluate (expression, context);
        if (!(expression instanceof Date))
            throw new Error ('$month only accepts Dates');
        return expression.getMonth() + 1;
    },
    '$second':          function (expression, context) {
        expression = evaluate (expression, context);
        if (!(expression instanceof Date))
            throw new Error ('$second only accepts Dates');
        return expression.getSeconds();
    },
    '$week':            function (expression, context) {
        expression = evaluate (expression, context);
        if (!(expression instanceof Date))
            throw new Error ('$week only accepts Dates');

        // create a target date set to Sunday of the same week as the expression
        var target = new Date (expression.getTime());
        var days = (expression.getDay() + 6) % 7;
        target.setDate (target.getDate() - days - 1);
        // store the time of the week's Sunday
        var firstSunday = target.getTime();

        // switch to January 1st and advance to Sunday
        target.setMonth (0, 1);
        days = target.getDay();
        if (days != 7)
            target.setMonth (0, 7 - days);

        return 1 + Math.ceil ((target.getTime() - firstSunday) / (1000 * 60 * 60 * 24 * 7));
    },
    '$year':            function (expression, context) {
        expression = evaluate (expression, context);
        if (!(expression instanceof Date))
            throw new Error ('$year only accepts Dates');
        return expression.getFullYear();
    },
    '$cond':            function (expression, context) {
        var ifx, thenx, elsex;
        if (expression instanceof Array) {
            ifx = expression[0];
            thenx = expression[1];
            elsex = expression[2];
        } else {
            if (typeof expression != 'object')
                throw new Error ('$cond requires either an Object or Array of arguments');
            ifx = expression.if;
            thenx = expression.then;
            elsex = expression.else;
        }

        if (evaluate (ifx, context) === true)
            return evaluate (thenx, context);
        return evaluate (elsex, context);
    },
    '$ifNull':          function (expression, context) {
        var val = evaluate (expression[0], context);
        if (val === null)
            return evaluate (expression[1], context);
        return val;
    }
};

var AggregationAccumulators = {
    '$addToSet':    function (expression, docs) {
        var set = new Set();
        for (var i in docs)
            set.add (evaluate (expression, { CURRENT:docs[i] }));
        return set.export();
    },
    '$avg':         function (expression, docs) {
        var count = 0;
        var total = 0;
        for (var i in docs) {
            var val = evaluate (expression, { CURRENT:docs[i] });
            if (typeof val != 'number')
                throw new FauxmongoError ('FORMAT', '$sum only accepts numbers');
            total += val;
            count++;
        }
        return total / count;
    },
    '$first':       function (expression, docs) {
        return evaluate (expression, { CURRENT:docs[0] });
    },
    '$last':        function (expression, docs) {
        return evaluate (expression, { CURRENT:docs[docs.length-1] });
    },
    '$max':         function (expression, docs) {
        var highest = evaluate (expression, { CURRENT:docs[0] });
        for (var i=1,j=docs.length; i<j; i++) {
            var val = evaluate (expression, { CURRENT:docs[i] });
            if (leafSorter (val, highest) > 0)
                highest = val;
        }
        return highest;
    },
    '$min':         function (expression, docs) {
        var lowest = evaluate (expression, { CURRENT:docs[0] });
        for (var i=1,j=docs.length; i<j; i++) {
            var val = evaluate (expression, { CURRENT:docs[i] });
            if (leafSorter (val, lowest) < 0)
                lowest = val;
        }
        return lowest;
    },
    '$push':        function (expression, docs) {
        var output = [];
        for (var i in docs)
            output.push (evaluate (expression, { CURRENT:docs[i] }));
        return output;
    },
    '$sum':         function (expression, docs) {
        var total = 0;
        for (var i in docs) {
            var val = evaluate (expression, { CURRENT:docs[i] });
            if (typeof val != 'number')
                throw new FauxmongoError ('FORMAT', '$sum only accepts numbers');
            total += val;
        }
        return total;
    }
};

module.exports.evaluate = evaluate;
module.exports.accumulators = AggregationAccumulators;

redpajama_set_name: RedPajamaGithub


text:
package org.jetbrains.plugins.ipnb.psi;

import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.impl.PsiManagerEx;
import com.intellij.psi.impl.file.impl.FileManager;
import com.intellij.psi.impl.source.tree.FileElement;
import com.intellij.testFramework.LightVirtualFile;
import com.jetbrains.python.psi.impl.PyFileImpl;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.ipnb.editor.panels.IpnbFilePanel;
import org.jetbrains.plugins.ipnb.editor.panels.code.IpnbCodeSourcePanel;

public class IpnbPyFragment extends PyFileImpl {
  private boolean myPhysical;
  private final IpnbFilePanel myFilePanel;
  private final IpnbCodeSourcePanel myCodeSourcePanel;
  private FileViewProvider myViewProvider;

  public IpnbPyFragment(Project project, CharSequence text, boolean isPhysical, IpnbCodeSourcePanel codeSourcePanel) {
    super(((PsiManagerEx)PsiManager.getInstance(project)).getFileManager().createFileViewProvider(
            new LightVirtualFile("code.py", IpnbPyLanguageDialect.getInstance(), text), isPhysical)
    );
    myPhysical = isPhysical;
    myCodeSourcePanel = codeSourcePanel;
    myFilePanel = codeSourcePanel.getIpnbCodePanel().getFileEditor().getIpnbFilePanel();
    ((SingleRootFileViewProvider)getViewProvider()).forceCachedPsi(this);
  }

  public IpnbCodeSourcePanel getCodeSourcePanel() {
    return myCodeSourcePanel;
  }

  protected IpnbPyFragment clone() {
    final IpnbPyFragment clone = (IpnbPyFragment)cloneImpl((FileElement)calcTreeElement().clone());
    clone.myPhysical = false;
    clone.myOriginalFile = this;
    FileManager fileManager = ((PsiManagerEx)getManager()).getFileManager();
    SingleRootFileViewProvider cloneViewProvider = (SingleRootFileViewProvider)fileManager.createFileViewProvider(new LightVirtualFile(getName(), getLanguage(), getText()), false);
    cloneViewProvider.forceCachedPsi(clone);
    clone.myViewProvider = cloneViewProvider;
    return clone;
  }

  @NotNull
  public FileViewProvider getViewProvider() {
    if(myViewProvider != null) return myViewProvider;
    return super.getViewProvider();
  }

  public boolean isPhysical() {
    return myPhysical;
  }

  public IpnbFilePanel getFilePanel() {
    return myFilePanel;
  }

  @Nullable
  @Override
  public PsiDirectory getContainingDirectory() {
    final VirtualFile file = myFilePanel.getVirtualFile();
    final VirtualFile parentFile = file.getParent();
    if (parentFile == null) {
      return super.getContainingDirectory();
    }
    if (!parentFile.isValid()) {
      return super.getContainingDirectory();
    }
    return getManager().findDirectory(parentFile);
  }

  @Override
  public PsiElement getNextSibling() {
    return null;
  }

  @Override
  public PsiElement getPrevSibling() {
    return null;
  }
}


text:
<?php

namespace Vich\UploaderBundle\Naming;

use Vich\UploaderBundle\Mapping\PropertyMapping;

/**
 * NamerInterface.
 *
 * @author Dustin Dobervich <ddobervich@gmail.com>
 */
interface NamerInterface
{
    /**
     * Creates a name for the file being uploaded.
     *
     * @param object          $object  The object the upload is attached to.
     * @param PropertyMapping $mapping The mapping to use to manipulate the given object.
     *
     * @return string The file name.
     */
    public function name($object, PropertyMapping $mapping);
}


text:
<?php

class Payment_Adapter_Onebip extends Payment_AdapterAbstract
{
    public function init()
    {

    }

    public static function getConfig()
    {
        return array(
            'supports_one_time_payments'   =>  true,
            'supports_subscriptions'       =>  false,
            'description'     =>  'Onebip is a system that allows mobile phone subscribers to transfer pre-paid or post-paid credit from their SIM card to another use.',
            'form'  => array(
                'username' => array('email', array(
                            'label' => 'The email address associated to your Onebip account.',
                    ),
                 ),
                'api_key' => array('password', array(
                            'label' => 'OneBip API key. Stored in OneBip account settings. Used to validate payment notification',
                    ),
                 ),
                'logo_url' => array('text', array(
                            'label' => 'URL to your company logo. The URL of the 360x45-pixel image displayed as your logo in the upper left corner of the Onebip payment pages',
                    ),
                 ),
            ),
        );
    }

    /**
     * Return payment gateway type
     * @return string
     */
    public function getType()
    {
        return Payment_AdapterAbstract::TYPE_FORM;
    }

    /**
     * Return payment gateway call url
     * @return string
     */
    public function getServiceURL()
    {
		return 'https://www.onebip.com/otms/';
    }

    /**
     * Init call to webservice or return form params
     *
     * @see http://www.onebip.com/website/docs/Onebip_API.pdf
     * @param Payment_Invoice $invoice
     */
    public function singlePayment(Payment_Invoice $invoice)
    {
        $data = array();
        $data['username'] = $this->getParam('username');
        $data['description'] = $invoice->getTitle();
        $data['price'] = $invoice->getTotalWithTax() * 100;
        $data['currency'] = $invoice->getCurrency();
        $data['command'] = 'standard_pay';

        $data['item_code'] = $invoice->getId();
        $data['return_url'] = $this->getParam('return_url');
        $data['notify_url'] = $this->getParam('notify_url');
        $data['cancel_url'] = $this->getParam('cancel_url');

        $c = $invoice->getBuyer();
        $data['customer_email']     = $c->getEmail();
        $data['customer_firstname'] = $c->getFirstName();
        $data['customer_lastname']  = $c->getLastName();

        if($c->getPhone()) {
            $data['customer_cell'] = $c->getPhone();
        }

        if($c->getCountry()) {
            $data['customer_country'] = $c->getCountry();
        }

        if($this->testMode) {
            $data['debug'] = 1;
            $data['debug_url'] = $this->getParam('notify_url');
        }

        $data['logo_url'] = $this->getParam('logo_url');

        return $data;
    }

    /**
     * Perform recurent payment
     * @param Payment_Invoice $invoice
     */
    public function recurrentPayment(Payment_Invoice $invoice)
    {
        throw new Payment_Exception('Not implemented yet');
    }

    public function isIpnValid($data, Payment_Invoice $invoice)
    {
        $ipn    = $data['get'];
        $server = $data['server'];

        if (isset($ipn['hash'])) {
            $my_api_key = $this->getParam('api_key');
            $basename = basename($server['REQUEST_URI']);
            $pos = strrpos($basename, "&hash");
            $basename_without_hash = substr($basename, 0, $pos);
            $my_hash = md5($my_api_key . $basename_without_hash);
            if ($my_hash != $ipn['hash']) {
                $this->setOutput('ERROR: Invalid hash code');
                return false;
            }
        }

        $this->setOutput('OK');
        return true;
    }

    public function getTransaction($data, Payment_Invoice $invoice)
    {
        $ipn = $data['get'];

        // Onebip parameters:
        $payment_id         = $ipn['payment_id'];
        $country            = $ipn['country'];
        $currency           = $ipn['currency'];
        $price              = $ipn['price'];
        $tax                = $ipn['tax'];
        $commission         = $ipn['commission'];
        $amount             = $ipn['amount'];
        $original_price     = $ipn['original_price'];
        $original_currency  = $ipn['original_currency'];

        $tx = new Payment_Transaction();
        $tx->setId($payment_id);
        $tx->setAmount($original_price / 100);
        $tx->setCurrency($original_currency);
        $tx->setStatus(Payment_Transaction::STATUS_COMPLETE);
        $tx->setType(Payment_Transaction::TXTYPE_PAYMENT);
        return $tx;
    }
}


text:
(function() {
  'use strict';

  angular
    .module('tweetstockr')
    .factory('networkService', networkService);

  function networkService ($http) {
    return {
      // Post data with authentication
      postAuth: function (postUrl, postData, onSuccessCallback, onErrorCallback) {
        $http({
          method: 'POST',
          url: postUrl,
          headers: {'Content-Type': 'application/x-www-form-urlencoded'},
          transformRequest: function(obj) {
            var str = [];
            for(var p in obj)
            str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]));
            return str.join('&');
          },
          data: postData,
          withCredentials: true
        }).then(function completeCallback(response) {
            if (response.data.redirect_to) {
              window.location = response.data.redirect_to;
            }

            if (response.data.success) {
              onSuccessCallback(response.data);
            } else {
              onErrorCallback(response.data || {'message':'Sorry! An error ocurred.'});
            }
          }, function postError(response) {
            onErrorCallback({'message':'Error: Could not connect to the server.'});
            console.log('Authenticated POST error: ' + response);
          });
        },

        // Get data with authentication
        getAuth: function (getUrl, onSuccessCallback, onErrorCallback) {
          $http({
            method: 'GET',
            url: getUrl,
            withCredentials: true
          })
          .then(function completeCallback(response) {
            if (response.data.redirect_to) {
              window.location = response.data.redirect_to;
            }

            onSuccessCallback(response.data);
          }, function getError(response) {
            onErrorCallback({'message':'Error: Could not connect to the server.'});
            console.log('Authenticated GET error: ' + response);
          });
        },

        // Get data without authentication
        get: function (getUrl, onSuccessCallback, onErrorCallback) {
          $http({
            method: 'GET',
            url: getUrl,
          })
          .then(function completeCallback(response) {
            if (response.data.redirect_to) {
              window.location = response.data.redirect_to;
            }

            onSuccessCallback(response.data);
          }, function getError(response) {
            onErrorCallback({'message':'Error: Could not connect to the server.'});
            console.log('GET error: ' + response);
          });
        },

      };
    }
})();


text:
package com.epam.catgenome.util.azure;

import com.azure.identity.ClientSecretCredentialBuilder;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.storage.blob.BlobClient;
import com.azure.storage.blob.BlobContainerClient;
import com.azure.storage.blob.BlobServiceClient;
import com.azure.storage.blob.BlobServiceClientBuilder;
import com.azure.storage.blob.models.BlobRange;
import com.azure.storage.blob.sas.BlobSasPermission;
import com.azure.storage.blob.sas.BlobServiceSasSignatureValues;
import com.azure.storage.common.StorageSharedKeyCredential;
import com.epam.catgenome.entity.BiologicalDataItemDownloadUrl;
import com.epam.catgenome.entity.BiologicalDataItemResourceType;
import lombok.*;
import org.apache.commons.lang3.StringUtils;
import javax.annotation.PostConstruct;
import java.io.InputStream;
import java.net.URI;
import java.time.Duration;
import java.time.OffsetDateTime;
import java.util.Date;

abstract class AbstractCredentialConfigurer implements AzureCredentialConfiguration {
    abstract BlobServiceClientBuilder configureCredential(BlobServiceClientBuilder builder);
}

@Getter
@Builder
class AccessKeyCredentialConfigurer extends AbstractCredentialConfigurer implements AzureCredentialConfiguration {

    private final String storageAccount;
    private final String storageKey;

    @Override
    BlobServiceClientBuilder configureCredential(BlobServiceClientBuilder builder) {
        return builder.credential(new StorageSharedKeyCredential(storageAccount, storageKey));
    }
}

@Getter
@Builder
class ServicePrincipalCredentialConfigurer extends AbstractCredentialConfigurer
        implements AzureCredentialConfiguration {

    private final String storageAccount;
    private final String clientId;
    private final String clientSecret;
    private final String tenantId;

    @Override
    BlobServiceClientBuilder configureCredential(BlobServiceClientBuilder builder) {
        return builder.credential(new ClientSecretCredentialBuilder()
                .clientId(clientId)
                .clientSecret(clientSecret)
                .tenantId(tenantId)
                .build());
    }
}

@Getter
@Builder
class DefaultCredentialConfigurer extends AbstractCredentialConfigurer implements AzureCredentialConfiguration {

    private final String storageAccount;
    private final String managedIdentityId;
    private final String tenantId;

    @Override
    BlobServiceClientBuilder configureCredential(BlobServiceClientBuilder builder) {

        DefaultAzureCredentialBuilder cb = new DefaultAzureCredentialBuilder();

        if(StringUtils.isNotEmpty(managedIdentityId)) {
            cb = cb.managedIdentityClientId(managedIdentityId);
        }

        if(StringUtils.isNotEmpty(tenantId)) {
            cb = cb.tenantId(tenantId);
        }

        return builder.credential(cb.build());
    }
}

public class AzureBlobClient {

    private static final String BLOB_URL_FORMAT = "https://%s.blob.core.windows.net";
    private static final String AZ_SCHEME = "az://";
    private static final String AZ_BLOB_DELIMITER = "/";
    private static final Long URL_EXPIRATION = 24 * 60 * 60 * 1000L;

    private AzureCredentialConfiguration credentialConfig;
    private BlobServiceClient blobService;

    private static AzureBlobClient instance;

    public AzureBlobClient() {
        //just to make test context work
    }

    public AzureBlobClient(@NonNull AbstractCredentialConfigurer credentialConfigurer) {
        this.credentialConfig = credentialConfigurer;
        this.blobService = credentialConfigurer.configureCredential(new BlobServiceClientBuilder()
                        .endpoint(String.format(BLOB_URL_FORMAT, credentialConfigurer.getStorageAccount())))
                .buildClient();
    }

    @PostConstruct
    public void init() {
        instance = this;
    }

    public InputStream loadFromTo(final String uri, final long offset, final long end) {
        final BlobClient client = getBlobURL(uri);
        final BlobRange blobRange = new BlobRange(offset, end - offset + 1);
        return client.openInputStream(blobRange, null);
    }

    public boolean blobExists(String uri) {
        return getBlobURL(uri).exists();
    }

    public long getFileSize(String uri){
        return getBlobURL(uri).getProperties().getBlobSize();
    }

    private BlobClient getBlobURL(final String uri) {
        final AzureBlobItem azureBlob = validateUri(uri);
        BlobContainerClient blobContainerClient = blobService.getBlobContainerClient(azureBlob.container);
        return blobContainerClient.getBlobClient(azureBlob.blobPath);
    }

    private AzureBlobItem validateUri(final String uri) {
        if (StringUtils.isBlank(uri)) {
            throw new IllegalArgumentException("Azure blob path is not specified.");
        }
        if (!uri.startsWith(AZ_SCHEME)) {
            throw new IllegalArgumentException(
                    String.format("Azure blob path must start with %s scheme. Actual value: %s.", AZ_SCHEME, uri));
        }
        return parseUri(uri);
    }

    @SneakyThrows
    private AzureBlobItem parseUri(final String azureBlobUri) {
        final URI uri = new URI(azureBlobUri);
        final String container = uri.getHost();
        final String blobPath = uri.getPath().substring(1);
        if (StringUtils.isBlank(blobPath) || blobPath.endsWith(AZ_BLOB_DELIMITER)) {
            throw new IllegalArgumentException("Azure blob math must point to a file. Actual path: " + blobPath);
        }
        return new AzureBlobItem(container, blobPath);
    }

    public InputStream loadFrom(String obj, long offset) {
        long contentLength = getFileSize(obj);
        return loadFromTo(obj, offset, contentLength);
    }

    /**
     * A method that creates an InputStream on a specific file URI.
     *
     * @param obj target file URI
     * @return an InputStream object on the file URI.
     */
    @SuppressWarnings("WeakerAccess")
    public InputStream loadFully(String obj) {
        return loadFrom(obj, 0);
    }

    public static boolean isAzSource(String inputUrl) {
        return inputUrl.startsWith(AZ_SCHEME);
    }

    public static AzureBlobClient getClient() {
        return instance;
    }

    public BiologicalDataItemDownloadUrl generatePresignedUrl(final String path) {
        final Date expires = new Date((new Date()).getTime() + URL_EXPIRATION);
        final String downloadUrl = buildBlobDownloadUrl(path);
        return BiologicalDataItemDownloadUrl.builder()
                .url(downloadUrl)
                .expires(expires)
                .type(BiologicalDataItemResourceType.AZ)
                .size(getFileSize(path))
                .build();
    }

    @Data
    private static final class AzureBlobItem {
        private final String container;
        private final String blobPath;
    }

    private String buildBlobDownloadUrl(final String blobPath) {
        final AzureBlobItem azureBlobItem = parseUri(blobPath);
        final BlobSasPermission permissions = new BlobSasPermission()
                .setReadPermission(true)
                .setAddPermission(false)
                .setWritePermission(false);
        final BlobServiceSasSignatureValues blobServiceSasSignatureValues =
                new BlobServiceSasSignatureValues(OffsetDateTime.now().plus(Duration.ofDays(1)), permissions);
        final String sasToken = getBlobURL(blobPath).generateSas(blobServiceSasSignatureValues);
        return String.format(BLOB_URL_FORMAT + "/%s/%s?%s", credentialConfig.getStorageAccount(),
                azureBlobItem.getContainer(), azureBlobItem.getBlobPath(), sasToken);
    }
}


text:
package com.microfocus.application.automation.tools.octane.actions.cucumber;

import com.microfocus.application.automation.tools.octane.Messages;
import hudson.FilePath;
import hudson.Util;
import hudson.model.TaskListener;
import hudson.remoting.VirtualChannel;
import jenkins.MasterToSlaveFileCallable;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.types.FileSet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;

/**
 * Helper Service for Gherkin results
 */
public class CucumberResultsService {

    public static final String GHERKIN_NGA_RESULTS_XML = "OctaneGherkinResults.xml";
    public static final String GHERKIN_NGA_RESULTS = "OctaneGherkinResults";
    public static final String DEFAULT_GLOB = "**/*" + GHERKIN_NGA_RESULTS_XML;

    private static TaskListener listener;

    public static String getGherkinResultFileName(int index) {
        return GHERKIN_NGA_RESULTS + index + ".xml";
    }

    public static String[] getCucumberResultFiles(final FilePath workspace, String glob) throws IOException, InterruptedException {
        if (glob == null || glob.isEmpty()) {
            glob = DEFAULT_GLOB;
            log(Messages.CucumberResultsActionEmptyConfiguration(), glob);
        }

        log("Looking for files that match the pattern %s in root directory %s", glob, workspace.getName());
        return workspace.act(new ResultFilesCallable(glob));
    }

    public static void copyResultFile(File resultFile, File destinationFolder, final FilePath workspace) throws IOException, InterruptedException {
        File existingReportFile;
        int existingResultIndex = -1;

        log("Copying %s to %s", resultFile.getPath(), destinationFolder.getPath());

        do {
            existingReportFile = new File(destinationFolder, getGherkinResultFileName(++existingResultIndex));
        } while (existingReportFile.exists());
        log("New file name on destination will be %s", existingReportFile.getPath());

        byte[] content = workspace.act(new FileContentCallable(resultFile));
        log("Got result file content");

        validateContent(content);

        File target = existingReportFile;
        try (FileOutputStream os = new FileOutputStream(target)) {
            os.write(content);
        }
        log("Result file copied to %s", target.getPath());
    }

    private static void validateContent(byte[] content) {
        String contentStr = new String(content, 0, Math.min(content.length , 2000));
        //Heuristic validation. we don't check the whole file structure here - we should be quick.
        if(!contentStr.contains("<features")) {
            throw new IllegalArgumentException("The file is not Octane Gherkin results file");
        }
    }

    public static void log(final String message, final String... stringFormatArgs) {
        if(listener != null) {
            listener.getLogger().println(String.format("%s: %s",
                Messages.CucumberReporterName(), String.format(message, stringFormatArgs)));
        }
    }

    public static void setListener(TaskListener l) {
        listener = l;
    }

    private static final class ResultFilesCallable extends MasterToSlaveFileCallable<String[]> {
        private final String glob;

        private ResultFilesCallable(String glob) {
            this.glob = glob;
        }

        @Override
        public String[] invoke(File rootDir, VirtualChannel channel) throws IOException {
            FileSet fs = Util.createFileSet(rootDir, glob);
            DirectoryScanner ds = fs.getDirectoryScanner();
            return ds.getIncludedFiles();
        }
    }

    private static final class FileContentCallable extends MasterToSlaveFileCallable<byte[]> {
        private final File file;

        private FileContentCallable(File file) {
            this.file = file;
        }

        @Override
        public byte[] invoke(File rootDir, VirtualChannel channel) throws IOException {
            return Files.readAllBytes(file.toPath());
        }
    }

}


text:
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Xunit;

using LimeBean.Interfaces;

namespace LimeBean.Tests {

    static class SharedChecks {
        public static readonly Guid SAMPLE_GUID = Guid.NewGuid();
        public static readonly DateTime SAMPLE_DATETIME = new DateTime(1984, 6, 14, 11, 22, 33);
        public static readonly DateTimeOffset SAMPLE_DATETIME_OFFSET = new DateTimeOffset(SAMPLE_DATETIME, TimeSpan.FromHours(6));
        public static readonly byte[] SAMPLE_BLOB = new byte[] { 1, 2, 3 };

        public static void CheckSchemaReadingKeepsCache(IDatabaseAccess db, DatabaseStorage storage) {
            db.Exec("create table foo(bar int)");
            db.Exec("insert into foo(bar) values(1)");

            var queryCount = 0;
            db.QueryExecuting += cmd => queryCount++;

            db.Cell<int>(true, "Select * from foo");
            storage.GetSchema();

            var savedQueryCount = queryCount;
            db.Cell<int>(true, "Select * from foo");

            Assert.Equal(savedQueryCount, queryCount);
        }

        public static void CheckRoundtripOfExtremalValues(RoundtripChecker checker, bool checkDecimal = false, bool checkDateTime = false, bool checkDateTimeOffset = false) {
            checker.Check(Int64.MinValue, Int64.MinValue);
            checker.Check(Int64.MaxValue, Int64.MaxValue);
            checker.Check(Double.Epsilon, Double.Epsilon);
            checker.Check(Double.MinValue, Double.MinValue);
            checker.Check(Double.MaxValue, Double.MaxValue);

            if(checkDecimal) {
                checker.Check(Decimal.MinValue, decimal.MinValue);
                checker.Check(Decimal.MaxValue, decimal.MaxValue);
            }

            if(checkDateTime) {
                checker.Check(DateTime.MinValue, DateTime.MinValue);
                checker.Check(DateTime.MaxValue.Date, DateTime.MaxValue.Date);
            }

            if(checkDateTimeOffset) {
                checker.Check(DateTimeOffset.MinValue, DateTimeOffset.MinValue);
                checker.Check(DateTimeOffset.MaxValue.Date, DateTimeOffset.MaxValue.Date);
            }

            var text = String.Empty.PadRight(84 * 1000, 'x');
            checker.Check(text, text);
        }

        public static void CheckBigNumberRoundtripForcesString(RoundtripChecker checker) {
            checker.Check(9223372036854775808, "9223372036854775808");
            checker.Check(9223372036854775808M, "9223372036854775808");
        }

        public static void CheckLongToDouble(IDatabaseAccess db, DatabaseStorage storage) {
            storage.EnterFluidMode();

            var bigLong = Int64.MinValue + 12345;
            var longID = storage.Store("foo", MakeRow("p", bigLong));

            storage.Store("foo", MakeRow("p", Math.PI));
            Assert.Equal(bigLong, db.Cell<long>(false, "select p from foo where id = {0}", longID));
        }

        public static void CheckDateTimeQueries(IDatabaseAccess db, DatabaseStorage storage) {
            storage.EnterFluidMode();

            var dateTime = SAMPLE_DATETIME;
            var date = SAMPLE_DATETIME.Date;

            storage.Store("foo", MakeRow("d", date));
            storage.Store("foo", MakeRow("d", dateTime));
            Assert.Equal(2, db.Cell<int>(false, "select count(*) from foo where d = {0} or d = {1}", date, dateTime));

            db.Exec("delete from foo");

            for(var i = -2; i <= 2; i++)
                storage.Store("foo", MakeRow("d", date.AddDays(i)));
            Assert.Equal(3, db.Cell<int>(false, "select count(*) from foo where d between {0} and {1}", date.AddDays(-1), date.AddDays(1)));

            Assert.Equal(date, db.Cell<DateTime>(false, "select d from foo where d = {0}", date));
        }

        public static void CheckGuidQuery(IDatabaseAccess db, DatabaseStorage storage) {
            storage.EnterFluidMode();
            storage.Store("foo", MakeRow("g", SAMPLE_GUID));
            Assert.Equal(SAMPLE_GUID, db.Cell<Guid>(false, "select g from foo where g = {0}", SAMPLE_GUID));
        }

        public static void CheckReadUncommitted(IDatabaseAccess db1, IDatabaseAccess db2) {
            db1.Exec("create table foo(f text)");
            db1.Exec("insert into foo(f) values('initial')");

            db1.Transaction(delegate() {
                db1.Exec("update foo set f='dirty'");

                db2.TransactionIsolation = IsolationLevel.ReadUncommitted;
                db2.Transaction(delegate() {
                    Assert.Equal("dirty", db2.Cell<string>(false, "select f from foo"));
                    return true;
                });

                return true;
            });
        }

        public static void CheckCustomRank_MissingColumn(IDatabaseAccess db, DatabaseStorage storage) {
            storage.EnterFluidMode();

            var row = MakeRow("a", new object());

            // Try create table
            AssertCannotAddColumn(Record.Exception(delegate() {
                storage.Store("foo1", row);
            }));

            storage.Store("foo2", MakeRow("b", 1));

            // Try add column
            AssertCannotAddColumn(Record.Exception(delegate() {
                storage.Store("foo2", row);
            }));
        }

        public static void CheckCompoundKey(DatabaseStorage storage, KeyUtil keys) {
            storage.EnterFluidMode();

            keys.RegisterKey("foo", new[] { "k1", "k2" }, null);

            var row = MakeRow(
                "k1", "text",
                "k2", Guid.NewGuid(),
                "v", "hello"
            );

            var id = storage.Store("foo", row) as CompoundKey;
            Assert.Equal(row["k1"], id["k1"]);
            Assert.Equal(row["k2"], id["k2"]);

            row = storage.Load("foo", id);
            Assert.Equal("hello", row["v"]);
        }

        public static void CheckStoringNull(DatabaseStorage storage) {
            storage.EnterFluidMode();

            var row = MakeRow("p", 1);
            var id = storage.Store("foo", row);

            row = storage.Load("foo", id);
            row["p"] = null;
            storage.Store("foo", row);

            row = storage.Load("foo", id);
            Assert.Null(row["p"]);
        }

        public static IDictionary<string, object> MakeRow(params object[] data) {
            var row = new Dictionary<string, object>();
            for(var i = 0; i < data.Length; i += 2) {
                row[(string)data[i]] = data[1 + i];
            }
            return row;
        }

        static void AssertCannotAddColumn(Exception x) {
            Assert.IsType<InvalidOperationException>(x);
            Assert.StartsWith("Cannot automatically add ", x.Message);
        }

    }

}


text:
/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';

import Amplitude from 'react-native-amplitude-analytics';

export default class Example extends Component {
  render() {

    const trackSessionEvents = true; // https://amplitude.zendesk.com/hc/en-us/articles/115003970027#tracking-events
    const amplitude = new Amplitude("Your Amplitude ID goes here", trackSessionEvents);
    alert(`amplitude: ${JSON.stringify(amplitude)}`)
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <Text style={styles.instructions}>
          Hello Amplitute
        </Text>
        <Text style={styles.instructions}>
          Your analytics should now be up and running
        </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

AppRegistry.registerComponent('Example', () => Example);


text:
@XmlSchema(
    namespace = JAXBConstants.NAMESPACE,
    location = JAXBConstants.LOCATION,
    elementFormDefault = XmlNsForm.QUALIFIED
)
@NonNullByDefault
package xyz.cloudkeeper.model.beans.element;

import xyz.cloudkeeper.model.util.JAXBConstants;
import xyz.cloudkeeper.model.util.NonNullByDefault;

import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;


text:
/*
 * HomePage Messages
 *
 * This contains all the text for the HomePage component.
 */
import { defineMessages } from 'react-intl';

export default defineMessages({
  info: {
    id: 'app.components.DialPad.info',
    defaultMessage: 'Phone numbers should be formatted with a "+" and country code e.g., +16175551212 (E.164 format).',
  },
});


text:
package main

import (
	"fmt"

	"golang.org/x/tools/go/loader"
	"golang.org/x/tools/go/ssa"
	"golang.org/x/tools/go/ssa/ssautil"
)

func main() {
	var conf loader.Config
	inputs := []string{"./bonzo"}

	if _, err := conf.FromArgs(inputs, true); err != nil {
		fmt.Printf("FromArgs(%s) failed: %s", inputs, err)
		return
	}

	conf.Import("runtime")

	iprog, err := conf.Load()
	if err != nil {
		fmt.Printf("conf.Load(%s) failed: %s", inputs, err)
		return
	}

	prog := ssautil.CreateProgram(iprog, ssa.SanityCheckFunctions)
	prog.BuildAll()

	var mainPkg *ssa.Package
	var initialPkgs []*ssa.Package
	for _, info := range iprog.InitialPackages() {
		if info.Pkg.Path() == "runtime" {
			continue // not an initial package
		}
		p := prog.Package(info.Pkg)
		initialPkgs = append(initialPkgs, p)
		if mainPkg == nil && p.Func("main") != nil {
			mainPkg = p
			fmt.Println("unexpexted main package in this bonzo example")
			return
		}
	}
	if mainPkg == nil {
		testmainPkg := prog.CreateTestMainPackage(initialPkgs...)
		if testmainPkg == nil {
			fmt.Printf("CreateTestMainPackage(%s) returned nil", mainPkg)
			return
		}
		if testmainPkg.Func("main") == nil {
			fmt.Printf("synthetic testmain package has no main")
			return
		}
		mainPkg = testmainPkg
	}

	fmt.Println("built:", mainPkg.String())
	for _, mem := range mainPkg.Members {
		if fn, isFn := mem.(*ssa.Function); isFn {
			printFunc(fn, 1)
		}
	}
}

func printFunc(fn *ssa.Function, depth int) {
	if depth == 0 {
		return
	}
	depth--
	printList := make(map[*ssa.Function]struct{})
	fmt.Println("\nfunction:", fn.String())
	for b, bl := range fn.Blocks {
		fmt.Printf("block %d:\n", b)
		for _, in := range bl.Instrs {
			if val, isVal := in.(ssa.Value); isVal {
				fmt.Println("\t", val.Name(), "=", in)
			} else {
				fmt.Println("\t", in)
			}
			for _, rand := range in.Operands(nil) {
				if called, isFn := (*rand).(*ssa.Function); isFn {
					printList[called] = struct{}{}
				}
			}
			if call, isCall := in.(*ssa.Call); isCall {
				sc := call.Call.StaticCallee()
				if sc != nil {
					printList[sc] = struct{}{}
				}
			}
		}
	}
	for called := range printList {
		printFunc(called, depth)
	}
}


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

namespace DeskboyDotNet
{
	interface ISaveAble
	{
		void save();
	}
}


text:
/* Override some defaults */
html, body {
  background-color: #eee;
}
body {
  padding-top: 40px; /* 40px to make the container go all the way to the bottom of the topbar */
}
.container > footer p {
  text-align: center; /* center align it with the container */
  margin: 12px 0;
}
.container {
  width: 820px; /* downsize our container to make the content feel a bit tighter and more cohesive. NOTE: this removes two full columns from the grid, meaning you only go to 14 columns and not 16. */
}

/* The white background content wrapper */
.content {
  background-color: #fff;
  padding: 20px;
  margin: 0 -20px; /* negative indent the amount of the padding to maintain the grid system */
  -webkit-border-radius: 0 0 6px 6px;
     -moz-border-radius: 0 0 6px 6px;
          border-radius: 0 0 6px 6px;
  -webkit-box-shadow: 0 1px 2px rgba(0,0,0,.15);
     -moz-box-shadow: 0 1px 2px rgba(0,0,0,.15);
          box-shadow: 0 1px 2px rgba(0,0,0,.15);
}

/* Page header tweaks */
.page-header {
  background-color: #f5f5f5;
  padding: 20px 20px 10px;
  margin: -20px -20px 20px;
}

/* Styles you shouldn't keep as they are for displaying this base example only */
.content .span10,
.content .span4 {
  min-height: 500px;
}
/* Give a quick and non-cross-browser friendly divider */
.content .span4 {
  margin-left: 0;
  padding-left: 19px;
  border-left: 1px solid #eee;
}

.navbar .btn {
  border: 0;
}

ul.audiotracks-list {
  margin-left: 0;
  margin-top: 16px;
}
ul.audiotracks-list li {
  margin-bottom: 5px;
  list-style: none;
}

.form-stacked { padding-left: 0; }
.audiotracks-form { padding-left: 20px; }
.audiotracks-form input { width: 300px; }
.audiotracks-form input[type=file] { width: auto; }
.audiotracks-form #save-button { clear: left; }
.audiotracks-form#delete-form { float: left; }
.audiotracks-form #delete-button {
  position: relative;
  top: -55px;
  left: 160px;
}
.audiotracks-edit-row img { vertical-align: middle; }
.audiotracks-edit-row { clear: both; margin-bottom: 10px; }
.audiotracks-edit-row .audiotracks-edit-half-row {
  float: left;
  margin-right: 20px;
  margin-bottom: 10px;
}
#audiotracks-delete-image-label {
  display: inline;
  width: auto;
  float: none;
}
#delete_image {
  display: inline;
  width: auto;
}
.messages { color: green; border: solid 1px green; padding: 0.2em; }
.messages li { list-style: none; }
.errorlist { color: red; list-style: none; display: inline; }
.errorlist li { color: red; }
.audiotracks-edit-row .errorlist { float: right; margin-bottom: 0; }
.audiotracks-edit-current-data { width: auto; float: none; }
#slug {
  float: left;
  margin-bottom: 30px;
}

#audiotracks-upload-form legend { padding-left: 0; }
#audiotracks-upload-form label { width: auto; margin-right: 10px; }
#slug label {
  display: block;
  width: auto;
  float: none;
  text-align: left;
}
#id_description { width: 630px; }
.btn.small { padding: 2px; }
.audiotracks-download { margin: 16px 0; }

.audiotracks-list-entry {
  padding: 24px 0;
  border-color: #eee;
  border-style: solid;
  border-width: 1px 0;
}

.audiotracks-list-entry:not(:first-child) {
  border-top: 0;
}

.audiotracks-list-entry .track-title {
  font-size: 24px;
  line-height: 24px;
}

.track-image {
  float: left;
  margin-right: 10px;
}

.audiotracks-detail .track-image {
  display: none;
}

.audiotracks-detail .audiotracks-list-entry {
  margin: 12px 12px 24px 12px;
  float: left;
  width: 596px; /* 820 - 200 - (2 * 12) */
}

.audiotracks-detail img:first-child {
  float: left;
}


text:
import ast
import os
import re
import sys
from setuptools import setup

# The project does not work on Python 2. In case someone tries to install it
# via pip2, raise a helpful error (rather than meaningless "TypeError:
# 'encoding' is an invalid keyword argument for this function").
if sys.version_info[0] == 2:
    sys.exit('Error: retdec-python does not support Python 2. Use Python 3.')
# Additionally, check that the user runs at least Python 3.4 as this is the
# minimal required version.
if sys.version_info < (3, 4):
    sys.exit('Error: retdec-python requires at least Python 3.4.')

# Utility function to read the contents of the given file.
def read_file(file_path):
    with open(file_path, encoding='utf-8') as f:
        return f.read()

def get_project_version():
    # Based on:
    #
    #   https://packaging.python.org/en/latest/single_source_version.html
    #   https://github.com/mitsuhiko/flask/blob/master/setup.py
    #
    return ast.literal_eval(
        re.search(
            r'__version__\s+=\s+(.*)',
            read_file(os.path.join('retdec', '__init__.py'))
        ).group(1)
    )

setup(
    name='retdec-python',
    version=get_project_version(),
    description=(
        'A Python library and tools providing easy access to the retdec.com '
        'decompilation service through their public REST API.'
    ),
    long_description=read_file('README.rst'),
    author='Petr Zemek',
    author_email='s3rvac@gmail.com',
    url='https://github.com/s3rvac/retdec-python',
    license=read_file('LICENSE'),
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: Implementation :: CPython',
        'Programming Language :: Python :: Implementation :: PyPy',
        'Topic :: Software Development :: Libraries :: Python Modules',
    ],
    keywords='retdec decompiler decompilation analysis fileinfo',
    packages=['retdec', 'retdec.tools'],
    install_requires=['requests'],
    scripts=[
        os.path.join('scripts', 'decompiler'),
        os.path.join('scripts', 'fileinfo')
    ]
)


text:
var psoRun = false,
    swarm = [],
    gobalBestParticle;
var maxVelocity = 40,
    cognition = 0.3,
    social = 0.3;

function psoStart(parameter) {
    switch (parameter) {
        case 'start':
            psoRun = true;
            break;
        case 'stop':
            psoRun = false;
            break;
        default:
            psoRun = !psoRun;
    }
    if (psoRun) {
        document.getElementById('psoStart').innerHTML = 'Stop (P)';
        fuzzyStart('stop');
        geneticStart('stop');
        startMotion('start');
    } else {
        document.getElementById('psoStart').innerHTML = 'Start (P)';
        startMotion('stop');
    }
}

function updateMaxVelocity(value) {
    maxVelocity = parseFloat(value);
}

function updateCognition(value) {
    cognition = parseFloat(value);
}

function updateSocial(value) {
    social = parseFloat(value);
}

function pso() {
    var output = 0;
    if (dimension == 3) {
        output = gobalBestParticle.rbf.getOutput([distanceCenter, distanceRight, distanceLeft]);
    } else if (dimension == 5) {
        output = gobalBestParticle.rbf.getOutput([posX, posY, distanceCenter, distanceRight, distanceLeft]);
    }
    angleWheel = (output * 80.0) - 40;
    readAngleWheel();
}

function psoTrain() {
    document.getElementById('psoStart').disabled = true;
    geneticStart('stop');
    fuzzyStart('stop');
    psoStart('stop');
    psoReset();
    for (var i = 0; i < size; i++) {
        swarm.push(Particle.createNew());
        swarm[i].randomBuild();
    }
    // Read data
    var rawData = readTextFile(dataset);
    for (var i = 0; i < rawData.length; i++) {
        if (rawData[i] !== '') {
            input[i] = [];
            var data = rawData[i].split(' ');
            for (var j = 0; j < data.length - 1; j++) {
                input[i].push(parseFloat(data[j]));
            }
            output.push((parseFloat(data[data.length - 1]) + 40) / 80.0);
        }
    }
    var minFitness = 1000000;
    var personalBest = [];
    for (var i = 0; i < swarm.length; i++) {
        personalBest.push(Particle.createNew());
    }
    for (var iterations = 0; iterations < maxIterations; iterations++) {
        // Calcuate fitness
        for (var i = 0; i < swarm.length; i++) {
            var temp = swarm[i].getFitness(output, input);
            // Personal best
            if (temp < personalBest[i].fitness) {
                personalBest[i] = swarm[i].clone();
                personalBest[i].fitness = temp;
            }
            // Gobal best
            if (temp < minFitness) {
                minFitness = temp;
                gobalBestParticle = swarm[i].clone();
                console.log(minFitness);
                document.getElementById('lossRate').innerHTML = minFitness.toFixed(4);
            }
        }
        if (minFitness < 0.001)
            break;
        // Update Velocity
        for (var i = 0; i < swarm.length; i++) {
            for (var j = 0; j < swarm[i].v.length; j++) {
                swarm[i].v[j] = swarm[i].v[j] + cognition * (personalBest[i].x[j] - swarm[i].x[j]) + social * (gobalBestParticle.x[j] - swarm[i].x[j]);
                swarm[i].v[j] = Math.min(Math.max(swarm[i].v[j], -maxVelocity), maxVelocity);
            }
            swarm[i].move();
        }
    }
    // Calcuate fitness
    for (var i = 0; i < swarm.length; i++) {
        var temp = swarm[i].getFitness(output, input);
        // Gobal best
        if (temp < minFitness) {
            minFitness = temp;
            gobalBestParticle = swarm[i].clone();
            console.log(minFitness);
            document.getElementById('lossRate').innerHTML = minFitness.toFixed(4);
        }
    }
    gobalBestParticle.getFitness(output, input);
    document.getElementById('psoStart').disabled = false;
    Materialize.toast('Training finished!', 3000);
}

function psoReset() {
    input = [];
    output = [];
    swarm = [];
    gobalBestParticle = null;
}


text:
module TfpMetaprogramming
  module MetaMethods
    module Aliases
      # Handles aliasing a method that SydneyBristow will override
      module AroundAlias
        # outputs text describing an around alias
        def around_espionage
          'I demonstrate the complicated nature
           of both government espionage and rubys
           around_aliases'
        end

        # aliases #around_alias to preserve original
        # functionality in case of overwrite
        alias_method :convolutions, :around_espionage
      end
    end
  end
end


text:
``pymap.cluster``
=================

.. automodule:: pymap.cluster
   :members:
   :special-members: __call__

``pymap.cluster.swim``
----------------------

.. automodule:: pymap.cluster.swim
   :members:


text:
/*++

Module Name:

    EmsPktPattern.c

Abstract:

    Implementation for packet validation validation

--*/

#include "EmsPktValidate.h"
#include "EmsTypes.h"
#include "EmsPktMain.h"
#include "EmsProtocols.h"
#include "EmsUtilityString.h"

STATIC INT8     Expression[EXPR_MAX_LEN];
STATIC BOOLEAN  Operands[EXPR_MAX_LEN];
STATIC INT8     Operators[EXPR_MAX_LEN];
STATIC BOOLEAN  *OperandTop;
STATIC INT8     *OperatorTop;

//
// operators in packet validate expression  :
//   AND  OR  NOT  (  )
//
OPERATOR_T      OperatorList[] = {
#define OP_AND  0
  {
    "AND"
  },
#define OP_OR 1
  {
    "OR"
  },
#define OP_NOT  2
  {
    "NOT"
  },
#define OP_LPA  3
  {
    "("
  },
#define OP_RPA  4
  {
    ")"
  },
#define OP_CRS  5
  {
    "#"
  },
  {
    NULL
  }
};

/* The priority relationhip between every two operator */

/* AND   OR    NOT   (     )     #  */
UINT32          Priority[6][6] = {
  {
    HIGHP,
    HIGHP,
    LOWP,
    LOWP,
    HIGHP,
    HIGHP
  },

  /* AND */
  {
    HIGHP,
    HIGHP,
    LOWP,
    LOWP,
    HIGHP,
    HIGHP
  },

  /* OR */
  {
    HIGHP,
    HIGHP,
    HIGHP,
    LOWP,
    HIGHP,
    HIGHP
  },

  /* NOT */
  {
    LOWP,
    LOWP,
    LOWP,
    LOWP,
    EQUAP,
    ERRP
  },

  /* ( */
  {
    HIGHP,
    HIGHP,
    HIGHP,
    ERRP,
    HIGHP,
    HIGHP
  },

  /* ) */
  {
    LOWP,
    LOWP,
    LOWP,
    LOWP,
    ERRP,
    EQUAP
  }
};  /* # */

STATIC
VOID_P
InitOperandStack (
  VOID_P
  )
/*++

Routine Description:

  Initialize the Stack of Operand

Arguments:

  VOID_P - None

Returns:

  None

--*/
{
  BOOLEAN *PacketPointer;
  UINT32  Index;
  PacketPointer = Operands;
  for (Index = 0; Index < EXPR_MAX_LEN; Index++) {
    PacketPointer[Index] = TRUE;
  }
}

STATIC
VOID_P
PushOperandStack (
  IN BOOLEAN Value
  )
/*++

Routine Description:

  Push an Operand into Stack.

Arguments:

  Value - The Operand to push.

Returns:

  None

--*/
{
  *OperandTop = Value;
  OperandTop += 1;
}

STATIC
BOOLEAN
PopOperandStack (
  VOID_P
  )
/*++

Routine Description:

  Pop an Operand from Stack.

Arguments:

  None

Returns:

  The Operand on top of stack.

--*/
{
  OperandTop -= 1;
  return *OperandTop;
}

STATIC
BOOLEAN
GetTopOperandStack (
  VOID_P
  )
/*++

Routine Description:

  Just get the top Operand from Stack, without any change to stack pointer.

Arguments:

  None

Returns:

  The Operand on top of stack.

--*/
{
  return *(OperandTop - 1);
}

STATIC
VOID_P
InitOperatorStack (
  VOID_P
  )
/*++

Routine Description:

  Initialize the Operator Stack.

Arguments:

  None

Returns:

  None

--*/
{
  INT8    *PacketPointer;
  UINT32  Index;
  PacketPointer = Operators;

  for (Index = 0; Index < EXPR_MAX_LEN; Index++) {
    PacketPointer[Index] = -1;
  }
}

/*++

Routine Description:
   Push an Operator into Stack.
Argumems:
   The Operator to push.
Returns:
--*/
STATIC
VOID_P
PushOperatorStack (
  IN INT8 Value
  )
/*++

Routine Description:

  Push an Operator into Stack.

Arguments:

  Value - The Operator to push.

Returns:

  None

--*/
{
  *OperatorTop = Value;
  OperatorTop += 1;
}

STATIC
INT8
PopOperatorStack (
  VOID_P
  )
/*++

Routine Description:

  Pop an Operator from Stack.

Arguments:

  None

Returns:

  The Operator on top of stack.

--*/
{
  OperatorTop -= 1;
  return *OperatorTop;
}

STATIC
INT8
GetTopOperatorStack (
  VOID_P
  )
/*++

Routine Description:

  Just get the top Operator from Stack, without any change to stack pointer.

Arguments:

  None

Returns:

  The Operator on top of stack.

--*/
{
  return *(OperatorTop - 1);
}

STATIC
INT8
GetOperatorIndex (
  IN INT8 *OperatorName
  )
/*++

Routine Description:

  Get index of the Operator for convenience of comparing priority.

Arguments:

  OperatorName - The Operator per se.'+','-',etc..

Returns:

  The Operator's index.

--*/
{
  UINT32  Index;
  for (Index = 0; OperatorList[Index].Name; Index++) {
    if (strlen (OperatorList[Index].Name) > strlen (OperatorName)) {
      continue;
    }

    if (!(strncmp (OperatorList[Index].Name, OperatorName, strlen (OperatorList[Index].Name)))) {
      return Index;
    }
  }

  return -1;
}

STATIC
UINT8
ComparePriority (
  IN INT8 Operator1,
  IN INT8 Operator2
  )
/*++

Routine Description:

  Compare priorities between two operators.

Arguments:

  Operator1 - The operators.
  Operator2 - The operators.

Returns:

  HIGHP, LOWP, EQUAP or ERRP

--*/
{
  return Priority[Operator1][Operator2];
}

STATIC
BOOLEAN
OneStepCalculate (
  IN INT8        Operation,
  IN BOOLEAN     Operand1,
  IN BOOLEAN     Operand2
  )
/*++

Routine Description:

  Just execute a step of calculate

Arguments:

  Operation - The Operator,'AND' 'OR' 'NOT' '/'
  Operand1  - The 1st operand
  Operand2  - The 2nd operand

Returns:

  The calculated result.

--*/
{
  BOOLEAN Result;
  Result = TRUE;

  switch (Operation) {
  case OP_AND:
    Result = Operand1 ? Operand2 : FALSE;
    break;

  case OP_OR:
    Result = Operand1 ? TRUE : Operand2;
    break;

  case OP_NOT:
    Result = Operand2 ? FALSE : TRUE;
    break;

  default:
    break;
  }

  return Result;
}

STATIC
BOOLEAN
GetOperand (
  IN     INT8      *ExprP,
  IN     FIELD_T   *Unpack,
  IN OUT UINT32    *Offset
  )
/*++

Routine Description:

  Calculate a Bool expression.
  e.g. "ip_addr=192.168.88.1"

Arguments:

  ExprP   - The expression
  Unpack  - The Data
  Offset  - The offset the calculation end

Returns:

  Calculated result.

--*/
{
  BOOLEAN Result;
  INT32   Status;
  UINT32  Index;
  UINT32  AddrIndex;
  UINT32  Len;
  UINT32  Value;
  EMS_IPV6_ADDR IPv6Addr;
  UINT8   Eth[6];

  Result = FALSE;
  //
  // Find first '='
  //
  for (Len = 0; ExprP[Len]; Len++) {
    if (ExprP[Len] == '=') {
      break;
    }
  }

  if (ExprP[Len] == '\0') {
    return Result;

  }

  Len++;

  for (; ExprP[Len]; Len++) {
    if (ExprP[Len] != ' ') {
      break;
    }
  }

  *Offset = Len;

  for (Index = 0; Unpack[Index].Name; Index++) {
    if (0 == strncmp_i (Unpack[Index].Name, ExprP, strlen (Unpack[Index].Name))) {

      switch (Unpack[Index].Type) {
      case OCTET1:
        Status = AsciiStringToUint32 (ExprP + Len, &Value);
        if (Status <= 0) {
          return ERROR_WRONGFORMAT;
        }

        *Offset += Status;
        if ((UINT8) Value == * (UINT8 *) (Unpack[Index].Value)) {
          return TRUE;
        } else {
          return FALSE;
        }

      case OCTET2:
        Status = AsciiStringToUint32 (ExprP + Len, &Value);
        if (Status < 0) {
          return ERROR_WRONGFORMAT;
        }

        *Offset += Status;
        if ((UINT16) Value == * (UINT16 *) (Unpack[Index].Value)) {
          return TRUE;
        } else {
          return FALSE;
        }

      case OCTET4:
        Status = AsciiStringToUint32 (ExprP + Len, &Value);
        if (Status < 0) {
          return ERROR_WRONGFORMAT;
        }

        *Offset += Status;
        if (*(UINT32 *) (Unpack[Index].Value) == (UINT32) Value) {
          return TRUE;
        } else {
          return FALSE;
        }

      case IPADDR:
        Status = AsciiStringToIpv4 (ExprP + Len, &Value);
        if (Status < 0) {
          return ERROR_WRONGFORMAT;
        }

        *Offset += Status;
        if (*(UINT32 *) (Unpack[Index].Value) == (UINT32) Value) {
          return TRUE;
        } else {
          return FALSE;
        }

	  case IPV6ADDR:
        Status = AsciiStringToIpv6 (ExprP + Len, &IPv6Addr);
        if (Status <= 0) {
          return ERROR_WRONGFORMAT;
        }

        *Offset += Status;
		for (AddrIndex = 0; AddrIndex< 8 ; AddrIndex++){
          if (((EMS_IPV6_ADDR*)Unpack[Index].Value)->__u6_addr.__u6_addr16[AddrIndex] !=
		  	    IPv6Addr.__u6_addr.__u6_addr16[AddrIndex]){
            return FALSE;
		  }
		}
		return TRUE;

      case MACADDR:
        Status = AsciiStringToMac (ExprP + Len, Eth);
        if (Status < 0) {
          return ERROR_WRONGFORMAT;
        }

        *Offset += Status;
        if (0 == memcmp (Unpack[Index].Value, Eth, 6)) {
          return TRUE;
        } else {
          return FALSE;
        }

      case STRING:
        if (Len != strlen (*(INT8 **) Unpack[Index].Value)) {
          return FALSE;
        }

        if (0 == strncmp (*(INT8 **) Unpack[Index].Value, ExprP + Len, Len)) {
          return TRUE;
        } else {
          return FALSE;
        }

      case PAYLOAD:
      //
      // How to validata payload ???
      // Now case writer has to use "ParsePacket" to store the payload into
      // a packet then validate it.
      //
      default:
        return ERROR_INTERNAL;
      }
    }
  }

  return FALSE;
}

BOOLEAN
Validate (
  IN INT8      *Pattern,
  IN FIELD_T   *Unpack
  )
/*++

Routine Description:

  The main process of validate

Arguments:

  Pattern - The pattern validation
  Unpack  - The Data

Returns:

  Calculated result.

--*/
{

  INT8    *ExprP;
  INT8    CurrentOperator;
  INT8    TempOperator;
  BOOLEAN Operand1;
  BOOLEAN Operand2;
  BOOLEAN TempResult;
  UINT32  ExprLenth;
  UINT32  Offset;

  if (NULL == Unpack || NULL == Pattern) {
    return FALSE;
  }

  strcpy (Expression, Pattern);

  InitOperatorStack ();
  InitOperandStack ();
  Operators[0]          = OP_CRS;
  ExprLenth             = strlen (Expression);
  Expression[ExprLenth] = '#';
  ExprP                 = Expression;
  OperatorTop           = Operators + 1;
  OperandTop            = Operands;

  while (*ExprP) {
    if (('#' == *ExprP) && (OP_CRS == GetTopOperatorStack ())) {
      break;
    }

    TempOperator = GetOperatorIndex (ExprP);

    if (TempOperator >= 0) {
      switch (ComparePriority (GetTopOperatorStack (), TempOperator)) {
      case HIGHP:
        CurrentOperator = PopOperatorStack ();
        Operand2        = PopOperandStack ();
        Operand1        = PopOperandStack ();
        TempResult      = OneStepCalculate (CurrentOperator, Operand1, Operand2);
        PushOperandStack (TempResult);
        break;

      case LOWP:
        PushOperatorStack (TempOperator);
        if (TempOperator == OP_NOT) {
          PushOperandStack (TRUE);
        }

        ExprP += strlen (OperatorList[TempOperator].Name);
        break;

      case EQUAP:
        PopOperatorStack ();
        ExprP += 1;
        break;

      default:
        return -1;
        break;
      }
    } else if (' ' == *ExprP) {
      ExprP += 1;
    } else {
      TempResult = GetOperand (ExprP, Unpack, &Offset);
      ExprP += Offset;
      PushOperandStack (TempResult);
    }
  }

  return GetTopOperandStack ();
}


text:
package org.example;

import java.io.StringWriter;
import java.io.Writer;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Collection;
import java.util.Date;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.json.Json;
import javax.json.stream.JsonGenerator;

class EJsonWriter {

  public static String write(Object object) {
    StringWriter writer = new StringWriter(200);
    write(object, writer);
    return writer.toString();
  }

  public static void write(Object object, Writer writer) {
    JsonGenerator generator = Json.createGenerator(writer);
    write(object, generator);
    generator.close();
  }

  public static void write(Object object, JsonGenerator jsonGenerator) {
    new EJsonWriter(jsonGenerator).writeJson(object);
  }

  private final JsonGenerator jsonGenerator;

  private EJsonWriter(JsonGenerator jsonGenerator) {
    this.jsonGenerator = jsonGenerator;
  }

  private void writeJson(Object object) {
    writeJson(null, object);
  }

  @SuppressWarnings("unchecked")
  private void writeJson(String name, Object object) {
    if (object == null) {
      writeNull(name);

    } else if (object instanceof Map) {
      writeMap(name, (Map<Object, Object>) object);

    } else if (object instanceof Collection) {
      writeCollection(name, (Collection<Object>) object);

    } else if (object instanceof Boolean) {
      writeBoolean(name, (Boolean) object);

    } else if (object instanceof Number) {
      writeNumber(name, (Number) object);

    } else if (object instanceof Date) {
      writeDate(name, (Date) object);

    } else if (object instanceof String) {
      writeString(name, (String) object);

    } else {
      writeString(name, object.toString());
    }

  }

  private void writeBoolean(String name, Boolean object) {
    if (name == null) {
      jsonGenerator.write(object);
    } else {
      jsonGenerator.write(name, object);
    }
  }

  private void writeDate(String name, Date object) {
    if (name == null) {
      jsonGenerator.write(object.getTime());
    } else {
      jsonGenerator.write(name, object.getTime());
    }
  }

  private void writeNumber(String name, Number object) {

    if (object instanceof Long) {
      writeLong(name, object);

    } else if (object instanceof Integer) {
      writeInteger(name, object);

    } else if (object instanceof Double) {
      writeDouble(name, object);

    } else if (object instanceof BigDecimal) {
      writeBigDecimal(name, object);

    } else if (object instanceof BigInteger) {
      writeBigInteger(name, object);

    } else {
      writeGeneralNumber(name, object);
    }
  }

  private void writeGeneralNumber(String name, Number object) {
    if (name == null) {
      jsonGenerator.write(new BigDecimal(object.toString()));
    } else {
      jsonGenerator.write(name, new BigDecimal(object.toString()));
    }
  }

  private void writeBigDecimal(String name, Number object) {
    if (name == null) {
      jsonGenerator.write((BigDecimal) object);
    } else {
      jsonGenerator.write(name, (BigDecimal) object);
    }
  }

  private void writeBigInteger(String name, Number object) {
    if (name == null) {
      jsonGenerator.write((BigInteger) object);
    } else {
      jsonGenerator.write(name, (BigInteger) object);
    }
  }

  private void writeDouble(String name, Number object) {
    if (name == null) {
      jsonGenerator.write((Double) object);
    } else {
      jsonGenerator.write(name, (Double) object);
    }
  }

  private void writeLong(String name, Number object) {
    if (name == null) {
      jsonGenerator.write((Long) object);
    } else {
      jsonGenerator.write(name, (Long) object);
    }
  }

  private void writeInteger(String name, Number object) {
    if (name == null) {
      jsonGenerator.write((Integer) object);
    } else {
      jsonGenerator.write(name, (Integer) object);
    }
  }

  private void writeNull(String name) {
    if (name == null) {
      jsonGenerator.writeNull();
    } else {
      jsonGenerator.writeNull(name);
    }
  }

  private void writeString(String name, String object) {
    if (name == null) {
      jsonGenerator.write(object);
    } else {
      jsonGenerator.write(name, object);
    }
  }

  private void writeCollection(String name, Collection<Object> collection) {
    if (name == null) {
      jsonGenerator.writeStartObject();
    } else {
      jsonGenerator.writeStartArray(name);
    }
    for (Object object : collection) {
      writeJson(null, object);
    }
    jsonGenerator.writeEnd();
  }

  private void writeMap(String name, Map<Object, Object> map) {

    if (name == null) {
      jsonGenerator.writeStartObject();
    } else {
      jsonGenerator.writeStartObject(name);
    }
    Set<Entry<Object, Object>> entrySet = map.entrySet();
    for (Entry<Object, Object> entry : entrySet) {
      writeJson(entry.getKey().toString(), entry.getValue());
    }
    jsonGenerator.writeEnd();
  }

}


text:
module Softlayer
  module User
    class Employee < Softlayer::User::Interface
      autoload :Department, 'softlayer/user/employee/department'
      attr_accessor :display_name
      attr_accessor :email
      attr_accessor :employee_department_id
      attr_accessor :first_name
      attr_accessor :last_name
      attr_accessor :office_phone
      attr_accessor :username
      attr_accessor :action_count
      attr_accessor :chat_transcript_count
      attr_accessor :layout_profile_count
      attr_accessor :role_count
      attr_accessor :ticket_activity_count
      attr_accessor :ticket_attachment_reference_count
      attr_accessor :actions
      attr_accessor :chat_transcript
      attr_accessor :employee_department
      attr_accessor :layout_profiles
      attr_accessor :metric_tracking_object
      attr_accessor :roles
      attr_accessor :ticket_activities
      attr_accessor :ticket_attachment_references

      class Representer < Softlayer::User::Interface::Representer
        include Representable::Hash
        include Representable::Coercion
        property :display_name, type: String
        property :email, type: String
        property :employee_department_id, type: Integer
        property :first_name, type: String
        property :last_name, type: String
        property :office_phone, type: String
        property :username, type: String
        property :action_count, type: BigDecimal
        property :chat_transcript_count, type: BigDecimal
        property :layout_profile_count, type: BigDecimal
        property :role_count, type: BigDecimal
        property :ticket_activity_count, type: BigDecimal
        property :ticket_attachment_reference_count, type: BigDecimal
      end
    end
  end
end


text:
#ifndef MSG_DIRECTION_H
#define MSG_DIRECTION_H

#ifdef __cplusplus
extern "C" {
#endif

typedef enum msg_direction_t_ {
	MSG_DIRECTION_SENDER,
	MSG_DIRECTION_RECEIVER,
	MSG_DIRECTION_BOTH,
} msg_direction_t;

#ifdef __cplusplus
}
#endif

#endif /* MSG_DIRECTION_H */


text:
<?xml version='1.0' encoding='utf-8'?>
<widget id="com.ionicframework.wooleapp293021" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <feature name="LocalStorage">
        <param name="ios-package" value="CDVLocalStorage" />
    </feature>
    <feature name="Geolocation">
        <param name="ios-package" value="CDVLocation" />
    </feature>
    <feature name="Console">
        <param name="ios-package" value="CDVLogger" />
    </feature>
    <feature name="Device">
        <param name="ios-package" value="CDVDevice" />
    </feature>
    <feature name="SplashScreen">
        <param name="ios-package" value="CDVSplashScreen" />
        <param name="onload" value="true" />
    </feature>
    <feature name="StatusBar">
        <param name="ios-package" value="CDVStatusBar" />
        <param name="onload" value="true" />
    </feature>
    <feature name="Keyboard">
        <param name="ios-package" onload="true" value="IonicKeyboard" />
    </feature>
    <name>WooleApp</name>
    <description>
        Um app para quem gosta de pedalar!
  </description>
    <author email="rafael.neri@gmail.com">
      Rafael Neri
  </author>
    <content src="index.html" />
    <access origin="*" />
    <preference name="AllowInlineMediaPlayback" value="false" />
    <preference name="BackupWebStorage" value="none" />
    <preference name="DisallowOverscroll" value="true" />
    <preference name="EnableViewportScale" value="false" />
    <preference name="KeyboardDisplayRequiresUserAction" value="true" />
    <preference name="MediaPlaybackRequiresUserAction" value="false" />
    <preference name="SuppressesIncrementalRendering" value="false" />
    <preference name="GapBetweenPages" value="0" />
    <preference name="PageLength" value="0" />
    <preference name="PaginationBreakingMode" value="page" />
    <preference name="PaginationMode" value="unpaginated" />
    <preference name="StatusBarOverlaysWebView" value="true" />
    <preference name="StatusBarStyle" value="lightcontent" />
    <preference name="webviewbounce" value="false" />
    <preference name="UIWebViewBounce" value="false" />
    <preference name="SplashScreenDelay" value="2000" />
    <preference name="FadeSplashScreenDuration" value="2000" />
    <preference name="android-minSdkVersion" value="16" />
</widget>


text:
package org.apache.struts2.convention.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * <!-- START SNIPPET: javadoc -->
 * <p>
 * This annotation allows a class to define more than one {@link InterceptorRef}
 * annotations.
 * </p>
 * <!-- END SNIPPET: javadoc -->
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface InterceptorRefs {
    InterceptorRef[] value();
}


text: Boilerplate for Android. Using Clean architecture.  ![Build](https://travis-ci.org/juanagu/jaagoo-android-boilerplate.svg?branch=master)


text:
/*
 * QBtSingleDeviceSelectorUIPrivate.h
 *
 *
 *      Author: ftylitak
 *
 * 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.
 */

#ifndef QBTSINGLEDEVICESELECTORUI_PRIVATE_STUB_H_
#define QBTSINGLEDEVICESELECTORUI_PRIVATE_STUB_H_

#include "DeviceDiscoverer/QBtSingleDeviceSelectorUI.h"
#include <QBtGlobal.h>
#include <QBtTypes.h>
#include <QBtDeviceDiscoverer.h>
#include <QtGui/QListWidget>
#include <QtGui/QLabel>
#include <QtGui/QVBoxLayout>
#include <QtGui/QMenuBar>
#include <QtGui/QAction>
#include <QtCore/QModelIndex>
#include <QtGui/QDialog>

QBT_NAMESPACE_BEGIN

/**
 * This class provides UI for searching remote bluetooth
 * devices, displaying them and selecting one device.
 *
 * When a device is selected, the UI is closed and the
 * device instance is returned through discoveryCompleted()
 * signal.
 * (NOTE: when closed it is not destroyed, just hiden)
 *
 * To use, create an instance of the class and call
 * show(). When shown, discovery starts as well.
 *
 * To get the selected remote device, the discoveryCompleted()
 * signal must be handled.
 */
class QBtSingleDeviceSelectorUIPrivate : public QDialog
{
   Q_OBJECT

public:
    /**
     * if parent == NULL, the list will be showed as indepentant
     * widget on the screen, thus it's not necessary for the client application
     * to have a GUI interface.
     */
    QBtSingleDeviceSelectorUIPrivate(QWidget* parent, QBtSingleDeviceSelectorUI* publicClass);

    /**
     * Destructor.
     */
    ~QBtSingleDeviceSelectorUIPrivate();

public slots:

    /**
     * On show, the device discovery starts.
     */
    void show();

protected slots:

    void populateDeviceList(const QBtDevice& device);
    void devSelected(QListWidgetItem* devName);
    void selectPressed();
    void exitPressed();

private:
    QWidget * _parent;
    QBtDevice* _selectedDevice;
    QBtDeviceDiscoverer* _discoverer;
    QListWidget* _devList;
    QLabel* _label;
    QVBoxLayout *_verticalLayout;
    QList<QBtDevice> _devicesFound;

    QMenuBar* _menu;
    QAction* _select;
    QAction* _exit;

    QBtSingleDeviceSelectorUI* _publicClass;
};

QBT_NAMESPACE_END

#endif