text:
var _      = require('lodash');
var async  = require('async');
var events = require('events');
var util   = require('util');

var config = require('./config');
var Plugin = require('./plugin');

/**
 * Exposes the current state of a WCT run, and emits events/hooks for anyone
 * downstream to listen to.
 *
 * @param {Object} options Any initially specified options.
 */
function Context(options) {
  options = options || {};

  /**
   * The configuration for the current WCT run.
   *
   * We guarantee that this object is never replaced (e.g. you are free to hold
   * a reference to it, and make changes to it).
   */
  this.options = config.merge(
    config.defaults(),
    config.fromDisk(options.enforceJsonConf, options.root),
    options
  );

  /** @type {!Object<string, !Array<function>>} */
  this._hookHandlers = {};
}
util.inherits(Context, events.EventEmitter);

// Hooks
//
// In addition to emitting events, a context also exposes "hooks" that
// interested parties can use to inject behavior.

/**
 * Registers a handler for a particular hook. Hooks are typically configured to
 * run _before_ a particular behavior.
 *
 * @param {string} name
 * @param {function(!Object, function(*))} handler
 * @return {!Context}
 */
Context.prototype.hook = function hook(name, handler) {
  this._hookHandlers[name] = this._hookHandlers[name] || [];
  this._hookHandlers[name].unshift(handler);
};

/**
 * Registers a handler that will run after any handlers registered by `hook`.
 *
 * @param {string} name
 * @param {function(!Object, function(*))} handler
 * @return {!Context}
 */
Context.prototype.hookLate = function hookLate(name, handler) {
  this._hookHandlers[name] = this._hookHandlers[name] || [];
  this._hookHandlers[name].push(handler);
};

/**
 * Once all registered handlers have run for the hook, your callback will be
 * triggered. If any of the handlers indicates an error state, any subsequent
 * handlers will be canceled, and the error will be passed to the callback for
 * the hook.
 *
 * Any additional arguments passed between `name` and `done` will be passed to
 * hooks (before the callback).
 *
 * @param {string} name
 * @param {function(*)} done
 * @return {!Context}
 */
Context.prototype.emitHook = function emitHook(name, done) {
  this.emit('log:debug', 'hook:', name);

  var hooks = (this._hookHandlers[name] || []);
  if (arguments.length > 2) {
    var hookArgs = Array.prototype.slice.call(arguments, 1, arguments.length - 1);
    done = arguments[arguments.length - 1];  // mutates arguments in loose mode!
    hooks = hooks.map(function(hook) {
      return hook.bind.apply(hook, [null].concat(hookArgs));
    });
  }

  // We execute the handlers _sequentially_. This may be slower, but it gives us
  // a lighter cognitive load and more obvious logs.
  async.series(hooks, function(error) {
    if (error) {
      this.emit('log:debug', 'hook done:', name, 'with error:', error);
    } else {
      this.emit('log:debug', 'hook done:', name);
    }
    done(error);
  }.bind(this));

  return this;
};

/**
 * @param {function(*, Array<!Plugin>)} done Asynchronously loads the plugins
 *     requested by `options.plugins`.
 */
Context.prototype.plugins = function plugins(done) {
  async.map(this.enabledPlugins(), Plugin.get, done);
};

/**
 * @return {!Array<string>} The names of enabled plugins.
 */
Context.prototype.enabledPlugins = function enabledPlugins() {
  // Plugins with falsy configuration or disabled: true are _not_ loaded.
  var pairs = _.reject(_.toPairs(this.options.plugins), function(p) { return !p[1] || p[1].disabled });
  return _.map(pairs, function(p) { return p[0] });
};

/**
 * @param {string} name
 * @return {!Object}
 */
Context.prototype.pluginOptions = function pluginOptions(name) {
  return this.options.plugins[Plugin.shortName(name)];
};

module.exports = Context;


text:
module Topologies
  #
  # Given a topology
  # Returns the edge nodes of that topology.
  #
  class EdgeNodesFinder
    def initialize(topology)
      @topology = topology
    end

    def find_edge_nodes
      all_topology_nodes.select do |n|
        n.edges(:out).empty?
      end
    end

    private

    def all_topology_nodes
      Network::Builders::Electricity.build(@topology).nodes
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
package com.hoho.android.usbserial.driver;

import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;

import java.io.IOException;

/**
 * Driver interface for a supported USB serial device.
 *
 * @author mike wakerly (opensource@hoho.com)
 */
public abstract class UsbSerialDriver {

    public static final int DEFAULT_READ_BUFFER_SIZE = 16 * 1024;
    public static final int DEFAULT_WRITE_BUFFER_SIZE = 16 * 1024;

    protected final UsbDevice mDevice;
    protected final UsbDeviceConnection mConnection;

    protected final Object mReadBufferLock = new Object();
    protected final Object mWriteBufferLock = new Object();

    /** Internal read buffer.  Guarded by {@link #mReadBufferLock}. */
    protected byte[] mReadBuffer;

    /** Internal write buffer.  Guarded by {@link #mWriteBufferLock}. */
    protected byte[] mWriteBuffer;

    public static final int DATABITS_5 = 5;
    public static final int DATABITS_6 = 6;
    public static final int DATABITS_7 = 7;
    public static final int DATABITS_8 = 8;

    public static final int FLOWCONTROL_NONE = 0;
    public static final int FLOWCONTROL_RTSCTS_IN = 1;
    public static final int FLOWCONTROL_RTSCTS_OUT = 2;
    public static final int FLOWCONTROL_XONXOFF_IN = 4;
    public static final int FLOWCONTROL_XONXOFF_OUT = 8;

    public static final int PARITY_EVEN = 2;
    public static final int PARITY_MARK = 3;
    public static final int PARITY_NONE = 0;
    public static final int PARITY_ODD = 1;
    public static final int PARITY_SPACE = 4;

    /** 1 stop bit. */
    public static final int STOPBITS_1 = 1;
    /** 1.5 stop bits. */
    public static final int STOPBITS_1_5 = 3;
    /** 2 stop bits. */
    public static final int STOPBITS_2 = 2;

    public UsbSerialDriver(UsbDevice device, UsbDeviceConnection connection) {
        mDevice = device;
        mConnection = connection;

        mReadBuffer = new byte[DEFAULT_READ_BUFFER_SIZE];
        mWriteBuffer = new byte[DEFAULT_WRITE_BUFFER_SIZE];
    }

    /**
     * Opens and initializes the device as a USB serial device. Upon success,
     * caller must ensure that {@link #close()} is eventually called.
     *
     * @throws IOException on error opening or initializing the device.
     */
    public abstract void open() throws IOException;

    /**
     * Closes the serial device.
     *
     * @throws IOException on error closing the device.
     */
    public abstract void close() throws IOException;

    /**
     * Reads as many bytes as possible into the destination buffer.
     *
     * @param dest the destination byte buffer
     * @param timeoutMillis the timeout for reading
     * @return the actual number of bytes read
     * @throws IOException if an error occurred during reading
     */
    public abstract int read(final byte[] dest, final int timeoutMillis) throws IOException;

    /**
     * Writes as many bytes as possible from the source buffer.
     *
     * @param src the source byte buffer
     * @param timeoutMillis the timeout for writing
     * @return the actual number of bytes written
     * @throws IOException if an error occurred during writing
     */
    public abstract int write(final byte[] src, final int timeoutMillis) throws IOException;

    /**
     * Sets the baud rate of the serial device.
     *
     * @param baudRate the desired baud rate, in bits per second
     * @return the actual rate set
     * @throws IOException on error setting the baud rate
     * @deprecated Use {@link #setParameters(int, int, int, int)} instead of this method.
     */
    @Deprecated
    public abstract int setBaudRate(final int baudRate) throws IOException;

    /**
     * Sets various serial port parameters.
     *
     * @param baudRate baud rate as an integer, for example {@code 115200}.
     * @param dataBits one of {@link #DATABITS_5}, {@link #DATABITS_6},
     *            {@link #DATABITS_7}, or {@link #DATABITS_8}.
     * @param stopBits one of {@link #STOPBITS_1}, {@link #STOPBITS_1_5}, or
     *            {@link #STOPBITS_2}.
     * @param parity one of {@link #PARITY_NONE}, {@link #PARITY_ODD},
     *            {@link #PARITY_EVEN}, {@link #PARITY_MARK}, or
     *            {@link #PARITY_SPACE}.
     * @throws IOException on error setting the port parameters
     */
    public abstract void setParameters(
            int baudRate, int dataBits, int stopBits, int parity) throws IOException;

    /**
     * Gets the CD (Carrier Detect) bit from the underlying UART.
     *
     * @return the current state, or {@code false} if not supported.
     * @throws IOException if an error occurred during reading
     */
    public abstract boolean getCD() throws IOException;

    /**
     * Gets the CTS (Clear To Send) bit from the underlying UART.
     *
     * @return the current state, or {@code false} if not supported.
     * @throws IOException if an error occurred during reading
     */
    public abstract boolean getCTS() throws IOException;

    /**
     * Gets the DSR (Data Set Ready) bit from the underlying UART.
     *
     * @return the current state, or {@code false} if not supported.
     * @throws IOException if an error occurred during reading
     */
    public abstract boolean getDSR() throws IOException;

    /**
     * Gets the DTR (Data Terminal Ready) bit from the underlying UART.
     *
     * @return the current state, or {@code false} if not supported.
     * @throws IOException if an error occurred during reading
     */
    public abstract boolean getDTR() throws IOException;

    /**
     * Sets the DTR (Data Terminal Ready) bit on the underlying UART, if
     * supported.
     *
     * @param value the value to set
     * @throws IOException if an error occurred during writing
     */
    public abstract void setDTR(boolean value) throws IOException;

    /**
     * Gets the RI (Ring Indicator) bit from the underlying UART.
     *
     * @return the current state, or {@code false} if not supported.
     * @throws IOException if an error occurred during reading
     */
    public abstract boolean getRI() throws IOException;

    /**
     * Gets the RTS (Request To Send) bit from the underlying UART.
     *
     * @return the current state, or {@code false} if not supported.
     * @throws IOException if an error occurred during reading
     */
    public abstract boolean getRTS() throws IOException;

