text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title></title>

  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="description" content="">
  <meta name="author" content="">

  <link href="../../assets/css/vendor/morris.css" rel="stylesheet">
  <link href="../../assets/css/vendor/bootstrap.css" rel="stylesheet">
  <link href="../../assets/css/vendor/font-awesome.css" rel="stylesheet">
  <link href="../../assets/css/vendor/font-awesome-ie7.css" rel="stylesheet">
  <link href="../../assets/css/vendor/codemirror.css" rel="stylesheet">
  <link href="../../assets/css/plato.css" rel="stylesheet">
  <link href="../../assets/css/plato-file.css" rel="stylesheet">

    Plato on Github

        Report Home

concurrency/redis-concurrency.js

Maintainability

69.07

Lines of code

336

Difficulty

74.42

Estimated Errors

2.30

Function weight

By Complexity

By SLOC

    <textarea id="file-source" class="col-md-12">/* jshint unused:true, undef:true, strict:true, plusplus:true */
/* global module:false, exports:true, setTimeout:false */

/**
 * @memberof RarefiedRedis
 */
(function () {

    // Baseline setup
    // --------------

    "use strict";

    // Establish the root object, `window` in the browser, or `exports` on the server.
    var root = this;

    function checkFunction(f) {
        if (!f || typeof f !== 'function') {
            return function () {
                if (typeof arguments[arguments.length - 1] === 'function') {
                    arguments[arguments.length - 1](new Error('checkFunction: given f was not a function'));
                }
            };
        }
        return f;
    }

    function optimism(f, context, maxOptimism, callback) {
        var tries = 1;
        var of;
        callback = checkFunction(callback);
        f = checkFunction(f);
        of = function () {
            var original = arguments;
            var args = Array.prototype.slice.call(arguments);
            while (args.length < f.length - 1) {
                args.push(undefined);
            }
            if (args.length === f.length && typeof args[args.length - 1] === 'function') {
                args.pop();
            }
            args.push(function (err, replies) {
                if (err) {
                    return callback(err);
                }
                if (replies === null) {
                    if (!maxOptimism || tries < maxOptimism) {
                        tries += 1;
                        return setTimeout(function () {
                            of.apply(null, original);
                        }, Math.ceil(Math.random()*100)); // Back off randomly anywhere between 0+ms - 999ms.
                    }
                    return callback(new Error('ERR optimistic concurrency failed'));
                }
                callback(null, replies);
            });
            f.apply(context, args);
        };
        return of;
    }

    function pessimism(f, context, maxPessimism, locker, timeout, callback) {
        var tries = 1;
        var pf;
        callback = checkFunction(callback);
        f = checkFunction(f);
        pf = function () {
            var original = arguments;
            locker.lock(timeout, function (err, locked, id) {
                var args = Array.prototype.slice.call(original);
                if (err) {
                    return callback(err);
                }
                if(!locked) {
                    if (!maxPessimism || tries < maxPessimism) {
                        tries += 1;
                        return setTimeout(function () {
                            pf.apply(null, original);
                        }, Math.ceil(Math.random()*100)); // Back off randomly anywhere between 0+ms - 999ms.
                    }
                    return callback(new Error('ERR pessimistic concurrency failed'));
                }
                while (args.length < f.length - 1) {
                    args.push(undefined);
                }
                if (args.length === f.length && typeof args[args.length - 1] === 'function') {
                    args.pop();
                }
                args.push(function (err, reply) {
                    if (err) {
                        return callback(err);
                    }
                    locker.unlock(id, function (err2, unlocked) {
                        if (err2) {
                            return callback(err2);
                        }
                        if (!unlocked) {
                            // We lost the lock before completion, so the operation
                            // is invalid.
                            return callback(null, null);
                        }
                        callback(null, reply);
                    });
                });
                args.push(locker);
                args.push(id);
                f.apply(context, args);
            });
        };
        return pf;
    }

    /**
     * Implement concurrency operations within redis. This abstraction exposes 2 interfaces
     * for concurrency: optimistic concurrency, and pessimistic concurrency. It's also
     * written in a literate style. An example of using this class:
     *
     * <pre><code>
     * var mover = new RedisReliableMover(redisClient);
     * (new RedisConcurrency(new RedisReliableLock(redisClient, lockKey)))
     *     .should
     *     .be
     *     .optimistic
     *     .on(mover.move, mover)
     *     .and
     *     .tell(function (err, member) {
     *           // Do stuff.
     *     })
     *     .when
     *     .invokedWith(key1, key2);
     * </code></pre>
     *
     * This piece of code will try optimistic concurrency 10 times on mover.move(key1, key2).
     * <br/>
     * <br/>
     * NOTE: Pessimistic concurrency uses a lock to enforce its pessimism. We only allow
     * that lock to be locked for some maximum time, currently 1h, in case the process dies
     * while holding the lock. Let's say the operation
     * pulls a key's value from redis, asks a different service to manipulate it, then sets
     * the key to this new value in redis. If that different service takes > 30s to respond,
     * the lock will have expired and is no longer valid. To allow pessimistic functions to
     * check this condition, the locker and lock id are passed to the function <i>after</i>
     * the callback. The operation can then check whether its lock is still valid before
     * setting the key in redis. This timeout can be extended using the 2nd parameter
     * to atMost, up to 1 hour (3600 seconds).
     * <br/>
     * <br/>
     * NOTE 2: Both optimistic concurrency and pessimistic concurrency are protocols, and
     * can be livelocked by a client not adhering to the protocol. For instance, in
     * optimistic concurrency, a producer that is heavily modifying a structure while we're
     * trying to do optimistic concurrency can starve any optimistic producer out. Just like
     * with redlocks, redis currently has no ability to enforce these protocols.
     *
     * @memberof! RarefiedRedis.Reliable
     * @class
     * @param {Object=} locker An object that implements lock semantics. This locker does pessimistic locking. If only doing optimistic concurrency, this parameter is not required.
     */
    function RedisConcurrency(locker) {
        var that = this;
        this._times = 10;
        this._f = 0;
        this._locker = locker;
        this._timeout = 30; // seconds!
        this.should = this;
        this.be = this;
        this.times = this;
        this.and = this;
        this.when = this;
        this.optimistic = {
            on: function () {
                that.on.apply(that, arguments);
                return that.optimistic;
            },
            tell: function () {
                that.tell.apply(that, arguments);
                return that.optimistic;
            },
            invokedWith: function () {
                var args = arguments;
                var f;
                f = optimism(that._f, that._context, that._times, that._callback);
                setTimeout(function () {
                    f.apply(null, args);
                }, 0);
                return that;
            },
        };
        this.optimistic.about = this.optimistic.on;
        this.optimistic.attempt = this.optimistic;
        this.optimistic.and = this.optimistic;
        this.optimistic.when = this.optimistic;
        this.optimistic.invoked = this.optimistic.invokedWith;
        this.pessimistic = {
            on: function () {
                that.on.apply(that, arguments);
                return that.pessimistic;
            },
            tell: function () {
                that.tell.apply(that, arguments);
                return that.pessimistic;
            },
            invokedWith: function () {
                var args = arguments;
                var f;
                f = pessimism(that._f, that._context, that._times, that._locker, that._timeout, that._callback);
                setTimeout(function () {
                    f.apply(null, args);
                }, 0);
                return that;
            }
        };
        this.pessimistic.about = this.pessimistic.on;
        this.pessimistic.attempt = this.pessimistic;
        this.pessimistic.and = this.pessimistic;
        this.pessimistic.when = this.pessimistic;
        this.pessimistic.invoked = this.pessimistic.invokedWith;
        this.eeyore = this.pessimistic;
        return this;
    }

    /**
     * Specify the operation to do concurrency on.
     *
     * @param {Function} f The function that does the operation.
     * @param {Object} context The context to call f with.
     */
    RedisConcurrency.prototype.on = function (f, context) {
        this._f = checkFunction(f);
        this._context = context;
        return this;
    };
    RedisConcurrency.prototype.about = RedisConcurrency.prototype.on;
    RedisConcurrency.prototype.attempt = RedisConcurrency.prototype.on;

    /**
     * Specify who to tell on whether the operation succeeded or failed.
     *
     * @param {Function} callback The callback to call when the operation is done. The reply will always be (null, null) if the operation failed. Anything else is context-specific to the concurrenct function.
     */
    RedisConcurrency.prototype.tell = function (callback) {
        this._callback = checkFunction(callback);
        return this;
    };

    /**
     * Specify how many times the concurrency should try before giving up.
     *
     * For optimistic concurrency, this number decides how many times to
     * attempt the operation before bailing.
     *
     * For pessimistic concurrency, this number decides how many times to
     * attempt to lock the resource before bailing.
     *
     * If the number given here is 0, we will never bail on the operation,
     * just keep trying.
     *
     * Negative times numbers are equivalent to 1. So atMost(-5) = atMost(1).
     *
     * Also, for pessimistic concurrency, you can pass a second timeout parameter
     * that determines how long the operation has to complete before being considered
     * invalid. This number is validated to be greater than 0 and less than 1 hour
     * (3600 seconds). It is specified in seconds.
     *
     * @param {number} t times to attempt the operation. = 0 to attempt forever.
     * @param {number=} timeout Determines in pessimistic concurrency how long an operation has to complete. Always validated such that 0 < timeout <= 3600.
     */
    RedisConcurrency.prototype.atMost = function (t, timeout) {
        this._times = t;
        if (isNaN(parseInt(this._times, 10))) {
            this._times = 10;
        }
        this._timeout = timeout;
        if (!this._timeout || isNaN(parseInt(this._timeout, 10)) || this._timeout <= 0) {
            this._timeout = 30;
        }
        this._timeout = Math.min(3600, this._timeout);
        return this;
    };

    /**
     * Invoke the chain
     */
    RedisConcurrency.prototype.invokedWith = function () {
        // If we're called invokedWith on a naked concurrency object,
        // assume we are optimistic.
        this.optimistic.invokedWith.apply(null, arguments);
        return this.optimistic;
    };
    RedisConcurrency.prototype.invoked = RedisConcurrency.prototype.invokedWith;

    /**
     * Return a concurrency object that only does optimistic concurrency.
     */
    RedisConcurrency.Optimistic = function () {
        var concurrency = new RedisConcurrency();
        var invokedWith = function () {
            return concurrency
                .optimistic
                .invokedWith
                .apply(concurrency, arguments);
        };
        concurrency.pessimistic = undefined;
        concurrency.attempt = concurrency.about;
        concurrency.invokedWith = invokedWith;
        concurrency.invoked = invokedWith;
        return concurrency;
    };

    /**
     * Return a concurrency object that only does pessimistic concurrency.
     *
     * @param {Object} locker An object that implements lock semantics.
     */
    RedisConcurrency.Pessimistic = function (locker) {
        var concurrency = new RedisConcurrency(locker);
        var invokedWith = function () {
            return concurrency
                .pessimistic
                .invokedWith
                .apply(concurrency, arguments);
        };
        concurrency.optimistic = undefined;
        concurrency.attempt = concurrency.about;
        concurrency.invokedWith = invokedWith;
        concurrency.invoked = invokedWith;
        return concurrency;
    };

    // Export the reliable object for **node.js/io.js**, with
    // backwards-compatibility for the old `require()` API. If we're in
    // the browser, add `RedisConcurrency` as a global object.
    if (typeof exports !== 'undefined') {
        if (typeof module !== 'undefined' && module.exports) {
            exports = module.exports = RedisConcurrency;
        }
        exports.RedisConcurrency = RedisConcurrency;
    }
    else {
        root.RedisConcurrency = RedisConcurrency;
    }

}).call(this);</textarea>

.


text:
Most sources on the internet recommend checking an `.editorconfig` file into every repository, much like a `package.json` or `Nuget.config` file.  However, you will likely be using the same coding style preferences in most of the projects that you develop with Visual Studio (C# projects in particular).  Therefore, to avoid duplicating these preferences into every new repository (a nightmare to update if your style preferences ever change), it is much simpler to have a single `.editorconfig` file in its own repository, and then your other repos utilize that one.

This repository contains such an `.editorconfig`.  It was developed for Danware's projects, but we hope that our style preferences are general enough, to be of use to any Visual Studio project, in any repository.

## Usage

Suppose you have the following directory structure:
```
root-directory\
    VisualStudioEditorConfig\
        .editorconfig
    Repo1\
    Repo2\
    RepoGroup\
        Repo3\
        Repo4\
    ...
```
If you want to use the same style preferences in all of your repos (Repo1, Repo2, Repo3, Repo4, etc.), then you should put the .editorconfig file in the "root-directory\" folder.  Unfortunately, the .editorconfig file was cloned into the subfolder "VsEditorConfig\".  You could copy the file to root-directory, but you would have to re-copy it everytime your style preferences change.  The solution is to create a symbolic link in root-directory to the versioned .editorconfig.

On Windows, run the following command at an elevated command prompt.  If you do not use an elevated command prompt (i.e., a command prompt opened with "Run as Administrator"), then you will get the error: `You do not have sufficient privilege to perform this operation.`
```
MKLINK "root-directory\.editorconfig" "root-directory\VsEditorConfig\.editorconfig"
```

On MacOS/Linux, run the following command:
```
ln -s "root-directory/VsEditorConfig/.editorconfig" "root-directory/.editorconfig"
```

Subsitute the above paths with those needed for your particular directory structure (absolute paths work best).  Once the link is created, you will be able to update the `.editorconfig` with `git pull` as normal, and the latest style preferences will then be available to all of your repositories (after restarting Visual Studio).

If you don't like any of our style/formatting preferences, then you can either fork our `.editorconfig` to use it as a starting point and modify it to fit your particular conventions, or add a separate `.editorconfig` with your overrides to the individual repos that need those overrides.

redpajama_set_name: RedPajamaGithub


text:
.class Landroid/hardware/camera2/legacy/RequestThreadManager$4;
.super Ljava/lang/Object;
.source "RequestThreadManager.java"

# interfaces
.implements Landroid/graphics/SurfaceTexture$OnFrameAvailableListener;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/hardware/camera2/legacy/RequestThreadManager;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Landroid/hardware/camera2/legacy/RequestThreadManager;

# direct methods
.method constructor <init>(Landroid/hardware/camera2/legacy/RequestThreadManager;)V
    .registers 2
    .param p1, "this$0"    # Landroid/hardware/camera2/legacy/RequestThreadManager;

    .prologue
    .line 260
    iput-object p1, p0, Landroid/hardware/camera2/legacy/RequestThreadManager$4;->this$0:Landroid/hardware/camera2/legacy/RequestThreadManager;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public onFrameAvailable(Landroid/graphics/SurfaceTexture;)V
    .registers 3
    .param p1, "surfaceTexture"    # Landroid/graphics/SurfaceTexture;

    .prologue
    .line 266
    iget-object v0, p0, Landroid/hardware/camera2/legacy/RequestThreadManager$4;->this$0:Landroid/hardware/camera2/legacy/RequestThreadManager;

    invoke-static {v0}, Landroid/hardware/camera2/legacy/RequestThreadManager;->-get8(Landroid/hardware/camera2/legacy/RequestThreadManager;)Landroid/hardware/camera2/legacy/GLThreadManager;

    move-result-object v0

    invoke-virtual {v0}, Landroid/hardware/camera2/legacy/GLThreadManager;->queueNewFrame()V

    .line 262
    return-void
.end method


text:
var mongoose = require('mongoose');
var Trick = mongoose.model('Trick');
var tricks = require('express').Router();
var config = require('../config/config');
var request = require('request');
var _ = require('lodash');
var APITrick = require('./API/tricks');

/**
 * New Trick
 */

exports.create = function (req, res) {
  res.render('tricks/new', {
    title: 'New Theater',
    trick: new Trick({})
  });
};

exports.myTrick = function (req, res) {
  var current_username = req.user.username;
  var username_params = req.params.username;

  if (current_username !== username_params) {
    res.redirect('/' + username_params);
  }

  var page = req.param('page') || 0;
  res.render('tricks/tricks-user', {
    title: '我的剧场',
    page: page,
    origin_url: '/' + current_username + '/tricks/'
  });
};

exports.homeTrick = function (req, res) {
  var page = req.param('page') || 0;
  res.render('index', {
    title: 'HomePage',
    page: page,
    origin_url: '/hall/'
  });
};

exports.deleteTrick = function(req, res) {
  var itemId = req.param('itemMogoId');
  var redirectUrl = req.param('redirectUrl');
  var trickTod = res.trick = req.trick;
  APITrick.deleteOneTrick(trickTod, function(err) {
    if(err) {
      res.render('500', {message: err.message, error: err});
    } else {
      res.redirect(redirectUrl);
    }
  });
};

exports.unityrender = function(req, res) {

  res.render('unity3d/unity3d', {
    title: '传媒大学 小剧场',
    isUnity: true
  });
};


text:
package models;

import dao.SimpleMap;

public class Login {
        public static final String TAG = Login.class.getName();

        public static final String TABLE = "login";
        public static final String PLAYER_ID = "player_id";
        public static final String TOKEN = "token";
        public static final String TIMESTAMP = "timestamp";

        protected Long playerId = null;
        protected String token = null;
        protected Long timestamp = null;

        public Long getPlayerId() {
                return playerId;
        }

        public Login(final SimpleMap data) {
                playerId = data.getLong(PLAYER_ID);
                token = data.getStr(TOKEN);
                timestamp = data.getLong(TIMESTAMP);
        }

        public boolean hasExpired() {
        /*
        * TODO: check expiry by current time and Player.TOKEN_LIFE
        * TODO: if token has expired, delete the entry in table `login`
        * */
                return false;
        }
}


text:
/**@scope pygowave*/
window.pygowave = $defined(window.pygowave) ? window.pygowave : new Hash();

pygowave.view = $defined(pygowave.view) ? pygowave.view : new Hash();

/**
 * Widgets for displaying and adding participants.
 *
 * @module pygowave.view.participants
 */
(function () {
	/* Imports */
	var Widget = pygowave.view.Widget;
	var SearchWidget = pygowave.view.SearchWidget;

	/**
	 * A widget to display a participant. This includes his/her avatar and a
	 * online indicator; may also display the participants nickname if rendered
	 * as searchbox widget.
	 *
	 * @class {private} pygowave.view.ParticipantWidget
	 * @extends pygowave.view.Widget
	 */
	var ParticipantWidget = new Class({
		Extends: Widget,

		// --- Event documentation ---
		/**
		 * Fired if clicked.
		 * @event onClick
		 * @param {ParticipantWidget} widget The clicked widget (for convenience)
		 */
		// ---------------------------

		/**
		 * Called on instantiation.
		 * @constructor {public} initialize
		 * @param {WaveView} view A reference back to the main view
		 * @param {Element} parentElement Parent DOM element to insert the widget
		 * @param {pygowave.model.Participant} participant Participant object
		 * @param {String} display_style Set the display style of the widget.
		 *        Possible values: 'normal', 'small', 'searchbox'.
		 * @param {String} where Where to inject the widget relative to the
		 *        parent element. Can be 'top', 'bottom', 'after', or 'before'.
		 */
		initialize: function (view, parentElement, participant, display_style, where) {
			this._view = view;
			this._participant = participant;
			var contentElement = new Element('div', {'class': 'wavelet_participant'});
			this._pImage = new Element('img', {
				'class': 'thumbnail',
				'src': '',
				'alt': '',
				'title': ''
			}).inject(contentElement);
			if (display_style == 'small') {
				contentElement.addClass('small');
				this._pNick = null;
			}
			else if (display_style == 'searchbox') {
				contentElement.addClass('searchbox');
				this._pNick = new Element('div', {
					'class': 'nicktext'
				}).inject(contentElement);
			}
			contentElement.addEvent('click', this._onClick.bind(this));
			this._onOnlineStateChanged = this._onOnlineStateChanged.bind(this);
			this._onDataChanged = this._onDataChanged.bind(this);
			this.parent(parentElement, contentElement, where);
		},

		/**
		 * Returns the displayed participant object.
		 * @function {public pygowave.model.Participant} participant
		 */
		participant: function () {
			return this._participant;
		},

		/**
		 * Overridden from {@link pygowave.view.Widget.dispose Widget.dispose}.

		 * Removes the widget from the DOM, sets the parentElement to null
		 * and removes event handlers.
		 * @function {public Widget} dispose
		 */
		dispose: function () {
			this.parent();
			this._participant.removeEvent('onlineStateChanged', this._onOnlineStateChanged);
			this._participant.removeEvent('dataChanged', this._onDataChanged);
			return this;
		},

		/**
		 * Overridden from {@link pygowave.view.Widget.inject Widget.inject}.

		 * Inject this widget somewhere else. Sets the parent element and adds
		 * event listeners to the (new) participant object.
		 *
		 * @function {public Widget} inject
		 * @param {Element} parentElement New parent element
		 * @param {optional String} where Where to inject the contentElement
		 *        relative to the parent element. Can be 'top', 'bottom',
		 *        'after', or 'before'.
		 * @param {optional pygowave.model.Participant} participant New
		 *        Participant object to bind this element to.
		 * @return Returns a reference to this widget.
		 */
		inject: function (parentElement, where, participant) {
			this.parent(parentElement, where);

			if ($defined(participant))
				this._participant = participant;
			else
				participant = this._participant;

			participant.addEvent('onlineStateChanged', this._onOnlineStateChanged);
			participant.addEvent('dataChanged', this._onDataChanged);

			var display_name = participant.displayName();
			if (display_name == "") display_name = "...";

			var tn = participant.thumbnailUrl();
			if (tn == "") tn = this._view.defaultThumbnailUrl();

			this._pImage.set({
				'src': tn,
				'alt': display_name,
				'title': display_name
			});

			if (this._pNick != null)
				this._pNick.set('text', display_name);
			this._onOnlineStateChanged(participant.isOnline());
			return this;
		},

		/**
		 * Callback for {@link pygowave.model.Participant.onOnlineStateChanged
		 * onOnlineStateChanged}. Shows/hides the online indicator.

		 * Note: The behaviour depends on your stylesheet. This method toggles
		 * between the 'offline' and 'online' classes of the element.
		 * @function {private} _onOnlineStateChanged
		 * @param {Boolean} online True if the participant is online
		 */
		_onOnlineStateChanged: function (online) {
			if (!$defined(this._oImage))
				this._oImage = new Element('div', {'class': 'indicator'}).inject(this.contentElement, 'bottom');

			this._oImage.addClass(online ? 'online' : 'offline').removeClass(online ? 'offline' : 'online');
		},

		/**
		 * Callback for {@link pygowave.model.Participant.onDataChanged
		 * onDataChanged}. Updates the representation of the participant.
		 * @function {private} _onDataChanged
		 */
		_onDataChanged: function () {
			var pImage = this._pImage;
			var display_name = this._participant.displayName();
			if (display_name == "") display_name = "...";
			pImage.set({
				"alt": display_name,
				"title": display_name
			});
			if (this._pNick != null)
				this._pNick.set('text', display_name);

			var tn = this._participant.thumbnailUrl();
			if (tn == "") tn = this._view.defaultThumbnailUrl();

			if (pImage.get("src") != tn) { // Exchange thumbnail
				new Fx.Tween(pImage, {duration:200}).start("opacity", 1, 0).chain(function () {
					pImage.set("src", "");
					pImage.set.delay(100, pImage, ["src", tn]);
					this.start.delay(100, this ,["opacity", 0, 1]);
				});
			}
		},

		/**
		 * Callback on click. Forwards event to listeners.
		 * @function _onClick
		 */
		_onClick: function () {
			this.fireEvent('click', this);
		}
	});

	/**
	 * Add participant window.
	 *
	 * @class {private} pygowave.view.AddParticipantWindow
	 * @extends MochaUI.Window
	 */
	var AddParticipantWindow = new Class({
		Extends: MochaUI.Window,
		/**
		 * Called on instantiation.
		 * @constructor {public} initialize
		 * @param {WaveView} view A reference back to the main view
		 * @param {String} waveletId ID of the Wavelet
		 */
		initialize: function (view, waveletId) {
			this._view = view;
			this._waveletId = waveletId;
			var buttons = {};
			buttons[gettext("Cancel")] = this._onCancel.bind(this);
			buttons[gettext("OK")] = this._onOK.bind(this);
			this._content = new Element('div');
			this._topBar = new Element('div', {'class': 'wavelet_add_participant_searchbar'}).inject(this._content);
			this._searchbox = new SearchWidget(this._topBar);
			this._results = new Element('div', {'class': 'wavelet_add_participant_results'}).inject(this._content);
			this.parent({
				title: gettext("Add participant"),
				content: this._content,
				width: 240,
				height: 410,
				headerStartColor: [95, 163, 237],
				headerStopColor: [85, 144, 210],
				bodyBgColor: [201, 226, 252],
				closeBgColor: [66, 114, 166],
				closeColor: [255, 255, 255],
				cornerRadius: 4,
				resizable: true,
				footerHeight: 34,
				rtl: this._view.options.rtl,
				buttons: buttons,
				padding: {top: 0, right: 0, bottom: 0, left: 0}
			});
			this.addEvent('closeComplete', this._onClose.bind(this));
			this._searchbox.setFocus.delay(350, this._searchbox);
			this._searchbox.addEvent('change', this._onQueryChange.bind(this));
			this._found = null;
			this._onSelect = this._onSelect.bind(this);
			this._selected = null;
		},

		/**
		 * Overrides drawWindow of mochaUI. Resizes result box to available
		 * space.
		 * @function {private} drawWindow
		 * @param {Element} windowEl Window element
		 * @param {Boolean} shadows False will draw a window without shadows
		 */
		drawWindow: function (windowEl, shadows) {
			this.parent(windowEl, shadows);
			this._results.setStyle("height", this.contentWrapperEl.getHeight()-this._topBar.getHeight());
		},

		/**
		 * Called if the users presses cancel.
		 * @function {private} _onCancel
		 */
		_onCancel: function () {
			MochaUI.closeWindow(this.windowEl);
		},

		/**
		 * Called if the user presses OK.
		 * @function {private} _onOK
		 */
		_onOK: function () {
			if (this._selected == null)
				this._view.showMessage(gettext("You must select a participant from your search results first."), gettext("Notice"));
			else {
				this._view.fireEvent('addParticipant', [this._waveletId, this._selected.participant().id()]);
				MochaUI.closeWindow(this.windowEl);
			}
		},

		/**
		 * Called if the window is closed. Disconnects events.
		 * @function {private} _onClose
		 */
		_onClose: function () {
			if (this._found != null) {
				for (var i = 0; i < this._found.length; i++)
					this._cleanupParticipantWidget(this._found[i]);
				this._found = null;
			}
		},

		/**
		 * Called if the user enters a query. Forwards event to view.
		 * @function {private} _onQueryChange
		 * @param {String} text Entered query text
		 */
		_onQueryChange: function (text) {
			this._view.fireEvent('searchForParticipant', [this._waveletId, text]);
		},

		/**
		 * Called if a participant was selected.
		 * @function {private} _onSelect
		 * @param {ParticipantWidget} widget The selected widget
		 */
		_onSelect: function (widget) {
			if (this._selected != null)
				this._selected.contentElement.removeClass("selected");
			widget.contentElement.addClass("selected");
			this._selected = widget;
		},

		/**
		 * Helper function to remove event handlers etc. from used
		 * ParticipantWidgets. Destroys the widget afterwards.
		 * @function {private} _cleanupParticipantWidget
		 * @param {ParticipantWidget} widget ParticipantWidget to be cleaned
		 */
		_cleanupParticipantWidget: function (widget) {
			widget.removeEvent('click', this._onSelect);
			if (this._selected == widget)
				this._selected = null;
			widget.dispose();
			widget.contentElement.destroy();
		},

		/**
		 * Update the search result on participant addition. Forwarded from the
		 * view.
		 *
		 * @function {public} updateSearchResults
		 * @param {pygowave.model.Participant[]} results Participant objects to
		 *        display as search result.
		 */
		updateSearchResults: function (results) {
			if (this._found == null) {
				this._found = new Array();
				this._results.set("html", "");
			}
			var i, j, deleted, id, newwgt;
			for (i = 0; i < this._found.length; i++) {
				if (i >= results.length) {
					this._cleanupParticipantWidget(this._found.pop(i));
					i--;
					continue;
				}

				id = this._found[i].participant().id();
				if (id != results[i].id()) {
					deleted = true;
					for (j = i+1; j < results.length; j++) {
						if (id == results[j].id())
							deleted = false;
					}
					if (deleted) {
						this._cleanupParticipantWidget(this._found.pop(i));
						i--;
					}
					else {
						newwgt = new ParticipantWidget(this._view, this._results, results[i], 'searchbox');
						newwgt.addEvent('click', this._onSelect);
						this._found.insert(i, newwgt);
					}
				}
			}
			for (; i < results.length; i++) {
				newwgt = new ParticipantWidget(this._view, this._results, results[i], 'searchbox');
				newwgt.addEvent('click', this._onSelect);
				this._found.append(newwgt);
			}
		},

		/**
		 * Remove search results and display the number of characters that must
		 * be entered for a valid search query. Forwarded from the view.
		 *
		 * @function {public} invalidSearch
		 * @param {Integer} chars Number of characters for a valid search
		 */
		invalidSearch: function (chars) {
			if (this._found != null) {
				for (var i = 0; i < this._found.length; i++)
					this._cleanupParticipantWidget(this._found[i])
			}
			this._found = null;
			this._results.set("html", "
" + gettext("Please enter at least %d letters.").sprintf(chars) + "
");
		}
	});

	/**
	 * Represents the "Add participant" button.
	 *
	 * @class {private} pygowave.view.AddParticipantWidget
	 * @extends pygowave.view.Widget
	 */
	var AddParticipantWidget = new Class({
		Extends: Widget,
		/**
		 * Called on instantiation.
		 * @constructor {public} initialize
		 * @param {WaveView} view A reference back to the main view
		 * @param {String} waveletId ID of the Wavelet
		 * @param {Element} parentElement Parent DOM element to insert the widget
		 */
		initialize: function (view, waveletId, parentElement) {
			this._view = view;
			this._waveletId = waveletId;
			var contentElement = new Element('div', {
				'class': 'wavelet_add_participant_widget',
				'title': gettext("Add participant")
			});
			this.parent(parentElement, contentElement);
			contentElement.addEvent('click', this._onClick.bind(this));
			this._addParticipantWindow = null;
		},

		/**
		 * Returns a reference to the AddParticipantWindow, if it is opened;
		 * null otherwise.
		 * @function {public AddParticipantWindow} addParticipantWindow
		 */
		addParticipantWindow: function () {
			return this._addParticipantWindow;
		},

		/**
		 * Callback on click.
		 * @function {private} _onClick
		 */
		_onClick: function () {
			if (this._addParticipantWindow == null) {
				this._addParticipantWindow = new AddParticipantWindow(this._view, this._waveletId);
				this._addParticipantWindow.addEvent('closeComplete', this._onClose.bind(this));
			}
			else
				MochaUI.focusWindow(this._addParticipantWindow.windowEl);
		},

		/**
		 * Callback if the search window is closed.
		 * @function {private} _onClose
		 */
		_onClose: function () {
			this._addParticipantWindow = null;
		}
	});

	pygowave.view.extend({
		ParticipantWidget: ParticipantWidget,
		AddParticipantWidget: AddParticipantWidget
	});
})();


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Like webview.xml, but with a wrap on the height instead -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:tools="http://schemas.android.com/tools"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <!-- OK -->
    <WebView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>

    <LinearLayout
            android:orientation="vertical"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent">

        <!-- Report error that parent height is wrap_content -->
        <WebView
                android:layout_width="match_parent"
                android:layout_height="match_parent"/>

        <!-- Suppressed -->
        <WebView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                tools:ignore="WebViewLayout"/>
    </LinearLayout>

</LinearLayout>


text:
using System;
using System.Linq;
using Bytes2you.DataAccess.Data;

namespace Bytes2you.DataAccess.EntityFramework.UnitTests.Testing.Mocks
{
    public class PersonDataEntityMock : IDataEntity<int>
    {
        public int Id { get; set; }
    }
}


text:
package golden

import (
	"fmt"
	"io/ioutil"
	"log"
	"strings"

	"github.com/pmezard/go-difflib/difflib"
)

// Compare compares the actual parameter to the contents of goldenFile and
// returns an empty string if they match. If they don't match, it returns a
// unified diff string documenting the differences.
//
// If the -update_golden flag is set, this function will overwrite the
// contents of goldenFile with the actual value. This is useful for updating
// the golden data automatically.
//
// goldenFile is a path relative to os.Getenv("GOROOT").
func Compare(actual string, goldenFile string) string {
	if shouldUpdateGolden() {
		fullPath, err := getFullPathForWrite(goldenFile)
		if err != nil {
			log.Fatalf("Error while getting path for writes: %v", err)
		}
		if err := ioutil.WriteFile(fullPath, []byte(actual), 0660); err != nil {
			log.Fatal(err)
		}
		return ""
	}

	fullPath, err := getFullPathForRead(goldenFile)
	if err != nil {
		log.Fatalf("Error while getting path for reads: %v", err)
	}

	expected, err := ioutil.ReadFile(fullPath)
	if err != nil {
		log.Fatalf("Error while reading golden file: %v", err)
	}
	if string(expected) == actual {
		return ""
	}
	udiff := difflib.UnifiedDiff{
		A:        difflib.SplitLines(string(expected)),
		FromFile: goldenFile,
		B:        difflib.SplitLines(actual),
		ToFile:   strings.TrimSuffix(goldenFile, ".golden") + ".actual",
		Context:  3,
	}
	diffstr, err := difflib.GetUnifiedDiffString(udiff)
	if err != nil {
		log.Fatalf("Error computing unified diff with golden file: %v", err)
	}
	return fmt.Sprintf("Actual data differs from golden data; run %q to update\n%v", formatUpdateCommand(), diffstr)
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Fieldiana, Bot. 13(4/2):771. 1958

#### Original name
null

### Remarks
null


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
New Zealand J. Bot. 25:166. 1987

#### Original name
Atropis pumila Kirk

### Remarks
null


text:
'use strict';

var Parser = require('./lib/parser');
var Translator = require('./lib/translator');
var stdinReader = require('./lib/stdin-reader');

function Compiler() {
    this.parser = new Parser();
    this.translator = new Translator();
}

Compiler.prototype.compile = function (source) {
    let ast = this.parser.parse(source);
    let js = this.translator.translate(ast);

    return js;
};

if (require.main === module) {
    stdinReader.pipe(function (source) {
        let compiler = new Compiler();
        let out = compiler.compile(source);
        console.log(out);
    });
}

module.exports = Compiler;


text:
package types

import (
	"errors"
	"fmt"

	"github.com/coreos/ignition/config/validate/report"
)

var (
	ErrCompressionInvalid = errors.New("invalid compression method")
)

func (f File) ValidateMode() report.Report {
	r := report.Report{}
	if err := validateMode(f.Mode); err != nil {
		r.Add(report.Entry{
			Message: err.Error(),
			Kind:    report.EntryError,
		})
	}
	return r
}

func (fc FileContents) ValidateCompression() report.Report {
	r := report.Report{}
	switch fc.Compression {
	case "", "gzip":
	default:
		r.Add(report.Entry{
			Message: ErrCompressionInvalid.Error(),
			Kind:    report.EntryError,
		})
	}
	return r
}

func (fc FileContents) ValidateSource() report.Report {
	r := report.Report{}
	err := validateURL(fc.Source)
	if err != nil {
		r.Add(report.Entry{
			Message: fmt.Sprintf("invalid url %q: %v", fc.Source, err),
			Kind:    report.EntryError,
		})
	}
	return r
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<servico xsi:schemaLocation="http://servicos.gov.br/v3/schema.../servico.xsd" xmlns="http://servicos.gov.br/v3/schema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <id>obter-autorizacao-para-estudos-geologicos-e-topograficos</id>
    <dbId>3153</dbId>
    <nome>Obter autorização para estudos geológicos e topográficos.</nome>
    <sigla></sigla>
    <descricao>Consiste em receber solicitação de empresas outorgadas para autorizar a realização de estudos geológicos e topográficos necessários à elaboração de projetos de redes de distribuição e de linhas de transmissão de energia elétrica.</descricao>
    <contato></contato>
    <gratuito>true</gratuito>
    <porcentagem-manual>false</porcentagem-manual>
    <servico-digital>false</servico-digital>
    <link-servico-digital></link-servico-digital>
    <solicitantes>
        <solicitante id="3739">
            <tipo>Empresas outorgadas de energia elétrica</tipo>
            <requisitos></requisitos>
        </solicitante>
    </solicitantes>
    <tempo-total-estimado>
        <entre min="31" max="60" unidade="dias-corridos"/>
        <descricao></descricao>
    </tempo-total-estimado>
    <validade-documento>
        <descricao></descricao>
    </validade-documento>
    <etapas>
        <etapa id="7155">
            <titulo>Solicitar autorização</titulo>
            <descricao>Encaminhar os documentos necessários para instrução do processo de autorização.</descricao>
            <documentos>
                <default>
                    <item id="10009">Documentação pertinente ao processo.</item>
                </default>
            </documentos>
            <custos>
                <default/>
            </custos>
            <canais-de-prestacao>
                <default>
                    <canal-de-prestacao id="7519" tipo="presencial">
                        <descricao>**Agência Nacional de Energia Elétrica** - SGAN 603 módulos I e J - Brasília/DF CEP: 70830-110</descricao>
                    </canal-de-prestacao>
                    <canal-de-prestacao id="7520" tipo="postal">
                        <descricao>**Agência Nacional de Energia Elétrica** - SGAN 603 módulos I e J - Brasília/DF CEP: 70830-110</descricao>
                    </canal-de-prestacao>
                </default>
            </canais-de-prestacao>
        </etapa>
    </etapas>
    <orgao id="http://estruturaorganizacional.dados.gov.br/id/unidade-organizacional/21089" dbId="909">
        <nomeOrgao>Agência Nacional de Energia Elétrica (ANEEL)</nomeOrgao>
    </orgao>
    <segmentos-da-sociedade>
        <item idSegmento="3" idServicoSegmento="7074">Empresas</item>
    </segmentos-da-sociedade>
    <areas-de-interesse>
        <item>Energia</item>
        <item>Energia elétrica</item>
    </areas-de-interesse>
    <palavras-chave>
        <item id="13162">aneel</item>
        <item id="13163">outorgadas</item>
        <item id="13164">estudo de terreno</item>
    </palavras-chave>
</servico>


text:
using System.Text;
using Xunit;

namespace System.Collections.Tests
{
    public class HashTable_ClearTests
    {
        [Fact]
        public void TestClearBasic()
        {
            StringBuilder sblMsg = new StringBuilder(99);
            Hashtable ht1 = null;
            string s1 = null;
            string s2 = null;

            int i = 0;
            ht1 = new Hashtable(); //default constructor
            ht1.Clear();

            Assert.Equal(0, ht1.Count);

            // add 100 key-val pairs
            ht1 = new Hashtable();

            for (i = 0; i < 100; i++)
            {
                sblMsg = new StringBuilder(99);
                sblMsg.Append("key_");
                sblMsg.Append(i);
                s1 = sblMsg.ToString();

                sblMsg = new StringBuilder(99);
                sblMsg.Append("val_");
                sblMsg.Append(i);
                s2 = sblMsg.ToString();

                ht1.Add(s1, s2);
            }

            Assert.Equal(100, ht1.Count);
            ht1.Clear();

            Assert.Equal(0, ht1.Count);

            //[]we will make a token call for some important methods to make sure that this is indeed clear
            s1 = "key_0";
            Assert.False(ht1.ContainsKey(s1));

            s1 = "val_0";
            Assert.False(ht1.ContainsValue(s1));

            //[]repeated clears of the HT. Nothing should happen

            for (i = 0; i < 100; i++)
            {
                ht1.Clear();

                Assert.Equal(0, ht1.Count);
            }
        }
    }
}


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('accounts', '0004_auto_20160719_0918'),
    ]

    operations = [
        migrations.AlterField(
            model_name='appuser',
            name='id',
            field=models.UUIDField(default=b'910073ec-08f4-453a-98b5-89be753dbca0', editable=False, primary_key=True, serialize=False),
        ),
    ]


text: Inline HTML (HyperText Markup Language) might be a problem!


text:
package grails.plugin.lightweightdeploy;

import com.google.common.io.ByteStreams;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class Utils {

    public static boolean deleteDir(final File dir) {
		if (!dir.exists()) {
			return true;
		}

		if (!dir.isDirectory()) {
			return false;
		}

		File[] files = dir.listFiles();
		if (files == null) {
			return false;
		}

		boolean result = true;
		for (File file : files) {
			if (file.isDirectory()) {
				if (!deleteDir(file)) {
					result = false;
				}
			}
			else {
				if (!file.delete()) {
					result = false;
				}
			}
		}

		if (!dir.delete()) {
			result = false;
		}

		return result;
	}

	public static void unzip(ZipEntry entry, ZipFile zipfile, File explodedDir) throws IOException {

		if (entry.isDirectory()) {
			new File(explodedDir, entry.getName()).mkdirs();
			return;
		}

		File outputFile = new File(explodedDir, entry.getName());
		if (!outputFile.getParentFile().exists()) {
			outputFile.getParentFile().mkdirs();
		}

		BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry));
		BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));

		try {
			ByteStreams.copy(inputStream, outputStream);
		}
		finally {
			outputStream.close();
			inputStream.close();
		}
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html
  PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<title>

          </title><meta name="author" content="Herbert Weir Smyth"/><meta name="generator" content="Text Encoding Initiative Consortium XSLT stylesheets"/><meta name="DC.Title" content="

          "/><meta name="DC.Type" content="Text"/><meta name="DC.Format" content="application/xhtml+xml"/><meta http-equiv="Content-Type" content="application/xhtml+xml; charset=utf-8"/><link href="tei.css" rel="stylesheet" type="text/css"/><link href="alph-tei.css" rel="stylesheet" type="text/css"/>

            AGREEMENT: THE CONCORDS

 Up: Part IV: Syntax Previous:
            EXPANSION OF THE SIMPLE SENTENCE
           Next:
            THE SUBJECT

925

There are three concords in simple sentences:

1. A finite verb agrees with its subject in number and person (949).

2. A word in apposition with another word agrees with it in case (976).

3. An adjective agrees with its substantive in gender, number, and case
                (1020).

(For the concord of relative pronouns, see 2501.)

926

Apparent violation of the concords is to be explained either by

a.
              Construction according to sense, where the
              agreement is with the real gender or number (e.g. 949 a, 950-953, 958, 996, 997, 1013,
              1044, 1050, 1055 a, 1058 b); or by

b.
              Attraction, when a word does not have its
              natural construction because of the influence of some other word or words in its
              clause (e.g. 1060 ff., 1239, 1978, 2465, 2502, 2522 ff.). This principle extends to
              moods and tenses (2183 ff.).

<address> Herbert Weir Smyth.

This work is licensed under a
            Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License.

</address>

The National Endowment for the Humanities provided support for entering this text.

XML for this text provided by
		Trustees of Tufts UniversityMedford, MAPerseus Project


text:
namespace debug {
class _CpuProfileGuard
{
	const std::string profile_name;
	static std::atomic<unsigned int> cnt;
public:
	_CpuProfileGuard(const std::string &name)
	:
		profile_name(std::string(name + "_" + std::to_string(cnt++)) )
	{
		ProfilerStart(profile_name.c_str());
	}

	~_CpuProfileGuard()
	{
		ProfilerFlush();
		ProfilerStop();
	}
};

}
#define CPU_PROFILE(X) debug::_CpuProfileGuard _cpu_profile_guard(X)
#else
#define CPU_PROFILE(X)
#endif

#endif


text:
package org.springframework.cloud.stream.binder.kafka.streams.function;

import java.time.Duration;
import java.util.Map;

import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.KTable;
import org.apache.kafka.streams.processor.Processor;
import org.apache.kafka.streams.processor.ProcessorContext;
import org.apache.kafka.streams.processor.ProcessorSupplier;
import org.apache.kafka.streams.state.KeyValueStore;
import org.apache.kafka.streams.state.StoreBuilder;
import org.apache.kafka.streams.state.Stores;
import org.apache.kafka.streams.state.WindowStore;
import org.junit.ClassRule;
import org.junit.Test;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.rule.EmbeddedKafkaRule;
import org.springframework.kafka.test.utils.KafkaTestUtils;

import static org.assertj.core.api.Assertions.assertThat;

public class KafkaStreamsFunctionStateStoreTests {

	@ClassRule
	public static EmbeddedKafkaRule embeddedKafkaRule = new EmbeddedKafkaRule(1, true,
			"counts");

	private static EmbeddedKafkaBroker embeddedKafka = embeddedKafkaRule.getEmbeddedKafka();

	@Test
	public void testKafkaStreamsFuncionWithMultipleStateStores() throws Exception {
		SpringApplication app = new SpringApplication(StateStoreTestApplication.class);
		app.setWebApplicationType(WebApplicationType.NONE);

		try (ConfigurableApplicationContext context = app.run("--server.port=0",
				"--spring.jmx.enabled=false",
				"--spring.cloud.stream.function.definition=biConsumerBean;hello",
				"--spring.cloud.stream.bindings.biConsumerBean-in-0.destination=words",
				"--spring.cloud.stream.bindings.hello-in-0.destination=words",
				"--spring.cloud.stream.kafka.streams.binder.functions.changed.applicationId=testKafkaStreamsFuncionWithMultipleStateStores-123",
				"--spring.cloud.stream.kafka.streams.binder.functions.hello.applicationId=testKafkaStreamsFuncionWithMultipleStateStores-456",
				"--spring.cloud.stream.kafka.streams.binder.configuration.commit.interval.ms=1000",
				"--spring.cloud.stream.kafka.streams.binder.configuration.default.key.serde" +
						"=org.apache.kafka.common.serialization.Serdes$StringSerde",
				"--spring.cloud.stream.kafka.streams.binder.configuration.default.value.serde" +
						"=org.apache.kafka.common.serialization.Serdes$StringSerde",
				"--spring.cloud.stream.kafka.streams.binder.brokers=" + embeddedKafka.getBrokersAsString())) {
			receiveAndValidate(context);
		}
	}

	private void receiveAndValidate(ConfigurableApplicationContext context) throws Exception {
		Map<String, Object> senderProps = KafkaTestUtils.producerProps(embeddedKafka);
		DefaultKafkaProducerFactory<Integer, String> pf = new DefaultKafkaProducerFactory<>(senderProps);
		try {
			KafkaTemplate<Integer, String> template = new KafkaTemplate<>(pf, true);
			template.setDefaultTopic("words");
			template.sendDefault(1, "foobar");
			Thread.sleep(2000L);
			StateStoreTestApplication processorApplication = context
					.getBean(StateStoreTestApplication.class);

			KeyValueStore<Long, Long> state1 = processorApplication.state1;
			assertThat(processorApplication.processed1).isTrue();
			assertThat(state1 != null).isTrue();
			assertThat(state1.name()).isEqualTo("my-store");
			WindowStore<Long, Long> state2 = processorApplication.state2;
			assertThat(state2 != null).isTrue();
			assertThat(state2.name()).isEqualTo("other-store");
			assertThat(state2.persistent()).isTrue();

			KeyValueStore<Long, Long> state3 = processorApplication.state1;
			assertThat(processorApplication.processed2).isTrue();
			assertThat(state3 != null).isTrue();
			assertThat(state3.name()).isEqualTo("my-store");
			WindowStore<Long, Long> state4 = processorApplication.state2;
			assertThat(state4 != null).isTrue();
			assertThat(state4.name()).isEqualTo("other-store");
			assertThat(state4.persistent()).isTrue();
		}
		finally {
			pf.destroy();
		}
	}

	@EnableAutoConfiguration
	public static class StateStoreTestApplication {

		KeyValueStore<Long, Long> state1;
		WindowStore<Long, Long> state2;

		KeyValueStore<Long, Long> state3;
		WindowStore<Long, Long> state4;

		boolean processed1;
		boolean processed2;

		@Bean(name = "biConsumerBean")
		public java.util.function.BiConsumer<KStream<Object, String>, KStream<Object, String>> process() {
			return (input0, input1) ->
					input0.process((ProcessorSupplier<Object, String>) () -> new Processor<Object, String>() {
						@Override
						@SuppressWarnings("unchecked")
						public void init(ProcessorContext context) {
							state1 = (KeyValueStore<Long, Long>) context.getStateStore("my-store");
							state2 = (WindowStore<Long, Long>) context.getStateStore("other-store");
						}

						@Override
						public void process(Object key, String value) {
							processed1 = true;
						}

						@Override
						public void close() {

						}
					}, "my-store", "other-store");
		}

		@Bean
		public java.util.function.Consumer<KTable<Object, String>> hello() {
			return input -> {
				input.toStream().process(() -> new Processor<Object, String>() {
					@Override
					@SuppressWarnings("unchecked")
					public void init(ProcessorContext context) {
						state3 = (KeyValueStore<Long, Long>) context.getStateStore("my-store");
						state4 = (WindowStore<Long, Long>) context.getStateStore("other-store");
					}

					@Override
					public void process(Object key, String value) {
						processed2 = true;
					}

					@Override
					public void close() {

					}
				}, "my-store", "other-store");
			};
		}

		@Bean
		public StoreBuilder myStore() {
			return Stores.keyValueStoreBuilder(
					Stores.persistentKeyValueStore("my-store"), Serdes.Long(),
					Serdes.Long());
		}

		@Bean
		public StoreBuilder otherStore() {
			return Stores.windowStoreBuilder(
					Stores.persistentWindowStore("other-store",
							Duration.ofSeconds(3), Duration.ofSeconds(3),  false), Serdes.Long(),
					Serdes.Long());
		}
	}

}


text:
package io.gravitee.am.gateway.handler.oauth2.service.assertion;

import io.gravitee.am.model.oidc.Client;
import io.reactivex.Maybe;
import io.vertx.reactivex.ext.web.RoutingContext;

/**
 * Client assertion as described for oauth2 assertion framework
 * and openid client authentication specs
 *
 * @author Alexandre FARIA (contact at alexandrefaria.net)
 * @author GraviteeSource Team
 */
public interface ClientAssertionService {

    Maybe<Client> assertClient(String assertionType, String assertion, String basePath);
}


text:
package com.cxsj.runhdu.utils;

import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;

/**
 * 动画控制工具类
 */
public class AnimationUtil {
    private static final String TAG = AnimationUtil.class.getSimpleName();

    /**
     * 从控件所在位置移动到控件的底部
     *
     * @return
     */
    public static TranslateAnimation moveToViewBottom() {
        TranslateAnimation mHiddenAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                0.0f, Animation.RELATIVE_TO_SELF, 5.0f);
        mHiddenAction.setDuration(2500);
        return mHiddenAction;
    }

    /**
     * 从控件的底部移动到控件所在位置
     *
     * @return
     */
    public static TranslateAnimation moveToViewLocation() {
        TranslateAnimation mHiddenAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                5.0f, Animation.RELATIVE_TO_SELF, 0.0f);
        mHiddenAction.setDuration(1500);
        return mHiddenAction;
    }

}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>uk.co.cynicode</groupId>
    <artifactId>CyniChatB</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>CyniChat</name>
    <description>The alpha stages of the CyniChat Minecraft plugin. As designed by Cynical.</description>

    <repositories>
        <!--<repository>
            <id>bungee-repo</id>
            <url>http://ci.md-5.net/</url>
        </repository>-->
        <repository>
            <!-- Bukkit can be found at the following repository -->
            <id>bukkit-repo</id>
            <url>http://repo.bukkit.org/content/groups/public/</url>
        </repository>
        <repository>
            <id>dev-repo</id>
            <url>http://dev.escapecraft.com/maven</url>
        </repository>
        <repository>
            <id>vault-repo</id>
            <url>http://ci.herocraftonline.com/plugin/repository/everything</url>
        </repository>
    </repositories>

    <pluginRepositories>
    </pluginRepositories>

    <dependencies>
        <dependency>
            <groupId>org.bukkit</groupId>
            <artifactId>craftbukkit</artifactId>
            <version>1.7.2-R0.1-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>net.milkbowl.vault</groupId>
            <artifactId>Vault</artifactId>
            <version>1.2.25-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.bukkit</groupId>
            <artifactId>bukkit</artifactId>
            <!-- Bukkit API Version, change if nessesary -->
            <version>1.7.2-R0.1-SNAPSHOT</version>
        </dependency>
    </dependencies>

    <distributionManagement>
        <repository>
            <id>dev-repo</id>
            <name>dev.escapecraft.com Releases</name>
            <url>scp://dev.escapecraft.com/var/www/maven</url>
        </repository>
        <!--<repository>
          <id>lin-repo</id>
          <name>linux machine Releases</name>
          <url>scp://192.168.137.234/home/m477h3w1012/.m2/repositories/</url>
        </repository>
        <snapshotRepository>
          <id>lin-repo-snap</id>
          <name>linux machine Snapshots</name>
          <url>scp://192.168.137.234/home/m477h3w1012/.m2/repositories/</url>
        </snapshotRepository>-->
        <snapshotRepository>
            <id>dev-repo-snap</id>
            <name>dev.escapecraft.com Snapshots</name>
            <url>scp://dev.escapecraft.com/var/www/maven</url>
        </snapshotRepository>
    </distributionManagement>

    <build>
        <extensions>
            <extension>
                <groupId>org.apache.maven.wagon</groupId>
                <artifactId>wagon-ssh</artifactId>
                <version>2.2</version>
            </extension>
        </extensions>
    </build>