    /**
     * Sets the RTS (Request To Send) bit on the underlying UART, if
     * supported.
     *
     * @param value the value to set
     * @throws IOException if an error occurred during writing
     */
    public abstract void setRTS(boolean value) throws IOException;

    /**
     * Returns the currently-bound USB device.
     *
     * @return the device
     */
    public final UsbDevice getDevice() {
        return mDevice;
    }

    /**
     * Sets the size of the internal buffer used to exchange data with the USB
     * stack for read operations.  Most users should not need to change this.
     *
     * @param bufferSize the size in bytes
     */
    public final void setReadBufferSize(int bufferSize) {
        synchronized (mReadBufferLock) {
            if (bufferSize == mReadBuffer.length) {
                return;
            }
            mReadBuffer = new byte[bufferSize];
        }
    }

    /**
     * Sets the size of the internal buffer used to exchange data with the USB
     * stack for write operations.  Most users should not need to change this.
     *
     * @param bufferSize the size in bytes
     */
    public final void setWriteBufferSize(int bufferSize) {
        synchronized (mWriteBufferLock) {
            if (bufferSize == mWriteBuffer.length) {
                return;
            }
            mWriteBuffer = new byte[bufferSize];
        }
    }

}


text:
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Adding M2M table for field db_liteattributes on 'ScriptDB'
        m2m_table_name = db.shorten_name(u'scripts_scriptdb_db_liteattributes')
        db.create_table(m2m_table_name, (
            ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
            ('scriptdb', models.ForeignKey(orm[u'scripts.scriptdb'], null=False)),
            ('liteattribute', models.ForeignKey(orm[u'typeclasses.liteattribute'], null=False))
        ))
        db.create_unique(m2m_table_name, ['scriptdb_id', 'liteattribute_id'])

        # Adding M2M table for field db_tags on 'ScriptDB'
        m2m_table_name = db.shorten_name(u'scripts_scriptdb_db_tags')
        db.create_table(m2m_table_name, (
            ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
            ('scriptdb', models.ForeignKey(orm[u'scripts.scriptdb'], null=False)),
            ('tag', models.ForeignKey(orm[u'typeclasses.tag'], null=False))
        ))
        db.create_unique(m2m_table_name, ['scriptdb_id', 'tag_id'])

    def backwards(self, orm):
        # Removing M2M table for field db_liteattributes on 'ScriptDB'
        db.delete_table(db.shorten_name(u'scripts_scriptdb_db_liteattributes'))

        # Removing M2M table for field db_tags on 'ScriptDB'
        db.delete_table(db.shorten_name(u'scripts_scriptdb_db_tags'))

    models = {
        u'auth.group': {
            'Meta': {'object_name': 'Group'},
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
            'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
        },
        u'auth.permission': {
            'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
            'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
        },
        u'contenttypes.contenttype': {
            'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
        },
        u'objects.objectdb': {
            'Meta': {'object_name': 'ObjectDB'},
            'db_attributes': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['typeclasses.Attribute']", 'null': 'True', 'symmetrical': 'False'}),
            'db_cmdset_storage': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
            'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            'db_destination': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'destinations_set'", 'null': 'True', 'to': u"orm['objects.ObjectDB']"}),
            'db_home': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'homes_set'", 'null': 'True', 'to': u"orm['objects.ObjectDB']"}),
            'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}),
            'db_liteattributes': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['typeclasses.LiteAttribute']", 'null': 'True', 'symmetrical': 'False'}),
            'db_location': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'locations_set'", 'null': 'True', 'to': u"orm['objects.ObjectDB']"}),
            'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
            'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
            'db_player': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['players.PlayerDB']", 'null': 'True', 'blank': 'True'}),
            'db_sessid': ('django.db.models.fields.IntegerField', [], {'null': 'True'}),
            'db_tags': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['typeclasses.Tag']", 'null': 'True', 'symmetrical': 'False'}),
            'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
        },
        u'players.playerdb': {
            'Meta': {'object_name': 'PlayerDB'},
            'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'db_attributes': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['typeclasses.Attribute']", 'null': 'True', 'symmetrical': 'False'}),
            'db_cmdset_storage': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}),
            'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            'db_is_connected': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}),
            'db_liteattributes': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['typeclasses.LiteAttribute']", 'null': 'True', 'symmetrical': 'False'}),
            'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
            'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
            'db_tags': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['typeclasses.Tag']", 'null': 'True', 'symmetrical': 'False'}),
            'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}),
            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
            'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
        },
        u'scripts.scriptdb': {
            'Meta': {'object_name': 'ScriptDB'},
            'db_attributes': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['typeclasses.Attribute']", 'null': 'True', 'symmetrical': 'False'}),
            'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            'db_desc': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
            'db_interval': ('django.db.models.fields.IntegerField', [], {'default': '-1'}),
            'db_is_active': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}),
            'db_liteattributes': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['typeclasses.LiteAttribute']", 'null': 'True', 'symmetrical': 'False'}),
            'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
            'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['objects.ObjectDB']", 'null': 'True', 'blank': 'True'}),
            'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
            'db_persistent': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'db_repeats': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
            'db_start_delay': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'db_tags': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['typeclasses.Tag']", 'null': 'True', 'symmetrical': 'False'}),
            'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
        },
        u'typeclasses.attribute': {
            'Meta': {'object_name': 'Attribute'},
            'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}),
            'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
            'db_value': ('src.utils.picklefield.PickledObjectField', [], {'null': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
        },
        u'typeclasses.liteattribute': {
            'Meta': {'object_name': 'LiteAttribute', 'index_together': "(('db_key', 'db_category'),)"},
            'db_category': ('django.db.models.fields.CharField', [], {'max_length': '64', 'null': 'True', 'blank': 'True'}),
            'db_data': ('django.db.models.fields.TextField', [], {}),
            'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
        },
        u'typeclasses.tag': {
            'Meta': {'unique_together': "(('db_key', 'db_category'),)", 'object_name': 'Tag', 'index_together': "(('db_key', 'db_category'),)"},
            'db_category': ('django.db.models.fields.CharField', [], {'max_length': '64', 'null': 'True'}),
            'db_data': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
            'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
        }
    }

    complete_apps = ['scripts']


text:
    <title th:inline="text">Edit · [[${post.title}]]</title>

          Admin : Blog : Edit Post

      <form layout:include="admin/blog/_post_form :: post-form" th:with="edit=1" th:action="@{'/admin/blog/' + ${post.id} + '/edit'}" method="post" th:object="${postForm}">
      </form>


text:
/**
 * Automatically generated file. DO NOT MODIFY
 */
package com.airbnb.android.react.lottie;

public final class BuildConfig {
  public static final boolean DEBUG = false;
  public static final String APPLICATION_ID = "com.airbnb.android.react.lottie";
  public static final String BUILD_TYPE = "release";
  public static final String FLAVOR = "";
  public static final int VERSION_CODE = -1;
  public static final String VERSION_NAME = "";
}


text:
package io.fabric8.kubernetes.client.mock;

import io.fabric8.kubernetes.api.model.apps.Deployment;
import io.fabric8.kubernetes.api.model.apps.DeploymentBuilder;
import io.fabric8.kubernetes.api.model.apps.DeploymentList;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.server.mock.KubernetesServer;
import org.junit.Rule;
import org.junit.Test;

import java.util.Collections;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

public class DeploymentCrudTest {
  @Rule
  public KubernetesServer server = new KubernetesServer(true, true);

  @Test
  public void testCrud() {
    KubernetesClient client = server.getClient();

    Deployment deployment1 = new DeploymentBuilder().withNewMetadata()
      .withName("deployment1")
      .withNamespace("ns1")
      .addToLabels("testKey", "testValue")
      .endMetadata()
      .withNewSpec()
      .endSpec()
      .build();

    Deployment deployment2 = new DeploymentBuilder().withNewMetadata()
      .withName("deployment2")
      .withNamespace("ns1")
      .addToLabels("testKey", "testValue")
      .endMetadata()
      .withNewSpec()
      .endSpec()
      .build();

    Deployment deployment3 = new DeploymentBuilder().withNewMetadata()
      .withName("deployment3")
      .addToLabels("testKey", "testValue")
      .withNamespace("ns2")
      .endMetadata()
      .withNewSpec()
      .endSpec()
      .build();

    client.apps().deployments().inNamespace("ns1").create(deployment1);
    client.apps().deployments().inNamespace("ns1").create(deployment2);
    client.apps().deployments().inNamespace("ns2").create(deployment3);

    DeploymentList aDeploymentList = client.apps().deployments().inAnyNamespace().list();
    assertNotNull(aDeploymentList);
    assertEquals(3, aDeploymentList.getItems().size());

    aDeploymentList = client.apps().deployments().inNamespace("ns1").list();
    assertNotNull(aDeploymentList);
    assertEquals(2, aDeploymentList.getItems().size());

    aDeploymentList = client.apps()
      .deployments()
      .inAnyNamespace()
      .withLabels(Collections.singletonMap("testKey", "testValue"))
      .list();
    assertNotNull(aDeploymentList);
    assertEquals(3, aDeploymentList.getItems().size());

    boolean bDeleted = client.apps().deployments().inNamespace("ns2").withName("deployment3").delete();
    assertTrue(bDeleted);

    deployment2 = client.apps().deployments()
      .inNamespace("ns1").withName("deployment2").edit()
      .editMetadata().addToLabels("key1", "value1").endMetadata().done();
    assertNotNull(deployment2);
    assertEquals("value1", deployment2.getMetadata().getLabels().get("key1"));
  }
}


text:
package org.vitanov.essentials.entitites;

import javax.persistence.*;

@Entity
@Table(name = "users")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    private String username;

    private String password;

    private String email;

    public User() {
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}


text:
    <md-button class="close md-fab md-mini md-hue-1" type="button" aria-label="Close" ng-click="create.showMap(false)" md-theme="grey">
        <md-icon md-svg-icon="material-set:clear"></md-icon>
    </md-button>

        Current location:{{create.currentGeo}}
        <md-button class="md-raised" aria-label="Search Address" ng-click="create.changeGeoloc(create.searchGeo)" ng-if="create.searchGeo">
            <md-icon md-svg-icon="material-set:search"></md-icon>search
        </md-button>
        <md-button class="md-raised" aria-label="Facebook Address" ng-click="create.changeGeoloc(create.fbGeo)" ng-if="create.fbGeo">
            <md-icon md-svg-icon="material-set:facebook"></md-icon>facebook
        </md-button>
        <md-button class="md-raised" aria-label="Device Address" ng-click="create.changeGeoloc(create.deviceGeo)" ng-if="create.deviceGeo">
            <md-icon md-svg-icon="material-set:smartphone"></md-icon>device
        </md-button>
        <md-button class="md-raised" aria-label="Saved Address" ng-click="create.changeGeoloc(create.dbaseGeo)" ng-if="create.dbaseGeo">
            <md-icon md-svg-icon="material-set:facebook"></md-icon>saved
        </md-button>


text:
HOST=127.0.0.1
TEST_PATH=./

all:

test: unittest

unittest:
	python -m unittest discover --pattern="*_test.py" -v

pytest:
	pytest --showlocals --durations=1 --pyargs

version:
	python -c "import miniflow; print(miniflow)"

smoke: version
	./tests/smoke_tests.py


text:
package com.danikula.android.garden.ui.list;

import android.content.Context;
import android.database.Cursor;
import android.widget.ResourceCursorAdapter;
import android.view.View;
import android.view.ViewGroup;

public abstract class ViewHolderResourceCursorAdapter extends ResourceCursorAdapter {

    private int[] managedViewIds;

    public ViewHolderResourceCursorAdapter(Context context, int layout, Cursor c, int... managedViewIds) {
        super(context, layout, c, false);
        this.managedViewIds = managedViewIds;
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        View newView = super.newView(context, cursor, parent);
        newView.setTag(new ViewHolder(newView, managedViewIds));
        return newView;
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        ViewHolder viewHolder = (ViewHolder) view.getTag();
        bindView(viewHolder, context, cursor);
    }

    public abstract void bindView(ViewHolder viewHolder, Context context, Cursor cursor);
}


text:
"""
Post-nanoemoji processing of the Noto COLRv1 Emoji files.

Adds additional sequences to properly support Safari, corrects 'name', etc.

For now substantially based on copying from a correct bitmap build.
"""
from absl import app
import functools
from fontTools.feaLib.builder import addOpenTypeFeaturesFromString
from fontTools import ttLib
from fontTools.ttLib.tables import _g_l_y_f as glyf
from fontTools.ttLib.tables import otTables as ot
import map_pua_emoji
from nototools import add_vs_cmap
from nototools import font_data
from nototools import unicode_data
from pathlib import Path

from colrv1_add_soft_light_to_flags import add_soft_light_to_flags

_CBDT_FILE = Path("fonts/NotoColorEmoji.ttf")
_COLR_FILES = {
    Path("fonts/Noto-COLRv1-noflags.ttf"),
    Path("fonts/Noto-COLRv1.ttf"),
}

def _is_colrv1(font):
    return "COLR" in font and font["COLR"].version == 1

def _is_cbdt(font):
    return "CBDT" in font

def _set_name(name_table, nameID):
    name_table.getName(value, nameID, 3, 1, 0x409)

def _set_name(name_table, nameID, value):
    name_table.setName(value, nameID, 3, 1, 0x409)

def _copy_names(colr_font, cbdt_font):
    colr_font["name"] = cbdt_font["name"]
    name_table = colr_font["name"]
    assert all(
        (n.platformID, n.platEncID, n.langID) == (3, 1, 0x409) for n in name_table.names
    ), "Should only have names Android uses"

    # Amendments
    _set_name(name_table, 10, "Color emoji font using COLRv1.")
    _set_name(name_table, 11, "https://github.com/googlefonts/noto-emoji")
    _set_name(name_table, 12, "https://github.com/googlefonts/noto-emoji")

# CBDT build step: @$(VS_ADDER) -vs 2640 2642 2695 --dstdir '.' -o "$@-with-pua-varsel" "$@-with-pua"
def _add_vs_cmap(colr_font):
    emoji_variants = unicode_data.get_unicode_emoji_variants() | {
        0x2640,
        0x2642,
        0x2695,
    }
    add_vs_cmap.modify_font("COLRv1 Emoji", colr_font, "emoji", emoji_variants)

def _is_variation_selector_cmap_table(table):
    assert table.format in {4, 12, 14}
    return table.format == 14

def _lookup_in_cmap(colr_font, codepoint):
    result = set()
    for table in colr_font["cmap"].tables:
        if _is_variation_selector_cmap_table(table):
            continue
        assert codepoint in table.cmap
        result.add(table.cmap[codepoint])
    assert len(result) == 1, f"Ambiguous mapping for {codepoint}: {result}"
    return next(iter(result))

def _add_cmap_entries(colr_font, codepoint, glyph_name):
    for table in colr_font["cmap"].tables:
        if _is_variation_selector_cmap_table(table):
            continue
        if not _is_bmp(codepoint) and table.format == 4:
            continue
        table.cmap[codepoint] = glyph_name
        #print(f"Map 0x{codepoint:04x} to {glyph_name}, format {table.format}")

FLAG_TAGS = set(range(0xE0030, 0xE0039 + 1)) | set(range(0xE0061, 0xE007A + 1))
CANCEL_TAG = 0xE007F

def _map_missing_flag_tag_chars_to_empty_glyphs(colr_font):
    # Add all tag characters used in flags + cancel tag
    tag_cps = FLAG_TAGS | {CANCEL_TAG}

    # Anything already cmap'd is fine
    tag_cps -= set(_Cmap(colr_font).keys())

    # CBDT maps these to blank glyphs
    glyf_table = colr_font["glyf"]
    hmtx_table = colr_font["hmtx"]
    glyph_order_size = len(glyf_table.glyphOrder)
    for cp in tag_cps:
        #print(f"Map 0x{cp:04x} to a blank glyf")
        glyph_name = f"u{cp:04X}"
        assert glyph_name not in glyf_table, f"{glyph_name} already in glyf"
        assert glyph_name not in hmtx_table.metrics, f"{glyph_name} already in hmtx"
        glyf_table[glyph_name] = glyf.Glyph()
        hmtx_table[glyph_name] = (0, 0)

        _add_cmap_entries(colr_font, cp, glyph_name)

def _is_bmp(cp):
    return cp in range(0x0000, 0xFFFF + 1)

def _ligaset_for_glyph(lookup_list, glyph_name):
    for lookup in lookup_list.Lookup:
        if lookup.LookupType != 4:
            continue
        for liga_set in lookup.SubTable:
            if glyph_name in liga_set.ligatures:
                return liga_set.ligatures[glyph_name]
    return None

def _Cmap(ttfont):
    def _Reducer(acc, u):
        acc.update(u)
        return acc

    unicode_cmaps = (t.cmap for t in ttfont["cmap"].tables if t.isUnicode())
    return functools.reduce(_Reducer, unicode_cmaps, {})

def _add_vertical_layout_tables(cbdt_font, colr_font):
    upem_scale = colr_font["head"].unitsPerEm / cbdt_font["head"].unitsPerEm

    vhea = colr_font["vhea"] = ttLib.newTable("vhea")
    vhea.tableVersion = 0x00010000
    vhea.ascent = round(cbdt_font["vhea"].ascent * upem_scale)
    vhea.descent = round(cbdt_font["vhea"].descent * upem_scale)
    vhea.lineGap = 0
    # most of the stuff below is recalculated by the compiler, but still needs to be
    # initialized... ¯\_(ツ)_/¯
    vhea.advanceHeightMax = 0
    vhea.minTopSideBearing = 0
    vhea.minBottomSideBearing = 0
    vhea.yMaxExtent = 0
    vhea.caretSlopeRise = 0
    vhea.caretSlopeRun = 0
    vhea.caretOffset = 0
    vhea.reserved0 = 0
    vhea.reserved1 = 0
    vhea.reserved2 = 0
    vhea.reserved3 = 0
    vhea.reserved4 = 0
    vhea.metricDataFormat = 0
    vhea.numberOfVMetrics = 0

    # emoji font is monospaced -- except for an odd uni0000 (NULL) glyph which happens
    # to have height=0; but colrv1 font doesn't have that anyway, so I just skip it
    cbdt_heights = set(h for h, _ in cbdt_font["vmtx"].metrics.values() if h != 0)
    assert len(cbdt_heights) == 1, "NotoColorEmoji CBDT font should be monospaced!"
    height = round(cbdt_heights.pop() * upem_scale)
    vmtx = colr_font["vmtx"] = ttLib.newTable("vmtx")
    vmtx.metrics = {}
    for gn in colr_font.getGlyphOrder():
        vmtx.metrics[gn] = height, 0

UNKNOWN_FLAG_PUA = 0xFE82B
BLACK_FLAG = 0x1F3F4
REGIONAL_INDICATORS = set(range(0x1F1E6, 0x1F1FF + 1))

def _add_fallback_subs_for_unknown_flags(colr_font):
    """Add GSUB lookups to replace unsupported flag sequences with the 'unknown flag'.

    In order to locate the unknown flag, the glyph must be mapped to 0xFE82B PUA code;
    the latter is removed from the cmap table after the GSUB has been updated.
    """
    cmap = _Cmap(colr_font)
    unknown_flag = cmap[UNKNOWN_FLAG_PUA]
    black_flag = cmap[BLACK_FLAG]
    cancel_tag = cmap[CANCEL_TAG]
    flag_tags = sorted(cmap[cp] for cp in FLAG_TAGS)
    # in the *-noflags.ttf font there are no region flags thus this list is empty
    regional_indicators = sorted(cmap[cp] for cp in REGIONAL_INDICATORS if cp in cmap)

    classes = f'@FLAG_TAGS = [{" ".join(flag_tags)}];\n'
    if regional_indicators:
        classes += f"""
            @REGIONAL_INDICATORS = [{" ".join(regional_indicators)}];
            @UNKNOWN_FLAG = [{" ".join([unknown_flag] * len(regional_indicators))}];
        """
    lookups = (
        # the first lookup is a dummy that stands for the emoji sequences ligatures
        # from the destination font; we only use it to ensure the lookup indices match.
        # We can't leave it empty otherwise feaLib optimizes it away.
        f"""
        lookup placeholder {{
            sub {unknown_flag} {unknown_flag} by {unknown_flag};
        }} placeholder;
        """
        + "\n".join(
            ["lookup delete_glyph {"]
            + [f"    sub {g} by NULL;" for g in sorted(regional_indicators + flag_tags)]
            + ["} delete_glyph;"]
        )
        + (
            """
            lookup replace_with_unknown_flag {
                sub @REGIONAL_INDICATORS by @UNKNOWN_FLAG;
            } replace_with_unknown_flag;
            """
            if regional_indicators
            else "\n"
        )
    )
    features = (
        "languagesystem DFLT dflt;\n"
        + classes
        + lookups
        + "feature ccmp {"
        + f"""
            lookup placeholder;
            sub {black_flag} @FLAG_TAGS' lookup delete_glyph;
            sub {black_flag} {cancel_tag} by {unknown_flag};
        """
        + (
            """
            sub @REGIONAL_INDICATORS' lookup replace_with_unknown_flag
                @REGIONAL_INDICATORS' lookup delete_glyph;
            """
            if regional_indicators
            else ""
        )
        + "} ccmp;"
    )
    # feaLib always builds a new GSUB table (can't update one in place) so we have to
    # use an empty TTFont and then update our GSUB with the newly built lookups
    temp_font = ttLib.TTFont()
    temp_font.setGlyphOrder(colr_font.getGlyphOrder())

    addOpenTypeFeaturesFromString(temp_font, features)

    temp_gsub = temp_font["GSUB"].table
    # sanity check
    assert len(temp_gsub.FeatureList.FeatureRecord) == 1
    assert temp_gsub.FeatureList.FeatureRecord[0].FeatureTag == "ccmp"
    temp_ccmp = temp_gsub.FeatureList.FeatureRecord[0].Feature

    colr_gsub = colr_font["GSUB"].table
    ccmps = [
        r.Feature for r in colr_gsub.FeatureList.FeatureRecord if r.FeatureTag == "ccmp"
    ]
    assert len(ccmps) == 1, f"expected only 1 'ccmp' feature record, found {len(ccmps)}"
    colr_ccmp = ccmps[0]

    colr_lookups = colr_gsub.LookupList.Lookup
    assert (
        len(colr_lookups) == 1
    ), f"expected only 1 lookup in COLRv1's GSUB.LookupList, found {len(colr_lookups)}"
    assert (
        colr_lookups[0].LookupType == 4
    ), f"expected Lookup[0] of type 4 in COLRv1, found {colr_lookups[0].LookupType}"

    colr_lookups.extend(temp_gsub.LookupList.Lookup[1:])
    colr_gsub.LookupList.LookupCount = len(colr_lookups)
    colr_ccmp.LookupListIndex = temp_ccmp.LookupListIndex
    colr_ccmp.LookupCount = len(colr_ccmp.LookupListIndex)

    # get rid of the Unknown Flag private codepoint as no longer needed
    font_data.delete_from_cmap(colr_font, [UNKNOWN_FLAG_PUA])

def _font(path, check_fn, check_fail_str):
    assert path.is_file(), path
    font = ttLib.TTFont(path)
    if not check_fn(font):
        raise ValueError(path + check_fail_str)
    return font

def main(_):
    cbdt_font = _font(_CBDT_FILE, _is_cbdt, " must be a CBDT font")

    for colr_file in _COLR_FILES:
        colr_font = _font(colr_file, _is_colrv1, " must be a COLRv1 font")

        print(f"Updating {colr_file} from {_CBDT_FILE}")

        _copy_names(colr_font, cbdt_font)

        # CBDT build step: @$(PYTHON) $(PUA_ADDER) "$@" "$@-with-pua"
        map_pua_emoji.add_pua_cmap_to_font(colr_font)

        _add_vs_cmap(colr_font)

        _map_missing_flag_tag_chars_to_empty_glyphs(colr_font)

        add_soft_light_to_flags(colr_font)

        _add_vertical_layout_tables(cbdt_font, colr_font)

        _add_fallback_subs_for_unknown_flags(colr_font)

        print("Writing", colr_file)
        colr_font.save(colr_file)

if __name__ == "__main__":
    app.run(main)


text:
<title>Document Error: Data follows</title>

Access Error: Data follows

Form formZone3_Zone3XmlStatus.xml is not defined


text:
package org.chocosolver.solver.constraints.nary.cumulative;

import gnu.trove.map.hash.THashMap;
import org.chocosolver.memory.IStateInt;
import org.chocosolver.solver.Solver;
import org.chocosolver.solver.constraints.Propagator;
import org.chocosolver.solver.constraints.PropagatorPriority;
import org.chocosolver.solver.exception.ContradictionException;
import org.chocosolver.solver.variables.IntVar;
import org.chocosolver.solver.variables.events.IntEventType;
import org.chocosolver.solver.variables.events.PropagatorEventType;
import org.chocosolver.util.ESat;
import org.chocosolver.util.objects.setDataStructures.ISet;
import org.chocosolver.util.objects.setDataStructures.SetFactory;
import org.chocosolver.util.tools.ArrayUtils;

import java.util.Arrays;

/**
 * Cumulative propagator
 * Performs energy checking and mandatory part based filtering
 * BEWARE : not idempotent, use two propagators to get the fix point
 *
 * @author Jean-Guillaume Fages
 * @since 31/01/13
 */
public class PropFullCumulative extends Propagator<IntVar> {

    //***********************************************************************************
    // VARIABLES
    //***********************************************************************************

    protected final int n;
    protected final IntVar[] s, d, e, h;
    protected final IntVar capa;
    protected CumulFilter[] filters;
    protected ISet allTasks;
    protected final boolean fast;
    protected final int awakeningMask;
    protected final IStateInt lastCapaMax;
    protected final Cumulative.Filter[] _filters;

    //***********************************************************************************
    // CONSTRUCTORS
    //***********************************************************************************

    /**
     * protected constructor, should not be called by a user
     */
    protected PropFullCumulative(IntVar[] s, IntVar[] d, IntVar[] e, IntVar[] h, IntVar capa,
                                 boolean reactToFineEvt, boolean fast, Cumulative.Filter... filters) {
        super(ArrayUtils.append(s, d, e, h, new IntVar[]{capa}), PropagatorPriority.QUADRATIC, reactToFineEvt);
        this.n = s.length;
        if (!(n == d.length && n == e.length && n == h.length)) {
            throw new UnsupportedOperationException();
        }
        this.fast = fast;
        this.s = Arrays.copyOfRange(vars, 0, n);
        this.d = Arrays.copyOfRange(vars, n, n * 2);
        this.e = Arrays.copyOfRange(vars, n * 2, n * 3);
        this.h = Arrays.copyOfRange(vars, n * 3, n * 4);
        this.capa = this.vars[4 * n];
        this.filters = new CumulFilter[filters.length];
        _filters = filters;
        for (int f = 0; f < filters.length; f++) {
            this.filters[f] = filters[f].make(n, this);
        }
        // awakes on instantiations only when FAST mode is set to true
        awakeningMask = fast ? IntEventType.instantiation() : IntEventType.boundAndInst();
        lastCapaMax = solver.getEnvironment().makeInt(capa.getUB() + 1);
        allTasks = SetFactory.makeFullSet(n);
    }

    /**
     * Classical cumulative propagator
     *
     * @param s       start 		variables
     * @param d       duration	variables
     * @param e       end			variables
     * @param h       height		variables
     * @param capa    capacity	variable
     * @param fast    optimization parameter: reduces the amount of filtering calls when set to true
     *                (only reacts to instantiation events)
     * @param filters filtering algorithm to use
     */
    public PropFullCumulative(IntVar[] s, IntVar[] d, IntVar[] e, IntVar[] h, IntVar capa,
                              boolean fast, Cumulative.Filter... filters) {
        this(s, d, e, h, capa, false, fast, filters);
    }

    //***********************************************************************************
    // METHODS
    //***********************************************************************************

    @Override
    public int getPropagationConditions(int idx) {
        if (idx >= 4 * n) {
            return IntEventType.DECUPP.getMask() + IntEventType.INSTANTIATE.getMask();
        }
        return awakeningMask;
    }

    @Override
    public void propagate(int evtmask) throws ContradictionException {
        if (PropagatorEventType.isFullPropagation(evtmask)) {
            propIni();
        }
        updateMaxCapa();
        filter(allTasks);
    }

    @Override
    public void propagate(int varIdx, int mask) throws ContradictionException {
        forcePropagate(PropagatorEventType.CUSTOM_PROPAGATION);
    }

    protected void propIni() throws ContradictionException {
        for (int i = 0; i < n; i++) {
            d[i].updateLowerBound(0, aCause); // should even be 1
            h[i].updateLowerBound(0, aCause);
            s[i].updateLowerBound(e[i].getLB() - d[i].getUB(), aCause);
            s[i].updateUpperBound(e[i].getUB() - d[i].getLB(), aCause);
            e[i].updateUpperBound(s[i].getUB() + d[i].getUB(), aCause);
            e[i].updateLowerBound(s[i].getLB() + d[i].getLB(), aCause);
            d[i].updateUpperBound(e[i].getUB() - s[i].getLB(), aCause);
            d[i].updateLowerBound(e[i].getLB() - s[i].getUB(), aCause);
        }
    }

    protected void updateMaxCapa() throws ContradictionException {
        if (lastCapaMax.get() != capa.getUB()) {
            int capaMax = capa.getUB();
            lastCapaMax.set(capaMax);
            for (int i = 0; i < n; i++) {
                h[i].updateUpperBound(capaMax, aCause);
            }
        }
    }

    public void filter(ISet tasks) throws ContradictionException {
        for (CumulFilter cf : filters) {
            cf.filter(s, d, e, h, capa, tasks);
        }
    }

    @Override
    public ESat isEntailed() {
        int min = s[0].getUB();
        int max = e[0].getLB();
        // check start + duration = end
        for (int i = 0; i < n; i++) {
            min = Math.min(min, s[i].getUB());
            max = Math.max(max, e[i].getLB());
            if (s[i].getLB() + d[i].getLB() > e[i].getUB()
                    || s[i].getUB() + d[i].getUB() < e[i].getLB()) {
                return ESat.FALSE;
            }
        }
        // check capacity
        int maxLoad = 0;
        if (min <= max) {
            int capamax = capa.getUB();
            int[] consoMin = new int[max - min];
            for (int i = 0; i < n; i++) {
                for (int t = s[i].getUB(); t < e[i].getLB(); t++) {
                    consoMin[t - min] += h[i].getLB();
                    if (consoMin[t - min] > capamax) {
                        return ESat.FALSE;
                    }
                    maxLoad = Math.max(maxLoad, consoMin[t - min]);
                }
            }
        }
        // check variables are instantiated
        for (int i = 0; i < vars.length - 1; i++) {
            if (!vars[i].isInstantiated()) {
                return ESat.UNDEFINED;
            }
        }
        assert min <= max;
        // capacity check entailed
        if (maxLoad <= vars[4 * n].getLB()) {
            return ESat.TRUE;
        }
        // capacity not instantiated
        return ESat.UNDEFINED;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder(this.getClass().getSimpleName() + "(");
        for (int i = 0; i < n; i++) {
            sb.append("[").append(vars[i].toString());
            sb.append(",").append(vars[i + n].toString());
            sb.append(",").append(vars[i + 2 * n].toString());
            sb.append(",").append(vars[i + 3 * n].toString()).append("],");
        }
        sb.append(vars[4 * n].toString()).append(")");
        return sb.toString();
    }

    @Override
    public void duplicate(Solver solver, THashMap<Object, Object> identitymap) {
        if (!identitymap.containsKey(this)) {
            // IntVar[] s, IntVar[] d, IntVar[] e, IntVar[] h, IntVar capa,
            // boolean fast, Cumulative.Filter... filters

            IntVar[] sVars = new IntVar[n];
            IntVar[] dVars = new IntVar[n];
            IntVar[] eVars = new IntVar[n];
            IntVar[] hVars = new IntVar[n];
            for (int i = 0; i < this.n; i++) {
                this.s[i].duplicate(solver, identitymap);
                sVars[i] = (IntVar) identitymap.get(this.s[i]);
                this.d[i].duplicate(solver, identitymap);
                dVars[i] = (IntVar) identitymap.get(this.d[i]);
                this.e[i].duplicate(solver, identitymap);
                eVars[i] = (IntVar) identitymap.get(this.e[i]);
                this.h[i].duplicate(solver, identitymap);
                hVars[i] = (IntVar) identitymap.get(this.h[i]);
            }
            this.capa.duplicate(solver, identitymap);
            IntVar cVar = (IntVar) identitymap.get(this.capa);
            identitymap.put(this, new PropFullCumulative(sVars, dVars, eVars, hVars, cVar, fast, _filters.clone()));
        }
    }
}


text:
package net.fortytwo.ripple.libs.data;

import net.fortytwo.flow.Sink;
import net.fortytwo.ripple.RippleException;
import net.fortytwo.ripple.libs.system.SystemLibrary;
import net.fortytwo.ripple.model.ModelConnection;
import net.fortytwo.ripple.model.PrimitiveStackMapping;
import net.fortytwo.ripple.model.RippleList;

import java.util.Date;

/**
 * A primitive which produces the current time, in seconds since midnight UTC of
 * January 1, 1970.
 *
 * @author Joshua Shinavier (http://fortytwo.net)
 */
public class ToMillis extends PrimitiveStackMapping {
    public String[] getIdentifiers() {
        return new String[]{
                DataLibrary.NS_2013_03 + "to-millis",
                SystemLibrary.NS_2008_08 + "dateTimeToMillis",
        };
    }

    public Parameter[] getParameters() {
        return new Parameter[]{
                new Parameter("dateTime", null, true)};
    }

    public String getComment() {
        return "converts an xsd:dateTime value to milliseconds since the Unix epoch";
    }

    public ToMillis() {
        super();
    }

    public void apply(final RippleList arg,
                      final Sink<RippleList> solutions,
                      final ModelConnection mc) throws RippleException {

        RippleList stack = arg;
        Date d = mc.toDate(stack.getFirst());
        stack = stack.getRest();

        solutions.accept(stack.push(
                d.getTime()));
    }
}


text:
external help file:
schema: 2.0.0
---

# New-Function
## SYNOPSIS
Create a new function, with comment based help.

## SYNTAX

```
New-Function [-Verb] <String> [-Noun] <String> [-Author] <String> [[-Version] <Version>]
 [[-FunctionParam] <Array>] [[-Link] <Array>] [-License] <String> [-LicenseToFile] [-PassThru] [-Force]
 [[-Path] <Object>]
```

## DESCRIPTION
Create a new function, including checking approved verbs, comment based help \(with license, author information, change log, links\), parameters, and the capability to include a separate file that includes the license.

## EXAMPLES

### -------------------------- EXAMPLE 1 --------------------------

	PS> new-function -verb notAVerb -noun doesntMatter...
	new-function : Cannot validate argument on parameter 'verb'.
	'notAVerb' did not match the expected set of approved verbs.

Description
-----------
Validation occurs at parameter ingestion, for the 'verb' parameter.
Parameter must be found with 'get-verb -verb $_'.

### -------------------------- EXAMPLE 2 --------------------------

	PS > $newFunctionParams = @{
	verb = "test"
	noun = "grammar"
	author = "Raoul Breton"
	functionParam = @("Being","Understanding","Signifying")
	license = "MIT"
	licenseToFile = $true
	}

	PS > new-function @newFunctionParams

Description
-----------
Creates a new .PS1 file named 'test-grammar.ps1', containing a function named 'test-grammar' with parameters 'being','understanding','signifying', and also creates a new 'license.txt' file with the selected license as contents.

## PARAMETERS

### -Verb
Specifies the verb to use for the function name, in the verb-noun convention.
Verb must be found in the approved list of verbs - 'get-verb' will output this list.

```yaml
Type: String
Parameter Sets: (All)
Aliases:

Required: True
Position: 1
Default value:
Accept pipeline input: False
Accept wildcard characters: False
```

### -Noun
Specifies the noun to use for the function name, in the verb-noun convention.
Currently there is not checking to validate singular form is used ('computer' instead of 'computers'), although this is checked by PSScriptAnalyzer.

```yaml
Type: String
Parameter Sets: (All)
Aliases:

Required: True
Position: 2
Default value:
Accept pipeline input: False
Accept wildcard characters: False
```

### -Author
Specifies the name of the author writing the function.

```yaml
Type: String
Parameter Sets: (All)
Aliases:

Required: True
Position: 3
Default value:
Accept pipeline input: False
Accept wildcard characters: False
```

### -Version
Specifies the version of the function to begin from.

```yaml
Type: Version
Parameter Sets: (All)
Aliases:

Required: False
Position: 4
Default value: 0.1.0
Accept pipeline input: False
Accept wildcard characters: False
```

### -FunctionParam
Specifies an array of string values to use as parameter names.

```yaml
Type: Array
Parameter Sets: (All)
Aliases:

Required: False
Position: 5
Default value:
Accept pipeline input: False
Accept wildcard characters: False
```

### -Link
Specifies an array of links that will be added to the comment based help.

```yaml
Type: Array
Parameter Sets: (All)
Aliases:

Required: False
Position: 6
Default value: @("http://example.com")
Accept pipeline input: False
Accept wildcard characters: False
```

### -License
Specifies the license to use, from the set of licenses available and formated in the 'LICENSE' directory.

```yaml
Type: String
Parameter Sets: (All)
Aliases:

Required: True
Position: 7
Default value: MIT
Accept pipeline input: False
Accept wildcard characters: False
```

### -LicenseToFile
Outputs the content of the license to a file in the same directory as the function.

```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:

Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```

### -PassThru
Returns the content of the newly created function.
By default, this cmdlet will not generate output to the console.

```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:

Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```

### -Force
By default, existing files with the same name will not be over written.
This forces the update.

```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:

Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```

### -Path
Specifies the location where the file\(s\) should be created.
Defaults to the present working directory.

```yaml
Type: Object
Parameter Sets: (All)
Aliases:

Required: False
Position: 8
Default value: $pwd
Accept pipeline input: False
Accept wildcard characters: False
```

## INPUTS

## OUTPUTS

## NOTES
The MIT License \(MIT\)
Copyright \(c\) 2016 Jim Schell

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

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

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

#### Name:       new-function
#### Author:     Jim Schell
#### Version:    0.1.6
#### License:    MIT

### Change Log

###### 2016-06-02::0.1.6
- updated how licenses are loaded, from within the function to reading psd1 files in a folder named 'LICENSE'.
New method includes license name \(full and short\) as well as the URI for the license.

###### 2016-06-02::0.1.5
- update out-file parameters to match intent on 'force' switch - updated to include 'noClobber' option \(default = true, force = false\)
- updated example where invalid verb used, error message has been improved with the 'throw' behavior
- updated formatting of notes section to simplify rendering of external help/ help as markdown \(hurrah for platyPS!\)

###### 2016-05-31::0.1.4
- update error handling of parameter validation for 'verb' parameter

###### 2016-05-31::0.1.3
- updated 'overWrite' to 'force'

###### 2016-05-27::0.1.2
- updated 'outToConsole' to 'passThru'

###### 2016-05-27::0.1.1
- after fighting with throw/ trap/ debug, realized that parameter names need to *match* in order to be processed \(as expected\).
Future-Self: Take notes.
Spell-check wouldn't be bad either.

###### 2016-05-27::0.1.0
- initial creation after months \(?years\) of having the idea

## RELATED LINKS

[Online Version:]()


text:
<?xml version="1.0" encoding="utf-8" ?>
<go-plugin id="script-executor" version="1">
    <about>
        <name>Script Executor</name>
        <version>1.0.1</version>
        <target-go-version>20.1.0</target-go-version>
        <description>
            Thoughtworks GoCD plugin to run scripts
        </description>
        <vendor>
            <name>Srinivas Upadhya</name>
            <url>https://github.com/srinivasupadhya</url>
        </vendor>
    </about>
</go-plugin>


text:
namespace System.Windows.Forms;

/// <summary>
/// Extension methods providing IObservable wrappers for the events on UserControl.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public static class ObservableUserControlEvents
{
    /// <summary>
    /// Returns an observable sequence wrapping the AutoSizeChanged event on the UserControl instance.
    /// </summary>
    /// <param name="instance">The UserControl instance to observe.</param>
    /// <returns>An observable sequence wrapping the AutoSizeChanged event on the UserControl instance.</returns>
    public static IObservable<EventPattern<EventArgs>> AutoSizeChangedObservable(this UserControl instance)
    {
        return Observable.FromEventPattern<EventHandler, EventArgs>(
            handler => instance.AutoSizeChanged += handler,
            handler => instance.AutoSizeChanged -= handler);
    }

    /// <summary>
    /// Returns an observable sequence wrapping the AutoValidateChanged event on the UserControl instance.
    /// </summary>
    /// <param name="instance">The UserControl instance to observe.</param>
    /// <returns>An observable sequence wrapping the AutoValidateChanged event on the UserControl instance.</returns>
    public static IObservable<EventPattern<EventArgs>> AutoValidateChangedObservable(this UserControl instance)
    {
        return Observable.FromEventPattern<EventHandler, EventArgs>(
            handler => instance.AutoValidateChanged += handler,
            handler => instance.AutoValidateChanged -= handler);
    }

    /// <summary>
    /// Returns an observable sequence wrapping the Load event on the UserControl instance.
    /// </summary>
    /// <param name="instance">The UserControl instance to observe.</param>
    /// <returns>An observable sequence wrapping the Load event on the UserControl instance.</returns>
    public static IObservable<EventPattern<EventArgs>> LoadObservable(this UserControl instance)
    {
        return Observable.FromEventPattern<EventHandler, EventArgs>(
            handler => instance.Load += handler,
            handler => instance.Load -= handler);
    }

    /// <summary>
    /// Returns an observable sequence wrapping the TextChanged event on the UserControl instance.
    /// </summary>
    /// <param name="instance">The UserControl instance to observe.</param>
    /// <returns>An observable sequence wrapping the TextChanged event on the UserControl instance.</returns>
    public static IObservable<EventPattern<EventArgs>> TextChangedObservable(this UserControl instance)
    {
        return Observable.FromEventPattern<EventHandler, EventArgs>(
            handler => instance.TextChanged += handler,
            handler => instance.TextChanged -= handler);
    }
}


text:
module.exports = function (app, utils, DB, url, script_dir) {

    // Utility to lookup and render the users page -- called from /users and /add_users
    var render_users = function (req, res) {
        DB.users.find(function (err, users) {
            if (err) return console.error(err);
            console.log(users);
            req.userlist = users;
            get_slicelet_data(req, res, function (req, res, error, slices) {
                if (error) {
                    utils.render_error_page(req, res, "Error in displaying users", error);
                } else {
                    var user_list = [];
                    var slice_dictionary = {}
                    slices.forEach(function(aSliceEntry) {
                        var userName = aSliceEntry.allocated;
                        slice_dictionary[userName] = aSliceEntry.name;
                    });

                    for (var index in req.userlist) {
                        var user = req.userlist[index];
                        user_list.push({
                            email: user['email'],
                            admin: user['admin'],
                            slice: slice_dictionary[user['email']]
                        });
                    }

                    res.render('admin_users', {
                        "userlist": user_list,
                        title: 'User List'
                    });
                }
            });
        });
    }

    var render_user_requests = function (req, res) {
        UserRequests.find({}, function (err, user_requests) {
            if (err) {
                console.log("Error finding outstanding user requests: " + err);
                utils.render_error_page(req, res, "Error in displaying user requests", error);
            }
            res.render('admin_user_requests', {
                "request_list": user_requests,
                title: 'User List'
            });
        });
    }

    // Delete user requests that have been serviced, or have been explicitly marked
    // for deletion.  We will not have to worry about synchronization, because we
    // are displaying the user page, not the requests page after this, giving plenty of time
    // to finish up
    var delete_requests = function (req, res, requests_to_delete) {
        // there is probably a better way to do this, but this is safe...revisit
        // when I learn mongoose a little better
        for (var i in requests_to_delete) {
            var userid = requests_to_delete[i];
            UserRequests.remove({
                email: userid
            }, function (err) {
                console.log("Error in deleting request for userid " + userid + ": " + err);
            });
        }
        // Just render the admin console again
        res.render('admin', {
            user: req.session.user
        });
    }

    // Act on the user requests.  This is called by /add_requested_users, and is broken
    // out as a separate function to avoid the usual node deep nesting...
    var act_on_user_requests = function (req, res, confirm, to_delete) {
        // first, make sure that we are going to delete all the records we
        // are confirming.  Also prepare the array for the batch add to DB.users.
        var new_users = [];
        // Should I check if this user is already in the DB?  That would be a pain, due
        // to the asynch nature of find...
        for (var confirm_index in confirm) {
            var user = confirm[confirm_index];
            if (to_delete.indexOf(user) == -1) {
                to_delete.push(user);
            }
            new_users.push({
                email: user
            });
        }
        console.log("users to be added: " + new_users);
        console.log("requests to be deleted: " + to_delete);
        if (new_users.length > 0) { // there are users to add
            DB.users.create(new_users, function (err, updated) {
                if (err) {
                    utils.render_error_page(req, res, "Error in updating users", err);
                    // note we won't do the deletes if we hit an error...
                } else {
                    console.log("Update action " + updated + " completed.");
                    delete_requests(req, res, to_delete);
                }
            });
        } else {
            delete_requests(req, res, to_delete);
        }
    }

    var setDeletedAdmins = function(req, res, deletedAdmins) {
        if (deletedAdmins.length > 0) {
            Users.update({email: {$in: deletedAdmins}}, {$set:{admin:false}}, {multi:true}, function (err, numAffected, raw) {
                if(err) {
                    utils.handleError(req, res, "Error in update_all_users: " + err)
                } else {
                    render_users(req, res);
                }
            });
        } else {
            render_users(req, res);
        }
    }

    var setNewAndDeletedAdmins = function(req, res, newAdmins, deletedAdmins) {
        if (newAdmins.length > 0) {
            DB.users.update({email: {$in: newAdmins}}, {$set:{admin:true}}, {multi:true}, function (err, numAffected, raw) {
                if(err) {
                    utils.handleError(req, res, "Error in update_all_users: " + err)
                } else {
                    setDeletedAdmins(req, res, deletedAdmins)
                }
            });
        } else {
            setDeletedAdmins(req, res, deletedAdmins)
        }
    }

    var update_all_users = function (req, res, admins_from_form) {
        var admins = utils.ensure_items_in_a_list(admins_from_form)
        DB.users.find({}, function(err, users) {
            if(err) {
                utils.handleError(req, res, "Error in update_all_users: " + err)
            } else {
                var newAdmins = [];
                var deletedAdmins = [];
                users.forEach(function(aUserRecord) {
                    var adminBitSet = admins.indexOf(aUserRecord.email) >= 0;
                    if (adminBitSet && !aUserRecord.admin) newAdmins.push(aUserRecord.email)
                    if (aUserRecord.admin && !adminBitSet) deletedAdmins.push(aUserRecord.email)
                });
                setNewAndDeletedAdmins(req, res, newAdmins, deletedAdmins);
            }
        })
    }

    var adminCheckOrDo = function(req, res, thenDo) {
        if (!req.session.admin) { // lovely Javascript -- does the right thing even when req.session.admin is null
            res.render('admin_only', {
                user: req.session.user,
                title: 'Unauthorized Admin'
            });
        } else {
            thenDo(req, res)
        }
    }

    // A utility function that gets slice data, and passes it to next_function.
    // next_function is a function with signature
    // next_function(req, res, error, slices)
    var get_slicelet_data = function (req, res, next_function) {
        DB.slices.find({}, function(err, allSlices) {
            if (allSlices && allSlices.length > 0) {
                var sliceDictionary = allSlices.map(function(aSliceEntry) {
                    var portString = aSliceEntry.ports.map(function(aPortSpec) {
                        return aPortSpec.container + '->' + aPortSpec.host
                    }).join(', ')
                    return {name:utils.makeSliceName(aSliceEntry.sliceNum),
                        allocated:aSliceEntry.user,
                        file:aSliceEntry.tarfile,
                        expiry_date:aSliceEntry.expires,
                        status: aSliceEntry.status,
                        ports:portString
                    }
                })
                next_function(req, res, err, sliceDictionary)
            } else {
                next_function(req, res, err, [])
            }
        });
    }

    // A utility function that gets nodes data, and passes it to next_function.
    // next_function is a function with signature
    // next_function(req, res, error, nodes)
    var get_nodes = function (req, res, next_function) {
        DB.nodes.find({}, function(err, nodes) {
            if (nodes && nodes.length > 0) {
                next_function(req, res, err, nodes)
            } else {
                next_function(req, res, err, [])
            }
        });
    }

    // Administrator actions and options.  Only available
    // through the admin console
    app.get('/admin', function (req, res) {
        if (!req.session.admin) {
            res.render('admin_only', {
                user: req.session.user,
                title: 'Unauthorized Admin'
            });
        } else {
            res.render('admin', {
                user: req.session.user
            });
        }
    });

    var showNodes = function(req, res, template) {
        console.log("Getting all nodes")
        get_nodes(req, res, function (req, res, error, nodes) {
            if (error) {
                utils.render_error_page(req, res, "Error in getting node data", error);
            } else {
                // console.log(nodes);
                res.render(template, {
                    nodes: nodes,
                    title: 'Node List'
                });
            }
        });

    }

    var showNodesAdmin = function(req, res) {
        showNodes(req, res, 'admin_nodes')
    }

     var showNodesUser = function(req, res) {
        showNodes(req, res, 'status')
    }

    app.get('/admin/nodes', function (req, res) {
       adminCheckOrDo(req, res, showNodesAdmin)
    });

    app.get('/status', function (req, res) {
       showNodesUser(req, res)
    });

    // not really an admin function, but simple code is that it belongs here, since it is very similar
    // to /admin/nodes

    var deleteNode = function(req, res) {
        DB.nodes.remove({ipAddress: req.body.ipAddress}, function(err) {
            if (err) {
                utils.render_error_page(req, res, 'Error deleting node ' + req.body.ipAddress)
            } else {
                showNodes(req, res)
            }
        });
    }

    app.post('/admin/node/delete', function(req, res) {
        adminCheckOrDo(req, res, deleteNode)
    })

    var renderAddNodeForm = function(req, res) {
        res.render('admin_node_addForm.jade')
    }

    app.get('/admin/node/addForm', function(req, res) {
        adminCheckOrDo(req, res, renderAddNodeForm)
    })

    var addNode = function(req, res) {
        var date = new Date()
        var doc = {
            date: date,
            ipAddress: req.body.ipAddress,
            siteName: req.body.siteName,
            sshNickname: req.body.sshNickname,
            dnsName: req.body.dnsName,
            permanent: false
        }
        DB.nodes.create(doc, function(err) {
            if (err) {
                utils.render_error_page('Error adding node with IP Address ' + doc.ipAddress + ' and dnsName ' + doc.dnsName)
            } else {
                showNodes(req, res)
            }
        })

    }

    app.post('/admin/node/addNode', function(req, res) {
        adminCheckOrDo(req, res, addNode)
    })

    app.get('/admin/slices', function (req, res) {
        if (!req.session.admin) { // lovely Javascript -- does the right thing even when req.session.admin is null
            res.render('admin_only', {
                user: req.session.user,
                title: 'Unauthorized Admin'
            });
        } else {
            console.log("Getting all slices")
            get_slicelet_data(req, res, function (req, res, error, slices) {
                if (error) {
                    utils.render_error_page(req, res, "Error in finding slice data", error);
                } else {
                    console.log(slices);
                    res.render('admin_slices', {
                        slices: slices,
                        title: 'Slice List'
                    });
                }
            });
        }
    });

    // get the slice renewal events, then render the log page
    var getSliceRenewalEventsAndRender = function(req, res, createRecords, deleteRecords) {
        DB.renewalLogs.find({}, function(err, renewalRecords) {
            if (err) {
                utils.render_error_page(req, res, "Error in finding slice renewal logs")
            } else {
                res.render('admin_logs', {
                    sliceCreationEvents: createRecords,
                    sliceDeletionEvents: deleteRecords,
                    sliceRenewalEvents: renewalRecords
                })
            }
        })
    }

    // get the deletion events, then get the renewal events and render the log page
    // get the slice renewal events, then render the log page
    var getSliceDeletionEventsAndRender = function(req, res, createRecords) {
        DB.deleteLogs.find({}, function(err, deleteRecords) {
            if (err) {
                utils.render_error_page(req, res, "Error in finding slice deletion logs")
            } else {
                getSliceRenewalEventsAndRender(req, res, createRecords, deleteRecords)
            }
        })
    }

    // get the creation events, then get the deletion and renewal events and render the log page
    // get the slice renewal events, then render the log page
    var getSliceCreationEventsAndRender = function(req, res) {
        DB.creationLogs.find({}, function(err, createRecords) {
            if (err) {
                utils.render_error_page(req, res, "Error in finding slice creation logs")
            } else {
                createRecords.forEach(function(aRecord) {
                    if (aRecord.ports && aRecord.ports.length > 0) {
                        aRecord.ports = aRecord.ports.map(function(aPort) {
                            return aPort.container + '->' + aPort.host
                        }).join(',')
                    }
                })
                getSliceDeletionEventsAndRender(req, res, createRecords)
            }
        })
    }

    var renderCustomSliceRequests = function(req, res) {
        DB.customSliceRequests.find({}, function(err, sliceRequests) {
            if (err) {
                utils.render_error_page(req, res, "Error in finding custom slice requests", err)
            } else {
                if (sliceRequests && sliceRequests.length > 0) {
                    var sliceRequestDictionary = sliceRequests.map(function(aRequest) {
                        var portString = aRequest.ports.map(function(aPortEntry){
                            return aPortEntry.container + '->' + aPortEntry.host
                        }).join(', ')
                        return {
                            name:aRequest.sliceName,
                            user:aRequest.user,
                            imageName:aRequest.imageName,
                            ports: portString
                        }
                    })
                    res.render('admin_custom_slices', {
                        title: 'Custom Slices',
                        slices:sliceRequestDictionary
                    })
                } else {
                    res.render('admin_custom_slices', {
                        title: 'Custom Slices (No Current Requests)',
                        slices:[]
                    })
                }

            }
        })

    }

    app.get('/admin/show_events', function(req, res) {
        adminCheckOrDo(req, res, getSliceCreationEventsAndRender)
    })

    app.get('/admin/users/custom', function(req, res) {
        adminCheckOrDo(req, res, renderCustomSliceRequests)
    })

    var renderCustomSliceEditPage = function(req, res) {
        var urlParts = url.parse(req.url, true)
        var query = urlParts.query
        DB.customSliceRequests.findOne({sliceName:query.sliceName}, function(err, sliceRequest){
            if (err) {
                utils.render_error_page(req, res, "Error in finding custom slice request " + req.body.sliceName, err)
            } else {
                res.render('slice_request', {
                    title: 'Editing Customer Slice Request ' + query.sliceName,
                    imageName: sliceRequest.imageName,
                    sliceName: query.sliceName,
                    ports: sliceRequest.ports,
                    callback: '/admin/approve_custom_slice_request',
                    user: sliceRequest.user,
                    params: {
                        sliceName: query.sliceName,
                        user: sliceRequest.user
                    }
                })
            }
        })
    }

    app.get('/admin/custom_slice_request_edit', function(req, res) {
        adminCheckOrDo(req, res, renderCustomSliceEditPage)
    })

    var approveCustomSliceRequest = function(req, res) {
        var ports = JSON.parse(req.body.ports)
        var modifyCommand = {
            $set: {
                imageName: req.body.imageName,
                status: 'Processing',
                ports: ports
            }
        }
        DB.slices.update({sliceName: req.body.sliceName}, modifyCommand, {}, function(err, slice) {
            if (err) {
                utils.render_error_page(req, res, 'Error modifying slice ' + req.body.sliceName)
            } else {
                DB.customSliceRequests.remove({sliceName: req.body.sliceName}, function(err) {
                    if (err) {
                        utils.render_error_page(req, res, 'Error deleting custom slice request for ' + req.body.sliceName)
                    } else {
                        // last thing -- must create the request to actually create the slice
                        DB.sliceRequests.create({
                            action:'create',
                            user:req.body.user,
                            sliceName: req.body.sliceName,
                            imageName: req.body.imageName,
                            ports: ports
                        }, function(err) {
                            if (err) {
                                utils.render_error_page(req, res, 'Error creating slice request for ' + req.body.sliceName)
                            } else {
                                res.render('admin', {
                                    user: req.session.user
                                })
                            }
                        });
                    }
                })
            }
        })
    }

    app.post('/admin/approve_custom_slice_request', function(req, res) {
        adminCheckOrDo(req, res, approveCustomSliceRequest)
    })

    app.get('/admin/users/requests', function (req, res) {
        if (!req.session.admin) { // lovely Javascript -- does the right thing even when req.session.admin is null
            res.render('admin_only', {
                user: req.session.user,
                title: 'Unauthorized Admin'
            });
        } else {
            render_user_requests(req, res);
        }
    });

    app.get('/admin/users', function (req, res) {
        if (!req.session.admin) { // lovely Javascript -- does the right thing even when req.session.admin is null
            res.render('admin_only', {
                user: req.session.user,
                title: 'Unauthorized Admin'
            });
        } else {
            render_users(req, res);
        }
    });

    // The next three functions implement acting on user requests.  This comes from
    // the form /add_requested_users on page user_requests.jade.
    // This form will give us two separate email lists: new user requests to be
    // confirmed, and requests to be deleted.  Here, we pull out the two lists
    // and call act_on_user_requests to manipulate the database.
    // I should probably factor those into things which actually just manipulate the db
    app.post('/admin/users/requests/add', function (req, res) {
        if (!req.session.admin) { // lovely Javascript -- does the right thing even when req.session.admin is null
            res.render('admin_only', {
                user: req.session.user,
                title: 'Unauthorized Admin'
            });
            return;
        }
        var to_confirm = utils.ensure_items_in_a_list(req.body.confirm);
        var to_delete = utils.ensure_items_in_a_list(req.body.to_delete);
        var user_string = "Will confirm " + to_confirm.length + " new users: " + to_confirm + ".";
        var delete_string = "Will delete " + to_delete.length + " requests: " + to_delete;
        console.log(user_string + " " + delete_string);
        if (to_confirm.length == 0 && to_delete.length == 0) {
            // nothing to do!
            res.render('admin', {
                user: req.session.user
            });
        } else {
            act_on_user_requests(req, res, to_confirm, to_delete);
        }
    });

    app.post('/admin/users/update', function (req, res) {
        if (!req.session.admin) { // lovely Javascript -- does the right thing even when req.session.admin is null
            res.render('admin_only', {
                user: req.session.user,
                title: 'Unauthorized Admin'
            });
            return;
        }
        var admins = req.body.admin;
        console.log("Updating users, admins = " + JSON.stringify(admins));
        update_all_users(req, res, admins);
    });

    // Add a user.  Nesting is way too deep here, but that is an artifact of the callback/continuation architecture
    // of node.js...I should refactor and clean this up.
    app.get('/admin/users/add', function (req, res) {
        if (!req.session.admin) { // lovely Javascript -- does the right thing even when req.session.admin is null
            res.render('admin_only', {
                user: req.session.user,
                title: 'Unauthorized Admin'
            });
        } else {
            // user name is a parameter to the call
            var query = url.parse(req.url, true).query;
            var username = query.user;
            if (!utils.validate_username(username)) {
                res.send("Invalid username " + username + " sent to add_user")
            } else {
                // Look for the user in the db.  If he's already there, send an error.  If
                // he's not, add him
                DB.users.find({
                    email: username
                }, function (err, users) {
                    if (err) {
                        res.send("Error in looking up " + username + ": " + err);
                    } else {
                        if (users.length == 0) { // go ahead and add the new user
                            DB.users.create({
                                email: username
                            }, function (err, new_user) {
                                if (err) {
                                    res.send("Error adding " + username + ": " + err);
                                } else {
                                    // Added the user.  Now show the users page
                                    render_users(req, res);
                                }
                            });
                        } else {
                            res.send("user " + username + " already in database: " + JSON.stringify(users));
                        }
                    }
                });
            }
        }
    });

    // dump the logfile
    app.get('/dump_logfile', function (req, res) {
        if (!req.session.admin) { // lovely Javascript -- does the right thing even when req.session.admin is null
            res.render('admin_only', {
                user: req.session.user,
                title: 'Unauthorized Admin'
            });
        } else {
            res.sendfile('/var/log/gee/geePortal.out.log');
        }
    });

    // dump the error logs
    // dump the logfile
    app.get('/dump_error_logs', function (req, res) {
        if (!req.session.admin) { // lovely Javascript -- does the right thing even when req.session.admin is null
            res.render('admin_only', {
                user: req.session.user,
                title: 'Unauthorized Admin'
            });
        } else {
            res.sendfile('/var/log/gee/geePortal.err.log');
        }
    });
}


text:
module OpenXml
  module Docx
    module Elements
      class WordProcessingShapesTextualContent < OpenXml::Docx::Element
        include HasChildren, HasProperties

        tag :txbx
        namespace :wps

        attribute :id, expects: :positive_integer

      end
    end
  end
end


text:
require 'spec_helper'

describe Account do
  it { should belong_to(:user) }
  it { should_not allow_mass_assignment_of(:user_id) }
end
# == Schema Information
#
# Table name: accounts
#
#  id               :integer         not null, primary key
#  user_id          :integer
#  personal_website :string(255)
#  location         :string(255)
#  signature        :string(255)
#  introduction     :text
#  twitter_id       :string(255)
#  created_at       :datetime
#  updated_at       :datetime
#


text:
namespace Events
{
    using System;
    using System.Linq;
    using System.Text;

    public class Event : IComparable
    {
        private const string EventMessageFormat = " | {0}";
        private const string DateTimeFormat = "yyyy-MM-ddTHH:mm:ss";
        private const string EventObjectIsNullExceptionMessage = "Object is not instance of Event";

        private DateTime date;
        private string title;
        private string location;

        public Event(DateTime date, string title, string location)
        {
            this.DateAndTime = date;
            this.Title = title;
            this.Location = location;
        }

        public DateTime DateAndTime
        {
            get { return this.date; }
            private set { this.date = value; }
        }

        public string Title
        {
            get { return this.title; }
            private set { this.title = value; }
        }

        public string Location
        {
            get { return this.location; }
            private set { this.location = value; }
        }

        public int CompareTo(object obj)
        {
            Event other = obj as Event;

            if (other != null)
            {
                int compareByDate = this.DateAndTime.CompareTo(other.DateAndTime);
                int compareByTitle = this.Title.CompareTo(other.Title);
                int compareByLocation = this.Location.CompareTo(other.Location);

                if (compareByDate == 0)
                {
                    if (compareByTitle == 0)
                    {
                        return compareByLocation;
                    }
                    else
                    {
                        return compareByTitle;
                    }
                }
                else
                {
                    return compareByDate;
                }
            }
            else
            {
                throw new ArgumentException(EventObjectIsNullExceptionMessage);
            }
        }

        public override string ToString()
        {
            StringBuilder eventMessage = new StringBuilder();
            eventMessage.Append(this.DateAndTime.ToString(DateTimeFormat));
            eventMessage.AppendFormat(EventMessageFormat, this.Title);

            if (!string.IsNullOrEmpty(this.Location) && !string.IsNullOrEmpty(this.Location))
            {
                eventMessage.AppendFormat(EventMessageFormat, this.Location);
            }

            return eventMessage.ToString();
        }
    }
}


text:
from py_algorithms.challenges.coderbyte.array_addition import ArrayAddition

class ArrayAdditionTest:
    def test_impl(self):
        inputs = {
            True: [4, 6, 23, 10, 1, 3],
            False: [4, 6, 123, 10, 1, 3]
        }
        f = ArrayAddition()
        for key in inputs:
            assert f(inputs[key]) == key


text:
<?php

namespace Cacic\CommonBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Cacic\CommonBundle\Common;

class BaseController extends Controller
{

	public function __construct()
	{
		$root_cacic = realpath( dirname(__FILE__) .'/../' ). '/Common';
		set_include_path( "." . PATH_SEPARATOR . $root_cacic );

		require_once 'include/library.php';
	}

}


text:
TODOS:

- [ ] meta click to show source in VSCode
- [ ] open dev server command
- [ ] open current file in Aerial (whitelisted by dev config, or HTML by default)
- [ ] send commands to preview HTML server
  - [ ] might have to be done via sockets
- [ ] use default dev server if it doesn't exist
- [ ] default dev server if one isn't provided


text:
function playSound(path) {
    // audio supported?
    if (typeof window.Audio === 'function') {
        var audioElem = new Audio(path);

        audioElem.play().catch(function(){
            debugger;
        })
    }
}

function playRandomSound(){
    var sound  =  srvModel.sounds[Math.floor((Math.random() *  srvModel.sounds.length) )];
    playSound(sound);
}


text:
package model;

import java.io.Serializable;
import java.util.ArrayList;
import model.Discount;
import model.Discountable;
import model.Image;
import model.Language;
import model.User;

public class Script implements model.Product {
    private final String id;
    private String name;
    private User author;
    private Language language;
    private double price;
    private String description;
    private Image image;
    private ArrayList<Discount> discounts;

    public Script(String id, String name, User author, Language language, double price, String description, Image image) {
        this.id = id;
        this.name = name;
        this.author = author;
        this.language = language;
        this.price = price;
        this.description = description;
        this.image = image;
        this.discounts = new ArrayList<Discount>();;
    }

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public User getAuthor() {
        return author;
    }

    public void setAuthor(User author) {
        this.author = author;
    }

    public Language getLanguage() {
        return language;
    }

    public void setLanguage(Language language) {
        this.language = language;
    }

    public double getPrice() {
        return Math.floor(price * 1e2) / 1e2;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Image getImage() {
        return image;
    }

    public void setImage(Image image) {
        this.image = image;
    }

    @Override
    public double getPriceWithDiscount() {
        double priceDiscounted = 0;
        for (Discount discount : discounts)
            priceDiscounted += discount.getPriceDiscounted(this);
        double finalPrice = Math.floor((price - priceDiscounted)* 1e2) / 1e2;
        return (finalPrice < 0)? 0 : finalPrice;
    }

    @Override
    public ArrayList<Discount> getDiscounts() {
        return discounts;
    }

    @Override
    public void setDiscounts(ArrayList<Discount> discounts) {
        this.discounts = discounts;
    }

    @Override
    public double getPriceDiscounted() {
        double priceDiscounted = 0;
        for (Discount discount : discounts) {
            priceDiscounted += discount.getPriceDiscounted(this);
        }
        return Math.floor((priceDiscounted) * 1e2) / 1e2;
    }

}


text:
This is a simple tool to drive capturing, saving, and replaying HTTP requests. It depends on `pcap_tools`, `tshark`, `dumpcap`, and `httperf`.

## Use

```shell
gem install qreplay
qreplay [capture|replay|transform|capture_only] [options]
```

- __capture__ - Use `tshark` to capture http packets.
- __replay__ - Replay HTTP session file with requests to a host/port.
- __transform__ - Transform a dumpcap file to a sesslog file. This is executed automatically in capture mode.
- __capture-only__ - Perform a capture without a transform step.

Options:
```
-c, --capture-time=<f>         Capture time length in seconds (default: 60.0)
-a, --capture-interface=<s>    Traffic capture interface (uses dumpcap default if not specified)
-p, --port=<i>                 Capture/replay traffic to port (default: 80)
-h, --host=<s>                 Replay host (default: 0.0.0.0)
-r, --req-sec=<i>              Requests per second for replays (default: 20)
-t, --total-requests=<i>       Total replay requests to send (default: 10000)
-u, --capture-file=<s>         Output file (default: ./qreplay.sesslog)
-f, --pcap-file=<s>            Temporary intermediate pcap file path (default: ./qreplay.pcap)
-i, --timeout=<i>              Timeout for replay requests (default: 10)
-s, --tshark-binary=<s>        TShark binary file location (default: tshark)
-d, --dumpcap-binary=<s>       dumpcap binary file location (default: dumpcap)
-e, --httperf-binary=<s>       httperf binary file location (default: httperf)
-v, --version                  Print version and exit
-l, --help                     Show this message
```

Capturing TCP traffic requires root privileges on most systems.

## Example

You want to capture traffic on a live web server. On the remote machine run:

```
sudo qreplay capture --capture-time 60 --port 80
```

This will use `tshark` to capture TCP traffic to/from port 80 for 60 seconds, stitch together HTTP requests from the TCP traffic, and save requests to `./qreplay.sesslog`. If you observe this file you will notice that each request line contains an HTTP method, path, and body in a format acceptable to `httperf`.

This example is invoking `sudo` so that it has access to the capture device.

You can then replay with:

```
qreplay replay --host 127.0.0.1 --port 80 --req-sec 50
```

To replay these requests to the local server at port 80 at a rate of 50 per second.

## Installing

Mac OS X (homebrew):
```
gem install qreplay
brew install wireshark httperf
```

Yum package manager:
```
gem install qreplay
yum install wireshark httperf
```

## httperf

By default, httperf only handles HTTP bodies with 10,000 bytes or less, which is easy to exceed if you're testing an application that POSTs significant amounts of data. We've increased a few of the arbitrary limitations in httperf in our fork [here](https://github.com/quizlet/httperf), and we recommend using it if you're hitting limits in the mainline httperf.

## License

The qreplay copyright is owned by Old School Industries LLC. We've licensed it under the MIT License, which can be found in [LICENSE.md](LICENSE.md).

## Thanks

Thanks to Bertrand Paquet for developing pcap tools and licensing it under the Apache 2 license. You can find more about pcap_tools [here](https://github.com/bpaquet/pcap_tools).