</project>


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<help>
    <name>DigPopGUI</name>
    <introduction>Test something will need to go here</introduction>
    <screen>
        <name>Step 1 - Maps</name>
        <description>This page allows users to enter all the applicable files.</description>
        <instruction>
            <instructionName>Land Use or Household Density Map</instructionName>
            <helpText>The Land Use Map is a raster map that provides land use data (city, farm, forest, etc.) for the regions in the region map.  Digital Populations uses this to guide the random placement of households within a region toward cells where people actually tend to live.  Must use exact same coordinate system as the Region Map. The Population Density map is the result of applying the per-class density table to the land-use map.  If this file is specified in the fitting criteria file, Digital Populations will skip the above processes altogether and use it directly.  In this case, the land-use map need not appear in the relationship file at all.</helpText>
        </instruction>
        <instruction>
            <instructionName>Region Map</instructionName>
            <helpText>This raster map provides the location of the regions or tracts that Digital Populations will populate.  This is the finest resolution that DigPop can work with -- a region is selected based on statistical analysis, but the location of a household within a region is random.  Coordinate system must be planar (i.e. UTM).  DigPop does not understand coordinate systems, so distance calculations will not be correct in other systems.</helpText>
        </instruction>
        <instruction>
            <instructionName>Census Enumerations</instructionName>
            <helpText>Regional summaries of socioeconomically attributes of interests</helpText>
        </instruction>
        <instruction>
            <instructionName>Constraint Map</instructionName>
            <helpText>Optional: Specifies areas where households with a specific value are NOT allowed, by explicitly disallowing the placement of certain households into certain map cells.  To use the constraint map, users must specify the map, then specify the household trait and value from the microdata that links to corresponding raster value on the map.  For example, houses with grid electricity would only be placed where a raster map of grid power has a specific raster value corresponding to access to electricity. For example, urban/rural regions, regions with/without electric </helpText>
        </instruction>
        <instruction>
            <instructionName>Population Micro-Data</instructionName>
            <helpText>This optional table provides residents for the households.  Each record identifies which household it resides within, and the residents are cloned when their household is cloned.  This allows Digital Populations to compute statistics from personal data.</helpText>
        </instruction>
        <instruction>
            <instructionName>Household Micro-Data</instructionName>
            <helpText>Digital Populations can't create households and people from scratch.  Instead, it clones the households from this table in a way that matches the region statistics.  The more households provided here, the fewer times any particular archtype needs to be cloned, and the better the result.  The relationship file describes how data in this table relates to the statistics in the region table.</helpText>
        </instruction>
    </screen>
    <screen>
        <name>Step 2 - Goal Relationship File</name>
        <description>This page allows users to setup the Goal Relationship File, which specifies a complete set of files for one region and how they relate to each other.</description>
        <instruction>
            <instructionName>Census File</instructionName>
            <helpText>This is the name of the census enumeration file from Step 1, with the regional summaries of socioeconomically attributes of interests.</helpText>
        </instruction>
        <instruction>
            <instructionName>Population File</instructionName>
            <helpText>The file provided in Step 1, the population table where each row describes one individual.</helpText>
        </instruction>
        <instruction>
            <instructionName>Household File</instructionName>
            <helpText>The file provided in Step 1, the household table provides a Unique ID Field that identifies the specific house each person lives in.  Records without household ID values will be ignored.</helpText>
        </instruction>
        <instruction>
            <instructionName>Household Density Map File</instructionName>
            <helpText>Population Density Map file is being used. In order to use a Land Use Population Map, please return to Step 1 and remove the selected Population Density Map. Only displayed if the user selected to use a Population Density Map in Step 1.</helpText>
        </instruction>
        <instruction>
            <instructionName>Land Use Map Information</instructionName>
            <helpText>Land Use Population Map file is being used. In order to use a Population Density Map, please return to Step 1 and remove the selected Land Use Population Map. Only displayed if the user selected to use a Land Use Population Map in Step 1.</helpText>
        </instruction>
        <instruction>
            <instructionName>Vacant Classes</instructionName>
            <helpText>The land use map guides where households can and cannot be placed. Vacant classes are the numerical areas that households cannot be placed (e.g. Open Water).</helpText>
        </instruction>
        <instruction>
            <instructionName>Vacant Class Description</instructionName>
            <helpText>The text description of the selected classes that households cannot be placed (e.g. Open Water).</helpText>
        </instruction>
        <instruction>
            <instructionName>Combination Classes</instructionName>
            <helpText>Combination classes group classes from the land use map that are expected to have similar population density to simplify analysis. All classes in the land use map must be covered either by a vacancy class or combination element. </helpText>
        </instruction>
        <instruction>
            <instructionName>Classes</instructionName>
            <helpText>The class or list of classes to be grouped together into a single population type. This is either a single item (e.g. 23), a range (e.g. 90-99), or a comma delimited combination of both (e.g. 4,41-60,71-80)</helpText>
        </instruction>
        <instruction>
            <instructionName>Target</instructionName>
            <helpText>The new class number for the combined class.</helpText>
        </instruction>
        <instruction>
            <instructionName>Description</instructionName>
            <helpText>The text description of the new combination class, to describe the population type (e.g. "Developed, Low Intensity")</helpText>
        </instruction>
    </screen>
    <screen>
        <name>Step 3 - Census and Survey Data</name>
        <description>This page allows users to configure the linkages between the census and survey data.</description>
        <instruction>
            <instructionName>Available Census Data</instructionName>
            <helpText>The columns from the census enumeration .csv file provided in Step 1. If a name has already been provided for the census data, it will be displayed as "[Census ID] - [Provided Name]".</helpText>
        </instruction>
        <instruction>
            <instructionName>Available Survey Data</instructionName>
            <helpText>The columns from the household or population micro-data .csv file provided in Step 1. Only one survey data field may be selected per Markov Chain</helpText>
        </instruction>
        <instruction>
            <instructionName>User Defined Description</instructionName>
            <helpText>Allows the user to edit the description for a census data trait ID. Will be pre-populated, but editable, if previous Markov Chains have been created.</helpText>
        </instruction>
        <instruction>
            <instructionName>Available Survey Data Column Values</instructionName>
            <helpText>The values to be selected for combination into a single user defined description. Each data column value can only be used one per Markov Chain. Once a value has been added to a group, it will be removed from the Available Survey Data Column value list. </helpText>
        </instruction>
        <instruction>
            <instructionName>User Defined Description</instructionName>
            <helpText>Allows the user to add or edit the description for a survey data column values. Will be pre-populated if previous Markov Chains have been created.</helpText>
        </instruction>
    </screen>
    <screen>
        <name>Step 4 - Markov Chain</name>
        <description>This page allows users to create a Markov Chain for creating multiple census enumeration files.</description>
        <instruction>
            <instructionName>Markov Chain Name</instructionName>
            <helpText>The user entered name of the current Markov Chain matrix.</helpText>
        </instruction>
        <instruction>
            <instructionName>Census Information</instructionName>
            <helpText>The user provided descriptions for census data traits selected in Step 3.</helpText>
        </instruction>
        <instruction>
            <instructionName>Survey Information</instructionName>
            <helpText>The user provided descriptions for survey data traits selected in Step 3.</helpText>
        </instruction>
        <instruction>
            <instructionName>Amount Left</instructionName>
            <helpText>Calculated as the available minimum or maximum values for the associated survey/census information based on values entered in the associated row/column. System calculated; Min Range (constrained by the max values) is from 0 to "[Proportion] – [Sum(minimum values provided)]", Max Range (constrained by the min values) is from 0 to "[Proportion] – [Sum(maximum values provided)]".</helpText>
        </instruction>
    </screen>
    <screen>
        <name>Step 5 - Generate Fitting Criteria File</name>
        <description>This page allows users to setup the Trait Weights for the Fitting Criteria File, which is the master control file.  The fitting criteria file specifies dependent file and criteria for one run.  The Markov Table generates new census region trait columns for the census enumeration .csv based on the microdata values (e.g. enumerations for 'flushed to pipe sewer').</description>
        <instruction>
            <instructionName>ID</instructionName>
            <helpText>The system generated trait ID for the new census region trait columns from the Markov Chain matrix. Populates the ID XML value.</helpText>
        </instruction>
        <instruction>
            <instructionName>Census Region Trait</instructionName>
            <helpText>The new census region trait column names for the census enumeration based on the microdata values used in the Markov Chain matrix (e.g. enumerations for 'flushed to pipe sewer'). Populates the Region Trait XML value.</helpText>
        </instruction>
        <instruction>
            <instructionName>Census Region Total</instructionName>
            <helpText>The Census Region Totals are generated by the system based on the Markov Chain name as "[Markov Chain Name]_MC_Total". Proportion values are calculated by the software from the raw inputs for the Markov Chain matrix.  The 'Census Region Totals' calculated to determine the proportion values are added as a new field to the census enumeration .csv file. Populates the Region Total XML value.</helpText>
        </instruction>
        <instruction>
            <instructionName>Survey Trait Table</instructionName>
            <helpText>The name of the table type that is being used, either HOUSEHOLDS or POPULATION. Populates the Pums Trait Table XML value.</helpText>
        </instruction>
        <instruction>
            <instructionName>Survey Trait Select</instructionName>
            <helpText>Populated from the selected Survey Trait column values in Step 3. Populates the Pums Trait Select XML value. </helpText>
        </instruction>
        <instruction>
            <instructionName>Survey Trait Field</instructionName>
            <helpText>Populated from the selected Survey Data traits in step 3. Populates the Pums Trait Field XML value.</helpText>
        </instruction>
        <instruction>
            <instructionName>Survey Total Table</instructionName>
            <helpText>The name of the table type that is being used, either HOUSEHOLDS or POPULATION. Populates the Pums Total Table XML value.</helpText>
        </instruction>
        <instruction>
            <instructionName>Survey Total Field</instructionName>
            <helpText>System generated, will always be 1. Populates the Pums Total Field XML value.</helpText>
        </instruction>
        <instruction>
            <instructionName>User Entered Description</instructionName>
            <helpText>The user defined description for the survey column data, provided in Step 3. To edit, please go back to Step 3. Populates the User Entered Description XML value.</helpText>
        </instruction>
        <instruction>
            <instructionName>Total Weight</instructionName>
            <helpText>The only editable field on the page. Values must be between 0 and 1. Populates the Trait Weight XML value.</helpText>
        </instruction>
    </screen>
    <screen>
        <name>Step 6 - Generate Trait Clusters</name>
        <description>This page allows users to Generate Trait Clusters. Cluster elements instruct the DigiPop tool's Phase 4 to introduce a degree of clustering by moving "similar" households closer to each other when computing precise easting/northing locations for each household.  The referenced trait provides a definition of "similar", and the remaining attributes specify an amount of clustering.</description>
        <instruction>
            <instructionName>Trait ID</instructionName>
            <helpText>The identifier for one of the Trait elements specified in Step 5. The value of the selected trait IDs with weights that can be clustered.</helpText>
        </instruction>
        <instruction>
            <instructionName>Reduction</instructionName>
            <helpText>Percentage reduction in "inertia," which is a measure of the randomness of an arrangement of households.  A reduction of inertia is an increase of clustering, and is achieved by moving households closer together. Goal will be this much lower than the "inertia" values calculated when phase 4 begins. The integer value of the reduction must be greater than 1.</helpText>
        </instruction>
        <instruction>
            <instructionName>Distance</instructionName>
            <helpText>The Maximum size of clusters to build. Only houses within this radius will be considered for clustering.  This values is in the same units as the input maps. Value must be greater than 0.</helpText>
        </instruction>
    </screen>
    <screen>
        <name>Step 7 - Generate Run Parameter File</name>
        <description>This page allows users to setup the Run Parameter File.  This is a record of all options and settings active the last time Digital Populations was run.  It provide access to "hidden" and internal options, and makes it easy to exactly reproduce an older run.</description>
        <instruction>
            <instructionName>Name of Run</instructionName>
            <helpText>Used as a comment to organize the runs.</helpText>
        </instruction>
        <instruction>
            <instructionName>Fitting File path</instructionName>
            <helpText>Path and name of main fitting criteria file, relative to current directory</helpText>
        </instruction>
        <instruction>
            <instructionName>Log the results of phase 1?</instructionName>
            <helpText>If true, the log file will receive the results of phase 1.</helpText>
        </instruction>
        <instruction>
            <instructionName>Log the quality evaluation reports between phases?</instructionName>
            <helpText>If true, the log file will receive detailed reports from  the quality evaluation objects between phases.</helpText>
        </instruction>
        <instruction>
            <instructionName>Does each Household record contain a full copy of the archetype record?</instructionName>
            <helpText>If false, each record in households.csv will contain coordinates plus a reference to one of the archetypes.  If true, each record will also contain a full copy of the archetype record.</helpText>
        </instruction>
        <instruction>
            <instructionName>Does each Population record contain a full copy of the archetype record?</instructionName>
            <helpText>If false, each record in populations.csv will contain coordinates plus a reference to one of the archetypes.  If true, each record will also contain a full copy of the archetype record.</helpText>
        </instruction>
        <instruction>
            <instructionName>First Realization Index</instructionName>
            <helpText>(argument -f) Index of first realization to generate. All realizations between 'first' and 'final' will be run and saved. In other words, ConflatePumsQueryWithTracts will run repeatedly, once for each realization, but with different random seeds each time.</helpText>
        </instruction>
        <instruction>
            <instructionName>Final Realization Index</instructionName>
            <helpText>(argument -l)  Index of final realization to generate.</helpText>
        </instruction>
        <instruction>
            <instructionName>Random Number seed</instructionName>
            <helpText>(argument -r) Random seed that will guide the creation of all random numbers. Running the program twice with the same seed will result in the exact same output. (When the program is NOT running parallel threads and the computer uses the same number of compute cycles.)  Delete from file to make program generate a new random seed.</helpText>
        </instruction>
        <instruction>
            <instructionName>Use only the first census tract?</instructionName>
            <helpText>This is a speed hack that causes algorithm to use only the first census tract.  The program runs very quickly, but the output is useless: used for debugging criteria_file. (Seeing what error messages pop up.)</helpText>
        </instruction>
        <instruction>
            <instructionName>Output Directory</instructionName>
            <helpText>(argument -o) Target directory for all output files, relative to current directory.</helpText>
        </instruction>
        <instruction>
            <instructionName>Number of parallel threads</instructionName>
            <helpText>The number of threads being run at the same time in parallel. Recommended to be in the range from 1 to a maximum of the number of processors on the users' computer.</helpText>
        </instruction>
        <instruction>
            <instructionName>Phase 1 Time limit</instructionName>
            <helpText>Limit phase 1 to this many minutes.</helpText>
        </instruction>
        <instruction>
            <instructionName>Phase 2 - Random Placement Percentage</instructionName>
            <helpText>(argument -s) This fraction of households will be placed randomly, regardless of whether the placement is a good fit or not.  Setting to zero will greatly improve the output of phase 2, but also take a great deal longer.</helpText>
        </instruction>
        <instruction>
            <instructionName>Phase 2 - Skip Tracts Probability</instructionName>
            <helpText>(argument -s) This fraction of tracts will be ignored when phase 2 tries to place a household into a tract.  If phase2_random_tract_prob is triggered, then this setting is not used.  Setting this to zero will make phase 2 properly evaluate all tracts, but take a great deal longer.</helpText>
        </instruction>
        <instruction>
            <instructionName>Phase 2 - Skipped Tracts Probability Delta</instructionName>
            <helpText>If phase2_tract_skip_prob_init caused phase 2 to skip every tract, then the fraction will be reduced by this amount, and placement will be tried again.</helpText>
        </instruction>
        <instruction>
            <instructionName>Phase 3 and 4 Intermediate Save Interval</instructionName>
            <helpText>Phase 3 will write a set of files every this many minutes.  Phase 4 also uses this timer for the same purpose.</helpText>
        </instruction>
        <instruction>
            <instructionName>Skip Phase 3?</instructionName>
            <helpText>If true, phase 3 will be skipped altogether.</helpText>
        </instruction>
        <instruction>
            <instructionName>Phase 3 Time limit</instructionName>
            <helpText>Limit phase 3 to this many minutes.</helpText>
        </instruction>
        <instruction>
            <instructionName>Phase 4 - Number of Lags</instructionName>
            <helpText>As a rule of thumb, 5 - 10 lags is appropriate.</helpText>
        </instruction>
        <instruction>
            <instructionName>Phase 4 - Save both ends?</instructionName>
            <helpText>Determine if the user should save at both ends of Phase 4.</helpText>
        </instruction>
        <instruction>
            <instructionName>Skip Phase 4?</instructionName>
            <helpText>If true, phase 4 will be skipped altogether.</helpText>
        </instruction>
        <instruction>
            <instructionName>Phase 4 Time Limit</instructionName>
            <helpText>Limit phase 4 to this many minutes.</helpText>
        </instruction>
    </screen>
</help>


text:
<?php
/*
UserCake Version: 2.0.2
http://usercake.com
*/

require_once("models/config.php");
if (!securePage($_SERVER['PHP_SELF'])){die();}
$permissionId = $_GET['id'];

//Check if selected permission level exists
if(!permissionIdExists($permissionId)){
	header("Location: admin_permissions.php"); die();
}

$permissionDetails = fetchPermissionDetails($permissionId); //Fetch information specific to permission level

//Forms posted
if(!empty($_POST)){

	//Delete selected permission level
	if(!empty($_POST['delete'])){
		$deletions = $_POST['delete'];
		if ($deletion_count = deletePermission($deletions)){
		$successes[] = lang("PERMISSION_DELETIONS_SUCCESSFUL", array($deletion_count));
		}
		else {
			$errors[] = lang("SQL_ERROR");
		}
	}
	else
	{
		//Update permission level name
		if($permissionDetails['name'] != $_POST['name']) {
			$permission = trim($_POST['name']);

			//Validate new name
			if (permissionNameExists($permission)){
				$errors[] = lang("ACCOUNT_PERMISSIONNAME_IN_USE", array($permission));
			}
			elseif (minMaxRange(1, 50, $permission)){
				$errors[] = lang("ACCOUNT_PERMISSION_CHAR_LIMIT", array(1, 50));
			}
			else {
				if (updatePermissionName($permissionId, $permission)){
					$successes[] = lang("PERMISSION_NAME_UPDATE", array($permission));
				}
				else {
					$errors[] = lang("SQL_ERROR");
				}
			}
		}

		//Remove access to pages
		if(!empty($_POST['removePermission'])){
			$remove = $_POST['removePermission'];
			if ($deletion_count = removePermission($permissionId, $remove)) {
				$successes[] = lang("PERMISSION_REMOVE_USERS", array($deletion_count));
			}
			else {
				$errors[] = lang("SQL_ERROR");
			}
		}

		//Add access to pages
		if(!empty($_POST['addPermission'])){
			$add = $_POST['addPermission'];
			if ($addition_count = addPermission($permissionId, $add)) {
				$successes[] = lang("PERMISSION_ADD_USERS", array($addition_count));
			}
			else {
				$errors[] = lang("SQL_ERROR");
			}
		}

		//Remove access to pages
		if(!empty($_POST['removePage'])){
			$remove = $_POST['removePage'];
			if ($deletion_count = removePage($remove, $permissionId)) {
				$successes[] = lang("PERMISSION_REMOVE_PAGES", array($deletion_count));
			}
			else {
				$errors[] = lang("SQL_ERROR");
			}
		}

		//Add access to pages
		if(!empty($_POST['addPage'])){
			$add = $_POST['addPage'];
			if ($addition_count = addPage($add, $permissionId)) {
				$successes[] = lang("PERMISSION_ADD_PAGES", array($addition_count));
			}
			else {
				$errors[] = lang("SQL_ERROR");
			}
		}
			$permissionDetails = fetchPermissionDetails($permissionId);
	}
}

$pagePermissions = fetchPermissionPages($permissionId); //Retrieve list of accessible pages
$permissionUsers = fetchPermissionUsers($permissionId); //Retrieve list of users with membership
$userData = fetchAllUsers(); //Fetch all users
$pageData = fetchAllPages(); //Fetch all pages

require_once("models/header.php");
echo "

Aved Battery Failure Analysis Database

Admin Permissions

";

include("left-nav.php");

echo "

";

echo resultBlock($errors,$successes);

echo "
<form name='adminPermission' action='".$_SERVER['PHP_SELF']."?id=".$permissionId."' method='post'>

Permission Information

ID:
".$permissionDetails['id']."

Name:
<input type='text' name='name' value='".$permissionDetails['name']."' />

Delete:
<input type='checkbox' name='delete[".$permissionDetails['id']."]' id='delete[".$permissionDetails['id']."]' value='".$permissionDetails['id']."'>

Permission Membership

Remove Members:";

//List users with permission level
foreach ($userData as $v1) {
	if(isset($permissionUsers[$v1['id']])){
		echo "
<input type='checkbox' name='removePermission[".$v1['id']."]' id='removePermission[".$v1['id']."]' value='".$v1['id']."'> ".$v1['display_name'];
	}
}

echo"

Add Members:";

//List users without permission level
foreach ($userData as $v1) {
	if(!isset($permissionUsers[$v1['id']])){
		echo "
<input type='checkbox' name='addPermission[".$v1['id']."]' id='addPermission[".$v1['id']."]' value='".$v1['id']."'> ".$v1['display_name'];
	}
}

echo"

Permission Access

Public Access:";

//List public pages
foreach ($pageData as $v1) {
	if($v1['private'] != 1){
		echo "
".$v1['page'];
	}
}

echo"

Remove Access:";

//List pages accessible to permission level
foreach ($pageData as $v1) {
	if(isset($pagePermissions[$v1['id']]) AND $v1['private'] == 1){
		echo "
<input type='checkbox' name='removePage[".$v1['id']."]' id='removePage[".$v1['id']."]' value='".$v1['id']."'> ".$v1['page'];
	}
}

echo"

Add Access:";

//List pages inaccessible to permission level
foreach ($pageData as $v1) {
	if(!isset($pagePermissions[$v1['id']]) AND $v1['private'] == 1){
		echo "
<input type='checkbox' name='addPage[".$v1['id']."]' id='addPage[".$v1['id']."]' value='".$v1['id']."'> ".$v1['page'];
	}
}

echo"

<input type='submit' value='Update' class='submit' />

</form>

";

?>


text:
class HospitalsController < ApplicationController

	before_filter :may_create_hospitals_required,
		:only => [:new,:create]
	before_filter :may_read_hospitals_required,
		:only => [:show,:index]
	before_filter :may_update_hospitals_required,
		:only => [:edit,:update]
	before_filter :may_destroy_hospitals_required,
		:only => :destroy

	before_filter :valid_id_required,
		:only => [:show,:edit,:update,:destroy]

	def index
		@hospitals = Hospital.includes(:organization)
	end

	def new
		@hospital = Hospital.new(params[:hospital])	#	don't "REQUIRE" here
	end

	def create
		@hospital = Hospital.new(hospital_params)
		@hospital.save!
		flash[:notice] = 'Success!'
		redirect_to @hospital
	rescue ActiveRecord::RecordNotSaved, ActiveRecord::RecordInvalid
		flash.now[:error] = "There was a problem creating the hospital"
		render :action => "new"
	end

	def update
		@hospital.update_attributes!(hospital_params)
		flash[:notice] = 'Success!'
		redirect_to hospitals_path
	rescue ActiveRecord::RecordNotSaved, ActiveRecord::RecordInvalid
		flash.now[:error] = "There was a problem updating the hospital"
		render :action => "edit"
	end

	def destroy
		@hospital.destroy
		redirect_to hospitals_path
	end

protected

	def valid_id_required
		if( !params[:id].blank? && Hospital.exists?(params[:id]) )
			@hospital = Hospital.find(params[:id])
		else
			access_denied("Valid id required!", hospitals_path)
		end
	end

	def hospital_params
		params.require(:hospital).permit(:is_active,:has_irb_waiver,:organization_id)
	end

end


text:
"""
This module, excel_file_generator.py, will be used to generate Excel files.
"""

# This is for creating a new file, I just want to modify an existing template excel file though.
'''
import xlsxwriter

workbook = xlsxwriter.Workbook('hello_world.xlsx')

hours_worksheet = workbook.add_worksheet('Hours')
hours_worksheet.write('A1', 'HELLO HELLO?!')

workbook.close()
'''

import openpyxl

# Check if Ubuntu is running this script.
from sys import platform as _platform
# Needed to get today's date and do other time logic.
import time
import datetime

if _platform == "linux" or _platform == "linux2":
	import sys
	# sys.path.remove('/home/dev_usr/urbtek/nexus_django')
	sys.path.append('/home/dev_usr/urbtek')
	file_path = '/dev/urbtek/universal_code/excel/base_excel_hours_logging.xlsx'
else:
	file_path = '/Users/utarsuno/git_repos/urbtek/urbtek/universal_code/excel/base_excel_hours_logging.xlsx'

# The date format.
FORMAT = '%m/%d/%Y'

today = datetime.datetime.today()
day_of_week = today.weekday()
to_end_of_week = datetime.timedelta(days = 6 - day_of_week)
end_of_week = today + to_end_of_week
to_beginning_of_week = datetime.timedelta(days = day_of_week)
beginning_of_week = today - to_beginning_of_week

monday     = beginning_of_week
tuesday    = beginning_of_week + datetime.timedelta(days=1)
wednesday  = beginning_of_week + datetime.timedelta(days=2)
thursday   = beginning_of_week + datetime.timedelta(days=3)
friday     = beginning_of_week + datetime.timedelta(days=4)
saturday   = beginning_of_week + datetime.timedelta(days=5)
sunday     = beginning_of_week + datetime.timedelta(days=6)
submit_day = beginning_of_week + datetime.timedelta(days=7)

# The cells to work with.
date_submitted  = 'K1'
monday_cells    = ['E4', 'E199', 'E207', monday.strftime(FORMAT)]
tuesday_cells   = ['F4', 'F199', 'F207', tuesday.strftime(FORMAT)]
wednesday_cells = ['G4', 'G199', 'G207', wednesday.strftime(FORMAT)]
thursday_cells  = ['H4', 'H199', 'H207', thursday.strftime(FORMAT)]
friday_cells    = ['I4', 'I199', 'I207', friday.strftime(FORMAT)]
saturday_cells  = ['J4', 'J199', 'J207', saturday.strftime(FORMAT)]
sunday_cells    = ['K4', 'K199', 'K207', sunday.strftime(FORMAT)]
hour_cells      = [monday_cells, tuesday_cells, wednesday_cells, thursday_cells, friday_cells, saturday_cells, sunday_cells]

# Load the Excel file here.
xfile = openpyxl.load_workbook('/Users/utarsuno/git_repos/urbtek/urbtek/universal_code/excel/base_excel_hours_logging.xlsx')

sheet = xfile.get_sheet_by_name('Sheet1')

sheet[date_submitted] = submit_day.strftime(FORMAT)
for c in hour_cells:
	sheet[c[0]] = c[3]
	sheet[c[1]] = c[1]
	sheet[c[2]] = c[2]

xfile.save('HELLO_TEST_YES.xlsx')

'''
today    = datetime.datetime.today()
tomorrow = today + datetime.timedelta(days=1)
print(today.strftime('%m/%d/%Y'))
print(tomorrow.strftime('%m/%d/%Y'))
'''


text:
var assert = require("assert"),
	fs = require("fs"),
	Imgflipper = require("../index.js");

var IMGFLIP_USERNAME = process.env.IMGFLIP_USERNAME,
	IMGFLIP_PASSWORD = process.env.IMGFLIP_PASSWORD;

describe("Imgflipper", function () {
	describe("#generateMeme()", function () {
		it("should return a valid url to a meme image", function (done) {
			var imgflipper = new Imgflipper(IMGFLIP_USERNAME, IMGFLIP_PASSWORD),
				cb = function (err, url) {
					assert.ifError(err);
					assert.ok(url);

					done();
				};

			imgflipper.generateMeme(61546, "Brace yourselves", "the sprint planning session is coming", cb);
		});
	});

	describe("#generateMemeImage()", function () {
		it("should write the generated meme image to the stream", function (done) {
			var imgflipper = new Imgflipper(IMGFLIP_USERNAME, IMGFLIP_PASSWORD),
				filename = "meme.jpg",
				fstream = fs.createWriteStream(filename),
				cb = function (err) {
					assert.ifError(err);

					var stats = fs.statSync(filename);
					assert.ok(stats);
					assert(stats.size > 0);

					fs.unlinkSync(filename);
					done();
				};

			imgflipper.generateMemeImage(61546, "Brace yourselves", "the sprint planning session is coming", fstream, cb);
		});
	});
});


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
BenchMarkClient
</TITLE>

<META NAME="date" CONTENT="2010-02-11">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.ublog.benchmark

Interface BenchMarkClient

All Known Implementing Classes:
ComplexBenchMarkClient, TwitterOperationsTest

public interface BenchMarkClient

Method Summary

 int
getClientID()

 int
getPeerID()

 boolean
hasMoreOperations()

 Pair<CollectionOperation,java.lang.Double>
nextOperation()

 void
setPeerID(int peerID)

Method Detail

hasMoreOperations

boolean hasMoreOperations()

nextOperation

Pair<CollectionOperation,java.lang.Double> nextOperation()

getClientID

int getClientID()

setPeerID

void setPeerID(int peerID)

getPeerID

int getPeerID()

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD